The JUCE cross-platform C++ framework, with DISTRHO/KXStudio specific changes
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

265406 lines
7.9MB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library - "Jules' Utility Class Extensions"
  4. Copyright 2004-9 by Raw Material Software Ltd.
  5. ------------------------------------------------------------------------------
  6. JUCE can be redistributed and/or modified under the terms of the GNU General
  7. Public License (Version 2), as published by the Free Software Foundation.
  8. A copy of the license is included in the JUCE distribution, or can be found
  9. online at www.gnu.org/licenses.
  10. JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
  11. WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
  12. A PARTICULAR PURPOSE. See the GNU General Public License for more details.
  13. ------------------------------------------------------------------------------
  14. To release a closed-source product which uses JUCE, commercial licenses are
  15. available: visit www.rawmaterialsoftware.com/juce for more information.
  16. ==============================================================================
  17. */
  18. /*
  19. This monolithic file contains the entire Juce source tree!
  20. To build an app which uses Juce, all you need to do is to add this
  21. file to your project, and include juce.h in your own cpp files.
  22. */
  23. #ifdef __JUCE_JUCEHEADER__
  24. /* When you add the amalgamated cpp file to your project, you mustn't include it in
  25. a file where you've already included juce.h - just put it inside a file on its own,
  26. possibly with your config flags preceding it, but don't include anything else. */
  27. #error
  28. #endif
  29. /********* Start of inlined file: juce_Config.h *********/
  30. #ifndef __JUCE_CONFIG_JUCEHEADER__
  31. #define __JUCE_CONFIG_JUCEHEADER__
  32. /*
  33. This file contains macros that enable/disable various JUCE features.
  34. */
  35. /** The name of the namespace that all Juce classes and functions will be
  36. put inside. If this is not defined, no namespace will be used.
  37. */
  38. #ifndef JUCE_NAMESPACE
  39. #define JUCE_NAMESPACE juce
  40. #endif
  41. /** Normally, JUCE_DEBUG is set to 1 or 0 based on compiler and project settings,
  42. but if you define this value, you can override this can force it to be true or
  43. false.
  44. */
  45. #ifndef JUCE_FORCE_DEBUG
  46. //#define JUCE_FORCE_DEBUG 1
  47. #endif
  48. /** If this flag is enabled, the the jassert and jassertfalse macros will
  49. always use Logger::writeToLog() to write a message when an assertion happens.
  50. Enabling it will also leave this turned on in release builds. When it's disabled,
  51. however, the jassert and jassertfalse macros will not be compiled in a
  52. release build.
  53. @see jassert, jassertfalse, Logger
  54. */
  55. #ifndef JUCE_LOG_ASSERTIONS
  56. // #define JUCE_LOG_ASSERTIONS 1
  57. #endif
  58. /** Comment out this macro if you haven't got the Steinberg ASIO SDK, without
  59. which the ASIOAudioIODevice class can't be built. See the comments in the
  60. ASIOAudioIODevice class's header file for more info about this.
  61. (This only affects a Win32 build)
  62. */
  63. #ifndef JUCE_ASIO
  64. #define JUCE_ASIO 1
  65. #endif
  66. /** Comment out this macro to disable the Windows WASAPI audio device type.
  67. */
  68. #ifndef JUCE_WASAPI
  69. // #define JUCE_WASAPI 1
  70. #endif
  71. /** Comment out this macro to disable the Windows WASAPI audio device type.
  72. */
  73. #ifndef JUCE_DIRECTSOUND
  74. #define JUCE_DIRECTSOUND 1
  75. #endif
  76. /** Comment out this macro to disable building of ALSA device support on Linux.
  77. */
  78. #ifndef JUCE_ALSA
  79. #define JUCE_ALSA 1
  80. #endif
  81. /** Comment out this macro if you don't want to enable QuickTime or if you don't
  82. have the SDK installed.
  83. If this flag is not enabled, the QuickTimeMovieComponent and QuickTimeAudioFormat
  84. classes will be unavailable.
  85. On Windows, if you enable this, you'll need to have the QuickTime SDK
  86. installed, and its header files will need to be on your include path.
  87. */
  88. #if ! (defined (JUCE_QUICKTIME) || defined (LINUX) || (defined (_WIN32) && ! defined (_MSC_VER)))
  89. #define JUCE_QUICKTIME 1
  90. #endif
  91. /** Comment out this macro if you don't want to enable OpenGL or if you don't
  92. have the appropriate headers and libraries available. If it's not enabled, the
  93. OpenGLComponent class will be unavailable.
  94. */
  95. #ifndef JUCE_OPENGL
  96. #define JUCE_OPENGL 1
  97. #endif
  98. /** These flags enable the Ogg-Vorbis and Flac audio formats.
  99. If you're not going to need either of these formats, turn off the flags to
  100. avoid bloating your codebase with them.
  101. */
  102. #ifndef JUCE_USE_FLAC
  103. #define JUCE_USE_FLAC 1
  104. #endif
  105. #ifndef JUCE_USE_OGGVORBIS
  106. #define JUCE_USE_OGGVORBIS 1
  107. #endif
  108. /** This flag lets you enable support for CD-burning. You might want to disable
  109. it to build without the MS SDK under windows.
  110. */
  111. #if (! defined (JUCE_USE_CDBURNER)) && ! (defined (_WIN32) && ! defined (_MSC_VER))
  112. #define JUCE_USE_CDBURNER 1
  113. #endif
  114. /** Enabling this provides support for cameras, using the CameraDevice class
  115. */
  116. #if JUCE_QUICKTIME && ! defined (JUCE_USE_CAMERA)
  117. // #define JUCE_USE_CAMERA 1
  118. #endif
  119. /** Enabling this macro means that all regions that get repainted will have a coloured
  120. line drawn around them.
  121. This is handy if you're trying to optimise drawing, because it lets you easily see
  122. when anything is being repainted unnecessarily.
  123. */
  124. #ifndef JUCE_ENABLE_REPAINT_DEBUGGING
  125. // #define JUCE_ENABLE_REPAINT_DEBUGGING 1
  126. #endif
  127. /** Enable this under Linux to use Xinerama for multi-monitor support.
  128. */
  129. #ifndef JUCE_USE_XINERAMA
  130. #define JUCE_USE_XINERAMA 1
  131. #endif
  132. /** Enable this under Linux to use XShm for faster shared-memory rendering.
  133. */
  134. #ifndef JUCE_USE_XSHM
  135. #define JUCE_USE_XSHM 1
  136. #endif
  137. /** Enabling this builds support for VST audio plugins.
  138. @see VSTPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_AU
  139. */
  140. #ifndef JUCE_PLUGINHOST_VST
  141. // #define JUCE_PLUGINHOST_VST 1
  142. #endif
  143. /** Enabling this builds support for AudioUnit audio plugins.
  144. @see AudioUnitPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_VST
  145. */
  146. #ifndef JUCE_PLUGINHOST_AU
  147. // #define JUCE_PLUGINHOST_AU 1
  148. #endif
  149. /** Enabling this will avoid including any UI code in the build. This is handy for
  150. writing command-line utilities, e.g. on linux boxes which don't have some
  151. of the UI libraries installed.
  152. */
  153. #ifndef JUCE_ONLY_BUILD_CORE_LIBRARY
  154. //#define JUCE_ONLY_BUILD_CORE_LIBRARY 1
  155. #endif
  156. /** This lets you disable building of the WebBrowserComponent, if it's not required.
  157. */
  158. #ifndef JUCE_WEB_BROWSER
  159. #define JUCE_WEB_BROWSER 1
  160. #endif
  161. /** Setting this allows the build to use old Carbon libraries that will be
  162. deprecated in newer versions of OSX. This is handy for some backwards-compatibility
  163. reasons.
  164. */
  165. #ifndef JUCE_SUPPORT_CARBON
  166. #define JUCE_SUPPORT_CARBON 1
  167. #endif
  168. /* These flags let you avoid the direct inclusion of some 3rd-party libs in the
  169. codebase - you might need to use this if you're linking to some of these libraries
  170. yourself.
  171. */
  172. #ifndef JUCE_INCLUDE_ZLIB_CODE
  173. #define JUCE_INCLUDE_ZLIB_CODE 1
  174. #endif
  175. #ifndef JUCE_INCLUDE_FLAC_CODE
  176. #define JUCE_INCLUDE_FLAC_CODE 1
  177. #endif
  178. #ifndef JUCE_INCLUDE_OGGVORBIS_CODE
  179. #define JUCE_INCLUDE_OGGVORBIS_CODE 1
  180. #endif
  181. #ifndef JUCE_INCLUDE_PNGLIB_CODE
  182. #define JUCE_INCLUDE_PNGLIB_CODE 1
  183. #endif
  184. #ifndef JUCE_INCLUDE_JPEGLIB_CODE
  185. #define JUCE_INCLUDE_JPEGLIB_CODE 1
  186. #endif
  187. /** Enable this to add extra memory-leak info to the new and delete operators.
  188. (Currently, this only affects Windows builds in debug mode).
  189. */
  190. #ifndef JUCE_CHECK_MEMORY_LEAKS
  191. #define JUCE_CHECK_MEMORY_LEAKS 1
  192. #endif
  193. /** Enable this to turn on juce's internal catching of exceptions.
  194. Turning it off will avoid any exception catching. With it on, all exceptions
  195. are passed to the JUCEApplication::unhandledException() callback for logging.
  196. */
  197. #ifndef JUCE_CATCH_UNHANDLED_EXCEPTIONS
  198. #define JUCE_CATCH_UNHANDLED_EXCEPTIONS 1
  199. #endif
  200. /** If this macro is set, the Juce String class will use unicode as its
  201. internal representation. If it isn't set, it'll use ANSI.
  202. */
  203. #ifndef JUCE_STRINGS_ARE_UNICODE
  204. #define JUCE_STRINGS_ARE_UNICODE 1
  205. #endif
  206. #endif
  207. /********* End of inlined file: juce_Config.h *********/
  208. // FORCE_AMALGAMATOR_INCLUDE
  209. //==============================================================================
  210. #ifdef _WIN32
  211. /********* Start of inlined file: juce_win32_NativeIncludes.h *********/
  212. #ifndef __JUCE_WIN32_NATIVEINCLUDES_JUCEHEADER__
  213. #define __JUCE_WIN32_NATIVEINCLUDES_JUCEHEADER__
  214. #ifndef STRICT
  215. #define STRICT 1
  216. #endif
  217. #undef WIN32_LEAN_AND_MEAN
  218. #define WIN32_LEAN_AND_MEAN 1
  219. #ifdef _MSC_VER
  220. #pragma warning (push)
  221. #pragma warning (disable : 4100 4201 4514 4312 4995)
  222. #endif
  223. #define _WIN32_WINNT 0x0500
  224. #define _UNICODE 1
  225. #define UNICODE 1
  226. #ifndef _WIN32_IE
  227. #define _WIN32_IE 0x0400
  228. #endif
  229. #include <windows.h>
  230. #include <windowsx.h>
  231. #include <commdlg.h>
  232. #include <shellapi.h>
  233. #include <mmsystem.h>
  234. #include <vfw.h>
  235. #include <tchar.h>
  236. #include <stddef.h>
  237. #include <ctime>
  238. #include <wininet.h>
  239. #include <nb30.h>
  240. #include <iphlpapi.h>
  241. #include <mapi.h>
  242. #include <float.h>
  243. #include <crtdbg.h>
  244. #include <process.h>
  245. #include <comutil.h>
  246. #include <Exdisp.h>
  247. #include <exdispid.h>
  248. #include <shlobj.h>
  249. #if JUCE_OPENGL
  250. #include <gl/gl.h>
  251. #endif
  252. #undef PACKED
  253. #if JUCE_ASIO
  254. /*
  255. This is very frustrating - we only need to use a handful of definitions from
  256. a couple of the header files in Steinberg's ASIO SDK, and it'd be easy to copy
  257. about 30 lines of code into this cpp file to create a fully stand-alone ASIO
  258. implementation...
  259. ..unfortunately that would break Steinberg's license agreement for use of
  260. their SDK, so I'm not allowed to do this.
  261. This means that anyone who wants to use JUCE's ASIO abilities will have to:
  262. 1) Agree to Steinberg's licensing terms and download the ASIO SDK
  263. (see www.steinberg.net/Steinberg/Developers.asp).
  264. 2) Rebuild the whole of JUCE, setting the global definition JUCE_ASIO (you
  265. can un-comment the "#define JUCE_ASIO" line in juce_Config.h
  266. if you prefer). Make sure that your header search path will find the
  267. iasiodrv.h file that comes with the SDK. (Only about 2-3 of the SDK header
  268. files are actually needed - so to simplify things, you could just copy
  269. these into your JUCE directory).
  270. If you're compiling and you get an error here because you don't have the
  271. ASIO SDK installed, you can disable ASIO support by commenting-out the
  272. "#define JUCE_ASIO" line in juce_Config.h, and rebuild your Juce library.
  273. */
  274. #include "iasiodrv.h"
  275. #endif
  276. #if JUCE_USE_CDBURNER
  277. /* You'll need the Platform SDK for these headers - if you don't have it and don't
  278. need to use CD-burning, then you might just want to disable the JUCE_USE_CDBURNER
  279. flag in juce_Config.h to avoid these includes.
  280. */
  281. #include <imapi.h>
  282. #include <imapierror.h>
  283. #endif
  284. #if JUCE_USE_CAMERA
  285. /* If you're using the camera classes, you'll need access to a few DirectShow headers.
  286. Both of these files are provided in the normal Windows SDK, but some Microsoft plonker
  287. didn't realise that qedit.h doesn't actually compile without the rest of the DirectShow SDK!
  288. Microsoft's suggested fix for this is to hack their qedit.h file! See:
  289. http://social.msdn.microsoft.com/Forums/en-US/windowssdk/thread/ed097d2c-3d68-4f48-8448-277eaaf68252
  290. .. which is a pathetic bodge, but a lot less hassle than installing the full DShow SDK.
  291. */
  292. #include <dshow.h>
  293. #include <qedit.h>
  294. #endif
  295. #if JUCE_WASAPI
  296. #include <MMReg.h>
  297. #include <mmdeviceapi.h>
  298. #include <Audioclient.h>
  299. #include <functiondiscoverykeys.h>
  300. #endif
  301. #if JUCE_QUICKTIME
  302. /* If you've got an include error here, you probably need to install the QuickTime SDK and
  303. add its header directory to your include path.
  304. Alternatively, if you don't need any QuickTime services, just turn off the JUCE_QUICKTIME
  305. flag in juce_Config.h
  306. */
  307. #include <Movies.h>
  308. #include <QTML.h>
  309. #include <QuickTimeComponents.h>
  310. #include <MediaHandlers.h>
  311. #include <ImageCodec.h>
  312. /* If you've got QuickTime 7 installed, then these COM objects should be found in
  313. the "\Program Files\Quicktime" directory. You'll need to add this directory to
  314. your include search path to make these import statements work.
  315. */
  316. #import <QTOLibrary.dll>
  317. #import <QTOControl.dll>
  318. #endif
  319. #ifdef _MSC_VER
  320. #pragma warning (pop)
  321. #endif
  322. /** A simple COM smart pointer.
  323. Avoids having to include ATL just to get one of these.
  324. */
  325. template <class T>
  326. class ComSmartPtr
  327. {
  328. public:
  329. ComSmartPtr() throw() : p (0) {}
  330. ComSmartPtr (T* const p_) : p (p_) { if (p_ != 0) p_->AddRef(); }
  331. ComSmartPtr (const ComSmartPtr<T>& p_) : p (p_.p) { if (p != 0) p->AddRef(); }
  332. ~ComSmartPtr() { if (p != 0) p->Release(); }
  333. operator T*() const throw() { return p; }
  334. T& operator*() const throw() { return *p; }
  335. T** operator&() throw() { return &p; }
  336. T* operator->() const throw() { return p; }
  337. T* operator= (T* const newP)
  338. {
  339. if (newP != 0)
  340. newP->AddRef();
  341. if (p != 0)
  342. p->Release();
  343. p = newP;
  344. return newP;
  345. }
  346. T* operator= (const ComSmartPtr<T>& newP) { return operator= (newP.p); }
  347. HRESULT CoCreateInstance (REFCLSID rclsid, DWORD dwClsContext)
  348. {
  349. #ifndef __MINGW32__
  350. operator= (0);
  351. return ::CoCreateInstance (rclsid, 0, dwClsContext, __uuidof(T), (void**) &p);
  352. #else
  353. return S_FALSE;
  354. #endif
  355. }
  356. T* p;
  357. };
  358. #endif // __JUCE_WIN32_NATIVEINCLUDES_JUCEHEADER__
  359. /********* End of inlined file: juce_win32_NativeIncludes.h *********/
  360. #elif defined (LINUX)
  361. /********* Start of inlined file: juce_linux_NativeIncludes.h *********/
  362. #ifndef __JUCE_LINUX_NATIVEINCLUDES_JUCEHEADER__
  363. #define __JUCE_LINUX_NATIVEINCLUDES_JUCEHEADER__
  364. /*
  365. This file wraps together all the linux-specific headers, so
  366. that we can include them all just once, and compile all our
  367. platform-specific stuff in one big lump, keeping it out of the
  368. way of the rest of the codebase.
  369. */
  370. #include <sched.h>
  371. #include <pthread.h>
  372. #include <sys/time.h>
  373. #include <errno.h>
  374. #include <sys/stat.h>
  375. #include <sys/dir.h>
  376. #include <sys/ptrace.h>
  377. #include <sys/vfs.h>
  378. #include <sys/wait.h>
  379. #include <fnmatch.h>
  380. #include <utime.h>
  381. #include <pwd.h>
  382. #include <fcntl.h>
  383. #include <dlfcn.h>
  384. #include <netdb.h>
  385. #include <arpa/inet.h>
  386. #include <netinet/in.h>
  387. #include <sys/types.h>
  388. #include <sys/ioctl.h>
  389. #include <sys/socket.h>
  390. #include <linux/if.h>
  391. #include <sys/sysinfo.h>
  392. #include <sys/file.h>
  393. #include <signal.h>
  394. /* Got a build error here? You'll need to install the freetype library...
  395. The name of the package to install is "libfreetype6-dev".
  396. */
  397. #include <ft2build.h>
  398. #include FT_FREETYPE_H
  399. #include <X11/Xlib.h>
  400. #include <X11/Xatom.h>
  401. #include <X11/Xresource.h>
  402. #include <X11/Xutil.h>
  403. #include <X11/Xmd.h>
  404. #include <X11/keysym.h>
  405. #include <X11/cursorfont.h>
  406. #if JUCE_USE_XINERAMA
  407. /* If you're trying to use Xinerama, you'll need to install the "libxinerama-dev" package.. */
  408. #include <X11/extensions/Xinerama.h>
  409. #endif
  410. #if JUCE_USE_XSHM
  411. #include <X11/extensions/XShm.h>
  412. #include <sys/shm.h>
  413. #include <sys/ipc.h>
  414. #endif
  415. #if JUCE_OPENGL
  416. /* Got an include error here?
  417. If you want to install OpenGL support, the packages to get are "mesa-common-dev"
  418. and "freeglut3-dev".
  419. Alternatively, you can turn off the JUCE_OPENGL flag in juce_Config.h if you
  420. want to disable it.
  421. */
  422. #include <GL/glx.h>
  423. #endif
  424. #undef KeyPress
  425. #if JUCE_ALSA
  426. /* Got an include error here? If so, you've either not got ALSA installed, or you've
  427. not got your paths set up correctly to find its header files.
  428. The package you need to install to get ASLA support is "libasound2-dev".
  429. If you don't have the ALSA library and don't want to build Juce with audio support,
  430. just disable the JUCE_ALSA flag in juce_Config.h
  431. */
  432. #include <alsa/asoundlib.h>
  433. #endif
  434. #undef SIZEOF
  435. #endif // __JUCE_LINUX_NATIVEINCLUDES_JUCEHEADER__
  436. /********* End of inlined file: juce_linux_NativeIncludes.h *********/
  437. #else
  438. /********* Start of inlined file: juce_mac_NativeIncludes.h *********/
  439. #ifndef __JUCE_MAC_NATIVEINCLUDES_JUCEHEADER__
  440. #define __JUCE_MAC_NATIVEINCLUDES_JUCEHEADER__
  441. /*
  442. This file wraps together all the mac-specific code, so that
  443. we can include all the native headers just once, and compile all our
  444. platform-specific stuff in one big lump, keeping it out of the way of
  445. the rest of the codebase.
  446. */
  447. #import <Cocoa/Cocoa.h>
  448. #import <CoreAudio/HostTime.h>
  449. #import <CoreAudio/AudioHardware.h>
  450. #import <CoreMIDI/MIDIServices.h>
  451. #import <QTKit/QTKit.h>
  452. #import <WebKit/WebKit.h>
  453. #import <DiscRecording/DiscRecording.h>
  454. #import <IOKit/IOKitLib.h>
  455. #import <IOKit/IOCFPlugIn.h>
  456. #import <IOKit/hid/IOHIDLib.h>
  457. #import <IOKit/hid/IOHIDKeys.h>
  458. #import <IOKit/network/IOEthernetInterface.h>
  459. #import <IOKit/network/IONetworkInterface.h>
  460. #import <IOKit/network/IOEthernetController.h>
  461. #import <IOKit/pwr_mgt/IOPMLib.h>
  462. #include <sys/sysctl.h>
  463. #include <sys/stat.h>
  464. #include <sys/dir.h>
  465. #include <sys/param.h>
  466. #include <sys/mount.h>
  467. #include <fnmatch.h>
  468. #include <utime.h>
  469. #include <dlfcn.h>
  470. #if MACOS_10_4_OR_EARLIER
  471. #include <GLUT/glut.h>
  472. typedef int NSInteger;
  473. typedef unsigned int NSUInteger;
  474. #endif
  475. #endif // __JUCE_MAC_NATIVEINCLUDES_JUCEHEADER__
  476. /********* End of inlined file: juce_mac_NativeIncludes.h *********/
  477. #endif
  478. //==============================================================================
  479. #define DONT_SET_USING_JUCE_NAMESPACE 1
  480. #include "juce_amalgamated.h"
  481. #define NO_DUMMY_DECL
  482. #if (defined(_MSC_VER) && (_MSC_VER <= 1200))
  483. #pragma warning (disable: 4309 4305)
  484. #endif
  485. #if JUCE_MAC && JUCE_32BIT && JUCE_SUPPORT_CARBON && ! JUCE_ONLY_BUILD_CORE_LIBRARY
  486. BEGIN_JUCE_NAMESPACE
  487. /********* Start of inlined file: juce_mac_CarbonViewWrapperComponent.h *********/
  488. #ifndef __JUCE_MAC_CARBONVIEWWRAPPERCOMPONENT_JUCEHEADER__
  489. #define __JUCE_MAC_CARBONVIEWWRAPPERCOMPONENT_JUCEHEADER__
  490. /**
  491. Creates a floating carbon window that can be used to hold a carbon UI.
  492. This is a handy class that's designed to be inlined where needed, e.g.
  493. in the audio plugin hosting code.
  494. */
  495. class CarbonViewWrapperComponent : public Component,
  496. public ComponentMovementWatcher,
  497. public Timer
  498. {
  499. public:
  500. CarbonViewWrapperComponent()
  501. : ComponentMovementWatcher (this),
  502. wrapperWindow (0),
  503. embeddedView (0),
  504. recursiveResize (false)
  505. {
  506. }
  507. virtual ~CarbonViewWrapperComponent()
  508. {
  509. jassert (embeddedView == 0); // must call deleteWindow() in the subclass's destructor!
  510. }
  511. virtual HIViewRef attachView (WindowRef windowRef, HIViewRef rootView) = 0;
  512. virtual void removeView (HIViewRef embeddedView) = 0;
  513. virtual void mouseDown (int x, int y) {}
  514. virtual void paint() {}
  515. virtual bool getEmbeddedViewSize (int& w, int& h)
  516. {
  517. if (embeddedView == 0)
  518. return false;
  519. HIRect bounds;
  520. HIViewGetBounds (embeddedView, &bounds);
  521. w = jmax (1, roundFloatToInt (bounds.size.width));
  522. h = jmax (1, roundFloatToInt (bounds.size.height));
  523. return true;
  524. }
  525. void createWindow()
  526. {
  527. if (wrapperWindow == 0)
  528. {
  529. Rect r;
  530. r.left = getScreenX();
  531. r.top = getScreenY();
  532. r.right = r.left + getWidth();
  533. r.bottom = r.top + getHeight();
  534. CreateNewWindow (kDocumentWindowClass,
  535. (WindowAttributes) (kWindowStandardHandlerAttribute | kWindowCompositingAttribute
  536. | kWindowNoShadowAttribute | kWindowNoTitleBarAttribute),
  537. &r, &wrapperWindow);
  538. jassert (wrapperWindow != 0);
  539. if (wrapperWindow == 0)
  540. return;
  541. NSWindow* carbonWindow = [[NSWindow alloc] initWithWindowRef: wrapperWindow];
  542. NSWindow* ownerWindow = [((NSView*) getWindowHandle()) window];
  543. [ownerWindow addChildWindow: carbonWindow
  544. ordered: NSWindowAbove];
  545. embeddedView = attachView (wrapperWindow, HIViewGetRoot (wrapperWindow));
  546. EventTypeSpec windowEventTypes[] = { { kEventClassWindow, kEventWindowGetClickActivation },
  547. { kEventClassWindow, kEventWindowHandleDeactivate } };
  548. EventHandlerUPP upp = NewEventHandlerUPP (carbonEventCallback);
  549. InstallWindowEventHandler (wrapperWindow, upp,
  550. sizeof (windowEventTypes) / sizeof (EventTypeSpec),
  551. windowEventTypes, this, &eventHandlerRef);
  552. setOurSizeToEmbeddedViewSize();
  553. setEmbeddedWindowToOurSize();
  554. creationTime = Time::getCurrentTime();
  555. }
  556. }
  557. void deleteWindow()
  558. {
  559. removeView (embeddedView);
  560. embeddedView = 0;
  561. if (wrapperWindow != 0)
  562. {
  563. RemoveEventHandler (eventHandlerRef);
  564. DisposeWindow (wrapperWindow);
  565. wrapperWindow = 0;
  566. }
  567. }
  568. void setOurSizeToEmbeddedViewSize()
  569. {
  570. int w, h;
  571. if (getEmbeddedViewSize (w, h))
  572. {
  573. if (w != getWidth() || h != getHeight())
  574. {
  575. startTimer (50);
  576. setSize (w, h);
  577. if (getParentComponent() != 0)
  578. getParentComponent()->setSize (w, h);
  579. }
  580. else
  581. {
  582. startTimer (jlimit (50, 500, getTimerInterval() + 20));
  583. }
  584. }
  585. else
  586. {
  587. stopTimer();
  588. }
  589. }
  590. void setEmbeddedWindowToOurSize()
  591. {
  592. if (! recursiveResize)
  593. {
  594. recursiveResize = true;
  595. if (embeddedView != 0)
  596. {
  597. HIRect r;
  598. r.origin.x = 0;
  599. r.origin.y = 0;
  600. r.size.width = (float) getWidth();
  601. r.size.height = (float) getHeight();
  602. HIViewSetFrame (embeddedView, &r);
  603. }
  604. if (wrapperWindow != 0)
  605. {
  606. Rect wr;
  607. wr.left = getScreenX();
  608. wr.top = getScreenY();
  609. wr.right = wr.left + getWidth();
  610. wr.bottom = wr.top + getHeight();
  611. SetWindowBounds (wrapperWindow, kWindowContentRgn, &wr);
  612. ShowWindow (wrapperWindow);
  613. }
  614. recursiveResize = false;
  615. }
  616. }
  617. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  618. {
  619. setEmbeddedWindowToOurSize();
  620. }
  621. void componentPeerChanged()
  622. {
  623. deleteWindow();
  624. createWindow();
  625. }
  626. void componentVisibilityChanged (Component&)
  627. {
  628. if (isShowing())
  629. createWindow();
  630. else
  631. deleteWindow();
  632. setEmbeddedWindowToOurSize();
  633. }
  634. void timerCallback()
  635. {
  636. setOurSizeToEmbeddedViewSize();
  637. // To avoid strange overpainting problems when the UI is first opened, we'll
  638. // repaint it a few times during the first second that it's on-screen..
  639. if ((Time::getCurrentTime() - creationTime).inMilliseconds() < 1000)
  640. HIViewSetNeedsDisplay (embeddedView, true);
  641. }
  642. OSStatus carbonEventHandler (EventHandlerCallRef nextHandlerRef,
  643. EventRef event)
  644. {
  645. switch (GetEventKind (event))
  646. {
  647. case kEventWindowHandleDeactivate:
  648. ActivateWindow (wrapperWindow, TRUE);
  649. break;
  650. case kEventWindowGetClickActivation:
  651. {
  652. getTopLevelComponent()->toFront (false);
  653. ClickActivationResult howToHandleClick = kActivateAndHandleClick;
  654. SetEventParameter (event, kEventParamClickActivation, typeClickActivationResult,
  655. sizeof (ClickActivationResult), &howToHandleClick);
  656. HIViewSetNeedsDisplay (embeddedView, true);
  657. }
  658. break;
  659. }
  660. return noErr;
  661. }
  662. static pascal OSStatus carbonEventCallback (EventHandlerCallRef nextHandlerRef,
  663. EventRef event, void* userData)
  664. {
  665. return ((CarbonViewWrapperComponent*) userData)->carbonEventHandler (nextHandlerRef, event);
  666. }
  667. protected:
  668. WindowRef wrapperWindow;
  669. HIViewRef embeddedView;
  670. bool recursiveResize;
  671. Time creationTime;
  672. EventHandlerRef eventHandlerRef;
  673. };
  674. #endif // __JUCE_MAC_CARBONVIEWWRAPPERCOMPONENT_JUCEHEADER__
  675. /********* End of inlined file: juce_mac_CarbonViewWrapperComponent.h *********/
  676. END_JUCE_NAMESPACE
  677. #endif
  678. #define JUCE_AMALGAMATED_TEMPLATE 1
  679. //==============================================================================
  680. /********* Start of inlined file: juce_FileLogger.cpp *********/
  681. BEGIN_JUCE_NAMESPACE
  682. FileLogger::FileLogger (const File& logFile_,
  683. const String& welcomeMessage,
  684. const int maxInitialFileSizeBytes)
  685. : logFile (logFile_)
  686. {
  687. if (maxInitialFileSizeBytes >= 0)
  688. trimFileSize (maxInitialFileSizeBytes);
  689. if (! logFile_.exists())
  690. {
  691. // do this so that the parent directories get created..
  692. logFile_.create();
  693. }
  694. logStream = logFile_.createOutputStream (256);
  695. jassert (logStream != 0);
  696. String welcome;
  697. welcome << "\r\n**********************************************************\r\n"
  698. << welcomeMessage
  699. << "\r\nLog started: " << Time::getCurrentTime().toString (true, true)
  700. << "\r\n";
  701. logMessage (welcome);
  702. }
  703. FileLogger::~FileLogger()
  704. {
  705. deleteAndZero (logStream);
  706. }
  707. void FileLogger::logMessage (const String& message)
  708. {
  709. if (logStream != 0)
  710. {
  711. Logger::outputDebugString (message);
  712. const ScopedLock sl (logLock);
  713. (*logStream) << message << T("\r\n");
  714. logStream->flush();
  715. }
  716. }
  717. void FileLogger::trimFileSize (int maxFileSizeBytes) const
  718. {
  719. if (maxFileSizeBytes <= 0)
  720. {
  721. logFile.deleteFile();
  722. }
  723. else
  724. {
  725. const int64 fileSize = logFile.getSize();
  726. if (fileSize > maxFileSizeBytes)
  727. {
  728. FileInputStream* const in = logFile.createInputStream();
  729. jassert (in != 0);
  730. if (in != 0)
  731. {
  732. in->setPosition (fileSize - maxFileSizeBytes);
  733. String content;
  734. {
  735. MemoryBlock contentToSave;
  736. contentToSave.setSize (maxFileSizeBytes + 4);
  737. contentToSave.fillWith (0);
  738. in->read (contentToSave.getData(), maxFileSizeBytes);
  739. delete in;
  740. content = contentToSave.toString();
  741. }
  742. int newStart = 0;
  743. while (newStart < fileSize
  744. && content[newStart] != '\n'
  745. && content[newStart] != '\r')
  746. ++newStart;
  747. logFile.deleteFile();
  748. logFile.appendText (content.substring (newStart), false, false);
  749. }
  750. }
  751. }
  752. }
  753. FileLogger* FileLogger::createDefaultAppLogger (const String& logFileSubDirectoryName,
  754. const String& logFileName,
  755. const String& welcomeMessage,
  756. const int maxInitialFileSizeBytes)
  757. {
  758. #if JUCE_MAC
  759. File logFile ("~/Library/Logs");
  760. logFile = logFile.getChildFile (logFileName);
  761. #else
  762. File logFile (File::getSpecialLocation (File::userApplicationDataDirectory));
  763. if (logFile.isDirectory())
  764. {
  765. logFile = logFile.getChildFile (logFileSubDirectoryName)
  766. .getChildFile (logFileName);
  767. }
  768. #endif
  769. return new FileLogger (logFile, welcomeMessage, maxInitialFileSizeBytes);
  770. }
  771. END_JUCE_NAMESPACE
  772. /********* End of inlined file: juce_FileLogger.cpp *********/
  773. /********* Start of inlined file: juce_Logger.cpp *********/
  774. BEGIN_JUCE_NAMESPACE
  775. Logger::Logger()
  776. {
  777. }
  778. Logger::~Logger()
  779. {
  780. }
  781. static Logger* currentLogger = 0;
  782. void Logger::setCurrentLogger (Logger* const newLogger,
  783. const bool deleteOldLogger)
  784. {
  785. Logger* const oldLogger = currentLogger;
  786. currentLogger = newLogger;
  787. if (deleteOldLogger && (oldLogger != 0))
  788. delete oldLogger;
  789. }
  790. void Logger::writeToLog (const String& message)
  791. {
  792. if (currentLogger != 0)
  793. currentLogger->logMessage (message);
  794. else
  795. outputDebugString (message);
  796. }
  797. #if JUCE_LOG_ASSERTIONS
  798. void JUCE_API juce_LogAssertion (const char* filename, const int lineNum) throw()
  799. {
  800. String m ("JUCE Assertion failure in ");
  801. m << filename << ", line " << lineNum;
  802. Logger::writeToLog (m);
  803. }
  804. #endif
  805. END_JUCE_NAMESPACE
  806. /********* End of inlined file: juce_Logger.cpp *********/
  807. /********* Start of inlined file: juce_Random.cpp *********/
  808. BEGIN_JUCE_NAMESPACE
  809. Random::Random (const int64 seedValue) throw()
  810. : seed (seedValue)
  811. {
  812. }
  813. Random::~Random() throw()
  814. {
  815. }
  816. void Random::setSeed (const int64 newSeed) throw()
  817. {
  818. seed = newSeed;
  819. }
  820. void Random::setSeedRandomly()
  821. {
  822. Random r1 (Time::getMillisecondCounter());
  823. Random r2 (Time::getHighResolutionTicks());
  824. Random r3 (Time::getHighResolutionTicksPerSecond());
  825. Random r4 (Time::currentTimeMillis());
  826. setSeed (nextInt64() ^ r1.nextInt64() ^ r2.nextInt64()
  827. ^ r3.nextInt64() ^ r4.nextInt64());
  828. }
  829. int Random::nextInt() throw()
  830. {
  831. seed = (seed * literal64bit (0x5deece66d) + 11) & literal64bit (0xffffffffffff);
  832. return (int) (seed >> 16);
  833. }
  834. int Random::nextInt (const int maxValue) throw()
  835. {
  836. jassert (maxValue > 0);
  837. return (nextInt() & 0x7fffffff) % maxValue;
  838. }
  839. int64 Random::nextInt64() throw()
  840. {
  841. return (((int64) nextInt()) << 32) | (int64) (uint64) (uint32) nextInt();
  842. }
  843. bool Random::nextBool() throw()
  844. {
  845. return (nextInt() & 0x80000000) != 0;
  846. }
  847. float Random::nextFloat() throw()
  848. {
  849. return ((uint32) nextInt()) / (float) 0xffffffff;
  850. }
  851. double Random::nextDouble() throw()
  852. {
  853. return ((uint32) nextInt()) / (double) 0xffffffff;
  854. }
  855. const BitArray Random::nextLargeNumber (const BitArray& maximumValue) throw()
  856. {
  857. BitArray n;
  858. do
  859. {
  860. fillBitsRandomly (n, 0, maximumValue.getHighestBit() + 1);
  861. }
  862. while (n.compare (maximumValue) >= 0);
  863. return n;
  864. }
  865. void Random::fillBitsRandomly (BitArray& arrayToChange, int startBit, int numBits) throw()
  866. {
  867. arrayToChange.setBit (startBit + numBits - 1, true); // to force the array to pre-allocate space
  868. while ((startBit & 31) != 0 && numBits > 0)
  869. {
  870. arrayToChange.setBit (startBit++, nextBool());
  871. --numBits;
  872. }
  873. while (numBits >= 32)
  874. {
  875. arrayToChange.setBitRangeAsInt (startBit, 32, (unsigned int) nextInt());
  876. startBit += 32;
  877. numBits -= 32;
  878. }
  879. while (--numBits >= 0)
  880. arrayToChange.setBit (startBit + numBits, nextBool());
  881. }
  882. Random& Random::getSystemRandom() throw()
  883. {
  884. static Random sysRand (1);
  885. return sysRand;
  886. }
  887. END_JUCE_NAMESPACE
  888. /********* End of inlined file: juce_Random.cpp *********/
  889. /********* Start of inlined file: juce_RelativeTime.cpp *********/
  890. BEGIN_JUCE_NAMESPACE
  891. RelativeTime::RelativeTime (const double seconds_) throw()
  892. : seconds (seconds_)
  893. {
  894. }
  895. RelativeTime::RelativeTime (const RelativeTime& other) throw()
  896. : seconds (other.seconds)
  897. {
  898. }
  899. RelativeTime::~RelativeTime() throw()
  900. {
  901. }
  902. const RelativeTime RelativeTime::milliseconds (const int milliseconds) throw()
  903. {
  904. return RelativeTime (milliseconds * 0.001);
  905. }
  906. const RelativeTime RelativeTime::milliseconds (const int64 milliseconds) throw()
  907. {
  908. return RelativeTime (milliseconds * 0.001);
  909. }
  910. const RelativeTime RelativeTime::minutes (const double numberOfMinutes) throw()
  911. {
  912. return RelativeTime (numberOfMinutes * 60.0);
  913. }
  914. const RelativeTime RelativeTime::hours (const double numberOfHours) throw()
  915. {
  916. return RelativeTime (numberOfHours * (60.0 * 60.0));
  917. }
  918. const RelativeTime RelativeTime::days (const double numberOfDays) throw()
  919. {
  920. return RelativeTime (numberOfDays * (60.0 * 60.0 * 24.0));
  921. }
  922. const RelativeTime RelativeTime::weeks (const double numberOfWeeks) throw()
  923. {
  924. return RelativeTime (numberOfWeeks * (60.0 * 60.0 * 24.0 * 7.0));
  925. }
  926. int64 RelativeTime::inMilliseconds() const throw()
  927. {
  928. return (int64)(seconds * 1000.0);
  929. }
  930. double RelativeTime::inMinutes() const throw()
  931. {
  932. return seconds / 60.0;
  933. }
  934. double RelativeTime::inHours() const throw()
  935. {
  936. return seconds / (60.0 * 60.0);
  937. }
  938. double RelativeTime::inDays() const throw()
  939. {
  940. return seconds / (60.0 * 60.0 * 24.0);
  941. }
  942. double RelativeTime::inWeeks() const throw()
  943. {
  944. return seconds / (60.0 * 60.0 * 24.0 * 7.0);
  945. }
  946. const String RelativeTime::getDescription (const String& returnValueForZeroTime) const throw()
  947. {
  948. if (seconds < 0.001 && seconds > -0.001)
  949. return returnValueForZeroTime;
  950. String result;
  951. if (seconds < 0)
  952. result = T("-");
  953. int fieldsShown = 0;
  954. int n = abs ((int) inWeeks());
  955. if (n > 0)
  956. {
  957. result << n << ((n == 1) ? TRANS(" week ")
  958. : TRANS(" weeks "));
  959. ++fieldsShown;
  960. }
  961. n = abs ((int) inDays()) % 7;
  962. if (n > 0)
  963. {
  964. result << n << ((n == 1) ? TRANS(" day ")
  965. : TRANS(" days "));
  966. ++fieldsShown;
  967. }
  968. if (fieldsShown < 2)
  969. {
  970. n = abs ((int) inHours()) % 24;
  971. if (n > 0)
  972. {
  973. result << n << ((n == 1) ? TRANS(" hr ")
  974. : TRANS(" hrs "));
  975. ++fieldsShown;
  976. }
  977. if (fieldsShown < 2)
  978. {
  979. n = abs ((int) inMinutes()) % 60;
  980. if (n > 0)
  981. {
  982. result << n << ((n == 1) ? TRANS(" min ")
  983. : TRANS(" mins "));
  984. ++fieldsShown;
  985. }
  986. if (fieldsShown < 2)
  987. {
  988. n = abs ((int) inSeconds()) % 60;
  989. if (n > 0)
  990. {
  991. result << n << ((n == 1) ? TRANS(" sec ")
  992. : TRANS(" secs "));
  993. ++fieldsShown;
  994. }
  995. if (fieldsShown < 1)
  996. {
  997. n = abs ((int) inMilliseconds()) % 1000;
  998. if (n > 0)
  999. {
  1000. result << n << TRANS(" ms");
  1001. ++fieldsShown;
  1002. }
  1003. }
  1004. }
  1005. }
  1006. }
  1007. return result.trimEnd();
  1008. }
  1009. const RelativeTime& RelativeTime::operator= (const RelativeTime& other) throw()
  1010. {
  1011. seconds = other.seconds;
  1012. return *this;
  1013. }
  1014. bool RelativeTime::operator== (const RelativeTime& other) const throw()
  1015. {
  1016. return seconds == other.seconds;
  1017. }
  1018. bool RelativeTime::operator!= (const RelativeTime& other) const throw()
  1019. {
  1020. return seconds != other.seconds;
  1021. }
  1022. bool RelativeTime::operator> (const RelativeTime& other) const throw()
  1023. {
  1024. return seconds > other.seconds;
  1025. }
  1026. bool RelativeTime::operator< (const RelativeTime& other) const throw()
  1027. {
  1028. return seconds < other.seconds;
  1029. }
  1030. bool RelativeTime::operator>= (const RelativeTime& other) const throw()
  1031. {
  1032. return seconds >= other.seconds;
  1033. }
  1034. bool RelativeTime::operator<= (const RelativeTime& other) const throw()
  1035. {
  1036. return seconds <= other.seconds;
  1037. }
  1038. const RelativeTime RelativeTime::operator+ (const RelativeTime& timeToAdd) const throw()
  1039. {
  1040. return RelativeTime (seconds + timeToAdd.seconds);
  1041. }
  1042. const RelativeTime RelativeTime::operator- (const RelativeTime& timeToSubtract) const throw()
  1043. {
  1044. return RelativeTime (seconds - timeToSubtract.seconds);
  1045. }
  1046. const RelativeTime RelativeTime::operator+ (const double secondsToAdd) const throw()
  1047. {
  1048. return RelativeTime (seconds + secondsToAdd);
  1049. }
  1050. const RelativeTime RelativeTime::operator- (const double secondsToSubtract) const throw()
  1051. {
  1052. return RelativeTime (seconds - secondsToSubtract);
  1053. }
  1054. const RelativeTime& RelativeTime::operator+= (const RelativeTime& timeToAdd) throw()
  1055. {
  1056. seconds += timeToAdd.seconds;
  1057. return *this;
  1058. }
  1059. const RelativeTime& RelativeTime::operator-= (const RelativeTime& timeToSubtract) throw()
  1060. {
  1061. seconds -= timeToSubtract.seconds;
  1062. return *this;
  1063. }
  1064. const RelativeTime& RelativeTime::operator+= (const double secondsToAdd) throw()
  1065. {
  1066. seconds += secondsToAdd;
  1067. return *this;
  1068. }
  1069. const RelativeTime& RelativeTime::operator-= (const double secondsToSubtract) throw()
  1070. {
  1071. seconds -= secondsToSubtract;
  1072. return *this;
  1073. }
  1074. END_JUCE_NAMESPACE
  1075. /********* End of inlined file: juce_RelativeTime.cpp *********/
  1076. /********* Start of inlined file: juce_SystemStats.cpp *********/
  1077. BEGIN_JUCE_NAMESPACE
  1078. void juce_initialiseStrings();
  1079. const String SystemStats::getJUCEVersion() throw()
  1080. {
  1081. return "JUCE v" + String (JUCE_MAJOR_VERSION) + "." + String (JUCE_MINOR_VERSION);
  1082. }
  1083. static bool juceInitialisedNonGUI = false;
  1084. void JUCE_PUBLIC_FUNCTION initialiseJuce_NonGUI()
  1085. {
  1086. if (! juceInitialisedNonGUI)
  1087. {
  1088. #if JUCE_MAC
  1089. const ScopedAutoReleasePool pool;
  1090. #endif
  1091. #ifdef JUCE_DEBUG
  1092. // Some simple test code to keep an eye on things and make sure these functions
  1093. // work ok on all platforms. Let me know if any of these assertions fail!
  1094. int n = 1;
  1095. atomicIncrement (n);
  1096. jassert (atomicIncrementAndReturn (n) == 3);
  1097. atomicDecrement (n);
  1098. jassert (atomicDecrementAndReturn (n) == 1);
  1099. jassert (swapByteOrder ((uint32) 0x11223344) == 0x44332211);
  1100. // quick test to make sure the run-time lib doesn't crash on freeing a null-pointer.
  1101. SystemStats* nullPointer = 0;
  1102. juce_free (nullPointer);
  1103. delete[] nullPointer;
  1104. delete nullPointer;
  1105. #endif
  1106. // Now the real initialisation..
  1107. juceInitialisedNonGUI = true;
  1108. DBG (SystemStats::getJUCEVersion());
  1109. Random::getSystemRandom().setSeedRandomly(); // (calling this more than once improves its randomness)
  1110. juce_initialiseStrings();
  1111. SystemStats::initialiseStats();
  1112. Random::getSystemRandom().setSeedRandomly(); // (calling this more than once improves its randomness)
  1113. }
  1114. }
  1115. #if JUCE_WIN32
  1116. // This is imported from the sockets code..
  1117. typedef int (__stdcall juce_CloseWin32SocketLibCall) (void);
  1118. extern juce_CloseWin32SocketLibCall* juce_CloseWin32SocketLib;
  1119. #endif
  1120. #if JUCE_DEBUG
  1121. extern void juce_CheckForDanglingStreams();
  1122. #endif
  1123. void JUCE_PUBLIC_FUNCTION shutdownJuce_NonGUI()
  1124. {
  1125. if (juceInitialisedNonGUI)
  1126. {
  1127. #if JUCE_MAC
  1128. const ScopedAutoReleasePool pool;
  1129. #endif
  1130. #if JUCE_WIN32
  1131. // need to shut down sockets if they were used..
  1132. if (juce_CloseWin32SocketLib != 0)
  1133. (*juce_CloseWin32SocketLib)();
  1134. #endif
  1135. LocalisedStrings::setCurrentMappings (0);
  1136. Thread::stopAllThreads (3000);
  1137. #if JUCE_DEBUG
  1138. juce_CheckForDanglingStreams();
  1139. #endif
  1140. juceInitialisedNonGUI = false;
  1141. }
  1142. }
  1143. #ifdef JUCE_DLL
  1144. void* juce_Malloc (const int size)
  1145. {
  1146. return malloc (size);
  1147. }
  1148. void* juce_Calloc (const int size)
  1149. {
  1150. return calloc (1, size);
  1151. }
  1152. void* juce_Realloc (void* const block, const int size)
  1153. {
  1154. return realloc (block, size);
  1155. }
  1156. void juce_Free (void* const block)
  1157. {
  1158. free (block);
  1159. }
  1160. #if defined (JUCE_DEBUG) && JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  1161. void* juce_DebugMalloc (const int size, const char* file, const int line)
  1162. {
  1163. return _malloc_dbg (size, _NORMAL_BLOCK, file, line);
  1164. }
  1165. void* juce_DebugCalloc (const int size, const char* file, const int line)
  1166. {
  1167. return _calloc_dbg (1, size, _NORMAL_BLOCK, file, line);
  1168. }
  1169. void* juce_DebugRealloc (void* const block, const int size, const char* file, const int line)
  1170. {
  1171. return _realloc_dbg (block, size, _NORMAL_BLOCK, file, line);
  1172. }
  1173. void juce_DebugFree (void* const block)
  1174. {
  1175. _free_dbg (block, _NORMAL_BLOCK);
  1176. }
  1177. #endif
  1178. #endif
  1179. END_JUCE_NAMESPACE
  1180. /********* End of inlined file: juce_SystemStats.cpp *********/
  1181. /********* Start of inlined file: juce_Time.cpp *********/
  1182. #ifdef _MSC_VER
  1183. #pragma warning (disable: 4514)
  1184. #pragma warning (push)
  1185. #endif
  1186. #ifndef JUCE_WIN32
  1187. #include <sys/time.h>
  1188. #else
  1189. #include <ctime>
  1190. #endif
  1191. #include <sys/timeb.h>
  1192. BEGIN_JUCE_NAMESPACE
  1193. #ifdef _MSC_VER
  1194. #pragma warning (pop)
  1195. #ifdef _INC_TIME_INL
  1196. #define USE_NEW_SECURE_TIME_FNS
  1197. #endif
  1198. #endif
  1199. static void millisToLocal (const int64 millis, struct tm& result) throw()
  1200. {
  1201. const int64 seconds = millis / 1000;
  1202. if (seconds < literal64bit (86400) || seconds >= literal64bit (2145916800))
  1203. {
  1204. // use extended maths for dates beyond 1970 to 2037..
  1205. const int timeZoneAdjustment = 31536000 - (int) (Time (1971, 0, 1, 0, 0).toMilliseconds() / 1000);
  1206. const int64 jdm = seconds + timeZoneAdjustment + literal64bit (210866803200);
  1207. const int days = (int) (jdm / literal64bit (86400));
  1208. const int a = 32044 + days;
  1209. const int b = (4 * a + 3) / 146097;
  1210. const int c = a - (b * 146097) / 4;
  1211. const int d = (4 * c + 3) / 1461;
  1212. const int e = c - (d * 1461) / 4;
  1213. const int m = (5 * e + 2) / 153;
  1214. result.tm_mday = e - (153 * m + 2) / 5 + 1;
  1215. result.tm_mon = m + 2 - 12 * (m / 10);
  1216. result.tm_year = b * 100 + d - 6700 + (m / 10);
  1217. result.tm_wday = (days + 1) % 7;
  1218. result.tm_yday = -1;
  1219. int t = (int) (jdm % literal64bit (86400));
  1220. result.tm_hour = t / 3600;
  1221. t %= 3600;
  1222. result.tm_min = t / 60;
  1223. result.tm_sec = t % 60;
  1224. result.tm_isdst = -1;
  1225. }
  1226. else
  1227. {
  1228. time_t now = (time_t) (seconds);
  1229. #if JUCE_WIN32
  1230. #ifdef USE_NEW_SECURE_TIME_FNS
  1231. if (now >= 0 && now <= 0x793406fff)
  1232. localtime_s (&result, &now);
  1233. else
  1234. zeromem (&result, sizeof (result));
  1235. #else
  1236. result = *localtime (&now);
  1237. #endif
  1238. #else
  1239. // more thread-safe
  1240. localtime_r (&now, &result);
  1241. #endif
  1242. }
  1243. }
  1244. Time::Time() throw()
  1245. : millisSinceEpoch (0)
  1246. {
  1247. }
  1248. Time::Time (const Time& other) throw()
  1249. : millisSinceEpoch (other.millisSinceEpoch)
  1250. {
  1251. }
  1252. Time::Time (const int64 ms) throw()
  1253. : millisSinceEpoch (ms)
  1254. {
  1255. }
  1256. Time::Time (const int year,
  1257. const int month,
  1258. const int day,
  1259. const int hours,
  1260. const int minutes,
  1261. const int seconds,
  1262. const int milliseconds,
  1263. const bool useLocalTime) throw()
  1264. {
  1265. jassert (year > 100); // year must be a 4-digit version
  1266. if (year < 1971 || year >= 2038 || ! useLocalTime)
  1267. {
  1268. // use extended maths for dates beyond 1970 to 2037..
  1269. const int timeZoneAdjustment = useLocalTime ? (31536000 - (int) (Time (1971, 0, 1, 0, 0).toMilliseconds() / 1000))
  1270. : 0;
  1271. const int a = (13 - month) / 12;
  1272. const int y = year + 4800 - a;
  1273. const int jd = day + (153 * (month + 12 * a - 2) + 2) / 5
  1274. + (y * 365) + (y / 4) - (y / 100) + (y / 400)
  1275. - 32045;
  1276. const int64 s = ((int64) jd) * literal64bit (86400) - literal64bit (210866803200);
  1277. millisSinceEpoch = 1000 * (s + (hours * 3600 + minutes * 60 + seconds - timeZoneAdjustment))
  1278. + milliseconds;
  1279. }
  1280. else
  1281. {
  1282. struct tm t;
  1283. t.tm_year = year - 1900;
  1284. t.tm_mon = month;
  1285. t.tm_mday = day;
  1286. t.tm_hour = hours;
  1287. t.tm_min = minutes;
  1288. t.tm_sec = seconds;
  1289. t.tm_isdst = -1;
  1290. millisSinceEpoch = 1000 * (int64) mktime (&t);
  1291. if (millisSinceEpoch < 0)
  1292. millisSinceEpoch = 0;
  1293. else
  1294. millisSinceEpoch += milliseconds;
  1295. }
  1296. }
  1297. Time::~Time() throw()
  1298. {
  1299. }
  1300. const Time& Time::operator= (const Time& other) throw()
  1301. {
  1302. millisSinceEpoch = other.millisSinceEpoch;
  1303. return *this;
  1304. }
  1305. int64 Time::currentTimeMillis() throw()
  1306. {
  1307. static uint32 lastCounterResult = 0xffffffff;
  1308. static int64 correction = 0;
  1309. const uint32 now = getMillisecondCounter();
  1310. // check the counter hasn't wrapped (also triggered the first time this function is called)
  1311. if (now < lastCounterResult)
  1312. {
  1313. // double-check it's actually wrapped, in case multi-cpu machines have timers that drift a bit.
  1314. if (lastCounterResult == 0xffffffff || now < lastCounterResult - 10)
  1315. {
  1316. // get the time once using normal library calls, and store the difference needed to
  1317. // turn the millisecond counter into a real time.
  1318. #if JUCE_WIN32
  1319. struct _timeb t;
  1320. #ifdef USE_NEW_SECURE_TIME_FNS
  1321. _ftime_s (&t);
  1322. #else
  1323. _ftime (&t);
  1324. #endif
  1325. correction = (((int64) t.time) * 1000 + t.millitm) - now;
  1326. #else
  1327. struct timeval tv;
  1328. struct timezone tz;
  1329. gettimeofday (&tv, &tz);
  1330. correction = (((int64) tv.tv_sec) * 1000 + tv.tv_usec / 1000) - now;
  1331. #endif
  1332. }
  1333. }
  1334. lastCounterResult = now;
  1335. return correction + now;
  1336. }
  1337. uint32 juce_millisecondsSinceStartup() throw();
  1338. static uint32 lastMSCounterValue = 0;
  1339. uint32 Time::getMillisecondCounter() throw()
  1340. {
  1341. const uint32 now = juce_millisecondsSinceStartup();
  1342. if (now < lastMSCounterValue)
  1343. {
  1344. // in multi-threaded apps this might be called concurrently, so
  1345. // make sure that our last counter value only increases and doesn't
  1346. // go backwards..
  1347. if (now < lastMSCounterValue - 1000)
  1348. lastMSCounterValue = now;
  1349. }
  1350. else
  1351. {
  1352. lastMSCounterValue = now;
  1353. }
  1354. return now;
  1355. }
  1356. uint32 Time::getApproximateMillisecondCounter() throw()
  1357. {
  1358. jassert (lastMSCounterValue != 0);
  1359. return lastMSCounterValue;
  1360. }
  1361. void Time::waitForMillisecondCounter (const uint32 targetTime) throw()
  1362. {
  1363. for (;;)
  1364. {
  1365. const uint32 now = getMillisecondCounter();
  1366. if (now >= targetTime)
  1367. break;
  1368. const int toWait = targetTime - now;
  1369. if (toWait > 2)
  1370. {
  1371. Thread::sleep (jmin (20, toWait >> 1));
  1372. }
  1373. else
  1374. {
  1375. // xxx should consider using mutex_pause on the mac as it apparently
  1376. // makes it seem less like a spinlock and avoids lowering the thread pri.
  1377. for (int i = 10; --i >= 0;)
  1378. Thread::yield();
  1379. }
  1380. }
  1381. }
  1382. double Time::highResolutionTicksToSeconds (const int64 ticks) throw()
  1383. {
  1384. return ticks / (double) getHighResolutionTicksPerSecond();
  1385. }
  1386. int64 Time::secondsToHighResolutionTicks (const double seconds) throw()
  1387. {
  1388. return (int64) (seconds * (double) getHighResolutionTicksPerSecond());
  1389. }
  1390. const Time JUCE_CALLTYPE Time::getCurrentTime() throw()
  1391. {
  1392. return Time (currentTimeMillis());
  1393. }
  1394. const String Time::toString (const bool includeDate,
  1395. const bool includeTime,
  1396. const bool includeSeconds,
  1397. const bool use24HourClock) const throw()
  1398. {
  1399. String result;
  1400. if (includeDate)
  1401. {
  1402. result << getDayOfMonth() << ' '
  1403. << getMonthName (true) << ' '
  1404. << getYear();
  1405. if (includeTime)
  1406. result << ' ';
  1407. }
  1408. if (includeTime)
  1409. {
  1410. if (includeSeconds)
  1411. {
  1412. result += String::formatted (T("%d:%02d:%02d "),
  1413. (use24HourClock) ? getHours()
  1414. : getHoursInAmPmFormat(),
  1415. getMinutes(),
  1416. getSeconds());
  1417. }
  1418. else
  1419. {
  1420. result += String::formatted (T("%d.%02d"),
  1421. (use24HourClock) ? getHours()
  1422. : getHoursInAmPmFormat(),
  1423. getMinutes());
  1424. }
  1425. if (! use24HourClock)
  1426. result << (isAfternoon() ? "pm" : "am");
  1427. }
  1428. return result.trimEnd();
  1429. }
  1430. const String Time::formatted (const tchar* const format) const throw()
  1431. {
  1432. tchar buffer[80];
  1433. struct tm t;
  1434. millisToLocal (millisSinceEpoch, t);
  1435. if (CharacterFunctions::ftime (buffer, 79, format, &t) <= 0)
  1436. {
  1437. int bufferSize = 128;
  1438. for (;;)
  1439. {
  1440. MemoryBlock mb (bufferSize * sizeof (tchar));
  1441. tchar* const b = (tchar*) mb.getData();
  1442. if (CharacterFunctions::ftime (b, bufferSize, format, &t) > 0)
  1443. return String (b);
  1444. bufferSize += 128;
  1445. }
  1446. }
  1447. return String (buffer);
  1448. }
  1449. int Time::getYear() const throw()
  1450. {
  1451. struct tm t;
  1452. millisToLocal (millisSinceEpoch, t);
  1453. return t.tm_year + 1900;
  1454. }
  1455. int Time::getMonth() const throw()
  1456. {
  1457. struct tm t;
  1458. millisToLocal (millisSinceEpoch, t);
  1459. return t.tm_mon;
  1460. }
  1461. int Time::getDayOfMonth() const throw()
  1462. {
  1463. struct tm t;
  1464. millisToLocal (millisSinceEpoch, t);
  1465. return t.tm_mday;
  1466. }
  1467. int Time::getDayOfWeek() const throw()
  1468. {
  1469. struct tm t;
  1470. millisToLocal (millisSinceEpoch, t);
  1471. return t.tm_wday;
  1472. }
  1473. int Time::getHours() const throw()
  1474. {
  1475. struct tm t;
  1476. millisToLocal (millisSinceEpoch, t);
  1477. return t.tm_hour;
  1478. }
  1479. int Time::getHoursInAmPmFormat() const throw()
  1480. {
  1481. const int hours = getHours();
  1482. if (hours == 0)
  1483. return 12;
  1484. else if (hours <= 12)
  1485. return hours;
  1486. else
  1487. return hours - 12;
  1488. }
  1489. bool Time::isAfternoon() const throw()
  1490. {
  1491. return getHours() >= 12;
  1492. }
  1493. static int extendedModulo (const int64 value, const int modulo) throw()
  1494. {
  1495. return (int) (value >= 0 ? (value % modulo)
  1496. : (value - ((value / modulo) + 1) * modulo));
  1497. }
  1498. int Time::getMinutes() const throw()
  1499. {
  1500. struct tm t;
  1501. millisToLocal (millisSinceEpoch, t);
  1502. return t.tm_min;
  1503. }
  1504. int Time::getSeconds() const throw()
  1505. {
  1506. return extendedModulo (millisSinceEpoch / 1000, 60);
  1507. }
  1508. int Time::getMilliseconds() const throw()
  1509. {
  1510. return extendedModulo (millisSinceEpoch, 1000);
  1511. }
  1512. bool Time::isDaylightSavingTime() const throw()
  1513. {
  1514. struct tm t;
  1515. millisToLocal (millisSinceEpoch, t);
  1516. return t.tm_isdst != 0;
  1517. }
  1518. const String Time::getTimeZone() const throw()
  1519. {
  1520. String zone[2];
  1521. #if JUCE_WIN32
  1522. _tzset();
  1523. #ifdef USE_NEW_SECURE_TIME_FNS
  1524. {
  1525. char name [128];
  1526. size_t length;
  1527. for (int i = 0; i < 2; ++i)
  1528. {
  1529. zeromem (name, sizeof (name));
  1530. _get_tzname (&length, name, 127, i);
  1531. zone[i] = name;
  1532. }
  1533. }
  1534. #else
  1535. const char** const zonePtr = (const char**) _tzname;
  1536. zone[0] = zonePtr[0];
  1537. zone[1] = zonePtr[1];
  1538. #endif
  1539. #else
  1540. tzset();
  1541. const char** const zonePtr = (const char**) tzname;
  1542. zone[0] = zonePtr[0];
  1543. zone[1] = zonePtr[1];
  1544. #endif
  1545. if (isDaylightSavingTime())
  1546. {
  1547. zone[0] = zone[1];
  1548. if (zone[0].length() > 3
  1549. && zone[0].containsIgnoreCase (T("daylight"))
  1550. && zone[0].contains (T("GMT")))
  1551. zone[0] = "BST";
  1552. }
  1553. return zone[0].substring (0, 3);
  1554. }
  1555. const String Time::getMonthName (const bool threeLetterVersion) const throw()
  1556. {
  1557. return getMonthName (getMonth(), threeLetterVersion);
  1558. }
  1559. const String Time::getWeekdayName (const bool threeLetterVersion) const throw()
  1560. {
  1561. return getWeekdayName (getDayOfWeek(), threeLetterVersion);
  1562. }
  1563. const String Time::getMonthName (int monthNumber,
  1564. const bool threeLetterVersion) throw()
  1565. {
  1566. const char* const shortMonthNames[] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
  1567. const char* const longMonthNames[] = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };
  1568. monthNumber %= 12;
  1569. return TRANS (threeLetterVersion ? shortMonthNames [monthNumber]
  1570. : longMonthNames [monthNumber]);
  1571. }
  1572. const String Time::getWeekdayName (int day,
  1573. const bool threeLetterVersion) throw()
  1574. {
  1575. const char* const shortDayNames[] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
  1576. const char* const longDayNames[] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };
  1577. day %= 7;
  1578. return TRANS (threeLetterVersion ? shortDayNames [day]
  1579. : longDayNames [day]);
  1580. }
  1581. END_JUCE_NAMESPACE
  1582. /********* End of inlined file: juce_Time.cpp *********/
  1583. /********* Start of inlined file: juce_BitArray.cpp *********/
  1584. BEGIN_JUCE_NAMESPACE
  1585. BitArray::BitArray() throw()
  1586. : numValues (4),
  1587. highestBit (-1),
  1588. negative (false)
  1589. {
  1590. values = (unsigned int*) juce_calloc (sizeof (unsigned int) * (numValues + 1));
  1591. }
  1592. BitArray::BitArray (const int value) throw()
  1593. : numValues (4),
  1594. highestBit (31),
  1595. negative (value < 0)
  1596. {
  1597. values = (unsigned int*) juce_calloc (sizeof (unsigned int) * (numValues + 1));
  1598. values[0] = abs (value);
  1599. highestBit = getHighestBit();
  1600. }
  1601. BitArray::BitArray (int64 value) throw()
  1602. : numValues (4),
  1603. highestBit (63),
  1604. negative (value < 0)
  1605. {
  1606. values = (unsigned int*) juce_calloc (sizeof (unsigned int) * (numValues + 1));
  1607. if (value < 0)
  1608. value = -value;
  1609. values[0] = (unsigned int) value;
  1610. values[1] = (unsigned int) (value >> 32);
  1611. highestBit = getHighestBit();
  1612. }
  1613. BitArray::BitArray (const unsigned int value) throw()
  1614. : numValues (4),
  1615. highestBit (31),
  1616. negative (false)
  1617. {
  1618. values = (unsigned int*) juce_calloc (sizeof (unsigned int) * (numValues + 1));
  1619. values[0] = value;
  1620. highestBit = getHighestBit();
  1621. }
  1622. BitArray::BitArray (const BitArray& other) throw()
  1623. : numValues (jmax (4, (other.highestBit >> 5) + 1)),
  1624. highestBit (other.getHighestBit()),
  1625. negative (other.negative)
  1626. {
  1627. const int bytes = sizeof (unsigned int) * (numValues + 1);
  1628. values = (unsigned int*) juce_malloc (bytes);
  1629. memcpy (values, other.values, bytes);
  1630. }
  1631. BitArray::~BitArray() throw()
  1632. {
  1633. juce_free (values);
  1634. }
  1635. const BitArray& BitArray::operator= (const BitArray& other) throw()
  1636. {
  1637. if (this != &other)
  1638. {
  1639. juce_free (values);
  1640. highestBit = other.getHighestBit();
  1641. numValues = jmax (4, (highestBit >> 5) + 1);
  1642. negative = other.negative;
  1643. const int memSize = sizeof (unsigned int) * (numValues + 1);
  1644. values = (unsigned int*)juce_malloc (memSize);
  1645. memcpy (values, other.values, memSize);
  1646. }
  1647. return *this;
  1648. }
  1649. // result == 0 = the same
  1650. // result < 0 = this number is smaller
  1651. // result > 0 = this number is bigger
  1652. int BitArray::compare (const BitArray& other) const throw()
  1653. {
  1654. if (isNegative() == other.isNegative())
  1655. {
  1656. const int absComp = compareAbsolute (other);
  1657. return isNegative() ? -absComp : absComp;
  1658. }
  1659. else
  1660. {
  1661. return isNegative() ? -1 : 1;
  1662. }
  1663. }
  1664. int BitArray::compareAbsolute (const BitArray& other) const throw()
  1665. {
  1666. const int h1 = getHighestBit();
  1667. const int h2 = other.getHighestBit();
  1668. if (h1 > h2)
  1669. return 1;
  1670. else if (h1 < h2)
  1671. return -1;
  1672. for (int i = (h1 >> 5) + 1; --i >= 0;)
  1673. if (values[i] != other.values[i])
  1674. return (values[i] > other.values[i]) ? 1 : -1;
  1675. return 0;
  1676. }
  1677. bool BitArray::operator== (const BitArray& other) const throw()
  1678. {
  1679. return compare (other) == 0;
  1680. }
  1681. bool BitArray::operator!= (const BitArray& other) const throw()
  1682. {
  1683. return compare (other) != 0;
  1684. }
  1685. bool BitArray::operator[] (const int bit) const throw()
  1686. {
  1687. return bit >= 0 && bit <= highestBit
  1688. && ((values [bit >> 5] & (1 << (bit & 31))) != 0);
  1689. }
  1690. bool BitArray::isEmpty() const throw()
  1691. {
  1692. return getHighestBit() < 0;
  1693. }
  1694. void BitArray::clear() throw()
  1695. {
  1696. if (numValues > 16)
  1697. {
  1698. juce_free (values);
  1699. numValues = 4;
  1700. values = (unsigned int*) juce_calloc (sizeof (unsigned int) * (numValues + 1));
  1701. }
  1702. else
  1703. {
  1704. zeromem (values, sizeof (unsigned int) * (numValues + 1));
  1705. }
  1706. highestBit = -1;
  1707. negative = false;
  1708. }
  1709. void BitArray::setBit (const int bit) throw()
  1710. {
  1711. if (bit >= 0)
  1712. {
  1713. if (bit > highestBit)
  1714. {
  1715. ensureSize (bit >> 5);
  1716. highestBit = bit;
  1717. }
  1718. values [bit >> 5] |= (1 << (bit & 31));
  1719. }
  1720. }
  1721. void BitArray::setBit (const int bit,
  1722. const bool shouldBeSet) throw()
  1723. {
  1724. if (shouldBeSet)
  1725. setBit (bit);
  1726. else
  1727. clearBit (bit);
  1728. }
  1729. void BitArray::clearBit (const int bit) throw()
  1730. {
  1731. if (bit >= 0 && bit <= highestBit)
  1732. values [bit >> 5] &= ~(1 << (bit & 31));
  1733. }
  1734. void BitArray::setRange (int startBit,
  1735. int numBits,
  1736. const bool shouldBeSet) throw()
  1737. {
  1738. while (--numBits >= 0)
  1739. setBit (startBit++, shouldBeSet);
  1740. }
  1741. void BitArray::insertBit (const int bit,
  1742. const bool shouldBeSet) throw()
  1743. {
  1744. if (bit >= 0)
  1745. shiftBits (1, bit);
  1746. setBit (bit, shouldBeSet);
  1747. }
  1748. void BitArray::andWith (const BitArray& other) throw()
  1749. {
  1750. // this operation will only work with the absolute values
  1751. jassert (isNegative() == other.isNegative());
  1752. int n = numValues;
  1753. while (n > other.numValues)
  1754. values[--n] = 0;
  1755. while (--n >= 0)
  1756. values[n] &= other.values[n];
  1757. if (other.highestBit < highestBit)
  1758. highestBit = other.highestBit;
  1759. highestBit = getHighestBit();
  1760. }
  1761. void BitArray::orWith (const BitArray& other) throw()
  1762. {
  1763. if (other.highestBit < 0)
  1764. return;
  1765. // this operation will only work with the absolute values
  1766. jassert (isNegative() == other.isNegative());
  1767. ensureSize (other.highestBit >> 5);
  1768. int n = (other.highestBit >> 5) + 1;
  1769. while (--n >= 0)
  1770. values[n] |= other.values[n];
  1771. if (other.highestBit > highestBit)
  1772. highestBit = other.highestBit;
  1773. highestBit = getHighestBit();
  1774. }
  1775. void BitArray::xorWith (const BitArray& other) throw()
  1776. {
  1777. if (other.highestBit < 0)
  1778. return;
  1779. // this operation will only work with the absolute values
  1780. jassert (isNegative() == other.isNegative());
  1781. ensureSize (other.highestBit >> 5);
  1782. int n = (other.highestBit >> 5) + 1;
  1783. while (--n >= 0)
  1784. values[n] ^= other.values[n];
  1785. if (other.highestBit > highestBit)
  1786. highestBit = other.highestBit;
  1787. highestBit = getHighestBit();
  1788. }
  1789. void BitArray::add (const BitArray& other) throw()
  1790. {
  1791. if (other.isNegative())
  1792. {
  1793. BitArray o (other);
  1794. o.negate();
  1795. subtract (o);
  1796. return;
  1797. }
  1798. if (isNegative())
  1799. {
  1800. if (compareAbsolute (other) < 0)
  1801. {
  1802. BitArray temp (*this);
  1803. temp.negate();
  1804. *this = other;
  1805. subtract (temp);
  1806. }
  1807. else
  1808. {
  1809. negate();
  1810. subtract (other);
  1811. negate();
  1812. }
  1813. return;
  1814. }
  1815. if (other.highestBit > highestBit)
  1816. highestBit = other.highestBit;
  1817. ++highestBit;
  1818. const int numInts = (highestBit >> 5) + 1;
  1819. ensureSize (numInts);
  1820. int64 remainder = 0;
  1821. for (int i = 0; i <= numInts; ++i)
  1822. {
  1823. if (i < numValues)
  1824. remainder += values[i];
  1825. if (i < other.numValues)
  1826. remainder += other.values[i];
  1827. values[i] = (unsigned int) remainder;
  1828. remainder >>= 32;
  1829. }
  1830. jassert (remainder == 0);
  1831. highestBit = getHighestBit();
  1832. }
  1833. void BitArray::subtract (const BitArray& other) throw()
  1834. {
  1835. if (other.isNegative())
  1836. {
  1837. BitArray o (other);
  1838. o.negate();
  1839. add (o);
  1840. return;
  1841. }
  1842. if (! isNegative())
  1843. {
  1844. if (compareAbsolute (other) < 0)
  1845. {
  1846. BitArray temp (*this);
  1847. *this = other;
  1848. subtract (temp);
  1849. negate();
  1850. return;
  1851. }
  1852. }
  1853. else
  1854. {
  1855. negate();
  1856. add (other);
  1857. negate();
  1858. return;
  1859. }
  1860. const int numInts = (highestBit >> 5) + 1;
  1861. const int maxOtherInts = (other.highestBit >> 5) + 1;
  1862. int64 amountToSubtract = 0;
  1863. for (int i = 0; i <= numInts; ++i)
  1864. {
  1865. if (i <= maxOtherInts)
  1866. amountToSubtract += (int64)other.values[i];
  1867. if (values[i] >= amountToSubtract)
  1868. {
  1869. values[i] = (unsigned int) (values[i] - amountToSubtract);
  1870. amountToSubtract = 0;
  1871. }
  1872. else
  1873. {
  1874. const int64 n = ((int64) values[i] + (((int64) 1) << 32)) - amountToSubtract;
  1875. values[i] = (unsigned int) n;
  1876. amountToSubtract = 1;
  1877. }
  1878. }
  1879. }
  1880. void BitArray::multiplyBy (const BitArray& other) throw()
  1881. {
  1882. BitArray total;
  1883. highestBit = getHighestBit();
  1884. const bool wasNegative = isNegative();
  1885. setNegative (false);
  1886. for (int i = 0; i <= highestBit; ++i)
  1887. {
  1888. if (operator[](i))
  1889. {
  1890. BitArray n (other);
  1891. n.setNegative (false);
  1892. n.shiftBits (i);
  1893. total.add (n);
  1894. }
  1895. }
  1896. *this = total;
  1897. negative = wasNegative ^ other.isNegative();
  1898. }
  1899. void BitArray::divideBy (const BitArray& divisor, BitArray& remainder) throw()
  1900. {
  1901. jassert (this != &remainder); // (can't handle passing itself in to get the remainder)
  1902. const int divHB = divisor.getHighestBit();
  1903. const int ourHB = getHighestBit();
  1904. if (divHB < 0 || ourHB < 0)
  1905. {
  1906. // division by zero
  1907. remainder.clear();
  1908. clear();
  1909. }
  1910. else
  1911. {
  1912. remainder = *this;
  1913. remainder.setNegative (false);
  1914. const bool wasNegative = isNegative();
  1915. clear();
  1916. BitArray temp (divisor);
  1917. temp.setNegative (false);
  1918. int leftShift = ourHB - divHB;
  1919. temp.shiftBits (leftShift);
  1920. while (leftShift >= 0)
  1921. {
  1922. if (remainder.compareAbsolute (temp) >= 0)
  1923. {
  1924. remainder.subtract (temp);
  1925. setBit (leftShift);
  1926. }
  1927. if (--leftShift >= 0)
  1928. temp.shiftBits (-1);
  1929. }
  1930. negative = wasNegative ^ divisor.isNegative();
  1931. remainder.setNegative (wasNegative);
  1932. }
  1933. }
  1934. void BitArray::modulo (const BitArray& divisor) throw()
  1935. {
  1936. BitArray remainder;
  1937. divideBy (divisor, remainder);
  1938. *this = remainder;
  1939. }
  1940. static const BitArray simpleGCD (BitArray* m, BitArray* n) throw()
  1941. {
  1942. while (! m->isEmpty())
  1943. {
  1944. if (n->compareAbsolute (*m) > 0)
  1945. swapVariables (m, n);
  1946. m->subtract (*n);
  1947. }
  1948. return *n;
  1949. }
  1950. const BitArray BitArray::findGreatestCommonDivisor (BitArray n) const throw()
  1951. {
  1952. BitArray m (*this);
  1953. while (! n.isEmpty())
  1954. {
  1955. if (abs (m.getHighestBit() - n.getHighestBit()) <= 16)
  1956. return simpleGCD (&m, &n);
  1957. BitArray temp1 (m), temp2;
  1958. temp1.divideBy (n, temp2);
  1959. m = n;
  1960. n = temp2;
  1961. }
  1962. return m;
  1963. }
  1964. void BitArray::exponentModulo (const BitArray& exponent,
  1965. const BitArray& modulus) throw()
  1966. {
  1967. BitArray exp (exponent);
  1968. exp.modulo (modulus);
  1969. BitArray value (*this);
  1970. value.modulo (modulus);
  1971. clear();
  1972. setBit (0);
  1973. while (! exp.isEmpty())
  1974. {
  1975. if (exp [0])
  1976. {
  1977. multiplyBy (value);
  1978. this->modulo (modulus);
  1979. }
  1980. value.multiplyBy (value);
  1981. value.modulo (modulus);
  1982. exp.shiftBits (-1);
  1983. }
  1984. }
  1985. void BitArray::inverseModulo (const BitArray& modulus) throw()
  1986. {
  1987. const BitArray one (1);
  1988. if (modulus == one || modulus.isNegative())
  1989. {
  1990. clear();
  1991. return;
  1992. }
  1993. if (isNegative() || compareAbsolute (modulus) >= 0)
  1994. this->modulo (modulus);
  1995. if (*this == one)
  1996. return;
  1997. if (! (*this)[0])
  1998. {
  1999. // not invertible
  2000. clear();
  2001. return;
  2002. }
  2003. BitArray a1 (modulus);
  2004. BitArray a2 (*this);
  2005. BitArray b1 (modulus);
  2006. BitArray b2 (1);
  2007. while (a2 != one)
  2008. {
  2009. BitArray temp1, temp2, multiplier (a1);
  2010. multiplier.divideBy (a2, temp1);
  2011. temp1 = a2;
  2012. temp1.multiplyBy (multiplier);
  2013. temp2 = a1;
  2014. temp2.subtract (temp1);
  2015. a1 = a2;
  2016. a2 = temp2;
  2017. temp1 = b2;
  2018. temp1.multiplyBy (multiplier);
  2019. temp2 = b1;
  2020. temp2.subtract (temp1);
  2021. b1 = b2;
  2022. b2 = temp2;
  2023. }
  2024. while (b2.isNegative())
  2025. b2.add (modulus);
  2026. b2.modulo (modulus);
  2027. *this = b2;
  2028. }
  2029. void BitArray::shiftBits (int bits, const int startBit) throw()
  2030. {
  2031. if (highestBit < 0)
  2032. return;
  2033. if (startBit > 0)
  2034. {
  2035. if (bits < 0)
  2036. {
  2037. // right shift
  2038. for (int i = startBit; i <= highestBit; ++i)
  2039. setBit (i, operator[] (i - bits));
  2040. highestBit = getHighestBit();
  2041. }
  2042. else if (bits > 0)
  2043. {
  2044. // left shift
  2045. for (int i = highestBit + 1; --i >= startBit;)
  2046. setBit (i + bits, operator[] (i));
  2047. while (--bits >= 0)
  2048. clearBit (bits + startBit);
  2049. }
  2050. }
  2051. else
  2052. {
  2053. if (bits < 0)
  2054. {
  2055. // right shift
  2056. bits = -bits;
  2057. if (bits > highestBit)
  2058. {
  2059. clear();
  2060. }
  2061. else
  2062. {
  2063. const int wordsToMove = bits >> 5;
  2064. int top = 1 + (highestBit >> 5) - wordsToMove;
  2065. highestBit -= bits;
  2066. if (wordsToMove > 0)
  2067. {
  2068. int i;
  2069. for (i = 0; i < top; ++i)
  2070. values [i] = values [i + wordsToMove];
  2071. for (i = 0; i < wordsToMove; ++i)
  2072. values [top + i] = 0;
  2073. bits &= 31;
  2074. }
  2075. if (bits != 0)
  2076. {
  2077. const int invBits = 32 - bits;
  2078. --top;
  2079. for (int i = 0; i < top; ++i)
  2080. values[i] = (values[i] >> bits) | (values [i + 1] << invBits);
  2081. values[top] = (values[top] >> bits);
  2082. }
  2083. highestBit = getHighestBit();
  2084. }
  2085. }
  2086. else if (bits > 0)
  2087. {
  2088. // left shift
  2089. ensureSize (((highestBit + bits) >> 5) + 1);
  2090. const int wordsToMove = bits >> 5;
  2091. int top = 1 + (highestBit >> 5);
  2092. highestBit += bits;
  2093. if (wordsToMove > 0)
  2094. {
  2095. int i;
  2096. for (i = top; --i >= 0;)
  2097. values [i + wordsToMove] = values [i];
  2098. for (i = 0; i < wordsToMove; ++i)
  2099. values [i] = 0;
  2100. bits &= 31;
  2101. }
  2102. if (bits != 0)
  2103. {
  2104. const int invBits = 32 - bits;
  2105. for (int i = top + 1 + wordsToMove; --i > wordsToMove;)
  2106. values[i] = (values[i] << bits) | (values [i - 1] >> invBits);
  2107. values [wordsToMove] = values [wordsToMove] << bits;
  2108. }
  2109. highestBit = getHighestBit();
  2110. }
  2111. }
  2112. }
  2113. const BitArray BitArray::getBitRange (int startBit, int numBits) const throw()
  2114. {
  2115. BitArray r;
  2116. numBits = jmin (numBits, getHighestBit() + 1 - startBit);
  2117. r.ensureSize (numBits >> 5);
  2118. r.highestBit = numBits;
  2119. int i = 0;
  2120. while (numBits > 0)
  2121. {
  2122. r.values[i++] = getBitRangeAsInt (startBit, jmin (32, numBits));
  2123. numBits -= 32;
  2124. startBit += 32;
  2125. }
  2126. r.highestBit = r.getHighestBit();
  2127. return r;
  2128. }
  2129. int BitArray::getBitRangeAsInt (const int startBit, int numBits) const throw()
  2130. {
  2131. if (numBits > 32)
  2132. {
  2133. jassertfalse // use getBitRange() if you need more than 32 bits..
  2134. numBits = 32;
  2135. }
  2136. numBits = jmin (numBits, highestBit + 1 - startBit);
  2137. if (numBits <= 0)
  2138. return 0;
  2139. const int pos = startBit >> 5;
  2140. const int offset = startBit & 31;
  2141. const int endSpace = 32 - numBits;
  2142. uint32 n = ((uint32) values [pos]) >> offset;
  2143. if (offset > endSpace)
  2144. n |= ((uint32) values [pos + 1]) << (32 - offset);
  2145. return (int) (n & (((uint32) 0xffffffff) >> endSpace));
  2146. }
  2147. void BitArray::setBitRangeAsInt (const int startBit, int numBits, unsigned int valueToSet) throw()
  2148. {
  2149. if (numBits > 32)
  2150. {
  2151. jassertfalse
  2152. numBits = 32;
  2153. }
  2154. for (int i = 0; i < numBits; ++i)
  2155. {
  2156. setBit (startBit + i, (valueToSet & 1) != 0);
  2157. valueToSet >>= 1;
  2158. }
  2159. }
  2160. bool BitArray::isNegative() const throw()
  2161. {
  2162. return negative && ! isEmpty();
  2163. }
  2164. void BitArray::setNegative (const bool neg) throw()
  2165. {
  2166. negative = neg;
  2167. }
  2168. void BitArray::negate() throw()
  2169. {
  2170. negative = (! negative) && ! isEmpty();
  2171. }
  2172. int BitArray::countNumberOfSetBits() const throw()
  2173. {
  2174. int total = 0;
  2175. for (int i = (highestBit >> 5) + 1; --i >= 0;)
  2176. {
  2177. unsigned int n = values[i];
  2178. if (n == 0xffffffff)
  2179. {
  2180. total += 32;
  2181. }
  2182. else
  2183. {
  2184. while (n != 0)
  2185. {
  2186. total += (n & 1);
  2187. n >>= 1;
  2188. }
  2189. }
  2190. }
  2191. return total;
  2192. }
  2193. int BitArray::getHighestBit() const throw()
  2194. {
  2195. for (int i = highestBit + 1; --i >= 0;)
  2196. if ((values [i >> 5] & (1 << (i & 31))) != 0)
  2197. return i;
  2198. return -1;
  2199. }
  2200. int BitArray::findNextSetBit (int i) const throw()
  2201. {
  2202. for (; i <= highestBit; ++i)
  2203. if ((values [i >> 5] & (1 << (i & 31))) != 0)
  2204. return i;
  2205. return -1;
  2206. }
  2207. int BitArray::findNextClearBit (int i) const throw()
  2208. {
  2209. for (; i <= highestBit; ++i)
  2210. if ((values [i >> 5] & (1 << (i & 31))) == 0)
  2211. break;
  2212. return i;
  2213. }
  2214. void BitArray::ensureSize (const int numVals) throw()
  2215. {
  2216. if (numVals + 2 >= numValues)
  2217. {
  2218. int oldSize = numValues;
  2219. numValues = ((numVals + 2) * 3) / 2;
  2220. values = (unsigned int*) juce_realloc (values, sizeof (unsigned int) * numValues + 4);
  2221. while (oldSize < numValues)
  2222. values [oldSize++] = 0;
  2223. }
  2224. }
  2225. const String BitArray::toString (const int base, const int minimumNumCharacters) const throw()
  2226. {
  2227. String s;
  2228. BitArray v (*this);
  2229. if (base == 2 || base == 8 || base == 16)
  2230. {
  2231. const int bits = (base == 2) ? 1 : (base == 8 ? 3 : 4);
  2232. static const tchar* const hexDigits = T("0123456789abcdef");
  2233. for (;;)
  2234. {
  2235. const int remainder = v.getBitRangeAsInt (0, bits);
  2236. v.shiftBits (-bits);
  2237. if (remainder == 0 && v.isEmpty())
  2238. break;
  2239. s = String::charToString (hexDigits [remainder]) + s;
  2240. }
  2241. }
  2242. else if (base == 10)
  2243. {
  2244. const BitArray ten (10);
  2245. BitArray remainder;
  2246. for (;;)
  2247. {
  2248. v.divideBy (ten, remainder);
  2249. if (remainder.isEmpty() && v.isEmpty())
  2250. break;
  2251. s = String (remainder.getBitRangeAsInt (0, 8)) + s;
  2252. }
  2253. }
  2254. else
  2255. {
  2256. jassertfalse // can't do the specified base
  2257. return String::empty;
  2258. }
  2259. const int length = s.length();
  2260. if (length < minimumNumCharacters)
  2261. s = String::repeatedString (T("0"), minimumNumCharacters - length);
  2262. return isNegative() ? T("-") + s : s;
  2263. }
  2264. void BitArray::parseString (const String& text,
  2265. const int base) throw()
  2266. {
  2267. clear();
  2268. const tchar* t = (const tchar*) text;
  2269. if (base == 2 || base == 8 || base == 16)
  2270. {
  2271. const int bits = (base == 2) ? 1 : (base == 8 ? 3 : 4);
  2272. for (;;)
  2273. {
  2274. const tchar c = *t++;
  2275. const int digit = CharacterFunctions::getHexDigitValue (c);
  2276. if (((unsigned int) digit) < (unsigned int) base)
  2277. {
  2278. shiftBits (bits);
  2279. add (digit);
  2280. }
  2281. else if (c == 0)
  2282. {
  2283. break;
  2284. }
  2285. }
  2286. }
  2287. else if (base == 10)
  2288. {
  2289. const BitArray ten ((unsigned int) 10);
  2290. for (;;)
  2291. {
  2292. const tchar c = *t++;
  2293. if (c >= T('0') && c <= T('9'))
  2294. {
  2295. multiplyBy (ten);
  2296. add ((int) (c - T('0')));
  2297. }
  2298. else if (c == 0)
  2299. {
  2300. break;
  2301. }
  2302. }
  2303. }
  2304. setNegative (text.trimStart().startsWithChar (T('-')));
  2305. }
  2306. const MemoryBlock BitArray::toMemoryBlock() const throw()
  2307. {
  2308. const int numBytes = (getHighestBit() + 8) >> 3;
  2309. MemoryBlock mb (numBytes);
  2310. for (int i = 0; i < numBytes; ++i)
  2311. mb[i] = (uint8) getBitRangeAsInt (i << 3, 8);
  2312. return mb;
  2313. }
  2314. void BitArray::loadFromMemoryBlock (const MemoryBlock& data) throw()
  2315. {
  2316. clear();
  2317. for (int i = data.getSize(); --i >= 0;)
  2318. this->setBitRangeAsInt (i << 3, 8, data [i]);
  2319. }
  2320. END_JUCE_NAMESPACE
  2321. /********* End of inlined file: juce_BitArray.cpp *********/
  2322. /********* Start of inlined file: juce_MemoryBlock.cpp *********/
  2323. BEGIN_JUCE_NAMESPACE
  2324. MemoryBlock::MemoryBlock() throw()
  2325. : data (0),
  2326. size (0)
  2327. {
  2328. }
  2329. MemoryBlock::MemoryBlock (const int initialSize,
  2330. const bool initialiseToZero) throw()
  2331. {
  2332. if (initialSize > 0)
  2333. {
  2334. size = initialSize;
  2335. if (initialiseToZero)
  2336. data = (char*) juce_calloc (initialSize);
  2337. else
  2338. data = (char*) juce_malloc (initialSize);
  2339. }
  2340. else
  2341. {
  2342. data = 0;
  2343. size = 0;
  2344. }
  2345. }
  2346. MemoryBlock::MemoryBlock (const MemoryBlock& other) throw()
  2347. : data (0),
  2348. size (other.size)
  2349. {
  2350. if (size > 0)
  2351. {
  2352. jassert (other.data != 0);
  2353. data = (char*) juce_malloc (size);
  2354. memcpy (data, other.data, size);
  2355. }
  2356. }
  2357. MemoryBlock::MemoryBlock (const void* const dataToInitialiseFrom,
  2358. const int sizeInBytes) throw()
  2359. : data (0),
  2360. size (jmax (0, sizeInBytes))
  2361. {
  2362. jassert (sizeInBytes >= 0);
  2363. if (size > 0)
  2364. {
  2365. jassert (dataToInitialiseFrom != 0); // non-zero size, but a zero pointer passed-in?
  2366. data = (char*) juce_malloc (size);
  2367. if (dataToInitialiseFrom != 0)
  2368. memcpy (data, dataToInitialiseFrom, size);
  2369. }
  2370. }
  2371. MemoryBlock::~MemoryBlock() throw()
  2372. {
  2373. jassert (size >= 0); // should never happen
  2374. jassert (size == 0 || data != 0); // non-zero size but no data allocated?
  2375. juce_free (data);
  2376. }
  2377. const MemoryBlock& MemoryBlock::operator= (const MemoryBlock& other) throw()
  2378. {
  2379. if (this != &other)
  2380. {
  2381. setSize (other.size, false);
  2382. memcpy (data, other.data, size);
  2383. }
  2384. return *this;
  2385. }
  2386. bool MemoryBlock::operator== (const MemoryBlock& other) const throw()
  2387. {
  2388. return (size == other.size)
  2389. && (memcmp (data, other.data, size) == 0);
  2390. }
  2391. bool MemoryBlock::operator!= (const MemoryBlock& other) const throw()
  2392. {
  2393. return ! operator== (other);
  2394. }
  2395. // this will resize the block to this size
  2396. void MemoryBlock::setSize (const int newSize,
  2397. const bool initialiseToZero) throw()
  2398. {
  2399. if (size != newSize)
  2400. {
  2401. if (newSize <= 0)
  2402. {
  2403. juce_free (data);
  2404. data = 0;
  2405. size = 0;
  2406. }
  2407. else
  2408. {
  2409. if (data != 0)
  2410. {
  2411. data = (char*) juce_realloc (data, newSize);
  2412. if (initialiseToZero && (newSize > size))
  2413. zeromem (data + size, newSize - size);
  2414. }
  2415. else
  2416. {
  2417. if (initialiseToZero)
  2418. data = (char*) juce_calloc (newSize);
  2419. else
  2420. data = (char*) juce_malloc (newSize);
  2421. }
  2422. size = newSize;
  2423. }
  2424. }
  2425. }
  2426. void MemoryBlock::ensureSize (const int minimumSize,
  2427. const bool initialiseToZero) throw()
  2428. {
  2429. if (size < minimumSize)
  2430. setSize (minimumSize, initialiseToZero);
  2431. }
  2432. void MemoryBlock::fillWith (const uint8 value) throw()
  2433. {
  2434. memset (data, (int) value, size);
  2435. }
  2436. void MemoryBlock::append (const void* const srcData,
  2437. const int numBytes) throw()
  2438. {
  2439. if (numBytes > 0)
  2440. {
  2441. const int oldSize = size;
  2442. setSize (size + numBytes);
  2443. memcpy (data + oldSize, srcData, numBytes);
  2444. }
  2445. }
  2446. void MemoryBlock::copyFrom (const void* const src, int offset, int num) throw()
  2447. {
  2448. const char* d = (const char*) src;
  2449. if (offset < 0)
  2450. {
  2451. d -= offset;
  2452. num -= offset;
  2453. offset = 0;
  2454. }
  2455. if (offset + num > size)
  2456. num = size - offset;
  2457. if (num > 0)
  2458. memcpy (data + offset, d, num);
  2459. }
  2460. void MemoryBlock::copyTo (void* const dst, int offset, int num) const throw()
  2461. {
  2462. char* d = (char*) dst;
  2463. if (offset < 0)
  2464. {
  2465. zeromem (d, -offset);
  2466. d -= offset;
  2467. num += offset;
  2468. offset = 0;
  2469. }
  2470. if (offset + num > size)
  2471. {
  2472. const int newNum = size - offset;
  2473. zeromem (d + newNum, num - newNum);
  2474. num = newNum;
  2475. }
  2476. if (num > 0)
  2477. memcpy (d, data + offset, num);
  2478. }
  2479. void MemoryBlock::removeSection (int startByte, int numBytesToRemove) throw()
  2480. {
  2481. if (startByte < 0)
  2482. {
  2483. numBytesToRemove += startByte;
  2484. startByte = 0;
  2485. }
  2486. if (startByte + numBytesToRemove >= size)
  2487. {
  2488. setSize (startByte);
  2489. }
  2490. else if (numBytesToRemove > 0)
  2491. {
  2492. memmove (data + startByte,
  2493. data + startByte + numBytesToRemove,
  2494. size - (startByte + numBytesToRemove));
  2495. setSize (size - numBytesToRemove);
  2496. }
  2497. }
  2498. const String MemoryBlock::toString() const throw()
  2499. {
  2500. return String (data, size);
  2501. }
  2502. int MemoryBlock::getBitRange (const int bitRangeStart, int numBits) const throw()
  2503. {
  2504. int res = 0;
  2505. int byte = bitRangeStart >> 3;
  2506. int offsetInByte = bitRangeStart & 7;
  2507. int bitsSoFar = 0;
  2508. while (numBits > 0 && byte < size)
  2509. {
  2510. const int bitsThisTime = jmin (numBits, 8 - offsetInByte);
  2511. const int mask = (0xff >> (8 - bitsThisTime)) << offsetInByte;
  2512. res |= (((data[byte] & mask) >> offsetInByte) << bitsSoFar);
  2513. bitsSoFar += bitsThisTime;
  2514. numBits -= bitsThisTime;
  2515. ++byte;
  2516. offsetInByte = 0;
  2517. }
  2518. return res;
  2519. }
  2520. void MemoryBlock::setBitRange (const int bitRangeStart, int numBits, int bitsToSet) throw()
  2521. {
  2522. int byte = bitRangeStart >> 3;
  2523. int offsetInByte = bitRangeStart & 7;
  2524. unsigned int mask = ~((((unsigned int)0xffffffff) << (32 - numBits)) >> (32 - numBits));
  2525. while (numBits > 0 && byte < size)
  2526. {
  2527. const int bitsThisTime = jmin (numBits, 8 - offsetInByte);
  2528. const unsigned int tempMask = (mask << offsetInByte) | ~((((unsigned int)0xffffffff) >> offsetInByte) << offsetInByte);
  2529. const unsigned int tempBits = bitsToSet << offsetInByte;
  2530. data[byte] = (char)((data[byte] & tempMask) | tempBits);
  2531. ++byte;
  2532. numBits -= bitsThisTime;
  2533. bitsToSet >>= bitsThisTime;
  2534. mask >>= bitsThisTime;
  2535. offsetInByte = 0;
  2536. }
  2537. }
  2538. void MemoryBlock::loadFromHexString (const String& hex) throw()
  2539. {
  2540. ensureSize (hex.length() >> 1);
  2541. char* dest = data;
  2542. int i = 0;
  2543. for (;;)
  2544. {
  2545. int byte = 0;
  2546. for (int loop = 2; --loop >= 0;)
  2547. {
  2548. byte <<= 4;
  2549. for (;;)
  2550. {
  2551. const tchar c = hex [i++];
  2552. if (c >= T('0') && c <= T('9'))
  2553. {
  2554. byte |= c - T('0');
  2555. break;
  2556. }
  2557. else if (c >= T('a') && c <= T('z'))
  2558. {
  2559. byte |= c - (T('a') - 10);
  2560. break;
  2561. }
  2562. else if (c >= T('A') && c <= T('Z'))
  2563. {
  2564. byte |= c - (T('A') - 10);
  2565. break;
  2566. }
  2567. else if (c == 0)
  2568. {
  2569. setSize ((int) (dest - data));
  2570. return;
  2571. }
  2572. }
  2573. }
  2574. *dest++ = (char) byte;
  2575. }
  2576. }
  2577. static const char* const encodingTable
  2578. = ".ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+";
  2579. const String MemoryBlock::toBase64Encoding() const throw()
  2580. {
  2581. const int numChars = ((size << 3) + 5) / 6;
  2582. String destString (size); // store the length, followed by a '.', and then the data.
  2583. const int initialLen = destString.length();
  2584. destString.preallocateStorage (initialLen + 2 + numChars);
  2585. tchar* d = const_cast <tchar*> (((const tchar*) destString) + initialLen);
  2586. *d++ = T('.');
  2587. for (int i = 0; i < numChars; ++i)
  2588. *d++ = encodingTable [getBitRange (i * 6, 6)];
  2589. *d++ = 0;
  2590. return destString;
  2591. }
  2592. bool MemoryBlock::fromBase64Encoding (const String& s) throw()
  2593. {
  2594. const int startPos = s.indexOfChar (T('.')) + 1;
  2595. if (startPos <= 0)
  2596. return false;
  2597. const int numBytesNeeded = s.substring (0, startPos - 1).getIntValue();
  2598. setSize (numBytesNeeded, true);
  2599. const int numChars = s.length() - startPos;
  2600. const tchar* const srcChars = ((const tchar*) s) + startPos;
  2601. int pos = 0;
  2602. for (int i = 0; i < numChars; ++i)
  2603. {
  2604. const char c = (char) srcChars[i];
  2605. for (int j = 0; j < 64; ++j)
  2606. {
  2607. if (encodingTable[j] == c)
  2608. {
  2609. setBitRange (pos, 6, j);
  2610. pos += 6;
  2611. break;
  2612. }
  2613. }
  2614. }
  2615. return true;
  2616. }
  2617. END_JUCE_NAMESPACE
  2618. /********* End of inlined file: juce_MemoryBlock.cpp *********/
  2619. /********* Start of inlined file: juce_PropertySet.cpp *********/
  2620. BEGIN_JUCE_NAMESPACE
  2621. PropertySet::PropertySet (const bool ignoreCaseOfKeyNames) throw()
  2622. : properties (ignoreCaseOfKeyNames),
  2623. fallbackProperties (0),
  2624. ignoreCaseOfKeys (ignoreCaseOfKeyNames)
  2625. {
  2626. }
  2627. PropertySet::PropertySet (const PropertySet& other) throw()
  2628. : properties (other.properties),
  2629. fallbackProperties (other.fallbackProperties),
  2630. ignoreCaseOfKeys (other.ignoreCaseOfKeys)
  2631. {
  2632. }
  2633. const PropertySet& PropertySet::operator= (const PropertySet& other) throw()
  2634. {
  2635. properties = other.properties;
  2636. fallbackProperties = other.fallbackProperties;
  2637. ignoreCaseOfKeys = other.ignoreCaseOfKeys;
  2638. propertyChanged();
  2639. return *this;
  2640. }
  2641. PropertySet::~PropertySet()
  2642. {
  2643. }
  2644. void PropertySet::clear()
  2645. {
  2646. const ScopedLock sl (lock);
  2647. if (properties.size() > 0)
  2648. {
  2649. properties.clear();
  2650. propertyChanged();
  2651. }
  2652. }
  2653. const String PropertySet::getValue (const String& keyName,
  2654. const String& defaultValue) const throw()
  2655. {
  2656. const ScopedLock sl (lock);
  2657. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  2658. if (index >= 0)
  2659. return properties.getAllValues() [index];
  2660. return fallbackProperties != 0 ? fallbackProperties->getValue (keyName, defaultValue)
  2661. : defaultValue;
  2662. }
  2663. int PropertySet::getIntValue (const String& keyName,
  2664. const int defaultValue) const throw()
  2665. {
  2666. const ScopedLock sl (lock);
  2667. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  2668. if (index >= 0)
  2669. return properties.getAllValues() [index].getIntValue();
  2670. return fallbackProperties != 0 ? fallbackProperties->getIntValue (keyName, defaultValue)
  2671. : defaultValue;
  2672. }
  2673. double PropertySet::getDoubleValue (const String& keyName,
  2674. const double defaultValue) const throw()
  2675. {
  2676. const ScopedLock sl (lock);
  2677. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  2678. if (index >= 0)
  2679. return properties.getAllValues()[index].getDoubleValue();
  2680. return fallbackProperties != 0 ? fallbackProperties->getDoubleValue (keyName, defaultValue)
  2681. : defaultValue;
  2682. }
  2683. bool PropertySet::getBoolValue (const String& keyName,
  2684. const bool defaultValue) const throw()
  2685. {
  2686. const ScopedLock sl (lock);
  2687. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  2688. if (index >= 0)
  2689. return properties.getAllValues() [index].getIntValue() != 0;
  2690. return fallbackProperties != 0 ? fallbackProperties->getBoolValue (keyName, defaultValue)
  2691. : defaultValue;
  2692. }
  2693. XmlElement* PropertySet::getXmlValue (const String& keyName) const
  2694. {
  2695. XmlDocument doc (getValue (keyName));
  2696. return doc.getDocumentElement();
  2697. }
  2698. void PropertySet::setValue (const String& keyName,
  2699. const String& value) throw()
  2700. {
  2701. jassert (keyName.isNotEmpty()); // shouldn't use an empty key name!
  2702. if (keyName.isNotEmpty())
  2703. {
  2704. const ScopedLock sl (lock);
  2705. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  2706. if (index < 0 || properties.getAllValues() [index] != value)
  2707. {
  2708. properties.set (keyName, value);
  2709. propertyChanged();
  2710. }
  2711. }
  2712. }
  2713. void PropertySet::removeValue (const String& keyName) throw()
  2714. {
  2715. if (keyName.isNotEmpty())
  2716. {
  2717. const ScopedLock sl (lock);
  2718. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  2719. if (index >= 0)
  2720. {
  2721. properties.remove (keyName);
  2722. propertyChanged();
  2723. }
  2724. }
  2725. }
  2726. void PropertySet::setValue (const String& keyName, const tchar* const value) throw()
  2727. {
  2728. setValue (keyName, String (value));
  2729. }
  2730. void PropertySet::setValue (const String& keyName, const int value) throw()
  2731. {
  2732. setValue (keyName, String (value));
  2733. }
  2734. void PropertySet::setValue (const String& keyName, const double value) throw()
  2735. {
  2736. setValue (keyName, String (value));
  2737. }
  2738. void PropertySet::setValue (const String& keyName, const bool value) throw()
  2739. {
  2740. setValue (keyName, String ((value) ? T("1") : T("0")));
  2741. }
  2742. void PropertySet::setValue (const String& keyName, const XmlElement* const xml)
  2743. {
  2744. setValue (keyName, (xml == 0) ? String::empty
  2745. : xml->createDocument (String::empty, true));
  2746. }
  2747. bool PropertySet::containsKey (const String& keyName) const throw()
  2748. {
  2749. const ScopedLock sl (lock);
  2750. return properties.getAllKeys().contains (keyName, ignoreCaseOfKeys);
  2751. }
  2752. void PropertySet::setFallbackPropertySet (PropertySet* fallbackProperties_) throw()
  2753. {
  2754. const ScopedLock sl (lock);
  2755. fallbackProperties = fallbackProperties_;
  2756. }
  2757. XmlElement* PropertySet::createXml (const String& nodeName) const throw()
  2758. {
  2759. const ScopedLock sl (lock);
  2760. XmlElement* const xml = new XmlElement (nodeName);
  2761. for (int i = 0; i < properties.getAllKeys().size(); ++i)
  2762. {
  2763. XmlElement* const e = new XmlElement (T("VALUE"));
  2764. e->setAttribute (T("name"), properties.getAllKeys()[i]);
  2765. e->setAttribute (T("val"), properties.getAllValues()[i]);
  2766. xml->addChildElement (e);
  2767. }
  2768. return xml;
  2769. }
  2770. void PropertySet::restoreFromXml (const XmlElement& xml) throw()
  2771. {
  2772. const ScopedLock sl (lock);
  2773. clear();
  2774. forEachXmlChildElementWithTagName (xml, e, T("VALUE"))
  2775. {
  2776. if (e->hasAttribute (T("name"))
  2777. && e->hasAttribute (T("val")))
  2778. {
  2779. properties.set (e->getStringAttribute (T("name")),
  2780. e->getStringAttribute (T("val")));
  2781. }
  2782. }
  2783. if (properties.size() > 0)
  2784. propertyChanged();
  2785. }
  2786. void PropertySet::propertyChanged()
  2787. {
  2788. }
  2789. END_JUCE_NAMESPACE
  2790. /********* End of inlined file: juce_PropertySet.cpp *********/
  2791. /********* Start of inlined file: juce_Variant.cpp *********/
  2792. BEGIN_JUCE_NAMESPACE
  2793. var::var() throw()
  2794. : type (voidType)
  2795. {
  2796. value.doubleValue = 0;
  2797. }
  2798. void var::releaseValue() throw()
  2799. {
  2800. if (type == stringType)
  2801. delete value.stringValue;
  2802. else if (type == objectType && value.objectValue != 0)
  2803. value.objectValue->decReferenceCount();
  2804. }
  2805. var::~var()
  2806. {
  2807. releaseValue();
  2808. }
  2809. var::var (const var& valueToCopy) throw()
  2810. : type (valueToCopy.type),
  2811. value (valueToCopy.value)
  2812. {
  2813. if (type == stringType)
  2814. value.stringValue = new String (*(value.stringValue));
  2815. else if (type == objectType && value.objectValue != 0)
  2816. value.objectValue->incReferenceCount();
  2817. }
  2818. var::var (const int value_) throw()
  2819. : type (intType)
  2820. {
  2821. value.intValue = value_;
  2822. }
  2823. var::var (const bool value_) throw()
  2824. : type (boolType)
  2825. {
  2826. value.boolValue = value_;
  2827. }
  2828. var::var (const double value_) throw()
  2829. : type (doubleType)
  2830. {
  2831. value.doubleValue = value_;
  2832. }
  2833. var::var (const String& value_) throw()
  2834. : type (stringType)
  2835. {
  2836. value.stringValue = new String (value_);
  2837. }
  2838. var::var (const char* const value_) throw()
  2839. : type (stringType)
  2840. {
  2841. value.stringValue = new String (value_);
  2842. }
  2843. var::var (const juce_wchar* const value_) throw()
  2844. : type (stringType)
  2845. {
  2846. value.stringValue = new String (value_);
  2847. }
  2848. var::var (DynamicObject* const object) throw()
  2849. : type (objectType)
  2850. {
  2851. value.objectValue = object;
  2852. if (object != 0)
  2853. object->incReferenceCount();
  2854. }
  2855. var::var (MethodFunction method_) throw()
  2856. : type (methodType)
  2857. {
  2858. value.methodValue = method_;
  2859. }
  2860. const var& var::operator= (const var& valueToCopy) throw()
  2861. {
  2862. if (this != &valueToCopy)
  2863. {
  2864. if (type == stringType)
  2865. delete value.stringValue;
  2866. DynamicObject* const oldObject = getObject();
  2867. type = valueToCopy.type;
  2868. value = valueToCopy.value;
  2869. if (type == stringType)
  2870. value.stringValue = new String (*(value.stringValue));
  2871. else if (type == objectType && value.objectValue != 0)
  2872. value.objectValue->incReferenceCount();
  2873. if (oldObject != 0)
  2874. oldObject->decReferenceCount();
  2875. }
  2876. return *this;
  2877. }
  2878. const var& var::operator= (const int value_) throw()
  2879. {
  2880. releaseValue();
  2881. type = intType;
  2882. value.intValue = value_;
  2883. return *this;
  2884. }
  2885. const var& var::operator= (const bool value_) throw()
  2886. {
  2887. releaseValue();
  2888. type = boolType;
  2889. value.boolValue = value_;
  2890. return *this;
  2891. }
  2892. const var& var::operator= (const double value_) throw()
  2893. {
  2894. releaseValue();
  2895. type = doubleType;
  2896. value.doubleValue = value_;
  2897. return *this;
  2898. }
  2899. const var& var::operator= (const char* const value_) throw()
  2900. {
  2901. releaseValue();
  2902. type = stringType;
  2903. value.stringValue = new String (value_);
  2904. return *this;
  2905. }
  2906. const var& var::operator= (const juce_wchar* const value_) throw()
  2907. {
  2908. releaseValue();
  2909. type = stringType;
  2910. value.stringValue = new String (value_);
  2911. return *this;
  2912. }
  2913. const var& var::operator= (const String& value_) throw()
  2914. {
  2915. releaseValue();
  2916. type = stringType;
  2917. value.stringValue = new String (value_);
  2918. return *this;
  2919. }
  2920. const var& var::operator= (DynamicObject* const value_) throw()
  2921. {
  2922. value_->incReferenceCount();
  2923. releaseValue();
  2924. type = objectType;
  2925. value.objectValue = value_;
  2926. return *this;
  2927. }
  2928. const var& var::operator= (MethodFunction method_) throw()
  2929. {
  2930. releaseValue();
  2931. type = doubleType;
  2932. value.methodValue = method_;
  2933. return *this;
  2934. }
  2935. var::operator int() const throw()
  2936. {
  2937. switch (type)
  2938. {
  2939. case voidType:
  2940. case objectType: break;
  2941. case intType: return value.intValue;
  2942. case boolType: return value.boolValue ? 1 : 0;
  2943. case doubleType: return (int) value.doubleValue;
  2944. case stringType: return value.stringValue->getIntValue();
  2945. default: jassertfalse; break;
  2946. }
  2947. return 0;
  2948. }
  2949. var::operator bool() const throw()
  2950. {
  2951. switch (type)
  2952. {
  2953. case voidType: break;
  2954. case objectType: return value.objectValue != 0;
  2955. case intType: return value.intValue != 0;
  2956. case boolType: return value.boolValue;
  2957. case doubleType: return value.doubleValue != 0;
  2958. case stringType: return value.stringValue->getIntValue() != 0
  2959. || value.stringValue->trim().equalsIgnoreCase (T("true"))
  2960. || value.stringValue->trim().equalsIgnoreCase (T("yes"));
  2961. default: jassertfalse; break;
  2962. }
  2963. return false;
  2964. }
  2965. var::operator double() const throw()
  2966. {
  2967. switch (type)
  2968. {
  2969. case voidType:
  2970. case objectType: break;
  2971. case intType: return value.intValue;
  2972. case boolType: return value.boolValue ? 1.0 : 0.0;
  2973. case doubleType: return value.doubleValue;
  2974. case stringType: return value.stringValue->getDoubleValue();
  2975. default: jassertfalse; break;
  2976. }
  2977. return 0;
  2978. }
  2979. const String var::toString() const throw()
  2980. {
  2981. switch (type)
  2982. {
  2983. case voidType:
  2984. case objectType: return "Object 0x" + String::toHexString ((int) (pointer_sized_int) value.objectValue);
  2985. case intType: return String (value.intValue);
  2986. case boolType: return value.boolValue ? T("1") : T("0");
  2987. case doubleType: return String (value.doubleValue);
  2988. case stringType: return *(value.stringValue);
  2989. default: jassertfalse; break;
  2990. }
  2991. return String::empty;
  2992. }
  2993. var::operator const String() const throw()
  2994. {
  2995. return toString();
  2996. }
  2997. DynamicObject* var::getObject() const throw()
  2998. {
  2999. return type == objectType ? value.objectValue : 0;
  3000. }
  3001. const var var::operator[] (const var::identifier& propertyName) const throw()
  3002. {
  3003. if (type == objectType && value.objectValue != 0)
  3004. return value.objectValue->getProperty (propertyName);
  3005. return var();
  3006. }
  3007. const var var::invoke (const var::identifier& method, const var* arguments, int numArguments) const
  3008. {
  3009. if (type == objectType && value.objectValue != 0)
  3010. return value.objectValue->invokeMethod (method, arguments, numArguments);
  3011. return var();
  3012. }
  3013. const var var::invoke (const var& targetObject, const var* arguments, int numArguments) const
  3014. {
  3015. if (isMethod())
  3016. {
  3017. DynamicObject* const target = targetObject.getObject();
  3018. if (target != 0)
  3019. return (target->*(value.methodValue)) (arguments, numArguments);
  3020. }
  3021. return var();
  3022. }
  3023. const var var::call (const var::identifier& method) const
  3024. {
  3025. return invoke (method, 0, 0);
  3026. }
  3027. const var var::call (const var::identifier& method, const var& arg1) const
  3028. {
  3029. return invoke (method, &arg1, 1);
  3030. }
  3031. const var var::call (const var::identifier& method, const var& arg1, const var& arg2) const
  3032. {
  3033. var args[] = { arg1, arg2 };
  3034. return invoke (method, args, 2);
  3035. }
  3036. const var var::call (const var::identifier& method, const var& arg1, const var& arg2, const var& arg3)
  3037. {
  3038. var args[] = { arg1, arg2, arg3 };
  3039. return invoke (method, args, 3);
  3040. }
  3041. const var var::call (const var::identifier& method, const var& arg1, const var& arg2, const var& arg3, const var& arg4) const
  3042. {
  3043. var args[] = { arg1, arg2, arg3, arg4 };
  3044. return invoke (method, args, 4);
  3045. }
  3046. const var var::call (const var::identifier& method, const var& arg1, const var& arg2, const var& arg3, const var& arg4, const var& arg5) const
  3047. {
  3048. var args[] = { arg1, arg2, arg3, arg4, arg5 };
  3049. return invoke (method, args, 5);
  3050. }
  3051. var::identifier::identifier (const String& name_) throw()
  3052. : name (name_),
  3053. hashCode (name_.hashCode())
  3054. {
  3055. }
  3056. var::identifier::identifier (const char* const name_) throw()
  3057. : name (name_),
  3058. hashCode (name.hashCode())
  3059. {
  3060. }
  3061. var::identifier::~identifier() throw()
  3062. {
  3063. }
  3064. DynamicObject::DynamicObject()
  3065. {
  3066. }
  3067. DynamicObject::~DynamicObject()
  3068. {
  3069. }
  3070. bool DynamicObject::hasProperty (const var::identifier& propertyName) const
  3071. {
  3072. const int index = propertyIds.indexOf (propertyName.hashCode);
  3073. return index >= 0 && ! propertyValues.getUnchecked (index)->isMethod();
  3074. }
  3075. const var DynamicObject::getProperty (const var::identifier& propertyName) const
  3076. {
  3077. const int index = propertyIds.indexOf (propertyName.hashCode);
  3078. if (index >= 0)
  3079. return *propertyValues.getUnchecked (index);
  3080. return var();
  3081. }
  3082. void DynamicObject::setProperty (const var::identifier& propertyName, const var& newValue)
  3083. {
  3084. const int index = propertyIds.indexOf (propertyName.hashCode);
  3085. if (index >= 0)
  3086. {
  3087. propertyValues.set (index, new var (newValue));
  3088. }
  3089. else
  3090. {
  3091. propertyIds.add (propertyName.hashCode);
  3092. propertyValues.add (new var (newValue));
  3093. }
  3094. }
  3095. void DynamicObject::removeProperty (const var::identifier& propertyName)
  3096. {
  3097. const int index = propertyIds.indexOf (propertyName.hashCode);
  3098. if (index >= 0)
  3099. {
  3100. propertyIds.remove (index);
  3101. propertyValues.remove (index);
  3102. }
  3103. }
  3104. bool DynamicObject::hasMethod (const var::identifier& methodName) const
  3105. {
  3106. return getProperty (methodName).isMethod();
  3107. }
  3108. const var DynamicObject::invokeMethod (const var::identifier& methodName,
  3109. const var* parameters,
  3110. int numParameters)
  3111. {
  3112. return getProperty (methodName).invoke (this, parameters, numParameters);
  3113. }
  3114. void DynamicObject::setMethod (const var::identifier& name,
  3115. var::MethodFunction methodFunction)
  3116. {
  3117. setProperty (name, methodFunction);
  3118. }
  3119. void DynamicObject::clear()
  3120. {
  3121. propertyIds.clear();
  3122. propertyValues.clear();
  3123. }
  3124. END_JUCE_NAMESPACE
  3125. /********* End of inlined file: juce_Variant.cpp *********/
  3126. /********* Start of inlined file: juce_BlowFish.cpp *********/
  3127. BEGIN_JUCE_NAMESPACE
  3128. static const uint32 initialPValues [18] =
  3129. {
  3130. 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344,
  3131. 0xa4093822, 0x299f31d0, 0x082efa98, 0xec4e6c89,
  3132. 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c,
  3133. 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917,
  3134. 0x9216d5d9, 0x8979fb1b
  3135. };
  3136. static const uint32 initialSValues [4 * 256] =
  3137. {
  3138. 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7,
  3139. 0xb8e1afed, 0x6a267e96, 0xba7c9045, 0xf12c7f99,
  3140. 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16,
  3141. 0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e,
  3142. 0x0d95748f, 0x728eb658, 0x718bcd58, 0x82154aee,
  3143. 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013,
  3144. 0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef,
  3145. 0x8e79dcb0, 0x603a180e, 0x6c9e0e8b, 0xb01e8a3e,
  3146. 0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60,
  3147. 0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440,
  3148. 0x55ca396a, 0x2aab10b6, 0xb4cc5c34, 0x1141e8ce,
  3149. 0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a,
  3150. 0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e,
  3151. 0xafd6ba33, 0x6c24cf5c, 0x7a325381, 0x28958677,
  3152. 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193,
  3153. 0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032,
  3154. 0xef845d5d, 0xe98575b1, 0xdc262302, 0xeb651b88,
  3155. 0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239,
  3156. 0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e,
  3157. 0x21c66842, 0xf6e96c9a, 0x670c9c61, 0xabd388f0,
  3158. 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3,
  3159. 0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98,
  3160. 0xa1f1651d, 0x39af0176, 0x66ca593e, 0x82430e88,
  3161. 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe,
  3162. 0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6,
  3163. 0x4ed3aa62, 0x363f7706, 0x1bfedf72, 0x429b023d,
  3164. 0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b,
  3165. 0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7,
  3166. 0xe3fe501a, 0xb6794c3b, 0x976ce0bd, 0x04c006ba,
  3167. 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463,
  3168. 0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f,
  3169. 0x6dfc511f, 0x9b30952c, 0xcc814544, 0xaf5ebd09,
  3170. 0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3,
  3171. 0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb,
  3172. 0x5579c0bd, 0x1a60320a, 0xd6a100c6, 0x402c7279,
  3173. 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8,
  3174. 0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab,
  3175. 0x323db5fa, 0xfd238760, 0x53317b48, 0x3e00df82,
  3176. 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db,
  3177. 0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573,
  3178. 0x695b27b0, 0xbbca58c8, 0xe1ffa35d, 0xb8f011a0,
  3179. 0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b,
  3180. 0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790,
  3181. 0xe1ddf2da, 0xa4cb7e33, 0x62fb1341, 0xcee4c6e8,
  3182. 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4,
  3183. 0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0,
  3184. 0xd08ed1d0, 0xafc725e0, 0x8e3c5b2f, 0x8e7594b7,
  3185. 0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c,
  3186. 0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad,
  3187. 0x2f2f2218, 0xbe0e1777, 0xea752dfe, 0x8b021fa1,
  3188. 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299,
  3189. 0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9,
  3190. 0x165fa266, 0x80957705, 0x93cc7314, 0x211a1477,
  3191. 0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf,
  3192. 0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49,
  3193. 0x00250e2d, 0x2071b35e, 0x226800bb, 0x57b8e0af,
  3194. 0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa,
  3195. 0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5,
  3196. 0x83260376, 0x6295cfa9, 0x11c81968, 0x4e734a41,
  3197. 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915,
  3198. 0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400,
  3199. 0x08ba6fb5, 0x571be91f, 0xf296ec6b, 0x2a0dd915,
  3200. 0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664,
  3201. 0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a,
  3202. 0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623,
  3203. 0xad6ea6b0, 0x49a7df7d, 0x9cee60b8, 0x8fedb266,
  3204. 0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1,
  3205. 0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e,
  3206. 0x3f54989a, 0x5b429d65, 0x6b8fe4d6, 0x99f73fd6,
  3207. 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1,
  3208. 0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e,
  3209. 0x09686b3f, 0x3ebaefc9, 0x3c971814, 0x6b6a70a1,
  3210. 0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737,
  3211. 0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8,
  3212. 0xb03ada37, 0xf0500c0d, 0xf01c1f04, 0x0200b3ff,
  3213. 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd,
  3214. 0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701,
  3215. 0x3ae5e581, 0x37c2dadc, 0xc8b57634, 0x9af3dda7,
  3216. 0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41,
  3217. 0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331,
  3218. 0x4e548b38, 0x4f6db908, 0x6f420d03, 0xf60a04bf,
  3219. 0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af,
  3220. 0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e,
  3221. 0x5512721f, 0x2e6b7124, 0x501adde6, 0x9f84cd87,
  3222. 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c,
  3223. 0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2,
  3224. 0xef1c1847, 0x3215d908, 0xdd433b37, 0x24c2ba16,
  3225. 0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd,
  3226. 0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b,
  3227. 0x043556f1, 0xd7a3c76b, 0x3c11183b, 0x5924a509,
  3228. 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e,
  3229. 0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3,
  3230. 0x771fe71c, 0x4e3d06fa, 0x2965dcb9, 0x99e71d0f,
  3231. 0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a,
  3232. 0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4,
  3233. 0xf2f74ea7, 0x361d2b3d, 0x1939260f, 0x19c27960,
  3234. 0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66,
  3235. 0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28,
  3236. 0xc332ddef, 0xbe6c5aa5, 0x65582185, 0x68ab9802,
  3237. 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84,
  3238. 0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510,
  3239. 0x13cca830, 0xeb61bd96, 0x0334fe1e, 0xaa0363cf,
  3240. 0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14,
  3241. 0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e,
  3242. 0x648b1eaf, 0x19bdf0ca, 0xa02369b9, 0x655abb50,
  3243. 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7,
  3244. 0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8,
  3245. 0xf837889a, 0x97e32d77, 0x11ed935f, 0x16681281,
  3246. 0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99,
  3247. 0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696,
  3248. 0xcdb30aeb, 0x532e3054, 0x8fd948e4, 0x6dbc3128,
  3249. 0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73,
  3250. 0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0,
  3251. 0x45eee2b6, 0xa3aaabea, 0xdb6c4f15, 0xfacb4fd0,
  3252. 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105,
  3253. 0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250,
  3254. 0xcf62a1f2, 0x5b8d2646, 0xfc8883a0, 0xc1c7b6a3,
  3255. 0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285,
  3256. 0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00,
  3257. 0x58428d2a, 0x0c55f5ea, 0x1dadf43e, 0x233f7061,
  3258. 0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb,
  3259. 0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e,
  3260. 0xa6078084, 0x19f8509e, 0xe8efd855, 0x61d99735,
  3261. 0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc,
  3262. 0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9,
  3263. 0xdb73dbd3, 0x105588cd, 0x675fda79, 0xe3674340,
  3264. 0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20,
  3265. 0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7,
  3266. 0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934,
  3267. 0x411520f7, 0x7602d4f7, 0xbcf46b2e, 0xd4a20068,
  3268. 0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af,
  3269. 0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840,
  3270. 0x4d95fc1d, 0x96b591af, 0x70f4ddd3, 0x66a02f45,
  3271. 0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504,
  3272. 0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a,
  3273. 0x28507825, 0x530429f4, 0x0a2c86da, 0xe9b66dfb,
  3274. 0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee,
  3275. 0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6,
  3276. 0xaace1e7c, 0xd3375fec, 0xce78a399, 0x406b2a42,
  3277. 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b,
  3278. 0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2,
  3279. 0x3a6efa74, 0xdd5b4332, 0x6841e7f7, 0xca7820fb,
  3280. 0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527,
  3281. 0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b,
  3282. 0x55a867bc, 0xa1159a58, 0xcca92963, 0x99e1db33,
  3283. 0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c,
  3284. 0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3,
  3285. 0x95c11548, 0xe4c66d22, 0x48c1133f, 0xc70f86dc,
  3286. 0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17,
  3287. 0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564,
  3288. 0x257b7834, 0x602a9c60, 0xdff8e8a3, 0x1f636c1b,
  3289. 0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115,
  3290. 0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922,
  3291. 0x85b2a20e, 0xe6ba0d99, 0xde720c8c, 0x2da2f728,
  3292. 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0,
  3293. 0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e,
  3294. 0x0a476341, 0x992eff74, 0x3a6f6eab, 0xf4f8fd37,
  3295. 0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d,
  3296. 0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804,
  3297. 0xf1290dc7, 0xcc00ffa3, 0xb5390f92, 0x690fed0b,
  3298. 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3,
  3299. 0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb,
  3300. 0x37392eb3, 0xcc115979, 0x8026e297, 0xf42e312d,
  3301. 0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c,
  3302. 0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350,
  3303. 0x1a6b1018, 0x11caedfa, 0x3d25bdd8, 0xe2e1c3c9,
  3304. 0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a,
  3305. 0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe,
  3306. 0x9dbc8057, 0xf0f7c086, 0x60787bf8, 0x6003604d,
  3307. 0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc,
  3308. 0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f,
  3309. 0x77a057be, 0xbde8ae24, 0x55464299, 0xbf582e61,
  3310. 0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2,
  3311. 0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9,
  3312. 0x7aeb2661, 0x8b1ddf84, 0x846a0e79, 0x915f95e2,
  3313. 0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c,
  3314. 0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e,
  3315. 0xb77f19b6, 0xe0a9dc09, 0x662d09a1, 0xc4324633,
  3316. 0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10,
  3317. 0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169,
  3318. 0xdcb7da83, 0x573906fe, 0xa1e2ce9b, 0x4fcd7f52,
  3319. 0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027,
  3320. 0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5,
  3321. 0xf0177a28, 0xc0f586e0, 0x006058aa, 0x30dc7d62,
  3322. 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634,
  3323. 0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76,
  3324. 0x6f05e409, 0x4b7c0188, 0x39720a3d, 0x7c927c24,
  3325. 0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc,
  3326. 0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4,
  3327. 0x1e50ef5e, 0xb161e6f8, 0xa28514d9, 0x6c51133c,
  3328. 0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837,
  3329. 0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0,
  3330. 0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b,
  3331. 0x5cb0679e, 0x4fa33742, 0xd3822740, 0x99bc9bbe,
  3332. 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b,
  3333. 0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4,
  3334. 0x5748ab2f, 0xbc946e79, 0xc6a376d2, 0x6549c2c8,
  3335. 0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6,
  3336. 0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304,
  3337. 0xa1fad5f0, 0x6a2d519a, 0x63ef8ce2, 0x9a86ee22,
  3338. 0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4,
  3339. 0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6,
  3340. 0x2826a2f9, 0xa73a3ae1, 0x4ba99586, 0xef5562e9,
  3341. 0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59,
  3342. 0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593,
  3343. 0xe990fd5a, 0x9e34d797, 0x2cf0b7d9, 0x022b8b51,
  3344. 0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28,
  3345. 0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c,
  3346. 0xe029ac71, 0xe019a5e6, 0x47b0acfd, 0xed93fa9b,
  3347. 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28,
  3348. 0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c,
  3349. 0x15056dd4, 0x88f46dba, 0x03a16125, 0x0564f0bd,
  3350. 0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a,
  3351. 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319,
  3352. 0x7533d928, 0xb155fdf5, 0x03563482, 0x8aba3cbb,
  3353. 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f,
  3354. 0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991,
  3355. 0xea7a90c2, 0xfb3e7bce, 0x5121ce64, 0x774fbe32,
  3356. 0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680,
  3357. 0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166,
  3358. 0xb39a460a, 0x6445c0dd, 0x586cdecf, 0x1c20c8ae,
  3359. 0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb,
  3360. 0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5,
  3361. 0x72eacea8, 0xfa6484bb, 0x8d6612ae, 0xbf3c6f47,
  3362. 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370,
  3363. 0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d,
  3364. 0x4040cb08, 0x4eb4e2cc, 0x34d2466a, 0x0115af84,
  3365. 0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048,
  3366. 0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8,
  3367. 0x611560b1, 0xe7933fdc, 0xbb3a792b, 0x344525bd,
  3368. 0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9,
  3369. 0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7,
  3370. 0x1a908749, 0xd44fbd9a, 0xd0dadecb, 0xd50ada38,
  3371. 0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f,
  3372. 0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c,
  3373. 0xbf97222c, 0x15e6fc2a, 0x0f91fc71, 0x9b941525,
  3374. 0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1,
  3375. 0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442,
  3376. 0xe0ec6e0e, 0x1698db3b, 0x4c98a0be, 0x3278e964,
  3377. 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e,
  3378. 0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8,
  3379. 0xdf359f8d, 0x9b992f2e, 0xe60b6f47, 0x0fe3f11d,
  3380. 0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f,
  3381. 0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299,
  3382. 0xf523f357, 0xa6327623, 0x93a83531, 0x56cccd02,
  3383. 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc,
  3384. 0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614,
  3385. 0xe6c6c7bd, 0x327a140a, 0x45e1d006, 0xc3f27b9a,
  3386. 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6,
  3387. 0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b,
  3388. 0x53113ec0, 0x1640e3d3, 0x38abbd60, 0x2547adf0,
  3389. 0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060,
  3390. 0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e,
  3391. 0x1948c25c, 0x02fb8a8c, 0x01c36ae4, 0xd6ebe1f9,
  3392. 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f,
  3393. 0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6
  3394. };
  3395. BlowFish::BlowFish (const uint8* keyData, int keyBytes)
  3396. {
  3397. memcpy (p, initialPValues, sizeof (p));
  3398. int i, j;
  3399. for (i = 4; --i >= 0;)
  3400. {
  3401. s[i] = (uint32*) juce_malloc (256 * sizeof (uint32));
  3402. memcpy (s[i], initialSValues + i * 256, 256 * sizeof (uint32));
  3403. }
  3404. j = 0;
  3405. for (i = 0; i < 18; ++i)
  3406. {
  3407. uint32 d = 0;
  3408. for (int k = 0; k < 4; ++k)
  3409. {
  3410. d = (d << 8) | keyData[j];
  3411. if (++j >= keyBytes)
  3412. j = 0;
  3413. }
  3414. p[i] = initialPValues[i] ^ d;
  3415. }
  3416. uint32 l = 0, r = 0;
  3417. for (i = 0; i < 18; i += 2)
  3418. {
  3419. encrypt (l, r);
  3420. p[i] = l;
  3421. p[i + 1] = r;
  3422. }
  3423. for (i = 0; i < 4; ++i)
  3424. {
  3425. for (j = 0; j < 256; j += 2)
  3426. {
  3427. encrypt (l, r);
  3428. s[i][j] = l;
  3429. s[i][j + 1] = r;
  3430. }
  3431. }
  3432. }
  3433. BlowFish::BlowFish (const BlowFish& other)
  3434. {
  3435. for (int i = 4; --i >= 0;)
  3436. s[i] = (uint32*) juce_malloc (256 * sizeof (uint32));
  3437. operator= (other);
  3438. }
  3439. const BlowFish& BlowFish::operator= (const BlowFish& other)
  3440. {
  3441. memcpy (p, other.p, sizeof (p));
  3442. for (int i = 4; --i >= 0;)
  3443. memcpy (s[i], other.s[i], 256 * sizeof (uint32));
  3444. return *this;
  3445. }
  3446. BlowFish::~BlowFish()
  3447. {
  3448. for (int i = 4; --i >= 0;)
  3449. juce_free (s[i]);
  3450. }
  3451. uint32 BlowFish::F (uint32 x) const
  3452. {
  3453. uint16 a, b, c, d;
  3454. uint32 y;
  3455. d = (uint16) (x & 0xff);
  3456. x >>= 8;
  3457. c = (uint16) (x & 0xff);
  3458. x >>= 8;
  3459. b = (uint16) (x & 0xff);
  3460. x >>= 8;
  3461. a = (uint16) (x & 0xff);
  3462. y = s[0][a] + s[1][b];
  3463. y = y ^ s[2][c];
  3464. y = y + s[3][d];
  3465. return y;
  3466. }
  3467. void BlowFish::encrypt (uint32& data1,
  3468. uint32& data2) const
  3469. {
  3470. uint32 l = data1;
  3471. uint32 r = data2;
  3472. for (int i = 0; i < 16; ++i)
  3473. {
  3474. l = l ^ p[i];
  3475. r = F (l) ^ r;
  3476. const uint32 temp = l;
  3477. l = r;
  3478. r = temp;
  3479. }
  3480. const uint32 temp = l;
  3481. l = r;
  3482. r = temp;
  3483. r = r ^ p[16];
  3484. l = l ^ p[17];
  3485. data1 = l;
  3486. data2 = r;
  3487. }
  3488. void BlowFish::decrypt (uint32& data1,
  3489. uint32& data2) const
  3490. {
  3491. uint32 l = data1;
  3492. uint32 r = data2;
  3493. for (int i = 17; i > 1; --i)
  3494. {
  3495. l =l ^ p[i];
  3496. r = F (l) ^ r;
  3497. const uint32 temp = l;
  3498. l = r;
  3499. r = temp;
  3500. }
  3501. const uint32 temp = l;
  3502. l = r;
  3503. r = temp;
  3504. r = r ^ p[1];
  3505. l = l ^ p[0];
  3506. data1 = l;
  3507. data2 = r;
  3508. }
  3509. END_JUCE_NAMESPACE
  3510. /********* End of inlined file: juce_BlowFish.cpp *********/
  3511. /********* Start of inlined file: juce_MD5.cpp *********/
  3512. BEGIN_JUCE_NAMESPACE
  3513. MD5::MD5()
  3514. {
  3515. zeromem (result, sizeof (result));
  3516. }
  3517. MD5::MD5 (const MD5& other)
  3518. {
  3519. memcpy (result, other.result, sizeof (result));
  3520. }
  3521. const MD5& MD5::operator= (const MD5& other)
  3522. {
  3523. memcpy (result, other.result, sizeof (result));
  3524. return *this;
  3525. }
  3526. MD5::MD5 (const MemoryBlock& data)
  3527. {
  3528. ProcessContext context;
  3529. context.processBlock ((const uint8*) data.getData(), data.getSize());
  3530. context.finish (result);
  3531. }
  3532. MD5::MD5 (const char* data, const int numBytes)
  3533. {
  3534. ProcessContext context;
  3535. context.processBlock ((const uint8*) data, numBytes);
  3536. context.finish (result);
  3537. }
  3538. MD5::MD5 (const String& text)
  3539. {
  3540. ProcessContext context;
  3541. const int len = text.length();
  3542. const juce_wchar* const t = text;
  3543. for (int i = 0; i < len; ++i)
  3544. {
  3545. // force the string into integer-sized unicode characters, to try to make it
  3546. // get the same results on all platforms + compilers.
  3547. uint32 unicodeChar = (uint32) t[i];
  3548. swapIfBigEndian (unicodeChar);
  3549. context.processBlock ((const uint8*) &unicodeChar,
  3550. sizeof (unicodeChar));
  3551. }
  3552. context.finish (result);
  3553. }
  3554. void MD5::processStream (InputStream& input, int numBytesToRead)
  3555. {
  3556. ProcessContext context;
  3557. if (numBytesToRead < 0)
  3558. numBytesToRead = INT_MAX;
  3559. while (numBytesToRead > 0)
  3560. {
  3561. char tempBuffer [512];
  3562. const int bytesRead = input.read (tempBuffer, jmin (numBytesToRead, sizeof (tempBuffer)));
  3563. if (bytesRead <= 0)
  3564. break;
  3565. numBytesToRead -= bytesRead;
  3566. context.processBlock ((const uint8*) tempBuffer, bytesRead);
  3567. }
  3568. context.finish (result);
  3569. }
  3570. MD5::MD5 (InputStream& input, int numBytesToRead)
  3571. {
  3572. processStream (input, numBytesToRead);
  3573. }
  3574. MD5::MD5 (const File& file)
  3575. {
  3576. FileInputStream* const fin = file.createInputStream();
  3577. if (fin != 0)
  3578. {
  3579. processStream (*fin, -1);
  3580. delete fin;
  3581. }
  3582. else
  3583. {
  3584. zeromem (result, sizeof (result));
  3585. }
  3586. }
  3587. MD5::~MD5()
  3588. {
  3589. }
  3590. MD5::ProcessContext::ProcessContext()
  3591. {
  3592. state[0] = 0x67452301;
  3593. state[1] = 0xefcdab89;
  3594. state[2] = 0x98badcfe;
  3595. state[3] = 0x10325476;
  3596. count[0] = 0;
  3597. count[1] = 0;
  3598. }
  3599. void MD5::ProcessContext::processBlock (const uint8* const data, int dataSize)
  3600. {
  3601. int bufferPos = ((count[0] >> 3) & 0x3F);
  3602. count[0] += (dataSize << 3);
  3603. if (count[0] < ((uint32) dataSize << 3))
  3604. count[1]++;
  3605. count[1] += (dataSize >> 29);
  3606. const int spaceLeft = 64 - bufferPos;
  3607. int i = 0;
  3608. if (dataSize >= spaceLeft)
  3609. {
  3610. memcpy (buffer + bufferPos, data, spaceLeft);
  3611. transform (buffer);
  3612. i = spaceLeft;
  3613. while (i < dataSize - 63)
  3614. {
  3615. transform (data + i);
  3616. i += 64;
  3617. }
  3618. bufferPos = 0;
  3619. }
  3620. memcpy (buffer + bufferPos, data + i, dataSize - i);
  3621. }
  3622. static void encode (uint8* const output,
  3623. const uint32* const input,
  3624. const int numBytes)
  3625. {
  3626. uint32* const o = (uint32*) output;
  3627. for (int i = 0; i < (numBytes >> 2); ++i)
  3628. o[i] = swapIfBigEndian (input [i]);
  3629. }
  3630. static void decode (uint32* const output,
  3631. const uint8* const input,
  3632. const int numBytes)
  3633. {
  3634. for (int i = 0; i < (numBytes >> 2); ++i)
  3635. output[i] = littleEndianInt ((const char*) input + (i << 2));
  3636. }
  3637. void MD5::ProcessContext::finish (uint8* const result)
  3638. {
  3639. unsigned char encodedLength[8];
  3640. encode (encodedLength, count, 8);
  3641. // Pad out to 56 mod 64.
  3642. const int index = (uint32) ((count[0] >> 3) & 0x3f);
  3643. const int paddingLength = (index < 56) ? (56 - index)
  3644. : (120 - index);
  3645. uint8 paddingBuffer [64];
  3646. zeromem (paddingBuffer, paddingLength);
  3647. paddingBuffer [0] = 0x80;
  3648. processBlock (paddingBuffer, paddingLength);
  3649. processBlock (encodedLength, 8);
  3650. encode (result, state, 16);
  3651. zeromem (buffer, sizeof (buffer));
  3652. }
  3653. #define S11 7
  3654. #define S12 12
  3655. #define S13 17
  3656. #define S14 22
  3657. #define S21 5
  3658. #define S22 9
  3659. #define S23 14
  3660. #define S24 20
  3661. #define S31 4
  3662. #define S32 11
  3663. #define S33 16
  3664. #define S34 23
  3665. #define S41 6
  3666. #define S42 10
  3667. #define S43 15
  3668. #define S44 21
  3669. static inline uint32 F (const uint32 x, const uint32 y, const uint32 z) { return (x & y) | (~x & z); }
  3670. static inline uint32 G (const uint32 x, const uint32 y, const uint32 z) { return (x & z) | (y & ~z); }
  3671. static inline uint32 H (const uint32 x, const uint32 y, const uint32 z) { return x ^ y ^ z; }
  3672. static inline uint32 I (const uint32 x, const uint32 y, const uint32 z) { return y ^ (x | ~z); }
  3673. static inline uint32 rotateLeft (const uint32 x, const uint32 n) { return (x << n) | (x >> (32 - n)); }
  3674. static inline void FF (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac)
  3675. {
  3676. a += F (b, c, d) + x + ac;
  3677. a = rotateLeft (a, s) + b;
  3678. }
  3679. static inline void GG (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac)
  3680. {
  3681. a += G (b, c, d) + x + ac;
  3682. a = rotateLeft (a, s) + b;
  3683. }
  3684. static inline void HH (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac)
  3685. {
  3686. a += H (b, c, d) + x + ac;
  3687. a = rotateLeft (a, s) + b;
  3688. }
  3689. static inline void II (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac)
  3690. {
  3691. a += I (b, c, d) + x + ac;
  3692. a = rotateLeft (a, s) + b;
  3693. }
  3694. void MD5::ProcessContext::transform (const uint8* const buffer)
  3695. {
  3696. uint32 a = state[0];
  3697. uint32 b = state[1];
  3698. uint32 c = state[2];
  3699. uint32 d = state[3];
  3700. uint32 x[16];
  3701. decode (x, buffer, 64);
  3702. FF (a, b, c, d, x[ 0], S11, 0xd76aa478); /* 1 */
  3703. FF (d, a, b, c, x[ 1], S12, 0xe8c7b756); /* 2 */
  3704. FF (c, d, a, b, x[ 2], S13, 0x242070db); /* 3 */
  3705. FF (b, c, d, a, x[ 3], S14, 0xc1bdceee); /* 4 */
  3706. FF (a, b, c, d, x[ 4], S11, 0xf57c0faf); /* 5 */
  3707. FF (d, a, b, c, x[ 5], S12, 0x4787c62a); /* 6 */
  3708. FF (c, d, a, b, x[ 6], S13, 0xa8304613); /* 7 */
  3709. FF (b, c, d, a, x[ 7], S14, 0xfd469501); /* 8 */
  3710. FF (a, b, c, d, x[ 8], S11, 0x698098d8); /* 9 */
  3711. FF (d, a, b, c, x[ 9], S12, 0x8b44f7af); /* 10 */
  3712. FF (c, d, a, b, x[10], S13, 0xffff5bb1); /* 11 */
  3713. FF (b, c, d, a, x[11], S14, 0x895cd7be); /* 12 */
  3714. FF (a, b, c, d, x[12], S11, 0x6b901122); /* 13 */
  3715. FF (d, a, b, c, x[13], S12, 0xfd987193); /* 14 */
  3716. FF (c, d, a, b, x[14], S13, 0xa679438e); /* 15 */
  3717. FF (b, c, d, a, x[15], S14, 0x49b40821); /* 16 */
  3718. GG (a, b, c, d, x[ 1], S21, 0xf61e2562); /* 17 */
  3719. GG (d, a, b, c, x[ 6], S22, 0xc040b340); /* 18 */
  3720. GG (c, d, a, b, x[11], S23, 0x265e5a51); /* 19 */
  3721. GG (b, c, d, a, x[ 0], S24, 0xe9b6c7aa); /* 20 */
  3722. GG (a, b, c, d, x[ 5], S21, 0xd62f105d); /* 21 */
  3723. GG (d, a, b, c, x[10], S22, 0x2441453); /* 22 */
  3724. GG (c, d, a, b, x[15], S23, 0xd8a1e681); /* 23 */
  3725. GG (b, c, d, a, x[ 4], S24, 0xe7d3fbc8); /* 24 */
  3726. GG (a, b, c, d, x[ 9], S21, 0x21e1cde6); /* 25 */
  3727. GG (d, a, b, c, x[14], S22, 0xc33707d6); /* 26 */
  3728. GG (c, d, a, b, x[ 3], S23, 0xf4d50d87); /* 27 */
  3729. GG (b, c, d, a, x[ 8], S24, 0x455a14ed); /* 28 */
  3730. GG (a, b, c, d, x[13], S21, 0xa9e3e905); /* 29 */
  3731. GG (d, a, b, c, x[ 2], S22, 0xfcefa3f8); /* 30 */
  3732. GG (c, d, a, b, x[ 7], S23, 0x676f02d9); /* 31 */
  3733. GG (b, c, d, a, x[12], S24, 0x8d2a4c8a); /* 32 */
  3734. HH (a, b, c, d, x[ 5], S31, 0xfffa3942); /* 33 */
  3735. HH (d, a, b, c, x[ 8], S32, 0x8771f681); /* 34 */
  3736. HH (c, d, a, b, x[11], S33, 0x6d9d6122); /* 35 */
  3737. HH (b, c, d, a, x[14], S34, 0xfde5380c); /* 36 */
  3738. HH (a, b, c, d, x[ 1], S31, 0xa4beea44); /* 37 */
  3739. HH (d, a, b, c, x[ 4], S32, 0x4bdecfa9); /* 38 */
  3740. HH (c, d, a, b, x[ 7], S33, 0xf6bb4b60); /* 39 */
  3741. HH (b, c, d, a, x[10], S34, 0xbebfbc70); /* 40 */
  3742. HH (a, b, c, d, x[13], S31, 0x289b7ec6); /* 41 */
  3743. HH (d, a, b, c, x[ 0], S32, 0xeaa127fa); /* 42 */
  3744. HH (c, d, a, b, x[ 3], S33, 0xd4ef3085); /* 43 */
  3745. HH (b, c, d, a, x[ 6], S34, 0x4881d05); /* 44 */
  3746. HH (a, b, c, d, x[ 9], S31, 0xd9d4d039); /* 45 */
  3747. HH (d, a, b, c, x[12], S32, 0xe6db99e5); /* 46 */
  3748. HH (c, d, a, b, x[15], S33, 0x1fa27cf8); /* 47 */
  3749. HH (b, c, d, a, x[ 2], S34, 0xc4ac5665); /* 48 */
  3750. II (a, b, c, d, x[ 0], S41, 0xf4292244); /* 49 */
  3751. II (d, a, b, c, x[ 7], S42, 0x432aff97); /* 50 */
  3752. II (c, d, a, b, x[14], S43, 0xab9423a7); /* 51 */
  3753. II (b, c, d, a, x[ 5], S44, 0xfc93a039); /* 52 */
  3754. II (a, b, c, d, x[12], S41, 0x655b59c3); /* 53 */
  3755. II (d, a, b, c, x[ 3], S42, 0x8f0ccc92); /* 54 */
  3756. II (c, d, a, b, x[10], S43, 0xffeff47d); /* 55 */
  3757. II (b, c, d, a, x[ 1], S44, 0x85845dd1); /* 56 */
  3758. II (a, b, c, d, x[ 8], S41, 0x6fa87e4f); /* 57 */
  3759. II (d, a, b, c, x[15], S42, 0xfe2ce6e0); /* 58 */
  3760. II (c, d, a, b, x[ 6], S43, 0xa3014314); /* 59 */
  3761. II (b, c, d, a, x[13], S44, 0x4e0811a1); /* 60 */
  3762. II (a, b, c, d, x[ 4], S41, 0xf7537e82); /* 61 */
  3763. II (d, a, b, c, x[11], S42, 0xbd3af235); /* 62 */
  3764. II (c, d, a, b, x[ 2], S43, 0x2ad7d2bb); /* 63 */
  3765. II (b, c, d, a, x[ 9], S44, 0xeb86d391); /* 64 */
  3766. state[0] += a;
  3767. state[1] += b;
  3768. state[2] += c;
  3769. state[3] += d;
  3770. zeromem (x, sizeof (x));
  3771. }
  3772. const MemoryBlock MD5::getRawChecksumData() const
  3773. {
  3774. return MemoryBlock (result, 16);
  3775. }
  3776. const String MD5::toHexString() const
  3777. {
  3778. return String::toHexString (result, 16, 0);
  3779. }
  3780. bool MD5::operator== (const MD5& other) const
  3781. {
  3782. return memcmp (result, other.result, 16) == 0;
  3783. }
  3784. bool MD5::operator!= (const MD5& other) const
  3785. {
  3786. return ! operator== (other);
  3787. }
  3788. END_JUCE_NAMESPACE
  3789. /********* End of inlined file: juce_MD5.cpp *********/
  3790. /********* Start of inlined file: juce_Primes.cpp *********/
  3791. BEGIN_JUCE_NAMESPACE
  3792. static void createSmallSieve (const int numBits, BitArray& result) throw()
  3793. {
  3794. result.setBit (numBits);
  3795. result.clearBit (numBits); // to enlarge the array
  3796. result.setBit (0);
  3797. int n = 2;
  3798. do
  3799. {
  3800. for (int i = n + n; i < numBits; i += n)
  3801. result.setBit (i);
  3802. n = result.findNextClearBit (n + 1);
  3803. }
  3804. while (n <= (numBits >> 1));
  3805. }
  3806. static void bigSieve (const BitArray& base,
  3807. const int numBits,
  3808. BitArray& result,
  3809. const BitArray& smallSieve,
  3810. const int smallSieveSize) throw()
  3811. {
  3812. jassert (! base[0]); // must be even!
  3813. result.setBit (numBits);
  3814. result.clearBit (numBits); // to enlarge the array
  3815. int index = smallSieve.findNextClearBit (0);
  3816. do
  3817. {
  3818. const int prime = (index << 1) + 1;
  3819. BitArray r (base);
  3820. BitArray remainder;
  3821. r.divideBy (prime, remainder);
  3822. int i = prime - remainder.getBitRangeAsInt (0, 32);
  3823. if (r.isEmpty())
  3824. i += prime;
  3825. if ((i & 1) == 0)
  3826. i += prime;
  3827. i = (i - 1) >> 1;
  3828. while (i < numBits)
  3829. {
  3830. result.setBit (i);
  3831. i += prime;
  3832. }
  3833. index = smallSieve.findNextClearBit (index + 1);
  3834. }
  3835. while (index < smallSieveSize);
  3836. }
  3837. static bool findCandidate (const BitArray& base,
  3838. const BitArray& sieve,
  3839. const int numBits,
  3840. BitArray& result,
  3841. const int certainty) throw()
  3842. {
  3843. for (int i = 0; i < numBits; ++i)
  3844. {
  3845. if (! sieve[i])
  3846. {
  3847. result = base;
  3848. result.add (BitArray ((unsigned int) ((i << 1) + 1)));
  3849. if (Primes::isProbablyPrime (result, certainty))
  3850. return true;
  3851. }
  3852. }
  3853. return false;
  3854. }
  3855. const BitArray Primes::createProbablePrime (const int bitLength,
  3856. const int certainty,
  3857. const int* randomSeeds,
  3858. int numRandomSeeds) throw()
  3859. {
  3860. int defaultSeeds [16];
  3861. if (numRandomSeeds <= 0)
  3862. {
  3863. randomSeeds = defaultSeeds;
  3864. numRandomSeeds = numElementsInArray (defaultSeeds);
  3865. Random r (0);
  3866. for (int j = 10; --j >= 0;)
  3867. {
  3868. r.setSeedRandomly();
  3869. for (int i = numRandomSeeds; --i >= 0;)
  3870. defaultSeeds[i] ^= r.nextInt() ^ Random::getSystemRandom().nextInt();
  3871. }
  3872. }
  3873. BitArray smallSieve;
  3874. const int smallSieveSize = 15000;
  3875. createSmallSieve (smallSieveSize, smallSieve);
  3876. BitArray p;
  3877. for (int i = numRandomSeeds; --i >= 0;)
  3878. {
  3879. BitArray p2;
  3880. Random r (randomSeeds[i]);
  3881. r.fillBitsRandomly (p2, 0, bitLength);
  3882. p.xorWith (p2);
  3883. }
  3884. p.setBit (bitLength - 1);
  3885. p.clearBit (0);
  3886. const int searchLen = jmax (1024, (bitLength / 20) * 64);
  3887. while (p.getHighestBit() < bitLength)
  3888. {
  3889. p.add (2 * searchLen);
  3890. BitArray sieve;
  3891. bigSieve (p, searchLen, sieve,
  3892. smallSieve, smallSieveSize);
  3893. BitArray candidate;
  3894. if (findCandidate (p, sieve, searchLen, candidate, certainty))
  3895. return candidate;
  3896. }
  3897. jassertfalse
  3898. return BitArray();
  3899. }
  3900. static bool passesMillerRabin (const BitArray& n, int iterations) throw()
  3901. {
  3902. const BitArray one (1);
  3903. const BitArray two (2);
  3904. BitArray nMinusOne (n);
  3905. nMinusOne.subtract (one);
  3906. BitArray d (nMinusOne);
  3907. const int s = d.findNextSetBit (0);
  3908. d.shiftBits (-s);
  3909. BitArray smallPrimes;
  3910. int numBitsInSmallPrimes = 0;
  3911. for (;;)
  3912. {
  3913. numBitsInSmallPrimes += 256;
  3914. createSmallSieve (numBitsInSmallPrimes, smallPrimes);
  3915. const int numPrimesFound = numBitsInSmallPrimes - smallPrimes.countNumberOfSetBits();
  3916. if (numPrimesFound > iterations + 1)
  3917. break;
  3918. }
  3919. int smallPrime = 2;
  3920. while (--iterations >= 0)
  3921. {
  3922. smallPrime = smallPrimes.findNextClearBit (smallPrime + 1);
  3923. BitArray r (smallPrime);
  3924. //r.createRandomNumber (nMinusOne);
  3925. r.exponentModulo (d, n);
  3926. if (! (r == one || r == nMinusOne))
  3927. {
  3928. for (int j = 0; j < s; ++j)
  3929. {
  3930. r.exponentModulo (two, n);
  3931. if (r == nMinusOne)
  3932. break;
  3933. }
  3934. if (r != nMinusOne)
  3935. return false;
  3936. }
  3937. }
  3938. return true;
  3939. }
  3940. bool Primes::isProbablyPrime (const BitArray& number,
  3941. const int certainty) throw()
  3942. {
  3943. if (! number[0])
  3944. return false;
  3945. if (number.getHighestBit() <= 10)
  3946. {
  3947. const int num = number.getBitRangeAsInt (0, 10);
  3948. for (int i = num / 2; --i > 1;)
  3949. if (num % i == 0)
  3950. return false;
  3951. return true;
  3952. }
  3953. else
  3954. {
  3955. const BitArray screen (2 * 3 * 5 * 7 * 11 * 13 * 17 * 19 * 23);
  3956. if (number.findGreatestCommonDivisor (screen) != BitArray (1))
  3957. return false;
  3958. return passesMillerRabin (number, certainty);
  3959. }
  3960. }
  3961. END_JUCE_NAMESPACE
  3962. /********* End of inlined file: juce_Primes.cpp *********/
  3963. /********* Start of inlined file: juce_RSAKey.cpp *********/
  3964. BEGIN_JUCE_NAMESPACE
  3965. RSAKey::RSAKey() throw()
  3966. {
  3967. }
  3968. RSAKey::RSAKey (const String& s) throw()
  3969. {
  3970. if (s.containsChar (T(',')))
  3971. {
  3972. part1.parseString (s.upToFirstOccurrenceOf (T(","), false, false), 16);
  3973. part2.parseString (s.fromFirstOccurrenceOf (T(","), false, false), 16);
  3974. }
  3975. else
  3976. {
  3977. // the string needs to be two hex numbers, comma-separated..
  3978. jassertfalse;
  3979. }
  3980. }
  3981. RSAKey::~RSAKey() throw()
  3982. {
  3983. }
  3984. const String RSAKey::toString() const throw()
  3985. {
  3986. return part1.toString (16) + T(",") + part2.toString (16);
  3987. }
  3988. bool RSAKey::applyToValue (BitArray& value) const throw()
  3989. {
  3990. if (part1.isEmpty() || part2.isEmpty()
  3991. || value.compare (0) <= 0)
  3992. {
  3993. jassertfalse // using an uninitialised key
  3994. value.clear();
  3995. return false;
  3996. }
  3997. BitArray result;
  3998. while (! value.isEmpty())
  3999. {
  4000. result.multiplyBy (part2);
  4001. BitArray remainder;
  4002. value.divideBy (part2, remainder);
  4003. remainder.exponentModulo (part1, part2);
  4004. result.add (remainder);
  4005. }
  4006. value = result;
  4007. return true;
  4008. }
  4009. static const BitArray findBestCommonDivisor (const BitArray& p,
  4010. const BitArray& q) throw()
  4011. {
  4012. const BitArray one (1);
  4013. // try 3, 5, 9, 17, etc first because these only contain 2 bits and so
  4014. // are fast to divide + multiply
  4015. for (int i = 2; i <= 65536; i *= 2)
  4016. {
  4017. const BitArray e (1 + i);
  4018. if (e.findGreatestCommonDivisor (p) == one
  4019. && e.findGreatestCommonDivisor (q) == one)
  4020. {
  4021. return e;
  4022. }
  4023. }
  4024. BitArray e (4);
  4025. while (! (e.findGreatestCommonDivisor (p) == one
  4026. && e.findGreatestCommonDivisor (q) == one))
  4027. {
  4028. e.add (one);
  4029. }
  4030. return e;
  4031. }
  4032. void RSAKey::createKeyPair (RSAKey& publicKey,
  4033. RSAKey& privateKey,
  4034. const int numBits,
  4035. const int* randomSeeds,
  4036. const int numRandomSeeds) throw()
  4037. {
  4038. jassert (numBits > 16); // not much point using less than this..
  4039. BitArray p (Primes::createProbablePrime (numBits / 2, 30, randomSeeds, numRandomSeeds));
  4040. BitArray q (Primes::createProbablePrime (numBits - numBits / 2, 30, randomSeeds, numRandomSeeds));
  4041. BitArray n (p);
  4042. n.multiplyBy (q); // n = pq
  4043. const BitArray one (1);
  4044. p.subtract (one);
  4045. q.subtract (one);
  4046. BitArray m (p);
  4047. m.multiplyBy (q); // m = (p - 1)(q - 1)
  4048. const BitArray e (findBestCommonDivisor (p, q));
  4049. BitArray d (e);
  4050. d.inverseModulo (m);
  4051. publicKey.part1 = e;
  4052. publicKey.part2 = n;
  4053. privateKey.part1 = d;
  4054. privateKey.part2 = n;
  4055. }
  4056. END_JUCE_NAMESPACE
  4057. /********* End of inlined file: juce_RSAKey.cpp *********/
  4058. /********* Start of inlined file: juce_InputStream.cpp *********/
  4059. BEGIN_JUCE_NAMESPACE
  4060. char InputStream::readByte()
  4061. {
  4062. char temp = 0;
  4063. read (&temp, 1);
  4064. return temp;
  4065. }
  4066. bool InputStream::readBool()
  4067. {
  4068. return readByte() != 0;
  4069. }
  4070. short InputStream::readShort()
  4071. {
  4072. char temp [2];
  4073. if (read (temp, 2) == 2)
  4074. return (short) littleEndianShort (temp);
  4075. else
  4076. return 0;
  4077. }
  4078. short InputStream::readShortBigEndian()
  4079. {
  4080. char temp [2];
  4081. if (read (temp, 2) == 2)
  4082. return (short) bigEndianShort (temp);
  4083. else
  4084. return 0;
  4085. }
  4086. int InputStream::readInt()
  4087. {
  4088. char temp [4];
  4089. if (read (temp, 4) == 4)
  4090. return (int) littleEndianInt (temp);
  4091. else
  4092. return 0;
  4093. }
  4094. int InputStream::readIntBigEndian()
  4095. {
  4096. char temp [4];
  4097. if (read (temp, 4) == 4)
  4098. return (int) bigEndianInt (temp);
  4099. else
  4100. return 0;
  4101. }
  4102. int InputStream::readCompressedInt()
  4103. {
  4104. int num = 0;
  4105. if (! isExhausted())
  4106. {
  4107. unsigned char numBytes = readByte();
  4108. const bool negative = (numBytes & 0x80) != 0;
  4109. numBytes &= 0x7f;
  4110. if (numBytes <= 4)
  4111. {
  4112. if (read (&num, numBytes) != numBytes)
  4113. return 0;
  4114. if (negative)
  4115. num = -num;
  4116. }
  4117. }
  4118. return num;
  4119. }
  4120. int64 InputStream::readInt64()
  4121. {
  4122. char temp [8];
  4123. if (read (temp, 8) == 8)
  4124. return (int64) swapIfBigEndian (*(uint64*)temp);
  4125. else
  4126. return 0;
  4127. }
  4128. int64 InputStream::readInt64BigEndian()
  4129. {
  4130. char temp [8];
  4131. if (read (temp, 8) == 8)
  4132. return (int64) swapIfLittleEndian (*(uint64*)temp);
  4133. else
  4134. return 0;
  4135. }
  4136. float InputStream::readFloat()
  4137. {
  4138. union { int asInt; float asFloat; } n;
  4139. n.asInt = readInt();
  4140. return n.asFloat;
  4141. }
  4142. float InputStream::readFloatBigEndian()
  4143. {
  4144. union { int asInt; float asFloat; } n;
  4145. n.asInt = readIntBigEndian();
  4146. return n.asFloat;
  4147. }
  4148. double InputStream::readDouble()
  4149. {
  4150. union { int64 asInt; double asDouble; } n;
  4151. n.asInt = readInt64();
  4152. return n.asDouble;
  4153. }
  4154. double InputStream::readDoubleBigEndian()
  4155. {
  4156. union { int64 asInt; double asDouble; } n;
  4157. n.asInt = readInt64BigEndian();
  4158. return n.asDouble;
  4159. }
  4160. const String InputStream::readString()
  4161. {
  4162. const int tempBufferSize = 256;
  4163. uint8 temp [tempBufferSize];
  4164. int i = 0;
  4165. while ((temp [i++] = readByte()) != 0)
  4166. {
  4167. if (i == tempBufferSize)
  4168. {
  4169. // too big for our quick buffer, so read it in blocks..
  4170. String result (String::fromUTF8 (temp, i));
  4171. i = 0;
  4172. for (;;)
  4173. {
  4174. if ((temp [i++] = readByte()) == 0)
  4175. {
  4176. result += String::fromUTF8 (temp, i - 1);
  4177. break;
  4178. }
  4179. else if (i == tempBufferSize)
  4180. {
  4181. result += String::fromUTF8 (temp, i);
  4182. i = 0;
  4183. }
  4184. }
  4185. return result;
  4186. }
  4187. }
  4188. return String::fromUTF8 (temp, i - 1);
  4189. }
  4190. const String InputStream::readNextLine()
  4191. {
  4192. String s;
  4193. const int maxChars = 256;
  4194. tchar buffer [maxChars];
  4195. int charsInBuffer = 0;
  4196. while (! isExhausted())
  4197. {
  4198. const uint8 c = readByte();
  4199. const int64 lastPos = getPosition();
  4200. if (c == '\n')
  4201. {
  4202. break;
  4203. }
  4204. else if (c == '\r')
  4205. {
  4206. if (readByte() != '\n')
  4207. setPosition (lastPos);
  4208. break;
  4209. }
  4210. buffer [charsInBuffer++] = c;
  4211. if (charsInBuffer == maxChars)
  4212. {
  4213. s.append (buffer, maxChars);
  4214. charsInBuffer = 0;
  4215. }
  4216. }
  4217. if (charsInBuffer > 0)
  4218. s.append (buffer, charsInBuffer);
  4219. return s;
  4220. }
  4221. int InputStream::readIntoMemoryBlock (MemoryBlock& block,
  4222. int numBytes)
  4223. {
  4224. const int64 totalLength = getTotalLength();
  4225. if (totalLength >= 0)
  4226. {
  4227. const int totalBytesRemaining = (int) jmin ((int64) 0x7fffffff,
  4228. totalLength - getPosition());
  4229. if (numBytes < 0)
  4230. numBytes = totalBytesRemaining;
  4231. else if (numBytes > 0)
  4232. numBytes = jmin (numBytes, totalBytesRemaining);
  4233. else
  4234. return 0;
  4235. }
  4236. const int originalBlockSize = block.getSize();
  4237. int totalBytesRead = 0;
  4238. if (numBytes > 0)
  4239. {
  4240. // know how many bytes we want, so we can resize the block first..
  4241. block.setSize (originalBlockSize + numBytes, false);
  4242. totalBytesRead = read (((char*) block.getData()) + originalBlockSize, numBytes);
  4243. }
  4244. else
  4245. {
  4246. // read until end of stram..
  4247. const int chunkSize = 32768;
  4248. for (;;)
  4249. {
  4250. block.ensureSize (originalBlockSize + totalBytesRead + chunkSize, false);
  4251. const int bytesJustIn = read (((char*) block.getData())
  4252. + originalBlockSize
  4253. + totalBytesRead,
  4254. chunkSize);
  4255. if (bytesJustIn == 0)
  4256. break;
  4257. totalBytesRead += bytesJustIn;
  4258. }
  4259. }
  4260. // trim off any excess left at the end
  4261. block.setSize (originalBlockSize + totalBytesRead, false);
  4262. return totalBytesRead;
  4263. }
  4264. const String InputStream::readEntireStreamAsString()
  4265. {
  4266. MemoryBlock mb;
  4267. const int size = readIntoMemoryBlock (mb);
  4268. return String::createStringFromData ((const char*) mb.getData(), size);
  4269. }
  4270. void InputStream::skipNextBytes (int64 numBytesToSkip)
  4271. {
  4272. if (numBytesToSkip > 0)
  4273. {
  4274. const int skipBufferSize = (int) jmin (numBytesToSkip, (int64) 16384);
  4275. MemoryBlock temp (skipBufferSize);
  4276. while ((numBytesToSkip > 0) && ! isExhausted())
  4277. {
  4278. numBytesToSkip -= read (temp.getData(), (int) jmin (numBytesToSkip, (int64) skipBufferSize));
  4279. }
  4280. }
  4281. }
  4282. END_JUCE_NAMESPACE
  4283. /********* End of inlined file: juce_InputStream.cpp *********/
  4284. /********* Start of inlined file: juce_OutputStream.cpp *********/
  4285. BEGIN_JUCE_NAMESPACE
  4286. #if JUCE_DEBUG
  4287. static CriticalSection activeStreamLock;
  4288. static VoidArray activeStreams;
  4289. void juce_CheckForDanglingStreams()
  4290. {
  4291. /*
  4292. It's always a bad idea to leak any object, but if you're leaking output
  4293. streams, then there's a good chance that you're failing to flush a file
  4294. to disk properly, which could result in corrupted data and other similar
  4295. nastiness..
  4296. */
  4297. jassert (activeStreams.size() == 0);
  4298. };
  4299. #endif
  4300. OutputStream::OutputStream() throw()
  4301. {
  4302. #if JUCE_DEBUG
  4303. activeStreamLock.enter();
  4304. activeStreams.add (this);
  4305. activeStreamLock.exit();
  4306. #endif
  4307. }
  4308. OutputStream::~OutputStream()
  4309. {
  4310. #if JUCE_DEBUG
  4311. activeStreamLock.enter();
  4312. activeStreams.removeValue (this);
  4313. activeStreamLock.exit();
  4314. #endif
  4315. }
  4316. void OutputStream::writeBool (bool b)
  4317. {
  4318. writeByte ((b) ? (char) 1
  4319. : (char) 0);
  4320. }
  4321. void OutputStream::writeByte (char byte)
  4322. {
  4323. write (&byte, 1);
  4324. }
  4325. void OutputStream::writeShort (short value)
  4326. {
  4327. const unsigned short v = swapIfBigEndian ((unsigned short) value);
  4328. write (&v, 2);
  4329. }
  4330. void OutputStream::writeShortBigEndian (short value)
  4331. {
  4332. const unsigned short v = swapIfLittleEndian ((unsigned short) value);
  4333. write (&v, 2);
  4334. }
  4335. void OutputStream::writeInt (int value)
  4336. {
  4337. const unsigned int v = swapIfBigEndian ((unsigned int) value);
  4338. write (&v, 4);
  4339. }
  4340. void OutputStream::writeIntBigEndian (int value)
  4341. {
  4342. const unsigned int v = swapIfLittleEndian ((unsigned int) value);
  4343. write (&v, 4);
  4344. }
  4345. void OutputStream::writeCompressedInt (int value)
  4346. {
  4347. unsigned int un = (value < 0) ? (unsigned int) -value
  4348. : (unsigned int) value;
  4349. unsigned int tn = un;
  4350. int numSigBytes = 0;
  4351. do
  4352. {
  4353. tn >>= 8;
  4354. numSigBytes++;
  4355. } while (tn & 0xff);
  4356. if (value < 0)
  4357. numSigBytes |= 0x80;
  4358. writeByte ((char) numSigBytes);
  4359. write (&un, numSigBytes);
  4360. }
  4361. void OutputStream::writeInt64 (int64 value)
  4362. {
  4363. const uint64 v = swapIfBigEndian ((uint64) value);
  4364. write (&v, 8);
  4365. }
  4366. void OutputStream::writeInt64BigEndian (int64 value)
  4367. {
  4368. const uint64 v = swapIfLittleEndian ((uint64) value);
  4369. write (&v, 8);
  4370. }
  4371. void OutputStream::writeFloat (float value)
  4372. {
  4373. union { int asInt; float asFloat; } n;
  4374. n.asFloat = value;
  4375. writeInt (n.asInt);
  4376. }
  4377. void OutputStream::writeFloatBigEndian (float value)
  4378. {
  4379. union { int asInt; float asFloat; } n;
  4380. n.asFloat = value;
  4381. writeIntBigEndian (n.asInt);
  4382. }
  4383. void OutputStream::writeDouble (double value)
  4384. {
  4385. union { int64 asInt; double asDouble; } n;
  4386. n.asDouble = value;
  4387. writeInt64 (n.asInt);
  4388. }
  4389. void OutputStream::writeDoubleBigEndian (double value)
  4390. {
  4391. union { int64 asInt; double asDouble; } n;
  4392. n.asDouble = value;
  4393. writeInt64BigEndian (n.asInt);
  4394. }
  4395. void OutputStream::writeString (const String& text)
  4396. {
  4397. const int numBytes = text.copyToUTF8 (0);
  4398. uint8* const temp = (uint8*) juce_malloc (numBytes);
  4399. text.copyToUTF8 (temp);
  4400. write (temp, numBytes); // (numBytes includes the terminating null).
  4401. juce_free (temp);
  4402. }
  4403. void OutputStream::printf (const char* pf, ...)
  4404. {
  4405. unsigned int bufSize = 256;
  4406. char* buf = (char*) juce_malloc (bufSize);
  4407. for (;;)
  4408. {
  4409. va_list list;
  4410. va_start (list, pf);
  4411. const int num = CharacterFunctions::vprintf (buf, bufSize, pf, list);
  4412. va_end (list);
  4413. if (num > 0)
  4414. {
  4415. write (buf, num);
  4416. break;
  4417. }
  4418. else if (num == 0)
  4419. {
  4420. break;
  4421. }
  4422. juce_free (buf);
  4423. bufSize += 256;
  4424. buf = (char*) juce_malloc (bufSize);
  4425. }
  4426. juce_free (buf);
  4427. }
  4428. OutputStream& OutputStream::operator<< (const int number)
  4429. {
  4430. const String s (number);
  4431. write ((const char*) s, s.length());
  4432. return *this;
  4433. }
  4434. OutputStream& OutputStream::operator<< (const double number)
  4435. {
  4436. const String s (number);
  4437. write ((const char*) s, s.length());
  4438. return *this;
  4439. }
  4440. OutputStream& OutputStream::operator<< (const char character)
  4441. {
  4442. writeByte (character);
  4443. return *this;
  4444. }
  4445. OutputStream& OutputStream::operator<< (const char* const text)
  4446. {
  4447. write (text, (int) strlen (text));
  4448. return *this;
  4449. }
  4450. OutputStream& OutputStream::operator<< (const juce_wchar* const text)
  4451. {
  4452. const String s (text);
  4453. write ((const char*) s, s.length());
  4454. return *this;
  4455. }
  4456. OutputStream& OutputStream::operator<< (const String& text)
  4457. {
  4458. write ((const char*) text,
  4459. text.length());
  4460. return *this;
  4461. }
  4462. void OutputStream::writeText (const String& text,
  4463. const bool asUnicode,
  4464. const bool writeUnicodeHeaderBytes)
  4465. {
  4466. if (asUnicode)
  4467. {
  4468. if (writeUnicodeHeaderBytes)
  4469. write ("\x0ff\x0fe", 2);
  4470. const juce_wchar* src = (const juce_wchar*) text;
  4471. bool lastCharWasReturn = false;
  4472. while (*src != 0)
  4473. {
  4474. if (*src == L'\n' && ! lastCharWasReturn)
  4475. writeShort ((short) L'\r');
  4476. lastCharWasReturn = (*src == L'\r');
  4477. writeShort ((short) *src++);
  4478. }
  4479. }
  4480. else
  4481. {
  4482. const char* src = (const char*) text;
  4483. const char* t = src;
  4484. for (;;)
  4485. {
  4486. if (*t == '\n')
  4487. {
  4488. if (t > src)
  4489. write (src, (int) (t - src));
  4490. write ("\r\n", 2);
  4491. src = t + 1;
  4492. }
  4493. else if (*t == '\r')
  4494. {
  4495. if (t[1] == '\n')
  4496. ++t;
  4497. }
  4498. else if (*t == 0)
  4499. {
  4500. if (t > src)
  4501. write (src, (int) (t - src));
  4502. break;
  4503. }
  4504. ++t;
  4505. }
  4506. }
  4507. }
  4508. int OutputStream::writeFromInputStream (InputStream& source,
  4509. int numBytesToWrite)
  4510. {
  4511. if (numBytesToWrite < 0)
  4512. numBytesToWrite = 0x7fffffff;
  4513. int numWritten = 0;
  4514. while (numBytesToWrite > 0 && ! source.isExhausted())
  4515. {
  4516. char buffer [8192];
  4517. const int num = source.read (buffer, jmin (numBytesToWrite, sizeof (buffer)));
  4518. if (num == 0)
  4519. break;
  4520. write (buffer, num);
  4521. numBytesToWrite -= num;
  4522. numWritten += num;
  4523. }
  4524. return numWritten;
  4525. }
  4526. END_JUCE_NAMESPACE
  4527. /********* End of inlined file: juce_OutputStream.cpp *********/
  4528. /********* Start of inlined file: juce_DirectoryIterator.cpp *********/
  4529. BEGIN_JUCE_NAMESPACE
  4530. void* juce_findFileStart (const String& directory, const String& wildCard, String& firstResultFile,
  4531. bool* isDirectory, bool* isHidden, int64* fileSize,
  4532. Time* modTime, Time* creationTime, bool* isReadOnly) throw();
  4533. bool juce_findFileNext (void* handle, String& resultFile,
  4534. bool* isDirectory, bool* isHidden, int64* fileSize,
  4535. Time* modTime, Time* creationTime, bool* isReadOnly) throw();
  4536. void juce_findFileClose (void* handle) throw();
  4537. DirectoryIterator::DirectoryIterator (const File& directory,
  4538. bool isRecursive,
  4539. const String& wc,
  4540. const int whatToLookFor_) throw()
  4541. : wildCard (wc),
  4542. index (-1),
  4543. whatToLookFor (whatToLookFor_),
  4544. subIterator (0)
  4545. {
  4546. // you have to specify the type of files you're looking for!
  4547. jassert ((whatToLookFor_ & (File::findFiles | File::findDirectories)) != 0);
  4548. jassert (whatToLookFor_ > 0 && whatToLookFor_ <= 7);
  4549. String path (directory.getFullPathName());
  4550. if (! path.endsWithChar (File::separator))
  4551. path += File::separator;
  4552. String filename;
  4553. bool isDirectory, isHidden;
  4554. void* const handle = juce_findFileStart (path,
  4555. isRecursive ? T("*") : wc,
  4556. filename, &isDirectory, &isHidden, 0, 0, 0, 0);
  4557. if (handle != 0)
  4558. {
  4559. do
  4560. {
  4561. if (! filename.containsOnly (T(".")))
  4562. {
  4563. bool addToList = false;
  4564. if (isDirectory)
  4565. {
  4566. if (isRecursive
  4567. && ((whatToLookFor_ & File::ignoreHiddenFiles) == 0
  4568. || ! isHidden))
  4569. {
  4570. dirsFound.add (new File (path + filename, 0));
  4571. }
  4572. addToList = (whatToLookFor_ & File::findDirectories) != 0;
  4573. }
  4574. else
  4575. {
  4576. addToList = (whatToLookFor_ & File::findFiles) != 0;
  4577. }
  4578. // if it's recursive, we're not relying on the OS iterator
  4579. // to do the wildcard match, so do it now..
  4580. if (isRecursive && addToList)
  4581. addToList = filename.matchesWildcard (wc, true);
  4582. if (addToList && (whatToLookFor_ & File::ignoreHiddenFiles) != 0)
  4583. addToList = ! isHidden;
  4584. if (addToList)
  4585. filesFound.add (new File (path + filename, 0));
  4586. }
  4587. } while (juce_findFileNext (handle, filename, &isDirectory, &isHidden, 0, 0, 0, 0));
  4588. juce_findFileClose (handle);
  4589. }
  4590. }
  4591. DirectoryIterator::~DirectoryIterator() throw()
  4592. {
  4593. if (subIterator != 0)
  4594. delete subIterator;
  4595. }
  4596. bool DirectoryIterator::next() throw()
  4597. {
  4598. if (subIterator != 0)
  4599. {
  4600. if (subIterator->next())
  4601. return true;
  4602. deleteAndZero (subIterator);
  4603. }
  4604. if (index >= filesFound.size() + dirsFound.size() - 1)
  4605. return false;
  4606. ++index;
  4607. if (index >= filesFound.size())
  4608. {
  4609. subIterator = new DirectoryIterator (*(dirsFound [index - filesFound.size()]),
  4610. true, wildCard, whatToLookFor);
  4611. return next();
  4612. }
  4613. return true;
  4614. }
  4615. const File DirectoryIterator::getFile() const throw()
  4616. {
  4617. if (subIterator != 0)
  4618. return subIterator->getFile();
  4619. const File* const f = filesFound [index];
  4620. return (f != 0) ? *f
  4621. : File::nonexistent;
  4622. }
  4623. float DirectoryIterator::getEstimatedProgress() const throw()
  4624. {
  4625. if (filesFound.size() + dirsFound.size() == 0)
  4626. {
  4627. return 0.0f;
  4628. }
  4629. else
  4630. {
  4631. const float detailedIndex = (subIterator != 0) ? index + subIterator->getEstimatedProgress()
  4632. : (float) index;
  4633. return detailedIndex / (filesFound.size() + dirsFound.size());
  4634. }
  4635. }
  4636. END_JUCE_NAMESPACE
  4637. /********* End of inlined file: juce_DirectoryIterator.cpp *********/
  4638. /********* Start of inlined file: juce_File.cpp *********/
  4639. #ifdef _MSC_VER
  4640. #pragma warning (disable: 4514)
  4641. #pragma warning (push)
  4642. #endif
  4643. #ifndef JUCE_WIN32
  4644. #include <pwd.h>
  4645. #endif
  4646. BEGIN_JUCE_NAMESPACE
  4647. #ifdef _MSC_VER
  4648. #pragma warning (pop)
  4649. #endif
  4650. void* juce_fileOpen (const String& path, bool forWriting) throw();
  4651. void juce_fileClose (void* handle) throw();
  4652. int juce_fileWrite (void* handle, const void* buffer, int size) throw();
  4653. int64 juce_fileGetPosition (void* handle) throw();
  4654. int64 juce_fileSetPosition (void* handle, int64 pos) throw();
  4655. void juce_fileFlush (void* handle) throw();
  4656. bool juce_fileExists (const String& fileName, const bool dontCountDirectories) throw();
  4657. bool juce_isDirectory (const String& fileName) throw();
  4658. int64 juce_getFileSize (const String& fileName) throw();
  4659. bool juce_canWriteToFile (const String& fileName) throw();
  4660. bool juce_setFileReadOnly (const String& fileName, bool isReadOnly) throw();
  4661. void juce_getFileTimes (const String& fileName, int64& modificationTime, int64& accessTime, int64& creationTime) throw();
  4662. bool juce_setFileTimes (const String& fileName, int64 modificationTime, int64 accessTime, int64 creationTime) throw();
  4663. bool juce_deleteFile (const String& fileName) throw();
  4664. bool juce_copyFile (const String& source, const String& dest) throw();
  4665. bool juce_moveFile (const String& source, const String& dest) throw();
  4666. // this must also create all paths involved in the directory.
  4667. void juce_createDirectory (const String& fileName) throw();
  4668. bool juce_launchFile (const String& fileName, const String& parameters) throw();
  4669. const StringArray juce_getFileSystemRoots() throw();
  4670. const String juce_getVolumeLabel (const String& filenameOnVolume, int& volumeSerialNumber) throw();
  4671. // starts a directory search operation with a wildcard, returning a handle for
  4672. // use in calls to juce_findFileNext.
  4673. // juce_firstResultFile gets the name of the file (not the whole pathname) and
  4674. // the other pointers, if non-null, are set based on the properties of the file.
  4675. void* juce_findFileStart (const String& directory, const String& wildCard, String& firstResultFile,
  4676. bool* isDirectory, bool* isHidden, int64* fileSize, Time* modTime,
  4677. Time* creationTime, bool* isReadOnly) throw();
  4678. // returns false when no more files are found
  4679. bool juce_findFileNext (void* handle, String& resultFile,
  4680. bool* isDirectory, bool* isHidden, int64* fileSize,
  4681. Time* modTime, Time* creationTime, bool* isReadOnly) throw();
  4682. void juce_findFileClose (void* handle) throw();
  4683. static const String juce_addTrailingSeparator (const String& path) throw()
  4684. {
  4685. return path.endsWithChar (File::separator) ? path
  4686. : path + File::separator;
  4687. }
  4688. static const String parseAbsolutePath (String path) throw()
  4689. {
  4690. if (path.isEmpty())
  4691. return String::empty;
  4692. #if JUCE_WIN32
  4693. // Windows..
  4694. path = path.replaceCharacter (T('/'), T('\\'));
  4695. if (path.startsWithChar (File::separator))
  4696. {
  4697. if (path[1] != File::separator)
  4698. {
  4699. jassertfalse // using a filename that starts with a slash is a bit dodgy on
  4700. // Windows, because it needs a drive letter, which in this case
  4701. // we'll take from the CWD.. but this is a bit of an assumption that
  4702. // could be wrong..
  4703. path = File::getCurrentWorkingDirectory().getFullPathName().substring (0, 2) + path;
  4704. }
  4705. }
  4706. else if (path.indexOfChar (T(':')) < 0)
  4707. {
  4708. if (path.isEmpty())
  4709. return String::empty;
  4710. jassertfalse // using a partial filename is a bad way to initialise a file, because
  4711. // we don't know what directory to put it in.
  4712. // Here we'll assume it's in the CWD, but this might not be what was
  4713. // intended..
  4714. return File::getCurrentWorkingDirectory().getChildFile (path).getFullPathName();
  4715. }
  4716. #else
  4717. // Mac or Linux..
  4718. path = path.replaceCharacter (T('\\'), T('/'));
  4719. if (path.startsWithChar (T('~')))
  4720. {
  4721. const char* homeDir = 0;
  4722. if (path[1] == File::separator || path[1] == 0)
  4723. {
  4724. // expand a name of the form "~/abc"
  4725. path = File::getSpecialLocation (File::userHomeDirectory).getFullPathName()
  4726. + path.substring (1);
  4727. }
  4728. else
  4729. {
  4730. // expand a name of type "~dave/abc"
  4731. const String userName (path.substring (1)
  4732. .upToFirstOccurrenceOf (T("/"), false, false));
  4733. struct passwd* const pw = getpwnam (userName);
  4734. if (pw != 0)
  4735. {
  4736. String home (homeDir);
  4737. if (home.endsWithChar (File::separator))
  4738. home [home.length() - 1] = 0;
  4739. path = String (pw->pw_dir)
  4740. + path.substring (userName.length());
  4741. }
  4742. }
  4743. }
  4744. else if (! path.startsWithChar (File::separator))
  4745. {
  4746. while (path.startsWith (T("./")))
  4747. path = path.substring (2);
  4748. if (path.isEmpty())
  4749. return String::empty;
  4750. jassertfalse // using a partial filename is a bad way to initialise a file, because
  4751. // we don't know what directory to put it in.
  4752. // Here we'll assume it's in the CWD, but this might not be what was
  4753. // intended..
  4754. return File::getCurrentWorkingDirectory().getChildFile (path).getFullPathName();
  4755. }
  4756. #endif
  4757. int len = path.length();
  4758. while (--len > 0 && path [len] == File::separator)
  4759. path [len] = 0;
  4760. return path;
  4761. }
  4762. const File File::nonexistent;
  4763. File::File (const String& fullPathName) throw()
  4764. : fullPath (parseAbsolutePath (fullPathName))
  4765. {
  4766. }
  4767. File::File (const String& path, int) throw()
  4768. : fullPath (path)
  4769. {
  4770. }
  4771. File::File (const File& other) throw()
  4772. : fullPath (other.fullPath)
  4773. {
  4774. }
  4775. const File& File::operator= (const String& newPath) throw()
  4776. {
  4777. fullPath = parseAbsolutePath (newPath);
  4778. return *this;
  4779. }
  4780. const File& File::operator= (const File& other) throw()
  4781. {
  4782. fullPath = other.fullPath;
  4783. return *this;
  4784. }
  4785. #if JUCE_LINUX
  4786. #define NAMES_ARE_CASE_SENSITIVE 1
  4787. #endif
  4788. bool File::areFileNamesCaseSensitive()
  4789. {
  4790. #if NAMES_ARE_CASE_SENSITIVE
  4791. return true;
  4792. #else
  4793. return false;
  4794. #endif
  4795. }
  4796. bool File::operator== (const File& other) const throw()
  4797. {
  4798. // case-insensitive on Windows, but not on linux.
  4799. #if NAMES_ARE_CASE_SENSITIVE
  4800. return fullPath == other.fullPath;
  4801. #else
  4802. return fullPath.equalsIgnoreCase (other.fullPath);
  4803. #endif
  4804. }
  4805. bool File::operator!= (const File& other) const throw()
  4806. {
  4807. return ! operator== (other);
  4808. }
  4809. bool File::exists() const throw()
  4810. {
  4811. return juce_fileExists (fullPath, false);
  4812. }
  4813. bool File::existsAsFile() const throw()
  4814. {
  4815. return juce_fileExists (fullPath, true);
  4816. }
  4817. bool File::isDirectory() const throw()
  4818. {
  4819. return juce_isDirectory (fullPath);
  4820. }
  4821. bool File::hasWriteAccess() const throw()
  4822. {
  4823. if (exists())
  4824. return juce_canWriteToFile (fullPath);
  4825. #ifndef JUCE_WIN32
  4826. else if ((! isDirectory()) && fullPath.containsChar (separator))
  4827. return getParentDirectory().hasWriteAccess();
  4828. else
  4829. return false;
  4830. #else
  4831. // on windows, it seems that even read-only directories can still be written into,
  4832. // so checking the parent directory's permissions would return the wrong result..
  4833. else
  4834. return true;
  4835. #endif
  4836. }
  4837. bool File::setReadOnly (const bool shouldBeReadOnly,
  4838. const bool applyRecursively) const throw()
  4839. {
  4840. bool worked = true;
  4841. if (applyRecursively && isDirectory())
  4842. {
  4843. OwnedArray <File> subFiles;
  4844. findChildFiles (subFiles, File::findFilesAndDirectories, false);
  4845. for (int i = subFiles.size(); --i >= 0;)
  4846. worked = subFiles[i]->setReadOnly (shouldBeReadOnly, true) && worked;
  4847. }
  4848. return juce_setFileReadOnly (fullPath, shouldBeReadOnly) && worked;
  4849. }
  4850. bool File::deleteFile() const throw()
  4851. {
  4852. return (! exists())
  4853. || juce_deleteFile (fullPath);
  4854. }
  4855. bool File::deleteRecursively() const throw()
  4856. {
  4857. bool worked = true;
  4858. if (isDirectory())
  4859. {
  4860. OwnedArray<File> subFiles;
  4861. findChildFiles (subFiles, File::findFilesAndDirectories, false);
  4862. for (int i = subFiles.size(); --i >= 0;)
  4863. worked = subFiles[i]->deleteRecursively() && worked;
  4864. }
  4865. return deleteFile() && worked;
  4866. }
  4867. bool File::moveFileTo (const File& newFile) const throw()
  4868. {
  4869. if (newFile.fullPath == fullPath)
  4870. return true;
  4871. #if ! NAMES_ARE_CASE_SENSITIVE
  4872. if (*this != newFile)
  4873. #endif
  4874. if (! newFile.deleteFile())
  4875. return false;
  4876. return juce_moveFile (fullPath, newFile.fullPath);
  4877. }
  4878. bool File::copyFileTo (const File& newFile) const throw()
  4879. {
  4880. if (*this == newFile)
  4881. return true;
  4882. if (! newFile.deleteFile())
  4883. return false;
  4884. return juce_copyFile (fullPath, newFile.fullPath);
  4885. }
  4886. bool File::copyDirectoryTo (const File& newDirectory) const throw()
  4887. {
  4888. if (isDirectory() && newDirectory.createDirectory())
  4889. {
  4890. OwnedArray<File> subFiles;
  4891. findChildFiles (subFiles, File::findFiles, false);
  4892. int i;
  4893. for (i = 0; i < subFiles.size(); ++i)
  4894. if (! subFiles[i]->copyFileTo (newDirectory.getChildFile (subFiles[i]->getFileName())))
  4895. return false;
  4896. subFiles.clear();
  4897. findChildFiles (subFiles, File::findDirectories, false);
  4898. for (i = 0; i < subFiles.size(); ++i)
  4899. if (! subFiles[i]->copyDirectoryTo (newDirectory.getChildFile (subFiles[i]->getFileName())))
  4900. return false;
  4901. return true;
  4902. }
  4903. return false;
  4904. }
  4905. const String File::getPathUpToLastSlash() const throw()
  4906. {
  4907. const int lastSlash = fullPath.lastIndexOfChar (separator);
  4908. if (lastSlash > 0)
  4909. return fullPath.substring (0, lastSlash);
  4910. else if (lastSlash == 0)
  4911. return separatorString;
  4912. else
  4913. return fullPath;
  4914. }
  4915. const File File::getParentDirectory() const throw()
  4916. {
  4917. return File (getPathUpToLastSlash());
  4918. }
  4919. const String File::getFileName() const throw()
  4920. {
  4921. return fullPath.substring (fullPath.lastIndexOfChar (separator) + 1);
  4922. }
  4923. int File::hashCode() const throw()
  4924. {
  4925. return fullPath.hashCode();
  4926. }
  4927. int64 File::hashCode64() const throw()
  4928. {
  4929. return fullPath.hashCode64();
  4930. }
  4931. const String File::getFileNameWithoutExtension() const throw()
  4932. {
  4933. const int lastSlash = fullPath.lastIndexOfChar (separator) + 1;
  4934. const int lastDot = fullPath.lastIndexOfChar (T('.'));
  4935. if (lastDot > lastSlash)
  4936. return fullPath.substring (lastSlash, lastDot);
  4937. else
  4938. return fullPath.substring (lastSlash);
  4939. }
  4940. bool File::isAChildOf (const File& potentialParent) const throw()
  4941. {
  4942. const String ourPath (getPathUpToLastSlash());
  4943. #if NAMES_ARE_CASE_SENSITIVE
  4944. if (potentialParent.fullPath == ourPath)
  4945. #else
  4946. if (potentialParent.fullPath.equalsIgnoreCase (ourPath))
  4947. #endif
  4948. {
  4949. return true;
  4950. }
  4951. else if (potentialParent.fullPath.length() >= ourPath.length())
  4952. {
  4953. return false;
  4954. }
  4955. else
  4956. {
  4957. return getParentDirectory().isAChildOf (potentialParent);
  4958. }
  4959. }
  4960. bool File::isAbsolutePath (const String& path) throw()
  4961. {
  4962. return path.startsWithChar (T('/')) || path.startsWithChar (T('\\'))
  4963. #if JUCE_WIN32
  4964. || (path.isNotEmpty() && ((const String&) path)[1] == T(':'));
  4965. #else
  4966. || path.startsWithChar (T('~'));
  4967. #endif
  4968. }
  4969. const File File::getChildFile (String relativePath) const throw()
  4970. {
  4971. if (isAbsolutePath (relativePath))
  4972. {
  4973. // the path is really absolute..
  4974. return File (relativePath);
  4975. }
  4976. else
  4977. {
  4978. // it's relative, so remove any ../ or ./ bits at the start.
  4979. String path (fullPath);
  4980. if (relativePath[0] == T('.'))
  4981. {
  4982. #if JUCE_WIN32
  4983. relativePath = relativePath.replaceCharacter (T('/'), T('\\')).trimStart();
  4984. #else
  4985. relativePath = relativePath.replaceCharacter (T('\\'), T('/')).trimStart();
  4986. #endif
  4987. while (relativePath[0] == T('.'))
  4988. {
  4989. if (relativePath[1] == T('.'))
  4990. {
  4991. if (relativePath [2] == 0 || relativePath[2] == separator)
  4992. {
  4993. const int lastSlash = path.lastIndexOfChar (separator);
  4994. if (lastSlash >= 0)
  4995. path = path.substring (0, lastSlash);
  4996. relativePath = relativePath.substring (3);
  4997. }
  4998. else
  4999. {
  5000. break;
  5001. }
  5002. }
  5003. else if (relativePath[1] == separator)
  5004. {
  5005. relativePath = relativePath.substring (2);
  5006. }
  5007. else
  5008. {
  5009. break;
  5010. }
  5011. }
  5012. }
  5013. return File (juce_addTrailingSeparator (path) + relativePath);
  5014. }
  5015. }
  5016. const File File::getSiblingFile (const String& fileName) const throw()
  5017. {
  5018. return getParentDirectory().getChildFile (fileName);
  5019. }
  5020. int64 File::getSize() const throw()
  5021. {
  5022. return juce_getFileSize (fullPath);
  5023. }
  5024. const String File::descriptionOfSizeInBytes (const int64 bytes)
  5025. {
  5026. if (bytes == 1)
  5027. {
  5028. return "1 byte";
  5029. }
  5030. else if (bytes < 1024)
  5031. {
  5032. return String ((int) bytes) + " bytes";
  5033. }
  5034. else if (bytes < 1024 * 1024)
  5035. {
  5036. return String (bytes / 1024.0, 1) + " KB";
  5037. }
  5038. else if (bytes < 1024 * 1024 * 1024)
  5039. {
  5040. return String (bytes / (1024.0 * 1024.0), 1) + " MB";
  5041. }
  5042. else
  5043. {
  5044. return String (bytes / (1024.0 * 1024.0 * 1024.0), 1) + " GB";
  5045. }
  5046. }
  5047. bool File::create() const throw()
  5048. {
  5049. if (! exists())
  5050. {
  5051. const File parentDir (getParentDirectory());
  5052. if (parentDir == *this || ! parentDir.createDirectory())
  5053. return false;
  5054. void* const fh = juce_fileOpen (fullPath, true);
  5055. if (fh == 0)
  5056. return false;
  5057. juce_fileClose (fh);
  5058. }
  5059. return true;
  5060. }
  5061. bool File::createDirectory() const throw()
  5062. {
  5063. if (! isDirectory())
  5064. {
  5065. const File parentDir (getParentDirectory());
  5066. if (parentDir == *this || ! parentDir.createDirectory())
  5067. return false;
  5068. String dir (fullPath);
  5069. while (dir.endsWithChar (separator))
  5070. dir [dir.length() - 1] = 0;
  5071. juce_createDirectory (dir);
  5072. return isDirectory();
  5073. }
  5074. return true;
  5075. }
  5076. const Time File::getCreationTime() const throw()
  5077. {
  5078. int64 m, a, c;
  5079. juce_getFileTimes (fullPath, m, a, c);
  5080. return Time (c);
  5081. }
  5082. bool File::setCreationTime (const Time& t) const throw()
  5083. {
  5084. return juce_setFileTimes (fullPath, 0, 0, t.toMilliseconds());
  5085. }
  5086. const Time File::getLastModificationTime() const throw()
  5087. {
  5088. int64 m, a, c;
  5089. juce_getFileTimes (fullPath, m, a, c);
  5090. return Time (m);
  5091. }
  5092. bool File::setLastModificationTime (const Time& t) const throw()
  5093. {
  5094. return juce_setFileTimes (fullPath, t.toMilliseconds(), 0, 0);
  5095. }
  5096. const Time File::getLastAccessTime() const throw()
  5097. {
  5098. int64 m, a, c;
  5099. juce_getFileTimes (fullPath, m, a, c);
  5100. return Time (a);
  5101. }
  5102. bool File::setLastAccessTime (const Time& t) const throw()
  5103. {
  5104. return juce_setFileTimes (fullPath, 0, t.toMilliseconds(), 0);
  5105. }
  5106. bool File::loadFileAsData (MemoryBlock& destBlock) const throw()
  5107. {
  5108. if (! existsAsFile())
  5109. return false;
  5110. FileInputStream in (*this);
  5111. return getSize() == in.readIntoMemoryBlock (destBlock);
  5112. }
  5113. const String File::loadFileAsString() const throw()
  5114. {
  5115. if (! existsAsFile())
  5116. return String::empty;
  5117. FileInputStream in (*this);
  5118. return in.readEntireStreamAsString();
  5119. }
  5120. static inline bool fileTypeMatches (const int whatToLookFor,
  5121. const bool isDir,
  5122. const bool isHidden)
  5123. {
  5124. return (whatToLookFor & (isDir ? File::findDirectories
  5125. : File::findFiles)) != 0
  5126. && ((! isHidden)
  5127. || (whatToLookFor & File::ignoreHiddenFiles) == 0);
  5128. }
  5129. int File::findChildFiles (OwnedArray<File>& results,
  5130. const int whatToLookFor,
  5131. const bool searchRecursively,
  5132. const String& wildCardPattern) const throw()
  5133. {
  5134. // you have to specify the type of files you're looking for!
  5135. jassert ((whatToLookFor & (findFiles | findDirectories)) != 0);
  5136. int total = 0;
  5137. // find child files or directories in this directory first..
  5138. if (isDirectory())
  5139. {
  5140. const String path (juce_addTrailingSeparator (fullPath));
  5141. String filename;
  5142. bool isDirectory, isHidden;
  5143. void* const handle = juce_findFileStart (path,
  5144. wildCardPattern,
  5145. filename,
  5146. &isDirectory, &isHidden,
  5147. 0, 0, 0, 0);
  5148. if (handle != 0)
  5149. {
  5150. do
  5151. {
  5152. if (fileTypeMatches (whatToLookFor, isDirectory, isHidden)
  5153. && ! filename.containsOnly (T(".")))
  5154. {
  5155. results.add (new File (path + filename, 0));
  5156. ++total;
  5157. }
  5158. } while (juce_findFileNext (handle, filename, &isDirectory, &isHidden, 0, 0, 0, 0));
  5159. juce_findFileClose (handle);
  5160. }
  5161. }
  5162. else
  5163. {
  5164. // trying to search for files inside a non-directory?
  5165. //jassertfalse
  5166. }
  5167. // and recurse down if required.
  5168. if (searchRecursively)
  5169. {
  5170. OwnedArray <File> subDirectories;
  5171. findChildFiles (subDirectories, File::findDirectories, false);
  5172. for (int i = 0; i < subDirectories.size(); ++i)
  5173. {
  5174. total += subDirectories.getUnchecked(i)
  5175. ->findChildFiles (results,
  5176. whatToLookFor,
  5177. true,
  5178. wildCardPattern);
  5179. }
  5180. }
  5181. return total;
  5182. }
  5183. int File::getNumberOfChildFiles (const int whatToLookFor,
  5184. const String& wildCardPattern) const throw()
  5185. {
  5186. // you have to specify the type of files you're looking for!
  5187. jassert (whatToLookFor > 0 && whatToLookFor <= 3);
  5188. int count = 0;
  5189. if (isDirectory())
  5190. {
  5191. String filename;
  5192. bool isDirectory, isHidden;
  5193. void* const handle = juce_findFileStart (fullPath,
  5194. wildCardPattern,
  5195. filename,
  5196. &isDirectory, &isHidden,
  5197. 0, 0, 0, 0);
  5198. if (handle != 0)
  5199. {
  5200. do
  5201. {
  5202. if (fileTypeMatches (whatToLookFor, isDirectory, isHidden)
  5203. && ! filename.containsOnly (T(".")))
  5204. {
  5205. ++count;
  5206. }
  5207. } while (juce_findFileNext (handle, filename, &isDirectory, &isHidden, 0, 0, 0, 0));
  5208. juce_findFileClose (handle);
  5209. }
  5210. }
  5211. else
  5212. {
  5213. // trying to search for files inside a non-directory?
  5214. jassertfalse
  5215. }
  5216. return count;
  5217. }
  5218. bool File::containsSubDirectories() const throw()
  5219. {
  5220. bool result = false;
  5221. if (isDirectory())
  5222. {
  5223. String filename;
  5224. bool isDirectory, isHidden;
  5225. void* const handle = juce_findFileStart (juce_addTrailingSeparator (fullPath),
  5226. T("*"), filename,
  5227. &isDirectory, &isHidden, 0, 0, 0, 0);
  5228. if (handle != 0)
  5229. {
  5230. do
  5231. {
  5232. if (isDirectory)
  5233. {
  5234. result = true;
  5235. break;
  5236. }
  5237. } while (juce_findFileNext (handle, filename, &isDirectory, &isHidden, 0, 0, 0, 0));
  5238. juce_findFileClose (handle);
  5239. }
  5240. }
  5241. return result;
  5242. }
  5243. const File File::getNonexistentChildFile (const String& prefix_,
  5244. const String& suffix,
  5245. bool putNumbersInBrackets) const throw()
  5246. {
  5247. File f (getChildFile (prefix_ + suffix));
  5248. if (f.exists())
  5249. {
  5250. int num = 2;
  5251. String prefix (prefix_);
  5252. // remove any bracketed numbers that may already be on the end..
  5253. if (prefix.trim().endsWithChar (T(')')))
  5254. {
  5255. putNumbersInBrackets = true;
  5256. const int openBracks = prefix.lastIndexOfChar (T('('));
  5257. const int closeBracks = prefix.lastIndexOfChar (T(')'));
  5258. if (openBracks > 0
  5259. && closeBracks > openBracks
  5260. && prefix.substring (openBracks + 1, closeBracks).containsOnly (T("0123456789")))
  5261. {
  5262. num = prefix.substring (openBracks + 1, closeBracks).getIntValue() + 1;
  5263. prefix = prefix.substring (0, openBracks);
  5264. }
  5265. }
  5266. // also use brackets if it ends in a digit.
  5267. putNumbersInBrackets = putNumbersInBrackets
  5268. || CharacterFunctions::isDigit (prefix.getLastCharacter());
  5269. do
  5270. {
  5271. if (putNumbersInBrackets)
  5272. f = getChildFile (prefix + T('(') + String (num++) + T(')') + suffix);
  5273. else
  5274. f = getChildFile (prefix + String (num++) + suffix);
  5275. } while (f.exists());
  5276. }
  5277. return f;
  5278. }
  5279. const File File::getNonexistentSibling (const bool putNumbersInBrackets) const throw()
  5280. {
  5281. if (exists())
  5282. {
  5283. return getParentDirectory()
  5284. .getNonexistentChildFile (getFileNameWithoutExtension(),
  5285. getFileExtension(),
  5286. putNumbersInBrackets);
  5287. }
  5288. else
  5289. {
  5290. return *this;
  5291. }
  5292. }
  5293. const String File::getFileExtension() const throw()
  5294. {
  5295. String ext;
  5296. if (! isDirectory())
  5297. {
  5298. const int indexOfDot = fullPath.lastIndexOfChar (T('.'));
  5299. if (indexOfDot > fullPath.lastIndexOfChar (separator))
  5300. ext = fullPath.substring (indexOfDot);
  5301. }
  5302. return ext;
  5303. }
  5304. bool File::hasFileExtension (const String& possibleSuffix) const throw()
  5305. {
  5306. if (possibleSuffix.isEmpty())
  5307. return fullPath.lastIndexOfChar (T('.')) <= fullPath.lastIndexOfChar (separator);
  5308. if (fullPath.endsWithIgnoreCase (possibleSuffix))
  5309. {
  5310. if (possibleSuffix.startsWithChar (T('.')))
  5311. return true;
  5312. const int dotPos = fullPath.length() - possibleSuffix.length() - 1;
  5313. if (dotPos >= 0)
  5314. return fullPath [dotPos] == T('.');
  5315. }
  5316. return false;
  5317. }
  5318. const File File::withFileExtension (const String& newExtension) const throw()
  5319. {
  5320. if (fullPath.isEmpty())
  5321. return File::nonexistent;
  5322. String filePart (getFileName());
  5323. int i = filePart.lastIndexOfChar (T('.'));
  5324. if (i < 0)
  5325. i = filePart.length();
  5326. String newExt (newExtension);
  5327. if (newExt.isNotEmpty() && ! newExt.startsWithChar (T('.')))
  5328. newExt = T(".") + newExt;
  5329. return getSiblingFile (filePart.substring (0, i) + newExt);
  5330. }
  5331. bool File::startAsProcess (const String& parameters) const throw()
  5332. {
  5333. return exists()
  5334. && juce_launchFile (fullPath, parameters);
  5335. }
  5336. FileInputStream* File::createInputStream() const throw()
  5337. {
  5338. if (existsAsFile())
  5339. return new FileInputStream (*this);
  5340. else
  5341. return 0;
  5342. }
  5343. FileOutputStream* File::createOutputStream (const int bufferSize) const throw()
  5344. {
  5345. FileOutputStream* const out = new FileOutputStream (*this, bufferSize);
  5346. if (out->failedToOpen())
  5347. {
  5348. delete out;
  5349. return 0;
  5350. }
  5351. else
  5352. {
  5353. return out;
  5354. }
  5355. }
  5356. bool File::appendData (const void* const dataToAppend,
  5357. const int numberOfBytes) const throw()
  5358. {
  5359. if (numberOfBytes > 0)
  5360. {
  5361. FileOutputStream* const out = createOutputStream();
  5362. if (out == 0)
  5363. return false;
  5364. out->write (dataToAppend, numberOfBytes);
  5365. delete out;
  5366. }
  5367. return true;
  5368. }
  5369. bool File::replaceWithData (const void* const dataToWrite,
  5370. const int numberOfBytes) const throw()
  5371. {
  5372. jassert (numberOfBytes >= 0); // a negative number of bytes??
  5373. if (numberOfBytes <= 0)
  5374. return deleteFile();
  5375. const File tempFile (getSiblingFile (T(".") + getFileName()).getNonexistentSibling (false));
  5376. if (tempFile.appendData (dataToWrite, numberOfBytes)
  5377. && tempFile.moveFileTo (*this))
  5378. {
  5379. return true;
  5380. }
  5381. tempFile.deleteFile();
  5382. return false;
  5383. }
  5384. bool File::appendText (const String& text,
  5385. const bool asUnicode,
  5386. const bool writeUnicodeHeaderBytes) const throw()
  5387. {
  5388. FileOutputStream* const out = createOutputStream();
  5389. if (out != 0)
  5390. {
  5391. out->writeText (text, asUnicode, writeUnicodeHeaderBytes);
  5392. delete out;
  5393. return true;
  5394. }
  5395. return false;
  5396. }
  5397. bool File::printf (const tchar* pf, ...) const throw()
  5398. {
  5399. va_list list;
  5400. va_start (list, pf);
  5401. String text;
  5402. text.vprintf (pf, list);
  5403. return appendData ((const char*) text, text.length());
  5404. }
  5405. bool File::replaceWithText (const String& textToWrite,
  5406. const bool asUnicode,
  5407. const bool writeUnicodeHeaderBytes) const throw()
  5408. {
  5409. const File tempFile (getSiblingFile (T(".") + getFileName()).getNonexistentSibling (false));
  5410. if (tempFile.appendText (textToWrite, asUnicode, writeUnicodeHeaderBytes)
  5411. && tempFile.moveFileTo (*this))
  5412. {
  5413. return true;
  5414. }
  5415. tempFile.deleteFile();
  5416. return false;
  5417. }
  5418. const String File::createLegalPathName (const String& original) throw()
  5419. {
  5420. String s (original);
  5421. String start;
  5422. if (s[1] == T(':'))
  5423. {
  5424. start = s.substring (0, 2);
  5425. s = s.substring (2);
  5426. }
  5427. return start + s.removeCharacters (T("\"#@,;:<>*^|?"))
  5428. .substring (0, 1024);
  5429. }
  5430. const String File::createLegalFileName (const String& original) throw()
  5431. {
  5432. String s (original.removeCharacters (T("\"#@,;:<>*^|?\\/")));
  5433. const int maxLength = 128; // only the length of the filename, not the whole path
  5434. const int len = s.length();
  5435. if (len > maxLength)
  5436. {
  5437. const int lastDot = s.lastIndexOfChar (T('.'));
  5438. if (lastDot > jmax (0, len - 12))
  5439. {
  5440. s = s.substring (0, maxLength - (len - lastDot))
  5441. + s.substring (lastDot);
  5442. }
  5443. else
  5444. {
  5445. s = s.substring (0, maxLength);
  5446. }
  5447. }
  5448. return s;
  5449. }
  5450. const String File::getRelativePathFrom (const File& dir) const throw()
  5451. {
  5452. String thisPath (fullPath);
  5453. {
  5454. int len = thisPath.length();
  5455. while (--len >= 0 && thisPath [len] == File::separator)
  5456. thisPath [len] = 0;
  5457. }
  5458. String dirPath (juce_addTrailingSeparator ((dir.existsAsFile()) ? dir.getParentDirectory().getFullPathName()
  5459. : dir.fullPath));
  5460. const int len = jmin (thisPath.length(), dirPath.length());
  5461. int commonBitLength = 0;
  5462. for (int i = 0; i < len; ++i)
  5463. {
  5464. #if NAMES_ARE_CASE_SENSITIVE
  5465. if (thisPath[i] != dirPath[i])
  5466. #else
  5467. if (CharacterFunctions::toLowerCase (thisPath[i])
  5468. != CharacterFunctions::toLowerCase (dirPath[i]))
  5469. #endif
  5470. {
  5471. break;
  5472. }
  5473. ++commonBitLength;
  5474. }
  5475. while (commonBitLength > 0 && thisPath [commonBitLength - 1] != File::separator)
  5476. --commonBitLength;
  5477. // if the only common bit is the root, then just return the full path..
  5478. if (commonBitLength <= 0
  5479. || (commonBitLength == 1 && thisPath [1] == File::separator))
  5480. return fullPath;
  5481. thisPath = thisPath.substring (commonBitLength);
  5482. dirPath = dirPath.substring (commonBitLength);
  5483. while (dirPath.isNotEmpty())
  5484. {
  5485. #if JUCE_WIN32
  5486. thisPath = T("..\\") + thisPath;
  5487. #else
  5488. thisPath = T("../") + thisPath;
  5489. #endif
  5490. const int sep = dirPath.indexOfChar (separator);
  5491. if (sep >= 0)
  5492. dirPath = dirPath.substring (sep + 1);
  5493. else
  5494. dirPath = String::empty;
  5495. }
  5496. return thisPath;
  5497. }
  5498. void File::findFileSystemRoots (OwnedArray<File>& destArray) throw()
  5499. {
  5500. const StringArray roots (juce_getFileSystemRoots());
  5501. for (int i = 0; i < roots.size(); ++i)
  5502. destArray.add (new File (roots[i]));
  5503. }
  5504. const String File::getVolumeLabel() const throw()
  5505. {
  5506. int serialNum;
  5507. return juce_getVolumeLabel (fullPath, serialNum);
  5508. }
  5509. int File::getVolumeSerialNumber() const throw()
  5510. {
  5511. int serialNum;
  5512. juce_getVolumeLabel (fullPath, serialNum);
  5513. return serialNum;
  5514. }
  5515. const File File::createTempFile (const String& fileNameEnding) throw()
  5516. {
  5517. String tempName (T("temp"));
  5518. static int tempNum = 0;
  5519. tempName << tempNum++ << fileNameEnding;
  5520. const File tempFile (getSpecialLocation (tempDirectory)
  5521. .getChildFile (tempName));
  5522. if (tempFile.exists())
  5523. return createTempFile (fileNameEnding);
  5524. else
  5525. return tempFile;
  5526. }
  5527. END_JUCE_NAMESPACE
  5528. /********* End of inlined file: juce_File.cpp *********/
  5529. /********* Start of inlined file: juce_FileInputStream.cpp *********/
  5530. BEGIN_JUCE_NAMESPACE
  5531. void* juce_fileOpen (const String& path, bool forWriting) throw();
  5532. void juce_fileClose (void* handle) throw();
  5533. int juce_fileRead (void* handle, void* buffer, int size) throw();
  5534. int64 juce_fileSetPosition (void* handle, int64 pos) throw();
  5535. FileInputStream::FileInputStream (const File& f)
  5536. : file (f),
  5537. currentPosition (0),
  5538. needToSeek (true)
  5539. {
  5540. totalSize = f.getSize();
  5541. fileHandle = juce_fileOpen (f.getFullPathName(), false);
  5542. }
  5543. FileInputStream::~FileInputStream()
  5544. {
  5545. juce_fileClose (fileHandle);
  5546. }
  5547. int64 FileInputStream::getTotalLength()
  5548. {
  5549. return totalSize;
  5550. }
  5551. int FileInputStream::read (void* buffer, int bytesToRead)
  5552. {
  5553. int num = 0;
  5554. if (needToSeek)
  5555. {
  5556. if (juce_fileSetPosition (fileHandle, currentPosition) < 0)
  5557. return 0;
  5558. needToSeek = false;
  5559. }
  5560. num = juce_fileRead (fileHandle, buffer, bytesToRead);
  5561. currentPosition += num;
  5562. return num;
  5563. }
  5564. bool FileInputStream::isExhausted()
  5565. {
  5566. return currentPosition >= totalSize;
  5567. }
  5568. int64 FileInputStream::getPosition()
  5569. {
  5570. return currentPosition;
  5571. }
  5572. bool FileInputStream::setPosition (int64 pos)
  5573. {
  5574. pos = jlimit ((int64) 0, totalSize, pos);
  5575. needToSeek |= (currentPosition != pos);
  5576. currentPosition = pos;
  5577. return true;
  5578. }
  5579. END_JUCE_NAMESPACE
  5580. /********* End of inlined file: juce_FileInputStream.cpp *********/
  5581. /********* Start of inlined file: juce_FileOutputStream.cpp *********/
  5582. BEGIN_JUCE_NAMESPACE
  5583. void* juce_fileOpen (const String& path, bool forWriting) throw();
  5584. void juce_fileClose (void* handle) throw();
  5585. int juce_fileWrite (void* handle, const void* buffer, int size) throw();
  5586. void juce_fileFlush (void* handle) throw();
  5587. int64 juce_fileGetPosition (void* handle) throw();
  5588. int64 juce_fileSetPosition (void* handle, int64 pos) throw();
  5589. FileOutputStream::FileOutputStream (const File& f,
  5590. const int bufferSize_)
  5591. : file (f),
  5592. bufferSize (bufferSize_),
  5593. bytesInBuffer (0)
  5594. {
  5595. fileHandle = juce_fileOpen (f.getFullPathName(), true);
  5596. if (fileHandle != 0)
  5597. {
  5598. currentPosition = juce_fileGetPosition (fileHandle);
  5599. if (currentPosition < 0)
  5600. {
  5601. jassertfalse
  5602. juce_fileClose (fileHandle);
  5603. fileHandle = 0;
  5604. }
  5605. }
  5606. buffer = (char*) juce_malloc (jmax (bufferSize_, 16));
  5607. }
  5608. FileOutputStream::~FileOutputStream()
  5609. {
  5610. flush();
  5611. juce_fileClose (fileHandle);
  5612. juce_free (buffer);
  5613. }
  5614. int64 FileOutputStream::getPosition()
  5615. {
  5616. return currentPosition;
  5617. }
  5618. bool FileOutputStream::setPosition (int64 newPosition)
  5619. {
  5620. if (newPosition != currentPosition)
  5621. {
  5622. flush();
  5623. currentPosition = juce_fileSetPosition (fileHandle, newPosition);
  5624. }
  5625. return newPosition == currentPosition;
  5626. }
  5627. void FileOutputStream::flush()
  5628. {
  5629. if (bytesInBuffer > 0)
  5630. {
  5631. juce_fileWrite (fileHandle, buffer, bytesInBuffer);
  5632. bytesInBuffer = 0;
  5633. }
  5634. juce_fileFlush (fileHandle);
  5635. }
  5636. bool FileOutputStream::write (const void* const src, const int numBytes)
  5637. {
  5638. if (bytesInBuffer + numBytes < bufferSize)
  5639. {
  5640. memcpy (buffer + bytesInBuffer, src, numBytes);
  5641. bytesInBuffer += numBytes;
  5642. currentPosition += numBytes;
  5643. }
  5644. else
  5645. {
  5646. if (bytesInBuffer > 0)
  5647. {
  5648. // flush the reservoir
  5649. const bool wroteOk = (juce_fileWrite (fileHandle, buffer, bytesInBuffer) == bytesInBuffer);
  5650. bytesInBuffer = 0;
  5651. if (! wroteOk)
  5652. return false;
  5653. }
  5654. if (numBytes < bufferSize)
  5655. {
  5656. memcpy (buffer + bytesInBuffer, src, numBytes);
  5657. bytesInBuffer += numBytes;
  5658. currentPosition += numBytes;
  5659. }
  5660. else
  5661. {
  5662. const int bytesWritten = juce_fileWrite (fileHandle, src, numBytes);
  5663. currentPosition += bytesWritten;
  5664. return bytesWritten == numBytes;
  5665. }
  5666. }
  5667. return true;
  5668. }
  5669. END_JUCE_NAMESPACE
  5670. /********* End of inlined file: juce_FileOutputStream.cpp *********/
  5671. /********* Start of inlined file: juce_FileSearchPath.cpp *********/
  5672. BEGIN_JUCE_NAMESPACE
  5673. FileSearchPath::FileSearchPath()
  5674. {
  5675. }
  5676. FileSearchPath::FileSearchPath (const String& path)
  5677. {
  5678. init (path);
  5679. }
  5680. FileSearchPath::FileSearchPath (const FileSearchPath& other)
  5681. : directories (other.directories)
  5682. {
  5683. }
  5684. FileSearchPath::~FileSearchPath()
  5685. {
  5686. }
  5687. const FileSearchPath& FileSearchPath::operator= (const String& path)
  5688. {
  5689. init (path);
  5690. return *this;
  5691. }
  5692. void FileSearchPath::init (const String& path)
  5693. {
  5694. directories.clear();
  5695. directories.addTokens (path, T(";"), T("\""));
  5696. directories.trim();
  5697. directories.removeEmptyStrings();
  5698. for (int i = directories.size(); --i >= 0;)
  5699. directories.set (i, directories[i].unquoted());
  5700. }
  5701. int FileSearchPath::getNumPaths() const
  5702. {
  5703. return directories.size();
  5704. }
  5705. const File FileSearchPath::operator[] (const int index) const
  5706. {
  5707. return File (directories [index]);
  5708. }
  5709. const String FileSearchPath::toString() const
  5710. {
  5711. StringArray directories2 (directories);
  5712. for (int i = directories2.size(); --i >= 0;)
  5713. if (directories2[i].containsChar (T(';')))
  5714. directories2.set (i, directories2[i].quoted());
  5715. return directories2.joinIntoString (T(";"));
  5716. }
  5717. void FileSearchPath::add (const File& dir, const int insertIndex)
  5718. {
  5719. directories.insert (insertIndex, dir.getFullPathName());
  5720. }
  5721. void FileSearchPath::addIfNotAlreadyThere (const File& dir)
  5722. {
  5723. for (int i = 0; i < directories.size(); ++i)
  5724. if (File (directories[i]) == dir)
  5725. return;
  5726. add (dir);
  5727. }
  5728. void FileSearchPath::remove (const int index)
  5729. {
  5730. directories.remove (index);
  5731. }
  5732. void FileSearchPath::addPath (const FileSearchPath& other)
  5733. {
  5734. for (int i = 0; i < other.getNumPaths(); ++i)
  5735. addIfNotAlreadyThere (other[i]);
  5736. }
  5737. void FileSearchPath::removeRedundantPaths()
  5738. {
  5739. for (int i = directories.size(); --i >= 0;)
  5740. {
  5741. const File d1 (directories[i]);
  5742. for (int j = directories.size(); --j >= 0;)
  5743. {
  5744. const File d2 (directories[j]);
  5745. if ((i != j) && (d1.isAChildOf (d2) || d1 == d2))
  5746. {
  5747. directories.remove (i);
  5748. break;
  5749. }
  5750. }
  5751. }
  5752. }
  5753. void FileSearchPath::removeNonExistentPaths()
  5754. {
  5755. for (int i = directories.size(); --i >= 0;)
  5756. if (! File (directories[i]).isDirectory())
  5757. directories.remove (i);
  5758. }
  5759. int FileSearchPath::findChildFiles (OwnedArray<File>& results,
  5760. const int whatToLookFor,
  5761. const bool searchRecursively,
  5762. const String& wildCardPattern) const
  5763. {
  5764. int total = 0;
  5765. for (int i = 0; i < directories.size(); ++i)
  5766. total += operator[] (i).findChildFiles (results,
  5767. whatToLookFor,
  5768. searchRecursively,
  5769. wildCardPattern);
  5770. return total;
  5771. }
  5772. bool FileSearchPath::isFileInPath (const File& fileToCheck,
  5773. const bool checkRecursively) const
  5774. {
  5775. for (int i = directories.size(); --i >= 0;)
  5776. {
  5777. const File d (directories[i]);
  5778. if (checkRecursively)
  5779. {
  5780. if (fileToCheck.isAChildOf (d))
  5781. return true;
  5782. }
  5783. else
  5784. {
  5785. if (fileToCheck.getParentDirectory() == d)
  5786. return true;
  5787. }
  5788. }
  5789. return false;
  5790. }
  5791. END_JUCE_NAMESPACE
  5792. /********* End of inlined file: juce_FileSearchPath.cpp *********/
  5793. /********* Start of inlined file: juce_NamedPipe.cpp *********/
  5794. BEGIN_JUCE_NAMESPACE
  5795. NamedPipe::NamedPipe()
  5796. : internal (0)
  5797. {
  5798. }
  5799. NamedPipe::~NamedPipe()
  5800. {
  5801. close();
  5802. }
  5803. bool NamedPipe::openExisting (const String& pipeName)
  5804. {
  5805. currentPipeName = pipeName;
  5806. return openInternal (pipeName, false);
  5807. }
  5808. bool NamedPipe::createNewPipe (const String& pipeName)
  5809. {
  5810. currentPipeName = pipeName;
  5811. return openInternal (pipeName, true);
  5812. }
  5813. bool NamedPipe::isOpen() const throw()
  5814. {
  5815. return internal != 0;
  5816. }
  5817. const String NamedPipe::getName() const throw()
  5818. {
  5819. return currentPipeName;
  5820. }
  5821. // other methods for this class are implemented in the platform-specific files
  5822. END_JUCE_NAMESPACE
  5823. /********* End of inlined file: juce_NamedPipe.cpp *********/
  5824. /********* Start of inlined file: juce_Socket.cpp *********/
  5825. #ifdef _WIN32
  5826. #include <winsock2.h>
  5827. #ifdef _MSC_VER
  5828. #pragma warning (disable : 4127 4389 4018)
  5829. #endif
  5830. #else
  5831. #if defined (LINUX) || defined (__linux__)
  5832. #include <sys/types.h>
  5833. #include <sys/socket.h>
  5834. #include <sys/errno.h>
  5835. #include <unistd.h>
  5836. #include <netinet/in.h>
  5837. #else
  5838. #if MACOSX_DEPLOYMENT_TARGET <= MAC_OS_X_VERSION_10_4
  5839. #include <CoreServices/CoreServices.h>
  5840. #endif
  5841. #endif
  5842. #include <fcntl.h>
  5843. #include <netdb.h>
  5844. #include <arpa/inet.h>
  5845. #include <netinet/tcp.h>
  5846. #endif
  5847. BEGIN_JUCE_NAMESPACE
  5848. #if JUCE_WIN32
  5849. typedef int (__stdcall juce_CloseWin32SocketLibCall) (void);
  5850. juce_CloseWin32SocketLibCall* juce_CloseWin32SocketLib = 0;
  5851. static void initWin32Sockets()
  5852. {
  5853. static CriticalSection lock;
  5854. const ScopedLock sl (lock);
  5855. if (juce_CloseWin32SocketLib == 0)
  5856. {
  5857. WSADATA wsaData;
  5858. const WORD wVersionRequested = MAKEWORD (1, 1);
  5859. WSAStartup (wVersionRequested, &wsaData);
  5860. juce_CloseWin32SocketLib = &WSACleanup;
  5861. }
  5862. }
  5863. #endif
  5864. static bool resetSocketOptions (const int handle, const bool isDatagram, const bool allowBroadcast) throw()
  5865. {
  5866. const int sndBufSize = 65536;
  5867. const int rcvBufSize = 65536;
  5868. const int one = 1;
  5869. return handle > 0
  5870. && setsockopt (handle, SOL_SOCKET, SO_RCVBUF, (const char*) &rcvBufSize, sizeof (rcvBufSize)) == 0
  5871. && setsockopt (handle, SOL_SOCKET, SO_SNDBUF, (const char*) &sndBufSize, sizeof (sndBufSize)) == 0
  5872. && (isDatagram ? ((! allowBroadcast) || setsockopt (handle, SOL_SOCKET, SO_BROADCAST, (const char*) &one, sizeof (one)) == 0)
  5873. : (setsockopt (handle, IPPROTO_TCP, TCP_NODELAY, (const char*) &one, sizeof (one)) == 0));
  5874. }
  5875. static bool bindSocketToPort (const int handle, const int port) throw()
  5876. {
  5877. if (handle <= 0 || port <= 0)
  5878. return false;
  5879. struct sockaddr_in servTmpAddr;
  5880. zerostruct (servTmpAddr);
  5881. servTmpAddr.sin_family = PF_INET;
  5882. servTmpAddr.sin_addr.s_addr = htonl (INADDR_ANY);
  5883. servTmpAddr.sin_port = htons ((uint16) port);
  5884. return bind (handle, (struct sockaddr*) &servTmpAddr, sizeof (struct sockaddr_in)) >= 0;
  5885. }
  5886. static int readSocket (const int handle,
  5887. void* const destBuffer, const int maxBytesToRead,
  5888. bool volatile& connected,
  5889. const bool blockUntilSpecifiedAmountHasArrived) throw()
  5890. {
  5891. int bytesRead = 0;
  5892. while (bytesRead < maxBytesToRead)
  5893. {
  5894. int bytesThisTime;
  5895. #if JUCE_WIN32
  5896. bytesThisTime = recv (handle, ((char*) destBuffer) + bytesRead, maxBytesToRead - bytesRead, 0);
  5897. #else
  5898. while ((bytesThisTime = ::read (handle, ((char*) destBuffer) + bytesRead, maxBytesToRead - bytesRead)) < 0
  5899. && errno == EINTR
  5900. && connected)
  5901. {
  5902. }
  5903. #endif
  5904. if (bytesThisTime <= 0 || ! connected)
  5905. {
  5906. if (bytesRead == 0)
  5907. bytesRead = -1;
  5908. break;
  5909. }
  5910. bytesRead += bytesThisTime;
  5911. if (! blockUntilSpecifiedAmountHasArrived)
  5912. break;
  5913. }
  5914. return bytesRead;
  5915. }
  5916. static int waitForReadiness (const int handle, const bool forReading,
  5917. const int timeoutMsecs) throw()
  5918. {
  5919. struct timeval timeout;
  5920. struct timeval* timeoutp;
  5921. if (timeoutMsecs >= 0)
  5922. {
  5923. timeout.tv_sec = timeoutMsecs / 1000;
  5924. timeout.tv_usec = (timeoutMsecs % 1000) * 1000;
  5925. timeoutp = &timeout;
  5926. }
  5927. else
  5928. {
  5929. timeoutp = 0;
  5930. }
  5931. fd_set rset, wset;
  5932. FD_ZERO (&rset);
  5933. FD_SET (handle, &rset);
  5934. FD_ZERO (&wset);
  5935. FD_SET (handle, &wset);
  5936. fd_set* const prset = forReading ? &rset : 0;
  5937. fd_set* const pwset = forReading ? 0 : &wset;
  5938. #if JUCE_WIN32
  5939. if (select (handle + 1, prset, pwset, 0, timeoutp) < 0)
  5940. return -1;
  5941. #else
  5942. {
  5943. int result;
  5944. while ((result = select (handle + 1, prset, pwset, 0, timeoutp)) < 0
  5945. && errno == EINTR)
  5946. {
  5947. }
  5948. if (result < 0)
  5949. return -1;
  5950. }
  5951. #endif
  5952. {
  5953. int opt;
  5954. #if defined (JUCE_LINUX) || defined (JUCE_MAC)
  5955. socklen_t len = sizeof (opt);
  5956. #else
  5957. int len = sizeof (opt);
  5958. #endif
  5959. if (getsockopt (handle, SOL_SOCKET, SO_ERROR, (char*) &opt, &len) < 0
  5960. || opt != 0)
  5961. return -1;
  5962. }
  5963. if ((forReading && FD_ISSET (handle, &rset))
  5964. || ((! forReading) && FD_ISSET (handle, &wset)))
  5965. return 1;
  5966. return 0;
  5967. }
  5968. static bool setSocketBlockingState (const int handle, const bool shouldBlock) throw()
  5969. {
  5970. #if JUCE_WIN32
  5971. u_long nonBlocking = shouldBlock ? 0 : 1;
  5972. if (ioctlsocket (handle, FIONBIO, &nonBlocking) != 0)
  5973. return false;
  5974. #else
  5975. int socketFlags = fcntl (handle, F_GETFL, 0);
  5976. if (socketFlags == -1)
  5977. return false;
  5978. if (shouldBlock)
  5979. socketFlags &= ~O_NONBLOCK;
  5980. else
  5981. socketFlags |= O_NONBLOCK;
  5982. if (fcntl (handle, F_SETFL, socketFlags) != 0)
  5983. return false;
  5984. #endif
  5985. return true;
  5986. }
  5987. static bool connectSocket (int volatile& handle,
  5988. const bool isDatagram,
  5989. void** serverAddress,
  5990. const String& hostName,
  5991. const int portNumber,
  5992. const int timeOutMillisecs) throw()
  5993. {
  5994. struct hostent* const hostEnt = gethostbyname (hostName);
  5995. if (hostEnt == 0)
  5996. return false;
  5997. struct in_addr targetAddress;
  5998. memcpy (&targetAddress.s_addr,
  5999. *(hostEnt->h_addr_list),
  6000. sizeof (targetAddress.s_addr));
  6001. struct sockaddr_in servTmpAddr;
  6002. zerostruct (servTmpAddr);
  6003. servTmpAddr.sin_family = PF_INET;
  6004. servTmpAddr.sin_addr = targetAddress;
  6005. servTmpAddr.sin_port = htons ((uint16) portNumber);
  6006. if (handle < 0)
  6007. handle = (int) socket (AF_INET, isDatagram ? SOCK_DGRAM : SOCK_STREAM, 0);
  6008. if (handle < 0)
  6009. return false;
  6010. if (isDatagram)
  6011. {
  6012. *serverAddress = new struct sockaddr_in();
  6013. *((struct sockaddr_in*) *serverAddress) = servTmpAddr;
  6014. return true;
  6015. }
  6016. setSocketBlockingState (handle, false);
  6017. const int result = ::connect (handle, (struct sockaddr*) &servTmpAddr, sizeof (struct sockaddr_in));
  6018. if (result < 0)
  6019. {
  6020. #if JUCE_WIN32
  6021. if (result == SOCKET_ERROR && WSAGetLastError() == WSAEWOULDBLOCK)
  6022. #else
  6023. if (errno == EINPROGRESS)
  6024. #endif
  6025. {
  6026. if (waitForReadiness (handle, false, timeOutMillisecs) != 1)
  6027. {
  6028. setSocketBlockingState (handle, true);
  6029. return false;
  6030. }
  6031. }
  6032. }
  6033. setSocketBlockingState (handle, true);
  6034. resetSocketOptions (handle, false, false);
  6035. return true;
  6036. }
  6037. StreamingSocket::StreamingSocket()
  6038. : portNumber (0),
  6039. handle (-1),
  6040. connected (false),
  6041. isListener (false)
  6042. {
  6043. #if JUCE_WIN32
  6044. initWin32Sockets();
  6045. #endif
  6046. }
  6047. StreamingSocket::StreamingSocket (const String& hostName_,
  6048. const int portNumber_,
  6049. const int handle_)
  6050. : hostName (hostName_),
  6051. portNumber (portNumber_),
  6052. handle (handle_),
  6053. connected (true),
  6054. isListener (false)
  6055. {
  6056. #if JUCE_WIN32
  6057. initWin32Sockets();
  6058. #endif
  6059. resetSocketOptions (handle_, false, false);
  6060. }
  6061. StreamingSocket::~StreamingSocket()
  6062. {
  6063. close();
  6064. }
  6065. int StreamingSocket::read (void* destBuffer, const int maxBytesToRead, const bool blockUntilSpecifiedAmountHasArrived)
  6066. {
  6067. return (connected && ! isListener) ? readSocket (handle, destBuffer, maxBytesToRead, connected, blockUntilSpecifiedAmountHasArrived)
  6068. : -1;
  6069. }
  6070. int StreamingSocket::write (const void* sourceBuffer, const int numBytesToWrite)
  6071. {
  6072. if (isListener || ! connected)
  6073. return -1;
  6074. #if JUCE_WIN32
  6075. return send (handle, (const char*) sourceBuffer, numBytesToWrite, 0);
  6076. #else
  6077. int result;
  6078. while ((result = ::write (handle, sourceBuffer, numBytesToWrite)) < 0
  6079. && errno == EINTR)
  6080. {
  6081. }
  6082. return result;
  6083. #endif
  6084. }
  6085. int StreamingSocket::waitUntilReady (const bool readyForReading,
  6086. const int timeoutMsecs) const
  6087. {
  6088. return connected ? waitForReadiness (handle, readyForReading, timeoutMsecs)
  6089. : -1;
  6090. }
  6091. bool StreamingSocket::bindToPort (const int port)
  6092. {
  6093. return bindSocketToPort (handle, port);
  6094. }
  6095. bool StreamingSocket::connect (const String& remoteHostName,
  6096. const int remotePortNumber,
  6097. const int timeOutMillisecs)
  6098. {
  6099. if (isListener)
  6100. {
  6101. jassertfalse // a listener socket can't connect to another one!
  6102. return false;
  6103. }
  6104. if (connected)
  6105. close();
  6106. hostName = remoteHostName;
  6107. portNumber = remotePortNumber;
  6108. isListener = false;
  6109. connected = connectSocket (handle, false, 0, remoteHostName,
  6110. remotePortNumber, timeOutMillisecs);
  6111. if (! (connected && resetSocketOptions (handle, false, false)))
  6112. {
  6113. close();
  6114. return false;
  6115. }
  6116. return true;
  6117. }
  6118. void StreamingSocket::close()
  6119. {
  6120. #if JUCE_WIN32
  6121. closesocket (handle);
  6122. connected = false;
  6123. #else
  6124. if (connected)
  6125. {
  6126. connected = false;
  6127. if (isListener)
  6128. {
  6129. // need to do this to interrupt the accept() function..
  6130. StreamingSocket temp;
  6131. temp.connect ("localhost", portNumber, 1000);
  6132. }
  6133. }
  6134. ::close (handle);
  6135. #endif
  6136. hostName = String::empty;
  6137. portNumber = 0;
  6138. handle = -1;
  6139. isListener = false;
  6140. }
  6141. bool StreamingSocket::createListener (const int newPortNumber)
  6142. {
  6143. if (connected)
  6144. close();
  6145. hostName = "listener";
  6146. portNumber = newPortNumber;
  6147. isListener = true;
  6148. struct sockaddr_in servTmpAddr;
  6149. zerostruct (servTmpAddr);
  6150. servTmpAddr.sin_family = PF_INET;
  6151. servTmpAddr.sin_addr.s_addr = htonl (INADDR_ANY);
  6152. servTmpAddr.sin_port = htons ((uint16) portNumber);
  6153. handle = (int) socket (AF_INET, SOCK_STREAM, 0);
  6154. if (handle < 0)
  6155. return false;
  6156. const int reuse = 1;
  6157. setsockopt (handle, SOL_SOCKET, SO_REUSEADDR, (const char*) &reuse, sizeof (reuse));
  6158. if (bind (handle, (struct sockaddr*) &servTmpAddr, sizeof (struct sockaddr_in)) < 0
  6159. || listen (handle, SOMAXCONN) < 0)
  6160. {
  6161. close();
  6162. return false;
  6163. }
  6164. connected = true;
  6165. return true;
  6166. }
  6167. StreamingSocket* StreamingSocket::waitForNextConnection() const
  6168. {
  6169. jassert (isListener || ! connected); // to call this method, you first have to use createListener() to
  6170. // prepare this socket as a listener.
  6171. if (connected && isListener)
  6172. {
  6173. struct sockaddr address;
  6174. #if defined (JUCE_LINUX) || defined (JUCE_MAC)
  6175. socklen_t len = sizeof (sockaddr);
  6176. #else
  6177. int len = sizeof (sockaddr);
  6178. #endif
  6179. const int newSocket = (int) accept (handle, &address, &len);
  6180. if (newSocket >= 0 && connected)
  6181. return new StreamingSocket (inet_ntoa (((struct sockaddr_in*) &address)->sin_addr),
  6182. portNumber, newSocket);
  6183. }
  6184. return 0;
  6185. }
  6186. bool StreamingSocket::isLocal() const throw()
  6187. {
  6188. return hostName == T("127.0.0.1");
  6189. }
  6190. DatagramSocket::DatagramSocket (const int localPortNumber, const bool allowBroadcast_)
  6191. : portNumber (0),
  6192. handle (-1),
  6193. connected (true),
  6194. allowBroadcast (allowBroadcast_),
  6195. serverAddress (0)
  6196. {
  6197. #if JUCE_WIN32
  6198. initWin32Sockets();
  6199. #endif
  6200. handle = (int) socket (AF_INET, SOCK_DGRAM, 0);
  6201. bindToPort (localPortNumber);
  6202. }
  6203. DatagramSocket::DatagramSocket (const String& hostName_, const int portNumber_,
  6204. const int handle_, const int localPortNumber)
  6205. : hostName (hostName_),
  6206. portNumber (portNumber_),
  6207. handle (handle_),
  6208. connected (true),
  6209. allowBroadcast (false),
  6210. serverAddress (0)
  6211. {
  6212. #if JUCE_WIN32
  6213. initWin32Sockets();
  6214. #endif
  6215. resetSocketOptions (handle_, true, allowBroadcast);
  6216. bindToPort (localPortNumber);
  6217. }
  6218. DatagramSocket::~DatagramSocket()
  6219. {
  6220. close();
  6221. delete ((struct sockaddr_in*) serverAddress);
  6222. serverAddress = 0;
  6223. }
  6224. void DatagramSocket::close()
  6225. {
  6226. #if JUCE_WIN32
  6227. closesocket (handle);
  6228. connected = false;
  6229. #else
  6230. connected = false;
  6231. ::close (handle);
  6232. #endif
  6233. hostName = String::empty;
  6234. portNumber = 0;
  6235. handle = -1;
  6236. }
  6237. bool DatagramSocket::bindToPort (const int port)
  6238. {
  6239. return bindSocketToPort (handle, port);
  6240. }
  6241. bool DatagramSocket::connect (const String& remoteHostName,
  6242. const int remotePortNumber,
  6243. const int timeOutMillisecs)
  6244. {
  6245. if (connected)
  6246. close();
  6247. hostName = remoteHostName;
  6248. portNumber = remotePortNumber;
  6249. connected = connectSocket (handle, true, &serverAddress,
  6250. remoteHostName, remotePortNumber,
  6251. timeOutMillisecs);
  6252. if (! (connected && resetSocketOptions (handle, true, allowBroadcast)))
  6253. {
  6254. close();
  6255. return false;
  6256. }
  6257. return true;
  6258. }
  6259. DatagramSocket* DatagramSocket::waitForNextConnection() const
  6260. {
  6261. struct sockaddr address;
  6262. #if defined (JUCE_LINUX) || defined (JUCE_MAC)
  6263. socklen_t len = sizeof (sockaddr);
  6264. #else
  6265. int len = sizeof (sockaddr);
  6266. #endif
  6267. while (waitUntilReady (true, -1) == 1)
  6268. {
  6269. char buf[1];
  6270. if (recvfrom (handle, buf, 0, 0, &address, &len) > 0)
  6271. {
  6272. return new DatagramSocket (inet_ntoa (((struct sockaddr_in*) &address)->sin_addr),
  6273. ntohs (((struct sockaddr_in*) &address)->sin_port),
  6274. -1, -1);
  6275. }
  6276. }
  6277. return 0;
  6278. }
  6279. int DatagramSocket::waitUntilReady (const bool readyForReading,
  6280. const int timeoutMsecs) const
  6281. {
  6282. return connected ? waitForReadiness (handle, readyForReading, timeoutMsecs)
  6283. : -1;
  6284. }
  6285. int DatagramSocket::read (void* destBuffer, const int maxBytesToRead, const bool blockUntilSpecifiedAmountHasArrived)
  6286. {
  6287. return connected ? readSocket (handle, destBuffer, maxBytesToRead, connected, blockUntilSpecifiedAmountHasArrived)
  6288. : -1;
  6289. }
  6290. int DatagramSocket::write (const void* sourceBuffer, const int numBytesToWrite)
  6291. {
  6292. // You need to call connect() first to set the server address..
  6293. jassert (serverAddress != 0 && connected);
  6294. return connected ? sendto (handle, (const char*) sourceBuffer,
  6295. numBytesToWrite, 0,
  6296. (const struct sockaddr*) serverAddress,
  6297. sizeof (struct sockaddr_in))
  6298. : -1;
  6299. }
  6300. bool DatagramSocket::isLocal() const throw()
  6301. {
  6302. return hostName == T("127.0.0.1");
  6303. }
  6304. END_JUCE_NAMESPACE
  6305. /********* End of inlined file: juce_Socket.cpp *********/
  6306. /********* Start of inlined file: juce_URL.cpp *********/
  6307. BEGIN_JUCE_NAMESPACE
  6308. URL::URL() throw()
  6309. {
  6310. }
  6311. URL::URL (const String& url_)
  6312. : url (url_)
  6313. {
  6314. int i = url.indexOfChar (T('?'));
  6315. if (i >= 0)
  6316. {
  6317. do
  6318. {
  6319. const int nextAmp = url.indexOfChar (i + 1, T('&'));
  6320. const int equalsPos = url.indexOfChar (i + 1, T('='));
  6321. if (equalsPos > i + 1)
  6322. {
  6323. if (nextAmp < 0)
  6324. {
  6325. parameters.set (removeEscapeChars (url.substring (i + 1, equalsPos)),
  6326. removeEscapeChars (url.substring (equalsPos + 1)));
  6327. }
  6328. else if (nextAmp > 0 && equalsPos < nextAmp)
  6329. {
  6330. parameters.set (removeEscapeChars (url.substring (i + 1, equalsPos)),
  6331. removeEscapeChars (url.substring (equalsPos + 1, nextAmp)));
  6332. }
  6333. }
  6334. i = nextAmp;
  6335. }
  6336. while (i >= 0);
  6337. url = url.upToFirstOccurrenceOf (T("?"), false, false);
  6338. }
  6339. }
  6340. URL::URL (const URL& other)
  6341. : url (other.url),
  6342. postData (other.postData),
  6343. parameters (other.parameters),
  6344. filesToUpload (other.filesToUpload),
  6345. mimeTypes (other.mimeTypes)
  6346. {
  6347. }
  6348. const URL& URL::operator= (const URL& other)
  6349. {
  6350. url = other.url;
  6351. postData = other.postData;
  6352. parameters = other.parameters;
  6353. filesToUpload = other.filesToUpload;
  6354. mimeTypes = other.mimeTypes;
  6355. return *this;
  6356. }
  6357. URL::~URL() throw()
  6358. {
  6359. }
  6360. static const String getMangledParameters (const StringPairArray& parameters)
  6361. {
  6362. String p;
  6363. for (int i = 0; i < parameters.size(); ++i)
  6364. {
  6365. if (i > 0)
  6366. p += T("&");
  6367. p << URL::addEscapeChars (parameters.getAllKeys() [i], true)
  6368. << T("=")
  6369. << URL::addEscapeChars (parameters.getAllValues() [i], true);
  6370. }
  6371. return p;
  6372. }
  6373. const String URL::toString (const bool includeGetParameters) const
  6374. {
  6375. if (includeGetParameters && parameters.size() > 0)
  6376. return url + T("?") + getMangledParameters (parameters);
  6377. else
  6378. return url;
  6379. }
  6380. bool URL::isWellFormed() const
  6381. {
  6382. //xxx TODO
  6383. return url.isNotEmpty();
  6384. }
  6385. static int findStartOfDomain (const String& url)
  6386. {
  6387. int i = 0;
  6388. while (CharacterFunctions::isLetterOrDigit (url[i])
  6389. || CharacterFunctions::indexOfChar (T("+-."), url[i], false) >= 0)
  6390. ++i;
  6391. return url[i] == T(':') ? i + 1 : 0;
  6392. }
  6393. const String URL::getDomain() const
  6394. {
  6395. int start = findStartOfDomain (url);
  6396. while (url[start] == T('/'))
  6397. ++start;
  6398. const int end1 = url.indexOfChar (start, T('/'));
  6399. const int end2 = url.indexOfChar (start, T(':'));
  6400. const int end = (end1 < 0 || end2 < 0) ? jmax (end1, end2)
  6401. : jmin (end1, end2);
  6402. return url.substring (start, end);
  6403. }
  6404. const String URL::getSubPath() const
  6405. {
  6406. int start = findStartOfDomain (url);
  6407. while (url[start] == T('/'))
  6408. ++start;
  6409. const int startOfPath = url.indexOfChar (start, T('/')) + 1;
  6410. return startOfPath <= 0 ? String::empty
  6411. : url.substring (startOfPath);
  6412. }
  6413. const String URL::getScheme() const
  6414. {
  6415. return url.substring (0, findStartOfDomain (url) - 1);
  6416. }
  6417. const URL URL::withNewSubPath (const String& newPath) const
  6418. {
  6419. int start = findStartOfDomain (url);
  6420. while (url[start] == T('/'))
  6421. ++start;
  6422. const int startOfPath = url.indexOfChar (start, T('/')) + 1;
  6423. URL u (*this);
  6424. if (startOfPath > 0)
  6425. u.url = url.substring (0, startOfPath);
  6426. if (! u.url.endsWithChar (T('/')))
  6427. u.url << '/';
  6428. if (newPath.startsWithChar (T('/')))
  6429. u.url << newPath.substring (1);
  6430. else
  6431. u.url << newPath;
  6432. return u;
  6433. }
  6434. bool URL::isProbablyAWebsiteURL (const String& possibleURL)
  6435. {
  6436. if (possibleURL.startsWithIgnoreCase (T("http:"))
  6437. || possibleURL.startsWithIgnoreCase (T("ftp:")))
  6438. return true;
  6439. if (possibleURL.startsWithIgnoreCase (T("file:"))
  6440. || possibleURL.containsChar (T('@'))
  6441. || possibleURL.endsWithChar (T('.'))
  6442. || (! possibleURL.containsChar (T('.'))))
  6443. return false;
  6444. if (possibleURL.startsWithIgnoreCase (T("www."))
  6445. && possibleURL.substring (5).containsChar (T('.')))
  6446. return true;
  6447. const char* commonTLDs[] = { "com", "net", "org", "uk", "de", "fr", "jp" };
  6448. for (int i = 0; i < numElementsInArray (commonTLDs); ++i)
  6449. if ((possibleURL + T("/")).containsIgnoreCase (T(".") + String (commonTLDs[i]) + T("/")))
  6450. return true;
  6451. return false;
  6452. }
  6453. bool URL::isProbablyAnEmailAddress (const String& possibleEmailAddress)
  6454. {
  6455. const int atSign = possibleEmailAddress.indexOfChar (T('@'));
  6456. return atSign > 0
  6457. && possibleEmailAddress.lastIndexOfChar (T('.')) > (atSign + 1)
  6458. && (! possibleEmailAddress.endsWithChar (T('.')));
  6459. }
  6460. void* juce_openInternetFile (const String& url,
  6461. const String& headers,
  6462. const MemoryBlock& optionalPostData,
  6463. const bool isPost,
  6464. URL::OpenStreamProgressCallback* callback,
  6465. void* callbackContext,
  6466. int timeOutMs);
  6467. void juce_closeInternetFile (void* handle);
  6468. int juce_readFromInternetFile (void* handle, void* dest, int bytesToRead);
  6469. int juce_seekInInternetFile (void* handle, int newPosition);
  6470. int64 juce_getInternetFileContentLength (void* handle);
  6471. class WebInputStream : public InputStream
  6472. {
  6473. public:
  6474. WebInputStream (const URL& url,
  6475. const bool isPost_,
  6476. URL::OpenStreamProgressCallback* const progressCallback_,
  6477. void* const progressCallbackContext_,
  6478. const String& extraHeaders,
  6479. int timeOutMs_)
  6480. : position (0),
  6481. finished (false),
  6482. isPost (isPost_),
  6483. progressCallback (progressCallback_),
  6484. progressCallbackContext (progressCallbackContext_),
  6485. timeOutMs (timeOutMs_)
  6486. {
  6487. server = url.toString (! isPost);
  6488. if (isPost_)
  6489. createHeadersAndPostData (url);
  6490. headers += extraHeaders;
  6491. if (! headers.endsWithChar (T('\n')))
  6492. headers << "\r\n";
  6493. handle = juce_openInternetFile (server, headers, postData, isPost,
  6494. progressCallback_, progressCallbackContext_,
  6495. timeOutMs);
  6496. }
  6497. ~WebInputStream()
  6498. {
  6499. juce_closeInternetFile (handle);
  6500. }
  6501. bool isError() const throw()
  6502. {
  6503. return handle == 0;
  6504. }
  6505. int64 getTotalLength()
  6506. {
  6507. return juce_getInternetFileContentLength (handle);
  6508. }
  6509. bool isExhausted()
  6510. {
  6511. return finished;
  6512. }
  6513. int read (void* dest, int bytes)
  6514. {
  6515. if (finished || isError())
  6516. {
  6517. return 0;
  6518. }
  6519. else
  6520. {
  6521. const int bytesRead = juce_readFromInternetFile (handle, dest, bytes);
  6522. position += bytesRead;
  6523. if (bytesRead == 0)
  6524. finished = true;
  6525. return bytesRead;
  6526. }
  6527. }
  6528. int64 getPosition()
  6529. {
  6530. return position;
  6531. }
  6532. bool setPosition (int64 wantedPos)
  6533. {
  6534. if (wantedPos != position)
  6535. {
  6536. finished = false;
  6537. const int actualPos = juce_seekInInternetFile (handle, (int) wantedPos);
  6538. if (actualPos == wantedPos)
  6539. {
  6540. position = wantedPos;
  6541. }
  6542. else
  6543. {
  6544. if (wantedPos < position)
  6545. {
  6546. juce_closeInternetFile (handle);
  6547. position = 0;
  6548. finished = false;
  6549. handle = juce_openInternetFile (server, headers, postData, isPost,
  6550. progressCallback, progressCallbackContext,
  6551. timeOutMs);
  6552. }
  6553. skipNextBytes (wantedPos - position);
  6554. }
  6555. }
  6556. return true;
  6557. }
  6558. juce_UseDebuggingNewOperator
  6559. private:
  6560. String server, headers;
  6561. MemoryBlock postData;
  6562. int64 position;
  6563. bool finished;
  6564. const bool isPost;
  6565. void* handle;
  6566. URL::OpenStreamProgressCallback* const progressCallback;
  6567. void* const progressCallbackContext;
  6568. const int timeOutMs;
  6569. void createHeadersAndPostData (const URL& url)
  6570. {
  6571. if (url.getFilesToUpload().size() > 0)
  6572. {
  6573. // need to upload some files, so do it as multi-part...
  6574. String boundary (String::toHexString (Random::getSystemRandom().nextInt64()));
  6575. headers << "Content-Type: multipart/form-data; boundary=" << boundary << "\r\n";
  6576. appendUTF8ToPostData ("--" + boundary);
  6577. int i;
  6578. for (i = 0; i < url.getParameters().size(); ++i)
  6579. {
  6580. String s;
  6581. s << "\r\nContent-Disposition: form-data; name=\""
  6582. << url.getParameters().getAllKeys() [i]
  6583. << "\"\r\n\r\n"
  6584. << url.getParameters().getAllValues() [i]
  6585. << "\r\n--"
  6586. << boundary;
  6587. appendUTF8ToPostData (s);
  6588. }
  6589. for (i = 0; i < url.getFilesToUpload().size(); ++i)
  6590. {
  6591. const File f (url.getFilesToUpload().getAllValues() [i]);
  6592. const String paramName (url.getFilesToUpload().getAllKeys() [i]);
  6593. String s;
  6594. s << "\r\nContent-Disposition: form-data; name=\""
  6595. << paramName
  6596. << "\"; filename=\""
  6597. << f.getFileName()
  6598. << "\"\r\n";
  6599. const String mimeType (url.getMimeTypesOfUploadFiles()
  6600. .getValue (paramName, String::empty));
  6601. if (mimeType.isNotEmpty())
  6602. s << "Content-Type: " << mimeType << "\r\n";
  6603. s << "Content-Transfer-Encoding: binary\r\n\r\n";
  6604. appendUTF8ToPostData (s);
  6605. f.loadFileAsData (postData);
  6606. s = "\r\n--" + boundary;
  6607. appendUTF8ToPostData (s);
  6608. }
  6609. appendUTF8ToPostData ("--\r\n");
  6610. }
  6611. else
  6612. {
  6613. appendUTF8ToPostData (getMangledParameters (url.getParameters()));
  6614. appendUTF8ToPostData (url.getPostData());
  6615. // just a short text attachment, so use simple url encoding..
  6616. headers = "Content-Type: application/x-www-form-urlencoded\r\nContent-length: "
  6617. + String (postData.getSize())
  6618. + "\r\n";
  6619. }
  6620. }
  6621. void appendUTF8ToPostData (const String& text) throw()
  6622. {
  6623. postData.append (text.toUTF8(),
  6624. (int) strlen (text.toUTF8()));
  6625. }
  6626. WebInputStream (const WebInputStream&);
  6627. const WebInputStream& operator= (const WebInputStream&);
  6628. };
  6629. InputStream* URL::createInputStream (const bool usePostCommand,
  6630. OpenStreamProgressCallback* const progressCallback,
  6631. void* const progressCallbackContext,
  6632. const String& extraHeaders,
  6633. const int timeOutMs) const
  6634. {
  6635. WebInputStream* wi = new WebInputStream (*this, usePostCommand,
  6636. progressCallback, progressCallbackContext,
  6637. extraHeaders,
  6638. timeOutMs);
  6639. if (wi->isError())
  6640. {
  6641. delete wi;
  6642. wi = 0;
  6643. }
  6644. return wi;
  6645. }
  6646. bool URL::readEntireBinaryStream (MemoryBlock& destData,
  6647. const bool usePostCommand) const
  6648. {
  6649. InputStream* const in = createInputStream (usePostCommand);
  6650. if (in != 0)
  6651. {
  6652. in->readIntoMemoryBlock (destData, -1);
  6653. delete in;
  6654. return true;
  6655. }
  6656. return false;
  6657. }
  6658. const String URL::readEntireTextStream (const bool usePostCommand) const
  6659. {
  6660. String result;
  6661. InputStream* const in = createInputStream (usePostCommand);
  6662. if (in != 0)
  6663. {
  6664. result = in->readEntireStreamAsString();
  6665. delete in;
  6666. }
  6667. return result;
  6668. }
  6669. XmlElement* URL::readEntireXmlStream (const bool usePostCommand) const
  6670. {
  6671. XmlDocument doc (readEntireTextStream (usePostCommand));
  6672. return doc.getDocumentElement();
  6673. }
  6674. const URL URL::withParameter (const String& parameterName,
  6675. const String& parameterValue) const
  6676. {
  6677. URL u (*this);
  6678. u.parameters.set (parameterName, parameterValue);
  6679. return u;
  6680. }
  6681. const URL URL::withFileToUpload (const String& parameterName,
  6682. const File& fileToUpload,
  6683. const String& mimeType) const
  6684. {
  6685. URL u (*this);
  6686. u.filesToUpload.set (parameterName, fileToUpload.getFullPathName());
  6687. u.mimeTypes.set (parameterName, mimeType);
  6688. return u;
  6689. }
  6690. const URL URL::withPOSTData (const String& postData_) const
  6691. {
  6692. URL u (*this);
  6693. u.postData = postData_;
  6694. return u;
  6695. }
  6696. const StringPairArray& URL::getParameters() const throw()
  6697. {
  6698. return parameters;
  6699. }
  6700. const StringPairArray& URL::getFilesToUpload() const throw()
  6701. {
  6702. return filesToUpload;
  6703. }
  6704. const StringPairArray& URL::getMimeTypesOfUploadFiles() const throw()
  6705. {
  6706. return mimeTypes;
  6707. }
  6708. const String URL::removeEscapeChars (const String& s)
  6709. {
  6710. const int len = s.length();
  6711. uint8* const resultUTF8 = (uint8*) juce_calloc (len * 4);
  6712. uint8* r = resultUTF8;
  6713. for (int i = 0; i < len; ++i)
  6714. {
  6715. char c = (char) s[i];
  6716. if (c == 0)
  6717. break;
  6718. if (c == '+')
  6719. {
  6720. c = ' ';
  6721. }
  6722. else if (c == '%')
  6723. {
  6724. c = (char) s.substring (i + 1, i + 3).getHexValue32();
  6725. i += 2;
  6726. }
  6727. *r++ = c;
  6728. }
  6729. const String stringResult (String::fromUTF8 (resultUTF8));
  6730. juce_free (resultUTF8);
  6731. return stringResult;
  6732. }
  6733. const String URL::addEscapeChars (const String& s, const bool isParameter)
  6734. {
  6735. String result;
  6736. result.preallocateStorage (s.length() + 8);
  6737. const char* utf8 = s.toUTF8();
  6738. const char* legalChars = isParameter ? "_-.*!'()"
  6739. : "_-$.*!'(),";
  6740. while (*utf8 != 0)
  6741. {
  6742. const char c = *utf8++;
  6743. if (CharacterFunctions::isLetterOrDigit (c)
  6744. || CharacterFunctions::indexOfChar (legalChars, c, false) >= 0)
  6745. {
  6746. result << c;
  6747. }
  6748. else
  6749. {
  6750. const int v = (int) (uint8) c;
  6751. if (v < 0x10)
  6752. result << T("%0");
  6753. else
  6754. result << T('%');
  6755. result << String::toHexString (v);
  6756. }
  6757. }
  6758. return result;
  6759. }
  6760. extern bool juce_launchFile (const String& fileName,
  6761. const String& parameters) throw();
  6762. bool URL::launchInDefaultBrowser() const
  6763. {
  6764. String u (toString (true));
  6765. if (u.contains (T("@")) && ! u.contains (T(":")))
  6766. u = "mailto:" + u;
  6767. return juce_launchFile (u, String::empty);
  6768. }
  6769. END_JUCE_NAMESPACE
  6770. /********* End of inlined file: juce_URL.cpp *********/
  6771. /********* Start of inlined file: juce_BufferedInputStream.cpp *********/
  6772. BEGIN_JUCE_NAMESPACE
  6773. BufferedInputStream::BufferedInputStream (InputStream* const source_,
  6774. const int bufferSize_,
  6775. const bool deleteSourceWhenDestroyed_) throw()
  6776. : source (source_),
  6777. deleteSourceWhenDestroyed (deleteSourceWhenDestroyed_),
  6778. bufferSize (jmax (256, bufferSize_)),
  6779. position (source_->getPosition()),
  6780. lastReadPos (0),
  6781. bufferOverlap (128)
  6782. {
  6783. const int sourceSize = (int) source_->getTotalLength();
  6784. if (sourceSize >= 0)
  6785. bufferSize = jmin (jmax (32, sourceSize), bufferSize);
  6786. bufferStart = position;
  6787. buffer = (char*) juce_malloc (bufferSize);
  6788. }
  6789. BufferedInputStream::~BufferedInputStream() throw()
  6790. {
  6791. if (deleteSourceWhenDestroyed)
  6792. delete source;
  6793. juce_free (buffer);
  6794. }
  6795. int64 BufferedInputStream::getTotalLength()
  6796. {
  6797. return source->getTotalLength();
  6798. }
  6799. int64 BufferedInputStream::getPosition()
  6800. {
  6801. return position;
  6802. }
  6803. bool BufferedInputStream::setPosition (int64 newPosition)
  6804. {
  6805. position = jmax ((int64) 0, newPosition);
  6806. return true;
  6807. }
  6808. bool BufferedInputStream::isExhausted()
  6809. {
  6810. return (position >= lastReadPos)
  6811. && source->isExhausted();
  6812. }
  6813. void BufferedInputStream::ensureBuffered()
  6814. {
  6815. const int64 bufferEndOverlap = lastReadPos - bufferOverlap;
  6816. if (position < bufferStart || position >= bufferEndOverlap)
  6817. {
  6818. int bytesRead;
  6819. if (position < lastReadPos
  6820. && position >= bufferEndOverlap
  6821. && position >= bufferStart)
  6822. {
  6823. const int bytesToKeep = (int) (lastReadPos - position);
  6824. memmove (buffer, buffer + position - bufferStart, bytesToKeep);
  6825. bufferStart = position;
  6826. bytesRead = source->read (buffer + bytesToKeep,
  6827. bufferSize - bytesToKeep);
  6828. lastReadPos += bytesRead;
  6829. bytesRead += bytesToKeep;
  6830. }
  6831. else
  6832. {
  6833. bufferStart = position;
  6834. source->setPosition (bufferStart);
  6835. bytesRead = source->read (buffer, bufferSize);
  6836. lastReadPos = bufferStart + bytesRead;
  6837. }
  6838. while (bytesRead < bufferSize)
  6839. buffer [bytesRead++] = 0;
  6840. }
  6841. }
  6842. int BufferedInputStream::read (void* destBuffer, int maxBytesToRead)
  6843. {
  6844. if (position >= bufferStart
  6845. && position + maxBytesToRead <= lastReadPos)
  6846. {
  6847. memcpy (destBuffer, buffer + (position - bufferStart), maxBytesToRead);
  6848. position += maxBytesToRead;
  6849. return maxBytesToRead;
  6850. }
  6851. else
  6852. {
  6853. if (position < bufferStart || position >= lastReadPos)
  6854. ensureBuffered();
  6855. int bytesRead = 0;
  6856. while (maxBytesToRead > 0)
  6857. {
  6858. const int bytesAvailable = jmin (maxBytesToRead, (int) (lastReadPos - position));
  6859. if (bytesAvailable > 0)
  6860. {
  6861. memcpy (destBuffer, buffer + (position - bufferStart), bytesAvailable);
  6862. maxBytesToRead -= bytesAvailable;
  6863. bytesRead += bytesAvailable;
  6864. position += bytesAvailable;
  6865. destBuffer = (void*) (((char*) destBuffer) + bytesAvailable);
  6866. }
  6867. const int64 oldLastReadPos = lastReadPos;
  6868. ensureBuffered();
  6869. if (oldLastReadPos == lastReadPos)
  6870. break; // if ensureBuffered() failed to read any more data, bail out
  6871. if (isExhausted())
  6872. break;
  6873. }
  6874. return bytesRead;
  6875. }
  6876. }
  6877. const String BufferedInputStream::readString()
  6878. {
  6879. if (position >= bufferStart
  6880. && position < lastReadPos)
  6881. {
  6882. const int maxChars = (int) (lastReadPos - position);
  6883. const char* const src = buffer + (position - bufferStart);
  6884. for (int i = 0; i < maxChars; ++i)
  6885. {
  6886. if (src[i] == 0)
  6887. {
  6888. position += i + 1;
  6889. return String::fromUTF8 ((const uint8*) src, i);
  6890. }
  6891. }
  6892. }
  6893. return InputStream::readString();
  6894. }
  6895. END_JUCE_NAMESPACE
  6896. /********* End of inlined file: juce_BufferedInputStream.cpp *********/
  6897. /********* Start of inlined file: juce_FileInputSource.cpp *********/
  6898. BEGIN_JUCE_NAMESPACE
  6899. FileInputSource::FileInputSource (const File& file_) throw()
  6900. : file (file_)
  6901. {
  6902. }
  6903. FileInputSource::~FileInputSource()
  6904. {
  6905. }
  6906. InputStream* FileInputSource::createInputStream()
  6907. {
  6908. return file.createInputStream();
  6909. }
  6910. InputStream* FileInputSource::createInputStreamFor (const String& relatedItemPath)
  6911. {
  6912. return file.getSiblingFile (relatedItemPath).createInputStream();
  6913. }
  6914. int64 FileInputSource::hashCode() const
  6915. {
  6916. return file.hashCode();
  6917. }
  6918. END_JUCE_NAMESPACE
  6919. /********* End of inlined file: juce_FileInputSource.cpp *********/
  6920. /********* Start of inlined file: juce_MemoryInputStream.cpp *********/
  6921. BEGIN_JUCE_NAMESPACE
  6922. MemoryInputStream::MemoryInputStream (const void* const sourceData,
  6923. const int sourceDataSize,
  6924. const bool keepInternalCopy) throw()
  6925. : data ((const char*) sourceData),
  6926. dataSize (sourceDataSize),
  6927. position (0)
  6928. {
  6929. if (keepInternalCopy)
  6930. {
  6931. internalCopy.append (data, sourceDataSize);
  6932. data = (const char*) internalCopy.getData();
  6933. }
  6934. }
  6935. MemoryInputStream::~MemoryInputStream() throw()
  6936. {
  6937. }
  6938. int64 MemoryInputStream::getTotalLength()
  6939. {
  6940. return dataSize;
  6941. }
  6942. int MemoryInputStream::read (void* buffer, int howMany)
  6943. {
  6944. const int num = jmin (howMany, dataSize - position);
  6945. memcpy (buffer, data + position, num);
  6946. position += num;
  6947. return num;
  6948. }
  6949. bool MemoryInputStream::isExhausted()
  6950. {
  6951. return (position >= dataSize);
  6952. }
  6953. bool MemoryInputStream::setPosition (int64 pos)
  6954. {
  6955. position = (int) jlimit ((int64) 0, (int64) dataSize, pos);
  6956. return true;
  6957. }
  6958. int64 MemoryInputStream::getPosition()
  6959. {
  6960. return position;
  6961. }
  6962. END_JUCE_NAMESPACE
  6963. /********* End of inlined file: juce_MemoryInputStream.cpp *********/
  6964. /********* Start of inlined file: juce_MemoryOutputStream.cpp *********/
  6965. BEGIN_JUCE_NAMESPACE
  6966. MemoryOutputStream::MemoryOutputStream (const int initialSize,
  6967. const int blockSizeToIncreaseBy,
  6968. MemoryBlock* const memoryBlockToWriteTo) throw()
  6969. : data (memoryBlockToWriteTo),
  6970. position (0),
  6971. size (0),
  6972. blockSize (jmax (16, blockSizeToIncreaseBy)),
  6973. ownsMemoryBlock (memoryBlockToWriteTo == 0)
  6974. {
  6975. if (memoryBlockToWriteTo == 0)
  6976. data = new MemoryBlock (initialSize);
  6977. else
  6978. memoryBlockToWriteTo->setSize (initialSize, false);
  6979. }
  6980. MemoryOutputStream::~MemoryOutputStream() throw()
  6981. {
  6982. if (ownsMemoryBlock)
  6983. delete data;
  6984. else
  6985. flush();
  6986. }
  6987. void MemoryOutputStream::flush()
  6988. {
  6989. if (! ownsMemoryBlock)
  6990. data->setSize (size, false);
  6991. }
  6992. void MemoryOutputStream::reset() throw()
  6993. {
  6994. position = 0;
  6995. size = 0;
  6996. }
  6997. bool MemoryOutputStream::write (const void* buffer, int howMany)
  6998. {
  6999. if (howMany > 0)
  7000. {
  7001. int storageNeeded = position + howMany;
  7002. if (storageNeeded >= data->getSize())
  7003. {
  7004. // if we need more space, increase the block by at least 10%..
  7005. storageNeeded += jmax (blockSize, storageNeeded / 10);
  7006. storageNeeded = storageNeeded - (storageNeeded % blockSize) + blockSize;
  7007. data->ensureSize (storageNeeded);
  7008. }
  7009. data->copyFrom (buffer, position, howMany);
  7010. position += howMany;
  7011. size = jmax (size, position);
  7012. }
  7013. return true;
  7014. }
  7015. const char* MemoryOutputStream::getData() throw()
  7016. {
  7017. if (data->getSize() > size)
  7018. ((char*) data->getData()) [size] = 0;
  7019. return (const char*) data->getData();
  7020. }
  7021. int MemoryOutputStream::getDataSize() const throw()
  7022. {
  7023. return size;
  7024. }
  7025. int64 MemoryOutputStream::getPosition()
  7026. {
  7027. return position;
  7028. }
  7029. bool MemoryOutputStream::setPosition (int64 newPosition)
  7030. {
  7031. if (newPosition <= size)
  7032. {
  7033. // ok to seek backwards
  7034. position = jlimit (0, size, (int) newPosition);
  7035. return true;
  7036. }
  7037. else
  7038. {
  7039. // trying to make it bigger isn't a good thing to do..
  7040. return false;
  7041. }
  7042. }
  7043. END_JUCE_NAMESPACE
  7044. /********* End of inlined file: juce_MemoryOutputStream.cpp *********/
  7045. /********* Start of inlined file: juce_SubregionStream.cpp *********/
  7046. BEGIN_JUCE_NAMESPACE
  7047. SubregionStream::SubregionStream (InputStream* const sourceStream,
  7048. const int64 startPositionInSourceStream_,
  7049. const int64 lengthOfSourceStream_,
  7050. const bool deleteSourceWhenDestroyed_) throw()
  7051. : source (sourceStream),
  7052. deleteSourceWhenDestroyed (deleteSourceWhenDestroyed_),
  7053. startPositionInSourceStream (startPositionInSourceStream_),
  7054. lengthOfSourceStream (lengthOfSourceStream_)
  7055. {
  7056. setPosition (0);
  7057. }
  7058. SubregionStream::~SubregionStream() throw()
  7059. {
  7060. if (deleteSourceWhenDestroyed)
  7061. delete source;
  7062. }
  7063. int64 SubregionStream::getTotalLength()
  7064. {
  7065. const int64 srcLen = source->getTotalLength() - startPositionInSourceStream;
  7066. return (lengthOfSourceStream >= 0) ? jmin (lengthOfSourceStream, srcLen)
  7067. : srcLen;
  7068. }
  7069. int64 SubregionStream::getPosition()
  7070. {
  7071. return source->getPosition() - startPositionInSourceStream;
  7072. }
  7073. bool SubregionStream::setPosition (int64 newPosition)
  7074. {
  7075. return source->setPosition (jmax ((int64) 0, newPosition + startPositionInSourceStream));
  7076. }
  7077. int SubregionStream::read (void* destBuffer, int maxBytesToRead)
  7078. {
  7079. if (lengthOfSourceStream < 0)
  7080. {
  7081. return source->read (destBuffer, maxBytesToRead);
  7082. }
  7083. else
  7084. {
  7085. maxBytesToRead = (int) jmin ((int64) maxBytesToRead, lengthOfSourceStream - getPosition());
  7086. if (maxBytesToRead <= 0)
  7087. return 0;
  7088. return source->read (destBuffer, maxBytesToRead);
  7089. }
  7090. }
  7091. bool SubregionStream::isExhausted()
  7092. {
  7093. if (lengthOfSourceStream >= 0)
  7094. return (getPosition() >= lengthOfSourceStream) || source->isExhausted();
  7095. else
  7096. return source->isExhausted();
  7097. }
  7098. END_JUCE_NAMESPACE
  7099. /********* End of inlined file: juce_SubregionStream.cpp *********/
  7100. /********* Start of inlined file: juce_PerformanceCounter.cpp *********/
  7101. BEGIN_JUCE_NAMESPACE
  7102. PerformanceCounter::PerformanceCounter (const String& name_,
  7103. int runsPerPrintout,
  7104. const File& loggingFile)
  7105. : name (name_),
  7106. numRuns (0),
  7107. runsPerPrint (runsPerPrintout),
  7108. totalTime (0),
  7109. outputFile (loggingFile)
  7110. {
  7111. if (outputFile != File::nonexistent)
  7112. {
  7113. String s ("**** Counter for \"");
  7114. s << name_ << "\" started at: "
  7115. << Time::getCurrentTime().toString (true, true)
  7116. << "\r\n";
  7117. outputFile.appendText (s, false, false);
  7118. }
  7119. }
  7120. PerformanceCounter::~PerformanceCounter()
  7121. {
  7122. printStatistics();
  7123. }
  7124. void PerformanceCounter::start()
  7125. {
  7126. started = Time::getHighResolutionTicks();
  7127. }
  7128. void PerformanceCounter::stop()
  7129. {
  7130. const int64 now = Time::getHighResolutionTicks();
  7131. totalTime += 1000.0 * Time::highResolutionTicksToSeconds (now - started);
  7132. if (++numRuns == runsPerPrint)
  7133. printStatistics();
  7134. }
  7135. void PerformanceCounter::printStatistics()
  7136. {
  7137. if (numRuns > 0)
  7138. {
  7139. String s ("Performance count for \"");
  7140. s << name << "\" - average over " << numRuns << " run(s) = ";
  7141. const int micros = (int) (totalTime * (1000.0 / numRuns));
  7142. if (micros > 10000)
  7143. s << (micros/1000) << " millisecs";
  7144. else
  7145. s << micros << " microsecs";
  7146. s << ", total = " << String (totalTime / 1000, 5) << " seconds";
  7147. Logger::outputDebugString (s);
  7148. s << "\r\n";
  7149. if (outputFile != File::nonexistent)
  7150. outputFile.appendText (s, false, false);
  7151. numRuns = 0;
  7152. totalTime = 0;
  7153. }
  7154. }
  7155. END_JUCE_NAMESPACE
  7156. /********* End of inlined file: juce_PerformanceCounter.cpp *********/
  7157. /********* Start of inlined file: juce_Uuid.cpp *********/
  7158. BEGIN_JUCE_NAMESPACE
  7159. Uuid::Uuid()
  7160. {
  7161. // Mix up any available MAC addresses with some time-based pseudo-random numbers
  7162. // to make it very very unlikely that two UUIDs will ever be the same..
  7163. static int64 macAddresses[2];
  7164. static bool hasCheckedMacAddresses = false;
  7165. if (! hasCheckedMacAddresses)
  7166. {
  7167. hasCheckedMacAddresses = true;
  7168. SystemStats::getMACAddresses (macAddresses, 2);
  7169. }
  7170. value.asInt64[0] = macAddresses[0];
  7171. value.asInt64[1] = macAddresses[1];
  7172. // We'll use both a local RNG that is re-seeded, plus the shared RNG,
  7173. // whose seed will carry over between calls to this method.
  7174. Random r (macAddresses[0] ^ macAddresses[1]
  7175. ^ Random::getSystemRandom().nextInt64());
  7176. for (int i = 4; --i >= 0;)
  7177. {
  7178. r.setSeedRandomly(); // calling this repeatedly improves randomness
  7179. value.asInt[i] ^= r.nextInt();
  7180. value.asInt[i] ^= Random::getSystemRandom().nextInt();
  7181. }
  7182. }
  7183. Uuid::~Uuid() throw()
  7184. {
  7185. }
  7186. Uuid::Uuid (const Uuid& other)
  7187. : value (other.value)
  7188. {
  7189. }
  7190. Uuid& Uuid::operator= (const Uuid& other)
  7191. {
  7192. if (this != &other)
  7193. value = other.value;
  7194. return *this;
  7195. }
  7196. bool Uuid::operator== (const Uuid& other) const
  7197. {
  7198. return memcmp (value.asBytes, other.value.asBytes, 16) == 0;
  7199. }
  7200. bool Uuid::operator!= (const Uuid& other) const
  7201. {
  7202. return ! operator== (other);
  7203. }
  7204. bool Uuid::isNull() const throw()
  7205. {
  7206. return (value.asInt64 [0] == 0) && (value.asInt64 [1] == 0);
  7207. }
  7208. const String Uuid::toString() const
  7209. {
  7210. return String::toHexString (value.asBytes, 16, 0);
  7211. }
  7212. Uuid::Uuid (const String& uuidString)
  7213. {
  7214. operator= (uuidString);
  7215. }
  7216. Uuid& Uuid::operator= (const String& uuidString)
  7217. {
  7218. int destIndex = 0;
  7219. int i = 0;
  7220. for (;;)
  7221. {
  7222. int byte = 0;
  7223. for (int loop = 2; --loop >= 0;)
  7224. {
  7225. byte <<= 4;
  7226. for (;;)
  7227. {
  7228. const tchar c = uuidString [i++];
  7229. if (c >= T('0') && c <= T('9'))
  7230. {
  7231. byte |= c - T('0');
  7232. break;
  7233. }
  7234. else if (c >= T('a') && c <= T('z'))
  7235. {
  7236. byte |= c - (T('a') - 10);
  7237. break;
  7238. }
  7239. else if (c >= T('A') && c <= T('Z'))
  7240. {
  7241. byte |= c - (T('A') - 10);
  7242. break;
  7243. }
  7244. else if (c == 0)
  7245. {
  7246. while (destIndex < 16)
  7247. value.asBytes [destIndex++] = 0;
  7248. return *this;
  7249. }
  7250. }
  7251. }
  7252. value.asBytes [destIndex++] = (uint8) byte;
  7253. }
  7254. }
  7255. Uuid::Uuid (const uint8* const rawData)
  7256. {
  7257. operator= (rawData);
  7258. }
  7259. Uuid& Uuid::operator= (const uint8* const rawData)
  7260. {
  7261. if (rawData != 0)
  7262. memcpy (value.asBytes, rawData, 16);
  7263. else
  7264. zeromem (value.asBytes, 16);
  7265. return *this;
  7266. }
  7267. END_JUCE_NAMESPACE
  7268. /********* End of inlined file: juce_Uuid.cpp *********/
  7269. /********* Start of inlined file: juce_ZipFile.cpp *********/
  7270. BEGIN_JUCE_NAMESPACE
  7271. struct ZipEntryInfo
  7272. {
  7273. ZipFile::ZipEntry entry;
  7274. int streamOffset;
  7275. int compressedSize;
  7276. bool compressed;
  7277. };
  7278. class ZipInputStream : public InputStream
  7279. {
  7280. public:
  7281. ZipInputStream (ZipFile& file_,
  7282. ZipEntryInfo& zei) throw()
  7283. : file (file_),
  7284. zipEntryInfo (zei),
  7285. pos (0),
  7286. headerSize (0),
  7287. inputStream (0)
  7288. {
  7289. inputStream = file_.inputStream;
  7290. if (file_.inputSource != 0)
  7291. {
  7292. inputStream = file.inputSource->createInputStream();
  7293. }
  7294. else
  7295. {
  7296. #ifdef JUCE_DEBUG
  7297. file_.numOpenStreams++;
  7298. #endif
  7299. }
  7300. char buffer [30];
  7301. if (inputStream != 0
  7302. && inputStream->setPosition (zei.streamOffset)
  7303. && inputStream->read (buffer, 30) == 30
  7304. && littleEndianInt (buffer) == 0x04034b50)
  7305. {
  7306. headerSize = 30 + littleEndianShort (buffer + 26)
  7307. + littleEndianShort (buffer + 28);
  7308. }
  7309. }
  7310. ~ZipInputStream() throw()
  7311. {
  7312. #ifdef JUCE_DEBUG
  7313. if (inputStream != 0 && inputStream == file.inputStream)
  7314. file.numOpenStreams--;
  7315. #endif
  7316. if (inputStream != file.inputStream)
  7317. delete inputStream;
  7318. }
  7319. int64 getTotalLength() throw()
  7320. {
  7321. return zipEntryInfo.compressedSize;
  7322. }
  7323. int read (void* buffer, int howMany) throw()
  7324. {
  7325. if (headerSize <= 0)
  7326. return 0;
  7327. howMany = (int) jmin ((int64) howMany, zipEntryInfo.compressedSize - pos);
  7328. if (inputStream == 0)
  7329. return 0;
  7330. int num;
  7331. if (inputStream == file.inputStream)
  7332. {
  7333. const ScopedLock sl (file.lock);
  7334. inputStream->setPosition (pos + zipEntryInfo.streamOffset + headerSize);
  7335. num = inputStream->read (buffer, howMany);
  7336. }
  7337. else
  7338. {
  7339. inputStream->setPosition (pos + zipEntryInfo.streamOffset + headerSize);
  7340. num = inputStream->read (buffer, howMany);
  7341. }
  7342. pos += num;
  7343. return num;
  7344. }
  7345. bool isExhausted() throw()
  7346. {
  7347. return headerSize <= 0 || pos >= zipEntryInfo.compressedSize;
  7348. }
  7349. int64 getPosition() throw()
  7350. {
  7351. return pos;
  7352. }
  7353. bool setPosition (int64 newPos) throw()
  7354. {
  7355. pos = jlimit ((int64) 0, (int64) zipEntryInfo.compressedSize, newPos);
  7356. return true;
  7357. }
  7358. private:
  7359. ZipFile& file;
  7360. ZipEntryInfo zipEntryInfo;
  7361. int64 pos;
  7362. int headerSize;
  7363. InputStream* inputStream;
  7364. ZipInputStream (const ZipInputStream&);
  7365. const ZipInputStream& operator= (const ZipInputStream&);
  7366. };
  7367. ZipFile::ZipFile (InputStream* const source_,
  7368. const bool deleteStreamWhenDestroyed_) throw()
  7369. : inputStream (source_),
  7370. inputSource (0),
  7371. deleteStreamWhenDestroyed (deleteStreamWhenDestroyed_)
  7372. #ifdef JUCE_DEBUG
  7373. , numOpenStreams (0)
  7374. #endif
  7375. {
  7376. init();
  7377. }
  7378. ZipFile::ZipFile (const File& file)
  7379. : inputStream (0),
  7380. deleteStreamWhenDestroyed (false)
  7381. #ifdef JUCE_DEBUG
  7382. , numOpenStreams (0)
  7383. #endif
  7384. {
  7385. inputSource = new FileInputSource (file);
  7386. init();
  7387. }
  7388. ZipFile::ZipFile (InputSource* const inputSource_)
  7389. : inputStream (0),
  7390. inputSource (inputSource_),
  7391. deleteStreamWhenDestroyed (false)
  7392. #ifdef JUCE_DEBUG
  7393. , numOpenStreams (0)
  7394. #endif
  7395. {
  7396. init();
  7397. }
  7398. ZipFile::~ZipFile() throw()
  7399. {
  7400. for (int i = entries.size(); --i >= 0;)
  7401. {
  7402. ZipEntryInfo* const zei = (ZipEntryInfo*) entries [i];
  7403. delete zei;
  7404. }
  7405. if (deleteStreamWhenDestroyed)
  7406. delete inputStream;
  7407. delete inputSource;
  7408. #ifdef JUCE_DEBUG
  7409. // If you hit this assertion, it means you've created a stream to read
  7410. // one of the items in the zipfile, but you've forgotten to delete that
  7411. // stream object before deleting the file.. Streams can't be kept open
  7412. // after the file is deleted because they need to share the input
  7413. // stream that the file uses to read itself.
  7414. jassert (numOpenStreams == 0);
  7415. #endif
  7416. }
  7417. int ZipFile::getNumEntries() const throw()
  7418. {
  7419. return entries.size();
  7420. }
  7421. const ZipFile::ZipEntry* ZipFile::getEntry (const int index) const throw()
  7422. {
  7423. ZipEntryInfo* const zei = (ZipEntryInfo*) entries [index];
  7424. return (zei != 0) ? &(zei->entry)
  7425. : 0;
  7426. }
  7427. int ZipFile::getIndexOfFileName (const String& fileName) const throw()
  7428. {
  7429. for (int i = 0; i < entries.size(); ++i)
  7430. if (((ZipEntryInfo*) entries.getUnchecked (i))->entry.filename == fileName)
  7431. return i;
  7432. return -1;
  7433. }
  7434. const ZipFile::ZipEntry* ZipFile::getEntry (const String& fileName) const throw()
  7435. {
  7436. return getEntry (getIndexOfFileName (fileName));
  7437. }
  7438. InputStream* ZipFile::createStreamForEntry (const int index)
  7439. {
  7440. ZipEntryInfo* const zei = (ZipEntryInfo*) entries[index];
  7441. InputStream* stream = 0;
  7442. if (zei != 0)
  7443. {
  7444. stream = new ZipInputStream (*this, *zei);
  7445. if (zei->compressed)
  7446. {
  7447. stream = new GZIPDecompressorInputStream (stream, true, true,
  7448. zei->entry.uncompressedSize);
  7449. // (much faster to unzip in big blocks using a buffer..)
  7450. stream = new BufferedInputStream (stream, 32768, true);
  7451. }
  7452. }
  7453. return stream;
  7454. }
  7455. class ZipFilenameComparator
  7456. {
  7457. public:
  7458. static int compareElements (const void* const first, const void* const second) throw()
  7459. {
  7460. return ((const ZipEntryInfo*) first)->entry.filename
  7461. .compare (((const ZipEntryInfo*) second)->entry.filename);
  7462. }
  7463. };
  7464. void ZipFile::sortEntriesByFilename()
  7465. {
  7466. ZipFilenameComparator sorter;
  7467. entries.sort (sorter);
  7468. }
  7469. void ZipFile::init()
  7470. {
  7471. InputStream* in = inputStream;
  7472. bool deleteInput = false;
  7473. if (inputSource != 0)
  7474. {
  7475. deleteInput = true;
  7476. in = inputSource->createInputStream();
  7477. }
  7478. if (in != 0)
  7479. {
  7480. numEntries = 0;
  7481. int pos = findEndOfZipEntryTable (in);
  7482. if (pos >= 0 && pos < in->getTotalLength())
  7483. {
  7484. const int size = (int) (in->getTotalLength() - pos);
  7485. in->setPosition (pos);
  7486. MemoryBlock headerData;
  7487. if (in->readIntoMemoryBlock (headerData, size) == size)
  7488. {
  7489. pos = 0;
  7490. for (int i = 0; i < numEntries; ++i)
  7491. {
  7492. if (pos + 46 > size)
  7493. break;
  7494. const char* const buffer = ((const char*) headerData.getData()) + pos;
  7495. const int fileNameLen = littleEndianShort (buffer + 28);
  7496. if (pos + 46 + fileNameLen > size)
  7497. break;
  7498. ZipEntryInfo* const zei = new ZipEntryInfo();
  7499. zei->entry.filename = String (buffer + 46, fileNameLen);
  7500. const int time = littleEndianShort (buffer + 12);
  7501. const int date = littleEndianShort (buffer + 14);
  7502. const int year = 1980 + (date >> 9);
  7503. const int month = ((date >> 5) & 15) - 1;
  7504. const int day = date & 31;
  7505. const int hours = time >> 11;
  7506. const int minutes = (time >> 5) & 63;
  7507. const int seconds = (time & 31) << 1;
  7508. zei->entry.fileTime = Time (year, month, day, hours, minutes, seconds);
  7509. zei->compressed = littleEndianShort (buffer + 10) != 0;
  7510. zei->compressedSize = littleEndianInt (buffer + 20);
  7511. zei->entry.uncompressedSize = littleEndianInt (buffer + 24);
  7512. zei->streamOffset = littleEndianInt (buffer + 42);
  7513. entries.add (zei);
  7514. pos += 46 + fileNameLen
  7515. + littleEndianShort (buffer + 30)
  7516. + littleEndianShort (buffer + 32);
  7517. }
  7518. }
  7519. }
  7520. if (deleteInput)
  7521. delete in;
  7522. }
  7523. }
  7524. int ZipFile::findEndOfZipEntryTable (InputStream* input)
  7525. {
  7526. BufferedInputStream in (input, 8192, false);
  7527. in.setPosition (in.getTotalLength());
  7528. int64 pos = in.getPosition();
  7529. const int64 lowestPos = jmax ((int64) 0, pos - 1024);
  7530. char buffer [32];
  7531. zeromem (buffer, sizeof (buffer));
  7532. while (pos > lowestPos)
  7533. {
  7534. in.setPosition (pos - 22);
  7535. pos = in.getPosition();
  7536. memcpy (buffer + 22, buffer, 4);
  7537. if (in.read (buffer, 22) != 22)
  7538. return 0;
  7539. for (int i = 0; i < 22; ++i)
  7540. {
  7541. if (littleEndianInt (buffer + i) == 0x06054b50)
  7542. {
  7543. in.setPosition (pos + i);
  7544. in.read (buffer, 22);
  7545. numEntries = littleEndianShort (buffer + 10);
  7546. return littleEndianInt (buffer + 16);
  7547. }
  7548. }
  7549. }
  7550. return 0;
  7551. }
  7552. void ZipFile::uncompressTo (const File& targetDirectory,
  7553. const bool shouldOverwriteFiles)
  7554. {
  7555. for (int i = 0; i < entries.size(); ++i)
  7556. {
  7557. const ZipEntryInfo& zei = *(ZipEntryInfo*) entries[i];
  7558. const File targetFile (targetDirectory.getChildFile (zei.entry.filename));
  7559. if (zei.entry.filename.endsWithChar (T('/')))
  7560. {
  7561. targetFile.createDirectory(); // (entry is a directory, not a file)
  7562. }
  7563. else
  7564. {
  7565. InputStream* const in = createStreamForEntry (i);
  7566. if (in != 0)
  7567. {
  7568. if (shouldOverwriteFiles)
  7569. targetFile.deleteFile();
  7570. if ((! targetFile.exists())
  7571. && targetFile.getParentDirectory().createDirectory())
  7572. {
  7573. FileOutputStream* const out = targetFile.createOutputStream();
  7574. if (out != 0)
  7575. {
  7576. out->writeFromInputStream (*in, -1);
  7577. delete out;
  7578. targetFile.setCreationTime (zei.entry.fileTime);
  7579. targetFile.setLastModificationTime (zei.entry.fileTime);
  7580. targetFile.setLastAccessTime (zei.entry.fileTime);
  7581. }
  7582. }
  7583. delete in;
  7584. }
  7585. }
  7586. }
  7587. }
  7588. END_JUCE_NAMESPACE
  7589. /********* End of inlined file: juce_ZipFile.cpp *********/
  7590. /********* Start of inlined file: juce_CharacterFunctions.cpp *********/
  7591. #ifdef _MSC_VER
  7592. #pragma warning (disable: 4514 4996)
  7593. #pragma warning (push)
  7594. #endif
  7595. #include <cwctype>
  7596. #include <cctype>
  7597. #include <ctime>
  7598. #ifdef _MSC_VER
  7599. #pragma warning (pop)
  7600. #endif
  7601. BEGIN_JUCE_NAMESPACE
  7602. int CharacterFunctions::length (const char* const s) throw()
  7603. {
  7604. return (int) strlen (s);
  7605. }
  7606. int CharacterFunctions::length (const juce_wchar* const s) throw()
  7607. {
  7608. return (int) wcslen (s);
  7609. }
  7610. void CharacterFunctions::copy (char* dest, const char* src, const int maxChars) throw()
  7611. {
  7612. strncpy (dest, src, maxChars);
  7613. }
  7614. void CharacterFunctions::copy (juce_wchar* dest, const juce_wchar* src, int maxChars) throw()
  7615. {
  7616. wcsncpy (dest, src, maxChars);
  7617. }
  7618. void CharacterFunctions::copy (juce_wchar* dest, const char* src, const int maxChars) throw()
  7619. {
  7620. mbstowcs (dest, src, maxChars);
  7621. }
  7622. void CharacterFunctions::copy (char* dest, const juce_wchar* src, const int maxChars) throw()
  7623. {
  7624. wcstombs (dest, src, maxChars);
  7625. }
  7626. int CharacterFunctions::bytesRequiredForCopy (const juce_wchar* src) throw()
  7627. {
  7628. return (int) wcstombs (0, src, 0);
  7629. }
  7630. void CharacterFunctions::append (char* dest, const char* src) throw()
  7631. {
  7632. strcat (dest, src);
  7633. }
  7634. void CharacterFunctions::append (juce_wchar* dest, const juce_wchar* src) throw()
  7635. {
  7636. wcscat (dest, src);
  7637. }
  7638. int CharacterFunctions::compare (const char* const s1, const char* const s2) throw()
  7639. {
  7640. return strcmp (s1, s2);
  7641. }
  7642. int CharacterFunctions::compare (const juce_wchar* s1, const juce_wchar* s2) throw()
  7643. {
  7644. jassert (s1 != 0 && s2 != 0);
  7645. return wcscmp (s1, s2);
  7646. }
  7647. int CharacterFunctions::compare (const char* const s1, const char* const s2, const int maxChars) throw()
  7648. {
  7649. jassert (s1 != 0 && s2 != 0);
  7650. return strncmp (s1, s2, maxChars);
  7651. }
  7652. int CharacterFunctions::compare (const juce_wchar* s1, const juce_wchar* s2, int maxChars) throw()
  7653. {
  7654. jassert (s1 != 0 && s2 != 0);
  7655. return wcsncmp (s1, s2, maxChars);
  7656. }
  7657. int CharacterFunctions::compareIgnoreCase (const char* const s1, const char* const s2) throw()
  7658. {
  7659. jassert (s1 != 0 && s2 != 0);
  7660. #if JUCE_WIN32
  7661. return stricmp (s1, s2);
  7662. #else
  7663. return strcasecmp (s1, s2);
  7664. #endif
  7665. }
  7666. int CharacterFunctions::compareIgnoreCase (const juce_wchar* s1, const juce_wchar* s2) throw()
  7667. {
  7668. jassert (s1 != 0 && s2 != 0);
  7669. #if JUCE_WIN32
  7670. return _wcsicmp (s1, s2);
  7671. #else
  7672. for (;;)
  7673. {
  7674. if (*s1 != *s2)
  7675. {
  7676. const int diff = toUpperCase (*s1) - toUpperCase (*s2);
  7677. if (diff != 0)
  7678. return diff < 0 ? -1 : 1;
  7679. }
  7680. else if (*s1 == 0)
  7681. break;
  7682. ++s1;
  7683. ++s2;
  7684. }
  7685. return 0;
  7686. #endif
  7687. }
  7688. int CharacterFunctions::compareIgnoreCase (const char* const s1, const char* const s2, const int maxChars) throw()
  7689. {
  7690. jassert (s1 != 0 && s2 != 0);
  7691. #if JUCE_WIN32
  7692. return strnicmp (s1, s2, maxChars);
  7693. #else
  7694. return strncasecmp (s1, s2, maxChars);
  7695. #endif
  7696. }
  7697. int CharacterFunctions::compareIgnoreCase (const juce_wchar* s1, const juce_wchar* s2, int maxChars) throw()
  7698. {
  7699. jassert (s1 != 0 && s2 != 0);
  7700. #if JUCE_WIN32
  7701. return _wcsnicmp (s1, s2, maxChars);
  7702. #else
  7703. while (--maxChars >= 0)
  7704. {
  7705. if (*s1 != *s2)
  7706. {
  7707. const int diff = toUpperCase (*s1) - toUpperCase (*s2);
  7708. if (diff != 0)
  7709. return diff < 0 ? -1 : 1;
  7710. }
  7711. else if (*s1 == 0)
  7712. break;
  7713. ++s1;
  7714. ++s2;
  7715. }
  7716. return 0;
  7717. #endif
  7718. }
  7719. const char* CharacterFunctions::find (const char* const haystack, const char* const needle) throw()
  7720. {
  7721. return strstr (haystack, needle);
  7722. }
  7723. const juce_wchar* CharacterFunctions::find (const juce_wchar* haystack, const juce_wchar* const needle) throw()
  7724. {
  7725. return wcsstr (haystack, needle);
  7726. }
  7727. int CharacterFunctions::indexOfChar (const char* const haystack, const char needle, const bool ignoreCase) throw()
  7728. {
  7729. if (haystack != 0)
  7730. {
  7731. int i = 0;
  7732. if (ignoreCase)
  7733. {
  7734. const char n1 = toLowerCase (needle);
  7735. const char n2 = toUpperCase (needle);
  7736. if (n1 != n2) // if the char is the same in upper/lower case, fall through to the normal search
  7737. {
  7738. while (haystack[i] != 0)
  7739. {
  7740. if (haystack[i] == n1 || haystack[i] == n2)
  7741. return i;
  7742. ++i;
  7743. }
  7744. return -1;
  7745. }
  7746. jassert (n1 == needle);
  7747. }
  7748. while (haystack[i] != 0)
  7749. {
  7750. if (haystack[i] == needle)
  7751. return i;
  7752. ++i;
  7753. }
  7754. }
  7755. return -1;
  7756. }
  7757. int CharacterFunctions::indexOfChar (const juce_wchar* const haystack, const juce_wchar needle, const bool ignoreCase) throw()
  7758. {
  7759. if (haystack != 0)
  7760. {
  7761. int i = 0;
  7762. if (ignoreCase)
  7763. {
  7764. const juce_wchar n1 = toLowerCase (needle);
  7765. const juce_wchar n2 = toUpperCase (needle);
  7766. if (n1 != n2) // if the char is the same in upper/lower case, fall through to the normal search
  7767. {
  7768. while (haystack[i] != 0)
  7769. {
  7770. if (haystack[i] == n1 || haystack[i] == n2)
  7771. return i;
  7772. ++i;
  7773. }
  7774. return -1;
  7775. }
  7776. jassert (n1 == needle);
  7777. }
  7778. while (haystack[i] != 0)
  7779. {
  7780. if (haystack[i] == needle)
  7781. return i;
  7782. ++i;
  7783. }
  7784. }
  7785. return -1;
  7786. }
  7787. int CharacterFunctions::indexOfCharFast (const char* const haystack, const char needle) throw()
  7788. {
  7789. jassert (haystack != 0);
  7790. int i = 0;
  7791. while (haystack[i] != 0)
  7792. {
  7793. if (haystack[i] == needle)
  7794. return i;
  7795. ++i;
  7796. }
  7797. return -1;
  7798. }
  7799. int CharacterFunctions::indexOfCharFast (const juce_wchar* const haystack, const juce_wchar needle) throw()
  7800. {
  7801. jassert (haystack != 0);
  7802. int i = 0;
  7803. while (haystack[i] != 0)
  7804. {
  7805. if (haystack[i] == needle)
  7806. return i;
  7807. ++i;
  7808. }
  7809. return -1;
  7810. }
  7811. int CharacterFunctions::getIntialSectionContainingOnly (const char* const text, const char* const allowedChars) throw()
  7812. {
  7813. return allowedChars == 0 ? 0 : (int) strspn (text, allowedChars);
  7814. }
  7815. int CharacterFunctions::getIntialSectionContainingOnly (const juce_wchar* const text, const juce_wchar* const allowedChars) throw()
  7816. {
  7817. if (allowedChars == 0)
  7818. return 0;
  7819. int i = 0;
  7820. for (;;)
  7821. {
  7822. if (indexOfCharFast (allowedChars, text[i]) < 0)
  7823. break;
  7824. ++i;
  7825. }
  7826. return i;
  7827. }
  7828. int CharacterFunctions::ftime (char* const dest, const int maxChars, const char* const format, const struct tm* const tm) throw()
  7829. {
  7830. return (int) strftime (dest, maxChars, format, tm);
  7831. }
  7832. int CharacterFunctions::ftime (juce_wchar* const dest, const int maxChars, const juce_wchar* const format, const struct tm* const tm) throw()
  7833. {
  7834. return (int) wcsftime (dest, maxChars, format, tm);
  7835. }
  7836. int CharacterFunctions::getIntValue (const char* const s) throw()
  7837. {
  7838. return atoi (s);
  7839. }
  7840. int CharacterFunctions::getIntValue (const juce_wchar* s) throw()
  7841. {
  7842. #if JUCE_WIN32
  7843. return _wtoi (s);
  7844. #else
  7845. int v = 0;
  7846. while (isWhitespace (*s))
  7847. ++s;
  7848. const bool isNeg = *s == T('-');
  7849. if (isNeg)
  7850. ++s;
  7851. for (;;)
  7852. {
  7853. const wchar_t c = *s++;
  7854. if (c >= T('0') && c <= T('9'))
  7855. v = v * 10 + (int) (c - T('0'));
  7856. else
  7857. break;
  7858. }
  7859. return isNeg ? -v : v;
  7860. #endif
  7861. }
  7862. int64 CharacterFunctions::getInt64Value (const char* s) throw()
  7863. {
  7864. #if JUCE_LINUX
  7865. return atoll (s);
  7866. #elif defined (JUCE_WIN32)
  7867. return _atoi64 (s);
  7868. #else
  7869. int64 v = 0;
  7870. while (isWhitespace (*s))
  7871. ++s;
  7872. const bool isNeg = *s == T('-');
  7873. if (isNeg)
  7874. ++s;
  7875. for (;;)
  7876. {
  7877. const char c = *s++;
  7878. if (c >= '0' && c <= '9')
  7879. v = v * 10 + (int64) (c - '0');
  7880. else
  7881. break;
  7882. }
  7883. return isNeg ? -v : v;
  7884. #endif
  7885. }
  7886. int64 CharacterFunctions::getInt64Value (const juce_wchar* s) throw()
  7887. {
  7888. #if JUCE_WIN32
  7889. return _wtoi64 (s);
  7890. #else
  7891. int64 v = 0;
  7892. while (isWhitespace (*s))
  7893. ++s;
  7894. const bool isNeg = *s == T('-');
  7895. if (isNeg)
  7896. ++s;
  7897. for (;;)
  7898. {
  7899. const juce_wchar c = *s++;
  7900. if (c >= T('0') && c <= T('9'))
  7901. v = v * 10 + (int64) (c - T('0'));
  7902. else
  7903. break;
  7904. }
  7905. return isNeg ? -v : v;
  7906. #endif
  7907. }
  7908. static double juce_mulexp10 (const double value, int exponent) throw()
  7909. {
  7910. if (exponent == 0)
  7911. return value;
  7912. if (value == 0)
  7913. return 0;
  7914. const bool negative = (exponent < 0);
  7915. if (negative)
  7916. exponent = -exponent;
  7917. double result = 1.0, power = 10.0;
  7918. for (int bit = 1; exponent != 0; bit <<= 1)
  7919. {
  7920. if ((exponent & bit) != 0)
  7921. {
  7922. exponent ^= bit;
  7923. result *= power;
  7924. if (exponent == 0)
  7925. break;
  7926. }
  7927. power *= power;
  7928. }
  7929. return negative ? (value / result) : (value * result);
  7930. }
  7931. template <class CharType>
  7932. double juce_atof (const CharType* const original) throw()
  7933. {
  7934. double result[3] = { 0, 0, 0 }, accumulator[2] = { 0, 0 };
  7935. int exponentAdjustment[2] = { 0, 0 }, exponentAccumulator[2] = { -1, -1 };
  7936. int exponent = 0, decPointIndex = 0, digit = 0;
  7937. int lastDigit = 0, numSignificantDigits = 0;
  7938. bool isNegative = false, digitsFound = false;
  7939. const int maxSignificantDigits = 15 + 2;
  7940. const CharType* s = original;
  7941. while (CharacterFunctions::isWhitespace (*s))
  7942. ++s;
  7943. switch (*s)
  7944. {
  7945. case '-': isNegative = true; // fall-through..
  7946. case '+': ++s;
  7947. }
  7948. if (*s == 'n' || *s == 'N' || *s == 'i' || *s == 'I')
  7949. return atof (String (original)); // Let the c library deal with NAN and INF
  7950. for (;;)
  7951. {
  7952. if (CharacterFunctions::isDigit (*s))
  7953. {
  7954. lastDigit = digit;
  7955. digit = *s++ - '0';
  7956. digitsFound = true;
  7957. if (decPointIndex != 0)
  7958. exponentAdjustment[1]++;
  7959. if (numSignificantDigits == 0 && digit == 0)
  7960. continue;
  7961. if (++numSignificantDigits > maxSignificantDigits)
  7962. {
  7963. if (digit > 5)
  7964. ++accumulator [decPointIndex];
  7965. else if (digit == 5 && (lastDigit & 1) != 0)
  7966. ++accumulator [decPointIndex];
  7967. if (decPointIndex > 0)
  7968. exponentAdjustment[1]--;
  7969. else
  7970. exponentAdjustment[0]++;
  7971. while (CharacterFunctions::isDigit (*s))
  7972. {
  7973. ++s;
  7974. if (decPointIndex == 0)
  7975. exponentAdjustment[0]++;
  7976. }
  7977. }
  7978. else
  7979. {
  7980. const double maxAccumulatorValue = (double) ((UINT_MAX - 9) / 10);
  7981. if (accumulator [decPointIndex] > maxAccumulatorValue)
  7982. {
  7983. result [decPointIndex] = juce_mulexp10 (result [decPointIndex], exponentAccumulator [decPointIndex])
  7984. + accumulator [decPointIndex];
  7985. accumulator [decPointIndex] = 0;
  7986. exponentAccumulator [decPointIndex] = 0;
  7987. }
  7988. accumulator [decPointIndex] = accumulator[decPointIndex] * 10 + digit;
  7989. exponentAccumulator [decPointIndex]++;
  7990. }
  7991. }
  7992. else if (decPointIndex == 0 && *s == '.')
  7993. {
  7994. ++s;
  7995. decPointIndex = 1;
  7996. if (numSignificantDigits > maxSignificantDigits)
  7997. {
  7998. while (CharacterFunctions::isDigit (*s))
  7999. ++s;
  8000. break;
  8001. }
  8002. }
  8003. else
  8004. {
  8005. break;
  8006. }
  8007. }
  8008. result[0] = juce_mulexp10 (result[0], exponentAccumulator[0]) + accumulator[0];
  8009. if (decPointIndex != 0)
  8010. result[1] = juce_mulexp10 (result[1], exponentAccumulator[1]) + accumulator[1];
  8011. if ((*s == 'e' || *s == 'E') && digitsFound)
  8012. {
  8013. bool negativeExponent = false;
  8014. switch (*++s)
  8015. {
  8016. case '-': negativeExponent = true; // fall-through..
  8017. case '+': ++s;
  8018. }
  8019. while (CharacterFunctions::isDigit (*s))
  8020. exponent = (exponent * 10) + (*s++ - '0');
  8021. if (negativeExponent)
  8022. exponent = -exponent;
  8023. }
  8024. double r = juce_mulexp10 (result[0], exponent + exponentAdjustment[0]);
  8025. if (decPointIndex != 0)
  8026. r += juce_mulexp10 (result[1], exponent - exponentAdjustment[1]);
  8027. return isNegative ? -r : r;
  8028. }
  8029. double CharacterFunctions::getDoubleValue (const char* const s) throw()
  8030. {
  8031. return juce_atof <char> (s);
  8032. }
  8033. double CharacterFunctions::getDoubleValue (const juce_wchar* const s) throw()
  8034. {
  8035. return juce_atof <juce_wchar> (s);
  8036. }
  8037. char CharacterFunctions::toUpperCase (const char character) throw()
  8038. {
  8039. return (char) toupper (character);
  8040. }
  8041. juce_wchar CharacterFunctions::toUpperCase (const juce_wchar character) throw()
  8042. {
  8043. return towupper (character);
  8044. }
  8045. void CharacterFunctions::toUpperCase (char* s) throw()
  8046. {
  8047. #if JUCE_WIN32
  8048. strupr (s);
  8049. #else
  8050. while (*s != 0)
  8051. {
  8052. *s = toUpperCase (*s);
  8053. ++s;
  8054. }
  8055. #endif
  8056. }
  8057. void CharacterFunctions::toUpperCase (juce_wchar* s) throw()
  8058. {
  8059. #if JUCE_WIN32
  8060. _wcsupr (s);
  8061. #else
  8062. while (*s != 0)
  8063. {
  8064. *s = toUpperCase (*s);
  8065. ++s;
  8066. }
  8067. #endif
  8068. }
  8069. bool CharacterFunctions::isUpperCase (const char character) throw()
  8070. {
  8071. return isupper (character) != 0;
  8072. }
  8073. bool CharacterFunctions::isUpperCase (const juce_wchar character) throw()
  8074. {
  8075. #if JUCE_WIN32
  8076. return iswupper (character) != 0;
  8077. #else
  8078. return toLowerCase (character) != character;
  8079. #endif
  8080. }
  8081. char CharacterFunctions::toLowerCase (const char character) throw()
  8082. {
  8083. return (char) tolower (character);
  8084. }
  8085. juce_wchar CharacterFunctions::toLowerCase (const juce_wchar character) throw()
  8086. {
  8087. return towlower (character);
  8088. }
  8089. void CharacterFunctions::toLowerCase (char* s) throw()
  8090. {
  8091. #if JUCE_WIN32
  8092. strlwr (s);
  8093. #else
  8094. while (*s != 0)
  8095. {
  8096. *s = toLowerCase (*s);
  8097. ++s;
  8098. }
  8099. #endif
  8100. }
  8101. void CharacterFunctions::toLowerCase (juce_wchar* s) throw()
  8102. {
  8103. #if JUCE_WIN32
  8104. _wcslwr (s);
  8105. #else
  8106. while (*s != 0)
  8107. {
  8108. *s = toLowerCase (*s);
  8109. ++s;
  8110. }
  8111. #endif
  8112. }
  8113. bool CharacterFunctions::isLowerCase (const char character) throw()
  8114. {
  8115. return islower (character) != 0;
  8116. }
  8117. bool CharacterFunctions::isLowerCase (const juce_wchar character) throw()
  8118. {
  8119. #if JUCE_WIN32
  8120. return iswlower (character) != 0;
  8121. #else
  8122. return toUpperCase (character) != character;
  8123. #endif
  8124. }
  8125. bool CharacterFunctions::isWhitespace (const char character) throw()
  8126. {
  8127. return character == T(' ') || (character <= 13 && character >= 9);
  8128. }
  8129. bool CharacterFunctions::isWhitespace (const juce_wchar character) throw()
  8130. {
  8131. return iswspace (character) != 0;
  8132. }
  8133. bool CharacterFunctions::isDigit (const char character) throw()
  8134. {
  8135. return (character >= '0' && character <= '9');
  8136. }
  8137. bool CharacterFunctions::isDigit (const juce_wchar character) throw()
  8138. {
  8139. return iswdigit (character) != 0;
  8140. }
  8141. bool CharacterFunctions::isLetter (const char character) throw()
  8142. {
  8143. return (character >= 'a' && character <= 'z')
  8144. || (character >= 'A' && character <= 'Z');
  8145. }
  8146. bool CharacterFunctions::isLetter (const juce_wchar character) throw()
  8147. {
  8148. return iswalpha (character) != 0;
  8149. }
  8150. bool CharacterFunctions::isLetterOrDigit (const char character) throw()
  8151. {
  8152. return (character >= 'a' && character <= 'z')
  8153. || (character >= 'A' && character <= 'Z')
  8154. || (character >= '0' && character <= '9');
  8155. }
  8156. bool CharacterFunctions::isLetterOrDigit (const juce_wchar character) throw()
  8157. {
  8158. return iswalnum (character) != 0;
  8159. }
  8160. int CharacterFunctions::getHexDigitValue (const tchar digit) throw()
  8161. {
  8162. if (digit >= T('0') && digit <= T('9'))
  8163. return digit - T('0');
  8164. else if (digit >= T('a') && digit <= T('f'))
  8165. return digit - (T('a') - 10);
  8166. else if (digit >= T('A') && digit <= T('F'))
  8167. return digit - (T('A') - 10);
  8168. return -1;
  8169. }
  8170. int CharacterFunctions::printf (char* const dest, const int maxLength, const char* const format, ...) throw()
  8171. {
  8172. va_list list;
  8173. va_start (list, format);
  8174. return vprintf (dest, maxLength, format, list);
  8175. }
  8176. int CharacterFunctions::printf (juce_wchar* const dest, const int maxLength, const juce_wchar* const format, ...) throw()
  8177. {
  8178. va_list list;
  8179. va_start (list, format);
  8180. return vprintf (dest, maxLength, format, list);
  8181. }
  8182. int CharacterFunctions::vprintf (char* const dest, const int maxLength, const char* const format, va_list& args) throw()
  8183. {
  8184. #if JUCE_WIN32
  8185. return (int) _vsnprintf (dest, maxLength, format, args);
  8186. #else
  8187. return (int) vsnprintf (dest, maxLength, format, args);
  8188. #endif
  8189. }
  8190. int CharacterFunctions::vprintf (juce_wchar* const dest, const int maxLength, const juce_wchar* const format, va_list& args) throw()
  8191. {
  8192. #if MACOS_10_3_OR_EARLIER
  8193. const String formatTemp (format);
  8194. size_t num = vprintf ((char*) dest, maxLength, formatTemp, args);
  8195. String temp ((char*) dest);
  8196. temp.copyToBuffer (dest, num);
  8197. dest [num] = 0;
  8198. return (int) num;
  8199. #elif defined (JUCE_WIN32)
  8200. return (int) _vsnwprintf (dest, maxLength, format, args);
  8201. #else
  8202. return (int) vswprintf (dest, maxLength, format, args);
  8203. #endif
  8204. }
  8205. END_JUCE_NAMESPACE
  8206. /********* End of inlined file: juce_CharacterFunctions.cpp *********/
  8207. /********* Start of inlined file: juce_LocalisedStrings.cpp *********/
  8208. BEGIN_JUCE_NAMESPACE
  8209. LocalisedStrings::LocalisedStrings (const String& fileContents) throw()
  8210. {
  8211. loadFromText (fileContents);
  8212. }
  8213. LocalisedStrings::LocalisedStrings (const File& fileToLoad) throw()
  8214. {
  8215. loadFromText (fileToLoad.loadFileAsString());
  8216. }
  8217. LocalisedStrings::~LocalisedStrings() throw()
  8218. {
  8219. }
  8220. const String LocalisedStrings::translate (const String& text) const throw()
  8221. {
  8222. return translations.getValue (text, text);
  8223. }
  8224. static int findCloseQuote (const String& text, int startPos) throw()
  8225. {
  8226. tchar lastChar = 0;
  8227. for (;;)
  8228. {
  8229. const tchar c = text [startPos];
  8230. if (c == 0 || (c == T('"') && lastChar != T('\\')))
  8231. break;
  8232. lastChar = c;
  8233. ++startPos;
  8234. }
  8235. return startPos;
  8236. }
  8237. static const String unescapeString (const String& s) throw()
  8238. {
  8239. return s.replace (T("\\\""), T("\""))
  8240. .replace (T("\\\'"), T("\'"))
  8241. .replace (T("\\t"), T("\t"))
  8242. .replace (T("\\r"), T("\r"))
  8243. .replace (T("\\n"), T("\n"));
  8244. }
  8245. void LocalisedStrings::loadFromText (const String& fileContents) throw()
  8246. {
  8247. StringArray lines;
  8248. lines.addLines (fileContents);
  8249. for (int i = 0; i < lines.size(); ++i)
  8250. {
  8251. String line (lines[i].trim());
  8252. if (line.startsWithChar (T('"')))
  8253. {
  8254. int closeQuote = findCloseQuote (line, 1);
  8255. const String originalText (unescapeString (line.substring (1, closeQuote)));
  8256. if (originalText.isNotEmpty())
  8257. {
  8258. const int openingQuote = findCloseQuote (line, closeQuote + 1);
  8259. closeQuote = findCloseQuote (line, openingQuote + 1);
  8260. const String newText (unescapeString (line.substring (openingQuote + 1, closeQuote)));
  8261. if (newText.isNotEmpty())
  8262. translations.set (originalText, newText);
  8263. }
  8264. }
  8265. else if (line.startsWithIgnoreCase (T("language:")))
  8266. {
  8267. languageName = line.substring (9).trim();
  8268. }
  8269. else if (line.startsWithIgnoreCase (T("countries:")))
  8270. {
  8271. countryCodes.addTokens (line.substring (10).trim(), true);
  8272. countryCodes.trim();
  8273. countryCodes.removeEmptyStrings();
  8274. }
  8275. }
  8276. }
  8277. void LocalisedStrings::setIgnoresCase (const bool shouldIgnoreCase) throw()
  8278. {
  8279. translations.setIgnoresCase (shouldIgnoreCase);
  8280. }
  8281. static CriticalSection currentMappingsLock;
  8282. static LocalisedStrings* currentMappings = 0;
  8283. void LocalisedStrings::setCurrentMappings (LocalisedStrings* newTranslations) throw()
  8284. {
  8285. const ScopedLock sl (currentMappingsLock);
  8286. delete currentMappings;
  8287. currentMappings = newTranslations;
  8288. }
  8289. LocalisedStrings* LocalisedStrings::getCurrentMappings() throw()
  8290. {
  8291. return currentMappings;
  8292. }
  8293. const String LocalisedStrings::translateWithCurrentMappings (const String& text) throw()
  8294. {
  8295. const ScopedLock sl (currentMappingsLock);
  8296. if (currentMappings != 0)
  8297. return currentMappings->translate (text);
  8298. return text;
  8299. }
  8300. const String LocalisedStrings::translateWithCurrentMappings (const char* text) throw()
  8301. {
  8302. return translateWithCurrentMappings (String (text));
  8303. }
  8304. END_JUCE_NAMESPACE
  8305. /********* End of inlined file: juce_LocalisedStrings.cpp *********/
  8306. /********* Start of inlined file: juce_String.cpp *********/
  8307. #ifdef _MSC_VER
  8308. #pragma warning (disable: 4514)
  8309. #pragma warning (push)
  8310. #endif
  8311. #include <locale>
  8312. #if JUCE_MSVC
  8313. #include <float.h>
  8314. #endif
  8315. BEGIN_JUCE_NAMESPACE
  8316. #ifdef _MSC_VER
  8317. #pragma warning (pop)
  8318. #endif
  8319. static const char* const emptyCharString = "\0\0\0\0JUCE";
  8320. static const int safeEmptyStringRefCount = 0x3fffffff;
  8321. String::InternalRefCountedStringHolder String::emptyString = { safeEmptyStringRefCount, 0, { 0 } };
  8322. static tchar decimalPoint = T('.');
  8323. void juce_initialiseStrings()
  8324. {
  8325. decimalPoint = String::fromUTF8 ((const uint8*) localeconv()->decimal_point) [0];
  8326. }
  8327. void String::deleteInternal() throw()
  8328. {
  8329. if (atomicDecrementAndReturn (text->refCount) == 0)
  8330. juce_free (text);
  8331. }
  8332. void String::createInternal (const int numChars) throw()
  8333. {
  8334. jassert (numChars > 0);
  8335. text = (InternalRefCountedStringHolder*) juce_malloc (sizeof (InternalRefCountedStringHolder)
  8336. + numChars * sizeof (tchar));
  8337. text->refCount = 1;
  8338. text->allocatedNumChars = numChars;
  8339. text->text[0] = 0;
  8340. }
  8341. void String::createInternal (const tchar* const t, const tchar* const textEnd) throw()
  8342. {
  8343. jassert (*(textEnd - 1) == 0); // must have a null terminator
  8344. const int numChars = (int) (textEnd - t);
  8345. createInternal (numChars - 1);
  8346. memcpy (text->text, t, numChars * sizeof (tchar));
  8347. }
  8348. void String::appendInternal (const tchar* const newText,
  8349. const int numExtraChars) throw()
  8350. {
  8351. if (numExtraChars > 0)
  8352. {
  8353. const int oldLen = CharacterFunctions::length (text->text);
  8354. const int newTotalLen = oldLen + numExtraChars;
  8355. if (text->refCount > 1)
  8356. {
  8357. // it's in use by other strings as well, so we need to make a private copy before messing with it..
  8358. InternalRefCountedStringHolder* const newTextHolder
  8359. = (InternalRefCountedStringHolder*) juce_malloc (sizeof (InternalRefCountedStringHolder)
  8360. + newTotalLen * sizeof (tchar));
  8361. newTextHolder->refCount = 1;
  8362. newTextHolder->allocatedNumChars = newTotalLen;
  8363. memcpy (newTextHolder->text, text->text, oldLen * sizeof (tchar));
  8364. memcpy (newTextHolder->text + oldLen, newText, numExtraChars * sizeof (tchar));
  8365. InternalRefCountedStringHolder* const old = text;
  8366. text = newTextHolder;
  8367. if (atomicDecrementAndReturn (old->refCount) == 0)
  8368. juce_free (old);
  8369. }
  8370. else
  8371. {
  8372. // no other strings using it, so just expand it if needed..
  8373. if (newTotalLen > text->allocatedNumChars)
  8374. {
  8375. text = (InternalRefCountedStringHolder*)
  8376. juce_realloc (text, sizeof (InternalRefCountedStringHolder)
  8377. + newTotalLen * sizeof (tchar));
  8378. text->allocatedNumChars = newTotalLen;
  8379. }
  8380. memcpy (text->text + oldLen, newText, numExtraChars * sizeof (tchar));
  8381. }
  8382. text->text [newTotalLen] = 0;
  8383. }
  8384. }
  8385. void String::dupeInternalIfMultiplyReferenced() throw()
  8386. {
  8387. if (text->refCount > 1)
  8388. {
  8389. InternalRefCountedStringHolder* const old = text;
  8390. const int len = old->allocatedNumChars;
  8391. InternalRefCountedStringHolder* const newTextHolder
  8392. = (InternalRefCountedStringHolder*) juce_malloc (sizeof (InternalRefCountedStringHolder)
  8393. + len * sizeof (tchar));
  8394. newTextHolder->refCount = 1;
  8395. newTextHolder->allocatedNumChars = len;
  8396. memcpy (newTextHolder->text, old->text, (len + 1) * sizeof (tchar));
  8397. text = newTextHolder;
  8398. if (atomicDecrementAndReturn (old->refCount) == 0)
  8399. juce_free (old);
  8400. }
  8401. }
  8402. const String String::empty;
  8403. String::String() throw()
  8404. : text (&emptyString)
  8405. {
  8406. }
  8407. String::String (const String& other) throw()
  8408. : text (other.text)
  8409. {
  8410. atomicIncrement (text->refCount);
  8411. }
  8412. String::String (const int numChars,
  8413. const int /*dummyVariable*/) throw()
  8414. {
  8415. createInternal (numChars);
  8416. }
  8417. String::String (const char* const t) throw()
  8418. {
  8419. if (t != 0 && *t != 0)
  8420. {
  8421. const int len = CharacterFunctions::length (t);
  8422. createInternal (len);
  8423. #if JUCE_STRINGS_ARE_UNICODE
  8424. CharacterFunctions::copy (text->text, t, len + 1);
  8425. #else
  8426. memcpy (text->text, t, len + 1);
  8427. #endif
  8428. }
  8429. else
  8430. {
  8431. text = &emptyString;
  8432. emptyString.refCount = safeEmptyStringRefCount;
  8433. }
  8434. }
  8435. String::String (const juce_wchar* const t) throw()
  8436. {
  8437. if (t != 0 && *t != 0)
  8438. {
  8439. #if JUCE_STRINGS_ARE_UNICODE
  8440. const int len = CharacterFunctions::length (t);
  8441. createInternal (len);
  8442. memcpy (text->text, t, (len + 1) * sizeof (tchar));
  8443. #else
  8444. const int len = CharacterFunctions::bytesRequiredForCopy (t);
  8445. createInternal (len);
  8446. CharacterFunctions::copy (text->text, t, len + 1);
  8447. #endif
  8448. }
  8449. else
  8450. {
  8451. text = &emptyString;
  8452. emptyString.refCount = safeEmptyStringRefCount;
  8453. }
  8454. }
  8455. String::String (const char* const t,
  8456. const int maxChars) throw()
  8457. {
  8458. int i;
  8459. for (i = 0; i < maxChars; ++i)
  8460. if (t[i] == 0)
  8461. break;
  8462. if (i > 0)
  8463. {
  8464. createInternal (i);
  8465. #if JUCE_STRINGS_ARE_UNICODE
  8466. CharacterFunctions::copy (text->text, t, i);
  8467. #else
  8468. memcpy (text->text, t, i);
  8469. #endif
  8470. text->text [i] = 0;
  8471. }
  8472. else
  8473. {
  8474. text = &emptyString;
  8475. emptyString.refCount = safeEmptyStringRefCount;
  8476. }
  8477. }
  8478. String::String (const juce_wchar* const t,
  8479. const int maxChars) throw()
  8480. {
  8481. int i;
  8482. for (i = 0; i < maxChars; ++i)
  8483. if (t[i] == 0)
  8484. break;
  8485. if (i > 0)
  8486. {
  8487. createInternal (i);
  8488. #if JUCE_STRINGS_ARE_UNICODE
  8489. memcpy (text->text, t, i * sizeof (tchar));
  8490. #else
  8491. CharacterFunctions::copy (text->text, t, i);
  8492. #endif
  8493. text->text [i] = 0;
  8494. }
  8495. else
  8496. {
  8497. text = &emptyString;
  8498. emptyString.refCount = safeEmptyStringRefCount;
  8499. }
  8500. }
  8501. const String String::charToString (const tchar character) throw()
  8502. {
  8503. tchar temp[2];
  8504. temp[0] = character;
  8505. temp[1] = 0;
  8506. return String (temp);
  8507. }
  8508. // pass in a pointer to the END of a buffer..
  8509. static tchar* int64ToCharString (tchar* t, const int64 n) throw()
  8510. {
  8511. *--t = 0;
  8512. int64 v = (n >= 0) ? n : -n;
  8513. do
  8514. {
  8515. *--t = (tchar) (T('0') + (int) (v % 10));
  8516. v /= 10;
  8517. } while (v > 0);
  8518. if (n < 0)
  8519. *--t = T('-');
  8520. return t;
  8521. }
  8522. static tchar* intToCharString (tchar* t, const int n) throw()
  8523. {
  8524. if (n == (int) 0x80000000) // (would cause an overflow)
  8525. return int64ToCharString (t, n);
  8526. *--t = 0;
  8527. int v = abs (n);
  8528. do
  8529. {
  8530. *--t = (tchar) (T('0') + (v % 10));
  8531. v /= 10;
  8532. } while (v > 0);
  8533. if (n < 0)
  8534. *--t = T('-');
  8535. return t;
  8536. }
  8537. static tchar* uintToCharString (tchar* t, unsigned int v) throw()
  8538. {
  8539. *--t = 0;
  8540. do
  8541. {
  8542. *--t = (tchar) (T('0') + (v % 10));
  8543. v /= 10;
  8544. } while (v > 0);
  8545. return t;
  8546. }
  8547. String::String (const int number) throw()
  8548. {
  8549. tchar buffer [16];
  8550. tchar* const end = buffer + 16;
  8551. createInternal (intToCharString (end, number), end);
  8552. }
  8553. String::String (const unsigned int number) throw()
  8554. {
  8555. tchar buffer [16];
  8556. tchar* const end = buffer + 16;
  8557. createInternal (uintToCharString (end, number), end);
  8558. }
  8559. String::String (const short number) throw()
  8560. {
  8561. tchar buffer [16];
  8562. tchar* const end = buffer + 16;
  8563. createInternal (intToCharString (end, (int) number), end);
  8564. }
  8565. String::String (const unsigned short number) throw()
  8566. {
  8567. tchar buffer [16];
  8568. tchar* const end = buffer + 16;
  8569. createInternal (uintToCharString (end, (unsigned int) number), end);
  8570. }
  8571. String::String (const int64 number) throw()
  8572. {
  8573. tchar buffer [32];
  8574. tchar* const end = buffer + 32;
  8575. createInternal (int64ToCharString (end, number), end);
  8576. }
  8577. String::String (const uint64 number) throw()
  8578. {
  8579. tchar buffer [32];
  8580. tchar* const end = buffer + 32;
  8581. tchar* t = end;
  8582. *--t = 0;
  8583. int64 v = number;
  8584. do
  8585. {
  8586. *--t = (tchar) (T('0') + (int) (v % 10));
  8587. v /= 10;
  8588. } while (v > 0);
  8589. createInternal (t, end);
  8590. }
  8591. // a double-to-string routine that actually uses the number of dec. places you asked for
  8592. // without resorting to exponent notation if the number's too big or small (which is what printf does).
  8593. void String::doubleToStringWithDecPlaces (double n, int numDecPlaces) throw()
  8594. {
  8595. const int bufSize = 80;
  8596. tchar buffer [bufSize];
  8597. int len;
  8598. tchar* t;
  8599. if (numDecPlaces > 0 && n > -1.0e20 && n < 1.0e20)
  8600. {
  8601. int64 v = (int64) (pow (10.0, numDecPlaces) * fabs (n) + 0.5);
  8602. t = buffer + bufSize;
  8603. *--t = (tchar) 0;
  8604. while (numDecPlaces >= 0 || v > 0)
  8605. {
  8606. if (numDecPlaces == 0)
  8607. *--t = decimalPoint;
  8608. *--t = (tchar) (T('0') + (v % 10));
  8609. v /= 10;
  8610. --numDecPlaces;
  8611. }
  8612. if (n < 0)
  8613. *--t = T('-');
  8614. len = (int) ((buffer + bufSize) - t);
  8615. }
  8616. else
  8617. {
  8618. len = CharacterFunctions::printf (buffer, bufSize, T("%.9g"), n) + 1;
  8619. t = buffer;
  8620. }
  8621. if (len > 1)
  8622. {
  8623. jassert (len < numElementsInArray (buffer));
  8624. createInternal (len - 1);
  8625. memcpy (text->text, t, len * sizeof (tchar));
  8626. }
  8627. else
  8628. {
  8629. jassert (*t == 0);
  8630. text = &emptyString;
  8631. emptyString.refCount = safeEmptyStringRefCount;
  8632. }
  8633. }
  8634. String::String (const float number,
  8635. const int numberOfDecimalPlaces) throw()
  8636. {
  8637. doubleToStringWithDecPlaces ((double) number,
  8638. numberOfDecimalPlaces);
  8639. }
  8640. String::String (const double number,
  8641. const int numberOfDecimalPlaces) throw()
  8642. {
  8643. doubleToStringWithDecPlaces (number,
  8644. numberOfDecimalPlaces);
  8645. }
  8646. String::~String() throw()
  8647. {
  8648. emptyString.refCount = safeEmptyStringRefCount;
  8649. if (atomicDecrementAndReturn (text->refCount) == 0)
  8650. juce_free (text);
  8651. }
  8652. void String::preallocateStorage (const int numChars) throw()
  8653. {
  8654. if (numChars > text->allocatedNumChars)
  8655. {
  8656. dupeInternalIfMultiplyReferenced();
  8657. text = (InternalRefCountedStringHolder*) juce_realloc (text, sizeof (InternalRefCountedStringHolder)
  8658. + numChars * sizeof (tchar));
  8659. text->allocatedNumChars = numChars;
  8660. }
  8661. }
  8662. #if JUCE_STRINGS_ARE_UNICODE
  8663. String::operator const char*() const throw()
  8664. {
  8665. if (isEmpty())
  8666. {
  8667. return (const char*) emptyCharString;
  8668. }
  8669. else
  8670. {
  8671. String* const mutableThis = const_cast <String*> (this);
  8672. mutableThis->dupeInternalIfMultiplyReferenced();
  8673. int len = CharacterFunctions::bytesRequiredForCopy (text->text) + 1;
  8674. mutableThis->text = (InternalRefCountedStringHolder*)
  8675. juce_realloc (text, sizeof (InternalRefCountedStringHolder)
  8676. + (len * sizeof (juce_wchar) + len));
  8677. char* otherCopy = (char*) (text->text + len);
  8678. --len;
  8679. CharacterFunctions::copy (otherCopy, text->text, len);
  8680. otherCopy [len] = 0;
  8681. return otherCopy;
  8682. }
  8683. }
  8684. #else
  8685. String::operator const juce_wchar*() const throw()
  8686. {
  8687. if (isEmpty())
  8688. {
  8689. return (const juce_wchar*) emptyCharString;
  8690. }
  8691. else
  8692. {
  8693. String* const mutableThis = const_cast <String*> (this);
  8694. mutableThis->dupeInternalIfMultiplyReferenced();
  8695. int len = CharacterFunctions::length (text->text) + 1;
  8696. mutableThis->text = (InternalRefCountedStringHolder*)
  8697. juce_realloc (text, sizeof (InternalRefCountedStringHolder)
  8698. + (len * sizeof (juce_wchar) + len));
  8699. juce_wchar* otherCopy = (juce_wchar*) (text->text + len);
  8700. --len;
  8701. CharacterFunctions::copy (otherCopy, text->text, len);
  8702. otherCopy [len] = 0;
  8703. return otherCopy;
  8704. }
  8705. }
  8706. #endif
  8707. void String::copyToBuffer (char* const destBuffer,
  8708. const int bufferSizeBytes) const throw()
  8709. {
  8710. #if JUCE_STRINGS_ARE_UNICODE
  8711. const int len = jmin (bufferSizeBytes, CharacterFunctions::bytesRequiredForCopy (text->text));
  8712. CharacterFunctions::copy (destBuffer, text->text, len);
  8713. #else
  8714. const int len = jmin (bufferSizeBytes, length());
  8715. memcpy (destBuffer, text->text, len * sizeof (tchar));
  8716. #endif
  8717. destBuffer [len] = 0;
  8718. }
  8719. void String::copyToBuffer (juce_wchar* const destBuffer,
  8720. const int maxCharsToCopy) const throw()
  8721. {
  8722. const int len = jmin (maxCharsToCopy, length());
  8723. #if JUCE_STRINGS_ARE_UNICODE
  8724. memcpy (destBuffer, text->text, len * sizeof (juce_wchar));
  8725. #else
  8726. CharacterFunctions::copy (destBuffer, text->text, len);
  8727. #endif
  8728. destBuffer [len] = 0;
  8729. }
  8730. int String::length() const throw()
  8731. {
  8732. return CharacterFunctions::length (text->text);
  8733. }
  8734. int String::hashCode() const throw()
  8735. {
  8736. const tchar* t = text->text;
  8737. int result = 0;
  8738. while (*t != (tchar) 0)
  8739. result = 31 * result + *t++;
  8740. return result;
  8741. }
  8742. int64 String::hashCode64() const throw()
  8743. {
  8744. const tchar* t = text->text;
  8745. int64 result = 0;
  8746. while (*t != (tchar) 0)
  8747. result = 101 * result + *t++;
  8748. return result;
  8749. }
  8750. const String& String::operator= (const tchar* const otherText) throw()
  8751. {
  8752. if (otherText != 0 && *otherText != 0)
  8753. {
  8754. const int otherLen = CharacterFunctions::length (otherText);
  8755. if (otherLen > 0)
  8756. {
  8757. // avoid resizing the memory block if the string is
  8758. // shrinking..
  8759. if (text->refCount > 1
  8760. || otherLen > text->allocatedNumChars
  8761. || otherLen <= (text->allocatedNumChars >> 1))
  8762. {
  8763. deleteInternal();
  8764. createInternal (otherLen);
  8765. }
  8766. memcpy (text->text, otherText, (otherLen + 1) * sizeof (tchar));
  8767. return *this;
  8768. }
  8769. }
  8770. deleteInternal();
  8771. text = &emptyString;
  8772. emptyString.refCount = safeEmptyStringRefCount;
  8773. return *this;
  8774. }
  8775. const String& String::operator= (const String& other) throw()
  8776. {
  8777. if (this != &other)
  8778. {
  8779. atomicIncrement (other.text->refCount);
  8780. if (atomicDecrementAndReturn (text->refCount) == 0)
  8781. juce_free (text);
  8782. text = other.text;
  8783. }
  8784. return *this;
  8785. }
  8786. bool String::operator== (const String& other) const throw()
  8787. {
  8788. return text == other.text
  8789. || CharacterFunctions::compare (text->text, other.text->text) == 0;
  8790. }
  8791. bool String::operator== (const tchar* const t) const throw()
  8792. {
  8793. return t != 0 ? CharacterFunctions::compare (text->text, t) == 0
  8794. : isEmpty();
  8795. }
  8796. bool String::equalsIgnoreCase (const tchar* t) const throw()
  8797. {
  8798. return t != 0 ? CharacterFunctions::compareIgnoreCase (text->text, t) == 0
  8799. : isEmpty();
  8800. }
  8801. bool String::equalsIgnoreCase (const String& other) const throw()
  8802. {
  8803. return text == other.text
  8804. || CharacterFunctions::compareIgnoreCase (text->text, other.text->text) == 0;
  8805. }
  8806. bool String::operator!= (const String& other) const throw()
  8807. {
  8808. return text != other.text
  8809. && CharacterFunctions::compare (text->text, other.text->text) != 0;
  8810. }
  8811. bool String::operator!= (const tchar* const t) const throw()
  8812. {
  8813. return t != 0 ? (CharacterFunctions::compare (text->text, t) != 0)
  8814. : isNotEmpty();
  8815. }
  8816. bool String::operator> (const String& other) const throw()
  8817. {
  8818. return compare (other) > 0;
  8819. }
  8820. bool String::operator< (const tchar* const other) const throw()
  8821. {
  8822. return compare (other) < 0;
  8823. }
  8824. bool String::operator>= (const String& other) const throw()
  8825. {
  8826. return compare (other) >= 0;
  8827. }
  8828. bool String::operator<= (const tchar* const other) const throw()
  8829. {
  8830. return compare (other) <= 0;
  8831. }
  8832. int String::compare (const tchar* const other) const throw()
  8833. {
  8834. return other != 0 ? CharacterFunctions::compare (text->text, other)
  8835. : isEmpty();
  8836. }
  8837. int String::compareIgnoreCase (const tchar* const other) const throw()
  8838. {
  8839. return other != 0 ? CharacterFunctions::compareIgnoreCase (text->text, other)
  8840. : isEmpty();
  8841. }
  8842. int String::compareLexicographically (const tchar* other) const throw()
  8843. {
  8844. if (other == 0)
  8845. return isEmpty();
  8846. const tchar* s1 = text->text;
  8847. while (*s1 != 0 && ! CharacterFunctions::isLetterOrDigit (*s1))
  8848. ++s1;
  8849. while (*other != 0 && ! CharacterFunctions::isLetterOrDigit (*other))
  8850. ++other;
  8851. return CharacterFunctions::compareIgnoreCase (s1, other);
  8852. }
  8853. const String String::operator+ (const String& other) const throw()
  8854. {
  8855. if (*(other.text->text) == 0)
  8856. return *this;
  8857. if (isEmpty())
  8858. return other;
  8859. const int len = CharacterFunctions::length (text->text);
  8860. const int otherLen = CharacterFunctions::length (other.text->text);
  8861. String result (len + otherLen, (int) 0);
  8862. memcpy (result.text->text, text->text, len * sizeof (tchar));
  8863. memcpy (result.text->text + len, other.text->text, otherLen * sizeof (tchar));
  8864. result.text->text [len + otherLen] = 0;
  8865. return result;
  8866. }
  8867. const String String::operator+ (const tchar* const textToAppend) const throw()
  8868. {
  8869. if (textToAppend == 0 || *textToAppend == 0)
  8870. return *this;
  8871. const int len = CharacterFunctions::length (text->text);
  8872. const int otherLen = CharacterFunctions::length (textToAppend);
  8873. String result (len + otherLen, (int) 0);
  8874. memcpy (result.text->text, text->text, len * sizeof (tchar));
  8875. memcpy (result.text->text + len, textToAppend, otherLen * sizeof (tchar));
  8876. result.text->text [len + otherLen] = 0;
  8877. return result;
  8878. }
  8879. const String String::operator+ (const tchar characterToAppend) const throw()
  8880. {
  8881. if (characterToAppend == 0)
  8882. return *this;
  8883. const int len = CharacterFunctions::length (text->text);
  8884. String result ((int) (len + 1), (int) 0);
  8885. memcpy (result.text->text, text->text, len * sizeof (tchar));
  8886. result.text->text[len] = characterToAppend;
  8887. result.text->text[len + 1] = 0;
  8888. return result;
  8889. }
  8890. const String JUCE_PUBLIC_FUNCTION operator+ (const char* const string1,
  8891. const String& string2) throw()
  8892. {
  8893. String s (string1);
  8894. s += string2;
  8895. return s;
  8896. }
  8897. const String JUCE_PUBLIC_FUNCTION operator+ (const juce_wchar* const string1,
  8898. const String& string2) throw()
  8899. {
  8900. String s (string1);
  8901. s += string2;
  8902. return s;
  8903. }
  8904. const String& String::operator+= (const tchar* const t) throw()
  8905. {
  8906. if (t != 0)
  8907. appendInternal (t, CharacterFunctions::length (t));
  8908. return *this;
  8909. }
  8910. const String& String::operator+= (const String& other) throw()
  8911. {
  8912. if (isEmpty())
  8913. operator= (other);
  8914. else
  8915. appendInternal (other.text->text,
  8916. CharacterFunctions::length (other.text->text));
  8917. return *this;
  8918. }
  8919. const String& String::operator+= (const char ch) throw()
  8920. {
  8921. char asString[2];
  8922. asString[0] = ch;
  8923. asString[1] = 0;
  8924. #if JUCE_STRINGS_ARE_UNICODE
  8925. operator+= (String (asString));
  8926. #else
  8927. appendInternal (asString, 1);
  8928. #endif
  8929. return *this;
  8930. }
  8931. const String& String::operator+= (const juce_wchar ch) throw()
  8932. {
  8933. juce_wchar asString[2];
  8934. asString[0] = ch;
  8935. asString[1] = 0;
  8936. #if JUCE_STRINGS_ARE_UNICODE
  8937. appendInternal (asString, 1);
  8938. #else
  8939. operator+= (String (asString));
  8940. #endif
  8941. return *this;
  8942. }
  8943. void String::append (const tchar* const other,
  8944. const int howMany) throw()
  8945. {
  8946. if (howMany > 0)
  8947. {
  8948. int i;
  8949. for (i = 0; i < howMany; ++i)
  8950. if (other[i] == 0)
  8951. break;
  8952. appendInternal (other, i);
  8953. }
  8954. }
  8955. String& String::operator<< (const int number) throw()
  8956. {
  8957. tchar buffer [64];
  8958. tchar* const end = buffer + 64;
  8959. const tchar* const t = intToCharString (end, number);
  8960. appendInternal (t, (int) (end - t) - 1);
  8961. return *this;
  8962. }
  8963. String& String::operator<< (const unsigned int number) throw()
  8964. {
  8965. tchar buffer [64];
  8966. tchar* const end = buffer + 64;
  8967. const tchar* const t = uintToCharString (end, number);
  8968. appendInternal (t, (int) (end - t) - 1);
  8969. return *this;
  8970. }
  8971. String& String::operator<< (const short number) throw()
  8972. {
  8973. tchar buffer [64];
  8974. tchar* const end = buffer + 64;
  8975. const tchar* const t = intToCharString (end, (int) number);
  8976. appendInternal (t, (int) (end - t) - 1);
  8977. return *this;
  8978. }
  8979. String& String::operator<< (const double number) throw()
  8980. {
  8981. operator+= (String (number));
  8982. return *this;
  8983. }
  8984. String& String::operator<< (const float number) throw()
  8985. {
  8986. operator+= (String (number));
  8987. return *this;
  8988. }
  8989. String& String::operator<< (const char character) throw()
  8990. {
  8991. operator+= (character);
  8992. return *this;
  8993. }
  8994. String& String::operator<< (const juce_wchar character) throw()
  8995. {
  8996. operator+= (character);
  8997. return *this;
  8998. }
  8999. String& String::operator<< (const char* const t) throw()
  9000. {
  9001. #if JUCE_STRINGS_ARE_UNICODE
  9002. operator+= (String (t));
  9003. #else
  9004. operator+= (t);
  9005. #endif
  9006. return *this;
  9007. }
  9008. String& String::operator<< (const juce_wchar* const t) throw()
  9009. {
  9010. #if JUCE_STRINGS_ARE_UNICODE
  9011. operator+= (t);
  9012. #else
  9013. operator+= (String (t));
  9014. #endif
  9015. return *this;
  9016. }
  9017. String& String::operator<< (const String& t) throw()
  9018. {
  9019. operator+= (t);
  9020. return *this;
  9021. }
  9022. int String::indexOfChar (const tchar character) const throw()
  9023. {
  9024. const tchar* t = text->text;
  9025. for (;;)
  9026. {
  9027. if (*t == character)
  9028. return (int) (t - text->text);
  9029. if (*t++ == 0)
  9030. return -1;
  9031. }
  9032. }
  9033. int String::lastIndexOfChar (const tchar character) const throw()
  9034. {
  9035. for (int i = CharacterFunctions::length (text->text); --i >= 0;)
  9036. if (text->text[i] == character)
  9037. return i;
  9038. return -1;
  9039. }
  9040. int String::indexOf (const tchar* const t) const throw()
  9041. {
  9042. const tchar* const r = CharacterFunctions::find (text->text, t);
  9043. return (r == 0) ? -1
  9044. : (int) (r - text->text);
  9045. }
  9046. int String::indexOfChar (const int startIndex,
  9047. const tchar character) const throw()
  9048. {
  9049. if (startIndex >= 0 && startIndex >= CharacterFunctions::length (text->text))
  9050. return -1;
  9051. const tchar* t = text->text + jmax (0, startIndex);
  9052. for (;;)
  9053. {
  9054. if (*t == character)
  9055. return (int) (t - text->text);
  9056. if (*t++ == 0)
  9057. return -1;
  9058. }
  9059. }
  9060. int String::indexOfAnyOf (const tchar* const charactersToLookFor,
  9061. const int startIndex,
  9062. const bool ignoreCase) const throw()
  9063. {
  9064. if (charactersToLookFor == 0
  9065. || (startIndex >= 0 && startIndex >= CharacterFunctions::length (text->text)))
  9066. return -1;
  9067. const tchar* t = text->text + jmax (0, startIndex);
  9068. while (*t != 0)
  9069. {
  9070. if (CharacterFunctions::indexOfChar (charactersToLookFor, *t, ignoreCase) >= 0)
  9071. return (int) (t - text->text);
  9072. ++t;
  9073. }
  9074. return -1;
  9075. }
  9076. int String::indexOf (const int startIndex,
  9077. const tchar* const other) const throw()
  9078. {
  9079. if (other == 0 || startIndex >= CharacterFunctions::length (text->text))
  9080. return -1;
  9081. const tchar* const found = CharacterFunctions::find (text->text + jmax (0, startIndex),
  9082. other);
  9083. return (found == 0) ? -1
  9084. : (int) (found - text->text);
  9085. }
  9086. int String::indexOfIgnoreCase (const tchar* const other) const throw()
  9087. {
  9088. if (other != 0 && *other != 0)
  9089. {
  9090. const int len = CharacterFunctions::length (other);
  9091. const int end = CharacterFunctions::length (text->text) - len;
  9092. for (int i = 0; i <= end; ++i)
  9093. if (CharacterFunctions::compareIgnoreCase (text->text + i, other, len) == 0)
  9094. return i;
  9095. }
  9096. return -1;
  9097. }
  9098. int String::indexOfIgnoreCase (const int startIndex,
  9099. const tchar* const other) const throw()
  9100. {
  9101. if (other != 0 && *other != 0)
  9102. {
  9103. const int len = CharacterFunctions::length (other);
  9104. const int end = length() - len;
  9105. for (int i = jmax (0, startIndex); i <= end; ++i)
  9106. if (CharacterFunctions::compareIgnoreCase (text->text + i, other, len) == 0)
  9107. return i;
  9108. }
  9109. return -1;
  9110. }
  9111. int String::lastIndexOf (const tchar* const other) const throw()
  9112. {
  9113. if (other != 0 && *other != 0)
  9114. {
  9115. const int len = CharacterFunctions::length (other);
  9116. int i = length() - len;
  9117. if (i >= 0)
  9118. {
  9119. const tchar* n = text->text + i;
  9120. while (i >= 0)
  9121. {
  9122. if (CharacterFunctions::compare (n--, other, len) == 0)
  9123. return i;
  9124. --i;
  9125. }
  9126. }
  9127. }
  9128. return -1;
  9129. }
  9130. int String::lastIndexOfIgnoreCase (const tchar* const other) const throw()
  9131. {
  9132. if (other != 0 && *other != 0)
  9133. {
  9134. const int len = CharacterFunctions::length (other);
  9135. int i = length() - len;
  9136. if (i >= 0)
  9137. {
  9138. const tchar* n = text->text + i;
  9139. while (i >= 0)
  9140. {
  9141. if (CharacterFunctions::compareIgnoreCase (n--, other, len) == 0)
  9142. return i;
  9143. --i;
  9144. }
  9145. }
  9146. }
  9147. return -1;
  9148. }
  9149. int String::lastIndexOfAnyOf (const tchar* const charactersToLookFor,
  9150. const bool ignoreCase) const throw()
  9151. {
  9152. for (int i = CharacterFunctions::length (text->text); --i >= 0;)
  9153. if (CharacterFunctions::indexOfChar (charactersToLookFor, text->text [i], ignoreCase) >= 0)
  9154. return i;
  9155. return -1;
  9156. }
  9157. bool String::contains (const tchar* const other) const throw()
  9158. {
  9159. return indexOf (other) >= 0;
  9160. }
  9161. bool String::containsChar (const tchar character) const throw()
  9162. {
  9163. return indexOfChar (character) >= 0;
  9164. }
  9165. bool String::containsIgnoreCase (const tchar* const t) const throw()
  9166. {
  9167. return indexOfIgnoreCase (t) >= 0;
  9168. }
  9169. int String::indexOfWholeWord (const tchar* const word) const throw()
  9170. {
  9171. if (word != 0 && *word != 0)
  9172. {
  9173. const int wordLen = CharacterFunctions::length (word);
  9174. const int end = length() - wordLen;
  9175. const tchar* t = text->text;
  9176. for (int i = 0; i <= end; ++i)
  9177. {
  9178. if (CharacterFunctions::compare (t, word, wordLen) == 0
  9179. && (i == 0 || ! CharacterFunctions::isLetterOrDigit (* (t - 1)))
  9180. && ! CharacterFunctions::isLetterOrDigit (t [wordLen]))
  9181. {
  9182. return i;
  9183. }
  9184. ++t;
  9185. }
  9186. }
  9187. return -1;
  9188. }
  9189. int String::indexOfWholeWordIgnoreCase (const tchar* const word) const throw()
  9190. {
  9191. if (word != 0 && *word != 0)
  9192. {
  9193. const int wordLen = CharacterFunctions::length (word);
  9194. const int end = length() - wordLen;
  9195. const tchar* t = text->text;
  9196. for (int i = 0; i <= end; ++i)
  9197. {
  9198. if (CharacterFunctions::compareIgnoreCase (t, word, wordLen) == 0
  9199. && (i == 0 || ! CharacterFunctions::isLetterOrDigit (* (t - 1)))
  9200. && ! CharacterFunctions::isLetterOrDigit (t [wordLen]))
  9201. {
  9202. return i;
  9203. }
  9204. ++t;
  9205. }
  9206. }
  9207. return -1;
  9208. }
  9209. bool String::containsWholeWord (const tchar* const wordToLookFor) const throw()
  9210. {
  9211. return indexOfWholeWord (wordToLookFor) >= 0;
  9212. }
  9213. bool String::containsWholeWordIgnoreCase (const tchar* const wordToLookFor) const throw()
  9214. {
  9215. return indexOfWholeWordIgnoreCase (wordToLookFor) >= 0;
  9216. }
  9217. static int indexOfMatch (const tchar* const wildcard,
  9218. const tchar* const test,
  9219. const bool ignoreCase) throw()
  9220. {
  9221. int start = 0;
  9222. while (test [start] != 0)
  9223. {
  9224. int i = 0;
  9225. for (;;)
  9226. {
  9227. const tchar wc = wildcard [i];
  9228. const tchar c = test [i + start];
  9229. if (wc == c
  9230. || (ignoreCase && CharacterFunctions::toLowerCase (wc) == CharacterFunctions::toLowerCase (c))
  9231. || (wc == T('?') && c != 0))
  9232. {
  9233. if (wc == 0)
  9234. return start;
  9235. ++i;
  9236. }
  9237. else
  9238. {
  9239. if (wc == T('*') && (wildcard [i + 1] == 0
  9240. || indexOfMatch (wildcard + i + 1,
  9241. test + start + i,
  9242. ignoreCase) >= 0))
  9243. {
  9244. return start;
  9245. }
  9246. break;
  9247. }
  9248. }
  9249. ++start;
  9250. }
  9251. return -1;
  9252. }
  9253. bool String::matchesWildcard (const tchar* wildcard, const bool ignoreCase) const throw()
  9254. {
  9255. int i = 0;
  9256. for (;;)
  9257. {
  9258. const tchar wc = wildcard [i];
  9259. const tchar c = text->text [i];
  9260. if (wc == c
  9261. || (ignoreCase && CharacterFunctions::toLowerCase (wc) == CharacterFunctions::toLowerCase (c))
  9262. || (wc == T('?') && c != 0))
  9263. {
  9264. if (wc == 0)
  9265. return true;
  9266. ++i;
  9267. }
  9268. else
  9269. {
  9270. return wc == T('*') && (wildcard [i + 1] == 0
  9271. || indexOfMatch (wildcard + i + 1,
  9272. text->text + i,
  9273. ignoreCase) >= 0);
  9274. }
  9275. }
  9276. }
  9277. void String::printf (const tchar* const pf, ...) throw()
  9278. {
  9279. va_list list;
  9280. va_start (list, pf);
  9281. vprintf (pf, list);
  9282. }
  9283. const String String::formatted (const tchar* const pf, ...) throw()
  9284. {
  9285. va_list list;
  9286. va_start (list, pf);
  9287. String result;
  9288. result.vprintf (pf, list);
  9289. return result;
  9290. }
  9291. void String::vprintf (const tchar* const pf, va_list& args) throw()
  9292. {
  9293. tchar stackBuf [256];
  9294. unsigned int bufSize = 256;
  9295. tchar* buf = stackBuf;
  9296. deleteInternal();
  9297. do
  9298. {
  9299. #if JUCE_LINUX && JUCE_64BIT
  9300. va_list tempArgs;
  9301. va_copy (tempArgs, args);
  9302. const int num = CharacterFunctions::vprintf (buf, bufSize - 1, pf, tempArgs);
  9303. va_end (tempArgs);
  9304. #else
  9305. const int num = CharacterFunctions::vprintf (buf, bufSize - 1, pf, args);
  9306. #endif
  9307. if (num > 0)
  9308. {
  9309. createInternal (num);
  9310. memcpy (text->text, buf, (num + 1) * sizeof (tchar));
  9311. break;
  9312. }
  9313. else if (num == 0)
  9314. {
  9315. text = &emptyString;
  9316. emptyString.refCount = safeEmptyStringRefCount;
  9317. break;
  9318. }
  9319. if (buf != stackBuf)
  9320. juce_free (buf);
  9321. bufSize += 256;
  9322. buf = (tchar*) juce_malloc (bufSize * sizeof (tchar));
  9323. }
  9324. while (bufSize < 65536); // this is a sanity check to avoid situations where vprintf repeatedly
  9325. // returns -1 because of an error rather than because it needs more space.
  9326. if (buf != stackBuf)
  9327. juce_free (buf);
  9328. }
  9329. const String String::repeatedString (const tchar* const stringToRepeat,
  9330. int numberOfTimesToRepeat) throw()
  9331. {
  9332. const int len = CharacterFunctions::length (stringToRepeat);
  9333. String result ((int) (len * numberOfTimesToRepeat + 1), (int) 0);
  9334. tchar* n = result.text->text;
  9335. n[0] = 0;
  9336. while (--numberOfTimesToRepeat >= 0)
  9337. {
  9338. CharacterFunctions::append (n, stringToRepeat);
  9339. n += len;
  9340. }
  9341. return result;
  9342. }
  9343. const String String::replaceSection (int index,
  9344. int numCharsToReplace,
  9345. const tchar* const stringToInsert) const throw()
  9346. {
  9347. if (index < 0)
  9348. {
  9349. // a negative index to replace from?
  9350. jassertfalse
  9351. index = 0;
  9352. }
  9353. if (numCharsToReplace < 0)
  9354. {
  9355. // replacing a negative number of characters?
  9356. numCharsToReplace = 0;
  9357. jassertfalse;
  9358. }
  9359. const int len = length();
  9360. if (index + numCharsToReplace > len)
  9361. {
  9362. if (index > len)
  9363. {
  9364. // replacing beyond the end of the string?
  9365. index = len;
  9366. jassertfalse
  9367. }
  9368. numCharsToReplace = len - index;
  9369. }
  9370. const int newStringLen = (stringToInsert != 0) ? CharacterFunctions::length (stringToInsert) : 0;
  9371. const int newTotalLen = len + newStringLen - numCharsToReplace;
  9372. if (newTotalLen <= 0)
  9373. return String::empty;
  9374. String result (newTotalLen, (int) 0);
  9375. memcpy (result.text->text,
  9376. text->text,
  9377. index * sizeof (tchar));
  9378. if (newStringLen > 0)
  9379. memcpy (result.text->text + index,
  9380. stringToInsert,
  9381. newStringLen * sizeof (tchar));
  9382. const int endStringLen = newTotalLen - (index + newStringLen);
  9383. if (endStringLen > 0)
  9384. memcpy (result.text->text + (index + newStringLen),
  9385. text->text + (index + numCharsToReplace),
  9386. endStringLen * sizeof (tchar));
  9387. result.text->text [newTotalLen] = 0;
  9388. return result;
  9389. }
  9390. const String String::replace (const tchar* const stringToReplace,
  9391. const tchar* const stringToInsert,
  9392. const bool ignoreCase) const throw()
  9393. {
  9394. const int stringToReplaceLen = CharacterFunctions::length (stringToReplace);
  9395. const int stringToInsertLen = CharacterFunctions::length (stringToInsert);
  9396. int i = 0;
  9397. String result (*this);
  9398. while ((i = (ignoreCase ? result.indexOfIgnoreCase (i, stringToReplace)
  9399. : result.indexOf (i, stringToReplace))) >= 0)
  9400. {
  9401. result = result.replaceSection (i, stringToReplaceLen, stringToInsert);
  9402. i += stringToInsertLen;
  9403. }
  9404. return result;
  9405. }
  9406. const String String::replaceCharacter (const tchar charToReplace,
  9407. const tchar charToInsert) const throw()
  9408. {
  9409. const int index = indexOfChar (charToReplace);
  9410. if (index < 0)
  9411. return *this;
  9412. String result (*this);
  9413. result.dupeInternalIfMultiplyReferenced();
  9414. tchar* t = result.text->text + index;
  9415. while (*t != 0)
  9416. {
  9417. if (*t == charToReplace)
  9418. *t = charToInsert;
  9419. ++t;
  9420. }
  9421. return result;
  9422. }
  9423. const String String::replaceCharacters (const String& charactersToReplace,
  9424. const tchar* const charactersToInsertInstead) const throw()
  9425. {
  9426. String result (*this);
  9427. result.dupeInternalIfMultiplyReferenced();
  9428. tchar* t = result.text->text;
  9429. const int len2 = CharacterFunctions::length (charactersToInsertInstead);
  9430. // the two strings passed in are supposed to be the same length!
  9431. jassert (len2 == charactersToReplace.length());
  9432. while (*t != 0)
  9433. {
  9434. const int index = charactersToReplace.indexOfChar (*t);
  9435. if (((unsigned int) index) < (unsigned int) len2)
  9436. *t = charactersToInsertInstead [index];
  9437. ++t;
  9438. }
  9439. return result;
  9440. }
  9441. bool String::startsWith (const tchar* const other) const throw()
  9442. {
  9443. return other != 0
  9444. && CharacterFunctions::compare (text->text, other, CharacterFunctions::length (other)) == 0;
  9445. }
  9446. bool String::startsWithIgnoreCase (const tchar* const other) const throw()
  9447. {
  9448. return other != 0
  9449. && CharacterFunctions::compareIgnoreCase (text->text, other, CharacterFunctions::length (other)) == 0;
  9450. }
  9451. bool String::startsWithChar (const tchar character) const throw()
  9452. {
  9453. jassert (character != 0); // strings can't contain a null character!
  9454. return text->text[0] == character;
  9455. }
  9456. bool String::endsWithChar (const tchar character) const throw()
  9457. {
  9458. jassert (character != 0); // strings can't contain a null character!
  9459. return text->text[0] != 0
  9460. && text->text [length() - 1] == character;
  9461. }
  9462. bool String::endsWith (const tchar* const other) const throw()
  9463. {
  9464. if (other == 0)
  9465. return false;
  9466. const int thisLen = length();
  9467. const int otherLen = CharacterFunctions::length (other);
  9468. return thisLen >= otherLen
  9469. && CharacterFunctions::compare (text->text + thisLen - otherLen, other) == 0;
  9470. }
  9471. bool String::endsWithIgnoreCase (const tchar* const other) const throw()
  9472. {
  9473. if (other == 0)
  9474. return false;
  9475. const int thisLen = length();
  9476. const int otherLen = CharacterFunctions::length (other);
  9477. return thisLen >= otherLen
  9478. && CharacterFunctions::compareIgnoreCase (text->text + thisLen - otherLen, other) == 0;
  9479. }
  9480. const String String::toUpperCase() const throw()
  9481. {
  9482. String result (*this);
  9483. result.dupeInternalIfMultiplyReferenced();
  9484. CharacterFunctions::toUpperCase (result.text->text);
  9485. return result;
  9486. }
  9487. const String String::toLowerCase() const throw()
  9488. {
  9489. String result (*this);
  9490. result.dupeInternalIfMultiplyReferenced();
  9491. CharacterFunctions::toLowerCase (result.text->text);
  9492. return result;
  9493. }
  9494. tchar& String::operator[] (const int index) throw()
  9495. {
  9496. jassert (((unsigned int) index) <= (unsigned int) length());
  9497. dupeInternalIfMultiplyReferenced();
  9498. return text->text [index];
  9499. }
  9500. tchar String::getLastCharacter() const throw()
  9501. {
  9502. return (isEmpty()) ? ((tchar) 0)
  9503. : text->text [CharacterFunctions::length (text->text) - 1];
  9504. }
  9505. const String String::substring (int start, int end) const throw()
  9506. {
  9507. if (start < 0)
  9508. start = 0;
  9509. else if (end <= start)
  9510. return empty;
  9511. int len = 0;
  9512. const tchar* const t = text->text;
  9513. while (len <= end && t [len] != 0)
  9514. ++len;
  9515. if (end >= len)
  9516. {
  9517. if (start == 0)
  9518. return *this;
  9519. end = len;
  9520. }
  9521. return String (text->text + start,
  9522. end - start);
  9523. }
  9524. const String String::substring (const int start) const throw()
  9525. {
  9526. if (start <= 0)
  9527. return *this;
  9528. const int len = CharacterFunctions::length (text->text);
  9529. if (start >= len)
  9530. return empty;
  9531. else
  9532. return String (text->text + start,
  9533. len - start);
  9534. }
  9535. const String String::dropLastCharacters (const int numberToDrop) const throw()
  9536. {
  9537. return String (text->text,
  9538. jmax (0, CharacterFunctions::length (text->text) - numberToDrop));
  9539. }
  9540. const String String::fromFirstOccurrenceOf (const tchar* const sub,
  9541. const bool includeSubString,
  9542. const bool ignoreCase) const throw()
  9543. {
  9544. const int i = ignoreCase ? indexOfIgnoreCase (sub)
  9545. : indexOf (sub);
  9546. if (i < 0)
  9547. return empty;
  9548. else
  9549. return substring (includeSubString ? i : i + CharacterFunctions::length (sub));
  9550. }
  9551. const String String::fromLastOccurrenceOf (const tchar* const sub,
  9552. const bool includeSubString,
  9553. const bool ignoreCase) const throw()
  9554. {
  9555. const int i = ignoreCase ? lastIndexOfIgnoreCase (sub)
  9556. : lastIndexOf (sub);
  9557. if (i < 0)
  9558. return *this;
  9559. else
  9560. return substring (includeSubString ? i : i + CharacterFunctions::length (sub));
  9561. }
  9562. const String String::upToFirstOccurrenceOf (const tchar* const sub,
  9563. const bool includeSubString,
  9564. const bool ignoreCase) const throw()
  9565. {
  9566. const int i = ignoreCase ? indexOfIgnoreCase (sub)
  9567. : indexOf (sub);
  9568. if (i < 0)
  9569. return *this;
  9570. else
  9571. return substring (0, includeSubString ? i + CharacterFunctions::length (sub) : i);
  9572. }
  9573. const String String::upToLastOccurrenceOf (const tchar* const sub,
  9574. const bool includeSubString,
  9575. const bool ignoreCase) const throw()
  9576. {
  9577. const int i = ignoreCase ? lastIndexOfIgnoreCase (sub)
  9578. : lastIndexOf (sub);
  9579. if (i < 0)
  9580. return *this;
  9581. return substring (0, includeSubString ? i + CharacterFunctions::length (sub) : i);
  9582. }
  9583. bool String::isQuotedString() const throw()
  9584. {
  9585. const String trimmed (trimStart());
  9586. return trimmed[0] == T('"')
  9587. || trimmed[0] == T('\'');
  9588. }
  9589. const String String::unquoted() const throw()
  9590. {
  9591. String s (*this);
  9592. if (s[0] == T('"') || s[0] == T('\''))
  9593. s = s.substring (1);
  9594. const int lastCharIndex = s.length() - 1;
  9595. if (lastCharIndex >= 0
  9596. && (s [lastCharIndex] == T('"') || s[lastCharIndex] == T('\'')))
  9597. s [lastCharIndex] = 0;
  9598. return s;
  9599. }
  9600. const String String::quoted (const tchar quoteCharacter) const throw()
  9601. {
  9602. if (isEmpty())
  9603. return charToString (quoteCharacter) + quoteCharacter;
  9604. String t (*this);
  9605. if (! t.startsWithChar (quoteCharacter))
  9606. t = charToString (quoteCharacter) + t;
  9607. if (! t.endsWithChar (quoteCharacter))
  9608. t += quoteCharacter;
  9609. return t;
  9610. }
  9611. const String String::trim() const throw()
  9612. {
  9613. if (isEmpty())
  9614. return empty;
  9615. int start = 0;
  9616. while (CharacterFunctions::isWhitespace (text->text [start]))
  9617. ++start;
  9618. const int len = CharacterFunctions::length (text->text);
  9619. int end = len - 1;
  9620. while ((end >= start) && CharacterFunctions::isWhitespace (text->text [end]))
  9621. --end;
  9622. ++end;
  9623. if (end <= start)
  9624. return empty;
  9625. else if (start > 0 || end < len)
  9626. return String (text->text + start, end - start);
  9627. else
  9628. return *this;
  9629. }
  9630. const String String::trimStart() const throw()
  9631. {
  9632. if (isEmpty())
  9633. return empty;
  9634. const tchar* t = text->text;
  9635. while (CharacterFunctions::isWhitespace (*t))
  9636. ++t;
  9637. if (t == text->text)
  9638. return *this;
  9639. else
  9640. return String (t);
  9641. }
  9642. const String String::trimEnd() const throw()
  9643. {
  9644. if (isEmpty())
  9645. return empty;
  9646. const tchar* endT = text->text + (CharacterFunctions::length (text->text) - 1);
  9647. while ((endT >= text->text) && CharacterFunctions::isWhitespace (*endT))
  9648. --endT;
  9649. return String (text->text, (int) (++endT - text->text));
  9650. }
  9651. const String String::retainCharacters (const tchar* const charactersToRetain) const throw()
  9652. {
  9653. jassert (charactersToRetain != 0);
  9654. if (isEmpty())
  9655. return empty;
  9656. String result (text->allocatedNumChars, (int) 0);
  9657. tchar* dst = result.text->text;
  9658. const tchar* src = text->text;
  9659. while (*src != 0)
  9660. {
  9661. if (CharacterFunctions::indexOfCharFast (charactersToRetain, *src) >= 0)
  9662. *dst++ = *src;
  9663. ++src;
  9664. }
  9665. *dst = 0;
  9666. return result;
  9667. }
  9668. const String String::removeCharacters (const tchar* const charactersToRemove) const throw()
  9669. {
  9670. jassert (charactersToRemove != 0);
  9671. if (isEmpty())
  9672. return empty;
  9673. String result (text->allocatedNumChars, (int) 0);
  9674. tchar* dst = result.text->text;
  9675. const tchar* src = text->text;
  9676. while (*src != 0)
  9677. {
  9678. if (CharacterFunctions::indexOfCharFast (charactersToRemove, *src) < 0)
  9679. *dst++ = *src;
  9680. ++src;
  9681. }
  9682. *dst = 0;
  9683. return result;
  9684. }
  9685. const String String::initialSectionContainingOnly (const tchar* const permittedCharacters) const throw()
  9686. {
  9687. return substring (0, CharacterFunctions::getIntialSectionContainingOnly (text->text, permittedCharacters));
  9688. }
  9689. const String String::initialSectionNotContaining (const tchar* const charactersToStopAt) const throw()
  9690. {
  9691. jassert (charactersToStopAt != 0);
  9692. const tchar* const t = text->text;
  9693. int i = 0;
  9694. while (t[i] != 0)
  9695. {
  9696. if (CharacterFunctions::indexOfCharFast (charactersToStopAt, t[i]) >= 0)
  9697. return String (text->text, i);
  9698. ++i;
  9699. }
  9700. return empty;
  9701. }
  9702. bool String::containsOnly (const tchar* const chars) const throw()
  9703. {
  9704. jassert (chars != 0);
  9705. const tchar* t = text->text;
  9706. while (*t != 0)
  9707. if (CharacterFunctions::indexOfCharFast (chars, *t++) < 0)
  9708. return false;
  9709. return true;
  9710. }
  9711. bool String::containsAnyOf (const tchar* const chars) const throw()
  9712. {
  9713. jassert (chars != 0);
  9714. const tchar* t = text->text;
  9715. while (*t != 0)
  9716. if (CharacterFunctions::indexOfCharFast (chars, *t++) >= 0)
  9717. return true;
  9718. return false;
  9719. }
  9720. bool String::containsNonWhitespaceChars() const throw()
  9721. {
  9722. const tchar* t = text->text;
  9723. while (*t != 0)
  9724. if (! CharacterFunctions::isWhitespace (*t++))
  9725. return true;
  9726. return false;
  9727. }
  9728. int String::getIntValue() const throw()
  9729. {
  9730. return CharacterFunctions::getIntValue (text->text);
  9731. }
  9732. int String::getTrailingIntValue() const throw()
  9733. {
  9734. int n = 0;
  9735. int mult = 1;
  9736. const tchar* t = text->text + length();
  9737. while (--t >= text->text)
  9738. {
  9739. const tchar c = *t;
  9740. if (! CharacterFunctions::isDigit (c))
  9741. {
  9742. if (c == T('-'))
  9743. n = -n;
  9744. break;
  9745. }
  9746. n += mult * (c - T('0'));
  9747. mult *= 10;
  9748. }
  9749. return n;
  9750. }
  9751. int64 String::getLargeIntValue() const throw()
  9752. {
  9753. return CharacterFunctions::getInt64Value (text->text);
  9754. }
  9755. float String::getFloatValue() const throw()
  9756. {
  9757. return (float) CharacterFunctions::getDoubleValue (text->text);
  9758. }
  9759. double String::getDoubleValue() const throw()
  9760. {
  9761. return CharacterFunctions::getDoubleValue (text->text);
  9762. }
  9763. static const tchar* const hexDigits = T("0123456789abcdef");
  9764. const String String::toHexString (const int number) throw()
  9765. {
  9766. tchar buffer[32];
  9767. tchar* const end = buffer + 32;
  9768. tchar* t = end;
  9769. *--t = 0;
  9770. unsigned int v = (unsigned int) number;
  9771. do
  9772. {
  9773. *--t = hexDigits [v & 15];
  9774. v >>= 4;
  9775. } while (v != 0);
  9776. return String (t, (int) (((char*) end) - (char*) t) - 1);
  9777. }
  9778. const String String::toHexString (const int64 number) throw()
  9779. {
  9780. tchar buffer[32];
  9781. tchar* const end = buffer + 32;
  9782. tchar* t = end;
  9783. *--t = 0;
  9784. uint64 v = (uint64) number;
  9785. do
  9786. {
  9787. *--t = hexDigits [(int) (v & 15)];
  9788. v >>= 4;
  9789. } while (v != 0);
  9790. return String (t, (int) (((char*) end) - (char*) t));
  9791. }
  9792. const String String::toHexString (const short number) throw()
  9793. {
  9794. return toHexString ((int) (unsigned short) number);
  9795. }
  9796. const String String::toHexString (const unsigned char* data,
  9797. const int size,
  9798. const int groupSize) throw()
  9799. {
  9800. if (size <= 0)
  9801. return empty;
  9802. int numChars = (size * 2) + 2;
  9803. if (groupSize > 0)
  9804. numChars += size / groupSize;
  9805. String s (numChars, (int) 0);
  9806. tchar* d = s.text->text;
  9807. for (int i = 0; i < size; ++i)
  9808. {
  9809. *d++ = hexDigits [(*data) >> 4];
  9810. *d++ = hexDigits [(*data) & 0xf];
  9811. ++data;
  9812. if (groupSize > 0 && (i % groupSize) == (groupSize - 1) && i < (size - 1))
  9813. *d++ = T(' ');
  9814. }
  9815. *d = 0;
  9816. return s;
  9817. }
  9818. int String::getHexValue32() const throw()
  9819. {
  9820. int result = 0;
  9821. const tchar* c = text->text;
  9822. for (;;)
  9823. {
  9824. const int hexValue = CharacterFunctions::getHexDigitValue (*c);
  9825. if (hexValue >= 0)
  9826. result = (result << 4) | hexValue;
  9827. else if (*c == 0)
  9828. break;
  9829. ++c;
  9830. }
  9831. return result;
  9832. }
  9833. int64 String::getHexValue64() const throw()
  9834. {
  9835. int64 result = 0;
  9836. const tchar* c = text->text;
  9837. for (;;)
  9838. {
  9839. const int hexValue = CharacterFunctions::getHexDigitValue (*c);
  9840. if (hexValue >= 0)
  9841. result = (result << 4) | hexValue;
  9842. else if (*c == 0)
  9843. break;
  9844. ++c;
  9845. }
  9846. return result;
  9847. }
  9848. const String String::createStringFromData (const void* const data_,
  9849. const int size) throw()
  9850. {
  9851. const char* const data = (const char*) data_;
  9852. if (size <= 0 || data == 0)
  9853. {
  9854. return empty;
  9855. }
  9856. else if (size < 2)
  9857. {
  9858. return charToString (data[0]);
  9859. }
  9860. else if ((data[0] == (char)-2 && data[1] == (char)-1)
  9861. || (data[0] == (char)-1 && data[1] == (char)-2))
  9862. {
  9863. // assume it's 16-bit unicode
  9864. const bool bigEndian = (data[0] == (char)-2);
  9865. const int numChars = size / 2 - 1;
  9866. String result;
  9867. result.preallocateStorage (numChars + 2);
  9868. const uint16* const src = (const uint16*) (data + 2);
  9869. tchar* const dst = const_cast <tchar*> ((const tchar*) result);
  9870. if (bigEndian)
  9871. {
  9872. for (int i = 0; i < numChars; ++i)
  9873. dst[i] = (tchar) swapIfLittleEndian (src[i]);
  9874. }
  9875. else
  9876. {
  9877. for (int i = 0; i < numChars; ++i)
  9878. dst[i] = (tchar) swapIfBigEndian (src[i]);
  9879. }
  9880. dst [numChars] = 0;
  9881. return result;
  9882. }
  9883. else
  9884. {
  9885. return String::fromUTF8 ((const uint8*) data, size);
  9886. }
  9887. }
  9888. const char* String::toUTF8() const throw()
  9889. {
  9890. if (isEmpty())
  9891. {
  9892. return (const char*) emptyCharString;
  9893. }
  9894. else
  9895. {
  9896. String* const mutableThis = const_cast <String*> (this);
  9897. mutableThis->dupeInternalIfMultiplyReferenced();
  9898. const int currentLen = CharacterFunctions::length (text->text) + 1;
  9899. const int utf8BytesNeeded = copyToUTF8 (0);
  9900. mutableThis->text = (InternalRefCountedStringHolder*)
  9901. juce_realloc (text, sizeof (InternalRefCountedStringHolder)
  9902. + (currentLen * sizeof (juce_wchar) + utf8BytesNeeded));
  9903. char* const otherCopy = (char*) (text->text + currentLen);
  9904. copyToUTF8 ((uint8*) otherCopy);
  9905. return otherCopy;
  9906. }
  9907. }
  9908. int String::copyToUTF8 (uint8* const buffer, const int maxBufferSizeBytes) const throw()
  9909. {
  9910. jassert (maxBufferSizeBytes >= 0); // keep this value positive, or no characters will be copied!
  9911. #if JUCE_STRINGS_ARE_UNICODE
  9912. int num = 0, index = 0;
  9913. for (;;)
  9914. {
  9915. const uint32 c = (uint32) text->text [index++];
  9916. if (c >= 0x80)
  9917. {
  9918. int numExtraBytes = 1;
  9919. if (c >= 0x800)
  9920. {
  9921. ++numExtraBytes;
  9922. if (c >= 0x10000)
  9923. {
  9924. ++numExtraBytes;
  9925. if (c >= 0x200000)
  9926. {
  9927. ++numExtraBytes;
  9928. if (c >= 0x4000000)
  9929. ++numExtraBytes;
  9930. }
  9931. }
  9932. }
  9933. if (buffer != 0)
  9934. {
  9935. if (num + numExtraBytes >= maxBufferSizeBytes)
  9936. {
  9937. buffer [num++] = 0;
  9938. break;
  9939. }
  9940. else
  9941. {
  9942. buffer [num++] = (uint8) ((0xff << (7 - numExtraBytes)) | (c >> (numExtraBytes * 6)));
  9943. while (--numExtraBytes >= 0)
  9944. buffer [num++] = (uint8) (0x80 | (0x3f & (c >> (numExtraBytes * 6))));
  9945. }
  9946. }
  9947. else
  9948. {
  9949. num += numExtraBytes + 1;
  9950. }
  9951. }
  9952. else
  9953. {
  9954. if (buffer != 0)
  9955. {
  9956. if (num + 1 >= maxBufferSizeBytes)
  9957. {
  9958. buffer [num++] = 0;
  9959. break;
  9960. }
  9961. buffer [num] = (uint8) c;
  9962. }
  9963. ++num;
  9964. }
  9965. if (c == 0)
  9966. break;
  9967. }
  9968. return num;
  9969. #else
  9970. const int numBytes = jmin (maxBufferSizeBytes, length() + 1);
  9971. if (buffer != 0)
  9972. copyToBuffer ((char*) buffer, maxBufferSizeBytes);
  9973. return numBytes;
  9974. #endif
  9975. }
  9976. const String String::fromUTF8 (const uint8* const buffer, int bufferSizeBytes) throw()
  9977. {
  9978. if (buffer == 0)
  9979. return empty;
  9980. if (bufferSizeBytes < 0)
  9981. bufferSizeBytes = INT_MAX;
  9982. int numBytes;
  9983. for (numBytes = 0; numBytes < bufferSizeBytes; ++numBytes)
  9984. if (buffer [numBytes] == 0)
  9985. break;
  9986. String result (numBytes + 1, 0);
  9987. tchar* dest = result.text->text;
  9988. int i = 0;
  9989. while (i < numBytes)
  9990. {
  9991. const uint8 c = buffer [i++];
  9992. if ((c & 0x80) != 0)
  9993. {
  9994. int mask = 0x7f;
  9995. int bit = 0x40;
  9996. int numExtraValues = 0;
  9997. while (bit != 0 && (c & bit) != 0)
  9998. {
  9999. bit >>= 1;
  10000. mask >>= 1;
  10001. ++numExtraValues;
  10002. }
  10003. int n = (c & mask);
  10004. while (--numExtraValues >= 0 && i < bufferSizeBytes)
  10005. {
  10006. const uint8 c = buffer[i];
  10007. if ((c & 0xc0) != 0x80)
  10008. break;
  10009. n <<= 6;
  10010. n |= (c & 0x3f);
  10011. ++i;
  10012. }
  10013. *dest++ = (tchar) n;
  10014. }
  10015. else
  10016. {
  10017. *dest++ = (tchar) c;
  10018. }
  10019. }
  10020. *dest = 0;
  10021. return result;
  10022. }
  10023. END_JUCE_NAMESPACE
  10024. /********* End of inlined file: juce_String.cpp *********/
  10025. /********* Start of inlined file: juce_StringArray.cpp *********/
  10026. BEGIN_JUCE_NAMESPACE
  10027. StringArray::StringArray() throw()
  10028. {
  10029. }
  10030. StringArray::StringArray (const StringArray& other) throw()
  10031. {
  10032. addArray (other);
  10033. }
  10034. StringArray::StringArray (const juce_wchar** const strings,
  10035. const int numberOfStrings) throw()
  10036. {
  10037. for (int i = 0; i < numberOfStrings; ++i)
  10038. add (strings [i]);
  10039. }
  10040. StringArray::StringArray (const char** const strings,
  10041. const int numberOfStrings) throw()
  10042. {
  10043. for (int i = 0; i < numberOfStrings; ++i)
  10044. add (strings [i]);
  10045. }
  10046. StringArray::StringArray (const juce_wchar** const strings) throw()
  10047. {
  10048. int i = 0;
  10049. while (strings[i] != 0)
  10050. add (strings [i++]);
  10051. }
  10052. StringArray::StringArray (const char** const strings) throw()
  10053. {
  10054. int i = 0;
  10055. while (strings[i] != 0)
  10056. add (strings [i++]);
  10057. }
  10058. const StringArray& StringArray::operator= (const StringArray& other) throw()
  10059. {
  10060. if (this != &other)
  10061. {
  10062. clear();
  10063. addArray (other);
  10064. }
  10065. return *this;
  10066. }
  10067. StringArray::~StringArray() throw()
  10068. {
  10069. clear();
  10070. }
  10071. bool StringArray::operator== (const StringArray& other) const throw()
  10072. {
  10073. if (other.size() != size())
  10074. return false;
  10075. for (int i = size(); --i >= 0;)
  10076. {
  10077. if (*(String*) other.strings.getUnchecked(i)
  10078. != *(String*) strings.getUnchecked(i))
  10079. {
  10080. return false;
  10081. }
  10082. }
  10083. return true;
  10084. }
  10085. bool StringArray::operator!= (const StringArray& other) const throw()
  10086. {
  10087. return ! operator== (other);
  10088. }
  10089. void StringArray::clear() throw()
  10090. {
  10091. for (int i = size(); --i >= 0;)
  10092. {
  10093. String* const s = (String*) strings.getUnchecked(i);
  10094. delete s;
  10095. }
  10096. strings.clear();
  10097. }
  10098. const String& StringArray::operator[] (const int index) const throw()
  10099. {
  10100. if (((unsigned int) index) < (unsigned int) strings.size())
  10101. return *(const String*) (strings.getUnchecked (index));
  10102. return String::empty;
  10103. }
  10104. void StringArray::add (const String& newString) throw()
  10105. {
  10106. strings.add (new String (newString));
  10107. }
  10108. void StringArray::insert (const int index,
  10109. const String& newString) throw()
  10110. {
  10111. strings.insert (index, new String (newString));
  10112. }
  10113. void StringArray::addIfNotAlreadyThere (const String& newString,
  10114. const bool ignoreCase) throw()
  10115. {
  10116. if (! contains (newString, ignoreCase))
  10117. add (newString);
  10118. }
  10119. void StringArray::addArray (const StringArray& otherArray,
  10120. int startIndex,
  10121. int numElementsToAdd) throw()
  10122. {
  10123. if (startIndex < 0)
  10124. {
  10125. jassertfalse
  10126. startIndex = 0;
  10127. }
  10128. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > otherArray.size())
  10129. numElementsToAdd = otherArray.size() - startIndex;
  10130. while (--numElementsToAdd >= 0)
  10131. strings.add (new String (*(const String*) otherArray.strings.getUnchecked (startIndex++)));
  10132. }
  10133. void StringArray::set (const int index,
  10134. const String& newString) throw()
  10135. {
  10136. String* const s = (String*) strings [index];
  10137. if (s != 0)
  10138. {
  10139. *s = newString;
  10140. }
  10141. else if (index >= 0)
  10142. {
  10143. add (newString);
  10144. }
  10145. }
  10146. bool StringArray::contains (const String& stringToLookFor,
  10147. const bool ignoreCase) const throw()
  10148. {
  10149. if (ignoreCase)
  10150. {
  10151. for (int i = size(); --i >= 0;)
  10152. if (stringToLookFor.equalsIgnoreCase (*(const String*)(strings.getUnchecked(i))))
  10153. return true;
  10154. }
  10155. else
  10156. {
  10157. for (int i = size(); --i >= 0;)
  10158. if (stringToLookFor == *(const String*)(strings.getUnchecked(i)))
  10159. return true;
  10160. }
  10161. return false;
  10162. }
  10163. int StringArray::indexOf (const String& stringToLookFor,
  10164. const bool ignoreCase,
  10165. int i) const throw()
  10166. {
  10167. if (i < 0)
  10168. i = 0;
  10169. const int numElements = size();
  10170. if (ignoreCase)
  10171. {
  10172. while (i < numElements)
  10173. {
  10174. if (stringToLookFor.equalsIgnoreCase (*(const String*) strings.getUnchecked (i)))
  10175. return i;
  10176. ++i;
  10177. }
  10178. }
  10179. else
  10180. {
  10181. while (i < numElements)
  10182. {
  10183. if (stringToLookFor == *(const String*) strings.getUnchecked (i))
  10184. return i;
  10185. ++i;
  10186. }
  10187. }
  10188. return -1;
  10189. }
  10190. void StringArray::remove (const int index) throw()
  10191. {
  10192. String* const s = (String*) strings [index];
  10193. if (s != 0)
  10194. {
  10195. strings.remove (index);
  10196. delete s;
  10197. }
  10198. }
  10199. void StringArray::removeString (const String& stringToRemove,
  10200. const bool ignoreCase) throw()
  10201. {
  10202. if (ignoreCase)
  10203. {
  10204. for (int i = size(); --i >= 0;)
  10205. if (stringToRemove.equalsIgnoreCase (*(const String*) strings.getUnchecked (i)))
  10206. remove (i);
  10207. }
  10208. else
  10209. {
  10210. for (int i = size(); --i >= 0;)
  10211. if (stringToRemove == *(const String*) strings.getUnchecked (i))
  10212. remove (i);
  10213. }
  10214. }
  10215. void StringArray::removeEmptyStrings (const bool removeWhitespaceStrings) throw()
  10216. {
  10217. if (removeWhitespaceStrings)
  10218. {
  10219. for (int i = size(); --i >= 0;)
  10220. if (! ((const String*) strings.getUnchecked(i))->containsNonWhitespaceChars())
  10221. remove (i);
  10222. }
  10223. else
  10224. {
  10225. for (int i = size(); --i >= 0;)
  10226. if (((const String*) strings.getUnchecked(i))->isEmpty())
  10227. remove (i);
  10228. }
  10229. }
  10230. void StringArray::trim() throw()
  10231. {
  10232. for (int i = size(); --i >= 0;)
  10233. {
  10234. String& s = *(String*) strings.getUnchecked(i);
  10235. s = s.trim();
  10236. }
  10237. }
  10238. class InternalStringArrayComparator
  10239. {
  10240. public:
  10241. static int compareElements (void* const first, void* const second) throw()
  10242. {
  10243. return ((const String*) first)->compare (*(const String*) second);
  10244. }
  10245. };
  10246. class InsensitiveInternalStringArrayComparator
  10247. {
  10248. public:
  10249. static int compareElements (void* const first, void* const second) throw()
  10250. {
  10251. return ((const String*) first)->compareIgnoreCase (*(const String*) second);
  10252. }
  10253. };
  10254. void StringArray::sort (const bool ignoreCase) throw()
  10255. {
  10256. if (ignoreCase)
  10257. {
  10258. InsensitiveInternalStringArrayComparator comp;
  10259. strings.sort (comp);
  10260. }
  10261. else
  10262. {
  10263. InternalStringArrayComparator comp;
  10264. strings.sort (comp);
  10265. }
  10266. }
  10267. void StringArray::move (const int currentIndex, int newIndex) throw()
  10268. {
  10269. strings.move (currentIndex, newIndex);
  10270. }
  10271. const String StringArray::joinIntoString (const String& separator,
  10272. int start,
  10273. int numberToJoin) const throw()
  10274. {
  10275. const int last = (numberToJoin < 0) ? size()
  10276. : jmin (size(), start + numberToJoin);
  10277. if (start < 0)
  10278. start = 0;
  10279. if (start >= last)
  10280. return String::empty;
  10281. if (start == last - 1)
  10282. return *(const String*) strings.getUnchecked (start);
  10283. const int separatorLen = separator.length();
  10284. int charsNeeded = separatorLen * (last - start - 1);
  10285. for (int i = start; i < last; ++i)
  10286. charsNeeded += ((const String*) strings.getUnchecked(i))->length();
  10287. String result;
  10288. result.preallocateStorage (charsNeeded);
  10289. tchar* dest = (tchar*) (const tchar*) result;
  10290. while (start < last)
  10291. {
  10292. const String& s = *(const String*) strings.getUnchecked (start);
  10293. const int len = s.length();
  10294. if (len > 0)
  10295. {
  10296. s.copyToBuffer (dest, len);
  10297. dest += len;
  10298. }
  10299. if (++start < last && separatorLen > 0)
  10300. {
  10301. separator.copyToBuffer (dest, separatorLen);
  10302. dest += separatorLen;
  10303. }
  10304. }
  10305. *dest = 0;
  10306. return result;
  10307. }
  10308. int StringArray::addTokens (const tchar* const text,
  10309. const bool preserveQuotedStrings) throw()
  10310. {
  10311. return addTokens (text,
  10312. T(" \n\r\t"),
  10313. preserveQuotedStrings ? T("\"") : 0);
  10314. }
  10315. int StringArray::addTokens (const tchar* const text,
  10316. const tchar* breakCharacters,
  10317. const tchar* quoteCharacters) throw()
  10318. {
  10319. int num = 0;
  10320. if (text != 0 && *text != 0)
  10321. {
  10322. if (breakCharacters == 0)
  10323. breakCharacters = T("");
  10324. if (quoteCharacters == 0)
  10325. quoteCharacters = T("");
  10326. bool insideQuotes = false;
  10327. tchar currentQuoteChar = 0;
  10328. int i = 0;
  10329. int tokenStart = 0;
  10330. for (;;)
  10331. {
  10332. const tchar c = text[i];
  10333. bool isBreak = (c == 0);
  10334. if (! (insideQuotes || isBreak))
  10335. {
  10336. const tchar* b = breakCharacters;
  10337. while (*b != 0)
  10338. {
  10339. if (*b++ == c)
  10340. {
  10341. isBreak = true;
  10342. break;
  10343. }
  10344. }
  10345. }
  10346. if (! isBreak)
  10347. {
  10348. bool isQuote = false;
  10349. const tchar* q = quoteCharacters;
  10350. while (*q != 0)
  10351. {
  10352. if (*q++ == c)
  10353. {
  10354. isQuote = true;
  10355. break;
  10356. }
  10357. }
  10358. if (isQuote)
  10359. {
  10360. if (insideQuotes)
  10361. {
  10362. // only break out of quotes-mode if we find a matching quote to the
  10363. // one that we opened with..
  10364. if (currentQuoteChar == c)
  10365. insideQuotes = false;
  10366. }
  10367. else
  10368. {
  10369. insideQuotes = true;
  10370. currentQuoteChar = c;
  10371. }
  10372. }
  10373. }
  10374. else
  10375. {
  10376. add (String (text + tokenStart, i - tokenStart));
  10377. ++num;
  10378. tokenStart = i + 1;
  10379. }
  10380. if (c == 0)
  10381. break;
  10382. ++i;
  10383. }
  10384. }
  10385. return num;
  10386. }
  10387. int StringArray::addLines (const tchar* text) throw()
  10388. {
  10389. int numLines = 0;
  10390. if (text != 0)
  10391. {
  10392. while (*text != 0)
  10393. {
  10394. const tchar* const startOfLine = text;
  10395. while (*text != 0)
  10396. {
  10397. if (*text == T('\r'))
  10398. {
  10399. ++text;
  10400. if (*text == T('\n'))
  10401. ++text;
  10402. break;
  10403. }
  10404. if (*text == T('\n'))
  10405. {
  10406. ++text;
  10407. break;
  10408. }
  10409. ++text;
  10410. }
  10411. const tchar* endOfLine = text;
  10412. if (endOfLine > startOfLine && (*(endOfLine - 1) == T('\r') || *(endOfLine - 1) == T('\n')))
  10413. --endOfLine;
  10414. if (endOfLine > startOfLine && (*(endOfLine - 1) == T('\r') || *(endOfLine - 1) == T('\n')))
  10415. --endOfLine;
  10416. add (String (startOfLine, jmax (0, (int) (endOfLine - startOfLine))));
  10417. ++numLines;
  10418. }
  10419. }
  10420. return numLines;
  10421. }
  10422. void StringArray::removeDuplicates (const bool ignoreCase) throw()
  10423. {
  10424. for (int i = 0; i < size() - 1; ++i)
  10425. {
  10426. const String& s = *(String*) strings.getUnchecked(i);
  10427. int nextIndex = i + 1;
  10428. for (;;)
  10429. {
  10430. nextIndex = indexOf (s, ignoreCase, nextIndex);
  10431. if (nextIndex < 0)
  10432. break;
  10433. remove (nextIndex);
  10434. }
  10435. }
  10436. }
  10437. void StringArray::appendNumbersToDuplicates (const bool ignoreCase,
  10438. const bool appendNumberToFirstInstance,
  10439. const tchar* const preNumberString,
  10440. const tchar* const postNumberString) throw()
  10441. {
  10442. for (int i = 0; i < size() - 1; ++i)
  10443. {
  10444. String& s = *(String*) strings.getUnchecked(i);
  10445. int nextIndex = indexOf (s, ignoreCase, i + 1);
  10446. if (nextIndex >= 0)
  10447. {
  10448. const String original (s);
  10449. int number = 0;
  10450. if (appendNumberToFirstInstance)
  10451. s = original + preNumberString + String (++number) + postNumberString;
  10452. else
  10453. ++number;
  10454. while (nextIndex >= 0)
  10455. {
  10456. set (nextIndex, (*this)[nextIndex] + preNumberString + String (++number) + postNumberString);
  10457. nextIndex = indexOf (original, ignoreCase, nextIndex + 1);
  10458. }
  10459. }
  10460. }
  10461. }
  10462. void StringArray::minimiseStorageOverheads() throw()
  10463. {
  10464. strings.minimiseStorageOverheads();
  10465. }
  10466. END_JUCE_NAMESPACE
  10467. /********* End of inlined file: juce_StringArray.cpp *********/
  10468. /********* Start of inlined file: juce_StringPairArray.cpp *********/
  10469. BEGIN_JUCE_NAMESPACE
  10470. StringPairArray::StringPairArray (const bool ignoreCase_) throw()
  10471. : ignoreCase (ignoreCase_)
  10472. {
  10473. }
  10474. StringPairArray::StringPairArray (const StringPairArray& other) throw()
  10475. : keys (other.keys),
  10476. values (other.values),
  10477. ignoreCase (other.ignoreCase)
  10478. {
  10479. }
  10480. StringPairArray::~StringPairArray() throw()
  10481. {
  10482. }
  10483. const StringPairArray& StringPairArray::operator= (const StringPairArray& other) throw()
  10484. {
  10485. keys = other.keys;
  10486. values = other.values;
  10487. return *this;
  10488. }
  10489. bool StringPairArray::operator== (const StringPairArray& other) const throw()
  10490. {
  10491. for (int i = keys.size(); --i >= 0;)
  10492. if (other [keys[i]] != values[i])
  10493. return false;
  10494. return true;
  10495. }
  10496. bool StringPairArray::operator!= (const StringPairArray& other) const throw()
  10497. {
  10498. return ! operator== (other);
  10499. }
  10500. const String& StringPairArray::operator[] (const String& key) const throw()
  10501. {
  10502. return values [keys.indexOf (key, ignoreCase)];
  10503. }
  10504. const String StringPairArray::getValue (const String& key, const String& defaultReturnValue) const
  10505. {
  10506. const int i = keys.indexOf (key, ignoreCase);
  10507. if (i >= 0)
  10508. return values[i];
  10509. return defaultReturnValue;
  10510. }
  10511. void StringPairArray::set (const String& key,
  10512. const String& value) throw()
  10513. {
  10514. const int i = keys.indexOf (key, ignoreCase);
  10515. if (i >= 0)
  10516. {
  10517. values.set (i, value);
  10518. }
  10519. else
  10520. {
  10521. keys.add (key);
  10522. values.add (value);
  10523. }
  10524. }
  10525. void StringPairArray::addArray (const StringPairArray& other)
  10526. {
  10527. for (int i = 0; i < other.size(); ++i)
  10528. set (other.keys[i], other.values[i]);
  10529. }
  10530. void StringPairArray::clear() throw()
  10531. {
  10532. keys.clear();
  10533. values.clear();
  10534. }
  10535. void StringPairArray::remove (const String& key) throw()
  10536. {
  10537. remove (keys.indexOf (key, ignoreCase));
  10538. }
  10539. void StringPairArray::remove (const int index) throw()
  10540. {
  10541. keys.remove (index);
  10542. values.remove (index);
  10543. }
  10544. void StringPairArray::setIgnoresCase (const bool shouldIgnoreCase) throw()
  10545. {
  10546. ignoreCase = shouldIgnoreCase;
  10547. }
  10548. const String StringPairArray::getDescription() const
  10549. {
  10550. String s;
  10551. for (int i = 0; i < keys.size(); ++i)
  10552. {
  10553. s << keys[i] << T(" = ") << values[i];
  10554. if (i < keys.size())
  10555. s << T(", ");
  10556. }
  10557. return s;
  10558. }
  10559. void StringPairArray::minimiseStorageOverheads() throw()
  10560. {
  10561. keys.minimiseStorageOverheads();
  10562. values.minimiseStorageOverheads();
  10563. }
  10564. END_JUCE_NAMESPACE
  10565. /********* End of inlined file: juce_StringPairArray.cpp *********/
  10566. /********* Start of inlined file: juce_XmlDocument.cpp *********/
  10567. BEGIN_JUCE_NAMESPACE
  10568. static bool isXmlIdentifierChar_Slow (const tchar c) throw()
  10569. {
  10570. return CharacterFunctions::isLetterOrDigit (c)
  10571. || c == T('_')
  10572. || c == T('-')
  10573. || c == T(':')
  10574. || c == T('.');
  10575. }
  10576. #define isXmlIdentifierChar(c) \
  10577. ((c > 0 && c <= 127) ? identifierLookupTable [(int) c] : isXmlIdentifierChar_Slow (c))
  10578. XmlDocument::XmlDocument (const String& documentText) throw()
  10579. : originalText (documentText),
  10580. ignoreEmptyTextElements (true),
  10581. inputSource (0)
  10582. {
  10583. }
  10584. XmlDocument::XmlDocument (const File& file)
  10585. {
  10586. inputSource = new FileInputSource (file);
  10587. }
  10588. XmlDocument::~XmlDocument() throw()
  10589. {
  10590. delete inputSource;
  10591. }
  10592. void XmlDocument::setInputSource (InputSource* const newSource) throw()
  10593. {
  10594. if (inputSource != newSource)
  10595. {
  10596. delete inputSource;
  10597. inputSource = newSource;
  10598. }
  10599. }
  10600. void XmlDocument::setEmptyTextElementsIgnored (const bool shouldBeIgnored) throw()
  10601. {
  10602. ignoreEmptyTextElements = shouldBeIgnored;
  10603. }
  10604. XmlElement* XmlDocument::getDocumentElement (const bool onlyReadOuterDocumentElement)
  10605. {
  10606. String textToParse (originalText);
  10607. if (textToParse.isEmpty() && inputSource != 0)
  10608. {
  10609. InputStream* const in = inputSource->createInputStream();
  10610. if (in != 0)
  10611. {
  10612. MemoryBlock data;
  10613. in->readIntoMemoryBlock (data, onlyReadOuterDocumentElement ? 8192 : -1);
  10614. delete in;
  10615. if (data.getSize() >= 2
  10616. && ((data[0] == (char)-2 && data[1] == (char)-1)
  10617. || (data[0] == (char)-1 && data[1] == (char)-2)))
  10618. {
  10619. textToParse = String::createStringFromData ((const char*) data.getData(), data.getSize());
  10620. }
  10621. else
  10622. {
  10623. textToParse = String::fromUTF8 ((const uint8*) data.getData(), data.getSize());
  10624. }
  10625. if (! onlyReadOuterDocumentElement)
  10626. originalText = textToParse;
  10627. }
  10628. }
  10629. input = textToParse;
  10630. lastError = String::empty;
  10631. errorOccurred = false;
  10632. outOfData = false;
  10633. needToLoadDTD = true;
  10634. for (int i = 0; i < 128; ++i)
  10635. identifierLookupTable[i] = isXmlIdentifierChar_Slow ((tchar) i);
  10636. if (textToParse.isEmpty())
  10637. {
  10638. lastError = "not enough input";
  10639. }
  10640. else
  10641. {
  10642. skipHeader();
  10643. if (input != 0)
  10644. {
  10645. XmlElement* const result = readNextElement (! onlyReadOuterDocumentElement);
  10646. if (errorOccurred)
  10647. delete result;
  10648. else
  10649. return result;
  10650. }
  10651. else
  10652. {
  10653. lastError = "incorrect xml header";
  10654. }
  10655. }
  10656. return 0;
  10657. }
  10658. const String& XmlDocument::getLastParseError() const throw()
  10659. {
  10660. return lastError;
  10661. }
  10662. void XmlDocument::setLastError (const String& desc, const bool carryOn) throw()
  10663. {
  10664. lastError = desc;
  10665. errorOccurred = ! carryOn;
  10666. }
  10667. const String XmlDocument::getFileContents (const String& filename) const
  10668. {
  10669. String result;
  10670. if (inputSource != 0)
  10671. {
  10672. InputStream* const in = inputSource->createInputStreamFor (filename.trim().unquoted());
  10673. if (in != 0)
  10674. {
  10675. result = in->readEntireStreamAsString();
  10676. delete in;
  10677. }
  10678. }
  10679. return result;
  10680. }
  10681. tchar XmlDocument::readNextChar() throw()
  10682. {
  10683. if (*input != 0)
  10684. {
  10685. return *input++;
  10686. }
  10687. else
  10688. {
  10689. outOfData = true;
  10690. return 0;
  10691. }
  10692. }
  10693. int XmlDocument::findNextTokenLength() throw()
  10694. {
  10695. int len = 0;
  10696. tchar c = *input;
  10697. while (isXmlIdentifierChar (c))
  10698. c = input [++len];
  10699. return len;
  10700. }
  10701. void XmlDocument::skipHeader() throw()
  10702. {
  10703. const tchar* const found = CharacterFunctions::find (input, T("<?xml"));
  10704. if (found != 0)
  10705. {
  10706. input = found;
  10707. input = CharacterFunctions::find (input, T("?>"));
  10708. if (input == 0)
  10709. return;
  10710. input += 2;
  10711. }
  10712. skipNextWhiteSpace();
  10713. const tchar* docType = CharacterFunctions::find (input, T("<!DOCTYPE"));
  10714. if (docType == 0)
  10715. return;
  10716. input = docType + 9;
  10717. int n = 1;
  10718. while (n > 0)
  10719. {
  10720. const tchar c = readNextChar();
  10721. if (outOfData)
  10722. return;
  10723. if (c == T('<'))
  10724. ++n;
  10725. else if (c == T('>'))
  10726. --n;
  10727. }
  10728. docType += 9;
  10729. dtdText = String (docType, (int) (input - (docType + 1))).trim();
  10730. }
  10731. void XmlDocument::skipNextWhiteSpace() throw()
  10732. {
  10733. for (;;)
  10734. {
  10735. tchar c = *input;
  10736. while (CharacterFunctions::isWhitespace (c))
  10737. c = *++input;
  10738. if (c == 0)
  10739. {
  10740. outOfData = true;
  10741. break;
  10742. }
  10743. else if (c == T('<'))
  10744. {
  10745. if (input[1] == T('!')
  10746. && input[2] == T('-')
  10747. && input[3] == T('-'))
  10748. {
  10749. const tchar* const closeComment = CharacterFunctions::find (input, T("-->"));
  10750. if (closeComment == 0)
  10751. {
  10752. outOfData = true;
  10753. break;
  10754. }
  10755. input = closeComment + 3;
  10756. continue;
  10757. }
  10758. else if (input[1] == T('?'))
  10759. {
  10760. const tchar* const closeBracket = CharacterFunctions::find (input, T("?>"));
  10761. if (closeBracket == 0)
  10762. {
  10763. outOfData = true;
  10764. break;
  10765. }
  10766. input = closeBracket + 2;
  10767. continue;
  10768. }
  10769. }
  10770. break;
  10771. }
  10772. }
  10773. void XmlDocument::readQuotedString (String& result) throw()
  10774. {
  10775. const tchar quote = readNextChar();
  10776. while (! outOfData)
  10777. {
  10778. const tchar character = readNextChar();
  10779. if (character == quote)
  10780. break;
  10781. if (character == T('&'))
  10782. {
  10783. --input;
  10784. readEntity (result);
  10785. }
  10786. else
  10787. {
  10788. --input;
  10789. const tchar* const start = input;
  10790. for (;;)
  10791. {
  10792. const tchar character = *input;
  10793. if (character == quote)
  10794. {
  10795. result.append (start, (int) (input - start));
  10796. ++input;
  10797. return;
  10798. }
  10799. else if (character == T('&'))
  10800. {
  10801. result.append (start, (int) (input - start));
  10802. break;
  10803. }
  10804. else if (character == 0)
  10805. {
  10806. outOfData = true;
  10807. setLastError ("unmatched quotes", false);
  10808. break;
  10809. }
  10810. ++input;
  10811. }
  10812. }
  10813. }
  10814. }
  10815. XmlElement* XmlDocument::readNextElement (const bool alsoParseSubElements) throw()
  10816. {
  10817. XmlElement* node = 0;
  10818. skipNextWhiteSpace();
  10819. if (outOfData)
  10820. return 0;
  10821. input = CharacterFunctions::find (input, T("<"));
  10822. if (input != 0)
  10823. {
  10824. ++input;
  10825. int tagLen = findNextTokenLength();
  10826. if (tagLen == 0)
  10827. {
  10828. // no tag name - but allow for a gap after the '<' before giving an error
  10829. skipNextWhiteSpace();
  10830. tagLen = findNextTokenLength();
  10831. if (tagLen == 0)
  10832. {
  10833. setLastError ("tag name missing", false);
  10834. return node;
  10835. }
  10836. }
  10837. node = new XmlElement (input, tagLen);
  10838. input += tagLen;
  10839. XmlElement::XmlAttributeNode* lastAttribute = 0;
  10840. // look for attributes
  10841. for (;;)
  10842. {
  10843. skipNextWhiteSpace();
  10844. const tchar c = *input;
  10845. // empty tag..
  10846. if (c == T('/') && input[1] == T('>'))
  10847. {
  10848. input += 2;
  10849. break;
  10850. }
  10851. // parse the guts of the element..
  10852. if (c == T('>'))
  10853. {
  10854. ++input;
  10855. skipNextWhiteSpace();
  10856. if (alsoParseSubElements)
  10857. readChildElements (node);
  10858. break;
  10859. }
  10860. // get an attribute..
  10861. if (isXmlIdentifierChar (c))
  10862. {
  10863. const int attNameLen = findNextTokenLength();
  10864. if (attNameLen > 0)
  10865. {
  10866. const tchar* attNameStart = input;
  10867. input += attNameLen;
  10868. skipNextWhiteSpace();
  10869. if (readNextChar() == T('='))
  10870. {
  10871. skipNextWhiteSpace();
  10872. const tchar c = *input;
  10873. if (c == T('"') || c == T('\''))
  10874. {
  10875. XmlElement::XmlAttributeNode* const newAtt
  10876. = new XmlElement::XmlAttributeNode (String (attNameStart, attNameLen),
  10877. String::empty);
  10878. readQuotedString (newAtt->value);
  10879. if (lastAttribute == 0)
  10880. node->attributes = newAtt;
  10881. else
  10882. lastAttribute->next = newAtt;
  10883. lastAttribute = newAtt;
  10884. continue;
  10885. }
  10886. }
  10887. }
  10888. }
  10889. else
  10890. {
  10891. if (! outOfData)
  10892. setLastError ("illegal character found in " + node->getTagName() + ": '" + c + "'", false);
  10893. }
  10894. break;
  10895. }
  10896. }
  10897. return node;
  10898. }
  10899. void XmlDocument::readChildElements (XmlElement* parent) throw()
  10900. {
  10901. XmlElement* lastChildNode = 0;
  10902. for (;;)
  10903. {
  10904. skipNextWhiteSpace();
  10905. if (outOfData)
  10906. {
  10907. setLastError ("unmatched tags", false);
  10908. break;
  10909. }
  10910. if (*input == T('<'))
  10911. {
  10912. if (input[1] == T('/'))
  10913. {
  10914. // our close tag..
  10915. input = CharacterFunctions::find (input, T(">"));
  10916. ++input;
  10917. break;
  10918. }
  10919. else if (input[1] == T('!')
  10920. && input[2] == T('[')
  10921. && input[3] == T('C')
  10922. && input[4] == T('D')
  10923. && input[5] == T('A')
  10924. && input[6] == T('T')
  10925. && input[7] == T('A')
  10926. && input[8] == T('['))
  10927. {
  10928. input += 9;
  10929. const tchar* const inputStart = input;
  10930. int len = 0;
  10931. for (;;)
  10932. {
  10933. if (*input == 0)
  10934. {
  10935. setLastError ("unterminated CDATA section", false);
  10936. outOfData = true;
  10937. break;
  10938. }
  10939. else if (input[0] == T(']')
  10940. && input[1] == T(']')
  10941. && input[2] == T('>'))
  10942. {
  10943. input += 3;
  10944. break;
  10945. }
  10946. ++input;
  10947. ++len;
  10948. }
  10949. XmlElement* const e = new XmlElement ((int) 0);
  10950. e->setText (String (inputStart, len));
  10951. if (lastChildNode != 0)
  10952. lastChildNode->nextElement = e;
  10953. else
  10954. parent->addChildElement (e);
  10955. lastChildNode = e;
  10956. }
  10957. else
  10958. {
  10959. // this is some other element, so parse and add it..
  10960. XmlElement* const n = readNextElement (true);
  10961. if (n != 0)
  10962. {
  10963. if (lastChildNode == 0)
  10964. parent->addChildElement (n);
  10965. else
  10966. lastChildNode->nextElement = n;
  10967. lastChildNode = n;
  10968. }
  10969. else
  10970. {
  10971. return;
  10972. }
  10973. }
  10974. }
  10975. else
  10976. {
  10977. // read character block..
  10978. XmlElement* const e = new XmlElement ((int)0);
  10979. if (lastChildNode != 0)
  10980. lastChildNode->nextElement = e;
  10981. else
  10982. parent->addChildElement (e);
  10983. lastChildNode = e;
  10984. String textElementContent;
  10985. for (;;)
  10986. {
  10987. const tchar c = *input;
  10988. if (c == T('<'))
  10989. break;
  10990. if (c == 0)
  10991. {
  10992. setLastError ("unmatched tags", false);
  10993. outOfData = true;
  10994. return;
  10995. }
  10996. if (c == T('&'))
  10997. {
  10998. String entity;
  10999. readEntity (entity);
  11000. if (entity.startsWithChar (T('<')) && entity [1] != 0)
  11001. {
  11002. const tchar* const oldInput = input;
  11003. const bool oldOutOfData = outOfData;
  11004. input = (const tchar*) entity;
  11005. outOfData = false;
  11006. for (;;)
  11007. {
  11008. XmlElement* const n = readNextElement (true);
  11009. if (n == 0)
  11010. break;
  11011. if (lastChildNode == 0)
  11012. parent->addChildElement (n);
  11013. else
  11014. lastChildNode->nextElement = n;
  11015. lastChildNode = n;
  11016. }
  11017. input = oldInput;
  11018. outOfData = oldOutOfData;
  11019. }
  11020. else
  11021. {
  11022. textElementContent += entity;
  11023. }
  11024. }
  11025. else
  11026. {
  11027. const tchar* start = input;
  11028. int len = 0;
  11029. for (;;)
  11030. {
  11031. const tchar c = *input;
  11032. if (c == T('<') || c == T('&'))
  11033. {
  11034. break;
  11035. }
  11036. else if (c == 0)
  11037. {
  11038. setLastError ("unmatched tags", false);
  11039. outOfData = true;
  11040. return;
  11041. }
  11042. ++input;
  11043. ++len;
  11044. }
  11045. textElementContent.append (start, len);
  11046. }
  11047. }
  11048. if (ignoreEmptyTextElements ? textElementContent.containsNonWhitespaceChars()
  11049. : textElementContent.isNotEmpty())
  11050. e->setText (textElementContent);
  11051. }
  11052. }
  11053. }
  11054. void XmlDocument::readEntity (String& result) throw()
  11055. {
  11056. // skip over the ampersand
  11057. ++input;
  11058. if (CharacterFunctions::compareIgnoreCase (input, T("amp;"), 4) == 0)
  11059. {
  11060. input += 4;
  11061. result += T("&");
  11062. }
  11063. else if (CharacterFunctions::compareIgnoreCase (input, T("quot;"), 5) == 0)
  11064. {
  11065. input += 5;
  11066. result += T("\"");
  11067. }
  11068. else if (CharacterFunctions::compareIgnoreCase (input, T("apos;"), 5) == 0)
  11069. {
  11070. input += 5;
  11071. result += T("\'");
  11072. }
  11073. else if (CharacterFunctions::compareIgnoreCase (input, T("lt;"), 3) == 0)
  11074. {
  11075. input += 3;
  11076. result += T("<");
  11077. }
  11078. else if (CharacterFunctions::compareIgnoreCase (input, T("gt;"), 3) == 0)
  11079. {
  11080. input += 3;
  11081. result += T(">");
  11082. }
  11083. else if (*input == T('#'))
  11084. {
  11085. int charCode = 0;
  11086. ++input;
  11087. if (*input == T('x') || *input == T('X'))
  11088. {
  11089. ++input;
  11090. int numChars = 0;
  11091. while (input[0] != T(';'))
  11092. {
  11093. const int hexValue = CharacterFunctions::getHexDigitValue (input[0]);
  11094. if (hexValue < 0 || ++numChars > 8)
  11095. {
  11096. setLastError ("illegal escape sequence", true);
  11097. break;
  11098. }
  11099. charCode = (charCode << 4) | hexValue;
  11100. ++input;
  11101. }
  11102. ++input;
  11103. }
  11104. else if (input[0] >= T('0') && input[0] <= T('9'))
  11105. {
  11106. int numChars = 0;
  11107. while (input[0] != T(';'))
  11108. {
  11109. if (++numChars > 12)
  11110. {
  11111. setLastError ("illegal escape sequence", true);
  11112. break;
  11113. }
  11114. charCode = charCode * 10 + (input[0] - T('0'));
  11115. ++input;
  11116. }
  11117. ++input;
  11118. }
  11119. else
  11120. {
  11121. setLastError ("illegal escape sequence", true);
  11122. result += T("&");
  11123. return;
  11124. }
  11125. result << (tchar) charCode;
  11126. }
  11127. else
  11128. {
  11129. const tchar* const entityNameStart = input;
  11130. const tchar* const closingSemiColon = CharacterFunctions::find (input, T(";"));
  11131. if (closingSemiColon == 0)
  11132. {
  11133. outOfData = true;
  11134. result += T("&");
  11135. }
  11136. else
  11137. {
  11138. input = closingSemiColon + 1;
  11139. result += expandExternalEntity (String (entityNameStart,
  11140. (int) (closingSemiColon - entityNameStart)));
  11141. }
  11142. }
  11143. }
  11144. const String XmlDocument::expandEntity (const String& ent)
  11145. {
  11146. if (ent.equalsIgnoreCase (T("amp")))
  11147. {
  11148. return T("&");
  11149. }
  11150. else if (ent.equalsIgnoreCase (T("quot")))
  11151. {
  11152. return T("\"");
  11153. }
  11154. else if (ent.equalsIgnoreCase (T("apos")))
  11155. {
  11156. return T("\'");
  11157. }
  11158. else if (ent.equalsIgnoreCase (T("lt")))
  11159. {
  11160. return T("<");
  11161. }
  11162. else if (ent.equalsIgnoreCase (T("gt")))
  11163. {
  11164. return T(">");
  11165. }
  11166. else if (ent[0] == T('#'))
  11167. {
  11168. if (ent[1] == T('x') || ent[1] == T('X'))
  11169. {
  11170. return String::charToString ((tchar) ent.substring (2).getHexValue32());
  11171. }
  11172. else if (ent[1] >= T('0') && ent[1] <= T('9'))
  11173. {
  11174. return String::charToString ((tchar) ent.substring (1).getIntValue());
  11175. }
  11176. setLastError ("illegal escape sequence", false);
  11177. return T("&");
  11178. }
  11179. else
  11180. {
  11181. return expandExternalEntity (ent);
  11182. }
  11183. }
  11184. const String XmlDocument::expandExternalEntity (const String& entity)
  11185. {
  11186. if (needToLoadDTD)
  11187. {
  11188. if (dtdText.isNotEmpty())
  11189. {
  11190. while (dtdText.endsWithChar (T('>')))
  11191. dtdText = dtdText.dropLastCharacters (1);
  11192. tokenisedDTD.addTokens (dtdText, true);
  11193. if (tokenisedDTD [tokenisedDTD.size() - 2].equalsIgnoreCase (T("system"))
  11194. && tokenisedDTD [tokenisedDTD.size() - 1].isQuotedString())
  11195. {
  11196. const String fn (tokenisedDTD [tokenisedDTD.size() - 1]);
  11197. tokenisedDTD.clear();
  11198. tokenisedDTD.addTokens (getFileContents (fn), true);
  11199. }
  11200. else
  11201. {
  11202. tokenisedDTD.clear();
  11203. const int openBracket = dtdText.indexOfChar (T('['));
  11204. if (openBracket > 0)
  11205. {
  11206. const int closeBracket = dtdText.lastIndexOfChar (T(']'));
  11207. if (closeBracket > openBracket)
  11208. tokenisedDTD.addTokens (dtdText.substring (openBracket + 1,
  11209. closeBracket), true);
  11210. }
  11211. }
  11212. for (int i = tokenisedDTD.size(); --i >= 0;)
  11213. {
  11214. if (tokenisedDTD[i].startsWithChar (T('%'))
  11215. && tokenisedDTD[i].endsWithChar (T(';')))
  11216. {
  11217. const String parsed (getParameterEntity (tokenisedDTD[i].substring (1, tokenisedDTD[i].length() - 1)));
  11218. StringArray newToks;
  11219. newToks.addTokens (parsed, true);
  11220. tokenisedDTD.remove (i);
  11221. for (int j = newToks.size(); --j >= 0;)
  11222. tokenisedDTD.insert (i, newToks[j]);
  11223. }
  11224. }
  11225. }
  11226. needToLoadDTD = false;
  11227. }
  11228. for (int i = 0; i < tokenisedDTD.size(); ++i)
  11229. {
  11230. if (tokenisedDTD[i] == entity)
  11231. {
  11232. if (tokenisedDTD[i - 1].equalsIgnoreCase (T("<!entity")))
  11233. {
  11234. String ent (tokenisedDTD [i + 1]);
  11235. while (ent.endsWithChar (T('>')))
  11236. ent = ent.dropLastCharacters (1);
  11237. ent = ent.trim().unquoted();
  11238. // check for sub-entities..
  11239. int ampersand = ent.indexOfChar (T('&'));
  11240. while (ampersand >= 0)
  11241. {
  11242. const int semiColon = ent.indexOf (i + 1, T(";"));
  11243. if (semiColon < 0)
  11244. {
  11245. setLastError ("entity without terminating semi-colon", false);
  11246. break;
  11247. }
  11248. const String resolved (expandEntity (ent.substring (i + 1, semiColon)));
  11249. ent = ent.substring (0, ampersand)
  11250. + resolved
  11251. + ent.substring (semiColon + 1);
  11252. ampersand = ent.indexOfChar (semiColon + 1, T('&'));
  11253. }
  11254. return ent;
  11255. }
  11256. }
  11257. }
  11258. setLastError ("unknown entity", true);
  11259. return entity;
  11260. }
  11261. const String XmlDocument::getParameterEntity (const String& entity)
  11262. {
  11263. for (int i = 0; i < tokenisedDTD.size(); ++i)
  11264. {
  11265. if (tokenisedDTD[i] == entity)
  11266. {
  11267. if (tokenisedDTD [i - 1] == T("%")
  11268. && tokenisedDTD [i - 2].equalsIgnoreCase (T("<!entity")))
  11269. {
  11270. String ent (tokenisedDTD [i + 1]);
  11271. while (ent.endsWithChar (T('>')))
  11272. ent = ent.dropLastCharacters (1);
  11273. if (ent.equalsIgnoreCase (T("system")))
  11274. {
  11275. String filename (tokenisedDTD [i + 2]);
  11276. while (filename.endsWithChar (T('>')))
  11277. filename = filename.dropLastCharacters (1);
  11278. return getFileContents (filename);
  11279. }
  11280. else
  11281. {
  11282. return ent.trim().unquoted();
  11283. }
  11284. }
  11285. }
  11286. }
  11287. return entity;
  11288. }
  11289. END_JUCE_NAMESPACE
  11290. /********* End of inlined file: juce_XmlDocument.cpp *********/
  11291. /********* Start of inlined file: juce_XmlElement.cpp *********/
  11292. BEGIN_JUCE_NAMESPACE
  11293. XmlElement::XmlAttributeNode::XmlAttributeNode (const XmlAttributeNode& other) throw()
  11294. : name (other.name),
  11295. value (other.value),
  11296. next (0)
  11297. {
  11298. }
  11299. XmlElement::XmlAttributeNode::XmlAttributeNode (const String& name_,
  11300. const String& value_) throw()
  11301. : name (name_),
  11302. value (value_),
  11303. next (0)
  11304. {
  11305. }
  11306. XmlElement::XmlElement (const String& tagName_) throw()
  11307. : tagName (tagName_),
  11308. firstChildElement (0),
  11309. nextElement (0),
  11310. attributes (0)
  11311. {
  11312. // the tag name mustn't be empty, or it'll look like a text element!
  11313. jassert (tagName_.containsNonWhitespaceChars())
  11314. }
  11315. XmlElement::XmlElement (int /*dummy*/) throw()
  11316. : firstChildElement (0),
  11317. nextElement (0),
  11318. attributes (0)
  11319. {
  11320. }
  11321. XmlElement::XmlElement (const tchar* const tagName_,
  11322. const int nameLen) throw()
  11323. : tagName (tagName_, nameLen),
  11324. firstChildElement (0),
  11325. nextElement (0),
  11326. attributes (0)
  11327. {
  11328. }
  11329. XmlElement::XmlElement (const XmlElement& other) throw()
  11330. : tagName (other.tagName),
  11331. firstChildElement (0),
  11332. nextElement (0),
  11333. attributes (0)
  11334. {
  11335. copyChildrenAndAttributesFrom (other);
  11336. }
  11337. const XmlElement& XmlElement::operator= (const XmlElement& other) throw()
  11338. {
  11339. if (this != &other)
  11340. {
  11341. removeAllAttributes();
  11342. deleteAllChildElements();
  11343. tagName = other.tagName;
  11344. copyChildrenAndAttributesFrom (other);
  11345. }
  11346. return *this;
  11347. }
  11348. void XmlElement::copyChildrenAndAttributesFrom (const XmlElement& other) throw()
  11349. {
  11350. XmlElement* child = other.firstChildElement;
  11351. XmlElement* lastChild = 0;
  11352. while (child != 0)
  11353. {
  11354. XmlElement* const copiedChild = new XmlElement (*child);
  11355. if (lastChild != 0)
  11356. lastChild->nextElement = copiedChild;
  11357. else
  11358. firstChildElement = copiedChild;
  11359. lastChild = copiedChild;
  11360. child = child->nextElement;
  11361. }
  11362. const XmlAttributeNode* att = other.attributes;
  11363. XmlAttributeNode* lastAtt = 0;
  11364. while (att != 0)
  11365. {
  11366. XmlAttributeNode* const newAtt = new XmlAttributeNode (*att);
  11367. if (lastAtt != 0)
  11368. lastAtt->next = newAtt;
  11369. else
  11370. attributes = newAtt;
  11371. lastAtt = newAtt;
  11372. att = att->next;
  11373. }
  11374. }
  11375. XmlElement::~XmlElement() throw()
  11376. {
  11377. XmlElement* child = firstChildElement;
  11378. while (child != 0)
  11379. {
  11380. XmlElement* const nextChild = child->nextElement;
  11381. delete child;
  11382. child = nextChild;
  11383. }
  11384. XmlAttributeNode* att = attributes;
  11385. while (att != 0)
  11386. {
  11387. XmlAttributeNode* const nextAtt = att->next;
  11388. delete att;
  11389. att = nextAtt;
  11390. }
  11391. }
  11392. static bool isLegalXmlChar (const juce_wchar character)
  11393. {
  11394. if ((character >= 'a' && character <= 'z')
  11395. || (character >= 'A' && character <= 'Z')
  11396. || (character >= '0' && character <= '9'))
  11397. return true;
  11398. const char* t = " .,;:-()_+=?!'#@[]/\\*%~{}";
  11399. do
  11400. {
  11401. if (((juce_wchar) (uint8) *t) == character)
  11402. return true;
  11403. }
  11404. while (*++t != 0);
  11405. return false;
  11406. }
  11407. static void escapeIllegalXmlChars (OutputStream& outputStream,
  11408. const String& text,
  11409. const bool changeNewLines) throw()
  11410. {
  11411. const juce_wchar* t = (const juce_wchar*) text;
  11412. for (;;)
  11413. {
  11414. const juce_wchar character = *t++;
  11415. if (character == 0)
  11416. {
  11417. break;
  11418. }
  11419. else if (isLegalXmlChar (character))
  11420. {
  11421. outputStream.writeByte ((char) character);
  11422. }
  11423. else
  11424. {
  11425. switch (character)
  11426. {
  11427. case '&':
  11428. outputStream.write ("&amp;", 5);
  11429. break;
  11430. case '"':
  11431. outputStream.write ("&quot;", 6);
  11432. break;
  11433. case '>':
  11434. outputStream.write ("&gt;", 4);
  11435. break;
  11436. case '<':
  11437. outputStream.write ("&lt;", 4);
  11438. break;
  11439. case '\n':
  11440. if (changeNewLines)
  11441. outputStream.write ("&#10;", 5);
  11442. else
  11443. outputStream.writeByte ((char) character);
  11444. break;
  11445. case '\r':
  11446. if (changeNewLines)
  11447. outputStream.write ("&#13;", 5);
  11448. else
  11449. outputStream.writeByte ((char) character);
  11450. break;
  11451. default:
  11452. {
  11453. String encoded (T("&#"));
  11454. encoded << String ((int) (unsigned int) character).trim()
  11455. << T(';');
  11456. outputStream.write ((const char*) encoded, encoded.length());
  11457. }
  11458. }
  11459. }
  11460. }
  11461. }
  11462. static void writeSpaces (OutputStream& out, int numSpaces) throw()
  11463. {
  11464. if (numSpaces > 0)
  11465. {
  11466. const char* const blanks = " ";
  11467. const int blankSize = (int) sizeof (blanks) - 1;
  11468. while (numSpaces > blankSize)
  11469. {
  11470. out.write (blanks, blankSize);
  11471. numSpaces -= blankSize;
  11472. }
  11473. out.write (blanks, numSpaces);
  11474. }
  11475. }
  11476. void XmlElement::writeElementAsText (OutputStream& outputStream,
  11477. const int indentationLevel,
  11478. const int lineWrapLength) const throw()
  11479. {
  11480. writeSpaces (outputStream, indentationLevel);
  11481. if (! isTextElement())
  11482. {
  11483. outputStream.writeByte ('<');
  11484. const int nameLen = tagName.length();
  11485. outputStream.write ((const char*) tagName, nameLen);
  11486. const int attIndent = indentationLevel + nameLen + 1;
  11487. int lineLen = 0;
  11488. const XmlAttributeNode* att = attributes;
  11489. while (att != 0)
  11490. {
  11491. if (lineLen > lineWrapLength && indentationLevel >= 0)
  11492. {
  11493. outputStream.write ("\r\n", 2);
  11494. writeSpaces (outputStream, attIndent);
  11495. lineLen = 0;
  11496. }
  11497. const int attNameLen = att->name.length();
  11498. outputStream.writeByte (' ');
  11499. outputStream.write ((const char*) (att->name), attNameLen);
  11500. outputStream.write ("=\"", 2);
  11501. escapeIllegalXmlChars (outputStream, att->value, true);
  11502. outputStream.writeByte ('"');
  11503. lineLen += 4 + attNameLen + att->value.length();
  11504. att = att->next;
  11505. }
  11506. if (firstChildElement != 0)
  11507. {
  11508. XmlElement* child = firstChildElement;
  11509. if (child->nextElement == 0 && child->isTextElement())
  11510. {
  11511. outputStream.writeByte ('>');
  11512. escapeIllegalXmlChars (outputStream, child->getText(), false);
  11513. }
  11514. else
  11515. {
  11516. if (indentationLevel >= 0)
  11517. outputStream.write (">\r\n", 3);
  11518. else
  11519. outputStream.writeByte ('>');
  11520. bool lastWasTextNode = false;
  11521. while (child != 0)
  11522. {
  11523. if (child->isTextElement())
  11524. {
  11525. if ((! lastWasTextNode) && (indentationLevel >= 0))
  11526. writeSpaces (outputStream, indentationLevel + 2);
  11527. escapeIllegalXmlChars (outputStream, child->getText(), false);
  11528. lastWasTextNode = true;
  11529. }
  11530. else
  11531. {
  11532. if (indentationLevel >= 0)
  11533. {
  11534. if (lastWasTextNode)
  11535. outputStream.write ("\r\n", 2);
  11536. child->writeElementAsText (outputStream, indentationLevel + 2, lineWrapLength);
  11537. }
  11538. else
  11539. {
  11540. child->writeElementAsText (outputStream, indentationLevel, lineWrapLength);
  11541. }
  11542. lastWasTextNode = false;
  11543. }
  11544. child = child->nextElement;
  11545. }
  11546. if (indentationLevel >= 0)
  11547. {
  11548. if (lastWasTextNode)
  11549. outputStream.write ("\r\n", 2);
  11550. writeSpaces (outputStream, indentationLevel);
  11551. }
  11552. }
  11553. outputStream.write ("</", 2);
  11554. outputStream.write ((const char*) tagName, nameLen);
  11555. if (indentationLevel >= 0)
  11556. outputStream.write (">\r\n", 3);
  11557. else
  11558. outputStream.writeByte ('>');
  11559. }
  11560. else
  11561. {
  11562. if (indentationLevel >= 0)
  11563. outputStream.write ("/>\r\n", 4);
  11564. else
  11565. outputStream.write ("/>", 2);
  11566. }
  11567. }
  11568. else
  11569. {
  11570. if (indentationLevel >= 0)
  11571. writeSpaces (outputStream, indentationLevel + 2);
  11572. escapeIllegalXmlChars (outputStream, getText(), false);
  11573. }
  11574. }
  11575. const String XmlElement::createDocument (const String& dtd,
  11576. const bool allOnOneLine,
  11577. const bool includeXmlHeader,
  11578. const tchar* const encoding,
  11579. const int lineWrapLength) const throw()
  11580. {
  11581. String doc;
  11582. doc.preallocateStorage (1024);
  11583. if (includeXmlHeader)
  11584. {
  11585. doc << "<?xml version=\"1.0\" encoding=\""
  11586. << encoding;
  11587. if (allOnOneLine)
  11588. doc += "\"?> ";
  11589. else
  11590. doc += "\"?>\n\n";
  11591. }
  11592. if (dtd.isNotEmpty())
  11593. {
  11594. if (allOnOneLine)
  11595. doc << dtd << " ";
  11596. else
  11597. doc << dtd << "\r\n";
  11598. }
  11599. MemoryOutputStream mem (2048, 4096);
  11600. writeElementAsText (mem, allOnOneLine ? -1 : 0, lineWrapLength);
  11601. return doc + String (mem.getData(),
  11602. mem.getDataSize());
  11603. }
  11604. bool XmlElement::writeToFile (const File& f,
  11605. const String& dtd,
  11606. const tchar* const encoding,
  11607. const int lineWrapLength) const throw()
  11608. {
  11609. if (f.hasWriteAccess())
  11610. {
  11611. const File tempFile (f.getNonexistentSibling());
  11612. FileOutputStream* const out = tempFile.createOutputStream();
  11613. if (out != 0)
  11614. {
  11615. *out << "<?xml version=\"1.0\" encoding=\"" << encoding << "\"?>\r\n\r\n"
  11616. << dtd << "\r\n";
  11617. writeElementAsText (*out, 0, lineWrapLength);
  11618. delete out;
  11619. if (tempFile.moveFileTo (f))
  11620. return true;
  11621. tempFile.deleteFile();
  11622. }
  11623. }
  11624. return false;
  11625. }
  11626. bool XmlElement::hasTagName (const tchar* const tagNameWanted) const throw()
  11627. {
  11628. #ifdef JUCE_DEBUG
  11629. // if debugging, check that the case is actually the same, because
  11630. // valid xml is case-sensitive, and although this lets it pass, it's
  11631. // better not to..
  11632. if (tagName.equalsIgnoreCase (tagNameWanted))
  11633. {
  11634. jassert (tagName == tagNameWanted);
  11635. return true;
  11636. }
  11637. else
  11638. {
  11639. return false;
  11640. }
  11641. #else
  11642. return tagName.equalsIgnoreCase (tagNameWanted);
  11643. #endif
  11644. }
  11645. XmlElement* XmlElement::getNextElementWithTagName (const tchar* const requiredTagName) const
  11646. {
  11647. XmlElement* e = nextElement;
  11648. while (e != 0 && ! e->hasTagName (requiredTagName))
  11649. e = e->nextElement;
  11650. return e;
  11651. }
  11652. int XmlElement::getNumAttributes() const throw()
  11653. {
  11654. const XmlAttributeNode* att = attributes;
  11655. int count = 0;
  11656. while (att != 0)
  11657. {
  11658. att = att->next;
  11659. ++count;
  11660. }
  11661. return count;
  11662. }
  11663. const String& XmlElement::getAttributeName (const int index) const throw()
  11664. {
  11665. const XmlAttributeNode* att = attributes;
  11666. int count = 0;
  11667. while (att != 0)
  11668. {
  11669. if (count == index)
  11670. return att->name;
  11671. att = att->next;
  11672. ++count;
  11673. }
  11674. return String::empty;
  11675. }
  11676. const String& XmlElement::getAttributeValue (const int index) const throw()
  11677. {
  11678. const XmlAttributeNode* att = attributes;
  11679. int count = 0;
  11680. while (att != 0)
  11681. {
  11682. if (count == index)
  11683. return att->value;
  11684. att = att->next;
  11685. ++count;
  11686. }
  11687. return String::empty;
  11688. }
  11689. bool XmlElement::hasAttribute (const tchar* const attributeName) const throw()
  11690. {
  11691. const XmlAttributeNode* att = attributes;
  11692. while (att != 0)
  11693. {
  11694. if (att->name.equalsIgnoreCase (attributeName))
  11695. return true;
  11696. att = att->next;
  11697. }
  11698. return false;
  11699. }
  11700. const String XmlElement::getStringAttribute (const tchar* const attributeName,
  11701. const tchar* const defaultReturnValue) const throw()
  11702. {
  11703. const XmlAttributeNode* att = attributes;
  11704. while (att != 0)
  11705. {
  11706. if (att->name.equalsIgnoreCase (attributeName))
  11707. return att->value;
  11708. att = att->next;
  11709. }
  11710. return defaultReturnValue;
  11711. }
  11712. int XmlElement::getIntAttribute (const tchar* const attributeName,
  11713. const int defaultReturnValue) const throw()
  11714. {
  11715. const XmlAttributeNode* att = attributes;
  11716. while (att != 0)
  11717. {
  11718. if (att->name.equalsIgnoreCase (attributeName))
  11719. return att->value.getIntValue();
  11720. att = att->next;
  11721. }
  11722. return defaultReturnValue;
  11723. }
  11724. double XmlElement::getDoubleAttribute (const tchar* const attributeName,
  11725. const double defaultReturnValue) const throw()
  11726. {
  11727. const XmlAttributeNode* att = attributes;
  11728. while (att != 0)
  11729. {
  11730. if (att->name.equalsIgnoreCase (attributeName))
  11731. return att->value.getDoubleValue();
  11732. att = att->next;
  11733. }
  11734. return defaultReturnValue;
  11735. }
  11736. bool XmlElement::getBoolAttribute (const tchar* const attributeName,
  11737. const bool defaultReturnValue) const throw()
  11738. {
  11739. const XmlAttributeNode* att = attributes;
  11740. while (att != 0)
  11741. {
  11742. if (att->name.equalsIgnoreCase (attributeName))
  11743. {
  11744. tchar firstChar = att->value[0];
  11745. if (CharacterFunctions::isWhitespace (firstChar))
  11746. firstChar = att->value.trimStart() [0];
  11747. return firstChar == T('1')
  11748. || firstChar == T('t')
  11749. || firstChar == T('y')
  11750. || firstChar == T('T')
  11751. || firstChar == T('Y');
  11752. }
  11753. att = att->next;
  11754. }
  11755. return defaultReturnValue;
  11756. }
  11757. bool XmlElement::compareAttribute (const tchar* const attributeName,
  11758. const tchar* const stringToCompareAgainst,
  11759. const bool ignoreCase) const throw()
  11760. {
  11761. const XmlAttributeNode* att = attributes;
  11762. while (att != 0)
  11763. {
  11764. if (att->name.equalsIgnoreCase (attributeName))
  11765. {
  11766. if (ignoreCase)
  11767. return att->value.equalsIgnoreCase (stringToCompareAgainst);
  11768. else
  11769. return att->value == stringToCompareAgainst;
  11770. }
  11771. att = att->next;
  11772. }
  11773. return false;
  11774. }
  11775. void XmlElement::setAttribute (const tchar* const attributeName,
  11776. const String& value) throw()
  11777. {
  11778. #ifdef JUCE_DEBUG
  11779. // check the identifier being passed in is legal..
  11780. const tchar* t = attributeName;
  11781. while (*t != 0)
  11782. {
  11783. jassert (CharacterFunctions::isLetterOrDigit (*t)
  11784. || *t == T('_')
  11785. || *t == T('-')
  11786. || *t == T(':'));
  11787. ++t;
  11788. }
  11789. #endif
  11790. if (attributes == 0)
  11791. {
  11792. attributes = new XmlAttributeNode (attributeName, value);
  11793. }
  11794. else
  11795. {
  11796. XmlAttributeNode* att = attributes;
  11797. for (;;)
  11798. {
  11799. if (att->name.equalsIgnoreCase (attributeName))
  11800. {
  11801. att->value = value;
  11802. break;
  11803. }
  11804. else if (att->next == 0)
  11805. {
  11806. att->next = new XmlAttributeNode (attributeName, value);
  11807. break;
  11808. }
  11809. att = att->next;
  11810. }
  11811. }
  11812. }
  11813. void XmlElement::setAttribute (const tchar* const attributeName,
  11814. const tchar* const text) throw()
  11815. {
  11816. setAttribute (attributeName, String (text));
  11817. }
  11818. void XmlElement::setAttribute (const tchar* const attributeName,
  11819. const int number) throw()
  11820. {
  11821. setAttribute (attributeName, String (number));
  11822. }
  11823. void XmlElement::setAttribute (const tchar* const attributeName,
  11824. const double number) throw()
  11825. {
  11826. tchar buffer [40];
  11827. CharacterFunctions::printf (buffer, numElementsInArray (buffer), T("%.9g"), number);
  11828. setAttribute (attributeName, buffer);
  11829. }
  11830. void XmlElement::removeAttribute (const tchar* const attributeName) throw()
  11831. {
  11832. XmlAttributeNode* att = attributes;
  11833. XmlAttributeNode* lastAtt = 0;
  11834. while (att != 0)
  11835. {
  11836. if (att->name.equalsIgnoreCase (attributeName))
  11837. {
  11838. if (lastAtt == 0)
  11839. attributes = att->next;
  11840. else
  11841. lastAtt->next = att->next;
  11842. delete att;
  11843. break;
  11844. }
  11845. lastAtt = att;
  11846. att = att->next;
  11847. }
  11848. }
  11849. void XmlElement::removeAllAttributes() throw()
  11850. {
  11851. while (attributes != 0)
  11852. {
  11853. XmlAttributeNode* const nextAtt = attributes->next;
  11854. delete attributes;
  11855. attributes = nextAtt;
  11856. }
  11857. }
  11858. int XmlElement::getNumChildElements() const throw()
  11859. {
  11860. int count = 0;
  11861. const XmlElement* child = firstChildElement;
  11862. while (child != 0)
  11863. {
  11864. ++count;
  11865. child = child->nextElement;
  11866. }
  11867. return count;
  11868. }
  11869. XmlElement* XmlElement::getChildElement (const int index) const throw()
  11870. {
  11871. int count = 0;
  11872. XmlElement* child = firstChildElement;
  11873. while (child != 0 && count < index)
  11874. {
  11875. child = child->nextElement;
  11876. ++count;
  11877. }
  11878. return child;
  11879. }
  11880. XmlElement* XmlElement::getChildByName (const tchar* const childName) const throw()
  11881. {
  11882. XmlElement* child = firstChildElement;
  11883. while (child != 0)
  11884. {
  11885. if (child->hasTagName (childName))
  11886. break;
  11887. child = child->nextElement;
  11888. }
  11889. return child;
  11890. }
  11891. void XmlElement::addChildElement (XmlElement* const newNode) throw()
  11892. {
  11893. if (newNode != 0)
  11894. {
  11895. if (firstChildElement == 0)
  11896. {
  11897. firstChildElement = newNode;
  11898. }
  11899. else
  11900. {
  11901. XmlElement* child = firstChildElement;
  11902. while (child->nextElement != 0)
  11903. child = child->nextElement;
  11904. child->nextElement = newNode;
  11905. // if this is non-zero, then something's probably
  11906. // gone wrong..
  11907. jassert (newNode->nextElement == 0);
  11908. }
  11909. }
  11910. }
  11911. void XmlElement::insertChildElement (XmlElement* const newNode,
  11912. int indexToInsertAt) throw()
  11913. {
  11914. if (newNode != 0)
  11915. {
  11916. removeChildElement (newNode, false);
  11917. if (indexToInsertAt == 0)
  11918. {
  11919. newNode->nextElement = firstChildElement;
  11920. firstChildElement = newNode;
  11921. }
  11922. else
  11923. {
  11924. if (firstChildElement == 0)
  11925. {
  11926. firstChildElement = newNode;
  11927. }
  11928. else
  11929. {
  11930. if (indexToInsertAt < 0)
  11931. indexToInsertAt = INT_MAX;
  11932. XmlElement* child = firstChildElement;
  11933. while (child->nextElement != 0 && --indexToInsertAt > 0)
  11934. child = child->nextElement;
  11935. newNode->nextElement = child->nextElement;
  11936. child->nextElement = newNode;
  11937. }
  11938. }
  11939. }
  11940. }
  11941. bool XmlElement::replaceChildElement (XmlElement* const currentChildElement,
  11942. XmlElement* const newNode) throw()
  11943. {
  11944. if (newNode != 0)
  11945. {
  11946. XmlElement* child = firstChildElement;
  11947. XmlElement* previousNode = 0;
  11948. while (child != 0)
  11949. {
  11950. if (child == currentChildElement)
  11951. {
  11952. if (child != newNode)
  11953. {
  11954. if (previousNode == 0)
  11955. firstChildElement = newNode;
  11956. else
  11957. previousNode->nextElement = newNode;
  11958. newNode->nextElement = child->nextElement;
  11959. delete child;
  11960. }
  11961. return true;
  11962. }
  11963. previousNode = child;
  11964. child = child->nextElement;
  11965. }
  11966. }
  11967. return false;
  11968. }
  11969. void XmlElement::removeChildElement (XmlElement* const childToRemove,
  11970. const bool shouldDeleteTheChild) throw()
  11971. {
  11972. if (childToRemove != 0)
  11973. {
  11974. if (firstChildElement == childToRemove)
  11975. {
  11976. firstChildElement = childToRemove->nextElement;
  11977. childToRemove->nextElement = 0;
  11978. }
  11979. else
  11980. {
  11981. XmlElement* child = firstChildElement;
  11982. XmlElement* last = 0;
  11983. while (child != 0)
  11984. {
  11985. if (child == childToRemove)
  11986. {
  11987. if (last == 0)
  11988. firstChildElement = child->nextElement;
  11989. else
  11990. last->nextElement = child->nextElement;
  11991. childToRemove->nextElement = 0;
  11992. break;
  11993. }
  11994. last = child;
  11995. child = child->nextElement;
  11996. }
  11997. }
  11998. if (shouldDeleteTheChild)
  11999. delete childToRemove;
  12000. }
  12001. }
  12002. bool XmlElement::isEquivalentTo (const XmlElement* const other,
  12003. const bool ignoreOrderOfAttributes) const throw()
  12004. {
  12005. if (this != other)
  12006. {
  12007. if (other == 0 || tagName != other->tagName)
  12008. {
  12009. return false;
  12010. }
  12011. if (ignoreOrderOfAttributes)
  12012. {
  12013. int totalAtts = 0;
  12014. const XmlAttributeNode* att = attributes;
  12015. while (att != 0)
  12016. {
  12017. if (! other->compareAttribute (att->name, att->value))
  12018. return false;
  12019. att = att->next;
  12020. ++totalAtts;
  12021. }
  12022. if (totalAtts != other->getNumAttributes())
  12023. return false;
  12024. }
  12025. else
  12026. {
  12027. const XmlAttributeNode* thisAtt = attributes;
  12028. const XmlAttributeNode* otherAtt = other->attributes;
  12029. for (;;)
  12030. {
  12031. if (thisAtt == 0 || otherAtt == 0)
  12032. {
  12033. if (thisAtt == otherAtt) // both 0, so it's a match
  12034. break;
  12035. return false;
  12036. }
  12037. if (thisAtt->name != otherAtt->name
  12038. || thisAtt->value != otherAtt->value)
  12039. {
  12040. return false;
  12041. }
  12042. thisAtt = thisAtt->next;
  12043. otherAtt = otherAtt->next;
  12044. }
  12045. }
  12046. const XmlElement* thisChild = firstChildElement;
  12047. const XmlElement* otherChild = other->firstChildElement;
  12048. for (;;)
  12049. {
  12050. if (thisChild == 0 || otherChild == 0)
  12051. {
  12052. if (thisChild == otherChild) // both 0, so it's a match
  12053. break;
  12054. return false;
  12055. }
  12056. if (! thisChild->isEquivalentTo (otherChild, ignoreOrderOfAttributes))
  12057. return false;
  12058. thisChild = thisChild->nextElement;
  12059. otherChild = otherChild->nextElement;
  12060. }
  12061. }
  12062. return true;
  12063. }
  12064. void XmlElement::deleteAllChildElements() throw()
  12065. {
  12066. while (firstChildElement != 0)
  12067. {
  12068. XmlElement* const nextChild = firstChildElement->nextElement;
  12069. delete firstChildElement;
  12070. firstChildElement = nextChild;
  12071. }
  12072. }
  12073. void XmlElement::deleteAllChildElementsWithTagName (const tchar* const name) throw()
  12074. {
  12075. XmlElement* child = firstChildElement;
  12076. while (child != 0)
  12077. {
  12078. if (child->hasTagName (name))
  12079. {
  12080. XmlElement* const nextChild = child->nextElement;
  12081. removeChildElement (child, true);
  12082. child = nextChild;
  12083. }
  12084. else
  12085. {
  12086. child = child->nextElement;
  12087. }
  12088. }
  12089. }
  12090. bool XmlElement::containsChildElement (const XmlElement* const possibleChild) const throw()
  12091. {
  12092. const XmlElement* child = firstChildElement;
  12093. while (child != 0)
  12094. {
  12095. if (child == possibleChild)
  12096. return true;
  12097. child = child->nextElement;
  12098. }
  12099. return false;
  12100. }
  12101. XmlElement* XmlElement::findParentElementOf (const XmlElement* const elementToLookFor) throw()
  12102. {
  12103. if (this == elementToLookFor || elementToLookFor == 0)
  12104. return 0;
  12105. XmlElement* child = firstChildElement;
  12106. while (child != 0)
  12107. {
  12108. if (elementToLookFor == child)
  12109. return this;
  12110. XmlElement* const found = child->findParentElementOf (elementToLookFor);
  12111. if (found != 0)
  12112. return found;
  12113. child = child->nextElement;
  12114. }
  12115. return 0;
  12116. }
  12117. XmlElement** XmlElement::getChildElementsAsArray (const int num) const throw()
  12118. {
  12119. XmlElement** const elems = new XmlElement* [num];
  12120. XmlElement* e = firstChildElement;
  12121. int i = 0;
  12122. while (e != 0)
  12123. {
  12124. elems [i++] = e;
  12125. e = e->nextElement;
  12126. }
  12127. return elems;
  12128. }
  12129. void XmlElement::reorderChildElements (XmlElement** const elems, const int num) throw()
  12130. {
  12131. XmlElement* e = firstChildElement = elems[0];
  12132. for (int i = 1; i < num; ++i)
  12133. {
  12134. e->nextElement = elems[i];
  12135. e = e->nextElement;
  12136. }
  12137. e->nextElement = 0;
  12138. }
  12139. bool XmlElement::isTextElement() const throw()
  12140. {
  12141. return tagName.isEmpty();
  12142. }
  12143. static const tchar* const juce_xmltextContentAttributeName = T("text");
  12144. const String XmlElement::getText() const throw()
  12145. {
  12146. jassert (isTextElement()); // you're trying to get the text from an element that
  12147. // isn't actually a text element.. If this contains text sub-nodes, you
  12148. // can use getAllSubText instead to
  12149. return getStringAttribute (juce_xmltextContentAttributeName);
  12150. }
  12151. void XmlElement::setText (const String& newText) throw()
  12152. {
  12153. if (isTextElement())
  12154. {
  12155. setAttribute (juce_xmltextContentAttributeName, newText);
  12156. }
  12157. else
  12158. {
  12159. jassertfalse // you can only change the text in a text element, not a normal one.
  12160. }
  12161. }
  12162. const String XmlElement::getAllSubText() const throw()
  12163. {
  12164. String result;
  12165. const XmlElement* child = firstChildElement;
  12166. while (child != 0)
  12167. {
  12168. if (child->isTextElement())
  12169. result += child->getText();
  12170. child = child->nextElement;
  12171. }
  12172. return result;
  12173. }
  12174. const String XmlElement::getChildElementAllSubText (const tchar* const childTagName,
  12175. const String& defaultReturnValue) const throw()
  12176. {
  12177. const XmlElement* const child = getChildByName (childTagName);
  12178. if (child != 0)
  12179. return child->getAllSubText();
  12180. return defaultReturnValue;
  12181. }
  12182. XmlElement* XmlElement::createTextElement (const String& text) throw()
  12183. {
  12184. XmlElement* const e = new XmlElement ((int) 0);
  12185. e->setAttribute (juce_xmltextContentAttributeName, text);
  12186. return e;
  12187. }
  12188. void XmlElement::addTextElement (const String& text) throw()
  12189. {
  12190. addChildElement (createTextElement (text));
  12191. }
  12192. void XmlElement::deleteAllTextElements() throw()
  12193. {
  12194. XmlElement* child = firstChildElement;
  12195. while (child != 0)
  12196. {
  12197. XmlElement* const next = child->nextElement;
  12198. if (child->isTextElement())
  12199. removeChildElement (child, true);
  12200. child = next;
  12201. }
  12202. }
  12203. END_JUCE_NAMESPACE
  12204. /********* End of inlined file: juce_XmlElement.cpp *********/
  12205. /********* Start of inlined file: juce_InterProcessLock.cpp *********/
  12206. BEGIN_JUCE_NAMESPACE
  12207. // (implemented in the platform-specific code files)
  12208. END_JUCE_NAMESPACE
  12209. /********* End of inlined file: juce_InterProcessLock.cpp *********/
  12210. /********* Start of inlined file: juce_ReadWriteLock.cpp *********/
  12211. BEGIN_JUCE_NAMESPACE
  12212. ReadWriteLock::ReadWriteLock() throw()
  12213. : numWaitingWriters (0),
  12214. numWriters (0),
  12215. writerThreadId (0)
  12216. {
  12217. }
  12218. ReadWriteLock::~ReadWriteLock() throw()
  12219. {
  12220. jassert (readerThreads.size() == 0);
  12221. jassert (numWriters == 0);
  12222. }
  12223. void ReadWriteLock::enterRead() const throw()
  12224. {
  12225. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  12226. const ScopedLock sl (accessLock);
  12227. for (;;)
  12228. {
  12229. jassert (readerThreads.size() % 2 == 0);
  12230. int i;
  12231. for (i = 0; i < readerThreads.size(); i += 2)
  12232. if (readerThreads.getUnchecked(i) == threadId)
  12233. break;
  12234. if (i < readerThreads.size()
  12235. || numWriters + numWaitingWriters == 0
  12236. || (threadId == writerThreadId && numWriters > 0))
  12237. {
  12238. if (i < readerThreads.size())
  12239. {
  12240. readerThreads.set (i + 1, (Thread::ThreadID) (1 + (pointer_sized_int) readerThreads.getUnchecked (i + 1)));
  12241. }
  12242. else
  12243. {
  12244. readerThreads.add (threadId);
  12245. readerThreads.add ((Thread::ThreadID) 1);
  12246. }
  12247. return;
  12248. }
  12249. const ScopedUnlock ul (accessLock);
  12250. waitEvent.wait (100);
  12251. }
  12252. }
  12253. void ReadWriteLock::exitRead() const throw()
  12254. {
  12255. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  12256. const ScopedLock sl (accessLock);
  12257. for (int i = 0; i < readerThreads.size(); i += 2)
  12258. {
  12259. if (readerThreads.getUnchecked(i) == threadId)
  12260. {
  12261. const pointer_sized_int newCount = ((pointer_sized_int) readerThreads.getUnchecked (i + 1)) - 1;
  12262. if (newCount == 0)
  12263. {
  12264. readerThreads.removeRange (i, 2);
  12265. waitEvent.signal();
  12266. }
  12267. else
  12268. {
  12269. readerThreads.set (i + 1, (Thread::ThreadID) newCount);
  12270. }
  12271. return;
  12272. }
  12273. }
  12274. jassertfalse // unlocking a lock that wasn't locked..
  12275. }
  12276. void ReadWriteLock::enterWrite() const throw()
  12277. {
  12278. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  12279. const ScopedLock sl (accessLock);
  12280. for (;;)
  12281. {
  12282. if (readerThreads.size() + numWriters == 0
  12283. || threadId == writerThreadId
  12284. || (readerThreads.size() == 2
  12285. && readerThreads.getUnchecked(0) == threadId))
  12286. {
  12287. writerThreadId = threadId;
  12288. ++numWriters;
  12289. break;
  12290. }
  12291. ++numWaitingWriters;
  12292. accessLock.exit();
  12293. waitEvent.wait (100);
  12294. accessLock.enter();
  12295. --numWaitingWriters;
  12296. }
  12297. }
  12298. bool ReadWriteLock::tryEnterWrite() const throw()
  12299. {
  12300. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  12301. const ScopedLock sl (accessLock);
  12302. if (readerThreads.size() + numWriters == 0
  12303. || threadId == writerThreadId
  12304. || (readerThreads.size() == 2
  12305. && readerThreads.getUnchecked(0) == threadId))
  12306. {
  12307. writerThreadId = threadId;
  12308. ++numWriters;
  12309. return true;
  12310. }
  12311. return false;
  12312. }
  12313. void ReadWriteLock::exitWrite() const throw()
  12314. {
  12315. const ScopedLock sl (accessLock);
  12316. // check this thread actually had the lock..
  12317. jassert (numWriters > 0 && writerThreadId == Thread::getCurrentThreadId());
  12318. if (--numWriters == 0)
  12319. {
  12320. writerThreadId = 0;
  12321. waitEvent.signal();
  12322. }
  12323. }
  12324. END_JUCE_NAMESPACE
  12325. /********* End of inlined file: juce_ReadWriteLock.cpp *********/
  12326. /********* Start of inlined file: juce_Thread.cpp *********/
  12327. BEGIN_JUCE_NAMESPACE
  12328. // these functions are implemented in the platform-specific code.
  12329. void* juce_createThread (void* userData) throw();
  12330. void juce_killThread (void* handle) throw();
  12331. bool juce_setThreadPriority (void* handle, int priority) throw();
  12332. void juce_setCurrentThreadName (const String& name) throw();
  12333. #if JUCE_WIN32
  12334. void juce_CloseThreadHandle (void* handle) throw();
  12335. #endif
  12336. static VoidArray runningThreads (4);
  12337. static CriticalSection runningThreadsLock;
  12338. void Thread::threadEntryPoint (Thread* const thread) throw()
  12339. {
  12340. {
  12341. const ScopedLock sl (runningThreadsLock);
  12342. runningThreads.add (thread);
  12343. }
  12344. JUCE_TRY
  12345. {
  12346. thread->threadId_ = Thread::getCurrentThreadId();
  12347. if (thread->threadName_.isNotEmpty())
  12348. juce_setCurrentThreadName (thread->threadName_);
  12349. if (thread->startSuspensionEvent_.wait (10000))
  12350. {
  12351. if (thread->affinityMask_ != 0)
  12352. setCurrentThreadAffinityMask (thread->affinityMask_);
  12353. thread->run();
  12354. }
  12355. }
  12356. JUCE_CATCH_ALL_ASSERT
  12357. {
  12358. const ScopedLock sl (runningThreadsLock);
  12359. jassert (runningThreads.contains (thread));
  12360. runningThreads.removeValue (thread);
  12361. }
  12362. #if JUCE_WIN32
  12363. juce_CloseThreadHandle (thread->threadHandle_);
  12364. #endif
  12365. thread->threadHandle_ = 0;
  12366. thread->threadId_ = 0;
  12367. }
  12368. // used to wrap the incoming call from the platform-specific code
  12369. void JUCE_API juce_threadEntryPoint (void* userData)
  12370. {
  12371. Thread::threadEntryPoint ((Thread*) userData);
  12372. }
  12373. Thread::Thread (const String& threadName)
  12374. : threadName_ (threadName),
  12375. threadHandle_ (0),
  12376. threadPriority_ (5),
  12377. threadId_ (0),
  12378. affinityMask_ (0),
  12379. threadShouldExit_ (false)
  12380. {
  12381. }
  12382. Thread::~Thread()
  12383. {
  12384. stopThread (100);
  12385. }
  12386. void Thread::startThread() throw()
  12387. {
  12388. const ScopedLock sl (startStopLock);
  12389. threadShouldExit_ = false;
  12390. if (threadHandle_ == 0)
  12391. {
  12392. threadHandle_ = juce_createThread ((void*) this);
  12393. juce_setThreadPriority (threadHandle_, threadPriority_);
  12394. startSuspensionEvent_.signal();
  12395. }
  12396. }
  12397. void Thread::startThread (const int priority) throw()
  12398. {
  12399. const ScopedLock sl (startStopLock);
  12400. if (threadHandle_ == 0)
  12401. {
  12402. threadPriority_ = priority;
  12403. startThread();
  12404. }
  12405. else
  12406. {
  12407. setPriority (priority);
  12408. }
  12409. }
  12410. bool Thread::isThreadRunning() const throw()
  12411. {
  12412. return threadHandle_ != 0;
  12413. }
  12414. void Thread::signalThreadShouldExit() throw()
  12415. {
  12416. threadShouldExit_ = true;
  12417. }
  12418. bool Thread::waitForThreadToExit (const int timeOutMilliseconds) const throw()
  12419. {
  12420. // Doh! So how exactly do you expect this thread to wait for itself to stop??
  12421. jassert (getThreadId() != getCurrentThreadId());
  12422. const int sleepMsPerIteration = 5;
  12423. int count = timeOutMilliseconds / sleepMsPerIteration;
  12424. while (isThreadRunning())
  12425. {
  12426. if (timeOutMilliseconds > 0 && --count < 0)
  12427. return false;
  12428. sleep (sleepMsPerIteration);
  12429. }
  12430. return true;
  12431. }
  12432. void Thread::stopThread (const int timeOutMilliseconds) throw()
  12433. {
  12434. // agh! You can't stop the thread that's calling this method! How on earth
  12435. // would that work??
  12436. jassert (getCurrentThreadId() != getThreadId());
  12437. const ScopedLock sl (startStopLock);
  12438. if (isThreadRunning())
  12439. {
  12440. signalThreadShouldExit();
  12441. notify();
  12442. if (timeOutMilliseconds != 0)
  12443. waitForThreadToExit (timeOutMilliseconds);
  12444. if (isThreadRunning())
  12445. {
  12446. // very bad karma if this point is reached, as
  12447. // there are bound to be locks and events left in
  12448. // silly states when a thread is killed by force..
  12449. jassertfalse
  12450. Logger::writeToLog ("!! killing thread by force !!");
  12451. juce_killThread (threadHandle_);
  12452. threadHandle_ = 0;
  12453. threadId_ = 0;
  12454. const ScopedLock sl (runningThreadsLock);
  12455. runningThreads.removeValue (this);
  12456. }
  12457. }
  12458. }
  12459. bool Thread::setPriority (const int priority) throw()
  12460. {
  12461. const ScopedLock sl (startStopLock);
  12462. const bool worked = juce_setThreadPriority (threadHandle_, priority);
  12463. if (worked)
  12464. threadPriority_ = priority;
  12465. return worked;
  12466. }
  12467. bool Thread::setCurrentThreadPriority (const int priority) throw()
  12468. {
  12469. return juce_setThreadPriority (0, priority);
  12470. }
  12471. void Thread::setAffinityMask (const uint32 affinityMask) throw()
  12472. {
  12473. affinityMask_ = affinityMask;
  12474. }
  12475. Thread::ThreadID Thread::getThreadId() const throw()
  12476. {
  12477. return threadId_;
  12478. }
  12479. bool Thread::wait (const int timeOutMilliseconds) const throw()
  12480. {
  12481. return defaultEvent_.wait (timeOutMilliseconds);
  12482. }
  12483. void Thread::notify() const throw()
  12484. {
  12485. defaultEvent_.signal();
  12486. }
  12487. int Thread::getNumRunningThreads() throw()
  12488. {
  12489. return runningThreads.size();
  12490. }
  12491. Thread* Thread::getCurrentThread() throw()
  12492. {
  12493. const ThreadID thisId = getCurrentThreadId();
  12494. const ScopedLock sl (runningThreadsLock);
  12495. for (int i = runningThreads.size(); --i >= 0;)
  12496. {
  12497. Thread* const t = (Thread*) (runningThreads.getUnchecked(i));
  12498. if (t->threadId_ == thisId)
  12499. return t;
  12500. }
  12501. return 0;
  12502. }
  12503. void Thread::stopAllThreads (const int timeOutMilliseconds) throw()
  12504. {
  12505. {
  12506. const ScopedLock sl (runningThreadsLock);
  12507. for (int i = runningThreads.size(); --i >= 0;)
  12508. ((Thread*) runningThreads.getUnchecked(i))->signalThreadShouldExit();
  12509. }
  12510. for (;;)
  12511. {
  12512. runningThreadsLock.enter();
  12513. Thread* const t = (Thread*) runningThreads[0];
  12514. runningThreadsLock.exit();
  12515. if (t == 0)
  12516. break;
  12517. t->stopThread (timeOutMilliseconds);
  12518. }
  12519. }
  12520. END_JUCE_NAMESPACE
  12521. /********* End of inlined file: juce_Thread.cpp *********/
  12522. /********* Start of inlined file: juce_ThreadPool.cpp *********/
  12523. BEGIN_JUCE_NAMESPACE
  12524. ThreadPoolJob::ThreadPoolJob (const String& name)
  12525. : jobName (name),
  12526. pool (0),
  12527. shouldStop (false),
  12528. isActive (false),
  12529. shouldBeDeleted (false)
  12530. {
  12531. }
  12532. ThreadPoolJob::~ThreadPoolJob()
  12533. {
  12534. // you mustn't delete a job while it's still in a pool! Use ThreadPool::removeJob()
  12535. // to remove it first!
  12536. jassert (pool == 0 || ! pool->contains (this));
  12537. }
  12538. const String ThreadPoolJob::getJobName() const
  12539. {
  12540. return jobName;
  12541. }
  12542. void ThreadPoolJob::setJobName (const String& newName)
  12543. {
  12544. jobName = newName;
  12545. }
  12546. void ThreadPoolJob::signalJobShouldExit()
  12547. {
  12548. shouldStop = true;
  12549. }
  12550. class ThreadPoolThread : public Thread
  12551. {
  12552. ThreadPool& pool;
  12553. bool volatile busy;
  12554. ThreadPoolThread (const ThreadPoolThread&);
  12555. const ThreadPoolThread& operator= (const ThreadPoolThread&);
  12556. public:
  12557. ThreadPoolThread (ThreadPool& pool_)
  12558. : Thread (T("Pool")),
  12559. pool (pool_),
  12560. busy (false)
  12561. {
  12562. }
  12563. ~ThreadPoolThread()
  12564. {
  12565. }
  12566. void run()
  12567. {
  12568. while (! threadShouldExit())
  12569. {
  12570. if (! pool.runNextJob())
  12571. wait (500);
  12572. }
  12573. }
  12574. };
  12575. ThreadPool::ThreadPool (const int numThreads_,
  12576. const bool startThreadsOnlyWhenNeeded,
  12577. const int stopThreadsWhenNotUsedTimeoutMs)
  12578. : numThreads (jmax (1, numThreads_)),
  12579. threadStopTimeout (stopThreadsWhenNotUsedTimeoutMs),
  12580. priority (5)
  12581. {
  12582. jassert (numThreads_ > 0); // not much point having one of these with no threads in it.
  12583. threads = (Thread**) juce_calloc (sizeof (Thread*) * numThreads);
  12584. for (int i = numThreads; --i >= 0;)
  12585. {
  12586. threads[i] = new ThreadPoolThread (*this);
  12587. if (! startThreadsOnlyWhenNeeded)
  12588. threads[i]->startThread (priority);
  12589. }
  12590. }
  12591. ThreadPool::~ThreadPool()
  12592. {
  12593. removeAllJobs (true, 4000);
  12594. int i;
  12595. for (i = numThreads; --i >= 0;)
  12596. threads[i]->signalThreadShouldExit();
  12597. for (i = numThreads; --i >= 0;)
  12598. {
  12599. threads[i]->stopThread (500);
  12600. delete threads[i];
  12601. }
  12602. juce_free (threads);
  12603. }
  12604. void ThreadPool::addJob (ThreadPoolJob* const job)
  12605. {
  12606. jassert (job->pool == 0);
  12607. if (job->pool == 0)
  12608. {
  12609. job->pool = this;
  12610. job->shouldStop = false;
  12611. job->isActive = false;
  12612. lock.enter();
  12613. jobs.add (job);
  12614. int numRunning = 0;
  12615. int i;
  12616. for (i = numThreads; --i >= 0;)
  12617. if (threads[i]->isThreadRunning() && ! threads[i]->threadShouldExit())
  12618. ++numRunning;
  12619. if (numRunning < numThreads)
  12620. {
  12621. bool startedOne = false;
  12622. int n = 1000;
  12623. while (--n >= 0 && ! startedOne)
  12624. {
  12625. for (int i = numThreads; --i >= 0;)
  12626. {
  12627. if (! threads[i]->isThreadRunning())
  12628. {
  12629. threads[i]->startThread (priority);
  12630. startedOne = true;
  12631. }
  12632. }
  12633. if (! startedOne)
  12634. Thread::sleep (5);
  12635. }
  12636. }
  12637. lock.exit();
  12638. for (i = numThreads; --i >= 0;)
  12639. threads[i]->notify();
  12640. }
  12641. }
  12642. int ThreadPool::getNumJobs() const throw()
  12643. {
  12644. return jobs.size();
  12645. }
  12646. ThreadPoolJob* ThreadPool::getJob (const int index) const
  12647. {
  12648. const ScopedLock sl (lock);
  12649. return (ThreadPoolJob*) jobs [index];
  12650. }
  12651. bool ThreadPool::contains (const ThreadPoolJob* const job) const throw()
  12652. {
  12653. const ScopedLock sl (lock);
  12654. return jobs.contains ((void*) job);
  12655. }
  12656. bool ThreadPool::isJobRunning (const ThreadPoolJob* const job) const
  12657. {
  12658. const ScopedLock sl (lock);
  12659. return jobs.contains ((void*) job) && job->isActive;
  12660. }
  12661. bool ThreadPool::waitForJobToFinish (const ThreadPoolJob* const job,
  12662. const int timeOutMs) const
  12663. {
  12664. if (job != 0)
  12665. {
  12666. const uint32 start = Time::getMillisecondCounter();
  12667. while (contains (job))
  12668. {
  12669. if (timeOutMs >= 0 && Time::getMillisecondCounter() >= start + timeOutMs)
  12670. return false;
  12671. Thread::sleep (2);
  12672. }
  12673. }
  12674. return true;
  12675. }
  12676. bool ThreadPool::removeJob (ThreadPoolJob* const job,
  12677. const bool interruptIfRunning,
  12678. const int timeOutMs)
  12679. {
  12680. if (job != 0)
  12681. {
  12682. lock.enter();
  12683. if (jobs.contains (job))
  12684. {
  12685. if (job->isActive)
  12686. {
  12687. if (interruptIfRunning)
  12688. job->signalJobShouldExit();
  12689. lock.exit();
  12690. return waitForJobToFinish (job, timeOutMs);
  12691. }
  12692. else
  12693. {
  12694. jobs.removeValue (job);
  12695. }
  12696. }
  12697. lock.exit();
  12698. }
  12699. return true;
  12700. }
  12701. bool ThreadPool::removeAllJobs (const bool interruptRunningJobs,
  12702. const int timeOutMs,
  12703. const bool deleteInactiveJobs)
  12704. {
  12705. lock.enter();
  12706. for (int i = jobs.size(); --i >= 0;)
  12707. {
  12708. ThreadPoolJob* const job = (ThreadPoolJob*) jobs.getUnchecked(i);
  12709. if (job->isActive)
  12710. {
  12711. if (interruptRunningJobs)
  12712. job->signalJobShouldExit();
  12713. }
  12714. else
  12715. {
  12716. jobs.remove (i);
  12717. if (deleteInactiveJobs)
  12718. delete job;
  12719. }
  12720. }
  12721. lock.exit();
  12722. const uint32 start = Time::getMillisecondCounter();
  12723. while (jobs.size() > 0)
  12724. {
  12725. if (timeOutMs >= 0 && Time::getMillisecondCounter() >= start + timeOutMs)
  12726. return false;
  12727. Thread::sleep (2);
  12728. }
  12729. return true;
  12730. }
  12731. const StringArray ThreadPool::getNamesOfAllJobs (const bool onlyReturnActiveJobs) const
  12732. {
  12733. StringArray s;
  12734. const ScopedLock sl (lock);
  12735. for (int i = 0; i < jobs.size(); ++i)
  12736. {
  12737. const ThreadPoolJob* const job = (const ThreadPoolJob*) jobs.getUnchecked(i);
  12738. if (job->isActive || ! onlyReturnActiveJobs)
  12739. s.add (job->getJobName());
  12740. }
  12741. return s;
  12742. }
  12743. bool ThreadPool::setThreadPriorities (const int newPriority)
  12744. {
  12745. bool ok = true;
  12746. if (priority != newPriority)
  12747. {
  12748. priority = newPriority;
  12749. for (int i = numThreads; --i >= 0;)
  12750. if (! threads[i]->setPriority (newPriority))
  12751. ok = false;
  12752. }
  12753. return ok;
  12754. }
  12755. bool ThreadPool::runNextJob()
  12756. {
  12757. lock.enter();
  12758. ThreadPoolJob* job = 0;
  12759. for (int i = 0; i < jobs.size(); ++i)
  12760. {
  12761. job = (ThreadPoolJob*) jobs [i];
  12762. if (job != 0 && ! (job->isActive || job->shouldStop))
  12763. break;
  12764. job = 0;
  12765. }
  12766. if (job != 0)
  12767. {
  12768. job->isActive = true;
  12769. lock.exit();
  12770. JUCE_TRY
  12771. {
  12772. ThreadPoolJob::JobStatus result = job->runJob();
  12773. lastJobEndTime = Time::getApproximateMillisecondCounter();
  12774. const ScopedLock sl (lock);
  12775. if (jobs.contains (job))
  12776. {
  12777. job->isActive = false;
  12778. if (result != ThreadPoolJob::jobNeedsRunningAgain || job->shouldStop)
  12779. {
  12780. job->pool = 0;
  12781. job->shouldStop = true;
  12782. jobs.removeValue (job);
  12783. if (result == ThreadPoolJob::jobHasFinishedAndShouldBeDeleted)
  12784. delete job;
  12785. }
  12786. else
  12787. {
  12788. // move the job to the end of the queue if it wants another go
  12789. jobs.move (jobs.indexOf (job), -1);
  12790. }
  12791. }
  12792. }
  12793. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  12794. catch (...)
  12795. {
  12796. lock.enter();
  12797. jobs.removeValue (job);
  12798. lock.exit();
  12799. }
  12800. #endif
  12801. }
  12802. else
  12803. {
  12804. lock.exit();
  12805. if (threadStopTimeout > 0
  12806. && Time::getApproximateMillisecondCounter() > lastJobEndTime + threadStopTimeout)
  12807. {
  12808. lock.enter();
  12809. if (jobs.size() == 0)
  12810. {
  12811. for (int i = numThreads; --i >= 0;)
  12812. threads[i]->signalThreadShouldExit();
  12813. }
  12814. lock.exit();
  12815. }
  12816. else
  12817. {
  12818. return false;
  12819. }
  12820. }
  12821. return true;
  12822. }
  12823. END_JUCE_NAMESPACE
  12824. /********* End of inlined file: juce_ThreadPool.cpp *********/
  12825. /********* Start of inlined file: juce_TimeSliceThread.cpp *********/
  12826. BEGIN_JUCE_NAMESPACE
  12827. TimeSliceThread::TimeSliceThread (const String& threadName)
  12828. : Thread (threadName),
  12829. index (0),
  12830. clientBeingCalled (0),
  12831. clientsChanged (false)
  12832. {
  12833. }
  12834. TimeSliceThread::~TimeSliceThread()
  12835. {
  12836. stopThread (2000);
  12837. }
  12838. void TimeSliceThread::addTimeSliceClient (TimeSliceClient* const client)
  12839. {
  12840. const ScopedLock sl (listLock);
  12841. clients.addIfNotAlreadyThere (client);
  12842. clientsChanged = true;
  12843. notify();
  12844. }
  12845. void TimeSliceThread::removeTimeSliceClient (TimeSliceClient* const client)
  12846. {
  12847. const ScopedLock sl1 (listLock);
  12848. clientsChanged = true;
  12849. // if there's a chance we're in the middle of calling this client, we need to
  12850. // also lock the outer lock..
  12851. if (clientBeingCalled == client)
  12852. {
  12853. const ScopedUnlock ul (listLock); // unlock first to get the order right..
  12854. const ScopedLock sl1 (callbackLock);
  12855. const ScopedLock sl2 (listLock);
  12856. clients.removeValue (client);
  12857. }
  12858. else
  12859. {
  12860. clients.removeValue (client);
  12861. }
  12862. }
  12863. int TimeSliceThread::getNumClients() const throw()
  12864. {
  12865. return clients.size();
  12866. }
  12867. TimeSliceClient* TimeSliceThread::getClient (const int index) const throw()
  12868. {
  12869. const ScopedLock sl (listLock);
  12870. return clients [index];
  12871. }
  12872. void TimeSliceThread::run()
  12873. {
  12874. int numCallsSinceBusy = 0;
  12875. while (! threadShouldExit())
  12876. {
  12877. int timeToWait = 500;
  12878. {
  12879. const ScopedLock sl (callbackLock);
  12880. {
  12881. const ScopedLock sl (listLock);
  12882. if (clients.size() > 0)
  12883. {
  12884. index = (index + 1) % clients.size();
  12885. clientBeingCalled = clients [index];
  12886. }
  12887. else
  12888. {
  12889. index = 0;
  12890. clientBeingCalled = 0;
  12891. }
  12892. if (clientsChanged)
  12893. {
  12894. clientsChanged = false;
  12895. numCallsSinceBusy = 0;
  12896. }
  12897. }
  12898. if (clientBeingCalled != 0)
  12899. {
  12900. if (clientBeingCalled->useTimeSlice())
  12901. numCallsSinceBusy = 0;
  12902. else
  12903. ++numCallsSinceBusy;
  12904. if (numCallsSinceBusy >= clients.size())
  12905. timeToWait = 500;
  12906. else if (index == 0)
  12907. timeToWait = 1; // throw in an occasional pause, to stop everything locking up
  12908. else
  12909. timeToWait = 0;
  12910. }
  12911. }
  12912. if (timeToWait > 0)
  12913. wait (timeToWait);
  12914. }
  12915. }
  12916. END_JUCE_NAMESPACE
  12917. /********* End of inlined file: juce_TimeSliceThread.cpp *********/
  12918. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  12919. /********* Start of inlined file: juce_Application.cpp *********/
  12920. #if JUCE_MSVC
  12921. #pragma warning (push)
  12922. #pragma warning (disable: 4245 4514 4100)
  12923. #include <crtdbg.h>
  12924. #pragma warning (pop)
  12925. #endif
  12926. BEGIN_JUCE_NAMESPACE
  12927. void juce_setCurrentThreadName (const String& name) throw();
  12928. static JUCEApplication* appInstance = 0;
  12929. JUCEApplication::JUCEApplication()
  12930. : appReturnValue (0),
  12931. stillInitialising (true)
  12932. {
  12933. }
  12934. JUCEApplication::~JUCEApplication()
  12935. {
  12936. }
  12937. JUCEApplication* JUCEApplication::getInstance() throw()
  12938. {
  12939. return appInstance;
  12940. }
  12941. bool JUCEApplication::isInitialising() const throw()
  12942. {
  12943. return stillInitialising;
  12944. }
  12945. const String JUCEApplication::getApplicationVersion()
  12946. {
  12947. return String::empty;
  12948. }
  12949. bool JUCEApplication::moreThanOneInstanceAllowed()
  12950. {
  12951. return true;
  12952. }
  12953. void JUCEApplication::anotherInstanceStarted (const String&)
  12954. {
  12955. }
  12956. void JUCEApplication::systemRequestedQuit()
  12957. {
  12958. quit();
  12959. }
  12960. void JUCEApplication::quit()
  12961. {
  12962. MessageManager::getInstance()->stopDispatchLoop();
  12963. }
  12964. void JUCEApplication::setApplicationReturnValue (const int newReturnValue) throw()
  12965. {
  12966. appReturnValue = newReturnValue;
  12967. }
  12968. void JUCEApplication::unhandledException (const std::exception*,
  12969. const String&,
  12970. const int)
  12971. {
  12972. jassertfalse
  12973. }
  12974. void JUCEApplication::sendUnhandledException (const std::exception* const e,
  12975. const char* const sourceFile,
  12976. const int lineNumber)
  12977. {
  12978. if (appInstance != 0)
  12979. appInstance->unhandledException (e, sourceFile, lineNumber);
  12980. }
  12981. ApplicationCommandTarget* JUCEApplication::getNextCommandTarget()
  12982. {
  12983. return 0;
  12984. }
  12985. void JUCEApplication::getAllCommands (Array <CommandID>& commands)
  12986. {
  12987. commands.add (StandardApplicationCommandIDs::quit);
  12988. }
  12989. void JUCEApplication::getCommandInfo (const CommandID commandID, ApplicationCommandInfo& result)
  12990. {
  12991. if (commandID == StandardApplicationCommandIDs::quit)
  12992. {
  12993. result.setInfo ("Quit",
  12994. "Quits the application",
  12995. "Application",
  12996. 0);
  12997. result.defaultKeypresses.add (KeyPress (T('q'), ModifierKeys::commandModifier, 0));
  12998. }
  12999. }
  13000. bool JUCEApplication::perform (const InvocationInfo& info)
  13001. {
  13002. if (info.commandID == StandardApplicationCommandIDs::quit)
  13003. {
  13004. systemRequestedQuit();
  13005. return true;
  13006. }
  13007. return false;
  13008. }
  13009. int JUCEApplication::main (String& commandLine, JUCEApplication* const app)
  13010. {
  13011. jassert (appInstance == 0);
  13012. appInstance = app;
  13013. app->commandLineParameters = commandLine.trim();
  13014. commandLine = String::empty;
  13015. initialiseJuce_GUI();
  13016. InterProcessLock* appLock = 0;
  13017. if (! app->moreThanOneInstanceAllowed())
  13018. {
  13019. appLock = new InterProcessLock ("juceAppLock_" + app->getApplicationName());
  13020. if (! appLock->enter(0))
  13021. {
  13022. MessageManager::broadcastMessage (app->getApplicationName() + "/" + app->commandLineParameters);
  13023. delete appInstance;
  13024. appInstance = 0;
  13025. DBG ("Another instance is running - quitting...");
  13026. return 0;
  13027. }
  13028. }
  13029. JUCE_TRY
  13030. {
  13031. juce_setCurrentThreadName ("Juce Message Thread");
  13032. // let the app do its setting-up..
  13033. app->initialise (app->commandLineParameters);
  13034. // register for broadcast new app messages
  13035. MessageManager::getInstance()->registerBroadcastListener (app);
  13036. app->stillInitialising = false;
  13037. // now loop until a quit message is received..
  13038. MessageManager::getInstance()->runDispatchLoop();
  13039. MessageManager::getInstance()->deregisterBroadcastListener (app);
  13040. if (appLock != 0)
  13041. {
  13042. appLock->exit();
  13043. delete appLock;
  13044. }
  13045. }
  13046. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  13047. catch (const std::exception& e)
  13048. {
  13049. app->unhandledException (&e, __FILE__, __LINE__);
  13050. }
  13051. catch (...)
  13052. {
  13053. app->unhandledException (0, __FILE__, __LINE__);
  13054. }
  13055. #endif
  13056. return shutdownAppAndClearUp();
  13057. }
  13058. int JUCEApplication::shutdownAppAndClearUp()
  13059. {
  13060. jassert (appInstance != 0);
  13061. JUCEApplication* const app = appInstance;
  13062. int returnValue = 0;
  13063. static bool reentrancyCheck = false;
  13064. if (! reentrancyCheck)
  13065. {
  13066. reentrancyCheck = true;
  13067. JUCE_TRY
  13068. {
  13069. // give the app a chance to clean up..
  13070. app->shutdown();
  13071. }
  13072. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  13073. catch (const std::exception& e)
  13074. {
  13075. app->unhandledException (&e, __FILE__, __LINE__);
  13076. }
  13077. catch (...)
  13078. {
  13079. app->unhandledException (0, __FILE__, __LINE__);
  13080. }
  13081. #endif
  13082. JUCE_TRY
  13083. {
  13084. shutdownJuce_GUI();
  13085. returnValue = app->getApplicationReturnValue();
  13086. appInstance = 0;
  13087. delete app;
  13088. }
  13089. JUCE_CATCH_ALL_ASSERT
  13090. reentrancyCheck = false;
  13091. }
  13092. return returnValue;
  13093. }
  13094. int JUCEApplication::main (int argc, char* argv[],
  13095. JUCEApplication* const newApp)
  13096. {
  13097. #if JUCE_MAC
  13098. const ScopedAutoReleasePool pool;
  13099. #endif
  13100. String cmd;
  13101. for (int i = 1; i < argc; ++i)
  13102. cmd << String::fromUTF8 ((const uint8*) argv[i]) << T(' ');
  13103. return JUCEApplication::main (cmd, newApp);
  13104. }
  13105. void JUCEApplication::actionListenerCallback (const String& message)
  13106. {
  13107. if (message.startsWith (getApplicationName() + "/"))
  13108. anotherInstanceStarted (message.substring (getApplicationName().length() + 1));
  13109. }
  13110. static bool juceInitialisedGUI = false;
  13111. void JUCE_PUBLIC_FUNCTION initialiseJuce_GUI()
  13112. {
  13113. if (! juceInitialisedGUI)
  13114. {
  13115. #if JUCE_MAC
  13116. const ScopedAutoReleasePool pool;
  13117. #endif
  13118. juceInitialisedGUI = true;
  13119. initialiseJuce_NonGUI();
  13120. MessageManager::getInstance();
  13121. LookAndFeel::setDefaultLookAndFeel (0);
  13122. #if JUCE_WIN32 && JUCE_DEBUG
  13123. // This section is just for catching people who mess up their project settings and
  13124. // turn RTTI off..
  13125. try
  13126. {
  13127. TextButton tb (String::empty);
  13128. Component* c = &tb;
  13129. // Got an exception here? Then TURN ON RTTI in your compiler settings!!
  13130. c = dynamic_cast <Button*> (c);
  13131. }
  13132. catch (...)
  13133. {
  13134. // Ended up here? If so, TURN ON RTTI in your compiler settings!! And if you
  13135. // got as far as this catch statement, then why haven't you got exception catching
  13136. // turned on in the debugger???
  13137. jassertfalse
  13138. }
  13139. #endif
  13140. }
  13141. }
  13142. void JUCE_PUBLIC_FUNCTION shutdownJuce_GUI()
  13143. {
  13144. if (juceInitialisedGUI)
  13145. {
  13146. #if JUCE_MAC
  13147. const ScopedAutoReleasePool pool;
  13148. #endif
  13149. {
  13150. DeletedAtShutdown::deleteAll();
  13151. LookAndFeel::clearDefaultLookAndFeel();
  13152. }
  13153. delete MessageManager::getInstance();
  13154. shutdownJuce_NonGUI();
  13155. juceInitialisedGUI = false;
  13156. }
  13157. }
  13158. END_JUCE_NAMESPACE
  13159. /********* End of inlined file: juce_Application.cpp *********/
  13160. /********* Start of inlined file: juce_ApplicationCommandInfo.cpp *********/
  13161. BEGIN_JUCE_NAMESPACE
  13162. ApplicationCommandInfo::ApplicationCommandInfo (const CommandID commandID_) throw()
  13163. : commandID (commandID_),
  13164. flags (0)
  13165. {
  13166. }
  13167. void ApplicationCommandInfo::setInfo (const String& shortName_,
  13168. const String& description_,
  13169. const String& categoryName_,
  13170. const int flags_) throw()
  13171. {
  13172. shortName = shortName_;
  13173. description = description_;
  13174. categoryName = categoryName_;
  13175. flags = flags_;
  13176. }
  13177. void ApplicationCommandInfo::setActive (const bool b) throw()
  13178. {
  13179. if (b)
  13180. flags &= ~isDisabled;
  13181. else
  13182. flags |= isDisabled;
  13183. }
  13184. void ApplicationCommandInfo::setTicked (const bool b) throw()
  13185. {
  13186. if (b)
  13187. flags |= isTicked;
  13188. else
  13189. flags &= ~isTicked;
  13190. }
  13191. void ApplicationCommandInfo::addDefaultKeypress (const int keyCode, const ModifierKeys& modifiers) throw()
  13192. {
  13193. defaultKeypresses.add (KeyPress (keyCode, modifiers, 0));
  13194. }
  13195. END_JUCE_NAMESPACE
  13196. /********* End of inlined file: juce_ApplicationCommandInfo.cpp *********/
  13197. /********* Start of inlined file: juce_ApplicationCommandManager.cpp *********/
  13198. BEGIN_JUCE_NAMESPACE
  13199. ApplicationCommandManager::ApplicationCommandManager()
  13200. : listeners (8),
  13201. firstTarget (0)
  13202. {
  13203. keyMappings = new KeyPressMappingSet (this);
  13204. Desktop::getInstance().addFocusChangeListener (this);
  13205. }
  13206. ApplicationCommandManager::~ApplicationCommandManager()
  13207. {
  13208. Desktop::getInstance().removeFocusChangeListener (this);
  13209. deleteAndZero (keyMappings);
  13210. }
  13211. void ApplicationCommandManager::clearCommands()
  13212. {
  13213. commands.clear();
  13214. keyMappings->clearAllKeyPresses();
  13215. triggerAsyncUpdate();
  13216. }
  13217. void ApplicationCommandManager::registerCommand (const ApplicationCommandInfo& newCommand)
  13218. {
  13219. // zero isn't a valid command ID!
  13220. jassert (newCommand.commandID != 0);
  13221. // the name isn't optional!
  13222. jassert (newCommand.shortName.isNotEmpty());
  13223. if (getCommandForID (newCommand.commandID) == 0)
  13224. {
  13225. ApplicationCommandInfo* const newInfo = new ApplicationCommandInfo (newCommand);
  13226. newInfo->flags &= ~ApplicationCommandInfo::isTicked;
  13227. commands.add (newInfo);
  13228. keyMappings->resetToDefaultMapping (newCommand.commandID);
  13229. triggerAsyncUpdate();
  13230. }
  13231. else
  13232. {
  13233. // trying to re-register the same command with different parameters?
  13234. jassert (newCommand.shortName == getCommandForID (newCommand.commandID)->shortName
  13235. && (newCommand.description == getCommandForID (newCommand.commandID)->description || newCommand.description.isEmpty())
  13236. && newCommand.categoryName == getCommandForID (newCommand.commandID)->categoryName
  13237. && newCommand.defaultKeypresses == getCommandForID (newCommand.commandID)->defaultKeypresses
  13238. && (newCommand.flags & (ApplicationCommandInfo::wantsKeyUpDownCallbacks | ApplicationCommandInfo::hiddenFromKeyEditor | ApplicationCommandInfo::readOnlyInKeyEditor))
  13239. == (getCommandForID (newCommand.commandID)->flags & (ApplicationCommandInfo::wantsKeyUpDownCallbacks | ApplicationCommandInfo::hiddenFromKeyEditor | ApplicationCommandInfo::readOnlyInKeyEditor)));
  13240. }
  13241. }
  13242. void ApplicationCommandManager::registerAllCommandsForTarget (ApplicationCommandTarget* target)
  13243. {
  13244. if (target != 0)
  13245. {
  13246. Array <CommandID> commandIDs;
  13247. target->getAllCommands (commandIDs);
  13248. for (int i = 0; i < commandIDs.size(); ++i)
  13249. {
  13250. ApplicationCommandInfo info (commandIDs.getUnchecked(i));
  13251. target->getCommandInfo (info.commandID, info);
  13252. registerCommand (info);
  13253. }
  13254. }
  13255. }
  13256. void ApplicationCommandManager::removeCommand (const CommandID commandID)
  13257. {
  13258. for (int i = commands.size(); --i >= 0;)
  13259. {
  13260. if (commands.getUnchecked (i)->commandID == commandID)
  13261. {
  13262. commands.remove (i);
  13263. triggerAsyncUpdate();
  13264. const Array <KeyPress> keys (keyMappings->getKeyPressesAssignedToCommand (commandID));
  13265. for (int j = keys.size(); --j >= 0;)
  13266. keyMappings->removeKeyPress (keys.getReference (j));
  13267. }
  13268. }
  13269. }
  13270. void ApplicationCommandManager::commandStatusChanged()
  13271. {
  13272. triggerAsyncUpdate();
  13273. }
  13274. const ApplicationCommandInfo* ApplicationCommandManager::getCommandForID (const CommandID commandID) const throw()
  13275. {
  13276. for (int i = commands.size(); --i >= 0;)
  13277. if (commands.getUnchecked(i)->commandID == commandID)
  13278. return commands.getUnchecked(i);
  13279. return 0;
  13280. }
  13281. const String ApplicationCommandManager::getNameOfCommand (const CommandID commandID) const throw()
  13282. {
  13283. const ApplicationCommandInfo* const ci = getCommandForID (commandID);
  13284. return (ci != 0) ? ci->shortName : String::empty;
  13285. }
  13286. const String ApplicationCommandManager::getDescriptionOfCommand (const CommandID commandID) const throw()
  13287. {
  13288. const ApplicationCommandInfo* const ci = getCommandForID (commandID);
  13289. return (ci != 0) ? (ci->description.isNotEmpty() ? ci->description : ci->shortName)
  13290. : String::empty;
  13291. }
  13292. const StringArray ApplicationCommandManager::getCommandCategories() const throw()
  13293. {
  13294. StringArray s;
  13295. for (int i = 0; i < commands.size(); ++i)
  13296. s.addIfNotAlreadyThere (commands.getUnchecked(i)->categoryName, false);
  13297. return s;
  13298. }
  13299. const Array <CommandID> ApplicationCommandManager::getCommandsInCategory (const String& categoryName) const throw()
  13300. {
  13301. Array <CommandID> results (4);
  13302. for (int i = 0; i < commands.size(); ++i)
  13303. if (commands.getUnchecked(i)->categoryName == categoryName)
  13304. results.add (commands.getUnchecked(i)->commandID);
  13305. return results;
  13306. }
  13307. bool ApplicationCommandManager::invokeDirectly (const CommandID commandID, const bool asynchronously)
  13308. {
  13309. ApplicationCommandTarget::InvocationInfo info (commandID);
  13310. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::direct;
  13311. return invoke (info, asynchronously);
  13312. }
  13313. bool ApplicationCommandManager::invoke (const ApplicationCommandTarget::InvocationInfo& info_, const bool asynchronously)
  13314. {
  13315. // This call isn't thread-safe for use from a non-UI thread without locking the message
  13316. // manager first..
  13317. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  13318. ApplicationCommandTarget* const target = getFirstCommandTarget (info_.commandID);
  13319. if (target == 0)
  13320. return false;
  13321. ApplicationCommandInfo commandInfo (0);
  13322. target->getCommandInfo (info_.commandID, commandInfo);
  13323. ApplicationCommandTarget::InvocationInfo info (info_);
  13324. info.commandFlags = commandInfo.flags;
  13325. sendListenerInvokeCallback (info);
  13326. const bool ok = target->invoke (info, asynchronously);
  13327. commandStatusChanged();
  13328. return ok;
  13329. }
  13330. ApplicationCommandTarget* ApplicationCommandManager::getFirstCommandTarget (const CommandID)
  13331. {
  13332. return firstTarget != 0 ? firstTarget
  13333. : findDefaultComponentTarget();
  13334. }
  13335. void ApplicationCommandManager::setFirstCommandTarget (ApplicationCommandTarget* const newTarget) throw()
  13336. {
  13337. firstTarget = newTarget;
  13338. }
  13339. ApplicationCommandTarget* ApplicationCommandManager::getTargetForCommand (const CommandID commandID,
  13340. ApplicationCommandInfo& upToDateInfo)
  13341. {
  13342. ApplicationCommandTarget* target = getFirstCommandTarget (commandID);
  13343. if (target == 0)
  13344. target = JUCEApplication::getInstance();
  13345. if (target != 0)
  13346. target = target->getTargetForCommand (commandID);
  13347. if (target != 0)
  13348. target->getCommandInfo (commandID, upToDateInfo);
  13349. return target;
  13350. }
  13351. ApplicationCommandTarget* ApplicationCommandManager::findTargetForComponent (Component* c)
  13352. {
  13353. ApplicationCommandTarget* target = dynamic_cast <ApplicationCommandTarget*> (c);
  13354. if (target == 0 && c != 0)
  13355. // (unable to use the syntax findParentComponentOfClass <ApplicationCommandTarget> () because of a VC6 compiler bug)
  13356. target = c->findParentComponentOfClass ((ApplicationCommandTarget*) 0);
  13357. return target;
  13358. }
  13359. ApplicationCommandTarget* ApplicationCommandManager::findDefaultComponentTarget()
  13360. {
  13361. Component* c = Component::getCurrentlyFocusedComponent();
  13362. if (c == 0)
  13363. {
  13364. TopLevelWindow* const activeWindow = TopLevelWindow::getActiveTopLevelWindow();
  13365. if (activeWindow != 0)
  13366. {
  13367. c = activeWindow->getPeer()->getLastFocusedSubcomponent();
  13368. if (c == 0)
  13369. c = activeWindow;
  13370. }
  13371. }
  13372. if (c == 0 && Process::isForegroundProcess())
  13373. {
  13374. // getting a bit desperate now - try all desktop comps..
  13375. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  13376. {
  13377. ApplicationCommandTarget* const target
  13378. = findTargetForComponent (Desktop::getInstance().getComponent (i)
  13379. ->getPeer()->getLastFocusedSubcomponent());
  13380. if (target != 0)
  13381. return target;
  13382. }
  13383. }
  13384. if (c != 0)
  13385. {
  13386. ResizableWindow* const resizableWindow = dynamic_cast <ResizableWindow*> (c);
  13387. // if we're focused on a ResizableWindow, chances are that it's the content
  13388. // component that really should get the event. And if not, the event will
  13389. // still be passed up to the top level window anyway, so let's send it to the
  13390. // content comp.
  13391. if (resizableWindow != 0 && resizableWindow->getContentComponent() != 0)
  13392. c = resizableWindow->getContentComponent();
  13393. ApplicationCommandTarget* const target = findTargetForComponent (c);
  13394. if (target != 0)
  13395. return target;
  13396. }
  13397. return JUCEApplication::getInstance();
  13398. }
  13399. void ApplicationCommandManager::addListener (ApplicationCommandManagerListener* const listener) throw()
  13400. {
  13401. jassert (listener != 0);
  13402. if (listener != 0)
  13403. listeners.add (listener);
  13404. }
  13405. void ApplicationCommandManager::removeListener (ApplicationCommandManagerListener* const listener) throw()
  13406. {
  13407. listeners.removeValue (listener);
  13408. }
  13409. void ApplicationCommandManager::sendListenerInvokeCallback (const ApplicationCommandTarget::InvocationInfo& info) const
  13410. {
  13411. for (int i = listeners.size(); --i >= 0;)
  13412. {
  13413. ((ApplicationCommandManagerListener*) listeners.getUnchecked (i))->applicationCommandInvoked (info);
  13414. i = jmin (i, listeners.size());
  13415. }
  13416. }
  13417. void ApplicationCommandManager::handleAsyncUpdate()
  13418. {
  13419. for (int i = listeners.size(); --i >= 0;)
  13420. {
  13421. ((ApplicationCommandManagerListener*) listeners.getUnchecked (i))->applicationCommandListChanged();
  13422. i = jmin (i, listeners.size());
  13423. }
  13424. }
  13425. void ApplicationCommandManager::globalFocusChanged (Component*)
  13426. {
  13427. commandStatusChanged();
  13428. }
  13429. END_JUCE_NAMESPACE
  13430. /********* End of inlined file: juce_ApplicationCommandManager.cpp *********/
  13431. /********* Start of inlined file: juce_ApplicationCommandTarget.cpp *********/
  13432. BEGIN_JUCE_NAMESPACE
  13433. ApplicationCommandTarget::ApplicationCommandTarget()
  13434. : messageInvoker (0)
  13435. {
  13436. }
  13437. ApplicationCommandTarget::~ApplicationCommandTarget()
  13438. {
  13439. deleteAndZero (messageInvoker);
  13440. }
  13441. bool ApplicationCommandTarget::tryToInvoke (const InvocationInfo& info, const bool async)
  13442. {
  13443. if (isCommandActive (info.commandID))
  13444. {
  13445. if (async)
  13446. {
  13447. if (messageInvoker == 0)
  13448. messageInvoker = new CommandTargetMessageInvoker (this);
  13449. messageInvoker->postMessage (new Message (0, 0, 0, new ApplicationCommandTarget::InvocationInfo (info)));
  13450. return true;
  13451. }
  13452. else
  13453. {
  13454. const bool success = perform (info);
  13455. jassert (success); // hmm - your target should have been able to perform this command. If it can't
  13456. // do it at the moment for some reason, it should clear the 'isActive' flag when it
  13457. // returns the command's info.
  13458. return success;
  13459. }
  13460. }
  13461. return false;
  13462. }
  13463. ApplicationCommandTarget* ApplicationCommandTarget::findFirstTargetParentComponent()
  13464. {
  13465. Component* c = dynamic_cast <Component*> (this);
  13466. if (c != 0)
  13467. // (unable to use the syntax findParentComponentOfClass <ApplicationCommandTarget> () because of a VC6 compiler bug)
  13468. return c->findParentComponentOfClass ((ApplicationCommandTarget*) 0);
  13469. return 0;
  13470. }
  13471. ApplicationCommandTarget* ApplicationCommandTarget::getTargetForCommand (const CommandID commandID)
  13472. {
  13473. ApplicationCommandTarget* target = this;
  13474. int depth = 0;
  13475. while (target != 0)
  13476. {
  13477. Array <CommandID> commandIDs;
  13478. target->getAllCommands (commandIDs);
  13479. if (commandIDs.contains (commandID))
  13480. return target;
  13481. target = target->getNextCommandTarget();
  13482. ++depth;
  13483. jassert (depth < 100); // could be a recursive command chain??
  13484. jassert (target != this); // definitely a recursive command chain!
  13485. if (depth > 100 || target == this)
  13486. break;
  13487. }
  13488. if (target == 0)
  13489. {
  13490. target = JUCEApplication::getInstance();
  13491. if (target != 0)
  13492. {
  13493. Array <CommandID> commandIDs;
  13494. target->getAllCommands (commandIDs);
  13495. if (commandIDs.contains (commandID))
  13496. return target;
  13497. }
  13498. }
  13499. return 0;
  13500. }
  13501. bool ApplicationCommandTarget::isCommandActive (const CommandID commandID)
  13502. {
  13503. ApplicationCommandInfo info (commandID);
  13504. info.flags = ApplicationCommandInfo::isDisabled;
  13505. getCommandInfo (commandID, info);
  13506. return (info.flags & ApplicationCommandInfo::isDisabled) == 0;
  13507. }
  13508. bool ApplicationCommandTarget::invoke (const InvocationInfo& info, const bool async)
  13509. {
  13510. ApplicationCommandTarget* target = this;
  13511. int depth = 0;
  13512. while (target != 0)
  13513. {
  13514. if (target->tryToInvoke (info, async))
  13515. return true;
  13516. target = target->getNextCommandTarget();
  13517. ++depth;
  13518. jassert (depth < 100); // could be a recursive command chain??
  13519. jassert (target != this); // definitely a recursive command chain!
  13520. if (depth > 100 || target == this)
  13521. break;
  13522. }
  13523. if (target == 0)
  13524. {
  13525. target = JUCEApplication::getInstance();
  13526. if (target != 0)
  13527. return target->tryToInvoke (info, async);
  13528. }
  13529. return false;
  13530. }
  13531. bool ApplicationCommandTarget::invokeDirectly (const CommandID commandID, const bool asynchronously)
  13532. {
  13533. ApplicationCommandTarget::InvocationInfo info (commandID);
  13534. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::direct;
  13535. return invoke (info, asynchronously);
  13536. }
  13537. ApplicationCommandTarget::InvocationInfo::InvocationInfo (const CommandID commandID_) throw()
  13538. : commandID (commandID_),
  13539. commandFlags (0),
  13540. invocationMethod (direct),
  13541. originatingComponent (0),
  13542. isKeyDown (false),
  13543. millisecsSinceKeyPressed (0)
  13544. {
  13545. }
  13546. ApplicationCommandTarget::CommandTargetMessageInvoker::CommandTargetMessageInvoker (ApplicationCommandTarget* const owner_)
  13547. : owner (owner_)
  13548. {
  13549. }
  13550. ApplicationCommandTarget::CommandTargetMessageInvoker::~CommandTargetMessageInvoker()
  13551. {
  13552. }
  13553. void ApplicationCommandTarget::CommandTargetMessageInvoker::handleMessage (const Message& message)
  13554. {
  13555. InvocationInfo* const info = (InvocationInfo*) message.pointerParameter;
  13556. owner->tryToInvoke (*info, false);
  13557. delete info;
  13558. }
  13559. END_JUCE_NAMESPACE
  13560. /********* End of inlined file: juce_ApplicationCommandTarget.cpp *********/
  13561. /********* Start of inlined file: juce_ApplicationProperties.cpp *********/
  13562. BEGIN_JUCE_NAMESPACE
  13563. juce_ImplementSingleton (ApplicationProperties)
  13564. ApplicationProperties::ApplicationProperties() throw()
  13565. : userProps (0),
  13566. commonProps (0),
  13567. msBeforeSaving (3000),
  13568. options (PropertiesFile::storeAsBinary),
  13569. commonSettingsAreReadOnly (0)
  13570. {
  13571. }
  13572. ApplicationProperties::~ApplicationProperties()
  13573. {
  13574. closeFiles();
  13575. clearSingletonInstance();
  13576. }
  13577. void ApplicationProperties::setStorageParameters (const String& applicationName,
  13578. const String& fileNameSuffix,
  13579. const String& folderName_,
  13580. const int millisecondsBeforeSaving,
  13581. const int propertiesFileOptions) throw()
  13582. {
  13583. appName = applicationName;
  13584. fileSuffix = fileNameSuffix;
  13585. folderName = folderName_;
  13586. msBeforeSaving = millisecondsBeforeSaving;
  13587. options = propertiesFileOptions;
  13588. }
  13589. bool ApplicationProperties::testWriteAccess (const bool testUserSettings,
  13590. const bool testCommonSettings,
  13591. const bool showWarningDialogOnFailure)
  13592. {
  13593. const bool userOk = (! testUserSettings) || getUserSettings()->save();
  13594. const bool commonOk = (! testCommonSettings) || getCommonSettings (false)->save();
  13595. if (! (userOk && commonOk))
  13596. {
  13597. if (showWarningDialogOnFailure)
  13598. {
  13599. String filenames;
  13600. if (userProps != 0 && ! userOk)
  13601. filenames << '\n' << userProps->getFile().getFullPathName();
  13602. if (commonProps != 0 && ! commonOk)
  13603. filenames << '\n' << commonProps->getFile().getFullPathName();
  13604. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  13605. appName + TRANS(" - Unable to save settings"),
  13606. TRANS("An error occurred when trying to save the application's settings file...\n\nIn order to save and restore its settings, ")
  13607. + appName + TRANS(" needs to be able to write to the following files:\n")
  13608. + filenames
  13609. + TRANS("\n\nMake sure that these files aren't read-only, and that the disk isn't full."));
  13610. }
  13611. return false;
  13612. }
  13613. return true;
  13614. }
  13615. void ApplicationProperties::openFiles() throw()
  13616. {
  13617. // You need to call setStorageParameters() before trying to get hold of the
  13618. // properties!
  13619. jassert (appName.isNotEmpty());
  13620. if (appName.isNotEmpty())
  13621. {
  13622. if (userProps == 0)
  13623. userProps = PropertiesFile::createDefaultAppPropertiesFile (appName, fileSuffix, folderName,
  13624. false, msBeforeSaving, options);
  13625. if (commonProps == 0)
  13626. commonProps = PropertiesFile::createDefaultAppPropertiesFile (appName, fileSuffix, folderName,
  13627. true, msBeforeSaving, options);
  13628. userProps->setFallbackPropertySet (commonProps);
  13629. }
  13630. }
  13631. PropertiesFile* ApplicationProperties::getUserSettings() throw()
  13632. {
  13633. if (userProps == 0)
  13634. openFiles();
  13635. return userProps;
  13636. }
  13637. PropertiesFile* ApplicationProperties::getCommonSettings (const bool returnUserPropsIfReadOnly) throw()
  13638. {
  13639. if (commonProps == 0)
  13640. openFiles();
  13641. if (returnUserPropsIfReadOnly)
  13642. {
  13643. if (commonSettingsAreReadOnly == 0)
  13644. commonSettingsAreReadOnly = commonProps->save() ? -1 : 1;
  13645. if (commonSettingsAreReadOnly > 0)
  13646. return userProps;
  13647. }
  13648. return commonProps;
  13649. }
  13650. bool ApplicationProperties::saveIfNeeded()
  13651. {
  13652. return (userProps == 0 || userProps->saveIfNeeded())
  13653. && (commonProps == 0 || commonProps->saveIfNeeded());
  13654. }
  13655. void ApplicationProperties::closeFiles()
  13656. {
  13657. deleteAndZero (userProps);
  13658. deleteAndZero (commonProps);
  13659. }
  13660. END_JUCE_NAMESPACE
  13661. /********* End of inlined file: juce_ApplicationProperties.cpp *********/
  13662. /********* Start of inlined file: juce_DeletedAtShutdown.cpp *********/
  13663. BEGIN_JUCE_NAMESPACE
  13664. static VoidArray objectsToDelete (16);
  13665. static CriticalSection lock;
  13666. DeletedAtShutdown::DeletedAtShutdown() throw()
  13667. {
  13668. const ScopedLock sl (lock);
  13669. objectsToDelete.add (this);
  13670. }
  13671. DeletedAtShutdown::~DeletedAtShutdown()
  13672. {
  13673. const ScopedLock sl (lock);
  13674. objectsToDelete.removeValue (this);
  13675. }
  13676. void DeletedAtShutdown::deleteAll()
  13677. {
  13678. // make a local copy of the array, so it can't get into a loop if something
  13679. // creates another DeletedAtShutdown object during its destructor.
  13680. lock.enter();
  13681. const VoidArray localCopy (objectsToDelete);
  13682. lock.exit();
  13683. for (int i = localCopy.size(); --i >= 0;)
  13684. {
  13685. JUCE_TRY
  13686. {
  13687. DeletedAtShutdown* const deletee = (DeletedAtShutdown*) localCopy.getUnchecked(i);
  13688. // double-check that it's not already been deleted during another object's destructor.
  13689. lock.enter();
  13690. const bool okToDelete = objectsToDelete.contains (deletee);
  13691. lock.exit();
  13692. if (okToDelete)
  13693. delete deletee;
  13694. }
  13695. JUCE_CATCH_EXCEPTION
  13696. }
  13697. // if no objects got re-created during shutdown, this should have been emptied by their
  13698. // destructors
  13699. jassert (objectsToDelete.size() == 0);
  13700. objectsToDelete.clear(); // just to make sure the array doesn't have any memory still allocated
  13701. }
  13702. END_JUCE_NAMESPACE
  13703. /********* End of inlined file: juce_DeletedAtShutdown.cpp *********/
  13704. /********* Start of inlined file: juce_PropertiesFile.cpp *********/
  13705. BEGIN_JUCE_NAMESPACE
  13706. static const int propFileMagicNumber = ((int) littleEndianInt ("PROP"));
  13707. static const int propFileMagicNumberCompressed = ((int) littleEndianInt ("CPRP"));
  13708. static const tchar* const propertyFileXmlTag = T("PROPERTIES");
  13709. static const tchar* const propertyTagName = T("VALUE");
  13710. PropertiesFile::PropertiesFile (const File& f,
  13711. const int millisecondsBeforeSaving,
  13712. const int options_) throw()
  13713. : PropertySet (ignoreCaseOfKeyNames),
  13714. file (f),
  13715. timerInterval (millisecondsBeforeSaving),
  13716. options (options_),
  13717. needsWriting (false)
  13718. {
  13719. // You need to correctly specify just one storage format for the file
  13720. jassert ((options_ & (storeAsBinary | storeAsCompressedBinary | storeAsXML)) == storeAsBinary
  13721. || (options_ & (storeAsBinary | storeAsCompressedBinary | storeAsXML)) == storeAsCompressedBinary
  13722. || (options_ & (storeAsBinary | storeAsCompressedBinary | storeAsXML)) == storeAsXML);
  13723. InputStream* fileStream = f.createInputStream();
  13724. if (fileStream != 0)
  13725. {
  13726. int magicNumber = fileStream->readInt();
  13727. if (magicNumber == propFileMagicNumberCompressed)
  13728. {
  13729. fileStream = new SubregionStream (fileStream, 4, -1, true);
  13730. fileStream = new GZIPDecompressorInputStream (fileStream, true);
  13731. magicNumber = propFileMagicNumber;
  13732. }
  13733. if (magicNumber == propFileMagicNumber)
  13734. {
  13735. BufferedInputStream in (fileStream, 2048, true);
  13736. int numValues = in.readInt();
  13737. while (--numValues >= 0 && ! in.isExhausted())
  13738. {
  13739. const String key (in.readString());
  13740. const String value (in.readString());
  13741. jassert (key.isNotEmpty());
  13742. if (key.isNotEmpty())
  13743. getAllProperties().set (key, value);
  13744. }
  13745. }
  13746. else
  13747. {
  13748. // Not a binary props file - let's see if it's XML..
  13749. delete fileStream;
  13750. XmlDocument parser (f);
  13751. XmlElement* doc = parser.getDocumentElement (true);
  13752. if (doc != 0 && doc->hasTagName (propertyFileXmlTag))
  13753. {
  13754. delete doc;
  13755. doc = parser.getDocumentElement();
  13756. if (doc != 0)
  13757. {
  13758. forEachXmlChildElementWithTagName (*doc, e, propertyTagName)
  13759. {
  13760. const String name (e->getStringAttribute (T("name")));
  13761. if (name.isNotEmpty())
  13762. {
  13763. getAllProperties().set (name,
  13764. e->getFirstChildElement() != 0
  13765. ? e->getFirstChildElement()->createDocument (String::empty, true)
  13766. : e->getStringAttribute (T("val")));
  13767. }
  13768. }
  13769. }
  13770. else
  13771. {
  13772. // must be a pretty broken XML file we're trying to parse here!
  13773. jassertfalse
  13774. }
  13775. delete doc;
  13776. }
  13777. }
  13778. }
  13779. }
  13780. PropertiesFile::~PropertiesFile()
  13781. {
  13782. saveIfNeeded();
  13783. }
  13784. bool PropertiesFile::saveIfNeeded()
  13785. {
  13786. const ScopedLock sl (getLock());
  13787. return (! needsWriting) || save();
  13788. }
  13789. bool PropertiesFile::needsToBeSaved() const throw()
  13790. {
  13791. const ScopedLock sl (getLock());
  13792. return needsWriting;
  13793. }
  13794. bool PropertiesFile::save()
  13795. {
  13796. const ScopedLock sl (getLock());
  13797. stopTimer();
  13798. if (file == File::nonexistent
  13799. || file.isDirectory()
  13800. || ! file.getParentDirectory().createDirectory())
  13801. return false;
  13802. if ((options & storeAsXML) != 0)
  13803. {
  13804. XmlElement* const doc = new XmlElement (propertyFileXmlTag);
  13805. for (int i = 0; i < getAllProperties().size(); ++i)
  13806. {
  13807. XmlElement* const e = new XmlElement (propertyTagName);
  13808. e->setAttribute (T("name"), getAllProperties().getAllKeys() [i]);
  13809. // if the value seems to contain xml, store it as such..
  13810. XmlDocument xmlContent (getAllProperties().getAllValues() [i]);
  13811. XmlElement* const childElement = xmlContent.getDocumentElement();
  13812. if (childElement != 0)
  13813. e->addChildElement (childElement);
  13814. else
  13815. e->setAttribute (T("val"), getAllProperties().getAllValues() [i]);
  13816. doc->addChildElement (e);
  13817. }
  13818. const bool ok = doc->writeToFile (file, String::empty);
  13819. delete doc;
  13820. return ok;
  13821. }
  13822. else
  13823. {
  13824. const File tempFile (file.getNonexistentSibling (false));
  13825. OutputStream* out = tempFile.createOutputStream();
  13826. if (out != 0)
  13827. {
  13828. if ((options & storeAsCompressedBinary) != 0)
  13829. {
  13830. out->writeInt (propFileMagicNumberCompressed);
  13831. out->flush();
  13832. out = new GZIPCompressorOutputStream (out, 9, true);
  13833. }
  13834. else
  13835. {
  13836. // have you set up the storage option flags correctly?
  13837. jassert ((options & storeAsBinary) != 0);
  13838. out->writeInt (propFileMagicNumber);
  13839. }
  13840. const int numProperties = getAllProperties().size();
  13841. out->writeInt (numProperties);
  13842. for (int i = 0; i < numProperties; ++i)
  13843. {
  13844. out->writeString (getAllProperties().getAllKeys() [i]);
  13845. out->writeString (getAllProperties().getAllValues() [i]);
  13846. }
  13847. out->flush();
  13848. delete out;
  13849. if (tempFile.moveFileTo (file))
  13850. {
  13851. needsWriting = false;
  13852. return true;
  13853. }
  13854. tempFile.deleteFile();
  13855. }
  13856. }
  13857. return false;
  13858. }
  13859. void PropertiesFile::timerCallback()
  13860. {
  13861. saveIfNeeded();
  13862. }
  13863. void PropertiesFile::propertyChanged()
  13864. {
  13865. sendChangeMessage (this);
  13866. needsWriting = true;
  13867. if (timerInterval > 0)
  13868. startTimer (timerInterval);
  13869. else if (timerInterval == 0)
  13870. saveIfNeeded();
  13871. }
  13872. const File PropertiesFile::getFile() const throw()
  13873. {
  13874. return file;
  13875. }
  13876. const File PropertiesFile::getDefaultAppSettingsFile (const String& applicationName,
  13877. const String& fileNameSuffix,
  13878. const String& folderName,
  13879. const bool commonToAllUsers)
  13880. {
  13881. // mustn't have illegal characters in this name..
  13882. jassert (applicationName == File::createLegalFileName (applicationName));
  13883. #if JUCE_MAC
  13884. File dir (commonToAllUsers ? "/Library/Preferences"
  13885. : "~/Library/Preferences");
  13886. if (folderName.isNotEmpty())
  13887. dir = dir.getChildFile (folderName);
  13888. #endif
  13889. #ifdef JUCE_LINUX
  13890. const File dir ((commonToAllUsers ? T("/var/") : T("~/"))
  13891. + (folderName.isNotEmpty() ? folderName
  13892. : (T(".") + applicationName)));
  13893. #endif
  13894. #if JUCE_WIN32
  13895. File dir (File::getSpecialLocation (commonToAllUsers ? File::commonApplicationDataDirectory
  13896. : File::userApplicationDataDirectory));
  13897. if (dir == File::nonexistent)
  13898. return File::nonexistent;
  13899. dir = dir.getChildFile (folderName.isNotEmpty() ? folderName
  13900. : applicationName);
  13901. #endif
  13902. return dir.getChildFile (applicationName)
  13903. .withFileExtension (fileNameSuffix);
  13904. }
  13905. PropertiesFile* PropertiesFile::createDefaultAppPropertiesFile (const String& applicationName,
  13906. const String& fileNameSuffix,
  13907. const String& folderName,
  13908. const bool commonToAllUsers,
  13909. const int millisecondsBeforeSaving,
  13910. const int propertiesFileOptions)
  13911. {
  13912. const File file (getDefaultAppSettingsFile (applicationName,
  13913. fileNameSuffix,
  13914. folderName,
  13915. commonToAllUsers));
  13916. jassert (file != File::nonexistent);
  13917. if (file == File::nonexistent)
  13918. return 0;
  13919. return new PropertiesFile (file, millisecondsBeforeSaving, propertiesFileOptions);
  13920. }
  13921. END_JUCE_NAMESPACE
  13922. /********* End of inlined file: juce_PropertiesFile.cpp *********/
  13923. /********* Start of inlined file: juce_FileBasedDocument.cpp *********/
  13924. BEGIN_JUCE_NAMESPACE
  13925. FileBasedDocument::FileBasedDocument (const String& fileExtension_,
  13926. const String& fileWildcard_,
  13927. const String& openFileDialogTitle_,
  13928. const String& saveFileDialogTitle_)
  13929. : changedSinceSave (false),
  13930. fileExtension (fileExtension_),
  13931. fileWildcard (fileWildcard_),
  13932. openFileDialogTitle (openFileDialogTitle_),
  13933. saveFileDialogTitle (saveFileDialogTitle_)
  13934. {
  13935. }
  13936. FileBasedDocument::~FileBasedDocument()
  13937. {
  13938. }
  13939. void FileBasedDocument::setChangedFlag (const bool hasChanged)
  13940. {
  13941. changedSinceSave = hasChanged;
  13942. }
  13943. void FileBasedDocument::changed()
  13944. {
  13945. changedSinceSave = true;
  13946. sendChangeMessage (this);
  13947. }
  13948. void FileBasedDocument::setFile (const File& newFile)
  13949. {
  13950. if (documentFile != newFile)
  13951. {
  13952. documentFile = newFile;
  13953. changedSinceSave = true;
  13954. }
  13955. }
  13956. bool FileBasedDocument::loadFrom (const File& newFile,
  13957. const bool showMessageOnFailure)
  13958. {
  13959. MouseCursor::showWaitCursor();
  13960. const File oldFile (documentFile);
  13961. documentFile = newFile;
  13962. String error;
  13963. if (newFile.existsAsFile())
  13964. {
  13965. error = loadDocument (newFile);
  13966. if (error.isEmpty())
  13967. {
  13968. setChangedFlag (false);
  13969. MouseCursor::hideWaitCursor();
  13970. setLastDocumentOpened (newFile);
  13971. return true;
  13972. }
  13973. }
  13974. else
  13975. {
  13976. error = "The file doesn't exist";
  13977. }
  13978. documentFile = oldFile;
  13979. MouseCursor::hideWaitCursor();
  13980. if (showMessageOnFailure)
  13981. {
  13982. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  13983. TRANS("Failed to open file..."),
  13984. TRANS("There was an error while trying to load the file:\n\n")
  13985. + newFile.getFullPathName()
  13986. + T("\n\n")
  13987. + error);
  13988. }
  13989. return false;
  13990. }
  13991. bool FileBasedDocument::loadFromUserSpecifiedFile (const bool showMessageOnFailure)
  13992. {
  13993. FileChooser fc (openFileDialogTitle,
  13994. getLastDocumentOpened(),
  13995. fileWildcard);
  13996. if (fc.browseForFileToOpen())
  13997. return loadFrom (fc.getResult(), showMessageOnFailure);
  13998. return false;
  13999. }
  14000. FileBasedDocument::SaveResult FileBasedDocument::save (const bool askUserForFileIfNotSpecified,
  14001. const bool showMessageOnFailure)
  14002. {
  14003. return saveAs (documentFile,
  14004. false,
  14005. askUserForFileIfNotSpecified,
  14006. showMessageOnFailure);
  14007. }
  14008. FileBasedDocument::SaveResult FileBasedDocument::saveAs (const File& newFile,
  14009. const bool warnAboutOverwritingExistingFiles,
  14010. const bool askUserForFileIfNotSpecified,
  14011. const bool showMessageOnFailure)
  14012. {
  14013. if (newFile == File::nonexistent)
  14014. {
  14015. if (askUserForFileIfNotSpecified)
  14016. {
  14017. return saveAsInteractive (true);
  14018. }
  14019. else
  14020. {
  14021. // can't save to an unspecified file
  14022. jassertfalse
  14023. return failedToWriteToFile;
  14024. }
  14025. }
  14026. if (warnAboutOverwritingExistingFiles && newFile.exists())
  14027. {
  14028. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  14029. TRANS("File already exists"),
  14030. TRANS("There's already a file called:\n\n")
  14031. + newFile.getFullPathName()
  14032. + TRANS("\n\nAre you sure you want to overwrite it?"),
  14033. TRANS("overwrite"),
  14034. TRANS("cancel")))
  14035. {
  14036. return userCancelledSave;
  14037. }
  14038. }
  14039. MouseCursor::showWaitCursor();
  14040. const File oldFile (documentFile);
  14041. documentFile = newFile;
  14042. String error (saveDocument (newFile));
  14043. if (error.isEmpty())
  14044. {
  14045. setChangedFlag (false);
  14046. MouseCursor::hideWaitCursor();
  14047. return savedOk;
  14048. }
  14049. documentFile = oldFile;
  14050. MouseCursor::hideWaitCursor();
  14051. if (showMessageOnFailure)
  14052. {
  14053. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  14054. TRANS("Error writing to file..."),
  14055. TRANS("An error occurred while trying to save \"")
  14056. + getDocumentTitle()
  14057. + TRANS("\" to the file:\n\n")
  14058. + newFile.getFullPathName()
  14059. + T("\n\n")
  14060. + error);
  14061. }
  14062. return failedToWriteToFile;
  14063. }
  14064. FileBasedDocument::SaveResult FileBasedDocument::saveIfNeededAndUserAgrees()
  14065. {
  14066. if (! hasChangedSinceSaved())
  14067. return savedOk;
  14068. const int r = AlertWindow::showYesNoCancelBox (AlertWindow::QuestionIcon,
  14069. TRANS("Closing document..."),
  14070. TRANS("Do you want to save the changes to \"")
  14071. + getDocumentTitle() + T("\"?"),
  14072. TRANS("save"),
  14073. TRANS("discard changes"),
  14074. TRANS("cancel"));
  14075. if (r == 1)
  14076. {
  14077. // save changes
  14078. return save (true, true);
  14079. }
  14080. else if (r == 2)
  14081. {
  14082. // discard changes
  14083. return savedOk;
  14084. }
  14085. return userCancelledSave;
  14086. }
  14087. FileBasedDocument::SaveResult FileBasedDocument::saveAsInteractive (const bool warnAboutOverwritingExistingFiles)
  14088. {
  14089. File f;
  14090. if (documentFile.existsAsFile())
  14091. f = documentFile;
  14092. else
  14093. f = getLastDocumentOpened();
  14094. String legalFilename (File::createLegalFileName (getDocumentTitle()));
  14095. if (legalFilename.isEmpty())
  14096. legalFilename = "unnamed";
  14097. if (f.existsAsFile() || f.getParentDirectory().isDirectory())
  14098. f = f.getSiblingFile (legalFilename);
  14099. else
  14100. f = File::getSpecialLocation (File::userDocumentsDirectory).getChildFile (legalFilename);
  14101. f = f.withFileExtension (fileExtension)
  14102. .getNonexistentSibling (true);
  14103. FileChooser fc (saveFileDialogTitle, f, fileWildcard);
  14104. if (fc.browseForFileToSave (warnAboutOverwritingExistingFiles))
  14105. {
  14106. setLastDocumentOpened (fc.getResult());
  14107. File chosen (fc.getResult());
  14108. if (chosen.getFileExtension().isEmpty())
  14109. chosen = chosen.withFileExtension (fileExtension);
  14110. return saveAs (chosen, false, false, true);
  14111. }
  14112. return userCancelledSave;
  14113. }
  14114. END_JUCE_NAMESPACE
  14115. /********* End of inlined file: juce_FileBasedDocument.cpp *********/
  14116. /********* Start of inlined file: juce_RecentlyOpenedFilesList.cpp *********/
  14117. BEGIN_JUCE_NAMESPACE
  14118. RecentlyOpenedFilesList::RecentlyOpenedFilesList()
  14119. : maxNumberOfItems (10)
  14120. {
  14121. }
  14122. RecentlyOpenedFilesList::~RecentlyOpenedFilesList()
  14123. {
  14124. }
  14125. void RecentlyOpenedFilesList::setMaxNumberOfItems (const int newMaxNumber)
  14126. {
  14127. maxNumberOfItems = jmax (1, newMaxNumber);
  14128. while (getNumFiles() > maxNumberOfItems)
  14129. files.remove (getNumFiles() - 1);
  14130. }
  14131. int RecentlyOpenedFilesList::getNumFiles() const
  14132. {
  14133. return files.size();
  14134. }
  14135. const File RecentlyOpenedFilesList::getFile (const int index) const
  14136. {
  14137. return File (files [index]);
  14138. }
  14139. void RecentlyOpenedFilesList::clear()
  14140. {
  14141. files.clear();
  14142. }
  14143. void RecentlyOpenedFilesList::addFile (const File& file)
  14144. {
  14145. const String path (file.getFullPathName());
  14146. files.removeString (path, true);
  14147. files.insert (0, path);
  14148. setMaxNumberOfItems (maxNumberOfItems);
  14149. }
  14150. void RecentlyOpenedFilesList::removeNonExistentFiles()
  14151. {
  14152. for (int i = getNumFiles(); --i >= 0;)
  14153. if (! getFile(i).exists())
  14154. files.remove (i);
  14155. }
  14156. int RecentlyOpenedFilesList::createPopupMenuItems (PopupMenu& menuToAddTo,
  14157. const int baseItemId,
  14158. const bool showFullPaths,
  14159. const bool dontAddNonExistentFiles,
  14160. const File** filesToAvoid)
  14161. {
  14162. int num = 0;
  14163. for (int i = 0; i < getNumFiles(); ++i)
  14164. {
  14165. const File f (getFile(i));
  14166. if ((! dontAddNonExistentFiles) || f.exists())
  14167. {
  14168. bool needsAvoiding = false;
  14169. if (filesToAvoid != 0)
  14170. {
  14171. const File** files = filesToAvoid;
  14172. while (*files != 0)
  14173. {
  14174. if (f == **files)
  14175. {
  14176. needsAvoiding = true;
  14177. break;
  14178. }
  14179. ++files;
  14180. }
  14181. }
  14182. if (! needsAvoiding)
  14183. {
  14184. menuToAddTo.addItem (baseItemId + i,
  14185. showFullPaths ? f.getFullPathName()
  14186. : f.getFileName());
  14187. ++num;
  14188. }
  14189. }
  14190. }
  14191. return num;
  14192. }
  14193. const String RecentlyOpenedFilesList::toString() const
  14194. {
  14195. return files.joinIntoString (T("\n"));
  14196. }
  14197. void RecentlyOpenedFilesList::restoreFromString (const String& stringifiedVersion)
  14198. {
  14199. clear();
  14200. files.addLines (stringifiedVersion);
  14201. setMaxNumberOfItems (maxNumberOfItems);
  14202. }
  14203. END_JUCE_NAMESPACE
  14204. /********* End of inlined file: juce_RecentlyOpenedFilesList.cpp *********/
  14205. /********* Start of inlined file: juce_UndoManager.cpp *********/
  14206. BEGIN_JUCE_NAMESPACE
  14207. UndoManager::UndoManager (const int maxNumberOfUnitsToKeep,
  14208. const int minimumTransactions)
  14209. : totalUnitsStored (0),
  14210. nextIndex (0),
  14211. newTransaction (true),
  14212. reentrancyCheck (false)
  14213. {
  14214. setMaxNumberOfStoredUnits (maxNumberOfUnitsToKeep,
  14215. minimumTransactions);
  14216. }
  14217. UndoManager::~UndoManager()
  14218. {
  14219. clearUndoHistory();
  14220. }
  14221. void UndoManager::clearUndoHistory()
  14222. {
  14223. transactions.clear();
  14224. transactionNames.clear();
  14225. totalUnitsStored = 0;
  14226. nextIndex = 0;
  14227. sendChangeMessage (this);
  14228. }
  14229. int UndoManager::getNumberOfUnitsTakenUpByStoredCommands() const
  14230. {
  14231. return totalUnitsStored;
  14232. }
  14233. void UndoManager::setMaxNumberOfStoredUnits (const int maxNumberOfUnitsToKeep,
  14234. const int minimumTransactions)
  14235. {
  14236. maxNumUnitsToKeep = jmax (1, maxNumberOfUnitsToKeep);
  14237. minimumTransactionsToKeep = jmax (1, minimumTransactions);
  14238. }
  14239. bool UndoManager::perform (UndoableAction* const command, const String& actionName)
  14240. {
  14241. if (command != 0)
  14242. {
  14243. if (actionName.isNotEmpty())
  14244. currentTransactionName = actionName;
  14245. if (reentrancyCheck)
  14246. {
  14247. jassertfalse // don't call perform() recursively from the UndoableAction::perform() or
  14248. // undo() methods, or else these actions won't actually get done.
  14249. return false;
  14250. }
  14251. else
  14252. {
  14253. bool success = false;
  14254. JUCE_TRY
  14255. {
  14256. success = command->perform();
  14257. }
  14258. JUCE_CATCH_EXCEPTION
  14259. jassert (success);
  14260. if (success)
  14261. {
  14262. if (nextIndex > 0 && ! newTransaction)
  14263. {
  14264. OwnedArray<UndoableAction>* commandSet = transactions [nextIndex - 1];
  14265. jassert (commandSet != 0);
  14266. if (commandSet == 0)
  14267. return false;
  14268. commandSet->add (command);
  14269. }
  14270. else
  14271. {
  14272. OwnedArray<UndoableAction>* commandSet = new OwnedArray<UndoableAction>();
  14273. commandSet->add (command);
  14274. transactions.insert (nextIndex, commandSet);
  14275. transactionNames.insert (nextIndex, currentTransactionName);
  14276. ++nextIndex;
  14277. }
  14278. totalUnitsStored += command->getSizeInUnits();
  14279. newTransaction = false;
  14280. }
  14281. while (nextIndex < transactions.size())
  14282. {
  14283. const OwnedArray <UndoableAction>* const lastSet = transactions.getLast();
  14284. for (int i = lastSet->size(); --i >= 0;)
  14285. totalUnitsStored -= lastSet->getUnchecked (i)->getSizeInUnits();
  14286. transactions.removeLast();
  14287. transactionNames.remove (transactionNames.size() - 1);
  14288. }
  14289. while (nextIndex > 0
  14290. && totalUnitsStored > maxNumUnitsToKeep
  14291. && transactions.size() > minimumTransactionsToKeep)
  14292. {
  14293. const OwnedArray <UndoableAction>* const firstSet = transactions.getFirst();
  14294. for (int i = firstSet->size(); --i >= 0;)
  14295. totalUnitsStored -= firstSet->getUnchecked (i)->getSizeInUnits();
  14296. jassert (totalUnitsStored >= 0); // something fishy going on if this fails!
  14297. transactions.remove (0);
  14298. transactionNames.remove (0);
  14299. --nextIndex;
  14300. }
  14301. sendChangeMessage (this);
  14302. return success;
  14303. }
  14304. }
  14305. return false;
  14306. }
  14307. void UndoManager::beginNewTransaction (const String& actionName)
  14308. {
  14309. newTransaction = true;
  14310. currentTransactionName = actionName;
  14311. }
  14312. void UndoManager::setCurrentTransactionName (const String& newName)
  14313. {
  14314. currentTransactionName = newName;
  14315. }
  14316. bool UndoManager::canUndo() const
  14317. {
  14318. return nextIndex > 0;
  14319. }
  14320. bool UndoManager::canRedo() const
  14321. {
  14322. return nextIndex < transactions.size();
  14323. }
  14324. const String UndoManager::getUndoDescription() const
  14325. {
  14326. return transactionNames [nextIndex - 1];
  14327. }
  14328. const String UndoManager::getRedoDescription() const
  14329. {
  14330. return transactionNames [nextIndex];
  14331. }
  14332. bool UndoManager::undo()
  14333. {
  14334. const OwnedArray<UndoableAction>* const commandSet = transactions [nextIndex - 1];
  14335. if (commandSet == 0)
  14336. return false;
  14337. reentrancyCheck = true;
  14338. bool failed = false;
  14339. for (int i = commandSet->size(); --i >= 0;)
  14340. {
  14341. if (! commandSet->getUnchecked(i)->undo())
  14342. {
  14343. jassertfalse
  14344. failed = true;
  14345. break;
  14346. }
  14347. }
  14348. reentrancyCheck = false;
  14349. if (failed)
  14350. {
  14351. clearUndoHistory();
  14352. }
  14353. else
  14354. {
  14355. --nextIndex;
  14356. }
  14357. beginNewTransaction();
  14358. sendChangeMessage (this);
  14359. return true;
  14360. }
  14361. bool UndoManager::redo()
  14362. {
  14363. const OwnedArray<UndoableAction>* const commandSet = transactions [nextIndex];
  14364. if (commandSet == 0)
  14365. return false;
  14366. reentrancyCheck = true;
  14367. bool failed = false;
  14368. for (int i = 0; i < commandSet->size(); ++i)
  14369. {
  14370. if (! commandSet->getUnchecked(i)->perform())
  14371. {
  14372. jassertfalse
  14373. failed = true;
  14374. break;
  14375. }
  14376. }
  14377. reentrancyCheck = false;
  14378. if (failed)
  14379. {
  14380. clearUndoHistory();
  14381. }
  14382. else
  14383. {
  14384. ++nextIndex;
  14385. }
  14386. beginNewTransaction();
  14387. sendChangeMessage (this);
  14388. return true;
  14389. }
  14390. bool UndoManager::undoCurrentTransactionOnly()
  14391. {
  14392. return newTransaction ? false
  14393. : undo();
  14394. }
  14395. void UndoManager::getActionsInCurrentTransaction (Array <const UndoableAction*>& actionsFound) const
  14396. {
  14397. const OwnedArray <UndoableAction>* const commandSet = transactions [nextIndex - 1];
  14398. if (commandSet != 0 && ! newTransaction)
  14399. {
  14400. for (int i = 0; i < commandSet->size(); ++i)
  14401. actionsFound.add (commandSet->getUnchecked(i));
  14402. }
  14403. }
  14404. END_JUCE_NAMESPACE
  14405. /********* End of inlined file: juce_UndoManager.cpp *********/
  14406. /********* Start of inlined file: juce_AiffAudioFormat.cpp *********/
  14407. BEGIN_JUCE_NAMESPACE
  14408. #undef chunkName
  14409. #define chunkName(a) (int)littleEndianInt(a)
  14410. #define aiffFormatName TRANS("AIFF file")
  14411. static const tchar* const aiffExtensions[] = { T(".aiff"), T(".aif"), 0 };
  14412. class AiffAudioFormatReader : public AudioFormatReader
  14413. {
  14414. public:
  14415. int bytesPerFrame;
  14416. int64 dataChunkStart;
  14417. bool littleEndian;
  14418. AiffAudioFormatReader (InputStream* in)
  14419. : AudioFormatReader (in, aiffFormatName)
  14420. {
  14421. if (input->readInt() == chunkName ("FORM"))
  14422. {
  14423. const int len = input->readIntBigEndian();
  14424. const int64 end = input->getPosition() + len;
  14425. const int nextType = input->readInt();
  14426. if (nextType == chunkName ("AIFF") || nextType == chunkName ("AIFC"))
  14427. {
  14428. bool hasGotVer = false;
  14429. bool hasGotData = false;
  14430. bool hasGotType = false;
  14431. while (input->getPosition() < end)
  14432. {
  14433. const int type = input->readInt();
  14434. const uint32 length = (uint32) input->readIntBigEndian();
  14435. const int64 chunkEnd = input->getPosition() + length;
  14436. if (type == chunkName ("FVER"))
  14437. {
  14438. hasGotVer = true;
  14439. const int ver = input->readIntBigEndian();
  14440. if (ver != 0 && ver != (int)0xa2805140)
  14441. break;
  14442. }
  14443. else if (type == chunkName ("COMM"))
  14444. {
  14445. hasGotType = true;
  14446. numChannels = (unsigned int)input->readShortBigEndian();
  14447. lengthInSamples = input->readIntBigEndian();
  14448. bitsPerSample = input->readShortBigEndian();
  14449. bytesPerFrame = (numChannels * bitsPerSample) >> 3;
  14450. unsigned char sampleRateBytes[10];
  14451. input->read (sampleRateBytes, 10);
  14452. const int byte0 = sampleRateBytes[0];
  14453. if ((byte0 & 0x80) != 0
  14454. || byte0 <= 0x3F || byte0 > 0x40
  14455. || (byte0 == 0x40 && sampleRateBytes[1] > 0x1C))
  14456. break;
  14457. unsigned int sampRate = bigEndianInt ((char*) sampleRateBytes + 2);
  14458. sampRate >>= (16414 - bigEndianShort ((char*) sampleRateBytes));
  14459. sampleRate = (int)sampRate;
  14460. if (length <= 18)
  14461. {
  14462. // some types don't have a chunk large enough to include a compression
  14463. // type, so assume it's just big-endian pcm
  14464. littleEndian = false;
  14465. }
  14466. else
  14467. {
  14468. const int compType = input->readInt();
  14469. if (compType == chunkName ("NONE") || compType == chunkName ("twos"))
  14470. {
  14471. littleEndian = false;
  14472. }
  14473. else if (compType == chunkName ("sowt"))
  14474. {
  14475. littleEndian = true;
  14476. }
  14477. else
  14478. {
  14479. sampleRate = 0;
  14480. break;
  14481. }
  14482. }
  14483. }
  14484. else if (type == chunkName ("SSND"))
  14485. {
  14486. hasGotData = true;
  14487. const int offset = input->readIntBigEndian();
  14488. dataChunkStart = input->getPosition() + 4 + offset;
  14489. lengthInSamples = (bytesPerFrame > 0) ? jmin (lengthInSamples, (int64) (length / bytesPerFrame)) : 0;
  14490. }
  14491. else if ((hasGotVer && hasGotData && hasGotType)
  14492. || chunkEnd < input->getPosition()
  14493. || input->isExhausted())
  14494. {
  14495. break;
  14496. }
  14497. input->setPosition (chunkEnd);
  14498. }
  14499. }
  14500. }
  14501. }
  14502. ~AiffAudioFormatReader()
  14503. {
  14504. }
  14505. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  14506. int64 startSampleInFile, int numSamples)
  14507. {
  14508. const int64 samplesAvailable = lengthInSamples - startSampleInFile;
  14509. if (samplesAvailable < numSamples)
  14510. {
  14511. for (int i = numDestChannels; --i >= 0;)
  14512. if (destSamples[i] != 0)
  14513. zeromem (destSamples[i] + startOffsetInDestBuffer, sizeof (int) * numSamples);
  14514. numSamples = (int) samplesAvailable;
  14515. }
  14516. if (numSamples <= 0)
  14517. return true;
  14518. input->setPosition (dataChunkStart + startSampleInFile * bytesPerFrame);
  14519. const int tempBufSize = 480 * 3 * 4; // (keep this a multiple of 3)
  14520. char tempBuffer [tempBufSize];
  14521. while (numSamples > 0)
  14522. {
  14523. int* left = destSamples[0];
  14524. if (left != 0)
  14525. left += startOffsetInDestBuffer;
  14526. int* right = numDestChannels > 1 ? destSamples[1] : 0;
  14527. if (right != 0)
  14528. right += startOffsetInDestBuffer;
  14529. const int numThisTime = jmin (tempBufSize / bytesPerFrame, numSamples);
  14530. const int bytesRead = input->read (tempBuffer, numThisTime * bytesPerFrame);
  14531. if (bytesRead < numThisTime * bytesPerFrame)
  14532. zeromem (tempBuffer + bytesRead, numThisTime * bytesPerFrame - bytesRead);
  14533. if (bitsPerSample == 16)
  14534. {
  14535. if (littleEndian)
  14536. {
  14537. const short* src = (const short*) tempBuffer;
  14538. if (numChannels > 1)
  14539. {
  14540. if (left == 0)
  14541. {
  14542. for (int i = numThisTime; --i >= 0;)
  14543. {
  14544. *right++ = (int) swapIfBigEndian ((unsigned short) *src++) << 16;
  14545. ++src;
  14546. }
  14547. }
  14548. else if (right == 0)
  14549. {
  14550. for (int i = numThisTime; --i >= 0;)
  14551. {
  14552. ++src;
  14553. *left++ = (int) swapIfBigEndian ((unsigned short) *src++) << 16;
  14554. }
  14555. }
  14556. else
  14557. {
  14558. for (int i = numThisTime; --i >= 0;)
  14559. {
  14560. *left++ = (int) swapIfBigEndian ((unsigned short) *src++) << 16;
  14561. *right++ = (int) swapIfBigEndian ((unsigned short) *src++) << 16;
  14562. }
  14563. }
  14564. }
  14565. else
  14566. {
  14567. for (int i = numThisTime; --i >= 0;)
  14568. {
  14569. *left++ = (int) swapIfBigEndian ((unsigned short) *src++) << 16;
  14570. }
  14571. }
  14572. }
  14573. else
  14574. {
  14575. const char* src = (const char*) tempBuffer;
  14576. if (numChannels > 1)
  14577. {
  14578. if (left == 0)
  14579. {
  14580. for (int i = numThisTime; --i >= 0;)
  14581. {
  14582. *right++ = bigEndianShort (src) << 16;
  14583. src += 4;
  14584. }
  14585. }
  14586. else if (right == 0)
  14587. {
  14588. for (int i = numThisTime; --i >= 0;)
  14589. {
  14590. src += 2;
  14591. *left++ = bigEndianShort (src) << 16;
  14592. src += 2;
  14593. }
  14594. }
  14595. else
  14596. {
  14597. for (int i = numThisTime; --i >= 0;)
  14598. {
  14599. *left++ = bigEndianShort (src) << 16;
  14600. src += 2;
  14601. *right++ = bigEndianShort (src) << 16;
  14602. src += 2;
  14603. }
  14604. }
  14605. }
  14606. else
  14607. {
  14608. for (int i = numThisTime; --i >= 0;)
  14609. {
  14610. *left++ = bigEndianShort (src) << 16;
  14611. src += 2;
  14612. }
  14613. }
  14614. }
  14615. }
  14616. else if (bitsPerSample == 24)
  14617. {
  14618. const char* src = (const char*)tempBuffer;
  14619. if (littleEndian)
  14620. {
  14621. if (numChannels > 1)
  14622. {
  14623. if (left == 0)
  14624. {
  14625. for (int i = numThisTime; --i >= 0;)
  14626. {
  14627. *right++ = littleEndian24Bit (src) << 8;
  14628. src += 6;
  14629. }
  14630. }
  14631. else if (right == 0)
  14632. {
  14633. for (int i = numThisTime; --i >= 0;)
  14634. {
  14635. src += 3;
  14636. *left++ = littleEndian24Bit (src) << 8;
  14637. src += 3;
  14638. }
  14639. }
  14640. else
  14641. {
  14642. for (int i = numThisTime; --i >= 0;)
  14643. {
  14644. *left++ = littleEndian24Bit (src) << 8;
  14645. src += 3;
  14646. *right++ = littleEndian24Bit (src) << 8;
  14647. src += 3;
  14648. }
  14649. }
  14650. }
  14651. else
  14652. {
  14653. for (int i = numThisTime; --i >= 0;)
  14654. {
  14655. *left++ = littleEndian24Bit (src) << 8;
  14656. src += 3;
  14657. }
  14658. }
  14659. }
  14660. else
  14661. {
  14662. if (numChannels > 1)
  14663. {
  14664. if (left == 0)
  14665. {
  14666. for (int i = numThisTime; --i >= 0;)
  14667. {
  14668. *right++ = bigEndian24Bit (src) << 8;
  14669. src += 6;
  14670. }
  14671. }
  14672. else if (right == 0)
  14673. {
  14674. for (int i = numThisTime; --i >= 0;)
  14675. {
  14676. src += 3;
  14677. *left++ = bigEndian24Bit (src) << 8;
  14678. src += 3;
  14679. }
  14680. }
  14681. else
  14682. {
  14683. for (int i = numThisTime; --i >= 0;)
  14684. {
  14685. *left++ = bigEndian24Bit (src) << 8;
  14686. src += 3;
  14687. *right++ = bigEndian24Bit (src) << 8;
  14688. src += 3;
  14689. }
  14690. }
  14691. }
  14692. else
  14693. {
  14694. for (int i = numThisTime; --i >= 0;)
  14695. {
  14696. *left++ = bigEndian24Bit (src) << 8;
  14697. src += 3;
  14698. }
  14699. }
  14700. }
  14701. }
  14702. else if (bitsPerSample == 32)
  14703. {
  14704. const unsigned int* src = (const unsigned int*) tempBuffer;
  14705. unsigned int* l = (unsigned int*) left;
  14706. unsigned int* r = (unsigned int*) right;
  14707. if (littleEndian)
  14708. {
  14709. if (numChannels > 1)
  14710. {
  14711. if (l == 0)
  14712. {
  14713. for (int i = numThisTime; --i >= 0;)
  14714. {
  14715. ++src;
  14716. *r++ = swapIfBigEndian (*src++);
  14717. }
  14718. }
  14719. else if (r == 0)
  14720. {
  14721. for (int i = numThisTime; --i >= 0;)
  14722. {
  14723. *l++ = swapIfBigEndian (*src++);
  14724. ++src;
  14725. }
  14726. }
  14727. else
  14728. {
  14729. for (int i = numThisTime; --i >= 0;)
  14730. {
  14731. *l++ = swapIfBigEndian (*src++);
  14732. *r++ = swapIfBigEndian (*src++);
  14733. }
  14734. }
  14735. }
  14736. else
  14737. {
  14738. for (int i = numThisTime; --i >= 0;)
  14739. {
  14740. *l++ = swapIfBigEndian (*src++);
  14741. }
  14742. }
  14743. }
  14744. else
  14745. {
  14746. if (numChannels > 1)
  14747. {
  14748. if (l == 0)
  14749. {
  14750. for (int i = numThisTime; --i >= 0;)
  14751. {
  14752. ++src;
  14753. *r++ = swapIfLittleEndian (*src++);
  14754. }
  14755. }
  14756. else if (r == 0)
  14757. {
  14758. for (int i = numThisTime; --i >= 0;)
  14759. {
  14760. *l++ = swapIfLittleEndian (*src++);
  14761. ++src;
  14762. }
  14763. }
  14764. else
  14765. {
  14766. for (int i = numThisTime; --i >= 0;)
  14767. {
  14768. *l++ = swapIfLittleEndian (*src++);
  14769. *r++ = swapIfLittleEndian (*src++);
  14770. }
  14771. }
  14772. }
  14773. else
  14774. {
  14775. for (int i = numThisTime; --i >= 0;)
  14776. {
  14777. *l++ = swapIfLittleEndian (*src++);
  14778. }
  14779. }
  14780. }
  14781. left = (int*) l;
  14782. right = (int*) r;
  14783. }
  14784. else if (bitsPerSample == 8)
  14785. {
  14786. const char* src = (const char*) tempBuffer;
  14787. if (numChannels > 1)
  14788. {
  14789. if (left == 0)
  14790. {
  14791. for (int i = numThisTime; --i >= 0;)
  14792. {
  14793. *right++ = ((int) *src++) << 24;
  14794. ++src;
  14795. }
  14796. }
  14797. else if (right == 0)
  14798. {
  14799. for (int i = numThisTime; --i >= 0;)
  14800. {
  14801. ++src;
  14802. *left++ = ((int) *src++) << 24;
  14803. }
  14804. }
  14805. else
  14806. {
  14807. for (int i = numThisTime; --i >= 0;)
  14808. {
  14809. *left++ = ((int) *src++) << 24;
  14810. *right++ = ((int) *src++) << 24;
  14811. }
  14812. }
  14813. }
  14814. else
  14815. {
  14816. for (int i = numThisTime; --i >= 0;)
  14817. {
  14818. *left++ = ((int) *src++) << 24;
  14819. }
  14820. }
  14821. }
  14822. startOffsetInDestBuffer += numThisTime;
  14823. numSamples -= numThisTime;
  14824. }
  14825. if (numSamples > 0)
  14826. {
  14827. for (int i = numDestChannels; --i >= 0;)
  14828. if (destSamples[i] != 0)
  14829. zeromem (destSamples[i] + startOffsetInDestBuffer,
  14830. sizeof (int) * numSamples);
  14831. }
  14832. return true;
  14833. }
  14834. juce_UseDebuggingNewOperator
  14835. private:
  14836. AiffAudioFormatReader (const AiffAudioFormatReader&);
  14837. const AiffAudioFormatReader& operator= (const AiffAudioFormatReader&);
  14838. };
  14839. class AiffAudioFormatWriter : public AudioFormatWriter
  14840. {
  14841. MemoryBlock tempBlock;
  14842. uint32 lengthInSamples, bytesWritten;
  14843. int64 headerPosition;
  14844. bool writeFailed;
  14845. AiffAudioFormatWriter (const AiffAudioFormatWriter&);
  14846. const AiffAudioFormatWriter& operator= (const AiffAudioFormatWriter&);
  14847. void writeHeader()
  14848. {
  14849. const bool couldSeekOk = output->setPosition (headerPosition);
  14850. (void) couldSeekOk;
  14851. // if this fails, you've given it an output stream that can't seek! It needs
  14852. // to be able to seek back to write the header
  14853. jassert (couldSeekOk);
  14854. const int headerLen = 54;
  14855. int audioBytes = lengthInSamples * ((bitsPerSample * numChannels) / 8);
  14856. audioBytes += (audioBytes & 1);
  14857. output->writeInt (chunkName ("FORM"));
  14858. output->writeIntBigEndian (headerLen + audioBytes - 8);
  14859. output->writeInt (chunkName ("AIFF"));
  14860. output->writeInt (chunkName ("COMM"));
  14861. output->writeIntBigEndian (18);
  14862. output->writeShortBigEndian ((short) numChannels);
  14863. output->writeIntBigEndian (lengthInSamples);
  14864. output->writeShortBigEndian ((short) bitsPerSample);
  14865. uint8 sampleRateBytes[10];
  14866. zeromem (sampleRateBytes, 10);
  14867. if (sampleRate <= 1)
  14868. {
  14869. sampleRateBytes[0] = 0x3f;
  14870. sampleRateBytes[1] = 0xff;
  14871. sampleRateBytes[2] = 0x80;
  14872. }
  14873. else
  14874. {
  14875. int mask = 0x40000000;
  14876. sampleRateBytes[0] = 0x40;
  14877. if (sampleRate >= mask)
  14878. {
  14879. jassertfalse
  14880. sampleRateBytes[1] = 0x1d;
  14881. }
  14882. else
  14883. {
  14884. int n = (int) sampleRate;
  14885. int i;
  14886. for (i = 0; i <= 32 ; ++i)
  14887. {
  14888. if ((n & mask) != 0)
  14889. break;
  14890. mask >>= 1;
  14891. }
  14892. n = n << (i + 1);
  14893. sampleRateBytes[1] = (uint8) (29 - i);
  14894. sampleRateBytes[2] = (uint8) ((n >> 24) & 0xff);
  14895. sampleRateBytes[3] = (uint8) ((n >> 16) & 0xff);
  14896. sampleRateBytes[4] = (uint8) ((n >> 8) & 0xff);
  14897. sampleRateBytes[5] = (uint8) (n & 0xff);
  14898. }
  14899. }
  14900. output->write (sampleRateBytes, 10);
  14901. output->writeInt (chunkName ("SSND"));
  14902. output->writeIntBigEndian (audioBytes + 8);
  14903. output->writeInt (0);
  14904. output->writeInt (0);
  14905. jassert (output->getPosition() == headerLen);
  14906. }
  14907. public:
  14908. AiffAudioFormatWriter (OutputStream* out,
  14909. const double sampleRate_,
  14910. const unsigned int chans,
  14911. const int bits)
  14912. : AudioFormatWriter (out,
  14913. aiffFormatName,
  14914. sampleRate_,
  14915. chans,
  14916. bits),
  14917. lengthInSamples (0),
  14918. bytesWritten (0),
  14919. writeFailed (false)
  14920. {
  14921. headerPosition = out->getPosition();
  14922. writeHeader();
  14923. }
  14924. ~AiffAudioFormatWriter()
  14925. {
  14926. if ((bytesWritten & 1) != 0)
  14927. output->writeByte (0);
  14928. writeHeader();
  14929. }
  14930. bool write (const int** data, int numSamples)
  14931. {
  14932. if (writeFailed)
  14933. return false;
  14934. const int bytes = numChannels * numSamples * bitsPerSample / 8;
  14935. tempBlock.ensureSize (bytes, false);
  14936. char* buffer = (char*) tempBlock.getData();
  14937. const int* left = data[0];
  14938. const int* right = data[1];
  14939. if (right == 0)
  14940. right = left;
  14941. if (bitsPerSample == 16)
  14942. {
  14943. short* b = (short*) buffer;
  14944. if (numChannels > 1)
  14945. {
  14946. for (int i = numSamples; --i >= 0;)
  14947. {
  14948. *b++ = (short) swapIfLittleEndian ((unsigned short) (*left++ >> 16));
  14949. *b++ = (short) swapIfLittleEndian ((unsigned short) (*right++ >> 16));
  14950. }
  14951. }
  14952. else
  14953. {
  14954. for (int i = numSamples; --i >= 0;)
  14955. {
  14956. *b++ = (short) swapIfLittleEndian ((unsigned short) (*left++ >> 16));
  14957. }
  14958. }
  14959. }
  14960. else if (bitsPerSample == 24)
  14961. {
  14962. char* b = (char*) buffer;
  14963. if (numChannels > 1)
  14964. {
  14965. for (int i = numSamples; --i >= 0;)
  14966. {
  14967. bigEndian24BitToChars (*left++ >> 8, b);
  14968. b += 3;
  14969. bigEndian24BitToChars (*right++ >> 8, b);
  14970. b += 3;
  14971. }
  14972. }
  14973. else
  14974. {
  14975. for (int i = numSamples; --i >= 0;)
  14976. {
  14977. bigEndian24BitToChars (*left++ >> 8, b);
  14978. b += 3;
  14979. }
  14980. }
  14981. }
  14982. else if (bitsPerSample == 32)
  14983. {
  14984. unsigned int* b = (unsigned int*) buffer;
  14985. if (numChannels > 1)
  14986. {
  14987. for (int i = numSamples; --i >= 0;)
  14988. {
  14989. *b++ = swapIfLittleEndian ((unsigned int) *left++);
  14990. *b++ = swapIfLittleEndian ((unsigned int) *right++);
  14991. }
  14992. }
  14993. else
  14994. {
  14995. for (int i = numSamples; --i >= 0;)
  14996. {
  14997. *b++ = swapIfLittleEndian ((unsigned int) *left++);
  14998. }
  14999. }
  15000. }
  15001. else if (bitsPerSample == 8)
  15002. {
  15003. char* b = (char*)buffer;
  15004. if (numChannels > 1)
  15005. {
  15006. for (int i = numSamples; --i >= 0;)
  15007. {
  15008. *b++ = (char) (*left++ >> 24);
  15009. *b++ = (char) (*right++ >> 24);
  15010. }
  15011. }
  15012. else
  15013. {
  15014. for (int i = numSamples; --i >= 0;)
  15015. {
  15016. *b++ = (char) (*left++ >> 24);
  15017. }
  15018. }
  15019. }
  15020. if (bytesWritten + bytes >= (uint32) 0xfff00000
  15021. || ! output->write (buffer, bytes))
  15022. {
  15023. // failed to write to disk, so let's try writing the header.
  15024. // If it's just run out of disk space, then if it does manage
  15025. // to write the header, we'll still have a useable file..
  15026. writeHeader();
  15027. writeFailed = true;
  15028. return false;
  15029. }
  15030. else
  15031. {
  15032. bytesWritten += bytes;
  15033. lengthInSamples += numSamples;
  15034. return true;
  15035. }
  15036. }
  15037. juce_UseDebuggingNewOperator
  15038. };
  15039. AiffAudioFormat::AiffAudioFormat()
  15040. : AudioFormat (aiffFormatName, (const tchar**) aiffExtensions)
  15041. {
  15042. }
  15043. AiffAudioFormat::~AiffAudioFormat()
  15044. {
  15045. }
  15046. const Array <int> AiffAudioFormat::getPossibleSampleRates()
  15047. {
  15048. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  15049. return Array <int> (rates);
  15050. }
  15051. const Array <int> AiffAudioFormat::getPossibleBitDepths()
  15052. {
  15053. const int depths[] = { 8, 16, 24, 0 };
  15054. return Array <int> (depths);
  15055. }
  15056. bool AiffAudioFormat::canDoStereo()
  15057. {
  15058. return true;
  15059. }
  15060. bool AiffAudioFormat::canDoMono()
  15061. {
  15062. return true;
  15063. }
  15064. #if JUCE_MAC
  15065. bool AiffAudioFormat::canHandleFile (const File& f)
  15066. {
  15067. if (AudioFormat::canHandleFile (f))
  15068. return true;
  15069. const OSType type = PlatformUtilities::getTypeOfFile (f.getFullPathName());
  15070. return type == 'AIFF' || type == 'AIFC'
  15071. || type == 'aiff' || type == 'aifc';
  15072. }
  15073. #endif
  15074. AudioFormatReader* AiffAudioFormat::createReaderFor (InputStream* sourceStream,
  15075. const bool deleteStreamIfOpeningFails)
  15076. {
  15077. AiffAudioFormatReader* w = new AiffAudioFormatReader (sourceStream);
  15078. if (w->sampleRate == 0)
  15079. {
  15080. if (! deleteStreamIfOpeningFails)
  15081. w->input = 0;
  15082. deleteAndZero (w);
  15083. }
  15084. return w;
  15085. }
  15086. AudioFormatWriter* AiffAudioFormat::createWriterFor (OutputStream* out,
  15087. double sampleRate,
  15088. unsigned int chans,
  15089. int bitsPerSample,
  15090. const StringPairArray& /*metadataValues*/,
  15091. int /*qualityOptionIndex*/)
  15092. {
  15093. if (getPossibleBitDepths().contains (bitsPerSample))
  15094. {
  15095. return new AiffAudioFormatWriter (out,
  15096. sampleRate,
  15097. chans,
  15098. bitsPerSample);
  15099. }
  15100. return 0;
  15101. }
  15102. END_JUCE_NAMESPACE
  15103. /********* End of inlined file: juce_AiffAudioFormat.cpp *********/
  15104. /********* Start of inlined file: juce_AudioCDReader.cpp *********/
  15105. BEGIN_JUCE_NAMESPACE
  15106. #if JUCE_MAC
  15107. // Mac version doesn't need any native code because it's all done with files..
  15108. // Windows + Linux versions are in the platform-dependent code sections.
  15109. static void findCDs (OwnedArray<File>& cds)
  15110. {
  15111. File volumes ("/Volumes");
  15112. volumes.findChildFiles (cds, File::findDirectories, false);
  15113. for (int i = cds.size(); --i >= 0;)
  15114. if (! cds[i]->getChildFile (".TOC.plist").exists())
  15115. cds.remove (i);
  15116. }
  15117. const StringArray AudioCDReader::getAvailableCDNames()
  15118. {
  15119. OwnedArray<File> cds;
  15120. findCDs (cds);
  15121. StringArray names;
  15122. for (int i = 0; i < cds.size(); ++i)
  15123. names.add (cds[i]->getFileName());
  15124. return names;
  15125. }
  15126. AudioCDReader* AudioCDReader::createReaderForCD (const int index)
  15127. {
  15128. OwnedArray<File> cds;
  15129. findCDs (cds);
  15130. if (cds[index] != 0)
  15131. return new AudioCDReader (*cds[index]);
  15132. else
  15133. return 0;
  15134. }
  15135. AudioCDReader::AudioCDReader (const File& volume)
  15136. : AudioFormatReader (0, "CD Audio"),
  15137. volumeDir (volume),
  15138. currentReaderTrack (-1),
  15139. reader (0)
  15140. {
  15141. sampleRate = 44100.0;
  15142. bitsPerSample = 16;
  15143. numChannels = 2;
  15144. usesFloatingPointData = false;
  15145. refreshTrackLengths();
  15146. }
  15147. AudioCDReader::~AudioCDReader()
  15148. {
  15149. if (reader != 0)
  15150. delete reader;
  15151. }
  15152. static int getTrackNumber (const File& file)
  15153. {
  15154. return file.getFileName()
  15155. .initialSectionContainingOnly (T("0123456789"))
  15156. .getIntValue();
  15157. }
  15158. int AudioCDReader::compareElements (const File* const first, const File* const second) throw()
  15159. {
  15160. const int firstTrack = getTrackNumber (*first);
  15161. const int secondTrack = getTrackNumber (*second);
  15162. jassert (firstTrack > 0 && secondTrack > 0);
  15163. return firstTrack - secondTrack;
  15164. }
  15165. void AudioCDReader::refreshTrackLengths()
  15166. {
  15167. tracks.clear();
  15168. trackStartSamples.clear();
  15169. volumeDir.findChildFiles (tracks, File::findFiles | File::ignoreHiddenFiles, false, T("*.aiff"));
  15170. tracks.sort (*this);
  15171. AiffAudioFormat format;
  15172. int sample = 0;
  15173. for (int i = 0; i < tracks.size(); ++i)
  15174. {
  15175. trackStartSamples.add (sample);
  15176. FileInputStream* const in = tracks[i]->createInputStream();
  15177. if (in != 0)
  15178. {
  15179. AudioFormatReader* const r = format.createReaderFor (in, true);
  15180. if (r != 0)
  15181. {
  15182. sample += r->lengthInSamples;
  15183. delete r;
  15184. }
  15185. }
  15186. }
  15187. trackStartSamples.add (sample);
  15188. lengthInSamples = sample;
  15189. }
  15190. bool AudioCDReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  15191. int64 startSampleInFile, int numSamples)
  15192. {
  15193. while (numSamples > 0)
  15194. {
  15195. int track = -1;
  15196. for (int i = 0; i < trackStartSamples.size() - 1; ++i)
  15197. {
  15198. if (startSampleInFile < trackStartSamples.getUnchecked (i + 1))
  15199. {
  15200. track = i;
  15201. break;
  15202. }
  15203. }
  15204. if (track < 0)
  15205. return false;
  15206. if (track != currentReaderTrack)
  15207. {
  15208. deleteAndZero (reader);
  15209. if (tracks [track] != 0)
  15210. {
  15211. FileInputStream* const in = tracks [track]->createInputStream();
  15212. if (in != 0)
  15213. {
  15214. BufferedInputStream* const bin = new BufferedInputStream (in, 65536, true);
  15215. AiffAudioFormat format;
  15216. reader = format.createReaderFor (bin, true);
  15217. if (reader == 0)
  15218. currentReaderTrack = -1;
  15219. else
  15220. currentReaderTrack = track;
  15221. }
  15222. }
  15223. }
  15224. if (reader == 0)
  15225. return false;
  15226. const int startPos = (int) (startSampleInFile - trackStartSamples.getUnchecked (track));
  15227. const int numAvailable = (int) jmin ((int64) numSamples, reader->lengthInSamples - startPos);
  15228. reader->readSamples (destSamples, numDestChannels, startOffsetInDestBuffer, startPos, numAvailable);
  15229. numSamples -= numAvailable;
  15230. startSampleInFile += numAvailable;
  15231. }
  15232. return true;
  15233. }
  15234. bool AudioCDReader::isCDStillPresent() const
  15235. {
  15236. return volumeDir.exists();
  15237. }
  15238. int AudioCDReader::getNumTracks() const
  15239. {
  15240. return tracks.size();
  15241. }
  15242. int AudioCDReader::getPositionOfTrackStart (int trackNum) const
  15243. {
  15244. return trackStartSamples [trackNum];
  15245. }
  15246. bool AudioCDReader::isTrackAudio (int trackNum) const
  15247. {
  15248. return tracks [trackNum] != 0;
  15249. }
  15250. void AudioCDReader::enableIndexScanning (bool b)
  15251. {
  15252. // any way to do this on a Mac??
  15253. }
  15254. int AudioCDReader::getLastIndex() const
  15255. {
  15256. return 0;
  15257. }
  15258. const Array <int> AudioCDReader::findIndexesInTrack (const int trackNumber)
  15259. {
  15260. return Array <int>();
  15261. }
  15262. int AudioCDReader::getCDDBId()
  15263. {
  15264. return 0; //xxx
  15265. }
  15266. #endif
  15267. END_JUCE_NAMESPACE
  15268. /********* End of inlined file: juce_AudioCDReader.cpp *********/
  15269. /********* Start of inlined file: juce_AudioFormat.cpp *********/
  15270. BEGIN_JUCE_NAMESPACE
  15271. AudioFormatReader::AudioFormatReader (InputStream* const in,
  15272. const String& formatName_)
  15273. : sampleRate (0),
  15274. bitsPerSample (0),
  15275. lengthInSamples (0),
  15276. numChannels (0),
  15277. usesFloatingPointData (false),
  15278. input (in),
  15279. formatName (formatName_)
  15280. {
  15281. }
  15282. AudioFormatReader::~AudioFormatReader()
  15283. {
  15284. delete input;
  15285. }
  15286. bool AudioFormatReader::read (int** destSamples,
  15287. int numDestChannels,
  15288. int64 startSampleInSource,
  15289. int numSamplesToRead,
  15290. const bool fillLeftoverChannelsWithCopies)
  15291. {
  15292. jassert (numDestChannels > 0); // you have to actually give this some channels to work with!
  15293. int startOffsetInDestBuffer = 0;
  15294. if (startSampleInSource < 0)
  15295. {
  15296. const int silence = (int) jmin (-startSampleInSource, (int64) numSamplesToRead);
  15297. for (int i = numDestChannels; --i >= 0;)
  15298. if (destSamples[i] != 0)
  15299. zeromem (destSamples[i], sizeof (int) * silence);
  15300. startOffsetInDestBuffer += silence;
  15301. numSamplesToRead -= silence;
  15302. startSampleInSource = 0;
  15303. }
  15304. if (numSamplesToRead <= 0)
  15305. return true;
  15306. if (! readSamples (destSamples, jmin (numChannels, numDestChannels), startOffsetInDestBuffer,
  15307. startSampleInSource, numSamplesToRead))
  15308. return false;
  15309. if (numDestChannels > (int) numChannels)
  15310. {
  15311. if (fillLeftoverChannelsWithCopies)
  15312. {
  15313. int* lastFullChannel = destSamples[0];
  15314. for (int i = numDestChannels; --i > 0;)
  15315. {
  15316. if (destSamples[i] != 0)
  15317. {
  15318. lastFullChannel = destSamples[i];
  15319. break;
  15320. }
  15321. }
  15322. if (lastFullChannel != 0)
  15323. for (int i = numChannels; i < numDestChannels; ++i)
  15324. if (destSamples[i] != 0)
  15325. memcpy (destSamples[i], lastFullChannel, sizeof (int) * numSamplesToRead);
  15326. }
  15327. else
  15328. {
  15329. for (int i = numChannels; i < numDestChannels; ++i)
  15330. if (destSamples[i] != 0)
  15331. zeromem (destSamples[i], sizeof (int) * numSamplesToRead);
  15332. }
  15333. }
  15334. return true;
  15335. }
  15336. static void findMaxMin (const float* src, const int num,
  15337. float& maxVal, float& minVal)
  15338. {
  15339. float mn = src[0];
  15340. float mx = mn;
  15341. for (int i = 1; i < num; ++i)
  15342. {
  15343. const float s = src[i];
  15344. if (s > mx)
  15345. mx = s;
  15346. if (s < mn)
  15347. mn = s;
  15348. }
  15349. maxVal = mx;
  15350. minVal = mn;
  15351. }
  15352. void AudioFormatReader::readMaxLevels (int64 startSampleInFile,
  15353. int64 numSamples,
  15354. float& lowestLeft, float& highestLeft,
  15355. float& lowestRight, float& highestRight)
  15356. {
  15357. if (numSamples <= 0)
  15358. {
  15359. lowestLeft = 0;
  15360. lowestRight = 0;
  15361. highestLeft = 0;
  15362. highestRight = 0;
  15363. return;
  15364. }
  15365. const int bufferSize = (int) jmin (numSamples, (int64) 4096);
  15366. MemoryBlock tempSpace (bufferSize * sizeof (int) * 2 + 64);
  15367. int* tempBuffer[3];
  15368. tempBuffer[0] = (int*) tempSpace.getData();
  15369. tempBuffer[1] = ((int*) tempSpace.getData()) + bufferSize;
  15370. tempBuffer[2] = 0;
  15371. if (usesFloatingPointData)
  15372. {
  15373. float lmin = 1.0e6;
  15374. float lmax = -lmin;
  15375. float rmin = lmin;
  15376. float rmax = lmax;
  15377. while (numSamples > 0)
  15378. {
  15379. const int numToDo = (int) jmin (numSamples, (int64) bufferSize);
  15380. read ((int**) tempBuffer, 2, startSampleInFile, numToDo, false);
  15381. numSamples -= numToDo;
  15382. startSampleInFile += numToDo;
  15383. float bufmin, bufmax;
  15384. findMaxMin ((float*) tempBuffer[0], numToDo, bufmax, bufmin);
  15385. lmin = jmin (lmin, bufmin);
  15386. lmax = jmax (lmax, bufmax);
  15387. if (numChannels > 1)
  15388. {
  15389. findMaxMin ((float*) tempBuffer[1], numToDo, bufmax, bufmin);
  15390. rmin = jmin (rmin, bufmin);
  15391. rmax = jmax (rmax, bufmax);
  15392. }
  15393. }
  15394. if (numChannels <= 1)
  15395. {
  15396. rmax = lmax;
  15397. rmin = lmin;
  15398. }
  15399. lowestLeft = lmin;
  15400. highestLeft = lmax;
  15401. lowestRight = rmin;
  15402. highestRight = rmax;
  15403. }
  15404. else
  15405. {
  15406. int lmax = INT_MIN;
  15407. int lmin = INT_MAX;
  15408. int rmax = INT_MIN;
  15409. int rmin = INT_MAX;
  15410. while (numSamples > 0)
  15411. {
  15412. const int numToDo = (int) jmin (numSamples, (int64) bufferSize);
  15413. read ((int**) tempBuffer, 2, startSampleInFile, numToDo, false);
  15414. numSamples -= numToDo;
  15415. startSampleInFile += numToDo;
  15416. for (int j = numChannels; --j >= 0;)
  15417. {
  15418. int bufMax = INT_MIN;
  15419. int bufMin = INT_MAX;
  15420. const int* const b = tempBuffer[j];
  15421. for (int i = 0; i < numToDo; ++i)
  15422. {
  15423. const int samp = b[i];
  15424. if (samp < bufMin)
  15425. bufMin = samp;
  15426. if (samp > bufMax)
  15427. bufMax = samp;
  15428. }
  15429. if (j == 0)
  15430. {
  15431. lmax = jmax (lmax, bufMax);
  15432. lmin = jmin (lmin, bufMin);
  15433. }
  15434. else
  15435. {
  15436. rmax = jmax (rmax, bufMax);
  15437. rmin = jmin (rmin, bufMin);
  15438. }
  15439. }
  15440. }
  15441. if (numChannels <= 1)
  15442. {
  15443. rmax = lmax;
  15444. rmin = lmin;
  15445. }
  15446. lowestLeft = lmin / (float)INT_MAX;
  15447. highestLeft = lmax / (float)INT_MAX;
  15448. lowestRight = rmin / (float)INT_MAX;
  15449. highestRight = rmax / (float)INT_MAX;
  15450. }
  15451. }
  15452. int64 AudioFormatReader::searchForLevel (int64 startSample,
  15453. int64 numSamplesToSearch,
  15454. const double magnitudeRangeMinimum,
  15455. const double magnitudeRangeMaximum,
  15456. const int minimumConsecutiveSamples)
  15457. {
  15458. if (numSamplesToSearch == 0)
  15459. return -1;
  15460. const int bufferSize = 4096;
  15461. MemoryBlock tempSpace (bufferSize * sizeof (int) * 2 + 64);
  15462. int* tempBuffer[3];
  15463. tempBuffer[0] = (int*) tempSpace.getData();
  15464. tempBuffer[1] = ((int*) tempSpace.getData()) + bufferSize;
  15465. tempBuffer[2] = 0;
  15466. int consecutive = 0;
  15467. int64 firstMatchPos = -1;
  15468. jassert (magnitudeRangeMaximum > magnitudeRangeMinimum);
  15469. const double doubleMin = jlimit (0.0, (double) INT_MAX, magnitudeRangeMinimum * INT_MAX);
  15470. const double doubleMax = jlimit (doubleMin, (double) INT_MAX, magnitudeRangeMaximum * INT_MAX);
  15471. const int intMagnitudeRangeMinimum = roundDoubleToInt (doubleMin);
  15472. const int intMagnitudeRangeMaximum = roundDoubleToInt (doubleMax);
  15473. while (numSamplesToSearch != 0)
  15474. {
  15475. const int numThisTime = (int) jmin (abs64 (numSamplesToSearch), (int64) bufferSize);
  15476. int64 bufferStart = startSample;
  15477. if (numSamplesToSearch < 0)
  15478. bufferStart -= numThisTime;
  15479. if (bufferStart >= (int) lengthInSamples)
  15480. break;
  15481. read ((int**) tempBuffer, 2, bufferStart, numThisTime, false);
  15482. int num = numThisTime;
  15483. while (--num >= 0)
  15484. {
  15485. if (numSamplesToSearch < 0)
  15486. --startSample;
  15487. bool matches = false;
  15488. const int index = (int) (startSample - bufferStart);
  15489. if (usesFloatingPointData)
  15490. {
  15491. const float sample1 = fabsf (((float*) tempBuffer[0]) [index]);
  15492. if (sample1 >= magnitudeRangeMinimum
  15493. && sample1 <= magnitudeRangeMaximum)
  15494. {
  15495. matches = true;
  15496. }
  15497. else if (numChannels > 1)
  15498. {
  15499. const float sample2 = fabsf (((float*) tempBuffer[1]) [index]);
  15500. matches = (sample2 >= magnitudeRangeMinimum
  15501. && sample2 <= magnitudeRangeMaximum);
  15502. }
  15503. }
  15504. else
  15505. {
  15506. const int sample1 = abs (tempBuffer[0] [index]);
  15507. if (sample1 >= intMagnitudeRangeMinimum
  15508. && sample1 <= intMagnitudeRangeMaximum)
  15509. {
  15510. matches = true;
  15511. }
  15512. else if (numChannels > 1)
  15513. {
  15514. const int sample2 = abs (tempBuffer[1][index]);
  15515. matches = (sample2 >= intMagnitudeRangeMinimum
  15516. && sample2 <= intMagnitudeRangeMaximum);
  15517. }
  15518. }
  15519. if (matches)
  15520. {
  15521. if (firstMatchPos < 0)
  15522. firstMatchPos = startSample;
  15523. if (++consecutive >= minimumConsecutiveSamples)
  15524. {
  15525. if (firstMatchPos < 0 || firstMatchPos >= lengthInSamples)
  15526. return -1;
  15527. return firstMatchPos;
  15528. }
  15529. }
  15530. else
  15531. {
  15532. consecutive = 0;
  15533. firstMatchPos = -1;
  15534. }
  15535. if (numSamplesToSearch > 0)
  15536. ++startSample;
  15537. }
  15538. if (numSamplesToSearch > 0)
  15539. numSamplesToSearch -= numThisTime;
  15540. else
  15541. numSamplesToSearch += numThisTime;
  15542. }
  15543. return -1;
  15544. }
  15545. AudioFormatWriter::AudioFormatWriter (OutputStream* const out,
  15546. const String& formatName_,
  15547. const double rate,
  15548. const unsigned int numChannels_,
  15549. const unsigned int bitsPerSample_)
  15550. : sampleRate (rate),
  15551. numChannels (numChannels_),
  15552. bitsPerSample (bitsPerSample_),
  15553. usesFloatingPointData (false),
  15554. output (out),
  15555. formatName (formatName_)
  15556. {
  15557. }
  15558. AudioFormatWriter::~AudioFormatWriter()
  15559. {
  15560. delete output;
  15561. }
  15562. bool AudioFormatWriter::writeFromAudioReader (AudioFormatReader& reader,
  15563. int64 startSample,
  15564. int64 numSamplesToRead)
  15565. {
  15566. const int bufferSize = 16384;
  15567. const int maxChans = 128;
  15568. AudioSampleBuffer tempBuffer (reader.numChannels, bufferSize);
  15569. int* buffers [maxChans];
  15570. for (int i = maxChans; --i >= 0;)
  15571. buffers[i] = 0;
  15572. if (numSamplesToRead < 0)
  15573. numSamplesToRead = reader.lengthInSamples;
  15574. while (numSamplesToRead > 0)
  15575. {
  15576. const int numToDo = (int) jmin (numSamplesToRead, (int64) bufferSize);
  15577. for (int i = tempBuffer.getNumChannels(); --i >= 0;)
  15578. buffers[i] = (int*) tempBuffer.getSampleData (i, 0);
  15579. if (! reader.read (buffers, maxChans, startSample, numToDo, false))
  15580. return false;
  15581. if (reader.usesFloatingPointData != isFloatingPoint())
  15582. {
  15583. int** bufferChan = buffers;
  15584. while (*bufferChan != 0)
  15585. {
  15586. int* b = *bufferChan++;
  15587. if (isFloatingPoint())
  15588. {
  15589. // int -> float
  15590. const double factor = 1.0 / INT_MAX;
  15591. for (int i = 0; i < numToDo; ++i)
  15592. ((float*)b)[i] = (float) (factor * b[i]);
  15593. }
  15594. else
  15595. {
  15596. // float -> int
  15597. for (int i = 0; i < numToDo; ++i)
  15598. {
  15599. const double samp = *(const float*) b;
  15600. if (samp <= -1.0)
  15601. *b++ = INT_MIN;
  15602. else if (samp >= 1.0)
  15603. *b++ = INT_MAX;
  15604. else
  15605. *b++ = roundDoubleToInt (INT_MAX * samp);
  15606. }
  15607. }
  15608. }
  15609. }
  15610. if (! write ((const int**) buffers, numToDo))
  15611. return false;
  15612. numSamplesToRead -= numToDo;
  15613. startSample += numToDo;
  15614. }
  15615. return true;
  15616. }
  15617. bool AudioFormatWriter::writeFromAudioSource (AudioSource& source,
  15618. int numSamplesToRead,
  15619. const int samplesPerBlock)
  15620. {
  15621. const int maxChans = 128;
  15622. AudioSampleBuffer tempBuffer (getNumChannels(), samplesPerBlock);
  15623. int* buffers [maxChans];
  15624. while (numSamplesToRead > 0)
  15625. {
  15626. const int numToDo = jmin (numSamplesToRead, samplesPerBlock);
  15627. AudioSourceChannelInfo info;
  15628. info.buffer = &tempBuffer;
  15629. info.startSample = 0;
  15630. info.numSamples = numToDo;
  15631. info.clearActiveBufferRegion();
  15632. source.getNextAudioBlock (info);
  15633. int i;
  15634. for (i = maxChans; --i >= 0;)
  15635. buffers[i] = 0;
  15636. for (i = tempBuffer.getNumChannels(); --i >= 0;)
  15637. buffers[i] = (int*) tempBuffer.getSampleData (i, 0);
  15638. if (! isFloatingPoint())
  15639. {
  15640. int** bufferChan = buffers;
  15641. while (*bufferChan != 0)
  15642. {
  15643. int* b = *bufferChan++;
  15644. // float -> int
  15645. for (int j = numToDo; --j >= 0;)
  15646. {
  15647. const double samp = *(const float*) b;
  15648. if (samp <= -1.0)
  15649. *b++ = INT_MIN;
  15650. else if (samp >= 1.0)
  15651. *b++ = INT_MAX;
  15652. else
  15653. *b++ = roundDoubleToInt (INT_MAX * samp);
  15654. }
  15655. }
  15656. }
  15657. if (! write ((const int**) buffers, numToDo))
  15658. return false;
  15659. numSamplesToRead -= numToDo;
  15660. }
  15661. return true;
  15662. }
  15663. AudioFormat::AudioFormat (const String& name,
  15664. const tchar** const extensions)
  15665. : formatName (name),
  15666. fileExtensions (extensions)
  15667. {
  15668. }
  15669. AudioFormat::~AudioFormat()
  15670. {
  15671. }
  15672. const String& AudioFormat::getFormatName() const
  15673. {
  15674. return formatName;
  15675. }
  15676. const StringArray& AudioFormat::getFileExtensions() const
  15677. {
  15678. return fileExtensions;
  15679. }
  15680. bool AudioFormat::canHandleFile (const File& f)
  15681. {
  15682. for (int i = 0; i < fileExtensions.size(); ++i)
  15683. if (f.hasFileExtension (fileExtensions[i]))
  15684. return true;
  15685. return false;
  15686. }
  15687. bool AudioFormat::isCompressed()
  15688. {
  15689. return false;
  15690. }
  15691. const StringArray AudioFormat::getQualityOptions()
  15692. {
  15693. return StringArray();
  15694. }
  15695. END_JUCE_NAMESPACE
  15696. /********* End of inlined file: juce_AudioFormat.cpp *********/
  15697. /********* Start of inlined file: juce_AudioFormatManager.cpp *********/
  15698. BEGIN_JUCE_NAMESPACE
  15699. AudioFormatManager::AudioFormatManager()
  15700. : knownFormats (4),
  15701. defaultFormatIndex (0)
  15702. {
  15703. }
  15704. AudioFormatManager::~AudioFormatManager()
  15705. {
  15706. clearFormats();
  15707. clearSingletonInstance();
  15708. }
  15709. juce_ImplementSingleton (AudioFormatManager);
  15710. void AudioFormatManager::registerFormat (AudioFormat* newFormat,
  15711. const bool makeThisTheDefaultFormat)
  15712. {
  15713. jassert (newFormat != 0);
  15714. if (newFormat != 0)
  15715. {
  15716. #ifdef JUCE_DEBUG
  15717. for (int i = getNumKnownFormats(); --i >= 0;)
  15718. {
  15719. if (getKnownFormat (i)->getFormatName() == newFormat->getFormatName())
  15720. {
  15721. jassertfalse // trying to add the same format twice!
  15722. }
  15723. }
  15724. #endif
  15725. if (makeThisTheDefaultFormat)
  15726. defaultFormatIndex = knownFormats.size();
  15727. knownFormats.add (newFormat);
  15728. }
  15729. }
  15730. void AudioFormatManager::registerBasicFormats()
  15731. {
  15732. #if JUCE_MAC
  15733. registerFormat (new AiffAudioFormat(), true);
  15734. registerFormat (new WavAudioFormat(), false);
  15735. #else
  15736. registerFormat (new WavAudioFormat(), true);
  15737. registerFormat (new AiffAudioFormat(), false);
  15738. #endif
  15739. #if JUCE_USE_FLAC
  15740. registerFormat (new FlacAudioFormat(), false);
  15741. #endif
  15742. #if JUCE_USE_OGGVORBIS
  15743. registerFormat (new OggVorbisAudioFormat(), false);
  15744. #endif
  15745. }
  15746. void AudioFormatManager::clearFormats()
  15747. {
  15748. for (int i = getNumKnownFormats(); --i >= 0;)
  15749. {
  15750. AudioFormat* const af = getKnownFormat(i);
  15751. delete af;
  15752. }
  15753. knownFormats.clear();
  15754. defaultFormatIndex = 0;
  15755. }
  15756. int AudioFormatManager::getNumKnownFormats() const
  15757. {
  15758. return knownFormats.size();
  15759. }
  15760. AudioFormat* AudioFormatManager::getKnownFormat (const int index) const
  15761. {
  15762. return (AudioFormat*) knownFormats [index];
  15763. }
  15764. AudioFormat* AudioFormatManager::getDefaultFormat() const
  15765. {
  15766. return getKnownFormat (defaultFormatIndex);
  15767. }
  15768. AudioFormat* AudioFormatManager::findFormatForFileExtension (const String& fileExtension) const
  15769. {
  15770. String e (fileExtension);
  15771. if (! e.startsWithChar (T('.')))
  15772. e = T(".") + e;
  15773. for (int i = 0; i < getNumKnownFormats(); ++i)
  15774. if (getKnownFormat(i)->getFileExtensions().contains (e, true))
  15775. return getKnownFormat(i);
  15776. return 0;
  15777. }
  15778. const String AudioFormatManager::getWildcardForAllFormats() const
  15779. {
  15780. StringArray allExtensions;
  15781. int i;
  15782. for (i = 0; i < getNumKnownFormats(); ++i)
  15783. allExtensions.addArray (getKnownFormat (i)->getFileExtensions());
  15784. allExtensions.trim();
  15785. allExtensions.removeEmptyStrings();
  15786. String s;
  15787. for (i = 0; i < allExtensions.size(); ++i)
  15788. {
  15789. s << T('*');
  15790. if (! allExtensions[i].startsWithChar (T('.')))
  15791. s << T('.');
  15792. s << allExtensions[i];
  15793. if (i < allExtensions.size() - 1)
  15794. s << T(';');
  15795. }
  15796. return s;
  15797. }
  15798. AudioFormatReader* AudioFormatManager::createReaderFor (const File& file)
  15799. {
  15800. // you need to actually register some formats before the manager can
  15801. // use them to open a file!
  15802. jassert (knownFormats.size() > 0);
  15803. for (int i = 0; i < getNumKnownFormats(); ++i)
  15804. {
  15805. AudioFormat* const af = getKnownFormat(i);
  15806. if (af->canHandleFile (file))
  15807. {
  15808. InputStream* const in = file.createInputStream();
  15809. if (in != 0)
  15810. {
  15811. AudioFormatReader* const r = af->createReaderFor (in, true);
  15812. if (r != 0)
  15813. return r;
  15814. }
  15815. }
  15816. }
  15817. return 0;
  15818. }
  15819. AudioFormatReader* AudioFormatManager::createReaderFor (InputStream* in)
  15820. {
  15821. // you need to actually register some formats before the manager can
  15822. // use them to open a file!
  15823. jassert (knownFormats.size() > 0);
  15824. if (in != 0)
  15825. {
  15826. const int64 originalStreamPos = in->getPosition();
  15827. for (int i = 0; i < getNumKnownFormats(); ++i)
  15828. {
  15829. AudioFormatReader* const r = getKnownFormat(i)->createReaderFor (in, false);
  15830. if (r != 0)
  15831. return r;
  15832. in->setPosition (originalStreamPos);
  15833. // the stream that is passed-in must be capable of being repositioned so
  15834. // that all the formats can have a go at opening it.
  15835. jassert (in->getPosition() == originalStreamPos);
  15836. }
  15837. delete in;
  15838. }
  15839. return 0;
  15840. }
  15841. END_JUCE_NAMESPACE
  15842. /********* End of inlined file: juce_AudioFormatManager.cpp *********/
  15843. /********* Start of inlined file: juce_AudioSubsectionReader.cpp *********/
  15844. BEGIN_JUCE_NAMESPACE
  15845. AudioSubsectionReader::AudioSubsectionReader (AudioFormatReader* const source_,
  15846. const int64 startSample_,
  15847. const int64 length_,
  15848. const bool deleteSourceWhenDeleted_)
  15849. : AudioFormatReader (0, source_->getFormatName()),
  15850. source (source_),
  15851. startSample (startSample_),
  15852. deleteSourceWhenDeleted (deleteSourceWhenDeleted_)
  15853. {
  15854. length = jmin (jmax ((int64) 0, source->lengthInSamples - startSample), length_);
  15855. sampleRate = source->sampleRate;
  15856. bitsPerSample = source->bitsPerSample;
  15857. lengthInSamples = length;
  15858. numChannels = source->numChannels;
  15859. usesFloatingPointData = source->usesFloatingPointData;
  15860. }
  15861. AudioSubsectionReader::~AudioSubsectionReader()
  15862. {
  15863. if (deleteSourceWhenDeleted)
  15864. delete source;
  15865. }
  15866. bool AudioSubsectionReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  15867. int64 startSampleInFile, int numSamples)
  15868. {
  15869. if (startSampleInFile + numSamples > length)
  15870. {
  15871. for (int i = numDestChannels; --i >= 0;)
  15872. if (destSamples[i] != 0)
  15873. zeromem (destSamples[i], sizeof (int) * numSamples);
  15874. numSamples = jmin (numSamples, (int) (length - startSampleInFile));
  15875. if (numSamples <= 0)
  15876. return true;
  15877. }
  15878. return source->readSamples (destSamples, numDestChannels, startOffsetInDestBuffer,
  15879. startSampleInFile + startSample, numSamples);
  15880. }
  15881. void AudioSubsectionReader::readMaxLevels (int64 startSampleInFile,
  15882. int64 numSamples,
  15883. float& lowestLeft,
  15884. float& highestLeft,
  15885. float& lowestRight,
  15886. float& highestRight)
  15887. {
  15888. startSampleInFile = jmax ((int64) 0, startSampleInFile);
  15889. numSamples = jmax ((int64) 0, jmin (numSamples, length - startSampleInFile));
  15890. source->readMaxLevels (startSampleInFile + startSample,
  15891. numSamples,
  15892. lowestLeft,
  15893. highestLeft,
  15894. lowestRight,
  15895. highestRight);
  15896. }
  15897. END_JUCE_NAMESPACE
  15898. /********* End of inlined file: juce_AudioSubsectionReader.cpp *********/
  15899. /********* Start of inlined file: juce_AudioThumbnail.cpp *********/
  15900. BEGIN_JUCE_NAMESPACE
  15901. const int timeBeforeDeletingReader = 2000;
  15902. struct AudioThumbnailDataFormat
  15903. {
  15904. char thumbnailMagic[4];
  15905. int samplesPerThumbSample;
  15906. int64 totalSamples; // source samples
  15907. int64 numFinishedSamples; // source samples
  15908. int numThumbnailSamples;
  15909. int numChannels;
  15910. int sampleRate;
  15911. char future[16];
  15912. char data[1];
  15913. };
  15914. #if JUCE_BIG_ENDIAN
  15915. static void swap (int& n) { n = (int) swapByteOrder ((uint32) n); }
  15916. static void swap (int64& n) { n = (int64) swapByteOrder ((uint64) n); }
  15917. #endif
  15918. static void swapEndiannessIfNeeded (AudioThumbnailDataFormat* const d)
  15919. {
  15920. (void) d;
  15921. #if JUCE_BIG_ENDIAN
  15922. swap (d->samplesPerThumbSample);
  15923. swap (d->totalSamples);
  15924. swap (d->numFinishedSamples);
  15925. swap (d->numThumbnailSamples);
  15926. swap (d->numChannels);
  15927. swap (d->sampleRate);
  15928. #endif
  15929. }
  15930. AudioThumbnail::AudioThumbnail (const int orginalSamplesPerThumbnailSample_,
  15931. AudioFormatManager& formatManagerToUse_,
  15932. AudioThumbnailCache& cacheToUse)
  15933. : formatManagerToUse (formatManagerToUse_),
  15934. cache (cacheToUse),
  15935. source (0),
  15936. reader (0),
  15937. orginalSamplesPerThumbnailSample (orginalSamplesPerThumbnailSample_)
  15938. {
  15939. clear();
  15940. }
  15941. AudioThumbnail::~AudioThumbnail()
  15942. {
  15943. cache.removeThumbnail (this);
  15944. const ScopedLock sl (readerLock);
  15945. deleteAndZero (reader);
  15946. delete source;
  15947. }
  15948. void AudioThumbnail::setSource (InputSource* const newSource)
  15949. {
  15950. cache.removeThumbnail (this);
  15951. timerCallback(); // stops the timer and deletes the reader
  15952. delete source;
  15953. source = newSource;
  15954. clear();
  15955. if (newSource != 0
  15956. && ! (cache.loadThumb (*this, newSource->hashCode())
  15957. && isFullyLoaded()))
  15958. {
  15959. {
  15960. const ScopedLock sl (readerLock);
  15961. reader = createReader();
  15962. }
  15963. if (reader != 0)
  15964. {
  15965. initialiseFromAudioFile (*reader);
  15966. cache.addThumbnail (this);
  15967. }
  15968. }
  15969. sendChangeMessage (this);
  15970. }
  15971. bool AudioThumbnail::useTimeSlice()
  15972. {
  15973. const ScopedLock sl (readerLock);
  15974. if (isFullyLoaded())
  15975. {
  15976. if (reader != 0)
  15977. startTimer (timeBeforeDeletingReader);
  15978. cache.removeThumbnail (this);
  15979. return false;
  15980. }
  15981. if (reader == 0)
  15982. reader = createReader();
  15983. if (reader != 0)
  15984. {
  15985. readNextBlockFromAudioFile (*reader);
  15986. stopTimer();
  15987. sendChangeMessage (this);
  15988. const bool justFinished = isFullyLoaded();
  15989. if (justFinished)
  15990. cache.storeThumb (*this, source->hashCode());
  15991. return ! justFinished;
  15992. }
  15993. return false;
  15994. }
  15995. AudioFormatReader* AudioThumbnail::createReader() const
  15996. {
  15997. if (source != 0)
  15998. {
  15999. InputStream* const audioFileStream = source->createInputStream();
  16000. if (audioFileStream != 0)
  16001. return formatManagerToUse.createReaderFor (audioFileStream);
  16002. }
  16003. return 0;
  16004. }
  16005. void AudioThumbnail::timerCallback()
  16006. {
  16007. stopTimer();
  16008. const ScopedLock sl (readerLock);
  16009. deleteAndZero (reader);
  16010. }
  16011. void AudioThumbnail::clear()
  16012. {
  16013. data.setSize (sizeof (AudioThumbnailDataFormat) + 3);
  16014. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  16015. d->thumbnailMagic[0] = 'j';
  16016. d->thumbnailMagic[1] = 'a';
  16017. d->thumbnailMagic[2] = 't';
  16018. d->thumbnailMagic[3] = 'm';
  16019. d->samplesPerThumbSample = orginalSamplesPerThumbnailSample;
  16020. d->totalSamples = 0;
  16021. d->numFinishedSamples = 0;
  16022. d->numThumbnailSamples = 0;
  16023. d->numChannels = 0;
  16024. d->sampleRate = 0;
  16025. numSamplesCached = 0;
  16026. cacheNeedsRefilling = true;
  16027. }
  16028. void AudioThumbnail::loadFrom (InputStream& input)
  16029. {
  16030. data.setSize (0);
  16031. input.readIntoMemoryBlock (data);
  16032. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  16033. swapEndiannessIfNeeded (d);
  16034. if (! (d->thumbnailMagic[0] == 'j'
  16035. && d->thumbnailMagic[1] == 'a'
  16036. && d->thumbnailMagic[2] == 't'
  16037. && d->thumbnailMagic[3] == 'm'))
  16038. {
  16039. clear();
  16040. }
  16041. numSamplesCached = 0;
  16042. cacheNeedsRefilling = true;
  16043. }
  16044. void AudioThumbnail::saveTo (OutputStream& output) const
  16045. {
  16046. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  16047. swapEndiannessIfNeeded (d);
  16048. output.write (data.getData(), data.getSize());
  16049. swapEndiannessIfNeeded (d);
  16050. }
  16051. bool AudioThumbnail::initialiseFromAudioFile (AudioFormatReader& reader)
  16052. {
  16053. AudioThumbnailDataFormat* d = (AudioThumbnailDataFormat*) data.getData();
  16054. d->totalSamples = reader.lengthInSamples;
  16055. d->numChannels = jmin (2, reader.numChannels);
  16056. d->numFinishedSamples = 0;
  16057. d->sampleRate = roundDoubleToInt (reader.sampleRate);
  16058. d->numThumbnailSamples = (int) (d->totalSamples / d->samplesPerThumbSample) + 1;
  16059. data.setSize (sizeof (AudioThumbnailDataFormat) + 3 + d->numThumbnailSamples * d->numChannels * 2);
  16060. d = (AudioThumbnailDataFormat*) data.getData();
  16061. zeromem (&(d->data[0]), d->numThumbnailSamples * d->numChannels * 2);
  16062. return d->totalSamples > 0;
  16063. }
  16064. bool AudioThumbnail::readNextBlockFromAudioFile (AudioFormatReader& reader)
  16065. {
  16066. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  16067. if (d->numFinishedSamples < d->totalSamples)
  16068. {
  16069. const int numToDo = (int) jmin ((int64) 65536, d->totalSamples - d->numFinishedSamples);
  16070. generateSection (reader,
  16071. d->numFinishedSamples,
  16072. numToDo);
  16073. d->numFinishedSamples += numToDo;
  16074. }
  16075. cacheNeedsRefilling = true;
  16076. return (d->numFinishedSamples < d->totalSamples);
  16077. }
  16078. int AudioThumbnail::getNumChannels() const throw()
  16079. {
  16080. const AudioThumbnailDataFormat* const d = (const AudioThumbnailDataFormat*) data.getData();
  16081. jassert (d != 0);
  16082. return d->numChannels;
  16083. }
  16084. double AudioThumbnail::getTotalLength() const throw()
  16085. {
  16086. const AudioThumbnailDataFormat* const d = (const AudioThumbnailDataFormat*) data.getData();
  16087. jassert (d != 0);
  16088. if (d->sampleRate > 0)
  16089. return d->totalSamples / (double)d->sampleRate;
  16090. else
  16091. return 0.0;
  16092. }
  16093. void AudioThumbnail::generateSection (AudioFormatReader& reader,
  16094. int64 startSample,
  16095. int numSamples)
  16096. {
  16097. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  16098. jassert (d != 0);
  16099. int firstDataPos = (int) (startSample / d->samplesPerThumbSample);
  16100. int lastDataPos = (int) ((startSample + numSamples) / d->samplesPerThumbSample);
  16101. char* l = getChannelData (0);
  16102. char* r = getChannelData (1);
  16103. for (int i = firstDataPos; i < lastDataPos; ++i)
  16104. {
  16105. const int sourceStart = i * d->samplesPerThumbSample;
  16106. const int sourceEnd = sourceStart + d->samplesPerThumbSample;
  16107. float lowestLeft, highestLeft, lowestRight, highestRight;
  16108. reader.readMaxLevels (sourceStart,
  16109. sourceEnd - sourceStart,
  16110. lowestLeft,
  16111. highestLeft,
  16112. lowestRight,
  16113. highestRight);
  16114. int n = i * 2;
  16115. if (r != 0)
  16116. {
  16117. l [n] = (char) jlimit (-128.0f, 127.0f, lowestLeft * 127.0f);
  16118. r [n++] = (char) jlimit (-128.0f, 127.0f, lowestRight * 127.0f);
  16119. l [n] = (char) jlimit (-128.0f, 127.0f, highestLeft * 127.0f);
  16120. r [n++] = (char) jlimit (-128.0f, 127.0f, highestRight * 127.0f);
  16121. }
  16122. else
  16123. {
  16124. l [n++] = (char) jlimit (-128.0f, 127.0f, lowestLeft * 127.0f);
  16125. l [n++] = (char) jlimit (-128.0f, 127.0f, highestLeft * 127.0f);
  16126. }
  16127. }
  16128. }
  16129. char* AudioThumbnail::getChannelData (int channel) const
  16130. {
  16131. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  16132. jassert (d != 0);
  16133. if (channel >= 0 && channel < d->numChannels)
  16134. return d->data + (channel * 2 * d->numThumbnailSamples);
  16135. return 0;
  16136. }
  16137. bool AudioThumbnail::isFullyLoaded() const throw()
  16138. {
  16139. const AudioThumbnailDataFormat* const d = (const AudioThumbnailDataFormat*) data.getData();
  16140. jassert (d != 0);
  16141. return d->numFinishedSamples >= d->totalSamples;
  16142. }
  16143. void AudioThumbnail::refillCache (const int numSamples,
  16144. double startTime,
  16145. const double timePerPixel)
  16146. {
  16147. const AudioThumbnailDataFormat* const d = (const AudioThumbnailDataFormat*) data.getData();
  16148. jassert (d != 0);
  16149. if (numSamples <= 0
  16150. || timePerPixel <= 0.0
  16151. || d->sampleRate <= 0)
  16152. {
  16153. numSamplesCached = 0;
  16154. cacheNeedsRefilling = true;
  16155. return;
  16156. }
  16157. if (numSamples == numSamplesCached
  16158. && numChannelsCached == d->numChannels
  16159. && startTime == cachedStart
  16160. && timePerPixel == cachedTimePerPixel
  16161. && ! cacheNeedsRefilling)
  16162. {
  16163. return;
  16164. }
  16165. numSamplesCached = numSamples;
  16166. numChannelsCached = d->numChannels;
  16167. cachedStart = startTime;
  16168. cachedTimePerPixel = timePerPixel;
  16169. cachedLevels.ensureSize (2 * numChannelsCached * numSamples);
  16170. const bool needExtraDetail = (timePerPixel * d->sampleRate <= d->samplesPerThumbSample);
  16171. const ScopedLock sl (readerLock);
  16172. cacheNeedsRefilling = false;
  16173. if (needExtraDetail && reader == 0)
  16174. reader = createReader();
  16175. if (reader != 0 && timePerPixel * d->sampleRate <= d->samplesPerThumbSample)
  16176. {
  16177. startTimer (timeBeforeDeletingReader);
  16178. char* cacheData = (char*) cachedLevels.getData();
  16179. int sample = roundDoubleToInt (startTime * d->sampleRate);
  16180. for (int i = numSamples; --i >= 0;)
  16181. {
  16182. const int nextSample = roundDoubleToInt ((startTime + timePerPixel) * d->sampleRate);
  16183. if (sample >= 0)
  16184. {
  16185. if (sample >= reader->lengthInSamples)
  16186. break;
  16187. float lmin, lmax, rmin, rmax;
  16188. reader->readMaxLevels (sample,
  16189. jmax (1, nextSample - sample),
  16190. lmin, lmax, rmin, rmax);
  16191. cacheData[0] = (char) jlimit (-128, 127, roundFloatToInt (lmin * 127.0f));
  16192. cacheData[1] = (char) jlimit (-128, 127, roundFloatToInt (lmax * 127.0f));
  16193. if (numChannelsCached > 1)
  16194. {
  16195. cacheData[2] = (char) jlimit (-128, 127, roundFloatToInt (rmin * 127.0f));
  16196. cacheData[3] = (char) jlimit (-128, 127, roundFloatToInt (rmax * 127.0f));
  16197. }
  16198. cacheData += 2 * numChannelsCached;
  16199. }
  16200. startTime += timePerPixel;
  16201. sample = nextSample;
  16202. }
  16203. }
  16204. else
  16205. {
  16206. for (int channelNum = 0; channelNum < numChannelsCached; ++channelNum)
  16207. {
  16208. char* const data = getChannelData (channelNum);
  16209. char* cacheData = ((char*) cachedLevels.getData()) + channelNum * 2;
  16210. const double timeToThumbSampleFactor = d->sampleRate / (double) d->samplesPerThumbSample;
  16211. startTime = cachedStart;
  16212. int sample = roundDoubleToInt (startTime * timeToThumbSampleFactor);
  16213. const int numFinished = (int) (d->numFinishedSamples / d->samplesPerThumbSample);
  16214. for (int i = numSamples; --i >= 0;)
  16215. {
  16216. const int nextSample = roundDoubleToInt ((startTime + timePerPixel) * timeToThumbSampleFactor);
  16217. if (sample >= 0 && data != 0)
  16218. {
  16219. char mx = -128;
  16220. char mn = 127;
  16221. while (sample <= nextSample)
  16222. {
  16223. if (sample >= numFinished)
  16224. break;
  16225. const int n = sample << 1;
  16226. const char sampMin = data [n];
  16227. const char sampMax = data [n + 1];
  16228. if (sampMin < mn)
  16229. mn = sampMin;
  16230. if (sampMax > mx)
  16231. mx = sampMax;
  16232. ++sample;
  16233. }
  16234. if (mn <= mx)
  16235. {
  16236. cacheData[0] = mn;
  16237. cacheData[1] = mx;
  16238. }
  16239. else
  16240. {
  16241. cacheData[0] = 1;
  16242. cacheData[1] = 0;
  16243. }
  16244. }
  16245. else
  16246. {
  16247. cacheData[0] = 1;
  16248. cacheData[1] = 0;
  16249. }
  16250. cacheData += numChannelsCached * 2;
  16251. startTime += timePerPixel;
  16252. sample = nextSample;
  16253. }
  16254. }
  16255. }
  16256. }
  16257. void AudioThumbnail::drawChannel (Graphics& g,
  16258. int x, int y, int w, int h,
  16259. double startTime,
  16260. double endTime,
  16261. int channelNum,
  16262. const float verticalZoomFactor)
  16263. {
  16264. refillCache (w, startTime, (endTime - startTime) / w);
  16265. if (numSamplesCached >= w
  16266. && channelNum >= 0
  16267. && channelNum < numChannelsCached)
  16268. {
  16269. const float topY = (float) y;
  16270. const float bottomY = topY + h;
  16271. const float midY = topY + h * 0.5f;
  16272. const float vscale = verticalZoomFactor * h / 256.0f;
  16273. const Rectangle clip (g.getClipBounds());
  16274. const int skipLeft = jlimit (0, w, clip.getX() - x);
  16275. w -= skipLeft;
  16276. x += skipLeft;
  16277. const char* cacheData = ((const char*) cachedLevels.getData())
  16278. + (channelNum << 1)
  16279. + skipLeft * (numChannelsCached << 1);
  16280. while (--w >= 0)
  16281. {
  16282. const char mn = cacheData[0];
  16283. const char mx = cacheData[1];
  16284. cacheData += numChannelsCached << 1;
  16285. if (mn <= mx) // if the wrong way round, signifies that the sample's not yet known
  16286. g.drawLine ((float) x, jmax (midY - mx * vscale - 0.3f, topY),
  16287. (float) x, jmin (midY - mn * vscale + 0.3f, bottomY));
  16288. ++x;
  16289. if (x >= clip.getRight())
  16290. break;
  16291. }
  16292. }
  16293. }
  16294. END_JUCE_NAMESPACE
  16295. /********* End of inlined file: juce_AudioThumbnail.cpp *********/
  16296. /********* Start of inlined file: juce_AudioThumbnailCache.cpp *********/
  16297. BEGIN_JUCE_NAMESPACE
  16298. struct ThumbnailCacheEntry
  16299. {
  16300. int64 hash;
  16301. uint32 lastUsed;
  16302. MemoryBlock data;
  16303. juce_UseDebuggingNewOperator
  16304. };
  16305. AudioThumbnailCache::AudioThumbnailCache (const int maxNumThumbsToStore_)
  16306. : TimeSliceThread (T("thumb cache")),
  16307. maxNumThumbsToStore (maxNumThumbsToStore_)
  16308. {
  16309. startThread (2);
  16310. }
  16311. AudioThumbnailCache::~AudioThumbnailCache()
  16312. {
  16313. }
  16314. bool AudioThumbnailCache::loadThumb (AudioThumbnail& thumb, const int64 hashCode)
  16315. {
  16316. for (int i = thumbs.size(); --i >= 0;)
  16317. {
  16318. if (thumbs[i]->hash == hashCode)
  16319. {
  16320. MemoryInputStream in ((const char*) thumbs[i]->data.getData(),
  16321. thumbs[i]->data.getSize(),
  16322. false);
  16323. thumb.loadFrom (in);
  16324. thumbs[i]->lastUsed = Time::getMillisecondCounter();
  16325. return true;
  16326. }
  16327. }
  16328. return false;
  16329. }
  16330. void AudioThumbnailCache::storeThumb (const AudioThumbnail& thumb,
  16331. const int64 hashCode)
  16332. {
  16333. MemoryOutputStream out;
  16334. thumb.saveTo (out);
  16335. ThumbnailCacheEntry* te = 0;
  16336. for (int i = thumbs.size(); --i >= 0;)
  16337. {
  16338. if (thumbs[i]->hash == hashCode)
  16339. {
  16340. te = thumbs[i];
  16341. break;
  16342. }
  16343. }
  16344. if (te == 0)
  16345. {
  16346. te = new ThumbnailCacheEntry();
  16347. te->hash = hashCode;
  16348. if (thumbs.size() < maxNumThumbsToStore)
  16349. {
  16350. thumbs.add (te);
  16351. }
  16352. else
  16353. {
  16354. int oldest = 0;
  16355. unsigned int oldestTime = Time::getMillisecondCounter() + 1;
  16356. int i;
  16357. for (i = thumbs.size(); --i >= 0;)
  16358. if (thumbs[i]->lastUsed < oldestTime)
  16359. oldest = i;
  16360. thumbs.set (i, te);
  16361. }
  16362. }
  16363. te->lastUsed = Time::getMillisecondCounter();
  16364. te->data.setSize (0);
  16365. te->data.append (out.getData(), out.getDataSize());
  16366. }
  16367. void AudioThumbnailCache::clear()
  16368. {
  16369. thumbs.clear();
  16370. }
  16371. void AudioThumbnailCache::addThumbnail (AudioThumbnail* const thumb)
  16372. {
  16373. addTimeSliceClient (thumb);
  16374. }
  16375. void AudioThumbnailCache::removeThumbnail (AudioThumbnail* const thumb)
  16376. {
  16377. removeTimeSliceClient (thumb);
  16378. }
  16379. END_JUCE_NAMESPACE
  16380. /********* End of inlined file: juce_AudioThumbnailCache.cpp *********/
  16381. /********* Start of inlined file: juce_QuickTimeAudioFormat.cpp *********/
  16382. #if JUCE_QUICKTIME
  16383. #if ! defined (_WIN32)
  16384. #include <QuickTime/Movies.h>
  16385. #include <QuickTime/QTML.h>
  16386. #include <QuickTime/QuickTimeComponents.h>
  16387. #include <QuickTime/MediaHandlers.h>
  16388. #include <QuickTime/ImageCodec.h>
  16389. #else
  16390. #ifdef _MSC_VER
  16391. #pragma warning (push)
  16392. #pragma warning (disable : 4100)
  16393. #endif
  16394. /* If you've got an include error here, you probably need to install the QuickTime SDK and
  16395. add its header directory to your include path.
  16396. Alternatively, if you don't need any QuickTime services, just turn off the JUC_QUICKTIME
  16397. flag in juce_Config.h
  16398. */
  16399. #include <Movies.h>
  16400. #include <QTML.h>
  16401. #include <QuickTimeComponents.h>
  16402. #include <MediaHandlers.h>
  16403. #include <ImageCodec.h>
  16404. #ifdef _MSC_VER
  16405. #pragma warning (pop)
  16406. #endif
  16407. #endif
  16408. #if ! (JUCE_MAC && JUCE_64BIT)
  16409. BEGIN_JUCE_NAMESPACE
  16410. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle);
  16411. #define quickTimeFormatName TRANS("QuickTime file")
  16412. static const tchar* const quickTimeExtensions[] = { T(".mov"), T(".mp3"), T(".mp4"), 0 };
  16413. class QTAudioReader : public AudioFormatReader
  16414. {
  16415. public:
  16416. QTAudioReader (InputStream* const input_, const int trackNum_)
  16417. : AudioFormatReader (input_, quickTimeFormatName),
  16418. ok (false),
  16419. movie (0),
  16420. trackNum (trackNum_),
  16421. extractor (0),
  16422. lastSampleRead (0),
  16423. lastThreadId (0),
  16424. dataHandle (0)
  16425. {
  16426. bufferList = (AudioBufferList*) juce_calloc (256);
  16427. #ifdef WIN32
  16428. if (InitializeQTML (0) != noErr)
  16429. return;
  16430. #endif
  16431. if (EnterMovies() != noErr)
  16432. return;
  16433. bool opened = juce_OpenQuickTimeMovieFromStream (input_, movie, dataHandle);
  16434. if (! opened)
  16435. return;
  16436. {
  16437. const int numTracks = GetMovieTrackCount (movie);
  16438. int trackCount = 0;
  16439. for (int i = 1; i <= numTracks; ++i)
  16440. {
  16441. track = GetMovieIndTrack (movie, i);
  16442. media = GetTrackMedia (track);
  16443. OSType mediaType;
  16444. GetMediaHandlerDescription (media, &mediaType, 0, 0);
  16445. if (mediaType == SoundMediaType
  16446. && trackCount++ == trackNum_)
  16447. {
  16448. ok = true;
  16449. break;
  16450. }
  16451. }
  16452. }
  16453. if (! ok)
  16454. return;
  16455. ok = false;
  16456. lengthInSamples = GetMediaDecodeDuration (media);
  16457. usesFloatingPointData = false;
  16458. samplesPerFrame = (int) (GetMediaDecodeDuration (media) / GetMediaSampleCount (media));
  16459. trackUnitsPerFrame = GetMovieTimeScale (movie) * samplesPerFrame
  16460. / GetMediaTimeScale (media);
  16461. OSStatus err = MovieAudioExtractionBegin (movie, 0, &extractor);
  16462. unsigned long output_layout_size;
  16463. err = MovieAudioExtractionGetPropertyInfo (extractor,
  16464. kQTPropertyClass_MovieAudioExtraction_Audio,
  16465. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  16466. 0, &output_layout_size, 0);
  16467. if (err != noErr)
  16468. return;
  16469. AudioChannelLayout* const qt_audio_channel_layout
  16470. = (AudioChannelLayout*) juce_calloc (output_layout_size);
  16471. err = MovieAudioExtractionGetProperty (extractor,
  16472. kQTPropertyClass_MovieAudioExtraction_Audio,
  16473. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  16474. output_layout_size, qt_audio_channel_layout, 0);
  16475. qt_audio_channel_layout->mChannelLayoutTag = kAudioChannelLayoutTag_Stereo;
  16476. err = MovieAudioExtractionSetProperty (extractor,
  16477. kQTPropertyClass_MovieAudioExtraction_Audio,
  16478. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  16479. sizeof (qt_audio_channel_layout),
  16480. qt_audio_channel_layout);
  16481. juce_free (qt_audio_channel_layout);
  16482. err = MovieAudioExtractionGetProperty (extractor,
  16483. kQTPropertyClass_MovieAudioExtraction_Audio,
  16484. kQTMovieAudioExtractionAudioPropertyID_AudioStreamBasicDescription,
  16485. sizeof (inputStreamDesc),
  16486. &inputStreamDesc, 0);
  16487. if (err != noErr)
  16488. return;
  16489. inputStreamDesc.mFormatFlags = kAudioFormatFlagIsSignedInteger
  16490. | kAudioFormatFlagIsPacked
  16491. | kAudioFormatFlagsNativeEndian;
  16492. inputStreamDesc.mBitsPerChannel = sizeof (SInt16) * 8;
  16493. inputStreamDesc.mChannelsPerFrame = jmin (2, inputStreamDesc.mChannelsPerFrame);
  16494. inputStreamDesc.mBytesPerFrame = sizeof (SInt16) * inputStreamDesc.mChannelsPerFrame;
  16495. inputStreamDesc.mBytesPerPacket = inputStreamDesc.mBytesPerFrame;
  16496. err = MovieAudioExtractionSetProperty (extractor,
  16497. kQTPropertyClass_MovieAudioExtraction_Audio,
  16498. kQTMovieAudioExtractionAudioPropertyID_AudioStreamBasicDescription,
  16499. sizeof (inputStreamDesc),
  16500. &inputStreamDesc);
  16501. if (err != noErr)
  16502. return;
  16503. Boolean allChannelsDiscrete = false;
  16504. err = MovieAudioExtractionSetProperty (extractor,
  16505. kQTPropertyClass_MovieAudioExtraction_Movie,
  16506. kQTMovieAudioExtractionMoviePropertyID_AllChannelsDiscrete,
  16507. sizeof (allChannelsDiscrete),
  16508. &allChannelsDiscrete);
  16509. if (err != noErr)
  16510. return;
  16511. bufferList->mNumberBuffers = 1;
  16512. bufferList->mBuffers[0].mNumberChannels = inputStreamDesc.mChannelsPerFrame;
  16513. bufferList->mBuffers[0].mDataByteSize = (UInt32) (samplesPerFrame * inputStreamDesc.mBytesPerFrame) + 16;
  16514. bufferList->mBuffers[0].mData = malloc (bufferList->mBuffers[0].mDataByteSize);
  16515. sampleRate = inputStreamDesc.mSampleRate;
  16516. bitsPerSample = 16;
  16517. numChannels = inputStreamDesc.mChannelsPerFrame;
  16518. detachThread();
  16519. ok = true;
  16520. }
  16521. ~QTAudioReader()
  16522. {
  16523. if (dataHandle != 0)
  16524. DisposeHandle (dataHandle);
  16525. if (extractor != 0)
  16526. {
  16527. MovieAudioExtractionEnd (extractor);
  16528. extractor = 0;
  16529. }
  16530. checkThreadIsAttached();
  16531. DisposeMovie (movie);
  16532. juce_free (bufferList->mBuffers[0].mData);
  16533. juce_free (bufferList);
  16534. #if JUCE_MAC
  16535. ExitMoviesOnThread ();
  16536. #endif
  16537. }
  16538. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  16539. int64 startSampleInFile, int numSamples)
  16540. {
  16541. checkThreadIsAttached();
  16542. while (numSamples > 0)
  16543. {
  16544. if (! loadFrame ((int) startSampleInFile))
  16545. return false;
  16546. const int numToDo = jmin (numSamples, samplesPerFrame);
  16547. for (int j = numDestChannels; --j >= 0;)
  16548. {
  16549. if (destSamples[j] != 0)
  16550. {
  16551. const short* const src = ((const short*) bufferList->mBuffers[0].mData) + j;
  16552. for (int i = 0; i < numToDo; ++i)
  16553. destSamples[j][startOffsetInDestBuffer + i] = src [i << 1] << 16;
  16554. }
  16555. }
  16556. startOffsetInDestBuffer += numToDo;
  16557. startSampleInFile += numToDo;
  16558. numSamples -= numToDo;
  16559. }
  16560. detachThread();
  16561. return true;
  16562. }
  16563. bool loadFrame (const int sampleNum)
  16564. {
  16565. if (lastSampleRead != sampleNum)
  16566. {
  16567. TimeRecord time;
  16568. time.scale = (TimeScale) inputStreamDesc.mSampleRate;
  16569. time.base = 0;
  16570. time.value.hi = 0;
  16571. time.value.lo = (UInt32) sampleNum;
  16572. OSStatus err = MovieAudioExtractionSetProperty (extractor,
  16573. kQTPropertyClass_MovieAudioExtraction_Movie,
  16574. kQTMovieAudioExtractionMoviePropertyID_CurrentTime,
  16575. sizeof (time), &time);
  16576. if (err != noErr)
  16577. return false;
  16578. }
  16579. bufferList->mBuffers[0].mDataByteSize = inputStreamDesc.mBytesPerFrame * samplesPerFrame;
  16580. UInt32 outFlags = 0;
  16581. UInt32 actualNumSamples = samplesPerFrame;
  16582. OSStatus err = MovieAudioExtractionFillBuffer (extractor, &actualNumSamples,
  16583. bufferList, &outFlags);
  16584. lastSampleRead = sampleNum + samplesPerFrame;
  16585. return err == noErr;
  16586. }
  16587. juce_UseDebuggingNewOperator
  16588. bool ok;
  16589. private:
  16590. Movie movie;
  16591. Media media;
  16592. Track track;
  16593. const int trackNum;
  16594. double trackUnitsPerFrame;
  16595. int samplesPerFrame;
  16596. int lastSampleRead;
  16597. Thread::ThreadID lastThreadId;
  16598. MovieAudioExtractionRef extractor;
  16599. AudioStreamBasicDescription inputStreamDesc;
  16600. AudioBufferList* bufferList;
  16601. Handle dataHandle;
  16602. /*OSErr readMovieStream (long offset, long size, void* dataPtr)
  16603. {
  16604. input->setPosition (offset);
  16605. input->read (dataPtr, size);
  16606. return noErr;
  16607. }
  16608. static OSErr readMovieStreamProc (long offset, long size, void* dataPtr, void* userRef)
  16609. {
  16610. return ((QTAudioReader*) userRef)->readMovieStream (offset, size, dataPtr);
  16611. }*/
  16612. void checkThreadIsAttached()
  16613. {
  16614. #if JUCE_MAC
  16615. if (Thread::getCurrentThreadId() != lastThreadId)
  16616. EnterMoviesOnThread (0);
  16617. AttachMovieToCurrentThread (movie);
  16618. #endif
  16619. }
  16620. void detachThread()
  16621. {
  16622. #if JUCE_MAC
  16623. DetachMovieFromCurrentThread (movie);
  16624. #endif
  16625. }
  16626. };
  16627. QuickTimeAudioFormat::QuickTimeAudioFormat()
  16628. : AudioFormat (quickTimeFormatName, (const tchar**) quickTimeExtensions)
  16629. {
  16630. }
  16631. QuickTimeAudioFormat::~QuickTimeAudioFormat()
  16632. {
  16633. }
  16634. const Array <int> QuickTimeAudioFormat::getPossibleSampleRates()
  16635. {
  16636. return Array<int>();
  16637. }
  16638. const Array <int> QuickTimeAudioFormat::getPossibleBitDepths()
  16639. {
  16640. return Array<int>();
  16641. }
  16642. bool QuickTimeAudioFormat::canDoStereo()
  16643. {
  16644. return true;
  16645. }
  16646. bool QuickTimeAudioFormat::canDoMono()
  16647. {
  16648. return true;
  16649. }
  16650. AudioFormatReader* QuickTimeAudioFormat::createReaderFor (InputStream* sourceStream,
  16651. const bool deleteStreamIfOpeningFails)
  16652. {
  16653. QTAudioReader* r = new QTAudioReader (sourceStream, 0);
  16654. if (! r->ok)
  16655. {
  16656. if (! deleteStreamIfOpeningFails)
  16657. r->input = 0;
  16658. deleteAndZero (r);
  16659. }
  16660. return r;
  16661. }
  16662. AudioFormatWriter* QuickTimeAudioFormat::createWriterFor (OutputStream* /*streamToWriteTo*/,
  16663. double /*sampleRateToUse*/,
  16664. unsigned int /*numberOfChannels*/,
  16665. int /*bitsPerSample*/,
  16666. const StringPairArray& /*metadataValues*/,
  16667. int /*qualityOptionIndex*/)
  16668. {
  16669. jassertfalse // not yet implemented!
  16670. return 0;
  16671. }
  16672. END_JUCE_NAMESPACE
  16673. #endif
  16674. #endif
  16675. /********* End of inlined file: juce_QuickTimeAudioFormat.cpp *********/
  16676. /********* Start of inlined file: juce_WavAudioFormat.cpp *********/
  16677. BEGIN_JUCE_NAMESPACE
  16678. #define wavFormatName TRANS("WAV file")
  16679. static const tchar* const wavExtensions[] = { T(".wav"), T(".bwf"), 0 };
  16680. const tchar* const WavAudioFormat::bwavDescription = T("bwav description");
  16681. const tchar* const WavAudioFormat::bwavOriginator = T("bwav originator");
  16682. const tchar* const WavAudioFormat::bwavOriginatorRef = T("bwav originator ref");
  16683. const tchar* const WavAudioFormat::bwavOriginationDate = T("bwav origination date");
  16684. const tchar* const WavAudioFormat::bwavOriginationTime = T("bwav origination time");
  16685. const tchar* const WavAudioFormat::bwavTimeReference = T("bwav time reference");
  16686. const tchar* const WavAudioFormat::bwavCodingHistory = T("bwav coding history");
  16687. const StringPairArray WavAudioFormat::createBWAVMetadata (const String& description,
  16688. const String& originator,
  16689. const String& originatorRef,
  16690. const Time& date,
  16691. const int64 timeReferenceSamples,
  16692. const String& codingHistory)
  16693. {
  16694. StringPairArray m;
  16695. m.set (bwavDescription, description);
  16696. m.set (bwavOriginator, originator);
  16697. m.set (bwavOriginatorRef, originatorRef);
  16698. m.set (bwavOriginationDate, date.formatted (T("%Y-%m-%d")));
  16699. m.set (bwavOriginationTime, date.formatted (T("%H:%M:%S")));
  16700. m.set (bwavTimeReference, String (timeReferenceSamples));
  16701. m.set (bwavCodingHistory, codingHistory);
  16702. return m;
  16703. }
  16704. #if JUCE_MSVC
  16705. #pragma pack (push, 1)
  16706. #define PACKED
  16707. #elif defined (JUCE_GCC)
  16708. #define PACKED __attribute__((packed))
  16709. #else
  16710. #define PACKED
  16711. #endif
  16712. struct BWAVChunk
  16713. {
  16714. uint8 description [256];
  16715. uint8 originator [32];
  16716. uint8 originatorRef [32];
  16717. uint8 originationDate [10];
  16718. uint8 originationTime [8];
  16719. uint32 timeRefLow;
  16720. uint32 timeRefHigh;
  16721. uint16 version;
  16722. uint8 umid[64];
  16723. uint8 reserved[190];
  16724. uint8 codingHistory[1];
  16725. void copyTo (StringPairArray& values) const
  16726. {
  16727. values.set (WavAudioFormat::bwavDescription, String::fromUTF8 (description, 256));
  16728. values.set (WavAudioFormat::bwavOriginator, String::fromUTF8 (originator, 32));
  16729. values.set (WavAudioFormat::bwavOriginatorRef, String::fromUTF8 (originatorRef, 32));
  16730. values.set (WavAudioFormat::bwavOriginationDate, String::fromUTF8 (originationDate, 10));
  16731. values.set (WavAudioFormat::bwavOriginationTime, String::fromUTF8 (originationTime, 8));
  16732. const uint32 timeLow = swapIfBigEndian (timeRefLow);
  16733. const uint32 timeHigh = swapIfBigEndian (timeRefHigh);
  16734. const int64 time = (((int64)timeHigh) << 32) + timeLow;
  16735. values.set (WavAudioFormat::bwavTimeReference, String (time));
  16736. values.set (WavAudioFormat::bwavCodingHistory, String::fromUTF8 (codingHistory));
  16737. }
  16738. static MemoryBlock createFrom (const StringPairArray& values)
  16739. {
  16740. const int sizeNeeded = sizeof (BWAVChunk) + values [WavAudioFormat::bwavCodingHistory].copyToUTF8 (0) - 1;
  16741. MemoryBlock data ((sizeNeeded + 3) & ~3);
  16742. data.fillWith (0);
  16743. BWAVChunk* b = (BWAVChunk*) data.getData();
  16744. // Allow these calls to overwrite an extra byte at the end, which is fine as long
  16745. // as they get called in the right order..
  16746. values [WavAudioFormat::bwavDescription].copyToUTF8 (b->description, 257);
  16747. values [WavAudioFormat::bwavOriginator].copyToUTF8 (b->originator, 33);
  16748. values [WavAudioFormat::bwavOriginatorRef].copyToUTF8 (b->originatorRef, 33);
  16749. values [WavAudioFormat::bwavOriginationDate].copyToUTF8 (b->originationDate, 11);
  16750. values [WavAudioFormat::bwavOriginationTime].copyToUTF8 (b->originationTime, 9);
  16751. const int64 time = values [WavAudioFormat::bwavTimeReference].getLargeIntValue();
  16752. b->timeRefLow = swapIfBigEndian ((uint32) (time & 0xffffffff));
  16753. b->timeRefHigh = swapIfBigEndian ((uint32) (time >> 32));
  16754. values [WavAudioFormat::bwavCodingHistory].copyToUTF8 (b->codingHistory);
  16755. if (b->description[0] != 0
  16756. || b->originator[0] != 0
  16757. || b->originationDate[0] != 0
  16758. || b->originationTime[0] != 0
  16759. || b->codingHistory[0] != 0
  16760. || time != 0)
  16761. {
  16762. return data;
  16763. }
  16764. return MemoryBlock();
  16765. }
  16766. } PACKED;
  16767. struct SMPLChunk
  16768. {
  16769. struct SampleLoop
  16770. {
  16771. uint32 identifier;
  16772. uint32 type;
  16773. uint32 start;
  16774. uint32 end;
  16775. uint32 fraction;
  16776. uint32 playCount;
  16777. } PACKED;
  16778. uint32 manufacturer;
  16779. uint32 product;
  16780. uint32 samplePeriod;
  16781. uint32 midiUnityNote;
  16782. uint32 midiPitchFraction;
  16783. uint32 smpteFormat;
  16784. uint32 smpteOffset;
  16785. uint32 numSampleLoops;
  16786. uint32 samplerData;
  16787. SampleLoop loops[1];
  16788. void copyTo (StringPairArray& values, const int totalSize) const
  16789. {
  16790. values.set (T("Manufacturer"), String (swapIfBigEndian (manufacturer)));
  16791. values.set (T("Product"), String (swapIfBigEndian (product)));
  16792. values.set (T("SamplePeriod"), String (swapIfBigEndian (samplePeriod)));
  16793. values.set (T("MidiUnityNote"), String (swapIfBigEndian (midiUnityNote)));
  16794. values.set (T("MidiPitchFraction"), String (swapIfBigEndian (midiPitchFraction)));
  16795. values.set (T("SmpteFormat"), String (swapIfBigEndian (smpteFormat)));
  16796. values.set (T("SmpteOffset"), String (swapIfBigEndian (smpteOffset)));
  16797. values.set (T("NumSampleLoops"), String (swapIfBigEndian (numSampleLoops)));
  16798. values.set (T("SamplerData"), String (swapIfBigEndian (samplerData)));
  16799. for (uint32 i = 0; i < numSampleLoops; ++i)
  16800. {
  16801. if ((uint8*) (loops + (i + 1)) > ((uint8*) this) + totalSize)
  16802. break;
  16803. values.set (String::formatted (T("Loop%dIdentifier"), i), String (swapIfBigEndian (loops[i].identifier)));
  16804. values.set (String::formatted (T("Loop%dType"), i), String (swapIfBigEndian (loops[i].type)));
  16805. values.set (String::formatted (T("Loop%dStart"), i), String (swapIfBigEndian (loops[i].start)));
  16806. values.set (String::formatted (T("Loop%dEnd"), i), String (swapIfBigEndian (loops[i].end)));
  16807. values.set (String::formatted (T("Loop%dFraction"), i), String (swapIfBigEndian (loops[i].fraction)));
  16808. values.set (String::formatted (T("Loop%dPlayCount"), i), String (swapIfBigEndian (loops[i].playCount)));
  16809. }
  16810. }
  16811. } PACKED;
  16812. #if JUCE_MSVC
  16813. #pragma pack (pop)
  16814. #endif
  16815. #undef PACKED
  16816. #undef chunkName
  16817. #define chunkName(a) ((int) littleEndianInt(a))
  16818. class WavAudioFormatReader : public AudioFormatReader
  16819. {
  16820. int bytesPerFrame;
  16821. int64 dataChunkStart, dataLength;
  16822. WavAudioFormatReader (const WavAudioFormatReader&);
  16823. const WavAudioFormatReader& operator= (const WavAudioFormatReader&);
  16824. public:
  16825. int64 bwavChunkStart, bwavSize;
  16826. WavAudioFormatReader (InputStream* const in)
  16827. : AudioFormatReader (in, wavFormatName),
  16828. dataLength (0),
  16829. bwavChunkStart (0),
  16830. bwavSize (0)
  16831. {
  16832. if (input->readInt() == chunkName ("RIFF"))
  16833. {
  16834. const uint32 len = (uint32) input->readInt();
  16835. const int64 end = input->getPosition() + len;
  16836. bool hasGotType = false;
  16837. bool hasGotData = false;
  16838. if (input->readInt() == chunkName ("WAVE"))
  16839. {
  16840. while (input->getPosition() < end
  16841. && ! input->isExhausted())
  16842. {
  16843. const int chunkType = input->readInt();
  16844. uint32 length = (uint32) input->readInt();
  16845. const int64 chunkEnd = input->getPosition() + length + (length & 1);
  16846. if (chunkType == chunkName ("fmt "))
  16847. {
  16848. // read the format chunk
  16849. const short format = input->readShort();
  16850. const short numChans = input->readShort();
  16851. sampleRate = input->readInt();
  16852. const int bytesPerSec = input->readInt();
  16853. numChannels = numChans;
  16854. bytesPerFrame = bytesPerSec / (int)sampleRate;
  16855. bitsPerSample = 8 * bytesPerFrame / numChans;
  16856. if (format == 3)
  16857. usesFloatingPointData = true;
  16858. else if (format != 1)
  16859. bytesPerFrame = 0;
  16860. hasGotType = true;
  16861. }
  16862. else if (chunkType == chunkName ("data"))
  16863. {
  16864. // get the data chunk's position
  16865. dataLength = length;
  16866. dataChunkStart = input->getPosition();
  16867. lengthInSamples = (bytesPerFrame > 0) ? (dataLength / bytesPerFrame) : 0;
  16868. hasGotData = true;
  16869. }
  16870. else if (chunkType == chunkName ("bext"))
  16871. {
  16872. bwavChunkStart = input->getPosition();
  16873. bwavSize = length;
  16874. // Broadcast-wav extension chunk..
  16875. BWAVChunk* const bwav = (BWAVChunk*) juce_calloc (jmax (length + 1, (int) sizeof (BWAVChunk)));
  16876. input->read (bwav, length);
  16877. bwav->copyTo (metadataValues);
  16878. juce_free (bwav);
  16879. }
  16880. else if (chunkType == chunkName ("smpl"))
  16881. {
  16882. SMPLChunk* const smpl = (SMPLChunk*) juce_calloc (jmax (length + 1, (int) sizeof (SMPLChunk)));
  16883. input->read (smpl, length);
  16884. smpl->copyTo (metadataValues, length);
  16885. juce_free (smpl);
  16886. }
  16887. else if (chunkEnd <= input->getPosition())
  16888. {
  16889. break;
  16890. }
  16891. input->setPosition (chunkEnd);
  16892. }
  16893. }
  16894. }
  16895. }
  16896. ~WavAudioFormatReader()
  16897. {
  16898. }
  16899. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  16900. int64 startSampleInFile, int numSamples)
  16901. {
  16902. const int64 samplesAvailable = lengthInSamples - startSampleInFile;
  16903. if (samplesAvailable < numSamples)
  16904. {
  16905. for (int i = numDestChannels; --i >= 0;)
  16906. if (destSamples[i] != 0)
  16907. zeromem (destSamples[i] + startOffsetInDestBuffer, sizeof (int) * numSamples);
  16908. numSamples = (int) samplesAvailable;
  16909. }
  16910. if (numSamples <= 0)
  16911. return true;
  16912. input->setPosition (dataChunkStart + startSampleInFile * bytesPerFrame);
  16913. const int tempBufSize = 480 * 3 * 4; // (keep this a multiple of 3)
  16914. char tempBuffer [tempBufSize];
  16915. while (numSamples > 0)
  16916. {
  16917. int* left = destSamples[0];
  16918. if (left != 0)
  16919. left += startOffsetInDestBuffer;
  16920. int* right = numDestChannels > 1 ? destSamples[1] : 0;
  16921. if (right != 0)
  16922. right += startOffsetInDestBuffer;
  16923. const int numThisTime = jmin (tempBufSize / bytesPerFrame, numSamples);
  16924. const int bytesRead = input->read (tempBuffer, numThisTime * bytesPerFrame);
  16925. if (bytesRead < numThisTime * bytesPerFrame)
  16926. zeromem (tempBuffer + bytesRead, numThisTime * bytesPerFrame - bytesRead);
  16927. if (bitsPerSample == 16)
  16928. {
  16929. const short* src = (const short*) tempBuffer;
  16930. if (numChannels > 1)
  16931. {
  16932. if (left == 0)
  16933. {
  16934. for (int i = numThisTime; --i >= 0;)
  16935. {
  16936. ++src;
  16937. *right++ = (int) swapIfBigEndian ((unsigned short) *src++) << 16;
  16938. }
  16939. }
  16940. else if (right == 0)
  16941. {
  16942. for (int i = numThisTime; --i >= 0;)
  16943. {
  16944. *left++ = (int) swapIfBigEndian ((unsigned short) *src++) << 16;
  16945. ++src;
  16946. }
  16947. }
  16948. else
  16949. {
  16950. for (int i = numThisTime; --i >= 0;)
  16951. {
  16952. *left++ = (int) swapIfBigEndian ((unsigned short) *src++) << 16;
  16953. *right++ = (int) swapIfBigEndian ((unsigned short) *src++) << 16;
  16954. }
  16955. }
  16956. }
  16957. else
  16958. {
  16959. for (int i = numThisTime; --i >= 0;)
  16960. {
  16961. *left++ = (int) swapIfBigEndian ((unsigned short) *src++) << 16;
  16962. }
  16963. }
  16964. }
  16965. else if (bitsPerSample == 24)
  16966. {
  16967. const char* src = (const char*) tempBuffer;
  16968. if (numChannels > 1)
  16969. {
  16970. if (left == 0)
  16971. {
  16972. for (int i = numThisTime; --i >= 0;)
  16973. {
  16974. src += 3;
  16975. *right++ = littleEndian24Bit (src) << 8;
  16976. src += 3;
  16977. }
  16978. }
  16979. else if (right == 0)
  16980. {
  16981. for (int i = numThisTime; --i >= 0;)
  16982. {
  16983. *left++ = littleEndian24Bit (src) << 8;
  16984. src += 6;
  16985. }
  16986. }
  16987. else
  16988. {
  16989. for (int i = 0; i < numThisTime; ++i)
  16990. {
  16991. *left++ = littleEndian24Bit (src) << 8;
  16992. src += 3;
  16993. *right++ = littleEndian24Bit (src) << 8;
  16994. src += 3;
  16995. }
  16996. }
  16997. }
  16998. else
  16999. {
  17000. for (int i = 0; i < numThisTime; ++i)
  17001. {
  17002. *left++ = littleEndian24Bit (src) << 8;
  17003. src += 3;
  17004. }
  17005. }
  17006. }
  17007. else if (bitsPerSample == 32)
  17008. {
  17009. const unsigned int* src = (const unsigned int*) tempBuffer;
  17010. unsigned int* l = (unsigned int*) left;
  17011. unsigned int* r = (unsigned int*) right;
  17012. if (numChannels > 1)
  17013. {
  17014. if (l == 0)
  17015. {
  17016. for (int i = numThisTime; --i >= 0;)
  17017. {
  17018. ++src;
  17019. *r++ = swapIfBigEndian (*src++);
  17020. }
  17021. }
  17022. else if (r == 0)
  17023. {
  17024. for (int i = numThisTime; --i >= 0;)
  17025. {
  17026. *l++ = swapIfBigEndian (*src++);
  17027. ++src;
  17028. }
  17029. }
  17030. else
  17031. {
  17032. for (int i = numThisTime; --i >= 0;)
  17033. {
  17034. *l++ = swapIfBigEndian (*src++);
  17035. *r++ = swapIfBigEndian (*src++);
  17036. }
  17037. }
  17038. }
  17039. else
  17040. {
  17041. for (int i = numThisTime; --i >= 0;)
  17042. {
  17043. *l++ = swapIfBigEndian (*src++);
  17044. }
  17045. }
  17046. left = (int*)l;
  17047. right = (int*)r;
  17048. }
  17049. else if (bitsPerSample == 8)
  17050. {
  17051. const unsigned char* src = (const unsigned char*) tempBuffer;
  17052. if (numChannels > 1)
  17053. {
  17054. if (left == 0)
  17055. {
  17056. for (int i = numThisTime; --i >= 0;)
  17057. {
  17058. ++src;
  17059. *right++ = ((int) *src++ - 128) << 24;
  17060. }
  17061. }
  17062. else if (right == 0)
  17063. {
  17064. for (int i = numThisTime; --i >= 0;)
  17065. {
  17066. *left++ = ((int) *src++ - 128) << 24;
  17067. ++src;
  17068. }
  17069. }
  17070. else
  17071. {
  17072. for (int i = numThisTime; --i >= 0;)
  17073. {
  17074. *left++ = ((int) *src++ - 128) << 24;
  17075. *right++ = ((int) *src++ - 128) << 24;
  17076. }
  17077. }
  17078. }
  17079. else
  17080. {
  17081. for (int i = numThisTime; --i >= 0;)
  17082. {
  17083. *left++ = ((int)*src++ - 128) << 24;
  17084. }
  17085. }
  17086. }
  17087. startOffsetInDestBuffer += numThisTime;
  17088. numSamples -= numThisTime;
  17089. }
  17090. if (numSamples > 0)
  17091. {
  17092. for (int i = numDestChannels; --i >= 0;)
  17093. if (destSamples[i] != 0)
  17094. zeromem (destSamples[i] + startOffsetInDestBuffer,
  17095. sizeof (int) * numSamples);
  17096. }
  17097. return true;
  17098. }
  17099. juce_UseDebuggingNewOperator
  17100. };
  17101. class WavAudioFormatWriter : public AudioFormatWriter
  17102. {
  17103. MemoryBlock tempBlock, bwavChunk;
  17104. uint32 lengthInSamples, bytesWritten;
  17105. int64 headerPosition;
  17106. bool writeFailed;
  17107. WavAudioFormatWriter (const WavAudioFormatWriter&);
  17108. const WavAudioFormatWriter& operator= (const WavAudioFormatWriter&);
  17109. void writeHeader()
  17110. {
  17111. const bool seekedOk = output->setPosition (headerPosition);
  17112. (void) seekedOk;
  17113. // if this fails, you've given it an output stream that can't seek! It needs
  17114. // to be able to seek back to write the header
  17115. jassert (seekedOk);
  17116. const int bytesPerFrame = numChannels * bitsPerSample / 8;
  17117. output->writeInt (chunkName ("RIFF"));
  17118. output->writeInt (lengthInSamples * bytesPerFrame
  17119. + ((bwavChunk.getSize() > 0) ? (44 + bwavChunk.getSize()) : 36));
  17120. output->writeInt (chunkName ("WAVE"));
  17121. output->writeInt (chunkName ("fmt "));
  17122. output->writeInt (16);
  17123. output->writeShort ((bitsPerSample < 32) ? (short) 1 /*WAVE_FORMAT_PCM*/
  17124. : (short) 3 /*WAVE_FORMAT_IEEE_FLOAT*/);
  17125. output->writeShort ((short) numChannels);
  17126. output->writeInt ((int) sampleRate);
  17127. output->writeInt (bytesPerFrame * (int) sampleRate);
  17128. output->writeShort ((short) bytesPerFrame);
  17129. output->writeShort ((short) bitsPerSample);
  17130. if (bwavChunk.getSize() > 0)
  17131. {
  17132. output->writeInt (chunkName ("bext"));
  17133. output->writeInt (bwavChunk.getSize());
  17134. output->write (bwavChunk.getData(), bwavChunk.getSize());
  17135. }
  17136. output->writeInt (chunkName ("data"));
  17137. output->writeInt (lengthInSamples * bytesPerFrame);
  17138. usesFloatingPointData = (bitsPerSample == 32);
  17139. }
  17140. public:
  17141. WavAudioFormatWriter (OutputStream* const out,
  17142. const double sampleRate,
  17143. const unsigned int numChannels_,
  17144. const int bits,
  17145. const StringPairArray& metadataValues)
  17146. : AudioFormatWriter (out,
  17147. wavFormatName,
  17148. sampleRate,
  17149. numChannels_,
  17150. bits),
  17151. lengthInSamples (0),
  17152. bytesWritten (0),
  17153. writeFailed (false)
  17154. {
  17155. if (metadataValues.size() > 0)
  17156. bwavChunk = BWAVChunk::createFrom (metadataValues);
  17157. headerPosition = out->getPosition();
  17158. writeHeader();
  17159. }
  17160. ~WavAudioFormatWriter()
  17161. {
  17162. writeHeader();
  17163. }
  17164. bool write (const int** data, int numSamples)
  17165. {
  17166. if (writeFailed)
  17167. return false;
  17168. const int bytes = numChannels * numSamples * bitsPerSample / 8;
  17169. tempBlock.ensureSize (bytes, false);
  17170. char* buffer = (char*) tempBlock.getData();
  17171. const int* left = data[0];
  17172. const int* right = data[1];
  17173. if (right == 0)
  17174. right = left;
  17175. if (bitsPerSample == 16)
  17176. {
  17177. short* b = (short*) buffer;
  17178. if (numChannels > 1)
  17179. {
  17180. for (int i = numSamples; --i >= 0;)
  17181. {
  17182. *b++ = (short) swapIfBigEndian ((unsigned short) (*left++ >> 16));
  17183. *b++ = (short) swapIfBigEndian ((unsigned short) (*right++ >> 16));
  17184. }
  17185. }
  17186. else
  17187. {
  17188. for (int i = numSamples; --i >= 0;)
  17189. {
  17190. *b++ = (short) swapIfBigEndian ((unsigned short) (*left++ >> 16));
  17191. }
  17192. }
  17193. }
  17194. else if (bitsPerSample == 24)
  17195. {
  17196. char* b = (char*) buffer;
  17197. if (numChannels > 1)
  17198. {
  17199. for (int i = numSamples; --i >= 0;)
  17200. {
  17201. littleEndian24BitToChars ((*left++) >> 8, b);
  17202. b += 3;
  17203. littleEndian24BitToChars ((*right++) >> 8, b);
  17204. b += 3;
  17205. }
  17206. }
  17207. else
  17208. {
  17209. for (int i = numSamples; --i >= 0;)
  17210. {
  17211. littleEndian24BitToChars ((*left++) >> 8, b);
  17212. b += 3;
  17213. }
  17214. }
  17215. }
  17216. else if (bitsPerSample == 32)
  17217. {
  17218. unsigned int* b = (unsigned int*) buffer;
  17219. if (numChannels > 1)
  17220. {
  17221. for (int i = numSamples; --i >= 0;)
  17222. {
  17223. *b++ = swapIfBigEndian ((unsigned int) *left++);
  17224. *b++ = swapIfBigEndian ((unsigned int) *right++);
  17225. }
  17226. }
  17227. else
  17228. {
  17229. for (int i = numSamples; --i >= 0;)
  17230. {
  17231. *b++ = swapIfBigEndian ((unsigned int) *left++);
  17232. }
  17233. }
  17234. }
  17235. else if (bitsPerSample == 8)
  17236. {
  17237. unsigned char* b = (unsigned char*) buffer;
  17238. if (numChannels > 1)
  17239. {
  17240. for (int i = numSamples; --i >= 0;)
  17241. {
  17242. *b++ = (unsigned char) (128 + (*left++ >> 24));
  17243. *b++ = (unsigned char) (128 + (*right++ >> 24));
  17244. }
  17245. }
  17246. else
  17247. {
  17248. for (int i = numSamples; --i >= 0;)
  17249. {
  17250. *b++ = (unsigned char) (128 + (*left++ >> 24));
  17251. }
  17252. }
  17253. }
  17254. if (bytesWritten + bytes >= (uint32) 0xfff00000
  17255. || ! output->write (buffer, bytes))
  17256. {
  17257. // failed to write to disk, so let's try writing the header.
  17258. // If it's just run out of disk space, then if it does manage
  17259. // to write the header, we'll still have a useable file..
  17260. writeHeader();
  17261. writeFailed = true;
  17262. return false;
  17263. }
  17264. else
  17265. {
  17266. bytesWritten += bytes;
  17267. lengthInSamples += numSamples;
  17268. return true;
  17269. }
  17270. }
  17271. juce_UseDebuggingNewOperator
  17272. };
  17273. WavAudioFormat::WavAudioFormat()
  17274. : AudioFormat (wavFormatName, (const tchar**) wavExtensions)
  17275. {
  17276. }
  17277. WavAudioFormat::~WavAudioFormat()
  17278. {
  17279. }
  17280. const Array <int> WavAudioFormat::getPossibleSampleRates()
  17281. {
  17282. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  17283. return Array <int> (rates);
  17284. }
  17285. const Array <int> WavAudioFormat::getPossibleBitDepths()
  17286. {
  17287. const int depths[] = { 8, 16, 24, 32, 0 };
  17288. return Array <int> (depths);
  17289. }
  17290. bool WavAudioFormat::canDoStereo()
  17291. {
  17292. return true;
  17293. }
  17294. bool WavAudioFormat::canDoMono()
  17295. {
  17296. return true;
  17297. }
  17298. AudioFormatReader* WavAudioFormat::createReaderFor (InputStream* sourceStream,
  17299. const bool deleteStreamIfOpeningFails)
  17300. {
  17301. WavAudioFormatReader* r = new WavAudioFormatReader (sourceStream);
  17302. if (r->sampleRate == 0)
  17303. {
  17304. if (! deleteStreamIfOpeningFails)
  17305. r->input = 0;
  17306. deleteAndZero (r);
  17307. }
  17308. return r;
  17309. }
  17310. AudioFormatWriter* WavAudioFormat::createWriterFor (OutputStream* out,
  17311. double sampleRate,
  17312. unsigned int numChannels,
  17313. int bitsPerSample,
  17314. const StringPairArray& metadataValues,
  17315. int /*qualityOptionIndex*/)
  17316. {
  17317. if (getPossibleBitDepths().contains (bitsPerSample))
  17318. {
  17319. return new WavAudioFormatWriter (out,
  17320. sampleRate,
  17321. numChannels,
  17322. bitsPerSample,
  17323. metadataValues);
  17324. }
  17325. return 0;
  17326. }
  17327. static bool juce_slowCopyOfWavFileWithNewMetadata (const File& file, const StringPairArray& metadata)
  17328. {
  17329. bool ok = false;
  17330. WavAudioFormat wav;
  17331. const File dest (file.getNonexistentSibling());
  17332. OutputStream* outStream = dest.createOutputStream();
  17333. if (outStream != 0)
  17334. {
  17335. AudioFormatReader* reader = wav.createReaderFor (file.createInputStream(), true);
  17336. if (reader != 0)
  17337. {
  17338. AudioFormatWriter* writer = wav.createWriterFor (outStream, reader->sampleRate,
  17339. reader->numChannels, reader->bitsPerSample,
  17340. metadata, 0);
  17341. if (writer != 0)
  17342. {
  17343. ok = writer->writeFromAudioReader (*reader, 0, -1);
  17344. outStream = 0;
  17345. delete writer;
  17346. }
  17347. delete reader;
  17348. }
  17349. delete outStream;
  17350. }
  17351. if (ok)
  17352. ok = dest.moveFileTo (file);
  17353. if (! ok)
  17354. dest.deleteFile();
  17355. return ok;
  17356. }
  17357. bool WavAudioFormat::replaceMetadataInFile (const File& wavFile, const StringPairArray& newMetadata)
  17358. {
  17359. WavAudioFormatReader* reader = (WavAudioFormatReader*) createReaderFor (wavFile.createInputStream(), true);
  17360. if (reader != 0)
  17361. {
  17362. const int64 bwavPos = reader->bwavChunkStart;
  17363. const int64 bwavSize = reader->bwavSize;
  17364. delete reader;
  17365. if (bwavSize > 0)
  17366. {
  17367. MemoryBlock chunk = BWAVChunk::createFrom (newMetadata);
  17368. if (chunk.getSize() <= bwavSize)
  17369. {
  17370. // the new one will fit in the space available, so write it directly..
  17371. const int64 oldSize = wavFile.getSize();
  17372. FileOutputStream* out = wavFile.createOutputStream();
  17373. out->setPosition (bwavPos);
  17374. out->write (chunk.getData(), chunk.getSize());
  17375. out->setPosition (oldSize);
  17376. delete out;
  17377. jassert (wavFile.getSize() == oldSize);
  17378. return true;
  17379. }
  17380. }
  17381. }
  17382. return juce_slowCopyOfWavFileWithNewMetadata (wavFile, newMetadata);
  17383. }
  17384. END_JUCE_NAMESPACE
  17385. /********* End of inlined file: juce_WavAudioFormat.cpp *********/
  17386. /********* Start of inlined file: juce_AudioFormatReaderSource.cpp *********/
  17387. BEGIN_JUCE_NAMESPACE
  17388. AudioFormatReaderSource::AudioFormatReaderSource (AudioFormatReader* const reader_,
  17389. const bool deleteReaderWhenThisIsDeleted)
  17390. : reader (reader_),
  17391. deleteReader (deleteReaderWhenThisIsDeleted),
  17392. nextPlayPos (0),
  17393. looping (false)
  17394. {
  17395. jassert (reader != 0);
  17396. }
  17397. AudioFormatReaderSource::~AudioFormatReaderSource()
  17398. {
  17399. releaseResources();
  17400. if (deleteReader)
  17401. delete reader;
  17402. }
  17403. void AudioFormatReaderSource::setNextReadPosition (int newPosition)
  17404. {
  17405. nextPlayPos = newPosition;
  17406. }
  17407. void AudioFormatReaderSource::setLooping (const bool shouldLoop) throw()
  17408. {
  17409. looping = shouldLoop;
  17410. }
  17411. int AudioFormatReaderSource::getNextReadPosition() const
  17412. {
  17413. return (looping) ? (nextPlayPos % (int) reader->lengthInSamples)
  17414. : nextPlayPos;
  17415. }
  17416. int AudioFormatReaderSource::getTotalLength() const
  17417. {
  17418. return (int) reader->lengthInSamples;
  17419. }
  17420. void AudioFormatReaderSource::prepareToPlay (int /*samplesPerBlockExpected*/,
  17421. double /*sampleRate*/)
  17422. {
  17423. }
  17424. void AudioFormatReaderSource::releaseResources()
  17425. {
  17426. }
  17427. void AudioFormatReaderSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  17428. {
  17429. if (info.numSamples > 0)
  17430. {
  17431. const int start = nextPlayPos;
  17432. if (looping)
  17433. {
  17434. const int newStart = start % (int) reader->lengthInSamples;
  17435. const int newEnd = (start + info.numSamples) % (int) reader->lengthInSamples;
  17436. if (newEnd > newStart)
  17437. {
  17438. info.buffer->readFromAudioReader (reader,
  17439. info.startSample,
  17440. newEnd - newStart,
  17441. newStart,
  17442. true, true);
  17443. }
  17444. else
  17445. {
  17446. const int endSamps = (int) reader->lengthInSamples - newStart;
  17447. info.buffer->readFromAudioReader (reader,
  17448. info.startSample,
  17449. endSamps,
  17450. newStart,
  17451. true, true);
  17452. info.buffer->readFromAudioReader (reader,
  17453. info.startSample + endSamps,
  17454. newEnd,
  17455. 0,
  17456. true, true);
  17457. }
  17458. nextPlayPos = newEnd;
  17459. }
  17460. else
  17461. {
  17462. info.buffer->readFromAudioReader (reader,
  17463. info.startSample,
  17464. info.numSamples,
  17465. start,
  17466. true, true);
  17467. nextPlayPos += info.numSamples;
  17468. }
  17469. }
  17470. }
  17471. END_JUCE_NAMESPACE
  17472. /********* End of inlined file: juce_AudioFormatReaderSource.cpp *********/
  17473. /********* Start of inlined file: juce_AudioSourcePlayer.cpp *********/
  17474. BEGIN_JUCE_NAMESPACE
  17475. AudioSourcePlayer::AudioSourcePlayer()
  17476. : source (0),
  17477. sampleRate (0),
  17478. bufferSize (0),
  17479. tempBuffer (2, 8),
  17480. lastGain (1.0f),
  17481. gain (1.0f)
  17482. {
  17483. }
  17484. AudioSourcePlayer::~AudioSourcePlayer()
  17485. {
  17486. setSource (0);
  17487. }
  17488. void AudioSourcePlayer::setSource (AudioSource* newSource)
  17489. {
  17490. if (source != newSource)
  17491. {
  17492. AudioSource* const oldSource = source;
  17493. if (newSource != 0 && bufferSize > 0 && sampleRate > 0)
  17494. newSource->prepareToPlay (bufferSize, sampleRate);
  17495. {
  17496. const ScopedLock sl (readLock);
  17497. source = newSource;
  17498. }
  17499. if (oldSource != 0)
  17500. oldSource->releaseResources();
  17501. }
  17502. }
  17503. void AudioSourcePlayer::setGain (const float newGain) throw()
  17504. {
  17505. gain = newGain;
  17506. }
  17507. void AudioSourcePlayer::audioDeviceIOCallback (const float** inputChannelData,
  17508. int totalNumInputChannels,
  17509. float** outputChannelData,
  17510. int totalNumOutputChannels,
  17511. int numSamples)
  17512. {
  17513. // these should have been prepared by audioDeviceAboutToStart()...
  17514. jassert (sampleRate > 0 && bufferSize > 0);
  17515. const ScopedLock sl (readLock);
  17516. if (source != 0)
  17517. {
  17518. AudioSourceChannelInfo info;
  17519. int i, numActiveChans = 0, numInputs = 0, numOutputs = 0;
  17520. // messy stuff needed to compact the channels down into an array
  17521. // of non-zero pointers..
  17522. for (i = 0; i < totalNumInputChannels; ++i)
  17523. {
  17524. if (inputChannelData[i] != 0)
  17525. {
  17526. inputChans [numInputs++] = inputChannelData[i];
  17527. if (numInputs >= numElementsInArray (inputChans))
  17528. break;
  17529. }
  17530. }
  17531. for (i = 0; i < totalNumOutputChannels; ++i)
  17532. {
  17533. if (outputChannelData[i] != 0)
  17534. {
  17535. outputChans [numOutputs++] = outputChannelData[i];
  17536. if (numOutputs >= numElementsInArray (outputChans))
  17537. break;
  17538. }
  17539. }
  17540. if (numInputs > numOutputs)
  17541. {
  17542. // if there aren't enough output channels for the number of
  17543. // inputs, we need to create some temporary extra ones (can't
  17544. // use the input data in case it gets written to)
  17545. tempBuffer.setSize (numInputs - numOutputs, numSamples,
  17546. false, false, true);
  17547. for (i = 0; i < numOutputs; ++i)
  17548. {
  17549. channels[numActiveChans] = outputChans[i];
  17550. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  17551. ++numActiveChans;
  17552. }
  17553. for (i = numOutputs; i < numInputs; ++i)
  17554. {
  17555. channels[numActiveChans] = tempBuffer.getSampleData (i - numOutputs, 0);
  17556. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  17557. ++numActiveChans;
  17558. }
  17559. }
  17560. else
  17561. {
  17562. for (i = 0; i < numInputs; ++i)
  17563. {
  17564. channels[numActiveChans] = outputChans[i];
  17565. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  17566. ++numActiveChans;
  17567. }
  17568. for (i = numInputs; i < numOutputs; ++i)
  17569. {
  17570. channels[numActiveChans] = outputChans[i];
  17571. zeromem (channels[numActiveChans], sizeof (float) * numSamples);
  17572. ++numActiveChans;
  17573. }
  17574. }
  17575. AudioSampleBuffer buffer (channels, numActiveChans, numSamples);
  17576. info.buffer = &buffer;
  17577. info.startSample = 0;
  17578. info.numSamples = numSamples;
  17579. source->getNextAudioBlock (info);
  17580. for (i = info.buffer->getNumChannels(); --i >= 0;)
  17581. info.buffer->applyGainRamp (i, info.startSample, info.numSamples, lastGain, gain);
  17582. lastGain = gain;
  17583. }
  17584. else
  17585. {
  17586. for (int i = 0; i < totalNumOutputChannels; ++i)
  17587. if (outputChannelData[i] != 0)
  17588. zeromem (outputChannelData[i], sizeof (float) * numSamples);
  17589. }
  17590. }
  17591. void AudioSourcePlayer::audioDeviceAboutToStart (AudioIODevice* device)
  17592. {
  17593. sampleRate = device->getCurrentSampleRate();
  17594. bufferSize = device->getCurrentBufferSizeSamples();
  17595. zeromem (channels, sizeof (channels));
  17596. if (source != 0)
  17597. source->prepareToPlay (bufferSize, sampleRate);
  17598. }
  17599. void AudioSourcePlayer::audioDeviceStopped()
  17600. {
  17601. if (source != 0)
  17602. source->releaseResources();
  17603. sampleRate = 0.0;
  17604. bufferSize = 0;
  17605. tempBuffer.setSize (2, 8);
  17606. }
  17607. END_JUCE_NAMESPACE
  17608. /********* End of inlined file: juce_AudioSourcePlayer.cpp *********/
  17609. /********* Start of inlined file: juce_AudioTransportSource.cpp *********/
  17610. BEGIN_JUCE_NAMESPACE
  17611. AudioTransportSource::AudioTransportSource()
  17612. : source (0),
  17613. resamplerSource (0),
  17614. bufferingSource (0),
  17615. positionableSource (0),
  17616. masterSource (0),
  17617. gain (1.0f),
  17618. lastGain (1.0f),
  17619. playing (false),
  17620. stopped (true),
  17621. sampleRate (44100.0),
  17622. sourceSampleRate (0.0),
  17623. blockSize (128),
  17624. readAheadBufferSize (0),
  17625. isPrepared (false),
  17626. inputStreamEOF (false)
  17627. {
  17628. }
  17629. AudioTransportSource::~AudioTransportSource()
  17630. {
  17631. setSource (0);
  17632. releaseResources();
  17633. }
  17634. void AudioTransportSource::setSource (PositionableAudioSource* const newSource,
  17635. int readAheadBufferSize_,
  17636. double sourceSampleRateToCorrectFor)
  17637. {
  17638. if (source == newSource)
  17639. {
  17640. if (source == 0)
  17641. return;
  17642. setSource (0, 0, 0); // deselect and reselect to avoid releasing resources wrongly
  17643. }
  17644. readAheadBufferSize = readAheadBufferSize_;
  17645. sourceSampleRate = sourceSampleRateToCorrectFor;
  17646. ResamplingAudioSource* newResamplerSource = 0;
  17647. BufferingAudioSource* newBufferingSource = 0;
  17648. PositionableAudioSource* newPositionableSource = 0;
  17649. AudioSource* newMasterSource = 0;
  17650. ResamplingAudioSource* oldResamplerSource = resamplerSource;
  17651. BufferingAudioSource* oldBufferingSource = bufferingSource;
  17652. AudioSource* oldMasterSource = masterSource;
  17653. if (newSource != 0)
  17654. {
  17655. newPositionableSource = newSource;
  17656. if (readAheadBufferSize_ > 0)
  17657. newPositionableSource = newBufferingSource
  17658. = new BufferingAudioSource (newPositionableSource, false, readAheadBufferSize_);
  17659. newPositionableSource->setNextReadPosition (0);
  17660. if (sourceSampleRateToCorrectFor != 0)
  17661. newMasterSource = newResamplerSource
  17662. = new ResamplingAudioSource (newPositionableSource, false);
  17663. else
  17664. newMasterSource = newPositionableSource;
  17665. if (isPrepared)
  17666. {
  17667. if (newResamplerSource != 0 && sourceSampleRate > 0 && sampleRate > 0)
  17668. newResamplerSource->setResamplingRatio (sourceSampleRate / sampleRate);
  17669. newMasterSource->prepareToPlay (blockSize, sampleRate);
  17670. }
  17671. }
  17672. {
  17673. const ScopedLock sl (callbackLock);
  17674. source = newSource;
  17675. resamplerSource = newResamplerSource;
  17676. bufferingSource = newBufferingSource;
  17677. masterSource = newMasterSource;
  17678. positionableSource = newPositionableSource;
  17679. playing = false;
  17680. }
  17681. if (oldMasterSource != 0)
  17682. oldMasterSource->releaseResources();
  17683. delete oldResamplerSource;
  17684. delete oldBufferingSource;
  17685. }
  17686. void AudioTransportSource::start()
  17687. {
  17688. if ((! playing) && masterSource != 0)
  17689. {
  17690. callbackLock.enter();
  17691. playing = true;
  17692. stopped = false;
  17693. inputStreamEOF = false;
  17694. callbackLock.exit();
  17695. sendChangeMessage (this);
  17696. }
  17697. }
  17698. void AudioTransportSource::stop()
  17699. {
  17700. if (playing)
  17701. {
  17702. callbackLock.enter();
  17703. playing = false;
  17704. callbackLock.exit();
  17705. int n = 500;
  17706. while (--n >= 0 && ! stopped)
  17707. Thread::sleep (2);
  17708. sendChangeMessage (this);
  17709. }
  17710. }
  17711. void AudioTransportSource::setPosition (double newPosition)
  17712. {
  17713. if (sampleRate > 0.0)
  17714. setNextReadPosition (roundDoubleToInt (newPosition * sampleRate));
  17715. }
  17716. double AudioTransportSource::getCurrentPosition() const
  17717. {
  17718. if (sampleRate > 0.0)
  17719. return getNextReadPosition() / sampleRate;
  17720. else
  17721. return 0.0;
  17722. }
  17723. void AudioTransportSource::setNextReadPosition (int newPosition)
  17724. {
  17725. if (positionableSource != 0)
  17726. {
  17727. if (sampleRate > 0 && sourceSampleRate > 0)
  17728. newPosition = roundDoubleToInt (newPosition * sourceSampleRate / sampleRate);
  17729. positionableSource->setNextReadPosition (newPosition);
  17730. }
  17731. }
  17732. int AudioTransportSource::getNextReadPosition() const
  17733. {
  17734. if (positionableSource != 0)
  17735. {
  17736. const double ratio = (sampleRate > 0 && sourceSampleRate > 0) ? sampleRate / sourceSampleRate : 1.0;
  17737. return roundDoubleToInt (positionableSource->getNextReadPosition() * ratio);
  17738. }
  17739. return 0;
  17740. }
  17741. int AudioTransportSource::getTotalLength() const
  17742. {
  17743. const ScopedLock sl (callbackLock);
  17744. if (positionableSource != 0)
  17745. {
  17746. const double ratio = (sampleRate > 0 && sourceSampleRate > 0) ? sampleRate / sourceSampleRate : 1.0;
  17747. return roundDoubleToInt (positionableSource->getTotalLength() * ratio);
  17748. }
  17749. return 0;
  17750. }
  17751. bool AudioTransportSource::isLooping() const
  17752. {
  17753. const ScopedLock sl (callbackLock);
  17754. return positionableSource != 0
  17755. && positionableSource->isLooping();
  17756. }
  17757. void AudioTransportSource::setGain (const float newGain) throw()
  17758. {
  17759. gain = newGain;
  17760. }
  17761. void AudioTransportSource::prepareToPlay (int samplesPerBlockExpected,
  17762. double sampleRate_)
  17763. {
  17764. const ScopedLock sl (callbackLock);
  17765. sampleRate = sampleRate_;
  17766. blockSize = samplesPerBlockExpected;
  17767. if (masterSource != 0)
  17768. masterSource->prepareToPlay (samplesPerBlockExpected, sampleRate);
  17769. if (resamplerSource != 0 && sourceSampleRate != 0)
  17770. resamplerSource->setResamplingRatio (sourceSampleRate / sampleRate);
  17771. isPrepared = true;
  17772. }
  17773. void AudioTransportSource::releaseResources()
  17774. {
  17775. const ScopedLock sl (callbackLock);
  17776. if (masterSource != 0)
  17777. masterSource->releaseResources();
  17778. isPrepared = false;
  17779. }
  17780. void AudioTransportSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  17781. {
  17782. const ScopedLock sl (callbackLock);
  17783. inputStreamEOF = false;
  17784. if (masterSource != 0 && ! stopped)
  17785. {
  17786. masterSource->getNextAudioBlock (info);
  17787. if (! playing)
  17788. {
  17789. // just stopped playing, so fade out the last block..
  17790. for (int i = info.buffer->getNumChannels(); --i >= 0;)
  17791. info.buffer->applyGainRamp (i, info.startSample, jmin (256, info.numSamples), 1.0f, 0.0f);
  17792. if (info.numSamples > 256)
  17793. info.buffer->clear (info.startSample + 256, info.numSamples - 256);
  17794. }
  17795. if (positionableSource->getNextReadPosition() > positionableSource->getTotalLength() + 1
  17796. && ! positionableSource->isLooping())
  17797. {
  17798. playing = false;
  17799. inputStreamEOF = true;
  17800. sendChangeMessage (this);
  17801. }
  17802. stopped = ! playing;
  17803. for (int i = info.buffer->getNumChannels(); --i >= 0;)
  17804. {
  17805. info.buffer->applyGainRamp (i, info.startSample, info.numSamples,
  17806. lastGain, gain);
  17807. }
  17808. }
  17809. else
  17810. {
  17811. info.clearActiveBufferRegion();
  17812. stopped = true;
  17813. }
  17814. lastGain = gain;
  17815. }
  17816. END_JUCE_NAMESPACE
  17817. /********* End of inlined file: juce_AudioTransportSource.cpp *********/
  17818. /********* Start of inlined file: juce_BufferingAudioSource.cpp *********/
  17819. BEGIN_JUCE_NAMESPACE
  17820. class SharedBufferingAudioSourceThread : public DeletedAtShutdown,
  17821. public Thread,
  17822. private Timer
  17823. {
  17824. public:
  17825. SharedBufferingAudioSourceThread()
  17826. : Thread ("Audio Buffer"),
  17827. sources (8)
  17828. {
  17829. }
  17830. ~SharedBufferingAudioSourceThread()
  17831. {
  17832. stopThread (10000);
  17833. clearSingletonInstance();
  17834. }
  17835. juce_DeclareSingleton (SharedBufferingAudioSourceThread, false)
  17836. void addSource (BufferingAudioSource* source)
  17837. {
  17838. const ScopedLock sl (lock);
  17839. if (! sources.contains ((void*) source))
  17840. {
  17841. sources.add ((void*) source);
  17842. startThread();
  17843. stopTimer();
  17844. }
  17845. notify();
  17846. }
  17847. void removeSource (BufferingAudioSource* source)
  17848. {
  17849. const ScopedLock sl (lock);
  17850. sources.removeValue ((void*) source);
  17851. if (sources.size() == 0)
  17852. startTimer (5000);
  17853. }
  17854. private:
  17855. VoidArray sources;
  17856. CriticalSection lock;
  17857. void run()
  17858. {
  17859. while (! threadShouldExit())
  17860. {
  17861. bool busy = false;
  17862. for (int i = sources.size(); --i >= 0;)
  17863. {
  17864. if (threadShouldExit())
  17865. return;
  17866. const ScopedLock sl (lock);
  17867. BufferingAudioSource* const b = (BufferingAudioSource*) sources[i];
  17868. if (b != 0 && b->readNextBufferChunk())
  17869. busy = true;
  17870. }
  17871. if (! busy)
  17872. wait (500);
  17873. }
  17874. }
  17875. void timerCallback()
  17876. {
  17877. stopTimer();
  17878. if (sources.size() == 0)
  17879. deleteInstance();
  17880. }
  17881. SharedBufferingAudioSourceThread (const SharedBufferingAudioSourceThread&);
  17882. const SharedBufferingAudioSourceThread& operator= (const SharedBufferingAudioSourceThread&);
  17883. };
  17884. juce_ImplementSingleton (SharedBufferingAudioSourceThread)
  17885. BufferingAudioSource::BufferingAudioSource (PositionableAudioSource* source_,
  17886. const bool deleteSourceWhenDeleted_,
  17887. int numberOfSamplesToBuffer_)
  17888. : source (source_),
  17889. deleteSourceWhenDeleted (deleteSourceWhenDeleted_),
  17890. numberOfSamplesToBuffer (jmax (1024, numberOfSamplesToBuffer_)),
  17891. buffer (2, 0),
  17892. bufferValidStart (0),
  17893. bufferValidEnd (0),
  17894. nextPlayPos (0),
  17895. wasSourceLooping (false)
  17896. {
  17897. jassert (source_ != 0);
  17898. jassert (numberOfSamplesToBuffer_ > 1024); // not much point using this class if you're
  17899. // not using a larger buffer..
  17900. }
  17901. BufferingAudioSource::~BufferingAudioSource()
  17902. {
  17903. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  17904. if (thread != 0)
  17905. thread->removeSource (this);
  17906. if (deleteSourceWhenDeleted)
  17907. delete source;
  17908. }
  17909. void BufferingAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate_)
  17910. {
  17911. source->prepareToPlay (samplesPerBlockExpected, sampleRate_);
  17912. sampleRate = sampleRate_;
  17913. buffer.setSize (2, jmax (samplesPerBlockExpected * 2, numberOfSamplesToBuffer));
  17914. buffer.clear();
  17915. bufferValidStart = 0;
  17916. bufferValidEnd = 0;
  17917. SharedBufferingAudioSourceThread::getInstance()->addSource (this);
  17918. while (bufferValidEnd - bufferValidStart < jmin (((int) sampleRate_) / 4,
  17919. buffer.getNumSamples() / 2))
  17920. {
  17921. SharedBufferingAudioSourceThread::getInstance()->notify();
  17922. Thread::sleep (5);
  17923. }
  17924. }
  17925. void BufferingAudioSource::releaseResources()
  17926. {
  17927. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  17928. if (thread != 0)
  17929. thread->removeSource (this);
  17930. buffer.setSize (2, 0);
  17931. source->releaseResources();
  17932. }
  17933. void BufferingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  17934. {
  17935. const ScopedLock sl (bufferStartPosLock);
  17936. const int validStart = jlimit (bufferValidStart, bufferValidEnd, nextPlayPos) - nextPlayPos;
  17937. const int validEnd = jlimit (bufferValidStart, bufferValidEnd, nextPlayPos + info.numSamples) - nextPlayPos;
  17938. if (validStart == validEnd)
  17939. {
  17940. // total cache miss
  17941. info.clearActiveBufferRegion();
  17942. }
  17943. else
  17944. {
  17945. if (validStart > 0)
  17946. info.buffer->clear (info.startSample, validStart); // partial cache miss at start
  17947. if (validEnd < info.numSamples)
  17948. info.buffer->clear (info.startSample + validEnd,
  17949. info.numSamples - validEnd); // partial cache miss at end
  17950. if (validStart < validEnd)
  17951. {
  17952. for (int chan = jmin (2, info.buffer->getNumChannels()); --chan >= 0;)
  17953. {
  17954. const int startBufferIndex = (validStart + nextPlayPos) % buffer.getNumSamples();
  17955. const int endBufferIndex = (validEnd + nextPlayPos) % buffer.getNumSamples();
  17956. if (startBufferIndex < endBufferIndex)
  17957. {
  17958. info.buffer->copyFrom (chan, info.startSample + validStart,
  17959. buffer,
  17960. chan, startBufferIndex,
  17961. validEnd - validStart);
  17962. }
  17963. else
  17964. {
  17965. const int initialSize = buffer.getNumSamples() - startBufferIndex;
  17966. info.buffer->copyFrom (chan, info.startSample + validStart,
  17967. buffer,
  17968. chan, startBufferIndex,
  17969. initialSize);
  17970. info.buffer->copyFrom (chan, info.startSample + validStart + initialSize,
  17971. buffer,
  17972. chan, 0,
  17973. (validEnd - validStart) - initialSize);
  17974. }
  17975. }
  17976. }
  17977. nextPlayPos += info.numSamples;
  17978. if (source->isLooping() && nextPlayPos > 0)
  17979. nextPlayPos %= source->getTotalLength();
  17980. }
  17981. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  17982. if (thread != 0)
  17983. thread->notify();
  17984. }
  17985. int BufferingAudioSource::getNextReadPosition() const
  17986. {
  17987. return (source->isLooping() && nextPlayPos > 0)
  17988. ? nextPlayPos % source->getTotalLength()
  17989. : nextPlayPos;
  17990. }
  17991. void BufferingAudioSource::setNextReadPosition (int newPosition)
  17992. {
  17993. const ScopedLock sl (bufferStartPosLock);
  17994. nextPlayPos = newPosition;
  17995. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  17996. if (thread != 0)
  17997. thread->notify();
  17998. }
  17999. bool BufferingAudioSource::readNextBufferChunk()
  18000. {
  18001. bufferStartPosLock.enter();
  18002. if (wasSourceLooping != isLooping())
  18003. {
  18004. wasSourceLooping = isLooping();
  18005. bufferValidStart = 0;
  18006. bufferValidEnd = 0;
  18007. }
  18008. int newBVS = jmax (0, nextPlayPos);
  18009. int newBVE = newBVS + buffer.getNumSamples() - 4;
  18010. int sectionToReadStart = 0;
  18011. int sectionToReadEnd = 0;
  18012. const int maxChunkSize = 2048;
  18013. if (newBVS < bufferValidStart || newBVS >= bufferValidEnd)
  18014. {
  18015. newBVE = jmin (newBVE, newBVS + maxChunkSize);
  18016. sectionToReadStart = newBVS;
  18017. sectionToReadEnd = newBVE;
  18018. bufferValidStart = 0;
  18019. bufferValidEnd = 0;
  18020. }
  18021. else if (abs (newBVS - bufferValidStart) > 512
  18022. || abs (newBVE - bufferValidEnd) > 512)
  18023. {
  18024. newBVE = jmin (newBVE, bufferValidEnd + maxChunkSize);
  18025. sectionToReadStart = bufferValidEnd;
  18026. sectionToReadEnd = newBVE;
  18027. bufferValidStart = newBVS;
  18028. bufferValidEnd = jmin (bufferValidEnd, newBVE);
  18029. }
  18030. bufferStartPosLock.exit();
  18031. if (sectionToReadStart != sectionToReadEnd)
  18032. {
  18033. const int bufferIndexStart = sectionToReadStart % buffer.getNumSamples();
  18034. const int bufferIndexEnd = sectionToReadEnd % buffer.getNumSamples();
  18035. if (bufferIndexStart < bufferIndexEnd)
  18036. {
  18037. readBufferSection (sectionToReadStart,
  18038. sectionToReadEnd - sectionToReadStart,
  18039. bufferIndexStart);
  18040. }
  18041. else
  18042. {
  18043. const int initialSize = buffer.getNumSamples() - bufferIndexStart;
  18044. readBufferSection (sectionToReadStart,
  18045. initialSize,
  18046. bufferIndexStart);
  18047. readBufferSection (sectionToReadStart + initialSize,
  18048. (sectionToReadEnd - sectionToReadStart) - initialSize,
  18049. 0);
  18050. }
  18051. const ScopedLock sl2 (bufferStartPosLock);
  18052. bufferValidStart = newBVS;
  18053. bufferValidEnd = newBVE;
  18054. return true;
  18055. }
  18056. else
  18057. {
  18058. return false;
  18059. }
  18060. }
  18061. void BufferingAudioSource::readBufferSection (int start, int length, int bufferOffset)
  18062. {
  18063. if (source->getNextReadPosition() != start)
  18064. source->setNextReadPosition (start);
  18065. AudioSourceChannelInfo info;
  18066. info.buffer = &buffer;
  18067. info.startSample = bufferOffset;
  18068. info.numSamples = length;
  18069. source->getNextAudioBlock (info);
  18070. }
  18071. END_JUCE_NAMESPACE
  18072. /********* End of inlined file: juce_BufferingAudioSource.cpp *********/
  18073. /********* Start of inlined file: juce_ChannelRemappingAudioSource.cpp *********/
  18074. BEGIN_JUCE_NAMESPACE
  18075. ChannelRemappingAudioSource::ChannelRemappingAudioSource (AudioSource* const source_,
  18076. const bool deleteSourceWhenDeleted_)
  18077. : requiredNumberOfChannels (2),
  18078. source (source_),
  18079. deleteSourceWhenDeleted (deleteSourceWhenDeleted_),
  18080. buffer (2, 16)
  18081. {
  18082. remappedInfo.buffer = &buffer;
  18083. remappedInfo.startSample = 0;
  18084. }
  18085. ChannelRemappingAudioSource::~ChannelRemappingAudioSource()
  18086. {
  18087. if (deleteSourceWhenDeleted)
  18088. delete source;
  18089. }
  18090. void ChannelRemappingAudioSource::setNumberOfChannelsToProduce (const int requiredNumberOfChannels_) throw()
  18091. {
  18092. const ScopedLock sl (lock);
  18093. requiredNumberOfChannels = requiredNumberOfChannels_;
  18094. }
  18095. void ChannelRemappingAudioSource::clearAllMappings() throw()
  18096. {
  18097. const ScopedLock sl (lock);
  18098. remappedInputs.clear();
  18099. remappedOutputs.clear();
  18100. }
  18101. void ChannelRemappingAudioSource::setInputChannelMapping (const int destIndex, const int sourceIndex) throw()
  18102. {
  18103. const ScopedLock sl (lock);
  18104. while (remappedInputs.size() < destIndex)
  18105. remappedInputs.add (-1);
  18106. remappedInputs.set (destIndex, sourceIndex);
  18107. }
  18108. void ChannelRemappingAudioSource::setOutputChannelMapping (const int sourceIndex, const int destIndex) throw()
  18109. {
  18110. const ScopedLock sl (lock);
  18111. while (remappedOutputs.size() < sourceIndex)
  18112. remappedOutputs.add (-1);
  18113. remappedOutputs.set (sourceIndex, destIndex);
  18114. }
  18115. int ChannelRemappingAudioSource::getRemappedInputChannel (const int inputChannelIndex) const throw()
  18116. {
  18117. const ScopedLock sl (lock);
  18118. if (inputChannelIndex >= 0 && inputChannelIndex < remappedInputs.size())
  18119. return remappedInputs.getUnchecked (inputChannelIndex);
  18120. return -1;
  18121. }
  18122. int ChannelRemappingAudioSource::getRemappedOutputChannel (const int outputChannelIndex) const throw()
  18123. {
  18124. const ScopedLock sl (lock);
  18125. if (outputChannelIndex >= 0 && outputChannelIndex < remappedOutputs.size())
  18126. return remappedOutputs .getUnchecked (outputChannelIndex);
  18127. return -1;
  18128. }
  18129. void ChannelRemappingAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  18130. {
  18131. source->prepareToPlay (samplesPerBlockExpected, sampleRate);
  18132. }
  18133. void ChannelRemappingAudioSource::releaseResources()
  18134. {
  18135. source->releaseResources();
  18136. }
  18137. void ChannelRemappingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill)
  18138. {
  18139. const ScopedLock sl (lock);
  18140. buffer.setSize (requiredNumberOfChannels, bufferToFill.numSamples, false, false, true);
  18141. const int numChans = bufferToFill.buffer->getNumChannels();
  18142. int i;
  18143. for (i = 0; i < buffer.getNumChannels(); ++i)
  18144. {
  18145. const int remappedChan = getRemappedInputChannel (i);
  18146. if (remappedChan >= 0 && remappedChan < numChans)
  18147. {
  18148. buffer.copyFrom (i, 0, *bufferToFill.buffer,
  18149. remappedChan,
  18150. bufferToFill.startSample,
  18151. bufferToFill.numSamples);
  18152. }
  18153. else
  18154. {
  18155. buffer.clear (i, 0, bufferToFill.numSamples);
  18156. }
  18157. }
  18158. remappedInfo.numSamples = bufferToFill.numSamples;
  18159. source->getNextAudioBlock (remappedInfo);
  18160. bufferToFill.clearActiveBufferRegion();
  18161. for (i = 0; i < requiredNumberOfChannels; ++i)
  18162. {
  18163. const int remappedChan = getRemappedOutputChannel (i);
  18164. if (remappedChan >= 0 && remappedChan < numChans)
  18165. {
  18166. bufferToFill.buffer->addFrom (remappedChan, bufferToFill.startSample,
  18167. buffer, i, 0, bufferToFill.numSamples);
  18168. }
  18169. }
  18170. }
  18171. XmlElement* ChannelRemappingAudioSource::createXml() const throw()
  18172. {
  18173. XmlElement* e = new XmlElement (T("MAPPINGS"));
  18174. String ins, outs;
  18175. int i;
  18176. const ScopedLock sl (lock);
  18177. for (i = 0; i < remappedInputs.size(); ++i)
  18178. ins << remappedInputs.getUnchecked(i) << T(' ');
  18179. for (i = 0; i < remappedOutputs.size(); ++i)
  18180. outs << remappedOutputs.getUnchecked(i) << T(' ');
  18181. e->setAttribute (T("inputs"), ins.trimEnd());
  18182. e->setAttribute (T("outputs"), outs.trimEnd());
  18183. return e;
  18184. }
  18185. void ChannelRemappingAudioSource::restoreFromXml (const XmlElement& e) throw()
  18186. {
  18187. if (e.hasTagName (T("MAPPINGS")))
  18188. {
  18189. const ScopedLock sl (lock);
  18190. clearAllMappings();
  18191. StringArray ins, outs;
  18192. ins.addTokens (e.getStringAttribute (T("inputs")), false);
  18193. outs.addTokens (e.getStringAttribute (T("outputs")), false);
  18194. int i;
  18195. for (i = 0; i < ins.size(); ++i)
  18196. remappedInputs.add (ins[i].getIntValue());
  18197. for (i = 0; i < outs.size(); ++i)
  18198. remappedOutputs.add (outs[i].getIntValue());
  18199. }
  18200. }
  18201. END_JUCE_NAMESPACE
  18202. /********* End of inlined file: juce_ChannelRemappingAudioSource.cpp *********/
  18203. /********* Start of inlined file: juce_IIRFilterAudioSource.cpp *********/
  18204. BEGIN_JUCE_NAMESPACE
  18205. IIRFilterAudioSource::IIRFilterAudioSource (AudioSource* const inputSource,
  18206. const bool deleteInputWhenDeleted_)
  18207. : input (inputSource),
  18208. deleteInputWhenDeleted (deleteInputWhenDeleted_)
  18209. {
  18210. jassert (inputSource != 0);
  18211. for (int i = 2; --i >= 0;)
  18212. iirFilters.add (new IIRFilter());
  18213. }
  18214. IIRFilterAudioSource::~IIRFilterAudioSource()
  18215. {
  18216. if (deleteInputWhenDeleted)
  18217. delete input;
  18218. }
  18219. void IIRFilterAudioSource::setFilterParameters (const IIRFilter& newSettings)
  18220. {
  18221. for (int i = iirFilters.size(); --i >= 0;)
  18222. iirFilters.getUnchecked(i)->copyCoefficientsFrom (newSettings);
  18223. }
  18224. void IIRFilterAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  18225. {
  18226. input->prepareToPlay (samplesPerBlockExpected, sampleRate);
  18227. for (int i = iirFilters.size(); --i >= 0;)
  18228. iirFilters.getUnchecked(i)->reset();
  18229. }
  18230. void IIRFilterAudioSource::releaseResources()
  18231. {
  18232. input->releaseResources();
  18233. }
  18234. void IIRFilterAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill)
  18235. {
  18236. input->getNextAudioBlock (bufferToFill);
  18237. const int numChannels = bufferToFill.buffer->getNumChannels();
  18238. while (numChannels > iirFilters.size())
  18239. iirFilters.add (new IIRFilter (*iirFilters.getUnchecked (0)));
  18240. for (int i = 0; i < numChannels; ++i)
  18241. iirFilters.getUnchecked(i)
  18242. ->processSamples (bufferToFill.buffer->getSampleData (i, bufferToFill.startSample),
  18243. bufferToFill.numSamples);
  18244. }
  18245. END_JUCE_NAMESPACE
  18246. /********* End of inlined file: juce_IIRFilterAudioSource.cpp *********/
  18247. /********* Start of inlined file: juce_MixerAudioSource.cpp *********/
  18248. BEGIN_JUCE_NAMESPACE
  18249. MixerAudioSource::MixerAudioSource()
  18250. : tempBuffer (2, 0),
  18251. currentSampleRate (0.0),
  18252. bufferSizeExpected (0)
  18253. {
  18254. }
  18255. MixerAudioSource::~MixerAudioSource()
  18256. {
  18257. removeAllInputs();
  18258. }
  18259. void MixerAudioSource::addInputSource (AudioSource* input, const bool deleteWhenRemoved)
  18260. {
  18261. if (input != 0 && ! inputs.contains (input))
  18262. {
  18263. lock.enter();
  18264. double localRate = currentSampleRate;
  18265. int localBufferSize = bufferSizeExpected;
  18266. lock.exit();
  18267. if (localRate != 0.0)
  18268. input->prepareToPlay (localBufferSize, localRate);
  18269. const ScopedLock sl (lock);
  18270. inputsToDelete.setBit (inputs.size(), deleteWhenRemoved);
  18271. inputs.add (input);
  18272. }
  18273. }
  18274. void MixerAudioSource::removeInputSource (AudioSource* input, const bool deleteInput)
  18275. {
  18276. if (input != 0)
  18277. {
  18278. lock.enter();
  18279. const int index = inputs.indexOf ((void*) input);
  18280. if (index >= 0)
  18281. {
  18282. inputsToDelete.shiftBits (index, 1);
  18283. inputs.remove (index);
  18284. }
  18285. lock.exit();
  18286. if (index >= 0)
  18287. {
  18288. input->releaseResources();
  18289. if (deleteInput)
  18290. delete input;
  18291. }
  18292. }
  18293. }
  18294. void MixerAudioSource::removeAllInputs()
  18295. {
  18296. lock.enter();
  18297. VoidArray inputsCopy (inputs);
  18298. BitArray inputsToDeleteCopy (inputsToDelete);
  18299. inputs.clear();
  18300. lock.exit();
  18301. for (int i = inputsCopy.size(); --i >= 0;)
  18302. if (inputsToDeleteCopy[i])
  18303. delete (AudioSource*) inputsCopy[i];
  18304. }
  18305. void MixerAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  18306. {
  18307. tempBuffer.setSize (2, samplesPerBlockExpected);
  18308. const ScopedLock sl (lock);
  18309. currentSampleRate = sampleRate;
  18310. bufferSizeExpected = samplesPerBlockExpected;
  18311. for (int i = inputs.size(); --i >= 0;)
  18312. ((AudioSource*) inputs.getUnchecked(i))->prepareToPlay (samplesPerBlockExpected,
  18313. sampleRate);
  18314. }
  18315. void MixerAudioSource::releaseResources()
  18316. {
  18317. const ScopedLock sl (lock);
  18318. for (int i = inputs.size(); --i >= 0;)
  18319. ((AudioSource*) inputs.getUnchecked(i))->releaseResources();
  18320. tempBuffer.setSize (2, 0);
  18321. currentSampleRate = 0;
  18322. bufferSizeExpected = 0;
  18323. }
  18324. void MixerAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  18325. {
  18326. const ScopedLock sl (lock);
  18327. if (inputs.size() > 0)
  18328. {
  18329. ((AudioSource*) inputs.getUnchecked(0))->getNextAudioBlock (info);
  18330. if (inputs.size() > 1)
  18331. {
  18332. tempBuffer.setSize (jmax (1, info.buffer->getNumChannels()),
  18333. info.buffer->getNumSamples());
  18334. AudioSourceChannelInfo info2;
  18335. info2.buffer = &tempBuffer;
  18336. info2.numSamples = info.numSamples;
  18337. info2.startSample = 0;
  18338. for (int i = 1; i < inputs.size(); ++i)
  18339. {
  18340. ((AudioSource*) inputs.getUnchecked(i))->getNextAudioBlock (info2);
  18341. for (int chan = 0; chan < info.buffer->getNumChannels(); ++chan)
  18342. info.buffer->addFrom (chan, info.startSample, tempBuffer, chan, 0, info.numSamples);
  18343. }
  18344. }
  18345. }
  18346. else
  18347. {
  18348. info.clearActiveBufferRegion();
  18349. }
  18350. }
  18351. END_JUCE_NAMESPACE
  18352. /********* End of inlined file: juce_MixerAudioSource.cpp *********/
  18353. /********* Start of inlined file: juce_ResamplingAudioSource.cpp *********/
  18354. BEGIN_JUCE_NAMESPACE
  18355. ResamplingAudioSource::ResamplingAudioSource (AudioSource* const inputSource,
  18356. const bool deleteInputWhenDeleted_)
  18357. : input (inputSource),
  18358. deleteInputWhenDeleted (deleteInputWhenDeleted_),
  18359. ratio (1.0),
  18360. lastRatio (1.0),
  18361. buffer (2, 0),
  18362. sampsInBuffer (0)
  18363. {
  18364. jassert (input != 0);
  18365. }
  18366. ResamplingAudioSource::~ResamplingAudioSource()
  18367. {
  18368. if (deleteInputWhenDeleted)
  18369. delete input;
  18370. }
  18371. void ResamplingAudioSource::setResamplingRatio (const double samplesInPerOutputSample)
  18372. {
  18373. jassert (samplesInPerOutputSample > 0);
  18374. const ScopedLock sl (ratioLock);
  18375. ratio = jmax (0.0, samplesInPerOutputSample);
  18376. }
  18377. void ResamplingAudioSource::prepareToPlay (int samplesPerBlockExpected,
  18378. double sampleRate)
  18379. {
  18380. const ScopedLock sl (ratioLock);
  18381. input->prepareToPlay (samplesPerBlockExpected, sampleRate);
  18382. buffer.setSize (2, roundDoubleToInt (samplesPerBlockExpected * ratio) + 32);
  18383. buffer.clear();
  18384. sampsInBuffer = 0;
  18385. bufferPos = 0;
  18386. subSampleOffset = 0.0;
  18387. createLowPass (ratio);
  18388. resetFilters();
  18389. }
  18390. void ResamplingAudioSource::releaseResources()
  18391. {
  18392. input->releaseResources();
  18393. buffer.setSize (2, 0);
  18394. }
  18395. void ResamplingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  18396. {
  18397. const ScopedLock sl (ratioLock);
  18398. if (lastRatio != ratio)
  18399. {
  18400. createLowPass (ratio);
  18401. lastRatio = ratio;
  18402. }
  18403. const int sampsNeeded = roundDoubleToInt (info.numSamples * ratio) + 2;
  18404. int bufferSize = buffer.getNumSamples();
  18405. if (bufferSize < sampsNeeded + 8)
  18406. {
  18407. bufferPos %= bufferSize;
  18408. bufferSize = sampsNeeded + 32;
  18409. buffer.setSize (buffer.getNumChannels(), bufferSize, true, true);
  18410. }
  18411. bufferPos %= bufferSize;
  18412. int endOfBufferPos = bufferPos + sampsInBuffer;
  18413. while (sampsNeeded > sampsInBuffer)
  18414. {
  18415. endOfBufferPos %= bufferSize;
  18416. int numToDo = jmin (sampsNeeded - sampsInBuffer,
  18417. bufferSize - endOfBufferPos);
  18418. AudioSourceChannelInfo readInfo;
  18419. readInfo.buffer = &buffer;
  18420. readInfo.numSamples = numToDo;
  18421. readInfo.startSample = endOfBufferPos;
  18422. input->getNextAudioBlock (readInfo);
  18423. if (ratio > 1.0001)
  18424. {
  18425. // for down-sampling, pre-apply the filter..
  18426. for (int i = jmin (2, info.buffer->getNumChannels()); --i >= 0;)
  18427. applyFilter (buffer.getSampleData (i, endOfBufferPos), numToDo, filterStates[i]);
  18428. }
  18429. sampsInBuffer += numToDo;
  18430. endOfBufferPos += numToDo;
  18431. }
  18432. float* dl = info.buffer->getSampleData (0, info.startSample);
  18433. float* dr = (info.buffer->getNumChannels() > 1) ? info.buffer->getSampleData (1, info.startSample) : 0;
  18434. const float* const bl = buffer.getSampleData (0, 0);
  18435. const float* const br = buffer.getSampleData (1, 0);
  18436. int nextPos = (bufferPos + 1) % bufferSize;
  18437. for (int m = info.numSamples; --m >= 0;)
  18438. {
  18439. const float alpha = (float) subSampleOffset;
  18440. const float invAlpha = 1.0f - alpha;
  18441. *dl++ = bl [bufferPos] * invAlpha + bl [nextPos] * alpha;
  18442. if (dr != 0)
  18443. *dr++ = br [bufferPos] * invAlpha + br [nextPos] * alpha;
  18444. subSampleOffset += ratio;
  18445. jassert (sampsInBuffer > 0);
  18446. while (subSampleOffset >= 1.0)
  18447. {
  18448. if (++bufferPos >= bufferSize)
  18449. bufferPos = 0;
  18450. --sampsInBuffer;
  18451. nextPos = (bufferPos + 1) % bufferSize;
  18452. subSampleOffset -= 1.0;
  18453. }
  18454. }
  18455. if (ratio < 0.9999)
  18456. {
  18457. // for up-sampling, apply the filter after transposing..
  18458. for (int i = jmin (2, info.buffer->getNumChannels()); --i >= 0;)
  18459. applyFilter (info.buffer->getSampleData (i, info.startSample), info.numSamples, filterStates[i]);
  18460. }
  18461. else if (ratio <= 1.0001)
  18462. {
  18463. // if the filter's not currently being applied, keep it stoked with the last couple of samples to avoid discontinuities
  18464. for (int i = jmin (2, info.buffer->getNumChannels()); --i >= 0;)
  18465. {
  18466. const float* const endOfBuffer = info.buffer->getSampleData (i, info.startSample + info.numSamples - 1);
  18467. FilterState& fs = filterStates[i];
  18468. if (info.numSamples > 1)
  18469. {
  18470. fs.y2 = fs.x2 = *(endOfBuffer - 1);
  18471. }
  18472. else
  18473. {
  18474. fs.y2 = fs.y1;
  18475. fs.x2 = fs.x1;
  18476. }
  18477. fs.y1 = fs.x1 = *endOfBuffer;
  18478. }
  18479. }
  18480. jassert (sampsInBuffer >= 0);
  18481. }
  18482. void ResamplingAudioSource::createLowPass (const double ratio)
  18483. {
  18484. const double proportionalRate = (ratio > 1.0) ? 0.5 / ratio
  18485. : 0.5 * ratio;
  18486. const double n = 1.0 / tan (double_Pi * jmax (0.001, proportionalRate));
  18487. const double nSquared = n * n;
  18488. const double c1 = 1.0 / (1.0 + sqrt (2.0) * n + nSquared);
  18489. setFilterCoefficients (c1,
  18490. c1 * 2.0f,
  18491. c1,
  18492. 1.0,
  18493. c1 * 2.0 * (1.0 - nSquared),
  18494. c1 * (1.0 - sqrt (2.0) * n + nSquared));
  18495. }
  18496. void ResamplingAudioSource::setFilterCoefficients (double c1, double c2, double c3, double c4, double c5, double c6)
  18497. {
  18498. const double a = 1.0 / c4;
  18499. c1 *= a;
  18500. c2 *= a;
  18501. c3 *= a;
  18502. c5 *= a;
  18503. c6 *= a;
  18504. coefficients[0] = c1;
  18505. coefficients[1] = c2;
  18506. coefficients[2] = c3;
  18507. coefficients[3] = c4;
  18508. coefficients[4] = c5;
  18509. coefficients[5] = c6;
  18510. }
  18511. void ResamplingAudioSource::resetFilters()
  18512. {
  18513. zeromem (filterStates, sizeof (filterStates));
  18514. }
  18515. void ResamplingAudioSource::applyFilter (float* samples, int num, FilterState& fs)
  18516. {
  18517. while (--num >= 0)
  18518. {
  18519. const double in = *samples;
  18520. double out = coefficients[0] * in
  18521. + coefficients[1] * fs.x1
  18522. + coefficients[2] * fs.x2
  18523. - coefficients[4] * fs.y1
  18524. - coefficients[5] * fs.y2;
  18525. #if JUCE_INTEL
  18526. if (! (out < -1.0e-8 || out > 1.0e-8))
  18527. out = 0;
  18528. #endif
  18529. fs.x2 = fs.x1;
  18530. fs.x1 = in;
  18531. fs.y2 = fs.y1;
  18532. fs.y1 = out;
  18533. *samples++ = (float) out;
  18534. }
  18535. }
  18536. END_JUCE_NAMESPACE
  18537. /********* End of inlined file: juce_ResamplingAudioSource.cpp *********/
  18538. /********* Start of inlined file: juce_ToneGeneratorAudioSource.cpp *********/
  18539. BEGIN_JUCE_NAMESPACE
  18540. ToneGeneratorAudioSource::ToneGeneratorAudioSource()
  18541. : frequency (1000.0),
  18542. sampleRate (44100.0),
  18543. currentPhase (0.0),
  18544. phasePerSample (0.0),
  18545. amplitude (0.5f)
  18546. {
  18547. }
  18548. ToneGeneratorAudioSource::~ToneGeneratorAudioSource()
  18549. {
  18550. }
  18551. void ToneGeneratorAudioSource::setAmplitude (const float newAmplitude)
  18552. {
  18553. amplitude = newAmplitude;
  18554. }
  18555. void ToneGeneratorAudioSource::setFrequency (const double newFrequencyHz)
  18556. {
  18557. frequency = newFrequencyHz;
  18558. phasePerSample = 0.0;
  18559. }
  18560. void ToneGeneratorAudioSource::prepareToPlay (int /*samplesPerBlockExpected*/,
  18561. double sampleRate_)
  18562. {
  18563. currentPhase = 0.0;
  18564. phasePerSample = 0.0;
  18565. sampleRate = sampleRate_;
  18566. }
  18567. void ToneGeneratorAudioSource::releaseResources()
  18568. {
  18569. }
  18570. void ToneGeneratorAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  18571. {
  18572. if (phasePerSample == 0.0)
  18573. phasePerSample = double_Pi * 2.0 / (sampleRate / frequency);
  18574. for (int i = 0; i < info.numSamples; ++i)
  18575. {
  18576. const float sample = amplitude * (float) sin (currentPhase);
  18577. currentPhase += phasePerSample;
  18578. for (int j = info.buffer->getNumChannels(); --j >= 0;)
  18579. *info.buffer->getSampleData (j, info.startSample + i) = sample;
  18580. }
  18581. }
  18582. END_JUCE_NAMESPACE
  18583. /********* End of inlined file: juce_ToneGeneratorAudioSource.cpp *********/
  18584. /********* Start of inlined file: juce_AudioDeviceManager.cpp *********/
  18585. BEGIN_JUCE_NAMESPACE
  18586. AudioDeviceManager::AudioDeviceSetup::AudioDeviceSetup()
  18587. : sampleRate (0),
  18588. bufferSize (0),
  18589. useDefaultInputChannels (true),
  18590. useDefaultOutputChannels (true)
  18591. {
  18592. }
  18593. bool AudioDeviceManager::AudioDeviceSetup::operator== (const AudioDeviceManager::AudioDeviceSetup& other) const
  18594. {
  18595. return outputDeviceName == other.outputDeviceName
  18596. && inputDeviceName == other.inputDeviceName
  18597. && sampleRate == other.sampleRate
  18598. && bufferSize == other.bufferSize
  18599. && inputChannels == other.inputChannels
  18600. && useDefaultInputChannels == other.useDefaultInputChannels
  18601. && outputChannels == other.outputChannels
  18602. && useDefaultOutputChannels == other.useDefaultOutputChannels;
  18603. }
  18604. AudioDeviceManager::AudioDeviceManager()
  18605. : currentAudioDevice (0),
  18606. numInputChansNeeded (0),
  18607. numOutputChansNeeded (2),
  18608. lastExplicitSettings (0),
  18609. listNeedsScanning (true),
  18610. useInputNames (false),
  18611. inputLevelMeasurementEnabledCount (0),
  18612. inputLevel (0),
  18613. testSound (0),
  18614. tempBuffer (2, 2),
  18615. enabledMidiInputs (4),
  18616. midiCallbacks (4),
  18617. midiCallbackDevices (4),
  18618. defaultMidiOutput (0),
  18619. cpuUsageMs (0),
  18620. timeToCpuScale (0)
  18621. {
  18622. callbackHandler.owner = this;
  18623. }
  18624. AudioDeviceManager::~AudioDeviceManager()
  18625. {
  18626. deleteAndZero (currentAudioDevice);
  18627. deleteAndZero (defaultMidiOutput);
  18628. delete lastExplicitSettings;
  18629. delete testSound;
  18630. }
  18631. void AudioDeviceManager::createDeviceTypesIfNeeded()
  18632. {
  18633. if (availableDeviceTypes.size() == 0)
  18634. {
  18635. createAudioDeviceTypes (availableDeviceTypes);
  18636. while (lastDeviceTypeConfigs.size() < availableDeviceTypes.size())
  18637. lastDeviceTypeConfigs.add (new AudioDeviceSetup());
  18638. if (availableDeviceTypes.size() > 0)
  18639. currentDeviceType = availableDeviceTypes.getUnchecked(0)->getTypeName();
  18640. }
  18641. }
  18642. const OwnedArray <AudioIODeviceType>& AudioDeviceManager::getAvailableDeviceTypes()
  18643. {
  18644. scanDevicesIfNeeded();
  18645. return availableDeviceTypes;
  18646. }
  18647. AudioIODeviceType* juce_createAudioIODeviceType_CoreAudio();
  18648. AudioIODeviceType* juce_createAudioIODeviceType_WASAPI();
  18649. AudioIODeviceType* juce_createAudioIODeviceType_DirectSound();
  18650. AudioIODeviceType* juce_createAudioIODeviceType_ASIO();
  18651. AudioIODeviceType* juce_createAudioIODeviceType_ALSA();
  18652. void AudioDeviceManager::createAudioDeviceTypes (OwnedArray <AudioIODeviceType>& list)
  18653. {
  18654. #if JUCE_WIN32
  18655. #if JUCE_WASAPI
  18656. if (SystemStats::getOperatingSystemType() >= SystemStats::WinVista)
  18657. list.add (juce_createAudioIODeviceType_WASAPI());
  18658. #endif
  18659. #if JUCE_DIRECTSOUND
  18660. list.add (juce_createAudioIODeviceType_DirectSound());
  18661. #endif
  18662. #if JUCE_ASIO
  18663. list.add (juce_createAudioIODeviceType_ASIO());
  18664. #endif
  18665. #endif
  18666. #if JUCE_MAC
  18667. list.add (juce_createAudioIODeviceType_CoreAudio());
  18668. #endif
  18669. #if JUCE_LINUX && JUCE_ALSA
  18670. list.add (juce_createAudioIODeviceType_ALSA());
  18671. #endif
  18672. }
  18673. const String AudioDeviceManager::initialise (const int numInputChannelsNeeded,
  18674. const int numOutputChannelsNeeded,
  18675. const XmlElement* const e,
  18676. const bool selectDefaultDeviceOnFailure,
  18677. const String& preferredDefaultDeviceName,
  18678. const AudioDeviceSetup* preferredSetupOptions)
  18679. {
  18680. scanDevicesIfNeeded();
  18681. numInputChansNeeded = numInputChannelsNeeded;
  18682. numOutputChansNeeded = numOutputChannelsNeeded;
  18683. if (e != 0 && e->hasTagName (T("DEVICESETUP")))
  18684. {
  18685. delete lastExplicitSettings;
  18686. lastExplicitSettings = new XmlElement (*e);
  18687. String error;
  18688. AudioDeviceSetup setup;
  18689. if (preferredSetupOptions != 0)
  18690. setup = *preferredSetupOptions;
  18691. if (e->getStringAttribute (T("audioDeviceName")).isNotEmpty())
  18692. {
  18693. setup.inputDeviceName = setup.outputDeviceName
  18694. = e->getStringAttribute (T("audioDeviceName"));
  18695. }
  18696. else
  18697. {
  18698. setup.inputDeviceName = e->getStringAttribute (T("audioInputDeviceName"));
  18699. setup.outputDeviceName = e->getStringAttribute (T("audioOutputDeviceName"));
  18700. }
  18701. currentDeviceType = e->getStringAttribute (T("deviceType"));
  18702. if (currentDeviceType.isEmpty())
  18703. {
  18704. AudioIODeviceType* const type = findType (setup.inputDeviceName, setup.outputDeviceName);
  18705. if (type != 0)
  18706. currentDeviceType = type->getTypeName();
  18707. else if (availableDeviceTypes.size() > 0)
  18708. currentDeviceType = availableDeviceTypes[0]->getTypeName();
  18709. }
  18710. setup.bufferSize = e->getIntAttribute (T("audioDeviceBufferSize"));
  18711. setup.sampleRate = e->getDoubleAttribute (T("audioDeviceRate"));
  18712. setup.inputChannels.parseString (e->getStringAttribute (T("audioDeviceInChans"), T("11")), 2);
  18713. setup.outputChannels.parseString (e->getStringAttribute (T("audioDeviceOutChans"), T("11")), 2);
  18714. setup.useDefaultInputChannels = ! e->hasAttribute (T("audioDeviceInChans"));
  18715. setup.useDefaultOutputChannels = ! e->hasAttribute (T("audioDeviceOutChans"));
  18716. error = setAudioDeviceSetup (setup, true);
  18717. midiInsFromXml.clear();
  18718. forEachXmlChildElementWithTagName (*e, c, T("MIDIINPUT"))
  18719. midiInsFromXml.add (c->getStringAttribute (T("name")));
  18720. const StringArray allMidiIns (MidiInput::getDevices());
  18721. for (int i = allMidiIns.size(); --i >= 0;)
  18722. setMidiInputEnabled (allMidiIns[i], midiInsFromXml.contains (allMidiIns[i]));
  18723. if (error.isNotEmpty() && selectDefaultDeviceOnFailure)
  18724. error = initialise (numInputChannelsNeeded, numOutputChannelsNeeded, 0,
  18725. false, preferredDefaultDeviceName);
  18726. setDefaultMidiOutput (e->getStringAttribute (T("defaultMidiOutput")));
  18727. return error;
  18728. }
  18729. else
  18730. {
  18731. AudioDeviceSetup setup;
  18732. if (preferredSetupOptions != 0)
  18733. {
  18734. setup = *preferredSetupOptions;
  18735. }
  18736. else if (preferredDefaultDeviceName.isNotEmpty())
  18737. {
  18738. for (int j = availableDeviceTypes.size(); --j >= 0;)
  18739. {
  18740. AudioIODeviceType* const type = availableDeviceTypes.getUnchecked(j);
  18741. StringArray outs (type->getDeviceNames (false));
  18742. int i;
  18743. for (i = 0; i < outs.size(); ++i)
  18744. {
  18745. if (outs[i].matchesWildcard (preferredDefaultDeviceName, true))
  18746. {
  18747. setup.outputDeviceName = outs[i];
  18748. break;
  18749. }
  18750. }
  18751. StringArray ins (type->getDeviceNames (true));
  18752. for (i = 0; i < ins.size(); ++i)
  18753. {
  18754. if (ins[i].matchesWildcard (preferredDefaultDeviceName, true))
  18755. {
  18756. setup.inputDeviceName = ins[i];
  18757. break;
  18758. }
  18759. }
  18760. }
  18761. }
  18762. insertDefaultDeviceNames (setup);
  18763. return setAudioDeviceSetup (setup, false);
  18764. }
  18765. }
  18766. void AudioDeviceManager::insertDefaultDeviceNames (AudioDeviceSetup& setup) const
  18767. {
  18768. AudioIODeviceType* type = getCurrentDeviceTypeObject();
  18769. if (type != 0)
  18770. {
  18771. if (setup.outputDeviceName.isEmpty())
  18772. setup.outputDeviceName = type->getDeviceNames (false) [type->getDefaultDeviceIndex (false)];
  18773. if (setup.inputDeviceName.isEmpty())
  18774. setup.inputDeviceName = type->getDeviceNames (true) [type->getDefaultDeviceIndex (true)];
  18775. }
  18776. }
  18777. XmlElement* AudioDeviceManager::createStateXml() const
  18778. {
  18779. return lastExplicitSettings != 0 ? new XmlElement (*lastExplicitSettings) : 0;
  18780. }
  18781. void AudioDeviceManager::scanDevicesIfNeeded()
  18782. {
  18783. if (listNeedsScanning)
  18784. {
  18785. listNeedsScanning = false;
  18786. createDeviceTypesIfNeeded();
  18787. for (int i = availableDeviceTypes.size(); --i >= 0;)
  18788. availableDeviceTypes.getUnchecked(i)->scanForDevices();
  18789. }
  18790. }
  18791. AudioIODeviceType* AudioDeviceManager::findType (const String& inputName, const String& outputName)
  18792. {
  18793. scanDevicesIfNeeded();
  18794. for (int i = availableDeviceTypes.size(); --i >= 0;)
  18795. {
  18796. AudioIODeviceType* const type = availableDeviceTypes.getUnchecked(i);
  18797. if ((inputName.isNotEmpty() && type->getDeviceNames (true).contains (inputName, true))
  18798. || (outputName.isNotEmpty() && type->getDeviceNames (false).contains (outputName, true)))
  18799. {
  18800. return type;
  18801. }
  18802. }
  18803. return 0;
  18804. }
  18805. void AudioDeviceManager::getAudioDeviceSetup (AudioDeviceSetup& setup)
  18806. {
  18807. setup = currentSetup;
  18808. }
  18809. void AudioDeviceManager::deleteCurrentDevice()
  18810. {
  18811. deleteAndZero (currentAudioDevice);
  18812. currentSetup.inputDeviceName = String::empty;
  18813. currentSetup.outputDeviceName = String::empty;
  18814. }
  18815. void AudioDeviceManager::setCurrentAudioDeviceType (const String& type,
  18816. const bool treatAsChosenDevice)
  18817. {
  18818. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  18819. {
  18820. if (availableDeviceTypes.getUnchecked(i)->getTypeName() == type
  18821. && currentDeviceType != type)
  18822. {
  18823. currentDeviceType = type;
  18824. AudioDeviceSetup s (*lastDeviceTypeConfigs.getUnchecked(i));
  18825. insertDefaultDeviceNames (s);
  18826. setAudioDeviceSetup (s, treatAsChosenDevice);
  18827. sendChangeMessage (this);
  18828. break;
  18829. }
  18830. }
  18831. }
  18832. AudioIODeviceType* AudioDeviceManager::getCurrentDeviceTypeObject() const
  18833. {
  18834. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  18835. if (availableDeviceTypes[i]->getTypeName() == currentDeviceType)
  18836. return availableDeviceTypes[i];
  18837. return availableDeviceTypes[0];
  18838. }
  18839. const String AudioDeviceManager::setAudioDeviceSetup (const AudioDeviceSetup& newSetup,
  18840. const bool treatAsChosenDevice)
  18841. {
  18842. jassert (&newSetup != &currentSetup); // this will have no effect
  18843. if (newSetup == currentSetup && currentAudioDevice != 0)
  18844. return String::empty;
  18845. if (! (newSetup == currentSetup))
  18846. sendChangeMessage (this);
  18847. stopDevice();
  18848. String error;
  18849. AudioIODeviceType* type = getCurrentDeviceTypeObject();
  18850. if (type == 0 || (newSetup.inputDeviceName.isEmpty()
  18851. && newSetup.outputDeviceName.isEmpty()))
  18852. {
  18853. deleteCurrentDevice();
  18854. if (treatAsChosenDevice)
  18855. updateXml();
  18856. return String::empty;
  18857. }
  18858. const String newInputDeviceName (numInputChansNeeded == 0 ? String::empty : newSetup.inputDeviceName);
  18859. const String newOutputDeviceName (numOutputChansNeeded == 0 ? String::empty : newSetup.outputDeviceName);
  18860. if (currentSetup.inputDeviceName != newInputDeviceName
  18861. || currentSetup.outputDeviceName != newOutputDeviceName
  18862. || currentAudioDevice == 0)
  18863. {
  18864. deleteCurrentDevice();
  18865. scanDevicesIfNeeded();
  18866. if (newOutputDeviceName.isNotEmpty()
  18867. && ! type->getDeviceNames (false).contains (newOutputDeviceName))
  18868. {
  18869. return "No such device: " + newOutputDeviceName;
  18870. }
  18871. if (newInputDeviceName.isNotEmpty()
  18872. && ! type->getDeviceNames (true).contains (newInputDeviceName))
  18873. {
  18874. return "No such device: " + newInputDeviceName;
  18875. }
  18876. currentAudioDevice = type->createDevice (newOutputDeviceName, newInputDeviceName);
  18877. if (currentAudioDevice == 0)
  18878. error = "Can't open the audio device!\n\nThis may be because another application is currently using the same device - if so, you should close any other applications and try again!";
  18879. else
  18880. error = currentAudioDevice->getLastError();
  18881. if (error.isNotEmpty())
  18882. {
  18883. deleteCurrentDevice();
  18884. return error;
  18885. }
  18886. if (newSetup.useDefaultInputChannels)
  18887. {
  18888. inputChannels.clear();
  18889. inputChannels.setRange (0, numInputChansNeeded, true);
  18890. }
  18891. if (newSetup.useDefaultOutputChannels)
  18892. {
  18893. outputChannels.clear();
  18894. outputChannels.setRange (0, numOutputChansNeeded, true);
  18895. }
  18896. if (newInputDeviceName.isEmpty())
  18897. inputChannels.clear();
  18898. if (newOutputDeviceName.isEmpty())
  18899. outputChannels.clear();
  18900. }
  18901. if (! newSetup.useDefaultInputChannels)
  18902. inputChannels = newSetup.inputChannels;
  18903. if (! newSetup.useDefaultOutputChannels)
  18904. outputChannels = newSetup.outputChannels;
  18905. currentSetup = newSetup;
  18906. currentSetup.sampleRate = chooseBestSampleRate (newSetup.sampleRate);
  18907. error = currentAudioDevice->open (inputChannels,
  18908. outputChannels,
  18909. currentSetup.sampleRate,
  18910. currentSetup.bufferSize);
  18911. if (error.isEmpty())
  18912. {
  18913. currentDeviceType = currentAudioDevice->getTypeName();
  18914. currentAudioDevice->start (&callbackHandler);
  18915. currentSetup.sampleRate = currentAudioDevice->getCurrentSampleRate();
  18916. currentSetup.bufferSize = currentAudioDevice->getCurrentBufferSizeSamples();
  18917. currentSetup.inputChannels = currentAudioDevice->getActiveInputChannels();
  18918. currentSetup.outputChannels = currentAudioDevice->getActiveOutputChannels();
  18919. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  18920. if (availableDeviceTypes.getUnchecked (i)->getTypeName() == currentDeviceType)
  18921. *(lastDeviceTypeConfigs.getUnchecked (i)) = currentSetup;
  18922. if (treatAsChosenDevice)
  18923. updateXml();
  18924. }
  18925. else
  18926. {
  18927. deleteCurrentDevice();
  18928. }
  18929. return error;
  18930. }
  18931. double AudioDeviceManager::chooseBestSampleRate (double rate) const
  18932. {
  18933. jassert (currentAudioDevice != 0);
  18934. if (rate > 0)
  18935. {
  18936. bool ok = false;
  18937. for (int i = currentAudioDevice->getNumSampleRates(); --i >= 0;)
  18938. {
  18939. const double sr = currentAudioDevice->getSampleRate (i);
  18940. if (sr == rate)
  18941. ok = true;
  18942. }
  18943. if (! ok)
  18944. rate = 0;
  18945. }
  18946. if (rate == 0)
  18947. {
  18948. double lowestAbove44 = 0.0;
  18949. for (int i = currentAudioDevice->getNumSampleRates(); --i >= 0;)
  18950. {
  18951. const double sr = currentAudioDevice->getSampleRate (i);
  18952. if (sr >= 44100.0 && (lowestAbove44 == 0 || sr < lowestAbove44))
  18953. lowestAbove44 = sr;
  18954. }
  18955. if (lowestAbove44 == 0.0)
  18956. rate = currentAudioDevice->getSampleRate (0);
  18957. else
  18958. rate = lowestAbove44;
  18959. }
  18960. return rate;
  18961. }
  18962. void AudioDeviceManager::stopDevice()
  18963. {
  18964. if (currentAudioDevice != 0)
  18965. currentAudioDevice->stop();
  18966. deleteAndZero (testSound);
  18967. }
  18968. void AudioDeviceManager::closeAudioDevice()
  18969. {
  18970. stopDevice();
  18971. deleteAndZero (currentAudioDevice);
  18972. }
  18973. void AudioDeviceManager::restartLastAudioDevice()
  18974. {
  18975. if (currentAudioDevice == 0)
  18976. {
  18977. if (currentSetup.inputDeviceName.isEmpty()
  18978. && currentSetup.outputDeviceName.isEmpty())
  18979. {
  18980. // This method will only reload the last device that was running
  18981. // before closeAudioDevice() was called - you need to actually open
  18982. // one first, with setAudioDevice().
  18983. jassertfalse
  18984. return;
  18985. }
  18986. AudioDeviceSetup s (currentSetup);
  18987. setAudioDeviceSetup (s, false);
  18988. }
  18989. }
  18990. void AudioDeviceManager::updateXml()
  18991. {
  18992. delete lastExplicitSettings;
  18993. lastExplicitSettings = new XmlElement (T("DEVICESETUP"));
  18994. lastExplicitSettings->setAttribute (T("deviceType"), currentDeviceType);
  18995. lastExplicitSettings->setAttribute (T("audioOutputDeviceName"), currentSetup.outputDeviceName);
  18996. lastExplicitSettings->setAttribute (T("audioInputDeviceName"), currentSetup.inputDeviceName);
  18997. if (currentAudioDevice != 0)
  18998. {
  18999. lastExplicitSettings->setAttribute (T("audioDeviceRate"), currentAudioDevice->getCurrentSampleRate());
  19000. if (currentAudioDevice->getDefaultBufferSize() != currentAudioDevice->getCurrentBufferSizeSamples())
  19001. lastExplicitSettings->setAttribute (T("audioDeviceBufferSize"), currentAudioDevice->getCurrentBufferSizeSamples());
  19002. if (! currentSetup.useDefaultInputChannels)
  19003. lastExplicitSettings->setAttribute (T("audioDeviceInChans"), currentSetup.inputChannels.toString (2));
  19004. if (! currentSetup.useDefaultOutputChannels)
  19005. lastExplicitSettings->setAttribute (T("audioDeviceOutChans"), currentSetup.outputChannels.toString (2));
  19006. }
  19007. for (int i = 0; i < enabledMidiInputs.size(); ++i)
  19008. {
  19009. XmlElement* const m = new XmlElement (T("MIDIINPUT"));
  19010. m->setAttribute (T("name"), enabledMidiInputs[i]->getName());
  19011. lastExplicitSettings->addChildElement (m);
  19012. }
  19013. if (midiInsFromXml.size() > 0)
  19014. {
  19015. // Add any midi devices that have been enabled before, but which aren't currently
  19016. // open because the device has been disconnected.
  19017. const StringArray availableMidiDevices (MidiInput::getDevices());
  19018. for (int i = 0; i < midiInsFromXml.size(); ++i)
  19019. {
  19020. if (! availableMidiDevices.contains (midiInsFromXml[i], true))
  19021. {
  19022. XmlElement* const m = new XmlElement (T("MIDIINPUT"));
  19023. m->setAttribute (T("name"), midiInsFromXml[i]);
  19024. lastExplicitSettings->addChildElement (m);
  19025. }
  19026. }
  19027. }
  19028. if (defaultMidiOutputName.isNotEmpty())
  19029. lastExplicitSettings->setAttribute (T("defaultMidiOutput"), defaultMidiOutputName);
  19030. }
  19031. void AudioDeviceManager::addAudioCallback (AudioIODeviceCallback* newCallback)
  19032. {
  19033. {
  19034. const ScopedLock sl (audioCallbackLock);
  19035. if (callbacks.contains (newCallback))
  19036. return;
  19037. }
  19038. if (currentAudioDevice != 0 && newCallback != 0)
  19039. newCallback->audioDeviceAboutToStart (currentAudioDevice);
  19040. const ScopedLock sl (audioCallbackLock);
  19041. callbacks.add (newCallback);
  19042. }
  19043. void AudioDeviceManager::removeAudioCallback (AudioIODeviceCallback* callback)
  19044. {
  19045. if (callback != 0)
  19046. {
  19047. bool needsDeinitialising = currentAudioDevice != 0;
  19048. {
  19049. const ScopedLock sl (audioCallbackLock);
  19050. needsDeinitialising = needsDeinitialising && callbacks.contains (callback);
  19051. callbacks.removeValue (callback);
  19052. }
  19053. if (needsDeinitialising)
  19054. callback->audioDeviceStopped();
  19055. }
  19056. }
  19057. void AudioDeviceManager::audioDeviceIOCallbackInt (const float** inputChannelData,
  19058. int numInputChannels,
  19059. float** outputChannelData,
  19060. int numOutputChannels,
  19061. int numSamples)
  19062. {
  19063. const ScopedLock sl (audioCallbackLock);
  19064. if (inputLevelMeasurementEnabledCount > 0)
  19065. {
  19066. for (int j = 0; j < numSamples; ++j)
  19067. {
  19068. float s = 0;
  19069. for (int i = 0; i < numInputChannels; ++i)
  19070. s += fabsf (inputChannelData[i][j]);
  19071. s /= numInputChannels;
  19072. const double decayFactor = 0.99992;
  19073. if (s > inputLevel)
  19074. inputLevel = s;
  19075. else if (inputLevel > 0.001f)
  19076. inputLevel *= decayFactor;
  19077. else
  19078. inputLevel = 0;
  19079. }
  19080. }
  19081. if (callbacks.size() > 0)
  19082. {
  19083. const double callbackStartTime = Time::getMillisecondCounterHiRes();
  19084. tempBuffer.setSize (jmax (1, numOutputChannels), jmax (1, numSamples), false, false, true);
  19085. callbacks.getUnchecked(0)->audioDeviceIOCallback (inputChannelData, numInputChannels,
  19086. outputChannelData, numOutputChannels, numSamples);
  19087. float** const tempChans = tempBuffer.getArrayOfChannels();
  19088. for (int i = callbacks.size(); --i > 0;)
  19089. {
  19090. callbacks.getUnchecked(i)->audioDeviceIOCallback (inputChannelData, numInputChannels,
  19091. tempChans, numOutputChannels, numSamples);
  19092. for (int chan = 0; chan < numOutputChannels; ++chan)
  19093. {
  19094. const float* const src = tempChans [chan];
  19095. float* const dst = outputChannelData [chan];
  19096. if (src != 0 && dst != 0)
  19097. for (int j = 0; j < numSamples; ++j)
  19098. dst[j] += src[j];
  19099. }
  19100. }
  19101. const double msTaken = Time::getMillisecondCounterHiRes() - callbackStartTime;
  19102. const double filterAmount = 0.2;
  19103. cpuUsageMs += filterAmount * (msTaken - cpuUsageMs);
  19104. }
  19105. else
  19106. {
  19107. for (int i = 0; i < numOutputChannels; ++i)
  19108. zeromem (outputChannelData[i], sizeof (float) * numSamples);
  19109. }
  19110. if (testSound != 0)
  19111. {
  19112. const int numSamps = jmin (numSamples, testSound->getNumSamples() - testSoundPosition);
  19113. const float* const src = testSound->getSampleData (0, testSoundPosition);
  19114. for (int i = 0; i < numOutputChannels; ++i)
  19115. for (int j = 0; j < numSamps; ++j)
  19116. outputChannelData [i][j] += src[j];
  19117. testSoundPosition += numSamps;
  19118. if (testSoundPosition >= testSound->getNumSamples())
  19119. {
  19120. delete testSound;
  19121. testSound = 0;
  19122. }
  19123. }
  19124. }
  19125. void AudioDeviceManager::audioDeviceAboutToStartInt (AudioIODevice* const device)
  19126. {
  19127. cpuUsageMs = 0;
  19128. const double sampleRate = device->getCurrentSampleRate();
  19129. const int blockSize = device->getCurrentBufferSizeSamples();
  19130. if (sampleRate > 0.0 && blockSize > 0)
  19131. {
  19132. const double msPerBlock = 1000.0 * blockSize / sampleRate;
  19133. timeToCpuScale = (msPerBlock > 0.0) ? (1.0 / msPerBlock) : 0.0;
  19134. }
  19135. {
  19136. const ScopedLock sl (audioCallbackLock);
  19137. for (int i = callbacks.size(); --i >= 0;)
  19138. callbacks.getUnchecked(i)->audioDeviceAboutToStart (device);
  19139. }
  19140. sendChangeMessage (this);
  19141. }
  19142. void AudioDeviceManager::audioDeviceStoppedInt()
  19143. {
  19144. cpuUsageMs = 0;
  19145. timeToCpuScale = 0;
  19146. sendChangeMessage (this);
  19147. const ScopedLock sl (audioCallbackLock);
  19148. for (int i = callbacks.size(); --i >= 0;)
  19149. callbacks.getUnchecked(i)->audioDeviceStopped();
  19150. }
  19151. double AudioDeviceManager::getCpuUsage() const
  19152. {
  19153. return jlimit (0.0, 1.0, timeToCpuScale * cpuUsageMs);
  19154. }
  19155. void AudioDeviceManager::setMidiInputEnabled (const String& name,
  19156. const bool enabled)
  19157. {
  19158. if (enabled != isMidiInputEnabled (name))
  19159. {
  19160. if (enabled)
  19161. {
  19162. const int index = MidiInput::getDevices().indexOf (name);
  19163. if (index >= 0)
  19164. {
  19165. MidiInput* const min = MidiInput::openDevice (index, &callbackHandler);
  19166. if (min != 0)
  19167. {
  19168. enabledMidiInputs.add (min);
  19169. min->start();
  19170. }
  19171. }
  19172. }
  19173. else
  19174. {
  19175. for (int i = enabledMidiInputs.size(); --i >= 0;)
  19176. if (enabledMidiInputs[i]->getName() == name)
  19177. enabledMidiInputs.remove (i);
  19178. }
  19179. updateXml();
  19180. sendChangeMessage (this);
  19181. }
  19182. }
  19183. bool AudioDeviceManager::isMidiInputEnabled (const String& name) const
  19184. {
  19185. for (int i = enabledMidiInputs.size(); --i >= 0;)
  19186. if (enabledMidiInputs[i]->getName() == name)
  19187. return true;
  19188. return false;
  19189. }
  19190. void AudioDeviceManager::addMidiInputCallback (const String& name,
  19191. MidiInputCallback* callback)
  19192. {
  19193. removeMidiInputCallback (name, callback);
  19194. if (name.isEmpty())
  19195. {
  19196. midiCallbacks.add (callback);
  19197. midiCallbackDevices.add (0);
  19198. }
  19199. else
  19200. {
  19201. for (int i = enabledMidiInputs.size(); --i >= 0;)
  19202. {
  19203. if (enabledMidiInputs[i]->getName() == name)
  19204. {
  19205. const ScopedLock sl (midiCallbackLock);
  19206. midiCallbacks.add (callback);
  19207. midiCallbackDevices.add (enabledMidiInputs[i]);
  19208. break;
  19209. }
  19210. }
  19211. }
  19212. }
  19213. void AudioDeviceManager::removeMidiInputCallback (const String& name,
  19214. MidiInputCallback* /*callback*/)
  19215. {
  19216. const ScopedLock sl (midiCallbackLock);
  19217. for (int i = midiCallbacks.size(); --i >= 0;)
  19218. {
  19219. String devName;
  19220. if (midiCallbackDevices.getUnchecked(i) != 0)
  19221. devName = midiCallbackDevices.getUnchecked(i)->getName();
  19222. if (devName == name)
  19223. {
  19224. midiCallbacks.remove (i);
  19225. midiCallbackDevices.remove (i);
  19226. }
  19227. }
  19228. }
  19229. void AudioDeviceManager::handleIncomingMidiMessageInt (MidiInput* source,
  19230. const MidiMessage& message)
  19231. {
  19232. if (! message.isActiveSense())
  19233. {
  19234. const bool isDefaultSource = (source == 0 || source == enabledMidiInputs.getFirst());
  19235. const ScopedLock sl (midiCallbackLock);
  19236. for (int i = midiCallbackDevices.size(); --i >= 0;)
  19237. {
  19238. MidiInput* const md = midiCallbackDevices.getUnchecked(i);
  19239. if (md == source || (md == 0 && isDefaultSource))
  19240. midiCallbacks.getUnchecked(i)->handleIncomingMidiMessage (source, message);
  19241. }
  19242. }
  19243. }
  19244. void AudioDeviceManager::setDefaultMidiOutput (const String& deviceName)
  19245. {
  19246. if (defaultMidiOutputName != deviceName)
  19247. {
  19248. SortedSet <AudioIODeviceCallback*> oldCallbacks;
  19249. {
  19250. const ScopedLock sl (audioCallbackLock);
  19251. oldCallbacks = callbacks;
  19252. callbacks.clear();
  19253. }
  19254. if (currentAudioDevice != 0)
  19255. for (int i = oldCallbacks.size(); --i >= 0;)
  19256. oldCallbacks.getUnchecked(i)->audioDeviceStopped();
  19257. deleteAndZero (defaultMidiOutput);
  19258. defaultMidiOutputName = deviceName;
  19259. if (deviceName.isNotEmpty())
  19260. defaultMidiOutput = MidiOutput::openDevice (MidiOutput::getDevices().indexOf (deviceName));
  19261. if (currentAudioDevice != 0)
  19262. for (int i = oldCallbacks.size(); --i >= 0;)
  19263. oldCallbacks.getUnchecked(i)->audioDeviceAboutToStart (currentAudioDevice);
  19264. {
  19265. const ScopedLock sl (audioCallbackLock);
  19266. callbacks = oldCallbacks;
  19267. }
  19268. updateXml();
  19269. sendChangeMessage (this);
  19270. }
  19271. }
  19272. void AudioDeviceManager::CallbackHandler::audioDeviceIOCallback (const float** inputChannelData,
  19273. int numInputChannels,
  19274. float** outputChannelData,
  19275. int numOutputChannels,
  19276. int numSamples)
  19277. {
  19278. owner->audioDeviceIOCallbackInt (inputChannelData, numInputChannels, outputChannelData, numOutputChannels, numSamples);
  19279. }
  19280. void AudioDeviceManager::CallbackHandler::audioDeviceAboutToStart (AudioIODevice* device)
  19281. {
  19282. owner->audioDeviceAboutToStartInt (device);
  19283. }
  19284. void AudioDeviceManager::CallbackHandler::audioDeviceStopped()
  19285. {
  19286. owner->audioDeviceStoppedInt();
  19287. }
  19288. void AudioDeviceManager::CallbackHandler::handleIncomingMidiMessage (MidiInput* source, const MidiMessage& message)
  19289. {
  19290. owner->handleIncomingMidiMessageInt (source, message);
  19291. }
  19292. void AudioDeviceManager::playTestSound()
  19293. {
  19294. audioCallbackLock.enter();
  19295. AudioSampleBuffer* oldSound = testSound;
  19296. testSound = 0;
  19297. audioCallbackLock.exit();
  19298. delete oldSound;
  19299. testSoundPosition = 0;
  19300. if (currentAudioDevice != 0)
  19301. {
  19302. const double sampleRate = currentAudioDevice->getCurrentSampleRate();
  19303. const int soundLength = (int) sampleRate;
  19304. AudioSampleBuffer* const newSound = new AudioSampleBuffer (1, soundLength);
  19305. float* samples = newSound->getSampleData (0);
  19306. const double frequency = MidiMessage::getMidiNoteInHertz (80);
  19307. const float amplitude = 0.5f;
  19308. const double phasePerSample = double_Pi * 2.0 / (sampleRate / frequency);
  19309. for (int i = 0; i < soundLength; ++i)
  19310. samples[i] = amplitude * (float) sin (i * phasePerSample);
  19311. newSound->applyGainRamp (0, 0, soundLength / 10, 0.0f, 1.0f);
  19312. newSound->applyGainRamp (0, soundLength - soundLength / 4, soundLength / 4, 1.0f, 0.0f);
  19313. const ScopedLock sl (audioCallbackLock);
  19314. testSound = newSound;
  19315. }
  19316. }
  19317. void AudioDeviceManager::enableInputLevelMeasurement (const bool enableMeasurement)
  19318. {
  19319. const ScopedLock sl (audioCallbackLock);
  19320. if (enableMeasurement)
  19321. ++inputLevelMeasurementEnabledCount;
  19322. else
  19323. --inputLevelMeasurementEnabledCount;
  19324. inputLevel = 0;
  19325. }
  19326. double AudioDeviceManager::getCurrentInputLevel() const
  19327. {
  19328. jassert (inputLevelMeasurementEnabledCount > 0); // you need to call enableInputLevelMeasurement() before using this!
  19329. return inputLevel;
  19330. }
  19331. END_JUCE_NAMESPACE
  19332. /********* End of inlined file: juce_AudioDeviceManager.cpp *********/
  19333. /********* Start of inlined file: juce_AudioIODevice.cpp *********/
  19334. BEGIN_JUCE_NAMESPACE
  19335. AudioIODevice::AudioIODevice (const String& deviceName, const String& typeName_)
  19336. : name (deviceName),
  19337. typeName (typeName_)
  19338. {
  19339. }
  19340. AudioIODevice::~AudioIODevice()
  19341. {
  19342. }
  19343. bool AudioIODevice::hasControlPanel() const
  19344. {
  19345. return false;
  19346. }
  19347. bool AudioIODevice::showControlPanel()
  19348. {
  19349. jassertfalse // this should only be called for devices which return true from
  19350. // their hasControlPanel() method.
  19351. return false;
  19352. }
  19353. END_JUCE_NAMESPACE
  19354. /********* End of inlined file: juce_AudioIODevice.cpp *********/
  19355. /********* Start of inlined file: juce_AudioIODeviceType.cpp *********/
  19356. BEGIN_JUCE_NAMESPACE
  19357. AudioIODeviceType::AudioIODeviceType (const tchar* const name)
  19358. : typeName (name)
  19359. {
  19360. }
  19361. AudioIODeviceType::~AudioIODeviceType()
  19362. {
  19363. }
  19364. END_JUCE_NAMESPACE
  19365. /********* End of inlined file: juce_AudioIODeviceType.cpp *********/
  19366. /********* Start of inlined file: juce_MidiOutput.cpp *********/
  19367. BEGIN_JUCE_NAMESPACE
  19368. MidiOutput::MidiOutput() throw()
  19369. : Thread ("midi out"),
  19370. internal (0),
  19371. firstMessage (0)
  19372. {
  19373. }
  19374. MidiOutput::PendingMessage::PendingMessage (const uint8* const data,
  19375. const int len,
  19376. const double sampleNumber) throw()
  19377. : message (data, len, sampleNumber)
  19378. {
  19379. }
  19380. void MidiOutput::sendBlockOfMessages (const MidiBuffer& buffer,
  19381. const double millisecondCounterToStartAt,
  19382. double samplesPerSecondForBuffer) throw()
  19383. {
  19384. // You've got to call startBackgroundThread() for this to actually work..
  19385. jassert (isThreadRunning());
  19386. // this needs to be a value in the future - RTFM for this method!
  19387. jassert (millisecondCounterToStartAt > 0);
  19388. const double timeScaleFactor = 1000.0 / samplesPerSecondForBuffer;
  19389. MidiBuffer::Iterator i (buffer);
  19390. const uint8* data;
  19391. int len, time;
  19392. while (i.getNextEvent (data, len, time))
  19393. {
  19394. const double eventTime = millisecondCounterToStartAt + timeScaleFactor * time;
  19395. PendingMessage* const m
  19396. = new PendingMessage (data, len, eventTime);
  19397. const ScopedLock sl (lock);
  19398. if (firstMessage == 0 || firstMessage->message.getTimeStamp() > eventTime)
  19399. {
  19400. m->next = firstMessage;
  19401. firstMessage = m;
  19402. }
  19403. else
  19404. {
  19405. PendingMessage* mm = firstMessage;
  19406. while (mm->next != 0 && mm->next->message.getTimeStamp() <= eventTime)
  19407. mm = mm->next;
  19408. m->next = mm->next;
  19409. mm->next = m;
  19410. }
  19411. }
  19412. notify();
  19413. }
  19414. void MidiOutput::clearAllPendingMessages() throw()
  19415. {
  19416. const ScopedLock sl (lock);
  19417. while (firstMessage != 0)
  19418. {
  19419. PendingMessage* const m = firstMessage;
  19420. firstMessage = firstMessage->next;
  19421. delete m;
  19422. }
  19423. }
  19424. void MidiOutput::startBackgroundThread() throw()
  19425. {
  19426. startThread (9);
  19427. }
  19428. void MidiOutput::stopBackgroundThread() throw()
  19429. {
  19430. stopThread (5000);
  19431. }
  19432. void MidiOutput::run()
  19433. {
  19434. while (! threadShouldExit())
  19435. {
  19436. uint32 now = Time::getMillisecondCounter();
  19437. uint32 eventTime = 0;
  19438. uint32 timeToWait = 500;
  19439. lock.enter();
  19440. PendingMessage* message = firstMessage;
  19441. if (message != 0)
  19442. {
  19443. eventTime = roundDoubleToInt (message->message.getTimeStamp());
  19444. if (eventTime > now + 20)
  19445. {
  19446. timeToWait = jmax (10, eventTime - now - 100);
  19447. message = 0;
  19448. }
  19449. else
  19450. {
  19451. firstMessage = message->next;
  19452. }
  19453. }
  19454. lock.exit();
  19455. if (message != 0)
  19456. {
  19457. if (eventTime > now)
  19458. {
  19459. Time::waitForMillisecondCounter (eventTime);
  19460. if (threadShouldExit())
  19461. break;
  19462. }
  19463. if (eventTime > now - 200)
  19464. sendMessageNow (message->message);
  19465. delete message;
  19466. }
  19467. else
  19468. {
  19469. jassert (timeToWait < 1000 * 30);
  19470. wait (timeToWait);
  19471. }
  19472. }
  19473. clearAllPendingMessages();
  19474. }
  19475. END_JUCE_NAMESPACE
  19476. /********* End of inlined file: juce_MidiOutput.cpp *********/
  19477. /********* Start of inlined file: juce_AudioDataConverters.cpp *********/
  19478. BEGIN_JUCE_NAMESPACE
  19479. void AudioDataConverters::convertFloatToInt16LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  19480. {
  19481. const double maxVal = (double) 0x7fff;
  19482. char* intData = (char*) dest;
  19483. if (dest != (void*) source || destBytesPerSample <= 4)
  19484. {
  19485. for (int i = 0; i < numSamples; ++i)
  19486. {
  19487. *(uint16*)intData = swapIfBigEndian ((uint16) (short) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  19488. intData += destBytesPerSample;
  19489. }
  19490. }
  19491. else
  19492. {
  19493. intData += destBytesPerSample * numSamples;
  19494. for (int i = numSamples; --i >= 0;)
  19495. {
  19496. intData -= destBytesPerSample;
  19497. *(uint16*)intData = swapIfBigEndian ((uint16) (short) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  19498. }
  19499. }
  19500. }
  19501. void AudioDataConverters::convertFloatToInt16BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  19502. {
  19503. const double maxVal = (double) 0x7fff;
  19504. char* intData = (char*) dest;
  19505. if (dest != (void*) source || destBytesPerSample <= 4)
  19506. {
  19507. for (int i = 0; i < numSamples; ++i)
  19508. {
  19509. *(uint16*)intData = swapIfLittleEndian ((uint16) (short) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  19510. intData += destBytesPerSample;
  19511. }
  19512. }
  19513. else
  19514. {
  19515. intData += destBytesPerSample * numSamples;
  19516. for (int i = numSamples; --i >= 0;)
  19517. {
  19518. intData -= destBytesPerSample;
  19519. *(uint16*)intData = swapIfLittleEndian ((uint16) (short) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  19520. }
  19521. }
  19522. }
  19523. void AudioDataConverters::convertFloatToInt24LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  19524. {
  19525. const double maxVal = (double) 0x7fffff;
  19526. char* intData = (char*) dest;
  19527. if (dest != (void*) source || destBytesPerSample <= 4)
  19528. {
  19529. for (int i = 0; i < numSamples; ++i)
  19530. {
  19531. littleEndian24BitToChars ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  19532. intData += destBytesPerSample;
  19533. }
  19534. }
  19535. else
  19536. {
  19537. intData += destBytesPerSample * numSamples;
  19538. for (int i = numSamples; --i >= 0;)
  19539. {
  19540. intData -= destBytesPerSample;
  19541. littleEndian24BitToChars ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  19542. }
  19543. }
  19544. }
  19545. void AudioDataConverters::convertFloatToInt24BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  19546. {
  19547. const double maxVal = (double) 0x7fffff;
  19548. char* intData = (char*) dest;
  19549. if (dest != (void*) source || destBytesPerSample <= 4)
  19550. {
  19551. for (int i = 0; i < numSamples; ++i)
  19552. {
  19553. bigEndian24BitToChars ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  19554. intData += destBytesPerSample;
  19555. }
  19556. }
  19557. else
  19558. {
  19559. intData += destBytesPerSample * numSamples;
  19560. for (int i = numSamples; --i >= 0;)
  19561. {
  19562. intData -= destBytesPerSample;
  19563. bigEndian24BitToChars ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  19564. }
  19565. }
  19566. }
  19567. void AudioDataConverters::convertFloatToInt32LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  19568. {
  19569. const double maxVal = (double) 0x7fffffff;
  19570. char* intData = (char*) dest;
  19571. if (dest != (void*) source || destBytesPerSample <= 4)
  19572. {
  19573. for (int i = 0; i < numSamples; ++i)
  19574. {
  19575. *(uint32*)intData = swapIfBigEndian ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  19576. intData += destBytesPerSample;
  19577. }
  19578. }
  19579. else
  19580. {
  19581. intData += destBytesPerSample * numSamples;
  19582. for (int i = numSamples; --i >= 0;)
  19583. {
  19584. intData -= destBytesPerSample;
  19585. *(uint32*)intData = swapIfBigEndian ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  19586. }
  19587. }
  19588. }
  19589. void AudioDataConverters::convertFloatToInt32BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  19590. {
  19591. const double maxVal = (double) 0x7fffffff;
  19592. char* intData = (char*) dest;
  19593. if (dest != (void*) source || destBytesPerSample <= 4)
  19594. {
  19595. for (int i = 0; i < numSamples; ++i)
  19596. {
  19597. *(uint32*)intData = swapIfLittleEndian ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  19598. intData += destBytesPerSample;
  19599. }
  19600. }
  19601. else
  19602. {
  19603. intData += destBytesPerSample * numSamples;
  19604. for (int i = numSamples; --i >= 0;)
  19605. {
  19606. intData -= destBytesPerSample;
  19607. *(uint32*)intData = swapIfLittleEndian ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  19608. }
  19609. }
  19610. }
  19611. void AudioDataConverters::convertFloatToFloat32LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  19612. {
  19613. jassert (dest != (void*) source || destBytesPerSample <= 4); // This op can't be performed on in-place data!
  19614. char* d = (char*) dest;
  19615. for (int i = 0; i < numSamples; ++i)
  19616. {
  19617. *(float*)d = source[i];
  19618. #if JUCE_BIG_ENDIAN
  19619. *(uint32*)d = swapByteOrder (*(uint32*)d);
  19620. #endif
  19621. d += destBytesPerSample;
  19622. }
  19623. }
  19624. void AudioDataConverters::convertFloatToFloat32BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  19625. {
  19626. jassert (dest != (void*) source || destBytesPerSample <= 4); // This op can't be performed on in-place data!
  19627. char* d = (char*) dest;
  19628. for (int i = 0; i < numSamples; ++i)
  19629. {
  19630. *(float*)d = source[i];
  19631. #if JUCE_LITTLE_ENDIAN
  19632. *(uint32*)d = swapByteOrder (*(uint32*)d);
  19633. #endif
  19634. d += destBytesPerSample;
  19635. }
  19636. }
  19637. void AudioDataConverters::convertInt16LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  19638. {
  19639. const float scale = 1.0f / 0x7fff;
  19640. const char* intData = (const char*) source;
  19641. if (source != (void*) dest || srcBytesPerSample >= 4)
  19642. {
  19643. for (int i = 0; i < numSamples; ++i)
  19644. {
  19645. dest[i] = scale * (short) swapIfBigEndian (*(uint16*)intData);
  19646. intData += srcBytesPerSample;
  19647. }
  19648. }
  19649. else
  19650. {
  19651. intData += srcBytesPerSample * numSamples;
  19652. for (int i = numSamples; --i >= 0;)
  19653. {
  19654. intData -= srcBytesPerSample;
  19655. dest[i] = scale * (short) swapIfBigEndian (*(uint16*)intData);
  19656. }
  19657. }
  19658. }
  19659. void AudioDataConverters::convertInt16BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  19660. {
  19661. const float scale = 1.0f / 0x7fff;
  19662. const char* intData = (const char*) source;
  19663. if (source != (void*) dest || srcBytesPerSample >= 4)
  19664. {
  19665. for (int i = 0; i < numSamples; ++i)
  19666. {
  19667. dest[i] = scale * (short) swapIfLittleEndian (*(uint16*)intData);
  19668. intData += srcBytesPerSample;
  19669. }
  19670. }
  19671. else
  19672. {
  19673. intData += srcBytesPerSample * numSamples;
  19674. for (int i = numSamples; --i >= 0;)
  19675. {
  19676. intData -= srcBytesPerSample;
  19677. dest[i] = scale * (short) swapIfLittleEndian (*(uint16*)intData);
  19678. }
  19679. }
  19680. }
  19681. void AudioDataConverters::convertInt24LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  19682. {
  19683. const float scale = 1.0f / 0x7fffff;
  19684. const char* intData = (const char*) source;
  19685. if (source != (void*) dest || srcBytesPerSample >= 4)
  19686. {
  19687. for (int i = 0; i < numSamples; ++i)
  19688. {
  19689. dest[i] = scale * (short) littleEndian24Bit (intData);
  19690. intData += srcBytesPerSample;
  19691. }
  19692. }
  19693. else
  19694. {
  19695. intData += srcBytesPerSample * numSamples;
  19696. for (int i = numSamples; --i >= 0;)
  19697. {
  19698. intData -= srcBytesPerSample;
  19699. dest[i] = scale * (short) littleEndian24Bit (intData);
  19700. }
  19701. }
  19702. }
  19703. void AudioDataConverters::convertInt24BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  19704. {
  19705. const float scale = 1.0f / 0x7fffff;
  19706. const char* intData = (const char*) source;
  19707. if (source != (void*) dest || srcBytesPerSample >= 4)
  19708. {
  19709. for (int i = 0; i < numSamples; ++i)
  19710. {
  19711. dest[i] = scale * (short) bigEndian24Bit (intData);
  19712. intData += srcBytesPerSample;
  19713. }
  19714. }
  19715. else
  19716. {
  19717. intData += srcBytesPerSample * numSamples;
  19718. for (int i = numSamples; --i >= 0;)
  19719. {
  19720. intData -= srcBytesPerSample;
  19721. dest[i] = scale * (short) bigEndian24Bit (intData);
  19722. }
  19723. }
  19724. }
  19725. void AudioDataConverters::convertInt32LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  19726. {
  19727. const float scale = 1.0f / 0x7fffffff;
  19728. const char* intData = (const char*) source;
  19729. if (source != (void*) dest || srcBytesPerSample >= 4)
  19730. {
  19731. for (int i = 0; i < numSamples; ++i)
  19732. {
  19733. dest[i] = scale * (int) swapIfBigEndian (*(uint32*) intData);
  19734. intData += srcBytesPerSample;
  19735. }
  19736. }
  19737. else
  19738. {
  19739. intData += srcBytesPerSample * numSamples;
  19740. for (int i = numSamples; --i >= 0;)
  19741. {
  19742. intData -= srcBytesPerSample;
  19743. dest[i] = scale * (int) swapIfBigEndian (*(uint32*) intData);
  19744. }
  19745. }
  19746. }
  19747. void AudioDataConverters::convertInt32BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  19748. {
  19749. const float scale = 1.0f / 0x7fffffff;
  19750. const char* intData = (const char*) source;
  19751. if (source != (void*) dest || srcBytesPerSample >= 4)
  19752. {
  19753. for (int i = 0; i < numSamples; ++i)
  19754. {
  19755. dest[i] = scale * (int) (swapIfLittleEndian (*(uint32*) intData));
  19756. intData += srcBytesPerSample;
  19757. }
  19758. }
  19759. else
  19760. {
  19761. intData += srcBytesPerSample * numSamples;
  19762. for (int i = numSamples; --i >= 0;)
  19763. {
  19764. intData -= srcBytesPerSample;
  19765. dest[i] = scale * (int) (swapIfLittleEndian (*(uint32*) intData));
  19766. }
  19767. }
  19768. }
  19769. void AudioDataConverters::convertFloat32LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  19770. {
  19771. const char* s = (const char*) source;
  19772. for (int i = 0; i < numSamples; ++i)
  19773. {
  19774. dest[i] = *(float*)s;
  19775. #if JUCE_BIG_ENDIAN
  19776. uint32* const d = (uint32*) (dest + i);
  19777. *d = swapByteOrder (*d);
  19778. #endif
  19779. s += srcBytesPerSample;
  19780. }
  19781. }
  19782. void AudioDataConverters::convertFloat32BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  19783. {
  19784. const char* s = (const char*) source;
  19785. for (int i = 0; i < numSamples; ++i)
  19786. {
  19787. dest[i] = *(float*)s;
  19788. #if JUCE_LITTLE_ENDIAN
  19789. uint32* const d = (uint32*) (dest + i);
  19790. *d = swapByteOrder (*d);
  19791. #endif
  19792. s += srcBytesPerSample;
  19793. }
  19794. }
  19795. void AudioDataConverters::convertFloatToFormat (const DataFormat destFormat,
  19796. const float* const source,
  19797. void* const dest,
  19798. const int numSamples)
  19799. {
  19800. switch (destFormat)
  19801. {
  19802. case int16LE:
  19803. convertFloatToInt16LE (source, dest, numSamples);
  19804. break;
  19805. case int16BE:
  19806. convertFloatToInt16BE (source, dest, numSamples);
  19807. break;
  19808. case int24LE:
  19809. convertFloatToInt24LE (source, dest, numSamples);
  19810. break;
  19811. case int24BE:
  19812. convertFloatToInt24BE (source, dest, numSamples);
  19813. break;
  19814. case int32LE:
  19815. convertFloatToInt32LE (source, dest, numSamples);
  19816. break;
  19817. case int32BE:
  19818. convertFloatToInt32BE (source, dest, numSamples);
  19819. break;
  19820. case float32LE:
  19821. convertFloatToFloat32LE (source, dest, numSamples);
  19822. break;
  19823. case float32BE:
  19824. convertFloatToFloat32BE (source, dest, numSamples);
  19825. break;
  19826. default:
  19827. jassertfalse
  19828. break;
  19829. }
  19830. }
  19831. void AudioDataConverters::convertFormatToFloat (const DataFormat sourceFormat,
  19832. const void* const source,
  19833. float* const dest,
  19834. const int numSamples)
  19835. {
  19836. switch (sourceFormat)
  19837. {
  19838. case int16LE:
  19839. convertInt16LEToFloat (source, dest, numSamples);
  19840. break;
  19841. case int16BE:
  19842. convertInt16BEToFloat (source, dest, numSamples);
  19843. break;
  19844. case int24LE:
  19845. convertInt24LEToFloat (source, dest, numSamples);
  19846. break;
  19847. case int24BE:
  19848. convertInt24BEToFloat (source, dest, numSamples);
  19849. break;
  19850. case int32LE:
  19851. convertInt32LEToFloat (source, dest, numSamples);
  19852. break;
  19853. case int32BE:
  19854. convertInt32BEToFloat (source, dest, numSamples);
  19855. break;
  19856. case float32LE:
  19857. convertFloat32LEToFloat (source, dest, numSamples);
  19858. break;
  19859. case float32BE:
  19860. convertFloat32BEToFloat (source, dest, numSamples);
  19861. break;
  19862. default:
  19863. jassertfalse
  19864. break;
  19865. }
  19866. }
  19867. void AudioDataConverters::interleaveSamples (const float** const source,
  19868. float* const dest,
  19869. const int numSamples,
  19870. const int numChannels)
  19871. {
  19872. for (int chan = 0; chan < numChannels; ++chan)
  19873. {
  19874. int i = chan;
  19875. const float* src = source [chan];
  19876. for (int j = 0; j < numSamples; ++j)
  19877. {
  19878. dest [i] = src [j];
  19879. i += numChannels;
  19880. }
  19881. }
  19882. }
  19883. void AudioDataConverters::deinterleaveSamples (const float* const source,
  19884. float** const dest,
  19885. const int numSamples,
  19886. const int numChannels)
  19887. {
  19888. for (int chan = 0; chan < numChannels; ++chan)
  19889. {
  19890. int i = chan;
  19891. float* dst = dest [chan];
  19892. for (int j = 0; j < numSamples; ++j)
  19893. {
  19894. dst [j] = source [i];
  19895. i += numChannels;
  19896. }
  19897. }
  19898. }
  19899. END_JUCE_NAMESPACE
  19900. /********* End of inlined file: juce_AudioDataConverters.cpp *********/
  19901. /********* Start of inlined file: juce_AudioSampleBuffer.cpp *********/
  19902. BEGIN_JUCE_NAMESPACE
  19903. AudioSampleBuffer::AudioSampleBuffer (const int numChannels_,
  19904. const int numSamples) throw()
  19905. : numChannels (numChannels_),
  19906. size (numSamples)
  19907. {
  19908. jassert (numSamples >= 0);
  19909. jassert (numChannels_ > 0);
  19910. allocatedBytes = numChannels * numSamples * sizeof (float) + 32;
  19911. allocatedData = (float*) juce_malloc (allocatedBytes);
  19912. channels = (float**) juce_malloc ((numChannels_ + 1) * sizeof (float*));
  19913. float* chan = allocatedData;
  19914. for (int i = 0; i < numChannels_; ++i)
  19915. {
  19916. channels[i] = chan;
  19917. chan += numSamples;
  19918. }
  19919. channels [numChannels_] = 0;
  19920. }
  19921. AudioSampleBuffer::AudioSampleBuffer (float** dataToReferTo,
  19922. const int numChannels_,
  19923. const int numSamples) throw()
  19924. : numChannels (numChannels_),
  19925. size (numSamples),
  19926. allocatedBytes (0),
  19927. allocatedData (0)
  19928. {
  19929. jassert (numChannels_ > 0);
  19930. // (try to avoid doing a malloc here, as that'll blow up things like Pro-Tools)
  19931. if (numChannels_ < numElementsInArray (preallocatedChannelSpace))
  19932. channels = (float**) preallocatedChannelSpace;
  19933. else
  19934. channels = (float**) juce_malloc ((numChannels_ + 1) * sizeof (float*));
  19935. for (int i = 0; i < numChannels_; ++i)
  19936. {
  19937. // you have to pass in the same number of valid pointers as numChannels
  19938. jassert (dataToReferTo[i] != 0);
  19939. channels[i] = dataToReferTo[i];
  19940. }
  19941. channels [numChannels_] = 0;
  19942. }
  19943. void AudioSampleBuffer::setDataToReferTo (float** dataToReferTo,
  19944. const int numChannels_,
  19945. const int numSamples) throw()
  19946. {
  19947. jassert (numChannels_ > 0);
  19948. juce_free (allocatedData);
  19949. allocatedData = 0;
  19950. allocatedBytes = 0;
  19951. if (numChannels_ > numChannels)
  19952. channels = (float**) juce_realloc (channels, (numChannels_ + 1) * sizeof (float*));
  19953. numChannels = numChannels_;
  19954. size = numSamples;
  19955. for (int i = 0; i < numChannels_; ++i)
  19956. {
  19957. // you have to pass in the same number of valid pointers as numChannels
  19958. jassert (dataToReferTo[i] != 0);
  19959. channels[i] = dataToReferTo[i];
  19960. }
  19961. channels [numChannels_] = 0;
  19962. }
  19963. AudioSampleBuffer::AudioSampleBuffer (const AudioSampleBuffer& other) throw()
  19964. : numChannels (other.numChannels),
  19965. size (other.size)
  19966. {
  19967. channels = (float**) juce_malloc ((other.numChannels + 1) * sizeof (float*));
  19968. if (other.allocatedData != 0)
  19969. {
  19970. allocatedBytes = numChannels * size * sizeof (float) + 32;
  19971. allocatedData = (float*) juce_malloc (allocatedBytes);
  19972. memcpy (allocatedData, other.allocatedData, allocatedBytes);
  19973. float* chan = allocatedData;
  19974. for (int i = 0; i < numChannels; ++i)
  19975. {
  19976. channels[i] = chan;
  19977. chan += size;
  19978. }
  19979. channels [numChannels] = 0;
  19980. }
  19981. else
  19982. {
  19983. allocatedData = 0;
  19984. allocatedBytes = 0;
  19985. memcpy (channels, other.channels, sizeof (channels));
  19986. }
  19987. }
  19988. const AudioSampleBuffer& AudioSampleBuffer::operator= (const AudioSampleBuffer& other) throw()
  19989. {
  19990. if (this != &other)
  19991. {
  19992. setSize (other.getNumChannels(), other.getNumSamples(), false, false, false);
  19993. const int numBytes = size * sizeof (float);
  19994. for (int i = 0; i < numChannels; ++i)
  19995. memcpy (channels[i], other.channels[i], numBytes);
  19996. }
  19997. return *this;
  19998. }
  19999. AudioSampleBuffer::~AudioSampleBuffer() throw()
  20000. {
  20001. juce_free (allocatedData);
  20002. if (channels != (float**) preallocatedChannelSpace)
  20003. juce_free (channels);
  20004. }
  20005. void AudioSampleBuffer::setSize (const int newNumChannels,
  20006. const int newNumSamples,
  20007. const bool keepExistingContent,
  20008. const bool clearExtraSpace,
  20009. const bool avoidReallocating) throw()
  20010. {
  20011. jassert (newNumChannels > 0);
  20012. if (newNumSamples != size || newNumChannels != numChannels)
  20013. {
  20014. const int newTotalBytes = newNumChannels * newNumSamples * sizeof (float) + 32;
  20015. if (keepExistingContent)
  20016. {
  20017. float* const newData = (clearExtraSpace) ? (float*) juce_calloc (newTotalBytes)
  20018. : (float*) juce_malloc (newTotalBytes);
  20019. const int sizeToCopy = sizeof (float) * jmin (newNumSamples, size);
  20020. for (int i = jmin (newNumChannels, numChannels); --i >= 0;)
  20021. {
  20022. memcpy (newData + i * newNumSamples,
  20023. channels[i],
  20024. sizeToCopy);
  20025. }
  20026. juce_free (allocatedData);
  20027. allocatedData = newData;
  20028. allocatedBytes = newTotalBytes;
  20029. }
  20030. else
  20031. {
  20032. if (avoidReallocating && allocatedBytes >= newTotalBytes)
  20033. {
  20034. if (clearExtraSpace)
  20035. zeromem (allocatedData, newTotalBytes);
  20036. }
  20037. else
  20038. {
  20039. juce_free (allocatedData);
  20040. allocatedData = (clearExtraSpace) ? (float*) juce_calloc (newTotalBytes)
  20041. : (float*) juce_malloc (newTotalBytes);
  20042. allocatedBytes = newTotalBytes;
  20043. }
  20044. }
  20045. size = newNumSamples;
  20046. if (newNumChannels > numChannels)
  20047. channels = (float**) juce_realloc (channels, (newNumChannels + 1) * sizeof (float*));
  20048. numChannels = newNumChannels;
  20049. float* chan = allocatedData;
  20050. for (int i = 0; i < newNumChannels; ++i)
  20051. {
  20052. channels[i] = chan;
  20053. chan += size;
  20054. }
  20055. channels [newNumChannels] = 0;
  20056. }
  20057. }
  20058. void AudioSampleBuffer::clear() throw()
  20059. {
  20060. for (int i = 0; i < numChannels; ++i)
  20061. zeromem (channels[i], size * sizeof (float));
  20062. }
  20063. void AudioSampleBuffer::clear (const int startSample,
  20064. const int numSamples) throw()
  20065. {
  20066. jassert (startSample >= 0 && startSample + numSamples <= size);
  20067. for (int i = 0; i < numChannels; ++i)
  20068. zeromem (channels [i] + startSample, numSamples * sizeof (float));
  20069. }
  20070. void AudioSampleBuffer::clear (const int channel,
  20071. const int startSample,
  20072. const int numSamples) throw()
  20073. {
  20074. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  20075. jassert (startSample >= 0 && startSample + numSamples <= size);
  20076. zeromem (channels [channel] + startSample, numSamples * sizeof (float));
  20077. }
  20078. void AudioSampleBuffer::applyGain (const int channel,
  20079. const int startSample,
  20080. int numSamples,
  20081. const float gain) throw()
  20082. {
  20083. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  20084. jassert (startSample >= 0 && startSample + numSamples <= size);
  20085. if (gain != 1.0f)
  20086. {
  20087. float* d = channels [channel] + startSample;
  20088. if (gain == 0.0f)
  20089. {
  20090. zeromem (d, sizeof (float) * numSamples);
  20091. }
  20092. else
  20093. {
  20094. while (--numSamples >= 0)
  20095. *d++ *= gain;
  20096. }
  20097. }
  20098. }
  20099. void AudioSampleBuffer::applyGainRamp (const int channel,
  20100. const int startSample,
  20101. int numSamples,
  20102. float startGain,
  20103. float endGain) throw()
  20104. {
  20105. if (startGain == endGain)
  20106. {
  20107. applyGain (channel, startSample, numSamples, startGain);
  20108. }
  20109. else
  20110. {
  20111. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  20112. jassert (startSample >= 0 && startSample + numSamples <= size);
  20113. const float increment = (endGain - startGain) / numSamples;
  20114. float* d = channels [channel] + startSample;
  20115. while (--numSamples >= 0)
  20116. {
  20117. *d++ *= startGain;
  20118. startGain += increment;
  20119. }
  20120. }
  20121. }
  20122. void AudioSampleBuffer::applyGain (const int startSample,
  20123. const int numSamples,
  20124. const float gain) throw()
  20125. {
  20126. for (int i = 0; i < numChannels; ++i)
  20127. applyGain (i, startSample, numSamples, gain);
  20128. }
  20129. void AudioSampleBuffer::addFrom (const int destChannel,
  20130. const int destStartSample,
  20131. const AudioSampleBuffer& source,
  20132. const int sourceChannel,
  20133. const int sourceStartSample,
  20134. int numSamples,
  20135. const float gain) throw()
  20136. {
  20137. jassert (&source != this || sourceChannel != destChannel);
  20138. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  20139. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  20140. jassert (((unsigned int) sourceChannel) < (unsigned int) source.numChannels);
  20141. jassert (sourceStartSample >= 0 && sourceStartSample + numSamples <= source.size);
  20142. if (gain != 0.0f && numSamples > 0)
  20143. {
  20144. float* d = channels [destChannel] + destStartSample;
  20145. const float* s = source.channels [sourceChannel] + sourceStartSample;
  20146. if (gain != 1.0f)
  20147. {
  20148. while (--numSamples >= 0)
  20149. *d++ += gain * *s++;
  20150. }
  20151. else
  20152. {
  20153. while (--numSamples >= 0)
  20154. *d++ += *s++;
  20155. }
  20156. }
  20157. }
  20158. void AudioSampleBuffer::addFrom (const int destChannel,
  20159. const int destStartSample,
  20160. const float* source,
  20161. int numSamples,
  20162. const float gain) throw()
  20163. {
  20164. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  20165. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  20166. jassert (source != 0);
  20167. if (gain != 0.0f && numSamples > 0)
  20168. {
  20169. float* d = channels [destChannel] + destStartSample;
  20170. if (gain != 1.0f)
  20171. {
  20172. while (--numSamples >= 0)
  20173. *d++ += gain * *source++;
  20174. }
  20175. else
  20176. {
  20177. while (--numSamples >= 0)
  20178. *d++ += *source++;
  20179. }
  20180. }
  20181. }
  20182. void AudioSampleBuffer::addFromWithRamp (const int destChannel,
  20183. const int destStartSample,
  20184. const float* source,
  20185. int numSamples,
  20186. float startGain,
  20187. const float endGain) throw()
  20188. {
  20189. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  20190. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  20191. jassert (source != 0);
  20192. if (startGain == endGain)
  20193. {
  20194. addFrom (destChannel,
  20195. destStartSample,
  20196. source,
  20197. numSamples,
  20198. startGain);
  20199. }
  20200. else
  20201. {
  20202. if (numSamples > 0 && (startGain != 0.0f || endGain != 0.0f))
  20203. {
  20204. const float increment = (endGain - startGain) / numSamples;
  20205. float* d = channels [destChannel] + destStartSample;
  20206. while (--numSamples >= 0)
  20207. {
  20208. *d++ += startGain * *source++;
  20209. startGain += increment;
  20210. }
  20211. }
  20212. }
  20213. }
  20214. void AudioSampleBuffer::copyFrom (const int destChannel,
  20215. const int destStartSample,
  20216. const AudioSampleBuffer& source,
  20217. const int sourceChannel,
  20218. const int sourceStartSample,
  20219. int numSamples) throw()
  20220. {
  20221. jassert (&source != this || sourceChannel != destChannel);
  20222. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  20223. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  20224. jassert (((unsigned int) sourceChannel) < (unsigned int) source.numChannels);
  20225. jassert (sourceStartSample >= 0 && sourceStartSample + numSamples <= source.size);
  20226. if (numSamples > 0)
  20227. {
  20228. memcpy (channels [destChannel] + destStartSample,
  20229. source.channels [sourceChannel] + sourceStartSample,
  20230. sizeof (float) * numSamples);
  20231. }
  20232. }
  20233. void AudioSampleBuffer::copyFrom (const int destChannel,
  20234. const int destStartSample,
  20235. const float* source,
  20236. int numSamples) throw()
  20237. {
  20238. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  20239. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  20240. jassert (source != 0);
  20241. if (numSamples > 0)
  20242. {
  20243. memcpy (channels [destChannel] + destStartSample,
  20244. source,
  20245. sizeof (float) * numSamples);
  20246. }
  20247. }
  20248. void AudioSampleBuffer::copyFrom (const int destChannel,
  20249. const int destStartSample,
  20250. const float* source,
  20251. int numSamples,
  20252. const float gain) throw()
  20253. {
  20254. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  20255. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  20256. jassert (source != 0);
  20257. if (numSamples > 0 && gain != 0)
  20258. {
  20259. float* d = channels [destChannel] + destStartSample;
  20260. if (gain != 1.0f)
  20261. {
  20262. while (--numSamples >= 0)
  20263. *d++ = gain * *source++;
  20264. }
  20265. else
  20266. {
  20267. memcpy (d, source, sizeof (float) * numSamples);
  20268. }
  20269. }
  20270. }
  20271. void AudioSampleBuffer::copyFromWithRamp (const int destChannel,
  20272. const int destStartSample,
  20273. const float* source,
  20274. int numSamples,
  20275. float startGain,
  20276. float endGain) throw()
  20277. {
  20278. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  20279. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  20280. jassert (source != 0);
  20281. if (startGain == endGain)
  20282. {
  20283. copyFrom (destChannel,
  20284. destStartSample,
  20285. source,
  20286. numSamples,
  20287. startGain);
  20288. }
  20289. else
  20290. {
  20291. if (numSamples > 0 && (startGain != 0.0f || endGain != 0.0f))
  20292. {
  20293. const float increment = (endGain - startGain) / numSamples;
  20294. float* d = channels [destChannel] + destStartSample;
  20295. while (--numSamples >= 0)
  20296. {
  20297. *d++ = startGain * *source++;
  20298. startGain += increment;
  20299. }
  20300. }
  20301. }
  20302. }
  20303. void AudioSampleBuffer::findMinMax (const int channel,
  20304. const int startSample,
  20305. int numSamples,
  20306. float& minVal,
  20307. float& maxVal) const throw()
  20308. {
  20309. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  20310. jassert (startSample >= 0 && startSample + numSamples <= size);
  20311. if (numSamples <= 0)
  20312. {
  20313. minVal = 0.0f;
  20314. maxVal = 0.0f;
  20315. }
  20316. else
  20317. {
  20318. const float* d = channels [channel] + startSample;
  20319. float mn = *d++;
  20320. float mx = mn;
  20321. while (--numSamples > 0) // (> 0 rather than >= 0 because we've already taken the first sample)
  20322. {
  20323. const float samp = *d++;
  20324. if (samp > mx)
  20325. mx = samp;
  20326. if (samp < mn)
  20327. mn = samp;
  20328. }
  20329. maxVal = mx;
  20330. minVal = mn;
  20331. }
  20332. }
  20333. float AudioSampleBuffer::getMagnitude (const int channel,
  20334. const int startSample,
  20335. const int numSamples) const throw()
  20336. {
  20337. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  20338. jassert (startSample >= 0 && startSample + numSamples <= size);
  20339. float mn, mx;
  20340. findMinMax (channel, startSample, numSamples, mn, mx);
  20341. return jmax (mn, -mn, mx, -mx);
  20342. }
  20343. float AudioSampleBuffer::getMagnitude (const int startSample,
  20344. const int numSamples) const throw()
  20345. {
  20346. float mag = 0.0f;
  20347. for (int i = 0; i < numChannels; ++i)
  20348. mag = jmax (mag, getMagnitude (i, startSample, numSamples));
  20349. return mag;
  20350. }
  20351. float AudioSampleBuffer::getRMSLevel (const int channel,
  20352. const int startSample,
  20353. const int numSamples) const throw()
  20354. {
  20355. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  20356. jassert (startSample >= 0 && startSample + numSamples <= size);
  20357. if (numSamples <= 0 || channel < 0 || channel >= numChannels)
  20358. return 0.0f;
  20359. const float* const data = channels [channel] + startSample;
  20360. double sum = 0.0;
  20361. for (int i = 0; i < numSamples; ++i)
  20362. {
  20363. const float sample = data [i];
  20364. sum += sample * sample;
  20365. }
  20366. return (float) sqrt (sum / numSamples);
  20367. }
  20368. void AudioSampleBuffer::readFromAudioReader (AudioFormatReader* reader,
  20369. const int startSample,
  20370. const int numSamples,
  20371. const int readerStartSample,
  20372. const bool useLeftChan,
  20373. const bool useRightChan) throw()
  20374. {
  20375. jassert (reader != 0);
  20376. jassert (startSample >= 0 && startSample + numSamples <= size);
  20377. if (numSamples > 0)
  20378. {
  20379. int* chans[3];
  20380. if (useLeftChan == useRightChan)
  20381. {
  20382. chans[0] = (int*) getSampleData (0, startSample);
  20383. chans[1] = (reader->numChannels > 1 && getNumChannels() > 1) ? (int*) getSampleData (1, startSample) : 0;
  20384. }
  20385. else if (useLeftChan || (reader->numChannels == 1))
  20386. {
  20387. chans[0] = (int*) getSampleData (0, startSample);
  20388. chans[1] = 0;
  20389. }
  20390. else if (useRightChan)
  20391. {
  20392. chans[0] = 0;
  20393. chans[1] = (int*) getSampleData (0, startSample);
  20394. }
  20395. chans[2] = 0;
  20396. reader->read (chans, 2, readerStartSample, numSamples, true);
  20397. if (! reader->usesFloatingPointData)
  20398. {
  20399. for (int j = 0; j < 2; ++j)
  20400. {
  20401. float* const d = (float*) (chans[j]);
  20402. if (d != 0)
  20403. {
  20404. const float multiplier = 1.0f / 0x7fffffff;
  20405. for (int i = 0; i < numSamples; ++i)
  20406. d[i] = *(int*)(d + i) * multiplier;
  20407. }
  20408. }
  20409. }
  20410. if (numChannels > 1 && (chans[0] == 0 || chans[1] == 0))
  20411. {
  20412. // if this is a stereo buffer and the source was mono, dupe the first channel..
  20413. memcpy (getSampleData (1, startSample),
  20414. getSampleData (0, startSample),
  20415. sizeof (float) * numSamples);
  20416. }
  20417. }
  20418. }
  20419. void AudioSampleBuffer::writeToAudioWriter (AudioFormatWriter* writer,
  20420. const int startSample,
  20421. const int numSamples) const throw()
  20422. {
  20423. jassert (startSample >= 0 && startSample + numSamples <= size);
  20424. if (numSamples > 0)
  20425. {
  20426. int* chans [3];
  20427. if (writer->isFloatingPoint())
  20428. {
  20429. chans[0] = (int*) getSampleData (0, startSample);
  20430. if (numChannels > 1)
  20431. chans[1] = (int*) getSampleData (1, startSample);
  20432. else
  20433. chans[1] = 0;
  20434. chans[2] = 0;
  20435. writer->write ((const int**) chans, numSamples);
  20436. }
  20437. else
  20438. {
  20439. chans[0] = (int*) juce_malloc (sizeof (int) * numSamples * 2);
  20440. if (numChannels > 1)
  20441. chans[1] = chans[0] + numSamples;
  20442. else
  20443. chans[1] = 0;
  20444. chans[2] = 0;
  20445. for (int j = 0; j < 2; ++j)
  20446. {
  20447. int* const dest = chans[j];
  20448. if (dest != 0)
  20449. {
  20450. const float* const src = channels [j] + startSample;
  20451. for (int i = 0; i < numSamples; ++i)
  20452. {
  20453. const double samp = src[i];
  20454. if (samp <= -1.0)
  20455. dest[i] = INT_MIN;
  20456. else if (samp >= 1.0)
  20457. dest[i] = INT_MAX;
  20458. else
  20459. dest[i] = roundDoubleToInt (INT_MAX * samp);
  20460. }
  20461. }
  20462. }
  20463. writer->write ((const int**) chans, numSamples);
  20464. juce_free (chans[0]);
  20465. }
  20466. }
  20467. }
  20468. END_JUCE_NAMESPACE
  20469. /********* End of inlined file: juce_AudioSampleBuffer.cpp *********/
  20470. /********* Start of inlined file: juce_IIRFilter.cpp *********/
  20471. BEGIN_JUCE_NAMESPACE
  20472. IIRFilter::IIRFilter() throw()
  20473. : active (false)
  20474. {
  20475. reset();
  20476. }
  20477. IIRFilter::IIRFilter (const IIRFilter& other) throw()
  20478. : active (other.active)
  20479. {
  20480. const ScopedLock sl (other.processLock);
  20481. memcpy (coefficients, other.coefficients, sizeof (coefficients));
  20482. reset();
  20483. }
  20484. IIRFilter::~IIRFilter() throw()
  20485. {
  20486. }
  20487. void IIRFilter::reset() throw()
  20488. {
  20489. const ScopedLock sl (processLock);
  20490. x1 = 0;
  20491. x2 = 0;
  20492. y1 = 0;
  20493. y2 = 0;
  20494. }
  20495. float IIRFilter::processSingleSampleRaw (const float in) throw()
  20496. {
  20497. float out = coefficients[0] * in
  20498. + coefficients[1] * x1
  20499. + coefficients[2] * x2
  20500. - coefficients[4] * y1
  20501. - coefficients[5] * y2;
  20502. #if JUCE_INTEL
  20503. if (! (out < -1.0e-8 || out > 1.0e-8))
  20504. out = 0;
  20505. #endif
  20506. x2 = x1;
  20507. x1 = in;
  20508. y2 = y1;
  20509. y1 = out;
  20510. return out;
  20511. }
  20512. void IIRFilter::processSamples (float* const samples,
  20513. const int numSamples) throw()
  20514. {
  20515. const ScopedLock sl (processLock);
  20516. if (active)
  20517. {
  20518. for (int i = 0; i < numSamples; ++i)
  20519. {
  20520. const float in = samples[i];
  20521. float out = coefficients[0] * in
  20522. + coefficients[1] * x1
  20523. + coefficients[2] * x2
  20524. - coefficients[4] * y1
  20525. - coefficients[5] * y2;
  20526. #if JUCE_INTEL
  20527. if (! (out < -1.0e-8 || out > 1.0e-8))
  20528. out = 0;
  20529. #endif
  20530. x2 = x1;
  20531. x1 = in;
  20532. y2 = y1;
  20533. y1 = out;
  20534. samples[i] = out;
  20535. }
  20536. }
  20537. }
  20538. void IIRFilter::makeLowPass (const double sampleRate,
  20539. const double frequency) throw()
  20540. {
  20541. jassert (sampleRate > 0);
  20542. const double n = 1.0 / tan (double_Pi * frequency / sampleRate);
  20543. const double nSquared = n * n;
  20544. const double c1 = 1.0 / (1.0 + sqrt (2.0) * n + nSquared);
  20545. setCoefficients (c1,
  20546. c1 * 2.0f,
  20547. c1,
  20548. 1.0,
  20549. c1 * 2.0 * (1.0 - nSquared),
  20550. c1 * (1.0 - sqrt (2.0) * n + nSquared));
  20551. }
  20552. void IIRFilter::makeHighPass (const double sampleRate,
  20553. const double frequency) throw()
  20554. {
  20555. const double n = tan (double_Pi * frequency / sampleRate);
  20556. const double nSquared = n * n;
  20557. const double c1 = 1.0 / (1.0 + sqrt (2.0) * n + nSquared);
  20558. setCoefficients (c1,
  20559. c1 * -2.0f,
  20560. c1,
  20561. 1.0,
  20562. c1 * 2.0 * (nSquared - 1.0),
  20563. c1 * (1.0 - sqrt (2.0) * n + nSquared));
  20564. }
  20565. void IIRFilter::makeLowShelf (const double sampleRate,
  20566. const double cutOffFrequency,
  20567. const double Q,
  20568. const float gainFactor) throw()
  20569. {
  20570. jassert (sampleRate > 0);
  20571. jassert (Q > 0);
  20572. const double A = jmax (0.0f, gainFactor);
  20573. const double aminus1 = A - 1.0;
  20574. const double aplus1 = A + 1.0;
  20575. const double omega = (double_Pi * 2.0 * jmax (cutOffFrequency, 2.0)) / sampleRate;
  20576. const double coso = cos (omega);
  20577. const double beta = sin (omega) * sqrt (A) / Q;
  20578. const double aminus1TimesCoso = aminus1 * coso;
  20579. setCoefficients (A * (aplus1 - aminus1TimesCoso + beta),
  20580. A * 2.0 * (aminus1 - aplus1 * coso),
  20581. A * (aplus1 - aminus1TimesCoso - beta),
  20582. aplus1 + aminus1TimesCoso + beta,
  20583. -2.0 * (aminus1 + aplus1 * coso),
  20584. aplus1 + aminus1TimesCoso - beta);
  20585. }
  20586. void IIRFilter::makeHighShelf (const double sampleRate,
  20587. const double cutOffFrequency,
  20588. const double Q,
  20589. const float gainFactor) throw()
  20590. {
  20591. jassert (sampleRate > 0);
  20592. jassert (Q > 0);
  20593. const double A = jmax (0.0f, gainFactor);
  20594. const double aminus1 = A - 1.0;
  20595. const double aplus1 = A + 1.0;
  20596. const double omega = (double_Pi * 2.0 * jmax (cutOffFrequency, 2.0)) / sampleRate;
  20597. const double coso = cos (omega);
  20598. const double beta = sin (omega) * sqrt (A) / Q;
  20599. const double aminus1TimesCoso = aminus1 * coso;
  20600. setCoefficients (A * (aplus1 + aminus1TimesCoso + beta),
  20601. A * -2.0 * (aminus1 + aplus1 * coso),
  20602. A * (aplus1 + aminus1TimesCoso - beta),
  20603. aplus1 - aminus1TimesCoso + beta,
  20604. 2.0 * (aminus1 - aplus1 * coso),
  20605. aplus1 - aminus1TimesCoso - beta);
  20606. }
  20607. void IIRFilter::makeBandPass (const double sampleRate,
  20608. const double centreFrequency,
  20609. const double Q,
  20610. const float gainFactor) throw()
  20611. {
  20612. jassert (sampleRate > 0);
  20613. jassert (Q > 0);
  20614. const double A = jmax (0.0f, gainFactor);
  20615. const double omega = (double_Pi * 2.0 * jmax (centreFrequency, 2.0)) / sampleRate;
  20616. const double alpha = 0.5 * sin (omega) / Q;
  20617. const double c2 = -2.0 * cos (omega);
  20618. const double alphaTimesA = alpha * A;
  20619. const double alphaOverA = alpha / A;
  20620. setCoefficients (1.0 + alphaTimesA,
  20621. c2,
  20622. 1.0 - alphaTimesA,
  20623. 1.0 + alphaOverA,
  20624. c2,
  20625. 1.0 - alphaOverA);
  20626. }
  20627. void IIRFilter::makeInactive() throw()
  20628. {
  20629. const ScopedLock sl (processLock);
  20630. active = false;
  20631. }
  20632. void IIRFilter::copyCoefficientsFrom (const IIRFilter& other) throw()
  20633. {
  20634. const ScopedLock sl (processLock);
  20635. memcpy (coefficients, other.coefficients, sizeof (coefficients));
  20636. active = other.active;
  20637. }
  20638. void IIRFilter::setCoefficients (double c1,
  20639. double c2,
  20640. double c3,
  20641. double c4,
  20642. double c5,
  20643. double c6) throw()
  20644. {
  20645. const double a = 1.0 / c4;
  20646. c1 *= a;
  20647. c2 *= a;
  20648. c3 *= a;
  20649. c5 *= a;
  20650. c6 *= a;
  20651. const ScopedLock sl (processLock);
  20652. coefficients[0] = (float) c1;
  20653. coefficients[1] = (float) c2;
  20654. coefficients[2] = (float) c3;
  20655. coefficients[3] = (float) c4;
  20656. coefficients[4] = (float) c5;
  20657. coefficients[5] = (float) c6;
  20658. active = true;
  20659. }
  20660. END_JUCE_NAMESPACE
  20661. /********* End of inlined file: juce_IIRFilter.cpp *********/
  20662. /********* Start of inlined file: juce_MidiBuffer.cpp *********/
  20663. BEGIN_JUCE_NAMESPACE
  20664. MidiBuffer::MidiBuffer() throw()
  20665. : ArrayAllocationBase <uint8> (32),
  20666. bytesUsed (0)
  20667. {
  20668. }
  20669. MidiBuffer::MidiBuffer (const MidiMessage& message) throw()
  20670. : ArrayAllocationBase <uint8> (32),
  20671. bytesUsed (0)
  20672. {
  20673. addEvent (message, 0);
  20674. }
  20675. MidiBuffer::MidiBuffer (const MidiBuffer& other) throw()
  20676. : ArrayAllocationBase <uint8> (32),
  20677. bytesUsed (other.bytesUsed)
  20678. {
  20679. ensureAllocatedSize (bytesUsed);
  20680. memcpy (elements, other.elements, bytesUsed);
  20681. }
  20682. const MidiBuffer& MidiBuffer::operator= (const MidiBuffer& other) throw()
  20683. {
  20684. if (this != &other)
  20685. {
  20686. bytesUsed = other.bytesUsed;
  20687. ensureAllocatedSize (bytesUsed);
  20688. if (bytesUsed > 0)
  20689. memcpy (elements, other.elements, bytesUsed);
  20690. }
  20691. return *this;
  20692. }
  20693. void MidiBuffer::swap (MidiBuffer& other)
  20694. {
  20695. swapVariables <uint8*> (this->elements, other.elements);
  20696. swapVariables <int> (this->numAllocated, other.numAllocated);
  20697. swapVariables <int> (this->bytesUsed, other.bytesUsed);
  20698. }
  20699. MidiBuffer::~MidiBuffer() throw()
  20700. {
  20701. }
  20702. void MidiBuffer::clear() throw()
  20703. {
  20704. bytesUsed = 0;
  20705. }
  20706. void MidiBuffer::clear (const int startSample,
  20707. const int numSamples) throw()
  20708. {
  20709. uint8* const start = findEventAfter (elements, startSample - 1);
  20710. uint8* const end = findEventAfter (start, startSample + numSamples - 1);
  20711. if (end > start)
  20712. {
  20713. const size_t bytesToMove = (size_t) (bytesUsed - (end - elements));
  20714. if (bytesToMove > 0)
  20715. memmove (start, end, bytesToMove);
  20716. bytesUsed -= (int) (end - start);
  20717. }
  20718. }
  20719. void MidiBuffer::addEvent (const MidiMessage& m,
  20720. const int sampleNumber) throw()
  20721. {
  20722. addEvent (m.getRawData(), m.getRawDataSize(), sampleNumber);
  20723. }
  20724. static int findActualEventLength (const uint8* const data,
  20725. const int maxBytes) throw()
  20726. {
  20727. unsigned int byte = (unsigned int) *data;
  20728. int size = 0;
  20729. if (byte == 0xf0 || byte == 0xf7)
  20730. {
  20731. const uint8* d = data + 1;
  20732. while (d < data + maxBytes)
  20733. if (*d++ == 0xf7)
  20734. break;
  20735. size = (int) (d - data);
  20736. }
  20737. else if (byte == 0xff)
  20738. {
  20739. int n;
  20740. const int bytesLeft = MidiMessage::readVariableLengthVal (data + 1, n);
  20741. size = jmin (maxBytes, n + 2 + bytesLeft);
  20742. }
  20743. else if (byte >= 0x80)
  20744. {
  20745. size = jmin (maxBytes, MidiMessage::getMessageLengthFromFirstByte ((uint8) byte));
  20746. }
  20747. return size;
  20748. }
  20749. void MidiBuffer::addEvent (const uint8* const newData,
  20750. const int maxBytes,
  20751. const int sampleNumber) throw()
  20752. {
  20753. const int numBytes = findActualEventLength (newData, maxBytes);
  20754. if (numBytes > 0)
  20755. {
  20756. ensureAllocatedSize (bytesUsed + numBytes + 6);
  20757. uint8* d = findEventAfter (elements, sampleNumber);
  20758. const size_t bytesToMove = (size_t) (bytesUsed - (d - elements));
  20759. if (bytesToMove > 0)
  20760. memmove (d + numBytes + 6,
  20761. d,
  20762. bytesToMove);
  20763. *(int*) d = sampleNumber;
  20764. d += 4;
  20765. *(uint16*) d = (uint16) numBytes;
  20766. d += 2;
  20767. memcpy (d, newData, numBytes);
  20768. bytesUsed += numBytes + 6;
  20769. }
  20770. }
  20771. void MidiBuffer::addEvents (const MidiBuffer& otherBuffer,
  20772. const int startSample,
  20773. const int numSamples,
  20774. const int sampleDeltaToAdd) throw()
  20775. {
  20776. Iterator i (otherBuffer);
  20777. i.setNextSamplePosition (startSample);
  20778. const uint8* data;
  20779. int size, position;
  20780. while (i.getNextEvent (data, size, position)
  20781. && (position < startSample + numSamples || numSamples < 0))
  20782. {
  20783. addEvent (data, size, position + sampleDeltaToAdd);
  20784. }
  20785. }
  20786. bool MidiBuffer::isEmpty() const throw()
  20787. {
  20788. return bytesUsed == 0;
  20789. }
  20790. int MidiBuffer::getNumEvents() const throw()
  20791. {
  20792. int n = 0;
  20793. const uint8* d = elements;
  20794. const uint8* const end = elements + bytesUsed;
  20795. while (d < end)
  20796. {
  20797. d += 4;
  20798. d += 2 + *(const uint16*) d;
  20799. ++n;
  20800. }
  20801. return n;
  20802. }
  20803. int MidiBuffer::getFirstEventTime() const throw()
  20804. {
  20805. return (bytesUsed > 0) ? *(const int*) elements : 0;
  20806. }
  20807. int MidiBuffer::getLastEventTime() const throw()
  20808. {
  20809. if (bytesUsed == 0)
  20810. return 0;
  20811. const uint8* d = elements;
  20812. const uint8* const endData = d + bytesUsed;
  20813. for (;;)
  20814. {
  20815. const uint8* nextOne = d + 6 + * (const uint16*) (d + 4);
  20816. if (nextOne >= endData)
  20817. return *(const int*) d;
  20818. d = nextOne;
  20819. }
  20820. }
  20821. uint8* MidiBuffer::findEventAfter (uint8* d, const int samplePosition) const throw()
  20822. {
  20823. const uint8* const endData = elements + bytesUsed;
  20824. while (d < endData && *(int*) d <= samplePosition)
  20825. {
  20826. d += 4;
  20827. d += 2 + *(uint16*) d;
  20828. }
  20829. return d;
  20830. }
  20831. MidiBuffer::Iterator::Iterator (const MidiBuffer& buffer) throw()
  20832. : buffer (buffer),
  20833. data (buffer.elements)
  20834. {
  20835. }
  20836. MidiBuffer::Iterator::~Iterator() throw()
  20837. {
  20838. }
  20839. void MidiBuffer::Iterator::setNextSamplePosition (const int samplePosition) throw()
  20840. {
  20841. data = buffer.elements;
  20842. const uint8* dataEnd = buffer.elements + buffer.bytesUsed;
  20843. while (data < dataEnd && *(int*) data < samplePosition)
  20844. {
  20845. data += 4;
  20846. data += 2 + *(uint16*) data;
  20847. }
  20848. }
  20849. bool MidiBuffer::Iterator::getNextEvent (const uint8* &midiData,
  20850. int& numBytes,
  20851. int& samplePosition) throw()
  20852. {
  20853. if (data >= buffer.elements + buffer.bytesUsed)
  20854. return false;
  20855. samplePosition = *(int*) data;
  20856. data += 4;
  20857. numBytes = *(uint16*) data;
  20858. data += 2;
  20859. midiData = data;
  20860. data += numBytes;
  20861. return true;
  20862. }
  20863. bool MidiBuffer::Iterator::getNextEvent (MidiMessage& result,
  20864. int& samplePosition) throw()
  20865. {
  20866. if (data >= buffer.elements + buffer.bytesUsed)
  20867. return false;
  20868. samplePosition = *(int*) data;
  20869. data += 4;
  20870. const int numBytes = *(uint16*) data;
  20871. data += 2;
  20872. result = MidiMessage (data, numBytes, samplePosition);
  20873. data += numBytes;
  20874. return true;
  20875. }
  20876. END_JUCE_NAMESPACE
  20877. /********* End of inlined file: juce_MidiBuffer.cpp *********/
  20878. /********* Start of inlined file: juce_MidiFile.cpp *********/
  20879. BEGIN_JUCE_NAMESPACE
  20880. struct TempoInfo
  20881. {
  20882. double bpm, timestamp;
  20883. };
  20884. struct TimeSigInfo
  20885. {
  20886. int numerator, denominator;
  20887. double timestamp;
  20888. };
  20889. MidiFile::MidiFile() throw()
  20890. : numTracks (0),
  20891. timeFormat ((short)(unsigned short)0xe728)
  20892. {
  20893. }
  20894. MidiFile::~MidiFile() throw()
  20895. {
  20896. clear();
  20897. }
  20898. void MidiFile::clear() throw()
  20899. {
  20900. while (numTracks > 0)
  20901. delete tracks [--numTracks];
  20902. }
  20903. int MidiFile::getNumTracks() const throw()
  20904. {
  20905. return numTracks;
  20906. }
  20907. const MidiMessageSequence* MidiFile::getTrack (const int index) const throw()
  20908. {
  20909. return (((unsigned int) index) < (unsigned int) numTracks) ? tracks[index] : 0;
  20910. }
  20911. void MidiFile::addTrack (const MidiMessageSequence& trackSequence) throw()
  20912. {
  20913. jassert (numTracks < numElementsInArray (tracks));
  20914. if (numTracks < numElementsInArray (tracks))
  20915. tracks [numTracks++] = new MidiMessageSequence (trackSequence);
  20916. }
  20917. short MidiFile::getTimeFormat() const throw()
  20918. {
  20919. return timeFormat;
  20920. }
  20921. void MidiFile::setTicksPerQuarterNote (const int ticks) throw()
  20922. {
  20923. timeFormat = (short)ticks;
  20924. }
  20925. void MidiFile::setSmpteTimeFormat (const int framesPerSecond,
  20926. const int subframeResolution) throw()
  20927. {
  20928. timeFormat = (short) (((-framesPerSecond) << 8) | subframeResolution);
  20929. }
  20930. void MidiFile::findAllTempoEvents (MidiMessageSequence& tempoChangeEvents) const
  20931. {
  20932. for (int i = numTracks; --i >= 0;)
  20933. {
  20934. const int numEvents = tracks[i]->getNumEvents();
  20935. for (int j = 0; j < numEvents; ++j)
  20936. {
  20937. const MidiMessage& m = tracks[i]->getEventPointer (j)->message;
  20938. if (m.isTempoMetaEvent())
  20939. tempoChangeEvents.addEvent (m);
  20940. }
  20941. }
  20942. }
  20943. void MidiFile::findAllTimeSigEvents (MidiMessageSequence& timeSigEvents) const
  20944. {
  20945. for (int i = numTracks; --i >= 0;)
  20946. {
  20947. const int numEvents = tracks[i]->getNumEvents();
  20948. for (int j = 0; j < numEvents; ++j)
  20949. {
  20950. const MidiMessage& m = tracks[i]->getEventPointer (j)->message;
  20951. if (m.isTimeSignatureMetaEvent())
  20952. timeSigEvents.addEvent (m);
  20953. }
  20954. }
  20955. }
  20956. double MidiFile::getLastTimestamp() const
  20957. {
  20958. double t = 0.0;
  20959. for (int i = numTracks; --i >= 0;)
  20960. t = jmax (t, tracks[i]->getEndTime());
  20961. return t;
  20962. }
  20963. static bool parseMidiHeader (const char* &data,
  20964. short& timeFormat,
  20965. short& fileType,
  20966. short& numberOfTracks)
  20967. {
  20968. unsigned int ch = (int) bigEndianInt (data);
  20969. data += 4;
  20970. if (ch != bigEndianInt ("MThd"))
  20971. {
  20972. bool ok = false;
  20973. if (ch == bigEndianInt ("RIFF"))
  20974. {
  20975. for (int i = 0; i < 8; ++i)
  20976. {
  20977. ch = bigEndianInt (data);
  20978. data += 4;
  20979. if (ch == bigEndianInt ("MThd"))
  20980. {
  20981. ok = true;
  20982. break;
  20983. }
  20984. }
  20985. }
  20986. if (! ok)
  20987. return false;
  20988. }
  20989. unsigned int bytesRemaining = bigEndianInt (data);
  20990. data += 4;
  20991. fileType = (short)bigEndianShort (data);
  20992. data += 2;
  20993. numberOfTracks = (short)bigEndianShort (data);
  20994. data += 2;
  20995. timeFormat = (short)bigEndianShort (data);
  20996. data += 2;
  20997. bytesRemaining -= 6;
  20998. data += bytesRemaining;
  20999. return true;
  21000. }
  21001. bool MidiFile::readFrom (InputStream& sourceStream)
  21002. {
  21003. clear();
  21004. MemoryBlock data;
  21005. const int maxSensibleMidiFileSize = 2 * 1024 * 1024;
  21006. // (put a sanity-check on the file size, as midi files are generally small)
  21007. if (sourceStream.readIntoMemoryBlock (data, maxSensibleMidiFileSize))
  21008. {
  21009. int size = data.getSize();
  21010. const char* d = (char*) data.getData();
  21011. short fileType, expectedTracks;
  21012. if (size > 16 && parseMidiHeader (d, timeFormat, fileType, expectedTracks))
  21013. {
  21014. size -= (int) (d - (char*) data.getData());
  21015. int track = 0;
  21016. while (size > 0 && track < expectedTracks)
  21017. {
  21018. const int chunkType = (int)bigEndianInt (d);
  21019. d += 4;
  21020. const int chunkSize = (int)bigEndianInt (d);
  21021. d += 4;
  21022. if (chunkSize <= 0)
  21023. break;
  21024. if (size < 0)
  21025. return false;
  21026. if (chunkType == (int)bigEndianInt ("MTrk"))
  21027. {
  21028. readNextTrack (d, chunkSize);
  21029. }
  21030. size -= chunkSize + 8;
  21031. d += chunkSize;
  21032. ++track;
  21033. }
  21034. return true;
  21035. }
  21036. }
  21037. return false;
  21038. }
  21039. // a comparator that puts all the note-offs before note-ons that have the same time
  21040. int MidiFile::compareElements (const MidiMessageSequence::MidiEventHolder* const first,
  21041. const MidiMessageSequence::MidiEventHolder* const second) throw()
  21042. {
  21043. const double diff = (first->message.getTimeStamp() - second->message.getTimeStamp());
  21044. if (diff == 0)
  21045. {
  21046. if (first->message.isNoteOff() && second->message.isNoteOn())
  21047. return -1;
  21048. else if (first->message.isNoteOn() && second->message.isNoteOff())
  21049. return 1;
  21050. else
  21051. return 0;
  21052. }
  21053. else
  21054. {
  21055. return (diff > 0) ? 1 : -1;
  21056. }
  21057. }
  21058. void MidiFile::readNextTrack (const char* data, int size)
  21059. {
  21060. double time = 0;
  21061. char lastStatusByte = 0;
  21062. MidiMessageSequence result;
  21063. while (size > 0)
  21064. {
  21065. int bytesUsed;
  21066. const int delay = MidiMessage::readVariableLengthVal ((const uint8*) data, bytesUsed);
  21067. data += bytesUsed;
  21068. size -= bytesUsed;
  21069. time += delay;
  21070. int messSize = 0;
  21071. const MidiMessage mm ((const uint8*) data, size, messSize, lastStatusByte, time);
  21072. if (messSize <= 0)
  21073. break;
  21074. size -= messSize;
  21075. data += messSize;
  21076. result.addEvent (mm);
  21077. const char firstByte = *(mm.getRawData());
  21078. if ((firstByte & 0xf0) != 0xf0)
  21079. lastStatusByte = firstByte;
  21080. }
  21081. // use a sort that puts all the note-offs before note-ons that have the same time
  21082. result.list.sort (*this, true);
  21083. result.updateMatchedPairs();
  21084. addTrack (result);
  21085. }
  21086. static double convertTicksToSeconds (const double time,
  21087. const MidiMessageSequence& tempoEvents,
  21088. const int timeFormat)
  21089. {
  21090. if (timeFormat > 0)
  21091. {
  21092. int numer = 4, denom = 4;
  21093. double tempoTime = 0.0, correctedTempoTime = 0.0;
  21094. const double tickLen = 1.0 / (timeFormat & 0x7fff);
  21095. double secsPerTick = 0.5 * tickLen;
  21096. const int numEvents = tempoEvents.getNumEvents();
  21097. for (int i = 0; i < numEvents; ++i)
  21098. {
  21099. const MidiMessage& m = tempoEvents.getEventPointer(i)->message;
  21100. if (time <= m.getTimeStamp())
  21101. break;
  21102. if (timeFormat > 0)
  21103. {
  21104. correctedTempoTime = correctedTempoTime
  21105. + (m.getTimeStamp() - tempoTime) * secsPerTick;
  21106. }
  21107. else
  21108. {
  21109. correctedTempoTime = tickLen * m.getTimeStamp() / (((timeFormat & 0x7fff) >> 8) * (timeFormat & 0xff));
  21110. }
  21111. tempoTime = m.getTimeStamp();
  21112. if (m.isTempoMetaEvent())
  21113. secsPerTick = tickLen * m.getTempoSecondsPerQuarterNote();
  21114. else if (m.isTimeSignatureMetaEvent())
  21115. m.getTimeSignatureInfo (numer, denom);
  21116. while (i + 1 < numEvents)
  21117. {
  21118. const MidiMessage& m2 = tempoEvents.getEventPointer(i + 1)->message;
  21119. if (m2.getTimeStamp() == tempoTime)
  21120. {
  21121. ++i;
  21122. if (m2.isTempoMetaEvent())
  21123. secsPerTick = tickLen * m2.getTempoSecondsPerQuarterNote();
  21124. else if (m2.isTimeSignatureMetaEvent())
  21125. m2.getTimeSignatureInfo (numer, denom);
  21126. }
  21127. else
  21128. {
  21129. break;
  21130. }
  21131. }
  21132. }
  21133. return correctedTempoTime + (time - tempoTime) * secsPerTick;
  21134. }
  21135. else
  21136. {
  21137. return time / (((timeFormat & 0x7fff) >> 8) * (timeFormat & 0xff));
  21138. }
  21139. }
  21140. void MidiFile::convertTimestampTicksToSeconds()
  21141. {
  21142. MidiMessageSequence tempoEvents;
  21143. findAllTempoEvents (tempoEvents);
  21144. findAllTimeSigEvents (tempoEvents);
  21145. for (int i = 0; i < numTracks; ++i)
  21146. {
  21147. MidiMessageSequence& ms = *tracks[i];
  21148. for (int j = ms.getNumEvents(); --j >= 0;)
  21149. {
  21150. MidiMessage& m = ms.getEventPointer(j)->message;
  21151. m.setTimeStamp (convertTicksToSeconds (m.getTimeStamp(),
  21152. tempoEvents,
  21153. timeFormat));
  21154. }
  21155. }
  21156. }
  21157. static void writeVariableLengthInt (OutputStream& out, unsigned int v)
  21158. {
  21159. unsigned int buffer = v & 0x7F;
  21160. while ((v >>= 7) != 0)
  21161. {
  21162. buffer <<= 8;
  21163. buffer |= ((v & 0x7F) | 0x80);
  21164. }
  21165. for (;;)
  21166. {
  21167. out.writeByte ((char) buffer);
  21168. if (buffer & 0x80)
  21169. buffer >>= 8;
  21170. else
  21171. break;
  21172. }
  21173. }
  21174. bool MidiFile::writeTo (OutputStream& out)
  21175. {
  21176. out.writeIntBigEndian ((int) bigEndianInt ("MThd"));
  21177. out.writeIntBigEndian (6);
  21178. out.writeShortBigEndian (1); // type
  21179. out.writeShortBigEndian (numTracks);
  21180. out.writeShortBigEndian (timeFormat);
  21181. for (int i = 0; i < numTracks; ++i)
  21182. writeTrack (out, i);
  21183. out.flush();
  21184. return true;
  21185. }
  21186. void MidiFile::writeTrack (OutputStream& mainOut,
  21187. const int trackNum)
  21188. {
  21189. MemoryOutputStream out;
  21190. const MidiMessageSequence& ms = *tracks[trackNum];
  21191. int lastTick = 0;
  21192. char lastStatusByte = 0;
  21193. for (int i = 0; i < ms.getNumEvents(); ++i)
  21194. {
  21195. const MidiMessage& mm = ms.getEventPointer(i)->message;
  21196. const int tick = roundDoubleToInt (mm.getTimeStamp());
  21197. const int delta = jmax (0, tick - lastTick);
  21198. writeVariableLengthInt (out, delta);
  21199. lastTick = tick;
  21200. const char statusByte = *(mm.getRawData());
  21201. if ((statusByte == lastStatusByte)
  21202. && ((statusByte & 0xf0) != 0xf0)
  21203. && i > 0
  21204. && mm.getRawDataSize() > 1)
  21205. {
  21206. out.write (mm.getRawData() + 1, mm.getRawDataSize() - 1);
  21207. }
  21208. else
  21209. {
  21210. out.write (mm.getRawData(), mm.getRawDataSize());
  21211. }
  21212. lastStatusByte = statusByte;
  21213. }
  21214. out.writeByte (0);
  21215. const MidiMessage m (MidiMessage::endOfTrack());
  21216. out.write (m.getRawData(),
  21217. m.getRawDataSize());
  21218. mainOut.writeIntBigEndian ((int)bigEndianInt ("MTrk"));
  21219. mainOut.writeIntBigEndian (out.getDataSize());
  21220. mainOut.write (out.getData(), out.getDataSize());
  21221. }
  21222. END_JUCE_NAMESPACE
  21223. /********* End of inlined file: juce_MidiFile.cpp *********/
  21224. /********* Start of inlined file: juce_MidiKeyboardState.cpp *********/
  21225. BEGIN_JUCE_NAMESPACE
  21226. MidiKeyboardState::MidiKeyboardState()
  21227. : listeners (2)
  21228. {
  21229. zeromem (noteStates, sizeof (noteStates));
  21230. }
  21231. MidiKeyboardState::~MidiKeyboardState()
  21232. {
  21233. }
  21234. void MidiKeyboardState::reset()
  21235. {
  21236. const ScopedLock sl (lock);
  21237. zeromem (noteStates, sizeof (noteStates));
  21238. eventsToAdd.clear();
  21239. }
  21240. bool MidiKeyboardState::isNoteOn (const int midiChannel, const int n) const throw()
  21241. {
  21242. jassert (midiChannel >= 0 && midiChannel <= 16);
  21243. return ((unsigned int) n) < 128
  21244. && (noteStates[n] & (1 << (midiChannel - 1))) != 0;
  21245. }
  21246. bool MidiKeyboardState::isNoteOnForChannels (const int midiChannelMask, const int n) const throw()
  21247. {
  21248. return ((unsigned int) n) < 128
  21249. && (noteStates[n] & midiChannelMask) != 0;
  21250. }
  21251. void MidiKeyboardState::noteOn (const int midiChannel, const int midiNoteNumber, const float velocity)
  21252. {
  21253. jassert (midiChannel >= 0 && midiChannel <= 16);
  21254. jassert (((unsigned int) midiNoteNumber) < 128);
  21255. const ScopedLock sl (lock);
  21256. if (((unsigned int) midiNoteNumber) < 128)
  21257. {
  21258. const int timeNow = (int) Time::getMillisecondCounter();
  21259. eventsToAdd.addEvent (MidiMessage::noteOn (midiChannel, midiNoteNumber, velocity), timeNow);
  21260. eventsToAdd.clear (0, timeNow - 500);
  21261. noteOnInternal (midiChannel, midiNoteNumber, velocity);
  21262. }
  21263. }
  21264. void MidiKeyboardState::noteOnInternal (const int midiChannel, const int midiNoteNumber, const float velocity)
  21265. {
  21266. if (((unsigned int) midiNoteNumber) < 128)
  21267. {
  21268. noteStates [midiNoteNumber] |= (1 << (midiChannel - 1));
  21269. for (int i = listeners.size(); --i >= 0;)
  21270. ((MidiKeyboardStateListener*) listeners.getUnchecked(i))
  21271. ->handleNoteOn (this, midiChannel, midiNoteNumber, velocity);
  21272. }
  21273. }
  21274. void MidiKeyboardState::noteOff (const int midiChannel, const int midiNoteNumber)
  21275. {
  21276. const ScopedLock sl (lock);
  21277. if (isNoteOn (midiChannel, midiNoteNumber))
  21278. {
  21279. const int timeNow = (int) Time::getMillisecondCounter();
  21280. eventsToAdd.addEvent (MidiMessage::noteOff (midiChannel, midiNoteNumber), timeNow);
  21281. eventsToAdd.clear (0, timeNow - 500);
  21282. noteOffInternal (midiChannel, midiNoteNumber);
  21283. }
  21284. }
  21285. void MidiKeyboardState::noteOffInternal (const int midiChannel, const int midiNoteNumber)
  21286. {
  21287. if (isNoteOn (midiChannel, midiNoteNumber))
  21288. {
  21289. noteStates [midiNoteNumber] &= ~(1 << (midiChannel - 1));
  21290. for (int i = listeners.size(); --i >= 0;)
  21291. ((MidiKeyboardStateListener*) listeners.getUnchecked(i))
  21292. ->handleNoteOff (this, midiChannel, midiNoteNumber);
  21293. }
  21294. }
  21295. void MidiKeyboardState::allNotesOff (const int midiChannel)
  21296. {
  21297. const ScopedLock sl (lock);
  21298. if (midiChannel <= 0)
  21299. {
  21300. for (int i = 1; i <= 16; ++i)
  21301. allNotesOff (i);
  21302. }
  21303. else
  21304. {
  21305. for (int i = 0; i < 128; ++i)
  21306. noteOff (midiChannel, i);
  21307. }
  21308. }
  21309. void MidiKeyboardState::processNextMidiEvent (const MidiMessage& message)
  21310. {
  21311. if (message.isNoteOn())
  21312. {
  21313. noteOnInternal (message.getChannel(), message.getNoteNumber(), message.getFloatVelocity());
  21314. }
  21315. else if (message.isNoteOff())
  21316. {
  21317. noteOffInternal (message.getChannel(), message.getNoteNumber());
  21318. }
  21319. else if (message.isAllNotesOff())
  21320. {
  21321. for (int i = 0; i < 128; ++i)
  21322. noteOffInternal (message.getChannel(), i);
  21323. }
  21324. }
  21325. void MidiKeyboardState::processNextMidiBuffer (MidiBuffer& buffer,
  21326. const int startSample,
  21327. const int numSamples,
  21328. const bool injectIndirectEvents)
  21329. {
  21330. MidiBuffer::Iterator i (buffer);
  21331. MidiMessage message (0xf4, 0.0);
  21332. int time;
  21333. const ScopedLock sl (lock);
  21334. while (i.getNextEvent (message, time))
  21335. processNextMidiEvent (message);
  21336. if (injectIndirectEvents)
  21337. {
  21338. MidiBuffer::Iterator i2 (eventsToAdd);
  21339. const int firstEventToAdd = eventsToAdd.getFirstEventTime();
  21340. const double scaleFactor = numSamples / (double) (eventsToAdd.getLastEventTime() + 1 - firstEventToAdd);
  21341. while (i2.getNextEvent (message, time))
  21342. {
  21343. const int pos = jlimit (0, numSamples - 1, roundDoubleToInt ((time - firstEventToAdd) * scaleFactor));
  21344. buffer.addEvent (message, startSample + pos);
  21345. }
  21346. }
  21347. eventsToAdd.clear();
  21348. }
  21349. void MidiKeyboardState::addListener (MidiKeyboardStateListener* const listener) throw()
  21350. {
  21351. const ScopedLock sl (lock);
  21352. listeners.addIfNotAlreadyThere (listener);
  21353. }
  21354. void MidiKeyboardState::removeListener (MidiKeyboardStateListener* const listener) throw()
  21355. {
  21356. const ScopedLock sl (lock);
  21357. listeners.removeValue (listener);
  21358. }
  21359. END_JUCE_NAMESPACE
  21360. /********* End of inlined file: juce_MidiKeyboardState.cpp *********/
  21361. /********* Start of inlined file: juce_MidiMessage.cpp *********/
  21362. BEGIN_JUCE_NAMESPACE
  21363. int MidiMessage::readVariableLengthVal (const uint8* data,
  21364. int& numBytesUsed) throw()
  21365. {
  21366. numBytesUsed = 0;
  21367. int v = 0;
  21368. int i;
  21369. do
  21370. {
  21371. i = (int) *data++;
  21372. if (++numBytesUsed > 6)
  21373. break;
  21374. v = (v << 7) + (i & 0x7f);
  21375. } while (i & 0x80);
  21376. return v;
  21377. }
  21378. int MidiMessage::getMessageLengthFromFirstByte (const uint8 firstByte) throw()
  21379. {
  21380. // this method only works for valid starting bytes of a short midi message
  21381. jassert (firstByte >= 0x80
  21382. && firstByte != 0xf0
  21383. && firstByte != 0xf7);
  21384. static const char messageLengths[] =
  21385. {
  21386. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  21387. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  21388. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  21389. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  21390. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  21391. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  21392. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  21393. 1, 2, 3, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1
  21394. };
  21395. return messageLengths [firstByte & 0x7f];
  21396. }
  21397. MidiMessage::MidiMessage (const uint8* const d,
  21398. const int dataSize,
  21399. const double t) throw()
  21400. : timeStamp (t),
  21401. message (0),
  21402. size (dataSize)
  21403. {
  21404. jassert (dataSize > 0);
  21405. if (dataSize <= 4)
  21406. data = (uint8*) &message;
  21407. else
  21408. data = (uint8*) juce_malloc (dataSize);
  21409. memcpy (data, d, dataSize);
  21410. // check that the length matches the data..
  21411. jassert (size > 3 || *d >= 0xf0 || getMessageLengthFromFirstByte (*d) == size);
  21412. }
  21413. MidiMessage::MidiMessage (const int byte1,
  21414. const double t) throw()
  21415. : timeStamp (t),
  21416. data ((uint8*) &message),
  21417. size (1)
  21418. {
  21419. data[0] = (uint8) byte1;
  21420. // check that the length matches the data..
  21421. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 1);
  21422. }
  21423. MidiMessage::MidiMessage (const int byte1,
  21424. const int byte2,
  21425. const double t) throw()
  21426. : timeStamp (t),
  21427. data ((uint8*) &message),
  21428. size (2)
  21429. {
  21430. data[0] = (uint8) byte1;
  21431. data[1] = (uint8) byte2;
  21432. // check that the length matches the data..
  21433. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 2);
  21434. }
  21435. MidiMessage::MidiMessage (const int byte1,
  21436. const int byte2,
  21437. const int byte3,
  21438. const double t) throw()
  21439. : timeStamp (t),
  21440. data ((uint8*) &message),
  21441. size (3)
  21442. {
  21443. data[0] = (uint8) byte1;
  21444. data[1] = (uint8) byte2;
  21445. data[2] = (uint8) byte3;
  21446. // check that the length matches the data..
  21447. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 3);
  21448. }
  21449. MidiMessage::MidiMessage (const MidiMessage& other) throw()
  21450. : timeStamp (other.timeStamp),
  21451. message (other.message),
  21452. size (other.size)
  21453. {
  21454. if (other.data != (uint8*) &other.message)
  21455. {
  21456. data = (uint8*) juce_malloc (size);
  21457. memcpy (data, other.data, size);
  21458. }
  21459. else
  21460. {
  21461. data = (uint8*) &message;
  21462. }
  21463. }
  21464. MidiMessage::MidiMessage (const MidiMessage& other,
  21465. const double newTimeStamp) throw()
  21466. : timeStamp (newTimeStamp),
  21467. message (other.message),
  21468. size (other.size)
  21469. {
  21470. if (other.data != (uint8*) &other.message)
  21471. {
  21472. data = (uint8*) juce_malloc (size);
  21473. memcpy (data, other.data, size);
  21474. }
  21475. else
  21476. {
  21477. data = (uint8*) &message;
  21478. }
  21479. }
  21480. MidiMessage::MidiMessage (const uint8* src,
  21481. int sz,
  21482. int& numBytesUsed,
  21483. const uint8 lastStatusByte,
  21484. double t) throw()
  21485. : timeStamp (t),
  21486. data ((uint8*) &message),
  21487. message (0)
  21488. {
  21489. unsigned int byte = (unsigned int) *src;
  21490. if (byte < 0x80)
  21491. {
  21492. byte = (unsigned int) (uint8) lastStatusByte;
  21493. numBytesUsed = -1;
  21494. }
  21495. else
  21496. {
  21497. numBytesUsed = 0;
  21498. --sz;
  21499. ++src;
  21500. }
  21501. if (byte >= 0x80)
  21502. {
  21503. if (byte == 0xf0)
  21504. {
  21505. const uint8* d = (const uint8*) src;
  21506. while (d < src + sz)
  21507. {
  21508. if (*d >= 0x80) // stop if we hit a status byte, and don't include it in this message
  21509. {
  21510. if (*d == 0xf7) // include an 0xf7 if we hit one
  21511. ++d;
  21512. break;
  21513. }
  21514. ++d;
  21515. }
  21516. size = 1 + (int) (d - src);
  21517. data = (uint8*) juce_malloc (size);
  21518. *data = (uint8) byte;
  21519. memcpy (data + 1, src, size - 1);
  21520. }
  21521. else if (byte == 0xff)
  21522. {
  21523. int n;
  21524. const int bytesLeft = readVariableLengthVal (src + 1, n);
  21525. size = jmin (sz + 1, n + 2 + bytesLeft);
  21526. data = (uint8*) juce_malloc (size);
  21527. *data = (uint8) byte;
  21528. memcpy (data + 1, src, size - 1);
  21529. }
  21530. else
  21531. {
  21532. size = getMessageLengthFromFirstByte ((uint8) byte);
  21533. *data = (uint8) byte;
  21534. if (size > 1)
  21535. {
  21536. data[1] = src[0];
  21537. if (size > 2)
  21538. data[2] = src[1];
  21539. }
  21540. }
  21541. numBytesUsed += size;
  21542. }
  21543. else
  21544. {
  21545. message = 0;
  21546. size = 0;
  21547. }
  21548. }
  21549. const MidiMessage& MidiMessage::operator= (const MidiMessage& other) throw()
  21550. {
  21551. if (this == &other)
  21552. return *this;
  21553. timeStamp = other.timeStamp;
  21554. size = other.size;
  21555. message = other.message;
  21556. if (data != (uint8*) &message)
  21557. juce_free (data);
  21558. if (other.data != (uint8*) &other.message)
  21559. {
  21560. data = (uint8*) juce_malloc (size);
  21561. memcpy (data, other.data, size);
  21562. }
  21563. else
  21564. {
  21565. data = (uint8*) &message;
  21566. }
  21567. return *this;
  21568. }
  21569. MidiMessage::~MidiMessage() throw()
  21570. {
  21571. if (data != (uint8*) &message)
  21572. juce_free (data);
  21573. }
  21574. int MidiMessage::getChannel() const throw()
  21575. {
  21576. if ((data[0] & 0xf0) != 0xf0)
  21577. return (data[0] & 0xf) + 1;
  21578. else
  21579. return 0;
  21580. }
  21581. bool MidiMessage::isForChannel (const int channel) const throw()
  21582. {
  21583. return ((data[0] & 0xf) == channel - 1)
  21584. && ((data[0] & 0xf0) != 0xf0);
  21585. }
  21586. void MidiMessage::setChannel (const int channel) throw()
  21587. {
  21588. if ((data[0] & 0xf0) != (uint8) 0xf0)
  21589. data[0] = (uint8) ((data[0] & (uint8)0xf0)
  21590. | (uint8)(channel - 1));
  21591. }
  21592. bool MidiMessage::isNoteOn() const throw()
  21593. {
  21594. return ((data[0] & 0xf0) == 0x90)
  21595. && (data[2] != 0);
  21596. }
  21597. bool MidiMessage::isNoteOff() const throw()
  21598. {
  21599. return ((data[0] & 0xf0) == 0x80)
  21600. || ((data[2] == 0) && ((data[0] & 0xf0) == 0x90));
  21601. }
  21602. bool MidiMessage::isNoteOnOrOff() const throw()
  21603. {
  21604. const int d = data[0] & 0xf0;
  21605. return (d == 0x90) || (d == 0x80);
  21606. }
  21607. int MidiMessage::getNoteNumber() const throw()
  21608. {
  21609. return data[1];
  21610. }
  21611. void MidiMessage::setNoteNumber (const int newNoteNumber) throw()
  21612. {
  21613. if (isNoteOnOrOff())
  21614. data[1] = (uint8) jlimit (0, 127, newNoteNumber);
  21615. }
  21616. uint8 MidiMessage::getVelocity() const throw()
  21617. {
  21618. if (isNoteOnOrOff())
  21619. return data[2];
  21620. else
  21621. return 0;
  21622. }
  21623. float MidiMessage::getFloatVelocity() const throw()
  21624. {
  21625. return getVelocity() * (1.0f / 127.0f);
  21626. }
  21627. void MidiMessage::setVelocity (const float newVelocity) throw()
  21628. {
  21629. if (isNoteOnOrOff())
  21630. data[2] = (uint8) jlimit (0, 0x7f, roundFloatToInt (newVelocity * 127.0f));
  21631. }
  21632. void MidiMessage::multiplyVelocity (const float scaleFactor) throw()
  21633. {
  21634. if (isNoteOnOrOff())
  21635. data[2] = (uint8) jlimit (0, 0x7f, roundFloatToInt (scaleFactor * data[2]));
  21636. }
  21637. bool MidiMessage::isAftertouch() const throw()
  21638. {
  21639. return (data[0] & 0xf0) == 0xa0;
  21640. }
  21641. int MidiMessage::getAfterTouchValue() const throw()
  21642. {
  21643. return data[2];
  21644. }
  21645. const MidiMessage MidiMessage::aftertouchChange (const int channel,
  21646. const int noteNum,
  21647. const int aftertouchValue) throw()
  21648. {
  21649. jassert (channel > 0 && channel <= 16);
  21650. jassert (((unsigned int) noteNum) <= 127);
  21651. jassert (((unsigned int) aftertouchValue) <= 127);
  21652. return MidiMessage (0xa0 | jlimit (0, 15, channel - 1),
  21653. noteNum & 0x7f,
  21654. aftertouchValue & 0x7f);
  21655. }
  21656. bool MidiMessage::isChannelPressure() const throw()
  21657. {
  21658. return (data[0] & 0xf0) == 0xd0;
  21659. }
  21660. int MidiMessage::getChannelPressureValue() const throw()
  21661. {
  21662. jassert (isChannelPressure());
  21663. return data[1];
  21664. }
  21665. const MidiMessage MidiMessage::channelPressureChange (const int channel,
  21666. const int pressure) throw()
  21667. {
  21668. jassert (channel > 0 && channel <= 16);
  21669. jassert (((unsigned int) pressure) <= 127);
  21670. return MidiMessage (0xd0 | jlimit (0, 15, channel - 1),
  21671. pressure & 0x7f);
  21672. }
  21673. bool MidiMessage::isProgramChange() const throw()
  21674. {
  21675. return (data[0] & 0xf0) == 0xc0;
  21676. }
  21677. int MidiMessage::getProgramChangeNumber() const throw()
  21678. {
  21679. return data[1];
  21680. }
  21681. const MidiMessage MidiMessage::programChange (const int channel,
  21682. const int programNumber) throw()
  21683. {
  21684. jassert (channel > 0 && channel <= 16);
  21685. return MidiMessage (0xc0 | jlimit (0, 15, channel - 1),
  21686. programNumber & 0x7f);
  21687. }
  21688. bool MidiMessage::isPitchWheel() const throw()
  21689. {
  21690. return (data[0] & 0xf0) == 0xe0;
  21691. }
  21692. int MidiMessage::getPitchWheelValue() const throw()
  21693. {
  21694. return data[1] | (data[2] << 7);
  21695. }
  21696. const MidiMessage MidiMessage::pitchWheel (const int channel,
  21697. const int position) throw()
  21698. {
  21699. jassert (channel > 0 && channel <= 16);
  21700. jassert (((unsigned int) position) <= 0x3fff);
  21701. return MidiMessage (0xe0 | jlimit (0, 15, channel - 1),
  21702. position & 127,
  21703. (position >> 7) & 127);
  21704. }
  21705. bool MidiMessage::isController() const throw()
  21706. {
  21707. return (data[0] & 0xf0) == 0xb0;
  21708. }
  21709. int MidiMessage::getControllerNumber() const throw()
  21710. {
  21711. jassert (isController());
  21712. return data[1];
  21713. }
  21714. int MidiMessage::getControllerValue() const throw()
  21715. {
  21716. jassert (isController());
  21717. return data[2];
  21718. }
  21719. const MidiMessage MidiMessage::controllerEvent (const int channel,
  21720. const int controllerType,
  21721. const int value) throw()
  21722. {
  21723. // the channel must be between 1 and 16 inclusive
  21724. jassert (channel > 0 && channel <= 16);
  21725. return MidiMessage (0xb0 | jlimit (0, 15, channel - 1),
  21726. controllerType & 127,
  21727. value & 127);
  21728. }
  21729. const MidiMessage MidiMessage::noteOn (const int channel,
  21730. const int noteNumber,
  21731. const float velocity) throw()
  21732. {
  21733. return noteOn (channel, noteNumber, (uint8)(velocity * 127.0f));
  21734. }
  21735. const MidiMessage MidiMessage::noteOn (const int channel,
  21736. const int noteNumber,
  21737. const uint8 velocity) throw()
  21738. {
  21739. jassert (channel > 0 && channel <= 16);
  21740. jassert (((unsigned int) noteNumber) <= 127);
  21741. return MidiMessage (0x90 | jlimit (0, 15, channel - 1),
  21742. noteNumber & 127,
  21743. jlimit (0, 127, roundFloatToInt (velocity)));
  21744. }
  21745. const MidiMessage MidiMessage::noteOff (const int channel,
  21746. const int noteNumber) throw()
  21747. {
  21748. jassert (channel > 0 && channel <= 16);
  21749. jassert (((unsigned int) noteNumber) <= 127);
  21750. return MidiMessage (0x80 | jlimit (0, 15, channel - 1), noteNumber & 127, 0);
  21751. }
  21752. const MidiMessage MidiMessage::allNotesOff (const int channel) throw()
  21753. {
  21754. jassert (channel > 0 && channel <= 16);
  21755. return controllerEvent (channel, 123, 0);
  21756. }
  21757. bool MidiMessage::isAllNotesOff() const throw()
  21758. {
  21759. return (data[0] & 0xf0) == 0xb0
  21760. && data[1] == 123;
  21761. }
  21762. const MidiMessage MidiMessage::allSoundOff (const int channel) throw()
  21763. {
  21764. return controllerEvent (channel, 120, 0);
  21765. }
  21766. bool MidiMessage::isAllSoundOff() const throw()
  21767. {
  21768. return (data[0] & 0xf0) == 0xb0
  21769. && data[1] == 120;
  21770. }
  21771. const MidiMessage MidiMessage::allControllersOff (const int channel) throw()
  21772. {
  21773. return controllerEvent (channel, 121, 0);
  21774. }
  21775. const MidiMessage MidiMessage::masterVolume (const float volume) throw()
  21776. {
  21777. const int vol = jlimit (0, 0x3fff, roundFloatToInt (volume * 0x4000));
  21778. uint8 buf[8];
  21779. buf[0] = 0xf0;
  21780. buf[1] = 0x7f;
  21781. buf[2] = 0x7f;
  21782. buf[3] = 0x04;
  21783. buf[4] = 0x01;
  21784. buf[5] = (uint8) (vol & 0x7f);
  21785. buf[6] = (uint8) (vol >> 7);
  21786. buf[7] = 0xf7;
  21787. return MidiMessage (buf, 8);
  21788. }
  21789. bool MidiMessage::isSysEx() const throw()
  21790. {
  21791. return *data == 0xf0;
  21792. }
  21793. const MidiMessage MidiMessage::createSysExMessage (const uint8* sysexData,
  21794. const int dataSize) throw()
  21795. {
  21796. MemoryBlock mm (dataSize + 2);
  21797. uint8* const m = (uint8*) mm.getData();
  21798. m[0] = 0xf0;
  21799. memcpy (m + 1, sysexData, dataSize);
  21800. m[dataSize + 1] = 0xf7;
  21801. return MidiMessage (m, dataSize + 2);
  21802. }
  21803. const uint8* MidiMessage::getSysExData() const throw()
  21804. {
  21805. return (isSysEx()) ? getRawData() + 1
  21806. : 0;
  21807. }
  21808. int MidiMessage::getSysExDataSize() const throw()
  21809. {
  21810. return (isSysEx()) ? size - 2
  21811. : 0;
  21812. }
  21813. bool MidiMessage::isMetaEvent() const throw()
  21814. {
  21815. return *data == 0xff;
  21816. }
  21817. bool MidiMessage::isActiveSense() const throw()
  21818. {
  21819. return *data == 0xfe;
  21820. }
  21821. int MidiMessage::getMetaEventType() const throw()
  21822. {
  21823. if (*data != 0xff)
  21824. return -1;
  21825. else
  21826. return data[1];
  21827. }
  21828. int MidiMessage::getMetaEventLength() const throw()
  21829. {
  21830. if (*data == 0xff)
  21831. {
  21832. int n;
  21833. return jmin (size - 2, readVariableLengthVal (data + 2, n));
  21834. }
  21835. return 0;
  21836. }
  21837. const uint8* MidiMessage::getMetaEventData() const throw()
  21838. {
  21839. int n;
  21840. const uint8* d = data + 2;
  21841. readVariableLengthVal (d, n);
  21842. return d + n;
  21843. }
  21844. bool MidiMessage::isTrackMetaEvent() const throw()
  21845. {
  21846. return getMetaEventType() == 0;
  21847. }
  21848. bool MidiMessage::isEndOfTrackMetaEvent() const throw()
  21849. {
  21850. return getMetaEventType() == 47;
  21851. }
  21852. bool MidiMessage::isTextMetaEvent() const throw()
  21853. {
  21854. const int t = getMetaEventType();
  21855. return t > 0 && t < 16;
  21856. }
  21857. const String MidiMessage::getTextFromTextMetaEvent() const throw()
  21858. {
  21859. return String ((const char*) getMetaEventData(),
  21860. getMetaEventLength());
  21861. }
  21862. bool MidiMessage::isTrackNameEvent() const throw()
  21863. {
  21864. return (data[1] == 3)
  21865. && (*data == 0xff);
  21866. }
  21867. bool MidiMessage::isTempoMetaEvent() const throw()
  21868. {
  21869. return (data[1] == 81)
  21870. && (*data == 0xff);
  21871. }
  21872. bool MidiMessage::isMidiChannelMetaEvent() const throw()
  21873. {
  21874. return (data[1] == 0x20)
  21875. && (*data == 0xff)
  21876. && (data[2] == 1);
  21877. }
  21878. int MidiMessage::getMidiChannelMetaEventChannel() const throw()
  21879. {
  21880. return data[3] + 1;
  21881. }
  21882. double MidiMessage::getTempoSecondsPerQuarterNote() const throw()
  21883. {
  21884. if (! isTempoMetaEvent())
  21885. return 0.0;
  21886. const uint8* const d = getMetaEventData();
  21887. return (((unsigned int) d[0] << 16)
  21888. | ((unsigned int) d[1] << 8)
  21889. | d[2])
  21890. / 1000000.0;
  21891. }
  21892. double MidiMessage::getTempoMetaEventTickLength (const short timeFormat) const throw()
  21893. {
  21894. if (timeFormat > 0)
  21895. {
  21896. if (! isTempoMetaEvent())
  21897. return 0.5 / timeFormat;
  21898. return getTempoSecondsPerQuarterNote() / timeFormat;
  21899. }
  21900. else
  21901. {
  21902. const int frameCode = (-timeFormat) >> 8;
  21903. double framesPerSecond;
  21904. switch (frameCode)
  21905. {
  21906. case 24: framesPerSecond = 24.0; break;
  21907. case 25: framesPerSecond = 25.0; break;
  21908. case 29: framesPerSecond = 29.97; break;
  21909. case 30: framesPerSecond = 30.0; break;
  21910. default: framesPerSecond = 30.0; break;
  21911. }
  21912. return (1.0 / framesPerSecond) / (timeFormat & 0xff);
  21913. }
  21914. }
  21915. const MidiMessage MidiMessage::tempoMetaEvent (int microsecondsPerQuarterNote) throw()
  21916. {
  21917. uint8 d[8];
  21918. d[0] = 0xff;
  21919. d[1] = 81;
  21920. d[2] = 3;
  21921. d[3] = (uint8) (microsecondsPerQuarterNote >> 16);
  21922. d[4] = (uint8) ((microsecondsPerQuarterNote >> 8) & 0xff);
  21923. d[5] = (uint8) (microsecondsPerQuarterNote & 0xff);
  21924. return MidiMessage (d, 6, 0.0);
  21925. }
  21926. bool MidiMessage::isTimeSignatureMetaEvent() const throw()
  21927. {
  21928. return (data[1] == 0x58)
  21929. && (*data == (uint8) 0xff);
  21930. }
  21931. void MidiMessage::getTimeSignatureInfo (int& numerator,
  21932. int& denominator) const throw()
  21933. {
  21934. if (isTimeSignatureMetaEvent())
  21935. {
  21936. const uint8* const d = getMetaEventData();
  21937. numerator = d[0];
  21938. denominator = 1 << d[1];
  21939. }
  21940. else
  21941. {
  21942. numerator = 4;
  21943. denominator = 4;
  21944. }
  21945. }
  21946. const MidiMessage MidiMessage::timeSignatureMetaEvent (const int numerator,
  21947. const int denominator) throw()
  21948. {
  21949. uint8 d[8];
  21950. d[0] = 0xff;
  21951. d[1] = 0x58;
  21952. d[2] = 0x04;
  21953. d[3] = (uint8) numerator;
  21954. int n = 1;
  21955. int powerOfTwo = 0;
  21956. while (n < denominator)
  21957. {
  21958. n <<= 1;
  21959. ++powerOfTwo;
  21960. }
  21961. d[4] = (uint8) powerOfTwo;
  21962. d[5] = 0x01;
  21963. d[6] = 96;
  21964. return MidiMessage (d, 7, 0.0);
  21965. }
  21966. const MidiMessage MidiMessage::midiChannelMetaEvent (const int channel) throw()
  21967. {
  21968. uint8 d[8];
  21969. d[0] = 0xff;
  21970. d[1] = 0x20;
  21971. d[2] = 0x01;
  21972. d[3] = (uint8) jlimit (0, 0xff, channel - 1);
  21973. return MidiMessage (d, 4, 0.0);
  21974. }
  21975. bool MidiMessage::isKeySignatureMetaEvent() const throw()
  21976. {
  21977. return getMetaEventType() == 89;
  21978. }
  21979. int MidiMessage::getKeySignatureNumberOfSharpsOrFlats() const throw()
  21980. {
  21981. return (int) *getMetaEventData();
  21982. }
  21983. const MidiMessage MidiMessage::endOfTrack() throw()
  21984. {
  21985. return MidiMessage (0xff, 0x2f, 0, 0.0);
  21986. }
  21987. bool MidiMessage::isSongPositionPointer() const throw()
  21988. {
  21989. return *data == 0xf2;
  21990. }
  21991. int MidiMessage::getSongPositionPointerMidiBeat() const throw()
  21992. {
  21993. return data[1] | (data[2] << 7);
  21994. }
  21995. const MidiMessage MidiMessage::songPositionPointer (const int positionInMidiBeats) throw()
  21996. {
  21997. return MidiMessage (0xf2,
  21998. positionInMidiBeats & 127,
  21999. (positionInMidiBeats >> 7) & 127);
  22000. }
  22001. bool MidiMessage::isMidiStart() const throw()
  22002. {
  22003. return *data == 0xfa;
  22004. }
  22005. const MidiMessage MidiMessage::midiStart() throw()
  22006. {
  22007. return MidiMessage (0xfa);
  22008. }
  22009. bool MidiMessage::isMidiContinue() const throw()
  22010. {
  22011. return *data == 0xfb;
  22012. }
  22013. const MidiMessage MidiMessage::midiContinue() throw()
  22014. {
  22015. return MidiMessage (0xfb);
  22016. }
  22017. bool MidiMessage::isMidiStop() const throw()
  22018. {
  22019. return *data == 0xfc;
  22020. }
  22021. const MidiMessage MidiMessage::midiStop() throw()
  22022. {
  22023. return MidiMessage (0xfc);
  22024. }
  22025. bool MidiMessage::isMidiClock() const throw()
  22026. {
  22027. return *data == 0xf8;
  22028. }
  22029. const MidiMessage MidiMessage::midiClock() throw()
  22030. {
  22031. return MidiMessage (0xf8);
  22032. }
  22033. bool MidiMessage::isQuarterFrame() const throw()
  22034. {
  22035. return *data == 0xf1;
  22036. }
  22037. int MidiMessage::getQuarterFrameSequenceNumber() const throw()
  22038. {
  22039. return ((int) data[1]) >> 4;
  22040. }
  22041. int MidiMessage::getQuarterFrameValue() const throw()
  22042. {
  22043. return ((int) data[1]) & 0x0f;
  22044. }
  22045. const MidiMessage MidiMessage::quarterFrame (const int sequenceNumber,
  22046. const int value) throw()
  22047. {
  22048. return MidiMessage (0xf1, (sequenceNumber << 4) | value);
  22049. }
  22050. bool MidiMessage::isFullFrame() const throw()
  22051. {
  22052. return data[0] == 0xf0
  22053. && data[1] == 0x7f
  22054. && size >= 10
  22055. && data[3] == 0x01
  22056. && data[4] == 0x01;
  22057. }
  22058. void MidiMessage::getFullFrameParameters (int& hours,
  22059. int& minutes,
  22060. int& seconds,
  22061. int& frames,
  22062. MidiMessage::SmpteTimecodeType& timecodeType) const throw()
  22063. {
  22064. jassert (isFullFrame());
  22065. timecodeType = (SmpteTimecodeType) (data[5] >> 5);
  22066. hours = data[5] & 0x1f;
  22067. minutes = data[6];
  22068. seconds = data[7];
  22069. frames = data[8];
  22070. }
  22071. const MidiMessage MidiMessage::fullFrame (const int hours,
  22072. const int minutes,
  22073. const int seconds,
  22074. const int frames,
  22075. MidiMessage::SmpteTimecodeType timecodeType)
  22076. {
  22077. uint8 d[10];
  22078. d[0] = 0xf0;
  22079. d[1] = 0x7f;
  22080. d[2] = 0x7f;
  22081. d[3] = 0x01;
  22082. d[4] = 0x01;
  22083. d[5] = (uint8) ((hours & 0x01f) | (timecodeType << 5));
  22084. d[6] = (uint8) minutes;
  22085. d[7] = (uint8) seconds;
  22086. d[8] = (uint8) frames;
  22087. d[9] = 0xf7;
  22088. return MidiMessage (d, 10, 0.0);
  22089. }
  22090. bool MidiMessage::isMidiMachineControlMessage() const throw()
  22091. {
  22092. return data[0] == 0xf0
  22093. && data[1] == 0x7f
  22094. && data[3] == 0x06
  22095. && size > 5;
  22096. }
  22097. MidiMessage::MidiMachineControlCommand MidiMessage::getMidiMachineControlCommand() const throw()
  22098. {
  22099. jassert (isMidiMachineControlMessage());
  22100. return (MidiMachineControlCommand) data[4];
  22101. }
  22102. const MidiMessage MidiMessage::midiMachineControlCommand (MidiMessage::MidiMachineControlCommand command)
  22103. {
  22104. uint8 d[6];
  22105. d[0] = 0xf0;
  22106. d[1] = 0x7f;
  22107. d[2] = 0x00;
  22108. d[3] = 0x06;
  22109. d[4] = (uint8) command;
  22110. d[5] = 0xf7;
  22111. return MidiMessage (d, 6, 0.0);
  22112. }
  22113. bool MidiMessage::isMidiMachineControlGoto (int& hours,
  22114. int& minutes,
  22115. int& seconds,
  22116. int& frames) const throw()
  22117. {
  22118. if (size >= 12
  22119. && data[0] == 0xf0
  22120. && data[1] == 0x7f
  22121. && data[3] == 0x06
  22122. && data[4] == 0x44
  22123. && data[5] == 0x06
  22124. && data[6] == 0x01)
  22125. {
  22126. hours = data[7] % 24; // (that some machines send out hours > 24)
  22127. minutes = data[8];
  22128. seconds = data[9];
  22129. frames = data[10];
  22130. return true;
  22131. }
  22132. return false;
  22133. }
  22134. const MidiMessage MidiMessage::midiMachineControlGoto (int hours,
  22135. int minutes,
  22136. int seconds,
  22137. int frames)
  22138. {
  22139. uint8 d[12];
  22140. d[0] = 0xf0;
  22141. d[1] = 0x7f;
  22142. d[2] = 0x00;
  22143. d[3] = 0x06;
  22144. d[4] = 0x44;
  22145. d[5] = 0x06;
  22146. d[6] = 0x01;
  22147. d[7] = (uint8) hours;
  22148. d[8] = (uint8) minutes;
  22149. d[9] = (uint8) seconds;
  22150. d[10] = (uint8) frames;
  22151. d[11] = 0xf7;
  22152. return MidiMessage (d, 12, 0.0);
  22153. }
  22154. const String MidiMessage::getMidiNoteName (int note,
  22155. bool useSharps,
  22156. bool includeOctaveNumber,
  22157. int octaveNumForMiddleC) throw()
  22158. {
  22159. static const char* const sharpNoteNames[] = { "C", "C#", "D", "D#", "E",
  22160. "F", "F#", "G", "G#", "A",
  22161. "A#", "B" };
  22162. static const char* const flatNoteNames[] = { "C", "Db", "D", "Eb", "E",
  22163. "F", "Gb", "G", "Ab", "A",
  22164. "Bb", "B" };
  22165. if (((unsigned int) note) < 128)
  22166. {
  22167. const String s ((useSharps) ? sharpNoteNames [note % 12]
  22168. : flatNoteNames [note % 12]);
  22169. if (includeOctaveNumber)
  22170. return s + String (note / 12 + (octaveNumForMiddleC - 5));
  22171. else
  22172. return s;
  22173. }
  22174. return String::empty;
  22175. }
  22176. const double MidiMessage::getMidiNoteInHertz (int noteNumber) throw()
  22177. {
  22178. noteNumber -= 12 * 6 + 9; // now 0 = A440
  22179. return 440.0 * pow (2.0, noteNumber / 12.0);
  22180. }
  22181. const String MidiMessage::getGMInstrumentName (int n) throw()
  22182. {
  22183. const char *names[] =
  22184. {
  22185. "Acoustic Grand Piano", "Bright Acoustic Piano", "Electric Grand Piano", "Honky-tonk Piano",
  22186. "Electric Piano 1", "Electric Piano 2", "Harpsichord", "Clavinet", "Celesta", "Glockenspiel",
  22187. "Music Box", "Vibraphone", "Marimba", "Xylophone", "Tubular Bells", "Dulcimer", "Drawbar Organ",
  22188. "Percussive Organ", "Rock Organ", "Church Organ", "Reed Organ", "Accordion", "Harmonica",
  22189. "Tango Accordion", "Acoustic Guitar (nylon)", "Acoustic Guitar (steel)", "Electric Guitar (jazz)",
  22190. "Electric Guitar (clean)", "Electric Guitar (mute)", "Overdriven Guitar", "Distortion Guitar",
  22191. "Guitar Harmonics", "Acoustic Bass", "Electric Bass (finger)", "Electric Bass (pick)",
  22192. "Fretless Bass", "Slap Bass 1", "Slap Bass 2", "Synth Bass 1", "Synth Bass 2", "Violin",
  22193. "Viola", "Cello", "Contrabass", "Tremolo Strings", "Pizzicato Strings", "Orchestral Harp",
  22194. "Timpani", "String Ensemble 1", "String Ensemble 2", "SynthStrings 1", "SynthStrings 2",
  22195. "Choir Aahs", "Voice Oohs", "Synth Voice", "Orchestra Hit", "Trumpet", "Trombone", "Tuba",
  22196. "Muted Trumpet", "French Horn", "Brass Section", "SynthBrass 1", "SynthBrass 2", "Soprano Sax",
  22197. "Alto Sax", "Tenor Sax", "Baritone Sax", "Oboe", "English Horn", "Bassoon", "Clarinet",
  22198. "Piccolo", "Flute", "Recorder", "Pan Flute", "Blown Bottle", "Shakuhachi", "Whistle",
  22199. "Ocarina", "Lead 1 (square)", "Lead 2 (sawtooth)", "Lead 3 (calliope)", "Lead 4 (chiff)",
  22200. "Lead 5 (charang)", "Lead 6 (voice)", "Lead 7 (fifths)", "Lead 8 (bass+lead)", "Pad 1 (new age)",
  22201. "Pad 2 (warm)", "Pad 3 (polysynth)", "Pad 4 (choir)", "Pad 5 (bowed)", "Pad 6 (metallic)",
  22202. "Pad 7 (halo)", "Pad 8 (sweep)", "FX 1 (rain)", "FX 2 (soundtrack)", "FX 3 (crystal)",
  22203. "FX 4 (atmosphere)", "FX 5 (brightness)", "FX 6 (goblins)", "FX 7 (echoes)", "FX 8 (sci-fi)",
  22204. "Sitar", "Banjo", "Shamisen", "Koto", "Kalimba", "Bag pipe", "Fiddle", "Shanai", "Tinkle Bell",
  22205. "Agogo", "Steel Drums", "Woodblock", "Taiko Drum", "Melodic Tom", "Synth Drum", "Reverse Cymbal",
  22206. "Guitar Fret Noise", "Breath Noise", "Seashore", "Bird Tweet", "Telephone Ring", "Helicopter",
  22207. "Applause", "Gunshot"
  22208. };
  22209. return (((unsigned int) n) < 128) ? names[n]
  22210. : (const char*)0;
  22211. }
  22212. const String MidiMessage::getGMInstrumentBankName (int n) throw()
  22213. {
  22214. const char* names[] =
  22215. {
  22216. "Piano", "Chromatic Percussion", "Organ", "Guitar",
  22217. "Bass", "Strings", "Ensemble", "Brass",
  22218. "Reed", "Pipe", "Synth Lead", "Synth Pad",
  22219. "Synth Effects", "Ethnic", "Percussive", "Sound Effects"
  22220. };
  22221. return (((unsigned int) n) <= 15) ? names[n]
  22222. : (const char*)0;
  22223. }
  22224. const String MidiMessage::getRhythmInstrumentName (int n) throw()
  22225. {
  22226. const char* names[] =
  22227. {
  22228. "Acoustic Bass Drum", "Bass Drum 1", "Side Stick", "Acoustic Snare",
  22229. "Hand Clap", "Electric Snare", "Low Floor Tom", "Closed Hi-Hat", "High Floor Tom",
  22230. "Pedal Hi-Hat", "Low Tom", "Open Hi-Hat", "Low-Mid Tom", "Hi-Mid Tom", "Crash Cymbal 1",
  22231. "High Tom", "Ride Cymbal 1", "Chinese Cymbal", "Ride Bell", "Tambourine", "Splash Cymbal",
  22232. "Cowbell", "Crash Cymbal 2", "Vibraslap", "Ride Cymbal 2", "Hi Bongo", "Low Bongo",
  22233. "Mute Hi Conga", "Open Hi Conga", "Low Conga", "High Timbale", "Low Timbale", "High Agogo",
  22234. "Low Agogo", "Cabasa", "Maracas", "Short Whistle", "Long Whistle", "Short Guiro",
  22235. "Long Guiro", "Claves", "Hi Wood Block", "Low Wood Block", "Mute Cuica", "Open Cuica",
  22236. "Mute Triangle", "Open Triangle"
  22237. };
  22238. return (n >= 35 && n <= 81) ? names [n - 35]
  22239. : (const char*)0;
  22240. }
  22241. const String MidiMessage::getControllerName (int n) throw()
  22242. {
  22243. const char* names[] =
  22244. {
  22245. "Bank Select", "Modulation Wheel (coarse)", "Breath controller (coarse)",
  22246. 0, "Foot Pedal (coarse)", "Portamento Time (coarse)",
  22247. "Data Entry (coarse)", "Volume (coarse)", "Balance (coarse)",
  22248. 0, "Pan position (coarse)", "Expression (coarse)", "Effect Control 1 (coarse)",
  22249. "Effect Control 2 (coarse)", 0, 0, "General Purpose Slider 1", "General Purpose Slider 2",
  22250. "General Purpose Slider 3", "General Purpose Slider 4", 0, 0, 0, 0, 0, 0, 0, 0,
  22251. 0, 0, 0, 0, "Bank Select (fine)", "Modulation Wheel (fine)", "Breath controller (fine)",
  22252. 0, "Foot Pedal (fine)", "Portamento Time (fine)", "Data Entry (fine)", "Volume (fine)",
  22253. "Balance (fine)", 0, "Pan position (fine)", "Expression (fine)", "Effect Control 1 (fine)",
  22254. "Effect Control 2 (fine)", 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  22255. "Hold Pedal (on/off)", "Portamento (on/off)", "Sustenuto Pedal (on/off)", "Soft Pedal (on/off)",
  22256. "Legato Pedal (on/off)", "Hold 2 Pedal (on/off)", "Sound Variation", "Sound Timbre",
  22257. "Sound Release Time", "Sound Attack Time", "Sound Brightness", "Sound Control 6",
  22258. "Sound Control 7", "Sound Control 8", "Sound Control 9", "Sound Control 10",
  22259. "General Purpose Button 1 (on/off)", "General Purpose Button 2 (on/off)",
  22260. "General Purpose Button 3 (on/off)", "General Purpose Button 4 (on/off)",
  22261. 0, 0, 0, 0, 0, 0, 0, "Reverb Level", "Tremolo Level", "Chorus Level", "Celeste Level",
  22262. "Phaser Level", "Data Button increment", "Data Button decrement", "Non-registered Parameter (fine)",
  22263. "Non-registered Parameter (coarse)", "Registered Parameter (fine)", "Registered Parameter (coarse)",
  22264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, "All Sound Off", "All Controllers Off",
  22265. "Local Keyboard (on/off)", "All Notes Off", "Omni Mode Off", "Omni Mode On", "Mono Operation",
  22266. "Poly Operation"
  22267. };
  22268. return (((unsigned int) n) < 128) ? names[n]
  22269. : (const char*)0;
  22270. }
  22271. END_JUCE_NAMESPACE
  22272. /********* End of inlined file: juce_MidiMessage.cpp *********/
  22273. /********* Start of inlined file: juce_MidiMessageCollector.cpp *********/
  22274. BEGIN_JUCE_NAMESPACE
  22275. MidiMessageCollector::MidiMessageCollector()
  22276. : lastCallbackTime (0),
  22277. sampleRate (44100.0001)
  22278. {
  22279. }
  22280. MidiMessageCollector::~MidiMessageCollector()
  22281. {
  22282. }
  22283. void MidiMessageCollector::reset (const double sampleRate_)
  22284. {
  22285. jassert (sampleRate_ > 0);
  22286. const ScopedLock sl (midiCallbackLock);
  22287. sampleRate = sampleRate_;
  22288. incomingMessages.clear();
  22289. lastCallbackTime = Time::getMillisecondCounterHiRes();
  22290. }
  22291. void MidiMessageCollector::addMessageToQueue (const MidiMessage& message)
  22292. {
  22293. // you need to call reset() to set the correct sample rate before using this object
  22294. jassert (sampleRate != 44100.0001);
  22295. // the messages that come in here need to be time-stamped correctly - see MidiInput
  22296. // for details of what the number should be.
  22297. jassert (message.getTimeStamp() != 0);
  22298. const ScopedLock sl (midiCallbackLock);
  22299. const int sampleNumber
  22300. = (int) ((message.getTimeStamp() - 0.001 * lastCallbackTime) * sampleRate);
  22301. incomingMessages.addEvent (message, sampleNumber);
  22302. // if the messages don't get used for over a second, we'd better
  22303. // get rid of any old ones to avoid the queue getting too big
  22304. if (sampleNumber > sampleRate)
  22305. incomingMessages.clear (0, sampleNumber - (int) sampleRate);
  22306. }
  22307. void MidiMessageCollector::removeNextBlockOfMessages (MidiBuffer& destBuffer,
  22308. const int numSamples)
  22309. {
  22310. // you need to call reset() to set the correct sample rate before using this object
  22311. jassert (sampleRate != 44100.0001);
  22312. const double timeNow = Time::getMillisecondCounterHiRes();
  22313. const double msElapsed = timeNow - lastCallbackTime;
  22314. const ScopedLock sl (midiCallbackLock);
  22315. lastCallbackTime = timeNow;
  22316. if (! incomingMessages.isEmpty())
  22317. {
  22318. int numSourceSamples = jmax (1, roundDoubleToInt (msElapsed * 0.001 * sampleRate));
  22319. int startSample = 0;
  22320. int scale = 1 << 16;
  22321. const uint8* midiData;
  22322. int numBytes, samplePosition;
  22323. MidiBuffer::Iterator iter (incomingMessages);
  22324. if (numSourceSamples > numSamples)
  22325. {
  22326. // if our list of events is longer than the buffer we're being
  22327. // asked for, scale them down to squeeze them all in..
  22328. const int maxBlockLengthToUse = numSamples << 5;
  22329. if (numSourceSamples > maxBlockLengthToUse)
  22330. {
  22331. startSample = numSourceSamples - maxBlockLengthToUse;
  22332. numSourceSamples = maxBlockLengthToUse;
  22333. iter.setNextSamplePosition (startSample);
  22334. }
  22335. scale = (numSamples << 10) / numSourceSamples;
  22336. while (iter.getNextEvent (midiData, numBytes, samplePosition))
  22337. {
  22338. samplePosition = ((samplePosition - startSample) * scale) >> 10;
  22339. destBuffer.addEvent (midiData, numBytes,
  22340. jlimit (0, numSamples - 1, samplePosition));
  22341. }
  22342. }
  22343. else
  22344. {
  22345. // if our event list is shorter than the number we need, put them
  22346. // towards the end of the buffer
  22347. startSample = numSamples - numSourceSamples;
  22348. while (iter.getNextEvent (midiData, numBytes, samplePosition))
  22349. {
  22350. destBuffer.addEvent (midiData, numBytes,
  22351. jlimit (0, numSamples - 1, samplePosition + startSample));
  22352. }
  22353. }
  22354. incomingMessages.clear();
  22355. }
  22356. }
  22357. void MidiMessageCollector::handleNoteOn (MidiKeyboardState*, int midiChannel, int midiNoteNumber, float velocity)
  22358. {
  22359. MidiMessage m (MidiMessage::noteOn (midiChannel, midiNoteNumber, velocity));
  22360. m.setTimeStamp (Time::getMillisecondCounterHiRes() * 0.001);
  22361. addMessageToQueue (m);
  22362. }
  22363. void MidiMessageCollector::handleNoteOff (MidiKeyboardState*, int midiChannel, int midiNoteNumber)
  22364. {
  22365. MidiMessage m (MidiMessage::noteOff (midiChannel, midiNoteNumber));
  22366. m.setTimeStamp (Time::getMillisecondCounterHiRes() * 0.001);
  22367. addMessageToQueue (m);
  22368. }
  22369. void MidiMessageCollector::handleIncomingMidiMessage (MidiInput*, const MidiMessage& message)
  22370. {
  22371. addMessageToQueue (message);
  22372. }
  22373. END_JUCE_NAMESPACE
  22374. /********* End of inlined file: juce_MidiMessageCollector.cpp *********/
  22375. /********* Start of inlined file: juce_MidiMessageSequence.cpp *********/
  22376. BEGIN_JUCE_NAMESPACE
  22377. MidiMessageSequence::MidiMessageSequence()
  22378. {
  22379. }
  22380. MidiMessageSequence::MidiMessageSequence (const MidiMessageSequence& other)
  22381. {
  22382. list.ensureStorageAllocated (other.list.size());
  22383. for (int i = 0; i < other.list.size(); ++i)
  22384. list.add (new MidiEventHolder (other.list.getUnchecked(i)->message));
  22385. }
  22386. const MidiMessageSequence& MidiMessageSequence::operator= (const MidiMessageSequence& other)
  22387. {
  22388. if (this != &other)
  22389. {
  22390. clear();
  22391. for (int i = 0; i < other.list.size(); ++i)
  22392. list.add (new MidiEventHolder (other.list.getUnchecked(i)->message));
  22393. }
  22394. return *this;
  22395. }
  22396. MidiMessageSequence::~MidiMessageSequence()
  22397. {
  22398. }
  22399. void MidiMessageSequence::clear()
  22400. {
  22401. list.clear();
  22402. }
  22403. int MidiMessageSequence::getNumEvents() const
  22404. {
  22405. return list.size();
  22406. }
  22407. MidiMessageSequence::MidiEventHolder* MidiMessageSequence::getEventPointer (const int index) const
  22408. {
  22409. return list [index];
  22410. }
  22411. double MidiMessageSequence::getTimeOfMatchingKeyUp (const int index) const
  22412. {
  22413. const MidiEventHolder* const meh = list [index];
  22414. if (meh != 0 && meh->noteOffObject != 0)
  22415. return meh->noteOffObject->message.getTimeStamp();
  22416. else
  22417. return 0.0;
  22418. }
  22419. int MidiMessageSequence::getIndexOfMatchingKeyUp (const int index) const
  22420. {
  22421. const MidiEventHolder* const meh = list [index];
  22422. return (meh != 0) ? list.indexOf (meh->noteOffObject) : -1;
  22423. }
  22424. int MidiMessageSequence::getIndexOf (MidiEventHolder* const event) const
  22425. {
  22426. return list.indexOf (event);
  22427. }
  22428. int MidiMessageSequence::getNextIndexAtTime (const double timeStamp) const
  22429. {
  22430. const int numEvents = list.size();
  22431. int i;
  22432. for (i = 0; i < numEvents; ++i)
  22433. if (list.getUnchecked(i)->message.getTimeStamp() >= timeStamp)
  22434. break;
  22435. return i;
  22436. }
  22437. double MidiMessageSequence::getStartTime() const
  22438. {
  22439. if (list.size() > 0)
  22440. return list.getUnchecked(0)->message.getTimeStamp();
  22441. else
  22442. return 0;
  22443. }
  22444. double MidiMessageSequence::getEndTime() const
  22445. {
  22446. if (list.size() > 0)
  22447. return list.getLast()->message.getTimeStamp();
  22448. else
  22449. return 0;
  22450. }
  22451. double MidiMessageSequence::getEventTime (const int index) const
  22452. {
  22453. if (((unsigned int) index) < (unsigned int) list.size())
  22454. return list.getUnchecked (index)->message.getTimeStamp();
  22455. return 0.0;
  22456. }
  22457. void MidiMessageSequence::addEvent (const MidiMessage& newMessage,
  22458. double timeAdjustment)
  22459. {
  22460. MidiEventHolder* const newOne = new MidiEventHolder (newMessage);
  22461. timeAdjustment += newMessage.getTimeStamp();
  22462. newOne->message.setTimeStamp (timeAdjustment);
  22463. int i;
  22464. for (i = list.size(); --i >= 0;)
  22465. if (list.getUnchecked(i)->message.getTimeStamp() <= timeAdjustment)
  22466. break;
  22467. list.insert (i + 1, newOne);
  22468. }
  22469. void MidiMessageSequence::deleteEvent (const int index,
  22470. const bool deleteMatchingNoteUp)
  22471. {
  22472. if (((unsigned int) index) < (unsigned int) list.size())
  22473. {
  22474. if (deleteMatchingNoteUp)
  22475. deleteEvent (getIndexOfMatchingKeyUp (index), false);
  22476. list.remove (index);
  22477. }
  22478. }
  22479. void MidiMessageSequence::addSequence (const MidiMessageSequence& other,
  22480. double timeAdjustment,
  22481. double firstAllowableTime,
  22482. double endOfAllowableDestTimes)
  22483. {
  22484. firstAllowableTime -= timeAdjustment;
  22485. endOfAllowableDestTimes -= timeAdjustment;
  22486. for (int i = 0; i < other.list.size(); ++i)
  22487. {
  22488. const MidiMessage& m = other.list.getUnchecked(i)->message;
  22489. const double t = m.getTimeStamp();
  22490. if (t >= firstAllowableTime && t < endOfAllowableDestTimes)
  22491. {
  22492. MidiEventHolder* const newOne = new MidiEventHolder (m);
  22493. newOne->message.setTimeStamp (timeAdjustment + t);
  22494. list.add (newOne);
  22495. }
  22496. }
  22497. sort();
  22498. }
  22499. int MidiMessageSequence::compareElements (const MidiMessageSequence::MidiEventHolder* const first,
  22500. const MidiMessageSequence::MidiEventHolder* const second) throw()
  22501. {
  22502. const double diff = first->message.getTimeStamp()
  22503. - second->message.getTimeStamp();
  22504. return (diff > 0) - (diff < 0);
  22505. }
  22506. void MidiMessageSequence::sort()
  22507. {
  22508. list.sort (*this, true);
  22509. }
  22510. void MidiMessageSequence::updateMatchedPairs()
  22511. {
  22512. for (int i = 0; i < list.size(); ++i)
  22513. {
  22514. const MidiMessage& m1 = list.getUnchecked(i)->message;
  22515. if (m1.isNoteOn())
  22516. {
  22517. list.getUnchecked(i)->noteOffObject = 0;
  22518. const int note = m1.getNoteNumber();
  22519. const int chan = m1.getChannel();
  22520. const int len = list.size();
  22521. for (int j = i + 1; j < len; ++j)
  22522. {
  22523. const MidiMessage& m = list.getUnchecked(j)->message;
  22524. if (m.getNoteNumber() == note && m.getChannel() == chan)
  22525. {
  22526. if (m.isNoteOff())
  22527. {
  22528. list.getUnchecked(i)->noteOffObject = list[j];
  22529. break;
  22530. }
  22531. else if (m.isNoteOn())
  22532. {
  22533. list.insert (j, new MidiEventHolder (MidiMessage::noteOff (chan, note)));
  22534. list.getUnchecked(j)->message.setTimeStamp (m.getTimeStamp());
  22535. list.getUnchecked(i)->noteOffObject = list[j];
  22536. break;
  22537. }
  22538. }
  22539. }
  22540. }
  22541. }
  22542. }
  22543. void MidiMessageSequence::addTimeToMessages (const double delta)
  22544. {
  22545. for (int i = list.size(); --i >= 0;)
  22546. list.getUnchecked (i)->message.setTimeStamp (list.getUnchecked (i)->message.getTimeStamp()
  22547. + delta);
  22548. }
  22549. void MidiMessageSequence::extractMidiChannelMessages (const int channelNumberToExtract,
  22550. MidiMessageSequence& destSequence,
  22551. const bool alsoIncludeMetaEvents) const
  22552. {
  22553. for (int i = 0; i < list.size(); ++i)
  22554. {
  22555. const MidiMessage& mm = list.getUnchecked(i)->message;
  22556. if (mm.isForChannel (channelNumberToExtract)
  22557. || (alsoIncludeMetaEvents && mm.isMetaEvent()))
  22558. {
  22559. destSequence.addEvent (mm);
  22560. }
  22561. }
  22562. }
  22563. void MidiMessageSequence::extractSysExMessages (MidiMessageSequence& destSequence) const
  22564. {
  22565. for (int i = 0; i < list.size(); ++i)
  22566. {
  22567. const MidiMessage& mm = list.getUnchecked(i)->message;
  22568. if (mm.isSysEx())
  22569. destSequence.addEvent (mm);
  22570. }
  22571. }
  22572. void MidiMessageSequence::deleteMidiChannelMessages (const int channelNumberToRemove)
  22573. {
  22574. for (int i = list.size(); --i >= 0;)
  22575. if (list.getUnchecked(i)->message.isForChannel (channelNumberToRemove))
  22576. list.remove(i);
  22577. }
  22578. void MidiMessageSequence::deleteSysExMessages()
  22579. {
  22580. for (int i = list.size(); --i >= 0;)
  22581. if (list.getUnchecked(i)->message.isSysEx())
  22582. list.remove(i);
  22583. }
  22584. void MidiMessageSequence::createControllerUpdatesForTime (const int channelNumber,
  22585. const double time,
  22586. OwnedArray<MidiMessage>& dest)
  22587. {
  22588. bool doneProg = false;
  22589. bool donePitchWheel = false;
  22590. Array <int> doneControllers (32);
  22591. for (int i = list.size(); --i >= 0;)
  22592. {
  22593. const MidiMessage& mm = list.getUnchecked(i)->message;
  22594. if (mm.isForChannel (channelNumber)
  22595. && mm.getTimeStamp() <= time)
  22596. {
  22597. if (mm.isProgramChange())
  22598. {
  22599. if (! doneProg)
  22600. {
  22601. dest.add (new MidiMessage (mm, 0.0));
  22602. doneProg = true;
  22603. }
  22604. }
  22605. else if (mm.isController())
  22606. {
  22607. if (! doneControllers.contains (mm.getControllerNumber()))
  22608. {
  22609. dest.add (new MidiMessage (mm, 0.0));
  22610. doneControllers.add (mm.getControllerNumber());
  22611. }
  22612. }
  22613. else if (mm.isPitchWheel())
  22614. {
  22615. if (! donePitchWheel)
  22616. {
  22617. dest.add (new MidiMessage (mm, 0.0));
  22618. donePitchWheel = true;
  22619. }
  22620. }
  22621. }
  22622. }
  22623. }
  22624. MidiMessageSequence::MidiEventHolder::MidiEventHolder (const MidiMessage& message_)
  22625. : message (message_),
  22626. noteOffObject (0)
  22627. {
  22628. }
  22629. MidiMessageSequence::MidiEventHolder::~MidiEventHolder()
  22630. {
  22631. }
  22632. END_JUCE_NAMESPACE
  22633. /********* End of inlined file: juce_MidiMessageSequence.cpp *********/
  22634. /********* Start of inlined file: juce_AudioPluginFormat.cpp *********/
  22635. BEGIN_JUCE_NAMESPACE
  22636. AudioPluginFormat::AudioPluginFormat() throw()
  22637. {
  22638. }
  22639. AudioPluginFormat::~AudioPluginFormat()
  22640. {
  22641. }
  22642. END_JUCE_NAMESPACE
  22643. /********* End of inlined file: juce_AudioPluginFormat.cpp *********/
  22644. /********* Start of inlined file: juce_AudioPluginFormatManager.cpp *********/
  22645. BEGIN_JUCE_NAMESPACE
  22646. AudioPluginFormatManager::AudioPluginFormatManager() throw()
  22647. {
  22648. }
  22649. AudioPluginFormatManager::~AudioPluginFormatManager() throw()
  22650. {
  22651. clearSingletonInstance();
  22652. }
  22653. juce_ImplementSingleton_SingleThreaded (AudioPluginFormatManager);
  22654. void AudioPluginFormatManager::addDefaultFormats()
  22655. {
  22656. #ifdef JUCE_DEBUG
  22657. // you should only call this method once!
  22658. for (int i = formats.size(); --i >= 0;)
  22659. {
  22660. #if JUCE_PLUGINHOST_VST
  22661. jassert (dynamic_cast <VSTPluginFormat*> (formats[i]) == 0);
  22662. #endif
  22663. #if JUCE_PLUGINHOST_AU && JUCE_MAC
  22664. jassert (dynamic_cast <AudioUnitPluginFormat*> (formats[i]) == 0);
  22665. #endif
  22666. #if JUCE_PLUGINHOST_DX && JUCE_WIN32
  22667. jassert (dynamic_cast <DirectXPluginFormat*> (formats[i]) == 0);
  22668. #endif
  22669. #if JUCE_PLUGINHOST_LADSPA && JUCE_LINUX
  22670. jassert (dynamic_cast <LADSPAPluginFormat*> (formats[i]) == 0);
  22671. #endif
  22672. }
  22673. #endif
  22674. #if JUCE_PLUGINHOST_AU && JUCE_MAC
  22675. formats.add (new AudioUnitPluginFormat());
  22676. #endif
  22677. #if JUCE_PLUGINHOST_VST
  22678. formats.add (new VSTPluginFormat());
  22679. #endif
  22680. #if JUCE_PLUGINHOST_DX && JUCE_WIN32
  22681. formats.add (new DirectXPluginFormat());
  22682. #endif
  22683. #if JUCE_PLUGINHOST_LADSPA && JUCE_LINUX
  22684. formats.add (new LADSPAPluginFormat());
  22685. #endif
  22686. }
  22687. int AudioPluginFormatManager::getNumFormats() throw()
  22688. {
  22689. return formats.size();
  22690. }
  22691. AudioPluginFormat* AudioPluginFormatManager::getFormat (const int index) throw()
  22692. {
  22693. return formats [index];
  22694. }
  22695. void AudioPluginFormatManager::addFormat (AudioPluginFormat* const format) throw()
  22696. {
  22697. formats.add (format);
  22698. }
  22699. AudioPluginInstance* AudioPluginFormatManager::createPluginInstance (const PluginDescription& description,
  22700. String& errorMessage) const
  22701. {
  22702. AudioPluginInstance* result = 0;
  22703. for (int i = 0; i < formats.size(); ++i)
  22704. {
  22705. result = formats.getUnchecked(i)->createInstanceFromDescription (description);
  22706. if (result != 0)
  22707. break;
  22708. }
  22709. if (result == 0)
  22710. {
  22711. if (! doesPluginStillExist (description))
  22712. errorMessage = TRANS ("This plug-in file no longer exists");
  22713. else
  22714. errorMessage = TRANS ("This plug-in failed to load correctly");
  22715. }
  22716. return result;
  22717. }
  22718. bool AudioPluginFormatManager::doesPluginStillExist (const PluginDescription& description) const
  22719. {
  22720. for (int i = 0; i < formats.size(); ++i)
  22721. if (formats.getUnchecked(i)->getName() == description.pluginFormatName)
  22722. return formats.getUnchecked(i)->doesPluginStillExist (description);
  22723. return false;
  22724. }
  22725. END_JUCE_NAMESPACE
  22726. /********* End of inlined file: juce_AudioPluginFormatManager.cpp *********/
  22727. /********* Start of inlined file: juce_AudioPluginInstance.cpp *********/
  22728. #define JUCE_PLUGIN_HOST 1
  22729. BEGIN_JUCE_NAMESPACE
  22730. AudioPluginInstance::AudioPluginInstance()
  22731. {
  22732. }
  22733. AudioPluginInstance::~AudioPluginInstance()
  22734. {
  22735. }
  22736. END_JUCE_NAMESPACE
  22737. /********* End of inlined file: juce_AudioPluginInstance.cpp *********/
  22738. /********* Start of inlined file: juce_KnownPluginList.cpp *********/
  22739. BEGIN_JUCE_NAMESPACE
  22740. KnownPluginList::KnownPluginList()
  22741. {
  22742. }
  22743. KnownPluginList::~KnownPluginList()
  22744. {
  22745. }
  22746. void KnownPluginList::clear()
  22747. {
  22748. if (types.size() > 0)
  22749. {
  22750. types.clear();
  22751. sendChangeMessage (this);
  22752. }
  22753. }
  22754. PluginDescription* KnownPluginList::getTypeForFile (const String& fileOrIdentifier) const throw()
  22755. {
  22756. for (int i = 0; i < types.size(); ++i)
  22757. if (types.getUnchecked(i)->fileOrIdentifier == fileOrIdentifier)
  22758. return types.getUnchecked(i);
  22759. return 0;
  22760. }
  22761. PluginDescription* KnownPluginList::getTypeForIdentifierString (const String& identifierString) const throw()
  22762. {
  22763. for (int i = 0; i < types.size(); ++i)
  22764. if (types.getUnchecked(i)->createIdentifierString() == identifierString)
  22765. return types.getUnchecked(i);
  22766. return 0;
  22767. }
  22768. bool KnownPluginList::addType (const PluginDescription& type)
  22769. {
  22770. for (int i = types.size(); --i >= 0;)
  22771. {
  22772. if (types.getUnchecked(i)->isDuplicateOf (type))
  22773. {
  22774. // strange - found a duplicate plugin with different info..
  22775. jassert (types.getUnchecked(i)->name == type.name);
  22776. jassert (types.getUnchecked(i)->isInstrument == type.isInstrument);
  22777. *types.getUnchecked(i) = type;
  22778. return false;
  22779. }
  22780. }
  22781. types.add (new PluginDescription (type));
  22782. sendChangeMessage (this);
  22783. return true;
  22784. }
  22785. void KnownPluginList::removeType (const int index) throw()
  22786. {
  22787. types.remove (index);
  22788. sendChangeMessage (this);
  22789. }
  22790. static Time getFileModTime (const String& fileOrIdentifier) throw()
  22791. {
  22792. if (fileOrIdentifier.startsWithChar (T('/'))
  22793. || fileOrIdentifier[1] == T(':'))
  22794. {
  22795. return File (fileOrIdentifier).getLastModificationTime();
  22796. }
  22797. return Time (0);
  22798. }
  22799. static bool timesAreDifferent (const Time& t1, const Time& t2) throw()
  22800. {
  22801. return t1 != t2 || t1 == Time (0);
  22802. }
  22803. bool KnownPluginList::isListingUpToDate (const String& fileOrIdentifier) const throw()
  22804. {
  22805. if (getTypeForFile (fileOrIdentifier) == 0)
  22806. return false;
  22807. for (int i = types.size(); --i >= 0;)
  22808. {
  22809. const PluginDescription* const d = types.getUnchecked(i);
  22810. if (d->fileOrIdentifier == fileOrIdentifier
  22811. && timesAreDifferent (d->lastFileModTime, getFileModTime (fileOrIdentifier)))
  22812. {
  22813. return false;
  22814. }
  22815. }
  22816. return true;
  22817. }
  22818. bool KnownPluginList::scanAndAddFile (const String& fileOrIdentifier,
  22819. const bool dontRescanIfAlreadyInList,
  22820. OwnedArray <PluginDescription>& typesFound,
  22821. AudioPluginFormat& format)
  22822. {
  22823. bool addedOne = false;
  22824. if (dontRescanIfAlreadyInList
  22825. && getTypeForFile (fileOrIdentifier) != 0)
  22826. {
  22827. bool needsRescanning = false;
  22828. for (int i = types.size(); --i >= 0;)
  22829. {
  22830. const PluginDescription* const d = types.getUnchecked(i);
  22831. if (d->fileOrIdentifier == fileOrIdentifier)
  22832. {
  22833. if (timesAreDifferent (d->lastFileModTime, getFileModTime (fileOrIdentifier)))
  22834. needsRescanning = true;
  22835. else
  22836. typesFound.add (new PluginDescription (*d));
  22837. }
  22838. }
  22839. if (! needsRescanning)
  22840. return false;
  22841. }
  22842. OwnedArray <PluginDescription> found;
  22843. format.findAllTypesForFile (found, fileOrIdentifier);
  22844. for (int i = 0; i < found.size(); ++i)
  22845. {
  22846. PluginDescription* const desc = found.getUnchecked(i);
  22847. jassert (desc != 0);
  22848. if (addType (*desc))
  22849. addedOne = true;
  22850. typesFound.add (new PluginDescription (*desc));
  22851. }
  22852. return addedOne;
  22853. }
  22854. void KnownPluginList::scanAndAddDragAndDroppedFiles (const StringArray& files,
  22855. OwnedArray <PluginDescription>& typesFound)
  22856. {
  22857. for (int i = 0; i < files.size(); ++i)
  22858. {
  22859. bool loaded = false;
  22860. for (int j = 0; j < AudioPluginFormatManager::getInstance()->getNumFormats(); ++j)
  22861. {
  22862. AudioPluginFormat* const format = AudioPluginFormatManager::getInstance()->getFormat (j);
  22863. if (scanAndAddFile (files[i], true, typesFound, *format))
  22864. loaded = true;
  22865. }
  22866. if (! loaded)
  22867. {
  22868. const File f (files[i]);
  22869. if (f.isDirectory())
  22870. {
  22871. StringArray s;
  22872. {
  22873. OwnedArray <File> subFiles;
  22874. f.findChildFiles (subFiles, File::findFilesAndDirectories, false);
  22875. for (int j = 0; j < subFiles.size(); ++j)
  22876. s.add (subFiles.getUnchecked (j)->getFullPathName());
  22877. }
  22878. scanAndAddDragAndDroppedFiles (s, typesFound);
  22879. }
  22880. }
  22881. }
  22882. }
  22883. class PluginSorter
  22884. {
  22885. public:
  22886. KnownPluginList::SortMethod method;
  22887. PluginSorter() throw() {}
  22888. int compareElements (const PluginDescription* const first,
  22889. const PluginDescription* const second) const throw()
  22890. {
  22891. int diff = 0;
  22892. if (method == KnownPluginList::sortByCategory)
  22893. diff = first->category.compareLexicographically (second->category);
  22894. else if (method == KnownPluginList::sortByManufacturer)
  22895. diff = first->manufacturerName.compareLexicographically (second->manufacturerName);
  22896. else if (method == KnownPluginList::sortByFileSystemLocation)
  22897. diff = first->fileOrIdentifier.replaceCharacter (T('\\'), T('/'))
  22898. .upToLastOccurrenceOf (T("/"), false, false)
  22899. .compare (second->fileOrIdentifier.replaceCharacter (T('\\'), T('/'))
  22900. .upToLastOccurrenceOf (T("/"), false, false));
  22901. if (diff == 0)
  22902. diff = first->name.compareLexicographically (second->name);
  22903. return diff;
  22904. }
  22905. };
  22906. void KnownPluginList::sort (const SortMethod method)
  22907. {
  22908. if (method != defaultOrder)
  22909. {
  22910. PluginSorter sorter;
  22911. sorter.method = method;
  22912. types.sort (sorter, true);
  22913. sendChangeMessage (this);
  22914. }
  22915. }
  22916. XmlElement* KnownPluginList::createXml() const
  22917. {
  22918. XmlElement* const e = new XmlElement (T("KNOWNPLUGINS"));
  22919. for (int i = 0; i < types.size(); ++i)
  22920. e->addChildElement (types.getUnchecked(i)->createXml());
  22921. return e;
  22922. }
  22923. void KnownPluginList::recreateFromXml (const XmlElement& xml)
  22924. {
  22925. clear();
  22926. if (xml.hasTagName (T("KNOWNPLUGINS")))
  22927. {
  22928. forEachXmlChildElement (xml, e)
  22929. {
  22930. PluginDescription info;
  22931. if (info.loadFromXml (*e))
  22932. addType (info);
  22933. }
  22934. }
  22935. }
  22936. const int menuIdBase = 0x324503f4;
  22937. // This is used to turn a bunch of paths into a nested menu structure.
  22938. struct PluginFilesystemTree
  22939. {
  22940. private:
  22941. String folder;
  22942. OwnedArray <PluginFilesystemTree> subFolders;
  22943. Array <PluginDescription*> plugins;
  22944. void addPlugin (PluginDescription* const pd, const String& path)
  22945. {
  22946. if (path.isEmpty())
  22947. {
  22948. plugins.add (pd);
  22949. }
  22950. else
  22951. {
  22952. const String firstSubFolder (path.upToFirstOccurrenceOf (T("/"), false, false));
  22953. const String remainingPath (path.fromFirstOccurrenceOf (T("/"), false, false));
  22954. for (int i = subFolders.size(); --i >= 0;)
  22955. {
  22956. if (subFolders.getUnchecked(i)->folder.equalsIgnoreCase (firstSubFolder))
  22957. {
  22958. subFolders.getUnchecked(i)->addPlugin (pd, remainingPath);
  22959. return;
  22960. }
  22961. }
  22962. PluginFilesystemTree* const newFolder = new PluginFilesystemTree();
  22963. newFolder->folder = firstSubFolder;
  22964. subFolders.add (newFolder);
  22965. newFolder->addPlugin (pd, remainingPath);
  22966. }
  22967. }
  22968. // removes any deeply nested folders that don't contain any actual plugins
  22969. void optimise()
  22970. {
  22971. for (int i = subFolders.size(); --i >= 0;)
  22972. {
  22973. PluginFilesystemTree* const sub = subFolders.getUnchecked(i);
  22974. sub->optimise();
  22975. if (sub->plugins.size() == 0)
  22976. {
  22977. for (int j = 0; j < sub->subFolders.size(); ++j)
  22978. subFolders.add (sub->subFolders.getUnchecked(j));
  22979. sub->subFolders.clear (false);
  22980. subFolders.remove (i);
  22981. }
  22982. }
  22983. }
  22984. public:
  22985. void buildTree (const Array <PluginDescription*>& allPlugins)
  22986. {
  22987. for (int i = 0; i < allPlugins.size(); ++i)
  22988. {
  22989. String path (allPlugins.getUnchecked(i)
  22990. ->fileOrIdentifier.replaceCharacter (T('\\'), T('/'))
  22991. .upToLastOccurrenceOf (T("/"), false, false));
  22992. if (path.substring (1, 2) == T(":"))
  22993. path = path.substring (2);
  22994. addPlugin (allPlugins.getUnchecked(i), path);
  22995. }
  22996. optimise();
  22997. }
  22998. void addToMenu (PopupMenu& m, const OwnedArray <PluginDescription>& allPlugins) const
  22999. {
  23000. int i;
  23001. for (i = 0; i < subFolders.size(); ++i)
  23002. {
  23003. const PluginFilesystemTree* const sub = subFolders.getUnchecked(i);
  23004. PopupMenu subMenu;
  23005. sub->addToMenu (subMenu, allPlugins);
  23006. #if JUCE_MAC
  23007. // avoid the special AU formatting nonsense on Mac..
  23008. m.addSubMenu (sub->folder.fromFirstOccurrenceOf (T(":"), false, false), subMenu);
  23009. #else
  23010. m.addSubMenu (sub->folder, subMenu);
  23011. #endif
  23012. }
  23013. for (i = 0; i < plugins.size(); ++i)
  23014. {
  23015. PluginDescription* const plugin = plugins.getUnchecked(i);
  23016. m.addItem (allPlugins.indexOf (plugin) + menuIdBase,
  23017. plugin->name, true, false);
  23018. }
  23019. }
  23020. };
  23021. void KnownPluginList::addToMenu (PopupMenu& menu, const SortMethod sortMethod) const
  23022. {
  23023. Array <PluginDescription*> sorted;
  23024. {
  23025. PluginSorter sorter;
  23026. sorter.method = sortMethod;
  23027. for (int i = 0; i < types.size(); ++i)
  23028. sorted.addSorted (sorter, types.getUnchecked(i));
  23029. }
  23030. if (sortMethod == sortByCategory
  23031. || sortMethod == sortByManufacturer)
  23032. {
  23033. String lastSubMenuName;
  23034. PopupMenu sub;
  23035. for (int i = 0; i < sorted.size(); ++i)
  23036. {
  23037. const PluginDescription* const pd = sorted.getUnchecked(i);
  23038. String thisSubMenuName (sortMethod == sortByCategory ? pd->category
  23039. : pd->manufacturerName);
  23040. if (! thisSubMenuName.containsNonWhitespaceChars())
  23041. thisSubMenuName = T("Other");
  23042. if (thisSubMenuName != lastSubMenuName)
  23043. {
  23044. if (sub.getNumItems() > 0)
  23045. {
  23046. menu.addSubMenu (lastSubMenuName, sub);
  23047. sub.clear();
  23048. }
  23049. lastSubMenuName = thisSubMenuName;
  23050. }
  23051. sub.addItem (types.indexOf (pd) + menuIdBase, pd->name, true, false);
  23052. }
  23053. if (sub.getNumItems() > 0)
  23054. menu.addSubMenu (lastSubMenuName, sub);
  23055. }
  23056. else if (sortMethod == sortByFileSystemLocation)
  23057. {
  23058. PluginFilesystemTree root;
  23059. root.buildTree (sorted);
  23060. root.addToMenu (menu, types);
  23061. }
  23062. else
  23063. {
  23064. for (int i = 0; i < sorted.size(); ++i)
  23065. {
  23066. const PluginDescription* const pd = sorted.getUnchecked(i);
  23067. menu.addItem (types.indexOf (pd) + menuIdBase, pd->name, true, false);
  23068. }
  23069. }
  23070. }
  23071. int KnownPluginList::getIndexChosenByMenu (const int menuResultCode) const
  23072. {
  23073. const int i = menuResultCode - menuIdBase;
  23074. return (((unsigned int) i) < (unsigned int) types.size()) ? i : -1;
  23075. }
  23076. END_JUCE_NAMESPACE
  23077. /********* End of inlined file: juce_KnownPluginList.cpp *********/
  23078. /********* Start of inlined file: juce_PluginDescription.cpp *********/
  23079. BEGIN_JUCE_NAMESPACE
  23080. PluginDescription::PluginDescription() throw()
  23081. : uid (0),
  23082. isInstrument (false),
  23083. numInputChannels (0),
  23084. numOutputChannels (0)
  23085. {
  23086. }
  23087. PluginDescription::~PluginDescription() throw()
  23088. {
  23089. }
  23090. PluginDescription::PluginDescription (const PluginDescription& other) throw()
  23091. : name (other.name),
  23092. pluginFormatName (other.pluginFormatName),
  23093. category (other.category),
  23094. manufacturerName (other.manufacturerName),
  23095. version (other.version),
  23096. fileOrIdentifier (other.fileOrIdentifier),
  23097. lastFileModTime (other.lastFileModTime),
  23098. uid (other.uid),
  23099. isInstrument (other.isInstrument),
  23100. numInputChannels (other.numInputChannels),
  23101. numOutputChannels (other.numOutputChannels)
  23102. {
  23103. }
  23104. const PluginDescription& PluginDescription::operator= (const PluginDescription& other) throw()
  23105. {
  23106. name = other.name;
  23107. pluginFormatName = other.pluginFormatName;
  23108. category = other.category;
  23109. manufacturerName = other.manufacturerName;
  23110. version = other.version;
  23111. fileOrIdentifier = other.fileOrIdentifier;
  23112. uid = other.uid;
  23113. isInstrument = other.isInstrument;
  23114. lastFileModTime = other.lastFileModTime;
  23115. numInputChannels = other.numInputChannels;
  23116. numOutputChannels = other.numOutputChannels;
  23117. return *this;
  23118. }
  23119. bool PluginDescription::isDuplicateOf (const PluginDescription& other) const
  23120. {
  23121. return fileOrIdentifier == other.fileOrIdentifier
  23122. && uid == other.uid;
  23123. }
  23124. const String PluginDescription::createIdentifierString() const throw()
  23125. {
  23126. return pluginFormatName
  23127. + T("-") + name
  23128. + T("-") + String::toHexString (fileOrIdentifier.hashCode())
  23129. + T("-") + String::toHexString (uid);
  23130. }
  23131. XmlElement* PluginDescription::createXml() const
  23132. {
  23133. XmlElement* const e = new XmlElement (T("PLUGIN"));
  23134. e->setAttribute (T("name"), name);
  23135. e->setAttribute (T("format"), pluginFormatName);
  23136. e->setAttribute (T("category"), category);
  23137. e->setAttribute (T("manufacturer"), manufacturerName);
  23138. e->setAttribute (T("version"), version);
  23139. e->setAttribute (T("file"), fileOrIdentifier);
  23140. e->setAttribute (T("uid"), String::toHexString (uid));
  23141. e->setAttribute (T("isInstrument"), isInstrument);
  23142. e->setAttribute (T("fileTime"), String::toHexString (lastFileModTime.toMilliseconds()));
  23143. e->setAttribute (T("numInputs"), numInputChannels);
  23144. e->setAttribute (T("numOutputs"), numOutputChannels);
  23145. return e;
  23146. }
  23147. bool PluginDescription::loadFromXml (const XmlElement& xml)
  23148. {
  23149. if (xml.hasTagName (T("PLUGIN")))
  23150. {
  23151. name = xml.getStringAttribute (T("name"));
  23152. pluginFormatName = xml.getStringAttribute (T("format"));
  23153. category = xml.getStringAttribute (T("category"));
  23154. manufacturerName = xml.getStringAttribute (T("manufacturer"));
  23155. version = xml.getStringAttribute (T("version"));
  23156. fileOrIdentifier = xml.getStringAttribute (T("file"));
  23157. uid = xml.getStringAttribute (T("uid")).getHexValue32();
  23158. isInstrument = xml.getBoolAttribute (T("isInstrument"), false);
  23159. lastFileModTime = Time (xml.getStringAttribute (T("fileTime")).getHexValue64());
  23160. numInputChannels = xml.getIntAttribute (T("numInputs"));
  23161. numOutputChannels = xml.getIntAttribute (T("numOutputs"));
  23162. return true;
  23163. }
  23164. return false;
  23165. }
  23166. END_JUCE_NAMESPACE
  23167. /********* End of inlined file: juce_PluginDescription.cpp *********/
  23168. /********* Start of inlined file: juce_PluginDirectoryScanner.cpp *********/
  23169. BEGIN_JUCE_NAMESPACE
  23170. PluginDirectoryScanner::PluginDirectoryScanner (KnownPluginList& listToAddTo,
  23171. AudioPluginFormat& formatToLookFor,
  23172. FileSearchPath directoriesToSearch,
  23173. const bool recursive,
  23174. const File& deadMansPedalFile_)
  23175. : list (listToAddTo),
  23176. format (formatToLookFor),
  23177. deadMansPedalFile (deadMansPedalFile_),
  23178. nextIndex (0),
  23179. progress (0)
  23180. {
  23181. directoriesToSearch.removeRedundantPaths();
  23182. filesOrIdentifiersToScan = format.searchPathsForPlugins (directoriesToSearch, recursive);
  23183. // If any plugins have crashed recently when being loaded, move them to the
  23184. // end of the list to give the others a chance to load correctly..
  23185. const StringArray crashedPlugins (getDeadMansPedalFile());
  23186. for (int i = 0; i < crashedPlugins.size(); ++i)
  23187. {
  23188. const String f = crashedPlugins[i];
  23189. for (int j = filesOrIdentifiersToScan.size(); --j >= 0;)
  23190. if (f == filesOrIdentifiersToScan[j])
  23191. filesOrIdentifiersToScan.move (j, -1);
  23192. }
  23193. }
  23194. PluginDirectoryScanner::~PluginDirectoryScanner()
  23195. {
  23196. }
  23197. const String PluginDirectoryScanner::getNextPluginFileThatWillBeScanned() const throw()
  23198. {
  23199. return format.getNameOfPluginFromIdentifier (filesOrIdentifiersToScan [nextIndex]);
  23200. }
  23201. bool PluginDirectoryScanner::scanNextFile (const bool dontRescanIfAlreadyInList)
  23202. {
  23203. String file (filesOrIdentifiersToScan [nextIndex]);
  23204. if (file.isNotEmpty())
  23205. {
  23206. if (! list.isListingUpToDate (file))
  23207. {
  23208. OwnedArray <PluginDescription> typesFound;
  23209. // Add this plugin to the end of the dead-man's pedal list in case it crashes...
  23210. StringArray crashedPlugins (getDeadMansPedalFile());
  23211. crashedPlugins.removeString (file);
  23212. crashedPlugins.add (file);
  23213. setDeadMansPedalFile (crashedPlugins);
  23214. list.scanAndAddFile (file,
  23215. dontRescanIfAlreadyInList,
  23216. typesFound,
  23217. format);
  23218. // Managed to load without crashing, so remove it from the dead-man's-pedal..
  23219. crashedPlugins.removeString (file);
  23220. setDeadMansPedalFile (crashedPlugins);
  23221. if (typesFound.size() == 0)
  23222. failedFiles.add (file);
  23223. }
  23224. ++nextIndex;
  23225. progress = nextIndex / (float) filesOrIdentifiersToScan.size();
  23226. }
  23227. return nextIndex < filesOrIdentifiersToScan.size();
  23228. }
  23229. const StringArray PluginDirectoryScanner::getDeadMansPedalFile() throw()
  23230. {
  23231. StringArray lines;
  23232. if (deadMansPedalFile != File::nonexistent)
  23233. {
  23234. lines.addLines (deadMansPedalFile.loadFileAsString());
  23235. lines.removeEmptyStrings();
  23236. }
  23237. return lines;
  23238. }
  23239. void PluginDirectoryScanner::setDeadMansPedalFile (const StringArray& newContents) throw()
  23240. {
  23241. if (deadMansPedalFile != File::nonexistent)
  23242. deadMansPedalFile.replaceWithText (newContents.joinIntoString ("\n"), true, true);
  23243. }
  23244. END_JUCE_NAMESPACE
  23245. /********* End of inlined file: juce_PluginDirectoryScanner.cpp *********/
  23246. /********* Start of inlined file: juce_PluginListComponent.cpp *********/
  23247. BEGIN_JUCE_NAMESPACE
  23248. PluginListComponent::PluginListComponent (KnownPluginList& listToEdit,
  23249. const File& deadMansPedalFile_,
  23250. PropertiesFile* const propertiesToUse_)
  23251. : list (listToEdit),
  23252. deadMansPedalFile (deadMansPedalFile_),
  23253. propertiesToUse (propertiesToUse_)
  23254. {
  23255. addAndMakeVisible (listBox = new ListBox (String::empty, this));
  23256. addAndMakeVisible (optionsButton = new TextButton ("Options..."));
  23257. optionsButton->addButtonListener (this);
  23258. optionsButton->setTriggeredOnMouseDown (true);
  23259. setSize (400, 600);
  23260. list.addChangeListener (this);
  23261. }
  23262. PluginListComponent::~PluginListComponent()
  23263. {
  23264. list.removeChangeListener (this);
  23265. deleteAllChildren();
  23266. }
  23267. void PluginListComponent::resized()
  23268. {
  23269. listBox->setBounds (0, 0, getWidth(), getHeight() - 30);
  23270. optionsButton->changeWidthToFitText (24);
  23271. optionsButton->setTopLeftPosition (8, getHeight() - 28);
  23272. }
  23273. void PluginListComponent::changeListenerCallback (void*)
  23274. {
  23275. listBox->updateContent();
  23276. listBox->repaint();
  23277. }
  23278. int PluginListComponent::getNumRows()
  23279. {
  23280. return list.getNumTypes();
  23281. }
  23282. void PluginListComponent::paintListBoxItem (int row,
  23283. Graphics& g,
  23284. int width, int height,
  23285. bool rowIsSelected)
  23286. {
  23287. if (rowIsSelected)
  23288. g.fillAll (findColour (TextEditor::highlightColourId));
  23289. const PluginDescription* const pd = list.getType (row);
  23290. if (pd != 0)
  23291. {
  23292. GlyphArrangement ga;
  23293. ga.addCurtailedLineOfText (Font (height * 0.7f, Font::bold), pd->name, 8.0f, height * 0.8f, width - 10.0f, true);
  23294. g.setColour (Colours::black);
  23295. ga.draw (g);
  23296. float x, y, r, b;
  23297. ga.getBoundingBox (0, -1, x, y, r, b, false);
  23298. String desc;
  23299. desc << pd->pluginFormatName
  23300. << (pd->isInstrument ? " instrument" : " effect")
  23301. << " - "
  23302. << pd->numInputChannels << (pd->numInputChannels == 1 ? " in" : " ins")
  23303. << " / "
  23304. << pd->numOutputChannels << (pd->numOutputChannels == 1 ? " out" : " outs");
  23305. if (pd->manufacturerName.isNotEmpty())
  23306. desc << " - " << pd->manufacturerName;
  23307. if (pd->version.isNotEmpty())
  23308. desc << " - " << pd->version;
  23309. if (pd->category.isNotEmpty())
  23310. desc << " - category: '" << pd->category << '\'';
  23311. g.setColour (Colours::grey);
  23312. ga.clear();
  23313. ga.addCurtailedLineOfText (Font (height * 0.6f), desc, r + 10.0f, height * 0.8f, width - r - 12.0f, true);
  23314. ga.draw (g);
  23315. }
  23316. }
  23317. void PluginListComponent::deleteKeyPressed (int lastRowSelected)
  23318. {
  23319. list.removeType (lastRowSelected);
  23320. }
  23321. void PluginListComponent::buttonClicked (Button* b)
  23322. {
  23323. if (optionsButton == b)
  23324. {
  23325. PopupMenu menu;
  23326. menu.addItem (1, TRANS("Clear list"));
  23327. menu.addItem (5, TRANS("Remove selected plugin from list"), listBox->getNumSelectedRows() > 0);
  23328. menu.addItem (6, TRANS("Show folder containing selected plugin"), listBox->getNumSelectedRows() > 0);
  23329. menu.addItem (7, TRANS("Remove any plugins whose files no longer exist"));
  23330. menu.addSeparator();
  23331. menu.addItem (2, TRANS("Sort alphabetically"));
  23332. menu.addItem (3, TRANS("Sort by category"));
  23333. menu.addItem (4, TRANS("Sort by manufacturer"));
  23334. menu.addSeparator();
  23335. for (int i = 0; i < AudioPluginFormatManager::getInstance()->getNumFormats(); ++i)
  23336. {
  23337. AudioPluginFormat* const format = AudioPluginFormatManager::getInstance()->getFormat (i);
  23338. if (format->getDefaultLocationsToSearch().getNumPaths() > 0)
  23339. menu.addItem (10 + i, "Scan for new or updated " + format->getName() + " plugins...");
  23340. }
  23341. const int r = menu.showAt (optionsButton);
  23342. if (r == 1)
  23343. {
  23344. list.clear();
  23345. }
  23346. else if (r == 2)
  23347. {
  23348. list.sort (KnownPluginList::sortAlphabetically);
  23349. }
  23350. else if (r == 3)
  23351. {
  23352. list.sort (KnownPluginList::sortByCategory);
  23353. }
  23354. else if (r == 4)
  23355. {
  23356. list.sort (KnownPluginList::sortByManufacturer);
  23357. }
  23358. else if (r == 5)
  23359. {
  23360. const SparseSet <int> selected (listBox->getSelectedRows());
  23361. for (int i = list.getNumTypes(); --i >= 0;)
  23362. if (selected.contains (i))
  23363. list.removeType (i);
  23364. }
  23365. else if (r == 6)
  23366. {
  23367. const PluginDescription* const desc = list.getType (listBox->getSelectedRow());
  23368. if (desc != 0)
  23369. {
  23370. if (File (desc->fileOrIdentifier).existsAsFile())
  23371. File (desc->fileOrIdentifier).getParentDirectory().startAsProcess();
  23372. }
  23373. }
  23374. else if (r == 7)
  23375. {
  23376. for (int i = list.getNumTypes(); --i >= 0;)
  23377. {
  23378. if (! AudioPluginFormatManager::getInstance()->doesPluginStillExist (*list.getType (i)))
  23379. {
  23380. list.removeType (i);
  23381. }
  23382. }
  23383. }
  23384. else if (r != 0)
  23385. {
  23386. typeToScan = r - 10;
  23387. startTimer (1);
  23388. }
  23389. }
  23390. }
  23391. void PluginListComponent::timerCallback()
  23392. {
  23393. stopTimer();
  23394. scanFor (AudioPluginFormatManager::getInstance()->getFormat (typeToScan));
  23395. }
  23396. bool PluginListComponent::isInterestedInFileDrag (const StringArray& /*files*/)
  23397. {
  23398. return true;
  23399. }
  23400. void PluginListComponent::filesDropped (const StringArray& files, int, int)
  23401. {
  23402. OwnedArray <PluginDescription> typesFound;
  23403. list.scanAndAddDragAndDroppedFiles (files, typesFound);
  23404. }
  23405. void PluginListComponent::scanFor (AudioPluginFormat* format)
  23406. {
  23407. if (format == 0)
  23408. return;
  23409. FileSearchPath path (format->getDefaultLocationsToSearch());
  23410. if (propertiesToUse != 0)
  23411. path = propertiesToUse->getValue ("lastPluginScanPath_" + format->getName(), path.toString());
  23412. {
  23413. AlertWindow aw (TRANS("Select folders to scan..."), String::empty, AlertWindow::NoIcon);
  23414. FileSearchPathListComponent pathList;
  23415. pathList.setSize (500, 300);
  23416. pathList.setPath (path);
  23417. aw.addCustomComponent (&pathList);
  23418. aw.addButton (TRANS("Scan"), 1, KeyPress::returnKey);
  23419. aw.addButton (TRANS("Cancel"), 0, KeyPress (KeyPress::escapeKey));
  23420. if (aw.runModalLoop() == 0)
  23421. return;
  23422. path = pathList.getPath();
  23423. }
  23424. if (propertiesToUse != 0)
  23425. {
  23426. propertiesToUse->setValue ("lastPluginScanPath_" + format->getName(), path.toString());
  23427. propertiesToUse->saveIfNeeded();
  23428. }
  23429. double progress = 0.0;
  23430. AlertWindow aw (TRANS("Scanning for plugins..."),
  23431. TRANS("Searching for all possible plugin files..."), AlertWindow::NoIcon);
  23432. aw.addButton (TRANS("Cancel"), 0, KeyPress (KeyPress::escapeKey));
  23433. aw.addProgressBarComponent (progress);
  23434. aw.enterModalState();
  23435. MessageManager::getInstance()->runDispatchLoopUntil (300);
  23436. PluginDirectoryScanner scanner (list, *format, path, true, deadMansPedalFile);
  23437. for (;;)
  23438. {
  23439. aw.setMessage (TRANS("Testing:\n\n")
  23440. + scanner.getNextPluginFileThatWillBeScanned());
  23441. MessageManager::getInstance()->runDispatchLoopUntil (20);
  23442. if (! scanner.scanNextFile (true))
  23443. break;
  23444. if (! aw.isCurrentlyModal())
  23445. break;
  23446. progress = scanner.getProgress();
  23447. }
  23448. if (scanner.getFailedFiles().size() > 0)
  23449. {
  23450. StringArray shortNames;
  23451. for (int i = 0; i < scanner.getFailedFiles().size(); ++i)
  23452. shortNames.add (File (scanner.getFailedFiles()[i]).getFileName());
  23453. AlertWindow::showMessageBox (AlertWindow::InfoIcon,
  23454. TRANS("Scan complete"),
  23455. TRANS("Note that the following files appeared to be plugin files, but failed to load correctly:\n\n")
  23456. + shortNames.joinIntoString (", "));
  23457. }
  23458. }
  23459. END_JUCE_NAMESPACE
  23460. /********* End of inlined file: juce_PluginListComponent.cpp *********/
  23461. /********* Start of inlined file: juce_AudioUnitPluginFormat.mm *********/
  23462. #if JUCE_PLUGINHOST_AU && (! (defined (LINUX) || defined (_WIN32)))
  23463. #include <AudioUnit/AudioUnit.h>
  23464. #include <AudioUnit/AUCocoaUIView.h>
  23465. #include <CoreAudioKit/AUGenericView.h>
  23466. #if JUCE_SUPPORT_CARBON
  23467. #include <AudioToolbox/AudioUnitUtilities.h>
  23468. #include <AudioUnit/AudioUnitCarbonView.h>
  23469. #endif
  23470. BEGIN_JUCE_NAMESPACE
  23471. #if JUCE_MAC && JUCE_SUPPORT_CARBON
  23472. #endif
  23473. #if JUCE_MAC
  23474. #if MACOS_10_3_OR_EARLIER
  23475. #define kAudioUnitType_Generator 'augn'
  23476. #endif
  23477. // Change this to disable logging of various activities
  23478. #ifndef AU_LOGGING
  23479. #define AU_LOGGING 1
  23480. #endif
  23481. #if AU_LOGGING
  23482. #define log(a) Logger::writeToLog(a);
  23483. #else
  23484. #define log(a)
  23485. #endif
  23486. static int insideCallback = 0;
  23487. static const String osTypeToString (OSType type) throw()
  23488. {
  23489. char s[4];
  23490. s[0] = (char) (((uint32) type) >> 24);
  23491. s[1] = (char) (((uint32) type) >> 16);
  23492. s[2] = (char) (((uint32) type) >> 8);
  23493. s[3] = (char) ((uint32) type);
  23494. return String (s, 4);
  23495. }
  23496. static OSType stringToOSType (const String& s1) throw()
  23497. {
  23498. const String s (s1 + " ");
  23499. return (((OSType) (unsigned char) s[0]) << 24)
  23500. | (((OSType) (unsigned char) s[1]) << 16)
  23501. | (((OSType) (unsigned char) s[2]) << 8)
  23502. | ((OSType) (unsigned char) s[3]);
  23503. }
  23504. static const tchar* auIdentifierPrefix = T("AudioUnit:");
  23505. static const String createAUPluginIdentifier (const ComponentDescription& desc)
  23506. {
  23507. jassert (osTypeToString ('abcd') == T("abcd")); // agh, must have got the endianness wrong..
  23508. jassert (stringToOSType ("abcd") == (OSType) 'abcd'); // ditto
  23509. String s (auIdentifierPrefix);
  23510. if (desc.componentType == kAudioUnitType_MusicDevice)
  23511. s << "Synths/";
  23512. else if (desc.componentType == kAudioUnitType_MusicEffect
  23513. || desc.componentType == kAudioUnitType_Effect)
  23514. s << "Effects/";
  23515. else if (desc.componentType == kAudioUnitType_Generator)
  23516. s << "Generators/";
  23517. else if (desc.componentType == kAudioUnitType_Panner)
  23518. s << "Panners/";
  23519. s << osTypeToString (desc.componentType)
  23520. << T(",")
  23521. << osTypeToString (desc.componentSubType)
  23522. << T(",")
  23523. << osTypeToString (desc.componentManufacturer);
  23524. return s;
  23525. }
  23526. static void getAUDetails (ComponentRecord* comp, String& name, String& manufacturer)
  23527. {
  23528. Handle componentNameHandle = NewHandle (sizeof (void*));
  23529. Handle componentInfoHandle = NewHandle (sizeof (void*));
  23530. if (componentNameHandle != 0 && componentInfoHandle != 0)
  23531. {
  23532. ComponentDescription desc;
  23533. if (GetComponentInfo (comp, &desc, componentNameHandle, componentInfoHandle, 0) == noErr)
  23534. {
  23535. ConstStr255Param nameString = (ConstStr255Param) (*componentNameHandle);
  23536. ConstStr255Param infoString = (ConstStr255Param) (*componentInfoHandle);
  23537. if (nameString != 0 && nameString[0] != 0)
  23538. {
  23539. const String all ((const char*) nameString + 1, nameString[0]);
  23540. DBG ("name: "+ all);
  23541. manufacturer = all.upToFirstOccurrenceOf (T(":"), false, false).trim();
  23542. name = all.fromFirstOccurrenceOf (T(":"), false, false).trim();
  23543. }
  23544. if (infoString != 0 && infoString[0] != 0)
  23545. {
  23546. const String all ((const char*) infoString + 1, infoString[0]);
  23547. DBG ("info: " + all);
  23548. }
  23549. if (name.isEmpty())
  23550. name = "<Unknown>";
  23551. }
  23552. DisposeHandle (componentNameHandle);
  23553. DisposeHandle (componentInfoHandle);
  23554. }
  23555. }
  23556. static bool getComponentDescFromIdentifier (const String& fileOrIdentifier, ComponentDescription& desc,
  23557. String& name, String& version, String& manufacturer)
  23558. {
  23559. zerostruct (desc);
  23560. if (fileOrIdentifier.startsWithIgnoreCase (auIdentifierPrefix))
  23561. {
  23562. String s (fileOrIdentifier.substring (jmax (fileOrIdentifier.lastIndexOfChar (T(':')),
  23563. fileOrIdentifier.lastIndexOfChar (T('/'))) + 1));
  23564. StringArray tokens;
  23565. tokens.addTokens (s, T(","), 0);
  23566. tokens.trim();
  23567. tokens.removeEmptyStrings();
  23568. if (tokens.size() == 3)
  23569. {
  23570. desc.componentType = stringToOSType (tokens[0]);
  23571. desc.componentSubType = stringToOSType (tokens[1]);
  23572. desc.componentManufacturer = stringToOSType (tokens[2]);
  23573. ComponentRecord* comp = FindNextComponent (0, &desc);
  23574. if (comp != 0)
  23575. {
  23576. getAUDetails (comp, name, manufacturer);
  23577. return true;
  23578. }
  23579. }
  23580. }
  23581. return false;
  23582. }
  23583. class AudioUnitPluginWindowCarbon;
  23584. class AudioUnitPluginWindowCocoa;
  23585. class AudioUnitPluginInstance : public AudioPluginInstance
  23586. {
  23587. public:
  23588. ~AudioUnitPluginInstance();
  23589. // AudioPluginInstance methods:
  23590. void fillInPluginDescription (PluginDescription& desc) const
  23591. {
  23592. desc.name = pluginName;
  23593. desc.fileOrIdentifier = createAUPluginIdentifier (componentDesc);
  23594. desc.uid = ((int) componentDesc.componentType)
  23595. ^ ((int) componentDesc.componentSubType)
  23596. ^ ((int) componentDesc.componentManufacturer);
  23597. desc.lastFileModTime = 0;
  23598. desc.pluginFormatName = "AudioUnit";
  23599. desc.category = getCategory();
  23600. desc.manufacturerName = manufacturer;
  23601. desc.version = version;
  23602. desc.numInputChannels = getNumInputChannels();
  23603. desc.numOutputChannels = getNumOutputChannels();
  23604. desc.isInstrument = (componentDesc.componentType == kAudioUnitType_MusicDevice);
  23605. }
  23606. const String getName() const { return pluginName; }
  23607. bool acceptsMidi() const { return wantsMidiMessages; }
  23608. bool producesMidi() const { return false; }
  23609. // AudioProcessor methods:
  23610. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  23611. void releaseResources();
  23612. void processBlock (AudioSampleBuffer& buffer,
  23613. MidiBuffer& midiMessages);
  23614. AudioProcessorEditor* createEditor();
  23615. const String getInputChannelName (const int index) const;
  23616. bool isInputChannelStereoPair (int index) const;
  23617. const String getOutputChannelName (const int index) const;
  23618. bool isOutputChannelStereoPair (int index) const;
  23619. int getNumParameters();
  23620. float getParameter (int index);
  23621. void setParameter (int index, float newValue);
  23622. const String getParameterName (int index);
  23623. const String getParameterText (int index);
  23624. bool isParameterAutomatable (int index) const;
  23625. int getNumPrograms();
  23626. int getCurrentProgram();
  23627. void setCurrentProgram (int index);
  23628. const String getProgramName (int index);
  23629. void changeProgramName (int index, const String& newName);
  23630. void getStateInformation (MemoryBlock& destData);
  23631. void getCurrentProgramStateInformation (MemoryBlock& destData);
  23632. void setStateInformation (const void* data, int sizeInBytes);
  23633. void setCurrentProgramStateInformation (const void* data, int sizeInBytes);
  23634. juce_UseDebuggingNewOperator
  23635. private:
  23636. friend class AudioUnitPluginWindowCarbon;
  23637. friend class AudioUnitPluginWindowCocoa;
  23638. friend class AudioUnitPluginFormat;
  23639. ComponentDescription componentDesc;
  23640. String pluginName, manufacturer, version;
  23641. String fileOrIdentifier;
  23642. CriticalSection lock;
  23643. bool initialised, wantsMidiMessages, wasPlaying;
  23644. AudioBufferList* outputBufferList;
  23645. AudioTimeStamp timeStamp;
  23646. AudioSampleBuffer* currentBuffer;
  23647. AudioUnit audioUnit;
  23648. Array <int> parameterIds;
  23649. bool getComponentDescFromFile (const String& fileOrIdentifier);
  23650. void initialise();
  23651. OSStatus renderGetInput (AudioUnitRenderActionFlags* ioActionFlags,
  23652. const AudioTimeStamp* inTimeStamp,
  23653. UInt32 inBusNumber,
  23654. UInt32 inNumberFrames,
  23655. AudioBufferList* ioData) const;
  23656. static OSStatus renderGetInputCallback (void* inRefCon,
  23657. AudioUnitRenderActionFlags* ioActionFlags,
  23658. const AudioTimeStamp* inTimeStamp,
  23659. UInt32 inBusNumber,
  23660. UInt32 inNumberFrames,
  23661. AudioBufferList* ioData)
  23662. {
  23663. return ((AudioUnitPluginInstance*) inRefCon)
  23664. ->renderGetInput (ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, ioData);
  23665. }
  23666. OSStatus getBeatAndTempo (Float64* outCurrentBeat, Float64* outCurrentTempo) const;
  23667. OSStatus getMusicalTimeLocation (UInt32* outDeltaSampleOffsetToNextBeat, Float32* outTimeSig_Numerator,
  23668. UInt32* outTimeSig_Denominator, Float64* outCurrentMeasureDownBeat) const;
  23669. OSStatus getTransportState (Boolean* outIsPlaying, Boolean* outTransportStateChanged,
  23670. Float64* outCurrentSampleInTimeLine, Boolean* outIsCycling,
  23671. Float64* outCycleStartBeat, Float64* outCycleEndBeat);
  23672. static OSStatus getBeatAndTempoCallback (void* inHostUserData, Float64* outCurrentBeat, Float64* outCurrentTempo)
  23673. {
  23674. return ((AudioUnitPluginInstance*) inHostUserData)->getBeatAndTempo (outCurrentBeat, outCurrentTempo);
  23675. }
  23676. static OSStatus getMusicalTimeLocationCallback (void* inHostUserData, UInt32* outDeltaSampleOffsetToNextBeat,
  23677. Float32* outTimeSig_Numerator, UInt32* outTimeSig_Denominator,
  23678. Float64* outCurrentMeasureDownBeat)
  23679. {
  23680. return ((AudioUnitPluginInstance*) inHostUserData)
  23681. ->getMusicalTimeLocation (outDeltaSampleOffsetToNextBeat, outTimeSig_Numerator,
  23682. outTimeSig_Denominator, outCurrentMeasureDownBeat);
  23683. }
  23684. static OSStatus getTransportStateCallback (void* inHostUserData, Boolean* outIsPlaying, Boolean* outTransportStateChanged,
  23685. Float64* outCurrentSampleInTimeLine, Boolean* outIsCycling,
  23686. Float64* outCycleStartBeat, Float64* outCycleEndBeat)
  23687. {
  23688. return ((AudioUnitPluginInstance*) inHostUserData)
  23689. ->getTransportState (outIsPlaying, outTransportStateChanged,
  23690. outCurrentSampleInTimeLine, outIsCycling,
  23691. outCycleStartBeat, outCycleEndBeat);
  23692. }
  23693. void getNumChannels (int& numIns, int& numOuts)
  23694. {
  23695. numIns = 0;
  23696. numOuts = 0;
  23697. AUChannelInfo supportedChannels [128];
  23698. UInt32 supportedChannelsSize = sizeof (supportedChannels);
  23699. if (AudioUnitGetProperty (audioUnit, kAudioUnitProperty_SupportedNumChannels, kAudioUnitScope_Global,
  23700. 0, supportedChannels, &supportedChannelsSize) == noErr
  23701. && supportedChannelsSize > 0)
  23702. {
  23703. for (int i = 0; i < supportedChannelsSize / sizeof (AUChannelInfo); ++i)
  23704. {
  23705. numIns = jmax (numIns, supportedChannels[i].inChannels);
  23706. numOuts = jmax (numOuts, supportedChannels[i].outChannels);
  23707. }
  23708. }
  23709. else
  23710. {
  23711. // (this really means the plugin will take any number of ins/outs as long
  23712. // as they are the same)
  23713. numIns = numOuts = 2;
  23714. }
  23715. }
  23716. const String getCategory() const;
  23717. AudioUnitPluginInstance (const String& fileOrIdentifier);
  23718. };
  23719. AudioUnitPluginInstance::AudioUnitPluginInstance (const String& fileOrIdentifier)
  23720. : fileOrIdentifier (fileOrIdentifier),
  23721. initialised (false),
  23722. wantsMidiMessages (false),
  23723. audioUnit (0),
  23724. outputBufferList (0),
  23725. currentBuffer (0)
  23726. {
  23727. try
  23728. {
  23729. ++insideCallback;
  23730. log (T("Opening AU: ") + fileOrIdentifier);
  23731. if (getComponentDescFromFile (fileOrIdentifier))
  23732. {
  23733. ComponentRecord* const comp = FindNextComponent (0, &componentDesc);
  23734. if (comp != 0)
  23735. {
  23736. audioUnit = (AudioUnit) OpenComponent (comp);
  23737. wantsMidiMessages = componentDesc.componentType == kAudioUnitType_MusicDevice
  23738. || componentDesc.componentType == kAudioUnitType_MusicEffect;
  23739. }
  23740. }
  23741. --insideCallback;
  23742. }
  23743. catch (...)
  23744. {
  23745. --insideCallback;
  23746. }
  23747. }
  23748. AudioUnitPluginInstance::~AudioUnitPluginInstance()
  23749. {
  23750. {
  23751. const ScopedLock sl (lock);
  23752. jassert (insideCallback == 0);
  23753. if (audioUnit != 0)
  23754. {
  23755. AudioUnitUninitialize (audioUnit);
  23756. CloseComponent (audioUnit);
  23757. audioUnit = 0;
  23758. }
  23759. }
  23760. juce_free (outputBufferList);
  23761. }
  23762. bool AudioUnitPluginInstance::getComponentDescFromFile (const String& fileOrIdentifier)
  23763. {
  23764. zerostruct (componentDesc);
  23765. if (getComponentDescFromIdentifier (fileOrIdentifier, componentDesc, pluginName, version, manufacturer))
  23766. return true;
  23767. const File file (fileOrIdentifier);
  23768. if (! file.hasFileExtension (T(".component")))
  23769. return false;
  23770. const char* const utf8 = fileOrIdentifier.toUTF8();
  23771. CFURLRef url = CFURLCreateFromFileSystemRepresentation (0, (const UInt8*) utf8,
  23772. strlen (utf8), file.isDirectory());
  23773. if (url != 0)
  23774. {
  23775. CFBundleRef bundleRef = CFBundleCreate (kCFAllocatorDefault, url);
  23776. CFRelease (url);
  23777. if (bundleRef != 0)
  23778. {
  23779. CFTypeRef name = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleName"));
  23780. if (name != 0 && CFGetTypeID (name) == CFStringGetTypeID())
  23781. pluginName = PlatformUtilities::cfStringToJuceString ((CFStringRef) name);
  23782. if (pluginName.isEmpty())
  23783. pluginName = file.getFileNameWithoutExtension();
  23784. CFTypeRef versionString = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleVersion"));
  23785. if (versionString != 0 && CFGetTypeID (versionString) == CFStringGetTypeID())
  23786. version = PlatformUtilities::cfStringToJuceString ((CFStringRef) versionString);
  23787. CFTypeRef manuString = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleGetInfoString"));
  23788. if (manuString != 0 && CFGetTypeID (manuString) == CFStringGetTypeID())
  23789. manufacturer = PlatformUtilities::cfStringToJuceString ((CFStringRef) manuString);
  23790. short resFileId = CFBundleOpenBundleResourceMap (bundleRef);
  23791. UseResFile (resFileId);
  23792. for (int i = 1; i <= Count1Resources ('thng'); ++i)
  23793. {
  23794. Handle h = Get1IndResource ('thng', i);
  23795. if (h != 0)
  23796. {
  23797. HLock (h);
  23798. const uint32* const types = (const uint32*) *h;
  23799. if (types[0] == kAudioUnitType_MusicDevice
  23800. || types[0] == kAudioUnitType_MusicEffect
  23801. || types[0] == kAudioUnitType_Effect
  23802. || types[0] == kAudioUnitType_Generator
  23803. || types[0] == kAudioUnitType_Panner)
  23804. {
  23805. componentDesc.componentType = types[0];
  23806. componentDesc.componentSubType = types[1];
  23807. componentDesc.componentManufacturer = types[2];
  23808. break;
  23809. }
  23810. HUnlock (h);
  23811. ReleaseResource (h);
  23812. }
  23813. }
  23814. CFBundleCloseBundleResourceMap (bundleRef, resFileId);
  23815. CFRelease (bundleRef);
  23816. }
  23817. }
  23818. return componentDesc.componentType != 0 && componentDesc.componentSubType != 0;
  23819. }
  23820. void AudioUnitPluginInstance::initialise()
  23821. {
  23822. if (initialised || audioUnit == 0)
  23823. return;
  23824. log (T("Initialising AU: ") + pluginName);
  23825. parameterIds.clear();
  23826. {
  23827. UInt32 paramListSize = 0;
  23828. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_ParameterList, kAudioUnitScope_Global,
  23829. 0, 0, &paramListSize);
  23830. if (paramListSize > 0)
  23831. {
  23832. parameterIds.insertMultiple (0, 0, paramListSize / sizeof (int));
  23833. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_ParameterList, kAudioUnitScope_Global,
  23834. 0, &parameterIds.getReference(0), &paramListSize);
  23835. }
  23836. }
  23837. {
  23838. AURenderCallbackStruct info;
  23839. zerostruct (info);
  23840. info.inputProcRefCon = this;
  23841. info.inputProc = renderGetInputCallback;
  23842. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input,
  23843. 0, &info, sizeof (info));
  23844. }
  23845. {
  23846. HostCallbackInfo info;
  23847. zerostruct (info);
  23848. info.hostUserData = this;
  23849. info.beatAndTempoProc = getBeatAndTempoCallback;
  23850. info.musicalTimeLocationProc = getMusicalTimeLocationCallback;
  23851. info.transportStateProc = getTransportStateCallback;
  23852. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_HostCallbacks, kAudioUnitScope_Global,
  23853. 0, &info, sizeof (info));
  23854. }
  23855. int numIns, numOuts;
  23856. getNumChannels (numIns, numOuts);
  23857. setPlayConfigDetails (numIns, numOuts, 0, 0);
  23858. initialised = AudioUnitInitialize (audioUnit) == noErr;
  23859. setLatencySamples (0);
  23860. }
  23861. void AudioUnitPluginInstance::prepareToPlay (double sampleRate_,
  23862. int samplesPerBlockExpected)
  23863. {
  23864. initialise();
  23865. if (initialised)
  23866. {
  23867. int numIns, numOuts;
  23868. getNumChannels (numIns, numOuts);
  23869. setPlayConfigDetails (numIns, numOuts, sampleRate_, samplesPerBlockExpected);
  23870. Float64 latencySecs = 0.0;
  23871. UInt32 latencySize = sizeof (latencySecs);
  23872. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_Latency, kAudioUnitScope_Global,
  23873. 0, &latencySecs, &latencySize);
  23874. setLatencySamples (roundDoubleToInt (latencySecs * sampleRate_));
  23875. AudioUnitReset (audioUnit, kAudioUnitScope_Input, 0);
  23876. AudioUnitReset (audioUnit, kAudioUnitScope_Output, 0);
  23877. AudioUnitReset (audioUnit, kAudioUnitScope_Global, 0);
  23878. AudioStreamBasicDescription stream;
  23879. zerostruct (stream);
  23880. stream.mSampleRate = sampleRate_;
  23881. stream.mFormatID = kAudioFormatLinearPCM;
  23882. stream.mFormatFlags = kAudioFormatFlagsNativeFloatPacked | kAudioFormatFlagIsNonInterleaved;
  23883. stream.mFramesPerPacket = 1;
  23884. stream.mBytesPerPacket = 4;
  23885. stream.mBytesPerFrame = 4;
  23886. stream.mBitsPerChannel = 32;
  23887. stream.mChannelsPerFrame = numIns;
  23888. OSStatus err = AudioUnitSetProperty (audioUnit,
  23889. kAudioUnitProperty_StreamFormat,
  23890. kAudioUnitScope_Input,
  23891. 0, &stream, sizeof (stream));
  23892. stream.mChannelsPerFrame = numOuts;
  23893. err = AudioUnitSetProperty (audioUnit,
  23894. kAudioUnitProperty_StreamFormat,
  23895. kAudioUnitScope_Output,
  23896. 0, &stream, sizeof (stream));
  23897. juce_free (outputBufferList);
  23898. outputBufferList = (AudioBufferList*) juce_calloc (sizeof (AudioBufferList) + sizeof (AudioBuffer) * (numOuts + 1));
  23899. outputBufferList->mNumberBuffers = numOuts;
  23900. for (int i = numOuts; --i >= 0;)
  23901. outputBufferList->mBuffers[i].mNumberChannels = 1;
  23902. zerostruct (timeStamp);
  23903. timeStamp.mSampleTime = 0;
  23904. timeStamp.mHostTime = AudioGetCurrentHostTime();
  23905. timeStamp.mFlags = kAudioTimeStampSampleTimeValid | kAudioTimeStampHostTimeValid;
  23906. currentBuffer = 0;
  23907. wasPlaying = false;
  23908. }
  23909. }
  23910. void AudioUnitPluginInstance::releaseResources()
  23911. {
  23912. if (initialised)
  23913. {
  23914. AudioUnitReset (audioUnit, kAudioUnitScope_Input, 0);
  23915. AudioUnitReset (audioUnit, kAudioUnitScope_Output, 0);
  23916. AudioUnitReset (audioUnit, kAudioUnitScope_Global, 0);
  23917. juce_free (outputBufferList);
  23918. outputBufferList = 0;
  23919. currentBuffer = 0;
  23920. }
  23921. }
  23922. OSStatus AudioUnitPluginInstance::renderGetInput (AudioUnitRenderActionFlags* ioActionFlags,
  23923. const AudioTimeStamp* inTimeStamp,
  23924. UInt32 inBusNumber,
  23925. UInt32 inNumberFrames,
  23926. AudioBufferList* ioData) const
  23927. {
  23928. if (inBusNumber == 0
  23929. && currentBuffer != 0)
  23930. {
  23931. jassert (inNumberFrames == currentBuffer->getNumSamples()); // if this ever happens, might need to add extra handling
  23932. for (int i = 0; i < ioData->mNumberBuffers; ++i)
  23933. {
  23934. if (i < currentBuffer->getNumChannels())
  23935. {
  23936. memcpy (ioData->mBuffers[i].mData,
  23937. currentBuffer->getSampleData (i, 0),
  23938. sizeof (float) * inNumberFrames);
  23939. }
  23940. else
  23941. {
  23942. zeromem (ioData->mBuffers[i].mData, sizeof (float) * inNumberFrames);
  23943. }
  23944. }
  23945. }
  23946. return noErr;
  23947. }
  23948. void AudioUnitPluginInstance::processBlock (AudioSampleBuffer& buffer,
  23949. MidiBuffer& midiMessages)
  23950. {
  23951. const int numSamples = buffer.getNumSamples();
  23952. if (initialised)
  23953. {
  23954. AudioUnitRenderActionFlags flags = 0;
  23955. timeStamp.mHostTime = AudioGetCurrentHostTime();
  23956. for (int i = getNumOutputChannels(); --i >= 0;)
  23957. {
  23958. outputBufferList->mBuffers[i].mDataByteSize = sizeof (float) * numSamples;
  23959. outputBufferList->mBuffers[i].mData = buffer.getSampleData (i, 0);
  23960. }
  23961. currentBuffer = &buffer;
  23962. if (wantsMidiMessages)
  23963. {
  23964. const uint8* midiEventData;
  23965. int midiEventSize, midiEventPosition;
  23966. MidiBuffer::Iterator i (midiMessages);
  23967. while (i.getNextEvent (midiEventData, midiEventSize, midiEventPosition))
  23968. {
  23969. if (midiEventSize <= 3)
  23970. MusicDeviceMIDIEvent (audioUnit,
  23971. midiEventData[0], midiEventData[1], midiEventData[2],
  23972. midiEventPosition);
  23973. else
  23974. MusicDeviceSysEx (audioUnit, midiEventData, midiEventSize);
  23975. }
  23976. midiMessages.clear();
  23977. }
  23978. AudioUnitRender (audioUnit, &flags, &timeStamp,
  23979. 0, numSamples, outputBufferList);
  23980. timeStamp.mSampleTime += numSamples;
  23981. }
  23982. else
  23983. {
  23984. // Not initialised, so just bypass..
  23985. for (int i = getNumInputChannels(); i < getNumOutputChannels(); ++i)
  23986. buffer.clear (i, 0, buffer.getNumSamples());
  23987. }
  23988. }
  23989. OSStatus AudioUnitPluginInstance::getBeatAndTempo (Float64* outCurrentBeat, Float64* outCurrentTempo) const
  23990. {
  23991. AudioPlayHead* const ph = getPlayHead();
  23992. AudioPlayHead::CurrentPositionInfo result;
  23993. if (ph != 0 && ph->getCurrentPosition (result))
  23994. {
  23995. if (outCurrentBeat != 0)
  23996. *outCurrentBeat = result.ppqPosition;
  23997. if (outCurrentTempo != 0)
  23998. *outCurrentTempo = result.bpm;
  23999. }
  24000. else
  24001. {
  24002. if (outCurrentBeat != 0)
  24003. *outCurrentBeat = 0;
  24004. if (outCurrentTempo != 0)
  24005. *outCurrentTempo = 120.0;
  24006. }
  24007. return noErr;
  24008. }
  24009. OSStatus AudioUnitPluginInstance::getMusicalTimeLocation (UInt32* outDeltaSampleOffsetToNextBeat,
  24010. Float32* outTimeSig_Numerator,
  24011. UInt32* outTimeSig_Denominator,
  24012. Float64* outCurrentMeasureDownBeat) const
  24013. {
  24014. AudioPlayHead* const ph = getPlayHead();
  24015. AudioPlayHead::CurrentPositionInfo result;
  24016. if (ph != 0 && ph->getCurrentPosition (result))
  24017. {
  24018. if (outTimeSig_Numerator != 0)
  24019. *outTimeSig_Numerator = result.timeSigNumerator;
  24020. if (outTimeSig_Denominator != 0)
  24021. *outTimeSig_Denominator = result.timeSigDenominator;
  24022. if (outDeltaSampleOffsetToNextBeat != 0)
  24023. *outDeltaSampleOffsetToNextBeat = 0; //xxx
  24024. if (outCurrentMeasureDownBeat != 0)
  24025. *outCurrentMeasureDownBeat = result.ppqPositionOfLastBarStart; //xxx wrong
  24026. }
  24027. else
  24028. {
  24029. if (outDeltaSampleOffsetToNextBeat != 0)
  24030. *outDeltaSampleOffsetToNextBeat = 0;
  24031. if (outTimeSig_Numerator != 0)
  24032. *outTimeSig_Numerator = 4;
  24033. if (outTimeSig_Denominator != 0)
  24034. *outTimeSig_Denominator = 4;
  24035. if (outCurrentMeasureDownBeat != 0)
  24036. *outCurrentMeasureDownBeat = 0;
  24037. }
  24038. return noErr;
  24039. }
  24040. OSStatus AudioUnitPluginInstance::getTransportState (Boolean* outIsPlaying,
  24041. Boolean* outTransportStateChanged,
  24042. Float64* outCurrentSampleInTimeLine,
  24043. Boolean* outIsCycling,
  24044. Float64* outCycleStartBeat,
  24045. Float64* outCycleEndBeat)
  24046. {
  24047. AudioPlayHead* const ph = getPlayHead();
  24048. AudioPlayHead::CurrentPositionInfo result;
  24049. if (ph != 0 && ph->getCurrentPosition (result))
  24050. {
  24051. if (outIsPlaying != 0)
  24052. *outIsPlaying = result.isPlaying;
  24053. if (outTransportStateChanged != 0)
  24054. {
  24055. *outTransportStateChanged = result.isPlaying != wasPlaying;
  24056. wasPlaying = result.isPlaying;
  24057. }
  24058. if (outCurrentSampleInTimeLine != 0)
  24059. *outCurrentSampleInTimeLine = roundDoubleToInt (result.timeInSeconds * getSampleRate());
  24060. if (outIsCycling != 0)
  24061. *outIsCycling = false;
  24062. if (outCycleStartBeat != 0)
  24063. *outCycleStartBeat = 0;
  24064. if (outCycleEndBeat != 0)
  24065. *outCycleEndBeat = 0;
  24066. }
  24067. else
  24068. {
  24069. if (outIsPlaying != 0)
  24070. *outIsPlaying = false;
  24071. if (outTransportStateChanged != 0)
  24072. *outTransportStateChanged = false;
  24073. if (outCurrentSampleInTimeLine != 0)
  24074. *outCurrentSampleInTimeLine = 0;
  24075. if (outIsCycling != 0)
  24076. *outIsCycling = false;
  24077. if (outCycleStartBeat != 0)
  24078. *outCycleStartBeat = 0;
  24079. if (outCycleEndBeat != 0)
  24080. *outCycleEndBeat = 0;
  24081. }
  24082. return noErr;
  24083. }
  24084. static VoidArray activeWindows;
  24085. class AudioUnitPluginWindowCocoa : public AudioProcessorEditor
  24086. {
  24087. public:
  24088. AudioUnitPluginWindowCocoa (AudioUnitPluginInstance& plugin_, const bool createGenericViewIfNeeded)
  24089. : AudioProcessorEditor (&plugin_),
  24090. plugin (plugin_),
  24091. wrapper (0)
  24092. {
  24093. addAndMakeVisible (wrapper = new NSViewComponent());
  24094. activeWindows.add (this);
  24095. setOpaque (true);
  24096. setVisible (true);
  24097. setSize (100, 100);
  24098. createView (createGenericViewIfNeeded);
  24099. }
  24100. ~AudioUnitPluginWindowCocoa()
  24101. {
  24102. const bool wasValid = isValid();
  24103. wrapper->setView (0);
  24104. activeWindows.removeValue (this);
  24105. if (wasValid)
  24106. plugin.editorBeingDeleted (this);
  24107. delete wrapper;
  24108. }
  24109. bool isValid() const { return wrapper->getView() != 0; }
  24110. void paint (Graphics& g)
  24111. {
  24112. g.fillAll (Colours::white);
  24113. }
  24114. void resized()
  24115. {
  24116. wrapper->setSize (getWidth(), getHeight());
  24117. }
  24118. private:
  24119. AudioUnitPluginInstance& plugin;
  24120. NSViewComponent* wrapper;
  24121. bool createView (const bool createGenericViewIfNeeded)
  24122. {
  24123. NSView* pluginView = 0;
  24124. UInt32 dataSize = 0;
  24125. Boolean isWritable = false;
  24126. if (AudioUnitGetPropertyInfo (plugin.audioUnit, kAudioUnitProperty_CocoaUI, kAudioUnitScope_Global,
  24127. 0, &dataSize, &isWritable) == noErr
  24128. && dataSize != 0
  24129. && AudioUnitGetPropertyInfo (plugin.audioUnit, kAudioUnitProperty_CocoaUI, kAudioUnitScope_Global,
  24130. 0, &dataSize, &isWritable) == noErr)
  24131. {
  24132. AudioUnitCocoaViewInfo* info = (AudioUnitCocoaViewInfo*) juce_calloc (dataSize);
  24133. if (AudioUnitGetProperty (plugin.audioUnit, kAudioUnitProperty_CocoaUI, kAudioUnitScope_Global,
  24134. 0, info, &dataSize) == noErr)
  24135. {
  24136. NSString* viewClassName = (NSString*) (info->mCocoaAUViewClass[0]);
  24137. NSString* path = (NSString*) CFURLCopyPath (info->mCocoaAUViewBundleLocation);
  24138. NSBundle* viewBundle = [NSBundle bundleWithPath: [path autorelease]];
  24139. Class viewClass = [viewBundle classNamed: viewClassName];
  24140. if ([viewClass conformsToProtocol: @protocol (AUCocoaUIBase)]
  24141. && [viewClass instancesRespondToSelector: @selector (interfaceVersion)]
  24142. && [viewClass instancesRespondToSelector: @selector (uiViewForAudioUnit: withSize:)])
  24143. {
  24144. id factory = [[[viewClass alloc] init] autorelease];
  24145. pluginView = [factory uiViewForAudioUnit: plugin.audioUnit
  24146. withSize: NSMakeSize (getWidth(), getHeight())];
  24147. }
  24148. for (int i = (dataSize - sizeof (CFURLRef)) / sizeof (CFStringRef); --i >= 0;)
  24149. {
  24150. CFRelease (info->mCocoaAUViewClass[i]);
  24151. CFRelease (info->mCocoaAUViewBundleLocation);
  24152. }
  24153. }
  24154. juce_free (info);
  24155. }
  24156. if (createGenericViewIfNeeded && (pluginView == 0))
  24157. pluginView = [[AUGenericView alloc] initWithAudioUnit: plugin.audioUnit];
  24158. wrapper->setView (pluginView);
  24159. if (pluginView != 0)
  24160. setSize ([pluginView frame].size.width,
  24161. [pluginView frame].size.height);
  24162. return pluginView != 0;
  24163. }
  24164. };
  24165. #if JUCE_SUPPORT_CARBON
  24166. class AudioUnitPluginWindowCarbon : public AudioProcessorEditor
  24167. {
  24168. public:
  24169. AudioUnitPluginWindowCarbon (AudioUnitPluginInstance& plugin_)
  24170. : AudioProcessorEditor (&plugin_),
  24171. plugin (plugin_),
  24172. viewComponent (0)
  24173. {
  24174. addAndMakeVisible (innerWrapper = new InnerWrapperComponent (this));
  24175. activeWindows.add (this);
  24176. setOpaque (true);
  24177. setVisible (true);
  24178. setSize (400, 300);
  24179. ComponentDescription viewList [16];
  24180. UInt32 viewListSize = sizeof (viewList);
  24181. AudioUnitGetProperty (plugin.audioUnit, kAudioUnitProperty_GetUIComponentList, kAudioUnitScope_Global,
  24182. 0, &viewList, &viewListSize);
  24183. componentRecord = FindNextComponent (0, &viewList[0]);
  24184. }
  24185. ~AudioUnitPluginWindowCarbon()
  24186. {
  24187. deleteAndZero (innerWrapper);
  24188. activeWindows.removeValue (this);
  24189. if (isValid())
  24190. plugin.editorBeingDeleted (this);
  24191. }
  24192. bool isValid() const throw() { return componentRecord != 0; }
  24193. void paint (Graphics& g)
  24194. {
  24195. g.fillAll (Colours::black);
  24196. }
  24197. void resized()
  24198. {
  24199. innerWrapper->setSize (getWidth(), getHeight());
  24200. }
  24201. bool keyStateChanged (const bool)
  24202. {
  24203. return false;
  24204. }
  24205. bool keyPressed (const KeyPress&)
  24206. {
  24207. return false;
  24208. }
  24209. void broughtToFront()
  24210. {
  24211. activeWindows.removeValue (this);
  24212. activeWindows.add (this);
  24213. }
  24214. AudioUnit getAudioUnit() const { return plugin.audioUnit; }
  24215. AudioUnitCarbonView getViewComponent()
  24216. {
  24217. if (viewComponent == 0 && componentRecord != 0)
  24218. viewComponent = (AudioUnitCarbonView) OpenComponent (componentRecord);
  24219. return viewComponent;
  24220. }
  24221. void closeViewComponent()
  24222. {
  24223. if (viewComponent != 0)
  24224. {
  24225. CloseComponent (viewComponent);
  24226. viewComponent = 0;
  24227. }
  24228. }
  24229. juce_UseDebuggingNewOperator
  24230. private:
  24231. AudioUnitPluginInstance& plugin;
  24232. ComponentRecord* componentRecord;
  24233. AudioUnitCarbonView viewComponent;
  24234. class InnerWrapperComponent : public CarbonViewWrapperComponent
  24235. {
  24236. public:
  24237. InnerWrapperComponent (AudioUnitPluginWindowCarbon* const owner_)
  24238. : owner (owner_)
  24239. {
  24240. }
  24241. ~InnerWrapperComponent()
  24242. {
  24243. deleteWindow();
  24244. }
  24245. HIViewRef attachView (WindowRef windowRef, HIViewRef rootView)
  24246. {
  24247. log (T("Opening AU GUI: ") + owner->plugin.getName());
  24248. AudioUnitCarbonView viewComponent = owner->getViewComponent();
  24249. if (viewComponent == 0)
  24250. return 0;
  24251. Float32Point pos = { 0, 0 };
  24252. Float32Point size = { 250, 200 };
  24253. HIViewRef pluginView = 0;
  24254. AudioUnitCarbonViewCreate (viewComponent,
  24255. owner->getAudioUnit(),
  24256. windowRef,
  24257. rootView,
  24258. &pos,
  24259. &size,
  24260. (ControlRef*) &pluginView);
  24261. return pluginView;
  24262. }
  24263. void removeView (HIViewRef)
  24264. {
  24265. log (T("Closing AU GUI: ") + owner->plugin.getName());
  24266. owner->closeViewComponent();
  24267. }
  24268. private:
  24269. AudioUnitPluginWindowCarbon* const owner;
  24270. };
  24271. friend class InnerWrapperComponent;
  24272. InnerWrapperComponent* innerWrapper;
  24273. };
  24274. #endif
  24275. AudioProcessorEditor* AudioUnitPluginInstance::createEditor()
  24276. {
  24277. AudioProcessorEditor* w = new AudioUnitPluginWindowCocoa (*this, false);
  24278. if (! ((AudioUnitPluginWindowCocoa*) w)->isValid())
  24279. deleteAndZero (w);
  24280. #if JUCE_SUPPORT_CARBON
  24281. if (w == 0)
  24282. {
  24283. w = new AudioUnitPluginWindowCarbon (*this);
  24284. if (! ((AudioUnitPluginWindowCarbon*) w)->isValid())
  24285. deleteAndZero (w);
  24286. }
  24287. #endif
  24288. if (w == 0)
  24289. w = new AudioUnitPluginWindowCocoa (*this, true); // use AUGenericView as a fallback
  24290. return w;
  24291. }
  24292. const String AudioUnitPluginInstance::getCategory() const
  24293. {
  24294. const char* result = 0;
  24295. switch (componentDesc.componentType)
  24296. {
  24297. case kAudioUnitType_Effect:
  24298. case kAudioUnitType_MusicEffect:
  24299. result = "Effect";
  24300. break;
  24301. case kAudioUnitType_MusicDevice:
  24302. result = "Synth";
  24303. break;
  24304. case kAudioUnitType_Generator:
  24305. result = "Generator";
  24306. break;
  24307. case kAudioUnitType_Panner:
  24308. result = "Panner";
  24309. break;
  24310. default:
  24311. break;
  24312. }
  24313. return result;
  24314. }
  24315. int AudioUnitPluginInstance::getNumParameters()
  24316. {
  24317. return parameterIds.size();
  24318. }
  24319. float AudioUnitPluginInstance::getParameter (int index)
  24320. {
  24321. const ScopedLock sl (lock);
  24322. Float32 value = 0.0f;
  24323. if (audioUnit != 0 && ((unsigned int) index) < (unsigned int) parameterIds.size())
  24324. {
  24325. AudioUnitGetParameter (audioUnit,
  24326. (UInt32) parameterIds.getUnchecked (index),
  24327. kAudioUnitScope_Global, 0,
  24328. &value);
  24329. }
  24330. return value;
  24331. }
  24332. void AudioUnitPluginInstance::setParameter (int index, float newValue)
  24333. {
  24334. const ScopedLock sl (lock);
  24335. if (audioUnit != 0 && ((unsigned int) index) < (unsigned int) parameterIds.size())
  24336. {
  24337. AudioUnitSetParameter (audioUnit,
  24338. (UInt32) parameterIds.getUnchecked (index),
  24339. kAudioUnitScope_Global, 0,
  24340. newValue, 0);
  24341. }
  24342. }
  24343. const String AudioUnitPluginInstance::getParameterName (int index)
  24344. {
  24345. AudioUnitParameterInfo info;
  24346. zerostruct (info);
  24347. UInt32 sz = sizeof (info);
  24348. String name;
  24349. if (AudioUnitGetProperty (audioUnit,
  24350. kAudioUnitProperty_ParameterInfo,
  24351. kAudioUnitScope_Global,
  24352. parameterIds [index], &info, &sz) == noErr)
  24353. {
  24354. if ((info.flags & kAudioUnitParameterFlag_HasCFNameString) != 0)
  24355. name = PlatformUtilities::cfStringToJuceString (info.cfNameString);
  24356. else
  24357. name = String (info.name, sizeof (info.name));
  24358. }
  24359. return name;
  24360. }
  24361. const String AudioUnitPluginInstance::getParameterText (int index)
  24362. {
  24363. return String (getParameter (index));
  24364. }
  24365. bool AudioUnitPluginInstance::isParameterAutomatable (int index) const
  24366. {
  24367. AudioUnitParameterInfo info;
  24368. UInt32 sz = sizeof (info);
  24369. if (AudioUnitGetProperty (audioUnit,
  24370. kAudioUnitProperty_ParameterInfo,
  24371. kAudioUnitScope_Global,
  24372. parameterIds [index], &info, &sz) == noErr)
  24373. {
  24374. return (info.flags & kAudioUnitParameterFlag_NonRealTime) == 0;
  24375. }
  24376. return true;
  24377. }
  24378. int AudioUnitPluginInstance::getNumPrograms()
  24379. {
  24380. CFArrayRef presets;
  24381. UInt32 sz = sizeof (CFArrayRef);
  24382. int num = 0;
  24383. if (AudioUnitGetProperty (audioUnit,
  24384. kAudioUnitProperty_FactoryPresets,
  24385. kAudioUnitScope_Global,
  24386. 0, &presets, &sz) == noErr)
  24387. {
  24388. num = (int) CFArrayGetCount (presets);
  24389. CFRelease (presets);
  24390. }
  24391. return num;
  24392. }
  24393. int AudioUnitPluginInstance::getCurrentProgram()
  24394. {
  24395. AUPreset current;
  24396. current.presetNumber = 0;
  24397. UInt32 sz = sizeof (AUPreset);
  24398. AudioUnitGetProperty (audioUnit,
  24399. kAudioUnitProperty_FactoryPresets,
  24400. kAudioUnitScope_Global,
  24401. 0, &current, &sz);
  24402. return current.presetNumber;
  24403. }
  24404. void AudioUnitPluginInstance::setCurrentProgram (int newIndex)
  24405. {
  24406. AUPreset current;
  24407. current.presetNumber = newIndex;
  24408. current.presetName = 0;
  24409. AudioUnitSetProperty (audioUnit,
  24410. kAudioUnitProperty_FactoryPresets,
  24411. kAudioUnitScope_Global,
  24412. 0, &current, sizeof (AUPreset));
  24413. }
  24414. const String AudioUnitPluginInstance::getProgramName (int index)
  24415. {
  24416. String s;
  24417. CFArrayRef presets;
  24418. UInt32 sz = sizeof (CFArrayRef);
  24419. if (AudioUnitGetProperty (audioUnit,
  24420. kAudioUnitProperty_FactoryPresets,
  24421. kAudioUnitScope_Global,
  24422. 0, &presets, &sz) == noErr)
  24423. {
  24424. for (CFIndex i = 0; i < CFArrayGetCount (presets); ++i)
  24425. {
  24426. const AUPreset* p = (const AUPreset*) CFArrayGetValueAtIndex (presets, i);
  24427. if (p != 0 && p->presetNumber == index)
  24428. {
  24429. s = PlatformUtilities::cfStringToJuceString (p->presetName);
  24430. break;
  24431. }
  24432. }
  24433. CFRelease (presets);
  24434. }
  24435. return s;
  24436. }
  24437. void AudioUnitPluginInstance::changeProgramName (int index, const String& newName)
  24438. {
  24439. jassertfalse // xxx not implemented!
  24440. }
  24441. const String AudioUnitPluginInstance::getInputChannelName (const int index) const
  24442. {
  24443. if (((unsigned int) index) < (unsigned int) getNumInputChannels())
  24444. return T("Input ") + String (index + 1);
  24445. return String::empty;
  24446. }
  24447. bool AudioUnitPluginInstance::isInputChannelStereoPair (int index) const
  24448. {
  24449. if (((unsigned int) index) >= (unsigned int) getNumInputChannels())
  24450. return false;
  24451. return true;
  24452. }
  24453. const String AudioUnitPluginInstance::getOutputChannelName (const int index) const
  24454. {
  24455. if (((unsigned int) index) < (unsigned int) getNumOutputChannels())
  24456. return T("Output ") + String (index + 1);
  24457. return String::empty;
  24458. }
  24459. bool AudioUnitPluginInstance::isOutputChannelStereoPair (int index) const
  24460. {
  24461. if (((unsigned int) index) >= (unsigned int) getNumOutputChannels())
  24462. return false;
  24463. return true;
  24464. }
  24465. void AudioUnitPluginInstance::getStateInformation (MemoryBlock& destData)
  24466. {
  24467. getCurrentProgramStateInformation (destData);
  24468. }
  24469. void AudioUnitPluginInstance::getCurrentProgramStateInformation (MemoryBlock& destData)
  24470. {
  24471. CFPropertyListRef propertyList = 0;
  24472. UInt32 sz = sizeof (CFPropertyListRef);
  24473. if (AudioUnitGetProperty (audioUnit,
  24474. kAudioUnitProperty_ClassInfo,
  24475. kAudioUnitScope_Global,
  24476. 0, &propertyList, &sz) == noErr)
  24477. {
  24478. CFWriteStreamRef stream = CFWriteStreamCreateWithAllocatedBuffers (kCFAllocatorDefault, kCFAllocatorDefault);
  24479. CFWriteStreamOpen (stream);
  24480. CFIndex bytesWritten = CFPropertyListWriteToStream (propertyList, stream, kCFPropertyListBinaryFormat_v1_0, 0);
  24481. CFWriteStreamClose (stream);
  24482. CFDataRef data = (CFDataRef) CFWriteStreamCopyProperty (stream, kCFStreamPropertyDataWritten);
  24483. destData.setSize (bytesWritten);
  24484. destData.copyFrom (CFDataGetBytePtr (data), 0, destData.getSize());
  24485. CFRelease (data);
  24486. CFRelease (stream);
  24487. CFRelease (propertyList);
  24488. }
  24489. }
  24490. void AudioUnitPluginInstance::setStateInformation (const void* data, int sizeInBytes)
  24491. {
  24492. setCurrentProgramStateInformation (data, sizeInBytes);
  24493. }
  24494. void AudioUnitPluginInstance::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  24495. {
  24496. CFReadStreamRef stream = CFReadStreamCreateWithBytesNoCopy (kCFAllocatorDefault,
  24497. (const UInt8*) data,
  24498. sizeInBytes,
  24499. kCFAllocatorNull);
  24500. CFReadStreamOpen (stream);
  24501. CFPropertyListFormat format = kCFPropertyListBinaryFormat_v1_0;
  24502. CFPropertyListRef propertyList = CFPropertyListCreateFromStream (kCFAllocatorDefault,
  24503. stream,
  24504. 0,
  24505. kCFPropertyListImmutable,
  24506. &format,
  24507. 0);
  24508. CFRelease (stream);
  24509. if (propertyList != 0)
  24510. AudioUnitSetProperty (audioUnit,
  24511. kAudioUnitProperty_ClassInfo,
  24512. kAudioUnitScope_Global,
  24513. 0, &propertyList, sizeof (propertyList));
  24514. }
  24515. AudioUnitPluginFormat::AudioUnitPluginFormat()
  24516. {
  24517. }
  24518. AudioUnitPluginFormat::~AudioUnitPluginFormat()
  24519. {
  24520. }
  24521. void AudioUnitPluginFormat::findAllTypesForFile (OwnedArray <PluginDescription>& results,
  24522. const String& fileOrIdentifier)
  24523. {
  24524. if (! fileMightContainThisPluginType (fileOrIdentifier))
  24525. return;
  24526. PluginDescription desc;
  24527. desc.fileOrIdentifier = fileOrIdentifier;
  24528. desc.uid = 0;
  24529. AudioUnitPluginInstance* instance = dynamic_cast <AudioUnitPluginInstance*> (createInstanceFromDescription (desc));
  24530. if (instance == 0)
  24531. return;
  24532. try
  24533. {
  24534. instance->fillInPluginDescription (desc);
  24535. results.add (new PluginDescription (desc));
  24536. }
  24537. catch (...)
  24538. {
  24539. // crashed while loading...
  24540. }
  24541. deleteAndZero (instance);
  24542. }
  24543. AudioPluginInstance* AudioUnitPluginFormat::createInstanceFromDescription (const PluginDescription& desc)
  24544. {
  24545. AudioUnitPluginInstance* result = 0;
  24546. if (fileMightContainThisPluginType (desc.fileOrIdentifier))
  24547. {
  24548. result = new AudioUnitPluginInstance (desc.fileOrIdentifier);
  24549. if (result->audioUnit != 0)
  24550. {
  24551. result->initialise();
  24552. }
  24553. else
  24554. {
  24555. deleteAndZero (result);
  24556. }
  24557. }
  24558. return result;
  24559. }
  24560. const StringArray AudioUnitPluginFormat::searchPathsForPlugins (const FileSearchPath& /*directoriesToSearch*/,
  24561. const bool /*recursive*/)
  24562. {
  24563. StringArray result;
  24564. ComponentRecord* comp = 0;
  24565. ComponentDescription desc;
  24566. zerostruct (desc);
  24567. for (;;)
  24568. {
  24569. zerostruct (desc);
  24570. comp = FindNextComponent (comp, &desc);
  24571. if (comp == 0)
  24572. break;
  24573. GetComponentInfo (comp, &desc, 0, 0, 0);
  24574. if (desc.componentType == kAudioUnitType_MusicDevice
  24575. || desc.componentType == kAudioUnitType_MusicEffect
  24576. || desc.componentType == kAudioUnitType_Effect
  24577. || desc.componentType == kAudioUnitType_Generator
  24578. || desc.componentType == kAudioUnitType_Panner)
  24579. {
  24580. const String s (createAUPluginIdentifier (desc));
  24581. DBG (s);
  24582. result.add (s);
  24583. }
  24584. }
  24585. return result;
  24586. }
  24587. bool AudioUnitPluginFormat::fileMightContainThisPluginType (const String& fileOrIdentifier)
  24588. {
  24589. ComponentDescription desc;
  24590. String name, version, manufacturer;
  24591. if (getComponentDescFromIdentifier (fileOrIdentifier, desc, name, version, manufacturer))
  24592. return FindNextComponent (0, &desc) != 0;
  24593. const File f (fileOrIdentifier);
  24594. return f.hasFileExtension (T(".component"))
  24595. && f.isDirectory();
  24596. }
  24597. const String AudioUnitPluginFormat::getNameOfPluginFromIdentifier (const String& fileOrIdentifier)
  24598. {
  24599. ComponentDescription desc;
  24600. String name, version, manufacturer;
  24601. getComponentDescFromIdentifier (fileOrIdentifier, desc, name, version, manufacturer);
  24602. if (name.isEmpty())
  24603. name = fileOrIdentifier;
  24604. return name;
  24605. }
  24606. bool AudioUnitPluginFormat::doesPluginStillExist (const PluginDescription& desc)
  24607. {
  24608. return File (desc.fileOrIdentifier).exists();
  24609. }
  24610. const FileSearchPath AudioUnitPluginFormat::getDefaultLocationsToSearch()
  24611. {
  24612. return FileSearchPath ("/(Default AudioUnit locations)");
  24613. }
  24614. #endif
  24615. END_JUCE_NAMESPACE
  24616. #undef log
  24617. #endif
  24618. /********* End of inlined file: juce_AudioUnitPluginFormat.mm *********/
  24619. /********* Start of inlined file: juce_VSTPluginFormat.mm *********/
  24620. // This file just wraps juce_VSTPluginFormat.cpp in an objective-C wrapper
  24621. #define JUCE_MAC_VST_INCLUDED 1
  24622. /********* Start of inlined file: juce_VSTPluginFormat.cpp *********/
  24623. #if JUCE_PLUGINHOST_VST
  24624. #if (defined (_WIN32) || defined (_WIN64))
  24625. #undef _WIN32_WINNT
  24626. #define _WIN32_WINNT 0x500
  24627. #undef STRICT
  24628. #define STRICT
  24629. #include <windows.h>
  24630. #include <float.h>
  24631. #pragma warning (disable : 4312 4355)
  24632. #elif defined (LINUX) || defined (__linux__)
  24633. #include <float.h>
  24634. #include <sys/time.h>
  24635. #include <X11/Xlib.h>
  24636. #include <X11/Xutil.h>
  24637. #include <X11/Xatom.h>
  24638. #undef Font
  24639. #undef KeyPress
  24640. #undef Drawable
  24641. #undef Time
  24642. #else
  24643. #ifndef JUCE_MAC_VST_INCLUDED
  24644. // On the mac, this file needs to be compiled indirectly, by using
  24645. // juce_VSTPluginFormat.mm instead - that wraps it as an objective-C file for cocoa
  24646. #error
  24647. #endif
  24648. #include <Cocoa/Cocoa.h>
  24649. #include <Carbon/Carbon.h>
  24650. #endif
  24651. #if ! (JUCE_MAC && JUCE_64BIT)
  24652. BEGIN_JUCE_NAMESPACE
  24653. #if JUCE_MAC && JUCE_SUPPORT_CARBON
  24654. #endif
  24655. #undef PRAGMA_ALIGN_SUPPORTED
  24656. #define VST_FORCE_DEPRECATED 0
  24657. #ifdef _MSC_VER
  24658. #pragma warning (push)
  24659. #pragma warning (disable: 4996)
  24660. #endif
  24661. /* Obviously you're going to need the Steinberg vstsdk2.4 folder in
  24662. your include path if you want to add VST support.
  24663. If you're not interested in VSTs, you can disable them by changing the
  24664. JUCE_PLUGINHOST_VST flag in juce_Config.h
  24665. */
  24666. #include "pluginterfaces/vst2.x/aeffectx.h"
  24667. #ifdef _MSC_VER
  24668. #pragma warning (pop)
  24669. #endif
  24670. #if JUCE_LINUX
  24671. #define Font JUCE_NAMESPACE::Font
  24672. #define KeyPress JUCE_NAMESPACE::KeyPress
  24673. #define Drawable JUCE_NAMESPACE::Drawable
  24674. #define Time JUCE_NAMESPACE::Time
  24675. #endif
  24676. /********* Start of inlined file: juce_VSTMidiEventList.h *********/
  24677. #ifdef __aeffect__
  24678. #ifndef __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  24679. #define __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  24680. /** Holds a set of VSTMidiEvent objects and makes it easy to add
  24681. events to the list.
  24682. This is used by both the VST hosting code and the plugin wrapper.
  24683. */
  24684. class VSTMidiEventList
  24685. {
  24686. public:
  24687. VSTMidiEventList()
  24688. : events (0), numEventsUsed (0), numEventsAllocated (0)
  24689. {
  24690. }
  24691. ~VSTMidiEventList()
  24692. {
  24693. freeEvents();
  24694. }
  24695. void clear()
  24696. {
  24697. numEventsUsed = 0;
  24698. if (events != 0)
  24699. events->numEvents = 0;
  24700. }
  24701. void addEvent (const void* const midiData, const int numBytes, const int frameOffset)
  24702. {
  24703. ensureSize (numEventsUsed + 1);
  24704. VstMidiEvent* const e = (VstMidiEvent*) (events->events [numEventsUsed]);
  24705. events->numEvents = ++numEventsUsed;
  24706. if (numBytes <= 4)
  24707. {
  24708. if (e->type == kVstSysExType)
  24709. {
  24710. juce_free (((VstMidiSysexEvent*) e)->sysexDump);
  24711. e->type = kVstMidiType;
  24712. e->byteSize = sizeof (VstMidiEvent);
  24713. e->noteLength = 0;
  24714. e->noteOffset = 0;
  24715. e->detune = 0;
  24716. e->noteOffVelocity = 0;
  24717. }
  24718. e->deltaFrames = frameOffset;
  24719. memcpy (e->midiData, midiData, numBytes);
  24720. }
  24721. else
  24722. {
  24723. VstMidiSysexEvent* const se = (VstMidiSysexEvent*) e;
  24724. if (se->type == kVstSysExType)
  24725. se->sysexDump = (char*) juce_realloc (se->sysexDump, numBytes);
  24726. else
  24727. se->sysexDump = (char*) juce_malloc (numBytes);
  24728. memcpy (se->sysexDump, midiData, numBytes);
  24729. se->type = kVstSysExType;
  24730. se->byteSize = sizeof (VstMidiSysexEvent);
  24731. se->deltaFrames = frameOffset;
  24732. se->flags = 0;
  24733. se->dumpBytes = numBytes;
  24734. se->resvd1 = 0;
  24735. se->resvd2 = 0;
  24736. }
  24737. }
  24738. // Handy method to pull the events out of an event buffer supplied by the host
  24739. // or plugin.
  24740. static void addEventsToMidiBuffer (const VstEvents* events, MidiBuffer& dest)
  24741. {
  24742. for (int i = 0; i < events->numEvents; ++i)
  24743. {
  24744. const VstEvent* const e = events->events[i];
  24745. if (e != 0)
  24746. {
  24747. if (e->type == kVstMidiType)
  24748. {
  24749. dest.addEvent ((const JUCE_NAMESPACE::uint8*) ((const VstMidiEvent*) e)->midiData,
  24750. 4, e->deltaFrames);
  24751. }
  24752. else if (e->type == kVstSysExType)
  24753. {
  24754. dest.addEvent ((const JUCE_NAMESPACE::uint8*) ((const VstMidiSysexEvent*) e)->sysexDump,
  24755. (int) ((const VstMidiSysexEvent*) e)->dumpBytes,
  24756. e->deltaFrames);
  24757. }
  24758. }
  24759. }
  24760. }
  24761. void ensureSize (int numEventsNeeded)
  24762. {
  24763. if (numEventsNeeded > numEventsAllocated)
  24764. {
  24765. numEventsNeeded = (numEventsNeeded + 32) & ~31;
  24766. const int size = 20 + sizeof (VstEvent*) * numEventsNeeded;
  24767. if (events == 0)
  24768. events = (VstEvents*) juce_calloc (size);
  24769. else
  24770. events = (VstEvents*) juce_realloc (events, size);
  24771. for (int i = numEventsAllocated; i < numEventsNeeded; ++i)
  24772. {
  24773. VstMidiEvent* const e = (VstMidiEvent*) juce_calloc (jmax ((int) sizeof (VstMidiEvent),
  24774. (int) sizeof (VstMidiSysexEvent)));
  24775. e->type = kVstMidiType;
  24776. e->byteSize = sizeof (VstMidiEvent);
  24777. events->events[i] = (VstEvent*) e;
  24778. }
  24779. numEventsAllocated = numEventsNeeded;
  24780. }
  24781. }
  24782. void freeEvents()
  24783. {
  24784. if (events != 0)
  24785. {
  24786. for (int i = numEventsAllocated; --i >= 0;)
  24787. {
  24788. VstMidiEvent* const e = (VstMidiEvent*) (events->events[i]);
  24789. if (e->type == kVstSysExType)
  24790. juce_free (((VstMidiSysexEvent*) e)->sysexDump);
  24791. juce_free (e);
  24792. }
  24793. juce_free (events);
  24794. events = 0;
  24795. numEventsUsed = 0;
  24796. numEventsAllocated = 0;
  24797. }
  24798. }
  24799. VstEvents* events;
  24800. private:
  24801. int numEventsUsed, numEventsAllocated;
  24802. };
  24803. #endif // __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  24804. #endif // __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  24805. /********* End of inlined file: juce_VSTMidiEventList.h *********/
  24806. #if ! JUCE_WIN32
  24807. #define _fpreset()
  24808. #define _clearfp()
  24809. #endif
  24810. extern void juce_callAnyTimersSynchronously();
  24811. const int fxbVersionNum = 1;
  24812. struct fxProgram
  24813. {
  24814. long chunkMagic; // 'CcnK'
  24815. long byteSize; // of this chunk, excl. magic + byteSize
  24816. long fxMagic; // 'FxCk'
  24817. long version;
  24818. long fxID; // fx unique id
  24819. long fxVersion;
  24820. long numParams;
  24821. char prgName[28];
  24822. float params[1]; // variable no. of parameters
  24823. };
  24824. struct fxSet
  24825. {
  24826. long chunkMagic; // 'CcnK'
  24827. long byteSize; // of this chunk, excl. magic + byteSize
  24828. long fxMagic; // 'FxBk'
  24829. long version;
  24830. long fxID; // fx unique id
  24831. long fxVersion;
  24832. long numPrograms;
  24833. char future[128];
  24834. fxProgram programs[1]; // variable no. of programs
  24835. };
  24836. struct fxChunkSet
  24837. {
  24838. long chunkMagic; // 'CcnK'
  24839. long byteSize; // of this chunk, excl. magic + byteSize
  24840. long fxMagic; // 'FxCh', 'FPCh', or 'FBCh'
  24841. long version;
  24842. long fxID; // fx unique id
  24843. long fxVersion;
  24844. long numPrograms;
  24845. char future[128];
  24846. long chunkSize;
  24847. char chunk[8]; // variable
  24848. };
  24849. struct fxProgramSet
  24850. {
  24851. long chunkMagic; // 'CcnK'
  24852. long byteSize; // of this chunk, excl. magic + byteSize
  24853. long fxMagic; // 'FxCh', 'FPCh', or 'FBCh'
  24854. long version;
  24855. long fxID; // fx unique id
  24856. long fxVersion;
  24857. long numPrograms;
  24858. char name[28];
  24859. long chunkSize;
  24860. char chunk[8]; // variable
  24861. };
  24862. #ifdef JUCE_LITTLE_ENDIAN
  24863. static long vst_swap (const long x) throw() { return (long) swapByteOrder ((uint32) x); }
  24864. static float vst_swapFloat (const float x) throw()
  24865. {
  24866. union { uint32 asInt; float asFloat; } n;
  24867. n.asFloat = x;
  24868. n.asInt = swapByteOrder (n.asInt);
  24869. return n.asFloat;
  24870. }
  24871. #else
  24872. #define vst_swap(x) (x)
  24873. #define vst_swapFloat(x) (x)
  24874. #endif
  24875. typedef AEffect* (*MainCall) (audioMasterCallback);
  24876. static VstIntPtr VSTCALLBACK audioMaster (AEffect* effect, VstInt32 opcode, VstInt32 index, VstIntPtr value, void* ptr, float opt);
  24877. static int shellUIDToCreate = 0;
  24878. static int insideVSTCallback = 0;
  24879. class VSTPluginWindow;
  24880. // Change this to disable logging of various VST activities
  24881. #ifndef VST_LOGGING
  24882. #define VST_LOGGING 1
  24883. #endif
  24884. #if VST_LOGGING
  24885. #define log(a) Logger::writeToLog(a);
  24886. #else
  24887. #define log(a)
  24888. #endif
  24889. #if JUCE_MAC && JUCE_PPC
  24890. static void* NewCFMFromMachO (void* const machofp) throw()
  24891. {
  24892. void* result = juce_malloc (8);
  24893. ((void**) result)[0] = machofp;
  24894. ((void**) result)[1] = result;
  24895. return result;
  24896. }
  24897. #endif
  24898. #if JUCE_LINUX
  24899. extern Display* display;
  24900. extern XContext improbableNumber;
  24901. typedef void (*EventProcPtr) (XEvent* ev);
  24902. static bool xErrorTriggered;
  24903. static int temporaryErrorHandler (Display*, XErrorEvent*)
  24904. {
  24905. xErrorTriggered = true;
  24906. return 0;
  24907. }
  24908. static int getPropertyFromXWindow (Window handle, Atom atom)
  24909. {
  24910. XErrorHandler oldErrorHandler = XSetErrorHandler (temporaryErrorHandler);
  24911. xErrorTriggered = false;
  24912. int userSize;
  24913. unsigned long bytes, userCount;
  24914. unsigned char* data;
  24915. Atom userType;
  24916. XGetWindowProperty (display, handle, atom, 0, 1, false, AnyPropertyType,
  24917. &userType, &userSize, &userCount, &bytes, &data);
  24918. XSetErrorHandler (oldErrorHandler);
  24919. return (userCount == 1 && ! xErrorTriggered) ? *(int*) data
  24920. : 0;
  24921. }
  24922. static Window getChildWindow (Window windowToCheck)
  24923. {
  24924. Window rootWindow, parentWindow;
  24925. Window* childWindows;
  24926. unsigned int numChildren;
  24927. XQueryTree (display,
  24928. windowToCheck,
  24929. &rootWindow,
  24930. &parentWindow,
  24931. &childWindows,
  24932. &numChildren);
  24933. if (numChildren > 0)
  24934. return childWindows [0];
  24935. return 0;
  24936. }
  24937. static void translateJuceToXButtonModifiers (const MouseEvent& e, XEvent& ev) throw()
  24938. {
  24939. if (e.mods.isLeftButtonDown())
  24940. {
  24941. ev.xbutton.button = Button1;
  24942. ev.xbutton.state |= Button1Mask;
  24943. }
  24944. else if (e.mods.isRightButtonDown())
  24945. {
  24946. ev.xbutton.button = Button3;
  24947. ev.xbutton.state |= Button3Mask;
  24948. }
  24949. else if (e.mods.isMiddleButtonDown())
  24950. {
  24951. ev.xbutton.button = Button2;
  24952. ev.xbutton.state |= Button2Mask;
  24953. }
  24954. }
  24955. static void translateJuceToXMotionModifiers (const MouseEvent& e, XEvent& ev) throw()
  24956. {
  24957. if (e.mods.isLeftButtonDown())
  24958. ev.xmotion.state |= Button1Mask;
  24959. else if (e.mods.isRightButtonDown())
  24960. ev.xmotion.state |= Button3Mask;
  24961. else if (e.mods.isMiddleButtonDown())
  24962. ev.xmotion.state |= Button2Mask;
  24963. }
  24964. static void translateJuceToXCrossingModifiers (const MouseEvent& e, XEvent& ev) throw()
  24965. {
  24966. if (e.mods.isLeftButtonDown())
  24967. ev.xcrossing.state |= Button1Mask;
  24968. else if (e.mods.isRightButtonDown())
  24969. ev.xcrossing.state |= Button3Mask;
  24970. else if (e.mods.isMiddleButtonDown())
  24971. ev.xcrossing.state |= Button2Mask;
  24972. }
  24973. static void translateJuceToXMouseWheelModifiers (const MouseEvent& e, const float increment, XEvent& ev) throw()
  24974. {
  24975. if (increment < 0)
  24976. {
  24977. ev.xbutton.button = Button5;
  24978. ev.xbutton.state |= Button5Mask;
  24979. }
  24980. else if (increment > 0)
  24981. {
  24982. ev.xbutton.button = Button4;
  24983. ev.xbutton.state |= Button4Mask;
  24984. }
  24985. }
  24986. #endif
  24987. static VoidArray activeModules;
  24988. class ModuleHandle : public ReferenceCountedObject
  24989. {
  24990. public:
  24991. File file;
  24992. MainCall moduleMain;
  24993. String pluginName;
  24994. static ModuleHandle* findOrCreateModule (const File& file)
  24995. {
  24996. for (int i = activeModules.size(); --i >= 0;)
  24997. {
  24998. ModuleHandle* const module = (ModuleHandle*) activeModules.getUnchecked(i);
  24999. if (module->file == file)
  25000. return module;
  25001. }
  25002. _fpreset(); // (doesn't do any harm)
  25003. ++insideVSTCallback;
  25004. shellUIDToCreate = 0;
  25005. log ("Attempting to load VST: " + file.getFullPathName());
  25006. ModuleHandle* m = new ModuleHandle (file);
  25007. if (! m->open())
  25008. deleteAndZero (m);
  25009. --insideVSTCallback;
  25010. _fpreset(); // (doesn't do any harm)
  25011. return m;
  25012. }
  25013. ModuleHandle (const File& file_)
  25014. : file (file_),
  25015. moduleMain (0),
  25016. #if JUCE_WIN32 || JUCE_LINUX
  25017. hModule (0)
  25018. #elif JUCE_MAC
  25019. fragId (0),
  25020. resHandle (0),
  25021. bundleRef (0),
  25022. resFileId (0)
  25023. #endif
  25024. {
  25025. activeModules.add (this);
  25026. #if JUCE_WIN32 || JUCE_LINUX
  25027. fullParentDirectoryPathName = file_.getParentDirectory().getFullPathName();
  25028. #elif JUCE_MAC
  25029. FSRef ref;
  25030. PlatformUtilities::makeFSRefFromPath (&ref, file_.getParentDirectory().getFullPathName());
  25031. FSGetCatalogInfo (&ref, kFSCatInfoNone, 0, 0, &parentDirFSSpec, 0);
  25032. #endif
  25033. }
  25034. ~ModuleHandle()
  25035. {
  25036. activeModules.removeValue (this);
  25037. close();
  25038. }
  25039. juce_UseDebuggingNewOperator
  25040. #if JUCE_WIN32 || JUCE_LINUX
  25041. void* hModule;
  25042. String fullParentDirectoryPathName;
  25043. bool open()
  25044. {
  25045. #if JUCE_WIN32
  25046. static bool timePeriodSet = false;
  25047. if (! timePeriodSet)
  25048. {
  25049. timePeriodSet = true;
  25050. timeBeginPeriod (2);
  25051. }
  25052. #endif
  25053. pluginName = file.getFileNameWithoutExtension();
  25054. hModule = PlatformUtilities::loadDynamicLibrary (file.getFullPathName());
  25055. moduleMain = (MainCall) PlatformUtilities::getProcedureEntryPoint (hModule, "VSTPluginMain");
  25056. if (moduleMain == 0)
  25057. moduleMain = (MainCall) PlatformUtilities::getProcedureEntryPoint (hModule, "main");
  25058. return moduleMain != 0;
  25059. }
  25060. void close()
  25061. {
  25062. _fpreset(); // (doesn't do any harm)
  25063. PlatformUtilities::freeDynamicLibrary (hModule);
  25064. }
  25065. void closeEffect (AEffect* eff)
  25066. {
  25067. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  25068. }
  25069. #else
  25070. CFragConnectionID fragId;
  25071. Handle resHandle;
  25072. CFBundleRef bundleRef;
  25073. FSSpec parentDirFSSpec;
  25074. short resFileId;
  25075. bool open()
  25076. {
  25077. bool ok = false;
  25078. const String filename (file.getFullPathName());
  25079. if (file.hasFileExtension (T(".vst")))
  25080. {
  25081. const char* const utf8 = filename.toUTF8();
  25082. CFURLRef url = CFURLCreateFromFileSystemRepresentation (0, (const UInt8*) utf8,
  25083. strlen (utf8), file.isDirectory());
  25084. if (url != 0)
  25085. {
  25086. bundleRef = CFBundleCreate (kCFAllocatorDefault, url);
  25087. CFRelease (url);
  25088. if (bundleRef != 0)
  25089. {
  25090. if (CFBundleLoadExecutable (bundleRef))
  25091. {
  25092. moduleMain = (MainCall) CFBundleGetFunctionPointerForName (bundleRef, CFSTR("main_macho"));
  25093. if (moduleMain == 0)
  25094. moduleMain = (MainCall) CFBundleGetFunctionPointerForName (bundleRef, CFSTR("VSTPluginMain"));
  25095. if (moduleMain != 0)
  25096. {
  25097. CFTypeRef name = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleName"));
  25098. if (name != 0)
  25099. {
  25100. if (CFGetTypeID (name) == CFStringGetTypeID())
  25101. {
  25102. char buffer[1024];
  25103. if (CFStringGetCString ((CFStringRef) name, buffer, sizeof (buffer), CFStringGetSystemEncoding()))
  25104. pluginName = buffer;
  25105. }
  25106. }
  25107. if (pluginName.isEmpty())
  25108. pluginName = file.getFileNameWithoutExtension();
  25109. resFileId = CFBundleOpenBundleResourceMap (bundleRef);
  25110. ok = true;
  25111. }
  25112. }
  25113. if (! ok)
  25114. {
  25115. CFBundleUnloadExecutable (bundleRef);
  25116. CFRelease (bundleRef);
  25117. bundleRef = 0;
  25118. }
  25119. }
  25120. }
  25121. }
  25122. #if JUCE_PPC
  25123. else
  25124. {
  25125. FSRef fn;
  25126. if (FSPathMakeRef ((UInt8*) (const char*) filename, &fn, 0) == noErr)
  25127. {
  25128. resFileId = FSOpenResFile (&fn, fsRdPerm);
  25129. if (resFileId != -1)
  25130. {
  25131. const int numEffs = Count1Resources ('aEff');
  25132. for (int i = 0; i < numEffs; ++i)
  25133. {
  25134. resHandle = Get1IndResource ('aEff', i + 1);
  25135. if (resHandle != 0)
  25136. {
  25137. OSType type;
  25138. Str255 name;
  25139. SInt16 id;
  25140. GetResInfo (resHandle, &id, &type, name);
  25141. pluginName = String ((const char*) name + 1, name[0]);
  25142. DetachResource (resHandle);
  25143. HLock (resHandle);
  25144. Ptr ptr;
  25145. Str255 errorText;
  25146. OSErr err = GetMemFragment (*resHandle, GetHandleSize (resHandle),
  25147. name, kPrivateCFragCopy,
  25148. &fragId, &ptr, errorText);
  25149. if (err == noErr)
  25150. {
  25151. moduleMain = (MainCall) newMachOFromCFM (ptr);
  25152. ok = true;
  25153. }
  25154. else
  25155. {
  25156. HUnlock (resHandle);
  25157. }
  25158. break;
  25159. }
  25160. }
  25161. if (! ok)
  25162. CloseResFile (resFileId);
  25163. }
  25164. }
  25165. }
  25166. #endif
  25167. return ok;
  25168. }
  25169. void close()
  25170. {
  25171. #if JUCE_PPC
  25172. if (fragId != 0)
  25173. {
  25174. if (moduleMain != 0)
  25175. disposeMachOFromCFM ((void*) moduleMain);
  25176. CloseConnection (&fragId);
  25177. HUnlock (resHandle);
  25178. if (resFileId != 0)
  25179. CloseResFile (resFileId);
  25180. }
  25181. else
  25182. #endif
  25183. if (bundleRef != 0)
  25184. {
  25185. CFBundleCloseBundleResourceMap (bundleRef, resFileId);
  25186. if (CFGetRetainCount (bundleRef) == 1)
  25187. CFBundleUnloadExecutable (bundleRef);
  25188. if (CFGetRetainCount (bundleRef) > 0)
  25189. CFRelease (bundleRef);
  25190. }
  25191. }
  25192. void closeEffect (AEffect* eff)
  25193. {
  25194. #if JUCE_PPC
  25195. if (fragId != 0)
  25196. {
  25197. VoidArray thingsToDelete;
  25198. thingsToDelete.add ((void*) eff->dispatcher);
  25199. thingsToDelete.add ((void*) eff->process);
  25200. thingsToDelete.add ((void*) eff->setParameter);
  25201. thingsToDelete.add ((void*) eff->getParameter);
  25202. thingsToDelete.add ((void*) eff->processReplacing);
  25203. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  25204. for (int i = thingsToDelete.size(); --i >= 0;)
  25205. disposeMachOFromCFM (thingsToDelete[i]);
  25206. }
  25207. else
  25208. #endif
  25209. {
  25210. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  25211. }
  25212. }
  25213. #if JUCE_PPC
  25214. static void* newMachOFromCFM (void* cfmfp)
  25215. {
  25216. if (cfmfp == 0)
  25217. return 0;
  25218. UInt32* const mfp = (UInt32*) juce_malloc (sizeof (UInt32) * 6);
  25219. mfp[0] = 0x3d800000 | ((UInt32) cfmfp >> 16);
  25220. mfp[1] = 0x618c0000 | ((UInt32) cfmfp & 0xffff);
  25221. mfp[2] = 0x800c0000;
  25222. mfp[3] = 0x804c0004;
  25223. mfp[4] = 0x7c0903a6;
  25224. mfp[5] = 0x4e800420;
  25225. MakeDataExecutable (mfp, sizeof (UInt32) * 6);
  25226. return mfp;
  25227. }
  25228. static void disposeMachOFromCFM (void* ptr)
  25229. {
  25230. juce_free (ptr);
  25231. }
  25232. void coerceAEffectFunctionCalls (AEffect* eff)
  25233. {
  25234. if (fragId != 0)
  25235. {
  25236. eff->dispatcher = (AEffectDispatcherProc) newMachOFromCFM ((void*) eff->dispatcher);
  25237. eff->process = (AEffectProcessProc) newMachOFromCFM ((void*) eff->process);
  25238. eff->setParameter = (AEffectSetParameterProc) newMachOFromCFM ((void*) eff->setParameter);
  25239. eff->getParameter = (AEffectGetParameterProc) newMachOFromCFM ((void*) eff->getParameter);
  25240. eff->processReplacing = (AEffectProcessProc) newMachOFromCFM ((void*) eff->processReplacing);
  25241. }
  25242. }
  25243. #endif
  25244. #endif
  25245. };
  25246. /**
  25247. An instance of a plugin, created by a VSTPluginFormat.
  25248. */
  25249. class VSTPluginInstance : public AudioPluginInstance,
  25250. private Timer,
  25251. private AsyncUpdater
  25252. {
  25253. public:
  25254. ~VSTPluginInstance();
  25255. // AudioPluginInstance methods:
  25256. void fillInPluginDescription (PluginDescription& desc) const
  25257. {
  25258. desc.name = name;
  25259. desc.fileOrIdentifier = module->file.getFullPathName();
  25260. desc.uid = getUID();
  25261. desc.lastFileModTime = module->file.getLastModificationTime();
  25262. desc.pluginFormatName = "VST";
  25263. desc.category = getCategory();
  25264. {
  25265. char buffer [kVstMaxVendorStrLen + 8];
  25266. zerostruct (buffer);
  25267. dispatch (effGetVendorString, 0, 0, buffer, 0);
  25268. desc.manufacturerName = buffer;
  25269. }
  25270. desc.version = getVersion();
  25271. desc.numInputChannels = getNumInputChannels();
  25272. desc.numOutputChannels = getNumOutputChannels();
  25273. desc.isInstrument = (effect != 0 && (effect->flags & effFlagsIsSynth) != 0);
  25274. }
  25275. const String getName() const { return name; }
  25276. int getUID() const throw();
  25277. bool acceptsMidi() const { return wantsMidiMessages; }
  25278. bool producesMidi() const { return dispatch (effCanDo, 0, 0, (void*) "sendVstMidiEvent", 0) > 0; }
  25279. // AudioProcessor methods:
  25280. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  25281. void releaseResources();
  25282. void processBlock (AudioSampleBuffer& buffer,
  25283. MidiBuffer& midiMessages);
  25284. AudioProcessorEditor* createEditor();
  25285. const String getInputChannelName (const int index) const;
  25286. bool isInputChannelStereoPair (int index) const;
  25287. const String getOutputChannelName (const int index) const;
  25288. bool isOutputChannelStereoPair (int index) const;
  25289. int getNumParameters() { return effect != 0 ? effect->numParams : 0; }
  25290. float getParameter (int index);
  25291. void setParameter (int index, float newValue);
  25292. const String getParameterName (int index);
  25293. const String getParameterText (int index);
  25294. bool isParameterAutomatable (int index) const;
  25295. int getNumPrograms() { return effect != 0 ? effect->numPrograms : 0; }
  25296. int getCurrentProgram() { return dispatch (effGetProgram, 0, 0, 0, 0); }
  25297. void setCurrentProgram (int index);
  25298. const String getProgramName (int index);
  25299. void changeProgramName (int index, const String& newName);
  25300. void getStateInformation (MemoryBlock& destData);
  25301. void getCurrentProgramStateInformation (MemoryBlock& destData);
  25302. void setStateInformation (const void* data, int sizeInBytes);
  25303. void setCurrentProgramStateInformation (const void* data, int sizeInBytes);
  25304. void timerCallback();
  25305. void handleAsyncUpdate();
  25306. VstIntPtr handleCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt);
  25307. juce_UseDebuggingNewOperator
  25308. private:
  25309. friend class VSTPluginWindow;
  25310. friend class VSTPluginFormat;
  25311. AEffect* effect;
  25312. String name;
  25313. CriticalSection lock;
  25314. bool wantsMidiMessages, initialised, isPowerOn;
  25315. mutable StringArray programNames;
  25316. AudioSampleBuffer tempBuffer;
  25317. CriticalSection midiInLock;
  25318. MidiBuffer incomingMidi;
  25319. VSTMidiEventList midiEventsToSend;
  25320. VstTimeInfo vstHostTime;
  25321. float** channels;
  25322. ReferenceCountedObjectPtr <ModuleHandle> module;
  25323. int dispatch (const int opcode, const int index, const int value, void* const ptr, float opt) const;
  25324. bool restoreProgramSettings (const fxProgram* const prog);
  25325. const String getCurrentProgramName();
  25326. void setParamsInProgramBlock (fxProgram* const prog) throw();
  25327. void updateStoredProgramNames();
  25328. void initialise();
  25329. void handleMidiFromPlugin (const VstEvents* const events);
  25330. void createTempParameterStore (MemoryBlock& dest);
  25331. void restoreFromTempParameterStore (const MemoryBlock& mb);
  25332. const String getParameterLabel (int index) const;
  25333. bool usesChunks() const throw() { return effect != 0 && (effect->flags & effFlagsProgramChunks) != 0; }
  25334. void getChunkData (MemoryBlock& mb, bool isPreset, int maxSizeMB) const;
  25335. void setChunkData (const char* data, int size, bool isPreset);
  25336. bool loadFromFXBFile (const void* data, int numBytes);
  25337. bool saveToFXBFile (MemoryBlock& dest, bool isFXB, int maxSizeMB);
  25338. int getVersionNumber() const throw() { return effect != 0 ? effect->version : 0; }
  25339. const String getVersion() const throw();
  25340. const String getCategory() const throw();
  25341. bool hasEditor() const throw() { return effect != 0 && (effect->flags & effFlagsHasEditor) != 0; }
  25342. void setPower (const bool on);
  25343. VSTPluginInstance (const ReferenceCountedObjectPtr <ModuleHandle>& module);
  25344. };
  25345. VSTPluginInstance::VSTPluginInstance (const ReferenceCountedObjectPtr <ModuleHandle>& module_)
  25346. : effect (0),
  25347. wantsMidiMessages (false),
  25348. initialised (false),
  25349. isPowerOn (false),
  25350. tempBuffer (1, 1),
  25351. channels (0),
  25352. module (module_)
  25353. {
  25354. try
  25355. {
  25356. _fpreset();
  25357. ++insideVSTCallback;
  25358. name = module->pluginName;
  25359. log (T("Creating VST instance: ") + name);
  25360. #if JUCE_MAC
  25361. if (module->resFileId != 0)
  25362. UseResFile (module->resFileId);
  25363. #if JUCE_PPC
  25364. if (module->fragId != 0)
  25365. {
  25366. static void* audioMasterCoerced = 0;
  25367. if (audioMasterCoerced == 0)
  25368. audioMasterCoerced = NewCFMFromMachO ((void*) &audioMaster);
  25369. effect = module->moduleMain ((audioMasterCallback) audioMasterCoerced);
  25370. }
  25371. else
  25372. #endif
  25373. #endif
  25374. {
  25375. effect = module->moduleMain (&audioMaster);
  25376. }
  25377. --insideVSTCallback;
  25378. if (effect != 0 && effect->magic == kEffectMagic)
  25379. {
  25380. #if JUCE_PPC
  25381. module->coerceAEffectFunctionCalls (effect);
  25382. #endif
  25383. jassert (effect->resvd2 == 0);
  25384. jassert (effect->object != 0);
  25385. _fpreset(); // some dodgy plugs fuck around with this
  25386. }
  25387. else
  25388. {
  25389. effect = 0;
  25390. }
  25391. }
  25392. catch (...)
  25393. {
  25394. --insideVSTCallback;
  25395. }
  25396. }
  25397. VSTPluginInstance::~VSTPluginInstance()
  25398. {
  25399. {
  25400. const ScopedLock sl (lock);
  25401. jassert (insideVSTCallback == 0);
  25402. if (effect != 0 && effect->magic == kEffectMagic)
  25403. {
  25404. try
  25405. {
  25406. #if JUCE_MAC
  25407. if (module->resFileId != 0)
  25408. UseResFile (module->resFileId);
  25409. #endif
  25410. // Must delete any editors before deleting the plugin instance!
  25411. jassert (getActiveEditor() == 0);
  25412. _fpreset(); // some dodgy plugs fuck around with this
  25413. module->closeEffect (effect);
  25414. }
  25415. catch (...)
  25416. {}
  25417. }
  25418. module = 0;
  25419. effect = 0;
  25420. }
  25421. juce_free (channels);
  25422. channels = 0;
  25423. }
  25424. void VSTPluginInstance::initialise()
  25425. {
  25426. if (initialised || effect == 0)
  25427. return;
  25428. log (T("Initialising VST: ") + module->pluginName);
  25429. initialised = true;
  25430. dispatch (effIdentify, 0, 0, 0, 0);
  25431. // this code would ask the plugin for its name, but so few plugins
  25432. // actually bother implementing this correctly, that it's better to
  25433. // just ignore it and use the file name instead.
  25434. /* {
  25435. char buffer [256];
  25436. zerostruct (buffer);
  25437. dispatch (effGetEffectName, 0, 0, buffer, 0);
  25438. name = String (buffer).trim();
  25439. if (name.isEmpty())
  25440. name = module->pluginName;
  25441. }
  25442. */
  25443. if (getSampleRate() > 0)
  25444. dispatch (effSetSampleRate, 0, 0, 0, (float) getSampleRate());
  25445. if (getBlockSize() > 0)
  25446. dispatch (effSetBlockSize, 0, jmax (32, getBlockSize()), 0, 0);
  25447. dispatch (effOpen, 0, 0, 0, 0);
  25448. setPlayConfigDetails (effect->numInputs, effect->numOutputs,
  25449. getSampleRate(), getBlockSize());
  25450. if (getNumPrograms() > 1)
  25451. setCurrentProgram (0);
  25452. else
  25453. dispatch (effSetProgram, 0, 0, 0, 0);
  25454. int i;
  25455. for (i = effect->numInputs; --i >= 0;)
  25456. dispatch (effConnectInput, i, 1, 0, 0);
  25457. for (i = effect->numOutputs; --i >= 0;)
  25458. dispatch (effConnectOutput, i, 1, 0, 0);
  25459. updateStoredProgramNames();
  25460. wantsMidiMessages = dispatch (effCanDo, 0, 0, (void*) "receiveVstMidiEvent", 0) > 0;
  25461. setLatencySamples (effect->initialDelay);
  25462. }
  25463. void VSTPluginInstance::prepareToPlay (double sampleRate_,
  25464. int samplesPerBlockExpected)
  25465. {
  25466. setPlayConfigDetails (effect->numInputs, effect->numOutputs,
  25467. sampleRate_, samplesPerBlockExpected);
  25468. setLatencySamples (effect->initialDelay);
  25469. juce_free (channels);
  25470. channels = (float**) juce_calloc (sizeof (float*) * jmax (16, getNumOutputChannels() + 2, getNumInputChannels() + 2));
  25471. vstHostTime.tempo = 120.0;
  25472. vstHostTime.timeSigNumerator = 4;
  25473. vstHostTime.timeSigDenominator = 4;
  25474. vstHostTime.sampleRate = sampleRate_;
  25475. vstHostTime.samplePos = 0;
  25476. vstHostTime.flags = kVstNanosValid; /*| kVstTransportPlaying | kVstTempoValid | kVstTimeSigValid*/;
  25477. initialise();
  25478. if (initialised)
  25479. {
  25480. wantsMidiMessages = wantsMidiMessages
  25481. || (dispatch (effCanDo, 0, 0, (void*) "receiveVstMidiEvent", 0) > 0);
  25482. if (wantsMidiMessages)
  25483. midiEventsToSend.ensureSize (256);
  25484. else
  25485. midiEventsToSend.freeEvents();
  25486. incomingMidi.clear();
  25487. dispatch (effSetSampleRate, 0, 0, 0, (float) sampleRate_);
  25488. dispatch (effSetBlockSize, 0, jmax (16, samplesPerBlockExpected), 0, 0);
  25489. tempBuffer.setSize (jmax (1, effect->numOutputs), samplesPerBlockExpected);
  25490. if (! isPowerOn)
  25491. setPower (true);
  25492. // dodgy hack to force some plugins to initialise the sample rate..
  25493. if ((! hasEditor()) && getNumParameters() > 0)
  25494. {
  25495. const float old = getParameter (0);
  25496. setParameter (0, (old < 0.5f) ? 1.0f : 0.0f);
  25497. setParameter (0, old);
  25498. }
  25499. dispatch (effStartProcess, 0, 0, 0, 0);
  25500. }
  25501. }
  25502. void VSTPluginInstance::releaseResources()
  25503. {
  25504. if (initialised)
  25505. {
  25506. dispatch (effStopProcess, 0, 0, 0, 0);
  25507. setPower (false);
  25508. }
  25509. tempBuffer.setSize (1, 1);
  25510. incomingMidi.clear();
  25511. midiEventsToSend.freeEvents();
  25512. juce_free (channels);
  25513. channels = 0;
  25514. }
  25515. void VSTPluginInstance::processBlock (AudioSampleBuffer& buffer,
  25516. MidiBuffer& midiMessages)
  25517. {
  25518. const int numSamples = buffer.getNumSamples();
  25519. if (initialised)
  25520. {
  25521. AudioPlayHead* playHead = getPlayHead();
  25522. if (playHead != 0)
  25523. {
  25524. AudioPlayHead::CurrentPositionInfo position;
  25525. playHead->getCurrentPosition (position);
  25526. vstHostTime.tempo = position.bpm;
  25527. vstHostTime.timeSigNumerator = position.timeSigNumerator;
  25528. vstHostTime.timeSigDenominator = position.timeSigDenominator;
  25529. vstHostTime.ppqPos = position.ppqPosition;
  25530. vstHostTime.barStartPos = position.ppqPositionOfLastBarStart;
  25531. vstHostTime.flags |= kVstTempoValid | kVstTimeSigValid | kVstPpqPosValid | kVstBarsValid;
  25532. if (position.isPlaying)
  25533. vstHostTime.flags |= kVstTransportPlaying;
  25534. else
  25535. vstHostTime.flags &= ~kVstTransportPlaying;
  25536. }
  25537. #if JUCE_WIN32
  25538. vstHostTime.nanoSeconds = timeGetTime() * 1000000.0;
  25539. #elif JUCE_LINUX
  25540. timeval micro;
  25541. gettimeofday (&micro, 0);
  25542. vstHostTime.nanoSeconds = micro.tv_usec * 1000.0;
  25543. #elif JUCE_MAC
  25544. UnsignedWide micro;
  25545. Microseconds (&micro);
  25546. vstHostTime.nanoSeconds = micro.lo * 1000.0;
  25547. #endif
  25548. if (wantsMidiMessages)
  25549. {
  25550. midiEventsToSend.clear();
  25551. midiEventsToSend.ensureSize (1);
  25552. MidiBuffer::Iterator iter (midiMessages);
  25553. const uint8* midiData;
  25554. int numBytesOfMidiData, samplePosition;
  25555. while (iter.getNextEvent (midiData, numBytesOfMidiData, samplePosition))
  25556. {
  25557. midiEventsToSend.addEvent (midiData, numBytesOfMidiData,
  25558. jlimit (0, numSamples - 1, samplePosition));
  25559. }
  25560. try
  25561. {
  25562. effect->dispatcher (effect, effProcessEvents, 0, 0, midiEventsToSend.events, 0);
  25563. }
  25564. catch (...)
  25565. {}
  25566. }
  25567. int i;
  25568. const int maxChans = jmax (effect->numInputs, effect->numOutputs);
  25569. for (i = 0; i < maxChans; ++i)
  25570. channels[i] = buffer.getSampleData (i);
  25571. channels [maxChans] = 0;
  25572. _clearfp();
  25573. if ((effect->flags & effFlagsCanReplacing) != 0)
  25574. {
  25575. try
  25576. {
  25577. effect->processReplacing (effect, channels, channels, numSamples);
  25578. }
  25579. catch (...)
  25580. {}
  25581. }
  25582. else
  25583. {
  25584. tempBuffer.setSize (effect->numOutputs, numSamples);
  25585. tempBuffer.clear();
  25586. float* outs [64];
  25587. for (i = effect->numOutputs; --i >= 0;)
  25588. outs[i] = tempBuffer.getSampleData (i);
  25589. outs [effect->numOutputs] = 0;
  25590. try
  25591. {
  25592. effect->process (effect, channels, outs, numSamples);
  25593. }
  25594. catch (...)
  25595. {}
  25596. for (i = effect->numOutputs; --i >= 0;)
  25597. buffer.copyFrom (i, 0, outs[i], numSamples);
  25598. }
  25599. }
  25600. else
  25601. {
  25602. // Not initialised, so just bypass..
  25603. for (int i = getNumInputChannels(); i < getNumOutputChannels(); ++i)
  25604. buffer.clear (i, 0, buffer.getNumSamples());
  25605. }
  25606. {
  25607. // copy any incoming midi..
  25608. const ScopedLock sl (midiInLock);
  25609. midiMessages = incomingMidi;
  25610. incomingMidi.clear();
  25611. }
  25612. }
  25613. void VSTPluginInstance::handleMidiFromPlugin (const VstEvents* const events)
  25614. {
  25615. if (events != 0)
  25616. {
  25617. const ScopedLock sl (midiInLock);
  25618. VSTMidiEventList::addEventsToMidiBuffer (events, incomingMidi);
  25619. }
  25620. }
  25621. static Array <VSTPluginWindow*> activeVSTWindows;
  25622. class VSTPluginWindow : public AudioProcessorEditor,
  25623. #if ! JUCE_MAC
  25624. public ComponentMovementWatcher,
  25625. #endif
  25626. public Timer
  25627. {
  25628. public:
  25629. VSTPluginWindow (VSTPluginInstance& plugin_)
  25630. : AudioProcessorEditor (&plugin_),
  25631. #if ! JUCE_MAC
  25632. ComponentMovementWatcher (this),
  25633. #endif
  25634. plugin (plugin_),
  25635. isOpen (false),
  25636. wasShowing (false),
  25637. pluginRefusesToResize (false),
  25638. pluginWantsKeys (false),
  25639. alreadyInside (false),
  25640. recursiveResize (false)
  25641. {
  25642. #if JUCE_WIN32
  25643. sizeCheckCount = 0;
  25644. pluginHWND = 0;
  25645. #elif JUCE_LINUX
  25646. pluginWindow = None;
  25647. pluginProc = None;
  25648. #else
  25649. addAndMakeVisible (innerWrapper = new InnerWrapperComponent (this));
  25650. #endif
  25651. activeVSTWindows.add (this);
  25652. setSize (1, 1);
  25653. setOpaque (true);
  25654. setVisible (true);
  25655. }
  25656. ~VSTPluginWindow()
  25657. {
  25658. #if JUCE_MAC
  25659. deleteAndZero (innerWrapper);
  25660. #else
  25661. closePluginWindow();
  25662. #endif
  25663. activeVSTWindows.removeValue (this);
  25664. plugin.editorBeingDeleted (this);
  25665. }
  25666. #if ! JUCE_MAC
  25667. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  25668. {
  25669. if (recursiveResize)
  25670. return;
  25671. Component* const topComp = getTopLevelComponent();
  25672. if (topComp->getPeer() != 0)
  25673. {
  25674. int x = 0, y = 0;
  25675. relativePositionToOtherComponent (topComp, x, y);
  25676. recursiveResize = true;
  25677. #if JUCE_WIN32
  25678. if (pluginHWND != 0)
  25679. MoveWindow (pluginHWND, x, y, getWidth(), getHeight(), TRUE);
  25680. #elif JUCE_LINUX
  25681. if (pluginWindow != 0)
  25682. {
  25683. XResizeWindow (display, pluginWindow, getWidth(), getHeight());
  25684. XMoveWindow (display, pluginWindow, x, y);
  25685. XMapRaised (display, pluginWindow);
  25686. }
  25687. #endif
  25688. recursiveResize = false;
  25689. }
  25690. }
  25691. void componentVisibilityChanged (Component&)
  25692. {
  25693. const bool isShowingNow = isShowing();
  25694. if (wasShowing != isShowingNow)
  25695. {
  25696. wasShowing = isShowingNow;
  25697. if (isShowingNow)
  25698. openPluginWindow();
  25699. else
  25700. closePluginWindow();
  25701. }
  25702. componentMovedOrResized (true, true);
  25703. }
  25704. void componentPeerChanged()
  25705. {
  25706. closePluginWindow();
  25707. openPluginWindow();
  25708. }
  25709. #endif
  25710. bool keyStateChanged (const bool)
  25711. {
  25712. return pluginWantsKeys;
  25713. }
  25714. bool keyPressed (const KeyPress&)
  25715. {
  25716. return pluginWantsKeys;
  25717. }
  25718. #if JUCE_MAC
  25719. void paint (Graphics& g)
  25720. {
  25721. g.fillAll (Colours::black);
  25722. }
  25723. #else
  25724. void paint (Graphics& g)
  25725. {
  25726. if (isOpen)
  25727. {
  25728. ComponentPeer* const peer = getPeer();
  25729. if (peer != 0)
  25730. {
  25731. peer->addMaskedRegion (getScreenX() - peer->getScreenX(),
  25732. getScreenY() - peer->getScreenY(),
  25733. getWidth(), getHeight());
  25734. #if JUCE_LINUX
  25735. if (pluginWindow != 0)
  25736. {
  25737. const Rectangle clip (g.getClipBounds());
  25738. XEvent ev;
  25739. zerostruct (ev);
  25740. ev.xexpose.type = Expose;
  25741. ev.xexpose.display = display;
  25742. ev.xexpose.window = pluginWindow;
  25743. ev.xexpose.x = clip.getX();
  25744. ev.xexpose.y = clip.getY();
  25745. ev.xexpose.width = clip.getWidth();
  25746. ev.xexpose.height = clip.getHeight();
  25747. sendEventToChild (&ev);
  25748. }
  25749. #endif
  25750. }
  25751. }
  25752. else
  25753. {
  25754. g.fillAll (Colours::black);
  25755. }
  25756. }
  25757. #endif
  25758. void timerCallback()
  25759. {
  25760. #if JUCE_WIN32
  25761. if (--sizeCheckCount <= 0)
  25762. {
  25763. sizeCheckCount = 10;
  25764. checkPluginWindowSize();
  25765. }
  25766. #endif
  25767. try
  25768. {
  25769. static bool reentrant = false;
  25770. if (! reentrant)
  25771. {
  25772. reentrant = true;
  25773. plugin.dispatch (effEditIdle, 0, 0, 0, 0);
  25774. reentrant = false;
  25775. }
  25776. }
  25777. catch (...)
  25778. {}
  25779. }
  25780. void mouseDown (const MouseEvent& e)
  25781. {
  25782. #if JUCE_LINUX
  25783. if (pluginWindow == 0)
  25784. return;
  25785. toFront (true);
  25786. XEvent ev;
  25787. zerostruct (ev);
  25788. ev.xbutton.display = display;
  25789. ev.xbutton.type = ButtonPress;
  25790. ev.xbutton.window = pluginWindow;
  25791. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  25792. ev.xbutton.time = CurrentTime;
  25793. ev.xbutton.x = e.x;
  25794. ev.xbutton.y = e.y;
  25795. ev.xbutton.x_root = e.getScreenX();
  25796. ev.xbutton.y_root = e.getScreenY();
  25797. translateJuceToXButtonModifiers (e, ev);
  25798. sendEventToChild (&ev);
  25799. #elif JUCE_WIN32
  25800. (void) e;
  25801. toFront (true);
  25802. #endif
  25803. }
  25804. void broughtToFront()
  25805. {
  25806. activeVSTWindows.removeValue (this);
  25807. activeVSTWindows.add (this);
  25808. #if JUCE_MAC
  25809. dispatch (effEditTop, 0, 0, 0, 0);
  25810. #endif
  25811. }
  25812. juce_UseDebuggingNewOperator
  25813. private:
  25814. VSTPluginInstance& plugin;
  25815. bool isOpen, wasShowing, recursiveResize;
  25816. bool pluginWantsKeys, pluginRefusesToResize, alreadyInside;
  25817. #if JUCE_WIN32
  25818. HWND pluginHWND;
  25819. void* originalWndProc;
  25820. int sizeCheckCount;
  25821. #elif JUCE_LINUX
  25822. Window pluginWindow;
  25823. EventProcPtr pluginProc;
  25824. #endif
  25825. #if JUCE_MAC
  25826. void openPluginWindow (WindowRef parentWindow)
  25827. {
  25828. if (isOpen || parentWindow == 0)
  25829. return;
  25830. isOpen = true;
  25831. ERect* rect = 0;
  25832. dispatch (effEditGetRect, 0, 0, &rect, 0);
  25833. dispatch (effEditOpen, 0, 0, parentWindow, 0);
  25834. // do this before and after like in the steinberg example
  25835. dispatch (effEditGetRect, 0, 0, &rect, 0);
  25836. dispatch (effGetProgram, 0, 0, 0, 0); // also in steinberg code
  25837. // Install keyboard hooks
  25838. pluginWantsKeys = (dispatch (effKeysRequired, 0, 0, 0, 0) == 0);
  25839. // double-check it's not too tiny
  25840. int w = 250, h = 150;
  25841. if (rect != 0)
  25842. {
  25843. w = rect->right - rect->left;
  25844. h = rect->bottom - rect->top;
  25845. if (w == 0 || h == 0)
  25846. {
  25847. w = 250;
  25848. h = 150;
  25849. }
  25850. }
  25851. w = jmax (w, 32);
  25852. h = jmax (h, 32);
  25853. setSize (w, h);
  25854. startTimer (18 + JUCE_NAMESPACE::Random::getSystemRandom().nextInt (5));
  25855. repaint();
  25856. }
  25857. #else
  25858. void openPluginWindow()
  25859. {
  25860. if (isOpen || getWindowHandle() == 0)
  25861. return;
  25862. log (T("Opening VST UI: ") + plugin.name);
  25863. isOpen = true;
  25864. ERect* rect = 0;
  25865. dispatch (effEditGetRect, 0, 0, &rect, 0);
  25866. dispatch (effEditOpen, 0, 0, getWindowHandle(), 0);
  25867. // do this before and after like in the steinberg example
  25868. dispatch (effEditGetRect, 0, 0, &rect, 0);
  25869. dispatch (effGetProgram, 0, 0, 0, 0); // also in steinberg code
  25870. // Install keyboard hooks
  25871. pluginWantsKeys = (dispatch (effKeysRequired, 0, 0, 0, 0) == 0);
  25872. #if JUCE_WIN32
  25873. originalWndProc = 0;
  25874. pluginHWND = GetWindow ((HWND) getWindowHandle(), GW_CHILD);
  25875. if (pluginHWND == 0)
  25876. {
  25877. isOpen = false;
  25878. setSize (300, 150);
  25879. return;
  25880. }
  25881. #pragma warning (push)
  25882. #pragma warning (disable: 4244)
  25883. originalWndProc = (void*) GetWindowLongPtr (pluginHWND, GWL_WNDPROC);
  25884. if (! pluginWantsKeys)
  25885. SetWindowLongPtr (pluginHWND, GWL_WNDPROC, (LONG_PTR) vstHookWndProc);
  25886. #pragma warning (pop)
  25887. int w, h;
  25888. RECT r;
  25889. GetWindowRect (pluginHWND, &r);
  25890. w = r.right - r.left;
  25891. h = r.bottom - r.top;
  25892. if (rect != 0)
  25893. {
  25894. const int rw = rect->right - rect->left;
  25895. const int rh = rect->bottom - rect->top;
  25896. if ((rw > 50 && rh > 50 && rw < 2000 && rh < 2000 && rw != w && rh != h)
  25897. || ((w == 0 && rw > 0) || (h == 0 && rh > 0)))
  25898. {
  25899. // very dodgy logic to decide which size is right.
  25900. if (abs (rw - w) > 350 || abs (rh - h) > 350)
  25901. {
  25902. SetWindowPos (pluginHWND, 0,
  25903. 0, 0, rw, rh,
  25904. SWP_NOMOVE | SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER);
  25905. GetWindowRect (pluginHWND, &r);
  25906. w = r.right - r.left;
  25907. h = r.bottom - r.top;
  25908. pluginRefusesToResize = (w != rw) || (h != rh);
  25909. w = rw;
  25910. h = rh;
  25911. }
  25912. }
  25913. }
  25914. #elif JUCE_LINUX
  25915. pluginWindow = getChildWindow ((Window) getWindowHandle());
  25916. if (pluginWindow != 0)
  25917. pluginProc = (EventProcPtr) getPropertyFromXWindow (pluginWindow,
  25918. XInternAtom (display, "_XEventProc", False));
  25919. int w = 250, h = 150;
  25920. if (rect != 0)
  25921. {
  25922. w = rect->right - rect->left;
  25923. h = rect->bottom - rect->top;
  25924. if (w == 0 || h == 0)
  25925. {
  25926. w = 250;
  25927. h = 150;
  25928. }
  25929. }
  25930. if (pluginWindow != 0)
  25931. XMapRaised (display, pluginWindow);
  25932. #endif
  25933. // double-check it's not too tiny
  25934. w = jmax (w, 32);
  25935. h = jmax (h, 32);
  25936. setSize (w, h);
  25937. #if JUCE_WIN32
  25938. checkPluginWindowSize();
  25939. #endif
  25940. startTimer (18 + JUCE_NAMESPACE::Random::getSystemRandom().nextInt (5));
  25941. repaint();
  25942. }
  25943. #endif
  25944. #if ! JUCE_MAC
  25945. void closePluginWindow()
  25946. {
  25947. if (isOpen)
  25948. {
  25949. log (T("Closing VST UI: ") + plugin.getName());
  25950. isOpen = false;
  25951. dispatch (effEditClose, 0, 0, 0, 0);
  25952. #if JUCE_WIN32
  25953. #pragma warning (push)
  25954. #pragma warning (disable: 4244)
  25955. if (pluginHWND != 0 && IsWindow (pluginHWND))
  25956. SetWindowLongPtr (pluginHWND, GWL_WNDPROC, (LONG_PTR) originalWndProc);
  25957. #pragma warning (pop)
  25958. stopTimer();
  25959. if (pluginHWND != 0 && IsWindow (pluginHWND))
  25960. DestroyWindow (pluginHWND);
  25961. pluginHWND = 0;
  25962. #elif JUCE_LINUX
  25963. stopTimer();
  25964. pluginWindow = 0;
  25965. pluginProc = 0;
  25966. #endif
  25967. }
  25968. }
  25969. #endif
  25970. int dispatch (const int opcode, const int index, const int value, void* const ptr, float opt)
  25971. {
  25972. return plugin.dispatch (opcode, index, value, ptr, opt);
  25973. }
  25974. #if JUCE_WIN32
  25975. void checkPluginWindowSize() throw()
  25976. {
  25977. RECT r;
  25978. GetWindowRect (pluginHWND, &r);
  25979. const int w = r.right - r.left;
  25980. const int h = r.bottom - r.top;
  25981. if (isShowing() && w > 0 && h > 0
  25982. && (w != getWidth() || h != getHeight())
  25983. && ! pluginRefusesToResize)
  25984. {
  25985. setSize (w, h);
  25986. sizeCheckCount = 0;
  25987. }
  25988. }
  25989. // hooks to get keyboard events from VST windows..
  25990. static LRESULT CALLBACK vstHookWndProc (HWND hW, UINT message, WPARAM wParam, LPARAM lParam)
  25991. {
  25992. for (int i = activeVSTWindows.size(); --i >= 0;)
  25993. {
  25994. const VSTPluginWindow* const w = (const VSTPluginWindow*) activeVSTWindows.getUnchecked (i);
  25995. if (w->pluginHWND == hW)
  25996. {
  25997. if (message == WM_CHAR
  25998. || message == WM_KEYDOWN
  25999. || message == WM_SYSKEYDOWN
  26000. || message == WM_KEYUP
  26001. || message == WM_SYSKEYUP
  26002. || message == WM_APPCOMMAND)
  26003. {
  26004. SendMessage ((HWND) w->getTopLevelComponent()->getWindowHandle(),
  26005. message, wParam, lParam);
  26006. }
  26007. return CallWindowProc ((WNDPROC) (w->originalWndProc),
  26008. (HWND) w->pluginHWND,
  26009. message,
  26010. wParam,
  26011. lParam);
  26012. }
  26013. }
  26014. return DefWindowProc (hW, message, wParam, lParam);
  26015. }
  26016. #endif
  26017. #if JUCE_LINUX
  26018. // overload mouse/keyboard events to forward them to the plugin's inner window..
  26019. void sendEventToChild (XEvent* event)
  26020. {
  26021. if (pluginProc != 0)
  26022. {
  26023. // if the plugin publishes an event procedure, pass the event directly..
  26024. pluginProc (event);
  26025. }
  26026. else if (pluginWindow != 0)
  26027. {
  26028. // if the plugin has a window, then send the event to the window so that
  26029. // its message thread will pick it up..
  26030. XSendEvent (display, pluginWindow, False, 0L, event);
  26031. XFlush (display);
  26032. }
  26033. }
  26034. void mouseEnter (const MouseEvent& e)
  26035. {
  26036. if (pluginWindow != 0)
  26037. {
  26038. XEvent ev;
  26039. zerostruct (ev);
  26040. ev.xcrossing.display = display;
  26041. ev.xcrossing.type = EnterNotify;
  26042. ev.xcrossing.window = pluginWindow;
  26043. ev.xcrossing.root = RootWindow (display, DefaultScreen (display));
  26044. ev.xcrossing.time = CurrentTime;
  26045. ev.xcrossing.x = e.x;
  26046. ev.xcrossing.y = e.y;
  26047. ev.xcrossing.x_root = e.getScreenX();
  26048. ev.xcrossing.y_root = e.getScreenY();
  26049. ev.xcrossing.mode = NotifyNormal; // NotifyGrab, NotifyUngrab
  26050. ev.xcrossing.detail = NotifyAncestor; // NotifyVirtual, NotifyInferior, NotifyNonlinear,NotifyNonlinearVirtual
  26051. translateJuceToXCrossingModifiers (e, ev);
  26052. sendEventToChild (&ev);
  26053. }
  26054. }
  26055. void mouseExit (const MouseEvent& e)
  26056. {
  26057. if (pluginWindow != 0)
  26058. {
  26059. XEvent ev;
  26060. zerostruct (ev);
  26061. ev.xcrossing.display = display;
  26062. ev.xcrossing.type = LeaveNotify;
  26063. ev.xcrossing.window = pluginWindow;
  26064. ev.xcrossing.root = RootWindow (display, DefaultScreen (display));
  26065. ev.xcrossing.time = CurrentTime;
  26066. ev.xcrossing.x = e.x;
  26067. ev.xcrossing.y = e.y;
  26068. ev.xcrossing.x_root = e.getScreenX();
  26069. ev.xcrossing.y_root = e.getScreenY();
  26070. ev.xcrossing.mode = NotifyNormal; // NotifyGrab, NotifyUngrab
  26071. ev.xcrossing.detail = NotifyAncestor; // NotifyVirtual, NotifyInferior, NotifyNonlinear,NotifyNonlinearVirtual
  26072. ev.xcrossing.focus = hasKeyboardFocus (true); // TODO - yes ?
  26073. translateJuceToXCrossingModifiers (e, ev);
  26074. sendEventToChild (&ev);
  26075. }
  26076. }
  26077. void mouseMove (const MouseEvent& e)
  26078. {
  26079. if (pluginWindow != 0)
  26080. {
  26081. XEvent ev;
  26082. zerostruct (ev);
  26083. ev.xmotion.display = display;
  26084. ev.xmotion.type = MotionNotify;
  26085. ev.xmotion.window = pluginWindow;
  26086. ev.xmotion.root = RootWindow (display, DefaultScreen (display));
  26087. ev.xmotion.time = CurrentTime;
  26088. ev.xmotion.is_hint = NotifyNormal;
  26089. ev.xmotion.x = e.x;
  26090. ev.xmotion.y = e.y;
  26091. ev.xmotion.x_root = e.getScreenX();
  26092. ev.xmotion.y_root = e.getScreenY();
  26093. sendEventToChild (&ev);
  26094. }
  26095. }
  26096. void mouseDrag (const MouseEvent& e)
  26097. {
  26098. if (pluginWindow != 0)
  26099. {
  26100. XEvent ev;
  26101. zerostruct (ev);
  26102. ev.xmotion.display = display;
  26103. ev.xmotion.type = MotionNotify;
  26104. ev.xmotion.window = pluginWindow;
  26105. ev.xmotion.root = RootWindow (display, DefaultScreen (display));
  26106. ev.xmotion.time = CurrentTime;
  26107. ev.xmotion.x = e.x ;
  26108. ev.xmotion.y = e.y;
  26109. ev.xmotion.x_root = e.getScreenX();
  26110. ev.xmotion.y_root = e.getScreenY();
  26111. ev.xmotion.is_hint = NotifyNormal;
  26112. translateJuceToXMotionModifiers (e, ev);
  26113. sendEventToChild (&ev);
  26114. }
  26115. }
  26116. void mouseUp (const MouseEvent& e)
  26117. {
  26118. if (pluginWindow != 0)
  26119. {
  26120. XEvent ev;
  26121. zerostruct (ev);
  26122. ev.xbutton.display = display;
  26123. ev.xbutton.type = ButtonRelease;
  26124. ev.xbutton.window = pluginWindow;
  26125. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  26126. ev.xbutton.time = CurrentTime;
  26127. ev.xbutton.x = e.x;
  26128. ev.xbutton.y = e.y;
  26129. ev.xbutton.x_root = e.getScreenX();
  26130. ev.xbutton.y_root = e.getScreenY();
  26131. translateJuceToXButtonModifiers (e, ev);
  26132. sendEventToChild (&ev);
  26133. }
  26134. }
  26135. void mouseWheelMove (const MouseEvent& e,
  26136. float incrementX,
  26137. float incrementY)
  26138. {
  26139. if (pluginWindow != 0)
  26140. {
  26141. XEvent ev;
  26142. zerostruct (ev);
  26143. ev.xbutton.display = display;
  26144. ev.xbutton.type = ButtonPress;
  26145. ev.xbutton.window = pluginWindow;
  26146. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  26147. ev.xbutton.time = CurrentTime;
  26148. ev.xbutton.x = e.x;
  26149. ev.xbutton.y = e.y;
  26150. ev.xbutton.x_root = e.getScreenX();
  26151. ev.xbutton.y_root = e.getScreenY();
  26152. translateJuceToXMouseWheelModifiers (e, incrementY, ev);
  26153. sendEventToChild (&ev);
  26154. // TODO - put a usleep here ?
  26155. ev.xbutton.type = ButtonRelease;
  26156. sendEventToChild (&ev);
  26157. }
  26158. }
  26159. #endif
  26160. #if JUCE_MAC
  26161. #if ! JUCE_SUPPORT_CARBON
  26162. #error "To build VSTs, you need to enable the JUCE_SUPPORT_CARBON flag in your config!"
  26163. #endif
  26164. class InnerWrapperComponent : public CarbonViewWrapperComponent
  26165. {
  26166. public:
  26167. InnerWrapperComponent (VSTPluginWindow* const owner_)
  26168. : owner (owner_),
  26169. alreadyInside (false)
  26170. {
  26171. }
  26172. ~InnerWrapperComponent()
  26173. {
  26174. deleteWindow();
  26175. }
  26176. HIViewRef attachView (WindowRef windowRef, HIViewRef rootView)
  26177. {
  26178. owner->openPluginWindow (windowRef);
  26179. return 0;
  26180. }
  26181. void removeView (HIViewRef)
  26182. {
  26183. owner->dispatch (effEditClose, 0, 0, 0, 0);
  26184. owner->dispatch (effEditSleep, 0, 0, 0, 0);
  26185. }
  26186. bool getEmbeddedViewSize (int& w, int& h)
  26187. {
  26188. ERect* rect = 0;
  26189. owner->dispatch (effEditGetRect, 0, 0, &rect, 0);
  26190. w = rect->right - rect->left;
  26191. h = rect->bottom - rect->top;
  26192. return true;
  26193. }
  26194. void mouseDown (int x, int y)
  26195. {
  26196. if (! alreadyInside)
  26197. {
  26198. alreadyInside = true;
  26199. getTopLevelComponent()->toFront (true);
  26200. owner->dispatch (effEditMouse, x, y, 0, 0);
  26201. alreadyInside = false;
  26202. }
  26203. else
  26204. {
  26205. PostEvent (::mouseDown, 0);
  26206. }
  26207. }
  26208. void paint()
  26209. {
  26210. ComponentPeer* const peer = getPeer();
  26211. if (peer != 0)
  26212. {
  26213. ERect r;
  26214. r.left = getScreenX() - peer->getScreenX();
  26215. r.right = r.left + getWidth();
  26216. r.top = getScreenY() - peer->getScreenY();
  26217. r.bottom = r.top + getHeight();
  26218. owner->dispatch (effEditDraw, 0, 0, &r, 0);
  26219. }
  26220. }
  26221. private:
  26222. VSTPluginWindow* const owner;
  26223. bool alreadyInside;
  26224. };
  26225. friend class InnerWrapperComponent;
  26226. InnerWrapperComponent* innerWrapper;
  26227. void resized()
  26228. {
  26229. innerWrapper->setSize (getWidth(), getHeight());
  26230. }
  26231. #endif
  26232. };
  26233. AudioProcessorEditor* VSTPluginInstance::createEditor()
  26234. {
  26235. if (hasEditor())
  26236. return new VSTPluginWindow (*this);
  26237. return 0;
  26238. }
  26239. void VSTPluginInstance::handleAsyncUpdate()
  26240. {
  26241. // indicates that something about the plugin has changed..
  26242. updateHostDisplay();
  26243. }
  26244. bool VSTPluginInstance::restoreProgramSettings (const fxProgram* const prog)
  26245. {
  26246. if (vst_swap (prog->chunkMagic) == 'CcnK' && vst_swap (prog->fxMagic) == 'FxCk')
  26247. {
  26248. changeProgramName (getCurrentProgram(), prog->prgName);
  26249. for (int i = 0; i < vst_swap (prog->numParams); ++i)
  26250. setParameter (i, vst_swapFloat (prog->params[i]));
  26251. return true;
  26252. }
  26253. return false;
  26254. }
  26255. bool VSTPluginInstance::loadFromFXBFile (const void* const data,
  26256. const int dataSize)
  26257. {
  26258. if (dataSize < 28)
  26259. return false;
  26260. const fxSet* const set = (const fxSet*) data;
  26261. if ((vst_swap (set->chunkMagic) != 'CcnK' && vst_swap (set->chunkMagic) != 'KncC')
  26262. || vst_swap (set->version) > fxbVersionNum)
  26263. return false;
  26264. if (vst_swap (set->fxMagic) == 'FxBk')
  26265. {
  26266. // bank of programs
  26267. if (vst_swap (set->numPrograms) >= 0)
  26268. {
  26269. const int oldProg = getCurrentProgram();
  26270. const int numParams = vst_swap (((const fxProgram*) (set->programs))->numParams);
  26271. const int progLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  26272. for (int i = 0; i < vst_swap (set->numPrograms); ++i)
  26273. {
  26274. if (i != oldProg)
  26275. {
  26276. const fxProgram* const prog = (const fxProgram*) (((const char*) (set->programs)) + i * progLen);
  26277. if (((const char*) prog) - ((const char*) set) >= dataSize)
  26278. return false;
  26279. if (vst_swap (set->numPrograms) > 0)
  26280. setCurrentProgram (i);
  26281. if (! restoreProgramSettings (prog))
  26282. return false;
  26283. }
  26284. }
  26285. if (vst_swap (set->numPrograms) > 0)
  26286. setCurrentProgram (oldProg);
  26287. const fxProgram* const prog = (const fxProgram*) (((const char*) (set->programs)) + oldProg * progLen);
  26288. if (((const char*) prog) - ((const char*) set) >= dataSize)
  26289. return false;
  26290. if (! restoreProgramSettings (prog))
  26291. return false;
  26292. }
  26293. }
  26294. else if (vst_swap (set->fxMagic) == 'FxCk')
  26295. {
  26296. // single program
  26297. const fxProgram* const prog = (const fxProgram*) data;
  26298. if (vst_swap (prog->chunkMagic) != 'CcnK')
  26299. return false;
  26300. changeProgramName (getCurrentProgram(), prog->prgName);
  26301. for (int i = 0; i < vst_swap (prog->numParams); ++i)
  26302. setParameter (i, vst_swapFloat (prog->params[i]));
  26303. }
  26304. else if (vst_swap (set->fxMagic) == 'FBCh' || vst_swap (set->fxMagic) == 'hCBF')
  26305. {
  26306. // non-preset chunk
  26307. const fxChunkSet* const cset = (const fxChunkSet*) data;
  26308. if (vst_swap (cset->chunkSize) + sizeof (fxChunkSet) - 8 > (unsigned int) dataSize)
  26309. return false;
  26310. setChunkData (cset->chunk, vst_swap (cset->chunkSize), false);
  26311. }
  26312. else if (vst_swap (set->fxMagic) == 'FPCh' || vst_swap (set->fxMagic) == 'hCPF')
  26313. {
  26314. // preset chunk
  26315. const fxProgramSet* const cset = (const fxProgramSet*) data;
  26316. if (vst_swap (cset->chunkSize) + sizeof (fxProgramSet) - 8 > (unsigned int) dataSize)
  26317. return false;
  26318. setChunkData (cset->chunk, vst_swap (cset->chunkSize), true);
  26319. changeProgramName (getCurrentProgram(), cset->name);
  26320. }
  26321. else
  26322. {
  26323. return false;
  26324. }
  26325. return true;
  26326. }
  26327. void VSTPluginInstance::setParamsInProgramBlock (fxProgram* const prog) throw()
  26328. {
  26329. const int numParams = getNumParameters();
  26330. prog->chunkMagic = vst_swap ('CcnK');
  26331. prog->byteSize = 0;
  26332. prog->fxMagic = vst_swap ('FxCk');
  26333. prog->version = vst_swap (fxbVersionNum);
  26334. prog->fxID = vst_swap (getUID());
  26335. prog->fxVersion = vst_swap (getVersionNumber());
  26336. prog->numParams = vst_swap (numParams);
  26337. getCurrentProgramName().copyToBuffer (prog->prgName, sizeof (prog->prgName) - 1);
  26338. for (int i = 0; i < numParams; ++i)
  26339. prog->params[i] = vst_swapFloat (getParameter (i));
  26340. }
  26341. bool VSTPluginInstance::saveToFXBFile (MemoryBlock& dest, bool isFXB, int maxSizeMB)
  26342. {
  26343. const int numPrograms = getNumPrograms();
  26344. const int numParams = getNumParameters();
  26345. if (usesChunks())
  26346. {
  26347. if (isFXB)
  26348. {
  26349. MemoryBlock chunk;
  26350. getChunkData (chunk, false, maxSizeMB);
  26351. const int totalLen = sizeof (fxChunkSet) + chunk.getSize() - 8;
  26352. dest.setSize (totalLen, true);
  26353. fxChunkSet* const set = (fxChunkSet*) dest.getData();
  26354. set->chunkMagic = vst_swap ('CcnK');
  26355. set->byteSize = 0;
  26356. set->fxMagic = vst_swap ('FBCh');
  26357. set->version = vst_swap (fxbVersionNum);
  26358. set->fxID = vst_swap (getUID());
  26359. set->fxVersion = vst_swap (getVersionNumber());
  26360. set->numPrograms = vst_swap (numPrograms);
  26361. set->chunkSize = vst_swap (chunk.getSize());
  26362. chunk.copyTo (set->chunk, 0, chunk.getSize());
  26363. }
  26364. else
  26365. {
  26366. MemoryBlock chunk;
  26367. getChunkData (chunk, true, maxSizeMB);
  26368. const int totalLen = sizeof (fxProgramSet) + chunk.getSize() - 8;
  26369. dest.setSize (totalLen, true);
  26370. fxProgramSet* const set = (fxProgramSet*) dest.getData();
  26371. set->chunkMagic = vst_swap ('CcnK');
  26372. set->byteSize = 0;
  26373. set->fxMagic = vst_swap ('FPCh');
  26374. set->version = vst_swap (fxbVersionNum);
  26375. set->fxID = vst_swap (getUID());
  26376. set->fxVersion = vst_swap (getVersionNumber());
  26377. set->numPrograms = vst_swap (numPrograms);
  26378. set->chunkSize = vst_swap (chunk.getSize());
  26379. getCurrentProgramName().copyToBuffer (set->name, sizeof (set->name) - 1);
  26380. chunk.copyTo (set->chunk, 0, chunk.getSize());
  26381. }
  26382. }
  26383. else
  26384. {
  26385. if (isFXB)
  26386. {
  26387. const int progLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  26388. const int len = (sizeof (fxSet) - sizeof (fxProgram)) + progLen * jmax (1, numPrograms);
  26389. dest.setSize (len, true);
  26390. fxSet* const set = (fxSet*) dest.getData();
  26391. set->chunkMagic = vst_swap ('CcnK');
  26392. set->byteSize = 0;
  26393. set->fxMagic = vst_swap ('FxBk');
  26394. set->version = vst_swap (fxbVersionNum);
  26395. set->fxID = vst_swap (getUID());
  26396. set->fxVersion = vst_swap (getVersionNumber());
  26397. set->numPrograms = vst_swap (numPrograms);
  26398. const int oldProgram = getCurrentProgram();
  26399. MemoryBlock oldSettings;
  26400. createTempParameterStore (oldSettings);
  26401. setParamsInProgramBlock ((fxProgram*) (((char*) (set->programs)) + oldProgram * progLen));
  26402. for (int i = 0; i < numPrograms; ++i)
  26403. {
  26404. if (i != oldProgram)
  26405. {
  26406. setCurrentProgram (i);
  26407. setParamsInProgramBlock ((fxProgram*) (((char*) (set->programs)) + i * progLen));
  26408. }
  26409. }
  26410. setCurrentProgram (oldProgram);
  26411. restoreFromTempParameterStore (oldSettings);
  26412. }
  26413. else
  26414. {
  26415. const int totalLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  26416. dest.setSize (totalLen, true);
  26417. setParamsInProgramBlock ((fxProgram*) dest.getData());
  26418. }
  26419. }
  26420. return true;
  26421. }
  26422. void VSTPluginInstance::getChunkData (MemoryBlock& mb, bool isPreset, int maxSizeMB) const
  26423. {
  26424. if (usesChunks())
  26425. {
  26426. void* data = 0;
  26427. const int bytes = dispatch (effGetChunk, isPreset ? 1 : 0, 0, &data, 0.0f);
  26428. if (data != 0 && bytes <= maxSizeMB * 1024 * 1024)
  26429. {
  26430. mb.setSize (bytes);
  26431. mb.copyFrom (data, 0, bytes);
  26432. }
  26433. }
  26434. }
  26435. void VSTPluginInstance::setChunkData (const char* data, int size, bool isPreset)
  26436. {
  26437. if (size > 0 && usesChunks())
  26438. {
  26439. dispatch (effSetChunk, isPreset ? 1 : 0, size, (void*) data, 0.0f);
  26440. if (! isPreset)
  26441. updateStoredProgramNames();
  26442. }
  26443. }
  26444. void VSTPluginInstance::timerCallback()
  26445. {
  26446. if (dispatch (effIdle, 0, 0, 0, 0) == 0)
  26447. stopTimer();
  26448. }
  26449. int VSTPluginInstance::dispatch (const int opcode, const int index, const int value, void* const ptr, float opt) const
  26450. {
  26451. const ScopedLock sl (lock);
  26452. ++insideVSTCallback;
  26453. int result = 0;
  26454. try
  26455. {
  26456. if (effect != 0)
  26457. {
  26458. #if JUCE_MAC
  26459. if (module->resFileId != 0)
  26460. UseResFile (module->resFileId);
  26461. CGrafPtr oldPort;
  26462. if (getActiveEditor() != 0)
  26463. {
  26464. int x = 0, y = 0;
  26465. getActiveEditor()->relativePositionToOtherComponent (getActiveEditor()->getTopLevelComponent(), x, y);
  26466. GetPort (&oldPort);
  26467. SetPortWindowPort ((WindowRef) getActiveEditor()->getWindowHandle());
  26468. SetOrigin (-x, -y);
  26469. }
  26470. #endif
  26471. result = effect->dispatcher (effect, opcode, index, value, ptr, opt);
  26472. #if JUCE_MAC
  26473. if (getActiveEditor() != 0)
  26474. SetPort (oldPort);
  26475. module->resFileId = CurResFile();
  26476. #endif
  26477. --insideVSTCallback;
  26478. return result;
  26479. }
  26480. }
  26481. catch (...)
  26482. {
  26483. //char s[512];
  26484. //sprintf (s, "dispatcher (%d, %d, %d, %x, %f)", opcode, index, value, (int)ptr, opt);
  26485. }
  26486. --insideVSTCallback;
  26487. return result;
  26488. }
  26489. // handles non plugin-specific callbacks..
  26490. static const int defaultVSTSampleRateValue = 16384;
  26491. static const int defaultVSTBlockSizeValue = 512;
  26492. static VstIntPtr handleGeneralCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt)
  26493. {
  26494. (void) index;
  26495. (void) value;
  26496. (void) opt;
  26497. switch (opcode)
  26498. {
  26499. case audioMasterCanDo:
  26500. {
  26501. static const char* canDos[] = { "supplyIdle",
  26502. "sendVstEvents",
  26503. "sendVstMidiEvent",
  26504. "sendVstTimeInfo",
  26505. "receiveVstEvents",
  26506. "receiveVstMidiEvent",
  26507. "supportShell",
  26508. "shellCategory" };
  26509. for (int i = 0; i < numElementsInArray (canDos); ++i)
  26510. if (strcmp (canDos[i], (const char*) ptr) == 0)
  26511. return 1;
  26512. return 0;
  26513. }
  26514. case audioMasterVersion:
  26515. return 0x2400;
  26516. case audioMasterCurrentId:
  26517. return shellUIDToCreate;
  26518. case audioMasterGetNumAutomatableParameters:
  26519. return 0;
  26520. case audioMasterGetAutomationState:
  26521. return 1;
  26522. case audioMasterGetVendorVersion:
  26523. return 0x0101;
  26524. case audioMasterGetVendorString:
  26525. case audioMasterGetProductString:
  26526. {
  26527. String hostName ("Juce VST Host");
  26528. if (JUCEApplication::getInstance() != 0)
  26529. hostName = JUCEApplication::getInstance()->getApplicationName();
  26530. hostName.copyToBuffer ((char*) ptr, jmin (kVstMaxVendorStrLen, kVstMaxProductStrLen) - 1);
  26531. }
  26532. break;
  26533. case audioMasterGetSampleRate:
  26534. return (VstIntPtr) defaultVSTSampleRateValue;
  26535. case audioMasterGetBlockSize:
  26536. return (VstIntPtr) defaultVSTBlockSizeValue;
  26537. case audioMasterSetOutputSampleRate:
  26538. return 0;
  26539. default:
  26540. DBG ("*** Unhandled VST Callback: " + String ((int) opcode));
  26541. break;
  26542. }
  26543. return 0;
  26544. }
  26545. // handles callbacks for a specific plugin
  26546. VstIntPtr VSTPluginInstance::handleCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt)
  26547. {
  26548. switch (opcode)
  26549. {
  26550. case audioMasterAutomate:
  26551. sendParamChangeMessageToListeners (index, opt);
  26552. break;
  26553. case audioMasterProcessEvents:
  26554. handleMidiFromPlugin ((const VstEvents*) ptr);
  26555. break;
  26556. case audioMasterGetTime:
  26557. #ifdef _MSC_VER
  26558. #pragma warning (push)
  26559. #pragma warning (disable: 4311)
  26560. #endif
  26561. return (VstIntPtr) &vstHostTime;
  26562. #ifdef _MSC_VER
  26563. #pragma warning (pop)
  26564. #endif
  26565. break;
  26566. case audioMasterIdle:
  26567. if (insideVSTCallback == 0 && MessageManager::getInstance()->isThisTheMessageThread())
  26568. {
  26569. ++insideVSTCallback;
  26570. #if JUCE_MAC
  26571. if (getActiveEditor() != 0)
  26572. dispatch (effEditIdle, 0, 0, 0, 0);
  26573. #endif
  26574. juce_callAnyTimersSynchronously();
  26575. handleUpdateNowIfNeeded();
  26576. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  26577. ComponentPeer::getPeer (i)->performAnyPendingRepaintsNow();
  26578. --insideVSTCallback;
  26579. }
  26580. break;
  26581. case audioMasterUpdateDisplay:
  26582. triggerAsyncUpdate();
  26583. break;
  26584. case audioMasterTempoAt:
  26585. // returns (10000 * bpm)
  26586. break;
  26587. case audioMasterNeedIdle:
  26588. startTimer (50);
  26589. break;
  26590. case audioMasterSizeWindow:
  26591. if (getActiveEditor() != 0)
  26592. getActiveEditor()->setSize (index, value);
  26593. return 1;
  26594. case audioMasterGetSampleRate:
  26595. return (VstIntPtr) (getSampleRate() > 0 ? getSampleRate() : defaultVSTSampleRateValue);
  26596. case audioMasterGetBlockSize:
  26597. return (VstIntPtr) (getBlockSize() > 0 ? getBlockSize() : defaultVSTBlockSizeValue);
  26598. case audioMasterWantMidi:
  26599. wantsMidiMessages = true;
  26600. break;
  26601. case audioMasterGetDirectory:
  26602. #if JUCE_MAC
  26603. return (VstIntPtr) (void*) &module->parentDirFSSpec;
  26604. #else
  26605. return (VstIntPtr) (pointer_sized_uint) (const char*) module->fullParentDirectoryPathName;
  26606. #endif
  26607. case audioMasterGetAutomationState:
  26608. // returns 0: not supported, 1: off, 2:read, 3:write, 4:read/write
  26609. break;
  26610. // none of these are handled (yet)..
  26611. case audioMasterBeginEdit:
  26612. case audioMasterEndEdit:
  26613. case audioMasterSetTime:
  26614. case audioMasterPinConnected:
  26615. case audioMasterGetParameterQuantization:
  26616. case audioMasterIOChanged:
  26617. case audioMasterGetInputLatency:
  26618. case audioMasterGetOutputLatency:
  26619. case audioMasterGetPreviousPlug:
  26620. case audioMasterGetNextPlug:
  26621. case audioMasterWillReplaceOrAccumulate:
  26622. case audioMasterGetCurrentProcessLevel:
  26623. case audioMasterOfflineStart:
  26624. case audioMasterOfflineRead:
  26625. case audioMasterOfflineWrite:
  26626. case audioMasterOfflineGetCurrentPass:
  26627. case audioMasterOfflineGetCurrentMetaPass:
  26628. case audioMasterVendorSpecific:
  26629. case audioMasterSetIcon:
  26630. case audioMasterGetLanguage:
  26631. case audioMasterOpenWindow:
  26632. case audioMasterCloseWindow:
  26633. break;
  26634. default:
  26635. return handleGeneralCallback (opcode, index, value, ptr, opt);
  26636. }
  26637. return 0;
  26638. }
  26639. // entry point for all callbacks from the plugin
  26640. static VstIntPtr VSTCALLBACK audioMaster (AEffect* effect, VstInt32 opcode, VstInt32 index, VstIntPtr value, void* ptr, float opt)
  26641. {
  26642. try
  26643. {
  26644. if (effect != 0 && effect->resvd2 != 0)
  26645. {
  26646. return ((VSTPluginInstance*)(effect->resvd2))
  26647. ->handleCallback (opcode, index, value, ptr, opt);
  26648. }
  26649. return handleGeneralCallback (opcode, index, value, ptr, opt);
  26650. }
  26651. catch (...)
  26652. {
  26653. return 0;
  26654. }
  26655. }
  26656. const String VSTPluginInstance::getVersion() const throw()
  26657. {
  26658. unsigned int v = dispatch (effGetVendorVersion, 0, 0, 0, 0);
  26659. String s;
  26660. if (v == 0 || v == -1)
  26661. v = getVersionNumber();
  26662. if (v != 0)
  26663. {
  26664. int versionBits[4];
  26665. int n = 0;
  26666. while (v != 0)
  26667. {
  26668. versionBits [n++] = (v & 0xff);
  26669. v >>= 8;
  26670. }
  26671. s << 'V';
  26672. while (n > 0)
  26673. {
  26674. s << versionBits [--n];
  26675. if (n > 0)
  26676. s << '.';
  26677. }
  26678. }
  26679. return s;
  26680. }
  26681. int VSTPluginInstance::getUID() const throw()
  26682. {
  26683. int uid = effect != 0 ? effect->uniqueID : 0;
  26684. if (uid == 0)
  26685. uid = module->file.hashCode();
  26686. return uid;
  26687. }
  26688. const String VSTPluginInstance::getCategory() const throw()
  26689. {
  26690. const char* result = 0;
  26691. switch (dispatch (effGetPlugCategory, 0, 0, 0, 0))
  26692. {
  26693. case kPlugCategEffect:
  26694. result = "Effect";
  26695. break;
  26696. case kPlugCategSynth:
  26697. result = "Synth";
  26698. break;
  26699. case kPlugCategAnalysis:
  26700. result = "Anaylsis";
  26701. break;
  26702. case kPlugCategMastering:
  26703. result = "Mastering";
  26704. break;
  26705. case kPlugCategSpacializer:
  26706. result = "Spacial";
  26707. break;
  26708. case kPlugCategRoomFx:
  26709. result = "Reverb";
  26710. break;
  26711. case kPlugSurroundFx:
  26712. result = "Surround";
  26713. break;
  26714. case kPlugCategRestoration:
  26715. result = "Restoration";
  26716. break;
  26717. case kPlugCategGenerator:
  26718. result = "Tone generation";
  26719. break;
  26720. default:
  26721. break;
  26722. }
  26723. return result;
  26724. }
  26725. float VSTPluginInstance::getParameter (int index)
  26726. {
  26727. if (effect != 0 && ((unsigned int) index) < (unsigned int) effect->numParams)
  26728. {
  26729. try
  26730. {
  26731. const ScopedLock sl (lock);
  26732. return effect->getParameter (effect, index);
  26733. }
  26734. catch (...)
  26735. {
  26736. }
  26737. }
  26738. return 0.0f;
  26739. }
  26740. void VSTPluginInstance::setParameter (int index, float newValue)
  26741. {
  26742. if (effect != 0 && ((unsigned int) index) < (unsigned int) effect->numParams)
  26743. {
  26744. try
  26745. {
  26746. const ScopedLock sl (lock);
  26747. if (effect->getParameter (effect, index) != newValue)
  26748. effect->setParameter (effect, index, newValue);
  26749. }
  26750. catch (...)
  26751. {
  26752. }
  26753. }
  26754. }
  26755. const String VSTPluginInstance::getParameterName (int index)
  26756. {
  26757. if (effect != 0)
  26758. {
  26759. jassert (index >= 0 && index < effect->numParams);
  26760. char nm [256];
  26761. zerostruct (nm);
  26762. dispatch (effGetParamName, index, 0, nm, 0);
  26763. return String (nm).trim();
  26764. }
  26765. return String::empty;
  26766. }
  26767. const String VSTPluginInstance::getParameterLabel (int index) const
  26768. {
  26769. if (effect != 0)
  26770. {
  26771. jassert (index >= 0 && index < effect->numParams);
  26772. char nm [256];
  26773. zerostruct (nm);
  26774. dispatch (effGetParamLabel, index, 0, nm, 0);
  26775. return String (nm).trim();
  26776. }
  26777. return String::empty;
  26778. }
  26779. const String VSTPluginInstance::getParameterText (int index)
  26780. {
  26781. if (effect != 0)
  26782. {
  26783. jassert (index >= 0 && index < effect->numParams);
  26784. char nm [256];
  26785. zerostruct (nm);
  26786. dispatch (effGetParamDisplay, index, 0, nm, 0);
  26787. return String (nm).trim();
  26788. }
  26789. return String::empty;
  26790. }
  26791. bool VSTPluginInstance::isParameterAutomatable (int index) const
  26792. {
  26793. if (effect != 0)
  26794. {
  26795. jassert (index >= 0 && index < effect->numParams);
  26796. return dispatch (effCanBeAutomated, index, 0, 0, 0) != 0;
  26797. }
  26798. return false;
  26799. }
  26800. void VSTPluginInstance::createTempParameterStore (MemoryBlock& dest)
  26801. {
  26802. dest.setSize (64 + 4 * getNumParameters());
  26803. dest.fillWith (0);
  26804. getCurrentProgramName().copyToBuffer ((char*) dest.getData(), 63);
  26805. float* const p = (float*) (((char*) dest.getData()) + 64);
  26806. for (int i = 0; i < getNumParameters(); ++i)
  26807. p[i] = getParameter(i);
  26808. }
  26809. void VSTPluginInstance::restoreFromTempParameterStore (const MemoryBlock& m)
  26810. {
  26811. changeProgramName (getCurrentProgram(), (const char*) m.getData());
  26812. float* p = (float*) (((char*) m.getData()) + 64);
  26813. for (int i = 0; i < getNumParameters(); ++i)
  26814. setParameter (i, p[i]);
  26815. }
  26816. void VSTPluginInstance::setCurrentProgram (int newIndex)
  26817. {
  26818. if (getNumPrograms() > 0 && newIndex != getCurrentProgram())
  26819. dispatch (effSetProgram, 0, jlimit (0, getNumPrograms() - 1, newIndex), 0, 0);
  26820. }
  26821. const String VSTPluginInstance::getProgramName (int index)
  26822. {
  26823. if (index == getCurrentProgram())
  26824. {
  26825. return getCurrentProgramName();
  26826. }
  26827. else if (effect != 0)
  26828. {
  26829. char nm [256];
  26830. zerostruct (nm);
  26831. if (dispatch (effGetProgramNameIndexed,
  26832. jlimit (0, getNumPrograms(), index),
  26833. -1, nm, 0) != 0)
  26834. {
  26835. return String (nm).trim();
  26836. }
  26837. }
  26838. return programNames [index];
  26839. }
  26840. void VSTPluginInstance::changeProgramName (int index, const String& newName)
  26841. {
  26842. if (index == getCurrentProgram())
  26843. {
  26844. if (getNumPrograms() > 0 && newName != getCurrentProgramName())
  26845. dispatch (effSetProgramName, 0, 0, (void*) (const char*) newName.substring (0, 24), 0.0f);
  26846. }
  26847. else
  26848. {
  26849. jassertfalse // xxx not implemented!
  26850. }
  26851. }
  26852. void VSTPluginInstance::updateStoredProgramNames()
  26853. {
  26854. if (effect != 0 && getNumPrograms() > 0)
  26855. {
  26856. char nm [256];
  26857. zerostruct (nm);
  26858. // only do this if the plugin can't use indexed names..
  26859. if (dispatch (effGetProgramNameIndexed, 0, -1, nm, 0) == 0)
  26860. {
  26861. const int oldProgram = getCurrentProgram();
  26862. MemoryBlock oldSettings;
  26863. createTempParameterStore (oldSettings);
  26864. for (int i = 0; i < getNumPrograms(); ++i)
  26865. {
  26866. setCurrentProgram (i);
  26867. getCurrentProgramName(); // (this updates the list)
  26868. }
  26869. setCurrentProgram (oldProgram);
  26870. restoreFromTempParameterStore (oldSettings);
  26871. }
  26872. }
  26873. }
  26874. const String VSTPluginInstance::getCurrentProgramName()
  26875. {
  26876. if (effect != 0)
  26877. {
  26878. char nm [256];
  26879. zerostruct (nm);
  26880. dispatch (effGetProgramName, 0, 0, nm, 0);
  26881. const int index = getCurrentProgram();
  26882. if (programNames[index].isEmpty())
  26883. {
  26884. while (programNames.size() < index)
  26885. programNames.add (String::empty);
  26886. programNames.set (index, String (nm).trim());
  26887. }
  26888. return String (nm).trim();
  26889. }
  26890. return String::empty;
  26891. }
  26892. const String VSTPluginInstance::getInputChannelName (const int index) const
  26893. {
  26894. if (index >= 0 && index < getNumInputChannels())
  26895. {
  26896. VstPinProperties pinProps;
  26897. if (dispatch (effGetInputProperties, index, 0, &pinProps, 0.0f) != 0)
  26898. return String (pinProps.label, sizeof (pinProps.label));
  26899. }
  26900. return String::empty;
  26901. }
  26902. bool VSTPluginInstance::isInputChannelStereoPair (int index) const
  26903. {
  26904. if (index < 0 || index >= getNumInputChannels())
  26905. return false;
  26906. VstPinProperties pinProps;
  26907. if (dispatch (effGetInputProperties, index, 0, &pinProps, 0.0f) != 0)
  26908. return (pinProps.flags & kVstPinIsStereo) != 0;
  26909. return true;
  26910. }
  26911. const String VSTPluginInstance::getOutputChannelName (const int index) const
  26912. {
  26913. if (index >= 0 && index < getNumOutputChannels())
  26914. {
  26915. VstPinProperties pinProps;
  26916. if (dispatch (effGetOutputProperties, index, 0, &pinProps, 0.0f) != 0)
  26917. return String (pinProps.label, sizeof (pinProps.label));
  26918. }
  26919. return String::empty;
  26920. }
  26921. bool VSTPluginInstance::isOutputChannelStereoPair (int index) const
  26922. {
  26923. if (index < 0 || index >= getNumOutputChannels())
  26924. return false;
  26925. VstPinProperties pinProps;
  26926. if (dispatch (effGetOutputProperties, index, 0, &pinProps, 0.0f) != 0)
  26927. return (pinProps.flags & kVstPinIsStereo) != 0;
  26928. return true;
  26929. }
  26930. void VSTPluginInstance::setPower (const bool on)
  26931. {
  26932. dispatch (effMainsChanged, 0, on ? 1 : 0, 0, 0);
  26933. isPowerOn = on;
  26934. }
  26935. const int defaultMaxSizeMB = 64;
  26936. void VSTPluginInstance::getStateInformation (MemoryBlock& destData)
  26937. {
  26938. saveToFXBFile (destData, true, defaultMaxSizeMB);
  26939. }
  26940. void VSTPluginInstance::getCurrentProgramStateInformation (MemoryBlock& destData)
  26941. {
  26942. saveToFXBFile (destData, false, defaultMaxSizeMB);
  26943. }
  26944. void VSTPluginInstance::setStateInformation (const void* data, int sizeInBytes)
  26945. {
  26946. loadFromFXBFile (data, sizeInBytes);
  26947. }
  26948. void VSTPluginInstance::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  26949. {
  26950. loadFromFXBFile (data, sizeInBytes);
  26951. }
  26952. VSTPluginFormat::VSTPluginFormat()
  26953. {
  26954. }
  26955. VSTPluginFormat::~VSTPluginFormat()
  26956. {
  26957. }
  26958. void VSTPluginFormat::findAllTypesForFile (OwnedArray <PluginDescription>& results,
  26959. const String& fileOrIdentifier)
  26960. {
  26961. if (! fileMightContainThisPluginType (fileOrIdentifier))
  26962. return;
  26963. PluginDescription desc;
  26964. desc.fileOrIdentifier = fileOrIdentifier;
  26965. desc.uid = 0;
  26966. VSTPluginInstance* instance = dynamic_cast <VSTPluginInstance*> (createInstanceFromDescription (desc));
  26967. if (instance == 0)
  26968. return;
  26969. try
  26970. {
  26971. #if JUCE_MAC
  26972. if (instance->module->resFileId != 0)
  26973. UseResFile (instance->module->resFileId);
  26974. #endif
  26975. instance->fillInPluginDescription (desc);
  26976. VstPlugCategory category = (VstPlugCategory) instance->dispatch (effGetPlugCategory, 0, 0, 0, 0);
  26977. if (category != kPlugCategShell)
  26978. {
  26979. // Normal plugin...
  26980. results.add (new PluginDescription (desc));
  26981. ++insideVSTCallback;
  26982. instance->dispatch (effOpen, 0, 0, 0, 0);
  26983. --insideVSTCallback;
  26984. }
  26985. else
  26986. {
  26987. // It's a shell plugin, so iterate all the subtypes...
  26988. char shellEffectName [64];
  26989. for (;;)
  26990. {
  26991. zerostruct (shellEffectName);
  26992. const int uid = instance->dispatch (effShellGetNextPlugin, 0, 0, shellEffectName, 0);
  26993. if (uid == 0)
  26994. {
  26995. break;
  26996. }
  26997. else
  26998. {
  26999. desc.uid = uid;
  27000. desc.name = shellEffectName;
  27001. bool alreadyThere = false;
  27002. for (int i = results.size(); --i >= 0;)
  27003. {
  27004. PluginDescription* const d = results.getUnchecked(i);
  27005. if (d->isDuplicateOf (desc))
  27006. {
  27007. alreadyThere = true;
  27008. break;
  27009. }
  27010. }
  27011. if (! alreadyThere)
  27012. results.add (new PluginDescription (desc));
  27013. }
  27014. }
  27015. }
  27016. }
  27017. catch (...)
  27018. {
  27019. // crashed while loading...
  27020. }
  27021. deleteAndZero (instance);
  27022. }
  27023. AudioPluginInstance* VSTPluginFormat::createInstanceFromDescription (const PluginDescription& desc)
  27024. {
  27025. VSTPluginInstance* result = 0;
  27026. if (fileMightContainThisPluginType (desc.fileOrIdentifier))
  27027. {
  27028. File file (desc.fileOrIdentifier);
  27029. const File previousWorkingDirectory (File::getCurrentWorkingDirectory());
  27030. file.getParentDirectory().setAsCurrentWorkingDirectory();
  27031. const ReferenceCountedObjectPtr <ModuleHandle> module (ModuleHandle::findOrCreateModule (file));
  27032. if (module != 0)
  27033. {
  27034. shellUIDToCreate = desc.uid;
  27035. result = new VSTPluginInstance (module);
  27036. if (result->effect != 0)
  27037. {
  27038. result->effect->resvd2 = (VstIntPtr) (pointer_sized_int) result;
  27039. result->initialise();
  27040. }
  27041. else
  27042. {
  27043. deleteAndZero (result);
  27044. }
  27045. }
  27046. previousWorkingDirectory.setAsCurrentWorkingDirectory();
  27047. }
  27048. return result;
  27049. }
  27050. bool VSTPluginFormat::fileMightContainThisPluginType (const String& fileOrIdentifier)
  27051. {
  27052. const File f (fileOrIdentifier);
  27053. #if JUCE_MAC
  27054. if (f.isDirectory() && f.hasFileExtension (T(".vst")))
  27055. return true;
  27056. #if JUCE_PPC
  27057. FSRef fileRef;
  27058. if (PlatformUtilities::makeFSRefFromPath (&fileRef, f.getFullPathName()))
  27059. {
  27060. const short resFileId = FSOpenResFile (&fileRef, fsRdPerm);
  27061. if (resFileId != -1)
  27062. {
  27063. const int numEffects = Count1Resources ('aEff');
  27064. CloseResFile (resFileId);
  27065. if (numEffects > 0)
  27066. return true;
  27067. }
  27068. }
  27069. #endif
  27070. return false;
  27071. #elif JUCE_WIN32
  27072. return f.existsAsFile()
  27073. && f.hasFileExtension (T(".dll"));
  27074. #elif JUCE_LINUX
  27075. return f.existsAsFile()
  27076. && f.hasFileExtension (T(".so"));
  27077. #endif
  27078. }
  27079. const String VSTPluginFormat::getNameOfPluginFromIdentifier (const String& fileOrIdentifier)
  27080. {
  27081. return fileOrIdentifier;
  27082. }
  27083. bool VSTPluginFormat::doesPluginStillExist (const PluginDescription& desc)
  27084. {
  27085. return File (desc.fileOrIdentifier).exists();
  27086. }
  27087. const StringArray VSTPluginFormat::searchPathsForPlugins (const FileSearchPath& directoriesToSearch, const bool recursive)
  27088. {
  27089. StringArray results;
  27090. for (int j = 0; j < directoriesToSearch.getNumPaths(); ++j)
  27091. recursiveFileSearch (results, directoriesToSearch [j], recursive);
  27092. return results;
  27093. }
  27094. void VSTPluginFormat::recursiveFileSearch (StringArray& results, const File& dir, const bool recursive)
  27095. {
  27096. // avoid allowing the dir iterator to be recursive, because we want to avoid letting it delve inside
  27097. // .component or .vst directories.
  27098. DirectoryIterator iter (dir, false, "*", File::findFilesAndDirectories);
  27099. while (iter.next())
  27100. {
  27101. const File f (iter.getFile());
  27102. bool isPlugin = false;
  27103. if (fileMightContainThisPluginType (f.getFullPathName()))
  27104. {
  27105. isPlugin = true;
  27106. results.add (f.getFullPathName());
  27107. }
  27108. if (recursive && (! isPlugin) && f.isDirectory())
  27109. recursiveFileSearch (results, f, true);
  27110. }
  27111. }
  27112. const FileSearchPath VSTPluginFormat::getDefaultLocationsToSearch()
  27113. {
  27114. #if JUCE_MAC
  27115. return FileSearchPath ("~/Library/Audio/Plug-Ins/VST;/Library/Audio/Plug-Ins/VST");
  27116. #elif JUCE_WIN32
  27117. const String programFiles (File::getSpecialLocation (File::globalApplicationsDirectory).getFullPathName());
  27118. return FileSearchPath (programFiles + "\\Steinberg\\VstPlugins");
  27119. #elif JUCE_LINUX
  27120. return FileSearchPath ("/usr/lib/vst");
  27121. #endif
  27122. }
  27123. END_JUCE_NAMESPACE
  27124. #endif
  27125. #undef log
  27126. #endif
  27127. /********* End of inlined file: juce_VSTPluginFormat.cpp *********/
  27128. /********* End of inlined file: juce_VSTPluginFormat.mm *********/
  27129. /********* Start of inlined file: juce_AudioProcessor.cpp *********/
  27130. BEGIN_JUCE_NAMESPACE
  27131. AudioProcessor::AudioProcessor()
  27132. : playHead (0),
  27133. activeEditor (0),
  27134. sampleRate (0),
  27135. blockSize (0),
  27136. numInputChannels (0),
  27137. numOutputChannels (0),
  27138. latencySamples (0),
  27139. suspended (false),
  27140. nonRealtime (false)
  27141. {
  27142. }
  27143. AudioProcessor::~AudioProcessor()
  27144. {
  27145. // ooh, nasty - the editor should have been deleted before the filter
  27146. // that it refers to is deleted..
  27147. jassert (activeEditor == 0);
  27148. #ifdef JUCE_DEBUG
  27149. // This will fail if you've called beginParameterChangeGesture() for one
  27150. // or more parameters without having made a corresponding call to endParameterChangeGesture...
  27151. jassert (changingParams.countNumberOfSetBits() == 0);
  27152. #endif
  27153. }
  27154. void AudioProcessor::setPlayHead (AudioPlayHead* const newPlayHead) throw()
  27155. {
  27156. playHead = newPlayHead;
  27157. }
  27158. void AudioProcessor::addListener (AudioProcessorListener* const newListener) throw()
  27159. {
  27160. const ScopedLock sl (listenerLock);
  27161. listeners.addIfNotAlreadyThere (newListener);
  27162. }
  27163. void AudioProcessor::removeListener (AudioProcessorListener* const listenerToRemove) throw()
  27164. {
  27165. const ScopedLock sl (listenerLock);
  27166. listeners.removeValue (listenerToRemove);
  27167. }
  27168. void AudioProcessor::setPlayConfigDetails (const int numIns,
  27169. const int numOuts,
  27170. const double sampleRate_,
  27171. const int blockSize_) throw()
  27172. {
  27173. numInputChannels = numIns;
  27174. numOutputChannels = numOuts;
  27175. sampleRate = sampleRate_;
  27176. blockSize = blockSize_;
  27177. }
  27178. void AudioProcessor::setNonRealtime (const bool nonRealtime_) throw()
  27179. {
  27180. nonRealtime = nonRealtime_;
  27181. }
  27182. void AudioProcessor::setLatencySamples (const int newLatency)
  27183. {
  27184. if (latencySamples != newLatency)
  27185. {
  27186. latencySamples = newLatency;
  27187. updateHostDisplay();
  27188. }
  27189. }
  27190. void AudioProcessor::setParameterNotifyingHost (const int parameterIndex,
  27191. const float newValue)
  27192. {
  27193. setParameter (parameterIndex, newValue);
  27194. sendParamChangeMessageToListeners (parameterIndex, newValue);
  27195. }
  27196. void AudioProcessor::sendParamChangeMessageToListeners (const int parameterIndex, const float newValue)
  27197. {
  27198. jassert (((unsigned int) parameterIndex) < (unsigned int) getNumParameters());
  27199. for (int i = listeners.size(); --i >= 0;)
  27200. {
  27201. listenerLock.enter();
  27202. AudioProcessorListener* const l = (AudioProcessorListener*) listeners [i];
  27203. listenerLock.exit();
  27204. if (l != 0)
  27205. l->audioProcessorParameterChanged (this, parameterIndex, newValue);
  27206. }
  27207. }
  27208. void AudioProcessor::beginParameterChangeGesture (int parameterIndex)
  27209. {
  27210. jassert (((unsigned int) parameterIndex) < (unsigned int) getNumParameters());
  27211. #ifdef JUCE_DEBUG
  27212. // This means you've called beginParameterChangeGesture twice in succession without a matching
  27213. // call to endParameterChangeGesture. That might be fine in most hosts, but better to avoid doing it.
  27214. jassert (! changingParams [parameterIndex]);
  27215. changingParams.setBit (parameterIndex);
  27216. #endif
  27217. for (int i = listeners.size(); --i >= 0;)
  27218. {
  27219. listenerLock.enter();
  27220. AudioProcessorListener* const l = (AudioProcessorListener*) listeners [i];
  27221. listenerLock.exit();
  27222. if (l != 0)
  27223. l->audioProcessorParameterChangeGestureBegin (this, parameterIndex);
  27224. }
  27225. }
  27226. void AudioProcessor::endParameterChangeGesture (int parameterIndex)
  27227. {
  27228. jassert (((unsigned int) parameterIndex) < (unsigned int) getNumParameters());
  27229. #ifdef JUCE_DEBUG
  27230. // This means you've called endParameterChangeGesture without having previously called
  27231. // endParameterChangeGesture. That might be fine in most hosts, but better to keep the
  27232. // calls matched correctly.
  27233. jassert (changingParams [parameterIndex]);
  27234. changingParams.clearBit (parameterIndex);
  27235. #endif
  27236. for (int i = listeners.size(); --i >= 0;)
  27237. {
  27238. listenerLock.enter();
  27239. AudioProcessorListener* const l = (AudioProcessorListener*) listeners [i];
  27240. listenerLock.exit();
  27241. if (l != 0)
  27242. l->audioProcessorParameterChangeGestureEnd (this, parameterIndex);
  27243. }
  27244. }
  27245. void AudioProcessor::updateHostDisplay()
  27246. {
  27247. for (int i = listeners.size(); --i >= 0;)
  27248. {
  27249. listenerLock.enter();
  27250. AudioProcessorListener* const l = (AudioProcessorListener*) listeners [i];
  27251. listenerLock.exit();
  27252. if (l != 0)
  27253. l->audioProcessorChanged (this);
  27254. }
  27255. }
  27256. bool AudioProcessor::isParameterAutomatable (int /*parameterIndex*/) const
  27257. {
  27258. return true;
  27259. }
  27260. bool AudioProcessor::isMetaParameter (int /*parameterIndex*/) const
  27261. {
  27262. return false;
  27263. }
  27264. void AudioProcessor::suspendProcessing (const bool shouldBeSuspended)
  27265. {
  27266. const ScopedLock sl (callbackLock);
  27267. suspended = shouldBeSuspended;
  27268. }
  27269. void AudioProcessor::reset()
  27270. {
  27271. }
  27272. void AudioProcessor::editorBeingDeleted (AudioProcessorEditor* const editor) throw()
  27273. {
  27274. const ScopedLock sl (callbackLock);
  27275. jassert (activeEditor == editor);
  27276. if (activeEditor == editor)
  27277. activeEditor = 0;
  27278. }
  27279. AudioProcessorEditor* AudioProcessor::createEditorIfNeeded()
  27280. {
  27281. if (activeEditor != 0)
  27282. return activeEditor;
  27283. AudioProcessorEditor* const ed = createEditor();
  27284. if (ed != 0)
  27285. {
  27286. // you must give your editor comp a size before returning it..
  27287. jassert (ed->getWidth() > 0 && ed->getHeight() > 0);
  27288. const ScopedLock sl (callbackLock);
  27289. activeEditor = ed;
  27290. }
  27291. return ed;
  27292. }
  27293. void AudioProcessor::getCurrentProgramStateInformation (JUCE_NAMESPACE::MemoryBlock& destData)
  27294. {
  27295. getStateInformation (destData);
  27296. }
  27297. void AudioProcessor::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  27298. {
  27299. setStateInformation (data, sizeInBytes);
  27300. }
  27301. // magic number to identify memory blocks that we've stored as XML
  27302. const uint32 magicXmlNumber = 0x21324356;
  27303. void AudioProcessor::copyXmlToBinary (const XmlElement& xml,
  27304. JUCE_NAMESPACE::MemoryBlock& destData)
  27305. {
  27306. const String xmlString (xml.createDocument (String::empty, true, false));
  27307. const int stringLength = xmlString.length();
  27308. destData.setSize (stringLength + 10);
  27309. char* const d = (char*) destData.getData();
  27310. *(uint32*) d = swapIfBigEndian ((const uint32) magicXmlNumber);
  27311. *(uint32*) (d + 4) = swapIfBigEndian ((const uint32) stringLength);
  27312. xmlString.copyToBuffer (d + 8, stringLength);
  27313. }
  27314. XmlElement* AudioProcessor::getXmlFromBinary (const void* data,
  27315. const int sizeInBytes)
  27316. {
  27317. if (sizeInBytes > 8
  27318. && littleEndianInt ((const char*) data) == magicXmlNumber)
  27319. {
  27320. const uint32 stringLength = littleEndianInt (((const char*) data) + 4);
  27321. if (stringLength > 0)
  27322. {
  27323. XmlDocument doc (String (((const char*) data) + 8,
  27324. jmin ((sizeInBytes - 8), stringLength)));
  27325. return doc.getDocumentElement();
  27326. }
  27327. }
  27328. return 0;
  27329. }
  27330. void AudioProcessorListener::audioProcessorParameterChangeGestureBegin (AudioProcessor*, int)
  27331. {
  27332. }
  27333. void AudioProcessorListener::audioProcessorParameterChangeGestureEnd (AudioProcessor*, int)
  27334. {
  27335. }
  27336. END_JUCE_NAMESPACE
  27337. /********* End of inlined file: juce_AudioProcessor.cpp *********/
  27338. /********* Start of inlined file: juce_AudioProcessorEditor.cpp *********/
  27339. BEGIN_JUCE_NAMESPACE
  27340. AudioProcessorEditor::AudioProcessorEditor (AudioProcessor* const owner_)
  27341. : owner (owner_)
  27342. {
  27343. // the filter must be valid..
  27344. jassert (owner != 0);
  27345. }
  27346. AudioProcessorEditor::~AudioProcessorEditor()
  27347. {
  27348. // if this fails, then the wrapper hasn't called editorBeingDeleted() on the
  27349. // filter for some reason..
  27350. jassert (owner->getActiveEditor() != this);
  27351. }
  27352. END_JUCE_NAMESPACE
  27353. /********* End of inlined file: juce_AudioProcessorEditor.cpp *********/
  27354. /********* Start of inlined file: juce_AudioProcessorGraph.cpp *********/
  27355. BEGIN_JUCE_NAMESPACE
  27356. const int AudioProcessorGraph::midiChannelIndex = 0x1000;
  27357. AudioProcessorGraph::Node::Node (const uint32 id_,
  27358. AudioProcessor* const processor_) throw()
  27359. : id (id_),
  27360. processor (processor_),
  27361. isPrepared (false)
  27362. {
  27363. jassert (processor_ != 0);
  27364. }
  27365. AudioProcessorGraph::Node::~Node()
  27366. {
  27367. delete processor;
  27368. }
  27369. void AudioProcessorGraph::Node::prepare (const double sampleRate, const int blockSize,
  27370. AudioProcessorGraph* const graph)
  27371. {
  27372. if (! isPrepared)
  27373. {
  27374. isPrepared = true;
  27375. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  27376. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (processor);
  27377. if (ioProc != 0)
  27378. ioProc->setParentGraph (graph);
  27379. processor->setPlayConfigDetails (processor->getNumInputChannels(),
  27380. processor->getNumOutputChannels(),
  27381. sampleRate, blockSize);
  27382. processor->prepareToPlay (sampleRate, blockSize);
  27383. }
  27384. }
  27385. void AudioProcessorGraph::Node::unprepare()
  27386. {
  27387. if (isPrepared)
  27388. {
  27389. isPrepared = false;
  27390. processor->releaseResources();
  27391. }
  27392. }
  27393. AudioProcessorGraph::AudioProcessorGraph()
  27394. : lastNodeId (0),
  27395. renderingBuffers (1, 1),
  27396. currentAudioOutputBuffer (1, 1)
  27397. {
  27398. }
  27399. AudioProcessorGraph::~AudioProcessorGraph()
  27400. {
  27401. clearRenderingSequence();
  27402. clear();
  27403. }
  27404. const String AudioProcessorGraph::getName() const
  27405. {
  27406. return "Audio Graph";
  27407. }
  27408. void AudioProcessorGraph::clear()
  27409. {
  27410. nodes.clear();
  27411. connections.clear();
  27412. triggerAsyncUpdate();
  27413. }
  27414. AudioProcessorGraph::Node* AudioProcessorGraph::getNodeForId (const uint32 nodeId) const throw()
  27415. {
  27416. for (int i = nodes.size(); --i >= 0;)
  27417. if (nodes.getUnchecked(i)->id == nodeId)
  27418. return nodes.getUnchecked(i);
  27419. return 0;
  27420. }
  27421. AudioProcessorGraph::Node* AudioProcessorGraph::addNode (AudioProcessor* const newProcessor,
  27422. uint32 nodeId)
  27423. {
  27424. if (newProcessor == 0)
  27425. {
  27426. jassertfalse
  27427. return 0;
  27428. }
  27429. if (nodeId == 0)
  27430. {
  27431. nodeId = ++lastNodeId;
  27432. }
  27433. else
  27434. {
  27435. // you can't add a node with an id that already exists in the graph..
  27436. jassert (getNodeForId (nodeId) == 0);
  27437. removeNode (nodeId);
  27438. }
  27439. lastNodeId = nodeId;
  27440. Node* const n = new Node (nodeId, newProcessor);
  27441. nodes.add (n);
  27442. triggerAsyncUpdate();
  27443. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  27444. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (n->processor);
  27445. if (ioProc != 0)
  27446. ioProc->setParentGraph (this);
  27447. return n;
  27448. }
  27449. bool AudioProcessorGraph::removeNode (const uint32 nodeId)
  27450. {
  27451. disconnectNode (nodeId);
  27452. for (int i = nodes.size(); --i >= 0;)
  27453. {
  27454. if (nodes.getUnchecked(i)->id == nodeId)
  27455. {
  27456. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  27457. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (nodes.getUnchecked(i)->processor);
  27458. if (ioProc != 0)
  27459. ioProc->setParentGraph (0);
  27460. nodes.remove (i);
  27461. triggerAsyncUpdate();
  27462. return true;
  27463. }
  27464. }
  27465. return false;
  27466. }
  27467. const AudioProcessorGraph::Connection* AudioProcessorGraph::getConnectionBetween (const uint32 sourceNodeId,
  27468. const int sourceChannelIndex,
  27469. const uint32 destNodeId,
  27470. const int destChannelIndex) const throw()
  27471. {
  27472. for (int i = connections.size(); --i >= 0;)
  27473. {
  27474. const Connection* const c = connections.getUnchecked(i);
  27475. if (c->sourceNodeId == sourceNodeId
  27476. && c->destNodeId == destNodeId
  27477. && c->sourceChannelIndex == sourceChannelIndex
  27478. && c->destChannelIndex == destChannelIndex)
  27479. {
  27480. return c;
  27481. }
  27482. }
  27483. return 0;
  27484. }
  27485. bool AudioProcessorGraph::isConnected (const uint32 possibleSourceNodeId,
  27486. const uint32 possibleDestNodeId) const throw()
  27487. {
  27488. for (int i = connections.size(); --i >= 0;)
  27489. {
  27490. const Connection* const c = connections.getUnchecked(i);
  27491. if (c->sourceNodeId == possibleSourceNodeId
  27492. && c->destNodeId == possibleDestNodeId)
  27493. {
  27494. return true;
  27495. }
  27496. }
  27497. return false;
  27498. }
  27499. bool AudioProcessorGraph::canConnect (const uint32 sourceNodeId,
  27500. const int sourceChannelIndex,
  27501. const uint32 destNodeId,
  27502. const int destChannelIndex) const throw()
  27503. {
  27504. if (sourceChannelIndex < 0
  27505. || destChannelIndex < 0
  27506. || sourceNodeId == destNodeId
  27507. || (destChannelIndex == midiChannelIndex) != (sourceChannelIndex == midiChannelIndex))
  27508. return false;
  27509. const Node* const source = getNodeForId (sourceNodeId);
  27510. if (source == 0
  27511. || (sourceChannelIndex != midiChannelIndex && sourceChannelIndex >= source->processor->getNumOutputChannels())
  27512. || (sourceChannelIndex == midiChannelIndex && ! source->processor->producesMidi()))
  27513. return false;
  27514. const Node* const dest = getNodeForId (destNodeId);
  27515. if (dest == 0
  27516. || (destChannelIndex != midiChannelIndex && destChannelIndex >= dest->processor->getNumInputChannels())
  27517. || (destChannelIndex == midiChannelIndex && ! dest->processor->acceptsMidi()))
  27518. return false;
  27519. return getConnectionBetween (sourceNodeId, sourceChannelIndex,
  27520. destNodeId, destChannelIndex) == 0;
  27521. }
  27522. bool AudioProcessorGraph::addConnection (const uint32 sourceNodeId,
  27523. const int sourceChannelIndex,
  27524. const uint32 destNodeId,
  27525. const int destChannelIndex)
  27526. {
  27527. if (! canConnect (sourceNodeId, sourceChannelIndex, destNodeId, destChannelIndex))
  27528. return false;
  27529. Connection* const c = new Connection();
  27530. c->sourceNodeId = sourceNodeId;
  27531. c->sourceChannelIndex = sourceChannelIndex;
  27532. c->destNodeId = destNodeId;
  27533. c->destChannelIndex = destChannelIndex;
  27534. connections.add (c);
  27535. triggerAsyncUpdate();
  27536. return true;
  27537. }
  27538. void AudioProcessorGraph::removeConnection (const int index)
  27539. {
  27540. connections.remove (index);
  27541. triggerAsyncUpdate();
  27542. }
  27543. bool AudioProcessorGraph::removeConnection (const uint32 sourceNodeId, const int sourceChannelIndex,
  27544. const uint32 destNodeId, const int destChannelIndex)
  27545. {
  27546. bool doneAnything = false;
  27547. for (int i = connections.size(); --i >= 0;)
  27548. {
  27549. const Connection* const c = connections.getUnchecked(i);
  27550. if (c->sourceNodeId == sourceNodeId
  27551. && c->destNodeId == destNodeId
  27552. && c->sourceChannelIndex == sourceChannelIndex
  27553. && c->destChannelIndex == destChannelIndex)
  27554. {
  27555. removeConnection (i);
  27556. doneAnything = true;
  27557. triggerAsyncUpdate();
  27558. }
  27559. }
  27560. return doneAnything;
  27561. }
  27562. bool AudioProcessorGraph::disconnectNode (const uint32 nodeId)
  27563. {
  27564. bool doneAnything = false;
  27565. for (int i = connections.size(); --i >= 0;)
  27566. {
  27567. const Connection* const c = connections.getUnchecked(i);
  27568. if (c->sourceNodeId == nodeId || c->destNodeId == nodeId)
  27569. {
  27570. removeConnection (i);
  27571. doneAnything = true;
  27572. triggerAsyncUpdate();
  27573. }
  27574. }
  27575. return doneAnything;
  27576. }
  27577. bool AudioProcessorGraph::removeIllegalConnections()
  27578. {
  27579. bool doneAnything = false;
  27580. for (int i = connections.size(); --i >= 0;)
  27581. {
  27582. const Connection* const c = connections.getUnchecked(i);
  27583. const Node* const source = getNodeForId (c->sourceNodeId);
  27584. const Node* const dest = getNodeForId (c->destNodeId);
  27585. if (source == 0 || dest == 0
  27586. || (c->sourceChannelIndex != midiChannelIndex
  27587. && (((unsigned int) c->sourceChannelIndex) >= (unsigned int) source->processor->getNumOutputChannels()))
  27588. || (c->sourceChannelIndex == midiChannelIndex
  27589. && ! source->processor->producesMidi())
  27590. || (c->destChannelIndex != midiChannelIndex
  27591. && (((unsigned int) c->destChannelIndex) >= (unsigned int) dest->processor->getNumInputChannels()))
  27592. || (c->destChannelIndex == midiChannelIndex
  27593. && ! dest->processor->acceptsMidi()))
  27594. {
  27595. removeConnection (i);
  27596. doneAnything = true;
  27597. triggerAsyncUpdate();
  27598. }
  27599. }
  27600. return doneAnything;
  27601. }
  27602. namespace GraphRenderingOps
  27603. {
  27604. class AudioGraphRenderingOp
  27605. {
  27606. public:
  27607. AudioGraphRenderingOp() throw() {}
  27608. virtual ~AudioGraphRenderingOp() throw() {}
  27609. virtual void perform (AudioSampleBuffer& sharedBufferChans,
  27610. const OwnedArray <MidiBuffer>& sharedMidiBuffers,
  27611. const int numSamples) throw() = 0;
  27612. juce_UseDebuggingNewOperator
  27613. };
  27614. class ClearChannelOp : public AudioGraphRenderingOp
  27615. {
  27616. public:
  27617. ClearChannelOp (const int channelNum_) throw()
  27618. : channelNum (channelNum_)
  27619. {}
  27620. ~ClearChannelOp() throw() {}
  27621. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples) throw()
  27622. {
  27623. sharedBufferChans.clear (channelNum, 0, numSamples);
  27624. }
  27625. private:
  27626. const int channelNum;
  27627. ClearChannelOp (const ClearChannelOp&);
  27628. const ClearChannelOp& operator= (const ClearChannelOp&);
  27629. };
  27630. class CopyChannelOp : public AudioGraphRenderingOp
  27631. {
  27632. public:
  27633. CopyChannelOp (const int srcChannelNum_, const int dstChannelNum_) throw()
  27634. : srcChannelNum (srcChannelNum_),
  27635. dstChannelNum (dstChannelNum_)
  27636. {}
  27637. ~CopyChannelOp() throw() {}
  27638. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples) throw()
  27639. {
  27640. sharedBufferChans.copyFrom (dstChannelNum, 0, sharedBufferChans, srcChannelNum, 0, numSamples);
  27641. }
  27642. private:
  27643. const int srcChannelNum, dstChannelNum;
  27644. CopyChannelOp (const CopyChannelOp&);
  27645. const CopyChannelOp& operator= (const CopyChannelOp&);
  27646. };
  27647. class AddChannelOp : public AudioGraphRenderingOp
  27648. {
  27649. public:
  27650. AddChannelOp (const int srcChannelNum_, const int dstChannelNum_) throw()
  27651. : srcChannelNum (srcChannelNum_),
  27652. dstChannelNum (dstChannelNum_)
  27653. {}
  27654. ~AddChannelOp() throw() {}
  27655. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples) throw()
  27656. {
  27657. sharedBufferChans.addFrom (dstChannelNum, 0, sharedBufferChans, srcChannelNum, 0, numSamples);
  27658. }
  27659. private:
  27660. const int srcChannelNum, dstChannelNum;
  27661. AddChannelOp (const AddChannelOp&);
  27662. const AddChannelOp& operator= (const AddChannelOp&);
  27663. };
  27664. class ClearMidiBufferOp : public AudioGraphRenderingOp
  27665. {
  27666. public:
  27667. ClearMidiBufferOp (const int bufferNum_) throw()
  27668. : bufferNum (bufferNum_)
  27669. {}
  27670. ~ClearMidiBufferOp() throw() {}
  27671. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int) throw()
  27672. {
  27673. sharedMidiBuffers.getUnchecked (bufferNum)->clear();
  27674. }
  27675. private:
  27676. const int bufferNum;
  27677. ClearMidiBufferOp (const ClearMidiBufferOp&);
  27678. const ClearMidiBufferOp& operator= (const ClearMidiBufferOp&);
  27679. };
  27680. class CopyMidiBufferOp : public AudioGraphRenderingOp
  27681. {
  27682. public:
  27683. CopyMidiBufferOp (const int srcBufferNum_, const int dstBufferNum_) throw()
  27684. : srcBufferNum (srcBufferNum_),
  27685. dstBufferNum (dstBufferNum_)
  27686. {}
  27687. ~CopyMidiBufferOp() throw() {}
  27688. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int) throw()
  27689. {
  27690. *sharedMidiBuffers.getUnchecked (dstBufferNum) = *sharedMidiBuffers.getUnchecked (srcBufferNum);
  27691. }
  27692. private:
  27693. const int srcBufferNum, dstBufferNum;
  27694. CopyMidiBufferOp (const CopyMidiBufferOp&);
  27695. const CopyMidiBufferOp& operator= (const CopyMidiBufferOp&);
  27696. };
  27697. class AddMidiBufferOp : public AudioGraphRenderingOp
  27698. {
  27699. public:
  27700. AddMidiBufferOp (const int srcBufferNum_, const int dstBufferNum_) throw()
  27701. : srcBufferNum (srcBufferNum_),
  27702. dstBufferNum (dstBufferNum_)
  27703. {}
  27704. ~AddMidiBufferOp() throw() {}
  27705. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int numSamples) throw()
  27706. {
  27707. sharedMidiBuffers.getUnchecked (dstBufferNum)
  27708. ->addEvents (*sharedMidiBuffers.getUnchecked (srcBufferNum), 0, numSamples, 0);
  27709. }
  27710. private:
  27711. const int srcBufferNum, dstBufferNum;
  27712. AddMidiBufferOp (const AddMidiBufferOp&);
  27713. const AddMidiBufferOp& operator= (const AddMidiBufferOp&);
  27714. };
  27715. class ProcessBufferOp : public AudioGraphRenderingOp
  27716. {
  27717. public:
  27718. ProcessBufferOp (const AudioProcessorGraph::Node::Ptr& node_,
  27719. const Array <int>& audioChannelsToUse_,
  27720. const int totalChans_,
  27721. const int midiBufferToUse_) throw()
  27722. : node (node_),
  27723. processor (node_->processor),
  27724. audioChannelsToUse (audioChannelsToUse_),
  27725. totalChans (jmax (1, totalChans_)),
  27726. midiBufferToUse (midiBufferToUse_)
  27727. {
  27728. channels = (float**) juce_calloc (sizeof (float*) * totalChans);
  27729. while (audioChannelsToUse.size() < totalChans)
  27730. audioChannelsToUse.add (0);
  27731. }
  27732. ~ProcessBufferOp() throw()
  27733. {
  27734. juce_free (channels);
  27735. }
  27736. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int numSamples) throw()
  27737. {
  27738. for (int i = totalChans; --i >= 0;)
  27739. channels[i] = sharedBufferChans.getSampleData (audioChannelsToUse.getUnchecked (i), 0);
  27740. AudioSampleBuffer buffer (channels, totalChans, numSamples);
  27741. processor->processBlock (buffer, *sharedMidiBuffers.getUnchecked (midiBufferToUse));
  27742. }
  27743. const AudioProcessorGraph::Node::Ptr node;
  27744. AudioProcessor* const processor;
  27745. private:
  27746. Array <int> audioChannelsToUse;
  27747. float** channels;
  27748. int totalChans;
  27749. int midiBufferToUse;
  27750. ProcessBufferOp (const ProcessBufferOp&);
  27751. const ProcessBufferOp& operator= (const ProcessBufferOp&);
  27752. };
  27753. /** Used to calculate the correct sequence of rendering ops needed, based on
  27754. the best re-use of shared buffers at each stage.
  27755. */
  27756. class RenderingOpSequenceCalculator
  27757. {
  27758. public:
  27759. RenderingOpSequenceCalculator (AudioProcessorGraph& graph_,
  27760. const VoidArray& orderedNodes_,
  27761. VoidArray& renderingOps)
  27762. : graph (graph_),
  27763. orderedNodes (orderedNodes_)
  27764. {
  27765. nodeIds.add (-2); // first buffer is read-only zeros
  27766. channels.add (0);
  27767. midiNodeIds.add (-2);
  27768. for (int i = 0; i < orderedNodes.size(); ++i)
  27769. {
  27770. createRenderingOpsForNode ((AudioProcessorGraph::Node*) orderedNodes.getUnchecked(i),
  27771. renderingOps, i);
  27772. markAnyUnusedBuffersAsFree (i);
  27773. }
  27774. }
  27775. int getNumBuffersNeeded() const throw() { return nodeIds.size(); }
  27776. int getNumMidiBuffersNeeded() const throw() { return midiNodeIds.size(); }
  27777. juce_UseDebuggingNewOperator
  27778. private:
  27779. AudioProcessorGraph& graph;
  27780. const VoidArray& orderedNodes;
  27781. Array <int> nodeIds, channels, midiNodeIds;
  27782. void createRenderingOpsForNode (AudioProcessorGraph::Node* const node,
  27783. VoidArray& renderingOps,
  27784. const int ourRenderingIndex)
  27785. {
  27786. const int numIns = node->processor->getNumInputChannels();
  27787. const int numOuts = node->processor->getNumOutputChannels();
  27788. const int totalChans = jmax (numIns, numOuts);
  27789. Array <int> audioChannelsToUse;
  27790. int midiBufferToUse = -1;
  27791. for (int inputChan = 0; inputChan < numIns; ++inputChan)
  27792. {
  27793. // get a list of all the inputs to this node
  27794. Array <int> sourceNodes, sourceOutputChans;
  27795. for (int i = graph.getNumConnections(); --i >= 0;)
  27796. {
  27797. const AudioProcessorGraph::Connection* const c = graph.getConnection (i);
  27798. if (c->destNodeId == node->id && c->destChannelIndex == inputChan)
  27799. {
  27800. sourceNodes.add (c->sourceNodeId);
  27801. sourceOutputChans.add (c->sourceChannelIndex);
  27802. }
  27803. }
  27804. int bufIndex = -1;
  27805. if (sourceNodes.size() == 0)
  27806. {
  27807. // unconnected input channel
  27808. if (inputChan >= numOuts)
  27809. {
  27810. bufIndex = getReadOnlyEmptyBuffer();
  27811. jassert (bufIndex >= 0);
  27812. }
  27813. else
  27814. {
  27815. bufIndex = getFreeBuffer (false);
  27816. renderingOps.add (new ClearChannelOp (bufIndex));
  27817. }
  27818. }
  27819. else if (sourceNodes.size() == 1)
  27820. {
  27821. // channel with a straightforward single input..
  27822. const int srcNode = sourceNodes.getUnchecked(0);
  27823. const int srcChan = sourceOutputChans.getUnchecked(0);
  27824. bufIndex = getBufferContaining (srcNode, srcChan);
  27825. if (bufIndex < 0)
  27826. {
  27827. // if not found, this is probably a feedback loop
  27828. bufIndex = getReadOnlyEmptyBuffer();
  27829. jassert (bufIndex >= 0);
  27830. }
  27831. if (inputChan < numOuts
  27832. && isBufferNeededLater (ourRenderingIndex,
  27833. inputChan,
  27834. srcNode, srcChan))
  27835. {
  27836. // can't mess up this channel because it's needed later by another node, so we
  27837. // need to use a copy of it..
  27838. const int newFreeBuffer = getFreeBuffer (false);
  27839. renderingOps.add (new CopyChannelOp (bufIndex, newFreeBuffer));
  27840. bufIndex = newFreeBuffer;
  27841. }
  27842. }
  27843. else
  27844. {
  27845. // channel with a mix of several inputs..
  27846. // try to find a re-usable channel from our inputs..
  27847. int reusableInputIndex = -1;
  27848. for (int i = 0; i < sourceNodes.size(); ++i)
  27849. {
  27850. const int sourceBufIndex = getBufferContaining (sourceNodes.getUnchecked(i),
  27851. sourceOutputChans.getUnchecked(i));
  27852. if (sourceBufIndex >= 0
  27853. && ! isBufferNeededLater (ourRenderingIndex,
  27854. inputChan,
  27855. sourceNodes.getUnchecked(i),
  27856. sourceOutputChans.getUnchecked(i)))
  27857. {
  27858. // we've found one of our input chans that can be re-used..
  27859. reusableInputIndex = i;
  27860. bufIndex = sourceBufIndex;
  27861. break;
  27862. }
  27863. }
  27864. if (reusableInputIndex < 0)
  27865. {
  27866. // can't re-use any of our input chans, so get a new one and copy everything into it..
  27867. bufIndex = getFreeBuffer (false);
  27868. jassert (bufIndex != 0);
  27869. const int srcIndex = getBufferContaining (sourceNodes.getUnchecked (0),
  27870. sourceOutputChans.getUnchecked (0));
  27871. if (srcIndex < 0)
  27872. {
  27873. // if not found, this is probably a feedback loop
  27874. renderingOps.add (new ClearChannelOp (bufIndex));
  27875. }
  27876. else
  27877. {
  27878. renderingOps.add (new CopyChannelOp (srcIndex, bufIndex));
  27879. }
  27880. reusableInputIndex = 0;
  27881. }
  27882. for (int j = 0; j < sourceNodes.size(); ++j)
  27883. {
  27884. if (j != reusableInputIndex)
  27885. {
  27886. const int srcIndex = getBufferContaining (sourceNodes.getUnchecked(j),
  27887. sourceOutputChans.getUnchecked(j));
  27888. if (srcIndex >= 0)
  27889. renderingOps.add (new AddChannelOp (srcIndex, bufIndex));
  27890. }
  27891. }
  27892. }
  27893. jassert (bufIndex >= 0);
  27894. audioChannelsToUse.add (bufIndex);
  27895. if (inputChan < numOuts)
  27896. markBufferAsContaining (bufIndex, node->id, inputChan);
  27897. }
  27898. for (int outputChan = numIns; outputChan < numOuts; ++outputChan)
  27899. {
  27900. const int bufIndex = getFreeBuffer (false);
  27901. jassert (bufIndex != 0);
  27902. audioChannelsToUse.add (bufIndex);
  27903. markBufferAsContaining (bufIndex, node->id, outputChan);
  27904. }
  27905. // Now the same thing for midi..
  27906. Array <int> midiSourceNodes;
  27907. for (int i = graph.getNumConnections(); --i >= 0;)
  27908. {
  27909. const AudioProcessorGraph::Connection* const c = graph.getConnection (i);
  27910. if (c->destNodeId == node->id && c->destChannelIndex == AudioProcessorGraph::midiChannelIndex)
  27911. midiSourceNodes.add (c->sourceNodeId);
  27912. }
  27913. if (midiSourceNodes.size() == 0)
  27914. {
  27915. // No midi inputs..
  27916. midiBufferToUse = getFreeBuffer (true); // need to pick a buffer even if the processor doesn't use midi
  27917. if (node->processor->acceptsMidi() || node->processor->producesMidi())
  27918. renderingOps.add (new ClearMidiBufferOp (midiBufferToUse));
  27919. }
  27920. else if (midiSourceNodes.size() == 1)
  27921. {
  27922. // One midi input..
  27923. midiBufferToUse = getBufferContaining (midiSourceNodes.getUnchecked(0),
  27924. AudioProcessorGraph::midiChannelIndex);
  27925. if (midiBufferToUse >= 0)
  27926. {
  27927. if (isBufferNeededLater (ourRenderingIndex,
  27928. AudioProcessorGraph::midiChannelIndex,
  27929. midiSourceNodes.getUnchecked(0),
  27930. AudioProcessorGraph::midiChannelIndex))
  27931. {
  27932. // can't mess up this channel because it's needed later by another node, so we
  27933. // need to use a copy of it..
  27934. const int newFreeBuffer = getFreeBuffer (true);
  27935. renderingOps.add (new CopyMidiBufferOp (midiBufferToUse, newFreeBuffer));
  27936. midiBufferToUse = newFreeBuffer;
  27937. }
  27938. }
  27939. else
  27940. {
  27941. // probably a feedback loop, so just use an empty one..
  27942. midiBufferToUse = getFreeBuffer (true); // need to pick a buffer even if the processor doesn't use midi
  27943. }
  27944. }
  27945. else
  27946. {
  27947. // More than one midi input being mixed..
  27948. int reusableInputIndex = -1;
  27949. for (int i = 0; i < midiSourceNodes.size(); ++i)
  27950. {
  27951. const int sourceBufIndex = getBufferContaining (midiSourceNodes.getUnchecked(i),
  27952. AudioProcessorGraph::midiChannelIndex);
  27953. if (sourceBufIndex >= 0
  27954. && ! isBufferNeededLater (ourRenderingIndex,
  27955. AudioProcessorGraph::midiChannelIndex,
  27956. midiSourceNodes.getUnchecked(i),
  27957. AudioProcessorGraph::midiChannelIndex))
  27958. {
  27959. // we've found one of our input buffers that can be re-used..
  27960. reusableInputIndex = i;
  27961. midiBufferToUse = sourceBufIndex;
  27962. break;
  27963. }
  27964. }
  27965. if (reusableInputIndex < 0)
  27966. {
  27967. // can't re-use any of our input buffers, so get a new one and copy everything into it..
  27968. midiBufferToUse = getFreeBuffer (true);
  27969. jassert (midiBufferToUse >= 0);
  27970. const int srcIndex = getBufferContaining (midiSourceNodes.getUnchecked(0),
  27971. AudioProcessorGraph::midiChannelIndex);
  27972. if (srcIndex >= 0)
  27973. renderingOps.add (new CopyMidiBufferOp (srcIndex, midiBufferToUse));
  27974. else
  27975. renderingOps.add (new ClearMidiBufferOp (midiBufferToUse));
  27976. reusableInputIndex = 0;
  27977. }
  27978. for (int j = 0; j < midiSourceNodes.size(); ++j)
  27979. {
  27980. if (j != reusableInputIndex)
  27981. {
  27982. const int srcIndex = getBufferContaining (midiSourceNodes.getUnchecked(j),
  27983. AudioProcessorGraph::midiChannelIndex);
  27984. if (srcIndex >= 0)
  27985. renderingOps.add (new AddMidiBufferOp (srcIndex, midiBufferToUse));
  27986. }
  27987. }
  27988. }
  27989. if (node->processor->producesMidi())
  27990. markBufferAsContaining (midiBufferToUse, node->id,
  27991. AudioProcessorGraph::midiChannelIndex);
  27992. renderingOps.add (new ProcessBufferOp (node, audioChannelsToUse,
  27993. totalChans, midiBufferToUse));
  27994. }
  27995. int getFreeBuffer (const bool forMidi)
  27996. {
  27997. if (forMidi)
  27998. {
  27999. for (int i = 1; i < midiNodeIds.size(); ++i)
  28000. if (midiNodeIds.getUnchecked(i) < 0)
  28001. return i;
  28002. midiNodeIds.add (-1);
  28003. return midiNodeIds.size() - 1;
  28004. }
  28005. else
  28006. {
  28007. for (int i = 1; i < nodeIds.size(); ++i)
  28008. if (nodeIds.getUnchecked(i) < 0)
  28009. return i;
  28010. nodeIds.add (-1);
  28011. channels.add (0);
  28012. return nodeIds.size() - 1;
  28013. }
  28014. }
  28015. int getReadOnlyEmptyBuffer() const throw()
  28016. {
  28017. return 0;
  28018. }
  28019. int getBufferContaining (const int nodeId, const int outputChannel) const throw()
  28020. {
  28021. if (outputChannel == AudioProcessorGraph::midiChannelIndex)
  28022. {
  28023. for (int i = midiNodeIds.size(); --i >= 0;)
  28024. if (midiNodeIds.getUnchecked(i) == nodeId)
  28025. return i;
  28026. }
  28027. else
  28028. {
  28029. for (int i = nodeIds.size(); --i >= 0;)
  28030. if (nodeIds.getUnchecked(i) == nodeId
  28031. && channels.getUnchecked(i) == outputChannel)
  28032. return i;
  28033. }
  28034. return -1;
  28035. }
  28036. void markAnyUnusedBuffersAsFree (const int stepIndex)
  28037. {
  28038. int i;
  28039. for (i = 0; i < nodeIds.size(); ++i)
  28040. {
  28041. if (nodeIds.getUnchecked(i) >= 0
  28042. && ! isBufferNeededLater (stepIndex, -1,
  28043. nodeIds.getUnchecked(i),
  28044. channels.getUnchecked(i)))
  28045. {
  28046. nodeIds.set (i, -1);
  28047. }
  28048. }
  28049. for (i = 0; i < midiNodeIds.size(); ++i)
  28050. {
  28051. if (midiNodeIds.getUnchecked(i) >= 0
  28052. && ! isBufferNeededLater (stepIndex, -1,
  28053. midiNodeIds.getUnchecked(i),
  28054. AudioProcessorGraph::midiChannelIndex))
  28055. {
  28056. midiNodeIds.set (i, -1);
  28057. }
  28058. }
  28059. }
  28060. bool isBufferNeededLater (int stepIndexToSearchFrom,
  28061. int inputChannelOfIndexToIgnore,
  28062. const int nodeId,
  28063. const int outputChanIndex) const throw()
  28064. {
  28065. while (stepIndexToSearchFrom < orderedNodes.size())
  28066. {
  28067. const AudioProcessorGraph::Node* const node = (const AudioProcessorGraph::Node*) orderedNodes.getUnchecked (stepIndexToSearchFrom);
  28068. if (outputChanIndex == AudioProcessorGraph::midiChannelIndex)
  28069. {
  28070. if (inputChannelOfIndexToIgnore != AudioProcessorGraph::midiChannelIndex
  28071. && graph.getConnectionBetween (nodeId, AudioProcessorGraph::midiChannelIndex,
  28072. node->id, AudioProcessorGraph::midiChannelIndex) != 0)
  28073. return true;
  28074. }
  28075. else
  28076. {
  28077. for (int i = 0; i < node->processor->getNumInputChannels(); ++i)
  28078. if (i != inputChannelOfIndexToIgnore
  28079. && graph.getConnectionBetween (nodeId, outputChanIndex,
  28080. node->id, i) != 0)
  28081. return true;
  28082. }
  28083. inputChannelOfIndexToIgnore = -1;
  28084. ++stepIndexToSearchFrom;
  28085. }
  28086. return false;
  28087. }
  28088. void markBufferAsContaining (int bufferNum, int nodeId, int outputIndex)
  28089. {
  28090. if (outputIndex == AudioProcessorGraph::midiChannelIndex)
  28091. {
  28092. jassert (bufferNum > 0 && bufferNum < midiNodeIds.size());
  28093. midiNodeIds.set (bufferNum, nodeId);
  28094. }
  28095. else
  28096. {
  28097. jassert (bufferNum >= 0 && bufferNum < nodeIds.size());
  28098. nodeIds.set (bufferNum, nodeId);
  28099. channels.set (bufferNum, outputIndex);
  28100. }
  28101. }
  28102. RenderingOpSequenceCalculator (const RenderingOpSequenceCalculator&);
  28103. const RenderingOpSequenceCalculator& operator= (const RenderingOpSequenceCalculator&);
  28104. };
  28105. }
  28106. void AudioProcessorGraph::clearRenderingSequence()
  28107. {
  28108. const ScopedLock sl (renderLock);
  28109. for (int i = renderingOps.size(); --i >= 0;)
  28110. {
  28111. GraphRenderingOps::AudioGraphRenderingOp* const r
  28112. = (GraphRenderingOps::AudioGraphRenderingOp*) renderingOps.getUnchecked(i);
  28113. renderingOps.remove (i);
  28114. delete r;
  28115. }
  28116. }
  28117. bool AudioProcessorGraph::isAnInputTo (const uint32 possibleInputId,
  28118. const uint32 possibleDestinationId,
  28119. const int recursionCheck) const throw()
  28120. {
  28121. if (recursionCheck > 0)
  28122. {
  28123. for (int i = connections.size(); --i >= 0;)
  28124. {
  28125. const AudioProcessorGraph::Connection* const c = connections.getUnchecked (i);
  28126. if (c->destNodeId == possibleDestinationId
  28127. && (c->sourceNodeId == possibleInputId
  28128. || isAnInputTo (possibleInputId, c->sourceNodeId, recursionCheck - 1)))
  28129. return true;
  28130. }
  28131. }
  28132. return false;
  28133. }
  28134. void AudioProcessorGraph::buildRenderingSequence()
  28135. {
  28136. VoidArray newRenderingOps;
  28137. int numRenderingBuffersNeeded = 2;
  28138. int numMidiBuffersNeeded = 1;
  28139. {
  28140. MessageManagerLock mml;
  28141. VoidArray orderedNodes;
  28142. int i;
  28143. for (i = 0; i < nodes.size(); ++i)
  28144. {
  28145. Node* const node = nodes.getUnchecked(i);
  28146. node->prepare (getSampleRate(), getBlockSize(), this);
  28147. int j = 0;
  28148. for (; j < orderedNodes.size(); ++j)
  28149. if (isAnInputTo (node->id,
  28150. ((Node*) orderedNodes.getUnchecked (j))->id,
  28151. nodes.size() + 1))
  28152. break;
  28153. orderedNodes.insert (j, node);
  28154. }
  28155. GraphRenderingOps::RenderingOpSequenceCalculator calculator (*this, orderedNodes, newRenderingOps);
  28156. numRenderingBuffersNeeded = calculator.getNumBuffersNeeded();
  28157. numMidiBuffersNeeded = calculator.getNumMidiBuffersNeeded();
  28158. }
  28159. VoidArray oldRenderingOps (renderingOps);
  28160. {
  28161. // swap over to the new rendering sequence..
  28162. const ScopedLock sl (renderLock);
  28163. renderingBuffers.setSize (numRenderingBuffersNeeded, getBlockSize());
  28164. renderingBuffers.clear();
  28165. for (int i = midiBuffers.size(); --i >= 0;)
  28166. midiBuffers.getUnchecked(i)->clear();
  28167. while (midiBuffers.size() < numMidiBuffersNeeded)
  28168. midiBuffers.add (new MidiBuffer());
  28169. renderingOps = newRenderingOps;
  28170. }
  28171. for (int i = oldRenderingOps.size(); --i >= 0;)
  28172. delete (GraphRenderingOps::AudioGraphRenderingOp*) oldRenderingOps.getUnchecked(i);
  28173. }
  28174. void AudioProcessorGraph::handleAsyncUpdate()
  28175. {
  28176. buildRenderingSequence();
  28177. }
  28178. void AudioProcessorGraph::prepareToPlay (double /*sampleRate*/, int estimatedSamplesPerBlock)
  28179. {
  28180. currentAudioInputBuffer = 0;
  28181. currentAudioOutputBuffer.setSize (jmax (1, getNumOutputChannels()), estimatedSamplesPerBlock);
  28182. currentMidiInputBuffer = 0;
  28183. currentMidiOutputBuffer.clear();
  28184. clearRenderingSequence();
  28185. buildRenderingSequence();
  28186. }
  28187. void AudioProcessorGraph::releaseResources()
  28188. {
  28189. for (int i = 0; i < nodes.size(); ++i)
  28190. nodes.getUnchecked(i)->unprepare();
  28191. renderingBuffers.setSize (1, 1);
  28192. midiBuffers.clear();
  28193. currentAudioInputBuffer = 0;
  28194. currentAudioOutputBuffer.setSize (1, 1);
  28195. currentMidiInputBuffer = 0;
  28196. currentMidiOutputBuffer.clear();
  28197. }
  28198. void AudioProcessorGraph::processBlock (AudioSampleBuffer& buffer, MidiBuffer& midiMessages)
  28199. {
  28200. const int numSamples = buffer.getNumSamples();
  28201. const ScopedLock sl (renderLock);
  28202. currentAudioInputBuffer = &buffer;
  28203. currentAudioOutputBuffer.setSize (jmax (1, buffer.getNumChannels()), numSamples);
  28204. currentAudioOutputBuffer.clear();
  28205. currentMidiInputBuffer = &midiMessages;
  28206. currentMidiOutputBuffer.clear();
  28207. int i;
  28208. for (i = 0; i < renderingOps.size(); ++i)
  28209. {
  28210. GraphRenderingOps::AudioGraphRenderingOp* const op
  28211. = (GraphRenderingOps::AudioGraphRenderingOp*) renderingOps.getUnchecked(i);
  28212. op->perform (renderingBuffers, midiBuffers, numSamples);
  28213. }
  28214. for (i = 0; i < buffer.getNumChannels(); ++i)
  28215. buffer.copyFrom (i, 0, currentAudioOutputBuffer, i, 0, numSamples);
  28216. }
  28217. const String AudioProcessorGraph::getInputChannelName (const int channelIndex) const
  28218. {
  28219. return "Input " + String (channelIndex + 1);
  28220. }
  28221. const String AudioProcessorGraph::getOutputChannelName (const int channelIndex) const
  28222. {
  28223. return "Output " + String (channelIndex + 1);
  28224. }
  28225. bool AudioProcessorGraph::isInputChannelStereoPair (int /*index*/) const
  28226. {
  28227. return true;
  28228. }
  28229. bool AudioProcessorGraph::isOutputChannelStereoPair (int /*index*/) const
  28230. {
  28231. return true;
  28232. }
  28233. bool AudioProcessorGraph::acceptsMidi() const
  28234. {
  28235. return true;
  28236. }
  28237. bool AudioProcessorGraph::producesMidi() const
  28238. {
  28239. return true;
  28240. }
  28241. void AudioProcessorGraph::getStateInformation (JUCE_NAMESPACE::MemoryBlock& /*destData*/)
  28242. {
  28243. }
  28244. void AudioProcessorGraph::setStateInformation (const void* /*data*/, int /*sizeInBytes*/)
  28245. {
  28246. }
  28247. AudioProcessorGraph::AudioGraphIOProcessor::AudioGraphIOProcessor (const IODeviceType type_)
  28248. : type (type_),
  28249. graph (0)
  28250. {
  28251. }
  28252. AudioProcessorGraph::AudioGraphIOProcessor::~AudioGraphIOProcessor()
  28253. {
  28254. }
  28255. const String AudioProcessorGraph::AudioGraphIOProcessor::getName() const
  28256. {
  28257. switch (type)
  28258. {
  28259. case audioOutputNode:
  28260. return "Audio Output";
  28261. case audioInputNode:
  28262. return "Audio Input";
  28263. case midiOutputNode:
  28264. return "Midi Output";
  28265. case midiInputNode:
  28266. return "Midi Input";
  28267. default:
  28268. break;
  28269. }
  28270. return String::empty;
  28271. }
  28272. void AudioProcessorGraph::AudioGraphIOProcessor::fillInPluginDescription (PluginDescription& d) const
  28273. {
  28274. d.name = getName();
  28275. d.uid = d.name.hashCode();
  28276. d.category = "I/O devices";
  28277. d.pluginFormatName = "Internal";
  28278. d.manufacturerName = "Raw Material Software";
  28279. d.version = "1.0";
  28280. d.isInstrument = false;
  28281. d.numInputChannels = getNumInputChannels();
  28282. if (type == audioOutputNode && graph != 0)
  28283. d.numInputChannels = graph->getNumInputChannels();
  28284. d.numOutputChannels = getNumOutputChannels();
  28285. if (type == audioInputNode && graph != 0)
  28286. d.numOutputChannels = graph->getNumOutputChannels();
  28287. }
  28288. void AudioProcessorGraph::AudioGraphIOProcessor::prepareToPlay (double, int)
  28289. {
  28290. jassert (graph != 0);
  28291. }
  28292. void AudioProcessorGraph::AudioGraphIOProcessor::releaseResources()
  28293. {
  28294. }
  28295. void AudioProcessorGraph::AudioGraphIOProcessor::processBlock (AudioSampleBuffer& buffer,
  28296. MidiBuffer& midiMessages)
  28297. {
  28298. jassert (graph != 0);
  28299. switch (type)
  28300. {
  28301. case audioOutputNode:
  28302. {
  28303. for (int i = jmin (graph->currentAudioOutputBuffer.getNumChannels(),
  28304. buffer.getNumChannels()); --i >= 0;)
  28305. {
  28306. graph->currentAudioOutputBuffer.addFrom (i, 0, buffer, i, 0, buffer.getNumSamples());
  28307. }
  28308. break;
  28309. }
  28310. case audioInputNode:
  28311. {
  28312. for (int i = jmin (graph->currentAudioInputBuffer->getNumChannels(),
  28313. buffer.getNumChannels()); --i >= 0;)
  28314. {
  28315. buffer.copyFrom (i, 0, *graph->currentAudioInputBuffer, i, 0, buffer.getNumSamples());
  28316. }
  28317. break;
  28318. }
  28319. case midiOutputNode:
  28320. graph->currentMidiOutputBuffer.addEvents (midiMessages, 0, buffer.getNumSamples(), 0);
  28321. break;
  28322. case midiInputNode:
  28323. midiMessages.addEvents (*graph->currentMidiInputBuffer, 0, buffer.getNumSamples(), 0);
  28324. break;
  28325. default:
  28326. break;
  28327. }
  28328. }
  28329. bool AudioProcessorGraph::AudioGraphIOProcessor::acceptsMidi() const
  28330. {
  28331. return type == midiOutputNode;
  28332. }
  28333. bool AudioProcessorGraph::AudioGraphIOProcessor::producesMidi() const
  28334. {
  28335. return type == midiInputNode;
  28336. }
  28337. const String AudioProcessorGraph::AudioGraphIOProcessor::getInputChannelName (const int channelIndex) const
  28338. {
  28339. switch (type)
  28340. {
  28341. case audioOutputNode:
  28342. return "Output " + String (channelIndex + 1);
  28343. case midiOutputNode:
  28344. return "Midi Output";
  28345. default:
  28346. break;
  28347. }
  28348. return String::empty;
  28349. }
  28350. const String AudioProcessorGraph::AudioGraphIOProcessor::getOutputChannelName (const int channelIndex) const
  28351. {
  28352. switch (type)
  28353. {
  28354. case audioInputNode:
  28355. return "Input " + String (channelIndex + 1);
  28356. case midiInputNode:
  28357. return "Midi Input";
  28358. default:
  28359. break;
  28360. }
  28361. return String::empty;
  28362. }
  28363. bool AudioProcessorGraph::AudioGraphIOProcessor::isInputChannelStereoPair (int /*index*/) const
  28364. {
  28365. return type == audioInputNode || type == audioOutputNode;
  28366. }
  28367. bool AudioProcessorGraph::AudioGraphIOProcessor::isOutputChannelStereoPair (int index) const
  28368. {
  28369. return isInputChannelStereoPair (index);
  28370. }
  28371. bool AudioProcessorGraph::AudioGraphIOProcessor::isInput() const throw()
  28372. {
  28373. return type == audioInputNode || type == midiInputNode;
  28374. }
  28375. bool AudioProcessorGraph::AudioGraphIOProcessor::isOutput() const throw()
  28376. {
  28377. return type == audioOutputNode || type == midiOutputNode;
  28378. }
  28379. AudioProcessorEditor* AudioProcessorGraph::AudioGraphIOProcessor::createEditor()
  28380. {
  28381. return 0;
  28382. }
  28383. int AudioProcessorGraph::AudioGraphIOProcessor::getNumParameters() { return 0; }
  28384. const String AudioProcessorGraph::AudioGraphIOProcessor::getParameterName (int) { return String::empty; }
  28385. float AudioProcessorGraph::AudioGraphIOProcessor::getParameter (int) { return 0.0f; }
  28386. const String AudioProcessorGraph::AudioGraphIOProcessor::getParameterText (int) { return String::empty; }
  28387. void AudioProcessorGraph::AudioGraphIOProcessor::setParameter (int, float) { }
  28388. int AudioProcessorGraph::AudioGraphIOProcessor::getNumPrograms() { return 0; }
  28389. int AudioProcessorGraph::AudioGraphIOProcessor::getCurrentProgram() { return 0; }
  28390. void AudioProcessorGraph::AudioGraphIOProcessor::setCurrentProgram (int) { }
  28391. const String AudioProcessorGraph::AudioGraphIOProcessor::getProgramName (int) { return String::empty; }
  28392. void AudioProcessorGraph::AudioGraphIOProcessor::changeProgramName (int, const String&) { }
  28393. void AudioProcessorGraph::AudioGraphIOProcessor::getStateInformation (JUCE_NAMESPACE::MemoryBlock&)
  28394. {
  28395. }
  28396. void AudioProcessorGraph::AudioGraphIOProcessor::setStateInformation (const void*, int)
  28397. {
  28398. }
  28399. void AudioProcessorGraph::AudioGraphIOProcessor::setParentGraph (AudioProcessorGraph* const newGraph) throw()
  28400. {
  28401. graph = newGraph;
  28402. if (graph != 0)
  28403. {
  28404. setPlayConfigDetails (type == audioOutputNode ? graph->getNumOutputChannels() : 0,
  28405. type == audioInputNode ? graph->getNumInputChannels() : 0,
  28406. getSampleRate(),
  28407. getBlockSize());
  28408. updateHostDisplay();
  28409. }
  28410. }
  28411. END_JUCE_NAMESPACE
  28412. /********* End of inlined file: juce_AudioProcessorGraph.cpp *********/
  28413. /********* Start of inlined file: juce_AudioProcessorPlayer.cpp *********/
  28414. BEGIN_JUCE_NAMESPACE
  28415. AudioProcessorPlayer::AudioProcessorPlayer()
  28416. : processor (0),
  28417. sampleRate (0),
  28418. blockSize (0),
  28419. isPrepared (false),
  28420. numInputChans (0),
  28421. numOutputChans (0),
  28422. tempBuffer (1, 1)
  28423. {
  28424. }
  28425. AudioProcessorPlayer::~AudioProcessorPlayer()
  28426. {
  28427. setProcessor (0);
  28428. }
  28429. void AudioProcessorPlayer::setProcessor (AudioProcessor* const processorToPlay)
  28430. {
  28431. if (processor != processorToPlay)
  28432. {
  28433. if (processorToPlay != 0 && sampleRate > 0 && blockSize > 0)
  28434. {
  28435. processorToPlay->setPlayConfigDetails (numInputChans, numOutputChans,
  28436. sampleRate, blockSize);
  28437. processorToPlay->prepareToPlay (sampleRate, blockSize);
  28438. }
  28439. lock.enter();
  28440. AudioProcessor* const oldOne = isPrepared ? processor : 0;
  28441. processor = processorToPlay;
  28442. isPrepared = true;
  28443. lock.exit();
  28444. if (oldOne != 0)
  28445. oldOne->releaseResources();
  28446. }
  28447. }
  28448. void AudioProcessorPlayer::audioDeviceIOCallback (const float** inputChannelData,
  28449. int numInputChannels,
  28450. float** outputChannelData,
  28451. int numOutputChannels,
  28452. int numSamples)
  28453. {
  28454. // these should have been prepared by audioDeviceAboutToStart()...
  28455. jassert (sampleRate > 0 && blockSize > 0);
  28456. incomingMidi.clear();
  28457. messageCollector.removeNextBlockOfMessages (incomingMidi, numSamples);
  28458. int i, totalNumChans = 0;
  28459. if (numInputChannels > numOutputChannels)
  28460. {
  28461. // if there aren't enough output channels for the number of
  28462. // inputs, we need to create some temporary extra ones (can't
  28463. // use the input data in case it gets written to)
  28464. tempBuffer.setSize (numInputChannels - numOutputChannels, numSamples,
  28465. false, false, true);
  28466. for (i = 0; i < numOutputChannels; ++i)
  28467. {
  28468. channels[totalNumChans] = outputChannelData[i];
  28469. memcpy (channels[totalNumChans], inputChannelData[i], sizeof (float) * numSamples);
  28470. ++totalNumChans;
  28471. }
  28472. for (i = numOutputChannels; i < numInputChannels; ++i)
  28473. {
  28474. channels[totalNumChans] = tempBuffer.getSampleData (i - numOutputChannels, 0);
  28475. memcpy (channels[totalNumChans], inputChannelData[i], sizeof (float) * numSamples);
  28476. ++totalNumChans;
  28477. }
  28478. }
  28479. else
  28480. {
  28481. for (i = 0; i < numInputChannels; ++i)
  28482. {
  28483. channels[totalNumChans] = outputChannelData[i];
  28484. memcpy (channels[totalNumChans], inputChannelData[i], sizeof (float) * numSamples);
  28485. ++totalNumChans;
  28486. }
  28487. for (i = numInputChannels; i < numOutputChannels; ++i)
  28488. {
  28489. channels[totalNumChans] = outputChannelData[i];
  28490. zeromem (channels[totalNumChans], sizeof (float) * numSamples);
  28491. ++totalNumChans;
  28492. }
  28493. }
  28494. AudioSampleBuffer buffer (channels, totalNumChans, numSamples);
  28495. const ScopedLock sl (lock);
  28496. if (processor != 0)
  28497. processor->processBlock (buffer, incomingMidi);
  28498. }
  28499. void AudioProcessorPlayer::audioDeviceAboutToStart (AudioIODevice* device)
  28500. {
  28501. const ScopedLock sl (lock);
  28502. sampleRate = device->getCurrentSampleRate();
  28503. blockSize = device->getCurrentBufferSizeSamples();
  28504. numInputChans = device->getActiveInputChannels().countNumberOfSetBits();
  28505. numOutputChans = device->getActiveOutputChannels().countNumberOfSetBits();
  28506. messageCollector.reset (sampleRate);
  28507. zeromem (channels, sizeof (channels));
  28508. if (processor != 0)
  28509. {
  28510. if (isPrepared)
  28511. processor->releaseResources();
  28512. AudioProcessor* const oldProcessor = processor;
  28513. setProcessor (0);
  28514. setProcessor (oldProcessor);
  28515. }
  28516. }
  28517. void AudioProcessorPlayer::audioDeviceStopped()
  28518. {
  28519. const ScopedLock sl (lock);
  28520. if (processor != 0 && isPrepared)
  28521. processor->releaseResources();
  28522. sampleRate = 0.0;
  28523. blockSize = 0;
  28524. isPrepared = false;
  28525. tempBuffer.setSize (1, 1);
  28526. }
  28527. void AudioProcessorPlayer::handleIncomingMidiMessage (MidiInput*, const MidiMessage& message)
  28528. {
  28529. messageCollector.addMessageToQueue (message);
  28530. }
  28531. END_JUCE_NAMESPACE
  28532. /********* End of inlined file: juce_AudioProcessorPlayer.cpp *********/
  28533. /********* Start of inlined file: juce_GenericAudioProcessorEditor.cpp *********/
  28534. BEGIN_JUCE_NAMESPACE
  28535. class ProcessorParameterPropertyComp : public PropertyComponent,
  28536. public AudioProcessorListener,
  28537. public AsyncUpdater
  28538. {
  28539. public:
  28540. ProcessorParameterPropertyComp (const String& name,
  28541. AudioProcessor* const owner_,
  28542. const int index_)
  28543. : PropertyComponent (name),
  28544. owner (owner_),
  28545. index (index_)
  28546. {
  28547. addAndMakeVisible (slider = new ParamSlider (owner_, index_));
  28548. owner_->addListener (this);
  28549. }
  28550. ~ProcessorParameterPropertyComp()
  28551. {
  28552. owner->removeListener (this);
  28553. deleteAllChildren();
  28554. }
  28555. void refresh()
  28556. {
  28557. slider->setValue (owner->getParameter (index), false);
  28558. }
  28559. void audioProcessorChanged (AudioProcessor*) {}
  28560. void audioProcessorParameterChanged (AudioProcessor*, int parameterIndex, float)
  28561. {
  28562. if (parameterIndex == index)
  28563. triggerAsyncUpdate();
  28564. }
  28565. void handleAsyncUpdate()
  28566. {
  28567. refresh();
  28568. }
  28569. juce_UseDebuggingNewOperator
  28570. private:
  28571. AudioProcessor* const owner;
  28572. const int index;
  28573. Slider* slider;
  28574. class ParamSlider : public Slider
  28575. {
  28576. public:
  28577. ParamSlider (AudioProcessor* const owner_, const int index_)
  28578. : Slider (String::empty),
  28579. owner (owner_),
  28580. index (index_)
  28581. {
  28582. setRange (0.0, 1.0, 0.0);
  28583. setSliderStyle (Slider::LinearBar);
  28584. setTextBoxIsEditable (false);
  28585. setScrollWheelEnabled (false);
  28586. }
  28587. ~ParamSlider()
  28588. {
  28589. }
  28590. void valueChanged()
  28591. {
  28592. const float newVal = (float) getValue();
  28593. if (owner->getParameter (index) != newVal)
  28594. owner->setParameter (index, newVal);
  28595. }
  28596. const String getTextFromValue (double /*value*/)
  28597. {
  28598. return owner->getParameterText (index);
  28599. }
  28600. juce_UseDebuggingNewOperator
  28601. private:
  28602. AudioProcessor* const owner;
  28603. const int index;
  28604. };
  28605. };
  28606. GenericAudioProcessorEditor::GenericAudioProcessorEditor (AudioProcessor* const owner)
  28607. : AudioProcessorEditor (owner)
  28608. {
  28609. setOpaque (true);
  28610. addAndMakeVisible (panel = new PropertyPanel());
  28611. Array <PropertyComponent*> params;
  28612. const int numParams = owner->getNumParameters();
  28613. int totalHeight = 0;
  28614. for (int i = 0; i < numParams; ++i)
  28615. {
  28616. String name (owner->getParameterName (i));
  28617. if (name.trim().isEmpty())
  28618. name = "Unnamed";
  28619. ProcessorParameterPropertyComp* const pc = new ProcessorParameterPropertyComp (name, owner, i);
  28620. params.add (pc);
  28621. totalHeight += pc->getPreferredHeight();
  28622. }
  28623. panel->addProperties (params);
  28624. setSize (400, jlimit (25, 400, totalHeight));
  28625. }
  28626. GenericAudioProcessorEditor::~GenericAudioProcessorEditor()
  28627. {
  28628. deleteAllChildren();
  28629. }
  28630. void GenericAudioProcessorEditor::paint (Graphics& g)
  28631. {
  28632. g.fillAll (Colours::white);
  28633. }
  28634. void GenericAudioProcessorEditor::resized()
  28635. {
  28636. panel->setSize (getWidth(), getHeight());
  28637. }
  28638. END_JUCE_NAMESPACE
  28639. /********* End of inlined file: juce_GenericAudioProcessorEditor.cpp *********/
  28640. /********* Start of inlined file: juce_Sampler.cpp *********/
  28641. BEGIN_JUCE_NAMESPACE
  28642. SamplerSound::SamplerSound (const String& name_,
  28643. AudioFormatReader& source,
  28644. const BitArray& midiNotes_,
  28645. const int midiNoteForNormalPitch,
  28646. const double attackTimeSecs,
  28647. const double releaseTimeSecs,
  28648. const double maxSampleLengthSeconds)
  28649. : name (name_),
  28650. midiNotes (midiNotes_),
  28651. midiRootNote (midiNoteForNormalPitch)
  28652. {
  28653. sourceSampleRate = source.sampleRate;
  28654. if (sourceSampleRate <= 0 || source.lengthInSamples <= 0)
  28655. {
  28656. data = 0;
  28657. length = 0;
  28658. attackSamples = 0;
  28659. releaseSamples = 0;
  28660. }
  28661. else
  28662. {
  28663. length = jmin ((int) source.lengthInSamples,
  28664. (int) (maxSampleLengthSeconds * sourceSampleRate));
  28665. data = new AudioSampleBuffer (jmin (2, source.numChannels), length + 4);
  28666. data->readFromAudioReader (&source, 0, length + 4, 0, true, true);
  28667. attackSamples = roundDoubleToInt (attackTimeSecs * sourceSampleRate);
  28668. releaseSamples = roundDoubleToInt (releaseTimeSecs * sourceSampleRate);
  28669. }
  28670. }
  28671. SamplerSound::~SamplerSound()
  28672. {
  28673. delete data;
  28674. data = 0;
  28675. }
  28676. bool SamplerSound::appliesToNote (const int midiNoteNumber)
  28677. {
  28678. return midiNotes [midiNoteNumber];
  28679. }
  28680. bool SamplerSound::appliesToChannel (const int /*midiChannel*/)
  28681. {
  28682. return true;
  28683. }
  28684. SamplerVoice::SamplerVoice()
  28685. : pitchRatio (0.0),
  28686. sourceSamplePosition (0.0),
  28687. lgain (0.0f),
  28688. rgain (0.0f),
  28689. isInAttack (false),
  28690. isInRelease (false)
  28691. {
  28692. }
  28693. SamplerVoice::~SamplerVoice()
  28694. {
  28695. }
  28696. bool SamplerVoice::canPlaySound (SynthesiserSound* sound)
  28697. {
  28698. return dynamic_cast <const SamplerSound*> (sound) != 0;
  28699. }
  28700. void SamplerVoice::startNote (const int midiNoteNumber,
  28701. const float velocity,
  28702. SynthesiserSound* s,
  28703. const int /*currentPitchWheelPosition*/)
  28704. {
  28705. const SamplerSound* const sound = dynamic_cast <const SamplerSound*> (s);
  28706. jassert (sound != 0); // this object can only play SamplerSounds!
  28707. if (sound != 0)
  28708. {
  28709. const double targetFreq = MidiMessage::getMidiNoteInHertz (midiNoteNumber);
  28710. const double naturalFreq = MidiMessage::getMidiNoteInHertz (sound->midiRootNote);
  28711. pitchRatio = (targetFreq * sound->sourceSampleRate) / (naturalFreq * getSampleRate());
  28712. sourceSamplePosition = 0.0;
  28713. lgain = velocity;
  28714. rgain = velocity;
  28715. isInAttack = (sound->attackSamples > 0);
  28716. isInRelease = false;
  28717. if (isInAttack)
  28718. {
  28719. attackReleaseLevel = 0.0f;
  28720. attackDelta = (float) (pitchRatio / sound->attackSamples);
  28721. }
  28722. else
  28723. {
  28724. attackReleaseLevel = 1.0f;
  28725. attackDelta = 0.0f;
  28726. }
  28727. if (sound->releaseSamples > 0)
  28728. {
  28729. releaseDelta = (float) (-pitchRatio / sound->releaseSamples);
  28730. }
  28731. else
  28732. {
  28733. releaseDelta = 0.0f;
  28734. }
  28735. }
  28736. }
  28737. void SamplerVoice::stopNote (const bool allowTailOff)
  28738. {
  28739. if (allowTailOff)
  28740. {
  28741. isInAttack = false;
  28742. isInRelease = true;
  28743. }
  28744. else
  28745. {
  28746. clearCurrentNote();
  28747. }
  28748. }
  28749. void SamplerVoice::pitchWheelMoved (const int /*newValue*/)
  28750. {
  28751. }
  28752. void SamplerVoice::controllerMoved (const int /*controllerNumber*/,
  28753. const int /*newValue*/)
  28754. {
  28755. }
  28756. void SamplerVoice::renderNextBlock (AudioSampleBuffer& outputBuffer, int startSample, int numSamples)
  28757. {
  28758. const SamplerSound* const playingSound = (SamplerSound*) (SynthesiserSound*) getCurrentlyPlayingSound();
  28759. if (playingSound != 0)
  28760. {
  28761. const float* const inL = playingSound->data->getSampleData (0, 0);
  28762. const float* const inR = playingSound->data->getNumChannels() > 1
  28763. ? playingSound->data->getSampleData (1, 0) : 0;
  28764. float* outL = outputBuffer.getSampleData (0, startSample);
  28765. float* outR = outputBuffer.getNumChannels() > 1 ? outputBuffer.getSampleData (1, startSample) : 0;
  28766. while (--numSamples >= 0)
  28767. {
  28768. const int pos = (int) sourceSamplePosition;
  28769. const float alpha = (float) (sourceSamplePosition - pos);
  28770. const float invAlpha = 1.0f - alpha;
  28771. // just using a very simple linear interpolation here..
  28772. float l = (inL [pos] * invAlpha + inL [pos + 1] * alpha);
  28773. float r = (inR != 0) ? (inR [pos] * invAlpha + inR [pos + 1] * alpha)
  28774. : l;
  28775. l *= lgain;
  28776. r *= rgain;
  28777. if (isInAttack)
  28778. {
  28779. l *= attackReleaseLevel;
  28780. r *= attackReleaseLevel;
  28781. attackReleaseLevel += attackDelta;
  28782. if (attackReleaseLevel >= 1.0f)
  28783. {
  28784. attackReleaseLevel = 1.0f;
  28785. isInAttack = false;
  28786. }
  28787. }
  28788. else if (isInRelease)
  28789. {
  28790. l *= attackReleaseLevel;
  28791. r *= attackReleaseLevel;
  28792. attackReleaseLevel += releaseDelta;
  28793. if (attackReleaseLevel <= 0.0f)
  28794. {
  28795. stopNote (false);
  28796. break;
  28797. }
  28798. }
  28799. if (outR != 0)
  28800. {
  28801. *outL++ += l;
  28802. *outR++ += r;
  28803. }
  28804. else
  28805. {
  28806. *outL++ += (l + r) * 0.5f;
  28807. }
  28808. sourceSamplePosition += pitchRatio;
  28809. if (sourceSamplePosition > playingSound->length)
  28810. {
  28811. stopNote (false);
  28812. break;
  28813. }
  28814. }
  28815. }
  28816. }
  28817. END_JUCE_NAMESPACE
  28818. /********* End of inlined file: juce_Sampler.cpp *********/
  28819. /********* Start of inlined file: juce_Synthesiser.cpp *********/
  28820. BEGIN_JUCE_NAMESPACE
  28821. SynthesiserSound::SynthesiserSound()
  28822. {
  28823. }
  28824. SynthesiserSound::~SynthesiserSound()
  28825. {
  28826. }
  28827. SynthesiserVoice::SynthesiserVoice()
  28828. : currentSampleRate (44100.0),
  28829. currentlyPlayingNote (-1),
  28830. noteOnTime (0),
  28831. currentlyPlayingSound (0)
  28832. {
  28833. }
  28834. SynthesiserVoice::~SynthesiserVoice()
  28835. {
  28836. }
  28837. bool SynthesiserVoice::isPlayingChannel (const int midiChannel) const
  28838. {
  28839. return currentlyPlayingSound != 0
  28840. && currentlyPlayingSound->appliesToChannel (midiChannel);
  28841. }
  28842. void SynthesiserVoice::setCurrentPlaybackSampleRate (const double newRate)
  28843. {
  28844. currentSampleRate = newRate;
  28845. }
  28846. void SynthesiserVoice::clearCurrentNote()
  28847. {
  28848. currentlyPlayingNote = -1;
  28849. currentlyPlayingSound = 0;
  28850. }
  28851. Synthesiser::Synthesiser()
  28852. : voices (2),
  28853. sounds (2),
  28854. sampleRate (0),
  28855. lastNoteOnCounter (0),
  28856. shouldStealNotes (true)
  28857. {
  28858. for (int i = 0; i < numElementsInArray (lastPitchWheelValues); ++i)
  28859. lastPitchWheelValues[i] = 0x2000;
  28860. }
  28861. Synthesiser::~Synthesiser()
  28862. {
  28863. }
  28864. SynthesiserVoice* Synthesiser::getVoice (const int index) const throw()
  28865. {
  28866. const ScopedLock sl (lock);
  28867. return voices [index];
  28868. }
  28869. void Synthesiser::clearVoices()
  28870. {
  28871. const ScopedLock sl (lock);
  28872. voices.clear();
  28873. }
  28874. void Synthesiser::addVoice (SynthesiserVoice* const newVoice)
  28875. {
  28876. const ScopedLock sl (lock);
  28877. voices.add (newVoice);
  28878. }
  28879. void Synthesiser::removeVoice (const int index)
  28880. {
  28881. const ScopedLock sl (lock);
  28882. voices.remove (index);
  28883. }
  28884. void Synthesiser::clearSounds()
  28885. {
  28886. const ScopedLock sl (lock);
  28887. sounds.clear();
  28888. }
  28889. void Synthesiser::addSound (const SynthesiserSound::Ptr& newSound)
  28890. {
  28891. const ScopedLock sl (lock);
  28892. sounds.add (newSound);
  28893. }
  28894. void Synthesiser::removeSound (const int index)
  28895. {
  28896. const ScopedLock sl (lock);
  28897. sounds.remove (index);
  28898. }
  28899. void Synthesiser::setNoteStealingEnabled (const bool shouldStealNotes_)
  28900. {
  28901. shouldStealNotes = shouldStealNotes_;
  28902. }
  28903. void Synthesiser::setCurrentPlaybackSampleRate (const double newRate)
  28904. {
  28905. if (sampleRate != newRate)
  28906. {
  28907. const ScopedLock sl (lock);
  28908. allNotesOff (0, false);
  28909. sampleRate = newRate;
  28910. for (int i = voices.size(); --i >= 0;)
  28911. voices.getUnchecked (i)->setCurrentPlaybackSampleRate (newRate);
  28912. }
  28913. }
  28914. void Synthesiser::renderNextBlock (AudioSampleBuffer& outputBuffer,
  28915. const MidiBuffer& midiData,
  28916. int startSample,
  28917. int numSamples)
  28918. {
  28919. // must set the sample rate before using this!
  28920. jassert (sampleRate != 0);
  28921. const ScopedLock sl (lock);
  28922. MidiBuffer::Iterator midiIterator (midiData);
  28923. midiIterator.setNextSamplePosition (startSample);
  28924. MidiMessage m (0xf4, 0.0);
  28925. while (numSamples > 0)
  28926. {
  28927. int midiEventPos;
  28928. const bool useEvent = midiIterator.getNextEvent (m, midiEventPos)
  28929. && midiEventPos < startSample + numSamples;
  28930. const int numThisTime = useEvent ? midiEventPos - startSample
  28931. : numSamples;
  28932. if (numThisTime > 0)
  28933. {
  28934. for (int i = voices.size(); --i >= 0;)
  28935. voices.getUnchecked (i)->renderNextBlock (outputBuffer, startSample, numThisTime);
  28936. }
  28937. if (useEvent)
  28938. {
  28939. if (m.isNoteOn())
  28940. {
  28941. const int channel = m.getChannel();
  28942. noteOn (channel,
  28943. m.getNoteNumber(),
  28944. m.getFloatVelocity());
  28945. }
  28946. else if (m.isNoteOff())
  28947. {
  28948. noteOff (m.getChannel(),
  28949. m.getNoteNumber(),
  28950. true);
  28951. }
  28952. else if (m.isAllNotesOff() || m.isAllSoundOff())
  28953. {
  28954. allNotesOff (m.getChannel(), true);
  28955. }
  28956. else if (m.isPitchWheel())
  28957. {
  28958. const int channel = m.getChannel();
  28959. const int wheelPos = m.getPitchWheelValue();
  28960. lastPitchWheelValues [channel - 1] = wheelPos;
  28961. handlePitchWheel (channel, wheelPos);
  28962. }
  28963. else if (m.isController())
  28964. {
  28965. handleController (m.getChannel(),
  28966. m.getControllerNumber(),
  28967. m.getControllerValue());
  28968. }
  28969. }
  28970. startSample += numThisTime;
  28971. numSamples -= numThisTime;
  28972. }
  28973. }
  28974. void Synthesiser::noteOn (const int midiChannel,
  28975. const int midiNoteNumber,
  28976. const float velocity)
  28977. {
  28978. const ScopedLock sl (lock);
  28979. for (int i = sounds.size(); --i >= 0;)
  28980. {
  28981. SynthesiserSound* const sound = sounds.getUnchecked(i);
  28982. if (sound->appliesToNote (midiNoteNumber)
  28983. && sound->appliesToChannel (midiChannel))
  28984. {
  28985. startVoice (findFreeVoice (sound, shouldStealNotes),
  28986. sound, midiChannel, midiNoteNumber, velocity);
  28987. }
  28988. }
  28989. }
  28990. void Synthesiser::startVoice (SynthesiserVoice* const voice,
  28991. SynthesiserSound* const sound,
  28992. const int midiChannel,
  28993. const int midiNoteNumber,
  28994. const float velocity)
  28995. {
  28996. if (voice != 0 && sound != 0)
  28997. {
  28998. if (voice->currentlyPlayingSound != 0)
  28999. voice->stopNote (false);
  29000. voice->startNote (midiNoteNumber,
  29001. velocity,
  29002. sound,
  29003. lastPitchWheelValues [midiChannel - 1]);
  29004. voice->currentlyPlayingNote = midiNoteNumber;
  29005. voice->noteOnTime = ++lastNoteOnCounter;
  29006. voice->currentlyPlayingSound = sound;
  29007. }
  29008. }
  29009. void Synthesiser::noteOff (const int midiChannel,
  29010. const int midiNoteNumber,
  29011. const bool allowTailOff)
  29012. {
  29013. const ScopedLock sl (lock);
  29014. for (int i = voices.size(); --i >= 0;)
  29015. {
  29016. SynthesiserVoice* const voice = voices.getUnchecked (i);
  29017. if (voice->getCurrentlyPlayingNote() == midiNoteNumber)
  29018. {
  29019. SynthesiserSound* const sound = voice->getCurrentlyPlayingSound();
  29020. if (sound != 0
  29021. && sound->appliesToNote (midiNoteNumber)
  29022. && sound->appliesToChannel (midiChannel))
  29023. {
  29024. voice->stopNote (allowTailOff);
  29025. // the subclass MUST call clearCurrentNote() if it's not tailing off! RTFM for stopNote()!
  29026. jassert (allowTailOff || (voice->getCurrentlyPlayingNote() < 0 && voice->getCurrentlyPlayingSound() == 0));
  29027. }
  29028. }
  29029. }
  29030. }
  29031. void Synthesiser::allNotesOff (const int midiChannel,
  29032. const bool allowTailOff)
  29033. {
  29034. const ScopedLock sl (lock);
  29035. for (int i = voices.size(); --i >= 0;)
  29036. {
  29037. SynthesiserVoice* const voice = voices.getUnchecked (i);
  29038. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  29039. voice->stopNote (allowTailOff);
  29040. }
  29041. }
  29042. void Synthesiser::handlePitchWheel (const int midiChannel,
  29043. const int wheelValue)
  29044. {
  29045. const ScopedLock sl (lock);
  29046. for (int i = voices.size(); --i >= 0;)
  29047. {
  29048. SynthesiserVoice* const voice = voices.getUnchecked (i);
  29049. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  29050. {
  29051. voice->pitchWheelMoved (wheelValue);
  29052. }
  29053. }
  29054. }
  29055. void Synthesiser::handleController (const int midiChannel,
  29056. const int controllerNumber,
  29057. const int controllerValue)
  29058. {
  29059. const ScopedLock sl (lock);
  29060. for (int i = voices.size(); --i >= 0;)
  29061. {
  29062. SynthesiserVoice* const voice = voices.getUnchecked (i);
  29063. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  29064. voice->controllerMoved (controllerNumber, controllerValue);
  29065. }
  29066. }
  29067. SynthesiserVoice* Synthesiser::findFreeVoice (SynthesiserSound* soundToPlay,
  29068. const bool stealIfNoneAvailable) const
  29069. {
  29070. const ScopedLock sl (lock);
  29071. for (int i = voices.size(); --i >= 0;)
  29072. if (voices.getUnchecked (i)->getCurrentlyPlayingNote() < 0
  29073. && voices.getUnchecked (i)->canPlaySound (soundToPlay))
  29074. return voices.getUnchecked (i);
  29075. if (stealIfNoneAvailable)
  29076. {
  29077. // currently this just steals the one that's been playing the longest, but could be made a bit smarter..
  29078. SynthesiserVoice* oldest = 0;
  29079. for (int i = voices.size(); --i >= 0;)
  29080. {
  29081. SynthesiserVoice* const voice = voices.getUnchecked (i);
  29082. if (voice->canPlaySound (soundToPlay)
  29083. && (oldest == 0 || oldest->noteOnTime > voice->noteOnTime))
  29084. oldest = voice;
  29085. }
  29086. jassert (oldest != 0);
  29087. return oldest;
  29088. }
  29089. return 0;
  29090. }
  29091. END_JUCE_NAMESPACE
  29092. /********* End of inlined file: juce_Synthesiser.cpp *********/
  29093. /********* Start of inlined file: juce_ActionBroadcaster.cpp *********/
  29094. BEGIN_JUCE_NAMESPACE
  29095. ActionBroadcaster::ActionBroadcaster() throw()
  29096. {
  29097. // are you trying to create this object before or after juce has been intialised??
  29098. jassert (MessageManager::instance != 0);
  29099. }
  29100. ActionBroadcaster::~ActionBroadcaster()
  29101. {
  29102. // all event-based objects must be deleted BEFORE juce is shut down!
  29103. jassert (MessageManager::instance != 0);
  29104. }
  29105. void ActionBroadcaster::addActionListener (ActionListener* const listener)
  29106. {
  29107. actionListenerList.addActionListener (listener);
  29108. }
  29109. void ActionBroadcaster::removeActionListener (ActionListener* const listener)
  29110. {
  29111. jassert (actionListenerList.isValidMessageListener());
  29112. if (actionListenerList.isValidMessageListener())
  29113. actionListenerList.removeActionListener (listener);
  29114. }
  29115. void ActionBroadcaster::removeAllActionListeners()
  29116. {
  29117. actionListenerList.removeAllActionListeners();
  29118. }
  29119. void ActionBroadcaster::sendActionMessage (const String& message) const
  29120. {
  29121. actionListenerList.sendActionMessage (message);
  29122. }
  29123. END_JUCE_NAMESPACE
  29124. /********* End of inlined file: juce_ActionBroadcaster.cpp *********/
  29125. /********* Start of inlined file: juce_ActionListenerList.cpp *********/
  29126. BEGIN_JUCE_NAMESPACE
  29127. // special message of our own with a string in it
  29128. class ActionMessage : public Message
  29129. {
  29130. public:
  29131. const String message;
  29132. ActionMessage (const String& messageText,
  29133. void* const listener_) throw()
  29134. : message (messageText)
  29135. {
  29136. pointerParameter = listener_;
  29137. }
  29138. ~ActionMessage() throw()
  29139. {
  29140. }
  29141. private:
  29142. ActionMessage (const ActionMessage&);
  29143. const ActionMessage& operator= (const ActionMessage&);
  29144. };
  29145. ActionListenerList::ActionListenerList() throw()
  29146. {
  29147. }
  29148. ActionListenerList::~ActionListenerList() throw()
  29149. {
  29150. }
  29151. void ActionListenerList::addActionListener (ActionListener* const listener) throw()
  29152. {
  29153. const ScopedLock sl (actionListenerLock_);
  29154. jassert (listener != 0);
  29155. jassert (! actionListeners_.contains (listener)); // trying to add a listener to the list twice!
  29156. if (listener != 0)
  29157. actionListeners_.add (listener);
  29158. }
  29159. void ActionListenerList::removeActionListener (ActionListener* const listener) throw()
  29160. {
  29161. const ScopedLock sl (actionListenerLock_);
  29162. jassert (actionListeners_.contains (listener)); // trying to remove a listener that isn't on the list!
  29163. actionListeners_.removeValue (listener);
  29164. }
  29165. void ActionListenerList::removeAllActionListeners() throw()
  29166. {
  29167. const ScopedLock sl (actionListenerLock_);
  29168. actionListeners_.clear();
  29169. }
  29170. void ActionListenerList::sendActionMessage (const String& message) const
  29171. {
  29172. const ScopedLock sl (actionListenerLock_);
  29173. for (int i = actionListeners_.size(); --i >= 0;)
  29174. {
  29175. postMessage (new ActionMessage (message,
  29176. (ActionListener*) actionListeners_.getUnchecked(i)));
  29177. }
  29178. }
  29179. void ActionListenerList::handleMessage (const Message& message)
  29180. {
  29181. const ActionMessage& am = (const ActionMessage&) message;
  29182. if (actionListeners_.contains (am.pointerParameter))
  29183. ((ActionListener*) am.pointerParameter)->actionListenerCallback (am.message);
  29184. }
  29185. END_JUCE_NAMESPACE
  29186. /********* End of inlined file: juce_ActionListenerList.cpp *********/
  29187. /********* Start of inlined file: juce_AsyncUpdater.cpp *********/
  29188. BEGIN_JUCE_NAMESPACE
  29189. AsyncUpdater::AsyncUpdater() throw()
  29190. : asyncMessagePending (false)
  29191. {
  29192. internalAsyncHandler.owner = this;
  29193. }
  29194. AsyncUpdater::~AsyncUpdater()
  29195. {
  29196. }
  29197. void AsyncUpdater::triggerAsyncUpdate() throw()
  29198. {
  29199. if (! asyncMessagePending)
  29200. {
  29201. asyncMessagePending = true;
  29202. internalAsyncHandler.postMessage (new Message());
  29203. }
  29204. }
  29205. void AsyncUpdater::cancelPendingUpdate() throw()
  29206. {
  29207. asyncMessagePending = false;
  29208. }
  29209. void AsyncUpdater::handleUpdateNowIfNeeded()
  29210. {
  29211. if (asyncMessagePending)
  29212. {
  29213. asyncMessagePending = false;
  29214. handleAsyncUpdate();
  29215. }
  29216. }
  29217. void AsyncUpdater::AsyncUpdaterInternal::handleMessage (const Message&)
  29218. {
  29219. owner->handleUpdateNowIfNeeded();
  29220. }
  29221. END_JUCE_NAMESPACE
  29222. /********* End of inlined file: juce_AsyncUpdater.cpp *********/
  29223. /********* Start of inlined file: juce_ChangeBroadcaster.cpp *********/
  29224. BEGIN_JUCE_NAMESPACE
  29225. ChangeBroadcaster::ChangeBroadcaster() throw()
  29226. {
  29227. // are you trying to create this object before or after juce has been intialised??
  29228. jassert (MessageManager::instance != 0);
  29229. }
  29230. ChangeBroadcaster::~ChangeBroadcaster()
  29231. {
  29232. // all event-based objects must be deleted BEFORE juce is shut down!
  29233. jassert (MessageManager::instance != 0);
  29234. }
  29235. void ChangeBroadcaster::addChangeListener (ChangeListener* const listener) throw()
  29236. {
  29237. changeListenerList.addChangeListener (listener);
  29238. }
  29239. void ChangeBroadcaster::removeChangeListener (ChangeListener* const listener) throw()
  29240. {
  29241. jassert (changeListenerList.isValidMessageListener());
  29242. if (changeListenerList.isValidMessageListener())
  29243. changeListenerList.removeChangeListener (listener);
  29244. }
  29245. void ChangeBroadcaster::removeAllChangeListeners() throw()
  29246. {
  29247. changeListenerList.removeAllChangeListeners();
  29248. }
  29249. void ChangeBroadcaster::sendChangeMessage (void* objectThatHasChanged) throw()
  29250. {
  29251. changeListenerList.sendChangeMessage (objectThatHasChanged);
  29252. }
  29253. void ChangeBroadcaster::sendSynchronousChangeMessage (void* objectThatHasChanged)
  29254. {
  29255. changeListenerList.sendSynchronousChangeMessage (objectThatHasChanged);
  29256. }
  29257. void ChangeBroadcaster::dispatchPendingMessages()
  29258. {
  29259. changeListenerList.dispatchPendingMessages();
  29260. }
  29261. END_JUCE_NAMESPACE
  29262. /********* End of inlined file: juce_ChangeBroadcaster.cpp *********/
  29263. /********* Start of inlined file: juce_ChangeListenerList.cpp *********/
  29264. BEGIN_JUCE_NAMESPACE
  29265. ChangeListenerList::ChangeListenerList() throw()
  29266. : lastChangedObject (0),
  29267. messagePending (false)
  29268. {
  29269. }
  29270. ChangeListenerList::~ChangeListenerList() throw()
  29271. {
  29272. }
  29273. void ChangeListenerList::addChangeListener (ChangeListener* const listener) throw()
  29274. {
  29275. const ScopedLock sl (lock);
  29276. jassert (listener != 0);
  29277. if (listener != 0)
  29278. listeners.add (listener);
  29279. }
  29280. void ChangeListenerList::removeChangeListener (ChangeListener* const listener) throw()
  29281. {
  29282. const ScopedLock sl (lock);
  29283. listeners.removeValue (listener);
  29284. }
  29285. void ChangeListenerList::removeAllChangeListeners() throw()
  29286. {
  29287. const ScopedLock sl (lock);
  29288. listeners.clear();
  29289. }
  29290. void ChangeListenerList::sendChangeMessage (void* const objectThatHasChanged) throw()
  29291. {
  29292. const ScopedLock sl (lock);
  29293. if ((! messagePending) && (listeners.size() > 0))
  29294. {
  29295. lastChangedObject = objectThatHasChanged;
  29296. postMessage (new Message (0, 0, 0, objectThatHasChanged));
  29297. messagePending = true;
  29298. }
  29299. }
  29300. void ChangeListenerList::handleMessage (const Message& message)
  29301. {
  29302. sendSynchronousChangeMessage (message.pointerParameter);
  29303. }
  29304. void ChangeListenerList::sendSynchronousChangeMessage (void* const objectThatHasChanged)
  29305. {
  29306. const ScopedLock sl (lock);
  29307. messagePending = false;
  29308. for (int i = listeners.size(); --i >= 0;)
  29309. {
  29310. ChangeListener* const l = (ChangeListener*) listeners.getUnchecked (i);
  29311. {
  29312. const ScopedUnlock tempUnlocker (lock);
  29313. l->changeListenerCallback (objectThatHasChanged);
  29314. }
  29315. i = jmin (i, listeners.size());
  29316. }
  29317. }
  29318. void ChangeListenerList::dispatchPendingMessages()
  29319. {
  29320. if (messagePending)
  29321. sendSynchronousChangeMessage (lastChangedObject);
  29322. }
  29323. END_JUCE_NAMESPACE
  29324. /********* End of inlined file: juce_ChangeListenerList.cpp *********/
  29325. /********* Start of inlined file: juce_InterprocessConnection.cpp *********/
  29326. BEGIN_JUCE_NAMESPACE
  29327. InterprocessConnection::InterprocessConnection (const bool callbacksOnMessageThread,
  29328. const uint32 magicMessageHeaderNumber)
  29329. : Thread ("Juce IPC connection"),
  29330. socket (0),
  29331. pipe (0),
  29332. callbackConnectionState (false),
  29333. useMessageThread (callbacksOnMessageThread),
  29334. magicMessageHeader (magicMessageHeaderNumber),
  29335. pipeReceiveMessageTimeout (-1)
  29336. {
  29337. }
  29338. InterprocessConnection::~InterprocessConnection()
  29339. {
  29340. callbackConnectionState = false;
  29341. disconnect();
  29342. }
  29343. bool InterprocessConnection::connectToSocket (const String& hostName,
  29344. const int portNumber,
  29345. const int timeOutMillisecs)
  29346. {
  29347. disconnect();
  29348. const ScopedLock sl (pipeAndSocketLock);
  29349. socket = new StreamingSocket();
  29350. if (socket->connect (hostName, portNumber, timeOutMillisecs))
  29351. {
  29352. connectionMadeInt();
  29353. startThread();
  29354. return true;
  29355. }
  29356. else
  29357. {
  29358. deleteAndZero (socket);
  29359. return false;
  29360. }
  29361. }
  29362. bool InterprocessConnection::connectToPipe (const String& pipeName,
  29363. const int pipeReceiveMessageTimeoutMs)
  29364. {
  29365. disconnect();
  29366. NamedPipe* const newPipe = new NamedPipe();
  29367. if (newPipe->openExisting (pipeName))
  29368. {
  29369. const ScopedLock sl (pipeAndSocketLock);
  29370. pipeReceiveMessageTimeout = pipeReceiveMessageTimeoutMs;
  29371. initialiseWithPipe (newPipe);
  29372. return true;
  29373. }
  29374. else
  29375. {
  29376. delete newPipe;
  29377. return false;
  29378. }
  29379. }
  29380. bool InterprocessConnection::createPipe (const String& pipeName,
  29381. const int pipeReceiveMessageTimeoutMs)
  29382. {
  29383. disconnect();
  29384. NamedPipe* const newPipe = new NamedPipe();
  29385. if (newPipe->createNewPipe (pipeName))
  29386. {
  29387. const ScopedLock sl (pipeAndSocketLock);
  29388. pipeReceiveMessageTimeout = pipeReceiveMessageTimeoutMs;
  29389. initialiseWithPipe (newPipe);
  29390. return true;
  29391. }
  29392. else
  29393. {
  29394. delete newPipe;
  29395. return false;
  29396. }
  29397. }
  29398. void InterprocessConnection::disconnect()
  29399. {
  29400. if (socket != 0)
  29401. socket->close();
  29402. if (pipe != 0)
  29403. {
  29404. pipe->cancelPendingReads();
  29405. pipe->close();
  29406. }
  29407. stopThread (4000);
  29408. {
  29409. const ScopedLock sl (pipeAndSocketLock);
  29410. deleteAndZero (socket);
  29411. deleteAndZero (pipe);
  29412. }
  29413. connectionLostInt();
  29414. }
  29415. bool InterprocessConnection::isConnected() const
  29416. {
  29417. const ScopedLock sl (pipeAndSocketLock);
  29418. return ((socket != 0 && socket->isConnected())
  29419. || (pipe != 0 && pipe->isOpen()))
  29420. && isThreadRunning();
  29421. }
  29422. const String InterprocessConnection::getConnectedHostName() const
  29423. {
  29424. if (pipe != 0)
  29425. {
  29426. return "localhost";
  29427. }
  29428. else if (socket != 0)
  29429. {
  29430. if (! socket->isLocal())
  29431. return socket->getHostName();
  29432. return "localhost";
  29433. }
  29434. return String::empty;
  29435. }
  29436. bool InterprocessConnection::sendMessage (const MemoryBlock& message)
  29437. {
  29438. uint32 messageHeader[2];
  29439. messageHeader [0] = swapIfBigEndian (magicMessageHeader);
  29440. messageHeader [1] = swapIfBigEndian ((uint32) message.getSize());
  29441. MemoryBlock messageData (sizeof (messageHeader) + message.getSize());
  29442. messageData.copyFrom (messageHeader, 0, sizeof (messageHeader));
  29443. messageData.copyFrom (message.getData(), sizeof (messageHeader), message.getSize());
  29444. int bytesWritten = 0;
  29445. const ScopedLock sl (pipeAndSocketLock);
  29446. if (socket != 0)
  29447. {
  29448. bytesWritten = socket->write (messageData.getData(), messageData.getSize());
  29449. }
  29450. else if (pipe != 0)
  29451. {
  29452. bytesWritten = pipe->write (messageData.getData(), messageData.getSize());
  29453. }
  29454. if (bytesWritten < 0)
  29455. {
  29456. // error..
  29457. return false;
  29458. }
  29459. return (bytesWritten == messageData.getSize());
  29460. }
  29461. void InterprocessConnection::initialiseWithSocket (StreamingSocket* const socket_)
  29462. {
  29463. jassert (socket == 0);
  29464. socket = socket_;
  29465. connectionMadeInt();
  29466. startThread();
  29467. }
  29468. void InterprocessConnection::initialiseWithPipe (NamedPipe* const pipe_)
  29469. {
  29470. jassert (pipe == 0);
  29471. pipe = pipe_;
  29472. connectionMadeInt();
  29473. startThread();
  29474. }
  29475. const int messageMagicNumber = 0xb734128b;
  29476. void InterprocessConnection::handleMessage (const Message& message)
  29477. {
  29478. if (message.intParameter1 == messageMagicNumber)
  29479. {
  29480. switch (message.intParameter2)
  29481. {
  29482. case 0:
  29483. {
  29484. MemoryBlock* const data = (MemoryBlock*) message.pointerParameter;
  29485. messageReceived (*data);
  29486. delete data;
  29487. break;
  29488. }
  29489. case 1:
  29490. connectionMade();
  29491. break;
  29492. case 2:
  29493. connectionLost();
  29494. break;
  29495. }
  29496. }
  29497. }
  29498. void InterprocessConnection::connectionMadeInt()
  29499. {
  29500. if (! callbackConnectionState)
  29501. {
  29502. callbackConnectionState = true;
  29503. if (useMessageThread)
  29504. postMessage (new Message (messageMagicNumber, 1, 0, 0));
  29505. else
  29506. connectionMade();
  29507. }
  29508. }
  29509. void InterprocessConnection::connectionLostInt()
  29510. {
  29511. if (callbackConnectionState)
  29512. {
  29513. callbackConnectionState = false;
  29514. if (useMessageThread)
  29515. postMessage (new Message (messageMagicNumber, 2, 0, 0));
  29516. else
  29517. connectionLost();
  29518. }
  29519. }
  29520. void InterprocessConnection::deliverDataInt (const MemoryBlock& data)
  29521. {
  29522. jassert (callbackConnectionState);
  29523. if (useMessageThread)
  29524. postMessage (new Message (messageMagicNumber, 0, 0, new MemoryBlock (data)));
  29525. else
  29526. messageReceived (data);
  29527. }
  29528. bool InterprocessConnection::readNextMessageInt()
  29529. {
  29530. const int maximumMessageSize = 1024 * 1024 * 10; // sanity check
  29531. uint32 messageHeader[2];
  29532. const int bytes = (socket != 0) ? socket->read (messageHeader, sizeof (messageHeader), true)
  29533. : pipe->read (messageHeader, sizeof (messageHeader), pipeReceiveMessageTimeout);
  29534. if (bytes == sizeof (messageHeader)
  29535. && swapIfBigEndian (messageHeader[0]) == magicMessageHeader)
  29536. {
  29537. const int bytesInMessage = (int) swapIfBigEndian (messageHeader[1]);
  29538. if (bytesInMessage > 0 && bytesInMessage < maximumMessageSize)
  29539. {
  29540. MemoryBlock messageData (bytesInMessage, true);
  29541. int bytesRead = 0;
  29542. while (bytesRead < bytesInMessage)
  29543. {
  29544. if (threadShouldExit())
  29545. return false;
  29546. const int numThisTime = jmin (bytesInMessage, 65536);
  29547. const int bytesIn = (socket != 0) ? socket->read (((char*) messageData.getData()) + bytesRead, numThisTime, true)
  29548. : pipe->read (((char*) messageData.getData()) + bytesRead, numThisTime,
  29549. pipeReceiveMessageTimeout);
  29550. if (bytesIn <= 0)
  29551. break;
  29552. bytesRead += bytesIn;
  29553. }
  29554. if (bytesRead >= 0)
  29555. deliverDataInt (messageData);
  29556. }
  29557. }
  29558. else if (bytes < 0)
  29559. {
  29560. {
  29561. const ScopedLock sl (pipeAndSocketLock);
  29562. deleteAndZero (socket);
  29563. }
  29564. connectionLostInt();
  29565. return false;
  29566. }
  29567. return true;
  29568. }
  29569. void InterprocessConnection::run()
  29570. {
  29571. while (! threadShouldExit())
  29572. {
  29573. if (socket != 0)
  29574. {
  29575. const int ready = socket->waitUntilReady (true, 0);
  29576. if (ready < 0)
  29577. {
  29578. {
  29579. const ScopedLock sl (pipeAndSocketLock);
  29580. deleteAndZero (socket);
  29581. }
  29582. connectionLostInt();
  29583. break;
  29584. }
  29585. else if (ready > 0)
  29586. {
  29587. if (! readNextMessageInt())
  29588. break;
  29589. }
  29590. else
  29591. {
  29592. Thread::sleep (2);
  29593. }
  29594. }
  29595. else if (pipe != 0)
  29596. {
  29597. if (! pipe->isOpen())
  29598. {
  29599. {
  29600. const ScopedLock sl (pipeAndSocketLock);
  29601. deleteAndZero (pipe);
  29602. }
  29603. connectionLostInt();
  29604. break;
  29605. }
  29606. else
  29607. {
  29608. if (! readNextMessageInt())
  29609. break;
  29610. }
  29611. }
  29612. else
  29613. {
  29614. break;
  29615. }
  29616. }
  29617. }
  29618. END_JUCE_NAMESPACE
  29619. /********* End of inlined file: juce_InterprocessConnection.cpp *********/
  29620. /********* Start of inlined file: juce_InterprocessConnectionServer.cpp *********/
  29621. BEGIN_JUCE_NAMESPACE
  29622. InterprocessConnectionServer::InterprocessConnectionServer()
  29623. : Thread ("Juce IPC server"),
  29624. socket (0)
  29625. {
  29626. }
  29627. InterprocessConnectionServer::~InterprocessConnectionServer()
  29628. {
  29629. stop();
  29630. }
  29631. bool InterprocessConnectionServer::beginWaitingForSocket (const int portNumber)
  29632. {
  29633. stop();
  29634. socket = new StreamingSocket();
  29635. if (socket->createListener (portNumber))
  29636. {
  29637. startThread();
  29638. return true;
  29639. }
  29640. deleteAndZero (socket);
  29641. return false;
  29642. }
  29643. void InterprocessConnectionServer::stop()
  29644. {
  29645. signalThreadShouldExit();
  29646. if (socket != 0)
  29647. socket->close();
  29648. stopThread (4000);
  29649. deleteAndZero (socket);
  29650. }
  29651. void InterprocessConnectionServer::run()
  29652. {
  29653. while ((! threadShouldExit()) && socket != 0)
  29654. {
  29655. StreamingSocket* const clientSocket = socket->waitForNextConnection();
  29656. if (clientSocket != 0)
  29657. {
  29658. InterprocessConnection* newConnection = createConnectionObject();
  29659. if (newConnection != 0)
  29660. {
  29661. newConnection->initialiseWithSocket (clientSocket);
  29662. }
  29663. else
  29664. {
  29665. delete clientSocket;
  29666. }
  29667. }
  29668. }
  29669. }
  29670. END_JUCE_NAMESPACE
  29671. /********* End of inlined file: juce_InterprocessConnectionServer.cpp *********/
  29672. /********* Start of inlined file: juce_Message.cpp *********/
  29673. BEGIN_JUCE_NAMESPACE
  29674. Message::Message() throw()
  29675. {
  29676. }
  29677. Message::~Message() throw()
  29678. {
  29679. }
  29680. Message::Message (const int intParameter1_,
  29681. const int intParameter2_,
  29682. const int intParameter3_,
  29683. void* const pointerParameter_) throw()
  29684. : intParameter1 (intParameter1_),
  29685. intParameter2 (intParameter2_),
  29686. intParameter3 (intParameter3_),
  29687. pointerParameter (pointerParameter_)
  29688. {
  29689. }
  29690. END_JUCE_NAMESPACE
  29691. /********* End of inlined file: juce_Message.cpp *********/
  29692. /********* Start of inlined file: juce_MessageListener.cpp *********/
  29693. BEGIN_JUCE_NAMESPACE
  29694. MessageListener::MessageListener() throw()
  29695. {
  29696. // are you trying to create a messagelistener before or after juce has been intialised??
  29697. jassert (MessageManager::instance != 0);
  29698. if (MessageManager::instance != 0)
  29699. MessageManager::instance->messageListeners.add (this);
  29700. }
  29701. MessageListener::~MessageListener()
  29702. {
  29703. if (MessageManager::instance != 0)
  29704. MessageManager::instance->messageListeners.removeValue (this);
  29705. }
  29706. void MessageListener::postMessage (Message* const message) const throw()
  29707. {
  29708. message->messageRecipient = const_cast <MessageListener*> (this);
  29709. if (MessageManager::instance == 0)
  29710. MessageManager::getInstance();
  29711. MessageManager::instance->postMessageToQueue (message);
  29712. }
  29713. bool MessageListener::isValidMessageListener() const throw()
  29714. {
  29715. return (MessageManager::instance != 0)
  29716. && MessageManager::instance->messageListeners.contains (this);
  29717. }
  29718. END_JUCE_NAMESPACE
  29719. /********* End of inlined file: juce_MessageListener.cpp *********/
  29720. /********* Start of inlined file: juce_MessageManager.cpp *********/
  29721. BEGIN_JUCE_NAMESPACE
  29722. // platform-specific functions..
  29723. bool juce_dispatchNextMessageOnSystemQueue (bool returnIfNoPendingMessages);
  29724. bool juce_postMessageToSystemQueue (void* message);
  29725. MessageManager* MessageManager::instance = 0;
  29726. static const int quitMessageId = 0xfffff321;
  29727. MessageManager::MessageManager() throw()
  29728. : broadcastListeners (0),
  29729. quitMessagePosted (false),
  29730. quitMessageReceived (false),
  29731. threadWithLock (0)
  29732. {
  29733. messageThreadId = Thread::getCurrentThreadId();
  29734. }
  29735. MessageManager::~MessageManager() throw()
  29736. {
  29737. deleteAndZero (broadcastListeners);
  29738. doPlatformSpecificShutdown();
  29739. jassert (instance == this);
  29740. instance = 0; // do this last in case this instance is still needed by doPlatformSpecificShutdown()
  29741. }
  29742. MessageManager* MessageManager::getInstance() throw()
  29743. {
  29744. if (instance == 0)
  29745. {
  29746. instance = new MessageManager();
  29747. doPlatformSpecificInitialisation();
  29748. }
  29749. return instance;
  29750. }
  29751. void MessageManager::postMessageToQueue (Message* const message)
  29752. {
  29753. if (quitMessagePosted || ! juce_postMessageToSystemQueue (message))
  29754. delete message;
  29755. }
  29756. CallbackMessage::CallbackMessage() throw() {}
  29757. CallbackMessage::~CallbackMessage() throw() {}
  29758. void CallbackMessage::post()
  29759. {
  29760. if (MessageManager::instance != 0)
  29761. MessageManager::instance->postCallbackMessage (this);
  29762. }
  29763. void MessageManager::postCallbackMessage (Message* const message)
  29764. {
  29765. message->messageRecipient = 0;
  29766. postMessageToQueue (message);
  29767. }
  29768. // not for public use..
  29769. void MessageManager::deliverMessage (void* message)
  29770. {
  29771. Message* const m = (Message*) message;
  29772. MessageListener* const recipient = m->messageRecipient;
  29773. JUCE_TRY
  29774. {
  29775. if (messageListeners.contains (recipient))
  29776. {
  29777. recipient->handleMessage (*m);
  29778. }
  29779. else if (recipient == 0)
  29780. {
  29781. if (m->intParameter1 == quitMessageId)
  29782. {
  29783. quitMessageReceived = true;
  29784. }
  29785. else if (dynamic_cast <CallbackMessage*> (m) != 0)
  29786. {
  29787. (dynamic_cast <CallbackMessage*> (m))->messageCallback();
  29788. }
  29789. }
  29790. }
  29791. JUCE_CATCH_EXCEPTION
  29792. delete m;
  29793. }
  29794. #if ! JUCE_MAC
  29795. void MessageManager::runDispatchLoop()
  29796. {
  29797. jassert (isThisTheMessageThread()); // must only be called by the message thread
  29798. runDispatchLoopUntil (-1);
  29799. }
  29800. void MessageManager::stopDispatchLoop()
  29801. {
  29802. Message* const m = new Message (quitMessageId, 0, 0, 0);
  29803. m->messageRecipient = 0;
  29804. postMessageToQueue (m);
  29805. quitMessagePosted = true;
  29806. }
  29807. bool MessageManager::runDispatchLoopUntil (int millisecondsToRunFor)
  29808. {
  29809. jassert (isThisTheMessageThread()); // must only be called by the message thread
  29810. const int64 endTime = Time::currentTimeMillis() + millisecondsToRunFor;
  29811. while ((millisecondsToRunFor < 0 || endTime > Time::currentTimeMillis())
  29812. && ! quitMessageReceived)
  29813. {
  29814. JUCE_TRY
  29815. {
  29816. if (! juce_dispatchNextMessageOnSystemQueue (millisecondsToRunFor >= 0))
  29817. {
  29818. const int msToWait = (int) (endTime - Time::currentTimeMillis());
  29819. if (msToWait > 0)
  29820. Thread::sleep (jmin (5, msToWait));
  29821. }
  29822. }
  29823. JUCE_CATCH_EXCEPTION
  29824. }
  29825. return ! quitMessageReceived;
  29826. }
  29827. #endif
  29828. void MessageManager::deliverBroadcastMessage (const String& value)
  29829. {
  29830. if (broadcastListeners != 0)
  29831. broadcastListeners->sendActionMessage (value);
  29832. }
  29833. void MessageManager::registerBroadcastListener (ActionListener* const listener) throw()
  29834. {
  29835. if (broadcastListeners == 0)
  29836. broadcastListeners = new ActionListenerList();
  29837. broadcastListeners->addActionListener (listener);
  29838. }
  29839. void MessageManager::deregisterBroadcastListener (ActionListener* const listener) throw()
  29840. {
  29841. if (broadcastListeners != 0)
  29842. broadcastListeners->removeActionListener (listener);
  29843. }
  29844. bool MessageManager::isThisTheMessageThread() const throw()
  29845. {
  29846. return Thread::getCurrentThreadId() == messageThreadId;
  29847. }
  29848. void MessageManager::setCurrentMessageThread (const Thread::ThreadID threadId) throw()
  29849. {
  29850. messageThreadId = threadId;
  29851. }
  29852. bool MessageManager::currentThreadHasLockedMessageManager() const throw()
  29853. {
  29854. const Thread::ThreadID thisThread = Thread::getCurrentThreadId();
  29855. return thisThread == messageThreadId || thisThread == threadWithLock;
  29856. }
  29857. /* The only safe way to lock the message thread while another thread does
  29858. some work is by posting a special message, whose purpose is to tie up the event
  29859. loop until the other thread has finished its business.
  29860. Any other approach can get horribly deadlocked if the OS uses its own hidden locks which
  29861. get locked before making an event callback, because if the same OS lock gets indirectly
  29862. accessed from another thread inside a MM lock, you're screwed. (this is exactly what happens
  29863. in Cocoa).
  29864. */
  29865. class SharedLockingEvents : public ReferenceCountedObject
  29866. {
  29867. public:
  29868. SharedLockingEvents() throw() {}
  29869. ~SharedLockingEvents() {}
  29870. /* This class just holds a couple of events to communicate between the MMLockMessage
  29871. and the MessageManagerLock. Because both of these objects may be deleted at any time,
  29872. this shared data must be kept in a separate, ref-counted container. */
  29873. WaitableEvent lockedEvent, releaseEvent;
  29874. };
  29875. class MMLockMessage : public CallbackMessage
  29876. {
  29877. public:
  29878. MMLockMessage (SharedLockingEvents* const events_) throw()
  29879. : events (events_)
  29880. {}
  29881. ~MMLockMessage() throw() {}
  29882. ReferenceCountedObjectPtr <SharedLockingEvents> events;
  29883. void messageCallback()
  29884. {
  29885. events->lockedEvent.signal();
  29886. events->releaseEvent.wait();
  29887. }
  29888. juce_UseDebuggingNewOperator
  29889. MMLockMessage (const MMLockMessage&);
  29890. const MMLockMessage& operator= (const MMLockMessage&);
  29891. };
  29892. MessageManagerLock::MessageManagerLock (Thread* const threadToCheck) throw()
  29893. : locked (false),
  29894. needsUnlocking (false)
  29895. {
  29896. init (threadToCheck, 0);
  29897. }
  29898. MessageManagerLock::MessageManagerLock (ThreadPoolJob* const jobToCheckForExitSignal) throw()
  29899. : locked (false),
  29900. needsUnlocking (false)
  29901. {
  29902. init (0, jobToCheckForExitSignal);
  29903. }
  29904. void MessageManagerLock::init (Thread* const threadToCheck, ThreadPoolJob* const job) throw()
  29905. {
  29906. if (MessageManager::instance != 0)
  29907. {
  29908. if (MessageManager::instance->currentThreadHasLockedMessageManager())
  29909. {
  29910. locked = true; // either we're on the message thread, or this is a re-entrant call.
  29911. }
  29912. else
  29913. {
  29914. if (threadToCheck == 0 && job == 0)
  29915. {
  29916. MessageManager::instance->lockingLock.enter();
  29917. }
  29918. else
  29919. {
  29920. while (! MessageManager::instance->lockingLock.tryEnter())
  29921. {
  29922. if ((threadToCheck != 0 && threadToCheck->threadShouldExit())
  29923. || (job != 0 && job->shouldExit()))
  29924. return;
  29925. Thread::sleep (1);
  29926. }
  29927. }
  29928. SharedLockingEvents* const events = new SharedLockingEvents();
  29929. sharedEvents = events;
  29930. events->incReferenceCount();
  29931. (new MMLockMessage (events))->post();
  29932. while (! events->lockedEvent.wait (50))
  29933. {
  29934. if ((threadToCheck != 0 && threadToCheck->threadShouldExit())
  29935. || (job != 0 && job->shouldExit()))
  29936. {
  29937. events->releaseEvent.signal();
  29938. events->decReferenceCount();
  29939. MessageManager::instance->lockingLock.exit();
  29940. return;
  29941. }
  29942. }
  29943. jassert (MessageManager::instance->threadWithLock == 0);
  29944. MessageManager::instance->threadWithLock = Thread::getCurrentThreadId();
  29945. locked = true;
  29946. needsUnlocking = true;
  29947. }
  29948. }
  29949. }
  29950. MessageManagerLock::~MessageManagerLock() throw()
  29951. {
  29952. if (needsUnlocking && MessageManager::instance != 0)
  29953. {
  29954. jassert (MessageManager::instance->currentThreadHasLockedMessageManager());
  29955. ((SharedLockingEvents*) sharedEvents)->releaseEvent.signal();
  29956. ((SharedLockingEvents*) sharedEvents)->decReferenceCount();
  29957. MessageManager::instance->threadWithLock = 0;
  29958. MessageManager::instance->lockingLock.exit();
  29959. }
  29960. }
  29961. END_JUCE_NAMESPACE
  29962. /********* End of inlined file: juce_MessageManager.cpp *********/
  29963. /********* Start of inlined file: juce_MultiTimer.cpp *********/
  29964. BEGIN_JUCE_NAMESPACE
  29965. class InternalMultiTimerCallback : public Timer
  29966. {
  29967. public:
  29968. InternalMultiTimerCallback (const int timerId_, MultiTimer& owner_)
  29969. : timerId (timerId_),
  29970. owner (owner_)
  29971. {
  29972. }
  29973. ~InternalMultiTimerCallback()
  29974. {
  29975. }
  29976. void timerCallback()
  29977. {
  29978. owner.timerCallback (timerId);
  29979. }
  29980. const int timerId;
  29981. private:
  29982. MultiTimer& owner;
  29983. };
  29984. MultiTimer::MultiTimer() throw()
  29985. {
  29986. }
  29987. MultiTimer::MultiTimer (const MultiTimer&) throw()
  29988. {
  29989. }
  29990. MultiTimer::~MultiTimer()
  29991. {
  29992. const ScopedLock sl (timerListLock);
  29993. for (int i = timers.size(); --i >= 0;)
  29994. delete (InternalMultiTimerCallback*) timers.getUnchecked(i);
  29995. timers.clear();
  29996. }
  29997. void MultiTimer::startTimer (const int timerId, const int intervalInMilliseconds) throw()
  29998. {
  29999. const ScopedLock sl (timerListLock);
  30000. for (int i = timers.size(); --i >= 0;)
  30001. {
  30002. InternalMultiTimerCallback* const t = (InternalMultiTimerCallback*) timers.getUnchecked(i);
  30003. if (t->timerId == timerId)
  30004. {
  30005. t->startTimer (intervalInMilliseconds);
  30006. return;
  30007. }
  30008. }
  30009. InternalMultiTimerCallback* const newTimer = new InternalMultiTimerCallback (timerId, *this);
  30010. timers.add (newTimer);
  30011. newTimer->startTimer (intervalInMilliseconds);
  30012. }
  30013. void MultiTimer::stopTimer (const int timerId) throw()
  30014. {
  30015. const ScopedLock sl (timerListLock);
  30016. for (int i = timers.size(); --i >= 0;)
  30017. {
  30018. InternalMultiTimerCallback* const t = (InternalMultiTimerCallback*) timers.getUnchecked(i);
  30019. if (t->timerId == timerId)
  30020. t->stopTimer();
  30021. }
  30022. }
  30023. bool MultiTimer::isTimerRunning (const int timerId) const throw()
  30024. {
  30025. const ScopedLock sl (timerListLock);
  30026. for (int i = timers.size(); --i >= 0;)
  30027. {
  30028. const InternalMultiTimerCallback* const t = (InternalMultiTimerCallback*) timers.getUnchecked(i);
  30029. if (t->timerId == timerId)
  30030. return t->isTimerRunning();
  30031. }
  30032. return false;
  30033. }
  30034. int MultiTimer::getTimerInterval (const int timerId) const throw()
  30035. {
  30036. const ScopedLock sl (timerListLock);
  30037. for (int i = timers.size(); --i >= 0;)
  30038. {
  30039. const InternalMultiTimerCallback* const t = (InternalMultiTimerCallback*) timers.getUnchecked(i);
  30040. if (t->timerId == timerId)
  30041. return t->getTimerInterval();
  30042. }
  30043. return 0;
  30044. }
  30045. END_JUCE_NAMESPACE
  30046. /********* End of inlined file: juce_MultiTimer.cpp *********/
  30047. /********* Start of inlined file: juce_Timer.cpp *********/
  30048. BEGIN_JUCE_NAMESPACE
  30049. class InternalTimerThread : private Thread,
  30050. private MessageListener,
  30051. private DeletedAtShutdown,
  30052. private AsyncUpdater
  30053. {
  30054. private:
  30055. friend class Timer;
  30056. static InternalTimerThread* instance;
  30057. static CriticalSection lock;
  30058. Timer* volatile firstTimer;
  30059. bool volatile callbackNeeded;
  30060. InternalTimerThread (const InternalTimerThread&);
  30061. const InternalTimerThread& operator= (const InternalTimerThread&);
  30062. void addTimer (Timer* const t) throw()
  30063. {
  30064. #ifdef JUCE_DEBUG
  30065. Timer* tt = firstTimer;
  30066. while (tt != 0)
  30067. {
  30068. // trying to add a timer that's already here - shouldn't get to this point,
  30069. // so if you get this assertion, let me know!
  30070. jassert (tt != t);
  30071. tt = tt->next;
  30072. }
  30073. jassert (t->previous == 0 && t->next == 0);
  30074. #endif
  30075. Timer* i = firstTimer;
  30076. if (i == 0 || i->countdownMs > t->countdownMs)
  30077. {
  30078. t->next = firstTimer;
  30079. firstTimer = t;
  30080. }
  30081. else
  30082. {
  30083. while (i->next != 0 && i->next->countdownMs <= t->countdownMs)
  30084. i = i->next;
  30085. jassert (i != 0);
  30086. t->next = i->next;
  30087. t->previous = i;
  30088. i->next = t;
  30089. }
  30090. if (t->next != 0)
  30091. t->next->previous = t;
  30092. jassert ((t->next == 0 || t->next->countdownMs >= t->countdownMs)
  30093. && (t->previous == 0 || t->previous->countdownMs <= t->countdownMs));
  30094. notify();
  30095. }
  30096. void removeTimer (Timer* const t) throw()
  30097. {
  30098. #ifdef JUCE_DEBUG
  30099. Timer* tt = firstTimer;
  30100. bool found = false;
  30101. while (tt != 0)
  30102. {
  30103. if (tt == t)
  30104. {
  30105. found = true;
  30106. break;
  30107. }
  30108. tt = tt->next;
  30109. }
  30110. // trying to remove a timer that's not here - shouldn't get to this point,
  30111. // so if you get this assertion, let me know!
  30112. jassert (found);
  30113. #endif
  30114. if (t->previous != 0)
  30115. {
  30116. jassert (firstTimer != t);
  30117. t->previous->next = t->next;
  30118. }
  30119. else
  30120. {
  30121. jassert (firstTimer == t);
  30122. firstTimer = t->next;
  30123. }
  30124. if (t->next != 0)
  30125. t->next->previous = t->previous;
  30126. t->next = 0;
  30127. t->previous = 0;
  30128. }
  30129. void decrementAllCounters (const int numMillisecs) const
  30130. {
  30131. Timer* t = firstTimer;
  30132. while (t != 0)
  30133. {
  30134. t->countdownMs -= numMillisecs;
  30135. t = t->next;
  30136. }
  30137. }
  30138. void handleAsyncUpdate()
  30139. {
  30140. startThread (7);
  30141. }
  30142. public:
  30143. InternalTimerThread()
  30144. : Thread ("Juce Timer"),
  30145. firstTimer (0),
  30146. callbackNeeded (false)
  30147. {
  30148. triggerAsyncUpdate();
  30149. }
  30150. ~InternalTimerThread() throw()
  30151. {
  30152. stopThread (4000);
  30153. jassert (instance == this || instance == 0);
  30154. if (instance == this)
  30155. instance = 0;
  30156. }
  30157. void run()
  30158. {
  30159. uint32 lastTime = Time::getMillisecondCounter();
  30160. while (! threadShouldExit())
  30161. {
  30162. uint32 now = Time::getMillisecondCounter();
  30163. if (now <= lastTime)
  30164. {
  30165. wait (2);
  30166. continue;
  30167. }
  30168. const int elapsed = now - lastTime;
  30169. lastTime = now;
  30170. lock.enter();
  30171. decrementAllCounters (elapsed);
  30172. const int timeUntilFirstTimer = (firstTimer != 0) ? firstTimer->countdownMs
  30173. : 1000;
  30174. lock.exit();
  30175. if (timeUntilFirstTimer <= 0)
  30176. {
  30177. callbackNeeded = true;
  30178. postMessage (new Message());
  30179. // sometimes, our message could get discarded by the OS (particularly when running as an RTAS when the app has a modal loop),
  30180. // so this is how long to wait before assuming the message has been lost and trying again.
  30181. const uint32 messageDeliveryTimeout = now + 2000;
  30182. while (callbackNeeded)
  30183. {
  30184. wait (4);
  30185. if (threadShouldExit())
  30186. return;
  30187. now = Time::getMillisecondCounter();
  30188. if (now > messageDeliveryTimeout)
  30189. break;
  30190. }
  30191. }
  30192. else
  30193. {
  30194. // don't wait for too long because running this loop also helps keep the
  30195. // Time::getApproximateMillisecondTimer value stay up-to-date
  30196. wait (jlimit (1, 50, timeUntilFirstTimer));
  30197. }
  30198. }
  30199. }
  30200. void handleMessage (const Message&)
  30201. {
  30202. const ScopedLock sl (lock);
  30203. while (firstTimer != 0 && firstTimer->countdownMs <= 0)
  30204. {
  30205. Timer* const t = firstTimer;
  30206. t->countdownMs = t->periodMs;
  30207. removeTimer (t);
  30208. addTimer (t);
  30209. const ScopedUnlock ul (lock);
  30210. JUCE_TRY
  30211. {
  30212. t->timerCallback();
  30213. }
  30214. JUCE_CATCH_EXCEPTION
  30215. }
  30216. callbackNeeded = false;
  30217. }
  30218. static void callAnyTimersSynchronously()
  30219. {
  30220. if (InternalTimerThread::instance != 0)
  30221. {
  30222. const Message m;
  30223. InternalTimerThread::instance->handleMessage (m);
  30224. }
  30225. }
  30226. static inline void add (Timer* const tim) throw()
  30227. {
  30228. if (instance == 0)
  30229. instance = new InternalTimerThread();
  30230. const ScopedLock sl (instance->lock);
  30231. instance->addTimer (tim);
  30232. }
  30233. static inline void remove (Timer* const tim) throw()
  30234. {
  30235. if (instance != 0)
  30236. {
  30237. const ScopedLock sl (instance->lock);
  30238. instance->removeTimer (tim);
  30239. }
  30240. }
  30241. static inline void resetCounter (Timer* const tim,
  30242. const int newCounter) throw()
  30243. {
  30244. if (instance != 0)
  30245. {
  30246. tim->countdownMs = newCounter;
  30247. tim->periodMs = newCounter;
  30248. if ((tim->next != 0 && tim->next->countdownMs < tim->countdownMs)
  30249. || (tim->previous != 0 && tim->previous->countdownMs > tim->countdownMs))
  30250. {
  30251. const ScopedLock sl (instance->lock);
  30252. instance->removeTimer (tim);
  30253. instance->addTimer (tim);
  30254. }
  30255. }
  30256. }
  30257. };
  30258. InternalTimerThread* InternalTimerThread::instance = 0;
  30259. CriticalSection InternalTimerThread::lock;
  30260. void juce_callAnyTimersSynchronously()
  30261. {
  30262. InternalTimerThread::callAnyTimersSynchronously();
  30263. }
  30264. #ifdef JUCE_DEBUG
  30265. static SortedSet <Timer*> activeTimers;
  30266. #endif
  30267. Timer::Timer() throw()
  30268. : countdownMs (0),
  30269. periodMs (0),
  30270. previous (0),
  30271. next (0)
  30272. {
  30273. #ifdef JUCE_DEBUG
  30274. activeTimers.add (this);
  30275. #endif
  30276. }
  30277. Timer::Timer (const Timer&) throw()
  30278. : countdownMs (0),
  30279. periodMs (0),
  30280. previous (0),
  30281. next (0)
  30282. {
  30283. #ifdef JUCE_DEBUG
  30284. activeTimers.add (this);
  30285. #endif
  30286. }
  30287. Timer::~Timer()
  30288. {
  30289. stopTimer();
  30290. #ifdef JUCE_DEBUG
  30291. activeTimers.removeValue (this);
  30292. #endif
  30293. }
  30294. void Timer::startTimer (const int interval) throw()
  30295. {
  30296. const ScopedLock sl (InternalTimerThread::lock);
  30297. #ifdef JUCE_DEBUG
  30298. // this isn't a valid object! Your timer might be a dangling pointer or something..
  30299. jassert (activeTimers.contains (this));
  30300. #endif
  30301. if (periodMs == 0)
  30302. {
  30303. countdownMs = interval;
  30304. periodMs = jmax (1, interval);
  30305. InternalTimerThread::add (this);
  30306. }
  30307. else
  30308. {
  30309. InternalTimerThread::resetCounter (this, interval);
  30310. }
  30311. }
  30312. void Timer::stopTimer() throw()
  30313. {
  30314. const ScopedLock sl (InternalTimerThread::lock);
  30315. #ifdef JUCE_DEBUG
  30316. // this isn't a valid object! Your timer might be a dangling pointer or something..
  30317. jassert (activeTimers.contains (this));
  30318. #endif
  30319. if (periodMs > 0)
  30320. {
  30321. InternalTimerThread::remove (this);
  30322. periodMs = 0;
  30323. }
  30324. }
  30325. END_JUCE_NAMESPACE
  30326. /********* End of inlined file: juce_Timer.cpp *********/
  30327. /********* Start of inlined file: juce_Component.cpp *********/
  30328. BEGIN_JUCE_NAMESPACE
  30329. Component* Component::componentUnderMouse = 0;
  30330. Component* Component::currentlyFocusedComponent = 0;
  30331. static Array <Component*> modalComponentStack (4), modalComponentReturnValueKeys (4);
  30332. static Array <int> modalReturnValues (4);
  30333. static const int customCommandMessage = 0x7fff0001;
  30334. static const int exitModalStateMessage = 0x7fff0002;
  30335. // these are also used by ComponentPeer
  30336. int64 juce_recentMouseDownTimes [4] = { 0, 0, 0, 0 };
  30337. int juce_recentMouseDownX [4] = { 0, 0, 0, 0 };
  30338. int juce_recentMouseDownY [4] = { 0, 0, 0, 0 };
  30339. Component* juce_recentMouseDownComponent [4] = { 0, 0, 0, 0 };
  30340. int juce_LastMousePosX = 0;
  30341. int juce_LastMousePosY = 0;
  30342. int juce_MouseClickCounter = 0;
  30343. bool juce_MouseHasMovedSignificantlySincePressed = false;
  30344. static int countMouseClicks() throw()
  30345. {
  30346. int numClicks = 0;
  30347. if (juce_recentMouseDownTimes[0] != 0)
  30348. {
  30349. if (! juce_MouseHasMovedSignificantlySincePressed)
  30350. ++numClicks;
  30351. for (int i = 1; i < numElementsInArray (juce_recentMouseDownTimes); ++i)
  30352. {
  30353. if (juce_recentMouseDownTimes[0] - juce_recentMouseDownTimes [i]
  30354. < (int) (MouseEvent::getDoubleClickTimeout() * (1.0 + 0.25 * (i - 1)))
  30355. && abs (juce_recentMouseDownX[0] - juce_recentMouseDownX[i]) < 8
  30356. && abs (juce_recentMouseDownY[0] - juce_recentMouseDownY[i]) < 8
  30357. && juce_recentMouseDownComponent[0] == juce_recentMouseDownComponent [i])
  30358. {
  30359. ++numClicks;
  30360. }
  30361. else
  30362. {
  30363. break;
  30364. }
  30365. }
  30366. }
  30367. return numClicks;
  30368. }
  30369. static int unboundedMouseOffsetX = 0;
  30370. static int unboundedMouseOffsetY = 0;
  30371. static bool isUnboundedMouseModeOn = false;
  30372. static bool isCursorVisibleUntilOffscreen;
  30373. #define checkMessageManagerIsLocked jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  30374. static uint32 nextComponentUID = 0;
  30375. Component::Component() throw()
  30376. : parentComponent_ (0),
  30377. componentUID (++nextComponentUID),
  30378. numDeepMouseListeners (0),
  30379. childComponentList_ (16),
  30380. lookAndFeel_ (0),
  30381. effect_ (0),
  30382. bufferedImage_ (0),
  30383. mouseListeners_ (0),
  30384. keyListeners_ (0),
  30385. componentListeners_ (0),
  30386. propertySet_ (0),
  30387. componentFlags_ (0)
  30388. {
  30389. }
  30390. Component::Component (const String& name) throw()
  30391. : componentName_ (name),
  30392. parentComponent_ (0),
  30393. componentUID (++nextComponentUID),
  30394. numDeepMouseListeners (0),
  30395. childComponentList_ (16),
  30396. lookAndFeel_ (0),
  30397. effect_ (0),
  30398. bufferedImage_ (0),
  30399. mouseListeners_ (0),
  30400. keyListeners_ (0),
  30401. componentListeners_ (0),
  30402. propertySet_ (0),
  30403. componentFlags_ (0)
  30404. {
  30405. }
  30406. Component::~Component()
  30407. {
  30408. if (parentComponent_ != 0)
  30409. {
  30410. parentComponent_->removeChildComponent (this);
  30411. }
  30412. else if ((currentlyFocusedComponent == this)
  30413. || isParentOf (currentlyFocusedComponent))
  30414. {
  30415. giveAwayFocus();
  30416. }
  30417. if (componentUnderMouse == this)
  30418. componentUnderMouse = 0;
  30419. if (flags.hasHeavyweightPeerFlag)
  30420. removeFromDesktop();
  30421. modalComponentStack.removeValue (this);
  30422. for (int i = childComponentList_.size(); --i >= 0;)
  30423. childComponentList_.getUnchecked(i)->parentComponent_ = 0;
  30424. delete bufferedImage_;
  30425. delete mouseListeners_;
  30426. delete keyListeners_;
  30427. delete componentListeners_;
  30428. delete propertySet_;
  30429. }
  30430. void Component::setName (const String& name)
  30431. {
  30432. // if component methods are being called from threads other than the message
  30433. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  30434. checkMessageManagerIsLocked
  30435. if (componentName_ != name)
  30436. {
  30437. componentName_ = name;
  30438. if (flags.hasHeavyweightPeerFlag)
  30439. {
  30440. ComponentPeer* const peer = getPeer();
  30441. jassert (peer != 0);
  30442. if (peer != 0)
  30443. peer->setTitle (name);
  30444. }
  30445. if (componentListeners_ != 0)
  30446. {
  30447. const ComponentDeletionWatcher deletionChecker (this);
  30448. for (int i = componentListeners_->size(); --i >= 0;)
  30449. {
  30450. ((ComponentListener*) componentListeners_->getUnchecked (i))
  30451. ->componentNameChanged (*this);
  30452. if (deletionChecker.hasBeenDeleted())
  30453. return;
  30454. i = jmin (i, componentListeners_->size());
  30455. }
  30456. }
  30457. }
  30458. }
  30459. void Component::setVisible (bool shouldBeVisible)
  30460. {
  30461. if (flags.visibleFlag != shouldBeVisible)
  30462. {
  30463. // if component methods are being called from threads other than the message
  30464. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  30465. checkMessageManagerIsLocked
  30466. const ComponentDeletionWatcher deletionChecker (this);
  30467. flags.visibleFlag = shouldBeVisible;
  30468. internalRepaint (0, 0, getWidth(), getHeight());
  30469. sendFakeMouseMove();
  30470. if (! shouldBeVisible)
  30471. {
  30472. if (currentlyFocusedComponent == this
  30473. || isParentOf (currentlyFocusedComponent))
  30474. {
  30475. if (parentComponent_ != 0)
  30476. parentComponent_->grabKeyboardFocus();
  30477. else
  30478. giveAwayFocus();
  30479. }
  30480. }
  30481. sendVisibilityChangeMessage();
  30482. if ((! deletionChecker.hasBeenDeleted()) && flags.hasHeavyweightPeerFlag)
  30483. {
  30484. ComponentPeer* const peer = getPeer();
  30485. jassert (peer != 0);
  30486. if (peer != 0)
  30487. {
  30488. peer->setVisible (shouldBeVisible);
  30489. internalHierarchyChanged();
  30490. }
  30491. }
  30492. }
  30493. }
  30494. void Component::visibilityChanged()
  30495. {
  30496. }
  30497. void Component::sendVisibilityChangeMessage()
  30498. {
  30499. const ComponentDeletionWatcher deletionChecker (this);
  30500. visibilityChanged();
  30501. if ((! deletionChecker.hasBeenDeleted()) && componentListeners_ != 0)
  30502. {
  30503. for (int i = componentListeners_->size(); --i >= 0;)
  30504. {
  30505. ((ComponentListener*) componentListeners_->getUnchecked (i))
  30506. ->componentVisibilityChanged (*this);
  30507. if (deletionChecker.hasBeenDeleted())
  30508. return;
  30509. i = jmin (i, componentListeners_->size());
  30510. }
  30511. }
  30512. }
  30513. bool Component::isShowing() const throw()
  30514. {
  30515. if (flags.visibleFlag)
  30516. {
  30517. if (parentComponent_ != 0)
  30518. {
  30519. return parentComponent_->isShowing();
  30520. }
  30521. else
  30522. {
  30523. const ComponentPeer* const peer = getPeer();
  30524. return peer != 0 && ! peer->isMinimised();
  30525. }
  30526. }
  30527. return false;
  30528. }
  30529. class FadeOutProxyComponent : public Component,
  30530. public Timer
  30531. {
  30532. public:
  30533. FadeOutProxyComponent (Component* comp,
  30534. const int fadeLengthMs,
  30535. const int deltaXToMove,
  30536. const int deltaYToMove,
  30537. const float scaleFactorAtEnd)
  30538. : lastTime (0),
  30539. alpha (1.0f),
  30540. scale (1.0f)
  30541. {
  30542. image = comp->createComponentSnapshot (Rectangle (0, 0, comp->getWidth(), comp->getHeight()));
  30543. setBounds (comp->getBounds());
  30544. comp->getParentComponent()->addAndMakeVisible (this);
  30545. toBehind (comp);
  30546. alphaChangePerMs = -1.0f / (float)fadeLengthMs;
  30547. centreX = comp->getX() + comp->getWidth() * 0.5f;
  30548. xChangePerMs = deltaXToMove / (float)fadeLengthMs;
  30549. centreY = comp->getY() + comp->getHeight() * 0.5f;
  30550. yChangePerMs = deltaYToMove / (float)fadeLengthMs;
  30551. scaleChangePerMs = (scaleFactorAtEnd - 1.0f) / (float)fadeLengthMs;
  30552. setInterceptsMouseClicks (false, false);
  30553. // 30 fps is enough for a fade, but we need a higher rate if it's moving as well..
  30554. startTimer (1000 / ((deltaXToMove == 0 && deltaYToMove == 0) ? 30 : 50));
  30555. }
  30556. ~FadeOutProxyComponent()
  30557. {
  30558. delete image;
  30559. }
  30560. void paint (Graphics& g)
  30561. {
  30562. g.setOpacity (alpha);
  30563. g.drawImage (image,
  30564. 0, 0, getWidth(), getHeight(),
  30565. 0, 0, image->getWidth(), image->getHeight());
  30566. }
  30567. void timerCallback()
  30568. {
  30569. const uint32 now = Time::getMillisecondCounter();
  30570. if (lastTime == 0)
  30571. lastTime = now;
  30572. const int msPassed = (now > lastTime) ? now - lastTime : 0;
  30573. lastTime = now;
  30574. alpha += alphaChangePerMs * msPassed;
  30575. if (alpha > 0)
  30576. {
  30577. if (xChangePerMs != 0.0f || yChangePerMs != 0.0f || scaleChangePerMs != 0.0f)
  30578. {
  30579. centreX += xChangePerMs * msPassed;
  30580. centreY += yChangePerMs * msPassed;
  30581. scale += scaleChangePerMs * msPassed;
  30582. const int w = roundFloatToInt (image->getWidth() * scale);
  30583. const int h = roundFloatToInt (image->getHeight() * scale);
  30584. setBounds (roundFloatToInt (centreX) - w / 2,
  30585. roundFloatToInt (centreY) - h / 2,
  30586. w, h);
  30587. }
  30588. repaint();
  30589. }
  30590. else
  30591. {
  30592. delete this;
  30593. }
  30594. }
  30595. juce_UseDebuggingNewOperator
  30596. private:
  30597. Image* image;
  30598. uint32 lastTime;
  30599. float alpha, alphaChangePerMs;
  30600. float centreX, xChangePerMs;
  30601. float centreY, yChangePerMs;
  30602. float scale, scaleChangePerMs;
  30603. FadeOutProxyComponent (const FadeOutProxyComponent&);
  30604. const FadeOutProxyComponent& operator= (const FadeOutProxyComponent&);
  30605. };
  30606. void Component::fadeOutComponent (const int millisecondsToFade,
  30607. const int deltaXToMove,
  30608. const int deltaYToMove,
  30609. const float scaleFactorAtEnd)
  30610. {
  30611. //xxx won't work for comps without parents
  30612. if (isShowing() && millisecondsToFade > 0)
  30613. new FadeOutProxyComponent (this, millisecondsToFade,
  30614. deltaXToMove, deltaYToMove, scaleFactorAtEnd);
  30615. setVisible (false);
  30616. }
  30617. bool Component::isValidComponent() const throw()
  30618. {
  30619. return (this != 0) && isValidMessageListener();
  30620. }
  30621. void* Component::getWindowHandle() const throw()
  30622. {
  30623. const ComponentPeer* const peer = getPeer();
  30624. if (peer != 0)
  30625. return peer->getNativeHandle();
  30626. return 0;
  30627. }
  30628. void Component::addToDesktop (int styleWanted, void* nativeWindowToAttachTo)
  30629. {
  30630. // if component methods are being called from threads other than the message
  30631. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  30632. checkMessageManagerIsLocked
  30633. if (! isOpaque())
  30634. styleWanted |= ComponentPeer::windowIsSemiTransparent;
  30635. int currentStyleFlags = 0;
  30636. // don't use getPeer(), so that we only get the peer that's specifically
  30637. // for this comp, and not for one of its parents.
  30638. ComponentPeer* peer = ComponentPeer::getPeerFor (this);
  30639. if (peer != 0)
  30640. currentStyleFlags = peer->getStyleFlags();
  30641. if (styleWanted != currentStyleFlags || ! flags.hasHeavyweightPeerFlag)
  30642. {
  30643. const ComponentDeletionWatcher deletionChecker (this);
  30644. #if JUCE_LINUX
  30645. // it's wise to give the component a non-zero size before
  30646. // putting it on the desktop, as X windows get confused by this, and
  30647. // a (1, 1) minimum size is enforced here.
  30648. setSize (jmax (1, getWidth()),
  30649. jmax (1, getHeight()));
  30650. #endif
  30651. int x = 0, y = 0;
  30652. relativePositionToGlobal (x, y);
  30653. bool wasFullscreen = false;
  30654. bool wasMinimised = false;
  30655. ComponentBoundsConstrainer* currentConstainer = 0;
  30656. Rectangle oldNonFullScreenBounds;
  30657. if (peer != 0)
  30658. {
  30659. wasFullscreen = peer->isFullScreen();
  30660. wasMinimised = peer->isMinimised();
  30661. currentConstainer = peer->getConstrainer();
  30662. oldNonFullScreenBounds = peer->getNonFullScreenBounds();
  30663. removeFromDesktop();
  30664. setTopLeftPosition (x, y);
  30665. }
  30666. if (parentComponent_ != 0)
  30667. parentComponent_->removeChildComponent (this);
  30668. if (! deletionChecker.hasBeenDeleted())
  30669. {
  30670. flags.hasHeavyweightPeerFlag = true;
  30671. peer = createNewPeer (styleWanted, nativeWindowToAttachTo);
  30672. Desktop::getInstance().addDesktopComponent (this);
  30673. bounds_.setPosition (x, y);
  30674. peer->setBounds (x, y, getWidth(), getHeight(), false);
  30675. peer->setVisible (isVisible());
  30676. if (wasFullscreen)
  30677. {
  30678. peer->setFullScreen (true);
  30679. peer->setNonFullScreenBounds (oldNonFullScreenBounds);
  30680. }
  30681. if (wasMinimised)
  30682. peer->setMinimised (true);
  30683. if (isAlwaysOnTop())
  30684. peer->setAlwaysOnTop (true);
  30685. peer->setConstrainer (currentConstainer);
  30686. repaint();
  30687. }
  30688. internalHierarchyChanged();
  30689. }
  30690. }
  30691. void Component::removeFromDesktop()
  30692. {
  30693. // if component methods are being called from threads other than the message
  30694. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  30695. checkMessageManagerIsLocked
  30696. if (flags.hasHeavyweightPeerFlag)
  30697. {
  30698. ComponentPeer* const peer = ComponentPeer::getPeerFor (this);
  30699. flags.hasHeavyweightPeerFlag = false;
  30700. jassert (peer != 0);
  30701. delete peer;
  30702. Desktop::getInstance().removeDesktopComponent (this);
  30703. }
  30704. }
  30705. bool Component::isOnDesktop() const throw()
  30706. {
  30707. return flags.hasHeavyweightPeerFlag;
  30708. }
  30709. void Component::userTriedToCloseWindow()
  30710. {
  30711. /* This means that the user's trying to get rid of your window with the 'close window' system
  30712. menu option (on windows) or possibly the task manager - you should really handle this
  30713. and delete or hide your component in an appropriate way.
  30714. If you want to ignore the event and don't want to trigger this assertion, just override
  30715. this method and do nothing.
  30716. */
  30717. jassertfalse
  30718. }
  30719. void Component::minimisationStateChanged (bool)
  30720. {
  30721. }
  30722. void Component::setOpaque (const bool shouldBeOpaque) throw()
  30723. {
  30724. if (shouldBeOpaque != flags.opaqueFlag)
  30725. {
  30726. flags.opaqueFlag = shouldBeOpaque;
  30727. if (flags.hasHeavyweightPeerFlag)
  30728. {
  30729. const ComponentPeer* const peer = ComponentPeer::getPeerFor (this);
  30730. if (peer != 0)
  30731. {
  30732. // to make it recreate the heavyweight window
  30733. addToDesktop (peer->getStyleFlags());
  30734. }
  30735. }
  30736. repaint();
  30737. }
  30738. }
  30739. bool Component::isOpaque() const throw()
  30740. {
  30741. return flags.opaqueFlag;
  30742. }
  30743. void Component::setBufferedToImage (const bool shouldBeBuffered) throw()
  30744. {
  30745. if (shouldBeBuffered != flags.bufferToImageFlag)
  30746. {
  30747. deleteAndZero (bufferedImage_);
  30748. flags.bufferToImageFlag = shouldBeBuffered;
  30749. }
  30750. }
  30751. void Component::toFront (const bool setAsForeground)
  30752. {
  30753. // if component methods are being called from threads other than the message
  30754. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  30755. checkMessageManagerIsLocked
  30756. if (flags.hasHeavyweightPeerFlag)
  30757. {
  30758. ComponentPeer* const peer = getPeer();
  30759. if (peer != 0)
  30760. {
  30761. peer->toFront (setAsForeground);
  30762. if (setAsForeground && ! hasKeyboardFocus (true))
  30763. grabKeyboardFocus();
  30764. }
  30765. }
  30766. else if (parentComponent_ != 0)
  30767. {
  30768. if (parentComponent_->childComponentList_.getLast() != this)
  30769. {
  30770. const int index = parentComponent_->childComponentList_.indexOf (this);
  30771. if (index >= 0)
  30772. {
  30773. int insertIndex = -1;
  30774. if (! flags.alwaysOnTopFlag)
  30775. {
  30776. insertIndex = parentComponent_->childComponentList_.size() - 1;
  30777. while (insertIndex > 0
  30778. && parentComponent_->childComponentList_.getUnchecked (insertIndex)->isAlwaysOnTop())
  30779. {
  30780. --insertIndex;
  30781. }
  30782. }
  30783. if (index != insertIndex)
  30784. {
  30785. parentComponent_->childComponentList_.move (index, insertIndex);
  30786. sendFakeMouseMove();
  30787. repaintParent();
  30788. }
  30789. }
  30790. }
  30791. if (setAsForeground)
  30792. {
  30793. internalBroughtToFront();
  30794. grabKeyboardFocus();
  30795. }
  30796. }
  30797. }
  30798. void Component::toBehind (Component* const other)
  30799. {
  30800. if (other != 0)
  30801. {
  30802. // the two components must belong to the same parent..
  30803. jassert (parentComponent_ == other->parentComponent_);
  30804. if (parentComponent_ != 0)
  30805. {
  30806. const int index = parentComponent_->childComponentList_.indexOf (this);
  30807. int otherIndex = parentComponent_->childComponentList_.indexOf (other);
  30808. if (index >= 0
  30809. && otherIndex >= 0
  30810. && index != otherIndex - 1
  30811. && other != this)
  30812. {
  30813. if (index < otherIndex)
  30814. --otherIndex;
  30815. parentComponent_->childComponentList_.move (index, otherIndex);
  30816. sendFakeMouseMove();
  30817. repaintParent();
  30818. }
  30819. }
  30820. else if (isOnDesktop())
  30821. {
  30822. jassert (other->isOnDesktop());
  30823. if (other->isOnDesktop())
  30824. {
  30825. ComponentPeer* const us = getPeer();
  30826. ComponentPeer* const them = other->getPeer();
  30827. jassert (us != 0 && them != 0);
  30828. if (us != 0 && them != 0)
  30829. us->toBehind (them);
  30830. }
  30831. }
  30832. }
  30833. }
  30834. void Component::toBack()
  30835. {
  30836. if (isOnDesktop())
  30837. {
  30838. jassertfalse //xxx need to add this to native window
  30839. }
  30840. else if (parentComponent_ != 0
  30841. && parentComponent_->childComponentList_.getFirst() != this)
  30842. {
  30843. const int index = parentComponent_->childComponentList_.indexOf (this);
  30844. if (index > 0)
  30845. {
  30846. int insertIndex = 0;
  30847. if (flags.alwaysOnTopFlag)
  30848. {
  30849. while (insertIndex < parentComponent_->childComponentList_.size()
  30850. && ! parentComponent_->childComponentList_.getUnchecked (insertIndex)->isAlwaysOnTop())
  30851. {
  30852. ++insertIndex;
  30853. }
  30854. }
  30855. if (index != insertIndex)
  30856. {
  30857. parentComponent_->childComponentList_.move (index, insertIndex);
  30858. sendFakeMouseMove();
  30859. repaintParent();
  30860. }
  30861. }
  30862. }
  30863. }
  30864. void Component::setAlwaysOnTop (const bool shouldStayOnTop)
  30865. {
  30866. if (shouldStayOnTop != flags.alwaysOnTopFlag)
  30867. {
  30868. flags.alwaysOnTopFlag = shouldStayOnTop;
  30869. if (isOnDesktop())
  30870. {
  30871. ComponentPeer* const peer = getPeer();
  30872. jassert (peer != 0);
  30873. if (peer != 0)
  30874. {
  30875. if (! peer->setAlwaysOnTop (shouldStayOnTop))
  30876. {
  30877. // some kinds of peer can't change their always-on-top status, so
  30878. // for these, we'll need to create a new window
  30879. const int oldFlags = peer->getStyleFlags();
  30880. removeFromDesktop();
  30881. addToDesktop (oldFlags);
  30882. }
  30883. }
  30884. }
  30885. if (shouldStayOnTop)
  30886. toFront (false);
  30887. internalHierarchyChanged();
  30888. }
  30889. }
  30890. bool Component::isAlwaysOnTop() const throw()
  30891. {
  30892. return flags.alwaysOnTopFlag;
  30893. }
  30894. int Component::proportionOfWidth (const float proportion) const throw()
  30895. {
  30896. return roundDoubleToInt (proportion * bounds_.getWidth());
  30897. }
  30898. int Component::proportionOfHeight (const float proportion) const throw()
  30899. {
  30900. return roundDoubleToInt (proportion * bounds_.getHeight());
  30901. }
  30902. int Component::getParentWidth() const throw()
  30903. {
  30904. return (parentComponent_ != 0) ? parentComponent_->getWidth()
  30905. : getParentMonitorArea().getWidth();
  30906. }
  30907. int Component::getParentHeight() const throw()
  30908. {
  30909. return (parentComponent_ != 0) ? parentComponent_->getHeight()
  30910. : getParentMonitorArea().getHeight();
  30911. }
  30912. int Component::getScreenX() const throw()
  30913. {
  30914. return (parentComponent_ != 0) ? parentComponent_->getScreenX() + getX()
  30915. : (flags.hasHeavyweightPeerFlag ? getPeer()->getScreenX()
  30916. : getX());
  30917. }
  30918. int Component::getScreenY() const throw()
  30919. {
  30920. return (parentComponent_ != 0) ? parentComponent_->getScreenY() + getY()
  30921. : (flags.hasHeavyweightPeerFlag ? getPeer()->getScreenY()
  30922. : getY());
  30923. }
  30924. void Component::relativePositionToGlobal (int& x, int& y) const throw()
  30925. {
  30926. const Component* c = this;
  30927. do
  30928. {
  30929. if (c->flags.hasHeavyweightPeerFlag)
  30930. {
  30931. c->getPeer()->relativePositionToGlobal (x, y);
  30932. break;
  30933. }
  30934. x += c->getX();
  30935. y += c->getY();
  30936. c = c->parentComponent_;
  30937. }
  30938. while (c != 0);
  30939. }
  30940. void Component::globalPositionToRelative (int& x, int& y) const throw()
  30941. {
  30942. if (flags.hasHeavyweightPeerFlag)
  30943. {
  30944. getPeer()->globalPositionToRelative (x, y);
  30945. }
  30946. else
  30947. {
  30948. if (parentComponent_ != 0)
  30949. parentComponent_->globalPositionToRelative (x, y);
  30950. x -= getX();
  30951. y -= getY();
  30952. }
  30953. }
  30954. void Component::relativePositionToOtherComponent (const Component* const targetComponent, int& x, int& y) const throw()
  30955. {
  30956. if (targetComponent != 0)
  30957. {
  30958. const Component* c = this;
  30959. do
  30960. {
  30961. if (c == targetComponent)
  30962. return;
  30963. if (c->flags.hasHeavyweightPeerFlag)
  30964. {
  30965. c->getPeer()->relativePositionToGlobal (x, y);
  30966. break;
  30967. }
  30968. x += c->getX();
  30969. y += c->getY();
  30970. c = c->parentComponent_;
  30971. }
  30972. while (c != 0);
  30973. targetComponent->globalPositionToRelative (x, y);
  30974. }
  30975. }
  30976. void Component::setBounds (int x, int y, int w, int h)
  30977. {
  30978. // if component methods are being called from threads other than the message
  30979. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  30980. checkMessageManagerIsLocked
  30981. if (w < 0) w = 0;
  30982. if (h < 0) h = 0;
  30983. const bool wasResized = (getWidth() != w || getHeight() != h);
  30984. const bool wasMoved = (getX() != x || getY() != y);
  30985. #ifdef JUCE_DEBUG
  30986. // It's a very bad idea to try to resize a window during its paint() method!
  30987. jassert (! (flags.isInsidePaintCall && wasResized && isOnDesktop()));
  30988. #endif
  30989. if (wasMoved || wasResized)
  30990. {
  30991. if (flags.visibleFlag)
  30992. {
  30993. // send a fake mouse move to trigger enter/exit messages if needed..
  30994. sendFakeMouseMove();
  30995. if (! flags.hasHeavyweightPeerFlag)
  30996. repaintParent();
  30997. }
  30998. bounds_.setBounds (x, y, w, h);
  30999. if (wasResized)
  31000. repaint();
  31001. else if (! flags.hasHeavyweightPeerFlag)
  31002. repaintParent();
  31003. if (flags.hasHeavyweightPeerFlag)
  31004. {
  31005. ComponentPeer* const peer = getPeer();
  31006. if (peer != 0)
  31007. {
  31008. if (wasMoved && wasResized)
  31009. peer->setBounds (getX(), getY(), getWidth(), getHeight(), false);
  31010. else if (wasMoved)
  31011. peer->setPosition (getX(), getY());
  31012. else if (wasResized)
  31013. peer->setSize (getWidth(), getHeight());
  31014. }
  31015. }
  31016. sendMovedResizedMessages (wasMoved, wasResized);
  31017. }
  31018. }
  31019. void Component::sendMovedResizedMessages (const bool wasMoved, const bool wasResized)
  31020. {
  31021. JUCE_TRY
  31022. {
  31023. if (wasMoved)
  31024. moved();
  31025. if (wasResized)
  31026. {
  31027. resized();
  31028. for (int i = childComponentList_.size(); --i >= 0;)
  31029. {
  31030. childComponentList_.getUnchecked(i)->parentSizeChanged();
  31031. i = jmin (i, childComponentList_.size());
  31032. }
  31033. }
  31034. if (parentComponent_ != 0)
  31035. parentComponent_->childBoundsChanged (this);
  31036. if (componentListeners_ != 0)
  31037. {
  31038. const ComponentDeletionWatcher deletionChecker (this);
  31039. for (int i = componentListeners_->size(); --i >= 0;)
  31040. {
  31041. ((ComponentListener*) componentListeners_->getUnchecked (i))
  31042. ->componentMovedOrResized (*this, wasMoved, wasResized);
  31043. if (deletionChecker.hasBeenDeleted())
  31044. return;
  31045. i = jmin (i, componentListeners_->size());
  31046. }
  31047. }
  31048. }
  31049. JUCE_CATCH_EXCEPTION
  31050. }
  31051. void Component::setSize (const int w, const int h)
  31052. {
  31053. setBounds (getX(), getY(), w, h);
  31054. }
  31055. void Component::setTopLeftPosition (const int x, const int y)
  31056. {
  31057. setBounds (x, y, getWidth(), getHeight());
  31058. }
  31059. void Component::setTopRightPosition (const int x, const int y)
  31060. {
  31061. setTopLeftPosition (x - getWidth(), y);
  31062. }
  31063. void Component::setBounds (const Rectangle& r)
  31064. {
  31065. setBounds (r.getX(),
  31066. r.getY(),
  31067. r.getWidth(),
  31068. r.getHeight());
  31069. }
  31070. void Component::setBoundsRelative (const float x, const float y,
  31071. const float w, const float h)
  31072. {
  31073. const int pw = getParentWidth();
  31074. const int ph = getParentHeight();
  31075. setBounds (roundFloatToInt (x * pw),
  31076. roundFloatToInt (y * ph),
  31077. roundFloatToInt (w * pw),
  31078. roundFloatToInt (h * ph));
  31079. }
  31080. void Component::setCentrePosition (const int x, const int y)
  31081. {
  31082. setTopLeftPosition (x - getWidth() / 2,
  31083. y - getHeight() / 2);
  31084. }
  31085. void Component::setCentreRelative (const float x, const float y)
  31086. {
  31087. setCentrePosition (roundFloatToInt (getParentWidth() * x),
  31088. roundFloatToInt (getParentHeight() * y));
  31089. }
  31090. void Component::centreWithSize (const int width, const int height)
  31091. {
  31092. setBounds ((getParentWidth() - width) / 2,
  31093. (getParentHeight() - height) / 2,
  31094. width,
  31095. height);
  31096. }
  31097. void Component::setBoundsInset (const BorderSize& borders)
  31098. {
  31099. setBounds (borders.getLeft(),
  31100. borders.getTop(),
  31101. getParentWidth() - (borders.getLeftAndRight()),
  31102. getParentHeight() - (borders.getTopAndBottom()));
  31103. }
  31104. void Component::setBoundsToFit (int x, int y, int width, int height,
  31105. const Justification& justification,
  31106. const bool onlyReduceInSize)
  31107. {
  31108. // it's no good calling this method unless both the component and
  31109. // target rectangle have a finite size.
  31110. jassert (getWidth() > 0 && getHeight() > 0 && width > 0 && height > 0);
  31111. if (getWidth() > 0 && getHeight() > 0
  31112. && width > 0 && height > 0)
  31113. {
  31114. int newW, newH;
  31115. if (onlyReduceInSize && getWidth() <= width && getHeight() <= height)
  31116. {
  31117. newW = getWidth();
  31118. newH = getHeight();
  31119. }
  31120. else
  31121. {
  31122. const double imageRatio = getHeight() / (double) getWidth();
  31123. const double targetRatio = height / (double) width;
  31124. if (imageRatio <= targetRatio)
  31125. {
  31126. newW = width;
  31127. newH = jmin (height, roundDoubleToInt (newW * imageRatio));
  31128. }
  31129. else
  31130. {
  31131. newH = height;
  31132. newW = jmin (width, roundDoubleToInt (newH / imageRatio));
  31133. }
  31134. }
  31135. if (newW > 0 && newH > 0)
  31136. {
  31137. int newX, newY;
  31138. justification.applyToRectangle (newX, newY, newW, newH,
  31139. x, y, width, height);
  31140. setBounds (newX, newY, newW, newH);
  31141. }
  31142. }
  31143. }
  31144. bool Component::hitTest (int x, int y)
  31145. {
  31146. if (! flags.ignoresMouseClicksFlag)
  31147. return true;
  31148. if (flags.allowChildMouseClicksFlag)
  31149. {
  31150. for (int i = getNumChildComponents(); --i >= 0;)
  31151. {
  31152. Component* const c = getChildComponent (i);
  31153. if (c->isVisible()
  31154. && c->bounds_.contains (x, y)
  31155. && c->hitTest (x - c->getX(),
  31156. y - c->getY()))
  31157. {
  31158. return true;
  31159. }
  31160. }
  31161. }
  31162. return false;
  31163. }
  31164. void Component::setInterceptsMouseClicks (const bool allowClicks,
  31165. const bool allowClicksOnChildComponents) throw()
  31166. {
  31167. flags.ignoresMouseClicksFlag = ! allowClicks;
  31168. flags.allowChildMouseClicksFlag = allowClicksOnChildComponents;
  31169. }
  31170. void Component::getInterceptsMouseClicks (bool& allowsClicksOnThisComponent,
  31171. bool& allowsClicksOnChildComponents) const throw()
  31172. {
  31173. allowsClicksOnThisComponent = ! flags.ignoresMouseClicksFlag;
  31174. allowsClicksOnChildComponents = flags.allowChildMouseClicksFlag;
  31175. }
  31176. bool Component::contains (const int x, const int y)
  31177. {
  31178. if (((unsigned int) x) < (unsigned int) getWidth()
  31179. && ((unsigned int) y) < (unsigned int) getHeight()
  31180. && hitTest (x, y))
  31181. {
  31182. if (parentComponent_ != 0)
  31183. {
  31184. return parentComponent_->contains (x + getX(),
  31185. y + getY());
  31186. }
  31187. else if (flags.hasHeavyweightPeerFlag)
  31188. {
  31189. const ComponentPeer* const peer = getPeer();
  31190. if (peer != 0)
  31191. return peer->contains (x, y, true);
  31192. }
  31193. }
  31194. return false;
  31195. }
  31196. bool Component::reallyContains (int x, int y, const bool returnTrueIfWithinAChild)
  31197. {
  31198. if (! contains (x, y))
  31199. return false;
  31200. Component* p = this;
  31201. while (p->parentComponent_ != 0)
  31202. {
  31203. x += p->getX();
  31204. y += p->getY();
  31205. p = p->parentComponent_;
  31206. }
  31207. const Component* const c = p->getComponentAt (x, y);
  31208. return (c == this) || (returnTrueIfWithinAChild && isParentOf (c));
  31209. }
  31210. Component* Component::getComponentAt (const int x, const int y)
  31211. {
  31212. if (flags.visibleFlag
  31213. && ((unsigned int) x) < (unsigned int) getWidth()
  31214. && ((unsigned int) y) < (unsigned int) getHeight()
  31215. && hitTest (x, y))
  31216. {
  31217. for (int i = childComponentList_.size(); --i >= 0;)
  31218. {
  31219. Component* const child = childComponentList_.getUnchecked(i);
  31220. Component* const c = child->getComponentAt (x - child->getX(),
  31221. y - child->getY());
  31222. if (c != 0)
  31223. return c;
  31224. }
  31225. return this;
  31226. }
  31227. return 0;
  31228. }
  31229. void Component::addChildComponent (Component* const child, int zOrder)
  31230. {
  31231. // if component methods are being called from threads other than the message
  31232. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31233. checkMessageManagerIsLocked
  31234. if (child != 0 && child->parentComponent_ != this)
  31235. {
  31236. if (child->parentComponent_ != 0)
  31237. child->parentComponent_->removeChildComponent (child);
  31238. else
  31239. child->removeFromDesktop();
  31240. child->parentComponent_ = this;
  31241. if (child->isVisible())
  31242. child->repaintParent();
  31243. if (! child->isAlwaysOnTop())
  31244. {
  31245. if (zOrder < 0 || zOrder > childComponentList_.size())
  31246. zOrder = childComponentList_.size();
  31247. while (zOrder > 0)
  31248. {
  31249. if (! childComponentList_.getUnchecked (zOrder - 1)->isAlwaysOnTop())
  31250. break;
  31251. --zOrder;
  31252. }
  31253. }
  31254. childComponentList_.insert (zOrder, child);
  31255. child->internalHierarchyChanged();
  31256. internalChildrenChanged();
  31257. }
  31258. }
  31259. void Component::addAndMakeVisible (Component* const child, int zOrder)
  31260. {
  31261. if (child != 0)
  31262. {
  31263. child->setVisible (true);
  31264. addChildComponent (child, zOrder);
  31265. }
  31266. }
  31267. void Component::removeChildComponent (Component* const child)
  31268. {
  31269. removeChildComponent (childComponentList_.indexOf (child));
  31270. }
  31271. Component* Component::removeChildComponent (const int index)
  31272. {
  31273. // if component methods are being called from threads other than the message
  31274. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31275. checkMessageManagerIsLocked
  31276. Component* const child = childComponentList_ [index];
  31277. if (child != 0)
  31278. {
  31279. sendFakeMouseMove();
  31280. child->repaintParent();
  31281. childComponentList_.remove (index);
  31282. child->parentComponent_ = 0;
  31283. JUCE_TRY
  31284. {
  31285. if ((currentlyFocusedComponent == child)
  31286. || child->isParentOf (currentlyFocusedComponent))
  31287. {
  31288. // get rid first to force the grabKeyboardFocus to change to us.
  31289. giveAwayFocus();
  31290. grabKeyboardFocus();
  31291. }
  31292. }
  31293. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  31294. catch (const std::exception& e)
  31295. {
  31296. currentlyFocusedComponent = 0;
  31297. Desktop::getInstance().triggerFocusCallback();
  31298. JUCEApplication::sendUnhandledException (&e, __FILE__, __LINE__);
  31299. }
  31300. catch (...)
  31301. {
  31302. currentlyFocusedComponent = 0;
  31303. Desktop::getInstance().triggerFocusCallback();
  31304. JUCEApplication::sendUnhandledException (0, __FILE__, __LINE__);
  31305. }
  31306. #endif
  31307. child->internalHierarchyChanged();
  31308. internalChildrenChanged();
  31309. }
  31310. return child;
  31311. }
  31312. void Component::removeAllChildren()
  31313. {
  31314. for (int i = childComponentList_.size(); --i >= 0;)
  31315. removeChildComponent (i);
  31316. }
  31317. void Component::deleteAllChildren()
  31318. {
  31319. for (int i = childComponentList_.size(); --i >= 0;)
  31320. delete (removeChildComponent (i));
  31321. }
  31322. int Component::getNumChildComponents() const throw()
  31323. {
  31324. return childComponentList_.size();
  31325. }
  31326. Component* Component::getChildComponent (const int index) const throw()
  31327. {
  31328. return childComponentList_ [index];
  31329. }
  31330. int Component::getIndexOfChildComponent (const Component* const child) const throw()
  31331. {
  31332. return childComponentList_.indexOf (const_cast <Component*> (child));
  31333. }
  31334. Component* Component::getTopLevelComponent() const throw()
  31335. {
  31336. const Component* comp = this;
  31337. while (comp->parentComponent_ != 0)
  31338. comp = comp->parentComponent_;
  31339. return (Component*) comp;
  31340. }
  31341. bool Component::isParentOf (const Component* possibleChild) const throw()
  31342. {
  31343. while (possibleChild->isValidComponent())
  31344. {
  31345. possibleChild = possibleChild->parentComponent_;
  31346. if (possibleChild == this)
  31347. return true;
  31348. }
  31349. return false;
  31350. }
  31351. void Component::parentHierarchyChanged()
  31352. {
  31353. }
  31354. void Component::childrenChanged()
  31355. {
  31356. }
  31357. void Component::internalChildrenChanged()
  31358. {
  31359. const ComponentDeletionWatcher deletionChecker (this);
  31360. const bool hasListeners = componentListeners_ != 0;
  31361. childrenChanged();
  31362. if (hasListeners)
  31363. {
  31364. if (deletionChecker.hasBeenDeleted())
  31365. return;
  31366. for (int i = componentListeners_->size(); --i >= 0;)
  31367. {
  31368. ((ComponentListener*) componentListeners_->getUnchecked (i))
  31369. ->componentChildrenChanged (*this);
  31370. if (deletionChecker.hasBeenDeleted())
  31371. return;
  31372. i = jmin (i, componentListeners_->size());
  31373. }
  31374. }
  31375. }
  31376. void Component::internalHierarchyChanged()
  31377. {
  31378. parentHierarchyChanged();
  31379. const ComponentDeletionWatcher deletionChecker (this);
  31380. if (componentListeners_ != 0)
  31381. {
  31382. for (int i = componentListeners_->size(); --i >= 0;)
  31383. {
  31384. ((ComponentListener*) componentListeners_->getUnchecked (i))
  31385. ->componentParentHierarchyChanged (*this);
  31386. if (deletionChecker.hasBeenDeleted())
  31387. return;
  31388. i = jmin (i, componentListeners_->size());
  31389. }
  31390. }
  31391. for (int i = childComponentList_.size(); --i >= 0;)
  31392. {
  31393. childComponentList_.getUnchecked (i)->internalHierarchyChanged();
  31394. // you really shouldn't delete the parent component during a callback telling you
  31395. // that it's changed..
  31396. jassert (! deletionChecker.hasBeenDeleted());
  31397. if (deletionChecker.hasBeenDeleted())
  31398. return;
  31399. i = jmin (i, childComponentList_.size());
  31400. }
  31401. }
  31402. void* Component::runModalLoopCallback (void* userData)
  31403. {
  31404. return (void*) (pointer_sized_int) ((Component*) userData)->runModalLoop();
  31405. }
  31406. int Component::runModalLoop()
  31407. {
  31408. if (! MessageManager::getInstance()->isThisTheMessageThread())
  31409. {
  31410. // use a callback so this can be called from non-gui threads
  31411. return (int) (pointer_sized_int)
  31412. MessageManager::getInstance()
  31413. ->callFunctionOnMessageThread (&runModalLoopCallback, (void*) this);
  31414. }
  31415. Component* const prevFocused = getCurrentlyFocusedComponent();
  31416. ComponentDeletionWatcher* deletionChecker = 0;
  31417. if (prevFocused != 0)
  31418. deletionChecker = new ComponentDeletionWatcher (prevFocused);
  31419. if (! isCurrentlyModal())
  31420. enterModalState();
  31421. JUCE_TRY
  31422. {
  31423. while (flags.currentlyModalFlag && flags.visibleFlag)
  31424. {
  31425. if (! MessageManager::getInstance()->runDispatchLoopUntil (20))
  31426. break;
  31427. // check whether this component was deleted during the last message
  31428. if (! isValidMessageListener())
  31429. break;
  31430. }
  31431. }
  31432. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  31433. catch (const std::exception& e)
  31434. {
  31435. JUCEApplication::sendUnhandledException (&e, __FILE__, __LINE__);
  31436. return 0;
  31437. }
  31438. catch (...)
  31439. {
  31440. JUCEApplication::sendUnhandledException (0, __FILE__, __LINE__);
  31441. return 0;
  31442. }
  31443. #endif
  31444. const int modalIndex = modalComponentReturnValueKeys.indexOf (this);
  31445. int returnValue = 0;
  31446. if (modalIndex >= 0)
  31447. {
  31448. modalComponentReturnValueKeys.remove (modalIndex);
  31449. returnValue = modalReturnValues.remove (modalIndex);
  31450. }
  31451. modalComponentStack.removeValue (this);
  31452. if (deletionChecker != 0)
  31453. {
  31454. if (! deletionChecker->hasBeenDeleted())
  31455. prevFocused->grabKeyboardFocus();
  31456. delete deletionChecker;
  31457. }
  31458. return returnValue;
  31459. }
  31460. void Component::enterModalState (const bool takeKeyboardFocus)
  31461. {
  31462. // if component methods are being called from threads other than the message
  31463. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31464. checkMessageManagerIsLocked
  31465. // Check for an attempt to make a component modal when it already is!
  31466. // This can cause nasty problems..
  31467. jassert (! flags.currentlyModalFlag);
  31468. if (! isCurrentlyModal())
  31469. {
  31470. modalComponentStack.add (this);
  31471. modalComponentReturnValueKeys.add (this);
  31472. modalReturnValues.add (0);
  31473. flags.currentlyModalFlag = true;
  31474. setVisible (true);
  31475. if (takeKeyboardFocus)
  31476. grabKeyboardFocus();
  31477. }
  31478. }
  31479. void Component::exitModalState (const int returnValue)
  31480. {
  31481. if (isCurrentlyModal())
  31482. {
  31483. if (MessageManager::getInstance()->isThisTheMessageThread())
  31484. {
  31485. const int modalIndex = modalComponentReturnValueKeys.indexOf (this);
  31486. if (modalIndex >= 0)
  31487. {
  31488. modalReturnValues.set (modalIndex, returnValue);
  31489. }
  31490. else
  31491. {
  31492. modalComponentReturnValueKeys.add (this);
  31493. modalReturnValues.add (returnValue);
  31494. }
  31495. modalComponentStack.removeValue (this);
  31496. flags.currentlyModalFlag = false;
  31497. bringModalComponentToFront();
  31498. }
  31499. else
  31500. {
  31501. postMessage (new Message (exitModalStateMessage, returnValue, 0, 0));
  31502. }
  31503. }
  31504. }
  31505. bool Component::isCurrentlyModal() const throw()
  31506. {
  31507. return flags.currentlyModalFlag
  31508. && getCurrentlyModalComponent() == this;
  31509. }
  31510. bool Component::isCurrentlyBlockedByAnotherModalComponent() const throw()
  31511. {
  31512. Component* const mc = getCurrentlyModalComponent();
  31513. return mc != 0
  31514. && mc != this
  31515. && (! mc->isParentOf (this))
  31516. && ! mc->canModalEventBeSentToComponent (this);
  31517. }
  31518. int JUCE_CALLTYPE Component::getNumCurrentlyModalComponents() throw()
  31519. {
  31520. return modalComponentStack.size();
  31521. }
  31522. Component* JUCE_CALLTYPE Component::getCurrentlyModalComponent (int index) throw()
  31523. {
  31524. Component* const c = (Component*) (modalComponentStack [modalComponentStack.size() - index - 1]);
  31525. return c->isValidComponent() ? c : 0;
  31526. }
  31527. void Component::bringModalComponentToFront()
  31528. {
  31529. ComponentPeer* lastOne = 0;
  31530. for (int i = 0; i < getNumCurrentlyModalComponents(); ++i)
  31531. {
  31532. Component* const c = getCurrentlyModalComponent (i);
  31533. if (c == 0)
  31534. break;
  31535. ComponentPeer* peer = c->getPeer();
  31536. if (peer != 0 && peer != lastOne)
  31537. {
  31538. if (lastOne == 0)
  31539. {
  31540. peer->toFront (true);
  31541. peer->grabFocus();
  31542. }
  31543. else
  31544. peer->toBehind (lastOne);
  31545. lastOne = peer;
  31546. }
  31547. }
  31548. }
  31549. void Component::setBroughtToFrontOnMouseClick (const bool shouldBeBroughtToFront) throw()
  31550. {
  31551. flags.bringToFrontOnClickFlag = shouldBeBroughtToFront;
  31552. }
  31553. bool Component::isBroughtToFrontOnMouseClick() const throw()
  31554. {
  31555. return flags.bringToFrontOnClickFlag;
  31556. }
  31557. void Component::setMouseCursor (const MouseCursor& cursor) throw()
  31558. {
  31559. cursor_ = cursor;
  31560. if (flags.visibleFlag)
  31561. {
  31562. int mx, my;
  31563. getMouseXYRelative (mx, my);
  31564. if (flags.draggingFlag || reallyContains (mx, my, false))
  31565. {
  31566. internalUpdateMouseCursor (false);
  31567. }
  31568. }
  31569. }
  31570. const MouseCursor Component::getMouseCursor()
  31571. {
  31572. return cursor_;
  31573. }
  31574. void Component::updateMouseCursor() const throw()
  31575. {
  31576. sendFakeMouseMove();
  31577. }
  31578. void Component::internalUpdateMouseCursor (bool forcedUpdate) throw()
  31579. {
  31580. ComponentPeer* const peer = getPeer();
  31581. if (peer != 0)
  31582. {
  31583. MouseCursor mc (getMouseCursor());
  31584. if (isUnboundedMouseModeOn && (unboundedMouseOffsetX != 0
  31585. || unboundedMouseOffsetY != 0
  31586. || ! isCursorVisibleUntilOffscreen))
  31587. {
  31588. mc = MouseCursor::NoCursor;
  31589. forcedUpdate = true;
  31590. }
  31591. static void* currentCursorHandle = 0;
  31592. if (forcedUpdate || mc.getHandle() != currentCursorHandle)
  31593. {
  31594. currentCursorHandle = mc.getHandle();
  31595. mc.showInWindow (peer);
  31596. }
  31597. }
  31598. }
  31599. void Component::setRepaintsOnMouseActivity (const bool shouldRepaint) throw()
  31600. {
  31601. flags.repaintOnMouseActivityFlag = shouldRepaint;
  31602. }
  31603. void Component::repaintParent() throw()
  31604. {
  31605. if (flags.visibleFlag)
  31606. internalRepaint (0, 0, getWidth(), getHeight());
  31607. }
  31608. void Component::repaint() throw()
  31609. {
  31610. repaint (0, 0, getWidth(), getHeight());
  31611. }
  31612. void Component::repaint (const int x, const int y,
  31613. const int w, const int h) throw()
  31614. {
  31615. deleteAndZero (bufferedImage_);
  31616. if (flags.visibleFlag)
  31617. internalRepaint (x, y, w, h);
  31618. }
  31619. void Component::internalRepaint (int x, int y, int w, int h)
  31620. {
  31621. // if component methods are being called from threads other than the message
  31622. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31623. checkMessageManagerIsLocked
  31624. if (x < 0)
  31625. {
  31626. w += x;
  31627. x = 0;
  31628. }
  31629. if (x + w > getWidth())
  31630. w = getWidth() - x;
  31631. if (w > 0)
  31632. {
  31633. if (y < 0)
  31634. {
  31635. h += y;
  31636. y = 0;
  31637. }
  31638. if (y + h > getHeight())
  31639. h = getHeight() - y;
  31640. if (h > 0)
  31641. {
  31642. if (parentComponent_ != 0)
  31643. {
  31644. x += getX();
  31645. y += getY();
  31646. if (parentComponent_->flags.visibleFlag)
  31647. parentComponent_->internalRepaint (x, y, w, h);
  31648. }
  31649. else if (flags.hasHeavyweightPeerFlag)
  31650. {
  31651. ComponentPeer* const peer = getPeer();
  31652. if (peer != 0)
  31653. peer->repaint (x, y, w, h);
  31654. }
  31655. }
  31656. }
  31657. }
  31658. void Component::paintEntireComponent (Graphics& originalContext)
  31659. {
  31660. jassert (! originalContext.isClipEmpty());
  31661. #ifdef JUCE_DEBUG
  31662. flags.isInsidePaintCall = true;
  31663. #endif
  31664. Graphics* g = &originalContext;
  31665. Image* effectImage = 0;
  31666. if (effect_ != 0)
  31667. {
  31668. effectImage = new Image (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  31669. getWidth(), getHeight(),
  31670. ! flags.opaqueFlag);
  31671. g = new Graphics (*effectImage);
  31672. }
  31673. g->saveState();
  31674. clipObscuredRegions (*g, g->getClipBounds(), 0, 0);
  31675. if (! g->isClipEmpty())
  31676. {
  31677. if (bufferedImage_ != 0)
  31678. {
  31679. g->setColour (Colours::black);
  31680. g->drawImageAt (bufferedImage_, 0, 0);
  31681. }
  31682. else
  31683. {
  31684. if (flags.bufferToImageFlag)
  31685. {
  31686. if (bufferedImage_ == 0)
  31687. {
  31688. bufferedImage_ = new Image (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  31689. getWidth(), getHeight(), ! flags.opaqueFlag);
  31690. Graphics imG (*bufferedImage_);
  31691. paint (imG);
  31692. }
  31693. g->setColour (Colours::black);
  31694. g->drawImageAt (bufferedImage_, 0, 0);
  31695. }
  31696. else
  31697. {
  31698. paint (*g);
  31699. g->resetToDefaultState();
  31700. }
  31701. }
  31702. }
  31703. g->restoreState();
  31704. for (int i = 0; i < childComponentList_.size(); ++i)
  31705. {
  31706. Component* const child = childComponentList_.getUnchecked (i);
  31707. if (child->isVisible())
  31708. {
  31709. g->saveState();
  31710. if (g->reduceClipRegion (child->getX(), child->getY(),
  31711. child->getWidth(), child->getHeight()))
  31712. {
  31713. for (int j = i + 1; j < childComponentList_.size(); ++j)
  31714. {
  31715. const Component* const sibling = childComponentList_.getUnchecked (j);
  31716. if (sibling->flags.opaqueFlag && sibling->isVisible())
  31717. g->excludeClipRegion (sibling->getX(), sibling->getY(),
  31718. sibling->getWidth(), sibling->getHeight());
  31719. }
  31720. if (! g->isClipEmpty())
  31721. {
  31722. g->setOrigin (child->getX(), child->getY());
  31723. child->paintEntireComponent (*g);
  31724. }
  31725. }
  31726. g->restoreState();
  31727. }
  31728. }
  31729. JUCE_TRY
  31730. {
  31731. g->saveState();
  31732. paintOverChildren (*g);
  31733. g->restoreState();
  31734. }
  31735. JUCE_CATCH_EXCEPTION
  31736. if (effect_ != 0)
  31737. {
  31738. delete g;
  31739. effect_->applyEffect (*effectImage, originalContext);
  31740. delete effectImage;
  31741. }
  31742. #ifdef JUCE_DEBUG
  31743. flags.isInsidePaintCall = false;
  31744. #endif
  31745. }
  31746. Image* Component::createComponentSnapshot (const Rectangle& areaToGrab,
  31747. const bool clipImageToComponentBounds)
  31748. {
  31749. Rectangle r (areaToGrab);
  31750. if (clipImageToComponentBounds)
  31751. r = r.getIntersection (Rectangle (0, 0, getWidth(), getHeight()));
  31752. Image* const componentImage = new Image (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  31753. jmax (1, r.getWidth()),
  31754. jmax (1, r.getHeight()),
  31755. true);
  31756. Graphics imageContext (*componentImage);
  31757. imageContext.setOrigin (-r.getX(),
  31758. -r.getY());
  31759. paintEntireComponent (imageContext);
  31760. return componentImage;
  31761. }
  31762. void Component::setComponentEffect (ImageEffectFilter* const effect)
  31763. {
  31764. if (effect_ != effect)
  31765. {
  31766. effect_ = effect;
  31767. repaint();
  31768. }
  31769. }
  31770. LookAndFeel& Component::getLookAndFeel() const throw()
  31771. {
  31772. const Component* c = this;
  31773. do
  31774. {
  31775. if (c->lookAndFeel_ != 0)
  31776. return *(c->lookAndFeel_);
  31777. c = c->parentComponent_;
  31778. }
  31779. while (c != 0);
  31780. return LookAndFeel::getDefaultLookAndFeel();
  31781. }
  31782. void Component::setLookAndFeel (LookAndFeel* const newLookAndFeel)
  31783. {
  31784. if (lookAndFeel_ != newLookAndFeel)
  31785. {
  31786. lookAndFeel_ = newLookAndFeel;
  31787. sendLookAndFeelChange();
  31788. }
  31789. }
  31790. void Component::lookAndFeelChanged()
  31791. {
  31792. }
  31793. void Component::sendLookAndFeelChange()
  31794. {
  31795. repaint();
  31796. lookAndFeelChanged();
  31797. // (it's not a great idea to do anything that would delete this component
  31798. // during the lookAndFeelChanged() callback)
  31799. jassert (isValidComponent());
  31800. const ComponentDeletionWatcher deletionChecker (this);
  31801. for (int i = childComponentList_.size(); --i >= 0;)
  31802. {
  31803. childComponentList_.getUnchecked (i)->sendLookAndFeelChange();
  31804. if (deletionChecker.hasBeenDeleted())
  31805. return;
  31806. i = jmin (i, childComponentList_.size());
  31807. }
  31808. }
  31809. static const String getColourPropertyName (const int colourId) throw()
  31810. {
  31811. String s;
  31812. s.preallocateStorage (18);
  31813. s << T("jcclr_") << colourId;
  31814. return s;
  31815. }
  31816. const Colour Component::findColour (const int colourId, const bool inheritFromParent) const throw()
  31817. {
  31818. const String customColour (getComponentProperty (getColourPropertyName (colourId),
  31819. inheritFromParent,
  31820. String::empty));
  31821. if (customColour.isNotEmpty())
  31822. return Colour (customColour.getIntValue());
  31823. return getLookAndFeel().findColour (colourId);
  31824. }
  31825. bool Component::isColourSpecified (const int colourId) const throw()
  31826. {
  31827. return getComponentProperty (getColourPropertyName (colourId),
  31828. false,
  31829. String::empty).isNotEmpty();
  31830. }
  31831. void Component::removeColour (const int colourId)
  31832. {
  31833. if (isColourSpecified (colourId))
  31834. {
  31835. removeComponentProperty (getColourPropertyName (colourId));
  31836. colourChanged();
  31837. }
  31838. }
  31839. void Component::setColour (const int colourId, const Colour& colour)
  31840. {
  31841. const String colourName (getColourPropertyName (colourId));
  31842. const String customColour (getComponentProperty (colourName, false, String::empty));
  31843. if (customColour.isEmpty() || Colour (customColour.getIntValue()) != colour)
  31844. {
  31845. setComponentProperty (colourName, colour);
  31846. colourChanged();
  31847. }
  31848. }
  31849. void Component::copyAllExplicitColoursTo (Component& target) const throw()
  31850. {
  31851. if (propertySet_ != 0)
  31852. {
  31853. const StringPairArray& props = propertySet_->getAllProperties();
  31854. const StringArray& keys = props.getAllKeys();
  31855. for (int i = 0; i < keys.size(); ++i)
  31856. {
  31857. if (keys[i].startsWith (T("jcclr_")))
  31858. {
  31859. target.setComponentProperty (keys[i],
  31860. props.getAllValues() [i]);
  31861. }
  31862. }
  31863. target.colourChanged();
  31864. }
  31865. }
  31866. void Component::colourChanged()
  31867. {
  31868. }
  31869. const Rectangle Component::getUnclippedArea() const
  31870. {
  31871. int x = 0, y = 0, w = getWidth(), h = getHeight();
  31872. Component* p = parentComponent_;
  31873. int px = getX();
  31874. int py = getY();
  31875. while (p != 0)
  31876. {
  31877. if (! Rectangle::intersectRectangles (x, y, w, h, -px, -py, p->getWidth(), p->getHeight()))
  31878. return Rectangle();
  31879. px += p->getX();
  31880. py += p->getY();
  31881. p = p->parentComponent_;
  31882. }
  31883. return Rectangle (x, y, w, h);
  31884. }
  31885. void Component::clipObscuredRegions (Graphics& g, const Rectangle& clipRect,
  31886. const int deltaX, const int deltaY) const throw()
  31887. {
  31888. for (int i = childComponentList_.size(); --i >= 0;)
  31889. {
  31890. const Component* const c = childComponentList_.getUnchecked(i);
  31891. if (c->isVisible())
  31892. {
  31893. Rectangle newClip (clipRect.getIntersection (c->bounds_));
  31894. if (! newClip.isEmpty())
  31895. {
  31896. if (c->isOpaque())
  31897. {
  31898. g.excludeClipRegion (deltaX + newClip.getX(),
  31899. deltaY + newClip.getY(),
  31900. newClip.getWidth(),
  31901. newClip.getHeight());
  31902. }
  31903. else
  31904. {
  31905. newClip.translate (-c->getX(), -c->getY());
  31906. c->clipObscuredRegions (g, newClip,
  31907. c->getX() + deltaX,
  31908. c->getY() + deltaY);
  31909. }
  31910. }
  31911. }
  31912. }
  31913. }
  31914. void Component::getVisibleArea (RectangleList& result,
  31915. const bool includeSiblings) const
  31916. {
  31917. result.clear();
  31918. const Rectangle unclipped (getUnclippedArea());
  31919. if (! unclipped.isEmpty())
  31920. {
  31921. result.add (unclipped);
  31922. if (includeSiblings)
  31923. {
  31924. const Component* const c = getTopLevelComponent();
  31925. int x = 0, y = 0;
  31926. c->relativePositionToOtherComponent (this, x, y);
  31927. c->subtractObscuredRegions (result, x, y,
  31928. Rectangle (0, 0, c->getWidth(), c->getHeight()),
  31929. this);
  31930. }
  31931. subtractObscuredRegions (result, 0, 0, unclipped, 0);
  31932. result.consolidate();
  31933. }
  31934. }
  31935. void Component::subtractObscuredRegions (RectangleList& result,
  31936. const int deltaX,
  31937. const int deltaY,
  31938. const Rectangle& clipRect,
  31939. const Component* const compToAvoid) const throw()
  31940. {
  31941. for (int i = childComponentList_.size(); --i >= 0;)
  31942. {
  31943. const Component* const c = childComponentList_.getUnchecked(i);
  31944. if (c != compToAvoid && c->isVisible())
  31945. {
  31946. if (c->isOpaque())
  31947. {
  31948. Rectangle childBounds (c->bounds_.getIntersection (clipRect));
  31949. childBounds.translate (deltaX, deltaY);
  31950. result.subtract (childBounds);
  31951. }
  31952. else
  31953. {
  31954. Rectangle newClip (clipRect.getIntersection (c->bounds_));
  31955. newClip.translate (-c->getX(), -c->getY());
  31956. c->subtractObscuredRegions (result,
  31957. c->getX() + deltaX,
  31958. c->getY() + deltaY,
  31959. newClip,
  31960. compToAvoid);
  31961. }
  31962. }
  31963. }
  31964. }
  31965. void Component::mouseEnter (const MouseEvent&)
  31966. {
  31967. // base class does nothing
  31968. }
  31969. void Component::mouseExit (const MouseEvent&)
  31970. {
  31971. // base class does nothing
  31972. }
  31973. void Component::mouseDown (const MouseEvent&)
  31974. {
  31975. // base class does nothing
  31976. }
  31977. void Component::mouseUp (const MouseEvent&)
  31978. {
  31979. // base class does nothing
  31980. }
  31981. void Component::mouseDrag (const MouseEvent&)
  31982. {
  31983. // base class does nothing
  31984. }
  31985. void Component::mouseMove (const MouseEvent&)
  31986. {
  31987. // base class does nothing
  31988. }
  31989. void Component::mouseDoubleClick (const MouseEvent&)
  31990. {
  31991. // base class does nothing
  31992. }
  31993. void Component::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  31994. {
  31995. // the base class just passes this event up to its parent..
  31996. if (parentComponent_ != 0)
  31997. parentComponent_->mouseWheelMove (e.getEventRelativeTo (parentComponent_),
  31998. wheelIncrementX, wheelIncrementY);
  31999. }
  32000. void Component::resized()
  32001. {
  32002. // base class does nothing
  32003. }
  32004. void Component::moved()
  32005. {
  32006. // base class does nothing
  32007. }
  32008. void Component::childBoundsChanged (Component*)
  32009. {
  32010. // base class does nothing
  32011. }
  32012. void Component::parentSizeChanged()
  32013. {
  32014. // base class does nothing
  32015. }
  32016. void Component::addComponentListener (ComponentListener* const newListener) throw()
  32017. {
  32018. if (componentListeners_ == 0)
  32019. componentListeners_ = new VoidArray (4);
  32020. componentListeners_->addIfNotAlreadyThere (newListener);
  32021. }
  32022. void Component::removeComponentListener (ComponentListener* const listenerToRemove) throw()
  32023. {
  32024. jassert (isValidComponent());
  32025. if (componentListeners_ != 0)
  32026. componentListeners_->removeValue (listenerToRemove);
  32027. }
  32028. void Component::inputAttemptWhenModal()
  32029. {
  32030. bringModalComponentToFront();
  32031. getLookAndFeel().playAlertSound();
  32032. }
  32033. bool Component::canModalEventBeSentToComponent (const Component*)
  32034. {
  32035. return false;
  32036. }
  32037. void Component::internalModalInputAttempt()
  32038. {
  32039. Component* const current = getCurrentlyModalComponent();
  32040. if (current != 0)
  32041. current->inputAttemptWhenModal();
  32042. }
  32043. void Component::paint (Graphics&)
  32044. {
  32045. // all painting is done in the subclasses
  32046. jassert (! isOpaque()); // if your component's opaque, you've gotta paint it!
  32047. }
  32048. void Component::paintOverChildren (Graphics&)
  32049. {
  32050. // all painting is done in the subclasses
  32051. }
  32052. void Component::handleMessage (const Message& message)
  32053. {
  32054. if (message.intParameter1 == exitModalStateMessage)
  32055. {
  32056. exitModalState (message.intParameter2);
  32057. }
  32058. else if (message.intParameter1 == customCommandMessage)
  32059. {
  32060. handleCommandMessage (message.intParameter2);
  32061. }
  32062. }
  32063. void Component::postCommandMessage (const int commandId) throw()
  32064. {
  32065. postMessage (new Message (customCommandMessage, commandId, 0, 0));
  32066. }
  32067. void Component::handleCommandMessage (int)
  32068. {
  32069. // used by subclasses
  32070. }
  32071. void Component::addMouseListener (MouseListener* const newListener,
  32072. const bool wantsEventsForAllNestedChildComponents) throw()
  32073. {
  32074. // if component methods are being called from threads other than the message
  32075. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32076. checkMessageManagerIsLocked
  32077. if (mouseListeners_ == 0)
  32078. mouseListeners_ = new VoidArray (4);
  32079. if (! mouseListeners_->contains (newListener))
  32080. {
  32081. if (wantsEventsForAllNestedChildComponents)
  32082. {
  32083. mouseListeners_->insert (0, newListener);
  32084. ++numDeepMouseListeners;
  32085. }
  32086. else
  32087. {
  32088. mouseListeners_->add (newListener);
  32089. }
  32090. }
  32091. }
  32092. void Component::removeMouseListener (MouseListener* const listenerToRemove) throw()
  32093. {
  32094. // if component methods are being called from threads other than the message
  32095. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32096. checkMessageManagerIsLocked
  32097. if (mouseListeners_ != 0)
  32098. {
  32099. const int index = mouseListeners_->indexOf (listenerToRemove);
  32100. if (index >= 0)
  32101. {
  32102. if (index < numDeepMouseListeners)
  32103. --numDeepMouseListeners;
  32104. mouseListeners_->remove (index);
  32105. }
  32106. }
  32107. }
  32108. void Component::internalMouseEnter (int x, int y, int64 time)
  32109. {
  32110. if (isCurrentlyBlockedByAnotherModalComponent())
  32111. {
  32112. // if something else is modal, always just show a normal mouse cursor
  32113. if (componentUnderMouse == this)
  32114. {
  32115. ComponentPeer* const peer = getPeer();
  32116. if (peer != 0)
  32117. {
  32118. MouseCursor mc (MouseCursor::NormalCursor);
  32119. mc.showInWindow (peer);
  32120. }
  32121. }
  32122. return;
  32123. }
  32124. if (! flags.mouseInsideFlag)
  32125. {
  32126. flags.mouseInsideFlag = true;
  32127. flags.mouseOverFlag = true;
  32128. flags.draggingFlag = false;
  32129. if (isValidComponent())
  32130. {
  32131. const ComponentDeletionWatcher deletionChecker (this);
  32132. if (flags.repaintOnMouseActivityFlag)
  32133. repaint();
  32134. const MouseEvent me (x, y,
  32135. ModifierKeys::getCurrentModifiers(),
  32136. this,
  32137. Time (time),
  32138. x, y,
  32139. Time (time),
  32140. 0, false);
  32141. mouseEnter (me);
  32142. if (deletionChecker.hasBeenDeleted())
  32143. return;
  32144. Desktop::getInstance().resetTimer();
  32145. for (int i = Desktop::getInstance().mouseListeners.size(); --i >= 0;)
  32146. {
  32147. ((MouseListener*) Desktop::getInstance().mouseListeners[i])->mouseEnter (me);
  32148. if (deletionChecker.hasBeenDeleted())
  32149. return;
  32150. i = jmin (i, Desktop::getInstance().mouseListeners.size());
  32151. }
  32152. if (mouseListeners_ != 0)
  32153. {
  32154. for (int i = mouseListeners_->size(); --i >= 0;)
  32155. {
  32156. ((MouseListener*) mouseListeners_->getUnchecked(i))->mouseEnter (me);
  32157. if (deletionChecker.hasBeenDeleted())
  32158. return;
  32159. i = jmin (i, mouseListeners_->size());
  32160. }
  32161. }
  32162. const Component* p = parentComponent_;
  32163. while (p != 0)
  32164. {
  32165. const ComponentDeletionWatcher parentDeletionChecker (p);
  32166. for (int i = p->numDeepMouseListeners; --i >= 0;)
  32167. {
  32168. ((MouseListener*) (p->mouseListeners_->getUnchecked(i)))->mouseEnter (me);
  32169. if (deletionChecker.hasBeenDeleted() || parentDeletionChecker.hasBeenDeleted())
  32170. return;
  32171. i = jmin (i, p->numDeepMouseListeners);
  32172. }
  32173. p = p->parentComponent_;
  32174. }
  32175. }
  32176. }
  32177. if (componentUnderMouse == this)
  32178. internalUpdateMouseCursor (true);
  32179. }
  32180. void Component::internalMouseExit (int x, int y, int64 time)
  32181. {
  32182. const ComponentDeletionWatcher deletionChecker (this);
  32183. if (flags.draggingFlag)
  32184. {
  32185. internalMouseUp (ModifierKeys::getCurrentModifiers().getRawFlags(), x, y, time);
  32186. if (deletionChecker.hasBeenDeleted())
  32187. return;
  32188. }
  32189. enableUnboundedMouseMovement (false);
  32190. if (flags.mouseInsideFlag || flags.mouseOverFlag)
  32191. {
  32192. flags.mouseInsideFlag = false;
  32193. flags.mouseOverFlag = false;
  32194. flags.draggingFlag = false;
  32195. if (flags.repaintOnMouseActivityFlag)
  32196. repaint();
  32197. const MouseEvent me (x, y,
  32198. ModifierKeys::getCurrentModifiers(),
  32199. this,
  32200. Time (time),
  32201. x, y,
  32202. Time (time),
  32203. 0, false);
  32204. mouseExit (me);
  32205. if (deletionChecker.hasBeenDeleted())
  32206. return;
  32207. Desktop::getInstance().resetTimer();
  32208. for (int i = Desktop::getInstance().mouseListeners.size(); --i >= 0;)
  32209. {
  32210. ((MouseListener*) Desktop::getInstance().mouseListeners[i])->mouseExit (me);
  32211. if (deletionChecker.hasBeenDeleted())
  32212. return;
  32213. i = jmin (i, Desktop::getInstance().mouseListeners.size());
  32214. }
  32215. if (mouseListeners_ != 0)
  32216. {
  32217. for (int i = mouseListeners_->size(); --i >= 0;)
  32218. {
  32219. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseExit (me);
  32220. if (deletionChecker.hasBeenDeleted())
  32221. return;
  32222. i = jmin (i, mouseListeners_->size());
  32223. }
  32224. }
  32225. const Component* p = parentComponent_;
  32226. while (p != 0)
  32227. {
  32228. const ComponentDeletionWatcher parentDeletionChecker (p);
  32229. for (int i = p->numDeepMouseListeners; --i >= 0;)
  32230. {
  32231. ((MouseListener*) (p->mouseListeners_->getUnchecked (i)))->mouseExit (me);
  32232. if (deletionChecker.hasBeenDeleted() || parentDeletionChecker.hasBeenDeleted())
  32233. return;
  32234. i = jmin (i, p->numDeepMouseListeners);
  32235. }
  32236. p = p->parentComponent_;
  32237. }
  32238. }
  32239. }
  32240. class InternalDragRepeater : public Timer
  32241. {
  32242. public:
  32243. InternalDragRepeater()
  32244. {}
  32245. ~InternalDragRepeater()
  32246. {}
  32247. void timerCallback()
  32248. {
  32249. Component* const c = Component::getComponentUnderMouse();
  32250. if (c != 0 && c->isMouseButtonDown())
  32251. {
  32252. int x, y;
  32253. c->getMouseXYRelative (x, y);
  32254. // the offsets have been added on, so must be taken off before calling the
  32255. // drag.. otherwise they'll be added twice
  32256. x -= unboundedMouseOffsetX;
  32257. y -= unboundedMouseOffsetY;
  32258. c->internalMouseDrag (x, y, Time::currentTimeMillis());
  32259. }
  32260. }
  32261. juce_UseDebuggingNewOperator
  32262. };
  32263. static InternalDragRepeater* dragRepeater = 0;
  32264. void Component::beginDragAutoRepeat (const int interval)
  32265. {
  32266. if (interval > 0)
  32267. {
  32268. if (dragRepeater == 0)
  32269. dragRepeater = new InternalDragRepeater();
  32270. if (dragRepeater->getTimerInterval() != interval)
  32271. dragRepeater->startTimer (interval);
  32272. }
  32273. else
  32274. {
  32275. deleteAndZero (dragRepeater);
  32276. }
  32277. }
  32278. void Component::internalMouseDown (const int x, const int y)
  32279. {
  32280. const ComponentDeletionWatcher deletionChecker (this);
  32281. if (isCurrentlyBlockedByAnotherModalComponent())
  32282. {
  32283. internalModalInputAttempt();
  32284. if (deletionChecker.hasBeenDeleted())
  32285. return;
  32286. // If processing the input attempt has exited the modal loop, we'll allow the event
  32287. // to be delivered..
  32288. if (isCurrentlyBlockedByAnotherModalComponent())
  32289. {
  32290. // allow blocked mouse-events to go to global listeners..
  32291. const MouseEvent me (x, y,
  32292. ModifierKeys::getCurrentModifiers(),
  32293. this,
  32294. Time (juce_recentMouseDownTimes[0]),
  32295. x, y,
  32296. Time (juce_recentMouseDownTimes[0]),
  32297. countMouseClicks(),
  32298. false);
  32299. Desktop::getInstance().resetTimer();
  32300. for (int i = Desktop::getInstance().mouseListeners.size(); --i >= 0;)
  32301. {
  32302. ((MouseListener*) Desktop::getInstance().mouseListeners[i])->mouseDown (me);
  32303. if (deletionChecker.hasBeenDeleted())
  32304. return;
  32305. i = jmin (i, Desktop::getInstance().mouseListeners.size());
  32306. }
  32307. return;
  32308. }
  32309. }
  32310. {
  32311. Component* c = this;
  32312. while (c != 0)
  32313. {
  32314. if (c->isBroughtToFrontOnMouseClick())
  32315. {
  32316. c->toFront (true);
  32317. if (deletionChecker.hasBeenDeleted())
  32318. return;
  32319. }
  32320. c = c->parentComponent_;
  32321. }
  32322. }
  32323. if (! flags.dontFocusOnMouseClickFlag)
  32324. grabFocusInternal (focusChangedByMouseClick);
  32325. if (! deletionChecker.hasBeenDeleted())
  32326. {
  32327. flags.draggingFlag = true;
  32328. flags.mouseOverFlag = true;
  32329. if (flags.repaintOnMouseActivityFlag)
  32330. repaint();
  32331. const MouseEvent me (x, y,
  32332. ModifierKeys::getCurrentModifiers(),
  32333. this,
  32334. Time (juce_recentMouseDownTimes[0]),
  32335. x, y,
  32336. Time (juce_recentMouseDownTimes[0]),
  32337. countMouseClicks(),
  32338. false);
  32339. mouseDown (me);
  32340. if (deletionChecker.hasBeenDeleted())
  32341. return;
  32342. Desktop::getInstance().resetTimer();
  32343. for (int i = Desktop::getInstance().mouseListeners.size(); --i >= 0;)
  32344. {
  32345. ((MouseListener*) Desktop::getInstance().mouseListeners[i])->mouseDown (me);
  32346. if (deletionChecker.hasBeenDeleted())
  32347. return;
  32348. i = jmin (i, Desktop::getInstance().mouseListeners.size());
  32349. }
  32350. if (mouseListeners_ != 0)
  32351. {
  32352. for (int i = mouseListeners_->size(); --i >= 0;)
  32353. {
  32354. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseDown (me);
  32355. if (deletionChecker.hasBeenDeleted())
  32356. return;
  32357. i = jmin (i, mouseListeners_->size());
  32358. }
  32359. }
  32360. const Component* p = parentComponent_;
  32361. while (p != 0)
  32362. {
  32363. const ComponentDeletionWatcher parentDeletionChecker (p);
  32364. for (int i = p->numDeepMouseListeners; --i >= 0;)
  32365. {
  32366. ((MouseListener*) (p->mouseListeners_->getUnchecked (i)))->mouseDown (me);
  32367. if (deletionChecker.hasBeenDeleted() || parentDeletionChecker.hasBeenDeleted())
  32368. return;
  32369. i = jmin (i, p->numDeepMouseListeners);
  32370. }
  32371. p = p->parentComponent_;
  32372. }
  32373. }
  32374. }
  32375. void Component::internalMouseUp (const int oldModifiers, int x, int y, const int64 time)
  32376. {
  32377. if (isValidComponent() && flags.draggingFlag)
  32378. {
  32379. flags.draggingFlag = false;
  32380. deleteAndZero (dragRepeater);
  32381. x += unboundedMouseOffsetX;
  32382. y += unboundedMouseOffsetY;
  32383. juce_LastMousePosX = x;
  32384. juce_LastMousePosY = y;
  32385. relativePositionToGlobal (juce_LastMousePosX, juce_LastMousePosY);
  32386. const ComponentDeletionWatcher deletionChecker (this);
  32387. if (flags.repaintOnMouseActivityFlag)
  32388. repaint();
  32389. int mdx = juce_recentMouseDownX[0];
  32390. int mdy = juce_recentMouseDownY[0];
  32391. globalPositionToRelative (mdx, mdy);
  32392. const MouseEvent me (x, y,
  32393. oldModifiers,
  32394. this,
  32395. Time (time),
  32396. mdx, mdy,
  32397. Time (juce_recentMouseDownTimes [0]),
  32398. countMouseClicks(),
  32399. juce_MouseHasMovedSignificantlySincePressed
  32400. || juce_recentMouseDownTimes[0] + 300 < time);
  32401. mouseUp (me);
  32402. if (deletionChecker.hasBeenDeleted())
  32403. return;
  32404. Desktop::getInstance().resetTimer();
  32405. for (int i = Desktop::getInstance().mouseListeners.size(); --i >= 0;)
  32406. {
  32407. ((MouseListener*) Desktop::getInstance().mouseListeners[i])->mouseUp (me);
  32408. if (deletionChecker.hasBeenDeleted())
  32409. return;
  32410. i = jmin (i, Desktop::getInstance().mouseListeners.size());
  32411. }
  32412. if (mouseListeners_ != 0)
  32413. {
  32414. for (int i = mouseListeners_->size(); --i >= 0;)
  32415. {
  32416. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseUp (me);
  32417. if (deletionChecker.hasBeenDeleted())
  32418. return;
  32419. i = jmin (i, mouseListeners_->size());
  32420. }
  32421. }
  32422. {
  32423. const Component* p = parentComponent_;
  32424. while (p != 0)
  32425. {
  32426. const ComponentDeletionWatcher parentDeletionChecker (p);
  32427. for (int i = p->numDeepMouseListeners; --i >= 0;)
  32428. {
  32429. ((MouseListener*) (p->mouseListeners_->getUnchecked (i)))->mouseUp (me);
  32430. if (deletionChecker.hasBeenDeleted() || parentDeletionChecker.hasBeenDeleted())
  32431. return;
  32432. i = jmin (i, p->numDeepMouseListeners);
  32433. }
  32434. p = p->parentComponent_;
  32435. }
  32436. }
  32437. // check for double-click
  32438. if (me.getNumberOfClicks() >= 2)
  32439. {
  32440. const int numListeners = (mouseListeners_ != 0) ? mouseListeners_->size() : 0;
  32441. mouseDoubleClick (me);
  32442. int i;
  32443. for (i = Desktop::getInstance().mouseListeners.size(); --i >= 0;)
  32444. {
  32445. ((MouseListener*) Desktop::getInstance().mouseListeners[i])->mouseDoubleClick (me);
  32446. if (deletionChecker.hasBeenDeleted())
  32447. return;
  32448. i = jmin (i, Desktop::getInstance().mouseListeners.size());
  32449. }
  32450. for (i = numListeners; --i >= 0;)
  32451. {
  32452. if (deletionChecker.hasBeenDeleted() || mouseListeners_ == 0)
  32453. return;
  32454. MouseListener* const ml = (MouseListener*)((*mouseListeners_)[i]);
  32455. if (ml != 0)
  32456. ml->mouseDoubleClick (me);
  32457. }
  32458. if (deletionChecker.hasBeenDeleted())
  32459. return;
  32460. const Component* p = parentComponent_;
  32461. while (p != 0)
  32462. {
  32463. const ComponentDeletionWatcher parentDeletionChecker (p);
  32464. for (i = p->numDeepMouseListeners; --i >= 0;)
  32465. {
  32466. ((MouseListener*) (p->mouseListeners_->getUnchecked (i)))->mouseDoubleClick (me);
  32467. if (deletionChecker.hasBeenDeleted() || parentDeletionChecker.hasBeenDeleted())
  32468. return;
  32469. i = jmin (i, p->numDeepMouseListeners);
  32470. }
  32471. p = p->parentComponent_;
  32472. }
  32473. }
  32474. }
  32475. enableUnboundedMouseMovement (false);
  32476. }
  32477. void Component::internalMouseDrag (int x, int y, const int64 time)
  32478. {
  32479. if (isValidComponent() && flags.draggingFlag)
  32480. {
  32481. flags.mouseOverFlag = reallyContains (x, y, false);
  32482. x += unboundedMouseOffsetX;
  32483. y += unboundedMouseOffsetY;
  32484. juce_LastMousePosX = x;
  32485. juce_LastMousePosY = y;
  32486. relativePositionToGlobal (juce_LastMousePosX, juce_LastMousePosY);
  32487. juce_MouseHasMovedSignificantlySincePressed
  32488. = juce_MouseHasMovedSignificantlySincePressed
  32489. || abs (juce_recentMouseDownX[0] - juce_LastMousePosX) >= 4
  32490. || abs (juce_recentMouseDownY[0] - juce_LastMousePosY) >= 4;
  32491. const ComponentDeletionWatcher deletionChecker (this);
  32492. int mdx = juce_recentMouseDownX[0];
  32493. int mdy = juce_recentMouseDownY[0];
  32494. globalPositionToRelative (mdx, mdy);
  32495. const MouseEvent me (x, y,
  32496. ModifierKeys::getCurrentModifiers(),
  32497. this,
  32498. Time (time),
  32499. mdx, mdy,
  32500. Time (juce_recentMouseDownTimes[0]),
  32501. countMouseClicks(),
  32502. juce_MouseHasMovedSignificantlySincePressed
  32503. || juce_recentMouseDownTimes[0] + 300 < time);
  32504. mouseDrag (me);
  32505. if (deletionChecker.hasBeenDeleted())
  32506. return;
  32507. Desktop::getInstance().resetTimer();
  32508. for (int i = Desktop::getInstance().mouseListeners.size(); --i >= 0;)
  32509. {
  32510. ((MouseListener*) Desktop::getInstance().mouseListeners[i])->mouseDrag (me);
  32511. if (deletionChecker.hasBeenDeleted())
  32512. return;
  32513. i = jmin (i, Desktop::getInstance().mouseListeners.size());
  32514. }
  32515. if (mouseListeners_ != 0)
  32516. {
  32517. for (int i = mouseListeners_->size(); --i >= 0;)
  32518. {
  32519. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseDrag (me);
  32520. if (deletionChecker.hasBeenDeleted())
  32521. return;
  32522. i = jmin (i, mouseListeners_->size());
  32523. }
  32524. }
  32525. const Component* p = parentComponent_;
  32526. while (p != 0)
  32527. {
  32528. const ComponentDeletionWatcher parentDeletionChecker (p);
  32529. for (int i = p->numDeepMouseListeners; --i >= 0;)
  32530. {
  32531. ((MouseListener*) (p->mouseListeners_->getUnchecked (i)))->mouseDrag (me);
  32532. if (deletionChecker.hasBeenDeleted() || parentDeletionChecker.hasBeenDeleted())
  32533. return;
  32534. i = jmin (i, p->numDeepMouseListeners);
  32535. }
  32536. p = p->parentComponent_;
  32537. }
  32538. if (this == componentUnderMouse)
  32539. {
  32540. if (isUnboundedMouseModeOn)
  32541. {
  32542. Rectangle screenArea (getParentMonitorArea().expanded (-2, -2));
  32543. int mx, my;
  32544. Desktop::getMousePosition (mx, my);
  32545. if (! screenArea.contains (mx, my))
  32546. {
  32547. int deltaX = 0, deltaY = 0;
  32548. if (mx <= screenArea.getX() || mx >= screenArea.getRight())
  32549. deltaX = getScreenX() + getWidth() / 2 - mx;
  32550. if (my <= screenArea.getY() || my >= screenArea.getBottom())
  32551. deltaY = getScreenY() + getHeight() / 2 - my;
  32552. unboundedMouseOffsetX -= deltaX;
  32553. unboundedMouseOffsetY -= deltaY;
  32554. Desktop::setMousePosition (mx + deltaX,
  32555. my + deltaY);
  32556. }
  32557. else if (isCursorVisibleUntilOffscreen
  32558. && (unboundedMouseOffsetX != 0 || unboundedMouseOffsetY != 0)
  32559. && screenArea.contains (mx + unboundedMouseOffsetX,
  32560. my + unboundedMouseOffsetY))
  32561. {
  32562. mx += unboundedMouseOffsetX;
  32563. my += unboundedMouseOffsetY;
  32564. unboundedMouseOffsetX = 0;
  32565. unboundedMouseOffsetY = 0;
  32566. Desktop::setMousePosition (mx, my);
  32567. }
  32568. }
  32569. internalUpdateMouseCursor (false);
  32570. }
  32571. }
  32572. }
  32573. void Component::internalMouseMove (const int x, const int y, const int64 time)
  32574. {
  32575. const ComponentDeletionWatcher deletionChecker (this);
  32576. if (isValidComponent())
  32577. {
  32578. const MouseEvent me (x, y,
  32579. ModifierKeys::getCurrentModifiers(),
  32580. this,
  32581. Time (time),
  32582. x, y,
  32583. Time (time),
  32584. 0, false);
  32585. if (isCurrentlyBlockedByAnotherModalComponent())
  32586. {
  32587. // allow blocked mouse-events to go to global listeners..
  32588. Desktop::getInstance().sendMouseMove();
  32589. }
  32590. else
  32591. {
  32592. if (this == componentUnderMouse)
  32593. internalUpdateMouseCursor (false);
  32594. flags.mouseOverFlag = true;
  32595. mouseMove (me);
  32596. if (deletionChecker.hasBeenDeleted())
  32597. return;
  32598. Desktop::getInstance().resetTimer();
  32599. for (int i = Desktop::getInstance().mouseListeners.size(); --i >= 0;)
  32600. {
  32601. ((MouseListener*) Desktop::getInstance().mouseListeners[i])->mouseMove (me);
  32602. if (deletionChecker.hasBeenDeleted())
  32603. return;
  32604. i = jmin (i, Desktop::getInstance().mouseListeners.size());
  32605. }
  32606. if (mouseListeners_ != 0)
  32607. {
  32608. for (int i = mouseListeners_->size(); --i >= 0;)
  32609. {
  32610. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseMove (me);
  32611. if (deletionChecker.hasBeenDeleted())
  32612. return;
  32613. i = jmin (i, mouseListeners_->size());
  32614. }
  32615. }
  32616. const Component* p = parentComponent_;
  32617. while (p != 0)
  32618. {
  32619. const ComponentDeletionWatcher parentDeletionChecker (p);
  32620. for (int i = p->numDeepMouseListeners; --i >= 0;)
  32621. {
  32622. ((MouseListener*) (p->mouseListeners_->getUnchecked (i)))->mouseMove (me);
  32623. if (deletionChecker.hasBeenDeleted() || parentDeletionChecker.hasBeenDeleted())
  32624. return;
  32625. i = jmin (i, p->numDeepMouseListeners);
  32626. }
  32627. p = p->parentComponent_;
  32628. }
  32629. }
  32630. }
  32631. }
  32632. void Component::internalMouseWheel (const int intAmountX, const int intAmountY, const int64 time)
  32633. {
  32634. const ComponentDeletionWatcher deletionChecker (this);
  32635. const float wheelIncrementX = intAmountX * (1.0f / 256.0f);
  32636. const float wheelIncrementY = intAmountY * (1.0f / 256.0f);
  32637. int mx, my;
  32638. getMouseXYRelative (mx, my);
  32639. const MouseEvent me (mx, my,
  32640. ModifierKeys::getCurrentModifiers(),
  32641. this,
  32642. Time (time),
  32643. mx, my,
  32644. Time (time),
  32645. 0, false);
  32646. if (isCurrentlyBlockedByAnotherModalComponent())
  32647. {
  32648. // allow blocked mouse-events to go to global listeners..
  32649. for (int i = Desktop::getInstance().mouseListeners.size(); --i >= 0;)
  32650. {
  32651. ((MouseListener*) Desktop::getInstance().mouseListeners[i])->mouseWheelMove (me, wheelIncrementX, wheelIncrementY);
  32652. if (deletionChecker.hasBeenDeleted())
  32653. return;
  32654. i = jmin (i, Desktop::getInstance().mouseListeners.size());
  32655. }
  32656. }
  32657. else
  32658. {
  32659. mouseWheelMove (me, wheelIncrementX, wheelIncrementY);
  32660. if (deletionChecker.hasBeenDeleted())
  32661. return;
  32662. for (int i = Desktop::getInstance().mouseListeners.size(); --i >= 0;)
  32663. {
  32664. ((MouseListener*) Desktop::getInstance().mouseListeners[i])->mouseWheelMove (me, wheelIncrementX, wheelIncrementY);
  32665. if (deletionChecker.hasBeenDeleted())
  32666. return;
  32667. i = jmin (i, Desktop::getInstance().mouseListeners.size());
  32668. }
  32669. if (mouseListeners_ != 0)
  32670. {
  32671. for (int i = mouseListeners_->size(); --i >= 0;)
  32672. {
  32673. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseWheelMove (me, wheelIncrementX, wheelIncrementY);
  32674. if (deletionChecker.hasBeenDeleted())
  32675. return;
  32676. i = jmin (i, mouseListeners_->size());
  32677. }
  32678. }
  32679. const Component* p = parentComponent_;
  32680. while (p != 0)
  32681. {
  32682. const ComponentDeletionWatcher parentDeletionChecker (p);
  32683. for (int i = p->numDeepMouseListeners; --i >= 0;)
  32684. {
  32685. ((MouseListener*) (p->mouseListeners_->getUnchecked (i)))->mouseWheelMove (me, wheelIncrementX, wheelIncrementY);
  32686. if (deletionChecker.hasBeenDeleted() || parentDeletionChecker.hasBeenDeleted())
  32687. return;
  32688. i = jmin (i, p->numDeepMouseListeners);
  32689. }
  32690. p = p->parentComponent_;
  32691. }
  32692. sendFakeMouseMove();
  32693. }
  32694. }
  32695. void Component::sendFakeMouseMove() const
  32696. {
  32697. ComponentPeer* const peer = getPeer();
  32698. if (peer != 0)
  32699. peer->sendFakeMouseMove();
  32700. }
  32701. void Component::broughtToFront()
  32702. {
  32703. }
  32704. void Component::internalBroughtToFront()
  32705. {
  32706. if (isValidComponent())
  32707. {
  32708. if (flags.hasHeavyweightPeerFlag)
  32709. Desktop::getInstance().componentBroughtToFront (this);
  32710. const ComponentDeletionWatcher deletionChecker (this);
  32711. broughtToFront();
  32712. if (deletionChecker.hasBeenDeleted())
  32713. return;
  32714. if (componentListeners_ != 0)
  32715. {
  32716. for (int i = componentListeners_->size(); --i >= 0;)
  32717. {
  32718. ((ComponentListener*) componentListeners_->getUnchecked (i))
  32719. ->componentBroughtToFront (*this);
  32720. if (deletionChecker.hasBeenDeleted())
  32721. return;
  32722. i = jmin (i, componentListeners_->size());
  32723. }
  32724. }
  32725. // when brought to the front and there's a modal component blocking this one,
  32726. // we need to bring the modal one to the front instead..
  32727. Component* const cm = getCurrentlyModalComponent();
  32728. if (cm != 0 && cm->getTopLevelComponent() != getTopLevelComponent())
  32729. bringModalComponentToFront();
  32730. }
  32731. }
  32732. void Component::focusGained (FocusChangeType)
  32733. {
  32734. // base class does nothing
  32735. }
  32736. void Component::internalFocusGain (const FocusChangeType cause)
  32737. {
  32738. const ComponentDeletionWatcher deletionChecker (this);
  32739. focusGained (cause);
  32740. if (! deletionChecker.hasBeenDeleted())
  32741. internalChildFocusChange (cause);
  32742. }
  32743. void Component::focusLost (FocusChangeType)
  32744. {
  32745. // base class does nothing
  32746. }
  32747. void Component::internalFocusLoss (const FocusChangeType cause)
  32748. {
  32749. const ComponentDeletionWatcher deletionChecker (this);
  32750. focusLost (focusChangedDirectly);
  32751. if (! deletionChecker.hasBeenDeleted())
  32752. internalChildFocusChange (cause);
  32753. }
  32754. void Component::focusOfChildComponentChanged (FocusChangeType /*cause*/)
  32755. {
  32756. // base class does nothing
  32757. }
  32758. void Component::internalChildFocusChange (FocusChangeType cause)
  32759. {
  32760. const bool childIsNowFocused = hasKeyboardFocus (true);
  32761. if (flags.childCompFocusedFlag != childIsNowFocused)
  32762. {
  32763. flags.childCompFocusedFlag = childIsNowFocused;
  32764. const ComponentDeletionWatcher deletionChecker (this);
  32765. focusOfChildComponentChanged (cause);
  32766. if (deletionChecker.hasBeenDeleted())
  32767. return;
  32768. }
  32769. if (parentComponent_ != 0)
  32770. parentComponent_->internalChildFocusChange (cause);
  32771. }
  32772. bool Component::isEnabled() const throw()
  32773. {
  32774. return (! flags.isDisabledFlag)
  32775. && (parentComponent_ == 0 || parentComponent_->isEnabled());
  32776. }
  32777. void Component::setEnabled (const bool shouldBeEnabled)
  32778. {
  32779. if (flags.isDisabledFlag == shouldBeEnabled)
  32780. {
  32781. flags.isDisabledFlag = ! shouldBeEnabled;
  32782. // if any parent components are disabled, setting our flag won't make a difference,
  32783. // so no need to send a change message
  32784. if (parentComponent_ == 0 || parentComponent_->isEnabled())
  32785. sendEnablementChangeMessage();
  32786. }
  32787. }
  32788. void Component::sendEnablementChangeMessage()
  32789. {
  32790. const ComponentDeletionWatcher deletionChecker (this);
  32791. enablementChanged();
  32792. if (deletionChecker.hasBeenDeleted())
  32793. return;
  32794. for (int i = getNumChildComponents(); --i >= 0;)
  32795. {
  32796. Component* const c = getChildComponent (i);
  32797. if (c != 0)
  32798. {
  32799. c->sendEnablementChangeMessage();
  32800. if (deletionChecker.hasBeenDeleted())
  32801. return;
  32802. }
  32803. }
  32804. }
  32805. void Component::enablementChanged()
  32806. {
  32807. }
  32808. void Component::setWantsKeyboardFocus (const bool wantsFocus) throw()
  32809. {
  32810. flags.wantsFocusFlag = wantsFocus;
  32811. }
  32812. void Component::setMouseClickGrabsKeyboardFocus (const bool shouldGrabFocus)
  32813. {
  32814. flags.dontFocusOnMouseClickFlag = ! shouldGrabFocus;
  32815. }
  32816. bool Component::getMouseClickGrabsKeyboardFocus() const throw()
  32817. {
  32818. return ! flags.dontFocusOnMouseClickFlag;
  32819. }
  32820. bool Component::getWantsKeyboardFocus() const throw()
  32821. {
  32822. return flags.wantsFocusFlag && ! flags.isDisabledFlag;
  32823. }
  32824. void Component::setFocusContainer (const bool isFocusContainer) throw()
  32825. {
  32826. flags.isFocusContainerFlag = isFocusContainer;
  32827. }
  32828. bool Component::isFocusContainer() const throw()
  32829. {
  32830. return flags.isFocusContainerFlag;
  32831. }
  32832. int Component::getExplicitFocusOrder() const throw()
  32833. {
  32834. return getComponentPropertyInt (T("_jexfo"), false, 0);
  32835. }
  32836. void Component::setExplicitFocusOrder (const int newFocusOrderIndex) throw()
  32837. {
  32838. setComponentProperty (T("_jexfo"), newFocusOrderIndex);
  32839. }
  32840. KeyboardFocusTraverser* Component::createFocusTraverser()
  32841. {
  32842. if (flags.isFocusContainerFlag || parentComponent_ == 0)
  32843. return new KeyboardFocusTraverser();
  32844. return parentComponent_->createFocusTraverser();
  32845. }
  32846. void Component::takeKeyboardFocus (const FocusChangeType cause)
  32847. {
  32848. // give the focus to this component
  32849. if (currentlyFocusedComponent != this)
  32850. {
  32851. JUCE_TRY
  32852. {
  32853. // get the focus onto our desktop window
  32854. ComponentPeer* const peer = getPeer();
  32855. if (peer != 0)
  32856. {
  32857. const ComponentDeletionWatcher deletionChecker (this);
  32858. peer->grabFocus();
  32859. if (peer->isFocused() && currentlyFocusedComponent != this)
  32860. {
  32861. Component* const componentLosingFocus = currentlyFocusedComponent;
  32862. currentlyFocusedComponent = this;
  32863. Desktop::getInstance().triggerFocusCallback();
  32864. // call this after setting currentlyFocusedComponent so that the one that's
  32865. // losing it has a chance to see where focus is going
  32866. if (componentLosingFocus->isValidComponent())
  32867. componentLosingFocus->internalFocusLoss (cause);
  32868. if (currentlyFocusedComponent == this)
  32869. {
  32870. focusGained (cause);
  32871. if (! deletionChecker.hasBeenDeleted())
  32872. internalChildFocusChange (cause);
  32873. }
  32874. }
  32875. }
  32876. }
  32877. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  32878. catch (const std::exception& e)
  32879. {
  32880. currentlyFocusedComponent = 0;
  32881. Desktop::getInstance().triggerFocusCallback();
  32882. JUCEApplication::sendUnhandledException (&e, __FILE__, __LINE__);
  32883. }
  32884. catch (...)
  32885. {
  32886. currentlyFocusedComponent = 0;
  32887. Desktop::getInstance().triggerFocusCallback();
  32888. JUCEApplication::sendUnhandledException (0, __FILE__, __LINE__);
  32889. }
  32890. #endif
  32891. }
  32892. }
  32893. void Component::grabFocusInternal (const FocusChangeType cause, const bool canTryParent)
  32894. {
  32895. if (isShowing())
  32896. {
  32897. if (flags.wantsFocusFlag && (isEnabled() || parentComponent_ == 0))
  32898. {
  32899. takeKeyboardFocus (cause);
  32900. }
  32901. else
  32902. {
  32903. if (isParentOf (currentlyFocusedComponent)
  32904. && currentlyFocusedComponent->isShowing())
  32905. {
  32906. // do nothing if the focused component is actually a child of ours..
  32907. }
  32908. else
  32909. {
  32910. // find the default child component..
  32911. KeyboardFocusTraverser* const traverser = createFocusTraverser();
  32912. if (traverser != 0)
  32913. {
  32914. Component* const defaultComp = traverser->getDefaultComponent (this);
  32915. delete traverser;
  32916. if (defaultComp != 0)
  32917. {
  32918. defaultComp->grabFocusInternal (cause, false);
  32919. return;
  32920. }
  32921. }
  32922. if (canTryParent && parentComponent_ != 0)
  32923. {
  32924. // if no children want it and we're allowed to try our parent comp,
  32925. // then pass up to parent, which will try our siblings.
  32926. parentComponent_->grabFocusInternal (cause, true);
  32927. }
  32928. }
  32929. }
  32930. }
  32931. }
  32932. void Component::grabKeyboardFocus()
  32933. {
  32934. // if component methods are being called from threads other than the message
  32935. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32936. checkMessageManagerIsLocked
  32937. grabFocusInternal (focusChangedDirectly);
  32938. }
  32939. void Component::moveKeyboardFocusToSibling (const bool moveToNext)
  32940. {
  32941. // if component methods are being called from threads other than the message
  32942. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32943. checkMessageManagerIsLocked
  32944. if (parentComponent_ != 0)
  32945. {
  32946. KeyboardFocusTraverser* const traverser = createFocusTraverser();
  32947. if (traverser != 0)
  32948. {
  32949. Component* const nextComp = moveToNext ? traverser->getNextComponent (this)
  32950. : traverser->getPreviousComponent (this);
  32951. delete traverser;
  32952. if (nextComp != 0)
  32953. {
  32954. if (nextComp->isCurrentlyBlockedByAnotherModalComponent())
  32955. {
  32956. const ComponentDeletionWatcher deletionChecker (nextComp);
  32957. internalModalInputAttempt();
  32958. if (deletionChecker.hasBeenDeleted()
  32959. || nextComp->isCurrentlyBlockedByAnotherModalComponent())
  32960. return;
  32961. }
  32962. nextComp->grabFocusInternal (focusChangedByTabKey);
  32963. return;
  32964. }
  32965. }
  32966. parentComponent_->moveKeyboardFocusToSibling (moveToNext);
  32967. }
  32968. }
  32969. bool Component::hasKeyboardFocus (const bool trueIfChildIsFocused) const throw()
  32970. {
  32971. return (currentlyFocusedComponent == this)
  32972. || (trueIfChildIsFocused && isParentOf (currentlyFocusedComponent));
  32973. }
  32974. Component* JUCE_CALLTYPE Component::getCurrentlyFocusedComponent() throw()
  32975. {
  32976. return currentlyFocusedComponent;
  32977. }
  32978. void Component::giveAwayFocus()
  32979. {
  32980. // use a copy so we can clear the value before the call
  32981. Component* const componentLosingFocus = currentlyFocusedComponent;
  32982. currentlyFocusedComponent = 0;
  32983. Desktop::getInstance().triggerFocusCallback();
  32984. if (componentLosingFocus->isValidComponent())
  32985. componentLosingFocus->internalFocusLoss (focusChangedDirectly);
  32986. }
  32987. bool Component::isMouseOver() const throw()
  32988. {
  32989. return flags.mouseOverFlag;
  32990. }
  32991. bool Component::isMouseButtonDown() const throw()
  32992. {
  32993. return flags.draggingFlag;
  32994. }
  32995. bool Component::isMouseOverOrDragging() const throw()
  32996. {
  32997. return flags.mouseOverFlag || flags.draggingFlag;
  32998. }
  32999. bool JUCE_CALLTYPE Component::isMouseButtonDownAnywhere() throw()
  33000. {
  33001. return ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown();
  33002. }
  33003. void Component::getMouseXYRelative (int& mx, int& my) const throw()
  33004. {
  33005. Desktop::getMousePosition (mx, my);
  33006. globalPositionToRelative (mx, my);
  33007. mx += unboundedMouseOffsetX;
  33008. my += unboundedMouseOffsetY;
  33009. }
  33010. void Component::enableUnboundedMouseMovement (bool enable,
  33011. bool keepCursorVisibleUntilOffscreen) throw()
  33012. {
  33013. enable = enable && isMouseButtonDown();
  33014. isCursorVisibleUntilOffscreen = keepCursorVisibleUntilOffscreen;
  33015. if (enable != isUnboundedMouseModeOn)
  33016. {
  33017. if ((! enable) && ((! isCursorVisibleUntilOffscreen)
  33018. || unboundedMouseOffsetX != 0
  33019. || unboundedMouseOffsetY != 0))
  33020. {
  33021. // when released, return the mouse to within the component's bounds
  33022. int mx, my;
  33023. getMouseXYRelative (mx, my);
  33024. mx = jlimit (0, getWidth(), mx);
  33025. my = jlimit (0, getHeight(), my);
  33026. relativePositionToGlobal (mx, my);
  33027. Desktop::setMousePosition (mx, my);
  33028. }
  33029. isUnboundedMouseModeOn = enable;
  33030. unboundedMouseOffsetX = 0;
  33031. unboundedMouseOffsetY = 0;
  33032. internalUpdateMouseCursor (true);
  33033. }
  33034. }
  33035. Component* JUCE_CALLTYPE Component::getComponentUnderMouse() throw()
  33036. {
  33037. return componentUnderMouse;
  33038. }
  33039. const Rectangle Component::getParentMonitorArea() const throw()
  33040. {
  33041. int centreX = getWidth() / 2;
  33042. int centreY = getHeight() / 2;
  33043. relativePositionToGlobal (centreX, centreY);
  33044. return Desktop::getInstance().getMonitorAreaContaining (centreX, centreY);
  33045. }
  33046. void Component::addKeyListener (KeyListener* const newListener) throw()
  33047. {
  33048. if (keyListeners_ == 0)
  33049. keyListeners_ = new VoidArray (4);
  33050. keyListeners_->addIfNotAlreadyThere (newListener);
  33051. }
  33052. void Component::removeKeyListener (KeyListener* const listenerToRemove) throw()
  33053. {
  33054. if (keyListeners_ != 0)
  33055. keyListeners_->removeValue (listenerToRemove);
  33056. }
  33057. bool Component::keyPressed (const KeyPress&)
  33058. {
  33059. return false;
  33060. }
  33061. bool Component::keyStateChanged (const bool /*isKeyDown*/)
  33062. {
  33063. return false;
  33064. }
  33065. void Component::modifierKeysChanged (const ModifierKeys& modifiers)
  33066. {
  33067. if (parentComponent_ != 0)
  33068. parentComponent_->modifierKeysChanged (modifiers);
  33069. }
  33070. void Component::internalModifierKeysChanged()
  33071. {
  33072. sendFakeMouseMove();
  33073. modifierKeysChanged (ModifierKeys::getCurrentModifiers());
  33074. }
  33075. ComponentPeer* Component::getPeer() const throw()
  33076. {
  33077. if (flags.hasHeavyweightPeerFlag)
  33078. return ComponentPeer::getPeerFor (this);
  33079. else if (parentComponent_ != 0)
  33080. return parentComponent_->getPeer();
  33081. else
  33082. return 0;
  33083. }
  33084. const String Component::getComponentProperty (const String& keyName,
  33085. const bool useParentComponentIfNotFound,
  33086. const String& defaultReturnValue) const throw()
  33087. {
  33088. if (propertySet_ != 0 && ((! useParentComponentIfNotFound) || propertySet_->containsKey (keyName)))
  33089. return propertySet_->getValue (keyName, defaultReturnValue);
  33090. if (useParentComponentIfNotFound && (parentComponent_ != 0))
  33091. return parentComponent_->getComponentProperty (keyName, true, defaultReturnValue);
  33092. return defaultReturnValue;
  33093. }
  33094. int Component::getComponentPropertyInt (const String& keyName,
  33095. const bool useParentComponentIfNotFound,
  33096. const int defaultReturnValue) const throw()
  33097. {
  33098. if (propertySet_ != 0 && ((! useParentComponentIfNotFound) || propertySet_->containsKey (keyName)))
  33099. return propertySet_->getIntValue (keyName, defaultReturnValue);
  33100. if (useParentComponentIfNotFound && (parentComponent_ != 0))
  33101. return parentComponent_->getComponentPropertyInt (keyName, true, defaultReturnValue);
  33102. return defaultReturnValue;
  33103. }
  33104. double Component::getComponentPropertyDouble (const String& keyName,
  33105. const bool useParentComponentIfNotFound,
  33106. const double defaultReturnValue) const throw()
  33107. {
  33108. if (propertySet_ != 0 && ((! useParentComponentIfNotFound) || propertySet_->containsKey (keyName)))
  33109. return propertySet_->getDoubleValue (keyName, defaultReturnValue);
  33110. if (useParentComponentIfNotFound && (parentComponent_ != 0))
  33111. return parentComponent_->getComponentPropertyDouble (keyName, true, defaultReturnValue);
  33112. return defaultReturnValue;
  33113. }
  33114. bool Component::getComponentPropertyBool (const String& keyName,
  33115. const bool useParentComponentIfNotFound,
  33116. const bool defaultReturnValue) const throw()
  33117. {
  33118. if (propertySet_ != 0 && ((! useParentComponentIfNotFound) || propertySet_->containsKey (keyName)))
  33119. return propertySet_->getBoolValue (keyName, defaultReturnValue);
  33120. if (useParentComponentIfNotFound && (parentComponent_ != 0))
  33121. return parentComponent_->getComponentPropertyBool (keyName, true, defaultReturnValue);
  33122. return defaultReturnValue;
  33123. }
  33124. const Colour Component::getComponentPropertyColour (const String& keyName,
  33125. const bool useParentComponentIfNotFound,
  33126. const Colour& defaultReturnValue) const throw()
  33127. {
  33128. return Colour ((uint32) getComponentPropertyInt (keyName,
  33129. useParentComponentIfNotFound,
  33130. defaultReturnValue.getARGB()));
  33131. }
  33132. void Component::setComponentProperty (const String& keyName, const String& value) throw()
  33133. {
  33134. if (propertySet_ == 0)
  33135. propertySet_ = new PropertySet();
  33136. propertySet_->setValue (keyName, value);
  33137. }
  33138. void Component::setComponentProperty (const String& keyName, const int value) throw()
  33139. {
  33140. if (propertySet_ == 0)
  33141. propertySet_ = new PropertySet();
  33142. propertySet_->setValue (keyName, value);
  33143. }
  33144. void Component::setComponentProperty (const String& keyName, const double value) throw()
  33145. {
  33146. if (propertySet_ == 0)
  33147. propertySet_ = new PropertySet();
  33148. propertySet_->setValue (keyName, value);
  33149. }
  33150. void Component::setComponentProperty (const String& keyName, const bool value) throw()
  33151. {
  33152. if (propertySet_ == 0)
  33153. propertySet_ = new PropertySet();
  33154. propertySet_->setValue (keyName, value);
  33155. }
  33156. void Component::setComponentProperty (const String& keyName, const Colour& colour) throw()
  33157. {
  33158. setComponentProperty (keyName, (int) colour.getARGB());
  33159. }
  33160. void Component::removeComponentProperty (const String& keyName) throw()
  33161. {
  33162. if (propertySet_ != 0)
  33163. propertySet_->removeValue (keyName);
  33164. }
  33165. ComponentDeletionWatcher::ComponentDeletionWatcher (const Component* const componentToWatch_) throw()
  33166. : componentToWatch (componentToWatch_),
  33167. componentUID (componentToWatch_->getComponentUID())
  33168. {
  33169. // not possible to check on an already-deleted object..
  33170. jassert (componentToWatch_->isValidComponent());
  33171. }
  33172. ComponentDeletionWatcher::~ComponentDeletionWatcher() throw() {}
  33173. bool ComponentDeletionWatcher::hasBeenDeleted() const throw()
  33174. {
  33175. return ! (componentToWatch->isValidComponent()
  33176. && componentToWatch->getComponentUID() == componentUID);
  33177. }
  33178. const Component* ComponentDeletionWatcher::getComponent() const throw()
  33179. {
  33180. return hasBeenDeleted() ? 0 : componentToWatch;
  33181. }
  33182. END_JUCE_NAMESPACE
  33183. /********* End of inlined file: juce_Component.cpp *********/
  33184. /********* Start of inlined file: juce_ComponentListener.cpp *********/
  33185. BEGIN_JUCE_NAMESPACE
  33186. void ComponentListener::componentMovedOrResized (Component&, bool, bool)
  33187. {
  33188. }
  33189. void ComponentListener::componentBroughtToFront (Component&)
  33190. {
  33191. }
  33192. void ComponentListener::componentVisibilityChanged (Component&)
  33193. {
  33194. }
  33195. void ComponentListener::componentChildrenChanged (Component&)
  33196. {
  33197. }
  33198. void ComponentListener::componentParentHierarchyChanged (Component&)
  33199. {
  33200. }
  33201. void ComponentListener::componentNameChanged (Component&)
  33202. {
  33203. }
  33204. END_JUCE_NAMESPACE
  33205. /********* End of inlined file: juce_ComponentListener.cpp *********/
  33206. /********* Start of inlined file: juce_Desktop.cpp *********/
  33207. BEGIN_JUCE_NAMESPACE
  33208. extern void juce_updateMultiMonitorInfo (Array <Rectangle>& monitorCoords,
  33209. const bool clipToWorkArea) throw();
  33210. static Desktop* juce_desktopInstance = 0;
  33211. Desktop::Desktop() throw()
  33212. : mouseListeners (2),
  33213. desktopComponents (4),
  33214. monitorCoordsClipped (2),
  33215. monitorCoordsUnclipped (2),
  33216. lastMouseX (0),
  33217. lastMouseY (0),
  33218. kioskModeComponent (0)
  33219. {
  33220. refreshMonitorSizes();
  33221. }
  33222. Desktop::~Desktop() throw()
  33223. {
  33224. jassert (juce_desktopInstance == this);
  33225. juce_desktopInstance = 0;
  33226. // doh! If you don't delete all your windows before exiting, you're going to
  33227. // be leaking memory!
  33228. jassert (desktopComponents.size() == 0);
  33229. }
  33230. Desktop& JUCE_CALLTYPE Desktop::getInstance() throw()
  33231. {
  33232. if (juce_desktopInstance == 0)
  33233. juce_desktopInstance = new Desktop();
  33234. return *juce_desktopInstance;
  33235. }
  33236. void Desktop::refreshMonitorSizes() throw()
  33237. {
  33238. const Array <Rectangle> oldClipped (monitorCoordsClipped);
  33239. const Array <Rectangle> oldUnclipped (monitorCoordsUnclipped);
  33240. monitorCoordsClipped.clear();
  33241. monitorCoordsUnclipped.clear();
  33242. juce_updateMultiMonitorInfo (monitorCoordsClipped, true);
  33243. juce_updateMultiMonitorInfo (monitorCoordsUnclipped, false);
  33244. jassert (monitorCoordsClipped.size() > 0
  33245. && monitorCoordsClipped.size() == monitorCoordsUnclipped.size());
  33246. if (oldClipped != monitorCoordsClipped
  33247. || oldUnclipped != monitorCoordsUnclipped)
  33248. {
  33249. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  33250. {
  33251. ComponentPeer* const p = ComponentPeer::getPeer (i);
  33252. if (p != 0)
  33253. p->handleScreenSizeChange();
  33254. }
  33255. }
  33256. }
  33257. int Desktop::getNumDisplayMonitors() const throw()
  33258. {
  33259. return monitorCoordsClipped.size();
  33260. }
  33261. const Rectangle Desktop::getDisplayMonitorCoordinates (const int index, const bool clippedToWorkArea) const throw()
  33262. {
  33263. return clippedToWorkArea ? monitorCoordsClipped [index]
  33264. : monitorCoordsUnclipped [index];
  33265. }
  33266. const RectangleList Desktop::getAllMonitorDisplayAreas (const bool clippedToWorkArea) const throw()
  33267. {
  33268. RectangleList rl;
  33269. for (int i = 0; i < getNumDisplayMonitors(); ++i)
  33270. rl.addWithoutMerging (getDisplayMonitorCoordinates (i, clippedToWorkArea));
  33271. return rl;
  33272. }
  33273. const Rectangle Desktop::getMainMonitorArea (const bool clippedToWorkArea) const throw()
  33274. {
  33275. return getDisplayMonitorCoordinates (0, clippedToWorkArea);
  33276. }
  33277. const Rectangle Desktop::getMonitorAreaContaining (int cx, int cy, const bool clippedToWorkArea) const throw()
  33278. {
  33279. Rectangle best (getMainMonitorArea (clippedToWorkArea));
  33280. double bestDistance = 1.0e10;
  33281. for (int i = getNumDisplayMonitors(); --i >= 0;)
  33282. {
  33283. const Rectangle rect (getDisplayMonitorCoordinates (i, clippedToWorkArea));
  33284. if (rect.contains (cx, cy))
  33285. return rect;
  33286. const double distance = juce_hypot ((double) (rect.getCentreX() - cx),
  33287. (double) (rect.getCentreY() - cy));
  33288. if (distance < bestDistance)
  33289. {
  33290. bestDistance = distance;
  33291. best = rect;
  33292. }
  33293. }
  33294. return best;
  33295. }
  33296. int Desktop::getNumComponents() const throw()
  33297. {
  33298. return desktopComponents.size();
  33299. }
  33300. Component* Desktop::getComponent (const int index) const throw()
  33301. {
  33302. return (Component*) desktopComponents [index];
  33303. }
  33304. Component* Desktop::findComponentAt (const int screenX,
  33305. const int screenY) const
  33306. {
  33307. for (int i = desktopComponents.size(); --i >= 0;)
  33308. {
  33309. Component* const c = (Component*) desktopComponents.getUnchecked(i);
  33310. int x = screenX, y = screenY;
  33311. c->globalPositionToRelative (x, y);
  33312. if (c->contains (x, y))
  33313. return c->getComponentAt (x, y);
  33314. }
  33315. return 0;
  33316. }
  33317. void Desktop::addDesktopComponent (Component* const c) throw()
  33318. {
  33319. jassert (c != 0);
  33320. jassert (! desktopComponents.contains (c));
  33321. desktopComponents.addIfNotAlreadyThere (c);
  33322. }
  33323. void Desktop::removeDesktopComponent (Component* const c) throw()
  33324. {
  33325. desktopComponents.removeValue (c);
  33326. }
  33327. void Desktop::componentBroughtToFront (Component* const c) throw()
  33328. {
  33329. const int index = desktopComponents.indexOf (c);
  33330. jassert (index >= 0);
  33331. if (index >= 0)
  33332. desktopComponents.move (index, -1);
  33333. }
  33334. // from Component.cpp
  33335. extern int juce_recentMouseDownX [4];
  33336. extern int juce_recentMouseDownY [4];
  33337. extern int juce_MouseClickCounter;
  33338. void Desktop::getLastMouseDownPosition (int& x, int& y) throw()
  33339. {
  33340. x = juce_recentMouseDownX [0];
  33341. y = juce_recentMouseDownY [0];
  33342. }
  33343. int Desktop::getMouseButtonClickCounter() throw()
  33344. {
  33345. return juce_MouseClickCounter;
  33346. }
  33347. void Desktop::addGlobalMouseListener (MouseListener* const listener) throw()
  33348. {
  33349. jassert (listener != 0);
  33350. if (listener != 0)
  33351. {
  33352. mouseListeners.add (listener);
  33353. resetTimer();
  33354. }
  33355. }
  33356. void Desktop::removeGlobalMouseListener (MouseListener* const listener) throw()
  33357. {
  33358. mouseListeners.removeValue (listener);
  33359. resetTimer();
  33360. }
  33361. void Desktop::addFocusChangeListener (FocusChangeListener* const listener) throw()
  33362. {
  33363. jassert (listener != 0);
  33364. if (listener != 0)
  33365. focusListeners.add (listener);
  33366. }
  33367. void Desktop::removeFocusChangeListener (FocusChangeListener* const listener) throw()
  33368. {
  33369. focusListeners.removeValue (listener);
  33370. }
  33371. void Desktop::triggerFocusCallback() throw()
  33372. {
  33373. triggerAsyncUpdate();
  33374. }
  33375. void Desktop::handleAsyncUpdate()
  33376. {
  33377. for (int i = focusListeners.size(); --i >= 0;)
  33378. {
  33379. ((FocusChangeListener*) focusListeners.getUnchecked (i))->globalFocusChanged (Component::getCurrentlyFocusedComponent());
  33380. i = jmin (i, focusListeners.size());
  33381. }
  33382. }
  33383. void Desktop::timerCallback()
  33384. {
  33385. int x, y;
  33386. getMousePosition (x, y);
  33387. if (lastMouseX != x || lastMouseY != y)
  33388. sendMouseMove();
  33389. }
  33390. void Desktop::sendMouseMove()
  33391. {
  33392. if (mouseListeners.size() > 0)
  33393. {
  33394. startTimer (20);
  33395. int x, y;
  33396. getMousePosition (x, y);
  33397. lastMouseX = x;
  33398. lastMouseY = y;
  33399. Component* const target = findComponentAt (x, y);
  33400. if (target != 0)
  33401. {
  33402. target->globalPositionToRelative (x, y);
  33403. ComponentDeletionWatcher deletionChecker (target);
  33404. const MouseEvent me (x, y,
  33405. ModifierKeys::getCurrentModifiers(),
  33406. target,
  33407. Time::getCurrentTime(),
  33408. x, y,
  33409. Time::getCurrentTime(),
  33410. 0, false);
  33411. for (int i = mouseListeners.size(); --i >= 0;)
  33412. {
  33413. if (ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown())
  33414. ((MouseListener*) mouseListeners[i])->mouseDrag (me);
  33415. else
  33416. ((MouseListener*) mouseListeners[i])->mouseMove (me);
  33417. if (deletionChecker.hasBeenDeleted())
  33418. return;
  33419. i = jmin (i, mouseListeners.size());
  33420. }
  33421. }
  33422. }
  33423. }
  33424. void Desktop::resetTimer() throw()
  33425. {
  33426. if (mouseListeners.size() == 0)
  33427. stopTimer();
  33428. else
  33429. startTimer (100);
  33430. getMousePosition (lastMouseX, lastMouseY);
  33431. }
  33432. extern void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars);
  33433. void Desktop::setKioskModeComponent (Component* componentToUse, const bool allowMenusAndBars)
  33434. {
  33435. if (kioskModeComponent != componentToUse)
  33436. {
  33437. // agh! Don't delete a component without first stopping it being the kiosk comp
  33438. jassert (kioskModeComponent == 0 || kioskModeComponent->isValidComponent());
  33439. // agh! Don't remove a component from the desktop if it's the kiosk comp!
  33440. jassert (kioskModeComponent == 0 || kioskModeComponent->isOnDesktop());
  33441. if (kioskModeComponent->isValidComponent())
  33442. {
  33443. juce_setKioskComponent (kioskModeComponent, false, allowMenusAndBars);
  33444. kioskModeComponent->setBounds (kioskComponentOriginalBounds);
  33445. }
  33446. kioskModeComponent = componentToUse;
  33447. if (kioskModeComponent != 0)
  33448. {
  33449. jassert (kioskModeComponent->isValidComponent());
  33450. // Only components that are already on the desktop can be put into kiosk mode!
  33451. jassert (kioskModeComponent->isOnDesktop());
  33452. kioskComponentOriginalBounds = kioskModeComponent->getBounds();
  33453. juce_setKioskComponent (kioskModeComponent, true, allowMenusAndBars);
  33454. }
  33455. }
  33456. }
  33457. END_JUCE_NAMESPACE
  33458. /********* End of inlined file: juce_Desktop.cpp *********/
  33459. /********* Start of inlined file: juce_ArrowButton.cpp *********/
  33460. BEGIN_JUCE_NAMESPACE
  33461. ArrowButton::ArrowButton (const String& name,
  33462. float arrowDirectionInRadians,
  33463. const Colour& arrowColour)
  33464. : Button (name),
  33465. colour (arrowColour)
  33466. {
  33467. path.lineTo (0.0f, 1.0f);
  33468. path.lineTo (1.0f, 0.5f);
  33469. path.closeSubPath();
  33470. path.applyTransform (AffineTransform::rotation (float_Pi * 2.0f * arrowDirectionInRadians,
  33471. 0.5f, 0.5f));
  33472. setComponentEffect (&shadow);
  33473. buttonStateChanged();
  33474. }
  33475. ArrowButton::~ArrowButton()
  33476. {
  33477. }
  33478. void ArrowButton::paintButton (Graphics& g,
  33479. bool /*isMouseOverButton*/,
  33480. bool /*isButtonDown*/)
  33481. {
  33482. g.setColour (colour);
  33483. g.fillPath (path, path.getTransformToScaleToFit ((float) offset,
  33484. (float) offset,
  33485. (float) (getWidth() - 3),
  33486. (float) (getHeight() - 3),
  33487. false));
  33488. }
  33489. void ArrowButton::buttonStateChanged()
  33490. {
  33491. offset = (isDown()) ? 1 : 0;
  33492. shadow.setShadowProperties ((isDown()) ? 1.2f : 3.0f,
  33493. 0.3f, -1, 0);
  33494. }
  33495. END_JUCE_NAMESPACE
  33496. /********* End of inlined file: juce_ArrowButton.cpp *********/
  33497. /********* Start of inlined file: juce_Button.cpp *********/
  33498. BEGIN_JUCE_NAMESPACE
  33499. Button::Button (const String& name)
  33500. : Component (name),
  33501. shortcuts (2),
  33502. keySource (0),
  33503. text (name),
  33504. buttonListeners (2),
  33505. repeatTimer (0),
  33506. buttonPressTime (0),
  33507. lastTimeCallbackTime (0),
  33508. commandManagerToUse (0),
  33509. autoRepeatDelay (-1),
  33510. autoRepeatSpeed (0),
  33511. autoRepeatMinimumDelay (-1),
  33512. radioGroupId (0),
  33513. commandID (0),
  33514. connectedEdgeFlags (0),
  33515. buttonState (buttonNormal),
  33516. isOn (false),
  33517. clickTogglesState (false),
  33518. needsToRelease (false),
  33519. needsRepainting (false),
  33520. isKeyDown (false),
  33521. triggerOnMouseDown (false),
  33522. generateTooltip (false)
  33523. {
  33524. setWantsKeyboardFocus (true);
  33525. }
  33526. Button::~Button()
  33527. {
  33528. if (commandManagerToUse != 0)
  33529. commandManagerToUse->removeListener (this);
  33530. delete repeatTimer;
  33531. clearShortcuts();
  33532. }
  33533. void Button::setButtonText (const String& newText) throw()
  33534. {
  33535. if (text != newText)
  33536. {
  33537. text = newText;
  33538. repaint();
  33539. }
  33540. }
  33541. void Button::setTooltip (const String& newTooltip)
  33542. {
  33543. SettableTooltipClient::setTooltip (newTooltip);
  33544. generateTooltip = false;
  33545. }
  33546. const String Button::getTooltip()
  33547. {
  33548. if (generateTooltip && commandManagerToUse != 0 && commandID != 0)
  33549. {
  33550. String tt (commandManagerToUse->getDescriptionOfCommand (commandID));
  33551. Array <KeyPress> keyPresses (commandManagerToUse->getKeyMappings()->getKeyPressesAssignedToCommand (commandID));
  33552. for (int i = 0; i < keyPresses.size(); ++i)
  33553. {
  33554. const String key (keyPresses.getReference(i).getTextDescription());
  33555. if (key.length() == 1)
  33556. tt << " [shortcut: '" << key << "']";
  33557. else
  33558. tt << " [" << key << ']';
  33559. }
  33560. return tt;
  33561. }
  33562. return SettableTooltipClient::getTooltip();
  33563. }
  33564. void Button::setConnectedEdges (const int connectedEdgeFlags_) throw()
  33565. {
  33566. if (connectedEdgeFlags != connectedEdgeFlags_)
  33567. {
  33568. connectedEdgeFlags = connectedEdgeFlags_;
  33569. repaint();
  33570. }
  33571. }
  33572. void Button::setToggleState (const bool shouldBeOn,
  33573. const bool sendChangeNotification)
  33574. {
  33575. if (shouldBeOn != isOn)
  33576. {
  33577. const ComponentDeletionWatcher deletionWatcher (this);
  33578. isOn = shouldBeOn;
  33579. repaint();
  33580. if (sendChangeNotification)
  33581. sendClickMessage (ModifierKeys());
  33582. if ((! deletionWatcher.hasBeenDeleted()) && isOn)
  33583. turnOffOtherButtonsInGroup (sendChangeNotification);
  33584. }
  33585. }
  33586. void Button::setClickingTogglesState (const bool shouldToggle) throw()
  33587. {
  33588. clickTogglesState = shouldToggle;
  33589. // if you've got clickTogglesState turned on, you shouldn't also connect the button
  33590. // up to be a command invoker. Instead, your command handler must flip the state of whatever
  33591. // it is that this button represents, and the button will update its state to reflect this
  33592. // in the applicationCommandListChanged() method.
  33593. jassert (commandManagerToUse == 0 || ! clickTogglesState);
  33594. }
  33595. bool Button::getClickingTogglesState() const throw()
  33596. {
  33597. return clickTogglesState;
  33598. }
  33599. void Button::setRadioGroupId (const int newGroupId)
  33600. {
  33601. if (radioGroupId != newGroupId)
  33602. {
  33603. radioGroupId = newGroupId;
  33604. if (isOn)
  33605. turnOffOtherButtonsInGroup (true);
  33606. }
  33607. }
  33608. void Button::turnOffOtherButtonsInGroup (const bool sendChangeNotification)
  33609. {
  33610. Component* const p = getParentComponent();
  33611. if (p != 0 && radioGroupId != 0)
  33612. {
  33613. const ComponentDeletionWatcher deletionWatcher (this);
  33614. for (int i = p->getNumChildComponents(); --i >= 0;)
  33615. {
  33616. Component* const c = p->getChildComponent (i);
  33617. if (c != this)
  33618. {
  33619. Button* const b = dynamic_cast <Button*> (c);
  33620. if (b != 0 && b->getRadioGroupId() == radioGroupId)
  33621. {
  33622. b->setToggleState (false, sendChangeNotification);
  33623. if (deletionWatcher.hasBeenDeleted())
  33624. return;
  33625. }
  33626. }
  33627. }
  33628. }
  33629. }
  33630. void Button::enablementChanged()
  33631. {
  33632. updateState (0);
  33633. repaint();
  33634. }
  33635. Button::ButtonState Button::updateState (const MouseEvent* const e) throw()
  33636. {
  33637. ButtonState state = buttonNormal;
  33638. if (isEnabled() && isVisible() && ! isCurrentlyBlockedByAnotherModalComponent())
  33639. {
  33640. int mx, my;
  33641. if (e == 0)
  33642. {
  33643. getMouseXYRelative (mx, my);
  33644. }
  33645. else
  33646. {
  33647. const MouseEvent e2 (e->getEventRelativeTo (this));
  33648. mx = e2.x;
  33649. my = e2.y;
  33650. }
  33651. const bool over = reallyContains (mx, my, true);
  33652. const bool down = isMouseButtonDown();
  33653. if ((down && (over || (triggerOnMouseDown && buttonState == buttonDown))) || isKeyDown)
  33654. state = buttonDown;
  33655. else if (over)
  33656. state = buttonOver;
  33657. }
  33658. setState (state);
  33659. return state;
  33660. }
  33661. void Button::setState (const ButtonState newState)
  33662. {
  33663. if (buttonState != newState)
  33664. {
  33665. buttonState = newState;
  33666. repaint();
  33667. if (buttonState == buttonDown)
  33668. {
  33669. buttonPressTime = Time::getApproximateMillisecondCounter();
  33670. lastTimeCallbackTime = buttonPressTime;
  33671. }
  33672. sendStateMessage();
  33673. }
  33674. }
  33675. bool Button::isDown() const throw()
  33676. {
  33677. return buttonState == buttonDown;
  33678. }
  33679. bool Button::isOver() const throw()
  33680. {
  33681. return buttonState != buttonNormal;
  33682. }
  33683. void Button::buttonStateChanged()
  33684. {
  33685. }
  33686. uint32 Button::getMillisecondsSinceButtonDown() const throw()
  33687. {
  33688. const uint32 now = Time::getApproximateMillisecondCounter();
  33689. return now > buttonPressTime ? now - buttonPressTime : 0;
  33690. }
  33691. void Button::setTriggeredOnMouseDown (const bool isTriggeredOnMouseDown) throw()
  33692. {
  33693. triggerOnMouseDown = isTriggeredOnMouseDown;
  33694. }
  33695. void Button::clicked()
  33696. {
  33697. }
  33698. void Button::clicked (const ModifierKeys& /*modifiers*/)
  33699. {
  33700. clicked();
  33701. }
  33702. static const int clickMessageId = 0x2f3f4f99;
  33703. void Button::triggerClick()
  33704. {
  33705. postCommandMessage (clickMessageId);
  33706. }
  33707. void Button::internalClickCallback (const ModifierKeys& modifiers)
  33708. {
  33709. if (clickTogglesState)
  33710. setToggleState ((radioGroupId != 0) || ! isOn, false);
  33711. sendClickMessage (modifiers);
  33712. }
  33713. void Button::flashButtonState() throw()
  33714. {
  33715. if (isEnabled())
  33716. {
  33717. needsToRelease = true;
  33718. setState (buttonDown);
  33719. getRepeatTimer().startTimer (100);
  33720. }
  33721. }
  33722. void Button::handleCommandMessage (int commandId)
  33723. {
  33724. if (commandId == clickMessageId)
  33725. {
  33726. if (isEnabled())
  33727. {
  33728. flashButtonState();
  33729. internalClickCallback (ModifierKeys::getCurrentModifiers());
  33730. }
  33731. }
  33732. else
  33733. {
  33734. Component::handleCommandMessage (commandId);
  33735. }
  33736. }
  33737. void Button::addButtonListener (ButtonListener* const newListener) throw()
  33738. {
  33739. jassert (newListener != 0);
  33740. jassert (! buttonListeners.contains (newListener)); // trying to add a listener to the list twice!
  33741. if (newListener != 0)
  33742. buttonListeners.add (newListener);
  33743. }
  33744. void Button::removeButtonListener (ButtonListener* const listener) throw()
  33745. {
  33746. jassert (buttonListeners.contains (listener)); // trying to remove a listener that isn't on the list!
  33747. buttonListeners.removeValue (listener);
  33748. }
  33749. void Button::sendClickMessage (const ModifierKeys& modifiers)
  33750. {
  33751. const ComponentDeletionWatcher cdw (this);
  33752. if (commandManagerToUse != 0 && commandID != 0)
  33753. {
  33754. ApplicationCommandTarget::InvocationInfo info (commandID);
  33755. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromButton;
  33756. info.originatingComponent = this;
  33757. commandManagerToUse->invoke (info, true);
  33758. }
  33759. clicked (modifiers);
  33760. if (! cdw.hasBeenDeleted())
  33761. {
  33762. for (int i = buttonListeners.size(); --i >= 0;)
  33763. {
  33764. ButtonListener* const bl = (ButtonListener*) buttonListeners[i];
  33765. if (bl != 0)
  33766. {
  33767. bl->buttonClicked (this);
  33768. if (cdw.hasBeenDeleted())
  33769. return;
  33770. }
  33771. }
  33772. }
  33773. }
  33774. void Button::sendStateMessage()
  33775. {
  33776. const ComponentDeletionWatcher cdw (this);
  33777. buttonStateChanged();
  33778. if (cdw.hasBeenDeleted())
  33779. return;
  33780. for (int i = buttonListeners.size(); --i >= 0;)
  33781. {
  33782. ButtonListener* const bl = (ButtonListener*) buttonListeners[i];
  33783. if (bl != 0)
  33784. {
  33785. bl->buttonStateChanged (this);
  33786. if (cdw.hasBeenDeleted())
  33787. return;
  33788. }
  33789. }
  33790. }
  33791. void Button::paint (Graphics& g)
  33792. {
  33793. if (needsToRelease && isEnabled())
  33794. {
  33795. needsToRelease = false;
  33796. needsRepainting = true;
  33797. }
  33798. paintButton (g, isOver(), isDown());
  33799. }
  33800. void Button::mouseEnter (const MouseEvent& e)
  33801. {
  33802. updateState (&e);
  33803. }
  33804. void Button::mouseExit (const MouseEvent& e)
  33805. {
  33806. updateState (&e);
  33807. }
  33808. void Button::mouseDown (const MouseEvent& e)
  33809. {
  33810. updateState (&e);
  33811. if (isDown())
  33812. {
  33813. if (autoRepeatDelay >= 0)
  33814. getRepeatTimer().startTimer (autoRepeatDelay);
  33815. if (triggerOnMouseDown)
  33816. internalClickCallback (e.mods);
  33817. }
  33818. }
  33819. void Button::mouseUp (const MouseEvent& e)
  33820. {
  33821. const bool wasDown = isDown();
  33822. updateState (&e);
  33823. if (wasDown && isOver() && ! triggerOnMouseDown)
  33824. internalClickCallback (e.mods);
  33825. }
  33826. void Button::mouseDrag (const MouseEvent& e)
  33827. {
  33828. const ButtonState oldState = buttonState;
  33829. updateState (&e);
  33830. if (autoRepeatDelay >= 0 && buttonState != oldState && isDown())
  33831. getRepeatTimer().startTimer (autoRepeatSpeed);
  33832. }
  33833. void Button::focusGained (FocusChangeType)
  33834. {
  33835. updateState (0);
  33836. repaint();
  33837. }
  33838. void Button::focusLost (FocusChangeType)
  33839. {
  33840. updateState (0);
  33841. repaint();
  33842. }
  33843. void Button::setVisible (bool shouldBeVisible)
  33844. {
  33845. if (shouldBeVisible != isVisible())
  33846. {
  33847. Component::setVisible (shouldBeVisible);
  33848. if (! shouldBeVisible)
  33849. needsToRelease = false;
  33850. updateState (0);
  33851. }
  33852. else
  33853. {
  33854. Component::setVisible (shouldBeVisible);
  33855. }
  33856. }
  33857. void Button::parentHierarchyChanged()
  33858. {
  33859. Component* const newKeySource = (shortcuts.size() == 0) ? 0 : getTopLevelComponent();
  33860. if (newKeySource != keySource)
  33861. {
  33862. if (keySource->isValidComponent())
  33863. keySource->removeKeyListener (this);
  33864. keySource = newKeySource;
  33865. if (keySource->isValidComponent())
  33866. keySource->addKeyListener (this);
  33867. }
  33868. }
  33869. void Button::setCommandToTrigger (ApplicationCommandManager* const commandManagerToUse_,
  33870. const int commandID_,
  33871. const bool generateTooltip_)
  33872. {
  33873. commandID = commandID_;
  33874. generateTooltip = generateTooltip_;
  33875. if (commandManagerToUse != commandManagerToUse_)
  33876. {
  33877. if (commandManagerToUse != 0)
  33878. commandManagerToUse->removeListener (this);
  33879. commandManagerToUse = commandManagerToUse_;
  33880. if (commandManagerToUse != 0)
  33881. commandManagerToUse->addListener (this);
  33882. // if you've got clickTogglesState turned on, you shouldn't also connect the button
  33883. // up to be a command invoker. Instead, your command handler must flip the state of whatever
  33884. // it is that this button represents, and the button will update its state to reflect this
  33885. // in the applicationCommandListChanged() method.
  33886. jassert (commandManagerToUse == 0 || ! clickTogglesState);
  33887. }
  33888. if (commandManagerToUse != 0)
  33889. applicationCommandListChanged();
  33890. else
  33891. setEnabled (true);
  33892. }
  33893. void Button::applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info)
  33894. {
  33895. if (info.commandID == commandID
  33896. && (info.commandFlags & ApplicationCommandInfo::dontTriggerVisualFeedback) == 0)
  33897. {
  33898. flashButtonState();
  33899. }
  33900. }
  33901. void Button::applicationCommandListChanged()
  33902. {
  33903. if (commandManagerToUse != 0)
  33904. {
  33905. ApplicationCommandInfo info (0);
  33906. ApplicationCommandTarget* const target = commandManagerToUse->getTargetForCommand (commandID, info);
  33907. setEnabled (target != 0 && (info.flags & ApplicationCommandInfo::isDisabled) == 0);
  33908. if (target != 0)
  33909. setToggleState ((info.flags & ApplicationCommandInfo::isTicked) != 0, false);
  33910. }
  33911. }
  33912. void Button::addShortcut (const KeyPress& key)
  33913. {
  33914. if (key.isValid())
  33915. {
  33916. jassert (! isRegisteredForShortcut (key)); // already registered!
  33917. shortcuts.add (key);
  33918. parentHierarchyChanged();
  33919. }
  33920. }
  33921. void Button::clearShortcuts()
  33922. {
  33923. shortcuts.clear();
  33924. parentHierarchyChanged();
  33925. }
  33926. bool Button::isShortcutPressed() const throw()
  33927. {
  33928. if (! isCurrentlyBlockedByAnotherModalComponent())
  33929. {
  33930. for (int i = shortcuts.size(); --i >= 0;)
  33931. if (shortcuts.getReference(i).isCurrentlyDown())
  33932. return true;
  33933. }
  33934. return false;
  33935. }
  33936. bool Button::isRegisteredForShortcut (const KeyPress& key) const throw()
  33937. {
  33938. for (int i = shortcuts.size(); --i >= 0;)
  33939. if (key == shortcuts.getReference(i))
  33940. return true;
  33941. return false;
  33942. }
  33943. bool Button::keyStateChanged (const bool, Component*)
  33944. {
  33945. if (! isEnabled())
  33946. return false;
  33947. const bool wasDown = isKeyDown;
  33948. isKeyDown = isShortcutPressed();
  33949. if (autoRepeatDelay >= 0 && (isKeyDown && ! wasDown))
  33950. getRepeatTimer().startTimer (autoRepeatDelay);
  33951. updateState (0);
  33952. if (isEnabled() && wasDown && ! isKeyDown)
  33953. {
  33954. internalClickCallback (ModifierKeys::getCurrentModifiers());
  33955. // (return immediately - this button may now have been deleted)
  33956. return true;
  33957. }
  33958. return wasDown || isKeyDown;
  33959. }
  33960. bool Button::keyPressed (const KeyPress&, Component*)
  33961. {
  33962. // returning true will avoid forwarding events for keys that we're using as shortcuts
  33963. return isShortcutPressed();
  33964. }
  33965. bool Button::keyPressed (const KeyPress& key)
  33966. {
  33967. if (isEnabled() && key.isKeyCode (KeyPress::returnKey))
  33968. {
  33969. triggerClick();
  33970. return true;
  33971. }
  33972. return false;
  33973. }
  33974. void Button::setRepeatSpeed (const int initialDelayMillisecs,
  33975. const int repeatMillisecs,
  33976. const int minimumDelayInMillisecs) throw()
  33977. {
  33978. autoRepeatDelay = initialDelayMillisecs;
  33979. autoRepeatSpeed = repeatMillisecs;
  33980. autoRepeatMinimumDelay = jmin (autoRepeatSpeed, minimumDelayInMillisecs);
  33981. }
  33982. void Button::repeatTimerCallback() throw()
  33983. {
  33984. if (needsRepainting)
  33985. {
  33986. getRepeatTimer().stopTimer();
  33987. updateState (0);
  33988. needsRepainting = false;
  33989. }
  33990. else if (autoRepeatSpeed > 0 && (isKeyDown || (updateState (0) == buttonDown)))
  33991. {
  33992. int repeatSpeed = autoRepeatSpeed;
  33993. if (autoRepeatMinimumDelay >= 0)
  33994. {
  33995. double timeHeldDown = jmin (1.0, getMillisecondsSinceButtonDown() / 4000.0);
  33996. timeHeldDown *= timeHeldDown;
  33997. repeatSpeed = repeatSpeed + (int) (timeHeldDown * (autoRepeatMinimumDelay - repeatSpeed));
  33998. }
  33999. repeatSpeed = jmax (1, repeatSpeed);
  34000. getRepeatTimer().startTimer (repeatSpeed);
  34001. const uint32 now = Time::getApproximateMillisecondCounter();
  34002. const int numTimesToCallback
  34003. = (now > lastTimeCallbackTime) ? jmax (1, (now - lastTimeCallbackTime) / repeatSpeed) : 1;
  34004. lastTimeCallbackTime = now;
  34005. const ComponentDeletionWatcher cdw (this);
  34006. for (int i = numTimesToCallback; --i >= 0;)
  34007. {
  34008. internalClickCallback (ModifierKeys::getCurrentModifiers());
  34009. if (cdw.hasBeenDeleted() || ! isDown())
  34010. return;
  34011. }
  34012. }
  34013. else if (! needsToRelease)
  34014. {
  34015. getRepeatTimer().stopTimer();
  34016. }
  34017. }
  34018. class InternalButtonRepeatTimer : public Timer
  34019. {
  34020. public:
  34021. InternalButtonRepeatTimer (Button& owner_) throw()
  34022. : owner (owner_)
  34023. {
  34024. }
  34025. ~InternalButtonRepeatTimer()
  34026. {
  34027. }
  34028. void timerCallback()
  34029. {
  34030. owner.repeatTimerCallback();
  34031. }
  34032. private:
  34033. Button& owner;
  34034. InternalButtonRepeatTimer (const InternalButtonRepeatTimer&);
  34035. const InternalButtonRepeatTimer& operator= (const InternalButtonRepeatTimer&);
  34036. };
  34037. Timer& Button::getRepeatTimer() throw()
  34038. {
  34039. if (repeatTimer == 0)
  34040. repeatTimer = new InternalButtonRepeatTimer (*this);
  34041. return *repeatTimer;
  34042. }
  34043. END_JUCE_NAMESPACE
  34044. /********* End of inlined file: juce_Button.cpp *********/
  34045. /********* Start of inlined file: juce_DrawableButton.cpp *********/
  34046. BEGIN_JUCE_NAMESPACE
  34047. DrawableButton::DrawableButton (const String& name,
  34048. const DrawableButton::ButtonStyle buttonStyle)
  34049. : Button (name),
  34050. style (buttonStyle),
  34051. normalImage (0),
  34052. overImage (0),
  34053. downImage (0),
  34054. disabledImage (0),
  34055. normalImageOn (0),
  34056. overImageOn (0),
  34057. downImageOn (0),
  34058. disabledImageOn (0),
  34059. edgeIndent (3)
  34060. {
  34061. if (buttonStyle == ImageOnButtonBackground)
  34062. {
  34063. backgroundOff = Colour (0xffbbbbff);
  34064. backgroundOn = Colour (0xff3333ff);
  34065. }
  34066. else
  34067. {
  34068. backgroundOff = Colours::transparentBlack;
  34069. backgroundOn = Colour (0xaabbbbff);
  34070. }
  34071. }
  34072. DrawableButton::~DrawableButton()
  34073. {
  34074. deleteImages();
  34075. }
  34076. void DrawableButton::deleteImages()
  34077. {
  34078. deleteAndZero (normalImage);
  34079. deleteAndZero (overImage);
  34080. deleteAndZero (downImage);
  34081. deleteAndZero (disabledImage);
  34082. deleteAndZero (normalImageOn);
  34083. deleteAndZero (overImageOn);
  34084. deleteAndZero (downImageOn);
  34085. deleteAndZero (disabledImageOn);
  34086. }
  34087. void DrawableButton::setImages (const Drawable* normal,
  34088. const Drawable* over,
  34089. const Drawable* down,
  34090. const Drawable* disabled,
  34091. const Drawable* normalOn,
  34092. const Drawable* overOn,
  34093. const Drawable* downOn,
  34094. const Drawable* disabledOn)
  34095. {
  34096. deleteImages();
  34097. jassert (normal != 0); // you really need to give it at least a normal image..
  34098. if (normal != 0)
  34099. normalImage = normal->createCopy();
  34100. if (over != 0)
  34101. overImage = over->createCopy();
  34102. if (down != 0)
  34103. downImage = down->createCopy();
  34104. if (disabled != 0)
  34105. disabledImage = disabled->createCopy();
  34106. if (normalOn != 0)
  34107. normalImageOn = normalOn->createCopy();
  34108. if (overOn != 0)
  34109. overImageOn = overOn->createCopy();
  34110. if (downOn != 0)
  34111. downImageOn = downOn->createCopy();
  34112. if (disabledOn != 0)
  34113. disabledImageOn = disabledOn->createCopy();
  34114. repaint();
  34115. }
  34116. void DrawableButton::setButtonStyle (const DrawableButton::ButtonStyle newStyle)
  34117. {
  34118. if (style != newStyle)
  34119. {
  34120. style = newStyle;
  34121. repaint();
  34122. }
  34123. }
  34124. void DrawableButton::setBackgroundColours (const Colour& toggledOffColour,
  34125. const Colour& toggledOnColour)
  34126. {
  34127. if (backgroundOff != toggledOffColour
  34128. || backgroundOn != toggledOnColour)
  34129. {
  34130. backgroundOff = toggledOffColour;
  34131. backgroundOn = toggledOnColour;
  34132. repaint();
  34133. }
  34134. }
  34135. const Colour& DrawableButton::getBackgroundColour() const throw()
  34136. {
  34137. return getToggleState() ? backgroundOn
  34138. : backgroundOff;
  34139. }
  34140. void DrawableButton::setEdgeIndent (const int numPixelsIndent)
  34141. {
  34142. edgeIndent = numPixelsIndent;
  34143. repaint();
  34144. }
  34145. void DrawableButton::paintButton (Graphics& g,
  34146. bool isMouseOverButton,
  34147. bool isButtonDown)
  34148. {
  34149. Rectangle imageSpace;
  34150. if (style == ImageOnButtonBackground)
  34151. {
  34152. const int insetX = getWidth() / 4;
  34153. const int insetY = getHeight() / 4;
  34154. imageSpace.setBounds (insetX, insetY, getWidth() - insetX * 2, getHeight() - insetY * 2);
  34155. getLookAndFeel().drawButtonBackground (g, *this,
  34156. getBackgroundColour(),
  34157. isMouseOverButton,
  34158. isButtonDown);
  34159. }
  34160. else
  34161. {
  34162. g.fillAll (getBackgroundColour());
  34163. const int textH = (style == ImageAboveTextLabel)
  34164. ? jmin (16, proportionOfHeight (0.25f))
  34165. : 0;
  34166. const int indentX = jmin (edgeIndent, proportionOfWidth (0.3f));
  34167. const int indentY = jmin (edgeIndent, proportionOfHeight (0.3f));
  34168. imageSpace.setBounds (indentX, indentY,
  34169. getWidth() - indentX * 2,
  34170. getHeight() - indentY * 2 - textH);
  34171. if (textH > 0)
  34172. {
  34173. g.setFont ((float) textH);
  34174. g.setColour (Colours::black.withAlpha (isEnabled() ? 1.0f : 0.4f));
  34175. g.drawFittedText (getButtonText(),
  34176. 2, getHeight() - textH - 1,
  34177. getWidth() - 4, textH,
  34178. Justification::centred, 1);
  34179. }
  34180. }
  34181. g.setImageResamplingQuality (Graphics::mediumResamplingQuality);
  34182. g.setOpacity (1.0f);
  34183. const Drawable* imageToDraw = 0;
  34184. if (isEnabled())
  34185. {
  34186. imageToDraw = getCurrentImage();
  34187. }
  34188. else
  34189. {
  34190. imageToDraw = getToggleState() ? disabledImageOn
  34191. : disabledImage;
  34192. if (imageToDraw == 0)
  34193. {
  34194. g.setOpacity (0.4f);
  34195. imageToDraw = getNormalImage();
  34196. }
  34197. }
  34198. if (imageToDraw != 0)
  34199. {
  34200. if (style == ImageRaw)
  34201. {
  34202. imageToDraw->draw (g);
  34203. }
  34204. else
  34205. {
  34206. imageToDraw->drawWithin (g,
  34207. imageSpace.getX(),
  34208. imageSpace.getY(),
  34209. imageSpace.getWidth(),
  34210. imageSpace.getHeight(),
  34211. RectanglePlacement::centred);
  34212. }
  34213. }
  34214. }
  34215. const Drawable* DrawableButton::getCurrentImage() const throw()
  34216. {
  34217. if (isDown())
  34218. return getDownImage();
  34219. if (isOver())
  34220. return getOverImage();
  34221. return getNormalImage();
  34222. }
  34223. const Drawable* DrawableButton::getNormalImage() const throw()
  34224. {
  34225. return (getToggleState() && normalImageOn != 0) ? normalImageOn
  34226. : normalImage;
  34227. }
  34228. const Drawable* DrawableButton::getOverImage() const throw()
  34229. {
  34230. const Drawable* d = normalImage;
  34231. if (getToggleState())
  34232. {
  34233. if (overImageOn != 0)
  34234. d = overImageOn;
  34235. else if (normalImageOn != 0)
  34236. d = normalImageOn;
  34237. else if (overImage != 0)
  34238. d = overImage;
  34239. }
  34240. else
  34241. {
  34242. if (overImage != 0)
  34243. d = overImage;
  34244. }
  34245. return d;
  34246. }
  34247. const Drawable* DrawableButton::getDownImage() const throw()
  34248. {
  34249. const Drawable* d = normalImage;
  34250. if (getToggleState())
  34251. {
  34252. if (downImageOn != 0)
  34253. d = downImageOn;
  34254. else if (overImageOn != 0)
  34255. d = overImageOn;
  34256. else if (normalImageOn != 0)
  34257. d = normalImageOn;
  34258. else if (downImage != 0)
  34259. d = downImage;
  34260. else
  34261. d = getOverImage();
  34262. }
  34263. else
  34264. {
  34265. if (downImage != 0)
  34266. d = downImage;
  34267. else
  34268. d = getOverImage();
  34269. }
  34270. return d;
  34271. }
  34272. END_JUCE_NAMESPACE
  34273. /********* End of inlined file: juce_DrawableButton.cpp *********/
  34274. /********* Start of inlined file: juce_HyperlinkButton.cpp *********/
  34275. BEGIN_JUCE_NAMESPACE
  34276. HyperlinkButton::HyperlinkButton (const String& linkText,
  34277. const URL& linkURL)
  34278. : Button (linkText),
  34279. url (linkURL),
  34280. font (14.0f, Font::underlined),
  34281. resizeFont (true),
  34282. justification (Justification::centred)
  34283. {
  34284. setMouseCursor (MouseCursor::PointingHandCursor);
  34285. setTooltip (linkURL.toString (false));
  34286. }
  34287. HyperlinkButton::~HyperlinkButton()
  34288. {
  34289. }
  34290. void HyperlinkButton::setFont (const Font& newFont,
  34291. const bool resizeToMatchComponentHeight,
  34292. const Justification& justificationType)
  34293. {
  34294. font = newFont;
  34295. resizeFont = resizeToMatchComponentHeight;
  34296. justification = justificationType;
  34297. repaint();
  34298. }
  34299. void HyperlinkButton::setURL (const URL& newURL) throw()
  34300. {
  34301. url = newURL;
  34302. setTooltip (newURL.toString (false));
  34303. }
  34304. const Font HyperlinkButton::getFontToUse() const
  34305. {
  34306. Font f (font);
  34307. if (resizeFont)
  34308. f.setHeight (getHeight() * 0.7f);
  34309. return f;
  34310. }
  34311. void HyperlinkButton::changeWidthToFitText()
  34312. {
  34313. setSize (getFontToUse().getStringWidth (getName()) + 6, getHeight());
  34314. }
  34315. void HyperlinkButton::colourChanged()
  34316. {
  34317. repaint();
  34318. }
  34319. void HyperlinkButton::clicked()
  34320. {
  34321. if (url.isWellFormed())
  34322. url.launchInDefaultBrowser();
  34323. }
  34324. void HyperlinkButton::paintButton (Graphics& g,
  34325. bool isMouseOverButton,
  34326. bool isButtonDown)
  34327. {
  34328. const Colour textColour (findColour (textColourId));
  34329. if (isEnabled())
  34330. g.setColour ((isMouseOverButton) ? textColour.darker ((isButtonDown) ? 1.3f : 0.4f)
  34331. : textColour);
  34332. else
  34333. g.setColour (textColour.withMultipliedAlpha (0.4f));
  34334. g.setFont (getFontToUse());
  34335. g.drawText (getButtonText(),
  34336. 2, 0, getWidth() - 2, getHeight(),
  34337. justification.getOnlyHorizontalFlags() | Justification::verticallyCentred,
  34338. true);
  34339. }
  34340. END_JUCE_NAMESPACE
  34341. /********* End of inlined file: juce_HyperlinkButton.cpp *********/
  34342. /********* Start of inlined file: juce_ImageButton.cpp *********/
  34343. BEGIN_JUCE_NAMESPACE
  34344. ImageButton::ImageButton (const String& text_)
  34345. : Button (text_),
  34346. scaleImageToFit (true),
  34347. preserveProportions (true),
  34348. alphaThreshold (0),
  34349. imageX (0),
  34350. imageY (0),
  34351. imageW (0),
  34352. imageH (0),
  34353. normalImage (0),
  34354. overImage (0),
  34355. downImage (0)
  34356. {
  34357. }
  34358. ImageButton::~ImageButton()
  34359. {
  34360. deleteImages();
  34361. }
  34362. void ImageButton::deleteImages()
  34363. {
  34364. if (normalImage != 0)
  34365. {
  34366. if (ImageCache::isImageInCache (normalImage))
  34367. ImageCache::release (normalImage);
  34368. else
  34369. delete normalImage;
  34370. }
  34371. if (overImage != 0)
  34372. {
  34373. if (ImageCache::isImageInCache (overImage))
  34374. ImageCache::release (overImage);
  34375. else
  34376. delete overImage;
  34377. }
  34378. if (downImage != 0)
  34379. {
  34380. if (ImageCache::isImageInCache (downImage))
  34381. ImageCache::release (downImage);
  34382. else
  34383. delete downImage;
  34384. }
  34385. }
  34386. void ImageButton::setImages (const bool resizeButtonNowToFitThisImage,
  34387. const bool rescaleImagesWhenButtonSizeChanges,
  34388. const bool preserveImageProportions,
  34389. Image* const normalImage_,
  34390. const float imageOpacityWhenNormal,
  34391. const Colour& overlayColourWhenNormal,
  34392. Image* const overImage_,
  34393. const float imageOpacityWhenOver,
  34394. const Colour& overlayColourWhenOver,
  34395. Image* const downImage_,
  34396. const float imageOpacityWhenDown,
  34397. const Colour& overlayColourWhenDown,
  34398. const float hitTestAlphaThreshold)
  34399. {
  34400. deleteImages();
  34401. normalImage = normalImage_;
  34402. overImage = overImage_;
  34403. downImage = downImage_;
  34404. if (resizeButtonNowToFitThisImage && normalImage != 0)
  34405. {
  34406. imageW = normalImage->getWidth();
  34407. imageH = normalImage->getHeight();
  34408. setSize (imageW, imageH);
  34409. }
  34410. scaleImageToFit = rescaleImagesWhenButtonSizeChanges;
  34411. preserveProportions = preserveImageProportions;
  34412. normalOpacity = imageOpacityWhenNormal;
  34413. normalOverlay = overlayColourWhenNormal;
  34414. overOpacity = imageOpacityWhenOver;
  34415. overOverlay = overlayColourWhenOver;
  34416. downOpacity = imageOpacityWhenDown;
  34417. downOverlay = overlayColourWhenDown;
  34418. alphaThreshold = (unsigned char) jlimit (0, 0xff, roundFloatToInt (255.0f * hitTestAlphaThreshold));
  34419. repaint();
  34420. }
  34421. Image* ImageButton::getCurrentImage() const
  34422. {
  34423. if (isDown() || getToggleState())
  34424. return getDownImage();
  34425. if (isOver())
  34426. return getOverImage();
  34427. return getNormalImage();
  34428. }
  34429. Image* ImageButton::getNormalImage() const throw()
  34430. {
  34431. return normalImage;
  34432. }
  34433. Image* ImageButton::getOverImage() const throw()
  34434. {
  34435. return (overImage != 0) ? overImage
  34436. : normalImage;
  34437. }
  34438. Image* ImageButton::getDownImage() const throw()
  34439. {
  34440. return (downImage != 0) ? downImage
  34441. : getOverImage();
  34442. }
  34443. void ImageButton::paintButton (Graphics& g,
  34444. bool isMouseOverButton,
  34445. bool isButtonDown)
  34446. {
  34447. if (! isEnabled())
  34448. {
  34449. isMouseOverButton = false;
  34450. isButtonDown = false;
  34451. }
  34452. Image* const im = getCurrentImage();
  34453. if (im != 0)
  34454. {
  34455. const int iw = im->getWidth();
  34456. const int ih = im->getHeight();
  34457. imageW = getWidth();
  34458. imageH = getHeight();
  34459. imageX = (imageW - iw) >> 1;
  34460. imageY = (imageH - ih) >> 1;
  34461. if (scaleImageToFit)
  34462. {
  34463. if (preserveProportions)
  34464. {
  34465. int newW, newH;
  34466. const float imRatio = ih / (float)iw;
  34467. const float destRatio = imageH / (float)imageW;
  34468. if (imRatio > destRatio)
  34469. {
  34470. newW = roundFloatToInt (imageH / imRatio);
  34471. newH = imageH;
  34472. }
  34473. else
  34474. {
  34475. newW = imageW;
  34476. newH = roundFloatToInt (imageW * imRatio);
  34477. }
  34478. imageX = (imageW - newW) / 2;
  34479. imageY = (imageH - newH) / 2;
  34480. imageW = newW;
  34481. imageH = newH;
  34482. }
  34483. else
  34484. {
  34485. imageX = 0;
  34486. imageY = 0;
  34487. }
  34488. }
  34489. if (! scaleImageToFit)
  34490. {
  34491. imageW = iw;
  34492. imageH = ih;
  34493. }
  34494. getLookAndFeel().drawImageButton (g, im, imageX, imageY, imageW, imageH,
  34495. isButtonDown ? downOverlay
  34496. : (isMouseOverButton ? overOverlay
  34497. : normalOverlay),
  34498. isButtonDown ? downOpacity
  34499. : (isMouseOverButton ? overOpacity
  34500. : normalOpacity),
  34501. *this);
  34502. }
  34503. }
  34504. bool ImageButton::hitTest (int x, int y)
  34505. {
  34506. if (alphaThreshold == 0)
  34507. return true;
  34508. Image* const im = getCurrentImage();
  34509. return im == 0
  34510. || (imageW > 0 && imageH > 0
  34511. && alphaThreshold < im->getPixelAt (((x - imageX) * im->getWidth()) / imageW,
  34512. ((y - imageY) * im->getHeight()) / imageH).getAlpha());
  34513. }
  34514. END_JUCE_NAMESPACE
  34515. /********* End of inlined file: juce_ImageButton.cpp *********/
  34516. /********* Start of inlined file: juce_ShapeButton.cpp *********/
  34517. BEGIN_JUCE_NAMESPACE
  34518. ShapeButton::ShapeButton (const String& text,
  34519. const Colour& normalColour_,
  34520. const Colour& overColour_,
  34521. const Colour& downColour_)
  34522. : Button (text),
  34523. normalColour (normalColour_),
  34524. overColour (overColour_),
  34525. downColour (downColour_),
  34526. maintainShapeProportions (false),
  34527. outlineWidth (0.0f)
  34528. {
  34529. }
  34530. ShapeButton::~ShapeButton()
  34531. {
  34532. }
  34533. void ShapeButton::setColours (const Colour& newNormalColour,
  34534. const Colour& newOverColour,
  34535. const Colour& newDownColour)
  34536. {
  34537. normalColour = newNormalColour;
  34538. overColour = newOverColour;
  34539. downColour = newDownColour;
  34540. }
  34541. void ShapeButton::setOutline (const Colour& newOutlineColour,
  34542. const float newOutlineWidth)
  34543. {
  34544. outlineColour = newOutlineColour;
  34545. outlineWidth = newOutlineWidth;
  34546. }
  34547. void ShapeButton::setShape (const Path& newShape,
  34548. const bool resizeNowToFitThisShape,
  34549. const bool maintainShapeProportions_,
  34550. const bool hasShadow)
  34551. {
  34552. shape = newShape;
  34553. maintainShapeProportions = maintainShapeProportions_;
  34554. shadow.setShadowProperties (3.0f, 0.5f, 0, 0);
  34555. setComponentEffect ((hasShadow) ? &shadow : 0);
  34556. if (resizeNowToFitThisShape)
  34557. {
  34558. float x, y, w, h;
  34559. shape.getBounds (x, y, w, h);
  34560. shape.applyTransform (AffineTransform::translation (-x, -y));
  34561. if (hasShadow)
  34562. {
  34563. w += 4.0f;
  34564. h += 4.0f;
  34565. shape.applyTransform (AffineTransform::translation (2.0f, 2.0f));
  34566. }
  34567. setSize (1 + (int) (w + outlineWidth),
  34568. 1 + (int) (h + outlineWidth));
  34569. }
  34570. }
  34571. void ShapeButton::paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown)
  34572. {
  34573. if (! isEnabled())
  34574. {
  34575. isMouseOverButton = false;
  34576. isButtonDown = false;
  34577. }
  34578. g.setColour ((isButtonDown) ? downColour
  34579. : (isMouseOverButton) ? overColour
  34580. : normalColour);
  34581. int w = getWidth();
  34582. int h = getHeight();
  34583. if (getComponentEffect() != 0)
  34584. {
  34585. w -= 4;
  34586. h -= 4;
  34587. }
  34588. const float offset = (outlineWidth * 0.5f) + (isButtonDown ? 1.5f : 0.0f);
  34589. const AffineTransform trans (shape.getTransformToScaleToFit (offset, offset,
  34590. w - offset - outlineWidth,
  34591. h - offset - outlineWidth,
  34592. maintainShapeProportions));
  34593. g.fillPath (shape, trans);
  34594. if (outlineWidth > 0.0f)
  34595. {
  34596. g.setColour (outlineColour);
  34597. g.strokePath (shape, PathStrokeType (outlineWidth), trans);
  34598. }
  34599. }
  34600. END_JUCE_NAMESPACE
  34601. /********* End of inlined file: juce_ShapeButton.cpp *********/
  34602. /********* Start of inlined file: juce_TextButton.cpp *********/
  34603. BEGIN_JUCE_NAMESPACE
  34604. TextButton::TextButton (const String& name,
  34605. const String& toolTip)
  34606. : Button (name)
  34607. {
  34608. setTooltip (toolTip);
  34609. }
  34610. TextButton::~TextButton()
  34611. {
  34612. }
  34613. void TextButton::paintButton (Graphics& g,
  34614. bool isMouseOverButton,
  34615. bool isButtonDown)
  34616. {
  34617. getLookAndFeel().drawButtonBackground (g, *this,
  34618. findColour (getToggleState() ? buttonOnColourId
  34619. : buttonColourId),
  34620. isMouseOverButton,
  34621. isButtonDown);
  34622. getLookAndFeel().drawButtonText (g, *this,
  34623. isMouseOverButton,
  34624. isButtonDown);
  34625. }
  34626. void TextButton::colourChanged()
  34627. {
  34628. repaint();
  34629. }
  34630. const Font TextButton::getFont()
  34631. {
  34632. return Font (jmin (15.0f, getHeight() * 0.6f));
  34633. }
  34634. void TextButton::changeWidthToFitText (const int newHeight)
  34635. {
  34636. if (newHeight >= 0)
  34637. setSize (jmax (1, getWidth()), newHeight);
  34638. setSize (getFont().getStringWidth (getButtonText()) + getHeight(),
  34639. getHeight());
  34640. }
  34641. END_JUCE_NAMESPACE
  34642. /********* End of inlined file: juce_TextButton.cpp *********/
  34643. /********* Start of inlined file: juce_ToggleButton.cpp *********/
  34644. BEGIN_JUCE_NAMESPACE
  34645. ToggleButton::ToggleButton (const String& buttonText)
  34646. : Button (buttonText)
  34647. {
  34648. setClickingTogglesState (true);
  34649. }
  34650. ToggleButton::~ToggleButton()
  34651. {
  34652. }
  34653. void ToggleButton::paintButton (Graphics& g,
  34654. bool isMouseOverButton,
  34655. bool isButtonDown)
  34656. {
  34657. getLookAndFeel().drawToggleButton (g, *this,
  34658. isMouseOverButton,
  34659. isButtonDown);
  34660. }
  34661. void ToggleButton::changeWidthToFitText()
  34662. {
  34663. getLookAndFeel().changeToggleButtonWidthToFitText (*this);
  34664. }
  34665. void ToggleButton::colourChanged()
  34666. {
  34667. repaint();
  34668. }
  34669. END_JUCE_NAMESPACE
  34670. /********* End of inlined file: juce_ToggleButton.cpp *********/
  34671. /********* Start of inlined file: juce_ToolbarButton.cpp *********/
  34672. BEGIN_JUCE_NAMESPACE
  34673. ToolbarButton::ToolbarButton (const int itemId_,
  34674. const String& buttonText,
  34675. Drawable* const normalImage_,
  34676. Drawable* const toggledOnImage_)
  34677. : ToolbarItemComponent (itemId_, buttonText, true),
  34678. normalImage (normalImage_),
  34679. toggledOnImage (toggledOnImage_)
  34680. {
  34681. }
  34682. ToolbarButton::~ToolbarButton()
  34683. {
  34684. delete normalImage;
  34685. delete toggledOnImage;
  34686. }
  34687. bool ToolbarButton::getToolbarItemSizes (int toolbarDepth,
  34688. bool /*isToolbarVertical*/,
  34689. int& preferredSize,
  34690. int& minSize, int& maxSize)
  34691. {
  34692. preferredSize = minSize = maxSize = toolbarDepth;
  34693. return true;
  34694. }
  34695. void ToolbarButton::paintButtonArea (Graphics& g,
  34696. int width, int height,
  34697. bool /*isMouseOver*/,
  34698. bool /*isMouseDown*/)
  34699. {
  34700. Drawable* d = normalImage;
  34701. if (getToggleState() && toggledOnImage != 0)
  34702. d = toggledOnImage;
  34703. if (! isEnabled())
  34704. {
  34705. Image im (Image::ARGB, width, height, true);
  34706. Graphics g2 (im);
  34707. d->drawWithin (g2, 0, 0, width, height, RectanglePlacement::centred);
  34708. im.desaturate();
  34709. g.drawImageAt (&im, 0, 0);
  34710. }
  34711. else
  34712. {
  34713. d->drawWithin (g, 0, 0, width, height, RectanglePlacement::centred);
  34714. }
  34715. }
  34716. void ToolbarButton::contentAreaChanged (const Rectangle&)
  34717. {
  34718. }
  34719. END_JUCE_NAMESPACE
  34720. /********* End of inlined file: juce_ToolbarButton.cpp *********/
  34721. /********* Start of inlined file: juce_ComboBox.cpp *********/
  34722. BEGIN_JUCE_NAMESPACE
  34723. ComboBox::ComboBox (const String& name)
  34724. : Component (name),
  34725. items (4),
  34726. currentIndex (-1),
  34727. isButtonDown (false),
  34728. separatorPending (false),
  34729. menuActive (false),
  34730. listeners (2),
  34731. label (0)
  34732. {
  34733. noChoicesMessage = TRANS("(no choices)");
  34734. setRepaintsOnMouseActivity (true);
  34735. lookAndFeelChanged();
  34736. }
  34737. ComboBox::~ComboBox()
  34738. {
  34739. if (menuActive)
  34740. PopupMenu::dismissAllActiveMenus();
  34741. deleteAllChildren();
  34742. }
  34743. void ComboBox::setEditableText (const bool isEditable)
  34744. {
  34745. label->setEditable (isEditable, isEditable, false);
  34746. setWantsKeyboardFocus (! isEditable);
  34747. resized();
  34748. }
  34749. bool ComboBox::isTextEditable() const throw()
  34750. {
  34751. return label->isEditable();
  34752. }
  34753. void ComboBox::setJustificationType (const Justification& justification) throw()
  34754. {
  34755. label->setJustificationType (justification);
  34756. }
  34757. const Justification ComboBox::getJustificationType() const throw()
  34758. {
  34759. return label->getJustificationType();
  34760. }
  34761. void ComboBox::setTooltip (const String& newTooltip)
  34762. {
  34763. SettableTooltipClient::setTooltip (newTooltip);
  34764. label->setTooltip (newTooltip);
  34765. }
  34766. void ComboBox::addItem (const String& newItemText,
  34767. const int newItemId) throw()
  34768. {
  34769. // you can't add empty strings to the list..
  34770. jassert (newItemText.isNotEmpty());
  34771. // IDs must be non-zero, as zero is used to indicate a lack of selecion.
  34772. jassert (newItemId != 0);
  34773. // you shouldn't use duplicate item IDs!
  34774. jassert (getItemForId (newItemId) == 0);
  34775. if (newItemText.isNotEmpty() && newItemId != 0)
  34776. {
  34777. if (separatorPending)
  34778. {
  34779. separatorPending = false;
  34780. ItemInfo* const item = new ItemInfo();
  34781. item->itemId = 0;
  34782. item->isEnabled = false;
  34783. item->isHeading = false;
  34784. items.add (item);
  34785. }
  34786. ItemInfo* const item = new ItemInfo();
  34787. item->name = newItemText;
  34788. item->itemId = newItemId;
  34789. item->isEnabled = true;
  34790. item->isHeading = false;
  34791. items.add (item);
  34792. }
  34793. }
  34794. void ComboBox::addSeparator() throw()
  34795. {
  34796. separatorPending = (items.size() > 0);
  34797. }
  34798. void ComboBox::addSectionHeading (const String& headingName) throw()
  34799. {
  34800. // you can't add empty strings to the list..
  34801. jassert (headingName.isNotEmpty());
  34802. if (headingName.isNotEmpty())
  34803. {
  34804. if (separatorPending)
  34805. {
  34806. separatorPending = false;
  34807. ItemInfo* const item = new ItemInfo();
  34808. item->itemId = 0;
  34809. item->isEnabled = false;
  34810. item->isHeading = false;
  34811. items.add (item);
  34812. }
  34813. ItemInfo* const item = new ItemInfo();
  34814. item->name = headingName;
  34815. item->itemId = 0;
  34816. item->isEnabled = true;
  34817. item->isHeading = true;
  34818. items.add (item);
  34819. }
  34820. }
  34821. void ComboBox::setItemEnabled (const int itemId,
  34822. const bool isEnabled) throw()
  34823. {
  34824. ItemInfo* const item = getItemForId (itemId);
  34825. if (item != 0)
  34826. item->isEnabled = isEnabled;
  34827. }
  34828. void ComboBox::changeItemText (const int itemId,
  34829. const String& newText) throw()
  34830. {
  34831. ItemInfo* const item = getItemForId (itemId);
  34832. jassert (item != 0);
  34833. if (item != 0)
  34834. item->name = newText;
  34835. }
  34836. void ComboBox::clear (const bool dontSendChangeMessage)
  34837. {
  34838. items.clear();
  34839. separatorPending = false;
  34840. if (! label->isEditable())
  34841. setSelectedItemIndex (-1, dontSendChangeMessage);
  34842. }
  34843. ComboBox::ItemInfo* ComboBox::getItemForId (const int itemId) const throw()
  34844. {
  34845. jassert (itemId != 0);
  34846. if (itemId != 0)
  34847. {
  34848. for (int i = items.size(); --i >= 0;)
  34849. if (items.getUnchecked(i)->itemId == itemId)
  34850. return items.getUnchecked(i);
  34851. }
  34852. return 0;
  34853. }
  34854. ComboBox::ItemInfo* ComboBox::getItemForIndex (const int index) const throw()
  34855. {
  34856. int n = 0;
  34857. for (int i = 0; i < items.size(); ++i)
  34858. {
  34859. ItemInfo* const item = items.getUnchecked(i);
  34860. if (item->isRealItem())
  34861. {
  34862. if (n++ == index)
  34863. return item;
  34864. }
  34865. }
  34866. return 0;
  34867. }
  34868. int ComboBox::getNumItems() const throw()
  34869. {
  34870. int n = 0;
  34871. for (int i = items.size(); --i >= 0;)
  34872. {
  34873. ItemInfo* const item = items.getUnchecked(i);
  34874. if (item->isRealItem())
  34875. ++n;
  34876. }
  34877. return n;
  34878. }
  34879. const String ComboBox::getItemText (const int index) const throw()
  34880. {
  34881. ItemInfo* const item = getItemForIndex (index);
  34882. if (item != 0)
  34883. return item->name;
  34884. return String::empty;
  34885. }
  34886. int ComboBox::getItemId (const int index) const throw()
  34887. {
  34888. ItemInfo* const item = getItemForIndex (index);
  34889. return (item != 0) ? item->itemId : 0;
  34890. }
  34891. bool ComboBox::ItemInfo::isSeparator() const throw()
  34892. {
  34893. return name.isEmpty();
  34894. }
  34895. bool ComboBox::ItemInfo::isRealItem() const throw()
  34896. {
  34897. return ! (isHeading || name.isEmpty());
  34898. }
  34899. int ComboBox::getSelectedItemIndex() const throw()
  34900. {
  34901. return (currentIndex >= 0 && getText() == getItemText (currentIndex))
  34902. ? currentIndex
  34903. : -1;
  34904. }
  34905. void ComboBox::setSelectedItemIndex (const int index,
  34906. const bool dontSendChangeMessage) throw()
  34907. {
  34908. if (currentIndex != index || label->getText() != getItemText (currentIndex))
  34909. {
  34910. if (((unsigned int) index) < (unsigned int) getNumItems())
  34911. currentIndex = index;
  34912. else
  34913. currentIndex = -1;
  34914. label->setText (getItemText (currentIndex), false);
  34915. if (! dontSendChangeMessage)
  34916. triggerAsyncUpdate();
  34917. }
  34918. }
  34919. void ComboBox::setSelectedId (const int newItemId,
  34920. const bool dontSendChangeMessage) throw()
  34921. {
  34922. for (int i = getNumItems(); --i >= 0;)
  34923. {
  34924. if (getItemId(i) == newItemId)
  34925. {
  34926. setSelectedItemIndex (i, dontSendChangeMessage);
  34927. break;
  34928. }
  34929. }
  34930. }
  34931. int ComboBox::getSelectedId() const throw()
  34932. {
  34933. const ItemInfo* const item = getItemForIndex (currentIndex);
  34934. return (item != 0 && getText() == item->name)
  34935. ? item->itemId
  34936. : 0;
  34937. }
  34938. void ComboBox::addListener (ComboBoxListener* const listener) throw()
  34939. {
  34940. jassert (listener != 0);
  34941. if (listener != 0)
  34942. listeners.add (listener);
  34943. }
  34944. void ComboBox::removeListener (ComboBoxListener* const listener) throw()
  34945. {
  34946. listeners.removeValue (listener);
  34947. }
  34948. void ComboBox::handleAsyncUpdate()
  34949. {
  34950. for (int i = listeners.size(); --i >= 0;)
  34951. {
  34952. ((ComboBoxListener*) listeners.getUnchecked (i))->comboBoxChanged (this);
  34953. i = jmin (i, listeners.size());
  34954. }
  34955. }
  34956. const String ComboBox::getText() const throw()
  34957. {
  34958. return label->getText();
  34959. }
  34960. void ComboBox::setText (const String& newText,
  34961. const bool dontSendChangeMessage) throw()
  34962. {
  34963. for (int i = items.size(); --i >= 0;)
  34964. {
  34965. ItemInfo* const item = items.getUnchecked(i);
  34966. if (item->isRealItem()
  34967. && item->name == newText)
  34968. {
  34969. setSelectedId (item->itemId, dontSendChangeMessage);
  34970. return;
  34971. }
  34972. }
  34973. currentIndex = -1;
  34974. if (label->getText() != newText)
  34975. {
  34976. label->setText (newText, false);
  34977. if (! dontSendChangeMessage)
  34978. triggerAsyncUpdate();
  34979. }
  34980. repaint();
  34981. }
  34982. void ComboBox::showEditor()
  34983. {
  34984. jassert (isTextEditable()); // you probably shouldn't do this to a non-editable combo box?
  34985. label->showEditor();
  34986. }
  34987. void ComboBox::setTextWhenNothingSelected (const String& newMessage) throw()
  34988. {
  34989. textWhenNothingSelected = newMessage;
  34990. repaint();
  34991. }
  34992. const String ComboBox::getTextWhenNothingSelected() const throw()
  34993. {
  34994. return textWhenNothingSelected;
  34995. }
  34996. void ComboBox::setTextWhenNoChoicesAvailable (const String& newMessage) throw()
  34997. {
  34998. noChoicesMessage = newMessage;
  34999. }
  35000. const String ComboBox::getTextWhenNoChoicesAvailable() const throw()
  35001. {
  35002. return noChoicesMessage;
  35003. }
  35004. void ComboBox::paint (Graphics& g)
  35005. {
  35006. getLookAndFeel().drawComboBox (g,
  35007. getWidth(),
  35008. getHeight(),
  35009. isButtonDown,
  35010. label->getRight(),
  35011. 0,
  35012. getWidth() - label->getRight(),
  35013. getHeight(),
  35014. *this);
  35015. if (textWhenNothingSelected.isNotEmpty()
  35016. && label->getText().isEmpty()
  35017. && ! label->isBeingEdited())
  35018. {
  35019. g.setColour (findColour (textColourId).withMultipliedAlpha (0.5f));
  35020. g.setFont (label->getFont());
  35021. g.drawFittedText (textWhenNothingSelected,
  35022. label->getX() + 2, label->getY() + 1,
  35023. label->getWidth() - 4, label->getHeight() - 2,
  35024. label->getJustificationType(),
  35025. jmax (1, (int) (label->getHeight() / label->getFont().getHeight())));
  35026. }
  35027. }
  35028. void ComboBox::resized()
  35029. {
  35030. if (getHeight() > 0 && getWidth() > 0)
  35031. getLookAndFeel().positionComboBoxText (*this, *label);
  35032. }
  35033. void ComboBox::enablementChanged()
  35034. {
  35035. repaint();
  35036. }
  35037. void ComboBox::lookAndFeelChanged()
  35038. {
  35039. repaint();
  35040. Label* const newLabel = getLookAndFeel().createComboBoxTextBox (*this);
  35041. if (label != 0)
  35042. {
  35043. newLabel->setEditable (label->isEditable());
  35044. newLabel->setJustificationType (label->getJustificationType());
  35045. newLabel->setTooltip (label->getTooltip());
  35046. newLabel->setText (label->getText(), false);
  35047. }
  35048. delete label;
  35049. label = newLabel;
  35050. addAndMakeVisible (newLabel);
  35051. newLabel->addListener (this);
  35052. newLabel->addMouseListener (this, false);
  35053. newLabel->setColour (Label::backgroundColourId, Colours::transparentBlack);
  35054. newLabel->setColour (Label::textColourId, findColour (ComboBox::textColourId));
  35055. newLabel->setColour (TextEditor::textColourId, findColour (ComboBox::textColourId));
  35056. newLabel->setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  35057. newLabel->setColour (TextEditor::highlightColourId, findColour (TextEditor::highlightColourId));
  35058. newLabel->setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  35059. resized();
  35060. }
  35061. void ComboBox::colourChanged()
  35062. {
  35063. lookAndFeelChanged();
  35064. }
  35065. bool ComboBox::keyPressed (const KeyPress& key)
  35066. {
  35067. bool used = false;
  35068. if (key.isKeyCode (KeyPress::upKey)
  35069. || key.isKeyCode (KeyPress::leftKey))
  35070. {
  35071. setSelectedItemIndex (jmax (0, currentIndex - 1));
  35072. used = true;
  35073. }
  35074. else if (key.isKeyCode (KeyPress::downKey)
  35075. || key.isKeyCode (KeyPress::rightKey))
  35076. {
  35077. setSelectedItemIndex (jmin (currentIndex + 1, getNumItems() - 1));
  35078. used = true;
  35079. }
  35080. else if (key.isKeyCode (KeyPress::returnKey))
  35081. {
  35082. showPopup();
  35083. used = true;
  35084. }
  35085. return used;
  35086. }
  35087. bool ComboBox::keyStateChanged (const bool isKeyDown)
  35088. {
  35089. // only forward key events that aren't used by this component
  35090. return isKeyDown
  35091. && (KeyPress::isKeyCurrentlyDown (KeyPress::upKey)
  35092. || KeyPress::isKeyCurrentlyDown (KeyPress::leftKey)
  35093. || KeyPress::isKeyCurrentlyDown (KeyPress::downKey)
  35094. || KeyPress::isKeyCurrentlyDown (KeyPress::rightKey));
  35095. }
  35096. void ComboBox::focusGained (FocusChangeType)
  35097. {
  35098. repaint();
  35099. }
  35100. void ComboBox::focusLost (FocusChangeType)
  35101. {
  35102. repaint();
  35103. }
  35104. void ComboBox::labelTextChanged (Label*)
  35105. {
  35106. triggerAsyncUpdate();
  35107. }
  35108. void ComboBox::showPopup()
  35109. {
  35110. if (! menuActive)
  35111. {
  35112. const int currentId = getSelectedId();
  35113. ComponentDeletionWatcher deletionWatcher (this);
  35114. PopupMenu menu;
  35115. menu.setLookAndFeel (&getLookAndFeel());
  35116. for (int i = 0; i < items.size(); ++i)
  35117. {
  35118. const ItemInfo* const item = items.getUnchecked(i);
  35119. if (item->isSeparator())
  35120. menu.addSeparator();
  35121. else if (item->isHeading)
  35122. menu.addSectionHeader (item->name);
  35123. else
  35124. menu.addItem (item->itemId, item->name,
  35125. item->isEnabled, item->itemId == currentId);
  35126. }
  35127. if (items.size() == 0)
  35128. menu.addItem (1, noChoicesMessage, false);
  35129. const int itemHeight = jlimit (12, 24, getHeight());
  35130. menuActive = true;
  35131. const int resultId = menu.showAt (this, currentId,
  35132. getWidth(), 1, itemHeight);
  35133. if (deletionWatcher.hasBeenDeleted())
  35134. return;
  35135. menuActive = false;
  35136. if (resultId != 0)
  35137. setSelectedId (resultId);
  35138. }
  35139. }
  35140. void ComboBox::mouseDown (const MouseEvent& e)
  35141. {
  35142. beginDragAutoRepeat (300);
  35143. isButtonDown = isEnabled();
  35144. if (isButtonDown
  35145. && (e.eventComponent == this || ! label->isEditable()))
  35146. {
  35147. showPopup();
  35148. }
  35149. }
  35150. void ComboBox::mouseDrag (const MouseEvent& e)
  35151. {
  35152. beginDragAutoRepeat (50);
  35153. if (isButtonDown && ! e.mouseWasClicked())
  35154. showPopup();
  35155. }
  35156. void ComboBox::mouseUp (const MouseEvent& e2)
  35157. {
  35158. if (isButtonDown)
  35159. {
  35160. isButtonDown = false;
  35161. repaint();
  35162. const MouseEvent e (e2.getEventRelativeTo (this));
  35163. if (reallyContains (e.x, e.y, true)
  35164. && (e2.eventComponent == this || ! label->isEditable()))
  35165. {
  35166. showPopup();
  35167. }
  35168. }
  35169. }
  35170. END_JUCE_NAMESPACE
  35171. /********* End of inlined file: juce_ComboBox.cpp *********/
  35172. /********* Start of inlined file: juce_Label.cpp *********/
  35173. BEGIN_JUCE_NAMESPACE
  35174. Label::Label (const String& componentName,
  35175. const String& labelText)
  35176. : Component (componentName),
  35177. text (labelText),
  35178. font (15.0f),
  35179. justification (Justification::centredLeft),
  35180. editor (0),
  35181. listeners (2),
  35182. ownerComponent (0),
  35183. deletionWatcher (0),
  35184. horizontalBorderSize (3),
  35185. verticalBorderSize (1),
  35186. minimumHorizontalScale (0.7f),
  35187. editSingleClick (false),
  35188. editDoubleClick (false),
  35189. lossOfFocusDiscardsChanges (false)
  35190. {
  35191. setColour (TextEditor::textColourId, Colours::black);
  35192. setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  35193. setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  35194. }
  35195. Label::~Label()
  35196. {
  35197. if (ownerComponent != 0 && ! deletionWatcher->hasBeenDeleted())
  35198. ownerComponent->removeComponentListener (this);
  35199. deleteAndZero (deletionWatcher);
  35200. if (editor != 0)
  35201. delete editor;
  35202. }
  35203. void Label::setText (const String& newText,
  35204. const bool broadcastChangeMessage)
  35205. {
  35206. hideEditor (true);
  35207. if (text != newText)
  35208. {
  35209. text = newText;
  35210. repaint();
  35211. textWasChanged();
  35212. if (ownerComponent != 0 && ! deletionWatcher->hasBeenDeleted())
  35213. componentMovedOrResized (*ownerComponent, true, true);
  35214. if (broadcastChangeMessage)
  35215. callChangeListeners();
  35216. }
  35217. }
  35218. const String Label::getText (const bool returnActiveEditorContents) const throw()
  35219. {
  35220. return (returnActiveEditorContents && isBeingEdited())
  35221. ? editor->getText()
  35222. : text;
  35223. }
  35224. void Label::setFont (const Font& newFont) throw()
  35225. {
  35226. font = newFont;
  35227. repaint();
  35228. }
  35229. const Font& Label::getFont() const throw()
  35230. {
  35231. return font;
  35232. }
  35233. void Label::setEditable (const bool editOnSingleClick,
  35234. const bool editOnDoubleClick,
  35235. const bool lossOfFocusDiscardsChanges_) throw()
  35236. {
  35237. editSingleClick = editOnSingleClick;
  35238. editDoubleClick = editOnDoubleClick;
  35239. lossOfFocusDiscardsChanges = lossOfFocusDiscardsChanges_;
  35240. setWantsKeyboardFocus (editOnSingleClick || editOnDoubleClick);
  35241. setFocusContainer (editOnSingleClick || editOnDoubleClick);
  35242. }
  35243. void Label::setJustificationType (const Justification& justification_) throw()
  35244. {
  35245. justification = justification_;
  35246. repaint();
  35247. }
  35248. void Label::setBorderSize (int h, int v)
  35249. {
  35250. horizontalBorderSize = h;
  35251. verticalBorderSize = v;
  35252. repaint();
  35253. }
  35254. void Label::attachToComponent (Component* owner,
  35255. const bool onLeft)
  35256. {
  35257. if (ownerComponent != 0 && ! deletionWatcher->hasBeenDeleted())
  35258. ownerComponent->removeComponentListener (this);
  35259. deleteAndZero (deletionWatcher);
  35260. ownerComponent = owner;
  35261. leftOfOwnerComp = onLeft;
  35262. if (ownerComponent != 0)
  35263. {
  35264. deletionWatcher = new ComponentDeletionWatcher (owner);
  35265. setVisible (owner->isVisible());
  35266. ownerComponent->addComponentListener (this);
  35267. componentParentHierarchyChanged (*ownerComponent);
  35268. componentMovedOrResized (*ownerComponent, true, true);
  35269. }
  35270. }
  35271. void Label::componentMovedOrResized (Component& component,
  35272. bool /*wasMoved*/,
  35273. bool /*wasResized*/)
  35274. {
  35275. if (leftOfOwnerComp)
  35276. {
  35277. setSize (jmin (getFont().getStringWidth (text) + 8, component.getX()),
  35278. component.getHeight());
  35279. setTopRightPosition (component.getX(), component.getY());
  35280. }
  35281. else
  35282. {
  35283. setSize (component.getWidth(),
  35284. 8 + roundFloatToInt (getFont().getHeight()));
  35285. setTopLeftPosition (component.getX(), component.getY() - getHeight());
  35286. }
  35287. }
  35288. void Label::componentParentHierarchyChanged (Component& component)
  35289. {
  35290. if (component.getParentComponent() != 0)
  35291. component.getParentComponent()->addChildComponent (this);
  35292. }
  35293. void Label::componentVisibilityChanged (Component& component)
  35294. {
  35295. setVisible (component.isVisible());
  35296. }
  35297. void Label::textWasEdited()
  35298. {
  35299. }
  35300. void Label::textWasChanged()
  35301. {
  35302. }
  35303. void Label::showEditor()
  35304. {
  35305. if (editor == 0)
  35306. {
  35307. addAndMakeVisible (editor = createEditorComponent());
  35308. editor->setText (getText(), false);
  35309. editor->addListener (this);
  35310. editor->grabKeyboardFocus();
  35311. editor->setHighlightedRegion (0, text.length());
  35312. editor->addListener (this);
  35313. resized();
  35314. repaint();
  35315. editorShown (editor);
  35316. enterModalState();
  35317. editor->grabKeyboardFocus();
  35318. }
  35319. }
  35320. void Label::editorShown (TextEditor* editorComponent)
  35321. {
  35322. }
  35323. void Label::editorAboutToBeHidden (TextEditor* editorComponent)
  35324. {
  35325. }
  35326. bool Label::updateFromTextEditorContents()
  35327. {
  35328. jassert (editor != 0);
  35329. const String newText (editor->getText());
  35330. if (text != newText)
  35331. {
  35332. text = newText;
  35333. repaint();
  35334. textWasChanged();
  35335. if (ownerComponent != 0 && ! deletionWatcher->hasBeenDeleted())
  35336. componentMovedOrResized (*ownerComponent, true, true);
  35337. return true;
  35338. }
  35339. return false;
  35340. }
  35341. void Label::hideEditor (const bool discardCurrentEditorContents)
  35342. {
  35343. if (editor != 0)
  35344. {
  35345. editorAboutToBeHidden (editor);
  35346. const bool changed = (! discardCurrentEditorContents)
  35347. && updateFromTextEditorContents();
  35348. deleteAndZero (editor);
  35349. repaint();
  35350. if (changed)
  35351. textWasEdited();
  35352. exitModalState (0);
  35353. if (changed && isValidComponent())
  35354. callChangeListeners();
  35355. }
  35356. }
  35357. void Label::inputAttemptWhenModal()
  35358. {
  35359. if (editor != 0)
  35360. {
  35361. if (lossOfFocusDiscardsChanges)
  35362. textEditorEscapeKeyPressed (*editor);
  35363. else
  35364. textEditorReturnKeyPressed (*editor);
  35365. }
  35366. }
  35367. bool Label::isBeingEdited() const throw()
  35368. {
  35369. return editor != 0;
  35370. }
  35371. TextEditor* Label::createEditorComponent()
  35372. {
  35373. TextEditor* const ed = new TextEditor (getName());
  35374. ed->setFont (font);
  35375. // copy these colours from our own settings..
  35376. const int cols[] = { TextEditor::backgroundColourId,
  35377. TextEditor::textColourId,
  35378. TextEditor::highlightColourId,
  35379. TextEditor::highlightedTextColourId,
  35380. TextEditor::caretColourId,
  35381. TextEditor::outlineColourId,
  35382. TextEditor::focusedOutlineColourId,
  35383. TextEditor::shadowColourId };
  35384. for (int i = 0; i < numElementsInArray (cols); ++i)
  35385. ed->setColour (cols[i], findColour (cols[i]));
  35386. return ed;
  35387. }
  35388. void Label::paint (Graphics& g)
  35389. {
  35390. getLookAndFeel().drawLabel (g, *this);
  35391. }
  35392. void Label::mouseUp (const MouseEvent& e)
  35393. {
  35394. if (editSingleClick
  35395. && e.mouseWasClicked()
  35396. && contains (e.x, e.y)
  35397. && ! e.mods.isPopupMenu())
  35398. {
  35399. showEditor();
  35400. }
  35401. }
  35402. void Label::mouseDoubleClick (const MouseEvent& e)
  35403. {
  35404. if (editDoubleClick && ! e.mods.isPopupMenu())
  35405. showEditor();
  35406. }
  35407. void Label::resized()
  35408. {
  35409. if (editor != 0)
  35410. editor->setBoundsInset (BorderSize (0));
  35411. }
  35412. void Label::focusGained (FocusChangeType cause)
  35413. {
  35414. if (editSingleClick && cause == focusChangedByTabKey)
  35415. showEditor();
  35416. }
  35417. void Label::enablementChanged()
  35418. {
  35419. repaint();
  35420. }
  35421. void Label::colourChanged()
  35422. {
  35423. repaint();
  35424. }
  35425. void Label::setMinimumHorizontalScale (const float newScale)
  35426. {
  35427. if (minimumHorizontalScale != newScale)
  35428. {
  35429. minimumHorizontalScale = newScale;
  35430. repaint();
  35431. }
  35432. }
  35433. // We'll use a custom focus traverser here to make sure focus goes from the
  35434. // text editor to another component rather than back to the label itself.
  35435. class LabelKeyboardFocusTraverser : public KeyboardFocusTraverser
  35436. {
  35437. public:
  35438. LabelKeyboardFocusTraverser() {}
  35439. Component* getNextComponent (Component* current)
  35440. {
  35441. return KeyboardFocusTraverser::getNextComponent (dynamic_cast <TextEditor*> (current) != 0
  35442. ? current->getParentComponent() : current);
  35443. }
  35444. Component* getPreviousComponent (Component* current)
  35445. {
  35446. return KeyboardFocusTraverser::getPreviousComponent (dynamic_cast <TextEditor*> (current) != 0
  35447. ? current->getParentComponent() : current);
  35448. }
  35449. };
  35450. KeyboardFocusTraverser* Label::createFocusTraverser()
  35451. {
  35452. return new LabelKeyboardFocusTraverser();
  35453. }
  35454. void Label::addListener (LabelListener* const listener) throw()
  35455. {
  35456. jassert (listener != 0);
  35457. if (listener != 0)
  35458. listeners.add (listener);
  35459. }
  35460. void Label::removeListener (LabelListener* const listener) throw()
  35461. {
  35462. listeners.removeValue (listener);
  35463. }
  35464. void Label::callChangeListeners()
  35465. {
  35466. for (int i = listeners.size(); --i >= 0;)
  35467. {
  35468. ((LabelListener*) listeners.getUnchecked (i))->labelTextChanged (this);
  35469. i = jmin (i, listeners.size());
  35470. }
  35471. }
  35472. void Label::textEditorTextChanged (TextEditor& ed)
  35473. {
  35474. if (editor != 0)
  35475. {
  35476. jassert (&ed == editor);
  35477. if (! (hasKeyboardFocus (true) || isCurrentlyBlockedByAnotherModalComponent()))
  35478. {
  35479. if (lossOfFocusDiscardsChanges)
  35480. textEditorEscapeKeyPressed (ed);
  35481. else
  35482. textEditorReturnKeyPressed (ed);
  35483. }
  35484. }
  35485. }
  35486. void Label::textEditorReturnKeyPressed (TextEditor& ed)
  35487. {
  35488. if (editor != 0)
  35489. {
  35490. jassert (&ed == editor);
  35491. (void) ed;
  35492. const bool changed = updateFromTextEditorContents();
  35493. hideEditor (true);
  35494. if (changed)
  35495. {
  35496. textWasEdited();
  35497. if (isValidComponent())
  35498. callChangeListeners();
  35499. }
  35500. }
  35501. }
  35502. void Label::textEditorEscapeKeyPressed (TextEditor& ed)
  35503. {
  35504. if (editor != 0)
  35505. {
  35506. jassert (&ed == editor);
  35507. (void) ed;
  35508. editor->setText (text, false);
  35509. hideEditor (true);
  35510. }
  35511. }
  35512. void Label::textEditorFocusLost (TextEditor& ed)
  35513. {
  35514. textEditorTextChanged (ed);
  35515. }
  35516. END_JUCE_NAMESPACE
  35517. /********* End of inlined file: juce_Label.cpp *********/
  35518. /********* Start of inlined file: juce_ListBox.cpp *********/
  35519. BEGIN_JUCE_NAMESPACE
  35520. class ListBoxRowComponent : public Component
  35521. {
  35522. public:
  35523. ListBoxRowComponent (ListBox& owner_)
  35524. : owner (owner_),
  35525. row (-1),
  35526. selected (false),
  35527. isDragging (false)
  35528. {
  35529. }
  35530. ~ListBoxRowComponent()
  35531. {
  35532. deleteAllChildren();
  35533. }
  35534. void paint (Graphics& g)
  35535. {
  35536. if (owner.getModel() != 0)
  35537. owner.getModel()->paintListBoxItem (row, g, getWidth(), getHeight(), selected);
  35538. }
  35539. void update (const int row_, const bool selected_)
  35540. {
  35541. if (row != row_ || selected != selected_)
  35542. {
  35543. repaint();
  35544. row = row_;
  35545. selected = selected_;
  35546. }
  35547. if (owner.getModel() != 0)
  35548. {
  35549. Component* const customComp = owner.getModel()->refreshComponentForRow (row_, selected_, getChildComponent (0));
  35550. if (customComp != 0)
  35551. {
  35552. addAndMakeVisible (customComp);
  35553. customComp->setBounds (0, 0, getWidth(), getHeight());
  35554. for (int i = getNumChildComponents(); --i >= 0;)
  35555. if (getChildComponent (i) != customComp)
  35556. delete getChildComponent (i);
  35557. }
  35558. else
  35559. {
  35560. deleteAllChildren();
  35561. }
  35562. }
  35563. }
  35564. void mouseDown (const MouseEvent& e)
  35565. {
  35566. isDragging = false;
  35567. selectRowOnMouseUp = false;
  35568. if (isEnabled())
  35569. {
  35570. if (! selected)
  35571. {
  35572. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  35573. if (owner.getModel() != 0)
  35574. owner.getModel()->listBoxItemClicked (row, e);
  35575. }
  35576. else
  35577. {
  35578. selectRowOnMouseUp = true;
  35579. }
  35580. }
  35581. }
  35582. void mouseUp (const MouseEvent& e)
  35583. {
  35584. if (isEnabled() && selectRowOnMouseUp && ! isDragging)
  35585. {
  35586. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  35587. if (owner.getModel() != 0)
  35588. owner.getModel()->listBoxItemClicked (row, e);
  35589. }
  35590. }
  35591. void mouseDoubleClick (const MouseEvent& e)
  35592. {
  35593. if (owner.getModel() != 0 && isEnabled())
  35594. owner.getModel()->listBoxItemDoubleClicked (row, e);
  35595. }
  35596. void mouseDrag (const MouseEvent& e)
  35597. {
  35598. if (isEnabled() && owner.getModel() != 0 && ! (e.mouseWasClicked() || isDragging))
  35599. {
  35600. const SparseSet <int> selectedRows (owner.getSelectedRows());
  35601. if (selectedRows.size() > 0)
  35602. {
  35603. const String dragDescription (owner.getModel()->getDragSourceDescription (selectedRows));
  35604. if (dragDescription.isNotEmpty())
  35605. {
  35606. isDragging = true;
  35607. DragAndDropContainer* const dragContainer
  35608. = DragAndDropContainer::findParentDragContainerFor (this);
  35609. if (dragContainer != 0)
  35610. {
  35611. Image* dragImage = owner.createSnapshotOfSelectedRows();
  35612. dragImage->multiplyAllAlphas (0.6f);
  35613. dragContainer->startDragging (dragDescription, &owner, dragImage, true);
  35614. }
  35615. else
  35616. {
  35617. // to be able to do a drag-and-drop operation, the listbox needs to
  35618. // be inside a component which is also a DragAndDropContainer.
  35619. jassertfalse
  35620. }
  35621. }
  35622. }
  35623. }
  35624. }
  35625. void resized()
  35626. {
  35627. if (getNumChildComponents() > 0)
  35628. getChildComponent(0)->setBounds (0, 0, getWidth(), getHeight());
  35629. }
  35630. juce_UseDebuggingNewOperator
  35631. bool neededFlag;
  35632. private:
  35633. ListBox& owner;
  35634. int row;
  35635. bool selected, isDragging, selectRowOnMouseUp;
  35636. ListBoxRowComponent (const ListBoxRowComponent&);
  35637. const ListBoxRowComponent& operator= (const ListBoxRowComponent&);
  35638. };
  35639. class ListViewport : public Viewport
  35640. {
  35641. public:
  35642. int firstIndex, firstWholeIndex, lastWholeIndex;
  35643. bool hasUpdated;
  35644. ListViewport (ListBox& owner_)
  35645. : owner (owner_)
  35646. {
  35647. setWantsKeyboardFocus (false);
  35648. setViewedComponent (new Component());
  35649. getViewedComponent()->addMouseListener (this, false);
  35650. getViewedComponent()->setWantsKeyboardFocus (false);
  35651. }
  35652. ~ListViewport()
  35653. {
  35654. getViewedComponent()->removeMouseListener (this);
  35655. getViewedComponent()->deleteAllChildren();
  35656. }
  35657. ListBoxRowComponent* getComponentForRow (const int row) const throw()
  35658. {
  35659. return (ListBoxRowComponent*) getViewedComponent()
  35660. ->getChildComponent (row % jmax (1, getViewedComponent()->getNumChildComponents()));
  35661. }
  35662. int getRowNumberOfComponent (Component* const rowComponent) const throw()
  35663. {
  35664. const int index = getIndexOfChildComponent (rowComponent);
  35665. const int num = getViewedComponent()->getNumChildComponents();
  35666. for (int i = num; --i >= 0;)
  35667. if (((firstIndex + i) % jmax (1, num)) == index)
  35668. return firstIndex + i;
  35669. return -1;
  35670. }
  35671. Component* getComponentForRowIfOnscreen (const int row) const throw()
  35672. {
  35673. return (row >= firstIndex && row < firstIndex + getViewedComponent()->getNumChildComponents())
  35674. ? getComponentForRow (row) : 0;
  35675. }
  35676. void visibleAreaChanged (int, int, int, int)
  35677. {
  35678. updateVisibleArea (true);
  35679. if (owner.getModel() != 0)
  35680. owner.getModel()->listWasScrolled();
  35681. }
  35682. void updateVisibleArea (const bool makeSureItUpdatesContent)
  35683. {
  35684. hasUpdated = false;
  35685. const int newX = getViewedComponent()->getX();
  35686. int newY = getViewedComponent()->getY();
  35687. const int newW = jmax (owner.minimumRowWidth, getMaximumVisibleWidth());
  35688. const int newH = owner.totalItems * owner.getRowHeight();
  35689. if (newY + newH < getMaximumVisibleHeight() && newH > getMaximumVisibleHeight())
  35690. newY = getMaximumVisibleHeight() - newH;
  35691. getViewedComponent()->setBounds (newX, newY, newW, newH);
  35692. if (makeSureItUpdatesContent && ! hasUpdated)
  35693. updateContents();
  35694. }
  35695. void updateContents()
  35696. {
  35697. hasUpdated = true;
  35698. const int rowHeight = owner.getRowHeight();
  35699. if (rowHeight > 0)
  35700. {
  35701. const int y = getViewPositionY();
  35702. const int w = getViewedComponent()->getWidth();
  35703. const int numNeeded = 2 + getMaximumVisibleHeight() / rowHeight;
  35704. while (numNeeded > getViewedComponent()->getNumChildComponents())
  35705. getViewedComponent()->addAndMakeVisible (new ListBoxRowComponent (owner));
  35706. jassert (numNeeded >= 0);
  35707. while (numNeeded < getViewedComponent()->getNumChildComponents())
  35708. {
  35709. Component* const rowToRemove
  35710. = getViewedComponent()->getChildComponent (getViewedComponent()->getNumChildComponents() - 1);
  35711. delete rowToRemove;
  35712. }
  35713. firstIndex = y / rowHeight;
  35714. firstWholeIndex = (y + rowHeight - 1) / rowHeight;
  35715. lastWholeIndex = (y + getMaximumVisibleHeight() - 1) / rowHeight;
  35716. for (int i = 0; i < numNeeded; ++i)
  35717. {
  35718. const int row = i + firstIndex;
  35719. ListBoxRowComponent* const rowComp = getComponentForRow (row);
  35720. if (rowComp != 0)
  35721. {
  35722. rowComp->setBounds (0, row * rowHeight, w, rowHeight);
  35723. rowComp->update (row, owner.isRowSelected (row));
  35724. }
  35725. }
  35726. }
  35727. if (owner.headerComponent != 0)
  35728. owner.headerComponent->setBounds (owner.outlineThickness + getViewedComponent()->getX(),
  35729. owner.outlineThickness,
  35730. jmax (owner.getWidth() - owner.outlineThickness * 2,
  35731. getViewedComponent()->getWidth()),
  35732. owner.headerComponent->getHeight());
  35733. }
  35734. void paint (Graphics& g)
  35735. {
  35736. if (isOpaque())
  35737. g.fillAll (owner.findColour (ListBox::backgroundColourId));
  35738. }
  35739. bool keyPressed (const KeyPress& key)
  35740. {
  35741. if (key.isKeyCode (KeyPress::upKey)
  35742. || key.isKeyCode (KeyPress::downKey)
  35743. || key.isKeyCode (KeyPress::pageUpKey)
  35744. || key.isKeyCode (KeyPress::pageDownKey)
  35745. || key.isKeyCode (KeyPress::homeKey)
  35746. || key.isKeyCode (KeyPress::endKey))
  35747. {
  35748. // we want to avoid these keypresses going to the viewport, and instead allow
  35749. // them to pass up to our listbox..
  35750. return false;
  35751. }
  35752. return Viewport::keyPressed (key);
  35753. }
  35754. juce_UseDebuggingNewOperator
  35755. private:
  35756. ListBox& owner;
  35757. ListViewport (const ListViewport&);
  35758. const ListViewport& operator= (const ListViewport&);
  35759. };
  35760. ListBox::ListBox (const String& name, ListBoxModel* const model_)
  35761. : Component (name),
  35762. model (model_),
  35763. headerComponent (0),
  35764. totalItems (0),
  35765. rowHeight (22),
  35766. minimumRowWidth (0),
  35767. outlineThickness (0),
  35768. lastRowSelected (-1),
  35769. mouseMoveSelects (false),
  35770. multipleSelection (false),
  35771. hasDoneInitialUpdate (false)
  35772. {
  35773. addAndMakeVisible (viewport = new ListViewport (*this));
  35774. setWantsKeyboardFocus (true);
  35775. colourChanged();
  35776. }
  35777. ListBox::~ListBox()
  35778. {
  35779. deleteAllChildren();
  35780. }
  35781. void ListBox::setModel (ListBoxModel* const newModel)
  35782. {
  35783. if (model != newModel)
  35784. {
  35785. model = newModel;
  35786. updateContent();
  35787. }
  35788. }
  35789. void ListBox::setMultipleSelectionEnabled (bool b)
  35790. {
  35791. multipleSelection = b;
  35792. }
  35793. void ListBox::setMouseMoveSelectsRows (bool b)
  35794. {
  35795. mouseMoveSelects = b;
  35796. if (b)
  35797. addMouseListener (this, true);
  35798. }
  35799. void ListBox::paint (Graphics& g)
  35800. {
  35801. if (! hasDoneInitialUpdate)
  35802. updateContent();
  35803. g.fillAll (findColour (backgroundColourId));
  35804. }
  35805. void ListBox::paintOverChildren (Graphics& g)
  35806. {
  35807. if (outlineThickness > 0)
  35808. {
  35809. g.setColour (findColour (outlineColourId));
  35810. g.drawRect (0, 0, getWidth(), getHeight(), outlineThickness);
  35811. }
  35812. }
  35813. void ListBox::resized()
  35814. {
  35815. viewport->setBoundsInset (BorderSize (outlineThickness + ((headerComponent != 0) ? headerComponent->getHeight() : 0),
  35816. outlineThickness,
  35817. outlineThickness,
  35818. outlineThickness));
  35819. viewport->setSingleStepSizes (20, getRowHeight());
  35820. viewport->updateVisibleArea (false);
  35821. }
  35822. void ListBox::visibilityChanged()
  35823. {
  35824. viewport->updateVisibleArea (true);
  35825. }
  35826. Viewport* ListBox::getViewport() const throw()
  35827. {
  35828. return viewport;
  35829. }
  35830. void ListBox::updateContent()
  35831. {
  35832. hasDoneInitialUpdate = true;
  35833. totalItems = (model != 0) ? model->getNumRows() : 0;
  35834. bool selectionChanged = false;
  35835. if (selected [selected.size() - 1] >= totalItems)
  35836. {
  35837. selected.removeRange (totalItems, INT_MAX - totalItems);
  35838. lastRowSelected = getSelectedRow (0);
  35839. selectionChanged = true;
  35840. }
  35841. viewport->updateVisibleArea (isVisible());
  35842. viewport->resized();
  35843. if (selectionChanged && model != 0)
  35844. model->selectedRowsChanged (lastRowSelected);
  35845. }
  35846. void ListBox::selectRow (const int row,
  35847. bool dontScroll,
  35848. bool deselectOthersFirst)
  35849. {
  35850. selectRowInternal (row, dontScroll, deselectOthersFirst, false);
  35851. }
  35852. void ListBox::selectRowInternal (const int row,
  35853. bool dontScroll,
  35854. bool deselectOthersFirst,
  35855. bool isMouseClick)
  35856. {
  35857. if (! multipleSelection)
  35858. deselectOthersFirst = true;
  35859. if ((! isRowSelected (row))
  35860. || (deselectOthersFirst && getNumSelectedRows() > 1))
  35861. {
  35862. if (((unsigned int) row) < (unsigned int) totalItems)
  35863. {
  35864. if (deselectOthersFirst)
  35865. selected.clear();
  35866. selected.addRange (row, 1);
  35867. if (getHeight() == 0 || getWidth() == 0)
  35868. dontScroll = true;
  35869. viewport->hasUpdated = false;
  35870. if (row < viewport->firstWholeIndex && ! dontScroll)
  35871. {
  35872. viewport->setViewPosition (viewport->getViewPositionX(),
  35873. row * getRowHeight());
  35874. }
  35875. else if (row >= viewport->lastWholeIndex && ! dontScroll)
  35876. {
  35877. const int rowsOnScreen = viewport->lastWholeIndex - viewport->firstWholeIndex;
  35878. if (row >= lastRowSelected + rowsOnScreen
  35879. && rowsOnScreen < totalItems - 1
  35880. && ! isMouseClick)
  35881. {
  35882. viewport->setViewPosition (viewport->getViewPositionX(),
  35883. jlimit (0, jmax (0, totalItems - rowsOnScreen), row)
  35884. * getRowHeight());
  35885. }
  35886. else
  35887. {
  35888. viewport->setViewPosition (viewport->getViewPositionX(),
  35889. jmax (0, (row + 1) * getRowHeight() - viewport->getMaximumVisibleHeight()));
  35890. }
  35891. }
  35892. if (! viewport->hasUpdated)
  35893. viewport->updateContents();
  35894. lastRowSelected = row;
  35895. model->selectedRowsChanged (row);
  35896. }
  35897. else
  35898. {
  35899. if (deselectOthersFirst)
  35900. deselectAllRows();
  35901. }
  35902. }
  35903. }
  35904. void ListBox::deselectRow (const int row)
  35905. {
  35906. if (selected.contains (row))
  35907. {
  35908. selected.removeRange (row, 1);
  35909. if (row == lastRowSelected)
  35910. lastRowSelected = getSelectedRow (0);
  35911. viewport->updateContents();
  35912. model->selectedRowsChanged (lastRowSelected);
  35913. }
  35914. }
  35915. void ListBox::setSelectedRows (const SparseSet<int>& setOfRowsToBeSelected,
  35916. const bool sendNotificationEventToModel)
  35917. {
  35918. selected = setOfRowsToBeSelected;
  35919. selected.removeRange (totalItems, INT_MAX - totalItems);
  35920. if (! isRowSelected (lastRowSelected))
  35921. lastRowSelected = getSelectedRow (0);
  35922. viewport->updateContents();
  35923. if ((model != 0) && sendNotificationEventToModel)
  35924. model->selectedRowsChanged (lastRowSelected);
  35925. }
  35926. const SparseSet<int> ListBox::getSelectedRows() const
  35927. {
  35928. return selected;
  35929. }
  35930. void ListBox::selectRangeOfRows (int firstRow, int lastRow)
  35931. {
  35932. if (multipleSelection && (firstRow != lastRow))
  35933. {
  35934. const int numRows = totalItems - 1;
  35935. firstRow = jlimit (0, jmax (0, numRows), firstRow);
  35936. lastRow = jlimit (0, jmax (0, numRows), lastRow);
  35937. selected.addRange (jmin (firstRow, lastRow),
  35938. abs (firstRow - lastRow) + 1);
  35939. selected.removeRange (lastRow, 1);
  35940. }
  35941. selectRowInternal (lastRow, false, false, true);
  35942. }
  35943. void ListBox::flipRowSelection (const int row)
  35944. {
  35945. if (isRowSelected (row))
  35946. deselectRow (row);
  35947. else
  35948. selectRowInternal (row, false, false, true);
  35949. }
  35950. void ListBox::deselectAllRows()
  35951. {
  35952. if (! selected.isEmpty())
  35953. {
  35954. selected.clear();
  35955. lastRowSelected = -1;
  35956. viewport->updateContents();
  35957. if (model != 0)
  35958. model->selectedRowsChanged (lastRowSelected);
  35959. }
  35960. }
  35961. void ListBox::selectRowsBasedOnModifierKeys (const int row,
  35962. const ModifierKeys& mods)
  35963. {
  35964. if (multipleSelection && mods.isCommandDown())
  35965. {
  35966. flipRowSelection (row);
  35967. }
  35968. else if (multipleSelection && mods.isShiftDown() && lastRowSelected >= 0)
  35969. {
  35970. selectRangeOfRows (lastRowSelected, row);
  35971. }
  35972. else if ((! mods.isPopupMenu()) || ! isRowSelected (row))
  35973. {
  35974. selectRowInternal (row, false, true, true);
  35975. }
  35976. }
  35977. int ListBox::getNumSelectedRows() const
  35978. {
  35979. return selected.size();
  35980. }
  35981. int ListBox::getSelectedRow (const int index) const
  35982. {
  35983. return (((unsigned int) index) < (unsigned int) selected.size())
  35984. ? selected [index] : -1;
  35985. }
  35986. bool ListBox::isRowSelected (const int row) const
  35987. {
  35988. return selected.contains (row);
  35989. }
  35990. int ListBox::getLastRowSelected() const
  35991. {
  35992. return (isRowSelected (lastRowSelected)) ? lastRowSelected : -1;
  35993. }
  35994. int ListBox::getRowContainingPosition (const int x, const int y) const throw()
  35995. {
  35996. if (((unsigned int) x) < (unsigned int) getWidth())
  35997. {
  35998. const int row = (viewport->getViewPositionY() + y - viewport->getY()) / rowHeight;
  35999. if (((unsigned int) row) < (unsigned int) totalItems)
  36000. return row;
  36001. }
  36002. return -1;
  36003. }
  36004. int ListBox::getInsertionIndexForPosition (const int x, const int y) const throw()
  36005. {
  36006. if (((unsigned int) x) < (unsigned int) getWidth())
  36007. {
  36008. const int row = (viewport->getViewPositionY() + y + rowHeight / 2 - viewport->getY()) / rowHeight;
  36009. return jlimit (0, totalItems, row);
  36010. }
  36011. return -1;
  36012. }
  36013. Component* ListBox::getComponentForRowNumber (const int row) const throw()
  36014. {
  36015. Component* const listRowComp = viewport->getComponentForRowIfOnscreen (row);
  36016. return listRowComp != 0 ? listRowComp->getChildComponent (0) : 0;
  36017. }
  36018. int ListBox::getRowNumberOfComponent (Component* const rowComponent) const throw()
  36019. {
  36020. return viewport->getRowNumberOfComponent (rowComponent);
  36021. }
  36022. const Rectangle ListBox::getRowPosition (const int rowNumber,
  36023. const bool relativeToComponentTopLeft) const throw()
  36024. {
  36025. const int rowHeight = getRowHeight();
  36026. int y = viewport->getY() + rowHeight * rowNumber;
  36027. if (relativeToComponentTopLeft)
  36028. y -= viewport->getViewPositionY();
  36029. return Rectangle (viewport->getX(), y,
  36030. viewport->getViewedComponent()->getWidth(), rowHeight);
  36031. }
  36032. void ListBox::setVerticalPosition (const double proportion)
  36033. {
  36034. const int offscreen = viewport->getViewedComponent()->getHeight() - viewport->getHeight();
  36035. viewport->setViewPosition (viewport->getViewPositionX(),
  36036. jmax (0, roundDoubleToInt (proportion * offscreen)));
  36037. }
  36038. double ListBox::getVerticalPosition() const
  36039. {
  36040. const int offscreen = viewport->getViewedComponent()->getHeight() - viewport->getHeight();
  36041. return (offscreen > 0) ? viewport->getViewPositionY() / (double) offscreen
  36042. : 0;
  36043. }
  36044. int ListBox::getVisibleRowWidth() const throw()
  36045. {
  36046. return viewport->getViewWidth();
  36047. }
  36048. void ListBox::scrollToEnsureRowIsOnscreen (const int row)
  36049. {
  36050. if (row < viewport->firstWholeIndex)
  36051. {
  36052. viewport->setViewPosition (viewport->getViewPositionX(),
  36053. row * getRowHeight());
  36054. }
  36055. else if (row >= viewport->lastWholeIndex)
  36056. {
  36057. viewport->setViewPosition (viewport->getViewPositionX(),
  36058. jmax (0, (row + 1) * getRowHeight() - viewport->getMaximumVisibleHeight()));
  36059. }
  36060. }
  36061. bool ListBox::keyPressed (const KeyPress& key)
  36062. {
  36063. const int numVisibleRows = viewport->getHeight() / getRowHeight();
  36064. const bool multiple = multipleSelection
  36065. && (lastRowSelected >= 0)
  36066. && (key.getModifiers().isShiftDown()
  36067. || key.getModifiers().isCtrlDown()
  36068. || key.getModifiers().isCommandDown());
  36069. if (key.isKeyCode (KeyPress::upKey))
  36070. {
  36071. if (multiple)
  36072. selectRangeOfRows (lastRowSelected, lastRowSelected - 1);
  36073. else
  36074. selectRow (jmax (0, lastRowSelected - 1));
  36075. }
  36076. else if (key.isKeyCode (KeyPress::returnKey)
  36077. && isRowSelected (lastRowSelected))
  36078. {
  36079. if (model != 0)
  36080. model->returnKeyPressed (lastRowSelected);
  36081. }
  36082. else if (key.isKeyCode (KeyPress::pageUpKey))
  36083. {
  36084. if (multiple)
  36085. selectRangeOfRows (lastRowSelected, lastRowSelected - numVisibleRows);
  36086. else
  36087. selectRow (jmax (0, jmax (0, lastRowSelected) - numVisibleRows));
  36088. }
  36089. else if (key.isKeyCode (KeyPress::pageDownKey))
  36090. {
  36091. if (multiple)
  36092. selectRangeOfRows (lastRowSelected, lastRowSelected + numVisibleRows);
  36093. else
  36094. selectRow (jmin (totalItems - 1, jmax (0, lastRowSelected) + numVisibleRows));
  36095. }
  36096. else if (key.isKeyCode (KeyPress::homeKey))
  36097. {
  36098. if (multiple && key.getModifiers().isShiftDown())
  36099. selectRangeOfRows (lastRowSelected, 0);
  36100. else
  36101. selectRow (0);
  36102. }
  36103. else if (key.isKeyCode (KeyPress::endKey))
  36104. {
  36105. if (multiple && key.getModifiers().isShiftDown())
  36106. selectRangeOfRows (lastRowSelected, totalItems - 1);
  36107. else
  36108. selectRow (totalItems - 1);
  36109. }
  36110. else if (key.isKeyCode (KeyPress::downKey))
  36111. {
  36112. if (multiple)
  36113. selectRangeOfRows (lastRowSelected, lastRowSelected + 1);
  36114. else
  36115. selectRow (jmin (totalItems - 1, jmax (0, lastRowSelected) + 1));
  36116. }
  36117. else if ((key.isKeyCode (KeyPress::deleteKey) || key.isKeyCode (KeyPress::backspaceKey))
  36118. && isRowSelected (lastRowSelected))
  36119. {
  36120. if (model != 0)
  36121. model->deleteKeyPressed (lastRowSelected);
  36122. }
  36123. else if (multiple && key == KeyPress (T('a'), ModifierKeys::commandModifier, 0))
  36124. {
  36125. selectRangeOfRows (0, INT_MAX);
  36126. }
  36127. else
  36128. {
  36129. return false;
  36130. }
  36131. return true;
  36132. }
  36133. bool ListBox::keyStateChanged (const bool isKeyDown)
  36134. {
  36135. return isKeyDown
  36136. && (KeyPress::isKeyCurrentlyDown (KeyPress::upKey)
  36137. || KeyPress::isKeyCurrentlyDown (KeyPress::pageUpKey)
  36138. || KeyPress::isKeyCurrentlyDown (KeyPress::downKey)
  36139. || KeyPress::isKeyCurrentlyDown (KeyPress::pageDownKey)
  36140. || KeyPress::isKeyCurrentlyDown (KeyPress::homeKey)
  36141. || KeyPress::isKeyCurrentlyDown (KeyPress::endKey)
  36142. || KeyPress::isKeyCurrentlyDown (KeyPress::returnKey));
  36143. }
  36144. void ListBox::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  36145. {
  36146. getHorizontalScrollBar()->mouseWheelMove (e, wheelIncrementX, 0);
  36147. getVerticalScrollBar()->mouseWheelMove (e, 0, wheelIncrementY);
  36148. }
  36149. void ListBox::mouseMove (const MouseEvent& e)
  36150. {
  36151. if (mouseMoveSelects)
  36152. {
  36153. const MouseEvent e2 (e.getEventRelativeTo (this));
  36154. selectRow (getRowContainingPosition (e2.x, e2.y), true);
  36155. lastMouseX = e2.x;
  36156. lastMouseY = e2.y;
  36157. }
  36158. }
  36159. void ListBox::mouseExit (const MouseEvent& e)
  36160. {
  36161. mouseMove (e);
  36162. }
  36163. void ListBox::mouseUp (const MouseEvent& e)
  36164. {
  36165. if (e.mouseWasClicked() && model != 0)
  36166. model->backgroundClicked();
  36167. }
  36168. void ListBox::setRowHeight (const int newHeight)
  36169. {
  36170. rowHeight = jmax (1, newHeight);
  36171. viewport->setSingleStepSizes (20, rowHeight);
  36172. updateContent();
  36173. }
  36174. int ListBox::getNumRowsOnScreen() const throw()
  36175. {
  36176. return viewport->getMaximumVisibleHeight() / rowHeight;
  36177. }
  36178. void ListBox::setMinimumContentWidth (const int newMinimumWidth)
  36179. {
  36180. minimumRowWidth = newMinimumWidth;
  36181. updateContent();
  36182. }
  36183. int ListBox::getVisibleContentWidth() const throw()
  36184. {
  36185. return viewport->getMaximumVisibleWidth();
  36186. }
  36187. ScrollBar* ListBox::getVerticalScrollBar() const throw()
  36188. {
  36189. return viewport->getVerticalScrollBar();
  36190. }
  36191. ScrollBar* ListBox::getHorizontalScrollBar() const throw()
  36192. {
  36193. return viewport->getHorizontalScrollBar();
  36194. }
  36195. void ListBox::colourChanged()
  36196. {
  36197. setOpaque (findColour (backgroundColourId).isOpaque());
  36198. viewport->setOpaque (isOpaque());
  36199. repaint();
  36200. }
  36201. void ListBox::setOutlineThickness (const int outlineThickness_)
  36202. {
  36203. outlineThickness = outlineThickness_;
  36204. resized();
  36205. }
  36206. void ListBox::setHeaderComponent (Component* const newHeaderComponent)
  36207. {
  36208. if (headerComponent != newHeaderComponent)
  36209. {
  36210. if (headerComponent != 0)
  36211. delete headerComponent;
  36212. headerComponent = newHeaderComponent;
  36213. addAndMakeVisible (newHeaderComponent);
  36214. ListBox::resized();
  36215. }
  36216. }
  36217. void ListBox::repaintRow (const int rowNumber) throw()
  36218. {
  36219. const Rectangle r (getRowPosition (rowNumber, true));
  36220. repaint (r.getX(), r.getY(), r.getWidth(), r.getHeight());
  36221. }
  36222. Image* ListBox::createSnapshotOfSelectedRows()
  36223. {
  36224. Image* snapshot = new Image (Image::ARGB, getWidth(), getHeight(), true);
  36225. Graphics g (*snapshot);
  36226. const int firstRow = getRowContainingPosition (0, 0);
  36227. for (int i = getNumRowsOnScreen() + 2; --i >= 0;)
  36228. {
  36229. Component* rowComp = viewport->getComponentForRowIfOnscreen (firstRow + i);
  36230. if (rowComp != 0 && isRowSelected (firstRow + i))
  36231. {
  36232. g.saveState();
  36233. int x = 0, y = 0;
  36234. rowComp->relativePositionToOtherComponent (this, x, y);
  36235. g.setOrigin (x, y);
  36236. g.reduceClipRegion (0, 0, rowComp->getWidth(), rowComp->getHeight());
  36237. rowComp->paintEntireComponent (g);
  36238. g.restoreState();
  36239. }
  36240. }
  36241. return snapshot;
  36242. }
  36243. Component* ListBoxModel::refreshComponentForRow (int, bool, Component* existingComponentToUpdate)
  36244. {
  36245. (void) existingComponentToUpdate;
  36246. jassert (existingComponentToUpdate == 0); // indicates a failure in the code the recycles the components
  36247. return 0;
  36248. }
  36249. void ListBoxModel::listBoxItemClicked (int, const MouseEvent&)
  36250. {
  36251. }
  36252. void ListBoxModel::listBoxItemDoubleClicked (int, const MouseEvent&)
  36253. {
  36254. }
  36255. void ListBoxModel::backgroundClicked()
  36256. {
  36257. }
  36258. void ListBoxModel::selectedRowsChanged (int)
  36259. {
  36260. }
  36261. void ListBoxModel::deleteKeyPressed (int)
  36262. {
  36263. }
  36264. void ListBoxModel::returnKeyPressed (int)
  36265. {
  36266. }
  36267. void ListBoxModel::listWasScrolled()
  36268. {
  36269. }
  36270. const String ListBoxModel::getDragSourceDescription (const SparseSet<int>&)
  36271. {
  36272. return String::empty;
  36273. }
  36274. END_JUCE_NAMESPACE
  36275. /********* End of inlined file: juce_ListBox.cpp *********/
  36276. /********* Start of inlined file: juce_ProgressBar.cpp *********/
  36277. BEGIN_JUCE_NAMESPACE
  36278. ProgressBar::ProgressBar (double& progress_)
  36279. : progress (progress_),
  36280. displayPercentage (true),
  36281. lastCallbackTime (0)
  36282. {
  36283. currentValue = jlimit (0.0, 1.0, progress);
  36284. }
  36285. ProgressBar::~ProgressBar()
  36286. {
  36287. }
  36288. void ProgressBar::setPercentageDisplay (const bool shouldDisplayPercentage)
  36289. {
  36290. displayPercentage = shouldDisplayPercentage;
  36291. repaint();
  36292. }
  36293. void ProgressBar::setTextToDisplay (const String& text)
  36294. {
  36295. displayPercentage = false;
  36296. displayedMessage = text;
  36297. }
  36298. void ProgressBar::lookAndFeelChanged()
  36299. {
  36300. setOpaque (findColour (backgroundColourId).isOpaque());
  36301. }
  36302. void ProgressBar::colourChanged()
  36303. {
  36304. lookAndFeelChanged();
  36305. }
  36306. void ProgressBar::paint (Graphics& g)
  36307. {
  36308. String text;
  36309. if (displayPercentage)
  36310. {
  36311. if (currentValue >= 0 && currentValue <= 1.0)
  36312. text << roundDoubleToInt (currentValue * 100.0) << T("%");
  36313. }
  36314. else
  36315. {
  36316. text = displayedMessage;
  36317. }
  36318. getLookAndFeel().drawProgressBar (g, *this,
  36319. getWidth(), getHeight(),
  36320. currentValue, text);
  36321. }
  36322. void ProgressBar::visibilityChanged()
  36323. {
  36324. if (isVisible())
  36325. startTimer (30);
  36326. else
  36327. stopTimer();
  36328. }
  36329. void ProgressBar::timerCallback()
  36330. {
  36331. double newProgress = progress;
  36332. if (currentValue != newProgress
  36333. || newProgress < 0 || newProgress >= 1.0
  36334. || currentMessage != displayedMessage)
  36335. {
  36336. if (currentValue < newProgress
  36337. && newProgress >= 0 && newProgress < 1.0
  36338. && currentValue >= 0 && currentValue < 1.0)
  36339. {
  36340. const uint32 now = Time::getMillisecondCounter();
  36341. const int timeSinceLastCallback = (int) (now - lastCallbackTime);
  36342. lastCallbackTime = now;
  36343. newProgress = jmin (currentValue + 0.00018 * timeSinceLastCallback,
  36344. newProgress);
  36345. }
  36346. currentValue = newProgress;
  36347. currentMessage = displayedMessage;
  36348. repaint();
  36349. }
  36350. }
  36351. END_JUCE_NAMESPACE
  36352. /********* End of inlined file: juce_ProgressBar.cpp *********/
  36353. /********* Start of inlined file: juce_Slider.cpp *********/
  36354. BEGIN_JUCE_NAMESPACE
  36355. class SliderPopupDisplayComponent : public BubbleComponent
  36356. {
  36357. public:
  36358. SliderPopupDisplayComponent (Slider* const owner_)
  36359. : owner (owner_),
  36360. font (15.0f, Font::bold)
  36361. {
  36362. setAlwaysOnTop (true);
  36363. }
  36364. ~SliderPopupDisplayComponent()
  36365. {
  36366. }
  36367. void paintContent (Graphics& g, int w, int h)
  36368. {
  36369. g.setFont (font);
  36370. g.setColour (Colours::black);
  36371. g.drawFittedText (text, 0, 0, w, h, Justification::centred, 1);
  36372. }
  36373. void getContentSize (int& w, int& h)
  36374. {
  36375. w = font.getStringWidth (text) + 18;
  36376. h = (int) (font.getHeight() * 1.6f);
  36377. }
  36378. void updatePosition (const String& newText)
  36379. {
  36380. if (text != newText)
  36381. {
  36382. text = newText;
  36383. repaint();
  36384. }
  36385. BubbleComponent::setPosition (owner);
  36386. }
  36387. juce_UseDebuggingNewOperator
  36388. private:
  36389. Slider* owner;
  36390. Font font;
  36391. String text;
  36392. SliderPopupDisplayComponent (const SliderPopupDisplayComponent&);
  36393. const SliderPopupDisplayComponent& operator= (const SliderPopupDisplayComponent&);
  36394. };
  36395. Slider::Slider (const String& name)
  36396. : Component (name),
  36397. listeners (2),
  36398. currentValue (0.0),
  36399. valueMin (0.0),
  36400. valueMax (0.0),
  36401. minimum (0),
  36402. maximum (10),
  36403. interval (0),
  36404. skewFactor (1.0),
  36405. velocityModeSensitivity (1.0),
  36406. velocityModeOffset (0.0),
  36407. velocityModeThreshold (1),
  36408. rotaryStart (float_Pi * 1.2f),
  36409. rotaryEnd (float_Pi * 2.8f),
  36410. numDecimalPlaces (7),
  36411. sliderRegionStart (0),
  36412. sliderRegionSize (1),
  36413. sliderBeingDragged (-1),
  36414. pixelsForFullDragExtent (250),
  36415. style (LinearHorizontal),
  36416. textBoxPos (TextBoxLeft),
  36417. textBoxWidth (80),
  36418. textBoxHeight (20),
  36419. incDecButtonMode (incDecButtonsNotDraggable),
  36420. editableText (true),
  36421. doubleClickToValue (false),
  36422. isVelocityBased (false),
  36423. userKeyOverridesVelocity (true),
  36424. rotaryStop (true),
  36425. incDecButtonsSideBySide (false),
  36426. sendChangeOnlyOnRelease (false),
  36427. popupDisplayEnabled (false),
  36428. menuEnabled (false),
  36429. menuShown (false),
  36430. scrollWheelEnabled (true),
  36431. snapsToMousePos (true),
  36432. valueBox (0),
  36433. incButton (0),
  36434. decButton (0),
  36435. popupDisplay (0),
  36436. parentForPopupDisplay (0)
  36437. {
  36438. setWantsKeyboardFocus (false);
  36439. setRepaintsOnMouseActivity (true);
  36440. lookAndFeelChanged();
  36441. updateText();
  36442. }
  36443. Slider::~Slider()
  36444. {
  36445. deleteAndZero (popupDisplay);
  36446. deleteAllChildren();
  36447. }
  36448. void Slider::handleAsyncUpdate()
  36449. {
  36450. cancelPendingUpdate();
  36451. for (int i = listeners.size(); --i >= 0;)
  36452. {
  36453. ((SliderListener*) listeners.getUnchecked (i))->sliderValueChanged (this);
  36454. i = jmin (i, listeners.size());
  36455. }
  36456. }
  36457. void Slider::sendDragStart()
  36458. {
  36459. startedDragging();
  36460. for (int i = listeners.size(); --i >= 0;)
  36461. {
  36462. ((SliderListener*) listeners.getUnchecked (i))->sliderDragStarted (this);
  36463. i = jmin (i, listeners.size());
  36464. }
  36465. }
  36466. void Slider::sendDragEnd()
  36467. {
  36468. stoppedDragging();
  36469. sliderBeingDragged = -1;
  36470. for (int i = listeners.size(); --i >= 0;)
  36471. {
  36472. ((SliderListener*) listeners.getUnchecked (i))->sliderDragEnded (this);
  36473. i = jmin (i, listeners.size());
  36474. }
  36475. }
  36476. void Slider::addListener (SliderListener* const listener) throw()
  36477. {
  36478. jassert (listener != 0);
  36479. if (listener != 0)
  36480. listeners.add (listener);
  36481. }
  36482. void Slider::removeListener (SliderListener* const listener) throw()
  36483. {
  36484. listeners.removeValue (listener);
  36485. }
  36486. void Slider::setSliderStyle (const SliderStyle newStyle)
  36487. {
  36488. if (style != newStyle)
  36489. {
  36490. style = newStyle;
  36491. repaint();
  36492. lookAndFeelChanged();
  36493. }
  36494. }
  36495. void Slider::setRotaryParameters (const float startAngleRadians,
  36496. const float endAngleRadians,
  36497. const bool stopAtEnd)
  36498. {
  36499. // make sure the values are sensible..
  36500. jassert (rotaryStart >= 0 && rotaryEnd >= 0);
  36501. jassert (rotaryStart < float_Pi * 4.0f && rotaryEnd < float_Pi * 4.0f);
  36502. jassert (rotaryStart < rotaryEnd);
  36503. rotaryStart = startAngleRadians;
  36504. rotaryEnd = endAngleRadians;
  36505. rotaryStop = stopAtEnd;
  36506. }
  36507. void Slider::setVelocityBasedMode (const bool velBased) throw()
  36508. {
  36509. isVelocityBased = velBased;
  36510. }
  36511. void Slider::setVelocityModeParameters (const double sensitivity,
  36512. const int threshold,
  36513. const double offset,
  36514. const bool userCanPressKeyToSwapMode) throw()
  36515. {
  36516. jassert (threshold >= 0);
  36517. jassert (sensitivity > 0);
  36518. jassert (offset >= 0);
  36519. velocityModeSensitivity = sensitivity;
  36520. velocityModeOffset = offset;
  36521. velocityModeThreshold = threshold;
  36522. userKeyOverridesVelocity = userCanPressKeyToSwapMode;
  36523. }
  36524. void Slider::setSkewFactor (const double factor) throw()
  36525. {
  36526. skewFactor = factor;
  36527. }
  36528. void Slider::setSkewFactorFromMidPoint (const double sliderValueToShowAtMidPoint) throw()
  36529. {
  36530. if (maximum > minimum)
  36531. skewFactor = log (0.5) / log ((sliderValueToShowAtMidPoint - minimum)
  36532. / (maximum - minimum));
  36533. }
  36534. void Slider::setMouseDragSensitivity (const int distanceForFullScaleDrag)
  36535. {
  36536. jassert (distanceForFullScaleDrag > 0);
  36537. pixelsForFullDragExtent = distanceForFullScaleDrag;
  36538. }
  36539. void Slider::setIncDecButtonsMode (const IncDecButtonMode mode)
  36540. {
  36541. if (incDecButtonMode != mode)
  36542. {
  36543. incDecButtonMode = mode;
  36544. lookAndFeelChanged();
  36545. }
  36546. }
  36547. void Slider::setTextBoxStyle (const TextEntryBoxPosition newPosition,
  36548. const bool isReadOnly,
  36549. const int textEntryBoxWidth,
  36550. const int textEntryBoxHeight)
  36551. {
  36552. textBoxPos = newPosition;
  36553. editableText = ! isReadOnly;
  36554. textBoxWidth = textEntryBoxWidth;
  36555. textBoxHeight = textEntryBoxHeight;
  36556. repaint();
  36557. lookAndFeelChanged();
  36558. }
  36559. void Slider::setTextBoxIsEditable (const bool shouldBeEditable) throw()
  36560. {
  36561. editableText = shouldBeEditable;
  36562. if (valueBox != 0)
  36563. valueBox->setEditable (shouldBeEditable && isEnabled());
  36564. }
  36565. void Slider::showTextBox()
  36566. {
  36567. jassert (editableText); // this should probably be avoided in read-only sliders.
  36568. if (valueBox != 0)
  36569. valueBox->showEditor();
  36570. }
  36571. void Slider::hideTextBox (const bool discardCurrentEditorContents)
  36572. {
  36573. if (valueBox != 0)
  36574. {
  36575. valueBox->hideEditor (discardCurrentEditorContents);
  36576. if (discardCurrentEditorContents)
  36577. updateText();
  36578. }
  36579. }
  36580. void Slider::setChangeNotificationOnlyOnRelease (const bool onlyNotifyOnRelease) throw()
  36581. {
  36582. sendChangeOnlyOnRelease = onlyNotifyOnRelease;
  36583. }
  36584. void Slider::setSliderSnapsToMousePosition (const bool shouldSnapToMouse) throw()
  36585. {
  36586. snapsToMousePos = shouldSnapToMouse;
  36587. }
  36588. void Slider::setPopupDisplayEnabled (const bool enabled,
  36589. Component* const parentComponentToUse) throw()
  36590. {
  36591. popupDisplayEnabled = enabled;
  36592. parentForPopupDisplay = parentComponentToUse;
  36593. }
  36594. void Slider::colourChanged()
  36595. {
  36596. lookAndFeelChanged();
  36597. }
  36598. void Slider::lookAndFeelChanged()
  36599. {
  36600. const String previousTextBoxContent (valueBox != 0 ? valueBox->getText()
  36601. : getTextFromValue (currentValue));
  36602. deleteAllChildren();
  36603. valueBox = 0;
  36604. LookAndFeel& lf = getLookAndFeel();
  36605. if (textBoxPos != NoTextBox)
  36606. {
  36607. addAndMakeVisible (valueBox = getLookAndFeel().createSliderTextBox (*this));
  36608. valueBox->setWantsKeyboardFocus (false);
  36609. valueBox->setText (previousTextBoxContent, false);
  36610. valueBox->setEditable (editableText && isEnabled());
  36611. valueBox->addListener (this);
  36612. if (style == LinearBar)
  36613. valueBox->addMouseListener (this, false);
  36614. valueBox->setTooltip (getTooltip());
  36615. }
  36616. if (style == IncDecButtons)
  36617. {
  36618. addAndMakeVisible (incButton = lf.createSliderButton (true));
  36619. incButton->addButtonListener (this);
  36620. addAndMakeVisible (decButton = lf.createSliderButton (false));
  36621. decButton->addButtonListener (this);
  36622. if (incDecButtonMode != incDecButtonsNotDraggable)
  36623. {
  36624. incButton->addMouseListener (this, false);
  36625. decButton->addMouseListener (this, false);
  36626. }
  36627. else
  36628. {
  36629. incButton->setRepeatSpeed (300, 100, 20);
  36630. incButton->addMouseListener (decButton, false);
  36631. decButton->setRepeatSpeed (300, 100, 20);
  36632. decButton->addMouseListener (incButton, false);
  36633. }
  36634. incButton->setTooltip (getTooltip());
  36635. decButton->setTooltip (getTooltip());
  36636. }
  36637. setComponentEffect (lf.getSliderEffect());
  36638. resized();
  36639. repaint();
  36640. }
  36641. void Slider::setRange (const double newMin,
  36642. const double newMax,
  36643. const double newInt)
  36644. {
  36645. if (minimum != newMin
  36646. || maximum != newMax
  36647. || interval != newInt)
  36648. {
  36649. minimum = newMin;
  36650. maximum = newMax;
  36651. interval = newInt;
  36652. // figure out the number of DPs needed to display all values at this
  36653. // interval setting.
  36654. numDecimalPlaces = 7;
  36655. if (newInt != 0)
  36656. {
  36657. int v = abs ((int) (newInt * 10000000));
  36658. while ((v % 10) == 0)
  36659. {
  36660. --numDecimalPlaces;
  36661. v /= 10;
  36662. }
  36663. }
  36664. // keep the current values inside the new range..
  36665. if (style != TwoValueHorizontal && style != TwoValueVertical)
  36666. {
  36667. setValue (currentValue, false, false);
  36668. }
  36669. else
  36670. {
  36671. setMinValue (getMinValue(), false, false);
  36672. setMaxValue (getMaxValue(), false, false);
  36673. }
  36674. updateText();
  36675. }
  36676. }
  36677. void Slider::triggerChangeMessage (const bool synchronous)
  36678. {
  36679. if (synchronous)
  36680. handleAsyncUpdate();
  36681. else
  36682. triggerAsyncUpdate();
  36683. valueChanged();
  36684. }
  36685. double Slider::getValue() const throw()
  36686. {
  36687. // for a two-value style slider, you should use the getMinValue() and getMaxValue()
  36688. // methods to get the two values.
  36689. jassert (style != TwoValueHorizontal && style != TwoValueVertical);
  36690. return currentValue;
  36691. }
  36692. void Slider::setValue (double newValue,
  36693. const bool sendUpdateMessage,
  36694. const bool sendMessageSynchronously)
  36695. {
  36696. // for a two-value style slider, you should use the setMinValue() and setMaxValue()
  36697. // methods to set the two values.
  36698. jassert (style != TwoValueHorizontal && style != TwoValueVertical);
  36699. newValue = constrainedValue (newValue);
  36700. if (style == ThreeValueHorizontal || style == ThreeValueVertical)
  36701. {
  36702. jassert (valueMin <= valueMax);
  36703. newValue = jlimit (valueMin, valueMax, newValue);
  36704. }
  36705. if (currentValue != newValue)
  36706. {
  36707. if (valueBox != 0)
  36708. valueBox->hideEditor (true);
  36709. currentValue = newValue;
  36710. updateText();
  36711. repaint();
  36712. if (popupDisplay != 0)
  36713. {
  36714. ((SliderPopupDisplayComponent*) popupDisplay)->updatePosition (getTextFromValue (currentValue));
  36715. popupDisplay->repaint();
  36716. }
  36717. if (sendUpdateMessage)
  36718. triggerChangeMessage (sendMessageSynchronously);
  36719. }
  36720. }
  36721. double Slider::getMinValue() const throw()
  36722. {
  36723. // The minimum value only applies to sliders that are in two- or three-value mode.
  36724. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  36725. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  36726. return valueMin;
  36727. }
  36728. double Slider::getMaxValue() const throw()
  36729. {
  36730. // The maximum value only applies to sliders that are in two- or three-value mode.
  36731. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  36732. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  36733. return valueMax;
  36734. }
  36735. void Slider::setMinValue (double newValue, const bool sendUpdateMessage, const bool sendMessageSynchronously, const bool allowNudgingOfOtherValues)
  36736. {
  36737. // The minimum value only applies to sliders that are in two- or three-value mode.
  36738. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  36739. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  36740. newValue = constrainedValue (newValue);
  36741. if (style == TwoValueHorizontal || style == TwoValueVertical)
  36742. {
  36743. if (allowNudgingOfOtherValues && newValue > valueMax)
  36744. setMaxValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  36745. newValue = jmin (valueMax, newValue);
  36746. }
  36747. else
  36748. {
  36749. if (allowNudgingOfOtherValues && newValue > currentValue)
  36750. setValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  36751. newValue = jmin (currentValue, newValue);
  36752. }
  36753. if (valueMin != newValue)
  36754. {
  36755. valueMin = newValue;
  36756. repaint();
  36757. if (popupDisplay != 0)
  36758. {
  36759. ((SliderPopupDisplayComponent*) popupDisplay)->updatePosition (getTextFromValue (valueMin));
  36760. popupDisplay->repaint();
  36761. }
  36762. if (sendUpdateMessage)
  36763. triggerChangeMessage (sendMessageSynchronously);
  36764. }
  36765. }
  36766. void Slider::setMaxValue (double newValue, const bool sendUpdateMessage, const bool sendMessageSynchronously, const bool allowNudgingOfOtherValues)
  36767. {
  36768. // The maximum value only applies to sliders that are in two- or three-value mode.
  36769. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  36770. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  36771. newValue = constrainedValue (newValue);
  36772. if (style == TwoValueHorizontal || style == TwoValueVertical)
  36773. {
  36774. if (allowNudgingOfOtherValues && newValue < valueMin)
  36775. setMinValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  36776. newValue = jmax (valueMin, newValue);
  36777. }
  36778. else
  36779. {
  36780. if (allowNudgingOfOtherValues && newValue < currentValue)
  36781. setValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  36782. newValue = jmax (currentValue, newValue);
  36783. }
  36784. if (valueMax != newValue)
  36785. {
  36786. valueMax = newValue;
  36787. repaint();
  36788. if (popupDisplay != 0)
  36789. {
  36790. ((SliderPopupDisplayComponent*) popupDisplay)->updatePosition (getTextFromValue (valueMax));
  36791. popupDisplay->repaint();
  36792. }
  36793. if (sendUpdateMessage)
  36794. triggerChangeMessage (sendMessageSynchronously);
  36795. }
  36796. }
  36797. void Slider::setDoubleClickReturnValue (const bool isDoubleClickEnabled,
  36798. const double valueToSetOnDoubleClick) throw()
  36799. {
  36800. doubleClickToValue = isDoubleClickEnabled;
  36801. doubleClickReturnValue = valueToSetOnDoubleClick;
  36802. }
  36803. double Slider::getDoubleClickReturnValue (bool& isEnabled_) const throw()
  36804. {
  36805. isEnabled_ = doubleClickToValue;
  36806. return doubleClickReturnValue;
  36807. }
  36808. void Slider::updateText()
  36809. {
  36810. if (valueBox != 0)
  36811. valueBox->setText (getTextFromValue (currentValue), false);
  36812. }
  36813. void Slider::setTextValueSuffix (const String& suffix)
  36814. {
  36815. if (textSuffix != suffix)
  36816. {
  36817. textSuffix = suffix;
  36818. updateText();
  36819. }
  36820. }
  36821. const String Slider::getTextFromValue (double v)
  36822. {
  36823. if (numDecimalPlaces > 0)
  36824. return String (v, numDecimalPlaces) + textSuffix;
  36825. else
  36826. return String (roundDoubleToInt (v)) + textSuffix;
  36827. }
  36828. double Slider::getValueFromText (const String& text)
  36829. {
  36830. String t (text.trimStart());
  36831. if (t.endsWith (textSuffix))
  36832. t = t.substring (0, t.length() - textSuffix.length());
  36833. while (t.startsWithChar (T('+')))
  36834. t = t.substring (1).trimStart();
  36835. return t.initialSectionContainingOnly (T("0123456789.,-"))
  36836. .getDoubleValue();
  36837. }
  36838. double Slider::proportionOfLengthToValue (double proportion)
  36839. {
  36840. if (skewFactor != 1.0 && proportion > 0.0)
  36841. proportion = exp (log (proportion) / skewFactor);
  36842. return minimum + (maximum - minimum) * proportion;
  36843. }
  36844. double Slider::valueToProportionOfLength (double value)
  36845. {
  36846. const double n = (value - minimum) / (maximum - minimum);
  36847. return skewFactor == 1.0 ? n : pow (n, skewFactor);
  36848. }
  36849. double Slider::snapValue (double attemptedValue, const bool)
  36850. {
  36851. return attemptedValue;
  36852. }
  36853. void Slider::startedDragging()
  36854. {
  36855. }
  36856. void Slider::stoppedDragging()
  36857. {
  36858. }
  36859. void Slider::valueChanged()
  36860. {
  36861. }
  36862. void Slider::enablementChanged()
  36863. {
  36864. repaint();
  36865. }
  36866. void Slider::setPopupMenuEnabled (const bool menuEnabled_) throw()
  36867. {
  36868. menuEnabled = menuEnabled_;
  36869. }
  36870. void Slider::setScrollWheelEnabled (const bool enabled) throw()
  36871. {
  36872. scrollWheelEnabled = enabled;
  36873. }
  36874. void Slider::labelTextChanged (Label* label)
  36875. {
  36876. const double newValue = snapValue (getValueFromText (label->getText()), false);
  36877. if (getValue() != newValue)
  36878. {
  36879. sendDragStart();
  36880. setValue (newValue, true, true);
  36881. sendDragEnd();
  36882. }
  36883. updateText(); // force a clean-up of the text, needed in case setValue() hasn't done this.
  36884. }
  36885. void Slider::buttonClicked (Button* button)
  36886. {
  36887. if (style == IncDecButtons)
  36888. {
  36889. sendDragStart();
  36890. if (button == incButton)
  36891. setValue (snapValue (getValue() + interval, false), true, true);
  36892. else if (button == decButton)
  36893. setValue (snapValue (getValue() - interval, false), true, true);
  36894. sendDragEnd();
  36895. }
  36896. }
  36897. double Slider::constrainedValue (double value) const throw()
  36898. {
  36899. if (interval > 0)
  36900. value = minimum + interval * floor ((value - minimum) / interval + 0.5);
  36901. if (value <= minimum || maximum <= minimum)
  36902. value = minimum;
  36903. else if (value >= maximum)
  36904. value = maximum;
  36905. return value;
  36906. }
  36907. float Slider::getLinearSliderPos (const double value)
  36908. {
  36909. double sliderPosProportional;
  36910. if (maximum > minimum)
  36911. {
  36912. if (value < minimum)
  36913. {
  36914. sliderPosProportional = 0.0;
  36915. }
  36916. else if (value > maximum)
  36917. {
  36918. sliderPosProportional = 1.0;
  36919. }
  36920. else
  36921. {
  36922. sliderPosProportional = valueToProportionOfLength (value);
  36923. jassert (sliderPosProportional >= 0 && sliderPosProportional <= 1.0);
  36924. }
  36925. }
  36926. else
  36927. {
  36928. sliderPosProportional = 0.5;
  36929. }
  36930. if (isVertical() || style == IncDecButtons)
  36931. sliderPosProportional = 1.0 - sliderPosProportional;
  36932. return (float) (sliderRegionStart + sliderPosProportional * sliderRegionSize);
  36933. }
  36934. bool Slider::isHorizontal() const throw()
  36935. {
  36936. return style == LinearHorizontal
  36937. || style == LinearBar
  36938. || style == TwoValueHorizontal
  36939. || style == ThreeValueHorizontal;
  36940. }
  36941. bool Slider::isVertical() const throw()
  36942. {
  36943. return style == LinearVertical
  36944. || style == TwoValueVertical
  36945. || style == ThreeValueVertical;
  36946. }
  36947. bool Slider::incDecDragDirectionIsHorizontal() const throw()
  36948. {
  36949. return incDecButtonMode == incDecButtonsDraggable_Horizontal
  36950. || (incDecButtonMode == incDecButtonsDraggable_AutoDirection && incDecButtonsSideBySide);
  36951. }
  36952. float Slider::getPositionOfValue (const double value)
  36953. {
  36954. if (isHorizontal() || isVertical())
  36955. {
  36956. return getLinearSliderPos (value);
  36957. }
  36958. else
  36959. {
  36960. jassertfalse // not a valid call on a slider that doesn't work linearly!
  36961. return 0.0f;
  36962. }
  36963. }
  36964. void Slider::paint (Graphics& g)
  36965. {
  36966. if (style != IncDecButtons)
  36967. {
  36968. if (style == Rotary || style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  36969. {
  36970. const float sliderPos = (float) valueToProportionOfLength (currentValue);
  36971. jassert (sliderPos >= 0 && sliderPos <= 1.0f);
  36972. getLookAndFeel().drawRotarySlider (g,
  36973. sliderRect.getX(),
  36974. sliderRect.getY(),
  36975. sliderRect.getWidth(),
  36976. sliderRect.getHeight(),
  36977. sliderPos,
  36978. rotaryStart, rotaryEnd,
  36979. *this);
  36980. }
  36981. else
  36982. {
  36983. getLookAndFeel().drawLinearSlider (g,
  36984. sliderRect.getX(),
  36985. sliderRect.getY(),
  36986. sliderRect.getWidth(),
  36987. sliderRect.getHeight(),
  36988. getLinearSliderPos (currentValue),
  36989. getLinearSliderPos (valueMin),
  36990. getLinearSliderPos (valueMax),
  36991. style,
  36992. *this);
  36993. }
  36994. if (style == LinearBar && valueBox == 0)
  36995. {
  36996. g.setColour (findColour (Slider::textBoxOutlineColourId));
  36997. g.drawRect (0, 0, getWidth(), getHeight(), 1);
  36998. }
  36999. }
  37000. }
  37001. void Slider::resized()
  37002. {
  37003. int minXSpace = 0;
  37004. int minYSpace = 0;
  37005. if (textBoxPos == TextBoxLeft || textBoxPos == TextBoxRight)
  37006. minXSpace = 30;
  37007. else
  37008. minYSpace = 15;
  37009. const int tbw = jmax (0, jmin (textBoxWidth, getWidth() - minXSpace));
  37010. const int tbh = jmax (0, jmin (textBoxHeight, getHeight() - minYSpace));
  37011. if (style == LinearBar)
  37012. {
  37013. if (valueBox != 0)
  37014. valueBox->setBounds (0, 0, getWidth(), getHeight());
  37015. }
  37016. else
  37017. {
  37018. if (textBoxPos == NoTextBox)
  37019. {
  37020. sliderRect.setBounds (0, 0, getWidth(), getHeight());
  37021. }
  37022. else if (textBoxPos == TextBoxLeft)
  37023. {
  37024. valueBox->setBounds (0, (getHeight() - tbh) / 2, tbw, tbh);
  37025. sliderRect.setBounds (tbw, 0, getWidth() - tbw, getHeight());
  37026. }
  37027. else if (textBoxPos == TextBoxRight)
  37028. {
  37029. valueBox->setBounds (getWidth() - tbw, (getHeight() - tbh) / 2, tbw, tbh);
  37030. sliderRect.setBounds (0, 0, getWidth() - tbw, getHeight());
  37031. }
  37032. else if (textBoxPos == TextBoxAbove)
  37033. {
  37034. valueBox->setBounds ((getWidth() - tbw) / 2, 0, tbw, tbh);
  37035. sliderRect.setBounds (0, tbh, getWidth(), getHeight() - tbh);
  37036. }
  37037. else if (textBoxPos == TextBoxBelow)
  37038. {
  37039. valueBox->setBounds ((getWidth() - tbw) / 2, getHeight() - tbh, tbw, tbh);
  37040. sliderRect.setBounds (0, 0, getWidth(), getHeight() - tbh);
  37041. }
  37042. }
  37043. const int indent = getLookAndFeel().getSliderThumbRadius (*this);
  37044. if (style == LinearBar)
  37045. {
  37046. const int barIndent = 1;
  37047. sliderRegionStart = barIndent;
  37048. sliderRegionSize = getWidth() - barIndent * 2;
  37049. sliderRect.setBounds (sliderRegionStart, barIndent,
  37050. sliderRegionSize, getHeight() - barIndent * 2);
  37051. }
  37052. else if (isHorizontal())
  37053. {
  37054. sliderRegionStart = sliderRect.getX() + indent;
  37055. sliderRegionSize = jmax (1, sliderRect.getWidth() - indent * 2);
  37056. sliderRect.setBounds (sliderRegionStart, sliderRect.getY(),
  37057. sliderRegionSize, sliderRect.getHeight());
  37058. }
  37059. else if (isVertical())
  37060. {
  37061. sliderRegionStart = sliderRect.getY() + indent;
  37062. sliderRegionSize = jmax (1, sliderRect.getHeight() - indent * 2);
  37063. sliderRect.setBounds (sliderRect.getX(), sliderRegionStart,
  37064. sliderRect.getWidth(), sliderRegionSize);
  37065. }
  37066. else
  37067. {
  37068. sliderRegionStart = 0;
  37069. sliderRegionSize = 100;
  37070. }
  37071. if (style == IncDecButtons)
  37072. {
  37073. Rectangle buttonRect (sliderRect);
  37074. if (textBoxPos == TextBoxLeft || textBoxPos == TextBoxRight)
  37075. buttonRect.expand (-2, 0);
  37076. else
  37077. buttonRect.expand (0, -2);
  37078. incDecButtonsSideBySide = buttonRect.getWidth() > buttonRect.getHeight();
  37079. if (incDecButtonsSideBySide)
  37080. {
  37081. decButton->setBounds (buttonRect.getX(),
  37082. buttonRect.getY(),
  37083. buttonRect.getWidth() / 2,
  37084. buttonRect.getHeight());
  37085. decButton->setConnectedEdges (Button::ConnectedOnRight);
  37086. incButton->setBounds (buttonRect.getCentreX(),
  37087. buttonRect.getY(),
  37088. buttonRect.getWidth() / 2,
  37089. buttonRect.getHeight());
  37090. incButton->setConnectedEdges (Button::ConnectedOnLeft);
  37091. }
  37092. else
  37093. {
  37094. incButton->setBounds (buttonRect.getX(),
  37095. buttonRect.getY(),
  37096. buttonRect.getWidth(),
  37097. buttonRect.getHeight() / 2);
  37098. incButton->setConnectedEdges (Button::ConnectedOnBottom);
  37099. decButton->setBounds (buttonRect.getX(),
  37100. buttonRect.getCentreY(),
  37101. buttonRect.getWidth(),
  37102. buttonRect.getHeight() / 2);
  37103. decButton->setConnectedEdges (Button::ConnectedOnTop);
  37104. }
  37105. }
  37106. }
  37107. void Slider::focusOfChildComponentChanged (FocusChangeType)
  37108. {
  37109. repaint();
  37110. }
  37111. void Slider::mouseDown (const MouseEvent& e)
  37112. {
  37113. mouseWasHidden = false;
  37114. incDecDragged = false;
  37115. mouseXWhenLastDragged = e.x;
  37116. mouseYWhenLastDragged = e.y;
  37117. mouseDragStartX = e.getMouseDownX();
  37118. mouseDragStartY = e.getMouseDownY();
  37119. if (isEnabled())
  37120. {
  37121. if (e.mods.isPopupMenu() && menuEnabled)
  37122. {
  37123. menuShown = true;
  37124. PopupMenu m;
  37125. m.addItem (1, TRANS ("velocity-sensitive mode"), true, isVelocityBased);
  37126. m.addSeparator();
  37127. if (style == Rotary || style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  37128. {
  37129. PopupMenu rotaryMenu;
  37130. rotaryMenu.addItem (2, TRANS ("use circular dragging"), true, style == Rotary);
  37131. rotaryMenu.addItem (3, TRANS ("use left-right dragging"), true, style == RotaryHorizontalDrag);
  37132. rotaryMenu.addItem (4, TRANS ("use up-down dragging"), true, style == RotaryVerticalDrag);
  37133. m.addSubMenu (TRANS ("rotary mode"), rotaryMenu);
  37134. }
  37135. const int r = m.show();
  37136. if (r == 1)
  37137. {
  37138. setVelocityBasedMode (! isVelocityBased);
  37139. }
  37140. else if (r == 2)
  37141. {
  37142. setSliderStyle (Rotary);
  37143. }
  37144. else if (r == 3)
  37145. {
  37146. setSliderStyle (RotaryHorizontalDrag);
  37147. }
  37148. else if (r == 4)
  37149. {
  37150. setSliderStyle (RotaryVerticalDrag);
  37151. }
  37152. }
  37153. else if (maximum > minimum)
  37154. {
  37155. menuShown = false;
  37156. if (valueBox != 0)
  37157. valueBox->hideEditor (true);
  37158. sliderBeingDragged = 0;
  37159. if (style == TwoValueHorizontal
  37160. || style == TwoValueVertical
  37161. || style == ThreeValueHorizontal
  37162. || style == ThreeValueVertical)
  37163. {
  37164. const float mousePos = (float) (isVertical() ? e.y : e.x);
  37165. const float normalPosDistance = fabsf (getLinearSliderPos (currentValue) - mousePos);
  37166. const float minPosDistance = fabsf (getLinearSliderPos (valueMin) - 0.1f - mousePos);
  37167. const float maxPosDistance = fabsf (getLinearSliderPos (valueMax) + 0.1f - mousePos);
  37168. if (style == TwoValueHorizontal || style == TwoValueVertical)
  37169. {
  37170. if (maxPosDistance <= minPosDistance)
  37171. sliderBeingDragged = 2;
  37172. else
  37173. sliderBeingDragged = 1;
  37174. }
  37175. else if (style == ThreeValueHorizontal || style == ThreeValueVertical)
  37176. {
  37177. if (normalPosDistance >= minPosDistance && maxPosDistance >= minPosDistance)
  37178. sliderBeingDragged = 1;
  37179. else if (normalPosDistance >= maxPosDistance)
  37180. sliderBeingDragged = 2;
  37181. }
  37182. }
  37183. minMaxDiff = valueMax - valueMin;
  37184. lastAngle = rotaryStart + (rotaryEnd - rotaryStart)
  37185. * valueToProportionOfLength (currentValue);
  37186. if (sliderBeingDragged == 2)
  37187. valueWhenLastDragged = valueMax;
  37188. else if (sliderBeingDragged == 1)
  37189. valueWhenLastDragged = valueMin;
  37190. else
  37191. valueWhenLastDragged = currentValue;
  37192. valueOnMouseDown = valueWhenLastDragged;
  37193. if (popupDisplayEnabled)
  37194. {
  37195. SliderPopupDisplayComponent* const popup = new SliderPopupDisplayComponent (this);
  37196. popupDisplay = popup;
  37197. if (parentForPopupDisplay != 0)
  37198. {
  37199. parentForPopupDisplay->addChildComponent (popup);
  37200. }
  37201. else
  37202. {
  37203. popup->addToDesktop (0);
  37204. }
  37205. popup->setVisible (true);
  37206. }
  37207. sendDragStart();
  37208. mouseDrag (e);
  37209. }
  37210. }
  37211. }
  37212. void Slider::mouseUp (const MouseEvent&)
  37213. {
  37214. if (isEnabled()
  37215. && (! menuShown)
  37216. && (maximum > minimum)
  37217. && (style != IncDecButtons || incDecDragged))
  37218. {
  37219. restoreMouseIfHidden();
  37220. if (sendChangeOnlyOnRelease && valueOnMouseDown != currentValue)
  37221. triggerChangeMessage (false);
  37222. sendDragEnd();
  37223. deleteAndZero (popupDisplay);
  37224. if (style == IncDecButtons)
  37225. {
  37226. incButton->setState (Button::buttonNormal);
  37227. decButton->setState (Button::buttonNormal);
  37228. }
  37229. }
  37230. }
  37231. void Slider::restoreMouseIfHidden()
  37232. {
  37233. if (mouseWasHidden)
  37234. {
  37235. mouseWasHidden = false;
  37236. Component* c = Component::getComponentUnderMouse();
  37237. if (c == 0)
  37238. c = this;
  37239. c->enableUnboundedMouseMovement (false);
  37240. const double pos = (sliderBeingDragged == 2) ? getMaxValue()
  37241. : ((sliderBeingDragged == 1) ? getMinValue()
  37242. : currentValue);
  37243. if (style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  37244. {
  37245. int x, y, downX, downY;
  37246. Desktop::getMousePosition (x, y);
  37247. Desktop::getLastMouseDownPosition (downX, downY);
  37248. if (style == RotaryHorizontalDrag)
  37249. {
  37250. const double posDiff = valueToProportionOfLength (pos) - valueToProportionOfLength (valueOnMouseDown);
  37251. x = roundDoubleToInt (pixelsForFullDragExtent * posDiff + downX);
  37252. y = downY;
  37253. }
  37254. else
  37255. {
  37256. const double posDiff = valueToProportionOfLength (valueOnMouseDown) - valueToProportionOfLength (pos);
  37257. x = downX;
  37258. y = roundDoubleToInt (pixelsForFullDragExtent * posDiff + downY);
  37259. }
  37260. Desktop::setMousePosition (x, y);
  37261. }
  37262. else
  37263. {
  37264. const int pixelPos = (int) getLinearSliderPos (pos);
  37265. int x = isHorizontal() ? pixelPos : (getWidth() / 2);
  37266. int y = isVertical() ? pixelPos : (getHeight() / 2);
  37267. relativePositionToGlobal (x, y);
  37268. Desktop::setMousePosition (x, y);
  37269. }
  37270. }
  37271. }
  37272. void Slider::modifierKeysChanged (const ModifierKeys& modifiers)
  37273. {
  37274. if (isEnabled()
  37275. && style != IncDecButtons
  37276. && style != Rotary
  37277. && isVelocityBased == modifiers.isAnyModifierKeyDown())
  37278. {
  37279. restoreMouseIfHidden();
  37280. }
  37281. }
  37282. static double smallestAngleBetween (double a1, double a2)
  37283. {
  37284. return jmin (fabs (a1 - a2),
  37285. fabs (a1 + double_Pi * 2.0 - a2),
  37286. fabs (a2 + double_Pi * 2.0 - a1));
  37287. }
  37288. void Slider::mouseDrag (const MouseEvent& e)
  37289. {
  37290. if (isEnabled()
  37291. && (! menuShown)
  37292. && (maximum > minimum))
  37293. {
  37294. if (style == Rotary)
  37295. {
  37296. int dx = e.x - sliderRect.getCentreX();
  37297. int dy = e.y - sliderRect.getCentreY();
  37298. if (dx * dx + dy * dy > 25)
  37299. {
  37300. double angle = atan2 ((double) dx, (double) -dy);
  37301. while (angle < 0.0)
  37302. angle += double_Pi * 2.0;
  37303. if (rotaryStop && ! e.mouseWasClicked())
  37304. {
  37305. if (fabs (angle - lastAngle) > double_Pi)
  37306. {
  37307. if (angle >= lastAngle)
  37308. angle -= double_Pi * 2.0;
  37309. else
  37310. angle += double_Pi * 2.0;
  37311. }
  37312. if (angle >= lastAngle)
  37313. angle = jmin (angle, (double) jmax (rotaryStart, rotaryEnd));
  37314. else
  37315. angle = jmax (angle, (double) jmin (rotaryStart, rotaryEnd));
  37316. }
  37317. else
  37318. {
  37319. while (angle < rotaryStart)
  37320. angle += double_Pi * 2.0;
  37321. if (angle > rotaryEnd)
  37322. {
  37323. if (smallestAngleBetween (angle, rotaryStart) <= smallestAngleBetween (angle, rotaryEnd))
  37324. angle = rotaryStart;
  37325. else
  37326. angle = rotaryEnd;
  37327. }
  37328. }
  37329. const double proportion = (angle - rotaryStart) / (rotaryEnd - rotaryStart);
  37330. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, proportion));
  37331. lastAngle = angle;
  37332. }
  37333. }
  37334. else
  37335. {
  37336. if (style == LinearBar && e.mouseWasClicked()
  37337. && valueBox != 0 && valueBox->isEditable())
  37338. return;
  37339. if (style == IncDecButtons && ! incDecDragged)
  37340. {
  37341. if (e.getDistanceFromDragStart() < 10 || e.mouseWasClicked())
  37342. return;
  37343. incDecDragged = true;
  37344. mouseDragStartX = e.x;
  37345. mouseDragStartY = e.y;
  37346. }
  37347. if ((isVelocityBased == (userKeyOverridesVelocity ? e.mods.testFlags (ModifierKeys::ctrlModifier | ModifierKeys::commandModifier | ModifierKeys::altModifier)
  37348. : false))
  37349. || ((maximum - minimum) / sliderRegionSize < interval))
  37350. {
  37351. const int mousePos = (isHorizontal() || style == RotaryHorizontalDrag) ? e.x : e.y;
  37352. double scaledMousePos = (mousePos - sliderRegionStart) / (double) sliderRegionSize;
  37353. if (style == RotaryHorizontalDrag
  37354. || style == RotaryVerticalDrag
  37355. || style == IncDecButtons
  37356. || ((style == LinearHorizontal || style == LinearVertical || style == LinearBar)
  37357. && ! snapsToMousePos))
  37358. {
  37359. const int mouseDiff = (style == RotaryHorizontalDrag
  37360. || style == LinearHorizontal
  37361. || style == LinearBar
  37362. || (style == IncDecButtons && incDecDragDirectionIsHorizontal()))
  37363. ? e.x - mouseDragStartX
  37364. : mouseDragStartY - e.y;
  37365. double newPos = valueToProportionOfLength (valueOnMouseDown)
  37366. + mouseDiff * (1.0 / pixelsForFullDragExtent);
  37367. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, newPos));
  37368. if (style == IncDecButtons)
  37369. {
  37370. incButton->setState (mouseDiff < 0 ? Button::buttonNormal : Button::buttonDown);
  37371. decButton->setState (mouseDiff > 0 ? Button::buttonNormal : Button::buttonDown);
  37372. }
  37373. }
  37374. else
  37375. {
  37376. if (isVertical())
  37377. scaledMousePos = 1.0 - scaledMousePos;
  37378. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, scaledMousePos));
  37379. }
  37380. }
  37381. else
  37382. {
  37383. const int mouseDiff = (isHorizontal() || style == RotaryHorizontalDrag
  37384. || (style == IncDecButtons && incDecDragDirectionIsHorizontal()))
  37385. ? e.x - mouseXWhenLastDragged
  37386. : e.y - mouseYWhenLastDragged;
  37387. const double maxSpeed = jmax (200, sliderRegionSize);
  37388. double speed = jlimit (0.0, maxSpeed, (double) abs (mouseDiff));
  37389. if (speed != 0)
  37390. {
  37391. speed = 0.2 * velocityModeSensitivity
  37392. * (1.0 + sin (double_Pi * (1.5 + jmin (0.5, velocityModeOffset
  37393. + jmax (0.0, (double) (speed - velocityModeThreshold))
  37394. / maxSpeed))));
  37395. if (mouseDiff < 0)
  37396. speed = -speed;
  37397. if (isVertical() || style == RotaryVerticalDrag
  37398. || (style == IncDecButtons && ! incDecDragDirectionIsHorizontal()))
  37399. speed = -speed;
  37400. const double currentPos = valueToProportionOfLength (valueWhenLastDragged);
  37401. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, currentPos + speed));
  37402. e.originalComponent->enableUnboundedMouseMovement (true, false);
  37403. mouseWasHidden = true;
  37404. }
  37405. }
  37406. }
  37407. valueWhenLastDragged = jlimit (minimum, maximum, valueWhenLastDragged);
  37408. if (sliderBeingDragged == 0)
  37409. {
  37410. setValue (snapValue (valueWhenLastDragged, true),
  37411. ! sendChangeOnlyOnRelease, true);
  37412. }
  37413. else if (sliderBeingDragged == 1)
  37414. {
  37415. setMinValue (snapValue (valueWhenLastDragged, true),
  37416. ! sendChangeOnlyOnRelease, false, true);
  37417. if (e.mods.isShiftDown())
  37418. setMaxValue (getMinValue() + minMaxDiff, false, false, true);
  37419. else
  37420. minMaxDiff = valueMax - valueMin;
  37421. }
  37422. else
  37423. {
  37424. jassert (sliderBeingDragged == 2);
  37425. setMaxValue (snapValue (valueWhenLastDragged, true),
  37426. ! sendChangeOnlyOnRelease, false, true);
  37427. if (e.mods.isShiftDown())
  37428. setMinValue (getMaxValue() - minMaxDiff, false, false, true);
  37429. else
  37430. minMaxDiff = valueMax - valueMin;
  37431. }
  37432. mouseXWhenLastDragged = e.x;
  37433. mouseYWhenLastDragged = e.y;
  37434. }
  37435. }
  37436. void Slider::mouseDoubleClick (const MouseEvent&)
  37437. {
  37438. if (doubleClickToValue
  37439. && isEnabled()
  37440. && style != IncDecButtons
  37441. && minimum <= doubleClickReturnValue
  37442. && maximum >= doubleClickReturnValue)
  37443. {
  37444. sendDragStart();
  37445. setValue (doubleClickReturnValue, true, true);
  37446. sendDragEnd();
  37447. }
  37448. }
  37449. void Slider::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  37450. {
  37451. if (scrollWheelEnabled && isEnabled()
  37452. && style != TwoValueHorizontal
  37453. && style != TwoValueVertical)
  37454. {
  37455. if (maximum > minimum && ! isMouseButtonDownAnywhere())
  37456. {
  37457. if (valueBox != 0)
  37458. valueBox->hideEditor (false);
  37459. const double proportionDelta = (wheelIncrementX != 0 ? -wheelIncrementX : wheelIncrementY) * 0.15f;
  37460. const double currentPos = valueToProportionOfLength (currentValue);
  37461. const double newValue = proportionOfLengthToValue (jlimit (0.0, 1.0, currentPos + proportionDelta));
  37462. double delta = (newValue != currentValue)
  37463. ? jmax (fabs (newValue - currentValue), interval) : 0;
  37464. if (currentValue > newValue)
  37465. delta = -delta;
  37466. sendDragStart();
  37467. setValue (snapValue (currentValue + delta, false), true, true);
  37468. sendDragEnd();
  37469. }
  37470. }
  37471. else
  37472. {
  37473. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  37474. }
  37475. }
  37476. void SliderListener::sliderDragStarted (Slider*)
  37477. {
  37478. }
  37479. void SliderListener::sliderDragEnded (Slider*)
  37480. {
  37481. }
  37482. END_JUCE_NAMESPACE
  37483. /********* End of inlined file: juce_Slider.cpp *********/
  37484. /********* Start of inlined file: juce_TableHeaderComponent.cpp *********/
  37485. BEGIN_JUCE_NAMESPACE
  37486. class DragOverlayComp : public Component
  37487. {
  37488. public:
  37489. DragOverlayComp (Image* const image_)
  37490. : image (image_)
  37491. {
  37492. image->multiplyAllAlphas (0.8f);
  37493. setAlwaysOnTop (true);
  37494. }
  37495. ~DragOverlayComp()
  37496. {
  37497. delete image;
  37498. }
  37499. void paint (Graphics& g)
  37500. {
  37501. g.drawImageAt (image, 0, 0);
  37502. }
  37503. private:
  37504. Image* image;
  37505. DragOverlayComp (const DragOverlayComp&);
  37506. const DragOverlayComp& operator= (const DragOverlayComp&);
  37507. };
  37508. TableHeaderComponent::TableHeaderComponent()
  37509. : listeners (2),
  37510. dragOverlayComp (0),
  37511. columnsChanged (false),
  37512. columnsResized (false),
  37513. sortChanged (false),
  37514. menuActive (true),
  37515. stretchToFit (false),
  37516. columnIdBeingResized (0),
  37517. columnIdBeingDragged (0),
  37518. columnIdUnderMouse (0),
  37519. lastDeliberateWidth (0)
  37520. {
  37521. }
  37522. TableHeaderComponent::~TableHeaderComponent()
  37523. {
  37524. delete dragOverlayComp;
  37525. }
  37526. void TableHeaderComponent::setPopupMenuActive (const bool hasMenu)
  37527. {
  37528. menuActive = hasMenu;
  37529. }
  37530. bool TableHeaderComponent::isPopupMenuActive() const throw() { return menuActive; }
  37531. int TableHeaderComponent::getNumColumns (const bool onlyCountVisibleColumns) const throw()
  37532. {
  37533. if (onlyCountVisibleColumns)
  37534. {
  37535. int num = 0;
  37536. for (int i = columns.size(); --i >= 0;)
  37537. if (columns.getUnchecked(i)->isVisible())
  37538. ++num;
  37539. return num;
  37540. }
  37541. else
  37542. {
  37543. return columns.size();
  37544. }
  37545. }
  37546. const String TableHeaderComponent::getColumnName (const int columnId) const throw()
  37547. {
  37548. const ColumnInfo* const ci = getInfoForId (columnId);
  37549. return ci != 0 ? ci->name : String::empty;
  37550. }
  37551. void TableHeaderComponent::setColumnName (const int columnId, const String& newName)
  37552. {
  37553. ColumnInfo* const ci = getInfoForId (columnId);
  37554. if (ci != 0 && ci->name != newName)
  37555. {
  37556. ci->name = newName;
  37557. sendColumnsChanged();
  37558. }
  37559. }
  37560. void TableHeaderComponent::addColumn (const String& columnName,
  37561. const int columnId,
  37562. const int width,
  37563. const int minimumWidth,
  37564. const int maximumWidth,
  37565. const int propertyFlags,
  37566. const int insertIndex)
  37567. {
  37568. // can't have a duplicate or null ID!
  37569. jassert (columnId != 0 && getIndexOfColumnId (columnId, false) < 0);
  37570. jassert (width > 0);
  37571. ColumnInfo* const ci = new ColumnInfo();
  37572. ci->name = columnName;
  37573. ci->id = columnId;
  37574. ci->width = width;
  37575. ci->lastDeliberateWidth = width;
  37576. ci->minimumWidth = minimumWidth;
  37577. ci->maximumWidth = maximumWidth;
  37578. if (ci->maximumWidth < 0)
  37579. ci->maximumWidth = INT_MAX;
  37580. jassert (ci->maximumWidth >= ci->minimumWidth);
  37581. ci->propertyFlags = propertyFlags;
  37582. columns.insert (insertIndex, ci);
  37583. sendColumnsChanged();
  37584. }
  37585. void TableHeaderComponent::removeColumn (const int columnIdToRemove)
  37586. {
  37587. const int index = getIndexOfColumnId (columnIdToRemove, false);
  37588. if (index >= 0)
  37589. {
  37590. columns.remove (index);
  37591. sortChanged = true;
  37592. sendColumnsChanged();
  37593. }
  37594. }
  37595. void TableHeaderComponent::removeAllColumns()
  37596. {
  37597. if (columns.size() > 0)
  37598. {
  37599. columns.clear();
  37600. sendColumnsChanged();
  37601. }
  37602. }
  37603. void TableHeaderComponent::moveColumn (const int columnId, int newIndex)
  37604. {
  37605. const int currentIndex = getIndexOfColumnId (columnId, false);
  37606. newIndex = visibleIndexToTotalIndex (newIndex);
  37607. if (columns [currentIndex] != 0 && currentIndex != newIndex)
  37608. {
  37609. columns.move (currentIndex, newIndex);
  37610. sendColumnsChanged();
  37611. }
  37612. }
  37613. void TableHeaderComponent::setColumnWidth (const int columnId, const int newWidth)
  37614. {
  37615. ColumnInfo* const ci = getInfoForId (columnId);
  37616. if (ci != 0 && ci->width != newWidth)
  37617. {
  37618. const int numColumns = getNumColumns (true);
  37619. ci->lastDeliberateWidth = ci->width
  37620. = jlimit (ci->minimumWidth, ci->maximumWidth, newWidth);
  37621. if (stretchToFit)
  37622. {
  37623. const int index = getIndexOfColumnId (columnId, true) + 1;
  37624. if (((unsigned int) index) < (unsigned int) numColumns)
  37625. {
  37626. const int x = getColumnPosition (index).getX();
  37627. if (lastDeliberateWidth == 0)
  37628. lastDeliberateWidth = getTotalWidth();
  37629. resizeColumnsToFit (visibleIndexToTotalIndex (index), lastDeliberateWidth - x);
  37630. }
  37631. }
  37632. repaint();
  37633. columnsResized = true;
  37634. triggerAsyncUpdate();
  37635. }
  37636. }
  37637. int TableHeaderComponent::getIndexOfColumnId (const int columnId, const bool onlyCountVisibleColumns) const throw()
  37638. {
  37639. int n = 0;
  37640. for (int i = 0; i < columns.size(); ++i)
  37641. {
  37642. if ((! onlyCountVisibleColumns) || columns.getUnchecked(i)->isVisible())
  37643. {
  37644. if (columns.getUnchecked(i)->id == columnId)
  37645. return n;
  37646. ++n;
  37647. }
  37648. }
  37649. return -1;
  37650. }
  37651. int TableHeaderComponent::getColumnIdOfIndex (int index, const bool onlyCountVisibleColumns) const throw()
  37652. {
  37653. if (onlyCountVisibleColumns)
  37654. index = visibleIndexToTotalIndex (index);
  37655. const ColumnInfo* const ci = columns [index];
  37656. return (ci != 0) ? ci->id : 0;
  37657. }
  37658. const Rectangle TableHeaderComponent::getColumnPosition (const int index) const throw()
  37659. {
  37660. int x = 0, width = 0, n = 0;
  37661. for (int i = 0; i < columns.size(); ++i)
  37662. {
  37663. x += width;
  37664. if (columns.getUnchecked(i)->isVisible())
  37665. {
  37666. width = columns.getUnchecked(i)->width;
  37667. if (n++ == index)
  37668. break;
  37669. }
  37670. else
  37671. {
  37672. width = 0;
  37673. }
  37674. }
  37675. return Rectangle (x, 0, width, getHeight());
  37676. }
  37677. int TableHeaderComponent::getColumnIdAtX (const int xToFind) const throw()
  37678. {
  37679. if (xToFind >= 0)
  37680. {
  37681. int x = 0;
  37682. for (int i = 0; i < columns.size(); ++i)
  37683. {
  37684. const ColumnInfo* const ci = columns.getUnchecked(i);
  37685. if (ci->isVisible())
  37686. {
  37687. x += ci->width;
  37688. if (xToFind < x)
  37689. return ci->id;
  37690. }
  37691. }
  37692. }
  37693. return 0;
  37694. }
  37695. int TableHeaderComponent::getTotalWidth() const throw()
  37696. {
  37697. int w = 0;
  37698. for (int i = columns.size(); --i >= 0;)
  37699. if (columns.getUnchecked(i)->isVisible())
  37700. w += columns.getUnchecked(i)->width;
  37701. return w;
  37702. }
  37703. void TableHeaderComponent::setStretchToFitActive (const bool shouldStretchToFit)
  37704. {
  37705. stretchToFit = shouldStretchToFit;
  37706. lastDeliberateWidth = getTotalWidth();
  37707. resized();
  37708. }
  37709. bool TableHeaderComponent::isStretchToFitActive() const throw()
  37710. {
  37711. return stretchToFit;
  37712. }
  37713. void TableHeaderComponent::resizeAllColumnsToFit (int targetTotalWidth)
  37714. {
  37715. if (stretchToFit && getWidth() > 0
  37716. && columnIdBeingResized == 0 && columnIdBeingDragged == 0)
  37717. {
  37718. lastDeliberateWidth = targetTotalWidth;
  37719. resizeColumnsToFit (0, targetTotalWidth);
  37720. }
  37721. }
  37722. void TableHeaderComponent::resizeColumnsToFit (int firstColumnIndex, int targetTotalWidth)
  37723. {
  37724. targetTotalWidth = jmax (targetTotalWidth, 0);
  37725. StretchableObjectResizer sor;
  37726. int i;
  37727. for (i = firstColumnIndex; i < columns.size(); ++i)
  37728. {
  37729. ColumnInfo* const ci = columns.getUnchecked(i);
  37730. if (ci->isVisible())
  37731. sor.addItem (ci->lastDeliberateWidth, ci->minimumWidth, ci->maximumWidth);
  37732. }
  37733. sor.resizeToFit (targetTotalWidth);
  37734. int visIndex = 0;
  37735. for (i = firstColumnIndex; i < columns.size(); ++i)
  37736. {
  37737. ColumnInfo* const ci = columns.getUnchecked(i);
  37738. if (ci->isVisible())
  37739. {
  37740. const int newWidth = jlimit (ci->minimumWidth, ci->maximumWidth,
  37741. (int) floor (sor.getItemSize (visIndex++)));
  37742. if (newWidth != ci->width)
  37743. {
  37744. ci->width = newWidth;
  37745. repaint();
  37746. columnsResized = true;
  37747. triggerAsyncUpdate();
  37748. }
  37749. }
  37750. }
  37751. }
  37752. void TableHeaderComponent::setColumnVisible (const int columnId, const bool shouldBeVisible)
  37753. {
  37754. ColumnInfo* const ci = getInfoForId (columnId);
  37755. if (ci != 0 && shouldBeVisible != ci->isVisible())
  37756. {
  37757. if (shouldBeVisible)
  37758. ci->propertyFlags |= visible;
  37759. else
  37760. ci->propertyFlags &= ~visible;
  37761. sendColumnsChanged();
  37762. resized();
  37763. }
  37764. }
  37765. bool TableHeaderComponent::isColumnVisible (const int columnId) const
  37766. {
  37767. const ColumnInfo* const ci = getInfoForId (columnId);
  37768. return ci != 0 && ci->isVisible();
  37769. }
  37770. void TableHeaderComponent::setSortColumnId (const int columnId, const bool sortForwards)
  37771. {
  37772. if (getSortColumnId() != columnId || isSortedForwards() != sortForwards)
  37773. {
  37774. for (int i = columns.size(); --i >= 0;)
  37775. columns.getUnchecked(i)->propertyFlags &= ~(sortedForwards | sortedBackwards);
  37776. ColumnInfo* const ci = getInfoForId (columnId);
  37777. if (ci != 0)
  37778. ci->propertyFlags |= (sortForwards ? sortedForwards : sortedBackwards);
  37779. reSortTable();
  37780. }
  37781. }
  37782. int TableHeaderComponent::getSortColumnId() const throw()
  37783. {
  37784. for (int i = columns.size(); --i >= 0;)
  37785. if ((columns.getUnchecked(i)->propertyFlags & (sortedForwards | sortedBackwards)) != 0)
  37786. return columns.getUnchecked(i)->id;
  37787. return 0;
  37788. }
  37789. bool TableHeaderComponent::isSortedForwards() const throw()
  37790. {
  37791. for (int i = columns.size(); --i >= 0;)
  37792. if ((columns.getUnchecked(i)->propertyFlags & (sortedForwards | sortedBackwards)) != 0)
  37793. return (columns.getUnchecked(i)->propertyFlags & sortedForwards) != 0;
  37794. return true;
  37795. }
  37796. void TableHeaderComponent::reSortTable()
  37797. {
  37798. sortChanged = true;
  37799. repaint();
  37800. triggerAsyncUpdate();
  37801. }
  37802. const String TableHeaderComponent::toString() const
  37803. {
  37804. String s;
  37805. XmlElement doc (T("TABLELAYOUT"));
  37806. doc.setAttribute (T("sortedCol"), getSortColumnId());
  37807. doc.setAttribute (T("sortForwards"), isSortedForwards());
  37808. for (int i = 0; i < columns.size(); ++i)
  37809. {
  37810. const ColumnInfo* const ci = columns.getUnchecked (i);
  37811. XmlElement* const e = new XmlElement (T("COLUMN"));
  37812. doc.addChildElement (e);
  37813. e->setAttribute (T("id"), ci->id);
  37814. e->setAttribute (T("visible"), ci->isVisible());
  37815. e->setAttribute (T("width"), ci->width);
  37816. }
  37817. return doc.createDocument (String::empty, true, false);
  37818. }
  37819. void TableHeaderComponent::restoreFromString (const String& storedVersion)
  37820. {
  37821. XmlDocument doc (storedVersion);
  37822. XmlElement* const storedXml = doc.getDocumentElement();
  37823. int index = 0;
  37824. if (storedXml != 0 && storedXml->hasTagName (T("TABLELAYOUT")))
  37825. {
  37826. forEachXmlChildElement (*storedXml, col)
  37827. {
  37828. const int tabId = col->getIntAttribute (T("id"));
  37829. ColumnInfo* const ci = getInfoForId (tabId);
  37830. if (ci != 0)
  37831. {
  37832. columns.move (columns.indexOf (ci), index);
  37833. ci->width = col->getIntAttribute (T("width"));
  37834. setColumnVisible (tabId, col->getBoolAttribute (T("visible")));
  37835. }
  37836. ++index;
  37837. }
  37838. columnsResized = true;
  37839. sendColumnsChanged();
  37840. setSortColumnId (storedXml->getIntAttribute (T("sortedCol")),
  37841. storedXml->getBoolAttribute (T("sortForwards"), true));
  37842. }
  37843. delete storedXml;
  37844. }
  37845. void TableHeaderComponent::addListener (TableHeaderListener* const newListener) throw()
  37846. {
  37847. listeners.addIfNotAlreadyThere (newListener);
  37848. }
  37849. void TableHeaderComponent::removeListener (TableHeaderListener* const listenerToRemove) throw()
  37850. {
  37851. listeners.removeValue (listenerToRemove);
  37852. }
  37853. void TableHeaderComponent::columnClicked (int columnId, const ModifierKeys& mods)
  37854. {
  37855. const ColumnInfo* const ci = getInfoForId (columnId);
  37856. if (ci != 0 && (ci->propertyFlags & sortable) != 0 && ! mods.isPopupMenu())
  37857. setSortColumnId (columnId, (ci->propertyFlags & sortedForwards) == 0);
  37858. }
  37859. void TableHeaderComponent::addMenuItems (PopupMenu& menu, const int /*columnIdClicked*/)
  37860. {
  37861. for (int i = 0; i < columns.size(); ++i)
  37862. {
  37863. const ColumnInfo* const ci = columns.getUnchecked(i);
  37864. if ((ci->propertyFlags & appearsOnColumnMenu) != 0)
  37865. menu.addItem (ci->id, ci->name,
  37866. (ci->propertyFlags & (sortedForwards | sortedBackwards)) == 0,
  37867. isColumnVisible (ci->id));
  37868. }
  37869. }
  37870. void TableHeaderComponent::reactToMenuItem (const int menuReturnId, const int /*columnIdClicked*/)
  37871. {
  37872. if (getIndexOfColumnId (menuReturnId, false) >= 0)
  37873. setColumnVisible (menuReturnId, ! isColumnVisible (menuReturnId));
  37874. }
  37875. void TableHeaderComponent::paint (Graphics& g)
  37876. {
  37877. LookAndFeel& lf = getLookAndFeel();
  37878. lf.drawTableHeaderBackground (g, *this);
  37879. const Rectangle clip (g.getClipBounds());
  37880. int x = 0;
  37881. for (int i = 0; i < columns.size(); ++i)
  37882. {
  37883. const ColumnInfo* const ci = columns.getUnchecked(i);
  37884. if (ci->isVisible())
  37885. {
  37886. if (x + ci->width > clip.getX()
  37887. && (ci->id != columnIdBeingDragged
  37888. || dragOverlayComp == 0
  37889. || ! dragOverlayComp->isVisible()))
  37890. {
  37891. g.saveState();
  37892. g.setOrigin (x, 0);
  37893. g.reduceClipRegion (0, 0, ci->width, getHeight());
  37894. lf.drawTableHeaderColumn (g, ci->name, ci->id, ci->width, getHeight(),
  37895. ci->id == columnIdUnderMouse,
  37896. ci->id == columnIdUnderMouse && isMouseButtonDown(),
  37897. ci->propertyFlags);
  37898. g.restoreState();
  37899. }
  37900. x += ci->width;
  37901. if (x >= clip.getRight())
  37902. break;
  37903. }
  37904. }
  37905. }
  37906. void TableHeaderComponent::resized()
  37907. {
  37908. }
  37909. void TableHeaderComponent::mouseMove (const MouseEvent& e)
  37910. {
  37911. updateColumnUnderMouse (e.x, e.y);
  37912. }
  37913. void TableHeaderComponent::mouseEnter (const MouseEvent& e)
  37914. {
  37915. updateColumnUnderMouse (e.x, e.y);
  37916. }
  37917. void TableHeaderComponent::mouseExit (const MouseEvent& e)
  37918. {
  37919. updateColumnUnderMouse (e.x, e.y);
  37920. }
  37921. void TableHeaderComponent::mouseDown (const MouseEvent& e)
  37922. {
  37923. repaint();
  37924. columnIdBeingResized = 0;
  37925. columnIdBeingDragged = 0;
  37926. if (columnIdUnderMouse != 0)
  37927. {
  37928. draggingColumnOffset = e.x - getColumnPosition (getIndexOfColumnId (columnIdUnderMouse, true)).getX();
  37929. if (e.mods.isPopupMenu())
  37930. columnClicked (columnIdUnderMouse, e.mods);
  37931. }
  37932. if (menuActive && e.mods.isPopupMenu())
  37933. showColumnChooserMenu (columnIdUnderMouse);
  37934. }
  37935. void TableHeaderComponent::mouseDrag (const MouseEvent& e)
  37936. {
  37937. if (columnIdBeingResized == 0
  37938. && columnIdBeingDragged == 0
  37939. && ! (e.mouseWasClicked() || e.mods.isPopupMenu()))
  37940. {
  37941. deleteAndZero (dragOverlayComp);
  37942. columnIdBeingResized = getResizeDraggerAt (e.getMouseDownX());
  37943. if (columnIdBeingResized != 0)
  37944. {
  37945. const ColumnInfo* const ci = getInfoForId (columnIdBeingResized);
  37946. initialColumnWidth = ci->width;
  37947. }
  37948. else
  37949. {
  37950. beginDrag (e);
  37951. }
  37952. }
  37953. if (columnIdBeingResized != 0)
  37954. {
  37955. const ColumnInfo* const ci = getInfoForId (columnIdBeingResized);
  37956. if (ci != 0)
  37957. {
  37958. int w = jlimit (ci->minimumWidth, ci->maximumWidth,
  37959. initialColumnWidth + e.getDistanceFromDragStartX());
  37960. if (stretchToFit)
  37961. {
  37962. // prevent us dragging a column too far right if we're in stretch-to-fit mode
  37963. int minWidthOnRight = 0;
  37964. for (int i = getIndexOfColumnId (columnIdBeingResized, false) + 1; i < columns.size(); ++i)
  37965. if (columns.getUnchecked (i)->isVisible())
  37966. minWidthOnRight += columns.getUnchecked (i)->minimumWidth;
  37967. const Rectangle currentPos (getColumnPosition (getIndexOfColumnId (columnIdBeingResized, true)));
  37968. w = jmax (ci->minimumWidth, jmin (w, getWidth() - minWidthOnRight - currentPos.getX()));
  37969. }
  37970. setColumnWidth (columnIdBeingResized, w);
  37971. }
  37972. }
  37973. else if (columnIdBeingDragged != 0)
  37974. {
  37975. if (e.y >= -50 && e.y < getHeight() + 50)
  37976. {
  37977. beginDrag (e);
  37978. if (dragOverlayComp != 0)
  37979. {
  37980. dragOverlayComp->setVisible (true);
  37981. dragOverlayComp->setBounds (jlimit (0,
  37982. jmax (0, getTotalWidth() - dragOverlayComp->getWidth()),
  37983. e.x - draggingColumnOffset),
  37984. 0,
  37985. dragOverlayComp->getWidth(),
  37986. getHeight());
  37987. for (int i = columns.size(); --i >= 0;)
  37988. {
  37989. const int currentIndex = getIndexOfColumnId (columnIdBeingDragged, true);
  37990. int newIndex = currentIndex;
  37991. if (newIndex > 0)
  37992. {
  37993. // if the previous column isn't draggable, we can't move our column
  37994. // past it, because that'd change the undraggable column's position..
  37995. const ColumnInfo* const previous = columns.getUnchecked (newIndex - 1);
  37996. if ((previous->propertyFlags & draggable) != 0)
  37997. {
  37998. const int leftOfPrevious = getColumnPosition (newIndex - 1).getX();
  37999. const int rightOfCurrent = getColumnPosition (newIndex).getRight();
  38000. if (abs (dragOverlayComp->getX() - leftOfPrevious)
  38001. < abs (dragOverlayComp->getRight() - rightOfCurrent))
  38002. {
  38003. --newIndex;
  38004. }
  38005. }
  38006. }
  38007. if (newIndex < columns.size() - 1)
  38008. {
  38009. // if the next column isn't draggable, we can't move our column
  38010. // past it, because that'd change the undraggable column's position..
  38011. const ColumnInfo* const nextCol = columns.getUnchecked (newIndex + 1);
  38012. if ((nextCol->propertyFlags & draggable) != 0)
  38013. {
  38014. const int leftOfCurrent = getColumnPosition (newIndex).getX();
  38015. const int rightOfNext = getColumnPosition (newIndex + 1).getRight();
  38016. if (abs (dragOverlayComp->getX() - leftOfCurrent)
  38017. > abs (dragOverlayComp->getRight() - rightOfNext))
  38018. {
  38019. ++newIndex;
  38020. }
  38021. }
  38022. }
  38023. if (newIndex != currentIndex)
  38024. moveColumn (columnIdBeingDragged, newIndex);
  38025. else
  38026. break;
  38027. }
  38028. }
  38029. }
  38030. else
  38031. {
  38032. endDrag (draggingColumnOriginalIndex);
  38033. }
  38034. }
  38035. }
  38036. void TableHeaderComponent::beginDrag (const MouseEvent& e)
  38037. {
  38038. if (columnIdBeingDragged == 0)
  38039. {
  38040. columnIdBeingDragged = getColumnIdAtX (e.getMouseDownX());
  38041. const ColumnInfo* const ci = getInfoForId (columnIdBeingDragged);
  38042. if (ci == 0 || (ci->propertyFlags & draggable) == 0)
  38043. {
  38044. columnIdBeingDragged = 0;
  38045. }
  38046. else
  38047. {
  38048. draggingColumnOriginalIndex = getIndexOfColumnId (columnIdBeingDragged, true);
  38049. const Rectangle columnRect (getColumnPosition (draggingColumnOriginalIndex));
  38050. const int temp = columnIdBeingDragged;
  38051. columnIdBeingDragged = 0;
  38052. addAndMakeVisible (dragOverlayComp = new DragOverlayComp (createComponentSnapshot (columnRect, false)));
  38053. columnIdBeingDragged = temp;
  38054. dragOverlayComp->setBounds (columnRect);
  38055. for (int i = listeners.size(); --i >= 0;)
  38056. {
  38057. listeners.getUnchecked(i)->tableColumnDraggingChanged (this, columnIdBeingDragged);
  38058. i = jmin (i, listeners.size() - 1);
  38059. }
  38060. }
  38061. }
  38062. }
  38063. void TableHeaderComponent::endDrag (const int finalIndex)
  38064. {
  38065. if (columnIdBeingDragged != 0)
  38066. {
  38067. moveColumn (columnIdBeingDragged, finalIndex);
  38068. columnIdBeingDragged = 0;
  38069. repaint();
  38070. for (int i = listeners.size(); --i >= 0;)
  38071. {
  38072. listeners.getUnchecked(i)->tableColumnDraggingChanged (this, 0);
  38073. i = jmin (i, listeners.size() - 1);
  38074. }
  38075. }
  38076. }
  38077. void TableHeaderComponent::mouseUp (const MouseEvent& e)
  38078. {
  38079. mouseDrag (e);
  38080. for (int i = columns.size(); --i >= 0;)
  38081. if (columns.getUnchecked (i)->isVisible())
  38082. columns.getUnchecked (i)->lastDeliberateWidth = columns.getUnchecked (i)->width;
  38083. columnIdBeingResized = 0;
  38084. repaint();
  38085. endDrag (getIndexOfColumnId (columnIdBeingDragged, true));
  38086. updateColumnUnderMouse (e.x, e.y);
  38087. if (columnIdUnderMouse != 0 && e.mouseWasClicked() && ! e.mods.isPopupMenu())
  38088. columnClicked (columnIdUnderMouse, e.mods);
  38089. deleteAndZero (dragOverlayComp);
  38090. }
  38091. const MouseCursor TableHeaderComponent::getMouseCursor()
  38092. {
  38093. int x, y;
  38094. getMouseXYRelative (x, y);
  38095. if (columnIdBeingResized != 0 || (getResizeDraggerAt (x) != 0 && ! isMouseButtonDown()))
  38096. return MouseCursor (MouseCursor::LeftRightResizeCursor);
  38097. return Component::getMouseCursor();
  38098. }
  38099. bool TableHeaderComponent::ColumnInfo::isVisible() const throw()
  38100. {
  38101. return (propertyFlags & TableHeaderComponent::visible) != 0;
  38102. }
  38103. TableHeaderComponent::ColumnInfo* TableHeaderComponent::getInfoForId (const int id) const throw()
  38104. {
  38105. for (int i = columns.size(); --i >= 0;)
  38106. if (columns.getUnchecked(i)->id == id)
  38107. return columns.getUnchecked(i);
  38108. return 0;
  38109. }
  38110. int TableHeaderComponent::visibleIndexToTotalIndex (const int visibleIndex) const throw()
  38111. {
  38112. int n = 0;
  38113. for (int i = 0; i < columns.size(); ++i)
  38114. {
  38115. if (columns.getUnchecked(i)->isVisible())
  38116. {
  38117. if (n == visibleIndex)
  38118. return i;
  38119. ++n;
  38120. }
  38121. }
  38122. return -1;
  38123. }
  38124. void TableHeaderComponent::sendColumnsChanged()
  38125. {
  38126. if (stretchToFit && lastDeliberateWidth > 0)
  38127. resizeAllColumnsToFit (lastDeliberateWidth);
  38128. repaint();
  38129. columnsChanged = true;
  38130. triggerAsyncUpdate();
  38131. }
  38132. void TableHeaderComponent::handleAsyncUpdate()
  38133. {
  38134. const bool changed = columnsChanged || sortChanged;
  38135. const bool sized = columnsResized || changed;
  38136. const bool sorted = sortChanged;
  38137. columnsChanged = false;
  38138. columnsResized = false;
  38139. sortChanged = false;
  38140. if (sorted)
  38141. {
  38142. for (int i = listeners.size(); --i >= 0;)
  38143. {
  38144. listeners.getUnchecked(i)->tableSortOrderChanged (this);
  38145. i = jmin (i, listeners.size() - 1);
  38146. }
  38147. }
  38148. if (changed)
  38149. {
  38150. for (int i = listeners.size(); --i >= 0;)
  38151. {
  38152. listeners.getUnchecked(i)->tableColumnsChanged (this);
  38153. i = jmin (i, listeners.size() - 1);
  38154. }
  38155. }
  38156. if (sized)
  38157. {
  38158. for (int i = listeners.size(); --i >= 0;)
  38159. {
  38160. listeners.getUnchecked(i)->tableColumnsResized (this);
  38161. i = jmin (i, listeners.size() - 1);
  38162. }
  38163. }
  38164. }
  38165. int TableHeaderComponent::getResizeDraggerAt (const int mouseX) const throw()
  38166. {
  38167. if (((unsigned int) mouseX) < (unsigned int) getWidth())
  38168. {
  38169. const int draggableDistance = 3;
  38170. int x = 0;
  38171. for (int i = 0; i < columns.size(); ++i)
  38172. {
  38173. const ColumnInfo* const ci = columns.getUnchecked(i);
  38174. if (ci->isVisible())
  38175. {
  38176. if (abs (mouseX - (x + ci->width)) <= draggableDistance
  38177. && (ci->propertyFlags & resizable) != 0)
  38178. return ci->id;
  38179. x += ci->width;
  38180. }
  38181. }
  38182. }
  38183. return 0;
  38184. }
  38185. void TableHeaderComponent::updateColumnUnderMouse (int x, int y)
  38186. {
  38187. const int newCol = (reallyContains (x, y, true) && getResizeDraggerAt (x) == 0)
  38188. ? getColumnIdAtX (x) : 0;
  38189. if (newCol != columnIdUnderMouse)
  38190. {
  38191. columnIdUnderMouse = newCol;
  38192. repaint();
  38193. }
  38194. }
  38195. void TableHeaderComponent::showColumnChooserMenu (const int columnIdClicked)
  38196. {
  38197. PopupMenu m;
  38198. addMenuItems (m, columnIdClicked);
  38199. if (m.getNumItems() > 0)
  38200. {
  38201. const int result = m.show();
  38202. if (result != 0)
  38203. reactToMenuItem (result, columnIdClicked);
  38204. }
  38205. }
  38206. void TableHeaderListener::tableColumnDraggingChanged (TableHeaderComponent*, int)
  38207. {
  38208. }
  38209. END_JUCE_NAMESPACE
  38210. /********* End of inlined file: juce_TableHeaderComponent.cpp *********/
  38211. /********* Start of inlined file: juce_TableListBox.cpp *********/
  38212. BEGIN_JUCE_NAMESPACE
  38213. static const tchar* const tableColumnPropertyTag = T("_tableColumnID");
  38214. class TableListRowComp : public Component
  38215. {
  38216. public:
  38217. TableListRowComp (TableListBox& owner_)
  38218. : owner (owner_),
  38219. row (-1),
  38220. isSelected (false)
  38221. {
  38222. }
  38223. ~TableListRowComp()
  38224. {
  38225. deleteAllChildren();
  38226. }
  38227. void paint (Graphics& g)
  38228. {
  38229. TableListBoxModel* const model = owner.getModel();
  38230. if (model != 0)
  38231. {
  38232. const TableHeaderComponent* const header = owner.getHeader();
  38233. model->paintRowBackground (g, row, getWidth(), getHeight(), isSelected);
  38234. const int numColumns = header->getNumColumns (true);
  38235. for (int i = 0; i < numColumns; ++i)
  38236. {
  38237. if (! columnsWithComponents [i])
  38238. {
  38239. const int columnId = header->getColumnIdOfIndex (i, true);
  38240. Rectangle columnRect (header->getColumnPosition (i));
  38241. columnRect.setSize (columnRect.getWidth(), getHeight());
  38242. g.saveState();
  38243. g.reduceClipRegion (columnRect);
  38244. g.setOrigin (columnRect.getX(), 0);
  38245. model->paintCell (g, row, columnId, columnRect.getWidth(), columnRect.getHeight(), isSelected);
  38246. g.restoreState();
  38247. }
  38248. }
  38249. }
  38250. }
  38251. void update (const int newRow, const bool isNowSelected)
  38252. {
  38253. if (newRow != row || isNowSelected != isSelected)
  38254. {
  38255. row = newRow;
  38256. isSelected = isNowSelected;
  38257. repaint();
  38258. }
  38259. if (row < owner.getNumRows())
  38260. {
  38261. jassert (row >= 0);
  38262. const tchar* const tagPropertyName = T("_tableLastUseNum");
  38263. const int newTag = Random::getSystemRandom().nextInt();
  38264. const TableHeaderComponent* const header = owner.getHeader();
  38265. const int numColumns = header->getNumColumns (true);
  38266. int i;
  38267. columnsWithComponents.clear();
  38268. if (owner.getModel() != 0)
  38269. {
  38270. for (i = 0; i < numColumns; ++i)
  38271. {
  38272. const int columnId = header->getColumnIdOfIndex (i, true);
  38273. Component* const newComp
  38274. = owner.getModel()->refreshComponentForCell (row, columnId, isSelected,
  38275. findChildComponentForColumn (columnId));
  38276. if (newComp != 0)
  38277. {
  38278. addAndMakeVisible (newComp);
  38279. newComp->setComponentProperty (tagPropertyName, newTag);
  38280. newComp->setComponentProperty (tableColumnPropertyTag, columnId);
  38281. const Rectangle columnRect (header->getColumnPosition (i));
  38282. newComp->setBounds (columnRect.getX(), 0, columnRect.getWidth(), getHeight());
  38283. columnsWithComponents.setBit (i);
  38284. }
  38285. }
  38286. }
  38287. for (i = getNumChildComponents(); --i >= 0;)
  38288. {
  38289. Component* const c = getChildComponent (i);
  38290. if (c->getComponentPropertyInt (tagPropertyName, false, 0) != newTag)
  38291. delete c;
  38292. }
  38293. }
  38294. else
  38295. {
  38296. columnsWithComponents.clear();
  38297. deleteAllChildren();
  38298. }
  38299. }
  38300. void resized()
  38301. {
  38302. for (int i = getNumChildComponents(); --i >= 0;)
  38303. {
  38304. Component* const c = getChildComponent (i);
  38305. const int columnId = c->getComponentPropertyInt (tableColumnPropertyTag, false, 0);
  38306. if (columnId != 0)
  38307. {
  38308. const Rectangle columnRect (owner.getHeader()->getColumnPosition (owner.getHeader()->getIndexOfColumnId (columnId, true)));
  38309. c->setBounds (columnRect.getX(), 0, columnRect.getWidth(), getHeight());
  38310. }
  38311. }
  38312. }
  38313. void mouseDown (const MouseEvent& e)
  38314. {
  38315. isDragging = false;
  38316. selectRowOnMouseUp = false;
  38317. if (isEnabled())
  38318. {
  38319. if (! isSelected)
  38320. {
  38321. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  38322. const int columnId = owner.getHeader()->getColumnIdAtX (e.x);
  38323. if (columnId != 0 && owner.getModel() != 0)
  38324. owner.getModel()->cellClicked (row, columnId, e);
  38325. }
  38326. else
  38327. {
  38328. selectRowOnMouseUp = true;
  38329. }
  38330. }
  38331. }
  38332. void mouseDrag (const MouseEvent& e)
  38333. {
  38334. if (isEnabled() && owner.getModel() != 0 && ! (e.mouseWasClicked() || isDragging))
  38335. {
  38336. const SparseSet <int> selectedRows (owner.getSelectedRows());
  38337. if (selectedRows.size() > 0)
  38338. {
  38339. const String dragDescription (owner.getModel()->getDragSourceDescription (selectedRows));
  38340. if (dragDescription.isNotEmpty())
  38341. {
  38342. isDragging = true;
  38343. DragAndDropContainer* const dragContainer
  38344. = DragAndDropContainer::findParentDragContainerFor (this);
  38345. if (dragContainer != 0)
  38346. {
  38347. Image* dragImage = owner.createSnapshotOfSelectedRows();
  38348. dragImage->multiplyAllAlphas (0.6f);
  38349. dragContainer->startDragging (dragDescription, &owner, dragImage, true);
  38350. }
  38351. else
  38352. {
  38353. // to be able to do a drag-and-drop operation, the listbox needs to
  38354. // be inside a component which is also a DragAndDropContainer.
  38355. jassertfalse
  38356. }
  38357. }
  38358. }
  38359. }
  38360. }
  38361. void mouseUp (const MouseEvent& e)
  38362. {
  38363. if (selectRowOnMouseUp && e.mouseWasClicked() && isEnabled())
  38364. {
  38365. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  38366. const int columnId = owner.getHeader()->getColumnIdAtX (e.x);
  38367. if (columnId != 0 && owner.getModel() != 0)
  38368. owner.getModel()->cellClicked (row, columnId, e);
  38369. }
  38370. }
  38371. void mouseDoubleClick (const MouseEvent& e)
  38372. {
  38373. const int columnId = owner.getHeader()->getColumnIdAtX (e.x);
  38374. if (columnId != 0 && owner.getModel() != 0)
  38375. owner.getModel()->cellDoubleClicked (row, columnId, e);
  38376. }
  38377. juce_UseDebuggingNewOperator
  38378. private:
  38379. TableListBox& owner;
  38380. int row;
  38381. bool isSelected, isDragging, selectRowOnMouseUp;
  38382. BitArray columnsWithComponents;
  38383. Component* findChildComponentForColumn (const int columnId) const
  38384. {
  38385. for (int i = getNumChildComponents(); --i >= 0;)
  38386. {
  38387. Component* const c = getChildComponent (i);
  38388. if (c->getComponentPropertyInt (tableColumnPropertyTag, false, 0) == columnId)
  38389. return c;
  38390. }
  38391. return 0;
  38392. }
  38393. TableListRowComp (const TableListRowComp&);
  38394. const TableListRowComp& operator= (const TableListRowComp&);
  38395. };
  38396. class TableListBoxHeader : public TableHeaderComponent
  38397. {
  38398. public:
  38399. TableListBoxHeader (TableListBox& owner_)
  38400. : owner (owner_)
  38401. {
  38402. }
  38403. ~TableListBoxHeader()
  38404. {
  38405. }
  38406. void addMenuItems (PopupMenu& menu, const int columnIdClicked)
  38407. {
  38408. if (owner.isAutoSizeMenuOptionShown())
  38409. {
  38410. menu.addItem (0xf836743, TRANS("Auto-size this column"), columnIdClicked != 0);
  38411. menu.addItem (0xf836744, TRANS("Auto-size all columns"), owner.getHeader()->getNumColumns (true) > 0);
  38412. menu.addSeparator();
  38413. }
  38414. TableHeaderComponent::addMenuItems (menu, columnIdClicked);
  38415. }
  38416. void reactToMenuItem (const int menuReturnId, const int columnIdClicked)
  38417. {
  38418. if (menuReturnId == 0xf836743)
  38419. {
  38420. owner.autoSizeColumn (columnIdClicked);
  38421. }
  38422. else if (menuReturnId == 0xf836744)
  38423. {
  38424. owner.autoSizeAllColumns();
  38425. }
  38426. else
  38427. {
  38428. TableHeaderComponent::reactToMenuItem (menuReturnId, columnIdClicked);
  38429. }
  38430. }
  38431. juce_UseDebuggingNewOperator
  38432. private:
  38433. TableListBox& owner;
  38434. TableListBoxHeader (const TableListBoxHeader&);
  38435. const TableListBoxHeader& operator= (const TableListBoxHeader&);
  38436. };
  38437. TableListBox::TableListBox (const String& name, TableListBoxModel* const model_)
  38438. : ListBox (name, 0),
  38439. model (model_),
  38440. autoSizeOptionsShown (true)
  38441. {
  38442. ListBox::model = this;
  38443. header = new TableListBoxHeader (*this);
  38444. header->setSize (100, 28);
  38445. header->addListener (this);
  38446. setHeaderComponent (header);
  38447. }
  38448. TableListBox::~TableListBox()
  38449. {
  38450. deleteAllChildren();
  38451. }
  38452. void TableListBox::setModel (TableListBoxModel* const newModel)
  38453. {
  38454. if (model != newModel)
  38455. {
  38456. model = newModel;
  38457. updateContent();
  38458. }
  38459. }
  38460. int TableListBox::getHeaderHeight() const throw()
  38461. {
  38462. return header->getHeight();
  38463. }
  38464. void TableListBox::setHeaderHeight (const int newHeight)
  38465. {
  38466. header->setSize (header->getWidth(), newHeight);
  38467. resized();
  38468. }
  38469. void TableListBox::autoSizeColumn (const int columnId)
  38470. {
  38471. const int width = model != 0 ? model->getColumnAutoSizeWidth (columnId) : 0;
  38472. if (width > 0)
  38473. header->setColumnWidth (columnId, width);
  38474. }
  38475. void TableListBox::autoSizeAllColumns()
  38476. {
  38477. for (int i = 0; i < header->getNumColumns (true); ++i)
  38478. autoSizeColumn (header->getColumnIdOfIndex (i, true));
  38479. }
  38480. void TableListBox::setAutoSizeMenuOptionShown (const bool shouldBeShown)
  38481. {
  38482. autoSizeOptionsShown = shouldBeShown;
  38483. }
  38484. bool TableListBox::isAutoSizeMenuOptionShown() const throw()
  38485. {
  38486. return autoSizeOptionsShown;
  38487. }
  38488. const Rectangle TableListBox::getCellPosition (const int columnId,
  38489. const int rowNumber,
  38490. const bool relativeToComponentTopLeft) const
  38491. {
  38492. Rectangle headerCell (header->getColumnPosition (header->getIndexOfColumnId (columnId, true)));
  38493. if (relativeToComponentTopLeft)
  38494. headerCell.translate (header->getX(), 0);
  38495. const Rectangle row (getRowPosition (rowNumber, relativeToComponentTopLeft));
  38496. return Rectangle (headerCell.getX(), row.getY(),
  38497. headerCell.getWidth(), row.getHeight());
  38498. }
  38499. void TableListBox::scrollToEnsureColumnIsOnscreen (const int columnId)
  38500. {
  38501. ScrollBar* const scrollbar = getHorizontalScrollBar();
  38502. if (scrollbar != 0)
  38503. {
  38504. const Rectangle pos (header->getColumnPosition (header->getIndexOfColumnId (columnId, true)));
  38505. double x = scrollbar->getCurrentRangeStart();
  38506. const double w = scrollbar->getCurrentRangeSize();
  38507. if (pos.getX() < x)
  38508. x = pos.getX();
  38509. else if (pos.getRight() > x + w)
  38510. x += jmax (0.0, pos.getRight() - (x + w));
  38511. scrollbar->setCurrentRangeStart (x);
  38512. }
  38513. }
  38514. int TableListBox::getNumRows()
  38515. {
  38516. return model != 0 ? model->getNumRows() : 0;
  38517. }
  38518. void TableListBox::paintListBoxItem (int, Graphics&, int, int, bool)
  38519. {
  38520. }
  38521. Component* TableListBox::refreshComponentForRow (int rowNumber, bool isRowSelected_, Component* existingComponentToUpdate)
  38522. {
  38523. if (existingComponentToUpdate == 0)
  38524. existingComponentToUpdate = new TableListRowComp (*this);
  38525. ((TableListRowComp*) existingComponentToUpdate)->update (rowNumber, isRowSelected_);
  38526. return existingComponentToUpdate;
  38527. }
  38528. void TableListBox::selectedRowsChanged (int row)
  38529. {
  38530. if (model != 0)
  38531. model->selectedRowsChanged (row);
  38532. }
  38533. void TableListBox::deleteKeyPressed (int row)
  38534. {
  38535. if (model != 0)
  38536. model->deleteKeyPressed (row);
  38537. }
  38538. void TableListBox::returnKeyPressed (int row)
  38539. {
  38540. if (model != 0)
  38541. model->returnKeyPressed (row);
  38542. }
  38543. void TableListBox::backgroundClicked()
  38544. {
  38545. if (model != 0)
  38546. model->backgroundClicked();
  38547. }
  38548. void TableListBox::listWasScrolled()
  38549. {
  38550. if (model != 0)
  38551. model->listWasScrolled();
  38552. }
  38553. void TableListBox::tableColumnsChanged (TableHeaderComponent*)
  38554. {
  38555. setMinimumContentWidth (header->getTotalWidth());
  38556. repaint();
  38557. updateColumnComponents();
  38558. }
  38559. void TableListBox::tableColumnsResized (TableHeaderComponent*)
  38560. {
  38561. setMinimumContentWidth (header->getTotalWidth());
  38562. repaint();
  38563. updateColumnComponents();
  38564. }
  38565. void TableListBox::tableSortOrderChanged (TableHeaderComponent*)
  38566. {
  38567. if (model != 0)
  38568. model->sortOrderChanged (header->getSortColumnId(),
  38569. header->isSortedForwards());
  38570. }
  38571. void TableListBox::tableColumnDraggingChanged (TableHeaderComponent*, int columnIdNowBeingDragged_)
  38572. {
  38573. columnIdNowBeingDragged = columnIdNowBeingDragged_;
  38574. repaint();
  38575. }
  38576. void TableListBox::resized()
  38577. {
  38578. ListBox::resized();
  38579. header->resizeAllColumnsToFit (getVisibleContentWidth());
  38580. setMinimumContentWidth (header->getTotalWidth());
  38581. }
  38582. void TableListBox::updateColumnComponents() const
  38583. {
  38584. const int firstRow = getRowContainingPosition (0, 0);
  38585. for (int i = firstRow + getNumRowsOnScreen() + 2; --i >= firstRow;)
  38586. {
  38587. TableListRowComp* const rowComp = dynamic_cast <TableListRowComp*> (getComponentForRowNumber (i));
  38588. if (rowComp != 0)
  38589. rowComp->resized();
  38590. }
  38591. }
  38592. void TableListBoxModel::cellClicked (int, int, const MouseEvent&)
  38593. {
  38594. }
  38595. void TableListBoxModel::cellDoubleClicked (int, int, const MouseEvent&)
  38596. {
  38597. }
  38598. void TableListBoxModel::backgroundClicked()
  38599. {
  38600. }
  38601. void TableListBoxModel::sortOrderChanged (int, const bool)
  38602. {
  38603. }
  38604. int TableListBoxModel::getColumnAutoSizeWidth (int)
  38605. {
  38606. return 0;
  38607. }
  38608. void TableListBoxModel::selectedRowsChanged (int)
  38609. {
  38610. }
  38611. void TableListBoxModel::deleteKeyPressed (int)
  38612. {
  38613. }
  38614. void TableListBoxModel::returnKeyPressed (int)
  38615. {
  38616. }
  38617. void TableListBoxModel::listWasScrolled()
  38618. {
  38619. }
  38620. const String TableListBoxModel::getDragSourceDescription (const SparseSet<int>&)
  38621. {
  38622. return String::empty;
  38623. }
  38624. Component* TableListBoxModel::refreshComponentForCell (int, int, bool, Component* existingComponentToUpdate)
  38625. {
  38626. (void) existingComponentToUpdate;
  38627. jassert (existingComponentToUpdate == 0); // indicates a failure in the code the recycles the components
  38628. return 0;
  38629. }
  38630. END_JUCE_NAMESPACE
  38631. /********* End of inlined file: juce_TableListBox.cpp *********/
  38632. /********* Start of inlined file: juce_TextEditor.cpp *********/
  38633. BEGIN_JUCE_NAMESPACE
  38634. #define SHOULD_WRAP(x, wrapwidth) (((x) - 0.0001f) >= (wrapwidth))
  38635. // a word or space that can't be broken down any further
  38636. struct TextAtom
  38637. {
  38638. String atomText;
  38639. float width;
  38640. uint16 numChars;
  38641. bool isWhitespace() const throw() { return CharacterFunctions::isWhitespace (atomText[0]); }
  38642. bool isNewLine() const throw() { return atomText[0] == T('\r') || atomText[0] == T('\n'); }
  38643. const String getText (const tchar passwordCharacter) const throw()
  38644. {
  38645. if (passwordCharacter == 0)
  38646. return atomText;
  38647. else
  38648. return String::repeatedString (String::charToString (passwordCharacter),
  38649. atomText.length());
  38650. }
  38651. const String getTrimmedText (const tchar passwordCharacter) const throw()
  38652. {
  38653. if (passwordCharacter == 0)
  38654. return atomText.substring (0, numChars);
  38655. else if (isNewLine())
  38656. return String::empty;
  38657. else
  38658. return String::repeatedString (String::charToString (passwordCharacter), numChars);
  38659. }
  38660. };
  38661. // a run of text with a single font and colour
  38662. class UniformTextSection
  38663. {
  38664. public:
  38665. UniformTextSection (const String& text,
  38666. const Font& font_,
  38667. const Colour& colour_,
  38668. const tchar passwordCharacter) throw()
  38669. : font (font_),
  38670. colour (colour_),
  38671. atoms (64)
  38672. {
  38673. initialiseAtoms (text, passwordCharacter);
  38674. }
  38675. UniformTextSection (const UniformTextSection& other) throw()
  38676. : font (other.font),
  38677. colour (other.colour),
  38678. atoms (64)
  38679. {
  38680. for (int i = 0; i < other.atoms.size(); ++i)
  38681. atoms.add (new TextAtom (*(const TextAtom*) other.atoms.getUnchecked(i)));
  38682. }
  38683. ~UniformTextSection() throw()
  38684. {
  38685. // (no need to delete the atoms, as they're explicitly deleted by the caller)
  38686. }
  38687. void clear() throw()
  38688. {
  38689. for (int i = atoms.size(); --i >= 0;)
  38690. {
  38691. TextAtom* const atom = getAtom(i);
  38692. delete atom;
  38693. }
  38694. atoms.clear();
  38695. }
  38696. int getNumAtoms() const throw()
  38697. {
  38698. return atoms.size();
  38699. }
  38700. TextAtom* getAtom (const int index) const throw()
  38701. {
  38702. return (TextAtom*) atoms.getUnchecked (index);
  38703. }
  38704. void append (const UniformTextSection& other, const tchar passwordCharacter) throw()
  38705. {
  38706. if (other.atoms.size() > 0)
  38707. {
  38708. TextAtom* const lastAtom = (TextAtom*) atoms.getLast();
  38709. int i = 0;
  38710. if (lastAtom != 0)
  38711. {
  38712. if (! CharacterFunctions::isWhitespace (lastAtom->atomText.getLastCharacter()))
  38713. {
  38714. TextAtom* const first = other.getAtom(0);
  38715. if (! CharacterFunctions::isWhitespace (first->atomText[0]))
  38716. {
  38717. lastAtom->atomText += first->atomText;
  38718. lastAtom->numChars = (uint16) (lastAtom->numChars + first->numChars);
  38719. lastAtom->width = font.getStringWidthFloat (lastAtom->getText (passwordCharacter));
  38720. delete first;
  38721. ++i;
  38722. }
  38723. }
  38724. }
  38725. while (i < other.atoms.size())
  38726. {
  38727. atoms.add (other.getAtom(i));
  38728. ++i;
  38729. }
  38730. }
  38731. }
  38732. UniformTextSection* split (const int indexToBreakAt,
  38733. const tchar passwordCharacter) throw()
  38734. {
  38735. UniformTextSection* const section2 = new UniformTextSection (String::empty,
  38736. font, colour,
  38737. passwordCharacter);
  38738. int index = 0;
  38739. for (int i = 0; i < atoms.size(); ++i)
  38740. {
  38741. TextAtom* const atom = getAtom(i);
  38742. const int nextIndex = index + atom->numChars;
  38743. if (index == indexToBreakAt)
  38744. {
  38745. int j;
  38746. for (j = i; j < atoms.size(); ++j)
  38747. section2->atoms.add (getAtom (j));
  38748. for (j = atoms.size(); --j >= i;)
  38749. atoms.remove (j);
  38750. break;
  38751. }
  38752. else if (indexToBreakAt >= index && indexToBreakAt < nextIndex)
  38753. {
  38754. TextAtom* const secondAtom = new TextAtom();
  38755. secondAtom->atomText = atom->atomText.substring (indexToBreakAt - index);
  38756. secondAtom->width = font.getStringWidthFloat (secondAtom->getText (passwordCharacter));
  38757. secondAtom->numChars = (uint16) secondAtom->atomText.length();
  38758. section2->atoms.add (secondAtom);
  38759. atom->atomText = atom->atomText.substring (0, indexToBreakAt - index);
  38760. atom->width = font.getStringWidthFloat (atom->getText (passwordCharacter));
  38761. atom->numChars = (uint16) (indexToBreakAt - index);
  38762. int j;
  38763. for (j = i + 1; j < atoms.size(); ++j)
  38764. section2->atoms.add (getAtom (j));
  38765. for (j = atoms.size(); --j > i;)
  38766. atoms.remove (j);
  38767. break;
  38768. }
  38769. index = nextIndex;
  38770. }
  38771. return section2;
  38772. }
  38773. const String getAllText() const throw()
  38774. {
  38775. String s;
  38776. s.preallocateStorage (getTotalLength());
  38777. tchar* endOfString = (tchar*) &(s[0]);
  38778. for (int i = 0; i < atoms.size(); ++i)
  38779. {
  38780. const TextAtom* const atom = getAtom(i);
  38781. memcpy (endOfString, &(atom->atomText[0]), atom->numChars * sizeof (tchar));
  38782. endOfString += atom->numChars;
  38783. }
  38784. *endOfString = 0;
  38785. jassert ((endOfString - (tchar*) &(s[0])) <= getTotalLength());
  38786. return s;
  38787. }
  38788. const String getTextSubstring (const int startCharacter,
  38789. const int endCharacter) const throw()
  38790. {
  38791. int index = 0;
  38792. int totalLen = 0;
  38793. int i;
  38794. for (i = 0; i < atoms.size(); ++i)
  38795. {
  38796. const TextAtom* const atom = getAtom (i);
  38797. const int nextIndex = index + atom->numChars;
  38798. if (startCharacter < nextIndex)
  38799. {
  38800. if (endCharacter <= index)
  38801. break;
  38802. const int start = jmax (0, startCharacter - index);
  38803. const int end = jmin (endCharacter - index, atom->numChars);
  38804. jassert (end >= start);
  38805. totalLen += end - start;
  38806. }
  38807. index = nextIndex;
  38808. }
  38809. String s;
  38810. s.preallocateStorage (totalLen + 1);
  38811. tchar* psz = (tchar*) (const tchar*) s;
  38812. index = 0;
  38813. for (i = 0; i < atoms.size(); ++i)
  38814. {
  38815. const TextAtom* const atom = getAtom (i);
  38816. const int nextIndex = index + atom->numChars;
  38817. if (startCharacter < nextIndex)
  38818. {
  38819. if (endCharacter <= index)
  38820. break;
  38821. const int start = jmax (0, startCharacter - index);
  38822. const int len = jmin (endCharacter - index, atom->numChars) - start;
  38823. memcpy (psz, ((const tchar*) atom->atomText) + start, len * sizeof (tchar));
  38824. psz += len;
  38825. *psz = 0;
  38826. }
  38827. index = nextIndex;
  38828. }
  38829. return s;
  38830. }
  38831. int getTotalLength() const throw()
  38832. {
  38833. int c = 0;
  38834. for (int i = atoms.size(); --i >= 0;)
  38835. c += getAtom(i)->numChars;
  38836. return c;
  38837. }
  38838. void setFont (const Font& newFont,
  38839. const tchar passwordCharacter) throw()
  38840. {
  38841. if (font != newFont)
  38842. {
  38843. font = newFont;
  38844. for (int i = atoms.size(); --i >= 0;)
  38845. {
  38846. TextAtom* const atom = (TextAtom*) atoms.getUnchecked(i);
  38847. atom->width = newFont.getStringWidthFloat (atom->getText (passwordCharacter));
  38848. }
  38849. }
  38850. }
  38851. juce_UseDebuggingNewOperator
  38852. Font font;
  38853. Colour colour;
  38854. private:
  38855. VoidArray atoms;
  38856. void initialiseAtoms (const String& textToParse,
  38857. const tchar passwordCharacter) throw()
  38858. {
  38859. int i = 0;
  38860. const int len = textToParse.length();
  38861. const tchar* const text = (const tchar*) textToParse;
  38862. while (i < len)
  38863. {
  38864. int start = i;
  38865. // create a whitespace atom unless it starts with non-ws
  38866. if (CharacterFunctions::isWhitespace (text[i])
  38867. && text[i] != T('\r')
  38868. && text[i] != T('\n'))
  38869. {
  38870. while (i < len
  38871. && CharacterFunctions::isWhitespace (text[i])
  38872. && text[i] != T('\r')
  38873. && text[i] != T('\n'))
  38874. {
  38875. ++i;
  38876. }
  38877. }
  38878. else
  38879. {
  38880. if (text[i] == T('\r'))
  38881. {
  38882. ++i;
  38883. if ((i < len) && (text[i] == T('\n')))
  38884. {
  38885. ++start;
  38886. ++i;
  38887. }
  38888. }
  38889. else if (text[i] == T('\n'))
  38890. {
  38891. ++i;
  38892. }
  38893. else
  38894. {
  38895. while ((i < len) && ! CharacterFunctions::isWhitespace (text[i]))
  38896. ++i;
  38897. }
  38898. }
  38899. TextAtom* const atom = new TextAtom();
  38900. atom->atomText = String (text + start, i - start);
  38901. atom->width = font.getStringWidthFloat (atom->getText (passwordCharacter));
  38902. atom->numChars = (uint16) (i - start);
  38903. atoms.add (atom);
  38904. }
  38905. }
  38906. const UniformTextSection& operator= (const UniformTextSection& other);
  38907. };
  38908. class TextEditorIterator
  38909. {
  38910. public:
  38911. TextEditorIterator (const VoidArray& sections_,
  38912. const float wordWrapWidth_,
  38913. const tchar passwordCharacter_) throw()
  38914. : indexInText (0),
  38915. lineY (0),
  38916. lineHeight (0),
  38917. maxDescent (0),
  38918. atomX (0),
  38919. atomRight (0),
  38920. atom (0),
  38921. currentSection (0),
  38922. sections (sections_),
  38923. sectionIndex (0),
  38924. atomIndex (0),
  38925. wordWrapWidth (wordWrapWidth_),
  38926. passwordCharacter (passwordCharacter_)
  38927. {
  38928. jassert (wordWrapWidth_ > 0);
  38929. if (sections.size() > 0)
  38930. currentSection = (const UniformTextSection*) sections.getUnchecked (sectionIndex);
  38931. if (currentSection != 0)
  38932. {
  38933. lineHeight = currentSection->font.getHeight();
  38934. maxDescent = currentSection->font.getDescent();
  38935. }
  38936. }
  38937. TextEditorIterator (const TextEditorIterator& other) throw()
  38938. : indexInText (other.indexInText),
  38939. lineY (other.lineY),
  38940. lineHeight (other.lineHeight),
  38941. maxDescent (other.maxDescent),
  38942. atomX (other.atomX),
  38943. atomRight (other.atomRight),
  38944. atom (other.atom),
  38945. currentSection (other.currentSection),
  38946. sections (other.sections),
  38947. sectionIndex (other.sectionIndex),
  38948. atomIndex (other.atomIndex),
  38949. wordWrapWidth (other.wordWrapWidth),
  38950. passwordCharacter (other.passwordCharacter),
  38951. tempAtom (other.tempAtom)
  38952. {
  38953. }
  38954. ~TextEditorIterator() throw()
  38955. {
  38956. }
  38957. bool next() throw()
  38958. {
  38959. if (atom == &tempAtom)
  38960. {
  38961. const int numRemaining = tempAtom.atomText.length() - tempAtom.numChars;
  38962. if (numRemaining > 0)
  38963. {
  38964. tempAtom.atomText = tempAtom.atomText.substring (tempAtom.numChars);
  38965. atomX = 0;
  38966. if (tempAtom.numChars > 0)
  38967. lineY += lineHeight;
  38968. indexInText += tempAtom.numChars;
  38969. GlyphArrangement g;
  38970. g.addLineOfText (currentSection->font, atom->getText (passwordCharacter), 0.0f, 0.0f);
  38971. int split;
  38972. for (split = 0; split < g.getNumGlyphs(); ++split)
  38973. if (SHOULD_WRAP (g.getGlyph (split).getRight(), wordWrapWidth))
  38974. break;
  38975. if (split > 0 && split <= numRemaining)
  38976. {
  38977. tempAtom.numChars = (uint16) split;
  38978. tempAtom.width = g.getGlyph (split - 1).getRight();
  38979. atomRight = atomX + tempAtom.width;
  38980. return true;
  38981. }
  38982. }
  38983. }
  38984. bool forceNewLine = false;
  38985. if (sectionIndex >= sections.size())
  38986. {
  38987. moveToEndOfLastAtom();
  38988. return false;
  38989. }
  38990. else if (atomIndex >= currentSection->getNumAtoms() - 1)
  38991. {
  38992. if (atomIndex >= currentSection->getNumAtoms())
  38993. {
  38994. if (++sectionIndex >= sections.size())
  38995. {
  38996. moveToEndOfLastAtom();
  38997. return false;
  38998. }
  38999. atomIndex = 0;
  39000. currentSection = (const UniformTextSection*) sections.getUnchecked (sectionIndex);
  39001. lineHeight = jmax (lineHeight, currentSection->font.getHeight());
  39002. maxDescent = jmax (maxDescent, currentSection->font.getDescent());
  39003. }
  39004. else
  39005. {
  39006. const TextAtom* const lastAtom = currentSection->getAtom (atomIndex);
  39007. if (! lastAtom->isWhitespace())
  39008. {
  39009. // handle the case where the last atom in a section is actually part of the same
  39010. // word as the first atom of the next section...
  39011. float right = atomRight + lastAtom->width;
  39012. float lineHeight2 = lineHeight;
  39013. float maxDescent2 = maxDescent;
  39014. for (int section = sectionIndex + 1; section < sections.size(); ++section)
  39015. {
  39016. const UniformTextSection* const s = (const UniformTextSection*) sections.getUnchecked (section);
  39017. if (s->getNumAtoms() == 0)
  39018. break;
  39019. const TextAtom* const nextAtom = s->getAtom (0);
  39020. if (nextAtom->isWhitespace())
  39021. break;
  39022. right += nextAtom->width;
  39023. lineHeight2 = jmax (lineHeight2, s->font.getHeight());
  39024. maxDescent2 = jmax (maxDescent2, s->font.getDescent());
  39025. if (SHOULD_WRAP (right, wordWrapWidth))
  39026. {
  39027. lineHeight = lineHeight2;
  39028. maxDescent = maxDescent2;
  39029. forceNewLine = true;
  39030. break;
  39031. }
  39032. if (s->getNumAtoms() > 1)
  39033. break;
  39034. }
  39035. }
  39036. }
  39037. }
  39038. if (atom != 0)
  39039. {
  39040. atomX = atomRight;
  39041. indexInText += atom->numChars;
  39042. if (atom->isNewLine())
  39043. {
  39044. atomX = 0;
  39045. lineY += lineHeight;
  39046. }
  39047. }
  39048. atom = currentSection->getAtom (atomIndex);
  39049. atomRight = atomX + atom->width;
  39050. ++atomIndex;
  39051. if (SHOULD_WRAP (atomRight, wordWrapWidth) || forceNewLine)
  39052. {
  39053. if (atom->isWhitespace())
  39054. {
  39055. // leave whitespace at the end of a line, but truncate it to avoid scrolling
  39056. atomRight = jmin (atomRight, wordWrapWidth);
  39057. }
  39058. else
  39059. {
  39060. return wrapCurrentAtom();
  39061. }
  39062. }
  39063. return true;
  39064. }
  39065. bool wrapCurrentAtom() throw()
  39066. {
  39067. atomRight = atom->width;
  39068. if (SHOULD_WRAP (atomRight, wordWrapWidth)) // atom too big to fit on a line, so break it up..
  39069. {
  39070. tempAtom = *atom;
  39071. tempAtom.width = 0;
  39072. tempAtom.numChars = 0;
  39073. atom = &tempAtom;
  39074. if (atomX > 0)
  39075. {
  39076. atomX = 0;
  39077. lineY += lineHeight;
  39078. }
  39079. return next();
  39080. }
  39081. atomX = 0;
  39082. lineY += lineHeight;
  39083. return true;
  39084. }
  39085. void draw (Graphics& g, const UniformTextSection*& lastSection) const throw()
  39086. {
  39087. if (passwordCharacter != 0 || ! atom->isWhitespace())
  39088. {
  39089. if (lastSection != currentSection)
  39090. {
  39091. lastSection = currentSection;
  39092. g.setColour (currentSection->colour);
  39093. g.setFont (currentSection->font);
  39094. }
  39095. jassert (atom->getTrimmedText (passwordCharacter).isNotEmpty());
  39096. GlyphArrangement ga;
  39097. ga.addLineOfText (currentSection->font,
  39098. atom->getTrimmedText (passwordCharacter),
  39099. atomX,
  39100. (float) roundFloatToInt (lineY + lineHeight - maxDescent));
  39101. ga.draw (g);
  39102. }
  39103. }
  39104. void drawSelection (Graphics& g,
  39105. const int selectionStart,
  39106. const int selectionEnd) const throw()
  39107. {
  39108. const int startX = roundFloatToInt (indexToX (selectionStart));
  39109. const int endX = roundFloatToInt (indexToX (selectionEnd));
  39110. const int y = roundFloatToInt (lineY);
  39111. const int nextY = roundFloatToInt (lineY + lineHeight);
  39112. g.fillRect (startX, y, endX - startX, nextY - y);
  39113. }
  39114. void drawSelectedText (Graphics& g,
  39115. const int selectionStart,
  39116. const int selectionEnd,
  39117. const Colour& selectedTextColour) const throw()
  39118. {
  39119. if (passwordCharacter != 0 || ! atom->isWhitespace())
  39120. {
  39121. GlyphArrangement ga;
  39122. ga.addLineOfText (currentSection->font,
  39123. atom->getTrimmedText (passwordCharacter),
  39124. atomX,
  39125. (float) roundFloatToInt (lineY + lineHeight - maxDescent));
  39126. if (selectionEnd < indexInText + atom->numChars)
  39127. {
  39128. GlyphArrangement ga2 (ga);
  39129. ga2.removeRangeOfGlyphs (0, selectionEnd - indexInText);
  39130. ga.removeRangeOfGlyphs (selectionEnd - indexInText, -1);
  39131. g.setColour (currentSection->colour);
  39132. ga2.draw (g);
  39133. }
  39134. if (selectionStart > indexInText)
  39135. {
  39136. GlyphArrangement ga2 (ga);
  39137. ga2.removeRangeOfGlyphs (selectionStart - indexInText, -1);
  39138. ga.removeRangeOfGlyphs (0, selectionStart - indexInText);
  39139. g.setColour (currentSection->colour);
  39140. ga2.draw (g);
  39141. }
  39142. g.setColour (selectedTextColour);
  39143. ga.draw (g);
  39144. }
  39145. }
  39146. float indexToX (const int indexToFind) const throw()
  39147. {
  39148. if (indexToFind <= indexInText)
  39149. return atomX;
  39150. if (indexToFind >= indexInText + atom->numChars)
  39151. return atomRight;
  39152. GlyphArrangement g;
  39153. g.addLineOfText (currentSection->font,
  39154. atom->getText (passwordCharacter),
  39155. atomX, 0.0f);
  39156. return jmin (atomRight, g.getGlyph (indexToFind - indexInText).getLeft());
  39157. }
  39158. int xToIndex (const float xToFind) const throw()
  39159. {
  39160. if (xToFind <= atomX || atom->isNewLine())
  39161. return indexInText;
  39162. if (xToFind >= atomRight)
  39163. return indexInText + atom->numChars;
  39164. GlyphArrangement g;
  39165. g.addLineOfText (currentSection->font,
  39166. atom->getText (passwordCharacter),
  39167. atomX, 0.0f);
  39168. int j;
  39169. for (j = 0; j < atom->numChars; ++j)
  39170. if ((g.getGlyph(j).getLeft() + g.getGlyph(j).getRight()) / 2 > xToFind)
  39171. break;
  39172. return indexInText + j;
  39173. }
  39174. void updateLineHeight() throw()
  39175. {
  39176. float x = atomRight;
  39177. int tempSectionIndex = sectionIndex;
  39178. int tempAtomIndex = atomIndex;
  39179. const UniformTextSection* currentSection = (const UniformTextSection*) sections.getUnchecked (tempSectionIndex);
  39180. while (! SHOULD_WRAP (x, wordWrapWidth))
  39181. {
  39182. if (tempSectionIndex >= sections.size())
  39183. break;
  39184. bool checkSize = false;
  39185. if (tempAtomIndex >= currentSection->getNumAtoms())
  39186. {
  39187. if (++tempSectionIndex >= sections.size())
  39188. break;
  39189. tempAtomIndex = 0;
  39190. currentSection = (const UniformTextSection*) sections.getUnchecked (tempSectionIndex);
  39191. checkSize = true;
  39192. }
  39193. const TextAtom* const atom = currentSection->getAtom (tempAtomIndex);
  39194. if (atom == 0)
  39195. break;
  39196. x += atom->width;
  39197. if (SHOULD_WRAP (x, wordWrapWidth) || atom->isNewLine())
  39198. break;
  39199. if (checkSize)
  39200. {
  39201. lineHeight = jmax (lineHeight, currentSection->font.getHeight());
  39202. maxDescent = jmax (maxDescent, currentSection->font.getDescent());
  39203. }
  39204. ++tempAtomIndex;
  39205. }
  39206. }
  39207. bool getCharPosition (const int index, float& cx, float& cy, float& lineHeight_) throw()
  39208. {
  39209. while (next())
  39210. {
  39211. if (indexInText + atom->numChars >= index)
  39212. {
  39213. updateLineHeight();
  39214. if (indexInText + atom->numChars > index)
  39215. {
  39216. cx = indexToX (index);
  39217. cy = lineY;
  39218. lineHeight_ = lineHeight;
  39219. return true;
  39220. }
  39221. }
  39222. }
  39223. cx = atomX;
  39224. cy = lineY;
  39225. lineHeight_ = lineHeight;
  39226. return false;
  39227. }
  39228. juce_UseDebuggingNewOperator
  39229. int indexInText;
  39230. float lineY, lineHeight, maxDescent;
  39231. float atomX, atomRight;
  39232. const TextAtom* atom;
  39233. const UniformTextSection* currentSection;
  39234. private:
  39235. const VoidArray& sections;
  39236. int sectionIndex, atomIndex;
  39237. const float wordWrapWidth;
  39238. const tchar passwordCharacter;
  39239. TextAtom tempAtom;
  39240. const TextEditorIterator& operator= (const TextEditorIterator&);
  39241. void moveToEndOfLastAtom() throw()
  39242. {
  39243. if (atom != 0)
  39244. {
  39245. atomX = atomRight;
  39246. if (atom->isNewLine())
  39247. {
  39248. atomX = 0.0f;
  39249. lineY += lineHeight;
  39250. }
  39251. }
  39252. }
  39253. };
  39254. class TextEditorInsertAction : public UndoableAction
  39255. {
  39256. TextEditor& owner;
  39257. const String text;
  39258. const int insertIndex, oldCaretPos, newCaretPos;
  39259. const Font font;
  39260. const Colour colour;
  39261. TextEditorInsertAction (const TextEditorInsertAction&);
  39262. const TextEditorInsertAction& operator= (const TextEditorInsertAction&);
  39263. public:
  39264. TextEditorInsertAction (TextEditor& owner_,
  39265. const String& text_,
  39266. const int insertIndex_,
  39267. const Font& font_,
  39268. const Colour& colour_,
  39269. const int oldCaretPos_,
  39270. const int newCaretPos_) throw()
  39271. : owner (owner_),
  39272. text (text_),
  39273. insertIndex (insertIndex_),
  39274. oldCaretPos (oldCaretPos_),
  39275. newCaretPos (newCaretPos_),
  39276. font (font_),
  39277. colour (colour_)
  39278. {
  39279. }
  39280. ~TextEditorInsertAction()
  39281. {
  39282. }
  39283. bool perform()
  39284. {
  39285. owner.insert (text, insertIndex, font, colour, 0, newCaretPos);
  39286. return true;
  39287. }
  39288. bool undo()
  39289. {
  39290. owner.remove (insertIndex, insertIndex + text.length(), 0, oldCaretPos);
  39291. return true;
  39292. }
  39293. int getSizeInUnits()
  39294. {
  39295. return text.length() + 16;
  39296. }
  39297. };
  39298. class TextEditorRemoveAction : public UndoableAction
  39299. {
  39300. TextEditor& owner;
  39301. const int startIndex, endIndex, oldCaretPos, newCaretPos;
  39302. VoidArray removedSections;
  39303. TextEditorRemoveAction (const TextEditorRemoveAction&);
  39304. const TextEditorRemoveAction& operator= (const TextEditorRemoveAction&);
  39305. public:
  39306. TextEditorRemoveAction (TextEditor& owner_,
  39307. const int startIndex_,
  39308. const int endIndex_,
  39309. const int oldCaretPos_,
  39310. const int newCaretPos_,
  39311. const VoidArray& removedSections_) throw()
  39312. : owner (owner_),
  39313. startIndex (startIndex_),
  39314. endIndex (endIndex_),
  39315. oldCaretPos (oldCaretPos_),
  39316. newCaretPos (newCaretPos_),
  39317. removedSections (removedSections_)
  39318. {
  39319. }
  39320. ~TextEditorRemoveAction()
  39321. {
  39322. for (int i = removedSections.size(); --i >= 0;)
  39323. {
  39324. UniformTextSection* const section = (UniformTextSection*) removedSections.getUnchecked (i);
  39325. section->clear();
  39326. delete section;
  39327. }
  39328. }
  39329. bool perform()
  39330. {
  39331. owner.remove (startIndex, endIndex, 0, newCaretPos);
  39332. return true;
  39333. }
  39334. bool undo()
  39335. {
  39336. owner.reinsert (startIndex, removedSections);
  39337. owner.moveCursorTo (oldCaretPos, false);
  39338. return true;
  39339. }
  39340. int getSizeInUnits()
  39341. {
  39342. int n = 0;
  39343. for (int i = removedSections.size(); --i >= 0;)
  39344. {
  39345. UniformTextSection* const section = (UniformTextSection*) removedSections.getUnchecked (i);
  39346. n += section->getTotalLength();
  39347. }
  39348. return n + 16;
  39349. }
  39350. };
  39351. class TextHolderComponent : public Component,
  39352. public Timer
  39353. {
  39354. TextEditor* const owner;
  39355. TextHolderComponent (const TextHolderComponent&);
  39356. const TextHolderComponent& operator= (const TextHolderComponent&);
  39357. public:
  39358. TextHolderComponent (TextEditor* const owner_)
  39359. : owner (owner_)
  39360. {
  39361. setWantsKeyboardFocus (false);
  39362. setInterceptsMouseClicks (false, true);
  39363. }
  39364. ~TextHolderComponent()
  39365. {
  39366. }
  39367. void paint (Graphics& g)
  39368. {
  39369. owner->drawContent (g);
  39370. }
  39371. void timerCallback()
  39372. {
  39373. owner->timerCallbackInt();
  39374. }
  39375. const MouseCursor getMouseCursor()
  39376. {
  39377. return owner->getMouseCursor();
  39378. }
  39379. };
  39380. class TextEditorViewport : public Viewport
  39381. {
  39382. TextEditor* const owner;
  39383. float lastWordWrapWidth;
  39384. TextEditorViewport (const TextEditorViewport&);
  39385. const TextEditorViewport& operator= (const TextEditorViewport&);
  39386. public:
  39387. TextEditorViewport (TextEditor* const owner_)
  39388. : owner (owner_),
  39389. lastWordWrapWidth (0)
  39390. {
  39391. }
  39392. ~TextEditorViewport()
  39393. {
  39394. }
  39395. void visibleAreaChanged (int, int, int, int)
  39396. {
  39397. const float wordWrapWidth = owner->getWordWrapWidth();
  39398. if (wordWrapWidth != lastWordWrapWidth)
  39399. {
  39400. lastWordWrapWidth = wordWrapWidth;
  39401. owner->updateTextHolderSize();
  39402. }
  39403. }
  39404. };
  39405. const int flashSpeedIntervalMs = 380;
  39406. const int textChangeMessageId = 0x10003001;
  39407. const int returnKeyMessageId = 0x10003002;
  39408. const int escapeKeyMessageId = 0x10003003;
  39409. const int focusLossMessageId = 0x10003004;
  39410. TextEditor::TextEditor (const String& name,
  39411. const tchar passwordCharacter_)
  39412. : Component (name),
  39413. borderSize (1, 1, 1, 3),
  39414. readOnly (false),
  39415. multiline (false),
  39416. wordWrap (false),
  39417. returnKeyStartsNewLine (false),
  39418. caretVisible (true),
  39419. popupMenuEnabled (true),
  39420. selectAllTextWhenFocused (false),
  39421. scrollbarVisible (true),
  39422. wasFocused (false),
  39423. caretFlashState (true),
  39424. keepCursorOnScreen (true),
  39425. tabKeyUsed (false),
  39426. menuActive (false),
  39427. cursorX (0),
  39428. cursorY (0),
  39429. cursorHeight (0),
  39430. maxTextLength (0),
  39431. selectionStart (0),
  39432. selectionEnd (0),
  39433. leftIndent (4),
  39434. topIndent (4),
  39435. lastTransactionTime (0),
  39436. currentFont (14.0f),
  39437. totalNumChars (0),
  39438. caretPosition (0),
  39439. sections (8),
  39440. passwordCharacter (passwordCharacter_),
  39441. dragType (notDragging),
  39442. listeners (2)
  39443. {
  39444. setOpaque (true);
  39445. addAndMakeVisible (viewport = new TextEditorViewport (this));
  39446. viewport->setViewedComponent (textHolder = new TextHolderComponent (this));
  39447. viewport->setWantsKeyboardFocus (false);
  39448. viewport->setScrollBarsShown (false, false);
  39449. setMouseCursor (MouseCursor::IBeamCursor);
  39450. setWantsKeyboardFocus (true);
  39451. }
  39452. TextEditor::~TextEditor()
  39453. {
  39454. clearInternal (0);
  39455. delete viewport;
  39456. }
  39457. void TextEditor::newTransaction() throw()
  39458. {
  39459. lastTransactionTime = Time::getApproximateMillisecondCounter();
  39460. undoManager.beginNewTransaction();
  39461. }
  39462. void TextEditor::doUndoRedo (const bool isRedo)
  39463. {
  39464. if (! isReadOnly())
  39465. {
  39466. if ((isRedo) ? undoManager.redo()
  39467. : undoManager.undo())
  39468. {
  39469. scrollToMakeSureCursorIsVisible();
  39470. repaint();
  39471. textChanged();
  39472. }
  39473. }
  39474. }
  39475. void TextEditor::setMultiLine (const bool shouldBeMultiLine,
  39476. const bool shouldWordWrap)
  39477. {
  39478. multiline = shouldBeMultiLine;
  39479. wordWrap = shouldWordWrap && shouldBeMultiLine;
  39480. setScrollbarsShown (scrollbarVisible);
  39481. viewport->setViewPosition (0, 0);
  39482. resized();
  39483. scrollToMakeSureCursorIsVisible();
  39484. }
  39485. bool TextEditor::isMultiLine() const throw()
  39486. {
  39487. return multiline;
  39488. }
  39489. void TextEditor::setScrollbarsShown (bool enabled) throw()
  39490. {
  39491. scrollbarVisible = enabled;
  39492. enabled = enabled && isMultiLine();
  39493. viewport->setScrollBarsShown (enabled, enabled);
  39494. }
  39495. void TextEditor::setReadOnly (const bool shouldBeReadOnly)
  39496. {
  39497. readOnly = shouldBeReadOnly;
  39498. enablementChanged();
  39499. }
  39500. bool TextEditor::isReadOnly() const throw()
  39501. {
  39502. return readOnly || ! isEnabled();
  39503. }
  39504. void TextEditor::setReturnKeyStartsNewLine (const bool shouldStartNewLine)
  39505. {
  39506. returnKeyStartsNewLine = shouldStartNewLine;
  39507. }
  39508. void TextEditor::setTabKeyUsedAsCharacter (const bool shouldTabKeyBeUsed) throw()
  39509. {
  39510. tabKeyUsed = shouldTabKeyBeUsed;
  39511. }
  39512. void TextEditor::setPopupMenuEnabled (const bool b) throw()
  39513. {
  39514. popupMenuEnabled = b;
  39515. }
  39516. void TextEditor::setSelectAllWhenFocused (const bool b) throw()
  39517. {
  39518. selectAllTextWhenFocused = b;
  39519. }
  39520. const Font TextEditor::getFont() const throw()
  39521. {
  39522. return currentFont;
  39523. }
  39524. void TextEditor::setFont (const Font& newFont) throw()
  39525. {
  39526. currentFont = newFont;
  39527. scrollToMakeSureCursorIsVisible();
  39528. }
  39529. void TextEditor::applyFontToAllText (const Font& newFont)
  39530. {
  39531. currentFont = newFont;
  39532. const Colour overallColour (findColour (textColourId));
  39533. for (int i = sections.size(); --i >= 0;)
  39534. {
  39535. UniformTextSection* const uts = (UniformTextSection*) sections.getUnchecked(i);
  39536. uts->setFont (newFont, passwordCharacter);
  39537. uts->colour = overallColour;
  39538. }
  39539. coalesceSimilarSections();
  39540. updateTextHolderSize();
  39541. scrollToMakeSureCursorIsVisible();
  39542. repaint();
  39543. }
  39544. void TextEditor::colourChanged()
  39545. {
  39546. setOpaque (findColour (backgroundColourId).isOpaque());
  39547. repaint();
  39548. }
  39549. void TextEditor::setCaretVisible (const bool shouldCaretBeVisible) throw()
  39550. {
  39551. caretVisible = shouldCaretBeVisible;
  39552. if (shouldCaretBeVisible)
  39553. textHolder->startTimer (flashSpeedIntervalMs);
  39554. setMouseCursor (shouldCaretBeVisible ? MouseCursor::IBeamCursor
  39555. : MouseCursor::NormalCursor);
  39556. }
  39557. void TextEditor::setInputRestrictions (const int maxLen,
  39558. const String& chars) throw()
  39559. {
  39560. maxTextLength = jmax (0, maxLen);
  39561. allowedCharacters = chars;
  39562. }
  39563. void TextEditor::setTextToShowWhenEmpty (const String& text, const Colour& colourToUse) throw()
  39564. {
  39565. textToShowWhenEmpty = text;
  39566. colourForTextWhenEmpty = colourToUse;
  39567. }
  39568. void TextEditor::setPasswordCharacter (const tchar newPasswordCharacter) throw()
  39569. {
  39570. if (passwordCharacter != newPasswordCharacter)
  39571. {
  39572. passwordCharacter = newPasswordCharacter;
  39573. resized();
  39574. repaint();
  39575. }
  39576. }
  39577. void TextEditor::setScrollBarThickness (const int newThicknessPixels)
  39578. {
  39579. viewport->setScrollBarThickness (newThicknessPixels);
  39580. }
  39581. void TextEditor::setScrollBarButtonVisibility (const bool buttonsVisible)
  39582. {
  39583. viewport->setScrollBarButtonVisibility (buttonsVisible);
  39584. }
  39585. void TextEditor::clear()
  39586. {
  39587. clearInternal (0);
  39588. updateTextHolderSize();
  39589. undoManager.clearUndoHistory();
  39590. }
  39591. void TextEditor::setText (const String& newText,
  39592. const bool sendTextChangeMessage)
  39593. {
  39594. const int newLength = newText.length();
  39595. if (newLength != getTotalNumChars() || getText() != newText)
  39596. {
  39597. const int oldCursorPos = caretPosition;
  39598. const bool cursorWasAtEnd = oldCursorPos >= getTotalNumChars();
  39599. clearInternal (0);
  39600. insert (newText, 0, currentFont, findColour (textColourId), 0, caretPosition);
  39601. // if you're adding text with line-feeds to a single-line text editor, it
  39602. // ain't gonna look right!
  39603. jassert (multiline || ! newText.containsAnyOf (T("\r\n")));
  39604. if (cursorWasAtEnd && ! isMultiLine())
  39605. moveCursorTo (getTotalNumChars(), false);
  39606. else
  39607. moveCursorTo (oldCursorPos, false);
  39608. if (sendTextChangeMessage)
  39609. textChanged();
  39610. repaint();
  39611. }
  39612. updateTextHolderSize();
  39613. scrollToMakeSureCursorIsVisible();
  39614. undoManager.clearUndoHistory();
  39615. }
  39616. void TextEditor::textChanged() throw()
  39617. {
  39618. updateTextHolderSize();
  39619. postCommandMessage (textChangeMessageId);
  39620. }
  39621. void TextEditor::returnPressed()
  39622. {
  39623. postCommandMessage (returnKeyMessageId);
  39624. }
  39625. void TextEditor::escapePressed()
  39626. {
  39627. postCommandMessage (escapeKeyMessageId);
  39628. }
  39629. void TextEditor::addListener (TextEditorListener* const newListener) throw()
  39630. {
  39631. jassert (newListener != 0)
  39632. if (newListener != 0)
  39633. listeners.add (newListener);
  39634. }
  39635. void TextEditor::removeListener (TextEditorListener* const listenerToRemove) throw()
  39636. {
  39637. listeners.removeValue (listenerToRemove);
  39638. }
  39639. void TextEditor::timerCallbackInt()
  39640. {
  39641. const bool newState = (! caretFlashState) && ! isCurrentlyBlockedByAnotherModalComponent();
  39642. if (caretFlashState != newState)
  39643. {
  39644. caretFlashState = newState;
  39645. if (caretFlashState)
  39646. wasFocused = true;
  39647. if (caretVisible
  39648. && hasKeyboardFocus (false)
  39649. && ! isReadOnly())
  39650. {
  39651. repaintCaret();
  39652. }
  39653. }
  39654. const unsigned int now = Time::getApproximateMillisecondCounter();
  39655. if (now > lastTransactionTime + 200)
  39656. newTransaction();
  39657. }
  39658. void TextEditor::repaintCaret()
  39659. {
  39660. if (! findColour (caretColourId).isTransparent())
  39661. repaint (borderSize.getLeft() + textHolder->getX() + leftIndent + roundFloatToInt (cursorX) - 1,
  39662. borderSize.getTop() + textHolder->getY() + topIndent + roundFloatToInt (cursorY) - 1,
  39663. 4,
  39664. roundFloatToInt (cursorHeight) + 2);
  39665. }
  39666. void TextEditor::repaintText (int textStartIndex, int textEndIndex)
  39667. {
  39668. if (textStartIndex > textEndIndex && textEndIndex > 0)
  39669. swapVariables (textStartIndex, textEndIndex);
  39670. float x = 0, y = 0, lh = currentFont.getHeight();
  39671. const float wordWrapWidth = getWordWrapWidth();
  39672. if (wordWrapWidth > 0)
  39673. {
  39674. TextEditorIterator i (sections, wordWrapWidth, passwordCharacter);
  39675. i.getCharPosition (textStartIndex, x, y, lh);
  39676. const int y1 = (int) y;
  39677. int y2;
  39678. if (textEndIndex >= 0)
  39679. {
  39680. i.getCharPosition (textEndIndex, x, y, lh);
  39681. y2 = (int) (y + lh * 2.0f);
  39682. }
  39683. else
  39684. {
  39685. y2 = textHolder->getHeight();
  39686. }
  39687. textHolder->repaint (0, y1, textHolder->getWidth(), y2 - y1);
  39688. }
  39689. }
  39690. void TextEditor::moveCaret (int newCaretPos) throw()
  39691. {
  39692. if (newCaretPos < 0)
  39693. newCaretPos = 0;
  39694. else if (newCaretPos > getTotalNumChars())
  39695. newCaretPos = getTotalNumChars();
  39696. if (newCaretPos != getCaretPosition())
  39697. {
  39698. repaintCaret();
  39699. caretFlashState = true;
  39700. caretPosition = newCaretPos;
  39701. textHolder->startTimer (flashSpeedIntervalMs);
  39702. scrollToMakeSureCursorIsVisible();
  39703. repaintCaret();
  39704. }
  39705. }
  39706. void TextEditor::setCaretPosition (const int newIndex) throw()
  39707. {
  39708. moveCursorTo (newIndex, false);
  39709. }
  39710. int TextEditor::getCaretPosition() const throw()
  39711. {
  39712. return caretPosition;
  39713. }
  39714. void TextEditor::scrollEditorToPositionCaret (const int desiredCaretX,
  39715. const int desiredCaretY) throw()
  39716. {
  39717. updateCaretPosition();
  39718. int vx = roundFloatToInt (cursorX) - desiredCaretX;
  39719. int vy = roundFloatToInt (cursorY) - desiredCaretY;
  39720. if (desiredCaretX < jmax (1, proportionOfWidth (0.05f)))
  39721. {
  39722. vx += desiredCaretX - proportionOfWidth (0.2f);
  39723. }
  39724. else if (desiredCaretX > jmax (0, viewport->getMaximumVisibleWidth() - (wordWrap ? 2 : 10)))
  39725. {
  39726. vx += desiredCaretX + (isMultiLine() ? proportionOfWidth (0.2f) : 10) - viewport->getMaximumVisibleWidth();
  39727. }
  39728. vx = jlimit (0, jmax (0, textHolder->getWidth() + 8 - viewport->getMaximumVisibleWidth()), vx);
  39729. if (! isMultiLine())
  39730. {
  39731. vy = viewport->getViewPositionY();
  39732. }
  39733. else
  39734. {
  39735. vy = jlimit (0, jmax (0, textHolder->getHeight() - viewport->getMaximumVisibleHeight()), vy);
  39736. const int curH = roundFloatToInt (cursorHeight);
  39737. if (desiredCaretY < 0)
  39738. {
  39739. vy = jmax (0, desiredCaretY + vy);
  39740. }
  39741. else if (desiredCaretY > jmax (0, viewport->getMaximumVisibleHeight() - topIndent - curH))
  39742. {
  39743. vy += desiredCaretY + 2 + curH + topIndent - viewport->getMaximumVisibleHeight();
  39744. }
  39745. }
  39746. viewport->setViewPosition (vx, vy);
  39747. }
  39748. const Rectangle TextEditor::getCaretRectangle() throw()
  39749. {
  39750. updateCaretPosition();
  39751. return Rectangle (roundFloatToInt (cursorX) - viewport->getX(),
  39752. roundFloatToInt (cursorY) - viewport->getY(),
  39753. 1, roundFloatToInt (cursorHeight));
  39754. }
  39755. float TextEditor::getWordWrapWidth() const throw()
  39756. {
  39757. return (wordWrap) ? (float) (viewport->getMaximumVisibleWidth() - leftIndent - leftIndent / 2)
  39758. : 1.0e10f;
  39759. }
  39760. void TextEditor::updateTextHolderSize() throw()
  39761. {
  39762. const float wordWrapWidth = getWordWrapWidth();
  39763. if (wordWrapWidth > 0)
  39764. {
  39765. float maxWidth = 0.0f;
  39766. TextEditorIterator i (sections, wordWrapWidth, passwordCharacter);
  39767. while (i.next())
  39768. maxWidth = jmax (maxWidth, i.atomRight);
  39769. const int w = leftIndent + roundFloatToInt (maxWidth);
  39770. const int h = topIndent + roundFloatToInt (jmax (i.lineY + i.lineHeight,
  39771. currentFont.getHeight()));
  39772. textHolder->setSize (w + 1, h + 1);
  39773. }
  39774. }
  39775. int TextEditor::getTextWidth() const throw()
  39776. {
  39777. return textHolder->getWidth();
  39778. }
  39779. int TextEditor::getTextHeight() const throw()
  39780. {
  39781. return textHolder->getHeight();
  39782. }
  39783. void TextEditor::setIndents (const int newLeftIndent,
  39784. const int newTopIndent) throw()
  39785. {
  39786. leftIndent = newLeftIndent;
  39787. topIndent = newTopIndent;
  39788. }
  39789. void TextEditor::setBorder (const BorderSize& border) throw()
  39790. {
  39791. borderSize = border;
  39792. resized();
  39793. }
  39794. const BorderSize TextEditor::getBorder() const throw()
  39795. {
  39796. return borderSize;
  39797. }
  39798. void TextEditor::setScrollToShowCursor (const bool shouldScrollToShowCursor) throw()
  39799. {
  39800. keepCursorOnScreen = shouldScrollToShowCursor;
  39801. }
  39802. void TextEditor::updateCaretPosition() throw()
  39803. {
  39804. cursorHeight = currentFont.getHeight(); // (in case the text is empty and the call below doesn't set this value)
  39805. getCharPosition (caretPosition, cursorX, cursorY, cursorHeight);
  39806. }
  39807. void TextEditor::scrollToMakeSureCursorIsVisible() throw()
  39808. {
  39809. updateCaretPosition();
  39810. if (keepCursorOnScreen)
  39811. {
  39812. int x = viewport->getViewPositionX();
  39813. int y = viewport->getViewPositionY();
  39814. const int relativeCursorX = roundFloatToInt (cursorX) - x;
  39815. const int relativeCursorY = roundFloatToInt (cursorY) - y;
  39816. if (relativeCursorX < jmax (1, proportionOfWidth (0.05f)))
  39817. {
  39818. x += relativeCursorX - proportionOfWidth (0.2f);
  39819. }
  39820. else if (relativeCursorX > jmax (0, viewport->getMaximumVisibleWidth() - (wordWrap ? 2 : 10)))
  39821. {
  39822. x += relativeCursorX + (isMultiLine() ? proportionOfWidth (0.2f) : 10) - viewport->getMaximumVisibleWidth();
  39823. }
  39824. x = jlimit (0, jmax (0, textHolder->getWidth() + 8 - viewport->getMaximumVisibleWidth()), x);
  39825. if (! isMultiLine())
  39826. {
  39827. y = (getHeight() - textHolder->getHeight() - topIndent) / -2;
  39828. }
  39829. else
  39830. {
  39831. const int curH = roundFloatToInt (cursorHeight);
  39832. if (relativeCursorY < 0)
  39833. {
  39834. y = jmax (0, relativeCursorY + y);
  39835. }
  39836. else if (relativeCursorY > jmax (0, viewport->getMaximumVisibleHeight() - topIndent - curH))
  39837. {
  39838. y += relativeCursorY + 2 + curH + topIndent - viewport->getMaximumVisibleHeight();
  39839. }
  39840. }
  39841. viewport->setViewPosition (x, y);
  39842. }
  39843. }
  39844. void TextEditor::moveCursorTo (const int newPosition,
  39845. const bool isSelecting) throw()
  39846. {
  39847. if (isSelecting)
  39848. {
  39849. moveCaret (newPosition);
  39850. const int oldSelStart = selectionStart;
  39851. const int oldSelEnd = selectionEnd;
  39852. if (dragType == notDragging)
  39853. {
  39854. if (abs (getCaretPosition() - selectionStart) < abs (getCaretPosition() - selectionEnd))
  39855. dragType = draggingSelectionStart;
  39856. else
  39857. dragType = draggingSelectionEnd;
  39858. }
  39859. if (dragType == draggingSelectionStart)
  39860. {
  39861. selectionStart = getCaretPosition();
  39862. if (selectionEnd < selectionStart)
  39863. {
  39864. swapVariables (selectionStart, selectionEnd);
  39865. dragType = draggingSelectionEnd;
  39866. }
  39867. }
  39868. else
  39869. {
  39870. selectionEnd = getCaretPosition();
  39871. if (selectionEnd < selectionStart)
  39872. {
  39873. swapVariables (selectionStart, selectionEnd);
  39874. dragType = draggingSelectionStart;
  39875. }
  39876. }
  39877. jassert (selectionStart <= selectionEnd);
  39878. jassert (oldSelStart <= oldSelEnd);
  39879. repaintText (jmin (oldSelStart, selectionStart),
  39880. jmax (oldSelEnd, selectionEnd));
  39881. }
  39882. else
  39883. {
  39884. dragType = notDragging;
  39885. if (selectionEnd > selectionStart)
  39886. repaintText (selectionStart, selectionEnd);
  39887. moveCaret (newPosition);
  39888. selectionStart = getCaretPosition();
  39889. selectionEnd = getCaretPosition();
  39890. }
  39891. }
  39892. int TextEditor::getTextIndexAt (const int x,
  39893. const int y) throw()
  39894. {
  39895. return indexAtPosition ((float) (x + viewport->getViewPositionX() - leftIndent),
  39896. (float) (y + viewport->getViewPositionY() - topIndent));
  39897. }
  39898. void TextEditor::insertTextAtCursor (String newText)
  39899. {
  39900. if (allowedCharacters.isNotEmpty())
  39901. newText = newText.retainCharacters (allowedCharacters);
  39902. if (! isMultiLine())
  39903. newText = newText.replaceCharacters (T("\r\n"), T(" "));
  39904. else
  39905. newText = newText.replace (T("\r\n"), T("\n"));
  39906. const int newCaretPos = selectionStart + newText.length();
  39907. const int insertIndex = selectionStart;
  39908. remove (selectionStart, selectionEnd,
  39909. &undoManager,
  39910. newText.isNotEmpty() ? newCaretPos - 1 : newCaretPos);
  39911. if (maxTextLength > 0)
  39912. newText = newText.substring (0, maxTextLength - getTotalNumChars());
  39913. if (newText.isNotEmpty())
  39914. insert (newText,
  39915. insertIndex,
  39916. currentFont,
  39917. findColour (textColourId),
  39918. &undoManager,
  39919. newCaretPos);
  39920. textChanged();
  39921. }
  39922. void TextEditor::setHighlightedRegion (int startPos, int numChars) throw()
  39923. {
  39924. moveCursorTo (startPos, false);
  39925. moveCursorTo (startPos + numChars, true);
  39926. }
  39927. void TextEditor::copy()
  39928. {
  39929. if (passwordCharacter == 0)
  39930. {
  39931. const String selection (getTextSubstring (selectionStart, selectionEnd));
  39932. if (selection.isNotEmpty())
  39933. SystemClipboard::copyTextToClipboard (selection);
  39934. }
  39935. }
  39936. void TextEditor::paste()
  39937. {
  39938. if (! isReadOnly())
  39939. {
  39940. const String clip (SystemClipboard::getTextFromClipboard());
  39941. if (clip.isNotEmpty())
  39942. insertTextAtCursor (clip);
  39943. }
  39944. }
  39945. void TextEditor::cut()
  39946. {
  39947. if (! isReadOnly())
  39948. {
  39949. moveCaret (selectionEnd);
  39950. insertTextAtCursor (String::empty);
  39951. }
  39952. }
  39953. void TextEditor::drawContent (Graphics& g)
  39954. {
  39955. const float wordWrapWidth = getWordWrapWidth();
  39956. if (wordWrapWidth > 0)
  39957. {
  39958. g.setOrigin (leftIndent, topIndent);
  39959. const Rectangle clip (g.getClipBounds());
  39960. Colour selectedTextColour;
  39961. TextEditorIterator i (sections, wordWrapWidth, passwordCharacter);
  39962. while (i.lineY + 200.0 < clip.getY() && i.next())
  39963. {}
  39964. if (selectionStart < selectionEnd)
  39965. {
  39966. g.setColour (findColour (highlightColourId)
  39967. .withMultipliedAlpha (hasKeyboardFocus (true) ? 1.0f : 0.5f));
  39968. selectedTextColour = findColour (highlightedTextColourId);
  39969. TextEditorIterator i2 (i);
  39970. while (i2.next() && i2.lineY < clip.getBottom())
  39971. {
  39972. i2.updateLineHeight();
  39973. if (i2.lineY + i2.lineHeight >= clip.getY()
  39974. && selectionEnd >= i2.indexInText
  39975. && selectionStart <= i2.indexInText + i2.atom->numChars)
  39976. {
  39977. i2.drawSelection (g, selectionStart, selectionEnd);
  39978. }
  39979. }
  39980. }
  39981. const UniformTextSection* lastSection = 0;
  39982. while (i.next() && i.lineY < clip.getBottom())
  39983. {
  39984. i.updateLineHeight();
  39985. if (i.lineY + i.lineHeight >= clip.getY())
  39986. {
  39987. if (selectionEnd >= i.indexInText
  39988. && selectionStart <= i.indexInText + i.atom->numChars)
  39989. {
  39990. i.drawSelectedText (g, selectionStart, selectionEnd, selectedTextColour);
  39991. lastSection = 0;
  39992. }
  39993. else
  39994. {
  39995. i.draw (g, lastSection);
  39996. }
  39997. }
  39998. }
  39999. }
  40000. }
  40001. void TextEditor::paint (Graphics& g)
  40002. {
  40003. getLookAndFeel().fillTextEditorBackground (g, getWidth(), getHeight(), *this);
  40004. }
  40005. void TextEditor::paintOverChildren (Graphics& g)
  40006. {
  40007. if (caretFlashState
  40008. && hasKeyboardFocus (false)
  40009. && caretVisible
  40010. && ! isReadOnly())
  40011. {
  40012. g.setColour (findColour (caretColourId));
  40013. g.fillRect (borderSize.getLeft() + textHolder->getX() + leftIndent + cursorX,
  40014. borderSize.getTop() + textHolder->getY() + topIndent + cursorY,
  40015. 2.0f, cursorHeight);
  40016. }
  40017. if (textToShowWhenEmpty.isNotEmpty()
  40018. && (! hasKeyboardFocus (false))
  40019. && getTotalNumChars() == 0)
  40020. {
  40021. g.setColour (colourForTextWhenEmpty);
  40022. g.setFont (getFont());
  40023. if (isMultiLine())
  40024. {
  40025. g.drawText (textToShowWhenEmpty,
  40026. 0, 0, getWidth(), getHeight(),
  40027. Justification::centred, true);
  40028. }
  40029. else
  40030. {
  40031. g.drawText (textToShowWhenEmpty,
  40032. leftIndent, topIndent,
  40033. viewport->getWidth() - leftIndent,
  40034. viewport->getHeight() - topIndent,
  40035. Justification::centredLeft, true);
  40036. }
  40037. }
  40038. getLookAndFeel().drawTextEditorOutline (g, getWidth(), getHeight(), *this);
  40039. }
  40040. void TextEditor::mouseDown (const MouseEvent& e)
  40041. {
  40042. beginDragAutoRepeat (100);
  40043. newTransaction();
  40044. if (wasFocused || ! selectAllTextWhenFocused)
  40045. {
  40046. if (! (popupMenuEnabled && e.mods.isPopupMenu()))
  40047. {
  40048. moveCursorTo (getTextIndexAt (e.x, e.y),
  40049. e.mods.isShiftDown());
  40050. }
  40051. else
  40052. {
  40053. PopupMenu m;
  40054. addPopupMenuItems (m, &e);
  40055. menuActive = true;
  40056. const int result = m.show();
  40057. menuActive = false;
  40058. if (result != 0)
  40059. performPopupMenuAction (result);
  40060. }
  40061. }
  40062. }
  40063. void TextEditor::mouseDrag (const MouseEvent& e)
  40064. {
  40065. if (wasFocused || ! selectAllTextWhenFocused)
  40066. {
  40067. if (! (popupMenuEnabled && e.mods.isPopupMenu()))
  40068. {
  40069. moveCursorTo (getTextIndexAt (e.x, e.y), true);
  40070. }
  40071. }
  40072. }
  40073. void TextEditor::mouseUp (const MouseEvent& e)
  40074. {
  40075. newTransaction();
  40076. textHolder->startTimer (flashSpeedIntervalMs);
  40077. if (wasFocused || ! selectAllTextWhenFocused)
  40078. {
  40079. if (! (popupMenuEnabled && e.mods.isPopupMenu()))
  40080. {
  40081. moveCaret (getTextIndexAt (e.x, e.y));
  40082. }
  40083. }
  40084. wasFocused = true;
  40085. }
  40086. void TextEditor::mouseDoubleClick (const MouseEvent& e)
  40087. {
  40088. int tokenEnd = getTextIndexAt (e.x, e.y);
  40089. int tokenStart = tokenEnd;
  40090. if (e.getNumberOfClicks() > 3)
  40091. {
  40092. tokenStart = 0;
  40093. tokenEnd = getTotalNumChars();
  40094. }
  40095. else
  40096. {
  40097. const String t (getText());
  40098. const int totalLength = getTotalNumChars();
  40099. while (tokenEnd < totalLength)
  40100. {
  40101. if (CharacterFunctions::isLetterOrDigit (t [tokenEnd]))
  40102. ++tokenEnd;
  40103. else
  40104. break;
  40105. }
  40106. tokenStart = tokenEnd;
  40107. while (tokenStart > 0)
  40108. {
  40109. if (CharacterFunctions::isLetterOrDigit (t [tokenStart - 1]))
  40110. --tokenStart;
  40111. else
  40112. break;
  40113. }
  40114. if (e.getNumberOfClicks() > 2)
  40115. {
  40116. while (tokenEnd < totalLength)
  40117. {
  40118. if (t [tokenEnd] != T('\r') && t [tokenEnd] != T('\n'))
  40119. ++tokenEnd;
  40120. else
  40121. break;
  40122. }
  40123. while (tokenStart > 0)
  40124. {
  40125. if (t [tokenStart - 1] != T('\r') && t [tokenStart - 1] != T('\n'))
  40126. --tokenStart;
  40127. else
  40128. break;
  40129. }
  40130. }
  40131. }
  40132. moveCursorTo (tokenEnd, false);
  40133. moveCursorTo (tokenStart, true);
  40134. }
  40135. void TextEditor::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  40136. {
  40137. if (! viewport->useMouseWheelMoveIfNeeded (e, wheelIncrementX, wheelIncrementY))
  40138. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  40139. }
  40140. bool TextEditor::keyPressed (const KeyPress& key)
  40141. {
  40142. if (isReadOnly() && key != KeyPress (T('c'), ModifierKeys::commandModifier, 0))
  40143. return false;
  40144. const bool moveInWholeWordSteps = key.getModifiers().isCtrlDown() || key.getModifiers().isAltDown();
  40145. if (key.isKeyCode (KeyPress::leftKey)
  40146. || key.isKeyCode (KeyPress::upKey))
  40147. {
  40148. newTransaction();
  40149. int newPos;
  40150. if (isMultiLine() && key.isKeyCode (KeyPress::upKey))
  40151. newPos = indexAtPosition (cursorX, cursorY - 1);
  40152. else if (moveInWholeWordSteps)
  40153. newPos = findWordBreakBefore (getCaretPosition());
  40154. else
  40155. newPos = getCaretPosition() - 1;
  40156. moveCursorTo (newPos, key.getModifiers().isShiftDown());
  40157. }
  40158. else if (key.isKeyCode (KeyPress::rightKey)
  40159. || key.isKeyCode (KeyPress::downKey))
  40160. {
  40161. newTransaction();
  40162. int newPos;
  40163. if (isMultiLine() && key.isKeyCode (KeyPress::downKey))
  40164. newPos = indexAtPosition (cursorX, cursorY + cursorHeight + 1);
  40165. else if (moveInWholeWordSteps)
  40166. newPos = findWordBreakAfter (getCaretPosition());
  40167. else
  40168. newPos = getCaretPosition() + 1;
  40169. moveCursorTo (newPos, key.getModifiers().isShiftDown());
  40170. }
  40171. else if (key.isKeyCode (KeyPress::pageDownKey) && isMultiLine())
  40172. {
  40173. newTransaction();
  40174. moveCursorTo (indexAtPosition (cursorX, cursorY + cursorHeight + viewport->getViewHeight()),
  40175. key.getModifiers().isShiftDown());
  40176. }
  40177. else if (key.isKeyCode (KeyPress::pageUpKey) && isMultiLine())
  40178. {
  40179. newTransaction();
  40180. moveCursorTo (indexAtPosition (cursorX, cursorY - viewport->getViewHeight()),
  40181. key.getModifiers().isShiftDown());
  40182. }
  40183. else if (key.isKeyCode (KeyPress::homeKey))
  40184. {
  40185. newTransaction();
  40186. if (isMultiLine() && ! moveInWholeWordSteps)
  40187. moveCursorTo (indexAtPosition (0.0f, cursorY),
  40188. key.getModifiers().isShiftDown());
  40189. else
  40190. moveCursorTo (0, key.getModifiers().isShiftDown());
  40191. }
  40192. else if (key.isKeyCode (KeyPress::endKey))
  40193. {
  40194. newTransaction();
  40195. if (isMultiLine() && ! moveInWholeWordSteps)
  40196. moveCursorTo (indexAtPosition ((float) textHolder->getWidth(), cursorY),
  40197. key.getModifiers().isShiftDown());
  40198. else
  40199. moveCursorTo (getTotalNumChars(), key.getModifiers().isShiftDown());
  40200. }
  40201. else if (key.isKeyCode (KeyPress::backspaceKey))
  40202. {
  40203. if (moveInWholeWordSteps)
  40204. {
  40205. moveCursorTo (findWordBreakBefore (getCaretPosition()), true);
  40206. }
  40207. else
  40208. {
  40209. if (selectionStart == selectionEnd && selectionStart > 0)
  40210. --selectionStart;
  40211. }
  40212. cut();
  40213. }
  40214. else if (key.isKeyCode (KeyPress::deleteKey))
  40215. {
  40216. if (key.getModifiers().isShiftDown())
  40217. copy();
  40218. if (selectionStart == selectionEnd
  40219. && selectionEnd < getTotalNumChars())
  40220. {
  40221. ++selectionEnd;
  40222. }
  40223. cut();
  40224. }
  40225. else if (key == KeyPress (T('c'), ModifierKeys::commandModifier, 0)
  40226. || key == KeyPress (KeyPress::insertKey, ModifierKeys::ctrlModifier, 0))
  40227. {
  40228. newTransaction();
  40229. copy();
  40230. }
  40231. else if (key == KeyPress (T('x'), ModifierKeys::commandModifier, 0))
  40232. {
  40233. newTransaction();
  40234. copy();
  40235. cut();
  40236. }
  40237. else if (key == KeyPress (T('v'), ModifierKeys::commandModifier, 0)
  40238. || key == KeyPress (KeyPress::insertKey, ModifierKeys::shiftModifier, 0))
  40239. {
  40240. newTransaction();
  40241. paste();
  40242. }
  40243. else if (key == KeyPress (T('z'), ModifierKeys::commandModifier, 0))
  40244. {
  40245. newTransaction();
  40246. doUndoRedo (false);
  40247. }
  40248. else if (key == KeyPress (T('y'), ModifierKeys::commandModifier, 0))
  40249. {
  40250. newTransaction();
  40251. doUndoRedo (true);
  40252. }
  40253. else if (key == KeyPress (T('a'), ModifierKeys::commandModifier, 0))
  40254. {
  40255. newTransaction();
  40256. moveCursorTo (getTotalNumChars(), false);
  40257. moveCursorTo (0, true);
  40258. }
  40259. else if (key == KeyPress::returnKey)
  40260. {
  40261. newTransaction();
  40262. if (returnKeyStartsNewLine)
  40263. insertTextAtCursor (T("\n"));
  40264. else
  40265. returnPressed();
  40266. }
  40267. else if (key.isKeyCode (KeyPress::escapeKey))
  40268. {
  40269. newTransaction();
  40270. moveCursorTo (getCaretPosition(), false);
  40271. escapePressed();
  40272. }
  40273. else if (key.getTextCharacter() >= ' '
  40274. || (tabKeyUsed && (key.getTextCharacter() == '\t')))
  40275. {
  40276. insertTextAtCursor (String::charToString (key.getTextCharacter()));
  40277. lastTransactionTime = Time::getApproximateMillisecondCounter();
  40278. }
  40279. else
  40280. {
  40281. return false;
  40282. }
  40283. return true;
  40284. }
  40285. bool TextEditor::keyStateChanged (const bool isKeyDown)
  40286. {
  40287. if (! isKeyDown)
  40288. return false;
  40289. #if JUCE_WIN32
  40290. if (KeyPress (KeyPress::F4Key, ModifierKeys::altModifier, 0).isCurrentlyDown())
  40291. return false; // We need to explicitly allow alt-F4 to pass through on Windows
  40292. #endif
  40293. // (overridden to avoid forwarding key events to the parent)
  40294. return ! ModifierKeys::getCurrentModifiers().isCommandDown();
  40295. }
  40296. const int baseMenuItemID = 0x7fff0000;
  40297. void TextEditor::addPopupMenuItems (PopupMenu& m, const MouseEvent*)
  40298. {
  40299. const bool writable = ! isReadOnly();
  40300. if (passwordCharacter == 0)
  40301. {
  40302. m.addItem (baseMenuItemID + 1, TRANS("cut"), writable);
  40303. m.addItem (baseMenuItemID + 2, TRANS("copy"), selectionStart < selectionEnd);
  40304. m.addItem (baseMenuItemID + 3, TRANS("paste"), writable);
  40305. }
  40306. m.addItem (baseMenuItemID + 4, TRANS("delete"), writable);
  40307. m.addSeparator();
  40308. m.addItem (baseMenuItemID + 5, TRANS("select all"));
  40309. m.addSeparator();
  40310. m.addItem (baseMenuItemID + 6, TRANS("undo"), undoManager.canUndo());
  40311. m.addItem (baseMenuItemID + 7, TRANS("redo"), undoManager.canRedo());
  40312. }
  40313. void TextEditor::performPopupMenuAction (const int menuItemID)
  40314. {
  40315. switch (menuItemID)
  40316. {
  40317. case baseMenuItemID + 1:
  40318. copy();
  40319. cut();
  40320. break;
  40321. case baseMenuItemID + 2:
  40322. copy();
  40323. break;
  40324. case baseMenuItemID + 3:
  40325. paste();
  40326. break;
  40327. case baseMenuItemID + 4:
  40328. cut();
  40329. break;
  40330. case baseMenuItemID + 5:
  40331. moveCursorTo (getTotalNumChars(), false);
  40332. moveCursorTo (0, true);
  40333. break;
  40334. case baseMenuItemID + 6:
  40335. doUndoRedo (false);
  40336. break;
  40337. case baseMenuItemID + 7:
  40338. doUndoRedo (true);
  40339. break;
  40340. default:
  40341. break;
  40342. }
  40343. }
  40344. void TextEditor::focusGained (FocusChangeType)
  40345. {
  40346. newTransaction();
  40347. caretFlashState = true;
  40348. if (selectAllTextWhenFocused)
  40349. {
  40350. moveCursorTo (0, false);
  40351. moveCursorTo (getTotalNumChars(), true);
  40352. }
  40353. repaint();
  40354. if (caretVisible)
  40355. textHolder->startTimer (flashSpeedIntervalMs);
  40356. ComponentPeer* const peer = getPeer();
  40357. if (peer != 0)
  40358. peer->textInputRequired (getScreenX() - peer->getScreenX(),
  40359. getScreenY() - peer->getScreenY());
  40360. }
  40361. void TextEditor::focusLost (FocusChangeType)
  40362. {
  40363. newTransaction();
  40364. wasFocused = false;
  40365. textHolder->stopTimer();
  40366. caretFlashState = false;
  40367. postCommandMessage (focusLossMessageId);
  40368. repaint();
  40369. }
  40370. void TextEditor::resized()
  40371. {
  40372. viewport->setBoundsInset (borderSize);
  40373. viewport->setSingleStepSizes (16, roundFloatToInt (currentFont.getHeight()));
  40374. updateTextHolderSize();
  40375. if (! isMultiLine())
  40376. {
  40377. scrollToMakeSureCursorIsVisible();
  40378. }
  40379. else
  40380. {
  40381. updateCaretPosition();
  40382. }
  40383. }
  40384. void TextEditor::handleCommandMessage (const int commandId)
  40385. {
  40386. const ComponentDeletionWatcher deletionChecker (this);
  40387. for (int i = listeners.size(); --i >= 0;)
  40388. {
  40389. TextEditorListener* const tl = (TextEditorListener*) listeners [i];
  40390. if (tl != 0)
  40391. {
  40392. switch (commandId)
  40393. {
  40394. case textChangeMessageId:
  40395. tl->textEditorTextChanged (*this);
  40396. break;
  40397. case returnKeyMessageId:
  40398. tl->textEditorReturnKeyPressed (*this);
  40399. break;
  40400. case escapeKeyMessageId:
  40401. tl->textEditorEscapeKeyPressed (*this);
  40402. break;
  40403. case focusLossMessageId:
  40404. tl->textEditorFocusLost (*this);
  40405. break;
  40406. default:
  40407. jassertfalse
  40408. break;
  40409. }
  40410. if (i > 0 && deletionChecker.hasBeenDeleted())
  40411. return;
  40412. }
  40413. }
  40414. }
  40415. void TextEditor::enablementChanged()
  40416. {
  40417. setMouseCursor (MouseCursor (isReadOnly() ? MouseCursor::NormalCursor
  40418. : MouseCursor::IBeamCursor));
  40419. repaint();
  40420. }
  40421. void TextEditor::clearInternal (UndoManager* const um) throw()
  40422. {
  40423. remove (0, getTotalNumChars(), um, caretPosition);
  40424. }
  40425. void TextEditor::insert (const String& text,
  40426. const int insertIndex,
  40427. const Font& font,
  40428. const Colour& colour,
  40429. UndoManager* const um,
  40430. const int caretPositionToMoveTo) throw()
  40431. {
  40432. if (text.isNotEmpty())
  40433. {
  40434. if (um != 0)
  40435. {
  40436. um->perform (new TextEditorInsertAction (*this,
  40437. text,
  40438. insertIndex,
  40439. font,
  40440. colour,
  40441. caretPosition,
  40442. caretPositionToMoveTo));
  40443. }
  40444. else
  40445. {
  40446. repaintText (insertIndex, -1); // must do this before and after changing the data, in case
  40447. // a line gets moved due to word wrap
  40448. int index = 0;
  40449. int nextIndex = 0;
  40450. for (int i = 0; i < sections.size(); ++i)
  40451. {
  40452. nextIndex = index + ((UniformTextSection*) sections.getUnchecked(i))->getTotalLength();
  40453. if (insertIndex == index)
  40454. {
  40455. sections.insert (i, new UniformTextSection (text,
  40456. font, colour,
  40457. passwordCharacter));
  40458. break;
  40459. }
  40460. else if (insertIndex > index && insertIndex < nextIndex)
  40461. {
  40462. splitSection (i, insertIndex - index);
  40463. sections.insert (i + 1, new UniformTextSection (text,
  40464. font, colour,
  40465. passwordCharacter));
  40466. break;
  40467. }
  40468. index = nextIndex;
  40469. }
  40470. if (nextIndex == insertIndex)
  40471. sections.add (new UniformTextSection (text,
  40472. font, colour,
  40473. passwordCharacter));
  40474. coalesceSimilarSections();
  40475. totalNumChars = -1;
  40476. moveCursorTo (caretPositionToMoveTo, false);
  40477. repaintText (insertIndex, -1);
  40478. }
  40479. }
  40480. }
  40481. void TextEditor::reinsert (const int insertIndex,
  40482. const VoidArray& sectionsToInsert) throw()
  40483. {
  40484. int index = 0;
  40485. int nextIndex = 0;
  40486. for (int i = 0; i < sections.size(); ++i)
  40487. {
  40488. nextIndex = index + ((UniformTextSection*) sections.getUnchecked(i))->getTotalLength();
  40489. if (insertIndex == index)
  40490. {
  40491. for (int j = sectionsToInsert.size(); --j >= 0;)
  40492. sections.insert (i, new UniformTextSection (*(UniformTextSection*) sectionsToInsert.getUnchecked(j)));
  40493. break;
  40494. }
  40495. else if (insertIndex > index && insertIndex < nextIndex)
  40496. {
  40497. splitSection (i, insertIndex - index);
  40498. for (int j = sectionsToInsert.size(); --j >= 0;)
  40499. sections.insert (i + 1, new UniformTextSection (*(UniformTextSection*) sectionsToInsert.getUnchecked(j)));
  40500. break;
  40501. }
  40502. index = nextIndex;
  40503. }
  40504. if (nextIndex == insertIndex)
  40505. {
  40506. for (int j = 0; j < sectionsToInsert.size(); ++j)
  40507. sections.add (new UniformTextSection (*(UniformTextSection*) sectionsToInsert.getUnchecked(j)));
  40508. }
  40509. coalesceSimilarSections();
  40510. totalNumChars = -1;
  40511. }
  40512. void TextEditor::remove (const int startIndex,
  40513. int endIndex,
  40514. UndoManager* const um,
  40515. const int caretPositionToMoveTo) throw()
  40516. {
  40517. if (endIndex > startIndex)
  40518. {
  40519. int index = 0;
  40520. for (int i = 0; i < sections.size(); ++i)
  40521. {
  40522. const int nextIndex = index + ((UniformTextSection*) sections[i])->getTotalLength();
  40523. if (startIndex > index && startIndex < nextIndex)
  40524. {
  40525. splitSection (i, startIndex - index);
  40526. --i;
  40527. }
  40528. else if (endIndex > index && endIndex < nextIndex)
  40529. {
  40530. splitSection (i, endIndex - index);
  40531. --i;
  40532. }
  40533. else
  40534. {
  40535. index = nextIndex;
  40536. if (index > endIndex)
  40537. break;
  40538. }
  40539. }
  40540. index = 0;
  40541. if (um != 0)
  40542. {
  40543. VoidArray removedSections;
  40544. for (int i = 0; i < sections.size(); ++i)
  40545. {
  40546. if (endIndex <= startIndex)
  40547. break;
  40548. UniformTextSection* const section = (UniformTextSection*) sections.getUnchecked (i);
  40549. const int nextIndex = index + section->getTotalLength();
  40550. if (startIndex <= index && endIndex >= nextIndex)
  40551. removedSections.add (new UniformTextSection (*section));
  40552. index = nextIndex;
  40553. }
  40554. um->perform (new TextEditorRemoveAction (*this,
  40555. startIndex,
  40556. endIndex,
  40557. caretPosition,
  40558. caretPositionToMoveTo,
  40559. removedSections));
  40560. }
  40561. else
  40562. {
  40563. for (int i = 0; i < sections.size(); ++i)
  40564. {
  40565. if (endIndex <= startIndex)
  40566. break;
  40567. UniformTextSection* const section = (UniformTextSection*) sections.getUnchecked (i);
  40568. const int nextIndex = index + section->getTotalLength();
  40569. if (startIndex <= index && endIndex >= nextIndex)
  40570. {
  40571. sections.remove(i);
  40572. endIndex -= (nextIndex - index);
  40573. section->clear();
  40574. delete section;
  40575. --i;
  40576. }
  40577. else
  40578. {
  40579. index = nextIndex;
  40580. }
  40581. }
  40582. coalesceSimilarSections();
  40583. totalNumChars = -1;
  40584. moveCursorTo (caretPositionToMoveTo, false);
  40585. repaintText (startIndex, -1);
  40586. }
  40587. }
  40588. }
  40589. const String TextEditor::getText() const throw()
  40590. {
  40591. String t;
  40592. for (int i = 0; i < sections.size(); ++i)
  40593. t += ((const UniformTextSection*) sections.getUnchecked(i))->getAllText();
  40594. return t;
  40595. }
  40596. const String TextEditor::getTextSubstring (const int startCharacter, const int endCharacter) const throw()
  40597. {
  40598. String t;
  40599. int index = 0;
  40600. for (int i = 0; i < sections.size(); ++i)
  40601. {
  40602. const UniformTextSection* const s = (const UniformTextSection*) sections.getUnchecked(i);
  40603. const int nextIndex = index + s->getTotalLength();
  40604. if (startCharacter < nextIndex)
  40605. {
  40606. if (endCharacter <= index)
  40607. break;
  40608. const int start = jmax (index, startCharacter);
  40609. t += s->getTextSubstring (start - index, endCharacter - index);
  40610. }
  40611. index = nextIndex;
  40612. }
  40613. return t;
  40614. }
  40615. const String TextEditor::getHighlightedText() const throw()
  40616. {
  40617. return getTextSubstring (getHighlightedRegionStart(),
  40618. getHighlightedRegionStart() + getHighlightedRegionLength());
  40619. }
  40620. int TextEditor::getTotalNumChars() throw()
  40621. {
  40622. if (totalNumChars < 0)
  40623. {
  40624. totalNumChars = 0;
  40625. for (int i = sections.size(); --i >= 0;)
  40626. totalNumChars += ((const UniformTextSection*) sections.getUnchecked(i))->getTotalLength();
  40627. }
  40628. return totalNumChars;
  40629. }
  40630. bool TextEditor::isEmpty() const throw()
  40631. {
  40632. if (totalNumChars != 0)
  40633. {
  40634. for (int i = sections.size(); --i >= 0;)
  40635. if (((const UniformTextSection*) sections.getUnchecked(i))->getTotalLength() > 0)
  40636. return false;
  40637. }
  40638. return true;
  40639. }
  40640. void TextEditor::getCharPosition (const int index, float& cx, float& cy, float& lineHeight) const throw()
  40641. {
  40642. const float wordWrapWidth = getWordWrapWidth();
  40643. if (wordWrapWidth > 0 && sections.size() > 0)
  40644. {
  40645. TextEditorIterator i (sections, wordWrapWidth, passwordCharacter);
  40646. i.getCharPosition (index, cx, cy, lineHeight);
  40647. }
  40648. else
  40649. {
  40650. cx = cy = 0;
  40651. lineHeight = currentFont.getHeight();
  40652. }
  40653. }
  40654. int TextEditor::indexAtPosition (const float x, const float y) throw()
  40655. {
  40656. const float wordWrapWidth = getWordWrapWidth();
  40657. if (wordWrapWidth > 0)
  40658. {
  40659. TextEditorIterator i (sections, wordWrapWidth, passwordCharacter);
  40660. while (i.next())
  40661. {
  40662. if (i.lineY + getHeight() > y)
  40663. i.updateLineHeight();
  40664. if (i.lineY + i.lineHeight > y)
  40665. {
  40666. if (i.lineY > y)
  40667. return jmax (0, i.indexInText - 1);
  40668. if (i.atomX >= x)
  40669. return i.indexInText;
  40670. if (x < i.atomRight)
  40671. return i.xToIndex (x);
  40672. }
  40673. }
  40674. }
  40675. return getTotalNumChars();
  40676. }
  40677. static int getCharacterCategory (const tchar character) throw()
  40678. {
  40679. return CharacterFunctions::isLetterOrDigit (character)
  40680. ? 2 : (CharacterFunctions::isWhitespace (character) ? 0 : 1);
  40681. }
  40682. int TextEditor::findWordBreakAfter (const int position) const throw()
  40683. {
  40684. const String t (getTextSubstring (position, position + 512));
  40685. const int totalLength = t.length();
  40686. int i = 0;
  40687. while (i < totalLength && CharacterFunctions::isWhitespace (t[i]))
  40688. ++i;
  40689. const int type = getCharacterCategory (t[i]);
  40690. while (i < totalLength && type == getCharacterCategory (t[i]))
  40691. ++i;
  40692. while (i < totalLength && CharacterFunctions::isWhitespace (t[i]))
  40693. ++i;
  40694. return position + i;
  40695. }
  40696. int TextEditor::findWordBreakBefore (const int position) const throw()
  40697. {
  40698. if (position <= 0)
  40699. return 0;
  40700. const int startOfBuffer = jmax (0, position - 512);
  40701. const String t (getTextSubstring (startOfBuffer, position));
  40702. int i = position - startOfBuffer;
  40703. while (i > 0 && CharacterFunctions::isWhitespace (t [i - 1]))
  40704. --i;
  40705. if (i > 0)
  40706. {
  40707. const int type = getCharacterCategory (t [i - 1]);
  40708. while (i > 0 && type == getCharacterCategory (t [i - 1]))
  40709. --i;
  40710. }
  40711. jassert (startOfBuffer + i >= 0);
  40712. return startOfBuffer + i;
  40713. }
  40714. void TextEditor::splitSection (const int sectionIndex,
  40715. const int charToSplitAt) throw()
  40716. {
  40717. jassert (sections[sectionIndex] != 0);
  40718. sections.insert (sectionIndex + 1,
  40719. ((UniformTextSection*) sections.getUnchecked (sectionIndex))
  40720. ->split (charToSplitAt, passwordCharacter));
  40721. }
  40722. void TextEditor::coalesceSimilarSections() throw()
  40723. {
  40724. for (int i = 0; i < sections.size() - 1; ++i)
  40725. {
  40726. UniformTextSection* const s1 = (UniformTextSection*) (sections.getUnchecked (i));
  40727. UniformTextSection* const s2 = (UniformTextSection*) (sections.getUnchecked (i + 1));
  40728. if (s1->font == s2->font
  40729. && s1->colour == s2->colour)
  40730. {
  40731. s1->append (*s2, passwordCharacter);
  40732. sections.remove (i + 1);
  40733. delete s2;
  40734. --i;
  40735. }
  40736. }
  40737. }
  40738. END_JUCE_NAMESPACE
  40739. /********* End of inlined file: juce_TextEditor.cpp *********/
  40740. /********* Start of inlined file: juce_Toolbar.cpp *********/
  40741. BEGIN_JUCE_NAMESPACE
  40742. const tchar* const Toolbar::toolbarDragDescriptor = T("_toolbarItem_");
  40743. class ToolbarSpacerComp : public ToolbarItemComponent
  40744. {
  40745. public:
  40746. ToolbarSpacerComp (const int itemId, const float fixedSize_, const bool drawBar_)
  40747. : ToolbarItemComponent (itemId, String::empty, false),
  40748. fixedSize (fixedSize_),
  40749. drawBar (drawBar_)
  40750. {
  40751. }
  40752. ~ToolbarSpacerComp()
  40753. {
  40754. }
  40755. bool getToolbarItemSizes (int toolbarThickness, bool /*isToolbarVertical*/,
  40756. int& preferredSize, int& minSize, int& maxSize)
  40757. {
  40758. if (fixedSize <= 0)
  40759. {
  40760. preferredSize = toolbarThickness * 2;
  40761. minSize = 4;
  40762. maxSize = 32768;
  40763. }
  40764. else
  40765. {
  40766. maxSize = roundFloatToInt (toolbarThickness * fixedSize);
  40767. minSize = drawBar ? maxSize : jmin (4, maxSize);
  40768. preferredSize = maxSize;
  40769. if (getEditingMode() == editableOnPalette)
  40770. preferredSize = maxSize = toolbarThickness / (drawBar ? 3 : 2);
  40771. }
  40772. return true;
  40773. }
  40774. void paintButtonArea (Graphics&, int, int, bool, bool)
  40775. {
  40776. }
  40777. void contentAreaChanged (const Rectangle&)
  40778. {
  40779. }
  40780. int getResizeOrder() const throw()
  40781. {
  40782. return fixedSize <= 0 ? 0 : 1;
  40783. }
  40784. void paint (Graphics& g)
  40785. {
  40786. const int w = getWidth();
  40787. const int h = getHeight();
  40788. if (drawBar)
  40789. {
  40790. g.setColour (findColour (Toolbar::separatorColourId, true));
  40791. const float thickness = 0.2f;
  40792. if (isToolbarVertical())
  40793. g.fillRect (w * 0.1f, h * (0.5f - thickness * 0.5f), w * 0.8f, h * thickness);
  40794. else
  40795. g.fillRect (w * (0.5f - thickness * 0.5f), h * 0.1f, w * thickness, h * 0.8f);
  40796. }
  40797. if (getEditingMode() != normalMode && ! drawBar)
  40798. {
  40799. g.setColour (findColour (Toolbar::separatorColourId, true));
  40800. const int indentX = jmin (2, (w - 3) / 2);
  40801. const int indentY = jmin (2, (h - 3) / 2);
  40802. g.drawRect (indentX, indentY, w - indentX * 2, h - indentY * 2, 1);
  40803. if (fixedSize <= 0)
  40804. {
  40805. float x1, y1, x2, y2, x3, y3, x4, y4, hw, hl;
  40806. if (isToolbarVertical())
  40807. {
  40808. x1 = w * 0.5f;
  40809. y1 = h * 0.4f;
  40810. x2 = x1;
  40811. y2 = indentX * 2.0f;
  40812. x3 = x1;
  40813. y3 = h * 0.6f;
  40814. x4 = x1;
  40815. y4 = h - y2;
  40816. hw = w * 0.15f;
  40817. hl = w * 0.2f;
  40818. }
  40819. else
  40820. {
  40821. x1 = w * 0.4f;
  40822. y1 = h * 0.5f;
  40823. x2 = indentX * 2.0f;
  40824. y2 = y1;
  40825. x3 = w * 0.6f;
  40826. y3 = y1;
  40827. x4 = w - x2;
  40828. y4 = y1;
  40829. hw = h * 0.15f;
  40830. hl = h * 0.2f;
  40831. }
  40832. Path p;
  40833. p.addArrow (x1, y1, x2, y2, 1.5f, hw, hl);
  40834. p.addArrow (x3, y3, x4, y4, 1.5f, hw, hl);
  40835. g.fillPath (p);
  40836. }
  40837. }
  40838. }
  40839. juce_UseDebuggingNewOperator
  40840. private:
  40841. const float fixedSize;
  40842. const bool drawBar;
  40843. ToolbarSpacerComp (const ToolbarSpacerComp&);
  40844. const ToolbarSpacerComp& operator= (const ToolbarSpacerComp&);
  40845. };
  40846. class MissingItemsComponent : public PopupMenuCustomComponent
  40847. {
  40848. public:
  40849. MissingItemsComponent (Toolbar& owner_, const int height_)
  40850. : PopupMenuCustomComponent (true),
  40851. owner (owner_),
  40852. height (height_)
  40853. {
  40854. for (int i = owner_.items.size(); --i >= 0;)
  40855. {
  40856. ToolbarItemComponent* const tc = owner_.items.getUnchecked(i);
  40857. if (dynamic_cast <ToolbarSpacerComp*> (tc) == 0 && ! tc->isVisible())
  40858. {
  40859. oldIndexes.insert (0, i);
  40860. addAndMakeVisible (tc, 0);
  40861. }
  40862. }
  40863. layout (400);
  40864. }
  40865. ~MissingItemsComponent()
  40866. {
  40867. // deleting the toolbar while its menu it open??
  40868. jassert (owner.isValidComponent());
  40869. for (int i = 0; i < getNumChildComponents(); ++i)
  40870. {
  40871. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getChildComponent (i));
  40872. if (tc != 0)
  40873. {
  40874. tc->setVisible (false);
  40875. const int index = oldIndexes.remove (i);
  40876. owner.addChildComponent (tc, index);
  40877. --i;
  40878. }
  40879. }
  40880. owner.resized();
  40881. }
  40882. void layout (const int preferredWidth)
  40883. {
  40884. const int indent = 8;
  40885. int x = indent;
  40886. int y = indent;
  40887. int maxX = 0;
  40888. for (int i = 0; i < getNumChildComponents(); ++i)
  40889. {
  40890. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getChildComponent (i));
  40891. if (tc != 0)
  40892. {
  40893. int preferredSize = 1, minSize = 1, maxSize = 1;
  40894. if (tc->getToolbarItemSizes (height, false, preferredSize, minSize, maxSize))
  40895. {
  40896. if (x + preferredSize > preferredWidth && x > indent)
  40897. {
  40898. x = indent;
  40899. y += height;
  40900. }
  40901. tc->setBounds (x, y, preferredSize, height);
  40902. x += preferredSize;
  40903. maxX = jmax (maxX, x);
  40904. }
  40905. }
  40906. }
  40907. setSize (maxX + 8, y + height + 8);
  40908. }
  40909. void getIdealSize (int& idealWidth, int& idealHeight)
  40910. {
  40911. idealWidth = getWidth();
  40912. idealHeight = getHeight();
  40913. }
  40914. juce_UseDebuggingNewOperator
  40915. private:
  40916. Toolbar& owner;
  40917. const int height;
  40918. Array <int> oldIndexes;
  40919. MissingItemsComponent (const MissingItemsComponent&);
  40920. const MissingItemsComponent& operator= (const MissingItemsComponent&);
  40921. };
  40922. Toolbar::Toolbar()
  40923. : vertical (false),
  40924. isEditingActive (false),
  40925. toolbarStyle (Toolbar::iconsOnly)
  40926. {
  40927. addChildComponent (missingItemsButton = getLookAndFeel().createToolbarMissingItemsButton (*this));
  40928. missingItemsButton->setAlwaysOnTop (true);
  40929. missingItemsButton->addButtonListener (this);
  40930. }
  40931. Toolbar::~Toolbar()
  40932. {
  40933. animator.cancelAllAnimations (true);
  40934. deleteAllChildren();
  40935. }
  40936. void Toolbar::setVertical (const bool shouldBeVertical)
  40937. {
  40938. if (vertical != shouldBeVertical)
  40939. {
  40940. vertical = shouldBeVertical;
  40941. resized();
  40942. }
  40943. }
  40944. void Toolbar::clear()
  40945. {
  40946. for (int i = items.size(); --i >= 0;)
  40947. {
  40948. ToolbarItemComponent* const tc = items.getUnchecked(i);
  40949. items.remove (i);
  40950. delete tc;
  40951. }
  40952. resized();
  40953. }
  40954. ToolbarItemComponent* Toolbar::createItem (ToolbarItemFactory& factory, const int itemId)
  40955. {
  40956. if (itemId == ToolbarItemFactory::separatorBarId)
  40957. return new ToolbarSpacerComp (itemId, 0.1f, true);
  40958. else if (itemId == ToolbarItemFactory::spacerId)
  40959. return new ToolbarSpacerComp (itemId, 0.5f, false);
  40960. else if (itemId == ToolbarItemFactory::flexibleSpacerId)
  40961. return new ToolbarSpacerComp (itemId, 0, false);
  40962. return factory.createItem (itemId);
  40963. }
  40964. void Toolbar::addItemInternal (ToolbarItemFactory& factory,
  40965. const int itemId,
  40966. const int insertIndex)
  40967. {
  40968. // An ID can't be zero - this might indicate a mistake somewhere?
  40969. jassert (itemId != 0);
  40970. ToolbarItemComponent* const tc = createItem (factory, itemId);
  40971. if (tc != 0)
  40972. {
  40973. #ifdef JUCE_DEBUG
  40974. Array <int> allowedIds;
  40975. factory.getAllToolbarItemIds (allowedIds);
  40976. // If your factory can create an item for a given ID, it must also return
  40977. // that ID from its getAllToolbarItemIds() method!
  40978. jassert (allowedIds.contains (itemId));
  40979. #endif
  40980. items.insert (insertIndex, tc);
  40981. addAndMakeVisible (tc, insertIndex);
  40982. }
  40983. }
  40984. void Toolbar::addItem (ToolbarItemFactory& factory,
  40985. const int itemId,
  40986. const int insertIndex)
  40987. {
  40988. addItemInternal (factory, itemId, insertIndex);
  40989. resized();
  40990. }
  40991. void Toolbar::addDefaultItems (ToolbarItemFactory& factoryToUse)
  40992. {
  40993. Array <int> ids;
  40994. factoryToUse.getDefaultItemSet (ids);
  40995. clear();
  40996. for (int i = 0; i < ids.size(); ++i)
  40997. addItemInternal (factoryToUse, ids.getUnchecked (i), -1);
  40998. resized();
  40999. }
  41000. void Toolbar::removeToolbarItem (const int itemIndex)
  41001. {
  41002. ToolbarItemComponent* const tc = getItemComponent (itemIndex);
  41003. if (tc != 0)
  41004. {
  41005. items.removeValue (tc);
  41006. delete tc;
  41007. resized();
  41008. }
  41009. }
  41010. int Toolbar::getNumItems() const throw()
  41011. {
  41012. return items.size();
  41013. }
  41014. int Toolbar::getItemId (const int itemIndex) const throw()
  41015. {
  41016. ToolbarItemComponent* const tc = getItemComponent (itemIndex);
  41017. return tc != 0 ? tc->getItemId() : 0;
  41018. }
  41019. ToolbarItemComponent* Toolbar::getItemComponent (const int itemIndex) const throw()
  41020. {
  41021. return items [itemIndex];
  41022. }
  41023. ToolbarItemComponent* Toolbar::getNextActiveComponent (int index, const int delta) const
  41024. {
  41025. for (;;)
  41026. {
  41027. index += delta;
  41028. ToolbarItemComponent* const tc = getItemComponent (index);
  41029. if (tc == 0)
  41030. break;
  41031. if (tc->isActive)
  41032. return tc;
  41033. }
  41034. return 0;
  41035. }
  41036. void Toolbar::setStyle (const ToolbarItemStyle& newStyle)
  41037. {
  41038. if (toolbarStyle != newStyle)
  41039. {
  41040. toolbarStyle = newStyle;
  41041. updateAllItemPositions (false);
  41042. }
  41043. }
  41044. const String Toolbar::toString() const
  41045. {
  41046. String s (T("TB:"));
  41047. for (int i = 0; i < getNumItems(); ++i)
  41048. s << getItemId(i) << T(' ');
  41049. return s.trimEnd();
  41050. }
  41051. bool Toolbar::restoreFromString (ToolbarItemFactory& factoryToUse,
  41052. const String& savedVersion)
  41053. {
  41054. if (! savedVersion.startsWith (T("TB:")))
  41055. return false;
  41056. StringArray tokens;
  41057. tokens.addTokens (savedVersion.substring (3), false);
  41058. clear();
  41059. for (int i = 0; i < tokens.size(); ++i)
  41060. addItemInternal (factoryToUse, tokens[i].getIntValue(), -1);
  41061. resized();
  41062. return true;
  41063. }
  41064. void Toolbar::paint (Graphics& g)
  41065. {
  41066. getLookAndFeel().paintToolbarBackground (g, getWidth(), getHeight(), *this);
  41067. }
  41068. int Toolbar::getThickness() const throw()
  41069. {
  41070. return vertical ? getWidth() : getHeight();
  41071. }
  41072. int Toolbar::getLength() const throw()
  41073. {
  41074. return vertical ? getHeight() : getWidth();
  41075. }
  41076. void Toolbar::setEditingActive (const bool active)
  41077. {
  41078. if (isEditingActive != active)
  41079. {
  41080. isEditingActive = active;
  41081. updateAllItemPositions (false);
  41082. }
  41083. }
  41084. void Toolbar::resized()
  41085. {
  41086. updateAllItemPositions (false);
  41087. }
  41088. void Toolbar::updateAllItemPositions (const bool animate)
  41089. {
  41090. if (getWidth() > 0 && getHeight() > 0)
  41091. {
  41092. StretchableObjectResizer resizer;
  41093. int i;
  41094. for (i = 0; i < items.size(); ++i)
  41095. {
  41096. ToolbarItemComponent* const tc = items.getUnchecked(i);
  41097. tc->setEditingMode (isEditingActive ? ToolbarItemComponent::editableOnToolbar
  41098. : ToolbarItemComponent::normalMode);
  41099. tc->setStyle (toolbarStyle);
  41100. ToolbarSpacerComp* const spacer = dynamic_cast <ToolbarSpacerComp*> (tc);
  41101. int preferredSize = 1, minSize = 1, maxSize = 1;
  41102. if (tc->getToolbarItemSizes (getThickness(), isVertical(),
  41103. preferredSize, minSize, maxSize))
  41104. {
  41105. tc->isActive = true;
  41106. resizer.addItem (preferredSize, minSize, maxSize,
  41107. spacer != 0 ? spacer->getResizeOrder() : 2);
  41108. }
  41109. else
  41110. {
  41111. tc->isActive = false;
  41112. tc->setVisible (false);
  41113. }
  41114. }
  41115. resizer.resizeToFit (getLength());
  41116. int totalLength = 0;
  41117. for (i = 0; i < resizer.getNumItems(); ++i)
  41118. totalLength += (int) resizer.getItemSize (i);
  41119. const bool itemsOffTheEnd = totalLength > getLength();
  41120. const int extrasButtonSize = getThickness() / 2;
  41121. missingItemsButton->setSize (extrasButtonSize, extrasButtonSize);
  41122. missingItemsButton->setVisible (itemsOffTheEnd);
  41123. missingItemsButton->setEnabled (! isEditingActive);
  41124. if (vertical)
  41125. missingItemsButton->setCentrePosition (getWidth() / 2,
  41126. getHeight() - 4 - extrasButtonSize / 2);
  41127. else
  41128. missingItemsButton->setCentrePosition (getWidth() - 4 - extrasButtonSize / 2,
  41129. getHeight() / 2);
  41130. const int maxLength = itemsOffTheEnd ? (vertical ? missingItemsButton->getY()
  41131. : missingItemsButton->getX()) - 4
  41132. : getLength();
  41133. int pos = 0, activeIndex = 0;
  41134. for (i = 0; i < items.size(); ++i)
  41135. {
  41136. ToolbarItemComponent* const tc = items.getUnchecked(i);
  41137. if (tc->isActive)
  41138. {
  41139. const int size = (int) resizer.getItemSize (activeIndex++);
  41140. Rectangle newBounds;
  41141. if (vertical)
  41142. newBounds.setBounds (0, pos, getWidth(), size);
  41143. else
  41144. newBounds.setBounds (pos, 0, size, getHeight());
  41145. if (animate)
  41146. {
  41147. animator.animateComponent (tc, newBounds, 200, 3.0, 0.0);
  41148. }
  41149. else
  41150. {
  41151. animator.cancelAnimation (tc, false);
  41152. tc->setBounds (newBounds);
  41153. }
  41154. pos += size;
  41155. tc->setVisible (pos <= maxLength
  41156. && ((! tc->isBeingDragged)
  41157. || tc->getEditingMode() == ToolbarItemComponent::editableOnPalette));
  41158. }
  41159. }
  41160. }
  41161. }
  41162. void Toolbar::buttonClicked (Button*)
  41163. {
  41164. jassert (missingItemsButton->isShowing());
  41165. if (missingItemsButton->isShowing())
  41166. {
  41167. PopupMenu m;
  41168. m.addCustomItem (1, new MissingItemsComponent (*this, getThickness()));
  41169. m.showAt (missingItemsButton);
  41170. }
  41171. }
  41172. bool Toolbar::isInterestedInDragSource (const String& sourceDescription,
  41173. Component* /*sourceComponent*/)
  41174. {
  41175. return sourceDescription == toolbarDragDescriptor && isEditingActive;
  41176. }
  41177. void Toolbar::itemDragMove (const String&, Component* sourceComponent, int x, int y)
  41178. {
  41179. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (sourceComponent);
  41180. if (tc != 0)
  41181. {
  41182. if (getNumItems() == 0)
  41183. {
  41184. if (tc->getEditingMode() == ToolbarItemComponent::editableOnPalette)
  41185. {
  41186. ToolbarItemPalette* const palette = tc->findParentComponentOfClass ((ToolbarItemPalette*) 0);
  41187. if (palette != 0)
  41188. palette->replaceComponent (tc);
  41189. }
  41190. else
  41191. {
  41192. jassert (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar);
  41193. }
  41194. items.add (tc);
  41195. addChildComponent (tc);
  41196. updateAllItemPositions (false);
  41197. }
  41198. else
  41199. {
  41200. for (int i = getNumItems(); --i >= 0;)
  41201. {
  41202. int currentIndex = getIndexOfChildComponent (tc);
  41203. if (currentIndex < 0)
  41204. {
  41205. if (tc->getEditingMode() == ToolbarItemComponent::editableOnPalette)
  41206. {
  41207. ToolbarItemPalette* const palette = tc->findParentComponentOfClass ((ToolbarItemPalette*) 0);
  41208. if (palette != 0)
  41209. palette->replaceComponent (tc);
  41210. }
  41211. else
  41212. {
  41213. jassert (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar);
  41214. }
  41215. items.add (tc);
  41216. addChildComponent (tc);
  41217. currentIndex = getIndexOfChildComponent (tc);
  41218. updateAllItemPositions (true);
  41219. }
  41220. int newIndex = currentIndex;
  41221. const int dragObjectLeft = vertical ? (y - tc->dragOffsetY) : (x - tc->dragOffsetX);
  41222. const int dragObjectRight = dragObjectLeft + (vertical ? tc->getHeight() : tc->getWidth());
  41223. const Rectangle current (animator.getComponentDestination (getChildComponent (newIndex)));
  41224. ToolbarItemComponent* const prev = getNextActiveComponent (newIndex, -1);
  41225. if (prev != 0)
  41226. {
  41227. const Rectangle previousPos (animator.getComponentDestination (prev));
  41228. if (abs (dragObjectLeft - (vertical ? previousPos.getY() : previousPos.getX())
  41229. < abs (dragObjectRight - (vertical ? current.getBottom() : current.getRight()))))
  41230. {
  41231. newIndex = getIndexOfChildComponent (prev);
  41232. }
  41233. }
  41234. ToolbarItemComponent* const next = getNextActiveComponent (newIndex, 1);
  41235. if (next != 0)
  41236. {
  41237. const Rectangle nextPos (animator.getComponentDestination (next));
  41238. if (abs (dragObjectLeft - (vertical ? current.getY() : current.getX())
  41239. > abs (dragObjectRight - (vertical ? nextPos.getBottom() : nextPos.getRight()))))
  41240. {
  41241. newIndex = getIndexOfChildComponent (next) + 1;
  41242. }
  41243. }
  41244. if (newIndex != currentIndex)
  41245. {
  41246. items.removeValue (tc);
  41247. removeChildComponent (tc);
  41248. addChildComponent (tc, newIndex);
  41249. items.insert (newIndex, tc);
  41250. updateAllItemPositions (true);
  41251. }
  41252. else
  41253. {
  41254. break;
  41255. }
  41256. }
  41257. }
  41258. }
  41259. }
  41260. void Toolbar::itemDragExit (const String&, Component* sourceComponent)
  41261. {
  41262. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (sourceComponent);
  41263. if (tc != 0)
  41264. {
  41265. if (isParentOf (tc))
  41266. {
  41267. items.removeValue (tc);
  41268. removeChildComponent (tc);
  41269. updateAllItemPositions (true);
  41270. }
  41271. }
  41272. }
  41273. void Toolbar::itemDropped (const String&, Component*, int, int)
  41274. {
  41275. }
  41276. void Toolbar::mouseDown (const MouseEvent& e)
  41277. {
  41278. if (e.mods.isPopupMenu())
  41279. {
  41280. }
  41281. }
  41282. class ToolbarCustomisationDialog : public DialogWindow
  41283. {
  41284. public:
  41285. ToolbarCustomisationDialog (ToolbarItemFactory& factory,
  41286. Toolbar* const toolbar_,
  41287. const int optionFlags)
  41288. : DialogWindow (TRANS("Add/remove items from toolbar"), Colours::white, true, true),
  41289. toolbar (toolbar_)
  41290. {
  41291. setContentComponent (new CustomiserPanel (factory, toolbar, optionFlags), true, true);
  41292. setResizable (true, true);
  41293. setResizeLimits (400, 300, 1500, 1000);
  41294. positionNearBar();
  41295. }
  41296. ~ToolbarCustomisationDialog()
  41297. {
  41298. setContentComponent (0, true);
  41299. }
  41300. void closeButtonPressed()
  41301. {
  41302. setVisible (false);
  41303. }
  41304. bool canModalEventBeSentToComponent (const Component* comp)
  41305. {
  41306. return toolbar->isParentOf (comp);
  41307. }
  41308. void positionNearBar()
  41309. {
  41310. const Rectangle screenSize (toolbar->getParentMonitorArea());
  41311. const int tbx = toolbar->getScreenX();
  41312. const int tby = toolbar->getScreenY();
  41313. const int gap = 8;
  41314. int x, y;
  41315. if (toolbar->isVertical())
  41316. {
  41317. y = tby;
  41318. if (tbx > screenSize.getCentreX())
  41319. x = tbx - getWidth() - gap;
  41320. else
  41321. x = tbx + toolbar->getWidth() + gap;
  41322. }
  41323. else
  41324. {
  41325. x = tbx + (toolbar->getWidth() - getWidth()) / 2;
  41326. if (tby > screenSize.getCentreY())
  41327. y = tby - getHeight() - gap;
  41328. else
  41329. y = tby + toolbar->getHeight() + gap;
  41330. }
  41331. setTopLeftPosition (x, y);
  41332. }
  41333. private:
  41334. Toolbar* const toolbar;
  41335. class CustomiserPanel : public Component,
  41336. private ComboBoxListener,
  41337. private ButtonListener
  41338. {
  41339. public:
  41340. CustomiserPanel (ToolbarItemFactory& factory_,
  41341. Toolbar* const toolbar_,
  41342. const int optionFlags)
  41343. : factory (factory_),
  41344. toolbar (toolbar_),
  41345. styleBox (0),
  41346. defaultButton (0)
  41347. {
  41348. addAndMakeVisible (palette = new ToolbarItemPalette (factory, toolbar));
  41349. if ((optionFlags & (Toolbar::allowIconsOnlyChoice
  41350. | Toolbar::allowIconsWithTextChoice
  41351. | Toolbar::allowTextOnlyChoice)) != 0)
  41352. {
  41353. addAndMakeVisible (styleBox = new ComboBox (String::empty));
  41354. styleBox->setEditableText (false);
  41355. if ((optionFlags & Toolbar::allowIconsOnlyChoice) != 0)
  41356. styleBox->addItem (TRANS("Show icons only"), 1);
  41357. if ((optionFlags & Toolbar::allowIconsWithTextChoice) != 0)
  41358. styleBox->addItem (TRANS("Show icons and descriptions"), 2);
  41359. if ((optionFlags & Toolbar::allowTextOnlyChoice) != 0)
  41360. styleBox->addItem (TRANS("Show descriptions only"), 3);
  41361. if (toolbar_->getStyle() == Toolbar::iconsOnly)
  41362. styleBox->setSelectedId (1);
  41363. else if (toolbar_->getStyle() == Toolbar::iconsWithText)
  41364. styleBox->setSelectedId (2);
  41365. else if (toolbar_->getStyle() == Toolbar::textOnly)
  41366. styleBox->setSelectedId (3);
  41367. styleBox->addListener (this);
  41368. }
  41369. if ((optionFlags & Toolbar::showResetToDefaultsButton) != 0)
  41370. {
  41371. addAndMakeVisible (defaultButton = new TextButton (TRANS ("Restore to default set of items")));
  41372. defaultButton->addButtonListener (this);
  41373. }
  41374. addAndMakeVisible (instructions = new Label (String::empty,
  41375. TRANS ("You can drag the items above and drop them onto a toolbar to add them.\n\nItems on the toolbar can also be dragged around to change their order, or dragged off the edge to delete them.")));
  41376. instructions->setFont (Font (13.0f));
  41377. setSize (500, 300);
  41378. }
  41379. ~CustomiserPanel()
  41380. {
  41381. deleteAllChildren();
  41382. }
  41383. void comboBoxChanged (ComboBox*)
  41384. {
  41385. if (styleBox->getSelectedId() == 1)
  41386. toolbar->setStyle (Toolbar::iconsOnly);
  41387. else if (styleBox->getSelectedId() == 2)
  41388. toolbar->setStyle (Toolbar::iconsWithText);
  41389. else if (styleBox->getSelectedId() == 3)
  41390. toolbar->setStyle (Toolbar::textOnly);
  41391. palette->resized(); // to make it update the styles
  41392. }
  41393. void buttonClicked (Button*)
  41394. {
  41395. toolbar->addDefaultItems (factory);
  41396. }
  41397. void paint (Graphics& g)
  41398. {
  41399. Colour background;
  41400. DialogWindow* const dw = findParentComponentOfClass ((DialogWindow*) 0);
  41401. if (dw != 0)
  41402. background = dw->getBackgroundColour();
  41403. g.setColour (background.contrasting().withAlpha (0.3f));
  41404. g.fillRect (palette->getX(), palette->getBottom() - 1, palette->getWidth(), 1);
  41405. }
  41406. void resized()
  41407. {
  41408. palette->setBounds (0, 0, getWidth(), getHeight() - 120);
  41409. if (styleBox != 0)
  41410. styleBox->setBounds (10, getHeight() - 110, 200, 22);
  41411. if (defaultButton != 0)
  41412. {
  41413. defaultButton->changeWidthToFitText (22);
  41414. defaultButton->setTopLeftPosition (240, getHeight() - 110);
  41415. }
  41416. instructions->setBounds (10, getHeight() - 80, getWidth() - 20, 80);
  41417. }
  41418. private:
  41419. ToolbarItemFactory& factory;
  41420. Toolbar* const toolbar;
  41421. Label* instructions;
  41422. ToolbarItemPalette* palette;
  41423. ComboBox* styleBox;
  41424. TextButton* defaultButton;
  41425. };
  41426. };
  41427. void Toolbar::showCustomisationDialog (ToolbarItemFactory& factory, const int optionFlags)
  41428. {
  41429. setEditingActive (true);
  41430. ToolbarCustomisationDialog dw (factory, this, optionFlags);
  41431. dw.runModalLoop();
  41432. jassert (isValidComponent()); // ? deleting the toolbar while it's being edited?
  41433. setEditingActive (false);
  41434. }
  41435. END_JUCE_NAMESPACE
  41436. /********* End of inlined file: juce_Toolbar.cpp *********/
  41437. /********* Start of inlined file: juce_ToolbarItemComponent.cpp *********/
  41438. BEGIN_JUCE_NAMESPACE
  41439. ToolbarItemFactory::ToolbarItemFactory()
  41440. {
  41441. }
  41442. ToolbarItemFactory::~ToolbarItemFactory()
  41443. {
  41444. }
  41445. class ItemDragAndDropOverlayComponent : public Component
  41446. {
  41447. public:
  41448. ItemDragAndDropOverlayComponent()
  41449. : isDragging (false)
  41450. {
  41451. setAlwaysOnTop (true);
  41452. setRepaintsOnMouseActivity (true);
  41453. setMouseCursor (MouseCursor::DraggingHandCursor);
  41454. }
  41455. ~ItemDragAndDropOverlayComponent()
  41456. {
  41457. }
  41458. void paint (Graphics& g)
  41459. {
  41460. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  41461. if (isMouseOverOrDragging()
  41462. && tc != 0
  41463. && tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  41464. {
  41465. g.setColour (findColour (Toolbar::editingModeOutlineColourId, true));
  41466. g.drawRect (0, 0, getWidth(), getHeight(),
  41467. jmin (2, (getWidth() - 1) / 2, (getHeight() - 1) / 2));
  41468. }
  41469. }
  41470. void mouseDown (const MouseEvent& e)
  41471. {
  41472. isDragging = false;
  41473. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  41474. if (tc != 0)
  41475. {
  41476. tc->dragOffsetX = e.x;
  41477. tc->dragOffsetY = e.y;
  41478. }
  41479. }
  41480. void mouseDrag (const MouseEvent& e)
  41481. {
  41482. if (! (isDragging || e.mouseWasClicked()))
  41483. {
  41484. isDragging = true;
  41485. DragAndDropContainer* const dnd = DragAndDropContainer::findParentDragContainerFor (this);
  41486. if (dnd != 0)
  41487. {
  41488. dnd->startDragging (Toolbar::toolbarDragDescriptor, getParentComponent(), 0, true);
  41489. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  41490. if (tc != 0)
  41491. {
  41492. tc->isBeingDragged = true;
  41493. if (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  41494. tc->setVisible (false);
  41495. }
  41496. }
  41497. }
  41498. }
  41499. void mouseUp (const MouseEvent&)
  41500. {
  41501. isDragging = false;
  41502. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  41503. if (tc != 0)
  41504. {
  41505. tc->isBeingDragged = false;
  41506. Toolbar* const tb = tc->getToolbar();
  41507. if (tb != 0)
  41508. tb->updateAllItemPositions (true);
  41509. else if (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  41510. delete tc;
  41511. }
  41512. }
  41513. void parentSizeChanged()
  41514. {
  41515. setBounds (0, 0, getParentWidth(), getParentHeight());
  41516. }
  41517. juce_UseDebuggingNewOperator
  41518. private:
  41519. bool isDragging;
  41520. ItemDragAndDropOverlayComponent (const ItemDragAndDropOverlayComponent&);
  41521. const ItemDragAndDropOverlayComponent& operator= (const ItemDragAndDropOverlayComponent&);
  41522. };
  41523. ToolbarItemComponent::ToolbarItemComponent (const int itemId_,
  41524. const String& labelText,
  41525. const bool isBeingUsedAsAButton_)
  41526. : Button (labelText),
  41527. itemId (itemId_),
  41528. mode (normalMode),
  41529. toolbarStyle (Toolbar::iconsOnly),
  41530. overlayComp (0),
  41531. dragOffsetX (0),
  41532. dragOffsetY (0),
  41533. isActive (true),
  41534. isBeingDragged (false),
  41535. isBeingUsedAsAButton (isBeingUsedAsAButton_)
  41536. {
  41537. // Your item ID can't be 0!
  41538. jassert (itemId_ != 0);
  41539. }
  41540. ToolbarItemComponent::~ToolbarItemComponent()
  41541. {
  41542. jassert (overlayComp == 0 || overlayComp->isValidComponent());
  41543. delete overlayComp;
  41544. }
  41545. Toolbar* ToolbarItemComponent::getToolbar() const
  41546. {
  41547. return dynamic_cast <Toolbar*> (getParentComponent());
  41548. }
  41549. bool ToolbarItemComponent::isToolbarVertical() const
  41550. {
  41551. const Toolbar* const t = getToolbar();
  41552. return t != 0 && t->isVertical();
  41553. }
  41554. void ToolbarItemComponent::setStyle (const Toolbar::ToolbarItemStyle& newStyle)
  41555. {
  41556. if (toolbarStyle != newStyle)
  41557. {
  41558. toolbarStyle = newStyle;
  41559. repaint();
  41560. resized();
  41561. }
  41562. }
  41563. void ToolbarItemComponent::paintButton (Graphics& g, bool isMouseOver, bool isMouseDown)
  41564. {
  41565. if (isBeingUsedAsAButton)
  41566. getLookAndFeel().paintToolbarButtonBackground (g, getWidth(), getHeight(),
  41567. isMouseOver, isMouseDown, *this);
  41568. if (toolbarStyle != Toolbar::iconsOnly)
  41569. {
  41570. const int indent = contentArea.getX();
  41571. int y = indent;
  41572. int h = getHeight() - indent * 2;
  41573. if (toolbarStyle == Toolbar::iconsWithText)
  41574. {
  41575. y = contentArea.getBottom() + indent / 2;
  41576. h -= contentArea.getHeight();
  41577. }
  41578. getLookAndFeel().paintToolbarButtonLabel (g, indent, y, getWidth() - indent * 2, h,
  41579. getButtonText(), *this);
  41580. }
  41581. if (! contentArea.isEmpty())
  41582. {
  41583. g.saveState();
  41584. g.setOrigin (contentArea.getX(), contentArea.getY());
  41585. g.reduceClipRegion (0, 0, contentArea.getWidth(), contentArea.getHeight());
  41586. paintButtonArea (g, contentArea.getWidth(), contentArea.getHeight(), isMouseOver, isMouseDown);
  41587. g.restoreState();
  41588. }
  41589. }
  41590. void ToolbarItemComponent::resized()
  41591. {
  41592. if (toolbarStyle != Toolbar::textOnly)
  41593. {
  41594. const int indent = jmin (proportionOfWidth (0.08f),
  41595. proportionOfHeight (0.08f));
  41596. contentArea = Rectangle (indent, indent,
  41597. getWidth() - indent * 2,
  41598. toolbarStyle == Toolbar::iconsWithText ? proportionOfHeight (0.55f)
  41599. : (getHeight() - indent * 2));
  41600. }
  41601. else
  41602. {
  41603. contentArea = Rectangle();
  41604. }
  41605. contentAreaChanged (contentArea);
  41606. }
  41607. void ToolbarItemComponent::setEditingMode (const ToolbarEditingMode newMode)
  41608. {
  41609. if (mode != newMode)
  41610. {
  41611. mode = newMode;
  41612. repaint();
  41613. if (mode == normalMode)
  41614. {
  41615. jassert (overlayComp == 0 || overlayComp->isValidComponent());
  41616. delete overlayComp;
  41617. overlayComp = 0;
  41618. }
  41619. else if (overlayComp == 0)
  41620. {
  41621. addAndMakeVisible (overlayComp = new ItemDragAndDropOverlayComponent());
  41622. overlayComp->parentSizeChanged();
  41623. }
  41624. resized();
  41625. }
  41626. }
  41627. END_JUCE_NAMESPACE
  41628. /********* End of inlined file: juce_ToolbarItemComponent.cpp *********/
  41629. /********* Start of inlined file: juce_ToolbarItemPalette.cpp *********/
  41630. BEGIN_JUCE_NAMESPACE
  41631. ToolbarItemPalette::ToolbarItemPalette (ToolbarItemFactory& factory_,
  41632. Toolbar* const toolbar_)
  41633. : factory (factory_),
  41634. toolbar (toolbar_)
  41635. {
  41636. Component* const itemHolder = new Component();
  41637. Array <int> allIds;
  41638. factory_.getAllToolbarItemIds (allIds);
  41639. for (int i = 0; i < allIds.size(); ++i)
  41640. {
  41641. ToolbarItemComponent* const tc = Toolbar::createItem (factory_, allIds.getUnchecked (i));
  41642. jassert (tc != 0);
  41643. if (tc != 0)
  41644. {
  41645. itemHolder->addAndMakeVisible (tc);
  41646. tc->setEditingMode (ToolbarItemComponent::editableOnPalette);
  41647. }
  41648. }
  41649. viewport = new Viewport();
  41650. viewport->setViewedComponent (itemHolder);
  41651. addAndMakeVisible (viewport);
  41652. }
  41653. ToolbarItemPalette::~ToolbarItemPalette()
  41654. {
  41655. viewport->getViewedComponent()->deleteAllChildren();
  41656. deleteAllChildren();
  41657. }
  41658. void ToolbarItemPalette::resized()
  41659. {
  41660. viewport->setBoundsInset (BorderSize (1));
  41661. Component* const itemHolder = viewport->getViewedComponent();
  41662. const int indent = 8;
  41663. const int preferredWidth = viewport->getWidth() - viewport->getScrollBarThickness() - indent;
  41664. const int height = toolbar->getThickness();
  41665. int x = indent;
  41666. int y = indent;
  41667. int maxX = 0;
  41668. for (int i = 0; i < itemHolder->getNumChildComponents(); ++i)
  41669. {
  41670. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (itemHolder->getChildComponent (i));
  41671. if (tc != 0)
  41672. {
  41673. tc->setStyle (toolbar->getStyle());
  41674. int preferredSize = 1, minSize = 1, maxSize = 1;
  41675. if (tc->getToolbarItemSizes (height, false, preferredSize, minSize, maxSize))
  41676. {
  41677. if (x + preferredSize > preferredWidth && x > indent)
  41678. {
  41679. x = indent;
  41680. y += height;
  41681. }
  41682. tc->setBounds (x, y, preferredSize, height);
  41683. x += preferredSize + 8;
  41684. maxX = jmax (maxX, x);
  41685. }
  41686. }
  41687. }
  41688. itemHolder->setSize (maxX, y + height + 8);
  41689. }
  41690. void ToolbarItemPalette::replaceComponent (ToolbarItemComponent* const comp)
  41691. {
  41692. ToolbarItemComponent* const tc = Toolbar::createItem (factory, comp->getItemId());
  41693. jassert (tc != 0);
  41694. if (tc != 0)
  41695. {
  41696. tc->setBounds (comp->getBounds());
  41697. tc->setStyle (toolbar->getStyle());
  41698. tc->setEditingMode (comp->getEditingMode());
  41699. viewport->getViewedComponent()->addAndMakeVisible (tc, getIndexOfChildComponent (comp));
  41700. }
  41701. }
  41702. END_JUCE_NAMESPACE
  41703. /********* End of inlined file: juce_ToolbarItemPalette.cpp *********/
  41704. /********* Start of inlined file: juce_TreeView.cpp *********/
  41705. BEGIN_JUCE_NAMESPACE
  41706. class TreeViewContentComponent : public Component,
  41707. public TooltipClient
  41708. {
  41709. public:
  41710. TreeViewContentComponent (TreeView* const owner_)
  41711. : owner (owner_),
  41712. buttonUnderMouse (0),
  41713. isDragging (false)
  41714. {
  41715. }
  41716. ~TreeViewContentComponent()
  41717. {
  41718. deleteAllChildren();
  41719. }
  41720. void mouseDown (const MouseEvent& e)
  41721. {
  41722. updateButtonUnderMouse (e);
  41723. isDragging = false;
  41724. needSelectionOnMouseUp = false;
  41725. Rectangle pos;
  41726. TreeViewItem* const item = findItemAt (e.y, pos);
  41727. if (item == 0)
  41728. return;
  41729. // (if the open/close buttons are hidden, we'll treat clicks to the left of the item
  41730. // as selection clicks)
  41731. if (e.x < pos.getX() && owner->openCloseButtonsVisible)
  41732. {
  41733. if (e.x >= pos.getX() - owner->getIndentSize())
  41734. item->setOpen (! item->isOpen());
  41735. // (clicks to the left of an open/close button are ignored)
  41736. }
  41737. else
  41738. {
  41739. // mouse-down inside the body of the item..
  41740. if (! owner->isMultiSelectEnabled())
  41741. item->setSelected (true, true);
  41742. else if (item->isSelected())
  41743. needSelectionOnMouseUp = ! e.mods.isPopupMenu();
  41744. else
  41745. selectBasedOnModifiers (item, e.mods);
  41746. MouseEvent e2 (e);
  41747. e2.x -= pos.getX();
  41748. e2.y -= pos.getY();
  41749. if (e2.x >= 0)
  41750. item->itemClicked (e2);
  41751. }
  41752. }
  41753. void mouseUp (const MouseEvent& e)
  41754. {
  41755. updateButtonUnderMouse (e);
  41756. if (needSelectionOnMouseUp && e.mouseWasClicked())
  41757. {
  41758. Rectangle pos;
  41759. TreeViewItem* const item = findItemAt (e.y, pos);
  41760. if (item != 0)
  41761. selectBasedOnModifiers (item, e.mods);
  41762. }
  41763. }
  41764. void mouseDoubleClick (const MouseEvent& e)
  41765. {
  41766. if (e.getNumberOfClicks() != 3) // ignore triple clicks
  41767. {
  41768. Rectangle pos;
  41769. TreeViewItem* const item = findItemAt (e.y, pos);
  41770. if (item != 0 && (e.x >= pos.getX() || ! owner->openCloseButtonsVisible))
  41771. {
  41772. MouseEvent e2 (e);
  41773. e2.x -= pos.getX();
  41774. e2.y -= pos.getY();
  41775. item->itemDoubleClicked (e2);
  41776. }
  41777. }
  41778. }
  41779. void mouseDrag (const MouseEvent& e)
  41780. {
  41781. if (isEnabled() && ! (e.mouseWasClicked() || isDragging))
  41782. {
  41783. isDragging = true;
  41784. Rectangle pos;
  41785. TreeViewItem* const item = findItemAt (e.getMouseDownY(), pos);
  41786. if (item != 0 && e.getMouseDownX() >= pos.getX())
  41787. {
  41788. const String dragDescription (item->getDragSourceDescription());
  41789. if (dragDescription.isNotEmpty())
  41790. {
  41791. DragAndDropContainer* const dragContainer
  41792. = DragAndDropContainer::findParentDragContainerFor (this);
  41793. if (dragContainer != 0)
  41794. {
  41795. pos.setSize (pos.getWidth(), item->itemHeight);
  41796. Image* dragImage = Component::createComponentSnapshot (pos, true);
  41797. dragImage->multiplyAllAlphas (0.6f);
  41798. dragContainer->startDragging (dragDescription, owner, dragImage, true);
  41799. }
  41800. else
  41801. {
  41802. // to be able to do a drag-and-drop operation, the treeview needs to
  41803. // be inside a component which is also a DragAndDropContainer.
  41804. jassertfalse
  41805. }
  41806. }
  41807. }
  41808. }
  41809. }
  41810. void mouseMove (const MouseEvent& e)
  41811. {
  41812. updateButtonUnderMouse (e);
  41813. }
  41814. void mouseExit (const MouseEvent& e)
  41815. {
  41816. updateButtonUnderMouse (e);
  41817. }
  41818. void paint (Graphics& g);
  41819. TreeViewItem* findItemAt (int y, Rectangle& itemPosition) const;
  41820. void updateComponents()
  41821. {
  41822. const int visibleTop = -getY();
  41823. const int visibleBottom = visibleTop + getParentHeight();
  41824. BitArray itemsToKeep;
  41825. TreeViewItem* item = owner->rootItem;
  41826. int y = (item != 0 && !owner->rootItemVisible) ? -item->itemHeight : 0;
  41827. while (item != 0 && y < visibleBottom)
  41828. {
  41829. y += item->itemHeight;
  41830. if (y >= visibleTop)
  41831. {
  41832. const int index = rowComponentIds.indexOf (item->uid);
  41833. if (index < 0)
  41834. {
  41835. Component* const comp = item->createItemComponent();
  41836. if (comp != 0)
  41837. {
  41838. addAndMakeVisible (comp);
  41839. itemsToKeep.setBit (rowComponentItems.size());
  41840. rowComponentItems.add (item);
  41841. rowComponentIds.add (item->uid);
  41842. rowComponents.add (comp);
  41843. }
  41844. }
  41845. else
  41846. {
  41847. itemsToKeep.setBit (index);
  41848. }
  41849. }
  41850. item = item->getNextVisibleItem (true);
  41851. }
  41852. for (int i = rowComponentItems.size(); --i >= 0;)
  41853. {
  41854. Component* const comp = (Component*) (rowComponents.getUnchecked(i));
  41855. bool keep = false;
  41856. if ((itemsToKeep[i] || (comp == Component::getComponentUnderMouse() && comp->isMouseButtonDown()))
  41857. && isParentOf (comp))
  41858. {
  41859. if (itemsToKeep[i])
  41860. {
  41861. const TreeViewItem* const item = (TreeViewItem*) rowComponentItems.getUnchecked(i);
  41862. Rectangle pos (item->getItemPosition (false));
  41863. pos.setSize (pos.getWidth(), item->itemHeight);
  41864. if (pos.getBottom() >= visibleTop && pos.getY() < visibleBottom)
  41865. {
  41866. keep = true;
  41867. comp->setBounds (pos);
  41868. }
  41869. }
  41870. else
  41871. {
  41872. comp->setSize (0, 0);
  41873. }
  41874. }
  41875. if (! keep)
  41876. {
  41877. delete comp;
  41878. rowComponents.remove (i);
  41879. rowComponentIds.remove (i);
  41880. rowComponentItems.remove (i);
  41881. }
  41882. }
  41883. }
  41884. void updateButtonUnderMouse (const MouseEvent& e)
  41885. {
  41886. TreeViewItem* newItem = 0;
  41887. if (owner->openCloseButtonsVisible)
  41888. {
  41889. Rectangle pos;
  41890. TreeViewItem* item = findItemAt (e.y, pos);
  41891. if (item != 0 && e.x < pos.getX() && e.x >= pos.getX() - owner->getIndentSize())
  41892. {
  41893. newItem = item;
  41894. if (! newItem->mightContainSubItems())
  41895. newItem = 0;
  41896. }
  41897. }
  41898. if (buttonUnderMouse != newItem)
  41899. {
  41900. if (buttonUnderMouse != 0 && containsItem (buttonUnderMouse))
  41901. {
  41902. const Rectangle r (buttonUnderMouse->getItemPosition (false));
  41903. repaint (0, r.getY(), r.getX(), buttonUnderMouse->getItemHeight());
  41904. }
  41905. buttonUnderMouse = newItem;
  41906. if (buttonUnderMouse != 0)
  41907. {
  41908. const Rectangle r (buttonUnderMouse->getItemPosition (false));
  41909. repaint (0, r.getY(), r.getX(), buttonUnderMouse->getItemHeight());
  41910. }
  41911. }
  41912. }
  41913. bool isMouseOverButton (TreeViewItem* item) const throw()
  41914. {
  41915. return item == buttonUnderMouse;
  41916. }
  41917. void resized()
  41918. {
  41919. owner->itemsChanged();
  41920. }
  41921. const String getTooltip()
  41922. {
  41923. int x, y;
  41924. getMouseXYRelative (x, y);
  41925. Rectangle pos;
  41926. TreeViewItem* const item = findItemAt (y, pos);
  41927. if (item != 0)
  41928. return item->getTooltip();
  41929. return owner->getTooltip();
  41930. }
  41931. juce_UseDebuggingNewOperator
  41932. private:
  41933. TreeView* const owner;
  41934. VoidArray rowComponentItems;
  41935. Array <int> rowComponentIds;
  41936. VoidArray rowComponents;
  41937. TreeViewItem* buttonUnderMouse;
  41938. bool isDragging, needSelectionOnMouseUp;
  41939. TreeViewContentComponent (const TreeViewContentComponent&);
  41940. const TreeViewContentComponent& operator= (const TreeViewContentComponent&);
  41941. void selectBasedOnModifiers (TreeViewItem* const item, const ModifierKeys& modifiers)
  41942. {
  41943. TreeViewItem* firstSelected = 0;
  41944. if (modifiers.isShiftDown() && ((firstSelected = owner->getSelectedItem (0)) != 0))
  41945. {
  41946. TreeViewItem* const lastSelected = owner->getSelectedItem (owner->getNumSelectedItems() - 1);
  41947. jassert (lastSelected != 0);
  41948. int rowStart = firstSelected->getRowNumberInTree();
  41949. int rowEnd = lastSelected->getRowNumberInTree();
  41950. if (rowStart > rowEnd)
  41951. swapVariables (rowStart, rowEnd);
  41952. int ourRow = item->getRowNumberInTree();
  41953. int otherEnd = ourRow < rowEnd ? rowStart : rowEnd;
  41954. if (ourRow > otherEnd)
  41955. swapVariables (ourRow, otherEnd);
  41956. for (int i = ourRow; i <= otherEnd; ++i)
  41957. owner->getItemOnRow (i)->setSelected (true, false);
  41958. }
  41959. else
  41960. {
  41961. const bool cmd = modifiers.isCommandDown();
  41962. item->setSelected ((! cmd) || (! item->isSelected()), ! cmd);
  41963. }
  41964. }
  41965. bool containsItem (TreeViewItem* const item) const
  41966. {
  41967. for (int i = rowComponentItems.size(); --i >= 0;)
  41968. if ((TreeViewItem*) rowComponentItems.getUnchecked (i) == item)
  41969. return true;
  41970. return false;
  41971. }
  41972. };
  41973. class TreeViewport : public Viewport
  41974. {
  41975. public:
  41976. TreeViewport() throw() {}
  41977. ~TreeViewport() throw() {}
  41978. void updateComponents()
  41979. {
  41980. if (getViewedComponent() != 0)
  41981. ((TreeViewContentComponent*) getViewedComponent())->updateComponents();
  41982. repaint();
  41983. }
  41984. void visibleAreaChanged (int, int, int, int)
  41985. {
  41986. updateComponents();
  41987. }
  41988. juce_UseDebuggingNewOperator
  41989. private:
  41990. TreeViewport (const TreeViewport&);
  41991. const TreeViewport& operator= (const TreeViewport&);
  41992. };
  41993. TreeView::TreeView (const String& componentName)
  41994. : Component (componentName),
  41995. rootItem (0),
  41996. indentSize (24),
  41997. defaultOpenness (false),
  41998. needsRecalculating (true),
  41999. rootItemVisible (true),
  42000. multiSelectEnabled (false),
  42001. openCloseButtonsVisible (true)
  42002. {
  42003. addAndMakeVisible (viewport = new TreeViewport());
  42004. viewport->setViewedComponent (new TreeViewContentComponent (this));
  42005. viewport->setWantsKeyboardFocus (false);
  42006. setWantsKeyboardFocus (true);
  42007. }
  42008. TreeView::~TreeView()
  42009. {
  42010. if (rootItem != 0)
  42011. rootItem->setOwnerView (0);
  42012. deleteAllChildren();
  42013. }
  42014. void TreeView::setRootItem (TreeViewItem* const newRootItem)
  42015. {
  42016. if (rootItem != newRootItem)
  42017. {
  42018. if (newRootItem != 0)
  42019. {
  42020. jassert (newRootItem->ownerView == 0); // can't use a tree item in more than one tree at once..
  42021. if (newRootItem->ownerView != 0)
  42022. newRootItem->ownerView->setRootItem (0);
  42023. }
  42024. if (rootItem != 0)
  42025. rootItem->setOwnerView (0);
  42026. rootItem = newRootItem;
  42027. if (newRootItem != 0)
  42028. newRootItem->setOwnerView (this);
  42029. needsRecalculating = true;
  42030. handleAsyncUpdate();
  42031. if (rootItem != 0 && (defaultOpenness || ! rootItemVisible))
  42032. {
  42033. rootItem->setOpen (false); // force a re-open
  42034. rootItem->setOpen (true);
  42035. }
  42036. }
  42037. }
  42038. void TreeView::deleteRootItem()
  42039. {
  42040. TreeViewItem* const oldItem = rootItem;
  42041. setRootItem (0);
  42042. delete oldItem;
  42043. }
  42044. void TreeView::setRootItemVisible (const bool shouldBeVisible)
  42045. {
  42046. rootItemVisible = shouldBeVisible;
  42047. if (rootItem != 0 && (defaultOpenness || ! rootItemVisible))
  42048. {
  42049. rootItem->setOpen (false); // force a re-open
  42050. rootItem->setOpen (true);
  42051. }
  42052. itemsChanged();
  42053. }
  42054. void TreeView::colourChanged()
  42055. {
  42056. setOpaque (findColour (backgroundColourId).isOpaque());
  42057. repaint();
  42058. }
  42059. void TreeView::setIndentSize (const int newIndentSize)
  42060. {
  42061. if (indentSize != newIndentSize)
  42062. {
  42063. indentSize = newIndentSize;
  42064. resized();
  42065. }
  42066. }
  42067. void TreeView::setDefaultOpenness (const bool isOpenByDefault)
  42068. {
  42069. if (defaultOpenness != isOpenByDefault)
  42070. {
  42071. defaultOpenness = isOpenByDefault;
  42072. itemsChanged();
  42073. }
  42074. }
  42075. void TreeView::setMultiSelectEnabled (const bool canMultiSelect)
  42076. {
  42077. multiSelectEnabled = canMultiSelect;
  42078. }
  42079. void TreeView::setOpenCloseButtonsVisible (const bool shouldBeVisible)
  42080. {
  42081. if (openCloseButtonsVisible != shouldBeVisible)
  42082. {
  42083. openCloseButtonsVisible = shouldBeVisible;
  42084. itemsChanged();
  42085. }
  42086. }
  42087. void TreeView::clearSelectedItems()
  42088. {
  42089. if (rootItem != 0)
  42090. rootItem->deselectAllRecursively();
  42091. }
  42092. int TreeView::getNumSelectedItems() const throw()
  42093. {
  42094. return (rootItem != 0) ? rootItem->countSelectedItemsRecursively() : 0;
  42095. }
  42096. TreeViewItem* TreeView::getSelectedItem (const int index) const throw()
  42097. {
  42098. return (rootItem != 0) ? rootItem->getSelectedItemWithIndex (index) : 0;
  42099. }
  42100. int TreeView::getNumRowsInTree() const
  42101. {
  42102. if (rootItem != 0)
  42103. return rootItem->getNumRows() - (rootItemVisible ? 0 : 1);
  42104. return 0;
  42105. }
  42106. TreeViewItem* TreeView::getItemOnRow (int index) const
  42107. {
  42108. if (! rootItemVisible)
  42109. ++index;
  42110. if (rootItem != 0 && index >= 0)
  42111. return rootItem->getItemOnRow (index);
  42112. return 0;
  42113. }
  42114. XmlElement* TreeView::getOpennessState (const bool alsoIncludeScrollPosition) const
  42115. {
  42116. XmlElement* e = 0;
  42117. if (rootItem != 0)
  42118. {
  42119. e = rootItem->createXmlOpenness();
  42120. if (e != 0 && alsoIncludeScrollPosition)
  42121. e->setAttribute (T("scrollPos"), viewport->getViewPositionY());
  42122. }
  42123. return e;
  42124. }
  42125. void TreeView::restoreOpennessState (const XmlElement& newState)
  42126. {
  42127. if (rootItem != 0)
  42128. {
  42129. rootItem->restoreFromXml (newState);
  42130. if (newState.hasAttribute (T("scrollPos")))
  42131. viewport->setViewPosition (viewport->getViewPositionX(),
  42132. newState.getIntAttribute (T("scrollPos")));
  42133. }
  42134. }
  42135. void TreeView::paint (Graphics& g)
  42136. {
  42137. g.fillAll (findColour (backgroundColourId));
  42138. }
  42139. void TreeView::resized()
  42140. {
  42141. viewport->setBounds (0, 0, getWidth(), getHeight());
  42142. itemsChanged();
  42143. handleAsyncUpdate();
  42144. }
  42145. void TreeView::enablementChanged()
  42146. {
  42147. repaint();
  42148. }
  42149. void TreeView::moveSelectedRow (int delta)
  42150. {
  42151. if (delta == 0)
  42152. return;
  42153. int rowSelected = 0;
  42154. TreeViewItem* const firstSelected = getSelectedItem (0);
  42155. if (firstSelected != 0)
  42156. rowSelected = firstSelected->getRowNumberInTree();
  42157. rowSelected = jlimit (0, getNumRowsInTree() - 1, rowSelected + delta);
  42158. for (;;)
  42159. {
  42160. TreeViewItem* item = getItemOnRow (rowSelected);
  42161. if (item != 0)
  42162. {
  42163. if (! item->canBeSelected())
  42164. {
  42165. // if the row we want to highlight doesn't allow it, try skipping
  42166. // to the next item..
  42167. const int nextRowToTry = jlimit (0, getNumRowsInTree() - 1,
  42168. rowSelected + (delta < 0 ? -1 : 1));
  42169. if (rowSelected != nextRowToTry)
  42170. {
  42171. rowSelected = nextRowToTry;
  42172. continue;
  42173. }
  42174. else
  42175. {
  42176. break;
  42177. }
  42178. }
  42179. item->setSelected (true, true);
  42180. scrollToKeepItemVisible (item);
  42181. }
  42182. break;
  42183. }
  42184. }
  42185. void TreeView::scrollToKeepItemVisible (TreeViewItem* item)
  42186. {
  42187. if (item != 0 && item->ownerView == this)
  42188. {
  42189. handleAsyncUpdate();
  42190. item = item->getDeepestOpenParentItem();
  42191. int y = item->y;
  42192. int viewTop = viewport->getViewPositionY();
  42193. if (y < viewTop)
  42194. {
  42195. viewport->setViewPosition (viewport->getViewPositionX(), y);
  42196. }
  42197. else if (y + item->itemHeight > viewTop + viewport->getViewHeight())
  42198. {
  42199. viewport->setViewPosition (viewport->getViewPositionX(),
  42200. (y + item->itemHeight) - viewport->getViewHeight());
  42201. }
  42202. }
  42203. }
  42204. bool TreeView::keyPressed (const KeyPress& key)
  42205. {
  42206. if (key.isKeyCode (KeyPress::upKey))
  42207. {
  42208. moveSelectedRow (-1);
  42209. }
  42210. else if (key.isKeyCode (KeyPress::downKey))
  42211. {
  42212. moveSelectedRow (1);
  42213. }
  42214. else if (key.isKeyCode (KeyPress::pageDownKey) || key.isKeyCode (KeyPress::pageUpKey))
  42215. {
  42216. if (rootItem != 0)
  42217. {
  42218. int rowsOnScreen = getHeight() / jmax (1, rootItem->itemHeight);
  42219. if (key.isKeyCode (KeyPress::pageUpKey))
  42220. rowsOnScreen = -rowsOnScreen;
  42221. moveSelectedRow (rowsOnScreen);
  42222. }
  42223. }
  42224. else if (key.isKeyCode (KeyPress::homeKey))
  42225. {
  42226. moveSelectedRow (-0x3fffffff);
  42227. }
  42228. else if (key.isKeyCode (KeyPress::endKey))
  42229. {
  42230. moveSelectedRow (0x3fffffff);
  42231. }
  42232. else if (key.isKeyCode (KeyPress::returnKey))
  42233. {
  42234. TreeViewItem* const firstSelected = getSelectedItem (0);
  42235. if (firstSelected != 0)
  42236. firstSelected->setOpen (! firstSelected->isOpen());
  42237. }
  42238. else if (key.isKeyCode (KeyPress::leftKey))
  42239. {
  42240. TreeViewItem* const firstSelected = getSelectedItem (0);
  42241. if (firstSelected != 0)
  42242. {
  42243. if (firstSelected->isOpen())
  42244. {
  42245. firstSelected->setOpen (false);
  42246. }
  42247. else
  42248. {
  42249. TreeViewItem* parent = firstSelected->parentItem;
  42250. if ((! rootItemVisible) && parent == rootItem)
  42251. parent = 0;
  42252. if (parent != 0)
  42253. {
  42254. parent->setSelected (true, true);
  42255. scrollToKeepItemVisible (parent);
  42256. }
  42257. }
  42258. }
  42259. }
  42260. else if (key.isKeyCode (KeyPress::rightKey))
  42261. {
  42262. TreeViewItem* const firstSelected = getSelectedItem (0);
  42263. if (firstSelected != 0)
  42264. {
  42265. if (firstSelected->isOpen() || ! firstSelected->mightContainSubItems())
  42266. moveSelectedRow (1);
  42267. else
  42268. firstSelected->setOpen (true);
  42269. }
  42270. }
  42271. else
  42272. {
  42273. return false;
  42274. }
  42275. return true;
  42276. }
  42277. void TreeView::itemsChanged() throw()
  42278. {
  42279. needsRecalculating = true;
  42280. repaint();
  42281. triggerAsyncUpdate();
  42282. }
  42283. void TreeView::handleAsyncUpdate()
  42284. {
  42285. if (needsRecalculating)
  42286. {
  42287. needsRecalculating = false;
  42288. const ScopedLock sl (nodeAlterationLock);
  42289. if (rootItem != 0)
  42290. rootItem->updatePositions (rootItemVisible ? 0 : -rootItem->itemHeight);
  42291. ((TreeViewport*) viewport)->updateComponents();
  42292. if (rootItem != 0)
  42293. {
  42294. viewport->getViewedComponent()
  42295. ->setSize (jmax (viewport->getMaximumVisibleWidth(), rootItem->totalWidth),
  42296. rootItem->totalHeight - (rootItemVisible ? 0 : rootItem->itemHeight));
  42297. }
  42298. else
  42299. {
  42300. viewport->getViewedComponent()->setSize (0, 0);
  42301. }
  42302. }
  42303. }
  42304. void TreeViewContentComponent::paint (Graphics& g)
  42305. {
  42306. if (owner->rootItem != 0)
  42307. {
  42308. owner->handleAsyncUpdate();
  42309. if (! owner->rootItemVisible)
  42310. g.setOrigin (0, -owner->rootItem->itemHeight);
  42311. owner->rootItem->paintRecursively (g, getWidth());
  42312. }
  42313. }
  42314. TreeViewItem* TreeViewContentComponent::findItemAt (int y, Rectangle& itemPosition) const
  42315. {
  42316. if (owner->rootItem != 0)
  42317. {
  42318. owner->handleAsyncUpdate();
  42319. if (! owner->rootItemVisible)
  42320. y += owner->rootItem->itemHeight;
  42321. TreeViewItem* const ti = owner->rootItem->findItemRecursively (y);
  42322. if (ti != 0)
  42323. itemPosition = ti->getItemPosition (false);
  42324. return ti;
  42325. }
  42326. return 0;
  42327. }
  42328. #define opennessDefault 0
  42329. #define opennessClosed 1
  42330. #define opennessOpen 2
  42331. TreeViewItem::TreeViewItem()
  42332. : ownerView (0),
  42333. parentItem (0),
  42334. subItems (8),
  42335. y (0),
  42336. itemHeight (0),
  42337. totalHeight (0),
  42338. selected (false),
  42339. redrawNeeded (true),
  42340. drawLinesInside (true),
  42341. drawsInLeftMargin (false),
  42342. openness (opennessDefault)
  42343. {
  42344. static int nextUID = 0;
  42345. uid = nextUID++;
  42346. }
  42347. TreeViewItem::~TreeViewItem()
  42348. {
  42349. }
  42350. const String TreeViewItem::getUniqueName() const
  42351. {
  42352. return String::empty;
  42353. }
  42354. void TreeViewItem::itemOpennessChanged (bool)
  42355. {
  42356. }
  42357. int TreeViewItem::getNumSubItems() const throw()
  42358. {
  42359. return subItems.size();
  42360. }
  42361. TreeViewItem* TreeViewItem::getSubItem (const int index) const throw()
  42362. {
  42363. return subItems [index];
  42364. }
  42365. void TreeViewItem::clearSubItems()
  42366. {
  42367. if (subItems.size() > 0)
  42368. {
  42369. if (ownerView != 0)
  42370. {
  42371. const ScopedLock sl (ownerView->nodeAlterationLock);
  42372. subItems.clear();
  42373. treeHasChanged();
  42374. }
  42375. else
  42376. {
  42377. subItems.clear();
  42378. }
  42379. }
  42380. }
  42381. void TreeViewItem::addSubItem (TreeViewItem* const newItem, const int insertPosition)
  42382. {
  42383. if (newItem != 0)
  42384. {
  42385. newItem->parentItem = this;
  42386. newItem->setOwnerView (ownerView);
  42387. newItem->y = 0;
  42388. newItem->itemHeight = newItem->getItemHeight();
  42389. newItem->totalHeight = 0;
  42390. newItem->itemWidth = newItem->getItemWidth();
  42391. newItem->totalWidth = 0;
  42392. if (ownerView != 0)
  42393. {
  42394. const ScopedLock sl (ownerView->nodeAlterationLock);
  42395. subItems.insert (insertPosition, newItem);
  42396. treeHasChanged();
  42397. if (newItem->isOpen())
  42398. newItem->itemOpennessChanged (true);
  42399. }
  42400. else
  42401. {
  42402. subItems.insert (insertPosition, newItem);
  42403. if (newItem->isOpen())
  42404. newItem->itemOpennessChanged (true);
  42405. }
  42406. }
  42407. }
  42408. void TreeViewItem::removeSubItem (const int index, const bool deleteItem)
  42409. {
  42410. if (ownerView != 0)
  42411. ownerView->nodeAlterationLock.enter();
  42412. if (((unsigned int) index) < (unsigned int) subItems.size())
  42413. {
  42414. subItems.remove (index, deleteItem);
  42415. treeHasChanged();
  42416. }
  42417. if (ownerView != 0)
  42418. ownerView->nodeAlterationLock.exit();
  42419. }
  42420. bool TreeViewItem::isOpen() const throw()
  42421. {
  42422. if (openness == opennessDefault)
  42423. return ownerView != 0 && ownerView->defaultOpenness;
  42424. else
  42425. return openness == opennessOpen;
  42426. }
  42427. void TreeViewItem::setOpen (const bool shouldBeOpen)
  42428. {
  42429. if (isOpen() != shouldBeOpen)
  42430. {
  42431. openness = shouldBeOpen ? opennessOpen
  42432. : opennessClosed;
  42433. treeHasChanged();
  42434. itemOpennessChanged (isOpen());
  42435. }
  42436. }
  42437. bool TreeViewItem::isSelected() const throw()
  42438. {
  42439. return selected;
  42440. }
  42441. void TreeViewItem::deselectAllRecursively()
  42442. {
  42443. setSelected (false, false);
  42444. for (int i = 0; i < subItems.size(); ++i)
  42445. subItems.getUnchecked(i)->deselectAllRecursively();
  42446. }
  42447. void TreeViewItem::setSelected (const bool shouldBeSelected,
  42448. const bool deselectOtherItemsFirst)
  42449. {
  42450. if (shouldBeSelected && ! canBeSelected())
  42451. return;
  42452. if (deselectOtherItemsFirst)
  42453. getTopLevelItem()->deselectAllRecursively();
  42454. if (shouldBeSelected != selected)
  42455. {
  42456. selected = shouldBeSelected;
  42457. if (ownerView != 0)
  42458. ownerView->repaint();
  42459. itemSelectionChanged (shouldBeSelected);
  42460. }
  42461. }
  42462. void TreeViewItem::paintItem (Graphics&, int, int)
  42463. {
  42464. }
  42465. void TreeViewItem::paintOpenCloseButton (Graphics& g, int width, int height, bool isMouseOver)
  42466. {
  42467. ownerView->getLookAndFeel()
  42468. .drawTreeviewPlusMinusBox (g, 0, 0, width, height, ! isOpen(), isMouseOver);
  42469. }
  42470. void TreeViewItem::itemClicked (const MouseEvent&)
  42471. {
  42472. }
  42473. void TreeViewItem::itemDoubleClicked (const MouseEvent&)
  42474. {
  42475. if (mightContainSubItems())
  42476. setOpen (! isOpen());
  42477. }
  42478. void TreeViewItem::itemSelectionChanged (bool)
  42479. {
  42480. }
  42481. const String TreeViewItem::getTooltip()
  42482. {
  42483. return String::empty;
  42484. }
  42485. const String TreeViewItem::getDragSourceDescription()
  42486. {
  42487. return String::empty;
  42488. }
  42489. const Rectangle TreeViewItem::getItemPosition (const bool relativeToTreeViewTopLeft) const throw()
  42490. {
  42491. const int indentX = getIndentX();
  42492. int width = itemWidth;
  42493. if (ownerView != 0 && width < 0)
  42494. width = ownerView->viewport->getViewWidth() - indentX;
  42495. Rectangle r (indentX, y, jmax (0, width), totalHeight);
  42496. if (relativeToTreeViewTopLeft)
  42497. r.setPosition (r.getX() - ownerView->viewport->getViewPositionX(),
  42498. r.getY() - ownerView->viewport->getViewPositionY());
  42499. return r;
  42500. }
  42501. void TreeViewItem::treeHasChanged() const throw()
  42502. {
  42503. if (ownerView != 0)
  42504. ownerView->itemsChanged();
  42505. }
  42506. void TreeViewItem::repaintItem() const
  42507. {
  42508. if (ownerView != 0 && areAllParentsOpen())
  42509. {
  42510. const Rectangle r (getItemPosition (true));
  42511. ownerView->viewport->repaint (0, r.getY(), r.getRight(), r.getHeight());
  42512. }
  42513. }
  42514. bool TreeViewItem::areAllParentsOpen() const throw()
  42515. {
  42516. return parentItem == 0
  42517. || (parentItem->isOpen() && parentItem->areAllParentsOpen());
  42518. }
  42519. void TreeViewItem::updatePositions (int newY)
  42520. {
  42521. y = newY;
  42522. itemHeight = getItemHeight();
  42523. totalHeight = itemHeight;
  42524. itemWidth = getItemWidth();
  42525. totalWidth = jmax (itemWidth, 0) + getIndentX();
  42526. if (isOpen())
  42527. {
  42528. newY += totalHeight;
  42529. for (int i = 0; i < subItems.size(); ++i)
  42530. {
  42531. TreeViewItem* const ti = subItems.getUnchecked(i);
  42532. ti->updatePositions (newY);
  42533. newY += ti->totalHeight;
  42534. totalHeight += ti->totalHeight;
  42535. totalWidth = jmax (totalWidth, ti->totalWidth);
  42536. }
  42537. }
  42538. }
  42539. TreeViewItem* TreeViewItem::getDeepestOpenParentItem() throw()
  42540. {
  42541. TreeViewItem* result = this;
  42542. TreeViewItem* item = this;
  42543. while (item->parentItem != 0)
  42544. {
  42545. item = item->parentItem;
  42546. if (! item->isOpen())
  42547. result = item;
  42548. }
  42549. return result;
  42550. }
  42551. void TreeViewItem::setOwnerView (TreeView* const newOwner) throw()
  42552. {
  42553. ownerView = newOwner;
  42554. for (int i = subItems.size(); --i >= 0;)
  42555. subItems.getUnchecked(i)->setOwnerView (newOwner);
  42556. }
  42557. int TreeViewItem::getIndentX() const throw()
  42558. {
  42559. const int indentWidth = ownerView->getIndentSize();
  42560. int x = ownerView->rootItemVisible ? indentWidth : 0;
  42561. if (! ownerView->openCloseButtonsVisible)
  42562. x -= indentWidth;
  42563. TreeViewItem* p = parentItem;
  42564. while (p != 0)
  42565. {
  42566. x += indentWidth;
  42567. p = p->parentItem;
  42568. }
  42569. return x;
  42570. }
  42571. void TreeViewItem::setDrawsInLeftMargin (bool canDrawInLeftMargin) throw()
  42572. {
  42573. drawsInLeftMargin = canDrawInLeftMargin;
  42574. }
  42575. void TreeViewItem::paintRecursively (Graphics& g, int width)
  42576. {
  42577. jassert (ownerView != 0);
  42578. if (ownerView == 0)
  42579. return;
  42580. const int indent = getIndentX();
  42581. const int itemW = itemWidth < 0 ? width - indent : itemWidth;
  42582. g.setColour (ownerView->findColour (TreeView::linesColourId));
  42583. const float halfH = itemHeight * 0.5f;
  42584. int depth = 0;
  42585. TreeViewItem* p = parentItem;
  42586. while (p != 0)
  42587. {
  42588. ++depth;
  42589. p = p->parentItem;
  42590. }
  42591. if (! ownerView->rootItemVisible)
  42592. --depth;
  42593. const int indentWidth = ownerView->getIndentSize();
  42594. if (depth >= 0 && ownerView->openCloseButtonsVisible)
  42595. {
  42596. float x = (depth + 0.5f) * indentWidth;
  42597. if (depth >= 0)
  42598. {
  42599. if (parentItem != 0 && parentItem->drawLinesInside)
  42600. g.drawLine (x, 0, x, isLastOfSiblings() ? halfH : (float) itemHeight);
  42601. if ((parentItem != 0 && parentItem->drawLinesInside)
  42602. || (parentItem == 0 && drawLinesInside))
  42603. g.drawLine (x, halfH, x + indentWidth / 2, halfH);
  42604. }
  42605. p = parentItem;
  42606. int d = depth;
  42607. while (p != 0 && --d >= 0)
  42608. {
  42609. x -= (float) indentWidth;
  42610. if ((p->parentItem == 0 || p->parentItem->drawLinesInside)
  42611. && ! p->isLastOfSiblings())
  42612. {
  42613. g.drawLine (x, 0, x, (float) itemHeight);
  42614. }
  42615. p = p->parentItem;
  42616. }
  42617. if (mightContainSubItems())
  42618. {
  42619. g.saveState();
  42620. g.setOrigin (depth * indentWidth, 0);
  42621. g.reduceClipRegion (0, 0, indentWidth, itemHeight);
  42622. paintOpenCloseButton (g, indentWidth, itemHeight,
  42623. ((TreeViewContentComponent*) ownerView->viewport->getViewedComponent())
  42624. ->isMouseOverButton (this));
  42625. g.restoreState();
  42626. }
  42627. }
  42628. {
  42629. g.saveState();
  42630. g.setOrigin (indent, 0);
  42631. if (g.reduceClipRegion (drawsInLeftMargin ? -indent : 0, 0,
  42632. drawsInLeftMargin ? itemW + indent : itemW, itemHeight))
  42633. paintItem (g, itemW, itemHeight);
  42634. g.restoreState();
  42635. }
  42636. if (isOpen())
  42637. {
  42638. const Rectangle clip (g.getClipBounds());
  42639. for (int i = 0; i < subItems.size(); ++i)
  42640. {
  42641. TreeViewItem* const ti = subItems.getUnchecked(i);
  42642. const int relY = ti->y - y;
  42643. if (relY >= clip.getBottom())
  42644. break;
  42645. if (relY + ti->totalHeight >= clip.getY())
  42646. {
  42647. g.saveState();
  42648. g.setOrigin (0, relY);
  42649. if (g.reduceClipRegion (0, 0, width, ti->totalHeight))
  42650. ti->paintRecursively (g, width);
  42651. g.restoreState();
  42652. }
  42653. }
  42654. }
  42655. }
  42656. bool TreeViewItem::isLastOfSiblings() const throw()
  42657. {
  42658. return parentItem == 0
  42659. || parentItem->subItems.getLast() == this;
  42660. }
  42661. TreeViewItem* TreeViewItem::getTopLevelItem() throw()
  42662. {
  42663. return (parentItem == 0) ? this
  42664. : parentItem->getTopLevelItem();
  42665. }
  42666. int TreeViewItem::getNumRows() const throw()
  42667. {
  42668. int num = 1;
  42669. if (isOpen())
  42670. {
  42671. for (int i = subItems.size(); --i >= 0;)
  42672. num += subItems.getUnchecked(i)->getNumRows();
  42673. }
  42674. return num;
  42675. }
  42676. TreeViewItem* TreeViewItem::getItemOnRow (int index) throw()
  42677. {
  42678. if (index == 0)
  42679. return this;
  42680. if (index > 0 && isOpen())
  42681. {
  42682. --index;
  42683. for (int i = 0; i < subItems.size(); ++i)
  42684. {
  42685. TreeViewItem* const item = subItems.getUnchecked(i);
  42686. if (index == 0)
  42687. return item;
  42688. const int numRows = item->getNumRows();
  42689. if (numRows > index)
  42690. return item->getItemOnRow (index);
  42691. index -= numRows;
  42692. }
  42693. }
  42694. return 0;
  42695. }
  42696. TreeViewItem* TreeViewItem::findItemRecursively (int y) throw()
  42697. {
  42698. if (((unsigned int) y) < (unsigned int) totalHeight)
  42699. {
  42700. const int h = itemHeight;
  42701. if (y < h)
  42702. return this;
  42703. if (isOpen())
  42704. {
  42705. y -= h;
  42706. for (int i = 0; i < subItems.size(); ++i)
  42707. {
  42708. TreeViewItem* const ti = subItems.getUnchecked(i);
  42709. if (ti->totalHeight >= y)
  42710. return ti->findItemRecursively (y);
  42711. y -= ti->totalHeight;
  42712. }
  42713. }
  42714. }
  42715. return 0;
  42716. }
  42717. int TreeViewItem::countSelectedItemsRecursively() const throw()
  42718. {
  42719. int total = 0;
  42720. if (isSelected())
  42721. ++total;
  42722. for (int i = subItems.size(); --i >= 0;)
  42723. total += subItems.getUnchecked(i)->countSelectedItemsRecursively();
  42724. return total;
  42725. }
  42726. TreeViewItem* TreeViewItem::getSelectedItemWithIndex (int index) throw()
  42727. {
  42728. if (isSelected())
  42729. {
  42730. if (index == 0)
  42731. return this;
  42732. --index;
  42733. }
  42734. if (index >= 0)
  42735. {
  42736. for (int i = 0; i < subItems.size(); ++i)
  42737. {
  42738. TreeViewItem* const item = subItems.getUnchecked(i);
  42739. TreeViewItem* const found = item->getSelectedItemWithIndex (index);
  42740. if (found != 0)
  42741. return found;
  42742. index -= item->countSelectedItemsRecursively();
  42743. }
  42744. }
  42745. return 0;
  42746. }
  42747. int TreeViewItem::getRowNumberInTree() const throw()
  42748. {
  42749. if (parentItem != 0 && ownerView != 0)
  42750. {
  42751. int n = 1 + parentItem->getRowNumberInTree();
  42752. int ourIndex = parentItem->subItems.indexOf (this);
  42753. jassert (ourIndex >= 0);
  42754. while (--ourIndex >= 0)
  42755. n += parentItem->subItems [ourIndex]->getNumRows();
  42756. if (parentItem->parentItem == 0
  42757. && ! ownerView->rootItemVisible)
  42758. --n;
  42759. return n;
  42760. }
  42761. else
  42762. {
  42763. return 0;
  42764. }
  42765. }
  42766. void TreeViewItem::setLinesDrawnForSubItems (const bool drawLines) throw()
  42767. {
  42768. drawLinesInside = drawLines;
  42769. }
  42770. TreeViewItem* TreeViewItem::getNextVisibleItem (const bool recurse) const throw()
  42771. {
  42772. if (recurse && isOpen() && subItems.size() > 0)
  42773. return subItems [0];
  42774. if (parentItem != 0)
  42775. {
  42776. const int nextIndex = parentItem->subItems.indexOf (this) + 1;
  42777. if (nextIndex >= parentItem->subItems.size())
  42778. return parentItem->getNextVisibleItem (false);
  42779. return parentItem->subItems [nextIndex];
  42780. }
  42781. return 0;
  42782. }
  42783. void TreeViewItem::restoreFromXml (const XmlElement& e)
  42784. {
  42785. if (e.hasTagName (T("CLOSED")))
  42786. {
  42787. setOpen (false);
  42788. }
  42789. else if (e.hasTagName (T("OPEN")))
  42790. {
  42791. setOpen (true);
  42792. forEachXmlChildElement (e, n)
  42793. {
  42794. const String id (n->getStringAttribute (T("id")));
  42795. for (int i = 0; i < subItems.size(); ++i)
  42796. {
  42797. TreeViewItem* const ti = subItems.getUnchecked(i);
  42798. if (ti->getUniqueName() == id)
  42799. {
  42800. ti->restoreFromXml (*n);
  42801. break;
  42802. }
  42803. }
  42804. }
  42805. }
  42806. }
  42807. XmlElement* TreeViewItem::createXmlOpenness() const
  42808. {
  42809. if (openness != opennessDefault)
  42810. {
  42811. const String name (getUniqueName());
  42812. if (name.isNotEmpty())
  42813. {
  42814. XmlElement* e;
  42815. if (isOpen())
  42816. {
  42817. e = new XmlElement (T("OPEN"));
  42818. for (int i = 0; i < subItems.size(); ++i)
  42819. e->addChildElement (subItems.getUnchecked(i)->createXmlOpenness());
  42820. }
  42821. else
  42822. {
  42823. e = new XmlElement (T("CLOSED"));
  42824. }
  42825. e->setAttribute (T("id"), name);
  42826. return e;
  42827. }
  42828. else
  42829. {
  42830. // trying to save the openness for an element that has no name - this won't
  42831. // work because it needs the names to identify what to open.
  42832. jassertfalse
  42833. }
  42834. }
  42835. return 0;
  42836. }
  42837. END_JUCE_NAMESPACE
  42838. /********* End of inlined file: juce_TreeView.cpp *********/
  42839. /********* Start of inlined file: juce_DirectoryContentsDisplayComponent.cpp *********/
  42840. BEGIN_JUCE_NAMESPACE
  42841. DirectoryContentsDisplayComponent::DirectoryContentsDisplayComponent (DirectoryContentsList& listToShow)
  42842. : fileList (listToShow),
  42843. listeners (2)
  42844. {
  42845. }
  42846. DirectoryContentsDisplayComponent::~DirectoryContentsDisplayComponent()
  42847. {
  42848. }
  42849. FileBrowserListener::~FileBrowserListener()
  42850. {
  42851. }
  42852. void DirectoryContentsDisplayComponent::addListener (FileBrowserListener* const listener) throw()
  42853. {
  42854. jassert (listener != 0);
  42855. if (listener != 0)
  42856. listeners.add (listener);
  42857. }
  42858. void DirectoryContentsDisplayComponent::removeListener (FileBrowserListener* const listener) throw()
  42859. {
  42860. listeners.removeValue (listener);
  42861. }
  42862. void DirectoryContentsDisplayComponent::sendSelectionChangeMessage()
  42863. {
  42864. const ComponentDeletionWatcher deletionWatcher (dynamic_cast <Component*> (this));
  42865. for (int i = listeners.size(); --i >= 0;)
  42866. {
  42867. ((FileBrowserListener*) listeners.getUnchecked (i))->selectionChanged();
  42868. if (deletionWatcher.hasBeenDeleted())
  42869. return;
  42870. i = jmin (i, listeners.size() - 1);
  42871. }
  42872. }
  42873. void DirectoryContentsDisplayComponent::sendMouseClickMessage (const File& file, const MouseEvent& e)
  42874. {
  42875. if (fileList.getDirectory().exists())
  42876. {
  42877. const ComponentDeletionWatcher deletionWatcher (dynamic_cast <Component*> (this));
  42878. for (int i = listeners.size(); --i >= 0;)
  42879. {
  42880. ((FileBrowserListener*) listeners.getUnchecked (i))->fileClicked (file, e);
  42881. if (deletionWatcher.hasBeenDeleted())
  42882. return;
  42883. i = jmin (i, listeners.size() - 1);
  42884. }
  42885. }
  42886. }
  42887. void DirectoryContentsDisplayComponent::sendDoubleClickMessage (const File& file)
  42888. {
  42889. if (fileList.getDirectory().exists())
  42890. {
  42891. const ComponentDeletionWatcher deletionWatcher (dynamic_cast <Component*> (this));
  42892. for (int i = listeners.size(); --i >= 0;)
  42893. {
  42894. ((FileBrowserListener*) listeners.getUnchecked (i))->fileDoubleClicked (file);
  42895. if (deletionWatcher.hasBeenDeleted())
  42896. return;
  42897. i = jmin (i, listeners.size() - 1);
  42898. }
  42899. }
  42900. }
  42901. END_JUCE_NAMESPACE
  42902. /********* End of inlined file: juce_DirectoryContentsDisplayComponent.cpp *********/
  42903. /********* Start of inlined file: juce_DirectoryContentsList.cpp *********/
  42904. BEGIN_JUCE_NAMESPACE
  42905. void* juce_findFileStart (const String& directory, const String& wildCard, String& firstResultFile,
  42906. bool* isDirectory, bool* isHidden, int64* fileSize, Time* modTime,
  42907. Time* creationTime, bool* isReadOnly) throw();
  42908. bool juce_findFileNext (void* handle, String& resultFile,
  42909. bool* isDirectory, bool* isHidden, int64* fileSize,
  42910. Time* modTime, Time* creationTime, bool* isReadOnly) throw();
  42911. void juce_findFileClose (void* handle) throw();
  42912. DirectoryContentsList::DirectoryContentsList (const FileFilter* const fileFilter_,
  42913. TimeSliceThread& thread_)
  42914. : fileFilter (fileFilter_),
  42915. thread (thread_),
  42916. includeDirectories (false),
  42917. includeFiles (false),
  42918. ignoreHiddenFiles (true),
  42919. fileFindHandle (0),
  42920. shouldStop (true)
  42921. {
  42922. }
  42923. DirectoryContentsList::~DirectoryContentsList()
  42924. {
  42925. clear();
  42926. }
  42927. void DirectoryContentsList::setIgnoresHiddenFiles (const bool shouldIgnoreHiddenFiles)
  42928. {
  42929. ignoreHiddenFiles = shouldIgnoreHiddenFiles;
  42930. }
  42931. const File& DirectoryContentsList::getDirectory() const throw()
  42932. {
  42933. return root;
  42934. }
  42935. void DirectoryContentsList::setDirectory (const File& directory,
  42936. const bool includeDirectories_,
  42937. const bool includeFiles_)
  42938. {
  42939. if (directory != root
  42940. || includeDirectories != includeDirectories_
  42941. || includeFiles != includeFiles_)
  42942. {
  42943. clear();
  42944. root = directory;
  42945. includeDirectories = includeDirectories_;
  42946. includeFiles = includeFiles_;
  42947. refresh();
  42948. }
  42949. }
  42950. void DirectoryContentsList::clear()
  42951. {
  42952. shouldStop = true;
  42953. thread.removeTimeSliceClient (this);
  42954. if (fileFindHandle != 0)
  42955. {
  42956. juce_findFileClose (fileFindHandle);
  42957. fileFindHandle = 0;
  42958. }
  42959. if (files.size() > 0)
  42960. {
  42961. files.clear();
  42962. changed();
  42963. }
  42964. }
  42965. void DirectoryContentsList::refresh()
  42966. {
  42967. clear();
  42968. if (root.isDirectory())
  42969. {
  42970. String fileFound;
  42971. bool fileFoundIsDir, isHidden, isReadOnly;
  42972. int64 fileSize;
  42973. Time modTime, creationTime;
  42974. String path (root.getFullPathName());
  42975. if (! path.endsWithChar (File::separator))
  42976. path += File::separator;
  42977. jassert (fileFindHandle == 0);
  42978. fileFindHandle = juce_findFileStart (path, T("*"), fileFound,
  42979. &fileFoundIsDir,
  42980. &isHidden,
  42981. &fileSize,
  42982. &modTime,
  42983. &creationTime,
  42984. &isReadOnly);
  42985. if (fileFindHandle != 0 && fileFound.isNotEmpty())
  42986. {
  42987. if (addFile (fileFound, fileFoundIsDir, isHidden,
  42988. fileSize, modTime, creationTime, isReadOnly))
  42989. {
  42990. changed();
  42991. }
  42992. }
  42993. shouldStop = false;
  42994. thread.addTimeSliceClient (this);
  42995. }
  42996. }
  42997. int DirectoryContentsList::getNumFiles() const
  42998. {
  42999. return files.size();
  43000. }
  43001. bool DirectoryContentsList::getFileInfo (const int index,
  43002. FileInfo& result) const
  43003. {
  43004. const ScopedLock sl (fileListLock);
  43005. const FileInfo* const info = files [index];
  43006. if (info != 0)
  43007. {
  43008. result = *info;
  43009. return true;
  43010. }
  43011. return false;
  43012. }
  43013. const File DirectoryContentsList::getFile (const int index) const
  43014. {
  43015. const ScopedLock sl (fileListLock);
  43016. const FileInfo* const info = files [index];
  43017. if (info != 0)
  43018. return root.getChildFile (info->filename);
  43019. return File::nonexistent;
  43020. }
  43021. bool DirectoryContentsList::isStillLoading() const
  43022. {
  43023. return fileFindHandle != 0;
  43024. }
  43025. void DirectoryContentsList::changed()
  43026. {
  43027. sendChangeMessage (this);
  43028. }
  43029. bool DirectoryContentsList::useTimeSlice()
  43030. {
  43031. const uint32 startTime = Time::getApproximateMillisecondCounter();
  43032. bool hasChanged = false;
  43033. for (int i = 100; --i >= 0;)
  43034. {
  43035. if (! checkNextFile (hasChanged))
  43036. {
  43037. if (hasChanged)
  43038. changed();
  43039. return false;
  43040. }
  43041. if (shouldStop || (Time::getApproximateMillisecondCounter() > startTime + 150))
  43042. break;
  43043. }
  43044. if (hasChanged)
  43045. changed();
  43046. return true;
  43047. }
  43048. bool DirectoryContentsList::checkNextFile (bool& hasChanged)
  43049. {
  43050. if (fileFindHandle != 0)
  43051. {
  43052. String fileFound;
  43053. bool fileFoundIsDir, isHidden, isReadOnly;
  43054. int64 fileSize;
  43055. Time modTime, creationTime;
  43056. if (juce_findFileNext (fileFindHandle, fileFound,
  43057. &fileFoundIsDir, &isHidden,
  43058. &fileSize,
  43059. &modTime,
  43060. &creationTime,
  43061. &isReadOnly))
  43062. {
  43063. if (addFile (fileFound, fileFoundIsDir, isHidden, fileSize,
  43064. modTime, creationTime, isReadOnly))
  43065. {
  43066. hasChanged = true;
  43067. }
  43068. return true;
  43069. }
  43070. else
  43071. {
  43072. juce_findFileClose (fileFindHandle);
  43073. fileFindHandle = 0;
  43074. }
  43075. }
  43076. return false;
  43077. }
  43078. int DirectoryContentsList::compareElements (const DirectoryContentsList::FileInfo* const first,
  43079. const DirectoryContentsList::FileInfo* const second) throw()
  43080. {
  43081. #if JUCE_WIN32
  43082. if (first->isDirectory != second->isDirectory)
  43083. return first->isDirectory ? -1 : 1;
  43084. #endif
  43085. return first->filename.compareIgnoreCase (second->filename);
  43086. }
  43087. bool DirectoryContentsList::addFile (const String& filename,
  43088. const bool isDir,
  43089. const bool isHidden,
  43090. const int64 fileSize,
  43091. const Time& modTime,
  43092. const Time& creationTime,
  43093. const bool isReadOnly)
  43094. {
  43095. if (filename == T("..")
  43096. || filename == T(".")
  43097. || (ignoreHiddenFiles && isHidden))
  43098. return false;
  43099. const File file (root.getChildFile (filename));
  43100. if (((isDir && includeDirectories) || ((! isDir) && includeFiles))
  43101. && (fileFilter == 0
  43102. || ((! isDir) && fileFilter->isFileSuitable (file))
  43103. || (isDir && fileFilter->isDirectorySuitable (file))))
  43104. {
  43105. FileInfo* const info = new FileInfo();
  43106. info->filename = filename;
  43107. info->fileSize = fileSize;
  43108. info->modificationTime = modTime;
  43109. info->creationTime = creationTime;
  43110. info->isDirectory = isDir;
  43111. info->isReadOnly = isReadOnly;
  43112. const ScopedLock sl (fileListLock);
  43113. for (int i = files.size(); --i >= 0;)
  43114. {
  43115. if (files.getUnchecked(i)->filename == info->filename)
  43116. {
  43117. delete info;
  43118. return false;
  43119. }
  43120. }
  43121. files.addSorted (*this, info);
  43122. return true;
  43123. }
  43124. return false;
  43125. }
  43126. END_JUCE_NAMESPACE
  43127. /********* End of inlined file: juce_DirectoryContentsList.cpp *********/
  43128. /********* Start of inlined file: juce_FileBrowserComponent.cpp *********/
  43129. BEGIN_JUCE_NAMESPACE
  43130. class DirectoriesOnlyFilter : public FileFilter
  43131. {
  43132. public:
  43133. DirectoriesOnlyFilter() : FileFilter (String::empty) {}
  43134. bool isFileSuitable (const File&) const { return false; }
  43135. bool isDirectorySuitable (const File&) const { return true; }
  43136. };
  43137. FileBrowserComponent::FileBrowserComponent (FileChooserMode mode_,
  43138. const File& initialFileOrDirectory,
  43139. const FileFilter* fileFilter,
  43140. FilePreviewComponent* previewComp_,
  43141. const bool useTreeView,
  43142. const bool filenameTextBoxIsReadOnly)
  43143. : directoriesOnlyFilter (0),
  43144. mode (mode_),
  43145. listeners (2),
  43146. previewComp (previewComp_),
  43147. thread ("Juce FileBrowser")
  43148. {
  43149. String filename;
  43150. if (initialFileOrDirectory == File::nonexistent)
  43151. {
  43152. currentRoot = File::getCurrentWorkingDirectory();
  43153. }
  43154. else if (initialFileOrDirectory.isDirectory())
  43155. {
  43156. currentRoot = initialFileOrDirectory;
  43157. }
  43158. else
  43159. {
  43160. currentRoot = initialFileOrDirectory.getParentDirectory();
  43161. filename = initialFileOrDirectory.getFileName();
  43162. }
  43163. if (mode_ == chooseDirectoryMode)
  43164. fileFilter = directoriesOnlyFilter = new DirectoriesOnlyFilter();
  43165. fileList = new DirectoryContentsList (fileFilter, thread);
  43166. if (useTreeView)
  43167. {
  43168. FileTreeComponent* const tree = new FileTreeComponent (*fileList);
  43169. addAndMakeVisible (tree);
  43170. fileListComponent = tree;
  43171. }
  43172. else
  43173. {
  43174. FileListComponent* const list = new FileListComponent (*fileList);
  43175. list->setOutlineThickness (1);
  43176. addAndMakeVisible (list);
  43177. fileListComponent = list;
  43178. }
  43179. fileListComponent->addListener (this);
  43180. addAndMakeVisible (currentPathBox = new ComboBox ("path"));
  43181. currentPathBox->setEditableText (true);
  43182. StringArray rootNames, rootPaths;
  43183. const BitArray separators (getRoots (rootNames, rootPaths));
  43184. for (int i = 0; i < rootNames.size(); ++i)
  43185. {
  43186. if (separators [i])
  43187. currentPathBox->addSeparator();
  43188. currentPathBox->addItem (rootNames[i], i + 1);
  43189. }
  43190. currentPathBox->addSeparator();
  43191. currentPathBox->addListener (this);
  43192. addAndMakeVisible (filenameBox = new TextEditor());
  43193. filenameBox->setMultiLine (false);
  43194. filenameBox->setSelectAllWhenFocused (true);
  43195. filenameBox->setText (filename, false);
  43196. filenameBox->addListener (this);
  43197. filenameBox->setReadOnly (filenameTextBoxIsReadOnly);
  43198. Label* label = new Label ("f", (mode == chooseDirectoryMode) ? TRANS("folder:")
  43199. : TRANS("file:"));
  43200. addAndMakeVisible (label);
  43201. label->attachToComponent (filenameBox, true);
  43202. addAndMakeVisible (goUpButton = getLookAndFeel().createFileBrowserGoUpButton());
  43203. goUpButton->addButtonListener (this);
  43204. goUpButton->setTooltip (TRANS ("go up to parent directory"));
  43205. if (previewComp != 0)
  43206. addAndMakeVisible (previewComp);
  43207. setRoot (currentRoot);
  43208. thread.startThread (4);
  43209. }
  43210. FileBrowserComponent::~FileBrowserComponent()
  43211. {
  43212. if (previewComp != 0)
  43213. removeChildComponent (previewComp);
  43214. deleteAllChildren();
  43215. deleteAndZero (fileList);
  43216. delete directoriesOnlyFilter;
  43217. thread.stopThread (10000);
  43218. }
  43219. void FileBrowserComponent::addListener (FileBrowserListener* const newListener) throw()
  43220. {
  43221. jassert (newListener != 0)
  43222. if (newListener != 0)
  43223. listeners.add (newListener);
  43224. }
  43225. void FileBrowserComponent::removeListener (FileBrowserListener* const listener) throw()
  43226. {
  43227. listeners.removeValue (listener);
  43228. }
  43229. const File FileBrowserComponent::getCurrentFile() const throw()
  43230. {
  43231. return currentRoot.getChildFile (filenameBox->getText());
  43232. }
  43233. bool FileBrowserComponent::currentFileIsValid() const
  43234. {
  43235. if (mode == saveFileMode)
  43236. return ! getCurrentFile().isDirectory();
  43237. else if (mode == loadFileMode)
  43238. return getCurrentFile().existsAsFile();
  43239. else if (mode == chooseDirectoryMode)
  43240. return getCurrentFile().isDirectory();
  43241. jassertfalse
  43242. return false;
  43243. }
  43244. const File FileBrowserComponent::getRoot() const
  43245. {
  43246. return currentRoot;
  43247. }
  43248. void FileBrowserComponent::setRoot (const File& newRootDirectory)
  43249. {
  43250. if (currentRoot != newRootDirectory)
  43251. {
  43252. fileListComponent->scrollToTop();
  43253. if (mode == chooseDirectoryMode)
  43254. filenameBox->setText (String::empty, false);
  43255. String path (newRootDirectory.getFullPathName());
  43256. if (path.isEmpty())
  43257. path += File::separator;
  43258. StringArray rootNames, rootPaths;
  43259. getRoots (rootNames, rootPaths);
  43260. if (! rootPaths.contains (path, true))
  43261. {
  43262. bool alreadyListed = false;
  43263. for (int i = currentPathBox->getNumItems(); --i >= 0;)
  43264. {
  43265. if (currentPathBox->getItemText (i).equalsIgnoreCase (path))
  43266. {
  43267. alreadyListed = true;
  43268. break;
  43269. }
  43270. }
  43271. if (! alreadyListed)
  43272. currentPathBox->addItem (path, currentPathBox->getNumItems() + 2);
  43273. }
  43274. }
  43275. currentRoot = newRootDirectory;
  43276. fileList->setDirectory (currentRoot, true, true);
  43277. String currentRootName (currentRoot.getFullPathName());
  43278. if (currentRootName.isEmpty())
  43279. currentRootName += File::separator;
  43280. currentPathBox->setText (currentRootName, true);
  43281. goUpButton->setEnabled (currentRoot.getParentDirectory().isDirectory()
  43282. && currentRoot.getParentDirectory() != currentRoot);
  43283. }
  43284. void FileBrowserComponent::goUp()
  43285. {
  43286. setRoot (getRoot().getParentDirectory());
  43287. }
  43288. void FileBrowserComponent::refresh()
  43289. {
  43290. fileList->refresh();
  43291. }
  43292. const String FileBrowserComponent::getActionVerb() const
  43293. {
  43294. return (mode == chooseDirectoryMode) ? TRANS("Choose")
  43295. : ((mode == saveFileMode) ? TRANS("Save") : TRANS("Open"));
  43296. }
  43297. FilePreviewComponent* FileBrowserComponent::getPreviewComponent() const throw()
  43298. {
  43299. return previewComp;
  43300. }
  43301. void FileBrowserComponent::resized()
  43302. {
  43303. getLookAndFeel()
  43304. .layoutFileBrowserComponent (*this, fileListComponent,
  43305. previewComp, currentPathBox,
  43306. filenameBox, goUpButton);
  43307. }
  43308. void FileBrowserComponent::sendListenerChangeMessage()
  43309. {
  43310. ComponentDeletionWatcher deletionWatcher (this);
  43311. if (previewComp != 0)
  43312. previewComp->selectedFileChanged (getCurrentFile());
  43313. jassert (! deletionWatcher.hasBeenDeleted());
  43314. for (int i = listeners.size(); --i >= 0;)
  43315. {
  43316. ((FileBrowserListener*) listeners.getUnchecked (i))->selectionChanged();
  43317. if (deletionWatcher.hasBeenDeleted())
  43318. return;
  43319. i = jmin (i, listeners.size() - 1);
  43320. }
  43321. }
  43322. void FileBrowserComponent::selectionChanged()
  43323. {
  43324. const File selected (fileListComponent->getSelectedFile());
  43325. if ((mode == chooseDirectoryMode && selected.isDirectory())
  43326. || selected.existsAsFile())
  43327. {
  43328. filenameBox->setText (selected.getRelativePathFrom (getRoot()), false);
  43329. }
  43330. sendListenerChangeMessage();
  43331. }
  43332. void FileBrowserComponent::fileClicked (const File& f, const MouseEvent& e)
  43333. {
  43334. ComponentDeletionWatcher deletionWatcher (this);
  43335. for (int i = listeners.size(); --i >= 0;)
  43336. {
  43337. ((FileBrowserListener*) listeners.getUnchecked (i))->fileClicked (f, e);
  43338. if (deletionWatcher.hasBeenDeleted())
  43339. return;
  43340. i = jmin (i, listeners.size() - 1);
  43341. }
  43342. }
  43343. void FileBrowserComponent::fileDoubleClicked (const File& f)
  43344. {
  43345. if (f.isDirectory())
  43346. {
  43347. setRoot (f);
  43348. }
  43349. else
  43350. {
  43351. ComponentDeletionWatcher deletionWatcher (this);
  43352. for (int i = listeners.size(); --i >= 0;)
  43353. {
  43354. ((FileBrowserListener*) listeners.getUnchecked (i))->fileDoubleClicked (f);
  43355. if (deletionWatcher.hasBeenDeleted())
  43356. return;
  43357. i = jmin (i, listeners.size() - 1);
  43358. }
  43359. }
  43360. }
  43361. bool FileBrowserComponent::keyPressed (const KeyPress& key)
  43362. {
  43363. #if JUCE_LINUX || JUCE_WIN32
  43364. if (key.getModifiers().isCommandDown()
  43365. && (key.getKeyCode() == 'H' || key.getKeyCode() == 'h'))
  43366. {
  43367. fileList->setIgnoresHiddenFiles (! fileList->ignoresHiddenFiles());
  43368. fileList->refresh();
  43369. return true;
  43370. }
  43371. #endif
  43372. return false;
  43373. }
  43374. void FileBrowserComponent::textEditorTextChanged (TextEditor&)
  43375. {
  43376. sendListenerChangeMessage();
  43377. }
  43378. void FileBrowserComponent::textEditorReturnKeyPressed (TextEditor&)
  43379. {
  43380. if (filenameBox->getText().containsChar (File::separator))
  43381. {
  43382. const File f (currentRoot.getChildFile (filenameBox->getText()));
  43383. if (f.isDirectory())
  43384. {
  43385. setRoot (f);
  43386. filenameBox->setText (String::empty);
  43387. }
  43388. else
  43389. {
  43390. setRoot (f.getParentDirectory());
  43391. filenameBox->setText (f.getFileName());
  43392. }
  43393. }
  43394. else
  43395. {
  43396. fileDoubleClicked (getCurrentFile());
  43397. }
  43398. }
  43399. void FileBrowserComponent::textEditorEscapeKeyPressed (TextEditor&)
  43400. {
  43401. }
  43402. void FileBrowserComponent::textEditorFocusLost (TextEditor&)
  43403. {
  43404. if (mode != saveFileMode)
  43405. selectionChanged();
  43406. }
  43407. void FileBrowserComponent::buttonClicked (Button*)
  43408. {
  43409. goUp();
  43410. }
  43411. void FileBrowserComponent::comboBoxChanged (ComboBox*)
  43412. {
  43413. const String newText (currentPathBox->getText().trim().unquoted());
  43414. if (newText.isNotEmpty())
  43415. {
  43416. const int index = currentPathBox->getSelectedId() - 1;
  43417. StringArray rootNames, rootPaths;
  43418. getRoots (rootNames, rootPaths);
  43419. if (rootPaths [index].isNotEmpty())
  43420. {
  43421. setRoot (File (rootPaths [index]));
  43422. }
  43423. else
  43424. {
  43425. File f (newText);
  43426. for (;;)
  43427. {
  43428. if (f.isDirectory())
  43429. {
  43430. setRoot (f);
  43431. break;
  43432. }
  43433. if (f.getParentDirectory() == f)
  43434. break;
  43435. f = f.getParentDirectory();
  43436. }
  43437. }
  43438. }
  43439. }
  43440. const BitArray FileBrowserComponent::getRoots (StringArray& rootNames, StringArray& rootPaths)
  43441. {
  43442. BitArray separators;
  43443. #if JUCE_WIN32
  43444. OwnedArray<File> roots;
  43445. File::findFileSystemRoots (roots);
  43446. rootPaths.clear();
  43447. for (int i = 0; i < roots.size(); ++i)
  43448. {
  43449. const File* const drive = roots.getUnchecked(i);
  43450. String name (drive->getFullPathName());
  43451. rootPaths.add (name);
  43452. if (drive->isOnHardDisk())
  43453. {
  43454. String volume (drive->getVolumeLabel());
  43455. if (volume.isEmpty())
  43456. volume = TRANS("Hard Drive");
  43457. name << " [" << drive->getVolumeLabel() << ']';
  43458. }
  43459. else if (drive->isOnCDRomDrive())
  43460. {
  43461. name << TRANS(" [CD/DVD drive]");
  43462. }
  43463. rootNames.add (name);
  43464. }
  43465. separators.setBit (rootPaths.size());
  43466. rootPaths.add (File::getSpecialLocation (File::userDocumentsDirectory).getFullPathName());
  43467. rootNames.add ("Documents");
  43468. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  43469. rootNames.add ("Desktop");
  43470. #endif
  43471. #if JUCE_MAC
  43472. rootPaths.add (File::getSpecialLocation (File::userHomeDirectory).getFullPathName());
  43473. rootNames.add ("Home folder");
  43474. rootPaths.add (File::getSpecialLocation (File::userDocumentsDirectory).getFullPathName());
  43475. rootNames.add ("Documents");
  43476. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  43477. rootNames.add ("Desktop");
  43478. separators.setBit (rootPaths.size());
  43479. OwnedArray <File> volumes;
  43480. File vol ("/Volumes");
  43481. vol.findChildFiles (volumes, File::findDirectories, false);
  43482. for (int i = 0; i < volumes.size(); ++i)
  43483. {
  43484. const File* const volume = volumes.getUnchecked(i);
  43485. if (volume->isDirectory() && ! volume->getFileName().startsWithChar (T('.')))
  43486. {
  43487. rootPaths.add (volume->getFullPathName());
  43488. rootNames.add (volume->getFileName());
  43489. }
  43490. }
  43491. #endif
  43492. #if JUCE_LINUX
  43493. rootPaths.add ("/");
  43494. rootNames.add ("/");
  43495. rootPaths.add (File::getSpecialLocation (File::userHomeDirectory).getFullPathName());
  43496. rootNames.add ("Home folder");
  43497. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  43498. rootNames.add ("Desktop");
  43499. #endif
  43500. return separators;
  43501. }
  43502. END_JUCE_NAMESPACE
  43503. /********* End of inlined file: juce_FileBrowserComponent.cpp *********/
  43504. /********* Start of inlined file: juce_FileChooser.cpp *********/
  43505. BEGIN_JUCE_NAMESPACE
  43506. FileChooser::FileChooser (const String& chooserBoxTitle,
  43507. const File& currentFileOrDirectory,
  43508. const String& fileFilters,
  43509. const bool useNativeDialogBox_)
  43510. : title (chooserBoxTitle),
  43511. filters (fileFilters),
  43512. startingFile (currentFileOrDirectory),
  43513. useNativeDialogBox (useNativeDialogBox_)
  43514. {
  43515. #if JUCE_LINUX
  43516. useNativeDialogBox = false;
  43517. #endif
  43518. if (! fileFilters.containsNonWhitespaceChars())
  43519. filters = T("*");
  43520. }
  43521. FileChooser::~FileChooser()
  43522. {
  43523. }
  43524. bool FileChooser::browseForFileToOpen (FilePreviewComponent* previewComponent)
  43525. {
  43526. return showDialog (false, false, false, false, previewComponent);
  43527. }
  43528. bool FileChooser::browseForMultipleFilesToOpen (FilePreviewComponent* previewComponent)
  43529. {
  43530. return showDialog (false, false, false, true, previewComponent);
  43531. }
  43532. bool FileChooser::browseForFileToSave (const bool warnAboutOverwritingExistingFiles)
  43533. {
  43534. return showDialog (false, true, warnAboutOverwritingExistingFiles, false, 0);
  43535. }
  43536. bool FileChooser::browseForDirectory()
  43537. {
  43538. return showDialog (true, false, false, false, 0);
  43539. }
  43540. const File FileChooser::getResult() const
  43541. {
  43542. // if you've used a multiple-file select, you should use the getResults() method
  43543. // to retrieve all the files that were chosen.
  43544. jassert (results.size() <= 1);
  43545. const File* const f = results.getFirst();
  43546. if (f != 0)
  43547. return *f;
  43548. return File::nonexistent;
  43549. }
  43550. const OwnedArray <File>& FileChooser::getResults() const
  43551. {
  43552. return results;
  43553. }
  43554. bool FileChooser::showDialog (const bool isDirectory,
  43555. const bool isSave,
  43556. const bool warnAboutOverwritingExistingFiles,
  43557. const bool selectMultipleFiles,
  43558. FilePreviewComponent* const previewComponent)
  43559. {
  43560. ComponentDeletionWatcher* currentlyFocusedChecker = 0;
  43561. Component* const currentlyFocused = Component::getCurrentlyFocusedComponent();
  43562. if (currentlyFocused != 0)
  43563. currentlyFocusedChecker = new ComponentDeletionWatcher (currentlyFocused);
  43564. results.clear();
  43565. // the preview component needs to be the right size before you pass it in here..
  43566. jassert (previewComponent == 0 || (previewComponent->getWidth() > 10
  43567. && previewComponent->getHeight() > 10));
  43568. #if JUCE_WIN32
  43569. if (useNativeDialogBox)
  43570. #else
  43571. if (useNativeDialogBox && (previewComponent == 0))
  43572. #endif
  43573. {
  43574. showPlatformDialog (results, title, startingFile, filters,
  43575. isDirectory, isSave,
  43576. warnAboutOverwritingExistingFiles,
  43577. selectMultipleFiles,
  43578. previewComponent);
  43579. }
  43580. else
  43581. {
  43582. jassert (! selectMultipleFiles); // not yet implemented for juce dialogs!
  43583. WildcardFileFilter wildcard (filters, String::empty);
  43584. FileBrowserComponent browserComponent (isDirectory ? FileBrowserComponent::chooseDirectoryMode
  43585. : (isSave ? FileBrowserComponent::saveFileMode
  43586. : FileBrowserComponent::loadFileMode),
  43587. startingFile, &wildcard, previewComponent);
  43588. FileChooserDialogBox box (title, String::empty,
  43589. browserComponent,
  43590. warnAboutOverwritingExistingFiles,
  43591. browserComponent.findColour (AlertWindow::backgroundColourId));
  43592. if (box.show())
  43593. results.add (new File (browserComponent.getCurrentFile()));
  43594. }
  43595. if (currentlyFocused != 0 && ! currentlyFocusedChecker->hasBeenDeleted())
  43596. currentlyFocused->grabKeyboardFocus();
  43597. delete currentlyFocusedChecker;
  43598. return results.size() > 0;
  43599. }
  43600. FilePreviewComponent::FilePreviewComponent()
  43601. {
  43602. }
  43603. FilePreviewComponent::~FilePreviewComponent()
  43604. {
  43605. }
  43606. END_JUCE_NAMESPACE
  43607. /********* End of inlined file: juce_FileChooser.cpp *********/
  43608. /********* Start of inlined file: juce_FileChooserDialogBox.cpp *********/
  43609. BEGIN_JUCE_NAMESPACE
  43610. FileChooserDialogBox::FileChooserDialogBox (const String& name,
  43611. const String& instructions,
  43612. FileBrowserComponent& chooserComponent,
  43613. const bool warnAboutOverwritingExistingFiles_,
  43614. const Colour& backgroundColour)
  43615. : ResizableWindow (name, backgroundColour, true),
  43616. warnAboutOverwritingExistingFiles (warnAboutOverwritingExistingFiles_)
  43617. {
  43618. content = new ContentComponent();
  43619. content->setName (name);
  43620. content->instructions = instructions;
  43621. content->chooserComponent = &chooserComponent;
  43622. content->addAndMakeVisible (&chooserComponent);
  43623. content->okButton = new TextButton (chooserComponent.getActionVerb());
  43624. content->addAndMakeVisible (content->okButton);
  43625. content->okButton->addButtonListener (this);
  43626. content->okButton->setEnabled (chooserComponent.currentFileIsValid());
  43627. content->okButton->addShortcut (KeyPress (KeyPress::returnKey, 0, 0));
  43628. content->cancelButton = new TextButton (TRANS("Cancel"));
  43629. content->addAndMakeVisible (content->cancelButton);
  43630. content->cancelButton->addButtonListener (this);
  43631. content->cancelButton->addShortcut (KeyPress (KeyPress::escapeKey, 0, 0));
  43632. setContentComponent (content);
  43633. setResizable (true, true);
  43634. setResizeLimits (300, 300, 1200, 1000);
  43635. content->chooserComponent->addListener (this);
  43636. }
  43637. FileChooserDialogBox::~FileChooserDialogBox()
  43638. {
  43639. content->chooserComponent->removeListener (this);
  43640. }
  43641. bool FileChooserDialogBox::show (int w, int h)
  43642. {
  43643. if (w <= 0)
  43644. {
  43645. Component* const previewComp = content->chooserComponent->getPreviewComponent();
  43646. if (previewComp != 0)
  43647. w = 400 + previewComp->getWidth();
  43648. else
  43649. w = 600;
  43650. }
  43651. if (h <= 0)
  43652. h = 500;
  43653. centreWithSize (w, h);
  43654. const bool ok = (runModalLoop() != 0);
  43655. setVisible (false);
  43656. return ok;
  43657. }
  43658. void FileChooserDialogBox::buttonClicked (Button* button)
  43659. {
  43660. if (button == content->okButton)
  43661. {
  43662. if (warnAboutOverwritingExistingFiles
  43663. && content->chooserComponent->getMode() == FileBrowserComponent::saveFileMode
  43664. && content->chooserComponent->getCurrentFile().exists())
  43665. {
  43666. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  43667. TRANS("File already exists"),
  43668. TRANS("There's already a file called:\n\n")
  43669. + content->chooserComponent->getCurrentFile().getFullPathName()
  43670. + T("\n\nAre you sure you want to overwrite it?"),
  43671. TRANS("overwrite"),
  43672. TRANS("cancel")))
  43673. {
  43674. return;
  43675. }
  43676. }
  43677. exitModalState (1);
  43678. }
  43679. else if (button == content->cancelButton)
  43680. closeButtonPressed();
  43681. }
  43682. void FileChooserDialogBox::closeButtonPressed()
  43683. {
  43684. setVisible (false);
  43685. }
  43686. void FileChooserDialogBox::selectionChanged()
  43687. {
  43688. content->okButton->setEnabled (content->chooserComponent->currentFileIsValid());
  43689. }
  43690. void FileChooserDialogBox::fileClicked (const File&, const MouseEvent&)
  43691. {
  43692. }
  43693. void FileChooserDialogBox::fileDoubleClicked (const File&)
  43694. {
  43695. selectionChanged();
  43696. content->okButton->triggerClick();
  43697. }
  43698. FileChooserDialogBox::ContentComponent::ContentComponent()
  43699. {
  43700. setInterceptsMouseClicks (false, true);
  43701. }
  43702. FileChooserDialogBox::ContentComponent::~ContentComponent()
  43703. {
  43704. delete okButton;
  43705. delete cancelButton;
  43706. }
  43707. void FileChooserDialogBox::ContentComponent::paint (Graphics& g)
  43708. {
  43709. g.setColour (Colours::black);
  43710. text.draw (g);
  43711. }
  43712. void FileChooserDialogBox::ContentComponent::resized()
  43713. {
  43714. getLookAndFeel().createFileChooserHeaderText (getName(), instructions, text, getWidth());
  43715. float left, top, right, bottom;
  43716. text.getBoundingBox (0, text.getNumGlyphs(), left, top, right, bottom, false);
  43717. const int y = roundFloatToInt (bottom) + 10;
  43718. const int buttonHeight = 26;
  43719. const int buttonY = getHeight() - buttonHeight - 8;
  43720. chooserComponent->setBounds (0, y, getWidth(), buttonY - y - 20);
  43721. okButton->setBounds (proportionOfWidth (0.25f), buttonY,
  43722. proportionOfWidth (0.2f), buttonHeight);
  43723. cancelButton->setBounds (proportionOfWidth (0.55f), buttonY,
  43724. proportionOfWidth (0.2f), buttonHeight);
  43725. }
  43726. END_JUCE_NAMESPACE
  43727. /********* End of inlined file: juce_FileChooserDialogBox.cpp *********/
  43728. /********* Start of inlined file: juce_FileFilter.cpp *********/
  43729. BEGIN_JUCE_NAMESPACE
  43730. FileFilter::FileFilter (const String& filterDescription)
  43731. : description (filterDescription)
  43732. {
  43733. }
  43734. FileFilter::~FileFilter()
  43735. {
  43736. }
  43737. const String& FileFilter::getDescription() const throw()
  43738. {
  43739. return description;
  43740. }
  43741. END_JUCE_NAMESPACE
  43742. /********* End of inlined file: juce_FileFilter.cpp *********/
  43743. /********* Start of inlined file: juce_FileListComponent.cpp *********/
  43744. BEGIN_JUCE_NAMESPACE
  43745. Image* juce_createIconForFile (const File& file);
  43746. FileListComponent::FileListComponent (DirectoryContentsList& listToShow)
  43747. : ListBox (String::empty, 0),
  43748. DirectoryContentsDisplayComponent (listToShow)
  43749. {
  43750. setModel (this);
  43751. fileList.addChangeListener (this);
  43752. }
  43753. FileListComponent::~FileListComponent()
  43754. {
  43755. fileList.removeChangeListener (this);
  43756. deleteAllChildren();
  43757. }
  43758. const File FileListComponent::getSelectedFile() const
  43759. {
  43760. return fileList.getFile (getSelectedRow());
  43761. }
  43762. void FileListComponent::scrollToTop()
  43763. {
  43764. getVerticalScrollBar()->setCurrentRangeStart (0);
  43765. }
  43766. void FileListComponent::changeListenerCallback (void*)
  43767. {
  43768. updateContent();
  43769. if (lastDirectory != fileList.getDirectory())
  43770. {
  43771. lastDirectory = fileList.getDirectory();
  43772. deselectAllRows();
  43773. }
  43774. }
  43775. class FileListItemComponent : public Component,
  43776. public TimeSliceClient,
  43777. public AsyncUpdater
  43778. {
  43779. public:
  43780. FileListItemComponent (FileListComponent& owner_,
  43781. TimeSliceThread& thread_) throw()
  43782. : owner (owner_),
  43783. thread (thread_),
  43784. icon (0)
  43785. {
  43786. }
  43787. ~FileListItemComponent() throw()
  43788. {
  43789. thread.removeTimeSliceClient (this);
  43790. clearIcon();
  43791. }
  43792. void paint (Graphics& g)
  43793. {
  43794. getLookAndFeel().drawFileBrowserRow (g, getWidth(), getHeight(),
  43795. file.getFileName(),
  43796. icon,
  43797. fileSize, modTime,
  43798. isDirectory, highlighted,
  43799. index);
  43800. }
  43801. void mouseDown (const MouseEvent& e)
  43802. {
  43803. owner.selectRowsBasedOnModifierKeys (index, e.mods);
  43804. owner.sendMouseClickMessage (file, e);
  43805. }
  43806. void mouseDoubleClick (const MouseEvent&)
  43807. {
  43808. owner.sendDoubleClickMessage (file);
  43809. }
  43810. void update (const File& root,
  43811. const DirectoryContentsList::FileInfo* const fileInfo,
  43812. const int index_,
  43813. const bool highlighted_) throw()
  43814. {
  43815. thread.removeTimeSliceClient (this);
  43816. if (highlighted_ != highlighted
  43817. || index_ != index)
  43818. {
  43819. index = index_;
  43820. highlighted = highlighted_;
  43821. repaint();
  43822. }
  43823. File newFile;
  43824. String newFileSize;
  43825. String newModTime;
  43826. if (fileInfo != 0)
  43827. {
  43828. newFile = root.getChildFile (fileInfo->filename);
  43829. newFileSize = File::descriptionOfSizeInBytes (fileInfo->fileSize);
  43830. newModTime = fileInfo->modificationTime.formatted (T("%d %b '%y %H:%M"));
  43831. }
  43832. if (newFile != file
  43833. || fileSize != newFileSize
  43834. || modTime != newModTime)
  43835. {
  43836. file = newFile;
  43837. fileSize = newFileSize;
  43838. modTime = newModTime;
  43839. isDirectory = fileInfo != 0 && fileInfo->isDirectory;
  43840. repaint();
  43841. clearIcon();
  43842. }
  43843. if (file != File::nonexistent
  43844. && icon == 0 && ! isDirectory)
  43845. {
  43846. updateIcon (true);
  43847. if (icon == 0)
  43848. thread.addTimeSliceClient (this);
  43849. }
  43850. }
  43851. bool useTimeSlice()
  43852. {
  43853. updateIcon (false);
  43854. return false;
  43855. }
  43856. void handleAsyncUpdate()
  43857. {
  43858. repaint();
  43859. }
  43860. juce_UseDebuggingNewOperator
  43861. private:
  43862. FileListComponent& owner;
  43863. TimeSliceThread& thread;
  43864. bool highlighted;
  43865. int index;
  43866. File file;
  43867. String fileSize;
  43868. String modTime;
  43869. Image* icon;
  43870. bool isDirectory;
  43871. void clearIcon() throw()
  43872. {
  43873. ImageCache::release (icon);
  43874. icon = 0;
  43875. }
  43876. void updateIcon (const bool onlyUpdateIfCached) throw()
  43877. {
  43878. if (icon == 0)
  43879. {
  43880. const int hashCode = (file.getFullPathName() + T("_iconCacheSalt")).hashCode();
  43881. Image* im = ImageCache::getFromHashCode (hashCode);
  43882. if (im == 0 && ! onlyUpdateIfCached)
  43883. {
  43884. im = juce_createIconForFile (file);
  43885. if (im != 0)
  43886. ImageCache::addImageToCache (im, hashCode);
  43887. }
  43888. if (im != 0)
  43889. {
  43890. icon = im;
  43891. triggerAsyncUpdate();
  43892. }
  43893. }
  43894. }
  43895. };
  43896. int FileListComponent::getNumRows()
  43897. {
  43898. return fileList.getNumFiles();
  43899. }
  43900. void FileListComponent::paintListBoxItem (int, Graphics&, int, int, bool)
  43901. {
  43902. }
  43903. Component* FileListComponent::refreshComponentForRow (int row, bool isSelected, Component* existingComponentToUpdate)
  43904. {
  43905. FileListItemComponent* comp = dynamic_cast <FileListItemComponent*> (existingComponentToUpdate);
  43906. if (comp == 0)
  43907. {
  43908. delete existingComponentToUpdate;
  43909. existingComponentToUpdate = comp = new FileListItemComponent (*this, fileList.getTimeSliceThread());
  43910. }
  43911. DirectoryContentsList::FileInfo fileInfo;
  43912. if (fileList.getFileInfo (row, fileInfo))
  43913. comp->update (fileList.getDirectory(), &fileInfo, row, isSelected);
  43914. else
  43915. comp->update (fileList.getDirectory(), 0, row, isSelected);
  43916. return comp;
  43917. }
  43918. void FileListComponent::selectedRowsChanged (int /*lastRowSelected*/)
  43919. {
  43920. sendSelectionChangeMessage();
  43921. }
  43922. void FileListComponent::deleteKeyPressed (int /*currentSelectedRow*/)
  43923. {
  43924. }
  43925. void FileListComponent::returnKeyPressed (int currentSelectedRow)
  43926. {
  43927. sendDoubleClickMessage (fileList.getFile (currentSelectedRow));
  43928. }
  43929. END_JUCE_NAMESPACE
  43930. /********* End of inlined file: juce_FileListComponent.cpp *********/
  43931. /********* Start of inlined file: juce_FilenameComponent.cpp *********/
  43932. BEGIN_JUCE_NAMESPACE
  43933. FilenameComponent::FilenameComponent (const String& name,
  43934. const File& currentFile,
  43935. const bool canEditFilename,
  43936. const bool isDirectory,
  43937. const bool isForSaving,
  43938. const String& fileBrowserWildcard,
  43939. const String& enforcedSuffix_,
  43940. const String& textWhenNothingSelected)
  43941. : Component (name),
  43942. maxRecentFiles (30),
  43943. isDir (isDirectory),
  43944. isSaving (isForSaving),
  43945. isFileDragOver (false),
  43946. wildcard (fileBrowserWildcard),
  43947. enforcedSuffix (enforcedSuffix_)
  43948. {
  43949. addAndMakeVisible (filenameBox = new ComboBox (T("fn")));
  43950. filenameBox->setEditableText (canEditFilename);
  43951. filenameBox->addListener (this);
  43952. filenameBox->setTextWhenNothingSelected (textWhenNothingSelected);
  43953. filenameBox->setTextWhenNoChoicesAvailable (TRANS("(no recently seleced files)"));
  43954. browseButton = 0;
  43955. setBrowseButtonText (T("..."));
  43956. setCurrentFile (currentFile, true);
  43957. }
  43958. FilenameComponent::~FilenameComponent()
  43959. {
  43960. deleteAllChildren();
  43961. }
  43962. void FilenameComponent::paintOverChildren (Graphics& g)
  43963. {
  43964. if (isFileDragOver)
  43965. {
  43966. g.setColour (Colours::red.withAlpha (0.2f));
  43967. g.drawRect (0, 0, getWidth(), getHeight(), 3);
  43968. }
  43969. }
  43970. void FilenameComponent::resized()
  43971. {
  43972. getLookAndFeel().layoutFilenameComponent (*this, filenameBox, browseButton);
  43973. }
  43974. void FilenameComponent::setBrowseButtonText (const String& newBrowseButtonText)
  43975. {
  43976. browseButtonText = newBrowseButtonText;
  43977. lookAndFeelChanged();
  43978. }
  43979. void FilenameComponent::lookAndFeelChanged()
  43980. {
  43981. deleteAndZero (browseButton);
  43982. addAndMakeVisible (browseButton = getLookAndFeel().createFilenameComponentBrowseButton (browseButtonText));
  43983. browseButton->setConnectedEdges (Button::ConnectedOnLeft);
  43984. resized();
  43985. browseButton->addButtonListener (this);
  43986. }
  43987. void FilenameComponent::setTooltip (const String& newTooltip)
  43988. {
  43989. SettableTooltipClient::setTooltip (newTooltip);
  43990. filenameBox->setTooltip (newTooltip);
  43991. }
  43992. void FilenameComponent::setDefaultBrowseTarget (const File& newDefaultDirectory) throw()
  43993. {
  43994. defaultBrowseFile = newDefaultDirectory;
  43995. }
  43996. void FilenameComponent::buttonClicked (Button*)
  43997. {
  43998. FileChooser fc (TRANS("Choose a new file"),
  43999. getCurrentFile() == File::nonexistent ? defaultBrowseFile
  44000. : getCurrentFile(),
  44001. wildcard);
  44002. if (isDir ? fc.browseForDirectory()
  44003. : (isSaving ? fc.browseForFileToSave (false)
  44004. : fc.browseForFileToOpen()))
  44005. {
  44006. setCurrentFile (fc.getResult(), true);
  44007. }
  44008. }
  44009. void FilenameComponent::comboBoxChanged (ComboBox*)
  44010. {
  44011. setCurrentFile (getCurrentFile(), true);
  44012. }
  44013. bool FilenameComponent::isInterestedInFileDrag (const StringArray&)
  44014. {
  44015. return true;
  44016. }
  44017. void FilenameComponent::filesDropped (const StringArray& filenames, int, int)
  44018. {
  44019. isFileDragOver = false;
  44020. repaint();
  44021. const File f (filenames[0]);
  44022. if (f.exists() && (f.isDirectory() == isDir))
  44023. setCurrentFile (f, true);
  44024. }
  44025. void FilenameComponent::fileDragEnter (const StringArray&, int, int)
  44026. {
  44027. isFileDragOver = true;
  44028. repaint();
  44029. }
  44030. void FilenameComponent::fileDragExit (const StringArray&)
  44031. {
  44032. isFileDragOver = false;
  44033. repaint();
  44034. }
  44035. const File FilenameComponent::getCurrentFile() const
  44036. {
  44037. File f (filenameBox->getText());
  44038. if (enforcedSuffix.isNotEmpty())
  44039. f = f.withFileExtension (enforcedSuffix);
  44040. return f;
  44041. }
  44042. void FilenameComponent::setCurrentFile (File newFile,
  44043. const bool addToRecentlyUsedList,
  44044. const bool sendChangeNotification)
  44045. {
  44046. if (enforcedSuffix.isNotEmpty())
  44047. newFile = newFile.withFileExtension (enforcedSuffix);
  44048. if (newFile.getFullPathName() != lastFilename)
  44049. {
  44050. lastFilename = newFile.getFullPathName();
  44051. if (addToRecentlyUsedList)
  44052. addRecentlyUsedFile (newFile);
  44053. filenameBox->setText (lastFilename, true);
  44054. if (sendChangeNotification)
  44055. triggerAsyncUpdate();
  44056. }
  44057. }
  44058. void FilenameComponent::setFilenameIsEditable (const bool shouldBeEditable)
  44059. {
  44060. filenameBox->setEditableText (shouldBeEditable);
  44061. }
  44062. const StringArray FilenameComponent::getRecentlyUsedFilenames() const
  44063. {
  44064. StringArray names;
  44065. for (int i = 0; i < filenameBox->getNumItems(); ++i)
  44066. names.add (filenameBox->getItemText (i));
  44067. return names;
  44068. }
  44069. void FilenameComponent::setRecentlyUsedFilenames (const StringArray& filenames)
  44070. {
  44071. if (filenames != getRecentlyUsedFilenames())
  44072. {
  44073. filenameBox->clear();
  44074. for (int i = 0; i < jmin (filenames.size(), maxRecentFiles); ++i)
  44075. filenameBox->addItem (filenames[i], i + 1);
  44076. }
  44077. }
  44078. void FilenameComponent::setMaxNumberOfRecentFiles (const int newMaximum)
  44079. {
  44080. maxRecentFiles = jmax (1, newMaximum);
  44081. setRecentlyUsedFilenames (getRecentlyUsedFilenames());
  44082. }
  44083. void FilenameComponent::addRecentlyUsedFile (const File& file)
  44084. {
  44085. StringArray files (getRecentlyUsedFilenames());
  44086. if (file.getFullPathName().isNotEmpty())
  44087. {
  44088. files.removeString (file.getFullPathName(), true);
  44089. files.insert (0, file.getFullPathName());
  44090. setRecentlyUsedFilenames (files);
  44091. }
  44092. }
  44093. void FilenameComponent::addListener (FilenameComponentListener* const listener) throw()
  44094. {
  44095. jassert (listener != 0);
  44096. if (listener != 0)
  44097. listeners.add (listener);
  44098. }
  44099. void FilenameComponent::removeListener (FilenameComponentListener* const listener) throw()
  44100. {
  44101. listeners.removeValue (listener);
  44102. }
  44103. void FilenameComponent::handleAsyncUpdate()
  44104. {
  44105. for (int i = listeners.size(); --i >= 0;)
  44106. {
  44107. ((FilenameComponentListener*) listeners.getUnchecked (i))->filenameComponentChanged (this);
  44108. i = jmin (i, listeners.size());
  44109. }
  44110. }
  44111. END_JUCE_NAMESPACE
  44112. /********* End of inlined file: juce_FilenameComponent.cpp *********/
  44113. /********* Start of inlined file: juce_FileSearchPathListComponent.cpp *********/
  44114. BEGIN_JUCE_NAMESPACE
  44115. FileSearchPathListComponent::FileSearchPathListComponent()
  44116. {
  44117. addAndMakeVisible (listBox = new ListBox (String::empty, this));
  44118. listBox->setColour (ListBox::backgroundColourId, Colours::black.withAlpha (0.02f));
  44119. listBox->setColour (ListBox::outlineColourId, Colours::black.withAlpha (0.1f));
  44120. listBox->setOutlineThickness (1);
  44121. addAndMakeVisible (addButton = new TextButton ("+"));
  44122. addButton->addButtonListener (this);
  44123. addButton->setConnectedEdges (Button::ConnectedOnLeft | Button::ConnectedOnRight | Button::ConnectedOnBottom | Button::ConnectedOnTop);
  44124. addAndMakeVisible (removeButton = new TextButton ("-"));
  44125. removeButton->addButtonListener (this);
  44126. removeButton->setConnectedEdges (Button::ConnectedOnLeft | Button::ConnectedOnRight | Button::ConnectedOnBottom | Button::ConnectedOnTop);
  44127. addAndMakeVisible (changeButton = new TextButton (TRANS("change...")));
  44128. changeButton->addButtonListener (this);
  44129. addAndMakeVisible (upButton = new DrawableButton (String::empty, DrawableButton::ImageOnButtonBackground));
  44130. upButton->addButtonListener (this);
  44131. {
  44132. Path arrowPath;
  44133. arrowPath.addArrow (50.0f, 100.0f, 50.0f, 0.0, 40.0f, 100.0f, 50.0f);
  44134. DrawablePath arrowImage;
  44135. arrowImage.setSolidFill (Colours::black.withAlpha (0.4f));
  44136. arrowImage.setPath (arrowPath);
  44137. ((DrawableButton*) upButton)->setImages (&arrowImage);
  44138. }
  44139. addAndMakeVisible (downButton = new DrawableButton (String::empty, DrawableButton::ImageOnButtonBackground));
  44140. downButton->addButtonListener (this);
  44141. {
  44142. Path arrowPath;
  44143. arrowPath.addArrow (50.0f, 0.0f, 50.0f, 100.0f, 40.0f, 100.0f, 50.0f);
  44144. DrawablePath arrowImage;
  44145. arrowImage.setSolidFill (Colours::black.withAlpha (0.4f));
  44146. arrowImage.setPath (arrowPath);
  44147. ((DrawableButton*) downButton)->setImages (&arrowImage);
  44148. }
  44149. updateButtons();
  44150. }
  44151. FileSearchPathListComponent::~FileSearchPathListComponent()
  44152. {
  44153. deleteAllChildren();
  44154. }
  44155. void FileSearchPathListComponent::updateButtons() throw()
  44156. {
  44157. const bool anythingSelected = listBox->getNumSelectedRows() > 0;
  44158. removeButton->setEnabled (anythingSelected);
  44159. changeButton->setEnabled (anythingSelected);
  44160. upButton->setEnabled (anythingSelected);
  44161. downButton->setEnabled (anythingSelected);
  44162. }
  44163. void FileSearchPathListComponent::changed() throw()
  44164. {
  44165. listBox->updateContent();
  44166. listBox->repaint();
  44167. updateButtons();
  44168. }
  44169. void FileSearchPathListComponent::setPath (const FileSearchPath& newPath)
  44170. {
  44171. if (newPath.toString() != path.toString())
  44172. {
  44173. path = newPath;
  44174. changed();
  44175. }
  44176. }
  44177. void FileSearchPathListComponent::setDefaultBrowseTarget (const File& newDefaultDirectory) throw()
  44178. {
  44179. defaultBrowseTarget = newDefaultDirectory;
  44180. }
  44181. int FileSearchPathListComponent::getNumRows()
  44182. {
  44183. return path.getNumPaths();
  44184. }
  44185. void FileSearchPathListComponent::paintListBoxItem (int rowNumber, Graphics& g, int width, int height, bool rowIsSelected)
  44186. {
  44187. if (rowIsSelected)
  44188. g.fillAll (findColour (TextEditor::highlightColourId));
  44189. g.setColour (findColour (ListBox::textColourId));
  44190. Font f (height * 0.7f);
  44191. f.setHorizontalScale (0.9f);
  44192. g.setFont (f);
  44193. g.drawText (path [rowNumber].getFullPathName(),
  44194. 4, 0, width - 6, height,
  44195. Justification::centredLeft, true);
  44196. }
  44197. void FileSearchPathListComponent::deleteKeyPressed (int row)
  44198. {
  44199. if (((unsigned int) row) < (unsigned int) path.getNumPaths())
  44200. {
  44201. path.remove (row);
  44202. changed();
  44203. }
  44204. }
  44205. void FileSearchPathListComponent::returnKeyPressed (int row)
  44206. {
  44207. FileChooser chooser (TRANS("Change folder..."), path [row], T("*"));
  44208. if (chooser.browseForDirectory())
  44209. {
  44210. path.remove (row);
  44211. path.add (chooser.getResult(), row);
  44212. changed();
  44213. }
  44214. }
  44215. void FileSearchPathListComponent::listBoxItemDoubleClicked (int row, const MouseEvent&)
  44216. {
  44217. returnKeyPressed (row);
  44218. }
  44219. void FileSearchPathListComponent::selectedRowsChanged (int)
  44220. {
  44221. updateButtons();
  44222. }
  44223. void FileSearchPathListComponent::paint (Graphics& g)
  44224. {
  44225. g.fillAll (findColour (backgroundColourId));
  44226. }
  44227. void FileSearchPathListComponent::resized()
  44228. {
  44229. const int buttonH = 22;
  44230. const int buttonY = getHeight() - buttonH - 4;
  44231. listBox->setBounds (2, 2, getWidth() - 4, buttonY - 5);
  44232. addButton->setBounds (2, buttonY, buttonH, buttonH);
  44233. removeButton->setBounds (addButton->getRight(), buttonY, buttonH, buttonH);
  44234. ((TextButton*) changeButton)->changeWidthToFitText (buttonH);
  44235. downButton->setSize (buttonH * 2, buttonH);
  44236. upButton->setSize (buttonH * 2, buttonH);
  44237. downButton->setTopRightPosition (getWidth() - 2, buttonY);
  44238. upButton->setTopRightPosition (downButton->getX() - 4, buttonY);
  44239. changeButton->setTopRightPosition (upButton->getX() - 8, buttonY);
  44240. }
  44241. bool FileSearchPathListComponent::isInterestedInFileDrag (const StringArray&)
  44242. {
  44243. return true;
  44244. }
  44245. void FileSearchPathListComponent::filesDropped (const StringArray& filenames, int, int mouseY)
  44246. {
  44247. for (int i = filenames.size(); --i >= 0;)
  44248. {
  44249. const File f (filenames[i]);
  44250. if (f.isDirectory())
  44251. {
  44252. const int row = listBox->getRowContainingPosition (0, mouseY - listBox->getY());
  44253. path.add (f, row);
  44254. changed();
  44255. }
  44256. }
  44257. }
  44258. void FileSearchPathListComponent::buttonClicked (Button* button)
  44259. {
  44260. const int currentRow = listBox->getSelectedRow();
  44261. if (button == removeButton)
  44262. {
  44263. deleteKeyPressed (currentRow);
  44264. }
  44265. else if (button == addButton)
  44266. {
  44267. File start (defaultBrowseTarget);
  44268. if (start == File::nonexistent)
  44269. start = path [0];
  44270. if (start == File::nonexistent)
  44271. start = File::getCurrentWorkingDirectory();
  44272. FileChooser chooser (TRANS("Add a folder..."), start, T("*"));
  44273. if (chooser.browseForDirectory())
  44274. {
  44275. path.add (chooser.getResult(), currentRow);
  44276. }
  44277. }
  44278. else if (button == changeButton)
  44279. {
  44280. returnKeyPressed (currentRow);
  44281. }
  44282. else if (button == upButton)
  44283. {
  44284. if (currentRow > 0 && currentRow < path.getNumPaths())
  44285. {
  44286. const File f (path[currentRow]);
  44287. path.remove (currentRow);
  44288. path.add (f, currentRow - 1);
  44289. listBox->selectRow (currentRow - 1);
  44290. }
  44291. }
  44292. else if (button == downButton)
  44293. {
  44294. if (currentRow >= 0 && currentRow < path.getNumPaths() - 1)
  44295. {
  44296. const File f (path[currentRow]);
  44297. path.remove (currentRow);
  44298. path.add (f, currentRow + 1);
  44299. listBox->selectRow (currentRow + 1);
  44300. }
  44301. }
  44302. changed();
  44303. }
  44304. END_JUCE_NAMESPACE
  44305. /********* End of inlined file: juce_FileSearchPathListComponent.cpp *********/
  44306. /********* Start of inlined file: juce_FileTreeComponent.cpp *********/
  44307. BEGIN_JUCE_NAMESPACE
  44308. Image* juce_createIconForFile (const File& file);
  44309. class FileListTreeItem : public TreeViewItem,
  44310. public TimeSliceClient,
  44311. public AsyncUpdater,
  44312. public ChangeListener
  44313. {
  44314. public:
  44315. FileListTreeItem (FileTreeComponent& owner_,
  44316. DirectoryContentsList* const parentContentsList_,
  44317. const int indexInContentsList_,
  44318. const File& file_,
  44319. TimeSliceThread& thread_) throw()
  44320. : file (file_),
  44321. owner (owner_),
  44322. parentContentsList (parentContentsList_),
  44323. indexInContentsList (indexInContentsList_),
  44324. subContentsList (0),
  44325. canDeleteSubContentsList (false),
  44326. thread (thread_),
  44327. icon (0)
  44328. {
  44329. DirectoryContentsList::FileInfo fileInfo;
  44330. if (parentContentsList_ != 0
  44331. && parentContentsList_->getFileInfo (indexInContentsList_, fileInfo))
  44332. {
  44333. fileSize = File::descriptionOfSizeInBytes (fileInfo.fileSize);
  44334. modTime = fileInfo.modificationTime.formatted (T("%d %b '%y %H:%M"));
  44335. isDirectory = fileInfo.isDirectory;
  44336. }
  44337. else
  44338. {
  44339. isDirectory = true;
  44340. }
  44341. }
  44342. ~FileListTreeItem() throw()
  44343. {
  44344. thread.removeTimeSliceClient (this);
  44345. clearSubItems();
  44346. ImageCache::release (icon);
  44347. if (canDeleteSubContentsList)
  44348. delete subContentsList;
  44349. }
  44350. bool mightContainSubItems() { return isDirectory; }
  44351. const String getUniqueName() const { return file.getFullPathName(); }
  44352. int getItemHeight() const { return 22; }
  44353. const String getDragSourceDescription() { return owner.getDragAndDropDescription(); }
  44354. void itemOpennessChanged (bool isNowOpen)
  44355. {
  44356. if (isNowOpen)
  44357. {
  44358. clearSubItems();
  44359. isDirectory = file.isDirectory();
  44360. if (isDirectory)
  44361. {
  44362. if (subContentsList == 0)
  44363. {
  44364. jassert (parentContentsList != 0);
  44365. DirectoryContentsList* const l = new DirectoryContentsList (parentContentsList->getFilter(), thread);
  44366. l->setDirectory (file, true, true);
  44367. setSubContentsList (l);
  44368. canDeleteSubContentsList = true;
  44369. }
  44370. changeListenerCallback (0);
  44371. }
  44372. }
  44373. }
  44374. void setSubContentsList (DirectoryContentsList* newList) throw()
  44375. {
  44376. jassert (subContentsList == 0);
  44377. subContentsList = newList;
  44378. newList->addChangeListener (this);
  44379. }
  44380. void changeListenerCallback (void*)
  44381. {
  44382. clearSubItems();
  44383. if (isOpen() && subContentsList != 0)
  44384. {
  44385. for (int i = 0; i < subContentsList->getNumFiles(); ++i)
  44386. {
  44387. FileListTreeItem* const item
  44388. = new FileListTreeItem (owner, subContentsList, i, subContentsList->getFile(i), thread);
  44389. addSubItem (item);
  44390. }
  44391. }
  44392. }
  44393. void paintItem (Graphics& g, int width, int height)
  44394. {
  44395. if (file != File::nonexistent && ! isDirectory)
  44396. {
  44397. updateIcon (true);
  44398. if (icon == 0)
  44399. thread.addTimeSliceClient (this);
  44400. }
  44401. owner.getLookAndFeel()
  44402. .drawFileBrowserRow (g, width, height,
  44403. file.getFileName(),
  44404. icon,
  44405. fileSize, modTime,
  44406. isDirectory, isSelected(),
  44407. indexInContentsList);
  44408. }
  44409. void itemClicked (const MouseEvent& e)
  44410. {
  44411. owner.sendMouseClickMessage (file, e);
  44412. }
  44413. void itemDoubleClicked (const MouseEvent& e)
  44414. {
  44415. TreeViewItem::itemDoubleClicked (e);
  44416. owner.sendDoubleClickMessage (file);
  44417. }
  44418. void itemSelectionChanged (bool)
  44419. {
  44420. owner.sendSelectionChangeMessage();
  44421. }
  44422. bool useTimeSlice()
  44423. {
  44424. updateIcon (false);
  44425. thread.removeTimeSliceClient (this);
  44426. return false;
  44427. }
  44428. void handleAsyncUpdate()
  44429. {
  44430. owner.repaint();
  44431. }
  44432. const File file;
  44433. juce_UseDebuggingNewOperator
  44434. private:
  44435. FileTreeComponent& owner;
  44436. DirectoryContentsList* parentContentsList;
  44437. int indexInContentsList;
  44438. DirectoryContentsList* subContentsList;
  44439. bool isDirectory, canDeleteSubContentsList;
  44440. TimeSliceThread& thread;
  44441. Image* icon;
  44442. String fileSize;
  44443. String modTime;
  44444. void updateIcon (const bool onlyUpdateIfCached) throw()
  44445. {
  44446. if (icon == 0)
  44447. {
  44448. const int hashCode = (file.getFullPathName() + T("_iconCacheSalt")).hashCode();
  44449. Image* im = ImageCache::getFromHashCode (hashCode);
  44450. if (im == 0 && ! onlyUpdateIfCached)
  44451. {
  44452. im = juce_createIconForFile (file);
  44453. if (im != 0)
  44454. ImageCache::addImageToCache (im, hashCode);
  44455. }
  44456. if (im != 0)
  44457. {
  44458. icon = im;
  44459. triggerAsyncUpdate();
  44460. }
  44461. }
  44462. }
  44463. };
  44464. FileTreeComponent::FileTreeComponent (DirectoryContentsList& listToShow)
  44465. : DirectoryContentsDisplayComponent (listToShow)
  44466. {
  44467. FileListTreeItem* const root
  44468. = new FileListTreeItem (*this, 0, 0, listToShow.getDirectory(),
  44469. listToShow.getTimeSliceThread());
  44470. root->setSubContentsList (&listToShow);
  44471. setRootItemVisible (false);
  44472. setRootItem (root);
  44473. }
  44474. FileTreeComponent::~FileTreeComponent()
  44475. {
  44476. TreeViewItem* const root = getRootItem();
  44477. setRootItem (0);
  44478. delete root;
  44479. }
  44480. const File FileTreeComponent::getSelectedFile() const
  44481. {
  44482. return getSelectedFile (0);
  44483. }
  44484. const File FileTreeComponent::getSelectedFile (const int index) const throw()
  44485. {
  44486. const FileListTreeItem* const item = dynamic_cast <const FileListTreeItem*> (getSelectedItem (index));
  44487. if (item != 0)
  44488. return item->file;
  44489. return File::nonexistent;
  44490. }
  44491. void FileTreeComponent::scrollToTop()
  44492. {
  44493. getViewport()->getVerticalScrollBar()->setCurrentRangeStart (0);
  44494. }
  44495. void FileTreeComponent::setDragAndDropDescription (const String& description) throw()
  44496. {
  44497. dragAndDropDescription = description;
  44498. }
  44499. END_JUCE_NAMESPACE
  44500. /********* End of inlined file: juce_FileTreeComponent.cpp *********/
  44501. /********* Start of inlined file: juce_ImagePreviewComponent.cpp *********/
  44502. BEGIN_JUCE_NAMESPACE
  44503. ImagePreviewComponent::ImagePreviewComponent()
  44504. : currentThumbnail (0)
  44505. {
  44506. }
  44507. ImagePreviewComponent::~ImagePreviewComponent()
  44508. {
  44509. delete currentThumbnail;
  44510. }
  44511. void ImagePreviewComponent::getThumbSize (int& w, int& h) const
  44512. {
  44513. const int availableW = proportionOfWidth (0.97f);
  44514. const int availableH = getHeight() - 13 * 4;
  44515. const double scale = jmin (1.0,
  44516. availableW / (double) w,
  44517. availableH / (double) h);
  44518. w = roundDoubleToInt (scale * w);
  44519. h = roundDoubleToInt (scale * h);
  44520. }
  44521. void ImagePreviewComponent::selectedFileChanged (const File& file)
  44522. {
  44523. if (fileToLoad != file)
  44524. {
  44525. fileToLoad = file;
  44526. startTimer (100);
  44527. }
  44528. }
  44529. void ImagePreviewComponent::timerCallback()
  44530. {
  44531. stopTimer();
  44532. deleteAndZero (currentThumbnail);
  44533. currentDetails = String::empty;
  44534. repaint();
  44535. FileInputStream* const in = fileToLoad.createInputStream();
  44536. if (in != 0)
  44537. {
  44538. ImageFileFormat* const format = ImageFileFormat::findImageFormatForStream (*in);
  44539. if (format != 0)
  44540. {
  44541. currentThumbnail = format->decodeImage (*in);
  44542. if (currentThumbnail != 0)
  44543. {
  44544. int w = currentThumbnail->getWidth();
  44545. int h = currentThumbnail->getHeight();
  44546. currentDetails
  44547. << fileToLoad.getFileName() << "\n"
  44548. << format->getFormatName() << "\n"
  44549. << w << " x " << h << " pixels\n"
  44550. << File::descriptionOfSizeInBytes (fileToLoad.getSize());
  44551. getThumbSize (w, h);
  44552. Image* const reduced = currentThumbnail->createCopy (w, h);
  44553. delete currentThumbnail;
  44554. currentThumbnail = reduced;
  44555. }
  44556. }
  44557. delete in;
  44558. }
  44559. }
  44560. void ImagePreviewComponent::paint (Graphics& g)
  44561. {
  44562. if (currentThumbnail != 0)
  44563. {
  44564. g.setFont (13.0f);
  44565. int w = currentThumbnail->getWidth();
  44566. int h = currentThumbnail->getHeight();
  44567. getThumbSize (w, h);
  44568. const int numLines = 4;
  44569. const int totalH = 13 * numLines + h + 4;
  44570. const int y = (getHeight() - totalH) / 2;
  44571. g.drawImageWithin (currentThumbnail,
  44572. (getWidth() - w) / 2, y, w, h,
  44573. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize,
  44574. false);
  44575. g.drawFittedText (currentDetails,
  44576. 0, y + h + 4, getWidth(), 100,
  44577. Justification::centredTop, numLines);
  44578. }
  44579. }
  44580. END_JUCE_NAMESPACE
  44581. /********* End of inlined file: juce_ImagePreviewComponent.cpp *********/
  44582. /********* Start of inlined file: juce_WildcardFileFilter.cpp *********/
  44583. BEGIN_JUCE_NAMESPACE
  44584. WildcardFileFilter::WildcardFileFilter (const String& wildcardPatterns,
  44585. const String& description)
  44586. : FileFilter (description.isEmpty() ? wildcardPatterns
  44587. : (description + T(" (") + wildcardPatterns + T(")")))
  44588. {
  44589. wildcards.addTokens (wildcardPatterns.toLowerCase(), T(";,"), T("\"'"));
  44590. wildcards.trim();
  44591. wildcards.removeEmptyStrings();
  44592. // special case for *.*, because people use it to mean "any file", but it
  44593. // would actually ignore files with no extension.
  44594. for (int i = wildcards.size(); --i >= 0;)
  44595. if (wildcards[i] == T("*.*"))
  44596. wildcards.set (i, T("*"));
  44597. }
  44598. WildcardFileFilter::~WildcardFileFilter()
  44599. {
  44600. }
  44601. bool WildcardFileFilter::isFileSuitable (const File& file) const
  44602. {
  44603. const String filename (file.getFileName());
  44604. for (int i = wildcards.size(); --i >= 0;)
  44605. if (filename.matchesWildcard (wildcards[i], true))
  44606. return true;
  44607. return false;
  44608. }
  44609. bool WildcardFileFilter::isDirectorySuitable (const File&) const
  44610. {
  44611. return true;
  44612. }
  44613. END_JUCE_NAMESPACE
  44614. /********* End of inlined file: juce_WildcardFileFilter.cpp *********/
  44615. /********* Start of inlined file: juce_KeyboardFocusTraverser.cpp *********/
  44616. BEGIN_JUCE_NAMESPACE
  44617. KeyboardFocusTraverser::KeyboardFocusTraverser()
  44618. {
  44619. }
  44620. KeyboardFocusTraverser::~KeyboardFocusTraverser()
  44621. {
  44622. }
  44623. // This will sort a set of components, so that they are ordered in terms of
  44624. // left-to-right and then top-to-bottom.
  44625. class ScreenPositionComparator
  44626. {
  44627. public:
  44628. ScreenPositionComparator() {}
  44629. static int compareElements (const Component* const first, const Component* const second) throw()
  44630. {
  44631. int explicitOrder1 = first->getExplicitFocusOrder();
  44632. if (explicitOrder1 <= 0)
  44633. explicitOrder1 = INT_MAX / 2;
  44634. int explicitOrder2 = second->getExplicitFocusOrder();
  44635. if (explicitOrder2 <= 0)
  44636. explicitOrder2 = INT_MAX / 2;
  44637. if (explicitOrder1 != explicitOrder2)
  44638. return explicitOrder1 - explicitOrder2;
  44639. const int diff = first->getY() - second->getY();
  44640. return (diff == 0) ? first->getX() - second->getX()
  44641. : diff;
  44642. }
  44643. };
  44644. static void findAllFocusableComponents (Component* const parent, Array <Component*>& comps)
  44645. {
  44646. if (parent->getNumChildComponents() > 0)
  44647. {
  44648. Array <Component*> localComps;
  44649. ScreenPositionComparator comparator;
  44650. int i;
  44651. for (i = parent->getNumChildComponents(); --i >= 0;)
  44652. {
  44653. Component* const c = parent->getChildComponent (i);
  44654. if (c->isVisible() && c->isEnabled())
  44655. localComps.addSorted (comparator, c);
  44656. }
  44657. for (i = 0; i < localComps.size(); ++i)
  44658. {
  44659. Component* const c = localComps.getUnchecked (i);
  44660. if (c->getWantsKeyboardFocus())
  44661. comps.add (c);
  44662. if (! c->isFocusContainer())
  44663. findAllFocusableComponents (c, comps);
  44664. }
  44665. }
  44666. }
  44667. static Component* getIncrementedComponent (Component* const current, const int delta) throw()
  44668. {
  44669. Component* focusContainer = current->getParentComponent();
  44670. if (focusContainer != 0)
  44671. {
  44672. while (focusContainer->getParentComponent() != 0 && ! focusContainer->isFocusContainer())
  44673. focusContainer = focusContainer->getParentComponent();
  44674. if (focusContainer != 0)
  44675. {
  44676. Array <Component*> comps;
  44677. findAllFocusableComponents (focusContainer, comps);
  44678. if (comps.size() > 0)
  44679. {
  44680. const int index = comps.indexOf (current);
  44681. return comps [(index + comps.size() + delta) % comps.size()];
  44682. }
  44683. }
  44684. }
  44685. return 0;
  44686. }
  44687. Component* KeyboardFocusTraverser::getNextComponent (Component* current)
  44688. {
  44689. return getIncrementedComponent (current, 1);
  44690. }
  44691. Component* KeyboardFocusTraverser::getPreviousComponent (Component* current)
  44692. {
  44693. return getIncrementedComponent (current, -1);
  44694. }
  44695. Component* KeyboardFocusTraverser::getDefaultComponent (Component* parentComponent)
  44696. {
  44697. Array <Component*> comps;
  44698. if (parentComponent != 0)
  44699. findAllFocusableComponents (parentComponent, comps);
  44700. return comps.getFirst();
  44701. }
  44702. END_JUCE_NAMESPACE
  44703. /********* End of inlined file: juce_KeyboardFocusTraverser.cpp *********/
  44704. /********* Start of inlined file: juce_KeyListener.cpp *********/
  44705. BEGIN_JUCE_NAMESPACE
  44706. bool KeyListener::keyStateChanged (const bool, Component*)
  44707. {
  44708. return false;
  44709. }
  44710. END_JUCE_NAMESPACE
  44711. /********* End of inlined file: juce_KeyListener.cpp *********/
  44712. /********* Start of inlined file: juce_KeyMappingEditorComponent.cpp *********/
  44713. BEGIN_JUCE_NAMESPACE
  44714. // N.B. these two includes are put here deliberately to avoid problems with
  44715. // old GCCs failing on long include paths
  44716. const int maxKeys = 3;
  44717. class KeyMappingChangeButton : public Button
  44718. {
  44719. public:
  44720. KeyMappingChangeButton (KeyMappingEditorComponent* const owner_,
  44721. const CommandID commandID_,
  44722. const String& keyName,
  44723. const int keyNum_)
  44724. : Button (keyName),
  44725. owner (owner_),
  44726. commandID (commandID_),
  44727. keyNum (keyNum_)
  44728. {
  44729. setWantsKeyboardFocus (false);
  44730. setTriggeredOnMouseDown (keyNum >= 0);
  44731. if (keyNum_ < 0)
  44732. setTooltip (TRANS("adds a new key-mapping"));
  44733. else
  44734. setTooltip (TRANS("click to change this key-mapping"));
  44735. }
  44736. ~KeyMappingChangeButton()
  44737. {
  44738. }
  44739. void paintButton (Graphics& g, bool isOver, bool isDown)
  44740. {
  44741. if (keyNum >= 0)
  44742. {
  44743. if (isEnabled())
  44744. {
  44745. const float alpha = isDown ? 0.3f : (isOver ? 0.15f : 0.08f);
  44746. g.fillAll (owner->textColour.withAlpha (alpha));
  44747. g.setOpacity (0.3f);
  44748. g.drawBevel (0, 0, getWidth(), getHeight(), 2);
  44749. }
  44750. g.setColour (owner->textColour);
  44751. g.setFont (getHeight() * 0.6f);
  44752. g.drawFittedText (getName(),
  44753. 3, 0, getWidth() - 6, getHeight(),
  44754. Justification::centred, 1);
  44755. }
  44756. else
  44757. {
  44758. const float thickness = 7.0f;
  44759. const float indent = 22.0f;
  44760. Path p;
  44761. p.addEllipse (0.0f, 0.0f, 100.0f, 100.0f);
  44762. p.addRectangle (indent, 50.0f - thickness, 100.0f - indent * 2.0f, thickness * 2.0f);
  44763. p.addRectangle (50.0f - thickness, indent, thickness * 2.0f, 50.0f - indent - thickness);
  44764. p.addRectangle (50.0f - thickness, 50.0f + thickness, thickness * 2.0f, 50.0f - indent - thickness);
  44765. p.setUsingNonZeroWinding (false);
  44766. g.setColour (owner->textColour.withAlpha (isDown ? 0.7f : (isOver ? 0.5f : 0.3f)));
  44767. g.fillPath (p, p.getTransformToScaleToFit (2.0f, 2.0f, getWidth() - 4.0f, getHeight() - 4.0f, true));
  44768. }
  44769. if (hasKeyboardFocus (false))
  44770. {
  44771. g.setColour (owner->textColour.withAlpha (0.4f));
  44772. g.drawRect (0, 0, getWidth(), getHeight());
  44773. }
  44774. }
  44775. void clicked()
  44776. {
  44777. if (keyNum >= 0)
  44778. {
  44779. // existing key clicked..
  44780. PopupMenu m;
  44781. m.addItem (1, TRANS("change this key-mapping"));
  44782. m.addSeparator();
  44783. m.addItem (2, TRANS("remove this key-mapping"));
  44784. const int res = m.show();
  44785. if (res == 1)
  44786. {
  44787. owner->assignNewKey (commandID, keyNum);
  44788. }
  44789. else if (res == 2)
  44790. {
  44791. owner->getMappings()->removeKeyPress (commandID, keyNum);
  44792. }
  44793. }
  44794. else
  44795. {
  44796. // + button pressed..
  44797. owner->assignNewKey (commandID, -1);
  44798. }
  44799. }
  44800. void fitToContent (const int h) throw()
  44801. {
  44802. if (keyNum < 0)
  44803. {
  44804. setSize (h, h);
  44805. }
  44806. else
  44807. {
  44808. Font f (h * 0.6f);
  44809. setSize (jlimit (h * 4, h * 8, 6 + f.getStringWidth (getName())), h);
  44810. }
  44811. }
  44812. juce_UseDebuggingNewOperator
  44813. private:
  44814. KeyMappingEditorComponent* const owner;
  44815. const CommandID commandID;
  44816. const int keyNum;
  44817. KeyMappingChangeButton (const KeyMappingChangeButton&);
  44818. const KeyMappingChangeButton& operator= (const KeyMappingChangeButton&);
  44819. };
  44820. class KeyMappingItemComponent : public Component
  44821. {
  44822. public:
  44823. KeyMappingItemComponent (KeyMappingEditorComponent* const owner_,
  44824. const CommandID commandID_)
  44825. : owner (owner_),
  44826. commandID (commandID_)
  44827. {
  44828. setInterceptsMouseClicks (false, true);
  44829. const bool isReadOnly = owner_->isCommandReadOnly (commandID);
  44830. const Array <KeyPress> keyPresses (owner_->getMappings()->getKeyPressesAssignedToCommand (commandID));
  44831. for (int i = 0; i < jmin (maxKeys, keyPresses.size()); ++i)
  44832. {
  44833. KeyMappingChangeButton* const kb
  44834. = new KeyMappingChangeButton (owner_, commandID,
  44835. owner_->getDescriptionForKeyPress (keyPresses.getReference (i)), i);
  44836. kb->setEnabled (! isReadOnly);
  44837. addAndMakeVisible (kb);
  44838. }
  44839. KeyMappingChangeButton* const kb
  44840. = new KeyMappingChangeButton (owner_, commandID, String::empty, -1);
  44841. addChildComponent (kb);
  44842. kb->setVisible (keyPresses.size() < maxKeys && ! isReadOnly);
  44843. }
  44844. ~KeyMappingItemComponent()
  44845. {
  44846. deleteAllChildren();
  44847. }
  44848. void paint (Graphics& g)
  44849. {
  44850. g.setFont (getHeight() * 0.7f);
  44851. g.setColour (owner->textColour);
  44852. g.drawFittedText (owner->getMappings()->getCommandManager()->getNameOfCommand (commandID),
  44853. 4, 0, jmax (40, getChildComponent (0)->getX() - 5), getHeight(),
  44854. Justification::centredLeft, true);
  44855. }
  44856. void resized()
  44857. {
  44858. int x = getWidth() - 4;
  44859. for (int i = getNumChildComponents(); --i >= 0;)
  44860. {
  44861. KeyMappingChangeButton* const kb = dynamic_cast <KeyMappingChangeButton*> (getChildComponent (i));
  44862. kb->fitToContent (getHeight() - 2);
  44863. kb->setTopRightPosition (x, 1);
  44864. x -= kb->getWidth() + 5;
  44865. }
  44866. }
  44867. juce_UseDebuggingNewOperator
  44868. private:
  44869. KeyMappingEditorComponent* const owner;
  44870. const CommandID commandID;
  44871. KeyMappingItemComponent (const KeyMappingItemComponent&);
  44872. const KeyMappingItemComponent& operator= (const KeyMappingItemComponent&);
  44873. };
  44874. class KeyMappingTreeViewItem : public TreeViewItem
  44875. {
  44876. public:
  44877. KeyMappingTreeViewItem (KeyMappingEditorComponent* const owner_,
  44878. const CommandID commandID_)
  44879. : owner (owner_),
  44880. commandID (commandID_)
  44881. {
  44882. }
  44883. ~KeyMappingTreeViewItem()
  44884. {
  44885. }
  44886. const String getUniqueName() const { return String ((int) commandID) + "_id"; }
  44887. bool mightContainSubItems() { return false; }
  44888. int getItemHeight() const { return 20; }
  44889. Component* createItemComponent()
  44890. {
  44891. return new KeyMappingItemComponent (owner, commandID);
  44892. }
  44893. juce_UseDebuggingNewOperator
  44894. private:
  44895. KeyMappingEditorComponent* const owner;
  44896. const CommandID commandID;
  44897. KeyMappingTreeViewItem (const KeyMappingTreeViewItem&);
  44898. const KeyMappingTreeViewItem& operator= (const KeyMappingTreeViewItem&);
  44899. };
  44900. class KeyCategoryTreeViewItem : public TreeViewItem
  44901. {
  44902. public:
  44903. KeyCategoryTreeViewItem (KeyMappingEditorComponent* const owner_,
  44904. const String& name)
  44905. : owner (owner_),
  44906. categoryName (name)
  44907. {
  44908. }
  44909. ~KeyCategoryTreeViewItem()
  44910. {
  44911. }
  44912. const String getUniqueName() const { return categoryName + "_cat"; }
  44913. bool mightContainSubItems() { return true; }
  44914. int getItemHeight() const { return 28; }
  44915. void paintItem (Graphics& g, int width, int height)
  44916. {
  44917. g.setFont (height * 0.6f, Font::bold);
  44918. g.setColour (owner->textColour);
  44919. g.drawText (categoryName,
  44920. 2, 0, width - 2, height,
  44921. Justification::centredLeft, true);
  44922. }
  44923. void itemOpennessChanged (bool isNowOpen)
  44924. {
  44925. if (isNowOpen)
  44926. {
  44927. if (getNumSubItems() == 0)
  44928. {
  44929. Array <CommandID> commands (owner->getMappings()->getCommandManager()->getCommandsInCategory (categoryName));
  44930. for (int i = 0; i < commands.size(); ++i)
  44931. {
  44932. if (owner->shouldCommandBeIncluded (commands[i]))
  44933. addSubItem (new KeyMappingTreeViewItem (owner, commands[i]));
  44934. }
  44935. }
  44936. }
  44937. else
  44938. {
  44939. clearSubItems();
  44940. }
  44941. }
  44942. juce_UseDebuggingNewOperator
  44943. private:
  44944. KeyMappingEditorComponent* owner;
  44945. String categoryName;
  44946. KeyCategoryTreeViewItem (const KeyCategoryTreeViewItem&);
  44947. const KeyCategoryTreeViewItem& operator= (const KeyCategoryTreeViewItem&);
  44948. };
  44949. KeyMappingEditorComponent::KeyMappingEditorComponent (KeyPressMappingSet* const mappingManager,
  44950. const bool showResetToDefaultButton)
  44951. : mappings (mappingManager),
  44952. textColour (Colours::black)
  44953. {
  44954. jassert (mappingManager != 0); // can't be null!
  44955. mappingManager->addChangeListener (this);
  44956. setLinesDrawnForSubItems (false);
  44957. resetButton = 0;
  44958. if (showResetToDefaultButton)
  44959. {
  44960. addAndMakeVisible (resetButton = new TextButton (TRANS("reset to defaults")));
  44961. resetButton->addButtonListener (this);
  44962. }
  44963. addAndMakeVisible (tree = new TreeView());
  44964. tree->setColour (TreeView::backgroundColourId, backgroundColour);
  44965. tree->setRootItemVisible (false);
  44966. tree->setDefaultOpenness (true);
  44967. tree->setRootItem (this);
  44968. }
  44969. KeyMappingEditorComponent::~KeyMappingEditorComponent()
  44970. {
  44971. mappings->removeChangeListener (this);
  44972. deleteAllChildren();
  44973. }
  44974. bool KeyMappingEditorComponent::mightContainSubItems()
  44975. {
  44976. return true;
  44977. }
  44978. const String KeyMappingEditorComponent::getUniqueName() const
  44979. {
  44980. return T("keys");
  44981. }
  44982. void KeyMappingEditorComponent::setColours (const Colour& mainBackground,
  44983. const Colour& textColour_)
  44984. {
  44985. backgroundColour = mainBackground;
  44986. textColour = textColour_;
  44987. tree->setColour (TreeView::backgroundColourId, backgroundColour);
  44988. }
  44989. void KeyMappingEditorComponent::parentHierarchyChanged()
  44990. {
  44991. changeListenerCallback (0);
  44992. }
  44993. void KeyMappingEditorComponent::resized()
  44994. {
  44995. int h = getHeight();
  44996. if (resetButton != 0)
  44997. {
  44998. const int buttonHeight = 20;
  44999. h -= buttonHeight + 8;
  45000. int x = getWidth() - 8;
  45001. const int y = h + 6;
  45002. resetButton->changeWidthToFitText (buttonHeight);
  45003. resetButton->setTopRightPosition (x, y);
  45004. }
  45005. tree->setBounds (0, 0, getWidth(), h);
  45006. }
  45007. void KeyMappingEditorComponent::buttonClicked (Button* button)
  45008. {
  45009. if (button == resetButton)
  45010. {
  45011. if (AlertWindow::showOkCancelBox (AlertWindow::QuestionIcon,
  45012. TRANS("Reset to defaults"),
  45013. TRANS("Are you sure you want to reset all the key-mappings to their default state?"),
  45014. TRANS("Reset")))
  45015. {
  45016. mappings->resetToDefaultMappings();
  45017. }
  45018. }
  45019. }
  45020. void KeyMappingEditorComponent::changeListenerCallback (void*)
  45021. {
  45022. XmlElement* openness = tree->getOpennessState (true);
  45023. clearSubItems();
  45024. const StringArray categories (mappings->getCommandManager()->getCommandCategories());
  45025. for (int i = 0; i < categories.size(); ++i)
  45026. {
  45027. const Array <CommandID> commands (mappings->getCommandManager()->getCommandsInCategory (categories[i]));
  45028. int count = 0;
  45029. for (int j = 0; j < commands.size(); ++j)
  45030. if (shouldCommandBeIncluded (commands[j]))
  45031. ++count;
  45032. if (count > 0)
  45033. addSubItem (new KeyCategoryTreeViewItem (this, categories[i]));
  45034. }
  45035. if (openness != 0)
  45036. {
  45037. tree->restoreOpennessState (*openness);
  45038. delete openness;
  45039. }
  45040. }
  45041. class KeyEntryWindow : public AlertWindow
  45042. {
  45043. public:
  45044. KeyEntryWindow (KeyMappingEditorComponent* const owner_)
  45045. : AlertWindow (TRANS("New key-mapping"),
  45046. TRANS("Please press a key combination now..."),
  45047. AlertWindow::NoIcon),
  45048. owner (owner_)
  45049. {
  45050. addButton (TRANS("ok"), 1);
  45051. addButton (TRANS("cancel"), 0);
  45052. // (avoid return + escape keys getting processed by the buttons..)
  45053. for (int i = getNumChildComponents(); --i >= 0;)
  45054. getChildComponent (i)->setWantsKeyboardFocus (false);
  45055. setWantsKeyboardFocus (true);
  45056. grabKeyboardFocus();
  45057. }
  45058. ~KeyEntryWindow()
  45059. {
  45060. }
  45061. bool keyPressed (const KeyPress& key)
  45062. {
  45063. lastPress = key;
  45064. String message (TRANS("Key: ") + owner->getDescriptionForKeyPress (key));
  45065. const CommandID previousCommand = owner->getMappings()->findCommandForKeyPress (key);
  45066. if (previousCommand != 0)
  45067. {
  45068. message << "\n\n"
  45069. << TRANS("(Currently assigned to \"")
  45070. << owner->getMappings()->getCommandManager()->getNameOfCommand (previousCommand)
  45071. << "\")";
  45072. }
  45073. setMessage (message);
  45074. return true;
  45075. }
  45076. bool keyStateChanged (const bool)
  45077. {
  45078. return true;
  45079. }
  45080. KeyPress lastPress;
  45081. juce_UseDebuggingNewOperator
  45082. private:
  45083. KeyMappingEditorComponent* owner;
  45084. KeyEntryWindow (const KeyEntryWindow&);
  45085. const KeyEntryWindow& operator= (const KeyEntryWindow&);
  45086. };
  45087. void KeyMappingEditorComponent::assignNewKey (const CommandID commandID, const int index)
  45088. {
  45089. KeyEntryWindow entryWindow (this);
  45090. if (entryWindow.runModalLoop() != 0)
  45091. {
  45092. entryWindow.setVisible (false);
  45093. if (entryWindow.lastPress.isValid())
  45094. {
  45095. const CommandID previousCommand = mappings->findCommandForKeyPress (entryWindow.lastPress);
  45096. if (previousCommand != 0)
  45097. {
  45098. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  45099. TRANS("Change key-mapping"),
  45100. TRANS("This key is already assigned to the command \"")
  45101. + mappings->getCommandManager()->getNameOfCommand (previousCommand)
  45102. + TRANS("\"\n\nDo you want to re-assign it to this new command instead?"),
  45103. TRANS("re-assign"),
  45104. TRANS("cancel")))
  45105. {
  45106. return;
  45107. }
  45108. }
  45109. mappings->removeKeyPress (entryWindow.lastPress);
  45110. if (index >= 0)
  45111. mappings->removeKeyPress (commandID, index);
  45112. mappings->addKeyPress (commandID, entryWindow.lastPress, index);
  45113. }
  45114. }
  45115. }
  45116. bool KeyMappingEditorComponent::shouldCommandBeIncluded (const CommandID commandID)
  45117. {
  45118. const ApplicationCommandInfo* const ci = mappings->getCommandManager()->getCommandForID (commandID);
  45119. return (ci != 0) && ((ci->flags & ApplicationCommandInfo::hiddenFromKeyEditor) == 0);
  45120. }
  45121. bool KeyMappingEditorComponent::isCommandReadOnly (const CommandID commandID)
  45122. {
  45123. const ApplicationCommandInfo* const ci = mappings->getCommandManager()->getCommandForID (commandID);
  45124. return (ci != 0) && ((ci->flags & ApplicationCommandInfo::readOnlyInKeyEditor) != 0);
  45125. }
  45126. const String KeyMappingEditorComponent::getDescriptionForKeyPress (const KeyPress& key)
  45127. {
  45128. return key.getTextDescription();
  45129. }
  45130. END_JUCE_NAMESPACE
  45131. /********* End of inlined file: juce_KeyMappingEditorComponent.cpp *********/
  45132. /********* Start of inlined file: juce_KeyPress.cpp *********/
  45133. BEGIN_JUCE_NAMESPACE
  45134. KeyPress::KeyPress() throw()
  45135. : keyCode (0),
  45136. mods (0),
  45137. textCharacter (0)
  45138. {
  45139. }
  45140. KeyPress::KeyPress (const int keyCode_,
  45141. const ModifierKeys& mods_,
  45142. const juce_wchar textCharacter_) throw()
  45143. : keyCode (keyCode_),
  45144. mods (mods_),
  45145. textCharacter (textCharacter_)
  45146. {
  45147. }
  45148. KeyPress::KeyPress (const int keyCode_) throw()
  45149. : keyCode (keyCode_),
  45150. textCharacter (0)
  45151. {
  45152. }
  45153. KeyPress::KeyPress (const KeyPress& other) throw()
  45154. : keyCode (other.keyCode),
  45155. mods (other.mods),
  45156. textCharacter (other.textCharacter)
  45157. {
  45158. }
  45159. const KeyPress& KeyPress::operator= (const KeyPress& other) throw()
  45160. {
  45161. keyCode = other.keyCode;
  45162. mods = other.mods;
  45163. textCharacter = other.textCharacter;
  45164. return *this;
  45165. }
  45166. bool KeyPress::operator== (const KeyPress& other) const throw()
  45167. {
  45168. return mods.getRawFlags() == other.mods.getRawFlags()
  45169. && (textCharacter == other.textCharacter
  45170. || textCharacter == 0
  45171. || other.textCharacter == 0)
  45172. && (keyCode == other.keyCode
  45173. || (keyCode < 256
  45174. && other.keyCode < 256
  45175. && CharacterFunctions::toLowerCase ((tchar) keyCode)
  45176. == CharacterFunctions::toLowerCase ((tchar) other.keyCode)));
  45177. }
  45178. bool KeyPress::operator!= (const KeyPress& other) const throw()
  45179. {
  45180. return ! operator== (other);
  45181. }
  45182. bool KeyPress::isCurrentlyDown() const throw()
  45183. {
  45184. return isKeyCurrentlyDown (keyCode)
  45185. && (ModifierKeys::getCurrentModifiers().getRawFlags() & ModifierKeys::allKeyboardModifiers)
  45186. == (mods.getRawFlags() & ModifierKeys::allKeyboardModifiers);
  45187. }
  45188. struct KeyNameAndCode
  45189. {
  45190. const char* name;
  45191. int code;
  45192. };
  45193. static const KeyNameAndCode keyNameTranslations[] =
  45194. {
  45195. { "spacebar", KeyPress::spaceKey },
  45196. { "return", KeyPress::returnKey },
  45197. { "escape", KeyPress::escapeKey },
  45198. { "backspace", KeyPress::backspaceKey },
  45199. { "cursor left", KeyPress::leftKey },
  45200. { "cursor right", KeyPress::rightKey },
  45201. { "cursor up", KeyPress::upKey },
  45202. { "cursor down", KeyPress::downKey },
  45203. { "page up", KeyPress::pageUpKey },
  45204. { "page down", KeyPress::pageDownKey },
  45205. { "home", KeyPress::homeKey },
  45206. { "end", KeyPress::endKey },
  45207. { "delete", KeyPress::deleteKey },
  45208. { "insert", KeyPress::insertKey },
  45209. { "tab", KeyPress::tabKey },
  45210. { "play", KeyPress::playKey },
  45211. { "stop", KeyPress::stopKey },
  45212. { "fast forward", KeyPress::fastForwardKey },
  45213. { "rewind", KeyPress::rewindKey }
  45214. };
  45215. static const tchar* const numberPadPrefix = T("numpad ");
  45216. const KeyPress KeyPress::createFromDescription (const String& desc) throw()
  45217. {
  45218. int modifiers = 0;
  45219. if (desc.containsWholeWordIgnoreCase (T("ctrl"))
  45220. || desc.containsWholeWordIgnoreCase (T("control"))
  45221. || desc.containsWholeWordIgnoreCase (T("ctl")))
  45222. modifiers |= ModifierKeys::ctrlModifier;
  45223. if (desc.containsWholeWordIgnoreCase (T("shift"))
  45224. || desc.containsWholeWordIgnoreCase (T("shft")))
  45225. modifiers |= ModifierKeys::shiftModifier;
  45226. if (desc.containsWholeWordIgnoreCase (T("alt"))
  45227. || desc.containsWholeWordIgnoreCase (T("option")))
  45228. modifiers |= ModifierKeys::altModifier;
  45229. if (desc.containsWholeWordIgnoreCase (T("command"))
  45230. || desc.containsWholeWordIgnoreCase (T("cmd")))
  45231. modifiers |= ModifierKeys::commandModifier;
  45232. int key = 0;
  45233. for (int i = 0; i < numElementsInArray (keyNameTranslations); ++i)
  45234. {
  45235. if (desc.containsWholeWordIgnoreCase (String (keyNameTranslations[i].name)))
  45236. {
  45237. key = keyNameTranslations[i].code;
  45238. break;
  45239. }
  45240. }
  45241. if (key == 0)
  45242. {
  45243. // see if it's a numpad key..
  45244. if (desc.containsIgnoreCase (numberPadPrefix))
  45245. {
  45246. const tchar lastChar = desc.trimEnd().getLastCharacter();
  45247. if (lastChar >= T('0') && lastChar <= T('9'))
  45248. key = numberPad0 + lastChar - T('0');
  45249. else if (lastChar == T('+'))
  45250. key = numberPadAdd;
  45251. else if (lastChar == T('-'))
  45252. key = numberPadSubtract;
  45253. else if (lastChar == T('*'))
  45254. key = numberPadMultiply;
  45255. else if (lastChar == T('/'))
  45256. key = numberPadDivide;
  45257. else if (lastChar == T('.'))
  45258. key = numberPadDecimalPoint;
  45259. else if (lastChar == T('='))
  45260. key = numberPadEquals;
  45261. else if (desc.endsWith (T("separator")))
  45262. key = numberPadSeparator;
  45263. else if (desc.endsWith (T("delete")))
  45264. key = numberPadDelete;
  45265. }
  45266. if (key == 0)
  45267. {
  45268. // see if it's a function key..
  45269. for (int i = 1; i <= 12; ++i)
  45270. if (desc.containsWholeWordIgnoreCase (T("f") + String (i)))
  45271. key = F1Key + i - 1;
  45272. if (key == 0)
  45273. {
  45274. // give up and use the hex code..
  45275. const int hexCode = desc.fromFirstOccurrenceOf (T("#"), false, false)
  45276. .toLowerCase()
  45277. .retainCharacters (T("0123456789abcdef"))
  45278. .getHexValue32();
  45279. if (hexCode > 0)
  45280. key = hexCode;
  45281. else
  45282. key = CharacterFunctions::toUpperCase (desc.getLastCharacter());
  45283. }
  45284. }
  45285. }
  45286. return KeyPress (key, ModifierKeys (modifiers), 0);
  45287. }
  45288. const String KeyPress::getTextDescription() const throw()
  45289. {
  45290. String desc;
  45291. if (keyCode > 0)
  45292. {
  45293. // some keyboard layouts use a shift-key to get the slash, but in those cases, we
  45294. // want to store it as being a slash, not shift+whatever.
  45295. if (textCharacter == T('/'))
  45296. return "/";
  45297. if (mods.isCtrlDown())
  45298. desc << "ctrl + ";
  45299. if (mods.isShiftDown())
  45300. desc << "shift + ";
  45301. #if JUCE_MAC
  45302. // only do this on the mac, because on Windows ctrl and command are the same,
  45303. // and this would get confusing
  45304. if (mods.isCommandDown())
  45305. desc << "command + ";
  45306. if (mods.isAltDown())
  45307. desc << "option + ";
  45308. #else
  45309. if (mods.isAltDown())
  45310. desc << "alt + ";
  45311. #endif
  45312. for (int i = 0; i < numElementsInArray (keyNameTranslations); ++i)
  45313. if (keyCode == keyNameTranslations[i].code)
  45314. return desc + keyNameTranslations[i].name;
  45315. if (keyCode >= F1Key && keyCode <= F16Key)
  45316. desc << 'F' << (1 + keyCode - F1Key);
  45317. else if (keyCode >= numberPad0 && keyCode <= numberPad9)
  45318. desc << numberPadPrefix << (keyCode - numberPad0);
  45319. else if (keyCode >= 33 && keyCode < 176)
  45320. desc += CharacterFunctions::toUpperCase ((tchar) keyCode);
  45321. else if (keyCode == numberPadAdd)
  45322. desc << numberPadPrefix << '+';
  45323. else if (keyCode == numberPadSubtract)
  45324. desc << numberPadPrefix << '-';
  45325. else if (keyCode == numberPadMultiply)
  45326. desc << numberPadPrefix << '*';
  45327. else if (keyCode == numberPadDivide)
  45328. desc << numberPadPrefix << '/';
  45329. else if (keyCode == numberPadSeparator)
  45330. desc << numberPadPrefix << "separator";
  45331. else if (keyCode == numberPadDecimalPoint)
  45332. desc << numberPadPrefix << '.';
  45333. else if (keyCode == numberPadDelete)
  45334. desc << numberPadPrefix << "delete";
  45335. else
  45336. desc << '#' << String::toHexString (keyCode);
  45337. }
  45338. return desc;
  45339. }
  45340. END_JUCE_NAMESPACE
  45341. /********* End of inlined file: juce_KeyPress.cpp *********/
  45342. /********* Start of inlined file: juce_KeyPressMappingSet.cpp *********/
  45343. BEGIN_JUCE_NAMESPACE
  45344. KeyPressMappingSet::KeyPressMappingSet (ApplicationCommandManager* const commandManager_) throw()
  45345. : commandManager (commandManager_)
  45346. {
  45347. // A manager is needed to get the descriptions of commands, and will be called when
  45348. // a command is invoked. So you can't leave this null..
  45349. jassert (commandManager_ != 0);
  45350. Desktop::getInstance().addFocusChangeListener (this);
  45351. }
  45352. KeyPressMappingSet::KeyPressMappingSet (const KeyPressMappingSet& other) throw()
  45353. : commandManager (other.commandManager)
  45354. {
  45355. Desktop::getInstance().addFocusChangeListener (this);
  45356. }
  45357. KeyPressMappingSet::~KeyPressMappingSet()
  45358. {
  45359. Desktop::getInstance().removeFocusChangeListener (this);
  45360. }
  45361. const Array <KeyPress> KeyPressMappingSet::getKeyPressesAssignedToCommand (const CommandID commandID) const throw()
  45362. {
  45363. for (int i = 0; i < mappings.size(); ++i)
  45364. if (mappings.getUnchecked(i)->commandID == commandID)
  45365. return mappings.getUnchecked (i)->keypresses;
  45366. return Array <KeyPress> ();
  45367. }
  45368. void KeyPressMappingSet::addKeyPress (const CommandID commandID,
  45369. const KeyPress& newKeyPress,
  45370. int insertIndex) throw()
  45371. {
  45372. if (findCommandForKeyPress (newKeyPress) != commandID)
  45373. {
  45374. removeKeyPress (newKeyPress);
  45375. if (newKeyPress.isValid())
  45376. {
  45377. for (int i = mappings.size(); --i >= 0;)
  45378. {
  45379. if (mappings.getUnchecked(i)->commandID == commandID)
  45380. {
  45381. mappings.getUnchecked(i)->keypresses.insert (insertIndex, newKeyPress);
  45382. sendChangeMessage (this);
  45383. return;
  45384. }
  45385. }
  45386. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  45387. if (ci != 0)
  45388. {
  45389. CommandMapping* const cm = new CommandMapping();
  45390. cm->commandID = commandID;
  45391. cm->keypresses.add (newKeyPress);
  45392. cm->wantsKeyUpDownCallbacks = (ci->flags & ApplicationCommandInfo::wantsKeyUpDownCallbacks) != 0;
  45393. mappings.add (cm);
  45394. sendChangeMessage (this);
  45395. }
  45396. }
  45397. }
  45398. }
  45399. void KeyPressMappingSet::resetToDefaultMappings() throw()
  45400. {
  45401. mappings.clear();
  45402. for (int i = 0; i < commandManager->getNumCommands(); ++i)
  45403. {
  45404. const ApplicationCommandInfo* const ci = commandManager->getCommandForIndex (i);
  45405. for (int j = 0; j < ci->defaultKeypresses.size(); ++j)
  45406. {
  45407. addKeyPress (ci->commandID,
  45408. ci->defaultKeypresses.getReference (j));
  45409. }
  45410. }
  45411. sendChangeMessage (this);
  45412. }
  45413. void KeyPressMappingSet::resetToDefaultMapping (const CommandID commandID) throw()
  45414. {
  45415. clearAllKeyPresses (commandID);
  45416. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  45417. for (int j = 0; j < ci->defaultKeypresses.size(); ++j)
  45418. {
  45419. addKeyPress (ci->commandID,
  45420. ci->defaultKeypresses.getReference (j));
  45421. }
  45422. }
  45423. void KeyPressMappingSet::clearAllKeyPresses() throw()
  45424. {
  45425. if (mappings.size() > 0)
  45426. {
  45427. sendChangeMessage (this);
  45428. mappings.clear();
  45429. }
  45430. }
  45431. void KeyPressMappingSet::clearAllKeyPresses (const CommandID commandID) throw()
  45432. {
  45433. for (int i = mappings.size(); --i >= 0;)
  45434. {
  45435. if (mappings.getUnchecked(i)->commandID == commandID)
  45436. {
  45437. mappings.remove (i);
  45438. sendChangeMessage (this);
  45439. }
  45440. }
  45441. }
  45442. void KeyPressMappingSet::removeKeyPress (const KeyPress& keypress) throw()
  45443. {
  45444. if (keypress.isValid())
  45445. {
  45446. for (int i = mappings.size(); --i >= 0;)
  45447. {
  45448. CommandMapping* const cm = mappings.getUnchecked(i);
  45449. for (int j = cm->keypresses.size(); --j >= 0;)
  45450. {
  45451. if (keypress == cm->keypresses [j])
  45452. {
  45453. cm->keypresses.remove (j);
  45454. sendChangeMessage (this);
  45455. }
  45456. }
  45457. }
  45458. }
  45459. }
  45460. void KeyPressMappingSet::removeKeyPress (const CommandID commandID,
  45461. const int keyPressIndex) throw()
  45462. {
  45463. for (int i = mappings.size(); --i >= 0;)
  45464. {
  45465. if (mappings.getUnchecked(i)->commandID == commandID)
  45466. {
  45467. mappings.getUnchecked(i)->keypresses.remove (keyPressIndex);
  45468. sendChangeMessage (this);
  45469. break;
  45470. }
  45471. }
  45472. }
  45473. CommandID KeyPressMappingSet::findCommandForKeyPress (const KeyPress& keyPress) const throw()
  45474. {
  45475. for (int i = 0; i < mappings.size(); ++i)
  45476. if (mappings.getUnchecked(i)->keypresses.contains (keyPress))
  45477. return mappings.getUnchecked(i)->commandID;
  45478. return 0;
  45479. }
  45480. bool KeyPressMappingSet::containsMapping (const CommandID commandID,
  45481. const KeyPress& keyPress) const throw()
  45482. {
  45483. for (int i = mappings.size(); --i >= 0;)
  45484. if (mappings.getUnchecked(i)->commandID == commandID)
  45485. return mappings.getUnchecked(i)->keypresses.contains (keyPress);
  45486. return false;
  45487. }
  45488. void KeyPressMappingSet::invokeCommand (const CommandID commandID,
  45489. const KeyPress& key,
  45490. const bool isKeyDown,
  45491. const int millisecsSinceKeyPressed,
  45492. Component* const originatingComponent) const
  45493. {
  45494. ApplicationCommandTarget::InvocationInfo info (commandID);
  45495. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromKeyPress;
  45496. info.isKeyDown = isKeyDown;
  45497. info.keyPress = key;
  45498. info.millisecsSinceKeyPressed = millisecsSinceKeyPressed;
  45499. info.originatingComponent = originatingComponent;
  45500. commandManager->invoke (info, false);
  45501. }
  45502. bool KeyPressMappingSet::restoreFromXml (const XmlElement& xmlVersion)
  45503. {
  45504. if (xmlVersion.hasTagName (T("KEYMAPPINGS")))
  45505. {
  45506. if (xmlVersion.getBoolAttribute (T("basedOnDefaults"), true))
  45507. {
  45508. // if the XML was created as a set of differences from the default mappings,
  45509. // (i.e. by calling createXml (true)), then we need to first restore the defaults.
  45510. resetToDefaultMappings();
  45511. }
  45512. else
  45513. {
  45514. // if the XML was created calling createXml (false), then we need to clear all
  45515. // the keys and treat the xml as describing the entire set of mappings.
  45516. clearAllKeyPresses();
  45517. }
  45518. forEachXmlChildElement (xmlVersion, map)
  45519. {
  45520. const CommandID commandId = map->getStringAttribute (T("commandId")).getHexValue32();
  45521. if (commandId != 0)
  45522. {
  45523. const KeyPress key (KeyPress::createFromDescription (map->getStringAttribute (T("key"))));
  45524. if (map->hasTagName (T("MAPPING")))
  45525. {
  45526. addKeyPress (commandId, key);
  45527. }
  45528. else if (map->hasTagName (T("UNMAPPING")))
  45529. {
  45530. if (containsMapping (commandId, key))
  45531. removeKeyPress (key);
  45532. }
  45533. }
  45534. }
  45535. return true;
  45536. }
  45537. return false;
  45538. }
  45539. XmlElement* KeyPressMappingSet::createXml (const bool saveDifferencesFromDefaultSet) const
  45540. {
  45541. KeyPressMappingSet* defaultSet = 0;
  45542. if (saveDifferencesFromDefaultSet)
  45543. {
  45544. defaultSet = new KeyPressMappingSet (commandManager);
  45545. defaultSet->resetToDefaultMappings();
  45546. }
  45547. XmlElement* const doc = new XmlElement (T("KEYMAPPINGS"));
  45548. doc->setAttribute (T("basedOnDefaults"), saveDifferencesFromDefaultSet);
  45549. int i;
  45550. for (i = 0; i < mappings.size(); ++i)
  45551. {
  45552. const CommandMapping* const cm = mappings.getUnchecked(i);
  45553. for (int j = 0; j < cm->keypresses.size(); ++j)
  45554. {
  45555. if (defaultSet == 0
  45556. || ! defaultSet->containsMapping (cm->commandID, cm->keypresses.getReference (j)))
  45557. {
  45558. XmlElement* const map = new XmlElement (T("MAPPING"));
  45559. map->setAttribute (T("commandId"), String::toHexString ((int) cm->commandID));
  45560. map->setAttribute (T("description"), commandManager->getDescriptionOfCommand (cm->commandID));
  45561. map->setAttribute (T("key"), cm->keypresses.getReference (j).getTextDescription());
  45562. doc->addChildElement (map);
  45563. }
  45564. }
  45565. }
  45566. if (defaultSet != 0)
  45567. {
  45568. for (i = 0; i < defaultSet->mappings.size(); ++i)
  45569. {
  45570. const CommandMapping* const cm = defaultSet->mappings.getUnchecked(i);
  45571. for (int j = 0; j < cm->keypresses.size(); ++j)
  45572. {
  45573. if (! containsMapping (cm->commandID, cm->keypresses.getReference (j)))
  45574. {
  45575. XmlElement* const map = new XmlElement (T("UNMAPPING"));
  45576. map->setAttribute (T("commandId"), String::toHexString ((int) cm->commandID));
  45577. map->setAttribute (T("description"), commandManager->getDescriptionOfCommand (cm->commandID));
  45578. map->setAttribute (T("key"), cm->keypresses.getReference (j).getTextDescription());
  45579. doc->addChildElement (map);
  45580. }
  45581. }
  45582. }
  45583. delete defaultSet;
  45584. }
  45585. return doc;
  45586. }
  45587. bool KeyPressMappingSet::keyPressed (const KeyPress& key,
  45588. Component* originatingComponent)
  45589. {
  45590. bool used = false;
  45591. const CommandID commandID = findCommandForKeyPress (key);
  45592. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  45593. if (ci != 0
  45594. && (ci->flags & ApplicationCommandInfo::wantsKeyUpDownCallbacks) == 0)
  45595. {
  45596. ApplicationCommandInfo info (0);
  45597. if (commandManager->getTargetForCommand (commandID, info) != 0
  45598. && (info.flags & ApplicationCommandInfo::isDisabled) == 0)
  45599. {
  45600. invokeCommand (commandID, key, true, 0, originatingComponent);
  45601. used = true;
  45602. }
  45603. else
  45604. {
  45605. if (originatingComponent != 0)
  45606. originatingComponent->getLookAndFeel().playAlertSound();
  45607. }
  45608. }
  45609. return used;
  45610. }
  45611. bool KeyPressMappingSet::keyStateChanged (const bool /*isKeyDown*/, Component* originatingComponent)
  45612. {
  45613. bool used = false;
  45614. const uint32 now = Time::getMillisecondCounter();
  45615. for (int i = mappings.size(); --i >= 0;)
  45616. {
  45617. CommandMapping* const cm = mappings.getUnchecked(i);
  45618. if (cm->wantsKeyUpDownCallbacks)
  45619. {
  45620. for (int j = cm->keypresses.size(); --j >= 0;)
  45621. {
  45622. const KeyPress key (cm->keypresses.getReference (j));
  45623. const bool isDown = key.isCurrentlyDown();
  45624. int keyPressEntryIndex = 0;
  45625. bool wasDown = false;
  45626. for (int k = keysDown.size(); --k >= 0;)
  45627. {
  45628. if (key == keysDown.getUnchecked(k)->key)
  45629. {
  45630. keyPressEntryIndex = k;
  45631. wasDown = true;
  45632. used = true;
  45633. break;
  45634. }
  45635. }
  45636. if (isDown != wasDown)
  45637. {
  45638. int millisecs = 0;
  45639. if (isDown)
  45640. {
  45641. KeyPressTime* const k = new KeyPressTime();
  45642. k->key = key;
  45643. k->timeWhenPressed = now;
  45644. keysDown.add (k);
  45645. }
  45646. else
  45647. {
  45648. const uint32 pressTime = keysDown.getUnchecked (keyPressEntryIndex)->timeWhenPressed;
  45649. if (now > pressTime)
  45650. millisecs = now - pressTime;
  45651. keysDown.remove (keyPressEntryIndex);
  45652. }
  45653. invokeCommand (cm->commandID, key, isDown, millisecs, originatingComponent);
  45654. used = true;
  45655. }
  45656. }
  45657. }
  45658. }
  45659. return used;
  45660. }
  45661. void KeyPressMappingSet::globalFocusChanged (Component* focusedComponent)
  45662. {
  45663. if (focusedComponent != 0)
  45664. focusedComponent->keyStateChanged (false);
  45665. }
  45666. END_JUCE_NAMESPACE
  45667. /********* End of inlined file: juce_KeyPressMappingSet.cpp *********/
  45668. /********* Start of inlined file: juce_ModifierKeys.cpp *********/
  45669. BEGIN_JUCE_NAMESPACE
  45670. ModifierKeys::ModifierKeys (const int flags_) throw()
  45671. : flags (flags_)
  45672. {
  45673. }
  45674. ModifierKeys::ModifierKeys (const ModifierKeys& other) throw()
  45675. : flags (other.flags)
  45676. {
  45677. }
  45678. const ModifierKeys& ModifierKeys::operator= (const ModifierKeys& other) throw()
  45679. {
  45680. flags = other.flags;
  45681. return *this;
  45682. }
  45683. int ModifierKeys::currentModifierFlags = 0;
  45684. const ModifierKeys ModifierKeys::getCurrentModifiers() throw()
  45685. {
  45686. return ModifierKeys (currentModifierFlags);
  45687. }
  45688. END_JUCE_NAMESPACE
  45689. /********* End of inlined file: juce_ModifierKeys.cpp *********/
  45690. /********* Start of inlined file: juce_ComponentAnimator.cpp *********/
  45691. BEGIN_JUCE_NAMESPACE
  45692. struct AnimationTask
  45693. {
  45694. AnimationTask (Component* const comp)
  45695. : component (comp),
  45696. watcher (comp)
  45697. {
  45698. }
  45699. Component* component;
  45700. ComponentDeletionWatcher watcher;
  45701. Rectangle destination;
  45702. int msElapsed, msTotal;
  45703. double startSpeed, midSpeed, endSpeed, lastProgress;
  45704. double left, top, right, bottom;
  45705. bool useTimeslice (const int elapsed)
  45706. {
  45707. if (watcher.hasBeenDeleted())
  45708. return false;
  45709. msElapsed += elapsed;
  45710. double newProgress = msElapsed / (double) msTotal;
  45711. if (newProgress >= 0 && newProgress < 1.0)
  45712. {
  45713. newProgress = timeToDistance (newProgress);
  45714. const double delta = (newProgress - lastProgress) / (1.0 - lastProgress);
  45715. jassert (newProgress >= lastProgress);
  45716. lastProgress = newProgress;
  45717. left += (destination.getX() - left) * delta;
  45718. top += (destination.getY() - top) * delta;
  45719. right += (destination.getRight() - right) * delta;
  45720. bottom += (destination.getBottom() - bottom) * delta;
  45721. if (delta < 1.0)
  45722. {
  45723. const Rectangle newBounds (roundDoubleToInt (left),
  45724. roundDoubleToInt (top),
  45725. roundDoubleToInt (right - left),
  45726. roundDoubleToInt (bottom - top));
  45727. if (newBounds != destination)
  45728. {
  45729. component->setBounds (newBounds);
  45730. return true;
  45731. }
  45732. }
  45733. }
  45734. component->setBounds (destination);
  45735. return false;
  45736. }
  45737. void moveToFinalDestination()
  45738. {
  45739. if (! watcher.hasBeenDeleted())
  45740. component->setBounds (destination);
  45741. }
  45742. private:
  45743. inline double timeToDistance (const double time) const
  45744. {
  45745. return (time < 0.5) ? time * (startSpeed + time * (midSpeed - startSpeed))
  45746. : 0.5 * (startSpeed + 0.5 * (midSpeed - startSpeed))
  45747. + (time - 0.5) * (midSpeed + (time - 0.5) * (endSpeed - midSpeed));
  45748. }
  45749. };
  45750. ComponentAnimator::ComponentAnimator()
  45751. : lastTime (0)
  45752. {
  45753. }
  45754. ComponentAnimator::~ComponentAnimator()
  45755. {
  45756. cancelAllAnimations (false);
  45757. jassert (tasks.size() == 0);
  45758. }
  45759. void* ComponentAnimator::findTaskFor (Component* const component) const
  45760. {
  45761. for (int i = tasks.size(); --i >= 0;)
  45762. if (component == ((AnimationTask*) tasks.getUnchecked(i))->component)
  45763. return tasks.getUnchecked(i);
  45764. return 0;
  45765. }
  45766. void ComponentAnimator::animateComponent (Component* const component,
  45767. const Rectangle& finalPosition,
  45768. const int millisecondsToSpendMoving,
  45769. const double startSpeed,
  45770. const double endSpeed)
  45771. {
  45772. if (component != 0)
  45773. {
  45774. AnimationTask* at = (AnimationTask*) findTaskFor (component);
  45775. if (at == 0)
  45776. {
  45777. at = new AnimationTask (component);
  45778. tasks.add (at);
  45779. sendChangeMessage (this);
  45780. }
  45781. at->msElapsed = 0;
  45782. at->lastProgress = 0;
  45783. at->msTotal = jmax (1, millisecondsToSpendMoving);
  45784. at->destination = finalPosition;
  45785. // the speeds must be 0 or greater!
  45786. jassert (startSpeed >= 0 && endSpeed >= 0)
  45787. const double invTotalDistance = 4.0 / (startSpeed + endSpeed + 2.0);
  45788. at->startSpeed = jmax (0.0, startSpeed * invTotalDistance);
  45789. at->midSpeed = invTotalDistance;
  45790. at->endSpeed = jmax (0.0, endSpeed * invTotalDistance);
  45791. at->left = component->getX();
  45792. at->top = component->getY();
  45793. at->right = component->getRight();
  45794. at->bottom = component->getBottom();
  45795. if (! isTimerRunning())
  45796. {
  45797. lastTime = Time::getMillisecondCounter();
  45798. startTimer (1000 / 50);
  45799. }
  45800. }
  45801. }
  45802. void ComponentAnimator::cancelAllAnimations (const bool moveComponentsToTheirFinalPositions)
  45803. {
  45804. for (int i = tasks.size(); --i >= 0;)
  45805. {
  45806. AnimationTask* const at = (AnimationTask*) tasks.getUnchecked(i);
  45807. if (moveComponentsToTheirFinalPositions)
  45808. at->moveToFinalDestination();
  45809. delete at;
  45810. tasks.remove (i);
  45811. sendChangeMessage (this);
  45812. }
  45813. }
  45814. void ComponentAnimator::cancelAnimation (Component* const component,
  45815. const bool moveComponentToItsFinalPosition)
  45816. {
  45817. AnimationTask* const at = (AnimationTask*) findTaskFor (component);
  45818. if (at != 0)
  45819. {
  45820. if (moveComponentToItsFinalPosition)
  45821. at->moveToFinalDestination();
  45822. tasks.removeValue (at);
  45823. delete at;
  45824. sendChangeMessage (this);
  45825. }
  45826. }
  45827. const Rectangle ComponentAnimator::getComponentDestination (Component* const component)
  45828. {
  45829. AnimationTask* const at = (AnimationTask*) findTaskFor (component);
  45830. if (at != 0)
  45831. return at->destination;
  45832. else if (component != 0)
  45833. return component->getBounds();
  45834. return Rectangle();
  45835. }
  45836. bool ComponentAnimator::isAnimating (Component* component) const
  45837. {
  45838. return findTaskFor (component) != 0;
  45839. }
  45840. void ComponentAnimator::timerCallback()
  45841. {
  45842. const uint32 timeNow = Time::getMillisecondCounter();
  45843. if (lastTime == 0 || lastTime == timeNow)
  45844. lastTime = timeNow;
  45845. const int elapsed = timeNow - lastTime;
  45846. for (int i = tasks.size(); --i >= 0;)
  45847. {
  45848. AnimationTask* const at = (AnimationTask*) tasks.getUnchecked(i);
  45849. if (! at->useTimeslice (elapsed))
  45850. {
  45851. tasks.remove (i);
  45852. delete at;
  45853. sendChangeMessage (this);
  45854. }
  45855. }
  45856. lastTime = timeNow;
  45857. if (tasks.size() == 0)
  45858. stopTimer();
  45859. }
  45860. END_JUCE_NAMESPACE
  45861. /********* End of inlined file: juce_ComponentAnimator.cpp *********/
  45862. /********* Start of inlined file: juce_ComponentBoundsConstrainer.cpp *********/
  45863. BEGIN_JUCE_NAMESPACE
  45864. ComponentBoundsConstrainer::ComponentBoundsConstrainer() throw()
  45865. : minW (0),
  45866. maxW (0x3fffffff),
  45867. minH (0),
  45868. maxH (0x3fffffff),
  45869. minOffTop (0),
  45870. minOffLeft (0),
  45871. minOffBottom (0),
  45872. minOffRight (0),
  45873. aspectRatio (0.0)
  45874. {
  45875. }
  45876. ComponentBoundsConstrainer::~ComponentBoundsConstrainer()
  45877. {
  45878. }
  45879. void ComponentBoundsConstrainer::setMinimumWidth (const int minimumWidth) throw()
  45880. {
  45881. minW = minimumWidth;
  45882. }
  45883. void ComponentBoundsConstrainer::setMaximumWidth (const int maximumWidth) throw()
  45884. {
  45885. maxW = maximumWidth;
  45886. }
  45887. void ComponentBoundsConstrainer::setMinimumHeight (const int minimumHeight) throw()
  45888. {
  45889. minH = minimumHeight;
  45890. }
  45891. void ComponentBoundsConstrainer::setMaximumHeight (const int maximumHeight) throw()
  45892. {
  45893. maxH = maximumHeight;
  45894. }
  45895. void ComponentBoundsConstrainer::setMinimumSize (const int minimumWidth, const int minimumHeight) throw()
  45896. {
  45897. jassert (maxW >= minimumWidth);
  45898. jassert (maxH >= minimumHeight);
  45899. jassert (minimumWidth > 0 && minimumHeight > 0);
  45900. minW = minimumWidth;
  45901. minH = minimumHeight;
  45902. if (minW > maxW)
  45903. maxW = minW;
  45904. if (minH > maxH)
  45905. maxH = minH;
  45906. }
  45907. void ComponentBoundsConstrainer::setMaximumSize (const int maximumWidth, const int maximumHeight) throw()
  45908. {
  45909. jassert (maximumWidth >= minW);
  45910. jassert (maximumHeight >= minH);
  45911. jassert (maximumWidth > 0 && maximumHeight > 0);
  45912. maxW = jmax (minW, maximumWidth);
  45913. maxH = jmax (minH, maximumHeight);
  45914. }
  45915. void ComponentBoundsConstrainer::setSizeLimits (const int minimumWidth,
  45916. const int minimumHeight,
  45917. const int maximumWidth,
  45918. const int maximumHeight) throw()
  45919. {
  45920. jassert (maximumWidth >= minimumWidth);
  45921. jassert (maximumHeight >= minimumHeight);
  45922. jassert (maximumWidth > 0 && maximumHeight > 0);
  45923. jassert (minimumWidth > 0 && minimumHeight > 0);
  45924. minW = jmax (0, minimumWidth);
  45925. minH = jmax (0, minimumHeight);
  45926. maxW = jmax (minW, maximumWidth);
  45927. maxH = jmax (minH, maximumHeight);
  45928. }
  45929. void ComponentBoundsConstrainer::setMinimumOnscreenAmounts (const int minimumWhenOffTheTop,
  45930. const int minimumWhenOffTheLeft,
  45931. const int minimumWhenOffTheBottom,
  45932. const int minimumWhenOffTheRight) throw()
  45933. {
  45934. minOffTop = minimumWhenOffTheTop;
  45935. minOffLeft = minimumWhenOffTheLeft;
  45936. minOffBottom = minimumWhenOffTheBottom;
  45937. minOffRight = minimumWhenOffTheRight;
  45938. }
  45939. void ComponentBoundsConstrainer::setFixedAspectRatio (const double widthOverHeight) throw()
  45940. {
  45941. aspectRatio = jmax (0.0, widthOverHeight);
  45942. }
  45943. double ComponentBoundsConstrainer::getFixedAspectRatio() const throw()
  45944. {
  45945. return aspectRatio;
  45946. }
  45947. void ComponentBoundsConstrainer::setBoundsForComponent (Component* const component,
  45948. int x, int y, int w, int h,
  45949. const bool isStretchingTop,
  45950. const bool isStretchingLeft,
  45951. const bool isStretchingBottom,
  45952. const bool isStretchingRight)
  45953. {
  45954. jassert (component != 0);
  45955. Rectangle limits;
  45956. Component* const p = component->getParentComponent();
  45957. if (p == 0)
  45958. limits = Desktop::getInstance().getAllMonitorDisplayAreas().getBounds();
  45959. else
  45960. limits.setSize (p->getWidth(), p->getHeight());
  45961. if (component->isOnDesktop())
  45962. {
  45963. ComponentPeer* const peer = component->getPeer();
  45964. const BorderSize border (peer->getFrameSize());
  45965. x -= border.getLeft();
  45966. y -= border.getTop();
  45967. w += border.getLeftAndRight();
  45968. h += border.getTopAndBottom();
  45969. checkBounds (x, y, w, h,
  45970. border.addedTo (component->getBounds()), limits,
  45971. isStretchingTop, isStretchingLeft,
  45972. isStretchingBottom, isStretchingRight);
  45973. x += border.getLeft();
  45974. y += border.getTop();
  45975. w -= border.getLeftAndRight();
  45976. h -= border.getTopAndBottom();
  45977. }
  45978. else
  45979. {
  45980. checkBounds (x, y, w, h,
  45981. component->getBounds(), limits,
  45982. isStretchingTop, isStretchingLeft,
  45983. isStretchingBottom, isStretchingRight);
  45984. }
  45985. applyBoundsToComponent (component, x, y, w, h);
  45986. }
  45987. void ComponentBoundsConstrainer::checkComponentBounds (Component* component)
  45988. {
  45989. setBoundsForComponent (component,
  45990. component->getX(), component->getY(),
  45991. component->getWidth(), component->getHeight(),
  45992. false, false, false, false);
  45993. }
  45994. void ComponentBoundsConstrainer::applyBoundsToComponent (Component* component,
  45995. int x, int y, int w, int h)
  45996. {
  45997. component->setBounds (x, y, w, h);
  45998. }
  45999. void ComponentBoundsConstrainer::resizeStart()
  46000. {
  46001. }
  46002. void ComponentBoundsConstrainer::resizeEnd()
  46003. {
  46004. }
  46005. void ComponentBoundsConstrainer::checkBounds (int& x, int& y, int& w, int& h,
  46006. const Rectangle& old,
  46007. const Rectangle& limits,
  46008. const bool isStretchingTop,
  46009. const bool isStretchingLeft,
  46010. const bool isStretchingBottom,
  46011. const bool isStretchingRight)
  46012. {
  46013. // constrain the size if it's being stretched..
  46014. if (isStretchingLeft)
  46015. {
  46016. x = jlimit (old.getRight() - maxW, old.getRight() - minW, x);
  46017. w = old.getRight() - x;
  46018. }
  46019. if (isStretchingRight)
  46020. {
  46021. w = jlimit (minW, maxW, w);
  46022. }
  46023. if (isStretchingTop)
  46024. {
  46025. y = jlimit (old.getBottom() - maxH, old.getBottom() - minH, y);
  46026. h = old.getBottom() - y;
  46027. }
  46028. if (isStretchingBottom)
  46029. {
  46030. h = jlimit (minH, maxH, h);
  46031. }
  46032. // constrain the aspect ratio if one has been specified..
  46033. if (aspectRatio > 0.0 && w > 0 && h > 0)
  46034. {
  46035. bool adjustWidth;
  46036. if ((isStretchingTop || isStretchingBottom) && ! (isStretchingLeft || isStretchingRight))
  46037. {
  46038. adjustWidth = true;
  46039. }
  46040. else if ((isStretchingLeft || isStretchingRight) && ! (isStretchingTop || isStretchingBottom))
  46041. {
  46042. adjustWidth = false;
  46043. }
  46044. else
  46045. {
  46046. const double oldRatio = (old.getHeight() > 0) ? fabs (old.getWidth() / (double) old.getHeight()) : 0.0;
  46047. const double newRatio = fabs (w / (double) h);
  46048. adjustWidth = (oldRatio > newRatio);
  46049. }
  46050. if (adjustWidth)
  46051. {
  46052. w = roundDoubleToInt (h * aspectRatio);
  46053. if (w > maxW || w < minW)
  46054. {
  46055. w = jlimit (minW, maxW, w);
  46056. h = roundDoubleToInt (w / aspectRatio);
  46057. }
  46058. }
  46059. else
  46060. {
  46061. h = roundDoubleToInt (w / aspectRatio);
  46062. if (h > maxH || h < minH)
  46063. {
  46064. h = jlimit (minH, maxH, h);
  46065. w = roundDoubleToInt (h * aspectRatio);
  46066. }
  46067. }
  46068. if ((isStretchingTop || isStretchingBottom) && ! (isStretchingLeft || isStretchingRight))
  46069. {
  46070. x = old.getX() + (old.getWidth() - w) / 2;
  46071. }
  46072. else if ((isStretchingLeft || isStretchingRight) && ! (isStretchingTop || isStretchingBottom))
  46073. {
  46074. y = old.getY() + (old.getHeight() - h) / 2;
  46075. }
  46076. else
  46077. {
  46078. if (isStretchingLeft)
  46079. x = old.getRight() - w;
  46080. if (isStretchingTop)
  46081. y = old.getBottom() - h;
  46082. }
  46083. }
  46084. // ...and constrain the position if limits have been set for that.
  46085. if (minOffTop > 0 || minOffLeft > 0 || minOffBottom > 0 || minOffRight > 0)
  46086. {
  46087. if (minOffTop > 0)
  46088. {
  46089. const int limit = limits.getY() + jmin (minOffTop - h, 0);
  46090. if (y < limit)
  46091. {
  46092. if (isStretchingTop)
  46093. h -= (limit - y);
  46094. y = limit;
  46095. }
  46096. }
  46097. if (minOffLeft > 0)
  46098. {
  46099. const int limit = limits.getX() + jmin (minOffLeft - w, 0);
  46100. if (x < limit)
  46101. {
  46102. if (isStretchingLeft)
  46103. w -= (limit - x);
  46104. x = limit;
  46105. }
  46106. }
  46107. if (minOffBottom > 0)
  46108. {
  46109. const int limit = limits.getBottom() - jmin (minOffBottom, h);
  46110. if (y > limit)
  46111. {
  46112. if (isStretchingBottom)
  46113. h += (limit - y);
  46114. else
  46115. y = limit;
  46116. }
  46117. }
  46118. if (minOffRight > 0)
  46119. {
  46120. const int limit = limits.getRight() - jmin (minOffRight, w);
  46121. if (x > limit)
  46122. {
  46123. if (isStretchingRight)
  46124. w += (limit - x);
  46125. else
  46126. x = limit;
  46127. }
  46128. }
  46129. }
  46130. jassert (w >= 0 && h >= 0);
  46131. }
  46132. END_JUCE_NAMESPACE
  46133. /********* End of inlined file: juce_ComponentBoundsConstrainer.cpp *********/
  46134. /********* Start of inlined file: juce_ComponentMovementWatcher.cpp *********/
  46135. BEGIN_JUCE_NAMESPACE
  46136. ComponentMovementWatcher::ComponentMovementWatcher (Component* const component_)
  46137. : component (component_),
  46138. lastPeer (0),
  46139. registeredParentComps (4),
  46140. reentrant (false)
  46141. {
  46142. jassert (component != 0); // can't use this with a null pointer..
  46143. #ifdef JUCE_DEBUG
  46144. deletionWatcher = new ComponentDeletionWatcher (component_);
  46145. #endif
  46146. component->addComponentListener (this);
  46147. registerWithParentComps();
  46148. }
  46149. ComponentMovementWatcher::~ComponentMovementWatcher()
  46150. {
  46151. component->removeComponentListener (this);
  46152. unregister();
  46153. #ifdef JUCE_DEBUG
  46154. delete deletionWatcher;
  46155. #endif
  46156. }
  46157. void ComponentMovementWatcher::componentParentHierarchyChanged (Component&)
  46158. {
  46159. #ifdef JUCE_DEBUG
  46160. // agh! don't delete the target component without deleting this object first!
  46161. jassert (! deletionWatcher->hasBeenDeleted());
  46162. #endif
  46163. if (! reentrant)
  46164. {
  46165. reentrant = true;
  46166. ComponentPeer* const peer = component->getPeer();
  46167. if (peer != lastPeer)
  46168. {
  46169. ComponentDeletionWatcher watcher (component);
  46170. componentPeerChanged();
  46171. if (watcher.hasBeenDeleted())
  46172. return;
  46173. lastPeer = peer;
  46174. }
  46175. unregister();
  46176. registerWithParentComps();
  46177. reentrant = false;
  46178. componentMovedOrResized (*component, true, true);
  46179. }
  46180. }
  46181. void ComponentMovementWatcher::componentMovedOrResized (Component&, bool wasMoved, bool wasResized)
  46182. {
  46183. #ifdef JUCE_DEBUG
  46184. // agh! don't delete the target component without deleting this object first!
  46185. jassert (! deletionWatcher->hasBeenDeleted());
  46186. #endif
  46187. if (wasMoved)
  46188. {
  46189. int x = 0, y = 0;
  46190. component->relativePositionToOtherComponent (component->getTopLevelComponent(), x, y);
  46191. wasMoved = (lastX != x || lastY != y);
  46192. lastX = x;
  46193. lastY = y;
  46194. }
  46195. wasResized = (lastWidth != component->getWidth() || lastHeight != component->getHeight());
  46196. lastWidth = component->getWidth();
  46197. lastHeight = component->getHeight();
  46198. if (wasMoved || wasResized)
  46199. componentMovedOrResized (wasMoved, wasResized);
  46200. }
  46201. void ComponentMovementWatcher::registerWithParentComps() throw()
  46202. {
  46203. Component* p = component->getParentComponent();
  46204. while (p != 0)
  46205. {
  46206. p->addComponentListener (this);
  46207. registeredParentComps.add (p);
  46208. p = p->getParentComponent();
  46209. }
  46210. }
  46211. void ComponentMovementWatcher::unregister() throw()
  46212. {
  46213. for (int i = registeredParentComps.size(); --i >= 0;)
  46214. ((Component*) registeredParentComps.getUnchecked(i))->removeComponentListener (this);
  46215. registeredParentComps.clear();
  46216. }
  46217. END_JUCE_NAMESPACE
  46218. /********* End of inlined file: juce_ComponentMovementWatcher.cpp *********/
  46219. /********* Start of inlined file: juce_GroupComponent.cpp *********/
  46220. BEGIN_JUCE_NAMESPACE
  46221. GroupComponent::GroupComponent (const String& componentName,
  46222. const String& labelText)
  46223. : Component (componentName),
  46224. text (labelText),
  46225. justification (Justification::left)
  46226. {
  46227. setInterceptsMouseClicks (false, true);
  46228. }
  46229. GroupComponent::~GroupComponent()
  46230. {
  46231. }
  46232. void GroupComponent::setText (const String& newText) throw()
  46233. {
  46234. if (text != newText)
  46235. {
  46236. text = newText;
  46237. repaint();
  46238. }
  46239. }
  46240. const String GroupComponent::getText() const throw()
  46241. {
  46242. return text;
  46243. }
  46244. void GroupComponent::setTextLabelPosition (const Justification& newJustification)
  46245. {
  46246. if (justification.getFlags() != newJustification.getFlags())
  46247. {
  46248. justification = newJustification;
  46249. repaint();
  46250. }
  46251. }
  46252. void GroupComponent::paint (Graphics& g)
  46253. {
  46254. getLookAndFeel()
  46255. .drawGroupComponentOutline (g, getWidth(), getHeight(),
  46256. text, justification,
  46257. *this);
  46258. }
  46259. void GroupComponent::enablementChanged()
  46260. {
  46261. repaint();
  46262. }
  46263. void GroupComponent::colourChanged()
  46264. {
  46265. repaint();
  46266. }
  46267. END_JUCE_NAMESPACE
  46268. /********* End of inlined file: juce_GroupComponent.cpp *********/
  46269. /********* Start of inlined file: juce_MultiDocumentPanel.cpp *********/
  46270. BEGIN_JUCE_NAMESPACE
  46271. MultiDocumentPanelWindow::MultiDocumentPanelWindow (const Colour& backgroundColour)
  46272. : DocumentWindow (String::empty, backgroundColour,
  46273. DocumentWindow::maximiseButton | DocumentWindow::closeButton, false)
  46274. {
  46275. }
  46276. MultiDocumentPanelWindow::~MultiDocumentPanelWindow()
  46277. {
  46278. }
  46279. void MultiDocumentPanelWindow::maximiseButtonPressed()
  46280. {
  46281. MultiDocumentPanel* const owner = getOwner();
  46282. jassert (owner != 0); // these windows are only designed to be used inside a MultiDocumentPanel!
  46283. if (owner != 0)
  46284. owner->setLayoutMode (MultiDocumentPanel::MaximisedWindowsWithTabs);
  46285. }
  46286. void MultiDocumentPanelWindow::closeButtonPressed()
  46287. {
  46288. MultiDocumentPanel* const owner = getOwner();
  46289. jassert (owner != 0); // these windows are only designed to be used inside a MultiDocumentPanel!
  46290. if (owner != 0)
  46291. owner->closeDocument (getContentComponent(), true);
  46292. }
  46293. void MultiDocumentPanelWindow::activeWindowStatusChanged()
  46294. {
  46295. DocumentWindow::activeWindowStatusChanged();
  46296. updateOrder();
  46297. }
  46298. void MultiDocumentPanelWindow::broughtToFront()
  46299. {
  46300. DocumentWindow::broughtToFront();
  46301. updateOrder();
  46302. }
  46303. void MultiDocumentPanelWindow::updateOrder()
  46304. {
  46305. MultiDocumentPanel* const owner = getOwner();
  46306. if (owner != 0)
  46307. owner->updateOrder();
  46308. }
  46309. MultiDocumentPanel* MultiDocumentPanelWindow::getOwner() const throw()
  46310. {
  46311. // (unable to use the syntax findParentComponentOfClass <MultiDocumentPanel> () because of a VC6 compiler bug)
  46312. return findParentComponentOfClass ((MultiDocumentPanel*) 0);
  46313. }
  46314. class MDITabbedComponentInternal : public TabbedComponent
  46315. {
  46316. public:
  46317. MDITabbedComponentInternal()
  46318. : TabbedComponent (TabbedButtonBar::TabsAtTop)
  46319. {
  46320. }
  46321. ~MDITabbedComponentInternal()
  46322. {
  46323. }
  46324. void currentTabChanged (const int, const String&)
  46325. {
  46326. // (unable to use the syntax findParentComponentOfClass <MultiDocumentPanel> () because of a VC6 compiler bug)
  46327. MultiDocumentPanel* const owner = findParentComponentOfClass ((MultiDocumentPanel*) 0);
  46328. if (owner != 0)
  46329. owner->updateOrder();
  46330. }
  46331. };
  46332. MultiDocumentPanel::MultiDocumentPanel()
  46333. : mode (MaximisedWindowsWithTabs),
  46334. tabComponent (0),
  46335. backgroundColour (Colours::lightblue),
  46336. maximumNumDocuments (0),
  46337. numDocsBeforeTabsUsed (0)
  46338. {
  46339. setOpaque (true);
  46340. }
  46341. MultiDocumentPanel::~MultiDocumentPanel()
  46342. {
  46343. closeAllDocuments (false);
  46344. }
  46345. static bool shouldDeleteComp (Component* const c)
  46346. {
  46347. return c->getComponentPropertyBool (T("mdiDocumentDelete_"), false);
  46348. }
  46349. bool MultiDocumentPanel::closeAllDocuments (const bool checkItsOkToCloseFirst)
  46350. {
  46351. while (components.size() > 0)
  46352. if (! closeDocument (components.getLast(), checkItsOkToCloseFirst))
  46353. return false;
  46354. return true;
  46355. }
  46356. MultiDocumentPanelWindow* MultiDocumentPanel::createNewDocumentWindow()
  46357. {
  46358. return new MultiDocumentPanelWindow (backgroundColour);
  46359. }
  46360. void MultiDocumentPanel::addWindow (Component* component)
  46361. {
  46362. MultiDocumentPanelWindow* const dw = createNewDocumentWindow();
  46363. dw->setResizable (true, false);
  46364. dw->setContentComponent (component, false, true);
  46365. dw->setName (component->getName());
  46366. dw->setBackgroundColour (component->getComponentPropertyColour (T("mdiDocumentBkg_"), false, backgroundColour));
  46367. int x = 4;
  46368. Component* const topComp = getChildComponent (getNumChildComponents() - 1);
  46369. if (topComp != 0 && topComp->getX() == x && topComp->getY() == x)
  46370. x += 16;
  46371. dw->setTopLeftPosition (x, x);
  46372. if (component->getComponentProperty (T("mdiDocumentPos_"), false, String::empty).isNotEmpty())
  46373. dw->restoreWindowStateFromString (component->getComponentProperty (T("mdiDocumentPos_"), false, String::empty));
  46374. addAndMakeVisible (dw);
  46375. dw->toFront (true);
  46376. }
  46377. bool MultiDocumentPanel::addDocument (Component* const component,
  46378. const Colour& docColour,
  46379. const bool deleteWhenRemoved)
  46380. {
  46381. // If you try passing a full DocumentWindow or ResizableWindow in here, you'll end up
  46382. // with a frame-within-a-frame! Just pass in the bare content component.
  46383. jassert (dynamic_cast <ResizableWindow*> (component) == 0);
  46384. if (component == 0 || (maximumNumDocuments > 0 && components.size() >= maximumNumDocuments))
  46385. return false;
  46386. components.add (component);
  46387. component->setComponentProperty (T("mdiDocumentDelete_"), deleteWhenRemoved);
  46388. component->setComponentProperty (T("mdiDocumentBkg_"), docColour);
  46389. component->addComponentListener (this);
  46390. if (mode == FloatingWindows)
  46391. {
  46392. if (isFullscreenWhenOneDocument())
  46393. {
  46394. if (components.size() == 1)
  46395. {
  46396. addAndMakeVisible (component);
  46397. }
  46398. else
  46399. {
  46400. if (components.size() == 2)
  46401. addWindow (components.getFirst());
  46402. addWindow (component);
  46403. }
  46404. }
  46405. else
  46406. {
  46407. addWindow (component);
  46408. }
  46409. }
  46410. else
  46411. {
  46412. if (tabComponent == 0 && components.size() > numDocsBeforeTabsUsed)
  46413. {
  46414. addAndMakeVisible (tabComponent = new MDITabbedComponentInternal());
  46415. Array <Component*> temp (components);
  46416. for (int i = 0; i < temp.size(); ++i)
  46417. tabComponent->addTab (temp[i]->getName(), docColour, temp[i], false);
  46418. resized();
  46419. }
  46420. else
  46421. {
  46422. if (tabComponent != 0)
  46423. tabComponent->addTab (component->getName(), docColour, component, false);
  46424. else
  46425. addAndMakeVisible (component);
  46426. }
  46427. setActiveDocument (component);
  46428. }
  46429. resized();
  46430. activeDocumentChanged();
  46431. return true;
  46432. }
  46433. bool MultiDocumentPanel::closeDocument (Component* component,
  46434. const bool checkItsOkToCloseFirst)
  46435. {
  46436. if (components.contains (component))
  46437. {
  46438. if (checkItsOkToCloseFirst && ! tryToCloseDocument (component))
  46439. return false;
  46440. component->removeComponentListener (this);
  46441. const bool shouldDelete = shouldDeleteComp (component);
  46442. component->removeComponentProperty (T("mdiDocumentDelete_"));
  46443. component->removeComponentProperty (T("mdiDocumentBkg_"));
  46444. if (mode == FloatingWindows)
  46445. {
  46446. for (int i = getNumChildComponents(); --i >= 0;)
  46447. {
  46448. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  46449. if (dw != 0 && dw->getContentComponent() == component)
  46450. {
  46451. dw->setContentComponent (0, false);
  46452. delete dw;
  46453. break;
  46454. }
  46455. }
  46456. if (shouldDelete)
  46457. delete component;
  46458. components.removeValue (component);
  46459. if (isFullscreenWhenOneDocument() && components.size() == 1)
  46460. {
  46461. for (int i = getNumChildComponents(); --i >= 0;)
  46462. {
  46463. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  46464. if (dw != 0)
  46465. {
  46466. dw->setContentComponent (0, false);
  46467. delete dw;
  46468. }
  46469. }
  46470. addAndMakeVisible (components.getFirst());
  46471. }
  46472. }
  46473. else
  46474. {
  46475. jassert (components.indexOf (component) >= 0);
  46476. if (tabComponent != 0)
  46477. {
  46478. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  46479. if (tabComponent->getTabContentComponent (i) == component)
  46480. tabComponent->removeTab (i);
  46481. }
  46482. else
  46483. {
  46484. removeChildComponent (component);
  46485. }
  46486. if (shouldDelete)
  46487. delete component;
  46488. if (tabComponent != 0 && tabComponent->getNumTabs() <= numDocsBeforeTabsUsed)
  46489. deleteAndZero (tabComponent);
  46490. components.removeValue (component);
  46491. if (components.size() > 0 && tabComponent == 0)
  46492. addAndMakeVisible (components.getFirst());
  46493. }
  46494. resized();
  46495. activeDocumentChanged();
  46496. }
  46497. else
  46498. {
  46499. jassertfalse
  46500. }
  46501. return true;
  46502. }
  46503. int MultiDocumentPanel::getNumDocuments() const throw()
  46504. {
  46505. return components.size();
  46506. }
  46507. Component* MultiDocumentPanel::getDocument (const int index) const throw()
  46508. {
  46509. return components [index];
  46510. }
  46511. Component* MultiDocumentPanel::getActiveDocument() const throw()
  46512. {
  46513. if (mode == FloatingWindows)
  46514. {
  46515. for (int i = getNumChildComponents(); --i >= 0;)
  46516. {
  46517. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  46518. if (dw != 0 && dw->isActiveWindow())
  46519. return dw->getContentComponent();
  46520. }
  46521. }
  46522. return components.getLast();
  46523. }
  46524. void MultiDocumentPanel::setActiveDocument (Component* component)
  46525. {
  46526. if (mode == FloatingWindows)
  46527. {
  46528. component = getContainerComp (component);
  46529. if (component != 0)
  46530. component->toFront (true);
  46531. }
  46532. else if (tabComponent != 0)
  46533. {
  46534. jassert (components.indexOf (component) >= 0);
  46535. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  46536. {
  46537. if (tabComponent->getTabContentComponent (i) == component)
  46538. {
  46539. tabComponent->setCurrentTabIndex (i);
  46540. break;
  46541. }
  46542. }
  46543. }
  46544. else
  46545. {
  46546. component->grabKeyboardFocus();
  46547. }
  46548. }
  46549. void MultiDocumentPanel::activeDocumentChanged()
  46550. {
  46551. }
  46552. void MultiDocumentPanel::setMaximumNumDocuments (const int newNumber)
  46553. {
  46554. maximumNumDocuments = newNumber;
  46555. }
  46556. void MultiDocumentPanel::useFullscreenWhenOneDocument (const bool shouldUseTabs)
  46557. {
  46558. numDocsBeforeTabsUsed = shouldUseTabs ? 1 : 0;
  46559. }
  46560. bool MultiDocumentPanel::isFullscreenWhenOneDocument() const throw()
  46561. {
  46562. return numDocsBeforeTabsUsed != 0;
  46563. }
  46564. void MultiDocumentPanel::setLayoutMode (const LayoutMode newLayoutMode)
  46565. {
  46566. if (mode != newLayoutMode)
  46567. {
  46568. mode = newLayoutMode;
  46569. if (mode == FloatingWindows)
  46570. {
  46571. deleteAndZero (tabComponent);
  46572. }
  46573. else
  46574. {
  46575. for (int i = getNumChildComponents(); --i >= 0;)
  46576. {
  46577. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  46578. if (dw != 0)
  46579. {
  46580. dw->getContentComponent()->setComponentProperty (T("mdiDocumentPos_"), dw->getWindowStateAsString());
  46581. dw->setContentComponent (0, false);
  46582. delete dw;
  46583. }
  46584. }
  46585. }
  46586. resized();
  46587. const Array <Component*> tempComps (components);
  46588. components.clear();
  46589. for (int i = 0; i < tempComps.size(); ++i)
  46590. {
  46591. Component* const c = tempComps.getUnchecked(i);
  46592. addDocument (c,
  46593. c->getComponentPropertyColour (T("mdiDocumentBkg_"), false, Colours::white),
  46594. shouldDeleteComp (c));
  46595. }
  46596. }
  46597. }
  46598. void MultiDocumentPanel::setBackgroundColour (const Colour& newBackgroundColour)
  46599. {
  46600. if (backgroundColour != newBackgroundColour)
  46601. {
  46602. backgroundColour = newBackgroundColour;
  46603. setOpaque (newBackgroundColour.isOpaque());
  46604. repaint();
  46605. }
  46606. }
  46607. void MultiDocumentPanel::paint (Graphics& g)
  46608. {
  46609. g.fillAll (backgroundColour);
  46610. }
  46611. void MultiDocumentPanel::resized()
  46612. {
  46613. if (mode == MaximisedWindowsWithTabs || components.size() == numDocsBeforeTabsUsed)
  46614. {
  46615. for (int i = getNumChildComponents(); --i >= 0;)
  46616. getChildComponent (i)->setBounds (0, 0, getWidth(), getHeight());
  46617. }
  46618. setWantsKeyboardFocus (components.size() == 0);
  46619. }
  46620. Component* MultiDocumentPanel::getContainerComp (Component* c) const
  46621. {
  46622. if (mode == FloatingWindows)
  46623. {
  46624. for (int i = 0; i < getNumChildComponents(); ++i)
  46625. {
  46626. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  46627. if (dw != 0 && dw->getContentComponent() == c)
  46628. {
  46629. c = dw;
  46630. break;
  46631. }
  46632. }
  46633. }
  46634. return c;
  46635. }
  46636. void MultiDocumentPanel::componentNameChanged (Component&)
  46637. {
  46638. if (mode == FloatingWindows)
  46639. {
  46640. for (int i = 0; i < getNumChildComponents(); ++i)
  46641. {
  46642. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  46643. if (dw != 0)
  46644. dw->setName (dw->getContentComponent()->getName());
  46645. }
  46646. }
  46647. else if (tabComponent != 0)
  46648. {
  46649. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  46650. tabComponent->setTabName (i, tabComponent->getTabContentComponent (i)->getName());
  46651. }
  46652. }
  46653. void MultiDocumentPanel::updateOrder()
  46654. {
  46655. const Array <Component*> oldList (components);
  46656. if (mode == FloatingWindows)
  46657. {
  46658. components.clear();
  46659. for (int i = 0; i < getNumChildComponents(); ++i)
  46660. {
  46661. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  46662. if (dw != 0)
  46663. components.add (dw->getContentComponent());
  46664. }
  46665. }
  46666. else
  46667. {
  46668. if (tabComponent != 0)
  46669. {
  46670. Component* const current = tabComponent->getCurrentContentComponent();
  46671. if (current != 0)
  46672. {
  46673. components.removeValue (current);
  46674. components.add (current);
  46675. }
  46676. }
  46677. }
  46678. if (components != oldList)
  46679. activeDocumentChanged();
  46680. }
  46681. END_JUCE_NAMESPACE
  46682. /********* End of inlined file: juce_MultiDocumentPanel.cpp *********/
  46683. /********* Start of inlined file: juce_ResizableBorderComponent.cpp *********/
  46684. BEGIN_JUCE_NAMESPACE
  46685. const int zoneL = 1;
  46686. const int zoneR = 2;
  46687. const int zoneT = 4;
  46688. const int zoneB = 8;
  46689. ResizableBorderComponent::ResizableBorderComponent (Component* const componentToResize,
  46690. ComponentBoundsConstrainer* const constrainer_)
  46691. : component (componentToResize),
  46692. constrainer (constrainer_),
  46693. borderSize (5),
  46694. mouseZone (0)
  46695. {
  46696. }
  46697. ResizableBorderComponent::~ResizableBorderComponent()
  46698. {
  46699. }
  46700. void ResizableBorderComponent::paint (Graphics& g)
  46701. {
  46702. getLookAndFeel().drawResizableFrame (g, getWidth(), getHeight(), borderSize);
  46703. }
  46704. void ResizableBorderComponent::mouseEnter (const MouseEvent& e)
  46705. {
  46706. updateMouseZone (e);
  46707. }
  46708. void ResizableBorderComponent::mouseMove (const MouseEvent& e)
  46709. {
  46710. updateMouseZone (e);
  46711. }
  46712. void ResizableBorderComponent::mouseDown (const MouseEvent& e)
  46713. {
  46714. if (component->isValidComponent())
  46715. {
  46716. updateMouseZone (e);
  46717. originalX = component->getX();
  46718. originalY = component->getY();
  46719. originalW = component->getWidth();
  46720. originalH = component->getHeight();
  46721. if (constrainer != 0)
  46722. constrainer->resizeStart();
  46723. }
  46724. else
  46725. {
  46726. jassertfalse
  46727. }
  46728. }
  46729. void ResizableBorderComponent::mouseDrag (const MouseEvent& e)
  46730. {
  46731. if (! component->isValidComponent())
  46732. {
  46733. jassertfalse
  46734. return;
  46735. }
  46736. int x = originalX;
  46737. int y = originalY;
  46738. int w = originalW;
  46739. int h = originalH;
  46740. const int dx = e.getDistanceFromDragStartX();
  46741. const int dy = e.getDistanceFromDragStartY();
  46742. if ((mouseZone & zoneL) != 0)
  46743. {
  46744. x += dx;
  46745. w -= dx;
  46746. }
  46747. if ((mouseZone & zoneT) != 0)
  46748. {
  46749. y += dy;
  46750. h -= dy;
  46751. }
  46752. if ((mouseZone & zoneR) != 0)
  46753. w += dx;
  46754. if ((mouseZone & zoneB) != 0)
  46755. h += dy;
  46756. if (constrainer != 0)
  46757. constrainer->setBoundsForComponent (component,
  46758. x, y, w, h,
  46759. (mouseZone & zoneT) != 0,
  46760. (mouseZone & zoneL) != 0,
  46761. (mouseZone & zoneB) != 0,
  46762. (mouseZone & zoneR) != 0);
  46763. else
  46764. component->setBounds (x, y, w, h);
  46765. }
  46766. void ResizableBorderComponent::mouseUp (const MouseEvent&)
  46767. {
  46768. if (constrainer != 0)
  46769. constrainer->resizeEnd();
  46770. }
  46771. bool ResizableBorderComponent::hitTest (int x, int y)
  46772. {
  46773. return x < borderSize.getLeft()
  46774. || x >= getWidth() - borderSize.getRight()
  46775. || y < borderSize.getTop()
  46776. || y >= getHeight() - borderSize.getBottom();
  46777. }
  46778. void ResizableBorderComponent::setBorderThickness (const BorderSize& newBorderSize) throw()
  46779. {
  46780. if (borderSize != newBorderSize)
  46781. {
  46782. borderSize = newBorderSize;
  46783. repaint();
  46784. }
  46785. }
  46786. const BorderSize ResizableBorderComponent::getBorderThickness() const throw()
  46787. {
  46788. return borderSize;
  46789. }
  46790. void ResizableBorderComponent::updateMouseZone (const MouseEvent& e) throw()
  46791. {
  46792. int newZone = 0;
  46793. if (ResizableBorderComponent::hitTest (e.x, e.y))
  46794. {
  46795. if (e.x < jmax (borderSize.getLeft(),
  46796. proportionOfWidth (0.1f),
  46797. jmin (10, proportionOfWidth (0.33f))))
  46798. newZone |= zoneL;
  46799. else if (e.x >= jmin (getWidth() - borderSize.getRight(),
  46800. proportionOfWidth (0.9f),
  46801. getWidth() - jmin (10, proportionOfWidth (0.33f))))
  46802. newZone |= zoneR;
  46803. if (e.y < jmax (borderSize.getTop(),
  46804. proportionOfHeight (0.1f),
  46805. jmin (10, proportionOfHeight (0.33f))))
  46806. newZone |= zoneT;
  46807. else if (e.y >= jmin (getHeight() - borderSize.getBottom(),
  46808. proportionOfHeight (0.9f),
  46809. getHeight() - jmin (10, proportionOfHeight (0.33f))))
  46810. newZone |= zoneB;
  46811. }
  46812. if (mouseZone != newZone)
  46813. {
  46814. mouseZone = newZone;
  46815. MouseCursor::StandardCursorType mc = MouseCursor::NormalCursor;
  46816. switch (newZone)
  46817. {
  46818. case (zoneL | zoneT):
  46819. mc = MouseCursor::TopLeftCornerResizeCursor;
  46820. break;
  46821. case zoneT:
  46822. mc = MouseCursor::TopEdgeResizeCursor;
  46823. break;
  46824. case (zoneR | zoneT):
  46825. mc = MouseCursor::TopRightCornerResizeCursor;
  46826. break;
  46827. case zoneL:
  46828. mc = MouseCursor::LeftEdgeResizeCursor;
  46829. break;
  46830. case zoneR:
  46831. mc = MouseCursor::RightEdgeResizeCursor;
  46832. break;
  46833. case (zoneL | zoneB):
  46834. mc = MouseCursor::BottomLeftCornerResizeCursor;
  46835. break;
  46836. case zoneB:
  46837. mc = MouseCursor::BottomEdgeResizeCursor;
  46838. break;
  46839. case (zoneR | zoneB):
  46840. mc = MouseCursor::BottomRightCornerResizeCursor;
  46841. break;
  46842. default:
  46843. break;
  46844. }
  46845. setMouseCursor (mc);
  46846. }
  46847. }
  46848. END_JUCE_NAMESPACE
  46849. /********* End of inlined file: juce_ResizableBorderComponent.cpp *********/
  46850. /********* Start of inlined file: juce_ResizableCornerComponent.cpp *********/
  46851. BEGIN_JUCE_NAMESPACE
  46852. ResizableCornerComponent::ResizableCornerComponent (Component* const componentToResize,
  46853. ComponentBoundsConstrainer* const constrainer_)
  46854. : component (componentToResize),
  46855. constrainer (constrainer_)
  46856. {
  46857. setRepaintsOnMouseActivity (true);
  46858. setMouseCursor (MouseCursor::BottomRightCornerResizeCursor);
  46859. }
  46860. ResizableCornerComponent::~ResizableCornerComponent()
  46861. {
  46862. }
  46863. void ResizableCornerComponent::paint (Graphics& g)
  46864. {
  46865. getLookAndFeel()
  46866. .drawCornerResizer (g, getWidth(), getHeight(),
  46867. isMouseOverOrDragging(),
  46868. isMouseButtonDown());
  46869. }
  46870. void ResizableCornerComponent::mouseDown (const MouseEvent&)
  46871. {
  46872. if (component->isValidComponent())
  46873. {
  46874. originalX = component->getX();
  46875. originalY = component->getY();
  46876. originalW = component->getWidth();
  46877. originalH = component->getHeight();
  46878. if (constrainer != 0)
  46879. constrainer->resizeStart();
  46880. }
  46881. else
  46882. {
  46883. jassertfalse
  46884. }
  46885. }
  46886. void ResizableCornerComponent::mouseDrag (const MouseEvent& e)
  46887. {
  46888. if (! component->isValidComponent())
  46889. {
  46890. jassertfalse
  46891. return;
  46892. }
  46893. int x = originalX;
  46894. int y = originalY;
  46895. int w = originalW + e.getDistanceFromDragStartX();
  46896. int h = originalH + e.getDistanceFromDragStartY();
  46897. if (constrainer != 0)
  46898. constrainer->setBoundsForComponent (component, x, y, w, h,
  46899. false, false, true, true);
  46900. else
  46901. component->setBounds (x, y, w, h);
  46902. }
  46903. void ResizableCornerComponent::mouseUp (const MouseEvent&)
  46904. {
  46905. if (constrainer != 0)
  46906. constrainer->resizeStart();
  46907. }
  46908. bool ResizableCornerComponent::hitTest (int x, int y)
  46909. {
  46910. if (getWidth() <= 0)
  46911. return false;
  46912. const int yAtX = getHeight() - (getHeight() * x / getWidth());
  46913. return y >= yAtX - getHeight() / 4;
  46914. }
  46915. END_JUCE_NAMESPACE
  46916. /********* End of inlined file: juce_ResizableCornerComponent.cpp *********/
  46917. /********* Start of inlined file: juce_ScrollBar.cpp *********/
  46918. BEGIN_JUCE_NAMESPACE
  46919. class ScrollbarButton : public Button
  46920. {
  46921. public:
  46922. int direction;
  46923. ScrollbarButton (const int direction_,
  46924. ScrollBar& owner_) throw()
  46925. : Button (String::empty),
  46926. direction (direction_),
  46927. owner (owner_)
  46928. {
  46929. setWantsKeyboardFocus (false);
  46930. }
  46931. ~ScrollbarButton()
  46932. {
  46933. }
  46934. void paintButton (Graphics& g,
  46935. bool isMouseOver,
  46936. bool isMouseDown)
  46937. {
  46938. getLookAndFeel()
  46939. .drawScrollbarButton (g, owner,
  46940. getWidth(), getHeight(),
  46941. direction,
  46942. owner.isVertical(),
  46943. isMouseOver, isMouseDown);
  46944. }
  46945. void clicked()
  46946. {
  46947. owner.moveScrollbarInSteps ((direction == 1 || direction == 2) ? 1 : -1);
  46948. }
  46949. juce_UseDebuggingNewOperator
  46950. private:
  46951. ScrollBar& owner;
  46952. ScrollbarButton (const ScrollbarButton&);
  46953. const ScrollbarButton& operator= (const ScrollbarButton&);
  46954. };
  46955. ScrollBar::ScrollBar (const bool vertical_,
  46956. const bool buttonsAreVisible)
  46957. : minimum (0.0),
  46958. maximum (1.0),
  46959. rangeStart (0.0),
  46960. rangeSize (0.1),
  46961. singleStepSize (0.1),
  46962. thumbAreaStart (0),
  46963. thumbAreaSize (0),
  46964. thumbStart (0),
  46965. thumbSize (0),
  46966. initialDelayInMillisecs (100),
  46967. repeatDelayInMillisecs (50),
  46968. minimumDelayInMillisecs (10),
  46969. vertical (vertical_),
  46970. isDraggingThumb (false),
  46971. alwaysVisible (false),
  46972. upButton (0),
  46973. downButton (0),
  46974. listeners (2)
  46975. {
  46976. setButtonVisibility (buttonsAreVisible);
  46977. setRepaintsOnMouseActivity (true);
  46978. setFocusContainer (true);
  46979. }
  46980. ScrollBar::~ScrollBar()
  46981. {
  46982. deleteAllChildren();
  46983. }
  46984. void ScrollBar::setRangeLimits (const double newMinimum,
  46985. const double newMaximum) throw()
  46986. {
  46987. minimum = newMinimum;
  46988. maximum = newMaximum;
  46989. jassert (maximum >= minimum); // these can't be the wrong way round!
  46990. setCurrentRangeStart (rangeStart);
  46991. updateThumbPosition();
  46992. }
  46993. void ScrollBar::setCurrentRange (double newStart,
  46994. double newSize) throw()
  46995. {
  46996. newSize = jlimit (0.0, maximum - minimum, newSize);
  46997. newStart = jlimit (minimum, maximum - newSize, newStart);
  46998. if (rangeStart != newStart
  46999. || rangeSize != newSize)
  47000. {
  47001. rangeStart = newStart;
  47002. rangeSize = newSize;
  47003. updateThumbPosition();
  47004. triggerAsyncUpdate();
  47005. }
  47006. }
  47007. void ScrollBar::setCurrentRangeStart (double newStart) throw()
  47008. {
  47009. setCurrentRange (newStart, rangeSize);
  47010. }
  47011. void ScrollBar::setSingleStepSize (const double newSingleStepSize) throw()
  47012. {
  47013. singleStepSize = newSingleStepSize;
  47014. }
  47015. void ScrollBar::moveScrollbarInSteps (const int howManySteps) throw()
  47016. {
  47017. setCurrentRangeStart (rangeStart + howManySteps * singleStepSize);
  47018. }
  47019. void ScrollBar::moveScrollbarInPages (const int howManyPages) throw()
  47020. {
  47021. setCurrentRangeStart (rangeStart + howManyPages * rangeSize);
  47022. }
  47023. void ScrollBar::scrollToTop() throw()
  47024. {
  47025. setCurrentRangeStart (minimum);
  47026. }
  47027. void ScrollBar::scrollToBottom() throw()
  47028. {
  47029. setCurrentRangeStart (maximum - rangeSize);
  47030. }
  47031. void ScrollBar::setButtonRepeatSpeed (const int initialDelayInMillisecs_,
  47032. const int repeatDelayInMillisecs_,
  47033. const int minimumDelayInMillisecs_) throw()
  47034. {
  47035. initialDelayInMillisecs = initialDelayInMillisecs_;
  47036. repeatDelayInMillisecs = repeatDelayInMillisecs_;
  47037. minimumDelayInMillisecs = minimumDelayInMillisecs_;
  47038. if (upButton != 0)
  47039. {
  47040. upButton->setRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  47041. downButton->setRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  47042. }
  47043. }
  47044. void ScrollBar::addListener (ScrollBarListener* const listener) throw()
  47045. {
  47046. jassert (listener != 0);
  47047. if (listener != 0)
  47048. listeners.add (listener);
  47049. }
  47050. void ScrollBar::removeListener (ScrollBarListener* const listener) throw()
  47051. {
  47052. listeners.removeValue (listener);
  47053. }
  47054. void ScrollBar::handleAsyncUpdate()
  47055. {
  47056. const double value = getCurrentRangeStart();
  47057. for (int i = listeners.size(); --i >= 0;)
  47058. {
  47059. ((ScrollBarListener*) listeners.getUnchecked (i))->scrollBarMoved (this, value);
  47060. i = jmin (i, listeners.size());
  47061. }
  47062. }
  47063. void ScrollBar::updateThumbPosition() throw()
  47064. {
  47065. int newThumbSize = roundDoubleToInt ((maximum > minimum) ? (rangeSize * thumbAreaSize) / (maximum - minimum)
  47066. : thumbAreaSize);
  47067. if (newThumbSize < getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  47068. newThumbSize = jmin (getLookAndFeel().getMinimumScrollbarThumbSize (*this), thumbAreaSize - 1);
  47069. if (newThumbSize > thumbAreaSize)
  47070. newThumbSize = thumbAreaSize;
  47071. int newThumbStart = thumbAreaStart;
  47072. if (maximum - minimum > rangeSize)
  47073. newThumbStart += roundDoubleToInt (((rangeStart - minimum) * (thumbAreaSize - newThumbSize))
  47074. / ((maximum - minimum) - rangeSize));
  47075. setVisible (alwaysVisible || (maximum - minimum > rangeSize && rangeSize > 0.0));
  47076. if (thumbStart != newThumbStart || thumbSize != newThumbSize)
  47077. {
  47078. const int repaintStart = jmin (thumbStart, newThumbStart) - 4;
  47079. const int repaintSize = jmax (thumbStart + thumbSize, newThumbStart + newThumbSize) + 8 - repaintStart;
  47080. if (vertical)
  47081. repaint (0, repaintStart, getWidth(), repaintSize);
  47082. else
  47083. repaint (repaintStart, 0, repaintSize, getHeight());
  47084. thumbStart = newThumbStart;
  47085. thumbSize = newThumbSize;
  47086. }
  47087. }
  47088. void ScrollBar::setOrientation (const bool shouldBeVertical) throw()
  47089. {
  47090. if (vertical != shouldBeVertical)
  47091. {
  47092. vertical = shouldBeVertical;
  47093. if (upButton != 0)
  47094. {
  47095. ((ScrollbarButton*) upButton)->direction = (vertical) ? 0 : 3;
  47096. ((ScrollbarButton*) downButton)->direction = (vertical) ? 2 : 1;
  47097. }
  47098. updateThumbPosition();
  47099. }
  47100. }
  47101. void ScrollBar::setButtonVisibility (const bool buttonsAreVisible)
  47102. {
  47103. deleteAndZero (upButton);
  47104. deleteAndZero (downButton);
  47105. if (buttonsAreVisible)
  47106. {
  47107. addAndMakeVisible (upButton = new ScrollbarButton ((vertical) ? 0 : 3, *this));
  47108. addAndMakeVisible (downButton = new ScrollbarButton ((vertical) ? 2 : 1, *this));
  47109. setButtonRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  47110. }
  47111. updateThumbPosition();
  47112. }
  47113. void ScrollBar::setAutoHide (const bool shouldHideWhenFullRange)
  47114. {
  47115. alwaysVisible = ! shouldHideWhenFullRange;
  47116. updateThumbPosition();
  47117. }
  47118. void ScrollBar::paint (Graphics& g)
  47119. {
  47120. if (thumbAreaSize > 0)
  47121. {
  47122. LookAndFeel& lf = getLookAndFeel();
  47123. const int thumb = (thumbAreaSize > lf.getMinimumScrollbarThumbSize (*this))
  47124. ? thumbSize : 0;
  47125. if (vertical)
  47126. {
  47127. lf.drawScrollbar (g, *this,
  47128. 0, thumbAreaStart,
  47129. getWidth(), thumbAreaSize,
  47130. vertical,
  47131. thumbStart, thumb,
  47132. isMouseOver(), isMouseButtonDown());
  47133. }
  47134. else
  47135. {
  47136. lf.drawScrollbar (g, *this,
  47137. thumbAreaStart, 0,
  47138. thumbAreaSize, getHeight(),
  47139. vertical,
  47140. thumbStart, thumb,
  47141. isMouseOver(), isMouseButtonDown());
  47142. }
  47143. }
  47144. }
  47145. void ScrollBar::lookAndFeelChanged()
  47146. {
  47147. setComponentEffect (getLookAndFeel().getScrollbarEffect());
  47148. }
  47149. void ScrollBar::resized()
  47150. {
  47151. const int length = ((vertical) ? getHeight() : getWidth());
  47152. const int buttonSize = (upButton != 0) ? jmin (getLookAndFeel().getScrollbarButtonSize (*this), (length >> 1))
  47153. : 0;
  47154. if (length < 32 + getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  47155. {
  47156. thumbAreaStart = length >> 1;
  47157. thumbAreaSize = 0;
  47158. }
  47159. else
  47160. {
  47161. thumbAreaStart = buttonSize;
  47162. thumbAreaSize = length - (buttonSize << 1);
  47163. }
  47164. if (upButton != 0)
  47165. {
  47166. if (vertical)
  47167. {
  47168. upButton->setBounds (0, 0, getWidth(), buttonSize);
  47169. downButton->setBounds (0, thumbAreaStart + thumbAreaSize, getWidth(), buttonSize);
  47170. }
  47171. else
  47172. {
  47173. upButton->setBounds (0, 0, buttonSize, getHeight());
  47174. downButton->setBounds (thumbAreaStart + thumbAreaSize, 0, buttonSize, getHeight());
  47175. }
  47176. }
  47177. updateThumbPosition();
  47178. }
  47179. void ScrollBar::mouseDown (const MouseEvent& e)
  47180. {
  47181. isDraggingThumb = false;
  47182. lastMousePos = vertical ? e.y : e.x;
  47183. dragStartMousePos = lastMousePos;
  47184. dragStartRange = rangeStart;
  47185. if (dragStartMousePos < thumbStart)
  47186. {
  47187. moveScrollbarInPages (-1);
  47188. startTimer (400);
  47189. }
  47190. else if (dragStartMousePos >= thumbStart + thumbSize)
  47191. {
  47192. moveScrollbarInPages (1);
  47193. startTimer (400);
  47194. }
  47195. else
  47196. {
  47197. isDraggingThumb = (thumbAreaSize > getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  47198. && (thumbAreaSize > thumbSize);
  47199. }
  47200. }
  47201. void ScrollBar::mouseDrag (const MouseEvent& e)
  47202. {
  47203. if (isDraggingThumb)
  47204. {
  47205. const int deltaPixels = ((vertical) ? e.y : e.x) - dragStartMousePos;
  47206. setCurrentRangeStart (dragStartRange
  47207. + deltaPixels * ((maximum - minimum) - rangeSize)
  47208. / (thumbAreaSize - thumbSize));
  47209. }
  47210. else
  47211. {
  47212. lastMousePos = (vertical) ? e.y : e.x;
  47213. }
  47214. }
  47215. void ScrollBar::mouseUp (const MouseEvent&)
  47216. {
  47217. isDraggingThumb = false;
  47218. stopTimer();
  47219. repaint();
  47220. }
  47221. void ScrollBar::mouseWheelMove (const MouseEvent&,
  47222. float wheelIncrementX,
  47223. float wheelIncrementY)
  47224. {
  47225. float increment = vertical ? wheelIncrementY : wheelIncrementX;
  47226. if (increment < 0)
  47227. increment = jmin (increment * 10.0f, -1.0f);
  47228. else if (increment > 0)
  47229. increment = jmax (increment * 10.0f, 1.0f);
  47230. setCurrentRangeStart (rangeStart - singleStepSize * increment);
  47231. }
  47232. void ScrollBar::timerCallback()
  47233. {
  47234. if (isMouseButtonDown())
  47235. {
  47236. startTimer (40);
  47237. if (lastMousePos < thumbStart)
  47238. setCurrentRangeStart (rangeStart - rangeSize);
  47239. else if (lastMousePos > thumbStart + thumbSize)
  47240. setCurrentRangeStart (rangeStart + rangeSize);
  47241. }
  47242. else
  47243. {
  47244. stopTimer();
  47245. }
  47246. }
  47247. bool ScrollBar::keyPressed (const KeyPress& key)
  47248. {
  47249. if (! isVisible())
  47250. return false;
  47251. if (key.isKeyCode (KeyPress::upKey) || key.isKeyCode (KeyPress::leftKey))
  47252. moveScrollbarInSteps (-1);
  47253. else if (key.isKeyCode (KeyPress::downKey) || key.isKeyCode (KeyPress::rightKey))
  47254. moveScrollbarInSteps (1);
  47255. else if (key.isKeyCode (KeyPress::pageUpKey))
  47256. moveScrollbarInPages (-1);
  47257. else if (key.isKeyCode (KeyPress::pageDownKey))
  47258. moveScrollbarInPages (1);
  47259. else if (key.isKeyCode (KeyPress::homeKey))
  47260. scrollToTop();
  47261. else if (key.isKeyCode (KeyPress::endKey))
  47262. scrollToBottom();
  47263. else
  47264. return false;
  47265. return true;
  47266. }
  47267. END_JUCE_NAMESPACE
  47268. /********* End of inlined file: juce_ScrollBar.cpp *********/
  47269. /********* Start of inlined file: juce_StretchableLayoutManager.cpp *********/
  47270. BEGIN_JUCE_NAMESPACE
  47271. StretchableLayoutManager::StretchableLayoutManager()
  47272. : totalSize (0)
  47273. {
  47274. }
  47275. StretchableLayoutManager::~StretchableLayoutManager()
  47276. {
  47277. }
  47278. void StretchableLayoutManager::clearAllItems()
  47279. {
  47280. items.clear();
  47281. totalSize = 0;
  47282. }
  47283. void StretchableLayoutManager::setItemLayout (const int itemIndex,
  47284. const double minimumSize,
  47285. const double maximumSize,
  47286. const double preferredSize)
  47287. {
  47288. ItemLayoutProperties* layout = getInfoFor (itemIndex);
  47289. if (layout == 0)
  47290. {
  47291. layout = new ItemLayoutProperties();
  47292. layout->itemIndex = itemIndex;
  47293. int i;
  47294. for (i = 0; i < items.size(); ++i)
  47295. if (items.getUnchecked (i)->itemIndex > itemIndex)
  47296. break;
  47297. items.insert (i, layout);
  47298. }
  47299. layout->minSize = minimumSize;
  47300. layout->maxSize = maximumSize;
  47301. layout->preferredSize = preferredSize;
  47302. layout->currentSize = 0;
  47303. }
  47304. bool StretchableLayoutManager::getItemLayout (const int itemIndex,
  47305. double& minimumSize,
  47306. double& maximumSize,
  47307. double& preferredSize) const
  47308. {
  47309. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  47310. if (layout != 0)
  47311. {
  47312. minimumSize = layout->minSize;
  47313. maximumSize = layout->maxSize;
  47314. preferredSize = layout->preferredSize;
  47315. return true;
  47316. }
  47317. return false;
  47318. }
  47319. void StretchableLayoutManager::setTotalSize (const int newTotalSize)
  47320. {
  47321. totalSize = newTotalSize;
  47322. fitComponentsIntoSpace (0, items.size(), totalSize, 0);
  47323. }
  47324. int StretchableLayoutManager::getItemCurrentPosition (const int itemIndex) const
  47325. {
  47326. int pos = 0;
  47327. for (int i = 0; i < itemIndex; ++i)
  47328. {
  47329. const ItemLayoutProperties* const layout = getInfoFor (i);
  47330. if (layout != 0)
  47331. pos += layout->currentSize;
  47332. }
  47333. return pos;
  47334. }
  47335. int StretchableLayoutManager::getItemCurrentAbsoluteSize (const int itemIndex) const
  47336. {
  47337. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  47338. if (layout != 0)
  47339. return layout->currentSize;
  47340. return 0;
  47341. }
  47342. double StretchableLayoutManager::getItemCurrentRelativeSize (const int itemIndex) const
  47343. {
  47344. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  47345. if (layout != 0)
  47346. return -layout->currentSize / (double) totalSize;
  47347. return 0;
  47348. }
  47349. void StretchableLayoutManager::setItemPosition (const int itemIndex,
  47350. int newPosition)
  47351. {
  47352. for (int i = items.size(); --i >= 0;)
  47353. {
  47354. const ItemLayoutProperties* const layout = items.getUnchecked(i);
  47355. if (layout->itemIndex == itemIndex)
  47356. {
  47357. int realTotalSize = jmax (totalSize, getMinimumSizeOfItems (0, items.size()));
  47358. const int minSizeAfterThisComp = getMinimumSizeOfItems (i, items.size());
  47359. const int maxSizeAfterThisComp = getMaximumSizeOfItems (i + 1, items.size());
  47360. newPosition = jmax (newPosition, totalSize - maxSizeAfterThisComp - layout->currentSize);
  47361. newPosition = jmin (newPosition, realTotalSize - minSizeAfterThisComp);
  47362. int endPos = fitComponentsIntoSpace (0, i, newPosition, 0);
  47363. endPos += layout->currentSize;
  47364. fitComponentsIntoSpace (i + 1, items.size(), totalSize - endPos, endPos);
  47365. updatePrefSizesToMatchCurrentPositions();
  47366. break;
  47367. }
  47368. }
  47369. }
  47370. void StretchableLayoutManager::layOutComponents (Component** const components,
  47371. int numComponents,
  47372. int x, int y, int w, int h,
  47373. const bool vertically,
  47374. const bool resizeOtherDimension)
  47375. {
  47376. setTotalSize (vertically ? h : w);
  47377. int pos = vertically ? y : x;
  47378. for (int i = 0; i < numComponents; ++i)
  47379. {
  47380. const ItemLayoutProperties* const layout = getInfoFor (i);
  47381. if (layout != 0)
  47382. {
  47383. Component* const c = components[i];
  47384. if (c != 0)
  47385. {
  47386. if (i == numComponents - 1)
  47387. {
  47388. // if it's the last item, crop it to exactly fit the available space..
  47389. if (resizeOtherDimension)
  47390. {
  47391. if (vertically)
  47392. c->setBounds (x, pos, w, jmax (layout->currentSize, h - pos));
  47393. else
  47394. c->setBounds (pos, y, jmax (layout->currentSize, w - pos), h);
  47395. }
  47396. else
  47397. {
  47398. if (vertically)
  47399. c->setBounds (c->getX(), pos, c->getWidth(), jmax (layout->currentSize, h - pos));
  47400. else
  47401. c->setBounds (pos, c->getY(), jmax (layout->currentSize, w - pos), c->getHeight());
  47402. }
  47403. }
  47404. else
  47405. {
  47406. if (resizeOtherDimension)
  47407. {
  47408. if (vertically)
  47409. c->setBounds (x, pos, w, layout->currentSize);
  47410. else
  47411. c->setBounds (pos, y, layout->currentSize, h);
  47412. }
  47413. else
  47414. {
  47415. if (vertically)
  47416. c->setBounds (c->getX(), pos, c->getWidth(), layout->currentSize);
  47417. else
  47418. c->setBounds (pos, c->getY(), layout->currentSize, c->getHeight());
  47419. }
  47420. }
  47421. }
  47422. pos += layout->currentSize;
  47423. }
  47424. }
  47425. }
  47426. StretchableLayoutManager::ItemLayoutProperties* StretchableLayoutManager::getInfoFor (const int itemIndex) const
  47427. {
  47428. for (int i = items.size(); --i >= 0;)
  47429. if (items.getUnchecked(i)->itemIndex == itemIndex)
  47430. return items.getUnchecked(i);
  47431. return 0;
  47432. }
  47433. int StretchableLayoutManager::fitComponentsIntoSpace (const int startIndex,
  47434. const int endIndex,
  47435. const int availableSpace,
  47436. int startPos)
  47437. {
  47438. // calculate the total sizes
  47439. int i;
  47440. double totalIdealSize = 0.0;
  47441. int totalMinimums = 0;
  47442. for (i = startIndex; i < endIndex; ++i)
  47443. {
  47444. ItemLayoutProperties* const layout = items.getUnchecked (i);
  47445. layout->currentSize = sizeToRealSize (layout->minSize, totalSize);
  47446. totalMinimums += layout->currentSize;
  47447. totalIdealSize += sizeToRealSize (layout->preferredSize, availableSpace);
  47448. }
  47449. if (totalIdealSize <= 0)
  47450. totalIdealSize = 1.0;
  47451. // now calc the best sizes..
  47452. int extraSpace = availableSpace - totalMinimums;
  47453. while (extraSpace > 0)
  47454. {
  47455. int numWantingMoreSpace = 0;
  47456. int numHavingTakenExtraSpace = 0;
  47457. // first figure out how many comps want a slice of the extra space..
  47458. for (i = startIndex; i < endIndex; ++i)
  47459. {
  47460. ItemLayoutProperties* const layout = items.getUnchecked (i);
  47461. double sizeWanted = sizeToRealSize (layout->preferredSize, availableSpace);
  47462. const int bestSize = jlimit (layout->currentSize,
  47463. jmax (layout->currentSize,
  47464. sizeToRealSize (layout->maxSize, totalSize)),
  47465. roundDoubleToInt (sizeWanted * availableSpace / totalIdealSize));
  47466. if (bestSize > layout->currentSize)
  47467. ++numWantingMoreSpace;
  47468. }
  47469. // ..share out the extra space..
  47470. for (i = startIndex; i < endIndex; ++i)
  47471. {
  47472. ItemLayoutProperties* const layout = items.getUnchecked (i);
  47473. double sizeWanted = sizeToRealSize (layout->preferredSize, availableSpace);
  47474. int bestSize = jlimit (layout->currentSize,
  47475. jmax (layout->currentSize, sizeToRealSize (layout->maxSize, totalSize)),
  47476. roundDoubleToInt (sizeWanted * availableSpace / totalIdealSize));
  47477. const int extraWanted = bestSize - layout->currentSize;
  47478. if (extraWanted > 0)
  47479. {
  47480. const int extraAllowed = jmin (extraWanted,
  47481. extraSpace / jmax (1, numWantingMoreSpace));
  47482. if (extraAllowed > 0)
  47483. {
  47484. ++numHavingTakenExtraSpace;
  47485. --numWantingMoreSpace;
  47486. layout->currentSize += extraAllowed;
  47487. extraSpace -= extraAllowed;
  47488. }
  47489. }
  47490. }
  47491. if (numHavingTakenExtraSpace <= 0)
  47492. break;
  47493. }
  47494. // ..and calculate the end position
  47495. for (i = startIndex; i < endIndex; ++i)
  47496. {
  47497. ItemLayoutProperties* const layout = items.getUnchecked(i);
  47498. startPos += layout->currentSize;
  47499. }
  47500. return startPos;
  47501. }
  47502. int StretchableLayoutManager::getMinimumSizeOfItems (const int startIndex,
  47503. const int endIndex) const
  47504. {
  47505. int totalMinimums = 0;
  47506. for (int i = startIndex; i < endIndex; ++i)
  47507. totalMinimums += sizeToRealSize (items.getUnchecked (i)->minSize, totalSize);
  47508. return totalMinimums;
  47509. }
  47510. int StretchableLayoutManager::getMaximumSizeOfItems (const int startIndex, const int endIndex) const
  47511. {
  47512. int totalMaximums = 0;
  47513. for (int i = startIndex; i < endIndex; ++i)
  47514. totalMaximums += sizeToRealSize (items.getUnchecked (i)->maxSize, totalSize);
  47515. return totalMaximums;
  47516. }
  47517. void StretchableLayoutManager::updatePrefSizesToMatchCurrentPositions()
  47518. {
  47519. for (int i = 0; i < items.size(); ++i)
  47520. {
  47521. ItemLayoutProperties* const layout = items.getUnchecked (i);
  47522. layout->preferredSize
  47523. = (layout->preferredSize < 0) ? getItemCurrentRelativeSize (i)
  47524. : getItemCurrentAbsoluteSize (i);
  47525. }
  47526. }
  47527. int StretchableLayoutManager::sizeToRealSize (double size, int totalSpace)
  47528. {
  47529. if (size < 0)
  47530. size *= -totalSpace;
  47531. return roundDoubleToInt (size);
  47532. }
  47533. END_JUCE_NAMESPACE
  47534. /********* End of inlined file: juce_StretchableLayoutManager.cpp *********/
  47535. /********* Start of inlined file: juce_StretchableLayoutResizerBar.cpp *********/
  47536. BEGIN_JUCE_NAMESPACE
  47537. StretchableLayoutResizerBar::StretchableLayoutResizerBar (StretchableLayoutManager* layout_,
  47538. const int itemIndex_,
  47539. const bool isVertical_)
  47540. : layout (layout_),
  47541. itemIndex (itemIndex_),
  47542. isVertical (isVertical_)
  47543. {
  47544. setRepaintsOnMouseActivity (true);
  47545. setMouseCursor (MouseCursor (isVertical_ ? MouseCursor::LeftRightResizeCursor
  47546. : MouseCursor::UpDownResizeCursor));
  47547. }
  47548. StretchableLayoutResizerBar::~StretchableLayoutResizerBar()
  47549. {
  47550. }
  47551. void StretchableLayoutResizerBar::paint (Graphics& g)
  47552. {
  47553. getLookAndFeel().drawStretchableLayoutResizerBar (g,
  47554. getWidth(), getHeight(),
  47555. isVertical,
  47556. isMouseOver(),
  47557. isMouseButtonDown());
  47558. }
  47559. void StretchableLayoutResizerBar::mouseDown (const MouseEvent&)
  47560. {
  47561. mouseDownPos = layout->getItemCurrentPosition (itemIndex);
  47562. }
  47563. void StretchableLayoutResizerBar::mouseDrag (const MouseEvent& e)
  47564. {
  47565. const int desiredPos = mouseDownPos + (isVertical ? e.getDistanceFromDragStartX()
  47566. : e.getDistanceFromDragStartY());
  47567. layout->setItemPosition (itemIndex, desiredPos);
  47568. hasBeenMoved();
  47569. }
  47570. void StretchableLayoutResizerBar::hasBeenMoved()
  47571. {
  47572. if (getParentComponent() != 0)
  47573. getParentComponent()->resized();
  47574. }
  47575. END_JUCE_NAMESPACE
  47576. /********* End of inlined file: juce_StretchableLayoutResizerBar.cpp *********/
  47577. /********* Start of inlined file: juce_StretchableObjectResizer.cpp *********/
  47578. BEGIN_JUCE_NAMESPACE
  47579. StretchableObjectResizer::StretchableObjectResizer()
  47580. {
  47581. }
  47582. StretchableObjectResizer::~StretchableObjectResizer()
  47583. {
  47584. }
  47585. void StretchableObjectResizer::addItem (const double size,
  47586. const double minSize, const double maxSize,
  47587. const int order)
  47588. {
  47589. jassert (order >= 0 && order < INT_MAX); // the order must be >= 0 and less than INT_MAX
  47590. Item* const item = new Item();
  47591. item->size = size;
  47592. item->minSize = minSize;
  47593. item->maxSize = maxSize;
  47594. item->order = order;
  47595. items.add (item);
  47596. }
  47597. double StretchableObjectResizer::getItemSize (const int index) const throw()
  47598. {
  47599. const Item* const it = items [index];
  47600. return it != 0 ? it->size : 0;
  47601. }
  47602. void StretchableObjectResizer::resizeToFit (const double targetSize)
  47603. {
  47604. int order = 0;
  47605. for (;;)
  47606. {
  47607. double currentSize = 0;
  47608. double minSize = 0;
  47609. double maxSize = 0;
  47610. int nextHighestOrder = INT_MAX;
  47611. for (int i = 0; i < items.size(); ++i)
  47612. {
  47613. const Item* const it = items.getUnchecked(i);
  47614. currentSize += it->size;
  47615. if (it->order <= order)
  47616. {
  47617. minSize += it->minSize;
  47618. maxSize += it->maxSize;
  47619. }
  47620. else
  47621. {
  47622. minSize += it->size;
  47623. maxSize += it->size;
  47624. nextHighestOrder = jmin (nextHighestOrder, it->order);
  47625. }
  47626. }
  47627. const double thisIterationTarget = jlimit (minSize, maxSize, targetSize);
  47628. if (thisIterationTarget >= currentSize)
  47629. {
  47630. const double availableExtraSpace = maxSize - currentSize;
  47631. const double targetAmountOfExtraSpace = thisIterationTarget - currentSize;
  47632. const double scale = targetAmountOfExtraSpace / availableExtraSpace;
  47633. for (int i = 0; i < items.size(); ++i)
  47634. {
  47635. Item* const it = items.getUnchecked(i);
  47636. if (it->order <= order)
  47637. it->size = jmin (it->maxSize, it->size + (it->maxSize - it->size) * scale);
  47638. }
  47639. }
  47640. else
  47641. {
  47642. const double amountOfSlack = currentSize - minSize;
  47643. const double targetAmountOfSlack = thisIterationTarget - minSize;
  47644. const double scale = targetAmountOfSlack / amountOfSlack;
  47645. for (int i = 0; i < items.size(); ++i)
  47646. {
  47647. Item* const it = items.getUnchecked(i);
  47648. if (it->order <= order)
  47649. it->size = jmax (it->minSize, it->minSize + (it->size - it->minSize) * scale);
  47650. }
  47651. }
  47652. if (nextHighestOrder < INT_MAX)
  47653. order = nextHighestOrder;
  47654. else
  47655. break;
  47656. }
  47657. }
  47658. END_JUCE_NAMESPACE
  47659. /********* End of inlined file: juce_StretchableObjectResizer.cpp *********/
  47660. /********* Start of inlined file: juce_TabbedButtonBar.cpp *********/
  47661. BEGIN_JUCE_NAMESPACE
  47662. TabBarButton::TabBarButton (const String& name,
  47663. TabbedButtonBar* const owner_,
  47664. const int index)
  47665. : Button (name),
  47666. owner (owner_),
  47667. tabIndex (index),
  47668. overlapPixels (0)
  47669. {
  47670. shadow.setShadowProperties (2.2f, 0.7f, 0, 0);
  47671. setComponentEffect (&shadow);
  47672. setWantsKeyboardFocus (false);
  47673. }
  47674. TabBarButton::~TabBarButton()
  47675. {
  47676. }
  47677. void TabBarButton::paintButton (Graphics& g,
  47678. bool isMouseOverButton,
  47679. bool isButtonDown)
  47680. {
  47681. int x, y, w, h;
  47682. getActiveArea (x, y, w, h);
  47683. g.setOrigin (x, y);
  47684. getLookAndFeel()
  47685. .drawTabButton (g, w, h,
  47686. owner->getTabBackgroundColour (tabIndex),
  47687. tabIndex, getButtonText(), *this,
  47688. owner->getOrientation(),
  47689. isMouseOverButton, isButtonDown,
  47690. getToggleState());
  47691. }
  47692. void TabBarButton::clicked (const ModifierKeys& mods)
  47693. {
  47694. if (mods.isPopupMenu())
  47695. owner->popupMenuClickOnTab (tabIndex, getButtonText());
  47696. else
  47697. owner->setCurrentTabIndex (tabIndex);
  47698. }
  47699. bool TabBarButton::hitTest (int mx, int my)
  47700. {
  47701. int x, y, w, h;
  47702. getActiveArea (x, y, w, h);
  47703. if (owner->getOrientation() == TabbedButtonBar::TabsAtLeft
  47704. || owner->getOrientation() == TabbedButtonBar::TabsAtRight)
  47705. {
  47706. if (((unsigned int) mx) < (unsigned int) getWidth()
  47707. && my >= y + overlapPixels
  47708. && my < y + h - overlapPixels)
  47709. return true;
  47710. }
  47711. else
  47712. {
  47713. if (mx >= x + overlapPixels && mx < x + w - overlapPixels
  47714. && ((unsigned int) my) < (unsigned int) getHeight())
  47715. return true;
  47716. }
  47717. Path p;
  47718. getLookAndFeel()
  47719. .createTabButtonShape (p, w, h, tabIndex, getButtonText(), *this,
  47720. owner->getOrientation(),
  47721. false, false, getToggleState());
  47722. return p.contains ((float) (mx - x),
  47723. (float) (my - y));
  47724. }
  47725. int TabBarButton::getBestTabLength (const int depth)
  47726. {
  47727. return jlimit (depth * 2,
  47728. depth * 7,
  47729. getLookAndFeel().getTabButtonBestWidth (tabIndex, getButtonText(), depth, *this));
  47730. }
  47731. void TabBarButton::getActiveArea (int& x, int& y, int& w, int& h)
  47732. {
  47733. x = 0;
  47734. y = 0;
  47735. int r = getWidth();
  47736. int b = getHeight();
  47737. const int spaceAroundImage = getLookAndFeel().getTabButtonSpaceAroundImage();
  47738. if (owner->getOrientation() != TabbedButtonBar::TabsAtLeft)
  47739. r -= spaceAroundImage;
  47740. if (owner->getOrientation() != TabbedButtonBar::TabsAtRight)
  47741. x += spaceAroundImage;
  47742. if (owner->getOrientation() != TabbedButtonBar::TabsAtBottom)
  47743. y += spaceAroundImage;
  47744. if (owner->getOrientation() != TabbedButtonBar::TabsAtTop)
  47745. b -= spaceAroundImage;
  47746. w = r - x;
  47747. h = b - y;
  47748. }
  47749. class TabAreaBehindFrontButtonComponent : public Component
  47750. {
  47751. public:
  47752. TabAreaBehindFrontButtonComponent (TabbedButtonBar* const owner_)
  47753. : owner (owner_)
  47754. {
  47755. setInterceptsMouseClicks (false, false);
  47756. }
  47757. ~TabAreaBehindFrontButtonComponent()
  47758. {
  47759. }
  47760. void paint (Graphics& g)
  47761. {
  47762. getLookAndFeel()
  47763. .drawTabAreaBehindFrontButton (g, getWidth(), getHeight(),
  47764. *owner, owner->getOrientation());
  47765. }
  47766. void enablementChanged()
  47767. {
  47768. repaint();
  47769. }
  47770. private:
  47771. TabbedButtonBar* const owner;
  47772. TabAreaBehindFrontButtonComponent (const TabAreaBehindFrontButtonComponent&);
  47773. const TabAreaBehindFrontButtonComponent& operator= (const TabAreaBehindFrontButtonComponent&);
  47774. };
  47775. TabbedButtonBar::TabbedButtonBar (const Orientation orientation_)
  47776. : orientation (orientation_),
  47777. currentTabIndex (-1),
  47778. extraTabsButton (0)
  47779. {
  47780. setInterceptsMouseClicks (false, true);
  47781. addAndMakeVisible (behindFrontTab = new TabAreaBehindFrontButtonComponent (this));
  47782. setFocusContainer (true);
  47783. }
  47784. TabbedButtonBar::~TabbedButtonBar()
  47785. {
  47786. deleteAllChildren();
  47787. }
  47788. void TabbedButtonBar::setOrientation (const Orientation newOrientation)
  47789. {
  47790. orientation = newOrientation;
  47791. for (int i = getNumChildComponents(); --i >= 0;)
  47792. getChildComponent (i)->resized();
  47793. resized();
  47794. }
  47795. TabBarButton* TabbedButtonBar::createTabButton (const String& name, const int index)
  47796. {
  47797. return new TabBarButton (name, this, index);
  47798. }
  47799. void TabbedButtonBar::clearTabs()
  47800. {
  47801. tabs.clear();
  47802. tabColours.clear();
  47803. currentTabIndex = -1;
  47804. deleteAndZero (extraTabsButton);
  47805. removeChildComponent (behindFrontTab);
  47806. deleteAllChildren();
  47807. addChildComponent (behindFrontTab);
  47808. setCurrentTabIndex (-1);
  47809. }
  47810. void TabbedButtonBar::addTab (const String& tabName,
  47811. const Colour& tabBackgroundColour,
  47812. int insertIndex)
  47813. {
  47814. jassert (tabName.isNotEmpty()); // you have to give them all a name..
  47815. if (tabName.isNotEmpty())
  47816. {
  47817. if (((unsigned int) insertIndex) > (unsigned int) tabs.size())
  47818. insertIndex = tabs.size();
  47819. for (int i = tabs.size(); --i >= insertIndex;)
  47820. {
  47821. TabBarButton* const tb = getTabButton (i);
  47822. if (tb != 0)
  47823. tb->tabIndex++;
  47824. }
  47825. tabs.insert (insertIndex, tabName);
  47826. tabColours.insert (insertIndex, tabBackgroundColour);
  47827. TabBarButton* const tb = createTabButton (tabName, insertIndex);
  47828. jassert (tb != 0); // your createTabButton() mustn't return zero!
  47829. addAndMakeVisible (tb, insertIndex);
  47830. resized();
  47831. if (currentTabIndex < 0)
  47832. setCurrentTabIndex (0);
  47833. }
  47834. }
  47835. void TabbedButtonBar::setTabName (const int tabIndex,
  47836. const String& newName)
  47837. {
  47838. if (((unsigned int) tabIndex) < (unsigned int) tabs.size()
  47839. && tabs[tabIndex] != newName)
  47840. {
  47841. tabs.set (tabIndex, newName);
  47842. TabBarButton* const tb = getTabButton (tabIndex);
  47843. if (tb != 0)
  47844. tb->setButtonText (newName);
  47845. resized();
  47846. }
  47847. }
  47848. void TabbedButtonBar::removeTab (const int tabIndex)
  47849. {
  47850. if (((unsigned int) tabIndex) < (unsigned int) tabs.size())
  47851. {
  47852. const int oldTabIndex = currentTabIndex;
  47853. if (currentTabIndex == tabIndex)
  47854. currentTabIndex = -1;
  47855. tabs.remove (tabIndex);
  47856. tabColours.remove (tabIndex);
  47857. TabBarButton* const tb = getTabButton (tabIndex);
  47858. if (tb != 0)
  47859. delete tb;
  47860. for (int i = tabIndex + 1; i <= tabs.size(); ++i)
  47861. {
  47862. TabBarButton* const tb = getTabButton (i);
  47863. if (tb != 0)
  47864. tb->tabIndex--;
  47865. }
  47866. resized();
  47867. setCurrentTabIndex (jlimit (0, jmax (0, tabs.size() - 1), oldTabIndex));
  47868. }
  47869. }
  47870. void TabbedButtonBar::moveTab (const int currentIndex,
  47871. const int newIndex)
  47872. {
  47873. tabs.move (currentIndex, newIndex);
  47874. tabColours.move (currentIndex, newIndex);
  47875. resized();
  47876. }
  47877. int TabbedButtonBar::getNumTabs() const
  47878. {
  47879. return tabs.size();
  47880. }
  47881. const StringArray TabbedButtonBar::getTabNames() const
  47882. {
  47883. return tabs;
  47884. }
  47885. void TabbedButtonBar::setCurrentTabIndex (int newIndex, const bool sendChangeMessage_)
  47886. {
  47887. if (currentTabIndex != newIndex)
  47888. {
  47889. if (((unsigned int) newIndex) >= (unsigned int) tabs.size())
  47890. newIndex = -1;
  47891. currentTabIndex = newIndex;
  47892. for (int i = 0; i < getNumChildComponents(); ++i)
  47893. {
  47894. TabBarButton* const tb = dynamic_cast <TabBarButton*> (getChildComponent (i));
  47895. if (tb != 0)
  47896. tb->setToggleState (tb->tabIndex == newIndex, false);
  47897. }
  47898. resized();
  47899. if (sendChangeMessage_)
  47900. sendChangeMessage (this);
  47901. currentTabChanged (newIndex, newIndex >= 0 ? tabs [newIndex] : String::empty);
  47902. }
  47903. }
  47904. TabBarButton* TabbedButtonBar::getTabButton (const int index) const
  47905. {
  47906. for (int i = getNumChildComponents(); --i >= 0;)
  47907. {
  47908. TabBarButton* const tb = dynamic_cast <TabBarButton*> (getChildComponent (i));
  47909. if (tb != 0 && tb->tabIndex == index)
  47910. return tb;
  47911. }
  47912. return 0;
  47913. }
  47914. void TabbedButtonBar::lookAndFeelChanged()
  47915. {
  47916. deleteAndZero (extraTabsButton);
  47917. resized();
  47918. }
  47919. void TabbedButtonBar::resized()
  47920. {
  47921. const double minimumScale = 0.7;
  47922. int depth = getWidth();
  47923. int length = getHeight();
  47924. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  47925. swapVariables (depth, length);
  47926. const int overlap = getLookAndFeel().getTabButtonOverlap (depth)
  47927. + getLookAndFeel().getTabButtonSpaceAroundImage() * 2;
  47928. int i, totalLength = overlap;
  47929. int numVisibleButtons = tabs.size();
  47930. for (i = 0; i < getNumChildComponents(); ++i)
  47931. {
  47932. TabBarButton* const tb = dynamic_cast <TabBarButton*> (getChildComponent (i));
  47933. if (tb != 0)
  47934. {
  47935. totalLength += tb->getBestTabLength (depth) - overlap;
  47936. tb->overlapPixels = overlap / 2;
  47937. }
  47938. }
  47939. double scale = 1.0;
  47940. if (totalLength > length)
  47941. scale = jmax (minimumScale, length / (double) totalLength);
  47942. const bool isTooBig = totalLength * scale > length;
  47943. int tabsButtonPos = 0;
  47944. if (isTooBig)
  47945. {
  47946. if (extraTabsButton == 0)
  47947. {
  47948. addAndMakeVisible (extraTabsButton = getLookAndFeel().createTabBarExtrasButton());
  47949. extraTabsButton->addButtonListener (this);
  47950. extraTabsButton->setAlwaysOnTop (true);
  47951. extraTabsButton->setTriggeredOnMouseDown (true);
  47952. }
  47953. const int buttonSize = jmin (proportionOfWidth (0.7f), proportionOfHeight (0.7f));
  47954. extraTabsButton->setSize (buttonSize, buttonSize);
  47955. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  47956. {
  47957. tabsButtonPos = getWidth() - buttonSize / 2 - 1;
  47958. extraTabsButton->setCentrePosition (tabsButtonPos, getHeight() / 2);
  47959. }
  47960. else
  47961. {
  47962. tabsButtonPos = getHeight() - buttonSize / 2 - 1;
  47963. extraTabsButton->setCentrePosition (getWidth() / 2, tabsButtonPos);
  47964. }
  47965. totalLength = 0;
  47966. for (i = 0; i < tabs.size(); ++i)
  47967. {
  47968. TabBarButton* const tb = getTabButton (i);
  47969. if (tb != 0)
  47970. {
  47971. const int newLength = totalLength + tb->getBestTabLength (depth);
  47972. if (i > 0 && newLength * minimumScale > tabsButtonPos)
  47973. {
  47974. totalLength += overlap;
  47975. break;
  47976. }
  47977. numVisibleButtons = i + 1;
  47978. totalLength = newLength - overlap;
  47979. }
  47980. }
  47981. scale = jmax (minimumScale, tabsButtonPos / (double) totalLength);
  47982. }
  47983. else
  47984. {
  47985. deleteAndZero (extraTabsButton);
  47986. }
  47987. int pos = 0;
  47988. TabBarButton* frontTab = 0;
  47989. for (i = 0; i < tabs.size(); ++i)
  47990. {
  47991. TabBarButton* const tb = getTabButton (i);
  47992. if (tb != 0)
  47993. {
  47994. const int bestLength = roundDoubleToInt (scale * tb->getBestTabLength (depth));
  47995. if (i < numVisibleButtons)
  47996. {
  47997. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  47998. tb->setBounds (pos, 0, bestLength, getHeight());
  47999. else
  48000. tb->setBounds (0, pos, getWidth(), bestLength);
  48001. tb->toBack();
  48002. if (tb->tabIndex == currentTabIndex)
  48003. frontTab = tb;
  48004. tb->setVisible (true);
  48005. }
  48006. else
  48007. {
  48008. tb->setVisible (false);
  48009. }
  48010. pos += bestLength - overlap;
  48011. }
  48012. }
  48013. behindFrontTab->setBounds (0, 0, getWidth(), getHeight());
  48014. if (frontTab != 0)
  48015. {
  48016. frontTab->toFront (false);
  48017. behindFrontTab->toBehind (frontTab);
  48018. }
  48019. }
  48020. const Colour TabbedButtonBar::getTabBackgroundColour (const int tabIndex)
  48021. {
  48022. return tabColours [tabIndex];
  48023. }
  48024. void TabbedButtonBar::setTabBackgroundColour (const int tabIndex, const Colour& newColour)
  48025. {
  48026. if (((unsigned int) tabIndex) < (unsigned int) tabColours.size()
  48027. && tabColours [tabIndex] != newColour)
  48028. {
  48029. tabColours.set (tabIndex, newColour);
  48030. repaint();
  48031. }
  48032. }
  48033. void TabbedButtonBar::buttonClicked (Button* button)
  48034. {
  48035. if (extraTabsButton == button)
  48036. {
  48037. PopupMenu m;
  48038. for (int i = 0; i < tabs.size(); ++i)
  48039. {
  48040. TabBarButton* const tb = getTabButton (i);
  48041. if (tb != 0 && ! tb->isVisible())
  48042. m.addItem (tb->tabIndex + 1, tabs[i], true, i == currentTabIndex);
  48043. }
  48044. const int res = m.showAt (extraTabsButton);
  48045. if (res != 0)
  48046. setCurrentTabIndex (res - 1);
  48047. }
  48048. }
  48049. void TabbedButtonBar::currentTabChanged (const int, const String&)
  48050. {
  48051. }
  48052. void TabbedButtonBar::popupMenuClickOnTab (const int, const String&)
  48053. {
  48054. }
  48055. END_JUCE_NAMESPACE
  48056. /********* End of inlined file: juce_TabbedButtonBar.cpp *********/
  48057. /********* Start of inlined file: juce_TabbedComponent.cpp *********/
  48058. BEGIN_JUCE_NAMESPACE
  48059. class TabCompButtonBar : public TabbedButtonBar
  48060. {
  48061. public:
  48062. TabCompButtonBar (TabbedComponent* const owner_,
  48063. const TabbedButtonBar::Orientation orientation)
  48064. : TabbedButtonBar (orientation),
  48065. owner (owner_)
  48066. {
  48067. }
  48068. ~TabCompButtonBar()
  48069. {
  48070. }
  48071. void currentTabChanged (const int newCurrentTabIndex,
  48072. const String& newTabName)
  48073. {
  48074. owner->changeCallback (newCurrentTabIndex, newTabName);
  48075. }
  48076. void popupMenuClickOnTab (const int tabIndex,
  48077. const String& tabName)
  48078. {
  48079. owner->popupMenuClickOnTab (tabIndex, tabName);
  48080. }
  48081. const Colour getTabBackgroundColour (const int tabIndex)
  48082. {
  48083. return owner->tabs->getTabBackgroundColour (tabIndex);
  48084. }
  48085. TabBarButton* createTabButton (const String& tabName, const int tabIndex)
  48086. {
  48087. return owner->createTabButton (tabName, tabIndex);
  48088. }
  48089. juce_UseDebuggingNewOperator
  48090. private:
  48091. TabbedComponent* const owner;
  48092. TabCompButtonBar (const TabCompButtonBar&);
  48093. const TabCompButtonBar& operator= (const TabCompButtonBar&);
  48094. };
  48095. TabbedComponent::TabbedComponent (const TabbedButtonBar::Orientation orientation)
  48096. : panelComponent (0),
  48097. tabDepth (30),
  48098. outlineThickness (1),
  48099. edgeIndent (0)
  48100. {
  48101. addAndMakeVisible (tabs = new TabCompButtonBar (this, orientation));
  48102. }
  48103. TabbedComponent::~TabbedComponent()
  48104. {
  48105. clearTabs();
  48106. delete tabs;
  48107. }
  48108. void TabbedComponent::setOrientation (const TabbedButtonBar::Orientation orientation)
  48109. {
  48110. tabs->setOrientation (orientation);
  48111. resized();
  48112. }
  48113. TabbedButtonBar::Orientation TabbedComponent::getOrientation() const throw()
  48114. {
  48115. return tabs->getOrientation();
  48116. }
  48117. void TabbedComponent::setTabBarDepth (const int newDepth)
  48118. {
  48119. if (tabDepth != newDepth)
  48120. {
  48121. tabDepth = newDepth;
  48122. resized();
  48123. }
  48124. }
  48125. TabBarButton* TabbedComponent::createTabButton (const String& tabName, const int tabIndex)
  48126. {
  48127. return new TabBarButton (tabName, tabs, tabIndex);
  48128. }
  48129. void TabbedComponent::clearTabs()
  48130. {
  48131. if (panelComponent != 0)
  48132. {
  48133. panelComponent->setVisible (false);
  48134. removeChildComponent (panelComponent);
  48135. panelComponent = 0;
  48136. }
  48137. tabs->clearTabs();
  48138. for (int i = contentComponents.size(); --i >= 0;)
  48139. {
  48140. Component* const c = contentComponents.getUnchecked(i);
  48141. // be careful not to delete these components until they've been removed from the tab component
  48142. jassert (c == 0 || c->isValidComponent());
  48143. if (c != 0 && c->getComponentPropertyBool (T("deleteByTabComp_"), false, false))
  48144. delete c;
  48145. }
  48146. contentComponents.clear();
  48147. }
  48148. void TabbedComponent::addTab (const String& tabName,
  48149. const Colour& tabBackgroundColour,
  48150. Component* const contentComponent,
  48151. const bool deleteComponentWhenNotNeeded,
  48152. const int insertIndex)
  48153. {
  48154. contentComponents.insert (insertIndex, contentComponent);
  48155. if (contentComponent != 0)
  48156. contentComponent->setComponentProperty (T("deleteByTabComp_"), deleteComponentWhenNotNeeded);
  48157. tabs->addTab (tabName, tabBackgroundColour, insertIndex);
  48158. }
  48159. void TabbedComponent::setTabName (const int tabIndex,
  48160. const String& newName)
  48161. {
  48162. tabs->setTabName (tabIndex, newName);
  48163. }
  48164. void TabbedComponent::removeTab (const int tabIndex)
  48165. {
  48166. Component* const c = contentComponents [tabIndex];
  48167. if (c != 0 && c->getComponentPropertyBool (T("deleteByTabComp_"), false, false))
  48168. {
  48169. if (c == panelComponent)
  48170. panelComponent = 0;
  48171. delete c;
  48172. }
  48173. contentComponents.remove (tabIndex);
  48174. tabs->removeTab (tabIndex);
  48175. }
  48176. int TabbedComponent::getNumTabs() const
  48177. {
  48178. return tabs->getNumTabs();
  48179. }
  48180. const StringArray TabbedComponent::getTabNames() const
  48181. {
  48182. return tabs->getTabNames();
  48183. }
  48184. Component* TabbedComponent::getTabContentComponent (const int tabIndex) const throw()
  48185. {
  48186. return contentComponents [tabIndex];
  48187. }
  48188. const Colour TabbedComponent::getTabBackgroundColour (const int tabIndex) const throw()
  48189. {
  48190. return tabs->getTabBackgroundColour (tabIndex);
  48191. }
  48192. void TabbedComponent::setTabBackgroundColour (const int tabIndex, const Colour& newColour)
  48193. {
  48194. tabs->setTabBackgroundColour (tabIndex, newColour);
  48195. if (getCurrentTabIndex() == tabIndex)
  48196. repaint();
  48197. }
  48198. void TabbedComponent::setCurrentTabIndex (const int newTabIndex, const bool sendChangeMessage)
  48199. {
  48200. tabs->setCurrentTabIndex (newTabIndex, sendChangeMessage);
  48201. }
  48202. int TabbedComponent::getCurrentTabIndex() const
  48203. {
  48204. return tabs->getCurrentTabIndex();
  48205. }
  48206. const String& TabbedComponent::getCurrentTabName() const
  48207. {
  48208. return tabs->getCurrentTabName();
  48209. }
  48210. void TabbedComponent::setOutline (int thickness)
  48211. {
  48212. outlineThickness = thickness;
  48213. repaint();
  48214. }
  48215. void TabbedComponent::setIndent (const int indentThickness)
  48216. {
  48217. edgeIndent = indentThickness;
  48218. }
  48219. void TabbedComponent::paint (Graphics& g)
  48220. {
  48221. g.fillAll (findColour (backgroundColourId));
  48222. const TabbedButtonBar::Orientation o = getOrientation();
  48223. int x = 0;
  48224. int y = 0;
  48225. int r = getWidth();
  48226. int b = getHeight();
  48227. if (o == TabbedButtonBar::TabsAtTop)
  48228. y += tabDepth;
  48229. else if (o == TabbedButtonBar::TabsAtBottom)
  48230. b -= tabDepth;
  48231. else if (o == TabbedButtonBar::TabsAtLeft)
  48232. x += tabDepth;
  48233. else if (o == TabbedButtonBar::TabsAtRight)
  48234. r -= tabDepth;
  48235. g.reduceClipRegion (x, y, r - x, b - y);
  48236. g.fillAll (tabs->getTabBackgroundColour (getCurrentTabIndex()));
  48237. if (outlineThickness > 0)
  48238. {
  48239. if (o == TabbedButtonBar::TabsAtTop)
  48240. --y;
  48241. else if (o == TabbedButtonBar::TabsAtBottom)
  48242. ++b;
  48243. else if (o == TabbedButtonBar::TabsAtLeft)
  48244. --x;
  48245. else if (o == TabbedButtonBar::TabsAtRight)
  48246. ++r;
  48247. g.setColour (findColour (outlineColourId));
  48248. g.drawRect (x, y, r - x, b - y, outlineThickness);
  48249. }
  48250. }
  48251. void TabbedComponent::resized()
  48252. {
  48253. const TabbedButtonBar::Orientation o = getOrientation();
  48254. const int indent = edgeIndent + outlineThickness;
  48255. BorderSize indents (indent);
  48256. if (o == TabbedButtonBar::TabsAtTop)
  48257. {
  48258. tabs->setBounds (0, 0, getWidth(), tabDepth);
  48259. indents.setTop (tabDepth + edgeIndent);
  48260. }
  48261. else if (o == TabbedButtonBar::TabsAtBottom)
  48262. {
  48263. tabs->setBounds (0, getHeight() - tabDepth, getWidth(), tabDepth);
  48264. indents.setBottom (tabDepth + edgeIndent);
  48265. }
  48266. else if (o == TabbedButtonBar::TabsAtLeft)
  48267. {
  48268. tabs->setBounds (0, 0, tabDepth, getHeight());
  48269. indents.setLeft (tabDepth + edgeIndent);
  48270. }
  48271. else if (o == TabbedButtonBar::TabsAtRight)
  48272. {
  48273. tabs->setBounds (getWidth() - tabDepth, 0, tabDepth, getHeight());
  48274. indents.setRight (tabDepth + edgeIndent);
  48275. }
  48276. const Rectangle bounds (indents.subtractedFrom (Rectangle (0, 0, getWidth(), getHeight())));
  48277. for (int i = contentComponents.size(); --i >= 0;)
  48278. if (contentComponents.getUnchecked (i) != 0)
  48279. contentComponents.getUnchecked (i)->setBounds (bounds);
  48280. }
  48281. void TabbedComponent::lookAndFeelChanged()
  48282. {
  48283. for (int i = contentComponents.size(); --i >= 0;)
  48284. if (contentComponents.getUnchecked (i) != 0)
  48285. contentComponents.getUnchecked (i)->lookAndFeelChanged();
  48286. }
  48287. void TabbedComponent::changeCallback (const int newCurrentTabIndex,
  48288. const String& newTabName)
  48289. {
  48290. if (panelComponent != 0)
  48291. {
  48292. panelComponent->setVisible (false);
  48293. removeChildComponent (panelComponent);
  48294. panelComponent = 0;
  48295. }
  48296. if (getCurrentTabIndex() >= 0)
  48297. {
  48298. panelComponent = contentComponents [getCurrentTabIndex()];
  48299. if (panelComponent != 0)
  48300. {
  48301. // do these ops as two stages instead of addAndMakeVisible() so that the
  48302. // component has always got a parent when it gets the visibilityChanged() callback
  48303. addChildComponent (panelComponent);
  48304. panelComponent->setVisible (true);
  48305. panelComponent->toFront (true);
  48306. }
  48307. repaint();
  48308. }
  48309. resized();
  48310. currentTabChanged (newCurrentTabIndex, newTabName);
  48311. }
  48312. void TabbedComponent::currentTabChanged (const int, const String&)
  48313. {
  48314. }
  48315. void TabbedComponent::popupMenuClickOnTab (const int, const String&)
  48316. {
  48317. }
  48318. END_JUCE_NAMESPACE
  48319. /********* End of inlined file: juce_TabbedComponent.cpp *********/
  48320. /********* Start of inlined file: juce_Viewport.cpp *********/
  48321. BEGIN_JUCE_NAMESPACE
  48322. Viewport::Viewport (const String& componentName)
  48323. : Component (componentName),
  48324. contentComp (0),
  48325. lastVX (0),
  48326. lastVY (0),
  48327. lastVW (0),
  48328. lastVH (0),
  48329. scrollBarThickness (0),
  48330. singleStepX (16),
  48331. singleStepY (16),
  48332. showHScrollbar (true),
  48333. showVScrollbar (true)
  48334. {
  48335. // content holder is used to clip the contents so they don't overlap the scrollbars
  48336. addAndMakeVisible (contentHolder = new Component());
  48337. contentHolder->setInterceptsMouseClicks (false, true);
  48338. verticalScrollBar = new ScrollBar (true);
  48339. horizontalScrollBar = new ScrollBar (false);
  48340. addChildComponent (verticalScrollBar);
  48341. addChildComponent (horizontalScrollBar);
  48342. verticalScrollBar->addListener (this);
  48343. horizontalScrollBar->addListener (this);
  48344. setInterceptsMouseClicks (false, true);
  48345. setWantsKeyboardFocus (true);
  48346. }
  48347. Viewport::~Viewport()
  48348. {
  48349. contentHolder->deleteAllChildren();
  48350. deleteAllChildren();
  48351. }
  48352. void Viewport::visibleAreaChanged (int, int, int, int)
  48353. {
  48354. }
  48355. void Viewport::setViewedComponent (Component* const newViewedComponent)
  48356. {
  48357. if (contentComp != newViewedComponent)
  48358. {
  48359. if (contentComp->isValidComponent())
  48360. {
  48361. Component* const oldComp = contentComp;
  48362. contentComp = 0;
  48363. delete oldComp;
  48364. }
  48365. contentComp = newViewedComponent;
  48366. if (contentComp != 0)
  48367. {
  48368. contentComp->setTopLeftPosition (0, 0);
  48369. contentHolder->addAndMakeVisible (contentComp);
  48370. contentComp->addComponentListener (this);
  48371. }
  48372. updateVisibleRegion();
  48373. }
  48374. }
  48375. int Viewport::getMaximumVisibleWidth() const throw()
  48376. {
  48377. return jmax (0, getWidth() - (verticalScrollBar->isVisible() ? getScrollBarThickness() : 0));
  48378. }
  48379. int Viewport::getMaximumVisibleHeight() const throw()
  48380. {
  48381. return jmax (0, getHeight() - (horizontalScrollBar->isVisible() ? getScrollBarThickness() : 0));
  48382. }
  48383. void Viewport::setViewPosition (const int xPixelsOffset,
  48384. const int yPixelsOffset)
  48385. {
  48386. if (contentComp != 0)
  48387. contentComp->setTopLeftPosition (-xPixelsOffset,
  48388. -yPixelsOffset);
  48389. }
  48390. void Viewport::setViewPositionProportionately (const double x,
  48391. const double y)
  48392. {
  48393. if (contentComp != 0)
  48394. setViewPosition (jmax (0, roundDoubleToInt (x * (contentComp->getWidth() - getWidth()))),
  48395. jmax (0, roundDoubleToInt (y * (contentComp->getHeight() - getHeight()))));
  48396. }
  48397. void Viewport::componentMovedOrResized (Component&, bool, bool)
  48398. {
  48399. updateVisibleRegion();
  48400. }
  48401. void Viewport::resized()
  48402. {
  48403. updateVisibleRegion();
  48404. }
  48405. void Viewport::updateVisibleRegion()
  48406. {
  48407. if (contentComp != 0)
  48408. {
  48409. const int newVX = -contentComp->getX();
  48410. const int newVY = -contentComp->getY();
  48411. if (newVX == 0 && newVY == 0
  48412. && contentComp->getWidth() <= getWidth()
  48413. && contentComp->getHeight() <= getHeight())
  48414. {
  48415. horizontalScrollBar->setVisible (false);
  48416. verticalScrollBar->setVisible (false);
  48417. }
  48418. if ((contentComp->getWidth() > 0) && showHScrollbar
  48419. && getHeight() > getScrollBarThickness())
  48420. {
  48421. horizontalScrollBar->setRangeLimits (0.0, contentComp->getWidth());
  48422. horizontalScrollBar->setCurrentRange (newVX, getMaximumVisibleWidth());
  48423. horizontalScrollBar->setSingleStepSize (singleStepX);
  48424. }
  48425. else
  48426. {
  48427. horizontalScrollBar->setVisible (false);
  48428. }
  48429. if ((contentComp->getHeight() > 0) && showVScrollbar
  48430. && getWidth() > getScrollBarThickness())
  48431. {
  48432. verticalScrollBar->setRangeLimits (0.0, contentComp->getHeight());
  48433. verticalScrollBar->setCurrentRange (newVY, getMaximumVisibleHeight());
  48434. verticalScrollBar->setSingleStepSize (singleStepY);
  48435. }
  48436. else
  48437. {
  48438. verticalScrollBar->setVisible (false);
  48439. }
  48440. if (verticalScrollBar->isVisible())
  48441. {
  48442. horizontalScrollBar->setCurrentRange (newVX, getMaximumVisibleWidth());
  48443. verticalScrollBar->setCurrentRange (newVY, getMaximumVisibleHeight());
  48444. verticalScrollBar
  48445. ->setBounds (getMaximumVisibleWidth(), 0,
  48446. getScrollBarThickness(), getMaximumVisibleHeight());
  48447. }
  48448. if (horizontalScrollBar->isVisible())
  48449. {
  48450. horizontalScrollBar->setCurrentRange (newVX, getMaximumVisibleWidth());
  48451. horizontalScrollBar
  48452. ->setBounds (0, getMaximumVisibleHeight(),
  48453. getMaximumVisibleWidth(), getScrollBarThickness());
  48454. }
  48455. contentHolder->setSize (getMaximumVisibleWidth(),
  48456. getMaximumVisibleHeight());
  48457. const int newVW = jmin (contentComp->getRight(), getMaximumVisibleWidth());
  48458. const int newVH = jmin (contentComp->getBottom(), getMaximumVisibleHeight());
  48459. if (newVX != lastVX
  48460. || newVY != lastVY
  48461. || newVW != lastVW
  48462. || newVH != lastVH)
  48463. {
  48464. lastVX = newVX;
  48465. lastVY = newVY;
  48466. lastVW = newVW;
  48467. lastVH = newVH;
  48468. visibleAreaChanged (newVX, newVY, newVW, newVH);
  48469. }
  48470. horizontalScrollBar->handleUpdateNowIfNeeded();
  48471. verticalScrollBar->handleUpdateNowIfNeeded();
  48472. }
  48473. else
  48474. {
  48475. horizontalScrollBar->setVisible (false);
  48476. verticalScrollBar->setVisible (false);
  48477. }
  48478. }
  48479. void Viewport::setSingleStepSizes (const int stepX,
  48480. const int stepY)
  48481. {
  48482. singleStepX = stepX;
  48483. singleStepY = stepY;
  48484. updateVisibleRegion();
  48485. }
  48486. void Viewport::setScrollBarsShown (const bool showVerticalScrollbarIfNeeded,
  48487. const bool showHorizontalScrollbarIfNeeded)
  48488. {
  48489. showVScrollbar = showVerticalScrollbarIfNeeded;
  48490. showHScrollbar = showHorizontalScrollbarIfNeeded;
  48491. updateVisibleRegion();
  48492. }
  48493. void Viewport::setScrollBarThickness (const int thickness)
  48494. {
  48495. scrollBarThickness = thickness;
  48496. updateVisibleRegion();
  48497. }
  48498. int Viewport::getScrollBarThickness() const throw()
  48499. {
  48500. return (scrollBarThickness > 0) ? scrollBarThickness
  48501. : getLookAndFeel().getDefaultScrollbarWidth();
  48502. }
  48503. void Viewport::setScrollBarButtonVisibility (const bool buttonsVisible)
  48504. {
  48505. verticalScrollBar->setButtonVisibility (buttonsVisible);
  48506. horizontalScrollBar->setButtonVisibility (buttonsVisible);
  48507. }
  48508. void Viewport::scrollBarMoved (ScrollBar* scrollBarThatHasMoved, const double newRangeStart)
  48509. {
  48510. if (scrollBarThatHasMoved == horizontalScrollBar)
  48511. {
  48512. setViewPosition (roundDoubleToInt (newRangeStart), getViewPositionY());
  48513. }
  48514. else if (scrollBarThatHasMoved == verticalScrollBar)
  48515. {
  48516. setViewPosition (getViewPositionX(), roundDoubleToInt (newRangeStart));
  48517. }
  48518. }
  48519. void Viewport::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  48520. {
  48521. if (! useMouseWheelMoveIfNeeded (e, wheelIncrementX, wheelIncrementY))
  48522. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  48523. }
  48524. bool Viewport::useMouseWheelMoveIfNeeded (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  48525. {
  48526. if (! (e.mods.isAltDown() || e.mods.isCtrlDown()))
  48527. {
  48528. const bool hasVertBar = verticalScrollBar->isVisible();
  48529. const bool hasHorzBar = horizontalScrollBar->isVisible();
  48530. if (hasHorzBar && (wheelIncrementX != 0 || e.mods.isShiftDown() || ! hasVertBar))
  48531. {
  48532. if (wheelIncrementX == 0 && ! hasVertBar)
  48533. wheelIncrementX = wheelIncrementY;
  48534. horizontalScrollBar->mouseWheelMove (e.getEventRelativeTo (horizontalScrollBar),
  48535. wheelIncrementX, wheelIncrementY);
  48536. return true;
  48537. }
  48538. else if (hasVertBar && wheelIncrementY != 0)
  48539. {
  48540. verticalScrollBar->mouseWheelMove (e.getEventRelativeTo (verticalScrollBar),
  48541. wheelIncrementX, wheelIncrementY);
  48542. return true;
  48543. }
  48544. }
  48545. return false;
  48546. }
  48547. bool Viewport::keyPressed (const KeyPress& key)
  48548. {
  48549. const bool isUpDownKey = key.isKeyCode (KeyPress::upKey)
  48550. || key.isKeyCode (KeyPress::downKey)
  48551. || key.isKeyCode (KeyPress::pageUpKey)
  48552. || key.isKeyCode (KeyPress::pageDownKey)
  48553. || key.isKeyCode (KeyPress::homeKey)
  48554. || key.isKeyCode (KeyPress::endKey);
  48555. if (verticalScrollBar->isVisible() && isUpDownKey)
  48556. return verticalScrollBar->keyPressed (key);
  48557. const bool isLeftRightKey = key.isKeyCode (KeyPress::leftKey)
  48558. || key.isKeyCode (KeyPress::rightKey);
  48559. if (horizontalScrollBar->isVisible() && (isUpDownKey || isLeftRightKey))
  48560. return horizontalScrollBar->keyPressed (key);
  48561. return false;
  48562. }
  48563. END_JUCE_NAMESPACE
  48564. /********* End of inlined file: juce_Viewport.cpp *********/
  48565. /********* Start of inlined file: juce_LookAndFeel.cpp *********/
  48566. BEGIN_JUCE_NAMESPACE
  48567. static const Colour createBaseColour (const Colour& buttonColour,
  48568. const bool hasKeyboardFocus,
  48569. const bool isMouseOverButton,
  48570. const bool isButtonDown) throw()
  48571. {
  48572. const float sat = hasKeyboardFocus ? 1.3f : 0.9f;
  48573. const Colour baseColour (buttonColour.withMultipliedSaturation (sat));
  48574. if (isButtonDown)
  48575. return baseColour.contrasting (0.2f);
  48576. else if (isMouseOverButton)
  48577. return baseColour.contrasting (0.1f);
  48578. return baseColour;
  48579. }
  48580. static String defaultSansName, defaultSerifName, defaultFixedName;
  48581. void clearUpDefaultFontNames() throw()
  48582. {
  48583. defaultSansName = String::empty;
  48584. defaultSerifName = String::empty;
  48585. defaultFixedName = String::empty;
  48586. }
  48587. LookAndFeel::LookAndFeel()
  48588. {
  48589. /* if this fails it means you're trying to create a LookAndFeel object before
  48590. the static Colours have been initialised. That ain't gonna work. It probably
  48591. means that you're using a static LookAndFeel object and that your compiler has
  48592. decided to intialise it before the Colours class.
  48593. */
  48594. jassert (Colours::white == Colour (0xffffffff));
  48595. // set up the standard set of colours..
  48596. #define textButtonColour 0xffbbbbff
  48597. #define textHighlightColour 0x401111ee
  48598. #define standardOutlineColour 0xb2808080
  48599. static const int standardColours[] =
  48600. {
  48601. TextButton::buttonColourId, textButtonColour,
  48602. TextButton::buttonOnColourId, 0xff4444ff,
  48603. TextButton::textColourId, 0xff000000,
  48604. ComboBox::buttonColourId, 0xffbbbbff,
  48605. ComboBox::outlineColourId, standardOutlineColour,
  48606. ToggleButton::textColourId, 0xff000000,
  48607. TextEditor::backgroundColourId, 0xffffffff,
  48608. TextEditor::textColourId, 0xff000000,
  48609. TextEditor::highlightColourId, textHighlightColour,
  48610. TextEditor::highlightedTextColourId, 0xff000000,
  48611. TextEditor::caretColourId, 0xff000000,
  48612. TextEditor::outlineColourId, 0x00000000,
  48613. TextEditor::focusedOutlineColourId, textButtonColour,
  48614. TextEditor::shadowColourId, 0x38000000,
  48615. Label::backgroundColourId, 0x00000000,
  48616. Label::textColourId, 0xff000000,
  48617. Label::outlineColourId, 0x00000000,
  48618. ScrollBar::backgroundColourId, 0x00000000,
  48619. ScrollBar::thumbColourId, 0xffffffff,
  48620. ScrollBar::trackColourId, 0xffffffff,
  48621. TreeView::linesColourId, 0x4c000000,
  48622. TreeView::backgroundColourId, 0x00000000,
  48623. PopupMenu::backgroundColourId, 0xffffffff,
  48624. PopupMenu::textColourId, 0xff000000,
  48625. PopupMenu::headerTextColourId, 0xff000000,
  48626. PopupMenu::highlightedTextColourId, 0xffffffff,
  48627. PopupMenu::highlightedBackgroundColourId, 0x991111aa,
  48628. ComboBox::textColourId, 0xff000000,
  48629. ComboBox::backgroundColourId, 0xffffffff,
  48630. ComboBox::arrowColourId, 0x99000000,
  48631. ListBox::backgroundColourId, 0xffffffff,
  48632. ListBox::outlineColourId, standardOutlineColour,
  48633. ListBox::textColourId, 0xff000000,
  48634. Slider::backgroundColourId, 0x00000000,
  48635. Slider::thumbColourId, textButtonColour,
  48636. Slider::trackColourId, 0x7fffffff,
  48637. Slider::rotarySliderFillColourId, 0x7f0000ff,
  48638. Slider::rotarySliderOutlineColourId, 0x66000000,
  48639. Slider::textBoxTextColourId, 0xff000000,
  48640. Slider::textBoxBackgroundColourId, 0xffffffff,
  48641. Slider::textBoxHighlightColourId, textHighlightColour,
  48642. Slider::textBoxOutlineColourId, standardOutlineColour,
  48643. ResizableWindow::backgroundColourId, 0xff777777,
  48644. //DocumentWindow::textColourId, 0xff000000, // (this is deliberately not set)
  48645. AlertWindow::backgroundColourId, 0xffededed,
  48646. AlertWindow::textColourId, 0xff000000,
  48647. AlertWindow::outlineColourId, 0xff666666,
  48648. ProgressBar::backgroundColourId, 0xffeeeeee,
  48649. ProgressBar::foregroundColourId, 0xffaaaaee,
  48650. TooltipWindow::backgroundColourId, 0xffeeeebb,
  48651. TooltipWindow::textColourId, 0xff000000,
  48652. TooltipWindow::outlineColourId, 0x4c000000,
  48653. TabbedComponent::backgroundColourId, 0x00000000,
  48654. TabbedComponent::outlineColourId, 0xff777777,
  48655. TabbedButtonBar::tabOutlineColourId, 0x80000000,
  48656. TabbedButtonBar::frontOutlineColourId, 0x90000000,
  48657. Toolbar::backgroundColourId, 0xfff6f8f9,
  48658. Toolbar::separatorColourId, 0x4c000000,
  48659. Toolbar::buttonMouseOverBackgroundColourId, 0x4c0000ff,
  48660. Toolbar::buttonMouseDownBackgroundColourId, 0x800000ff,
  48661. Toolbar::labelTextColourId, 0xff000000,
  48662. Toolbar::editingModeOutlineColourId, 0xffff0000,
  48663. HyperlinkButton::textColourId, 0xcc1111ee,
  48664. GroupComponent::outlineColourId, 0x66000000,
  48665. GroupComponent::textColourId, 0xff000000,
  48666. DirectoryContentsDisplayComponent::highlightColourId, textHighlightColour,
  48667. DirectoryContentsDisplayComponent::textColourId, 0xff000000,
  48668. 0x1000440, /*LassoComponent::lassoFillColourId*/ 0x66dddddd,
  48669. 0x1000441, /*LassoComponent::lassoOutlineColourId*/ 0x99111111,
  48670. MidiKeyboardComponent::whiteNoteColourId, 0xffffffff,
  48671. MidiKeyboardComponent::blackNoteColourId, 0xff000000,
  48672. MidiKeyboardComponent::keySeparatorLineColourId, 0x66000000,
  48673. MidiKeyboardComponent::mouseOverKeyOverlayColourId, 0x80ffff00,
  48674. MidiKeyboardComponent::keyDownOverlayColourId, 0xffb6b600,
  48675. MidiKeyboardComponent::textLabelColourId, 0xff000000,
  48676. MidiKeyboardComponent::upDownButtonBackgroundColourId, 0xffd3d3d3,
  48677. MidiKeyboardComponent::upDownButtonArrowColourId, 0xff000000,
  48678. ColourSelector::backgroundColourId, 0xffe5e5e5,
  48679. ColourSelector::labelTextColourId, 0xff000000,
  48680. FileSearchPathListComponent::backgroundColourId, 0xffffffff,
  48681. };
  48682. for (int i = 0; i < numElementsInArray (standardColours); i += 2)
  48683. setColour (standardColours [i], Colour (standardColours [i + 1]));
  48684. if (defaultSansName.isEmpty())
  48685. Typeface::getDefaultFontNames (defaultSansName, defaultSerifName, defaultFixedName);
  48686. defaultSans = defaultSansName;
  48687. defaultSerif = defaultSerifName;
  48688. defaultFixed = defaultFixedName;
  48689. }
  48690. LookAndFeel::~LookAndFeel()
  48691. {
  48692. }
  48693. const Colour LookAndFeel::findColour (const int colourId) const throw()
  48694. {
  48695. const int index = colourIds.indexOf (colourId);
  48696. if (index >= 0)
  48697. return colours [index];
  48698. jassertfalse
  48699. return Colours::black;
  48700. }
  48701. void LookAndFeel::setColour (const int colourId, const Colour& colour) throw()
  48702. {
  48703. const int index = colourIds.indexOf (colourId);
  48704. if (index >= 0)
  48705. colours.set (index, colour);
  48706. colourIds.add (colourId);
  48707. colours.add (colour);
  48708. }
  48709. bool LookAndFeel::isColourSpecified (const int colourId) const throw()
  48710. {
  48711. return colourIds.contains (colourId);
  48712. }
  48713. static LookAndFeel* defaultLF = 0;
  48714. static LookAndFeel* currentDefaultLF = 0;
  48715. LookAndFeel& LookAndFeel::getDefaultLookAndFeel() throw()
  48716. {
  48717. // if this happens, your app hasn't initialised itself properly.. if you're
  48718. // trying to hack your own main() function, have a look at
  48719. // JUCEApplication::initialiseForGUI()
  48720. jassert (currentDefaultLF != 0);
  48721. return *currentDefaultLF;
  48722. }
  48723. void LookAndFeel::setDefaultLookAndFeel (LookAndFeel* newDefaultLookAndFeel) throw()
  48724. {
  48725. if (newDefaultLookAndFeel == 0)
  48726. {
  48727. if (defaultLF == 0)
  48728. defaultLF = new LookAndFeel();
  48729. newDefaultLookAndFeel = defaultLF;
  48730. }
  48731. currentDefaultLF = newDefaultLookAndFeel;
  48732. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  48733. {
  48734. Component* const c = Desktop::getInstance().getComponent (i);
  48735. if (c != 0)
  48736. c->sendLookAndFeelChange();
  48737. }
  48738. }
  48739. void LookAndFeel::clearDefaultLookAndFeel() throw()
  48740. {
  48741. if (currentDefaultLF == defaultLF)
  48742. currentDefaultLF = 0;
  48743. deleteAndZero (defaultLF);
  48744. }
  48745. const Typeface::Ptr LookAndFeel::getTypefaceForFont (const Font& font)
  48746. {
  48747. String faceName (font.getTypefaceName());
  48748. if (faceName == Typeface::defaultTypefaceNameSans)
  48749. faceName = defaultSans;
  48750. else if (faceName == Typeface::defaultTypefaceNameSerif)
  48751. faceName = defaultSerif;
  48752. else if (faceName == Typeface::defaultTypefaceNameMono)
  48753. faceName = defaultFixed;
  48754. return new Typeface (faceName, font.isBold(), font.isItalic());
  48755. }
  48756. void LookAndFeel::setDefaultSansSerifTypefaceName (const String& newName)
  48757. {
  48758. defaultSans = newName;
  48759. }
  48760. void LookAndFeel::drawButtonBackground (Graphics& g,
  48761. Button& button,
  48762. const Colour& backgroundColour,
  48763. bool isMouseOverButton,
  48764. bool isButtonDown)
  48765. {
  48766. const int width = button.getWidth();
  48767. const int height = button.getHeight();
  48768. const float outlineThickness = button.isEnabled() ? ((isButtonDown || isMouseOverButton) ? 1.2f : 0.7f) : 0.4f;
  48769. const float halfThickness = outlineThickness * 0.5f;
  48770. const float indentL = button.isConnectedOnLeft() ? 0.1f : halfThickness;
  48771. const float indentR = button.isConnectedOnRight() ? 0.1f : halfThickness;
  48772. const float indentT = button.isConnectedOnTop() ? 0.1f : halfThickness;
  48773. const float indentB = button.isConnectedOnBottom() ? 0.1f : halfThickness;
  48774. const Colour baseColour (createBaseColour (backgroundColour,
  48775. button.hasKeyboardFocus (true),
  48776. isMouseOverButton, isButtonDown)
  48777. .withMultipliedAlpha (button.isEnabled() ? 1.0f : 0.5f));
  48778. drawGlassLozenge (g,
  48779. indentL,
  48780. indentT,
  48781. width - indentL - indentR,
  48782. height - indentT - indentB,
  48783. baseColour, outlineThickness, -1.0f,
  48784. button.isConnectedOnLeft(),
  48785. button.isConnectedOnRight(),
  48786. button.isConnectedOnTop(),
  48787. button.isConnectedOnBottom());
  48788. }
  48789. const Font LookAndFeel::getFontForTextButton (TextButton& button)
  48790. {
  48791. return button.getFont();
  48792. }
  48793. void LookAndFeel::drawButtonText (Graphics& g, TextButton& button,
  48794. bool /*isMouseOverButton*/, bool /*isButtonDown*/)
  48795. {
  48796. g.setFont (getFontForTextButton (button));
  48797. g.setColour (button.findColour (TextButton::textColourId)
  48798. .withMultipliedAlpha (button.isEnabled() ? 1.0f : 0.5f));
  48799. const int yIndent = jmin (4, button.proportionOfHeight (0.3f));
  48800. const int cornerSize = jmin (button.getHeight(), button.getWidth()) / 2;
  48801. const int fontHeight = roundFloatToInt (g.getCurrentFont().getHeight() * 0.6f);
  48802. const int leftIndent = jmin (fontHeight, 2 + cornerSize / (button.isConnectedOnLeft() ? 4 : 2));
  48803. const int rightIndent = jmin (fontHeight, 2 + cornerSize / (button.isConnectedOnRight() ? 4 : 2));
  48804. g.drawFittedText (button.getButtonText(),
  48805. leftIndent,
  48806. yIndent,
  48807. button.getWidth() - leftIndent - rightIndent,
  48808. button.getHeight() - yIndent * 2,
  48809. Justification::centred, 2);
  48810. }
  48811. void LookAndFeel::drawTickBox (Graphics& g,
  48812. Component& component,
  48813. int x, int y, int w, int h,
  48814. const bool ticked,
  48815. const bool isEnabled,
  48816. const bool isMouseOverButton,
  48817. const bool isButtonDown)
  48818. {
  48819. const float boxSize = w * 0.7f;
  48820. drawGlassSphere (g, (float) x, y + (h - boxSize) * 0.5f, boxSize,
  48821. createBaseColour (component.findColour (TextButton::buttonColourId)
  48822. .withMultipliedAlpha (isEnabled ? 1.0f : 0.5f),
  48823. true,
  48824. isMouseOverButton,
  48825. isButtonDown),
  48826. isEnabled ? ((isButtonDown || isMouseOverButton) ? 1.1f : 0.5f) : 0.3f);
  48827. if (ticked)
  48828. {
  48829. Path tick;
  48830. tick.startNewSubPath (1.5f, 3.0f);
  48831. tick.lineTo (3.0f, 6.0f);
  48832. tick.lineTo (6.0f, 0.0f);
  48833. g.setColour (isEnabled ? Colours::black : Colours::grey);
  48834. const AffineTransform trans (AffineTransform::scale (w / 9.0f, h / 9.0f)
  48835. .translated ((float) x, (float) y));
  48836. g.strokePath (tick, PathStrokeType (2.5f), trans);
  48837. }
  48838. }
  48839. void LookAndFeel::drawToggleButton (Graphics& g,
  48840. ToggleButton& button,
  48841. bool isMouseOverButton,
  48842. bool isButtonDown)
  48843. {
  48844. if (button.hasKeyboardFocus (true))
  48845. {
  48846. g.setColour (button.findColour (TextEditor::focusedOutlineColourId));
  48847. g.drawRect (0, 0, button.getWidth(), button.getHeight());
  48848. }
  48849. const int tickWidth = jmin (20, button.getHeight() - 4);
  48850. drawTickBox (g, button, 4, (button.getHeight() - tickWidth) / 2,
  48851. tickWidth, tickWidth,
  48852. button.getToggleState(),
  48853. button.isEnabled(),
  48854. isMouseOverButton,
  48855. isButtonDown);
  48856. g.setColour (button.findColour (ToggleButton::textColourId));
  48857. g.setFont (jmin (15.0f, button.getHeight() * 0.6f));
  48858. if (! button.isEnabled())
  48859. g.setOpacity (0.5f);
  48860. const int textX = tickWidth + 5;
  48861. g.drawFittedText (button.getButtonText(),
  48862. textX, 4,
  48863. button.getWidth() - textX - 2, button.getHeight() - 8,
  48864. Justification::centredLeft, 10);
  48865. }
  48866. void LookAndFeel::changeToggleButtonWidthToFitText (ToggleButton& button)
  48867. {
  48868. Font font (jmin (15.0f, button.getHeight() * 0.6f));
  48869. const int tickWidth = jmin (24, button.getHeight());
  48870. button.setSize (font.getStringWidth (button.getButtonText()) + tickWidth + 8,
  48871. button.getHeight());
  48872. }
  48873. AlertWindow* LookAndFeel::createAlertWindow (const String& title,
  48874. const String& message,
  48875. const String& button1,
  48876. const String& button2,
  48877. const String& button3,
  48878. AlertWindow::AlertIconType iconType,
  48879. int numButtons,
  48880. Component* associatedComponent)
  48881. {
  48882. AlertWindow* aw = new AlertWindow (title, message, iconType, associatedComponent);
  48883. if (numButtons == 1)
  48884. {
  48885. aw->addButton (button1, 0,
  48886. KeyPress (KeyPress::escapeKey, 0, 0),
  48887. KeyPress (KeyPress::returnKey, 0, 0));
  48888. }
  48889. else
  48890. {
  48891. const KeyPress button1ShortCut (CharacterFunctions::toLowerCase (button1[0]), 0, 0);
  48892. KeyPress button2ShortCut (CharacterFunctions::toLowerCase (button2[0]), 0, 0);
  48893. if (button1ShortCut == button2ShortCut)
  48894. button2ShortCut = KeyPress();
  48895. if (numButtons == 2)
  48896. {
  48897. aw->addButton (button1, 1, KeyPress (KeyPress::returnKey, 0, 0), button1ShortCut);
  48898. aw->addButton (button2, 0, KeyPress (KeyPress::escapeKey, 0, 0), button2ShortCut);
  48899. }
  48900. else if (numButtons == 3)
  48901. {
  48902. aw->addButton (button1, 1, button1ShortCut);
  48903. aw->addButton (button2, 2, button2ShortCut);
  48904. aw->addButton (button3, 0, KeyPress (KeyPress::escapeKey, 0, 0));
  48905. }
  48906. }
  48907. return aw;
  48908. }
  48909. void LookAndFeel::drawAlertBox (Graphics& g,
  48910. AlertWindow& alert,
  48911. const Rectangle& textArea,
  48912. TextLayout& textLayout)
  48913. {
  48914. g.fillAll (alert.findColour (AlertWindow::backgroundColourId));
  48915. int iconSpaceUsed = 0;
  48916. Justification alignment (Justification::horizontallyCentred);
  48917. const int iconWidth = 80;
  48918. int iconSize = jmin (iconWidth + 50, alert.getHeight() + 20);
  48919. if (alert.containsAnyExtraComponents() || alert.getNumButtons() > 2)
  48920. iconSize = jmin (iconSize, textArea.getHeight() + 50);
  48921. const Rectangle iconRect (iconSize / -10, iconSize / -10,
  48922. iconSize, iconSize);
  48923. if (alert.getAlertType() != AlertWindow::NoIcon)
  48924. {
  48925. Path icon;
  48926. uint32 colour;
  48927. char character;
  48928. if (alert.getAlertType() == AlertWindow::WarningIcon)
  48929. {
  48930. colour = 0x55ff5555;
  48931. character = '!';
  48932. icon.addTriangle (iconRect.getX() + iconRect.getWidth() * 0.5f, (float) iconRect.getY(),
  48933. (float) iconRect.getRight(), (float) iconRect.getBottom(),
  48934. (float) iconRect.getX(), (float) iconRect.getBottom());
  48935. icon = icon.createPathWithRoundedCorners (5.0f);
  48936. }
  48937. else
  48938. {
  48939. colour = alert.getAlertType() == AlertWindow::InfoIcon ? 0x605555ff : 0x40b69900;
  48940. character = alert.getAlertType() == AlertWindow::InfoIcon ? 'i' : '?';
  48941. icon.addEllipse ((float) iconRect.getX(), (float) iconRect.getY(),
  48942. (float) iconRect.getWidth(), (float) iconRect.getHeight());
  48943. }
  48944. GlyphArrangement ga;
  48945. ga.addFittedText (Font (iconRect.getHeight() * 0.9f, Font::bold),
  48946. String::charToString (character),
  48947. (float) iconRect.getX(), (float) iconRect.getY(),
  48948. (float) iconRect.getWidth(), (float) iconRect.getHeight(),
  48949. Justification::centred, false);
  48950. ga.createPath (icon);
  48951. icon.setUsingNonZeroWinding (false);
  48952. g.setColour (Colour (colour));
  48953. g.fillPath (icon);
  48954. iconSpaceUsed = iconWidth;
  48955. alignment = Justification::left;
  48956. }
  48957. g.setColour (alert.findColour (AlertWindow::textColourId));
  48958. textLayout.drawWithin (g,
  48959. textArea.getX() + iconSpaceUsed, textArea.getY(),
  48960. textArea.getWidth() - iconSpaceUsed, textArea.getHeight(),
  48961. alignment.getFlags() | Justification::top);
  48962. g.setColour (alert.findColour (AlertWindow::outlineColourId));
  48963. g.drawRect (0, 0, alert.getWidth(), alert.getHeight());
  48964. }
  48965. int LookAndFeel::getAlertBoxWindowFlags()
  48966. {
  48967. return ComponentPeer::windowAppearsOnTaskbar
  48968. | ComponentPeer::windowHasDropShadow;
  48969. }
  48970. int LookAndFeel::getAlertWindowButtonHeight()
  48971. {
  48972. return 28;
  48973. }
  48974. const Font LookAndFeel::getAlertWindowFont()
  48975. {
  48976. return Font (12.0f);
  48977. }
  48978. void LookAndFeel::drawProgressBar (Graphics& g, ProgressBar& progressBar,
  48979. int width, int height,
  48980. double progress, const String& textToShow)
  48981. {
  48982. const Colour background (progressBar.findColour (ProgressBar::backgroundColourId));
  48983. const Colour foreground (progressBar.findColour (ProgressBar::foregroundColourId));
  48984. g.fillAll (background);
  48985. if (progress >= 0.0f && progress < 1.0f)
  48986. {
  48987. drawGlassLozenge (g, 1.0f, 1.0f,
  48988. (float) jlimit (0.0, width - 2.0, progress * (width - 2.0)),
  48989. (float) (height - 2),
  48990. foreground,
  48991. 0.5f, 0.0f,
  48992. true, true, true, true);
  48993. }
  48994. else
  48995. {
  48996. // spinning bar..
  48997. g.setColour (foreground);
  48998. const int stripeWidth = height * 2;
  48999. const int position = (Time::getMillisecondCounter() / 15) % stripeWidth;
  49000. Path p;
  49001. for (float x = (float) (- position); x < width + stripeWidth; x += stripeWidth)
  49002. p.addQuadrilateral (x, 0.0f,
  49003. x + stripeWidth * 0.5f, 0.0f,
  49004. x, (float) height,
  49005. x - stripeWidth * 0.5f, (float) height);
  49006. Image im (Image::ARGB, width, height, true);
  49007. {
  49008. Graphics g (im);
  49009. drawGlassLozenge (g, 1.0f, 1.0f,
  49010. (float) (width - 2),
  49011. (float) (height - 2),
  49012. foreground,
  49013. 0.5f, 0.0f,
  49014. true, true, true, true);
  49015. }
  49016. ImageBrush ib (&im, 0, 0, 0.85f);
  49017. g.setBrush (&ib);
  49018. g.fillPath (p);
  49019. }
  49020. if (textToShow.isNotEmpty())
  49021. {
  49022. g.setColour (Colour::contrasting (background, foreground));
  49023. g.setFont (height * 0.6f);
  49024. g.drawText (textToShow, 0, 0, width, height, Justification::centred, false);
  49025. }
  49026. }
  49027. void LookAndFeel::drawSpinningWaitAnimation (Graphics& g, int x, int y, int w, int h)
  49028. {
  49029. const float radius = jmin (w, h) * 0.4f;
  49030. const float thickness = radius * 0.15f;
  49031. Path p;
  49032. p.addRoundedRectangle (radius * 0.4f, thickness * -0.5f,
  49033. radius * 0.6f, thickness,
  49034. thickness * 0.5f);
  49035. const float cx = x + w * 0.5f;
  49036. const float cy = y + h * 0.5f;
  49037. const uint32 animationIndex = (Time::getMillisecondCounter() / (1000 / 10)) % 12;
  49038. const Colour col (g.getCurrentColour());
  49039. for (int i = 0; i < 12; ++i)
  49040. {
  49041. const int n = (i + 12 - animationIndex) % 12;
  49042. g.setColour (col.withMultipliedAlpha ((n + 1) / 12.0f));
  49043. g.fillPath (p, AffineTransform::rotation (i * (float_Pi / 6.0f))
  49044. .translated (cx, cy));
  49045. }
  49046. }
  49047. void LookAndFeel::drawScrollbarButton (Graphics& g,
  49048. ScrollBar& scrollbar,
  49049. int width, int height,
  49050. int buttonDirection,
  49051. bool /*isScrollbarVertical*/,
  49052. bool /*isMouseOverButton*/,
  49053. bool isButtonDown)
  49054. {
  49055. Path p;
  49056. if (buttonDirection == 0)
  49057. p.addTriangle (width * 0.5f, height * 0.2f,
  49058. width * 0.1f, height * 0.7f,
  49059. width * 0.9f, height * 0.7f);
  49060. else if (buttonDirection == 1)
  49061. p.addTriangle (width * 0.8f, height * 0.5f,
  49062. width * 0.3f, height * 0.1f,
  49063. width * 0.3f, height * 0.9f);
  49064. else if (buttonDirection == 2)
  49065. p.addTriangle (width * 0.5f, height * 0.8f,
  49066. width * 0.1f, height * 0.3f,
  49067. width * 0.9f, height * 0.3f);
  49068. else if (buttonDirection == 3)
  49069. p.addTriangle (width * 0.2f, height * 0.5f,
  49070. width * 0.7f, height * 0.1f,
  49071. width * 0.7f, height * 0.9f);
  49072. if (isButtonDown)
  49073. g.setColour (scrollbar.findColour (ScrollBar::thumbColourId).contrasting (0.2f));
  49074. else
  49075. g.setColour (scrollbar.findColour (ScrollBar::thumbColourId));
  49076. g.fillPath (p);
  49077. g.setColour (Colour (0x80000000));
  49078. g.strokePath (p, PathStrokeType (0.5f));
  49079. }
  49080. void LookAndFeel::drawScrollbar (Graphics& g,
  49081. ScrollBar& scrollbar,
  49082. int x, int y,
  49083. int width, int height,
  49084. bool isScrollbarVertical,
  49085. int thumbStartPosition,
  49086. int thumbSize,
  49087. bool /*isMouseOver*/,
  49088. bool /*isMouseDown*/)
  49089. {
  49090. g.fillAll (scrollbar.findColour (ScrollBar::backgroundColourId));
  49091. Path slotPath, thumbPath;
  49092. const float slotIndent = jmin (width, height) > 15 ? 1.0f : 0.0f;
  49093. const float slotIndentx2 = slotIndent * 2.0f;
  49094. const float thumbIndent = slotIndent + 1.0f;
  49095. const float thumbIndentx2 = thumbIndent * 2.0f;
  49096. float gx1 = 0.0f, gy1 = 0.0f, gx2 = 0.0f, gy2 = 0.0f;
  49097. if (isScrollbarVertical)
  49098. {
  49099. slotPath.addRoundedRectangle (x + slotIndent,
  49100. y + slotIndent,
  49101. width - slotIndentx2,
  49102. height - slotIndentx2,
  49103. (width - slotIndentx2) * 0.5f);
  49104. if (thumbSize > 0)
  49105. thumbPath.addRoundedRectangle (x + thumbIndent,
  49106. thumbStartPosition + thumbIndent,
  49107. width - thumbIndentx2,
  49108. thumbSize - thumbIndentx2,
  49109. (width - thumbIndentx2) * 0.5f);
  49110. gx1 = (float) x;
  49111. gx2 = x + width * 0.7f;
  49112. }
  49113. else
  49114. {
  49115. slotPath.addRoundedRectangle (x + slotIndent,
  49116. y + slotIndent,
  49117. width - slotIndentx2,
  49118. height - slotIndentx2,
  49119. (height - slotIndentx2) * 0.5f);
  49120. if (thumbSize > 0)
  49121. thumbPath.addRoundedRectangle (thumbStartPosition + thumbIndent,
  49122. y + thumbIndent,
  49123. thumbSize - thumbIndentx2,
  49124. height - thumbIndentx2,
  49125. (height - thumbIndentx2) * 0.5f);
  49126. gy1 = (float) y;
  49127. gy2 = y + height * 0.7f;
  49128. }
  49129. const Colour thumbColour (scrollbar.findColour (ScrollBar::trackColourId));
  49130. GradientBrush gb (thumbColour.overlaidWith (Colour (0x44000000)),
  49131. gx1, gy1,
  49132. thumbColour.overlaidWith (Colour (0x19000000)),
  49133. gx2, gy2, false);
  49134. g.setBrush (&gb);
  49135. g.fillPath (slotPath);
  49136. if (isScrollbarVertical)
  49137. {
  49138. gx1 = x + width * 0.6f;
  49139. gx2 = (float) x + width;
  49140. }
  49141. else
  49142. {
  49143. gy1 = y + height * 0.6f;
  49144. gy2 = (float) y + height;
  49145. }
  49146. GradientBrush gb2 (Colours::transparentBlack,
  49147. gx1, gy1,
  49148. Colour (0x19000000),
  49149. gx2, gy2, false);
  49150. g.setBrush (&gb2);
  49151. g.fillPath (slotPath);
  49152. g.setColour (thumbColour);
  49153. g.fillPath (thumbPath);
  49154. GradientBrush gb3 (Colour (0x10000000),
  49155. gx1, gy1,
  49156. Colours::transparentBlack,
  49157. gx2, gy2, false);
  49158. g.saveState();
  49159. g.setBrush (&gb3);
  49160. if (isScrollbarVertical)
  49161. g.reduceClipRegion (x + width / 2, y, width, height);
  49162. else
  49163. g.reduceClipRegion (x, y + height / 2, width, height);
  49164. g.fillPath (thumbPath);
  49165. g.restoreState();
  49166. g.setColour (Colour (0x4c000000));
  49167. g.strokePath (thumbPath, PathStrokeType (0.4f));
  49168. }
  49169. ImageEffectFilter* LookAndFeel::getScrollbarEffect()
  49170. {
  49171. return 0;
  49172. }
  49173. int LookAndFeel::getMinimumScrollbarThumbSize (ScrollBar& scrollbar)
  49174. {
  49175. return jmin (scrollbar.getWidth(), scrollbar.getHeight()) * 2;
  49176. }
  49177. int LookAndFeel::getDefaultScrollbarWidth()
  49178. {
  49179. return 18;
  49180. }
  49181. int LookAndFeel::getScrollbarButtonSize (ScrollBar& scrollbar)
  49182. {
  49183. return 2 + (scrollbar.isVertical() ? scrollbar.getWidth()
  49184. : scrollbar.getHeight());
  49185. }
  49186. const Path LookAndFeel::getTickShape (const float height)
  49187. {
  49188. static const unsigned char tickShapeData[] =
  49189. {
  49190. 109,0,224,168,68,0,0,119,67,108,0,224,172,68,0,128,146,67,113,0,192,148,68,0,0,219,67,0,96,110,68,0,224,56,68,113,0,64,51,68,0,32,130,68,0,64,20,68,0,224,
  49191. 162,68,108,0,128,3,68,0,128,168,68,113,0,128,221,67,0,192,175,68,0,0,207,67,0,32,179,68,113,0,0,201,67,0,224,173,68,0,0,181,67,0,224,161,68,108,0,128,168,67,
  49192. 0,128,154,68,113,0,128,141,67,0,192,138,68,0,128,108,67,0,64,131,68,113,0,0,62,67,0,128,119,68,0,0,5,67,0,128,114,68,113,0,0,102,67,0,192,88,68,0,128,155,
  49193. 67,0,192,88,68,113,0,0,190,67,0,192,88,68,0,128,232,67,0,224,131,68,108,0,128,246,67,0,192,139,68,113,0,64,33,68,0,128,87,68,0,0,93,68,0,224,26,68,113,0,
  49194. 96,140,68,0,128,188,67,0,224,168,68,0,0,119,67,99,101
  49195. };
  49196. Path p;
  49197. p.loadPathFromData (tickShapeData, sizeof (tickShapeData));
  49198. p.scaleToFit (0, 0, height * 2.0f, height, true);
  49199. return p;
  49200. }
  49201. const Path LookAndFeel::getCrossShape (const float height)
  49202. {
  49203. static const unsigned char crossShapeData[] =
  49204. {
  49205. 109,0,0,17,68,0,96,145,68,108,0,192,13,68,0,192,147,68,113,0,0,213,67,0,64,174,68,0,0,168,67,0,64,174,68,113,0,0,104,67,0,64,174,68,0,0,5,67,0,64,
  49206. 153,68,113,0,0,18,67,0,64,153,68,0,0,24,67,0,64,153,68,113,0,0,135,67,0,64,153,68,0,128,207,67,0,224,130,68,108,0,0,220,67,0,0,126,68,108,0,0,204,67,
  49207. 0,128,117,68,113,0,0,138,67,0,64,82,68,0,0,138,67,0,192,57,68,113,0,0,138,67,0,192,37,68,0,128,210,67,0,64,10,68,113,0,128,220,67,0,64,45,68,0,0,8,
  49208. 68,0,128,78,68,108,0,192,14,68,0,0,87,68,108,0,64,20,68,0,0,80,68,113,0,192,57,68,0,0,32,68,0,128,88,68,0,0,32,68,113,0,64,112,68,0,0,32,68,0,
  49209. 128,124,68,0,64,68,68,113,0,0,121,68,0,192,67,68,0,128,119,68,0,192,67,68,113,0,192,108,68,0,192,67,68,0,32,89,68,0,96,82,68,113,0,128,69,68,0,0,97,68,
  49210. 0,0,56,68,0,64,115,68,108,0,64,49,68,0,128,124,68,108,0,192,55,68,0,96,129,68,113,0,0,92,68,0,224,146,68,0,192,129,68,0,224,146,68,113,0,64,110,68,0,64,
  49211. 168,68,0,64,87,68,0,64,168,68,113,0,128,66,68,0,64,168,68,0,64,27,68,0,32,150,68,99,101
  49212. };
  49213. Path p;
  49214. p.loadPathFromData (crossShapeData, sizeof (crossShapeData));
  49215. p.scaleToFit (0, 0, height * 2.0f, height, true);
  49216. return p;
  49217. }
  49218. void LookAndFeel::drawTreeviewPlusMinusBox (Graphics& g, int x, int y, int w, int h, bool isPlus, bool /*isMouseOver*/)
  49219. {
  49220. const int boxSize = ((jmin (16, w, h) << 1) / 3) | 1;
  49221. x += (w - boxSize) >> 1;
  49222. y += (h - boxSize) >> 1;
  49223. w = boxSize;
  49224. h = boxSize;
  49225. g.setColour (Colour (0xe5ffffff));
  49226. g.fillRect (x, y, w, h);
  49227. g.setColour (Colour (0x80000000));
  49228. g.drawRect (x, y, w, h);
  49229. const float size = boxSize / 2 + 1.0f;
  49230. const float centre = (float) (boxSize / 2);
  49231. g.fillRect (x + (w - size) * 0.5f, y + centre, size, 1.0f);
  49232. if (isPlus)
  49233. g.fillRect (x + centre, y + (h - size) * 0.5f, 1.0f, size);
  49234. }
  49235. void LookAndFeel::drawBubble (Graphics& g,
  49236. float tipX, float tipY,
  49237. float boxX, float boxY,
  49238. float boxW, float boxH)
  49239. {
  49240. int side = 0;
  49241. if (tipX < boxX)
  49242. side = 1;
  49243. else if (tipX > boxX + boxW)
  49244. side = 3;
  49245. else if (tipY > boxY + boxH)
  49246. side = 2;
  49247. const float indent = 2.0f;
  49248. Path p;
  49249. p.addBubble (boxX + indent,
  49250. boxY + indent,
  49251. boxW - indent * 2.0f,
  49252. boxH - indent * 2.0f,
  49253. 5.0f,
  49254. tipX, tipY,
  49255. side,
  49256. 0.5f,
  49257. jmin (15.0f, boxW * 0.3f, boxH * 0.3f));
  49258. //xxx need to take comp as param for colour
  49259. g.setColour (findColour (TooltipWindow::backgroundColourId).withAlpha (0.9f));
  49260. g.fillPath (p);
  49261. //xxx as above
  49262. g.setColour (findColour (TooltipWindow::textColourId).withAlpha (0.4f));
  49263. g.strokePath (p, PathStrokeType (1.33f));
  49264. }
  49265. const Font LookAndFeel::getPopupMenuFont()
  49266. {
  49267. return Font (17.0f);
  49268. }
  49269. void LookAndFeel::getIdealPopupMenuItemSize (const String& text,
  49270. const bool isSeparator,
  49271. int standardMenuItemHeight,
  49272. int& idealWidth,
  49273. int& idealHeight)
  49274. {
  49275. if (isSeparator)
  49276. {
  49277. idealWidth = 50;
  49278. idealHeight = standardMenuItemHeight > 0 ? standardMenuItemHeight / 2 : 10;
  49279. }
  49280. else
  49281. {
  49282. Font font (getPopupMenuFont());
  49283. if (standardMenuItemHeight > 0 && font.getHeight() > standardMenuItemHeight / 1.3f)
  49284. font.setHeight (standardMenuItemHeight / 1.3f);
  49285. idealHeight = standardMenuItemHeight > 0 ? standardMenuItemHeight : roundFloatToInt (font.getHeight() * 1.3f);
  49286. idealWidth = font.getStringWidth (text) + idealHeight * 2;
  49287. }
  49288. }
  49289. void LookAndFeel::drawPopupMenuBackground (Graphics& g, int width, int height)
  49290. {
  49291. const Colour background (findColour (PopupMenu::backgroundColourId));
  49292. g.fillAll (background);
  49293. g.setColour (background.overlaidWith (Colour (0x2badd8e6)));
  49294. for (int i = 0; i < height; i += 3)
  49295. g.fillRect (0, i, width, 1);
  49296. #if ! JUCE_MAC
  49297. g.setColour (findColour (PopupMenu::textColourId).withAlpha (0.6f));
  49298. g.drawRect (0, 0, width, height);
  49299. #endif
  49300. }
  49301. void LookAndFeel::drawPopupMenuUpDownArrow (Graphics& g,
  49302. int width, int height,
  49303. bool isScrollUpArrow)
  49304. {
  49305. const Colour background (findColour (PopupMenu::backgroundColourId));
  49306. GradientBrush gb (background,
  49307. 0.0f, height * 0.5f,
  49308. background.withAlpha (0.0f),
  49309. 0.0f, isScrollUpArrow ? ((float) height) : 0.0f,
  49310. false);
  49311. g.setBrush (&gb);
  49312. g.fillRect (1, 1, width - 2, height - 2);
  49313. const float hw = width * 0.5f;
  49314. const float arrowW = height * 0.3f;
  49315. const float y1 = height * (isScrollUpArrow ? 0.6f : 0.3f);
  49316. const float y2 = height * (isScrollUpArrow ? 0.3f : 0.6f);
  49317. Path p;
  49318. p.addTriangle (hw - arrowW, y1,
  49319. hw + arrowW, y1,
  49320. hw, y2);
  49321. g.setColour (findColour (PopupMenu::textColourId).withAlpha (0.5f));
  49322. g.fillPath (p);
  49323. }
  49324. void LookAndFeel::drawPopupMenuItem (Graphics& g,
  49325. int width, int height,
  49326. const bool isSeparator,
  49327. const bool isActive,
  49328. const bool isHighlighted,
  49329. const bool isTicked,
  49330. const bool hasSubMenu,
  49331. const String& text,
  49332. const String& shortcutKeyText,
  49333. Image* image,
  49334. const Colour* const textColourToUse)
  49335. {
  49336. const float halfH = height * 0.5f;
  49337. if (isSeparator)
  49338. {
  49339. const float separatorIndent = 5.5f;
  49340. g.setColour (Colour (0x33000000));
  49341. g.drawLine (separatorIndent, halfH, width - separatorIndent, halfH);
  49342. g.setColour (Colour (0x66ffffff));
  49343. g.drawLine (separatorIndent, halfH + 1.0f, width - separatorIndent, halfH + 1.0f);
  49344. }
  49345. else
  49346. {
  49347. Colour textColour (findColour (PopupMenu::textColourId));
  49348. if (textColourToUse != 0)
  49349. textColour = *textColourToUse;
  49350. if (isHighlighted)
  49351. {
  49352. g.setColour (findColour (PopupMenu::highlightedBackgroundColourId));
  49353. g.fillRect (1, 1, width - 2, height - 2);
  49354. g.setColour (findColour (PopupMenu::highlightedTextColourId));
  49355. }
  49356. else
  49357. {
  49358. g.setColour (textColour);
  49359. }
  49360. if (! isActive)
  49361. g.setOpacity (0.3f);
  49362. Font font (getPopupMenuFont());
  49363. if (font.getHeight() > height / 1.3f)
  49364. font.setHeight (height / 1.3f);
  49365. g.setFont (font);
  49366. const int leftBorder = (height * 5) / 4;
  49367. const int rightBorder = 4;
  49368. if (image != 0)
  49369. {
  49370. g.drawImageWithin (image,
  49371. 2, 1, leftBorder - 4, height - 2,
  49372. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize, false);
  49373. }
  49374. else if (isTicked)
  49375. {
  49376. const Path tick (getTickShape (1.0f));
  49377. const float th = font.getAscent();
  49378. const float ty = halfH - th * 0.5f;
  49379. g.fillPath (tick, tick.getTransformToScaleToFit (2.0f, ty, (float) (leftBorder - 4),
  49380. th, true));
  49381. }
  49382. g.drawFittedText (text,
  49383. leftBorder, 0,
  49384. width - (leftBorder + rightBorder), height,
  49385. Justification::centredLeft, 1);
  49386. if (shortcutKeyText.isNotEmpty())
  49387. {
  49388. Font f2 (g.getCurrentFont());
  49389. f2.setHeight (f2.getHeight() * 0.75f);
  49390. f2.setHorizontalScale (0.95f);
  49391. g.setFont (f2);
  49392. g.drawText (shortcutKeyText,
  49393. leftBorder,
  49394. 0,
  49395. width - (leftBorder + rightBorder + 4),
  49396. height,
  49397. Justification::centredRight,
  49398. true);
  49399. }
  49400. if (hasSubMenu)
  49401. {
  49402. const float arrowH = 0.6f * getPopupMenuFont().getAscent();
  49403. const float x = width - height * 0.6f;
  49404. Path p;
  49405. p.addTriangle (x, halfH - arrowH * 0.5f,
  49406. x, halfH + arrowH * 0.5f,
  49407. x + arrowH * 0.6f, halfH);
  49408. g.fillPath (p);
  49409. }
  49410. }
  49411. }
  49412. int LookAndFeel::getMenuWindowFlags()
  49413. {
  49414. return ComponentPeer::windowHasDropShadow;
  49415. }
  49416. void LookAndFeel::drawMenuBarBackground (Graphics& g, int width, int height,
  49417. bool, MenuBarComponent& menuBar)
  49418. {
  49419. const Colour baseColour (createBaseColour (menuBar.findColour (PopupMenu::backgroundColourId), false, false, false));
  49420. if (menuBar.isEnabled())
  49421. {
  49422. drawShinyButtonShape (g,
  49423. -4.0f, 0.0f,
  49424. width + 8.0f, (float) height,
  49425. 0.0f,
  49426. baseColour,
  49427. 0.4f,
  49428. true, true, true, true);
  49429. }
  49430. else
  49431. {
  49432. g.fillAll (baseColour);
  49433. }
  49434. }
  49435. const Font LookAndFeel::getMenuBarFont (MenuBarComponent& menuBar, int /*itemIndex*/, const String& /*itemText*/)
  49436. {
  49437. return Font (menuBar.getHeight() * 0.7f);
  49438. }
  49439. int LookAndFeel::getMenuBarItemWidth (MenuBarComponent& menuBar, int itemIndex, const String& itemText)
  49440. {
  49441. return getMenuBarFont (menuBar, itemIndex, itemText)
  49442. .getStringWidth (itemText) + menuBar.getHeight();
  49443. }
  49444. void LookAndFeel::drawMenuBarItem (Graphics& g,
  49445. int width, int height,
  49446. int itemIndex,
  49447. const String& itemText,
  49448. bool isMouseOverItem,
  49449. bool isMenuOpen,
  49450. bool /*isMouseOverBar*/,
  49451. MenuBarComponent& menuBar)
  49452. {
  49453. if (! menuBar.isEnabled())
  49454. {
  49455. g.setColour (menuBar.findColour (PopupMenu::textColourId)
  49456. .withMultipliedAlpha (0.5f));
  49457. }
  49458. else if (isMenuOpen || isMouseOverItem)
  49459. {
  49460. g.fillAll (menuBar.findColour (PopupMenu::highlightedBackgroundColourId));
  49461. g.setColour (menuBar.findColour (PopupMenu::highlightedTextColourId));
  49462. }
  49463. else
  49464. {
  49465. g.setColour (menuBar.findColour (PopupMenu::textColourId));
  49466. }
  49467. g.setFont (getMenuBarFont (menuBar, itemIndex, itemText));
  49468. g.drawFittedText (itemText, 0, 0, width, height, Justification::centred, 1);
  49469. }
  49470. void LookAndFeel::fillTextEditorBackground (Graphics& g, int /*width*/, int /*height*/,
  49471. TextEditor& textEditor)
  49472. {
  49473. g.fillAll (textEditor.findColour (TextEditor::backgroundColourId));
  49474. }
  49475. void LookAndFeel::drawTextEditorOutline (Graphics& g, int width, int height, TextEditor& textEditor)
  49476. {
  49477. if (textEditor.isEnabled())
  49478. {
  49479. if (textEditor.hasKeyboardFocus (true) && ! textEditor.isReadOnly())
  49480. {
  49481. const int border = 2;
  49482. g.setColour (textEditor.findColour (TextEditor::focusedOutlineColourId));
  49483. g.drawRect (0, 0, width, height, border);
  49484. g.setOpacity (1.0f);
  49485. const Colour shadowColour (textEditor.findColour (TextEditor::shadowColourId).withMultipliedAlpha (0.75f));
  49486. g.drawBevel (0, 0, width, height + 2, border + 2, shadowColour, shadowColour);
  49487. }
  49488. else
  49489. {
  49490. g.setColour (textEditor.findColour (TextEditor::outlineColourId));
  49491. g.drawRect (0, 0, width, height);
  49492. g.setOpacity (1.0f);
  49493. const Colour shadowColour (textEditor.findColour (TextEditor::shadowColourId));
  49494. g.drawBevel (0, 0, width, height + 2, 3, shadowColour, shadowColour);
  49495. }
  49496. }
  49497. }
  49498. void LookAndFeel::drawComboBox (Graphics& g, int width, int height,
  49499. const bool isButtonDown,
  49500. int buttonX, int buttonY,
  49501. int buttonW, int buttonH,
  49502. ComboBox& box)
  49503. {
  49504. g.fillAll (box.findColour (ComboBox::backgroundColourId));
  49505. if (box.isEnabled() && box.hasKeyboardFocus (false))
  49506. {
  49507. g.setColour (box.findColour (TextButton::buttonColourId));
  49508. g.drawRect (0, 0, width, height, 2);
  49509. }
  49510. else
  49511. {
  49512. g.setColour (box.findColour (ComboBox::outlineColourId));
  49513. g.drawRect (0, 0, width, height);
  49514. }
  49515. const float outlineThickness = box.isEnabled() ? (isButtonDown ? 1.2f : 0.5f) : 0.3f;
  49516. const Colour baseColour (createBaseColour (box.findColour (ComboBox::buttonColourId),
  49517. box.hasKeyboardFocus (true),
  49518. false, isButtonDown)
  49519. .withMultipliedAlpha (box.isEnabled() ? 1.0f : 0.5f));
  49520. drawGlassLozenge (g,
  49521. buttonX + outlineThickness, buttonY + outlineThickness,
  49522. buttonW - outlineThickness * 2.0f, buttonH - outlineThickness * 2.0f,
  49523. baseColour, outlineThickness, -1.0f,
  49524. true, true, true, true);
  49525. if (box.isEnabled())
  49526. {
  49527. const float arrowX = 0.3f;
  49528. const float arrowH = 0.2f;
  49529. Path p;
  49530. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.45f - arrowH),
  49531. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.45f,
  49532. buttonX + buttonW * arrowX, buttonY + buttonH * 0.45f);
  49533. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.55f + arrowH),
  49534. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.55f,
  49535. buttonX + buttonW * arrowX, buttonY + buttonH * 0.55f);
  49536. g.setColour (box.findColour (ComboBox::arrowColourId));
  49537. g.fillPath (p);
  49538. }
  49539. }
  49540. const Font LookAndFeel::getComboBoxFont (ComboBox& box)
  49541. {
  49542. return Font (jmin (15.0f, box.getHeight() * 0.85f));
  49543. }
  49544. Label* LookAndFeel::createComboBoxTextBox (ComboBox&)
  49545. {
  49546. return new Label (String::empty, String::empty);
  49547. }
  49548. void LookAndFeel::positionComboBoxText (ComboBox& box, Label& label)
  49549. {
  49550. label.setBounds (1, 1,
  49551. box.getWidth() + 3 - box.getHeight(),
  49552. box.getHeight() - 2);
  49553. label.setFont (getComboBoxFont (box));
  49554. }
  49555. void LookAndFeel::drawLabel (Graphics& g, Label& label)
  49556. {
  49557. g.fillAll (label.findColour (Label::backgroundColourId));
  49558. if (! label.isBeingEdited())
  49559. {
  49560. const float alpha = label.isEnabled() ? 1.0f : 0.5f;
  49561. g.setColour (label.findColour (Label::textColourId).withMultipliedAlpha (alpha));
  49562. g.setFont (label.getFont());
  49563. g.drawFittedText (label.getText(),
  49564. label.getHorizontalBorderSize(),
  49565. label.getVerticalBorderSize(),
  49566. label.getWidth() - 2 * label.getHorizontalBorderSize(),
  49567. label.getHeight() - 2 * label.getVerticalBorderSize(),
  49568. label.getJustificationType(),
  49569. jmax (1, (int) (label.getHeight() / label.getFont().getHeight())),
  49570. label.getMinimumHorizontalScale());
  49571. g.setColour (label.findColour (Label::outlineColourId).withMultipliedAlpha (alpha));
  49572. g.drawRect (0, 0, label.getWidth(), label.getHeight());
  49573. }
  49574. else if (label.isEnabled())
  49575. {
  49576. g.setColour (label.findColour (Label::outlineColourId));
  49577. g.drawRect (0, 0, label.getWidth(), label.getHeight());
  49578. }
  49579. }
  49580. void LookAndFeel::drawLinearSliderBackground (Graphics& g,
  49581. int x, int y,
  49582. int width, int height,
  49583. float /*sliderPos*/,
  49584. float /*minSliderPos*/,
  49585. float /*maxSliderPos*/,
  49586. const Slider::SliderStyle /*style*/,
  49587. Slider& slider)
  49588. {
  49589. const float sliderRadius = (float) (getSliderThumbRadius (slider) - 2);
  49590. const Colour trackColour (slider.findColour (Slider::trackColourId));
  49591. const Colour gradCol1 (trackColour.overlaidWith (Colours::black.withAlpha (slider.isEnabled() ? 0.25f : 0.13f)));
  49592. const Colour gradCol2 (trackColour.overlaidWith (Colour (0x14000000)));
  49593. Path indent;
  49594. if (slider.isHorizontal())
  49595. {
  49596. const float iy = y + height * 0.5f - sliderRadius * 0.5f;
  49597. const float ih = sliderRadius;
  49598. GradientBrush gb (gradCol1, 0.0f, iy,
  49599. gradCol2, 0.0f, iy + ih, false);
  49600. g.setBrush (&gb);
  49601. indent.addRoundedRectangle (x - sliderRadius * 0.5f, iy,
  49602. width + sliderRadius, ih,
  49603. 5.0f);
  49604. g.fillPath (indent);
  49605. }
  49606. else
  49607. {
  49608. const float ix = x + width * 0.5f - sliderRadius * 0.5f;
  49609. const float iw = sliderRadius;
  49610. GradientBrush gb (gradCol1, ix, 0.0f,
  49611. gradCol2, ix + iw, 0.0f, false);
  49612. g.setBrush (&gb);
  49613. indent.addRoundedRectangle (ix, y - sliderRadius * 0.5f,
  49614. iw, height + sliderRadius,
  49615. 5.0f);
  49616. g.fillPath (indent);
  49617. }
  49618. g.setColour (Colour (0x4c000000));
  49619. g.strokePath (indent, PathStrokeType (0.5f));
  49620. }
  49621. void LookAndFeel::drawLinearSliderThumb (Graphics& g,
  49622. int x, int y,
  49623. int width, int height,
  49624. float sliderPos,
  49625. float minSliderPos,
  49626. float maxSliderPos,
  49627. const Slider::SliderStyle style,
  49628. Slider& slider)
  49629. {
  49630. const float sliderRadius = (float) (getSliderThumbRadius (slider) - 2);
  49631. Colour knobColour (createBaseColour (slider.findColour (Slider::thumbColourId),
  49632. slider.hasKeyboardFocus (false) && slider.isEnabled(),
  49633. slider.isMouseOverOrDragging() && slider.isEnabled(),
  49634. slider.isMouseButtonDown() && slider.isEnabled()));
  49635. const float outlineThickness = slider.isEnabled() ? 0.8f : 0.3f;
  49636. if (style == Slider::LinearHorizontal || style == Slider::LinearVertical)
  49637. {
  49638. float kx, ky;
  49639. if (style == Slider::LinearVertical)
  49640. {
  49641. kx = x + width * 0.5f;
  49642. ky = sliderPos;
  49643. }
  49644. else
  49645. {
  49646. kx = sliderPos;
  49647. ky = y + height * 0.5f;
  49648. }
  49649. drawGlassSphere (g,
  49650. kx - sliderRadius,
  49651. ky - sliderRadius,
  49652. sliderRadius * 2.0f,
  49653. knobColour, outlineThickness);
  49654. }
  49655. else
  49656. {
  49657. if (style == Slider::ThreeValueVertical)
  49658. {
  49659. drawGlassSphere (g, x + width * 0.5f - sliderRadius,
  49660. sliderPos - sliderRadius,
  49661. sliderRadius * 2.0f,
  49662. knobColour, outlineThickness);
  49663. }
  49664. else if (style == Slider::ThreeValueHorizontal)
  49665. {
  49666. drawGlassSphere (g,sliderPos - sliderRadius,
  49667. y + height * 0.5f - sliderRadius,
  49668. sliderRadius * 2.0f,
  49669. knobColour, outlineThickness);
  49670. }
  49671. if (style == Slider::TwoValueVertical || style == Slider::ThreeValueVertical)
  49672. {
  49673. const float sr = jmin (sliderRadius, width * 0.4f);
  49674. drawGlassPointer (g, jmax (0.0f, x + width * 0.5f - sliderRadius * 2.0f),
  49675. minSliderPos - sliderRadius,
  49676. sliderRadius * 2.0f, knobColour, outlineThickness, 1);
  49677. drawGlassPointer (g, jmin (x + width - sliderRadius * 2.0f, x + width * 0.5f), maxSliderPos - sr,
  49678. sliderRadius * 2.0f, knobColour, outlineThickness, 3);
  49679. }
  49680. else if (style == Slider::TwoValueHorizontal || style == Slider::ThreeValueHorizontal)
  49681. {
  49682. const float sr = jmin (sliderRadius, height * 0.4f);
  49683. drawGlassPointer (g, minSliderPos - sr,
  49684. jmax (0.0f, y + height * 0.5f - sliderRadius * 2.0f),
  49685. sliderRadius * 2.0f, knobColour, outlineThickness, 2);
  49686. drawGlassPointer (g, maxSliderPos - sliderRadius,
  49687. jmin (y + height - sliderRadius * 2.0f, y + height * 0.5f),
  49688. sliderRadius * 2.0f, knobColour, outlineThickness, 4);
  49689. }
  49690. }
  49691. }
  49692. void LookAndFeel::drawLinearSlider (Graphics& g,
  49693. int x, int y,
  49694. int width, int height,
  49695. float sliderPos,
  49696. float minSliderPos,
  49697. float maxSliderPos,
  49698. const Slider::SliderStyle style,
  49699. Slider& slider)
  49700. {
  49701. g.fillAll (slider.findColour (Slider::backgroundColourId));
  49702. if (style == Slider::LinearBar)
  49703. {
  49704. const bool isMouseOver = slider.isMouseOverOrDragging() && slider.isEnabled();
  49705. Colour baseColour (createBaseColour (slider.findColour (Slider::thumbColourId)
  49706. .withMultipliedSaturation (slider.isEnabled() ? 1.0f : 0.5f),
  49707. false,
  49708. isMouseOver,
  49709. isMouseOver || slider.isMouseButtonDown()));
  49710. drawShinyButtonShape (g,
  49711. (float) x, (float) y, sliderPos - (float) x, (float) height, 0.0f,
  49712. baseColour,
  49713. slider.isEnabled() ? 0.9f : 0.3f,
  49714. true, true, true, true);
  49715. }
  49716. else
  49717. {
  49718. drawLinearSliderBackground (g, x, y, width, height, sliderPos, minSliderPos, maxSliderPos, style, slider);
  49719. drawLinearSliderThumb (g, x, y, width, height, sliderPos, minSliderPos, maxSliderPos, style, slider);
  49720. }
  49721. }
  49722. int LookAndFeel::getSliderThumbRadius (Slider& slider)
  49723. {
  49724. return jmin (7,
  49725. slider.getHeight() / 2,
  49726. slider.getWidth() / 2) + 2;
  49727. }
  49728. void LookAndFeel::drawRotarySlider (Graphics& g,
  49729. int x, int y,
  49730. int width, int height,
  49731. float sliderPos,
  49732. const float rotaryStartAngle,
  49733. const float rotaryEndAngle,
  49734. Slider& slider)
  49735. {
  49736. const float radius = jmin (width / 2, height / 2) - 2.0f;
  49737. const float centreX = x + width * 0.5f;
  49738. const float centreY = y + height * 0.5f;
  49739. const float rx = centreX - radius;
  49740. const float ry = centreY - radius;
  49741. const float rw = radius * 2.0f;
  49742. const float angle = rotaryStartAngle + sliderPos * (rotaryEndAngle - rotaryStartAngle);
  49743. const bool isMouseOver = slider.isMouseOverOrDragging() && slider.isEnabled();
  49744. if (radius > 12.0f)
  49745. {
  49746. if (slider.isEnabled())
  49747. g.setColour (slider.findColour (Slider::rotarySliderFillColourId).withAlpha (isMouseOver ? 1.0f : 0.7f));
  49748. else
  49749. g.setColour (Colour (0x80808080));
  49750. const float thickness = 0.7f;
  49751. {
  49752. Path filledArc;
  49753. filledArc.addPieSegment (rx, ry, rw, rw,
  49754. rotaryStartAngle,
  49755. angle,
  49756. thickness);
  49757. g.fillPath (filledArc);
  49758. }
  49759. if (thickness > 0)
  49760. {
  49761. const float innerRadius = radius * 0.2f;
  49762. Path p;
  49763. p.addTriangle (-innerRadius, 0.0f,
  49764. 0.0f, -radius * thickness * 1.1f,
  49765. innerRadius, 0.0f);
  49766. p.addEllipse (-innerRadius, -innerRadius, innerRadius * 2.0f, innerRadius * 2.0f);
  49767. g.fillPath (p, AffineTransform::rotation (angle).translated (centreX, centreY));
  49768. }
  49769. if (slider.isEnabled())
  49770. {
  49771. g.setColour (slider.findColour (Slider::rotarySliderOutlineColourId));
  49772. Path outlineArc;
  49773. outlineArc.addPieSegment (rx, ry, rw, rw, rotaryStartAngle, rotaryEndAngle, thickness);
  49774. outlineArc.closeSubPath();
  49775. g.strokePath (outlineArc, PathStrokeType (slider.isEnabled() ? (isMouseOver ? 2.0f : 1.2f) : 0.3f));
  49776. }
  49777. }
  49778. else
  49779. {
  49780. if (slider.isEnabled())
  49781. g.setColour (slider.findColour (Slider::rotarySliderFillColourId).withAlpha (isMouseOver ? 1.0f : 0.7f));
  49782. else
  49783. g.setColour (Colour (0x80808080));
  49784. Path p;
  49785. p.addEllipse (-0.4f * rw, -0.4f * rw, rw * 0.8f, rw * 0.8f);
  49786. PathStrokeType (rw * 0.1f).createStrokedPath (p, p);
  49787. p.addLineSegment (0.0f, 0.0f, 0.0f, -radius, rw * 0.2f);
  49788. g.fillPath (p, AffineTransform::rotation (angle).translated (centreX, centreY));
  49789. }
  49790. }
  49791. Button* LookAndFeel::createSliderButton (const bool isIncrement)
  49792. {
  49793. return new TextButton (isIncrement ? "+" : "-", String::empty);
  49794. }
  49795. class SliderLabelComp : public Label
  49796. {
  49797. public:
  49798. SliderLabelComp() : Label (String::empty, String::empty) {}
  49799. ~SliderLabelComp() {}
  49800. void mouseWheelMove (const MouseEvent&, float, float) {}
  49801. };
  49802. Label* LookAndFeel::createSliderTextBox (Slider& slider)
  49803. {
  49804. Label* const l = new SliderLabelComp();
  49805. l->setJustificationType (Justification::centred);
  49806. l->setColour (Label::textColourId, slider.findColour (Slider::textBoxTextColourId));
  49807. l->setColour (Label::backgroundColourId,
  49808. (slider.getSliderStyle() == Slider::LinearBar) ? Colours::transparentBlack
  49809. : slider.findColour (Slider::textBoxBackgroundColourId));
  49810. l->setColour (Label::outlineColourId, slider.findColour (Slider::textBoxOutlineColourId));
  49811. l->setColour (TextEditor::textColourId, slider.findColour (Slider::textBoxTextColourId));
  49812. l->setColour (TextEditor::backgroundColourId,
  49813. slider.findColour (Slider::textBoxBackgroundColourId)
  49814. .withAlpha (slider.getSliderStyle() == Slider::LinearBar ? 0.7f : 1.0f));
  49815. l->setColour (TextEditor::outlineColourId, slider.findColour (Slider::textBoxOutlineColourId));
  49816. return l;
  49817. }
  49818. ImageEffectFilter* LookAndFeel::getSliderEffect()
  49819. {
  49820. return 0;
  49821. }
  49822. static const TextLayout layoutTooltipText (const String& text) throw()
  49823. {
  49824. const float tooltipFontSize = 12.0f;
  49825. const int maxToolTipWidth = 400;
  49826. const Font f (tooltipFontSize, Font::bold);
  49827. TextLayout tl (text, f);
  49828. tl.layout (maxToolTipWidth, Justification::left, true);
  49829. return tl;
  49830. }
  49831. void LookAndFeel::getTooltipSize (const String& tipText, int& width, int& height)
  49832. {
  49833. const TextLayout tl (layoutTooltipText (tipText));
  49834. width = tl.getWidth() + 14;
  49835. height = tl.getHeight() + 6;
  49836. }
  49837. void LookAndFeel::drawTooltip (Graphics& g, const String& text, int width, int height)
  49838. {
  49839. g.fillAll (findColour (TooltipWindow::backgroundColourId));
  49840. const Colour textCol (findColour (TooltipWindow::textColourId));
  49841. #if ! JUCE_MAC // The mac windows already have a non-optional 1 pix outline, so don't double it here..
  49842. g.setColour (findColour (TooltipWindow::outlineColourId));
  49843. g.drawRect (0, 0, width, height, 1);
  49844. #endif
  49845. const TextLayout tl (layoutTooltipText (text));
  49846. g.setColour (findColour (TooltipWindow::textColourId));
  49847. tl.drawWithin (g, 0, 0, width, height, Justification::centred);
  49848. }
  49849. Button* LookAndFeel::createFilenameComponentBrowseButton (const String& text)
  49850. {
  49851. return new TextButton (text, TRANS("click to browse for a different file"));
  49852. }
  49853. void LookAndFeel::layoutFilenameComponent (FilenameComponent& filenameComp,
  49854. ComboBox* filenameBox,
  49855. Button* browseButton)
  49856. {
  49857. browseButton->setSize (80, filenameComp.getHeight());
  49858. TextButton* const tb = dynamic_cast <TextButton*> (browseButton);
  49859. if (tb != 0)
  49860. tb->changeWidthToFitText();
  49861. browseButton->setTopRightPosition (filenameComp.getWidth(), 0);
  49862. filenameBox->setBounds (0, 0, browseButton->getX(), filenameComp.getHeight());
  49863. }
  49864. void LookAndFeel::drawImageButton (Graphics& g, Image* image,
  49865. int imageX, int imageY, int imageW, int imageH,
  49866. const Colour& overlayColour,
  49867. float imageOpacity,
  49868. ImageButton& button)
  49869. {
  49870. if (! button.isEnabled())
  49871. imageOpacity *= 0.3f;
  49872. if (! overlayColour.isOpaque())
  49873. {
  49874. g.setOpacity (imageOpacity);
  49875. g.drawImage (image, imageX, imageY, imageW, imageH,
  49876. 0, 0, image->getWidth(), image->getHeight(), false);
  49877. }
  49878. if (! overlayColour.isTransparent())
  49879. {
  49880. g.setColour (overlayColour);
  49881. g.drawImage (image, imageX, imageY, imageW, imageH,
  49882. 0, 0, image->getWidth(), image->getHeight(), true);
  49883. }
  49884. }
  49885. void LookAndFeel::drawCornerResizer (Graphics& g,
  49886. int w, int h,
  49887. bool /*isMouseOver*/,
  49888. bool /*isMouseDragging*/)
  49889. {
  49890. const float lineThickness = jmin (w, h) * 0.075f;
  49891. for (float i = 0.0f; i < 1.0f; i += 0.3f)
  49892. {
  49893. g.setColour (Colours::lightgrey);
  49894. g.drawLine (w * i,
  49895. h + 1.0f,
  49896. w + 1.0f,
  49897. h * i,
  49898. lineThickness);
  49899. g.setColour (Colours::darkgrey);
  49900. g.drawLine (w * i + lineThickness,
  49901. h + 1.0f,
  49902. w + 1.0f,
  49903. h * i + lineThickness,
  49904. lineThickness);
  49905. }
  49906. }
  49907. void LookAndFeel::drawResizableFrame (Graphics&, int /*w*/, int /*h*/,
  49908. const BorderSize& /*borders*/)
  49909. {
  49910. }
  49911. void LookAndFeel::fillResizableWindowBackground (Graphics& g, int /*w*/, int /*h*/,
  49912. const BorderSize& /*border*/, ResizableWindow& window)
  49913. {
  49914. g.fillAll (window.getBackgroundColour());
  49915. }
  49916. void LookAndFeel::drawResizableWindowBorder (Graphics& g, int w, int h,
  49917. const BorderSize& border, ResizableWindow&)
  49918. {
  49919. g.setColour (Colour (0x80000000));
  49920. g.drawRect (0, 0, w, h);
  49921. g.setColour (Colour (0x19000000));
  49922. g.drawRect (border.getLeft() - 1,
  49923. border.getTop() - 1,
  49924. w + 2 - border.getLeftAndRight(),
  49925. h + 2 - border.getTopAndBottom());
  49926. }
  49927. void LookAndFeel::drawDocumentWindowTitleBar (DocumentWindow& window,
  49928. Graphics& g, int w, int h,
  49929. int titleSpaceX, int titleSpaceW,
  49930. const Image* icon,
  49931. bool drawTitleTextOnLeft)
  49932. {
  49933. const bool isActive = window.isActiveWindow();
  49934. GradientBrush gb (window.getBackgroundColour(),
  49935. 0.0f, 0.0f,
  49936. window.getBackgroundColour().contrasting (isActive ? 0.15f : 0.05f),
  49937. 0.0f, (float) h, false);
  49938. g.setBrush (&gb);
  49939. g.fillAll();
  49940. g.setFont (h * 0.65f, Font::bold);
  49941. int textW = g.getCurrentFont().getStringWidth (window.getName());
  49942. int iconW = 0;
  49943. int iconH = 0;
  49944. if (icon != 0)
  49945. {
  49946. iconH = (int) g.getCurrentFont().getHeight();
  49947. iconW = icon->getWidth() * iconH / icon->getHeight() + 4;
  49948. }
  49949. textW = jmin (titleSpaceW, textW + iconW);
  49950. int textX = drawTitleTextOnLeft ? titleSpaceX
  49951. : jmax (titleSpaceX, (w - textW) / 2);
  49952. if (textX + textW > titleSpaceX + titleSpaceW)
  49953. textX = titleSpaceX + titleSpaceW - textW;
  49954. if (icon != 0)
  49955. {
  49956. g.setOpacity (isActive ? 1.0f : 0.6f);
  49957. g.drawImageWithin (icon, textX, (h - iconH) / 2, iconW, iconH,
  49958. RectanglePlacement::centred, false);
  49959. textX += iconW;
  49960. textW -= iconW;
  49961. }
  49962. if (window.isColourSpecified (DocumentWindow::textColourId) || isColourSpecified (DocumentWindow::textColourId))
  49963. g.setColour (findColour (DocumentWindow::textColourId));
  49964. else
  49965. g.setColour (window.getBackgroundColour().contrasting (isActive ? 0.7f : 0.4f));
  49966. g.drawText (window.getName(), textX, 0, textW, h, Justification::centredLeft, true);
  49967. }
  49968. class GlassWindowButton : public Button
  49969. {
  49970. public:
  49971. GlassWindowButton (const String& name, const Colour& col,
  49972. const Path& normalShape_,
  49973. const Path& toggledShape_) throw()
  49974. : Button (name),
  49975. colour (col),
  49976. normalShape (normalShape_),
  49977. toggledShape (toggledShape_)
  49978. {
  49979. }
  49980. ~GlassWindowButton()
  49981. {
  49982. }
  49983. void paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown)
  49984. {
  49985. float alpha = isMouseOverButton ? (isButtonDown ? 1.0f : 0.8f) : 0.55f;
  49986. if (! isEnabled())
  49987. alpha *= 0.5f;
  49988. float x = 0, y = 0, diam;
  49989. if (getWidth() < getHeight())
  49990. {
  49991. diam = (float) getWidth();
  49992. y = (getHeight() - getWidth()) * 0.5f;
  49993. }
  49994. else
  49995. {
  49996. diam = (float) getHeight();
  49997. y = (getWidth() - getHeight()) * 0.5f;
  49998. }
  49999. x += diam * 0.05f;
  50000. y += diam * 0.05f;
  50001. diam *= 0.9f;
  50002. GradientBrush gb1 (Colour::greyLevel (0.9f).withAlpha (alpha), 0, y + diam,
  50003. Colour::greyLevel (0.6f).withAlpha (alpha), 0, y, false);
  50004. g.setBrush (&gb1);
  50005. g.fillEllipse (x, y, diam, diam);
  50006. x += 2.0f;
  50007. y += 2.0f;
  50008. diam -= 4.0f;
  50009. LookAndFeel::drawGlassSphere (g, x, y, diam, colour.withAlpha (alpha), 1.0f);
  50010. Path& p = getToggleState() ? toggledShape : normalShape;
  50011. const AffineTransform t (p.getTransformToScaleToFit (x + diam * 0.3f, y + diam * 0.3f,
  50012. diam * 0.4f, diam * 0.4f, true));
  50013. g.setColour (Colours::black.withAlpha (alpha * 0.6f));
  50014. g.fillPath (p, t);
  50015. }
  50016. juce_UseDebuggingNewOperator
  50017. private:
  50018. Colour colour;
  50019. Path normalShape, toggledShape;
  50020. GlassWindowButton (const GlassWindowButton&);
  50021. const GlassWindowButton& operator= (const GlassWindowButton&);
  50022. };
  50023. Button* LookAndFeel::createDocumentWindowButton (int buttonType)
  50024. {
  50025. Path shape;
  50026. const float crossThickness = 0.25f;
  50027. if (buttonType == DocumentWindow::closeButton)
  50028. {
  50029. shape.addLineSegment (0.0f, 0.0f, 1.0f, 1.0f, crossThickness * 1.4f);
  50030. shape.addLineSegment (1.0f, 0.0f, 0.0f, 1.0f, crossThickness * 1.4f);
  50031. return new GlassWindowButton ("close", Colour (0xffdd1100), shape, shape);
  50032. }
  50033. else if (buttonType == DocumentWindow::minimiseButton)
  50034. {
  50035. shape.addLineSegment (0.0f, 0.5f, 1.0f, 0.5f, crossThickness);
  50036. return new GlassWindowButton ("minimise", Colour (0xffaa8811), shape, shape);
  50037. }
  50038. else if (buttonType == DocumentWindow::maximiseButton)
  50039. {
  50040. shape.addLineSegment (0.5f, 0.0f, 0.5f, 1.0f, crossThickness);
  50041. shape.addLineSegment (0.0f, 0.5f, 1.0f, 0.5f, crossThickness);
  50042. Path fullscreenShape;
  50043. fullscreenShape.startNewSubPath (45.0f, 100.0f);
  50044. fullscreenShape.lineTo (0.0f, 100.0f);
  50045. fullscreenShape.lineTo (0.0f, 0.0f);
  50046. fullscreenShape.lineTo (100.0f, 0.0f);
  50047. fullscreenShape.lineTo (100.0f, 45.0f);
  50048. fullscreenShape.addRectangle (45.0f, 45.0f, 100.0f, 100.0f);
  50049. PathStrokeType (30.0f).createStrokedPath (fullscreenShape, fullscreenShape);
  50050. return new GlassWindowButton ("maximise", Colour (0xff119911), shape, fullscreenShape);
  50051. }
  50052. jassertfalse
  50053. return 0;
  50054. }
  50055. void LookAndFeel::positionDocumentWindowButtons (DocumentWindow&,
  50056. int titleBarX,
  50057. int titleBarY,
  50058. int titleBarW,
  50059. int titleBarH,
  50060. Button* minimiseButton,
  50061. Button* maximiseButton,
  50062. Button* closeButton,
  50063. bool positionTitleBarButtonsOnLeft)
  50064. {
  50065. const int buttonW = titleBarH - titleBarH / 8;
  50066. int x = positionTitleBarButtonsOnLeft ? titleBarX + 4
  50067. : titleBarX + titleBarW - buttonW - buttonW / 4;
  50068. if (closeButton != 0)
  50069. {
  50070. closeButton->setBounds (x, titleBarY, buttonW, titleBarH);
  50071. x += positionTitleBarButtonsOnLeft ? buttonW : -(buttonW + buttonW / 4);
  50072. }
  50073. if (positionTitleBarButtonsOnLeft)
  50074. swapVariables (minimiseButton, maximiseButton);
  50075. if (maximiseButton != 0)
  50076. {
  50077. maximiseButton->setBounds (x, titleBarY, buttonW, titleBarH);
  50078. x += positionTitleBarButtonsOnLeft ? buttonW : -buttonW;
  50079. }
  50080. if (minimiseButton != 0)
  50081. minimiseButton->setBounds (x, titleBarY, buttonW, titleBarH);
  50082. }
  50083. int LookAndFeel::getDefaultMenuBarHeight()
  50084. {
  50085. return 24;
  50086. }
  50087. DropShadower* LookAndFeel::createDropShadowerForComponent (Component*)
  50088. {
  50089. return new DropShadower (0.4f, 1, 5, 10);
  50090. }
  50091. void LookAndFeel::drawStretchableLayoutResizerBar (Graphics& g,
  50092. int w, int h,
  50093. bool /*isVerticalBar*/,
  50094. bool isMouseOver,
  50095. bool isMouseDragging)
  50096. {
  50097. float alpha = 0.5f;
  50098. if (isMouseOver || isMouseDragging)
  50099. {
  50100. g.fillAll (Colour (0x190000ff));
  50101. alpha = 1.0f;
  50102. }
  50103. const float cx = w * 0.5f;
  50104. const float cy = h * 0.5f;
  50105. const float cr = jmin (w, h) * 0.4f;
  50106. GradientBrush gb (Colours::white.withAlpha (alpha), cx + cr * 0.1f, cy + cr,
  50107. Colours::black.withAlpha (alpha), cx, cy - cr * 4.0f,
  50108. true);
  50109. g.setBrush (&gb);
  50110. g.fillEllipse (cx - cr, cy - cr, cr * 2.0f, cr * 2.0f);
  50111. }
  50112. void LookAndFeel::drawGroupComponentOutline (Graphics& g, int width, int height,
  50113. const String& text,
  50114. const Justification& position,
  50115. GroupComponent& group)
  50116. {
  50117. const float textH = 15.0f;
  50118. const float indent = 3.0f;
  50119. const float textEdgeGap = 4.0f;
  50120. float cs = 5.0f;
  50121. Font f (textH);
  50122. Path p;
  50123. float x = indent;
  50124. float y = f.getAscent() - 3.0f;
  50125. float w = jmax (0.0f, width - x * 2.0f);
  50126. float h = jmax (0.0f, height - y - indent);
  50127. cs = jmin (cs, w * 0.5f, h * 0.5f);
  50128. const float cs2 = 2.0f * cs;
  50129. float textW = text.isEmpty() ? 0 : jlimit (0.0f, jmax (0.0f, w - cs2 - textEdgeGap * 2), f.getStringWidth (text) + textEdgeGap * 2.0f);
  50130. float textX = cs + textEdgeGap;
  50131. if (position.testFlags (Justification::horizontallyCentred))
  50132. textX = cs + (w - cs2 - textW) * 0.5f;
  50133. else if (position.testFlags (Justification::right))
  50134. textX = w - cs - textW - textEdgeGap;
  50135. p.startNewSubPath (x + textX + textW, y);
  50136. p.lineTo (x + w - cs, y);
  50137. p.addArc (x + w - cs2, y, cs2, cs2, 0, float_Pi * 0.5f);
  50138. p.lineTo (x + w, y + h - cs);
  50139. p.addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  50140. p.lineTo (x + cs, y + h);
  50141. p.addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  50142. p.lineTo (x, y + cs);
  50143. p.addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f);
  50144. p.lineTo (x + textX, y);
  50145. const float alpha = group.isEnabled() ? 1.0f : 0.5f;
  50146. g.setColour (group.findColour (GroupComponent::outlineColourId)
  50147. .withMultipliedAlpha (alpha));
  50148. g.strokePath (p, PathStrokeType (2.0f));
  50149. g.setColour (group.findColour (GroupComponent::textColourId)
  50150. .withMultipliedAlpha (alpha));
  50151. g.setFont (f);
  50152. g.drawText (text,
  50153. roundFloatToInt (x + textX), 0,
  50154. roundFloatToInt (textW),
  50155. roundFloatToInt (textH),
  50156. Justification::centred, true);
  50157. }
  50158. int LookAndFeel::getTabButtonOverlap (int tabDepth)
  50159. {
  50160. return 1 + tabDepth / 3;
  50161. }
  50162. int LookAndFeel::getTabButtonSpaceAroundImage()
  50163. {
  50164. return 4;
  50165. }
  50166. void LookAndFeel::createTabButtonShape (Path& p,
  50167. int width, int height,
  50168. int /*tabIndex*/,
  50169. const String& /*text*/,
  50170. Button& /*button*/,
  50171. TabbedButtonBar::Orientation orientation,
  50172. const bool /*isMouseOver*/,
  50173. const bool /*isMouseDown*/,
  50174. const bool /*isFrontTab*/)
  50175. {
  50176. const float w = (float) width;
  50177. const float h = (float) height;
  50178. float length = w;
  50179. float depth = h;
  50180. if (orientation == TabbedButtonBar::TabsAtLeft
  50181. || orientation == TabbedButtonBar::TabsAtRight)
  50182. {
  50183. swapVariables (length, depth);
  50184. }
  50185. const float indent = (float) getTabButtonOverlap ((int) depth);
  50186. const float overhang = 4.0f;
  50187. if (orientation == TabbedButtonBar::TabsAtLeft)
  50188. {
  50189. p.startNewSubPath (w, 0.0f);
  50190. p.lineTo (0.0f, indent);
  50191. p.lineTo (0.0f, h - indent);
  50192. p.lineTo (w, h);
  50193. p.lineTo (w + overhang, h + overhang);
  50194. p.lineTo (w + overhang, -overhang);
  50195. }
  50196. else if (orientation == TabbedButtonBar::TabsAtRight)
  50197. {
  50198. p.startNewSubPath (0.0f, 0.0f);
  50199. p.lineTo (w, indent);
  50200. p.lineTo (w, h - indent);
  50201. p.lineTo (0.0f, h);
  50202. p.lineTo (-overhang, h + overhang);
  50203. p.lineTo (-overhang, -overhang);
  50204. }
  50205. else if (orientation == TabbedButtonBar::TabsAtBottom)
  50206. {
  50207. p.startNewSubPath (0.0f, 0.0f);
  50208. p.lineTo (indent, h);
  50209. p.lineTo (w - indent, h);
  50210. p.lineTo (w, 0.0f);
  50211. p.lineTo (w + overhang, -overhang);
  50212. p.lineTo (-overhang, -overhang);
  50213. }
  50214. else
  50215. {
  50216. p.startNewSubPath (0.0f, h);
  50217. p.lineTo (indent, 0.0f);
  50218. p.lineTo (w - indent, 0.0f);
  50219. p.lineTo (w, h);
  50220. p.lineTo (w + overhang, h + overhang);
  50221. p.lineTo (-overhang, h + overhang);
  50222. }
  50223. p.closeSubPath();
  50224. p = p.createPathWithRoundedCorners (3.0f);
  50225. }
  50226. void LookAndFeel::fillTabButtonShape (Graphics& g,
  50227. const Path& path,
  50228. const Colour& preferredColour,
  50229. int /*tabIndex*/,
  50230. const String& /*text*/,
  50231. Button& button,
  50232. TabbedButtonBar::Orientation /*orientation*/,
  50233. const bool /*isMouseOver*/,
  50234. const bool /*isMouseDown*/,
  50235. const bool isFrontTab)
  50236. {
  50237. g.setColour (isFrontTab ? preferredColour
  50238. : preferredColour.withMultipliedAlpha (0.9f));
  50239. g.fillPath (path);
  50240. g.setColour (button.findColour (isFrontTab ? TabbedButtonBar::frontOutlineColourId
  50241. : TabbedButtonBar::tabOutlineColourId, false)
  50242. .withMultipliedAlpha (button.isEnabled() ? 1.0f : 0.5f));
  50243. g.strokePath (path, PathStrokeType (isFrontTab ? 1.0f : 0.5f));
  50244. }
  50245. void LookAndFeel::drawTabButtonText (Graphics& g,
  50246. int x, int y, int w, int h,
  50247. const Colour& preferredBackgroundColour,
  50248. int /*tabIndex*/,
  50249. const String& text,
  50250. Button& button,
  50251. TabbedButtonBar::Orientation orientation,
  50252. const bool isMouseOver,
  50253. const bool isMouseDown,
  50254. const bool isFrontTab)
  50255. {
  50256. int length = w;
  50257. int depth = h;
  50258. if (orientation == TabbedButtonBar::TabsAtLeft
  50259. || orientation == TabbedButtonBar::TabsAtRight)
  50260. {
  50261. swapVariables (length, depth);
  50262. }
  50263. Font font (depth * 0.6f);
  50264. font.setUnderline (button.hasKeyboardFocus (false));
  50265. GlyphArrangement textLayout;
  50266. textLayout.addFittedText (font, text.trim(),
  50267. 0.0f, 0.0f, (float) length, (float) depth,
  50268. Justification::centred,
  50269. jmax (1, depth / 12));
  50270. AffineTransform transform;
  50271. if (orientation == TabbedButtonBar::TabsAtLeft)
  50272. {
  50273. transform = transform.rotated (float_Pi * -0.5f)
  50274. .translated ((float) x, (float) (y + h));
  50275. }
  50276. else if (orientation == TabbedButtonBar::TabsAtRight)
  50277. {
  50278. transform = transform.rotated (float_Pi * 0.5f)
  50279. .translated ((float) (x + w), (float) y);
  50280. }
  50281. else
  50282. {
  50283. transform = transform.translated ((float) x, (float) y);
  50284. }
  50285. if (isFrontTab && (button.isColourSpecified (TabbedButtonBar::frontTextColourId) || isColourSpecified (TabbedButtonBar::frontTextColourId)))
  50286. g.setColour (findColour (TabbedButtonBar::frontTextColourId));
  50287. else if (button.isColourSpecified (TabbedButtonBar::tabTextColourId) || isColourSpecified (TabbedButtonBar::tabTextColourId))
  50288. g.setColour (findColour (TabbedButtonBar::tabTextColourId));
  50289. else
  50290. g.setColour (preferredBackgroundColour.contrasting());
  50291. if (! (isMouseOver || isMouseDown))
  50292. g.setOpacity (0.8f);
  50293. if (! button.isEnabled())
  50294. g.setOpacity (0.3f);
  50295. textLayout.draw (g, transform);
  50296. }
  50297. int LookAndFeel::getTabButtonBestWidth (int /*tabIndex*/,
  50298. const String& text,
  50299. int tabDepth,
  50300. Button&)
  50301. {
  50302. Font f (tabDepth * 0.6f);
  50303. return f.getStringWidth (text.trim()) + getTabButtonOverlap (tabDepth) * 2;
  50304. }
  50305. void LookAndFeel::drawTabButton (Graphics& g,
  50306. int w, int h,
  50307. const Colour& preferredColour,
  50308. int tabIndex,
  50309. const String& text,
  50310. Button& button,
  50311. TabbedButtonBar::Orientation orientation,
  50312. const bool isMouseOver,
  50313. const bool isMouseDown,
  50314. const bool isFrontTab)
  50315. {
  50316. int length = w;
  50317. int depth = h;
  50318. if (orientation == TabbedButtonBar::TabsAtLeft
  50319. || orientation == TabbedButtonBar::TabsAtRight)
  50320. {
  50321. swapVariables (length, depth);
  50322. }
  50323. Path tabShape;
  50324. createTabButtonShape (tabShape, w, h,
  50325. tabIndex, text, button, orientation,
  50326. isMouseOver, isMouseDown, isFrontTab);
  50327. fillTabButtonShape (g, tabShape, preferredColour,
  50328. tabIndex, text, button, orientation,
  50329. isMouseOver, isMouseDown, isFrontTab);
  50330. const int indent = getTabButtonOverlap (depth);
  50331. int x = 0, y = 0;
  50332. if (orientation == TabbedButtonBar::TabsAtLeft
  50333. || orientation == TabbedButtonBar::TabsAtRight)
  50334. {
  50335. y += indent;
  50336. h -= indent * 2;
  50337. }
  50338. else
  50339. {
  50340. x += indent;
  50341. w -= indent * 2;
  50342. }
  50343. drawTabButtonText (g, x, y, w, h, preferredColour,
  50344. tabIndex, text, button, orientation,
  50345. isMouseOver, isMouseDown, isFrontTab);
  50346. }
  50347. void LookAndFeel::drawTabAreaBehindFrontButton (Graphics& g,
  50348. int w, int h,
  50349. TabbedButtonBar& tabBar,
  50350. TabbedButtonBar::Orientation orientation)
  50351. {
  50352. const float shadowSize = 0.2f;
  50353. float x1 = 0.0f, y1 = 0.0f, x2 = 0.0f, y2 = 0.0f;
  50354. Rectangle shadowRect;
  50355. if (orientation == TabbedButtonBar::TabsAtLeft)
  50356. {
  50357. x1 = (float) w;
  50358. x2 = w * (1.0f - shadowSize);
  50359. shadowRect.setBounds ((int) x2, 0, w - (int) x2, h);
  50360. }
  50361. else if (orientation == TabbedButtonBar::TabsAtRight)
  50362. {
  50363. x2 = w * shadowSize;
  50364. shadowRect.setBounds (0, 0, (int) x2, h);
  50365. }
  50366. else if (orientation == TabbedButtonBar::TabsAtBottom)
  50367. {
  50368. y2 = h * shadowSize;
  50369. shadowRect.setBounds (0, 0, w, (int) y2);
  50370. }
  50371. else
  50372. {
  50373. y1 = (float) h;
  50374. y2 = h * (1.0f - shadowSize);
  50375. shadowRect.setBounds (0, (int) y2, w, h - (int) y2);
  50376. }
  50377. GradientBrush gb (Colours::black.withAlpha (tabBar.isEnabled() ? 0.3f : 0.15f), x1, y1,
  50378. Colours::transparentBlack, x2, y2,
  50379. false);
  50380. g.setBrush (&gb);
  50381. shadowRect.expand (2, 2);
  50382. g.fillRect (shadowRect);
  50383. g.setColour (Colour (0x80000000));
  50384. if (orientation == TabbedButtonBar::TabsAtLeft)
  50385. {
  50386. g.fillRect (w - 1, 0, 1, h);
  50387. }
  50388. else if (orientation == TabbedButtonBar::TabsAtRight)
  50389. {
  50390. g.fillRect (0, 0, 1, h);
  50391. }
  50392. else if (orientation == TabbedButtonBar::TabsAtBottom)
  50393. {
  50394. g.fillRect (0, 0, w, 1);
  50395. }
  50396. else
  50397. {
  50398. g.fillRect (0, h - 1, w, 1);
  50399. }
  50400. }
  50401. Button* LookAndFeel::createTabBarExtrasButton()
  50402. {
  50403. const float thickness = 7.0f;
  50404. const float indent = 22.0f;
  50405. Path p;
  50406. p.addEllipse (-10.0f, -10.0f, 120.0f, 120.0f);
  50407. DrawablePath ellipse;
  50408. ellipse.setPath (p);
  50409. ellipse.setSolidFill (Colour (0x99ffffff));
  50410. p.clear();
  50411. p.addEllipse (0.0f, 0.0f, 100.0f, 100.0f);
  50412. p.addRectangle (indent, 50.0f - thickness, 100.0f - indent * 2.0f, thickness * 2.0f);
  50413. p.addRectangle (50.0f - thickness, indent, thickness * 2.0f, 50.0f - indent - thickness);
  50414. p.addRectangle (50.0f - thickness, 50.0f + thickness, thickness * 2.0f, 50.0f - indent - thickness);
  50415. p.setUsingNonZeroWinding (false);
  50416. DrawablePath dp;
  50417. dp.setPath (p);
  50418. dp.setSolidFill (Colour (0x59000000));
  50419. DrawableComposite normalImage;
  50420. normalImage.insertDrawable (ellipse);
  50421. normalImage.insertDrawable (dp);
  50422. dp.setSolidFill (Colour (0xcc000000));
  50423. DrawableComposite overImage;
  50424. overImage.insertDrawable (ellipse);
  50425. overImage.insertDrawable (dp);
  50426. DrawableButton* db = new DrawableButton (T("tabs"), DrawableButton::ImageFitted);
  50427. db->setImages (&normalImage, &overImage, 0);
  50428. return db;
  50429. }
  50430. void LookAndFeel::drawTableHeaderBackground (Graphics& g, TableHeaderComponent& header)
  50431. {
  50432. g.fillAll (Colours::white);
  50433. const int w = header.getWidth();
  50434. const int h = header.getHeight();
  50435. GradientBrush gb (Colour (0xffe8ebf9), 0.0f, h * 0.5f,
  50436. Colour (0xfff6f8f9), 0.0f, h - 1.0f,
  50437. false);
  50438. g.setBrush (&gb);
  50439. g.fillRect (0, h / 2, w, h);
  50440. g.setColour (Colour (0x33000000));
  50441. g.fillRect (0, h - 1, w, 1);
  50442. for (int i = header.getNumColumns (true); --i >= 0;)
  50443. g.fillRect (header.getColumnPosition (i).getRight() - 1, 0, 1, h - 1);
  50444. }
  50445. void LookAndFeel::drawTableHeaderColumn (Graphics& g, const String& columnName, int /*columnId*/,
  50446. int width, int height,
  50447. bool isMouseOver, bool isMouseDown,
  50448. int columnFlags)
  50449. {
  50450. if (isMouseDown)
  50451. g.fillAll (Colour (0x8899aadd));
  50452. else if (isMouseOver)
  50453. g.fillAll (Colour (0x5599aadd));
  50454. int rightOfText = width - 4;
  50455. if ((columnFlags & (TableHeaderComponent::sortedForwards | TableHeaderComponent::sortedBackwards)) != 0)
  50456. {
  50457. const float top = height * ((columnFlags & TableHeaderComponent::sortedForwards) != 0 ? 0.35f : (1.0f - 0.35f));
  50458. const float bottom = height - top;
  50459. const float w = height * 0.5f;
  50460. const float x = rightOfText - (w * 1.25f);
  50461. rightOfText = (int) x;
  50462. Path sortArrow;
  50463. sortArrow.addTriangle (x, bottom, x + w * 0.5f, top, x + w, bottom);
  50464. g.setColour (Colour (0x99000000));
  50465. g.fillPath (sortArrow);
  50466. }
  50467. g.setColour (Colours::black);
  50468. g.setFont (height * 0.5f, Font::bold);
  50469. const int textX = 4;
  50470. g.drawFittedText (columnName, textX, 0, rightOfText - textX, height, Justification::centredLeft, 1);
  50471. }
  50472. void LookAndFeel::paintToolbarBackground (Graphics& g, int w, int h, Toolbar& toolbar)
  50473. {
  50474. const Colour background (toolbar.findColour (Toolbar::backgroundColourId));
  50475. GradientBrush gb (background, 0.0f, 0.0f,
  50476. background.darker (0.1f),
  50477. toolbar.isVertical() ? w - 1.0f : 0.0f,
  50478. toolbar.isVertical() ? 0.0f : h - 1.0f,
  50479. false);
  50480. g.setBrush (&gb);
  50481. g.fillAll();
  50482. }
  50483. Button* LookAndFeel::createToolbarMissingItemsButton (Toolbar& /*toolbar*/)
  50484. {
  50485. return createTabBarExtrasButton();
  50486. }
  50487. void LookAndFeel::paintToolbarButtonBackground (Graphics& g, int /*width*/, int /*height*/,
  50488. bool isMouseOver, bool isMouseDown,
  50489. ToolbarItemComponent& component)
  50490. {
  50491. if (isMouseDown)
  50492. g.fillAll (component.findColour (Toolbar::buttonMouseDownBackgroundColourId, true));
  50493. else if (isMouseOver)
  50494. g.fillAll (component.findColour (Toolbar::buttonMouseOverBackgroundColourId, true));
  50495. }
  50496. void LookAndFeel::paintToolbarButtonLabel (Graphics& g, int x, int y, int width, int height,
  50497. const String& text, ToolbarItemComponent& component)
  50498. {
  50499. g.setColour (component.findColour (Toolbar::labelTextColourId, true)
  50500. .withAlpha (component.isEnabled() ? 1.0f : 0.25f));
  50501. const float fontHeight = jmin (14.0f, height * 0.85f);
  50502. g.setFont (fontHeight);
  50503. g.drawFittedText (text,
  50504. x, y, width, height,
  50505. Justification::centred,
  50506. jmax (1, height / (int) fontHeight));
  50507. }
  50508. void LookAndFeel::drawPropertyPanelSectionHeader (Graphics& g, const String& name,
  50509. bool isOpen, int width, int height)
  50510. {
  50511. const int buttonSize = (height * 3) / 4;
  50512. const int buttonIndent = (height - buttonSize) / 2;
  50513. drawTreeviewPlusMinusBox (g, buttonIndent, buttonIndent, buttonSize, buttonSize, ! isOpen);
  50514. const int textX = buttonIndent * 2 + buttonSize + 2;
  50515. g.setColour (Colours::black);
  50516. g.setFont (height * 0.7f, Font::bold);
  50517. g.drawText (name, textX, 0, width - textX - 4, height, Justification::centredLeft, true);
  50518. }
  50519. void LookAndFeel::drawPropertyComponentBackground (Graphics& g, int width, int height,
  50520. PropertyComponent&)
  50521. {
  50522. g.setColour (Colour (0x66ffffff));
  50523. g.fillRect (0, 0, width, height - 1);
  50524. }
  50525. void LookAndFeel::drawPropertyComponentLabel (Graphics& g, int, int height,
  50526. PropertyComponent& component)
  50527. {
  50528. g.setColour (Colours::black);
  50529. if (! component.isEnabled())
  50530. g.setOpacity (g.getCurrentColour().getFloatAlpha() * 0.6f);
  50531. g.setFont (jmin (height, 24) * 0.65f);
  50532. const Rectangle r (getPropertyComponentContentPosition (component));
  50533. g.drawFittedText (component.getName(),
  50534. 3, r.getY(), r.getX() - 5, r.getHeight(),
  50535. Justification::centredLeft, 2);
  50536. }
  50537. const Rectangle LookAndFeel::getPropertyComponentContentPosition (PropertyComponent& component)
  50538. {
  50539. return Rectangle (component.getWidth() / 3, 1,
  50540. component.getWidth() - component.getWidth() / 3 - 1, component.getHeight() - 3);
  50541. }
  50542. void LookAndFeel::createFileChooserHeaderText (const String& title,
  50543. const String& instructions,
  50544. GlyphArrangement& text,
  50545. int width)
  50546. {
  50547. text.clear();
  50548. text.addJustifiedText (Font (17.0f, Font::bold), title,
  50549. 8.0f, 22.0f, width - 16.0f,
  50550. Justification::centred);
  50551. text.addJustifiedText (Font (14.0f), instructions,
  50552. 8.0f, 24.0f + 16.0f, width - 16.0f,
  50553. Justification::centred);
  50554. }
  50555. void LookAndFeel::drawFileBrowserRow (Graphics& g, int width, int height,
  50556. const String& filename, Image* icon,
  50557. const String& fileSizeDescription,
  50558. const String& fileTimeDescription,
  50559. const bool isDirectory,
  50560. const bool isItemSelected,
  50561. const int /*itemIndex*/)
  50562. {
  50563. if (isItemSelected)
  50564. g.fillAll (findColour (DirectoryContentsDisplayComponent::highlightColourId));
  50565. g.setColour (findColour (DirectoryContentsDisplayComponent::textColourId));
  50566. g.setFont (height * 0.7f);
  50567. Image* im = icon;
  50568. Image* toRelease = 0;
  50569. if (im == 0)
  50570. {
  50571. toRelease = im = (isDirectory ? getDefaultFolderImage()
  50572. : getDefaultDocumentFileImage());
  50573. }
  50574. const int x = 32;
  50575. if (im != 0)
  50576. {
  50577. g.drawImageWithin (im, 2, 2, x - 4, height - 4,
  50578. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize,
  50579. false);
  50580. ImageCache::release (toRelease);
  50581. }
  50582. if (width > 450 && ! isDirectory)
  50583. {
  50584. const int sizeX = roundFloatToInt (width * 0.7f);
  50585. const int dateX = roundFloatToInt (width * 0.8f);
  50586. g.drawFittedText (filename,
  50587. x, 0, sizeX - x, height,
  50588. Justification::centredLeft, 1);
  50589. g.setFont (height * 0.5f);
  50590. g.setColour (Colours::darkgrey);
  50591. if (! isDirectory)
  50592. {
  50593. g.drawFittedText (fileSizeDescription,
  50594. sizeX, 0, dateX - sizeX - 8, height,
  50595. Justification::centredRight, 1);
  50596. g.drawFittedText (fileTimeDescription,
  50597. dateX, 0, width - 8 - dateX, height,
  50598. Justification::centredRight, 1);
  50599. }
  50600. }
  50601. else
  50602. {
  50603. g.drawFittedText (filename,
  50604. x, 0, width - x, height,
  50605. Justification::centredLeft, 1);
  50606. }
  50607. }
  50608. Button* LookAndFeel::createFileBrowserGoUpButton()
  50609. {
  50610. DrawableButton* goUpButton = new DrawableButton ("up", DrawableButton::ImageOnButtonBackground);
  50611. Path arrowPath;
  50612. arrowPath.addArrow (50.0f, 100.0f, 50.0f, 0.0, 40.0f, 100.0f, 50.0f);
  50613. DrawablePath arrowImage;
  50614. arrowImage.setSolidFill (Colours::black.withAlpha (0.4f));
  50615. arrowImage.setPath (arrowPath);
  50616. goUpButton->setImages (&arrowImage);
  50617. return goUpButton;
  50618. }
  50619. void LookAndFeel::layoutFileBrowserComponent (FileBrowserComponent& browserComp,
  50620. DirectoryContentsDisplayComponent* fileListComponent,
  50621. FilePreviewComponent* previewComp,
  50622. ComboBox* currentPathBox,
  50623. TextEditor* filenameBox,
  50624. Button* goUpButton)
  50625. {
  50626. const int x = 8;
  50627. int w = browserComp.getWidth() - x - x;
  50628. if (previewComp != 0)
  50629. {
  50630. const int previewWidth = w / 3;
  50631. previewComp->setBounds (x + w - previewWidth, 0, previewWidth, browserComp.getHeight());
  50632. w -= previewWidth + 4;
  50633. }
  50634. int y = 4;
  50635. const int controlsHeight = 22;
  50636. const int bottomSectionHeight = controlsHeight + 8;
  50637. const int upButtonWidth = 50;
  50638. currentPathBox->setBounds (x, y, w - upButtonWidth - 6, controlsHeight);
  50639. goUpButton->setBounds (x + w - upButtonWidth, y, upButtonWidth, controlsHeight);
  50640. y += controlsHeight + 4;
  50641. Component* const listAsComp = dynamic_cast <Component*> (fileListComponent);
  50642. listAsComp->setBounds (x, y, w, browserComp.getHeight() - y - bottomSectionHeight);
  50643. y = listAsComp->getBottom() + 4;
  50644. filenameBox->setBounds (x + 50, y, w - 50, controlsHeight);
  50645. }
  50646. Image* LookAndFeel::getDefaultFolderImage()
  50647. {
  50648. static const unsigned char foldericon_png[] = { 137,80,78,71,13,10,26,10,0,0,0,13,73,72,68,82,0,0,0,32,0,0,0,28,8,6,0,0,0,0,194,189,34,0,0,0,4,103,65,77,65,0,0,175,200,55,5,
  50649. 138,233,0,0,0,25,116,69,88,116,83,111,102,116,119,97,114,101,0,65,100,111,98,101,32,73,109,97,103,101,82,101,97,100,121,113,201,101,60,0,0,9,46,73,68,65,84,120,218,98,252,255,255,63,3,50,240,41,95,192,
  50650. 197,205,198,32,202,204,202,33,241,254,235,47,133,47,191,24,180,213,164,133,152,69,24,222,44,234,42,77,188,245,31,170,129,145,145,145,1,29,128,164,226,91,86,113,252,248,207,200,171,37,39,204,239,170,43,
  50651. 254,206,218,88,231,61,62,61,0,1,196,2,149,96,116,200,158,102,194,202,201,227,197,193,206,166,194,204,193,33,195,202,204,38,42,197,197,42,196,193,202,33,240,241,231,15,134,151,95,127,9,2,149,22,0,241,47,
  50652. 152,230,128,134,245,204,63,191,188,103,83,144,16,16,228,229,102,151,76,239,217,32,199,204,198,169,205,254,159,65,245,203,79,6,169,131,151,30,47,1,42,91,10,196,127,208,236,101,76,235,90,43,101,160,40,242,
  50653. 19,32,128,64,78,98,52,12,41,149,145,215,52,89,162,38,35,107,39,196,203,203,192,206,194,206,192,197,198,202,192,203,197,198,192,205,193,206,240,252,227,103,134,139,55,175,191,127,243,242,78,219,187,207,
  50654. 63,215,255,98,23,48,228,227,96,83,98,102,102,85,225,224,228,80,20,224,230,86,226,225,228,150,103,101,97,101,230,227,228,96,224,0,234,191,243,252,5,195,222,19,199,38,191,127,112,161,83,66,199,86,141,131,
  50655. 149,69,146,133,153,69,137,149,133,89,157,141,131,77,83,140,143,243,219,255,31,159,123,0,2,136,69,90,207,129,157,71,68,42,66,71,73,209,210,81,91,27,24,142,140,12,127,255,253,103,0,185,236,31,3,144,6,50,
  50656. 148,68,216,25,216,24,117,4,239,11,243,214,49,50,51,84,178,48,114,240,112,177,114,177,240,115,113,49,241,112,112,48,176,179,178,51,176,48,49,3,85,255,99,248,253,247,15,195,247,159,191,25,30,191,126,253,
  50657. 71,74,76,200,66,75,197,119,138,168,144,160,150,168,0,183,160,152,32,15,175,188,184,32,199,175,191,127,25,214,31,184,120,247,236,209,253,159,0,2,136,133,95,70,93,74,88,80,196,83,69,66,130,149,9,104,219,
  50658. 151,31,191,193,150,194,146,6,136,102,102,98,100,16,227,231,103,16,23,210,230,101,101,102,100,248,255,143,137,225,223,63,6,6,22,102,38,134,239,191,126,49,220,123,241,134,225,227,247,175,64,7,252,101,96,
  50659. 97,249,207,192,193,198,200,160,171,34,192,108,165,235,104,42,204,207,101,42,194,199,197,192,199,201,198,192,197,193,202,192,198,202,194,176,247,194,3,134,155,183,110,61,188,127,124,221,19,128,0,92,146,
  50660. 49,14,64,64,16,69,63,153,85,16,52,18,74,71,112,6,87,119,0,165,160,86,138,32,172,216,29,49,182,84,253,169,94,94,230,127,17,87,133,34,146,174,3,88,126,240,219,164,147,113,31,145,244,152,112,179,211,130,
  50661. 34,31,203,113,162,233,6,36,49,163,174,74,124,140,60,141,144,165,161,220,228,25,3,24,105,255,17,168,101,1,139,245,188,93,104,251,73,239,235,50,90,189,111,175,0,98,249,254,254,249,175,239,223,190,126,6,
  50662. 5,27,19,47,90,170,102,0,249,158,129,129,141,133,25,228,20,6,38,38,72,74,7,185,243,243,247,239,12,23,31,60,98,228,231,253,207,144,227,107,206,32,202,199,193,240,249,251,127,134,95,191,255,49,124,249,250,
  50663. 159,225,237,239,95,12,63,127,1,35,229,31,194,71,32,71,63,123,251,245,223,197,27,183,159,189,187,178,103,61,80,232,59,64,0,177,48,252,5,134,225,255,191,223,126,254,250,13,182,132,1,41,167,176,3,53,128,
  50664. 188,254,226,253,103,96,212,252,96,120,247,249,203,255,79,223,191,254,255,250,235,199,191,239,63,191,255,87,145,17,100,73,116,181,100,252,249,243,63,195,149,123,223,193,14,132,101,55,96,52,3,125,255,15,
  50665. 204,254,15,132,160,232,253,13,20,124,248,226,227,223,23,207,30,221,120,119,255,226,109,160,210,31,0,1,196,242,231,219,135,175,140,255,126,190,7,197,37,35,19,34,216,65,248,211,143,111,255,79,223,121,240,
  50666. 255,211,183,79,76,220,156,172,12,236,204,140,140,252,124,28,140,250,226,82,140,106,82,34,140,124,156,156,12,175,222,253,1,90,4,137,162,63,127,33,161,6,178,242,215,239,255,224,160,255,15,198,12,64,7,48,
  50667. 128,211,200,253,151,111,254,254,248,240,236,44,80,217,71,80,246,4,8,32,160,31,255,255,100,102,248,243,238,199,159,63,16,221,16,19,128,248,31,195,181,199,207,254,255,253,247,133,49,212,78,27,104,8,11,40,
  50668. 94,25,184,216,89,129,108,38,70,144,242,183,31,17,105,230,63,148,248,15,97,49,252,248,249,15,20,85,72,105,9,148,187,254,49,220,127,254,242,207,243,75,135,14,128,130,31,84,64,1,4,16,203,247,143,175,127,
  50669. 48,253,254,246,234,7,48,206,96,137,13,4,64,65,248,234,195,7,6,7,3,57,70,33,46,97,134,111,63,254,50,252,5,250,244,51,216,103,255,192,185,0,150,91,80,44,135,242,127,253,129,164,23,24,96,102,250,207,112,
  50670. 255,213,219,255,247,31,63,188,251,246,201,173,199,176,2,13,32,128,88,62,188,121,241,243,211,231,207,31,126,2,147,236,63,168,6,144,193,223,190,255,254,207,198,198,192,40,35,44,206,240,252,205,79,6,132,
  50671. 223,24,224,150,32,251,28,25,128,211,29,19,170,24,51,48,88,111,61,127,206,248,254,245,179,139,192,18,247,219,239,239,95,192,249,9,32,128,88,126,124,249,248,231,203,183,111,159,128,33,240,15,24,68,160,180,
  50672. 2,204,223,140,12,111,63,127,102,16,228,229,4,6,53,35,195,31,176,119,25,112,3,70,84,55,0,203,50,112,33,134,108,249,103,160,7,159,189,126,253,235,235,227,203,7,255,255,251,247,13,86,63,0,4,16,168,46,248,
  50673. 199,250,231,243,235,159,191,126,254,248,245,251,47,23,11,51,51,48,184,152,24,94,127,250,248,95,68,136,151,241,243,55,96,208,51,160,218,255,31,139,27,144,197,254,98,201,202,79,223,124,96,120,245,232,250,
  50674. 185,119,143,174,95,250,243,243,219,119,152,60,64,0,129,2,234,223,183,215,15,95,48,254,255,253,3,146,109,192,229,5,195,135,47,159,25,248,184,121,24,126,0,227,29,88,240,49,252,101,36,14,255,1,90,249,7,156,
  50675. 222,17,24,24,164,12,207,223,189,99,248,250,252,230,97,96,229,245,2,104,231,111,152,3,0,2,8,228,128,191,15,239,220,120,255,255,223,159,47,160,116,0,42,44,222,124,250,244,239,207,255,63,12,236,108,236,64,
  50676. 67,65,81,0,52,244,63,113,248,47,52,10,96,14,98,2,230,191,119,223,127,48,60,121,254,248,235,151,55,207,46,1,163,252,35,114,128,1,4,16,40,10,254,191,121,249,252,199,175,159,63,191,254,2,230,45,118,22,22,
  50677. 134,219,207,94,252,231,224,100,103,250,247,15,148,32,64,85,12,34,14,254,227,72,6,255,225,9,240,63,138,26,46,96,214,189,249,244,37,195,139,167,143,30,124,253,246,253,9,40,245,255,71,202,30,0,1,196,2,226,
  50678. 0,243,232,159,239,63,127,124,253,11,202,94,64,169,23,31,62,50,138,137,242,49,50,0,211,195,223,255,80,7,252,199,159,6,224,137,145,9,146,231,153,160,165,218,23,96,29,240,244,237,59,134,111,175,31,95,250,
  50679. 252,230,241,83,244,182,1,64,0,177,192,28,14,76,132,31,128,169,19,88,220,126,253,207,206,198,196,32,38,36,0,244,61,11,176,148,251,139,145,3,208,29,0,178,16,82,228,66,42,174,223,192,26,8,152,162,25,222,
  50680. 125,248,200,240,242,253,39,134,151,79,238,126,254,242,242,238,177,15,47,30,190,5,215,242,72,0,32,128,224,14,96,254,255,231,61,168,92,123,241,254,253,127,1,62,78,6,78,110,78,134,223,64,195,254,50,98,183,
  50681. 24,36,12,202,179,224,202,9,88,228,253,132,90,250,246,211,71,134,55,175,94,254,122,255,250,249,247,15,175,159,126,249,251,237,195,135,95,175,110,31,122,117,251,244,49,160,150,111,255,209,218,128,0,1,152,
  50682. 44,183,21,0,65,32,136,110,247,254,255,243,122,9,187,64,105,174,74,22,138,25,173,80,208,194,188,238,156,151,217,217,15,32,182,197,37,83,201,4,31,243,178,169,232,242,214,224,223,252,103,175,35,85,1,41,129,
  50683. 228,148,142,8,214,30,32,149,6,161,204,109,182,53,236,184,156,78,142,147,195,153,89,35,198,3,87,166,249,220,227,198,59,218,48,252,223,185,111,30,1,132,228,128,127,31,222,124,248,248,27,24,152,28,60,220,
  50684. 220,12,44,172,172,224,224,103,5,102,98,144,133,160,236,244,229,231,47,134,239,223,127,49,188,121,251,158,225,241,179,103,12,31,223,189,254,251,227,221,139,55,191,62,188,120,246,235,205,189,59,207,238,
  50685. 94,58,241,228,254,109,144,101,159,128,248,51,40,9,32,97,80,217,255,15,221,1,0,1,4,143,130,207,159,191,126,252,246,234,213,111,94,126,94,118,73,94,9,198,127,64,223,126,252,246,147,225,243,215,239,12,223,
  50686. 128,229,198,251,15,239,24,62,189,126,249,227,203,171,135,47,63,189,122,252,228,235,155,199,247,95,63,188,118,227,197,227,123,247,127,255,250,249,30,104,198,7,32,126,11,181,252,7,212,183,160,4,247,7,155,
  50687. 197,48,0,16,64,112,7,60,121,241,238,189,16,207,15,134,63,63,216,25,95,125,248,198,112,227,241,27,134,15,239,223,50,124,126,245,228,253,143,55,143,158,191,123,116,237,226,171,135,55,175,126,253,252,225,
  50688. 229,183,47,159,95,254,253,245,227,253,175,159,223,223,193,124,7,181,20,84,105,252,70,143,103,124,0,32,128,224,14,224,102,253,251,81,144,253,223,235,167,207,30,254,124,127,231,252,155,143,175,159,188,250,
  50689. 246,254,249,125,96,60,62,248,250,233,253,147,119,207,238,221,6,150,214,175,129,106,191,130,18,19,146,133,120,125,72,8,0,4,16,34,27,190,121,112,251,3,211,159,69,143,110,223,229,120,255,232,230,221,215,
  50690. 79,239,62,4,102,203,207,72,241,9,11,218,63,72,89,137,20,207,98,100,93,16,0,8,32,70,144,1,64,14,168,209,199,7,196,194,160,166,27,212,135,95,96,65,10,173,95,254,34,219,6,51,128,88,7,96,235,21,129,0,64,0,
  50691. 193,28,192,8,174,53,33,152,1,155,133,184,12,196,165,4,151,133,232,0,32,192,0,151,97,210,163,246,134,208,52,0,0,0,0,73,69,78,68,174,66,96,130,0,0};
  50692. return ImageCache::getFromMemory (foldericon_png, sizeof (foldericon_png));
  50693. }
  50694. Image* LookAndFeel::getDefaultDocumentFileImage()
  50695. {
  50696. static const unsigned char fileicon_png[] = { 137,80,78,71,13,10,26,10,0,0,0,13,73,72,68,82,0,0,0,32,0,0,0,32,8,6,0,0,0,115,122,122,244,0,0,0,4,103,65,77,65,0,0,175,200,55,5,
  50697. 138,233,0,0,0,25,116,69,88,116,83,111,102,116,119,97,114,101,0,65,100,111,98,101,32,73,109,97,103,101,82,101,97,100,121,113,201,101,60,0,0,4,99,73,68,65,84,120,218,98,252,255,255,63,3,12,48,50,50,50,1,
  50698. 169,127,200,98,148,2,160,153,204,64,243,254,226,146,7,8,32,22,52,203,255,107,233,233,91,76,93,176,184,232,239,239,95,127,24,40,112,8,19,51,203,255,179,23,175,108,1,90,190,28,104,54,43,80,232,207,127,44,
  50699. 62,3,8,32,6,144,24,84,156,25,132,189,252,3,146,255,83,9,220,127,254,242,134,162,138,170,10,208,92,144,3,152,97,118,33,99,128,0,98,66,114,11,200,1,92,255,254,252,225,32,215,215,32,127,64,240,127,80,60,
  50700. 50,40,72,136,169,47,95,179,118,130,136,148,140,0,40,80,128,33,193,136,174,7,32,128,144,29,192,8,117,41,59,209,22,66,241,191,255,16,12,244,19,195,63,48,134,240,255,0,9,115,125,93,239,252,130,130,108,168,
  50701. 249,44,232,102,0,4,16,19,22,62,51,33,11,255,195,44,4,211,255,25,96,16,33,6,117,24,56,226,25,24,202,139,10,75,226,51,115,66,160,105,13,197,17,0,1,196,68,172,79,255,33,91,206,192,192,128,176,22,17,10,200,
  50702. 234,32,161,240,31,24,10,255,24,152,153,153,184,39,244,247,117,107,234,234,105,131,66,1,154,224,193,0,32,128,240,58,0,22,180,255,144,18,13,40,136,33,113,140,36,255,15,17,26,48,12,81,15,145,255,254,251,
  50703. 31,131,0,59,171,84,81,73,105,33,208,216,191,200,161,12,16,64,44,248,131,251,63,10,31,198,253,143,38,6,83,7,11,33,228,232,2,123,4,202,226,228,96,151,132,166,49,144,35,126,131,196,0,2,136,5,103,60,51,252,
  50704. 71,49,12,213,130,255,168,226,232,150,254,255,15,143,6,80,202,3,133,16,200,198,63,127,193,229,17,39,16,127,135,217,7,16,64,88,67,0,28,143,255,25,225,46,135,249,18,155,133,240,178,4,205,145,8,62,52,186,
  50705. 32,234,152,160,118,194,179,35,64,0,177,96,11,123,144,236,95,104,92,162,228,113,36,11,81,125,140,112,56,186,131,96,226,176,172,137,148,229,193,0,32,128,88,112,167,248,255,112,223,48,34,165,110,6,124,190,
  50706. 253,143,61,106,192,9,19,73,28,25,0,4,16,206,40,248,251,15,45,104,209,130,21,51,222,145,18,238,127,180,68,8,244,250,95,164,16,66,6,0,1,196,130,45,253,195,12,250,135,53,206,255,195,131,18,213,98,236,81,
  50707. 243,31,154,11,144,115,8,50,0,8,32,156,81,0,203,227,12,80,223,98,230,4,68,72,96,38,78,84,11,65,9,250,47,146,3,145,1,64,0,97,117,192,95,112,34,68,138,130,255,176,224,251,143,226,51,6,6,68,29,192,136,20,
  50708. 77,200,69,54,35,3,36,49,255,69,77,132,112,0,16,64,44,56,139,94,36,7,96,102,59,164,108,249,31,181,82,98,64,203,174,255,144,234,142,127,88,146,33,64,0,97,205,134,240,120,67,75,76,136,224,198,140,22,6,44,
  50709. 142,66,201,41,255,177,231,2,128,0,194,25,5,255,254,161,134,192,127,6,28,229,0,129,242,1,150,56,33,81,138,209,28,96,0,8,32,172,81,0,78,3,104,190,68,182,224,31,146,197,224,56,6,146,140,176,202,135,17,169,
  50710. 96,130,40,64,56,0,139,93,0,1,132,61,10,64,248,31,106,156,162,199,55,204,65,255,144,178,38,74,84,252,71,51,239,63,246,68,8,16,64,44,216,74,1,88,217,13,203,191,32,1,80,58,7,133,224,127,6,68,114,6,241,65,
  50711. 81,197,8,101,255,71,114,33,92,237,127,228,52,128,233,2,128,0,98,193,149,3,64,117,193,255,127,255,81,75,191,127,168,5,18,136,255,31,45,161,49,32,151,134,72,252,127,12,216,203,98,128,0,98,193,210,144,135,
  50712. 248,30,201,242,127,208,252,140,145,27,160,113,206,136,148,197,192,121,159,17,53,184,225,149,17,22,23,0,4,16,11,182,150,237,63,168,207,96,142,248,143,163,72,6,203,253,67,13,61,6,104,14,66,46,17,254,65,
  50713. 19,40,182,16,0,8,32,22,108,109,235,255,176,234,24,35,79,255,199,222,30,64,81,135,90,35,194,211,4,142,92,0,16,64,88,29,0,107,7,254,251,247,31,53,78,241,54,207,80,29,135,209,96,249,143,189,46,0,8,32,116,
  50714. 7,252,101,102,103,103,228,103,99,96,248,193,198,137,53,248,49,125,204,128,225,227,255,88,18,54,47,176,25,202,205,195,205,6,109,11,194,149,0,4,16,35,204,85,208,254,27,159,128,176,176,142,166,182,142,21,
  50715. 48,4,248,129,41,143,13,217,16,70,52,95,147,0,254,0,187,69,95,223,188,122,125,235,206,141,107,7,129,252,247,64,123,193,237,66,128,0,66,118,0,168,189,198,3,196,252,32,135,64,105,54,228,230,19,185,29,100,
  50716. 168,175,191,0,241,7,32,254,4,196,159,129,246,254,2,73,2,4,16,11,90,72,125,135,210,63,161,138,153,169,212,75,255,15,117,196,15,40,134,119,215,1,2,12,0,187,0,132,247,216,161,197,124,0,0,0,0,73,69,78,68,
  50717. 174,66,96,130,0,0};
  50718. return ImageCache::getFromMemory (fileicon_png, sizeof (fileicon_png));
  50719. }
  50720. void LookAndFeel::playAlertSound()
  50721. {
  50722. PlatformUtilities::beep();
  50723. }
  50724. void LookAndFeel::drawLevelMeter (Graphics& g, int width, int height, float level)
  50725. {
  50726. g.setColour (Colours::white.withAlpha (0.7f));
  50727. g.fillRoundedRectangle (0.0f, 0.0f, (float) width, (float) height, 3.0f);
  50728. g.setColour (Colours::black.withAlpha (0.2f));
  50729. g.drawRoundedRectangle (1.0f, 1.0f, width - 2.0f, height - 2.0f, 3.0f, 1.0f);
  50730. const int totalBlocks = 7;
  50731. const int numBlocks = roundDoubleToInt (totalBlocks * level);
  50732. const float w = (width - 6.0f) / (float) totalBlocks;
  50733. for (int i = 0; i < totalBlocks; ++i)
  50734. {
  50735. if (i >= numBlocks)
  50736. g.setColour (Colours::lightblue.withAlpha (0.6f));
  50737. else
  50738. g.setColour (i < totalBlocks - 1 ? Colours::blue.withAlpha (0.5f)
  50739. : Colours::red);
  50740. g.fillRoundedRectangle (3.0f + i * w + w * 0.1f, 3.0f, w * 0.8f, height - 6.0f, w * 0.4f);
  50741. }
  50742. }
  50743. static void createRoundedPath (Path& p,
  50744. const float x, const float y,
  50745. const float w, const float h,
  50746. const float cs,
  50747. const bool curveTopLeft, const bool curveTopRight,
  50748. const bool curveBottomLeft, const bool curveBottomRight) throw()
  50749. {
  50750. const float cs2 = 2.0f * cs;
  50751. if (curveTopLeft)
  50752. {
  50753. p.startNewSubPath (x, y + cs);
  50754. p.addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f);
  50755. }
  50756. else
  50757. {
  50758. p.startNewSubPath (x, y);
  50759. }
  50760. if (curveTopRight)
  50761. {
  50762. p.lineTo (x + w - cs, y);
  50763. p.addArc (x + w - cs2, y, cs2, cs2, 0.0f, float_Pi * 0.5f);
  50764. }
  50765. else
  50766. {
  50767. p.lineTo (x + w, y);
  50768. }
  50769. if (curveBottomRight)
  50770. {
  50771. p.lineTo (x + w, y + h - cs);
  50772. p.addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  50773. }
  50774. else
  50775. {
  50776. p.lineTo (x + w, y + h);
  50777. }
  50778. if (curveBottomLeft)
  50779. {
  50780. p.lineTo (x + cs, y + h);
  50781. p.addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  50782. }
  50783. else
  50784. {
  50785. p.lineTo (x, y + h);
  50786. }
  50787. p.closeSubPath();
  50788. }
  50789. void LookAndFeel::drawShinyButtonShape (Graphics& g,
  50790. float x, float y, float w, float h,
  50791. float maxCornerSize,
  50792. const Colour& baseColour,
  50793. const float strokeWidth,
  50794. const bool flatOnLeft,
  50795. const bool flatOnRight,
  50796. const bool flatOnTop,
  50797. const bool flatOnBottom) throw()
  50798. {
  50799. if (w <= strokeWidth * 1.1f || h <= strokeWidth * 1.1f)
  50800. return;
  50801. const float cs = jmin (maxCornerSize, w * 0.5f, h * 0.5f);
  50802. Path outline;
  50803. createRoundedPath (outline, x, y, w, h, cs,
  50804. ! (flatOnLeft || flatOnTop),
  50805. ! (flatOnRight || flatOnTop),
  50806. ! (flatOnLeft || flatOnBottom),
  50807. ! (flatOnRight || flatOnBottom));
  50808. ColourGradient cg (baseColour, 0.0f, y,
  50809. baseColour.overlaidWith (Colour (0x070000ff)), 0.0f, y + h,
  50810. false);
  50811. cg.addColour (0.5, baseColour.overlaidWith (Colour (0x33ffffff)));
  50812. cg.addColour (0.51, baseColour.overlaidWith (Colour (0x110000ff)));
  50813. GradientBrush gb (cg);
  50814. g.setBrush (&gb);
  50815. g.fillPath (outline);
  50816. g.setColour (Colour (0x80000000));
  50817. g.strokePath (outline, PathStrokeType (strokeWidth));
  50818. }
  50819. void LookAndFeel::drawGlassSphere (Graphics& g,
  50820. const float x, const float y,
  50821. const float diameter,
  50822. const Colour& colour,
  50823. const float outlineThickness) throw()
  50824. {
  50825. if (diameter <= outlineThickness)
  50826. return;
  50827. Path p;
  50828. p.addEllipse (x, y, diameter, diameter);
  50829. {
  50830. ColourGradient cg (Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y,
  50831. Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y + diameter, false);
  50832. cg.addColour (0.4, Colours::white.overlaidWith (colour));
  50833. GradientBrush gb (cg);
  50834. g.setBrush (&gb);
  50835. g.fillPath (p);
  50836. }
  50837. {
  50838. GradientBrush gb (Colours::white, 0, y + diameter * 0.06f,
  50839. Colours::transparentWhite, 0, y + diameter * 0.3f, false);
  50840. g.setBrush (&gb);
  50841. g.fillEllipse (x + diameter * 0.2f, y + diameter * 0.05f, diameter * 0.6f, diameter * 0.4f);
  50842. }
  50843. {
  50844. ColourGradient cg (Colours::transparentBlack,
  50845. x + diameter * 0.5f, y + diameter * 0.5f,
  50846. Colours::black.withAlpha (0.5f * outlineThickness * colour.getFloatAlpha()),
  50847. x, y + diameter * 0.5f, true);
  50848. cg.addColour (0.7, Colours::transparentBlack);
  50849. cg.addColour (0.8, Colours::black.withAlpha (0.1f * outlineThickness));
  50850. GradientBrush gb (cg);
  50851. g.setBrush (&gb);
  50852. g.fillPath (p);
  50853. }
  50854. g.setColour (Colours::black.withAlpha (0.5f * colour.getFloatAlpha()));
  50855. g.drawEllipse (x, y, diameter, diameter, outlineThickness);
  50856. }
  50857. void LookAndFeel::drawGlassPointer (Graphics& g,
  50858. const float x, const float y,
  50859. const float diameter,
  50860. const Colour& colour, const float outlineThickness,
  50861. const int direction) throw()
  50862. {
  50863. if (diameter <= outlineThickness)
  50864. return;
  50865. Path p;
  50866. p.startNewSubPath (x + diameter * 0.5f, y);
  50867. p.lineTo (x + diameter, y + diameter * 0.6f);
  50868. p.lineTo (x + diameter, y + diameter);
  50869. p.lineTo (x, y + diameter);
  50870. p.lineTo (x, y + diameter * 0.6f);
  50871. p.closeSubPath();
  50872. p.applyTransform (AffineTransform::rotation (direction * (float_Pi * 0.5f), x + diameter * 0.5f, y + diameter * 0.5f));
  50873. {
  50874. ColourGradient cg (Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y,
  50875. Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y + diameter, false);
  50876. cg.addColour (0.4, Colours::white.overlaidWith (colour));
  50877. GradientBrush gb (cg);
  50878. g.setBrush (&gb);
  50879. g.fillPath (p);
  50880. }
  50881. {
  50882. ColourGradient cg (Colours::transparentBlack,
  50883. x + diameter * 0.5f, y + diameter * 0.5f,
  50884. Colours::black.withAlpha (0.5f * outlineThickness * colour.getFloatAlpha()),
  50885. x - diameter * 0.2f, y + diameter * 0.5f, true);
  50886. cg.addColour (0.5, Colours::transparentBlack);
  50887. cg.addColour (0.7, Colours::black.withAlpha (0.07f * outlineThickness));
  50888. GradientBrush gb (cg);
  50889. g.setBrush (&gb);
  50890. g.fillPath (p);
  50891. }
  50892. g.setColour (Colours::black.withAlpha (0.5f * colour.getFloatAlpha()));
  50893. g.strokePath (p, PathStrokeType (outlineThickness));
  50894. }
  50895. void LookAndFeel::drawGlassLozenge (Graphics& g,
  50896. const float x, const float y,
  50897. const float width, const float height,
  50898. const Colour& colour,
  50899. const float outlineThickness,
  50900. const float cornerSize,
  50901. const bool flatOnLeft,
  50902. const bool flatOnRight,
  50903. const bool flatOnTop,
  50904. const bool flatOnBottom) throw()
  50905. {
  50906. if (width <= outlineThickness || height <= outlineThickness)
  50907. return;
  50908. const int intX = (int) x;
  50909. const int intY = (int) y;
  50910. const int intW = (int) width;
  50911. const int intH = (int) height;
  50912. const float cs = cornerSize < 0 ? jmin (width * 0.5f, height * 0.5f) : cornerSize;
  50913. const float edgeBlurRadius = height * 0.75f + (height - cs * 2.0f);
  50914. const int intEdge = (int) edgeBlurRadius;
  50915. Path outline;
  50916. createRoundedPath (outline, x, y, width, height, cs,
  50917. ! (flatOnLeft || flatOnTop),
  50918. ! (flatOnRight || flatOnTop),
  50919. ! (flatOnLeft || flatOnBottom),
  50920. ! (flatOnRight || flatOnBottom));
  50921. {
  50922. ColourGradient cg (colour.darker (0.2f), 0, y,
  50923. colour.darker (0.2f), 0, y + height, false);
  50924. cg.addColour (0.03, colour.withMultipliedAlpha (0.3f));
  50925. cg.addColour (0.4, colour);
  50926. cg.addColour (0.97, colour.withMultipliedAlpha (0.3f));
  50927. GradientBrush gb (cg);
  50928. g.setBrush (&gb);
  50929. g.fillPath (outline);
  50930. }
  50931. ColourGradient cg (Colours::transparentBlack, x + edgeBlurRadius, y + height * 0.5f,
  50932. colour.darker (0.2f), x, y + height * 0.5f, true);
  50933. cg.addColour (jlimit (0.0, 1.0, 1.0 - (cs * 0.5f) / edgeBlurRadius), Colours::transparentBlack);
  50934. cg.addColour (jlimit (0.0, 1.0, 1.0 - (cs * 0.25f) / edgeBlurRadius), colour.darker (0.2f).withMultipliedAlpha (0.3f));
  50935. if (! (flatOnLeft || flatOnTop || flatOnBottom))
  50936. {
  50937. GradientBrush gb (cg);
  50938. g.saveState();
  50939. g.setBrush (&gb);
  50940. g.reduceClipRegion (intX, intY, intEdge, intH);
  50941. g.fillPath (outline);
  50942. g.restoreState();
  50943. }
  50944. if (! (flatOnRight || flatOnTop || flatOnBottom))
  50945. {
  50946. cg.x1 = x + width - edgeBlurRadius;
  50947. cg.x2 = x + width;
  50948. GradientBrush gb (cg);
  50949. g.saveState();
  50950. g.setBrush (&gb);
  50951. g.reduceClipRegion (intX + intW - intEdge, intY, 2 + intEdge, intH);
  50952. g.fillPath (outline);
  50953. g.restoreState();
  50954. }
  50955. {
  50956. const float leftIndent = flatOnLeft ? 0.0f : cs * 0.4f;
  50957. const float rightIndent = flatOnRight ? 0.0f : cs * 0.4f;
  50958. Path highlight;
  50959. createRoundedPath (highlight,
  50960. x + leftIndent,
  50961. y + cs * 0.1f,
  50962. width - (leftIndent + rightIndent),
  50963. height * 0.4f, cs * 0.4f,
  50964. ! (flatOnLeft || flatOnTop),
  50965. ! (flatOnRight || flatOnTop),
  50966. ! (flatOnLeft || flatOnBottom),
  50967. ! (flatOnRight || flatOnBottom));
  50968. GradientBrush gb (colour.brighter (10.0f), 0, y + height * 0.06f,
  50969. Colours::transparentWhite, 0, y + height * 0.4f, false);
  50970. g.setBrush (&gb);
  50971. g.fillPath (highlight);
  50972. }
  50973. g.setColour (colour.darker().withMultipliedAlpha (1.5f));
  50974. g.strokePath (outline, PathStrokeType (outlineThickness));
  50975. }
  50976. END_JUCE_NAMESPACE
  50977. /********* End of inlined file: juce_LookAndFeel.cpp *********/
  50978. /********* Start of inlined file: juce_OldSchoolLookAndFeel.cpp *********/
  50979. BEGIN_JUCE_NAMESPACE
  50980. OldSchoolLookAndFeel::OldSchoolLookAndFeel()
  50981. {
  50982. setColour (TextButton::buttonColourId, Colour (0xffbbbbff));
  50983. setColour (ListBox::outlineColourId, findColour (ComboBox::outlineColourId));
  50984. setColour (ScrollBar::thumbColourId, Colour (0xffbbbbdd));
  50985. setColour (ScrollBar::backgroundColourId, Colours::transparentBlack);
  50986. setColour (Slider::thumbColourId, Colours::white);
  50987. setColour (Slider::trackColourId, Colour (0x7f000000));
  50988. setColour (Slider::textBoxOutlineColourId, Colours::grey);
  50989. setColour (ProgressBar::backgroundColourId, Colours::white.withAlpha (0.6f));
  50990. setColour (ProgressBar::foregroundColourId, Colours::green.withAlpha (0.7f));
  50991. setColour (PopupMenu::backgroundColourId, Colour (0xffeef5f8));
  50992. setColour (PopupMenu::highlightedBackgroundColourId, Colour (0xbfa4c2ce));
  50993. setColour (PopupMenu::highlightedTextColourId, Colours::black);
  50994. setColour (TextEditor::focusedOutlineColourId, findColour (TextButton::buttonColourId));
  50995. scrollbarShadow.setShadowProperties (2.2f, 0.5f, 0, 0);
  50996. }
  50997. OldSchoolLookAndFeel::~OldSchoolLookAndFeel()
  50998. {
  50999. }
  51000. void OldSchoolLookAndFeel::drawButtonBackground (Graphics& g,
  51001. Button& button,
  51002. const Colour& backgroundColour,
  51003. bool isMouseOverButton,
  51004. bool isButtonDown)
  51005. {
  51006. const int width = button.getWidth();
  51007. const int height = button.getHeight();
  51008. const float indent = 2.0f;
  51009. const int cornerSize = jmin (roundFloatToInt (width * 0.4f),
  51010. roundFloatToInt (height * 0.4f));
  51011. Path p;
  51012. p.addRoundedRectangle (indent, indent,
  51013. width - indent * 2.0f,
  51014. height - indent * 2.0f,
  51015. (float) cornerSize);
  51016. Colour bc (backgroundColour.withMultipliedSaturation (0.3f));
  51017. if (isMouseOverButton)
  51018. {
  51019. if (isButtonDown)
  51020. bc = bc.brighter();
  51021. else if (bc.getBrightness() > 0.5f)
  51022. bc = bc.darker (0.1f);
  51023. else
  51024. bc = bc.brighter (0.1f);
  51025. }
  51026. g.setColour (bc);
  51027. g.fillPath (p);
  51028. g.setColour (bc.contrasting().withAlpha ((isMouseOverButton) ? 0.6f : 0.4f));
  51029. g.strokePath (p, PathStrokeType ((isMouseOverButton) ? 2.0f : 1.4f));
  51030. }
  51031. void OldSchoolLookAndFeel::drawTickBox (Graphics& g,
  51032. Component& /*component*/,
  51033. int x, int y, int w, int h,
  51034. const bool ticked,
  51035. const bool isEnabled,
  51036. const bool /*isMouseOverButton*/,
  51037. const bool isButtonDown)
  51038. {
  51039. Path box;
  51040. box.addRoundedRectangle (0.0f, 2.0f, 6.0f, 6.0f, 1.0f);
  51041. g.setColour (isEnabled ? Colours::blue.withAlpha (isButtonDown ? 0.3f : 0.1f)
  51042. : Colours::lightgrey.withAlpha (0.1f));
  51043. AffineTransform trans (AffineTransform::scale (w / 9.0f, h / 9.0f)
  51044. .translated ((float) x, (float) y));
  51045. g.fillPath (box, trans);
  51046. g.setColour (Colours::black.withAlpha (0.6f));
  51047. g.strokePath (box, PathStrokeType (0.9f), trans);
  51048. if (ticked)
  51049. {
  51050. Path tick;
  51051. tick.startNewSubPath (1.5f, 3.0f);
  51052. tick.lineTo (3.0f, 6.0f);
  51053. tick.lineTo (6.0f, 0.0f);
  51054. g.setColour (isEnabled ? Colours::black : Colours::grey);
  51055. g.strokePath (tick, PathStrokeType (2.5f), trans);
  51056. }
  51057. }
  51058. void OldSchoolLookAndFeel::drawToggleButton (Graphics& g,
  51059. ToggleButton& button,
  51060. bool isMouseOverButton,
  51061. bool isButtonDown)
  51062. {
  51063. if (button.hasKeyboardFocus (true))
  51064. {
  51065. g.setColour (button.findColour (TextEditor::focusedOutlineColourId));
  51066. g.drawRect (0, 0, button.getWidth(), button.getHeight());
  51067. }
  51068. const int tickWidth = jmin (20, button.getHeight() - 4);
  51069. drawTickBox (g, button, 4, (button.getHeight() - tickWidth) / 2,
  51070. tickWidth, tickWidth,
  51071. button.getToggleState(),
  51072. button.isEnabled(),
  51073. isMouseOverButton,
  51074. isButtonDown);
  51075. g.setColour (button.findColour (ToggleButton::textColourId));
  51076. g.setFont (jmin (15.0f, button.getHeight() * 0.6f));
  51077. if (! button.isEnabled())
  51078. g.setOpacity (0.5f);
  51079. const int textX = tickWidth + 5;
  51080. g.drawFittedText (button.getButtonText(),
  51081. textX, 4,
  51082. button.getWidth() - textX - 2, button.getHeight() - 8,
  51083. Justification::centredLeft, 10);
  51084. }
  51085. void OldSchoolLookAndFeel::drawProgressBar (Graphics& g, ProgressBar& progressBar,
  51086. int width, int height,
  51087. double progress, const String& textToShow)
  51088. {
  51089. if (progress < 0 || progress >= 1.0)
  51090. {
  51091. LookAndFeel::drawProgressBar (g, progressBar, width, height, progress, textToShow);
  51092. }
  51093. else
  51094. {
  51095. const Colour background (progressBar.findColour (ProgressBar::backgroundColourId));
  51096. const Colour foreground (progressBar.findColour (ProgressBar::foregroundColourId));
  51097. g.fillAll (background);
  51098. g.setColour (foreground);
  51099. g.fillRect (1, 1,
  51100. jlimit (0, width - 2, roundDoubleToInt (progress * (width - 2))),
  51101. height - 2);
  51102. if (textToShow.isNotEmpty())
  51103. {
  51104. g.setColour (Colour::contrasting (background, foreground));
  51105. g.setFont (height * 0.6f);
  51106. g.drawText (textToShow, 0, 0, width, height, Justification::centred, false);
  51107. }
  51108. }
  51109. }
  51110. void OldSchoolLookAndFeel::drawScrollbarButton (Graphics& g,
  51111. ScrollBar& bar,
  51112. int width, int height,
  51113. int buttonDirection,
  51114. bool isScrollbarVertical,
  51115. bool isMouseOverButton,
  51116. bool isButtonDown)
  51117. {
  51118. if (isScrollbarVertical)
  51119. width -= 2;
  51120. else
  51121. height -= 2;
  51122. Path p;
  51123. if (buttonDirection == 0)
  51124. p.addTriangle (width * 0.5f, height * 0.2f,
  51125. width * 0.1f, height * 0.7f,
  51126. width * 0.9f, height * 0.7f);
  51127. else if (buttonDirection == 1)
  51128. p.addTriangle (width * 0.8f, height * 0.5f,
  51129. width * 0.3f, height * 0.1f,
  51130. width * 0.3f, height * 0.9f);
  51131. else if (buttonDirection == 2)
  51132. p.addTriangle (width * 0.5f, height * 0.8f,
  51133. width * 0.1f, height * 0.3f,
  51134. width * 0.9f, height * 0.3f);
  51135. else if (buttonDirection == 3)
  51136. p.addTriangle (width * 0.2f, height * 0.5f,
  51137. width * 0.7f, height * 0.1f,
  51138. width * 0.7f, height * 0.9f);
  51139. if (isButtonDown)
  51140. g.setColour (Colours::white);
  51141. else if (isMouseOverButton)
  51142. g.setColour (Colours::white.withAlpha (0.7f));
  51143. else
  51144. g.setColour (bar.findColour (ScrollBar::thumbColourId).withAlpha (0.5f));
  51145. g.fillPath (p);
  51146. g.setColour (Colours::black.withAlpha (0.5f));
  51147. g.strokePath (p, PathStrokeType (0.5f));
  51148. }
  51149. void OldSchoolLookAndFeel::drawScrollbar (Graphics& g,
  51150. ScrollBar& bar,
  51151. int x, int y,
  51152. int width, int height,
  51153. bool isScrollbarVertical,
  51154. int thumbStartPosition,
  51155. int thumbSize,
  51156. bool isMouseOver,
  51157. bool isMouseDown)
  51158. {
  51159. g.fillAll (bar.findColour (ScrollBar::backgroundColourId));
  51160. g.setColour (bar.findColour (ScrollBar::thumbColourId)
  51161. .withAlpha ((isMouseOver || isMouseDown) ? 0.4f : 0.15f));
  51162. if (thumbSize > 0.0f)
  51163. {
  51164. Rectangle thumb;
  51165. if (isScrollbarVertical)
  51166. {
  51167. width -= 2;
  51168. g.fillRect (x + roundFloatToInt (width * 0.35f), y,
  51169. roundFloatToInt (width * 0.3f), height);
  51170. thumb.setBounds (x + 1, thumbStartPosition,
  51171. width - 2, thumbSize);
  51172. }
  51173. else
  51174. {
  51175. height -= 2;
  51176. g.fillRect (x, y + roundFloatToInt (height * 0.35f),
  51177. width, roundFloatToInt (height * 0.3f));
  51178. thumb.setBounds (thumbStartPosition, y + 1,
  51179. thumbSize, height - 2);
  51180. }
  51181. g.setColour (bar.findColour (ScrollBar::thumbColourId)
  51182. .withAlpha ((isMouseOver || isMouseDown) ? 0.95f : 0.7f));
  51183. g.fillRect (thumb);
  51184. g.setColour (Colours::black.withAlpha ((isMouseOver || isMouseDown) ? 0.4f : 0.25f));
  51185. g.drawRect (thumb.getX(), thumb.getY(), thumb.getWidth(), thumb.getHeight());
  51186. if (thumbSize > 16)
  51187. {
  51188. for (int i = 3; --i >= 0;)
  51189. {
  51190. const float linePos = thumbStartPosition + thumbSize / 2 + (i - 1) * 4.0f;
  51191. g.setColour (Colours::black.withAlpha (0.15f));
  51192. if (isScrollbarVertical)
  51193. {
  51194. g.drawLine (x + width * 0.2f, linePos, width * 0.8f, linePos);
  51195. g.setColour (Colours::white.withAlpha (0.15f));
  51196. g.drawLine (width * 0.2f, linePos - 1, width * 0.8f, linePos - 1);
  51197. }
  51198. else
  51199. {
  51200. g.drawLine (linePos, height * 0.2f, linePos, height * 0.8f);
  51201. g.setColour (Colours::white.withAlpha (0.15f));
  51202. g.drawLine (linePos - 1, height * 0.2f, linePos - 1, height * 0.8f);
  51203. }
  51204. }
  51205. }
  51206. }
  51207. }
  51208. ImageEffectFilter* OldSchoolLookAndFeel::getScrollbarEffect()
  51209. {
  51210. return &scrollbarShadow;
  51211. }
  51212. void OldSchoolLookAndFeel::drawPopupMenuBackground (Graphics& g, int width, int height)
  51213. {
  51214. g.fillAll (findColour (PopupMenu::backgroundColourId));
  51215. g.setColour (Colours::black.withAlpha (0.6f));
  51216. g.drawRect (0, 0, width, height);
  51217. }
  51218. void OldSchoolLookAndFeel::drawMenuBarBackground (Graphics& g, int /*width*/, int /*height*/,
  51219. bool, MenuBarComponent& menuBar)
  51220. {
  51221. g.fillAll (menuBar.findColour (PopupMenu::backgroundColourId));
  51222. }
  51223. void OldSchoolLookAndFeel::drawTextEditorOutline (Graphics& g, int width, int height, TextEditor& textEditor)
  51224. {
  51225. if (textEditor.isEnabled())
  51226. {
  51227. g.setColour (textEditor.findColour (TextEditor::outlineColourId));
  51228. g.drawRect (0, 0, width, height);
  51229. }
  51230. }
  51231. void OldSchoolLookAndFeel::drawComboBox (Graphics& g, int width, int height,
  51232. const bool isButtonDown,
  51233. int buttonX, int buttonY,
  51234. int buttonW, int buttonH,
  51235. ComboBox& box)
  51236. {
  51237. g.fillAll (box.findColour (ComboBox::backgroundColourId));
  51238. g.setColour (box.findColour ((isButtonDown) ? ComboBox::buttonColourId
  51239. : ComboBox::backgroundColourId));
  51240. g.fillRect (buttonX, buttonY, buttonW, buttonH);
  51241. g.setColour (box.findColour (ComboBox::outlineColourId));
  51242. g.drawRect (0, 0, width, height);
  51243. const float arrowX = 0.2f;
  51244. const float arrowH = 0.3f;
  51245. if (box.isEnabled())
  51246. {
  51247. Path p;
  51248. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.45f - arrowH),
  51249. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.45f,
  51250. buttonX + buttonW * arrowX, buttonY + buttonH * 0.45f);
  51251. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.55f + arrowH),
  51252. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.55f,
  51253. buttonX + buttonW * arrowX, buttonY + buttonH * 0.55f);
  51254. g.setColour (box.findColour ((isButtonDown) ? ComboBox::backgroundColourId
  51255. : ComboBox::buttonColourId));
  51256. g.fillPath (p);
  51257. }
  51258. }
  51259. const Font OldSchoolLookAndFeel::getComboBoxFont (ComboBox& box)
  51260. {
  51261. Font f (jmin (15.0f, box.getHeight() * 0.85f));
  51262. f.setHorizontalScale (0.9f);
  51263. return f;
  51264. }
  51265. static void drawTriangle (Graphics& g, float x1, float y1, float x2, float y2, float x3, float y3, const Colour& fill, const Colour& outline) throw()
  51266. {
  51267. Path p;
  51268. p.addTriangle (x1, y1, x2, y2, x3, y3);
  51269. g.setColour (fill);
  51270. g.fillPath (p);
  51271. g.setColour (outline);
  51272. g.strokePath (p, PathStrokeType (0.3f));
  51273. }
  51274. void OldSchoolLookAndFeel::drawLinearSlider (Graphics& g,
  51275. int x, int y,
  51276. int w, int h,
  51277. float sliderPos,
  51278. float minSliderPos,
  51279. float maxSliderPos,
  51280. const Slider::SliderStyle style,
  51281. Slider& slider)
  51282. {
  51283. g.fillAll (slider.findColour (Slider::backgroundColourId));
  51284. if (style == Slider::LinearBar)
  51285. {
  51286. g.setColour (slider.findColour (Slider::thumbColourId));
  51287. g.fillRect (x, y, (int) sliderPos - x, h);
  51288. g.setColour (slider.findColour (Slider::textBoxTextColourId).withMultipliedAlpha (0.5f));
  51289. g.drawRect (x, y, (int) sliderPos - x, h);
  51290. }
  51291. else
  51292. {
  51293. g.setColour (slider.findColour (Slider::trackColourId)
  51294. .withMultipliedAlpha (slider.isEnabled() ? 1.0f : 0.3f));
  51295. if (slider.isHorizontal())
  51296. {
  51297. g.fillRect (x, y + roundFloatToInt (h * 0.6f),
  51298. w, roundFloatToInt (h * 0.2f));
  51299. }
  51300. else
  51301. {
  51302. g.fillRect (x + roundFloatToInt (w * 0.5f - jmin (3.0f, w * 0.1f)), y,
  51303. jmin (4, roundFloatToInt (w * 0.2f)), h);
  51304. }
  51305. float alpha = 0.35f;
  51306. if (slider.isEnabled())
  51307. alpha = slider.isMouseOverOrDragging() ? 1.0f : 0.7f;
  51308. const Colour fill (slider.findColour (Slider::thumbColourId).withAlpha (alpha));
  51309. const Colour outline (Colours::black.withAlpha (slider.isEnabled() ? 0.7f : 0.35f));
  51310. if (style == Slider::TwoValueVertical || style == Slider::ThreeValueVertical)
  51311. {
  51312. drawTriangle (g, x + w * 0.5f + jmin (4.0f, w * 0.3f), minSliderPos,
  51313. x + w * 0.5f - jmin (8.0f, w * 0.4f), minSliderPos - 7.0f,
  51314. x + w * 0.5f - jmin (8.0f, w * 0.4f), minSliderPos,
  51315. fill, outline);
  51316. drawTriangle (g, x + w * 0.5f + jmin (4.0f, w * 0.3f), maxSliderPos,
  51317. x + w * 0.5f - jmin (8.0f, w * 0.4f), maxSliderPos,
  51318. x + w * 0.5f - jmin (8.0f, w * 0.4f), maxSliderPos + 7.0f,
  51319. fill, outline);
  51320. }
  51321. else if (style == Slider::TwoValueHorizontal || style == Slider::ThreeValueHorizontal)
  51322. {
  51323. drawTriangle (g, minSliderPos, y + h * 0.6f - jmin (4.0f, h * 0.3f),
  51324. minSliderPos - 7.0f, y + h * 0.9f ,
  51325. minSliderPos, y + h * 0.9f,
  51326. fill, outline);
  51327. drawTriangle (g, maxSliderPos, y + h * 0.6f - jmin (4.0f, h * 0.3f),
  51328. maxSliderPos, y + h * 0.9f,
  51329. maxSliderPos + 7.0f, y + h * 0.9f,
  51330. fill, outline);
  51331. }
  51332. if (style == Slider::LinearHorizontal || style == Slider::ThreeValueHorizontal)
  51333. {
  51334. drawTriangle (g, sliderPos, y + h * 0.9f,
  51335. sliderPos - 7.0f, y + h * 0.2f,
  51336. sliderPos + 7.0f, y + h * 0.2f,
  51337. fill, outline);
  51338. }
  51339. else if (style == Slider::LinearVertical || style == Slider::ThreeValueVertical)
  51340. {
  51341. drawTriangle (g, x + w * 0.5f - jmin (4.0f, w * 0.3f), sliderPos,
  51342. x + w * 0.5f + jmin (8.0f, w * 0.4f), sliderPos - 7.0f,
  51343. x + w * 0.5f + jmin (8.0f, w * 0.4f), sliderPos + 7.0f,
  51344. fill, outline);
  51345. }
  51346. }
  51347. }
  51348. Button* OldSchoolLookAndFeel::createSliderButton (const bool isIncrement)
  51349. {
  51350. if (isIncrement)
  51351. return new ArrowButton ("u", 0.75f, Colours::white.withAlpha (0.8f));
  51352. else
  51353. return new ArrowButton ("d", 0.25f, Colours::white.withAlpha (0.8f));
  51354. }
  51355. ImageEffectFilter* OldSchoolLookAndFeel::getSliderEffect()
  51356. {
  51357. return &scrollbarShadow;
  51358. }
  51359. int OldSchoolLookAndFeel::getSliderThumbRadius (Slider&)
  51360. {
  51361. return 8;
  51362. }
  51363. void OldSchoolLookAndFeel::drawCornerResizer (Graphics& g,
  51364. int w, int h,
  51365. bool isMouseOver,
  51366. bool isMouseDragging)
  51367. {
  51368. g.setColour ((isMouseOver || isMouseDragging) ? Colours::lightgrey
  51369. : Colours::darkgrey);
  51370. const float lineThickness = jmin (w, h) * 0.1f;
  51371. for (float i = 0.0f; i < 1.0f; i += 0.3f)
  51372. {
  51373. g.drawLine (w * i,
  51374. h + 1.0f,
  51375. w + 1.0f,
  51376. h * i,
  51377. lineThickness);
  51378. }
  51379. }
  51380. Button* OldSchoolLookAndFeel::createDocumentWindowButton (int buttonType)
  51381. {
  51382. Path shape;
  51383. if (buttonType == DocumentWindow::closeButton)
  51384. {
  51385. shape.addLineSegment (0.0f, 0.0f, 1.0f, 1.0f, 0.35f);
  51386. shape.addLineSegment (1.0f, 0.0f, 0.0f, 1.0f, 0.35f);
  51387. ShapeButton* const b = new ShapeButton ("close",
  51388. Colour (0x7fff3333),
  51389. Colour (0xd7ff3333),
  51390. Colour (0xf7ff3333));
  51391. b->setShape (shape, true, true, true);
  51392. return b;
  51393. }
  51394. else if (buttonType == DocumentWindow::minimiseButton)
  51395. {
  51396. shape.addLineSegment (0.0f, 0.5f, 1.0f, 0.5f, 0.25f);
  51397. DrawableButton* b = new DrawableButton ("minimise", DrawableButton::ImageFitted);
  51398. DrawablePath dp;
  51399. dp.setPath (shape);
  51400. dp.setSolidFill (Colours::black.withAlpha (0.3f));
  51401. b->setImages (&dp);
  51402. return b;
  51403. }
  51404. else if (buttonType == DocumentWindow::maximiseButton)
  51405. {
  51406. shape.addLineSegment (0.5f, 0.0f, 0.5f, 1.0f, 0.25f);
  51407. shape.addLineSegment (0.0f, 0.5f, 1.0f, 0.5f, 0.25f);
  51408. DrawableButton* b = new DrawableButton ("maximise", DrawableButton::ImageFitted);
  51409. DrawablePath dp;
  51410. dp.setPath (shape);
  51411. dp.setSolidFill (Colours::black.withAlpha (0.3f));
  51412. b->setImages (&dp);
  51413. return b;
  51414. }
  51415. jassertfalse
  51416. return 0;
  51417. }
  51418. void OldSchoolLookAndFeel::positionDocumentWindowButtons (DocumentWindow&,
  51419. int titleBarX,
  51420. int titleBarY,
  51421. int titleBarW,
  51422. int titleBarH,
  51423. Button* minimiseButton,
  51424. Button* maximiseButton,
  51425. Button* closeButton,
  51426. bool positionTitleBarButtonsOnLeft)
  51427. {
  51428. titleBarY += titleBarH / 8;
  51429. titleBarH -= titleBarH / 4;
  51430. const int buttonW = titleBarH;
  51431. int x = positionTitleBarButtonsOnLeft ? titleBarX + 4
  51432. : titleBarX + titleBarW - buttonW - 4;
  51433. if (closeButton != 0)
  51434. {
  51435. closeButton->setBounds (x, titleBarY, buttonW, titleBarH);
  51436. x += positionTitleBarButtonsOnLeft ? buttonW + buttonW / 5
  51437. : -(buttonW + buttonW / 5);
  51438. }
  51439. if (positionTitleBarButtonsOnLeft)
  51440. swapVariables (minimiseButton, maximiseButton);
  51441. if (maximiseButton != 0)
  51442. {
  51443. maximiseButton->setBounds (x, titleBarY - 2, buttonW, titleBarH);
  51444. x += positionTitleBarButtonsOnLeft ? buttonW : -buttonW;
  51445. }
  51446. if (minimiseButton != 0)
  51447. minimiseButton->setBounds (x, titleBarY - 2, buttonW, titleBarH);
  51448. }
  51449. END_JUCE_NAMESPACE
  51450. /********* End of inlined file: juce_OldSchoolLookAndFeel.cpp *********/
  51451. /********* Start of inlined file: juce_MenuBarComponent.cpp *********/
  51452. BEGIN_JUCE_NAMESPACE
  51453. class DummyMenuComponent : public Component
  51454. {
  51455. DummyMenuComponent (const DummyMenuComponent&);
  51456. const DummyMenuComponent& operator= (const DummyMenuComponent&);
  51457. public:
  51458. DummyMenuComponent() {}
  51459. ~DummyMenuComponent() {}
  51460. void inputAttemptWhenModal()
  51461. {
  51462. exitModalState (0);
  51463. }
  51464. };
  51465. MenuBarComponent::MenuBarComponent (MenuBarModel* model_)
  51466. : model (0),
  51467. itemUnderMouse (-1),
  51468. currentPopupIndex (-1),
  51469. indexToShowAgain (-1),
  51470. lastMouseX (0),
  51471. lastMouseY (0),
  51472. inModalState (false),
  51473. currentPopup (0)
  51474. {
  51475. setRepaintsOnMouseActivity (true);
  51476. setWantsKeyboardFocus (false);
  51477. setMouseClickGrabsKeyboardFocus (false);
  51478. setModel (model_);
  51479. }
  51480. MenuBarComponent::~MenuBarComponent()
  51481. {
  51482. setModel (0);
  51483. Desktop::getInstance().removeGlobalMouseListener (this);
  51484. deleteAndZero (currentPopup);
  51485. }
  51486. void MenuBarComponent::setModel (MenuBarModel* const newModel)
  51487. {
  51488. if (model != newModel)
  51489. {
  51490. if (model != 0)
  51491. model->removeListener (this);
  51492. model = newModel;
  51493. if (model != 0)
  51494. model->addListener (this);
  51495. repaint();
  51496. menuBarItemsChanged (0);
  51497. }
  51498. }
  51499. void MenuBarComponent::paint (Graphics& g)
  51500. {
  51501. const bool isMouseOverBar = currentPopupIndex >= 0 || itemUnderMouse >= 0 || isMouseOver();
  51502. getLookAndFeel().drawMenuBarBackground (g,
  51503. getWidth(),
  51504. getHeight(),
  51505. isMouseOverBar,
  51506. *this);
  51507. if (model != 0)
  51508. {
  51509. for (int i = 0; i < menuNames.size(); ++i)
  51510. {
  51511. g.saveState();
  51512. g.setOrigin (xPositions [i], 0);
  51513. g.reduceClipRegion (0, 0, xPositions[i + 1] - xPositions[i], getHeight());
  51514. getLookAndFeel().drawMenuBarItem (g,
  51515. xPositions[i + 1] - xPositions[i],
  51516. getHeight(),
  51517. i,
  51518. menuNames[i],
  51519. i == itemUnderMouse,
  51520. i == currentPopupIndex,
  51521. isMouseOverBar,
  51522. *this);
  51523. g.restoreState();
  51524. }
  51525. }
  51526. }
  51527. void MenuBarComponent::resized()
  51528. {
  51529. xPositions.clear();
  51530. int x = 2;
  51531. xPositions.add (x);
  51532. for (int i = 0; i < menuNames.size(); ++i)
  51533. {
  51534. x += getLookAndFeel().getMenuBarItemWidth (*this, i, menuNames[i]);
  51535. xPositions.add (x);
  51536. }
  51537. }
  51538. int MenuBarComponent::getItemAt (const int x, const int y)
  51539. {
  51540. for (int i = 0; i < xPositions.size(); ++i)
  51541. if (x >= xPositions[i] && x < xPositions[i + 1])
  51542. return reallyContains (x, y, true) ? i : -1;
  51543. return -1;
  51544. }
  51545. void MenuBarComponent::repaintMenuItem (int index)
  51546. {
  51547. if (((unsigned int) index) < (unsigned int) xPositions.size())
  51548. {
  51549. const int x1 = xPositions [index];
  51550. const int x2 = xPositions [index + 1];
  51551. repaint (x1 - 2, 0, x2 - x1 + 4, getHeight());
  51552. }
  51553. }
  51554. void MenuBarComponent::updateItemUnderMouse (int x, int y)
  51555. {
  51556. const int newItem = getItemAt (x, y);
  51557. if (itemUnderMouse != newItem)
  51558. {
  51559. repaintMenuItem (itemUnderMouse);
  51560. itemUnderMouse = newItem;
  51561. repaintMenuItem (itemUnderMouse);
  51562. }
  51563. }
  51564. void MenuBarComponent::hideCurrentMenu()
  51565. {
  51566. deleteAndZero (currentPopup);
  51567. repaint();
  51568. }
  51569. void MenuBarComponent::showMenu (int index)
  51570. {
  51571. if (index != currentPopupIndex)
  51572. {
  51573. if (inModalState)
  51574. {
  51575. hideCurrentMenu();
  51576. indexToShowAgain = index;
  51577. return;
  51578. }
  51579. indexToShowAgain = -1;
  51580. currentPopupIndex = -1;
  51581. itemUnderMouse = index;
  51582. deleteAndZero (currentPopup);
  51583. menuBarItemsChanged (0);
  51584. Component* const prevFocused = getCurrentlyFocusedComponent();
  51585. ComponentDeletionWatcher* prevCompDeletionChecker = 0;
  51586. if (prevFocused != 0)
  51587. prevCompDeletionChecker = new ComponentDeletionWatcher (prevFocused);
  51588. ComponentDeletionWatcher deletionChecker (this);
  51589. enterModalState (false);
  51590. inModalState = true;
  51591. int result = 0;
  51592. ApplicationCommandManager* managerOfChosenCommand = 0;
  51593. Desktop::getInstance().addGlobalMouseListener (this);
  51594. for (;;)
  51595. {
  51596. const int x = getScreenX() + xPositions [itemUnderMouse];
  51597. const int w = xPositions [itemUnderMouse + 1] - xPositions [itemUnderMouse];
  51598. currentPopupIndex = itemUnderMouse;
  51599. indexToShowAgain = -1;
  51600. repaint();
  51601. if (((unsigned int) itemUnderMouse) < (unsigned int) menuNames.size())
  51602. {
  51603. PopupMenu m (model->getMenuForIndex (itemUnderMouse,
  51604. menuNames [itemUnderMouse]));
  51605. currentPopup = m.createMenuComponent (x, getScreenY(),
  51606. w, getHeight(),
  51607. 0, w, 0, 0,
  51608. true, this,
  51609. &managerOfChosenCommand,
  51610. this);
  51611. }
  51612. if (currentPopup == 0)
  51613. {
  51614. currentPopup = new DummyMenuComponent();
  51615. addAndMakeVisible (currentPopup);
  51616. }
  51617. currentPopup->enterModalState (false);
  51618. currentPopup->toFront (false); // need to do this after making it modal, or it could
  51619. // be stuck behind other comps that are already modal..
  51620. result = currentPopup->runModalLoop();
  51621. if (deletionChecker.hasBeenDeleted())
  51622. {
  51623. delete prevCompDeletionChecker;
  51624. return;
  51625. }
  51626. const int lastPopupIndex = currentPopupIndex;
  51627. deleteAndZero (currentPopup);
  51628. currentPopupIndex = -1;
  51629. if (result != 0)
  51630. {
  51631. topLevelIndexClicked = lastPopupIndex;
  51632. break;
  51633. }
  51634. else if (indexToShowAgain >= 0)
  51635. {
  51636. menuBarItemsChanged (0);
  51637. repaint();
  51638. itemUnderMouse = indexToShowAgain;
  51639. if (((unsigned int) itemUnderMouse) >= (unsigned int) menuNames.size())
  51640. break;
  51641. }
  51642. else
  51643. {
  51644. break;
  51645. }
  51646. }
  51647. Desktop::getInstance().removeGlobalMouseListener (this);
  51648. inModalState = false;
  51649. exitModalState (0);
  51650. if (prevCompDeletionChecker != 0)
  51651. {
  51652. if (! prevCompDeletionChecker->hasBeenDeleted())
  51653. prevFocused->grabKeyboardFocus();
  51654. delete prevCompDeletionChecker;
  51655. }
  51656. int mx, my;
  51657. getMouseXYRelative (mx, my);
  51658. updateItemUnderMouse (mx, my);
  51659. repaint();
  51660. if (result != 0)
  51661. {
  51662. if (managerOfChosenCommand != 0)
  51663. {
  51664. ApplicationCommandTarget::InvocationInfo info (result);
  51665. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromMenu;
  51666. managerOfChosenCommand->invoke (info, true);
  51667. }
  51668. postCommandMessage (result);
  51669. }
  51670. }
  51671. }
  51672. void MenuBarComponent::handleCommandMessage (int commandId)
  51673. {
  51674. if (model != 0)
  51675. model->menuItemSelected (commandId, topLevelIndexClicked);
  51676. }
  51677. void MenuBarComponent::mouseEnter (const MouseEvent& e)
  51678. {
  51679. if (e.eventComponent == this)
  51680. updateItemUnderMouse (e.x, e.y);
  51681. }
  51682. void MenuBarComponent::mouseExit (const MouseEvent& e)
  51683. {
  51684. if (e.eventComponent == this)
  51685. updateItemUnderMouse (e.x, e.y);
  51686. }
  51687. void MenuBarComponent::mouseDown (const MouseEvent& e)
  51688. {
  51689. const MouseEvent e2 (e.getEventRelativeTo (this));
  51690. if (currentPopupIndex < 0)
  51691. {
  51692. updateItemUnderMouse (e2.x, e2.y);
  51693. currentPopupIndex = -2;
  51694. showMenu (itemUnderMouse);
  51695. }
  51696. }
  51697. void MenuBarComponent::mouseDrag (const MouseEvent& e)
  51698. {
  51699. const MouseEvent e2 (e.getEventRelativeTo (this));
  51700. const int item = getItemAt (e2.x, e2.y);
  51701. if (item >= 0)
  51702. showMenu (item);
  51703. }
  51704. void MenuBarComponent::mouseUp (const MouseEvent& e)
  51705. {
  51706. const MouseEvent e2 (e.getEventRelativeTo (this));
  51707. updateItemUnderMouse (e2.x, e2.y);
  51708. if (itemUnderMouse < 0 && dynamic_cast <DummyMenuComponent*> (currentPopup) != 0)
  51709. hideCurrentMenu();
  51710. }
  51711. void MenuBarComponent::mouseMove (const MouseEvent& e)
  51712. {
  51713. const MouseEvent e2 (e.getEventRelativeTo (this));
  51714. if (lastMouseX != e2.x || lastMouseY != e2.y)
  51715. {
  51716. if (currentPopupIndex >= 0)
  51717. {
  51718. const int item = getItemAt (e2.x, e2.y);
  51719. if (item >= 0)
  51720. showMenu (item);
  51721. }
  51722. else
  51723. {
  51724. updateItemUnderMouse (e2.x, e2.y);
  51725. }
  51726. lastMouseX = e2.x;
  51727. lastMouseY = e2.y;
  51728. }
  51729. }
  51730. bool MenuBarComponent::keyPressed (const KeyPress& key)
  51731. {
  51732. bool used = false;
  51733. const int numMenus = menuNames.size();
  51734. const int currentIndex = jlimit (0, menuNames.size() - 1, currentPopupIndex);
  51735. if (key.isKeyCode (KeyPress::leftKey))
  51736. {
  51737. showMenu ((currentIndex + numMenus - 1) % numMenus);
  51738. used = true;
  51739. }
  51740. else if (key.isKeyCode (KeyPress::rightKey))
  51741. {
  51742. showMenu ((currentIndex + 1) % numMenus);
  51743. used = true;
  51744. }
  51745. return used;
  51746. }
  51747. void MenuBarComponent::inputAttemptWhenModal()
  51748. {
  51749. hideCurrentMenu();
  51750. }
  51751. void MenuBarComponent::menuBarItemsChanged (MenuBarModel* /*menuBarModel*/)
  51752. {
  51753. StringArray newNames;
  51754. if (model != 0)
  51755. newNames = model->getMenuBarNames();
  51756. if (newNames != menuNames)
  51757. {
  51758. menuNames = newNames;
  51759. repaint();
  51760. resized();
  51761. }
  51762. }
  51763. void MenuBarComponent::menuCommandInvoked (MenuBarModel* /*menuBarModel*/,
  51764. const ApplicationCommandTarget::InvocationInfo& info)
  51765. {
  51766. if (model == 0
  51767. || (info.commandFlags & ApplicationCommandInfo::dontTriggerVisualFeedback) != 0)
  51768. return;
  51769. for (int i = 0; i < menuNames.size(); ++i)
  51770. {
  51771. const PopupMenu menu (model->getMenuForIndex (i, menuNames [i]));
  51772. if (menu.containsCommandItem (info.commandID))
  51773. {
  51774. itemUnderMouse = i;
  51775. repaintMenuItem (i);
  51776. startTimer (200);
  51777. break;
  51778. }
  51779. }
  51780. }
  51781. void MenuBarComponent::timerCallback()
  51782. {
  51783. stopTimer();
  51784. int mx, my;
  51785. getMouseXYRelative (mx, my);
  51786. updateItemUnderMouse (mx, my);
  51787. }
  51788. END_JUCE_NAMESPACE
  51789. /********* End of inlined file: juce_MenuBarComponent.cpp *********/
  51790. /********* Start of inlined file: juce_MenuBarModel.cpp *********/
  51791. BEGIN_JUCE_NAMESPACE
  51792. MenuBarModel::MenuBarModel() throw()
  51793. : manager (0)
  51794. {
  51795. }
  51796. MenuBarModel::~MenuBarModel()
  51797. {
  51798. setApplicationCommandManagerToWatch (0);
  51799. }
  51800. void MenuBarModel::menuItemsChanged()
  51801. {
  51802. triggerAsyncUpdate();
  51803. }
  51804. void MenuBarModel::setApplicationCommandManagerToWatch (ApplicationCommandManager* const newManager) throw()
  51805. {
  51806. if (manager != newManager)
  51807. {
  51808. if (manager != 0)
  51809. manager->removeListener (this);
  51810. manager = newManager;
  51811. if (manager != 0)
  51812. manager->addListener (this);
  51813. }
  51814. }
  51815. void MenuBarModel::addListener (MenuBarModelListener* const newListener) throw()
  51816. {
  51817. jassert (newListener != 0);
  51818. jassert (! listeners.contains (newListener)); // trying to add a listener to the list twice!
  51819. if (newListener != 0)
  51820. listeners.add (newListener);
  51821. }
  51822. void MenuBarModel::removeListener (MenuBarModelListener* const listenerToRemove) throw()
  51823. {
  51824. // Trying to remove a listener that isn't on the list!
  51825. // If this assertion happens because this object is a dangling pointer, make sure you've not
  51826. // deleted this menu model while it's still being used by something (e.g. by a MenuBarComponent)
  51827. jassert (listeners.contains (listenerToRemove));
  51828. listeners.removeValue (listenerToRemove);
  51829. }
  51830. void MenuBarModel::handleAsyncUpdate()
  51831. {
  51832. for (int i = listeners.size(); --i >= 0;)
  51833. {
  51834. ((MenuBarModelListener*) listeners.getUnchecked (i))->menuBarItemsChanged (this);
  51835. i = jmin (i, listeners.size());
  51836. }
  51837. }
  51838. void MenuBarModel::applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info)
  51839. {
  51840. for (int i = listeners.size(); --i >= 0;)
  51841. {
  51842. ((MenuBarModelListener*) listeners.getUnchecked (i))->menuCommandInvoked (this, info);
  51843. i = jmin (i, listeners.size());
  51844. }
  51845. }
  51846. void MenuBarModel::applicationCommandListChanged()
  51847. {
  51848. menuItemsChanged();
  51849. }
  51850. END_JUCE_NAMESPACE
  51851. /********* End of inlined file: juce_MenuBarModel.cpp *********/
  51852. /********* Start of inlined file: juce_PopupMenu.cpp *********/
  51853. BEGIN_JUCE_NAMESPACE
  51854. static VoidArray activeMenuWindows;
  51855. class MenuItemInfo
  51856. {
  51857. public:
  51858. const int itemId;
  51859. String text;
  51860. const Colour textColour;
  51861. const bool active, isSeparator, isTicked, usesColour;
  51862. Image* image;
  51863. PopupMenuCustomComponent* const customComp;
  51864. PopupMenu* subMenu;
  51865. ApplicationCommandManager* const commandManager;
  51866. MenuItemInfo() throw()
  51867. : itemId (0),
  51868. active (true),
  51869. isSeparator (true),
  51870. isTicked (false),
  51871. usesColour (false),
  51872. image (0),
  51873. customComp (0),
  51874. subMenu (0),
  51875. commandManager (0)
  51876. {
  51877. }
  51878. MenuItemInfo (const int itemId_,
  51879. const String& text_,
  51880. const bool active_,
  51881. const bool isTicked_,
  51882. const Image* im,
  51883. const Colour& textColour_,
  51884. const bool usesColour_,
  51885. PopupMenuCustomComponent* const customComp_,
  51886. const PopupMenu* const subMenu_,
  51887. ApplicationCommandManager* const commandManager_) throw()
  51888. : itemId (itemId_),
  51889. text (text_),
  51890. textColour (textColour_),
  51891. active (active_),
  51892. isSeparator (false),
  51893. isTicked (isTicked_),
  51894. usesColour (usesColour_),
  51895. image (0),
  51896. customComp (customComp_),
  51897. commandManager (commandManager_)
  51898. {
  51899. subMenu = (subMenu_ != 0) ? new PopupMenu (*subMenu_) : 0;
  51900. if (customComp != 0)
  51901. customComp->refCount_++;
  51902. if (im != 0)
  51903. image = im->createCopy();
  51904. if (commandManager_ != 0 && itemId_ != 0)
  51905. {
  51906. String shortcutKey;
  51907. Array <KeyPress> keyPresses (commandManager_->getKeyMappings()
  51908. ->getKeyPressesAssignedToCommand (itemId_));
  51909. for (int i = 0; i < keyPresses.size(); ++i)
  51910. {
  51911. const String key (keyPresses.getReference(i).getTextDescription());
  51912. if (shortcutKey.isNotEmpty())
  51913. shortcutKey << ", ";
  51914. if (key.length() == 1)
  51915. shortcutKey << "shortcut: '" << key << '\'';
  51916. else
  51917. shortcutKey << key;
  51918. }
  51919. shortcutKey = shortcutKey.trim();
  51920. if (shortcutKey.isNotEmpty())
  51921. text << "<end>" << shortcutKey;
  51922. }
  51923. }
  51924. MenuItemInfo (const MenuItemInfo& other) throw()
  51925. : itemId (other.itemId),
  51926. text (other.text),
  51927. textColour (other.textColour),
  51928. active (other.active),
  51929. isSeparator (other.isSeparator),
  51930. isTicked (other.isTicked),
  51931. usesColour (other.usesColour),
  51932. customComp (other.customComp),
  51933. commandManager (other.commandManager)
  51934. {
  51935. if (other.subMenu != 0)
  51936. subMenu = new PopupMenu (*(other.subMenu));
  51937. else
  51938. subMenu = 0;
  51939. if (other.image != 0)
  51940. image = other.image->createCopy();
  51941. else
  51942. image = 0;
  51943. if (customComp != 0)
  51944. customComp->refCount_++;
  51945. }
  51946. ~MenuItemInfo() throw()
  51947. {
  51948. delete subMenu;
  51949. delete image;
  51950. if (customComp != 0 && --(customComp->refCount_) == 0)
  51951. delete customComp;
  51952. }
  51953. bool canBeTriggered() const throw()
  51954. {
  51955. return active && ! (isSeparator || (subMenu != 0));
  51956. }
  51957. bool hasActiveSubMenu() const throw()
  51958. {
  51959. return active && (subMenu != 0);
  51960. }
  51961. juce_UseDebuggingNewOperator
  51962. private:
  51963. const MenuItemInfo& operator= (const MenuItemInfo&);
  51964. };
  51965. class MenuItemComponent : public Component
  51966. {
  51967. bool isHighlighted;
  51968. public:
  51969. MenuItemInfo itemInfo;
  51970. MenuItemComponent (const MenuItemInfo& itemInfo_)
  51971. : isHighlighted (false),
  51972. itemInfo (itemInfo_)
  51973. {
  51974. if (itemInfo.customComp != 0)
  51975. addAndMakeVisible (itemInfo.customComp);
  51976. }
  51977. ~MenuItemComponent()
  51978. {
  51979. if (itemInfo.customComp != 0)
  51980. removeChildComponent (itemInfo.customComp);
  51981. }
  51982. void getIdealSize (int& idealWidth,
  51983. int& idealHeight,
  51984. const int standardItemHeight)
  51985. {
  51986. if (itemInfo.customComp != 0)
  51987. {
  51988. itemInfo.customComp->getIdealSize (idealWidth, idealHeight);
  51989. }
  51990. else
  51991. {
  51992. getLookAndFeel().getIdealPopupMenuItemSize (itemInfo.text,
  51993. itemInfo.isSeparator,
  51994. standardItemHeight,
  51995. idealWidth,
  51996. idealHeight);
  51997. }
  51998. }
  51999. void paint (Graphics& g)
  52000. {
  52001. if (itemInfo.customComp == 0)
  52002. {
  52003. String mainText (itemInfo.text);
  52004. String endText;
  52005. const int endIndex = mainText.indexOf (T("<end>"));
  52006. if (endIndex >= 0)
  52007. {
  52008. endText = mainText.substring (endIndex + 5).trim();
  52009. mainText = mainText.substring (0, endIndex);
  52010. }
  52011. getLookAndFeel()
  52012. .drawPopupMenuItem (g, getWidth(), getHeight(),
  52013. itemInfo.isSeparator,
  52014. itemInfo.active,
  52015. isHighlighted,
  52016. itemInfo.isTicked,
  52017. itemInfo.subMenu != 0,
  52018. mainText, endText,
  52019. itemInfo.image,
  52020. itemInfo.usesColour ? &(itemInfo.textColour) : 0);
  52021. }
  52022. }
  52023. void resized()
  52024. {
  52025. if (getNumChildComponents() > 0)
  52026. getChildComponent(0)->setBounds (2, 0, getWidth() - 4, getHeight());
  52027. }
  52028. void setHighlighted (bool shouldBeHighlighted)
  52029. {
  52030. shouldBeHighlighted = shouldBeHighlighted && itemInfo.active;
  52031. if (isHighlighted != shouldBeHighlighted)
  52032. {
  52033. isHighlighted = shouldBeHighlighted;
  52034. if (itemInfo.customComp != 0)
  52035. {
  52036. itemInfo.customComp->isHighlighted = shouldBeHighlighted;
  52037. itemInfo.customComp->repaint();
  52038. }
  52039. repaint();
  52040. }
  52041. }
  52042. private:
  52043. MenuItemComponent (const MenuItemComponent&);
  52044. const MenuItemComponent& operator= (const MenuItemComponent&);
  52045. };
  52046. static const int scrollZone = 24;
  52047. static const int borderSize = 2;
  52048. static const int timerInterval = 50;
  52049. static const int dismissCommandId = 0x6287345f;
  52050. static bool wasHiddenBecauseOfAppChange = false;
  52051. class PopupMenuWindow : public Component,
  52052. private Timer
  52053. {
  52054. public:
  52055. PopupMenuWindow() throw()
  52056. : Component (T("menu")),
  52057. owner (0),
  52058. currentChild (0),
  52059. activeSubMenu (0),
  52060. menuBarComponent (0),
  52061. managerOfChosenCommand (0),
  52062. componentAttachedTo (0),
  52063. attachedCompWatcher (0),
  52064. lastMouseX (0),
  52065. lastMouseY (0),
  52066. minimumWidth (0),
  52067. maximumNumColumns (7),
  52068. standardItemHeight (0),
  52069. isOver (false),
  52070. hasBeenOver (false),
  52071. isDown (false),
  52072. needsToScroll (false),
  52073. hideOnExit (false),
  52074. disableMouseMoves (false),
  52075. hasAnyJuceCompHadFocus (false),
  52076. numColumns (0),
  52077. contentHeight (0),
  52078. childYOffset (0),
  52079. timeEnteredCurrentChildComp (0),
  52080. scrollAcceleration (1.0)
  52081. {
  52082. menuCreationTime = lastFocused = lastScroll = Time::getMillisecondCounter();
  52083. setWantsKeyboardFocus (true);
  52084. setMouseClickGrabsKeyboardFocus (false);
  52085. setOpaque (true);
  52086. setAlwaysOnTop (true);
  52087. Desktop::getInstance().addGlobalMouseListener (this);
  52088. activeMenuWindows.add (this);
  52089. }
  52090. ~PopupMenuWindow()
  52091. {
  52092. activeMenuWindows.removeValue (this);
  52093. Desktop::getInstance().removeGlobalMouseListener (this);
  52094. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  52095. delete activeSubMenu;
  52096. deleteAllChildren();
  52097. delete attachedCompWatcher;
  52098. }
  52099. static PopupMenuWindow* create (const PopupMenu& menu,
  52100. const bool dismissOnMouseUp,
  52101. PopupMenuWindow* const owner_,
  52102. const int minX, const int maxX,
  52103. const int minY, const int maxY,
  52104. const int minimumWidth,
  52105. const int maximumNumColumns,
  52106. const int standardItemHeight,
  52107. const bool alignToRectangle,
  52108. const int itemIdThatMustBeVisible,
  52109. Component* const menuBarComponent,
  52110. ApplicationCommandManager** managerOfChosenCommand,
  52111. Component* const componentAttachedTo) throw()
  52112. {
  52113. if (menu.items.size() > 0)
  52114. {
  52115. int totalItems = 0;
  52116. PopupMenuWindow* const mw = new PopupMenuWindow();
  52117. mw->setLookAndFeel (menu.lookAndFeel);
  52118. mw->setWantsKeyboardFocus (false);
  52119. mw->minimumWidth = minimumWidth;
  52120. mw->maximumNumColumns = maximumNumColumns;
  52121. mw->standardItemHeight = standardItemHeight;
  52122. mw->dismissOnMouseUp = dismissOnMouseUp;
  52123. for (int i = 0; i < menu.items.size(); ++i)
  52124. {
  52125. MenuItemInfo* const item = (MenuItemInfo*) menu.items.getUnchecked(i);
  52126. mw->addItem (*item);
  52127. ++totalItems;
  52128. }
  52129. if (totalItems == 0)
  52130. {
  52131. delete mw;
  52132. }
  52133. else
  52134. {
  52135. mw->owner = owner_;
  52136. mw->menuBarComponent = menuBarComponent;
  52137. mw->managerOfChosenCommand = managerOfChosenCommand;
  52138. mw->componentAttachedTo = componentAttachedTo;
  52139. delete mw->attachedCompWatcher;
  52140. mw->attachedCompWatcher = componentAttachedTo != 0 ? new ComponentDeletionWatcher (componentAttachedTo) : 0;
  52141. mw->calculateWindowPos (minX, maxX, minY, maxY, alignToRectangle);
  52142. mw->setTopLeftPosition (mw->windowPos.getX(),
  52143. mw->windowPos.getY());
  52144. mw->updateYPositions();
  52145. if (itemIdThatMustBeVisible != 0)
  52146. {
  52147. const int y = minY - mw->windowPos.getY();
  52148. mw->ensureItemIsVisible (itemIdThatMustBeVisible,
  52149. (((unsigned int) y) < (unsigned int) mw->windowPos.getHeight()) ? y : -1);
  52150. }
  52151. mw->resizeToBestWindowPos();
  52152. mw->addToDesktop (ComponentPeer::windowIsTemporary
  52153. | mw->getLookAndFeel().getMenuWindowFlags());
  52154. return mw;
  52155. }
  52156. }
  52157. return 0;
  52158. }
  52159. void paint (Graphics& g)
  52160. {
  52161. getLookAndFeel().drawPopupMenuBackground (g, getWidth(), getHeight());
  52162. }
  52163. void paintOverChildren (Graphics& g)
  52164. {
  52165. if (isScrolling())
  52166. {
  52167. LookAndFeel& lf = getLookAndFeel();
  52168. if (isScrollZoneActive (false))
  52169. lf.drawPopupMenuUpDownArrow (g, getWidth(), scrollZone, true);
  52170. if (isScrollZoneActive (true))
  52171. {
  52172. g.setOrigin (0, getHeight() - scrollZone);
  52173. lf.drawPopupMenuUpDownArrow (g, getWidth(), scrollZone, false);
  52174. }
  52175. }
  52176. }
  52177. bool isScrollZoneActive (bool bottomOne) const
  52178. {
  52179. return isScrolling()
  52180. && (bottomOne
  52181. ? childYOffset < contentHeight - windowPos.getHeight()
  52182. : childYOffset > 0);
  52183. }
  52184. void addItem (const MenuItemInfo& item) throw()
  52185. {
  52186. MenuItemComponent* const mic = new MenuItemComponent (item);
  52187. addAndMakeVisible (mic);
  52188. int itemW = 80;
  52189. int itemH = 16;
  52190. mic->getIdealSize (itemW, itemH, standardItemHeight);
  52191. mic->setSize (itemW, jlimit (2, 600, itemH));
  52192. mic->addMouseListener (this, false);
  52193. }
  52194. // hide this and all sub-comps
  52195. void hide (const MenuItemInfo* const item) throw()
  52196. {
  52197. if (isVisible())
  52198. {
  52199. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  52200. deleteAndZero (activeSubMenu);
  52201. currentChild = 0;
  52202. exitModalState (item != 0 ? item->itemId : 0);
  52203. setVisible (false);
  52204. if (item != 0
  52205. && item->commandManager != 0
  52206. && item->itemId != 0)
  52207. {
  52208. *managerOfChosenCommand = item->commandManager;
  52209. }
  52210. }
  52211. }
  52212. void dismissMenu (const MenuItemInfo* const item) throw()
  52213. {
  52214. if (owner != 0)
  52215. {
  52216. owner->dismissMenu (item);
  52217. }
  52218. else
  52219. {
  52220. if (item != 0)
  52221. {
  52222. // need a copy of this on the stack as the one passed in will get deleted during this call
  52223. const MenuItemInfo mi (*item);
  52224. hide (&mi);
  52225. }
  52226. else
  52227. {
  52228. hide (0);
  52229. }
  52230. }
  52231. }
  52232. void mouseMove (const MouseEvent&)
  52233. {
  52234. timerCallback();
  52235. }
  52236. void mouseDown (const MouseEvent&)
  52237. {
  52238. timerCallback();
  52239. }
  52240. void mouseDrag (const MouseEvent&)
  52241. {
  52242. timerCallback();
  52243. }
  52244. void mouseUp (const MouseEvent&)
  52245. {
  52246. timerCallback();
  52247. }
  52248. void mouseWheelMove (const MouseEvent&, float /*amountX*/, float amountY)
  52249. {
  52250. alterChildYPos (roundFloatToInt (-10.0f * amountY * scrollZone));
  52251. lastMouseX = -1;
  52252. }
  52253. bool keyPressed (const KeyPress& key)
  52254. {
  52255. if (key.isKeyCode (KeyPress::downKey))
  52256. {
  52257. selectNextItem (1);
  52258. }
  52259. else if (key.isKeyCode (KeyPress::upKey))
  52260. {
  52261. selectNextItem (-1);
  52262. }
  52263. else if (key.isKeyCode (KeyPress::leftKey))
  52264. {
  52265. PopupMenuWindow* parentWindow = owner;
  52266. if (parentWindow != 0)
  52267. {
  52268. MenuItemComponent* currentChildOfParent
  52269. = (parentWindow != 0) ? parentWindow->currentChild : 0;
  52270. hide (0);
  52271. if (parentWindow->isValidComponent())
  52272. parentWindow->setCurrentlyHighlightedChild (currentChildOfParent);
  52273. disableTimerUntilMouseMoves();
  52274. }
  52275. else if (menuBarComponent != 0)
  52276. {
  52277. menuBarComponent->keyPressed (key);
  52278. }
  52279. }
  52280. else if (key.isKeyCode (KeyPress::rightKey))
  52281. {
  52282. disableTimerUntilMouseMoves();
  52283. if (showSubMenuFor (currentChild))
  52284. {
  52285. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  52286. if (activeSubMenu != 0 && activeSubMenu->isVisible())
  52287. activeSubMenu->selectNextItem (1);
  52288. }
  52289. else if (menuBarComponent != 0)
  52290. {
  52291. menuBarComponent->keyPressed (key);
  52292. }
  52293. }
  52294. else if (key.isKeyCode (KeyPress::returnKey))
  52295. {
  52296. triggerCurrentlyHighlightedItem();
  52297. }
  52298. else if (key.isKeyCode (KeyPress::escapeKey))
  52299. {
  52300. dismissMenu (0);
  52301. }
  52302. else
  52303. {
  52304. return false;
  52305. }
  52306. return true;
  52307. }
  52308. void inputAttemptWhenModal()
  52309. {
  52310. timerCallback();
  52311. if (! isOverAnyMenu())
  52312. {
  52313. if (componentAttachedTo != 0 && ! attachedCompWatcher->hasBeenDeleted())
  52314. {
  52315. // we want to dismiss the menu, but if we do it synchronously, then
  52316. // the mouse-click will be allowed to pass through. That's good, except
  52317. // when the user clicks on the button that orginally popped the menu up,
  52318. // as they'll expect the menu to go away, and in fact it'll just
  52319. // come back. So only dismiss synchronously if they're not on the original
  52320. // comp that we're attached to.
  52321. int mx, my;
  52322. componentAttachedTo->getMouseXYRelative (mx, my);
  52323. if (componentAttachedTo->reallyContains (mx, my, true))
  52324. {
  52325. postCommandMessage (dismissCommandId); // dismiss asynchrounously
  52326. return;
  52327. }
  52328. }
  52329. dismissMenu (0);
  52330. }
  52331. }
  52332. void handleCommandMessage (int commandId)
  52333. {
  52334. Component::handleCommandMessage (commandId);
  52335. if (commandId == dismissCommandId)
  52336. dismissMenu (0);
  52337. }
  52338. void timerCallback()
  52339. {
  52340. if (! isVisible())
  52341. return;
  52342. if (attachedCompWatcher != 0 && attachedCompWatcher->hasBeenDeleted())
  52343. {
  52344. dismissMenu (0);
  52345. return;
  52346. }
  52347. PopupMenuWindow* currentlyModalWindow = dynamic_cast <PopupMenuWindow*> (Component::getCurrentlyModalComponent());
  52348. if (currentlyModalWindow != 0 && ! treeContains (currentlyModalWindow))
  52349. return;
  52350. startTimer (timerInterval); // do this in case it was called from a mouse
  52351. // move rather than a real timer callback
  52352. int mx, my;
  52353. Desktop::getMousePosition (mx, my);
  52354. int x = mx, y = my;
  52355. globalPositionToRelative (x, y);
  52356. const uint32 now = Time::getMillisecondCounter();
  52357. if (now > timeEnteredCurrentChildComp + 100
  52358. && reallyContains (x, y, true)
  52359. && currentChild->isValidComponent()
  52360. && (! disableMouseMoves)
  52361. && ! (activeSubMenu != 0 && activeSubMenu->isVisible()))
  52362. {
  52363. showSubMenuFor (currentChild);
  52364. }
  52365. if (mx != lastMouseX || my != lastMouseY || now > lastMouseMoveTime + 350)
  52366. {
  52367. highlightItemUnderMouse (mx, my, x, y);
  52368. }
  52369. bool overScrollArea = false;
  52370. if (isScrolling()
  52371. && (isOver || (isDown && ((unsigned int) x) < (unsigned int) getWidth()))
  52372. && ((isScrollZoneActive (false) && y < scrollZone)
  52373. || (isScrollZoneActive (true) && y > getHeight() - scrollZone)))
  52374. {
  52375. if (now > lastScroll + 20)
  52376. {
  52377. scrollAcceleration = jmin (4.0, scrollAcceleration * 1.04);
  52378. int amount = 0;
  52379. for (int i = 0; i < getNumChildComponents() && amount == 0; ++i)
  52380. amount = ((int) scrollAcceleration) * getChildComponent (i)->getHeight();
  52381. alterChildYPos (y < scrollZone ? -amount : amount);
  52382. lastScroll = now;
  52383. }
  52384. overScrollArea = true;
  52385. lastMouseX = -1; // trigger a mouse-move
  52386. }
  52387. else
  52388. {
  52389. scrollAcceleration = 1.0;
  52390. }
  52391. const bool wasDown = isDown;
  52392. bool isOverAny = isOverAnyMenu();
  52393. if (hideOnExit && hasBeenOver && (! isOverAny) && activeSubMenu != 0)
  52394. {
  52395. activeSubMenu->updateMouseOverStatus (mx, my);
  52396. isOverAny = isOverAnyMenu();
  52397. }
  52398. if (hideOnExit && hasBeenOver && ! isOverAny)
  52399. {
  52400. hide (0);
  52401. }
  52402. else
  52403. {
  52404. isDown = hasBeenOver
  52405. && (ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown()
  52406. || ModifierKeys::getCurrentModifiersRealtime().isAnyMouseButtonDown());
  52407. bool anyFocused = Process::isForegroundProcess();
  52408. if (anyFocused && Component::getCurrentlyFocusedComponent() == 0)
  52409. {
  52410. // because no component at all may have focus, our test here will
  52411. // only be triggered when something has focus and then loses it.
  52412. anyFocused = ! hasAnyJuceCompHadFocus;
  52413. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  52414. {
  52415. if (ComponentPeer::getPeer (i)->isFocused())
  52416. {
  52417. anyFocused = true;
  52418. hasAnyJuceCompHadFocus = true;
  52419. break;
  52420. }
  52421. }
  52422. }
  52423. if (! anyFocused)
  52424. {
  52425. if (now > lastFocused + 10)
  52426. {
  52427. wasHiddenBecauseOfAppChange = true;
  52428. dismissMenu (0);
  52429. return; // may have been deleted by the previous call..
  52430. }
  52431. }
  52432. else if (wasDown && now > menuCreationTime + 250
  52433. && ! (isDown || overScrollArea))
  52434. {
  52435. isOver = reallyContains (x, y, true);
  52436. if (isOver)
  52437. {
  52438. triggerCurrentlyHighlightedItem();
  52439. }
  52440. else if ((hasBeenOver || ! dismissOnMouseUp) && ! isOverAny)
  52441. {
  52442. dismissMenu (0);
  52443. }
  52444. return; // may have been deleted by the previous calls..
  52445. }
  52446. else
  52447. {
  52448. lastFocused = now;
  52449. }
  52450. }
  52451. }
  52452. juce_UseDebuggingNewOperator
  52453. private:
  52454. PopupMenuWindow* owner;
  52455. MenuItemComponent* currentChild;
  52456. PopupMenuWindow* activeSubMenu;
  52457. Component* menuBarComponent;
  52458. ApplicationCommandManager** managerOfChosenCommand;
  52459. Component* componentAttachedTo;
  52460. ComponentDeletionWatcher* attachedCompWatcher;
  52461. Rectangle windowPos;
  52462. int lastMouseX, lastMouseY;
  52463. int minimumWidth, maximumNumColumns, standardItemHeight;
  52464. bool isOver, hasBeenOver, isDown, needsToScroll;
  52465. bool dismissOnMouseUp, hideOnExit, disableMouseMoves, hasAnyJuceCompHadFocus;
  52466. int numColumns, contentHeight, childYOffset;
  52467. Array <int> columnWidths;
  52468. uint32 menuCreationTime, lastFocused, lastScroll, lastMouseMoveTime, timeEnteredCurrentChildComp;
  52469. double scrollAcceleration;
  52470. bool overlaps (const Rectangle& r) const throw()
  52471. {
  52472. return r.intersects (getBounds())
  52473. || (owner != 0 && owner->overlaps (r));
  52474. }
  52475. bool isOverAnyMenu() const throw()
  52476. {
  52477. return (owner != 0) ? owner->isOverAnyMenu()
  52478. : isOverChildren();
  52479. }
  52480. bool isOverChildren() const throw()
  52481. {
  52482. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  52483. return isVisible()
  52484. && (isOver || (activeSubMenu != 0 && activeSubMenu->isOverChildren()));
  52485. }
  52486. void updateMouseOverStatus (const int mx, const int my) throw()
  52487. {
  52488. int rx = mx, ry = my;
  52489. globalPositionToRelative (rx, ry);
  52490. isOver = reallyContains (rx, ry, true);
  52491. if (activeSubMenu != 0)
  52492. activeSubMenu->updateMouseOverStatus (mx, my);
  52493. }
  52494. bool treeContains (const PopupMenuWindow* const window) const throw()
  52495. {
  52496. const PopupMenuWindow* mw = this;
  52497. while (mw->owner != 0)
  52498. mw = mw->owner;
  52499. while (mw != 0)
  52500. {
  52501. if (mw == window)
  52502. return true;
  52503. mw = mw->activeSubMenu;
  52504. }
  52505. return false;
  52506. }
  52507. void calculateWindowPos (const int minX, const int maxX,
  52508. const int minY, const int maxY,
  52509. const bool alignToRectangle)
  52510. {
  52511. const Rectangle mon (Desktop::getInstance()
  52512. .getMonitorAreaContaining ((minX + maxX) / 2,
  52513. (minY + maxY) / 2,
  52514. #if JUCE_MAC
  52515. true));
  52516. #else
  52517. false)); // on windows, don't stop the menu overlapping the taskbar
  52518. #endif
  52519. int x, y, widthToUse, heightToUse;
  52520. layoutMenuItems (mon.getWidth() - 24, widthToUse, heightToUse);
  52521. if (alignToRectangle)
  52522. {
  52523. x = minX;
  52524. const int spaceUnder = mon.getHeight() - (maxY - mon.getY());
  52525. const int spaceOver = minY - mon.getY();
  52526. if (heightToUse < spaceUnder - 30 || spaceUnder >= spaceOver)
  52527. y = maxY;
  52528. else
  52529. y = minY - heightToUse;
  52530. }
  52531. else
  52532. {
  52533. bool tendTowardsRight = (minX + maxX) / 2 < mon.getCentreX();
  52534. if (owner != 0)
  52535. {
  52536. if (owner->owner != 0)
  52537. {
  52538. const bool ownerGoingRight = (owner->getX() + owner->getWidth() / 2
  52539. > owner->owner->getX() + owner->owner->getWidth() / 2);
  52540. if (ownerGoingRight && maxX + widthToUse < mon.getRight() - 4)
  52541. tendTowardsRight = true;
  52542. else if ((! ownerGoingRight) && minX > widthToUse + 4)
  52543. tendTowardsRight = false;
  52544. }
  52545. else if (maxX + widthToUse < mon.getRight() - 32)
  52546. {
  52547. tendTowardsRight = true;
  52548. }
  52549. }
  52550. const int biggestSpace = jmax (mon.getRight() - maxX,
  52551. minX - mon.getX()) - 32;
  52552. if (biggestSpace < widthToUse)
  52553. {
  52554. layoutMenuItems (biggestSpace + (maxX - minX) / 3, widthToUse, heightToUse);
  52555. if (numColumns > 1)
  52556. layoutMenuItems (biggestSpace - 4, widthToUse, heightToUse);
  52557. tendTowardsRight = (mon.getRight() - maxX) >= (minX - mon.getX());
  52558. }
  52559. if (tendTowardsRight)
  52560. x = jmin (mon.getRight() - widthToUse - 4, maxX);
  52561. else
  52562. x = jmax (mon.getX() + 4, minX - widthToUse);
  52563. y = minY;
  52564. if ((minY + maxY) / 2 > mon.getCentreY())
  52565. y = jmax (mon.getY(), maxY - heightToUse);
  52566. }
  52567. x = jlimit (mon.getX() + 1, mon.getRight() - (widthToUse + 6), x);
  52568. y = jlimit (mon.getY() + 1, mon.getBottom() - (heightToUse + 6), y);
  52569. windowPos.setBounds (x, y, widthToUse, heightToUse);
  52570. // sets this flag if it's big enough to obscure any of its parent menus
  52571. hideOnExit = (owner != 0)
  52572. && owner->windowPos.intersects (windowPos.expanded (-4, -4));
  52573. }
  52574. void layoutMenuItems (const int maxMenuW, int& width, int& height)
  52575. {
  52576. numColumns = 0;
  52577. contentHeight = 0;
  52578. const int maxMenuH = getParentHeight() - 24;
  52579. int totalW;
  52580. do
  52581. {
  52582. ++numColumns;
  52583. totalW = workOutBestSize (numColumns, maxMenuW);
  52584. if (totalW > maxMenuW)
  52585. {
  52586. numColumns = jmax (1, numColumns - 1);
  52587. totalW = workOutBestSize (numColumns, maxMenuW); // to update col widths
  52588. break;
  52589. }
  52590. else if (totalW > maxMenuW / 2 || contentHeight < maxMenuH)
  52591. {
  52592. break;
  52593. }
  52594. } while (numColumns < maximumNumColumns);
  52595. const int actualH = jmin (contentHeight, maxMenuH);
  52596. needsToScroll = contentHeight > actualH;
  52597. width = updateYPositions();
  52598. height = actualH + borderSize * 2;
  52599. }
  52600. int workOutBestSize (const int numColumns, const int maxMenuW)
  52601. {
  52602. int totalW = 0;
  52603. contentHeight = 0;
  52604. int childNum = 0;
  52605. for (int col = 0; col < numColumns; ++col)
  52606. {
  52607. int i, colW = 50, colH = 0;
  52608. const int numChildren = jmin (getNumChildComponents() - childNum,
  52609. (getNumChildComponents() + numColumns - 1) / numColumns);
  52610. for (i = numChildren; --i >= 0;)
  52611. {
  52612. colW = jmax (colW, getChildComponent (childNum + i)->getWidth());
  52613. colH += getChildComponent (childNum + i)->getHeight();
  52614. }
  52615. colW = jmin (maxMenuW / jmax (1, numColumns - 2), colW + borderSize * 2);
  52616. columnWidths.set (col, colW);
  52617. totalW += colW;
  52618. contentHeight = jmax (contentHeight, colH);
  52619. childNum += numChildren;
  52620. }
  52621. if (totalW < minimumWidth)
  52622. {
  52623. totalW = minimumWidth;
  52624. for (int col = 0; col < numColumns; ++col)
  52625. columnWidths.set (0, totalW / numColumns);
  52626. }
  52627. return totalW;
  52628. }
  52629. void ensureItemIsVisible (const int itemId, int wantedY)
  52630. {
  52631. jassert (itemId != 0)
  52632. for (int i = getNumChildComponents(); --i >= 0;)
  52633. {
  52634. MenuItemComponent* const m = (MenuItemComponent*) getChildComponent (i);
  52635. if (m != 0
  52636. && m->itemInfo.itemId == itemId
  52637. && windowPos.getHeight() > scrollZone * 4)
  52638. {
  52639. const int currentY = m->getY();
  52640. if (wantedY > 0 || currentY < 0 || m->getBottom() > windowPos.getHeight())
  52641. {
  52642. if (wantedY < 0)
  52643. wantedY = jlimit (scrollZone,
  52644. jmax (scrollZone, windowPos.getHeight() - (scrollZone + m->getHeight())),
  52645. currentY);
  52646. const Rectangle mon (Desktop::getInstance()
  52647. .getMonitorAreaContaining (windowPos.getX(),
  52648. windowPos.getY(),
  52649. true));
  52650. int deltaY = wantedY - currentY;
  52651. const int newY = jlimit (mon.getY(),
  52652. mon.getBottom() - windowPos.getHeight(),
  52653. windowPos.getY() + deltaY);
  52654. deltaY -= newY - windowPos.getY();
  52655. childYOffset -= deltaY;
  52656. windowPos.setPosition (windowPos.getX(), newY);
  52657. updateYPositions();
  52658. }
  52659. break;
  52660. }
  52661. }
  52662. }
  52663. void resizeToBestWindowPos()
  52664. {
  52665. Rectangle r (windowPos);
  52666. if (childYOffset < 0)
  52667. {
  52668. r.setBounds (r.getX(), r.getY() - childYOffset,
  52669. r.getWidth(), r.getHeight() + childYOffset);
  52670. }
  52671. else if (childYOffset > 0)
  52672. {
  52673. const int spaceAtBottom = r.getHeight() - (contentHeight - childYOffset);
  52674. if (spaceAtBottom > 0)
  52675. r.setSize (r.getWidth(), r.getHeight() - spaceAtBottom);
  52676. }
  52677. setBounds (r);
  52678. updateYPositions();
  52679. }
  52680. void alterChildYPos (const int delta)
  52681. {
  52682. if (isScrolling())
  52683. {
  52684. childYOffset += delta;
  52685. if (delta < 0)
  52686. {
  52687. childYOffset = jmax (childYOffset, 0);
  52688. }
  52689. else if (delta > 0)
  52690. {
  52691. childYOffset = jmin (childYOffset,
  52692. contentHeight - windowPos.getHeight() + borderSize);
  52693. }
  52694. updateYPositions();
  52695. }
  52696. else
  52697. {
  52698. childYOffset = 0;
  52699. }
  52700. resizeToBestWindowPos();
  52701. repaint();
  52702. }
  52703. int updateYPositions()
  52704. {
  52705. int x = 0;
  52706. int childNum = 0;
  52707. for (int col = 0; col < numColumns; ++col)
  52708. {
  52709. const int numChildren = jmin (getNumChildComponents() - childNum,
  52710. (getNumChildComponents() + numColumns - 1) / numColumns);
  52711. const int colW = columnWidths [col];
  52712. int y = borderSize - (childYOffset + (getY() - windowPos.getY()));
  52713. for (int i = 0; i < numChildren; ++i)
  52714. {
  52715. Component* const c = getChildComponent (childNum + i);
  52716. c->setBounds (x, y, colW, c->getHeight());
  52717. y += c->getHeight();
  52718. }
  52719. x += colW;
  52720. childNum += numChildren;
  52721. }
  52722. return x;
  52723. }
  52724. bool isScrolling() const throw()
  52725. {
  52726. return childYOffset != 0 || needsToScroll;
  52727. }
  52728. void setCurrentlyHighlightedChild (MenuItemComponent* const child) throw()
  52729. {
  52730. if (currentChild->isValidComponent())
  52731. currentChild->setHighlighted (false);
  52732. currentChild = child;
  52733. if (currentChild != 0)
  52734. {
  52735. currentChild->setHighlighted (true);
  52736. timeEnteredCurrentChildComp = Time::getApproximateMillisecondCounter();
  52737. }
  52738. }
  52739. bool showSubMenuFor (MenuItemComponent* const childComp)
  52740. {
  52741. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  52742. deleteAndZero (activeSubMenu);
  52743. if (childComp->isValidComponent() && childComp->itemInfo.hasActiveSubMenu())
  52744. {
  52745. int left = 0, top = 0;
  52746. childComp->relativePositionToGlobal (left, top);
  52747. int right = childComp->getWidth(), bottom = childComp->getHeight();
  52748. childComp->relativePositionToGlobal (right, bottom);
  52749. activeSubMenu = PopupMenuWindow::create (*(childComp->itemInfo.subMenu),
  52750. dismissOnMouseUp,
  52751. this,
  52752. left, right, top, bottom,
  52753. 0, maximumNumColumns,
  52754. standardItemHeight,
  52755. false, 0, menuBarComponent,
  52756. managerOfChosenCommand,
  52757. componentAttachedTo);
  52758. if (activeSubMenu != 0)
  52759. {
  52760. activeSubMenu->setVisible (true);
  52761. activeSubMenu->enterModalState (false);
  52762. activeSubMenu->toFront (false);
  52763. return true;
  52764. }
  52765. }
  52766. return false;
  52767. }
  52768. void highlightItemUnderMouse (const int mx, const int my, const int x, const int y)
  52769. {
  52770. isOver = reallyContains (x, y, true);
  52771. if (isOver)
  52772. hasBeenOver = true;
  52773. if (abs (lastMouseX - mx) > 2 || abs (lastMouseY - my) > 2)
  52774. {
  52775. lastMouseMoveTime = Time::getApproximateMillisecondCounter();
  52776. if (disableMouseMoves && isOver)
  52777. disableMouseMoves = false;
  52778. }
  52779. if (disableMouseMoves)
  52780. return;
  52781. bool isMovingTowardsMenu = false;
  52782. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent())
  52783. if (isOver && (activeSubMenu != 0) && (mx != lastMouseX || my != lastMouseY))
  52784. {
  52785. // try to intelligently guess whether the user is moving the mouse towards a currently-open
  52786. // submenu. To do this, look at whether the mouse stays inside a triangular region that
  52787. // extends from the last mouse pos to the submenu's rectangle..
  52788. float subX = (float) activeSubMenu->getScreenX();
  52789. if (activeSubMenu->getX() > getX())
  52790. {
  52791. lastMouseX -= 2; // to enlarge the triangle a bit, in case the mouse only moves a couple of pixels
  52792. }
  52793. else
  52794. {
  52795. lastMouseX += 2;
  52796. subX += activeSubMenu->getWidth();
  52797. }
  52798. Path areaTowardsSubMenu;
  52799. areaTowardsSubMenu.addTriangle ((float) lastMouseX,
  52800. (float) lastMouseY,
  52801. subX,
  52802. (float) activeSubMenu->getScreenY(),
  52803. subX,
  52804. (float) (activeSubMenu->getScreenY() + activeSubMenu->getHeight()));
  52805. isMovingTowardsMenu = areaTowardsSubMenu.contains ((float) mx, (float) my);
  52806. }
  52807. lastMouseX = mx;
  52808. lastMouseY = my;
  52809. if (! isMovingTowardsMenu)
  52810. {
  52811. Component* c = getComponentAt (x, y);
  52812. if (c == this)
  52813. c = 0;
  52814. MenuItemComponent* mic = dynamic_cast <MenuItemComponent*> (c);
  52815. if (mic == 0 && c != 0)
  52816. mic = c->findParentComponentOfClass ((MenuItemComponent*) 0);
  52817. if (mic != currentChild
  52818. && (isOver || (activeSubMenu == 0) || ! activeSubMenu->isVisible()))
  52819. {
  52820. if (isOver && (c != 0) && (activeSubMenu != 0))
  52821. {
  52822. activeSubMenu->hide (0);
  52823. }
  52824. if (! isOver)
  52825. mic = 0;
  52826. setCurrentlyHighlightedChild (mic);
  52827. }
  52828. }
  52829. }
  52830. void triggerCurrentlyHighlightedItem()
  52831. {
  52832. if (currentChild->isValidComponent()
  52833. && currentChild->itemInfo.canBeTriggered()
  52834. && (currentChild->itemInfo.customComp == 0
  52835. || currentChild->itemInfo.customComp->isTriggeredAutomatically))
  52836. {
  52837. dismissMenu (&currentChild->itemInfo);
  52838. }
  52839. }
  52840. void selectNextItem (const int delta)
  52841. {
  52842. disableTimerUntilMouseMoves();
  52843. MenuItemComponent* mic = 0;
  52844. bool wasLastOne = (currentChild == 0);
  52845. const int numItems = getNumChildComponents();
  52846. for (int i = 0; i < numItems + 1; ++i)
  52847. {
  52848. int index = (delta > 0) ? i : (numItems - 1 - i);
  52849. index = (index + numItems) % numItems;
  52850. mic = dynamic_cast <MenuItemComponent*> (getChildComponent (index));
  52851. if (mic != 0 && (mic->itemInfo.canBeTriggered() || mic->itemInfo.hasActiveSubMenu())
  52852. && wasLastOne)
  52853. break;
  52854. if (mic == currentChild)
  52855. wasLastOne = true;
  52856. }
  52857. setCurrentlyHighlightedChild (mic);
  52858. }
  52859. void disableTimerUntilMouseMoves() throw()
  52860. {
  52861. disableMouseMoves = true;
  52862. if (owner != 0)
  52863. owner->disableTimerUntilMouseMoves();
  52864. }
  52865. PopupMenuWindow (const PopupMenuWindow&);
  52866. const PopupMenuWindow& operator= (const PopupMenuWindow&);
  52867. };
  52868. PopupMenu::PopupMenu() throw()
  52869. : items (8),
  52870. lookAndFeel (0),
  52871. separatorPending (false)
  52872. {
  52873. }
  52874. PopupMenu::PopupMenu (const PopupMenu& other) throw()
  52875. : items (8),
  52876. lookAndFeel (other.lookAndFeel),
  52877. separatorPending (false)
  52878. {
  52879. items.ensureStorageAllocated (other.items.size());
  52880. for (int i = 0; i < other.items.size(); ++i)
  52881. items.add (new MenuItemInfo (*(const MenuItemInfo*) other.items.getUnchecked(i)));
  52882. }
  52883. const PopupMenu& PopupMenu::operator= (const PopupMenu& other) throw()
  52884. {
  52885. if (this != &other)
  52886. {
  52887. lookAndFeel = other.lookAndFeel;
  52888. clear();
  52889. items.ensureStorageAllocated (other.items.size());
  52890. for (int i = 0; i < other.items.size(); ++i)
  52891. items.add (new MenuItemInfo (*(const MenuItemInfo*) other.items.getUnchecked(i)));
  52892. }
  52893. return *this;
  52894. }
  52895. PopupMenu::~PopupMenu() throw()
  52896. {
  52897. clear();
  52898. }
  52899. void PopupMenu::clear() throw()
  52900. {
  52901. for (int i = items.size(); --i >= 0;)
  52902. {
  52903. MenuItemInfo* const mi = (MenuItemInfo*) items.getUnchecked(i);
  52904. delete mi;
  52905. }
  52906. items.clear();
  52907. separatorPending = false;
  52908. }
  52909. void PopupMenu::addSeparatorIfPending()
  52910. {
  52911. if (separatorPending)
  52912. {
  52913. separatorPending = false;
  52914. if (items.size() > 0)
  52915. items.add (new MenuItemInfo());
  52916. }
  52917. }
  52918. void PopupMenu::addItem (const int itemResultId,
  52919. const String& itemText,
  52920. const bool isActive,
  52921. const bool isTicked,
  52922. const Image* const iconToUse) throw()
  52923. {
  52924. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  52925. // didn't pick anything, so you shouldn't use it as the id
  52926. // for an item..
  52927. addSeparatorIfPending();
  52928. items.add (new MenuItemInfo (itemResultId,
  52929. itemText,
  52930. isActive,
  52931. isTicked,
  52932. iconToUse,
  52933. Colours::black,
  52934. false,
  52935. 0, 0, 0));
  52936. }
  52937. void PopupMenu::addCommandItem (ApplicationCommandManager* commandManager,
  52938. const int commandID,
  52939. const String& displayName) throw()
  52940. {
  52941. jassert (commandManager != 0 && commandID != 0);
  52942. const ApplicationCommandInfo* const registeredInfo = commandManager->getCommandForID (commandID);
  52943. if (registeredInfo != 0)
  52944. {
  52945. ApplicationCommandInfo info (*registeredInfo);
  52946. ApplicationCommandTarget* const target = commandManager->getTargetForCommand (commandID, info);
  52947. addSeparatorIfPending();
  52948. items.add (new MenuItemInfo (commandID,
  52949. displayName.isNotEmpty() ? displayName
  52950. : info.shortName,
  52951. target != 0 && (info.flags & ApplicationCommandInfo::isDisabled) == 0,
  52952. (info.flags & ApplicationCommandInfo::isTicked) != 0,
  52953. 0,
  52954. Colours::black,
  52955. false,
  52956. 0, 0,
  52957. commandManager));
  52958. }
  52959. }
  52960. void PopupMenu::addColouredItem (const int itemResultId,
  52961. const String& itemText,
  52962. const Colour& itemTextColour,
  52963. const bool isActive,
  52964. const bool isTicked,
  52965. const Image* const iconToUse) throw()
  52966. {
  52967. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  52968. // didn't pick anything, so you shouldn't use it as the id
  52969. // for an item..
  52970. addSeparatorIfPending();
  52971. items.add (new MenuItemInfo (itemResultId,
  52972. itemText,
  52973. isActive,
  52974. isTicked,
  52975. iconToUse,
  52976. itemTextColour,
  52977. true,
  52978. 0, 0, 0));
  52979. }
  52980. void PopupMenu::addCustomItem (const int itemResultId,
  52981. PopupMenuCustomComponent* const customComponent) throw()
  52982. {
  52983. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  52984. // didn't pick anything, so you shouldn't use it as the id
  52985. // for an item..
  52986. addSeparatorIfPending();
  52987. items.add (new MenuItemInfo (itemResultId,
  52988. String::empty,
  52989. true,
  52990. false,
  52991. 0,
  52992. Colours::black,
  52993. false,
  52994. customComponent,
  52995. 0, 0));
  52996. }
  52997. class NormalComponentWrapper : public PopupMenuCustomComponent
  52998. {
  52999. public:
  53000. NormalComponentWrapper (Component* const comp,
  53001. const int w, const int h,
  53002. const bool triggerMenuItemAutomaticallyWhenClicked)
  53003. : PopupMenuCustomComponent (triggerMenuItemAutomaticallyWhenClicked),
  53004. width (w),
  53005. height (h)
  53006. {
  53007. addAndMakeVisible (comp);
  53008. }
  53009. ~NormalComponentWrapper() {}
  53010. void getIdealSize (int& idealWidth, int& idealHeight)
  53011. {
  53012. idealWidth = width;
  53013. idealHeight = height;
  53014. }
  53015. void resized()
  53016. {
  53017. if (getChildComponent(0) != 0)
  53018. getChildComponent(0)->setBounds (0, 0, getWidth(), getHeight());
  53019. }
  53020. juce_UseDebuggingNewOperator
  53021. private:
  53022. const int width, height;
  53023. NormalComponentWrapper (const NormalComponentWrapper&);
  53024. const NormalComponentWrapper& operator= (const NormalComponentWrapper&);
  53025. };
  53026. void PopupMenu::addCustomItem (const int itemResultId,
  53027. Component* customComponent,
  53028. int idealWidth, int idealHeight,
  53029. const bool triggerMenuItemAutomaticallyWhenClicked) throw()
  53030. {
  53031. addCustomItem (itemResultId,
  53032. new NormalComponentWrapper (customComponent,
  53033. idealWidth, idealHeight,
  53034. triggerMenuItemAutomaticallyWhenClicked));
  53035. }
  53036. void PopupMenu::addSubMenu (const String& subMenuName,
  53037. const PopupMenu& subMenu,
  53038. const bool isActive,
  53039. Image* const iconToUse,
  53040. const bool isTicked) throw()
  53041. {
  53042. addSeparatorIfPending();
  53043. items.add (new MenuItemInfo (0,
  53044. subMenuName,
  53045. isActive && (subMenu.getNumItems() > 0),
  53046. isTicked,
  53047. iconToUse,
  53048. Colours::black,
  53049. false,
  53050. 0,
  53051. &subMenu,
  53052. 0));
  53053. }
  53054. void PopupMenu::addSeparator() throw()
  53055. {
  53056. separatorPending = true;
  53057. }
  53058. class HeaderItemComponent : public PopupMenuCustomComponent
  53059. {
  53060. public:
  53061. HeaderItemComponent (const String& name)
  53062. : PopupMenuCustomComponent (false)
  53063. {
  53064. setName (name);
  53065. }
  53066. ~HeaderItemComponent()
  53067. {
  53068. }
  53069. void paint (Graphics& g)
  53070. {
  53071. Font f (getLookAndFeel().getPopupMenuFont());
  53072. f.setBold (true);
  53073. g.setFont (f);
  53074. g.setColour (findColour (PopupMenu::headerTextColourId));
  53075. g.drawFittedText (getName(),
  53076. 12, 0, getWidth() - 16, proportionOfHeight (0.8f),
  53077. Justification::bottomLeft, 1);
  53078. }
  53079. void getIdealSize (int& idealWidth,
  53080. int& idealHeight)
  53081. {
  53082. getLookAndFeel().getIdealPopupMenuItemSize (getName(), false, -1, idealWidth, idealHeight);
  53083. idealHeight += idealHeight / 2;
  53084. idealWidth += idealWidth / 4;
  53085. }
  53086. juce_UseDebuggingNewOperator
  53087. };
  53088. void PopupMenu::addSectionHeader (const String& title) throw()
  53089. {
  53090. addCustomItem (0X4734a34f, new HeaderItemComponent (title));
  53091. }
  53092. Component* PopupMenu::createMenuComponent (const int x, const int y, const int w, const int h,
  53093. const int itemIdThatMustBeVisible,
  53094. const int minimumWidth,
  53095. const int maximumNumColumns,
  53096. const int standardItemHeight,
  53097. const bool alignToRectangle,
  53098. Component* menuBarComponent,
  53099. ApplicationCommandManager** managerOfChosenCommand,
  53100. Component* const componentAttachedTo) throw()
  53101. {
  53102. PopupMenuWindow* const pw
  53103. = PopupMenuWindow::create (*this,
  53104. ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown(),
  53105. 0,
  53106. x, x + w,
  53107. y, y + h,
  53108. minimumWidth,
  53109. maximumNumColumns,
  53110. standardItemHeight,
  53111. alignToRectangle,
  53112. itemIdThatMustBeVisible,
  53113. menuBarComponent,
  53114. managerOfChosenCommand,
  53115. componentAttachedTo);
  53116. if (pw != 0)
  53117. pw->setVisible (true);
  53118. return pw;
  53119. }
  53120. int PopupMenu::showMenu (const int x, const int y, const int w, const int h,
  53121. const int itemIdThatMustBeVisible,
  53122. const int minimumWidth,
  53123. const int maximumNumColumns,
  53124. const int standardItemHeight,
  53125. const bool alignToRectangle,
  53126. Component* const componentAttachedTo) throw()
  53127. {
  53128. Component* const prevFocused = Component::getCurrentlyFocusedComponent();
  53129. ComponentDeletionWatcher* deletionChecker1 = 0;
  53130. if (prevFocused != 0)
  53131. deletionChecker1 = new ComponentDeletionWatcher (prevFocused);
  53132. Component* const prevTopLevel = (prevFocused != 0) ? prevFocused->getTopLevelComponent() : 0;
  53133. ComponentDeletionWatcher* deletionChecker2 = 0;
  53134. if (prevTopLevel != 0)
  53135. deletionChecker2 = new ComponentDeletionWatcher (prevTopLevel);
  53136. wasHiddenBecauseOfAppChange = false;
  53137. int result = 0;
  53138. ApplicationCommandManager* managerOfChosenCommand = 0;
  53139. Component* const popupComp = createMenuComponent (x, y, w, h,
  53140. itemIdThatMustBeVisible,
  53141. minimumWidth,
  53142. maximumNumColumns > 0 ? maximumNumColumns : 7,
  53143. standardItemHeight,
  53144. alignToRectangle, 0,
  53145. &managerOfChosenCommand,
  53146. componentAttachedTo);
  53147. if (popupComp != 0)
  53148. {
  53149. popupComp->enterModalState (false);
  53150. popupComp->toFront (false); // need to do this after making it modal, or it could
  53151. // be stuck behind other comps that are already modal..
  53152. result = popupComp->runModalLoop();
  53153. delete popupComp;
  53154. if (! wasHiddenBecauseOfAppChange)
  53155. {
  53156. if (deletionChecker2 != 0 && ! deletionChecker2->hasBeenDeleted())
  53157. prevTopLevel->toFront (true);
  53158. if (deletionChecker1 != 0 && ! deletionChecker1->hasBeenDeleted())
  53159. prevFocused->grabKeyboardFocus();
  53160. }
  53161. }
  53162. delete deletionChecker1;
  53163. delete deletionChecker2;
  53164. if (managerOfChosenCommand != 0 && result != 0)
  53165. {
  53166. ApplicationCommandTarget::InvocationInfo info (result);
  53167. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromMenu;
  53168. managerOfChosenCommand->invoke (info, true);
  53169. }
  53170. return result;
  53171. }
  53172. int PopupMenu::show (const int itemIdThatMustBeVisible,
  53173. const int minimumWidth,
  53174. const int maximumNumColumns,
  53175. const int standardItemHeight)
  53176. {
  53177. int x, y;
  53178. Desktop::getMousePosition (x, y);
  53179. return showAt (x, y,
  53180. itemIdThatMustBeVisible,
  53181. minimumWidth,
  53182. maximumNumColumns,
  53183. standardItemHeight);
  53184. }
  53185. int PopupMenu::showAt (const int screenX,
  53186. const int screenY,
  53187. const int itemIdThatMustBeVisible,
  53188. const int minimumWidth,
  53189. const int maximumNumColumns,
  53190. const int standardItemHeight)
  53191. {
  53192. return showMenu (screenX, screenY, 1, 1,
  53193. itemIdThatMustBeVisible,
  53194. minimumWidth, maximumNumColumns,
  53195. standardItemHeight,
  53196. false, 0);
  53197. }
  53198. int PopupMenu::showAt (Component* componentToAttachTo,
  53199. const int itemIdThatMustBeVisible,
  53200. const int minimumWidth,
  53201. const int maximumNumColumns,
  53202. const int standardItemHeight)
  53203. {
  53204. if (componentToAttachTo != 0)
  53205. {
  53206. return showMenu (componentToAttachTo->getScreenX(),
  53207. componentToAttachTo->getScreenY(),
  53208. componentToAttachTo->getWidth(),
  53209. componentToAttachTo->getHeight(),
  53210. itemIdThatMustBeVisible,
  53211. minimumWidth,
  53212. maximumNumColumns,
  53213. standardItemHeight,
  53214. true, componentToAttachTo);
  53215. }
  53216. else
  53217. {
  53218. return show (itemIdThatMustBeVisible,
  53219. minimumWidth,
  53220. maximumNumColumns,
  53221. standardItemHeight);
  53222. }
  53223. }
  53224. void JUCE_CALLTYPE PopupMenu::dismissAllActiveMenus() throw()
  53225. {
  53226. for (int i = activeMenuWindows.size(); --i >= 0;)
  53227. {
  53228. PopupMenuWindow* const pmw = (PopupMenuWindow*) activeMenuWindows[i];
  53229. if (pmw != 0)
  53230. pmw->dismissMenu (0);
  53231. }
  53232. }
  53233. int PopupMenu::getNumItems() const throw()
  53234. {
  53235. int num = 0;
  53236. for (int i = items.size(); --i >= 0;)
  53237. if (! ((MenuItemInfo*) items.getUnchecked(i))->isSeparator)
  53238. ++num;
  53239. return num;
  53240. }
  53241. bool PopupMenu::containsCommandItem (const int commandID) const throw()
  53242. {
  53243. for (int i = items.size(); --i >= 0;)
  53244. {
  53245. const MenuItemInfo* mi = (const MenuItemInfo*) items.getUnchecked (i);
  53246. if ((mi->itemId == commandID && mi->commandManager != 0)
  53247. || (mi->subMenu != 0 && mi->subMenu->containsCommandItem (commandID)))
  53248. {
  53249. return true;
  53250. }
  53251. }
  53252. return false;
  53253. }
  53254. bool PopupMenu::containsAnyActiveItems() const throw()
  53255. {
  53256. for (int i = items.size(); --i >= 0;)
  53257. {
  53258. const MenuItemInfo* const mi = (const MenuItemInfo*) items.getUnchecked (i);
  53259. if (mi->subMenu != 0)
  53260. {
  53261. if (mi->subMenu->containsAnyActiveItems())
  53262. return true;
  53263. }
  53264. else if (mi->active)
  53265. {
  53266. return true;
  53267. }
  53268. }
  53269. return false;
  53270. }
  53271. void PopupMenu::setLookAndFeel (LookAndFeel* const newLookAndFeel) throw()
  53272. {
  53273. lookAndFeel = newLookAndFeel;
  53274. }
  53275. PopupMenuCustomComponent::PopupMenuCustomComponent (const bool isTriggeredAutomatically_)
  53276. : refCount_ (0),
  53277. isHighlighted (false),
  53278. isTriggeredAutomatically (isTriggeredAutomatically_)
  53279. {
  53280. }
  53281. PopupMenuCustomComponent::~PopupMenuCustomComponent()
  53282. {
  53283. jassert (refCount_ == 0); // should be deleted only by the menu component, as they keep a ref-count.
  53284. }
  53285. void PopupMenuCustomComponent::triggerMenuItem()
  53286. {
  53287. MenuItemComponent* const mic = dynamic_cast<MenuItemComponent*> (getParentComponent());
  53288. if (mic != 0)
  53289. {
  53290. PopupMenuWindow* const pmw = dynamic_cast<PopupMenuWindow*> (mic->getParentComponent());
  53291. if (pmw != 0)
  53292. {
  53293. pmw->dismissMenu (&mic->itemInfo);
  53294. }
  53295. else
  53296. {
  53297. // something must have gone wrong with the component hierarchy if this happens..
  53298. jassertfalse
  53299. }
  53300. }
  53301. else
  53302. {
  53303. // why isn't this component inside a menu? Not much point triggering the item if
  53304. // there's no menu.
  53305. jassertfalse
  53306. }
  53307. }
  53308. PopupMenu::MenuItemIterator::MenuItemIterator (const PopupMenu& menu_) throw()
  53309. : subMenu (0),
  53310. itemId (0),
  53311. isSeparator (false),
  53312. isTicked (false),
  53313. isEnabled (false),
  53314. isCustomComponent (false),
  53315. isSectionHeader (false),
  53316. customColour (0),
  53317. customImage (0),
  53318. menu (menu_),
  53319. index (0)
  53320. {
  53321. }
  53322. PopupMenu::MenuItemIterator::~MenuItemIterator() throw()
  53323. {
  53324. }
  53325. bool PopupMenu::MenuItemIterator::next() throw()
  53326. {
  53327. if (index >= menu.items.size())
  53328. return false;
  53329. const MenuItemInfo* const item = (const MenuItemInfo*) menu.items.getUnchecked (index);
  53330. ++index;
  53331. itemName = item->customComp != 0 ? item->customComp->getName() : item->text;
  53332. subMenu = item->subMenu;
  53333. itemId = item->itemId;
  53334. isSeparator = item->isSeparator;
  53335. isTicked = item->isTicked;
  53336. isEnabled = item->active;
  53337. isSectionHeader = dynamic_cast <HeaderItemComponent*> (item->customComp) != 0;
  53338. isCustomComponent = (! isSectionHeader) && item->customComp != 0;
  53339. customColour = item->usesColour ? &(item->textColour) : 0;
  53340. customImage = item->image;
  53341. commandManager = item->commandManager;
  53342. return true;
  53343. }
  53344. END_JUCE_NAMESPACE
  53345. /********* End of inlined file: juce_PopupMenu.cpp *********/
  53346. /********* Start of inlined file: juce_ComponentDragger.cpp *********/
  53347. BEGIN_JUCE_NAMESPACE
  53348. ComponentDragger::ComponentDragger()
  53349. : constrainer (0),
  53350. originalX (0),
  53351. originalY (0)
  53352. {
  53353. }
  53354. ComponentDragger::~ComponentDragger()
  53355. {
  53356. }
  53357. void ComponentDragger::startDraggingComponent (Component* const componentToDrag,
  53358. ComponentBoundsConstrainer* const constrainer_)
  53359. {
  53360. jassert (componentToDrag->isValidComponent());
  53361. if (componentToDrag->isValidComponent())
  53362. {
  53363. constrainer = constrainer_;
  53364. originalX = 0;
  53365. originalY = 0;
  53366. componentToDrag->relativePositionToGlobal (originalX, originalY);
  53367. }
  53368. }
  53369. void ComponentDragger::dragComponent (Component* const componentToDrag, const MouseEvent& e)
  53370. {
  53371. jassert (componentToDrag->isValidComponent());
  53372. jassert (e.mods.isAnyMouseButtonDown()); // (the event has to be a drag event..)
  53373. if (componentToDrag->isValidComponent())
  53374. {
  53375. int x = originalX;
  53376. int y = originalY;
  53377. int w = componentToDrag->getWidth();
  53378. int h = componentToDrag->getHeight();
  53379. const Component* const parentComp = componentToDrag->getParentComponent();
  53380. if (parentComp != 0)
  53381. parentComp->globalPositionToRelative (x, y);
  53382. x += e.getDistanceFromDragStartX();
  53383. y += e.getDistanceFromDragStartY();
  53384. if (constrainer != 0)
  53385. constrainer->setBoundsForComponent (componentToDrag, x, y, w, h,
  53386. false, false, false, false);
  53387. else
  53388. componentToDrag->setBounds (x, y, w, h);
  53389. }
  53390. }
  53391. END_JUCE_NAMESPACE
  53392. /********* End of inlined file: juce_ComponentDragger.cpp *********/
  53393. /********* Start of inlined file: juce_DragAndDropContainer.cpp *********/
  53394. BEGIN_JUCE_NAMESPACE
  53395. bool juce_performDragDropFiles (const StringArray& files, const bool copyFiles, bool& shouldStop);
  53396. bool juce_performDragDropText (const String& text, bool& shouldStop);
  53397. class DragImageComponent : public Component,
  53398. public Timer
  53399. {
  53400. private:
  53401. Image* image;
  53402. Component* const source;
  53403. DragAndDropContainer* const owner;
  53404. ComponentDeletionWatcher* sourceWatcher;
  53405. Component* mouseDragSource;
  53406. ComponentDeletionWatcher* mouseDragSourceWatcher;
  53407. DragAndDropTarget* currentlyOver;
  53408. ComponentDeletionWatcher* currentlyOverWatcher;
  53409. String dragDesc;
  53410. int xOff, yOff;
  53411. bool hasCheckedForExternalDrag, drawImage;
  53412. DragImageComponent (const DragImageComponent&);
  53413. const DragImageComponent& operator= (const DragImageComponent&);
  53414. public:
  53415. DragImageComponent (Image* const im,
  53416. const String& desc,
  53417. Component* const s,
  53418. DragAndDropContainer* const o)
  53419. : image (im),
  53420. source (s),
  53421. owner (o),
  53422. currentlyOver (0),
  53423. currentlyOverWatcher (0),
  53424. dragDesc (desc),
  53425. hasCheckedForExternalDrag (false),
  53426. drawImage (true)
  53427. {
  53428. setSize (im->getWidth(), im->getHeight());
  53429. sourceWatcher = new ComponentDeletionWatcher (source);
  53430. mouseDragSource = Component::getComponentUnderMouse();
  53431. if (mouseDragSource == 0)
  53432. mouseDragSource = source;
  53433. mouseDragSourceWatcher = new ComponentDeletionWatcher (mouseDragSource);
  53434. mouseDragSource->addMouseListener (this, false);
  53435. int mx, my;
  53436. Desktop::getLastMouseDownPosition (mx, my);
  53437. source->globalPositionToRelative (mx, my);
  53438. xOff = jlimit (0, im->getWidth(), mx);
  53439. yOff = jlimit (0, im->getHeight(), my);
  53440. startTimer (200);
  53441. setInterceptsMouseClicks (false, false);
  53442. setAlwaysOnTop (true);
  53443. }
  53444. ~DragImageComponent()
  53445. {
  53446. if (owner->dragImageComponent == this)
  53447. owner->dragImageComponent = 0;
  53448. if (! mouseDragSourceWatcher->hasBeenDeleted())
  53449. {
  53450. mouseDragSource->removeMouseListener (this);
  53451. if (currentlyOverWatcher != 0 && ! currentlyOverWatcher->hasBeenDeleted())
  53452. if (currentlyOver->isInterestedInDragSource (dragDesc, source))
  53453. currentlyOver->itemDragExit (dragDesc, source);
  53454. }
  53455. delete mouseDragSourceWatcher;
  53456. delete sourceWatcher;
  53457. delete image;
  53458. delete currentlyOverWatcher;
  53459. }
  53460. void paint (Graphics& g)
  53461. {
  53462. if (isOpaque())
  53463. g.fillAll (Colours::white);
  53464. if (drawImage)
  53465. {
  53466. g.setOpacity (1.0f);
  53467. g.drawImageAt (image, 0, 0);
  53468. }
  53469. }
  53470. DragAndDropTarget* findTarget (const int screenX, const int screenY,
  53471. int& relX, int& relY) const throw()
  53472. {
  53473. Component* hit = getParentComponent();
  53474. if (hit == 0)
  53475. {
  53476. hit = Desktop::getInstance().findComponentAt (screenX, screenY);
  53477. }
  53478. else
  53479. {
  53480. int rx = screenX, ry = screenY;
  53481. hit->globalPositionToRelative (rx, ry);
  53482. hit = hit->getComponentAt (rx, ry);
  53483. }
  53484. // (note: use a local copy of the dragDesc member in case the callback runs
  53485. // a modal loop and deletes this object before the method completes)
  53486. const String dragDescLocal (dragDesc);
  53487. while (hit != 0)
  53488. {
  53489. DragAndDropTarget* const ddt = dynamic_cast <DragAndDropTarget*> (hit);
  53490. if (ddt != 0 && ddt->isInterestedInDragSource (dragDescLocal, source))
  53491. {
  53492. relX = screenX;
  53493. relY = screenY;
  53494. hit->globalPositionToRelative (relX, relY);
  53495. return ddt;
  53496. }
  53497. hit = hit->getParentComponent();
  53498. }
  53499. return 0;
  53500. }
  53501. void mouseUp (const MouseEvent& e)
  53502. {
  53503. if (e.originalComponent != this)
  53504. {
  53505. if (! mouseDragSourceWatcher->hasBeenDeleted())
  53506. mouseDragSource->removeMouseListener (this);
  53507. bool dropAccepted = false;
  53508. DragAndDropTarget* ddt = 0;
  53509. int relX = 0, relY = 0;
  53510. if (isVisible())
  53511. {
  53512. setVisible (false);
  53513. ddt = findTarget (e.getScreenX(),
  53514. e.getScreenY(),
  53515. relX, relY);
  53516. // fade this component and remove it - it'll be deleted later by the timer callback
  53517. dropAccepted = ddt != 0;
  53518. setVisible (true);
  53519. if (dropAccepted || sourceWatcher->hasBeenDeleted())
  53520. {
  53521. fadeOutComponent (120);
  53522. }
  53523. else
  53524. {
  53525. int targetX = source->getWidth() / 2;
  53526. int targetY = source->getHeight() / 2;
  53527. source->relativePositionToGlobal (targetX, targetY);
  53528. int ourCentreX = getWidth() / 2;
  53529. int ourCentreY = getHeight() / 2;
  53530. relativePositionToGlobal (ourCentreX, ourCentreY);
  53531. fadeOutComponent (120,
  53532. targetX - ourCentreX,
  53533. targetY - ourCentreY);
  53534. }
  53535. }
  53536. if (getParentComponent() != 0)
  53537. getParentComponent()->removeChildComponent (this);
  53538. if (dropAccepted && ddt != 0)
  53539. {
  53540. // (note: use a local copy of the dragDesc member in case the callback runs
  53541. // a modal loop and deletes this object before the method completes)
  53542. const String dragDescLocal (dragDesc);
  53543. currentlyOver = 0;
  53544. deleteAndZero (currentlyOverWatcher);
  53545. ddt->itemDropped (dragDescLocal, source, relX, relY);
  53546. }
  53547. // careful - this object could now be deleted..
  53548. }
  53549. }
  53550. void updateLocation (const bool canDoExternalDrag, int x, int y)
  53551. {
  53552. // (note: use a local copy of the dragDesc member in case the callback runs
  53553. // a modal loop and deletes this object before it returns)
  53554. const String dragDescLocal (dragDesc);
  53555. int newX = x - xOff;
  53556. int newY = y - yOff;
  53557. if (getParentComponent() != 0)
  53558. getParentComponent()->globalPositionToRelative (newX, newY);
  53559. if (newX != getX() || newY != getY())
  53560. {
  53561. setTopLeftPosition (newX, newY);
  53562. int relX = 0, relY = 0;
  53563. DragAndDropTarget* const ddt = findTarget (x, y, relX, relY);
  53564. drawImage = (ddt == 0) || ddt->shouldDrawDragImageWhenOver();
  53565. if (ddt != currentlyOver)
  53566. {
  53567. if (currentlyOverWatcher != 0 && ! currentlyOverWatcher->hasBeenDeleted())
  53568. {
  53569. Component* const over = dynamic_cast <Component*> (currentlyOver);
  53570. if (over != 0
  53571. && over->isValidComponent()
  53572. && ! (sourceWatcher->hasBeenDeleted())
  53573. && currentlyOver->isInterestedInDragSource (dragDescLocal, source))
  53574. {
  53575. currentlyOver->itemDragExit (dragDescLocal, source);
  53576. }
  53577. }
  53578. currentlyOver = ddt;
  53579. deleteAndZero (currentlyOverWatcher);
  53580. if (ddt != 0)
  53581. {
  53582. currentlyOverWatcher = new ComponentDeletionWatcher (dynamic_cast <Component*> (ddt));
  53583. if (currentlyOver->isInterestedInDragSource (dragDescLocal, source))
  53584. currentlyOver->itemDragEnter (dragDescLocal, source, relX, relY);
  53585. }
  53586. }
  53587. else if (currentlyOverWatcher != 0 && currentlyOverWatcher->hasBeenDeleted())
  53588. {
  53589. currentlyOver = 0;
  53590. deleteAndZero (currentlyOverWatcher);
  53591. }
  53592. if (currentlyOver != 0
  53593. && currentlyOver->isInterestedInDragSource (dragDescLocal, source))
  53594. currentlyOver->itemDragMove (dragDescLocal, source, relX, relY);
  53595. if (currentlyOver == 0
  53596. && canDoExternalDrag
  53597. && ! hasCheckedForExternalDrag)
  53598. {
  53599. if (Desktop::getInstance().findComponentAt (x, y) == 0)
  53600. {
  53601. hasCheckedForExternalDrag = true;
  53602. StringArray files;
  53603. bool canMoveFiles = false;
  53604. if (owner->shouldDropFilesWhenDraggedExternally (dragDescLocal, source, files, canMoveFiles)
  53605. && files.size() > 0)
  53606. {
  53607. ComponentDeletionWatcher cdw (this);
  53608. setVisible (false);
  53609. if (ModifierKeys::getCurrentModifiersRealtime().isAnyMouseButtonDown())
  53610. DragAndDropContainer::performExternalDragDropOfFiles (files, canMoveFiles);
  53611. if (! cdw.hasBeenDeleted())
  53612. delete this;
  53613. return;
  53614. }
  53615. }
  53616. }
  53617. }
  53618. }
  53619. void mouseDrag (const MouseEvent& e)
  53620. {
  53621. if (e.originalComponent != this)
  53622. updateLocation (true, e.getScreenX(), e.getScreenY());
  53623. }
  53624. void timerCallback()
  53625. {
  53626. if (sourceWatcher->hasBeenDeleted())
  53627. {
  53628. delete this;
  53629. }
  53630. else if (! isMouseButtonDownAnywhere())
  53631. {
  53632. if (! mouseDragSourceWatcher->hasBeenDeleted())
  53633. mouseDragSource->removeMouseListener (this);
  53634. delete this;
  53635. }
  53636. }
  53637. };
  53638. DragAndDropContainer::DragAndDropContainer()
  53639. : dragImageComponent (0)
  53640. {
  53641. }
  53642. DragAndDropContainer::~DragAndDropContainer()
  53643. {
  53644. if (dragImageComponent != 0)
  53645. delete dragImageComponent;
  53646. }
  53647. void DragAndDropContainer::startDragging (const String& sourceDescription,
  53648. Component* sourceComponent,
  53649. Image* im,
  53650. const bool allowDraggingToExternalWindows)
  53651. {
  53652. if (dragImageComponent != 0)
  53653. {
  53654. if (im != 0)
  53655. delete im;
  53656. }
  53657. else
  53658. {
  53659. Component* const thisComp = dynamic_cast <Component*> (this);
  53660. if (thisComp != 0)
  53661. {
  53662. int mx, my;
  53663. Desktop::getLastMouseDownPosition (mx, my);
  53664. if (im == 0)
  53665. {
  53666. im = sourceComponent->createComponentSnapshot (Rectangle (0, 0, sourceComponent->getWidth(), sourceComponent->getHeight()));
  53667. if (im->getFormat() != Image::ARGB)
  53668. {
  53669. Image* newIm = new Image (Image::ARGB, im->getWidth(), im->getHeight(), true);
  53670. Graphics g2 (*newIm);
  53671. g2.drawImageAt (im, 0, 0);
  53672. delete im;
  53673. im = newIm;
  53674. }
  53675. im->multiplyAllAlphas (0.6f);
  53676. const int lo = 150;
  53677. const int hi = 400;
  53678. int rx = mx, ry = my;
  53679. sourceComponent->globalPositionToRelative (rx, ry);
  53680. const int cx = jlimit (0, im->getWidth(), rx);
  53681. const int cy = jlimit (0, im->getHeight(), ry);
  53682. for (int y = im->getHeight(); --y >= 0;)
  53683. {
  53684. const double dy = (y - cy) * (y - cy);
  53685. for (int x = im->getWidth(); --x >= 0;)
  53686. {
  53687. const int dx = x - cx;
  53688. const int distance = roundDoubleToInt (sqrt (dx * dx + dy));
  53689. if (distance > lo)
  53690. {
  53691. const float alpha = (distance > hi) ? 0
  53692. : (hi - distance) / (float) (hi - lo)
  53693. + Random::getSystemRandom().nextFloat() * 0.008f;
  53694. im->multiplyAlphaAt (x, y, alpha);
  53695. }
  53696. }
  53697. }
  53698. }
  53699. DragImageComponent* const dic
  53700. = new DragImageComponent (im,
  53701. sourceDescription,
  53702. sourceComponent,
  53703. this);
  53704. dragImageComponent = dic;
  53705. currentDragDesc = sourceDescription;
  53706. if (allowDraggingToExternalWindows)
  53707. {
  53708. if (! Desktop::canUseSemiTransparentWindows())
  53709. dic->setOpaque (true);
  53710. dic->addToDesktop (ComponentPeer::windowIgnoresMouseClicks
  53711. | ComponentPeer::windowIsTemporary
  53712. | ComponentPeer::windowIgnoresKeyPresses);
  53713. }
  53714. else
  53715. thisComp->addChildComponent (dic);
  53716. dic->updateLocation (false, mx, my);
  53717. dic->setVisible (true);
  53718. }
  53719. else
  53720. {
  53721. // this class must only be implemented by an object that
  53722. // is also a Component.
  53723. jassertfalse
  53724. if (im != 0)
  53725. delete im;
  53726. }
  53727. }
  53728. }
  53729. bool DragAndDropContainer::isDragAndDropActive() const
  53730. {
  53731. return dragImageComponent != 0;
  53732. }
  53733. const String DragAndDropContainer::getCurrentDragDescription() const
  53734. {
  53735. return (dragImageComponent != 0) ? currentDragDesc
  53736. : String::empty;
  53737. }
  53738. DragAndDropContainer* DragAndDropContainer::findParentDragContainerFor (Component* c)
  53739. {
  53740. if (c == 0)
  53741. return 0;
  53742. // (unable to use the syntax findParentComponentOfClass <DragAndDropContainer> () because of a VC6 compiler bug)
  53743. return c->findParentComponentOfClass ((DragAndDropContainer*) 0);
  53744. }
  53745. bool DragAndDropContainer::shouldDropFilesWhenDraggedExternally (const String&, Component*, StringArray&, bool&)
  53746. {
  53747. return false;
  53748. }
  53749. void DragAndDropTarget::itemDragEnter (const String&, Component*, int, int)
  53750. {
  53751. }
  53752. void DragAndDropTarget::itemDragMove (const String&, Component*, int, int)
  53753. {
  53754. }
  53755. void DragAndDropTarget::itemDragExit (const String&, Component*)
  53756. {
  53757. }
  53758. bool DragAndDropTarget::shouldDrawDragImageWhenOver()
  53759. {
  53760. return true;
  53761. }
  53762. void FileDragAndDropTarget::fileDragEnter (const StringArray&, int, int)
  53763. {
  53764. }
  53765. void FileDragAndDropTarget::fileDragMove (const StringArray&, int, int)
  53766. {
  53767. }
  53768. void FileDragAndDropTarget::fileDragExit (const StringArray&)
  53769. {
  53770. }
  53771. END_JUCE_NAMESPACE
  53772. /********* End of inlined file: juce_DragAndDropContainer.cpp *********/
  53773. /********* Start of inlined file: juce_MouseCursor.cpp *********/
  53774. BEGIN_JUCE_NAMESPACE
  53775. void* juce_createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY) throw();
  53776. void* juce_createStandardMouseCursor (MouseCursor::StandardCursorType type) throw();
  53777. // isStandard set depending on which interface was used to create the cursor
  53778. void juce_deleteMouseCursor (void* const cursorHandle, const bool isStandard) throw();
  53779. static CriticalSection mouseCursorLock;
  53780. static VoidArray standardCursors (2);
  53781. class RefCountedMouseCursor
  53782. {
  53783. public:
  53784. RefCountedMouseCursor (const MouseCursor::StandardCursorType t) throw()
  53785. : refCount (1),
  53786. standardType (t),
  53787. isStandard (true)
  53788. {
  53789. handle = juce_createStandardMouseCursor (standardType);
  53790. standardCursors.add (this);
  53791. }
  53792. RefCountedMouseCursor (Image& image,
  53793. const int hotSpotX,
  53794. const int hotSpotY) throw()
  53795. : refCount (1),
  53796. standardType (MouseCursor::NormalCursor),
  53797. isStandard (false)
  53798. {
  53799. handle = juce_createMouseCursorFromImage (image, hotSpotX, hotSpotY);
  53800. }
  53801. ~RefCountedMouseCursor() throw()
  53802. {
  53803. juce_deleteMouseCursor (handle, isStandard);
  53804. standardCursors.removeValue (this);
  53805. }
  53806. void decRef() throw()
  53807. {
  53808. if (--refCount == 0)
  53809. delete this;
  53810. }
  53811. void incRef() throw()
  53812. {
  53813. ++refCount;
  53814. }
  53815. void* getHandle() const throw()
  53816. {
  53817. return handle;
  53818. }
  53819. static RefCountedMouseCursor* findInstance (MouseCursor::StandardCursorType type) throw()
  53820. {
  53821. const ScopedLock sl (mouseCursorLock);
  53822. for (int i = 0; i < standardCursors.size(); i++)
  53823. {
  53824. RefCountedMouseCursor* const r = (RefCountedMouseCursor*) standardCursors.getUnchecked(i);
  53825. if (r->standardType == type)
  53826. {
  53827. r->incRef();
  53828. return r;
  53829. }
  53830. }
  53831. return new RefCountedMouseCursor (type);
  53832. }
  53833. juce_UseDebuggingNewOperator
  53834. private:
  53835. void* handle;
  53836. int refCount;
  53837. const MouseCursor::StandardCursorType standardType;
  53838. const bool isStandard;
  53839. const RefCountedMouseCursor& operator= (const RefCountedMouseCursor&);
  53840. };
  53841. MouseCursor::MouseCursor() throw()
  53842. {
  53843. cursorHandle = RefCountedMouseCursor::findInstance (NormalCursor);
  53844. }
  53845. MouseCursor::MouseCursor (const StandardCursorType type) throw()
  53846. {
  53847. cursorHandle = RefCountedMouseCursor::findInstance (type);
  53848. }
  53849. MouseCursor::MouseCursor (Image& image,
  53850. const int hotSpotX,
  53851. const int hotSpotY) throw()
  53852. {
  53853. cursorHandle = new RefCountedMouseCursor (image, hotSpotX, hotSpotY);
  53854. }
  53855. MouseCursor::MouseCursor (const MouseCursor& other) throw()
  53856. : cursorHandle (other.cursorHandle)
  53857. {
  53858. const ScopedLock sl (mouseCursorLock);
  53859. cursorHandle->incRef();
  53860. }
  53861. MouseCursor::~MouseCursor() throw()
  53862. {
  53863. const ScopedLock sl (mouseCursorLock);
  53864. cursorHandle->decRef();
  53865. }
  53866. const MouseCursor& MouseCursor::operator= (const MouseCursor& other) throw()
  53867. {
  53868. if (this != &other)
  53869. {
  53870. const ScopedLock sl (mouseCursorLock);
  53871. cursorHandle->decRef();
  53872. cursorHandle = other.cursorHandle;
  53873. cursorHandle->incRef();
  53874. }
  53875. return *this;
  53876. }
  53877. bool MouseCursor::operator== (const MouseCursor& other) const throw()
  53878. {
  53879. return cursorHandle == other.cursorHandle;
  53880. }
  53881. bool MouseCursor::operator!= (const MouseCursor& other) const throw()
  53882. {
  53883. return cursorHandle != other.cursorHandle;
  53884. }
  53885. void* MouseCursor::getHandle() const throw()
  53886. {
  53887. return cursorHandle->getHandle();
  53888. }
  53889. void MouseCursor::showWaitCursor() throw()
  53890. {
  53891. const MouseCursor mc (MouseCursor::WaitCursor);
  53892. mc.showInAllWindows();
  53893. }
  53894. void MouseCursor::hideWaitCursor() throw()
  53895. {
  53896. if (Component::getComponentUnderMouse()->isValidComponent())
  53897. {
  53898. Component::getComponentUnderMouse()->getMouseCursor().showInAllWindows();
  53899. }
  53900. else
  53901. {
  53902. const MouseCursor mc (MouseCursor::NormalCursor);
  53903. mc.showInAllWindows();
  53904. }
  53905. }
  53906. END_JUCE_NAMESPACE
  53907. /********* End of inlined file: juce_MouseCursor.cpp *********/
  53908. /********* Start of inlined file: juce_MouseEvent.cpp *********/
  53909. BEGIN_JUCE_NAMESPACE
  53910. MouseEvent::MouseEvent (const int x_,
  53911. const int y_,
  53912. const ModifierKeys& mods_,
  53913. Component* const originator,
  53914. const Time& eventTime_,
  53915. const int mouseDownX_,
  53916. const int mouseDownY_,
  53917. const Time& mouseDownTime_,
  53918. const int numberOfClicks_,
  53919. const bool mouseWasDragged) throw()
  53920. : x (x_),
  53921. y (y_),
  53922. mods (mods_),
  53923. eventComponent (originator),
  53924. originalComponent (originator),
  53925. eventTime (eventTime_),
  53926. mouseDownX (mouseDownX_),
  53927. mouseDownY (mouseDownY_),
  53928. mouseDownTime (mouseDownTime_),
  53929. numberOfClicks (numberOfClicks_),
  53930. wasMovedSinceMouseDown (mouseWasDragged)
  53931. {
  53932. }
  53933. MouseEvent::~MouseEvent() throw()
  53934. {
  53935. }
  53936. bool MouseEvent::mouseWasClicked() const throw()
  53937. {
  53938. return ! wasMovedSinceMouseDown;
  53939. }
  53940. int MouseEvent::getMouseDownX() const throw()
  53941. {
  53942. return mouseDownX;
  53943. }
  53944. int MouseEvent::getMouseDownY() const throw()
  53945. {
  53946. return mouseDownY;
  53947. }
  53948. int MouseEvent::getDistanceFromDragStartX() const throw()
  53949. {
  53950. return x - mouseDownX;
  53951. }
  53952. int MouseEvent::getDistanceFromDragStartY() const throw()
  53953. {
  53954. return y - mouseDownY;
  53955. }
  53956. int MouseEvent::getDistanceFromDragStart() const throw()
  53957. {
  53958. return roundDoubleToInt (juce_hypot (getDistanceFromDragStartX(),
  53959. getDistanceFromDragStartY()));
  53960. }
  53961. int MouseEvent::getLengthOfMousePress() const throw()
  53962. {
  53963. if (mouseDownTime.toMilliseconds() > 0)
  53964. return jmax (0, (int) (eventTime - mouseDownTime).inMilliseconds());
  53965. return 0;
  53966. }
  53967. int MouseEvent::getScreenX() const throw()
  53968. {
  53969. int sx = x, sy = y;
  53970. eventComponent->relativePositionToGlobal (sx, sy);
  53971. return sx;
  53972. }
  53973. int MouseEvent::getScreenY() const throw()
  53974. {
  53975. int sx = x, sy = y;
  53976. eventComponent->relativePositionToGlobal (sx, sy);
  53977. return sy;
  53978. }
  53979. int MouseEvent::getMouseDownScreenX() const throw()
  53980. {
  53981. int sx = mouseDownX, sy = mouseDownY;
  53982. eventComponent->relativePositionToGlobal (sx, sy);
  53983. return sx;
  53984. }
  53985. int MouseEvent::getMouseDownScreenY() const throw()
  53986. {
  53987. int sx = mouseDownX, sy = mouseDownY;
  53988. eventComponent->relativePositionToGlobal (sx, sy);
  53989. return sy;
  53990. }
  53991. const MouseEvent MouseEvent::getEventRelativeTo (Component* const otherComponent) const throw()
  53992. {
  53993. if (otherComponent == 0)
  53994. {
  53995. jassertfalse
  53996. return *this;
  53997. }
  53998. MouseEvent me (*this);
  53999. eventComponent->relativePositionToOtherComponent (otherComponent, me.x, me.y);
  54000. eventComponent->relativePositionToOtherComponent (otherComponent, me.mouseDownX, me.mouseDownY);
  54001. me.eventComponent = otherComponent;
  54002. return me;
  54003. }
  54004. static int doubleClickTimeOutMs = 400;
  54005. void MouseEvent::setDoubleClickTimeout (const int newTime) throw()
  54006. {
  54007. doubleClickTimeOutMs = newTime;
  54008. }
  54009. int MouseEvent::getDoubleClickTimeout() throw()
  54010. {
  54011. return doubleClickTimeOutMs;
  54012. }
  54013. END_JUCE_NAMESPACE
  54014. /********* End of inlined file: juce_MouseEvent.cpp *********/
  54015. /********* Start of inlined file: juce_MouseHoverDetector.cpp *********/
  54016. BEGIN_JUCE_NAMESPACE
  54017. MouseHoverDetector::MouseHoverDetector (const int hoverTimeMillisecs_)
  54018. : source (0),
  54019. hoverTimeMillisecs (hoverTimeMillisecs_),
  54020. hasJustHovered (false)
  54021. {
  54022. internalTimer.owner = this;
  54023. }
  54024. MouseHoverDetector::~MouseHoverDetector()
  54025. {
  54026. setHoverComponent (0);
  54027. }
  54028. void MouseHoverDetector::setHoverTimeMillisecs (const int newTimeInMillisecs)
  54029. {
  54030. hoverTimeMillisecs = newTimeInMillisecs;
  54031. }
  54032. void MouseHoverDetector::setHoverComponent (Component* const newSourceComponent)
  54033. {
  54034. if (source != newSourceComponent)
  54035. {
  54036. internalTimer.stopTimer();
  54037. hasJustHovered = false;
  54038. if (source != 0)
  54039. {
  54040. // ! you need to delete the hover detector before deleting its component
  54041. jassert (source->isValidComponent());
  54042. source->removeMouseListener (&internalTimer);
  54043. }
  54044. source = newSourceComponent;
  54045. if (newSourceComponent != 0)
  54046. newSourceComponent->addMouseListener (&internalTimer, false);
  54047. }
  54048. }
  54049. void MouseHoverDetector::hoverTimerCallback()
  54050. {
  54051. internalTimer.stopTimer();
  54052. if (source != 0)
  54053. {
  54054. int mx, my;
  54055. source->getMouseXYRelative (mx, my);
  54056. if (source->reallyContains (mx, my, false))
  54057. {
  54058. hasJustHovered = true;
  54059. mouseHovered (mx, my);
  54060. }
  54061. }
  54062. }
  54063. void MouseHoverDetector::checkJustHoveredCallback()
  54064. {
  54065. if (hasJustHovered)
  54066. {
  54067. hasJustHovered = false;
  54068. mouseMovedAfterHover();
  54069. }
  54070. }
  54071. void MouseHoverDetector::HoverDetectorInternal::timerCallback()
  54072. {
  54073. owner->hoverTimerCallback();
  54074. }
  54075. void MouseHoverDetector::HoverDetectorInternal::mouseEnter (const MouseEvent&)
  54076. {
  54077. stopTimer();
  54078. owner->checkJustHoveredCallback();
  54079. }
  54080. void MouseHoverDetector::HoverDetectorInternal::mouseExit (const MouseEvent&)
  54081. {
  54082. stopTimer();
  54083. owner->checkJustHoveredCallback();
  54084. }
  54085. void MouseHoverDetector::HoverDetectorInternal::mouseDown (const MouseEvent&)
  54086. {
  54087. stopTimer();
  54088. owner->checkJustHoveredCallback();
  54089. }
  54090. void MouseHoverDetector::HoverDetectorInternal::mouseUp (const MouseEvent&)
  54091. {
  54092. stopTimer();
  54093. owner->checkJustHoveredCallback();
  54094. }
  54095. void MouseHoverDetector::HoverDetectorInternal::mouseMove (const MouseEvent& e)
  54096. {
  54097. if (lastX != e.x || lastY != e.y) // to avoid fake mouse-moves setting it off
  54098. {
  54099. lastX = e.x;
  54100. lastY = e.y;
  54101. if (owner->source != 0)
  54102. startTimer (owner->hoverTimeMillisecs);
  54103. owner->checkJustHoveredCallback();
  54104. }
  54105. }
  54106. void MouseHoverDetector::HoverDetectorInternal::mouseWheelMove (const MouseEvent&, float, float)
  54107. {
  54108. stopTimer();
  54109. owner->checkJustHoveredCallback();
  54110. }
  54111. END_JUCE_NAMESPACE
  54112. /********* End of inlined file: juce_MouseHoverDetector.cpp *********/
  54113. /********* Start of inlined file: juce_MouseListener.cpp *********/
  54114. BEGIN_JUCE_NAMESPACE
  54115. void MouseListener::mouseEnter (const MouseEvent&)
  54116. {
  54117. }
  54118. void MouseListener::mouseExit (const MouseEvent&)
  54119. {
  54120. }
  54121. void MouseListener::mouseDown (const MouseEvent&)
  54122. {
  54123. }
  54124. void MouseListener::mouseUp (const MouseEvent&)
  54125. {
  54126. }
  54127. void MouseListener::mouseDrag (const MouseEvent&)
  54128. {
  54129. }
  54130. void MouseListener::mouseMove (const MouseEvent&)
  54131. {
  54132. }
  54133. void MouseListener::mouseDoubleClick (const MouseEvent&)
  54134. {
  54135. }
  54136. void MouseListener::mouseWheelMove (const MouseEvent&, float, float)
  54137. {
  54138. }
  54139. END_JUCE_NAMESPACE
  54140. /********* End of inlined file: juce_MouseListener.cpp *********/
  54141. /********* Start of inlined file: juce_BooleanPropertyComponent.cpp *********/
  54142. BEGIN_JUCE_NAMESPACE
  54143. BooleanPropertyComponent::BooleanPropertyComponent (const String& name,
  54144. const String& buttonTextWhenTrue,
  54145. const String& buttonTextWhenFalse)
  54146. : PropertyComponent (name),
  54147. onText (buttonTextWhenTrue),
  54148. offText (buttonTextWhenFalse)
  54149. {
  54150. addAndMakeVisible (button = new ToggleButton (String::empty));
  54151. button->setClickingTogglesState (false);
  54152. button->addButtonListener (this);
  54153. }
  54154. BooleanPropertyComponent::~BooleanPropertyComponent()
  54155. {
  54156. deleteAllChildren();
  54157. }
  54158. void BooleanPropertyComponent::paint (Graphics& g)
  54159. {
  54160. PropertyComponent::paint (g);
  54161. const Rectangle r (button->getBounds());
  54162. g.setColour (Colours::white);
  54163. g.fillRect (r);
  54164. g.setColour (findColour (ComboBox::outlineColourId));
  54165. g.drawRect (r.getX(), r.getY(), r.getWidth(), r.getHeight());
  54166. }
  54167. void BooleanPropertyComponent::refresh()
  54168. {
  54169. button->setToggleState (getState(), false);
  54170. button->setButtonText (button->getToggleState() ? onText : offText);
  54171. }
  54172. void BooleanPropertyComponent::buttonClicked (Button*)
  54173. {
  54174. setState (! getState());
  54175. }
  54176. END_JUCE_NAMESPACE
  54177. /********* End of inlined file: juce_BooleanPropertyComponent.cpp *********/
  54178. /********* Start of inlined file: juce_ButtonPropertyComponent.cpp *********/
  54179. BEGIN_JUCE_NAMESPACE
  54180. ButtonPropertyComponent::ButtonPropertyComponent (const String& name,
  54181. const bool triggerOnMouseDown)
  54182. : PropertyComponent (name)
  54183. {
  54184. addAndMakeVisible (button = new TextButton (String::empty));
  54185. button->setTriggeredOnMouseDown (triggerOnMouseDown);
  54186. button->addButtonListener (this);
  54187. }
  54188. ButtonPropertyComponent::~ButtonPropertyComponent()
  54189. {
  54190. deleteAllChildren();
  54191. }
  54192. void ButtonPropertyComponent::refresh()
  54193. {
  54194. button->setButtonText (getButtonText());
  54195. }
  54196. void ButtonPropertyComponent::buttonClicked (Button*)
  54197. {
  54198. buttonClicked();
  54199. }
  54200. END_JUCE_NAMESPACE
  54201. /********* End of inlined file: juce_ButtonPropertyComponent.cpp *********/
  54202. /********* Start of inlined file: juce_ChoicePropertyComponent.cpp *********/
  54203. BEGIN_JUCE_NAMESPACE
  54204. ChoicePropertyComponent::ChoicePropertyComponent (const String& name)
  54205. : PropertyComponent (name),
  54206. comboBox (0)
  54207. {
  54208. }
  54209. ChoicePropertyComponent::~ChoicePropertyComponent()
  54210. {
  54211. deleteAllChildren();
  54212. }
  54213. const StringArray& ChoicePropertyComponent::getChoices() const throw()
  54214. {
  54215. return choices;
  54216. }
  54217. void ChoicePropertyComponent::refresh()
  54218. {
  54219. if (comboBox == 0)
  54220. {
  54221. addAndMakeVisible (comboBox = new ComboBox (String::empty));
  54222. for (int i = 0; i < choices.size(); ++i)
  54223. {
  54224. if (choices[i].isNotEmpty())
  54225. comboBox->addItem (choices[i], i + 1);
  54226. else
  54227. comboBox->addSeparator();
  54228. }
  54229. comboBox->setEditableText (false);
  54230. comboBox->addListener (this);
  54231. }
  54232. comboBox->setSelectedId (getIndex() + 1, true);
  54233. }
  54234. void ChoicePropertyComponent::comboBoxChanged (ComboBox*)
  54235. {
  54236. const int newIndex = comboBox->getSelectedId() - 1;
  54237. if (newIndex != getIndex())
  54238. setIndex (newIndex);
  54239. }
  54240. END_JUCE_NAMESPACE
  54241. /********* End of inlined file: juce_ChoicePropertyComponent.cpp *********/
  54242. /********* Start of inlined file: juce_PropertyComponent.cpp *********/
  54243. BEGIN_JUCE_NAMESPACE
  54244. PropertyComponent::PropertyComponent (const String& name,
  54245. const int preferredHeight_)
  54246. : Component (name),
  54247. preferredHeight (preferredHeight_)
  54248. {
  54249. jassert (name.isNotEmpty());
  54250. }
  54251. PropertyComponent::~PropertyComponent()
  54252. {
  54253. }
  54254. void PropertyComponent::paint (Graphics& g)
  54255. {
  54256. getLookAndFeel().drawPropertyComponentBackground (g, getWidth(), getHeight(), *this);
  54257. getLookAndFeel().drawPropertyComponentLabel (g, getWidth(), getHeight(), *this);
  54258. }
  54259. void PropertyComponent::resized()
  54260. {
  54261. if (getNumChildComponents() > 0)
  54262. getChildComponent (0)->setBounds (getLookAndFeel().getPropertyComponentContentPosition (*this));
  54263. }
  54264. void PropertyComponent::enablementChanged()
  54265. {
  54266. repaint();
  54267. }
  54268. END_JUCE_NAMESPACE
  54269. /********* End of inlined file: juce_PropertyComponent.cpp *********/
  54270. /********* Start of inlined file: juce_PropertyPanel.cpp *********/
  54271. BEGIN_JUCE_NAMESPACE
  54272. class PropertyHolderComponent : public Component
  54273. {
  54274. public:
  54275. PropertyHolderComponent()
  54276. {
  54277. }
  54278. ~PropertyHolderComponent()
  54279. {
  54280. deleteAllChildren();
  54281. }
  54282. void paint (Graphics&)
  54283. {
  54284. }
  54285. void updateLayout (const int width);
  54286. void refreshAll() const;
  54287. };
  54288. class PropertySectionComponent : public Component
  54289. {
  54290. public:
  54291. PropertySectionComponent (const String& sectionTitle,
  54292. const Array <PropertyComponent*>& newProperties,
  54293. const bool open)
  54294. : Component (sectionTitle),
  54295. titleHeight (sectionTitle.isNotEmpty() ? 22 : 0),
  54296. isOpen_ (open)
  54297. {
  54298. for (int i = newProperties.size(); --i >= 0;)
  54299. {
  54300. addAndMakeVisible (newProperties.getUnchecked(i));
  54301. newProperties.getUnchecked(i)->refresh();
  54302. }
  54303. }
  54304. ~PropertySectionComponent()
  54305. {
  54306. deleteAllChildren();
  54307. }
  54308. void paint (Graphics& g)
  54309. {
  54310. if (titleHeight > 0)
  54311. getLookAndFeel().drawPropertyPanelSectionHeader (g, getName(), isOpen(), getWidth(), titleHeight);
  54312. }
  54313. void resized()
  54314. {
  54315. int y = titleHeight;
  54316. for (int i = getNumChildComponents(); --i >= 0;)
  54317. {
  54318. PropertyComponent* const pec = dynamic_cast <PropertyComponent*> (getChildComponent (i));
  54319. if (pec != 0)
  54320. {
  54321. const int prefH = pec->getPreferredHeight();
  54322. pec->setBounds (1, y, getWidth() - 2, prefH);
  54323. y += prefH;
  54324. }
  54325. }
  54326. }
  54327. int getPreferredHeight() const
  54328. {
  54329. int y = titleHeight;
  54330. if (isOpen())
  54331. {
  54332. for (int i = 0; i < getNumChildComponents(); ++i)
  54333. {
  54334. PropertyComponent* pec = dynamic_cast <PropertyComponent*> (getChildComponent (i));
  54335. if (pec != 0)
  54336. y += pec->getPreferredHeight();
  54337. }
  54338. }
  54339. return y;
  54340. }
  54341. void setOpen (const bool open)
  54342. {
  54343. if (isOpen_ != open)
  54344. {
  54345. isOpen_ = open;
  54346. for (int i = 0; i < getNumChildComponents(); ++i)
  54347. {
  54348. PropertyComponent* pec = dynamic_cast <PropertyComponent*> (getChildComponent (i));
  54349. if (pec != 0)
  54350. pec->setVisible (open);
  54351. }
  54352. // (unable to use the syntax findParentComponentOfClass <DragAndDropContainer> () because of a VC6 compiler bug)
  54353. PropertyPanel* const pp = findParentComponentOfClass ((PropertyPanel*) 0);
  54354. if (pp != 0)
  54355. pp->resized();
  54356. }
  54357. }
  54358. bool isOpen() const throw()
  54359. {
  54360. return isOpen_;
  54361. }
  54362. void refreshAll() const
  54363. {
  54364. for (int i = 0; i < getNumChildComponents(); ++i)
  54365. {
  54366. PropertyComponent* pec = dynamic_cast <PropertyComponent*> (getChildComponent (i));
  54367. if (pec != 0)
  54368. pec->refresh();
  54369. }
  54370. }
  54371. void mouseDown (const MouseEvent&)
  54372. {
  54373. }
  54374. void mouseUp (const MouseEvent& e)
  54375. {
  54376. if (e.getMouseDownX() < titleHeight
  54377. && e.x < titleHeight
  54378. && e.y < titleHeight
  54379. && e.getNumberOfClicks() != 2)
  54380. {
  54381. setOpen (! isOpen());
  54382. }
  54383. }
  54384. void mouseDoubleClick (const MouseEvent& e)
  54385. {
  54386. if (e.y < titleHeight)
  54387. setOpen (! isOpen());
  54388. }
  54389. private:
  54390. int titleHeight;
  54391. bool isOpen_;
  54392. };
  54393. void PropertyHolderComponent::updateLayout (const int width)
  54394. {
  54395. int y = 0;
  54396. for (int i = getNumChildComponents(); --i >= 0;)
  54397. {
  54398. PropertySectionComponent* const section
  54399. = dynamic_cast <PropertySectionComponent*> (getChildComponent (i));
  54400. if (section != 0)
  54401. {
  54402. const int prefH = section->getPreferredHeight();
  54403. section->setBounds (0, y, width, prefH);
  54404. y += prefH;
  54405. }
  54406. }
  54407. setSize (width, y);
  54408. repaint();
  54409. }
  54410. void PropertyHolderComponent::refreshAll() const
  54411. {
  54412. for (int i = getNumChildComponents(); --i >= 0;)
  54413. {
  54414. PropertySectionComponent* const section
  54415. = dynamic_cast <PropertySectionComponent*> (getChildComponent (i));
  54416. if (section != 0)
  54417. section->refreshAll();
  54418. }
  54419. }
  54420. PropertyPanel::PropertyPanel()
  54421. {
  54422. messageWhenEmpty = TRANS("(nothing selected)");
  54423. addAndMakeVisible (viewport = new Viewport());
  54424. viewport->setViewedComponent (propertyHolderComponent = new PropertyHolderComponent());
  54425. viewport->setFocusContainer (true);
  54426. }
  54427. PropertyPanel::~PropertyPanel()
  54428. {
  54429. clear();
  54430. deleteAllChildren();
  54431. }
  54432. void PropertyPanel::paint (Graphics& g)
  54433. {
  54434. if (propertyHolderComponent->getNumChildComponents() == 0)
  54435. {
  54436. g.setColour (Colours::black.withAlpha (0.5f));
  54437. g.setFont (14.0f);
  54438. g.drawText (messageWhenEmpty, 0, 0, getWidth(), 30,
  54439. Justification::centred, true);
  54440. }
  54441. }
  54442. void PropertyPanel::resized()
  54443. {
  54444. viewport->setBounds (0, 0, getWidth(), getHeight());
  54445. updatePropHolderLayout();
  54446. }
  54447. void PropertyPanel::clear()
  54448. {
  54449. if (propertyHolderComponent->getNumChildComponents() > 0)
  54450. {
  54451. propertyHolderComponent->deleteAllChildren();
  54452. repaint();
  54453. }
  54454. }
  54455. void PropertyPanel::addProperties (const Array <PropertyComponent*>& newProperties)
  54456. {
  54457. if (propertyHolderComponent->getNumChildComponents() == 0)
  54458. repaint();
  54459. propertyHolderComponent->addAndMakeVisible (new PropertySectionComponent (String::empty,
  54460. newProperties,
  54461. true), 0);
  54462. updatePropHolderLayout();
  54463. }
  54464. void PropertyPanel::addSection (const String& sectionTitle,
  54465. const Array <PropertyComponent*>& newProperties,
  54466. const bool shouldBeOpen)
  54467. {
  54468. jassert (sectionTitle.isNotEmpty());
  54469. if (propertyHolderComponent->getNumChildComponents() == 0)
  54470. repaint();
  54471. propertyHolderComponent->addAndMakeVisible (new PropertySectionComponent (sectionTitle,
  54472. newProperties,
  54473. shouldBeOpen), 0);
  54474. updatePropHolderLayout();
  54475. }
  54476. void PropertyPanel::updatePropHolderLayout() const
  54477. {
  54478. const int maxWidth = viewport->getMaximumVisibleWidth();
  54479. ((PropertyHolderComponent*) propertyHolderComponent)->updateLayout (maxWidth);
  54480. const int newMaxWidth = viewport->getMaximumVisibleWidth();
  54481. if (maxWidth != newMaxWidth)
  54482. {
  54483. // need to do this twice because of scrollbars changing the size, etc.
  54484. ((PropertyHolderComponent*) propertyHolderComponent)->updateLayout (newMaxWidth);
  54485. }
  54486. }
  54487. void PropertyPanel::refreshAll() const
  54488. {
  54489. ((PropertyHolderComponent*) propertyHolderComponent)->refreshAll();
  54490. }
  54491. const StringArray PropertyPanel::getSectionNames() const
  54492. {
  54493. StringArray s;
  54494. for (int i = 0; i < propertyHolderComponent->getNumChildComponents(); ++i)
  54495. {
  54496. PropertySectionComponent* const section = dynamic_cast <PropertySectionComponent*> (propertyHolderComponent->getChildComponent (i));
  54497. if (section != 0 && section->getName().isNotEmpty())
  54498. s.add (section->getName());
  54499. }
  54500. return s;
  54501. }
  54502. bool PropertyPanel::isSectionOpen (const int sectionIndex) const
  54503. {
  54504. int index = 0;
  54505. for (int i = 0; i < propertyHolderComponent->getNumChildComponents(); ++i)
  54506. {
  54507. PropertySectionComponent* const section = dynamic_cast <PropertySectionComponent*> (propertyHolderComponent->getChildComponent (i));
  54508. if (section != 0 && section->getName().isNotEmpty())
  54509. {
  54510. if (index == sectionIndex)
  54511. return section->isOpen();
  54512. ++index;
  54513. }
  54514. }
  54515. return false;
  54516. }
  54517. void PropertyPanel::setSectionOpen (const int sectionIndex, const bool shouldBeOpen)
  54518. {
  54519. int index = 0;
  54520. for (int i = 0; i < propertyHolderComponent->getNumChildComponents(); ++i)
  54521. {
  54522. PropertySectionComponent* const section = dynamic_cast <PropertySectionComponent*> (propertyHolderComponent->getChildComponent (i));
  54523. if (section != 0 && section->getName().isNotEmpty())
  54524. {
  54525. if (index == sectionIndex)
  54526. {
  54527. section->setOpen (shouldBeOpen);
  54528. break;
  54529. }
  54530. ++index;
  54531. }
  54532. }
  54533. }
  54534. void PropertyPanel::setSectionEnabled (const int sectionIndex, const bool shouldBeEnabled)
  54535. {
  54536. int index = 0;
  54537. for (int i = 0; i < propertyHolderComponent->getNumChildComponents(); ++i)
  54538. {
  54539. PropertySectionComponent* const section = dynamic_cast <PropertySectionComponent*> (propertyHolderComponent->getChildComponent (i));
  54540. if (section != 0 && section->getName().isNotEmpty())
  54541. {
  54542. if (index == sectionIndex)
  54543. {
  54544. section->setEnabled (shouldBeEnabled);
  54545. break;
  54546. }
  54547. ++index;
  54548. }
  54549. }
  54550. }
  54551. XmlElement* PropertyPanel::getOpennessState() const
  54552. {
  54553. XmlElement* const xml = new XmlElement (T("PROPERTYPANELSTATE"));
  54554. const StringArray sections (getSectionNames());
  54555. for (int i = 0; i < sections.size(); ++i)
  54556. {
  54557. if (sections[i].isNotEmpty())
  54558. {
  54559. XmlElement* const e = new XmlElement (T("SECTION"));
  54560. e->setAttribute (T("name"), sections[i]);
  54561. e->setAttribute (T("open"), isSectionOpen (i) ? 1 : 0);
  54562. xml->addChildElement (e);
  54563. }
  54564. }
  54565. return xml;
  54566. }
  54567. void PropertyPanel::restoreOpennessState (const XmlElement& xml)
  54568. {
  54569. if (xml.hasTagName (T("PROPERTYPANELSTATE")))
  54570. {
  54571. const StringArray sections (getSectionNames());
  54572. forEachXmlChildElementWithTagName (xml, e, T("SECTION"))
  54573. {
  54574. setSectionOpen (sections.indexOf (e->getStringAttribute (T("name"))),
  54575. e->getBoolAttribute (T("open")));
  54576. }
  54577. }
  54578. }
  54579. void PropertyPanel::setMessageWhenEmpty (const String& newMessage)
  54580. {
  54581. if (messageWhenEmpty != newMessage)
  54582. {
  54583. messageWhenEmpty = newMessage;
  54584. repaint();
  54585. }
  54586. }
  54587. const String& PropertyPanel::getMessageWhenEmpty() const throw()
  54588. {
  54589. return messageWhenEmpty;
  54590. }
  54591. END_JUCE_NAMESPACE
  54592. /********* End of inlined file: juce_PropertyPanel.cpp *********/
  54593. /********* Start of inlined file: juce_SliderPropertyComponent.cpp *********/
  54594. BEGIN_JUCE_NAMESPACE
  54595. SliderPropertyComponent::SliderPropertyComponent (const String& name,
  54596. const double rangeMin,
  54597. const double rangeMax,
  54598. const double interval,
  54599. const double skewFactor)
  54600. : PropertyComponent (name)
  54601. {
  54602. addAndMakeVisible (slider = new Slider (name));
  54603. slider->setRange (rangeMin, rangeMax, interval);
  54604. slider->setSkewFactor (skewFactor);
  54605. slider->setSliderStyle (Slider::LinearBar);
  54606. slider->addListener (this);
  54607. }
  54608. SliderPropertyComponent::~SliderPropertyComponent()
  54609. {
  54610. deleteAllChildren();
  54611. }
  54612. void SliderPropertyComponent::refresh()
  54613. {
  54614. slider->setValue (getValue(), false);
  54615. }
  54616. void SliderPropertyComponent::sliderValueChanged (Slider*)
  54617. {
  54618. if (getValue() != slider->getValue())
  54619. setValue (slider->getValue());
  54620. }
  54621. END_JUCE_NAMESPACE
  54622. /********* End of inlined file: juce_SliderPropertyComponent.cpp *********/
  54623. /********* Start of inlined file: juce_TextPropertyComponent.cpp *********/
  54624. BEGIN_JUCE_NAMESPACE
  54625. class TextPropLabel : public Label
  54626. {
  54627. TextPropertyComponent& owner;
  54628. int maxChars;
  54629. bool isMultiline;
  54630. public:
  54631. TextPropLabel (TextPropertyComponent& owner_,
  54632. const int maxChars_, const bool isMultiline_)
  54633. : Label (String::empty, String::empty),
  54634. owner (owner_),
  54635. maxChars (maxChars_),
  54636. isMultiline (isMultiline_)
  54637. {
  54638. setEditable (true, true, false);
  54639. setColour (backgroundColourId, Colours::white);
  54640. setColour (outlineColourId, findColour (ComboBox::outlineColourId));
  54641. }
  54642. ~TextPropLabel()
  54643. {
  54644. }
  54645. TextEditor* createEditorComponent()
  54646. {
  54647. TextEditor* const textEditor = Label::createEditorComponent();
  54648. textEditor->setInputRestrictions (maxChars);
  54649. if (isMultiline)
  54650. {
  54651. textEditor->setMultiLine (true, true);
  54652. textEditor->setReturnKeyStartsNewLine (true);
  54653. }
  54654. return textEditor;
  54655. }
  54656. void textWasEdited()
  54657. {
  54658. owner.textWasEdited();
  54659. }
  54660. };
  54661. TextPropertyComponent::TextPropertyComponent (const String& name,
  54662. const int maxNumChars,
  54663. const bool isMultiLine)
  54664. : PropertyComponent (name)
  54665. {
  54666. addAndMakeVisible (textEditor = new TextPropLabel (*this, maxNumChars, isMultiLine));
  54667. if (isMultiLine)
  54668. {
  54669. textEditor->setJustificationType (Justification::topLeft);
  54670. preferredHeight = 120;
  54671. }
  54672. }
  54673. TextPropertyComponent::~TextPropertyComponent()
  54674. {
  54675. deleteAllChildren();
  54676. }
  54677. void TextPropertyComponent::refresh()
  54678. {
  54679. textEditor->setText (getText(), false);
  54680. }
  54681. void TextPropertyComponent::textWasEdited()
  54682. {
  54683. const String newText (textEditor->getText());
  54684. if (getText() != newText)
  54685. setText (newText);
  54686. }
  54687. END_JUCE_NAMESPACE
  54688. /********* End of inlined file: juce_TextPropertyComponent.cpp *********/
  54689. /********* Start of inlined file: juce_AudioDeviceSelectorComponent.cpp *********/
  54690. BEGIN_JUCE_NAMESPACE
  54691. class SimpleDeviceManagerInputLevelMeter : public Component,
  54692. public Timer
  54693. {
  54694. public:
  54695. SimpleDeviceManagerInputLevelMeter (AudioDeviceManager* const manager_)
  54696. : manager (manager_),
  54697. level (0)
  54698. {
  54699. startTimer (50);
  54700. manager->enableInputLevelMeasurement (true);
  54701. }
  54702. ~SimpleDeviceManagerInputLevelMeter()
  54703. {
  54704. manager->enableInputLevelMeasurement (false);
  54705. }
  54706. void timerCallback()
  54707. {
  54708. const float newLevel = (float) manager->getCurrentInputLevel();
  54709. if (fabsf (level - newLevel) > 0.005f)
  54710. {
  54711. level = newLevel;
  54712. repaint();
  54713. }
  54714. }
  54715. void paint (Graphics& g)
  54716. {
  54717. getLookAndFeel().drawLevelMeter (g, getWidth(), getHeight(),
  54718. (float) exp (log (level) / 3.0)); // (add a bit of a skew to make the level more obvious)
  54719. }
  54720. private:
  54721. AudioDeviceManager* const manager;
  54722. float level;
  54723. };
  54724. class MidiInputSelectorComponentListBox : public ListBox,
  54725. public ListBoxModel
  54726. {
  54727. public:
  54728. MidiInputSelectorComponentListBox (AudioDeviceManager& deviceManager_,
  54729. const String& noItemsMessage_,
  54730. const int minNumber_,
  54731. const int maxNumber_)
  54732. : ListBox (String::empty, 0),
  54733. deviceManager (deviceManager_),
  54734. noItemsMessage (noItemsMessage_),
  54735. minNumber (minNumber_),
  54736. maxNumber (maxNumber_)
  54737. {
  54738. items = MidiInput::getDevices();
  54739. setModel (this);
  54740. setOutlineThickness (1);
  54741. }
  54742. ~MidiInputSelectorComponentListBox()
  54743. {
  54744. }
  54745. int getNumRows()
  54746. {
  54747. return items.size();
  54748. }
  54749. void paintListBoxItem (int row,
  54750. Graphics& g,
  54751. int width, int height,
  54752. bool rowIsSelected)
  54753. {
  54754. if (((unsigned int) row) < (unsigned int) items.size())
  54755. {
  54756. if (rowIsSelected)
  54757. g.fillAll (findColour (TextEditor::highlightColourId)
  54758. .withMultipliedAlpha (0.3f));
  54759. const String item (items [row]);
  54760. bool enabled = deviceManager.isMidiInputEnabled (item);
  54761. const int x = getTickX();
  54762. const int tickW = height - height / 4;
  54763. getLookAndFeel().drawTickBox (g, *this, x - tickW, (height - tickW) / 2, tickW, tickW,
  54764. enabled, true, true, false);
  54765. g.setFont (height * 0.6f);
  54766. g.setColour (findColour (ListBox::textColourId, true).withMultipliedAlpha (enabled ? 1.0f : 0.6f));
  54767. g.drawText (item, x, 0, width - x - 2, height, Justification::centredLeft, true);
  54768. }
  54769. }
  54770. void listBoxItemClicked (int row, const MouseEvent& e)
  54771. {
  54772. selectRow (row);
  54773. if (e.x < getTickX())
  54774. flipEnablement (row);
  54775. }
  54776. void listBoxItemDoubleClicked (int row, const MouseEvent&)
  54777. {
  54778. flipEnablement (row);
  54779. }
  54780. void returnKeyPressed (int row)
  54781. {
  54782. flipEnablement (row);
  54783. }
  54784. void paint (Graphics& g)
  54785. {
  54786. ListBox::paint (g);
  54787. if (items.size() == 0)
  54788. {
  54789. g.setColour (Colours::grey);
  54790. g.setFont (13.0f);
  54791. g.drawText (noItemsMessage,
  54792. 0, 0, getWidth(), getHeight() / 2,
  54793. Justification::centred, true);
  54794. }
  54795. }
  54796. int getBestHeight (const int preferredHeight)
  54797. {
  54798. const int extra = getOutlineThickness() * 2;
  54799. return jmax (getRowHeight() * 2 + extra,
  54800. jmin (getRowHeight() * getNumRows() + extra,
  54801. preferredHeight));
  54802. }
  54803. juce_UseDebuggingNewOperator
  54804. private:
  54805. AudioDeviceManager& deviceManager;
  54806. const String noItemsMessage;
  54807. StringArray items;
  54808. int minNumber, maxNumber;
  54809. void flipEnablement (const int row)
  54810. {
  54811. if (((unsigned int) row) < (unsigned int) items.size())
  54812. {
  54813. const String item (items [row]);
  54814. deviceManager.setMidiInputEnabled (item, ! deviceManager.isMidiInputEnabled (item));
  54815. }
  54816. }
  54817. int getTickX() const throw()
  54818. {
  54819. return getRowHeight() + 5;
  54820. }
  54821. MidiInputSelectorComponentListBox (const MidiInputSelectorComponentListBox&);
  54822. const MidiInputSelectorComponentListBox& operator= (const MidiInputSelectorComponentListBox&);
  54823. };
  54824. class AudioDeviceSettingsPanel : public Component,
  54825. public ComboBoxListener,
  54826. public ChangeListener,
  54827. public ButtonListener
  54828. {
  54829. public:
  54830. AudioDeviceSettingsPanel (AudioIODeviceType* type_,
  54831. AudioIODeviceType::DeviceSetupDetails& setup_,
  54832. const bool hideAdvancedOptionsWithButton)
  54833. : type (type_),
  54834. setup (setup_)
  54835. {
  54836. sampleRateDropDown = 0;
  54837. sampleRateLabel = 0;
  54838. bufferSizeDropDown = 0;
  54839. bufferSizeLabel = 0;
  54840. outputDeviceDropDown = 0;
  54841. outputDeviceLabel = 0;
  54842. inputDeviceDropDown = 0;
  54843. inputDeviceLabel = 0;
  54844. testButton = 0;
  54845. inputLevelMeter = 0;
  54846. showUIButton = 0;
  54847. inputChanList = 0;
  54848. outputChanList = 0;
  54849. inputChanLabel = 0;
  54850. outputChanLabel = 0;
  54851. showAdvancedSettingsButton = 0;
  54852. if (hideAdvancedOptionsWithButton)
  54853. {
  54854. addAndMakeVisible (showAdvancedSettingsButton = new TextButton (TRANS("Show advanced settings...")));
  54855. showAdvancedSettingsButton->addButtonListener (this);
  54856. }
  54857. type->scanForDevices();
  54858. setup.manager->addChangeListener (this);
  54859. changeListenerCallback (0);
  54860. }
  54861. ~AudioDeviceSettingsPanel()
  54862. {
  54863. setup.manager->removeChangeListener (this);
  54864. deleteAndZero (outputDeviceLabel);
  54865. deleteAndZero (inputDeviceLabel);
  54866. deleteAndZero (sampleRateLabel);
  54867. deleteAndZero (bufferSizeLabel);
  54868. deleteAndZero (showUIButton);
  54869. deleteAndZero (inputChanLabel);
  54870. deleteAndZero (outputChanLabel);
  54871. deleteAndZero (showAdvancedSettingsButton);
  54872. deleteAllChildren();
  54873. }
  54874. void resized()
  54875. {
  54876. const int lx = proportionOfWidth (0.35f);
  54877. const int w = proportionOfWidth (0.4f);
  54878. const int h = 24;
  54879. const int space = 6;
  54880. const int dh = h + space;
  54881. int y = 0;
  54882. if (outputDeviceDropDown != 0)
  54883. {
  54884. outputDeviceDropDown->setBounds (lx, y, w, h);
  54885. if (testButton != 0)
  54886. testButton->setBounds (proportionOfWidth (0.77f),
  54887. outputDeviceDropDown->getY(),
  54888. proportionOfWidth (0.18f),
  54889. h);
  54890. y += dh;
  54891. }
  54892. if (inputDeviceDropDown != 0)
  54893. {
  54894. inputDeviceDropDown->setBounds (lx, y, w, h);
  54895. inputLevelMeter->setBounds (proportionOfWidth (0.77f),
  54896. inputDeviceDropDown->getY(),
  54897. proportionOfWidth (0.18f),
  54898. h);
  54899. y += dh;
  54900. }
  54901. const int maxBoxHeight = 100;//(getHeight() - y - dh * 2) / numBoxes;
  54902. if (outputChanList != 0)
  54903. {
  54904. const int bh = outputChanList->getBestHeight (maxBoxHeight);
  54905. outputChanList->setBounds (lx, y, proportionOfWidth (0.55f), bh);
  54906. y += bh + space;
  54907. }
  54908. if (inputChanList != 0)
  54909. {
  54910. const int bh = inputChanList->getBestHeight (maxBoxHeight);
  54911. inputChanList->setBounds (lx, y, proportionOfWidth (0.55f), bh);
  54912. y += bh + space;
  54913. }
  54914. y += space * 2;
  54915. if (showAdvancedSettingsButton != 0)
  54916. {
  54917. showAdvancedSettingsButton->changeWidthToFitText (h);
  54918. showAdvancedSettingsButton->setTopLeftPosition (lx, y);
  54919. }
  54920. if (sampleRateDropDown != 0)
  54921. {
  54922. sampleRateDropDown->setVisible (showAdvancedSettingsButton == 0
  54923. || ! showAdvancedSettingsButton->isVisible());
  54924. sampleRateDropDown->setBounds (lx, y, w, h);
  54925. y += dh;
  54926. }
  54927. if (bufferSizeDropDown != 0)
  54928. {
  54929. bufferSizeDropDown->setVisible (showAdvancedSettingsButton == 0
  54930. || ! showAdvancedSettingsButton->isVisible());
  54931. bufferSizeDropDown->setBounds (lx, y, w, h);
  54932. y += dh;
  54933. }
  54934. if (showUIButton != 0)
  54935. {
  54936. showUIButton->setVisible (showAdvancedSettingsButton == 0
  54937. || ! showAdvancedSettingsButton->isVisible());
  54938. showUIButton->changeWidthToFitText (h);
  54939. showUIButton->setTopLeftPosition (lx, y);
  54940. }
  54941. }
  54942. void comboBoxChanged (ComboBox* comboBoxThatHasChanged)
  54943. {
  54944. if (comboBoxThatHasChanged == 0)
  54945. return;
  54946. AudioDeviceManager::AudioDeviceSetup config;
  54947. setup.manager->getAudioDeviceSetup (config);
  54948. String error;
  54949. if (comboBoxThatHasChanged == outputDeviceDropDown
  54950. || comboBoxThatHasChanged == inputDeviceDropDown)
  54951. {
  54952. if (outputDeviceDropDown != 0)
  54953. config.outputDeviceName = outputDeviceDropDown->getSelectedId() < 0 ? String::empty
  54954. : outputDeviceDropDown->getText();
  54955. if (inputDeviceDropDown != 0)
  54956. config.inputDeviceName = inputDeviceDropDown->getSelectedId() < 0 ? String::empty
  54957. : inputDeviceDropDown->getText();
  54958. if (! type->hasSeparateInputsAndOutputs())
  54959. config.inputDeviceName = config.outputDeviceName;
  54960. if (comboBoxThatHasChanged == inputDeviceDropDown)
  54961. config.useDefaultInputChannels = true;
  54962. else
  54963. config.useDefaultOutputChannels = true;
  54964. error = setup.manager->setAudioDeviceSetup (config, true);
  54965. showCorrectDeviceName (inputDeviceDropDown, true);
  54966. showCorrectDeviceName (outputDeviceDropDown, false);
  54967. updateControlPanelButton();
  54968. resized();
  54969. }
  54970. else if (comboBoxThatHasChanged == sampleRateDropDown)
  54971. {
  54972. if (sampleRateDropDown->getSelectedId() > 0)
  54973. {
  54974. config.sampleRate = sampleRateDropDown->getSelectedId();
  54975. error = setup.manager->setAudioDeviceSetup (config, true);
  54976. }
  54977. }
  54978. else if (comboBoxThatHasChanged == bufferSizeDropDown)
  54979. {
  54980. if (bufferSizeDropDown->getSelectedId() > 0)
  54981. {
  54982. config.bufferSize = bufferSizeDropDown->getSelectedId();
  54983. error = setup.manager->setAudioDeviceSetup (config, true);
  54984. }
  54985. }
  54986. if (error.isNotEmpty())
  54987. {
  54988. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  54989. T("Error when trying to open audio device!"),
  54990. error);
  54991. }
  54992. }
  54993. void buttonClicked (Button* button)
  54994. {
  54995. if (button == showAdvancedSettingsButton)
  54996. {
  54997. showAdvancedSettingsButton->setVisible (false);
  54998. resized();
  54999. }
  55000. else if (button == showUIButton)
  55001. {
  55002. AudioIODevice* const device = setup.manager->getCurrentAudioDevice();
  55003. if (device != 0 && device->showControlPanel())
  55004. {
  55005. setup.manager->closeAudioDevice();
  55006. setup.manager->restartLastAudioDevice();
  55007. getTopLevelComponent()->toFront (true);
  55008. }
  55009. }
  55010. else if (button == testButton && testButton != 0)
  55011. {
  55012. setup.manager->playTestSound();
  55013. }
  55014. }
  55015. void updateControlPanelButton()
  55016. {
  55017. AudioIODevice* const currentDevice = setup.manager->getCurrentAudioDevice();
  55018. deleteAndZero (showUIButton);
  55019. if (currentDevice != 0 && currentDevice->hasControlPanel())
  55020. {
  55021. addAndMakeVisible (showUIButton = new TextButton (TRANS ("show this device's control panel"),
  55022. TRANS ("opens the device's own control panel")));
  55023. showUIButton->addButtonListener (this);
  55024. }
  55025. resized();
  55026. }
  55027. void changeListenerCallback (void*)
  55028. {
  55029. AudioIODevice* const currentDevice = setup.manager->getCurrentAudioDevice();
  55030. if (setup.maxNumOutputChannels > 0 || ! type->hasSeparateInputsAndOutputs())
  55031. {
  55032. if (outputDeviceDropDown == 0)
  55033. {
  55034. outputDeviceDropDown = new ComboBox (String::empty);
  55035. outputDeviceDropDown->addListener (this);
  55036. addAndMakeVisible (outputDeviceDropDown);
  55037. outputDeviceLabel = new Label (String::empty,
  55038. type->hasSeparateInputsAndOutputs() ? TRANS ("output:")
  55039. : TRANS ("device:"));
  55040. outputDeviceLabel->attachToComponent (outputDeviceDropDown, true);
  55041. if (setup.maxNumOutputChannels > 0)
  55042. {
  55043. addAndMakeVisible (testButton = new TextButton (TRANS ("Test")));
  55044. testButton->addButtonListener (this);
  55045. }
  55046. }
  55047. addNamesToDeviceBox (*outputDeviceDropDown, false);
  55048. }
  55049. if (setup.maxNumInputChannels > 0 && type->hasSeparateInputsAndOutputs())
  55050. {
  55051. if (inputDeviceDropDown == 0)
  55052. {
  55053. inputDeviceDropDown = new ComboBox (String::empty);
  55054. inputDeviceDropDown->addListener (this);
  55055. addAndMakeVisible (inputDeviceDropDown);
  55056. inputDeviceLabel = new Label (String::empty, TRANS ("input:"));
  55057. inputDeviceLabel->attachToComponent (inputDeviceDropDown, true);
  55058. addAndMakeVisible (inputLevelMeter
  55059. = new SimpleDeviceManagerInputLevelMeter (setup.manager));
  55060. }
  55061. addNamesToDeviceBox (*inputDeviceDropDown, true);
  55062. }
  55063. updateControlPanelButton();
  55064. showCorrectDeviceName (inputDeviceDropDown, true);
  55065. showCorrectDeviceName (outputDeviceDropDown, false);
  55066. if (currentDevice != 0)
  55067. {
  55068. if (setup.maxNumOutputChannels > 0
  55069. && setup.minNumOutputChannels < setup.manager->getCurrentAudioDevice()->getOutputChannelNames().size())
  55070. {
  55071. if (outputChanList == 0)
  55072. {
  55073. addAndMakeVisible (outputChanList
  55074. = new ChannelSelectorListBox (setup, ChannelSelectorListBox::audioOutputType,
  55075. TRANS ("(no audio output channels found)")));
  55076. outputChanLabel = new Label (String::empty, TRANS ("active output channels:"));
  55077. outputChanLabel->attachToComponent (outputChanList, true);
  55078. }
  55079. outputChanList->refresh();
  55080. }
  55081. else
  55082. {
  55083. deleteAndZero (outputChanLabel);
  55084. deleteAndZero (outputChanList);
  55085. }
  55086. if (setup.maxNumInputChannels > 0
  55087. && setup.minNumInputChannels < setup.manager->getCurrentAudioDevice()->getInputChannelNames().size())
  55088. {
  55089. if (inputChanList == 0)
  55090. {
  55091. addAndMakeVisible (inputChanList
  55092. = new ChannelSelectorListBox (setup, ChannelSelectorListBox::audioInputType,
  55093. TRANS ("(no audio input channels found)")));
  55094. inputChanLabel = new Label (String::empty, TRANS ("active input channels:"));
  55095. inputChanLabel->attachToComponent (inputChanList, true);
  55096. }
  55097. inputChanList->refresh();
  55098. }
  55099. else
  55100. {
  55101. deleteAndZero (inputChanLabel);
  55102. deleteAndZero (inputChanList);
  55103. }
  55104. // sample rate..
  55105. {
  55106. if (sampleRateDropDown == 0)
  55107. {
  55108. addAndMakeVisible (sampleRateDropDown = new ComboBox (String::empty));
  55109. sampleRateDropDown->addListener (this);
  55110. delete sampleRateLabel;
  55111. sampleRateLabel = new Label (String::empty, TRANS ("sample rate:"));
  55112. sampleRateLabel->attachToComponent (sampleRateDropDown, true);
  55113. }
  55114. else
  55115. {
  55116. sampleRateDropDown->clear();
  55117. sampleRateDropDown->removeListener (this);
  55118. }
  55119. const int numRates = currentDevice->getNumSampleRates();
  55120. for (int i = 0; i < numRates; ++i)
  55121. {
  55122. const int rate = roundDoubleToInt (currentDevice->getSampleRate (i));
  55123. sampleRateDropDown->addItem (String (rate) + T(" Hz"), rate);
  55124. }
  55125. sampleRateDropDown->setSelectedId (roundDoubleToInt (currentDevice->getCurrentSampleRate()), true);
  55126. sampleRateDropDown->addListener (this);
  55127. }
  55128. // buffer size
  55129. {
  55130. if (bufferSizeDropDown == 0)
  55131. {
  55132. addAndMakeVisible (bufferSizeDropDown = new ComboBox (String::empty));
  55133. bufferSizeDropDown->addListener (this);
  55134. delete bufferSizeLabel;
  55135. bufferSizeLabel = new Label (String::empty, TRANS ("audio buffer size:"));
  55136. bufferSizeLabel->attachToComponent (bufferSizeDropDown, true);
  55137. }
  55138. else
  55139. {
  55140. bufferSizeDropDown->clear();
  55141. }
  55142. const int numBufferSizes = currentDevice->getNumBufferSizesAvailable();
  55143. double currentRate = currentDevice->getCurrentSampleRate();
  55144. if (currentRate == 0)
  55145. currentRate = 48000.0;
  55146. for (int i = 0; i < numBufferSizes; ++i)
  55147. {
  55148. const int bs = currentDevice->getBufferSizeSamples (i);
  55149. bufferSizeDropDown->addItem (String (bs)
  55150. + T(" samples (")
  55151. + String (bs * 1000.0 / currentRate, 1)
  55152. + T(" ms)"),
  55153. bs);
  55154. }
  55155. bufferSizeDropDown->setSelectedId (currentDevice->getCurrentBufferSizeSamples(), true);
  55156. }
  55157. }
  55158. else
  55159. {
  55160. jassert (setup.manager->getCurrentAudioDevice() == 0); // not the correct device type!
  55161. deleteAndZero (sampleRateLabel);
  55162. deleteAndZero (bufferSizeLabel);
  55163. deleteAndZero (sampleRateDropDown);
  55164. deleteAndZero (bufferSizeDropDown);
  55165. if (outputDeviceDropDown != 0)
  55166. outputDeviceDropDown->setSelectedId (-1, true);
  55167. if (inputDeviceDropDown != 0)
  55168. inputDeviceDropDown->setSelectedId (-1, true);
  55169. }
  55170. resized();
  55171. setSize (getWidth(), getLowestY() + 4);
  55172. }
  55173. private:
  55174. AudioIODeviceType* const type;
  55175. const AudioIODeviceType::DeviceSetupDetails setup;
  55176. ComboBox* outputDeviceDropDown;
  55177. ComboBox* inputDeviceDropDown;
  55178. ComboBox* sampleRateDropDown;
  55179. ComboBox* bufferSizeDropDown;
  55180. Label* outputDeviceLabel;
  55181. Label* inputDeviceLabel;
  55182. Label* sampleRateLabel;
  55183. Label* bufferSizeLabel;
  55184. Label* inputChanLabel;
  55185. Label* outputChanLabel;
  55186. TextButton* testButton;
  55187. Component* inputLevelMeter;
  55188. TextButton* showUIButton;
  55189. TextButton* showAdvancedSettingsButton;
  55190. void showCorrectDeviceName (ComboBox* const box, const bool isInput)
  55191. {
  55192. if (box != 0)
  55193. {
  55194. AudioIODevice* const currentDevice = dynamic_cast <AudioIODevice*> (setup.manager->getCurrentAudioDevice());
  55195. const int index = type->getIndexOfDevice (currentDevice, isInput);
  55196. box->setSelectedId (index + 1, true);
  55197. if (testButton != 0 && ! isInput)
  55198. testButton->setEnabled (index >= 0);
  55199. }
  55200. }
  55201. void addNamesToDeviceBox (ComboBox& combo, bool isInputs)
  55202. {
  55203. const StringArray devs (type->getDeviceNames (isInputs));
  55204. combo.clear (true);
  55205. for (int i = 0; i < devs.size(); ++i)
  55206. combo.addItem (devs[i], i + 1);
  55207. combo.addItem (TRANS("<< none >>"), -1);
  55208. combo.setSelectedId (-1, true);
  55209. }
  55210. int getLowestY() const
  55211. {
  55212. int y = 0;
  55213. for (int i = getNumChildComponents(); --i >= 0;)
  55214. y = jmax (y, getChildComponent (i)->getBottom());
  55215. return y;
  55216. }
  55217. class ChannelSelectorListBox : public ListBox,
  55218. public ListBoxModel
  55219. {
  55220. public:
  55221. enum BoxType
  55222. {
  55223. audioInputType,
  55224. audioOutputType
  55225. };
  55226. ChannelSelectorListBox (const AudioIODeviceType::DeviceSetupDetails& setup_,
  55227. const BoxType type_,
  55228. const String& noItemsMessage_)
  55229. : ListBox (String::empty, 0),
  55230. setup (setup_),
  55231. type (type_),
  55232. noItemsMessage (noItemsMessage_)
  55233. {
  55234. refresh();
  55235. setModel (this);
  55236. setOutlineThickness (1);
  55237. }
  55238. ~ChannelSelectorListBox()
  55239. {
  55240. }
  55241. void refresh()
  55242. {
  55243. items.clear();
  55244. AudioIODevice* const currentDevice = setup.manager->getCurrentAudioDevice();
  55245. if (currentDevice != 0)
  55246. {
  55247. if (type == audioInputType)
  55248. items = currentDevice->getInputChannelNames();
  55249. else if (type == audioOutputType)
  55250. items = currentDevice->getOutputChannelNames();
  55251. if (setup.useStereoPairs)
  55252. {
  55253. StringArray pairs;
  55254. for (int i = 0; i < items.size(); i += 2)
  55255. {
  55256. String name (items[i]);
  55257. String name2 (items[i + 1]);
  55258. String commonBit;
  55259. for (int j = 0; j < name.length(); ++j)
  55260. if (name.substring (0, j).equalsIgnoreCase (name2.substring (0, j)))
  55261. commonBit = name.substring (0, j);
  55262. pairs.add (name.trim()
  55263. + " + "
  55264. + name2.substring (commonBit.length()).trim());
  55265. }
  55266. items = pairs;
  55267. }
  55268. }
  55269. updateContent();
  55270. repaint();
  55271. }
  55272. int getNumRows()
  55273. {
  55274. return items.size();
  55275. }
  55276. void paintListBoxItem (int row,
  55277. Graphics& g,
  55278. int width, int height,
  55279. bool rowIsSelected)
  55280. {
  55281. if (((unsigned int) row) < (unsigned int) items.size())
  55282. {
  55283. if (rowIsSelected)
  55284. g.fillAll (findColour (TextEditor::highlightColourId)
  55285. .withMultipliedAlpha (0.3f));
  55286. const String item (items [row]);
  55287. bool enabled = false;
  55288. AudioDeviceManager::AudioDeviceSetup config;
  55289. setup.manager->getAudioDeviceSetup (config);
  55290. if (setup.useStereoPairs)
  55291. {
  55292. if (type == audioInputType)
  55293. enabled = config.inputChannels [row * 2] || config.inputChannels [row * 2 + 1];
  55294. else if (type == audioOutputType)
  55295. enabled = config.outputChannels [row * 2] || config.outputChannels [row * 2 + 1];
  55296. }
  55297. else
  55298. {
  55299. if (type == audioInputType)
  55300. enabled = config.inputChannels [row];
  55301. else if (type == audioOutputType)
  55302. enabled = config.outputChannels [row];
  55303. }
  55304. const int x = getTickX();
  55305. const int tickW = height - height / 4;
  55306. getLookAndFeel().drawTickBox (g, *this, x - tickW, (height - tickW) / 2, tickW, tickW,
  55307. enabled, true, true, false);
  55308. g.setFont (height * 0.6f);
  55309. g.setColour (findColour (ListBox::textColourId, true).withMultipliedAlpha (enabled ? 1.0f : 0.6f));
  55310. g.drawText (item, x, 0, width - x - 2, height, Justification::centredLeft, true);
  55311. }
  55312. }
  55313. void listBoxItemClicked (int row, const MouseEvent& e)
  55314. {
  55315. selectRow (row);
  55316. if (e.x < getTickX())
  55317. flipEnablement (row);
  55318. }
  55319. void listBoxItemDoubleClicked (int row, const MouseEvent&)
  55320. {
  55321. flipEnablement (row);
  55322. }
  55323. void returnKeyPressed (int row)
  55324. {
  55325. flipEnablement (row);
  55326. }
  55327. void paint (Graphics& g)
  55328. {
  55329. ListBox::paint (g);
  55330. if (items.size() == 0)
  55331. {
  55332. g.setColour (Colours::grey);
  55333. g.setFont (13.0f);
  55334. g.drawText (noItemsMessage,
  55335. 0, 0, getWidth(), getHeight() / 2,
  55336. Justification::centred, true);
  55337. }
  55338. }
  55339. int getBestHeight (int maxHeight)
  55340. {
  55341. return getRowHeight() * jlimit (2, jmax (2, maxHeight / getRowHeight()),
  55342. getNumRows())
  55343. + getOutlineThickness() * 2;
  55344. }
  55345. juce_UseDebuggingNewOperator
  55346. private:
  55347. const AudioIODeviceType::DeviceSetupDetails setup;
  55348. const BoxType type;
  55349. const String noItemsMessage;
  55350. StringArray items;
  55351. void flipEnablement (const int row)
  55352. {
  55353. jassert (type == audioInputType || type == audioOutputType);
  55354. if (((unsigned int) row) < (unsigned int) items.size())
  55355. {
  55356. AudioDeviceManager::AudioDeviceSetup config;
  55357. setup.manager->getAudioDeviceSetup (config);
  55358. if (setup.useStereoPairs)
  55359. {
  55360. BitArray bits;
  55361. BitArray& original = (type == audioInputType ? config.inputChannels
  55362. : config.outputChannels);
  55363. int i;
  55364. for (i = 0; i < 256; i += 2)
  55365. bits.setBit (i / 2, original [i] || original [i + 1]);
  55366. if (type == audioInputType)
  55367. {
  55368. config.useDefaultInputChannels = false;
  55369. flipBit (bits, row, setup.minNumInputChannels / 2, setup.maxNumInputChannels / 2);
  55370. }
  55371. else
  55372. {
  55373. config.useDefaultOutputChannels = false;
  55374. flipBit (bits, row, setup.minNumOutputChannels / 2, setup.maxNumOutputChannels / 2);
  55375. }
  55376. for (i = 0; i < 256; ++i)
  55377. original.setBit (i, bits [i / 2]);
  55378. }
  55379. else
  55380. {
  55381. if (type == audioInputType)
  55382. {
  55383. config.useDefaultInputChannels = false;
  55384. flipBit (config.inputChannels, row, setup.minNumInputChannels, setup.maxNumInputChannels);
  55385. }
  55386. else
  55387. {
  55388. config.useDefaultOutputChannels = false;
  55389. flipBit (config.outputChannels, row, setup.minNumOutputChannels, setup.maxNumOutputChannels);
  55390. }
  55391. }
  55392. String error (setup.manager->setAudioDeviceSetup (config, true));
  55393. if (! error.isEmpty())
  55394. {
  55395. //xxx
  55396. }
  55397. }
  55398. }
  55399. static void flipBit (BitArray& chans, int index, int minNumber, int maxNumber)
  55400. {
  55401. const int numActive = chans.countNumberOfSetBits();
  55402. if (chans [index])
  55403. {
  55404. if (numActive > minNumber)
  55405. chans.setBit (index, false);
  55406. }
  55407. else
  55408. {
  55409. if (numActive >= maxNumber)
  55410. {
  55411. const int firstActiveChan = chans.findNextSetBit();
  55412. chans.setBit (index > firstActiveChan
  55413. ? firstActiveChan : chans.getHighestBit(),
  55414. false);
  55415. }
  55416. chans.setBit (index, true);
  55417. }
  55418. }
  55419. int getTickX() const throw()
  55420. {
  55421. return getRowHeight() + 5;
  55422. }
  55423. ChannelSelectorListBox (const ChannelSelectorListBox&);
  55424. const ChannelSelectorListBox& operator= (const ChannelSelectorListBox&);
  55425. };
  55426. ChannelSelectorListBox* inputChanList;
  55427. ChannelSelectorListBox* outputChanList;
  55428. AudioDeviceSettingsPanel (const AudioDeviceSettingsPanel&);
  55429. const AudioDeviceSettingsPanel& operator= (const AudioDeviceSettingsPanel&);
  55430. };
  55431. AudioDeviceSelectorComponent::AudioDeviceSelectorComponent (AudioDeviceManager& deviceManager_,
  55432. const int minInputChannels_,
  55433. const int maxInputChannels_,
  55434. const int minOutputChannels_,
  55435. const int maxOutputChannels_,
  55436. const bool showMidiInputOptions,
  55437. const bool showMidiOutputSelector,
  55438. const bool showChannelsAsStereoPairs_,
  55439. const bool hideAdvancedOptionsWithButton_)
  55440. : deviceManager (deviceManager_),
  55441. deviceTypeDropDown (0),
  55442. deviceTypeDropDownLabel (0),
  55443. audioDeviceSettingsComp (0),
  55444. minOutputChannels (minOutputChannels_),
  55445. maxOutputChannels (maxOutputChannels_),
  55446. minInputChannels (minInputChannels_),
  55447. maxInputChannels (maxInputChannels_),
  55448. showChannelsAsStereoPairs (showChannelsAsStereoPairs_),
  55449. hideAdvancedOptionsWithButton (hideAdvancedOptionsWithButton_)
  55450. {
  55451. jassert (minOutputChannels >= 0 && minOutputChannels <= maxOutputChannels);
  55452. jassert (minInputChannels >= 0 && minInputChannels <= maxInputChannels);
  55453. if (deviceManager_.getAvailableDeviceTypes().size() > 1)
  55454. {
  55455. deviceTypeDropDown = new ComboBox (String::empty);
  55456. for (int i = 0; i < deviceManager_.getAvailableDeviceTypes().size(); ++i)
  55457. {
  55458. deviceTypeDropDown
  55459. ->addItem (deviceManager_.getAvailableDeviceTypes().getUnchecked(i)->getTypeName(),
  55460. i + 1);
  55461. }
  55462. addAndMakeVisible (deviceTypeDropDown);
  55463. deviceTypeDropDown->addListener (this);
  55464. deviceTypeDropDownLabel = new Label (String::empty, TRANS ("audio device type:"));
  55465. deviceTypeDropDownLabel->setJustificationType (Justification::centredRight);
  55466. deviceTypeDropDownLabel->attachToComponent (deviceTypeDropDown, true);
  55467. }
  55468. if (showMidiInputOptions)
  55469. {
  55470. addAndMakeVisible (midiInputsList
  55471. = new MidiInputSelectorComponentListBox (deviceManager,
  55472. TRANS("(no midi inputs available)"),
  55473. 0, 0));
  55474. midiInputsLabel = new Label (String::empty, TRANS ("active midi inputs:"));
  55475. midiInputsLabel->setJustificationType (Justification::topRight);
  55476. midiInputsLabel->attachToComponent (midiInputsList, true);
  55477. }
  55478. else
  55479. {
  55480. midiInputsList = 0;
  55481. midiInputsLabel = 0;
  55482. }
  55483. if (showMidiOutputSelector)
  55484. {
  55485. addAndMakeVisible (midiOutputSelector = new ComboBox (String::empty));
  55486. midiOutputSelector->addListener (this);
  55487. midiOutputLabel = new Label ("lm", TRANS("Midi Output:"));
  55488. midiOutputLabel->attachToComponent (midiOutputSelector, true);
  55489. }
  55490. else
  55491. {
  55492. midiOutputSelector = 0;
  55493. midiOutputLabel = 0;
  55494. }
  55495. deviceManager_.addChangeListener (this);
  55496. changeListenerCallback (0);
  55497. }
  55498. AudioDeviceSelectorComponent::~AudioDeviceSelectorComponent()
  55499. {
  55500. deviceManager.removeChangeListener (this);
  55501. deleteAllChildren();
  55502. }
  55503. void AudioDeviceSelectorComponent::resized()
  55504. {
  55505. const int lx = proportionOfWidth (0.35f);
  55506. const int w = proportionOfWidth (0.4f);
  55507. const int h = 24;
  55508. const int space = 6;
  55509. const int dh = h + space;
  55510. int y = 15;
  55511. if (deviceTypeDropDown != 0)
  55512. {
  55513. deviceTypeDropDown->setBounds (lx, y, proportionOfWidth (0.3f), h);
  55514. y += dh + space * 2;
  55515. }
  55516. if (audioDeviceSettingsComp != 0)
  55517. {
  55518. audioDeviceSettingsComp->setBounds (0, y, getWidth(), audioDeviceSettingsComp->getHeight());
  55519. y += audioDeviceSettingsComp->getHeight() + space;
  55520. }
  55521. if (midiInputsList != 0)
  55522. {
  55523. const int bh = midiInputsList->getBestHeight (jmin (h * 8, getHeight() - y - space - h));
  55524. midiInputsList->setBounds (lx, y, w, bh);
  55525. y += bh + space;
  55526. }
  55527. if (midiOutputSelector != 0)
  55528. midiOutputSelector->setBounds (lx, y, w, h);
  55529. }
  55530. void AudioDeviceSelectorComponent::childBoundsChanged (Component* child)
  55531. {
  55532. if (child == audioDeviceSettingsComp)
  55533. resized();
  55534. }
  55535. void AudioDeviceSelectorComponent::buttonClicked (Button*)
  55536. {
  55537. AudioIODevice* const device = deviceManager.getCurrentAudioDevice();
  55538. if (device != 0 && device->hasControlPanel())
  55539. {
  55540. if (device->showControlPanel())
  55541. deviceManager.restartLastAudioDevice();
  55542. getTopLevelComponent()->toFront (true);
  55543. }
  55544. }
  55545. void AudioDeviceSelectorComponent::comboBoxChanged (ComboBox* comboBoxThatHasChanged)
  55546. {
  55547. if (comboBoxThatHasChanged == deviceTypeDropDown)
  55548. {
  55549. AudioIODeviceType* const type = deviceManager.getAvailableDeviceTypes() [deviceTypeDropDown->getSelectedId() - 1];
  55550. if (type != 0)
  55551. {
  55552. deleteAndZero (audioDeviceSettingsComp);
  55553. deviceManager.setCurrentAudioDeviceType (type->getTypeName(), true);
  55554. changeListenerCallback (0); // needed in case the type hasn't actally changed
  55555. }
  55556. }
  55557. else if (comboBoxThatHasChanged == midiOutputSelector)
  55558. {
  55559. deviceManager.setDefaultMidiOutput (midiOutputSelector->getText());
  55560. }
  55561. }
  55562. void AudioDeviceSelectorComponent::changeListenerCallback (void*)
  55563. {
  55564. if (deviceTypeDropDown != 0)
  55565. {
  55566. deviceTypeDropDown->setText (deviceManager.getCurrentAudioDeviceType(), false);
  55567. }
  55568. if (audioDeviceSettingsComp == 0
  55569. || audioDeviceSettingsCompType != deviceManager.getCurrentAudioDeviceType())
  55570. {
  55571. audioDeviceSettingsCompType = deviceManager.getCurrentAudioDeviceType();
  55572. deleteAndZero (audioDeviceSettingsComp);
  55573. AudioIODeviceType* const type
  55574. = deviceManager.getAvailableDeviceTypes() [deviceTypeDropDown == 0
  55575. ? 0 : deviceTypeDropDown->getSelectedId() - 1];
  55576. if (type != 0)
  55577. {
  55578. AudioIODeviceType::DeviceSetupDetails details;
  55579. details.manager = &deviceManager;
  55580. details.minNumInputChannels = minInputChannels;
  55581. details.maxNumInputChannels = maxInputChannels;
  55582. details.minNumOutputChannels = minOutputChannels;
  55583. details.maxNumOutputChannels = maxOutputChannels;
  55584. details.useStereoPairs = showChannelsAsStereoPairs;
  55585. audioDeviceSettingsComp = new AudioDeviceSettingsPanel (type, details, hideAdvancedOptionsWithButton);
  55586. if (audioDeviceSettingsComp != 0)
  55587. {
  55588. addAndMakeVisible (audioDeviceSettingsComp);
  55589. audioDeviceSettingsComp->resized();
  55590. }
  55591. }
  55592. }
  55593. if (midiInputsList != 0)
  55594. {
  55595. midiInputsList->updateContent();
  55596. midiInputsList->repaint();
  55597. }
  55598. if (midiOutputSelector != 0)
  55599. {
  55600. midiOutputSelector->clear();
  55601. const StringArray midiOuts (MidiOutput::getDevices());
  55602. midiOutputSelector->addItem (TRANS("<< none >>"), -1);
  55603. midiOutputSelector->addSeparator();
  55604. for (int i = 0; i < midiOuts.size(); ++i)
  55605. midiOutputSelector->addItem (midiOuts[i], i + 1);
  55606. int current = -1;
  55607. if (deviceManager.getDefaultMidiOutput() != 0)
  55608. current = 1 + midiOuts.indexOf (deviceManager.getDefaultMidiOutputName());
  55609. midiOutputSelector->setSelectedId (current, true);
  55610. }
  55611. resized();
  55612. }
  55613. END_JUCE_NAMESPACE
  55614. /********* End of inlined file: juce_AudioDeviceSelectorComponent.cpp *********/
  55615. /********* Start of inlined file: juce_BubbleComponent.cpp *********/
  55616. BEGIN_JUCE_NAMESPACE
  55617. BubbleComponent::BubbleComponent()
  55618. : side (0),
  55619. allowablePlacements (above | below | left | right),
  55620. arrowTipX (0.0f),
  55621. arrowTipY (0.0f)
  55622. {
  55623. setInterceptsMouseClicks (false, false);
  55624. shadow.setShadowProperties (5.0f, 0.35f, 0, 0);
  55625. setComponentEffect (&shadow);
  55626. }
  55627. BubbleComponent::~BubbleComponent()
  55628. {
  55629. }
  55630. void BubbleComponent::paint (Graphics& g)
  55631. {
  55632. int x = content.getX();
  55633. int y = content.getY();
  55634. int w = content.getWidth();
  55635. int h = content.getHeight();
  55636. int cw, ch;
  55637. getContentSize (cw, ch);
  55638. if (side == 3)
  55639. x += w - cw;
  55640. else if (side != 1)
  55641. x += (w - cw) / 2;
  55642. w = cw;
  55643. if (side == 2)
  55644. y += h - ch;
  55645. else if (side != 0)
  55646. y += (h - ch) / 2;
  55647. h = ch;
  55648. getLookAndFeel().drawBubble (g, arrowTipX, arrowTipY,
  55649. (float) x, (float) y,
  55650. (float) w, (float) h);
  55651. const int cx = x + (w - cw) / 2;
  55652. const int cy = y + (h - ch) / 2;
  55653. const int indent = 3;
  55654. g.setOrigin (cx + indent, cy + indent);
  55655. g.reduceClipRegion (0, 0, cw - indent * 2, ch - indent * 2);
  55656. paintContent (g, cw - indent * 2, ch - indent * 2);
  55657. }
  55658. void BubbleComponent::setAllowedPlacement (const int newPlacement)
  55659. {
  55660. allowablePlacements = newPlacement;
  55661. }
  55662. void BubbleComponent::setPosition (Component* componentToPointTo)
  55663. {
  55664. jassert (componentToPointTo->isValidComponent());
  55665. int tx = 0;
  55666. int ty = 0;
  55667. if (getParentComponent() != 0)
  55668. componentToPointTo->relativePositionToOtherComponent (getParentComponent(), tx, ty);
  55669. else
  55670. componentToPointTo->relativePositionToGlobal (tx, ty);
  55671. setPosition (Rectangle (tx, ty, componentToPointTo->getWidth(), componentToPointTo->getHeight()));
  55672. }
  55673. void BubbleComponent::setPosition (const int arrowTipX,
  55674. const int arrowTipY)
  55675. {
  55676. setPosition (Rectangle (arrowTipX, arrowTipY, 1, 1));
  55677. }
  55678. void BubbleComponent::setPosition (const Rectangle& rectangleToPointTo)
  55679. {
  55680. Rectangle availableSpace;
  55681. if (getParentComponent() != 0)
  55682. {
  55683. availableSpace.setSize (getParentComponent()->getWidth(),
  55684. getParentComponent()->getHeight());
  55685. }
  55686. else
  55687. {
  55688. availableSpace = getParentMonitorArea();
  55689. }
  55690. int x = 0;
  55691. int y = 0;
  55692. int w = 150;
  55693. int h = 30;
  55694. getContentSize (w, h);
  55695. w += 30;
  55696. h += 30;
  55697. const float edgeIndent = 2.0f;
  55698. const int arrowLength = jmin (10, h / 3, w / 3);
  55699. int spaceAbove = ((allowablePlacements & above) != 0) ? jmax (0, rectangleToPointTo.getY() - availableSpace.getY()) : -1;
  55700. int spaceBelow = ((allowablePlacements & below) != 0) ? jmax (0, availableSpace.getBottom() - rectangleToPointTo.getBottom()) : -1;
  55701. int spaceLeft = ((allowablePlacements & left) != 0) ? jmax (0, rectangleToPointTo.getX() - availableSpace.getX()) : -1;
  55702. int spaceRight = ((allowablePlacements & right) != 0) ? jmax (0, availableSpace.getRight() - rectangleToPointTo.getRight()) : -1;
  55703. // look at whether the component is elongated, and if so, try to position next to its longer dimension.
  55704. if (rectangleToPointTo.getWidth() > rectangleToPointTo.getHeight() * 2
  55705. && (spaceAbove > h + 20 || spaceBelow > h + 20))
  55706. {
  55707. spaceLeft = spaceRight = 0;
  55708. }
  55709. else if (rectangleToPointTo.getWidth() < rectangleToPointTo.getHeight() / 2
  55710. && (spaceLeft > w + 20 || spaceRight > w + 20))
  55711. {
  55712. spaceAbove = spaceBelow = 0;
  55713. }
  55714. if (jmax (spaceAbove, spaceBelow) >= jmax (spaceLeft, spaceRight))
  55715. {
  55716. x = rectangleToPointTo.getX() + (rectangleToPointTo.getWidth() - w) / 2;
  55717. arrowTipX = w * 0.5f;
  55718. content.setSize (w, h - arrowLength);
  55719. if (spaceAbove >= spaceBelow)
  55720. {
  55721. // above
  55722. y = rectangleToPointTo.getY() - h;
  55723. content.setPosition (0, 0);
  55724. arrowTipY = h - edgeIndent;
  55725. side = 2;
  55726. }
  55727. else
  55728. {
  55729. // below
  55730. y = rectangleToPointTo.getBottom();
  55731. content.setPosition (0, arrowLength);
  55732. arrowTipY = edgeIndent;
  55733. side = 0;
  55734. }
  55735. }
  55736. else
  55737. {
  55738. y = rectangleToPointTo.getY() + (rectangleToPointTo.getHeight() - h) / 2;
  55739. arrowTipY = h * 0.5f;
  55740. content.setSize (w - arrowLength, h);
  55741. if (spaceLeft > spaceRight)
  55742. {
  55743. // on the left
  55744. x = rectangleToPointTo.getX() - w;
  55745. content.setPosition (0, 0);
  55746. arrowTipX = w - edgeIndent;
  55747. side = 3;
  55748. }
  55749. else
  55750. {
  55751. // on the right
  55752. x = rectangleToPointTo.getRight();
  55753. content.setPosition (arrowLength, 0);
  55754. arrowTipX = edgeIndent;
  55755. side = 1;
  55756. }
  55757. }
  55758. setBounds (x, y, w, h);
  55759. }
  55760. END_JUCE_NAMESPACE
  55761. /********* End of inlined file: juce_BubbleComponent.cpp *********/
  55762. /********* Start of inlined file: juce_BubbleMessageComponent.cpp *********/
  55763. BEGIN_JUCE_NAMESPACE
  55764. BubbleMessageComponent::BubbleMessageComponent (int fadeOutLengthMs)
  55765. : fadeOutLength (fadeOutLengthMs),
  55766. deleteAfterUse (false)
  55767. {
  55768. }
  55769. BubbleMessageComponent::~BubbleMessageComponent()
  55770. {
  55771. fadeOutComponent (fadeOutLength);
  55772. }
  55773. void BubbleMessageComponent::showAt (int x, int y,
  55774. const String& text,
  55775. const int numMillisecondsBeforeRemoving,
  55776. const bool removeWhenMouseClicked,
  55777. const bool deleteSelfAfterUse)
  55778. {
  55779. textLayout.clear();
  55780. textLayout.setText (text, Font (14.0f));
  55781. textLayout.layout (256, Justification::centredLeft, true);
  55782. setPosition (x, y);
  55783. init (numMillisecondsBeforeRemoving, removeWhenMouseClicked, deleteSelfAfterUse);
  55784. }
  55785. void BubbleMessageComponent::showAt (Component* const component,
  55786. const String& text,
  55787. const int numMillisecondsBeforeRemoving,
  55788. const bool removeWhenMouseClicked,
  55789. const bool deleteSelfAfterUse)
  55790. {
  55791. textLayout.clear();
  55792. textLayout.setText (text, Font (14.0f));
  55793. textLayout.layout (256, Justification::centredLeft, true);
  55794. setPosition (component);
  55795. init (numMillisecondsBeforeRemoving, removeWhenMouseClicked, deleteSelfAfterUse);
  55796. }
  55797. void BubbleMessageComponent::init (const int numMillisecondsBeforeRemoving,
  55798. const bool removeWhenMouseClicked,
  55799. const bool deleteSelfAfterUse)
  55800. {
  55801. setVisible (true);
  55802. deleteAfterUse = deleteSelfAfterUse;
  55803. if (numMillisecondsBeforeRemoving > 0)
  55804. expiryTime = Time::getMillisecondCounter() + numMillisecondsBeforeRemoving;
  55805. else
  55806. expiryTime = 0;
  55807. startTimer (77);
  55808. mouseClickCounter = Desktop::getInstance().getMouseButtonClickCounter();
  55809. if (! (removeWhenMouseClicked && isShowing()))
  55810. mouseClickCounter += 0xfffff;
  55811. repaint();
  55812. }
  55813. void BubbleMessageComponent::getContentSize (int& w, int& h)
  55814. {
  55815. w = textLayout.getWidth() + 16;
  55816. h = textLayout.getHeight() + 16;
  55817. }
  55818. void BubbleMessageComponent::paintContent (Graphics& g, int w, int h)
  55819. {
  55820. g.setColour (findColour (TooltipWindow::textColourId));
  55821. textLayout.drawWithin (g, 0, 0, w, h, Justification::centred);
  55822. }
  55823. void BubbleMessageComponent::timerCallback()
  55824. {
  55825. if (Desktop::getInstance().getMouseButtonClickCounter() > mouseClickCounter)
  55826. {
  55827. stopTimer();
  55828. setVisible (false);
  55829. if (deleteAfterUse)
  55830. delete this;
  55831. }
  55832. else if (expiryTime != 0 && Time::getMillisecondCounter() > expiryTime)
  55833. {
  55834. stopTimer();
  55835. fadeOutComponent (fadeOutLength);
  55836. if (deleteAfterUse)
  55837. delete this;
  55838. }
  55839. }
  55840. END_JUCE_NAMESPACE
  55841. /********* End of inlined file: juce_BubbleMessageComponent.cpp *********/
  55842. /********* Start of inlined file: juce_ColourSelector.cpp *********/
  55843. BEGIN_JUCE_NAMESPACE
  55844. static const int swatchesPerRow = 8;
  55845. static const int swatchHeight = 22;
  55846. class ColourComponentSlider : public Slider
  55847. {
  55848. public:
  55849. ColourComponentSlider (const String& name)
  55850. : Slider (name)
  55851. {
  55852. setRange (0.0, 255.0, 1.0);
  55853. }
  55854. ~ColourComponentSlider()
  55855. {
  55856. }
  55857. const String getTextFromValue (double currentValue)
  55858. {
  55859. return String::formatted (T("%02X"), (int)currentValue);
  55860. }
  55861. double getValueFromText (const String& text)
  55862. {
  55863. return (double) text.getHexValue32();
  55864. }
  55865. private:
  55866. ColourComponentSlider (const ColourComponentSlider&);
  55867. const ColourComponentSlider& operator= (const ColourComponentSlider&);
  55868. };
  55869. class ColourSpaceMarker : public Component
  55870. {
  55871. public:
  55872. ColourSpaceMarker()
  55873. {
  55874. setInterceptsMouseClicks (false, false);
  55875. }
  55876. ~ColourSpaceMarker()
  55877. {
  55878. }
  55879. void paint (Graphics& g)
  55880. {
  55881. g.setColour (Colour::greyLevel (0.1f));
  55882. g.drawEllipse (1.0f, 1.0f, getWidth() - 2.0f, getHeight() - 2.0f, 1.0f);
  55883. g.setColour (Colour::greyLevel (0.9f));
  55884. g.drawEllipse (2.0f, 2.0f, getWidth() - 4.0f, getHeight() - 4.0f, 1.0f);
  55885. }
  55886. private:
  55887. ColourSpaceMarker (const ColourSpaceMarker&);
  55888. const ColourSpaceMarker& operator= (const ColourSpaceMarker&);
  55889. };
  55890. class ColourSpaceView : public Component
  55891. {
  55892. ColourSelector* const owner;
  55893. float& h;
  55894. float& s;
  55895. float& v;
  55896. float lastHue;
  55897. ColourSpaceMarker* marker;
  55898. const int edge;
  55899. public:
  55900. ColourSpaceView (ColourSelector* owner_,
  55901. float& h_, float& s_, float& v_,
  55902. const int edgeSize)
  55903. : owner (owner_),
  55904. h (h_), s (s_), v (v_),
  55905. lastHue (0.0f),
  55906. edge (edgeSize)
  55907. {
  55908. addAndMakeVisible (marker = new ColourSpaceMarker());
  55909. setMouseCursor (MouseCursor::CrosshairCursor);
  55910. }
  55911. ~ColourSpaceView()
  55912. {
  55913. deleteAllChildren();
  55914. }
  55915. void paint (Graphics& g)
  55916. {
  55917. const float hue = h;
  55918. const float xScale = 1.0f / (getWidth() - edge * 2);
  55919. const float yScale = 1.0f / (getHeight() - edge * 2);
  55920. const Rectangle clip (g.getClipBounds());
  55921. const int x1 = jmax (clip.getX(), edge) & ~1;
  55922. const int x2 = jmin (clip.getRight(), getWidth() - edge) | 1;
  55923. const int y1 = jmax (clip.getY(), edge) & ~1;
  55924. const int y2 = jmin (clip.getBottom(), getHeight() - edge) | 1;
  55925. for (int y = y1; y < y2; y += 2)
  55926. {
  55927. const float v = jlimit (0.0f, 1.0f, 1.0f - (y - edge) * yScale);
  55928. for (int x = x1; x < x2; x += 2)
  55929. {
  55930. const float s = jlimit (0.0f, 1.0f, (x - edge) * xScale);
  55931. g.setColour (Colour (hue, s, v, 1.0f));
  55932. g.fillRect (x, y, 2, 2);
  55933. }
  55934. }
  55935. }
  55936. void mouseDown (const MouseEvent& e)
  55937. {
  55938. mouseDrag (e);
  55939. }
  55940. void mouseDrag (const MouseEvent& e)
  55941. {
  55942. const float s = (e.x - edge) / (float) (getWidth() - edge * 2);
  55943. const float v = 1.0f - (e.y - edge) / (float) (getHeight() - edge * 2);
  55944. owner->setSV (s, v);
  55945. }
  55946. void updateIfNeeded()
  55947. {
  55948. if (lastHue != h)
  55949. {
  55950. lastHue = h;
  55951. repaint();
  55952. }
  55953. resized();
  55954. }
  55955. void resized()
  55956. {
  55957. marker->setBounds (roundFloatToInt ((getWidth() - edge * 2) * s),
  55958. roundFloatToInt ((getHeight() - edge * 2) * (1.0f - v)),
  55959. edge * 2, edge * 2);
  55960. }
  55961. private:
  55962. ColourSpaceView (const ColourSpaceView&);
  55963. const ColourSpaceView& operator= (const ColourSpaceView&);
  55964. };
  55965. class HueSelectorMarker : public Component
  55966. {
  55967. public:
  55968. HueSelectorMarker()
  55969. {
  55970. setInterceptsMouseClicks (false, false);
  55971. }
  55972. ~HueSelectorMarker()
  55973. {
  55974. }
  55975. void paint (Graphics& g)
  55976. {
  55977. Path p;
  55978. p.addTriangle (1.0f, 1.0f,
  55979. getWidth() * 0.3f, getHeight() * 0.5f,
  55980. 1.0f, getHeight() - 1.0f);
  55981. p.addTriangle (getWidth() - 1.0f, 1.0f,
  55982. getWidth() * 0.7f, getHeight() * 0.5f,
  55983. getWidth() - 1.0f, getHeight() - 1.0f);
  55984. g.setColour (Colours::white.withAlpha (0.75f));
  55985. g.fillPath (p);
  55986. g.setColour (Colours::black.withAlpha (0.75f));
  55987. g.strokePath (p, PathStrokeType (1.2f));
  55988. }
  55989. private:
  55990. HueSelectorMarker (const HueSelectorMarker&);
  55991. const HueSelectorMarker& operator= (const HueSelectorMarker&);
  55992. };
  55993. class HueSelectorComp : public Component
  55994. {
  55995. public:
  55996. HueSelectorComp (ColourSelector* owner_,
  55997. float& h_, float& s_, float& v_,
  55998. const int edgeSize)
  55999. : owner (owner_),
  56000. h (h_), s (s_), v (v_),
  56001. lastHue (0.0f),
  56002. edge (edgeSize)
  56003. {
  56004. addAndMakeVisible (marker = new HueSelectorMarker());
  56005. }
  56006. ~HueSelectorComp()
  56007. {
  56008. deleteAllChildren();
  56009. }
  56010. void paint (Graphics& g)
  56011. {
  56012. const float yScale = 1.0f / (getHeight() - edge * 2);
  56013. const Rectangle clip (g.getClipBounds());
  56014. for (int y = jmin (clip.getBottom(), getHeight() - edge); --y >= jmax (edge, clip.getY());)
  56015. {
  56016. g.setColour (Colour ((y - edge) * yScale, 1.0f, 1.0f, 1.0f));
  56017. g.fillRect (edge, y, getWidth() - edge * 2, 1);
  56018. }
  56019. }
  56020. void resized()
  56021. {
  56022. marker->setBounds (0, roundFloatToInt ((getHeight() - edge * 2) * h),
  56023. getWidth(), edge * 2);
  56024. }
  56025. void mouseDown (const MouseEvent& e)
  56026. {
  56027. mouseDrag (e);
  56028. }
  56029. void mouseDrag (const MouseEvent& e)
  56030. {
  56031. const float hue = (e.y - edge) / (float) (getHeight() - edge * 2);
  56032. owner->setHue (hue);
  56033. }
  56034. void updateIfNeeded()
  56035. {
  56036. resized();
  56037. }
  56038. private:
  56039. ColourSelector* const owner;
  56040. float& h;
  56041. float& s;
  56042. float& v;
  56043. float lastHue;
  56044. HueSelectorMarker* marker;
  56045. const int edge;
  56046. HueSelectorComp (const HueSelectorComp&);
  56047. const HueSelectorComp& operator= (const HueSelectorComp&);
  56048. };
  56049. class SwatchComponent : public Component
  56050. {
  56051. public:
  56052. SwatchComponent (ColourSelector* owner_, int index_)
  56053. : owner (owner_),
  56054. index (index_)
  56055. {
  56056. }
  56057. ~SwatchComponent()
  56058. {
  56059. }
  56060. void paint (Graphics& g)
  56061. {
  56062. const Colour colour (owner->getSwatchColour (index));
  56063. g.fillCheckerBoard (0, 0, getWidth(), getHeight(),
  56064. 6, 6,
  56065. Colour (0xffdddddd).overlaidWith (colour),
  56066. Colour (0xffffffff).overlaidWith (colour));
  56067. }
  56068. void mouseDown (const MouseEvent&)
  56069. {
  56070. PopupMenu m;
  56071. m.addItem (1, TRANS("Use this swatch as the current colour"));
  56072. m.addSeparator();
  56073. m.addItem (2, TRANS("Set this swatch to the current colour"));
  56074. const int r = m.showAt (this);
  56075. if (r == 1)
  56076. {
  56077. owner->setCurrentColour (owner->getSwatchColour (index));
  56078. }
  56079. else if (r == 2)
  56080. {
  56081. if (owner->getSwatchColour (index) != owner->getCurrentColour())
  56082. {
  56083. owner->setSwatchColour (index, owner->getCurrentColour());
  56084. repaint();
  56085. }
  56086. }
  56087. }
  56088. private:
  56089. ColourSelector* const owner;
  56090. const int index;
  56091. SwatchComponent (const SwatchComponent&);
  56092. const SwatchComponent& operator= (const SwatchComponent&);
  56093. };
  56094. ColourSelector::ColourSelector (const int flags_,
  56095. const int edgeGap_,
  56096. const int gapAroundColourSpaceComponent)
  56097. : colour (Colours::white),
  56098. flags (flags_),
  56099. topSpace (0),
  56100. edgeGap (edgeGap_)
  56101. {
  56102. // not much point having a selector with no components in it!
  56103. jassert ((flags_ & (showColourAtTop | showSliders | showColourspace)) != 0);
  56104. updateHSV();
  56105. if ((flags & showSliders) != 0)
  56106. {
  56107. addAndMakeVisible (sliders[0] = new ColourComponentSlider (TRANS ("red")));
  56108. addAndMakeVisible (sliders[1] = new ColourComponentSlider (TRANS ("green")));
  56109. addAndMakeVisible (sliders[2] = new ColourComponentSlider (TRANS ("blue")));
  56110. addChildComponent (sliders[3] = new ColourComponentSlider (TRANS ("alpha")));
  56111. sliders[3]->setVisible ((flags & showAlphaChannel) != 0);
  56112. for (int i = 4; --i >= 0;)
  56113. sliders[i]->addListener (this);
  56114. }
  56115. else
  56116. {
  56117. zeromem (sliders, sizeof (sliders));
  56118. }
  56119. if ((flags & showColourspace) != 0)
  56120. {
  56121. addAndMakeVisible (colourSpace = new ColourSpaceView (this, h, s, v, gapAroundColourSpaceComponent));
  56122. addAndMakeVisible (hueSelector = new HueSelectorComp (this, h, s, v, gapAroundColourSpaceComponent));
  56123. }
  56124. else
  56125. {
  56126. colourSpace = 0;
  56127. hueSelector = 0;
  56128. }
  56129. update();
  56130. }
  56131. ColourSelector::~ColourSelector()
  56132. {
  56133. dispatchPendingMessages();
  56134. deleteAllChildren();
  56135. }
  56136. const Colour ColourSelector::getCurrentColour() const
  56137. {
  56138. return ((flags & showAlphaChannel) != 0) ? colour
  56139. : colour.withAlpha ((uint8) 0xff);
  56140. }
  56141. void ColourSelector::setCurrentColour (const Colour& c)
  56142. {
  56143. if (c != colour)
  56144. {
  56145. colour = ((flags & showAlphaChannel) != 0) ? c : c.withAlpha ((uint8) 0xff);
  56146. updateHSV();
  56147. update();
  56148. }
  56149. }
  56150. void ColourSelector::setHue (float newH)
  56151. {
  56152. newH = jlimit (0.0f, 1.0f, newH);
  56153. if (h != newH)
  56154. {
  56155. h = newH;
  56156. colour = Colour (h, s, v, colour.getFloatAlpha());
  56157. update();
  56158. }
  56159. }
  56160. void ColourSelector::setSV (float newS, float newV)
  56161. {
  56162. newS = jlimit (0.0f, 1.0f, newS);
  56163. newV = jlimit (0.0f, 1.0f, newV);
  56164. if (s != newS || v != newV)
  56165. {
  56166. s = newS;
  56167. v = newV;
  56168. colour = Colour (h, s, v, colour.getFloatAlpha());
  56169. update();
  56170. }
  56171. }
  56172. void ColourSelector::updateHSV()
  56173. {
  56174. colour.getHSB (h, s, v);
  56175. }
  56176. void ColourSelector::update()
  56177. {
  56178. if (sliders[0] != 0)
  56179. {
  56180. sliders[0]->setValue ((int) colour.getRed());
  56181. sliders[1]->setValue ((int) colour.getGreen());
  56182. sliders[2]->setValue ((int) colour.getBlue());
  56183. sliders[3]->setValue ((int) colour.getAlpha());
  56184. }
  56185. if (colourSpace != 0)
  56186. {
  56187. ((ColourSpaceView*) colourSpace)->updateIfNeeded();
  56188. ((HueSelectorComp*) hueSelector)->updateIfNeeded();
  56189. }
  56190. if ((flags & showColourAtTop) != 0)
  56191. repaint (0, edgeGap, getWidth(), topSpace - edgeGap);
  56192. sendChangeMessage (this);
  56193. }
  56194. void ColourSelector::paint (Graphics& g)
  56195. {
  56196. g.fillAll (findColour (backgroundColourId));
  56197. if ((flags & showColourAtTop) != 0)
  56198. {
  56199. const Colour colour (getCurrentColour());
  56200. g.fillCheckerBoard (edgeGap, edgeGap, getWidth() - edgeGap - edgeGap, topSpace - edgeGap - edgeGap,
  56201. 10, 10,
  56202. Colour (0xffdddddd).overlaidWith (colour),
  56203. Colour (0xffffffff).overlaidWith (colour));
  56204. g.setColour (Colours::white.overlaidWith (colour).contrasting());
  56205. g.setFont (14.0f, true);
  56206. g.drawText (((flags & showAlphaChannel) != 0)
  56207. ? String::formatted (T("#%02X%02X%02X%02X"),
  56208. (int) colour.getAlpha(),
  56209. (int) colour.getRed(),
  56210. (int) colour.getGreen(),
  56211. (int) colour.getBlue())
  56212. : String::formatted (T("#%02X%02X%02X"),
  56213. (int) colour.getRed(),
  56214. (int) colour.getGreen(),
  56215. (int) colour.getBlue()),
  56216. 0, edgeGap, getWidth(), topSpace - edgeGap * 2,
  56217. Justification::centred, false);
  56218. }
  56219. if ((flags & showSliders) != 0)
  56220. {
  56221. g.setColour (findColour (labelTextColourId));
  56222. g.setFont (11.0f);
  56223. for (int i = 4; --i >= 0;)
  56224. {
  56225. if (sliders[i]->isVisible())
  56226. g.drawText (sliders[i]->getName() + T(":"),
  56227. 0, sliders[i]->getY(),
  56228. sliders[i]->getX() - 8, sliders[i]->getHeight(),
  56229. Justification::centredRight, false);
  56230. }
  56231. }
  56232. }
  56233. void ColourSelector::resized()
  56234. {
  56235. const int numSliders = ((flags & showAlphaChannel) != 0) ? 4 : 3;
  56236. const int numSwatches = getNumSwatches();
  56237. const int swatchSpace = numSwatches > 0 ? edgeGap + swatchHeight * ((numSwatches + 7) / swatchesPerRow) : 0;
  56238. const int sliderSpace = ((flags & showSliders) != 0) ? jmin (22 * numSliders + edgeGap, proportionOfHeight (0.3f)) : 0;
  56239. topSpace = ((flags & showColourAtTop) != 0) ? jmin (30 + edgeGap * 2, proportionOfHeight (0.2f)) : edgeGap;
  56240. int y = topSpace;
  56241. if ((flags & showColourspace) != 0)
  56242. {
  56243. const int hueWidth = jmin (50, proportionOfWidth (0.15f));
  56244. colourSpace->setBounds (edgeGap, y,
  56245. getWidth() - hueWidth - edgeGap - 4,
  56246. getHeight() - topSpace - sliderSpace - swatchSpace - edgeGap);
  56247. hueSelector->setBounds (colourSpace->getRight() + 4, y,
  56248. getWidth() - edgeGap - (colourSpace->getRight() + 4),
  56249. colourSpace->getHeight());
  56250. y = getHeight() - sliderSpace - swatchSpace - edgeGap;
  56251. }
  56252. if ((flags & showSliders) != 0)
  56253. {
  56254. const int sliderHeight = jmax (4, sliderSpace / numSliders);
  56255. for (int i = 0; i < numSliders; ++i)
  56256. {
  56257. sliders[i]->setBounds (proportionOfWidth (0.2f), y,
  56258. proportionOfWidth (0.72f), sliderHeight - 2);
  56259. y += sliderHeight;
  56260. }
  56261. }
  56262. if (numSwatches > 0)
  56263. {
  56264. const int startX = 8;
  56265. const int xGap = 4;
  56266. const int yGap = 4;
  56267. const int swatchWidth = (getWidth() - startX * 2) / swatchesPerRow;
  56268. y += edgeGap;
  56269. if (swatchComponents.size() != numSwatches)
  56270. {
  56271. int i;
  56272. for (i = swatchComponents.size(); --i >= 0;)
  56273. {
  56274. SwatchComponent* const sc = (SwatchComponent*) swatchComponents.getUnchecked(i);
  56275. delete sc;
  56276. }
  56277. for (i = 0; i < numSwatches; ++i)
  56278. {
  56279. SwatchComponent* const sc = new SwatchComponent (this, i);
  56280. swatchComponents.add (sc);
  56281. addAndMakeVisible (sc);
  56282. }
  56283. }
  56284. int x = startX;
  56285. for (int i = 0; i < swatchComponents.size(); ++i)
  56286. {
  56287. SwatchComponent* const sc = (SwatchComponent*) swatchComponents.getUnchecked(i);
  56288. sc->setBounds (x + xGap / 2,
  56289. y + yGap / 2,
  56290. swatchWidth - xGap,
  56291. swatchHeight - yGap);
  56292. if (((i + 1) % swatchesPerRow) == 0)
  56293. {
  56294. x = startX;
  56295. y += swatchHeight;
  56296. }
  56297. else
  56298. {
  56299. x += swatchWidth;
  56300. }
  56301. }
  56302. }
  56303. }
  56304. void ColourSelector::sliderValueChanged (Slider*)
  56305. {
  56306. if (sliders[0] != 0)
  56307. setCurrentColour (Colour ((uint8) sliders[0]->getValue(),
  56308. (uint8) sliders[1]->getValue(),
  56309. (uint8) sliders[2]->getValue(),
  56310. (uint8) sliders[3]->getValue()));
  56311. }
  56312. int ColourSelector::getNumSwatches() const
  56313. {
  56314. return 0;
  56315. }
  56316. const Colour ColourSelector::getSwatchColour (const int) const
  56317. {
  56318. jassertfalse // if you've overridden getNumSwatches(), you also need to implement this method
  56319. return Colours::black;
  56320. }
  56321. void ColourSelector::setSwatchColour (const int, const Colour&) const
  56322. {
  56323. jassertfalse // if you've overridden getNumSwatches(), you also need to implement this method
  56324. }
  56325. END_JUCE_NAMESPACE
  56326. /********* End of inlined file: juce_ColourSelector.cpp *********/
  56327. /********* Start of inlined file: juce_DropShadower.cpp *********/
  56328. BEGIN_JUCE_NAMESPACE
  56329. class ShadowWindow : public Component
  56330. {
  56331. Component* owner;
  56332. Image** shadowImageSections;
  56333. const int type; // 0 = left, 1 = right, 2 = top, 3 = bottom. left + right are full-height
  56334. public:
  56335. ShadowWindow (Component* const owner_,
  56336. const int type_,
  56337. Image** const shadowImageSections_)
  56338. : owner (owner_),
  56339. shadowImageSections (shadowImageSections_),
  56340. type (type_)
  56341. {
  56342. setInterceptsMouseClicks (false, false);
  56343. if (owner_->isOnDesktop())
  56344. {
  56345. setSize (1, 1); // to keep the OS happy by not having zero-size windows
  56346. addToDesktop (ComponentPeer::windowIgnoresMouseClicks
  56347. | ComponentPeer::windowIsTemporary
  56348. | ComponentPeer::windowIgnoresKeyPresses);
  56349. }
  56350. else if (owner_->getParentComponent() != 0)
  56351. {
  56352. owner_->getParentComponent()->addChildComponent (this);
  56353. }
  56354. }
  56355. ~ShadowWindow()
  56356. {
  56357. }
  56358. void paint (Graphics& g)
  56359. {
  56360. Image* const topLeft = shadowImageSections [type * 3];
  56361. Image* const bottomRight = shadowImageSections [type * 3 + 1];
  56362. Image* const filler = shadowImageSections [type * 3 + 2];
  56363. ImageBrush fillBrush (filler, 0, 0, 1.0f);
  56364. g.setOpacity (1.0f);
  56365. if (type < 2)
  56366. {
  56367. int imH = jmin (topLeft->getHeight(), getHeight() / 2);
  56368. g.drawImage (topLeft,
  56369. 0, 0, topLeft->getWidth(), imH,
  56370. 0, 0, topLeft->getWidth(), imH);
  56371. imH = jmin (bottomRight->getHeight(), getHeight() - getHeight() / 2);
  56372. g.drawImage (bottomRight,
  56373. 0, getHeight() - imH, bottomRight->getWidth(), imH,
  56374. 0, bottomRight->getHeight() - imH, bottomRight->getWidth(), imH);
  56375. g.setBrush (&fillBrush);
  56376. g.fillRect (0, topLeft->getHeight(), getWidth(), getHeight() - (topLeft->getHeight() + bottomRight->getHeight()));
  56377. }
  56378. else
  56379. {
  56380. int imW = jmin (topLeft->getWidth(), getWidth() / 2);
  56381. g.drawImage (topLeft,
  56382. 0, 0, imW, topLeft->getHeight(),
  56383. 0, 0, imW, topLeft->getHeight());
  56384. imW = jmin (bottomRight->getWidth(), getWidth() - getWidth() / 2);
  56385. g.drawImage (bottomRight,
  56386. getWidth() - imW, 0, imW, bottomRight->getHeight(),
  56387. bottomRight->getWidth() - imW, 0, imW, bottomRight->getHeight());
  56388. g.setBrush (&fillBrush);
  56389. g.fillRect (topLeft->getWidth(), 0, getWidth() - (topLeft->getWidth() + bottomRight->getWidth()), getHeight());
  56390. }
  56391. }
  56392. void resized()
  56393. {
  56394. repaint(); // (needed for correct repainting)
  56395. }
  56396. private:
  56397. ShadowWindow (const ShadowWindow&);
  56398. const ShadowWindow& operator= (const ShadowWindow&);
  56399. };
  56400. DropShadower::DropShadower (const float alpha_,
  56401. const int xOffset_,
  56402. const int yOffset_,
  56403. const float blurRadius_)
  56404. : owner (0),
  56405. numShadows (0),
  56406. shadowEdge (jmax (xOffset_, yOffset_) + (int) blurRadius_),
  56407. xOffset (xOffset_),
  56408. yOffset (yOffset_),
  56409. alpha (alpha_),
  56410. blurRadius (blurRadius_),
  56411. inDestructor (false),
  56412. reentrant (false)
  56413. {
  56414. }
  56415. DropShadower::~DropShadower()
  56416. {
  56417. if (owner != 0)
  56418. owner->removeComponentListener (this);
  56419. inDestructor = true;
  56420. deleteShadowWindows();
  56421. }
  56422. void DropShadower::deleteShadowWindows()
  56423. {
  56424. if (numShadows > 0)
  56425. {
  56426. int i;
  56427. for (i = numShadows; --i >= 0;)
  56428. delete shadowWindows[i];
  56429. for (i = 12; --i >= 0;)
  56430. delete shadowImageSections[i];
  56431. numShadows = 0;
  56432. }
  56433. }
  56434. void DropShadower::setOwner (Component* componentToFollow)
  56435. {
  56436. if (componentToFollow != owner)
  56437. {
  56438. if (owner != 0)
  56439. owner->removeComponentListener (this);
  56440. // (the component can't be null)
  56441. jassert (componentToFollow != 0);
  56442. owner = componentToFollow;
  56443. jassert (owner != 0);
  56444. jassert (owner->isOpaque()); // doesn't work properly for semi-transparent comps!
  56445. owner->addComponentListener (this);
  56446. updateShadows();
  56447. }
  56448. }
  56449. void DropShadower::componentMovedOrResized (Component&, bool /*wasMoved*/, bool /*wasResized*/)
  56450. {
  56451. updateShadows();
  56452. }
  56453. void DropShadower::componentBroughtToFront (Component&)
  56454. {
  56455. bringShadowWindowsToFront();
  56456. }
  56457. void DropShadower::componentChildrenChanged (Component&)
  56458. {
  56459. }
  56460. void DropShadower::componentParentHierarchyChanged (Component&)
  56461. {
  56462. deleteShadowWindows();
  56463. updateShadows();
  56464. }
  56465. void DropShadower::componentVisibilityChanged (Component&)
  56466. {
  56467. updateShadows();
  56468. }
  56469. void DropShadower::updateShadows()
  56470. {
  56471. if (reentrant || inDestructor || (owner == 0))
  56472. return;
  56473. reentrant = true;
  56474. ComponentPeer* const nw = owner->getPeer();
  56475. const bool isOwnerVisible = owner->isVisible()
  56476. && (nw == 0 || ! nw->isMinimised());
  56477. const bool createShadowWindows = numShadows == 0
  56478. && owner->getWidth() > 0
  56479. && owner->getHeight() > 0
  56480. && isOwnerVisible
  56481. && (Desktop::canUseSemiTransparentWindows()
  56482. || owner->getParentComponent() != 0);
  56483. if (createShadowWindows)
  56484. {
  56485. // keep a cached version of the image to save doing the gaussian too often
  56486. String imageId;
  56487. imageId << shadowEdge << T(',')
  56488. << xOffset << T(',')
  56489. << yOffset << T(',')
  56490. << alpha;
  56491. const int hash = imageId.hashCode();
  56492. Image* bigIm = ImageCache::getFromHashCode (hash);
  56493. if (bigIm == 0)
  56494. {
  56495. bigIm = new Image (Image::ARGB, shadowEdge * 5, shadowEdge * 5, true);
  56496. Graphics bigG (*bigIm);
  56497. bigG.setColour (Colours::black.withAlpha (alpha));
  56498. bigG.fillRect (shadowEdge + xOffset,
  56499. shadowEdge + yOffset,
  56500. bigIm->getWidth() - (shadowEdge * 2),
  56501. bigIm->getHeight() - (shadowEdge * 2));
  56502. ImageConvolutionKernel blurKernel (roundFloatToInt (blurRadius * 2.0f));
  56503. blurKernel.createGaussianBlur (blurRadius);
  56504. blurKernel.applyToImage (*bigIm, 0,
  56505. xOffset,
  56506. yOffset,
  56507. bigIm->getWidth(),
  56508. bigIm->getHeight());
  56509. ImageCache::addImageToCache (bigIm, hash);
  56510. }
  56511. const int iw = bigIm->getWidth();
  56512. const int ih = bigIm->getHeight();
  56513. const int shadowEdge2 = shadowEdge * 2;
  56514. setShadowImage (bigIm, 0, shadowEdge, shadowEdge2, 0, 0);
  56515. setShadowImage (bigIm, 1, shadowEdge, shadowEdge2, 0, ih - shadowEdge2);
  56516. setShadowImage (bigIm, 2, shadowEdge, shadowEdge, 0, shadowEdge2);
  56517. setShadowImage (bigIm, 3, shadowEdge, shadowEdge2, iw - shadowEdge, 0);
  56518. setShadowImage (bigIm, 4, shadowEdge, shadowEdge2, iw - shadowEdge, ih - shadowEdge2);
  56519. setShadowImage (bigIm, 5, shadowEdge, shadowEdge, iw - shadowEdge, shadowEdge2);
  56520. setShadowImage (bigIm, 6, shadowEdge, shadowEdge, shadowEdge, 0);
  56521. setShadowImage (bigIm, 7, shadowEdge, shadowEdge, iw - shadowEdge2, 0);
  56522. setShadowImage (bigIm, 8, shadowEdge, shadowEdge, shadowEdge2, 0);
  56523. setShadowImage (bigIm, 9, shadowEdge, shadowEdge, shadowEdge, ih - shadowEdge);
  56524. setShadowImage (bigIm, 10, shadowEdge, shadowEdge, iw - shadowEdge2, ih - shadowEdge);
  56525. setShadowImage (bigIm, 11, shadowEdge, shadowEdge, shadowEdge2, ih - shadowEdge);
  56526. ImageCache::release (bigIm);
  56527. for (int i = 0; i < 4; ++i)
  56528. {
  56529. shadowWindows[numShadows] = new ShadowWindow (owner, i, shadowImageSections);
  56530. ++numShadows;
  56531. }
  56532. }
  56533. if (numShadows > 0)
  56534. {
  56535. for (int i = numShadows; --i >= 0;)
  56536. {
  56537. shadowWindows[i]->setAlwaysOnTop (owner->isAlwaysOnTop());
  56538. shadowWindows[i]->setVisible (isOwnerVisible);
  56539. }
  56540. const int x = owner->getX();
  56541. const int y = owner->getY() - shadowEdge;
  56542. const int w = owner->getWidth();
  56543. const int h = owner->getHeight() + shadowEdge + shadowEdge;
  56544. shadowWindows[0]->setBounds (x - shadowEdge,
  56545. y,
  56546. shadowEdge,
  56547. h);
  56548. shadowWindows[1]->setBounds (x + w,
  56549. y,
  56550. shadowEdge,
  56551. h);
  56552. shadowWindows[2]->setBounds (x,
  56553. y,
  56554. w,
  56555. shadowEdge);
  56556. shadowWindows[3]->setBounds (x,
  56557. owner->getBottom(),
  56558. w,
  56559. shadowEdge);
  56560. }
  56561. reentrant = false;
  56562. if (createShadowWindows)
  56563. bringShadowWindowsToFront();
  56564. }
  56565. void DropShadower::setShadowImage (Image* const src,
  56566. const int num,
  56567. const int w,
  56568. const int h,
  56569. const int sx,
  56570. const int sy) throw()
  56571. {
  56572. shadowImageSections[num] = new Image (Image::ARGB, w, h, true);
  56573. Graphics g (*shadowImageSections[num]);
  56574. g.drawImage (src, 0, 0, w, h, sx, sy, w, h);
  56575. }
  56576. void DropShadower::bringShadowWindowsToFront()
  56577. {
  56578. if (! (inDestructor || reentrant))
  56579. {
  56580. updateShadows();
  56581. reentrant = true;
  56582. for (int i = numShadows; --i >= 0;)
  56583. shadowWindows[i]->toBehind (owner);
  56584. reentrant = false;
  56585. }
  56586. }
  56587. END_JUCE_NAMESPACE
  56588. /********* End of inlined file: juce_DropShadower.cpp *********/
  56589. /********* Start of inlined file: juce_MagnifierComponent.cpp *********/
  56590. BEGIN_JUCE_NAMESPACE
  56591. class MagnifyingPeer : public ComponentPeer
  56592. {
  56593. public:
  56594. MagnifyingPeer (Component* const component_,
  56595. MagnifierComponent* const magnifierComp_)
  56596. : ComponentPeer (component_, 0),
  56597. magnifierComp (magnifierComp_)
  56598. {
  56599. }
  56600. ~MagnifyingPeer()
  56601. {
  56602. }
  56603. void* getNativeHandle() const { return 0; }
  56604. void setVisible (bool) {}
  56605. void setTitle (const String&) {}
  56606. void setPosition (int, int) {}
  56607. void setSize (int, int) {}
  56608. void setBounds (int, int, int, int, const bool) {}
  56609. void setMinimised (bool) {}
  56610. bool isMinimised() const { return false; }
  56611. void setFullScreen (bool) {}
  56612. bool isFullScreen() const { return false; }
  56613. const BorderSize getFrameSize() const { return BorderSize (0); }
  56614. bool setAlwaysOnTop (bool) { return true; }
  56615. void toFront (bool) {}
  56616. void toBehind (ComponentPeer*) {}
  56617. void setIcon (const Image&) {}
  56618. bool isFocused() const
  56619. {
  56620. return magnifierComp->hasKeyboardFocus (true);
  56621. }
  56622. void grabFocus()
  56623. {
  56624. ComponentPeer* peer = magnifierComp->getPeer();
  56625. if (peer != 0)
  56626. peer->grabFocus();
  56627. }
  56628. void textInputRequired (int x, int y)
  56629. {
  56630. ComponentPeer* peer = magnifierComp->getPeer();
  56631. if (peer != 0)
  56632. peer->textInputRequired (x, y);
  56633. }
  56634. void getBounds (int& x, int& y, int& w, int& h) const
  56635. {
  56636. x = magnifierComp->getScreenX();
  56637. y = magnifierComp->getScreenY();
  56638. w = component->getWidth();
  56639. h = component->getHeight();
  56640. }
  56641. int getScreenX() const { return magnifierComp->getScreenX(); }
  56642. int getScreenY() const { return magnifierComp->getScreenY(); }
  56643. void relativePositionToGlobal (int& x, int& y)
  56644. {
  56645. const double zoom = magnifierComp->getScaleFactor();
  56646. x = roundDoubleToInt (x * zoom);
  56647. y = roundDoubleToInt (y * zoom);
  56648. magnifierComp->relativePositionToGlobal (x, y);
  56649. }
  56650. void globalPositionToRelative (int& x, int& y)
  56651. {
  56652. magnifierComp->globalPositionToRelative (x, y);
  56653. const double zoom = magnifierComp->getScaleFactor();
  56654. x = roundDoubleToInt (x / zoom);
  56655. y = roundDoubleToInt (y / zoom);
  56656. }
  56657. bool contains (int x, int y, bool) const
  56658. {
  56659. return ((unsigned int) x) < (unsigned int) magnifierComp->getWidth()
  56660. && ((unsigned int) y) < (unsigned int) magnifierComp->getHeight();
  56661. }
  56662. void repaint (int x, int y, int w, int h)
  56663. {
  56664. const double zoom = magnifierComp->getScaleFactor();
  56665. magnifierComp->repaint ((int) (x * zoom),
  56666. (int) (y * zoom),
  56667. roundDoubleToInt (w * zoom) + 1,
  56668. roundDoubleToInt (h * zoom) + 1);
  56669. }
  56670. void performAnyPendingRepaintsNow()
  56671. {
  56672. }
  56673. juce_UseDebuggingNewOperator
  56674. private:
  56675. MagnifierComponent* const magnifierComp;
  56676. MagnifyingPeer (const MagnifyingPeer&);
  56677. const MagnifyingPeer& operator= (const MagnifyingPeer&);
  56678. };
  56679. class PeerHolderComp : public Component
  56680. {
  56681. public:
  56682. PeerHolderComp (MagnifierComponent* const magnifierComp_)
  56683. : magnifierComp (magnifierComp_)
  56684. {
  56685. setVisible (true);
  56686. }
  56687. ~PeerHolderComp()
  56688. {
  56689. }
  56690. ComponentPeer* createNewPeer (int, void*)
  56691. {
  56692. return new MagnifyingPeer (this, magnifierComp);
  56693. }
  56694. void childBoundsChanged (Component* c)
  56695. {
  56696. if (c != 0)
  56697. {
  56698. setSize (c->getWidth(), c->getHeight());
  56699. magnifierComp->childBoundsChanged (this);
  56700. }
  56701. }
  56702. void mouseWheelMove (const MouseEvent& e, float ix, float iy)
  56703. {
  56704. // unhandled mouse wheel moves can be referred upwards to the parent comp..
  56705. Component* const p = magnifierComp->getParentComponent();
  56706. if (p != 0)
  56707. p->mouseWheelMove (e.getEventRelativeTo (p), ix, iy);
  56708. }
  56709. private:
  56710. MagnifierComponent* const magnifierComp;
  56711. PeerHolderComp (const PeerHolderComp&);
  56712. const PeerHolderComp& operator= (const PeerHolderComp&);
  56713. };
  56714. MagnifierComponent::MagnifierComponent (Component* const content_,
  56715. const bool deleteContentCompWhenNoLongerNeeded)
  56716. : content (content_),
  56717. scaleFactor (0.0),
  56718. peer (0),
  56719. deleteContent (deleteContentCompWhenNoLongerNeeded),
  56720. quality (Graphics::lowResamplingQuality)
  56721. {
  56722. holderComp = new PeerHolderComp (this);
  56723. setScaleFactor (1.0);
  56724. }
  56725. MagnifierComponent::~MagnifierComponent()
  56726. {
  56727. delete holderComp;
  56728. if (deleteContent)
  56729. delete content;
  56730. }
  56731. void MagnifierComponent::setScaleFactor (double newScaleFactor)
  56732. {
  56733. jassert (newScaleFactor > 0.0); // hmm - unlikely to work well with a negative scale factor
  56734. newScaleFactor = jlimit (1.0 / 8.0, 1000.0, newScaleFactor);
  56735. if (scaleFactor != newScaleFactor)
  56736. {
  56737. scaleFactor = newScaleFactor;
  56738. if (scaleFactor == 1.0)
  56739. {
  56740. holderComp->removeFromDesktop();
  56741. peer = 0;
  56742. addChildComponent (content);
  56743. childBoundsChanged (content);
  56744. }
  56745. else
  56746. {
  56747. holderComp->addAndMakeVisible (content);
  56748. holderComp->childBoundsChanged (content);
  56749. childBoundsChanged (holderComp);
  56750. holderComp->addToDesktop (0);
  56751. peer = holderComp->getPeer();
  56752. }
  56753. repaint();
  56754. }
  56755. }
  56756. void MagnifierComponent::setResamplingQuality (Graphics::ResamplingQuality newQuality)
  56757. {
  56758. quality = newQuality;
  56759. }
  56760. void MagnifierComponent::paint (Graphics& g)
  56761. {
  56762. const int w = holderComp->getWidth();
  56763. const int h = holderComp->getHeight();
  56764. if (w == 0 || h == 0)
  56765. return;
  56766. const Rectangle r (g.getClipBounds());
  56767. const int srcX = (int) (r.getX() / scaleFactor);
  56768. const int srcY = (int) (r.getY() / scaleFactor);
  56769. int srcW = roundDoubleToInt (r.getRight() / scaleFactor) - srcX;
  56770. int srcH = roundDoubleToInt (r.getBottom() / scaleFactor) - srcY;
  56771. if (scaleFactor >= 1.0)
  56772. {
  56773. ++srcW;
  56774. ++srcH;
  56775. }
  56776. Image temp (Image::ARGB, jmax (w, srcX + srcW), jmax (h, srcY + srcH), false);
  56777. temp.clear (srcX, srcY, srcW, srcH);
  56778. Graphics g2 (temp);
  56779. g2.reduceClipRegion (srcX, srcY, srcW, srcH);
  56780. holderComp->paintEntireComponent (g2);
  56781. g.setImageResamplingQuality (quality);
  56782. g.drawImage (&temp,
  56783. 0, 0, (int) (w * scaleFactor), (int) (h * scaleFactor),
  56784. 0, 0, w, h,
  56785. false);
  56786. }
  56787. void MagnifierComponent::childBoundsChanged (Component* c)
  56788. {
  56789. if (c != 0)
  56790. setSize (roundDoubleToInt (c->getWidth() * scaleFactor),
  56791. roundDoubleToInt (c->getHeight() * scaleFactor));
  56792. }
  56793. void MagnifierComponent::mouseDown (const MouseEvent& e)
  56794. {
  56795. if (peer != 0)
  56796. peer->handleMouseDown (scaleInt (e.x), scaleInt (e.y), e.eventTime.toMilliseconds());
  56797. }
  56798. void MagnifierComponent::mouseUp (const MouseEvent& e)
  56799. {
  56800. if (peer != 0)
  56801. peer->handleMouseUp (e.mods.getRawFlags(), scaleInt (e.x), scaleInt (e.y), e.eventTime.toMilliseconds());
  56802. }
  56803. void MagnifierComponent::mouseDrag (const MouseEvent& e)
  56804. {
  56805. if (peer != 0)
  56806. peer->handleMouseDrag (scaleInt (e.x), scaleInt (e.y), e.eventTime.toMilliseconds());
  56807. }
  56808. void MagnifierComponent::mouseMove (const MouseEvent& e)
  56809. {
  56810. if (peer != 0)
  56811. peer->handleMouseMove (scaleInt (e.x), scaleInt (e.y), e.eventTime.toMilliseconds());
  56812. }
  56813. void MagnifierComponent::mouseEnter (const MouseEvent& e)
  56814. {
  56815. if (peer != 0)
  56816. peer->handleMouseEnter (scaleInt (e.x), scaleInt (e.y), e.eventTime.toMilliseconds());
  56817. }
  56818. void MagnifierComponent::mouseExit (const MouseEvent& e)
  56819. {
  56820. if (peer != 0)
  56821. peer->handleMouseExit (scaleInt (e.x), scaleInt (e.y), e.eventTime.toMilliseconds());
  56822. }
  56823. void MagnifierComponent::mouseWheelMove (const MouseEvent& e, float ix, float iy)
  56824. {
  56825. if (peer != 0)
  56826. peer->handleMouseWheel (roundFloatToInt (ix * 256.0f),
  56827. roundFloatToInt (iy * 256.0f),
  56828. e.eventTime.toMilliseconds());
  56829. else
  56830. Component::mouseWheelMove (e, ix, iy);
  56831. }
  56832. int MagnifierComponent::scaleInt (const int n) const throw()
  56833. {
  56834. return roundDoubleToInt (n / scaleFactor);
  56835. }
  56836. END_JUCE_NAMESPACE
  56837. /********* End of inlined file: juce_MagnifierComponent.cpp *********/
  56838. /********* Start of inlined file: juce_MidiKeyboardComponent.cpp *********/
  56839. BEGIN_JUCE_NAMESPACE
  56840. class MidiKeyboardUpDownButton : public Button
  56841. {
  56842. public:
  56843. MidiKeyboardUpDownButton (MidiKeyboardComponent* const owner_,
  56844. const int delta_)
  56845. : Button (String::empty),
  56846. owner (owner_),
  56847. delta (delta_)
  56848. {
  56849. setOpaque (true);
  56850. }
  56851. ~MidiKeyboardUpDownButton()
  56852. {
  56853. }
  56854. void clicked()
  56855. {
  56856. int note = owner->getLowestVisibleKey();
  56857. if (delta < 0)
  56858. note = (note - 1) / 12;
  56859. else
  56860. note = note / 12 + 1;
  56861. owner->setLowestVisibleKey (note * 12);
  56862. }
  56863. void paintButton (Graphics& g,
  56864. bool isMouseOverButton,
  56865. bool isButtonDown)
  56866. {
  56867. owner->drawUpDownButton (g, getWidth(), getHeight(),
  56868. isMouseOverButton, isButtonDown,
  56869. delta > 0);
  56870. }
  56871. private:
  56872. MidiKeyboardComponent* const owner;
  56873. const int delta;
  56874. MidiKeyboardUpDownButton (const MidiKeyboardUpDownButton&);
  56875. const MidiKeyboardUpDownButton& operator= (const MidiKeyboardUpDownButton&);
  56876. };
  56877. MidiKeyboardComponent::MidiKeyboardComponent (MidiKeyboardState& state_,
  56878. const Orientation orientation_)
  56879. : state (state_),
  56880. xOffset (0),
  56881. blackNoteLength (1),
  56882. keyWidth (16.0f),
  56883. orientation (orientation_),
  56884. midiChannel (1),
  56885. midiInChannelMask (0xffff),
  56886. velocity (1.0f),
  56887. noteUnderMouse (-1),
  56888. mouseDownNote (-1),
  56889. rangeStart (0),
  56890. rangeEnd (127),
  56891. firstKey (12 * 4),
  56892. canScroll (true),
  56893. mouseDragging (false),
  56894. keyPresses (4),
  56895. keyPressNotes (16),
  56896. keyMappingOctave (6),
  56897. octaveNumForMiddleC (3)
  56898. {
  56899. addChildComponent (scrollDown = new MidiKeyboardUpDownButton (this, -1));
  56900. addChildComponent (scrollUp = new MidiKeyboardUpDownButton (this, 1));
  56901. // initialise with a default set of querty key-mappings..
  56902. const char* const keymap = "awsedftgyhujkolp;";
  56903. for (int i = String (keymap).length(); --i >= 0;)
  56904. setKeyPressForNote (KeyPress (keymap[i], 0, 0), i);
  56905. setOpaque (true);
  56906. setWantsKeyboardFocus (true);
  56907. state.addListener (this);
  56908. }
  56909. MidiKeyboardComponent::~MidiKeyboardComponent()
  56910. {
  56911. state.removeListener (this);
  56912. jassert (mouseDownNote < 0 && keysPressed.countNumberOfSetBits() == 0); // leaving stuck notes!
  56913. deleteAllChildren();
  56914. }
  56915. void MidiKeyboardComponent::setKeyWidth (const float widthInPixels)
  56916. {
  56917. keyWidth = widthInPixels;
  56918. resized();
  56919. }
  56920. void MidiKeyboardComponent::setOrientation (const Orientation newOrientation)
  56921. {
  56922. if (orientation != newOrientation)
  56923. {
  56924. orientation = newOrientation;
  56925. resized();
  56926. }
  56927. }
  56928. void MidiKeyboardComponent::setAvailableRange (const int lowestNote,
  56929. const int highestNote)
  56930. {
  56931. jassert (lowestNote >= 0 && lowestNote <= 127);
  56932. jassert (highestNote >= 0 && highestNote <= 127);
  56933. jassert (lowestNote <= highestNote);
  56934. if (rangeStart != lowestNote || rangeEnd != highestNote)
  56935. {
  56936. rangeStart = jlimit (0, 127, lowestNote);
  56937. rangeEnd = jlimit (0, 127, highestNote);
  56938. firstKey = jlimit (rangeStart, rangeEnd, firstKey);
  56939. resized();
  56940. }
  56941. }
  56942. void MidiKeyboardComponent::setLowestVisibleKey (int noteNumber)
  56943. {
  56944. noteNumber = jlimit (rangeStart, rangeEnd, noteNumber);
  56945. if (noteNumber != firstKey)
  56946. {
  56947. firstKey = noteNumber;
  56948. sendChangeMessage (this);
  56949. resized();
  56950. }
  56951. }
  56952. void MidiKeyboardComponent::setScrollButtonsVisible (const bool canScroll_)
  56953. {
  56954. if (canScroll != canScroll_)
  56955. {
  56956. canScroll = canScroll_;
  56957. resized();
  56958. }
  56959. }
  56960. void MidiKeyboardComponent::colourChanged()
  56961. {
  56962. repaint();
  56963. }
  56964. void MidiKeyboardComponent::setMidiChannel (const int midiChannelNumber)
  56965. {
  56966. jassert (midiChannelNumber > 0 && midiChannelNumber <= 16);
  56967. if (midiChannel != midiChannelNumber)
  56968. {
  56969. resetAnyKeysInUse();
  56970. midiChannel = jlimit (1, 16, midiChannelNumber);
  56971. }
  56972. }
  56973. void MidiKeyboardComponent::setMidiChannelsToDisplay (const int midiChannelMask)
  56974. {
  56975. midiInChannelMask = midiChannelMask;
  56976. triggerAsyncUpdate();
  56977. }
  56978. void MidiKeyboardComponent::setVelocity (const float velocity_)
  56979. {
  56980. velocity = jlimit (0.0f, 1.0f, velocity_);
  56981. }
  56982. void MidiKeyboardComponent::getKeyPosition (int midiNoteNumber, const float keyWidth, int& x, int& w) const
  56983. {
  56984. jassert (midiNoteNumber >= 0 && midiNoteNumber < 128);
  56985. static const float blackNoteWidth = 0.7f;
  56986. static const float notePos[] = { 0.0f, 1 - blackNoteWidth * 0.6f,
  56987. 1.0f, 2 - blackNoteWidth * 0.4f,
  56988. 2.0f, 3.0f, 4 - blackNoteWidth * 0.7f,
  56989. 4.0f, 5 - blackNoteWidth * 0.5f,
  56990. 5.0f, 6 - blackNoteWidth * 0.3f,
  56991. 6.0f };
  56992. static const float widths[] = { 1.0f, blackNoteWidth,
  56993. 1.0f, blackNoteWidth,
  56994. 1.0f, 1.0f, blackNoteWidth,
  56995. 1.0f, blackNoteWidth,
  56996. 1.0f, blackNoteWidth,
  56997. 1.0f };
  56998. const int octave = midiNoteNumber / 12;
  56999. const int note = midiNoteNumber % 12;
  57000. x = roundFloatToInt (octave * 7.0f * keyWidth + notePos [note] * keyWidth);
  57001. w = roundFloatToInt (widths [note] * keyWidth);
  57002. }
  57003. void MidiKeyboardComponent::getKeyPos (int midiNoteNumber, int& x, int& w) const
  57004. {
  57005. getKeyPosition (midiNoteNumber, keyWidth, x, w);
  57006. int rx, rw;
  57007. getKeyPosition (rangeStart, keyWidth, rx, rw);
  57008. x -= xOffset + rx;
  57009. }
  57010. int MidiKeyboardComponent::getKeyStartPosition (const int midiNoteNumber) const
  57011. {
  57012. int x, y;
  57013. getKeyPos (midiNoteNumber, x, y);
  57014. return x;
  57015. }
  57016. static const uint8 whiteNotes[] = { 0, 2, 4, 5, 7, 9, 11 };
  57017. static const uint8 blackNotes[] = { 1, 3, 6, 8, 10 };
  57018. int MidiKeyboardComponent::xyToNote (int x, int y)
  57019. {
  57020. if (! reallyContains (x, y, false))
  57021. return -1;
  57022. if (orientation != horizontalKeyboard)
  57023. {
  57024. swapVariables (x, y);
  57025. if (orientation == verticalKeyboardFacingLeft)
  57026. y = getWidth() - y;
  57027. else
  57028. x = getHeight() - x;
  57029. }
  57030. return remappedXYToNote (x + xOffset, y);
  57031. }
  57032. int MidiKeyboardComponent::remappedXYToNote (int x, int y) const
  57033. {
  57034. if (y < blackNoteLength)
  57035. {
  57036. for (int octaveStart = 12 * (rangeStart / 12); octaveStart <= rangeEnd; octaveStart += 12)
  57037. {
  57038. for (int i = 0; i < 5; ++i)
  57039. {
  57040. const int note = octaveStart + blackNotes [i];
  57041. if (note >= rangeStart && note <= rangeEnd)
  57042. {
  57043. int kx, kw;
  57044. getKeyPos (note, kx, kw);
  57045. kx += xOffset;
  57046. if (x >= kx && x < kx + kw)
  57047. return note;
  57048. }
  57049. }
  57050. }
  57051. }
  57052. for (int octaveStart = 12 * (rangeStart / 12); octaveStart <= rangeEnd; octaveStart += 12)
  57053. {
  57054. for (int i = 0; i < 7; ++i)
  57055. {
  57056. const int note = octaveStart + whiteNotes [i];
  57057. if (note >= rangeStart && note <= rangeEnd)
  57058. {
  57059. int kx, kw;
  57060. getKeyPos (note, kx, kw);
  57061. kx += xOffset;
  57062. if (x >= kx && x < kx + kw)
  57063. return note;
  57064. }
  57065. }
  57066. }
  57067. return -1;
  57068. }
  57069. void MidiKeyboardComponent::repaintNote (const int noteNum)
  57070. {
  57071. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  57072. {
  57073. int x, w;
  57074. getKeyPos (noteNum, x, w);
  57075. if (orientation == horizontalKeyboard)
  57076. repaint (x, 0, w, getHeight());
  57077. else if (orientation == verticalKeyboardFacingLeft)
  57078. repaint (0, x, getWidth(), w);
  57079. else if (orientation == verticalKeyboardFacingRight)
  57080. repaint (0, getHeight() - x - w, getWidth(), w);
  57081. }
  57082. }
  57083. void MidiKeyboardComponent::paint (Graphics& g)
  57084. {
  57085. g.fillAll (Colours::white.overlaidWith (findColour (whiteNoteColourId)));
  57086. const Colour lineColour (findColour (keySeparatorLineColourId));
  57087. const Colour textColour (findColour (textLabelColourId));
  57088. int x, w, octave;
  57089. for (octave = 0; octave < 128; octave += 12)
  57090. {
  57091. for (int white = 0; white < 7; ++white)
  57092. {
  57093. const int noteNum = octave + whiteNotes [white];
  57094. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  57095. {
  57096. getKeyPos (noteNum, x, w);
  57097. if (orientation == horizontalKeyboard)
  57098. drawWhiteNote (noteNum, g, x, 0, w, getHeight(),
  57099. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  57100. noteUnderMouse == noteNum,
  57101. lineColour, textColour);
  57102. else if (orientation == verticalKeyboardFacingLeft)
  57103. drawWhiteNote (noteNum, g, 0, x, getWidth(), w,
  57104. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  57105. noteUnderMouse == noteNum,
  57106. lineColour, textColour);
  57107. else if (orientation == verticalKeyboardFacingRight)
  57108. drawWhiteNote (noteNum, g, 0, getHeight() - x - w, getWidth(), w,
  57109. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  57110. noteUnderMouse == noteNum,
  57111. lineColour, textColour);
  57112. }
  57113. }
  57114. }
  57115. float x1 = 0.0f, y1 = 0.0f, x2 = 0.0f, y2 = 0.0f;
  57116. if (orientation == verticalKeyboardFacingLeft)
  57117. {
  57118. x1 = getWidth() - 1.0f;
  57119. x2 = getWidth() - 5.0f;
  57120. }
  57121. else if (orientation == verticalKeyboardFacingRight)
  57122. x2 = 5.0f;
  57123. else
  57124. y2 = 5.0f;
  57125. GradientBrush gb (Colours::black.withAlpha (0.3f), x1, y1,
  57126. Colours::transparentBlack, x2, y2, false);
  57127. g.setBrush (&gb);
  57128. getKeyPos (rangeEnd, x, w);
  57129. x += w;
  57130. if (orientation == verticalKeyboardFacingLeft)
  57131. g.fillRect (getWidth() - 5, 0, 5, x);
  57132. else if (orientation == verticalKeyboardFacingRight)
  57133. g.fillRect (0, 0, 5, x);
  57134. else
  57135. g.fillRect (0, 0, x, 5);
  57136. g.setColour (lineColour);
  57137. if (orientation == verticalKeyboardFacingLeft)
  57138. g.fillRect (0, 0, 1, x);
  57139. else if (orientation == verticalKeyboardFacingRight)
  57140. g.fillRect (getWidth() - 1, 0, 1, x);
  57141. else
  57142. g.fillRect (0, getHeight() - 1, x, 1);
  57143. const Colour blackNoteColour (findColour (blackNoteColourId));
  57144. for (octave = 0; octave < 128; octave += 12)
  57145. {
  57146. for (int black = 0; black < 5; ++black)
  57147. {
  57148. const int noteNum = octave + blackNotes [black];
  57149. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  57150. {
  57151. getKeyPos (noteNum, x, w);
  57152. if (orientation == horizontalKeyboard)
  57153. drawBlackNote (noteNum, g, x, 0, w, blackNoteLength,
  57154. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  57155. noteUnderMouse == noteNum,
  57156. blackNoteColour);
  57157. else if (orientation == verticalKeyboardFacingLeft)
  57158. drawBlackNote (noteNum, g, getWidth() - blackNoteLength, x, blackNoteLength, w,
  57159. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  57160. noteUnderMouse == noteNum,
  57161. blackNoteColour);
  57162. else if (orientation == verticalKeyboardFacingRight)
  57163. drawBlackNote (noteNum, g, 0, getHeight() - x - w, blackNoteLength, w,
  57164. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  57165. noteUnderMouse == noteNum,
  57166. blackNoteColour);
  57167. }
  57168. }
  57169. }
  57170. }
  57171. void MidiKeyboardComponent::drawWhiteNote (int midiNoteNumber,
  57172. Graphics& g, int x, int y, int w, int h,
  57173. bool isDown, bool isOver,
  57174. const Colour& lineColour,
  57175. const Colour& textColour)
  57176. {
  57177. Colour c (Colours::transparentWhite);
  57178. if (isDown)
  57179. c = findColour (keyDownOverlayColourId);
  57180. if (isOver)
  57181. c = c.overlaidWith (findColour (mouseOverKeyOverlayColourId));
  57182. g.setColour (c);
  57183. g.fillRect (x, y, w, h);
  57184. const String text (getWhiteNoteText (midiNoteNumber));
  57185. if (! text.isEmpty())
  57186. {
  57187. g.setColour (textColour);
  57188. Font f (jmin (12.0f, keyWidth * 0.9f));
  57189. f.setHorizontalScale (0.8f);
  57190. g.setFont (f);
  57191. Justification justification (Justification::centredBottom);
  57192. if (orientation == verticalKeyboardFacingLeft)
  57193. justification = Justification::centredLeft;
  57194. else if (orientation == verticalKeyboardFacingRight)
  57195. justification = Justification::centredRight;
  57196. g.drawFittedText (text, x + 2, y + 2, w - 4, h - 4, justification, 1);
  57197. }
  57198. g.setColour (lineColour);
  57199. if (orientation == horizontalKeyboard)
  57200. g.fillRect (x, y, 1, h);
  57201. else if (orientation == verticalKeyboardFacingLeft)
  57202. g.fillRect (x, y, w, 1);
  57203. else if (orientation == verticalKeyboardFacingRight)
  57204. g.fillRect (x, y + h - 1, w, 1);
  57205. if (midiNoteNumber == rangeEnd)
  57206. {
  57207. if (orientation == horizontalKeyboard)
  57208. g.fillRect (x + w, y, 1, h);
  57209. else if (orientation == verticalKeyboardFacingLeft)
  57210. g.fillRect (x, y + h, w, 1);
  57211. else if (orientation == verticalKeyboardFacingRight)
  57212. g.fillRect (x, y - 1, w, 1);
  57213. }
  57214. }
  57215. void MidiKeyboardComponent::drawBlackNote (int /*midiNoteNumber*/,
  57216. Graphics& g, int x, int y, int w, int h,
  57217. bool isDown, bool isOver,
  57218. const Colour& noteFillColour)
  57219. {
  57220. Colour c (noteFillColour);
  57221. if (isDown)
  57222. c = c.overlaidWith (findColour (keyDownOverlayColourId));
  57223. if (isOver)
  57224. c = c.overlaidWith (findColour (mouseOverKeyOverlayColourId));
  57225. g.setColour (c);
  57226. g.fillRect (x, y, w, h);
  57227. if (isDown)
  57228. {
  57229. g.setColour (noteFillColour);
  57230. g.drawRect (x, y, w, h);
  57231. }
  57232. else
  57233. {
  57234. const int xIndent = jmax (1, jmin (w, h) / 8);
  57235. g.setColour (c.brighter());
  57236. if (orientation == horizontalKeyboard)
  57237. g.fillRect (x + xIndent, y, w - xIndent * 2, 7 * h / 8);
  57238. else if (orientation == verticalKeyboardFacingLeft)
  57239. g.fillRect (x + w / 8, y + xIndent, w - w / 8, h - xIndent * 2);
  57240. else if (orientation == verticalKeyboardFacingRight)
  57241. g.fillRect (x, y + xIndent, 7 * w / 8, h - xIndent * 2);
  57242. }
  57243. }
  57244. void MidiKeyboardComponent::setOctaveForMiddleC (const int octaveNumForMiddleC_) throw()
  57245. {
  57246. octaveNumForMiddleC = octaveNumForMiddleC_;
  57247. repaint();
  57248. }
  57249. const String MidiKeyboardComponent::getWhiteNoteText (const int midiNoteNumber)
  57250. {
  57251. if (keyWidth > 14.0f && midiNoteNumber % 12 == 0)
  57252. return MidiMessage::getMidiNoteName (midiNoteNumber, true, true, octaveNumForMiddleC);
  57253. return String::empty;
  57254. }
  57255. void MidiKeyboardComponent::drawUpDownButton (Graphics& g, int w, int h,
  57256. const bool isMouseOver,
  57257. const bool isButtonDown,
  57258. const bool movesOctavesUp)
  57259. {
  57260. g.fillAll (findColour (upDownButtonBackgroundColourId));
  57261. float angle;
  57262. if (orientation == MidiKeyboardComponent::horizontalKeyboard)
  57263. angle = movesOctavesUp ? 0.0f : 0.5f;
  57264. else if (orientation == MidiKeyboardComponent::verticalKeyboardFacingLeft)
  57265. angle = movesOctavesUp ? 0.25f : 0.75f;
  57266. else
  57267. angle = movesOctavesUp ? 0.75f : 0.25f;
  57268. Path path;
  57269. path.lineTo (0.0f, 1.0f);
  57270. path.lineTo (1.0f, 0.5f);
  57271. path.closeSubPath();
  57272. path.applyTransform (AffineTransform::rotation (float_Pi * 2.0f * angle, 0.5f, 0.5f));
  57273. g.setColour (findColour (upDownButtonArrowColourId)
  57274. .withAlpha (isButtonDown ? 1.0f : (isMouseOver ? 0.6f : 0.4f)));
  57275. g.fillPath (path, path.getTransformToScaleToFit (1.0f, 1.0f,
  57276. w - 2.0f,
  57277. h - 2.0f,
  57278. true));
  57279. }
  57280. void MidiKeyboardComponent::resized()
  57281. {
  57282. int w = getWidth();
  57283. int h = getHeight();
  57284. if (w > 0 && h > 0)
  57285. {
  57286. if (orientation != horizontalKeyboard)
  57287. swapVariables (w, h);
  57288. blackNoteLength = roundFloatToInt (h * 0.7f);
  57289. int kx2, kw2;
  57290. getKeyPos (rangeEnd, kx2, kw2);
  57291. kx2 += kw2;
  57292. if (firstKey != rangeStart)
  57293. {
  57294. int kx1, kw1;
  57295. getKeyPos (rangeStart, kx1, kw1);
  57296. if (kx2 - kx1 <= w)
  57297. {
  57298. firstKey = rangeStart;
  57299. sendChangeMessage (this);
  57300. repaint();
  57301. }
  57302. }
  57303. const bool showScrollButtons = canScroll && (firstKey > rangeStart || kx2 > w + xOffset * 2);
  57304. scrollDown->setVisible (showScrollButtons);
  57305. scrollUp->setVisible (showScrollButtons);
  57306. xOffset = 0;
  57307. if (showScrollButtons)
  57308. {
  57309. const int scrollButtonW = jmin (12, w / 2);
  57310. if (orientation == horizontalKeyboard)
  57311. {
  57312. scrollDown->setBounds (0, 0, scrollButtonW, getHeight());
  57313. scrollUp->setBounds (getWidth() - scrollButtonW, 0, scrollButtonW, getHeight());
  57314. }
  57315. else if (orientation == verticalKeyboardFacingLeft)
  57316. {
  57317. scrollDown->setBounds (0, 0, getWidth(), scrollButtonW);
  57318. scrollUp->setBounds (0, getHeight() - scrollButtonW, getWidth(), scrollButtonW);
  57319. }
  57320. else if (orientation == verticalKeyboardFacingRight)
  57321. {
  57322. scrollDown->setBounds (0, getHeight() - scrollButtonW, getWidth(), scrollButtonW);
  57323. scrollUp->setBounds (0, 0, getWidth(), scrollButtonW);
  57324. }
  57325. int endOfLastKey, kw;
  57326. getKeyPos (rangeEnd, endOfLastKey, kw);
  57327. endOfLastKey += kw;
  57328. const int spaceAvailable = w - scrollButtonW * 2;
  57329. const int lastStartKey = remappedXYToNote (endOfLastKey - spaceAvailable, 0) + 1;
  57330. if (lastStartKey >= 0 && firstKey > lastStartKey)
  57331. {
  57332. firstKey = jlimit (rangeStart, rangeEnd, lastStartKey);
  57333. sendChangeMessage (this);
  57334. }
  57335. int newOffset = 0;
  57336. getKeyPos (firstKey, newOffset, kw);
  57337. xOffset = newOffset - scrollButtonW;
  57338. }
  57339. else
  57340. {
  57341. firstKey = rangeStart;
  57342. }
  57343. timerCallback();
  57344. repaint();
  57345. }
  57346. }
  57347. void MidiKeyboardComponent::handleNoteOn (MidiKeyboardState*, int /*midiChannel*/, int /*midiNoteNumber*/, float /*velocity*/)
  57348. {
  57349. triggerAsyncUpdate();
  57350. }
  57351. void MidiKeyboardComponent::handleNoteOff (MidiKeyboardState*, int /*midiChannel*/, int /*midiNoteNumber*/)
  57352. {
  57353. triggerAsyncUpdate();
  57354. }
  57355. void MidiKeyboardComponent::handleAsyncUpdate()
  57356. {
  57357. for (int i = rangeStart; i <= rangeEnd; ++i)
  57358. {
  57359. if (keysCurrentlyDrawnDown[i] != state.isNoteOnForChannels (midiInChannelMask, i))
  57360. {
  57361. keysCurrentlyDrawnDown.setBit (i, state.isNoteOnForChannels (midiInChannelMask, i));
  57362. repaintNote (i);
  57363. }
  57364. }
  57365. }
  57366. void MidiKeyboardComponent::resetAnyKeysInUse()
  57367. {
  57368. if (keysPressed.countNumberOfSetBits() > 0 || mouseDownNote > 0)
  57369. {
  57370. state.allNotesOff (midiChannel);
  57371. keysPressed.clear();
  57372. mouseDownNote = -1;
  57373. }
  57374. }
  57375. void MidiKeyboardComponent::updateNoteUnderMouse (int x, int y)
  57376. {
  57377. const int newNote = (mouseDragging || isMouseOver())
  57378. ? xyToNote (x, y) : -1;
  57379. if (noteUnderMouse != newNote)
  57380. {
  57381. if (mouseDownNote >= 0)
  57382. {
  57383. state.noteOff (midiChannel, mouseDownNote);
  57384. mouseDownNote = -1;
  57385. }
  57386. if (mouseDragging && newNote >= 0)
  57387. {
  57388. state.noteOn (midiChannel, newNote, velocity);
  57389. mouseDownNote = newNote;
  57390. }
  57391. repaintNote (noteUnderMouse);
  57392. noteUnderMouse = newNote;
  57393. repaintNote (noteUnderMouse);
  57394. }
  57395. else if (mouseDownNote >= 0 && ! mouseDragging)
  57396. {
  57397. state.noteOff (midiChannel, mouseDownNote);
  57398. mouseDownNote = -1;
  57399. }
  57400. }
  57401. void MidiKeyboardComponent::mouseMove (const MouseEvent& e)
  57402. {
  57403. updateNoteUnderMouse (e.x, e.y);
  57404. stopTimer();
  57405. }
  57406. void MidiKeyboardComponent::mouseDrag (const MouseEvent& e)
  57407. {
  57408. const int newNote = xyToNote (e.x, e.y);
  57409. if (newNote >= 0)
  57410. mouseDraggedToKey (newNote, e);
  57411. updateNoteUnderMouse (e.x, e.y);
  57412. }
  57413. bool MidiKeyboardComponent::mouseDownOnKey (int /*midiNoteNumber*/, const MouseEvent&)
  57414. {
  57415. return true;
  57416. }
  57417. void MidiKeyboardComponent::mouseDraggedToKey (int /*midiNoteNumber*/, const MouseEvent&)
  57418. {
  57419. }
  57420. void MidiKeyboardComponent::mouseDown (const MouseEvent& e)
  57421. {
  57422. const int newNote = xyToNote (e.x, e.y);
  57423. mouseDragging = false;
  57424. if (newNote >= 0 && mouseDownOnKey (newNote, e))
  57425. {
  57426. repaintNote (noteUnderMouse);
  57427. noteUnderMouse = -1;
  57428. mouseDragging = true;
  57429. updateNoteUnderMouse (e.x, e.y);
  57430. startTimer (500);
  57431. }
  57432. }
  57433. void MidiKeyboardComponent::mouseUp (const MouseEvent& e)
  57434. {
  57435. mouseDragging = false;
  57436. updateNoteUnderMouse (e.x, e.y);
  57437. stopTimer();
  57438. }
  57439. void MidiKeyboardComponent::mouseEnter (const MouseEvent& e)
  57440. {
  57441. updateNoteUnderMouse (e.x, e.y);
  57442. }
  57443. void MidiKeyboardComponent::mouseExit (const MouseEvent& e)
  57444. {
  57445. updateNoteUnderMouse (e.x, e.y);
  57446. }
  57447. void MidiKeyboardComponent::mouseWheelMove (const MouseEvent&, float ix, float iy)
  57448. {
  57449. setLowestVisibleKey (getLowestVisibleKey() + roundFloatToInt ((ix != 0 ? ix : iy) * 5.0f));
  57450. }
  57451. void MidiKeyboardComponent::timerCallback()
  57452. {
  57453. int mx, my;
  57454. getMouseXYRelative (mx, my);
  57455. updateNoteUnderMouse (mx, my);
  57456. }
  57457. void MidiKeyboardComponent::clearKeyMappings()
  57458. {
  57459. resetAnyKeysInUse();
  57460. keyPressNotes.clear();
  57461. keyPresses.clear();
  57462. }
  57463. void MidiKeyboardComponent::setKeyPressForNote (const KeyPress& key,
  57464. const int midiNoteOffsetFromC)
  57465. {
  57466. removeKeyPressForNote (midiNoteOffsetFromC);
  57467. keyPressNotes.add (midiNoteOffsetFromC);
  57468. keyPresses.add (key);
  57469. }
  57470. void MidiKeyboardComponent::removeKeyPressForNote (const int midiNoteOffsetFromC)
  57471. {
  57472. for (int i = keyPressNotes.size(); --i >= 0;)
  57473. {
  57474. if (keyPressNotes.getUnchecked (i) == midiNoteOffsetFromC)
  57475. {
  57476. keyPressNotes.remove (i);
  57477. keyPresses.remove (i);
  57478. }
  57479. }
  57480. }
  57481. void MidiKeyboardComponent::setKeyPressBaseOctave (const int newOctaveNumber)
  57482. {
  57483. jassert (newOctaveNumber >= 0 && newOctaveNumber <= 10);
  57484. keyMappingOctave = newOctaveNumber;
  57485. }
  57486. bool MidiKeyboardComponent::keyStateChanged (const bool /*isKeyDown*/)
  57487. {
  57488. bool keyPressUsed = false;
  57489. for (int i = keyPresses.size(); --i >= 0;)
  57490. {
  57491. const int note = 12 * keyMappingOctave + keyPressNotes.getUnchecked (i);
  57492. if (keyPresses.getReference(i).isCurrentlyDown())
  57493. {
  57494. if (! keysPressed [note])
  57495. {
  57496. keysPressed.setBit (note);
  57497. state.noteOn (midiChannel, note, velocity);
  57498. keyPressUsed = true;
  57499. }
  57500. }
  57501. else
  57502. {
  57503. if (keysPressed [note])
  57504. {
  57505. keysPressed.clearBit (note);
  57506. state.noteOff (midiChannel, note);
  57507. keyPressUsed = true;
  57508. }
  57509. }
  57510. }
  57511. return keyPressUsed;
  57512. }
  57513. void MidiKeyboardComponent::focusLost (FocusChangeType)
  57514. {
  57515. resetAnyKeysInUse();
  57516. }
  57517. END_JUCE_NAMESPACE
  57518. /********* End of inlined file: juce_MidiKeyboardComponent.cpp *********/
  57519. /********* Start of inlined file: juce_OpenGLComponent.cpp *********/
  57520. #if JUCE_OPENGL
  57521. BEGIN_JUCE_NAMESPACE
  57522. extern void juce_glViewport (const int w, const int h);
  57523. OpenGLPixelFormat::OpenGLPixelFormat (const int bitsPerRGBComponent,
  57524. const int alphaBits_,
  57525. const int depthBufferBits_,
  57526. const int stencilBufferBits_) throw()
  57527. : redBits (bitsPerRGBComponent),
  57528. greenBits (bitsPerRGBComponent),
  57529. blueBits (bitsPerRGBComponent),
  57530. alphaBits (alphaBits_),
  57531. depthBufferBits (depthBufferBits_),
  57532. stencilBufferBits (stencilBufferBits_),
  57533. accumulationBufferRedBits (0),
  57534. accumulationBufferGreenBits (0),
  57535. accumulationBufferBlueBits (0),
  57536. accumulationBufferAlphaBits (0),
  57537. fullSceneAntiAliasingNumSamples (0)
  57538. {
  57539. }
  57540. bool OpenGLPixelFormat::operator== (const OpenGLPixelFormat& other) const throw()
  57541. {
  57542. return memcmp (this, &other, sizeof (other)) == 0;
  57543. }
  57544. static VoidArray knownContexts;
  57545. OpenGLContext::OpenGLContext() throw()
  57546. {
  57547. knownContexts.add (this);
  57548. }
  57549. OpenGLContext::~OpenGLContext()
  57550. {
  57551. knownContexts.removeValue (this);
  57552. }
  57553. OpenGLContext* OpenGLContext::getCurrentContext()
  57554. {
  57555. for (int i = knownContexts.size(); --i >= 0;)
  57556. {
  57557. OpenGLContext* const oglc = (OpenGLContext*) knownContexts.getUnchecked(i);
  57558. if (oglc->isActive())
  57559. return oglc;
  57560. }
  57561. return 0;
  57562. }
  57563. class OpenGLComponentWatcher : public ComponentMovementWatcher
  57564. {
  57565. public:
  57566. OpenGLComponentWatcher (OpenGLComponent* const owner_)
  57567. : ComponentMovementWatcher (owner_),
  57568. owner (owner_),
  57569. wasShowing (false)
  57570. {
  57571. }
  57572. ~OpenGLComponentWatcher() {}
  57573. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  57574. {
  57575. owner->updateContextPosition();
  57576. }
  57577. void componentPeerChanged()
  57578. {
  57579. const ScopedLock sl (owner->getContextLock());
  57580. owner->deleteContext();
  57581. }
  57582. void componentVisibilityChanged (Component&)
  57583. {
  57584. const bool isShowingNow = owner->isShowing();
  57585. if (wasShowing != isShowingNow)
  57586. {
  57587. wasShowing = isShowingNow;
  57588. owner->updateContextPosition();
  57589. }
  57590. }
  57591. juce_UseDebuggingNewOperator
  57592. private:
  57593. OpenGLComponent* const owner;
  57594. bool wasShowing;
  57595. };
  57596. OpenGLComponent::OpenGLComponent()
  57597. : context (0),
  57598. contextToShareListsWith (0),
  57599. needToUpdateViewport (true)
  57600. {
  57601. setOpaque (true);
  57602. componentWatcher = new OpenGLComponentWatcher (this);
  57603. }
  57604. OpenGLComponent::~OpenGLComponent()
  57605. {
  57606. deleteContext();
  57607. delete componentWatcher;
  57608. }
  57609. void OpenGLComponent::deleteContext()
  57610. {
  57611. const ScopedLock sl (contextLock);
  57612. deleteAndZero (context);
  57613. }
  57614. void OpenGLComponent::updateContextPosition()
  57615. {
  57616. needToUpdateViewport = true;
  57617. if (getWidth() > 0 && getHeight() > 0)
  57618. {
  57619. Component* const topComp = getTopLevelComponent();
  57620. if (topComp->getPeer() != 0)
  57621. {
  57622. const ScopedLock sl (contextLock);
  57623. if (context != 0)
  57624. context->updateWindowPosition (getScreenX() - topComp->getScreenX(),
  57625. getScreenY() - topComp->getScreenY(),
  57626. getWidth(),
  57627. getHeight(),
  57628. topComp->getHeight());
  57629. }
  57630. }
  57631. }
  57632. const OpenGLPixelFormat OpenGLComponent::getPixelFormat() const
  57633. {
  57634. OpenGLPixelFormat pf;
  57635. const ScopedLock sl (contextLock);
  57636. if (context != 0)
  57637. pf = context->getPixelFormat();
  57638. return pf;
  57639. }
  57640. void OpenGLComponent::setPixelFormat (const OpenGLPixelFormat& formatToUse)
  57641. {
  57642. if (! (preferredPixelFormat == formatToUse))
  57643. {
  57644. const ScopedLock sl (contextLock);
  57645. deleteContext();
  57646. preferredPixelFormat = formatToUse;
  57647. }
  57648. }
  57649. void OpenGLComponent::shareWith (OpenGLContext* context)
  57650. {
  57651. if (contextToShareListsWith != context)
  57652. {
  57653. const ScopedLock sl (contextLock);
  57654. deleteContext();
  57655. contextToShareListsWith = context;
  57656. }
  57657. }
  57658. bool OpenGLComponent::makeCurrentContextActive()
  57659. {
  57660. if (context == 0)
  57661. {
  57662. const ScopedLock sl (contextLock);
  57663. if (isShowing() && getTopLevelComponent()->getPeer() != 0)
  57664. {
  57665. context = OpenGLContext::createContextForWindow (this,
  57666. preferredPixelFormat,
  57667. contextToShareListsWith);
  57668. if (context != 0)
  57669. {
  57670. updateContextPosition();
  57671. if (context->makeActive())
  57672. newOpenGLContextCreated();
  57673. }
  57674. }
  57675. }
  57676. return context != 0 && context->makeActive();
  57677. }
  57678. void OpenGLComponent::makeCurrentContextInactive()
  57679. {
  57680. if (context != 0)
  57681. context->makeInactive();
  57682. }
  57683. bool OpenGLComponent::isActiveContext() const throw()
  57684. {
  57685. return context != 0 && context->isActive();
  57686. }
  57687. void OpenGLComponent::swapBuffers()
  57688. {
  57689. if (context != 0)
  57690. context->swapBuffers();
  57691. }
  57692. void OpenGLComponent::paint (Graphics&)
  57693. {
  57694. if (renderAndSwapBuffers())
  57695. {
  57696. ComponentPeer* const peer = getPeer();
  57697. if (peer != 0)
  57698. {
  57699. peer->addMaskedRegion (getScreenX() - peer->getScreenX(),
  57700. getScreenY() - peer->getScreenY(),
  57701. getWidth(), getHeight());
  57702. }
  57703. }
  57704. }
  57705. bool OpenGLComponent::renderAndSwapBuffers()
  57706. {
  57707. const ScopedLock sl (contextLock);
  57708. if (! makeCurrentContextActive())
  57709. return false;
  57710. if (needToUpdateViewport)
  57711. {
  57712. needToUpdateViewport = false;
  57713. juce_glViewport (getWidth(), getHeight());
  57714. }
  57715. renderOpenGL();
  57716. swapBuffers();
  57717. return true;
  57718. }
  57719. void OpenGLComponent::internalRepaint (int x, int y, int w, int h)
  57720. {
  57721. Component::internalRepaint (x, y, w, h);
  57722. if (context != 0)
  57723. context->repaint();
  57724. }
  57725. END_JUCE_NAMESPACE
  57726. #endif
  57727. /********* End of inlined file: juce_OpenGLComponent.cpp *********/
  57728. /********* Start of inlined file: juce_PreferencesPanel.cpp *********/
  57729. BEGIN_JUCE_NAMESPACE
  57730. PreferencesPanel::PreferencesPanel()
  57731. : currentPage (0),
  57732. buttonSize (70)
  57733. {
  57734. }
  57735. PreferencesPanel::~PreferencesPanel()
  57736. {
  57737. deleteAllChildren();
  57738. }
  57739. void PreferencesPanel::addSettingsPage (const String& title,
  57740. const Drawable* icon,
  57741. const Drawable* overIcon,
  57742. const Drawable* downIcon)
  57743. {
  57744. DrawableButton* button = new DrawableButton (title, DrawableButton::ImageAboveTextLabel);
  57745. button->setImages (icon, overIcon, downIcon);
  57746. button->setRadioGroupId (1);
  57747. button->addButtonListener (this);
  57748. button->setClickingTogglesState (true);
  57749. button->setWantsKeyboardFocus (false);
  57750. addAndMakeVisible (button);
  57751. resized();
  57752. if (currentPage == 0)
  57753. setCurrentPage (title);
  57754. }
  57755. void PreferencesPanel::addSettingsPage (const String& title,
  57756. const char* imageData,
  57757. const int imageDataSize)
  57758. {
  57759. DrawableImage icon, iconOver, iconDown;
  57760. icon.setImage (ImageCache::getFromMemory (imageData, imageDataSize), true);
  57761. iconOver.setImage (ImageCache::getFromMemory (imageData, imageDataSize), true);
  57762. iconOver.setOverlayColour (Colours::black.withAlpha (0.12f));
  57763. iconDown.setImage (ImageCache::getFromMemory (imageData, imageDataSize), true);
  57764. iconDown.setOverlayColour (Colours::black.withAlpha (0.25f));
  57765. addSettingsPage (title, &icon, &iconOver, &iconDown);
  57766. }
  57767. class PrefsDialogWindow : public DialogWindow
  57768. {
  57769. public:
  57770. PrefsDialogWindow (const String& dialogtitle,
  57771. const Colour& backgroundColour)
  57772. : DialogWindow (dialogtitle, backgroundColour, true)
  57773. {
  57774. }
  57775. ~PrefsDialogWindow()
  57776. {
  57777. }
  57778. void closeButtonPressed()
  57779. {
  57780. exitModalState (0);
  57781. }
  57782. private:
  57783. PrefsDialogWindow (const PrefsDialogWindow&);
  57784. const PrefsDialogWindow& operator= (const PrefsDialogWindow&);
  57785. };
  57786. void PreferencesPanel::showInDialogBox (const String& dialogtitle,
  57787. int dialogWidth,
  57788. int dialogHeight,
  57789. const Colour& backgroundColour)
  57790. {
  57791. setSize (dialogWidth, dialogHeight);
  57792. PrefsDialogWindow dw (dialogtitle, backgroundColour);
  57793. dw.setContentComponent (this, true, true);
  57794. dw.centreAroundComponent (0, dw.getWidth(), dw.getHeight());
  57795. dw.runModalLoop();
  57796. dw.setContentComponent (0, false, false);
  57797. }
  57798. void PreferencesPanel::resized()
  57799. {
  57800. int x = 0;
  57801. for (int i = 0; i < getNumChildComponents(); ++i)
  57802. {
  57803. Component* c = getChildComponent (i);
  57804. if (dynamic_cast <DrawableButton*> (c) == 0)
  57805. {
  57806. c->setBounds (0, buttonSize + 5, getWidth(), getHeight() - buttonSize - 5);
  57807. }
  57808. else
  57809. {
  57810. c->setBounds (x, 0, buttonSize, buttonSize);
  57811. x += buttonSize;
  57812. }
  57813. }
  57814. }
  57815. void PreferencesPanel::paint (Graphics& g)
  57816. {
  57817. g.setColour (Colours::grey);
  57818. g.fillRect (0, buttonSize + 2, getWidth(), 1);
  57819. }
  57820. void PreferencesPanel::setCurrentPage (const String& pageName)
  57821. {
  57822. if (currentPageName != pageName)
  57823. {
  57824. currentPageName = pageName;
  57825. deleteAndZero (currentPage);
  57826. currentPage = createComponentForPage (pageName);
  57827. if (currentPage != 0)
  57828. {
  57829. addAndMakeVisible (currentPage);
  57830. currentPage->toBack();
  57831. resized();
  57832. }
  57833. for (int i = 0; i < getNumChildComponents(); ++i)
  57834. {
  57835. DrawableButton* db = dynamic_cast <DrawableButton*> (getChildComponent (i));
  57836. if (db != 0 && db->getName() == pageName)
  57837. {
  57838. db->setToggleState (true, false);
  57839. break;
  57840. }
  57841. }
  57842. }
  57843. }
  57844. void PreferencesPanel::buttonClicked (Button*)
  57845. {
  57846. for (int i = 0; i < getNumChildComponents(); ++i)
  57847. {
  57848. DrawableButton* db = dynamic_cast <DrawableButton*> (getChildComponent (i));
  57849. if (db != 0 && db->getToggleState())
  57850. {
  57851. setCurrentPage (db->getName());
  57852. break;
  57853. }
  57854. }
  57855. }
  57856. END_JUCE_NAMESPACE
  57857. /********* End of inlined file: juce_PreferencesPanel.cpp *********/
  57858. /********* Start of inlined file: juce_SystemTrayIconComponent.cpp *********/
  57859. #if JUCE_WIN32 || JUCE_LINUX
  57860. BEGIN_JUCE_NAMESPACE
  57861. SystemTrayIconComponent::SystemTrayIconComponent()
  57862. {
  57863. addToDesktop (0);
  57864. }
  57865. SystemTrayIconComponent::~SystemTrayIconComponent()
  57866. {
  57867. }
  57868. END_JUCE_NAMESPACE
  57869. #endif
  57870. /********* End of inlined file: juce_SystemTrayIconComponent.cpp *********/
  57871. /********* Start of inlined file: juce_AlertWindow.cpp *********/
  57872. BEGIN_JUCE_NAMESPACE
  57873. static const int titleH = 24;
  57874. static const int iconWidth = 80;
  57875. class AlertWindowTextEditor : public TextEditor
  57876. {
  57877. public:
  57878. #if JUCE_LINUX
  57879. #define PASSWORD_CHAR 0x2022
  57880. #else
  57881. #define PASSWORD_CHAR 0x25cf
  57882. #endif
  57883. AlertWindowTextEditor (const String& name,
  57884. const bool isPasswordBox)
  57885. : TextEditor (name,
  57886. isPasswordBox ? (const tchar) PASSWORD_CHAR
  57887. : (const tchar) 0)
  57888. {
  57889. setSelectAllWhenFocused (true);
  57890. }
  57891. ~AlertWindowTextEditor()
  57892. {
  57893. }
  57894. void returnPressed()
  57895. {
  57896. // pass these up the component hierarchy to be trigger the buttons
  57897. getParentComponent()->keyPressed (KeyPress (KeyPress::returnKey, 0, T('\n')));
  57898. }
  57899. void escapePressed()
  57900. {
  57901. // pass these up the component hierarchy to be trigger the buttons
  57902. getParentComponent()->keyPressed (KeyPress (KeyPress::escapeKey, 0, 0));
  57903. }
  57904. private:
  57905. AlertWindowTextEditor (const AlertWindowTextEditor&);
  57906. const AlertWindowTextEditor& operator= (const AlertWindowTextEditor&);
  57907. };
  57908. AlertWindow::AlertWindow (const String& title,
  57909. const String& message,
  57910. AlertIconType iconType,
  57911. Component* associatedComponent_)
  57912. : TopLevelWindow (title, true),
  57913. alertIconType (iconType),
  57914. associatedComponent (associatedComponent_)
  57915. {
  57916. if (message.isEmpty())
  57917. text = T(" "); // to force an update if the message is empty
  57918. setMessage (message);
  57919. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  57920. {
  57921. Component* const c = Desktop::getInstance().getComponent (i);
  57922. if (c != 0 && c->isAlwaysOnTop() && c->isShowing())
  57923. {
  57924. setAlwaysOnTop (true);
  57925. break;
  57926. }
  57927. }
  57928. if (JUCEApplication::getInstance() == 0)
  57929. setAlwaysOnTop (true); // for a plugin, make it always-on-top because the host windows are often top-level
  57930. lookAndFeelChanged();
  57931. constrainer.setMinimumOnscreenAmounts (0x10000, 0x10000, 0x10000, 0x10000);
  57932. }
  57933. AlertWindow::~AlertWindow()
  57934. {
  57935. for (int i = customComps.size(); --i >= 0;)
  57936. removeChildComponent ((Component*) customComps[i]);
  57937. deleteAllChildren();
  57938. }
  57939. void AlertWindow::userTriedToCloseWindow()
  57940. {
  57941. exitModalState (0);
  57942. }
  57943. void AlertWindow::setMessage (const String& message)
  57944. {
  57945. const String newMessage (message.substring (0, 2048));
  57946. if (text != newMessage)
  57947. {
  57948. text = newMessage;
  57949. font.setHeight (15.0f);
  57950. Font titleFont (font.getHeight() * 1.1f, Font::bold);
  57951. textLayout.setText (getName() + T("\n\n"), titleFont);
  57952. textLayout.appendText (text, font);
  57953. updateLayout (true);
  57954. repaint();
  57955. }
  57956. }
  57957. void AlertWindow::buttonClicked (Button* button)
  57958. {
  57959. for (int i = 0; i < buttons.size(); i++)
  57960. {
  57961. TextButton* const c = (TextButton*) buttons[i];
  57962. if (button->getName() == c->getName())
  57963. {
  57964. if (c->getParentComponent() != 0)
  57965. c->getParentComponent()->exitModalState (c->getCommandID());
  57966. break;
  57967. }
  57968. }
  57969. }
  57970. void AlertWindow::addButton (const String& name,
  57971. const int returnValue,
  57972. const KeyPress& shortcutKey1,
  57973. const KeyPress& shortcutKey2)
  57974. {
  57975. TextButton* const b = new TextButton (name, String::empty);
  57976. b->setWantsKeyboardFocus (true);
  57977. b->setMouseClickGrabsKeyboardFocus (false);
  57978. b->setCommandToTrigger (0, returnValue, false);
  57979. b->addShortcut (shortcutKey1);
  57980. b->addShortcut (shortcutKey2);
  57981. b->addButtonListener (this);
  57982. b->changeWidthToFitText (getLookAndFeel().getAlertWindowButtonHeight());
  57983. addAndMakeVisible (b, 0);
  57984. buttons.add (b);
  57985. updateLayout (false);
  57986. }
  57987. int AlertWindow::getNumButtons() const
  57988. {
  57989. return buttons.size();
  57990. }
  57991. void AlertWindow::addTextEditor (const String& name,
  57992. const String& initialContents,
  57993. const String& onScreenLabel,
  57994. const bool isPasswordBox)
  57995. {
  57996. AlertWindowTextEditor* const tc = new AlertWindowTextEditor (name, isPasswordBox);
  57997. tc->setColour (TextEditor::outlineColourId, findColour (ComboBox::outlineColourId));
  57998. tc->setFont (font);
  57999. tc->setText (initialContents);
  58000. tc->setCaretPosition (initialContents.length());
  58001. addAndMakeVisible (tc);
  58002. textBoxes.add (tc);
  58003. allComps.add (tc);
  58004. textboxNames.add (onScreenLabel);
  58005. updateLayout (false);
  58006. }
  58007. const String AlertWindow::getTextEditorContents (const String& nameOfTextEditor) const
  58008. {
  58009. for (int i = textBoxes.size(); --i >= 0;)
  58010. if (((TextEditor*)textBoxes[i])->getName() == nameOfTextEditor)
  58011. return ((TextEditor*)textBoxes[i])->getText();
  58012. return String::empty;
  58013. }
  58014. void AlertWindow::addComboBox (const String& name,
  58015. const StringArray& items,
  58016. const String& onScreenLabel)
  58017. {
  58018. ComboBox* const cb = new ComboBox (name);
  58019. for (int i = 0; i < items.size(); ++i)
  58020. cb->addItem (items[i], i + 1);
  58021. addAndMakeVisible (cb);
  58022. cb->setSelectedItemIndex (0);
  58023. comboBoxes.add (cb);
  58024. allComps.add (cb);
  58025. comboBoxNames.add (onScreenLabel);
  58026. updateLayout (false);
  58027. }
  58028. ComboBox* AlertWindow::getComboBoxComponent (const String& nameOfList) const
  58029. {
  58030. for (int i = comboBoxes.size(); --i >= 0;)
  58031. if (((ComboBox*) comboBoxes[i])->getName() == nameOfList)
  58032. return (ComboBox*) comboBoxes[i];
  58033. return 0;
  58034. }
  58035. class AlertTextComp : public TextEditor
  58036. {
  58037. AlertTextComp (const AlertTextComp&);
  58038. const AlertTextComp& operator= (const AlertTextComp&);
  58039. int bestWidth;
  58040. public:
  58041. AlertTextComp (const String& message,
  58042. const Font& font)
  58043. {
  58044. setReadOnly (true);
  58045. setMultiLine (true, true);
  58046. setCaretVisible (false);
  58047. setScrollbarsShown (true);
  58048. lookAndFeelChanged();
  58049. setWantsKeyboardFocus (false);
  58050. setFont (font);
  58051. setText (message, false);
  58052. bestWidth = 2 * (int) sqrt (font.getHeight() * font.getStringWidth (message));
  58053. setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  58054. setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  58055. setColour (TextEditor::shadowColourId, Colours::transparentBlack);
  58056. }
  58057. ~AlertTextComp()
  58058. {
  58059. }
  58060. int getPreferredWidth() const throw() { return bestWidth; }
  58061. void updateLayout (const int width)
  58062. {
  58063. TextLayout text;
  58064. text.appendText (getText(), getFont());
  58065. text.layout (width - 8, Justification::topLeft, true);
  58066. setSize (width, jmin (width, text.getHeight() + (int) getFont().getHeight()));
  58067. }
  58068. };
  58069. void AlertWindow::addTextBlock (const String& text)
  58070. {
  58071. AlertTextComp* const c = new AlertTextComp (text, font);
  58072. textBlocks.add (c);
  58073. allComps.add (c);
  58074. addAndMakeVisible (c);
  58075. updateLayout (false);
  58076. }
  58077. void AlertWindow::addProgressBarComponent (double& progressValue)
  58078. {
  58079. ProgressBar* const pb = new ProgressBar (progressValue);
  58080. progressBars.add (pb);
  58081. allComps.add (pb);
  58082. addAndMakeVisible (pb);
  58083. updateLayout (false);
  58084. }
  58085. void AlertWindow::addCustomComponent (Component* const component)
  58086. {
  58087. customComps.add (component);
  58088. allComps.add (component);
  58089. addAndMakeVisible (component);
  58090. updateLayout (false);
  58091. }
  58092. int AlertWindow::getNumCustomComponents() const
  58093. {
  58094. return customComps.size();
  58095. }
  58096. Component* AlertWindow::getCustomComponent (const int index) const
  58097. {
  58098. return (Component*) customComps [index];
  58099. }
  58100. Component* AlertWindow::removeCustomComponent (const int index)
  58101. {
  58102. Component* const c = getCustomComponent (index);
  58103. if (c != 0)
  58104. {
  58105. customComps.removeValue (c);
  58106. allComps.removeValue (c);
  58107. removeChildComponent (c);
  58108. updateLayout (false);
  58109. }
  58110. return c;
  58111. }
  58112. void AlertWindow::paint (Graphics& g)
  58113. {
  58114. getLookAndFeel().drawAlertBox (g, *this, textArea, textLayout);
  58115. g.setColour (findColour (textColourId));
  58116. g.setFont (getLookAndFeel().getAlertWindowFont());
  58117. int i;
  58118. for (i = textBoxes.size(); --i >= 0;)
  58119. {
  58120. if (textboxNames[i].isNotEmpty())
  58121. {
  58122. const TextEditor* const te = (TextEditor*) textBoxes[i];
  58123. g.drawFittedText (textboxNames[i],
  58124. te->getX(), te->getY() - 14,
  58125. te->getWidth(), 14,
  58126. Justification::centredLeft, 1);
  58127. }
  58128. }
  58129. for (i = comboBoxNames.size(); --i >= 0;)
  58130. {
  58131. if (comboBoxNames[i].isNotEmpty())
  58132. {
  58133. const ComboBox* const cb = (ComboBox*) comboBoxes[i];
  58134. g.drawFittedText (comboBoxNames[i],
  58135. cb->getX(), cb->getY() - 14,
  58136. cb->getWidth(), 14,
  58137. Justification::centredLeft, 1);
  58138. }
  58139. }
  58140. }
  58141. void AlertWindow::updateLayout (const bool onlyIncreaseSize)
  58142. {
  58143. const int wid = jmax (font.getStringWidth (text),
  58144. font.getStringWidth (getName()));
  58145. const int sw = (int) sqrt (font.getHeight() * wid);
  58146. int w = jmin (300 + sw * 2, (int) (getParentWidth() * 0.7f));
  58147. const int edgeGap = 10;
  58148. int iconSpace;
  58149. if (alertIconType == NoIcon)
  58150. {
  58151. textLayout.layout (w, Justification::horizontallyCentred, true);
  58152. iconSpace = 0;
  58153. }
  58154. else
  58155. {
  58156. textLayout.layout (w, Justification::left, true);
  58157. iconSpace = iconWidth;
  58158. }
  58159. w = jmax (350, textLayout.getWidth() + iconSpace + edgeGap * 4);
  58160. w = jmin (w, (int) (getParentWidth() * 0.7f));
  58161. const int textLayoutH = textLayout.getHeight();
  58162. const int textBottom = 16 + titleH + textLayoutH;
  58163. int h = textBottom;
  58164. int buttonW = 40;
  58165. int i;
  58166. for (i = 0; i < buttons.size(); ++i)
  58167. buttonW += 16 + ((const TextButton*) buttons[i])->getWidth();
  58168. w = jmax (buttonW, w);
  58169. h += (textBoxes.size() + comboBoxes.size() + progressBars.size()) * 50;
  58170. if (buttons.size() > 0)
  58171. h += 20 + ((TextButton*) buttons[0])->getHeight();
  58172. for (i = customComps.size(); --i >= 0;)
  58173. {
  58174. w = jmax (w, ((Component*) customComps[i])->getWidth() + 40);
  58175. h += 10 + ((Component*) customComps[i])->getHeight();
  58176. }
  58177. for (i = textBlocks.size(); --i >= 0;)
  58178. {
  58179. const AlertTextComp* const ac = (AlertTextComp*) textBlocks[i];
  58180. w = jmax (w, ac->getPreferredWidth());
  58181. }
  58182. w = jmin (w, (int) (getParentWidth() * 0.7f));
  58183. for (i = textBlocks.size(); --i >= 0;)
  58184. {
  58185. AlertTextComp* const ac = (AlertTextComp*) textBlocks[i];
  58186. ac->updateLayout ((int) (w * 0.8f));
  58187. h += ac->getHeight() + 10;
  58188. }
  58189. h = jmin (getParentHeight() - 50, h);
  58190. if (onlyIncreaseSize)
  58191. {
  58192. w = jmax (w, getWidth());
  58193. h = jmax (h, getHeight());
  58194. }
  58195. if (! isVisible())
  58196. {
  58197. centreAroundComponent (associatedComponent, w, h);
  58198. }
  58199. else
  58200. {
  58201. const int cx = getX() + getWidth() / 2;
  58202. const int cy = getY() + getHeight() / 2;
  58203. setBounds (cx - w / 2,
  58204. cy - h / 2,
  58205. w, h);
  58206. }
  58207. textArea.setBounds (edgeGap, edgeGap, w - (edgeGap * 2), h - edgeGap);
  58208. const int spacer = 16;
  58209. int totalWidth = -spacer;
  58210. for (i = buttons.size(); --i >= 0;)
  58211. totalWidth += ((TextButton*) buttons[i])->getWidth() + spacer;
  58212. int x = (w - totalWidth) / 2;
  58213. int y = (int) (getHeight() * 0.95f);
  58214. for (i = 0; i < buttons.size(); ++i)
  58215. {
  58216. TextButton* const c = (TextButton*) buttons[i];
  58217. int ny = proportionOfHeight (0.95f) - c->getHeight();
  58218. c->setTopLeftPosition (x, ny);
  58219. if (ny < y)
  58220. y = ny;
  58221. x += c->getWidth() + spacer;
  58222. c->toFront (false);
  58223. }
  58224. y = textBottom;
  58225. for (i = 0; i < allComps.size(); ++i)
  58226. {
  58227. Component* const c = (Component*) allComps[i];
  58228. const int h = 22;
  58229. const int comboIndex = comboBoxes.indexOf (c);
  58230. if (comboIndex >= 0 && comboBoxNames [comboIndex].isNotEmpty())
  58231. y += 18;
  58232. const int tbIndex = textBoxes.indexOf (c);
  58233. if (tbIndex >= 0 && textboxNames[tbIndex].isNotEmpty())
  58234. y += 18;
  58235. if (customComps.contains (c) || textBlocks.contains (c))
  58236. {
  58237. c->setTopLeftPosition ((getWidth() - c->getWidth()) / 2, y);
  58238. y += c->getHeight() + 10;
  58239. }
  58240. else
  58241. {
  58242. c->setBounds (proportionOfWidth (0.1f), y, proportionOfWidth (0.8f), h);
  58243. y += h + 10;
  58244. }
  58245. }
  58246. setWantsKeyboardFocus (getNumChildComponents() == 0);
  58247. }
  58248. bool AlertWindow::containsAnyExtraComponents() const
  58249. {
  58250. return textBoxes.size()
  58251. + comboBoxes.size()
  58252. + progressBars.size()
  58253. + customComps.size() > 0;
  58254. }
  58255. void AlertWindow::mouseDown (const MouseEvent&)
  58256. {
  58257. dragger.startDraggingComponent (this, &constrainer);
  58258. }
  58259. void AlertWindow::mouseDrag (const MouseEvent& e)
  58260. {
  58261. dragger.dragComponent (this, e);
  58262. }
  58263. bool AlertWindow::keyPressed (const KeyPress& key)
  58264. {
  58265. for (int i = buttons.size(); --i >= 0;)
  58266. {
  58267. TextButton* const b = (TextButton*) buttons[i];
  58268. if (b->isRegisteredForShortcut (key))
  58269. {
  58270. b->triggerClick();
  58271. return true;
  58272. }
  58273. }
  58274. if (key.isKeyCode (KeyPress::escapeKey) && buttons.size() == 0)
  58275. {
  58276. exitModalState (0);
  58277. return true;
  58278. }
  58279. else if (key.isKeyCode (KeyPress::returnKey) && buttons.size() == 1)
  58280. {
  58281. ((TextButton*) buttons.getFirst())->triggerClick();
  58282. return true;
  58283. }
  58284. return false;
  58285. }
  58286. void AlertWindow::lookAndFeelChanged()
  58287. {
  58288. const int flags = getLookAndFeel().getAlertBoxWindowFlags();
  58289. setUsingNativeTitleBar ((flags & ComponentPeer::windowHasTitleBar) != 0);
  58290. setDropShadowEnabled (isOpaque() && (flags & ComponentPeer::windowHasDropShadow) != 0);
  58291. }
  58292. int AlertWindow::getDesktopWindowStyleFlags() const
  58293. {
  58294. return getLookAndFeel().getAlertBoxWindowFlags();
  58295. }
  58296. struct AlertWindowInfo
  58297. {
  58298. String title, message, button1, button2, button3;
  58299. AlertWindow::AlertIconType iconType;
  58300. int numButtons;
  58301. Component* associatedComponent;
  58302. int run() const
  58303. {
  58304. return (int) (pointer_sized_int)
  58305. MessageManager::getInstance()->callFunctionOnMessageThread (showCallback, (void*) this);
  58306. }
  58307. private:
  58308. int show() const
  58309. {
  58310. jassert (associatedComponent == 0 || associatedComponent->isValidComponent()); // has your comp been deleted?
  58311. LookAndFeel& lf = associatedComponent->isValidComponent() ? associatedComponent->getLookAndFeel()
  58312. : LookAndFeel::getDefaultLookAndFeel();
  58313. Component* const alertBox = lf.createAlertWindow (title, message, button1, button2, button3,
  58314. iconType, numButtons, associatedComponent);
  58315. jassert (alertBox != 0); // you have to return one of these!
  58316. const int result = alertBox->runModalLoop();
  58317. delete alertBox;
  58318. return result;
  58319. }
  58320. static void* showCallback (void* userData)
  58321. {
  58322. return (void*) (pointer_sized_int) ((const AlertWindowInfo*) userData)->show();
  58323. }
  58324. };
  58325. void AlertWindow::showMessageBox (AlertIconType iconType,
  58326. const String& title,
  58327. const String& message,
  58328. const String& buttonText,
  58329. Component* associatedComponent)
  58330. {
  58331. AlertWindowInfo info;
  58332. info.title = title;
  58333. info.message = message;
  58334. info.button1 = buttonText.isEmpty() ? TRANS("ok") : buttonText;
  58335. info.iconType = iconType;
  58336. info.numButtons = 1;
  58337. info.associatedComponent = associatedComponent;
  58338. info.run();
  58339. }
  58340. bool AlertWindow::showOkCancelBox (AlertIconType iconType,
  58341. const String& title,
  58342. const String& message,
  58343. const String& button1Text,
  58344. const String& button2Text,
  58345. Component* associatedComponent)
  58346. {
  58347. AlertWindowInfo info;
  58348. info.title = title;
  58349. info.message = message;
  58350. info.button1 = button1Text.isEmpty() ? TRANS("ok") : button1Text;
  58351. info.button2 = button2Text.isEmpty() ? TRANS("cancel") : button2Text;
  58352. info.iconType = iconType;
  58353. info.numButtons = 2;
  58354. info.associatedComponent = associatedComponent;
  58355. return info.run() != 0;
  58356. }
  58357. int AlertWindow::showYesNoCancelBox (AlertIconType iconType,
  58358. const String& title,
  58359. const String& message,
  58360. const String& button1Text,
  58361. const String& button2Text,
  58362. const String& button3Text,
  58363. Component* associatedComponent)
  58364. {
  58365. AlertWindowInfo info;
  58366. info.title = title;
  58367. info.message = message;
  58368. info.button1 = button1Text.isEmpty() ? TRANS("yes") : button1Text;
  58369. info.button2 = button2Text.isEmpty() ? TRANS("no") : button2Text;
  58370. info.button3 = button3Text.isEmpty() ? TRANS("cancel") : button3Text;
  58371. info.iconType = iconType;
  58372. info.numButtons = 3;
  58373. info.associatedComponent = associatedComponent;
  58374. return info.run();
  58375. }
  58376. END_JUCE_NAMESPACE
  58377. /********* End of inlined file: juce_AlertWindow.cpp *********/
  58378. /********* Start of inlined file: juce_ComponentPeer.cpp *********/
  58379. BEGIN_JUCE_NAMESPACE
  58380. //#define JUCE_ENABLE_REPAINT_DEBUGGING 1
  58381. // these are over in juce_component.cpp
  58382. extern int64 juce_recentMouseDownTimes[4];
  58383. extern int juce_recentMouseDownX [4];
  58384. extern int juce_recentMouseDownY [4];
  58385. extern Component* juce_recentMouseDownComponent [4];
  58386. extern int juce_LastMousePosX;
  58387. extern int juce_LastMousePosY;
  58388. extern int juce_MouseClickCounter;
  58389. extern bool juce_MouseHasMovedSignificantlySincePressed;
  58390. static const int fakeMouseMoveMessage = 0x7fff00ff;
  58391. static VoidArray heavyweightPeers (4);
  58392. ComponentPeer::ComponentPeer (Component* const component_,
  58393. const int styleFlags_) throw()
  58394. : component (component_),
  58395. styleFlags (styleFlags_),
  58396. lastPaintTime (0),
  58397. constrainer (0),
  58398. lastFocusedComponent (0),
  58399. dragAndDropTargetComponent (0),
  58400. lastDragAndDropCompUnderMouse (0),
  58401. fakeMouseMessageSent (false),
  58402. isWindowMinimised (false)
  58403. {
  58404. heavyweightPeers.add (this);
  58405. }
  58406. ComponentPeer::~ComponentPeer()
  58407. {
  58408. heavyweightPeers.removeValue (this);
  58409. delete dragAndDropTargetComponent;
  58410. Desktop::getInstance().triggerFocusCallback();
  58411. }
  58412. int ComponentPeer::getNumPeers() throw()
  58413. {
  58414. return heavyweightPeers.size();
  58415. }
  58416. ComponentPeer* ComponentPeer::getPeer (const int index) throw()
  58417. {
  58418. return (ComponentPeer*) heavyweightPeers [index];
  58419. }
  58420. ComponentPeer* ComponentPeer::getPeerFor (const Component* const component) throw()
  58421. {
  58422. for (int i = heavyweightPeers.size(); --i >= 0;)
  58423. {
  58424. ComponentPeer* const peer = (ComponentPeer*) heavyweightPeers.getUnchecked(i);
  58425. if (peer->getComponent() == component)
  58426. return peer;
  58427. }
  58428. return 0;
  58429. }
  58430. bool ComponentPeer::isValidPeer (const ComponentPeer* const peer) throw()
  58431. {
  58432. return heavyweightPeers.contains (const_cast <ComponentPeer*> (peer));
  58433. }
  58434. void ComponentPeer::updateCurrentModifiers() throw()
  58435. {
  58436. ModifierKeys::updateCurrentModifiers();
  58437. }
  58438. void ComponentPeer::handleMouseEnter (int x, int y, const int64 time)
  58439. {
  58440. jassert (component->isValidComponent());
  58441. updateCurrentModifiers();
  58442. Component* c = component->getComponentAt (x, y);
  58443. const ComponentDeletionWatcher deletionChecker (component);
  58444. if (c != Component::componentUnderMouse && Component::componentUnderMouse != 0)
  58445. {
  58446. jassert (Component::componentUnderMouse->isValidComponent());
  58447. const int oldX = x;
  58448. const int oldY = y;
  58449. component->relativePositionToOtherComponent (Component::componentUnderMouse, x, y);
  58450. Component::componentUnderMouse->internalMouseExit (x, y, time);
  58451. Component::componentUnderMouse = 0;
  58452. if (deletionChecker.hasBeenDeleted())
  58453. return;
  58454. c = component->getComponentAt (oldX, oldY);
  58455. }
  58456. Component::componentUnderMouse = c;
  58457. if (Component::componentUnderMouse != 0)
  58458. {
  58459. component->relativePositionToOtherComponent (Component::componentUnderMouse, x, y);
  58460. Component::componentUnderMouse->internalMouseEnter (x, y, time);
  58461. }
  58462. }
  58463. void ComponentPeer::handleMouseMove (int x, int y, const int64 time)
  58464. {
  58465. jassert (component->isValidComponent());
  58466. updateCurrentModifiers();
  58467. fakeMouseMessageSent = false;
  58468. const ComponentDeletionWatcher deletionChecker (component);
  58469. Component* c = component->getComponentAt (x, y);
  58470. if (c != Component::componentUnderMouse)
  58471. {
  58472. const int oldX = x;
  58473. const int oldY = y;
  58474. if (Component::componentUnderMouse != 0)
  58475. {
  58476. component->relativePositionToOtherComponent (Component::componentUnderMouse, x, y);
  58477. Component::componentUnderMouse->internalMouseExit (x, y, time);
  58478. x = oldX;
  58479. y = oldY;
  58480. Component::componentUnderMouse = 0;
  58481. if (deletionChecker.hasBeenDeleted())
  58482. return; // if this window has just been deleted..
  58483. c = component->getComponentAt (x, y);
  58484. }
  58485. Component::componentUnderMouse = c;
  58486. if (c != 0)
  58487. {
  58488. component->relativePositionToOtherComponent (c, x, y);
  58489. c->internalMouseEnter (x, y, time);
  58490. x = oldX;
  58491. y = oldY;
  58492. if (deletionChecker.hasBeenDeleted())
  58493. return; // if this window has just been deleted..
  58494. }
  58495. }
  58496. if (Component::componentUnderMouse != 0)
  58497. {
  58498. component->relativePositionToOtherComponent (Component::componentUnderMouse, x, y);
  58499. Component::componentUnderMouse->internalMouseMove (x, y, time);
  58500. }
  58501. }
  58502. void ComponentPeer::handleMouseDown (int x, int y, const int64 time)
  58503. {
  58504. ++juce_MouseClickCounter;
  58505. updateCurrentModifiers();
  58506. int numMouseButtonsDown = 0;
  58507. if (ModifierKeys::getCurrentModifiers().isLeftButtonDown())
  58508. ++numMouseButtonsDown;
  58509. if (ModifierKeys::getCurrentModifiers().isRightButtonDown())
  58510. ++numMouseButtonsDown;
  58511. if (ModifierKeys::getCurrentModifiers().isMiddleButtonDown())
  58512. ++numMouseButtonsDown;
  58513. if (numMouseButtonsDown == 1)
  58514. {
  58515. Component::componentUnderMouse = component->getComponentAt (x, y);
  58516. if (Component::componentUnderMouse != 0)
  58517. {
  58518. // can't set these in the mouseDownInt() method, because it's re-entrant, so do it here..
  58519. for (int i = numElementsInArray (juce_recentMouseDownTimes); --i > 0;)
  58520. {
  58521. juce_recentMouseDownTimes [i] = juce_recentMouseDownTimes [i - 1];
  58522. juce_recentMouseDownX [i] = juce_recentMouseDownX [i - 1];
  58523. juce_recentMouseDownY [i] = juce_recentMouseDownY [i - 1];
  58524. juce_recentMouseDownComponent [i] = juce_recentMouseDownComponent [i - 1];
  58525. }
  58526. juce_recentMouseDownTimes[0] = time;
  58527. juce_recentMouseDownX[0] = x;
  58528. juce_recentMouseDownY[0] = y;
  58529. juce_recentMouseDownComponent[0] = Component::componentUnderMouse;
  58530. relativePositionToGlobal (juce_recentMouseDownX[0], juce_recentMouseDownY[0]);
  58531. juce_MouseHasMovedSignificantlySincePressed = false;
  58532. component->relativePositionToOtherComponent (Component::componentUnderMouse, x, y);
  58533. Component::componentUnderMouse->internalMouseDown (x, y);
  58534. }
  58535. }
  58536. }
  58537. void ComponentPeer::handleMouseDrag (int x, int y, const int64 time)
  58538. {
  58539. updateCurrentModifiers();
  58540. if (Component::componentUnderMouse != 0)
  58541. {
  58542. component->relativePositionToOtherComponent (Component::componentUnderMouse, x, y);
  58543. Component::componentUnderMouse->internalMouseDrag (x, y, time);
  58544. }
  58545. }
  58546. void ComponentPeer::handleMouseUp (const int oldModifiers, int x, int y, const int64 time)
  58547. {
  58548. updateCurrentModifiers();
  58549. int numMouseButtonsDown = 0;
  58550. if ((oldModifiers & ModifierKeys::leftButtonModifier) != 0)
  58551. ++numMouseButtonsDown;
  58552. if ((oldModifiers & ModifierKeys::rightButtonModifier) != 0)
  58553. ++numMouseButtonsDown;
  58554. if ((oldModifiers & ModifierKeys::middleButtonModifier) != 0)
  58555. ++numMouseButtonsDown;
  58556. if (numMouseButtonsDown == 1)
  58557. {
  58558. const ComponentDeletionWatcher deletionChecker (component);
  58559. Component* c = component->getComponentAt (x, y);
  58560. if (c != Component::componentUnderMouse)
  58561. {
  58562. const int oldX = x;
  58563. const int oldY = y;
  58564. if (Component::componentUnderMouse != 0)
  58565. {
  58566. component->relativePositionToOtherComponent (Component::componentUnderMouse, x, y);
  58567. Component::componentUnderMouse->internalMouseUp (oldModifiers, x, y, time);
  58568. x = oldX;
  58569. y = oldY;
  58570. if (Component::componentUnderMouse != 0)
  58571. Component::componentUnderMouse->internalMouseExit (x, y, time);
  58572. if (deletionChecker.hasBeenDeleted())
  58573. return;
  58574. c = component->getComponentAt (oldX, oldY);
  58575. }
  58576. Component::componentUnderMouse = c;
  58577. if (Component::componentUnderMouse != 0)
  58578. {
  58579. component->relativePositionToOtherComponent (Component::componentUnderMouse, x, y);
  58580. Component::componentUnderMouse->internalMouseEnter (x, y, time);
  58581. }
  58582. }
  58583. else
  58584. {
  58585. if (Component::componentUnderMouse != 0)
  58586. {
  58587. component->relativePositionToOtherComponent (Component::componentUnderMouse, x, y);
  58588. Component::componentUnderMouse->internalMouseUp (oldModifiers, x, y, time);
  58589. }
  58590. }
  58591. }
  58592. }
  58593. void ComponentPeer::handleMouseExit (int x, int y, const int64 time)
  58594. {
  58595. jassert (component->isValidComponent());
  58596. updateCurrentModifiers();
  58597. if (Component::componentUnderMouse != 0)
  58598. {
  58599. component->relativePositionToOtherComponent (Component::componentUnderMouse, x, y);
  58600. Component::componentUnderMouse->internalMouseExit (x, y, time);
  58601. Component::componentUnderMouse = 0;
  58602. }
  58603. }
  58604. void ComponentPeer::handleMouseWheel (const int amountX, const int amountY, const int64 time)
  58605. {
  58606. updateCurrentModifiers();
  58607. if (Component::componentUnderMouse != 0)
  58608. Component::componentUnderMouse->internalMouseWheel (amountX, amountY, time);
  58609. }
  58610. void ComponentPeer::sendFakeMouseMove() throw()
  58611. {
  58612. if ((! fakeMouseMessageSent)
  58613. && component->flags.hasHeavyweightPeerFlag
  58614. && ! ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown())
  58615. {
  58616. if (! isMinimised())
  58617. {
  58618. int realX, realY, realW, realH;
  58619. getBounds (realX, realY, realW, realH);
  58620. component->bounds_.setBounds (realX, realY, realW, realH);
  58621. }
  58622. int x, y;
  58623. component->getMouseXYRelative (x, y);
  58624. if (((unsigned int) x) < (unsigned int) component->getWidth()
  58625. && ((unsigned int) y) < (unsigned int) component->getHeight()
  58626. && contains (x, y, false))
  58627. {
  58628. postMessage (new Message (fakeMouseMoveMessage, x, y, 0));
  58629. }
  58630. fakeMouseMessageSent = true;
  58631. }
  58632. }
  58633. void ComponentPeer::handleMessage (const Message& message)
  58634. {
  58635. if (message.intParameter1 == fakeMouseMoveMessage)
  58636. {
  58637. if (! ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown())
  58638. handleMouseMove (message.intParameter2,
  58639. message.intParameter3,
  58640. Time::currentTimeMillis());
  58641. }
  58642. }
  58643. void ComponentPeer::handlePaint (LowLevelGraphicsContext& contextToPaintTo)
  58644. {
  58645. Graphics g (&contextToPaintTo);
  58646. #if JUCE_ENABLE_REPAINT_DEBUGGING
  58647. g.saveState();
  58648. #endif
  58649. JUCE_TRY
  58650. {
  58651. component->paintEntireComponent (g);
  58652. }
  58653. JUCE_CATCH_EXCEPTION
  58654. #if JUCE_ENABLE_REPAINT_DEBUGGING
  58655. // enabling this code will fill all areas that get repainted with a colour overlay, to show
  58656. // clearly when things are being repainted.
  58657. {
  58658. g.restoreState();
  58659. g.fillAll (Colour ((uint8) Random::getSystemRandom().nextInt (255),
  58660. (uint8) Random::getSystemRandom().nextInt (255),
  58661. (uint8) Random::getSystemRandom().nextInt (255),
  58662. (uint8) 0x50));
  58663. }
  58664. #endif
  58665. }
  58666. bool ComponentPeer::handleKeyPress (const int keyCode,
  58667. const juce_wchar textCharacter)
  58668. {
  58669. updateCurrentModifiers();
  58670. Component* target = Component::currentlyFocusedComponent->isValidComponent()
  58671. ? Component::currentlyFocusedComponent
  58672. : component;
  58673. if (target->isCurrentlyBlockedByAnotherModalComponent())
  58674. {
  58675. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  58676. if (currentModalComp != 0)
  58677. target = currentModalComp;
  58678. }
  58679. const KeyPress keyInfo (keyCode,
  58680. ModifierKeys::getCurrentModifiers().getRawFlags()
  58681. & ModifierKeys::allKeyboardModifiers,
  58682. textCharacter);
  58683. bool keyWasUsed = false;
  58684. while (target != 0)
  58685. {
  58686. const ComponentDeletionWatcher deletionChecker (target);
  58687. if (target->keyListeners_ != 0)
  58688. {
  58689. for (int i = target->keyListeners_->size(); --i >= 0;)
  58690. {
  58691. keyWasUsed = ((KeyListener*) target->keyListeners_->getUnchecked(i))->keyPressed (keyInfo, target);
  58692. if (keyWasUsed || deletionChecker.hasBeenDeleted())
  58693. return keyWasUsed;
  58694. i = jmin (i, target->keyListeners_->size());
  58695. }
  58696. }
  58697. keyWasUsed = target->keyPressed (keyInfo);
  58698. if (keyWasUsed || deletionChecker.hasBeenDeleted())
  58699. break;
  58700. if (keyInfo.isKeyCode (KeyPress::tabKey) && Component::getCurrentlyFocusedComponent() != 0)
  58701. {
  58702. Component* const currentlyFocused = Component::getCurrentlyFocusedComponent();
  58703. currentlyFocused->moveKeyboardFocusToSibling (! keyInfo.getModifiers().isShiftDown());
  58704. keyWasUsed = (currentlyFocused != Component::getCurrentlyFocusedComponent());
  58705. break;
  58706. }
  58707. target = target->parentComponent_;
  58708. }
  58709. return keyWasUsed;
  58710. }
  58711. bool ComponentPeer::handleKeyUpOrDown (const bool isKeyDown)
  58712. {
  58713. updateCurrentModifiers();
  58714. Component* target = Component::currentlyFocusedComponent->isValidComponent()
  58715. ? Component::currentlyFocusedComponent
  58716. : component;
  58717. if (target->isCurrentlyBlockedByAnotherModalComponent())
  58718. {
  58719. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  58720. if (currentModalComp != 0)
  58721. target = currentModalComp;
  58722. }
  58723. bool keyWasUsed = false;
  58724. while (target != 0)
  58725. {
  58726. const ComponentDeletionWatcher deletionChecker (target);
  58727. keyWasUsed = target->keyStateChanged (isKeyDown);
  58728. if (keyWasUsed || deletionChecker.hasBeenDeleted())
  58729. break;
  58730. if (target->keyListeners_ != 0)
  58731. {
  58732. for (int i = target->keyListeners_->size(); --i >= 0;)
  58733. {
  58734. keyWasUsed = ((KeyListener*) target->keyListeners_->getUnchecked(i))->keyStateChanged (isKeyDown, target);
  58735. if (keyWasUsed || deletionChecker.hasBeenDeleted())
  58736. return keyWasUsed;
  58737. i = jmin (i, target->keyListeners_->size());
  58738. }
  58739. }
  58740. target = target->parentComponent_;
  58741. }
  58742. return keyWasUsed;
  58743. }
  58744. void ComponentPeer::handleModifierKeysChange()
  58745. {
  58746. updateCurrentModifiers();
  58747. Component* target = Component::getComponentUnderMouse();
  58748. if (target == 0)
  58749. target = Component::getCurrentlyFocusedComponent();
  58750. if (target == 0)
  58751. target = component;
  58752. if (target->isValidComponent())
  58753. target->internalModifierKeysChanged();
  58754. }
  58755. void ComponentPeer::handleBroughtToFront()
  58756. {
  58757. updateCurrentModifiers();
  58758. if (component != 0)
  58759. component->internalBroughtToFront();
  58760. }
  58761. void ComponentPeer::setConstrainer (ComponentBoundsConstrainer* const newConstrainer) throw()
  58762. {
  58763. constrainer = newConstrainer;
  58764. }
  58765. void ComponentPeer::handleMovedOrResized()
  58766. {
  58767. jassert (component->isValidComponent());
  58768. updateCurrentModifiers();
  58769. const bool nowMinimised = isMinimised();
  58770. if (component->flags.hasHeavyweightPeerFlag && ! nowMinimised)
  58771. {
  58772. const ComponentDeletionWatcher deletionChecker (component);
  58773. int realX, realY, realW, realH;
  58774. getBounds (realX, realY, realW, realH);
  58775. const bool wasMoved = (component->getX() != realX || component->getY() != realY);
  58776. const bool wasResized = (component->getWidth() != realW || component->getHeight() != realH);
  58777. if (wasMoved || wasResized)
  58778. {
  58779. component->bounds_.setBounds (realX, realY, realW, realH);
  58780. if (wasResized)
  58781. component->repaint();
  58782. component->sendMovedResizedMessages (wasMoved, wasResized);
  58783. if (deletionChecker.hasBeenDeleted())
  58784. return;
  58785. }
  58786. }
  58787. if (isWindowMinimised != nowMinimised)
  58788. {
  58789. isWindowMinimised = nowMinimised;
  58790. component->minimisationStateChanged (nowMinimised);
  58791. component->sendVisibilityChangeMessage();
  58792. }
  58793. if (! isFullScreen())
  58794. lastNonFullscreenBounds = component->getBounds();
  58795. }
  58796. void ComponentPeer::handleFocusGain()
  58797. {
  58798. updateCurrentModifiers();
  58799. if (component->isParentOf (lastFocusedComponent))
  58800. {
  58801. Component::currentlyFocusedComponent = lastFocusedComponent;
  58802. Desktop::getInstance().triggerFocusCallback();
  58803. lastFocusedComponent->internalFocusGain (Component::focusChangedDirectly);
  58804. }
  58805. else
  58806. {
  58807. if (! component->isCurrentlyBlockedByAnotherModalComponent())
  58808. component->grabKeyboardFocus();
  58809. else
  58810. Component::bringModalComponentToFront();
  58811. }
  58812. }
  58813. void ComponentPeer::handleFocusLoss()
  58814. {
  58815. updateCurrentModifiers();
  58816. if (component->hasKeyboardFocus (true))
  58817. {
  58818. lastFocusedComponent = Component::currentlyFocusedComponent;
  58819. if (lastFocusedComponent != 0)
  58820. {
  58821. Component::currentlyFocusedComponent = 0;
  58822. Desktop::getInstance().triggerFocusCallback();
  58823. lastFocusedComponent->internalFocusLoss (Component::focusChangedByMouseClick);
  58824. }
  58825. }
  58826. }
  58827. Component* ComponentPeer::getLastFocusedSubcomponent() const throw()
  58828. {
  58829. return (component->isParentOf (lastFocusedComponent) && lastFocusedComponent->isShowing())
  58830. ? lastFocusedComponent
  58831. : component;
  58832. }
  58833. void ComponentPeer::handleScreenSizeChange()
  58834. {
  58835. updateCurrentModifiers();
  58836. component->parentSizeChanged();
  58837. handleMovedOrResized();
  58838. }
  58839. void ComponentPeer::setNonFullScreenBounds (const Rectangle& newBounds) throw()
  58840. {
  58841. lastNonFullscreenBounds = newBounds;
  58842. }
  58843. const Rectangle& ComponentPeer::getNonFullScreenBounds() const throw()
  58844. {
  58845. return lastNonFullscreenBounds;
  58846. }
  58847. static FileDragAndDropTarget* findDragAndDropTarget (Component* c,
  58848. const StringArray& files,
  58849. FileDragAndDropTarget* const lastOne)
  58850. {
  58851. while (c != 0)
  58852. {
  58853. FileDragAndDropTarget* const t = dynamic_cast <FileDragAndDropTarget*> (c);
  58854. if (t != 0 && (t == lastOne || t->isInterestedInFileDrag (files)))
  58855. return t;
  58856. c = c->getParentComponent();
  58857. }
  58858. return 0;
  58859. }
  58860. void ComponentPeer::handleFileDragMove (const StringArray& files, int x, int y)
  58861. {
  58862. updateCurrentModifiers();
  58863. FileDragAndDropTarget* lastTarget = 0;
  58864. if (dragAndDropTargetComponent != 0 && ! dragAndDropTargetComponent->hasBeenDeleted())
  58865. lastTarget = const_cast <FileDragAndDropTarget*> (dynamic_cast <const FileDragAndDropTarget*> (dragAndDropTargetComponent->getComponent()));
  58866. FileDragAndDropTarget* newTarget = 0;
  58867. Component* const compUnderMouse = component->getComponentAt (x, y);
  58868. if (compUnderMouse != lastDragAndDropCompUnderMouse)
  58869. {
  58870. lastDragAndDropCompUnderMouse = compUnderMouse;
  58871. newTarget = findDragAndDropTarget (compUnderMouse, files, lastTarget);
  58872. if (newTarget != lastTarget)
  58873. {
  58874. if (lastTarget != 0)
  58875. lastTarget->fileDragExit (files);
  58876. deleteAndZero (dragAndDropTargetComponent);
  58877. if (newTarget != 0)
  58878. {
  58879. Component* const targetComp = dynamic_cast <Component*> (newTarget);
  58880. int mx = x, my = y;
  58881. component->relativePositionToOtherComponent (targetComp, mx, my);
  58882. dragAndDropTargetComponent = new ComponentDeletionWatcher (dynamic_cast <Component*> (newTarget));
  58883. newTarget->fileDragEnter (files, mx, my);
  58884. }
  58885. }
  58886. }
  58887. else
  58888. {
  58889. newTarget = lastTarget;
  58890. }
  58891. if (newTarget != 0)
  58892. {
  58893. Component* const targetComp = dynamic_cast <Component*> (newTarget);
  58894. component->relativePositionToOtherComponent (targetComp, x, y);
  58895. newTarget->fileDragMove (files, x, y);
  58896. }
  58897. }
  58898. void ComponentPeer::handleFileDragExit (const StringArray& files)
  58899. {
  58900. handleFileDragMove (files, -1, -1);
  58901. jassert (dragAndDropTargetComponent == 0);
  58902. lastDragAndDropCompUnderMouse = 0;
  58903. }
  58904. void ComponentPeer::handleFileDragDrop (const StringArray& files, int x, int y)
  58905. {
  58906. handleFileDragMove (files, x, y);
  58907. if (dragAndDropTargetComponent != 0 && ! dragAndDropTargetComponent->hasBeenDeleted())
  58908. {
  58909. FileDragAndDropTarget* const target = const_cast <FileDragAndDropTarget*> (dynamic_cast <const FileDragAndDropTarget*> (dragAndDropTargetComponent->getComponent()));
  58910. deleteAndZero (dragAndDropTargetComponent);
  58911. lastDragAndDropCompUnderMouse = 0;
  58912. if (target != 0)
  58913. {
  58914. Component* const targetComp = dynamic_cast <Component*> (target);
  58915. if (targetComp->isCurrentlyBlockedByAnotherModalComponent())
  58916. {
  58917. targetComp->internalModalInputAttempt();
  58918. if (targetComp->isCurrentlyBlockedByAnotherModalComponent())
  58919. return;
  58920. }
  58921. component->relativePositionToOtherComponent (targetComp, x, y);
  58922. target->filesDropped (files, x, y);
  58923. }
  58924. }
  58925. }
  58926. void ComponentPeer::handleUserClosingWindow()
  58927. {
  58928. updateCurrentModifiers();
  58929. component->userTriedToCloseWindow();
  58930. }
  58931. void ComponentPeer::bringModalComponentToFront()
  58932. {
  58933. Component::bringModalComponentToFront();
  58934. }
  58935. void ComponentPeer::clearMaskedRegion() throw()
  58936. {
  58937. maskedRegion.clear();
  58938. }
  58939. void ComponentPeer::addMaskedRegion (int x, int y, int w, int h) throw()
  58940. {
  58941. maskedRegion.add (x, y, w, h);
  58942. }
  58943. END_JUCE_NAMESPACE
  58944. /********* End of inlined file: juce_ComponentPeer.cpp *********/
  58945. /********* Start of inlined file: juce_DialogWindow.cpp *********/
  58946. BEGIN_JUCE_NAMESPACE
  58947. DialogWindow::DialogWindow (const String& name,
  58948. const Colour& backgroundColour_,
  58949. const bool escapeKeyTriggersCloseButton_,
  58950. const bool addToDesktop_)
  58951. : DocumentWindow (name, backgroundColour_, DocumentWindow::closeButton, addToDesktop_),
  58952. escapeKeyTriggersCloseButton (escapeKeyTriggersCloseButton_)
  58953. {
  58954. }
  58955. DialogWindow::~DialogWindow()
  58956. {
  58957. }
  58958. void DialogWindow::resized()
  58959. {
  58960. DocumentWindow::resized();
  58961. const KeyPress esc (KeyPress::escapeKey, 0, 0);
  58962. if (escapeKeyTriggersCloseButton
  58963. && getCloseButton() != 0
  58964. && ! getCloseButton()->isRegisteredForShortcut (esc))
  58965. {
  58966. getCloseButton()->addShortcut (esc);
  58967. }
  58968. }
  58969. class TempDialogWindow : public DialogWindow
  58970. {
  58971. public:
  58972. TempDialogWindow (const String& title, const Colour& colour, const bool escapeCloses)
  58973. : DialogWindow (title, colour, escapeCloses, true)
  58974. {
  58975. }
  58976. ~TempDialogWindow()
  58977. {
  58978. }
  58979. void closeButtonPressed()
  58980. {
  58981. setVisible (false);
  58982. }
  58983. private:
  58984. TempDialogWindow (const TempDialogWindow&);
  58985. const TempDialogWindow& operator= (const TempDialogWindow&);
  58986. };
  58987. int DialogWindow::showModalDialog (const String& dialogTitle,
  58988. Component* contentComponent,
  58989. Component* componentToCentreAround,
  58990. const Colour& colour,
  58991. const bool escapeKeyTriggersCloseButton,
  58992. const bool shouldBeResizable,
  58993. const bool useBottomRightCornerResizer)
  58994. {
  58995. TempDialogWindow dw (dialogTitle, colour, escapeKeyTriggersCloseButton);
  58996. dw.setContentComponent (contentComponent, true, true);
  58997. dw.centreAroundComponent (componentToCentreAround, dw.getWidth(), dw.getHeight());
  58998. dw.setResizable (shouldBeResizable, useBottomRightCornerResizer);
  58999. const int result = dw.runModalLoop();
  59000. dw.setContentComponent (0, false);
  59001. return result;
  59002. }
  59003. END_JUCE_NAMESPACE
  59004. /********* End of inlined file: juce_DialogWindow.cpp *********/
  59005. /********* Start of inlined file: juce_DocumentWindow.cpp *********/
  59006. BEGIN_JUCE_NAMESPACE
  59007. DocumentWindow::DocumentWindow (const String& title,
  59008. const Colour& backgroundColour,
  59009. const int requiredButtons_,
  59010. const bool addToDesktop_)
  59011. : ResizableWindow (title, backgroundColour, addToDesktop_),
  59012. titleBarHeight (26),
  59013. menuBarHeight (24),
  59014. requiredButtons (requiredButtons_),
  59015. #if JUCE_MAC
  59016. positionTitleBarButtonsOnLeft (true),
  59017. #else
  59018. positionTitleBarButtonsOnLeft (false),
  59019. #endif
  59020. drawTitleTextCentred (true),
  59021. titleBarIcon (0),
  59022. menuBar (0),
  59023. menuBarModel (0)
  59024. {
  59025. zeromem (titleBarButtons, sizeof (titleBarButtons));
  59026. setResizeLimits (128, 128, 32768, 32768);
  59027. lookAndFeelChanged();
  59028. }
  59029. DocumentWindow::~DocumentWindow()
  59030. {
  59031. for (int i = 0; i < 3; ++i)
  59032. delete titleBarButtons[i];
  59033. delete titleBarIcon;
  59034. delete menuBar;
  59035. }
  59036. void DocumentWindow::repaintTitleBar()
  59037. {
  59038. const int border = getBorderSize();
  59039. repaint (border, border, getWidth() - border * 2, getTitleBarHeight());
  59040. }
  59041. void DocumentWindow::setName (const String& newName)
  59042. {
  59043. if (newName != getName())
  59044. {
  59045. Component::setName (newName);
  59046. repaintTitleBar();
  59047. }
  59048. }
  59049. void DocumentWindow::setIcon (const Image* imageToUse)
  59050. {
  59051. deleteAndZero (titleBarIcon);
  59052. if (imageToUse != 0)
  59053. titleBarIcon = imageToUse->createCopy();
  59054. repaintTitleBar();
  59055. }
  59056. void DocumentWindow::setTitleBarHeight (const int newHeight)
  59057. {
  59058. titleBarHeight = newHeight;
  59059. resized();
  59060. repaintTitleBar();
  59061. }
  59062. void DocumentWindow::setTitleBarButtonsRequired (const int requiredButtons_,
  59063. const bool positionTitleBarButtonsOnLeft_)
  59064. {
  59065. requiredButtons = requiredButtons_;
  59066. positionTitleBarButtonsOnLeft = positionTitleBarButtonsOnLeft_;
  59067. lookAndFeelChanged();
  59068. }
  59069. void DocumentWindow::setTitleBarTextCentred (const bool textShouldBeCentred)
  59070. {
  59071. drawTitleTextCentred = textShouldBeCentred;
  59072. repaintTitleBar();
  59073. }
  59074. void DocumentWindow::setMenuBar (MenuBarModel* menuBarModel_,
  59075. const int menuBarHeight_)
  59076. {
  59077. if (menuBarModel != menuBarModel_)
  59078. {
  59079. delete menuBar;
  59080. menuBar = 0;
  59081. menuBarModel = menuBarModel_;
  59082. menuBarHeight = (menuBarHeight_ > 0) ? menuBarHeight_
  59083. : getLookAndFeel().getDefaultMenuBarHeight();
  59084. if (menuBarModel != 0)
  59085. {
  59086. // (call the Component method directly to avoid the assertion in ResizableWindow)
  59087. Component::addAndMakeVisible (menuBar = new MenuBarComponent (menuBarModel));
  59088. menuBar->setEnabled (isActiveWindow());
  59089. }
  59090. resized();
  59091. }
  59092. }
  59093. void DocumentWindow::closeButtonPressed()
  59094. {
  59095. /* If you've got a close button, you have to override this method to get
  59096. rid of your window!
  59097. If the window is just a pop-up, you should override this method and make
  59098. it delete the window in whatever way is appropriate for your app. E.g. you
  59099. might just want to call "delete this".
  59100. If your app is centred around this window such that the whole app should quit when
  59101. the window is closed, then you will probably want to use this method as an opportunity
  59102. to call JUCEApplication::quit(), and leave the window to be deleted later by your
  59103. JUCEApplication::shutdown() method. (Doing it this way means that your window will
  59104. still get cleaned-up if the app is quit by some other means (e.g. a cmd-Q on the mac
  59105. or closing it via the taskbar icon on Windows).
  59106. */
  59107. jassertfalse
  59108. }
  59109. void DocumentWindow::minimiseButtonPressed()
  59110. {
  59111. setMinimised (true);
  59112. }
  59113. void DocumentWindow::maximiseButtonPressed()
  59114. {
  59115. setFullScreen (! isFullScreen());
  59116. }
  59117. void DocumentWindow::paint (Graphics& g)
  59118. {
  59119. ResizableWindow::paint (g);
  59120. if (resizableBorder == 0 && getBorderSize() == 1)
  59121. {
  59122. g.setColour (getBackgroundColour().overlaidWith (Colour (0x80000000)));
  59123. g.drawRect (0, 0, getWidth(), getHeight());
  59124. }
  59125. const int border = getBorderSize();
  59126. g.setOrigin (border, border);
  59127. g.reduceClipRegion (0, 0, getWidth() - border * 2, getTitleBarHeight());
  59128. int titleSpaceX1 = 6;
  59129. int titleSpaceX2 = getWidth() - 6;
  59130. for (int i = 0; i < 3; ++i)
  59131. {
  59132. if (titleBarButtons[i] != 0)
  59133. {
  59134. if (positionTitleBarButtonsOnLeft)
  59135. titleSpaceX1 = jmax (titleSpaceX1, titleBarButtons[i]->getRight() + (getWidth() - titleBarButtons[i]->getRight()) / 8);
  59136. else
  59137. titleSpaceX2 = jmin (titleSpaceX2, titleBarButtons[i]->getX() - (titleBarButtons[i]->getX() / 8));
  59138. }
  59139. }
  59140. getLookAndFeel()
  59141. .drawDocumentWindowTitleBar (*this, g,
  59142. getWidth() - border * 2,
  59143. getTitleBarHeight(),
  59144. titleSpaceX1, jmax (1, titleSpaceX2 - titleSpaceX1),
  59145. titleBarIcon, ! drawTitleTextCentred);
  59146. }
  59147. void DocumentWindow::resized()
  59148. {
  59149. ResizableWindow::resized();
  59150. if (titleBarButtons[1] != 0)
  59151. titleBarButtons[1]->setToggleState (isFullScreen(), false);
  59152. const int border = getBorderSize();
  59153. getLookAndFeel()
  59154. .positionDocumentWindowButtons (*this,
  59155. border, border,
  59156. getWidth() - border * 2, getTitleBarHeight(),
  59157. titleBarButtons[0],
  59158. titleBarButtons[1],
  59159. titleBarButtons[2],
  59160. positionTitleBarButtonsOnLeft);
  59161. if (menuBar != 0)
  59162. menuBar->setBounds (border, border + getTitleBarHeight(),
  59163. getWidth() - border * 2, menuBarHeight);
  59164. }
  59165. Button* DocumentWindow::getCloseButton() const throw()
  59166. {
  59167. return titleBarButtons[2];
  59168. }
  59169. Button* DocumentWindow::getMinimiseButton() const throw()
  59170. {
  59171. return titleBarButtons[0];
  59172. }
  59173. Button* DocumentWindow::getMaximiseButton() const throw()
  59174. {
  59175. return titleBarButtons[1];
  59176. }
  59177. int DocumentWindow::getDesktopWindowStyleFlags() const
  59178. {
  59179. int flags = ResizableWindow::getDesktopWindowStyleFlags();
  59180. if ((requiredButtons & minimiseButton) != 0)
  59181. flags |= ComponentPeer::windowHasMinimiseButton;
  59182. if ((requiredButtons & maximiseButton) != 0)
  59183. flags |= ComponentPeer::windowHasMaximiseButton;
  59184. if ((requiredButtons & closeButton) != 0)
  59185. flags |= ComponentPeer::windowHasCloseButton;
  59186. return flags;
  59187. }
  59188. void DocumentWindow::lookAndFeelChanged()
  59189. {
  59190. int i;
  59191. for (i = 0; i < 3; ++i)
  59192. deleteAndZero (titleBarButtons[i]);
  59193. if (! isUsingNativeTitleBar())
  59194. {
  59195. titleBarButtons[0] = ((requiredButtons & minimiseButton) != 0)
  59196. ? getLookAndFeel().createDocumentWindowButton (minimiseButton) : 0;
  59197. titleBarButtons[1] = ((requiredButtons & maximiseButton) != 0)
  59198. ? getLookAndFeel().createDocumentWindowButton (maximiseButton) : 0;
  59199. titleBarButtons[2] = ((requiredButtons & closeButton) != 0)
  59200. ? getLookAndFeel().createDocumentWindowButton (closeButton) : 0;
  59201. for (i = 0; i < 3; ++i)
  59202. {
  59203. if (titleBarButtons[i] != 0)
  59204. {
  59205. buttonListener.owner = this;
  59206. titleBarButtons[i]->addButtonListener (&buttonListener);
  59207. titleBarButtons[i]->setWantsKeyboardFocus (false);
  59208. // (call the Component method directly to avoid the assertion in ResizableWindow)
  59209. Component::addAndMakeVisible (titleBarButtons[i]);
  59210. }
  59211. }
  59212. if (getCloseButton() != 0)
  59213. {
  59214. #if JUCE_MAC
  59215. getCloseButton()->addShortcut (KeyPress (T('w'), ModifierKeys::commandModifier, 0));
  59216. #else
  59217. getCloseButton()->addShortcut (KeyPress (KeyPress::F4Key, ModifierKeys::altModifier, 0));
  59218. #endif
  59219. }
  59220. }
  59221. activeWindowStatusChanged();
  59222. ResizableWindow::lookAndFeelChanged();
  59223. }
  59224. void DocumentWindow::parentHierarchyChanged()
  59225. {
  59226. lookAndFeelChanged();
  59227. }
  59228. void DocumentWindow::activeWindowStatusChanged()
  59229. {
  59230. ResizableWindow::activeWindowStatusChanged();
  59231. for (int i = 0; i < 3; ++i)
  59232. if (titleBarButtons[i] != 0)
  59233. titleBarButtons[i]->setEnabled (isActiveWindow());
  59234. if (menuBar != 0)
  59235. menuBar->setEnabled (isActiveWindow());
  59236. }
  59237. const BorderSize DocumentWindow::getBorderThickness()
  59238. {
  59239. return BorderSize (getBorderSize());
  59240. }
  59241. const BorderSize DocumentWindow::getContentComponentBorder()
  59242. {
  59243. const int size = getBorderSize();
  59244. return BorderSize (size
  59245. + (isUsingNativeTitleBar() ? 0 : titleBarHeight)
  59246. + (menuBar != 0 ? menuBarHeight : 0),
  59247. size, size, size);
  59248. }
  59249. void DocumentWindow::mouseDoubleClick (const MouseEvent& e)
  59250. {
  59251. const int border = getBorderSize();
  59252. if (e.x >= border
  59253. && e.y >= border
  59254. && e.x < getWidth() - border
  59255. && e.y < border + getTitleBarHeight()
  59256. && getMaximiseButton() != 0)
  59257. {
  59258. getMaximiseButton()->triggerClick();
  59259. }
  59260. }
  59261. void DocumentWindow::userTriedToCloseWindow()
  59262. {
  59263. closeButtonPressed();
  59264. }
  59265. int DocumentWindow::getTitleBarHeight() const
  59266. {
  59267. return isUsingNativeTitleBar() ? 0 : jmin (titleBarHeight, getHeight() - 4);
  59268. }
  59269. int DocumentWindow::getBorderSize() const
  59270. {
  59271. return (isFullScreen() || isUsingNativeTitleBar()) ? 0 : (resizableBorder != 0 ? 4 : 1);
  59272. }
  59273. DocumentWindow::ButtonListenerProxy::ButtonListenerProxy()
  59274. {
  59275. }
  59276. void DocumentWindow::ButtonListenerProxy::buttonClicked (Button* button)
  59277. {
  59278. if (button == owner->getMinimiseButton())
  59279. {
  59280. owner->minimiseButtonPressed();
  59281. }
  59282. else if (button == owner->getMaximiseButton())
  59283. {
  59284. owner->maximiseButtonPressed();
  59285. }
  59286. else if (button == owner->getCloseButton())
  59287. {
  59288. owner->closeButtonPressed();
  59289. }
  59290. }
  59291. END_JUCE_NAMESPACE
  59292. /********* End of inlined file: juce_DocumentWindow.cpp *********/
  59293. /********* Start of inlined file: juce_ResizableWindow.cpp *********/
  59294. BEGIN_JUCE_NAMESPACE
  59295. ResizableWindow::ResizableWindow (const String& name,
  59296. const bool addToDesktop_)
  59297. : TopLevelWindow (name, addToDesktop_),
  59298. resizableCorner (0),
  59299. resizableBorder (0),
  59300. contentComponent (0),
  59301. resizeToFitContent (false),
  59302. fullscreen (false),
  59303. lastNonFullScreenPos (50, 50, 256, 256),
  59304. constrainer (0)
  59305. #ifdef JUCE_DEBUG
  59306. , hasBeenResized (false)
  59307. #endif
  59308. {
  59309. defaultConstrainer.setMinimumOnscreenAmounts (0x10000, 16, 24, 16);
  59310. lastNonFullScreenPos.setBounds (50, 50, 256, 256);
  59311. if (addToDesktop_)
  59312. Component::addToDesktop (getDesktopWindowStyleFlags());
  59313. }
  59314. ResizableWindow::ResizableWindow (const String& name,
  59315. const Colour& backgroundColour_,
  59316. const bool addToDesktop_)
  59317. : TopLevelWindow (name, addToDesktop_),
  59318. resizableCorner (0),
  59319. resizableBorder (0),
  59320. contentComponent (0),
  59321. resizeToFitContent (false),
  59322. fullscreen (false),
  59323. lastNonFullScreenPos (50, 50, 256, 256),
  59324. constrainer (0)
  59325. #ifdef JUCE_DEBUG
  59326. , hasBeenResized (false)
  59327. #endif
  59328. {
  59329. setBackgroundColour (backgroundColour_);
  59330. defaultConstrainer.setMinimumOnscreenAmounts (0x10000, 16, 24, 16);
  59331. if (addToDesktop_)
  59332. Component::addToDesktop (getDesktopWindowStyleFlags());
  59333. }
  59334. ResizableWindow::~ResizableWindow()
  59335. {
  59336. deleteAndZero (resizableCorner);
  59337. deleteAndZero (resizableBorder);
  59338. deleteAndZero (contentComponent);
  59339. // have you been adding your own components directly to this window..? tut tut tut.
  59340. // Read the instructions for using a ResizableWindow!
  59341. jassert (getNumChildComponents() == 0);
  59342. }
  59343. int ResizableWindow::getDesktopWindowStyleFlags() const
  59344. {
  59345. int flags = TopLevelWindow::getDesktopWindowStyleFlags();
  59346. if (isResizable() && (flags & ComponentPeer::windowHasTitleBar) != 0)
  59347. flags |= ComponentPeer::windowIsResizable;
  59348. return flags;
  59349. }
  59350. void ResizableWindow::setContentComponent (Component* const newContentComponent,
  59351. const bool deleteOldOne,
  59352. const bool resizeToFit)
  59353. {
  59354. resizeToFitContent = resizeToFit;
  59355. if (contentComponent != newContentComponent)
  59356. {
  59357. if (deleteOldOne)
  59358. delete contentComponent;
  59359. else
  59360. removeChildComponent (contentComponent);
  59361. contentComponent = newContentComponent;
  59362. Component::addAndMakeVisible (contentComponent);
  59363. }
  59364. if (resizeToFit)
  59365. childBoundsChanged (contentComponent);
  59366. resized(); // must always be called to position the new content comp
  59367. }
  59368. void ResizableWindow::setContentComponentSize (int width, int height)
  59369. {
  59370. jassert (width > 0 && height > 0); // not a great idea to give it a zero size..
  59371. const BorderSize border (getContentComponentBorder());
  59372. setSize (width + border.getLeftAndRight(),
  59373. height + border.getTopAndBottom());
  59374. }
  59375. const BorderSize ResizableWindow::getBorderThickness()
  59376. {
  59377. return BorderSize (isUsingNativeTitleBar() ? 0 : ((resizableBorder != 0 && ! isFullScreen()) ? 5 : 3));
  59378. }
  59379. const BorderSize ResizableWindow::getContentComponentBorder()
  59380. {
  59381. return getBorderThickness();
  59382. }
  59383. void ResizableWindow::moved()
  59384. {
  59385. updateLastPos();
  59386. }
  59387. void ResizableWindow::visibilityChanged()
  59388. {
  59389. TopLevelWindow::visibilityChanged();
  59390. updateLastPos();
  59391. }
  59392. void ResizableWindow::resized()
  59393. {
  59394. if (resizableBorder != 0)
  59395. {
  59396. resizableBorder->setVisible (! isFullScreen());
  59397. resizableBorder->setBorderThickness (getBorderThickness());
  59398. resizableBorder->setSize (getWidth(), getHeight());
  59399. resizableBorder->toBack();
  59400. }
  59401. if (resizableCorner != 0)
  59402. {
  59403. resizableCorner->setVisible (! isFullScreen());
  59404. const int resizerSize = 18;
  59405. resizableCorner->setBounds (getWidth() - resizerSize,
  59406. getHeight() - resizerSize,
  59407. resizerSize, resizerSize);
  59408. }
  59409. if (contentComponent != 0)
  59410. contentComponent->setBoundsInset (getContentComponentBorder());
  59411. updateLastPos();
  59412. #ifdef JUCE_DEBUG
  59413. hasBeenResized = true;
  59414. #endif
  59415. }
  59416. void ResizableWindow::childBoundsChanged (Component* child)
  59417. {
  59418. if ((child == contentComponent) && (child != 0) && resizeToFitContent)
  59419. {
  59420. // not going to look very good if this component has a zero size..
  59421. jassert (child->getWidth() > 0);
  59422. jassert (child->getHeight() > 0);
  59423. const BorderSize borders (getContentComponentBorder());
  59424. setSize (child->getWidth() + borders.getLeftAndRight(),
  59425. child->getHeight() + borders.getTopAndBottom());
  59426. }
  59427. }
  59428. void ResizableWindow::activeWindowStatusChanged()
  59429. {
  59430. const BorderSize borders (getContentComponentBorder());
  59431. repaint (0, 0, getWidth(), borders.getTop());
  59432. repaint (0, borders.getTop(), borders.getLeft(), getHeight() - borders.getBottom() - borders.getTop());
  59433. repaint (0, getHeight() - borders.getBottom(), getWidth(), borders.getBottom());
  59434. repaint (getWidth() - borders.getRight(), borders.getTop(), borders.getRight(), getHeight() - borders.getBottom() - borders.getTop());
  59435. }
  59436. void ResizableWindow::setResizable (const bool shouldBeResizable,
  59437. const bool useBottomRightCornerResizer)
  59438. {
  59439. if (shouldBeResizable)
  59440. {
  59441. if (useBottomRightCornerResizer)
  59442. {
  59443. deleteAndZero (resizableBorder);
  59444. if (resizableCorner == 0)
  59445. {
  59446. Component::addChildComponent (resizableCorner = new ResizableCornerComponent (this, constrainer));
  59447. resizableCorner->setAlwaysOnTop (true);
  59448. }
  59449. }
  59450. else
  59451. {
  59452. deleteAndZero (resizableCorner);
  59453. if (resizableBorder == 0)
  59454. Component::addChildComponent (resizableBorder = new ResizableBorderComponent (this, constrainer));
  59455. }
  59456. }
  59457. else
  59458. {
  59459. deleteAndZero (resizableCorner);
  59460. deleteAndZero (resizableBorder);
  59461. }
  59462. if (isUsingNativeTitleBar())
  59463. recreateDesktopWindow();
  59464. childBoundsChanged (contentComponent);
  59465. resized();
  59466. }
  59467. bool ResizableWindow::isResizable() const throw()
  59468. {
  59469. return resizableCorner != 0
  59470. || resizableBorder != 0;
  59471. }
  59472. void ResizableWindow::setResizeLimits (const int newMinimumWidth,
  59473. const int newMinimumHeight,
  59474. const int newMaximumWidth,
  59475. const int newMaximumHeight) throw()
  59476. {
  59477. // if you've set up a custom constrainer then these settings won't have any effect..
  59478. jassert (constrainer == &defaultConstrainer || constrainer == 0);
  59479. if (constrainer == 0)
  59480. setConstrainer (&defaultConstrainer);
  59481. defaultConstrainer.setSizeLimits (newMinimumWidth, newMinimumHeight,
  59482. newMaximumWidth, newMaximumHeight);
  59483. setBoundsConstrained (getX(), getY(), getWidth(), getHeight());
  59484. }
  59485. void ResizableWindow::setConstrainer (ComponentBoundsConstrainer* newConstrainer)
  59486. {
  59487. if (constrainer != newConstrainer)
  59488. {
  59489. constrainer = newConstrainer;
  59490. const bool useBottomRightCornerResizer = resizableCorner != 0;
  59491. const bool shouldBeResizable = useBottomRightCornerResizer || resizableBorder != 0;
  59492. deleteAndZero (resizableCorner);
  59493. deleteAndZero (resizableBorder);
  59494. setResizable (shouldBeResizable, useBottomRightCornerResizer);
  59495. ComponentPeer* const peer = getPeer();
  59496. if (peer != 0)
  59497. peer->setConstrainer (newConstrainer);
  59498. }
  59499. }
  59500. void ResizableWindow::setBoundsConstrained (int x, int y, int w, int h)
  59501. {
  59502. if (constrainer != 0)
  59503. constrainer->setBoundsForComponent (this, x, y, w, h, false, false, false, false);
  59504. else
  59505. setBounds (x, y, w, h);
  59506. }
  59507. void ResizableWindow::paint (Graphics& g)
  59508. {
  59509. getLookAndFeel().fillResizableWindowBackground (g, getWidth(), getHeight(),
  59510. getBorderThickness(), *this);
  59511. if (! isFullScreen())
  59512. {
  59513. getLookAndFeel().drawResizableWindowBorder (g, getWidth(), getHeight(),
  59514. getBorderThickness(), *this);
  59515. }
  59516. #ifdef JUCE_DEBUG
  59517. /* If this fails, then you've probably written a subclass with a resized()
  59518. callback but forgotten to make it call its parent class's resized() method.
  59519. It's important when you override methods like resized(), moved(),
  59520. etc., that you make sure the base class methods also get called.
  59521. Of course you shouldn't really be overriding ResizableWindow::resized() anyway,
  59522. because your content should all be inside the content component - and it's the
  59523. content component's resized() method that you should be using to do your
  59524. layout.
  59525. */
  59526. jassert (hasBeenResized || (getWidth() == 0 && getHeight() == 0));
  59527. #endif
  59528. }
  59529. void ResizableWindow::lookAndFeelChanged()
  59530. {
  59531. resized();
  59532. if (isOnDesktop())
  59533. {
  59534. Component::addToDesktop (getDesktopWindowStyleFlags());
  59535. ComponentPeer* const peer = getPeer();
  59536. if (peer != 0)
  59537. peer->setConstrainer (constrainer);
  59538. }
  59539. }
  59540. const Colour ResizableWindow::getBackgroundColour() const throw()
  59541. {
  59542. return findColour (backgroundColourId, false);
  59543. }
  59544. void ResizableWindow::setBackgroundColour (const Colour& newColour)
  59545. {
  59546. Colour backgroundColour (newColour);
  59547. if (! Desktop::canUseSemiTransparentWindows())
  59548. backgroundColour = newColour.withAlpha (1.0f);
  59549. setColour (backgroundColourId, backgroundColour);
  59550. setOpaque (backgroundColour.isOpaque());
  59551. repaint();
  59552. }
  59553. bool ResizableWindow::isFullScreen() const
  59554. {
  59555. if (isOnDesktop())
  59556. {
  59557. ComponentPeer* const peer = getPeer();
  59558. return peer != 0 && peer->isFullScreen();
  59559. }
  59560. return fullscreen;
  59561. }
  59562. void ResizableWindow::setFullScreen (const bool shouldBeFullScreen)
  59563. {
  59564. if (shouldBeFullScreen != isFullScreen())
  59565. {
  59566. updateLastPos();
  59567. fullscreen = shouldBeFullScreen;
  59568. if (isOnDesktop())
  59569. {
  59570. ComponentPeer* const peer = getPeer();
  59571. if (peer != 0)
  59572. {
  59573. // keep a copy of this intact in case the real one gets messed-up while we're un-maximising
  59574. const Rectangle lastPos (lastNonFullScreenPos);
  59575. peer->setFullScreen (shouldBeFullScreen);
  59576. if (! shouldBeFullScreen)
  59577. setBounds (lastPos);
  59578. }
  59579. else
  59580. {
  59581. jassertfalse
  59582. }
  59583. }
  59584. else
  59585. {
  59586. if (shouldBeFullScreen)
  59587. setBounds (0, 0, getParentWidth(), getParentHeight());
  59588. else
  59589. setBounds (lastNonFullScreenPos);
  59590. }
  59591. resized();
  59592. }
  59593. }
  59594. bool ResizableWindow::isMinimised() const
  59595. {
  59596. ComponentPeer* const peer = getPeer();
  59597. return (peer != 0) && peer->isMinimised();
  59598. }
  59599. void ResizableWindow::setMinimised (const bool shouldMinimise)
  59600. {
  59601. if (shouldMinimise != isMinimised())
  59602. {
  59603. ComponentPeer* const peer = getPeer();
  59604. if (peer != 0)
  59605. {
  59606. updateLastPos();
  59607. peer->setMinimised (shouldMinimise);
  59608. }
  59609. else
  59610. {
  59611. jassertfalse
  59612. }
  59613. }
  59614. }
  59615. void ResizableWindow::updateLastPos()
  59616. {
  59617. if (isShowing() && ! (isFullScreen() || isMinimised()))
  59618. {
  59619. lastNonFullScreenPos = getBounds();
  59620. }
  59621. }
  59622. void ResizableWindow::parentSizeChanged()
  59623. {
  59624. if (isFullScreen() && getParentComponent() != 0)
  59625. {
  59626. setBounds (0, 0, getParentWidth(), getParentHeight());
  59627. }
  59628. }
  59629. const String ResizableWindow::getWindowStateAsString()
  59630. {
  59631. updateLastPos();
  59632. String s;
  59633. if (isFullScreen())
  59634. s << "fs ";
  59635. s << lastNonFullScreenPos.getX() << T(' ')
  59636. << lastNonFullScreenPos.getY() << T(' ')
  59637. << lastNonFullScreenPos.getWidth() << T(' ')
  59638. << lastNonFullScreenPos.getHeight();
  59639. return s;
  59640. }
  59641. bool ResizableWindow::restoreWindowStateFromString (const String& s)
  59642. {
  59643. StringArray tokens;
  59644. tokens.addTokens (s, false);
  59645. tokens.removeEmptyStrings();
  59646. tokens.trim();
  59647. const bool fs = tokens[0].startsWithIgnoreCase (T("fs"));
  59648. const int n = fs ? 1 : 0;
  59649. if (tokens.size() != 4 + n)
  59650. return false;
  59651. Rectangle r (tokens[n].getIntValue(),
  59652. tokens[n + 1].getIntValue(),
  59653. tokens[n + 2].getIntValue(),
  59654. tokens[n + 3].getIntValue());
  59655. if (r.isEmpty())
  59656. return false;
  59657. const Rectangle screen (Desktop::getInstance().getMonitorAreaContaining (r.getX(), r.getY()));
  59658. if (! screen.contains (r))
  59659. {
  59660. r.setSize (jmin (r.getWidth(), screen.getWidth()),
  59661. jmin (r.getHeight(), screen.getHeight()));
  59662. r.setPosition (jlimit (screen.getX(), screen.getRight() - r.getWidth(), r.getX()),
  59663. jlimit (screen.getY(), screen.getBottom() - r.getHeight(), r.getY()));
  59664. }
  59665. lastNonFullScreenPos = r;
  59666. if (isOnDesktop())
  59667. {
  59668. ComponentPeer* const peer = getPeer();
  59669. if (peer != 0)
  59670. peer->setNonFullScreenBounds (r);
  59671. }
  59672. setFullScreen (fs);
  59673. if (! fs)
  59674. setBoundsConstrained (r.getX(),
  59675. r.getY(),
  59676. r.getWidth(),
  59677. r.getHeight());
  59678. return true;
  59679. }
  59680. void ResizableWindow::mouseDown (const MouseEvent&)
  59681. {
  59682. if (! isFullScreen())
  59683. dragger.startDraggingComponent (this, constrainer);
  59684. }
  59685. void ResizableWindow::mouseDrag (const MouseEvent& e)
  59686. {
  59687. if (! isFullScreen())
  59688. dragger.dragComponent (this, e);
  59689. }
  59690. #ifdef JUCE_DEBUG
  59691. void ResizableWindow::addChildComponent (Component* const child, int zOrder)
  59692. {
  59693. /* Agh! You shouldn't add components directly to a ResizableWindow - this class
  59694. manages its child components automatically, and if you add your own it'll cause
  59695. trouble. Instead, use setContentComponent() to give it a component which
  59696. will be automatically resized and kept in the right place - then you can add
  59697. subcomponents to the content comp. See the notes for the ResizableWindow class
  59698. for more info.
  59699. If you really know what you're doing and want to avoid this assertion, just call
  59700. Component::addChildComponent directly.
  59701. */
  59702. jassertfalse
  59703. Component::addChildComponent (child, zOrder);
  59704. }
  59705. void ResizableWindow::addAndMakeVisible (Component* const child, int zOrder)
  59706. {
  59707. /* Agh! You shouldn't add components directly to a ResizableWindow - this class
  59708. manages its child components automatically, and if you add your own it'll cause
  59709. trouble. Instead, use setContentComponent() to give it a component which
  59710. will be automatically resized and kept in the right place - then you can add
  59711. subcomponents to the content comp. See the notes for the ResizableWindow class
  59712. for more info.
  59713. If you really know what you're doing and want to avoid this assertion, just call
  59714. Component::addAndMakeVisible directly.
  59715. */
  59716. jassertfalse
  59717. Component::addAndMakeVisible (child, zOrder);
  59718. }
  59719. #endif
  59720. END_JUCE_NAMESPACE
  59721. /********* End of inlined file: juce_ResizableWindow.cpp *********/
  59722. /********* Start of inlined file: juce_SplashScreen.cpp *********/
  59723. BEGIN_JUCE_NAMESPACE
  59724. SplashScreen::SplashScreen()
  59725. : backgroundImage (0),
  59726. isImageInCache (false)
  59727. {
  59728. setOpaque (true);
  59729. }
  59730. SplashScreen::~SplashScreen()
  59731. {
  59732. if (isImageInCache)
  59733. ImageCache::release (backgroundImage);
  59734. else
  59735. delete backgroundImage;
  59736. }
  59737. void SplashScreen::show (const String& title,
  59738. Image* const backgroundImage_,
  59739. const int minimumTimeToDisplayFor,
  59740. const bool useDropShadow,
  59741. const bool removeOnMouseClick)
  59742. {
  59743. backgroundImage = backgroundImage_;
  59744. jassert (backgroundImage_ != 0);
  59745. if (backgroundImage_ != 0)
  59746. {
  59747. isImageInCache = ImageCache::isImageInCache (backgroundImage_);
  59748. setOpaque (! backgroundImage_->hasAlphaChannel());
  59749. show (title,
  59750. backgroundImage_->getWidth(),
  59751. backgroundImage_->getHeight(),
  59752. minimumTimeToDisplayFor,
  59753. useDropShadow,
  59754. removeOnMouseClick);
  59755. }
  59756. }
  59757. void SplashScreen::show (const String& title,
  59758. const int width,
  59759. const int height,
  59760. const int minimumTimeToDisplayFor,
  59761. const bool useDropShadow,
  59762. const bool removeOnMouseClick)
  59763. {
  59764. setName (title);
  59765. setAlwaysOnTop (true);
  59766. setVisible (true);
  59767. centreWithSize (width, height);
  59768. addToDesktop (useDropShadow ? ComponentPeer::windowHasDropShadow : 0);
  59769. toFront (false);
  59770. MessageManager::getInstance()->runDispatchLoopUntil (300);
  59771. repaint();
  59772. originalClickCounter = removeOnMouseClick
  59773. ? Desktop::getMouseButtonClickCounter()
  59774. : INT_MAX;
  59775. earliestTimeToDelete = Time::getCurrentTime() + RelativeTime::milliseconds (minimumTimeToDisplayFor);
  59776. startTimer (50);
  59777. }
  59778. void SplashScreen::paint (Graphics& g)
  59779. {
  59780. if (backgroundImage != 0)
  59781. {
  59782. g.setOpacity (1.0f);
  59783. g.drawImage (backgroundImage,
  59784. 0, 0, getWidth(), getHeight(),
  59785. 0, 0, backgroundImage->getWidth(), backgroundImage->getHeight());
  59786. }
  59787. }
  59788. void SplashScreen::timerCallback()
  59789. {
  59790. if (Time::getCurrentTime() > earliestTimeToDelete
  59791. || Desktop::getMouseButtonClickCounter() > originalClickCounter)
  59792. {
  59793. delete this;
  59794. }
  59795. }
  59796. END_JUCE_NAMESPACE
  59797. /********* End of inlined file: juce_SplashScreen.cpp *********/
  59798. /********* Start of inlined file: juce_ThreadWithProgressWindow.cpp *********/
  59799. BEGIN_JUCE_NAMESPACE
  59800. ThreadWithProgressWindow::ThreadWithProgressWindow (const String& title,
  59801. const bool hasProgressBar,
  59802. const bool hasCancelButton,
  59803. const int timeOutMsWhenCancelling_,
  59804. const String& cancelButtonText)
  59805. : Thread ("Juce Progress Window"),
  59806. progress (0.0),
  59807. timeOutMsWhenCancelling (timeOutMsWhenCancelling_)
  59808. {
  59809. alertWindow = LookAndFeel::getDefaultLookAndFeel()
  59810. .createAlertWindow (title, String::empty, cancelButtonText,
  59811. String::empty, String::empty,
  59812. AlertWindow::NoIcon, hasCancelButton ? 1 : 0, 0);
  59813. if (hasProgressBar)
  59814. alertWindow->addProgressBarComponent (progress);
  59815. }
  59816. ThreadWithProgressWindow::~ThreadWithProgressWindow()
  59817. {
  59818. stopThread (timeOutMsWhenCancelling);
  59819. delete alertWindow;
  59820. }
  59821. bool ThreadWithProgressWindow::runThread (const int priority)
  59822. {
  59823. startThread (priority);
  59824. startTimer (100);
  59825. {
  59826. const ScopedLock sl (messageLock);
  59827. alertWindow->setMessage (message);
  59828. }
  59829. const bool finishedNaturally = alertWindow->runModalLoop() != 0;
  59830. stopThread (timeOutMsWhenCancelling);
  59831. alertWindow->setVisible (false);
  59832. return finishedNaturally;
  59833. }
  59834. void ThreadWithProgressWindow::setProgress (const double newProgress)
  59835. {
  59836. progress = newProgress;
  59837. }
  59838. void ThreadWithProgressWindow::setStatusMessage (const String& newStatusMessage)
  59839. {
  59840. const ScopedLock sl (messageLock);
  59841. message = newStatusMessage;
  59842. }
  59843. void ThreadWithProgressWindow::timerCallback()
  59844. {
  59845. if (! isThreadRunning())
  59846. {
  59847. // thread has finished normally..
  59848. alertWindow->exitModalState (1);
  59849. alertWindow->setVisible (false);
  59850. }
  59851. else
  59852. {
  59853. const ScopedLock sl (messageLock);
  59854. alertWindow->setMessage (message);
  59855. }
  59856. }
  59857. END_JUCE_NAMESPACE
  59858. /********* End of inlined file: juce_ThreadWithProgressWindow.cpp *********/
  59859. /********* Start of inlined file: juce_TooltipWindow.cpp *********/
  59860. BEGIN_JUCE_NAMESPACE
  59861. TooltipWindow::TooltipWindow (Component* const parentComponent,
  59862. const int millisecondsBeforeTipAppears_)
  59863. : Component ("tooltip"),
  59864. millisecondsBeforeTipAppears (millisecondsBeforeTipAppears_),
  59865. mouseX (0),
  59866. mouseY (0),
  59867. lastHideTime (0),
  59868. lastComponentUnderMouse (0),
  59869. changedCompsSinceShown (true)
  59870. {
  59871. startTimer (123);
  59872. setAlwaysOnTop (true);
  59873. setOpaque (true);
  59874. if (parentComponent != 0)
  59875. parentComponent->addChildComponent (this);
  59876. }
  59877. TooltipWindow::~TooltipWindow()
  59878. {
  59879. hide();
  59880. }
  59881. void TooltipWindow::setMillisecondsBeforeTipAppears (const int newTimeMs) throw()
  59882. {
  59883. millisecondsBeforeTipAppears = newTimeMs;
  59884. }
  59885. void TooltipWindow::paint (Graphics& g)
  59886. {
  59887. getLookAndFeel().drawTooltip (g, tipShowing, getWidth(), getHeight());
  59888. }
  59889. void TooltipWindow::mouseEnter (const MouseEvent&)
  59890. {
  59891. hide();
  59892. }
  59893. void TooltipWindow::showFor (Component* const c, const String& tip)
  59894. {
  59895. jassert (tip.isNotEmpty());
  59896. tipShowing = tip;
  59897. int mx, my;
  59898. Desktop::getMousePosition (mx, my);
  59899. if (getParentComponent() != 0)
  59900. getParentComponent()->globalPositionToRelative (mx, my);
  59901. int x, y, w, h;
  59902. getLookAndFeel().getTooltipSize (tip, w, h);
  59903. if (mx > getParentWidth() / 2)
  59904. x = mx - (w + 12);
  59905. else
  59906. x = mx + 24;
  59907. if (my > getParentHeight() / 2)
  59908. y = my - (h + 6);
  59909. else
  59910. y = my + 6;
  59911. setBounds (x, y, w, h);
  59912. setVisible (true);
  59913. if (getParentComponent() == 0)
  59914. {
  59915. addToDesktop (ComponentPeer::windowHasDropShadow
  59916. | ComponentPeer::windowIsTemporary
  59917. | ComponentPeer::windowIgnoresKeyPresses);
  59918. }
  59919. toFront (false);
  59920. }
  59921. const String TooltipWindow::getTipFor (Component* const c)
  59922. {
  59923. if (c->isValidComponent()
  59924. && Process::isForegroundProcess()
  59925. && ! Component::isMouseButtonDownAnywhere())
  59926. {
  59927. TooltipClient* const ttc = dynamic_cast <TooltipClient*> (c);
  59928. if (ttc != 0 && ! c->isCurrentlyBlockedByAnotherModalComponent())
  59929. return ttc->getTooltip();
  59930. }
  59931. return String::empty;
  59932. }
  59933. void TooltipWindow::hide()
  59934. {
  59935. tipShowing = String::empty;
  59936. removeFromDesktop();
  59937. setVisible (false);
  59938. }
  59939. void TooltipWindow::timerCallback()
  59940. {
  59941. const unsigned int now = Time::getApproximateMillisecondCounter();
  59942. Component* const newComp = Component::getComponentUnderMouse();
  59943. const String newTip (getTipFor (newComp));
  59944. const bool tipChanged = (newTip != lastTipUnderMouse || newComp != lastComponentUnderMouse);
  59945. lastComponentUnderMouse = newComp;
  59946. lastTipUnderMouse = newTip;
  59947. const int clickCount = Desktop::getInstance().getMouseButtonClickCounter();
  59948. const bool mouseWasClicked = clickCount > mouseClicks;
  59949. mouseClicks = clickCount;
  59950. int mx, my;
  59951. Desktop::getMousePosition (mx, my);
  59952. const bool mouseMovedQuickly = (abs (mx - mouseX) + abs (my - mouseY) > 12);
  59953. mouseX = mx;
  59954. mouseY = my;
  59955. if (tipChanged || mouseWasClicked || mouseMovedQuickly)
  59956. lastCompChangeTime = now;
  59957. if (isVisible() || now < lastHideTime + 500)
  59958. {
  59959. // if a tip is currently visible (or has just disappeared), update to a new one
  59960. // immediately if needed..
  59961. if (newComp == 0 || mouseWasClicked || newTip.isEmpty())
  59962. {
  59963. if (isVisible())
  59964. {
  59965. lastHideTime = now;
  59966. hide();
  59967. }
  59968. }
  59969. else if (tipChanged)
  59970. {
  59971. showFor (newComp, newTip);
  59972. }
  59973. }
  59974. else
  59975. {
  59976. // if there isn't currently a tip, but one is needed, only let it
  59977. // appear after a timeout..
  59978. if (newTip.isNotEmpty()
  59979. && newTip != tipShowing
  59980. && now > lastCompChangeTime + millisecondsBeforeTipAppears)
  59981. {
  59982. showFor (newComp, newTip);
  59983. }
  59984. }
  59985. }
  59986. END_JUCE_NAMESPACE
  59987. /********* End of inlined file: juce_TooltipWindow.cpp *********/
  59988. /********* Start of inlined file: juce_TopLevelWindow.cpp *********/
  59989. BEGIN_JUCE_NAMESPACE
  59990. /** Keeps track of the active top level window.
  59991. */
  59992. class TopLevelWindowManager : public Timer,
  59993. public DeletedAtShutdown
  59994. {
  59995. public:
  59996. TopLevelWindowManager()
  59997. : windows (8),
  59998. currentActive (0)
  59999. {
  60000. }
  60001. ~TopLevelWindowManager()
  60002. {
  60003. clearSingletonInstance();
  60004. }
  60005. juce_DeclareSingleton_SingleThreaded_Minimal (TopLevelWindowManager)
  60006. void timerCallback()
  60007. {
  60008. startTimer (jmin (1731, getTimerInterval() * 2));
  60009. TopLevelWindow* active = 0;
  60010. if (Process::isForegroundProcess())
  60011. {
  60012. active = currentActive;
  60013. Component* const c = Component::getCurrentlyFocusedComponent();
  60014. TopLevelWindow* tlw = dynamic_cast <TopLevelWindow*> (c);
  60015. if (tlw == 0 && c != 0)
  60016. // (unable to use the syntax findParentComponentOfClass <TopLevelWindow> () because of a VC6 compiler bug)
  60017. tlw = c->findParentComponentOfClass ((TopLevelWindow*) 0);
  60018. if (tlw != 0)
  60019. active = tlw;
  60020. }
  60021. if (active != currentActive)
  60022. {
  60023. currentActive = active;
  60024. for (int i = windows.size(); --i >= 0;)
  60025. {
  60026. TopLevelWindow* const tlw = (TopLevelWindow*) windows.getUnchecked (i);
  60027. tlw->setWindowActive (isWindowActive (tlw));
  60028. i = jmin (i, windows.size() - 1);
  60029. }
  60030. Desktop::getInstance().triggerFocusCallback();
  60031. }
  60032. }
  60033. bool addWindow (TopLevelWindow* const w) throw()
  60034. {
  60035. windows.add (w);
  60036. startTimer (10);
  60037. return isWindowActive (w);
  60038. }
  60039. void removeWindow (TopLevelWindow* const w) throw()
  60040. {
  60041. startTimer (10);
  60042. if (currentActive == w)
  60043. currentActive = 0;
  60044. windows.removeValue (w);
  60045. if (windows.size() == 0)
  60046. deleteInstance();
  60047. }
  60048. VoidArray windows;
  60049. private:
  60050. TopLevelWindow* currentActive;
  60051. bool isWindowActive (TopLevelWindow* const tlw) const throw()
  60052. {
  60053. return (tlw == currentActive
  60054. || tlw->isParentOf (currentActive)
  60055. || tlw->hasKeyboardFocus (true))
  60056. && tlw->isShowing();
  60057. }
  60058. TopLevelWindowManager (const TopLevelWindowManager&);
  60059. const TopLevelWindowManager& operator= (const TopLevelWindowManager&);
  60060. };
  60061. juce_ImplementSingleton_SingleThreaded (TopLevelWindowManager)
  60062. void juce_CheckCurrentlyFocusedTopLevelWindow() throw()
  60063. {
  60064. if (TopLevelWindowManager::getInstanceWithoutCreating() != 0)
  60065. TopLevelWindowManager::getInstanceWithoutCreating()->startTimer (20);
  60066. }
  60067. TopLevelWindow::TopLevelWindow (const String& name,
  60068. const bool addToDesktop_)
  60069. : Component (name),
  60070. useDropShadow (true),
  60071. useNativeTitleBar (false),
  60072. windowIsActive_ (false),
  60073. shadower (0)
  60074. {
  60075. setOpaque (true);
  60076. if (addToDesktop_)
  60077. Component::addToDesktop (getDesktopWindowStyleFlags());
  60078. else
  60079. setDropShadowEnabled (true);
  60080. setWantsKeyboardFocus (true);
  60081. setBroughtToFrontOnMouseClick (true);
  60082. windowIsActive_ = TopLevelWindowManager::getInstance()->addWindow (this);
  60083. }
  60084. TopLevelWindow::~TopLevelWindow()
  60085. {
  60086. deleteAndZero (shadower);
  60087. TopLevelWindowManager::getInstance()->removeWindow (this);
  60088. }
  60089. void TopLevelWindow::focusOfChildComponentChanged (FocusChangeType)
  60090. {
  60091. if (hasKeyboardFocus (true))
  60092. TopLevelWindowManager::getInstance()->timerCallback();
  60093. else
  60094. TopLevelWindowManager::getInstance()->startTimer (10);
  60095. }
  60096. void TopLevelWindow::setWindowActive (const bool isNowActive) throw()
  60097. {
  60098. if (windowIsActive_ != isNowActive)
  60099. {
  60100. windowIsActive_ = isNowActive;
  60101. activeWindowStatusChanged();
  60102. }
  60103. }
  60104. void TopLevelWindow::activeWindowStatusChanged()
  60105. {
  60106. }
  60107. void TopLevelWindow::parentHierarchyChanged()
  60108. {
  60109. setDropShadowEnabled (useDropShadow);
  60110. }
  60111. void TopLevelWindow::visibilityChanged()
  60112. {
  60113. if (isShowing())
  60114. toFront (true);
  60115. }
  60116. int TopLevelWindow::getDesktopWindowStyleFlags() const
  60117. {
  60118. int flags = ComponentPeer::windowAppearsOnTaskbar;
  60119. if (useDropShadow)
  60120. flags |= ComponentPeer::windowHasDropShadow;
  60121. if (useNativeTitleBar)
  60122. flags |= ComponentPeer::windowHasTitleBar;
  60123. return flags;
  60124. }
  60125. void TopLevelWindow::setDropShadowEnabled (const bool useShadow)
  60126. {
  60127. useDropShadow = useShadow;
  60128. if (isOnDesktop())
  60129. {
  60130. deleteAndZero (shadower);
  60131. Component::addToDesktop (getDesktopWindowStyleFlags());
  60132. }
  60133. else
  60134. {
  60135. if (useShadow && isOpaque())
  60136. {
  60137. if (shadower == 0)
  60138. {
  60139. shadower = getLookAndFeel().createDropShadowerForComponent (this);
  60140. if (shadower != 0)
  60141. shadower->setOwner (this);
  60142. }
  60143. }
  60144. else
  60145. {
  60146. deleteAndZero (shadower);
  60147. }
  60148. }
  60149. }
  60150. void TopLevelWindow::setUsingNativeTitleBar (const bool useNativeTitleBar_)
  60151. {
  60152. if (useNativeTitleBar != useNativeTitleBar_)
  60153. {
  60154. useNativeTitleBar = useNativeTitleBar_;
  60155. recreateDesktopWindow();
  60156. sendLookAndFeelChange();
  60157. }
  60158. }
  60159. void TopLevelWindow::recreateDesktopWindow()
  60160. {
  60161. if (isOnDesktop())
  60162. {
  60163. Component::addToDesktop (getDesktopWindowStyleFlags());
  60164. toFront (true);
  60165. }
  60166. }
  60167. void TopLevelWindow::addToDesktop (int windowStyleFlags, void* nativeWindowToAttachTo)
  60168. {
  60169. /* It's not recommended to change the desktop window flags directly for a TopLevelWindow,
  60170. because this class needs to make sure its layout corresponds with settings like whether
  60171. it's got a native title bar or not.
  60172. If you need custom flags for your window, you can override the getDesktopWindowStyleFlags()
  60173. method. If you do this, it's best to call the base class's getDesktopWindowStyleFlags()
  60174. method, then add or remove whatever flags are necessary from this value before returning it.
  60175. */
  60176. jassert ((windowStyleFlags & ~ComponentPeer::windowIsSemiTransparent)
  60177. == (getDesktopWindowStyleFlags() & ~ComponentPeer::windowIsSemiTransparent));
  60178. Component::addToDesktop (windowStyleFlags, nativeWindowToAttachTo);
  60179. if (windowStyleFlags != getDesktopWindowStyleFlags())
  60180. sendLookAndFeelChange();
  60181. }
  60182. void TopLevelWindow::centreAroundComponent (Component* c, const int width, const int height)
  60183. {
  60184. if (c == 0)
  60185. c = TopLevelWindow::getActiveTopLevelWindow();
  60186. if (c == 0)
  60187. {
  60188. centreWithSize (width, height);
  60189. }
  60190. else
  60191. {
  60192. int x = (c->getWidth() - width) / 2;
  60193. int y = (c->getHeight() - height) / 2;
  60194. c->relativePositionToGlobal (x, y);
  60195. Rectangle parentArea (c->getParentMonitorArea());
  60196. if (getParentComponent() != 0)
  60197. {
  60198. getParentComponent()->globalPositionToRelative (x, y);
  60199. parentArea.setBounds (0, 0, getParentWidth(), getParentHeight());
  60200. }
  60201. parentArea.reduce (12, 12);
  60202. setBounds (jlimit (parentArea.getX(), jmax (parentArea.getX(), parentArea.getRight() - width), x),
  60203. jlimit (parentArea.getY(), jmax (parentArea.getY(), parentArea.getBottom() - height), y),
  60204. width, height);
  60205. }
  60206. }
  60207. int TopLevelWindow::getNumTopLevelWindows() throw()
  60208. {
  60209. return TopLevelWindowManager::getInstance()->windows.size();
  60210. }
  60211. TopLevelWindow* TopLevelWindow::getTopLevelWindow (const int index) throw()
  60212. {
  60213. return (TopLevelWindow*) TopLevelWindowManager::getInstance()->windows [index];
  60214. }
  60215. TopLevelWindow* TopLevelWindow::getActiveTopLevelWindow() throw()
  60216. {
  60217. TopLevelWindow* best = 0;
  60218. int bestNumTWLParents = -1;
  60219. for (int i = TopLevelWindow::getNumTopLevelWindows(); --i >= 0;)
  60220. {
  60221. TopLevelWindow* const tlw = TopLevelWindow::getTopLevelWindow (i);
  60222. if (tlw->isActiveWindow())
  60223. {
  60224. int numTWLParents = 0;
  60225. const Component* c = tlw->getParentComponent();
  60226. while (c != 0)
  60227. {
  60228. if (dynamic_cast <const TopLevelWindow*> (c) != 0)
  60229. ++numTWLParents;
  60230. c = c->getParentComponent();
  60231. }
  60232. if (bestNumTWLParents < numTWLParents)
  60233. {
  60234. best = tlw;
  60235. bestNumTWLParents = numTWLParents;
  60236. }
  60237. }
  60238. }
  60239. return best;
  60240. }
  60241. END_JUCE_NAMESPACE
  60242. /********* End of inlined file: juce_TopLevelWindow.cpp *********/
  60243. /********* Start of inlined file: juce_Brush.cpp *********/
  60244. BEGIN_JUCE_NAMESPACE
  60245. Brush::Brush() throw()
  60246. {
  60247. }
  60248. Brush::~Brush() throw()
  60249. {
  60250. }
  60251. void Brush::paintVerticalLine (LowLevelGraphicsContext& context,
  60252. int x, float y1, float y2) throw()
  60253. {
  60254. Path p;
  60255. p.addRectangle ((float) x, y1, 1.0f, y2 - y1);
  60256. paintPath (context, p, AffineTransform::identity);
  60257. }
  60258. void Brush::paintHorizontalLine (LowLevelGraphicsContext& context,
  60259. int y, float x1, float x2) throw()
  60260. {
  60261. Path p;
  60262. p.addRectangle (x1, (float) y, x2 - x1, 1.0f);
  60263. paintPath (context, p, AffineTransform::identity);
  60264. }
  60265. void Brush::paintLine (LowLevelGraphicsContext& context,
  60266. float x1, float y1, float x2, float y2) throw()
  60267. {
  60268. Path p;
  60269. p.addLineSegment (x1, y1, x2, y2, 1.0f);
  60270. paintPath (context, p, AffineTransform::identity);
  60271. }
  60272. END_JUCE_NAMESPACE
  60273. /********* End of inlined file: juce_Brush.cpp *********/
  60274. /********* Start of inlined file: juce_GradientBrush.cpp *********/
  60275. BEGIN_JUCE_NAMESPACE
  60276. GradientBrush::GradientBrush (const Colour& colour1,
  60277. const float x1,
  60278. const float y1,
  60279. const Colour& colour2,
  60280. const float x2,
  60281. const float y2,
  60282. const bool isRadial) throw()
  60283. : gradient (colour1, x1, y1,
  60284. colour2, x2, y2,
  60285. isRadial)
  60286. {
  60287. }
  60288. GradientBrush::GradientBrush (const ColourGradient& gradient_) throw()
  60289. : gradient (gradient_)
  60290. {
  60291. }
  60292. GradientBrush::~GradientBrush() throw()
  60293. {
  60294. }
  60295. Brush* GradientBrush::createCopy() const throw()
  60296. {
  60297. return new GradientBrush (gradient);
  60298. }
  60299. void GradientBrush::applyTransform (const AffineTransform& transform) throw()
  60300. {
  60301. gradient.transform = gradient.transform.followedBy (transform);
  60302. }
  60303. void GradientBrush::multiplyOpacity (const float multiple) throw()
  60304. {
  60305. gradient.multiplyOpacity (multiple);
  60306. }
  60307. bool GradientBrush::isInvisible() const throw()
  60308. {
  60309. return gradient.isInvisible();
  60310. }
  60311. void GradientBrush::paintPath (LowLevelGraphicsContext& context,
  60312. const Path& path, const AffineTransform& transform) throw()
  60313. {
  60314. context.fillPathWithGradient (path, transform, gradient, EdgeTable::Oversampling_4times);
  60315. }
  60316. void GradientBrush::paintRectangle (LowLevelGraphicsContext& context,
  60317. int x, int y, int w, int h) throw()
  60318. {
  60319. context.fillRectWithGradient (x, y, w, h, gradient);
  60320. }
  60321. void GradientBrush::paintAlphaChannel (LowLevelGraphicsContext& context,
  60322. const Image& alphaChannelImage, int imageX, int imageY,
  60323. int x, int y, int w, int h) throw()
  60324. {
  60325. context.saveState();
  60326. if (context.reduceClipRegion (x, y, w, h))
  60327. context.fillAlphaChannelWithGradient (alphaChannelImage, imageX, imageY, gradient);
  60328. context.restoreState();
  60329. }
  60330. END_JUCE_NAMESPACE
  60331. /********* End of inlined file: juce_GradientBrush.cpp *********/
  60332. /********* Start of inlined file: juce_ImageBrush.cpp *********/
  60333. BEGIN_JUCE_NAMESPACE
  60334. ImageBrush::ImageBrush (Image* const image_,
  60335. const int anchorX_,
  60336. const int anchorY_,
  60337. const float opacity_) throw()
  60338. : image (image_),
  60339. anchorX (anchorX_),
  60340. anchorY (anchorY_),
  60341. opacity (opacity_)
  60342. {
  60343. jassert (image != 0); // not much point creating a brush without an image, is there?
  60344. if (image != 0)
  60345. {
  60346. if (image->getWidth() == 0 || image->getHeight() == 0)
  60347. {
  60348. jassertfalse // you've passed in an empty image - not exactly brilliant for tiling.
  60349. image = 0;
  60350. }
  60351. }
  60352. }
  60353. ImageBrush::~ImageBrush() throw()
  60354. {
  60355. }
  60356. Brush* ImageBrush::createCopy() const throw()
  60357. {
  60358. return new ImageBrush (image, anchorX, anchorY, opacity);
  60359. }
  60360. void ImageBrush::multiplyOpacity (const float multiple) throw()
  60361. {
  60362. opacity *= multiple;
  60363. }
  60364. bool ImageBrush::isInvisible() const throw()
  60365. {
  60366. return opacity == 0.0f;
  60367. }
  60368. void ImageBrush::applyTransform (const AffineTransform& /*transform*/) throw()
  60369. {
  60370. //xxx should probably be smarter and warp the image
  60371. }
  60372. void ImageBrush::getStartXY (int& x, int& y) const throw()
  60373. {
  60374. x -= anchorX;
  60375. y -= anchorY;
  60376. const int iw = image->getWidth();
  60377. const int ih = image->getHeight();
  60378. if (x < 0)
  60379. x = ((x / iw) - 1) * iw;
  60380. else
  60381. x = (x / iw) * iw;
  60382. if (y < 0)
  60383. y = ((y / ih) - 1) * ih;
  60384. else
  60385. y = (y / ih) * ih;
  60386. x += anchorX;
  60387. y += anchorY;
  60388. }
  60389. void ImageBrush::paintRectangle (LowLevelGraphicsContext& context,
  60390. int x, int y, int w, int h) throw()
  60391. {
  60392. context.saveState();
  60393. if (image != 0 && context.reduceClipRegion (x, y, w, h))
  60394. {
  60395. const int right = x + w;
  60396. const int bottom = y + h;
  60397. const int iw = image->getWidth();
  60398. const int ih = image->getHeight();
  60399. int startX = x;
  60400. getStartXY (startX, y);
  60401. while (y < bottom)
  60402. {
  60403. x = startX;
  60404. while (x < right)
  60405. {
  60406. context.blendImage (*image, x, y, iw, ih, 0, 0, opacity);
  60407. x += iw;
  60408. }
  60409. y += ih;
  60410. }
  60411. }
  60412. context.restoreState();
  60413. }
  60414. void ImageBrush::paintPath (LowLevelGraphicsContext& context,
  60415. const Path& path, const AffineTransform& transform) throw()
  60416. {
  60417. if (image != 0)
  60418. {
  60419. Rectangle clip (context.getClipBounds());
  60420. {
  60421. float x, y, w, h;
  60422. path.getBoundsTransformed (transform, x, y, w, h);
  60423. clip = clip.getIntersection (Rectangle ((int) floorf (x),
  60424. (int) floorf (y),
  60425. 2 + (int) floorf (w),
  60426. 2 + (int) floorf (h)));
  60427. }
  60428. int x = clip.getX();
  60429. int y = clip.getY();
  60430. const int right = clip.getRight();
  60431. const int bottom = clip.getBottom();
  60432. const int iw = image->getWidth();
  60433. const int ih = image->getHeight();
  60434. int startX = x;
  60435. getStartXY (startX, y);
  60436. while (y < bottom)
  60437. {
  60438. x = startX;
  60439. while (x < right)
  60440. {
  60441. context.fillPathWithImage (path, transform, *image, x, y, opacity, EdgeTable::Oversampling_4times);
  60442. x += iw;
  60443. }
  60444. y += ih;
  60445. }
  60446. }
  60447. }
  60448. void ImageBrush::paintAlphaChannel (LowLevelGraphicsContext& context,
  60449. const Image& alphaChannelImage, int imageX, int imageY,
  60450. int x, int y, int w, int h) throw()
  60451. {
  60452. context.saveState();
  60453. if (image != 0 && context.reduceClipRegion (x, y, w, h))
  60454. {
  60455. const Rectangle clip (context.getClipBounds());
  60456. x = clip.getX();
  60457. y = clip.getY();
  60458. const int right = clip.getRight();
  60459. const int bottom = clip.getBottom();
  60460. const int iw = image->getWidth();
  60461. const int ih = image->getHeight();
  60462. int startX = x;
  60463. getStartXY (startX, y);
  60464. while (y < bottom)
  60465. {
  60466. x = startX;
  60467. while (x < right)
  60468. {
  60469. context.fillAlphaChannelWithImage (alphaChannelImage,
  60470. imageX, imageY, *image,
  60471. x, y, opacity);
  60472. x += iw;
  60473. }
  60474. y += ih;
  60475. }
  60476. }
  60477. context.restoreState();
  60478. }
  60479. END_JUCE_NAMESPACE
  60480. /********* End of inlined file: juce_ImageBrush.cpp *********/
  60481. /********* Start of inlined file: juce_SolidColourBrush.cpp *********/
  60482. BEGIN_JUCE_NAMESPACE
  60483. SolidColourBrush::SolidColourBrush() throw()
  60484. : colour (0xff000000)
  60485. {
  60486. }
  60487. SolidColourBrush::SolidColourBrush (const Colour& colour_) throw()
  60488. : colour (colour_)
  60489. {
  60490. }
  60491. SolidColourBrush::~SolidColourBrush() throw()
  60492. {
  60493. }
  60494. Brush* SolidColourBrush::createCopy() const throw()
  60495. {
  60496. return new SolidColourBrush (colour);
  60497. }
  60498. void SolidColourBrush::applyTransform (const AffineTransform& /*transform*/) throw()
  60499. {
  60500. }
  60501. void SolidColourBrush::multiplyOpacity (const float multiple) throw()
  60502. {
  60503. colour = colour.withMultipliedAlpha (multiple);
  60504. }
  60505. bool SolidColourBrush::isInvisible() const throw()
  60506. {
  60507. return colour.isTransparent();
  60508. }
  60509. void SolidColourBrush::paintPath (LowLevelGraphicsContext& context,
  60510. const Path& path, const AffineTransform& transform) throw()
  60511. {
  60512. if (! colour.isTransparent())
  60513. context.fillPathWithColour (path, transform, colour, EdgeTable::Oversampling_4times);
  60514. }
  60515. void SolidColourBrush::paintRectangle (LowLevelGraphicsContext& context,
  60516. int x, int y, int w, int h) throw()
  60517. {
  60518. if (! colour.isTransparent())
  60519. context.fillRectWithColour (x, y, w, h, colour, false);
  60520. }
  60521. void SolidColourBrush::paintAlphaChannel (LowLevelGraphicsContext& context,
  60522. const Image& alphaChannelImage, int imageX, int imageY,
  60523. int x, int y, int w, int h) throw()
  60524. {
  60525. if (! colour.isTransparent())
  60526. {
  60527. context.saveState();
  60528. if (context.reduceClipRegion (x, y, w, h))
  60529. context.fillAlphaChannelWithColour (alphaChannelImage, imageX, imageY, colour);
  60530. context.restoreState();
  60531. }
  60532. }
  60533. void SolidColourBrush::paintVerticalLine (LowLevelGraphicsContext& context,
  60534. int x, float y1, float y2) throw()
  60535. {
  60536. context.drawVerticalLine (x, y1, y2, colour);
  60537. }
  60538. void SolidColourBrush::paintHorizontalLine (LowLevelGraphicsContext& context,
  60539. int y, float x1, float x2) throw()
  60540. {
  60541. context.drawHorizontalLine (y, x1, x2, colour);
  60542. }
  60543. void SolidColourBrush::paintLine (LowLevelGraphicsContext& context,
  60544. float x1, float y1, float x2, float y2) throw()
  60545. {
  60546. context.drawLine (x1, y1, x2, y2, colour);
  60547. }
  60548. END_JUCE_NAMESPACE
  60549. /********* End of inlined file: juce_SolidColourBrush.cpp *********/
  60550. /********* Start of inlined file: juce_Colour.cpp *********/
  60551. BEGIN_JUCE_NAMESPACE
  60552. static forcedinline uint8 floatAlphaToInt (const float alpha)
  60553. {
  60554. return (uint8) jlimit (0, 0xff, roundFloatToInt (alpha * 255.0f));
  60555. }
  60556. static const float oneOver255 = 1.0f / 255.0f;
  60557. Colour::Colour() throw()
  60558. : argb (0)
  60559. {
  60560. }
  60561. Colour::Colour (const Colour& other) throw()
  60562. : argb (other.argb)
  60563. {
  60564. }
  60565. const Colour& Colour::operator= (const Colour& other) throw()
  60566. {
  60567. argb = other.argb;
  60568. return *this;
  60569. }
  60570. bool Colour::operator== (const Colour& other) const throw()
  60571. {
  60572. return argb.getARGB() == other.argb.getARGB();
  60573. }
  60574. bool Colour::operator!= (const Colour& other) const throw()
  60575. {
  60576. return argb.getARGB() != other.argb.getARGB();
  60577. }
  60578. Colour::Colour (const uint32 argb_) throw()
  60579. : argb (argb_)
  60580. {
  60581. }
  60582. Colour::Colour (const uint8 red,
  60583. const uint8 green,
  60584. const uint8 blue) throw()
  60585. {
  60586. argb.setARGB (0xff, red, green, blue);
  60587. }
  60588. const Colour Colour::fromRGB (const uint8 red,
  60589. const uint8 green,
  60590. const uint8 blue) throw()
  60591. {
  60592. return Colour (red, green, blue);
  60593. }
  60594. Colour::Colour (const uint8 red,
  60595. const uint8 green,
  60596. const uint8 blue,
  60597. const uint8 alpha) throw()
  60598. {
  60599. argb.setARGB (alpha, red, green, blue);
  60600. }
  60601. const Colour Colour::fromRGBA (const uint8 red,
  60602. const uint8 green,
  60603. const uint8 blue,
  60604. const uint8 alpha) throw()
  60605. {
  60606. return Colour (red, green, blue, alpha);
  60607. }
  60608. Colour::Colour (const uint8 red,
  60609. const uint8 green,
  60610. const uint8 blue,
  60611. const float alpha) throw()
  60612. {
  60613. argb.setARGB (floatAlphaToInt (alpha), red, green, blue);
  60614. }
  60615. const Colour Colour::fromRGBAFloat (const uint8 red,
  60616. const uint8 green,
  60617. const uint8 blue,
  60618. const float alpha) throw()
  60619. {
  60620. return Colour (red, green, blue, alpha);
  60621. }
  60622. static void convertHSBtoRGB (float h, float s, float v,
  60623. uint8& r, uint8& g, uint8& b) throw()
  60624. {
  60625. v = jlimit (0.0f, 1.0f, v);
  60626. v *= 255.0f;
  60627. const uint8 intV = (uint8) roundFloatToInt (v);
  60628. if (s <= 0)
  60629. {
  60630. r = intV;
  60631. g = intV;
  60632. b = intV;
  60633. }
  60634. else
  60635. {
  60636. s = jmin (1.0f, s);
  60637. h = jlimit (0.0f, 1.0f, h);
  60638. h = (h - floorf (h)) * 6.0f + 0.00001f; // need a small adjustment to compensate for rounding errors
  60639. const float f = h - floorf (h);
  60640. const uint8 x = (uint8) roundFloatToInt (v * (1.0f - s));
  60641. const float y = v * (1.0f - s * f);
  60642. const float z = v * (1.0f - (s * (1.0f - f)));
  60643. if (h < 1.0f)
  60644. {
  60645. r = intV;
  60646. g = (uint8) roundFloatToInt (z);
  60647. b = x;
  60648. }
  60649. else if (h < 2.0f)
  60650. {
  60651. r = (uint8) roundFloatToInt (y);
  60652. g = intV;
  60653. b = x;
  60654. }
  60655. else if (h < 3.0f)
  60656. {
  60657. r = x;
  60658. g = intV;
  60659. b = (uint8) roundFloatToInt (z);
  60660. }
  60661. else if (h < 4.0f)
  60662. {
  60663. r = x;
  60664. g = (uint8) roundFloatToInt (y);
  60665. b = intV;
  60666. }
  60667. else if (h < 5.0f)
  60668. {
  60669. r = (uint8) roundFloatToInt (z);
  60670. g = x;
  60671. b = intV;
  60672. }
  60673. else if (h < 6.0f)
  60674. {
  60675. r = intV;
  60676. g = x;
  60677. b = (uint8) roundFloatToInt (y);
  60678. }
  60679. else
  60680. {
  60681. r = 0;
  60682. g = 0;
  60683. b = 0;
  60684. }
  60685. }
  60686. }
  60687. Colour::Colour (const float hue,
  60688. const float saturation,
  60689. const float brightness,
  60690. const float alpha) throw()
  60691. {
  60692. uint8 r = getRed(), g = getGreen(), b = getBlue();
  60693. convertHSBtoRGB (hue, saturation, brightness, r, g, b);
  60694. argb.setARGB (floatAlphaToInt (alpha), r, g, b);
  60695. }
  60696. const Colour Colour::fromHSV (const float hue,
  60697. const float saturation,
  60698. const float brightness,
  60699. const float alpha) throw()
  60700. {
  60701. return Colour (hue, saturation, brightness, alpha);
  60702. }
  60703. Colour::Colour (const float hue,
  60704. const float saturation,
  60705. const float brightness,
  60706. const uint8 alpha) throw()
  60707. {
  60708. uint8 r = getRed(), g = getGreen(), b = getBlue();
  60709. convertHSBtoRGB (hue, saturation, brightness, r, g, b);
  60710. argb.setARGB (alpha, r, g, b);
  60711. }
  60712. Colour::~Colour() throw()
  60713. {
  60714. }
  60715. const PixelARGB Colour::getPixelARGB() const throw()
  60716. {
  60717. PixelARGB p (argb);
  60718. p.premultiply();
  60719. return p;
  60720. }
  60721. uint32 Colour::getARGB() const throw()
  60722. {
  60723. return argb.getARGB();
  60724. }
  60725. bool Colour::isTransparent() const throw()
  60726. {
  60727. return getAlpha() == 0;
  60728. }
  60729. bool Colour::isOpaque() const throw()
  60730. {
  60731. return getAlpha() == 0xff;
  60732. }
  60733. const Colour Colour::withAlpha (const uint8 newAlpha) const throw()
  60734. {
  60735. PixelARGB newCol (argb);
  60736. newCol.setAlpha (newAlpha);
  60737. return Colour (newCol.getARGB());
  60738. }
  60739. const Colour Colour::withAlpha (const float newAlpha) const throw()
  60740. {
  60741. jassert (newAlpha >= 0 && newAlpha <= 1.0f);
  60742. PixelARGB newCol (argb);
  60743. newCol.setAlpha (floatAlphaToInt (newAlpha));
  60744. return Colour (newCol.getARGB());
  60745. }
  60746. const Colour Colour::withMultipliedAlpha (const float alphaMultiplier) const throw()
  60747. {
  60748. jassert (alphaMultiplier >= 0);
  60749. PixelARGB newCol (argb);
  60750. newCol.setAlpha ((uint8) jmin (0xff, roundFloatToInt (alphaMultiplier * newCol.getAlpha())));
  60751. return Colour (newCol.getARGB());
  60752. }
  60753. const Colour Colour::overlaidWith (const Colour& src) const throw()
  60754. {
  60755. const int destAlpha = getAlpha();
  60756. if (destAlpha > 0)
  60757. {
  60758. const int invA = 0xff - (int) src.getAlpha();
  60759. const int resA = 0xff - (((0xff - destAlpha) * invA) >> 8);
  60760. if (resA > 0)
  60761. {
  60762. const int da = (invA * destAlpha) / resA;
  60763. return Colour ((uint8) (src.getRed() + ((((int) getRed() - src.getRed()) * da) >> 8)),
  60764. (uint8) (src.getGreen() + ((((int) getGreen() - src.getGreen()) * da) >> 8)),
  60765. (uint8) (src.getBlue() + ((((int) getBlue() - src.getBlue()) * da) >> 8)),
  60766. (uint8) resA);
  60767. }
  60768. return *this;
  60769. }
  60770. else
  60771. {
  60772. return src;
  60773. }
  60774. }
  60775. float Colour::getFloatRed() const throw()
  60776. {
  60777. return getRed() * oneOver255;
  60778. }
  60779. float Colour::getFloatGreen() const throw()
  60780. {
  60781. return getGreen() * oneOver255;
  60782. }
  60783. float Colour::getFloatBlue() const throw()
  60784. {
  60785. return getBlue() * oneOver255;
  60786. }
  60787. float Colour::getFloatAlpha() const throw()
  60788. {
  60789. return getAlpha() * oneOver255;
  60790. }
  60791. void Colour::getHSB (float& h, float& s, float& v) const throw()
  60792. {
  60793. const int r = getRed();
  60794. const int g = getGreen();
  60795. const int b = getBlue();
  60796. const int hi = jmax (r, g, b);
  60797. const int lo = jmin (r, g, b);
  60798. if (hi != 0)
  60799. {
  60800. s = (hi - lo) / (float) hi;
  60801. if (s != 0)
  60802. {
  60803. const float invDiff = 1.0f / (hi - lo);
  60804. const float red = (hi - r) * invDiff;
  60805. const float green = (hi - g) * invDiff;
  60806. const float blue = (hi - b) * invDiff;
  60807. if (r == hi)
  60808. h = blue - green;
  60809. else if (g == hi)
  60810. h = 2.0f + red - blue;
  60811. else
  60812. h = 4.0f + green - red;
  60813. h *= 1.0f / 6.0f;
  60814. if (h < 0)
  60815. ++h;
  60816. }
  60817. else
  60818. {
  60819. h = 0;
  60820. }
  60821. }
  60822. else
  60823. {
  60824. s = 0;
  60825. h = 0;
  60826. }
  60827. v = hi * oneOver255;
  60828. }
  60829. float Colour::getHue() const throw()
  60830. {
  60831. float h, s, b;
  60832. getHSB (h, s, b);
  60833. return h;
  60834. }
  60835. const Colour Colour::withHue (const float hue) const throw()
  60836. {
  60837. float h, s, b;
  60838. getHSB (h, s, b);
  60839. return Colour (hue, s, b, getAlpha());
  60840. }
  60841. const Colour Colour::withRotatedHue (const float amountToRotate) const throw()
  60842. {
  60843. float h, s, b;
  60844. getHSB (h, s, b);
  60845. h += amountToRotate;
  60846. h -= floorf (h);
  60847. return Colour (h, s, b, getAlpha());
  60848. }
  60849. float Colour::getSaturation() const throw()
  60850. {
  60851. float h, s, b;
  60852. getHSB (h, s, b);
  60853. return s;
  60854. }
  60855. const Colour Colour::withSaturation (const float saturation) const throw()
  60856. {
  60857. float h, s, b;
  60858. getHSB (h, s, b);
  60859. return Colour (h, saturation, b, getAlpha());
  60860. }
  60861. const Colour Colour::withMultipliedSaturation (const float amount) const throw()
  60862. {
  60863. float h, s, b;
  60864. getHSB (h, s, b);
  60865. return Colour (h, jmin (1.0f, s * amount), b, getAlpha());
  60866. }
  60867. float Colour::getBrightness() const throw()
  60868. {
  60869. float h, s, b;
  60870. getHSB (h, s, b);
  60871. return b;
  60872. }
  60873. const Colour Colour::withBrightness (const float brightness) const throw()
  60874. {
  60875. float h, s, b;
  60876. getHSB (h, s, b);
  60877. return Colour (h, s, brightness, getAlpha());
  60878. }
  60879. const Colour Colour::withMultipliedBrightness (const float amount) const throw()
  60880. {
  60881. float h, s, b;
  60882. getHSB (h, s, b);
  60883. b *= amount;
  60884. if (b > 1.0f)
  60885. b = 1.0f;
  60886. return Colour (h, s, b, getAlpha());
  60887. }
  60888. const Colour Colour::brighter (float amount) const throw()
  60889. {
  60890. amount = 1.0f / (1.0f + amount);
  60891. return Colour ((uint8) (255 - (amount * (255 - getRed()))),
  60892. (uint8) (255 - (amount * (255 - getGreen()))),
  60893. (uint8) (255 - (amount * (255 - getBlue()))),
  60894. getAlpha());
  60895. }
  60896. const Colour Colour::darker (float amount) const throw()
  60897. {
  60898. amount = 1.0f / (1.0f + amount);
  60899. return Colour ((uint8) (amount * getRed()),
  60900. (uint8) (amount * getGreen()),
  60901. (uint8) (amount * getBlue()),
  60902. getAlpha());
  60903. }
  60904. const Colour Colour::greyLevel (const float brightness) throw()
  60905. {
  60906. const uint8 level
  60907. = (uint8) jlimit (0x00, 0xff, roundFloatToInt (brightness * 255.0f));
  60908. return Colour (level, level, level);
  60909. }
  60910. const Colour Colour::contrasting (const float amount) const throw()
  60911. {
  60912. return overlaidWith ((((int) getRed() + (int) getGreen() + (int) getBlue() >= 3 * 128)
  60913. ? Colours::black
  60914. : Colours::white).withAlpha (amount));
  60915. }
  60916. const Colour Colour::contrasting (const Colour& colour1,
  60917. const Colour& colour2) throw()
  60918. {
  60919. const float b1 = colour1.getBrightness();
  60920. const float b2 = colour2.getBrightness();
  60921. float best = 0.0f;
  60922. float bestDist = 0.0f;
  60923. for (float i = 0.0f; i < 1.0f; i += 0.02f)
  60924. {
  60925. const float d1 = fabsf (i - b1);
  60926. const float d2 = fabsf (i - b2);
  60927. const float dist = jmin (d1, d2, 1.0f - d1, 1.0f - d2);
  60928. if (dist > bestDist)
  60929. {
  60930. best = i;
  60931. bestDist = dist;
  60932. }
  60933. }
  60934. return colour1.overlaidWith (colour2.withMultipliedAlpha (0.5f))
  60935. .withBrightness (best);
  60936. }
  60937. const String Colour::toString() const throw()
  60938. {
  60939. return String::toHexString ((int) argb.getARGB());
  60940. }
  60941. const Colour Colour::fromString (const String& encodedColourString)
  60942. {
  60943. return Colour ((uint32) encodedColourString.getHexValue32());
  60944. }
  60945. END_JUCE_NAMESPACE
  60946. /********* End of inlined file: juce_Colour.cpp *********/
  60947. /********* Start of inlined file: juce_ColourGradient.cpp *********/
  60948. BEGIN_JUCE_NAMESPACE
  60949. ColourGradient::ColourGradient() throw()
  60950. : colours (4)
  60951. {
  60952. #ifdef JUCE_DEBUG
  60953. x1 = 987654.0f;
  60954. #endif
  60955. }
  60956. ColourGradient::ColourGradient (const Colour& colour1,
  60957. const float x1_,
  60958. const float y1_,
  60959. const Colour& colour2,
  60960. const float x2_,
  60961. const float y2_,
  60962. const bool isRadial_) throw()
  60963. : x1 (x1_),
  60964. y1 (y1_),
  60965. x2 (x2_),
  60966. y2 (y2_),
  60967. isRadial (isRadial_),
  60968. colours (4)
  60969. {
  60970. colours.add (0);
  60971. colours.add (colour1.getARGB());
  60972. colours.add (1 << 16);
  60973. colours.add (colour2.getARGB());
  60974. }
  60975. ColourGradient::~ColourGradient() throw()
  60976. {
  60977. }
  60978. void ColourGradient::clearColours() throw()
  60979. {
  60980. colours.clear();
  60981. }
  60982. void ColourGradient::addColour (const double proportionAlongGradient,
  60983. const Colour& colour) throw()
  60984. {
  60985. // must be within the two end-points
  60986. jassert (proportionAlongGradient >= 0 && proportionAlongGradient <= 1.0);
  60987. const uint32 pos = jlimit (0, 65535, roundDoubleToInt (proportionAlongGradient * 65536.0));
  60988. int i;
  60989. for (i = 0; i < colours.size(); i += 2)
  60990. if (colours.getUnchecked(i) > pos)
  60991. break;
  60992. colours.insert (i, pos);
  60993. colours.insert (i + 1, colour.getARGB());
  60994. }
  60995. void ColourGradient::multiplyOpacity (const float multiplier) throw()
  60996. {
  60997. for (int i = 1; i < colours.size(); i += 2)
  60998. {
  60999. const Colour c (colours.getUnchecked(i));
  61000. colours.set (i, c.withMultipliedAlpha (multiplier).getARGB());
  61001. }
  61002. }
  61003. int ColourGradient::getNumColours() const throw()
  61004. {
  61005. return colours.size() >> 1;
  61006. }
  61007. double ColourGradient::getColourPosition (const int index) const throw()
  61008. {
  61009. return jlimit (0.0, 1.0, colours [index << 1] / 65535.0);
  61010. }
  61011. const Colour ColourGradient::getColour (const int index) const throw()
  61012. {
  61013. return Colour (colours [(index << 1) + 1]);
  61014. }
  61015. PixelARGB* ColourGradient::createLookupTable (int& numEntries) const throw()
  61016. {
  61017. #ifdef JUCE_DEBUG
  61018. // trying to use the object without setting its co-ordinates? Have a careful read of
  61019. // the comments for the constructors.
  61020. jassert (x1 != 987654.0f);
  61021. #endif
  61022. const int numColours = colours.size() >> 1;
  61023. float tx1 = x1, ty1 = y1, tx2 = x2, ty2 = y2;
  61024. transform.transformPoint (tx1, ty1);
  61025. transform.transformPoint (tx2, ty2);
  61026. const double distance = juce_hypot (tx1 - tx2, ty1 - ty2);
  61027. numEntries = jlimit (1, (numColours - 1) << 8, 3 * (int) distance);
  61028. PixelARGB* const lookupTable = (PixelARGB*) juce_calloc (numEntries * sizeof (PixelARGB));
  61029. if (numColours >= 2)
  61030. {
  61031. jassert (colours.getUnchecked (0) == 0); // the first colour specified has to go at position 0
  61032. PixelARGB pix1 (colours.getUnchecked (1));
  61033. pix1.premultiply();
  61034. int index = 0;
  61035. for (int j = 2; j < colours.size(); j += 2)
  61036. {
  61037. const int numToDo = ((colours.getUnchecked (j) * (numEntries - 1)) >> 16) - index;
  61038. PixelARGB pix2 (colours.getUnchecked (j + 1));
  61039. pix2.premultiply();
  61040. for (int i = 0; i < numToDo; ++i)
  61041. {
  61042. jassert (index >= 0 && index < numEntries);
  61043. lookupTable[index] = pix1;
  61044. lookupTable[index].tween (pix2, (i << 8) / numToDo);
  61045. ++index;
  61046. }
  61047. pix1 = pix2;
  61048. }
  61049. while (index < numEntries)
  61050. lookupTable [index++] = pix1;
  61051. }
  61052. else
  61053. {
  61054. jassertfalse // no colours specified!
  61055. }
  61056. return lookupTable;
  61057. }
  61058. bool ColourGradient::isOpaque() const throw()
  61059. {
  61060. for (int i = 1; i < colours.size(); i += 2)
  61061. if (PixelARGB (colours.getUnchecked(i)).getAlpha() < 0xff)
  61062. return false;
  61063. return true;
  61064. }
  61065. bool ColourGradient::isInvisible() const throw()
  61066. {
  61067. for (int i = 1; i < colours.size(); i += 2)
  61068. if (PixelARGB (colours.getUnchecked(i)).getAlpha() > 0)
  61069. return false;
  61070. return true;
  61071. }
  61072. END_JUCE_NAMESPACE
  61073. /********* End of inlined file: juce_ColourGradient.cpp *********/
  61074. /********* Start of inlined file: juce_Colours.cpp *********/
  61075. BEGIN_JUCE_NAMESPACE
  61076. const Colour Colours::transparentBlack (0);
  61077. const Colour Colours::transparentWhite (0x00ffffff);
  61078. const Colour Colours::aliceblue (0xfff0f8ff);
  61079. const Colour Colours::antiquewhite (0xfffaebd7);
  61080. const Colour Colours::aqua (0xff00ffff);
  61081. const Colour Colours::aquamarine (0xff7fffd4);
  61082. const Colour Colours::azure (0xfff0ffff);
  61083. const Colour Colours::beige (0xfff5f5dc);
  61084. const Colour Colours::bisque (0xffffe4c4);
  61085. const Colour Colours::black (0xff000000);
  61086. const Colour Colours::blanchedalmond (0xffffebcd);
  61087. const Colour Colours::blue (0xff0000ff);
  61088. const Colour Colours::blueviolet (0xff8a2be2);
  61089. const Colour Colours::brown (0xffa52a2a);
  61090. const Colour Colours::burlywood (0xffdeb887);
  61091. const Colour Colours::cadetblue (0xff5f9ea0);
  61092. const Colour Colours::chartreuse (0xff7fff00);
  61093. const Colour Colours::chocolate (0xffd2691e);
  61094. const Colour Colours::coral (0xffff7f50);
  61095. const Colour Colours::cornflowerblue (0xff6495ed);
  61096. const Colour Colours::cornsilk (0xfffff8dc);
  61097. const Colour Colours::crimson (0xffdc143c);
  61098. const Colour Colours::cyan (0xff00ffff);
  61099. const Colour Colours::darkblue (0xff00008b);
  61100. const Colour Colours::darkcyan (0xff008b8b);
  61101. const Colour Colours::darkgoldenrod (0xffb8860b);
  61102. const Colour Colours::darkgrey (0xff555555);
  61103. const Colour Colours::darkgreen (0xff006400);
  61104. const Colour Colours::darkkhaki (0xffbdb76b);
  61105. const Colour Colours::darkmagenta (0xff8b008b);
  61106. const Colour Colours::darkolivegreen (0xff556b2f);
  61107. const Colour Colours::darkorange (0xffff8c00);
  61108. const Colour Colours::darkorchid (0xff9932cc);
  61109. const Colour Colours::darkred (0xff8b0000);
  61110. const Colour Colours::darksalmon (0xffe9967a);
  61111. const Colour Colours::darkseagreen (0xff8fbc8f);
  61112. const Colour Colours::darkslateblue (0xff483d8b);
  61113. const Colour Colours::darkslategrey (0xff2f4f4f);
  61114. const Colour Colours::darkturquoise (0xff00ced1);
  61115. const Colour Colours::darkviolet (0xff9400d3);
  61116. const Colour Colours::deeppink (0xffff1493);
  61117. const Colour Colours::deepskyblue (0xff00bfff);
  61118. const Colour Colours::dimgrey (0xff696969);
  61119. const Colour Colours::dodgerblue (0xff1e90ff);
  61120. const Colour Colours::firebrick (0xffb22222);
  61121. const Colour Colours::floralwhite (0xfffffaf0);
  61122. const Colour Colours::forestgreen (0xff228b22);
  61123. const Colour Colours::fuchsia (0xffff00ff);
  61124. const Colour Colours::gainsboro (0xffdcdcdc);
  61125. const Colour Colours::gold (0xffffd700);
  61126. const Colour Colours::goldenrod (0xffdaa520);
  61127. const Colour Colours::grey (0xff808080);
  61128. const Colour Colours::green (0xff008000);
  61129. const Colour Colours::greenyellow (0xffadff2f);
  61130. const Colour Colours::honeydew (0xfff0fff0);
  61131. const Colour Colours::hotpink (0xffff69b4);
  61132. const Colour Colours::indianred (0xffcd5c5c);
  61133. const Colour Colours::indigo (0xff4b0082);
  61134. const Colour Colours::ivory (0xfffffff0);
  61135. const Colour Colours::khaki (0xfff0e68c);
  61136. const Colour Colours::lavender (0xffe6e6fa);
  61137. const Colour Colours::lavenderblush (0xfffff0f5);
  61138. const Colour Colours::lemonchiffon (0xfffffacd);
  61139. const Colour Colours::lightblue (0xffadd8e6);
  61140. const Colour Colours::lightcoral (0xfff08080);
  61141. const Colour Colours::lightcyan (0xffe0ffff);
  61142. const Colour Colours::lightgoldenrodyellow (0xfffafad2);
  61143. const Colour Colours::lightgreen (0xff90ee90);
  61144. const Colour Colours::lightgrey (0xffd3d3d3);
  61145. const Colour Colours::lightpink (0xffffb6c1);
  61146. const Colour Colours::lightsalmon (0xffffa07a);
  61147. const Colour Colours::lightseagreen (0xff20b2aa);
  61148. const Colour Colours::lightskyblue (0xff87cefa);
  61149. const Colour Colours::lightslategrey (0xff778899);
  61150. const Colour Colours::lightsteelblue (0xffb0c4de);
  61151. const Colour Colours::lightyellow (0xffffffe0);
  61152. const Colour Colours::lime (0xff00ff00);
  61153. const Colour Colours::limegreen (0xff32cd32);
  61154. const Colour Colours::linen (0xfffaf0e6);
  61155. const Colour Colours::magenta (0xffff00ff);
  61156. const Colour Colours::maroon (0xff800000);
  61157. const Colour Colours::mediumaquamarine (0xff66cdaa);
  61158. const Colour Colours::mediumblue (0xff0000cd);
  61159. const Colour Colours::mediumorchid (0xffba55d3);
  61160. const Colour Colours::mediumpurple (0xff9370db);
  61161. const Colour Colours::mediumseagreen (0xff3cb371);
  61162. const Colour Colours::mediumslateblue (0xff7b68ee);
  61163. const Colour Colours::mediumspringgreen (0xff00fa9a);
  61164. const Colour Colours::mediumturquoise (0xff48d1cc);
  61165. const Colour Colours::mediumvioletred (0xffc71585);
  61166. const Colour Colours::midnightblue (0xff191970);
  61167. const Colour Colours::mintcream (0xfff5fffa);
  61168. const Colour Colours::mistyrose (0xffffe4e1);
  61169. const Colour Colours::navajowhite (0xffffdead);
  61170. const Colour Colours::navy (0xff000080);
  61171. const Colour Colours::oldlace (0xfffdf5e6);
  61172. const Colour Colours::olive (0xff808000);
  61173. const Colour Colours::olivedrab (0xff6b8e23);
  61174. const Colour Colours::orange (0xffffa500);
  61175. const Colour Colours::orangered (0xffff4500);
  61176. const Colour Colours::orchid (0xffda70d6);
  61177. const Colour Colours::palegoldenrod (0xffeee8aa);
  61178. const Colour Colours::palegreen (0xff98fb98);
  61179. const Colour Colours::paleturquoise (0xffafeeee);
  61180. const Colour Colours::palevioletred (0xffdb7093);
  61181. const Colour Colours::papayawhip (0xffffefd5);
  61182. const Colour Colours::peachpuff (0xffffdab9);
  61183. const Colour Colours::peru (0xffcd853f);
  61184. const Colour Colours::pink (0xffffc0cb);
  61185. const Colour Colours::plum (0xffdda0dd);
  61186. const Colour Colours::powderblue (0xffb0e0e6);
  61187. const Colour Colours::purple (0xff800080);
  61188. const Colour Colours::red (0xffff0000);
  61189. const Colour Colours::rosybrown (0xffbc8f8f);
  61190. const Colour Colours::royalblue (0xff4169e1);
  61191. const Colour Colours::saddlebrown (0xff8b4513);
  61192. const Colour Colours::salmon (0xfffa8072);
  61193. const Colour Colours::sandybrown (0xfff4a460);
  61194. const Colour Colours::seagreen (0xff2e8b57);
  61195. const Colour Colours::seashell (0xfffff5ee);
  61196. const Colour Colours::sienna (0xffa0522d);
  61197. const Colour Colours::silver (0xffc0c0c0);
  61198. const Colour Colours::skyblue (0xff87ceeb);
  61199. const Colour Colours::slateblue (0xff6a5acd);
  61200. const Colour Colours::slategrey (0xff708090);
  61201. const Colour Colours::snow (0xfffffafa);
  61202. const Colour Colours::springgreen (0xff00ff7f);
  61203. const Colour Colours::steelblue (0xff4682b4);
  61204. const Colour Colours::tan (0xffd2b48c);
  61205. const Colour Colours::teal (0xff008080);
  61206. const Colour Colours::thistle (0xffd8bfd8);
  61207. const Colour Colours::tomato (0xffff6347);
  61208. const Colour Colours::turquoise (0xff40e0d0);
  61209. const Colour Colours::violet (0xffee82ee);
  61210. const Colour Colours::wheat (0xfff5deb3);
  61211. const Colour Colours::white (0xffffffff);
  61212. const Colour Colours::whitesmoke (0xfff5f5f5);
  61213. const Colour Colours::yellow (0xffffff00);
  61214. const Colour Colours::yellowgreen (0xff9acd32);
  61215. const Colour Colours::findColourForName (const String& colourName,
  61216. const Colour& defaultColour)
  61217. {
  61218. static const int presets[] =
  61219. {
  61220. // (first value is the string's hashcode, second is ARGB)
  61221. 0x05978fff, 0xff000000, /* black */
  61222. 0x06bdcc29, 0xffffffff, /* white */
  61223. 0x002e305a, 0xff0000ff, /* blue */
  61224. 0x00308adf, 0xff808080, /* grey */
  61225. 0x05e0cf03, 0xff008000, /* green */
  61226. 0x0001b891, 0xffff0000, /* red */
  61227. 0xd43c6474, 0xffffff00, /* yellow */
  61228. 0x620886da, 0xfff0f8ff, /* aliceblue */
  61229. 0x20a2676a, 0xfffaebd7, /* antiquewhite */
  61230. 0x002dcebc, 0xff00ffff, /* aqua */
  61231. 0x46bb5f7e, 0xff7fffd4, /* aquamarine */
  61232. 0x0590228f, 0xfff0ffff, /* azure */
  61233. 0x05947fe4, 0xfff5f5dc, /* beige */
  61234. 0xad388e35, 0xffffe4c4, /* bisque */
  61235. 0x00674f7e, 0xffffebcd, /* blanchedalmond */
  61236. 0x39129959, 0xff8a2be2, /* blueviolet */
  61237. 0x059a8136, 0xffa52a2a, /* brown */
  61238. 0x89cea8f9, 0xffdeb887, /* burlywood */
  61239. 0x0fa260cf, 0xff5f9ea0, /* cadetblue */
  61240. 0x6b748956, 0xff7fff00, /* chartreuse */
  61241. 0x2903623c, 0xffd2691e, /* chocolate */
  61242. 0x05a74431, 0xffff7f50, /* coral */
  61243. 0x618d42dd, 0xff6495ed, /* cornflowerblue */
  61244. 0xe4b479fd, 0xfffff8dc, /* cornsilk */
  61245. 0x3d8c4edf, 0xffdc143c, /* crimson */
  61246. 0x002ed323, 0xff00ffff, /* cyan */
  61247. 0x67cc74d0, 0xff00008b, /* darkblue */
  61248. 0x67cd1799, 0xff008b8b, /* darkcyan */
  61249. 0x31bbd168, 0xffb8860b, /* darkgoldenrod */
  61250. 0x67cecf55, 0xff555555, /* darkgrey */
  61251. 0x920b194d, 0xff006400, /* darkgreen */
  61252. 0x923edd4c, 0xffbdb76b, /* darkkhaki */
  61253. 0x5c293873, 0xff8b008b, /* darkmagenta */
  61254. 0x6b6671fe, 0xff556b2f, /* darkolivegreen */
  61255. 0xbcfd2524, 0xffff8c00, /* darkorange */
  61256. 0xbcfdf799, 0xff9932cc, /* darkorchid */
  61257. 0x55ee0d5b, 0xff8b0000, /* darkred */
  61258. 0xc2e5f564, 0xffe9967a, /* darksalmon */
  61259. 0x61be858a, 0xff8fbc8f, /* darkseagreen */
  61260. 0xc2b0f2bd, 0xff483d8b, /* darkslateblue */
  61261. 0xc2b34d42, 0xff2f4f4f, /* darkslategrey */
  61262. 0x7cf2b06b, 0xff00ced1, /* darkturquoise */
  61263. 0xc8769375, 0xff9400d3, /* darkviolet */
  61264. 0x25832862, 0xffff1493, /* deeppink */
  61265. 0xfcad568f, 0xff00bfff, /* deepskyblue */
  61266. 0x634c8b67, 0xff696969, /* dimgrey */
  61267. 0x45c1ce55, 0xff1e90ff, /* dodgerblue */
  61268. 0xef19e3cb, 0xffb22222, /* firebrick */
  61269. 0xb852b195, 0xfffffaf0, /* floralwhite */
  61270. 0xd086fd06, 0xff228b22, /* forestgreen */
  61271. 0xe106b6d7, 0xffff00ff, /* fuchsia */
  61272. 0x7880d61e, 0xffdcdcdc, /* gainsboro */
  61273. 0x00308060, 0xffffd700, /* gold */
  61274. 0xb3b3bc1e, 0xffdaa520, /* goldenrod */
  61275. 0xbab8a537, 0xffadff2f, /* greenyellow */
  61276. 0xe4cacafb, 0xfff0fff0, /* honeydew */
  61277. 0x41892743, 0xffff69b4, /* hotpink */
  61278. 0xd5796f1a, 0xffcd5c5c, /* indianred */
  61279. 0xb969fed2, 0xff4b0082, /* indigo */
  61280. 0x05fef6a9, 0xfffffff0, /* ivory */
  61281. 0x06149302, 0xfff0e68c, /* khaki */
  61282. 0xad5a05c7, 0xffe6e6fa, /* lavender */
  61283. 0x7c4d5b99, 0xfffff0f5, /* lavenderblush */
  61284. 0x195756f0, 0xfffffacd, /* lemonchiffon */
  61285. 0x28e4ea70, 0xffadd8e6, /* lightblue */
  61286. 0xf3c7ccdb, 0xfff08080, /* lightcoral */
  61287. 0x28e58d39, 0xffe0ffff, /* lightcyan */
  61288. 0x21234e3c, 0xfffafad2, /* lightgoldenrodyellow */
  61289. 0xf40157ad, 0xff90ee90, /* lightgreen */
  61290. 0x28e744f5, 0xffd3d3d3, /* lightgrey */
  61291. 0x28eb3b8c, 0xffffb6c1, /* lightpink */
  61292. 0x9fb78304, 0xffffa07a, /* lightsalmon */
  61293. 0x50632b2a, 0xff20b2aa, /* lightseagreen */
  61294. 0x68fb7b25, 0xff87cefa, /* lightskyblue */
  61295. 0xa8a35ba2, 0xff778899, /* lightslategrey */
  61296. 0xa20d484f, 0xffb0c4de, /* lightsteelblue */
  61297. 0xaa2cf10a, 0xffffffe0, /* lightyellow */
  61298. 0x0032afd5, 0xff00ff00, /* lime */
  61299. 0x607bbc4e, 0xff32cd32, /* limegreen */
  61300. 0x06234efa, 0xfffaf0e6, /* linen */
  61301. 0x316858a9, 0xffff00ff, /* magenta */
  61302. 0xbf8ca470, 0xff800000, /* maroon */
  61303. 0xbd58e0b3, 0xff66cdaa, /* mediumaquamarine */
  61304. 0x967dfd4f, 0xff0000cd, /* mediumblue */
  61305. 0x056f5c58, 0xffba55d3, /* mediumorchid */
  61306. 0x07556b71, 0xff9370db, /* mediumpurple */
  61307. 0x5369b689, 0xff3cb371, /* mediumseagreen */
  61308. 0x066be19e, 0xff7b68ee, /* mediumslateblue */
  61309. 0x3256b281, 0xff00fa9a, /* mediumspringgreen */
  61310. 0xc0ad9f4c, 0xff48d1cc, /* mediumturquoise */
  61311. 0x628e63dd, 0xffc71585, /* mediumvioletred */
  61312. 0x168eb32a, 0xff191970, /* midnightblue */
  61313. 0x4306b960, 0xfff5fffa, /* mintcream */
  61314. 0x4cbc0e6b, 0xffffe4e1, /* mistyrose */
  61315. 0xe97218a6, 0xffffdead, /* navajowhite */
  61316. 0x00337bb6, 0xff000080, /* navy */
  61317. 0xadd2d33e, 0xfffdf5e6, /* oldlace */
  61318. 0x064ee1db, 0xff808000, /* olive */
  61319. 0x9e33a98a, 0xff6b8e23, /* olivedrab */
  61320. 0xc3de262e, 0xffffa500, /* orange */
  61321. 0x58bebba3, 0xffff4500, /* orangered */
  61322. 0xc3def8a3, 0xffda70d6, /* orchid */
  61323. 0x28cb4834, 0xffeee8aa, /* palegoldenrod */
  61324. 0x3d9dd619, 0xff98fb98, /* palegreen */
  61325. 0x74022737, 0xffafeeee, /* paleturquoise */
  61326. 0x15e2ebc8, 0xffdb7093, /* palevioletred */
  61327. 0x5fd898e2, 0xffffefd5, /* papayawhip */
  61328. 0x93e1b776, 0xffffdab9, /* peachpuff */
  61329. 0x003472f8, 0xffcd853f, /* peru */
  61330. 0x00348176, 0xffffc0cb, /* pink */
  61331. 0x00348d94, 0xffdda0dd, /* plum */
  61332. 0xd036be93, 0xffb0e0e6, /* powderblue */
  61333. 0xc5c507bc, 0xff800080, /* purple */
  61334. 0xa89d65b3, 0xffbc8f8f, /* rosybrown */
  61335. 0xbd9413e1, 0xff4169e1, /* royalblue */
  61336. 0xf456044f, 0xff8b4513, /* saddlebrown */
  61337. 0xc9c6f66e, 0xfffa8072, /* salmon */
  61338. 0x0bb131e1, 0xfff4a460, /* sandybrown */
  61339. 0x34636c14, 0xff2e8b57, /* seagreen */
  61340. 0x3507fb41, 0xfffff5ee, /* seashell */
  61341. 0xca348772, 0xffa0522d, /* sienna */
  61342. 0xca37d30d, 0xffc0c0c0, /* silver */
  61343. 0x80da74fb, 0xff87ceeb, /* skyblue */
  61344. 0x44a8dd73, 0xff6a5acd, /* slateblue */
  61345. 0x44ab37f8, 0xff708090, /* slategrey */
  61346. 0x0035f183, 0xfffffafa, /* snow */
  61347. 0xd5440d16, 0xff00ff7f, /* springgreen */
  61348. 0x3e1524a5, 0xff4682b4, /* steelblue */
  61349. 0x0001bfa1, 0xffd2b48c, /* tan */
  61350. 0x0036425c, 0xff008080, /* teal */
  61351. 0xafc8858f, 0xffd8bfd8, /* thistle */
  61352. 0xcc41600a, 0xffff6347, /* tomato */
  61353. 0xfeea9b21, 0xff40e0d0, /* turquoise */
  61354. 0xcf57947f, 0xffee82ee, /* violet */
  61355. 0x06bdbae7, 0xfff5deb3, /* wheat */
  61356. 0x10802ee6, 0xfff5f5f5, /* whitesmoke */
  61357. 0xe1b5130f, 0xff9acd32 /* yellowgreen */
  61358. };
  61359. const int hash = colourName.trim().toLowerCase().hashCode();
  61360. for (int i = 0; i < numElementsInArray (presets); i += 2)
  61361. if (presets [i] == hash)
  61362. return Colour (presets [i + 1]);
  61363. return defaultColour;
  61364. }
  61365. END_JUCE_NAMESPACE
  61366. /********* End of inlined file: juce_Colours.cpp *********/
  61367. /********* Start of inlined file: juce_EdgeTable.cpp *********/
  61368. BEGIN_JUCE_NAMESPACE
  61369. EdgeTable::EdgeTable (const int top_,
  61370. const int height_,
  61371. const OversamplingLevel oversampling_,
  61372. const int expectedEdgesPerLine) throw()
  61373. : top (top_),
  61374. height (height_),
  61375. maxEdgesPerLine (expectedEdgesPerLine),
  61376. lineStrideElements ((expectedEdgesPerLine << 1) + 1),
  61377. oversampling (oversampling_)
  61378. {
  61379. table = (int*) juce_calloc ((height << (int)oversampling_)
  61380. * lineStrideElements * sizeof (int));
  61381. }
  61382. EdgeTable::EdgeTable (const EdgeTable& other) throw()
  61383. : table (0)
  61384. {
  61385. operator= (other);
  61386. }
  61387. const EdgeTable& EdgeTable::operator= (const EdgeTable& other) throw()
  61388. {
  61389. juce_free (table);
  61390. top = other.top;
  61391. height = other.height;
  61392. maxEdgesPerLine = other.maxEdgesPerLine;
  61393. lineStrideElements = other.lineStrideElements;
  61394. oversampling = other.oversampling;
  61395. const int tableSize = (height << (int)oversampling)
  61396. * lineStrideElements * sizeof (int);
  61397. table = (int*) juce_malloc (tableSize);
  61398. memcpy (table, other.table, tableSize);
  61399. return *this;
  61400. }
  61401. EdgeTable::~EdgeTable() throw()
  61402. {
  61403. juce_free (table);
  61404. }
  61405. void EdgeTable::remapTableForNumEdges (const int newNumEdgesPerLine) throw()
  61406. {
  61407. if (newNumEdgesPerLine != maxEdgesPerLine)
  61408. {
  61409. maxEdgesPerLine = newNumEdgesPerLine;
  61410. const int newLineStrideElements = maxEdgesPerLine * 2 + 1;
  61411. int* const newTable = (int*) juce_malloc ((height << (int) oversampling)
  61412. * newLineStrideElements * sizeof (int));
  61413. for (int i = 0; i < (height << (int) oversampling); ++i)
  61414. {
  61415. const int* srcLine = table + lineStrideElements * i;
  61416. int* dstLine = newTable + newLineStrideElements * i;
  61417. int num = *srcLine++;
  61418. *dstLine++ = num;
  61419. num <<= 1;
  61420. while (--num >= 0)
  61421. *dstLine++ = *srcLine++;
  61422. }
  61423. juce_free (table);
  61424. table = newTable;
  61425. lineStrideElements = newLineStrideElements;
  61426. }
  61427. }
  61428. void EdgeTable::optimiseTable() throw()
  61429. {
  61430. int maxLineElements = 0;
  61431. for (int i = height; --i >= 0;)
  61432. maxLineElements = jmax (maxLineElements,
  61433. table [i * lineStrideElements]);
  61434. remapTableForNumEdges (maxLineElements);
  61435. }
  61436. void EdgeTable::addEdgePoint (const int x, const int y, const int winding) throw()
  61437. {
  61438. jassert (y >= 0 && y < (height << oversampling))
  61439. int* lineStart = table + lineStrideElements * y;
  61440. int n = lineStart[0];
  61441. if (n >= maxEdgesPerLine)
  61442. {
  61443. remapTableForNumEdges (maxEdgesPerLine + juce_edgeTableDefaultEdgesPerLine);
  61444. jassert (n < maxEdgesPerLine);
  61445. lineStart = table + lineStrideElements * y;
  61446. }
  61447. n <<= 1;
  61448. int* const line = lineStart + 1;
  61449. while (n > 0)
  61450. {
  61451. const int cx = line [n - 2];
  61452. if (cx <= x)
  61453. break;
  61454. line [n] = cx;
  61455. line [n + 1] = line [n - 1];
  61456. n -= 2;
  61457. }
  61458. line [n] = x;
  61459. line [n + 1] = winding;
  61460. lineStart[0]++;
  61461. }
  61462. void EdgeTable::addPath (const Path& path,
  61463. const AffineTransform& transform) throw()
  61464. {
  61465. const int windingAmount = 256 / (1 << (int) oversampling);
  61466. const float timesOversampling = (float) (1 << (int) oversampling);
  61467. const int bottomLimit = (height << (int) oversampling);
  61468. PathFlatteningIterator iter (path, transform);
  61469. while (iter.next())
  61470. {
  61471. int y1 = roundFloatToInt (iter.y1 * timesOversampling) - (top << (int) oversampling);
  61472. int y2 = roundFloatToInt (iter.y2 * timesOversampling) - (top << (int) oversampling);
  61473. if (y1 != y2)
  61474. {
  61475. const double x1 = 256.0 * iter.x1;
  61476. const double x2 = 256.0 * iter.x2;
  61477. const double multiplier = (x2 - x1) / (y2 - y1);
  61478. const int oldY1 = y1;
  61479. int winding;
  61480. if (y1 > y2)
  61481. {
  61482. swapVariables (y1, y2);
  61483. winding = windingAmount;
  61484. }
  61485. else
  61486. {
  61487. winding = -windingAmount;
  61488. }
  61489. jassert (y1 < y2);
  61490. if (y1 < 0)
  61491. y1 = 0;
  61492. if (y2 > bottomLimit)
  61493. y2 = bottomLimit;
  61494. while (y1 < y2)
  61495. {
  61496. addEdgePoint (roundDoubleToInt (x1 + multiplier * (y1 - oldY1)),
  61497. y1,
  61498. winding);
  61499. ++y1;
  61500. }
  61501. }
  61502. }
  61503. if (! path.isUsingNonZeroWinding())
  61504. {
  61505. // if it's an alternate-winding path, we need to go through and
  61506. // make sure all the windings are alternating.
  61507. int* lineStart = table;
  61508. for (int i = height << (int) oversampling; --i >= 0;)
  61509. {
  61510. int* line = lineStart;
  61511. lineStart += lineStrideElements;
  61512. int num = *line;
  61513. while (--num >= 0)
  61514. {
  61515. line += 2;
  61516. *line = abs (*line);
  61517. if (--num >= 0)
  61518. {
  61519. line += 2;
  61520. *line = -abs (*line);
  61521. }
  61522. }
  61523. }
  61524. }
  61525. }
  61526. END_JUCE_NAMESPACE
  61527. /********* End of inlined file: juce_EdgeTable.cpp *********/
  61528. /********* Start of inlined file: juce_Graphics.cpp *********/
  61529. BEGIN_JUCE_NAMESPACE
  61530. static const Graphics::ResamplingQuality defaultQuality = Graphics::mediumResamplingQuality;
  61531. #define MINIMUM_COORD -0x3fffffff
  61532. #define MAXIMUM_COORD 0x3fffffff
  61533. #undef ASSERT_COORDS_ARE_SENSIBLE_NUMBERS
  61534. #define ASSERT_COORDS_ARE_SENSIBLE_NUMBERS(x, y, w, h) \
  61535. jassert ((int) x >= MINIMUM_COORD \
  61536. && (int) x <= MAXIMUM_COORD \
  61537. && (int) y >= MINIMUM_COORD \
  61538. && (int) y <= MAXIMUM_COORD \
  61539. && (int) w >= MINIMUM_COORD \
  61540. && (int) w <= MAXIMUM_COORD \
  61541. && (int) h >= MINIMUM_COORD \
  61542. && (int) h <= MAXIMUM_COORD);
  61543. LowLevelGraphicsContext::LowLevelGraphicsContext()
  61544. {
  61545. }
  61546. LowLevelGraphicsContext::~LowLevelGraphicsContext()
  61547. {
  61548. }
  61549. Graphics::Graphics (Image& imageToDrawOnto) throw()
  61550. : context (imageToDrawOnto.createLowLevelContext()),
  61551. ownsContext (true),
  61552. state (new GraphicsState()),
  61553. saveStatePending (false)
  61554. {
  61555. }
  61556. Graphics::Graphics (LowLevelGraphicsContext* const internalContext) throw()
  61557. : context (internalContext),
  61558. ownsContext (false),
  61559. state (new GraphicsState()),
  61560. saveStatePending (false)
  61561. {
  61562. }
  61563. Graphics::~Graphics() throw()
  61564. {
  61565. delete state;
  61566. if (ownsContext)
  61567. delete context;
  61568. }
  61569. void Graphics::resetToDefaultState() throw()
  61570. {
  61571. setColour (Colours::black);
  61572. state->font.resetToDefaultState();
  61573. state->quality = defaultQuality;
  61574. }
  61575. bool Graphics::isVectorDevice() const throw()
  61576. {
  61577. return context->isVectorDevice();
  61578. }
  61579. bool Graphics::reduceClipRegion (const int x, const int y,
  61580. const int w, const int h) throw()
  61581. {
  61582. saveStateIfPending();
  61583. return context->reduceClipRegion (x, y, w, h);
  61584. }
  61585. bool Graphics::reduceClipRegion (const RectangleList& clipRegion) throw()
  61586. {
  61587. saveStateIfPending();
  61588. return context->reduceClipRegion (clipRegion);
  61589. }
  61590. void Graphics::excludeClipRegion (const int x, const int y,
  61591. const int w, const int h) throw()
  61592. {
  61593. saveStateIfPending();
  61594. context->excludeClipRegion (x, y, w, h);
  61595. }
  61596. bool Graphics::isClipEmpty() const throw()
  61597. {
  61598. return context->isClipEmpty();
  61599. }
  61600. const Rectangle Graphics::getClipBounds() const throw()
  61601. {
  61602. return context->getClipBounds();
  61603. }
  61604. void Graphics::saveState() throw()
  61605. {
  61606. saveStateIfPending();
  61607. saveStatePending = true;
  61608. }
  61609. void Graphics::restoreState() throw()
  61610. {
  61611. if (saveStatePending)
  61612. {
  61613. saveStatePending = false;
  61614. }
  61615. else
  61616. {
  61617. const int stackSize = stateStack.size();
  61618. if (stackSize > 0)
  61619. {
  61620. context->restoreState();
  61621. delete state;
  61622. state = stateStack.getUnchecked (stackSize - 1);
  61623. stateStack.removeLast (1, false);
  61624. }
  61625. else
  61626. {
  61627. // Trying to call restoreState() more times than you've called saveState() !
  61628. // Be careful to correctly match each saveState() with exactly one call to restoreState().
  61629. jassertfalse
  61630. }
  61631. }
  61632. }
  61633. void Graphics::saveStateIfPending() throw()
  61634. {
  61635. if (saveStatePending)
  61636. {
  61637. saveStatePending = false;
  61638. context->saveState();
  61639. stateStack.add (new GraphicsState (*state));
  61640. }
  61641. }
  61642. void Graphics::setOrigin (const int newOriginX,
  61643. const int newOriginY) throw()
  61644. {
  61645. saveStateIfPending();
  61646. context->setOrigin (newOriginX, newOriginY);
  61647. }
  61648. bool Graphics::clipRegionIntersects (const int x, const int y,
  61649. const int w, const int h) const throw()
  61650. {
  61651. return context->clipRegionIntersects (x, y, w, h);
  61652. }
  61653. void Graphics::setColour (const Colour& newColour) throw()
  61654. {
  61655. saveStateIfPending();
  61656. state->colour = newColour;
  61657. deleteAndZero (state->brush);
  61658. }
  61659. const Colour& Graphics::getCurrentColour() const throw()
  61660. {
  61661. return state->colour;
  61662. }
  61663. void Graphics::setOpacity (const float newOpacity) throw()
  61664. {
  61665. saveStateIfPending();
  61666. state->colour = state->colour.withAlpha (newOpacity);
  61667. }
  61668. void Graphics::setBrush (const Brush* const newBrush) throw()
  61669. {
  61670. saveStateIfPending();
  61671. delete state->brush;
  61672. if (newBrush != 0)
  61673. state->brush = newBrush->createCopy();
  61674. else
  61675. state->brush = 0;
  61676. }
  61677. Graphics::GraphicsState::GraphicsState() throw()
  61678. : colour (Colours::black),
  61679. brush (0),
  61680. quality (defaultQuality)
  61681. {
  61682. }
  61683. Graphics::GraphicsState::GraphicsState (const GraphicsState& other) throw()
  61684. : colour (other.colour),
  61685. brush (other.brush != 0 ? other.brush->createCopy() : 0),
  61686. font (other.font),
  61687. quality (other.quality)
  61688. {
  61689. }
  61690. Graphics::GraphicsState::~GraphicsState() throw()
  61691. {
  61692. delete brush;
  61693. }
  61694. void Graphics::setFont (const Font& newFont) throw()
  61695. {
  61696. saveStateIfPending();
  61697. state->font = newFont;
  61698. }
  61699. void Graphics::setFont (const float newFontHeight,
  61700. const int newFontStyleFlags) throw()
  61701. {
  61702. saveStateIfPending();
  61703. state->font.setSizeAndStyle (newFontHeight, newFontStyleFlags, 1.0f, 0.0f);
  61704. }
  61705. const Font& Graphics::getCurrentFont() const throw()
  61706. {
  61707. return state->font;
  61708. }
  61709. void Graphics::drawSingleLineText (const String& text,
  61710. const int startX,
  61711. const int baselineY) const throw()
  61712. {
  61713. if (text.isNotEmpty()
  61714. && startX < context->getClipBounds().getRight())
  61715. {
  61716. GlyphArrangement arr;
  61717. arr.addLineOfText (state->font, text, (float) startX, (float) baselineY);
  61718. arr.draw (*this);
  61719. }
  61720. }
  61721. void Graphics::drawTextAsPath (const String& text,
  61722. const AffineTransform& transform) const throw()
  61723. {
  61724. if (text.isNotEmpty())
  61725. {
  61726. GlyphArrangement arr;
  61727. arr.addLineOfText (state->font, text, 0.0f, 0.0f);
  61728. arr.draw (*this, transform);
  61729. }
  61730. }
  61731. void Graphics::drawMultiLineText (const String& text,
  61732. const int startX,
  61733. const int baselineY,
  61734. const int maximumLineWidth) const throw()
  61735. {
  61736. if (text.isNotEmpty()
  61737. && startX < context->getClipBounds().getRight())
  61738. {
  61739. GlyphArrangement arr;
  61740. arr.addJustifiedText (state->font, text,
  61741. (float) startX, (float) baselineY, (float) maximumLineWidth,
  61742. Justification::left);
  61743. arr.draw (*this);
  61744. }
  61745. }
  61746. void Graphics::drawText (const String& text,
  61747. const int x,
  61748. const int y,
  61749. const int width,
  61750. const int height,
  61751. const Justification& justificationType,
  61752. const bool useEllipsesIfTooBig) const throw()
  61753. {
  61754. if (text.isNotEmpty() && context->clipRegionIntersects (x, y, width, height))
  61755. {
  61756. GlyphArrangement arr;
  61757. arr.addCurtailedLineOfText (state->font, text,
  61758. 0.0f, 0.0f, (float)width,
  61759. useEllipsesIfTooBig);
  61760. arr.justifyGlyphs (0, arr.getNumGlyphs(),
  61761. (float) x, (float) y,
  61762. (float) width, (float) height,
  61763. justificationType);
  61764. arr.draw (*this);
  61765. }
  61766. }
  61767. void Graphics::drawFittedText (const String& text,
  61768. const int x,
  61769. const int y,
  61770. const int width,
  61771. const int height,
  61772. const Justification& justification,
  61773. const int maximumNumberOfLines,
  61774. const float minimumHorizontalScale) const throw()
  61775. {
  61776. if (text.isNotEmpty()
  61777. && width > 0 && height > 0
  61778. && context->clipRegionIntersects (x, y, width, height))
  61779. {
  61780. GlyphArrangement arr;
  61781. arr.addFittedText (state->font, text,
  61782. (float) x, (float) y,
  61783. (float) width, (float) height,
  61784. justification,
  61785. maximumNumberOfLines,
  61786. minimumHorizontalScale);
  61787. arr.draw (*this);
  61788. }
  61789. }
  61790. void Graphics::fillRect (int x,
  61791. int y,
  61792. int width,
  61793. int height) const throw()
  61794. {
  61795. // passing in a silly number can cause maths problems in rendering!
  61796. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (x, y, width, height);
  61797. SolidColourBrush colourBrush (state->colour);
  61798. (state->brush != 0 ? *(state->brush) : (Brush&) colourBrush).paintRectangle (*context, x, y, width, height);
  61799. }
  61800. void Graphics::fillRect (const Rectangle& r) const throw()
  61801. {
  61802. fillRect (r.getX(),
  61803. r.getY(),
  61804. r.getWidth(),
  61805. r.getHeight());
  61806. }
  61807. void Graphics::fillRect (const float x,
  61808. const float y,
  61809. const float width,
  61810. const float height) const throw()
  61811. {
  61812. // passing in a silly number can cause maths problems in rendering!
  61813. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (x, y, width, height);
  61814. Path p;
  61815. p.addRectangle (x, y, width, height);
  61816. fillPath (p);
  61817. }
  61818. void Graphics::setPixel (int x, int y) const throw()
  61819. {
  61820. if (context->clipRegionIntersects (x, y, 1, 1))
  61821. {
  61822. SolidColourBrush colourBrush (state->colour);
  61823. (state->brush != 0 ? *(state->brush) : (Brush&) colourBrush).paintRectangle (*context, x, y, 1, 1);
  61824. }
  61825. }
  61826. void Graphics::fillAll() const throw()
  61827. {
  61828. fillRect (context->getClipBounds());
  61829. }
  61830. void Graphics::fillAll (const Colour& colourToUse) const throw()
  61831. {
  61832. if (! colourToUse.isTransparent())
  61833. {
  61834. const Rectangle clip (context->getClipBounds());
  61835. context->fillRectWithColour (clip.getX(), clip.getY(), clip.getWidth(), clip.getHeight(),
  61836. colourToUse, false);
  61837. }
  61838. }
  61839. void Graphics::fillPath (const Path& path,
  61840. const AffineTransform& transform) const throw()
  61841. {
  61842. if ((! context->isClipEmpty()) && ! path.isEmpty())
  61843. {
  61844. SolidColourBrush colourBrush (state->colour);
  61845. (state->brush != 0 ? *(state->brush) : (Brush&) colourBrush).paintPath (*context, path, transform);
  61846. }
  61847. }
  61848. void Graphics::strokePath (const Path& path,
  61849. const PathStrokeType& strokeType,
  61850. const AffineTransform& transform) const throw()
  61851. {
  61852. if ((! state->colour.isTransparent()) || state->brush != 0)
  61853. {
  61854. Path stroke;
  61855. strokeType.createStrokedPath (stroke, path, transform);
  61856. fillPath (stroke);
  61857. }
  61858. }
  61859. void Graphics::drawRect (const int x,
  61860. const int y,
  61861. const int width,
  61862. const int height,
  61863. const int lineThickness) const throw()
  61864. {
  61865. // passing in a silly number can cause maths problems in rendering!
  61866. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (x, y, width, height);
  61867. SolidColourBrush colourBrush (state->colour);
  61868. Brush& b = (state->brush != 0 ? *(state->brush) : (Brush&) colourBrush);
  61869. b.paintRectangle (*context, x, y, width, lineThickness);
  61870. b.paintRectangle (*context, x, y + lineThickness, lineThickness, height - lineThickness * 2);
  61871. b.paintRectangle (*context, x + width - lineThickness, y + lineThickness, lineThickness, height - lineThickness * 2);
  61872. b.paintRectangle (*context, x, y + height - lineThickness, width, lineThickness);
  61873. }
  61874. void Graphics::drawRect (const float x,
  61875. const float y,
  61876. const float width,
  61877. const float height,
  61878. const float lineThickness) const throw()
  61879. {
  61880. // passing in a silly number can cause maths problems in rendering!
  61881. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (x, y, width, height);
  61882. Path p;
  61883. p.addRectangle (x, y, width, lineThickness);
  61884. p.addRectangle (x, y + lineThickness, lineThickness, height - lineThickness * 2.0f);
  61885. p.addRectangle (x + width - lineThickness, y + lineThickness, lineThickness, height - lineThickness * 2.0f);
  61886. p.addRectangle (x, y + height - lineThickness, width, lineThickness);
  61887. fillPath (p);
  61888. }
  61889. void Graphics::drawRect (const Rectangle& r,
  61890. const int lineThickness) const throw()
  61891. {
  61892. drawRect (r.getX(), r.getY(),
  61893. r.getWidth(), r.getHeight(),
  61894. lineThickness);
  61895. }
  61896. void Graphics::drawBevel (const int x,
  61897. const int y,
  61898. const int width,
  61899. const int height,
  61900. const int bevelThickness,
  61901. const Colour& topLeftColour,
  61902. const Colour& bottomRightColour,
  61903. const bool useGradient,
  61904. const bool sharpEdgeOnOutside) const throw()
  61905. {
  61906. // passing in a silly number can cause maths problems in rendering!
  61907. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (x, y, width, height);
  61908. if (clipRegionIntersects (x, y, width, height))
  61909. {
  61910. const float oldOpacity = state->colour.getFloatAlpha();
  61911. const float ramp = oldOpacity / bevelThickness;
  61912. for (int i = bevelThickness; --i >= 0;)
  61913. {
  61914. const float op = useGradient ? ramp * (sharpEdgeOnOutside ? bevelThickness - i : i)
  61915. : oldOpacity;
  61916. context->fillRectWithColour (x + i, y + i, width - i * 2, 1, topLeftColour.withMultipliedAlpha (op), false);
  61917. context->fillRectWithColour (x + i, y + i + 1, 1, height - i * 2 - 2, topLeftColour.withMultipliedAlpha (op * 0.75f), false);
  61918. context->fillRectWithColour (x + i, y + height - i - 1, width - i * 2, 1, bottomRightColour.withMultipliedAlpha (op), false);
  61919. context->fillRectWithColour (x + width - i - 1, y + i + 1, 1, height - i * 2 - 2, bottomRightColour.withMultipliedAlpha (op * 0.75f), false);
  61920. }
  61921. }
  61922. }
  61923. void Graphics::fillEllipse (const float x,
  61924. const float y,
  61925. const float width,
  61926. const float height) const throw()
  61927. {
  61928. // passing in a silly number can cause maths problems in rendering!
  61929. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (x, y, width, height);
  61930. Path p;
  61931. p.addEllipse (x, y, width, height);
  61932. fillPath (p);
  61933. }
  61934. void Graphics::drawEllipse (const float x,
  61935. const float y,
  61936. const float width,
  61937. const float height,
  61938. const float lineThickness) const throw()
  61939. {
  61940. // passing in a silly number can cause maths problems in rendering!
  61941. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (x, y, width, height);
  61942. Path p;
  61943. p.addEllipse (x, y, width, height);
  61944. strokePath (p, PathStrokeType (lineThickness));
  61945. }
  61946. void Graphics::fillRoundedRectangle (const float x,
  61947. const float y,
  61948. const float width,
  61949. const float height,
  61950. const float cornerSize) const throw()
  61951. {
  61952. // passing in a silly number can cause maths problems in rendering!
  61953. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (x, y, width, height);
  61954. Path p;
  61955. p.addRoundedRectangle (x, y, width, height, cornerSize);
  61956. fillPath (p);
  61957. }
  61958. void Graphics::fillRoundedRectangle (const Rectangle& r,
  61959. const float cornerSize) const throw()
  61960. {
  61961. fillRoundedRectangle ((float) r.getX(),
  61962. (float) r.getY(),
  61963. (float) r.getWidth(),
  61964. (float) r.getHeight(),
  61965. cornerSize);
  61966. }
  61967. void Graphics::drawRoundedRectangle (const float x,
  61968. const float y,
  61969. const float width,
  61970. const float height,
  61971. const float cornerSize,
  61972. const float lineThickness) const throw()
  61973. {
  61974. // passing in a silly number can cause maths problems in rendering!
  61975. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (x, y, width, height);
  61976. Path p;
  61977. p.addRoundedRectangle (x, y, width, height, cornerSize);
  61978. strokePath (p, PathStrokeType (lineThickness));
  61979. }
  61980. void Graphics::drawRoundedRectangle (const Rectangle& r,
  61981. const float cornerSize,
  61982. const float lineThickness) const throw()
  61983. {
  61984. drawRoundedRectangle ((float) r.getX(),
  61985. (float) r.getY(),
  61986. (float) r.getWidth(),
  61987. (float) r.getHeight(),
  61988. cornerSize, lineThickness);
  61989. }
  61990. void Graphics::drawArrow (const float startX,
  61991. const float startY,
  61992. const float endX,
  61993. const float endY,
  61994. const float lineThickness,
  61995. const float arrowheadWidth,
  61996. const float arrowheadLength) const throw()
  61997. {
  61998. Path p;
  61999. p.addArrow (startX, startY, endX, endY,
  62000. lineThickness, arrowheadWidth, arrowheadLength);
  62001. fillPath (p);
  62002. }
  62003. void Graphics::fillCheckerBoard (int x, int y,
  62004. int width, int height,
  62005. const int checkWidth,
  62006. const int checkHeight,
  62007. const Colour& colour1,
  62008. const Colour& colour2) const throw()
  62009. {
  62010. jassert (checkWidth > 0 && checkHeight > 0); // can't be zero or less!
  62011. if (checkWidth > 0 && checkHeight > 0)
  62012. {
  62013. if (colour1 == colour2)
  62014. {
  62015. context->fillRectWithColour (x, y, width, height, colour1, false);
  62016. }
  62017. else
  62018. {
  62019. const Rectangle clip (context->getClipBounds());
  62020. const int right = jmin (x + width, clip.getRight());
  62021. const int bottom = jmin (y + height, clip.getBottom());
  62022. int cy = 0;
  62023. while (y < bottom)
  62024. {
  62025. int cx = cy;
  62026. for (int xx = x; xx < right; xx += checkWidth)
  62027. context->fillRectWithColour (xx, y,
  62028. jmin (checkWidth, right - xx),
  62029. jmin (checkHeight, bottom - y),
  62030. ((cx++ & 1) == 0) ? colour1 : colour2,
  62031. false);
  62032. ++cy;
  62033. y += checkHeight;
  62034. }
  62035. }
  62036. }
  62037. }
  62038. void Graphics::drawVerticalLine (const int x, float top, float bottom) const throw()
  62039. {
  62040. SolidColourBrush colourBrush (state->colour);
  62041. (state->brush != 0 ? *(state->brush) : (Brush&) colourBrush).paintVerticalLine (*context, x, top, bottom);
  62042. }
  62043. void Graphics::drawHorizontalLine (const int y, float left, float right) const throw()
  62044. {
  62045. SolidColourBrush colourBrush (state->colour);
  62046. (state->brush != 0 ? *(state->brush) : (Brush&) colourBrush).paintHorizontalLine (*context, y, left, right);
  62047. }
  62048. void Graphics::drawLine (float x1, float y1,
  62049. float x2, float y2) const throw()
  62050. {
  62051. if (! context->isClipEmpty())
  62052. {
  62053. SolidColourBrush colourBrush (state->colour);
  62054. (state->brush != 0 ? *(state->brush) : (Brush&) colourBrush).paintLine (*context, x1, y1, x2, y2);
  62055. }
  62056. }
  62057. void Graphics::drawLine (const float startX,
  62058. const float startY,
  62059. const float endX,
  62060. const float endY,
  62061. const float lineThickness) const throw()
  62062. {
  62063. Path p;
  62064. p.addLineSegment (startX, startY, endX, endY, lineThickness);
  62065. fillPath (p);
  62066. }
  62067. void Graphics::drawLine (const Line& line) const throw()
  62068. {
  62069. drawLine (line.getStartX(), line.getStartY(), line.getEndX(), line.getEndY());
  62070. }
  62071. void Graphics::drawLine (const Line& line,
  62072. const float lineThickness) const throw()
  62073. {
  62074. drawLine (line.getStartX(), line.getStartY(), line.getEndX(), line.getEndY(), lineThickness);
  62075. }
  62076. void Graphics::drawDashedLine (const float startX,
  62077. const float startY,
  62078. const float endX,
  62079. const float endY,
  62080. const float* const dashLengths,
  62081. const int numDashLengths,
  62082. const float lineThickness) const throw()
  62083. {
  62084. const double dx = endX - startX;
  62085. const double dy = endY - startY;
  62086. const double totalLen = juce_hypot (dx, dy);
  62087. if (totalLen >= 0.5)
  62088. {
  62089. const double onePixAlpha = 1.0 / totalLen;
  62090. double alpha = 0.0;
  62091. float x = startX;
  62092. float y = startY;
  62093. int n = 0;
  62094. while (alpha < 1.0f)
  62095. {
  62096. alpha = jmin (1.0, alpha + dashLengths[n++] * onePixAlpha);
  62097. n = n % numDashLengths;
  62098. const float oldX = x;
  62099. const float oldY = y;
  62100. x = (float) (startX + dx * alpha);
  62101. y = (float) (startY + dy * alpha);
  62102. if ((n & 1) != 0)
  62103. {
  62104. if (lineThickness != 1.0f)
  62105. drawLine (oldX, oldY, x, y, lineThickness);
  62106. else
  62107. drawLine (oldX, oldY, x, y);
  62108. }
  62109. }
  62110. }
  62111. }
  62112. void Graphics::setImageResamplingQuality (const Graphics::ResamplingQuality newQuality) throw()
  62113. {
  62114. saveStateIfPending();
  62115. state->quality = newQuality;
  62116. }
  62117. void Graphics::drawImageAt (const Image* const imageToDraw,
  62118. const int topLeftX,
  62119. const int topLeftY,
  62120. const bool fillAlphaChannelWithCurrentBrush) const throw()
  62121. {
  62122. if (imageToDraw != 0)
  62123. {
  62124. const int imageW = imageToDraw->getWidth();
  62125. const int imageH = imageToDraw->getHeight();
  62126. drawImage (imageToDraw,
  62127. topLeftX, topLeftY, imageW, imageH,
  62128. 0, 0, imageW, imageH,
  62129. fillAlphaChannelWithCurrentBrush);
  62130. }
  62131. }
  62132. void Graphics::drawImageWithin (const Image* const imageToDraw,
  62133. const int destX,
  62134. const int destY,
  62135. const int destW,
  62136. const int destH,
  62137. const RectanglePlacement& placementWithinTarget,
  62138. const bool fillAlphaChannelWithCurrentBrush) const throw()
  62139. {
  62140. // passing in a silly number can cause maths problems in rendering!
  62141. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (destX, destY, destW, destH);
  62142. if (imageToDraw != 0)
  62143. {
  62144. const int imageW = imageToDraw->getWidth();
  62145. const int imageH = imageToDraw->getHeight();
  62146. if (imageW > 0 && imageH > 0)
  62147. {
  62148. double newX = 0.0, newY = 0.0;
  62149. double newW = imageW;
  62150. double newH = imageH;
  62151. placementWithinTarget.applyTo (newX, newY, newW, newH,
  62152. destX, destY, destW, destH);
  62153. if (newW > 0 && newH > 0)
  62154. {
  62155. drawImage (imageToDraw,
  62156. roundDoubleToInt (newX), roundDoubleToInt (newY),
  62157. roundDoubleToInt (newW), roundDoubleToInt (newH),
  62158. 0, 0, imageW, imageH,
  62159. fillAlphaChannelWithCurrentBrush);
  62160. }
  62161. }
  62162. }
  62163. }
  62164. void Graphics::drawImage (const Image* const imageToDraw,
  62165. int dx, int dy, int dw, int dh,
  62166. int sx, int sy, int sw, int sh,
  62167. const bool fillAlphaChannelWithCurrentBrush) const throw()
  62168. {
  62169. // passing in a silly number can cause maths problems in rendering!
  62170. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (dx, dy, dw, dh);
  62171. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (sx, sy, sw, sh);
  62172. if (imageToDraw == 0 || ! context->clipRegionIntersects (dx, dy, dw, dh))
  62173. return;
  62174. if (sw == dw && sh == dh)
  62175. {
  62176. if (sx < 0)
  62177. {
  62178. dx -= sx;
  62179. dw += sx;
  62180. sw += sx;
  62181. sx = 0;
  62182. }
  62183. if (sx + sw > imageToDraw->getWidth())
  62184. {
  62185. const int amount = sx + sw - imageToDraw->getWidth();
  62186. dw -= amount;
  62187. sw -= amount;
  62188. }
  62189. if (sy < 0)
  62190. {
  62191. dy -= sy;
  62192. dh += sy;
  62193. sh += sy;
  62194. sy = 0;
  62195. }
  62196. if (sy + sh > imageToDraw->getHeight())
  62197. {
  62198. const int amount = sy + sh - imageToDraw->getHeight();
  62199. dh -= amount;
  62200. sh -= amount;
  62201. }
  62202. if (dw <= 0 || dh <= 0 || sw <= 0 || sh <= 0)
  62203. return;
  62204. if (fillAlphaChannelWithCurrentBrush)
  62205. {
  62206. SolidColourBrush colourBrush (state->colour);
  62207. (state->brush != 0 ? *(state->brush) : (Brush&) colourBrush)
  62208. .paintAlphaChannel (*context, *imageToDraw,
  62209. dx - sx, dy - sy,
  62210. dx, dy,
  62211. dw, dh);
  62212. }
  62213. else
  62214. {
  62215. context->blendImage (*imageToDraw,
  62216. dx, dy, dw, dh, sx, sy,
  62217. state->colour.getFloatAlpha());
  62218. }
  62219. }
  62220. else
  62221. {
  62222. if (dw <= 0 || dh <= 0 || sw <= 0 || sh <= 0)
  62223. return;
  62224. if (fillAlphaChannelWithCurrentBrush)
  62225. {
  62226. if (imageToDraw->isRGB())
  62227. {
  62228. fillRect (dx, dy, dw, dh);
  62229. }
  62230. else
  62231. {
  62232. int tx = dx;
  62233. int ty = dy;
  62234. int tw = dw;
  62235. int th = dh;
  62236. if (context->getClipBounds().intersectRectangle (tx, ty, tw, th))
  62237. {
  62238. Image temp (imageToDraw->getFormat(), tw, th, true);
  62239. Graphics g (temp);
  62240. g.setImageResamplingQuality (state->quality);
  62241. g.setOrigin (dx - tx, dy - ty);
  62242. g.drawImage (imageToDraw,
  62243. 0, 0, dw, dh,
  62244. sx, sy, sw, sh,
  62245. false);
  62246. SolidColourBrush colourBrush (state->colour);
  62247. (state->brush != 0 ? *(state->brush) : (Brush&) colourBrush)
  62248. .paintAlphaChannel (*context, temp, tx, ty, tx, ty, tw, th);
  62249. }
  62250. }
  62251. }
  62252. else
  62253. {
  62254. context->blendImageRescaling (*imageToDraw,
  62255. dx, dy, dw, dh,
  62256. sx, sy, sw, sh,
  62257. state->colour.getFloatAlpha(),
  62258. state->quality);
  62259. }
  62260. }
  62261. }
  62262. void Graphics::drawImageTransformed (const Image* const imageToDraw,
  62263. int sourceClipX,
  62264. int sourceClipY,
  62265. int sourceClipWidth,
  62266. int sourceClipHeight,
  62267. const AffineTransform& transform,
  62268. const bool fillAlphaChannelWithCurrentBrush) const throw()
  62269. {
  62270. if (imageToDraw != 0
  62271. && (! context->isClipEmpty())
  62272. && ! transform.isSingularity())
  62273. {
  62274. if (transform.isIdentity())
  62275. {
  62276. drawImage (imageToDraw,
  62277. sourceClipX, sourceClipY, sourceClipWidth, sourceClipHeight,
  62278. sourceClipX, sourceClipY, sourceClipWidth, sourceClipHeight,
  62279. fillAlphaChannelWithCurrentBrush);
  62280. }
  62281. else if (fillAlphaChannelWithCurrentBrush)
  62282. {
  62283. Path p;
  62284. p.addRectangle ((float) sourceClipX, (float) sourceClipY,
  62285. (float) sourceClipWidth, (float) sourceClipHeight);
  62286. p.applyTransform (transform);
  62287. float dx, dy, dw, dh;
  62288. p.getBounds (dx, dy, dw, dh);
  62289. int tx = (int) dx;
  62290. int ty = (int) dy;
  62291. int tw = roundFloatToInt (dw) + 2;
  62292. int th = roundFloatToInt (dh) + 2;
  62293. if (context->getClipBounds().intersectRectangle (tx, ty, tw, th))
  62294. {
  62295. Image temp (imageToDraw->getFormat(), tw, th, true);
  62296. Graphics g (temp);
  62297. g.setImageResamplingQuality (state->quality);
  62298. g.drawImageTransformed (imageToDraw,
  62299. sourceClipX,
  62300. sourceClipY,
  62301. sourceClipWidth,
  62302. sourceClipHeight,
  62303. transform.translated ((float) -tx, (float) -ty),
  62304. false);
  62305. SolidColourBrush colourBrush (state->colour);
  62306. (state->brush != 0 ? *(state->brush) : (Brush&) colourBrush).paintAlphaChannel (*context, temp, tx, ty, tx, ty, tw, th);
  62307. }
  62308. }
  62309. else
  62310. {
  62311. context->blendImageWarping (*imageToDraw,
  62312. sourceClipX,
  62313. sourceClipY,
  62314. sourceClipWidth,
  62315. sourceClipHeight,
  62316. transform,
  62317. state->colour.getFloatAlpha(),
  62318. state->quality);
  62319. }
  62320. }
  62321. }
  62322. END_JUCE_NAMESPACE
  62323. /********* End of inlined file: juce_Graphics.cpp *********/
  62324. /********* Start of inlined file: juce_Justification.cpp *********/
  62325. BEGIN_JUCE_NAMESPACE
  62326. Justification::Justification (const Justification& other) throw()
  62327. : flags (other.flags)
  62328. {
  62329. }
  62330. const Justification& Justification::operator= (const Justification& other) throw()
  62331. {
  62332. flags = other.flags;
  62333. return *this;
  62334. }
  62335. int Justification::getOnlyVerticalFlags() const throw()
  62336. {
  62337. return flags & (top | bottom | verticallyCentred);
  62338. }
  62339. int Justification::getOnlyHorizontalFlags() const throw()
  62340. {
  62341. return flags & (left | right | horizontallyCentred | horizontallyJustified);
  62342. }
  62343. void Justification::applyToRectangle (int& x, int& y,
  62344. const int w, const int h,
  62345. const int spaceX, const int spaceY,
  62346. const int spaceW, const int spaceH) const throw()
  62347. {
  62348. if ((flags & horizontallyCentred) != 0)
  62349. {
  62350. x = spaceX + ((spaceW - w) >> 1);
  62351. }
  62352. else if ((flags & right) != 0)
  62353. {
  62354. x = spaceX + spaceW - w;
  62355. }
  62356. else
  62357. {
  62358. x = spaceX;
  62359. }
  62360. if ((flags & verticallyCentred) != 0)
  62361. {
  62362. y = spaceY + ((spaceH - h) >> 1);
  62363. }
  62364. else if ((flags & bottom) != 0)
  62365. {
  62366. y = spaceY + spaceH - h;
  62367. }
  62368. else
  62369. {
  62370. y = spaceY;
  62371. }
  62372. }
  62373. END_JUCE_NAMESPACE
  62374. /********* End of inlined file: juce_Justification.cpp *********/
  62375. /********* Start of inlined file: juce_LowLevelGraphicsPostScriptRenderer.cpp *********/
  62376. BEGIN_JUCE_NAMESPACE
  62377. #if JUCE_MSVC
  62378. #pragma warning (disable: 4996) // deprecated sprintf warning
  62379. #endif
  62380. // this will throw an assertion if you try to draw something that's not
  62381. // possible in postscript
  62382. #define WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS 0
  62383. #if defined (JUCE_DEBUG) && WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS
  62384. #define notPossibleInPostscriptAssert jassertfalse
  62385. #else
  62386. #define notPossibleInPostscriptAssert
  62387. #endif
  62388. LowLevelGraphicsPostScriptRenderer::LowLevelGraphicsPostScriptRenderer (OutputStream& resultingPostScript,
  62389. const String& documentTitle,
  62390. const int totalWidth_,
  62391. const int totalHeight_)
  62392. : out (resultingPostScript),
  62393. totalWidth (totalWidth_),
  62394. totalHeight (totalHeight_),
  62395. xOffset (0),
  62396. yOffset (0),
  62397. needToClip (true)
  62398. {
  62399. clip = new RectangleList (Rectangle (0, 0, totalWidth_, totalHeight_));
  62400. const float scale = jmin ((520.0f / totalWidth_), (750.0f / totalHeight));
  62401. out << "%!PS-Adobe-3.0 EPSF-3.0"
  62402. "\n%%BoundingBox: 0 0 600 824"
  62403. "\n%%Pages: 0"
  62404. "\n%%Creator: Raw Material Software JUCE"
  62405. "\n%%Title: " << documentTitle <<
  62406. "\n%%CreationDate: none"
  62407. "\n%%LanguageLevel: 2"
  62408. "\n%%EndComments"
  62409. "\n%%BeginProlog"
  62410. "\n%%BeginResource: JRes"
  62411. "\n/bd {bind def} bind def"
  62412. "\n/c {setrgbcolor} bd"
  62413. "\n/m {moveto} bd"
  62414. "\n/l {lineto} bd"
  62415. "\n/rl {rlineto} bd"
  62416. "\n/ct {curveto} bd"
  62417. "\n/cp {closepath} bd"
  62418. "\n/pr {3 index 3 index moveto 1 index 0 rlineto 0 1 index rlineto pop neg 0 rlineto pop pop closepath} bd"
  62419. "\n/doclip {initclip newpath} bd"
  62420. "\n/endclip {clip newpath} bd"
  62421. "\n%%EndResource"
  62422. "\n%%EndProlog"
  62423. "\n%%BeginSetup"
  62424. "\n%%EndSetup"
  62425. "\n%%Page: 1 1"
  62426. "\n%%BeginPageSetup"
  62427. "\n%%EndPageSetup\n\n"
  62428. << "40 800 translate\n"
  62429. << scale << ' ' << scale << " scale\n\n";
  62430. }
  62431. LowLevelGraphicsPostScriptRenderer::~LowLevelGraphicsPostScriptRenderer()
  62432. {
  62433. delete clip;
  62434. }
  62435. bool LowLevelGraphicsPostScriptRenderer::isVectorDevice() const
  62436. {
  62437. return true;
  62438. }
  62439. void LowLevelGraphicsPostScriptRenderer::setOrigin (int x, int y)
  62440. {
  62441. if (x != 0 || y != 0)
  62442. {
  62443. xOffset += x;
  62444. yOffset += y;
  62445. needToClip = true;
  62446. }
  62447. }
  62448. bool LowLevelGraphicsPostScriptRenderer::reduceClipRegion (int x, int y, int w, int h)
  62449. {
  62450. needToClip = true;
  62451. return clip->clipTo (Rectangle (x + xOffset, y + yOffset, w, h));
  62452. }
  62453. bool LowLevelGraphicsPostScriptRenderer::reduceClipRegion (const RectangleList& clipRegion)
  62454. {
  62455. needToClip = true;
  62456. return clip->clipTo (clipRegion);
  62457. }
  62458. void LowLevelGraphicsPostScriptRenderer::excludeClipRegion (int x, int y, int w, int h)
  62459. {
  62460. needToClip = true;
  62461. clip->subtract (Rectangle (x + xOffset, y + yOffset, w, h));
  62462. }
  62463. bool LowLevelGraphicsPostScriptRenderer::clipRegionIntersects (int x, int y, int w, int h)
  62464. {
  62465. return clip->intersectsRectangle (Rectangle (x + xOffset, y + yOffset, w, h));
  62466. }
  62467. const Rectangle LowLevelGraphicsPostScriptRenderer::getClipBounds() const
  62468. {
  62469. return clip->getBounds().translated (-xOffset, -yOffset);
  62470. }
  62471. bool LowLevelGraphicsPostScriptRenderer::isClipEmpty() const
  62472. {
  62473. return clip->isEmpty();
  62474. }
  62475. LowLevelGraphicsPostScriptRenderer::SavedState::SavedState (RectangleList* const clip_,
  62476. const int xOffset_, const int yOffset_)
  62477. : clip (clip_),
  62478. xOffset (xOffset_),
  62479. yOffset (yOffset_)
  62480. {
  62481. }
  62482. LowLevelGraphicsPostScriptRenderer::SavedState::~SavedState()
  62483. {
  62484. delete clip;
  62485. }
  62486. void LowLevelGraphicsPostScriptRenderer::saveState()
  62487. {
  62488. stateStack.add (new SavedState (new RectangleList (*clip), xOffset, yOffset));
  62489. }
  62490. void LowLevelGraphicsPostScriptRenderer::restoreState()
  62491. {
  62492. SavedState* const top = stateStack.getLast();
  62493. if (top != 0)
  62494. {
  62495. clip->swapWith (*top->clip);
  62496. xOffset = top->xOffset;
  62497. yOffset = top->yOffset;
  62498. stateStack.removeLast();
  62499. needToClip = true;
  62500. }
  62501. else
  62502. {
  62503. jassertfalse // trying to pop with an empty stack!
  62504. }
  62505. }
  62506. void LowLevelGraphicsPostScriptRenderer::writeClip()
  62507. {
  62508. if (needToClip)
  62509. {
  62510. needToClip = false;
  62511. out << "doclip ";
  62512. int itemsOnLine = 0;
  62513. for (RectangleList::Iterator i (*clip); i.next();)
  62514. {
  62515. if (++itemsOnLine == 6)
  62516. {
  62517. itemsOnLine = 0;
  62518. out << '\n';
  62519. }
  62520. const Rectangle& r = *i.getRectangle();
  62521. out << r.getX() << ' ' << -r.getY() << ' '
  62522. << r.getWidth() << ' ' << -r.getHeight() << " pr ";
  62523. }
  62524. out << "endclip\n";
  62525. }
  62526. }
  62527. void LowLevelGraphicsPostScriptRenderer::writeColour (const Colour& colour)
  62528. {
  62529. Colour c (Colours::white.overlaidWith (colour));
  62530. if (lastColour != c)
  62531. {
  62532. lastColour = c;
  62533. out << String (c.getFloatRed(), 3) << ' '
  62534. << String (c.getFloatGreen(), 3) << ' '
  62535. << String (c.getFloatBlue(), 3) << " c\n";
  62536. }
  62537. }
  62538. void LowLevelGraphicsPostScriptRenderer::writeXY (const float x, const float y) const
  62539. {
  62540. out << String (x, 2) << ' '
  62541. << String (-y, 2) << ' ';
  62542. }
  62543. void LowLevelGraphicsPostScriptRenderer::writePath (const Path& path) const
  62544. {
  62545. out << "newpath ";
  62546. float lastX = 0.0f;
  62547. float lastY = 0.0f;
  62548. int itemsOnLine = 0;
  62549. Path::Iterator i (path);
  62550. while (i.next())
  62551. {
  62552. if (++itemsOnLine == 4)
  62553. {
  62554. itemsOnLine = 0;
  62555. out << '\n';
  62556. }
  62557. switch (i.elementType)
  62558. {
  62559. case Path::Iterator::startNewSubPath:
  62560. writeXY (i.x1, i.y1);
  62561. lastX = i.x1;
  62562. lastY = i.y1;
  62563. out << "m ";
  62564. break;
  62565. case Path::Iterator::lineTo:
  62566. writeXY (i.x1, i.y1);
  62567. lastX = i.x1;
  62568. lastY = i.y1;
  62569. out << "l ";
  62570. break;
  62571. case Path::Iterator::quadraticTo:
  62572. {
  62573. const float cp1x = lastX + (i.x1 - lastX) * 2.0f / 3.0f;
  62574. const float cp1y = lastY + (i.y1 - lastY) * 2.0f / 3.0f;
  62575. const float cp2x = cp1x + (i.x2 - lastX) / 3.0f;
  62576. const float cp2y = cp1y + (i.y2 - lastY) / 3.0f;
  62577. writeXY (cp1x, cp1y);
  62578. writeXY (cp2x, cp2y);
  62579. writeXY (i.x2, i.y2);
  62580. out << "ct ";
  62581. lastX = i.x2;
  62582. lastY = i.y2;
  62583. }
  62584. break;
  62585. case Path::Iterator::cubicTo:
  62586. writeXY (i.x1, i.y1);
  62587. writeXY (i.x2, i.y2);
  62588. writeXY (i.x3, i.y3);
  62589. out << "ct ";
  62590. lastX = i.x3;
  62591. lastY = i.y3;
  62592. break;
  62593. case Path::Iterator::closePath:
  62594. out << "cp ";
  62595. break;
  62596. default:
  62597. jassertfalse
  62598. break;
  62599. }
  62600. }
  62601. out << '\n';
  62602. }
  62603. void LowLevelGraphicsPostScriptRenderer::writeTransform (const AffineTransform& trans) const
  62604. {
  62605. out << "[ "
  62606. << trans.mat00 << ' '
  62607. << trans.mat10 << ' '
  62608. << trans.mat01 << ' '
  62609. << trans.mat11 << ' '
  62610. << trans.mat02 << ' '
  62611. << trans.mat12 << " ] concat ";
  62612. }
  62613. void LowLevelGraphicsPostScriptRenderer::fillRectWithColour (int x, int y, int w, int h, const Colour& colour, const bool /*replaceExistingContents*/)
  62614. {
  62615. writeClip();
  62616. writeColour (colour);
  62617. x += xOffset;
  62618. y += yOffset;
  62619. out << x << ' ' << -(y + h) << ' ' << w << ' ' << h << " rectfill\n";
  62620. }
  62621. void LowLevelGraphicsPostScriptRenderer::fillRectWithGradient (int x, int y, int w, int h, const ColourGradient& gradient)
  62622. {
  62623. Path p;
  62624. p.addRectangle ((float) x, (float) y, (float) w, (float) h);
  62625. fillPathWithGradient (p, AffineTransform::identity, gradient, EdgeTable::Oversampling_256times);
  62626. }
  62627. void LowLevelGraphicsPostScriptRenderer::fillPathWithColour (const Path& path, const AffineTransform& t,
  62628. const Colour& colour, EdgeTable::OversamplingLevel /*quality*/)
  62629. {
  62630. writeClip();
  62631. Path p (path);
  62632. p.applyTransform (t.translated ((float) xOffset, (float) yOffset));
  62633. writePath (p);
  62634. writeColour (colour);
  62635. out << "fill\n";
  62636. }
  62637. void LowLevelGraphicsPostScriptRenderer::fillPathWithGradient (const Path& path, const AffineTransform& t, const ColourGradient& gradient, EdgeTable::OversamplingLevel /*quality*/)
  62638. {
  62639. // this doesn't work correctly yet - it could be improved to handle solid gradients, but
  62640. // postscript can't do semi-transparent ones.
  62641. notPossibleInPostscriptAssert // you can disable this warning by setting the WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS flag at the top of this file
  62642. writeClip();
  62643. out << "gsave ";
  62644. {
  62645. Path p (path);
  62646. p.applyTransform (t.translated ((float) xOffset, (float) yOffset));
  62647. writePath (p);
  62648. out << "clip\n";
  62649. }
  62650. int numColours = 256;
  62651. PixelARGB* const colours = gradient.createLookupTable (numColours);
  62652. for (int i = numColours; --i >= 0;)
  62653. colours[i].unpremultiply();
  62654. const Rectangle bounds (clip->getBounds());
  62655. // ideally this would draw lots of lines or ellipses to approximate the gradient, but for the
  62656. // time-being, this just fills it with the average colour..
  62657. writeColour (Colour (colours [numColours / 2].getARGB()));
  62658. out << bounds.getX() << ' ' << -bounds.getBottom() << ' ' << bounds.getWidth() << ' ' << bounds.getHeight() << " rectfill\n";
  62659. juce_free (colours);
  62660. out << "grestore\n";
  62661. }
  62662. void LowLevelGraphicsPostScriptRenderer::fillPathWithImage (const Path& path, const AffineTransform& transform,
  62663. const Image& sourceImage,
  62664. int imageX, int imageY,
  62665. float opacity, EdgeTable::OversamplingLevel /*quality*/)
  62666. {
  62667. writeClip();
  62668. out << "gsave ";
  62669. Path p (path);
  62670. p.applyTransform (transform.translated ((float) xOffset, (float) yOffset));
  62671. writePath (p);
  62672. out << "clip\n";
  62673. blendImage (sourceImage, imageX, imageY, sourceImage.getWidth(), sourceImage.getHeight(), 0, 0, opacity);
  62674. out << "grestore\n";
  62675. }
  62676. void LowLevelGraphicsPostScriptRenderer::fillAlphaChannelWithColour (const Image& /*clipImage*/, int x, int y, const Colour& colour)
  62677. {
  62678. x += xOffset;
  62679. y += yOffset;
  62680. writeClip();
  62681. writeColour (colour);
  62682. notPossibleInPostscriptAssert // you can disable this warning by setting the WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS flag at the top of this file
  62683. }
  62684. void LowLevelGraphicsPostScriptRenderer::fillAlphaChannelWithGradient (const Image& /*alphaChannelImage*/, int imageX, int imageY, const ColourGradient& /*gradient*/)
  62685. {
  62686. imageX += xOffset;
  62687. imageY += yOffset;
  62688. writeClip();
  62689. notPossibleInPostscriptAssert // you can disable this warning by setting the WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS flag at the top of this file
  62690. }
  62691. void LowLevelGraphicsPostScriptRenderer::fillAlphaChannelWithImage (const Image& /*alphaImage*/, int alphaImageX, int alphaImageY,
  62692. const Image& /*fillerImage*/, int fillerImageX, int fillerImageY, float /*opacity*/)
  62693. {
  62694. alphaImageX += xOffset;
  62695. alphaImageY += yOffset;
  62696. fillerImageX += xOffset;
  62697. fillerImageY += yOffset;
  62698. writeClip();
  62699. notPossibleInPostscriptAssert // you can disable this warning by setting the WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS flag at the top of this file
  62700. }
  62701. void LowLevelGraphicsPostScriptRenderer::blendImageRescaling (const Image& sourceImage,
  62702. int dx, int dy, int dw, int dh,
  62703. int sx, int sy, int sw, int sh,
  62704. float alpha,
  62705. const Graphics::ResamplingQuality quality)
  62706. {
  62707. if (sw > 0 && sh > 0)
  62708. {
  62709. jassert (sx >= 0 && sx + sw <= sourceImage.getWidth());
  62710. jassert (sy >= 0 && sy + sh <= sourceImage.getHeight());
  62711. if (sw == dw && sh == dh)
  62712. {
  62713. blendImage (sourceImage,
  62714. dx, dy, dw, dh,
  62715. sx, sy, alpha);
  62716. }
  62717. else
  62718. {
  62719. blendImageWarping (sourceImage,
  62720. sx, sy, sw, sh,
  62721. AffineTransform::scale (dw / (float) sw,
  62722. dh / (float) sh)
  62723. .translated ((float) (dx - sx),
  62724. (float) (dy - sy)),
  62725. alpha,
  62726. quality);
  62727. }
  62728. }
  62729. }
  62730. void LowLevelGraphicsPostScriptRenderer::blendImage (const Image& sourceImage, int dx, int dy, int dw, int dh, int sx, int sy, float opacity)
  62731. {
  62732. blendImageWarping (sourceImage,
  62733. sx, sy, dw, dh,
  62734. AffineTransform::translation ((float) dx, (float) dy),
  62735. opacity, Graphics::highResamplingQuality);
  62736. }
  62737. void LowLevelGraphicsPostScriptRenderer::writeImage (const Image& im,
  62738. const int sx, const int sy,
  62739. const int maxW, const int maxH) const
  62740. {
  62741. out << "{<\n";
  62742. const int w = jmin (maxW, im.getWidth());
  62743. const int h = jmin (maxH, im.getHeight());
  62744. int charsOnLine = 0;
  62745. int lineStride, pixelStride;
  62746. const uint8* data = im.lockPixelDataReadOnly (0, 0, w, h, lineStride, pixelStride);
  62747. Colour pixel;
  62748. for (int y = h; --y >= 0;)
  62749. {
  62750. for (int x = 0; x < w; ++x)
  62751. {
  62752. const uint8* pixelData = data + lineStride * y + pixelStride * x;
  62753. if (x >= sx && y >= sy)
  62754. {
  62755. if (im.isARGB())
  62756. {
  62757. PixelARGB p (*(const PixelARGB*) pixelData);
  62758. p.unpremultiply();
  62759. pixel = Colours::white.overlaidWith (Colour (p.getARGB()));
  62760. }
  62761. else if (im.isRGB())
  62762. {
  62763. pixel = Colour (((const PixelRGB*) pixelData)->getARGB());
  62764. }
  62765. else
  62766. {
  62767. pixel = Colour ((uint8) 0, (uint8) 0, (uint8) 0, *pixelData);
  62768. }
  62769. }
  62770. else
  62771. {
  62772. pixel = Colours::transparentWhite;
  62773. }
  62774. char colourString [16];
  62775. sprintf (colourString, "%x%x%x", pixel.getRed(), pixel.getGreen(), pixel.getBlue());
  62776. out << (const char*) colourString;
  62777. charsOnLine += 3;
  62778. if (charsOnLine > 100)
  62779. {
  62780. out << '\n';
  62781. charsOnLine = 0;
  62782. }
  62783. }
  62784. }
  62785. im.releasePixelDataReadOnly (data);
  62786. out << "\n>}\n";
  62787. }
  62788. void LowLevelGraphicsPostScriptRenderer::blendImageWarping (const Image& sourceImage,
  62789. int srcClipX, int srcClipY,
  62790. int srcClipW, int srcClipH,
  62791. const AffineTransform& t,
  62792. float /*opacity*/,
  62793. const Graphics::ResamplingQuality /*quality*/)
  62794. {
  62795. const int w = jmin (sourceImage.getWidth(), srcClipX + srcClipW);
  62796. const int h = jmin (sourceImage.getHeight(), srcClipY + srcClipH);
  62797. writeClip();
  62798. out << "gsave ";
  62799. writeTransform (t.translated ((float) xOffset, (float) yOffset)
  62800. .scaled (1.0f, -1.0f));
  62801. RectangleList imageClip;
  62802. sourceImage.createSolidAreaMask (imageClip, 0.5f);
  62803. imageClip.clipTo (Rectangle (srcClipX, srcClipY, srcClipW, srcClipH));
  62804. out << "newpath ";
  62805. int itemsOnLine = 0;
  62806. for (RectangleList::Iterator i (imageClip); i.next();)
  62807. {
  62808. if (++itemsOnLine == 6)
  62809. {
  62810. out << '\n';
  62811. itemsOnLine = 0;
  62812. }
  62813. const Rectangle& r = *i.getRectangle();
  62814. out << r.getX() << ' ' << r.getY() << ' ' << r.getWidth() << ' ' << r.getHeight() << " pr ";
  62815. }
  62816. out << " clip newpath\n";
  62817. out << w << ' ' << h << " scale\n";
  62818. out << w << ' ' << h << " 8 [" << w << " 0 0 -" << h << ' ' << (int) 0 << ' ' << h << " ]\n";
  62819. writeImage (sourceImage, srcClipX, srcClipY, srcClipW, srcClipH);
  62820. out << "false 3 colorimage grestore\n";
  62821. needToClip = true;
  62822. }
  62823. void LowLevelGraphicsPostScriptRenderer::drawLine (double x1, double y1, double x2, double y2, const Colour& colour)
  62824. {
  62825. Path p;
  62826. p.addLineSegment ((float) x1, (float) y1, (float) x2, (float) y2, 1.0f);
  62827. fillPathWithColour (p, AffineTransform::identity, colour, EdgeTable::Oversampling_256times);
  62828. }
  62829. void LowLevelGraphicsPostScriptRenderer::drawVerticalLine (const int x, double top, double bottom, const Colour& col)
  62830. {
  62831. drawLine (x, top, x, bottom, col);
  62832. }
  62833. void LowLevelGraphicsPostScriptRenderer::drawHorizontalLine (const int y, double left, double right, const Colour& col)
  62834. {
  62835. drawLine (left, y, right, y, col);
  62836. }
  62837. END_JUCE_NAMESPACE
  62838. /********* End of inlined file: juce_LowLevelGraphicsPostScriptRenderer.cpp *********/
  62839. /********* Start of inlined file: juce_LowLevelGraphicsSoftwareRenderer.cpp *********/
  62840. BEGIN_JUCE_NAMESPACE
  62841. #if ! (defined (JUCE_MAC) || (defined (JUCE_WIN32) && defined (JUCE_64BIT)))
  62842. #define JUCE_USE_SSE_INSTRUCTIONS 1
  62843. #endif
  62844. #if defined (JUCE_DEBUG) && JUCE_MSVC
  62845. #pragma warning (disable: 4714)
  62846. #endif
  62847. #define MINIMUM_COORD -0x3fffffff
  62848. #define MAXIMUM_COORD 0x3fffffff
  62849. #undef ASSERT_COORDS_ARE_SENSIBLE_NUMBERS
  62850. #define ASSERT_COORDS_ARE_SENSIBLE_NUMBERS(x, y, w, h) \
  62851. jassert ((int) x >= MINIMUM_COORD \
  62852. && (int) x <= MAXIMUM_COORD \
  62853. && (int) y >= MINIMUM_COORD \
  62854. && (int) y <= MAXIMUM_COORD \
  62855. && (int) w >= 0 \
  62856. && (int) w < MAXIMUM_COORD \
  62857. && (int) h >= 0 \
  62858. && (int) h < MAXIMUM_COORD);
  62859. static void replaceRectRGB (uint8* pixels, const int w, int h, const int stride, const Colour& colour) throw()
  62860. {
  62861. const PixelARGB blendColour (colour.getPixelARGB());
  62862. if (w < 32)
  62863. {
  62864. while (--h >= 0)
  62865. {
  62866. PixelRGB* dest = (PixelRGB*) pixels;
  62867. for (int i = w; --i >= 0;)
  62868. (dest++)->set (blendColour);
  62869. pixels += stride;
  62870. }
  62871. }
  62872. else
  62873. {
  62874. // for wider fills, it's worth using some optimisations..
  62875. const uint8 r = blendColour.getRed();
  62876. const uint8 g = blendColour.getGreen();
  62877. const uint8 b = blendColour.getBlue();
  62878. if (r == g && r == b) // if all the component values are the same, we can cheat..
  62879. {
  62880. while (--h >= 0)
  62881. {
  62882. memset (pixels, r, w * 3);
  62883. pixels += stride;
  62884. }
  62885. }
  62886. else
  62887. {
  62888. PixelRGB filler [4];
  62889. filler[0].set (blendColour);
  62890. filler[1].set (blendColour);
  62891. filler[2].set (blendColour);
  62892. filler[3].set (blendColour);
  62893. const int* const intFiller = (const int*) filler;
  62894. while (--h >= 0)
  62895. {
  62896. uint8* dest = (uint8*) pixels;
  62897. int i = w;
  62898. while ((i > 8) && (((pointer_sized_int) dest & 7) != 0))
  62899. {
  62900. ((PixelRGB*) dest)->set (blendColour);
  62901. dest += 3;
  62902. --i;
  62903. }
  62904. while (i >= 4)
  62905. {
  62906. ((int*) dest) [0] = intFiller[0];
  62907. ((int*) dest) [1] = intFiller[1];
  62908. ((int*) dest) [2] = intFiller[2];
  62909. dest += 12;
  62910. i -= 4;
  62911. }
  62912. while (--i >= 0)
  62913. {
  62914. ((PixelRGB*) dest)->set (blendColour);
  62915. dest += 3;
  62916. }
  62917. pixels += stride;
  62918. }
  62919. }
  62920. }
  62921. }
  62922. static void replaceRectARGB (uint8* pixels, const int w, int h, const int stride, const Colour& colour) throw()
  62923. {
  62924. const PixelARGB blendColour (colour.getPixelARGB());
  62925. while (--h >= 0)
  62926. {
  62927. PixelARGB* const dest = (PixelARGB*) pixels;
  62928. for (int i = 0; i < w; ++i)
  62929. dest[i] = blendColour;
  62930. pixels += stride;
  62931. }
  62932. }
  62933. static void blendRectRGB (uint8* pixels, const int w, int h, const int stride, const Colour& colour) throw()
  62934. {
  62935. if (colour.isOpaque())
  62936. {
  62937. replaceRectRGB (pixels, w, h, stride, colour);
  62938. }
  62939. else
  62940. {
  62941. const PixelARGB blendColour (colour.getPixelARGB());
  62942. const int alpha = blendColour.getAlpha();
  62943. if (alpha <= 0)
  62944. return;
  62945. #if defined (JUCE_USE_SSE_INSTRUCTIONS) && ! JUCE_64BIT
  62946. if (SystemStats::hasSSE())
  62947. {
  62948. int64 rgb0 = (((int64) blendColour.getRed()) << 32)
  62949. | (int64) ((blendColour.getGreen() << 16)
  62950. | blendColour.getBlue());
  62951. const int invAlpha = 0xff - alpha;
  62952. int64 aaaa = (invAlpha << 16) | invAlpha;
  62953. aaaa = (aaaa << 16) | aaaa;
  62954. #ifndef JUCE_GCC
  62955. __asm
  62956. {
  62957. movq mm1, aaaa
  62958. movq mm2, rgb0
  62959. pxor mm7, mm7
  62960. }
  62961. while (--h >= 0)
  62962. {
  62963. __asm
  62964. {
  62965. mov edx, pixels
  62966. mov ebx, w
  62967. pixloop:
  62968. prefetchnta [edx]
  62969. mov ax, [edx + 1]
  62970. shl eax, 8
  62971. mov al, [edx]
  62972. movd mm0, eax
  62973. punpcklbw mm0, mm7
  62974. pmullw mm0, mm1
  62975. psrlw mm0, 8
  62976. paddw mm0, mm2
  62977. packuswb mm0, mm7
  62978. movd eax, mm0
  62979. mov [edx], al
  62980. inc edx
  62981. shr eax, 8
  62982. mov [edx], ax
  62983. add edx, 2
  62984. dec ebx
  62985. jg pixloop
  62986. }
  62987. pixels += stride;
  62988. }
  62989. __asm emms
  62990. #else
  62991. __asm__ __volatile__ (
  62992. "\tpush %%ebx \n"
  62993. "\tmovq %[aaaa], %%mm1 \n"
  62994. "\tmovq %[rgb0], %%mm2 \n"
  62995. "\tpxor %%mm7, %%mm7 \n"
  62996. ".lineLoop2: \n"
  62997. "\tmovl %%esi,%%edx \n"
  62998. "\tmovl %[w], %%ebx \n"
  62999. ".pixLoop2: \n"
  63000. "\tprefetchnta (%%edx) \n"
  63001. "\tmov (%%edx), %%ax \n"
  63002. "\tshl $8, %%eax \n"
  63003. "\tmov 2(%%edx), %%al \n"
  63004. "\tmovd %%eax, %%mm0 \n"
  63005. "\tpunpcklbw %%mm7, %%mm0 \n"
  63006. "\tpmullw %%mm1, %%mm0 \n"
  63007. "\tpsrlw $8, %%mm0 \n"
  63008. "\tpaddw %%mm2, %%mm0 \n"
  63009. "\tpackuswb %%mm7, %%mm0 \n"
  63010. "\tmovd %%mm0, %%eax \n"
  63011. "\tmovb %%al, (%%edx) \n"
  63012. "\tinc %%edx \n"
  63013. "\tshr $8, %%eax \n"
  63014. "\tmovw %%ax, (%%edx) \n"
  63015. "\tadd $2, %%edx \n"
  63016. "\tdec %%ebx \n"
  63017. "\tjg .pixLoop2 \n"
  63018. "\tadd %%edi, %%esi \n"
  63019. "\tdec %%ecx \n"
  63020. "\tjg .lineLoop2 \n"
  63021. "\tpop %%ebx \n"
  63022. "\temms \n"
  63023. : /* No output registers */
  63024. : [aaaa] "m" (aaaa), /* Input registers */
  63025. [rgb0] "m" (rgb0),
  63026. [w] "m" (w),
  63027. "c" (h),
  63028. [stride] "D" (stride),
  63029. [pixels] "S" (pixels)
  63030. : "cc", "eax", "edx", "memory" /* Clobber list */
  63031. );
  63032. #endif
  63033. }
  63034. else
  63035. #endif
  63036. {
  63037. while (--h >= 0)
  63038. {
  63039. PixelRGB* dest = (PixelRGB*) pixels;
  63040. for (int i = w; --i >= 0;)
  63041. (dest++)->blend (blendColour);
  63042. pixels += stride;
  63043. }
  63044. }
  63045. }
  63046. }
  63047. static void blendRectARGB (uint8* pixels, const int w, int h, const int stride, const Colour& colour) throw()
  63048. {
  63049. if (colour.isOpaque())
  63050. {
  63051. replaceRectARGB (pixels, w, h, stride, colour);
  63052. }
  63053. else
  63054. {
  63055. const PixelARGB blendColour (colour.getPixelARGB());
  63056. const int alpha = blendColour.getAlpha();
  63057. if (alpha <= 0)
  63058. return;
  63059. while (--h >= 0)
  63060. {
  63061. PixelARGB* dest = (PixelARGB*) pixels;
  63062. for (int i = w; --i >= 0;)
  63063. (dest++)->blend (blendColour);
  63064. pixels += stride;
  63065. }
  63066. }
  63067. }
  63068. static void blendAlphaMapARGB (uint8* destPixel, const int imageStride,
  63069. const uint8* alphaValues, const int w, int h,
  63070. const int pixelStride, const int lineStride,
  63071. const Colour& colour) throw()
  63072. {
  63073. const PixelARGB srcPix (colour.getPixelARGB());
  63074. while (--h >= 0)
  63075. {
  63076. PixelARGB* dest = (PixelARGB*) destPixel;
  63077. const uint8* src = alphaValues;
  63078. int i = w;
  63079. while (--i >= 0)
  63080. {
  63081. unsigned int srcAlpha = *src;
  63082. src += pixelStride;
  63083. if (srcAlpha > 0)
  63084. dest->blend (srcPix, srcAlpha);
  63085. ++dest;
  63086. }
  63087. alphaValues += lineStride;
  63088. destPixel += imageStride;
  63089. }
  63090. }
  63091. static void blendAlphaMapRGB (uint8* destPixel, const int imageStride,
  63092. const uint8* alphaValues, int const width, int height,
  63093. const int pixelStride, const int lineStride,
  63094. const Colour& colour) throw()
  63095. {
  63096. const PixelARGB srcPix (colour.getPixelARGB());
  63097. while (--height >= 0)
  63098. {
  63099. PixelRGB* dest = (PixelRGB*) destPixel;
  63100. const uint8* src = alphaValues;
  63101. int i = width;
  63102. while (--i >= 0)
  63103. {
  63104. unsigned int srcAlpha = *src;
  63105. src += pixelStride;
  63106. if (srcAlpha > 0)
  63107. dest->blend (srcPix, srcAlpha);
  63108. ++dest;
  63109. }
  63110. alphaValues += lineStride;
  63111. destPixel += imageStride;
  63112. }
  63113. }
  63114. template <class PixelType>
  63115. class SolidColourEdgeTableRenderer
  63116. {
  63117. uint8* const data;
  63118. const int stride;
  63119. PixelType* linePixels;
  63120. PixelARGB sourceColour;
  63121. SolidColourEdgeTableRenderer (const SolidColourEdgeTableRenderer&);
  63122. const SolidColourEdgeTableRenderer& operator= (const SolidColourEdgeTableRenderer&);
  63123. public:
  63124. SolidColourEdgeTableRenderer (uint8* const data_,
  63125. const int stride_,
  63126. const Colour& colour) throw()
  63127. : data (data_),
  63128. stride (stride_),
  63129. sourceColour (colour.getPixelARGB())
  63130. {
  63131. }
  63132. forcedinline void setEdgeTableYPos (const int y) throw()
  63133. {
  63134. linePixels = (PixelType*) (data + stride * y);
  63135. }
  63136. forcedinline void handleEdgeTablePixel (const int x, const int alphaLevel) const throw()
  63137. {
  63138. linePixels[x].blend (sourceColour, alphaLevel);
  63139. }
  63140. forcedinline void handleEdgeTableLine (const int x, int width, const int alphaLevel) const throw()
  63141. {
  63142. PixelARGB p (sourceColour);
  63143. p.multiplyAlpha (alphaLevel);
  63144. PixelType* dest = linePixels + x;
  63145. if (p.getAlpha() < 0xff)
  63146. {
  63147. do
  63148. {
  63149. dest->blend (p);
  63150. ++dest;
  63151. } while (--width > 0);
  63152. }
  63153. else
  63154. {
  63155. do
  63156. {
  63157. dest->set (p);
  63158. ++dest;
  63159. } while (--width > 0);
  63160. }
  63161. }
  63162. };
  63163. class AlphaBitmapRenderer
  63164. {
  63165. uint8* data;
  63166. int stride;
  63167. uint8* lineStart;
  63168. AlphaBitmapRenderer (const AlphaBitmapRenderer&);
  63169. const AlphaBitmapRenderer& operator= (const AlphaBitmapRenderer&);
  63170. public:
  63171. AlphaBitmapRenderer (uint8* const data_,
  63172. const int stride_) throw()
  63173. : data (data_),
  63174. stride (stride_)
  63175. {
  63176. }
  63177. forcedinline void setEdgeTableYPos (const int y) throw()
  63178. {
  63179. lineStart = data + (stride * y);
  63180. }
  63181. forcedinline void handleEdgeTablePixel (const int x, const int alphaLevel) const throw()
  63182. {
  63183. lineStart [x] = (uint8) alphaLevel;
  63184. }
  63185. forcedinline void handleEdgeTableLine (const int x, int width, const int alphaLevel) const throw()
  63186. {
  63187. uint8* d = lineStart + x;
  63188. while (--width >= 0)
  63189. *d++ = (uint8) alphaLevel;
  63190. }
  63191. };
  63192. static const int numScaleBits = 12;
  63193. class LinearGradientPixelGenerator
  63194. {
  63195. const PixelARGB* const lookupTable;
  63196. const int numEntries;
  63197. PixelARGB linePix;
  63198. int start, scale;
  63199. double grad, yTerm;
  63200. bool vertical, horizontal;
  63201. LinearGradientPixelGenerator (const LinearGradientPixelGenerator&);
  63202. const LinearGradientPixelGenerator& operator= (const LinearGradientPixelGenerator&);
  63203. public:
  63204. LinearGradientPixelGenerator (const ColourGradient& gradient,
  63205. const PixelARGB* const lookupTable_, const int numEntries_)
  63206. : lookupTable (lookupTable_),
  63207. numEntries (numEntries_)
  63208. {
  63209. jassert (numEntries_ >= 0);
  63210. float x1 = gradient.x1;
  63211. float y1 = gradient.y1;
  63212. float x2 = gradient.x2;
  63213. float y2 = gradient.y2;
  63214. if (! gradient.transform.isIdentity())
  63215. {
  63216. Line l (x2, y2, x1, y1);
  63217. const Point p3 = l.getPointAlongLine (0.0, 100.0f);
  63218. float x3 = p3.getX();
  63219. float y3 = p3.getY();
  63220. gradient.transform.transformPoint (x1, y1);
  63221. gradient.transform.transformPoint (x2, y2);
  63222. gradient.transform.transformPoint (x3, y3);
  63223. Line l2 (x2, y2, x3, y3);
  63224. float prop = l2.findNearestPointTo (x1, y1);
  63225. const Point newP2 (l2.getPointAlongLineProportionally (prop));
  63226. x2 = newP2.getX();
  63227. y2 = newP2.getY();
  63228. }
  63229. vertical = fabs (x1 - x2) < 0.001f;
  63230. horizontal = fabs (y1 - y2) < 0.001f;
  63231. if (vertical)
  63232. {
  63233. scale = roundDoubleToInt ((numEntries << numScaleBits) / (double) (y2 - y1));
  63234. start = roundDoubleToInt (y1 * scale);
  63235. }
  63236. else if (horizontal)
  63237. {
  63238. scale = roundDoubleToInt ((numEntries << numScaleBits) / (double) (x2 - x1));
  63239. start = roundDoubleToInt (x1 * scale);
  63240. }
  63241. else
  63242. {
  63243. grad = (y2 - y1) / (double) (x1 - x2);
  63244. yTerm = y1 - x1 / grad;
  63245. scale = roundDoubleToInt ((numEntries << numScaleBits) / (yTerm * grad - (y2 * grad - x2)));
  63246. grad *= scale;
  63247. }
  63248. }
  63249. forcedinline void setY (const int y) throw()
  63250. {
  63251. if (vertical)
  63252. linePix = lookupTable [jlimit (0, numEntries, (y * scale - start) >> numScaleBits)];
  63253. else if (! horizontal)
  63254. start = roundDoubleToInt ((y - yTerm) * grad);
  63255. }
  63256. forcedinline const PixelARGB getPixel (const int x) const throw()
  63257. {
  63258. if (vertical)
  63259. return linePix;
  63260. return lookupTable [jlimit (0, numEntries, (x * scale - start) >> numScaleBits)];
  63261. }
  63262. };
  63263. class RadialGradientPixelGenerator
  63264. {
  63265. protected:
  63266. const PixelARGB* const lookupTable;
  63267. const int numEntries;
  63268. const double gx1, gy1;
  63269. double maxDist, invScale;
  63270. double dy;
  63271. RadialGradientPixelGenerator (const RadialGradientPixelGenerator&);
  63272. const RadialGradientPixelGenerator& operator= (const RadialGradientPixelGenerator&);
  63273. public:
  63274. RadialGradientPixelGenerator (const ColourGradient& gradient,
  63275. const PixelARGB* const lookupTable_, const int numEntries_) throw()
  63276. : lookupTable (lookupTable_),
  63277. numEntries (numEntries_),
  63278. gx1 (gradient.x1),
  63279. gy1 (gradient.y1)
  63280. {
  63281. jassert (numEntries_ >= 0);
  63282. const float dx = gradient.x1 - gradient.x2;
  63283. const float dy = gradient.y1 - gradient.y2;
  63284. maxDist = dx * dx + dy * dy;
  63285. invScale = (numEntries + 1) / sqrt (maxDist);
  63286. }
  63287. forcedinline void setY (const int y) throw()
  63288. {
  63289. dy = y - gy1;
  63290. dy *= dy;
  63291. }
  63292. forcedinline const PixelARGB getPixel (const int px) const throw()
  63293. {
  63294. double x = px - gx1;
  63295. x *= x;
  63296. x += dy;
  63297. if (x >= maxDist)
  63298. return lookupTable [numEntries];
  63299. else
  63300. return lookupTable [jmin (numEntries, roundDoubleToInt (sqrt (x) * invScale))];
  63301. }
  63302. };
  63303. class TransformedRadialGradientPixelGenerator : public RadialGradientPixelGenerator
  63304. {
  63305. double tM10, tM00, lineYM01, lineYM11;
  63306. AffineTransform inverseTransform;
  63307. TransformedRadialGradientPixelGenerator (const TransformedRadialGradientPixelGenerator&);
  63308. const TransformedRadialGradientPixelGenerator& operator= (const TransformedRadialGradientPixelGenerator&);
  63309. public:
  63310. TransformedRadialGradientPixelGenerator (const ColourGradient& gradient,
  63311. const PixelARGB* const lookupTable_, const int numEntries_) throw()
  63312. : RadialGradientPixelGenerator (gradient, lookupTable_, numEntries_),
  63313. inverseTransform (gradient.transform.inverted())
  63314. {
  63315. tM10 = inverseTransform.mat10;
  63316. tM00 = inverseTransform.mat00;
  63317. }
  63318. forcedinline void setY (const int y) throw()
  63319. {
  63320. lineYM01 = inverseTransform.mat01 * y + inverseTransform.mat02 - gx1;
  63321. lineYM11 = inverseTransform.mat11 * y + inverseTransform.mat12 - gy1;
  63322. }
  63323. forcedinline const PixelARGB getPixel (const int px) const throw()
  63324. {
  63325. double x = px;
  63326. const double y = tM10 * x + lineYM11;
  63327. x = tM00 * x + lineYM01;
  63328. x *= x;
  63329. x += y * y;
  63330. if (x >= maxDist)
  63331. return lookupTable [numEntries];
  63332. else
  63333. return lookupTable [jmin (numEntries, roundDoubleToInt (sqrt (x) * invScale))];
  63334. }
  63335. };
  63336. template <class PixelType, class GradientType>
  63337. class GradientEdgeTableRenderer : public GradientType
  63338. {
  63339. uint8* const data;
  63340. const int stride;
  63341. PixelType* linePixels;
  63342. GradientEdgeTableRenderer (const GradientEdgeTableRenderer&);
  63343. const GradientEdgeTableRenderer& operator= (const GradientEdgeTableRenderer&);
  63344. public:
  63345. GradientEdgeTableRenderer (uint8* const data_,
  63346. const int stride_,
  63347. const ColourGradient& gradient,
  63348. const PixelARGB* const lookupTable, const int numEntries) throw()
  63349. : GradientType (gradient, lookupTable, numEntries - 1),
  63350. data (data_),
  63351. stride (stride_)
  63352. {
  63353. }
  63354. forcedinline void setEdgeTableYPos (const int y) throw()
  63355. {
  63356. linePixels = (PixelType*) (data + stride * y);
  63357. GradientType::setY (y);
  63358. }
  63359. forcedinline void handleEdgeTablePixel (const int x, const int alphaLevel) const throw()
  63360. {
  63361. linePixels[x].blend (GradientType::getPixel (x), alphaLevel);
  63362. }
  63363. forcedinline void handleEdgeTableLine (int x, int width, const int alphaLevel) const throw()
  63364. {
  63365. PixelType* dest = linePixels + x;
  63366. if (alphaLevel < 0xff)
  63367. {
  63368. do
  63369. {
  63370. (dest++)->blend (GradientType::getPixel (x++), alphaLevel);
  63371. } while (--width > 0);
  63372. }
  63373. else
  63374. {
  63375. do
  63376. {
  63377. (dest++)->blend (GradientType::getPixel (x++));
  63378. } while (--width > 0);
  63379. }
  63380. }
  63381. };
  63382. template <class DestPixelType, class SrcPixelType>
  63383. class ImageFillEdgeTableRenderer
  63384. {
  63385. uint8* const destImageData;
  63386. const uint8* srcImageData;
  63387. int stride, srcStride, extraAlpha;
  63388. DestPixelType* linePixels;
  63389. SrcPixelType* sourceLineStart;
  63390. ImageFillEdgeTableRenderer (const ImageFillEdgeTableRenderer&);
  63391. const ImageFillEdgeTableRenderer& operator= (const ImageFillEdgeTableRenderer&);
  63392. public:
  63393. ImageFillEdgeTableRenderer (uint8* const destImageData_,
  63394. const int stride_,
  63395. const uint8* srcImageData_,
  63396. const int srcStride_,
  63397. int extraAlpha_,
  63398. SrcPixelType*) throw() // dummy param to avoid compiler error
  63399. : destImageData (destImageData_),
  63400. srcImageData (srcImageData_),
  63401. stride (stride_),
  63402. srcStride (srcStride_),
  63403. extraAlpha (extraAlpha_)
  63404. {
  63405. }
  63406. forcedinline void setEdgeTableYPos (int y) throw()
  63407. {
  63408. linePixels = (DestPixelType*) (destImageData + stride * y);
  63409. sourceLineStart = (SrcPixelType*) (srcImageData + srcStride * y);
  63410. }
  63411. forcedinline void handleEdgeTablePixel (const int x, int alphaLevel) const throw()
  63412. {
  63413. alphaLevel = (alphaLevel * extraAlpha) >> 8;
  63414. linePixels[x].blend (sourceLineStart [x], alphaLevel);
  63415. }
  63416. forcedinline void handleEdgeTableLine (int x, int width, int alphaLevel) const throw()
  63417. {
  63418. DestPixelType* dest = linePixels + x;
  63419. alphaLevel = (alphaLevel * extraAlpha) >> 8;
  63420. if (alphaLevel < 0xfe)
  63421. {
  63422. do
  63423. {
  63424. dest++ ->blend (sourceLineStart [x++], alphaLevel);
  63425. } while (--width > 0);
  63426. }
  63427. else
  63428. {
  63429. do
  63430. {
  63431. dest++ ->blend (sourceLineStart [x++]);
  63432. } while (--width > 0);
  63433. }
  63434. }
  63435. };
  63436. static void blendRowOfPixels (PixelARGB* dst,
  63437. const PixelRGB* src,
  63438. int width) throw()
  63439. {
  63440. while (--width >= 0)
  63441. (dst++)->set (*src++);
  63442. }
  63443. static void blendRowOfPixels (PixelRGB* dst,
  63444. const PixelRGB* src,
  63445. int width) throw()
  63446. {
  63447. memcpy (dst, src, 3 * width);
  63448. }
  63449. static void blendRowOfPixels (PixelRGB* dst,
  63450. const PixelARGB* src,
  63451. int width) throw()
  63452. {
  63453. while (--width >= 0)
  63454. (dst++)->blend (*src++);
  63455. }
  63456. static void blendRowOfPixels (PixelARGB* dst,
  63457. const PixelARGB* src,
  63458. int width) throw()
  63459. {
  63460. while (--width >= 0)
  63461. (dst++)->blend (*src++);
  63462. }
  63463. static void blendRowOfPixels (PixelARGB* dst,
  63464. const PixelRGB* src,
  63465. int width,
  63466. const uint8 alpha) throw()
  63467. {
  63468. while (--width >= 0)
  63469. (dst++)->blend (*src++, alpha);
  63470. }
  63471. static void blendRowOfPixels (PixelRGB* dst,
  63472. const PixelRGB* src,
  63473. int width,
  63474. const uint8 alpha) throw()
  63475. {
  63476. uint8* d = (uint8*) dst;
  63477. const uint8* s = (const uint8*) src;
  63478. const int inverseAlpha = 0xff - alpha;
  63479. while (--width >= 0)
  63480. {
  63481. d[0] = (uint8) (s[0] + (((d[0] - s[0]) * inverseAlpha) >> 8));
  63482. d[1] = (uint8) (s[1] + (((d[1] - s[1]) * inverseAlpha) >> 8));
  63483. d[2] = (uint8) (s[2] + (((d[2] - s[2]) * inverseAlpha) >> 8));
  63484. d += 3;
  63485. s += 3;
  63486. }
  63487. }
  63488. static void blendRowOfPixels (PixelRGB* dst,
  63489. const PixelARGB* src,
  63490. int width,
  63491. const uint8 alpha) throw()
  63492. {
  63493. while (--width >= 0)
  63494. (dst++)->blend (*src++, alpha);
  63495. }
  63496. static void blendRowOfPixels (PixelARGB* dst,
  63497. const PixelARGB* src,
  63498. int width,
  63499. const uint8 alpha) throw()
  63500. {
  63501. while (--width >= 0)
  63502. (dst++)->blend (*src++, alpha);
  63503. }
  63504. template <class DestPixelType, class SrcPixelType>
  63505. static void overlayImage (DestPixelType* dest,
  63506. const int destStride,
  63507. const SrcPixelType* src,
  63508. const int srcStride,
  63509. const int width,
  63510. int height,
  63511. const uint8 alpha) throw()
  63512. {
  63513. if (alpha < 0xff)
  63514. {
  63515. while (--height >= 0)
  63516. {
  63517. blendRowOfPixels (dest, src, width, alpha);
  63518. dest = (DestPixelType*) (((uint8*) dest) + destStride);
  63519. src = (const SrcPixelType*) (((const uint8*) src) + srcStride);
  63520. }
  63521. }
  63522. else
  63523. {
  63524. while (--height >= 0)
  63525. {
  63526. blendRowOfPixels (dest, src, width);
  63527. dest = (DestPixelType*) (((uint8*) dest) + destStride);
  63528. src = (const SrcPixelType*) (((const uint8*) src) + srcStride);
  63529. }
  63530. }
  63531. }
  63532. template <class DestPixelType, class SrcPixelType>
  63533. static void transformedImageRender (Image& destImage,
  63534. const Image& sourceImage,
  63535. const int destClipX, const int destClipY,
  63536. const int destClipW, const int destClipH,
  63537. const int srcClipX, const int srcClipY,
  63538. const int srcClipWidth, const int srcClipHeight,
  63539. double srcX, double srcY,
  63540. const double lineDX, const double lineDY,
  63541. const double pixelDX, const double pixelDY,
  63542. const uint8 alpha,
  63543. const Graphics::ResamplingQuality quality,
  63544. DestPixelType*,
  63545. SrcPixelType*) throw() // forced by a compiler bug to include dummy
  63546. // parameters of the templated classes to
  63547. // make it use the correct instance of this function..
  63548. {
  63549. int destStride, destPixelStride;
  63550. uint8* const destPixels = destImage.lockPixelDataReadWrite (destClipX, destClipY, destClipW, destClipH, destStride, destPixelStride);
  63551. int srcStride, srcPixelStride;
  63552. const uint8* const srcPixels = sourceImage.lockPixelDataReadOnly (srcClipX, srcClipY, srcClipWidth, srcClipHeight, srcStride, srcPixelStride);
  63553. if (quality == Graphics::lowResamplingQuality) // nearest-neighbour..
  63554. {
  63555. if (alpha == 255)
  63556. {
  63557. for (int y = 0; y < destClipH; ++y)
  63558. {
  63559. double sx = srcX;
  63560. double sy = srcY;
  63561. DestPixelType* dest = (DestPixelType*) (destPixels + destStride * y);
  63562. for (int x = destClipW; --x >= 0;)
  63563. {
  63564. const int ix = ((int) sx) - srcClipX;
  63565. if (((unsigned int) ix) < (unsigned int) srcClipWidth)
  63566. {
  63567. const int iy = ((int) sy) - srcClipY;
  63568. if (((unsigned int) iy) < (unsigned int) srcClipHeight)
  63569. {
  63570. const SrcPixelType* const src = (const SrcPixelType*) (srcPixels + srcStride * iy + srcPixelStride * ix);
  63571. dest->set (*src);
  63572. }
  63573. }
  63574. ++dest;
  63575. sx += pixelDX;
  63576. sy += pixelDY;
  63577. }
  63578. srcX += lineDX;
  63579. srcY += lineDY;
  63580. }
  63581. }
  63582. else
  63583. {
  63584. for (int y = 0; y < destClipH; ++y)
  63585. {
  63586. double sx = srcX;
  63587. double sy = srcY;
  63588. DestPixelType* dest = (DestPixelType*) (destPixels + destStride * y);
  63589. for (int x = destClipW; --x >= 0;)
  63590. {
  63591. const int ix = ((int) sx) - srcClipX;
  63592. if (((unsigned int) ix) < (unsigned int) srcClipWidth)
  63593. {
  63594. const int iy = ((int) sy) - srcClipY;
  63595. if (((unsigned int) iy) < (unsigned int) srcClipHeight)
  63596. {
  63597. const SrcPixelType* const src = (const SrcPixelType*) (srcPixels + srcStride * iy + srcPixelStride * ix);
  63598. dest->blend (*src, alpha);
  63599. }
  63600. }
  63601. ++dest;
  63602. sx += pixelDX;
  63603. sy += pixelDY;
  63604. }
  63605. srcX += lineDX;
  63606. srcY += lineDY;
  63607. }
  63608. }
  63609. }
  63610. else
  63611. {
  63612. jassert (quality == Graphics::mediumResamplingQuality); // (only bilinear is implemented, so that's what you'll get here..)
  63613. for (int y = 0; y < destClipH; ++y)
  63614. {
  63615. double sx = srcX - (srcClipWidth == destClipW ? 0.0 : 0.5);
  63616. double sy = srcY - (srcClipHeight == destClipH ? 0.0 : 0.5);
  63617. DestPixelType* dest = (DestPixelType*) (destPixels + destStride * y);
  63618. for (int x = 0; x < destClipW; ++x)
  63619. {
  63620. const double fx = floor (sx);
  63621. const double fy = floor (sy);
  63622. const int ix = roundDoubleToInt (fx) - srcClipX;
  63623. const int iy = roundDoubleToInt (fy) - srcClipY;
  63624. if (ix < srcClipWidth && iy < srcClipHeight)
  63625. {
  63626. PixelARGB p1 (0), p2 (0), p3 (0), p4 (0);
  63627. const SrcPixelType* src = (const SrcPixelType*) (srcPixels + srcStride * iy + srcPixelStride * ix);
  63628. if (iy >= 0)
  63629. {
  63630. if (ix >= 0)
  63631. p1.set (src[0]);
  63632. if (((unsigned int) (ix + 1)) < (unsigned int) srcClipWidth)
  63633. p2.set (src[1]);
  63634. }
  63635. if (((unsigned int) (iy + 1)) < (unsigned int) srcClipHeight)
  63636. {
  63637. src = (const SrcPixelType*) (((const uint8*) src) + srcStride);
  63638. if (ix >= 0)
  63639. p3.set (src[0]);
  63640. if (((unsigned int) (ix + 1)) < (unsigned int) srcClipWidth)
  63641. p4.set (src[1]);
  63642. }
  63643. const int dx = roundDoubleToInt ((sx - fx) * 255.0);
  63644. p1.tween (p2, dx);
  63645. p3.tween (p4, dx);
  63646. p1.tween (p3, roundDoubleToInt ((sy - fy) * 255.0));
  63647. if (p1.getAlpha() > 0)
  63648. dest->blend (p1, alpha);
  63649. }
  63650. ++dest;
  63651. sx += pixelDX;
  63652. sy += pixelDY;
  63653. }
  63654. srcX += lineDX;
  63655. srcY += lineDY;
  63656. }
  63657. }
  63658. destImage.releasePixelDataReadWrite (destPixels);
  63659. sourceImage.releasePixelDataReadOnly (srcPixels);
  63660. }
  63661. template <class SrcPixelType, class DestPixelType>
  63662. static void renderAlphaMap (DestPixelType* destPixels,
  63663. int destStride,
  63664. SrcPixelType* srcPixels,
  63665. int srcStride,
  63666. const uint8* alphaValues,
  63667. const int lineStride, const int pixelStride,
  63668. int width, int height,
  63669. const int extraAlpha) throw()
  63670. {
  63671. while (--height >= 0)
  63672. {
  63673. SrcPixelType* srcPix = srcPixels;
  63674. srcPixels = (SrcPixelType*) (((const uint8*) srcPixels) + srcStride);
  63675. DestPixelType* destPix = destPixels;
  63676. destPixels = (DestPixelType*) (((uint8*) destPixels) + destStride);
  63677. const uint8* alpha = alphaValues;
  63678. alphaValues += lineStride;
  63679. if (extraAlpha < 0x100)
  63680. {
  63681. for (int i = width; --i >= 0;)
  63682. {
  63683. destPix++ ->blend (*srcPix++, (extraAlpha * *alpha) >> 8);
  63684. alpha += pixelStride;
  63685. }
  63686. }
  63687. else
  63688. {
  63689. for (int i = width; --i >= 0;)
  63690. {
  63691. destPix++ ->blend (*srcPix++, *alpha);
  63692. alpha += pixelStride;
  63693. }
  63694. }
  63695. }
  63696. }
  63697. LowLevelGraphicsSoftwareRenderer::LowLevelGraphicsSoftwareRenderer (Image& image_)
  63698. : image (image_),
  63699. xOffset (0),
  63700. yOffset (0),
  63701. stateStack (20)
  63702. {
  63703. clip = new RectangleList (Rectangle (0, 0, image_.getWidth(), image_.getHeight()));
  63704. }
  63705. LowLevelGraphicsSoftwareRenderer::~LowLevelGraphicsSoftwareRenderer()
  63706. {
  63707. delete clip;
  63708. }
  63709. bool LowLevelGraphicsSoftwareRenderer::isVectorDevice() const
  63710. {
  63711. return false;
  63712. }
  63713. void LowLevelGraphicsSoftwareRenderer::setOrigin (int x, int y)
  63714. {
  63715. xOffset += x;
  63716. yOffset += y;
  63717. }
  63718. bool LowLevelGraphicsSoftwareRenderer::reduceClipRegion (int x, int y, int w, int h)
  63719. {
  63720. return clip->clipTo (Rectangle (x + xOffset, y + yOffset, w, h));
  63721. }
  63722. bool LowLevelGraphicsSoftwareRenderer::reduceClipRegion (const RectangleList& clipRegion)
  63723. {
  63724. RectangleList temp (clipRegion);
  63725. temp.offsetAll (xOffset, yOffset);
  63726. return clip->clipTo (temp);
  63727. }
  63728. void LowLevelGraphicsSoftwareRenderer::excludeClipRegion (int x, int y, int w, int h)
  63729. {
  63730. clip->subtract (Rectangle (x + xOffset, y + yOffset, w, h));
  63731. }
  63732. bool LowLevelGraphicsSoftwareRenderer::clipRegionIntersects (int x, int y, int w, int h)
  63733. {
  63734. return clip->intersectsRectangle (Rectangle (x + xOffset, y + yOffset, w, h));
  63735. }
  63736. const Rectangle LowLevelGraphicsSoftwareRenderer::getClipBounds() const
  63737. {
  63738. return clip->getBounds().translated (-xOffset, -yOffset);
  63739. }
  63740. bool LowLevelGraphicsSoftwareRenderer::isClipEmpty() const
  63741. {
  63742. return clip->isEmpty();
  63743. }
  63744. LowLevelGraphicsSoftwareRenderer::SavedState::SavedState (RectangleList* const clip_,
  63745. const int xOffset_, const int yOffset_)
  63746. : clip (clip_),
  63747. xOffset (xOffset_),
  63748. yOffset (yOffset_)
  63749. {
  63750. }
  63751. LowLevelGraphicsSoftwareRenderer::SavedState::~SavedState()
  63752. {
  63753. delete clip;
  63754. }
  63755. void LowLevelGraphicsSoftwareRenderer::saveState()
  63756. {
  63757. stateStack.add (new SavedState (new RectangleList (*clip), xOffset, yOffset));
  63758. }
  63759. void LowLevelGraphicsSoftwareRenderer::restoreState()
  63760. {
  63761. SavedState* const top = stateStack.getLast();
  63762. if (top != 0)
  63763. {
  63764. clip->swapWith (*top->clip);
  63765. xOffset = top->xOffset;
  63766. yOffset = top->yOffset;
  63767. stateStack.removeLast();
  63768. }
  63769. else
  63770. {
  63771. jassertfalse // trying to pop with an empty stack!
  63772. }
  63773. }
  63774. void LowLevelGraphicsSoftwareRenderer::fillRectWithColour (int x, int y, int w, int h, const Colour& colour, const bool replaceExistingContents)
  63775. {
  63776. x += xOffset;
  63777. y += yOffset;
  63778. for (RectangleList::Iterator i (*clip); i.next();)
  63779. {
  63780. clippedFillRectWithColour (*i.getRectangle(), x, y, w, h, colour, replaceExistingContents);
  63781. }
  63782. }
  63783. void LowLevelGraphicsSoftwareRenderer::clippedFillRectWithColour (const Rectangle& clipRect,
  63784. int x, int y, int w, int h, const Colour& colour, const bool replaceExistingContents)
  63785. {
  63786. if (clipRect.intersectRectangle (x, y, w, h))
  63787. {
  63788. int stride, pixelStride;
  63789. uint8* const pixels = (uint8*) image.lockPixelDataReadWrite (x, y, w, h, stride, pixelStride);
  63790. if (image.getFormat() == Image::RGB)
  63791. {
  63792. if (replaceExistingContents)
  63793. replaceRectRGB (pixels, w, h, stride, colour);
  63794. else
  63795. blendRectRGB (pixels, w, h, stride, colour);
  63796. }
  63797. else if (image.getFormat() == Image::ARGB)
  63798. {
  63799. if (replaceExistingContents)
  63800. replaceRectARGB (pixels, w, h, stride, colour);
  63801. else
  63802. blendRectARGB (pixels, w, h, stride, colour);
  63803. }
  63804. else
  63805. {
  63806. jassertfalse // not done!
  63807. }
  63808. image.releasePixelDataReadWrite (pixels);
  63809. }
  63810. }
  63811. void LowLevelGraphicsSoftwareRenderer::fillRectWithGradient (int x, int y, int w, int h, const ColourGradient& gradient)
  63812. {
  63813. Path p;
  63814. p.addRectangle ((float) x, (float) y, (float) w, (float) h);
  63815. fillPathWithGradient (p, AffineTransform::identity, gradient, EdgeTable::Oversampling_none);
  63816. }
  63817. bool LowLevelGraphicsSoftwareRenderer::getPathBounds (int clipX, int clipY, int clipW, int clipH,
  63818. const Path& path, const AffineTransform& transform,
  63819. int& x, int& y, int& w, int& h) const
  63820. {
  63821. float tx, ty, tw, th;
  63822. path.getBoundsTransformed (transform, tx, ty, tw, th);
  63823. x = roundDoubleToInt (tx) - 1;
  63824. y = roundDoubleToInt (ty) - 1;
  63825. w = roundDoubleToInt (tw) + 2;
  63826. h = roundDoubleToInt (th) + 2;
  63827. // seems like this operation is using some crazy out-of-range numbers..
  63828. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (x, y, w, h);
  63829. return Rectangle::intersectRectangles (x, y, w, h, clipX, clipY, clipW, clipH);
  63830. }
  63831. void LowLevelGraphicsSoftwareRenderer::fillPathWithColour (const Path& path, const AffineTransform& t,
  63832. const Colour& colour, EdgeTable::OversamplingLevel quality)
  63833. {
  63834. for (RectangleList::Iterator i (*clip); i.next();)
  63835. {
  63836. const Rectangle& r = *i.getRectangle();
  63837. clippedFillPathWithColour (r.getX(), r.getY(), r.getWidth(), r.getHeight(), path, t, colour, quality);
  63838. }
  63839. }
  63840. void LowLevelGraphicsSoftwareRenderer::clippedFillPathWithColour (int clipX, int clipY, int clipW, int clipH, const Path& path, const AffineTransform& t,
  63841. const Colour& colour, EdgeTable::OversamplingLevel quality)
  63842. {
  63843. const AffineTransform transform (t.translated ((float) xOffset, (float) yOffset));
  63844. int cx, cy, cw, ch;
  63845. if (getPathBounds (clipX, clipY, clipW, clipH, path, transform, cx, cy, cw, ch))
  63846. {
  63847. EdgeTable edgeTable (0, ch, quality);
  63848. edgeTable.addPath (path, transform.translated ((float) -cx, (float) -cy));
  63849. int stride, pixelStride;
  63850. uint8* const pixels = (uint8*) image.lockPixelDataReadWrite (cx, cy, cw, ch, stride, pixelStride);
  63851. if (image.getFormat() == Image::RGB)
  63852. {
  63853. jassert (pixelStride == 3);
  63854. SolidColourEdgeTableRenderer <PixelRGB> renderer (pixels, stride, colour);
  63855. edgeTable.iterate (renderer, 0, 0, cw, ch, 0);
  63856. }
  63857. else if (image.getFormat() == Image::ARGB)
  63858. {
  63859. jassert (pixelStride == 4);
  63860. SolidColourEdgeTableRenderer <PixelARGB> renderer (pixels, stride, colour);
  63861. edgeTable.iterate (renderer, 0, 0, cw, ch, 0);
  63862. }
  63863. else if (image.getFormat() == Image::SingleChannel)
  63864. {
  63865. jassert (pixelStride == 1);
  63866. AlphaBitmapRenderer renderer (pixels, stride);
  63867. edgeTable.iterate (renderer, 0, 0, cw, ch, 0);
  63868. }
  63869. image.releasePixelDataReadWrite (pixels);
  63870. }
  63871. }
  63872. void LowLevelGraphicsSoftwareRenderer::fillPathWithGradient (const Path& path, const AffineTransform& t, const ColourGradient& gradient, EdgeTable::OversamplingLevel quality)
  63873. {
  63874. for (RectangleList::Iterator i (*clip); i.next();)
  63875. {
  63876. const Rectangle& r = *i.getRectangle();
  63877. clippedFillPathWithGradient (r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  63878. path, t, gradient, quality);
  63879. }
  63880. }
  63881. void LowLevelGraphicsSoftwareRenderer::clippedFillPathWithGradient (int clipX, int clipY, int clipW, int clipH, const Path& path, const AffineTransform& t,
  63882. const ColourGradient& gradient, EdgeTable::OversamplingLevel quality)
  63883. {
  63884. const AffineTransform transform (t.translated ((float) xOffset, (float) yOffset));
  63885. int cx, cy, cw, ch;
  63886. if (getPathBounds (clipX, clipY, clipW, clipH, path, transform, cx, cy, cw, ch))
  63887. {
  63888. int stride, pixelStride;
  63889. uint8* const pixels = (uint8*) image.lockPixelDataReadWrite (cx, cy, cw, ch, stride, pixelStride);
  63890. ColourGradient g2 (gradient);
  63891. const bool isIdentity = g2.transform.isIdentity();
  63892. if (isIdentity)
  63893. {
  63894. g2.x1 += xOffset - cx;
  63895. g2.x2 += xOffset - cx;
  63896. g2.y1 += yOffset - cy;
  63897. g2.y2 += yOffset - cy;
  63898. }
  63899. else
  63900. {
  63901. g2.transform = g2.transform.translated ((float) (xOffset - cx),
  63902. (float) (yOffset - cy));
  63903. }
  63904. int numLookupEntries;
  63905. PixelARGB* const lookupTable = g2.createLookupTable (numLookupEntries);
  63906. jassert (numLookupEntries > 0);
  63907. EdgeTable edgeTable (0, ch, quality);
  63908. edgeTable.addPath (path, transform.translated ((float) -cx, (float) -cy));
  63909. if (image.getFormat() == Image::RGB)
  63910. {
  63911. jassert (pixelStride == 3);
  63912. if (g2.isRadial)
  63913. {
  63914. if (isIdentity)
  63915. {
  63916. GradientEdgeTableRenderer <PixelRGB, RadialGradientPixelGenerator> renderer (pixels, stride, g2, lookupTable, numLookupEntries);
  63917. edgeTable.iterate (renderer, 0, 0, cw, ch, 0);
  63918. }
  63919. else
  63920. {
  63921. GradientEdgeTableRenderer <PixelRGB, TransformedRadialGradientPixelGenerator> renderer (pixels, stride, g2, lookupTable, numLookupEntries);
  63922. edgeTable.iterate (renderer, 0, 0, cw, ch, 0);
  63923. }
  63924. }
  63925. else
  63926. {
  63927. GradientEdgeTableRenderer <PixelRGB, LinearGradientPixelGenerator> renderer (pixels, stride, g2, lookupTable, numLookupEntries);
  63928. edgeTable.iterate (renderer, 0, 0, cw, ch, 0);
  63929. }
  63930. }
  63931. else if (image.getFormat() == Image::ARGB)
  63932. {
  63933. jassert (pixelStride == 4);
  63934. if (g2.isRadial)
  63935. {
  63936. if (isIdentity)
  63937. {
  63938. GradientEdgeTableRenderer <PixelARGB, RadialGradientPixelGenerator> renderer (pixels, stride, g2, lookupTable, numLookupEntries);
  63939. edgeTable.iterate (renderer, 0, 0, cw, ch, 0);
  63940. }
  63941. else
  63942. {
  63943. GradientEdgeTableRenderer <PixelARGB, TransformedRadialGradientPixelGenerator> renderer (pixels, stride, g2, lookupTable, numLookupEntries);
  63944. edgeTable.iterate (renderer, 0, 0, cw, ch, 0);
  63945. }
  63946. }
  63947. else
  63948. {
  63949. GradientEdgeTableRenderer <PixelARGB, LinearGradientPixelGenerator> renderer (pixels, stride, g2, lookupTable, numLookupEntries);
  63950. edgeTable.iterate (renderer, 0, 0, cw, ch, 0);
  63951. }
  63952. }
  63953. else if (image.getFormat() == Image::SingleChannel)
  63954. {
  63955. jassertfalse // not done!
  63956. }
  63957. juce_free (lookupTable);
  63958. image.releasePixelDataReadWrite (pixels);
  63959. }
  63960. }
  63961. void LowLevelGraphicsSoftwareRenderer::fillPathWithImage (const Path& path, const AffineTransform& transform,
  63962. const Image& sourceImage, int imageX, int imageY, float opacity, EdgeTable::OversamplingLevel quality)
  63963. {
  63964. imageX += xOffset;
  63965. imageY += yOffset;
  63966. for (RectangleList::Iterator i (*clip); i.next();)
  63967. {
  63968. const Rectangle& r = *i.getRectangle();
  63969. clippedFillPathWithImage (r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  63970. path, transform, sourceImage, imageX, imageY, opacity, quality);
  63971. }
  63972. }
  63973. void LowLevelGraphicsSoftwareRenderer::clippedFillPathWithImage (int x, int y, int w, int h, const Path& path, const AffineTransform& transform,
  63974. const Image& sourceImage, int imageX, int imageY, float opacity, EdgeTable::OversamplingLevel quality)
  63975. {
  63976. if (Rectangle::intersectRectangles (x, y, w, h, imageX, imageY, sourceImage.getWidth(), sourceImage.getHeight()))
  63977. {
  63978. EdgeTable edgeTable (0, h, quality);
  63979. edgeTable.addPath (path, transform.translated ((float) (xOffset - x), (float) (yOffset - y)));
  63980. int stride, pixelStride;
  63981. uint8* const pixels = (uint8*) image.lockPixelDataReadWrite (x, y, w, h, stride, pixelStride);
  63982. int srcStride, srcPixelStride;
  63983. const uint8* const srcPix = (const uint8*) sourceImage.lockPixelDataReadOnly (x - imageX, y - imageY, w, h, srcStride, srcPixelStride);
  63984. const int alpha = jlimit (0, 255, roundDoubleToInt (opacity * 255.0f));
  63985. if (image.getFormat() == Image::RGB)
  63986. {
  63987. if (sourceImage.getFormat() == Image::RGB)
  63988. {
  63989. ImageFillEdgeTableRenderer <PixelRGB, PixelRGB> renderer (pixels, stride,
  63990. srcPix, srcStride,
  63991. alpha, (PixelRGB*) 0);
  63992. edgeTable.iterate (renderer, 0, 0, w, h, 0);
  63993. }
  63994. else if (sourceImage.getFormat() == Image::ARGB)
  63995. {
  63996. ImageFillEdgeTableRenderer <PixelRGB, PixelARGB> renderer (pixels, stride,
  63997. srcPix, srcStride,
  63998. alpha, (PixelARGB*) 0);
  63999. edgeTable.iterate (renderer, 0, 0, w, h, 0);
  64000. }
  64001. else
  64002. {
  64003. jassertfalse // not done!
  64004. }
  64005. }
  64006. else if (image.getFormat() == Image::ARGB)
  64007. {
  64008. if (sourceImage.getFormat() == Image::RGB)
  64009. {
  64010. ImageFillEdgeTableRenderer <PixelARGB, PixelRGB> renderer (pixels, stride,
  64011. srcPix, srcStride,
  64012. alpha, (PixelRGB*) 0);
  64013. edgeTable.iterate (renderer, 0, 0, w, h, 0);
  64014. }
  64015. else if (sourceImage.getFormat() == Image::ARGB)
  64016. {
  64017. ImageFillEdgeTableRenderer <PixelARGB, PixelARGB> renderer (pixels, stride,
  64018. srcPix, srcStride,
  64019. alpha, (PixelARGB*) 0);
  64020. edgeTable.iterate (renderer, 0, 0, w, h, 0);
  64021. }
  64022. else
  64023. {
  64024. jassertfalse // not done!
  64025. }
  64026. }
  64027. else
  64028. {
  64029. jassertfalse // not done!
  64030. }
  64031. sourceImage.releasePixelDataReadOnly (srcPix);
  64032. image.releasePixelDataReadWrite (pixels);
  64033. }
  64034. }
  64035. void LowLevelGraphicsSoftwareRenderer::fillAlphaChannelWithColour (const Image& clipImage, int x, int y, const Colour& colour)
  64036. {
  64037. x += xOffset;
  64038. y += yOffset;
  64039. for (RectangleList::Iterator i (*clip); i.next();)
  64040. {
  64041. const Rectangle& r = *i.getRectangle();
  64042. clippedFillAlphaChannelWithColour (r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  64043. clipImage, x, y, colour);
  64044. }
  64045. }
  64046. void LowLevelGraphicsSoftwareRenderer::clippedFillAlphaChannelWithColour (int clipX, int clipY, int clipW, int clipH, const Image& clipImage, int x, int y, const Colour& colour)
  64047. {
  64048. int w = clipImage.getWidth();
  64049. int h = clipImage.getHeight();
  64050. int sx = 0;
  64051. int sy = 0;
  64052. if (x < clipX)
  64053. {
  64054. sx = clipX - x;
  64055. w -= clipX - x;
  64056. x = clipX;
  64057. }
  64058. if (y < clipY)
  64059. {
  64060. sy = clipY - y;
  64061. h -= clipY - y;
  64062. y = clipY;
  64063. }
  64064. if (x + w > clipX + clipW)
  64065. w = clipX + clipW - x;
  64066. if (y + h > clipY + clipH)
  64067. h = clipY + clipH - y;
  64068. if (w > 0 && h > 0)
  64069. {
  64070. int stride, alphaStride, pixelStride;
  64071. uint8* const pixels = (uint8*) image.lockPixelDataReadWrite (x, y, w, h, stride, pixelStride);
  64072. const uint8* const alphaValues
  64073. = clipImage.lockPixelDataReadOnly (sx, sy, w, h, alphaStride, pixelStride);
  64074. #if JUCE_BIG_ENDIAN
  64075. const uint8* const alphas = alphaValues;
  64076. #else
  64077. const uint8* const alphas = alphaValues + (clipImage.getFormat() == Image::ARGB ? 3 : 0);
  64078. #endif
  64079. if (image.getFormat() == Image::RGB)
  64080. {
  64081. blendAlphaMapRGB (pixels, stride,
  64082. alphas, w, h,
  64083. pixelStride, alphaStride,
  64084. colour);
  64085. }
  64086. else if (image.getFormat() == Image::ARGB)
  64087. {
  64088. blendAlphaMapARGB (pixels, stride,
  64089. alphas, w, h,
  64090. pixelStride, alphaStride,
  64091. colour);
  64092. }
  64093. else
  64094. {
  64095. jassertfalse // not done!
  64096. }
  64097. clipImage.releasePixelDataReadOnly (alphaValues);
  64098. image.releasePixelDataReadWrite (pixels);
  64099. }
  64100. }
  64101. void LowLevelGraphicsSoftwareRenderer::fillAlphaChannelWithGradient (const Image& alphaChannelImage, int imageX, int imageY, const ColourGradient& gradient)
  64102. {
  64103. imageX += xOffset;
  64104. imageY += yOffset;
  64105. for (RectangleList::Iterator i (*clip); i.next();)
  64106. {
  64107. const Rectangle& r = *i.getRectangle();
  64108. clippedFillAlphaChannelWithGradient (r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  64109. alphaChannelImage, imageX, imageY, gradient);
  64110. }
  64111. }
  64112. void LowLevelGraphicsSoftwareRenderer::clippedFillAlphaChannelWithGradient (int x, int y, int w, int h,
  64113. const Image& alphaChannelImage,
  64114. int imageX, int imageY, const ColourGradient& gradient)
  64115. {
  64116. if (Rectangle::intersectRectangles (x, y, w, h, imageX, imageY, alphaChannelImage.getWidth(), alphaChannelImage.getHeight()))
  64117. {
  64118. ColourGradient g2 (gradient);
  64119. g2.x1 += xOffset - x;
  64120. g2.x2 += xOffset - x;
  64121. g2.y1 += yOffset - y;
  64122. g2.y2 += yOffset - y;
  64123. Image temp (g2.isOpaque() ? Image::RGB : Image::ARGB, w, h, true);
  64124. LowLevelGraphicsSoftwareRenderer tempG (temp);
  64125. tempG.fillRectWithGradient (0, 0, w, h, g2);
  64126. clippedFillAlphaChannelWithImage (x, y, w, h,
  64127. alphaChannelImage, imageX, imageY,
  64128. temp, x, y, 1.0f);
  64129. }
  64130. }
  64131. void LowLevelGraphicsSoftwareRenderer::fillAlphaChannelWithImage (const Image& alphaImage, int alphaImageX, int alphaImageY,
  64132. const Image& fillerImage, int fillerImageX, int fillerImageY, float opacity)
  64133. {
  64134. alphaImageX += xOffset;
  64135. alphaImageY += yOffset;
  64136. fillerImageX += xOffset;
  64137. fillerImageY += yOffset;
  64138. for (RectangleList::Iterator i (*clip); i.next();)
  64139. {
  64140. const Rectangle& r = *i.getRectangle();
  64141. clippedFillAlphaChannelWithImage (r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  64142. alphaImage, alphaImageX, alphaImageY,
  64143. fillerImage, fillerImageX, fillerImageY, opacity);
  64144. }
  64145. }
  64146. void LowLevelGraphicsSoftwareRenderer::clippedFillAlphaChannelWithImage (int x, int y, int w, int h, const Image& alphaImage, int alphaImageX, int alphaImageY,
  64147. const Image& fillerImage, int fillerImageX, int fillerImageY, float opacity)
  64148. {
  64149. if (Rectangle::intersectRectangles (x, y, w, h, alphaImageX, alphaImageY, alphaImage.getWidth(), alphaImage.getHeight())
  64150. && Rectangle::intersectRectangles (x, y, w, h, fillerImageX, fillerImageY, fillerImage.getWidth(), fillerImage.getHeight()))
  64151. {
  64152. int dstStride, dstPixStride;
  64153. uint8* const dstPix = image.lockPixelDataReadWrite (x, y, w, h, dstStride, dstPixStride);
  64154. int srcStride, srcPixStride;
  64155. const uint8* const srcPix = fillerImage.lockPixelDataReadOnly (x - fillerImageX, y - fillerImageY, w, h, srcStride, srcPixStride);
  64156. int maskStride, maskPixStride;
  64157. const uint8* const alpha
  64158. = alphaImage.lockPixelDataReadOnly (x - alphaImageX, y - alphaImageY, w, h, maskStride, maskPixStride);
  64159. #if JUCE_BIG_ENDIAN
  64160. const uint8* const alphaValues = alpha;
  64161. #else
  64162. const uint8* const alphaValues = alpha + (alphaImage.getFormat() == Image::ARGB ? 3 : 0);
  64163. #endif
  64164. const int extraAlpha = jlimit (0, 0x100, roundDoubleToInt (opacity * 256.0f));
  64165. if (image.getFormat() == Image::RGB)
  64166. {
  64167. if (fillerImage.getFormat() == Image::RGB)
  64168. {
  64169. renderAlphaMap ((PixelRGB*) dstPix, dstStride, (const PixelRGB*) srcPix, srcStride, alphaValues, maskStride, maskPixStride, w, h, extraAlpha);
  64170. }
  64171. else if (fillerImage.getFormat() == Image::ARGB)
  64172. {
  64173. renderAlphaMap ((PixelRGB*) dstPix, dstStride, (const PixelARGB*) srcPix, srcStride, alphaValues, maskStride, maskPixStride, w, h, extraAlpha);
  64174. }
  64175. else
  64176. {
  64177. jassertfalse // not done!
  64178. }
  64179. }
  64180. else if (image.getFormat() == Image::ARGB)
  64181. {
  64182. if (fillerImage.getFormat() == Image::RGB)
  64183. {
  64184. renderAlphaMap ((PixelARGB*) dstPix, dstStride, (const PixelRGB*) srcPix, srcStride, alphaValues, maskStride, maskPixStride, w, h, extraAlpha);
  64185. }
  64186. else if (fillerImage.getFormat() == Image::ARGB)
  64187. {
  64188. renderAlphaMap ((PixelARGB*) dstPix, dstStride, (const PixelARGB*) srcPix, srcStride, alphaValues, maskStride, maskPixStride, w, h, extraAlpha);
  64189. }
  64190. else
  64191. {
  64192. jassertfalse // not done!
  64193. }
  64194. }
  64195. else
  64196. {
  64197. jassertfalse // not done!
  64198. }
  64199. alphaImage.releasePixelDataReadOnly (alphaValues);
  64200. fillerImage.releasePixelDataReadOnly (srcPix);
  64201. image.releasePixelDataReadWrite (dstPix);
  64202. }
  64203. }
  64204. void LowLevelGraphicsSoftwareRenderer::blendImage (const Image& sourceImage, int dx, int dy, int dw, int dh, int sx, int sy, float opacity)
  64205. {
  64206. dx += xOffset;
  64207. dy += yOffset;
  64208. for (RectangleList::Iterator i (*clip); i.next();)
  64209. {
  64210. const Rectangle& r = *i.getRectangle();
  64211. clippedBlendImage (r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  64212. sourceImage, dx, dy, dw, dh, sx, sy, opacity);
  64213. }
  64214. }
  64215. void LowLevelGraphicsSoftwareRenderer::clippedBlendImage (int clipX, int clipY, int clipW, int clipH,
  64216. const Image& sourceImage, int dx, int dy, int dw, int dh, int sx, int sy, float opacity)
  64217. {
  64218. if (dx < clipX)
  64219. {
  64220. sx += clipX - dx;
  64221. dw -= clipX - dx;
  64222. dx = clipX;
  64223. }
  64224. if (dy < clipY)
  64225. {
  64226. sy += clipY - dy;
  64227. dh -= clipY - dy;
  64228. dy = clipY;
  64229. }
  64230. if (dx + dw > clipX + clipW)
  64231. dw = clipX + clipW - dx;
  64232. if (dy + dh > clipY + clipH)
  64233. dh = clipY + clipH - dy;
  64234. if (dw <= 0 || dh <= 0)
  64235. return;
  64236. const uint8 alpha = (uint8) jlimit (0, 0xff, roundDoubleToInt (opacity * 256.0f));
  64237. if (alpha == 0)
  64238. return;
  64239. int dstStride, dstPixelStride;
  64240. uint8* const dstPixels = image.lockPixelDataReadWrite (dx, dy, dw, dh, dstStride, dstPixelStride);
  64241. int srcStride, srcPixelStride;
  64242. const uint8* const srcPixels = sourceImage.lockPixelDataReadOnly (sx, sy, dw, dh, srcStride, srcPixelStride);
  64243. if (image.getFormat() == Image::ARGB)
  64244. {
  64245. if (sourceImage.getFormat() == Image::ARGB)
  64246. {
  64247. overlayImage ((PixelARGB*) dstPixels, dstStride,
  64248. (PixelARGB*) srcPixels, srcStride,
  64249. dw, dh, alpha);
  64250. }
  64251. else if (sourceImage.getFormat() == Image::RGB)
  64252. {
  64253. overlayImage ((PixelARGB*) dstPixels, dstStride,
  64254. (PixelRGB*) srcPixels, srcStride,
  64255. dw, dh, alpha);
  64256. }
  64257. else
  64258. {
  64259. jassertfalse
  64260. }
  64261. }
  64262. else if (image.getFormat() == Image::RGB)
  64263. {
  64264. if (sourceImage.getFormat() == Image::ARGB)
  64265. {
  64266. overlayImage ((PixelRGB*) dstPixels, dstStride,
  64267. (PixelARGB*) srcPixels, srcStride,
  64268. dw, dh, alpha);
  64269. }
  64270. else if (sourceImage.getFormat() == Image::RGB)
  64271. {
  64272. overlayImage ((PixelRGB*) dstPixels, dstStride,
  64273. (PixelRGB*) srcPixels, srcStride,
  64274. dw, dh, alpha);
  64275. }
  64276. else
  64277. {
  64278. jassertfalse
  64279. }
  64280. }
  64281. else
  64282. {
  64283. jassertfalse
  64284. }
  64285. image.releasePixelDataReadWrite (dstPixels);
  64286. sourceImage.releasePixelDataReadOnly (srcPixels);
  64287. }
  64288. void LowLevelGraphicsSoftwareRenderer::blendImageRescaling (const Image& sourceImage,
  64289. int dx, int dy, int dw, int dh,
  64290. int sx, int sy, int sw, int sh,
  64291. float alpha,
  64292. const Graphics::ResamplingQuality quality)
  64293. {
  64294. if (sw > 0 && sh > 0)
  64295. {
  64296. if (sw == dw && sh == dh)
  64297. {
  64298. blendImage (sourceImage,
  64299. dx, dy, dw, dh,
  64300. sx, sy, alpha);
  64301. }
  64302. else
  64303. {
  64304. blendImageWarping (sourceImage,
  64305. sx, sy, sw, sh,
  64306. AffineTransform::translation ((float) -sx,
  64307. (float) -sy)
  64308. .scaled (dw / (float) sw,
  64309. dh / (float) sh)
  64310. .translated ((float) dx,
  64311. (float) dy),
  64312. alpha,
  64313. quality);
  64314. }
  64315. }
  64316. }
  64317. void LowLevelGraphicsSoftwareRenderer::blendImageWarping (const Image& sourceImage,
  64318. int srcClipX, int srcClipY, int srcClipW, int srcClipH,
  64319. const AffineTransform& t,
  64320. float opacity,
  64321. const Graphics::ResamplingQuality quality)
  64322. {
  64323. const AffineTransform transform (t.translated ((float) xOffset, (float) yOffset));
  64324. for (RectangleList::Iterator i (*clip); i.next();)
  64325. {
  64326. const Rectangle& r = *i.getRectangle();
  64327. clippedBlendImageWarping (r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  64328. sourceImage, srcClipX, srcClipY, srcClipW, srcClipH,
  64329. transform, opacity, quality);
  64330. }
  64331. }
  64332. void LowLevelGraphicsSoftwareRenderer::clippedBlendImageWarping (int destClipX, int destClipY, int destClipW, int destClipH,
  64333. const Image& sourceImage,
  64334. int srcClipX, int srcClipY, int srcClipW, int srcClipH,
  64335. const AffineTransform& transform,
  64336. float opacity,
  64337. const Graphics::ResamplingQuality quality)
  64338. {
  64339. if (opacity > 0 && destClipW > 0 && destClipH > 0 && ! transform.isSingularity())
  64340. {
  64341. Rectangle::intersectRectangles (srcClipX, srcClipY, srcClipW, srcClipH,
  64342. 0, 0, sourceImage.getWidth(), sourceImage.getHeight());
  64343. if (srcClipW <= 0 || srcClipH <= 0)
  64344. return;
  64345. jassert (srcClipX >= 0 && srcClipY >= 0);
  64346. Path imageBounds;
  64347. imageBounds.addRectangle ((float) srcClipX, (float) srcClipY, (float) srcClipW, (float) srcClipH);
  64348. imageBounds.applyTransform (transform);
  64349. float imX, imY, imW, imH;
  64350. imageBounds.getBounds (imX, imY, imW, imH);
  64351. if (Rectangle::intersectRectangles (destClipX, destClipY, destClipW, destClipH,
  64352. (int) floorf (imX),
  64353. (int) floorf (imY),
  64354. 1 + roundDoubleToInt (imW),
  64355. 1 + roundDoubleToInt (imH)))
  64356. {
  64357. const uint8 alpha = (uint8) jlimit (0, 0xff, roundDoubleToInt (opacity * 256.0f));
  64358. float srcX1 = (float) destClipX;
  64359. float srcY1 = (float) destClipY;
  64360. float srcX2 = (float) (destClipX + destClipW);
  64361. float srcY2 = srcY1;
  64362. float srcX3 = srcX1;
  64363. float srcY3 = (float) (destClipY + destClipH);
  64364. AffineTransform inverse (transform.inverted());
  64365. inverse.transformPoint (srcX1, srcY1);
  64366. inverse.transformPoint (srcX2, srcY2);
  64367. inverse.transformPoint (srcX3, srcY3);
  64368. const double lineDX = (double) (srcX3 - srcX1) / destClipH;
  64369. const double lineDY = (double) (srcY3 - srcY1) / destClipH;
  64370. const double pixelDX = (double) (srcX2 - srcX1) / destClipW;
  64371. const double pixelDY = (double) (srcY2 - srcY1) / destClipW;
  64372. if (image.getFormat() == Image::ARGB)
  64373. {
  64374. if (sourceImage.getFormat() == Image::ARGB)
  64375. {
  64376. transformedImageRender (image, sourceImage,
  64377. destClipX, destClipY, destClipW, destClipH,
  64378. srcClipX, srcClipY, srcClipW, srcClipH,
  64379. srcX1, srcY1, lineDX, lineDY, pixelDX, pixelDY,
  64380. alpha, quality, (PixelARGB*)0, (PixelARGB*)0);
  64381. }
  64382. else if (sourceImage.getFormat() == Image::RGB)
  64383. {
  64384. transformedImageRender (image, sourceImage,
  64385. destClipX, destClipY, destClipW, destClipH,
  64386. srcClipX, srcClipY, srcClipW, srcClipH,
  64387. srcX1, srcY1, lineDX, lineDY, pixelDX, pixelDY,
  64388. alpha, quality, (PixelARGB*)0, (PixelRGB*)0);
  64389. }
  64390. else
  64391. {
  64392. jassertfalse
  64393. }
  64394. }
  64395. else if (image.getFormat() == Image::RGB)
  64396. {
  64397. if (sourceImage.getFormat() == Image::ARGB)
  64398. {
  64399. transformedImageRender (image, sourceImage,
  64400. destClipX, destClipY, destClipW, destClipH,
  64401. srcClipX, srcClipY, srcClipW, srcClipH,
  64402. srcX1, srcY1, lineDX, lineDY, pixelDX, pixelDY,
  64403. alpha, quality, (PixelRGB*)0, (PixelARGB*)0);
  64404. }
  64405. else if (sourceImage.getFormat() == Image::RGB)
  64406. {
  64407. transformedImageRender (image, sourceImage,
  64408. destClipX, destClipY, destClipW, destClipH,
  64409. srcClipX, srcClipY, srcClipW, srcClipH,
  64410. srcX1, srcY1, lineDX, lineDY, pixelDX, pixelDY,
  64411. alpha, quality, (PixelRGB*)0, (PixelRGB*)0);
  64412. }
  64413. else
  64414. {
  64415. jassertfalse
  64416. }
  64417. }
  64418. else
  64419. {
  64420. jassertfalse
  64421. }
  64422. }
  64423. }
  64424. }
  64425. void LowLevelGraphicsSoftwareRenderer::drawLine (double x1, double y1, double x2, double y2, const Colour& colour)
  64426. {
  64427. x1 += xOffset;
  64428. y1 += yOffset;
  64429. x2 += xOffset;
  64430. y2 += yOffset;
  64431. for (RectangleList::Iterator i (*clip); i.next();)
  64432. {
  64433. const Rectangle& r = *i.getRectangle();
  64434. clippedDrawLine (r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  64435. x1, y1, x2, y2, colour);
  64436. }
  64437. }
  64438. void LowLevelGraphicsSoftwareRenderer::clippedDrawLine (int clipX, int clipY, int clipW, int clipH, double x1, double y1, double x2, double y2, const Colour& colour)
  64439. {
  64440. if (clipW > 0 && clipH > 0)
  64441. {
  64442. if (x1 == x2)
  64443. {
  64444. if (y2 < y1)
  64445. swapVariables (y1, y2);
  64446. clippedDrawVerticalLine (clipX, clipY, clipW, clipH, roundDoubleToInt (x1), y1, y2, colour);
  64447. }
  64448. else if (y1 == y2)
  64449. {
  64450. if (x2 < x1)
  64451. swapVariables (x1, x2);
  64452. clippedDrawHorizontalLine (clipX, clipY, clipW, clipH, roundDoubleToInt (y1), x1, x2, colour);
  64453. }
  64454. else
  64455. {
  64456. double gradient = (y2 - y1) / (x2 - x1);
  64457. if (fabs (gradient) > 1.0)
  64458. {
  64459. gradient = 1.0 / gradient;
  64460. int y = roundDoubleToInt (y1);
  64461. const int startY = y;
  64462. int endY = roundDoubleToInt (y2);
  64463. if (y > endY)
  64464. swapVariables (y, endY);
  64465. while (y < endY)
  64466. {
  64467. const double x = x1 + gradient * (y - startY);
  64468. clippedDrawHorizontalLine (clipX, clipY, clipW, clipH, y, x, x + 1.0, colour);
  64469. ++y;
  64470. }
  64471. }
  64472. else
  64473. {
  64474. int x = roundDoubleToInt (x1);
  64475. const int startX = x;
  64476. int endX = roundDoubleToInt (x2);
  64477. if (x > endX)
  64478. swapVariables (x, endX);
  64479. while (x < endX)
  64480. {
  64481. const double y = y1 + gradient * (x - startX);
  64482. clippedDrawVerticalLine (clipX, clipY, clipW, clipH, x, y, y + 1.0, colour);
  64483. ++x;
  64484. }
  64485. }
  64486. }
  64487. }
  64488. }
  64489. void LowLevelGraphicsSoftwareRenderer::drawVerticalLine (const int x, double top, double bottom, const Colour& col)
  64490. {
  64491. for (RectangleList::Iterator i (*clip); i.next();)
  64492. {
  64493. const Rectangle& r = *i.getRectangle();
  64494. clippedDrawVerticalLine (r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  64495. x + xOffset, top + yOffset, bottom + yOffset, col);
  64496. }
  64497. }
  64498. void LowLevelGraphicsSoftwareRenderer::clippedDrawVerticalLine (int clipX, int clipY, int clipW, int clipH,
  64499. const int x, double top, double bottom, const Colour& col)
  64500. {
  64501. jassert (top <= bottom);
  64502. if (((unsigned int) (x - clipX)) < (unsigned int) clipW
  64503. && top < clipY + clipH
  64504. && bottom > clipY
  64505. && clipW > 0)
  64506. {
  64507. if (top < clipY)
  64508. top = clipY;
  64509. if (bottom > clipY + clipH)
  64510. bottom = clipY + clipH;
  64511. if (bottom > top)
  64512. drawVertical (x, top, bottom, col);
  64513. }
  64514. }
  64515. void LowLevelGraphicsSoftwareRenderer::drawHorizontalLine (const int y, double left, double right, const Colour& col)
  64516. {
  64517. for (RectangleList::Iterator i (*clip); i.next();)
  64518. {
  64519. const Rectangle& r = *i.getRectangle();
  64520. clippedDrawHorizontalLine (r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  64521. y + yOffset, left + xOffset, right + xOffset, col);
  64522. }
  64523. }
  64524. void LowLevelGraphicsSoftwareRenderer::clippedDrawHorizontalLine (int clipX, int clipY, int clipW, int clipH,
  64525. const int y, double left, double right, const Colour& col)
  64526. {
  64527. jassert (left <= right);
  64528. if (((unsigned int) (y - clipY)) < (unsigned int) clipH
  64529. && left < clipX + clipW
  64530. && right > clipX
  64531. && clipW > 0)
  64532. {
  64533. if (left < clipX)
  64534. left = clipX;
  64535. if (right > clipX + clipW)
  64536. right = clipX + clipW;
  64537. if (right > left)
  64538. drawHorizontal (y, left, right, col);
  64539. }
  64540. }
  64541. void LowLevelGraphicsSoftwareRenderer::drawVertical (const int x,
  64542. const double top,
  64543. const double bottom,
  64544. const Colour& col)
  64545. {
  64546. int wholeStart = (int) top;
  64547. const int wholeEnd = (int) bottom;
  64548. const int lastAlpha = roundDoubleToInt (255.0 * (bottom - wholeEnd));
  64549. const int totalPixels = (wholeEnd - wholeStart) + (lastAlpha > 0 ? 1 : 0);
  64550. if (totalPixels <= 0)
  64551. return;
  64552. int lineStride, dstPixelStride;
  64553. uint8* const dstPixels = image.lockPixelDataReadWrite (x, wholeStart, 1, totalPixels, lineStride, dstPixelStride);
  64554. uint8* dest = dstPixels;
  64555. PixelARGB colour (col.getPixelARGB());
  64556. if (wholeEnd == wholeStart)
  64557. {
  64558. if (image.getFormat() == Image::ARGB)
  64559. ((PixelARGB*) dest)->blend (colour, roundDoubleToInt (255.0 * (bottom - top)));
  64560. else if (image.getFormat() == Image::RGB)
  64561. ((PixelRGB*) dest)->blend (colour, roundDoubleToInt (255.0 * (bottom - top)));
  64562. else
  64563. {
  64564. jassertfalse
  64565. }
  64566. }
  64567. else
  64568. {
  64569. if (image.getFormat() == Image::ARGB)
  64570. {
  64571. ((PixelARGB*) dest)->blend (colour, roundDoubleToInt (255.0 * (1.0 - (top - wholeStart))));
  64572. ++wholeStart;
  64573. dest += lineStride;
  64574. if (colour.getAlpha() == 0xff)
  64575. {
  64576. while (wholeEnd > wholeStart)
  64577. {
  64578. ((PixelARGB*) dest)->set (colour);
  64579. ++wholeStart;
  64580. dest += lineStride;
  64581. }
  64582. }
  64583. else
  64584. {
  64585. while (wholeEnd > wholeStart)
  64586. {
  64587. ((PixelARGB*) dest)->blend (colour);
  64588. ++wholeStart;
  64589. dest += lineStride;
  64590. }
  64591. }
  64592. if (lastAlpha > 0)
  64593. {
  64594. ((PixelARGB*) dest)->blend (colour, lastAlpha);
  64595. }
  64596. }
  64597. else if (image.getFormat() == Image::RGB)
  64598. {
  64599. ((PixelRGB*) dest)->blend (colour, roundDoubleToInt (255.0 * (1.0 - (top - wholeStart))));
  64600. ++wholeStart;
  64601. dest += lineStride;
  64602. if (colour.getAlpha() == 0xff)
  64603. {
  64604. while (wholeEnd > wholeStart)
  64605. {
  64606. ((PixelRGB*) dest)->set (colour);
  64607. ++wholeStart;
  64608. dest += lineStride;
  64609. }
  64610. }
  64611. else
  64612. {
  64613. while (wholeEnd > wholeStart)
  64614. {
  64615. ((PixelRGB*) dest)->blend (colour);
  64616. ++wholeStart;
  64617. dest += lineStride;
  64618. }
  64619. }
  64620. if (lastAlpha > 0)
  64621. {
  64622. ((PixelRGB*) dest)->blend (colour, lastAlpha);
  64623. }
  64624. }
  64625. else
  64626. {
  64627. jassertfalse
  64628. }
  64629. }
  64630. image.releasePixelDataReadWrite (dstPixels);
  64631. }
  64632. void LowLevelGraphicsSoftwareRenderer::drawHorizontal (const int y,
  64633. const double top,
  64634. const double bottom,
  64635. const Colour& col)
  64636. {
  64637. int wholeStart = (int) top;
  64638. const int wholeEnd = (int) bottom;
  64639. const int lastAlpha = roundDoubleToInt (255.0 * (bottom - wholeEnd));
  64640. const int totalPixels = (wholeEnd - wholeStart) + (lastAlpha > 0 ? 1 : 0);
  64641. if (totalPixels <= 0)
  64642. return;
  64643. int lineStride, dstPixelStride;
  64644. uint8* const dstPixels = image.lockPixelDataReadWrite (wholeStart, y, totalPixels, 1, lineStride, dstPixelStride);
  64645. uint8* dest = dstPixels;
  64646. PixelARGB colour (col.getPixelARGB());
  64647. if (wholeEnd == wholeStart)
  64648. {
  64649. if (image.getFormat() == Image::ARGB)
  64650. ((PixelARGB*) dest)->blend (colour, roundDoubleToInt (255.0 * (bottom - top)));
  64651. else if (image.getFormat() == Image::RGB)
  64652. ((PixelRGB*) dest)->blend (colour, roundDoubleToInt (255.0 * (bottom - top)));
  64653. else
  64654. {
  64655. jassertfalse
  64656. }
  64657. }
  64658. else
  64659. {
  64660. if (image.getFormat() == Image::ARGB)
  64661. {
  64662. ((PixelARGB*) dest)->blend (colour, roundDoubleToInt (255.0 * (1.0 - (top - wholeStart))));
  64663. dest += dstPixelStride;
  64664. ++wholeStart;
  64665. if (colour.getAlpha() == 0xff)
  64666. {
  64667. while (wholeEnd > wholeStart)
  64668. {
  64669. ((PixelARGB*) dest)->set (colour);
  64670. dest += dstPixelStride;
  64671. ++wholeStart;
  64672. }
  64673. }
  64674. else
  64675. {
  64676. while (wholeEnd > wholeStart)
  64677. {
  64678. ((PixelARGB*) dest)->blend (colour);
  64679. dest += dstPixelStride;
  64680. ++wholeStart;
  64681. }
  64682. }
  64683. if (lastAlpha > 0)
  64684. {
  64685. ((PixelARGB*) dest)->blend (colour, lastAlpha);
  64686. }
  64687. }
  64688. else if (image.getFormat() == Image::RGB)
  64689. {
  64690. ((PixelRGB*) dest)->blend (colour, roundDoubleToInt (255.0 * (1.0 - (top - wholeStart))));
  64691. dest += dstPixelStride;
  64692. ++wholeStart;
  64693. if (colour.getAlpha() == 0xff)
  64694. {
  64695. while (wholeEnd > wholeStart)
  64696. {
  64697. ((PixelRGB*) dest)->set (colour);
  64698. dest += dstPixelStride;
  64699. ++wholeStart;
  64700. }
  64701. }
  64702. else
  64703. {
  64704. while (wholeEnd > wholeStart)
  64705. {
  64706. ((PixelRGB*) dest)->blend (colour);
  64707. dest += dstPixelStride;
  64708. ++wholeStart;
  64709. }
  64710. }
  64711. if (lastAlpha > 0)
  64712. {
  64713. ((PixelRGB*) dest)->blend (colour, lastAlpha);
  64714. }
  64715. }
  64716. else
  64717. {
  64718. jassertfalse
  64719. }
  64720. }
  64721. image.releasePixelDataReadWrite (dstPixels);
  64722. }
  64723. END_JUCE_NAMESPACE
  64724. /********* End of inlined file: juce_LowLevelGraphicsSoftwareRenderer.cpp *********/
  64725. /********* Start of inlined file: juce_RectanglePlacement.cpp *********/
  64726. BEGIN_JUCE_NAMESPACE
  64727. RectanglePlacement::RectanglePlacement (const RectanglePlacement& other) throw()
  64728. : flags (other.flags)
  64729. {
  64730. }
  64731. const RectanglePlacement& RectanglePlacement::operator= (const RectanglePlacement& other) throw()
  64732. {
  64733. flags = other.flags;
  64734. return *this;
  64735. }
  64736. void RectanglePlacement::applyTo (double& x, double& y,
  64737. double& w, double& h,
  64738. const double dx, const double dy,
  64739. const double dw, const double dh) const throw()
  64740. {
  64741. if (w == 0 || h == 0)
  64742. return;
  64743. if ((flags & stretchToFit) != 0)
  64744. {
  64745. x = dx;
  64746. y = dy;
  64747. w = dw;
  64748. h = dh;
  64749. }
  64750. else
  64751. {
  64752. double scale = (flags & fillDestination) != 0 ? jmax (dw / w, dh / h)
  64753. : jmin (dw / w, dh / h);
  64754. if ((flags & onlyReduceInSize) != 0)
  64755. scale = jmin (scale, 1.0);
  64756. if ((flags & onlyIncreaseInSize) != 0)
  64757. scale = jmax (scale, 1.0);
  64758. w *= scale;
  64759. h *= scale;
  64760. if ((flags & xLeft) != 0)
  64761. x = dx;
  64762. else if ((flags & xRight) != 0)
  64763. x = dx + dw - w;
  64764. else
  64765. x = dx + (dw - w) * 0.5;
  64766. if ((flags & yTop) != 0)
  64767. y = dy;
  64768. else if ((flags & yBottom) != 0)
  64769. y = dy + dh - h;
  64770. else
  64771. y = dy + (dh - h) * 0.5;
  64772. }
  64773. }
  64774. const AffineTransform RectanglePlacement::getTransformToFit (float x, float y,
  64775. float w, float h,
  64776. const float dx, const float dy,
  64777. const float dw, const float dh) const throw()
  64778. {
  64779. if (w == 0 || h == 0)
  64780. return AffineTransform::identity;
  64781. const float scaleX = dw / w;
  64782. const float scaleY = dh / h;
  64783. if ((flags & stretchToFit) != 0)
  64784. return AffineTransform::translation (-x, -y)
  64785. .scaled (scaleX, scaleY)
  64786. .translated (dx, dy);
  64787. float scale = (flags & fillDestination) != 0 ? jmax (scaleX, scaleY)
  64788. : jmin (scaleX, scaleY);
  64789. if ((flags & onlyReduceInSize) != 0)
  64790. scale = jmin (scale, 1.0f);
  64791. if ((flags & onlyIncreaseInSize) != 0)
  64792. scale = jmax (scale, 1.0f);
  64793. w *= scale;
  64794. h *= scale;
  64795. float newX = dx;
  64796. if ((flags & xRight) != 0)
  64797. newX += dw - w; // right
  64798. else if ((flags & xLeft) == 0)
  64799. newX += (dw - w) / 2.0f; // centre
  64800. float newY = dy;
  64801. if ((flags & yBottom) != 0)
  64802. newY += dh - h; // bottom
  64803. else if ((flags & yTop) == 0)
  64804. newY += (dh - h) / 2.0f; // centre
  64805. return AffineTransform::translation (-x, -y)
  64806. .scaled (scale, scale)
  64807. .translated (newX, newY);
  64808. }
  64809. END_JUCE_NAMESPACE
  64810. /********* End of inlined file: juce_RectanglePlacement.cpp *********/
  64811. /********* Start of inlined file: juce_Drawable.cpp *********/
  64812. BEGIN_JUCE_NAMESPACE
  64813. Drawable::RenderingContext::RenderingContext (Graphics& g_,
  64814. const AffineTransform& transform_,
  64815. const float opacity_) throw()
  64816. : g (g_),
  64817. transform (transform_),
  64818. opacity (opacity_)
  64819. {
  64820. }
  64821. Drawable::Drawable()
  64822. {
  64823. }
  64824. Drawable::~Drawable()
  64825. {
  64826. }
  64827. void Drawable::draw (Graphics& g,
  64828. const AffineTransform& transform) const
  64829. {
  64830. const RenderingContext context (g, transform, g.getCurrentColour().getFloatAlpha());
  64831. render (context);
  64832. }
  64833. void Drawable::drawAt (Graphics& g, const float x, const float y) const
  64834. {
  64835. draw (g, AffineTransform::translation (x, y));
  64836. }
  64837. void Drawable::drawWithin (Graphics& g,
  64838. const int destX,
  64839. const int destY,
  64840. const int destW,
  64841. const int destH,
  64842. const RectanglePlacement& placement) const
  64843. {
  64844. if (destW > 0 && destH > 0)
  64845. {
  64846. float x, y, w, h;
  64847. getBounds (x, y, w, h);
  64848. draw (g, placement.getTransformToFit (x, y, w, h,
  64849. (float) destX, (float) destY,
  64850. (float) destW, (float) destH));
  64851. }
  64852. }
  64853. Drawable* Drawable::createFromImageData (const void* data, const int numBytes)
  64854. {
  64855. Drawable* result = 0;
  64856. Image* const image = ImageFileFormat::loadFrom (data, numBytes);
  64857. if (image != 0)
  64858. {
  64859. DrawableImage* const di = new DrawableImage();
  64860. di->setImage (image, true);
  64861. result = di;
  64862. }
  64863. else
  64864. {
  64865. const String asString (String::createStringFromData (data, numBytes));
  64866. XmlDocument doc (asString);
  64867. XmlElement* const outer = doc.getDocumentElement (true);
  64868. if (outer != 0 && outer->hasTagName (T("svg")))
  64869. {
  64870. XmlElement* const svg = doc.getDocumentElement();
  64871. if (svg != 0)
  64872. {
  64873. result = Drawable::createFromSVG (*svg);
  64874. delete svg;
  64875. }
  64876. }
  64877. delete outer;
  64878. }
  64879. return result;
  64880. }
  64881. Drawable* Drawable::createFromImageDataStream (InputStream& dataSource)
  64882. {
  64883. MemoryBlock mb;
  64884. dataSource.readIntoMemoryBlock (mb);
  64885. return createFromImageData (mb.getData(), mb.getSize());
  64886. }
  64887. Drawable* Drawable::createFromImageFile (const File& file)
  64888. {
  64889. FileInputStream* fin = file.createInputStream();
  64890. if (fin == 0)
  64891. return 0;
  64892. Drawable* d = createFromImageDataStream (*fin);
  64893. delete fin;
  64894. return d;
  64895. }
  64896. Drawable* Drawable::readFromBinaryStream (InputStream& input)
  64897. {
  64898. char header[8];
  64899. if (input.read (header, sizeof (header)) != sizeof (header))
  64900. return 0;
  64901. DrawableComposite* result = 0;
  64902. if (memcmp (header, "JuceDrw1", sizeof (header)) == 0)
  64903. {
  64904. result = new DrawableComposite();
  64905. if (! result->readBinary (input))
  64906. deleteAndZero (result);
  64907. }
  64908. return result;
  64909. }
  64910. bool Drawable::writeToBinaryStream (OutputStream& output) const
  64911. {
  64912. output.write ("JuceDrw1", 8);
  64913. return writeBinary (output);
  64914. }
  64915. Drawable* Drawable::readFromXml (const XmlElement& xml)
  64916. {
  64917. DrawableComposite* result = 0;
  64918. if (xml.hasTagName (T("JuceDrawable")))
  64919. {
  64920. result = new DrawableComposite();
  64921. if (! result->readXml (xml))
  64922. deleteAndZero (result);
  64923. }
  64924. return result;
  64925. }
  64926. XmlElement* Drawable::createXml() const
  64927. {
  64928. if (dynamic_cast <const DrawableComposite*> (this) == 0)
  64929. {
  64930. DrawableComposite tempDC;
  64931. tempDC.insertDrawable (const_cast <Drawable*> (this));
  64932. XmlElement* result = tempDC.createXml();
  64933. tempDC.removeDrawable (0, false);
  64934. return result;
  64935. }
  64936. else
  64937. {
  64938. XmlElement* e = new XmlElement (T("JuceDrawable"));
  64939. writeXml (*e);
  64940. return e;
  64941. }
  64942. }
  64943. END_JUCE_NAMESPACE
  64944. /********* End of inlined file: juce_Drawable.cpp *********/
  64945. /********* Start of inlined file: juce_DrawableComposite.cpp *********/
  64946. BEGIN_JUCE_NAMESPACE
  64947. DrawableComposite::DrawableComposite()
  64948. {
  64949. }
  64950. DrawableComposite::~DrawableComposite()
  64951. {
  64952. }
  64953. void DrawableComposite::insertDrawable (Drawable* drawable,
  64954. const AffineTransform& transform,
  64955. const int index)
  64956. {
  64957. if (drawable != 0)
  64958. {
  64959. if (! drawables.contains (drawable))
  64960. {
  64961. drawables.insert (index, drawable);
  64962. if (transform.isIdentity())
  64963. transforms.insert (index, 0);
  64964. else
  64965. transforms.insert (index, new AffineTransform (transform));
  64966. }
  64967. else
  64968. {
  64969. jassertfalse // trying to add a drawable that's already in here!
  64970. }
  64971. }
  64972. }
  64973. void DrawableComposite::insertDrawable (const Drawable& drawable,
  64974. const AffineTransform& transform,
  64975. const int index)
  64976. {
  64977. insertDrawable (drawable.createCopy(), transform, index);
  64978. }
  64979. void DrawableComposite::removeDrawable (const int index, const bool deleteDrawable)
  64980. {
  64981. drawables.remove (index, deleteDrawable);
  64982. transforms.remove (index);
  64983. }
  64984. void DrawableComposite::bringToFront (const int index)
  64985. {
  64986. if (index >= 0 && index < drawables.size() - 1)
  64987. {
  64988. drawables.move (index, -1);
  64989. transforms.move (index, -1);
  64990. }
  64991. }
  64992. void DrawableComposite::render (const Drawable::RenderingContext& context) const
  64993. {
  64994. if (drawables.size() > 0 && context.opacity > 0)
  64995. {
  64996. if (context.opacity >= 1.0f || drawables.size() == 1)
  64997. {
  64998. Drawable::RenderingContext contextCopy (context);
  64999. for (int i = 0; i < drawables.size(); ++i)
  65000. {
  65001. const AffineTransform* const t = transforms.getUnchecked(i);
  65002. contextCopy.transform = (t == 0) ? context.transform
  65003. : t->followedBy (context.transform);
  65004. drawables.getUnchecked(i)->render (contextCopy);
  65005. }
  65006. }
  65007. else
  65008. {
  65009. // To correctly render a whole composite layer with an overall transparency,
  65010. // we need to render everything opaquely into a temp buffer, then blend that
  65011. // with the target opacity...
  65012. const Rectangle clipBounds (context.g.getClipBounds());
  65013. Image tempImage (Image::ARGB, clipBounds.getWidth(), clipBounds.getHeight(), true);
  65014. {
  65015. Graphics tempG (tempImage);
  65016. tempG.setOrigin (-clipBounds.getX(), -clipBounds.getY());
  65017. Drawable::RenderingContext tempContext (tempG, context.transform, 1.0f);
  65018. render (tempContext);
  65019. }
  65020. context.g.setOpacity (context.opacity);
  65021. context.g.drawImageAt (&tempImage, clipBounds.getX(), clipBounds.getY());
  65022. }
  65023. }
  65024. }
  65025. void DrawableComposite::getBounds (float& x, float& y, float& width, float& height) const
  65026. {
  65027. Path totalPath;
  65028. for (int i = 0; i < drawables.size(); ++i)
  65029. {
  65030. drawables.getUnchecked(i)->getBounds (x, y, width, height);
  65031. if (width > 0.0f && height > 0.0f)
  65032. {
  65033. Path outline;
  65034. outline.addRectangle (x, y, width, height);
  65035. const AffineTransform* const t = transforms.getUnchecked(i);
  65036. if (t == 0)
  65037. totalPath.addPath (outline);
  65038. else
  65039. totalPath.addPath (outline, *t);
  65040. }
  65041. }
  65042. totalPath.getBounds (x, y, width, height);
  65043. }
  65044. bool DrawableComposite::hitTest (float x, float y) const
  65045. {
  65046. for (int i = 0; i < drawables.size(); ++i)
  65047. {
  65048. float tx = x;
  65049. float ty = y;
  65050. const AffineTransform* const t = transforms.getUnchecked(i);
  65051. if (t != 0)
  65052. t->inverted().transformPoint (tx, ty);
  65053. if (drawables.getUnchecked(i)->hitTest (tx, ty))
  65054. return true;
  65055. }
  65056. return false;
  65057. }
  65058. Drawable* DrawableComposite::createCopy() const
  65059. {
  65060. DrawableComposite* const dc = new DrawableComposite();
  65061. for (int i = 0; i < drawables.size(); ++i)
  65062. {
  65063. dc->drawables.add (drawables.getUnchecked(i)->createCopy());
  65064. const AffineTransform* const t = transforms.getUnchecked(i);
  65065. dc->transforms.add (t != 0 ? new AffineTransform (*t) : 0);
  65066. }
  65067. return dc;
  65068. }
  65069. const char juce_drawableCompositeTransformFlag = 't';
  65070. const char juce_drawableCompositeBinaryType = 'C';
  65071. const char juce_drawablePathBinaryType = 'P';
  65072. const char juce_drawableImageBinaryType = 'I';
  65073. const char juce_drawableTextBinaryType = 'T';
  65074. bool DrawableComposite::readBinary (InputStream& input)
  65075. {
  65076. AffineTransform transform;
  65077. while (! input.isExhausted())
  65078. {
  65079. const int n = input.readByte();
  65080. if (n == 0)
  65081. break;
  65082. if (n == juce_drawableCompositeTransformFlag)
  65083. {
  65084. float f[6];
  65085. for (int i = 0; i < 6; ++i)
  65086. f[i] = input.readFloat();
  65087. transform = AffineTransform (f[0], f[1], f[2], f[3], f[4], f[5]);
  65088. }
  65089. else
  65090. {
  65091. Drawable* d = 0;
  65092. switch (n)
  65093. {
  65094. case juce_drawableCompositeBinaryType: d = new DrawableComposite(); break;
  65095. case juce_drawablePathBinaryType: d = new DrawablePath(); break;
  65096. case juce_drawableImageBinaryType: d = new DrawableImage(); break;
  65097. case juce_drawableTextBinaryType: d = new DrawableText(); break;
  65098. default: jassertfalse; return false;
  65099. }
  65100. d->setName (input.readString());
  65101. if (! d->readBinary (input))
  65102. {
  65103. delete d;
  65104. return false;
  65105. }
  65106. insertDrawable (d, transform);
  65107. transform = AffineTransform::identity;
  65108. }
  65109. }
  65110. return true;
  65111. }
  65112. bool DrawableComposite::writeBinary (OutputStream& output) const
  65113. {
  65114. for (int i = 0; i < drawables.size(); ++i)
  65115. {
  65116. AffineTransform* transform = transforms.getUnchecked(i);
  65117. if (transform != 0)
  65118. {
  65119. output.writeByte (juce_drawableCompositeTransformFlag);
  65120. output.writeFloat (transform->mat00);
  65121. output.writeFloat (transform->mat01);
  65122. output.writeFloat (transform->mat02);
  65123. output.writeFloat (transform->mat10);
  65124. output.writeFloat (transform->mat11);
  65125. output.writeFloat (transform->mat12);
  65126. }
  65127. Drawable* const d = drawables.getUnchecked(i);
  65128. char typeFlag;
  65129. if (dynamic_cast <DrawableComposite*> (d) != 0)
  65130. typeFlag = juce_drawableCompositeBinaryType;
  65131. else if (dynamic_cast <DrawablePath*> (d) != 0)
  65132. typeFlag = juce_drawablePathBinaryType;
  65133. else if (dynamic_cast <DrawableImage*> (d) != 0)
  65134. typeFlag = juce_drawableImageBinaryType;
  65135. else if (dynamic_cast <DrawableText*> (d) != 0)
  65136. typeFlag = juce_drawableTextBinaryType;
  65137. else
  65138. {
  65139. jassertfalse;
  65140. continue;
  65141. }
  65142. output.writeByte (typeFlag);
  65143. output.writeString (d->getName());
  65144. d->writeBinary (output);
  65145. }
  65146. output.writeByte (0);
  65147. return true;
  65148. }
  65149. const tchar* juce_drawableCompositeXmlTag = T("Group");
  65150. const tchar* juce_drawablePathXmlTag = T("Path");
  65151. const tchar* juce_drawableImageXmlTag = T("Image");
  65152. const tchar* juce_drawableTextXmlTag = T("Text");
  65153. bool DrawableComposite::readXml (const XmlElement& xml)
  65154. {
  65155. forEachXmlChildElement (xml, e)
  65156. {
  65157. Drawable* d = 0;
  65158. if (e->hasTagName (juce_drawableCompositeXmlTag))
  65159. d = new DrawableComposite();
  65160. else if (e->hasTagName (juce_drawablePathXmlTag))
  65161. d = new DrawablePath();
  65162. else if (e->hasTagName (juce_drawableImageXmlTag))
  65163. d = new DrawableImage();
  65164. else if (e->hasTagName (juce_drawableTextXmlTag))
  65165. d = new DrawableText();
  65166. else
  65167. {
  65168. jassertfalse;
  65169. return false;
  65170. }
  65171. d->setName (e->getStringAttribute (T("id")));
  65172. if (! d->readXml (*e))
  65173. {
  65174. jassertfalse;
  65175. delete d;
  65176. return false;
  65177. }
  65178. AffineTransform transform;
  65179. const String transformAtt (e->getStringAttribute (T("transform")));
  65180. if (transformAtt.isNotEmpty())
  65181. {
  65182. StringArray tokens;
  65183. tokens.addTokens (transformAtt.trim(), false);
  65184. tokens.removeEmptyStrings (true);
  65185. if (tokens.size() == 6)
  65186. {
  65187. float f[6];
  65188. for (int i = 0; i < 6; ++i)
  65189. f[i] = (float) tokens[i].getDoubleValue();
  65190. transform = AffineTransform (f[0], f[1], f[2], f[3], f[4], f[5]);
  65191. }
  65192. }
  65193. insertDrawable (d, transform);
  65194. }
  65195. return true;
  65196. }
  65197. void DrawableComposite::writeXml (XmlElement& xml) const
  65198. {
  65199. for (int i = 0; i < drawables.size(); ++i)
  65200. {
  65201. XmlElement* e = 0;
  65202. Drawable* const d = drawables.getUnchecked(i);
  65203. if (dynamic_cast <DrawableComposite*> (d) != 0)
  65204. e = new XmlElement (juce_drawableCompositeXmlTag);
  65205. else if (dynamic_cast <DrawablePath*> (d) != 0)
  65206. e = new XmlElement (juce_drawablePathXmlTag);
  65207. else if (dynamic_cast <DrawableImage*> (d) != 0)
  65208. e = new XmlElement (juce_drawableImageXmlTag);
  65209. else if (dynamic_cast <DrawableText*> (d) != 0)
  65210. e = new XmlElement (juce_drawableTextXmlTag);
  65211. else
  65212. {
  65213. jassertfalse;
  65214. continue;
  65215. }
  65216. AffineTransform* transform = transforms.getUnchecked(i);
  65217. if (transform != 0)
  65218. {
  65219. String t;
  65220. t << transform->mat00 << " " << transform->mat01 << " " << transform->mat02 << " "
  65221. << transform->mat10 << " " << transform->mat11 << " " << transform->mat12;
  65222. e->setAttribute (T("transform"), t);
  65223. }
  65224. if (d->getName().isNotEmpty())
  65225. e->setAttribute (T("id"), d->getName());
  65226. d->writeXml (*e);
  65227. xml.addChildElement (e);
  65228. }
  65229. }
  65230. END_JUCE_NAMESPACE
  65231. /********* End of inlined file: juce_DrawableComposite.cpp *********/
  65232. /********* Start of inlined file: juce_DrawableImage.cpp *********/
  65233. BEGIN_JUCE_NAMESPACE
  65234. DrawableImage::DrawableImage()
  65235. : image (0),
  65236. canDeleteImage (false),
  65237. opacity (1.0f),
  65238. overlayColour (0x00000000)
  65239. {
  65240. }
  65241. DrawableImage::~DrawableImage()
  65242. {
  65243. clearImage();
  65244. }
  65245. void DrawableImage::clearImage()
  65246. {
  65247. if (canDeleteImage && image != 0)
  65248. {
  65249. if (ImageCache::isImageInCache (image))
  65250. ImageCache::release (image);
  65251. else
  65252. delete image;
  65253. }
  65254. image = 0;
  65255. }
  65256. void DrawableImage::setImage (const Image& imageToCopy)
  65257. {
  65258. clearImage();
  65259. image = new Image (imageToCopy);
  65260. canDeleteImage = true;
  65261. }
  65262. void DrawableImage::setImage (Image* imageToUse,
  65263. const bool releaseWhenNotNeeded)
  65264. {
  65265. clearImage();
  65266. image = imageToUse;
  65267. canDeleteImage = releaseWhenNotNeeded;
  65268. }
  65269. void DrawableImage::setOpacity (const float newOpacity)
  65270. {
  65271. opacity = newOpacity;
  65272. }
  65273. void DrawableImage::setOverlayColour (const Colour& newOverlayColour)
  65274. {
  65275. overlayColour = newOverlayColour;
  65276. }
  65277. void DrawableImage::render (const Drawable::RenderingContext& context) const
  65278. {
  65279. if (image != 0)
  65280. {
  65281. if (opacity > 0.0f && ! overlayColour.isOpaque())
  65282. {
  65283. context.g.setOpacity (context.opacity * opacity);
  65284. context.g.drawImageTransformed (image,
  65285. 0, 0, image->getWidth(), image->getHeight(),
  65286. context.transform, false);
  65287. }
  65288. if (! overlayColour.isTransparent())
  65289. {
  65290. context.g.setColour (overlayColour.withMultipliedAlpha (context.opacity));
  65291. context.g.drawImageTransformed (image,
  65292. 0, 0, image->getWidth(), image->getHeight(),
  65293. context.transform, true);
  65294. }
  65295. }
  65296. }
  65297. void DrawableImage::getBounds (float& x, float& y, float& width, float& height) const
  65298. {
  65299. x = 0.0f;
  65300. y = 0.0f;
  65301. width = 0.0f;
  65302. height = 0.0f;
  65303. if (image != 0)
  65304. {
  65305. width = (float) image->getWidth();
  65306. height = (float) image->getHeight();
  65307. }
  65308. }
  65309. bool DrawableImage::hitTest (float x, float y) const
  65310. {
  65311. return image != 0
  65312. && x >= 0.0f
  65313. && y >= 0.0f
  65314. && x < image->getWidth()
  65315. && y < image->getHeight()
  65316. && image->getPixelAt (roundFloatToInt (x), roundFloatToInt (y)).getAlpha() >= 127;
  65317. }
  65318. Drawable* DrawableImage::createCopy() const
  65319. {
  65320. DrawableImage* const di = new DrawableImage();
  65321. di->opacity = opacity;
  65322. di->overlayColour = overlayColour;
  65323. if (image != 0)
  65324. {
  65325. if ((! canDeleteImage) || ! ImageCache::isImageInCache (image))
  65326. {
  65327. di->setImage (*image);
  65328. }
  65329. else
  65330. {
  65331. ImageCache::incReferenceCount (image);
  65332. di->setImage (image, true);
  65333. }
  65334. }
  65335. return di;
  65336. }
  65337. bool DrawableImage::readBinary (InputStream& input)
  65338. {
  65339. opacity = input.readFloat();
  65340. overlayColour = Colour (input.readInt());
  65341. const int dataLen = input.readInt();
  65342. if (dataLen > 0)
  65343. {
  65344. MemoryBlock imageData;
  65345. input.readIntoMemoryBlock (imageData, dataLen);
  65346. Image* im = ImageFileFormat::loadFrom (imageData.getData(), imageData.getSize());
  65347. if (im == 0)
  65348. return false;
  65349. setImage (im, true);
  65350. }
  65351. return true;
  65352. }
  65353. bool DrawableImage::writeBinary (OutputStream& output) const
  65354. {
  65355. MemoryOutputStream imageData;
  65356. if (image != 0)
  65357. {
  65358. PNGImageFormat pngFormat;
  65359. if (! pngFormat.writeImageToStream (*image, imageData))
  65360. return false;
  65361. }
  65362. output.writeFloat (opacity);
  65363. output.writeInt (overlayColour.getARGB());
  65364. output.writeInt (imageData.getDataSize());
  65365. output.write (imageData.getData(), imageData.getDataSize());
  65366. return true;
  65367. }
  65368. bool DrawableImage::readXml (const XmlElement& xml)
  65369. {
  65370. opacity = (float) xml.getDoubleAttribute (T("opacity"), 1.0);
  65371. overlayColour = Colour (xml.getStringAttribute (T("overlay"), T("0")).getHexValue32());
  65372. MemoryBlock imageData;
  65373. if (imageData.fromBase64Encoding (xml.getAllSubText()))
  65374. {
  65375. Image* const im = ImageFileFormat::loadFrom (imageData.getData(), imageData.getSize());
  65376. if (im == 0)
  65377. return false;
  65378. setImage (im, true);
  65379. }
  65380. return true;
  65381. }
  65382. void DrawableImage::writeXml (XmlElement& xml) const
  65383. {
  65384. if (opacity < 1.0f)
  65385. xml.setAttribute (T("opacity"), (double) opacity);
  65386. if (! overlayColour.isTransparent())
  65387. xml.setAttribute (T("overlay"), String::toHexString ((int) overlayColour.getARGB()));
  65388. if (image != 0)
  65389. {
  65390. MemoryOutputStream imageData;
  65391. PNGImageFormat pngFormat;
  65392. if (pngFormat.writeImageToStream (*image, imageData))
  65393. {
  65394. String base64 (MemoryBlock (imageData.getData(), imageData.getDataSize()).toBase64Encoding());
  65395. for (int i = (base64.length() & ~127); i >= 0; i -= 128)
  65396. base64 = base64.substring (0, i) + "\n" + base64.substring (i);
  65397. xml.addTextElement (base64);
  65398. }
  65399. }
  65400. }
  65401. END_JUCE_NAMESPACE
  65402. /********* End of inlined file: juce_DrawableImage.cpp *********/
  65403. /********* Start of inlined file: juce_DrawablePath.cpp *********/
  65404. BEGIN_JUCE_NAMESPACE
  65405. DrawablePath::DrawablePath()
  65406. : fillBrush (new SolidColourBrush (Colours::black)),
  65407. strokeBrush (0),
  65408. strokeType (0.0f)
  65409. {
  65410. }
  65411. DrawablePath::~DrawablePath()
  65412. {
  65413. delete fillBrush;
  65414. delete strokeBrush;
  65415. }
  65416. void DrawablePath::setPath (const Path& newPath)
  65417. {
  65418. path = newPath;
  65419. updateOutline();
  65420. }
  65421. void DrawablePath::setSolidFill (const Colour& newColour)
  65422. {
  65423. delete fillBrush;
  65424. fillBrush = new SolidColourBrush (newColour);
  65425. }
  65426. void DrawablePath::setFillBrush (const Brush& newBrush)
  65427. {
  65428. delete fillBrush;
  65429. fillBrush = newBrush.createCopy();
  65430. }
  65431. void DrawablePath::setOutline (const float thickness, const Colour& colour)
  65432. {
  65433. strokeType = PathStrokeType (thickness);
  65434. delete strokeBrush;
  65435. strokeBrush = new SolidColourBrush (colour);
  65436. updateOutline();
  65437. }
  65438. void DrawablePath::setOutline (const PathStrokeType& strokeType_, const Brush& newStrokeBrush)
  65439. {
  65440. strokeType = strokeType_;
  65441. delete strokeBrush;
  65442. strokeBrush = newStrokeBrush.createCopy();
  65443. updateOutline();
  65444. }
  65445. void DrawablePath::render (const Drawable::RenderingContext& context) const
  65446. {
  65447. {
  65448. Brush* const tempBrush = fillBrush->createCopy();
  65449. tempBrush->applyTransform (context.transform);
  65450. tempBrush->multiplyOpacity (context.opacity);
  65451. context.g.setBrush (tempBrush);
  65452. context.g.fillPath (path, context.transform);
  65453. delete tempBrush;
  65454. }
  65455. if (strokeBrush != 0 && strokeType.getStrokeThickness() > 0.0f)
  65456. {
  65457. Brush* const tempBrush = strokeBrush->createCopy();
  65458. tempBrush->applyTransform (context.transform);
  65459. tempBrush->multiplyOpacity (context.opacity);
  65460. context.g.setBrush (tempBrush);
  65461. context.g.fillPath (outline, context.transform);
  65462. delete tempBrush;
  65463. }
  65464. }
  65465. void DrawablePath::updateOutline()
  65466. {
  65467. outline.clear();
  65468. strokeType.createStrokedPath (outline, path, AffineTransform::identity, 4.0f);
  65469. }
  65470. void DrawablePath::getBounds (float& x, float& y, float& width, float& height) const
  65471. {
  65472. if (strokeType.getStrokeThickness() > 0.0f)
  65473. outline.getBounds (x, y, width, height);
  65474. else
  65475. path.getBounds (x, y, width, height);
  65476. }
  65477. bool DrawablePath::hitTest (float x, float y) const
  65478. {
  65479. return path.contains (x, y)
  65480. || outline.contains (x, y);
  65481. }
  65482. Drawable* DrawablePath::createCopy() const
  65483. {
  65484. DrawablePath* const dp = new DrawablePath();
  65485. dp->path = path;
  65486. dp->setFillBrush (*fillBrush);
  65487. if (strokeBrush != 0)
  65488. dp->setOutline (strokeType, *strokeBrush);
  65489. return dp;
  65490. }
  65491. static Brush* readBrushFromBinary (InputStream& input)
  65492. {
  65493. switch (input.readByte())
  65494. {
  65495. case 1:
  65496. return new SolidColourBrush (Colour ((uint32) input.readInt()));
  65497. case 2:
  65498. {
  65499. ColourGradient gradient;
  65500. gradient.x1 = input.readFloat();
  65501. gradient.y1 = input.readFloat();
  65502. gradient.x2 = input.readFloat();
  65503. gradient.y2 = input.readFloat();
  65504. gradient.isRadial = input.readByte() != 0;
  65505. const int numColours = input.readCompressedInt();
  65506. for (int i = 0; i < numColours; ++i)
  65507. {
  65508. double proportion = (double) input.readFloat();
  65509. const Colour colour ((uint32) input.readInt());
  65510. gradient.addColour (proportion, colour);
  65511. }
  65512. return new GradientBrush (gradient);
  65513. }
  65514. case 3:
  65515. {
  65516. jassertfalse; //xxx TODO
  65517. return new ImageBrush (0, 0, 0, 0);
  65518. }
  65519. default:
  65520. break;
  65521. }
  65522. return 0;
  65523. }
  65524. static void writeBrushToBinary (OutputStream& output, const Brush* const brush)
  65525. {
  65526. if (brush == 0)
  65527. {
  65528. output.writeByte (0);
  65529. return;
  65530. }
  65531. const SolidColourBrush* cb;
  65532. const GradientBrush* gb;
  65533. const ImageBrush* ib;
  65534. if ((cb = dynamic_cast <const SolidColourBrush*> (brush)) != 0)
  65535. {
  65536. output.writeByte (1);
  65537. output.writeInt ((int) cb->getColour().getARGB());
  65538. }
  65539. else if ((gb = dynamic_cast <const GradientBrush*> (brush)) != 0)
  65540. {
  65541. output.writeByte (2);
  65542. const ColourGradient& g = gb->getGradient();
  65543. output.writeFloat (g.x1);
  65544. output.writeFloat (g.y1);
  65545. output.writeFloat (g.x2);
  65546. output.writeFloat (g.y2);
  65547. output.writeByte (g.isRadial ? 1 : 0);
  65548. output.writeCompressedInt (g.getNumColours());
  65549. for (int i = 0; i < g.getNumColours(); ++i)
  65550. {
  65551. output.writeFloat ((float) g.getColourPosition (i));
  65552. output.writeInt ((int) g.getColour (i).getARGB());
  65553. }
  65554. }
  65555. else if ((ib = dynamic_cast <const ImageBrush*> (brush)) != 0)
  65556. {
  65557. output.writeByte (3);
  65558. jassertfalse; //xxx TODO
  65559. }
  65560. }
  65561. static Brush* readBrushFromXml (const XmlElement* xml)
  65562. {
  65563. if (xml == 0)
  65564. return 0;
  65565. const String type (xml->getStringAttribute (T("type")));
  65566. if (type.equalsIgnoreCase (T("solid")))
  65567. return new SolidColourBrush (Colour ((uint32) xml->getStringAttribute (T("colour"), T("ff000000")).getHexValue32()));
  65568. if (type.equalsIgnoreCase (T("gradient")))
  65569. {
  65570. ColourGradient gradient;
  65571. gradient.x1 = (float) xml->getDoubleAttribute (T("x1"));
  65572. gradient.y1 = (float) xml->getDoubleAttribute (T("y1"));
  65573. gradient.x2 = (float) xml->getDoubleAttribute (T("x2"));
  65574. gradient.y2 = (float) xml->getDoubleAttribute (T("y2"));
  65575. gradient.isRadial = xml->getBoolAttribute (T("radial"), false);
  65576. StringArray colours;
  65577. colours.addTokens (xml->getStringAttribute (T("colours")), false);
  65578. for (int i = 0; i < colours.size() / 2; ++i)
  65579. gradient.addColour (colours[i * 2].getDoubleValue(),
  65580. Colour ((uint32) colours[i * 2 + 1].getHexValue32()));
  65581. return new GradientBrush (gradient);
  65582. }
  65583. if (type.equalsIgnoreCase (T("image")))
  65584. {
  65585. jassertfalse; //xxx TODO
  65586. return new ImageBrush (0, 0, 0, 0);
  65587. }
  65588. return 0;
  65589. }
  65590. static XmlElement* writeBrushToXml (const String& tagName, const Brush* brush)
  65591. {
  65592. if (brush == 0)
  65593. return 0;
  65594. XmlElement* const xml = new XmlElement (tagName);
  65595. const SolidColourBrush* cb;
  65596. const GradientBrush* gb;
  65597. const ImageBrush* ib;
  65598. if ((cb = dynamic_cast <const SolidColourBrush*> (brush)) != 0)
  65599. {
  65600. xml->setAttribute (T("type"), T("solid"));
  65601. xml->setAttribute (T("colour"), String::toHexString ((int) cb->getColour().getARGB()));
  65602. }
  65603. else if ((gb = dynamic_cast <const GradientBrush*> (brush)) != 0)
  65604. {
  65605. xml->setAttribute (T("type"), T("gradient"));
  65606. const ColourGradient& g = gb->getGradient();
  65607. xml->setAttribute (T("x1"), g.x1);
  65608. xml->setAttribute (T("y1"), g.y1);
  65609. xml->setAttribute (T("x2"), g.x2);
  65610. xml->setAttribute (T("y2"), g.y2);
  65611. xml->setAttribute (T("radial"), g.isRadial);
  65612. String s;
  65613. for (int i = 0; i < g.getNumColours(); ++i)
  65614. s << " " << g.getColourPosition (i) << " " << String::toHexString ((int) g.getColour(i).getARGB());
  65615. xml->setAttribute (T("colours"), s.trimStart());
  65616. }
  65617. else if ((ib = dynamic_cast <const ImageBrush*> (brush)) != 0)
  65618. {
  65619. xml->setAttribute (T("type"), T("image"));
  65620. jassertfalse; //xxx TODO
  65621. }
  65622. return xml;
  65623. }
  65624. bool DrawablePath::readBinary (InputStream& input)
  65625. {
  65626. delete fillBrush;
  65627. fillBrush = readBrushFromBinary (input);
  65628. delete strokeBrush;
  65629. strokeBrush = readBrushFromBinary (input);
  65630. const float strokeThickness = input.readFloat();
  65631. const int jointStyle = input.readByte();
  65632. const int endStyle = input.readByte();
  65633. strokeType = PathStrokeType (strokeThickness,
  65634. jointStyle == 1 ? PathStrokeType::curved
  65635. : (jointStyle == 2 ? PathStrokeType::beveled
  65636. : PathStrokeType::mitered),
  65637. endStyle == 1 ? PathStrokeType::square
  65638. : (endStyle == 2 ? PathStrokeType::rounded
  65639. : PathStrokeType::butt));
  65640. const int pathSize = input.readInt();
  65641. MemoryBlock pathData;
  65642. input.readIntoMemoryBlock (pathData, pathSize);
  65643. if (pathData.getSize() != pathSize)
  65644. return false;
  65645. path.clear();
  65646. path.loadPathFromData ((const uint8*) pathData.getData(), pathSize);
  65647. updateOutline();
  65648. return true;
  65649. }
  65650. bool DrawablePath::writeBinary (OutputStream& output) const
  65651. {
  65652. writeBrushToBinary (output, fillBrush);
  65653. writeBrushToBinary (output, strokeBrush);
  65654. output.writeFloat (strokeType.getStrokeThickness());
  65655. output.writeByte (strokeType.getJointStyle() == PathStrokeType::mitered ? 0
  65656. : (strokeType.getJointStyle() == PathStrokeType::curved ? 1 : 2));
  65657. output.writeByte (strokeType.getEndStyle() == PathStrokeType::butt ? 0
  65658. : (strokeType.getEndStyle() == PathStrokeType::square ? 1 : 2));
  65659. MemoryOutputStream out;
  65660. path.writePathToStream (out);
  65661. output.writeInt (out.getDataSize());
  65662. output.write (out.getData(), out.getDataSize());
  65663. return true;
  65664. }
  65665. bool DrawablePath::readXml (const XmlElement& xml)
  65666. {
  65667. delete fillBrush;
  65668. fillBrush = readBrushFromXml (xml.getChildByName (T("fill")));
  65669. delete strokeBrush;
  65670. strokeBrush = readBrushFromXml (xml.getChildByName (T("stroke")));
  65671. const String jointStyle (xml.getStringAttribute (T("jointStyle"), String::empty));
  65672. const String endStyle (xml.getStringAttribute (T("capStyle"), String::empty));
  65673. strokeType = PathStrokeType ((float) xml.getDoubleAttribute (T("strokeWidth"), 0.0),
  65674. jointStyle.equalsIgnoreCase (T("curved")) ? PathStrokeType::curved
  65675. : (jointStyle.equalsIgnoreCase (T("bevel")) ? PathStrokeType::beveled
  65676. : PathStrokeType::mitered),
  65677. endStyle.equalsIgnoreCase (T("square")) ? PathStrokeType::square
  65678. : (endStyle.equalsIgnoreCase (T("round")) ? PathStrokeType::rounded
  65679. : PathStrokeType::butt));
  65680. path.clear();
  65681. path.restoreFromString (xml.getAllSubText());
  65682. updateOutline();
  65683. return true;
  65684. }
  65685. void DrawablePath::writeXml (XmlElement& xml) const
  65686. {
  65687. xml.addChildElement (writeBrushToXml (T("fill"), fillBrush));
  65688. xml.addChildElement (writeBrushToXml (T("stroke"), strokeBrush));
  65689. xml.setAttribute (T("strokeWidth"), (double) strokeType.getStrokeThickness());
  65690. xml.setAttribute (T("jointStyle"),
  65691. strokeType.getJointStyle() == PathStrokeType::mitered ? T("miter")
  65692. : (strokeType.getJointStyle() == PathStrokeType::curved ? T("curved") : T("bevel")));
  65693. xml.setAttribute (T("capStyle"),
  65694. strokeType.getEndStyle() == PathStrokeType::butt ? T("butt")
  65695. : (strokeType.getEndStyle() == PathStrokeType::square ? T("square") : T("round")));
  65696. xml.addTextElement (path.toString());
  65697. }
  65698. END_JUCE_NAMESPACE
  65699. /********* End of inlined file: juce_DrawablePath.cpp *********/
  65700. /********* Start of inlined file: juce_DrawableText.cpp *********/
  65701. BEGIN_JUCE_NAMESPACE
  65702. DrawableText::DrawableText()
  65703. : colour (Colours::white)
  65704. {
  65705. }
  65706. DrawableText::~DrawableText()
  65707. {
  65708. }
  65709. void DrawableText::setText (const GlyphArrangement& newText)
  65710. {
  65711. text = newText;
  65712. }
  65713. void DrawableText::setText (const String& newText, const Font& fontToUse)
  65714. {
  65715. text.clear();
  65716. text.addLineOfText (fontToUse, newText, 0.0f, 0.0f);
  65717. }
  65718. void DrawableText::setColour (const Colour& newColour)
  65719. {
  65720. colour = newColour;
  65721. }
  65722. void DrawableText::render (const Drawable::RenderingContext& context) const
  65723. {
  65724. context.g.setColour (colour.withMultipliedAlpha (context.opacity));
  65725. text.draw (context.g, context.transform);
  65726. }
  65727. void DrawableText::getBounds (float& x, float& y, float& width, float& height) const
  65728. {
  65729. text.getBoundingBox (0, -1, x, y, width, height, false); // (really returns top, left, bottom, right)
  65730. width -= x;
  65731. height -= y;
  65732. }
  65733. bool DrawableText::hitTest (float x, float y) const
  65734. {
  65735. return text.findGlyphIndexAt (x, y) >= 0;
  65736. }
  65737. Drawable* DrawableText::createCopy() const
  65738. {
  65739. DrawableText* const dt = new DrawableText();
  65740. dt->text = text;
  65741. dt->colour = colour;
  65742. return dt;
  65743. }
  65744. bool DrawableText::readBinary (InputStream& input)
  65745. {
  65746. jassertfalse; //xxx TODO
  65747. return false;
  65748. }
  65749. bool DrawableText::writeBinary (OutputStream& output) const
  65750. {
  65751. jassertfalse; //xxx TODO
  65752. return false;
  65753. }
  65754. bool DrawableText::readXml (const XmlElement& xml)
  65755. {
  65756. jassertfalse; //xxx TODO
  65757. return false;
  65758. }
  65759. void DrawableText::writeXml (XmlElement& xml) const
  65760. {
  65761. jassertfalse; //xxx TODO
  65762. }
  65763. END_JUCE_NAMESPACE
  65764. /********* End of inlined file: juce_DrawableText.cpp *********/
  65765. /********* Start of inlined file: juce_SVGParser.cpp *********/
  65766. BEGIN_JUCE_NAMESPACE
  65767. class SVGState
  65768. {
  65769. public:
  65770. SVGState (const XmlElement* const topLevel)
  65771. : topLevelXml (topLevel),
  65772. x (0), y (0),
  65773. width (512), height (512),
  65774. viewBoxW (0), viewBoxH (0)
  65775. {
  65776. }
  65777. ~SVGState()
  65778. {
  65779. }
  65780. Drawable* parseSVGElement (const XmlElement& xml)
  65781. {
  65782. if (! xml.hasTagName (T("svg")))
  65783. return 0;
  65784. DrawableComposite* const drawable = new DrawableComposite();
  65785. drawable->setName (xml.getStringAttribute (T("id")));
  65786. SVGState newState (*this);
  65787. if (xml.hasAttribute (T("transform")))
  65788. newState.addTransform (xml);
  65789. newState.x = getCoordLength (xml.getStringAttribute (T("x"), String (newState.x)), viewBoxW);
  65790. newState.y = getCoordLength (xml.getStringAttribute (T("y"), String (newState.y)), viewBoxH);
  65791. newState.width = getCoordLength (xml.getStringAttribute (T("width"), String (newState.width)), viewBoxW);
  65792. newState.height = getCoordLength (xml.getStringAttribute (T("height"), String (newState.height)), viewBoxH);
  65793. if (xml.hasAttribute (T("viewBox")))
  65794. {
  65795. const String viewParams (xml.getStringAttribute (T("viewBox")));
  65796. int i = 0;
  65797. float vx, vy, vw, vh;
  65798. if (parseCoords (viewParams, vx, vy, i, true)
  65799. && parseCoords (viewParams, vw, vh, i, true)
  65800. && vw > 0
  65801. && vh > 0)
  65802. {
  65803. newState.viewBoxW = vw;
  65804. newState.viewBoxH = vh;
  65805. int placementFlags = 0;
  65806. const String aspect (xml.getStringAttribute (T("preserveAspectRatio")));
  65807. if (aspect.containsIgnoreCase (T("none")))
  65808. {
  65809. placementFlags = RectanglePlacement::stretchToFit;
  65810. }
  65811. else
  65812. {
  65813. if (aspect.containsIgnoreCase (T("slice")))
  65814. placementFlags |= RectanglePlacement::fillDestination;
  65815. if (aspect.containsIgnoreCase (T("xMin")))
  65816. placementFlags |= RectanglePlacement::xLeft;
  65817. else if (aspect.containsIgnoreCase (T("xMax")))
  65818. placementFlags |= RectanglePlacement::xRight;
  65819. else
  65820. placementFlags |= RectanglePlacement::xMid;
  65821. if (aspect.containsIgnoreCase (T("yMin")))
  65822. placementFlags |= RectanglePlacement::yTop;
  65823. else if (aspect.containsIgnoreCase (T("yMax")))
  65824. placementFlags |= RectanglePlacement::yBottom;
  65825. else
  65826. placementFlags |= RectanglePlacement::yMid;
  65827. }
  65828. const RectanglePlacement placement (placementFlags);
  65829. newState.transform
  65830. = placement.getTransformToFit (vx, vy, vw, vh,
  65831. 0.0f, 0.0f, newState.width, newState.height)
  65832. .followedBy (newState.transform);
  65833. }
  65834. }
  65835. else
  65836. {
  65837. if (viewBoxW == 0)
  65838. newState.viewBoxW = newState.width;
  65839. if (viewBoxH == 0)
  65840. newState.viewBoxH = newState.height;
  65841. }
  65842. newState.parseSubElements (xml, drawable);
  65843. return drawable;
  65844. }
  65845. private:
  65846. const XmlElement* const topLevelXml;
  65847. float x, y, width, height, viewBoxW, viewBoxH;
  65848. AffineTransform transform;
  65849. String cssStyleText;
  65850. void parseSubElements (const XmlElement& xml, DrawableComposite* const parentDrawable)
  65851. {
  65852. forEachXmlChildElement (xml, e)
  65853. {
  65854. Drawable* d = 0;
  65855. if (e->hasTagName (T("g")))
  65856. d = parseGroupElement (*e);
  65857. else if (e->hasTagName (T("svg")))
  65858. d = parseSVGElement (*e);
  65859. else if (e->hasTagName (T("path")))
  65860. d = parsePath (*e);
  65861. else if (e->hasTagName (T("rect")))
  65862. d = parseRect (*e);
  65863. else if (e->hasTagName (T("circle")))
  65864. d = parseCircle (*e);
  65865. else if (e->hasTagName (T("ellipse")))
  65866. d = parseEllipse (*e);
  65867. else if (e->hasTagName (T("line")))
  65868. d = parseLine (*e);
  65869. else if (e->hasTagName (T("polyline")))
  65870. d = parsePolygon (*e, true);
  65871. else if (e->hasTagName (T("polygon")))
  65872. d = parsePolygon (*e, false);
  65873. else if (e->hasTagName (T("text")))
  65874. d = parseText (*e);
  65875. else if (e->hasTagName (T("switch")))
  65876. d = parseSwitch (*e);
  65877. else if (e->hasTagName (T("style")))
  65878. parseCSSStyle (*e);
  65879. parentDrawable->insertDrawable (d);
  65880. }
  65881. }
  65882. DrawableComposite* parseSwitch (const XmlElement& xml)
  65883. {
  65884. const XmlElement* const group = xml.getChildByName (T("g"));
  65885. if (group != 0)
  65886. return parseGroupElement (*group);
  65887. return 0;
  65888. }
  65889. DrawableComposite* parseGroupElement (const XmlElement& xml)
  65890. {
  65891. DrawableComposite* const drawable = new DrawableComposite();
  65892. drawable->setName (xml.getStringAttribute (T("id")));
  65893. if (xml.hasAttribute (T("transform")))
  65894. {
  65895. SVGState newState (*this);
  65896. newState.addTransform (xml);
  65897. newState.parseSubElements (xml, drawable);
  65898. }
  65899. else
  65900. {
  65901. parseSubElements (xml, drawable);
  65902. }
  65903. return drawable;
  65904. }
  65905. Drawable* parsePath (const XmlElement& xml) const
  65906. {
  65907. const String d (xml.getStringAttribute (T("d")).trimStart());
  65908. Path path;
  65909. if (getStyleAttribute (&xml, T("fill-rule")).trim().equalsIgnoreCase (T("evenodd")))
  65910. path.setUsingNonZeroWinding (false);
  65911. int index = 0;
  65912. float lastX = 0, lastY = 0;
  65913. float lastX2 = 0, lastY2 = 0;
  65914. tchar lastCommandChar = 0;
  65915. bool carryOn = true;
  65916. const String validCommandChars (T("MmLlHhVvCcSsQqTtAaZz"));
  65917. for (;;)
  65918. {
  65919. float x, y, x2, y2, x3, y3;
  65920. const bool isRelative = (d[index] >= 'a' && d[index] <= 'z');
  65921. if (validCommandChars.containsChar (d[index]))
  65922. lastCommandChar = d [index++];
  65923. switch (lastCommandChar)
  65924. {
  65925. case T('M'):
  65926. case T('m'):
  65927. case T('L'):
  65928. case T('l'):
  65929. if (parseCoords (d, x, y, index, false))
  65930. {
  65931. if (isRelative)
  65932. {
  65933. x += lastX;
  65934. y += lastY;
  65935. }
  65936. if (lastCommandChar == T('M') || lastCommandChar == T('m'))
  65937. path.startNewSubPath (x, y);
  65938. else
  65939. path.lineTo (x, y);
  65940. lastX2 = lastX;
  65941. lastY2 = lastY;
  65942. lastX = x;
  65943. lastY = y;
  65944. }
  65945. else
  65946. {
  65947. ++index;
  65948. }
  65949. break;
  65950. case T('H'):
  65951. case T('h'):
  65952. if (parseCoord (d, x, index, false, true))
  65953. {
  65954. if (isRelative)
  65955. x += lastX;
  65956. path.lineTo (x, lastY);
  65957. lastX2 = lastX;
  65958. lastX = x;
  65959. }
  65960. else
  65961. {
  65962. ++index;
  65963. }
  65964. break;
  65965. case T('V'):
  65966. case T('v'):
  65967. if (parseCoord (d, y, index, false, false))
  65968. {
  65969. if (isRelative)
  65970. y += lastY;
  65971. path.lineTo (lastX, y);
  65972. lastY2 = lastY;
  65973. lastY = y;
  65974. }
  65975. else
  65976. {
  65977. ++index;
  65978. }
  65979. break;
  65980. case T('C'):
  65981. case T('c'):
  65982. if (parseCoords (d, x, y, index, false)
  65983. && parseCoords (d, x2, y2, index, false)
  65984. && parseCoords (d, x3, y3, index, false))
  65985. {
  65986. if (isRelative)
  65987. {
  65988. x += lastX;
  65989. y += lastY;
  65990. x2 += lastX;
  65991. y2 += lastY;
  65992. x3 += lastX;
  65993. y3 += lastY;
  65994. }
  65995. path.cubicTo (x, y, x2, y2, x3, y3);
  65996. lastX2 = x2;
  65997. lastY2 = y2;
  65998. lastX = x3;
  65999. lastY = y3;
  66000. }
  66001. else
  66002. {
  66003. ++index;
  66004. }
  66005. break;
  66006. case T('S'):
  66007. case T('s'):
  66008. if (parseCoords (d, x, y, index, false)
  66009. && parseCoords (d, x3, y3, index, false))
  66010. {
  66011. if (isRelative)
  66012. {
  66013. x += lastX;
  66014. y += lastY;
  66015. x3 += lastX;
  66016. y3 += lastY;
  66017. }
  66018. x2 = lastX + (lastX - lastX2);
  66019. y2 = lastY + (lastY - lastY2);
  66020. path.cubicTo (x2, y2, x, y, x3, y3);
  66021. lastX2 = x;
  66022. lastY2 = y;
  66023. lastX = x3;
  66024. lastY = y3;
  66025. }
  66026. else
  66027. {
  66028. ++index;
  66029. }
  66030. break;
  66031. case T('Q'):
  66032. case T('q'):
  66033. if (parseCoords (d, x, y, index, false)
  66034. && parseCoords (d, x2, y2, index, false))
  66035. {
  66036. if (isRelative)
  66037. {
  66038. x += lastX;
  66039. y += lastY;
  66040. x2 += lastX;
  66041. y2 += lastY;
  66042. }
  66043. path.quadraticTo (x, y, x2, y2);
  66044. lastX2 = x;
  66045. lastY2 = y;
  66046. lastX = x2;
  66047. lastY = y2;
  66048. }
  66049. else
  66050. {
  66051. ++index;
  66052. }
  66053. break;
  66054. case T('T'):
  66055. case T('t'):
  66056. if (parseCoords (d, x, y, index, false))
  66057. {
  66058. if (isRelative)
  66059. {
  66060. x += lastX;
  66061. y += lastY;
  66062. }
  66063. x2 = lastX + (lastX - lastX2);
  66064. y2 = lastY + (lastY - lastY2);
  66065. path.quadraticTo (x2, y2, x, y);
  66066. lastX2 = x2;
  66067. lastY2 = y2;
  66068. lastX = x;
  66069. lastY = y;
  66070. }
  66071. else
  66072. {
  66073. ++index;
  66074. }
  66075. break;
  66076. case T('A'):
  66077. case T('a'):
  66078. if (parseCoords (d, x, y, index, false))
  66079. {
  66080. String num;
  66081. if (parseNextNumber (d, num, index, false))
  66082. {
  66083. const float angle = num.getFloatValue() * (180.0f / float_Pi);
  66084. if (parseNextNumber (d, num, index, false))
  66085. {
  66086. const bool largeArc = num.getIntValue() != 0;
  66087. if (parseNextNumber (d, num, index, false))
  66088. {
  66089. const bool sweep = num.getIntValue() != 0;
  66090. if (parseCoords (d, x2, y2, index, false))
  66091. {
  66092. if (isRelative)
  66093. {
  66094. x2 += lastX;
  66095. y2 += lastY;
  66096. }
  66097. if (lastX != x2 || lastY != y2)
  66098. {
  66099. double centreX, centreY, startAngle, deltaAngle;
  66100. double rx = x, ry = y;
  66101. endpointToCentreParameters (lastX, lastY, x2, y2,
  66102. angle, largeArc, sweep,
  66103. rx, ry, centreX, centreY,
  66104. startAngle, deltaAngle);
  66105. path.addCentredArc ((float) centreX, (float) centreY,
  66106. (float) rx, (float) ry,
  66107. angle, (float) startAngle, (float) (startAngle + deltaAngle),
  66108. false);
  66109. path.lineTo (x2, y2);
  66110. }
  66111. lastX2 = lastX;
  66112. lastY2 = lastY;
  66113. lastX = x2;
  66114. lastY = y2;
  66115. }
  66116. }
  66117. }
  66118. }
  66119. }
  66120. else
  66121. {
  66122. ++index;
  66123. }
  66124. break;
  66125. case T('Z'):
  66126. case T('z'):
  66127. path.closeSubPath();
  66128. while (CharacterFunctions::isWhitespace (d [index]))
  66129. ++index;
  66130. break;
  66131. default:
  66132. carryOn = false;
  66133. break;
  66134. }
  66135. if (! carryOn)
  66136. break;
  66137. }
  66138. return parseShape (xml, path);
  66139. }
  66140. Drawable* parseRect (const XmlElement& xml) const
  66141. {
  66142. Path rect;
  66143. const bool hasRX = xml.hasAttribute (T("rx"));
  66144. const bool hasRY = xml.hasAttribute (T("ry"));
  66145. if (hasRX || hasRY)
  66146. {
  66147. float rx = getCoordLength (xml.getStringAttribute (T("rx")), viewBoxW);
  66148. float ry = getCoordLength (xml.getStringAttribute (T("ry")), viewBoxH);
  66149. if (! hasRX)
  66150. rx = ry;
  66151. else if (! hasRY)
  66152. ry = rx;
  66153. rect.addRoundedRectangle (getCoordLength (xml.getStringAttribute (T("x")), viewBoxW),
  66154. getCoordLength (xml.getStringAttribute (T("y")), viewBoxH),
  66155. getCoordLength (xml.getStringAttribute (T("width")), viewBoxW),
  66156. getCoordLength (xml.getStringAttribute (T("height")), viewBoxH),
  66157. rx, ry);
  66158. }
  66159. else
  66160. {
  66161. rect.addRectangle (getCoordLength (xml.getStringAttribute (T("x")), viewBoxW),
  66162. getCoordLength (xml.getStringAttribute (T("y")), viewBoxH),
  66163. getCoordLength (xml.getStringAttribute (T("width")), viewBoxW),
  66164. getCoordLength (xml.getStringAttribute (T("height")), viewBoxH));
  66165. }
  66166. return parseShape (xml, rect);
  66167. }
  66168. Drawable* parseCircle (const XmlElement& xml) const
  66169. {
  66170. Path circle;
  66171. const float cx = getCoordLength (xml.getStringAttribute (T("cx")), viewBoxW);
  66172. const float cy = getCoordLength (xml.getStringAttribute (T("cy")), viewBoxH);
  66173. const float radius = getCoordLength (xml.getStringAttribute (T("r")), viewBoxW);
  66174. circle.addEllipse (cx - radius, cy - radius, radius * 2.0f, radius * 2.0f);
  66175. return parseShape (xml, circle);
  66176. }
  66177. Drawable* parseEllipse (const XmlElement& xml) const
  66178. {
  66179. Path ellipse;
  66180. const float cx = getCoordLength (xml.getStringAttribute (T("cx")), viewBoxW);
  66181. const float cy = getCoordLength (xml.getStringAttribute (T("cy")), viewBoxH);
  66182. const float radiusX = getCoordLength (xml.getStringAttribute (T("rx")), viewBoxW);
  66183. const float radiusY = getCoordLength (xml.getStringAttribute (T("ry")), viewBoxH);
  66184. ellipse.addEllipse (cx - radiusX, cy - radiusY, radiusX * 2.0f, radiusY * 2.0f);
  66185. return parseShape (xml, ellipse);
  66186. }
  66187. Drawable* parseLine (const XmlElement& xml) const
  66188. {
  66189. Path line;
  66190. const float x1 = getCoordLength (xml.getStringAttribute (T("x1")), viewBoxW);
  66191. const float y1 = getCoordLength (xml.getStringAttribute (T("y1")), viewBoxH);
  66192. const float x2 = getCoordLength (xml.getStringAttribute (T("x2")), viewBoxW);
  66193. const float y2 = getCoordLength (xml.getStringAttribute (T("y2")), viewBoxH);
  66194. line.startNewSubPath (x1, y1);
  66195. line.lineTo (x2, y2);
  66196. return parseShape (xml, line);
  66197. }
  66198. Drawable* parsePolygon (const XmlElement& xml, const bool isPolyline) const
  66199. {
  66200. const String points (xml.getStringAttribute (T("points")));
  66201. Path path;
  66202. int index = 0;
  66203. float x, y;
  66204. if (parseCoords (points, x, y, index, true))
  66205. {
  66206. float firstX = x;
  66207. float firstY = y;
  66208. float lastX = 0, lastY = 0;
  66209. path.startNewSubPath (x, y);
  66210. while (parseCoords (points, x, y, index, true))
  66211. {
  66212. lastX = x;
  66213. lastY = y;
  66214. path.lineTo (x, y);
  66215. }
  66216. if ((! isPolyline) || (firstX == lastX && firstY == lastY))
  66217. path.closeSubPath();
  66218. }
  66219. return parseShape (xml, path);
  66220. }
  66221. Drawable* parseShape (const XmlElement& xml, Path& path,
  66222. const bool parseTransform = true) const
  66223. {
  66224. if (parseTransform && xml.hasAttribute (T("transform")))
  66225. {
  66226. SVGState newState (*this);
  66227. newState.addTransform (xml);
  66228. return newState.parseShape (xml, path, false);
  66229. }
  66230. DrawablePath* dp = new DrawablePath();
  66231. dp->setName (xml.getStringAttribute (T("id")));
  66232. dp->setSolidFill (Colours::transparentBlack);
  66233. path.applyTransform (transform);
  66234. dp->setPath (path);
  66235. Path::Iterator iter (path);
  66236. bool containsClosedSubPath = false;
  66237. while (iter.next())
  66238. {
  66239. if (iter.elementType == Path::Iterator::closePath)
  66240. {
  66241. containsClosedSubPath = true;
  66242. break;
  66243. }
  66244. }
  66245. Brush* const fillBrush
  66246. = getBrushForFill (path,
  66247. getStyleAttribute (&xml, T("fill")),
  66248. getStyleAttribute (&xml, T("fill-opacity")),
  66249. getStyleAttribute (&xml, T("opacity")),
  66250. containsClosedSubPath ? Colours::black
  66251. : Colours::transparentBlack);
  66252. if (fillBrush != 0)
  66253. {
  66254. if (! fillBrush->isInvisible())
  66255. {
  66256. fillBrush->applyTransform (transform);
  66257. dp->setFillBrush (*fillBrush);
  66258. }
  66259. delete fillBrush;
  66260. }
  66261. const String strokeType (getStyleAttribute (&xml, T("stroke")));
  66262. if (strokeType.isNotEmpty() && ! strokeType.equalsIgnoreCase (T("none")))
  66263. {
  66264. Brush* const strokeBrush
  66265. = getBrushForFill (path, strokeType,
  66266. getStyleAttribute (&xml, T("stroke-opacity")),
  66267. getStyleAttribute (&xml, T("opacity")),
  66268. Colours::transparentBlack);
  66269. if (strokeBrush != 0)
  66270. {
  66271. const PathStrokeType stroke (getStrokeFor (&xml));
  66272. if (! strokeBrush->isInvisible())
  66273. {
  66274. strokeBrush->applyTransform (transform);
  66275. dp->setOutline (stroke, *strokeBrush);
  66276. }
  66277. delete strokeBrush;
  66278. }
  66279. }
  66280. return dp;
  66281. }
  66282. const XmlElement* findLinkedElement (const XmlElement* e) const
  66283. {
  66284. const String id (e->getStringAttribute (T("xlink:href")));
  66285. if (! id.startsWithChar (T('#')))
  66286. return 0;
  66287. return findElementForId (topLevelXml, id.substring (1));
  66288. }
  66289. void addGradientStopsIn (ColourGradient& cg, const XmlElement* const fillXml) const
  66290. {
  66291. if (fillXml == 0)
  66292. return;
  66293. forEachXmlChildElementWithTagName (*fillXml, e, T("stop"))
  66294. {
  66295. int index = 0;
  66296. Colour col (parseColour (getStyleAttribute (e, T("stop-color")), index, Colours::black));
  66297. const String opacity (getStyleAttribute (e, T("stop-opacity"), T("1")));
  66298. col = col.withMultipliedAlpha (jlimit (0.0f, 1.0f, opacity.getFloatValue()));
  66299. double offset = e->getDoubleAttribute (T("offset"));
  66300. if (e->getStringAttribute (T("offset")).containsChar (T('%')))
  66301. offset *= 0.01;
  66302. cg.addColour (jlimit (0.0, 1.0, offset), col);
  66303. }
  66304. }
  66305. Brush* getBrushForFill (const Path& path,
  66306. const String& fill,
  66307. const String& fillOpacity,
  66308. const String& overallOpacity,
  66309. const Colour& defaultColour) const
  66310. {
  66311. float opacity = 1.0f;
  66312. if (overallOpacity.isNotEmpty())
  66313. opacity = jlimit (0.0f, 1.0f, overallOpacity.getFloatValue());
  66314. if (fillOpacity.isNotEmpty())
  66315. opacity *= (jlimit (0.0f, 1.0f, fillOpacity.getFloatValue()));
  66316. if (fill.startsWithIgnoreCase (T("url")))
  66317. {
  66318. const String id (fill.fromFirstOccurrenceOf (T("#"), false, false)
  66319. .upToLastOccurrenceOf (T(")"), false, false).trim());
  66320. const XmlElement* const fillXml = findElementForId (topLevelXml, id);
  66321. if (fillXml != 0
  66322. && (fillXml->hasTagName (T("linearGradient"))
  66323. || fillXml->hasTagName (T("radialGradient"))))
  66324. {
  66325. const XmlElement* inheritedFrom = findLinkedElement (fillXml);
  66326. ColourGradient cg;
  66327. addGradientStopsIn (cg, inheritedFrom);
  66328. addGradientStopsIn (cg, fillXml);
  66329. if (cg.getNumColours() > 0)
  66330. {
  66331. cg.addColour (0.0, cg.getColour (0));
  66332. cg.addColour (1.0, cg.getColour (cg.getNumColours() - 1));
  66333. }
  66334. else
  66335. {
  66336. cg.addColour (0.0, Colours::black);
  66337. cg.addColour (1.0, Colours::black);
  66338. }
  66339. if (overallOpacity.isNotEmpty())
  66340. cg.multiplyOpacity (overallOpacity.getFloatValue());
  66341. jassert (cg.getNumColours() > 0);
  66342. cg.isRadial = fillXml->hasTagName (T("radialGradient"));
  66343. cg.transform = parseTransform (fillXml->getStringAttribute (T("gradientTransform")));
  66344. float width = viewBoxW;
  66345. float height = viewBoxH;
  66346. float dx = 0.0;
  66347. float dy = 0.0;
  66348. const bool userSpace = fillXml->getStringAttribute (T("gradientUnits")).equalsIgnoreCase (T("userSpaceOnUse"));
  66349. if (! userSpace)
  66350. path.getBounds (dx, dy, width, height);
  66351. if (cg.isRadial)
  66352. {
  66353. cg.x1 = dx + getCoordLength (fillXml->getStringAttribute (T("cx"), T("50%")), width);
  66354. cg.y1 = dy + getCoordLength (fillXml->getStringAttribute (T("cy"), T("50%")), height);
  66355. const float radius = getCoordLength (fillXml->getStringAttribute (T("r"), T("50%")), width);
  66356. cg.x2 = cg.x1 + radius;
  66357. cg.y2 = cg.y1;
  66358. //xxx (the fx, fy focal point isn't handled properly here..)
  66359. }
  66360. else
  66361. {
  66362. cg.x1 = dx + getCoordLength (fillXml->getStringAttribute (T("x1"), T("0%")), width);
  66363. cg.y1 = dy + getCoordLength (fillXml->getStringAttribute (T("y1"), T("0%")), height);
  66364. cg.x2 = dx + getCoordLength (fillXml->getStringAttribute (T("x2"), T("100%")), width);
  66365. cg.y2 = dy + getCoordLength (fillXml->getStringAttribute (T("y2"), T("0%")), height);
  66366. if (cg.x1 == cg.x2 && cg.y1 == cg.y2)
  66367. return new SolidColourBrush (cg.getColour (cg.getNumColours() - 1));
  66368. }
  66369. return new GradientBrush (cg);
  66370. }
  66371. }
  66372. if (fill.equalsIgnoreCase (T("none")))
  66373. return new SolidColourBrush (Colours::transparentBlack);
  66374. int i = 0;
  66375. Colour colour (parseColour (fill, i, defaultColour));
  66376. colour = colour.withMultipliedAlpha (opacity);
  66377. return new SolidColourBrush (colour);
  66378. }
  66379. const PathStrokeType getStrokeFor (const XmlElement* const xml) const
  66380. {
  66381. const String width (getStyleAttribute (xml, T("stroke-width")));
  66382. const String cap (getStyleAttribute (xml, T("stroke-linecap")));
  66383. const String join (getStyleAttribute (xml, T("stroke-linejoin")));
  66384. //const String mitreLimit (getStyleAttribute (xml, T("stroke-miterlimit")));
  66385. //const String dashArray (getStyleAttribute (xml, T("stroke-dasharray")));
  66386. //const String dashOffset (getStyleAttribute (xml, T("stroke-dashoffset")));
  66387. PathStrokeType::JointStyle joinStyle = PathStrokeType::mitered;
  66388. PathStrokeType::EndCapStyle capStyle = PathStrokeType::butt;
  66389. if (join.equalsIgnoreCase (T("round")))
  66390. joinStyle = PathStrokeType::curved;
  66391. else if (join.equalsIgnoreCase (T("bevel")))
  66392. joinStyle = PathStrokeType::beveled;
  66393. if (cap.equalsIgnoreCase (T("round")))
  66394. capStyle = PathStrokeType::rounded;
  66395. else if (cap.equalsIgnoreCase (T("square")))
  66396. capStyle = PathStrokeType::square;
  66397. float ox = 0.0f, oy = 0.0f;
  66398. transform.transformPoint (ox, oy);
  66399. float x = getCoordLength (width, viewBoxW), y = 0.0f;
  66400. transform.transformPoint (x, y);
  66401. return PathStrokeType (width.isNotEmpty() ? juce_hypotf (x - ox, y - oy) : 1.0f,
  66402. joinStyle, capStyle);
  66403. }
  66404. Drawable* parseText (const XmlElement& xml)
  66405. {
  66406. Array <float> xCoords, yCoords, dxCoords, dyCoords;
  66407. getCoordList (xCoords, getInheritedAttribute (&xml, T("x")), true, true);
  66408. getCoordList (yCoords, getInheritedAttribute (&xml, T("y")), true, false);
  66409. getCoordList (dxCoords, getInheritedAttribute (&xml, T("dx")), true, true);
  66410. getCoordList (dyCoords, getInheritedAttribute (&xml, T("dy")), true, false);
  66411. //xxx not done text yet!
  66412. forEachXmlChildElement (xml, e)
  66413. {
  66414. if (e->isTextElement())
  66415. {
  66416. const String text (e->getText());
  66417. Path path;
  66418. Drawable* s = parseShape (*e, path);
  66419. delete s;
  66420. }
  66421. else if (e->hasTagName (T("tspan")))
  66422. {
  66423. Drawable* s = parseText (*e);
  66424. delete s;
  66425. }
  66426. }
  66427. return 0;
  66428. }
  66429. void addTransform (const XmlElement& xml)
  66430. {
  66431. transform = parseTransform (xml.getStringAttribute (T("transform")))
  66432. .followedBy (transform);
  66433. }
  66434. bool parseCoord (const String& s, float& value, int& index,
  66435. const bool allowUnits, const bool isX) const
  66436. {
  66437. String number;
  66438. if (! parseNextNumber (s, number, index, allowUnits))
  66439. {
  66440. value = 0;
  66441. return false;
  66442. }
  66443. value = getCoordLength (number, isX ? viewBoxW : viewBoxH);
  66444. return true;
  66445. }
  66446. bool parseCoords (const String& s, float& x, float& y,
  66447. int& index, const bool allowUnits) const
  66448. {
  66449. return parseCoord (s, x, index, allowUnits, true)
  66450. && parseCoord (s, y, index, allowUnits, false);
  66451. }
  66452. float getCoordLength (const String& s, const float sizeForProportions) const
  66453. {
  66454. float n = s.getFloatValue();
  66455. const int len = s.length();
  66456. if (len > 2)
  66457. {
  66458. const float dpi = 96.0f;
  66459. const tchar n1 = s [len - 2];
  66460. const tchar n2 = s [len - 1];
  66461. if (n1 == T('i') && n2 == T('n'))
  66462. n *= dpi;
  66463. else if (n1 == T('m') && n2 == T('m'))
  66464. n *= dpi / 25.4f;
  66465. else if (n1 == T('c') && n2 == T('m'))
  66466. n *= dpi / 2.54f;
  66467. else if (n1 == T('p') && n2 == T('c'))
  66468. n *= 15.0f;
  66469. else if (n2 == T('%'))
  66470. n *= 0.01f * sizeForProportions;
  66471. }
  66472. return n;
  66473. }
  66474. void getCoordList (Array <float>& coords, const String& list,
  66475. const bool allowUnits, const bool isX) const
  66476. {
  66477. int index = 0;
  66478. float value;
  66479. while (parseCoord (list, value, index, allowUnits, isX))
  66480. coords.add (value);
  66481. }
  66482. void parseCSSStyle (const XmlElement& xml)
  66483. {
  66484. cssStyleText = xml.getAllSubText() + T("\n") + cssStyleText;
  66485. }
  66486. const String getStyleAttribute (const XmlElement* xml, const String& attributeName,
  66487. const String& defaultValue = String::empty) const
  66488. {
  66489. if (xml->hasAttribute (attributeName))
  66490. return xml->getStringAttribute (attributeName, defaultValue);
  66491. const String styleAtt (xml->getStringAttribute (T("style")));
  66492. if (styleAtt.isNotEmpty())
  66493. {
  66494. const String value (getAttributeFromStyleList (styleAtt, attributeName, String::empty));
  66495. if (value.isNotEmpty())
  66496. return value;
  66497. }
  66498. else if (xml->hasAttribute (T("class")))
  66499. {
  66500. const String className (T(".") + xml->getStringAttribute (T("class")));
  66501. int index = cssStyleText.indexOfIgnoreCase (className + T(" "));
  66502. if (index < 0)
  66503. index = cssStyleText.indexOfIgnoreCase (className + T("{"));
  66504. if (index >= 0)
  66505. {
  66506. const int openBracket = cssStyleText.indexOfChar (index, T('{'));
  66507. if (openBracket > index)
  66508. {
  66509. const int closeBracket = cssStyleText.indexOfChar (openBracket, T('}'));
  66510. if (closeBracket > openBracket)
  66511. {
  66512. const String value (getAttributeFromStyleList (cssStyleText.substring (openBracket + 1, closeBracket), attributeName, defaultValue));
  66513. if (value.isNotEmpty())
  66514. return value;
  66515. }
  66516. }
  66517. }
  66518. }
  66519. xml = const_cast <XmlElement*> (topLevelXml)->findParentElementOf (xml);
  66520. if (xml != 0)
  66521. return getStyleAttribute (xml, attributeName, defaultValue);
  66522. return defaultValue;
  66523. }
  66524. const String getInheritedAttribute (const XmlElement* xml, const String& attributeName) const
  66525. {
  66526. if (xml->hasAttribute (attributeName))
  66527. return xml->getStringAttribute (attributeName);
  66528. xml = const_cast <XmlElement*> (topLevelXml)->findParentElementOf (xml);
  66529. if (xml != 0)
  66530. return getInheritedAttribute (xml, attributeName);
  66531. return String::empty;
  66532. }
  66533. static bool isIdentifierChar (const tchar c)
  66534. {
  66535. return CharacterFunctions::isLetter (c) || c == T('-');
  66536. }
  66537. static const String getAttributeFromStyleList (const String& list, const String& attributeName, const String& defaultValue)
  66538. {
  66539. int i = 0;
  66540. for (;;)
  66541. {
  66542. i = list.indexOf (i, attributeName);
  66543. if (i < 0)
  66544. break;
  66545. if ((i == 0 || (i > 0 && ! isIdentifierChar (list [i - 1])))
  66546. && ! isIdentifierChar (list [i + attributeName.length()]))
  66547. {
  66548. i = list.indexOfChar (i, T(':'));
  66549. if (i < 0)
  66550. break;
  66551. int end = list.indexOfChar (i, T(';'));
  66552. if (end < 0)
  66553. end = 0x7ffff;
  66554. return list.substring (i + 1, end).trim();
  66555. }
  66556. ++i;
  66557. }
  66558. return defaultValue;
  66559. }
  66560. static bool parseNextNumber (const String& source, String& value, int& index, const bool allowUnits)
  66561. {
  66562. const tchar* const s = (const tchar*) source;
  66563. while (CharacterFunctions::isWhitespace (s[index]) || s[index] == T(','))
  66564. ++index;
  66565. int start = index;
  66566. if (CharacterFunctions::isDigit (s[index]) || s[index] == T('.') || s[index] == T('-'))
  66567. ++index;
  66568. while (CharacterFunctions::isDigit (s[index]) || s[index] == T('.'))
  66569. ++index;
  66570. if ((s[index] == T('e') || s[index] == T('E'))
  66571. && (CharacterFunctions::isDigit (s[index + 1])
  66572. || s[index + 1] == T('-')
  66573. || s[index + 1] == T('+')))
  66574. {
  66575. index += 2;
  66576. while (CharacterFunctions::isDigit (s[index]))
  66577. ++index;
  66578. }
  66579. if (allowUnits)
  66580. {
  66581. while (CharacterFunctions::isLetter (s[index]))
  66582. ++index;
  66583. }
  66584. if (index == start)
  66585. return false;
  66586. value = String (s + start, index - start);
  66587. while (CharacterFunctions::isWhitespace (s[index]) || s[index] == T(','))
  66588. ++index;
  66589. return true;
  66590. }
  66591. static const Colour parseColour (const String& s, int& index, const Colour& defaultColour)
  66592. {
  66593. if (s [index] == T('#'))
  66594. {
  66595. uint32 hex [6];
  66596. zeromem (hex, sizeof (hex));
  66597. int numChars = 0;
  66598. for (int i = 6; --i >= 0;)
  66599. {
  66600. const int hexValue = CharacterFunctions::getHexDigitValue (s [++index]);
  66601. if (hexValue >= 0)
  66602. hex [numChars++] = hexValue;
  66603. else
  66604. break;
  66605. }
  66606. if (numChars <= 3)
  66607. return Colour ((uint8) (hex [0] * 0x11),
  66608. (uint8) (hex [1] * 0x11),
  66609. (uint8) (hex [2] * 0x11));
  66610. else
  66611. return Colour ((uint8) ((hex [0] << 4) + hex [1]),
  66612. (uint8) ((hex [2] << 4) + hex [3]),
  66613. (uint8) ((hex [4] << 4) + hex [5]));
  66614. }
  66615. else if (s [index] == T('r')
  66616. && s [index + 1] == T('g')
  66617. && s [index + 2] == T('b'))
  66618. {
  66619. const int openBracket = s.indexOfChar (index, T('('));
  66620. const int closeBracket = s.indexOfChar (openBracket, T(')'));
  66621. if (openBracket >= 3 && closeBracket > openBracket)
  66622. {
  66623. index = closeBracket;
  66624. StringArray tokens;
  66625. tokens.addTokens (s.substring (openBracket + 1, closeBracket), T(","), T(""));
  66626. tokens.trim();
  66627. tokens.removeEmptyStrings();
  66628. if (tokens[0].containsChar (T('%')))
  66629. return Colour ((uint8) roundDoubleToInt (2.55 * tokens[0].getDoubleValue()),
  66630. (uint8) roundDoubleToInt (2.55 * tokens[1].getDoubleValue()),
  66631. (uint8) roundDoubleToInt (2.55 * tokens[2].getDoubleValue()));
  66632. else
  66633. return Colour ((uint8) tokens[0].getIntValue(),
  66634. (uint8) tokens[1].getIntValue(),
  66635. (uint8) tokens[2].getIntValue());
  66636. }
  66637. }
  66638. return Colours::findColourForName (s, defaultColour);
  66639. }
  66640. static const AffineTransform parseTransform (String t)
  66641. {
  66642. AffineTransform result;
  66643. while (t.isNotEmpty())
  66644. {
  66645. StringArray tokens;
  66646. tokens.addTokens (t.fromFirstOccurrenceOf (T("("), false, false)
  66647. .upToFirstOccurrenceOf (T(")"), false, false),
  66648. T(", "), 0);
  66649. tokens.removeEmptyStrings (true);
  66650. float numbers [6];
  66651. for (int i = 0; i < 6; ++i)
  66652. numbers[i] = tokens[i].getFloatValue();
  66653. AffineTransform trans;
  66654. if (t.startsWithIgnoreCase (T("matrix")))
  66655. {
  66656. trans = AffineTransform (numbers[0], numbers[2], numbers[4],
  66657. numbers[1], numbers[3], numbers[5]);
  66658. }
  66659. else if (t.startsWithIgnoreCase (T("translate")))
  66660. {
  66661. trans = trans.translated (numbers[0], numbers[1]);
  66662. }
  66663. else if (t.startsWithIgnoreCase (T("scale")))
  66664. {
  66665. if (tokens.size() == 1)
  66666. trans = trans.scaled (numbers[0], numbers[0]);
  66667. else
  66668. trans = trans.scaled (numbers[0], numbers[1]);
  66669. }
  66670. else if (t.startsWithIgnoreCase (T("rotate")))
  66671. {
  66672. if (tokens.size() != 3)
  66673. trans = trans.rotated (numbers[0] / (180.0f / float_Pi));
  66674. else
  66675. trans = trans.rotated (numbers[0] / (180.0f / float_Pi),
  66676. numbers[1], numbers[2]);
  66677. }
  66678. else if (t.startsWithIgnoreCase (T("skewX")))
  66679. {
  66680. trans = AffineTransform (1.0f, tanf (numbers[0] * (float_Pi / 180.0f)), 0.0f,
  66681. 0.0f, 1.0f, 0.0f);
  66682. }
  66683. else if (t.startsWithIgnoreCase (T("skewY")))
  66684. {
  66685. trans = AffineTransform (1.0f, 0.0f, 0.0f,
  66686. tanf (numbers[0] * (float_Pi / 180.0f)), 1.0f, 0.0f);
  66687. }
  66688. result = trans.followedBy (result);
  66689. t = t.fromFirstOccurrenceOf (T(")"), false, false).trimStart();
  66690. }
  66691. return result;
  66692. }
  66693. static void endpointToCentreParameters (const double x1, const double y1,
  66694. const double x2, const double y2,
  66695. const double angle,
  66696. const bool largeArc, const bool sweep,
  66697. double& rx, double& ry,
  66698. double& centreX, double& centreY,
  66699. double& startAngle, double& deltaAngle)
  66700. {
  66701. const double midX = (x1 - x2) * 0.5;
  66702. const double midY = (y1 - y2) * 0.5;
  66703. const double cosAngle = cos (angle);
  66704. const double sinAngle = sin (angle);
  66705. const double xp = cosAngle * midX + sinAngle * midY;
  66706. const double yp = cosAngle * midY - sinAngle * midX;
  66707. const double xp2 = xp * xp;
  66708. const double yp2 = yp * yp;
  66709. double rx2 = rx * rx;
  66710. double ry2 = ry * ry;
  66711. const double s = (xp2 / rx2) + (yp2 / ry2);
  66712. double c;
  66713. if (s <= 1.0)
  66714. {
  66715. c = sqrt (jmax (0.0, ((rx2 * ry2) - (rx2 * yp2) - (ry2 * xp2))
  66716. / (( rx2 * yp2) + (ry2 * xp2))));
  66717. if (largeArc == sweep)
  66718. c = -c;
  66719. }
  66720. else
  66721. {
  66722. const double s2 = sqrt (s);
  66723. rx *= s2;
  66724. ry *= s2;
  66725. rx2 = rx * rx;
  66726. ry2 = ry * ry;
  66727. c = 0;
  66728. }
  66729. const double cpx = ((rx * yp) / ry) * c;
  66730. const double cpy = ((-ry * xp) / rx) * c;
  66731. centreX = ((x1 + x2) * 0.5) + (cosAngle * cpx) - (sinAngle * cpy);
  66732. centreY = ((y1 + y2) * 0.5) + (sinAngle * cpx) + (cosAngle * cpy);
  66733. const double ux = (xp - cpx) / rx;
  66734. const double uy = (yp - cpy) / ry;
  66735. const double vx = (-xp - cpx) / rx;
  66736. const double vy = (-yp - cpy) / ry;
  66737. const double length = juce_hypot (ux, uy);
  66738. startAngle = acos (jlimit (-1.0, 1.0, ux / length));
  66739. if (uy < 0)
  66740. startAngle = -startAngle;
  66741. startAngle += double_Pi * 0.5;
  66742. deltaAngle = acos (jlimit (-1.0, 1.0, ((ux * vx) + (uy * vy))
  66743. / (length * juce_hypot (vx, vy))));
  66744. if ((ux * vy) - (uy * vx) < 0)
  66745. deltaAngle = -deltaAngle;
  66746. if (sweep)
  66747. {
  66748. if (deltaAngle < 0)
  66749. deltaAngle += double_Pi * 2.0;
  66750. }
  66751. else
  66752. {
  66753. if (deltaAngle > 0)
  66754. deltaAngle -= double_Pi * 2.0;
  66755. }
  66756. deltaAngle = fmod (deltaAngle, double_Pi * 2.0);
  66757. }
  66758. static const XmlElement* findElementForId (const XmlElement* const parent, const String& id)
  66759. {
  66760. forEachXmlChildElement (*parent, e)
  66761. {
  66762. if (e->compareAttribute (T("id"), id))
  66763. return e;
  66764. const XmlElement* const found = findElementForId (e, id);
  66765. if (found != 0)
  66766. return found;
  66767. }
  66768. return 0;
  66769. }
  66770. const SVGState& operator= (const SVGState&);
  66771. };
  66772. Drawable* Drawable::createFromSVG (const XmlElement& svgDocument)
  66773. {
  66774. SVGState state (&svgDocument);
  66775. return state.parseSVGElement (svgDocument);
  66776. }
  66777. END_JUCE_NAMESPACE
  66778. /********* End of inlined file: juce_SVGParser.cpp *********/
  66779. /********* Start of inlined file: juce_DropShadowEffect.cpp *********/
  66780. BEGIN_JUCE_NAMESPACE
  66781. #if JUCE_MSVC
  66782. #pragma optimize ("t", on) // try to avoid slowing everything down in debug builds
  66783. #endif
  66784. DropShadowEffect::DropShadowEffect()
  66785. : offsetX (0),
  66786. offsetY (0),
  66787. radius (4),
  66788. opacity (0.6f)
  66789. {
  66790. }
  66791. DropShadowEffect::~DropShadowEffect()
  66792. {
  66793. }
  66794. void DropShadowEffect::setShadowProperties (const float newRadius,
  66795. const float newOpacity,
  66796. const int newShadowOffsetX,
  66797. const int newShadowOffsetY)
  66798. {
  66799. radius = jmax (1.1f, newRadius);
  66800. offsetX = newShadowOffsetX;
  66801. offsetY = newShadowOffsetY;
  66802. opacity = newOpacity;
  66803. }
  66804. void DropShadowEffect::applyEffect (Image& image, Graphics& g)
  66805. {
  66806. const int w = image.getWidth();
  66807. const int h = image.getHeight();
  66808. int lineStride, pixelStride;
  66809. const PixelARGB* srcPixels = (const PixelARGB*) image.lockPixelDataReadOnly (0, 0, image.getWidth(), image.getHeight(), lineStride, pixelStride);
  66810. Image shadowImage (Image::SingleChannel, w, h, false);
  66811. int destStride, destPixelStride;
  66812. uint8* const shadowChannel = (uint8*) shadowImage.lockPixelDataReadWrite (0, 0, w, h, destStride, destPixelStride);
  66813. const int filter = roundFloatToInt (63.0f / radius);
  66814. const int radiusMinus1 = roundFloatToInt ((radius - 1.0f) * 63.0f);
  66815. for (int x = w; --x >= 0;)
  66816. {
  66817. int shadowAlpha = 0;
  66818. const PixelARGB* src = srcPixels + x;
  66819. uint8* shadowPix = shadowChannel + x;
  66820. for (int y = h; --y >= 0;)
  66821. {
  66822. shadowAlpha = ((shadowAlpha * radiusMinus1 + (src->getAlpha() << 6)) * filter) >> 12;
  66823. *shadowPix = (uint8) shadowAlpha;
  66824. src = (const PixelARGB*) (((const uint8*) src) + lineStride);
  66825. shadowPix += destStride;
  66826. }
  66827. }
  66828. for (int y = h; --y >= 0;)
  66829. {
  66830. int shadowAlpha = 0;
  66831. uint8* shadowPix = shadowChannel + y * destStride;
  66832. for (int x = w; --x >= 0;)
  66833. {
  66834. shadowAlpha = ((shadowAlpha * radiusMinus1 + (*shadowPix << 6)) * filter) >> 12;
  66835. *shadowPix++ = (uint8) shadowAlpha;
  66836. }
  66837. }
  66838. image.releasePixelDataReadOnly (srcPixels);
  66839. shadowImage.releasePixelDataReadWrite (shadowChannel);
  66840. g.setColour (Colours::black.withAlpha (opacity));
  66841. g.drawImageAt (&shadowImage, offsetX, offsetY, true);
  66842. g.setOpacity (1.0f);
  66843. g.drawImageAt (&image, 0, 0);
  66844. }
  66845. END_JUCE_NAMESPACE
  66846. /********* End of inlined file: juce_DropShadowEffect.cpp *********/
  66847. /********* Start of inlined file: juce_GlowEffect.cpp *********/
  66848. BEGIN_JUCE_NAMESPACE
  66849. GlowEffect::GlowEffect()
  66850. : radius (2.0f),
  66851. colour (Colours::white)
  66852. {
  66853. }
  66854. GlowEffect::~GlowEffect()
  66855. {
  66856. }
  66857. void GlowEffect::setGlowProperties (const float newRadius,
  66858. const Colour& newColour)
  66859. {
  66860. radius = newRadius;
  66861. colour = newColour;
  66862. }
  66863. void GlowEffect::applyEffect (Image& image, Graphics& g)
  66864. {
  66865. const int w = image.getWidth();
  66866. const int h = image.getHeight();
  66867. Image temp (image.getFormat(), w, h, true);
  66868. ImageConvolutionKernel blurKernel (roundFloatToInt (radius * 2.0f));
  66869. blurKernel.createGaussianBlur (radius);
  66870. blurKernel.rescaleAllValues (radius);
  66871. blurKernel.applyToImage (temp, &image, 0, 0, w, h);
  66872. g.setColour (colour);
  66873. g.drawImageAt (&temp, 0, 0, true);
  66874. g.setOpacity (1.0f);
  66875. g.drawImageAt (&image, 0, 0, false);
  66876. }
  66877. END_JUCE_NAMESPACE
  66878. /********* End of inlined file: juce_GlowEffect.cpp *********/
  66879. /********* Start of inlined file: juce_ReduceOpacityEffect.cpp *********/
  66880. BEGIN_JUCE_NAMESPACE
  66881. ReduceOpacityEffect::ReduceOpacityEffect (const float opacity_)
  66882. : opacity (opacity_)
  66883. {
  66884. }
  66885. ReduceOpacityEffect::~ReduceOpacityEffect()
  66886. {
  66887. }
  66888. void ReduceOpacityEffect::setOpacity (const float newOpacity)
  66889. {
  66890. opacity = jlimit (0.0f, 1.0f, newOpacity);
  66891. }
  66892. void ReduceOpacityEffect::applyEffect (Image& image, Graphics& g)
  66893. {
  66894. g.setOpacity (opacity);
  66895. g.drawImageAt (&image, 0, 0);
  66896. }
  66897. END_JUCE_NAMESPACE
  66898. /********* End of inlined file: juce_ReduceOpacityEffect.cpp *********/
  66899. /********* Start of inlined file: juce_Font.cpp *********/
  66900. BEGIN_JUCE_NAMESPACE
  66901. static const float minFontHeight = 0.1f;
  66902. static const float maxFontHeight = 10000.0f;
  66903. static const float defaultFontHeight = 14.0f;
  66904. Font::Font() throw()
  66905. : typefaceName (Typeface::defaultTypefaceNameSans),
  66906. height (defaultFontHeight),
  66907. horizontalScale (1.0f),
  66908. kerning (0),
  66909. ascent (0),
  66910. styleFlags (Font::plain)
  66911. {
  66912. }
  66913. void Font::resetToDefaultState() throw()
  66914. {
  66915. typefaceName = Typeface::defaultTypefaceNameSans;
  66916. height = defaultFontHeight;
  66917. horizontalScale = 1.0f;
  66918. kerning = 0;
  66919. ascent = 0;
  66920. styleFlags = Font::plain;
  66921. typeface = 0;
  66922. }
  66923. Font::Font (const float fontHeight,
  66924. const int styleFlags_) throw()
  66925. : typefaceName (Typeface::defaultTypefaceNameSans),
  66926. height (jlimit (minFontHeight, maxFontHeight, fontHeight)),
  66927. horizontalScale (1.0f),
  66928. kerning (0),
  66929. ascent (0),
  66930. styleFlags (styleFlags_)
  66931. {
  66932. }
  66933. Font::Font (const String& typefaceName_,
  66934. const float fontHeight,
  66935. const int styleFlags_) throw()
  66936. : typefaceName (typefaceName_),
  66937. height (jlimit (minFontHeight, maxFontHeight, fontHeight)),
  66938. horizontalScale (1.0f),
  66939. kerning (0),
  66940. ascent (0),
  66941. styleFlags (styleFlags_)
  66942. {
  66943. }
  66944. Font::Font (const Font& other) throw()
  66945. : typefaceName (other.typefaceName),
  66946. height (other.height),
  66947. horizontalScale (other.horizontalScale),
  66948. kerning (other.kerning),
  66949. ascent (other.ascent),
  66950. styleFlags (other.styleFlags),
  66951. typeface (other.typeface)
  66952. {
  66953. }
  66954. const Font& Font::operator= (const Font& other) throw()
  66955. {
  66956. if (this != &other)
  66957. {
  66958. typefaceName = other.typefaceName;
  66959. height = other.height;
  66960. styleFlags = other.styleFlags;
  66961. horizontalScale = other.horizontalScale;
  66962. kerning = other.kerning;
  66963. ascent = other.ascent;
  66964. typeface = other.typeface;
  66965. }
  66966. return *this;
  66967. }
  66968. Font::~Font() throw()
  66969. {
  66970. }
  66971. Font::Font (const Typeface& face) throw()
  66972. : height (11.0f),
  66973. horizontalScale (1.0f),
  66974. kerning (0),
  66975. ascent (0),
  66976. styleFlags (plain)
  66977. {
  66978. typefaceName = face.getName();
  66979. setBold (face.isBold());
  66980. setItalic (face.isItalic());
  66981. typeface = new Typeface (face);
  66982. }
  66983. bool Font::operator== (const Font& other) const throw()
  66984. {
  66985. return height == other.height
  66986. && horizontalScale == other.horizontalScale
  66987. && kerning == other.kerning
  66988. && styleFlags == other.styleFlags
  66989. && typefaceName == other.typefaceName;
  66990. }
  66991. bool Font::operator!= (const Font& other) const throw()
  66992. {
  66993. return ! operator== (other);
  66994. }
  66995. void Font::setTypefaceName (const String& faceName) throw()
  66996. {
  66997. typefaceName = faceName;
  66998. typeface = 0;
  66999. ascent = 0;
  67000. }
  67001. static String fallbackFont;
  67002. const String Font::getFallbackFontName() throw()
  67003. {
  67004. return fallbackFont;
  67005. }
  67006. void Font::setFallbackFontName (const String& name) throw()
  67007. {
  67008. fallbackFont = name;
  67009. }
  67010. void Font::setHeight (float newHeight) throw()
  67011. {
  67012. height = jlimit (minFontHeight, maxFontHeight, newHeight);
  67013. }
  67014. void Font::setHeightWithoutChangingWidth (float newHeight) throw()
  67015. {
  67016. newHeight = jlimit (minFontHeight, maxFontHeight, newHeight);
  67017. horizontalScale *= (height / newHeight);
  67018. height = newHeight;
  67019. }
  67020. void Font::setStyleFlags (const int newFlags) throw()
  67021. {
  67022. if (styleFlags != newFlags)
  67023. {
  67024. styleFlags = newFlags;
  67025. typeface = 0;
  67026. ascent = 0;
  67027. }
  67028. }
  67029. void Font::setSizeAndStyle (const float newHeight,
  67030. const int newStyleFlags,
  67031. const float newHorizontalScale,
  67032. const float newKerningAmount) throw()
  67033. {
  67034. height = jlimit (minFontHeight, maxFontHeight, newHeight);
  67035. horizontalScale = newHorizontalScale;
  67036. kerning = newKerningAmount;
  67037. setStyleFlags (newStyleFlags);
  67038. }
  67039. void Font::setHorizontalScale (const float scaleFactor) throw()
  67040. {
  67041. horizontalScale = scaleFactor;
  67042. }
  67043. void Font::setExtraKerningFactor (const float extraKerning) throw()
  67044. {
  67045. kerning = extraKerning;
  67046. }
  67047. void Font::setBold (const bool shouldBeBold) throw()
  67048. {
  67049. setStyleFlags (shouldBeBold ? (styleFlags | bold)
  67050. : (styleFlags & ~bold));
  67051. }
  67052. bool Font::isBold() const throw()
  67053. {
  67054. return (styleFlags & bold) != 0;
  67055. }
  67056. void Font::setItalic (const bool shouldBeItalic) throw()
  67057. {
  67058. setStyleFlags (shouldBeItalic ? (styleFlags | italic)
  67059. : (styleFlags & ~italic));
  67060. }
  67061. bool Font::isItalic() const throw()
  67062. {
  67063. return (styleFlags & italic) != 0;
  67064. }
  67065. void Font::setUnderline (const bool shouldBeUnderlined) throw()
  67066. {
  67067. setStyleFlags (shouldBeUnderlined ? (styleFlags | underlined)
  67068. : (styleFlags & ~underlined));
  67069. }
  67070. bool Font::isUnderlined() const throw()
  67071. {
  67072. return (styleFlags & underlined) != 0;
  67073. }
  67074. float Font::getAscent() const throw()
  67075. {
  67076. if (ascent == 0)
  67077. ascent = getTypeface()->getAscent();
  67078. return height * ascent;
  67079. }
  67080. float Font::getDescent() const throw()
  67081. {
  67082. return height - getAscent();
  67083. }
  67084. int Font::getStringWidth (const String& text) const throw()
  67085. {
  67086. return roundFloatToInt (getStringWidthFloat (text));
  67087. }
  67088. float Font::getStringWidthFloat (const String& text) const throw()
  67089. {
  67090. float x = 0.0f;
  67091. if (text.isNotEmpty())
  67092. {
  67093. Typeface* const typeface = getTypeface();
  67094. const juce_wchar* t = (const juce_wchar*) text;
  67095. do
  67096. {
  67097. const TypefaceGlyphInfo* const glyph = typeface->getGlyph (*t++);
  67098. if (glyph != 0)
  67099. x += kerning + glyph->getHorizontalSpacing (*t);
  67100. }
  67101. while (*t != 0);
  67102. x *= height;
  67103. x *= horizontalScale;
  67104. }
  67105. return x;
  67106. }
  67107. Typeface* Font::getTypeface() const throw()
  67108. {
  67109. if (typeface == 0)
  67110. typeface = Typeface::getTypefaceFor (*this);
  67111. return typeface;
  67112. }
  67113. void Font::findFonts (OwnedArray<Font>& destArray) throw()
  67114. {
  67115. const StringArray names (findAllTypefaceNames());
  67116. for (int i = 0; i < names.size(); ++i)
  67117. destArray.add (new Font (names[i], defaultFontHeight, Font::plain));
  67118. }
  67119. END_JUCE_NAMESPACE
  67120. /********* End of inlined file: juce_Font.cpp *********/
  67121. /********* Start of inlined file: juce_GlyphArrangement.cpp *********/
  67122. BEGIN_JUCE_NAMESPACE
  67123. #define SHOULD_WRAP(x, wrapwidth) (((x) - 0.0001f) >= (wrapwidth))
  67124. class FontGlyphAlphaMap
  67125. {
  67126. public:
  67127. bool draw (const Graphics& g, float x, const float y) const throw()
  67128. {
  67129. if (bitmap1 == 0)
  67130. return false;
  67131. x += xOrigin;
  67132. const float xFloor = floorf (x);
  67133. const int intX = (int) xFloor;
  67134. g.drawImageAt (((x - xFloor) >= 0.5f && bitmap2 != 0) ? bitmap2 : bitmap1,
  67135. intX, (int) floorf (y + yOrigin), true);
  67136. return true;
  67137. }
  67138. juce_UseDebuggingNewOperator
  67139. private:
  67140. Image* bitmap1;
  67141. Image* bitmap2;
  67142. float xOrigin, yOrigin;
  67143. int lastAccessCount;
  67144. Typeface::Ptr typeface;
  67145. float height, horizontalScale;
  67146. juce_wchar character;
  67147. friend class GlyphCache;
  67148. FontGlyphAlphaMap() throw()
  67149. : bitmap1 (0),
  67150. bitmap2 (0),
  67151. lastAccessCount (0),
  67152. height (0),
  67153. horizontalScale (0),
  67154. character (0)
  67155. {
  67156. }
  67157. ~FontGlyphAlphaMap() throw()
  67158. {
  67159. delete bitmap1;
  67160. delete bitmap2;
  67161. }
  67162. class AlphaBitmapRenderer
  67163. {
  67164. uint8* const data;
  67165. const int stride;
  67166. uint8* lineStart;
  67167. AlphaBitmapRenderer (const AlphaBitmapRenderer&);
  67168. const AlphaBitmapRenderer& operator= (const AlphaBitmapRenderer&);
  67169. public:
  67170. AlphaBitmapRenderer (uint8* const data_,
  67171. const int stride_) throw()
  67172. : data (data_),
  67173. stride (stride_)
  67174. {
  67175. }
  67176. forcedinline void setEdgeTableYPos (const int y) throw()
  67177. {
  67178. lineStart = data + (stride * y);
  67179. }
  67180. forcedinline void handleEdgeTablePixel (const int x, const int alphaLevel) const throw()
  67181. {
  67182. lineStart [x] = (uint8) alphaLevel;
  67183. }
  67184. forcedinline void handleEdgeTableLine (const int x, int width, const int alphaLevel) const throw()
  67185. {
  67186. uint8* d = lineStart + x;
  67187. while (--width >= 0)
  67188. *d++ = (uint8) alphaLevel;
  67189. }
  67190. };
  67191. Image* createAlphaMapFromPath (const Path& path,
  67192. float& topLeftX, float& topLeftY,
  67193. float xScale, float yScale,
  67194. const float subPixelOffsetX) throw()
  67195. {
  67196. Image* im = 0;
  67197. float px, py, pw, ph;
  67198. path.getBounds (px, py, pw, ph);
  67199. topLeftX = floorf (px * xScale);
  67200. topLeftY = floorf (py * yScale);
  67201. int bitmapWidth = roundFloatToInt (pw * xScale) + 2;
  67202. int bitmapHeight = roundFloatToInt (ph * yScale) + 2;
  67203. im = new Image (Image::SingleChannel, bitmapWidth, bitmapHeight, true);
  67204. EdgeTable edgeTable (0, bitmapHeight, EdgeTable::Oversampling_16times);
  67205. edgeTable.addPath (path, AffineTransform::scale (xScale, yScale)
  67206. .translated (subPixelOffsetX - topLeftX, -topLeftY));
  67207. int stride, pixelStride;
  67208. uint8* const pixels = (uint8*) im->lockPixelDataReadWrite (0, 0, bitmapWidth, bitmapHeight, stride, pixelStride);
  67209. jassert (pixelStride == 1);
  67210. AlphaBitmapRenderer renderer (pixels, stride);
  67211. edgeTable.iterate (renderer, 0, 0, bitmapWidth, bitmapHeight, 0);
  67212. im->releasePixelDataReadWrite (pixels);
  67213. return im;
  67214. }
  67215. void generate (Typeface* const face,
  67216. const juce_wchar character_,
  67217. const float fontHeight,
  67218. const float fontHorizontalScale) throw()
  67219. {
  67220. character = character_;
  67221. typeface = face;
  67222. height = fontHeight;
  67223. horizontalScale = fontHorizontalScale;
  67224. const Path* const glyphPath = face->getOutlineForGlyph (character_);
  67225. deleteAndZero (bitmap1);
  67226. deleteAndZero (bitmap2);
  67227. const float fontHScale = fontHeight * fontHorizontalScale;
  67228. if (glyphPath != 0 && ! glyphPath->isEmpty())
  67229. {
  67230. bitmap1 = createAlphaMapFromPath (*glyphPath, xOrigin, yOrigin, fontHScale, fontHeight, 0.0f);
  67231. if (fontHScale < 24.0f)
  67232. bitmap2 = createAlphaMapFromPath (*glyphPath, xOrigin, yOrigin, fontHScale, fontHeight, 0.5f);
  67233. }
  67234. else
  67235. {
  67236. xOrigin = yOrigin = 0;
  67237. }
  67238. }
  67239. };
  67240. static const int defaultNumGlyphsToCache = 120;
  67241. class GlyphCache;
  67242. static GlyphCache* cacheInstance = 0;
  67243. class GlyphCache : private DeletedAtShutdown
  67244. {
  67245. public:
  67246. static GlyphCache* getInstance() throw()
  67247. {
  67248. if (cacheInstance == 0)
  67249. cacheInstance = new GlyphCache();
  67250. return cacheInstance;
  67251. }
  67252. const FontGlyphAlphaMap& getGlyphFor (Typeface* const typeface,
  67253. const float fontHeight,
  67254. const float fontHorizontalScale,
  67255. const juce_wchar character) throw()
  67256. {
  67257. ++accessCounter;
  67258. int oldestCounter = INT_MAX;
  67259. int oldestIndex = 0;
  67260. for (int i = numGlyphs; --i >= 0;)
  67261. {
  67262. FontGlyphAlphaMap& g = glyphs[i];
  67263. if (g.character == character
  67264. && g.height == fontHeight
  67265. && g.typeface->hashCode() == typeface->hashCode()
  67266. && g.horizontalScale == fontHorizontalScale)
  67267. {
  67268. g.lastAccessCount = accessCounter;
  67269. ++hits;
  67270. return g;
  67271. }
  67272. if (oldestCounter > g.lastAccessCount)
  67273. {
  67274. oldestCounter = g.lastAccessCount;
  67275. oldestIndex = i;
  67276. }
  67277. }
  67278. ++misses;
  67279. if (hits + misses > (numGlyphs << 4))
  67280. {
  67281. if (misses * 2 > hits)
  67282. setCacheSize (numGlyphs + 32);
  67283. hits = 0;
  67284. misses = 0;
  67285. oldestIndex = 0;
  67286. }
  67287. FontGlyphAlphaMap& oldest = glyphs [oldestIndex];
  67288. oldest.lastAccessCount = accessCounter;
  67289. oldest.generate (typeface,
  67290. character,
  67291. fontHeight,
  67292. fontHorizontalScale);
  67293. return oldest;
  67294. }
  67295. void setCacheSize (const int num) throw()
  67296. {
  67297. if (numGlyphs != num)
  67298. {
  67299. numGlyphs = num;
  67300. if (glyphs != 0)
  67301. delete[] glyphs;
  67302. glyphs = new FontGlyphAlphaMap [numGlyphs];
  67303. hits = 0;
  67304. misses = 0;
  67305. }
  67306. }
  67307. juce_UseDebuggingNewOperator
  67308. private:
  67309. FontGlyphAlphaMap* glyphs;
  67310. int numGlyphs, accessCounter;
  67311. int hits, misses;
  67312. GlyphCache() throw()
  67313. : glyphs (0),
  67314. numGlyphs (0),
  67315. accessCounter (0)
  67316. {
  67317. setCacheSize (defaultNumGlyphsToCache);
  67318. }
  67319. ~GlyphCache() throw()
  67320. {
  67321. delete[] glyphs;
  67322. jassert (cacheInstance == this);
  67323. cacheInstance = 0;
  67324. }
  67325. GlyphCache (const GlyphCache&);
  67326. const GlyphCache& operator= (const GlyphCache&);
  67327. };
  67328. PositionedGlyph::PositionedGlyph() throw()
  67329. {
  67330. }
  67331. void PositionedGlyph::draw (const Graphics& g) const throw()
  67332. {
  67333. if (! glyphInfo->isWhitespace())
  67334. {
  67335. if (fontHeight < 100.0f && fontHeight > 0.1f && ! g.isVectorDevice())
  67336. {
  67337. const FontGlyphAlphaMap& alphaMap
  67338. = GlyphCache::getInstance()->getGlyphFor (glyphInfo->getTypeface(),
  67339. fontHeight,
  67340. fontHorizontalScale,
  67341. getCharacter());
  67342. alphaMap.draw (g, x, y);
  67343. }
  67344. else
  67345. {
  67346. // that's a bit of a dodgy size, isn't it??
  67347. jassert (fontHeight > 0.0f && fontHeight < 4000.0f);
  67348. draw (g, AffineTransform::identity);
  67349. }
  67350. }
  67351. }
  67352. void PositionedGlyph::draw (const Graphics& g,
  67353. const AffineTransform& transform) const throw()
  67354. {
  67355. if (! glyphInfo->isWhitespace())
  67356. {
  67357. g.fillPath (glyphInfo->getPath(),
  67358. AffineTransform::scale (fontHeight * fontHorizontalScale, fontHeight)
  67359. .translated (x, y)
  67360. .followedBy (transform));
  67361. }
  67362. }
  67363. void PositionedGlyph::createPath (Path& path) const throw()
  67364. {
  67365. if (! glyphInfo->isWhitespace())
  67366. {
  67367. path.addPath (glyphInfo->getPath(),
  67368. AffineTransform::scale (fontHeight * fontHorizontalScale, fontHeight)
  67369. .translated (x, y));
  67370. }
  67371. }
  67372. bool PositionedGlyph::hitTest (float px, float py) const throw()
  67373. {
  67374. if (px >= getLeft() && px < getRight()
  67375. && py >= getTop() && py < getBottom()
  67376. && fontHeight > 0.0f
  67377. && ! glyphInfo->isWhitespace())
  67378. {
  67379. AffineTransform::translation (-x, -y)
  67380. .scaled (1.0f / (fontHeight * fontHorizontalScale), 1.0f / fontHeight)
  67381. .transformPoint (px, py);
  67382. return glyphInfo->getPath().contains (px, py);
  67383. }
  67384. return false;
  67385. }
  67386. void PositionedGlyph::moveBy (const float deltaX,
  67387. const float deltaY) throw()
  67388. {
  67389. x += deltaX;
  67390. y += deltaY;
  67391. }
  67392. GlyphArrangement::GlyphArrangement() throw()
  67393. : numGlyphs (0),
  67394. numAllocated (0),
  67395. glyphs (0)
  67396. {
  67397. }
  67398. GlyphArrangement::GlyphArrangement (const GlyphArrangement& other) throw()
  67399. : numGlyphs (0),
  67400. numAllocated (0),
  67401. glyphs (0)
  67402. {
  67403. addGlyphArrangement (other);
  67404. }
  67405. const GlyphArrangement& GlyphArrangement::operator= (const GlyphArrangement& other) throw()
  67406. {
  67407. if (this != &other)
  67408. {
  67409. clear();
  67410. addGlyphArrangement (other);
  67411. }
  67412. return *this;
  67413. }
  67414. GlyphArrangement::~GlyphArrangement() throw()
  67415. {
  67416. clear();
  67417. juce_free (glyphs);
  67418. }
  67419. void GlyphArrangement::ensureNumGlyphsAllocated (const int minGlyphs) throw()
  67420. {
  67421. if (numAllocated <= minGlyphs)
  67422. {
  67423. numAllocated = minGlyphs + 2;
  67424. if (glyphs == 0)
  67425. glyphs = (PositionedGlyph*) juce_malloc (numAllocated * sizeof (PositionedGlyph));
  67426. else
  67427. glyphs = (PositionedGlyph*) juce_realloc (glyphs, numAllocated * sizeof (PositionedGlyph));
  67428. }
  67429. }
  67430. void GlyphArrangement::incGlyphRefCount (const int i) const throw()
  67431. {
  67432. jassert (((unsigned int) i) < (unsigned int) numGlyphs);
  67433. if (glyphs[i].glyphInfo != 0 && glyphs[i].glyphInfo->getTypeface() != 0)
  67434. glyphs[i].glyphInfo->getTypeface()->incReferenceCount();
  67435. }
  67436. void GlyphArrangement::decGlyphRefCount (const int i) const throw()
  67437. {
  67438. if (glyphs[i].glyphInfo != 0 && glyphs[i].glyphInfo->getTypeface() != 0)
  67439. glyphs[i].glyphInfo->getTypeface()->decReferenceCount();
  67440. }
  67441. void GlyphArrangement::clear() throw()
  67442. {
  67443. for (int i = numGlyphs; --i >= 0;)
  67444. decGlyphRefCount (i);
  67445. numGlyphs = 0;
  67446. }
  67447. PositionedGlyph& GlyphArrangement::getGlyph (const int index) const throw()
  67448. {
  67449. jassert (((unsigned int) index) < (unsigned int) numGlyphs);
  67450. return glyphs [index];
  67451. }
  67452. void GlyphArrangement::addGlyphArrangement (const GlyphArrangement& other) throw()
  67453. {
  67454. ensureNumGlyphsAllocated (numGlyphs + other.numGlyphs);
  67455. memcpy (glyphs + numGlyphs, other.glyphs,
  67456. other.numGlyphs * sizeof (PositionedGlyph));
  67457. for (int i = other.numGlyphs; --i >= 0;)
  67458. incGlyphRefCount (numGlyphs++);
  67459. }
  67460. void GlyphArrangement::removeLast() throw()
  67461. {
  67462. if (numGlyphs > 0)
  67463. decGlyphRefCount (--numGlyphs);
  67464. }
  67465. void GlyphArrangement::removeRangeOfGlyphs (int startIndex, const int num) throw()
  67466. {
  67467. jassert (startIndex >= 0);
  67468. if (startIndex < 0)
  67469. startIndex = 0;
  67470. if (num < 0 || startIndex + num >= numGlyphs)
  67471. {
  67472. while (numGlyphs > startIndex)
  67473. removeLast();
  67474. }
  67475. else if (num > 0)
  67476. {
  67477. int i;
  67478. for (i = startIndex; i < startIndex + num; ++i)
  67479. decGlyphRefCount (i);
  67480. for (i = numGlyphs - (startIndex + num); --i >= 0;)
  67481. {
  67482. glyphs [startIndex] = glyphs [startIndex + num];
  67483. ++startIndex;
  67484. }
  67485. numGlyphs -= num;
  67486. }
  67487. }
  67488. void GlyphArrangement::addLineOfText (const Font& font,
  67489. const String& text,
  67490. const float xOffset,
  67491. const float yOffset) throw()
  67492. {
  67493. addCurtailedLineOfText (font, text,
  67494. xOffset, yOffset,
  67495. 1.0e10f, false);
  67496. }
  67497. void GlyphArrangement::addCurtailedLineOfText (const Font& font,
  67498. const String& text,
  67499. float xOffset,
  67500. const float yOffset,
  67501. const float maxWidthPixels,
  67502. const bool useEllipsis) throw()
  67503. {
  67504. const int textLen = text.length();
  67505. if (textLen > 0)
  67506. {
  67507. ensureNumGlyphsAllocated (numGlyphs + textLen + 3); // extra chars for ellipsis
  67508. Typeface* const typeface = font.getTypeface();
  67509. const float fontHeight = font.getHeight();
  67510. const float ascent = font.getAscent();
  67511. const float fontHorizontalScale = font.getHorizontalScale();
  67512. const float heightTimesScale = fontHorizontalScale * fontHeight;
  67513. const float kerningFactor = font.getExtraKerningFactor();
  67514. const float startX = xOffset;
  67515. const juce_wchar* const unicodeText = (const juce_wchar*) text;
  67516. for (int i = 0; i < textLen; ++i)
  67517. {
  67518. const TypefaceGlyphInfo* const glyph = typeface->getGlyph (unicodeText[i]);
  67519. if (glyph != 0)
  67520. {
  67521. jassert (numAllocated > numGlyphs);
  67522. ensureNumGlyphsAllocated (numGlyphs);
  67523. PositionedGlyph& pg = glyphs [numGlyphs];
  67524. pg.glyphInfo = glyph;
  67525. pg.x = xOffset;
  67526. pg.y = yOffset;
  67527. pg.w = heightTimesScale * glyph->getHorizontalSpacing (0);
  67528. pg.fontHeight = fontHeight;
  67529. pg.fontAscent = ascent;
  67530. pg.fontHorizontalScale = fontHorizontalScale;
  67531. pg.isUnderlined = font.isUnderlined();
  67532. xOffset += heightTimesScale * (kerningFactor + glyph->getHorizontalSpacing (unicodeText [i + 1]));
  67533. if (xOffset - startX > maxWidthPixels + 1.0f)
  67534. {
  67535. // curtail the string if it's too wide..
  67536. if (useEllipsis && textLen > 3 && numGlyphs >= 3)
  67537. appendEllipsis (font, startX + maxWidthPixels);
  67538. break;
  67539. }
  67540. else
  67541. {
  67542. if (glyph->getTypeface() != 0)
  67543. glyph->getTypeface()->incReferenceCount();
  67544. ++numGlyphs;
  67545. }
  67546. }
  67547. }
  67548. }
  67549. }
  67550. void GlyphArrangement::appendEllipsis (const Font& font, const float maxXPixels) throw()
  67551. {
  67552. const TypefaceGlyphInfo* const dotGlyph = font.getTypeface()->getGlyph (T('.'));
  67553. if (dotGlyph != 0)
  67554. {
  67555. if (numGlyphs > 0)
  67556. {
  67557. PositionedGlyph& glyph = glyphs [numGlyphs - 1];
  67558. const float fontHeight = glyph.fontHeight;
  67559. const float fontHorizontalScale = glyph.fontHorizontalScale;
  67560. const float fontAscent = glyph.fontAscent;
  67561. const float dx = fontHeight * fontHorizontalScale
  67562. * (font.getExtraKerningFactor() + dotGlyph->getHorizontalSpacing (T('.')));
  67563. float xOffset = 0.0f, yOffset = 0.0f;
  67564. for (int dotPos = 3; --dotPos >= 0 && numGlyphs > 0;)
  67565. {
  67566. removeLast();
  67567. jassert (numAllocated > numGlyphs);
  67568. PositionedGlyph& pg = glyphs [numGlyphs];
  67569. xOffset = pg.x;
  67570. yOffset = pg.y;
  67571. if (numGlyphs == 0 || xOffset + dx * 3 <= maxXPixels)
  67572. break;
  67573. }
  67574. for (int i = 3; --i >= 0;)
  67575. {
  67576. jassert (numAllocated > numGlyphs);
  67577. ensureNumGlyphsAllocated (numGlyphs);
  67578. PositionedGlyph& pg = glyphs [numGlyphs];
  67579. pg.glyphInfo = dotGlyph;
  67580. pg.x = xOffset;
  67581. pg.y = yOffset;
  67582. pg.w = dx;
  67583. pg.fontHeight = fontHeight;
  67584. pg.fontAscent = fontAscent;
  67585. pg.fontHorizontalScale = fontHorizontalScale;
  67586. pg.isUnderlined = font.isUnderlined();
  67587. xOffset += dx;
  67588. if (dotGlyph->getTypeface() != 0)
  67589. dotGlyph->getTypeface()->incReferenceCount();
  67590. ++numGlyphs;
  67591. }
  67592. }
  67593. }
  67594. }
  67595. void GlyphArrangement::addJustifiedText (const Font& font,
  67596. const String& text,
  67597. float x, float y,
  67598. const float maxLineWidth,
  67599. const Justification& horizontalLayout) throw()
  67600. {
  67601. int lineStartIndex = numGlyphs;
  67602. addLineOfText (font, text, x, y);
  67603. const float originalY = y;
  67604. while (lineStartIndex < numGlyphs)
  67605. {
  67606. int i = lineStartIndex;
  67607. if (glyphs[i].getCharacter() != T('\n') && glyphs[i].getCharacter() != T('\r'))
  67608. ++i;
  67609. const float lineMaxX = glyphs [lineStartIndex].getLeft() + maxLineWidth;
  67610. int lastWordBreakIndex = -1;
  67611. while (i < numGlyphs)
  67612. {
  67613. PositionedGlyph& pg = glyphs[i];
  67614. const juce_wchar c = pg.getCharacter();
  67615. if (c == T('\r') || c == T('\n'))
  67616. {
  67617. ++i;
  67618. if (c == T('\r') && i < numGlyphs && glyphs [i].getCharacter() == T('\n'))
  67619. ++i;
  67620. break;
  67621. }
  67622. else if (pg.isWhitespace())
  67623. {
  67624. lastWordBreakIndex = i + 1;
  67625. }
  67626. else if (SHOULD_WRAP (pg.getRight(), lineMaxX))
  67627. {
  67628. if (lastWordBreakIndex >= 0)
  67629. i = lastWordBreakIndex;
  67630. break;
  67631. }
  67632. ++i;
  67633. }
  67634. const float currentLineStartX = glyphs [lineStartIndex].getLeft();
  67635. float currentLineEndX = currentLineStartX;
  67636. for (int j = i; --j >= lineStartIndex;)
  67637. {
  67638. if (! glyphs[j].isWhitespace())
  67639. {
  67640. currentLineEndX = glyphs[j].getRight();
  67641. break;
  67642. }
  67643. }
  67644. float deltaX = 0.0f;
  67645. if (horizontalLayout.testFlags (Justification::horizontallyJustified))
  67646. spreadOutLine (lineStartIndex, i - lineStartIndex, maxLineWidth);
  67647. else if (horizontalLayout.testFlags (Justification::horizontallyCentred))
  67648. deltaX = (maxLineWidth - (currentLineEndX - currentLineStartX)) * 0.5f;
  67649. else if (horizontalLayout.testFlags (Justification::right))
  67650. deltaX = maxLineWidth - (currentLineEndX - currentLineStartX);
  67651. moveRangeOfGlyphs (lineStartIndex, i - lineStartIndex,
  67652. x + deltaX - currentLineStartX, y - originalY);
  67653. lineStartIndex = i;
  67654. y += font.getHeight();
  67655. }
  67656. }
  67657. void GlyphArrangement::addFittedText (const Font& f,
  67658. const String& text,
  67659. float x, float y,
  67660. float width, float height,
  67661. const Justification& layout,
  67662. int maximumLines,
  67663. const float minimumHorizontalScale) throw()
  67664. {
  67665. // doesn't make much sense if this is outside a sensible range of 0.5 to 1.0
  67666. jassert (minimumHorizontalScale > 0 && minimumHorizontalScale <= 1.0f);
  67667. if (text.containsAnyOf (T("\r\n")))
  67668. {
  67669. GlyphArrangement ga;
  67670. ga.addJustifiedText (f, text, x, y, width, layout);
  67671. float l, t, r, b;
  67672. ga.getBoundingBox (0, -1, l, t, r, b, false);
  67673. float dy = y - t;
  67674. if (layout.testFlags (Justification::verticallyCentred))
  67675. dy += (height - (b - t)) * 0.5f;
  67676. else if (layout.testFlags (Justification::bottom))
  67677. dy += height - (b - t);
  67678. ga.moveRangeOfGlyphs (0, -1, 0.0f, dy);
  67679. addGlyphArrangement (ga);
  67680. return;
  67681. }
  67682. int startIndex = numGlyphs;
  67683. addLineOfText (f, text.trim(), x, y);
  67684. if (numGlyphs > startIndex)
  67685. {
  67686. float lineWidth = glyphs[numGlyphs - 1].getRight() - glyphs[startIndex].getLeft();
  67687. if (lineWidth <= 0)
  67688. return;
  67689. if (lineWidth * minimumHorizontalScale < width)
  67690. {
  67691. if (lineWidth > width)
  67692. {
  67693. stretchRangeOfGlyphs (startIndex, numGlyphs - startIndex,
  67694. width / lineWidth);
  67695. }
  67696. justifyGlyphs (startIndex, numGlyphs - startIndex,
  67697. x, y, width, height, layout);
  67698. }
  67699. else if (maximumLines <= 1)
  67700. {
  67701. const float ratio = jmax (minimumHorizontalScale, width / lineWidth);
  67702. stretchRangeOfGlyphs (startIndex, numGlyphs - startIndex, ratio);
  67703. while (numGlyphs > 0 && glyphs [numGlyphs - 1].x + glyphs [numGlyphs - 1].w >= x + width)
  67704. removeLast();
  67705. appendEllipsis (f, x + width);
  67706. justifyGlyphs (startIndex, numGlyphs - startIndex,
  67707. x, y, width, height, layout);
  67708. }
  67709. else
  67710. {
  67711. Font font (f);
  67712. String txt (text.trim());
  67713. const int length = txt.length();
  67714. int numLines = 1;
  67715. const int originalStartIndex = startIndex;
  67716. if (length <= 12 && ! txt.containsAnyOf (T(" -\t\r\n")))
  67717. maximumLines = 1;
  67718. maximumLines = jmin (maximumLines, length);
  67719. while (numLines < maximumLines)
  67720. {
  67721. ++numLines;
  67722. const float newFontHeight = height / (float)numLines;
  67723. if (newFontHeight < 8.0f)
  67724. break;
  67725. if (newFontHeight < font.getHeight())
  67726. {
  67727. font.setHeight (newFontHeight);
  67728. while (numGlyphs > startIndex)
  67729. removeLast();
  67730. addLineOfText (font, txt, x, y);
  67731. lineWidth = glyphs[numGlyphs - 1].getRight() - glyphs[startIndex].getLeft();
  67732. }
  67733. if (numLines > lineWidth / width)
  67734. break;
  67735. }
  67736. if (numLines < 1)
  67737. numLines = 1;
  67738. float lineY = y;
  67739. float widthPerLine = lineWidth / numLines;
  67740. int lastLineStartIndex = 0;
  67741. for (int line = 0; line < numLines; ++line)
  67742. {
  67743. int i = startIndex;
  67744. lastLineStartIndex = i;
  67745. float lineStartX = glyphs[startIndex].getLeft();
  67746. while (i < numGlyphs)
  67747. {
  67748. lineWidth = (glyphs[i].getRight() - lineStartX);
  67749. if (lineWidth > widthPerLine)
  67750. {
  67751. // got to a point where the line's too long, so skip forward to find a
  67752. // good place to break it..
  67753. const int searchStartIndex = i;
  67754. while (i < numGlyphs)
  67755. {
  67756. if ((glyphs[i].getRight() - lineStartX) * minimumHorizontalScale < width)
  67757. {
  67758. if (glyphs[i].isWhitespace()
  67759. || glyphs[i].getCharacter() == T('-'))
  67760. {
  67761. ++i;
  67762. break;
  67763. }
  67764. }
  67765. else
  67766. {
  67767. // can't find a suitable break, so try looking backwards..
  67768. i = searchStartIndex;
  67769. for (int back = 1; back < jmin (5, i - startIndex - 1); ++back)
  67770. {
  67771. if (glyphs[i - back].isWhitespace()
  67772. || glyphs[i - back].getCharacter() == T('-'))
  67773. {
  67774. i -= back - 1;
  67775. break;
  67776. }
  67777. }
  67778. break;
  67779. }
  67780. ++i;
  67781. }
  67782. break;
  67783. }
  67784. ++i;
  67785. }
  67786. int wsStart = i;
  67787. while (wsStart > 0 && glyphs[wsStart - 1].isWhitespace())
  67788. --wsStart;
  67789. int wsEnd = i;
  67790. while (wsEnd < numGlyphs && glyphs[wsEnd].isWhitespace())
  67791. ++wsEnd;
  67792. removeRangeOfGlyphs (wsStart, wsEnd - wsStart);
  67793. i = jmax (wsStart, startIndex + 1);
  67794. lineWidth = glyphs[i - 1].getRight() - lineStartX;
  67795. if (lineWidth > width)
  67796. {
  67797. stretchRangeOfGlyphs (startIndex, i - startIndex,
  67798. width / lineWidth);
  67799. }
  67800. justifyGlyphs (startIndex, i - startIndex,
  67801. x, lineY, width, font.getHeight(),
  67802. layout.getOnlyHorizontalFlags() | Justification::verticallyCentred);
  67803. startIndex = i;
  67804. lineY += font.getHeight();
  67805. if (startIndex >= numGlyphs)
  67806. break;
  67807. }
  67808. if (startIndex < numGlyphs)
  67809. {
  67810. while (numGlyphs > startIndex)
  67811. removeLast();
  67812. if (startIndex - originalStartIndex > 4)
  67813. {
  67814. const float lineStartX = glyphs[lastLineStartIndex].getLeft();
  67815. appendEllipsis (font, lineStartX + width);
  67816. lineWidth = glyphs[startIndex - 1].getRight() - lineStartX;
  67817. if (lineWidth > width)
  67818. {
  67819. stretchRangeOfGlyphs (lastLineStartIndex, startIndex - lastLineStartIndex,
  67820. width / lineWidth);
  67821. }
  67822. justifyGlyphs (lastLineStartIndex, startIndex - lastLineStartIndex,
  67823. x, lineY - font.getHeight(), width, font.getHeight(),
  67824. layout.getOnlyHorizontalFlags() | Justification::verticallyCentred);
  67825. }
  67826. startIndex = numGlyphs;
  67827. }
  67828. justifyGlyphs (originalStartIndex, startIndex - originalStartIndex,
  67829. x, y, width, height, layout.getFlags() & ~Justification::horizontallyJustified);
  67830. }
  67831. }
  67832. }
  67833. void GlyphArrangement::moveRangeOfGlyphs (int startIndex, int num,
  67834. const float dx, const float dy) throw()
  67835. {
  67836. jassert (startIndex >= 0);
  67837. if (dx != 0.0f || dy != 0.0f)
  67838. {
  67839. if (num < 0 || startIndex + num > numGlyphs)
  67840. num = numGlyphs - startIndex;
  67841. while (--num >= 0)
  67842. {
  67843. jassert (((unsigned int) startIndex) <= (unsigned int) numGlyphs);
  67844. glyphs [startIndex++].moveBy (dx, dy);
  67845. }
  67846. }
  67847. }
  67848. void GlyphArrangement::stretchRangeOfGlyphs (int startIndex, int num,
  67849. const float horizontalScaleFactor) throw()
  67850. {
  67851. jassert (startIndex >= 0);
  67852. if (num < 0 || startIndex + num > numGlyphs)
  67853. num = numGlyphs - startIndex;
  67854. if (num > 0)
  67855. {
  67856. const float xAnchor = glyphs[startIndex].getLeft();
  67857. while (--num >= 0)
  67858. {
  67859. jassert (((unsigned int) startIndex) <= (unsigned int) numGlyphs);
  67860. PositionedGlyph& pg = glyphs[startIndex++];
  67861. pg.x = xAnchor + (pg.x - xAnchor) * horizontalScaleFactor;
  67862. pg.fontHorizontalScale *= horizontalScaleFactor;
  67863. pg.w *= horizontalScaleFactor;
  67864. }
  67865. }
  67866. }
  67867. void GlyphArrangement::getBoundingBox (int startIndex, int num,
  67868. float& left,
  67869. float& top,
  67870. float& right,
  67871. float& bottom,
  67872. const bool includeWhitespace) const throw()
  67873. {
  67874. jassert (startIndex >= 0);
  67875. if (num < 0 || startIndex + num > numGlyphs)
  67876. num = numGlyphs - startIndex;
  67877. left = 0.0f;
  67878. top = 0.0f;
  67879. right = 0.0f;
  67880. bottom = 0.0f;
  67881. bool isFirst = true;
  67882. while (--num >= 0)
  67883. {
  67884. const PositionedGlyph& pg = glyphs [startIndex++];
  67885. if (includeWhitespace || ! pg.isWhitespace())
  67886. {
  67887. if (isFirst)
  67888. {
  67889. isFirst = false;
  67890. left = pg.getLeft();
  67891. top = pg.getTop();
  67892. right = pg.getRight();
  67893. bottom = pg.getBottom();
  67894. }
  67895. else
  67896. {
  67897. left = jmin (left, pg.getLeft());
  67898. top = jmin (top, pg.getTop());
  67899. right = jmax (right, pg.getRight());
  67900. bottom = jmax (bottom, pg.getBottom());
  67901. }
  67902. }
  67903. }
  67904. }
  67905. void GlyphArrangement::justifyGlyphs (const int startIndex,
  67906. const int num,
  67907. const float x, const float y,
  67908. const float width, const float height,
  67909. const Justification& justification) throw()
  67910. {
  67911. jassert (num >= 0 && startIndex >= 0);
  67912. if (numGlyphs > 0 && num > 0)
  67913. {
  67914. float left, top, right, bottom;
  67915. getBoundingBox (startIndex, num, left, top, right, bottom,
  67916. ! justification.testFlags (Justification::horizontallyJustified
  67917. | Justification::horizontallyCentred));
  67918. float deltaX = 0.0f;
  67919. if (justification.testFlags (Justification::horizontallyJustified))
  67920. deltaX = x - left;
  67921. else if (justification.testFlags (Justification::horizontallyCentred))
  67922. deltaX = x + (width - (right - left)) * 0.5f - left;
  67923. else if (justification.testFlags (Justification::right))
  67924. deltaX = (x + width) - right;
  67925. else
  67926. deltaX = x - left;
  67927. float deltaY = 0.0f;
  67928. if (justification.testFlags (Justification::top))
  67929. deltaY = y - top;
  67930. else if (justification.testFlags (Justification::bottom))
  67931. deltaY = (y + height) - bottom;
  67932. else
  67933. deltaY = y + (height - (bottom - top)) * 0.5f - top;
  67934. moveRangeOfGlyphs (startIndex, num, deltaX, deltaY);
  67935. if (justification.testFlags (Justification::horizontallyJustified))
  67936. {
  67937. int lineStart = 0;
  67938. float baseY = glyphs [startIndex].getBaselineY();
  67939. int i;
  67940. for (i = 0; i < num; ++i)
  67941. {
  67942. const float glyphY = glyphs [startIndex + i].getBaselineY();
  67943. if (glyphY != baseY)
  67944. {
  67945. spreadOutLine (startIndex + lineStart, i - lineStart, width);
  67946. lineStart = i;
  67947. baseY = glyphY;
  67948. }
  67949. }
  67950. if (i > lineStart)
  67951. spreadOutLine (startIndex + lineStart, i - lineStart, width);
  67952. }
  67953. }
  67954. }
  67955. void GlyphArrangement::spreadOutLine (const int start, const int num, const float targetWidth) throw()
  67956. {
  67957. if (start + num < numGlyphs
  67958. && glyphs [start + num - 1].getCharacter() != T('\r')
  67959. && glyphs [start + num - 1].getCharacter() != T('\n'))
  67960. {
  67961. int numSpaces = 0;
  67962. int spacesAtEnd = 0;
  67963. for (int i = 0; i < num; ++i)
  67964. {
  67965. if (glyphs [start + i].isWhitespace())
  67966. {
  67967. ++spacesAtEnd;
  67968. ++numSpaces;
  67969. }
  67970. else
  67971. {
  67972. spacesAtEnd = 0;
  67973. }
  67974. }
  67975. numSpaces -= spacesAtEnd;
  67976. if (numSpaces > 0)
  67977. {
  67978. const float startX = glyphs [start].getLeft();
  67979. const float endX = glyphs [start + num - 1 - spacesAtEnd].getRight();
  67980. const float extraPaddingBetweenWords
  67981. = (targetWidth - (endX - startX)) / (float) numSpaces;
  67982. float deltaX = 0.0f;
  67983. for (int i = 0; i < num; ++i)
  67984. {
  67985. glyphs [start + i].moveBy (deltaX, 0.0);
  67986. if (glyphs [start + i].isWhitespace())
  67987. deltaX += extraPaddingBetweenWords;
  67988. }
  67989. }
  67990. }
  67991. }
  67992. void GlyphArrangement::draw (const Graphics& g) const throw()
  67993. {
  67994. for (int i = 0; i < numGlyphs; ++i)
  67995. {
  67996. glyphs[i].draw (g);
  67997. if (glyphs[i].isUnderlined)
  67998. {
  67999. const float lineThickness = (glyphs[i].fontHeight - glyphs[i].fontAscent) * 0.3f;
  68000. juce_wchar nextChar = 0;
  68001. if (i < numGlyphs - 1
  68002. && glyphs[i + 1].y == glyphs[i].y)
  68003. {
  68004. nextChar = glyphs[i + 1].glyphInfo->getCharacter();
  68005. }
  68006. g.fillRect (glyphs[i].x,
  68007. glyphs[i].y + lineThickness * 2.0f,
  68008. glyphs[i].fontHeight
  68009. * glyphs[i].fontHorizontalScale
  68010. * glyphs[i].glyphInfo->getHorizontalSpacing (nextChar),
  68011. lineThickness);
  68012. }
  68013. }
  68014. }
  68015. void GlyphArrangement::draw (const Graphics& g, const AffineTransform& transform) const throw()
  68016. {
  68017. for (int i = 0; i < numGlyphs; ++i)
  68018. {
  68019. glyphs[i].draw (g, transform);
  68020. if (glyphs[i].isUnderlined)
  68021. {
  68022. const float lineThickness = (glyphs[i].fontHeight - glyphs[i].fontAscent) * 0.3f;
  68023. juce_wchar nextChar = 0;
  68024. if (i < numGlyphs - 1
  68025. && glyphs[i + 1].y == glyphs[i].y)
  68026. {
  68027. nextChar = glyphs[i + 1].glyphInfo->getCharacter();
  68028. }
  68029. Path p;
  68030. p.addLineSegment (glyphs[i].x,
  68031. glyphs[i].y + lineThickness * 2.5f,
  68032. glyphs[i].x + glyphs[i].fontHeight
  68033. * glyphs[i].fontHorizontalScale
  68034. * glyphs[i].glyphInfo->getHorizontalSpacing (nextChar),
  68035. glyphs[i].y + lineThickness * 2.5f,
  68036. lineThickness);
  68037. g.fillPath (p, transform);
  68038. }
  68039. }
  68040. }
  68041. void GlyphArrangement::createPath (Path& path) const throw()
  68042. {
  68043. for (int i = 0; i < numGlyphs; ++i)
  68044. glyphs[i].createPath (path);
  68045. }
  68046. int GlyphArrangement::findGlyphIndexAt (float x, float y) const throw()
  68047. {
  68048. for (int i = 0; i < numGlyphs; ++i)
  68049. if (glyphs[i].hitTest (x, y))
  68050. return i;
  68051. return -1;
  68052. }
  68053. END_JUCE_NAMESPACE
  68054. /********* End of inlined file: juce_GlyphArrangement.cpp *********/
  68055. /********* Start of inlined file: juce_TextLayout.cpp *********/
  68056. BEGIN_JUCE_NAMESPACE
  68057. class TextLayoutToken
  68058. {
  68059. public:
  68060. String text;
  68061. Font font;
  68062. int x, y, w, h;
  68063. int line, lineHeight;
  68064. bool isWhitespace, isNewLine;
  68065. TextLayoutToken (const String& t,
  68066. const Font& f,
  68067. const bool isWhitespace_) throw()
  68068. : text (t),
  68069. font (f),
  68070. x(0),
  68071. y(0),
  68072. isWhitespace (isWhitespace_)
  68073. {
  68074. w = font.getStringWidth (t);
  68075. h = roundFloatToInt (f.getHeight());
  68076. isNewLine = t.containsAnyOf (T("\r\n"));
  68077. }
  68078. TextLayoutToken (const TextLayoutToken& other) throw()
  68079. : text (other.text),
  68080. font (other.font),
  68081. x (other.x),
  68082. y (other.y),
  68083. w (other.w),
  68084. h (other.h),
  68085. line (other.line),
  68086. lineHeight (other.lineHeight),
  68087. isWhitespace (other.isWhitespace),
  68088. isNewLine (other.isNewLine)
  68089. {
  68090. }
  68091. ~TextLayoutToken() throw()
  68092. {
  68093. }
  68094. void draw (Graphics& g,
  68095. const int xOffset,
  68096. const int yOffset) throw()
  68097. {
  68098. if (! isWhitespace)
  68099. {
  68100. g.setFont (font);
  68101. g.drawSingleLineText (text.trimEnd(),
  68102. xOffset + x,
  68103. yOffset + y + (lineHeight - h)
  68104. + roundFloatToInt (font.getAscent()));
  68105. }
  68106. }
  68107. juce_UseDebuggingNewOperator
  68108. };
  68109. TextLayout::TextLayout() throw()
  68110. : tokens (64),
  68111. totalLines (0)
  68112. {
  68113. }
  68114. TextLayout::TextLayout (const String& text,
  68115. const Font& font) throw()
  68116. : tokens (64),
  68117. totalLines (0)
  68118. {
  68119. appendText (text, font);
  68120. }
  68121. TextLayout::TextLayout (const TextLayout& other) throw()
  68122. : tokens (64),
  68123. totalLines (0)
  68124. {
  68125. *this = other;
  68126. }
  68127. const TextLayout& TextLayout::operator= (const TextLayout& other) throw()
  68128. {
  68129. if (this != &other)
  68130. {
  68131. clear();
  68132. totalLines = other.totalLines;
  68133. for (int i = 0; i < other.tokens.size(); ++i)
  68134. tokens.add (new TextLayoutToken (*(const TextLayoutToken*)(other.tokens.getUnchecked(i))));
  68135. }
  68136. return *this;
  68137. }
  68138. TextLayout::~TextLayout() throw()
  68139. {
  68140. clear();
  68141. }
  68142. void TextLayout::clear() throw()
  68143. {
  68144. for (int i = tokens.size(); --i >= 0;)
  68145. {
  68146. TextLayoutToken* const t = (TextLayoutToken*)tokens.getUnchecked(i);
  68147. delete t;
  68148. }
  68149. tokens.clear();
  68150. totalLines = 0;
  68151. }
  68152. void TextLayout::appendText (const String& text,
  68153. const Font& font) throw()
  68154. {
  68155. const tchar* t = text;
  68156. String currentString;
  68157. int lastCharType = 0;
  68158. for (;;)
  68159. {
  68160. const tchar c = *t++;
  68161. if (c == 0)
  68162. break;
  68163. int charType;
  68164. if (c == T('\r') || c == T('\n'))
  68165. {
  68166. charType = 0;
  68167. }
  68168. else if (CharacterFunctions::isWhitespace (c))
  68169. {
  68170. charType = 2;
  68171. }
  68172. else
  68173. {
  68174. charType = 1;
  68175. }
  68176. if (charType == 0 || charType != lastCharType)
  68177. {
  68178. if (currentString.isNotEmpty())
  68179. {
  68180. tokens.add (new TextLayoutToken (currentString, font,
  68181. lastCharType == 2 || lastCharType == 0));
  68182. }
  68183. currentString = String::charToString (c);
  68184. if (c == T('\r') && *t == T('\n'))
  68185. currentString += *t++;
  68186. }
  68187. else
  68188. {
  68189. currentString += c;
  68190. }
  68191. lastCharType = charType;
  68192. }
  68193. if (currentString.isNotEmpty())
  68194. tokens.add (new TextLayoutToken (currentString,
  68195. font,
  68196. lastCharType == 2));
  68197. }
  68198. void TextLayout::setText (const String& text, const Font& font) throw()
  68199. {
  68200. clear();
  68201. appendText (text, font);
  68202. }
  68203. void TextLayout::layout (int maxWidth,
  68204. const Justification& justification,
  68205. const bool attemptToBalanceLineLengths) throw()
  68206. {
  68207. if (attemptToBalanceLineLengths)
  68208. {
  68209. const int originalW = maxWidth;
  68210. int bestWidth = maxWidth;
  68211. float bestLineProportion = 0.0f;
  68212. while (maxWidth > originalW / 2)
  68213. {
  68214. layout (maxWidth, justification, false);
  68215. if (getNumLines() <= 1)
  68216. return;
  68217. const int lastLineW = getLineWidth (getNumLines() - 1);
  68218. const int lastButOneLineW = getLineWidth (getNumLines() - 2);
  68219. const float prop = lastLineW / (float) lastButOneLineW;
  68220. if (prop > 0.9f)
  68221. return;
  68222. if (prop > bestLineProportion)
  68223. {
  68224. bestLineProportion = prop;
  68225. bestWidth = maxWidth;
  68226. }
  68227. maxWidth -= 10;
  68228. }
  68229. layout (bestWidth, justification, false);
  68230. }
  68231. else
  68232. {
  68233. int x = 0;
  68234. int y = 0;
  68235. int h = 0;
  68236. totalLines = 0;
  68237. int i;
  68238. for (i = 0; i < tokens.size(); ++i)
  68239. {
  68240. TextLayoutToken* const t = (TextLayoutToken*)tokens.getUnchecked(i);
  68241. t->x = x;
  68242. t->y = y;
  68243. t->line = totalLines;
  68244. x += t->w;
  68245. h = jmax (h, t->h);
  68246. const TextLayoutToken* nextTok = (TextLayoutToken*) tokens [i + 1];
  68247. if (nextTok == 0)
  68248. break;
  68249. if (t->isNewLine || ((! nextTok->isWhitespace) && x + nextTok->w > maxWidth))
  68250. {
  68251. // finished a line, so go back and update the heights of the things on it
  68252. for (int j = i; j >= 0; --j)
  68253. {
  68254. TextLayoutToken* const tok = (TextLayoutToken*)tokens.getUnchecked(j);
  68255. if (tok->line == totalLines)
  68256. tok->lineHeight = h;
  68257. else
  68258. break;
  68259. }
  68260. x = 0;
  68261. y += h;
  68262. h = 0;
  68263. ++totalLines;
  68264. }
  68265. }
  68266. // finished a line, so go back and update the heights of the things on it
  68267. for (int j = jmin (i, tokens.size() - 1); j >= 0; --j)
  68268. {
  68269. TextLayoutToken* const t = (TextLayoutToken*) tokens.getUnchecked(j);
  68270. if (t->line == totalLines)
  68271. t->lineHeight = h;
  68272. else
  68273. break;
  68274. }
  68275. ++totalLines;
  68276. if (! justification.testFlags (Justification::left))
  68277. {
  68278. int totalW = getWidth();
  68279. for (i = totalLines; --i >= 0;)
  68280. {
  68281. const int lineW = getLineWidth (i);
  68282. int dx = 0;
  68283. if (justification.testFlags (Justification::horizontallyCentred))
  68284. dx = (totalW - lineW) / 2;
  68285. else if (justification.testFlags (Justification::right))
  68286. dx = totalW - lineW;
  68287. for (int j = tokens.size(); --j >= 0;)
  68288. {
  68289. TextLayoutToken* const t = (TextLayoutToken*)tokens.getUnchecked(j);
  68290. if (t->line == i)
  68291. t->x += dx;
  68292. }
  68293. }
  68294. }
  68295. }
  68296. }
  68297. int TextLayout::getLineWidth (const int lineNumber) const throw()
  68298. {
  68299. int maxW = 0;
  68300. for (int i = tokens.size(); --i >= 0;)
  68301. {
  68302. const TextLayoutToken* const t = (TextLayoutToken*) tokens.getUnchecked(i);
  68303. if (t->line == lineNumber && ! t->isWhitespace)
  68304. maxW = jmax (maxW, t->x + t->w);
  68305. }
  68306. return maxW;
  68307. }
  68308. int TextLayout::getWidth() const throw()
  68309. {
  68310. int maxW = 0;
  68311. for (int i = tokens.size(); --i >= 0;)
  68312. {
  68313. const TextLayoutToken* const t = (TextLayoutToken*) tokens.getUnchecked(i);
  68314. if (! t->isWhitespace)
  68315. maxW = jmax (maxW, t->x + t->w);
  68316. }
  68317. return maxW;
  68318. }
  68319. int TextLayout::getHeight() const throw()
  68320. {
  68321. int maxH = 0;
  68322. for (int i = tokens.size(); --i >= 0;)
  68323. {
  68324. const TextLayoutToken* const t = (TextLayoutToken*) tokens.getUnchecked(i);
  68325. if (! t->isWhitespace)
  68326. maxH = jmax (maxH, t->y + t->h);
  68327. }
  68328. return maxH;
  68329. }
  68330. void TextLayout::draw (Graphics& g,
  68331. const int xOffset,
  68332. const int yOffset) const throw()
  68333. {
  68334. for (int i = tokens.size(); --i >= 0;)
  68335. ((TextLayoutToken*) tokens.getUnchecked(i))->draw (g, xOffset, yOffset);
  68336. }
  68337. void TextLayout::drawWithin (Graphics& g,
  68338. int x, int y, int w, int h,
  68339. const Justification& justification) const throw()
  68340. {
  68341. justification.applyToRectangle (x, y, getWidth(), getHeight(),
  68342. x, y, w, h);
  68343. draw (g, x, y);
  68344. }
  68345. END_JUCE_NAMESPACE
  68346. /********* End of inlined file: juce_TextLayout.cpp *********/
  68347. /********* Start of inlined file: juce_Typeface.cpp *********/
  68348. BEGIN_JUCE_NAMESPACE
  68349. TypefaceGlyphInfo::TypefaceGlyphInfo (const juce_wchar character_,
  68350. const Path& shape,
  68351. const float horizontalSeparation,
  68352. Typeface* const typeface_) throw()
  68353. : character (character_),
  68354. path (shape),
  68355. width (horizontalSeparation),
  68356. typeface (typeface_)
  68357. {
  68358. }
  68359. TypefaceGlyphInfo::~TypefaceGlyphInfo() throw()
  68360. {
  68361. }
  68362. float TypefaceGlyphInfo::getHorizontalSpacing (const juce_wchar subsequentCharacter) const throw()
  68363. {
  68364. if (subsequentCharacter != 0)
  68365. {
  68366. const KerningPair* const pairs = (const KerningPair*) kerningPairs.getData();
  68367. const int numPairs = getNumKerningPairs();
  68368. for (int i = 0; i < numPairs; ++i)
  68369. if (pairs [i].character2 == subsequentCharacter)
  68370. return width + pairs [i].kerningAmount;
  68371. }
  68372. return width;
  68373. }
  68374. void TypefaceGlyphInfo::addKerningPair (const juce_wchar subsequentCharacter,
  68375. const float extraKerningAmount) throw()
  68376. {
  68377. const int numPairs = getNumKerningPairs();
  68378. kerningPairs.setSize ((numPairs + 1) * sizeof (KerningPair));
  68379. KerningPair& p = getKerningPair (numPairs);
  68380. p.character2 = subsequentCharacter;
  68381. p.kerningAmount = extraKerningAmount;
  68382. }
  68383. TypefaceGlyphInfo::KerningPair& TypefaceGlyphInfo::getKerningPair (const int index) const throw()
  68384. {
  68385. return ((KerningPair*) kerningPairs.getData()) [index];
  68386. }
  68387. int TypefaceGlyphInfo::getNumKerningPairs() const throw()
  68388. {
  68389. return kerningPairs.getSize() / sizeof (KerningPair);
  68390. }
  68391. const tchar* Typeface::defaultTypefaceNameSans = T("<Sans-Serif>");
  68392. const tchar* Typeface::defaultTypefaceNameSerif = T("<Serif>");
  68393. const tchar* Typeface::defaultTypefaceNameMono = T("<Monospaced>");
  68394. Typeface::Typeface() throw()
  68395. : hash (0),
  68396. isFullyPopulated (false)
  68397. {
  68398. zeromem (lookupTable, sizeof (lookupTable));
  68399. }
  68400. Typeface::Typeface (const Typeface& other)
  68401. : typefaceName (other.typefaceName),
  68402. ascent (other.ascent),
  68403. bold (other.bold),
  68404. italic (other.italic),
  68405. isFullyPopulated (other.isFullyPopulated),
  68406. defaultCharacter (other.defaultCharacter)
  68407. {
  68408. zeromem (lookupTable, sizeof (lookupTable));
  68409. for (int i = 0; i < other.glyphs.size(); ++i)
  68410. addGlyphCopy ((const TypefaceGlyphInfo*) other.glyphs.getUnchecked(i));
  68411. updateHashCode();
  68412. }
  68413. Typeface::Typeface (const String& faceName,
  68414. const bool bold,
  68415. const bool italic)
  68416. : isFullyPopulated (false)
  68417. {
  68418. zeromem (lookupTable, sizeof (lookupTable));
  68419. initialiseTypefaceCharacteristics (faceName, bold, italic, false);
  68420. updateHashCode();
  68421. }
  68422. Typeface::~Typeface()
  68423. {
  68424. clear();
  68425. }
  68426. const Typeface& Typeface::operator= (const Typeface& other) throw()
  68427. {
  68428. if (this != &other)
  68429. {
  68430. clear();
  68431. typefaceName = other.typefaceName;
  68432. ascent = other.ascent;
  68433. bold = other.bold;
  68434. italic = other.italic;
  68435. isFullyPopulated = other.isFullyPopulated;
  68436. defaultCharacter = other.defaultCharacter;
  68437. for (int i = 0; i < other.glyphs.size(); ++i)
  68438. addGlyphCopy ((const TypefaceGlyphInfo*) other.glyphs.getUnchecked(i));
  68439. updateHashCode();
  68440. }
  68441. return *this;
  68442. }
  68443. void Typeface::updateHashCode() throw()
  68444. {
  68445. hash = typefaceName.hashCode();
  68446. if (bold)
  68447. hash ^= 0xffff;
  68448. if (italic)
  68449. hash ^= 0xffff0000;
  68450. }
  68451. void Typeface::clear() throw()
  68452. {
  68453. zeromem (lookupTable, sizeof (lookupTable));
  68454. typefaceName = String::empty;
  68455. bold = false;
  68456. italic = false;
  68457. for (int i = glyphs.size(); --i >= 0;)
  68458. {
  68459. TypefaceGlyphInfo* const g = (TypefaceGlyphInfo*) (glyphs.getUnchecked(i));
  68460. delete g;
  68461. }
  68462. glyphs.clear();
  68463. updateHashCode();
  68464. }
  68465. Typeface::Typeface (InputStream& serialisedTypefaceStream)
  68466. {
  68467. zeromem (lookupTable, sizeof (lookupTable));
  68468. isFullyPopulated = true;
  68469. GZIPDecompressorInputStream gzin (&serialisedTypefaceStream, false);
  68470. BufferedInputStream in (&gzin, 32768, false);
  68471. typefaceName = in.readString();
  68472. bold = in.readBool();
  68473. italic = in.readBool();
  68474. ascent = in.readFloat();
  68475. defaultCharacter = (juce_wchar) in.readShort();
  68476. int i, numChars = in.readInt();
  68477. for (i = 0; i < numChars; ++i)
  68478. {
  68479. const juce_wchar c = (juce_wchar) in.readShort();
  68480. const float width = in.readFloat();
  68481. Path p;
  68482. p.loadPathFromStream (in);
  68483. addGlyph (c, p, width);
  68484. }
  68485. const int numKerningPairs = in.readInt();
  68486. for (i = 0; i < numKerningPairs; ++i)
  68487. {
  68488. const juce_wchar char1 = (juce_wchar) in.readShort();
  68489. const juce_wchar char2 = (juce_wchar) in.readShort();
  68490. addKerningPair (char1, char2, in.readFloat());
  68491. }
  68492. updateHashCode();
  68493. }
  68494. void Typeface::serialise (OutputStream& outputStream)
  68495. {
  68496. GZIPCompressorOutputStream out (&outputStream);
  68497. out.writeString (typefaceName);
  68498. out.writeBool (bold);
  68499. out.writeBool (italic);
  68500. out.writeFloat (ascent);
  68501. out.writeShort ((short) (unsigned short) defaultCharacter);
  68502. out.writeInt (glyphs.size());
  68503. int i, numKerningPairs = 0;
  68504. for (i = 0; i < glyphs.size(); ++i)
  68505. {
  68506. const TypefaceGlyphInfo& g = *(const TypefaceGlyphInfo*)(glyphs.getUnchecked (i));
  68507. out.writeShort ((short) (unsigned short) g.character);
  68508. out.writeFloat (g.width);
  68509. g.path.writePathToStream (out);
  68510. numKerningPairs += g.getNumKerningPairs();
  68511. }
  68512. out.writeInt (numKerningPairs);
  68513. for (i = 0; i < glyphs.size(); ++i)
  68514. {
  68515. const TypefaceGlyphInfo& g = *(const TypefaceGlyphInfo*)(glyphs.getUnchecked (i));
  68516. for (int j = 0; j < g.getNumKerningPairs(); ++j)
  68517. {
  68518. const TypefaceGlyphInfo::KerningPair& p = g.getKerningPair (j);
  68519. out.writeShort ((short) (unsigned short) g.character);
  68520. out.writeShort ((short) (unsigned short) p.character2);
  68521. out.writeFloat (p.kerningAmount);
  68522. }
  68523. }
  68524. }
  68525. const Path* Typeface::getOutlineForGlyph (const juce_wchar character) throw()
  68526. {
  68527. const TypefaceGlyphInfo* const g = (const TypefaceGlyphInfo*) getGlyph (character);
  68528. if (g != 0)
  68529. return &(g->path);
  68530. else
  68531. return 0;
  68532. }
  68533. const TypefaceGlyphInfo* Typeface::getGlyph (const juce_wchar character) throw()
  68534. {
  68535. if (((unsigned int) character) < 128 && lookupTable [character] > 0)
  68536. return (const TypefaceGlyphInfo*) glyphs [(int) lookupTable [character]];
  68537. for (int i = 0; i < glyphs.size(); ++i)
  68538. {
  68539. const TypefaceGlyphInfo* const g = (const TypefaceGlyphInfo*) glyphs.getUnchecked(i);
  68540. if (g->character == character)
  68541. return g;
  68542. }
  68543. if ((! isFullyPopulated)
  68544. && findAndAddSystemGlyph (character))
  68545. {
  68546. for (int i = 0; i < glyphs.size(); ++i)
  68547. {
  68548. const TypefaceGlyphInfo* const g = (const TypefaceGlyphInfo*) glyphs.getUnchecked(i);
  68549. if (g->character == character)
  68550. return g;
  68551. }
  68552. }
  68553. if (CharacterFunctions::isWhitespace (character) && character != L' ')
  68554. {
  68555. const TypefaceGlyphInfo* spaceGlyph = getGlyph (L' ');
  68556. if (spaceGlyph != 0)
  68557. {
  68558. // Add a copy of the empty glyph, mapped onto this character
  68559. addGlyph (character, spaceGlyph->getPath(), spaceGlyph->getHorizontalSpacing (0));
  68560. spaceGlyph = (const TypefaceGlyphInfo*) glyphs [(int) lookupTable [character]];
  68561. }
  68562. return spaceGlyph;
  68563. }
  68564. else if (character != defaultCharacter)
  68565. {
  68566. const Font fallbackFont (Font::getFallbackFontName(), 10, 0);
  68567. Typeface* const fallbackTypeface = fallbackFont.getTypeface();
  68568. if (fallbackTypeface != 0 && fallbackTypeface != this)
  68569. return fallbackTypeface->getGlyph (character);
  68570. return getGlyph (defaultCharacter);
  68571. }
  68572. return 0;
  68573. }
  68574. void Typeface::addGlyph (const juce_wchar character,
  68575. const Path& path,
  68576. const float horizontalSpacing) throw()
  68577. {
  68578. #ifdef JUCE_DEBUG
  68579. for (int i = 0; i < glyphs.size(); ++i)
  68580. {
  68581. const TypefaceGlyphInfo* const g = (const TypefaceGlyphInfo*) glyphs.getUnchecked(i);
  68582. if (g->character == character)
  68583. jassertfalse;
  68584. }
  68585. #endif
  68586. if (((unsigned int) character) < 128)
  68587. lookupTable [character] = (short) glyphs.size();
  68588. glyphs.add (new TypefaceGlyphInfo (character,
  68589. path,
  68590. horizontalSpacing,
  68591. this));
  68592. }
  68593. void Typeface::addGlyphCopy (const TypefaceGlyphInfo* const glyphInfoToCopy) throw()
  68594. {
  68595. if (glyphInfoToCopy != 0)
  68596. {
  68597. if (glyphInfoToCopy->character > 0 && glyphInfoToCopy->character < 128)
  68598. lookupTable [glyphInfoToCopy->character] = (short) glyphs.size();
  68599. TypefaceGlyphInfo* const newOne
  68600. = new TypefaceGlyphInfo (glyphInfoToCopy->character,
  68601. glyphInfoToCopy->path,
  68602. glyphInfoToCopy->width,
  68603. this);
  68604. newOne->kerningPairs = glyphInfoToCopy->kerningPairs;
  68605. glyphs.add (newOne);
  68606. }
  68607. }
  68608. void Typeface::addKerningPair (const juce_wchar char1,
  68609. const juce_wchar char2,
  68610. const float extraAmount) throw()
  68611. {
  68612. TypefaceGlyphInfo* const g = (TypefaceGlyphInfo*) getGlyph (char1);
  68613. if (g != 0)
  68614. g->addKerningPair (char2, extraAmount);
  68615. }
  68616. void Typeface::setName (const String& name) throw()
  68617. {
  68618. typefaceName = name;
  68619. updateHashCode();
  68620. }
  68621. void Typeface::setAscent (const float newAscent) throw()
  68622. {
  68623. ascent = newAscent;
  68624. }
  68625. void Typeface::setDefaultCharacter (const juce_wchar newDefaultCharacter) throw()
  68626. {
  68627. defaultCharacter = newDefaultCharacter;
  68628. }
  68629. void Typeface::setBold (const bool shouldBeBold) throw()
  68630. {
  68631. bold = shouldBeBold;
  68632. updateHashCode();
  68633. }
  68634. void Typeface::setItalic (const bool shouldBeItalic) throw()
  68635. {
  68636. italic = shouldBeItalic;
  68637. updateHashCode();
  68638. }
  68639. class TypefaceCache;
  68640. static TypefaceCache* typefaceCacheInstance = 0;
  68641. void clearUpDefaultFontNames() throw(); // in juce_LookAndFeel.cpp
  68642. class TypefaceCache : private DeletedAtShutdown
  68643. {
  68644. private:
  68645. struct CachedFace
  68646. {
  68647. CachedFace() throw()
  68648. : lastUsageCount (0),
  68649. flags (0)
  68650. {
  68651. }
  68652. String typefaceName;
  68653. int lastUsageCount;
  68654. int flags;
  68655. Typeface::Ptr typeFace;
  68656. };
  68657. int counter;
  68658. OwnedArray <CachedFace> faces;
  68659. TypefaceCache (const TypefaceCache&);
  68660. const TypefaceCache& operator= (const TypefaceCache&);
  68661. public:
  68662. TypefaceCache (int numToCache = 10)
  68663. : counter (1),
  68664. faces (2)
  68665. {
  68666. while (--numToCache >= 0)
  68667. {
  68668. CachedFace* const face = new CachedFace();
  68669. face->typeFace = new Typeface();
  68670. faces.add (face);
  68671. }
  68672. }
  68673. ~TypefaceCache()
  68674. {
  68675. faces.clear();
  68676. jassert (typefaceCacheInstance == this);
  68677. typefaceCacheInstance = 0;
  68678. clearUpDefaultFontNames();
  68679. }
  68680. static TypefaceCache* getInstance() throw()
  68681. {
  68682. if (typefaceCacheInstance == 0)
  68683. typefaceCacheInstance = new TypefaceCache();
  68684. return typefaceCacheInstance;
  68685. }
  68686. const Typeface::Ptr findTypefaceFor (const Font& font) throw()
  68687. {
  68688. const int flags = font.getStyleFlags() & (Font::bold | Font::italic);
  68689. int i;
  68690. for (i = faces.size(); --i >= 0;)
  68691. {
  68692. CachedFace* const face = faces.getUnchecked(i);
  68693. if (face->flags == flags
  68694. && face->typefaceName == font.getTypefaceName())
  68695. {
  68696. face->lastUsageCount = ++counter;
  68697. return face->typeFace;
  68698. }
  68699. }
  68700. int replaceIndex = 0;
  68701. int bestLastUsageCount = INT_MAX;
  68702. for (i = faces.size(); --i >= 0;)
  68703. {
  68704. const int lu = faces.getUnchecked(i)->lastUsageCount;
  68705. if (bestLastUsageCount > lu)
  68706. {
  68707. bestLastUsageCount = lu;
  68708. replaceIndex = i;
  68709. }
  68710. }
  68711. CachedFace* const face = faces.getUnchecked (replaceIndex);
  68712. face->typefaceName = font.getTypefaceName();
  68713. face->flags = flags;
  68714. face->lastUsageCount = ++counter;
  68715. face->typeFace = LookAndFeel::getDefaultLookAndFeel().getTypefaceForFont (font);
  68716. return face->typeFace;
  68717. }
  68718. };
  68719. const Typeface::Ptr Typeface::getTypefaceFor (const Font& font) throw()
  68720. {
  68721. return TypefaceCache::getInstance()->findTypefaceFor (font);
  68722. }
  68723. END_JUCE_NAMESPACE
  68724. /********* End of inlined file: juce_Typeface.cpp *********/
  68725. /********* Start of inlined file: juce_AffineTransform.cpp *********/
  68726. BEGIN_JUCE_NAMESPACE
  68727. AffineTransform::AffineTransform() throw()
  68728. : mat00 (1.0f),
  68729. mat01 (0),
  68730. mat02 (0),
  68731. mat10 (0),
  68732. mat11 (1.0f),
  68733. mat12 (0)
  68734. {
  68735. }
  68736. AffineTransform::AffineTransform (const AffineTransform& other) throw()
  68737. : mat00 (other.mat00),
  68738. mat01 (other.mat01),
  68739. mat02 (other.mat02),
  68740. mat10 (other.mat10),
  68741. mat11 (other.mat11),
  68742. mat12 (other.mat12)
  68743. {
  68744. }
  68745. AffineTransform::AffineTransform (const float mat00_,
  68746. const float mat01_,
  68747. const float mat02_,
  68748. const float mat10_,
  68749. const float mat11_,
  68750. const float mat12_) throw()
  68751. : mat00 (mat00_),
  68752. mat01 (mat01_),
  68753. mat02 (mat02_),
  68754. mat10 (mat10_),
  68755. mat11 (mat11_),
  68756. mat12 (mat12_)
  68757. {
  68758. }
  68759. const AffineTransform& AffineTransform::operator= (const AffineTransform& other) throw()
  68760. {
  68761. mat00 = other.mat00;
  68762. mat01 = other.mat01;
  68763. mat02 = other.mat02;
  68764. mat10 = other.mat10;
  68765. mat11 = other.mat11;
  68766. mat12 = other.mat12;
  68767. return *this;
  68768. }
  68769. bool AffineTransform::operator== (const AffineTransform& other) const throw()
  68770. {
  68771. return mat00 == other.mat00
  68772. && mat01 == other.mat01
  68773. && mat02 == other.mat02
  68774. && mat10 == other.mat10
  68775. && mat11 == other.mat11
  68776. && mat12 == other.mat12;
  68777. }
  68778. bool AffineTransform::operator!= (const AffineTransform& other) const throw()
  68779. {
  68780. return ! operator== (other);
  68781. }
  68782. bool AffineTransform::isIdentity() const throw()
  68783. {
  68784. return (mat01 == 0)
  68785. && (mat02 == 0)
  68786. && (mat10 == 0)
  68787. && (mat12 == 0)
  68788. && (mat00 == 1.0f)
  68789. && (mat11 == 1.0f);
  68790. }
  68791. const AffineTransform AffineTransform::identity;
  68792. const AffineTransform AffineTransform::followedBy (const AffineTransform& other) const throw()
  68793. {
  68794. return AffineTransform (other.mat00 * mat00 + other.mat01 * mat10,
  68795. other.mat00 * mat01 + other.mat01 * mat11,
  68796. other.mat00 * mat02 + other.mat01 * mat12 + other.mat02,
  68797. other.mat10 * mat00 + other.mat11 * mat10,
  68798. other.mat10 * mat01 + other.mat11 * mat11,
  68799. other.mat10 * mat02 + other.mat11 * mat12 + other.mat12);
  68800. }
  68801. const AffineTransform AffineTransform::followedBy (const float omat00,
  68802. const float omat01,
  68803. const float omat02,
  68804. const float omat10,
  68805. const float omat11,
  68806. const float omat12) const throw()
  68807. {
  68808. return AffineTransform (omat00 * mat00 + omat01 * mat10,
  68809. omat00 * mat01 + omat01 * mat11,
  68810. omat00 * mat02 + omat01 * mat12 + omat02,
  68811. omat10 * mat00 + omat11 * mat10,
  68812. omat10 * mat01 + omat11 * mat11,
  68813. omat10 * mat02 + omat11 * mat12 + omat12);
  68814. }
  68815. const AffineTransform AffineTransform::translated (const float dx,
  68816. const float dy) const throw()
  68817. {
  68818. return followedBy (1.0f, 0, dx,
  68819. 0, 1.0f, dy);
  68820. }
  68821. const AffineTransform AffineTransform::translation (const float dx,
  68822. const float dy) throw()
  68823. {
  68824. return AffineTransform (1.0f, 0, dx,
  68825. 0, 1.0f, dy);
  68826. }
  68827. const AffineTransform AffineTransform::rotated (const float rad) const throw()
  68828. {
  68829. const float cosRad = cosf (rad);
  68830. const float sinRad = sinf (rad);
  68831. return followedBy (cosRad, -sinRad, 0,
  68832. sinRad, cosRad, 0);
  68833. }
  68834. const AffineTransform AffineTransform::rotation (const float rad) throw()
  68835. {
  68836. const float cosRad = cosf (rad);
  68837. const float sinRad = sinf (rad);
  68838. return AffineTransform (cosRad, -sinRad, 0,
  68839. sinRad, cosRad, 0);
  68840. }
  68841. const AffineTransform AffineTransform::rotated (const float angle,
  68842. const float pivotX,
  68843. const float pivotY) const throw()
  68844. {
  68845. return translated (-pivotX, -pivotY)
  68846. .rotated (angle)
  68847. .translated (pivotX, pivotY);
  68848. }
  68849. const AffineTransform AffineTransform::rotation (const float angle,
  68850. const float pivotX,
  68851. const float pivotY) throw()
  68852. {
  68853. return translation (-pivotX, -pivotY)
  68854. .rotated (angle)
  68855. .translated (pivotX, pivotY);
  68856. }
  68857. const AffineTransform AffineTransform::scaled (const float factorX,
  68858. const float factorY) const throw()
  68859. {
  68860. return followedBy (factorX, 0, 0,
  68861. 0, factorY, 0);
  68862. }
  68863. const AffineTransform AffineTransform::scale (const float factorX,
  68864. const float factorY) throw()
  68865. {
  68866. return AffineTransform (factorX, 0, 0,
  68867. 0, factorY, 0);
  68868. }
  68869. const AffineTransform AffineTransform::sheared (const float shearX,
  68870. const float shearY) const throw()
  68871. {
  68872. return followedBy (1.0f, shearX, 0,
  68873. shearY, 1.0f, 0);
  68874. }
  68875. const AffineTransform AffineTransform::inverted() const throw()
  68876. {
  68877. double determinant = (mat00 * mat11 - mat10 * mat01);
  68878. if (determinant != 0.0)
  68879. {
  68880. determinant = 1.0 / determinant;
  68881. const float dst00 = (float) (mat11 * determinant);
  68882. const float dst10 = (float) (-mat10 * determinant);
  68883. const float dst01 = (float) (-mat01 * determinant);
  68884. const float dst11 = (float) (mat00 * determinant);
  68885. return AffineTransform (dst00, dst01, -mat02 * dst00 - mat12 * dst01,
  68886. dst10, dst11, -mat02 * dst10 - mat12 * dst11);
  68887. }
  68888. else
  68889. {
  68890. // singularity..
  68891. return *this;
  68892. }
  68893. }
  68894. bool AffineTransform::isSingularity() const throw()
  68895. {
  68896. return (mat00 * mat11 - mat10 * mat01) == 0.0;
  68897. }
  68898. void AffineTransform::transformPoint (float& x,
  68899. float& y) const throw()
  68900. {
  68901. const float oldX = x;
  68902. x = mat00 * oldX + mat01 * y + mat02;
  68903. y = mat10 * oldX + mat11 * y + mat12;
  68904. }
  68905. void AffineTransform::transformPoint (double& x,
  68906. double& y) const throw()
  68907. {
  68908. const double oldX = x;
  68909. x = mat00 * oldX + mat01 * y + mat02;
  68910. y = mat10 * oldX + mat11 * y + mat12;
  68911. }
  68912. END_JUCE_NAMESPACE
  68913. /********* End of inlined file: juce_AffineTransform.cpp *********/
  68914. /********* Start of inlined file: juce_BorderSize.cpp *********/
  68915. BEGIN_JUCE_NAMESPACE
  68916. BorderSize::BorderSize() throw()
  68917. : top (0),
  68918. left (0),
  68919. bottom (0),
  68920. right (0)
  68921. {
  68922. }
  68923. BorderSize::BorderSize (const BorderSize& other) throw()
  68924. : top (other.top),
  68925. left (other.left),
  68926. bottom (other.bottom),
  68927. right (other.right)
  68928. {
  68929. }
  68930. BorderSize::BorderSize (const int topGap,
  68931. const int leftGap,
  68932. const int bottomGap,
  68933. const int rightGap) throw()
  68934. : top (topGap),
  68935. left (leftGap),
  68936. bottom (bottomGap),
  68937. right (rightGap)
  68938. {
  68939. }
  68940. BorderSize::BorderSize (const int allGaps) throw()
  68941. : top (allGaps),
  68942. left (allGaps),
  68943. bottom (allGaps),
  68944. right (allGaps)
  68945. {
  68946. }
  68947. BorderSize::~BorderSize() throw()
  68948. {
  68949. }
  68950. void BorderSize::setTop (const int newTopGap) throw()
  68951. {
  68952. top = newTopGap;
  68953. }
  68954. void BorderSize::setLeft (const int newLeftGap) throw()
  68955. {
  68956. left = newLeftGap;
  68957. }
  68958. void BorderSize::setBottom (const int newBottomGap) throw()
  68959. {
  68960. bottom = newBottomGap;
  68961. }
  68962. void BorderSize::setRight (const int newRightGap) throw()
  68963. {
  68964. right = newRightGap;
  68965. }
  68966. const Rectangle BorderSize::subtractedFrom (const Rectangle& r) const throw()
  68967. {
  68968. return Rectangle (r.getX() + left,
  68969. r.getY() + top,
  68970. r.getWidth() - (left + right),
  68971. r.getHeight() - (top + bottom));
  68972. }
  68973. void BorderSize::subtractFrom (Rectangle& r) const throw()
  68974. {
  68975. r.setBounds (r.getX() + left,
  68976. r.getY() + top,
  68977. r.getWidth() - (left + right),
  68978. r.getHeight() - (top + bottom));
  68979. }
  68980. const Rectangle BorderSize::addedTo (const Rectangle& r) const throw()
  68981. {
  68982. return Rectangle (r.getX() - left,
  68983. r.getY() - top,
  68984. r.getWidth() + (left + right),
  68985. r.getHeight() + (top + bottom));
  68986. }
  68987. void BorderSize::addTo (Rectangle& r) const throw()
  68988. {
  68989. r.setBounds (r.getX() - left,
  68990. r.getY() - top,
  68991. r.getWidth() + (left + right),
  68992. r.getHeight() + (top + bottom));
  68993. }
  68994. bool BorderSize::operator== (const BorderSize& other) const throw()
  68995. {
  68996. return top == other.top
  68997. && left == other.left
  68998. && bottom == other.bottom
  68999. && right == other.right;
  69000. }
  69001. bool BorderSize::operator!= (const BorderSize& other) const throw()
  69002. {
  69003. return ! operator== (other);
  69004. }
  69005. END_JUCE_NAMESPACE
  69006. /********* End of inlined file: juce_BorderSize.cpp *********/
  69007. /********* Start of inlined file: juce_Line.cpp *********/
  69008. BEGIN_JUCE_NAMESPACE
  69009. static bool juce_lineIntersection (const float x1, const float y1,
  69010. const float x2, const float y2,
  69011. const float x3, const float y3,
  69012. const float x4, const float y4,
  69013. float& intersectionX,
  69014. float& intersectionY) throw()
  69015. {
  69016. if (x2 != x3 || y2 != y3)
  69017. {
  69018. const float dx1 = x2 - x1;
  69019. const float dy1 = y2 - y1;
  69020. const float dx2 = x4 - x3;
  69021. const float dy2 = y4 - y3;
  69022. const float divisor = dx1 * dy2 - dx2 * dy1;
  69023. if (divisor == 0)
  69024. {
  69025. if (! ((dx1 == 0 && dy1 == 0) || (dx2 == 0 && dy2 == 0)))
  69026. {
  69027. if (dy1 == 0 && dy2 != 0)
  69028. {
  69029. const float along = (y1 - y3) / dy2;
  69030. intersectionX = x3 + along * dx2;
  69031. intersectionY = y1;
  69032. return along >= 0 && along <= 1.0f;
  69033. }
  69034. else if (dy2 == 0 && dy1 != 0)
  69035. {
  69036. const float along = (y3 - y1) / dy1;
  69037. intersectionX = x1 + along * dx1;
  69038. intersectionY = y3;
  69039. return along >= 0 && along <= 1.0f;
  69040. }
  69041. else if (dx1 == 0 && dx2 != 0)
  69042. {
  69043. const float along = (x1 - x3) / dx2;
  69044. intersectionX = x1;
  69045. intersectionY = y3 + along * dy2;
  69046. return along >= 0 && along <= 1.0f;
  69047. }
  69048. else if (dx2 == 0 && dx1 != 0)
  69049. {
  69050. const float along = (x3 - x1) / dx1;
  69051. intersectionX = x3;
  69052. intersectionY = y1 + along * dy1;
  69053. return along >= 0 && along <= 1.0f;
  69054. }
  69055. }
  69056. intersectionX = 0.5f * (x2 + x3);
  69057. intersectionY = 0.5f * (y2 + y3);
  69058. return false;
  69059. }
  69060. const float along1 = ((y1 - y3) * dx2 - (x1 - x3) * dy2) / divisor;
  69061. intersectionX = x1 + along1 * dx1;
  69062. intersectionY = y1 + along1 * dy1;
  69063. if (along1 < 0 || along1 > 1.0f)
  69064. return false;
  69065. const float along2 = ((y1 - y3) * dx1 - (x1 - x3) * dy1) / divisor;
  69066. return along2 >= 0 && along2 <= 1.0f;
  69067. }
  69068. intersectionX = x2;
  69069. intersectionY = y2;
  69070. return true;
  69071. }
  69072. Line::Line() throw()
  69073. : startX (0.0f),
  69074. startY (0.0f),
  69075. endX (0.0f),
  69076. endY (0.0f)
  69077. {
  69078. }
  69079. Line::Line (const Line& other) throw()
  69080. : startX (other.startX),
  69081. startY (other.startY),
  69082. endX (other.endX),
  69083. endY (other.endY)
  69084. {
  69085. }
  69086. Line::Line (const float startX_, const float startY_,
  69087. const float endX_, const float endY_) throw()
  69088. : startX (startX_),
  69089. startY (startY_),
  69090. endX (endX_),
  69091. endY (endY_)
  69092. {
  69093. }
  69094. Line::Line (const Point& start,
  69095. const Point& end) throw()
  69096. : startX (start.getX()),
  69097. startY (start.getY()),
  69098. endX (end.getX()),
  69099. endY (end.getY())
  69100. {
  69101. }
  69102. const Line& Line::operator= (const Line& other) throw()
  69103. {
  69104. startX = other.startX;
  69105. startY = other.startY;
  69106. endX = other.endX;
  69107. endY = other.endY;
  69108. return *this;
  69109. }
  69110. Line::~Line() throw()
  69111. {
  69112. }
  69113. const Point Line::getStart() const throw()
  69114. {
  69115. return Point (startX, startY);
  69116. }
  69117. const Point Line::getEnd() const throw()
  69118. {
  69119. return Point (endX, endY);
  69120. }
  69121. void Line::setStart (const float newStartX,
  69122. const float newStartY) throw()
  69123. {
  69124. startX = newStartX;
  69125. startY = newStartY;
  69126. }
  69127. void Line::setStart (const Point& newStart) throw()
  69128. {
  69129. startX = newStart.getX();
  69130. startY = newStart.getY();
  69131. }
  69132. void Line::setEnd (const float newEndX,
  69133. const float newEndY) throw()
  69134. {
  69135. endX = newEndX;
  69136. endY = newEndY;
  69137. }
  69138. void Line::setEnd (const Point& newEnd) throw()
  69139. {
  69140. endX = newEnd.getX();
  69141. endY = newEnd.getY();
  69142. }
  69143. bool Line::operator== (const Line& other) const throw()
  69144. {
  69145. return startX == other.startX
  69146. && startY == other.startY
  69147. && endX == other.endX
  69148. && endY == other.endY;
  69149. }
  69150. bool Line::operator!= (const Line& other) const throw()
  69151. {
  69152. return startX != other.startX
  69153. || startY != other.startY
  69154. || endX != other.endX
  69155. || endY != other.endY;
  69156. }
  69157. void Line::applyTransform (const AffineTransform& transform) throw()
  69158. {
  69159. transform.transformPoint (startX, startY);
  69160. transform.transformPoint (endX, endY);
  69161. }
  69162. float Line::getLength() const throw()
  69163. {
  69164. return (float) juce_hypot (startX - endX,
  69165. startY - endY);
  69166. }
  69167. float Line::getAngle() const throw()
  69168. {
  69169. return atan2f (endX - startX,
  69170. endY - startY);
  69171. }
  69172. const Point Line::getPointAlongLine (const float distanceFromStart) const throw()
  69173. {
  69174. const float alpha = distanceFromStart / getLength();
  69175. return Point (startX + (endX - startX) * alpha,
  69176. startY + (endY - startY) * alpha);
  69177. }
  69178. const Point Line::getPointAlongLine (const float offsetX,
  69179. const float offsetY) const throw()
  69180. {
  69181. const float dx = endX - startX;
  69182. const float dy = endY - startY;
  69183. const double length = juce_hypot (dx, dy);
  69184. if (length == 0)
  69185. return Point (startX, startY);
  69186. else
  69187. return Point (startX + (float) (((dx * offsetX) - (dy * offsetY)) / length),
  69188. startY + (float) (((dy * offsetX) + (dx * offsetY)) / length));
  69189. }
  69190. const Point Line::getPointAlongLineProportionally (const float alpha) const throw()
  69191. {
  69192. return Point (startX + (endX - startX) * alpha,
  69193. startY + (endY - startY) * alpha);
  69194. }
  69195. float Line::getDistanceFromLine (const float x,
  69196. const float y) const throw()
  69197. {
  69198. const double dx = endX - startX;
  69199. const double dy = endY - startY;
  69200. const double length = dx * dx + dy * dy;
  69201. if (length > 0)
  69202. {
  69203. const double prop = ((x - startX) * dx + (y - startY) * dy) / length;
  69204. if (prop >= 0.0f && prop < 1.0f)
  69205. {
  69206. return (float) juce_hypot (x - (startX + prop * dx),
  69207. y - (startY + prop * dy));
  69208. }
  69209. }
  69210. return (float) jmin (juce_hypot (x - startX, y - startY),
  69211. juce_hypot (x - endX, y - endY));
  69212. }
  69213. float Line::findNearestPointTo (const float x,
  69214. const float y) const throw()
  69215. {
  69216. const double dx = endX - startX;
  69217. const double dy = endY - startY;
  69218. const double length = dx * dx + dy * dy;
  69219. if (length <= 0.0)
  69220. return 0.0f;
  69221. return jlimit (0.0f, 1.0f,
  69222. (float) (((x - startX) * dx + (y - startY) * dy) / length));
  69223. }
  69224. const Line Line::withShortenedStart (const float distanceToShortenBy) const throw()
  69225. {
  69226. const float length = getLength();
  69227. return Line (getPointAlongLine (jmin (distanceToShortenBy, length)),
  69228. getEnd());
  69229. }
  69230. const Line Line::withShortenedEnd (const float distanceToShortenBy) const throw()
  69231. {
  69232. const float length = getLength();
  69233. return Line (getStart(),
  69234. getPointAlongLine (length - jmin (distanceToShortenBy, length)));
  69235. }
  69236. bool Line::clipToPath (const Path& path,
  69237. const bool keepSectionOutsidePath) throw()
  69238. {
  69239. const bool startInside = path.contains (startX, startY);
  69240. const bool endInside = path.contains (endX, endY);
  69241. if (startInside == endInside)
  69242. {
  69243. if (keepSectionOutsidePath != startInside)
  69244. {
  69245. // entirely outside the path
  69246. return false;
  69247. }
  69248. else
  69249. {
  69250. // entirely inside the path
  69251. startX = 0.0f;
  69252. startY = 0.0f;
  69253. endX = 0.0f;
  69254. endY = 0.0f;
  69255. return true;
  69256. }
  69257. }
  69258. else
  69259. {
  69260. bool changed = false;
  69261. PathFlatteningIterator iter (path, AffineTransform::identity);
  69262. while (iter.next())
  69263. {
  69264. float ix, iy;
  69265. if (intersects (Line (iter.x1, iter.y1,
  69266. iter.x2, iter.y2),
  69267. ix, iy))
  69268. {
  69269. if ((startInside && keepSectionOutsidePath)
  69270. || (endInside && ! keepSectionOutsidePath))
  69271. {
  69272. setStart (ix, iy);
  69273. }
  69274. else
  69275. {
  69276. setEnd (ix, iy);
  69277. }
  69278. changed = true;
  69279. }
  69280. }
  69281. return changed;
  69282. }
  69283. }
  69284. bool Line::intersects (const Line& line,
  69285. float& intersectionX,
  69286. float& intersectionY) const throw()
  69287. {
  69288. return juce_lineIntersection (startX, startY,
  69289. endX, endY,
  69290. line.startX, line.startY,
  69291. line.endX, line.endY,
  69292. intersectionX,
  69293. intersectionY);
  69294. }
  69295. bool Line::isVertical() const throw()
  69296. {
  69297. return startX == endX;
  69298. }
  69299. bool Line::isHorizontal() const throw()
  69300. {
  69301. return startY == endY;
  69302. }
  69303. bool Line::isPointAbove (const float x, const float y) const throw()
  69304. {
  69305. return startX != endX
  69306. && y < ((endY - startY) * (x - startX)) / (endX - startX) + startY;
  69307. }
  69308. END_JUCE_NAMESPACE
  69309. /********* End of inlined file: juce_Line.cpp *********/
  69310. /********* Start of inlined file: juce_Path.cpp *********/
  69311. BEGIN_JUCE_NAMESPACE
  69312. // tests that some co-ords aren't NaNs
  69313. #define CHECK_COORDS_ARE_VALID(x, y) \
  69314. jassert (x == x && y == y);
  69315. const float Path::lineMarker = 100001.0f;
  69316. const float Path::moveMarker = 100002.0f;
  69317. const float Path::quadMarker = 100003.0f;
  69318. const float Path::cubicMarker = 100004.0f;
  69319. const float Path::closeSubPathMarker = 100005.0f;
  69320. static const int defaultGranularity = 32;
  69321. Path::Path() throw()
  69322. : ArrayAllocationBase <float> (defaultGranularity),
  69323. numElements (0),
  69324. pathXMin (0),
  69325. pathXMax (0),
  69326. pathYMin (0),
  69327. pathYMax (0),
  69328. useNonZeroWinding (true)
  69329. {
  69330. }
  69331. Path::~Path() throw()
  69332. {
  69333. }
  69334. Path::Path (const Path& other) throw()
  69335. : ArrayAllocationBase <float> (defaultGranularity),
  69336. numElements (other.numElements),
  69337. pathXMin (other.pathXMin),
  69338. pathXMax (other.pathXMax),
  69339. pathYMin (other.pathYMin),
  69340. pathYMax (other.pathYMax),
  69341. useNonZeroWinding (other.useNonZeroWinding)
  69342. {
  69343. if (numElements > 0)
  69344. {
  69345. setAllocatedSize (numElements);
  69346. memcpy (elements, other.elements, numElements * sizeof (float));
  69347. }
  69348. }
  69349. const Path& Path::operator= (const Path& other) throw()
  69350. {
  69351. if (this != &other)
  69352. {
  69353. ensureAllocatedSize (other.numElements);
  69354. numElements = other.numElements;
  69355. pathXMin = other.pathXMin;
  69356. pathXMax = other.pathXMax;
  69357. pathYMin = other.pathYMin;
  69358. pathYMax = other.pathYMax;
  69359. useNonZeroWinding = other.useNonZeroWinding;
  69360. if (numElements > 0)
  69361. memcpy (elements, other.elements, numElements * sizeof (float));
  69362. }
  69363. return *this;
  69364. }
  69365. void Path::clear() throw()
  69366. {
  69367. numElements = 0;
  69368. pathXMin = 0;
  69369. pathYMin = 0;
  69370. pathYMax = 0;
  69371. pathXMax = 0;
  69372. }
  69373. void Path::swapWithPath (Path& other)
  69374. {
  69375. swapVariables <int> (this->numAllocated, other.numAllocated);
  69376. swapVariables <float*> (this->elements, other.elements);
  69377. swapVariables <int> (this->numElements, other.numElements);
  69378. swapVariables <float> (this->pathXMin, other.pathXMin);
  69379. swapVariables <float> (this->pathXMax, other.pathXMax);
  69380. swapVariables <float> (this->pathYMin, other.pathYMin);
  69381. swapVariables <float> (this->pathYMax, other.pathYMax);
  69382. swapVariables <bool> (this->useNonZeroWinding, other.useNonZeroWinding);
  69383. }
  69384. void Path::setUsingNonZeroWinding (const bool isNonZero) throw()
  69385. {
  69386. useNonZeroWinding = isNonZero;
  69387. }
  69388. void Path::scaleToFit (const float x, const float y, const float w, const float h,
  69389. const bool preserveProportions) throw()
  69390. {
  69391. applyTransform (getTransformToScaleToFit (x, y, w, h, preserveProportions));
  69392. }
  69393. bool Path::isEmpty() const throw()
  69394. {
  69395. int i = 0;
  69396. while (i < numElements)
  69397. {
  69398. const float type = elements [i++];
  69399. if (type == moveMarker)
  69400. {
  69401. i += 2;
  69402. }
  69403. else if (type == lineMarker
  69404. || type == quadMarker
  69405. || type == cubicMarker)
  69406. {
  69407. return false;
  69408. }
  69409. }
  69410. return true;
  69411. }
  69412. void Path::getBounds (float& x, float& y,
  69413. float& w, float& h) const throw()
  69414. {
  69415. x = pathXMin;
  69416. y = pathYMin;
  69417. w = pathXMax - pathXMin;
  69418. h = pathYMax - pathYMin;
  69419. }
  69420. void Path::getBoundsTransformed (const AffineTransform& transform,
  69421. float& x, float& y,
  69422. float& w, float& h) const throw()
  69423. {
  69424. float x1 = pathXMin;
  69425. float y1 = pathYMin;
  69426. transform.transformPoint (x1, y1);
  69427. float x2 = pathXMax;
  69428. float y2 = pathYMin;
  69429. transform.transformPoint (x2, y2);
  69430. float x3 = pathXMin;
  69431. float y3 = pathYMax;
  69432. transform.transformPoint (x3, y3);
  69433. float x4 = pathXMax;
  69434. float y4 = pathYMax;
  69435. transform.transformPoint (x4, y4);
  69436. x = jmin (x1, x2, x3, x4);
  69437. y = jmin (y1, y2, y3, y4);
  69438. w = jmax (x1, x2, x3, x4) - x;
  69439. h = jmax (y1, y2, y3, y4) - y;
  69440. }
  69441. void Path::startNewSubPath (const float x,
  69442. const float y) throw()
  69443. {
  69444. CHECK_COORDS_ARE_VALID (x, y);
  69445. if (numElements == 0)
  69446. {
  69447. pathXMin = pathXMax = x;
  69448. pathYMin = pathYMax = y;
  69449. }
  69450. else
  69451. {
  69452. pathXMin = jmin (pathXMin, x);
  69453. pathXMax = jmax (pathXMax, x);
  69454. pathYMin = jmin (pathYMin, y);
  69455. pathYMax = jmax (pathYMax, y);
  69456. }
  69457. ensureAllocatedSize (numElements + 3);
  69458. elements [numElements++] = moveMarker;
  69459. elements [numElements++] = x;
  69460. elements [numElements++] = y;
  69461. }
  69462. void Path::lineTo (const float x, const float y) throw()
  69463. {
  69464. CHECK_COORDS_ARE_VALID (x, y);
  69465. if (numElements == 0)
  69466. startNewSubPath (0, 0);
  69467. ensureAllocatedSize (numElements + 3);
  69468. elements [numElements++] = lineMarker;
  69469. elements [numElements++] = x;
  69470. elements [numElements++] = y;
  69471. pathXMin = jmin (pathXMin, x);
  69472. pathXMax = jmax (pathXMax, x);
  69473. pathYMin = jmin (pathYMin, y);
  69474. pathYMax = jmax (pathYMax, y);
  69475. }
  69476. void Path::quadraticTo (const float x1, const float y1,
  69477. const float x2, const float y2) throw()
  69478. {
  69479. CHECK_COORDS_ARE_VALID (x1, y1);
  69480. CHECK_COORDS_ARE_VALID (x2, y2);
  69481. if (numElements == 0)
  69482. startNewSubPath (0, 0);
  69483. ensureAllocatedSize (numElements + 5);
  69484. elements [numElements++] = quadMarker;
  69485. elements [numElements++] = x1;
  69486. elements [numElements++] = y1;
  69487. elements [numElements++] = x2;
  69488. elements [numElements++] = y2;
  69489. pathXMin = jmin (pathXMin, x1, x2);
  69490. pathXMax = jmax (pathXMax, x1, x2);
  69491. pathYMin = jmin (pathYMin, y1, y2);
  69492. pathYMax = jmax (pathYMax, y1, y2);
  69493. }
  69494. void Path::cubicTo (const float x1, const float y1,
  69495. const float x2, const float y2,
  69496. const float x3, const float y3) throw()
  69497. {
  69498. CHECK_COORDS_ARE_VALID (x1, y1);
  69499. CHECK_COORDS_ARE_VALID (x2, y2);
  69500. CHECK_COORDS_ARE_VALID (x3, y3);
  69501. if (numElements == 0)
  69502. startNewSubPath (0, 0);
  69503. ensureAllocatedSize (numElements + 7);
  69504. elements [numElements++] = cubicMarker;
  69505. elements [numElements++] = x1;
  69506. elements [numElements++] = y1;
  69507. elements [numElements++] = x2;
  69508. elements [numElements++] = y2;
  69509. elements [numElements++] = x3;
  69510. elements [numElements++] = y3;
  69511. pathXMin = jmin (pathXMin, x1, x2, x3);
  69512. pathXMax = jmax (pathXMax, x1, x2, x3);
  69513. pathYMin = jmin (pathYMin, y1, y2, y3);
  69514. pathYMax = jmax (pathYMax, y1, y2, y3);
  69515. }
  69516. void Path::closeSubPath() throw()
  69517. {
  69518. if (numElements > 0
  69519. && elements [numElements - 1] != closeSubPathMarker)
  69520. {
  69521. ensureAllocatedSize (numElements + 1);
  69522. elements [numElements++] = closeSubPathMarker;
  69523. }
  69524. }
  69525. const Point Path::getCurrentPosition() const
  69526. {
  69527. int i = numElements - 1;
  69528. if (i > 0 && elements[i] == closeSubPathMarker)
  69529. {
  69530. while (i >= 0)
  69531. {
  69532. if (elements[i] == moveMarker)
  69533. {
  69534. i += 2;
  69535. break;
  69536. }
  69537. --i;
  69538. }
  69539. }
  69540. if (i > 0)
  69541. return Point (elements [i - 1], elements [i]);
  69542. return Point (0.0f, 0.0f);
  69543. }
  69544. void Path::addRectangle (const float x, const float y,
  69545. const float w, const float h) throw()
  69546. {
  69547. startNewSubPath (x, y + h);
  69548. lineTo (x, y);
  69549. lineTo (x + w, y);
  69550. lineTo (x + w, y + h);
  69551. closeSubPath();
  69552. }
  69553. void Path::addRoundedRectangle (const float x, const float y,
  69554. const float w, const float h,
  69555. float csx,
  69556. float csy) throw()
  69557. {
  69558. csx = jmin (csx, w * 0.5f);
  69559. csy = jmin (csy, h * 0.5f);
  69560. const float cs45x = csx * 0.45f;
  69561. const float cs45y = csy * 0.45f;
  69562. const float x2 = x + w;
  69563. const float y2 = y + h;
  69564. startNewSubPath (x + csx, y);
  69565. lineTo (x2 - csx, y);
  69566. cubicTo (x2 - cs45x, y, x2, y + cs45y, x2, y + csy);
  69567. lineTo (x2, y2 - csy);
  69568. cubicTo (x2, y2 - cs45y, x2 - cs45x, y2, x2 - csx, y2);
  69569. lineTo (x + csx, y2);
  69570. cubicTo (x + cs45x, y2, x, y2 - cs45y, x, y2 - csy);
  69571. lineTo (x, y + csy);
  69572. cubicTo (x, y + cs45y, x + cs45x, y, x + csx, y);
  69573. closeSubPath();
  69574. }
  69575. void Path::addRoundedRectangle (const float x, const float y,
  69576. const float w, const float h,
  69577. float cs) throw()
  69578. {
  69579. addRoundedRectangle (x, y, w, h, cs, cs);
  69580. }
  69581. void Path::addTriangle (const float x1, const float y1,
  69582. const float x2, const float y2,
  69583. const float x3, const float y3) throw()
  69584. {
  69585. startNewSubPath (x1, y1);
  69586. lineTo (x2, y2);
  69587. lineTo (x3, y3);
  69588. closeSubPath();
  69589. }
  69590. void Path::addQuadrilateral (const float x1, const float y1,
  69591. const float x2, const float y2,
  69592. const float x3, const float y3,
  69593. const float x4, const float y4) throw()
  69594. {
  69595. startNewSubPath (x1, y1);
  69596. lineTo (x2, y2);
  69597. lineTo (x3, y3);
  69598. lineTo (x4, y4);
  69599. closeSubPath();
  69600. }
  69601. void Path::addEllipse (const float x, const float y,
  69602. const float w, const float h) throw()
  69603. {
  69604. const float hw = w * 0.5f;
  69605. const float hw55 = hw * 0.55f;
  69606. const float hh = h * 0.5f;
  69607. const float hh45 = hh * 0.55f;
  69608. const float cx = x + hw;
  69609. const float cy = y + hh;
  69610. startNewSubPath (cx, cy - hh);
  69611. cubicTo (cx + hw55, cy - hh, cx + hw, cy - hh45, cx + hw, cy);
  69612. cubicTo (cx + hw, cy + hh45, cx + hw55, cy + hh, cx, cy + hh);
  69613. cubicTo (cx - hw55, cy + hh, cx - hw, cy + hh45, cx - hw, cy);
  69614. cubicTo (cx - hw, cy - hh45, cx - hw55, cy - hh, cx, cy - hh);
  69615. closeSubPath();
  69616. }
  69617. void Path::addArc (const float x, const float y,
  69618. const float w, const float h,
  69619. const float fromRadians,
  69620. const float toRadians,
  69621. const bool startAsNewSubPath) throw()
  69622. {
  69623. const float radiusX = w / 2.0f;
  69624. const float radiusY = h / 2.0f;
  69625. addCentredArc (x + radiusX,
  69626. y + radiusY,
  69627. radiusX, radiusY,
  69628. 0.0f,
  69629. fromRadians, toRadians,
  69630. startAsNewSubPath);
  69631. }
  69632. static const float ellipseAngularIncrement = 0.05f;
  69633. void Path::addCentredArc (const float centreX, const float centreY,
  69634. const float radiusX, const float radiusY,
  69635. const float rotationOfEllipse,
  69636. const float fromRadians,
  69637. const float toRadians,
  69638. const bool startAsNewSubPath) throw()
  69639. {
  69640. if (radiusX > 0.0f && radiusY > 0.0f)
  69641. {
  69642. const AffineTransform rotation (AffineTransform::rotation (rotationOfEllipse, centreX, centreY));
  69643. float angle = fromRadians;
  69644. if (startAsNewSubPath)
  69645. {
  69646. float x = centreX + radiusX * sinf (angle);
  69647. float y = centreY - radiusY * cosf (angle);
  69648. if (rotationOfEllipse != 0)
  69649. rotation.transformPoint (x, y);
  69650. startNewSubPath (x, y);
  69651. }
  69652. if (fromRadians < toRadians)
  69653. {
  69654. if (startAsNewSubPath)
  69655. angle += ellipseAngularIncrement;
  69656. while (angle < toRadians)
  69657. {
  69658. float x = centreX + radiusX * sinf (angle);
  69659. float y = centreY - radiusY * cosf (angle);
  69660. if (rotationOfEllipse != 0)
  69661. rotation.transformPoint (x, y);
  69662. lineTo (x, y);
  69663. angle += ellipseAngularIncrement;
  69664. }
  69665. }
  69666. else
  69667. {
  69668. if (startAsNewSubPath)
  69669. angle -= ellipseAngularIncrement;
  69670. while (angle > toRadians)
  69671. {
  69672. float x = centreX + radiusX * sinf (angle);
  69673. float y = centreY - radiusY * cosf (angle);
  69674. if (rotationOfEllipse != 0)
  69675. rotation.transformPoint (x, y);
  69676. lineTo (x, y);
  69677. angle -= ellipseAngularIncrement;
  69678. }
  69679. }
  69680. float x = centreX + radiusX * sinf (toRadians);
  69681. float y = centreY - radiusY * cosf (toRadians);
  69682. if (rotationOfEllipse != 0)
  69683. rotation.transformPoint (x, y);
  69684. lineTo (x, y);
  69685. }
  69686. }
  69687. void Path::addPieSegment (const float x, const float y,
  69688. const float width, const float height,
  69689. const float fromRadians,
  69690. const float toRadians,
  69691. const float innerCircleProportionalSize)
  69692. {
  69693. float hw = width * 0.5f;
  69694. float hh = height * 0.5f;
  69695. const float centreX = x + hw;
  69696. const float centreY = y + hh;
  69697. startNewSubPath (centreX + hw * sinf (fromRadians),
  69698. centreY - hh * cosf (fromRadians));
  69699. addArc (x, y, width, height, fromRadians, toRadians);
  69700. if (fabs (fromRadians - toRadians) > float_Pi * 1.999f)
  69701. {
  69702. closeSubPath();
  69703. if (innerCircleProportionalSize > 0)
  69704. {
  69705. hw *= innerCircleProportionalSize;
  69706. hh *= innerCircleProportionalSize;
  69707. startNewSubPath (centreX + hw * sinf (toRadians),
  69708. centreY - hh * cosf (toRadians));
  69709. addArc (centreX - hw, centreY - hh, hw * 2.0f, hh * 2.0f,
  69710. toRadians, fromRadians);
  69711. }
  69712. }
  69713. else
  69714. {
  69715. if (innerCircleProportionalSize > 0)
  69716. {
  69717. hw *= innerCircleProportionalSize;
  69718. hh *= innerCircleProportionalSize;
  69719. addArc (centreX - hw, centreY - hh, hw * 2.0f, hh * 2.0f,
  69720. toRadians, fromRadians);
  69721. }
  69722. else
  69723. {
  69724. lineTo (centreX, centreY);
  69725. }
  69726. }
  69727. closeSubPath();
  69728. }
  69729. static void perpendicularOffset (const float x1, const float y1,
  69730. const float x2, const float y2,
  69731. const float offsetX, const float offsetY,
  69732. float& resultX, float& resultY) throw()
  69733. {
  69734. const float dx = x2 - x1;
  69735. const float dy = y2 - y1;
  69736. const float len = juce_hypotf (dx, dy);
  69737. if (len == 0)
  69738. {
  69739. resultX = x1;
  69740. resultY = y1;
  69741. }
  69742. else
  69743. {
  69744. resultX = x1 + ((dx * offsetX) - (dy * offsetY)) / len;
  69745. resultY = y1 + ((dy * offsetX) + (dx * offsetY)) / len;
  69746. }
  69747. }
  69748. void Path::addLineSegment (const float startX, const float startY,
  69749. const float endX, const float endY,
  69750. float lineThickness) throw()
  69751. {
  69752. lineThickness *= 0.5f;
  69753. float x, y;
  69754. perpendicularOffset (startX, startY, endX, endY,
  69755. 0, lineThickness, x, y);
  69756. startNewSubPath (x, y);
  69757. perpendicularOffset (startX, startY, endX, endY,
  69758. 0, -lineThickness, x, y);
  69759. lineTo (x, y);
  69760. perpendicularOffset (endX, endY, startX, startY,
  69761. 0, lineThickness, x, y);
  69762. lineTo (x, y);
  69763. perpendicularOffset (endX, endY, startX, startY,
  69764. 0, -lineThickness, x, y);
  69765. lineTo (x, y);
  69766. closeSubPath();
  69767. }
  69768. void Path::addArrow (const float startX, const float startY,
  69769. const float endX, const float endY,
  69770. float lineThickness,
  69771. float arrowheadWidth,
  69772. float arrowheadLength) throw()
  69773. {
  69774. lineThickness *= 0.5f;
  69775. arrowheadWidth *= 0.5f;
  69776. arrowheadLength = jmin (arrowheadLength, 0.8f * juce_hypotf (startX - endX,
  69777. startY - endY));
  69778. float x, y;
  69779. perpendicularOffset (startX, startY, endX, endY,
  69780. 0, lineThickness, x, y);
  69781. startNewSubPath (x, y);
  69782. perpendicularOffset (startX, startY, endX, endY,
  69783. 0, -lineThickness, x, y);
  69784. lineTo (x, y);
  69785. perpendicularOffset (endX, endY, startX, startY,
  69786. arrowheadLength, lineThickness, x, y);
  69787. lineTo (x, y);
  69788. perpendicularOffset (endX, endY, startX, startY,
  69789. arrowheadLength, arrowheadWidth, x, y);
  69790. lineTo (x, y);
  69791. perpendicularOffset (endX, endY, startX, startY,
  69792. 0, 0, x, y);
  69793. lineTo (x, y);
  69794. perpendicularOffset (endX, endY, startX, startY,
  69795. arrowheadLength, -arrowheadWidth, x, y);
  69796. lineTo (x, y);
  69797. perpendicularOffset (endX, endY, startX, startY,
  69798. arrowheadLength, -lineThickness, x, y);
  69799. lineTo (x, y);
  69800. closeSubPath();
  69801. }
  69802. void Path::addStar (const float centreX,
  69803. const float centreY,
  69804. const int numberOfPoints,
  69805. const float innerRadius,
  69806. const float outerRadius,
  69807. const float startAngle)
  69808. {
  69809. jassert (numberOfPoints > 1); // this would be silly.
  69810. if (numberOfPoints > 1)
  69811. {
  69812. const float angleBetweenPoints = float_Pi * 2.0f / numberOfPoints;
  69813. for (int i = 0; i < numberOfPoints; ++i)
  69814. {
  69815. float angle = startAngle + i * angleBetweenPoints;
  69816. const float x = centreX + outerRadius * sinf (angle);
  69817. const float y = centreY - outerRadius * cosf (angle);
  69818. if (i == 0)
  69819. startNewSubPath (x, y);
  69820. else
  69821. lineTo (x, y);
  69822. angle += angleBetweenPoints * 0.5f;
  69823. lineTo (centreX + innerRadius * sinf (angle),
  69824. centreY - innerRadius * cosf (angle));
  69825. }
  69826. closeSubPath();
  69827. }
  69828. }
  69829. void Path::addBubble (float x, float y,
  69830. float w, float h,
  69831. float cs,
  69832. float tipX,
  69833. float tipY,
  69834. int whichSide,
  69835. float arrowPos,
  69836. float arrowWidth)
  69837. {
  69838. if (w > 1.0f && h > 1.0f)
  69839. {
  69840. cs = jmin (cs, w * 0.5f, h * 0.5f);
  69841. const float cs2 = 2.0f * cs;
  69842. startNewSubPath (x + cs, y);
  69843. if (whichSide == 0)
  69844. {
  69845. const float halfArrowW = jmin (arrowWidth, w - cs2) * 0.5f;
  69846. const float arrowX1 = x + cs + jmax (0.0f, (w - cs2) * arrowPos - halfArrowW);
  69847. lineTo (arrowX1, y);
  69848. lineTo (tipX, tipY);
  69849. lineTo (arrowX1 + halfArrowW * 2.0f, y);
  69850. }
  69851. lineTo (x + w - cs, y);
  69852. if (cs > 0.0f)
  69853. addArc (x + w - cs2, y, cs2, cs2, 0, float_Pi * 0.5f);
  69854. if (whichSide == 3)
  69855. {
  69856. const float halfArrowH = jmin (arrowWidth, h - cs2) * 0.5f;
  69857. const float arrowY1 = y + cs + jmax (0.0f, (h - cs2) * arrowPos - halfArrowH);
  69858. lineTo (x + w, arrowY1);
  69859. lineTo (tipX, tipY);
  69860. lineTo (x + w, arrowY1 + halfArrowH * 2.0f);
  69861. }
  69862. lineTo (x + w, y + h - cs);
  69863. if (cs > 0.0f)
  69864. addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  69865. if (whichSide == 2)
  69866. {
  69867. const float halfArrowW = jmin (arrowWidth, w - cs2) * 0.5f;
  69868. const float arrowX1 = x + cs + jmax (0.0f, (w - cs2) * arrowPos - halfArrowW);
  69869. lineTo (arrowX1 + halfArrowW * 2.0f, y + h);
  69870. lineTo (tipX, tipY);
  69871. lineTo (arrowX1, y + h);
  69872. }
  69873. lineTo (x + cs, y + h);
  69874. if (cs > 0.0f)
  69875. addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  69876. if (whichSide == 1)
  69877. {
  69878. const float halfArrowH = jmin (arrowWidth, h - cs2) * 0.5f;
  69879. const float arrowY1 = y + cs + jmax (0.0f, (h - cs2) * arrowPos - halfArrowH);
  69880. lineTo (x, arrowY1 + halfArrowH * 2.0f);
  69881. lineTo (tipX, tipY);
  69882. lineTo (x, arrowY1);
  69883. }
  69884. lineTo (x, y + cs);
  69885. if (cs > 0.0f)
  69886. addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f - ellipseAngularIncrement);
  69887. closeSubPath();
  69888. }
  69889. }
  69890. void Path::addPath (const Path& other) throw()
  69891. {
  69892. int i = 0;
  69893. while (i < other.numElements)
  69894. {
  69895. const float type = other.elements [i++];
  69896. if (type == moveMarker)
  69897. {
  69898. startNewSubPath (other.elements [i],
  69899. other.elements [i + 1]);
  69900. i += 2;
  69901. }
  69902. else if (type == lineMarker)
  69903. {
  69904. lineTo (other.elements [i],
  69905. other.elements [i + 1]);
  69906. i += 2;
  69907. }
  69908. else if (type == quadMarker)
  69909. {
  69910. quadraticTo (other.elements [i],
  69911. other.elements [i + 1],
  69912. other.elements [i + 2],
  69913. other.elements [i + 3]);
  69914. i += 4;
  69915. }
  69916. else if (type == cubicMarker)
  69917. {
  69918. cubicTo (other.elements [i],
  69919. other.elements [i + 1],
  69920. other.elements [i + 2],
  69921. other.elements [i + 3],
  69922. other.elements [i + 4],
  69923. other.elements [i + 5]);
  69924. i += 6;
  69925. }
  69926. else if (type == closeSubPathMarker)
  69927. {
  69928. closeSubPath();
  69929. }
  69930. else
  69931. {
  69932. // something's gone wrong with the element list!
  69933. jassertfalse
  69934. }
  69935. }
  69936. }
  69937. void Path::addPath (const Path& other,
  69938. const AffineTransform& transformToApply) throw()
  69939. {
  69940. int i = 0;
  69941. while (i < other.numElements)
  69942. {
  69943. const float type = other.elements [i++];
  69944. if (type == closeSubPathMarker)
  69945. {
  69946. closeSubPath();
  69947. }
  69948. else
  69949. {
  69950. float x = other.elements [i++];
  69951. float y = other.elements [i++];
  69952. transformToApply.transformPoint (x, y);
  69953. if (type == moveMarker)
  69954. {
  69955. startNewSubPath (x, y);
  69956. }
  69957. else if (type == lineMarker)
  69958. {
  69959. lineTo (x, y);
  69960. }
  69961. else if (type == quadMarker)
  69962. {
  69963. float x2 = other.elements [i++];
  69964. float y2 = other.elements [i++];
  69965. transformToApply.transformPoint (x2, y2);
  69966. quadraticTo (x, y, x2, y2);
  69967. }
  69968. else if (type == cubicMarker)
  69969. {
  69970. float x2 = other.elements [i++];
  69971. float y2 = other.elements [i++];
  69972. float x3 = other.elements [i++];
  69973. float y3 = other.elements [i++];
  69974. transformToApply.transformPoint (x2, y2);
  69975. transformToApply.transformPoint (x3, y3);
  69976. cubicTo (x, y, x2, y2, x3, y3);
  69977. }
  69978. else
  69979. {
  69980. // something's gone wrong with the element list!
  69981. jassertfalse
  69982. }
  69983. }
  69984. }
  69985. }
  69986. void Path::applyTransform (const AffineTransform& transform) throw()
  69987. {
  69988. int i = 0;
  69989. pathYMin = pathXMin = 0;
  69990. pathYMax = pathXMax = 0;
  69991. bool setMaxMin = false;
  69992. while (i < numElements)
  69993. {
  69994. const float type = elements [i++];
  69995. if (type == moveMarker)
  69996. {
  69997. transform.transformPoint (elements [i],
  69998. elements [i + 1]);
  69999. if (setMaxMin)
  70000. {
  70001. pathXMin = jmin (pathXMin, elements [i]);
  70002. pathXMax = jmax (pathXMax, elements [i]);
  70003. pathYMin = jmin (pathYMin, elements [i + 1]);
  70004. pathYMax = jmax (pathYMax, elements [i + 1]);
  70005. }
  70006. else
  70007. {
  70008. pathXMin = pathXMax = elements [i];
  70009. pathYMin = pathYMax = elements [i + 1];
  70010. setMaxMin = true;
  70011. }
  70012. i += 2;
  70013. }
  70014. else if (type == lineMarker)
  70015. {
  70016. transform.transformPoint (elements [i],
  70017. elements [i + 1]);
  70018. pathXMin = jmin (pathXMin, elements [i]);
  70019. pathXMax = jmax (pathXMax, elements [i]);
  70020. pathYMin = jmin (pathYMin, elements [i + 1]);
  70021. pathYMax = jmax (pathYMax, elements [i + 1]);
  70022. i += 2;
  70023. }
  70024. else if (type == quadMarker)
  70025. {
  70026. transform.transformPoint (elements [i],
  70027. elements [i + 1]);
  70028. transform.transformPoint (elements [i + 2],
  70029. elements [i + 3]);
  70030. pathXMin = jmin (pathXMin, elements [i], elements [i + 2]);
  70031. pathXMax = jmax (pathXMax, elements [i], elements [i + 2]);
  70032. pathYMin = jmin (pathYMin, elements [i + 1], elements [i + 3]);
  70033. pathYMax = jmax (pathYMax, elements [i + 1], elements [i + 3]);
  70034. i += 4;
  70035. }
  70036. else if (type == cubicMarker)
  70037. {
  70038. transform.transformPoint (elements [i],
  70039. elements [i + 1]);
  70040. transform.transformPoint (elements [i + 2],
  70041. elements [i + 3]);
  70042. transform.transformPoint (elements [i + 4],
  70043. elements [i + 5]);
  70044. pathXMin = jmin (pathXMin, elements [i], elements [i + 2], elements [i + 4]);
  70045. pathXMax = jmax (pathXMax, elements [i], elements [i + 2], elements [i + 4]);
  70046. pathYMin = jmin (pathYMin, elements [i + 1], elements [i + 3], elements [i + 5]);
  70047. pathYMax = jmax (pathYMax, elements [i + 1], elements [i + 3], elements [i + 5]);
  70048. i += 6;
  70049. }
  70050. }
  70051. }
  70052. const AffineTransform Path::getTransformToScaleToFit (const float x, const float y,
  70053. const float w, const float h,
  70054. const bool preserveProportions,
  70055. const Justification& justification) const throw()
  70056. {
  70057. float sx, sy, sw, sh;
  70058. getBounds (sx, sy, sw, sh);
  70059. if (preserveProportions)
  70060. {
  70061. if (w <= 0 || h <= 0 || sw <= 0 || sh <= 0)
  70062. return AffineTransform::identity;
  70063. float newW, newH;
  70064. const float srcRatio = sh / sw;
  70065. if (srcRatio > h / w)
  70066. {
  70067. newW = h / srcRatio;
  70068. newH = h;
  70069. }
  70070. else
  70071. {
  70072. newW = w;
  70073. newH = w * srcRatio;
  70074. }
  70075. float newXCentre = x;
  70076. float newYCentre = y;
  70077. if (justification.testFlags (Justification::left))
  70078. newXCentre += newW * 0.5f;
  70079. else if (justification.testFlags (Justification::right))
  70080. newXCentre += w - newW * 0.5f;
  70081. else
  70082. newXCentre += w * 0.5f;
  70083. if (justification.testFlags (Justification::top))
  70084. newYCentre += newH * 0.5f;
  70085. else if (justification.testFlags (Justification::bottom))
  70086. newYCentre += h - newH * 0.5f;
  70087. else
  70088. newYCentre += h * 0.5f;
  70089. return AffineTransform::translation (sw * -0.5f - sx, sh * -0.5f - sy)
  70090. .scaled (newW / sw, newH / sh)
  70091. .translated (newXCentre, newYCentre);
  70092. }
  70093. else
  70094. {
  70095. return AffineTransform::translation (-sx, -sy)
  70096. .scaled (w / sw, h / sh)
  70097. .translated (x, y);
  70098. }
  70099. }
  70100. bool Path::contains (const float x, const float y, const float tolerence) const throw()
  70101. {
  70102. if (x <= pathXMin || x >= pathXMax
  70103. || y <= pathYMin || y >= pathYMax)
  70104. return false;
  70105. PathFlatteningIterator i (*this, AffineTransform::identity, tolerence);
  70106. int positiveCrossings = 0;
  70107. int negativeCrossings = 0;
  70108. while (i.next())
  70109. {
  70110. if ((i.y1 <= y && i.y2 > y)
  70111. || (i.y2 <= y && i.y1 > y))
  70112. {
  70113. const float intersectX = i.x1 + (i.x2 - i.x1) * (y - i.y1) / (i.y2 - i.y1);
  70114. if (intersectX <= x)
  70115. {
  70116. if (i.y1 < i.y2)
  70117. ++positiveCrossings;
  70118. else
  70119. ++negativeCrossings;
  70120. }
  70121. }
  70122. }
  70123. return (useNonZeroWinding) ? (negativeCrossings != positiveCrossings)
  70124. : ((negativeCrossings + positiveCrossings) & 1) != 0;
  70125. }
  70126. bool Path::intersectsLine (const float x1, const float y1,
  70127. const float x2, const float y2,
  70128. const float tolerence) throw()
  70129. {
  70130. PathFlatteningIterator i (*this, AffineTransform::identity, tolerence);
  70131. const Line line1 (x1, y1, x2, y2);
  70132. while (i.next())
  70133. {
  70134. const Line line2 (i.x1, i.y1, i.x2, i.y2);
  70135. float ix, iy;
  70136. if (line1.intersects (line2, ix, iy))
  70137. return true;
  70138. }
  70139. return false;
  70140. }
  70141. const Path Path::createPathWithRoundedCorners (const float cornerRadius) const throw()
  70142. {
  70143. if (cornerRadius <= 0.01f)
  70144. return *this;
  70145. int indexOfPathStart = 0, indexOfPathStartThis = 0;
  70146. int n = 0;
  70147. bool lastWasLine = false, firstWasLine = false;
  70148. Path p;
  70149. while (n < numElements)
  70150. {
  70151. const float type = elements [n++];
  70152. if (type == moveMarker)
  70153. {
  70154. indexOfPathStart = p.numElements;
  70155. indexOfPathStartThis = n - 1;
  70156. const float x = elements [n++];
  70157. const float y = elements [n++];
  70158. p.startNewSubPath (x, y);
  70159. lastWasLine = false;
  70160. firstWasLine = (elements [n] == lineMarker);
  70161. }
  70162. else if (type == lineMarker || type == closeSubPathMarker)
  70163. {
  70164. float startX = 0, startY = 0, joinX = 0, joinY = 0, endX, endY;
  70165. if (type == lineMarker)
  70166. {
  70167. endX = elements [n++];
  70168. endY = elements [n++];
  70169. if (n > 8)
  70170. {
  70171. startX = elements [n - 8];
  70172. startY = elements [n - 7];
  70173. joinX = elements [n - 5];
  70174. joinY = elements [n - 4];
  70175. }
  70176. }
  70177. else
  70178. {
  70179. endX = elements [indexOfPathStartThis + 1];
  70180. endY = elements [indexOfPathStartThis + 2];
  70181. if (n > 6)
  70182. {
  70183. startX = elements [n - 6];
  70184. startY = elements [n - 5];
  70185. joinX = elements [n - 3];
  70186. joinY = elements [n - 2];
  70187. }
  70188. }
  70189. if (lastWasLine)
  70190. {
  70191. const double len1 = juce_hypot (startX - joinX,
  70192. startY - joinY);
  70193. if (len1 > 0)
  70194. {
  70195. const double propNeeded = jmin (0.5, cornerRadius / len1);
  70196. p.elements [p.numElements - 2] = (float) (joinX - (joinX - startX) * propNeeded);
  70197. p.elements [p.numElements - 1] = (float) (joinY - (joinY - startY) * propNeeded);
  70198. }
  70199. const double len2 = juce_hypot (endX - joinX,
  70200. endY - joinY);
  70201. if (len2 > 0)
  70202. {
  70203. const double propNeeded = jmin (0.5, cornerRadius / len2);
  70204. p.quadraticTo (joinX, joinY,
  70205. (float) (joinX + (endX - joinX) * propNeeded),
  70206. (float) (joinY + (endY - joinY) * propNeeded));
  70207. }
  70208. p.lineTo (endX, endY);
  70209. }
  70210. else if (type == lineMarker)
  70211. {
  70212. p.lineTo (endX, endY);
  70213. lastWasLine = true;
  70214. }
  70215. if (type == closeSubPathMarker)
  70216. {
  70217. if (firstWasLine)
  70218. {
  70219. startX = elements [n - 3];
  70220. startY = elements [n - 2];
  70221. joinX = endX;
  70222. joinY = endY;
  70223. endX = elements [indexOfPathStartThis + 4];
  70224. endY = elements [indexOfPathStartThis + 5];
  70225. const double len1 = juce_hypot (startX - joinX,
  70226. startY - joinY);
  70227. if (len1 > 0)
  70228. {
  70229. const double propNeeded = jmin (0.5, cornerRadius / len1);
  70230. p.elements [p.numElements - 2] = (float) (joinX - (joinX - startX) * propNeeded);
  70231. p.elements [p.numElements - 1] = (float) (joinY - (joinY - startY) * propNeeded);
  70232. }
  70233. const double len2 = juce_hypot (endX - joinX,
  70234. endY - joinY);
  70235. if (len2 > 0)
  70236. {
  70237. const double propNeeded = jmin (0.5, cornerRadius / len2);
  70238. endX = (float) (joinX + (endX - joinX) * propNeeded);
  70239. endY = (float) (joinY + (endY - joinY) * propNeeded);
  70240. p.quadraticTo (joinX, joinY, endX, endY);
  70241. p.elements [indexOfPathStart + 1] = endX;
  70242. p.elements [indexOfPathStart + 2] = endY;
  70243. }
  70244. }
  70245. p.closeSubPath();
  70246. }
  70247. }
  70248. else if (type == quadMarker)
  70249. {
  70250. lastWasLine = false;
  70251. const float x1 = elements [n++];
  70252. const float y1 = elements [n++];
  70253. const float x2 = elements [n++];
  70254. const float y2 = elements [n++];
  70255. p.quadraticTo (x1, y1, x2, y2);
  70256. }
  70257. else if (type == cubicMarker)
  70258. {
  70259. lastWasLine = false;
  70260. const float x1 = elements [n++];
  70261. const float y1 = elements [n++];
  70262. const float x2 = elements [n++];
  70263. const float y2 = elements [n++];
  70264. const float x3 = elements [n++];
  70265. const float y3 = elements [n++];
  70266. p.cubicTo (x1, y1, x2, y2, x3, y3);
  70267. }
  70268. }
  70269. return p;
  70270. }
  70271. void Path::loadPathFromStream (InputStream& source)
  70272. {
  70273. while (! source.isExhausted())
  70274. {
  70275. switch (source.readByte())
  70276. {
  70277. case 'm':
  70278. {
  70279. const float x = source.readFloat();
  70280. const float y = source.readFloat();
  70281. startNewSubPath (x, y);
  70282. break;
  70283. }
  70284. case 'l':
  70285. {
  70286. const float x = source.readFloat();
  70287. const float y = source.readFloat();
  70288. lineTo (x, y);
  70289. break;
  70290. }
  70291. case 'q':
  70292. {
  70293. const float x1 = source.readFloat();
  70294. const float y1 = source.readFloat();
  70295. const float x2 = source.readFloat();
  70296. const float y2 = source.readFloat();
  70297. quadraticTo (x1, y1, x2, y2);
  70298. break;
  70299. }
  70300. case 'b':
  70301. {
  70302. const float x1 = source.readFloat();
  70303. const float y1 = source.readFloat();
  70304. const float x2 = source.readFloat();
  70305. const float y2 = source.readFloat();
  70306. const float x3 = source.readFloat();
  70307. const float y3 = source.readFloat();
  70308. cubicTo (x1, y1, x2, y2, x3, y3);
  70309. break;
  70310. }
  70311. case 'c':
  70312. closeSubPath();
  70313. break;
  70314. case 'n':
  70315. useNonZeroWinding = true;
  70316. break;
  70317. case 'z':
  70318. useNonZeroWinding = false;
  70319. break;
  70320. case 'e':
  70321. return; // end of path marker
  70322. default:
  70323. jassertfalse // illegal char in the stream
  70324. break;
  70325. }
  70326. }
  70327. }
  70328. void Path::loadPathFromData (const unsigned char* const data,
  70329. const int numberOfBytes) throw()
  70330. {
  70331. MemoryInputStream in ((const char*) data, numberOfBytes, false);
  70332. loadPathFromStream (in);
  70333. }
  70334. void Path::writePathToStream (OutputStream& dest) const
  70335. {
  70336. dest.writeByte ((useNonZeroWinding) ? 'n' : 'z');
  70337. int i = 0;
  70338. while (i < numElements)
  70339. {
  70340. const float type = elements [i++];
  70341. if (type == moveMarker)
  70342. {
  70343. dest.writeByte ('m');
  70344. dest.writeFloat (elements [i++]);
  70345. dest.writeFloat (elements [i++]);
  70346. }
  70347. else if (type == lineMarker)
  70348. {
  70349. dest.writeByte ('l');
  70350. dest.writeFloat (elements [i++]);
  70351. dest.writeFloat (elements [i++]);
  70352. }
  70353. else if (type == quadMarker)
  70354. {
  70355. dest.writeByte ('q');
  70356. dest.writeFloat (elements [i++]);
  70357. dest.writeFloat (elements [i++]);
  70358. dest.writeFloat (elements [i++]);
  70359. dest.writeFloat (elements [i++]);
  70360. }
  70361. else if (type == cubicMarker)
  70362. {
  70363. dest.writeByte ('b');
  70364. dest.writeFloat (elements [i++]);
  70365. dest.writeFloat (elements [i++]);
  70366. dest.writeFloat (elements [i++]);
  70367. dest.writeFloat (elements [i++]);
  70368. dest.writeFloat (elements [i++]);
  70369. dest.writeFloat (elements [i++]);
  70370. }
  70371. else if (type == closeSubPathMarker)
  70372. {
  70373. dest.writeByte ('c');
  70374. }
  70375. }
  70376. dest.writeByte ('e'); // marks the end-of-path
  70377. }
  70378. const String Path::toString() const
  70379. {
  70380. String s;
  70381. s.preallocateStorage (numElements * 4);
  70382. if (! useNonZeroWinding)
  70383. s << T("a ");
  70384. int i = 0;
  70385. float lastMarker = 0.0f;
  70386. while (i < numElements)
  70387. {
  70388. const float marker = elements [i++];
  70389. tchar markerChar = 0;
  70390. int numCoords = 0;
  70391. if (marker == moveMarker)
  70392. {
  70393. markerChar = T('m');
  70394. numCoords = 2;
  70395. }
  70396. else if (marker == lineMarker)
  70397. {
  70398. markerChar = T('l');
  70399. numCoords = 2;
  70400. }
  70401. else if (marker == quadMarker)
  70402. {
  70403. markerChar = T('q');
  70404. numCoords = 4;
  70405. }
  70406. else if (marker == cubicMarker)
  70407. {
  70408. markerChar = T('c');
  70409. numCoords = 6;
  70410. }
  70411. else
  70412. {
  70413. jassert (marker == closeSubPathMarker);
  70414. markerChar = T('z');
  70415. }
  70416. if (marker != lastMarker)
  70417. {
  70418. s << markerChar << T(' ');
  70419. lastMarker = marker;
  70420. }
  70421. while (--numCoords >= 0 && i < numElements)
  70422. {
  70423. String n (elements [i++], 3);
  70424. while (n.endsWithChar (T('0')))
  70425. n = n.dropLastCharacters (1);
  70426. if (n.endsWithChar (T('.')))
  70427. n = n.dropLastCharacters (1);
  70428. s << n << T(' ');
  70429. }
  70430. }
  70431. return s.trimEnd();
  70432. }
  70433. static const String nextToken (const tchar*& t)
  70434. {
  70435. while (CharacterFunctions::isWhitespace (*t))
  70436. ++t;
  70437. const tchar* const start = t;
  70438. while (*t != 0 && ! CharacterFunctions::isWhitespace (*t))
  70439. ++t;
  70440. const int length = (int) (t - start);
  70441. while (CharacterFunctions::isWhitespace (*t))
  70442. ++t;
  70443. return String (start, length);
  70444. }
  70445. void Path::restoreFromString (const String& stringVersion)
  70446. {
  70447. clear();
  70448. setUsingNonZeroWinding (true);
  70449. const tchar* t = stringVersion;
  70450. tchar marker = T('m');
  70451. int numValues = 2;
  70452. float values [6];
  70453. while (*t != 0)
  70454. {
  70455. const String token (nextToken (t));
  70456. const tchar firstChar = token[0];
  70457. int startNum = 0;
  70458. if (firstChar == T('m') || firstChar == T('l'))
  70459. {
  70460. marker = firstChar;
  70461. numValues = 2;
  70462. }
  70463. else if (firstChar == T('q'))
  70464. {
  70465. marker = firstChar;
  70466. numValues = 4;
  70467. }
  70468. else if (firstChar == T('c'))
  70469. {
  70470. marker = firstChar;
  70471. numValues = 6;
  70472. }
  70473. else if (firstChar == T('z'))
  70474. {
  70475. marker = firstChar;
  70476. numValues = 0;
  70477. }
  70478. else if (firstChar == T('a'))
  70479. {
  70480. setUsingNonZeroWinding (false);
  70481. continue;
  70482. }
  70483. else
  70484. {
  70485. ++startNum;
  70486. values [0] = token.getFloatValue();
  70487. }
  70488. for (int i = startNum; i < numValues; ++i)
  70489. values [i] = nextToken (t).getFloatValue();
  70490. switch (marker)
  70491. {
  70492. case T('m'):
  70493. startNewSubPath (values[0], values[1]);
  70494. break;
  70495. case T('l'):
  70496. lineTo (values[0], values[1]);
  70497. break;
  70498. case T('q'):
  70499. quadraticTo (values[0], values[1],
  70500. values[2], values[3]);
  70501. break;
  70502. case T('c'):
  70503. cubicTo (values[0], values[1],
  70504. values[2], values[3],
  70505. values[4], values[5]);
  70506. break;
  70507. case T('z'):
  70508. closeSubPath();
  70509. break;
  70510. default:
  70511. jassertfalse // illegal string format?
  70512. break;
  70513. }
  70514. }
  70515. }
  70516. Path::Iterator::Iterator (const Path& path_)
  70517. : path (path_),
  70518. index (0)
  70519. {
  70520. }
  70521. Path::Iterator::~Iterator()
  70522. {
  70523. }
  70524. bool Path::Iterator::next()
  70525. {
  70526. const float* const elements = path.elements;
  70527. if (index < path.numElements)
  70528. {
  70529. const float type = elements [index++];
  70530. if (type == moveMarker)
  70531. {
  70532. elementType = startNewSubPath;
  70533. x1 = elements [index++];
  70534. y1 = elements [index++];
  70535. }
  70536. else if (type == lineMarker)
  70537. {
  70538. elementType = lineTo;
  70539. x1 = elements [index++];
  70540. y1 = elements [index++];
  70541. }
  70542. else if (type == quadMarker)
  70543. {
  70544. elementType = quadraticTo;
  70545. x1 = elements [index++];
  70546. y1 = elements [index++];
  70547. x2 = elements [index++];
  70548. y2 = elements [index++];
  70549. }
  70550. else if (type == cubicMarker)
  70551. {
  70552. elementType = cubicTo;
  70553. x1 = elements [index++];
  70554. y1 = elements [index++];
  70555. x2 = elements [index++];
  70556. y2 = elements [index++];
  70557. x3 = elements [index++];
  70558. y3 = elements [index++];
  70559. }
  70560. else if (type == closeSubPathMarker)
  70561. {
  70562. elementType = closePath;
  70563. }
  70564. return true;
  70565. }
  70566. return false;
  70567. }
  70568. END_JUCE_NAMESPACE
  70569. /********* End of inlined file: juce_Path.cpp *********/
  70570. /********* Start of inlined file: juce_PathIterator.cpp *********/
  70571. BEGIN_JUCE_NAMESPACE
  70572. #if JUCE_MSVC
  70573. #pragma optimize ("t", on)
  70574. #endif
  70575. PathFlatteningIterator::PathFlatteningIterator (const Path& path_,
  70576. const AffineTransform& transform_,
  70577. float tolerence_) throw()
  70578. : x2 (0),
  70579. y2 (0),
  70580. closesSubPath (false),
  70581. subPathIndex (-1),
  70582. path (path_),
  70583. transform (transform_),
  70584. points (path_.elements),
  70585. tolerence (tolerence_ * tolerence_),
  70586. subPathCloseX (0),
  70587. subPathCloseY (0),
  70588. index (0),
  70589. stackSize (32)
  70590. {
  70591. stackBase = (float*) juce_malloc (stackSize * sizeof (float));
  70592. isIdentityTransform = transform.isIdentity();
  70593. stackPos = stackBase;
  70594. }
  70595. PathFlatteningIterator::~PathFlatteningIterator() throw()
  70596. {
  70597. juce_free (stackBase);
  70598. }
  70599. bool PathFlatteningIterator::next() throw()
  70600. {
  70601. x1 = x2;
  70602. y1 = y2;
  70603. float x3 = 0;
  70604. float y3 = 0;
  70605. float x4 = 0;
  70606. float y4 = 0;
  70607. float type;
  70608. for (;;)
  70609. {
  70610. if (stackPos == stackBase)
  70611. {
  70612. if (index >= path.numElements)
  70613. {
  70614. return false;
  70615. }
  70616. else
  70617. {
  70618. type = points [index++];
  70619. if (type != Path::closeSubPathMarker)
  70620. {
  70621. x2 = points [index++];
  70622. y2 = points [index++];
  70623. if (! isIdentityTransform)
  70624. transform.transformPoint (x2, y2);
  70625. if (type == Path::quadMarker)
  70626. {
  70627. x3 = points [index++];
  70628. y3 = points [index++];
  70629. if (! isIdentityTransform)
  70630. transform.transformPoint (x3, y3);
  70631. }
  70632. else if (type == Path::cubicMarker)
  70633. {
  70634. x3 = points [index++];
  70635. y3 = points [index++];
  70636. x4 = points [index++];
  70637. y4 = points [index++];
  70638. if (! isIdentityTransform)
  70639. {
  70640. transform.transformPoint (x3, y3);
  70641. transform.transformPoint (x4, y4);
  70642. }
  70643. }
  70644. }
  70645. }
  70646. }
  70647. else
  70648. {
  70649. type = *--stackPos;
  70650. if (type != Path::closeSubPathMarker)
  70651. {
  70652. x2 = *--stackPos;
  70653. y2 = *--stackPos;
  70654. if (type == Path::quadMarker)
  70655. {
  70656. x3 = *--stackPos;
  70657. y3 = *--stackPos;
  70658. }
  70659. else if (type == Path::cubicMarker)
  70660. {
  70661. x3 = *--stackPos;
  70662. y3 = *--stackPos;
  70663. x4 = *--stackPos;
  70664. y4 = *--stackPos;
  70665. }
  70666. }
  70667. }
  70668. if (type == Path::lineMarker)
  70669. {
  70670. ++subPathIndex;
  70671. closesSubPath = (stackPos == stackBase)
  70672. && (index < path.numElements)
  70673. && (points [index] == Path::closeSubPathMarker)
  70674. && x2 == subPathCloseX
  70675. && y2 == subPathCloseY;
  70676. return true;
  70677. }
  70678. else if (type == Path::quadMarker)
  70679. {
  70680. const int offset = (int) (stackPos - stackBase);
  70681. if (offset >= stackSize - 10)
  70682. {
  70683. stackSize <<= 1;
  70684. stackBase = (float*) juce_realloc (stackBase, stackSize * sizeof (float));
  70685. stackPos = stackBase + offset;
  70686. }
  70687. const float dx1 = x1 - x2;
  70688. const float dy1 = y1 - y2;
  70689. const float dx2 = x2 - x3;
  70690. const float dy2 = y2 - y3;
  70691. const float m1x = (x1 + x2) * 0.5f;
  70692. const float m1y = (y1 + y2) * 0.5f;
  70693. const float m2x = (x2 + x3) * 0.5f;
  70694. const float m2y = (y2 + y3) * 0.5f;
  70695. const float m3x = (m1x + m2x) * 0.5f;
  70696. const float m3y = (m1y + m2y) * 0.5f;
  70697. if (dx1*dx1 + dy1*dy1 + dx2*dx2 + dy2*dy2 > tolerence)
  70698. {
  70699. *stackPos++ = y3;
  70700. *stackPos++ = x3;
  70701. *stackPos++ = m2y;
  70702. *stackPos++ = m2x;
  70703. *stackPos++ = Path::quadMarker;
  70704. *stackPos++ = m3y;
  70705. *stackPos++ = m3x;
  70706. *stackPos++ = m1y;
  70707. *stackPos++ = m1x;
  70708. *stackPos++ = Path::quadMarker;
  70709. }
  70710. else
  70711. {
  70712. *stackPos++ = y3;
  70713. *stackPos++ = x3;
  70714. *stackPos++ = Path::lineMarker;
  70715. *stackPos++ = m3y;
  70716. *stackPos++ = m3x;
  70717. *stackPos++ = Path::lineMarker;
  70718. }
  70719. jassert (stackPos < stackBase + stackSize);
  70720. }
  70721. else if (type == Path::cubicMarker)
  70722. {
  70723. const int offset = (int) (stackPos - stackBase);
  70724. if (offset >= stackSize - 16)
  70725. {
  70726. stackSize <<= 1;
  70727. stackBase = (float*) juce_realloc (stackBase, stackSize * sizeof (float));
  70728. stackPos = stackBase + offset;
  70729. }
  70730. const float dx1 = x1 - x2;
  70731. const float dy1 = y1 - y2;
  70732. const float dx2 = x2 - x3;
  70733. const float dy2 = y2 - y3;
  70734. const float dx3 = x3 - x4;
  70735. const float dy3 = y3 - y4;
  70736. const float m1x = (x1 + x2) * 0.5f;
  70737. const float m1y = (y1 + y2) * 0.5f;
  70738. const float m2x = (x3 + x2) * 0.5f;
  70739. const float m2y = (y3 + y2) * 0.5f;
  70740. const float m3x = (x3 + x4) * 0.5f;
  70741. const float m3y = (y3 + y4) * 0.5f;
  70742. const float m4x = (m1x + m2x) * 0.5f;
  70743. const float m4y = (m1y + m2y) * 0.5f;
  70744. const float m5x = (m3x + m2x) * 0.5f;
  70745. const float m5y = (m3y + m2y) * 0.5f;
  70746. if (dx1*dx1 + dy1*dy1 + dx2*dx2
  70747. + dy2*dy2 + dx3*dx3 + dy3*dy3 > tolerence)
  70748. {
  70749. *stackPos++ = y4;
  70750. *stackPos++ = x4;
  70751. *stackPos++ = m3y;
  70752. *stackPos++ = m3x;
  70753. *stackPos++ = m5y;
  70754. *stackPos++ = m5x;
  70755. *stackPos++ = Path::cubicMarker;
  70756. *stackPos++ = (m4y + m5y) * 0.5f;
  70757. *stackPos++ = (m4x + m5x) * 0.5f;
  70758. *stackPos++ = m4y;
  70759. *stackPos++ = m4x;
  70760. *stackPos++ = m1y;
  70761. *stackPos++ = m1x;
  70762. *stackPos++ = Path::cubicMarker;
  70763. }
  70764. else
  70765. {
  70766. *stackPos++ = y4;
  70767. *stackPos++ = x4;
  70768. *stackPos++ = Path::lineMarker;
  70769. *stackPos++ = m5y;
  70770. *stackPos++ = m5x;
  70771. *stackPos++ = Path::lineMarker;
  70772. *stackPos++ = m4y;
  70773. *stackPos++ = m4x;
  70774. *stackPos++ = Path::lineMarker;
  70775. }
  70776. }
  70777. else if (type == Path::closeSubPathMarker)
  70778. {
  70779. if (x2 != subPathCloseX || y2 != subPathCloseY)
  70780. {
  70781. x1 = x2;
  70782. y1 = y2;
  70783. x2 = subPathCloseX;
  70784. y2 = subPathCloseY;
  70785. closesSubPath = true;
  70786. return true;
  70787. }
  70788. }
  70789. else
  70790. {
  70791. jassert (type == Path::moveMarker);
  70792. subPathIndex = -1;
  70793. subPathCloseX = x1 = x2;
  70794. subPathCloseY = y1 = y2;
  70795. }
  70796. }
  70797. }
  70798. END_JUCE_NAMESPACE
  70799. /********* End of inlined file: juce_PathIterator.cpp *********/
  70800. /********* Start of inlined file: juce_PathStrokeType.cpp *********/
  70801. BEGIN_JUCE_NAMESPACE
  70802. PathStrokeType::PathStrokeType (const float strokeThickness,
  70803. const JointStyle jointStyle_,
  70804. const EndCapStyle endStyle_) throw()
  70805. : thickness (strokeThickness),
  70806. jointStyle (jointStyle_),
  70807. endStyle (endStyle_)
  70808. {
  70809. }
  70810. PathStrokeType::PathStrokeType (const PathStrokeType& other) throw()
  70811. : thickness (other.thickness),
  70812. jointStyle (other.jointStyle),
  70813. endStyle (other.endStyle)
  70814. {
  70815. }
  70816. const PathStrokeType& PathStrokeType::operator= (const PathStrokeType& other) throw()
  70817. {
  70818. thickness = other.thickness;
  70819. jointStyle = other.jointStyle;
  70820. endStyle = other.endStyle;
  70821. return *this;
  70822. }
  70823. PathStrokeType::~PathStrokeType() throw()
  70824. {
  70825. }
  70826. bool PathStrokeType::operator== (const PathStrokeType& other) const throw()
  70827. {
  70828. return thickness == other.thickness
  70829. && jointStyle == other.jointStyle
  70830. && endStyle == other.endStyle;
  70831. }
  70832. bool PathStrokeType::operator!= (const PathStrokeType& other) const throw()
  70833. {
  70834. return ! operator== (other);
  70835. }
  70836. static bool lineIntersection (const float x1, const float y1,
  70837. const float x2, const float y2,
  70838. const float x3, const float y3,
  70839. const float x4, const float y4,
  70840. float& intersectionX,
  70841. float& intersectionY,
  70842. float& distanceBeyondLine1EndSquared) throw()
  70843. {
  70844. if (x2 != x3 || y2 != y3)
  70845. {
  70846. const float dx1 = x2 - x1;
  70847. const float dy1 = y2 - y1;
  70848. const float dx2 = x4 - x3;
  70849. const float dy2 = y4 - y3;
  70850. const float divisor = dx1 * dy2 - dx2 * dy1;
  70851. if (divisor == 0)
  70852. {
  70853. if (! ((dx1 == 0 && dy1 == 0) || (dx2 == 0 && dy2 == 0)))
  70854. {
  70855. if (dy1 == 0 && dy2 != 0)
  70856. {
  70857. const float along = (y1 - y3) / dy2;
  70858. intersectionX = x3 + along * dx2;
  70859. intersectionY = y1;
  70860. distanceBeyondLine1EndSquared = intersectionX - x2;
  70861. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  70862. if ((x2 > x1) == (intersectionX < x2))
  70863. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  70864. return along >= 0 && along <= 1.0f;
  70865. }
  70866. else if (dy2 == 0 && dy1 != 0)
  70867. {
  70868. const float along = (y3 - y1) / dy1;
  70869. intersectionX = x1 + along * dx1;
  70870. intersectionY = y3;
  70871. distanceBeyondLine1EndSquared = (along - 1.0f) * dx1;
  70872. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  70873. if (along < 1.0f)
  70874. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  70875. return along >= 0 && along <= 1.0f;
  70876. }
  70877. else if (dx1 == 0 && dx2 != 0)
  70878. {
  70879. const float along = (x1 - x3) / dx2;
  70880. intersectionX = x1;
  70881. intersectionY = y3 + along * dy2;
  70882. distanceBeyondLine1EndSquared = intersectionY - y2;
  70883. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  70884. if ((y2 > y1) == (intersectionY < y2))
  70885. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  70886. return along >= 0 && along <= 1.0f;
  70887. }
  70888. else if (dx2 == 0 && dx1 != 0)
  70889. {
  70890. const float along = (x3 - x1) / dx1;
  70891. intersectionX = x3;
  70892. intersectionY = y1 + along * dy1;
  70893. distanceBeyondLine1EndSquared = (along - 1.0f) * dy1;
  70894. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  70895. if (along < 1.0f)
  70896. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  70897. return along >= 0 && along <= 1.0f;
  70898. }
  70899. }
  70900. intersectionX = 0.5f * (x2 + x3);
  70901. intersectionY = 0.5f * (y2 + y3);
  70902. distanceBeyondLine1EndSquared = 0.0f;
  70903. return false;
  70904. }
  70905. else
  70906. {
  70907. const float along1 = ((y1 - y3) * dx2 - (x1 - x3) * dy2) / divisor;
  70908. intersectionX = x1 + along1 * dx1;
  70909. intersectionY = y1 + along1 * dy1;
  70910. if (along1 >= 0 && along1 <= 1.0f)
  70911. {
  70912. const float along2 = ((y1 - y3) * dx1 - (x1 - x3) * dy1);
  70913. if (along2 >= 0 && along2 <= divisor)
  70914. {
  70915. distanceBeyondLine1EndSquared = 0.0f;
  70916. return true;
  70917. }
  70918. }
  70919. distanceBeyondLine1EndSquared = along1 - 1.0f;
  70920. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  70921. distanceBeyondLine1EndSquared *= (dx1 * dx1 + dy1 * dy1);
  70922. if (along1 < 1.0f)
  70923. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  70924. return false;
  70925. }
  70926. }
  70927. intersectionX = x2;
  70928. intersectionY = y2;
  70929. distanceBeyondLine1EndSquared = 0.0f;
  70930. return true;
  70931. }
  70932. // part of stroke drawing stuff
  70933. static void addEdgeAndJoint (Path& destPath,
  70934. const PathStrokeType::JointStyle style,
  70935. const float maxMiterExtensionSquared, const float width,
  70936. const float x1, const float y1,
  70937. const float x2, const float y2,
  70938. const float x3, const float y3,
  70939. const float x4, const float y4,
  70940. const float midX, const float midY) throw()
  70941. {
  70942. if (style == PathStrokeType::beveled
  70943. || (x3 == x4 && y3 == y4)
  70944. || (x1 == x2 && y1 == y2))
  70945. {
  70946. destPath.lineTo (x2, y2);
  70947. destPath.lineTo (x3, y3);
  70948. }
  70949. else
  70950. {
  70951. float jx, jy, distanceBeyondLine1EndSquared;
  70952. // if they intersect, use this point..
  70953. if (lineIntersection (x1, y1, x2, y2,
  70954. x3, y3, x4, y4,
  70955. jx, jy, distanceBeyondLine1EndSquared))
  70956. {
  70957. destPath.lineTo (jx, jy);
  70958. }
  70959. else
  70960. {
  70961. if (style == PathStrokeType::mitered)
  70962. {
  70963. if (distanceBeyondLine1EndSquared < maxMiterExtensionSquared
  70964. && distanceBeyondLine1EndSquared > 0.0f)
  70965. {
  70966. destPath.lineTo (jx, jy);
  70967. }
  70968. else
  70969. {
  70970. // the end sticks out too far, so just use a blunt joint
  70971. destPath.lineTo (x2, y2);
  70972. destPath.lineTo (x3, y3);
  70973. }
  70974. }
  70975. else
  70976. {
  70977. // curved joints
  70978. float angle = atan2f (x2 - midX, y2 - midY);
  70979. float angle2 = atan2f (x3 - midX, y3 - midY);
  70980. while (angle < angle2 - 0.01f)
  70981. angle2 -= float_Pi * 2.0f;
  70982. destPath.lineTo (x2, y2);
  70983. while (angle > angle2)
  70984. {
  70985. destPath.lineTo (midX + width * sinf (angle),
  70986. midY + width * cosf (angle));
  70987. angle -= 0.1f;
  70988. }
  70989. destPath.lineTo (x3, y3);
  70990. }
  70991. }
  70992. }
  70993. }
  70994. static inline void addLineEnd (Path& destPath,
  70995. const PathStrokeType::EndCapStyle style,
  70996. const float x1, const float y1,
  70997. const float x2, const float y2,
  70998. const float width) throw()
  70999. {
  71000. if (style == PathStrokeType::butt)
  71001. {
  71002. destPath.lineTo (x2, y2);
  71003. }
  71004. else
  71005. {
  71006. float offx1, offy1, offx2, offy2;
  71007. float dx = x2 - x1;
  71008. float dy = y2 - y1;
  71009. const float len = juce_hypotf (dx, dy);
  71010. if (len == 0)
  71011. {
  71012. offx1 = offx2 = x1;
  71013. offy1 = offy2 = y1;
  71014. }
  71015. else
  71016. {
  71017. const float offset = width / len;
  71018. dx *= offset;
  71019. dy *= offset;
  71020. offx1 = x1 + dy;
  71021. offy1 = y1 - dx;
  71022. offx2 = x2 + dy;
  71023. offy2 = y2 - dx;
  71024. }
  71025. if (style == PathStrokeType::square)
  71026. {
  71027. // sqaure ends
  71028. destPath.lineTo (offx1, offy1);
  71029. destPath.lineTo (offx2, offy2);
  71030. destPath.lineTo (x2, y2);
  71031. }
  71032. else
  71033. {
  71034. // rounded ends
  71035. const float midx = (offx1 + offx2) * 0.5f;
  71036. const float midy = (offy1 + offy2) * 0.5f;
  71037. destPath.cubicTo (x1 + (offx1 - x1) * 0.55f, y1 + (offy1 - y1) * 0.55f,
  71038. offx1 + (midx - offx1) * 0.45f, offy1 + (midy - offy1) * 0.45f,
  71039. midx, midy);
  71040. destPath.cubicTo (midx + (offx2 - midx) * 0.55f, midy + (offy2 - midy) * 0.55f,
  71041. offx2 + (x2 - offx2) * 0.45f, offy2 + (y2 - offy2) * 0.45f,
  71042. x2, y2);
  71043. }
  71044. }
  71045. }
  71046. struct LineSection
  71047. {
  71048. LineSection() throw() {}
  71049. LineSection (int) throw() {}
  71050. float x1, y1, x2, y2; // original line
  71051. float lx1, ly1, lx2, ly2; // the left-hand stroke
  71052. float rx1, ry1, rx2, ry2; // the right-hand stroke
  71053. };
  71054. static void addSubPath (Path& destPath, const Array <LineSection>& subPath,
  71055. const bool isClosed,
  71056. const float width, const float maxMiterExtensionSquared,
  71057. const PathStrokeType::JointStyle jointStyle, const PathStrokeType::EndCapStyle endStyle) throw()
  71058. {
  71059. jassert (subPath.size() > 0);
  71060. const LineSection& firstLine = subPath.getReference (0);
  71061. float lastX1 = firstLine.lx1;
  71062. float lastY1 = firstLine.ly1;
  71063. float lastX2 = firstLine.lx2;
  71064. float lastY2 = firstLine.ly2;
  71065. if (isClosed)
  71066. {
  71067. destPath.startNewSubPath (lastX1, lastY1);
  71068. }
  71069. else
  71070. {
  71071. destPath.startNewSubPath (firstLine.rx2, firstLine.ry2);
  71072. addLineEnd (destPath, endStyle,
  71073. firstLine.rx2, firstLine.ry2,
  71074. lastX1, lastY1,
  71075. width);
  71076. }
  71077. int i;
  71078. for (i = 1; i < subPath.size(); ++i)
  71079. {
  71080. const LineSection& l = subPath.getReference (i);
  71081. addEdgeAndJoint (destPath, jointStyle,
  71082. maxMiterExtensionSquared, width,
  71083. lastX1, lastY1, lastX2, lastY2,
  71084. l.lx1, l.ly1, l.lx2, l.ly2,
  71085. l.x1, l.y1);
  71086. lastX1 = l.lx1;
  71087. lastY1 = l.ly1;
  71088. lastX2 = l.lx2;
  71089. lastY2 = l.ly2;
  71090. }
  71091. const LineSection& lastLine = subPath.getReference (subPath.size() - 1);
  71092. if (isClosed)
  71093. {
  71094. const LineSection& l = subPath.getReference (0);
  71095. addEdgeAndJoint (destPath, jointStyle,
  71096. maxMiterExtensionSquared, width,
  71097. lastX1, lastY1, lastX2, lastY2,
  71098. l.lx1, l.ly1, l.lx2, l.ly2,
  71099. l.x1, l.y1);
  71100. destPath.closeSubPath();
  71101. destPath.startNewSubPath (lastLine.rx1, lastLine.ry1);
  71102. }
  71103. else
  71104. {
  71105. destPath.lineTo (lastX2, lastY2);
  71106. addLineEnd (destPath, endStyle,
  71107. lastX2, lastY2,
  71108. lastLine.rx1, lastLine.ry1,
  71109. width);
  71110. }
  71111. lastX1 = lastLine.rx1;
  71112. lastY1 = lastLine.ry1;
  71113. lastX2 = lastLine.rx2;
  71114. lastY2 = lastLine.ry2;
  71115. for (i = subPath.size() - 1; --i >= 0;)
  71116. {
  71117. const LineSection& l = subPath.getReference (i);
  71118. addEdgeAndJoint (destPath, jointStyle,
  71119. maxMiterExtensionSquared, width,
  71120. lastX1, lastY1, lastX2, lastY2,
  71121. l.rx1, l.ry1, l.rx2, l.ry2,
  71122. l.x2, l.y2);
  71123. lastX1 = l.rx1;
  71124. lastY1 = l.ry1;
  71125. lastX2 = l.rx2;
  71126. lastY2 = l.ry2;
  71127. }
  71128. if (isClosed)
  71129. {
  71130. addEdgeAndJoint (destPath, jointStyle,
  71131. maxMiterExtensionSquared, width,
  71132. lastX1, lastY1, lastX2, lastY2,
  71133. lastLine.rx1, lastLine.ry1, lastLine.rx2, lastLine.ry2,
  71134. lastLine.x2, lastLine.y2);
  71135. }
  71136. else
  71137. {
  71138. // do the last line
  71139. destPath.lineTo (lastX2, lastY2);
  71140. }
  71141. destPath.closeSubPath();
  71142. }
  71143. void PathStrokeType::createStrokedPath (Path& destPath,
  71144. const Path& source,
  71145. const AffineTransform& transform,
  71146. const float extraAccuracy) const throw()
  71147. {
  71148. if (thickness <= 0)
  71149. {
  71150. destPath.clear();
  71151. return;
  71152. }
  71153. const Path* sourcePath = &source;
  71154. Path temp;
  71155. if (sourcePath == &destPath)
  71156. {
  71157. destPath.swapWithPath (temp);
  71158. sourcePath = &temp;
  71159. }
  71160. else
  71161. {
  71162. destPath.clear();
  71163. }
  71164. destPath.setUsingNonZeroWinding (true);
  71165. const float maxMiterExtensionSquared = 9.0f * thickness * thickness;
  71166. const float width = 0.5f * thickness;
  71167. // Iterate the path, creating a list of the
  71168. // left/right-hand lines along either side of it...
  71169. PathFlatteningIterator it (*sourcePath, transform, 9.0f / extraAccuracy);
  71170. Array <LineSection> subPath;
  71171. LineSection l;
  71172. l.x1 = 0;
  71173. l.y1 = 0;
  71174. const float minSegmentLength = 2.0f / (extraAccuracy * extraAccuracy);
  71175. while (it.next())
  71176. {
  71177. if (it.subPathIndex == 0)
  71178. {
  71179. if (subPath.size() > 0)
  71180. {
  71181. addSubPath (destPath, subPath, false, width, maxMiterExtensionSquared, jointStyle, endStyle);
  71182. subPath.clearQuick();
  71183. }
  71184. l.x1 = it.x1;
  71185. l.y1 = it.y1;
  71186. }
  71187. l.x2 = it.x2;
  71188. l.y2 = it.y2;
  71189. float dx = l.x2 - l.x1;
  71190. float dy = l.y2 - l.y1;
  71191. const float hypotSquared = dx*dx + dy*dy;
  71192. if (it.closesSubPath || hypotSquared > minSegmentLength || it.isLastInSubpath())
  71193. {
  71194. const float len = sqrtf (hypotSquared);
  71195. if (len == 0)
  71196. {
  71197. l.rx1 = l.rx2 = l.lx1 = l.lx2 = l.x1;
  71198. l.ry1 = l.ry2 = l.ly1 = l.ly2 = l.y1;
  71199. }
  71200. else
  71201. {
  71202. const float offset = width / len;
  71203. dx *= offset;
  71204. dy *= offset;
  71205. l.rx2 = l.x1 - dy;
  71206. l.ry2 = l.y1 + dx;
  71207. l.lx1 = l.x1 + dy;
  71208. l.ly1 = l.y1 - dx;
  71209. l.lx2 = l.x2 + dy;
  71210. l.ly2 = l.y2 - dx;
  71211. l.rx1 = l.x2 - dy;
  71212. l.ry1 = l.y2 + dx;
  71213. }
  71214. subPath.add (l);
  71215. if (it.closesSubPath)
  71216. {
  71217. addSubPath (destPath, subPath, true, width, maxMiterExtensionSquared, jointStyle, endStyle);
  71218. subPath.clearQuick();
  71219. }
  71220. else
  71221. {
  71222. l.x1 = it.x2;
  71223. l.y1 = it.y2;
  71224. }
  71225. }
  71226. }
  71227. if (subPath.size() > 0)
  71228. addSubPath (destPath, subPath, false, width, maxMiterExtensionSquared, jointStyle, endStyle);
  71229. }
  71230. void PathStrokeType::createDashedStroke (Path& destPath,
  71231. const Path& sourcePath,
  71232. const float* dashLengths,
  71233. int numDashLengths,
  71234. const AffineTransform& transform,
  71235. const float extraAccuracy) const throw()
  71236. {
  71237. if (thickness <= 0)
  71238. return;
  71239. // this should really be an even number..
  71240. jassert ((numDashLengths & 1) == 0);
  71241. Path newDestPath;
  71242. PathFlatteningIterator it (sourcePath, transform, 9.0f / extraAccuracy);
  71243. bool first = true;
  71244. int dashNum = 0;
  71245. float pos = 0.0f, lineLen = 0.0f, lineEndPos = 0.0f;
  71246. float dx = 0.0f, dy = 0.0f;
  71247. for (;;)
  71248. {
  71249. const bool isSolid = ((dashNum & 1) == 0);
  71250. const float dashLen = dashLengths [dashNum++ % numDashLengths];
  71251. jassert (dashLen > 0); // must be a positive increment!
  71252. if (dashLen <= 0)
  71253. break;
  71254. pos += dashLen;
  71255. while (pos > lineEndPos)
  71256. {
  71257. if (! it.next())
  71258. {
  71259. if (isSolid && ! first)
  71260. newDestPath.lineTo (it.x2, it.y2);
  71261. createStrokedPath (destPath, newDestPath, AffineTransform::identity, extraAccuracy);
  71262. return;
  71263. }
  71264. if (isSolid && ! first)
  71265. newDestPath.lineTo (it.x1, it.y1);
  71266. else
  71267. newDestPath.startNewSubPath (it.x1, it.y1);
  71268. dx = it.x2 - it.x1;
  71269. dy = it.y2 - it.y1;
  71270. lineLen = juce_hypotf (dx, dy);
  71271. lineEndPos += lineLen;
  71272. first = it.closesSubPath;
  71273. }
  71274. const float alpha = (pos - (lineEndPos - lineLen)) / lineLen;
  71275. if (isSolid)
  71276. newDestPath.lineTo (it.x1 + dx * alpha,
  71277. it.y1 + dy * alpha);
  71278. else
  71279. newDestPath.startNewSubPath (it.x1 + dx * alpha,
  71280. it.y1 + dy * alpha);
  71281. }
  71282. }
  71283. END_JUCE_NAMESPACE
  71284. /********* End of inlined file: juce_PathStrokeType.cpp *********/
  71285. /********* Start of inlined file: juce_Point.cpp *********/
  71286. BEGIN_JUCE_NAMESPACE
  71287. Point::Point() throw()
  71288. : x (0.0f),
  71289. y (0.0f)
  71290. {
  71291. }
  71292. Point::Point (const Point& other) throw()
  71293. : x (other.x),
  71294. y (other.y)
  71295. {
  71296. }
  71297. const Point& Point::operator= (const Point& other) throw()
  71298. {
  71299. x = other.x;
  71300. y = other.y;
  71301. return *this;
  71302. }
  71303. Point::Point (const float x_,
  71304. const float y_) throw()
  71305. : x (x_),
  71306. y (y_)
  71307. {
  71308. }
  71309. Point::~Point() throw()
  71310. {
  71311. }
  71312. void Point::setXY (const float x_,
  71313. const float y_) throw()
  71314. {
  71315. x = x_;
  71316. y = y_;
  71317. }
  71318. void Point::applyTransform (const AffineTransform& transform) throw()
  71319. {
  71320. transform.transformPoint (x, y);
  71321. }
  71322. END_JUCE_NAMESPACE
  71323. /********* End of inlined file: juce_Point.cpp *********/
  71324. /********* Start of inlined file: juce_PositionedRectangle.cpp *********/
  71325. BEGIN_JUCE_NAMESPACE
  71326. PositionedRectangle::PositionedRectangle() throw()
  71327. : x (0.0),
  71328. y (0.0),
  71329. w (0.0),
  71330. h (0.0),
  71331. xMode (anchorAtLeftOrTop | absoluteFromParentTopLeft),
  71332. yMode (anchorAtLeftOrTop | absoluteFromParentTopLeft),
  71333. wMode (absoluteSize),
  71334. hMode (absoluteSize)
  71335. {
  71336. }
  71337. PositionedRectangle::PositionedRectangle (const PositionedRectangle& other) throw()
  71338. : x (other.x),
  71339. y (other.y),
  71340. w (other.w),
  71341. h (other.h),
  71342. xMode (other.xMode),
  71343. yMode (other.yMode),
  71344. wMode (other.wMode),
  71345. hMode (other.hMode)
  71346. {
  71347. }
  71348. const PositionedRectangle& PositionedRectangle::operator= (const PositionedRectangle& other) throw()
  71349. {
  71350. if (this != &other)
  71351. {
  71352. x = other.x;
  71353. y = other.y;
  71354. w = other.w;
  71355. h = other.h;
  71356. xMode = other.xMode;
  71357. yMode = other.yMode;
  71358. wMode = other.wMode;
  71359. hMode = other.hMode;
  71360. }
  71361. return *this;
  71362. }
  71363. PositionedRectangle::~PositionedRectangle() throw()
  71364. {
  71365. }
  71366. const bool PositionedRectangle::operator== (const PositionedRectangle& other) const throw()
  71367. {
  71368. return x == other.x
  71369. && y == other.y
  71370. && w == other.w
  71371. && h == other.h
  71372. && xMode == other.xMode
  71373. && yMode == other.yMode
  71374. && wMode == other.wMode
  71375. && hMode == other.hMode;
  71376. }
  71377. const bool PositionedRectangle::operator!= (const PositionedRectangle& other) const throw()
  71378. {
  71379. return ! operator== (other);
  71380. }
  71381. PositionedRectangle::PositionedRectangle (const String& stringVersion) throw()
  71382. {
  71383. StringArray tokens;
  71384. tokens.addTokens (stringVersion, false);
  71385. decodePosString (tokens [0], xMode, x);
  71386. decodePosString (tokens [1], yMode, y);
  71387. decodeSizeString (tokens [2], wMode, w);
  71388. decodeSizeString (tokens [3], hMode, h);
  71389. }
  71390. const String PositionedRectangle::toString() const throw()
  71391. {
  71392. String s;
  71393. s.preallocateStorage (12);
  71394. addPosDescription (s, xMode, x);
  71395. s << T(' ');
  71396. addPosDescription (s, yMode, y);
  71397. s << T(' ');
  71398. addSizeDescription (s, wMode, w);
  71399. s << T(' ');
  71400. addSizeDescription (s, hMode, h);
  71401. return s;
  71402. }
  71403. const Rectangle PositionedRectangle::getRectangle (const Rectangle& target) const throw()
  71404. {
  71405. jassert (! target.isEmpty());
  71406. double x_, y_, w_, h_;
  71407. applyPosAndSize (x_, w_, x, w, xMode, wMode, target.getX(), target.getWidth());
  71408. applyPosAndSize (y_, h_, y, h, yMode, hMode, target.getY(), target.getHeight());
  71409. return Rectangle (roundDoubleToInt (x_), roundDoubleToInt (y_),
  71410. roundDoubleToInt (w_), roundDoubleToInt (h_));
  71411. }
  71412. void PositionedRectangle::getRectangleDouble (const Rectangle& target,
  71413. double& x_, double& y_,
  71414. double& w_, double& h_) const throw()
  71415. {
  71416. jassert (! target.isEmpty());
  71417. applyPosAndSize (x_, w_, x, w, xMode, wMode, target.getX(), target.getWidth());
  71418. applyPosAndSize (y_, h_, y, h, yMode, hMode, target.getY(), target.getHeight());
  71419. }
  71420. void PositionedRectangle::applyToComponent (Component& comp) const throw()
  71421. {
  71422. comp.setBounds (getRectangle (Rectangle (0, 0, comp.getParentWidth(), comp.getParentHeight())));
  71423. }
  71424. void PositionedRectangle::updateFrom (const Rectangle& rectangle,
  71425. const Rectangle& target) throw()
  71426. {
  71427. updatePosAndSize (x, w, rectangle.getX(), rectangle.getWidth(), xMode, wMode, target.getX(), target.getWidth());
  71428. updatePosAndSize (y, h, rectangle.getY(), rectangle.getHeight(), yMode, hMode, target.getY(), target.getHeight());
  71429. }
  71430. void PositionedRectangle::updateFromDouble (const double newX, const double newY,
  71431. const double newW, const double newH,
  71432. const Rectangle& target) throw()
  71433. {
  71434. updatePosAndSize (x, w, newX, newW, xMode, wMode, target.getX(), target.getWidth());
  71435. updatePosAndSize (y, h, newY, newH, yMode, hMode, target.getY(), target.getHeight());
  71436. }
  71437. void PositionedRectangle::updateFromComponent (const Component& comp) throw()
  71438. {
  71439. if (comp.getParentComponent() == 0 && ! comp.isOnDesktop())
  71440. updateFrom (comp.getBounds(), Rectangle());
  71441. else
  71442. updateFrom (comp.getBounds(), Rectangle (0, 0, comp.getParentWidth(), comp.getParentHeight()));
  71443. }
  71444. PositionedRectangle::AnchorPoint PositionedRectangle::getAnchorPointX() const throw()
  71445. {
  71446. return (AnchorPoint) (xMode & (anchorAtLeftOrTop | anchorAtRightOrBottom | anchorAtCentre));
  71447. }
  71448. PositionedRectangle::PositionMode PositionedRectangle::getPositionModeX() const throw()
  71449. {
  71450. return (PositionMode) (xMode & (absoluteFromParentTopLeft
  71451. | absoluteFromParentBottomRight
  71452. | absoluteFromParentCentre
  71453. | proportionOfParentSize));
  71454. }
  71455. PositionedRectangle::AnchorPoint PositionedRectangle::getAnchorPointY() const throw()
  71456. {
  71457. return (AnchorPoint) (yMode & (anchorAtLeftOrTop | anchorAtRightOrBottom | anchorAtCentre));
  71458. }
  71459. PositionedRectangle::PositionMode PositionedRectangle::getPositionModeY() const throw()
  71460. {
  71461. return (PositionMode) (yMode & (absoluteFromParentTopLeft
  71462. | absoluteFromParentBottomRight
  71463. | absoluteFromParentCentre
  71464. | proportionOfParentSize));
  71465. }
  71466. PositionedRectangle::SizeMode PositionedRectangle::getWidthMode() const throw()
  71467. {
  71468. return (SizeMode) wMode;
  71469. }
  71470. PositionedRectangle::SizeMode PositionedRectangle::getHeightMode() const throw()
  71471. {
  71472. return (SizeMode) hMode;
  71473. }
  71474. void PositionedRectangle::setModes (const AnchorPoint xAnchor,
  71475. const PositionMode xMode_,
  71476. const AnchorPoint yAnchor,
  71477. const PositionMode yMode_,
  71478. const SizeMode widthMode,
  71479. const SizeMode heightMode,
  71480. const Rectangle& target) throw()
  71481. {
  71482. if (xMode != (xAnchor | xMode_) || wMode != widthMode)
  71483. {
  71484. double tx, tw;
  71485. applyPosAndSize (tx, tw, x, w, xMode, wMode, target.getX(), target.getWidth());
  71486. xMode = (uint8) (xAnchor | xMode_);
  71487. wMode = (uint8) widthMode;
  71488. updatePosAndSize (x, w, tx, tw, xMode, wMode, target.getX(), target.getWidth());
  71489. }
  71490. if (yMode != (yAnchor | yMode_) || hMode != heightMode)
  71491. {
  71492. double ty, th;
  71493. applyPosAndSize (ty, th, y, h, yMode, hMode, target.getY(), target.getHeight());
  71494. yMode = (uint8) (yAnchor | yMode_);
  71495. hMode = (uint8) heightMode;
  71496. updatePosAndSize (y, h, ty, th, yMode, hMode, target.getY(), target.getHeight());
  71497. }
  71498. }
  71499. bool PositionedRectangle::isPositionAbsolute() const throw()
  71500. {
  71501. return xMode == absoluteFromParentTopLeft
  71502. && yMode == absoluteFromParentTopLeft
  71503. && wMode == absoluteSize
  71504. && hMode == absoluteSize;
  71505. }
  71506. void PositionedRectangle::addPosDescription (String& s, const uint8 mode, const double value) const throw()
  71507. {
  71508. if ((mode & proportionOfParentSize) != 0)
  71509. {
  71510. s << (roundDoubleToInt (value * 100000.0) / 1000.0) << T('%');
  71511. }
  71512. else
  71513. {
  71514. s << (roundDoubleToInt (value * 100.0) / 100.0);
  71515. if ((mode & absoluteFromParentBottomRight) != 0)
  71516. s << T('R');
  71517. else if ((mode & absoluteFromParentCentre) != 0)
  71518. s << T('C');
  71519. }
  71520. if ((mode & anchorAtRightOrBottom) != 0)
  71521. s << T('r');
  71522. else if ((mode & anchorAtCentre) != 0)
  71523. s << T('c');
  71524. }
  71525. void PositionedRectangle::addSizeDescription (String& s, const uint8 mode, const double value) const throw()
  71526. {
  71527. if (mode == proportionalSize)
  71528. s << (roundDoubleToInt (value * 100000.0) / 1000.0) << T('%');
  71529. else if (mode == parentSizeMinusAbsolute)
  71530. s << (roundDoubleToInt (value * 100.0) / 100.0) << T('M');
  71531. else
  71532. s << (roundDoubleToInt (value * 100.0) / 100.0);
  71533. }
  71534. void PositionedRectangle::decodePosString (const String& s, uint8& mode, double& value) throw()
  71535. {
  71536. if (s.containsChar (T('r')))
  71537. mode = anchorAtRightOrBottom;
  71538. else if (s.containsChar (T('c')))
  71539. mode = anchorAtCentre;
  71540. else
  71541. mode = anchorAtLeftOrTop;
  71542. if (s.containsChar (T('%')))
  71543. {
  71544. mode |= proportionOfParentSize;
  71545. value = s.removeCharacters (T("%rcRC")).getDoubleValue() / 100.0;
  71546. }
  71547. else
  71548. {
  71549. if (s.containsChar (T('R')))
  71550. mode |= absoluteFromParentBottomRight;
  71551. else if (s.containsChar (T('C')))
  71552. mode |= absoluteFromParentCentre;
  71553. else
  71554. mode |= absoluteFromParentTopLeft;
  71555. value = s.removeCharacters (T("rcRC")).getDoubleValue();
  71556. }
  71557. }
  71558. void PositionedRectangle::decodeSizeString (const String& s, uint8& mode, double& value) throw()
  71559. {
  71560. if (s.containsChar (T('%')))
  71561. {
  71562. mode = proportionalSize;
  71563. value = s.upToFirstOccurrenceOf (T("%"), false, false).getDoubleValue() / 100.0;
  71564. }
  71565. else if (s.containsChar (T('M')))
  71566. {
  71567. mode = parentSizeMinusAbsolute;
  71568. value = s.getDoubleValue();
  71569. }
  71570. else
  71571. {
  71572. mode = absoluteSize;
  71573. value = s.getDoubleValue();
  71574. }
  71575. }
  71576. void PositionedRectangle::applyPosAndSize (double& xOut, double& wOut,
  71577. const double x_, const double w_,
  71578. const uint8 xMode_, const uint8 wMode_,
  71579. const int parentPos,
  71580. const int parentSize) const throw()
  71581. {
  71582. if (wMode_ == proportionalSize)
  71583. wOut = roundDoubleToInt (w_ * parentSize);
  71584. else if (wMode_ == parentSizeMinusAbsolute)
  71585. wOut = jmax (0, parentSize - roundDoubleToInt (w_));
  71586. else
  71587. wOut = roundDoubleToInt (w_);
  71588. if ((xMode_ & proportionOfParentSize) != 0)
  71589. xOut = parentPos + x_ * parentSize;
  71590. else if ((xMode_ & absoluteFromParentBottomRight) != 0)
  71591. xOut = (parentPos + parentSize) - x_;
  71592. else if ((xMode_ & absoluteFromParentCentre) != 0)
  71593. xOut = x_ + (parentPos + parentSize / 2);
  71594. else
  71595. xOut = x_ + parentPos;
  71596. if ((xMode_ & anchorAtRightOrBottom) != 0)
  71597. xOut -= wOut;
  71598. else if ((xMode_ & anchorAtCentre) != 0)
  71599. xOut -= wOut / 2;
  71600. }
  71601. void PositionedRectangle::updatePosAndSize (double& xOut, double& wOut,
  71602. double x_, const double w_,
  71603. const uint8 xMode_, const uint8 wMode_,
  71604. const int parentPos,
  71605. const int parentSize) const throw()
  71606. {
  71607. if (wMode_ == proportionalSize)
  71608. {
  71609. if (parentSize > 0)
  71610. wOut = w_ / parentSize;
  71611. }
  71612. else if (wMode_ == parentSizeMinusAbsolute)
  71613. wOut = parentSize - w_;
  71614. else
  71615. wOut = w_;
  71616. if ((xMode_ & anchorAtRightOrBottom) != 0)
  71617. x_ += w_;
  71618. else if ((xMode_ & anchorAtCentre) != 0)
  71619. x_ += w_ / 2;
  71620. if ((xMode_ & proportionOfParentSize) != 0)
  71621. {
  71622. if (parentSize > 0)
  71623. xOut = (x_ - parentPos) / parentSize;
  71624. }
  71625. else if ((xMode_ & absoluteFromParentBottomRight) != 0)
  71626. xOut = (parentPos + parentSize) - x_;
  71627. else if ((xMode_ & absoluteFromParentCentre) != 0)
  71628. xOut = x_ - (parentPos + parentSize / 2);
  71629. else
  71630. xOut = x_ - parentPos;
  71631. }
  71632. END_JUCE_NAMESPACE
  71633. /********* End of inlined file: juce_PositionedRectangle.cpp *********/
  71634. /********* Start of inlined file: juce_Rectangle.cpp *********/
  71635. BEGIN_JUCE_NAMESPACE
  71636. Rectangle::Rectangle() throw()
  71637. : x (0),
  71638. y (0),
  71639. w (0),
  71640. h (0)
  71641. {
  71642. }
  71643. Rectangle::Rectangle (const int x_, const int y_,
  71644. const int w_, const int h_) throw()
  71645. : x (x_),
  71646. y (y_),
  71647. w (w_),
  71648. h (h_)
  71649. {
  71650. }
  71651. Rectangle::Rectangle (const int w_, const int h_) throw()
  71652. : x (0),
  71653. y (0),
  71654. w (w_),
  71655. h (h_)
  71656. {
  71657. }
  71658. Rectangle::Rectangle (const Rectangle& other) throw()
  71659. : x (other.x),
  71660. y (other.y),
  71661. w (other.w),
  71662. h (other.h)
  71663. {
  71664. }
  71665. Rectangle::~Rectangle() throw()
  71666. {
  71667. }
  71668. bool Rectangle::isEmpty() const throw()
  71669. {
  71670. return w <= 0 || h <= 0;
  71671. }
  71672. void Rectangle::setBounds (const int x_,
  71673. const int y_,
  71674. const int w_,
  71675. const int h_) throw()
  71676. {
  71677. x = x_;
  71678. y = y_;
  71679. w = w_;
  71680. h = h_;
  71681. }
  71682. void Rectangle::setPosition (const int x_,
  71683. const int y_) throw()
  71684. {
  71685. x = x_;
  71686. y = y_;
  71687. }
  71688. void Rectangle::setSize (const int w_,
  71689. const int h_) throw()
  71690. {
  71691. w = w_;
  71692. h = h_;
  71693. }
  71694. void Rectangle::setLeft (const int newLeft) throw()
  71695. {
  71696. w = jmax (0, x + w - newLeft);
  71697. x = newLeft;
  71698. }
  71699. void Rectangle::setTop (const int newTop) throw()
  71700. {
  71701. h = jmax (0, y + h - newTop);
  71702. y = newTop;
  71703. }
  71704. void Rectangle::setRight (const int newRight) throw()
  71705. {
  71706. x = jmin (x, newRight);
  71707. w = newRight - x;
  71708. }
  71709. void Rectangle::setBottom (const int newBottom) throw()
  71710. {
  71711. y = jmin (y, newBottom);
  71712. h = newBottom - y;
  71713. }
  71714. void Rectangle::translate (const int dx,
  71715. const int dy) throw()
  71716. {
  71717. x += dx;
  71718. y += dy;
  71719. }
  71720. const Rectangle Rectangle::translated (const int dx,
  71721. const int dy) const throw()
  71722. {
  71723. return Rectangle (x + dx, y + dy, w, h);
  71724. }
  71725. void Rectangle::expand (const int deltaX,
  71726. const int deltaY) throw()
  71727. {
  71728. const int nw = jmax (0, w + deltaX + deltaX);
  71729. const int nh = jmax (0, h + deltaY + deltaY);
  71730. setBounds (x - deltaX,
  71731. y - deltaY,
  71732. nw, nh);
  71733. }
  71734. const Rectangle Rectangle::expanded (const int deltaX,
  71735. const int deltaY) const throw()
  71736. {
  71737. const int nw = jmax (0, w + deltaX + deltaX);
  71738. const int nh = jmax (0, h + deltaY + deltaY);
  71739. return Rectangle (x - deltaX,
  71740. y - deltaY,
  71741. nw, nh);
  71742. }
  71743. void Rectangle::reduce (const int deltaX,
  71744. const int deltaY) throw()
  71745. {
  71746. expand (-deltaX, -deltaY);
  71747. }
  71748. const Rectangle Rectangle::reduced (const int deltaX,
  71749. const int deltaY) const throw()
  71750. {
  71751. return expanded (-deltaX, -deltaY);
  71752. }
  71753. bool Rectangle::operator== (const Rectangle& other) const throw()
  71754. {
  71755. return x == other.x
  71756. && y == other.y
  71757. && w == other.w
  71758. && h == other.h;
  71759. }
  71760. bool Rectangle::operator!= (const Rectangle& other) const throw()
  71761. {
  71762. return x != other.x
  71763. || y != other.y
  71764. || w != other.w
  71765. || h != other.h;
  71766. }
  71767. bool Rectangle::contains (const int px,
  71768. const int py) const throw()
  71769. {
  71770. return px >= x
  71771. && py >= y
  71772. && px < x + w
  71773. && py < y + h;
  71774. }
  71775. bool Rectangle::contains (const Rectangle& other) const throw()
  71776. {
  71777. return x <= other.x
  71778. && y <= other.y
  71779. && x + w >= other.x + other.w
  71780. && y + h >= other.y + other.h;
  71781. }
  71782. bool Rectangle::intersects (const Rectangle& other) const throw()
  71783. {
  71784. return x + w > other.x
  71785. && y + h > other.y
  71786. && x < other.x + other.w
  71787. && y < other.y + other.h
  71788. && w > 0
  71789. && h > 0;
  71790. }
  71791. const Rectangle Rectangle::getIntersection (const Rectangle& other) const throw()
  71792. {
  71793. const int nx = jmax (x, other.x);
  71794. const int ny = jmax (y, other.y);
  71795. const int nw = jmin (x + w, other.x + other.w) - nx;
  71796. const int nh = jmin (y + h, other.y + other.h) - ny;
  71797. if (nw >= 0 && nh >= 0)
  71798. return Rectangle (nx, ny, nw, nh);
  71799. else
  71800. return Rectangle();
  71801. }
  71802. bool Rectangle::intersectRectangle (int& x1, int& y1, int& w1, int& h1) const throw()
  71803. {
  71804. const int maxX = jmax (x1, x);
  71805. w1 = jmin (x1 + w1, x + w) - maxX;
  71806. if (w1 > 0)
  71807. {
  71808. const int maxY = jmax (y1, y);
  71809. h1 = jmin (y1 + h1, y + h) - maxY;
  71810. if (h1 > 0)
  71811. {
  71812. x1 = maxX;
  71813. y1 = maxY;
  71814. return true;
  71815. }
  71816. }
  71817. return false;
  71818. }
  71819. bool Rectangle::intersectRectangles (int& x1, int& y1, int& w1, int& h1,
  71820. int x2, int y2, int w2, int h2) throw()
  71821. {
  71822. const int x = jmax (x1, x2);
  71823. w1 = jmin (x1 + w1, x2 + w2) - x;
  71824. if (w1 > 0)
  71825. {
  71826. const int y = jmax (y1, y2);
  71827. h1 = jmin (y1 + h1, y2 + h2) - y;
  71828. if (h1 > 0)
  71829. {
  71830. x1 = x;
  71831. y1 = y;
  71832. return true;
  71833. }
  71834. }
  71835. return false;
  71836. }
  71837. const Rectangle Rectangle::getUnion (const Rectangle& other) const throw()
  71838. {
  71839. const int newX = jmin (x, other.x);
  71840. const int newY = jmin (y, other.y);
  71841. return Rectangle (newX, newY,
  71842. jmax (x + w, other.x + other.w) - newX,
  71843. jmax (y + h, other.y + other.h) - newY);
  71844. }
  71845. bool Rectangle::enlargeIfAdjacent (const Rectangle& other) throw()
  71846. {
  71847. if (x == other.x && getRight() == other.getRight()
  71848. && (other.getBottom() >= y && other.y <= getBottom()))
  71849. {
  71850. const int newY = jmin (y, other.y);
  71851. h = jmax (getBottom(), other.getBottom()) - newY;
  71852. y = newY;
  71853. return true;
  71854. }
  71855. else if (y == other.y && getBottom() == other.getBottom()
  71856. && (other.getRight() >= x && other.x <= getRight()))
  71857. {
  71858. const int newX = jmin (x, other.x);
  71859. w = jmax (getRight(), other.getRight()) - newX;
  71860. x = newX;
  71861. return true;
  71862. }
  71863. return false;
  71864. }
  71865. bool Rectangle::reduceIfPartlyContainedIn (const Rectangle& other) throw()
  71866. {
  71867. int inside = 0;
  71868. const int otherR = other.getRight();
  71869. if (x >= other.x && x < otherR)
  71870. inside = 1;
  71871. const int otherB = other.getBottom();
  71872. if (y >= other.y && y < otherB)
  71873. inside |= 2;
  71874. const int r = x + w;
  71875. if (r >= other.x && r < otherR)
  71876. inside |= 4;
  71877. const int b = y + h;
  71878. if (b >= other.y && b < otherB)
  71879. inside |= 8;
  71880. switch (inside)
  71881. {
  71882. case 1 + 2 + 8:
  71883. w = r - otherR;
  71884. x = otherR;
  71885. return true;
  71886. case 1 + 2 + 4:
  71887. h = b - otherB;
  71888. y = otherB;
  71889. return true;
  71890. case 2 + 4 + 8:
  71891. w = other.x - x;
  71892. return true;
  71893. case 1 + 4 + 8:
  71894. h = other.y - y;
  71895. return true;
  71896. }
  71897. return false;
  71898. }
  71899. const String Rectangle::toString() const throw()
  71900. {
  71901. String s;
  71902. s.preallocateStorage (16);
  71903. s << x << T(' ')
  71904. << y << T(' ')
  71905. << w << T(' ')
  71906. << h;
  71907. return s;
  71908. }
  71909. const Rectangle Rectangle::fromString (const String& stringVersion)
  71910. {
  71911. StringArray toks;
  71912. toks.addTokens (stringVersion.trim(), T(",; \t\r\n"), 0);
  71913. return Rectangle (toks[0].trim().getIntValue(),
  71914. toks[1].trim().getIntValue(),
  71915. toks[2].trim().getIntValue(),
  71916. toks[3].trim().getIntValue());
  71917. }
  71918. END_JUCE_NAMESPACE
  71919. /********* End of inlined file: juce_Rectangle.cpp *********/
  71920. /********* Start of inlined file: juce_RectangleList.cpp *********/
  71921. BEGIN_JUCE_NAMESPACE
  71922. RectangleList::RectangleList() throw()
  71923. {
  71924. }
  71925. RectangleList::RectangleList (const Rectangle& rect) throw()
  71926. {
  71927. if (! rect.isEmpty())
  71928. rects.add (rect);
  71929. }
  71930. RectangleList::RectangleList (const RectangleList& other) throw()
  71931. : rects (other.rects)
  71932. {
  71933. }
  71934. const RectangleList& RectangleList::operator= (const RectangleList& other) throw()
  71935. {
  71936. if (this != &other)
  71937. rects = other.rects;
  71938. return *this;
  71939. }
  71940. RectangleList::~RectangleList() throw()
  71941. {
  71942. }
  71943. void RectangleList::clear() throw()
  71944. {
  71945. rects.clearQuick();
  71946. }
  71947. const Rectangle RectangleList::getRectangle (const int index) const throw()
  71948. {
  71949. if (((unsigned int) index) < (unsigned int) rects.size())
  71950. return rects.getReference (index);
  71951. return Rectangle();
  71952. }
  71953. bool RectangleList::isEmpty() const throw()
  71954. {
  71955. return rects.size() == 0;
  71956. }
  71957. RectangleList::Iterator::Iterator (const RectangleList& list) throw()
  71958. : current (0),
  71959. owner (list),
  71960. index (list.rects.size())
  71961. {
  71962. }
  71963. RectangleList::Iterator::~Iterator() throw()
  71964. {
  71965. }
  71966. bool RectangleList::Iterator::next() throw()
  71967. {
  71968. if (--index >= 0)
  71969. {
  71970. current = & (owner.rects.getReference (index));
  71971. return true;
  71972. }
  71973. return false;
  71974. }
  71975. void RectangleList::add (const Rectangle& rect) throw()
  71976. {
  71977. if (! rect.isEmpty())
  71978. {
  71979. if (rects.size() == 0)
  71980. {
  71981. rects.add (rect);
  71982. }
  71983. else
  71984. {
  71985. bool anyOverlaps = false;
  71986. int i;
  71987. for (i = rects.size(); --i >= 0;)
  71988. {
  71989. Rectangle& ourRect = rects.getReference (i);
  71990. if (rect.intersects (ourRect))
  71991. {
  71992. if (rect.contains (ourRect))
  71993. rects.remove (i);
  71994. else if (! ourRect.reduceIfPartlyContainedIn (rect))
  71995. anyOverlaps = true;
  71996. }
  71997. }
  71998. if (anyOverlaps && rects.size() > 0)
  71999. {
  72000. RectangleList r (rect);
  72001. for (i = rects.size(); --i >= 0;)
  72002. {
  72003. const Rectangle& ourRect = rects.getReference (i);
  72004. if (rect.intersects (ourRect))
  72005. {
  72006. r.subtract (ourRect);
  72007. if (r.rects.size() == 0)
  72008. return;
  72009. }
  72010. }
  72011. for (i = r.getNumRectangles(); --i >= 0;)
  72012. rects.add (r.rects.getReference (i));
  72013. }
  72014. else
  72015. {
  72016. rects.add (rect);
  72017. }
  72018. }
  72019. }
  72020. }
  72021. void RectangleList::addWithoutMerging (const Rectangle& rect) throw()
  72022. {
  72023. rects.add (rect);
  72024. }
  72025. void RectangleList::add (const int x, const int y, const int w, const int h) throw()
  72026. {
  72027. if (rects.size() == 0)
  72028. {
  72029. if (w > 0 && h > 0)
  72030. rects.add (Rectangle (x, y, w, h));
  72031. }
  72032. else
  72033. {
  72034. add (Rectangle (x, y, w, h));
  72035. }
  72036. }
  72037. void RectangleList::add (const RectangleList& other) throw()
  72038. {
  72039. for (int i = 0; i < other.rects.size(); ++i)
  72040. add (other.rects.getReference (i));
  72041. }
  72042. void RectangleList::subtract (const Rectangle& rect) throw()
  72043. {
  72044. const int originalNumRects = rects.size();
  72045. if (originalNumRects > 0)
  72046. {
  72047. const int x1 = rect.x;
  72048. const int y1 = rect.y;
  72049. const int x2 = x1 + rect.w;
  72050. const int y2 = y1 + rect.h;
  72051. for (int i = getNumRectangles(); --i >= 0;)
  72052. {
  72053. Rectangle& r = rects.getReference (i);
  72054. const int rx1 = r.x;
  72055. const int ry1 = r.y;
  72056. const int rx2 = rx1 + r.w;
  72057. const int ry2 = ry1 + r.h;
  72058. if (! (x2 <= rx1 || x1 >= rx2 || y2 <= ry1 || y1 >= ry2))
  72059. {
  72060. if (x1 > rx1 && x1 < rx2)
  72061. {
  72062. if (y1 <= ry1 && y2 >= ry2 && x2 >= rx2)
  72063. {
  72064. r.w = x1 - rx1;
  72065. }
  72066. else
  72067. {
  72068. r.x = x1;
  72069. r.w = rx2 - x1;
  72070. rects.insert (i + 1, Rectangle (rx1, ry1, x1 - rx1, ry2 - ry1));
  72071. i += 2;
  72072. }
  72073. }
  72074. else if (x2 > rx1 && x2 < rx2)
  72075. {
  72076. r.x = x2;
  72077. r.w = rx2 - x2;
  72078. if (y1 > ry1 || y2 < ry2 || x1 > rx1)
  72079. {
  72080. rects.insert (i + 1, Rectangle (rx1, ry1, x2 - rx1, ry2 - ry1));
  72081. i += 2;
  72082. }
  72083. }
  72084. else if (y1 > ry1 && y1 < ry2)
  72085. {
  72086. if (x1 <= rx1 && x2 >= rx2 && y2 >= ry2)
  72087. {
  72088. r.h = y1 - ry1;
  72089. }
  72090. else
  72091. {
  72092. r.y = y1;
  72093. r.h = ry2 - y1;
  72094. rects.insert (i + 1, Rectangle (rx1, ry1, rx2 - rx1, y1 - ry1));
  72095. i += 2;
  72096. }
  72097. }
  72098. else if (y2 > ry1 && y2 < ry2)
  72099. {
  72100. r.y = y2;
  72101. r.h = ry2 - y2;
  72102. if (x1 > rx1 || x2 < rx2 || y1 > ry1)
  72103. {
  72104. rects.insert (i + 1, Rectangle (rx1, ry1, rx2 - rx1, y2 - ry1));
  72105. i += 2;
  72106. }
  72107. }
  72108. else
  72109. {
  72110. rects.remove (i);
  72111. }
  72112. }
  72113. }
  72114. if (rects.size() > originalNumRects + 10)
  72115. consolidate();
  72116. }
  72117. }
  72118. void RectangleList::subtract (const RectangleList& otherList) throw()
  72119. {
  72120. for (int i = otherList.rects.size(); --i >= 0;)
  72121. subtract (otherList.rects.getReference (i));
  72122. }
  72123. bool RectangleList::clipTo (const Rectangle& rect) throw()
  72124. {
  72125. bool notEmpty = false;
  72126. if (rect.isEmpty())
  72127. {
  72128. clear();
  72129. }
  72130. else
  72131. {
  72132. for (int i = rects.size(); --i >= 0;)
  72133. {
  72134. Rectangle& r = rects.getReference (i);
  72135. if (! rect.intersectRectangle (r.x, r.y, r.w, r.h))
  72136. rects.remove (i);
  72137. else
  72138. notEmpty = true;
  72139. }
  72140. }
  72141. return notEmpty;
  72142. }
  72143. bool RectangleList::clipTo (const RectangleList& other) throw()
  72144. {
  72145. if (rects.size() == 0)
  72146. return false;
  72147. RectangleList result;
  72148. for (int j = 0; j < rects.size(); ++j)
  72149. {
  72150. const Rectangle& rect = rects.getReference (j);
  72151. for (int i = other.rects.size(); --i >= 0;)
  72152. {
  72153. Rectangle r (other.rects.getReference (i));
  72154. if (rect.intersectRectangle (r.x, r.y, r.w, r.h))
  72155. result.rects.add (r);
  72156. }
  72157. }
  72158. swapWith (result);
  72159. return ! isEmpty();
  72160. }
  72161. bool RectangleList::getIntersectionWith (const Rectangle& rect, RectangleList& destRegion) const throw()
  72162. {
  72163. destRegion.clear();
  72164. if (! rect.isEmpty())
  72165. {
  72166. for (int i = rects.size(); --i >= 0;)
  72167. {
  72168. Rectangle r (rects.getReference (i));
  72169. if (rect.intersectRectangle (r.x, r.y, r.w, r.h))
  72170. destRegion.rects.add (r);
  72171. }
  72172. }
  72173. return destRegion.rects.size() > 0;
  72174. }
  72175. void RectangleList::swapWith (RectangleList& otherList) throw()
  72176. {
  72177. rects.swapWithArray (otherList.rects);
  72178. }
  72179. void RectangleList::consolidate() throw()
  72180. {
  72181. int i;
  72182. for (i = 0; i < getNumRectangles() - 1; ++i)
  72183. {
  72184. Rectangle& r = rects.getReference (i);
  72185. const int rx1 = r.x;
  72186. const int ry1 = r.y;
  72187. const int rx2 = rx1 + r.w;
  72188. const int ry2 = ry1 + r.h;
  72189. for (int j = rects.size(); --j > i;)
  72190. {
  72191. Rectangle& r2 = rects.getReference (j);
  72192. const int jrx1 = r2.x;
  72193. const int jry1 = r2.y;
  72194. const int jrx2 = jrx1 + r2.w;
  72195. const int jry2 = jry1 + r2.h;
  72196. // if the vertical edges of any blocks are touching and their horizontals don't
  72197. // line up, split them horizontally..
  72198. if (jrx1 == rx2 || jrx2 == rx1)
  72199. {
  72200. if (jry1 > ry1 && jry1 < ry2)
  72201. {
  72202. r.h = jry1 - ry1;
  72203. rects.add (Rectangle (rx1, jry1, rx2 - rx1, ry2 - jry1));
  72204. i = -1;
  72205. break;
  72206. }
  72207. if (jry2 > ry1 && jry2 < ry2)
  72208. {
  72209. r.h = jry2 - ry1;
  72210. rects.add (Rectangle (rx1, jry2, rx2 - rx1, ry2 - jry2));
  72211. i = -1;
  72212. break;
  72213. }
  72214. else if (ry1 > jry1 && ry1 < jry2)
  72215. {
  72216. r2.h = ry1 - jry1;
  72217. rects.add (Rectangle (jrx1, ry1, jrx2 - jrx1, jry2 - ry1));
  72218. i = -1;
  72219. break;
  72220. }
  72221. else if (ry2 > jry1 && ry2 < jry2)
  72222. {
  72223. r2.h = ry2 - jry1;
  72224. rects.add (Rectangle (jrx1, ry2, jrx2 - jrx1, jry2 - ry2));
  72225. i = -1;
  72226. break;
  72227. }
  72228. }
  72229. }
  72230. }
  72231. for (i = 0; i < rects.size() - 1; ++i)
  72232. {
  72233. Rectangle& r = rects.getReference (i);
  72234. for (int j = rects.size(); --j > i;)
  72235. {
  72236. if (r.enlargeIfAdjacent (rects.getReference (j)))
  72237. {
  72238. rects.remove (j);
  72239. i = -1;
  72240. break;
  72241. }
  72242. }
  72243. }
  72244. }
  72245. bool RectangleList::containsPoint (const int x, const int y) const throw()
  72246. {
  72247. for (int i = getNumRectangles(); --i >= 0;)
  72248. if (rects.getReference (i).contains (x, y))
  72249. return true;
  72250. return false;
  72251. }
  72252. bool RectangleList::containsRectangle (const Rectangle& rectangleToCheck) const throw()
  72253. {
  72254. if (rects.size() > 1)
  72255. {
  72256. RectangleList r (rectangleToCheck);
  72257. for (int i = rects.size(); --i >= 0;)
  72258. {
  72259. r.subtract (rects.getReference (i));
  72260. if (r.rects.size() == 0)
  72261. return true;
  72262. }
  72263. }
  72264. else if (rects.size() > 0)
  72265. {
  72266. return rects.getReference (0).contains (rectangleToCheck);
  72267. }
  72268. return false;
  72269. }
  72270. bool RectangleList::intersectsRectangle (const Rectangle& rectangleToCheck) const throw()
  72271. {
  72272. for (int i = rects.size(); --i >= 0;)
  72273. if (rects.getReference (i).intersects (rectangleToCheck))
  72274. return true;
  72275. return false;
  72276. }
  72277. bool RectangleList::intersects (const RectangleList& other) const throw()
  72278. {
  72279. for (int i = rects.size(); --i >= 0;)
  72280. if (other.intersectsRectangle (rects.getReference (i)))
  72281. return true;
  72282. return false;
  72283. }
  72284. const Rectangle RectangleList::getBounds() const throw()
  72285. {
  72286. if (rects.size() <= 1)
  72287. {
  72288. if (rects.size() == 0)
  72289. return Rectangle();
  72290. else
  72291. return rects.getReference (0);
  72292. }
  72293. else
  72294. {
  72295. const Rectangle& r = rects.getReference (0);
  72296. int minX = r.x;
  72297. int minY = r.y;
  72298. int maxX = minX + r.w;
  72299. int maxY = minY + r.h;
  72300. for (int i = rects.size(); --i > 0;)
  72301. {
  72302. const Rectangle& r2 = rects.getReference (i);
  72303. minX = jmin (minX, r2.x);
  72304. minY = jmin (minY, r2.y);
  72305. maxX = jmax (maxX, r2.getRight());
  72306. maxY = jmax (maxY, r2.getBottom());
  72307. }
  72308. return Rectangle (minX, minY, maxX - minX, maxY - minY);
  72309. }
  72310. }
  72311. void RectangleList::offsetAll (const int dx, const int dy) throw()
  72312. {
  72313. for (int i = rects.size(); --i >= 0;)
  72314. {
  72315. Rectangle& r = rects.getReference (i);
  72316. r.x += dx;
  72317. r.y += dy;
  72318. }
  72319. }
  72320. const Path RectangleList::toPath() const throw()
  72321. {
  72322. Path p;
  72323. for (int i = rects.size(); --i >= 0;)
  72324. {
  72325. const Rectangle& r = rects.getReference (i);
  72326. p.addRectangle ((float) r.x,
  72327. (float) r.y,
  72328. (float) r.w,
  72329. (float) r.h);
  72330. }
  72331. return p;
  72332. }
  72333. END_JUCE_NAMESPACE
  72334. /********* End of inlined file: juce_RectangleList.cpp *********/
  72335. /********* Start of inlined file: juce_Image.cpp *********/
  72336. BEGIN_JUCE_NAMESPACE
  72337. static const int fullAlphaThreshold = 253;
  72338. Image::Image (const PixelFormat format_,
  72339. const int imageWidth_,
  72340. const int imageHeight_)
  72341. : format (format_),
  72342. imageWidth (imageWidth_),
  72343. imageHeight (imageHeight_),
  72344. imageData (0)
  72345. {
  72346. jassert (format_ == RGB || format_ == ARGB || format_ == SingleChannel);
  72347. jassert (imageWidth_ > 0 && imageHeight_ > 0); // it's illegal to create a zero-sized image - the
  72348. // actual image will be at least 1x1.
  72349. }
  72350. Image::Image (const PixelFormat format_,
  72351. const int imageWidth_,
  72352. const int imageHeight_,
  72353. const bool clearImage)
  72354. : format (format_),
  72355. imageWidth (imageWidth_),
  72356. imageHeight (imageHeight_)
  72357. {
  72358. jassert (format_ == RGB || format_ == ARGB || format_ == SingleChannel);
  72359. jassert (imageWidth_ > 0 && imageHeight_ > 0); // it's illegal to create a zero-sized image - the
  72360. // actual image will be at least 1x1.
  72361. pixelStride = (format == RGB) ? 3 : ((format == ARGB) ? 4 : 1);
  72362. lineStride = (pixelStride * jmax (1, imageWidth_) + 3) & ~3;
  72363. const int dataSize = lineStride * jmax (1, imageHeight_);
  72364. imageData = (uint8*) (clearImage ? juce_calloc (dataSize)
  72365. : juce_malloc (dataSize));
  72366. }
  72367. Image::Image (const Image& other)
  72368. : format (other.format),
  72369. imageWidth (other.imageWidth),
  72370. imageHeight (other.imageHeight)
  72371. {
  72372. pixelStride = (format == RGB) ? 3 : ((format == ARGB) ? 4 : 1);
  72373. lineStride = (pixelStride * jmax (1, imageWidth) + 3) & ~3;
  72374. const int dataSize = lineStride * jmax (1, imageHeight);
  72375. imageData = (uint8*) juce_malloc (dataSize);
  72376. int ls, ps;
  72377. const uint8* srcData = other.lockPixelDataReadOnly (0, 0, imageWidth, imageHeight, ls, ps);
  72378. setPixelData (0, 0, imageWidth, imageHeight, srcData, ls);
  72379. other.releasePixelDataReadOnly (srcData);
  72380. }
  72381. Image::~Image()
  72382. {
  72383. juce_free (imageData);
  72384. }
  72385. LowLevelGraphicsContext* Image::createLowLevelContext()
  72386. {
  72387. return new LowLevelGraphicsSoftwareRenderer (*this);
  72388. }
  72389. uint8* Image::lockPixelDataReadWrite (int x, int y, int w, int h, int& ls, int& ps)
  72390. {
  72391. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= imageWidth && y + h <= imageHeight);
  72392. w = w;
  72393. h = h;
  72394. ls = lineStride;
  72395. ps = pixelStride;
  72396. return imageData + x * pixelStride + y * lineStride;
  72397. }
  72398. void Image::releasePixelDataReadWrite (void*)
  72399. {
  72400. }
  72401. const uint8* Image::lockPixelDataReadOnly (int x, int y, int w, int h, int& ls, int& ps) const
  72402. {
  72403. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= imageWidth && y + h <= imageHeight);
  72404. w = w;
  72405. h = h;
  72406. ls = lineStride;
  72407. ps = pixelStride;
  72408. return imageData + x * pixelStride + y * lineStride;
  72409. }
  72410. void Image::releasePixelDataReadOnly (const void*) const
  72411. {
  72412. }
  72413. void Image::setPixelData (int x, int y, int w, int h,
  72414. const uint8* sourcePixelData, int sourceLineStride)
  72415. {
  72416. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= imageWidth && y + h <= imageHeight);
  72417. if (Rectangle::intersectRectangles (x, y, w, h, 0, 0, imageWidth, imageHeight))
  72418. {
  72419. int ls, ps;
  72420. uint8* dest = lockPixelDataReadWrite (x, y, w, h, ls, ps);
  72421. for (int i = 0; i < h; ++i)
  72422. {
  72423. memcpy (dest + ls * i,
  72424. sourcePixelData + sourceLineStride * i,
  72425. w * pixelStride);
  72426. }
  72427. releasePixelDataReadWrite (dest);
  72428. }
  72429. }
  72430. void Image::clear (int dx, int dy, int dw, int dh,
  72431. const Colour& colourToClearTo)
  72432. {
  72433. const PixelARGB col (colourToClearTo.getPixelARGB());
  72434. int ls, ps;
  72435. uint8* dstData = lockPixelDataReadWrite (dx, dy, dw, dh, ls, ps);
  72436. uint8* dest = dstData;
  72437. while (--dh >= 0)
  72438. {
  72439. uint8* line = dest;
  72440. dest += ls;
  72441. if (isARGB())
  72442. {
  72443. for (int x = dw; --x >= 0;)
  72444. {
  72445. ((PixelARGB*) line)->set (col);
  72446. line += ps;
  72447. }
  72448. }
  72449. else if (isRGB())
  72450. {
  72451. for (int x = dw; --x >= 0;)
  72452. {
  72453. ((PixelRGB*) line)->set (col);
  72454. line += ps;
  72455. }
  72456. }
  72457. else
  72458. {
  72459. for (int x = dw; --x >= 0;)
  72460. {
  72461. *line = col.getAlpha();
  72462. line += ps;
  72463. }
  72464. }
  72465. }
  72466. releasePixelDataReadWrite (dstData);
  72467. }
  72468. Image* Image::createCopy (int newWidth, int newHeight,
  72469. const Graphics::ResamplingQuality quality) const
  72470. {
  72471. if (newWidth < 0)
  72472. newWidth = imageWidth;
  72473. if (newHeight < 0)
  72474. newHeight = imageHeight;
  72475. Image* const newImage = new Image (format, newWidth, newHeight, true);
  72476. Graphics g (*newImage);
  72477. g.setImageResamplingQuality (quality);
  72478. g.drawImage (this,
  72479. 0, 0, newWidth, newHeight,
  72480. 0, 0, imageWidth, imageHeight,
  72481. false);
  72482. return newImage;
  72483. }
  72484. const Colour Image::getPixelAt (const int x, const int y) const
  72485. {
  72486. Colour c;
  72487. if (((unsigned int) x) < (unsigned int) imageWidth
  72488. && ((unsigned int) y) < (unsigned int) imageHeight)
  72489. {
  72490. int ls, ps;
  72491. const uint8* const pixels = lockPixelDataReadOnly (x, y, 1, 1, ls, ps);
  72492. if (isARGB())
  72493. {
  72494. PixelARGB p (*(const PixelARGB*) pixels);
  72495. p.unpremultiply();
  72496. c = Colour (p.getARGB());
  72497. }
  72498. else if (isRGB())
  72499. c = Colour (((const PixelRGB*) pixels)->getARGB());
  72500. else
  72501. c = Colour ((uint8) 0, (uint8) 0, (uint8) 0, *pixels);
  72502. releasePixelDataReadOnly (pixels);
  72503. }
  72504. return c;
  72505. }
  72506. void Image::setPixelAt (const int x, const int y,
  72507. const Colour& colour)
  72508. {
  72509. if (((unsigned int) x) < (unsigned int) imageWidth
  72510. && ((unsigned int) y) < (unsigned int) imageHeight)
  72511. {
  72512. int ls, ps;
  72513. uint8* const pixels = lockPixelDataReadWrite (x, y, 1, 1, ls, ps);
  72514. const PixelARGB col (colour.getPixelARGB());
  72515. if (isARGB())
  72516. ((PixelARGB*) pixels)->set (col);
  72517. else if (isRGB())
  72518. ((PixelRGB*) pixels)->set (col);
  72519. else
  72520. *pixels = col.getAlpha();
  72521. releasePixelDataReadWrite (pixels);
  72522. }
  72523. }
  72524. void Image::multiplyAlphaAt (const int x, const int y,
  72525. const float multiplier)
  72526. {
  72527. if (((unsigned int) x) < (unsigned int) imageWidth
  72528. && ((unsigned int) y) < (unsigned int) imageHeight
  72529. && hasAlphaChannel())
  72530. {
  72531. int ls, ps;
  72532. uint8* const pixels = lockPixelDataReadWrite (x, y, 1, 1, ls, ps);
  72533. if (isARGB())
  72534. ((PixelARGB*) pixels)->multiplyAlpha (multiplier);
  72535. else
  72536. *pixels = (uint8) (*pixels * multiplier);
  72537. releasePixelDataReadWrite (pixels);
  72538. }
  72539. }
  72540. void Image::multiplyAllAlphas (const float amountToMultiplyBy)
  72541. {
  72542. if (hasAlphaChannel())
  72543. {
  72544. int ls, ps;
  72545. uint8* const pixels = lockPixelDataReadWrite (0, 0, getWidth(), getHeight(), ls, ps);
  72546. if (isARGB())
  72547. {
  72548. for (int y = 0; y < imageHeight; ++y)
  72549. {
  72550. uint8* p = pixels + y * ls;
  72551. for (int x = 0; x < imageWidth; ++x)
  72552. {
  72553. ((PixelARGB*) p)->multiplyAlpha (amountToMultiplyBy);
  72554. p += ps;
  72555. }
  72556. }
  72557. }
  72558. else
  72559. {
  72560. for (int y = 0; y < imageHeight; ++y)
  72561. {
  72562. uint8* p = pixels + y * ls;
  72563. for (int x = 0; x < imageWidth; ++x)
  72564. {
  72565. *p = (uint8) (*p * amountToMultiplyBy);
  72566. p += ps;
  72567. }
  72568. }
  72569. }
  72570. releasePixelDataReadWrite (pixels);
  72571. }
  72572. else
  72573. {
  72574. jassertfalse // can't do this without an alpha-channel!
  72575. }
  72576. }
  72577. void Image::desaturate()
  72578. {
  72579. if (isARGB() || isRGB())
  72580. {
  72581. int ls, ps;
  72582. uint8* const pixels = lockPixelDataReadWrite (0, 0, getWidth(), getHeight(), ls, ps);
  72583. if (isARGB())
  72584. {
  72585. for (int y = 0; y < imageHeight; ++y)
  72586. {
  72587. uint8* p = pixels + y * ls;
  72588. for (int x = 0; x < imageWidth; ++x)
  72589. {
  72590. ((PixelARGB*) p)->desaturate();
  72591. p += ps;
  72592. }
  72593. }
  72594. }
  72595. else
  72596. {
  72597. for (int y = 0; y < imageHeight; ++y)
  72598. {
  72599. uint8* p = pixels + y * ls;
  72600. for (int x = 0; x < imageWidth; ++x)
  72601. {
  72602. ((PixelRGB*) p)->desaturate();
  72603. p += ps;
  72604. }
  72605. }
  72606. }
  72607. releasePixelDataReadWrite (pixels);
  72608. }
  72609. }
  72610. void Image::createSolidAreaMask (RectangleList& result, const float alphaThreshold) const
  72611. {
  72612. if (hasAlphaChannel())
  72613. {
  72614. const uint8 threshold = (uint8) jlimit (0, 255, roundFloatToInt (alphaThreshold * 255.0f));
  72615. SparseSet <int> pixelsOnRow;
  72616. int ls, ps;
  72617. const uint8* const pixels = lockPixelDataReadOnly (0, 0, imageWidth, imageHeight, ls, ps);
  72618. for (int y = 0; y < imageHeight; ++y)
  72619. {
  72620. pixelsOnRow.clear();
  72621. const uint8* lineData = pixels + ls * y;
  72622. if (isARGB())
  72623. {
  72624. for (int x = 0; x < imageWidth; ++x)
  72625. {
  72626. if (((const PixelARGB*) lineData)->getAlpha() >= threshold)
  72627. pixelsOnRow.addRange (x, 1);
  72628. lineData += ps;
  72629. }
  72630. }
  72631. else
  72632. {
  72633. for (int x = 0; x < imageWidth; ++x)
  72634. {
  72635. if (*lineData >= threshold)
  72636. pixelsOnRow.addRange (x, 1);
  72637. lineData += ps;
  72638. }
  72639. }
  72640. for (int i = 0; i < pixelsOnRow.getNumRanges(); ++i)
  72641. {
  72642. int x, w;
  72643. if (pixelsOnRow.getRange (i, x, w))
  72644. result.add (Rectangle (x, y, w, 1));
  72645. }
  72646. result.consolidate();
  72647. }
  72648. releasePixelDataReadOnly (pixels);
  72649. }
  72650. else
  72651. {
  72652. result.add (0, 0, imageWidth, imageHeight);
  72653. }
  72654. }
  72655. void Image::moveImageSection (int dx, int dy,
  72656. int sx, int sy,
  72657. int w, int h)
  72658. {
  72659. if (dx < 0)
  72660. {
  72661. w += dx;
  72662. sx -= dx;
  72663. dx = 0;
  72664. }
  72665. if (dy < 0)
  72666. {
  72667. h += dy;
  72668. sy -= dy;
  72669. dy = 0;
  72670. }
  72671. if (sx < 0)
  72672. {
  72673. w += sx;
  72674. dx -= sx;
  72675. sx = 0;
  72676. }
  72677. if (sy < 0)
  72678. {
  72679. h += sy;
  72680. dy -= sy;
  72681. sy = 0;
  72682. }
  72683. const int minX = jmin (dx, sx);
  72684. const int minY = jmin (dy, sy);
  72685. w = jmin (w, getWidth() - jmax (sx, dx));
  72686. h = jmin (h, getHeight() - jmax (sy, dy));
  72687. if (w > 0 && h > 0)
  72688. {
  72689. const int maxX = jmax (dx, sx) + w;
  72690. const int maxY = jmax (dy, sy) + h;
  72691. int ls, ps;
  72692. uint8* const pixels = lockPixelDataReadWrite (minX, minY, maxX - minX, maxY - minY, ls, ps);
  72693. uint8* dst = pixels + ls * (dy - minY) + ps * (dx - minX);
  72694. const uint8* src = pixels + ls * (sy - minY) + ps * (sx - minX);
  72695. const int lineSize = ps * w;
  72696. if (dy > sy)
  72697. {
  72698. while (--h >= 0)
  72699. {
  72700. const int offset = h * ls;
  72701. memmove (dst + offset, src + offset, lineSize);
  72702. }
  72703. }
  72704. else if (dst != src)
  72705. {
  72706. while (--h >= 0)
  72707. {
  72708. memmove (dst, src, lineSize);
  72709. dst += ls;
  72710. src += ls;
  72711. }
  72712. }
  72713. releasePixelDataReadWrite (pixels);
  72714. }
  72715. }
  72716. END_JUCE_NAMESPACE
  72717. /********* End of inlined file: juce_Image.cpp *********/
  72718. /********* Start of inlined file: juce_ImageCache.cpp *********/
  72719. BEGIN_JUCE_NAMESPACE
  72720. struct CachedImageInfo
  72721. {
  72722. Image* image;
  72723. int64 hashCode;
  72724. int refCount;
  72725. unsigned int releaseTime;
  72726. juce_UseDebuggingNewOperator
  72727. };
  72728. static ImageCache* instance = 0;
  72729. static int cacheTimeout = 5000;
  72730. ImageCache::ImageCache() throw()
  72731. : images (4)
  72732. {
  72733. }
  72734. ImageCache::~ImageCache()
  72735. {
  72736. const ScopedLock sl (lock);
  72737. for (int i = images.size(); --i >= 0;)
  72738. {
  72739. CachedImageInfo* const ci = (CachedImageInfo*)(images.getUnchecked(i));
  72740. delete ci->image;
  72741. delete ci;
  72742. }
  72743. images.clear();
  72744. jassert (instance == this);
  72745. instance = 0;
  72746. }
  72747. Image* ImageCache::getFromHashCode (const int64 hashCode)
  72748. {
  72749. if (instance != 0)
  72750. {
  72751. const ScopedLock sl (instance->lock);
  72752. for (int i = instance->images.size(); --i >= 0;)
  72753. {
  72754. CachedImageInfo* const ci = (CachedImageInfo*) instance->images.getUnchecked(i);
  72755. if (ci->hashCode == hashCode)
  72756. {
  72757. atomicIncrement (ci->refCount);
  72758. return ci->image;
  72759. }
  72760. }
  72761. }
  72762. return 0;
  72763. }
  72764. void ImageCache::addImageToCache (Image* const image,
  72765. const int64 hashCode)
  72766. {
  72767. if (image != 0)
  72768. {
  72769. if (instance == 0)
  72770. instance = new ImageCache();
  72771. CachedImageInfo* const newC = new CachedImageInfo();
  72772. newC->hashCode = hashCode;
  72773. newC->image = image;
  72774. newC->refCount = 1;
  72775. newC->releaseTime = 0;
  72776. const ScopedLock sl (instance->lock);
  72777. instance->images.add (newC);
  72778. }
  72779. }
  72780. void ImageCache::release (Image* const imageToRelease)
  72781. {
  72782. if (imageToRelease != 0 && instance != 0)
  72783. {
  72784. const ScopedLock sl (instance->lock);
  72785. for (int i = instance->images.size(); --i >= 0;)
  72786. {
  72787. CachedImageInfo* const ci = (CachedImageInfo*) instance->images.getUnchecked(i);
  72788. if (ci->image == imageToRelease)
  72789. {
  72790. if (--(ci->refCount) == 0)
  72791. ci->releaseTime = Time::getApproximateMillisecondCounter();
  72792. if (! instance->isTimerRunning())
  72793. instance->startTimer (999);
  72794. break;
  72795. }
  72796. }
  72797. }
  72798. }
  72799. bool ImageCache::isImageInCache (Image* const imageToLookFor)
  72800. {
  72801. if (instance != 0)
  72802. {
  72803. const ScopedLock sl (instance->lock);
  72804. for (int i = instance->images.size(); --i >= 0;)
  72805. if (((const CachedImageInfo*) instance->images.getUnchecked(i))->image == imageToLookFor)
  72806. return true;
  72807. }
  72808. return false;
  72809. }
  72810. void ImageCache::incReferenceCount (Image* const image)
  72811. {
  72812. if (instance != 0)
  72813. {
  72814. const ScopedLock sl (instance->lock);
  72815. for (int i = instance->images.size(); --i >= 0;)
  72816. {
  72817. CachedImageInfo* const ci = (CachedImageInfo*) instance->images.getUnchecked(i);
  72818. if (ci->image == image)
  72819. {
  72820. ci->refCount++;
  72821. return;
  72822. }
  72823. }
  72824. }
  72825. jassertfalse // (trying to inc the ref count of an image that's not in the cache)
  72826. }
  72827. void ImageCache::timerCallback()
  72828. {
  72829. int numberStillNeedingReleasing = 0;
  72830. const unsigned int now = Time::getApproximateMillisecondCounter();
  72831. const ScopedLock sl (lock);
  72832. for (int i = images.size(); --i >= 0;)
  72833. {
  72834. CachedImageInfo* const ci = (CachedImageInfo*) images.getUnchecked(i);
  72835. if (ci->refCount <= 0)
  72836. {
  72837. if (now > ci->releaseTime + cacheTimeout
  72838. || now < ci->releaseTime - 1000)
  72839. {
  72840. images.remove (i);
  72841. delete ci->image;
  72842. delete ci;
  72843. }
  72844. else
  72845. {
  72846. ++numberStillNeedingReleasing;
  72847. }
  72848. }
  72849. }
  72850. if (numberStillNeedingReleasing == 0)
  72851. stopTimer();
  72852. }
  72853. Image* ImageCache::getFromFile (const File& file)
  72854. {
  72855. const int64 hashCode = file.getFullPathName().hashCode64();
  72856. Image* image = getFromHashCode (hashCode);
  72857. if (image == 0)
  72858. {
  72859. image = ImageFileFormat::loadFrom (file);
  72860. addImageToCache (image, hashCode);
  72861. }
  72862. return image;
  72863. }
  72864. Image* ImageCache::getFromMemory (const void* imageData,
  72865. const int dataSize)
  72866. {
  72867. const int64 hashCode = (int64) (pointer_sized_int) imageData;
  72868. Image* image = getFromHashCode (hashCode);
  72869. if (image == 0)
  72870. {
  72871. image = ImageFileFormat::loadFrom (imageData, dataSize);
  72872. addImageToCache (image, hashCode);
  72873. }
  72874. return image;
  72875. }
  72876. void ImageCache::setCacheTimeout (const int millisecs)
  72877. {
  72878. cacheTimeout = millisecs;
  72879. }
  72880. END_JUCE_NAMESPACE
  72881. /********* End of inlined file: juce_ImageCache.cpp *********/
  72882. /********* Start of inlined file: juce_ImageConvolutionKernel.cpp *********/
  72883. BEGIN_JUCE_NAMESPACE
  72884. ImageConvolutionKernel::ImageConvolutionKernel (const int size_) throw()
  72885. : size (size_)
  72886. {
  72887. values = new float* [size];
  72888. for (int i = size; --i >= 0;)
  72889. values[i] = new float [size];
  72890. clear();
  72891. }
  72892. ImageConvolutionKernel::~ImageConvolutionKernel() throw()
  72893. {
  72894. for (int i = size; --i >= 0;)
  72895. delete[] values[i];
  72896. delete[] values;
  72897. }
  72898. void ImageConvolutionKernel::setKernelValue (const int x,
  72899. const int y,
  72900. const float value) throw()
  72901. {
  72902. if (((unsigned int) x) < (unsigned int) size
  72903. && ((unsigned int) y) < (unsigned int) size)
  72904. {
  72905. values[x][y] = value;
  72906. }
  72907. else
  72908. {
  72909. jassertfalse
  72910. }
  72911. }
  72912. void ImageConvolutionKernel::clear() throw()
  72913. {
  72914. for (int y = size; --y >= 0;)
  72915. for (int x = size; --x >= 0;)
  72916. values[x][y] = 0;
  72917. }
  72918. void ImageConvolutionKernel::setOverallSum (const float desiredTotalSum) throw()
  72919. {
  72920. double currentTotal = 0.0;
  72921. for (int y = size; --y >= 0;)
  72922. for (int x = size; --x >= 0;)
  72923. currentTotal += values[x][y];
  72924. rescaleAllValues ((float) (desiredTotalSum / currentTotal));
  72925. }
  72926. void ImageConvolutionKernel::rescaleAllValues (const float multiplier) throw()
  72927. {
  72928. for (int y = size; --y >= 0;)
  72929. for (int x = size; --x >= 0;)
  72930. values[x][y] *= multiplier;
  72931. }
  72932. void ImageConvolutionKernel::createGaussianBlur (const float radius) throw()
  72933. {
  72934. const double radiusFactor = -1.0 / (radius * radius * 2);
  72935. const int centre = size >> 1;
  72936. for (int y = size; --y >= 0;)
  72937. {
  72938. for (int x = size; --x >= 0;)
  72939. {
  72940. const int cx = x - centre;
  72941. const int cy = y - centre;
  72942. values[x][y] = (float) exp (radiusFactor * (cx * cx + cy * cy));
  72943. }
  72944. }
  72945. setOverallSum (1.0f);
  72946. }
  72947. void ImageConvolutionKernel::applyToImage (Image& destImage,
  72948. const Image* sourceImage,
  72949. int dx,
  72950. int dy,
  72951. int dw,
  72952. int dh) const
  72953. {
  72954. Image* imageCreated = 0;
  72955. if (sourceImage == 0)
  72956. {
  72957. sourceImage = imageCreated = destImage.createCopy();
  72958. }
  72959. else
  72960. {
  72961. jassert (sourceImage->getWidth() == destImage.getWidth()
  72962. && sourceImage->getHeight() == destImage.getHeight()
  72963. && sourceImage->getFormat() == destImage.getFormat());
  72964. if (sourceImage->getWidth() != destImage.getWidth()
  72965. || sourceImage->getHeight() != destImage.getHeight()
  72966. || sourceImage->getFormat() != destImage.getFormat())
  72967. return;
  72968. }
  72969. const int imageWidth = destImage.getWidth();
  72970. const int imageHeight = destImage.getHeight();
  72971. if (dx >= imageWidth || dy >= imageHeight)
  72972. return;
  72973. if (dx + dw > imageWidth)
  72974. dw = imageWidth - dx;
  72975. if (dy + dh > imageHeight)
  72976. dh = imageHeight - dy;
  72977. const int dx2 = dx + dw;
  72978. const int dy2 = dy + dh;
  72979. int lineStride, pixelStride;
  72980. uint8* pixels = destImage.lockPixelDataReadWrite (dx, dy, dw, dh, lineStride, pixelStride);
  72981. uint8* line = pixels;
  72982. int srcLineStride, srcPixelStride;
  72983. const uint8* srcPixels = sourceImage->lockPixelDataReadOnly (0, 0, sourceImage->getWidth(), sourceImage->getHeight(), srcLineStride, srcPixelStride);
  72984. if (pixelStride == 4)
  72985. {
  72986. for (int y = dy; y < dy2; ++y)
  72987. {
  72988. uint8* dest = line;
  72989. line += lineStride;
  72990. for (int x = dx; x < dx2; ++x)
  72991. {
  72992. float c1 = 0;
  72993. float c2 = 0;
  72994. float c3 = 0;
  72995. float c4 = 0;
  72996. for (int yy = 0; yy < size; ++yy)
  72997. {
  72998. const int sy = y + yy - (size >> 1);
  72999. if (sy >= imageHeight)
  73000. break;
  73001. if (sy >= 0)
  73002. {
  73003. int sx = x - (size >> 1);
  73004. const uint8* src = srcPixels + srcLineStride * sy + srcPixelStride * sx;
  73005. for (int xx = 0; xx < size; ++xx)
  73006. {
  73007. if (sx >= imageWidth)
  73008. break;
  73009. if (sx >= 0)
  73010. {
  73011. const float kernelMult = values[xx][yy];
  73012. c1 += kernelMult * *src++;
  73013. c2 += kernelMult * *src++;
  73014. c3 += kernelMult * *src++;
  73015. c4 += kernelMult * *src++;
  73016. }
  73017. else
  73018. {
  73019. src += 4;
  73020. }
  73021. ++sx;
  73022. }
  73023. }
  73024. }
  73025. *dest++ = (uint8) jmin (0xff, roundFloatToInt (c1));
  73026. *dest++ = (uint8) jmin (0xff, roundFloatToInt (c2));
  73027. *dest++ = (uint8) jmin (0xff, roundFloatToInt (c3));
  73028. *dest++ = (uint8) jmin (0xff, roundFloatToInt (c4));
  73029. }
  73030. }
  73031. }
  73032. else if (pixelStride == 3)
  73033. {
  73034. for (int y = dy; y < dy2; ++y)
  73035. {
  73036. uint8* dest = line;
  73037. line += lineStride;
  73038. for (int x = dx; x < dx2; ++x)
  73039. {
  73040. float c1 = 0;
  73041. float c2 = 0;
  73042. float c3 = 0;
  73043. for (int yy = 0; yy < size; ++yy)
  73044. {
  73045. const int sy = y + yy - (size >> 1);
  73046. if (sy >= imageHeight)
  73047. break;
  73048. if (sy >= 0)
  73049. {
  73050. int sx = x - (size >> 1);
  73051. const uint8* src = srcPixels + srcLineStride * sy + srcPixelStride * sx;
  73052. for (int xx = 0; xx < size; ++xx)
  73053. {
  73054. if (sx >= imageWidth)
  73055. break;
  73056. if (sx >= 0)
  73057. {
  73058. const float kernelMult = values[xx][yy];
  73059. c1 += kernelMult * *src++;
  73060. c2 += kernelMult * *src++;
  73061. c3 += kernelMult * *src++;
  73062. }
  73063. else
  73064. {
  73065. src += 3;
  73066. }
  73067. ++sx;
  73068. }
  73069. }
  73070. }
  73071. *dest++ = (uint8) roundFloatToInt (c1);
  73072. *dest++ = (uint8) roundFloatToInt (c2);
  73073. *dest++ = (uint8) roundFloatToInt (c3);
  73074. }
  73075. }
  73076. }
  73077. sourceImage->releasePixelDataReadOnly (srcPixels);
  73078. destImage.releasePixelDataReadWrite (pixels);
  73079. if (imageCreated != 0)
  73080. delete imageCreated;
  73081. }
  73082. END_JUCE_NAMESPACE
  73083. /********* End of inlined file: juce_ImageConvolutionKernel.cpp *********/
  73084. /********* Start of inlined file: juce_ImageFileFormat.cpp *********/
  73085. BEGIN_JUCE_NAMESPACE
  73086. /********* Start of inlined file: juce_GIFLoader.h *********/
  73087. #ifndef __JUCE_GIFLOADER_JUCEHEADER__
  73088. #define __JUCE_GIFLOADER_JUCEHEADER__
  73089. #ifndef DOXYGEN
  73090. static const int maxGifCode = 1 << 12;
  73091. /**
  73092. Used internally by ImageFileFormat - don't use this class directly in your
  73093. application.
  73094. @see ImageFileFormat
  73095. */
  73096. class GIFLoader
  73097. {
  73098. public:
  73099. GIFLoader (InputStream& in);
  73100. ~GIFLoader() throw();
  73101. Image* getImage() const throw() { return image; }
  73102. private:
  73103. Image* image;
  73104. InputStream& input;
  73105. uint8 buffer [300];
  73106. uint8 palette [256][4];
  73107. bool dataBlockIsZero, fresh, finished;
  73108. int currentBit, lastBit, lastByteIndex;
  73109. int codeSize, setCodeSize;
  73110. int maxCode, maxCodeSize;
  73111. int firstcode, oldcode;
  73112. int clearCode, end_code;
  73113. int table [2] [maxGifCode];
  73114. int stack [2 * maxGifCode];
  73115. int *sp;
  73116. bool getSizeFromHeader (int& width, int& height);
  73117. bool readPalette (const int numCols);
  73118. int readDataBlock (unsigned char* dest);
  73119. int processExtension (int type, int& transparent);
  73120. int readLZWByte (bool initialise, int input_code_size);
  73121. int getCode (int code_size, bool initialise);
  73122. bool readImage (int width, int height,
  73123. int interlace, int transparent);
  73124. GIFLoader (const GIFLoader&);
  73125. const GIFLoader& operator= (const GIFLoader&);
  73126. };
  73127. #endif // DOXYGEN
  73128. #endif // __JUCE_GIFLOADER_JUCEHEADER__
  73129. /********* End of inlined file: juce_GIFLoader.h *********/
  73130. Image* juce_loadPNGImageFromStream (InputStream& inputStream) throw();
  73131. bool juce_writePNGImageToStream (const Image& image, OutputStream& out) throw();
  73132. PNGImageFormat::PNGImageFormat() throw() {}
  73133. PNGImageFormat::~PNGImageFormat() throw() {}
  73134. const String PNGImageFormat::getFormatName()
  73135. {
  73136. return T("PNG");
  73137. }
  73138. bool PNGImageFormat::canUnderstand (InputStream& in)
  73139. {
  73140. const int bytesNeeded = 4;
  73141. char header [bytesNeeded];
  73142. return in.read (header, bytesNeeded) == bytesNeeded
  73143. && header[1] == 'P'
  73144. && header[2] == 'N'
  73145. && header[3] == 'G';
  73146. }
  73147. Image* PNGImageFormat::decodeImage (InputStream& in)
  73148. {
  73149. return juce_loadPNGImageFromStream (in);
  73150. }
  73151. bool PNGImageFormat::writeImageToStream (const Image& sourceImage,
  73152. OutputStream& destStream)
  73153. {
  73154. return juce_writePNGImageToStream (sourceImage, destStream);
  73155. }
  73156. Image* juce_loadJPEGImageFromStream (InputStream& inputStream) throw();
  73157. bool juce_writeJPEGImageToStream (const Image& image, OutputStream& out, float quality) throw();
  73158. JPEGImageFormat::JPEGImageFormat() throw()
  73159. : quality (-1.0f)
  73160. {
  73161. }
  73162. JPEGImageFormat::~JPEGImageFormat() throw() {}
  73163. void JPEGImageFormat::setQuality (const float newQuality)
  73164. {
  73165. quality = newQuality;
  73166. }
  73167. const String JPEGImageFormat::getFormatName()
  73168. {
  73169. return T("JPEG");
  73170. }
  73171. bool JPEGImageFormat::canUnderstand (InputStream& in)
  73172. {
  73173. const int bytesNeeded = 10;
  73174. uint8 header [bytesNeeded];
  73175. if (in.read (header, bytesNeeded) == bytesNeeded)
  73176. {
  73177. return header[0] == 0xff
  73178. && header[1] == 0xd8
  73179. && header[2] == 0xff
  73180. && (header[3] == 0xe0 || header[3] == 0xe1);
  73181. }
  73182. return false;
  73183. }
  73184. Image* JPEGImageFormat::decodeImage (InputStream& in)
  73185. {
  73186. return juce_loadJPEGImageFromStream (in);
  73187. }
  73188. bool JPEGImageFormat::writeImageToStream (const Image& sourceImage,
  73189. OutputStream& destStream)
  73190. {
  73191. return juce_writeJPEGImageToStream (sourceImage, destStream, quality);
  73192. }
  73193. class GIFImageFormat : public ImageFileFormat
  73194. {
  73195. public:
  73196. GIFImageFormat() throw() {}
  73197. ~GIFImageFormat() throw() {}
  73198. const String getFormatName()
  73199. {
  73200. return T("GIF");
  73201. }
  73202. bool canUnderstand (InputStream& in)
  73203. {
  73204. const int bytesNeeded = 4;
  73205. char header [bytesNeeded];
  73206. return (in.read (header, bytesNeeded) == bytesNeeded)
  73207. && header[0] == 'G'
  73208. && header[1] == 'I'
  73209. && header[2] == 'F';
  73210. }
  73211. Image* decodeImage (InputStream& in)
  73212. {
  73213. GIFLoader* const loader = new GIFLoader (in);
  73214. Image* const im = loader->getImage();
  73215. delete loader;
  73216. return im;
  73217. }
  73218. bool writeImageToStream (const Image& /*sourceImage*/, OutputStream& /*destStream*/)
  73219. {
  73220. return false;
  73221. }
  73222. };
  73223. ImageFileFormat* ImageFileFormat::findImageFormatForStream (InputStream& input)
  73224. {
  73225. static PNGImageFormat png;
  73226. static JPEGImageFormat jpg;
  73227. static GIFImageFormat gif;
  73228. ImageFileFormat* formats[4];
  73229. int numFormats = 0;
  73230. formats [numFormats++] = &png;
  73231. formats [numFormats++] = &jpg;
  73232. formats [numFormats++] = &gif;
  73233. const int64 streamPos = input.getPosition();
  73234. for (int i = 0; i < numFormats; ++i)
  73235. {
  73236. const bool found = formats[i]->canUnderstand (input);
  73237. input.setPosition (streamPos);
  73238. if (found)
  73239. return formats[i];
  73240. }
  73241. return 0;
  73242. }
  73243. Image* ImageFileFormat::loadFrom (InputStream& input)
  73244. {
  73245. ImageFileFormat* const format = findImageFormatForStream (input);
  73246. if (format != 0)
  73247. return format->decodeImage (input);
  73248. return 0;
  73249. }
  73250. Image* ImageFileFormat::loadFrom (const File& file)
  73251. {
  73252. InputStream* const in = file.createInputStream();
  73253. if (in != 0)
  73254. {
  73255. BufferedInputStream b (in, 8192, true);
  73256. return loadFrom (b);
  73257. }
  73258. return 0;
  73259. }
  73260. Image* ImageFileFormat::loadFrom (const void* rawData, const int numBytes)
  73261. {
  73262. if (rawData != 0 && numBytes > 4)
  73263. {
  73264. MemoryInputStream stream (rawData, numBytes, false);
  73265. return loadFrom (stream);
  73266. }
  73267. return 0;
  73268. }
  73269. END_JUCE_NAMESPACE
  73270. /********* End of inlined file: juce_ImageFileFormat.cpp *********/
  73271. /********* Start of inlined file: juce_GIFLoader.cpp *********/
  73272. BEGIN_JUCE_NAMESPACE
  73273. static inline int makeWord (const unsigned char a, const unsigned char b) throw()
  73274. {
  73275. return (b << 8) | a;
  73276. }
  73277. GIFLoader::GIFLoader (InputStream& in)
  73278. : image (0),
  73279. input (in),
  73280. dataBlockIsZero (false),
  73281. fresh (false),
  73282. finished (false)
  73283. {
  73284. currentBit = lastBit = lastByteIndex = 0;
  73285. maxCode = maxCodeSize = codeSize = setCodeSize = 0;
  73286. firstcode = oldcode = 0;
  73287. clearCode = end_code = 0;
  73288. int imageWidth, imageHeight;
  73289. int transparent = -1;
  73290. if (! getSizeFromHeader (imageWidth, imageHeight))
  73291. return;
  73292. if ((imageWidth <= 0) || (imageHeight <= 0))
  73293. return;
  73294. unsigned char buf [16];
  73295. if (in.read (buf, 3) != 3)
  73296. return;
  73297. int numColours = 2 << (buf[0] & 7);
  73298. if ((buf[0] & 0x80) != 0)
  73299. readPalette (numColours);
  73300. for (;;)
  73301. {
  73302. if (input.read (buf, 1) != 1)
  73303. break;
  73304. if (buf[0] == ';')
  73305. break;
  73306. if (buf[0] == '!')
  73307. {
  73308. if (input.read (buf, 1) != 1)
  73309. break;
  73310. if (processExtension (buf[0], transparent) < 0)
  73311. break;
  73312. continue;
  73313. }
  73314. if (buf[0] != ',')
  73315. continue;
  73316. if (input.read (buf, 9) != 9)
  73317. break;
  73318. imageWidth = makeWord (buf[4], buf[5]);
  73319. imageHeight = makeWord (buf[6], buf[7]);
  73320. numColours = 2 << (buf[8] & 7);
  73321. if ((buf[8] & 0x80) != 0)
  73322. if (! readPalette (numColours))
  73323. break;
  73324. image = new Image ((transparent >= 0) ? Image::ARGB : Image::RGB,
  73325. imageWidth, imageHeight, (transparent >= 0));
  73326. readImage (imageWidth, imageHeight,
  73327. (buf[8] & 0x40) != 0,
  73328. transparent);
  73329. break;
  73330. }
  73331. }
  73332. GIFLoader::~GIFLoader() throw()
  73333. {
  73334. }
  73335. bool GIFLoader::getSizeFromHeader (int& w, int& h)
  73336. {
  73337. unsigned char b [8];
  73338. if (input.read (b, 6) == 6)
  73339. {
  73340. if ((strncmp ("GIF87a", (char*) b, 6) == 0)
  73341. || (strncmp ("GIF89a", (char*) b, 6) == 0))
  73342. {
  73343. if (input.read (b, 4) == 4)
  73344. {
  73345. w = makeWord (b[0], b[1]);
  73346. h = makeWord (b[2], b[3]);
  73347. return true;
  73348. }
  73349. }
  73350. }
  73351. return false;
  73352. }
  73353. bool GIFLoader::readPalette (const int numCols)
  73354. {
  73355. unsigned char rgb[4];
  73356. for (int i = 0; i < numCols; ++i)
  73357. {
  73358. input.read (rgb, 3);
  73359. palette [i][0] = rgb[0];
  73360. palette [i][1] = rgb[1];
  73361. palette [i][2] = rgb[2];
  73362. palette [i][3] = 0xff;
  73363. }
  73364. return true;
  73365. }
  73366. int GIFLoader::readDataBlock (unsigned char* const dest)
  73367. {
  73368. unsigned char n;
  73369. if (input.read (&n, 1) == 1)
  73370. {
  73371. dataBlockIsZero = (n == 0);
  73372. if (dataBlockIsZero || (input.read (dest, n) == n))
  73373. return n;
  73374. }
  73375. return -1;
  73376. }
  73377. int GIFLoader::processExtension (const int type, int& transparent)
  73378. {
  73379. unsigned char b [300];
  73380. int n = 0;
  73381. if (type == 0xf9)
  73382. {
  73383. n = readDataBlock (b);
  73384. if (n < 0)
  73385. return 1;
  73386. if ((b[0] & 0x1) != 0)
  73387. transparent = b[3];
  73388. }
  73389. do
  73390. {
  73391. n = readDataBlock (b);
  73392. }
  73393. while (n > 0);
  73394. return n;
  73395. }
  73396. int GIFLoader::getCode (const int codeSize, const bool initialise)
  73397. {
  73398. if (initialise)
  73399. {
  73400. currentBit = 0;
  73401. lastBit = 0;
  73402. finished = false;
  73403. return 0;
  73404. }
  73405. if ((currentBit + codeSize) >= lastBit)
  73406. {
  73407. if (finished)
  73408. return -1;
  73409. buffer[0] = buffer [lastByteIndex - 2];
  73410. buffer[1] = buffer [lastByteIndex - 1];
  73411. const int n = readDataBlock (&buffer[2]);
  73412. if (n == 0)
  73413. finished = true;
  73414. lastByteIndex = 2 + n;
  73415. currentBit = (currentBit - lastBit) + 16;
  73416. lastBit = (2 + n) * 8 ;
  73417. }
  73418. int result = 0;
  73419. int i = currentBit;
  73420. for (int j = 0; j < codeSize; ++j)
  73421. {
  73422. result |= ((buffer[i >> 3] & (1 << (i & 7))) != 0) << j;
  73423. ++i;
  73424. }
  73425. currentBit += codeSize;
  73426. return result;
  73427. }
  73428. int GIFLoader::readLZWByte (const bool initialise, const int inputCodeSize)
  73429. {
  73430. int code, incode, i;
  73431. if (initialise)
  73432. {
  73433. setCodeSize = inputCodeSize;
  73434. codeSize = setCodeSize + 1;
  73435. clearCode = 1 << setCodeSize;
  73436. end_code = clearCode + 1;
  73437. maxCodeSize = 2 * clearCode;
  73438. maxCode = clearCode + 2;
  73439. getCode (0, true);
  73440. fresh = true;
  73441. for (i = 0; i < clearCode; ++i)
  73442. {
  73443. table[0][i] = 0;
  73444. table[1][i] = i;
  73445. }
  73446. for (; i < maxGifCode; ++i)
  73447. {
  73448. table[0][i] = 0;
  73449. table[1][i] = 0;
  73450. }
  73451. sp = stack;
  73452. return 0;
  73453. }
  73454. else if (fresh)
  73455. {
  73456. fresh = false;
  73457. do
  73458. {
  73459. firstcode = oldcode
  73460. = getCode (codeSize, false);
  73461. }
  73462. while (firstcode == clearCode);
  73463. return firstcode;
  73464. }
  73465. if (sp > stack)
  73466. return *--sp;
  73467. while ((code = getCode (codeSize, false)) >= 0)
  73468. {
  73469. if (code == clearCode)
  73470. {
  73471. for (i = 0; i < clearCode; ++i)
  73472. {
  73473. table[0][i] = 0;
  73474. table[1][i] = i;
  73475. }
  73476. for (; i < maxGifCode; ++i)
  73477. {
  73478. table[0][i] = 0;
  73479. table[1][i] = 0;
  73480. }
  73481. codeSize = setCodeSize + 1;
  73482. maxCodeSize = 2 * clearCode;
  73483. maxCode = clearCode + 2;
  73484. sp = stack;
  73485. firstcode = oldcode = getCode (codeSize, false);
  73486. return firstcode;
  73487. }
  73488. else if (code == end_code)
  73489. {
  73490. if (dataBlockIsZero)
  73491. return -2;
  73492. unsigned char buf [260];
  73493. int n;
  73494. while ((n = readDataBlock (buf)) > 0)
  73495. {}
  73496. if (n != 0)
  73497. return -2;
  73498. }
  73499. incode = code;
  73500. if (code >= maxCode)
  73501. {
  73502. *sp++ = firstcode;
  73503. code = oldcode;
  73504. }
  73505. while (code >= clearCode)
  73506. {
  73507. *sp++ = table[1][code];
  73508. if (code == table[0][code])
  73509. return -2;
  73510. code = table[0][code];
  73511. }
  73512. *sp++ = firstcode = table[1][code];
  73513. if ((code = maxCode) < maxGifCode)
  73514. {
  73515. table[0][code] = oldcode;
  73516. table[1][code] = firstcode;
  73517. ++maxCode;
  73518. if ((maxCode >= maxCodeSize)
  73519. && (maxCodeSize < maxGifCode))
  73520. {
  73521. maxCodeSize <<= 1;
  73522. ++codeSize;
  73523. }
  73524. }
  73525. oldcode = incode;
  73526. if (sp > stack)
  73527. return *--sp;
  73528. }
  73529. return code;
  73530. }
  73531. bool GIFLoader::readImage (const int width, const int height,
  73532. const int interlace, const int transparent)
  73533. {
  73534. unsigned char c;
  73535. if (input.read (&c, 1) != 1
  73536. || readLZWByte (true, c) < 0)
  73537. return false;
  73538. if (transparent >= 0)
  73539. {
  73540. palette [transparent][0] = 0;
  73541. palette [transparent][1] = 0;
  73542. palette [transparent][2] = 0;
  73543. palette [transparent][3] = 0;
  73544. }
  73545. int index;
  73546. int xpos = 0, ypos = 0, pass = 0;
  73547. int stride, pixelStride;
  73548. uint8* const pixels = image->lockPixelDataReadWrite (0, 0, width, height, stride, pixelStride);
  73549. uint8* p = pixels;
  73550. const bool hasAlpha = image->hasAlphaChannel();
  73551. while ((index = readLZWByte (false, c)) >= 0)
  73552. {
  73553. const uint8* const paletteEntry = palette [index];
  73554. if (hasAlpha)
  73555. {
  73556. ((PixelARGB*) p)->setARGB (paletteEntry[3],
  73557. paletteEntry[0],
  73558. paletteEntry[1],
  73559. paletteEntry[2]);
  73560. ((PixelARGB*) p)->premultiply();
  73561. p += pixelStride;
  73562. }
  73563. else
  73564. {
  73565. ((PixelRGB*) p)->setARGB (0,
  73566. paletteEntry[0],
  73567. paletteEntry[1],
  73568. paletteEntry[2]);
  73569. p += pixelStride;
  73570. }
  73571. ++xpos;
  73572. if (xpos == width)
  73573. {
  73574. xpos = 0;
  73575. if (interlace)
  73576. {
  73577. switch (pass)
  73578. {
  73579. case 0:
  73580. case 1:
  73581. ypos += 8;
  73582. break;
  73583. case 2:
  73584. ypos += 4;
  73585. break;
  73586. case 3:
  73587. ypos += 2;
  73588. break;
  73589. }
  73590. while (ypos >= height)
  73591. {
  73592. ++pass;
  73593. switch (pass)
  73594. {
  73595. case 1:
  73596. ypos = 4;
  73597. break;
  73598. case 2:
  73599. ypos = 2;
  73600. break;
  73601. case 3:
  73602. ypos = 1;
  73603. break;
  73604. default:
  73605. return true;
  73606. }
  73607. }
  73608. }
  73609. else
  73610. {
  73611. ++ypos;
  73612. }
  73613. p = pixels + xpos * pixelStride + ypos * stride;
  73614. }
  73615. if (ypos >= height)
  73616. break;
  73617. }
  73618. image->releasePixelDataReadWrite (pixels);
  73619. return true;
  73620. }
  73621. END_JUCE_NAMESPACE
  73622. /********* End of inlined file: juce_GIFLoader.cpp *********/
  73623. #endif
  73624. //==============================================================================
  73625. // some files include lots of library code, so leave them to the end to avoid cluttering
  73626. // up the build for the clean files.
  73627. /********* Start of inlined file: juce_GZIPCompressorOutputStream.cpp *********/
  73628. namespace zlibNamespace
  73629. {
  73630. #if JUCE_INCLUDE_ZLIB_CODE
  73631. #undef OS_CODE
  73632. #undef fdopen
  73633. /********* Start of inlined file: zlib.h *********/
  73634. #ifndef ZLIB_H
  73635. #define ZLIB_H
  73636. /********* Start of inlined file: zconf.h *********/
  73637. /* @(#) $Id: zconf.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  73638. #ifndef ZCONF_H
  73639. #define ZCONF_H
  73640. // *** Just a few hacks here to make it compile nicely with Juce..
  73641. #define Z_PREFIX 1
  73642. #undef __MACTYPES__
  73643. #ifdef _MSC_VER
  73644. #pragma warning (disable : 4131 4127 4244 4267)
  73645. #endif
  73646. /*
  73647. * If you *really* need a unique prefix for all types and library functions,
  73648. * compile with -DZ_PREFIX. The "standard" zlib should be compiled without it.
  73649. */
  73650. #ifdef Z_PREFIX
  73651. # define deflateInit_ z_deflateInit_
  73652. # define deflate z_deflate
  73653. # define deflateEnd z_deflateEnd
  73654. # define inflateInit_ z_inflateInit_
  73655. # define inflate z_inflate
  73656. # define inflateEnd z_inflateEnd
  73657. # define deflateInit2_ z_deflateInit2_
  73658. # define deflateSetDictionary z_deflateSetDictionary
  73659. # define deflateCopy z_deflateCopy
  73660. # define deflateReset z_deflateReset
  73661. # define deflateParams z_deflateParams
  73662. # define deflateBound z_deflateBound
  73663. # define deflatePrime z_deflatePrime
  73664. # define inflateInit2_ z_inflateInit2_
  73665. # define inflateSetDictionary z_inflateSetDictionary
  73666. # define inflateSync z_inflateSync
  73667. # define inflateSyncPoint z_inflateSyncPoint
  73668. # define inflateCopy z_inflateCopy
  73669. # define inflateReset z_inflateReset
  73670. # define inflateBack z_inflateBack
  73671. # define inflateBackEnd z_inflateBackEnd
  73672. # define compress z_compress
  73673. # define compress2 z_compress2
  73674. # define compressBound z_compressBound
  73675. # define uncompress z_uncompress
  73676. # define adler32 z_adler32
  73677. # define crc32 z_crc32
  73678. # define get_crc_table z_get_crc_table
  73679. # define zError z_zError
  73680. # define alloc_func z_alloc_func
  73681. # define free_func z_free_func
  73682. # define in_func z_in_func
  73683. # define out_func z_out_func
  73684. # define Byte z_Byte
  73685. # define uInt z_uInt
  73686. # define uLong z_uLong
  73687. # define Bytef z_Bytef
  73688. # define charf z_charf
  73689. # define intf z_intf
  73690. # define uIntf z_uIntf
  73691. # define uLongf z_uLongf
  73692. # define voidpf z_voidpf
  73693. # define voidp z_voidp
  73694. #endif
  73695. #if defined(__MSDOS__) && !defined(MSDOS)
  73696. # define MSDOS
  73697. #endif
  73698. #if (defined(OS_2) || defined(__OS2__)) && !defined(OS2)
  73699. # define OS2
  73700. #endif
  73701. #if defined(_WINDOWS) && !defined(WINDOWS)
  73702. # define WINDOWS
  73703. #endif
  73704. #if defined(_WIN32) || defined(_WIN32_WCE) || defined(__WIN32__)
  73705. # ifndef WIN32
  73706. # define WIN32
  73707. # endif
  73708. #endif
  73709. #if (defined(MSDOS) || defined(OS2) || defined(WINDOWS)) && !defined(WIN32)
  73710. # if !defined(__GNUC__) && !defined(__FLAT__) && !defined(__386__)
  73711. # ifndef SYS16BIT
  73712. # define SYS16BIT
  73713. # endif
  73714. # endif
  73715. #endif
  73716. /*
  73717. * Compile with -DMAXSEG_64K if the alloc function cannot allocate more
  73718. * than 64k bytes at a time (needed on systems with 16-bit int).
  73719. */
  73720. #ifdef SYS16BIT
  73721. # define MAXSEG_64K
  73722. #endif
  73723. #ifdef MSDOS
  73724. # define UNALIGNED_OK
  73725. #endif
  73726. #ifdef __STDC_VERSION__
  73727. # ifndef STDC
  73728. # define STDC
  73729. # endif
  73730. # if __STDC_VERSION__ >= 199901L
  73731. # ifndef STDC99
  73732. # define STDC99
  73733. # endif
  73734. # endif
  73735. #endif
  73736. #if !defined(STDC) && (defined(__STDC__) || defined(__cplusplus))
  73737. # define STDC
  73738. #endif
  73739. #if !defined(STDC) && (defined(__GNUC__) || defined(__BORLANDC__))
  73740. # define STDC
  73741. #endif
  73742. #if !defined(STDC) && (defined(MSDOS) || defined(WINDOWS) || defined(WIN32))
  73743. # define STDC
  73744. #endif
  73745. #if !defined(STDC) && (defined(OS2) || defined(__HOS_AIX__))
  73746. # define STDC
  73747. #endif
  73748. #if defined(__OS400__) && !defined(STDC) /* iSeries (formerly AS/400). */
  73749. # define STDC
  73750. #endif
  73751. #ifndef STDC
  73752. # ifndef const /* cannot use !defined(STDC) && !defined(const) on Mac */
  73753. # define const /* note: need a more gentle solution here */
  73754. # endif
  73755. #endif
  73756. /* Some Mac compilers merge all .h files incorrectly: */
  73757. #if defined(__MWERKS__)||defined(applec)||defined(THINK_C)||defined(__SC__)
  73758. # define NO_DUMMY_DECL
  73759. #endif
  73760. /* Maximum value for memLevel in deflateInit2 */
  73761. #ifndef MAX_MEM_LEVEL
  73762. # ifdef MAXSEG_64K
  73763. # define MAX_MEM_LEVEL 8
  73764. # else
  73765. # define MAX_MEM_LEVEL 9
  73766. # endif
  73767. #endif
  73768. /* Maximum value for windowBits in deflateInit2 and inflateInit2.
  73769. * WARNING: reducing MAX_WBITS makes minigzip unable to extract .gz files
  73770. * created by gzip. (Files created by minigzip can still be extracted by
  73771. * gzip.)
  73772. */
  73773. #ifndef MAX_WBITS
  73774. # define MAX_WBITS 15 /* 32K LZ77 window */
  73775. #endif
  73776. /* The memory requirements for deflate are (in bytes):
  73777. (1 << (windowBits+2)) + (1 << (memLevel+9))
  73778. that is: 128K for windowBits=15 + 128K for memLevel = 8 (default values)
  73779. plus a few kilobytes for small objects. For example, if you want to reduce
  73780. the default memory requirements from 256K to 128K, compile with
  73781. make CFLAGS="-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7"
  73782. Of course this will generally degrade compression (there's no free lunch).
  73783. The memory requirements for inflate are (in bytes) 1 << windowBits
  73784. that is, 32K for windowBits=15 (default value) plus a few kilobytes
  73785. for small objects.
  73786. */
  73787. /* Type declarations */
  73788. #ifndef OF /* function prototypes */
  73789. # ifdef STDC
  73790. # define OF(args) args
  73791. # else
  73792. # define OF(args) ()
  73793. # endif
  73794. #endif
  73795. /* The following definitions for FAR are needed only for MSDOS mixed
  73796. * model programming (small or medium model with some far allocations).
  73797. * This was tested only with MSC; for other MSDOS compilers you may have
  73798. * to define NO_MEMCPY in zutil.h. If you don't need the mixed model,
  73799. * just define FAR to be empty.
  73800. */
  73801. #ifdef SYS16BIT
  73802. # if defined(M_I86SM) || defined(M_I86MM)
  73803. /* MSC small or medium model */
  73804. # define SMALL_MEDIUM
  73805. # ifdef _MSC_VER
  73806. # define FAR _far
  73807. # else
  73808. # define FAR far
  73809. # endif
  73810. # endif
  73811. # if (defined(__SMALL__) || defined(__MEDIUM__))
  73812. /* Turbo C small or medium model */
  73813. # define SMALL_MEDIUM
  73814. # ifdef __BORLANDC__
  73815. # define FAR _far
  73816. # else
  73817. # define FAR far
  73818. # endif
  73819. # endif
  73820. #endif
  73821. #if defined(WINDOWS) || defined(WIN32)
  73822. /* If building or using zlib as a DLL, define ZLIB_DLL.
  73823. * This is not mandatory, but it offers a little performance increase.
  73824. */
  73825. # ifdef ZLIB_DLL
  73826. # if defined(WIN32) && (!defined(__BORLANDC__) || (__BORLANDC__ >= 0x500))
  73827. # ifdef ZLIB_INTERNAL
  73828. # define ZEXTERN extern __declspec(dllexport)
  73829. # else
  73830. # define ZEXTERN extern __declspec(dllimport)
  73831. # endif
  73832. # endif
  73833. # endif /* ZLIB_DLL */
  73834. /* If building or using zlib with the WINAPI/WINAPIV calling convention,
  73835. * define ZLIB_WINAPI.
  73836. * Caution: the standard ZLIB1.DLL is NOT compiled using ZLIB_WINAPI.
  73837. */
  73838. # ifdef ZLIB_WINAPI
  73839. # ifdef FAR
  73840. # undef FAR
  73841. # endif
  73842. # include <windows.h>
  73843. /* No need for _export, use ZLIB.DEF instead. */
  73844. /* For complete Windows compatibility, use WINAPI, not __stdcall. */
  73845. # define ZEXPORT WINAPI
  73846. # ifdef WIN32
  73847. # define ZEXPORTVA WINAPIV
  73848. # else
  73849. # define ZEXPORTVA FAR CDECL
  73850. # endif
  73851. # endif
  73852. #endif
  73853. #if defined (__BEOS__)
  73854. # ifdef ZLIB_DLL
  73855. # ifdef ZLIB_INTERNAL
  73856. # define ZEXPORT __declspec(dllexport)
  73857. # define ZEXPORTVA __declspec(dllexport)
  73858. # else
  73859. # define ZEXPORT __declspec(dllimport)
  73860. # define ZEXPORTVA __declspec(dllimport)
  73861. # endif
  73862. # endif
  73863. #endif
  73864. #ifndef ZEXTERN
  73865. # define ZEXTERN extern
  73866. #endif
  73867. #ifndef ZEXPORT
  73868. # define ZEXPORT
  73869. #endif
  73870. #ifndef ZEXPORTVA
  73871. # define ZEXPORTVA
  73872. #endif
  73873. #ifndef FAR
  73874. # define FAR
  73875. #endif
  73876. #if !defined(__MACTYPES__)
  73877. typedef unsigned char Byte; /* 8 bits */
  73878. #endif
  73879. typedef unsigned int uInt; /* 16 bits or more */
  73880. typedef unsigned long uLong; /* 32 bits or more */
  73881. #ifdef SMALL_MEDIUM
  73882. /* Borland C/C++ and some old MSC versions ignore FAR inside typedef */
  73883. # define Bytef Byte FAR
  73884. #else
  73885. typedef Byte FAR Bytef;
  73886. #endif
  73887. typedef char FAR charf;
  73888. typedef int FAR intf;
  73889. typedef uInt FAR uIntf;
  73890. typedef uLong FAR uLongf;
  73891. #ifdef STDC
  73892. typedef void const *voidpc;
  73893. typedef void FAR *voidpf;
  73894. typedef void *voidp;
  73895. #else
  73896. typedef Byte const *voidpc;
  73897. typedef Byte FAR *voidpf;
  73898. typedef Byte *voidp;
  73899. #endif
  73900. #if 0 /* HAVE_UNISTD_H -- this line is updated by ./configure */
  73901. # include <sys/types.h> /* for off_t */
  73902. # include <unistd.h> /* for SEEK_* and off_t */
  73903. # ifdef VMS
  73904. # include <unixio.h> /* for off_t */
  73905. # endif
  73906. # define z_off_t off_t
  73907. #endif
  73908. #ifndef SEEK_SET
  73909. # define SEEK_SET 0 /* Seek from beginning of file. */
  73910. # define SEEK_CUR 1 /* Seek from current position. */
  73911. # define SEEK_END 2 /* Set file pointer to EOF plus "offset" */
  73912. #endif
  73913. #ifndef z_off_t
  73914. # define z_off_t long
  73915. #endif
  73916. #if defined(__OS400__)
  73917. # define NO_vsnprintf
  73918. #endif
  73919. #if defined(__MVS__)
  73920. # define NO_vsnprintf
  73921. # ifdef FAR
  73922. # undef FAR
  73923. # endif
  73924. #endif
  73925. /* MVS linker does not support external names larger than 8 bytes */
  73926. #if defined(__MVS__)
  73927. # pragma map(deflateInit_,"DEIN")
  73928. # pragma map(deflateInit2_,"DEIN2")
  73929. # pragma map(deflateEnd,"DEEND")
  73930. # pragma map(deflateBound,"DEBND")
  73931. # pragma map(inflateInit_,"ININ")
  73932. # pragma map(inflateInit2_,"ININ2")
  73933. # pragma map(inflateEnd,"INEND")
  73934. # pragma map(inflateSync,"INSY")
  73935. # pragma map(inflateSetDictionary,"INSEDI")
  73936. # pragma map(compressBound,"CMBND")
  73937. # pragma map(inflate_table,"INTABL")
  73938. # pragma map(inflate_fast,"INFA")
  73939. # pragma map(inflate_copyright,"INCOPY")
  73940. #endif
  73941. #endif /* ZCONF_H */
  73942. /********* End of inlined file: zconf.h *********/
  73943. #ifdef __cplusplus
  73944. extern "C" {
  73945. #endif
  73946. #define ZLIB_VERSION "1.2.3"
  73947. #define ZLIB_VERNUM 0x1230
  73948. /*
  73949. The 'zlib' compression library provides in-memory compression and
  73950. decompression functions, including integrity checks of the uncompressed
  73951. data. This version of the library supports only one compression method
  73952. (deflation) but other algorithms will be added later and will have the same
  73953. stream interface.
  73954. Compression can be done in a single step if the buffers are large
  73955. enough (for example if an input file is mmap'ed), or can be done by
  73956. repeated calls of the compression function. In the latter case, the
  73957. application must provide more input and/or consume the output
  73958. (providing more output space) before each call.
  73959. The compressed data format used by default by the in-memory functions is
  73960. the zlib format, which is a zlib wrapper documented in RFC 1950, wrapped
  73961. around a deflate stream, which is itself documented in RFC 1951.
  73962. The library also supports reading and writing files in gzip (.gz) format
  73963. with an interface similar to that of stdio using the functions that start
  73964. with "gz". The gzip format is different from the zlib format. gzip is a
  73965. gzip wrapper, documented in RFC 1952, wrapped around a deflate stream.
  73966. This library can optionally read and write gzip streams in memory as well.
  73967. The zlib format was designed to be compact and fast for use in memory
  73968. and on communications channels. The gzip format was designed for single-
  73969. file compression on file systems, has a larger header than zlib to maintain
  73970. directory information, and uses a different, slower check method than zlib.
  73971. The library does not install any signal handler. The decoder checks
  73972. the consistency of the compressed data, so the library should never
  73973. crash even in case of corrupted input.
  73974. */
  73975. typedef voidpf (*alloc_func) OF((voidpf opaque, uInt items, uInt size));
  73976. typedef void (*free_func) OF((voidpf opaque, voidpf address));
  73977. struct internal_state;
  73978. typedef struct z_stream_s {
  73979. Bytef *next_in; /* next input byte */
  73980. uInt avail_in; /* number of bytes available at next_in */
  73981. uLong total_in; /* total nb of input bytes read so far */
  73982. Bytef *next_out; /* next output byte should be put there */
  73983. uInt avail_out; /* remaining free space at next_out */
  73984. uLong total_out; /* total nb of bytes output so far */
  73985. char *msg; /* last error message, NULL if no error */
  73986. struct internal_state FAR *state; /* not visible by applications */
  73987. alloc_func zalloc; /* used to allocate the internal state */
  73988. free_func zfree; /* used to free the internal state */
  73989. voidpf opaque; /* private data object passed to zalloc and zfree */
  73990. int data_type; /* best guess about the data type: binary or text */
  73991. uLong adler; /* adler32 value of the uncompressed data */
  73992. uLong reserved; /* reserved for future use */
  73993. } z_stream;
  73994. typedef z_stream FAR *z_streamp;
  73995. /*
  73996. gzip header information passed to and from zlib routines. See RFC 1952
  73997. for more details on the meanings of these fields.
  73998. */
  73999. typedef struct gz_header_s {
  74000. int text; /* true if compressed data believed to be text */
  74001. uLong time; /* modification time */
  74002. int xflags; /* extra flags (not used when writing a gzip file) */
  74003. int os; /* operating system */
  74004. Bytef *extra; /* pointer to extra field or Z_NULL if none */
  74005. uInt extra_len; /* extra field length (valid if extra != Z_NULL) */
  74006. uInt extra_max; /* space at extra (only when reading header) */
  74007. Bytef *name; /* pointer to zero-terminated file name or Z_NULL */
  74008. uInt name_max; /* space at name (only when reading header) */
  74009. Bytef *comment; /* pointer to zero-terminated comment or Z_NULL */
  74010. uInt comm_max; /* space at comment (only when reading header) */
  74011. int hcrc; /* true if there was or will be a header crc */
  74012. int done; /* true when done reading gzip header (not used
  74013. when writing a gzip file) */
  74014. } gz_header;
  74015. typedef gz_header FAR *gz_headerp;
  74016. /*
  74017. The application must update next_in and avail_in when avail_in has
  74018. dropped to zero. It must update next_out and avail_out when avail_out
  74019. has dropped to zero. The application must initialize zalloc, zfree and
  74020. opaque before calling the init function. All other fields are set by the
  74021. compression library and must not be updated by the application.
  74022. The opaque value provided by the application will be passed as the first
  74023. parameter for calls of zalloc and zfree. This can be useful for custom
  74024. memory management. The compression library attaches no meaning to the
  74025. opaque value.
  74026. zalloc must return Z_NULL if there is not enough memory for the object.
  74027. If zlib is used in a multi-threaded application, zalloc and zfree must be
  74028. thread safe.
  74029. On 16-bit systems, the functions zalloc and zfree must be able to allocate
  74030. exactly 65536 bytes, but will not be required to allocate more than this
  74031. if the symbol MAXSEG_64K is defined (see zconf.h). WARNING: On MSDOS,
  74032. pointers returned by zalloc for objects of exactly 65536 bytes *must*
  74033. have their offset normalized to zero. The default allocation function
  74034. provided by this library ensures this (see zutil.c). To reduce memory
  74035. requirements and avoid any allocation of 64K objects, at the expense of
  74036. compression ratio, compile the library with -DMAX_WBITS=14 (see zconf.h).
  74037. The fields total_in and total_out can be used for statistics or
  74038. progress reports. After compression, total_in holds the total size of
  74039. the uncompressed data and may be saved for use in the decompressor
  74040. (particularly if the decompressor wants to decompress everything in
  74041. a single step).
  74042. */
  74043. /* constants */
  74044. #define Z_NO_FLUSH 0
  74045. #define Z_PARTIAL_FLUSH 1 /* will be removed, use Z_SYNC_FLUSH instead */
  74046. #define Z_SYNC_FLUSH 2
  74047. #define Z_FULL_FLUSH 3
  74048. #define Z_FINISH 4
  74049. #define Z_BLOCK 5
  74050. /* Allowed flush values; see deflate() and inflate() below for details */
  74051. #define Z_OK 0
  74052. #define Z_STREAM_END 1
  74053. #define Z_NEED_DICT 2
  74054. #define Z_ERRNO (-1)
  74055. #define Z_STREAM_ERROR (-2)
  74056. #define Z_DATA_ERROR (-3)
  74057. #define Z_MEM_ERROR (-4)
  74058. #define Z_BUF_ERROR (-5)
  74059. #define Z_VERSION_ERROR (-6)
  74060. /* Return codes for the compression/decompression functions. Negative
  74061. * values are errors, positive values are used for special but normal events.
  74062. */
  74063. #define Z_NO_COMPRESSION 0
  74064. #define Z_BEST_SPEED 1
  74065. #define Z_BEST_COMPRESSION 9
  74066. #define Z_DEFAULT_COMPRESSION (-1)
  74067. /* compression levels */
  74068. #define Z_FILTERED 1
  74069. #define Z_HUFFMAN_ONLY 2
  74070. #define Z_RLE 3
  74071. #define Z_FIXED 4
  74072. #define Z_DEFAULT_STRATEGY 0
  74073. /* compression strategy; see deflateInit2() below for details */
  74074. #define Z_BINARY 0
  74075. #define Z_TEXT 1
  74076. #define Z_ASCII Z_TEXT /* for compatibility with 1.2.2 and earlier */
  74077. #define Z_UNKNOWN 2
  74078. /* Possible values of the data_type field (though see inflate()) */
  74079. #define Z_DEFLATED 8
  74080. /* The deflate compression method (the only one supported in this version) */
  74081. #define Z_NULL 0 /* for initializing zalloc, zfree, opaque */
  74082. #define zlib_version zlibVersion()
  74083. /* for compatibility with versions < 1.0.2 */
  74084. /* basic functions */
  74085. //ZEXTERN const char * ZEXPORT zlibVersion OF((void));
  74086. /* The application can compare zlibVersion and ZLIB_VERSION for consistency.
  74087. If the first character differs, the library code actually used is
  74088. not compatible with the zlib.h header file used by the application.
  74089. This check is automatically made by deflateInit and inflateInit.
  74090. */
  74091. /*
  74092. ZEXTERN int ZEXPORT deflateInit OF((z_streamp strm, int level));
  74093. Initializes the internal stream state for compression. The fields
  74094. zalloc, zfree and opaque must be initialized before by the caller.
  74095. If zalloc and zfree are set to Z_NULL, deflateInit updates them to
  74096. use default allocation functions.
  74097. The compression level must be Z_DEFAULT_COMPRESSION, or between 0 and 9:
  74098. 1 gives best speed, 9 gives best compression, 0 gives no compression at
  74099. all (the input data is simply copied a block at a time).
  74100. Z_DEFAULT_COMPRESSION requests a default compromise between speed and
  74101. compression (currently equivalent to level 6).
  74102. deflateInit returns Z_OK if success, Z_MEM_ERROR if there was not
  74103. enough memory, Z_STREAM_ERROR if level is not a valid compression level,
  74104. Z_VERSION_ERROR if the zlib library version (zlib_version) is incompatible
  74105. with the version assumed by the caller (ZLIB_VERSION).
  74106. msg is set to null if there is no error message. deflateInit does not
  74107. perform any compression: this will be done by deflate().
  74108. */
  74109. ZEXTERN int ZEXPORT deflate OF((z_streamp strm, int flush));
  74110. /*
  74111. deflate compresses as much data as possible, and stops when the input
  74112. buffer becomes empty or the output buffer becomes full. It may introduce some
  74113. output latency (reading input without producing any output) except when
  74114. forced to flush.
  74115. The detailed semantics are as follows. deflate performs one or both of the
  74116. following actions:
  74117. - Compress more input starting at next_in and update next_in and avail_in
  74118. accordingly. If not all input can be processed (because there is not
  74119. enough room in the output buffer), next_in and avail_in are updated and
  74120. processing will resume at this point for the next call of deflate().
  74121. - Provide more output starting at next_out and update next_out and avail_out
  74122. accordingly. This action is forced if the parameter flush is non zero.
  74123. Forcing flush frequently degrades the compression ratio, so this parameter
  74124. should be set only when necessary (in interactive applications).
  74125. Some output may be provided even if flush is not set.
  74126. Before the call of deflate(), the application should ensure that at least
  74127. one of the actions is possible, by providing more input and/or consuming
  74128. more output, and updating avail_in or avail_out accordingly; avail_out
  74129. should never be zero before the call. The application can consume the
  74130. compressed output when it wants, for example when the output buffer is full
  74131. (avail_out == 0), or after each call of deflate(). If deflate returns Z_OK
  74132. and with zero avail_out, it must be called again after making room in the
  74133. output buffer because there might be more output pending.
  74134. Normally the parameter flush is set to Z_NO_FLUSH, which allows deflate to
  74135. decide how much data to accumualte before producing output, in order to
  74136. maximize compression.
  74137. If the parameter flush is set to Z_SYNC_FLUSH, all pending output is
  74138. flushed to the output buffer and the output is aligned on a byte boundary, so
  74139. that the decompressor can get all input data available so far. (In particular
  74140. avail_in is zero after the call if enough output space has been provided
  74141. before the call.) Flushing may degrade compression for some compression
  74142. algorithms and so it should be used only when necessary.
  74143. If flush is set to Z_FULL_FLUSH, all output is flushed as with
  74144. Z_SYNC_FLUSH, and the compression state is reset so that decompression can
  74145. restart from this point if previous compressed data has been damaged or if
  74146. random access is desired. Using Z_FULL_FLUSH too often can seriously degrade
  74147. compression.
  74148. If deflate returns with avail_out == 0, this function must be called again
  74149. with the same value of the flush parameter and more output space (updated
  74150. avail_out), until the flush is complete (deflate returns with non-zero
  74151. avail_out). In the case of a Z_FULL_FLUSH or Z_SYNC_FLUSH, make sure that
  74152. avail_out is greater than six to avoid repeated flush markers due to
  74153. avail_out == 0 on return.
  74154. If the parameter flush is set to Z_FINISH, pending input is processed,
  74155. pending output is flushed and deflate returns with Z_STREAM_END if there
  74156. was enough output space; if deflate returns with Z_OK, this function must be
  74157. called again with Z_FINISH and more output space (updated avail_out) but no
  74158. more input data, until it returns with Z_STREAM_END or an error. After
  74159. deflate has returned Z_STREAM_END, the only possible operations on the
  74160. stream are deflateReset or deflateEnd.
  74161. Z_FINISH can be used immediately after deflateInit if all the compression
  74162. is to be done in a single step. In this case, avail_out must be at least
  74163. the value returned by deflateBound (see below). If deflate does not return
  74164. Z_STREAM_END, then it must be called again as described above.
  74165. deflate() sets strm->adler to the adler32 checksum of all input read
  74166. so far (that is, total_in bytes).
  74167. deflate() may update strm->data_type if it can make a good guess about
  74168. the input data type (Z_BINARY or Z_TEXT). In doubt, the data is considered
  74169. binary. This field is only for information purposes and does not affect
  74170. the compression algorithm in any manner.
  74171. deflate() returns Z_OK if some progress has been made (more input
  74172. processed or more output produced), Z_STREAM_END if all input has been
  74173. consumed and all output has been produced (only when flush is set to
  74174. Z_FINISH), Z_STREAM_ERROR if the stream state was inconsistent (for example
  74175. if next_in or next_out was NULL), Z_BUF_ERROR if no progress is possible
  74176. (for example avail_in or avail_out was zero). Note that Z_BUF_ERROR is not
  74177. fatal, and deflate() can be called again with more input and more output
  74178. space to continue compressing.
  74179. */
  74180. ZEXTERN int ZEXPORT deflateEnd OF((z_streamp strm));
  74181. /*
  74182. All dynamically allocated data structures for this stream are freed.
  74183. This function discards any unprocessed input and does not flush any
  74184. pending output.
  74185. deflateEnd returns Z_OK if success, Z_STREAM_ERROR if the
  74186. stream state was inconsistent, Z_DATA_ERROR if the stream was freed
  74187. prematurely (some input or output was discarded). In the error case,
  74188. msg may be set but then points to a static string (which must not be
  74189. deallocated).
  74190. */
  74191. /*
  74192. ZEXTERN int ZEXPORT inflateInit OF((z_streamp strm));
  74193. Initializes the internal stream state for decompression. The fields
  74194. next_in, avail_in, zalloc, zfree and opaque must be initialized before by
  74195. the caller. If next_in is not Z_NULL and avail_in is large enough (the exact
  74196. value depends on the compression method), inflateInit determines the
  74197. compression method from the zlib header and allocates all data structures
  74198. accordingly; otherwise the allocation will be deferred to the first call of
  74199. inflate. If zalloc and zfree are set to Z_NULL, inflateInit updates them to
  74200. use default allocation functions.
  74201. inflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough
  74202. memory, Z_VERSION_ERROR if the zlib library version is incompatible with the
  74203. version assumed by the caller. msg is set to null if there is no error
  74204. message. inflateInit does not perform any decompression apart from reading
  74205. the zlib header if present: this will be done by inflate(). (So next_in and
  74206. avail_in may be modified, but next_out and avail_out are unchanged.)
  74207. */
  74208. ZEXTERN int ZEXPORT inflate OF((z_streamp strm, int flush));
  74209. /*
  74210. inflate decompresses as much data as possible, and stops when the input
  74211. buffer becomes empty or the output buffer becomes full. It may introduce
  74212. some output latency (reading input without producing any output) except when
  74213. forced to flush.
  74214. The detailed semantics are as follows. inflate performs one or both of the
  74215. following actions:
  74216. - Decompress more input starting at next_in and update next_in and avail_in
  74217. accordingly. If not all input can be processed (because there is not
  74218. enough room in the output buffer), next_in is updated and processing
  74219. will resume at this point for the next call of inflate().
  74220. - Provide more output starting at next_out and update next_out and avail_out
  74221. accordingly. inflate() provides as much output as possible, until there
  74222. is no more input data or no more space in the output buffer (see below
  74223. about the flush parameter).
  74224. Before the call of inflate(), the application should ensure that at least
  74225. one of the actions is possible, by providing more input and/or consuming
  74226. more output, and updating the next_* and avail_* values accordingly.
  74227. The application can consume the uncompressed output when it wants, for
  74228. example when the output buffer is full (avail_out == 0), or after each
  74229. call of inflate(). If inflate returns Z_OK and with zero avail_out, it
  74230. must be called again after making room in the output buffer because there
  74231. might be more output pending.
  74232. The flush parameter of inflate() can be Z_NO_FLUSH, Z_SYNC_FLUSH,
  74233. Z_FINISH, or Z_BLOCK. Z_SYNC_FLUSH requests that inflate() flush as much
  74234. output as possible to the output buffer. Z_BLOCK requests that inflate() stop
  74235. if and when it gets to the next deflate block boundary. When decoding the
  74236. zlib or gzip format, this will cause inflate() to return immediately after
  74237. the header and before the first block. When doing a raw inflate, inflate()
  74238. will go ahead and process the first block, and will return when it gets to
  74239. the end of that block, or when it runs out of data.
  74240. The Z_BLOCK option assists in appending to or combining deflate streams.
  74241. Also to assist in this, on return inflate() will set strm->data_type to the
  74242. number of unused bits in the last byte taken from strm->next_in, plus 64
  74243. if inflate() is currently decoding the last block in the deflate stream,
  74244. plus 128 if inflate() returned immediately after decoding an end-of-block
  74245. code or decoding the complete header up to just before the first byte of the
  74246. deflate stream. The end-of-block will not be indicated until all of the
  74247. uncompressed data from that block has been written to strm->next_out. The
  74248. number of unused bits may in general be greater than seven, except when
  74249. bit 7 of data_type is set, in which case the number of unused bits will be
  74250. less than eight.
  74251. inflate() should normally be called until it returns Z_STREAM_END or an
  74252. error. However if all decompression is to be performed in a single step
  74253. (a single call of inflate), the parameter flush should be set to
  74254. Z_FINISH. In this case all pending input is processed and all pending
  74255. output is flushed; avail_out must be large enough to hold all the
  74256. uncompressed data. (The size of the uncompressed data may have been saved
  74257. by the compressor for this purpose.) The next operation on this stream must
  74258. be inflateEnd to deallocate the decompression state. The use of Z_FINISH
  74259. is never required, but can be used to inform inflate that a faster approach
  74260. may be used for the single inflate() call.
  74261. In this implementation, inflate() always flushes as much output as
  74262. possible to the output buffer, and always uses the faster approach on the
  74263. first call. So the only effect of the flush parameter in this implementation
  74264. is on the return value of inflate(), as noted below, or when it returns early
  74265. because Z_BLOCK is used.
  74266. If a preset dictionary is needed after this call (see inflateSetDictionary
  74267. below), inflate sets strm->adler to the adler32 checksum of the dictionary
  74268. chosen by the compressor and returns Z_NEED_DICT; otherwise it sets
  74269. strm->adler to the adler32 checksum of all output produced so far (that is,
  74270. total_out bytes) and returns Z_OK, Z_STREAM_END or an error code as described
  74271. below. At the end of the stream, inflate() checks that its computed adler32
  74272. checksum is equal to that saved by the compressor and returns Z_STREAM_END
  74273. only if the checksum is correct.
  74274. inflate() will decompress and check either zlib-wrapped or gzip-wrapped
  74275. deflate data. The header type is detected automatically. Any information
  74276. contained in the gzip header is not retained, so applications that need that
  74277. information should instead use raw inflate, see inflateInit2() below, or
  74278. inflateBack() and perform their own processing of the gzip header and
  74279. trailer.
  74280. inflate() returns Z_OK if some progress has been made (more input processed
  74281. or more output produced), Z_STREAM_END if the end of the compressed data has
  74282. been reached and all uncompressed output has been produced, Z_NEED_DICT if a
  74283. preset dictionary is needed at this point, Z_DATA_ERROR if the input data was
  74284. corrupted (input stream not conforming to the zlib format or incorrect check
  74285. value), Z_STREAM_ERROR if the stream structure was inconsistent (for example
  74286. if next_in or next_out was NULL), Z_MEM_ERROR if there was not enough memory,
  74287. Z_BUF_ERROR if no progress is possible or if there was not enough room in the
  74288. output buffer when Z_FINISH is used. Note that Z_BUF_ERROR is not fatal, and
  74289. inflate() can be called again with more input and more output space to
  74290. continue decompressing. If Z_DATA_ERROR is returned, the application may then
  74291. call inflateSync() to look for a good compression block if a partial recovery
  74292. of the data is desired.
  74293. */
  74294. ZEXTERN int ZEXPORT inflateEnd OF((z_streamp strm));
  74295. /*
  74296. All dynamically allocated data structures for this stream are freed.
  74297. This function discards any unprocessed input and does not flush any
  74298. pending output.
  74299. inflateEnd returns Z_OK if success, Z_STREAM_ERROR if the stream state
  74300. was inconsistent. In the error case, msg may be set but then points to a
  74301. static string (which must not be deallocated).
  74302. */
  74303. /* Advanced functions */
  74304. /*
  74305. The following functions are needed only in some special applications.
  74306. */
  74307. /*
  74308. ZEXTERN int ZEXPORT deflateInit2 OF((z_streamp strm,
  74309. int level,
  74310. int method,
  74311. int windowBits,
  74312. int memLevel,
  74313. int strategy));
  74314. This is another version of deflateInit with more compression options. The
  74315. fields next_in, zalloc, zfree and opaque must be initialized before by
  74316. the caller.
  74317. The method parameter is the compression method. It must be Z_DEFLATED in
  74318. this version of the library.
  74319. The windowBits parameter is the base two logarithm of the window size
  74320. (the size of the history buffer). It should be in the range 8..15 for this
  74321. version of the library. Larger values of this parameter result in better
  74322. compression at the expense of memory usage. The default value is 15 if
  74323. deflateInit is used instead.
  74324. windowBits can also be -8..-15 for raw deflate. In this case, -windowBits
  74325. determines the window size. deflate() will then generate raw deflate data
  74326. with no zlib header or trailer, and will not compute an adler32 check value.
  74327. windowBits can also be greater than 15 for optional gzip encoding. Add
  74328. 16 to windowBits to write a simple gzip header and trailer around the
  74329. compressed data instead of a zlib wrapper. The gzip header will have no
  74330. file name, no extra data, no comment, no modification time (set to zero),
  74331. no header crc, and the operating system will be set to 255 (unknown). If a
  74332. gzip stream is being written, strm->adler is a crc32 instead of an adler32.
  74333. The memLevel parameter specifies how much memory should be allocated
  74334. for the internal compression state. memLevel=1 uses minimum memory but
  74335. is slow and reduces compression ratio; memLevel=9 uses maximum memory
  74336. for optimal speed. The default value is 8. See zconf.h for total memory
  74337. usage as a function of windowBits and memLevel.
  74338. The strategy parameter is used to tune the compression algorithm. Use the
  74339. value Z_DEFAULT_STRATEGY for normal data, Z_FILTERED for data produced by a
  74340. filter (or predictor), Z_HUFFMAN_ONLY to force Huffman encoding only (no
  74341. string match), or Z_RLE to limit match distances to one (run-length
  74342. encoding). Filtered data consists mostly of small values with a somewhat
  74343. random distribution. In this case, the compression algorithm is tuned to
  74344. compress them better. The effect of Z_FILTERED is to force more Huffman
  74345. coding and less string matching; it is somewhat intermediate between
  74346. Z_DEFAULT and Z_HUFFMAN_ONLY. Z_RLE is designed to be almost as fast as
  74347. Z_HUFFMAN_ONLY, but give better compression for PNG image data. The strategy
  74348. parameter only affects the compression ratio but not the correctness of the
  74349. compressed output even if it is not set appropriately. Z_FIXED prevents the
  74350. use of dynamic Huffman codes, allowing for a simpler decoder for special
  74351. applications.
  74352. deflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  74353. memory, Z_STREAM_ERROR if a parameter is invalid (such as an invalid
  74354. method). msg is set to null if there is no error message. deflateInit2 does
  74355. not perform any compression: this will be done by deflate().
  74356. */
  74357. ZEXTERN int ZEXPORT deflateSetDictionary OF((z_streamp strm,
  74358. const Bytef *dictionary,
  74359. uInt dictLength));
  74360. /*
  74361. Initializes the compression dictionary from the given byte sequence
  74362. without producing any compressed output. This function must be called
  74363. immediately after deflateInit, deflateInit2 or deflateReset, before any
  74364. call of deflate. The compressor and decompressor must use exactly the same
  74365. dictionary (see inflateSetDictionary).
  74366. The dictionary should consist of strings (byte sequences) that are likely
  74367. to be encountered later in the data to be compressed, with the most commonly
  74368. used strings preferably put towards the end of the dictionary. Using a
  74369. dictionary is most useful when the data to be compressed is short and can be
  74370. predicted with good accuracy; the data can then be compressed better than
  74371. with the default empty dictionary.
  74372. Depending on the size of the compression data structures selected by
  74373. deflateInit or deflateInit2, a part of the dictionary may in effect be
  74374. discarded, for example if the dictionary is larger than the window size in
  74375. deflate or deflate2. Thus the strings most likely to be useful should be
  74376. put at the end of the dictionary, not at the front. In addition, the
  74377. current implementation of deflate will use at most the window size minus
  74378. 262 bytes of the provided dictionary.
  74379. Upon return of this function, strm->adler is set to the adler32 value
  74380. of the dictionary; the decompressor may later use this value to determine
  74381. which dictionary has been used by the compressor. (The adler32 value
  74382. applies to the whole dictionary even if only a subset of the dictionary is
  74383. actually used by the compressor.) If a raw deflate was requested, then the
  74384. adler32 value is not computed and strm->adler is not set.
  74385. deflateSetDictionary returns Z_OK if success, or Z_STREAM_ERROR if a
  74386. parameter is invalid (such as NULL dictionary) or the stream state is
  74387. inconsistent (for example if deflate has already been called for this stream
  74388. or if the compression method is bsort). deflateSetDictionary does not
  74389. perform any compression: this will be done by deflate().
  74390. */
  74391. ZEXTERN int ZEXPORT deflateCopy OF((z_streamp dest,
  74392. z_streamp source));
  74393. /*
  74394. Sets the destination stream as a complete copy of the source stream.
  74395. This function can be useful when several compression strategies will be
  74396. tried, for example when there are several ways of pre-processing the input
  74397. data with a filter. The streams that will be discarded should then be freed
  74398. by calling deflateEnd. Note that deflateCopy duplicates the internal
  74399. compression state which can be quite large, so this strategy is slow and
  74400. can consume lots of memory.
  74401. deflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
  74402. enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
  74403. (such as zalloc being NULL). msg is left unchanged in both source and
  74404. destination.
  74405. */
  74406. ZEXTERN int ZEXPORT deflateReset OF((z_streamp strm));
  74407. /*
  74408. This function is equivalent to deflateEnd followed by deflateInit,
  74409. but does not free and reallocate all the internal compression state.
  74410. The stream will keep the same compression level and any other attributes
  74411. that may have been set by deflateInit2.
  74412. deflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
  74413. stream state was inconsistent (such as zalloc or state being NULL).
  74414. */
  74415. ZEXTERN int ZEXPORT deflateParams OF((z_streamp strm,
  74416. int level,
  74417. int strategy));
  74418. /*
  74419. Dynamically update the compression level and compression strategy. The
  74420. interpretation of level and strategy is as in deflateInit2. This can be
  74421. used to switch between compression and straight copy of the input data, or
  74422. to switch to a different kind of input data requiring a different
  74423. strategy. If the compression level is changed, the input available so far
  74424. is compressed with the old level (and may be flushed); the new level will
  74425. take effect only at the next call of deflate().
  74426. Before the call of deflateParams, the stream state must be set as for
  74427. a call of deflate(), since the currently available input may have to
  74428. be compressed and flushed. In particular, strm->avail_out must be non-zero.
  74429. deflateParams returns Z_OK if success, Z_STREAM_ERROR if the source
  74430. stream state was inconsistent or if a parameter was invalid, Z_BUF_ERROR
  74431. if strm->avail_out was zero.
  74432. */
  74433. ZEXTERN int ZEXPORT deflateTune OF((z_streamp strm,
  74434. int good_length,
  74435. int max_lazy,
  74436. int nice_length,
  74437. int max_chain));
  74438. /*
  74439. Fine tune deflate's internal compression parameters. This should only be
  74440. used by someone who understands the algorithm used by zlib's deflate for
  74441. searching for the best matching string, and even then only by the most
  74442. fanatic optimizer trying to squeeze out the last compressed bit for their
  74443. specific input data. Read the deflate.c source code for the meaning of the
  74444. max_lazy, good_length, nice_length, and max_chain parameters.
  74445. deflateTune() can be called after deflateInit() or deflateInit2(), and
  74446. returns Z_OK on success, or Z_STREAM_ERROR for an invalid deflate stream.
  74447. */
  74448. ZEXTERN uLong ZEXPORT deflateBound OF((z_streamp strm,
  74449. uLong sourceLen));
  74450. /*
  74451. deflateBound() returns an upper bound on the compressed size after
  74452. deflation of sourceLen bytes. It must be called after deflateInit()
  74453. or deflateInit2(). This would be used to allocate an output buffer
  74454. for deflation in a single pass, and so would be called before deflate().
  74455. */
  74456. ZEXTERN int ZEXPORT deflatePrime OF((z_streamp strm,
  74457. int bits,
  74458. int value));
  74459. /*
  74460. deflatePrime() inserts bits in the deflate output stream. The intent
  74461. is that this function is used to start off the deflate output with the
  74462. bits leftover from a previous deflate stream when appending to it. As such,
  74463. this function can only be used for raw deflate, and must be used before the
  74464. first deflate() call after a deflateInit2() or deflateReset(). bits must be
  74465. less than or equal to 16, and that many of the least significant bits of
  74466. value will be inserted in the output.
  74467. deflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source
  74468. stream state was inconsistent.
  74469. */
  74470. ZEXTERN int ZEXPORT deflateSetHeader OF((z_streamp strm,
  74471. gz_headerp head));
  74472. /*
  74473. deflateSetHeader() provides gzip header information for when a gzip
  74474. stream is requested by deflateInit2(). deflateSetHeader() may be called
  74475. after deflateInit2() or deflateReset() and before the first call of
  74476. deflate(). The text, time, os, extra field, name, and comment information
  74477. in the provided gz_header structure are written to the gzip header (xflag is
  74478. ignored -- the extra flags are set according to the compression level). The
  74479. caller must assure that, if not Z_NULL, name and comment are terminated with
  74480. a zero byte, and that if extra is not Z_NULL, that extra_len bytes are
  74481. available there. If hcrc is true, a gzip header crc is included. Note that
  74482. the current versions of the command-line version of gzip (up through version
  74483. 1.3.x) do not support header crc's, and will report that it is a "multi-part
  74484. gzip file" and give up.
  74485. If deflateSetHeader is not used, the default gzip header has text false,
  74486. the time set to zero, and os set to 255, with no extra, name, or comment
  74487. fields. The gzip header is returned to the default state by deflateReset().
  74488. deflateSetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source
  74489. stream state was inconsistent.
  74490. */
  74491. /*
  74492. ZEXTERN int ZEXPORT inflateInit2 OF((z_streamp strm,
  74493. int windowBits));
  74494. This is another version of inflateInit with an extra parameter. The
  74495. fields next_in, avail_in, zalloc, zfree and opaque must be initialized
  74496. before by the caller.
  74497. The windowBits parameter is the base two logarithm of the maximum window
  74498. size (the size of the history buffer). It should be in the range 8..15 for
  74499. this version of the library. The default value is 15 if inflateInit is used
  74500. instead. windowBits must be greater than or equal to the windowBits value
  74501. provided to deflateInit2() while compressing, or it must be equal to 15 if
  74502. deflateInit2() was not used. If a compressed stream with a larger window
  74503. size is given as input, inflate() will return with the error code
  74504. Z_DATA_ERROR instead of trying to allocate a larger window.
  74505. windowBits can also be -8..-15 for raw inflate. In this case, -windowBits
  74506. determines the window size. inflate() will then process raw deflate data,
  74507. not looking for a zlib or gzip header, not generating a check value, and not
  74508. looking for any check values for comparison at the end of the stream. This
  74509. is for use with other formats that use the deflate compressed data format
  74510. such as zip. Those formats provide their own check values. If a custom
  74511. format is developed using the raw deflate format for compressed data, it is
  74512. recommended that a check value such as an adler32 or a crc32 be applied to
  74513. the uncompressed data as is done in the zlib, gzip, and zip formats. For
  74514. most applications, the zlib format should be used as is. Note that comments
  74515. above on the use in deflateInit2() applies to the magnitude of windowBits.
  74516. windowBits can also be greater than 15 for optional gzip decoding. Add
  74517. 32 to windowBits to enable zlib and gzip decoding with automatic header
  74518. detection, or add 16 to decode only the gzip format (the zlib format will
  74519. return a Z_DATA_ERROR). If a gzip stream is being decoded, strm->adler is
  74520. a crc32 instead of an adler32.
  74521. inflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  74522. memory, Z_STREAM_ERROR if a parameter is invalid (such as a null strm). msg
  74523. is set to null if there is no error message. inflateInit2 does not perform
  74524. any decompression apart from reading the zlib header if present: this will
  74525. be done by inflate(). (So next_in and avail_in may be modified, but next_out
  74526. and avail_out are unchanged.)
  74527. */
  74528. ZEXTERN int ZEXPORT inflateSetDictionary OF((z_streamp strm,
  74529. const Bytef *dictionary,
  74530. uInt dictLength));
  74531. /*
  74532. Initializes the decompression dictionary from the given uncompressed byte
  74533. sequence. This function must be called immediately after a call of inflate,
  74534. if that call returned Z_NEED_DICT. The dictionary chosen by the compressor
  74535. can be determined from the adler32 value returned by that call of inflate.
  74536. The compressor and decompressor must use exactly the same dictionary (see
  74537. deflateSetDictionary). For raw inflate, this function can be called
  74538. immediately after inflateInit2() or inflateReset() and before any call of
  74539. inflate() to set the dictionary. The application must insure that the
  74540. dictionary that was used for compression is provided.
  74541. inflateSetDictionary returns Z_OK if success, Z_STREAM_ERROR if a
  74542. parameter is invalid (such as NULL dictionary) or the stream state is
  74543. inconsistent, Z_DATA_ERROR if the given dictionary doesn't match the
  74544. expected one (incorrect adler32 value). inflateSetDictionary does not
  74545. perform any decompression: this will be done by subsequent calls of
  74546. inflate().
  74547. */
  74548. ZEXTERN int ZEXPORT inflateSync OF((z_streamp strm));
  74549. /*
  74550. Skips invalid compressed data until a full flush point (see above the
  74551. description of deflate with Z_FULL_FLUSH) can be found, or until all
  74552. available input is skipped. No output is provided.
  74553. inflateSync returns Z_OK if a full flush point has been found, Z_BUF_ERROR
  74554. if no more input was provided, Z_DATA_ERROR if no flush point has been found,
  74555. or Z_STREAM_ERROR if the stream structure was inconsistent. In the success
  74556. case, the application may save the current current value of total_in which
  74557. indicates where valid compressed data was found. In the error case, the
  74558. application may repeatedly call inflateSync, providing more input each time,
  74559. until success or end of the input data.
  74560. */
  74561. ZEXTERN int ZEXPORT inflateCopy OF((z_streamp dest,
  74562. z_streamp source));
  74563. /*
  74564. Sets the destination stream as a complete copy of the source stream.
  74565. This function can be useful when randomly accessing a large stream. The
  74566. first pass through the stream can periodically record the inflate state,
  74567. allowing restarting inflate at those points when randomly accessing the
  74568. stream.
  74569. inflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
  74570. enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
  74571. (such as zalloc being NULL). msg is left unchanged in both source and
  74572. destination.
  74573. */
  74574. ZEXTERN int ZEXPORT inflateReset OF((z_streamp strm));
  74575. /*
  74576. This function is equivalent to inflateEnd followed by inflateInit,
  74577. but does not free and reallocate all the internal decompression state.
  74578. The stream will keep attributes that may have been set by inflateInit2.
  74579. inflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
  74580. stream state was inconsistent (such as zalloc or state being NULL).
  74581. */
  74582. ZEXTERN int ZEXPORT inflatePrime OF((z_streamp strm,
  74583. int bits,
  74584. int value));
  74585. /*
  74586. This function inserts bits in the inflate input stream. The intent is
  74587. that this function is used to start inflating at a bit position in the
  74588. middle of a byte. The provided bits will be used before any bytes are used
  74589. from next_in. This function should only be used with raw inflate, and
  74590. should be used before the first inflate() call after inflateInit2() or
  74591. inflateReset(). bits must be less than or equal to 16, and that many of the
  74592. least significant bits of value will be inserted in the input.
  74593. inflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source
  74594. stream state was inconsistent.
  74595. */
  74596. ZEXTERN int ZEXPORT inflateGetHeader OF((z_streamp strm,
  74597. gz_headerp head));
  74598. /*
  74599. inflateGetHeader() requests that gzip header information be stored in the
  74600. provided gz_header structure. inflateGetHeader() may be called after
  74601. inflateInit2() or inflateReset(), and before the first call of inflate().
  74602. As inflate() processes the gzip stream, head->done is zero until the header
  74603. is completed, at which time head->done is set to one. If a zlib stream is
  74604. being decoded, then head->done is set to -1 to indicate that there will be
  74605. no gzip header information forthcoming. Note that Z_BLOCK can be used to
  74606. force inflate() to return immediately after header processing is complete
  74607. and before any actual data is decompressed.
  74608. The text, time, xflags, and os fields are filled in with the gzip header
  74609. contents. hcrc is set to true if there is a header CRC. (The header CRC
  74610. was valid if done is set to one.) If extra is not Z_NULL, then extra_max
  74611. contains the maximum number of bytes to write to extra. Once done is true,
  74612. extra_len contains the actual extra field length, and extra contains the
  74613. extra field, or that field truncated if extra_max is less than extra_len.
  74614. If name is not Z_NULL, then up to name_max characters are written there,
  74615. terminated with a zero unless the length is greater than name_max. If
  74616. comment is not Z_NULL, then up to comm_max characters are written there,
  74617. terminated with a zero unless the length is greater than comm_max. When
  74618. any of extra, name, or comment are not Z_NULL and the respective field is
  74619. not present in the header, then that field is set to Z_NULL to signal its
  74620. absence. This allows the use of deflateSetHeader() with the returned
  74621. structure to duplicate the header. However if those fields are set to
  74622. allocated memory, then the application will need to save those pointers
  74623. elsewhere so that they can be eventually freed.
  74624. If inflateGetHeader is not used, then the header information is simply
  74625. discarded. The header is always checked for validity, including the header
  74626. CRC if present. inflateReset() will reset the process to discard the header
  74627. information. The application would need to call inflateGetHeader() again to
  74628. retrieve the header from the next gzip stream.
  74629. inflateGetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source
  74630. stream state was inconsistent.
  74631. */
  74632. /*
  74633. ZEXTERN int ZEXPORT inflateBackInit OF((z_streamp strm, int windowBits,
  74634. unsigned char FAR *window));
  74635. Initialize the internal stream state for decompression using inflateBack()
  74636. calls. The fields zalloc, zfree and opaque in strm must be initialized
  74637. before the call. If zalloc and zfree are Z_NULL, then the default library-
  74638. derived memory allocation routines are used. windowBits is the base two
  74639. logarithm of the window size, in the range 8..15. window is a caller
  74640. supplied buffer of that size. Except for special applications where it is
  74641. assured that deflate was used with small window sizes, windowBits must be 15
  74642. and a 32K byte window must be supplied to be able to decompress general
  74643. deflate streams.
  74644. See inflateBack() for the usage of these routines.
  74645. inflateBackInit will return Z_OK on success, Z_STREAM_ERROR if any of
  74646. the paramaters are invalid, Z_MEM_ERROR if the internal state could not
  74647. be allocated, or Z_VERSION_ERROR if the version of the library does not
  74648. match the version of the header file.
  74649. */
  74650. typedef unsigned (*in_func) OF((void FAR *, unsigned char FAR * FAR *));
  74651. typedef int (*out_func) OF((void FAR *, unsigned char FAR *, unsigned));
  74652. ZEXTERN int ZEXPORT inflateBack OF((z_streamp strm,
  74653. in_func in, void FAR *in_desc,
  74654. out_func out, void FAR *out_desc));
  74655. /*
  74656. inflateBack() does a raw inflate with a single call using a call-back
  74657. interface for input and output. This is more efficient than inflate() for
  74658. file i/o applications in that it avoids copying between the output and the
  74659. sliding window by simply making the window itself the output buffer. This
  74660. function trusts the application to not change the output buffer passed by
  74661. the output function, at least until inflateBack() returns.
  74662. inflateBackInit() must be called first to allocate the internal state
  74663. and to initialize the state with the user-provided window buffer.
  74664. inflateBack() may then be used multiple times to inflate a complete, raw
  74665. deflate stream with each call. inflateBackEnd() is then called to free
  74666. the allocated state.
  74667. A raw deflate stream is one with no zlib or gzip header or trailer.
  74668. This routine would normally be used in a utility that reads zip or gzip
  74669. files and writes out uncompressed files. The utility would decode the
  74670. header and process the trailer on its own, hence this routine expects
  74671. only the raw deflate stream to decompress. This is different from the
  74672. normal behavior of inflate(), which expects either a zlib or gzip header and
  74673. trailer around the deflate stream.
  74674. inflateBack() uses two subroutines supplied by the caller that are then
  74675. called by inflateBack() for input and output. inflateBack() calls those
  74676. routines until it reads a complete deflate stream and writes out all of the
  74677. uncompressed data, or until it encounters an error. The function's
  74678. parameters and return types are defined above in the in_func and out_func
  74679. typedefs. inflateBack() will call in(in_desc, &buf) which should return the
  74680. number of bytes of provided input, and a pointer to that input in buf. If
  74681. there is no input available, in() must return zero--buf is ignored in that
  74682. case--and inflateBack() will return a buffer error. inflateBack() will call
  74683. out(out_desc, buf, len) to write the uncompressed data buf[0..len-1]. out()
  74684. should return zero on success, or non-zero on failure. If out() returns
  74685. non-zero, inflateBack() will return with an error. Neither in() nor out()
  74686. are permitted to change the contents of the window provided to
  74687. inflateBackInit(), which is also the buffer that out() uses to write from.
  74688. The length written by out() will be at most the window size. Any non-zero
  74689. amount of input may be provided by in().
  74690. For convenience, inflateBack() can be provided input on the first call by
  74691. setting strm->next_in and strm->avail_in. If that input is exhausted, then
  74692. in() will be called. Therefore strm->next_in must be initialized before
  74693. calling inflateBack(). If strm->next_in is Z_NULL, then in() will be called
  74694. immediately for input. If strm->next_in is not Z_NULL, then strm->avail_in
  74695. must also be initialized, and then if strm->avail_in is not zero, input will
  74696. initially be taken from strm->next_in[0 .. strm->avail_in - 1].
  74697. The in_desc and out_desc parameters of inflateBack() is passed as the
  74698. first parameter of in() and out() respectively when they are called. These
  74699. descriptors can be optionally used to pass any information that the caller-
  74700. supplied in() and out() functions need to do their job.
  74701. On return, inflateBack() will set strm->next_in and strm->avail_in to
  74702. pass back any unused input that was provided by the last in() call. The
  74703. return values of inflateBack() can be Z_STREAM_END on success, Z_BUF_ERROR
  74704. if in() or out() returned an error, Z_DATA_ERROR if there was a format
  74705. error in the deflate stream (in which case strm->msg is set to indicate the
  74706. nature of the error), or Z_STREAM_ERROR if the stream was not properly
  74707. initialized. In the case of Z_BUF_ERROR, an input or output error can be
  74708. distinguished using strm->next_in which will be Z_NULL only if in() returned
  74709. an error. If strm->next is not Z_NULL, then the Z_BUF_ERROR was due to
  74710. out() returning non-zero. (in() will always be called before out(), so
  74711. strm->next_in is assured to be defined if out() returns non-zero.) Note
  74712. that inflateBack() cannot return Z_OK.
  74713. */
  74714. ZEXTERN int ZEXPORT inflateBackEnd OF((z_streamp strm));
  74715. /*
  74716. All memory allocated by inflateBackInit() is freed.
  74717. inflateBackEnd() returns Z_OK on success, or Z_STREAM_ERROR if the stream
  74718. state was inconsistent.
  74719. */
  74720. //ZEXTERN uLong ZEXPORT zlibCompileFlags OF((void));
  74721. /* Return flags indicating compile-time options.
  74722. Type sizes, two bits each, 00 = 16 bits, 01 = 32, 10 = 64, 11 = other:
  74723. 1.0: size of uInt
  74724. 3.2: size of uLong
  74725. 5.4: size of voidpf (pointer)
  74726. 7.6: size of z_off_t
  74727. Compiler, assembler, and debug options:
  74728. 8: DEBUG
  74729. 9: ASMV or ASMINF -- use ASM code
  74730. 10: ZLIB_WINAPI -- exported functions use the WINAPI calling convention
  74731. 11: 0 (reserved)
  74732. One-time table building (smaller code, but not thread-safe if true):
  74733. 12: BUILDFIXED -- build static block decoding tables when needed
  74734. 13: DYNAMIC_CRC_TABLE -- build CRC calculation tables when needed
  74735. 14,15: 0 (reserved)
  74736. Library content (indicates missing functionality):
  74737. 16: NO_GZCOMPRESS -- gz* functions cannot compress (to avoid linking
  74738. deflate code when not needed)
  74739. 17: NO_GZIP -- deflate can't write gzip streams, and inflate can't detect
  74740. and decode gzip streams (to avoid linking crc code)
  74741. 18-19: 0 (reserved)
  74742. Operation variations (changes in library functionality):
  74743. 20: PKZIP_BUG_WORKAROUND -- slightly more permissive inflate
  74744. 21: FASTEST -- deflate algorithm with only one, lowest compression level
  74745. 22,23: 0 (reserved)
  74746. The sprintf variant used by gzprintf (zero is best):
  74747. 24: 0 = vs*, 1 = s* -- 1 means limited to 20 arguments after the format
  74748. 25: 0 = *nprintf, 1 = *printf -- 1 means gzprintf() not secure!
  74749. 26: 0 = returns value, 1 = void -- 1 means inferred string length returned
  74750. Remainder:
  74751. 27-31: 0 (reserved)
  74752. */
  74753. /* utility functions */
  74754. /*
  74755. The following utility functions are implemented on top of the
  74756. basic stream-oriented functions. To simplify the interface, some
  74757. default options are assumed (compression level and memory usage,
  74758. standard memory allocation functions). The source code of these
  74759. utility functions can easily be modified if you need special options.
  74760. */
  74761. ZEXTERN int ZEXPORT compress OF((Bytef *dest, uLongf *destLen,
  74762. const Bytef *source, uLong sourceLen));
  74763. /*
  74764. Compresses the source buffer into the destination buffer. sourceLen is
  74765. the byte length of the source buffer. Upon entry, destLen is the total
  74766. size of the destination buffer, which must be at least the value returned
  74767. by compressBound(sourceLen). Upon exit, destLen is the actual size of the
  74768. compressed buffer.
  74769. This function can be used to compress a whole file at once if the
  74770. input file is mmap'ed.
  74771. compress returns Z_OK if success, Z_MEM_ERROR if there was not
  74772. enough memory, Z_BUF_ERROR if there was not enough room in the output
  74773. buffer.
  74774. */
  74775. ZEXTERN int ZEXPORT compress2 OF((Bytef *dest, uLongf *destLen,
  74776. const Bytef *source, uLong sourceLen,
  74777. int level));
  74778. /*
  74779. Compresses the source buffer into the destination buffer. The level
  74780. parameter has the same meaning as in deflateInit. sourceLen is the byte
  74781. length of the source buffer. Upon entry, destLen is the total size of the
  74782. destination buffer, which must be at least the value returned by
  74783. compressBound(sourceLen). Upon exit, destLen is the actual size of the
  74784. compressed buffer.
  74785. compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  74786. memory, Z_BUF_ERROR if there was not enough room in the output buffer,
  74787. Z_STREAM_ERROR if the level parameter is invalid.
  74788. */
  74789. ZEXTERN uLong ZEXPORT compressBound OF((uLong sourceLen));
  74790. /*
  74791. compressBound() returns an upper bound on the compressed size after
  74792. compress() or compress2() on sourceLen bytes. It would be used before
  74793. a compress() or compress2() call to allocate the destination buffer.
  74794. */
  74795. ZEXTERN int ZEXPORT uncompress OF((Bytef *dest, uLongf *destLen,
  74796. const Bytef *source, uLong sourceLen));
  74797. /*
  74798. Decompresses the source buffer into the destination buffer. sourceLen is
  74799. the byte length of the source buffer. Upon entry, destLen is the total
  74800. size of the destination buffer, which must be large enough to hold the
  74801. entire uncompressed data. (The size of the uncompressed data must have
  74802. been saved previously by the compressor and transmitted to the decompressor
  74803. by some mechanism outside the scope of this compression library.)
  74804. Upon exit, destLen is the actual size of the compressed buffer.
  74805. This function can be used to decompress a whole file at once if the
  74806. input file is mmap'ed.
  74807. uncompress returns Z_OK if success, Z_MEM_ERROR if there was not
  74808. enough memory, Z_BUF_ERROR if there was not enough room in the output
  74809. buffer, or Z_DATA_ERROR if the input data was corrupted or incomplete.
  74810. */
  74811. typedef voidp gzFile;
  74812. ZEXTERN gzFile ZEXPORT gzopen OF((const char *path, const char *mode));
  74813. /*
  74814. Opens a gzip (.gz) file for reading or writing. The mode parameter
  74815. is as in fopen ("rb" or "wb") but can also include a compression level
  74816. ("wb9") or a strategy: 'f' for filtered data as in "wb6f", 'h' for
  74817. Huffman only compression as in "wb1h", or 'R' for run-length encoding
  74818. as in "wb1R". (See the description of deflateInit2 for more information
  74819. about the strategy parameter.)
  74820. gzopen can be used to read a file which is not in gzip format; in this
  74821. case gzread will directly read from the file without decompression.
  74822. gzopen returns NULL if the file could not be opened or if there was
  74823. insufficient memory to allocate the (de)compression state; errno
  74824. can be checked to distinguish the two cases (if errno is zero, the
  74825. zlib error is Z_MEM_ERROR). */
  74826. ZEXTERN gzFile ZEXPORT gzdopen OF((int fd, const char *mode));
  74827. /*
  74828. gzdopen() associates a gzFile with the file descriptor fd. File
  74829. descriptors are obtained from calls like open, dup, creat, pipe or
  74830. fileno (in the file has been previously opened with fopen).
  74831. The mode parameter is as in gzopen.
  74832. The next call of gzclose on the returned gzFile will also close the
  74833. file descriptor fd, just like fclose(fdopen(fd), mode) closes the file
  74834. descriptor fd. If you want to keep fd open, use gzdopen(dup(fd), mode).
  74835. gzdopen returns NULL if there was insufficient memory to allocate
  74836. the (de)compression state.
  74837. */
  74838. ZEXTERN int ZEXPORT gzsetparams OF((gzFile file, int level, int strategy));
  74839. /*
  74840. Dynamically update the compression level or strategy. See the description
  74841. of deflateInit2 for the meaning of these parameters.
  74842. gzsetparams returns Z_OK if success, or Z_STREAM_ERROR if the file was not
  74843. opened for writing.
  74844. */
  74845. ZEXTERN int ZEXPORT gzread OF((gzFile file, voidp buf, unsigned len));
  74846. /*
  74847. Reads the given number of uncompressed bytes from the compressed file.
  74848. If the input file was not in gzip format, gzread copies the given number
  74849. of bytes into the buffer.
  74850. gzread returns the number of uncompressed bytes actually read (0 for
  74851. end of file, -1 for error). */
  74852. ZEXTERN int ZEXPORT gzwrite OF((gzFile file,
  74853. voidpc buf, unsigned len));
  74854. /*
  74855. Writes the given number of uncompressed bytes into the compressed file.
  74856. gzwrite returns the number of uncompressed bytes actually written
  74857. (0 in case of error).
  74858. */
  74859. ZEXTERN int ZEXPORTVA gzprintf OF((gzFile file, const char *format, ...));
  74860. /*
  74861. Converts, formats, and writes the args to the compressed file under
  74862. control of the format string, as in fprintf. gzprintf returns the number of
  74863. uncompressed bytes actually written (0 in case of error). The number of
  74864. uncompressed bytes written is limited to 4095. The caller should assure that
  74865. this limit is not exceeded. If it is exceeded, then gzprintf() will return
  74866. return an error (0) with nothing written. In this case, there may also be a
  74867. buffer overflow with unpredictable consequences, which is possible only if
  74868. zlib was compiled with the insecure functions sprintf() or vsprintf()
  74869. because the secure snprintf() or vsnprintf() functions were not available.
  74870. */
  74871. ZEXTERN int ZEXPORT gzputs OF((gzFile file, const char *s));
  74872. /*
  74873. Writes the given null-terminated string to the compressed file, excluding
  74874. the terminating null character.
  74875. gzputs returns the number of characters written, or -1 in case of error.
  74876. */
  74877. ZEXTERN char * ZEXPORT gzgets OF((gzFile file, char *buf, int len));
  74878. /*
  74879. Reads bytes from the compressed file until len-1 characters are read, or
  74880. a newline character is read and transferred to buf, or an end-of-file
  74881. condition is encountered. The string is then terminated with a null
  74882. character.
  74883. gzgets returns buf, or Z_NULL in case of error.
  74884. */
  74885. ZEXTERN int ZEXPORT gzputc OF((gzFile file, int c));
  74886. /*
  74887. Writes c, converted to an unsigned char, into the compressed file.
  74888. gzputc returns the value that was written, or -1 in case of error.
  74889. */
  74890. ZEXTERN int ZEXPORT gzgetc OF((gzFile file));
  74891. /*
  74892. Reads one byte from the compressed file. gzgetc returns this byte
  74893. or -1 in case of end of file or error.
  74894. */
  74895. ZEXTERN int ZEXPORT gzungetc OF((int c, gzFile file));
  74896. /*
  74897. Push one character back onto the stream to be read again later.
  74898. Only one character of push-back is allowed. gzungetc() returns the
  74899. character pushed, or -1 on failure. gzungetc() will fail if a
  74900. character has been pushed but not read yet, or if c is -1. The pushed
  74901. character will be discarded if the stream is repositioned with gzseek()
  74902. or gzrewind().
  74903. */
  74904. ZEXTERN int ZEXPORT gzflush OF((gzFile file, int flush));
  74905. /*
  74906. Flushes all pending output into the compressed file. The parameter
  74907. flush is as in the deflate() function. The return value is the zlib
  74908. error number (see function gzerror below). gzflush returns Z_OK if
  74909. the flush parameter is Z_FINISH and all output could be flushed.
  74910. gzflush should be called only when strictly necessary because it can
  74911. degrade compression.
  74912. */
  74913. ZEXTERN z_off_t ZEXPORT gzseek OF((gzFile file,
  74914. z_off_t offset, int whence));
  74915. /*
  74916. Sets the starting position for the next gzread or gzwrite on the
  74917. given compressed file. The offset represents a number of bytes in the
  74918. uncompressed data stream. The whence parameter is defined as in lseek(2);
  74919. the value SEEK_END is not supported.
  74920. If the file is opened for reading, this function is emulated but can be
  74921. extremely slow. If the file is opened for writing, only forward seeks are
  74922. supported; gzseek then compresses a sequence of zeroes up to the new
  74923. starting position.
  74924. gzseek returns the resulting offset location as measured in bytes from
  74925. the beginning of the uncompressed stream, or -1 in case of error, in
  74926. particular if the file is opened for writing and the new starting position
  74927. would be before the current position.
  74928. */
  74929. ZEXTERN int ZEXPORT gzrewind OF((gzFile file));
  74930. /*
  74931. Rewinds the given file. This function is supported only for reading.
  74932. gzrewind(file) is equivalent to (int)gzseek(file, 0L, SEEK_SET)
  74933. */
  74934. ZEXTERN z_off_t ZEXPORT gztell OF((gzFile file));
  74935. /*
  74936. Returns the starting position for the next gzread or gzwrite on the
  74937. given compressed file. This position represents a number of bytes in the
  74938. uncompressed data stream.
  74939. gztell(file) is equivalent to gzseek(file, 0L, SEEK_CUR)
  74940. */
  74941. ZEXTERN int ZEXPORT gzeof OF((gzFile file));
  74942. /*
  74943. Returns 1 when EOF has previously been detected reading the given
  74944. input stream, otherwise zero.
  74945. */
  74946. ZEXTERN int ZEXPORT gzdirect OF((gzFile file));
  74947. /*
  74948. Returns 1 if file is being read directly without decompression, otherwise
  74949. zero.
  74950. */
  74951. ZEXTERN int ZEXPORT gzclose OF((gzFile file));
  74952. /*
  74953. Flushes all pending output if necessary, closes the compressed file
  74954. and deallocates all the (de)compression state. The return value is the zlib
  74955. error number (see function gzerror below).
  74956. */
  74957. ZEXTERN const char * ZEXPORT gzerror OF((gzFile file, int *errnum));
  74958. /*
  74959. Returns the error message for the last error which occurred on the
  74960. given compressed file. errnum is set to zlib error number. If an
  74961. error occurred in the file system and not in the compression library,
  74962. errnum is set to Z_ERRNO and the application may consult errno
  74963. to get the exact error code.
  74964. */
  74965. ZEXTERN void ZEXPORT gzclearerr OF((gzFile file));
  74966. /*
  74967. Clears the error and end-of-file flags for file. This is analogous to the
  74968. clearerr() function in stdio. This is useful for continuing to read a gzip
  74969. file that is being written concurrently.
  74970. */
  74971. /* checksum functions */
  74972. /*
  74973. These functions are not related to compression but are exported
  74974. anyway because they might be useful in applications using the
  74975. compression library.
  74976. */
  74977. ZEXTERN uLong ZEXPORT adler32 OF((uLong adler, const Bytef *buf, uInt len));
  74978. /*
  74979. Update a running Adler-32 checksum with the bytes buf[0..len-1] and
  74980. return the updated checksum. If buf is NULL, this function returns
  74981. the required initial value for the checksum.
  74982. An Adler-32 checksum is almost as reliable as a CRC32 but can be computed
  74983. much faster. Usage example:
  74984. uLong adler = adler32(0L, Z_NULL, 0);
  74985. while (read_buffer(buffer, length) != EOF) {
  74986. adler = adler32(adler, buffer, length);
  74987. }
  74988. if (adler != original_adler) error();
  74989. */
  74990. ZEXTERN uLong ZEXPORT adler32_combine OF((uLong adler1, uLong adler2,
  74991. z_off_t len2));
  74992. /*
  74993. Combine two Adler-32 checksums into one. For two sequences of bytes, seq1
  74994. and seq2 with lengths len1 and len2, Adler-32 checksums were calculated for
  74995. each, adler1 and adler2. adler32_combine() returns the Adler-32 checksum of
  74996. seq1 and seq2 concatenated, requiring only adler1, adler2, and len2.
  74997. */
  74998. ZEXTERN uLong ZEXPORT crc32 OF((uLong crc, const Bytef *buf, uInt len));
  74999. /*
  75000. Update a running CRC-32 with the bytes buf[0..len-1] and return the
  75001. updated CRC-32. If buf is NULL, this function returns the required initial
  75002. value for the for the crc. Pre- and post-conditioning (one's complement) is
  75003. performed within this function so it shouldn't be done by the application.
  75004. Usage example:
  75005. uLong crc = crc32(0L, Z_NULL, 0);
  75006. while (read_buffer(buffer, length) != EOF) {
  75007. crc = crc32(crc, buffer, length);
  75008. }
  75009. if (crc != original_crc) error();
  75010. */
  75011. ZEXTERN uLong ZEXPORT crc32_combine OF((uLong crc1, uLong crc2, z_off_t len2));
  75012. /*
  75013. Combine two CRC-32 check values into one. For two sequences of bytes,
  75014. seq1 and seq2 with lengths len1 and len2, CRC-32 check values were
  75015. calculated for each, crc1 and crc2. crc32_combine() returns the CRC-32
  75016. check value of seq1 and seq2 concatenated, requiring only crc1, crc2, and
  75017. len2.
  75018. */
  75019. /* various hacks, don't look :) */
  75020. /* deflateInit and inflateInit are macros to allow checking the zlib version
  75021. * and the compiler's view of z_stream:
  75022. */
  75023. ZEXTERN int ZEXPORT deflateInit_ OF((z_streamp strm, int level,
  75024. const char *version, int stream_size));
  75025. ZEXTERN int ZEXPORT inflateInit_ OF((z_streamp strm,
  75026. const char *version, int stream_size));
  75027. ZEXTERN int ZEXPORT deflateInit2_ OF((z_streamp strm, int level, int method,
  75028. int windowBits, int memLevel,
  75029. int strategy, const char *version,
  75030. int stream_size));
  75031. ZEXTERN int ZEXPORT inflateInit2_ OF((z_streamp strm, int windowBits,
  75032. const char *version, int stream_size));
  75033. ZEXTERN int ZEXPORT inflateBackInit_ OF((z_streamp strm, int windowBits,
  75034. unsigned char FAR *window,
  75035. const char *version,
  75036. int stream_size));
  75037. #define deflateInit(strm, level) \
  75038. deflateInit_((strm), (level), ZLIB_VERSION, sizeof(z_stream))
  75039. #define inflateInit(strm) \
  75040. inflateInit_((strm), ZLIB_VERSION, sizeof(z_stream))
  75041. #define deflateInit2(strm, level, method, windowBits, memLevel, strategy) \
  75042. deflateInit2_((strm),(level),(method),(windowBits),(memLevel),\
  75043. (strategy), ZLIB_VERSION, sizeof(z_stream))
  75044. #define inflateInit2(strm, windowBits) \
  75045. inflateInit2_((strm), (windowBits), ZLIB_VERSION, sizeof(z_stream))
  75046. #define inflateBackInit(strm, windowBits, window) \
  75047. inflateBackInit_((strm), (windowBits), (window), \
  75048. ZLIB_VERSION, sizeof(z_stream))
  75049. #if !defined(ZUTIL_H) && !defined(NO_DUMMY_DECL)
  75050. struct internal_state {int dummy;}; /* hack for buggy compilers */
  75051. #endif
  75052. ZEXTERN const char * ZEXPORT zError OF((int));
  75053. ZEXTERN int ZEXPORT inflateSyncPoint OF((z_streamp z));
  75054. ZEXTERN const uLongf * ZEXPORT get_crc_table OF((void));
  75055. #ifdef __cplusplus
  75056. }
  75057. #endif
  75058. #endif /* ZLIB_H */
  75059. /********* End of inlined file: zlib.h *********/
  75060. #undef OS_CODE
  75061. #else
  75062. #include <zlib.h>
  75063. #endif
  75064. }
  75065. BEGIN_JUCE_NAMESPACE
  75066. using namespace zlibNamespace;
  75067. // internal helper object that holds the zlib structures so they don't have to be
  75068. // included publicly.
  75069. class GZIPCompressorHelper
  75070. {
  75071. private:
  75072. z_stream* stream;
  75073. uint8* data;
  75074. int dataSize, compLevel, strategy;
  75075. bool setParams;
  75076. public:
  75077. bool finished, shouldFinish;
  75078. GZIPCompressorHelper (const int compressionLevel, const bool nowrap)
  75079. : data (0),
  75080. dataSize (0),
  75081. compLevel (compressionLevel),
  75082. strategy (0),
  75083. setParams (true),
  75084. finished (false),
  75085. shouldFinish (false)
  75086. {
  75087. stream = (z_stream*) juce_calloc (sizeof (z_stream));
  75088. if (deflateInit2 (stream,
  75089. compLevel,
  75090. Z_DEFLATED,
  75091. nowrap ? -MAX_WBITS : MAX_WBITS,
  75092. 8,
  75093. strategy) != Z_OK)
  75094. {
  75095. juce_free (stream);
  75096. stream = 0;
  75097. }
  75098. }
  75099. ~GZIPCompressorHelper()
  75100. {
  75101. if (stream != 0)
  75102. {
  75103. deflateEnd (stream);
  75104. juce_free (stream);
  75105. }
  75106. }
  75107. bool needsInput() const throw()
  75108. {
  75109. return dataSize <= 0;
  75110. }
  75111. void setInput (uint8* const newData, const int size) throw()
  75112. {
  75113. data = newData;
  75114. dataSize = size;
  75115. }
  75116. int doNextBlock (uint8* const dest, const int destSize) throw()
  75117. {
  75118. if (stream != 0)
  75119. {
  75120. stream->next_in = data;
  75121. stream->next_out = dest;
  75122. stream->avail_in = dataSize;
  75123. stream->avail_out = destSize;
  75124. const int result = setParams ? deflateParams (stream, compLevel, strategy)
  75125. : deflate (stream, shouldFinish ? Z_FINISH : Z_NO_FLUSH);
  75126. setParams = false;
  75127. switch (result)
  75128. {
  75129. case Z_STREAM_END:
  75130. finished = true;
  75131. case Z_OK:
  75132. data += dataSize - stream->avail_in;
  75133. dataSize = stream->avail_in;
  75134. return destSize - stream->avail_out;
  75135. default:
  75136. break;
  75137. }
  75138. }
  75139. return 0;
  75140. }
  75141. };
  75142. const int gzipCompBufferSize = 32768;
  75143. GZIPCompressorOutputStream::GZIPCompressorOutputStream (OutputStream* const destStream_,
  75144. int compressionLevel,
  75145. const bool deleteDestStream_,
  75146. const bool noWrap)
  75147. : destStream (destStream_),
  75148. deleteDestStream (deleteDestStream_)
  75149. {
  75150. if (compressionLevel < 1 || compressionLevel > 9)
  75151. compressionLevel = -1;
  75152. helper = new GZIPCompressorHelper (compressionLevel, noWrap);
  75153. buffer = (uint8*) juce_malloc (gzipCompBufferSize);
  75154. }
  75155. GZIPCompressorOutputStream::~GZIPCompressorOutputStream()
  75156. {
  75157. flush();
  75158. GZIPCompressorHelper* const h = (GZIPCompressorHelper*) helper;
  75159. delete h;
  75160. juce_free (buffer);
  75161. if (deleteDestStream)
  75162. delete destStream;
  75163. }
  75164. void GZIPCompressorOutputStream::flush()
  75165. {
  75166. GZIPCompressorHelper* const h = (GZIPCompressorHelper*) helper;
  75167. if (! h->finished)
  75168. {
  75169. h->shouldFinish = true;
  75170. while (! h->finished)
  75171. doNextBlock();
  75172. }
  75173. destStream->flush();
  75174. }
  75175. bool GZIPCompressorOutputStream::write (const void* destBuffer, int howMany)
  75176. {
  75177. GZIPCompressorHelper* const h = (GZIPCompressorHelper*) helper;
  75178. if (! h->finished)
  75179. {
  75180. h->setInput ((uint8*) destBuffer, howMany);
  75181. while (! h->needsInput())
  75182. {
  75183. if (! doNextBlock())
  75184. return false;
  75185. }
  75186. }
  75187. return true;
  75188. }
  75189. bool GZIPCompressorOutputStream::doNextBlock()
  75190. {
  75191. GZIPCompressorHelper* const h = (GZIPCompressorHelper*) helper;
  75192. const int len = h->doNextBlock (buffer, gzipCompBufferSize);
  75193. if (len > 0)
  75194. return destStream->write (buffer, len);
  75195. else
  75196. return true;
  75197. }
  75198. int64 GZIPCompressorOutputStream::getPosition()
  75199. {
  75200. return destStream->getPosition();
  75201. }
  75202. bool GZIPCompressorOutputStream::setPosition (int64 /*newPosition*/)
  75203. {
  75204. jassertfalse // can't do it!
  75205. return false;
  75206. }
  75207. END_JUCE_NAMESPACE
  75208. /********* End of inlined file: juce_GZIPCompressorOutputStream.cpp *********/
  75209. /********* Start of inlined file: juce_GZIPDecompressorInputStream.cpp *********/
  75210. #if JUCE_MSVC
  75211. #pragma warning (push)
  75212. #pragma warning (disable: 4309 4305)
  75213. #endif
  75214. namespace zlibNamespace
  75215. {
  75216. #if JUCE_INCLUDE_ZLIB_CODE
  75217. extern "C"
  75218. {
  75219. #undef OS_CODE
  75220. #undef fdopen
  75221. #define ZLIB_INTERNAL
  75222. #define NO_DUMMY_DECL
  75223. /********* Start of inlined file: adler32.c *********/
  75224. /* @(#) $Id: adler32.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  75225. #define ZLIB_INTERNAL
  75226. #define BASE 65521UL /* largest prime smaller than 65536 */
  75227. #define NMAX 5552
  75228. /* NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1 */
  75229. #define DO1(buf,i) {adler += (buf)[i]; sum2 += adler;}
  75230. #define DO2(buf,i) DO1(buf,i); DO1(buf,i+1);
  75231. #define DO4(buf,i) DO2(buf,i); DO2(buf,i+2);
  75232. #define DO8(buf,i) DO4(buf,i); DO4(buf,i+4);
  75233. #define DO16(buf) DO8(buf,0); DO8(buf,8);
  75234. /* use NO_DIVIDE if your processor does not do division in hardware */
  75235. #ifdef NO_DIVIDE
  75236. # define MOD(a) \
  75237. do { \
  75238. if (a >= (BASE << 16)) a -= (BASE << 16); \
  75239. if (a >= (BASE << 15)) a -= (BASE << 15); \
  75240. if (a >= (BASE << 14)) a -= (BASE << 14); \
  75241. if (a >= (BASE << 13)) a -= (BASE << 13); \
  75242. if (a >= (BASE << 12)) a -= (BASE << 12); \
  75243. if (a >= (BASE << 11)) a -= (BASE << 11); \
  75244. if (a >= (BASE << 10)) a -= (BASE << 10); \
  75245. if (a >= (BASE << 9)) a -= (BASE << 9); \
  75246. if (a >= (BASE << 8)) a -= (BASE << 8); \
  75247. if (a >= (BASE << 7)) a -= (BASE << 7); \
  75248. if (a >= (BASE << 6)) a -= (BASE << 6); \
  75249. if (a >= (BASE << 5)) a -= (BASE << 5); \
  75250. if (a >= (BASE << 4)) a -= (BASE << 4); \
  75251. if (a >= (BASE << 3)) a -= (BASE << 3); \
  75252. if (a >= (BASE << 2)) a -= (BASE << 2); \
  75253. if (a >= (BASE << 1)) a -= (BASE << 1); \
  75254. if (a >= BASE) a -= BASE; \
  75255. } while (0)
  75256. # define MOD4(a) \
  75257. do { \
  75258. if (a >= (BASE << 4)) a -= (BASE << 4); \
  75259. if (a >= (BASE << 3)) a -= (BASE << 3); \
  75260. if (a >= (BASE << 2)) a -= (BASE << 2); \
  75261. if (a >= (BASE << 1)) a -= (BASE << 1); \
  75262. if (a >= BASE) a -= BASE; \
  75263. } while (0)
  75264. #else
  75265. # define MOD(a) a %= BASE
  75266. # define MOD4(a) a %= BASE
  75267. #endif
  75268. /* ========================================================================= */
  75269. uLong ZEXPORT adler32(uLong adler, const Bytef *buf, uInt len)
  75270. {
  75271. unsigned long sum2;
  75272. unsigned n;
  75273. /* split Adler-32 into component sums */
  75274. sum2 = (adler >> 16) & 0xffff;
  75275. adler &= 0xffff;
  75276. /* in case user likes doing a byte at a time, keep it fast */
  75277. if (len == 1) {
  75278. adler += buf[0];
  75279. if (adler >= BASE)
  75280. adler -= BASE;
  75281. sum2 += adler;
  75282. if (sum2 >= BASE)
  75283. sum2 -= BASE;
  75284. return adler | (sum2 << 16);
  75285. }
  75286. /* initial Adler-32 value (deferred check for len == 1 speed) */
  75287. if (buf == Z_NULL)
  75288. return 1L;
  75289. /* in case short lengths are provided, keep it somewhat fast */
  75290. if (len < 16) {
  75291. while (len--) {
  75292. adler += *buf++;
  75293. sum2 += adler;
  75294. }
  75295. if (adler >= BASE)
  75296. adler -= BASE;
  75297. MOD4(sum2); /* only added so many BASE's */
  75298. return adler | (sum2 << 16);
  75299. }
  75300. /* do length NMAX blocks -- requires just one modulo operation */
  75301. while (len >= NMAX) {
  75302. len -= NMAX;
  75303. n = NMAX / 16; /* NMAX is divisible by 16 */
  75304. do {
  75305. DO16(buf); /* 16 sums unrolled */
  75306. buf += 16;
  75307. } while (--n);
  75308. MOD(adler);
  75309. MOD(sum2);
  75310. }
  75311. /* do remaining bytes (less than NMAX, still just one modulo) */
  75312. if (len) { /* avoid modulos if none remaining */
  75313. while (len >= 16) {
  75314. len -= 16;
  75315. DO16(buf);
  75316. buf += 16;
  75317. }
  75318. while (len--) {
  75319. adler += *buf++;
  75320. sum2 += adler;
  75321. }
  75322. MOD(adler);
  75323. MOD(sum2);
  75324. }
  75325. /* return recombined sums */
  75326. return adler | (sum2 << 16);
  75327. }
  75328. /* ========================================================================= */
  75329. uLong ZEXPORT adler32_combine(uLong adler1, uLong adler2, z_off_t len2)
  75330. {
  75331. unsigned long sum1;
  75332. unsigned long sum2;
  75333. unsigned rem;
  75334. /* the derivation of this formula is left as an exercise for the reader */
  75335. rem = (unsigned)(len2 % BASE);
  75336. sum1 = adler1 & 0xffff;
  75337. sum2 = rem * sum1;
  75338. MOD(sum2);
  75339. sum1 += (adler2 & 0xffff) + BASE - 1;
  75340. sum2 += ((adler1 >> 16) & 0xffff) + ((adler2 >> 16) & 0xffff) + BASE - rem;
  75341. if (sum1 > BASE) sum1 -= BASE;
  75342. if (sum1 > BASE) sum1 -= BASE;
  75343. if (sum2 > (BASE << 1)) sum2 -= (BASE << 1);
  75344. if (sum2 > BASE) sum2 -= BASE;
  75345. return sum1 | (sum2 << 16);
  75346. }
  75347. /********* End of inlined file: adler32.c *********/
  75348. /********* Start of inlined file: compress.c *********/
  75349. /* @(#) $Id: compress.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  75350. #define ZLIB_INTERNAL
  75351. /* ===========================================================================
  75352. Compresses the source buffer into the destination buffer. The level
  75353. parameter has the same meaning as in deflateInit. sourceLen is the byte
  75354. length of the source buffer. Upon entry, destLen is the total size of the
  75355. destination buffer, which must be at least 0.1% larger than sourceLen plus
  75356. 12 bytes. Upon exit, destLen is the actual size of the compressed buffer.
  75357. compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  75358. memory, Z_BUF_ERROR if there was not enough room in the output buffer,
  75359. Z_STREAM_ERROR if the level parameter is invalid.
  75360. */
  75361. int ZEXPORT compress2 (Bytef *dest, uLongf *destLen, const Bytef *source,
  75362. uLong sourceLen, int level)
  75363. {
  75364. z_stream stream;
  75365. int err;
  75366. stream.next_in = (Bytef*)source;
  75367. stream.avail_in = (uInt)sourceLen;
  75368. #ifdef MAXSEG_64K
  75369. /* Check for source > 64K on 16-bit machine: */
  75370. if ((uLong)stream.avail_in != sourceLen) return Z_BUF_ERROR;
  75371. #endif
  75372. stream.next_out = dest;
  75373. stream.avail_out = (uInt)*destLen;
  75374. if ((uLong)stream.avail_out != *destLen) return Z_BUF_ERROR;
  75375. stream.zalloc = (alloc_func)0;
  75376. stream.zfree = (free_func)0;
  75377. stream.opaque = (voidpf)0;
  75378. err = deflateInit(&stream, level);
  75379. if (err != Z_OK) return err;
  75380. err = deflate(&stream, Z_FINISH);
  75381. if (err != Z_STREAM_END) {
  75382. deflateEnd(&stream);
  75383. return err == Z_OK ? Z_BUF_ERROR : err;
  75384. }
  75385. *destLen = stream.total_out;
  75386. err = deflateEnd(&stream);
  75387. return err;
  75388. }
  75389. /* ===========================================================================
  75390. */
  75391. int ZEXPORT compress (Bytef *dest, uLongf *destLen, const Bytef *source, uLong sourceLen)
  75392. {
  75393. return compress2(dest, destLen, source, sourceLen, Z_DEFAULT_COMPRESSION);
  75394. }
  75395. /* ===========================================================================
  75396. If the default memLevel or windowBits for deflateInit() is changed, then
  75397. this function needs to be updated.
  75398. */
  75399. uLong ZEXPORT compressBound (uLong sourceLen)
  75400. {
  75401. return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) + 11;
  75402. }
  75403. /********* End of inlined file: compress.c *********/
  75404. #undef DO1
  75405. #undef DO8
  75406. /********* Start of inlined file: crc32.c *********/
  75407. /* @(#) $Id: crc32.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  75408. /*
  75409. Note on the use of DYNAMIC_CRC_TABLE: there is no mutex or semaphore
  75410. protection on the static variables used to control the first-use generation
  75411. of the crc tables. Therefore, if you #define DYNAMIC_CRC_TABLE, you should
  75412. first call get_crc_table() to initialize the tables before allowing more than
  75413. one thread to use crc32().
  75414. */
  75415. #ifdef MAKECRCH
  75416. # include <stdio.h>
  75417. # ifndef DYNAMIC_CRC_TABLE
  75418. # define DYNAMIC_CRC_TABLE
  75419. # endif /* !DYNAMIC_CRC_TABLE */
  75420. #endif /* MAKECRCH */
  75421. /********* Start of inlined file: zutil.h *********/
  75422. /* WARNING: this file should *not* be used by applications. It is
  75423. part of the implementation of the compression library and is
  75424. subject to change. Applications should only use zlib.h.
  75425. */
  75426. /* @(#) $Id: zutil.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  75427. #ifndef ZUTIL_H
  75428. #define ZUTIL_H
  75429. #define ZLIB_INTERNAL
  75430. #ifdef STDC
  75431. # ifndef _WIN32_WCE
  75432. # include <stddef.h>
  75433. # endif
  75434. # include <string.h>
  75435. # include <stdlib.h>
  75436. #endif
  75437. #ifdef NO_ERRNO_H
  75438. # ifdef _WIN32_WCE
  75439. /* The Microsoft C Run-Time Library for Windows CE doesn't have
  75440. * errno. We define it as a global variable to simplify porting.
  75441. * Its value is always 0 and should not be used. We rename it to
  75442. * avoid conflict with other libraries that use the same workaround.
  75443. */
  75444. # define errno z_errno
  75445. # endif
  75446. extern int errno;
  75447. #else
  75448. # ifndef _WIN32_WCE
  75449. # include <errno.h>
  75450. # endif
  75451. #endif
  75452. #ifndef local
  75453. # define local static
  75454. #endif
  75455. /* compile with -Dlocal if your debugger can't find static symbols */
  75456. typedef unsigned char uch;
  75457. typedef uch FAR uchf;
  75458. typedef unsigned short ush;
  75459. typedef ush FAR ushf;
  75460. typedef unsigned long ulg;
  75461. extern const char * const z_errmsg[10]; /* indexed by 2-zlib_error */
  75462. /* (size given to avoid silly warnings with Visual C++) */
  75463. #define ERR_MSG(err) z_errmsg[Z_NEED_DICT-(err)]
  75464. #define ERR_RETURN(strm,err) \
  75465. return (strm->msg = (char*)ERR_MSG(err), (err))
  75466. /* To be used only when the state is known to be valid */
  75467. /* common constants */
  75468. #ifndef DEF_WBITS
  75469. # define DEF_WBITS MAX_WBITS
  75470. #endif
  75471. /* default windowBits for decompression. MAX_WBITS is for compression only */
  75472. #if MAX_MEM_LEVEL >= 8
  75473. # define DEF_MEM_LEVEL 8
  75474. #else
  75475. # define DEF_MEM_LEVEL MAX_MEM_LEVEL
  75476. #endif
  75477. /* default memLevel */
  75478. #define STORED_BLOCK 0
  75479. #define STATIC_TREES 1
  75480. #define DYN_TREES 2
  75481. /* The three kinds of block type */
  75482. #define MIN_MATCH 3
  75483. #define MAX_MATCH 258
  75484. /* The minimum and maximum match lengths */
  75485. #define PRESET_DICT 0x20 /* preset dictionary flag in zlib header */
  75486. /* target dependencies */
  75487. #if defined(MSDOS) || (defined(WINDOWS) && !defined(WIN32))
  75488. # define OS_CODE 0x00
  75489. # if defined(__TURBOC__) || defined(__BORLANDC__)
  75490. # if(__STDC__ == 1) && (defined(__LARGE__) || defined(__COMPACT__))
  75491. /* Allow compilation with ANSI keywords only enabled */
  75492. void _Cdecl farfree( void *block );
  75493. void *_Cdecl farmalloc( unsigned long nbytes );
  75494. # else
  75495. # include <alloc.h>
  75496. # endif
  75497. # else /* MSC or DJGPP */
  75498. # include <malloc.h>
  75499. # endif
  75500. #endif
  75501. #ifdef AMIGA
  75502. # define OS_CODE 0x01
  75503. #endif
  75504. #if defined(VAXC) || defined(VMS)
  75505. # define OS_CODE 0x02
  75506. # define F_OPEN(name, mode) \
  75507. fopen((name), (mode), "mbc=60", "ctx=stm", "rfm=fix", "mrs=512")
  75508. #endif
  75509. #if defined(ATARI) || defined(atarist)
  75510. # define OS_CODE 0x05
  75511. #endif
  75512. #ifdef OS2
  75513. # define OS_CODE 0x06
  75514. # ifdef M_I86
  75515. #include <malloc.h>
  75516. # endif
  75517. #endif
  75518. #if defined(MACOS) || TARGET_OS_MAC
  75519. # define OS_CODE 0x07
  75520. # if defined(__MWERKS__) && __dest_os != __be_os && __dest_os != __win32_os
  75521. # include <unix.h> /* for fdopen */
  75522. # else
  75523. # ifndef fdopen
  75524. # define fdopen(fd,mode) NULL /* No fdopen() */
  75525. # endif
  75526. # endif
  75527. #endif
  75528. #ifdef TOPS20
  75529. # define OS_CODE 0x0a
  75530. #endif
  75531. #ifdef WIN32
  75532. # ifndef __CYGWIN__ /* Cygwin is Unix, not Win32 */
  75533. # define OS_CODE 0x0b
  75534. # endif
  75535. #endif
  75536. #ifdef __50SERIES /* Prime/PRIMOS */
  75537. # define OS_CODE 0x0f
  75538. #endif
  75539. #if defined(_BEOS_) || defined(RISCOS)
  75540. # define fdopen(fd,mode) NULL /* No fdopen() */
  75541. #endif
  75542. #if (defined(_MSC_VER) && (_MSC_VER > 600))
  75543. # if defined(_WIN32_WCE)
  75544. # define fdopen(fd,mode) NULL /* No fdopen() */
  75545. # ifndef _PTRDIFF_T_DEFINED
  75546. typedef int ptrdiff_t;
  75547. # define _PTRDIFF_T_DEFINED
  75548. # endif
  75549. # else
  75550. # define fdopen(fd,type) _fdopen(fd,type)
  75551. # endif
  75552. #endif
  75553. /* common defaults */
  75554. #ifndef OS_CODE
  75555. # define OS_CODE 0x03 /* assume Unix */
  75556. #endif
  75557. #ifndef F_OPEN
  75558. # define F_OPEN(name, mode) fopen((name), (mode))
  75559. #endif
  75560. /* functions */
  75561. #if defined(STDC99) || (defined(__TURBOC__) && __TURBOC__ >= 0x550)
  75562. # ifndef HAVE_VSNPRINTF
  75563. # define HAVE_VSNPRINTF
  75564. # endif
  75565. #endif
  75566. #if defined(__CYGWIN__)
  75567. # ifndef HAVE_VSNPRINTF
  75568. # define HAVE_VSNPRINTF
  75569. # endif
  75570. #endif
  75571. #ifndef HAVE_VSNPRINTF
  75572. # ifdef MSDOS
  75573. /* vsnprintf may exist on some MS-DOS compilers (DJGPP?),
  75574. but for now we just assume it doesn't. */
  75575. # define NO_vsnprintf
  75576. # endif
  75577. # ifdef __TURBOC__
  75578. # define NO_vsnprintf
  75579. # endif
  75580. # ifdef WIN32
  75581. /* In Win32, vsnprintf is available as the "non-ANSI" _vsnprintf. */
  75582. # if !defined(vsnprintf) && !defined(NO_vsnprintf)
  75583. # define vsnprintf _vsnprintf
  75584. # endif
  75585. # endif
  75586. # ifdef __SASC
  75587. # define NO_vsnprintf
  75588. # endif
  75589. #endif
  75590. #ifdef VMS
  75591. # define NO_vsnprintf
  75592. #endif
  75593. #if defined(pyr)
  75594. # define NO_MEMCPY
  75595. #endif
  75596. #if defined(SMALL_MEDIUM) && !defined(_MSC_VER) && !defined(__SC__)
  75597. /* Use our own functions for small and medium model with MSC <= 5.0.
  75598. * You may have to use the same strategy for Borland C (untested).
  75599. * The __SC__ check is for Symantec.
  75600. */
  75601. # define NO_MEMCPY
  75602. #endif
  75603. #if defined(STDC) && !defined(HAVE_MEMCPY) && !defined(NO_MEMCPY)
  75604. # define HAVE_MEMCPY
  75605. #endif
  75606. #ifdef HAVE_MEMCPY
  75607. # ifdef SMALL_MEDIUM /* MSDOS small or medium model */
  75608. # define zmemcpy _fmemcpy
  75609. # define zmemcmp _fmemcmp
  75610. # define zmemzero(dest, len) _fmemset(dest, 0, len)
  75611. # else
  75612. # define zmemcpy memcpy
  75613. # define zmemcmp memcmp
  75614. # define zmemzero(dest, len) memset(dest, 0, len)
  75615. # endif
  75616. #else
  75617. extern void zmemcpy OF((Bytef* dest, const Bytef* source, uInt len));
  75618. extern int zmemcmp OF((const Bytef* s1, const Bytef* s2, uInt len));
  75619. extern void zmemzero OF((Bytef* dest, uInt len));
  75620. #endif
  75621. /* Diagnostic functions */
  75622. #ifdef DEBUG
  75623. # include <stdio.h>
  75624. extern int z_verbose;
  75625. extern void z_error OF((const char *m));
  75626. # define Assert(cond,msg) {if(!(cond)) z_error(msg);}
  75627. # define Trace(x) {if (z_verbose>=0) fprintf x ;}
  75628. # define Tracev(x) {if (z_verbose>0) fprintf x ;}
  75629. # define Tracevv(x) {if (z_verbose>1) fprintf x ;}
  75630. # define Tracec(c,x) {if (z_verbose>0 && (c)) fprintf x ;}
  75631. # define Tracecv(c,x) {if (z_verbose>1 && (c)) fprintf x ;}
  75632. #else
  75633. # define Assert(cond,msg)
  75634. # define Trace(x)
  75635. # define Tracev(x)
  75636. # define Tracevv(x)
  75637. # define Tracec(c,x)
  75638. # define Tracecv(c,x)
  75639. #endif
  75640. voidpf zcalloc OF((voidpf opaque, unsigned items, unsigned size));
  75641. void zcfree OF((voidpf opaque, voidpf ptr));
  75642. #define ZALLOC(strm, items, size) \
  75643. (*((strm)->zalloc))((strm)->opaque, (items), (size))
  75644. #define ZFREE(strm, addr) (*((strm)->zfree))((strm)->opaque, (voidpf)(addr))
  75645. #define TRY_FREE(s, p) {if (p) ZFREE(s, p);}
  75646. #endif /* ZUTIL_H */
  75647. /********* End of inlined file: zutil.h *********/
  75648. /* for STDC and FAR definitions */
  75649. #define local static
  75650. /* Find a four-byte integer type for crc32_little() and crc32_big(). */
  75651. #ifndef NOBYFOUR
  75652. # ifdef STDC /* need ANSI C limits.h to determine sizes */
  75653. # include <limits.h>
  75654. # define BYFOUR
  75655. # if (UINT_MAX == 0xffffffffUL)
  75656. typedef unsigned int u4;
  75657. # else
  75658. # if (ULONG_MAX == 0xffffffffUL)
  75659. typedef unsigned long u4;
  75660. # else
  75661. # if (USHRT_MAX == 0xffffffffUL)
  75662. typedef unsigned short u4;
  75663. # else
  75664. # undef BYFOUR /* can't find a four-byte integer type! */
  75665. # endif
  75666. # endif
  75667. # endif
  75668. # endif /* STDC */
  75669. #endif /* !NOBYFOUR */
  75670. /* Definitions for doing the crc four data bytes at a time. */
  75671. #ifdef BYFOUR
  75672. # define REV(w) (((w)>>24)+(((w)>>8)&0xff00)+ \
  75673. (((w)&0xff00)<<8)+(((w)&0xff)<<24))
  75674. local unsigned long crc32_little OF((unsigned long,
  75675. const unsigned char FAR *, unsigned));
  75676. local unsigned long crc32_big OF((unsigned long,
  75677. const unsigned char FAR *, unsigned));
  75678. # define TBLS 8
  75679. #else
  75680. # define TBLS 1
  75681. #endif /* BYFOUR */
  75682. /* Local functions for crc concatenation */
  75683. local unsigned long gf2_matrix_times OF((unsigned long *mat,
  75684. unsigned long vec));
  75685. local void gf2_matrix_square OF((unsigned long *square, unsigned long *mat));
  75686. #ifdef DYNAMIC_CRC_TABLE
  75687. local volatile int crc_table_empty = 1;
  75688. local unsigned long FAR crc_table[TBLS][256];
  75689. local void make_crc_table OF((void));
  75690. #ifdef MAKECRCH
  75691. local void write_table OF((FILE *, const unsigned long FAR *));
  75692. #endif /* MAKECRCH */
  75693. /*
  75694. Generate tables for a byte-wise 32-bit CRC calculation on the polynomial:
  75695. x^32+x^26+x^23+x^22+x^16+x^12+x^11+x^10+x^8+x^7+x^5+x^4+x^2+x+1.
  75696. Polynomials over GF(2) are represented in binary, one bit per coefficient,
  75697. with the lowest powers in the most significant bit. Then adding polynomials
  75698. is just exclusive-or, and multiplying a polynomial by x is a right shift by
  75699. one. If we call the above polynomial p, and represent a byte as the
  75700. polynomial q, also with the lowest power in the most significant bit (so the
  75701. byte 0xb1 is the polynomial x^7+x^3+x+1), then the CRC is (q*x^32) mod p,
  75702. where a mod b means the remainder after dividing a by b.
  75703. This calculation is done using the shift-register method of multiplying and
  75704. taking the remainder. The register is initialized to zero, and for each
  75705. incoming bit, x^32 is added mod p to the register if the bit is a one (where
  75706. x^32 mod p is p+x^32 = x^26+...+1), and the register is multiplied mod p by
  75707. x (which is shifting right by one and adding x^32 mod p if the bit shifted
  75708. out is a one). We start with the highest power (least significant bit) of
  75709. q and repeat for all eight bits of q.
  75710. The first table is simply the CRC of all possible eight bit values. This is
  75711. all the information needed to generate CRCs on data a byte at a time for all
  75712. combinations of CRC register values and incoming bytes. The remaining tables
  75713. allow for word-at-a-time CRC calculation for both big-endian and little-
  75714. endian machines, where a word is four bytes.
  75715. */
  75716. local void make_crc_table()
  75717. {
  75718. unsigned long c;
  75719. int n, k;
  75720. unsigned long poly; /* polynomial exclusive-or pattern */
  75721. /* terms of polynomial defining this crc (except x^32): */
  75722. static volatile int first = 1; /* flag to limit concurrent making */
  75723. static const unsigned char p[] = {0,1,2,4,5,7,8,10,11,12,16,22,23,26};
  75724. /* See if another task is already doing this (not thread-safe, but better
  75725. than nothing -- significantly reduces duration of vulnerability in
  75726. case the advice about DYNAMIC_CRC_TABLE is ignored) */
  75727. if (first) {
  75728. first = 0;
  75729. /* make exclusive-or pattern from polynomial (0xedb88320UL) */
  75730. poly = 0UL;
  75731. for (n = 0; n < sizeof(p)/sizeof(unsigned char); n++)
  75732. poly |= 1UL << (31 - p[n]);
  75733. /* generate a crc for every 8-bit value */
  75734. for (n = 0; n < 256; n++) {
  75735. c = (unsigned long)n;
  75736. for (k = 0; k < 8; k++)
  75737. c = c & 1 ? poly ^ (c >> 1) : c >> 1;
  75738. crc_table[0][n] = c;
  75739. }
  75740. #ifdef BYFOUR
  75741. /* generate crc for each value followed by one, two, and three zeros,
  75742. and then the byte reversal of those as well as the first table */
  75743. for (n = 0; n < 256; n++) {
  75744. c = crc_table[0][n];
  75745. crc_table[4][n] = REV(c);
  75746. for (k = 1; k < 4; k++) {
  75747. c = crc_table[0][c & 0xff] ^ (c >> 8);
  75748. crc_table[k][n] = c;
  75749. crc_table[k + 4][n] = REV(c);
  75750. }
  75751. }
  75752. #endif /* BYFOUR */
  75753. crc_table_empty = 0;
  75754. }
  75755. else { /* not first */
  75756. /* wait for the other guy to finish (not efficient, but rare) */
  75757. while (crc_table_empty)
  75758. ;
  75759. }
  75760. #ifdef MAKECRCH
  75761. /* write out CRC tables to crc32.h */
  75762. {
  75763. FILE *out;
  75764. out = fopen("crc32.h", "w");
  75765. if (out == NULL) return;
  75766. fprintf(out, "/* crc32.h -- tables for rapid CRC calculation\n");
  75767. fprintf(out, " * Generated automatically by crc32.c\n */\n\n");
  75768. fprintf(out, "local const unsigned long FAR ");
  75769. fprintf(out, "crc_table[TBLS][256] =\n{\n {\n");
  75770. write_table(out, crc_table[0]);
  75771. # ifdef BYFOUR
  75772. fprintf(out, "#ifdef BYFOUR\n");
  75773. for (k = 1; k < 8; k++) {
  75774. fprintf(out, " },\n {\n");
  75775. write_table(out, crc_table[k]);
  75776. }
  75777. fprintf(out, "#endif\n");
  75778. # endif /* BYFOUR */
  75779. fprintf(out, " }\n};\n");
  75780. fclose(out);
  75781. }
  75782. #endif /* MAKECRCH */
  75783. }
  75784. #ifdef MAKECRCH
  75785. local void write_table(out, table)
  75786. FILE *out;
  75787. const unsigned long FAR *table;
  75788. {
  75789. int n;
  75790. for (n = 0; n < 256; n++)
  75791. fprintf(out, "%s0x%08lxUL%s", n % 5 ? "" : " ", table[n],
  75792. n == 255 ? "\n" : (n % 5 == 4 ? ",\n" : ", "));
  75793. }
  75794. #endif /* MAKECRCH */
  75795. #else /* !DYNAMIC_CRC_TABLE */
  75796. /* ========================================================================
  75797. * Tables of CRC-32s of all single-byte values, made by make_crc_table().
  75798. */
  75799. /********* Start of inlined file: crc32.h *********/
  75800. local const unsigned long FAR crc_table[TBLS][256] =
  75801. {
  75802. {
  75803. 0x00000000UL, 0x77073096UL, 0xee0e612cUL, 0x990951baUL, 0x076dc419UL,
  75804. 0x706af48fUL, 0xe963a535UL, 0x9e6495a3UL, 0x0edb8832UL, 0x79dcb8a4UL,
  75805. 0xe0d5e91eUL, 0x97d2d988UL, 0x09b64c2bUL, 0x7eb17cbdUL, 0xe7b82d07UL,
  75806. 0x90bf1d91UL, 0x1db71064UL, 0x6ab020f2UL, 0xf3b97148UL, 0x84be41deUL,
  75807. 0x1adad47dUL, 0x6ddde4ebUL, 0xf4d4b551UL, 0x83d385c7UL, 0x136c9856UL,
  75808. 0x646ba8c0UL, 0xfd62f97aUL, 0x8a65c9ecUL, 0x14015c4fUL, 0x63066cd9UL,
  75809. 0xfa0f3d63UL, 0x8d080df5UL, 0x3b6e20c8UL, 0x4c69105eUL, 0xd56041e4UL,
  75810. 0xa2677172UL, 0x3c03e4d1UL, 0x4b04d447UL, 0xd20d85fdUL, 0xa50ab56bUL,
  75811. 0x35b5a8faUL, 0x42b2986cUL, 0xdbbbc9d6UL, 0xacbcf940UL, 0x32d86ce3UL,
  75812. 0x45df5c75UL, 0xdcd60dcfUL, 0xabd13d59UL, 0x26d930acUL, 0x51de003aUL,
  75813. 0xc8d75180UL, 0xbfd06116UL, 0x21b4f4b5UL, 0x56b3c423UL, 0xcfba9599UL,
  75814. 0xb8bda50fUL, 0x2802b89eUL, 0x5f058808UL, 0xc60cd9b2UL, 0xb10be924UL,
  75815. 0x2f6f7c87UL, 0x58684c11UL, 0xc1611dabUL, 0xb6662d3dUL, 0x76dc4190UL,
  75816. 0x01db7106UL, 0x98d220bcUL, 0xefd5102aUL, 0x71b18589UL, 0x06b6b51fUL,
  75817. 0x9fbfe4a5UL, 0xe8b8d433UL, 0x7807c9a2UL, 0x0f00f934UL, 0x9609a88eUL,
  75818. 0xe10e9818UL, 0x7f6a0dbbUL, 0x086d3d2dUL, 0x91646c97UL, 0xe6635c01UL,
  75819. 0x6b6b51f4UL, 0x1c6c6162UL, 0x856530d8UL, 0xf262004eUL, 0x6c0695edUL,
  75820. 0x1b01a57bUL, 0x8208f4c1UL, 0xf50fc457UL, 0x65b0d9c6UL, 0x12b7e950UL,
  75821. 0x8bbeb8eaUL, 0xfcb9887cUL, 0x62dd1ddfUL, 0x15da2d49UL, 0x8cd37cf3UL,
  75822. 0xfbd44c65UL, 0x4db26158UL, 0x3ab551ceUL, 0xa3bc0074UL, 0xd4bb30e2UL,
  75823. 0x4adfa541UL, 0x3dd895d7UL, 0xa4d1c46dUL, 0xd3d6f4fbUL, 0x4369e96aUL,
  75824. 0x346ed9fcUL, 0xad678846UL, 0xda60b8d0UL, 0x44042d73UL, 0x33031de5UL,
  75825. 0xaa0a4c5fUL, 0xdd0d7cc9UL, 0x5005713cUL, 0x270241aaUL, 0xbe0b1010UL,
  75826. 0xc90c2086UL, 0x5768b525UL, 0x206f85b3UL, 0xb966d409UL, 0xce61e49fUL,
  75827. 0x5edef90eUL, 0x29d9c998UL, 0xb0d09822UL, 0xc7d7a8b4UL, 0x59b33d17UL,
  75828. 0x2eb40d81UL, 0xb7bd5c3bUL, 0xc0ba6cadUL, 0xedb88320UL, 0x9abfb3b6UL,
  75829. 0x03b6e20cUL, 0x74b1d29aUL, 0xead54739UL, 0x9dd277afUL, 0x04db2615UL,
  75830. 0x73dc1683UL, 0xe3630b12UL, 0x94643b84UL, 0x0d6d6a3eUL, 0x7a6a5aa8UL,
  75831. 0xe40ecf0bUL, 0x9309ff9dUL, 0x0a00ae27UL, 0x7d079eb1UL, 0xf00f9344UL,
  75832. 0x8708a3d2UL, 0x1e01f268UL, 0x6906c2feUL, 0xf762575dUL, 0x806567cbUL,
  75833. 0x196c3671UL, 0x6e6b06e7UL, 0xfed41b76UL, 0x89d32be0UL, 0x10da7a5aUL,
  75834. 0x67dd4accUL, 0xf9b9df6fUL, 0x8ebeeff9UL, 0x17b7be43UL, 0x60b08ed5UL,
  75835. 0xd6d6a3e8UL, 0xa1d1937eUL, 0x38d8c2c4UL, 0x4fdff252UL, 0xd1bb67f1UL,
  75836. 0xa6bc5767UL, 0x3fb506ddUL, 0x48b2364bUL, 0xd80d2bdaUL, 0xaf0a1b4cUL,
  75837. 0x36034af6UL, 0x41047a60UL, 0xdf60efc3UL, 0xa867df55UL, 0x316e8eefUL,
  75838. 0x4669be79UL, 0xcb61b38cUL, 0xbc66831aUL, 0x256fd2a0UL, 0x5268e236UL,
  75839. 0xcc0c7795UL, 0xbb0b4703UL, 0x220216b9UL, 0x5505262fUL, 0xc5ba3bbeUL,
  75840. 0xb2bd0b28UL, 0x2bb45a92UL, 0x5cb36a04UL, 0xc2d7ffa7UL, 0xb5d0cf31UL,
  75841. 0x2cd99e8bUL, 0x5bdeae1dUL, 0x9b64c2b0UL, 0xec63f226UL, 0x756aa39cUL,
  75842. 0x026d930aUL, 0x9c0906a9UL, 0xeb0e363fUL, 0x72076785UL, 0x05005713UL,
  75843. 0x95bf4a82UL, 0xe2b87a14UL, 0x7bb12baeUL, 0x0cb61b38UL, 0x92d28e9bUL,
  75844. 0xe5d5be0dUL, 0x7cdcefb7UL, 0x0bdbdf21UL, 0x86d3d2d4UL, 0xf1d4e242UL,
  75845. 0x68ddb3f8UL, 0x1fda836eUL, 0x81be16cdUL, 0xf6b9265bUL, 0x6fb077e1UL,
  75846. 0x18b74777UL, 0x88085ae6UL, 0xff0f6a70UL, 0x66063bcaUL, 0x11010b5cUL,
  75847. 0x8f659effUL, 0xf862ae69UL, 0x616bffd3UL, 0x166ccf45UL, 0xa00ae278UL,
  75848. 0xd70dd2eeUL, 0x4e048354UL, 0x3903b3c2UL, 0xa7672661UL, 0xd06016f7UL,
  75849. 0x4969474dUL, 0x3e6e77dbUL, 0xaed16a4aUL, 0xd9d65adcUL, 0x40df0b66UL,
  75850. 0x37d83bf0UL, 0xa9bcae53UL, 0xdebb9ec5UL, 0x47b2cf7fUL, 0x30b5ffe9UL,
  75851. 0xbdbdf21cUL, 0xcabac28aUL, 0x53b39330UL, 0x24b4a3a6UL, 0xbad03605UL,
  75852. 0xcdd70693UL, 0x54de5729UL, 0x23d967bfUL, 0xb3667a2eUL, 0xc4614ab8UL,
  75853. 0x5d681b02UL, 0x2a6f2b94UL, 0xb40bbe37UL, 0xc30c8ea1UL, 0x5a05df1bUL,
  75854. 0x2d02ef8dUL
  75855. #ifdef BYFOUR
  75856. },
  75857. {
  75858. 0x00000000UL, 0x191b3141UL, 0x32366282UL, 0x2b2d53c3UL, 0x646cc504UL,
  75859. 0x7d77f445UL, 0x565aa786UL, 0x4f4196c7UL, 0xc8d98a08UL, 0xd1c2bb49UL,
  75860. 0xfaefe88aUL, 0xe3f4d9cbUL, 0xacb54f0cUL, 0xb5ae7e4dUL, 0x9e832d8eUL,
  75861. 0x87981ccfUL, 0x4ac21251UL, 0x53d92310UL, 0x78f470d3UL, 0x61ef4192UL,
  75862. 0x2eaed755UL, 0x37b5e614UL, 0x1c98b5d7UL, 0x05838496UL, 0x821b9859UL,
  75863. 0x9b00a918UL, 0xb02dfadbUL, 0xa936cb9aUL, 0xe6775d5dUL, 0xff6c6c1cUL,
  75864. 0xd4413fdfUL, 0xcd5a0e9eUL, 0x958424a2UL, 0x8c9f15e3UL, 0xa7b24620UL,
  75865. 0xbea97761UL, 0xf1e8e1a6UL, 0xe8f3d0e7UL, 0xc3de8324UL, 0xdac5b265UL,
  75866. 0x5d5daeaaUL, 0x44469febUL, 0x6f6bcc28UL, 0x7670fd69UL, 0x39316baeUL,
  75867. 0x202a5aefUL, 0x0b07092cUL, 0x121c386dUL, 0xdf4636f3UL, 0xc65d07b2UL,
  75868. 0xed705471UL, 0xf46b6530UL, 0xbb2af3f7UL, 0xa231c2b6UL, 0x891c9175UL,
  75869. 0x9007a034UL, 0x179fbcfbUL, 0x0e848dbaUL, 0x25a9de79UL, 0x3cb2ef38UL,
  75870. 0x73f379ffUL, 0x6ae848beUL, 0x41c51b7dUL, 0x58de2a3cUL, 0xf0794f05UL,
  75871. 0xe9627e44UL, 0xc24f2d87UL, 0xdb541cc6UL, 0x94158a01UL, 0x8d0ebb40UL,
  75872. 0xa623e883UL, 0xbf38d9c2UL, 0x38a0c50dUL, 0x21bbf44cUL, 0x0a96a78fUL,
  75873. 0x138d96ceUL, 0x5ccc0009UL, 0x45d73148UL, 0x6efa628bUL, 0x77e153caUL,
  75874. 0xbabb5d54UL, 0xa3a06c15UL, 0x888d3fd6UL, 0x91960e97UL, 0xded79850UL,
  75875. 0xc7cca911UL, 0xece1fad2UL, 0xf5facb93UL, 0x7262d75cUL, 0x6b79e61dUL,
  75876. 0x4054b5deUL, 0x594f849fUL, 0x160e1258UL, 0x0f152319UL, 0x243870daUL,
  75877. 0x3d23419bUL, 0x65fd6ba7UL, 0x7ce65ae6UL, 0x57cb0925UL, 0x4ed03864UL,
  75878. 0x0191aea3UL, 0x188a9fe2UL, 0x33a7cc21UL, 0x2abcfd60UL, 0xad24e1afUL,
  75879. 0xb43fd0eeUL, 0x9f12832dUL, 0x8609b26cUL, 0xc94824abUL, 0xd05315eaUL,
  75880. 0xfb7e4629UL, 0xe2657768UL, 0x2f3f79f6UL, 0x362448b7UL, 0x1d091b74UL,
  75881. 0x04122a35UL, 0x4b53bcf2UL, 0x52488db3UL, 0x7965de70UL, 0x607eef31UL,
  75882. 0xe7e6f3feUL, 0xfefdc2bfUL, 0xd5d0917cUL, 0xcccba03dUL, 0x838a36faUL,
  75883. 0x9a9107bbUL, 0xb1bc5478UL, 0xa8a76539UL, 0x3b83984bUL, 0x2298a90aUL,
  75884. 0x09b5fac9UL, 0x10aecb88UL, 0x5fef5d4fUL, 0x46f46c0eUL, 0x6dd93fcdUL,
  75885. 0x74c20e8cUL, 0xf35a1243UL, 0xea412302UL, 0xc16c70c1UL, 0xd8774180UL,
  75886. 0x9736d747UL, 0x8e2de606UL, 0xa500b5c5UL, 0xbc1b8484UL, 0x71418a1aUL,
  75887. 0x685abb5bUL, 0x4377e898UL, 0x5a6cd9d9UL, 0x152d4f1eUL, 0x0c367e5fUL,
  75888. 0x271b2d9cUL, 0x3e001cddUL, 0xb9980012UL, 0xa0833153UL, 0x8bae6290UL,
  75889. 0x92b553d1UL, 0xddf4c516UL, 0xc4eff457UL, 0xefc2a794UL, 0xf6d996d5UL,
  75890. 0xae07bce9UL, 0xb71c8da8UL, 0x9c31de6bUL, 0x852aef2aUL, 0xca6b79edUL,
  75891. 0xd37048acUL, 0xf85d1b6fUL, 0xe1462a2eUL, 0x66de36e1UL, 0x7fc507a0UL,
  75892. 0x54e85463UL, 0x4df36522UL, 0x02b2f3e5UL, 0x1ba9c2a4UL, 0x30849167UL,
  75893. 0x299fa026UL, 0xe4c5aeb8UL, 0xfdde9ff9UL, 0xd6f3cc3aUL, 0xcfe8fd7bUL,
  75894. 0x80a96bbcUL, 0x99b25afdUL, 0xb29f093eUL, 0xab84387fUL, 0x2c1c24b0UL,
  75895. 0x350715f1UL, 0x1e2a4632UL, 0x07317773UL, 0x4870e1b4UL, 0x516bd0f5UL,
  75896. 0x7a468336UL, 0x635db277UL, 0xcbfad74eUL, 0xd2e1e60fUL, 0xf9ccb5ccUL,
  75897. 0xe0d7848dUL, 0xaf96124aUL, 0xb68d230bUL, 0x9da070c8UL, 0x84bb4189UL,
  75898. 0x03235d46UL, 0x1a386c07UL, 0x31153fc4UL, 0x280e0e85UL, 0x674f9842UL,
  75899. 0x7e54a903UL, 0x5579fac0UL, 0x4c62cb81UL, 0x8138c51fUL, 0x9823f45eUL,
  75900. 0xb30ea79dUL, 0xaa1596dcUL, 0xe554001bUL, 0xfc4f315aUL, 0xd7626299UL,
  75901. 0xce7953d8UL, 0x49e14f17UL, 0x50fa7e56UL, 0x7bd72d95UL, 0x62cc1cd4UL,
  75902. 0x2d8d8a13UL, 0x3496bb52UL, 0x1fbbe891UL, 0x06a0d9d0UL, 0x5e7ef3ecUL,
  75903. 0x4765c2adUL, 0x6c48916eUL, 0x7553a02fUL, 0x3a1236e8UL, 0x230907a9UL,
  75904. 0x0824546aUL, 0x113f652bUL, 0x96a779e4UL, 0x8fbc48a5UL, 0xa4911b66UL,
  75905. 0xbd8a2a27UL, 0xf2cbbce0UL, 0xebd08da1UL, 0xc0fdde62UL, 0xd9e6ef23UL,
  75906. 0x14bce1bdUL, 0x0da7d0fcUL, 0x268a833fUL, 0x3f91b27eUL, 0x70d024b9UL,
  75907. 0x69cb15f8UL, 0x42e6463bUL, 0x5bfd777aUL, 0xdc656bb5UL, 0xc57e5af4UL,
  75908. 0xee530937UL, 0xf7483876UL, 0xb809aeb1UL, 0xa1129ff0UL, 0x8a3fcc33UL,
  75909. 0x9324fd72UL
  75910. },
  75911. {
  75912. 0x00000000UL, 0x01c26a37UL, 0x0384d46eUL, 0x0246be59UL, 0x0709a8dcUL,
  75913. 0x06cbc2ebUL, 0x048d7cb2UL, 0x054f1685UL, 0x0e1351b8UL, 0x0fd13b8fUL,
  75914. 0x0d9785d6UL, 0x0c55efe1UL, 0x091af964UL, 0x08d89353UL, 0x0a9e2d0aUL,
  75915. 0x0b5c473dUL, 0x1c26a370UL, 0x1de4c947UL, 0x1fa2771eUL, 0x1e601d29UL,
  75916. 0x1b2f0bacUL, 0x1aed619bUL, 0x18abdfc2UL, 0x1969b5f5UL, 0x1235f2c8UL,
  75917. 0x13f798ffUL, 0x11b126a6UL, 0x10734c91UL, 0x153c5a14UL, 0x14fe3023UL,
  75918. 0x16b88e7aUL, 0x177ae44dUL, 0x384d46e0UL, 0x398f2cd7UL, 0x3bc9928eUL,
  75919. 0x3a0bf8b9UL, 0x3f44ee3cUL, 0x3e86840bUL, 0x3cc03a52UL, 0x3d025065UL,
  75920. 0x365e1758UL, 0x379c7d6fUL, 0x35dac336UL, 0x3418a901UL, 0x3157bf84UL,
  75921. 0x3095d5b3UL, 0x32d36beaUL, 0x331101ddUL, 0x246be590UL, 0x25a98fa7UL,
  75922. 0x27ef31feUL, 0x262d5bc9UL, 0x23624d4cUL, 0x22a0277bUL, 0x20e69922UL,
  75923. 0x2124f315UL, 0x2a78b428UL, 0x2bbade1fUL, 0x29fc6046UL, 0x283e0a71UL,
  75924. 0x2d711cf4UL, 0x2cb376c3UL, 0x2ef5c89aUL, 0x2f37a2adUL, 0x709a8dc0UL,
  75925. 0x7158e7f7UL, 0x731e59aeUL, 0x72dc3399UL, 0x7793251cUL, 0x76514f2bUL,
  75926. 0x7417f172UL, 0x75d59b45UL, 0x7e89dc78UL, 0x7f4bb64fUL, 0x7d0d0816UL,
  75927. 0x7ccf6221UL, 0x798074a4UL, 0x78421e93UL, 0x7a04a0caUL, 0x7bc6cafdUL,
  75928. 0x6cbc2eb0UL, 0x6d7e4487UL, 0x6f38fadeUL, 0x6efa90e9UL, 0x6bb5866cUL,
  75929. 0x6a77ec5bUL, 0x68315202UL, 0x69f33835UL, 0x62af7f08UL, 0x636d153fUL,
  75930. 0x612bab66UL, 0x60e9c151UL, 0x65a6d7d4UL, 0x6464bde3UL, 0x662203baUL,
  75931. 0x67e0698dUL, 0x48d7cb20UL, 0x4915a117UL, 0x4b531f4eUL, 0x4a917579UL,
  75932. 0x4fde63fcUL, 0x4e1c09cbUL, 0x4c5ab792UL, 0x4d98dda5UL, 0x46c49a98UL,
  75933. 0x4706f0afUL, 0x45404ef6UL, 0x448224c1UL, 0x41cd3244UL, 0x400f5873UL,
  75934. 0x4249e62aUL, 0x438b8c1dUL, 0x54f16850UL, 0x55330267UL, 0x5775bc3eUL,
  75935. 0x56b7d609UL, 0x53f8c08cUL, 0x523aaabbUL, 0x507c14e2UL, 0x51be7ed5UL,
  75936. 0x5ae239e8UL, 0x5b2053dfUL, 0x5966ed86UL, 0x58a487b1UL, 0x5deb9134UL,
  75937. 0x5c29fb03UL, 0x5e6f455aUL, 0x5fad2f6dUL, 0xe1351b80UL, 0xe0f771b7UL,
  75938. 0xe2b1cfeeUL, 0xe373a5d9UL, 0xe63cb35cUL, 0xe7fed96bUL, 0xe5b86732UL,
  75939. 0xe47a0d05UL, 0xef264a38UL, 0xeee4200fUL, 0xeca29e56UL, 0xed60f461UL,
  75940. 0xe82fe2e4UL, 0xe9ed88d3UL, 0xebab368aUL, 0xea695cbdUL, 0xfd13b8f0UL,
  75941. 0xfcd1d2c7UL, 0xfe976c9eUL, 0xff5506a9UL, 0xfa1a102cUL, 0xfbd87a1bUL,
  75942. 0xf99ec442UL, 0xf85cae75UL, 0xf300e948UL, 0xf2c2837fUL, 0xf0843d26UL,
  75943. 0xf1465711UL, 0xf4094194UL, 0xf5cb2ba3UL, 0xf78d95faUL, 0xf64fffcdUL,
  75944. 0xd9785d60UL, 0xd8ba3757UL, 0xdafc890eUL, 0xdb3ee339UL, 0xde71f5bcUL,
  75945. 0xdfb39f8bUL, 0xddf521d2UL, 0xdc374be5UL, 0xd76b0cd8UL, 0xd6a966efUL,
  75946. 0xd4efd8b6UL, 0xd52db281UL, 0xd062a404UL, 0xd1a0ce33UL, 0xd3e6706aUL,
  75947. 0xd2241a5dUL, 0xc55efe10UL, 0xc49c9427UL, 0xc6da2a7eUL, 0xc7184049UL,
  75948. 0xc25756ccUL, 0xc3953cfbUL, 0xc1d382a2UL, 0xc011e895UL, 0xcb4dafa8UL,
  75949. 0xca8fc59fUL, 0xc8c97bc6UL, 0xc90b11f1UL, 0xcc440774UL, 0xcd866d43UL,
  75950. 0xcfc0d31aUL, 0xce02b92dUL, 0x91af9640UL, 0x906dfc77UL, 0x922b422eUL,
  75951. 0x93e92819UL, 0x96a63e9cUL, 0x976454abUL, 0x9522eaf2UL, 0x94e080c5UL,
  75952. 0x9fbcc7f8UL, 0x9e7eadcfUL, 0x9c381396UL, 0x9dfa79a1UL, 0x98b56f24UL,
  75953. 0x99770513UL, 0x9b31bb4aUL, 0x9af3d17dUL, 0x8d893530UL, 0x8c4b5f07UL,
  75954. 0x8e0de15eUL, 0x8fcf8b69UL, 0x8a809decUL, 0x8b42f7dbUL, 0x89044982UL,
  75955. 0x88c623b5UL, 0x839a6488UL, 0x82580ebfUL, 0x801eb0e6UL, 0x81dcdad1UL,
  75956. 0x8493cc54UL, 0x8551a663UL, 0x8717183aUL, 0x86d5720dUL, 0xa9e2d0a0UL,
  75957. 0xa820ba97UL, 0xaa6604ceUL, 0xaba46ef9UL, 0xaeeb787cUL, 0xaf29124bUL,
  75958. 0xad6fac12UL, 0xacadc625UL, 0xa7f18118UL, 0xa633eb2fUL, 0xa4755576UL,
  75959. 0xa5b73f41UL, 0xa0f829c4UL, 0xa13a43f3UL, 0xa37cfdaaUL, 0xa2be979dUL,
  75960. 0xb5c473d0UL, 0xb40619e7UL, 0xb640a7beUL, 0xb782cd89UL, 0xb2cddb0cUL,
  75961. 0xb30fb13bUL, 0xb1490f62UL, 0xb08b6555UL, 0xbbd72268UL, 0xba15485fUL,
  75962. 0xb853f606UL, 0xb9919c31UL, 0xbcde8ab4UL, 0xbd1ce083UL, 0xbf5a5edaUL,
  75963. 0xbe9834edUL
  75964. },
  75965. {
  75966. 0x00000000UL, 0xb8bc6765UL, 0xaa09c88bUL, 0x12b5afeeUL, 0x8f629757UL,
  75967. 0x37def032UL, 0x256b5fdcUL, 0x9dd738b9UL, 0xc5b428efUL, 0x7d084f8aUL,
  75968. 0x6fbde064UL, 0xd7018701UL, 0x4ad6bfb8UL, 0xf26ad8ddUL, 0xe0df7733UL,
  75969. 0x58631056UL, 0x5019579fUL, 0xe8a530faUL, 0xfa109f14UL, 0x42acf871UL,
  75970. 0xdf7bc0c8UL, 0x67c7a7adUL, 0x75720843UL, 0xcdce6f26UL, 0x95ad7f70UL,
  75971. 0x2d111815UL, 0x3fa4b7fbUL, 0x8718d09eUL, 0x1acfe827UL, 0xa2738f42UL,
  75972. 0xb0c620acUL, 0x087a47c9UL, 0xa032af3eUL, 0x188ec85bUL, 0x0a3b67b5UL,
  75973. 0xb28700d0UL, 0x2f503869UL, 0x97ec5f0cUL, 0x8559f0e2UL, 0x3de59787UL,
  75974. 0x658687d1UL, 0xdd3ae0b4UL, 0xcf8f4f5aUL, 0x7733283fUL, 0xeae41086UL,
  75975. 0x525877e3UL, 0x40edd80dUL, 0xf851bf68UL, 0xf02bf8a1UL, 0x48979fc4UL,
  75976. 0x5a22302aUL, 0xe29e574fUL, 0x7f496ff6UL, 0xc7f50893UL, 0xd540a77dUL,
  75977. 0x6dfcc018UL, 0x359fd04eUL, 0x8d23b72bUL, 0x9f9618c5UL, 0x272a7fa0UL,
  75978. 0xbafd4719UL, 0x0241207cUL, 0x10f48f92UL, 0xa848e8f7UL, 0x9b14583dUL,
  75979. 0x23a83f58UL, 0x311d90b6UL, 0x89a1f7d3UL, 0x1476cf6aUL, 0xaccaa80fUL,
  75980. 0xbe7f07e1UL, 0x06c36084UL, 0x5ea070d2UL, 0xe61c17b7UL, 0xf4a9b859UL,
  75981. 0x4c15df3cUL, 0xd1c2e785UL, 0x697e80e0UL, 0x7bcb2f0eUL, 0xc377486bUL,
  75982. 0xcb0d0fa2UL, 0x73b168c7UL, 0x6104c729UL, 0xd9b8a04cUL, 0x446f98f5UL,
  75983. 0xfcd3ff90UL, 0xee66507eUL, 0x56da371bUL, 0x0eb9274dUL, 0xb6054028UL,
  75984. 0xa4b0efc6UL, 0x1c0c88a3UL, 0x81dbb01aUL, 0x3967d77fUL, 0x2bd27891UL,
  75985. 0x936e1ff4UL, 0x3b26f703UL, 0x839a9066UL, 0x912f3f88UL, 0x299358edUL,
  75986. 0xb4446054UL, 0x0cf80731UL, 0x1e4da8dfUL, 0xa6f1cfbaUL, 0xfe92dfecUL,
  75987. 0x462eb889UL, 0x549b1767UL, 0xec277002UL, 0x71f048bbUL, 0xc94c2fdeUL,
  75988. 0xdbf98030UL, 0x6345e755UL, 0x6b3fa09cUL, 0xd383c7f9UL, 0xc1366817UL,
  75989. 0x798a0f72UL, 0xe45d37cbUL, 0x5ce150aeUL, 0x4e54ff40UL, 0xf6e89825UL,
  75990. 0xae8b8873UL, 0x1637ef16UL, 0x048240f8UL, 0xbc3e279dUL, 0x21e91f24UL,
  75991. 0x99557841UL, 0x8be0d7afUL, 0x335cb0caUL, 0xed59b63bUL, 0x55e5d15eUL,
  75992. 0x47507eb0UL, 0xffec19d5UL, 0x623b216cUL, 0xda874609UL, 0xc832e9e7UL,
  75993. 0x708e8e82UL, 0x28ed9ed4UL, 0x9051f9b1UL, 0x82e4565fUL, 0x3a58313aUL,
  75994. 0xa78f0983UL, 0x1f336ee6UL, 0x0d86c108UL, 0xb53aa66dUL, 0xbd40e1a4UL,
  75995. 0x05fc86c1UL, 0x1749292fUL, 0xaff54e4aUL, 0x322276f3UL, 0x8a9e1196UL,
  75996. 0x982bbe78UL, 0x2097d91dUL, 0x78f4c94bUL, 0xc048ae2eUL, 0xd2fd01c0UL,
  75997. 0x6a4166a5UL, 0xf7965e1cUL, 0x4f2a3979UL, 0x5d9f9697UL, 0xe523f1f2UL,
  75998. 0x4d6b1905UL, 0xf5d77e60UL, 0xe762d18eUL, 0x5fdeb6ebUL, 0xc2098e52UL,
  75999. 0x7ab5e937UL, 0x680046d9UL, 0xd0bc21bcUL, 0x88df31eaUL, 0x3063568fUL,
  76000. 0x22d6f961UL, 0x9a6a9e04UL, 0x07bda6bdUL, 0xbf01c1d8UL, 0xadb46e36UL,
  76001. 0x15080953UL, 0x1d724e9aUL, 0xa5ce29ffUL, 0xb77b8611UL, 0x0fc7e174UL,
  76002. 0x9210d9cdUL, 0x2aacbea8UL, 0x38191146UL, 0x80a57623UL, 0xd8c66675UL,
  76003. 0x607a0110UL, 0x72cfaefeUL, 0xca73c99bUL, 0x57a4f122UL, 0xef189647UL,
  76004. 0xfdad39a9UL, 0x45115eccUL, 0x764dee06UL, 0xcef18963UL, 0xdc44268dUL,
  76005. 0x64f841e8UL, 0xf92f7951UL, 0x41931e34UL, 0x5326b1daUL, 0xeb9ad6bfUL,
  76006. 0xb3f9c6e9UL, 0x0b45a18cUL, 0x19f00e62UL, 0xa14c6907UL, 0x3c9b51beUL,
  76007. 0x842736dbUL, 0x96929935UL, 0x2e2efe50UL, 0x2654b999UL, 0x9ee8defcUL,
  76008. 0x8c5d7112UL, 0x34e11677UL, 0xa9362eceUL, 0x118a49abUL, 0x033fe645UL,
  76009. 0xbb838120UL, 0xe3e09176UL, 0x5b5cf613UL, 0x49e959fdUL, 0xf1553e98UL,
  76010. 0x6c820621UL, 0xd43e6144UL, 0xc68bceaaUL, 0x7e37a9cfUL, 0xd67f4138UL,
  76011. 0x6ec3265dUL, 0x7c7689b3UL, 0xc4caeed6UL, 0x591dd66fUL, 0xe1a1b10aUL,
  76012. 0xf3141ee4UL, 0x4ba87981UL, 0x13cb69d7UL, 0xab770eb2UL, 0xb9c2a15cUL,
  76013. 0x017ec639UL, 0x9ca9fe80UL, 0x241599e5UL, 0x36a0360bUL, 0x8e1c516eUL,
  76014. 0x866616a7UL, 0x3eda71c2UL, 0x2c6fde2cUL, 0x94d3b949UL, 0x090481f0UL,
  76015. 0xb1b8e695UL, 0xa30d497bUL, 0x1bb12e1eUL, 0x43d23e48UL, 0xfb6e592dUL,
  76016. 0xe9dbf6c3UL, 0x516791a6UL, 0xccb0a91fUL, 0x740cce7aUL, 0x66b96194UL,
  76017. 0xde0506f1UL
  76018. },
  76019. {
  76020. 0x00000000UL, 0x96300777UL, 0x2c610eeeUL, 0xba510999UL, 0x19c46d07UL,
  76021. 0x8ff46a70UL, 0x35a563e9UL, 0xa395649eUL, 0x3288db0eUL, 0xa4b8dc79UL,
  76022. 0x1ee9d5e0UL, 0x88d9d297UL, 0x2b4cb609UL, 0xbd7cb17eUL, 0x072db8e7UL,
  76023. 0x911dbf90UL, 0x6410b71dUL, 0xf220b06aUL, 0x4871b9f3UL, 0xde41be84UL,
  76024. 0x7dd4da1aUL, 0xebe4dd6dUL, 0x51b5d4f4UL, 0xc785d383UL, 0x56986c13UL,
  76025. 0xc0a86b64UL, 0x7af962fdUL, 0xecc9658aUL, 0x4f5c0114UL, 0xd96c0663UL,
  76026. 0x633d0ffaUL, 0xf50d088dUL, 0xc8206e3bUL, 0x5e10694cUL, 0xe44160d5UL,
  76027. 0x727167a2UL, 0xd1e4033cUL, 0x47d4044bUL, 0xfd850dd2UL, 0x6bb50aa5UL,
  76028. 0xfaa8b535UL, 0x6c98b242UL, 0xd6c9bbdbUL, 0x40f9bcacUL, 0xe36cd832UL,
  76029. 0x755cdf45UL, 0xcf0dd6dcUL, 0x593dd1abUL, 0xac30d926UL, 0x3a00de51UL,
  76030. 0x8051d7c8UL, 0x1661d0bfUL, 0xb5f4b421UL, 0x23c4b356UL, 0x9995bacfUL,
  76031. 0x0fa5bdb8UL, 0x9eb80228UL, 0x0888055fUL, 0xb2d90cc6UL, 0x24e90bb1UL,
  76032. 0x877c6f2fUL, 0x114c6858UL, 0xab1d61c1UL, 0x3d2d66b6UL, 0x9041dc76UL,
  76033. 0x0671db01UL, 0xbc20d298UL, 0x2a10d5efUL, 0x8985b171UL, 0x1fb5b606UL,
  76034. 0xa5e4bf9fUL, 0x33d4b8e8UL, 0xa2c90778UL, 0x34f9000fUL, 0x8ea80996UL,
  76035. 0x18980ee1UL, 0xbb0d6a7fUL, 0x2d3d6d08UL, 0x976c6491UL, 0x015c63e6UL,
  76036. 0xf4516b6bUL, 0x62616c1cUL, 0xd8306585UL, 0x4e0062f2UL, 0xed95066cUL,
  76037. 0x7ba5011bUL, 0xc1f40882UL, 0x57c40ff5UL, 0xc6d9b065UL, 0x50e9b712UL,
  76038. 0xeab8be8bUL, 0x7c88b9fcUL, 0xdf1ddd62UL, 0x492dda15UL, 0xf37cd38cUL,
  76039. 0x654cd4fbUL, 0x5861b24dUL, 0xce51b53aUL, 0x7400bca3UL, 0xe230bbd4UL,
  76040. 0x41a5df4aUL, 0xd795d83dUL, 0x6dc4d1a4UL, 0xfbf4d6d3UL, 0x6ae96943UL,
  76041. 0xfcd96e34UL, 0x468867adUL, 0xd0b860daUL, 0x732d0444UL, 0xe51d0333UL,
  76042. 0x5f4c0aaaUL, 0xc97c0dddUL, 0x3c710550UL, 0xaa410227UL, 0x10100bbeUL,
  76043. 0x86200cc9UL, 0x25b56857UL, 0xb3856f20UL, 0x09d466b9UL, 0x9fe461ceUL,
  76044. 0x0ef9de5eUL, 0x98c9d929UL, 0x2298d0b0UL, 0xb4a8d7c7UL, 0x173db359UL,
  76045. 0x810db42eUL, 0x3b5cbdb7UL, 0xad6cbac0UL, 0x2083b8edUL, 0xb6b3bf9aUL,
  76046. 0x0ce2b603UL, 0x9ad2b174UL, 0x3947d5eaUL, 0xaf77d29dUL, 0x1526db04UL,
  76047. 0x8316dc73UL, 0x120b63e3UL, 0x843b6494UL, 0x3e6a6d0dUL, 0xa85a6a7aUL,
  76048. 0x0bcf0ee4UL, 0x9dff0993UL, 0x27ae000aUL, 0xb19e077dUL, 0x44930ff0UL,
  76049. 0xd2a30887UL, 0x68f2011eUL, 0xfec20669UL, 0x5d5762f7UL, 0xcb676580UL,
  76050. 0x71366c19UL, 0xe7066b6eUL, 0x761bd4feUL, 0xe02bd389UL, 0x5a7ada10UL,
  76051. 0xcc4add67UL, 0x6fdfb9f9UL, 0xf9efbe8eUL, 0x43beb717UL, 0xd58eb060UL,
  76052. 0xe8a3d6d6UL, 0x7e93d1a1UL, 0xc4c2d838UL, 0x52f2df4fUL, 0xf167bbd1UL,
  76053. 0x6757bca6UL, 0xdd06b53fUL, 0x4b36b248UL, 0xda2b0dd8UL, 0x4c1b0aafUL,
  76054. 0xf64a0336UL, 0x607a0441UL, 0xc3ef60dfUL, 0x55df67a8UL, 0xef8e6e31UL,
  76055. 0x79be6946UL, 0x8cb361cbUL, 0x1a8366bcUL, 0xa0d26f25UL, 0x36e26852UL,
  76056. 0x95770cccUL, 0x03470bbbUL, 0xb9160222UL, 0x2f260555UL, 0xbe3bbac5UL,
  76057. 0x280bbdb2UL, 0x925ab42bUL, 0x046ab35cUL, 0xa7ffd7c2UL, 0x31cfd0b5UL,
  76058. 0x8b9ed92cUL, 0x1daede5bUL, 0xb0c2649bUL, 0x26f263ecUL, 0x9ca36a75UL,
  76059. 0x0a936d02UL, 0xa906099cUL, 0x3f360eebUL, 0x85670772UL, 0x13570005UL,
  76060. 0x824abf95UL, 0x147ab8e2UL, 0xae2bb17bUL, 0x381bb60cUL, 0x9b8ed292UL,
  76061. 0x0dbed5e5UL, 0xb7efdc7cUL, 0x21dfdb0bUL, 0xd4d2d386UL, 0x42e2d4f1UL,
  76062. 0xf8b3dd68UL, 0x6e83da1fUL, 0xcd16be81UL, 0x5b26b9f6UL, 0xe177b06fUL,
  76063. 0x7747b718UL, 0xe65a0888UL, 0x706a0fffUL, 0xca3b0666UL, 0x5c0b0111UL,
  76064. 0xff9e658fUL, 0x69ae62f8UL, 0xd3ff6b61UL, 0x45cf6c16UL, 0x78e20aa0UL,
  76065. 0xeed20dd7UL, 0x5483044eUL, 0xc2b30339UL, 0x612667a7UL, 0xf71660d0UL,
  76066. 0x4d476949UL, 0xdb776e3eUL, 0x4a6ad1aeUL, 0xdc5ad6d9UL, 0x660bdf40UL,
  76067. 0xf03bd837UL, 0x53aebca9UL, 0xc59ebbdeUL, 0x7fcfb247UL, 0xe9ffb530UL,
  76068. 0x1cf2bdbdUL, 0x8ac2bacaUL, 0x3093b353UL, 0xa6a3b424UL, 0x0536d0baUL,
  76069. 0x9306d7cdUL, 0x2957de54UL, 0xbf67d923UL, 0x2e7a66b3UL, 0xb84a61c4UL,
  76070. 0x021b685dUL, 0x942b6f2aUL, 0x37be0bb4UL, 0xa18e0cc3UL, 0x1bdf055aUL,
  76071. 0x8def022dUL
  76072. },
  76073. {
  76074. 0x00000000UL, 0x41311b19UL, 0x82623632UL, 0xc3532d2bUL, 0x04c56c64UL,
  76075. 0x45f4777dUL, 0x86a75a56UL, 0xc796414fUL, 0x088ad9c8UL, 0x49bbc2d1UL,
  76076. 0x8ae8effaUL, 0xcbd9f4e3UL, 0x0c4fb5acUL, 0x4d7eaeb5UL, 0x8e2d839eUL,
  76077. 0xcf1c9887UL, 0x5112c24aUL, 0x1023d953UL, 0xd370f478UL, 0x9241ef61UL,
  76078. 0x55d7ae2eUL, 0x14e6b537UL, 0xd7b5981cUL, 0x96848305UL, 0x59981b82UL,
  76079. 0x18a9009bUL, 0xdbfa2db0UL, 0x9acb36a9UL, 0x5d5d77e6UL, 0x1c6c6cffUL,
  76080. 0xdf3f41d4UL, 0x9e0e5acdUL, 0xa2248495UL, 0xe3159f8cUL, 0x2046b2a7UL,
  76081. 0x6177a9beUL, 0xa6e1e8f1UL, 0xe7d0f3e8UL, 0x2483dec3UL, 0x65b2c5daUL,
  76082. 0xaaae5d5dUL, 0xeb9f4644UL, 0x28cc6b6fUL, 0x69fd7076UL, 0xae6b3139UL,
  76083. 0xef5a2a20UL, 0x2c09070bUL, 0x6d381c12UL, 0xf33646dfUL, 0xb2075dc6UL,
  76084. 0x715470edUL, 0x30656bf4UL, 0xf7f32abbUL, 0xb6c231a2UL, 0x75911c89UL,
  76085. 0x34a00790UL, 0xfbbc9f17UL, 0xba8d840eUL, 0x79dea925UL, 0x38efb23cUL,
  76086. 0xff79f373UL, 0xbe48e86aUL, 0x7d1bc541UL, 0x3c2ade58UL, 0x054f79f0UL,
  76087. 0x447e62e9UL, 0x872d4fc2UL, 0xc61c54dbUL, 0x018a1594UL, 0x40bb0e8dUL,
  76088. 0x83e823a6UL, 0xc2d938bfUL, 0x0dc5a038UL, 0x4cf4bb21UL, 0x8fa7960aUL,
  76089. 0xce968d13UL, 0x0900cc5cUL, 0x4831d745UL, 0x8b62fa6eUL, 0xca53e177UL,
  76090. 0x545dbbbaUL, 0x156ca0a3UL, 0xd63f8d88UL, 0x970e9691UL, 0x5098d7deUL,
  76091. 0x11a9ccc7UL, 0xd2fae1ecUL, 0x93cbfaf5UL, 0x5cd76272UL, 0x1de6796bUL,
  76092. 0xdeb55440UL, 0x9f844f59UL, 0x58120e16UL, 0x1923150fUL, 0xda703824UL,
  76093. 0x9b41233dUL, 0xa76bfd65UL, 0xe65ae67cUL, 0x2509cb57UL, 0x6438d04eUL,
  76094. 0xa3ae9101UL, 0xe29f8a18UL, 0x21cca733UL, 0x60fdbc2aUL, 0xafe124adUL,
  76095. 0xeed03fb4UL, 0x2d83129fUL, 0x6cb20986UL, 0xab2448c9UL, 0xea1553d0UL,
  76096. 0x29467efbUL, 0x687765e2UL, 0xf6793f2fUL, 0xb7482436UL, 0x741b091dUL,
  76097. 0x352a1204UL, 0xf2bc534bUL, 0xb38d4852UL, 0x70de6579UL, 0x31ef7e60UL,
  76098. 0xfef3e6e7UL, 0xbfc2fdfeUL, 0x7c91d0d5UL, 0x3da0cbccUL, 0xfa368a83UL,
  76099. 0xbb07919aUL, 0x7854bcb1UL, 0x3965a7a8UL, 0x4b98833bUL, 0x0aa99822UL,
  76100. 0xc9fab509UL, 0x88cbae10UL, 0x4f5def5fUL, 0x0e6cf446UL, 0xcd3fd96dUL,
  76101. 0x8c0ec274UL, 0x43125af3UL, 0x022341eaUL, 0xc1706cc1UL, 0x804177d8UL,
  76102. 0x47d73697UL, 0x06e62d8eUL, 0xc5b500a5UL, 0x84841bbcUL, 0x1a8a4171UL,
  76103. 0x5bbb5a68UL, 0x98e87743UL, 0xd9d96c5aUL, 0x1e4f2d15UL, 0x5f7e360cUL,
  76104. 0x9c2d1b27UL, 0xdd1c003eUL, 0x120098b9UL, 0x533183a0UL, 0x9062ae8bUL,
  76105. 0xd153b592UL, 0x16c5f4ddUL, 0x57f4efc4UL, 0x94a7c2efUL, 0xd596d9f6UL,
  76106. 0xe9bc07aeUL, 0xa88d1cb7UL, 0x6bde319cUL, 0x2aef2a85UL, 0xed796bcaUL,
  76107. 0xac4870d3UL, 0x6f1b5df8UL, 0x2e2a46e1UL, 0xe136de66UL, 0xa007c57fUL,
  76108. 0x6354e854UL, 0x2265f34dUL, 0xe5f3b202UL, 0xa4c2a91bUL, 0x67918430UL,
  76109. 0x26a09f29UL, 0xb8aec5e4UL, 0xf99fdefdUL, 0x3accf3d6UL, 0x7bfde8cfUL,
  76110. 0xbc6ba980UL, 0xfd5ab299UL, 0x3e099fb2UL, 0x7f3884abUL, 0xb0241c2cUL,
  76111. 0xf1150735UL, 0x32462a1eUL, 0x73773107UL, 0xb4e17048UL, 0xf5d06b51UL,
  76112. 0x3683467aUL, 0x77b25d63UL, 0x4ed7facbUL, 0x0fe6e1d2UL, 0xccb5ccf9UL,
  76113. 0x8d84d7e0UL, 0x4a1296afUL, 0x0b238db6UL, 0xc870a09dUL, 0x8941bb84UL,
  76114. 0x465d2303UL, 0x076c381aUL, 0xc43f1531UL, 0x850e0e28UL, 0x42984f67UL,
  76115. 0x03a9547eUL, 0xc0fa7955UL, 0x81cb624cUL, 0x1fc53881UL, 0x5ef42398UL,
  76116. 0x9da70eb3UL, 0xdc9615aaUL, 0x1b0054e5UL, 0x5a314ffcUL, 0x996262d7UL,
  76117. 0xd85379ceUL, 0x174fe149UL, 0x567efa50UL, 0x952dd77bUL, 0xd41ccc62UL,
  76118. 0x138a8d2dUL, 0x52bb9634UL, 0x91e8bb1fUL, 0xd0d9a006UL, 0xecf37e5eUL,
  76119. 0xadc26547UL, 0x6e91486cUL, 0x2fa05375UL, 0xe836123aUL, 0xa9070923UL,
  76120. 0x6a542408UL, 0x2b653f11UL, 0xe479a796UL, 0xa548bc8fUL, 0x661b91a4UL,
  76121. 0x272a8abdUL, 0xe0bccbf2UL, 0xa18dd0ebUL, 0x62defdc0UL, 0x23efe6d9UL,
  76122. 0xbde1bc14UL, 0xfcd0a70dUL, 0x3f838a26UL, 0x7eb2913fUL, 0xb924d070UL,
  76123. 0xf815cb69UL, 0x3b46e642UL, 0x7a77fd5bUL, 0xb56b65dcUL, 0xf45a7ec5UL,
  76124. 0x370953eeUL, 0x763848f7UL, 0xb1ae09b8UL, 0xf09f12a1UL, 0x33cc3f8aUL,
  76125. 0x72fd2493UL
  76126. },
  76127. {
  76128. 0x00000000UL, 0x376ac201UL, 0x6ed48403UL, 0x59be4602UL, 0xdca80907UL,
  76129. 0xebc2cb06UL, 0xb27c8d04UL, 0x85164f05UL, 0xb851130eUL, 0x8f3bd10fUL,
  76130. 0xd685970dUL, 0xe1ef550cUL, 0x64f91a09UL, 0x5393d808UL, 0x0a2d9e0aUL,
  76131. 0x3d475c0bUL, 0x70a3261cUL, 0x47c9e41dUL, 0x1e77a21fUL, 0x291d601eUL,
  76132. 0xac0b2f1bUL, 0x9b61ed1aUL, 0xc2dfab18UL, 0xf5b56919UL, 0xc8f23512UL,
  76133. 0xff98f713UL, 0xa626b111UL, 0x914c7310UL, 0x145a3c15UL, 0x2330fe14UL,
  76134. 0x7a8eb816UL, 0x4de47a17UL, 0xe0464d38UL, 0xd72c8f39UL, 0x8e92c93bUL,
  76135. 0xb9f80b3aUL, 0x3cee443fUL, 0x0b84863eUL, 0x523ac03cUL, 0x6550023dUL,
  76136. 0x58175e36UL, 0x6f7d9c37UL, 0x36c3da35UL, 0x01a91834UL, 0x84bf5731UL,
  76137. 0xb3d59530UL, 0xea6bd332UL, 0xdd011133UL, 0x90e56b24UL, 0xa78fa925UL,
  76138. 0xfe31ef27UL, 0xc95b2d26UL, 0x4c4d6223UL, 0x7b27a022UL, 0x2299e620UL,
  76139. 0x15f32421UL, 0x28b4782aUL, 0x1fdeba2bUL, 0x4660fc29UL, 0x710a3e28UL,
  76140. 0xf41c712dUL, 0xc376b32cUL, 0x9ac8f52eUL, 0xada2372fUL, 0xc08d9a70UL,
  76141. 0xf7e75871UL, 0xae591e73UL, 0x9933dc72UL, 0x1c259377UL, 0x2b4f5176UL,
  76142. 0x72f11774UL, 0x459bd575UL, 0x78dc897eUL, 0x4fb64b7fUL, 0x16080d7dUL,
  76143. 0x2162cf7cUL, 0xa4748079UL, 0x931e4278UL, 0xcaa0047aUL, 0xfdcac67bUL,
  76144. 0xb02ebc6cUL, 0x87447e6dUL, 0xdefa386fUL, 0xe990fa6eUL, 0x6c86b56bUL,
  76145. 0x5bec776aUL, 0x02523168UL, 0x3538f369UL, 0x087faf62UL, 0x3f156d63UL,
  76146. 0x66ab2b61UL, 0x51c1e960UL, 0xd4d7a665UL, 0xe3bd6464UL, 0xba032266UL,
  76147. 0x8d69e067UL, 0x20cbd748UL, 0x17a11549UL, 0x4e1f534bUL, 0x7975914aUL,
  76148. 0xfc63de4fUL, 0xcb091c4eUL, 0x92b75a4cUL, 0xa5dd984dUL, 0x989ac446UL,
  76149. 0xaff00647UL, 0xf64e4045UL, 0xc1248244UL, 0x4432cd41UL, 0x73580f40UL,
  76150. 0x2ae64942UL, 0x1d8c8b43UL, 0x5068f154UL, 0x67023355UL, 0x3ebc7557UL,
  76151. 0x09d6b756UL, 0x8cc0f853UL, 0xbbaa3a52UL, 0xe2147c50UL, 0xd57ebe51UL,
  76152. 0xe839e25aUL, 0xdf53205bUL, 0x86ed6659UL, 0xb187a458UL, 0x3491eb5dUL,
  76153. 0x03fb295cUL, 0x5a456f5eUL, 0x6d2fad5fUL, 0x801b35e1UL, 0xb771f7e0UL,
  76154. 0xeecfb1e2UL, 0xd9a573e3UL, 0x5cb33ce6UL, 0x6bd9fee7UL, 0x3267b8e5UL,
  76155. 0x050d7ae4UL, 0x384a26efUL, 0x0f20e4eeUL, 0x569ea2ecUL, 0x61f460edUL,
  76156. 0xe4e22fe8UL, 0xd388ede9UL, 0x8a36abebUL, 0xbd5c69eaUL, 0xf0b813fdUL,
  76157. 0xc7d2d1fcUL, 0x9e6c97feUL, 0xa90655ffUL, 0x2c101afaUL, 0x1b7ad8fbUL,
  76158. 0x42c49ef9UL, 0x75ae5cf8UL, 0x48e900f3UL, 0x7f83c2f2UL, 0x263d84f0UL,
  76159. 0x115746f1UL, 0x944109f4UL, 0xa32bcbf5UL, 0xfa958df7UL, 0xcdff4ff6UL,
  76160. 0x605d78d9UL, 0x5737bad8UL, 0x0e89fcdaUL, 0x39e33edbUL, 0xbcf571deUL,
  76161. 0x8b9fb3dfUL, 0xd221f5ddUL, 0xe54b37dcUL, 0xd80c6bd7UL, 0xef66a9d6UL,
  76162. 0xb6d8efd4UL, 0x81b22dd5UL, 0x04a462d0UL, 0x33cea0d1UL, 0x6a70e6d3UL,
  76163. 0x5d1a24d2UL, 0x10fe5ec5UL, 0x27949cc4UL, 0x7e2adac6UL, 0x494018c7UL,
  76164. 0xcc5657c2UL, 0xfb3c95c3UL, 0xa282d3c1UL, 0x95e811c0UL, 0xa8af4dcbUL,
  76165. 0x9fc58fcaUL, 0xc67bc9c8UL, 0xf1110bc9UL, 0x740744ccUL, 0x436d86cdUL,
  76166. 0x1ad3c0cfUL, 0x2db902ceUL, 0x4096af91UL, 0x77fc6d90UL, 0x2e422b92UL,
  76167. 0x1928e993UL, 0x9c3ea696UL, 0xab546497UL, 0xf2ea2295UL, 0xc580e094UL,
  76168. 0xf8c7bc9fUL, 0xcfad7e9eUL, 0x9613389cUL, 0xa179fa9dUL, 0x246fb598UL,
  76169. 0x13057799UL, 0x4abb319bUL, 0x7dd1f39aUL, 0x3035898dUL, 0x075f4b8cUL,
  76170. 0x5ee10d8eUL, 0x698bcf8fUL, 0xec9d808aUL, 0xdbf7428bUL, 0x82490489UL,
  76171. 0xb523c688UL, 0x88649a83UL, 0xbf0e5882UL, 0xe6b01e80UL, 0xd1dadc81UL,
  76172. 0x54cc9384UL, 0x63a65185UL, 0x3a181787UL, 0x0d72d586UL, 0xa0d0e2a9UL,
  76173. 0x97ba20a8UL, 0xce0466aaUL, 0xf96ea4abUL, 0x7c78ebaeUL, 0x4b1229afUL,
  76174. 0x12ac6fadUL, 0x25c6adacUL, 0x1881f1a7UL, 0x2feb33a6UL, 0x765575a4UL,
  76175. 0x413fb7a5UL, 0xc429f8a0UL, 0xf3433aa1UL, 0xaafd7ca3UL, 0x9d97bea2UL,
  76176. 0xd073c4b5UL, 0xe71906b4UL, 0xbea740b6UL, 0x89cd82b7UL, 0x0cdbcdb2UL,
  76177. 0x3bb10fb3UL, 0x620f49b1UL, 0x55658bb0UL, 0x6822d7bbUL, 0x5f4815baUL,
  76178. 0x06f653b8UL, 0x319c91b9UL, 0xb48adebcUL, 0x83e01cbdUL, 0xda5e5abfUL,
  76179. 0xed3498beUL
  76180. },
  76181. {
  76182. 0x00000000UL, 0x6567bcb8UL, 0x8bc809aaUL, 0xeeafb512UL, 0x5797628fUL,
  76183. 0x32f0de37UL, 0xdc5f6b25UL, 0xb938d79dUL, 0xef28b4c5UL, 0x8a4f087dUL,
  76184. 0x64e0bd6fUL, 0x018701d7UL, 0xb8bfd64aUL, 0xddd86af2UL, 0x3377dfe0UL,
  76185. 0x56106358UL, 0x9f571950UL, 0xfa30a5e8UL, 0x149f10faUL, 0x71f8ac42UL,
  76186. 0xc8c07bdfUL, 0xada7c767UL, 0x43087275UL, 0x266fcecdUL, 0x707fad95UL,
  76187. 0x1518112dUL, 0xfbb7a43fUL, 0x9ed01887UL, 0x27e8cf1aUL, 0x428f73a2UL,
  76188. 0xac20c6b0UL, 0xc9477a08UL, 0x3eaf32a0UL, 0x5bc88e18UL, 0xb5673b0aUL,
  76189. 0xd00087b2UL, 0x6938502fUL, 0x0c5fec97UL, 0xe2f05985UL, 0x8797e53dUL,
  76190. 0xd1878665UL, 0xb4e03addUL, 0x5a4f8fcfUL, 0x3f283377UL, 0x8610e4eaUL,
  76191. 0xe3775852UL, 0x0dd8ed40UL, 0x68bf51f8UL, 0xa1f82bf0UL, 0xc49f9748UL,
  76192. 0x2a30225aUL, 0x4f579ee2UL, 0xf66f497fUL, 0x9308f5c7UL, 0x7da740d5UL,
  76193. 0x18c0fc6dUL, 0x4ed09f35UL, 0x2bb7238dUL, 0xc518969fUL, 0xa07f2a27UL,
  76194. 0x1947fdbaUL, 0x7c204102UL, 0x928ff410UL, 0xf7e848a8UL, 0x3d58149bUL,
  76195. 0x583fa823UL, 0xb6901d31UL, 0xd3f7a189UL, 0x6acf7614UL, 0x0fa8caacUL,
  76196. 0xe1077fbeUL, 0x8460c306UL, 0xd270a05eUL, 0xb7171ce6UL, 0x59b8a9f4UL,
  76197. 0x3cdf154cUL, 0x85e7c2d1UL, 0xe0807e69UL, 0x0e2fcb7bUL, 0x6b4877c3UL,
  76198. 0xa20f0dcbUL, 0xc768b173UL, 0x29c70461UL, 0x4ca0b8d9UL, 0xf5986f44UL,
  76199. 0x90ffd3fcUL, 0x7e5066eeUL, 0x1b37da56UL, 0x4d27b90eUL, 0x284005b6UL,
  76200. 0xc6efb0a4UL, 0xa3880c1cUL, 0x1ab0db81UL, 0x7fd76739UL, 0x9178d22bUL,
  76201. 0xf41f6e93UL, 0x03f7263bUL, 0x66909a83UL, 0x883f2f91UL, 0xed589329UL,
  76202. 0x546044b4UL, 0x3107f80cUL, 0xdfa84d1eUL, 0xbacff1a6UL, 0xecdf92feUL,
  76203. 0x89b82e46UL, 0x67179b54UL, 0x027027ecUL, 0xbb48f071UL, 0xde2f4cc9UL,
  76204. 0x3080f9dbUL, 0x55e74563UL, 0x9ca03f6bUL, 0xf9c783d3UL, 0x176836c1UL,
  76205. 0x720f8a79UL, 0xcb375de4UL, 0xae50e15cUL, 0x40ff544eUL, 0x2598e8f6UL,
  76206. 0x73888baeUL, 0x16ef3716UL, 0xf8408204UL, 0x9d273ebcUL, 0x241fe921UL,
  76207. 0x41785599UL, 0xafd7e08bUL, 0xcab05c33UL, 0x3bb659edUL, 0x5ed1e555UL,
  76208. 0xb07e5047UL, 0xd519ecffUL, 0x6c213b62UL, 0x094687daUL, 0xe7e932c8UL,
  76209. 0x828e8e70UL, 0xd49eed28UL, 0xb1f95190UL, 0x5f56e482UL, 0x3a31583aUL,
  76210. 0x83098fa7UL, 0xe66e331fUL, 0x08c1860dUL, 0x6da63ab5UL, 0xa4e140bdUL,
  76211. 0xc186fc05UL, 0x2f294917UL, 0x4a4ef5afUL, 0xf3762232UL, 0x96119e8aUL,
  76212. 0x78be2b98UL, 0x1dd99720UL, 0x4bc9f478UL, 0x2eae48c0UL, 0xc001fdd2UL,
  76213. 0xa566416aUL, 0x1c5e96f7UL, 0x79392a4fUL, 0x97969f5dUL, 0xf2f123e5UL,
  76214. 0x05196b4dUL, 0x607ed7f5UL, 0x8ed162e7UL, 0xebb6de5fUL, 0x528e09c2UL,
  76215. 0x37e9b57aUL, 0xd9460068UL, 0xbc21bcd0UL, 0xea31df88UL, 0x8f566330UL,
  76216. 0x61f9d622UL, 0x049e6a9aUL, 0xbda6bd07UL, 0xd8c101bfUL, 0x366eb4adUL,
  76217. 0x53090815UL, 0x9a4e721dUL, 0xff29cea5UL, 0x11867bb7UL, 0x74e1c70fUL,
  76218. 0xcdd91092UL, 0xa8beac2aUL, 0x46111938UL, 0x2376a580UL, 0x7566c6d8UL,
  76219. 0x10017a60UL, 0xfeaecf72UL, 0x9bc973caUL, 0x22f1a457UL, 0x479618efUL,
  76220. 0xa939adfdUL, 0xcc5e1145UL, 0x06ee4d76UL, 0x6389f1ceUL, 0x8d2644dcUL,
  76221. 0xe841f864UL, 0x51792ff9UL, 0x341e9341UL, 0xdab12653UL, 0xbfd69aebUL,
  76222. 0xe9c6f9b3UL, 0x8ca1450bUL, 0x620ef019UL, 0x07694ca1UL, 0xbe519b3cUL,
  76223. 0xdb362784UL, 0x35999296UL, 0x50fe2e2eUL, 0x99b95426UL, 0xfcdee89eUL,
  76224. 0x12715d8cUL, 0x7716e134UL, 0xce2e36a9UL, 0xab498a11UL, 0x45e63f03UL,
  76225. 0x208183bbUL, 0x7691e0e3UL, 0x13f65c5bUL, 0xfd59e949UL, 0x983e55f1UL,
  76226. 0x2106826cUL, 0x44613ed4UL, 0xaace8bc6UL, 0xcfa9377eUL, 0x38417fd6UL,
  76227. 0x5d26c36eUL, 0xb389767cUL, 0xd6eecac4UL, 0x6fd61d59UL, 0x0ab1a1e1UL,
  76228. 0xe41e14f3UL, 0x8179a84bUL, 0xd769cb13UL, 0xb20e77abUL, 0x5ca1c2b9UL,
  76229. 0x39c67e01UL, 0x80fea99cUL, 0xe5991524UL, 0x0b36a036UL, 0x6e511c8eUL,
  76230. 0xa7166686UL, 0xc271da3eUL, 0x2cde6f2cUL, 0x49b9d394UL, 0xf0810409UL,
  76231. 0x95e6b8b1UL, 0x7b490da3UL, 0x1e2eb11bUL, 0x483ed243UL, 0x2d596efbUL,
  76232. 0xc3f6dbe9UL, 0xa6916751UL, 0x1fa9b0ccUL, 0x7ace0c74UL, 0x9461b966UL,
  76233. 0xf10605deUL
  76234. #endif
  76235. }
  76236. };
  76237. /********* End of inlined file: crc32.h *********/
  76238. #endif /* DYNAMIC_CRC_TABLE */
  76239. /* =========================================================================
  76240. * This function can be used by asm versions of crc32()
  76241. */
  76242. const unsigned long FAR * ZEXPORT get_crc_table()
  76243. {
  76244. #ifdef DYNAMIC_CRC_TABLE
  76245. if (crc_table_empty)
  76246. make_crc_table();
  76247. #endif /* DYNAMIC_CRC_TABLE */
  76248. return (const unsigned long FAR *)crc_table;
  76249. }
  76250. /* ========================================================================= */
  76251. #define DO1 crc = crc_table[0][((int)crc ^ (*buf++)) & 0xff] ^ (crc >> 8)
  76252. #define DO8 DO1; DO1; DO1; DO1; DO1; DO1; DO1; DO1
  76253. /* ========================================================================= */
  76254. unsigned long ZEXPORT crc32 (unsigned long crc, const unsigned char FAR *buf, unsigned len)
  76255. {
  76256. if (buf == Z_NULL) return 0UL;
  76257. #ifdef DYNAMIC_CRC_TABLE
  76258. if (crc_table_empty)
  76259. make_crc_table();
  76260. #endif /* DYNAMIC_CRC_TABLE */
  76261. #ifdef BYFOUR
  76262. if (sizeof(void *) == sizeof(ptrdiff_t)) {
  76263. u4 endian;
  76264. endian = 1;
  76265. if (*((unsigned char *)(&endian)))
  76266. return crc32_little(crc, buf, len);
  76267. else
  76268. return crc32_big(crc, buf, len);
  76269. }
  76270. #endif /* BYFOUR */
  76271. crc = crc ^ 0xffffffffUL;
  76272. while (len >= 8) {
  76273. DO8;
  76274. len -= 8;
  76275. }
  76276. if (len) do {
  76277. DO1;
  76278. } while (--len);
  76279. return crc ^ 0xffffffffUL;
  76280. }
  76281. #ifdef BYFOUR
  76282. /* ========================================================================= */
  76283. #define DOLIT4 c ^= *buf4++; \
  76284. c = crc_table[3][c & 0xff] ^ crc_table[2][(c >> 8) & 0xff] ^ \
  76285. crc_table[1][(c >> 16) & 0xff] ^ crc_table[0][c >> 24]
  76286. #define DOLIT32 DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4
  76287. /* ========================================================================= */
  76288. local unsigned long crc32_little(unsigned long crc, const unsigned char FAR *buf, unsigned len)
  76289. {
  76290. register u4 c;
  76291. register const u4 FAR *buf4;
  76292. c = (u4)crc;
  76293. c = ~c;
  76294. while (len && ((ptrdiff_t)buf & 3)) {
  76295. c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8);
  76296. len--;
  76297. }
  76298. buf4 = (const u4 FAR *)(const void FAR *)buf;
  76299. while (len >= 32) {
  76300. DOLIT32;
  76301. len -= 32;
  76302. }
  76303. while (len >= 4) {
  76304. DOLIT4;
  76305. len -= 4;
  76306. }
  76307. buf = (const unsigned char FAR *)buf4;
  76308. if (len) do {
  76309. c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8);
  76310. } while (--len);
  76311. c = ~c;
  76312. return (unsigned long)c;
  76313. }
  76314. /* ========================================================================= */
  76315. #define DOBIG4 c ^= *++buf4; \
  76316. c = crc_table[4][c & 0xff] ^ crc_table[5][(c >> 8) & 0xff] ^ \
  76317. crc_table[6][(c >> 16) & 0xff] ^ crc_table[7][c >> 24]
  76318. #define DOBIG32 DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4
  76319. /* ========================================================================= */
  76320. local unsigned long crc32_big (unsigned long crc, const unsigned char FAR *buf, unsigned len)
  76321. {
  76322. register u4 c;
  76323. register const u4 FAR *buf4;
  76324. c = REV((u4)crc);
  76325. c = ~c;
  76326. while (len && ((ptrdiff_t)buf & 3)) {
  76327. c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);
  76328. len--;
  76329. }
  76330. buf4 = (const u4 FAR *)(const void FAR *)buf;
  76331. buf4--;
  76332. while (len >= 32) {
  76333. DOBIG32;
  76334. len -= 32;
  76335. }
  76336. while (len >= 4) {
  76337. DOBIG4;
  76338. len -= 4;
  76339. }
  76340. buf4++;
  76341. buf = (const unsigned char FAR *)buf4;
  76342. if (len) do {
  76343. c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);
  76344. } while (--len);
  76345. c = ~c;
  76346. return (unsigned long)(REV(c));
  76347. }
  76348. #endif /* BYFOUR */
  76349. #define GF2_DIM 32 /* dimension of GF(2) vectors (length of CRC) */
  76350. /* ========================================================================= */
  76351. local unsigned long gf2_matrix_times (unsigned long *mat, unsigned long vec)
  76352. {
  76353. unsigned long sum;
  76354. sum = 0;
  76355. while (vec) {
  76356. if (vec & 1)
  76357. sum ^= *mat;
  76358. vec >>= 1;
  76359. mat++;
  76360. }
  76361. return sum;
  76362. }
  76363. /* ========================================================================= */
  76364. local void gf2_matrix_square (unsigned long *square, unsigned long *mat)
  76365. {
  76366. int n;
  76367. for (n = 0; n < GF2_DIM; n++)
  76368. square[n] = gf2_matrix_times(mat, mat[n]);
  76369. }
  76370. /* ========================================================================= */
  76371. uLong ZEXPORT crc32_combine (uLong crc1, uLong crc2, z_off_t len2)
  76372. {
  76373. int n;
  76374. unsigned long row;
  76375. unsigned long even[GF2_DIM]; /* even-power-of-two zeros operator */
  76376. unsigned long odd[GF2_DIM]; /* odd-power-of-two zeros operator */
  76377. /* degenerate case */
  76378. if (len2 == 0)
  76379. return crc1;
  76380. /* put operator for one zero bit in odd */
  76381. odd[0] = 0xedb88320L; /* CRC-32 polynomial */
  76382. row = 1;
  76383. for (n = 1; n < GF2_DIM; n++) {
  76384. odd[n] = row;
  76385. row <<= 1;
  76386. }
  76387. /* put operator for two zero bits in even */
  76388. gf2_matrix_square(even, odd);
  76389. /* put operator for four zero bits in odd */
  76390. gf2_matrix_square(odd, even);
  76391. /* apply len2 zeros to crc1 (first square will put the operator for one
  76392. zero byte, eight zero bits, in even) */
  76393. do {
  76394. /* apply zeros operator for this bit of len2 */
  76395. gf2_matrix_square(even, odd);
  76396. if (len2 & 1)
  76397. crc1 = gf2_matrix_times(even, crc1);
  76398. len2 >>= 1;
  76399. /* if no more bits set, then done */
  76400. if (len2 == 0)
  76401. break;
  76402. /* another iteration of the loop with odd and even swapped */
  76403. gf2_matrix_square(odd, even);
  76404. if (len2 & 1)
  76405. crc1 = gf2_matrix_times(odd, crc1);
  76406. len2 >>= 1;
  76407. /* if no more bits set, then done */
  76408. } while (len2 != 0);
  76409. /* return combined crc */
  76410. crc1 ^= crc2;
  76411. return crc1;
  76412. }
  76413. /********* End of inlined file: crc32.c *********/
  76414. /********* Start of inlined file: deflate.c *********/
  76415. /*
  76416. * ALGORITHM
  76417. *
  76418. * The "deflation" process depends on being able to identify portions
  76419. * of the input text which are identical to earlier input (within a
  76420. * sliding window trailing behind the input currently being processed).
  76421. *
  76422. * The most straightforward technique turns out to be the fastest for
  76423. * most input files: try all possible matches and select the longest.
  76424. * The key feature of this algorithm is that insertions into the string
  76425. * dictionary are very simple and thus fast, and deletions are avoided
  76426. * completely. Insertions are performed at each input character, whereas
  76427. * string matches are performed only when the previous match ends. So it
  76428. * is preferable to spend more time in matches to allow very fast string
  76429. * insertions and avoid deletions. The matching algorithm for small
  76430. * strings is inspired from that of Rabin & Karp. A brute force approach
  76431. * is used to find longer strings when a small match has been found.
  76432. * A similar algorithm is used in comic (by Jan-Mark Wams) and freeze
  76433. * (by Leonid Broukhis).
  76434. * A previous version of this file used a more sophisticated algorithm
  76435. * (by Fiala and Greene) which is guaranteed to run in linear amortized
  76436. * time, but has a larger average cost, uses more memory and is patented.
  76437. * However the F&G algorithm may be faster for some highly redundant
  76438. * files if the parameter max_chain_length (described below) is too large.
  76439. *
  76440. * ACKNOWLEDGEMENTS
  76441. *
  76442. * The idea of lazy evaluation of matches is due to Jan-Mark Wams, and
  76443. * I found it in 'freeze' written by Leonid Broukhis.
  76444. * Thanks to many people for bug reports and testing.
  76445. *
  76446. * REFERENCES
  76447. *
  76448. * Deutsch, L.P.,"DEFLATE Compressed Data Format Specification".
  76449. * Available in http://www.ietf.org/rfc/rfc1951.txt
  76450. *
  76451. * A description of the Rabin and Karp algorithm is given in the book
  76452. * "Algorithms" by R. Sedgewick, Addison-Wesley, p252.
  76453. *
  76454. * Fiala,E.R., and Greene,D.H.
  76455. * Data Compression with Finite Windows, Comm.ACM, 32,4 (1989) 490-595
  76456. *
  76457. */
  76458. /* @(#) $Id: deflate.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  76459. /********* Start of inlined file: deflate.h *********/
  76460. /* WARNING: this file should *not* be used by applications. It is
  76461. part of the implementation of the compression library and is
  76462. subject to change. Applications should only use zlib.h.
  76463. */
  76464. /* @(#) $Id: deflate.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  76465. #ifndef DEFLATE_H
  76466. #define DEFLATE_H
  76467. /* define NO_GZIP when compiling if you want to disable gzip header and
  76468. trailer creation by deflate(). NO_GZIP would be used to avoid linking in
  76469. the crc code when it is not needed. For shared libraries, gzip encoding
  76470. should be left enabled. */
  76471. #ifndef NO_GZIP
  76472. # define GZIP
  76473. #endif
  76474. #define NO_DUMMY_DECL
  76475. /* ===========================================================================
  76476. * Internal compression state.
  76477. */
  76478. #define LENGTH_CODES 29
  76479. /* number of length codes, not counting the special END_BLOCK code */
  76480. #define LITERALS 256
  76481. /* number of literal bytes 0..255 */
  76482. #define L_CODES (LITERALS+1+LENGTH_CODES)
  76483. /* number of Literal or Length codes, including the END_BLOCK code */
  76484. #define D_CODES 30
  76485. /* number of distance codes */
  76486. #define BL_CODES 19
  76487. /* number of codes used to transfer the bit lengths */
  76488. #define HEAP_SIZE (2*L_CODES+1)
  76489. /* maximum heap size */
  76490. #define MAX_BITS 15
  76491. /* All codes must not exceed MAX_BITS bits */
  76492. #define INIT_STATE 42
  76493. #define EXTRA_STATE 69
  76494. #define NAME_STATE 73
  76495. #define COMMENT_STATE 91
  76496. #define HCRC_STATE 103
  76497. #define BUSY_STATE 113
  76498. #define FINISH_STATE 666
  76499. /* Stream status */
  76500. /* Data structure describing a single value and its code string. */
  76501. typedef struct ct_data_s {
  76502. union {
  76503. ush freq; /* frequency count */
  76504. ush code; /* bit string */
  76505. } fc;
  76506. union {
  76507. ush dad; /* father node in Huffman tree */
  76508. ush len; /* length of bit string */
  76509. } dl;
  76510. } FAR ct_data;
  76511. #define Freq fc.freq
  76512. #define Code fc.code
  76513. #define Dad dl.dad
  76514. #define Len dl.len
  76515. typedef struct static_tree_desc_s static_tree_desc;
  76516. typedef struct tree_desc_s {
  76517. ct_data *dyn_tree; /* the dynamic tree */
  76518. int max_code; /* largest code with non zero frequency */
  76519. static_tree_desc *stat_desc; /* the corresponding static tree */
  76520. } FAR tree_desc;
  76521. typedef ush Pos;
  76522. typedef Pos FAR Posf;
  76523. typedef unsigned IPos;
  76524. /* A Pos is an index in the character window. We use short instead of int to
  76525. * save space in the various tables. IPos is used only for parameter passing.
  76526. */
  76527. typedef struct internal_state {
  76528. z_streamp strm; /* pointer back to this zlib stream */
  76529. int status; /* as the name implies */
  76530. Bytef *pending_buf; /* output still pending */
  76531. ulg pending_buf_size; /* size of pending_buf */
  76532. Bytef *pending_out; /* next pending byte to output to the stream */
  76533. uInt pending; /* nb of bytes in the pending buffer */
  76534. int wrap; /* bit 0 true for zlib, bit 1 true for gzip */
  76535. gz_headerp gzhead; /* gzip header information to write */
  76536. uInt gzindex; /* where in extra, name, or comment */
  76537. Byte method; /* STORED (for zip only) or DEFLATED */
  76538. int last_flush; /* value of flush param for previous deflate call */
  76539. /* used by deflate.c: */
  76540. uInt w_size; /* LZ77 window size (32K by default) */
  76541. uInt w_bits; /* log2(w_size) (8..16) */
  76542. uInt w_mask; /* w_size - 1 */
  76543. Bytef *window;
  76544. /* Sliding window. Input bytes are read into the second half of the window,
  76545. * and move to the first half later to keep a dictionary of at least wSize
  76546. * bytes. With this organization, matches are limited to a distance of
  76547. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  76548. * performed with a length multiple of the block size. Also, it limits
  76549. * the window size to 64K, which is quite useful on MSDOS.
  76550. * To do: use the user input buffer as sliding window.
  76551. */
  76552. ulg window_size;
  76553. /* Actual size of window: 2*wSize, except when the user input buffer
  76554. * is directly used as sliding window.
  76555. */
  76556. Posf *prev;
  76557. /* Link to older string with same hash index. To limit the size of this
  76558. * array to 64K, this link is maintained only for the last 32K strings.
  76559. * An index in this array is thus a window index modulo 32K.
  76560. */
  76561. Posf *head; /* Heads of the hash chains or NIL. */
  76562. uInt ins_h; /* hash index of string to be inserted */
  76563. uInt hash_size; /* number of elements in hash table */
  76564. uInt hash_bits; /* log2(hash_size) */
  76565. uInt hash_mask; /* hash_size-1 */
  76566. uInt hash_shift;
  76567. /* Number of bits by which ins_h must be shifted at each input
  76568. * step. It must be such that after MIN_MATCH steps, the oldest
  76569. * byte no longer takes part in the hash key, that is:
  76570. * hash_shift * MIN_MATCH >= hash_bits
  76571. */
  76572. long block_start;
  76573. /* Window position at the beginning of the current output block. Gets
  76574. * negative when the window is moved backwards.
  76575. */
  76576. uInt match_length; /* length of best match */
  76577. IPos prev_match; /* previous match */
  76578. int match_available; /* set if previous match exists */
  76579. uInt strstart; /* start of string to insert */
  76580. uInt match_start; /* start of matching string */
  76581. uInt lookahead; /* number of valid bytes ahead in window */
  76582. uInt prev_length;
  76583. /* Length of the best match at previous step. Matches not greater than this
  76584. * are discarded. This is used in the lazy match evaluation.
  76585. */
  76586. uInt max_chain_length;
  76587. /* To speed up deflation, hash chains are never searched beyond this
  76588. * length. A higher limit improves compression ratio but degrades the
  76589. * speed.
  76590. */
  76591. uInt max_lazy_match;
  76592. /* Attempt to find a better match only when the current match is strictly
  76593. * smaller than this value. This mechanism is used only for compression
  76594. * levels >= 4.
  76595. */
  76596. # define max_insert_length max_lazy_match
  76597. /* Insert new strings in the hash table only if the match length is not
  76598. * greater than this length. This saves time but degrades compression.
  76599. * max_insert_length is used only for compression levels <= 3.
  76600. */
  76601. int level; /* compression level (1..9) */
  76602. int strategy; /* favor or force Huffman coding*/
  76603. uInt good_match;
  76604. /* Use a faster search when the previous match is longer than this */
  76605. int nice_match; /* Stop searching when current match exceeds this */
  76606. /* used by trees.c: */
  76607. /* Didn't use ct_data typedef below to supress compiler warning */
  76608. struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  76609. struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  76610. struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  76611. struct tree_desc_s l_desc; /* desc. for literal tree */
  76612. struct tree_desc_s d_desc; /* desc. for distance tree */
  76613. struct tree_desc_s bl_desc; /* desc. for bit length tree */
  76614. ush bl_count[MAX_BITS+1];
  76615. /* number of codes at each bit length for an optimal tree */
  76616. int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  76617. int heap_len; /* number of elements in the heap */
  76618. int heap_max; /* element of largest frequency */
  76619. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  76620. * The same heap array is used to build all trees.
  76621. */
  76622. uch depth[2*L_CODES+1];
  76623. /* Depth of each subtree used as tie breaker for trees of equal frequency
  76624. */
  76625. uchf *l_buf; /* buffer for literals or lengths */
  76626. uInt lit_bufsize;
  76627. /* Size of match buffer for literals/lengths. There are 4 reasons for
  76628. * limiting lit_bufsize to 64K:
  76629. * - frequencies can be kept in 16 bit counters
  76630. * - if compression is not successful for the first block, all input
  76631. * data is still in the window so we can still emit a stored block even
  76632. * when input comes from standard input. (This can also be done for
  76633. * all blocks if lit_bufsize is not greater than 32K.)
  76634. * - if compression is not successful for a file smaller than 64K, we can
  76635. * even emit a stored file instead of a stored block (saving 5 bytes).
  76636. * This is applicable only for zip (not gzip or zlib).
  76637. * - creating new Huffman trees less frequently may not provide fast
  76638. * adaptation to changes in the input data statistics. (Take for
  76639. * example a binary file with poorly compressible code followed by
  76640. * a highly compressible string table.) Smaller buffer sizes give
  76641. * fast adaptation but have of course the overhead of transmitting
  76642. * trees more frequently.
  76643. * - I can't count above 4
  76644. */
  76645. uInt last_lit; /* running index in l_buf */
  76646. ushf *d_buf;
  76647. /* Buffer for distances. To simplify the code, d_buf and l_buf have
  76648. * the same number of elements. To use different lengths, an extra flag
  76649. * array would be necessary.
  76650. */
  76651. ulg opt_len; /* bit length of current block with optimal trees */
  76652. ulg static_len; /* bit length of current block with static trees */
  76653. uInt matches; /* number of string matches in current block */
  76654. int last_eob_len; /* bit length of EOB code for last block */
  76655. #ifdef DEBUG
  76656. ulg compressed_len; /* total bit length of compressed file mod 2^32 */
  76657. ulg bits_sent; /* bit length of compressed data sent mod 2^32 */
  76658. #endif
  76659. ush bi_buf;
  76660. /* Output buffer. bits are inserted starting at the bottom (least
  76661. * significant bits).
  76662. */
  76663. int bi_valid;
  76664. /* Number of valid bits in bi_buf. All bits above the last valid bit
  76665. * are always zero.
  76666. */
  76667. } FAR deflate_state;
  76668. /* Output a byte on the stream.
  76669. * IN assertion: there is enough room in pending_buf.
  76670. */
  76671. #define put_byte(s, c) {s->pending_buf[s->pending++] = (c);}
  76672. #define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
  76673. /* Minimum amount of lookahead, except at the end of the input file.
  76674. * See deflate.c for comments about the MIN_MATCH+1.
  76675. */
  76676. #define MAX_DIST(s) ((s)->w_size-MIN_LOOKAHEAD)
  76677. /* In order to simplify the code, particularly on 16 bit machines, match
  76678. * distances are limited to MAX_DIST instead of WSIZE.
  76679. */
  76680. /* in trees.c */
  76681. void _tr_init OF((deflate_state *s));
  76682. int _tr_tally OF((deflate_state *s, unsigned dist, unsigned lc));
  76683. void _tr_flush_block OF((deflate_state *s, charf *buf, ulg stored_len,
  76684. int eof));
  76685. void _tr_align OF((deflate_state *s));
  76686. void _tr_stored_block OF((deflate_state *s, charf *buf, ulg stored_len,
  76687. int eof));
  76688. #define d_code(dist) \
  76689. ((dist) < 256 ? _dist_code[dist] : _dist_code[256+((dist)>>7)])
  76690. /* Mapping from a distance to a distance code. dist is the distance - 1 and
  76691. * must not have side effects. _dist_code[256] and _dist_code[257] are never
  76692. * used.
  76693. */
  76694. #ifndef DEBUG
  76695. /* Inline versions of _tr_tally for speed: */
  76696. #if defined(GEN_TREES_H) || !defined(STDC)
  76697. extern uch _length_code[];
  76698. extern uch _dist_code[];
  76699. #else
  76700. extern const uch _length_code[];
  76701. extern const uch _dist_code[];
  76702. #endif
  76703. # define _tr_tally_lit(s, c, flush) \
  76704. { uch cc = (c); \
  76705. s->d_buf[s->last_lit] = 0; \
  76706. s->l_buf[s->last_lit++] = cc; \
  76707. s->dyn_ltree[cc].Freq++; \
  76708. flush = (s->last_lit == s->lit_bufsize-1); \
  76709. }
  76710. # define _tr_tally_dist(s, distance, length, flush) \
  76711. { uch len = (length); \
  76712. ush dist = (distance); \
  76713. s->d_buf[s->last_lit] = dist; \
  76714. s->l_buf[s->last_lit++] = len; \
  76715. dist--; \
  76716. s->dyn_ltree[_length_code[len]+LITERALS+1].Freq++; \
  76717. s->dyn_dtree[d_code(dist)].Freq++; \
  76718. flush = (s->last_lit == s->lit_bufsize-1); \
  76719. }
  76720. #else
  76721. # define _tr_tally_lit(s, c, flush) flush = _tr_tally(s, 0, c)
  76722. # define _tr_tally_dist(s, distance, length, flush) \
  76723. flush = _tr_tally(s, distance, length)
  76724. #endif
  76725. #endif /* DEFLATE_H */
  76726. /********* End of inlined file: deflate.h *********/
  76727. const char deflate_copyright[] =
  76728. " deflate 1.2.3 Copyright 1995-2005 Jean-loup Gailly ";
  76729. /*
  76730. If you use the zlib library in a product, an acknowledgment is welcome
  76731. in the documentation of your product. If for some reason you cannot
  76732. include such an acknowledgment, I would appreciate that you keep this
  76733. copyright string in the executable of your product.
  76734. */
  76735. /* ===========================================================================
  76736. * Function prototypes.
  76737. */
  76738. typedef enum {
  76739. need_more, /* block not completed, need more input or more output */
  76740. block_done, /* block flush performed */
  76741. finish_started, /* finish started, need only more output at next deflate */
  76742. finish_done /* finish done, accept no more input or output */
  76743. } block_state;
  76744. typedef block_state (*compress_func) OF((deflate_state *s, int flush));
  76745. /* Compression function. Returns the block state after the call. */
  76746. local void fill_window OF((deflate_state *s));
  76747. local block_state deflate_stored OF((deflate_state *s, int flush));
  76748. local block_state deflate_fast OF((deflate_state *s, int flush));
  76749. #ifndef FASTEST
  76750. local block_state deflate_slow OF((deflate_state *s, int flush));
  76751. #endif
  76752. local void lm_init OF((deflate_state *s));
  76753. local void putShortMSB OF((deflate_state *s, uInt b));
  76754. local void flush_pending OF((z_streamp strm));
  76755. local int read_buf OF((z_streamp strm, Bytef *buf, unsigned size));
  76756. #ifndef FASTEST
  76757. #ifdef ASMV
  76758. void match_init OF((void)); /* asm code initialization */
  76759. uInt longest_match OF((deflate_state *s, IPos cur_match));
  76760. #else
  76761. local uInt longest_match OF((deflate_state *s, IPos cur_match));
  76762. #endif
  76763. #endif
  76764. local uInt longest_match_fast OF((deflate_state *s, IPos cur_match));
  76765. #ifdef DEBUG
  76766. local void check_match OF((deflate_state *s, IPos start, IPos match,
  76767. int length));
  76768. #endif
  76769. /* ===========================================================================
  76770. * Local data
  76771. */
  76772. #define NIL 0
  76773. /* Tail of hash chains */
  76774. #ifndef TOO_FAR
  76775. # define TOO_FAR 4096
  76776. #endif
  76777. /* Matches of length 3 are discarded if their distance exceeds TOO_FAR */
  76778. #define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
  76779. /* Minimum amount of lookahead, except at the end of the input file.
  76780. * See deflate.c for comments about the MIN_MATCH+1.
  76781. */
  76782. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  76783. * the desired pack level (0..9). The values given below have been tuned to
  76784. * exclude worst case performance for pathological files. Better values may be
  76785. * found for specific files.
  76786. */
  76787. typedef struct config_s {
  76788. ush good_length; /* reduce lazy search above this match length */
  76789. ush max_lazy; /* do not perform lazy search above this match length */
  76790. ush nice_length; /* quit search above this match length */
  76791. ush max_chain;
  76792. compress_func func;
  76793. } config;
  76794. #ifdef FASTEST
  76795. local const config configuration_table[2] = {
  76796. /* good lazy nice chain */
  76797. /* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */
  76798. /* 1 */ {4, 4, 8, 4, deflate_fast}}; /* max speed, no lazy matches */
  76799. #else
  76800. local const config configuration_table[10] = {
  76801. /* good lazy nice chain */
  76802. /* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */
  76803. /* 1 */ {4, 4, 8, 4, deflate_fast}, /* max speed, no lazy matches */
  76804. /* 2 */ {4, 5, 16, 8, deflate_fast},
  76805. /* 3 */ {4, 6, 32, 32, deflate_fast},
  76806. /* 4 */ {4, 4, 16, 16, deflate_slow}, /* lazy matches */
  76807. /* 5 */ {8, 16, 32, 32, deflate_slow},
  76808. /* 6 */ {8, 16, 128, 128, deflate_slow},
  76809. /* 7 */ {8, 32, 128, 256, deflate_slow},
  76810. /* 8 */ {32, 128, 258, 1024, deflate_slow},
  76811. /* 9 */ {32, 258, 258, 4096, deflate_slow}}; /* max compression */
  76812. #endif
  76813. /* Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4
  76814. * For deflate_fast() (levels <= 3) good is ignored and lazy has a different
  76815. * meaning.
  76816. */
  76817. #define EQUAL 0
  76818. /* result of memcmp for equal strings */
  76819. #ifndef NO_DUMMY_DECL
  76820. struct static_tree_desc_s {int dummy;}; /* for buggy compilers */
  76821. #endif
  76822. /* ===========================================================================
  76823. * Update a hash value with the given input byte
  76824. * IN assertion: all calls to to UPDATE_HASH are made with consecutive
  76825. * input characters, so that a running hash key can be computed from the
  76826. * previous key instead of complete recalculation each time.
  76827. */
  76828. #define UPDATE_HASH(s,h,c) (h = (((h)<<s->hash_shift) ^ (c)) & s->hash_mask)
  76829. /* ===========================================================================
  76830. * Insert string str in the dictionary and set match_head to the previous head
  76831. * of the hash chain (the most recent string with same hash key). Return
  76832. * the previous length of the hash chain.
  76833. * If this file is compiled with -DFASTEST, the compression level is forced
  76834. * to 1, and no hash chains are maintained.
  76835. * IN assertion: all calls to to INSERT_STRING are made with consecutive
  76836. * input characters and the first MIN_MATCH bytes of str are valid
  76837. * (except for the last MIN_MATCH-1 bytes of the input file).
  76838. */
  76839. #ifdef FASTEST
  76840. #define INSERT_STRING(s, str, match_head) \
  76841. (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
  76842. match_head = s->head[s->ins_h], \
  76843. s->head[s->ins_h] = (Pos)(str))
  76844. #else
  76845. #define INSERT_STRING(s, str, match_head) \
  76846. (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
  76847. match_head = s->prev[(str) & s->w_mask] = s->head[s->ins_h], \
  76848. s->head[s->ins_h] = (Pos)(str))
  76849. #endif
  76850. /* ===========================================================================
  76851. * Initialize the hash table (avoiding 64K overflow for 16 bit systems).
  76852. * prev[] will be initialized on the fly.
  76853. */
  76854. #define CLEAR_HASH(s) \
  76855. s->head[s->hash_size-1] = NIL; \
  76856. zmemzero((Bytef *)s->head, (unsigned)(s->hash_size-1)*sizeof(*s->head));
  76857. /* ========================================================================= */
  76858. int ZEXPORT deflateInit_(z_streamp strm, int level, const char *version, int stream_size)
  76859. {
  76860. return deflateInit2_(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL,
  76861. Z_DEFAULT_STRATEGY, version, stream_size);
  76862. /* To do: ignore strm->next_in if we use it as window */
  76863. }
  76864. /* ========================================================================= */
  76865. int ZEXPORT deflateInit2_ (z_streamp strm, int level, int method, int windowBits, int memLevel, int strategy, const char *version, int stream_size)
  76866. {
  76867. deflate_state *s;
  76868. int wrap = 1;
  76869. static const char my_version[] = ZLIB_VERSION;
  76870. ushf *overlay;
  76871. /* We overlay pending_buf and d_buf+l_buf. This works since the average
  76872. * output size for (length,distance) codes is <= 24 bits.
  76873. */
  76874. if (version == Z_NULL || version[0] != my_version[0] ||
  76875. stream_size != sizeof(z_stream)) {
  76876. return Z_VERSION_ERROR;
  76877. }
  76878. if (strm == Z_NULL) return Z_STREAM_ERROR;
  76879. strm->msg = Z_NULL;
  76880. if (strm->zalloc == (alloc_func)0) {
  76881. strm->zalloc = zcalloc;
  76882. strm->opaque = (voidpf)0;
  76883. }
  76884. if (strm->zfree == (free_func)0) strm->zfree = zcfree;
  76885. #ifdef FASTEST
  76886. if (level != 0) level = 1;
  76887. #else
  76888. if (level == Z_DEFAULT_COMPRESSION) level = 6;
  76889. #endif
  76890. if (windowBits < 0) { /* suppress zlib wrapper */
  76891. wrap = 0;
  76892. windowBits = -windowBits;
  76893. }
  76894. #ifdef GZIP
  76895. else if (windowBits > 15) {
  76896. wrap = 2; /* write gzip wrapper instead */
  76897. windowBits -= 16;
  76898. }
  76899. #endif
  76900. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != Z_DEFLATED ||
  76901. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  76902. strategy < 0 || strategy > Z_FIXED) {
  76903. return Z_STREAM_ERROR;
  76904. }
  76905. if (windowBits == 8) windowBits = 9; /* until 256-byte window bug fixed */
  76906. s = (deflate_state *) ZALLOC(strm, 1, sizeof(deflate_state));
  76907. if (s == Z_NULL) return Z_MEM_ERROR;
  76908. strm->state = (struct internal_state FAR *)s;
  76909. s->strm = strm;
  76910. s->wrap = wrap;
  76911. s->gzhead = Z_NULL;
  76912. s->w_bits = windowBits;
  76913. s->w_size = 1 << s->w_bits;
  76914. s->w_mask = s->w_size - 1;
  76915. s->hash_bits = memLevel + 7;
  76916. s->hash_size = 1 << s->hash_bits;
  76917. s->hash_mask = s->hash_size - 1;
  76918. s->hash_shift = ((s->hash_bits+MIN_MATCH-1)/MIN_MATCH);
  76919. s->window = (Bytef *) ZALLOC(strm, s->w_size, 2*sizeof(Byte));
  76920. s->prev = (Posf *) ZALLOC(strm, s->w_size, sizeof(Pos));
  76921. s->head = (Posf *) ZALLOC(strm, s->hash_size, sizeof(Pos));
  76922. s->lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  76923. overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2);
  76924. s->pending_buf = (uchf *) overlay;
  76925. s->pending_buf_size = (ulg)s->lit_bufsize * (sizeof(ush)+2L);
  76926. if (s->window == Z_NULL || s->prev == Z_NULL || s->head == Z_NULL ||
  76927. s->pending_buf == Z_NULL) {
  76928. s->status = FINISH_STATE;
  76929. strm->msg = (char*)ERR_MSG(Z_MEM_ERROR);
  76930. deflateEnd (strm);
  76931. return Z_MEM_ERROR;
  76932. }
  76933. s->d_buf = overlay + s->lit_bufsize/sizeof(ush);
  76934. s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize;
  76935. s->level = level;
  76936. s->strategy = strategy;
  76937. s->method = (Byte)method;
  76938. return deflateReset(strm);
  76939. }
  76940. /* ========================================================================= */
  76941. int ZEXPORT deflateSetDictionary (z_streamp strm, const Bytef *dictionary, uInt dictLength)
  76942. {
  76943. deflate_state *s;
  76944. uInt length = dictLength;
  76945. uInt n;
  76946. IPos hash_head = 0;
  76947. if (strm == Z_NULL || strm->state == Z_NULL || dictionary == Z_NULL ||
  76948. strm->state->wrap == 2 ||
  76949. (strm->state->wrap == 1 && strm->state->status != INIT_STATE))
  76950. return Z_STREAM_ERROR;
  76951. s = strm->state;
  76952. if (s->wrap)
  76953. strm->adler = adler32(strm->adler, dictionary, dictLength);
  76954. if (length < MIN_MATCH) return Z_OK;
  76955. if (length > MAX_DIST(s)) {
  76956. length = MAX_DIST(s);
  76957. dictionary += dictLength - length; /* use the tail of the dictionary */
  76958. }
  76959. zmemcpy(s->window, dictionary, length);
  76960. s->strstart = length;
  76961. s->block_start = (long)length;
  76962. /* Insert all strings in the hash table (except for the last two bytes).
  76963. * s->lookahead stays null, so s->ins_h will be recomputed at the next
  76964. * call of fill_window.
  76965. */
  76966. s->ins_h = s->window[0];
  76967. UPDATE_HASH(s, s->ins_h, s->window[1]);
  76968. for (n = 0; n <= length - MIN_MATCH; n++) {
  76969. INSERT_STRING(s, n, hash_head);
  76970. }
  76971. if (hash_head) hash_head = 0; /* to make compiler happy */
  76972. return Z_OK;
  76973. }
  76974. /* ========================================================================= */
  76975. int ZEXPORT deflateReset (z_streamp strm)
  76976. {
  76977. deflate_state *s;
  76978. if (strm == Z_NULL || strm->state == Z_NULL ||
  76979. strm->zalloc == (alloc_func)0 || strm->zfree == (free_func)0) {
  76980. return Z_STREAM_ERROR;
  76981. }
  76982. strm->total_in = strm->total_out = 0;
  76983. strm->msg = Z_NULL; /* use zfree if we ever allocate msg dynamically */
  76984. strm->data_type = Z_UNKNOWN;
  76985. s = (deflate_state *)strm->state;
  76986. s->pending = 0;
  76987. s->pending_out = s->pending_buf;
  76988. if (s->wrap < 0) {
  76989. s->wrap = -s->wrap; /* was made negative by deflate(..., Z_FINISH); */
  76990. }
  76991. s->status = s->wrap ? INIT_STATE : BUSY_STATE;
  76992. strm->adler =
  76993. #ifdef GZIP
  76994. s->wrap == 2 ? crc32(0L, Z_NULL, 0) :
  76995. #endif
  76996. adler32(0L, Z_NULL, 0);
  76997. s->last_flush = Z_NO_FLUSH;
  76998. _tr_init(s);
  76999. lm_init(s);
  77000. return Z_OK;
  77001. }
  77002. /* ========================================================================= */
  77003. int ZEXPORT deflateSetHeader (z_streamp strm, gz_headerp head)
  77004. {
  77005. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  77006. if (strm->state->wrap != 2) return Z_STREAM_ERROR;
  77007. strm->state->gzhead = head;
  77008. return Z_OK;
  77009. }
  77010. /* ========================================================================= */
  77011. int ZEXPORT deflatePrime (z_streamp strm, int bits, int value)
  77012. {
  77013. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  77014. strm->state->bi_valid = bits;
  77015. strm->state->bi_buf = (ush)(value & ((1 << bits) - 1));
  77016. return Z_OK;
  77017. }
  77018. /* ========================================================================= */
  77019. int ZEXPORT deflateParams (z_streamp strm, int level, int strategy)
  77020. {
  77021. deflate_state *s;
  77022. compress_func func;
  77023. int err = Z_OK;
  77024. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  77025. s = strm->state;
  77026. #ifdef FASTEST
  77027. if (level != 0) level = 1;
  77028. #else
  77029. if (level == Z_DEFAULT_COMPRESSION) level = 6;
  77030. #endif
  77031. if (level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED) {
  77032. return Z_STREAM_ERROR;
  77033. }
  77034. func = configuration_table[s->level].func;
  77035. if (func != configuration_table[level].func && strm->total_in != 0) {
  77036. /* Flush the last buffer: */
  77037. err = deflate(strm, Z_PARTIAL_FLUSH);
  77038. }
  77039. if (s->level != level) {
  77040. s->level = level;
  77041. s->max_lazy_match = configuration_table[level].max_lazy;
  77042. s->good_match = configuration_table[level].good_length;
  77043. s->nice_match = configuration_table[level].nice_length;
  77044. s->max_chain_length = configuration_table[level].max_chain;
  77045. }
  77046. s->strategy = strategy;
  77047. return err;
  77048. }
  77049. /* ========================================================================= */
  77050. int ZEXPORT deflateTune (z_streamp strm, int good_length, int max_lazy, int nice_length, int max_chain)
  77051. {
  77052. deflate_state *s;
  77053. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  77054. s = strm->state;
  77055. s->good_match = good_length;
  77056. s->max_lazy_match = max_lazy;
  77057. s->nice_match = nice_length;
  77058. s->max_chain_length = max_chain;
  77059. return Z_OK;
  77060. }
  77061. /* =========================================================================
  77062. * For the default windowBits of 15 and memLevel of 8, this function returns
  77063. * a close to exact, as well as small, upper bound on the compressed size.
  77064. * They are coded as constants here for a reason--if the #define's are
  77065. * changed, then this function needs to be changed as well. The return
  77066. * value for 15 and 8 only works for those exact settings.
  77067. *
  77068. * For any setting other than those defaults for windowBits and memLevel,
  77069. * the value returned is a conservative worst case for the maximum expansion
  77070. * resulting from using fixed blocks instead of stored blocks, which deflate
  77071. * can emit on compressed data for some combinations of the parameters.
  77072. *
  77073. * This function could be more sophisticated to provide closer upper bounds
  77074. * for every combination of windowBits and memLevel, as well as wrap.
  77075. * But even the conservative upper bound of about 14% expansion does not
  77076. * seem onerous for output buffer allocation.
  77077. */
  77078. uLong ZEXPORT deflateBound (z_streamp strm, uLong sourceLen)
  77079. {
  77080. deflate_state *s;
  77081. uLong destLen;
  77082. /* conservative upper bound */
  77083. destLen = sourceLen +
  77084. ((sourceLen + 7) >> 3) + ((sourceLen + 63) >> 6) + 11;
  77085. /* if can't get parameters, return conservative bound */
  77086. if (strm == Z_NULL || strm->state == Z_NULL)
  77087. return destLen;
  77088. /* if not default parameters, return conservative bound */
  77089. s = strm->state;
  77090. if (s->w_bits != 15 || s->hash_bits != 8 + 7)
  77091. return destLen;
  77092. /* default settings: return tight bound for that case */
  77093. return compressBound(sourceLen);
  77094. }
  77095. /* =========================================================================
  77096. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  77097. * IN assertion: the stream state is correct and there is enough room in
  77098. * pending_buf.
  77099. */
  77100. local void putShortMSB (deflate_state *s, uInt b)
  77101. {
  77102. put_byte(s, (Byte)(b >> 8));
  77103. put_byte(s, (Byte)(b & 0xff));
  77104. }
  77105. /* =========================================================================
  77106. * Flush as much pending output as possible. All deflate() output goes
  77107. * through this function so some applications may wish to modify it
  77108. * to avoid allocating a large strm->next_out buffer and copying into it.
  77109. * (See also read_buf()).
  77110. */
  77111. local void flush_pending (z_streamp strm)
  77112. {
  77113. unsigned len = strm->state->pending;
  77114. if (len > strm->avail_out) len = strm->avail_out;
  77115. if (len == 0) return;
  77116. zmemcpy(strm->next_out, strm->state->pending_out, len);
  77117. strm->next_out += len;
  77118. strm->state->pending_out += len;
  77119. strm->total_out += len;
  77120. strm->avail_out -= len;
  77121. strm->state->pending -= len;
  77122. if (strm->state->pending == 0) {
  77123. strm->state->pending_out = strm->state->pending_buf;
  77124. }
  77125. }
  77126. /* ========================================================================= */
  77127. int ZEXPORT deflate (z_streamp strm, int flush)
  77128. {
  77129. int old_flush; /* value of flush param for previous deflate call */
  77130. deflate_state *s;
  77131. if (strm == Z_NULL || strm->state == Z_NULL ||
  77132. flush > Z_FINISH || flush < 0) {
  77133. return Z_STREAM_ERROR;
  77134. }
  77135. s = strm->state;
  77136. if (strm->next_out == Z_NULL ||
  77137. (strm->next_in == Z_NULL && strm->avail_in != 0) ||
  77138. (s->status == FINISH_STATE && flush != Z_FINISH)) {
  77139. ERR_RETURN(strm, Z_STREAM_ERROR);
  77140. }
  77141. if (strm->avail_out == 0) ERR_RETURN(strm, Z_BUF_ERROR);
  77142. s->strm = strm; /* just in case */
  77143. old_flush = s->last_flush;
  77144. s->last_flush = flush;
  77145. /* Write the header */
  77146. if (s->status == INIT_STATE) {
  77147. #ifdef GZIP
  77148. if (s->wrap == 2) {
  77149. strm->adler = crc32(0L, Z_NULL, 0);
  77150. put_byte(s, 31);
  77151. put_byte(s, 139);
  77152. put_byte(s, 8);
  77153. if (s->gzhead == NULL) {
  77154. put_byte(s, 0);
  77155. put_byte(s, 0);
  77156. put_byte(s, 0);
  77157. put_byte(s, 0);
  77158. put_byte(s, 0);
  77159. put_byte(s, s->level == 9 ? 2 :
  77160. (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
  77161. 4 : 0));
  77162. put_byte(s, OS_CODE);
  77163. s->status = BUSY_STATE;
  77164. }
  77165. else {
  77166. put_byte(s, (s->gzhead->text ? 1 : 0) +
  77167. (s->gzhead->hcrc ? 2 : 0) +
  77168. (s->gzhead->extra == Z_NULL ? 0 : 4) +
  77169. (s->gzhead->name == Z_NULL ? 0 : 8) +
  77170. (s->gzhead->comment == Z_NULL ? 0 : 16)
  77171. );
  77172. put_byte(s, (Byte)(s->gzhead->time & 0xff));
  77173. put_byte(s, (Byte)((s->gzhead->time >> 8) & 0xff));
  77174. put_byte(s, (Byte)((s->gzhead->time >> 16) & 0xff));
  77175. put_byte(s, (Byte)((s->gzhead->time >> 24) & 0xff));
  77176. put_byte(s, s->level == 9 ? 2 :
  77177. (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
  77178. 4 : 0));
  77179. put_byte(s, s->gzhead->os & 0xff);
  77180. if (s->gzhead->extra != NULL) {
  77181. put_byte(s, s->gzhead->extra_len & 0xff);
  77182. put_byte(s, (s->gzhead->extra_len >> 8) & 0xff);
  77183. }
  77184. if (s->gzhead->hcrc)
  77185. strm->adler = crc32(strm->adler, s->pending_buf,
  77186. s->pending);
  77187. s->gzindex = 0;
  77188. s->status = EXTRA_STATE;
  77189. }
  77190. }
  77191. else
  77192. #endif
  77193. {
  77194. uInt header = (Z_DEFLATED + ((s->w_bits-8)<<4)) << 8;
  77195. uInt level_flags;
  77196. if (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2)
  77197. level_flags = 0;
  77198. else if (s->level < 6)
  77199. level_flags = 1;
  77200. else if (s->level == 6)
  77201. level_flags = 2;
  77202. else
  77203. level_flags = 3;
  77204. header |= (level_flags << 6);
  77205. if (s->strstart != 0) header |= PRESET_DICT;
  77206. header += 31 - (header % 31);
  77207. s->status = BUSY_STATE;
  77208. putShortMSB(s, header);
  77209. /* Save the adler32 of the preset dictionary: */
  77210. if (s->strstart != 0) {
  77211. putShortMSB(s, (uInt)(strm->adler >> 16));
  77212. putShortMSB(s, (uInt)(strm->adler & 0xffff));
  77213. }
  77214. strm->adler = adler32(0L, Z_NULL, 0);
  77215. }
  77216. }
  77217. #ifdef GZIP
  77218. if (s->status == EXTRA_STATE) {
  77219. if (s->gzhead->extra != NULL) {
  77220. uInt beg = s->pending; /* start of bytes to update crc */
  77221. while (s->gzindex < (s->gzhead->extra_len & 0xffff)) {
  77222. if (s->pending == s->pending_buf_size) {
  77223. if (s->gzhead->hcrc && s->pending > beg)
  77224. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  77225. s->pending - beg);
  77226. flush_pending(strm);
  77227. beg = s->pending;
  77228. if (s->pending == s->pending_buf_size)
  77229. break;
  77230. }
  77231. put_byte(s, s->gzhead->extra[s->gzindex]);
  77232. s->gzindex++;
  77233. }
  77234. if (s->gzhead->hcrc && s->pending > beg)
  77235. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  77236. s->pending - beg);
  77237. if (s->gzindex == s->gzhead->extra_len) {
  77238. s->gzindex = 0;
  77239. s->status = NAME_STATE;
  77240. }
  77241. }
  77242. else
  77243. s->status = NAME_STATE;
  77244. }
  77245. if (s->status == NAME_STATE) {
  77246. if (s->gzhead->name != NULL) {
  77247. uInt beg = s->pending; /* start of bytes to update crc */
  77248. int val;
  77249. do {
  77250. if (s->pending == s->pending_buf_size) {
  77251. if (s->gzhead->hcrc && s->pending > beg)
  77252. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  77253. s->pending - beg);
  77254. flush_pending(strm);
  77255. beg = s->pending;
  77256. if (s->pending == s->pending_buf_size) {
  77257. val = 1;
  77258. break;
  77259. }
  77260. }
  77261. val = s->gzhead->name[s->gzindex++];
  77262. put_byte(s, val);
  77263. } while (val != 0);
  77264. if (s->gzhead->hcrc && s->pending > beg)
  77265. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  77266. s->pending - beg);
  77267. if (val == 0) {
  77268. s->gzindex = 0;
  77269. s->status = COMMENT_STATE;
  77270. }
  77271. }
  77272. else
  77273. s->status = COMMENT_STATE;
  77274. }
  77275. if (s->status == COMMENT_STATE) {
  77276. if (s->gzhead->comment != NULL) {
  77277. uInt beg = s->pending; /* start of bytes to update crc */
  77278. int val;
  77279. do {
  77280. if (s->pending == s->pending_buf_size) {
  77281. if (s->gzhead->hcrc && s->pending > beg)
  77282. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  77283. s->pending - beg);
  77284. flush_pending(strm);
  77285. beg = s->pending;
  77286. if (s->pending == s->pending_buf_size) {
  77287. val = 1;
  77288. break;
  77289. }
  77290. }
  77291. val = s->gzhead->comment[s->gzindex++];
  77292. put_byte(s, val);
  77293. } while (val != 0);
  77294. if (s->gzhead->hcrc && s->pending > beg)
  77295. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  77296. s->pending - beg);
  77297. if (val == 0)
  77298. s->status = HCRC_STATE;
  77299. }
  77300. else
  77301. s->status = HCRC_STATE;
  77302. }
  77303. if (s->status == HCRC_STATE) {
  77304. if (s->gzhead->hcrc) {
  77305. if (s->pending + 2 > s->pending_buf_size)
  77306. flush_pending(strm);
  77307. if (s->pending + 2 <= s->pending_buf_size) {
  77308. put_byte(s, (Byte)(strm->adler & 0xff));
  77309. put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
  77310. strm->adler = crc32(0L, Z_NULL, 0);
  77311. s->status = BUSY_STATE;
  77312. }
  77313. }
  77314. else
  77315. s->status = BUSY_STATE;
  77316. }
  77317. #endif
  77318. /* Flush as much pending output as possible */
  77319. if (s->pending != 0) {
  77320. flush_pending(strm);
  77321. if (strm->avail_out == 0) {
  77322. /* Since avail_out is 0, deflate will be called again with
  77323. * more output space, but possibly with both pending and
  77324. * avail_in equal to zero. There won't be anything to do,
  77325. * but this is not an error situation so make sure we
  77326. * return OK instead of BUF_ERROR at next call of deflate:
  77327. */
  77328. s->last_flush = -1;
  77329. return Z_OK;
  77330. }
  77331. /* Make sure there is something to do and avoid duplicate consecutive
  77332. * flushes. For repeated and useless calls with Z_FINISH, we keep
  77333. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  77334. */
  77335. } else if (strm->avail_in == 0 && flush <= old_flush &&
  77336. flush != Z_FINISH) {
  77337. ERR_RETURN(strm, Z_BUF_ERROR);
  77338. }
  77339. /* User must not provide more input after the first FINISH: */
  77340. if (s->status == FINISH_STATE && strm->avail_in != 0) {
  77341. ERR_RETURN(strm, Z_BUF_ERROR);
  77342. }
  77343. /* Start a new block or continue the current one.
  77344. */
  77345. if (strm->avail_in != 0 || s->lookahead != 0 ||
  77346. (flush != Z_NO_FLUSH && s->status != FINISH_STATE)) {
  77347. block_state bstate;
  77348. bstate = (*(configuration_table[s->level].func))(s, flush);
  77349. if (bstate == finish_started || bstate == finish_done) {
  77350. s->status = FINISH_STATE;
  77351. }
  77352. if (bstate == need_more || bstate == finish_started) {
  77353. if (strm->avail_out == 0) {
  77354. s->last_flush = -1; /* avoid BUF_ERROR next call, see above */
  77355. }
  77356. return Z_OK;
  77357. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  77358. * of deflate should use the same flush parameter to make sure
  77359. * that the flush is complete. So we don't have to output an
  77360. * empty block here, this will be done at next call. This also
  77361. * ensures that for a very small output buffer, we emit at most
  77362. * one empty block.
  77363. */
  77364. }
  77365. if (bstate == block_done) {
  77366. if (flush == Z_PARTIAL_FLUSH) {
  77367. _tr_align(s);
  77368. } else { /* FULL_FLUSH or SYNC_FLUSH */
  77369. _tr_stored_block(s, (char*)0, 0L, 0);
  77370. /* For a full flush, this empty block will be recognized
  77371. * as a special marker by inflate_sync().
  77372. */
  77373. if (flush == Z_FULL_FLUSH) {
  77374. CLEAR_HASH(s); /* forget history */
  77375. }
  77376. }
  77377. flush_pending(strm);
  77378. if (strm->avail_out == 0) {
  77379. s->last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  77380. return Z_OK;
  77381. }
  77382. }
  77383. }
  77384. Assert(strm->avail_out > 0, "bug2");
  77385. if (flush != Z_FINISH) return Z_OK;
  77386. if (s->wrap <= 0) return Z_STREAM_END;
  77387. /* Write the trailer */
  77388. #ifdef GZIP
  77389. if (s->wrap == 2) {
  77390. put_byte(s, (Byte)(strm->adler & 0xff));
  77391. put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
  77392. put_byte(s, (Byte)((strm->adler >> 16) & 0xff));
  77393. put_byte(s, (Byte)((strm->adler >> 24) & 0xff));
  77394. put_byte(s, (Byte)(strm->total_in & 0xff));
  77395. put_byte(s, (Byte)((strm->total_in >> 8) & 0xff));
  77396. put_byte(s, (Byte)((strm->total_in >> 16) & 0xff));
  77397. put_byte(s, (Byte)((strm->total_in >> 24) & 0xff));
  77398. }
  77399. else
  77400. #endif
  77401. {
  77402. putShortMSB(s, (uInt)(strm->adler >> 16));
  77403. putShortMSB(s, (uInt)(strm->adler & 0xffff));
  77404. }
  77405. flush_pending(strm);
  77406. /* If avail_out is zero, the application will call deflate again
  77407. * to flush the rest.
  77408. */
  77409. if (s->wrap > 0) s->wrap = -s->wrap; /* write the trailer only once! */
  77410. return s->pending != 0 ? Z_OK : Z_STREAM_END;
  77411. }
  77412. /* ========================================================================= */
  77413. int ZEXPORT deflateEnd (z_streamp strm)
  77414. {
  77415. int status;
  77416. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  77417. status = strm->state->status;
  77418. if (status != INIT_STATE &&
  77419. status != EXTRA_STATE &&
  77420. status != NAME_STATE &&
  77421. status != COMMENT_STATE &&
  77422. status != HCRC_STATE &&
  77423. status != BUSY_STATE &&
  77424. status != FINISH_STATE) {
  77425. return Z_STREAM_ERROR;
  77426. }
  77427. /* Deallocate in reverse order of allocations: */
  77428. TRY_FREE(strm, strm->state->pending_buf);
  77429. TRY_FREE(strm, strm->state->head);
  77430. TRY_FREE(strm, strm->state->prev);
  77431. TRY_FREE(strm, strm->state->window);
  77432. ZFREE(strm, strm->state);
  77433. strm->state = Z_NULL;
  77434. return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK;
  77435. }
  77436. /* =========================================================================
  77437. * Copy the source state to the destination state.
  77438. * To simplify the source, this is not supported for 16-bit MSDOS (which
  77439. * doesn't have enough memory anyway to duplicate compression states).
  77440. */
  77441. int ZEXPORT deflateCopy (z_streamp dest, z_streamp source)
  77442. {
  77443. #ifdef MAXSEG_64K
  77444. return Z_STREAM_ERROR;
  77445. #else
  77446. deflate_state *ds;
  77447. deflate_state *ss;
  77448. ushf *overlay;
  77449. if (source == Z_NULL || dest == Z_NULL || source->state == Z_NULL) {
  77450. return Z_STREAM_ERROR;
  77451. }
  77452. ss = source->state;
  77453. zmemcpy(dest, source, sizeof(z_stream));
  77454. ds = (deflate_state *) ZALLOC(dest, 1, sizeof(deflate_state));
  77455. if (ds == Z_NULL) return Z_MEM_ERROR;
  77456. dest->state = (struct internal_state FAR *) ds;
  77457. zmemcpy(ds, ss, sizeof(deflate_state));
  77458. ds->strm = dest;
  77459. ds->window = (Bytef *) ZALLOC(dest, ds->w_size, 2*sizeof(Byte));
  77460. ds->prev = (Posf *) ZALLOC(dest, ds->w_size, sizeof(Pos));
  77461. ds->head = (Posf *) ZALLOC(dest, ds->hash_size, sizeof(Pos));
  77462. overlay = (ushf *) ZALLOC(dest, ds->lit_bufsize, sizeof(ush)+2);
  77463. ds->pending_buf = (uchf *) overlay;
  77464. if (ds->window == Z_NULL || ds->prev == Z_NULL || ds->head == Z_NULL ||
  77465. ds->pending_buf == Z_NULL) {
  77466. deflateEnd (dest);
  77467. return Z_MEM_ERROR;
  77468. }
  77469. /* following zmemcpy do not work for 16-bit MSDOS */
  77470. zmemcpy(ds->window, ss->window, ds->w_size * 2 * sizeof(Byte));
  77471. zmemcpy(ds->prev, ss->prev, ds->w_size * sizeof(Pos));
  77472. zmemcpy(ds->head, ss->head, ds->hash_size * sizeof(Pos));
  77473. zmemcpy(ds->pending_buf, ss->pending_buf, (uInt)ds->pending_buf_size);
  77474. ds->pending_out = ds->pending_buf + (ss->pending_out - ss->pending_buf);
  77475. ds->d_buf = overlay + ds->lit_bufsize/sizeof(ush);
  77476. ds->l_buf = ds->pending_buf + (1+sizeof(ush))*ds->lit_bufsize;
  77477. ds->l_desc.dyn_tree = ds->dyn_ltree;
  77478. ds->d_desc.dyn_tree = ds->dyn_dtree;
  77479. ds->bl_desc.dyn_tree = ds->bl_tree;
  77480. return Z_OK;
  77481. #endif /* MAXSEG_64K */
  77482. }
  77483. /* ===========================================================================
  77484. * Read a new buffer from the current input stream, update the adler32
  77485. * and total number of bytes read. All deflate() input goes through
  77486. * this function so some applications may wish to modify it to avoid
  77487. * allocating a large strm->next_in buffer and copying from it.
  77488. * (See also flush_pending()).
  77489. */
  77490. local int read_buf (z_streamp strm, Bytef *buf, unsigned size)
  77491. {
  77492. unsigned len = strm->avail_in;
  77493. if (len > size) len = size;
  77494. if (len == 0) return 0;
  77495. strm->avail_in -= len;
  77496. if (strm->state->wrap == 1) {
  77497. strm->adler = adler32(strm->adler, strm->next_in, len);
  77498. }
  77499. #ifdef GZIP
  77500. else if (strm->state->wrap == 2) {
  77501. strm->adler = crc32(strm->adler, strm->next_in, len);
  77502. }
  77503. #endif
  77504. zmemcpy(buf, strm->next_in, len);
  77505. strm->next_in += len;
  77506. strm->total_in += len;
  77507. return (int)len;
  77508. }
  77509. /* ===========================================================================
  77510. * Initialize the "longest match" routines for a new zlib stream
  77511. */
  77512. local void lm_init (deflate_state *s)
  77513. {
  77514. s->window_size = (ulg)2L*s->w_size;
  77515. CLEAR_HASH(s);
  77516. /* Set the default configuration parameters:
  77517. */
  77518. s->max_lazy_match = configuration_table[s->level].max_lazy;
  77519. s->good_match = configuration_table[s->level].good_length;
  77520. s->nice_match = configuration_table[s->level].nice_length;
  77521. s->max_chain_length = configuration_table[s->level].max_chain;
  77522. s->strstart = 0;
  77523. s->block_start = 0L;
  77524. s->lookahead = 0;
  77525. s->match_length = s->prev_length = MIN_MATCH-1;
  77526. s->match_available = 0;
  77527. s->ins_h = 0;
  77528. #ifndef FASTEST
  77529. #ifdef ASMV
  77530. match_init(); /* initialize the asm code */
  77531. #endif
  77532. #endif
  77533. }
  77534. #ifndef FASTEST
  77535. /* ===========================================================================
  77536. * Set match_start to the longest match starting at the given string and
  77537. * return its length. Matches shorter or equal to prev_length are discarded,
  77538. * in which case the result is equal to prev_length and match_start is
  77539. * garbage.
  77540. * IN assertions: cur_match is the head of the hash chain for the current
  77541. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  77542. * OUT assertion: the match length is not greater than s->lookahead.
  77543. */
  77544. #ifndef ASMV
  77545. /* For 80x86 and 680x0, an optimized version will be provided in match.asm or
  77546. * match.S. The code will be functionally equivalent.
  77547. */
  77548. local uInt longest_match(deflate_state *s, IPos cur_match)
  77549. {
  77550. unsigned chain_length = s->max_chain_length;/* max hash chain length */
  77551. register Bytef *scan = s->window + s->strstart; /* current string */
  77552. register Bytef *match; /* matched string */
  77553. register int len; /* length of current match */
  77554. int best_len = s->prev_length; /* best match length so far */
  77555. int nice_match = s->nice_match; /* stop if match long enough */
  77556. IPos limit = s->strstart > (IPos)MAX_DIST(s) ?
  77557. s->strstart - (IPos)MAX_DIST(s) : NIL;
  77558. /* Stop when cur_match becomes <= limit. To simplify the code,
  77559. * we prevent matches with the string of window index 0.
  77560. */
  77561. Posf *prev = s->prev;
  77562. uInt wmask = s->w_mask;
  77563. #ifdef UNALIGNED_OK
  77564. /* Compare two bytes at a time. Note: this is not always beneficial.
  77565. * Try with and without -DUNALIGNED_OK to check.
  77566. */
  77567. register Bytef *strend = s->window + s->strstart + MAX_MATCH - 1;
  77568. register ush scan_start = *(ushf*)scan;
  77569. register ush scan_end = *(ushf*)(scan+best_len-1);
  77570. #else
  77571. register Bytef *strend = s->window + s->strstart + MAX_MATCH;
  77572. register Byte scan_end1 = scan[best_len-1];
  77573. register Byte scan_end = scan[best_len];
  77574. #endif
  77575. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  77576. * It is easy to get rid of this optimization if necessary.
  77577. */
  77578. Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  77579. /* Do not waste too much time if we already have a good match: */
  77580. if (s->prev_length >= s->good_match) {
  77581. chain_length >>= 2;
  77582. }
  77583. /* Do not look for matches beyond the end of the input. This is necessary
  77584. * to make deflate deterministic.
  77585. */
  77586. if ((uInt)nice_match > s->lookahead) nice_match = s->lookahead;
  77587. Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  77588. do {
  77589. Assert(cur_match < s->strstart, "no future");
  77590. match = s->window + cur_match;
  77591. /* Skip to next match if the match length cannot increase
  77592. * or if the match length is less than 2. Note that the checks below
  77593. * for insufficient lookahead only occur occasionally for performance
  77594. * reasons. Therefore uninitialized memory will be accessed, and
  77595. * conditional jumps will be made that depend on those values.
  77596. * However the length of the match is limited to the lookahead, so
  77597. * the output of deflate is not affected by the uninitialized values.
  77598. */
  77599. #if (defined(UNALIGNED_OK) && MAX_MATCH == 258)
  77600. /* This code assumes sizeof(unsigned short) == 2. Do not use
  77601. * UNALIGNED_OK if your compiler uses a different size.
  77602. */
  77603. if (*(ushf*)(match+best_len-1) != scan_end ||
  77604. *(ushf*)match != scan_start) continue;
  77605. /* It is not necessary to compare scan[2] and match[2] since they are
  77606. * always equal when the other bytes match, given that the hash keys
  77607. * are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at
  77608. * strstart+3, +5, ... up to strstart+257. We check for insufficient
  77609. * lookahead only every 4th comparison; the 128th check will be made
  77610. * at strstart+257. If MAX_MATCH-2 is not a multiple of 8, it is
  77611. * necessary to put more guard bytes at the end of the window, or
  77612. * to check more often for insufficient lookahead.
  77613. */
  77614. Assert(scan[2] == match[2], "scan[2]?");
  77615. scan++, match++;
  77616. do {
  77617. } while (*(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  77618. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  77619. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  77620. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  77621. scan < strend);
  77622. /* The funny "do {}" generates better code on most compilers */
  77623. /* Here, scan <= window+strstart+257 */
  77624. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  77625. if (*scan == *match) scan++;
  77626. len = (MAX_MATCH - 1) - (int)(strend-scan);
  77627. scan = strend - (MAX_MATCH-1);
  77628. #else /* UNALIGNED_OK */
  77629. if (match[best_len] != scan_end ||
  77630. match[best_len-1] != scan_end1 ||
  77631. *match != *scan ||
  77632. *++match != scan[1]) continue;
  77633. /* The check at best_len-1 can be removed because it will be made
  77634. * again later. (This heuristic is not always a win.)
  77635. * It is not necessary to compare scan[2] and match[2] since they
  77636. * are always equal when the other bytes match, given that
  77637. * the hash keys are equal and that HASH_BITS >= 8.
  77638. */
  77639. scan += 2, match++;
  77640. Assert(*scan == *match, "match[2]?");
  77641. /* We check for insufficient lookahead only every 8th comparison;
  77642. * the 256th check will be made at strstart+258.
  77643. */
  77644. do {
  77645. } while (*++scan == *++match && *++scan == *++match &&
  77646. *++scan == *++match && *++scan == *++match &&
  77647. *++scan == *++match && *++scan == *++match &&
  77648. *++scan == *++match && *++scan == *++match &&
  77649. scan < strend);
  77650. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  77651. len = MAX_MATCH - (int)(strend - scan);
  77652. scan = strend - MAX_MATCH;
  77653. #endif /* UNALIGNED_OK */
  77654. if (len > best_len) {
  77655. s->match_start = cur_match;
  77656. best_len = len;
  77657. if (len >= nice_match) break;
  77658. #ifdef UNALIGNED_OK
  77659. scan_end = *(ushf*)(scan+best_len-1);
  77660. #else
  77661. scan_end1 = scan[best_len-1];
  77662. scan_end = scan[best_len];
  77663. #endif
  77664. }
  77665. } while ((cur_match = prev[cur_match & wmask]) > limit
  77666. && --chain_length != 0);
  77667. if ((uInt)best_len <= s->lookahead) return (uInt)best_len;
  77668. return s->lookahead;
  77669. }
  77670. #endif /* ASMV */
  77671. #endif /* FASTEST */
  77672. /* ---------------------------------------------------------------------------
  77673. * Optimized version for level == 1 or strategy == Z_RLE only
  77674. */
  77675. local uInt longest_match_fast (deflate_state *s, IPos cur_match)
  77676. {
  77677. register Bytef *scan = s->window + s->strstart; /* current string */
  77678. register Bytef *match; /* matched string */
  77679. register int len; /* length of current match */
  77680. register Bytef *strend = s->window + s->strstart + MAX_MATCH;
  77681. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  77682. * It is easy to get rid of this optimization if necessary.
  77683. */
  77684. Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  77685. Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  77686. Assert(cur_match < s->strstart, "no future");
  77687. match = s->window + cur_match;
  77688. /* Return failure if the match length is less than 2:
  77689. */
  77690. if (match[0] != scan[0] || match[1] != scan[1]) return MIN_MATCH-1;
  77691. /* The check at best_len-1 can be removed because it will be made
  77692. * again later. (This heuristic is not always a win.)
  77693. * It is not necessary to compare scan[2] and match[2] since they
  77694. * are always equal when the other bytes match, given that
  77695. * the hash keys are equal and that HASH_BITS >= 8.
  77696. */
  77697. scan += 2, match += 2;
  77698. Assert(*scan == *match, "match[2]?");
  77699. /* We check for insufficient lookahead only every 8th comparison;
  77700. * the 256th check will be made at strstart+258.
  77701. */
  77702. do {
  77703. } while (*++scan == *++match && *++scan == *++match &&
  77704. *++scan == *++match && *++scan == *++match &&
  77705. *++scan == *++match && *++scan == *++match &&
  77706. *++scan == *++match && *++scan == *++match &&
  77707. scan < strend);
  77708. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  77709. len = MAX_MATCH - (int)(strend - scan);
  77710. if (len < MIN_MATCH) return MIN_MATCH - 1;
  77711. s->match_start = cur_match;
  77712. return (uInt)len <= s->lookahead ? (uInt)len : s->lookahead;
  77713. }
  77714. #ifdef DEBUG
  77715. /* ===========================================================================
  77716. * Check that the match at match_start is indeed a match.
  77717. */
  77718. local void check_match(deflate_state *s, IPos start, IPos match, int length)
  77719. {
  77720. /* check that the match is indeed a match */
  77721. if (zmemcmp(s->window + match,
  77722. s->window + start, length) != EQUAL) {
  77723. fprintf(stderr, " start %u, match %u, length %d\n",
  77724. start, match, length);
  77725. do {
  77726. fprintf(stderr, "%c%c", s->window[match++], s->window[start++]);
  77727. } while (--length != 0);
  77728. z_error("invalid match");
  77729. }
  77730. if (z_verbose > 1) {
  77731. fprintf(stderr,"\\[%d,%d]", start-match, length);
  77732. do { putc(s->window[start++], stderr); } while (--length != 0);
  77733. }
  77734. }
  77735. #else
  77736. # define check_match(s, start, match, length)
  77737. #endif /* DEBUG */
  77738. /* ===========================================================================
  77739. * Fill the window when the lookahead becomes insufficient.
  77740. * Updates strstart and lookahead.
  77741. *
  77742. * IN assertion: lookahead < MIN_LOOKAHEAD
  77743. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  77744. * At least one byte has been read, or avail_in == 0; reads are
  77745. * performed for at least two bytes (required for the zip translate_eol
  77746. * option -- not supported here).
  77747. */
  77748. local void fill_window (deflate_state *s)
  77749. {
  77750. register unsigned n, m;
  77751. register Posf *p;
  77752. unsigned more; /* Amount of free space at the end of the window. */
  77753. uInt wsize = s->w_size;
  77754. do {
  77755. more = (unsigned)(s->window_size -(ulg)s->lookahead -(ulg)s->strstart);
  77756. /* Deal with !@#$% 64K limit: */
  77757. if (sizeof(int) <= 2) {
  77758. if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  77759. more = wsize;
  77760. } else if (more == (unsigned)(-1)) {
  77761. /* Very unlikely, but possible on 16 bit machine if
  77762. * strstart == 0 && lookahead == 1 (input done a byte at time)
  77763. */
  77764. more--;
  77765. }
  77766. }
  77767. /* If the window is almost full and there is insufficient lookahead,
  77768. * move the upper half to the lower one to make room in the upper half.
  77769. */
  77770. if (s->strstart >= wsize+MAX_DIST(s)) {
  77771. zmemcpy(s->window, s->window+wsize, (unsigned)wsize);
  77772. s->match_start -= wsize;
  77773. s->strstart -= wsize; /* we now have strstart >= MAX_DIST */
  77774. s->block_start -= (long) wsize;
  77775. /* Slide the hash table (could be avoided with 32 bit values
  77776. at the expense of memory usage). We slide even when level == 0
  77777. to keep the hash table consistent if we switch back to level > 0
  77778. later. (Using level 0 permanently is not an optimal usage of
  77779. zlib, so we don't care about this pathological case.)
  77780. */
  77781. /* %%% avoid this when Z_RLE */
  77782. n = s->hash_size;
  77783. p = &s->head[n];
  77784. do {
  77785. m = *--p;
  77786. *p = (Pos)(m >= wsize ? m-wsize : NIL);
  77787. } while (--n);
  77788. n = wsize;
  77789. #ifndef FASTEST
  77790. p = &s->prev[n];
  77791. do {
  77792. m = *--p;
  77793. *p = (Pos)(m >= wsize ? m-wsize : NIL);
  77794. /* If n is not on any hash chain, prev[n] is garbage but
  77795. * its value will never be used.
  77796. */
  77797. } while (--n);
  77798. #endif
  77799. more += wsize;
  77800. }
  77801. if (s->strm->avail_in == 0) return;
  77802. /* If there was no sliding:
  77803. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  77804. * more == window_size - lookahead - strstart
  77805. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  77806. * => more >= window_size - 2*WSIZE + 2
  77807. * In the BIG_MEM or MMAP case (not yet supported),
  77808. * window_size == input_size + MIN_LOOKAHEAD &&
  77809. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  77810. * Otherwise, window_size == 2*WSIZE so more >= 2.
  77811. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  77812. */
  77813. Assert(more >= 2, "more < 2");
  77814. n = read_buf(s->strm, s->window + s->strstart + s->lookahead, more);
  77815. s->lookahead += n;
  77816. /* Initialize the hash value now that we have some input: */
  77817. if (s->lookahead >= MIN_MATCH) {
  77818. s->ins_h = s->window[s->strstart];
  77819. UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
  77820. #if MIN_MATCH != 3
  77821. Call UPDATE_HASH() MIN_MATCH-3 more times
  77822. #endif
  77823. }
  77824. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  77825. * but this is not important since only literal bytes will be emitted.
  77826. */
  77827. } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0);
  77828. }
  77829. /* ===========================================================================
  77830. * Flush the current block, with given end-of-file flag.
  77831. * IN assertion: strstart is set to the end of the current match.
  77832. */
  77833. #define FLUSH_BLOCK_ONLY(s, eof) { \
  77834. _tr_flush_block(s, (s->block_start >= 0L ? \
  77835. (charf *)&s->window[(unsigned)s->block_start] : \
  77836. (charf *)Z_NULL), \
  77837. (ulg)((long)s->strstart - s->block_start), \
  77838. (eof)); \
  77839. s->block_start = s->strstart; \
  77840. flush_pending(s->strm); \
  77841. Tracev((stderr,"[FLUSH]")); \
  77842. }
  77843. /* Same but force premature exit if necessary. */
  77844. #define FLUSH_BLOCK(s, eof) { \
  77845. FLUSH_BLOCK_ONLY(s, eof); \
  77846. if (s->strm->avail_out == 0) return (eof) ? finish_started : need_more; \
  77847. }
  77848. /* ===========================================================================
  77849. * Copy without compression as much as possible from the input stream, return
  77850. * the current block state.
  77851. * This function does not insert new strings in the dictionary since
  77852. * uncompressible data is probably not useful. This function is used
  77853. * only for the level=0 compression option.
  77854. * NOTE: this function should be optimized to avoid extra copying from
  77855. * window to pending_buf.
  77856. */
  77857. local block_state deflate_stored(deflate_state *s, int flush)
  77858. {
  77859. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  77860. * to pending_buf_size, and each stored block has a 5 byte header:
  77861. */
  77862. ulg max_block_size = 0xffff;
  77863. ulg max_start;
  77864. if (max_block_size > s->pending_buf_size - 5) {
  77865. max_block_size = s->pending_buf_size - 5;
  77866. }
  77867. /* Copy as much as possible from input to output: */
  77868. for (;;) {
  77869. /* Fill the window as much as possible: */
  77870. if (s->lookahead <= 1) {
  77871. Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  77872. s->block_start >= (long)s->w_size, "slide too late");
  77873. fill_window(s);
  77874. if (s->lookahead == 0 && flush == Z_NO_FLUSH) return need_more;
  77875. if (s->lookahead == 0) break; /* flush the current block */
  77876. }
  77877. Assert(s->block_start >= 0L, "block gone");
  77878. s->strstart += s->lookahead;
  77879. s->lookahead = 0;
  77880. /* Emit a stored block if pending_buf will be full: */
  77881. max_start = s->block_start + max_block_size;
  77882. if (s->strstart == 0 || (ulg)s->strstart >= max_start) {
  77883. /* strstart == 0 is possible when wraparound on 16-bit machine */
  77884. s->lookahead = (uInt)(s->strstart - max_start);
  77885. s->strstart = (uInt)max_start;
  77886. FLUSH_BLOCK(s, 0);
  77887. }
  77888. /* Flush if we may have to slide, otherwise block_start may become
  77889. * negative and the data will be gone:
  77890. */
  77891. if (s->strstart - (uInt)s->block_start >= MAX_DIST(s)) {
  77892. FLUSH_BLOCK(s, 0);
  77893. }
  77894. }
  77895. FLUSH_BLOCK(s, flush == Z_FINISH);
  77896. return flush == Z_FINISH ? finish_done : block_done;
  77897. }
  77898. /* ===========================================================================
  77899. * Compress as much as possible from the input stream, return the current
  77900. * block state.
  77901. * This function does not perform lazy evaluation of matches and inserts
  77902. * new strings in the dictionary only for unmatched strings or for short
  77903. * matches. It is used only for the fast compression options.
  77904. */
  77905. local block_state deflate_fast(deflate_state *s, int flush)
  77906. {
  77907. IPos hash_head = NIL; /* head of the hash chain */
  77908. int bflush; /* set if current block must be flushed */
  77909. for (;;) {
  77910. /* Make sure that we always have enough lookahead, except
  77911. * at the end of the input file. We need MAX_MATCH bytes
  77912. * for the next match, plus MIN_MATCH bytes to insert the
  77913. * string following the next match.
  77914. */
  77915. if (s->lookahead < MIN_LOOKAHEAD) {
  77916. fill_window(s);
  77917. if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
  77918. return need_more;
  77919. }
  77920. if (s->lookahead == 0) break; /* flush the current block */
  77921. }
  77922. /* Insert the string window[strstart .. strstart+2] in the
  77923. * dictionary, and set hash_head to the head of the hash chain:
  77924. */
  77925. if (s->lookahead >= MIN_MATCH) {
  77926. INSERT_STRING(s, s->strstart, hash_head);
  77927. }
  77928. /* Find the longest match, discarding those <= prev_length.
  77929. * At this point we have always match_length < MIN_MATCH
  77930. */
  77931. if (hash_head != NIL && s->strstart - hash_head <= MAX_DIST(s)) {
  77932. /* To simplify the code, we prevent matches with the string
  77933. * of window index 0 (in particular we have to avoid a match
  77934. * of the string with itself at the start of the input file).
  77935. */
  77936. #ifdef FASTEST
  77937. if ((s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) ||
  77938. (s->strategy == Z_RLE && s->strstart - hash_head == 1)) {
  77939. s->match_length = longest_match_fast (s, hash_head);
  77940. }
  77941. #else
  77942. if (s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) {
  77943. s->match_length = longest_match (s, hash_head);
  77944. } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) {
  77945. s->match_length = longest_match_fast (s, hash_head);
  77946. }
  77947. #endif
  77948. /* longest_match() or longest_match_fast() sets match_start */
  77949. }
  77950. if (s->match_length >= MIN_MATCH) {
  77951. check_match(s, s->strstart, s->match_start, s->match_length);
  77952. _tr_tally_dist(s, s->strstart - s->match_start,
  77953. s->match_length - MIN_MATCH, bflush);
  77954. s->lookahead -= s->match_length;
  77955. /* Insert new strings in the hash table only if the match length
  77956. * is not too large. This saves time but degrades compression.
  77957. */
  77958. #ifndef FASTEST
  77959. if (s->match_length <= s->max_insert_length &&
  77960. s->lookahead >= MIN_MATCH) {
  77961. s->match_length--; /* string at strstart already in table */
  77962. do {
  77963. s->strstart++;
  77964. INSERT_STRING(s, s->strstart, hash_head);
  77965. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  77966. * always MIN_MATCH bytes ahead.
  77967. */
  77968. } while (--s->match_length != 0);
  77969. s->strstart++;
  77970. } else
  77971. #endif
  77972. {
  77973. s->strstart += s->match_length;
  77974. s->match_length = 0;
  77975. s->ins_h = s->window[s->strstart];
  77976. UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
  77977. #if MIN_MATCH != 3
  77978. Call UPDATE_HASH() MIN_MATCH-3 more times
  77979. #endif
  77980. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  77981. * matter since it will be recomputed at next deflate call.
  77982. */
  77983. }
  77984. } else {
  77985. /* No match, output a literal byte */
  77986. Tracevv((stderr,"%c", s->window[s->strstart]));
  77987. _tr_tally_lit (s, s->window[s->strstart], bflush);
  77988. s->lookahead--;
  77989. s->strstart++;
  77990. }
  77991. if (bflush) FLUSH_BLOCK(s, 0);
  77992. }
  77993. FLUSH_BLOCK(s, flush == Z_FINISH);
  77994. return flush == Z_FINISH ? finish_done : block_done;
  77995. }
  77996. #ifndef FASTEST
  77997. /* ===========================================================================
  77998. * Same as above, but achieves better compression. We use a lazy
  77999. * evaluation for matches: a match is finally adopted only if there is
  78000. * no better match at the next window position.
  78001. */
  78002. local block_state deflate_slow(deflate_state *s, int flush)
  78003. {
  78004. IPos hash_head = NIL; /* head of hash chain */
  78005. int bflush; /* set if current block must be flushed */
  78006. /* Process the input block. */
  78007. for (;;) {
  78008. /* Make sure that we always have enough lookahead, except
  78009. * at the end of the input file. We need MAX_MATCH bytes
  78010. * for the next match, plus MIN_MATCH bytes to insert the
  78011. * string following the next match.
  78012. */
  78013. if (s->lookahead < MIN_LOOKAHEAD) {
  78014. fill_window(s);
  78015. if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
  78016. return need_more;
  78017. }
  78018. if (s->lookahead == 0) break; /* flush the current block */
  78019. }
  78020. /* Insert the string window[strstart .. strstart+2] in the
  78021. * dictionary, and set hash_head to the head of the hash chain:
  78022. */
  78023. if (s->lookahead >= MIN_MATCH) {
  78024. INSERT_STRING(s, s->strstart, hash_head);
  78025. }
  78026. /* Find the longest match, discarding those <= prev_length.
  78027. */
  78028. s->prev_length = s->match_length, s->prev_match = s->match_start;
  78029. s->match_length = MIN_MATCH-1;
  78030. if (hash_head != NIL && s->prev_length < s->max_lazy_match &&
  78031. s->strstart - hash_head <= MAX_DIST(s)) {
  78032. /* To simplify the code, we prevent matches with the string
  78033. * of window index 0 (in particular we have to avoid a match
  78034. * of the string with itself at the start of the input file).
  78035. */
  78036. if (s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) {
  78037. s->match_length = longest_match (s, hash_head);
  78038. } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) {
  78039. s->match_length = longest_match_fast (s, hash_head);
  78040. }
  78041. /* longest_match() or longest_match_fast() sets match_start */
  78042. if (s->match_length <= 5 && (s->strategy == Z_FILTERED
  78043. #if TOO_FAR <= 32767
  78044. || (s->match_length == MIN_MATCH &&
  78045. s->strstart - s->match_start > TOO_FAR)
  78046. #endif
  78047. )) {
  78048. /* If prev_match is also MIN_MATCH, match_start is garbage
  78049. * but we will ignore the current match anyway.
  78050. */
  78051. s->match_length = MIN_MATCH-1;
  78052. }
  78053. }
  78054. /* If there was a match at the previous step and the current
  78055. * match is not better, output the previous match:
  78056. */
  78057. if (s->prev_length >= MIN_MATCH && s->match_length <= s->prev_length) {
  78058. uInt max_insert = s->strstart + s->lookahead - MIN_MATCH;
  78059. /* Do not insert strings in hash table beyond this. */
  78060. check_match(s, s->strstart-1, s->prev_match, s->prev_length);
  78061. _tr_tally_dist(s, s->strstart -1 - s->prev_match,
  78062. s->prev_length - MIN_MATCH, bflush);
  78063. /* Insert in hash table all strings up to the end of the match.
  78064. * strstart-1 and strstart are already inserted. If there is not
  78065. * enough lookahead, the last two strings are not inserted in
  78066. * the hash table.
  78067. */
  78068. s->lookahead -= s->prev_length-1;
  78069. s->prev_length -= 2;
  78070. do {
  78071. if (++s->strstart <= max_insert) {
  78072. INSERT_STRING(s, s->strstart, hash_head);
  78073. }
  78074. } while (--s->prev_length != 0);
  78075. s->match_available = 0;
  78076. s->match_length = MIN_MATCH-1;
  78077. s->strstart++;
  78078. if (bflush) FLUSH_BLOCK(s, 0);
  78079. } else if (s->match_available) {
  78080. /* If there was no match at the previous position, output a
  78081. * single literal. If there was a match but the current match
  78082. * is longer, truncate the previous match to a single literal.
  78083. */
  78084. Tracevv((stderr,"%c", s->window[s->strstart-1]));
  78085. _tr_tally_lit(s, s->window[s->strstart-1], bflush);
  78086. if (bflush) {
  78087. FLUSH_BLOCK_ONLY(s, 0);
  78088. }
  78089. s->strstart++;
  78090. s->lookahead--;
  78091. if (s->strm->avail_out == 0) return need_more;
  78092. } else {
  78093. /* There is no previous match to compare with, wait for
  78094. * the next step to decide.
  78095. */
  78096. s->match_available = 1;
  78097. s->strstart++;
  78098. s->lookahead--;
  78099. }
  78100. }
  78101. Assert (flush != Z_NO_FLUSH, "no flush?");
  78102. if (s->match_available) {
  78103. Tracevv((stderr,"%c", s->window[s->strstart-1]));
  78104. _tr_tally_lit(s, s->window[s->strstart-1], bflush);
  78105. s->match_available = 0;
  78106. }
  78107. FLUSH_BLOCK(s, flush == Z_FINISH);
  78108. return flush == Z_FINISH ? finish_done : block_done;
  78109. }
  78110. #endif /* FASTEST */
  78111. #if 0
  78112. /* ===========================================================================
  78113. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  78114. * one. Do not maintain a hash table. (It will be regenerated if this run of
  78115. * deflate switches away from Z_RLE.)
  78116. */
  78117. local block_state deflate_rle(s, flush)
  78118. deflate_state *s;
  78119. int flush;
  78120. {
  78121. int bflush; /* set if current block must be flushed */
  78122. uInt run; /* length of run */
  78123. uInt max; /* maximum length of run */
  78124. uInt prev; /* byte at distance one to match */
  78125. Bytef *scan; /* scan for end of run */
  78126. for (;;) {
  78127. /* Make sure that we always have enough lookahead, except
  78128. * at the end of the input file. We need MAX_MATCH bytes
  78129. * for the longest encodable run.
  78130. */
  78131. if (s->lookahead < MAX_MATCH) {
  78132. fill_window(s);
  78133. if (s->lookahead < MAX_MATCH && flush == Z_NO_FLUSH) {
  78134. return need_more;
  78135. }
  78136. if (s->lookahead == 0) break; /* flush the current block */
  78137. }
  78138. /* See how many times the previous byte repeats */
  78139. run = 0;
  78140. if (s->strstart > 0) { /* if there is a previous byte, that is */
  78141. max = s->lookahead < MAX_MATCH ? s->lookahead : MAX_MATCH;
  78142. scan = s->window + s->strstart - 1;
  78143. prev = *scan++;
  78144. do {
  78145. if (*scan++ != prev)
  78146. break;
  78147. } while (++run < max);
  78148. }
  78149. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  78150. if (run >= MIN_MATCH) {
  78151. check_match(s, s->strstart, s->strstart - 1, run);
  78152. _tr_tally_dist(s, 1, run - MIN_MATCH, bflush);
  78153. s->lookahead -= run;
  78154. s->strstart += run;
  78155. } else {
  78156. /* No match, output a literal byte */
  78157. Tracevv((stderr,"%c", s->window[s->strstart]));
  78158. _tr_tally_lit (s, s->window[s->strstart], bflush);
  78159. s->lookahead--;
  78160. s->strstart++;
  78161. }
  78162. if (bflush) FLUSH_BLOCK(s, 0);
  78163. }
  78164. FLUSH_BLOCK(s, flush == Z_FINISH);
  78165. return flush == Z_FINISH ? finish_done : block_done;
  78166. }
  78167. #endif
  78168. /********* End of inlined file: deflate.c *********/
  78169. /********* Start of inlined file: inffast.c *********/
  78170. /********* Start of inlined file: inftrees.h *********/
  78171. /* WARNING: this file should *not* be used by applications. It is
  78172. part of the implementation of the compression library and is
  78173. subject to change. Applications should only use zlib.h.
  78174. */
  78175. #ifndef _INFTREES_H_
  78176. #define _INFTREES_H_
  78177. /* Structure for decoding tables. Each entry provides either the
  78178. information needed to do the operation requested by the code that
  78179. indexed that table entry, or it provides a pointer to another
  78180. table that indexes more bits of the code. op indicates whether
  78181. the entry is a pointer to another table, a literal, a length or
  78182. distance, an end-of-block, or an invalid code. For a table
  78183. pointer, the low four bits of op is the number of index bits of
  78184. that table. For a length or distance, the low four bits of op
  78185. is the number of extra bits to get after the code. bits is
  78186. the number of bits in this code or part of the code to drop off
  78187. of the bit buffer. val is the actual byte to output in the case
  78188. of a literal, the base length or distance, or the offset from
  78189. the current table to the next table. Each entry is four bytes. */
  78190. typedef struct {
  78191. unsigned char op; /* operation, extra bits, table bits */
  78192. unsigned char bits; /* bits in this part of the code */
  78193. unsigned short val; /* offset in table or code value */
  78194. } code;
  78195. /* op values as set by inflate_table():
  78196. 00000000 - literal
  78197. 0000tttt - table link, tttt != 0 is the number of table index bits
  78198. 0001eeee - length or distance, eeee is the number of extra bits
  78199. 01100000 - end of block
  78200. 01000000 - invalid code
  78201. */
  78202. /* Maximum size of dynamic tree. The maximum found in a long but non-
  78203. exhaustive search was 1444 code structures (852 for length/literals
  78204. and 592 for distances, the latter actually the result of an
  78205. exhaustive search). The true maximum is not known, but the value
  78206. below is more than safe. */
  78207. #define ENOUGH 2048
  78208. #define MAXD 592
  78209. /* Type of code to build for inftable() */
  78210. typedef enum {
  78211. CODES,
  78212. LENS,
  78213. DISTS
  78214. } codetype;
  78215. extern int inflate_table OF((codetype type, unsigned short FAR *lens,
  78216. unsigned codes, code FAR * FAR *table,
  78217. unsigned FAR *bits, unsigned short FAR *work));
  78218. #endif
  78219. /********* End of inlined file: inftrees.h *********/
  78220. /********* Start of inlined file: inflate.h *********/
  78221. /* WARNING: this file should *not* be used by applications. It is
  78222. part of the implementation of the compression library and is
  78223. subject to change. Applications should only use zlib.h.
  78224. */
  78225. #ifndef _INFLATE_H_
  78226. #define _INFLATE_H_
  78227. /* define NO_GZIP when compiling if you want to disable gzip header and
  78228. trailer decoding by inflate(). NO_GZIP would be used to avoid linking in
  78229. the crc code when it is not needed. For shared libraries, gzip decoding
  78230. should be left enabled. */
  78231. #ifndef NO_GZIP
  78232. # define GUNZIP
  78233. #endif
  78234. /* Possible inflate modes between inflate() calls */
  78235. typedef enum {
  78236. HEAD, /* i: waiting for magic header */
  78237. FLAGS, /* i: waiting for method and flags (gzip) */
  78238. TIME, /* i: waiting for modification time (gzip) */
  78239. OS, /* i: waiting for extra flags and operating system (gzip) */
  78240. EXLEN, /* i: waiting for extra length (gzip) */
  78241. EXTRA, /* i: waiting for extra bytes (gzip) */
  78242. NAME, /* i: waiting for end of file name (gzip) */
  78243. COMMENT, /* i: waiting for end of comment (gzip) */
  78244. HCRC, /* i: waiting for header crc (gzip) */
  78245. DICTID, /* i: waiting for dictionary check value */
  78246. DICT, /* waiting for inflateSetDictionary() call */
  78247. TYPE, /* i: waiting for type bits, including last-flag bit */
  78248. TYPEDO, /* i: same, but skip check to exit inflate on new block */
  78249. STORED, /* i: waiting for stored size (length and complement) */
  78250. COPY, /* i/o: waiting for input or output to copy stored block */
  78251. TABLE, /* i: waiting for dynamic block table lengths */
  78252. LENLENS, /* i: waiting for code length code lengths */
  78253. CODELENS, /* i: waiting for length/lit and distance code lengths */
  78254. LEN, /* i: waiting for length/lit code */
  78255. LENEXT, /* i: waiting for length extra bits */
  78256. DIST, /* i: waiting for distance code */
  78257. DISTEXT, /* i: waiting for distance extra bits */
  78258. MATCH, /* o: waiting for output space to copy string */
  78259. LIT, /* o: waiting for output space to write literal */
  78260. CHECK, /* i: waiting for 32-bit check value */
  78261. LENGTH, /* i: waiting for 32-bit length (gzip) */
  78262. DONE, /* finished check, done -- remain here until reset */
  78263. BAD, /* got a data error -- remain here until reset */
  78264. MEM, /* got an inflate() memory error -- remain here until reset */
  78265. SYNC /* looking for synchronization bytes to restart inflate() */
  78266. } inflate_mode;
  78267. /*
  78268. State transitions between above modes -
  78269. (most modes can go to the BAD or MEM mode -- not shown for clarity)
  78270. Process header:
  78271. HEAD -> (gzip) or (zlib)
  78272. (gzip) -> FLAGS -> TIME -> OS -> EXLEN -> EXTRA -> NAME
  78273. NAME -> COMMENT -> HCRC -> TYPE
  78274. (zlib) -> DICTID or TYPE
  78275. DICTID -> DICT -> TYPE
  78276. Read deflate blocks:
  78277. TYPE -> STORED or TABLE or LEN or CHECK
  78278. STORED -> COPY -> TYPE
  78279. TABLE -> LENLENS -> CODELENS -> LEN
  78280. Read deflate codes:
  78281. LEN -> LENEXT or LIT or TYPE
  78282. LENEXT -> DIST -> DISTEXT -> MATCH -> LEN
  78283. LIT -> LEN
  78284. Process trailer:
  78285. CHECK -> LENGTH -> DONE
  78286. */
  78287. /* state maintained between inflate() calls. Approximately 7K bytes. */
  78288. struct inflate_state {
  78289. inflate_mode mode; /* current inflate mode */
  78290. int last; /* true if processing last block */
  78291. int wrap; /* bit 0 true for zlib, bit 1 true for gzip */
  78292. int havedict; /* true if dictionary provided */
  78293. int flags; /* gzip header method and flags (0 if zlib) */
  78294. unsigned dmax; /* zlib header max distance (INFLATE_STRICT) */
  78295. unsigned long check; /* protected copy of check value */
  78296. unsigned long total; /* protected copy of output count */
  78297. gz_headerp head; /* where to save gzip header information */
  78298. /* sliding window */
  78299. unsigned wbits; /* log base 2 of requested window size */
  78300. unsigned wsize; /* window size or zero if not using window */
  78301. unsigned whave; /* valid bytes in the window */
  78302. unsigned write; /* window write index */
  78303. unsigned char FAR *window; /* allocated sliding window, if needed */
  78304. /* bit accumulator */
  78305. unsigned long hold; /* input bit accumulator */
  78306. unsigned bits; /* number of bits in "in" */
  78307. /* for string and stored block copying */
  78308. unsigned length; /* literal or length of data to copy */
  78309. unsigned offset; /* distance back to copy string from */
  78310. /* for table and code decoding */
  78311. unsigned extra; /* extra bits needed */
  78312. /* fixed and dynamic code tables */
  78313. code const FAR *lencode; /* starting table for length/literal codes */
  78314. code const FAR *distcode; /* starting table for distance codes */
  78315. unsigned lenbits; /* index bits for lencode */
  78316. unsigned distbits; /* index bits for distcode */
  78317. /* dynamic table building */
  78318. unsigned ncode; /* number of code length code lengths */
  78319. unsigned nlen; /* number of length code lengths */
  78320. unsigned ndist; /* number of distance code lengths */
  78321. unsigned have; /* number of code lengths in lens[] */
  78322. code FAR *next; /* next available space in codes[] */
  78323. unsigned short lens[320]; /* temporary storage for code lengths */
  78324. unsigned short work[288]; /* work area for code table building */
  78325. code codes[ENOUGH]; /* space for code tables */
  78326. };
  78327. #endif
  78328. /********* End of inlined file: inflate.h *********/
  78329. /********* Start of inlined file: inffast.h *********/
  78330. /* WARNING: this file should *not* be used by applications. It is
  78331. part of the implementation of the compression library and is
  78332. subject to change. Applications should only use zlib.h.
  78333. */
  78334. void inflate_fast OF((z_streamp strm, unsigned start));
  78335. /********* End of inlined file: inffast.h *********/
  78336. #ifndef ASMINF
  78337. /* Allow machine dependent optimization for post-increment or pre-increment.
  78338. Based on testing to date,
  78339. Pre-increment preferred for:
  78340. - PowerPC G3 (Adler)
  78341. - MIPS R5000 (Randers-Pehrson)
  78342. Post-increment preferred for:
  78343. - none
  78344. No measurable difference:
  78345. - Pentium III (Anderson)
  78346. - M68060 (Nikl)
  78347. */
  78348. #ifdef POSTINC
  78349. # define OFF 0
  78350. # define PUP(a) *(a)++
  78351. #else
  78352. # define OFF 1
  78353. # define PUP(a) *++(a)
  78354. #endif
  78355. /*
  78356. Decode literal, length, and distance codes and write out the resulting
  78357. literal and match bytes until either not enough input or output is
  78358. available, an end-of-block is encountered, or a data error is encountered.
  78359. When large enough input and output buffers are supplied to inflate(), for
  78360. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  78361. inflate execution time is spent in this routine.
  78362. Entry assumptions:
  78363. state->mode == LEN
  78364. strm->avail_in >= 6
  78365. strm->avail_out >= 258
  78366. start >= strm->avail_out
  78367. state->bits < 8
  78368. On return, state->mode is one of:
  78369. LEN -- ran out of enough output space or enough available input
  78370. TYPE -- reached end of block code, inflate() to interpret next block
  78371. BAD -- error in block data
  78372. Notes:
  78373. - The maximum input bits used by a length/distance pair is 15 bits for the
  78374. length code, 5 bits for the length extra, 15 bits for the distance code,
  78375. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  78376. Therefore if strm->avail_in >= 6, then there is enough input to avoid
  78377. checking for available input while decoding.
  78378. - The maximum bytes that a single length/distance pair can output is 258
  78379. bytes, which is the maximum length that can be coded. inflate_fast()
  78380. requires strm->avail_out >= 258 for each loop to avoid checking for
  78381. output space.
  78382. */
  78383. void inflate_fast (z_streamp strm, unsigned start)
  78384. {
  78385. struct inflate_state FAR *state;
  78386. unsigned char FAR *in; /* local strm->next_in */
  78387. unsigned char FAR *last; /* while in < last, enough input available */
  78388. unsigned char FAR *out; /* local strm->next_out */
  78389. unsigned char FAR *beg; /* inflate()'s initial strm->next_out */
  78390. unsigned char FAR *end; /* while out < end, enough space available */
  78391. #ifdef INFLATE_STRICT
  78392. unsigned dmax; /* maximum distance from zlib header */
  78393. #endif
  78394. unsigned wsize; /* window size or zero if not using window */
  78395. unsigned whave; /* valid bytes in the window */
  78396. unsigned write; /* window write index */
  78397. unsigned char FAR *window; /* allocated sliding window, if wsize != 0 */
  78398. unsigned long hold; /* local strm->hold */
  78399. unsigned bits; /* local strm->bits */
  78400. code const FAR *lcode; /* local strm->lencode */
  78401. code const FAR *dcode; /* local strm->distcode */
  78402. unsigned lmask; /* mask for first level of length codes */
  78403. unsigned dmask; /* mask for first level of distance codes */
  78404. code thisx; /* retrieved table entry */
  78405. unsigned op; /* code bits, operation, extra bits, or */
  78406. /* window position, window bytes to copy */
  78407. unsigned len; /* match length, unused bytes */
  78408. unsigned dist; /* match distance */
  78409. unsigned char FAR *from; /* where to copy match from */
  78410. /* copy state to local variables */
  78411. state = (struct inflate_state FAR *)strm->state;
  78412. in = strm->next_in - OFF;
  78413. last = in + (strm->avail_in - 5);
  78414. out = strm->next_out - OFF;
  78415. beg = out - (start - strm->avail_out);
  78416. end = out + (strm->avail_out - 257);
  78417. #ifdef INFLATE_STRICT
  78418. dmax = state->dmax;
  78419. #endif
  78420. wsize = state->wsize;
  78421. whave = state->whave;
  78422. write = state->write;
  78423. window = state->window;
  78424. hold = state->hold;
  78425. bits = state->bits;
  78426. lcode = state->lencode;
  78427. dcode = state->distcode;
  78428. lmask = (1U << state->lenbits) - 1;
  78429. dmask = (1U << state->distbits) - 1;
  78430. /* decode literals and length/distances until end-of-block or not enough
  78431. input data or output space */
  78432. do {
  78433. if (bits < 15) {
  78434. hold += (unsigned long)(PUP(in)) << bits;
  78435. bits += 8;
  78436. hold += (unsigned long)(PUP(in)) << bits;
  78437. bits += 8;
  78438. }
  78439. thisx = lcode[hold & lmask];
  78440. dolen:
  78441. op = (unsigned)(thisx.bits);
  78442. hold >>= op;
  78443. bits -= op;
  78444. op = (unsigned)(thisx.op);
  78445. if (op == 0) { /* literal */
  78446. Tracevv((stderr, thisx.val >= 0x20 && thisx.val < 0x7f ?
  78447. "inflate: literal '%c'\n" :
  78448. "inflate: literal 0x%02x\n", thisx.val));
  78449. PUP(out) = (unsigned char)(thisx.val);
  78450. }
  78451. else if (op & 16) { /* length base */
  78452. len = (unsigned)(thisx.val);
  78453. op &= 15; /* number of extra bits */
  78454. if (op) {
  78455. if (bits < op) {
  78456. hold += (unsigned long)(PUP(in)) << bits;
  78457. bits += 8;
  78458. }
  78459. len += (unsigned)hold & ((1U << op) - 1);
  78460. hold >>= op;
  78461. bits -= op;
  78462. }
  78463. Tracevv((stderr, "inflate: length %u\n", len));
  78464. if (bits < 15) {
  78465. hold += (unsigned long)(PUP(in)) << bits;
  78466. bits += 8;
  78467. hold += (unsigned long)(PUP(in)) << bits;
  78468. bits += 8;
  78469. }
  78470. thisx = dcode[hold & dmask];
  78471. dodist:
  78472. op = (unsigned)(thisx.bits);
  78473. hold >>= op;
  78474. bits -= op;
  78475. op = (unsigned)(thisx.op);
  78476. if (op & 16) { /* distance base */
  78477. dist = (unsigned)(thisx.val);
  78478. op &= 15; /* number of extra bits */
  78479. if (bits < op) {
  78480. hold += (unsigned long)(PUP(in)) << bits;
  78481. bits += 8;
  78482. if (bits < op) {
  78483. hold += (unsigned long)(PUP(in)) << bits;
  78484. bits += 8;
  78485. }
  78486. }
  78487. dist += (unsigned)hold & ((1U << op) - 1);
  78488. #ifdef INFLATE_STRICT
  78489. if (dist > dmax) {
  78490. strm->msg = (char *)"invalid distance too far back";
  78491. state->mode = BAD;
  78492. break;
  78493. }
  78494. #endif
  78495. hold >>= op;
  78496. bits -= op;
  78497. Tracevv((stderr, "inflate: distance %u\n", dist));
  78498. op = (unsigned)(out - beg); /* max distance in output */
  78499. if (dist > op) { /* see if copy from window */
  78500. op = dist - op; /* distance back in window */
  78501. if (op > whave) {
  78502. strm->msg = (char *)"invalid distance too far back";
  78503. state->mode = BAD;
  78504. break;
  78505. }
  78506. from = window - OFF;
  78507. if (write == 0) { /* very common case */
  78508. from += wsize - op;
  78509. if (op < len) { /* some from window */
  78510. len -= op;
  78511. do {
  78512. PUP(out) = PUP(from);
  78513. } while (--op);
  78514. from = out - dist; /* rest from output */
  78515. }
  78516. }
  78517. else if (write < op) { /* wrap around window */
  78518. from += wsize + write - op;
  78519. op -= write;
  78520. if (op < len) { /* some from end of window */
  78521. len -= op;
  78522. do {
  78523. PUP(out) = PUP(from);
  78524. } while (--op);
  78525. from = window - OFF;
  78526. if (write < len) { /* some from start of window */
  78527. op = write;
  78528. len -= op;
  78529. do {
  78530. PUP(out) = PUP(from);
  78531. } while (--op);
  78532. from = out - dist; /* rest from output */
  78533. }
  78534. }
  78535. }
  78536. else { /* contiguous in window */
  78537. from += write - op;
  78538. if (op < len) { /* some from window */
  78539. len -= op;
  78540. do {
  78541. PUP(out) = PUP(from);
  78542. } while (--op);
  78543. from = out - dist; /* rest from output */
  78544. }
  78545. }
  78546. while (len > 2) {
  78547. PUP(out) = PUP(from);
  78548. PUP(out) = PUP(from);
  78549. PUP(out) = PUP(from);
  78550. len -= 3;
  78551. }
  78552. if (len) {
  78553. PUP(out) = PUP(from);
  78554. if (len > 1)
  78555. PUP(out) = PUP(from);
  78556. }
  78557. }
  78558. else {
  78559. from = out - dist; /* copy direct from output */
  78560. do { /* minimum length is three */
  78561. PUP(out) = PUP(from);
  78562. PUP(out) = PUP(from);
  78563. PUP(out) = PUP(from);
  78564. len -= 3;
  78565. } while (len > 2);
  78566. if (len) {
  78567. PUP(out) = PUP(from);
  78568. if (len > 1)
  78569. PUP(out) = PUP(from);
  78570. }
  78571. }
  78572. }
  78573. else if ((op & 64) == 0) { /* 2nd level distance code */
  78574. thisx = dcode[thisx.val + (hold & ((1U << op) - 1))];
  78575. goto dodist;
  78576. }
  78577. else {
  78578. strm->msg = (char *)"invalid distance code";
  78579. state->mode = BAD;
  78580. break;
  78581. }
  78582. }
  78583. else if ((op & 64) == 0) { /* 2nd level length code */
  78584. thisx = lcode[thisx.val + (hold & ((1U << op) - 1))];
  78585. goto dolen;
  78586. }
  78587. else if (op & 32) { /* end-of-block */
  78588. Tracevv((stderr, "inflate: end of block\n"));
  78589. state->mode = TYPE;
  78590. break;
  78591. }
  78592. else {
  78593. strm->msg = (char *)"invalid literal/length code";
  78594. state->mode = BAD;
  78595. break;
  78596. }
  78597. } while (in < last && out < end);
  78598. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  78599. len = bits >> 3;
  78600. in -= len;
  78601. bits -= len << 3;
  78602. hold &= (1U << bits) - 1;
  78603. /* update state and return */
  78604. strm->next_in = in + OFF;
  78605. strm->next_out = out + OFF;
  78606. strm->avail_in = (unsigned)(in < last ? 5 + (last - in) : 5 - (in - last));
  78607. strm->avail_out = (unsigned)(out < end ?
  78608. 257 + (end - out) : 257 - (out - end));
  78609. state->hold = hold;
  78610. state->bits = bits;
  78611. return;
  78612. }
  78613. /*
  78614. inflate_fast() speedups that turned out slower (on a PowerPC G3 750CXe):
  78615. - Using bit fields for code structure
  78616. - Different op definition to avoid & for extra bits (do & for table bits)
  78617. - Three separate decoding do-loops for direct, window, and write == 0
  78618. - Special case for distance > 1 copies to do overlapped load and store copy
  78619. - Explicit branch predictions (based on measured branch probabilities)
  78620. - Deferring match copy and interspersed it with decoding subsequent codes
  78621. - Swapping literal/length else
  78622. - Swapping window/direct else
  78623. - Larger unrolled copy loops (three is about right)
  78624. - Moving len -= 3 statement into middle of loop
  78625. */
  78626. #endif /* !ASMINF */
  78627. /********* End of inlined file: inffast.c *********/
  78628. #undef PULLBYTE
  78629. #undef LOAD
  78630. #undef RESTORE
  78631. #undef INITBITS
  78632. #undef NEEDBITS
  78633. #undef DROPBITS
  78634. #undef BYTEBITS
  78635. /********* Start of inlined file: inflate.c *********/
  78636. /*
  78637. * Change history:
  78638. *
  78639. * 1.2.beta0 24 Nov 2002
  78640. * - First version -- complete rewrite of inflate to simplify code, avoid
  78641. * creation of window when not needed, minimize use of window when it is
  78642. * needed, make inffast.c even faster, implement gzip decoding, and to
  78643. * improve code readability and style over the previous zlib inflate code
  78644. *
  78645. * 1.2.beta1 25 Nov 2002
  78646. * - Use pointers for available input and output checking in inffast.c
  78647. * - Remove input and output counters in inffast.c
  78648. * - Change inffast.c entry and loop from avail_in >= 7 to >= 6
  78649. * - Remove unnecessary second byte pull from length extra in inffast.c
  78650. * - Unroll direct copy to three copies per loop in inffast.c
  78651. *
  78652. * 1.2.beta2 4 Dec 2002
  78653. * - Change external routine names to reduce potential conflicts
  78654. * - Correct filename to inffixed.h for fixed tables in inflate.c
  78655. * - Make hbuf[] unsigned char to match parameter type in inflate.c
  78656. * - Change strm->next_out[-state->offset] to *(strm->next_out - state->offset)
  78657. * to avoid negation problem on Alphas (64 bit) in inflate.c
  78658. *
  78659. * 1.2.beta3 22 Dec 2002
  78660. * - Add comments on state->bits assertion in inffast.c
  78661. * - Add comments on op field in inftrees.h
  78662. * - Fix bug in reuse of allocated window after inflateReset()
  78663. * - Remove bit fields--back to byte structure for speed
  78664. * - Remove distance extra == 0 check in inflate_fast()--only helps for lengths
  78665. * - Change post-increments to pre-increments in inflate_fast(), PPC biased?
  78666. * - Add compile time option, POSTINC, to use post-increments instead (Intel?)
  78667. * - Make MATCH copy in inflate() much faster for when inflate_fast() not used
  78668. * - Use local copies of stream next and avail values, as well as local bit
  78669. * buffer and bit count in inflate()--for speed when inflate_fast() not used
  78670. *
  78671. * 1.2.beta4 1 Jan 2003
  78672. * - Split ptr - 257 statements in inflate_table() to avoid compiler warnings
  78673. * - Move a comment on output buffer sizes from inffast.c to inflate.c
  78674. * - Add comments in inffast.c to introduce the inflate_fast() routine
  78675. * - Rearrange window copies in inflate_fast() for speed and simplification
  78676. * - Unroll last copy for window match in inflate_fast()
  78677. * - Use local copies of window variables in inflate_fast() for speed
  78678. * - Pull out common write == 0 case for speed in inflate_fast()
  78679. * - Make op and len in inflate_fast() unsigned for consistency
  78680. * - Add FAR to lcode and dcode declarations in inflate_fast()
  78681. * - Simplified bad distance check in inflate_fast()
  78682. * - Added inflateBackInit(), inflateBack(), and inflateBackEnd() in new
  78683. * source file infback.c to provide a call-back interface to inflate for
  78684. * programs like gzip and unzip -- uses window as output buffer to avoid
  78685. * window copying
  78686. *
  78687. * 1.2.beta5 1 Jan 2003
  78688. * - Improved inflateBack() interface to allow the caller to provide initial
  78689. * input in strm.
  78690. * - Fixed stored blocks bug in inflateBack()
  78691. *
  78692. * 1.2.beta6 4 Jan 2003
  78693. * - Added comments in inffast.c on effectiveness of POSTINC
  78694. * - Typecasting all around to reduce compiler warnings
  78695. * - Changed loops from while (1) or do {} while (1) to for (;;), again to
  78696. * make compilers happy
  78697. * - Changed type of window in inflateBackInit() to unsigned char *
  78698. *
  78699. * 1.2.beta7 27 Jan 2003
  78700. * - Changed many types to unsigned or unsigned short to avoid warnings
  78701. * - Added inflateCopy() function
  78702. *
  78703. * 1.2.0 9 Mar 2003
  78704. * - Changed inflateBack() interface to provide separate opaque descriptors
  78705. * for the in() and out() functions
  78706. * - Changed inflateBack() argument and in_func typedef to swap the length
  78707. * and buffer address return values for the input function
  78708. * - Check next_in and next_out for Z_NULL on entry to inflate()
  78709. *
  78710. * The history for versions after 1.2.0 are in ChangeLog in zlib distribution.
  78711. */
  78712. /********* Start of inlined file: inffast.h *********/
  78713. /* WARNING: this file should *not* be used by applications. It is
  78714. part of the implementation of the compression library and is
  78715. subject to change. Applications should only use zlib.h.
  78716. */
  78717. void inflate_fast OF((z_streamp strm, unsigned start));
  78718. /********* End of inlined file: inffast.h *********/
  78719. #ifdef MAKEFIXED
  78720. # ifndef BUILDFIXED
  78721. # define BUILDFIXED
  78722. # endif
  78723. #endif
  78724. /* function prototypes */
  78725. local void fixedtables OF((struct inflate_state FAR *state));
  78726. local int updatewindow OF((z_streamp strm, unsigned out));
  78727. #ifdef BUILDFIXED
  78728. void makefixed OF((void));
  78729. #endif
  78730. local unsigned syncsearch OF((unsigned FAR *have, unsigned char FAR *buf,
  78731. unsigned len));
  78732. int ZEXPORT inflateReset (z_streamp strm)
  78733. {
  78734. struct inflate_state FAR *state;
  78735. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  78736. state = (struct inflate_state FAR *)strm->state;
  78737. strm->total_in = strm->total_out = state->total = 0;
  78738. strm->msg = Z_NULL;
  78739. strm->adler = 1; /* to support ill-conceived Java test suite */
  78740. state->mode = HEAD;
  78741. state->last = 0;
  78742. state->havedict = 0;
  78743. state->dmax = 32768U;
  78744. state->head = Z_NULL;
  78745. state->wsize = 0;
  78746. state->whave = 0;
  78747. state->write = 0;
  78748. state->hold = 0;
  78749. state->bits = 0;
  78750. state->lencode = state->distcode = state->next = state->codes;
  78751. Tracev((stderr, "inflate: reset\n"));
  78752. return Z_OK;
  78753. }
  78754. int ZEXPORT inflatePrime (z_streamp strm, int bits, int value)
  78755. {
  78756. struct inflate_state FAR *state;
  78757. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  78758. state = (struct inflate_state FAR *)strm->state;
  78759. if (bits > 16 || state->bits + bits > 32) return Z_STREAM_ERROR;
  78760. value &= (1L << bits) - 1;
  78761. state->hold += value << state->bits;
  78762. state->bits += bits;
  78763. return Z_OK;
  78764. }
  78765. int ZEXPORT inflateInit2_(z_streamp strm, int windowBits, const char *version, int stream_size)
  78766. {
  78767. struct inflate_state FAR *state;
  78768. if (version == Z_NULL || version[0] != ZLIB_VERSION[0] ||
  78769. stream_size != (int)(sizeof(z_stream)))
  78770. return Z_VERSION_ERROR;
  78771. if (strm == Z_NULL) return Z_STREAM_ERROR;
  78772. strm->msg = Z_NULL; /* in case we return an error */
  78773. if (strm->zalloc == (alloc_func)0) {
  78774. strm->zalloc = zcalloc;
  78775. strm->opaque = (voidpf)0;
  78776. }
  78777. if (strm->zfree == (free_func)0) strm->zfree = zcfree;
  78778. state = (struct inflate_state FAR *)
  78779. ZALLOC(strm, 1, sizeof(struct inflate_state));
  78780. if (state == Z_NULL) return Z_MEM_ERROR;
  78781. Tracev((stderr, "inflate: allocated\n"));
  78782. strm->state = (struct internal_state FAR *)state;
  78783. if (windowBits < 0) {
  78784. state->wrap = 0;
  78785. windowBits = -windowBits;
  78786. }
  78787. else {
  78788. state->wrap = (windowBits >> 4) + 1;
  78789. #ifdef GUNZIP
  78790. if (windowBits < 48) windowBits &= 15;
  78791. #endif
  78792. }
  78793. if (windowBits < 8 || windowBits > 15) {
  78794. ZFREE(strm, state);
  78795. strm->state = Z_NULL;
  78796. return Z_STREAM_ERROR;
  78797. }
  78798. state->wbits = (unsigned)windowBits;
  78799. state->window = Z_NULL;
  78800. return inflateReset(strm);
  78801. }
  78802. int ZEXPORT inflateInit_ (z_streamp strm, const char *version, int stream_size)
  78803. {
  78804. return inflateInit2_(strm, DEF_WBITS, version, stream_size);
  78805. }
  78806. /*
  78807. Return state with length and distance decoding tables and index sizes set to
  78808. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  78809. If BUILDFIXED is defined, then instead this routine builds the tables the
  78810. first time it's called, and returns those tables the first time and
  78811. thereafter. This reduces the size of the code by about 2K bytes, in
  78812. exchange for a little execution time. However, BUILDFIXED should not be
  78813. used for threaded applications, since the rewriting of the tables and virgin
  78814. may not be thread-safe.
  78815. */
  78816. local void fixedtables (struct inflate_state FAR *state)
  78817. {
  78818. #ifdef BUILDFIXED
  78819. static int virgin = 1;
  78820. static code *lenfix, *distfix;
  78821. static code fixed[544];
  78822. /* build fixed huffman tables if first call (may not be thread safe) */
  78823. if (virgin) {
  78824. unsigned sym, bits;
  78825. static code *next;
  78826. /* literal/length table */
  78827. sym = 0;
  78828. while (sym < 144) state->lens[sym++] = 8;
  78829. while (sym < 256) state->lens[sym++] = 9;
  78830. while (sym < 280) state->lens[sym++] = 7;
  78831. while (sym < 288) state->lens[sym++] = 8;
  78832. next = fixed;
  78833. lenfix = next;
  78834. bits = 9;
  78835. inflate_table(LENS, state->lens, 288, &(next), &(bits), state->work);
  78836. /* distance table */
  78837. sym = 0;
  78838. while (sym < 32) state->lens[sym++] = 5;
  78839. distfix = next;
  78840. bits = 5;
  78841. inflate_table(DISTS, state->lens, 32, &(next), &(bits), state->work);
  78842. /* do this just once */
  78843. virgin = 0;
  78844. }
  78845. #else /* !BUILDFIXED */
  78846. /********* Start of inlined file: inffixed.h *********/
  78847. /* inffixed.h -- table for decoding fixed codes
  78848. * Generated automatically by makefixed().
  78849. */
  78850. /* WARNING: this file should *not* be used by applications. It
  78851. is part of the implementation of the compression library and
  78852. is subject to change. Applications should only use zlib.h.
  78853. */
  78854. static const code lenfix[512] = {
  78855. {96,7,0},{0,8,80},{0,8,16},{20,8,115},{18,7,31},{0,8,112},{0,8,48},
  78856. {0,9,192},{16,7,10},{0,8,96},{0,8,32},{0,9,160},{0,8,0},{0,8,128},
  78857. {0,8,64},{0,9,224},{16,7,6},{0,8,88},{0,8,24},{0,9,144},{19,7,59},
  78858. {0,8,120},{0,8,56},{0,9,208},{17,7,17},{0,8,104},{0,8,40},{0,9,176},
  78859. {0,8,8},{0,8,136},{0,8,72},{0,9,240},{16,7,4},{0,8,84},{0,8,20},
  78860. {21,8,227},{19,7,43},{0,8,116},{0,8,52},{0,9,200},{17,7,13},{0,8,100},
  78861. {0,8,36},{0,9,168},{0,8,4},{0,8,132},{0,8,68},{0,9,232},{16,7,8},
  78862. {0,8,92},{0,8,28},{0,9,152},{20,7,83},{0,8,124},{0,8,60},{0,9,216},
  78863. {18,7,23},{0,8,108},{0,8,44},{0,9,184},{0,8,12},{0,8,140},{0,8,76},
  78864. {0,9,248},{16,7,3},{0,8,82},{0,8,18},{21,8,163},{19,7,35},{0,8,114},
  78865. {0,8,50},{0,9,196},{17,7,11},{0,8,98},{0,8,34},{0,9,164},{0,8,2},
  78866. {0,8,130},{0,8,66},{0,9,228},{16,7,7},{0,8,90},{0,8,26},{0,9,148},
  78867. {20,7,67},{0,8,122},{0,8,58},{0,9,212},{18,7,19},{0,8,106},{0,8,42},
  78868. {0,9,180},{0,8,10},{0,8,138},{0,8,74},{0,9,244},{16,7,5},{0,8,86},
  78869. {0,8,22},{64,8,0},{19,7,51},{0,8,118},{0,8,54},{0,9,204},{17,7,15},
  78870. {0,8,102},{0,8,38},{0,9,172},{0,8,6},{0,8,134},{0,8,70},{0,9,236},
  78871. {16,7,9},{0,8,94},{0,8,30},{0,9,156},{20,7,99},{0,8,126},{0,8,62},
  78872. {0,9,220},{18,7,27},{0,8,110},{0,8,46},{0,9,188},{0,8,14},{0,8,142},
  78873. {0,8,78},{0,9,252},{96,7,0},{0,8,81},{0,8,17},{21,8,131},{18,7,31},
  78874. {0,8,113},{0,8,49},{0,9,194},{16,7,10},{0,8,97},{0,8,33},{0,9,162},
  78875. {0,8,1},{0,8,129},{0,8,65},{0,9,226},{16,7,6},{0,8,89},{0,8,25},
  78876. {0,9,146},{19,7,59},{0,8,121},{0,8,57},{0,9,210},{17,7,17},{0,8,105},
  78877. {0,8,41},{0,9,178},{0,8,9},{0,8,137},{0,8,73},{0,9,242},{16,7,4},
  78878. {0,8,85},{0,8,21},{16,8,258},{19,7,43},{0,8,117},{0,8,53},{0,9,202},
  78879. {17,7,13},{0,8,101},{0,8,37},{0,9,170},{0,8,5},{0,8,133},{0,8,69},
  78880. {0,9,234},{16,7,8},{0,8,93},{0,8,29},{0,9,154},{20,7,83},{0,8,125},
  78881. {0,8,61},{0,9,218},{18,7,23},{0,8,109},{0,8,45},{0,9,186},{0,8,13},
  78882. {0,8,141},{0,8,77},{0,9,250},{16,7,3},{0,8,83},{0,8,19},{21,8,195},
  78883. {19,7,35},{0,8,115},{0,8,51},{0,9,198},{17,7,11},{0,8,99},{0,8,35},
  78884. {0,9,166},{0,8,3},{0,8,131},{0,8,67},{0,9,230},{16,7,7},{0,8,91},
  78885. {0,8,27},{0,9,150},{20,7,67},{0,8,123},{0,8,59},{0,9,214},{18,7,19},
  78886. {0,8,107},{0,8,43},{0,9,182},{0,8,11},{0,8,139},{0,8,75},{0,9,246},
  78887. {16,7,5},{0,8,87},{0,8,23},{64,8,0},{19,7,51},{0,8,119},{0,8,55},
  78888. {0,9,206},{17,7,15},{0,8,103},{0,8,39},{0,9,174},{0,8,7},{0,8,135},
  78889. {0,8,71},{0,9,238},{16,7,9},{0,8,95},{0,8,31},{0,9,158},{20,7,99},
  78890. {0,8,127},{0,8,63},{0,9,222},{18,7,27},{0,8,111},{0,8,47},{0,9,190},
  78891. {0,8,15},{0,8,143},{0,8,79},{0,9,254},{96,7,0},{0,8,80},{0,8,16},
  78892. {20,8,115},{18,7,31},{0,8,112},{0,8,48},{0,9,193},{16,7,10},{0,8,96},
  78893. {0,8,32},{0,9,161},{0,8,0},{0,8,128},{0,8,64},{0,9,225},{16,7,6},
  78894. {0,8,88},{0,8,24},{0,9,145},{19,7,59},{0,8,120},{0,8,56},{0,9,209},
  78895. {17,7,17},{0,8,104},{0,8,40},{0,9,177},{0,8,8},{0,8,136},{0,8,72},
  78896. {0,9,241},{16,7,4},{0,8,84},{0,8,20},{21,8,227},{19,7,43},{0,8,116},
  78897. {0,8,52},{0,9,201},{17,7,13},{0,8,100},{0,8,36},{0,9,169},{0,8,4},
  78898. {0,8,132},{0,8,68},{0,9,233},{16,7,8},{0,8,92},{0,8,28},{0,9,153},
  78899. {20,7,83},{0,8,124},{0,8,60},{0,9,217},{18,7,23},{0,8,108},{0,8,44},
  78900. {0,9,185},{0,8,12},{0,8,140},{0,8,76},{0,9,249},{16,7,3},{0,8,82},
  78901. {0,8,18},{21,8,163},{19,7,35},{0,8,114},{0,8,50},{0,9,197},{17,7,11},
  78902. {0,8,98},{0,8,34},{0,9,165},{0,8,2},{0,8,130},{0,8,66},{0,9,229},
  78903. {16,7,7},{0,8,90},{0,8,26},{0,9,149},{20,7,67},{0,8,122},{0,8,58},
  78904. {0,9,213},{18,7,19},{0,8,106},{0,8,42},{0,9,181},{0,8,10},{0,8,138},
  78905. {0,8,74},{0,9,245},{16,7,5},{0,8,86},{0,8,22},{64,8,0},{19,7,51},
  78906. {0,8,118},{0,8,54},{0,9,205},{17,7,15},{0,8,102},{0,8,38},{0,9,173},
  78907. {0,8,6},{0,8,134},{0,8,70},{0,9,237},{16,7,9},{0,8,94},{0,8,30},
  78908. {0,9,157},{20,7,99},{0,8,126},{0,8,62},{0,9,221},{18,7,27},{0,8,110},
  78909. {0,8,46},{0,9,189},{0,8,14},{0,8,142},{0,8,78},{0,9,253},{96,7,0},
  78910. {0,8,81},{0,8,17},{21,8,131},{18,7,31},{0,8,113},{0,8,49},{0,9,195},
  78911. {16,7,10},{0,8,97},{0,8,33},{0,9,163},{0,8,1},{0,8,129},{0,8,65},
  78912. {0,9,227},{16,7,6},{0,8,89},{0,8,25},{0,9,147},{19,7,59},{0,8,121},
  78913. {0,8,57},{0,9,211},{17,7,17},{0,8,105},{0,8,41},{0,9,179},{0,8,9},
  78914. {0,8,137},{0,8,73},{0,9,243},{16,7,4},{0,8,85},{0,8,21},{16,8,258},
  78915. {19,7,43},{0,8,117},{0,8,53},{0,9,203},{17,7,13},{0,8,101},{0,8,37},
  78916. {0,9,171},{0,8,5},{0,8,133},{0,8,69},{0,9,235},{16,7,8},{0,8,93},
  78917. {0,8,29},{0,9,155},{20,7,83},{0,8,125},{0,8,61},{0,9,219},{18,7,23},
  78918. {0,8,109},{0,8,45},{0,9,187},{0,8,13},{0,8,141},{0,8,77},{0,9,251},
  78919. {16,7,3},{0,8,83},{0,8,19},{21,8,195},{19,7,35},{0,8,115},{0,8,51},
  78920. {0,9,199},{17,7,11},{0,8,99},{0,8,35},{0,9,167},{0,8,3},{0,8,131},
  78921. {0,8,67},{0,9,231},{16,7,7},{0,8,91},{0,8,27},{0,9,151},{20,7,67},
  78922. {0,8,123},{0,8,59},{0,9,215},{18,7,19},{0,8,107},{0,8,43},{0,9,183},
  78923. {0,8,11},{0,8,139},{0,8,75},{0,9,247},{16,7,5},{0,8,87},{0,8,23},
  78924. {64,8,0},{19,7,51},{0,8,119},{0,8,55},{0,9,207},{17,7,15},{0,8,103},
  78925. {0,8,39},{0,9,175},{0,8,7},{0,8,135},{0,8,71},{0,9,239},{16,7,9},
  78926. {0,8,95},{0,8,31},{0,9,159},{20,7,99},{0,8,127},{0,8,63},{0,9,223},
  78927. {18,7,27},{0,8,111},{0,8,47},{0,9,191},{0,8,15},{0,8,143},{0,8,79},
  78928. {0,9,255}
  78929. };
  78930. static const code distfix[32] = {
  78931. {16,5,1},{23,5,257},{19,5,17},{27,5,4097},{17,5,5},{25,5,1025},
  78932. {21,5,65},{29,5,16385},{16,5,3},{24,5,513},{20,5,33},{28,5,8193},
  78933. {18,5,9},{26,5,2049},{22,5,129},{64,5,0},{16,5,2},{23,5,385},
  78934. {19,5,25},{27,5,6145},{17,5,7},{25,5,1537},{21,5,97},{29,5,24577},
  78935. {16,5,4},{24,5,769},{20,5,49},{28,5,12289},{18,5,13},{26,5,3073},
  78936. {22,5,193},{64,5,0}
  78937. };
  78938. /********* End of inlined file: inffixed.h *********/
  78939. #endif /* BUILDFIXED */
  78940. state->lencode = lenfix;
  78941. state->lenbits = 9;
  78942. state->distcode = distfix;
  78943. state->distbits = 5;
  78944. }
  78945. #ifdef MAKEFIXED
  78946. #include <stdio.h>
  78947. /*
  78948. Write out the inffixed.h that is #include'd above. Defining MAKEFIXED also
  78949. defines BUILDFIXED, so the tables are built on the fly. makefixed() writes
  78950. those tables to stdout, which would be piped to inffixed.h. A small program
  78951. can simply call makefixed to do this:
  78952. void makefixed(void);
  78953. int main(void)
  78954. {
  78955. makefixed();
  78956. return 0;
  78957. }
  78958. Then that can be linked with zlib built with MAKEFIXED defined and run:
  78959. a.out > inffixed.h
  78960. */
  78961. void makefixed()
  78962. {
  78963. unsigned low, size;
  78964. struct inflate_state state;
  78965. fixedtables(&state);
  78966. puts(" /* inffixed.h -- table for decoding fixed codes");
  78967. puts(" * Generated automatically by makefixed().");
  78968. puts(" */");
  78969. puts("");
  78970. puts(" /* WARNING: this file should *not* be used by applications.");
  78971. puts(" It is part of the implementation of this library and is");
  78972. puts(" subject to change. Applications should only use zlib.h.");
  78973. puts(" */");
  78974. puts("");
  78975. size = 1U << 9;
  78976. printf(" static const code lenfix[%u] = {", size);
  78977. low = 0;
  78978. for (;;) {
  78979. if ((low % 7) == 0) printf("\n ");
  78980. printf("{%u,%u,%d}", state.lencode[low].op, state.lencode[low].bits,
  78981. state.lencode[low].val);
  78982. if (++low == size) break;
  78983. putchar(',');
  78984. }
  78985. puts("\n };");
  78986. size = 1U << 5;
  78987. printf("\n static const code distfix[%u] = {", size);
  78988. low = 0;
  78989. for (;;) {
  78990. if ((low % 6) == 0) printf("\n ");
  78991. printf("{%u,%u,%d}", state.distcode[low].op, state.distcode[low].bits,
  78992. state.distcode[low].val);
  78993. if (++low == size) break;
  78994. putchar(',');
  78995. }
  78996. puts("\n };");
  78997. }
  78998. #endif /* MAKEFIXED */
  78999. /*
  79000. Update the window with the last wsize (normally 32K) bytes written before
  79001. returning. If window does not exist yet, create it. This is only called
  79002. when a window is already in use, or when output has been written during this
  79003. inflate call, but the end of the deflate stream has not been reached yet.
  79004. It is also called to create a window for dictionary data when a dictionary
  79005. is loaded.
  79006. Providing output buffers larger than 32K to inflate() should provide a speed
  79007. advantage, since only the last 32K of output is copied to the sliding window
  79008. upon return from inflate(), and since all distances after the first 32K of
  79009. output will fall in the output data, making match copies simpler and faster.
  79010. The advantage may be dependent on the size of the processor's data caches.
  79011. */
  79012. local int updatewindow (z_streamp strm, unsigned out)
  79013. {
  79014. struct inflate_state FAR *state;
  79015. unsigned copy, dist;
  79016. state = (struct inflate_state FAR *)strm->state;
  79017. /* if it hasn't been done already, allocate space for the window */
  79018. if (state->window == Z_NULL) {
  79019. state->window = (unsigned char FAR *)
  79020. ZALLOC(strm, 1U << state->wbits,
  79021. sizeof(unsigned char));
  79022. if (state->window == Z_NULL) return 1;
  79023. }
  79024. /* if window not in use yet, initialize */
  79025. if (state->wsize == 0) {
  79026. state->wsize = 1U << state->wbits;
  79027. state->write = 0;
  79028. state->whave = 0;
  79029. }
  79030. /* copy state->wsize or less output bytes into the circular window */
  79031. copy = out - strm->avail_out;
  79032. if (copy >= state->wsize) {
  79033. zmemcpy(state->window, strm->next_out - state->wsize, state->wsize);
  79034. state->write = 0;
  79035. state->whave = state->wsize;
  79036. }
  79037. else {
  79038. dist = state->wsize - state->write;
  79039. if (dist > copy) dist = copy;
  79040. zmemcpy(state->window + state->write, strm->next_out - copy, dist);
  79041. copy -= dist;
  79042. if (copy) {
  79043. zmemcpy(state->window, strm->next_out - copy, copy);
  79044. state->write = copy;
  79045. state->whave = state->wsize;
  79046. }
  79047. else {
  79048. state->write += dist;
  79049. if (state->write == state->wsize) state->write = 0;
  79050. if (state->whave < state->wsize) state->whave += dist;
  79051. }
  79052. }
  79053. return 0;
  79054. }
  79055. /* Macros for inflate(): */
  79056. /* check function to use adler32() for zlib or crc32() for gzip */
  79057. #ifdef GUNZIP
  79058. # define UPDATE(check, buf, len) \
  79059. (state->flags ? crc32(check, buf, len) : adler32(check, buf, len))
  79060. #else
  79061. # define UPDATE(check, buf, len) adler32(check, buf, len)
  79062. #endif
  79063. /* check macros for header crc */
  79064. #ifdef GUNZIP
  79065. # define CRC2(check, word) \
  79066. do { \
  79067. hbuf[0] = (unsigned char)(word); \
  79068. hbuf[1] = (unsigned char)((word) >> 8); \
  79069. check = crc32(check, hbuf, 2); \
  79070. } while (0)
  79071. # define CRC4(check, word) \
  79072. do { \
  79073. hbuf[0] = (unsigned char)(word); \
  79074. hbuf[1] = (unsigned char)((word) >> 8); \
  79075. hbuf[2] = (unsigned char)((word) >> 16); \
  79076. hbuf[3] = (unsigned char)((word) >> 24); \
  79077. check = crc32(check, hbuf, 4); \
  79078. } while (0)
  79079. #endif
  79080. /* Load registers with state in inflate() for speed */
  79081. #define LOAD() \
  79082. do { \
  79083. put = strm->next_out; \
  79084. left = strm->avail_out; \
  79085. next = strm->next_in; \
  79086. have = strm->avail_in; \
  79087. hold = state->hold; \
  79088. bits = state->bits; \
  79089. } while (0)
  79090. /* Restore state from registers in inflate() */
  79091. #define RESTORE() \
  79092. do { \
  79093. strm->next_out = put; \
  79094. strm->avail_out = left; \
  79095. strm->next_in = next; \
  79096. strm->avail_in = have; \
  79097. state->hold = hold; \
  79098. state->bits = bits; \
  79099. } while (0)
  79100. /* Clear the input bit accumulator */
  79101. #define INITBITS() \
  79102. do { \
  79103. hold = 0; \
  79104. bits = 0; \
  79105. } while (0)
  79106. /* Get a byte of input into the bit accumulator, or return from inflate()
  79107. if there is no input available. */
  79108. #define PULLBYTE() \
  79109. do { \
  79110. if (have == 0) goto inf_leave; \
  79111. have--; \
  79112. hold += (unsigned long)(*next++) << bits; \
  79113. bits += 8; \
  79114. } while (0)
  79115. /* Assure that there are at least n bits in the bit accumulator. If there is
  79116. not enough available input to do that, then return from inflate(). */
  79117. #define NEEDBITS(n) \
  79118. do { \
  79119. while (bits < (unsigned)(n)) \
  79120. PULLBYTE(); \
  79121. } while (0)
  79122. /* Return the low n bits of the bit accumulator (n < 16) */
  79123. #define BITS(n) \
  79124. ((unsigned)hold & ((1U << (n)) - 1))
  79125. /* Remove n bits from the bit accumulator */
  79126. #define DROPBITS(n) \
  79127. do { \
  79128. hold >>= (n); \
  79129. bits -= (unsigned)(n); \
  79130. } while (0)
  79131. /* Remove zero to seven bits as needed to go to a byte boundary */
  79132. #define BYTEBITS() \
  79133. do { \
  79134. hold >>= bits & 7; \
  79135. bits -= bits & 7; \
  79136. } while (0)
  79137. /* Reverse the bytes in a 32-bit value */
  79138. #define REVERSE(q) \
  79139. ((((q) >> 24) & 0xff) + (((q) >> 8) & 0xff00) + \
  79140. (((q) & 0xff00) << 8) + (((q) & 0xff) << 24))
  79141. /*
  79142. inflate() uses a state machine to process as much input data and generate as
  79143. much output data as possible before returning. The state machine is
  79144. structured roughly as follows:
  79145. for (;;) switch (state) {
  79146. ...
  79147. case STATEn:
  79148. if (not enough input data or output space to make progress)
  79149. return;
  79150. ... make progress ...
  79151. state = STATEm;
  79152. break;
  79153. ...
  79154. }
  79155. so when inflate() is called again, the same case is attempted again, and
  79156. if the appropriate resources are provided, the machine proceeds to the
  79157. next state. The NEEDBITS() macro is usually the way the state evaluates
  79158. whether it can proceed or should return. NEEDBITS() does the return if
  79159. the requested bits are not available. The typical use of the BITS macros
  79160. is:
  79161. NEEDBITS(n);
  79162. ... do something with BITS(n) ...
  79163. DROPBITS(n);
  79164. where NEEDBITS(n) either returns from inflate() if there isn't enough
  79165. input left to load n bits into the accumulator, or it continues. BITS(n)
  79166. gives the low n bits in the accumulator. When done, DROPBITS(n) drops
  79167. the low n bits off the accumulator. INITBITS() clears the accumulator
  79168. and sets the number of available bits to zero. BYTEBITS() discards just
  79169. enough bits to put the accumulator on a byte boundary. After BYTEBITS()
  79170. and a NEEDBITS(8), then BITS(8) would return the next byte in the stream.
  79171. NEEDBITS(n) uses PULLBYTE() to get an available byte of input, or to return
  79172. if there is no input available. The decoding of variable length codes uses
  79173. PULLBYTE() directly in order to pull just enough bytes to decode the next
  79174. code, and no more.
  79175. Some states loop until they get enough input, making sure that enough
  79176. state information is maintained to continue the loop where it left off
  79177. if NEEDBITS() returns in the loop. For example, want, need, and keep
  79178. would all have to actually be part of the saved state in case NEEDBITS()
  79179. returns:
  79180. case STATEw:
  79181. while (want < need) {
  79182. NEEDBITS(n);
  79183. keep[want++] = BITS(n);
  79184. DROPBITS(n);
  79185. }
  79186. state = STATEx;
  79187. case STATEx:
  79188. As shown above, if the next state is also the next case, then the break
  79189. is omitted.
  79190. A state may also return if there is not enough output space available to
  79191. complete that state. Those states are copying stored data, writing a
  79192. literal byte, and copying a matching string.
  79193. When returning, a "goto inf_leave" is used to update the total counters,
  79194. update the check value, and determine whether any progress has been made
  79195. during that inflate() call in order to return the proper return code.
  79196. Progress is defined as a change in either strm->avail_in or strm->avail_out.
  79197. When there is a window, goto inf_leave will update the window with the last
  79198. output written. If a goto inf_leave occurs in the middle of decompression
  79199. and there is no window currently, goto inf_leave will create one and copy
  79200. output to the window for the next call of inflate().
  79201. In this implementation, the flush parameter of inflate() only affects the
  79202. return code (per zlib.h). inflate() always writes as much as possible to
  79203. strm->next_out, given the space available and the provided input--the effect
  79204. documented in zlib.h of Z_SYNC_FLUSH. Furthermore, inflate() always defers
  79205. the allocation of and copying into a sliding window until necessary, which
  79206. provides the effect documented in zlib.h for Z_FINISH when the entire input
  79207. stream available. So the only thing the flush parameter actually does is:
  79208. when flush is set to Z_FINISH, inflate() cannot return Z_OK. Instead it
  79209. will return Z_BUF_ERROR if it has not reached the end of the stream.
  79210. */
  79211. int ZEXPORT inflate (z_streamp strm, int flush)
  79212. {
  79213. struct inflate_state FAR *state;
  79214. unsigned char FAR *next; /* next input */
  79215. unsigned char FAR *put; /* next output */
  79216. unsigned have, left; /* available input and output */
  79217. unsigned long hold; /* bit buffer */
  79218. unsigned bits; /* bits in bit buffer */
  79219. unsigned in, out; /* save starting available input and output */
  79220. unsigned copy; /* number of stored or match bytes to copy */
  79221. unsigned char FAR *from; /* where to copy match bytes from */
  79222. code thisx; /* current decoding table entry */
  79223. code last; /* parent table entry */
  79224. unsigned len; /* length to copy for repeats, bits to drop */
  79225. int ret; /* return code */
  79226. #ifdef GUNZIP
  79227. unsigned char hbuf[4]; /* buffer for gzip header crc calculation */
  79228. #endif
  79229. static const unsigned short order[19] = /* permutation of code lengths */
  79230. {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
  79231. if (strm == Z_NULL || strm->state == Z_NULL || strm->next_out == Z_NULL ||
  79232. (strm->next_in == Z_NULL && strm->avail_in != 0))
  79233. return Z_STREAM_ERROR;
  79234. state = (struct inflate_state FAR *)strm->state;
  79235. if (state->mode == TYPE) state->mode = TYPEDO; /* skip check */
  79236. LOAD();
  79237. in = have;
  79238. out = left;
  79239. ret = Z_OK;
  79240. for (;;)
  79241. switch (state->mode) {
  79242. case HEAD:
  79243. if (state->wrap == 0) {
  79244. state->mode = TYPEDO;
  79245. break;
  79246. }
  79247. NEEDBITS(16);
  79248. #ifdef GUNZIP
  79249. if ((state->wrap & 2) && hold == 0x8b1f) { /* gzip header */
  79250. state->check = crc32(0L, Z_NULL, 0);
  79251. CRC2(state->check, hold);
  79252. INITBITS();
  79253. state->mode = FLAGS;
  79254. break;
  79255. }
  79256. state->flags = 0; /* expect zlib header */
  79257. if (state->head != Z_NULL)
  79258. state->head->done = -1;
  79259. if (!(state->wrap & 1) || /* check if zlib header allowed */
  79260. #else
  79261. if (
  79262. #endif
  79263. ((BITS(8) << 8) + (hold >> 8)) % 31) {
  79264. strm->msg = (char *)"incorrect header check";
  79265. state->mode = BAD;
  79266. break;
  79267. }
  79268. if (BITS(4) != Z_DEFLATED) {
  79269. strm->msg = (char *)"unknown compression method";
  79270. state->mode = BAD;
  79271. break;
  79272. }
  79273. DROPBITS(4);
  79274. len = BITS(4) + 8;
  79275. if (len > state->wbits) {
  79276. strm->msg = (char *)"invalid window size";
  79277. state->mode = BAD;
  79278. break;
  79279. }
  79280. state->dmax = 1U << len;
  79281. Tracev((stderr, "inflate: zlib header ok\n"));
  79282. strm->adler = state->check = adler32(0L, Z_NULL, 0);
  79283. state->mode = hold & 0x200 ? DICTID : TYPE;
  79284. INITBITS();
  79285. break;
  79286. #ifdef GUNZIP
  79287. case FLAGS:
  79288. NEEDBITS(16);
  79289. state->flags = (int)(hold);
  79290. if ((state->flags & 0xff) != Z_DEFLATED) {
  79291. strm->msg = (char *)"unknown compression method";
  79292. state->mode = BAD;
  79293. break;
  79294. }
  79295. if (state->flags & 0xe000) {
  79296. strm->msg = (char *)"unknown header flags set";
  79297. state->mode = BAD;
  79298. break;
  79299. }
  79300. if (state->head != Z_NULL)
  79301. state->head->text = (int)((hold >> 8) & 1);
  79302. if (state->flags & 0x0200) CRC2(state->check, hold);
  79303. INITBITS();
  79304. state->mode = TIME;
  79305. case TIME:
  79306. NEEDBITS(32);
  79307. if (state->head != Z_NULL)
  79308. state->head->time = hold;
  79309. if (state->flags & 0x0200) CRC4(state->check, hold);
  79310. INITBITS();
  79311. state->mode = OS;
  79312. case OS:
  79313. NEEDBITS(16);
  79314. if (state->head != Z_NULL) {
  79315. state->head->xflags = (int)(hold & 0xff);
  79316. state->head->os = (int)(hold >> 8);
  79317. }
  79318. if (state->flags & 0x0200) CRC2(state->check, hold);
  79319. INITBITS();
  79320. state->mode = EXLEN;
  79321. case EXLEN:
  79322. if (state->flags & 0x0400) {
  79323. NEEDBITS(16);
  79324. state->length = (unsigned)(hold);
  79325. if (state->head != Z_NULL)
  79326. state->head->extra_len = (unsigned)hold;
  79327. if (state->flags & 0x0200) CRC2(state->check, hold);
  79328. INITBITS();
  79329. }
  79330. else if (state->head != Z_NULL)
  79331. state->head->extra = Z_NULL;
  79332. state->mode = EXTRA;
  79333. case EXTRA:
  79334. if (state->flags & 0x0400) {
  79335. copy = state->length;
  79336. if (copy > have) copy = have;
  79337. if (copy) {
  79338. if (state->head != Z_NULL &&
  79339. state->head->extra != Z_NULL) {
  79340. len = state->head->extra_len - state->length;
  79341. zmemcpy(state->head->extra + len, next,
  79342. len + copy > state->head->extra_max ?
  79343. state->head->extra_max - len : copy);
  79344. }
  79345. if (state->flags & 0x0200)
  79346. state->check = crc32(state->check, next, copy);
  79347. have -= copy;
  79348. next += copy;
  79349. state->length -= copy;
  79350. }
  79351. if (state->length) goto inf_leave;
  79352. }
  79353. state->length = 0;
  79354. state->mode = NAME;
  79355. case NAME:
  79356. if (state->flags & 0x0800) {
  79357. if (have == 0) goto inf_leave;
  79358. copy = 0;
  79359. do {
  79360. len = (unsigned)(next[copy++]);
  79361. if (state->head != Z_NULL &&
  79362. state->head->name != Z_NULL &&
  79363. state->length < state->head->name_max)
  79364. state->head->name[state->length++] = len;
  79365. } while (len && copy < have);
  79366. if (state->flags & 0x0200)
  79367. state->check = crc32(state->check, next, copy);
  79368. have -= copy;
  79369. next += copy;
  79370. if (len) goto inf_leave;
  79371. }
  79372. else if (state->head != Z_NULL)
  79373. state->head->name = Z_NULL;
  79374. state->length = 0;
  79375. state->mode = COMMENT;
  79376. case COMMENT:
  79377. if (state->flags & 0x1000) {
  79378. if (have == 0) goto inf_leave;
  79379. copy = 0;
  79380. do {
  79381. len = (unsigned)(next[copy++]);
  79382. if (state->head != Z_NULL &&
  79383. state->head->comment != Z_NULL &&
  79384. state->length < state->head->comm_max)
  79385. state->head->comment[state->length++] = len;
  79386. } while (len && copy < have);
  79387. if (state->flags & 0x0200)
  79388. state->check = crc32(state->check, next, copy);
  79389. have -= copy;
  79390. next += copy;
  79391. if (len) goto inf_leave;
  79392. }
  79393. else if (state->head != Z_NULL)
  79394. state->head->comment = Z_NULL;
  79395. state->mode = HCRC;
  79396. case HCRC:
  79397. if (state->flags & 0x0200) {
  79398. NEEDBITS(16);
  79399. if (hold != (state->check & 0xffff)) {
  79400. strm->msg = (char *)"header crc mismatch";
  79401. state->mode = BAD;
  79402. break;
  79403. }
  79404. INITBITS();
  79405. }
  79406. if (state->head != Z_NULL) {
  79407. state->head->hcrc = (int)((state->flags >> 9) & 1);
  79408. state->head->done = 1;
  79409. }
  79410. strm->adler = state->check = crc32(0L, Z_NULL, 0);
  79411. state->mode = TYPE;
  79412. break;
  79413. #endif
  79414. case DICTID:
  79415. NEEDBITS(32);
  79416. strm->adler = state->check = REVERSE(hold);
  79417. INITBITS();
  79418. state->mode = DICT;
  79419. case DICT:
  79420. if (state->havedict == 0) {
  79421. RESTORE();
  79422. return Z_NEED_DICT;
  79423. }
  79424. strm->adler = state->check = adler32(0L, Z_NULL, 0);
  79425. state->mode = TYPE;
  79426. case TYPE:
  79427. if (flush == Z_BLOCK) goto inf_leave;
  79428. case TYPEDO:
  79429. if (state->last) {
  79430. BYTEBITS();
  79431. state->mode = CHECK;
  79432. break;
  79433. }
  79434. NEEDBITS(3);
  79435. state->last = BITS(1);
  79436. DROPBITS(1);
  79437. switch (BITS(2)) {
  79438. case 0: /* stored block */
  79439. Tracev((stderr, "inflate: stored block%s\n",
  79440. state->last ? " (last)" : ""));
  79441. state->mode = STORED;
  79442. break;
  79443. case 1: /* fixed block */
  79444. fixedtables(state);
  79445. Tracev((stderr, "inflate: fixed codes block%s\n",
  79446. state->last ? " (last)" : ""));
  79447. state->mode = LEN; /* decode codes */
  79448. break;
  79449. case 2: /* dynamic block */
  79450. Tracev((stderr, "inflate: dynamic codes block%s\n",
  79451. state->last ? " (last)" : ""));
  79452. state->mode = TABLE;
  79453. break;
  79454. case 3:
  79455. strm->msg = (char *)"invalid block type";
  79456. state->mode = BAD;
  79457. }
  79458. DROPBITS(2);
  79459. break;
  79460. case STORED:
  79461. BYTEBITS(); /* go to byte boundary */
  79462. NEEDBITS(32);
  79463. if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) {
  79464. strm->msg = (char *)"invalid stored block lengths";
  79465. state->mode = BAD;
  79466. break;
  79467. }
  79468. state->length = (unsigned)hold & 0xffff;
  79469. Tracev((stderr, "inflate: stored length %u\n",
  79470. state->length));
  79471. INITBITS();
  79472. state->mode = COPY;
  79473. case COPY:
  79474. copy = state->length;
  79475. if (copy) {
  79476. if (copy > have) copy = have;
  79477. if (copy > left) copy = left;
  79478. if (copy == 0) goto inf_leave;
  79479. zmemcpy(put, next, copy);
  79480. have -= copy;
  79481. next += copy;
  79482. left -= copy;
  79483. put += copy;
  79484. state->length -= copy;
  79485. break;
  79486. }
  79487. Tracev((stderr, "inflate: stored end\n"));
  79488. state->mode = TYPE;
  79489. break;
  79490. case TABLE:
  79491. NEEDBITS(14);
  79492. state->nlen = BITS(5) + 257;
  79493. DROPBITS(5);
  79494. state->ndist = BITS(5) + 1;
  79495. DROPBITS(5);
  79496. state->ncode = BITS(4) + 4;
  79497. DROPBITS(4);
  79498. #ifndef PKZIP_BUG_WORKAROUND
  79499. if (state->nlen > 286 || state->ndist > 30) {
  79500. strm->msg = (char *)"too many length or distance symbols";
  79501. state->mode = BAD;
  79502. break;
  79503. }
  79504. #endif
  79505. Tracev((stderr, "inflate: table sizes ok\n"));
  79506. state->have = 0;
  79507. state->mode = LENLENS;
  79508. case LENLENS:
  79509. while (state->have < state->ncode) {
  79510. NEEDBITS(3);
  79511. state->lens[order[state->have++]] = (unsigned short)BITS(3);
  79512. DROPBITS(3);
  79513. }
  79514. while (state->have < 19)
  79515. state->lens[order[state->have++]] = 0;
  79516. state->next = state->codes;
  79517. state->lencode = (code const FAR *)(state->next);
  79518. state->lenbits = 7;
  79519. ret = inflate_table(CODES, state->lens, 19, &(state->next),
  79520. &(state->lenbits), state->work);
  79521. if (ret) {
  79522. strm->msg = (char *)"invalid code lengths set";
  79523. state->mode = BAD;
  79524. break;
  79525. }
  79526. Tracev((stderr, "inflate: code lengths ok\n"));
  79527. state->have = 0;
  79528. state->mode = CODELENS;
  79529. case CODELENS:
  79530. while (state->have < state->nlen + state->ndist) {
  79531. for (;;) {
  79532. thisx = state->lencode[BITS(state->lenbits)];
  79533. if ((unsigned)(thisx.bits) <= bits) break;
  79534. PULLBYTE();
  79535. }
  79536. if (thisx.val < 16) {
  79537. NEEDBITS(thisx.bits);
  79538. DROPBITS(thisx.bits);
  79539. state->lens[state->have++] = thisx.val;
  79540. }
  79541. else {
  79542. if (thisx.val == 16) {
  79543. NEEDBITS(thisx.bits + 2);
  79544. DROPBITS(thisx.bits);
  79545. if (state->have == 0) {
  79546. strm->msg = (char *)"invalid bit length repeat";
  79547. state->mode = BAD;
  79548. break;
  79549. }
  79550. len = state->lens[state->have - 1];
  79551. copy = 3 + BITS(2);
  79552. DROPBITS(2);
  79553. }
  79554. else if (thisx.val == 17) {
  79555. NEEDBITS(thisx.bits + 3);
  79556. DROPBITS(thisx.bits);
  79557. len = 0;
  79558. copy = 3 + BITS(3);
  79559. DROPBITS(3);
  79560. }
  79561. else {
  79562. NEEDBITS(thisx.bits + 7);
  79563. DROPBITS(thisx.bits);
  79564. len = 0;
  79565. copy = 11 + BITS(7);
  79566. DROPBITS(7);
  79567. }
  79568. if (state->have + copy > state->nlen + state->ndist) {
  79569. strm->msg = (char *)"invalid bit length repeat";
  79570. state->mode = BAD;
  79571. break;
  79572. }
  79573. while (copy--)
  79574. state->lens[state->have++] = (unsigned short)len;
  79575. }
  79576. }
  79577. /* handle error breaks in while */
  79578. if (state->mode == BAD) break;
  79579. /* build code tables */
  79580. state->next = state->codes;
  79581. state->lencode = (code const FAR *)(state->next);
  79582. state->lenbits = 9;
  79583. ret = inflate_table(LENS, state->lens, state->nlen, &(state->next),
  79584. &(state->lenbits), state->work);
  79585. if (ret) {
  79586. strm->msg = (char *)"invalid literal/lengths set";
  79587. state->mode = BAD;
  79588. break;
  79589. }
  79590. state->distcode = (code const FAR *)(state->next);
  79591. state->distbits = 6;
  79592. ret = inflate_table(DISTS, state->lens + state->nlen, state->ndist,
  79593. &(state->next), &(state->distbits), state->work);
  79594. if (ret) {
  79595. strm->msg = (char *)"invalid distances set";
  79596. state->mode = BAD;
  79597. break;
  79598. }
  79599. Tracev((stderr, "inflate: codes ok\n"));
  79600. state->mode = LEN;
  79601. case LEN:
  79602. if (have >= 6 && left >= 258) {
  79603. RESTORE();
  79604. inflate_fast(strm, out);
  79605. LOAD();
  79606. break;
  79607. }
  79608. for (;;) {
  79609. thisx = state->lencode[BITS(state->lenbits)];
  79610. if ((unsigned)(thisx.bits) <= bits) break;
  79611. PULLBYTE();
  79612. }
  79613. if (thisx.op && (thisx.op & 0xf0) == 0) {
  79614. last = thisx;
  79615. for (;;) {
  79616. thisx = state->lencode[last.val +
  79617. (BITS(last.bits + last.op) >> last.bits)];
  79618. if ((unsigned)(last.bits + thisx.bits) <= bits) break;
  79619. PULLBYTE();
  79620. }
  79621. DROPBITS(last.bits);
  79622. }
  79623. DROPBITS(thisx.bits);
  79624. state->length = (unsigned)thisx.val;
  79625. if ((int)(thisx.op) == 0) {
  79626. Tracevv((stderr, thisx.val >= 0x20 && thisx.val < 0x7f ?
  79627. "inflate: literal '%c'\n" :
  79628. "inflate: literal 0x%02x\n", thisx.val));
  79629. state->mode = LIT;
  79630. break;
  79631. }
  79632. if (thisx.op & 32) {
  79633. Tracevv((stderr, "inflate: end of block\n"));
  79634. state->mode = TYPE;
  79635. break;
  79636. }
  79637. if (thisx.op & 64) {
  79638. strm->msg = (char *)"invalid literal/length code";
  79639. state->mode = BAD;
  79640. break;
  79641. }
  79642. state->extra = (unsigned)(thisx.op) & 15;
  79643. state->mode = LENEXT;
  79644. case LENEXT:
  79645. if (state->extra) {
  79646. NEEDBITS(state->extra);
  79647. state->length += BITS(state->extra);
  79648. DROPBITS(state->extra);
  79649. }
  79650. Tracevv((stderr, "inflate: length %u\n", state->length));
  79651. state->mode = DIST;
  79652. case DIST:
  79653. for (;;) {
  79654. thisx = state->distcode[BITS(state->distbits)];
  79655. if ((unsigned)(thisx.bits) <= bits) break;
  79656. PULLBYTE();
  79657. }
  79658. if ((thisx.op & 0xf0) == 0) {
  79659. last = thisx;
  79660. for (;;) {
  79661. thisx = state->distcode[last.val +
  79662. (BITS(last.bits + last.op) >> last.bits)];
  79663. if ((unsigned)(last.bits + thisx.bits) <= bits) break;
  79664. PULLBYTE();
  79665. }
  79666. DROPBITS(last.bits);
  79667. }
  79668. DROPBITS(thisx.bits);
  79669. if (thisx.op & 64) {
  79670. strm->msg = (char *)"invalid distance code";
  79671. state->mode = BAD;
  79672. break;
  79673. }
  79674. state->offset = (unsigned)thisx.val;
  79675. state->extra = (unsigned)(thisx.op) & 15;
  79676. state->mode = DISTEXT;
  79677. case DISTEXT:
  79678. if (state->extra) {
  79679. NEEDBITS(state->extra);
  79680. state->offset += BITS(state->extra);
  79681. DROPBITS(state->extra);
  79682. }
  79683. #ifdef INFLATE_STRICT
  79684. if (state->offset > state->dmax) {
  79685. strm->msg = (char *)"invalid distance too far back";
  79686. state->mode = BAD;
  79687. break;
  79688. }
  79689. #endif
  79690. if (state->offset > state->whave + out - left) {
  79691. strm->msg = (char *)"invalid distance too far back";
  79692. state->mode = BAD;
  79693. break;
  79694. }
  79695. Tracevv((stderr, "inflate: distance %u\n", state->offset));
  79696. state->mode = MATCH;
  79697. case MATCH:
  79698. if (left == 0) goto inf_leave;
  79699. copy = out - left;
  79700. if (state->offset > copy) { /* copy from window */
  79701. copy = state->offset - copy;
  79702. if (copy > state->write) {
  79703. copy -= state->write;
  79704. from = state->window + (state->wsize - copy);
  79705. }
  79706. else
  79707. from = state->window + (state->write - copy);
  79708. if (copy > state->length) copy = state->length;
  79709. }
  79710. else { /* copy from output */
  79711. from = put - state->offset;
  79712. copy = state->length;
  79713. }
  79714. if (copy > left) copy = left;
  79715. left -= copy;
  79716. state->length -= copy;
  79717. do {
  79718. *put++ = *from++;
  79719. } while (--copy);
  79720. if (state->length == 0) state->mode = LEN;
  79721. break;
  79722. case LIT:
  79723. if (left == 0) goto inf_leave;
  79724. *put++ = (unsigned char)(state->length);
  79725. left--;
  79726. state->mode = LEN;
  79727. break;
  79728. case CHECK:
  79729. if (state->wrap) {
  79730. NEEDBITS(32);
  79731. out -= left;
  79732. strm->total_out += out;
  79733. state->total += out;
  79734. if (out)
  79735. strm->adler = state->check =
  79736. UPDATE(state->check, put - out, out);
  79737. out = left;
  79738. if ((
  79739. #ifdef GUNZIP
  79740. state->flags ? hold :
  79741. #endif
  79742. REVERSE(hold)) != state->check) {
  79743. strm->msg = (char *)"incorrect data check";
  79744. state->mode = BAD;
  79745. break;
  79746. }
  79747. INITBITS();
  79748. Tracev((stderr, "inflate: check matches trailer\n"));
  79749. }
  79750. #ifdef GUNZIP
  79751. state->mode = LENGTH;
  79752. case LENGTH:
  79753. if (state->wrap && state->flags) {
  79754. NEEDBITS(32);
  79755. if (hold != (state->total & 0xffffffffUL)) {
  79756. strm->msg = (char *)"incorrect length check";
  79757. state->mode = BAD;
  79758. break;
  79759. }
  79760. INITBITS();
  79761. Tracev((stderr, "inflate: length matches trailer\n"));
  79762. }
  79763. #endif
  79764. state->mode = DONE;
  79765. case DONE:
  79766. ret = Z_STREAM_END;
  79767. goto inf_leave;
  79768. case BAD:
  79769. ret = Z_DATA_ERROR;
  79770. goto inf_leave;
  79771. case MEM:
  79772. return Z_MEM_ERROR;
  79773. case SYNC:
  79774. default:
  79775. return Z_STREAM_ERROR;
  79776. }
  79777. /*
  79778. Return from inflate(), updating the total counts and the check value.
  79779. If there was no progress during the inflate() call, return a buffer
  79780. error. Call updatewindow() to create and/or update the window state.
  79781. Note: a memory error from inflate() is non-recoverable.
  79782. */
  79783. inf_leave:
  79784. RESTORE();
  79785. if (state->wsize || (state->mode < CHECK && out != strm->avail_out))
  79786. if (updatewindow(strm, out)) {
  79787. state->mode = MEM;
  79788. return Z_MEM_ERROR;
  79789. }
  79790. in -= strm->avail_in;
  79791. out -= strm->avail_out;
  79792. strm->total_in += in;
  79793. strm->total_out += out;
  79794. state->total += out;
  79795. if (state->wrap && out)
  79796. strm->adler = state->check =
  79797. UPDATE(state->check, strm->next_out - out, out);
  79798. strm->data_type = state->bits + (state->last ? 64 : 0) +
  79799. (state->mode == TYPE ? 128 : 0);
  79800. if (((in == 0 && out == 0) || flush == Z_FINISH) && ret == Z_OK)
  79801. ret = Z_BUF_ERROR;
  79802. return ret;
  79803. }
  79804. int ZEXPORT inflateEnd (z_streamp strm)
  79805. {
  79806. struct inflate_state FAR *state;
  79807. if (strm == Z_NULL || strm->state == Z_NULL || strm->zfree == (free_func)0)
  79808. return Z_STREAM_ERROR;
  79809. state = (struct inflate_state FAR *)strm->state;
  79810. if (state->window != Z_NULL) ZFREE(strm, state->window);
  79811. ZFREE(strm, strm->state);
  79812. strm->state = Z_NULL;
  79813. Tracev((stderr, "inflate: end\n"));
  79814. return Z_OK;
  79815. }
  79816. int ZEXPORT inflateSetDictionary (z_streamp strm, const Bytef *dictionary, uInt dictLength)
  79817. {
  79818. struct inflate_state FAR *state;
  79819. unsigned long id_;
  79820. /* check state */
  79821. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  79822. state = (struct inflate_state FAR *)strm->state;
  79823. if (state->wrap != 0 && state->mode != DICT)
  79824. return Z_STREAM_ERROR;
  79825. /* check for correct dictionary id */
  79826. if (state->mode == DICT) {
  79827. id_ = adler32(0L, Z_NULL, 0);
  79828. id_ = adler32(id_, dictionary, dictLength);
  79829. if (id_ != state->check)
  79830. return Z_DATA_ERROR;
  79831. }
  79832. /* copy dictionary to window */
  79833. if (updatewindow(strm, strm->avail_out)) {
  79834. state->mode = MEM;
  79835. return Z_MEM_ERROR;
  79836. }
  79837. if (dictLength > state->wsize) {
  79838. zmemcpy(state->window, dictionary + dictLength - state->wsize,
  79839. state->wsize);
  79840. state->whave = state->wsize;
  79841. }
  79842. else {
  79843. zmemcpy(state->window + state->wsize - dictLength, dictionary,
  79844. dictLength);
  79845. state->whave = dictLength;
  79846. }
  79847. state->havedict = 1;
  79848. Tracev((stderr, "inflate: dictionary set\n"));
  79849. return Z_OK;
  79850. }
  79851. int ZEXPORT inflateGetHeader (z_streamp strm, gz_headerp head)
  79852. {
  79853. struct inflate_state FAR *state;
  79854. /* check state */
  79855. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  79856. state = (struct inflate_state FAR *)strm->state;
  79857. if ((state->wrap & 2) == 0) return Z_STREAM_ERROR;
  79858. /* save header structure */
  79859. state->head = head;
  79860. head->done = 0;
  79861. return Z_OK;
  79862. }
  79863. /*
  79864. Search buf[0..len-1] for the pattern: 0, 0, 0xff, 0xff. Return when found
  79865. or when out of input. When called, *have is the number of pattern bytes
  79866. found in order so far, in 0..3. On return *have is updated to the new
  79867. state. If on return *have equals four, then the pattern was found and the
  79868. return value is how many bytes were read including the last byte of the
  79869. pattern. If *have is less than four, then the pattern has not been found
  79870. yet and the return value is len. In the latter case, syncsearch() can be
  79871. called again with more data and the *have state. *have is initialized to
  79872. zero for the first call.
  79873. */
  79874. local unsigned syncsearch (unsigned FAR *have, unsigned char FAR *buf, unsigned len)
  79875. {
  79876. unsigned got;
  79877. unsigned next;
  79878. got = *have;
  79879. next = 0;
  79880. while (next < len && got < 4) {
  79881. if ((int)(buf[next]) == (got < 2 ? 0 : 0xff))
  79882. got++;
  79883. else if (buf[next])
  79884. got = 0;
  79885. else
  79886. got = 4 - got;
  79887. next++;
  79888. }
  79889. *have = got;
  79890. return next;
  79891. }
  79892. int ZEXPORT inflateSync (z_streamp strm)
  79893. {
  79894. unsigned len; /* number of bytes to look at or looked at */
  79895. unsigned long in, out; /* temporary to save total_in and total_out */
  79896. unsigned char buf[4]; /* to restore bit buffer to byte string */
  79897. struct inflate_state FAR *state;
  79898. /* check parameters */
  79899. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  79900. state = (struct inflate_state FAR *)strm->state;
  79901. if (strm->avail_in == 0 && state->bits < 8) return Z_BUF_ERROR;
  79902. /* if first time, start search in bit buffer */
  79903. if (state->mode != SYNC) {
  79904. state->mode = SYNC;
  79905. state->hold <<= state->bits & 7;
  79906. state->bits -= state->bits & 7;
  79907. len = 0;
  79908. while (state->bits >= 8) {
  79909. buf[len++] = (unsigned char)(state->hold);
  79910. state->hold >>= 8;
  79911. state->bits -= 8;
  79912. }
  79913. state->have = 0;
  79914. syncsearch(&(state->have), buf, len);
  79915. }
  79916. /* search available input */
  79917. len = syncsearch(&(state->have), strm->next_in, strm->avail_in);
  79918. strm->avail_in -= len;
  79919. strm->next_in += len;
  79920. strm->total_in += len;
  79921. /* return no joy or set up to restart inflate() on a new block */
  79922. if (state->have != 4) return Z_DATA_ERROR;
  79923. in = strm->total_in; out = strm->total_out;
  79924. inflateReset(strm);
  79925. strm->total_in = in; strm->total_out = out;
  79926. state->mode = TYPE;
  79927. return Z_OK;
  79928. }
  79929. /*
  79930. Returns true if inflate is currently at the end of a block generated by
  79931. Z_SYNC_FLUSH or Z_FULL_FLUSH. This function is used by one PPP
  79932. implementation to provide an additional safety check. PPP uses
  79933. Z_SYNC_FLUSH but removes the length bytes of the resulting empty stored
  79934. block. When decompressing, PPP checks that at the end of input packet,
  79935. inflate is waiting for these length bytes.
  79936. */
  79937. int ZEXPORT inflateSyncPoint (z_streamp strm)
  79938. {
  79939. struct inflate_state FAR *state;
  79940. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  79941. state = (struct inflate_state FAR *)strm->state;
  79942. return state->mode == STORED && state->bits == 0;
  79943. }
  79944. int ZEXPORT inflateCopy(z_streamp dest, z_streamp source)
  79945. {
  79946. struct inflate_state FAR *state;
  79947. struct inflate_state FAR *copy;
  79948. unsigned char FAR *window;
  79949. unsigned wsize;
  79950. /* check input */
  79951. if (dest == Z_NULL || source == Z_NULL || source->state == Z_NULL ||
  79952. source->zalloc == (alloc_func)0 || source->zfree == (free_func)0)
  79953. return Z_STREAM_ERROR;
  79954. state = (struct inflate_state FAR *)source->state;
  79955. /* allocate space */
  79956. copy = (struct inflate_state FAR *)
  79957. ZALLOC(source, 1, sizeof(struct inflate_state));
  79958. if (copy == Z_NULL) return Z_MEM_ERROR;
  79959. window = Z_NULL;
  79960. if (state->window != Z_NULL) {
  79961. window = (unsigned char FAR *)
  79962. ZALLOC(source, 1U << state->wbits, sizeof(unsigned char));
  79963. if (window == Z_NULL) {
  79964. ZFREE(source, copy);
  79965. return Z_MEM_ERROR;
  79966. }
  79967. }
  79968. /* copy state */
  79969. zmemcpy(dest, source, sizeof(z_stream));
  79970. zmemcpy(copy, state, sizeof(struct inflate_state));
  79971. if (state->lencode >= state->codes &&
  79972. state->lencode <= state->codes + ENOUGH - 1) {
  79973. copy->lencode = copy->codes + (state->lencode - state->codes);
  79974. copy->distcode = copy->codes + (state->distcode - state->codes);
  79975. }
  79976. copy->next = copy->codes + (state->next - state->codes);
  79977. if (window != Z_NULL) {
  79978. wsize = 1U << state->wbits;
  79979. zmemcpy(window, state->window, wsize);
  79980. }
  79981. copy->window = window;
  79982. dest->state = (struct internal_state FAR *)copy;
  79983. return Z_OK;
  79984. }
  79985. /********* End of inlined file: inflate.c *********/
  79986. /********* Start of inlined file: inftrees.c *********/
  79987. #define MAXBITS 15
  79988. const char inflate_copyright[] =
  79989. " inflate 1.2.3 Copyright 1995-2005 Mark Adler ";
  79990. /*
  79991. If you use the zlib library in a product, an acknowledgment is welcome
  79992. in the documentation of your product. If for some reason you cannot
  79993. include such an acknowledgment, I would appreciate that you keep this
  79994. copyright string in the executable of your product.
  79995. */
  79996. /*
  79997. Build a set of tables to decode the provided canonical Huffman code.
  79998. The code lengths are lens[0..codes-1]. The result starts at *table,
  79999. whose indices are 0..2^bits-1. work is a writable array of at least
  80000. lens shorts, which is used as a work area. type is the type of code
  80001. to be generated, CODES, LENS, or DISTS. On return, zero is success,
  80002. -1 is an invalid code, and +1 means that ENOUGH isn't enough. table
  80003. on return points to the next available entry's address. bits is the
  80004. requested root table index bits, and on return it is the actual root
  80005. table index bits. It will differ if the request is greater than the
  80006. longest code or if it is less than the shortest code.
  80007. */
  80008. int inflate_table (codetype type,
  80009. unsigned short FAR *lens,
  80010. unsigned codes,
  80011. code FAR * FAR *table,
  80012. unsigned FAR *bits,
  80013. unsigned short FAR *work)
  80014. {
  80015. unsigned len; /* a code's length in bits */
  80016. unsigned sym; /* index of code symbols */
  80017. unsigned min, max; /* minimum and maximum code lengths */
  80018. unsigned root; /* number of index bits for root table */
  80019. unsigned curr; /* number of index bits for current table */
  80020. unsigned drop; /* code bits to drop for sub-table */
  80021. int left; /* number of prefix codes available */
  80022. unsigned used; /* code entries in table used */
  80023. unsigned huff; /* Huffman code */
  80024. unsigned incr; /* for incrementing code, index */
  80025. unsigned fill; /* index for replicating entries */
  80026. unsigned low; /* low bits for current root entry */
  80027. unsigned mask; /* mask for low root bits */
  80028. code thisx; /* table entry for duplication */
  80029. code FAR *next; /* next available space in table */
  80030. const unsigned short FAR *base; /* base value table to use */
  80031. const unsigned short FAR *extra; /* extra bits table to use */
  80032. int end; /* use base and extra for symbol > end */
  80033. unsigned short count[MAXBITS+1]; /* number of codes of each length */
  80034. unsigned short offs[MAXBITS+1]; /* offsets in table for each length */
  80035. static const unsigned short lbase[31] = { /* Length codes 257..285 base */
  80036. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  80037. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0};
  80038. static const unsigned short lext[31] = { /* Length codes 257..285 extra */
  80039. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  80040. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 201, 196};
  80041. static const unsigned short dbase[32] = { /* Distance codes 0..29 base */
  80042. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  80043. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  80044. 8193, 12289, 16385, 24577, 0, 0};
  80045. static const unsigned short dext[32] = { /* Distance codes 0..29 extra */
  80046. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  80047. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  80048. 28, 28, 29, 29, 64, 64};
  80049. /*
  80050. Process a set of code lengths to create a canonical Huffman code. The
  80051. code lengths are lens[0..codes-1]. Each length corresponds to the
  80052. symbols 0..codes-1. The Huffman code is generated by first sorting the
  80053. symbols by length from short to long, and retaining the symbol order
  80054. for codes with equal lengths. Then the code starts with all zero bits
  80055. for the first code of the shortest length, and the codes are integer
  80056. increments for the same length, and zeros are appended as the length
  80057. increases. For the deflate format, these bits are stored backwards
  80058. from their more natural integer increment ordering, and so when the
  80059. decoding tables are built in the large loop below, the integer codes
  80060. are incremented backwards.
  80061. This routine assumes, but does not check, that all of the entries in
  80062. lens[] are in the range 0..MAXBITS. The caller must assure this.
  80063. 1..MAXBITS is interpreted as that code length. zero means that that
  80064. symbol does not occur in this code.
  80065. The codes are sorted by computing a count of codes for each length,
  80066. creating from that a table of starting indices for each length in the
  80067. sorted table, and then entering the symbols in order in the sorted
  80068. table. The sorted table is work[], with that space being provided by
  80069. the caller.
  80070. The length counts are used for other purposes as well, i.e. finding
  80071. the minimum and maximum length codes, determining if there are any
  80072. codes at all, checking for a valid set of lengths, and looking ahead
  80073. at length counts to determine sub-table sizes when building the
  80074. decoding tables.
  80075. */
  80076. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  80077. for (len = 0; len <= MAXBITS; len++)
  80078. count[len] = 0;
  80079. for (sym = 0; sym < codes; sym++)
  80080. count[lens[sym]]++;
  80081. /* bound code lengths, force root to be within code lengths */
  80082. root = *bits;
  80083. for (max = MAXBITS; max >= 1; max--)
  80084. if (count[max] != 0) break;
  80085. if (root > max) root = max;
  80086. if (max == 0) { /* no symbols to code at all */
  80087. thisx.op = (unsigned char)64; /* invalid code marker */
  80088. thisx.bits = (unsigned char)1;
  80089. thisx.val = (unsigned short)0;
  80090. *(*table)++ = thisx; /* make a table to force an error */
  80091. *(*table)++ = thisx;
  80092. *bits = 1;
  80093. return 0; /* no symbols, but wait for decoding to report error */
  80094. }
  80095. for (min = 1; min <= MAXBITS; min++)
  80096. if (count[min] != 0) break;
  80097. if (root < min) root = min;
  80098. /* check for an over-subscribed or incomplete set of lengths */
  80099. left = 1;
  80100. for (len = 1; len <= MAXBITS; len++) {
  80101. left <<= 1;
  80102. left -= count[len];
  80103. if (left < 0) return -1; /* over-subscribed */
  80104. }
  80105. if (left > 0 && (type == CODES || max != 1))
  80106. return -1; /* incomplete set */
  80107. /* generate offsets into symbol table for each length for sorting */
  80108. offs[1] = 0;
  80109. for (len = 1; len < MAXBITS; len++)
  80110. offs[len + 1] = offs[len] + count[len];
  80111. /* sort symbols by length, by symbol order within each length */
  80112. for (sym = 0; sym < codes; sym++)
  80113. if (lens[sym] != 0) work[offs[lens[sym]]++] = (unsigned short)sym;
  80114. /*
  80115. Create and fill in decoding tables. In this loop, the table being
  80116. filled is at next and has curr index bits. The code being used is huff
  80117. with length len. That code is converted to an index by dropping drop
  80118. bits off of the bottom. For codes where len is less than drop + curr,
  80119. those top drop + curr - len bits are incremented through all values to
  80120. fill the table with replicated entries.
  80121. root is the number of index bits for the root table. When len exceeds
  80122. root, sub-tables are created pointed to by the root entry with an index
  80123. of the low root bits of huff. This is saved in low to check for when a
  80124. new sub-table should be started. drop is zero when the root table is
  80125. being filled, and drop is root when sub-tables are being filled.
  80126. When a new sub-table is needed, it is necessary to look ahead in the
  80127. code lengths to determine what size sub-table is needed. The length
  80128. counts are used for this, and so count[] is decremented as codes are
  80129. entered in the tables.
  80130. used keeps track of how many table entries have been allocated from the
  80131. provided *table space. It is checked when a LENS table is being made
  80132. against the space in *table, ENOUGH, minus the maximum space needed by
  80133. the worst case distance code, MAXD. This should never happen, but the
  80134. sufficiency of ENOUGH has not been proven exhaustively, hence the check.
  80135. This assumes that when type == LENS, bits == 9.
  80136. sym increments through all symbols, and the loop terminates when
  80137. all codes of length max, i.e. all codes, have been processed. This
  80138. routine permits incomplete codes, so another loop after this one fills
  80139. in the rest of the decoding tables with invalid code markers.
  80140. */
  80141. /* set up for code type */
  80142. switch (type) {
  80143. case CODES:
  80144. base = extra = work; /* dummy value--not used */
  80145. end = 19;
  80146. break;
  80147. case LENS:
  80148. base = lbase;
  80149. base -= 257;
  80150. extra = lext;
  80151. extra -= 257;
  80152. end = 256;
  80153. break;
  80154. default: /* DISTS */
  80155. base = dbase;
  80156. extra = dext;
  80157. end = -1;
  80158. }
  80159. /* initialize state for loop */
  80160. huff = 0; /* starting code */
  80161. sym = 0; /* starting code symbol */
  80162. len = min; /* starting code length */
  80163. next = *table; /* current table to fill in */
  80164. curr = root; /* current table index bits */
  80165. drop = 0; /* current bits to drop from code for index */
  80166. low = (unsigned)(-1); /* trigger new sub-table when len > root */
  80167. used = 1U << root; /* use root table entries */
  80168. mask = used - 1; /* mask for comparing low */
  80169. /* check available table space */
  80170. if (type == LENS && used >= ENOUGH - MAXD)
  80171. return 1;
  80172. /* process all codes and make table entries */
  80173. for (;;) {
  80174. /* create table entry */
  80175. thisx.bits = (unsigned char)(len - drop);
  80176. if ((int)(work[sym]) < end) {
  80177. thisx.op = (unsigned char)0;
  80178. thisx.val = work[sym];
  80179. }
  80180. else if ((int)(work[sym]) > end) {
  80181. thisx.op = (unsigned char)(extra[work[sym]]);
  80182. thisx.val = base[work[sym]];
  80183. }
  80184. else {
  80185. thisx.op = (unsigned char)(32 + 64); /* end of block */
  80186. thisx.val = 0;
  80187. }
  80188. /* replicate for those indices with low len bits equal to huff */
  80189. incr = 1U << (len - drop);
  80190. fill = 1U << curr;
  80191. min = fill; /* save offset to next table */
  80192. do {
  80193. fill -= incr;
  80194. next[(huff >> drop) + fill] = thisx;
  80195. } while (fill != 0);
  80196. /* backwards increment the len-bit code huff */
  80197. incr = 1U << (len - 1);
  80198. while (huff & incr)
  80199. incr >>= 1;
  80200. if (incr != 0) {
  80201. huff &= incr - 1;
  80202. huff += incr;
  80203. }
  80204. else
  80205. huff = 0;
  80206. /* go to next symbol, update count, len */
  80207. sym++;
  80208. if (--(count[len]) == 0) {
  80209. if (len == max) break;
  80210. len = lens[work[sym]];
  80211. }
  80212. /* create new sub-table if needed */
  80213. if (len > root && (huff & mask) != low) {
  80214. /* if first time, transition to sub-tables */
  80215. if (drop == 0)
  80216. drop = root;
  80217. /* increment past last table */
  80218. next += min; /* here min is 1 << curr */
  80219. /* determine length of next table */
  80220. curr = len - drop;
  80221. left = (int)(1 << curr);
  80222. while (curr + drop < max) {
  80223. left -= count[curr + drop];
  80224. if (left <= 0) break;
  80225. curr++;
  80226. left <<= 1;
  80227. }
  80228. /* check for enough space */
  80229. used += 1U << curr;
  80230. if (type == LENS && used >= ENOUGH - MAXD)
  80231. return 1;
  80232. /* point entry in root table to sub-table */
  80233. low = huff & mask;
  80234. (*table)[low].op = (unsigned char)curr;
  80235. (*table)[low].bits = (unsigned char)root;
  80236. (*table)[low].val = (unsigned short)(next - *table);
  80237. }
  80238. }
  80239. /*
  80240. Fill in rest of table for incomplete codes. This loop is similar to the
  80241. loop above in incrementing huff for table indices. It is assumed that
  80242. len is equal to curr + drop, so there is no loop needed to increment
  80243. through high index bits. When the current sub-table is filled, the loop
  80244. drops back to the root table to fill in any remaining entries there.
  80245. */
  80246. thisx.op = (unsigned char)64; /* invalid code marker */
  80247. thisx.bits = (unsigned char)(len - drop);
  80248. thisx.val = (unsigned short)0;
  80249. while (huff != 0) {
  80250. /* when done with sub-table, drop back to root table */
  80251. if (drop != 0 && (huff & mask) != low) {
  80252. drop = 0;
  80253. len = root;
  80254. next = *table;
  80255. thisx.bits = (unsigned char)len;
  80256. }
  80257. /* put invalid code marker in table */
  80258. next[huff >> drop] = thisx;
  80259. /* backwards increment the len-bit code huff */
  80260. incr = 1U << (len - 1);
  80261. while (huff & incr)
  80262. incr >>= 1;
  80263. if (incr != 0) {
  80264. huff &= incr - 1;
  80265. huff += incr;
  80266. }
  80267. else
  80268. huff = 0;
  80269. }
  80270. /* set return parameters */
  80271. *table += used;
  80272. *bits = root;
  80273. return 0;
  80274. }
  80275. /********* End of inlined file: inftrees.c *********/
  80276. /********* Start of inlined file: trees.c *********/
  80277. /*
  80278. * ALGORITHM
  80279. *
  80280. * The "deflation" process uses several Huffman trees. The more
  80281. * common source values are represented by shorter bit sequences.
  80282. *
  80283. * Each code tree is stored in a compressed form which is itself
  80284. * a Huffman encoding of the lengths of all the code strings (in
  80285. * ascending order by source values). The actual code strings are
  80286. * reconstructed from the lengths in the inflate process, as described
  80287. * in the deflate specification.
  80288. *
  80289. * REFERENCES
  80290. *
  80291. * Deutsch, L.P.,"'Deflate' Compressed Data Format Specification".
  80292. * Available in ftp.uu.net:/pub/archiving/zip/doc/deflate-1.1.doc
  80293. *
  80294. * Storer, James A.
  80295. * Data Compression: Methods and Theory, pp. 49-50.
  80296. * Computer Science Press, 1988. ISBN 0-7167-8156-5.
  80297. *
  80298. * Sedgewick, R.
  80299. * Algorithms, p290.
  80300. * Addison-Wesley, 1983. ISBN 0-201-06672-6.
  80301. */
  80302. /* @(#) $Id: trees.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  80303. /* #define GEN_TREES_H */
  80304. #ifdef DEBUG
  80305. # include <ctype.h>
  80306. #endif
  80307. /* ===========================================================================
  80308. * Constants
  80309. */
  80310. #define MAX_BL_BITS 7
  80311. /* Bit length codes must not exceed MAX_BL_BITS bits */
  80312. #define END_BLOCK 256
  80313. /* end of block literal code */
  80314. #define REP_3_6 16
  80315. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  80316. #define REPZ_3_10 17
  80317. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  80318. #define REPZ_11_138 18
  80319. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  80320. local const int extra_lbits[LENGTH_CODES] /* extra bits for each length code */
  80321. = {0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0};
  80322. local const int extra_dbits[D_CODES] /* extra bits for each distance code */
  80323. = {0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13};
  80324. local const int extra_blbits[BL_CODES]/* extra bits for each bit length code */
  80325. = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7};
  80326. local const uch bl_order[BL_CODES]
  80327. = {16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15};
  80328. /* The lengths of the bit length codes are sent in order of decreasing
  80329. * probability, to avoid transmitting the lengths for unused bit length codes.
  80330. */
  80331. #define Buf_size (8 * 2*sizeof(char))
  80332. /* Number of bits used within bi_buf. (bi_buf might be implemented on
  80333. * more than 16 bits on some systems.)
  80334. */
  80335. /* ===========================================================================
  80336. * Local data. These are initialized only once.
  80337. */
  80338. #define DIST_CODE_LEN 512 /* see definition of array dist_code below */
  80339. #if defined(GEN_TREES_H) || !defined(STDC)
  80340. /* non ANSI compilers may not accept trees.h */
  80341. local ct_data static_ltree[L_CODES+2];
  80342. /* The static literal tree. Since the bit lengths are imposed, there is no
  80343. * need for the L_CODES extra codes used during heap construction. However
  80344. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  80345. * below).
  80346. */
  80347. local ct_data static_dtree[D_CODES];
  80348. /* The static distance tree. (Actually a trivial tree since all codes use
  80349. * 5 bits.)
  80350. */
  80351. uch _dist_code[DIST_CODE_LEN];
  80352. /* Distance codes. The first 256 values correspond to the distances
  80353. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  80354. * the 15 bit distances.
  80355. */
  80356. uch _length_code[MAX_MATCH-MIN_MATCH+1];
  80357. /* length code for each normalized match length (0 == MIN_MATCH) */
  80358. local int base_length[LENGTH_CODES];
  80359. /* First normalized length for each code (0 = MIN_MATCH) */
  80360. local int base_dist[D_CODES];
  80361. /* First normalized distance for each code (0 = distance of 1) */
  80362. #else
  80363. /********* Start of inlined file: trees.h *********/
  80364. local const ct_data static_ltree[L_CODES+2] = {
  80365. {{ 12},{ 8}}, {{140},{ 8}}, {{ 76},{ 8}}, {{204},{ 8}}, {{ 44},{ 8}},
  80366. {{172},{ 8}}, {{108},{ 8}}, {{236},{ 8}}, {{ 28},{ 8}}, {{156},{ 8}},
  80367. {{ 92},{ 8}}, {{220},{ 8}}, {{ 60},{ 8}}, {{188},{ 8}}, {{124},{ 8}},
  80368. {{252},{ 8}}, {{ 2},{ 8}}, {{130},{ 8}}, {{ 66},{ 8}}, {{194},{ 8}},
  80369. {{ 34},{ 8}}, {{162},{ 8}}, {{ 98},{ 8}}, {{226},{ 8}}, {{ 18},{ 8}},
  80370. {{146},{ 8}}, {{ 82},{ 8}}, {{210},{ 8}}, {{ 50},{ 8}}, {{178},{ 8}},
  80371. {{114},{ 8}}, {{242},{ 8}}, {{ 10},{ 8}}, {{138},{ 8}}, {{ 74},{ 8}},
  80372. {{202},{ 8}}, {{ 42},{ 8}}, {{170},{ 8}}, {{106},{ 8}}, {{234},{ 8}},
  80373. {{ 26},{ 8}}, {{154},{ 8}}, {{ 90},{ 8}}, {{218},{ 8}}, {{ 58},{ 8}},
  80374. {{186},{ 8}}, {{122},{ 8}}, {{250},{ 8}}, {{ 6},{ 8}}, {{134},{ 8}},
  80375. {{ 70},{ 8}}, {{198},{ 8}}, {{ 38},{ 8}}, {{166},{ 8}}, {{102},{ 8}},
  80376. {{230},{ 8}}, {{ 22},{ 8}}, {{150},{ 8}}, {{ 86},{ 8}}, {{214},{ 8}},
  80377. {{ 54},{ 8}}, {{182},{ 8}}, {{118},{ 8}}, {{246},{ 8}}, {{ 14},{ 8}},
  80378. {{142},{ 8}}, {{ 78},{ 8}}, {{206},{ 8}}, {{ 46},{ 8}}, {{174},{ 8}},
  80379. {{110},{ 8}}, {{238},{ 8}}, {{ 30},{ 8}}, {{158},{ 8}}, {{ 94},{ 8}},
  80380. {{222},{ 8}}, {{ 62},{ 8}}, {{190},{ 8}}, {{126},{ 8}}, {{254},{ 8}},
  80381. {{ 1},{ 8}}, {{129},{ 8}}, {{ 65},{ 8}}, {{193},{ 8}}, {{ 33},{ 8}},
  80382. {{161},{ 8}}, {{ 97},{ 8}}, {{225},{ 8}}, {{ 17},{ 8}}, {{145},{ 8}},
  80383. {{ 81},{ 8}}, {{209},{ 8}}, {{ 49},{ 8}}, {{177},{ 8}}, {{113},{ 8}},
  80384. {{241},{ 8}}, {{ 9},{ 8}}, {{137},{ 8}}, {{ 73},{ 8}}, {{201},{ 8}},
  80385. {{ 41},{ 8}}, {{169},{ 8}}, {{105},{ 8}}, {{233},{ 8}}, {{ 25},{ 8}},
  80386. {{153},{ 8}}, {{ 89},{ 8}}, {{217},{ 8}}, {{ 57},{ 8}}, {{185},{ 8}},
  80387. {{121},{ 8}}, {{249},{ 8}}, {{ 5},{ 8}}, {{133},{ 8}}, {{ 69},{ 8}},
  80388. {{197},{ 8}}, {{ 37},{ 8}}, {{165},{ 8}}, {{101},{ 8}}, {{229},{ 8}},
  80389. {{ 21},{ 8}}, {{149},{ 8}}, {{ 85},{ 8}}, {{213},{ 8}}, {{ 53},{ 8}},
  80390. {{181},{ 8}}, {{117},{ 8}}, {{245},{ 8}}, {{ 13},{ 8}}, {{141},{ 8}},
  80391. {{ 77},{ 8}}, {{205},{ 8}}, {{ 45},{ 8}}, {{173},{ 8}}, {{109},{ 8}},
  80392. {{237},{ 8}}, {{ 29},{ 8}}, {{157},{ 8}}, {{ 93},{ 8}}, {{221},{ 8}},
  80393. {{ 61},{ 8}}, {{189},{ 8}}, {{125},{ 8}}, {{253},{ 8}}, {{ 19},{ 9}},
  80394. {{275},{ 9}}, {{147},{ 9}}, {{403},{ 9}}, {{ 83},{ 9}}, {{339},{ 9}},
  80395. {{211},{ 9}}, {{467},{ 9}}, {{ 51},{ 9}}, {{307},{ 9}}, {{179},{ 9}},
  80396. {{435},{ 9}}, {{115},{ 9}}, {{371},{ 9}}, {{243},{ 9}}, {{499},{ 9}},
  80397. {{ 11},{ 9}}, {{267},{ 9}}, {{139},{ 9}}, {{395},{ 9}}, {{ 75},{ 9}},
  80398. {{331},{ 9}}, {{203},{ 9}}, {{459},{ 9}}, {{ 43},{ 9}}, {{299},{ 9}},
  80399. {{171},{ 9}}, {{427},{ 9}}, {{107},{ 9}}, {{363},{ 9}}, {{235},{ 9}},
  80400. {{491},{ 9}}, {{ 27},{ 9}}, {{283},{ 9}}, {{155},{ 9}}, {{411},{ 9}},
  80401. {{ 91},{ 9}}, {{347},{ 9}}, {{219},{ 9}}, {{475},{ 9}}, {{ 59},{ 9}},
  80402. {{315},{ 9}}, {{187},{ 9}}, {{443},{ 9}}, {{123},{ 9}}, {{379},{ 9}},
  80403. {{251},{ 9}}, {{507},{ 9}}, {{ 7},{ 9}}, {{263},{ 9}}, {{135},{ 9}},
  80404. {{391},{ 9}}, {{ 71},{ 9}}, {{327},{ 9}}, {{199},{ 9}}, {{455},{ 9}},
  80405. {{ 39},{ 9}}, {{295},{ 9}}, {{167},{ 9}}, {{423},{ 9}}, {{103},{ 9}},
  80406. {{359},{ 9}}, {{231},{ 9}}, {{487},{ 9}}, {{ 23},{ 9}}, {{279},{ 9}},
  80407. {{151},{ 9}}, {{407},{ 9}}, {{ 87},{ 9}}, {{343},{ 9}}, {{215},{ 9}},
  80408. {{471},{ 9}}, {{ 55},{ 9}}, {{311},{ 9}}, {{183},{ 9}}, {{439},{ 9}},
  80409. {{119},{ 9}}, {{375},{ 9}}, {{247},{ 9}}, {{503},{ 9}}, {{ 15},{ 9}},
  80410. {{271},{ 9}}, {{143},{ 9}}, {{399},{ 9}}, {{ 79},{ 9}}, {{335},{ 9}},
  80411. {{207},{ 9}}, {{463},{ 9}}, {{ 47},{ 9}}, {{303},{ 9}}, {{175},{ 9}},
  80412. {{431},{ 9}}, {{111},{ 9}}, {{367},{ 9}}, {{239},{ 9}}, {{495},{ 9}},
  80413. {{ 31},{ 9}}, {{287},{ 9}}, {{159},{ 9}}, {{415},{ 9}}, {{ 95},{ 9}},
  80414. {{351},{ 9}}, {{223},{ 9}}, {{479},{ 9}}, {{ 63},{ 9}}, {{319},{ 9}},
  80415. {{191},{ 9}}, {{447},{ 9}}, {{127},{ 9}}, {{383},{ 9}}, {{255},{ 9}},
  80416. {{511},{ 9}}, {{ 0},{ 7}}, {{ 64},{ 7}}, {{ 32},{ 7}}, {{ 96},{ 7}},
  80417. {{ 16},{ 7}}, {{ 80},{ 7}}, {{ 48},{ 7}}, {{112},{ 7}}, {{ 8},{ 7}},
  80418. {{ 72},{ 7}}, {{ 40},{ 7}}, {{104},{ 7}}, {{ 24},{ 7}}, {{ 88},{ 7}},
  80419. {{ 56},{ 7}}, {{120},{ 7}}, {{ 4},{ 7}}, {{ 68},{ 7}}, {{ 36},{ 7}},
  80420. {{100},{ 7}}, {{ 20},{ 7}}, {{ 84},{ 7}}, {{ 52},{ 7}}, {{116},{ 7}},
  80421. {{ 3},{ 8}}, {{131},{ 8}}, {{ 67},{ 8}}, {{195},{ 8}}, {{ 35},{ 8}},
  80422. {{163},{ 8}}, {{ 99},{ 8}}, {{227},{ 8}}
  80423. };
  80424. local const ct_data static_dtree[D_CODES] = {
  80425. {{ 0},{ 5}}, {{16},{ 5}}, {{ 8},{ 5}}, {{24},{ 5}}, {{ 4},{ 5}},
  80426. {{20},{ 5}}, {{12},{ 5}}, {{28},{ 5}}, {{ 2},{ 5}}, {{18},{ 5}},
  80427. {{10},{ 5}}, {{26},{ 5}}, {{ 6},{ 5}}, {{22},{ 5}}, {{14},{ 5}},
  80428. {{30},{ 5}}, {{ 1},{ 5}}, {{17},{ 5}}, {{ 9},{ 5}}, {{25},{ 5}},
  80429. {{ 5},{ 5}}, {{21},{ 5}}, {{13},{ 5}}, {{29},{ 5}}, {{ 3},{ 5}},
  80430. {{19},{ 5}}, {{11},{ 5}}, {{27},{ 5}}, {{ 7},{ 5}}, {{23},{ 5}}
  80431. };
  80432. const uch _dist_code[DIST_CODE_LEN] = {
  80433. 0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8,
  80434. 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10,
  80435. 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11,
  80436. 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
  80437. 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13,
  80438. 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
  80439. 13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  80440. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  80441. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  80442. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15,
  80443. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
  80444. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
  80445. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 16, 17,
  80446. 18, 18, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22,
  80447. 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  80448. 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
  80449. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
  80450. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27,
  80451. 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  80452. 27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  80453. 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  80454. 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  80455. 28, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  80456. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  80457. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  80458. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29
  80459. };
  80460. const uch _length_code[MAX_MATCH-MIN_MATCH+1]= {
  80461. 0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 12, 12,
  80462. 13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16,
  80463. 17, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19,
  80464. 19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
  80465. 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22,
  80466. 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23,
  80467. 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  80468. 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  80469. 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
  80470. 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26,
  80471. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
  80472. 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  80473. 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28
  80474. };
  80475. local const int base_length[LENGTH_CODES] = {
  80476. 0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 32, 40, 48, 56,
  80477. 64, 80, 96, 112, 128, 160, 192, 224, 0
  80478. };
  80479. local const int base_dist[D_CODES] = {
  80480. 0, 1, 2, 3, 4, 6, 8, 12, 16, 24,
  80481. 32, 48, 64, 96, 128, 192, 256, 384, 512, 768,
  80482. 1024, 1536, 2048, 3072, 4096, 6144, 8192, 12288, 16384, 24576
  80483. };
  80484. /********* End of inlined file: trees.h *********/
  80485. #endif /* GEN_TREES_H */
  80486. struct static_tree_desc_s {
  80487. const ct_data *static_tree; /* static tree or NULL */
  80488. const intf *extra_bits; /* extra bits for each code or NULL */
  80489. int extra_base; /* base index for extra_bits */
  80490. int elems; /* max number of elements in the tree */
  80491. int max_length; /* max bit length for the codes */
  80492. };
  80493. local static_tree_desc static_l_desc =
  80494. {static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS};
  80495. local static_tree_desc static_d_desc =
  80496. {static_dtree, extra_dbits, 0, D_CODES, MAX_BITS};
  80497. local static_tree_desc static_bl_desc =
  80498. {(const ct_data *)0, extra_blbits, 0, BL_CODES, MAX_BL_BITS};
  80499. /* ===========================================================================
  80500. * Local (static) routines in this file.
  80501. */
  80502. local void tr_static_init OF((void));
  80503. local void init_block OF((deflate_state *s));
  80504. local void pqdownheap OF((deflate_state *s, ct_data *tree, int k));
  80505. local void gen_bitlen OF((deflate_state *s, tree_desc *desc));
  80506. local void gen_codes OF((ct_data *tree, int max_code, ushf *bl_count));
  80507. local void build_tree OF((deflate_state *s, tree_desc *desc));
  80508. local void scan_tree OF((deflate_state *s, ct_data *tree, int max_code));
  80509. local void send_tree OF((deflate_state *s, ct_data *tree, int max_code));
  80510. local int build_bl_tree OF((deflate_state *s));
  80511. local void send_all_trees OF((deflate_state *s, int lcodes, int dcodes,
  80512. int blcodes));
  80513. local void compress_block OF((deflate_state *s, ct_data *ltree,
  80514. ct_data *dtree));
  80515. local void set_data_type OF((deflate_state *s));
  80516. local unsigned bi_reverse OF((unsigned value, int length));
  80517. local void bi_windup OF((deflate_state *s));
  80518. local void bi_flush OF((deflate_state *s));
  80519. local void copy_block OF((deflate_state *s, charf *buf, unsigned len,
  80520. int header));
  80521. #ifdef GEN_TREES_H
  80522. local void gen_trees_header OF((void));
  80523. #endif
  80524. #ifndef DEBUG
  80525. # define send_code(s, c, tree) send_bits(s, tree[c].Code, tree[c].Len)
  80526. /* Send a code of the given tree. c and tree must not have side effects */
  80527. #else /* DEBUG */
  80528. # define send_code(s, c, tree) \
  80529. { if (z_verbose>2) fprintf(stderr,"\ncd %3d ",(c)); \
  80530. send_bits(s, tree[c].Code, tree[c].Len); }
  80531. #endif
  80532. /* ===========================================================================
  80533. * Output a short LSB first on the stream.
  80534. * IN assertion: there is enough room in pendingBuf.
  80535. */
  80536. #define put_short(s, w) { \
  80537. put_byte(s, (uch)((w) & 0xff)); \
  80538. put_byte(s, (uch)((ush)(w) >> 8)); \
  80539. }
  80540. /* ===========================================================================
  80541. * Send a value on a given number of bits.
  80542. * IN assertion: length <= 16 and value fits in length bits.
  80543. */
  80544. #ifdef DEBUG
  80545. local void send_bits OF((deflate_state *s, int value, int length));
  80546. local void send_bits (deflate_state *s, int value, int length)
  80547. {
  80548. Tracevv((stderr," l %2d v %4x ", length, value));
  80549. Assert(length > 0 && length <= 15, "invalid length");
  80550. s->bits_sent += (ulg)length;
  80551. /* If not enough room in bi_buf, use (valid) bits from bi_buf and
  80552. * (16 - bi_valid) bits from value, leaving (width - (16-bi_valid))
  80553. * unused bits in value.
  80554. */
  80555. if (s->bi_valid > (int)Buf_size - length) {
  80556. s->bi_buf |= (value << s->bi_valid);
  80557. put_short(s, s->bi_buf);
  80558. s->bi_buf = (ush)value >> (Buf_size - s->bi_valid);
  80559. s->bi_valid += length - Buf_size;
  80560. } else {
  80561. s->bi_buf |= value << s->bi_valid;
  80562. s->bi_valid += length;
  80563. }
  80564. }
  80565. #else /* !DEBUG */
  80566. #define send_bits(s, value, length) \
  80567. { int len = length;\
  80568. if (s->bi_valid > (int)Buf_size - len) {\
  80569. int val = value;\
  80570. s->bi_buf |= (val << s->bi_valid);\
  80571. put_short(s, s->bi_buf);\
  80572. s->bi_buf = (ush)val >> (Buf_size - s->bi_valid);\
  80573. s->bi_valid += len - Buf_size;\
  80574. } else {\
  80575. s->bi_buf |= (value) << s->bi_valid;\
  80576. s->bi_valid += len;\
  80577. }\
  80578. }
  80579. #endif /* DEBUG */
  80580. /* the arguments must not have side effects */
  80581. /* ===========================================================================
  80582. * Initialize the various 'constant' tables.
  80583. */
  80584. local void tr_static_init()
  80585. {
  80586. #if defined(GEN_TREES_H) || !defined(STDC)
  80587. static int static_init_done = 0;
  80588. int n; /* iterates over tree elements */
  80589. int bits; /* bit counter */
  80590. int length; /* length value */
  80591. int code; /* code value */
  80592. int dist; /* distance index */
  80593. ush bl_count[MAX_BITS+1];
  80594. /* number of codes at each bit length for an optimal tree */
  80595. if (static_init_done) return;
  80596. /* For some embedded targets, global variables are not initialized: */
  80597. static_l_desc.static_tree = static_ltree;
  80598. static_l_desc.extra_bits = extra_lbits;
  80599. static_d_desc.static_tree = static_dtree;
  80600. static_d_desc.extra_bits = extra_dbits;
  80601. static_bl_desc.extra_bits = extra_blbits;
  80602. /* Initialize the mapping length (0..255) -> length code (0..28) */
  80603. length = 0;
  80604. for (code = 0; code < LENGTH_CODES-1; code++) {
  80605. base_length[code] = length;
  80606. for (n = 0; n < (1<<extra_lbits[code]); n++) {
  80607. _length_code[length++] = (uch)code;
  80608. }
  80609. }
  80610. Assert (length == 256, "tr_static_init: length != 256");
  80611. /* Note that the length 255 (match length 258) can be represented
  80612. * in two different ways: code 284 + 5 bits or code 285, so we
  80613. * overwrite length_code[255] to use the best encoding:
  80614. */
  80615. _length_code[length-1] = (uch)code;
  80616. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  80617. dist = 0;
  80618. for (code = 0 ; code < 16; code++) {
  80619. base_dist[code] = dist;
  80620. for (n = 0; n < (1<<extra_dbits[code]); n++) {
  80621. _dist_code[dist++] = (uch)code;
  80622. }
  80623. }
  80624. Assert (dist == 256, "tr_static_init: dist != 256");
  80625. dist >>= 7; /* from now on, all distances are divided by 128 */
  80626. for ( ; code < D_CODES; code++) {
  80627. base_dist[code] = dist << 7;
  80628. for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
  80629. _dist_code[256 + dist++] = (uch)code;
  80630. }
  80631. }
  80632. Assert (dist == 256, "tr_static_init: 256+dist != 512");
  80633. /* Construct the codes of the static literal tree */
  80634. for (bits = 0; bits <= MAX_BITS; bits++) bl_count[bits] = 0;
  80635. n = 0;
  80636. while (n <= 143) static_ltree[n++].Len = 8, bl_count[8]++;
  80637. while (n <= 255) static_ltree[n++].Len = 9, bl_count[9]++;
  80638. while (n <= 279) static_ltree[n++].Len = 7, bl_count[7]++;
  80639. while (n <= 287) static_ltree[n++].Len = 8, bl_count[8]++;
  80640. /* Codes 286 and 287 do not exist, but we must include them in the
  80641. * tree construction to get a canonical Huffman tree (longest code
  80642. * all ones)
  80643. */
  80644. gen_codes((ct_data *)static_ltree, L_CODES+1, bl_count);
  80645. /* The static distance tree is trivial: */
  80646. for (n = 0; n < D_CODES; n++) {
  80647. static_dtree[n].Len = 5;
  80648. static_dtree[n].Code = bi_reverse((unsigned)n, 5);
  80649. }
  80650. static_init_done = 1;
  80651. # ifdef GEN_TREES_H
  80652. gen_trees_header();
  80653. # endif
  80654. #endif /* defined(GEN_TREES_H) || !defined(STDC) */
  80655. }
  80656. /* ===========================================================================
  80657. * Genererate the file trees.h describing the static trees.
  80658. */
  80659. #ifdef GEN_TREES_H
  80660. # ifndef DEBUG
  80661. # include <stdio.h>
  80662. # endif
  80663. # define SEPARATOR(i, last, width) \
  80664. ((i) == (last)? "\n};\n\n" : \
  80665. ((i) % (width) == (width)-1 ? ",\n" : ", "))
  80666. void gen_trees_header()
  80667. {
  80668. FILE *header = fopen("trees.h", "w");
  80669. int i;
  80670. Assert (header != NULL, "Can't open trees.h");
  80671. fprintf(header,
  80672. "/* header created automatically with -DGEN_TREES_H */\n\n");
  80673. fprintf(header, "local const ct_data static_ltree[L_CODES+2] = {\n");
  80674. for (i = 0; i < L_CODES+2; i++) {
  80675. fprintf(header, "{{%3u},{%3u}}%s", static_ltree[i].Code,
  80676. static_ltree[i].Len, SEPARATOR(i, L_CODES+1, 5));
  80677. }
  80678. fprintf(header, "local const ct_data static_dtree[D_CODES] = {\n");
  80679. for (i = 0; i < D_CODES; i++) {
  80680. fprintf(header, "{{%2u},{%2u}}%s", static_dtree[i].Code,
  80681. static_dtree[i].Len, SEPARATOR(i, D_CODES-1, 5));
  80682. }
  80683. fprintf(header, "const uch _dist_code[DIST_CODE_LEN] = {\n");
  80684. for (i = 0; i < DIST_CODE_LEN; i++) {
  80685. fprintf(header, "%2u%s", _dist_code[i],
  80686. SEPARATOR(i, DIST_CODE_LEN-1, 20));
  80687. }
  80688. fprintf(header, "const uch _length_code[MAX_MATCH-MIN_MATCH+1]= {\n");
  80689. for (i = 0; i < MAX_MATCH-MIN_MATCH+1; i++) {
  80690. fprintf(header, "%2u%s", _length_code[i],
  80691. SEPARATOR(i, MAX_MATCH-MIN_MATCH, 20));
  80692. }
  80693. fprintf(header, "local const int base_length[LENGTH_CODES] = {\n");
  80694. for (i = 0; i < LENGTH_CODES; i++) {
  80695. fprintf(header, "%1u%s", base_length[i],
  80696. SEPARATOR(i, LENGTH_CODES-1, 20));
  80697. }
  80698. fprintf(header, "local const int base_dist[D_CODES] = {\n");
  80699. for (i = 0; i < D_CODES; i++) {
  80700. fprintf(header, "%5u%s", base_dist[i],
  80701. SEPARATOR(i, D_CODES-1, 10));
  80702. }
  80703. fclose(header);
  80704. }
  80705. #endif /* GEN_TREES_H */
  80706. /* ===========================================================================
  80707. * Initialize the tree data structures for a new zlib stream.
  80708. */
  80709. void _tr_init(deflate_state *s)
  80710. {
  80711. tr_static_init();
  80712. s->l_desc.dyn_tree = s->dyn_ltree;
  80713. s->l_desc.stat_desc = &static_l_desc;
  80714. s->d_desc.dyn_tree = s->dyn_dtree;
  80715. s->d_desc.stat_desc = &static_d_desc;
  80716. s->bl_desc.dyn_tree = s->bl_tree;
  80717. s->bl_desc.stat_desc = &static_bl_desc;
  80718. s->bi_buf = 0;
  80719. s->bi_valid = 0;
  80720. s->last_eob_len = 8; /* enough lookahead for inflate */
  80721. #ifdef DEBUG
  80722. s->compressed_len = 0L;
  80723. s->bits_sent = 0L;
  80724. #endif
  80725. /* Initialize the first block of the first file: */
  80726. init_block(s);
  80727. }
  80728. /* ===========================================================================
  80729. * Initialize a new block.
  80730. */
  80731. local void init_block (deflate_state *s)
  80732. {
  80733. int n; /* iterates over tree elements */
  80734. /* Initialize the trees. */
  80735. for (n = 0; n < L_CODES; n++) s->dyn_ltree[n].Freq = 0;
  80736. for (n = 0; n < D_CODES; n++) s->dyn_dtree[n].Freq = 0;
  80737. for (n = 0; n < BL_CODES; n++) s->bl_tree[n].Freq = 0;
  80738. s->dyn_ltree[END_BLOCK].Freq = 1;
  80739. s->opt_len = s->static_len = 0L;
  80740. s->last_lit = s->matches = 0;
  80741. }
  80742. #define SMALLEST 1
  80743. /* Index within the heap array of least frequent node in the Huffman tree */
  80744. /* ===========================================================================
  80745. * Remove the smallest element from the heap and recreate the heap with
  80746. * one less element. Updates heap and heap_len.
  80747. */
  80748. #define pqremove(s, tree, top) \
  80749. {\
  80750. top = s->heap[SMALLEST]; \
  80751. s->heap[SMALLEST] = s->heap[s->heap_len--]; \
  80752. pqdownheap(s, tree, SMALLEST); \
  80753. }
  80754. /* ===========================================================================
  80755. * Compares to subtrees, using the tree depth as tie breaker when
  80756. * the subtrees have equal frequency. This minimizes the worst case length.
  80757. */
  80758. #define smaller(tree, n, m, depth) \
  80759. (tree[n].Freq < tree[m].Freq || \
  80760. (tree[n].Freq == tree[m].Freq && depth[n] <= depth[m]))
  80761. /* ===========================================================================
  80762. * Restore the heap property by moving down the tree starting at node k,
  80763. * exchanging a node with the smallest of its two sons if necessary, stopping
  80764. * when the heap property is re-established (each father smaller than its
  80765. * two sons).
  80766. */
  80767. local void pqdownheap (deflate_state *s,
  80768. ct_data *tree, /* the tree to restore */
  80769. int k) /* node to move down */
  80770. {
  80771. int v = s->heap[k];
  80772. int j = k << 1; /* left son of k */
  80773. while (j <= s->heap_len) {
  80774. /* Set j to the smallest of the two sons: */
  80775. if (j < s->heap_len &&
  80776. smaller(tree, s->heap[j+1], s->heap[j], s->depth)) {
  80777. j++;
  80778. }
  80779. /* Exit if v is smaller than both sons */
  80780. if (smaller(tree, v, s->heap[j], s->depth)) break;
  80781. /* Exchange v with the smallest son */
  80782. s->heap[k] = s->heap[j]; k = j;
  80783. /* And continue down the tree, setting j to the left son of k */
  80784. j <<= 1;
  80785. }
  80786. s->heap[k] = v;
  80787. }
  80788. /* ===========================================================================
  80789. * Compute the optimal bit lengths for a tree and update the total bit length
  80790. * for the current block.
  80791. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  80792. * above are the tree nodes sorted by increasing frequency.
  80793. * OUT assertions: the field len is set to the optimal bit length, the
  80794. * array bl_count contains the frequencies for each bit length.
  80795. * The length opt_len is updated; static_len is also updated if stree is
  80796. * not null.
  80797. */
  80798. local void gen_bitlen (deflate_state *s, tree_desc *desc)
  80799. {
  80800. ct_data *tree = desc->dyn_tree;
  80801. int max_code = desc->max_code;
  80802. const ct_data *stree = desc->stat_desc->static_tree;
  80803. const intf *extra = desc->stat_desc->extra_bits;
  80804. int base = desc->stat_desc->extra_base;
  80805. int max_length = desc->stat_desc->max_length;
  80806. int h; /* heap index */
  80807. int n, m; /* iterate over the tree elements */
  80808. int bits; /* bit length */
  80809. int xbits; /* extra bits */
  80810. ush f; /* frequency */
  80811. int overflow = 0; /* number of elements with bit length too large */
  80812. for (bits = 0; bits <= MAX_BITS; bits++) s->bl_count[bits] = 0;
  80813. /* In a first pass, compute the optimal bit lengths (which may
  80814. * overflow in the case of the bit length tree).
  80815. */
  80816. tree[s->heap[s->heap_max]].Len = 0; /* root of the heap */
  80817. for (h = s->heap_max+1; h < HEAP_SIZE; h++) {
  80818. n = s->heap[h];
  80819. bits = tree[tree[n].Dad].Len + 1;
  80820. if (bits > max_length) bits = max_length, overflow++;
  80821. tree[n].Len = (ush)bits;
  80822. /* We overwrite tree[n].Dad which is no longer needed */
  80823. if (n > max_code) continue; /* not a leaf node */
  80824. s->bl_count[bits]++;
  80825. xbits = 0;
  80826. if (n >= base) xbits = extra[n-base];
  80827. f = tree[n].Freq;
  80828. s->opt_len += (ulg)f * (bits + xbits);
  80829. if (stree) s->static_len += (ulg)f * (stree[n].Len + xbits);
  80830. }
  80831. if (overflow == 0) return;
  80832. Trace((stderr,"\nbit length overflow\n"));
  80833. /* This happens for example on obj2 and pic of the Calgary corpus */
  80834. /* Find the first bit length which could increase: */
  80835. do {
  80836. bits = max_length-1;
  80837. while (s->bl_count[bits] == 0) bits--;
  80838. s->bl_count[bits]--; /* move one leaf down the tree */
  80839. s->bl_count[bits+1] += 2; /* move one overflow item as its brother */
  80840. s->bl_count[max_length]--;
  80841. /* The brother of the overflow item also moves one step up,
  80842. * but this does not affect bl_count[max_length]
  80843. */
  80844. overflow -= 2;
  80845. } while (overflow > 0);
  80846. /* Now recompute all bit lengths, scanning in increasing frequency.
  80847. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  80848. * lengths instead of fixing only the wrong ones. This idea is taken
  80849. * from 'ar' written by Haruhiko Okumura.)
  80850. */
  80851. for (bits = max_length; bits != 0; bits--) {
  80852. n = s->bl_count[bits];
  80853. while (n != 0) {
  80854. m = s->heap[--h];
  80855. if (m > max_code) continue;
  80856. if ((unsigned) tree[m].Len != (unsigned) bits) {
  80857. Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  80858. s->opt_len += ((long)bits - (long)tree[m].Len)
  80859. *(long)tree[m].Freq;
  80860. tree[m].Len = (ush)bits;
  80861. }
  80862. n--;
  80863. }
  80864. }
  80865. }
  80866. /* ===========================================================================
  80867. * Generate the codes for a given tree and bit counts (which need not be
  80868. * optimal).
  80869. * IN assertion: the array bl_count contains the bit length statistics for
  80870. * the given tree and the field len is set for all tree elements.
  80871. * OUT assertion: the field code is set for all tree elements of non
  80872. * zero code length.
  80873. */
  80874. local void gen_codes (ct_data *tree, /* the tree to decorate */
  80875. int max_code, /* largest code with non zero frequency */
  80876. ushf *bl_count) /* number of codes at each bit length */
  80877. {
  80878. ush next_code[MAX_BITS+1]; /* next code value for each bit length */
  80879. ush code = 0; /* running code value */
  80880. int bits; /* bit index */
  80881. int n; /* code index */
  80882. /* The distribution counts are first used to generate the code values
  80883. * without bit reversal.
  80884. */
  80885. for (bits = 1; bits <= MAX_BITS; bits++) {
  80886. next_code[bits] = code = (code + bl_count[bits-1]) << 1;
  80887. }
  80888. /* Check that the bit counts in bl_count are consistent. The last code
  80889. * must be all ones.
  80890. */
  80891. Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  80892. "inconsistent bit counts");
  80893. Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  80894. for (n = 0; n <= max_code; n++) {
  80895. int len = tree[n].Len;
  80896. if (len == 0) continue;
  80897. /* Now reverse the bits */
  80898. tree[n].Code = bi_reverse(next_code[len]++, len);
  80899. Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  80900. n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  80901. }
  80902. }
  80903. /* ===========================================================================
  80904. * Construct one Huffman tree and assigns the code bit strings and lengths.
  80905. * Update the total bit length for the current block.
  80906. * IN assertion: the field freq is set for all tree elements.
  80907. * OUT assertions: the fields len and code are set to the optimal bit length
  80908. * and corresponding code. The length opt_len is updated; static_len is
  80909. * also updated if stree is not null. The field max_code is set.
  80910. */
  80911. local void build_tree (deflate_state *s,
  80912. tree_desc *desc) /* the tree descriptor */
  80913. {
  80914. ct_data *tree = desc->dyn_tree;
  80915. const ct_data *stree = desc->stat_desc->static_tree;
  80916. int elems = desc->stat_desc->elems;
  80917. int n, m; /* iterate over heap elements */
  80918. int max_code = -1; /* largest code with non zero frequency */
  80919. int node; /* new node being created */
  80920. /* Construct the initial heap, with least frequent element in
  80921. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  80922. * heap[0] is not used.
  80923. */
  80924. s->heap_len = 0, s->heap_max = HEAP_SIZE;
  80925. for (n = 0; n < elems; n++) {
  80926. if (tree[n].Freq != 0) {
  80927. s->heap[++(s->heap_len)] = max_code = n;
  80928. s->depth[n] = 0;
  80929. } else {
  80930. tree[n].Len = 0;
  80931. }
  80932. }
  80933. /* The pkzip format requires that at least one distance code exists,
  80934. * and that at least one bit should be sent even if there is only one
  80935. * possible code. So to avoid special checks later on we force at least
  80936. * two codes of non zero frequency.
  80937. */
  80938. while (s->heap_len < 2) {
  80939. node = s->heap[++(s->heap_len)] = (max_code < 2 ? ++max_code : 0);
  80940. tree[node].Freq = 1;
  80941. s->depth[node] = 0;
  80942. s->opt_len--; if (stree) s->static_len -= stree[node].Len;
  80943. /* node is 0 or 1 so it does not have extra bits */
  80944. }
  80945. desc->max_code = max_code;
  80946. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  80947. * establish sub-heaps of increasing lengths:
  80948. */
  80949. for (n = s->heap_len/2; n >= 1; n--) pqdownheap(s, tree, n);
  80950. /* Construct the Huffman tree by repeatedly combining the least two
  80951. * frequent nodes.
  80952. */
  80953. node = elems; /* next internal node of the tree */
  80954. do {
  80955. pqremove(s, tree, n); /* n = node of least frequency */
  80956. m = s->heap[SMALLEST]; /* m = node of next least frequency */
  80957. s->heap[--(s->heap_max)] = n; /* keep the nodes sorted by frequency */
  80958. s->heap[--(s->heap_max)] = m;
  80959. /* Create a new node father of n and m */
  80960. tree[node].Freq = tree[n].Freq + tree[m].Freq;
  80961. s->depth[node] = (uch)((s->depth[n] >= s->depth[m] ?
  80962. s->depth[n] : s->depth[m]) + 1);
  80963. tree[n].Dad = tree[m].Dad = (ush)node;
  80964. #ifdef DUMP_BL_TREE
  80965. if (tree == s->bl_tree) {
  80966. fprintf(stderr,"\nnode %d(%d), sons %d(%d) %d(%d)",
  80967. node, tree[node].Freq, n, tree[n].Freq, m, tree[m].Freq);
  80968. }
  80969. #endif
  80970. /* and insert the new node in the heap */
  80971. s->heap[SMALLEST] = node++;
  80972. pqdownheap(s, tree, SMALLEST);
  80973. } while (s->heap_len >= 2);
  80974. s->heap[--(s->heap_max)] = s->heap[SMALLEST];
  80975. /* At this point, the fields freq and dad are set. We can now
  80976. * generate the bit lengths.
  80977. */
  80978. gen_bitlen(s, (tree_desc *)desc);
  80979. /* The field len is now set, we can generate the bit codes */
  80980. gen_codes ((ct_data *)tree, max_code, s->bl_count);
  80981. }
  80982. /* ===========================================================================
  80983. * Scan a literal or distance tree to determine the frequencies of the codes
  80984. * in the bit length tree.
  80985. */
  80986. local void scan_tree (deflate_state *s,
  80987. ct_data *tree, /* the tree to be scanned */
  80988. int max_code) /* and its largest code of non zero frequency */
  80989. {
  80990. int n; /* iterates over all tree elements */
  80991. int prevlen = -1; /* last emitted length */
  80992. int curlen; /* length of current code */
  80993. int nextlen = tree[0].Len; /* length of next code */
  80994. int count = 0; /* repeat count of the current code */
  80995. int max_count = 7; /* max repeat count */
  80996. int min_count = 4; /* min repeat count */
  80997. if (nextlen == 0) max_count = 138, min_count = 3;
  80998. tree[max_code+1].Len = (ush)0xffff; /* guard */
  80999. for (n = 0; n <= max_code; n++) {
  81000. curlen = nextlen; nextlen = tree[n+1].Len;
  81001. if (++count < max_count && curlen == nextlen) {
  81002. continue;
  81003. } else if (count < min_count) {
  81004. s->bl_tree[curlen].Freq += count;
  81005. } else if (curlen != 0) {
  81006. if (curlen != prevlen) s->bl_tree[curlen].Freq++;
  81007. s->bl_tree[REP_3_6].Freq++;
  81008. } else if (count <= 10) {
  81009. s->bl_tree[REPZ_3_10].Freq++;
  81010. } else {
  81011. s->bl_tree[REPZ_11_138].Freq++;
  81012. }
  81013. count = 0; prevlen = curlen;
  81014. if (nextlen == 0) {
  81015. max_count = 138, min_count = 3;
  81016. } else if (curlen == nextlen) {
  81017. max_count = 6, min_count = 3;
  81018. } else {
  81019. max_count = 7, min_count = 4;
  81020. }
  81021. }
  81022. }
  81023. /* ===========================================================================
  81024. * Send a literal or distance tree in compressed form, using the codes in
  81025. * bl_tree.
  81026. */
  81027. local void send_tree (deflate_state *s,
  81028. ct_data *tree, /* the tree to be scanned */
  81029. int max_code) /* and its largest code of non zero frequency */
  81030. {
  81031. int n; /* iterates over all tree elements */
  81032. int prevlen = -1; /* last emitted length */
  81033. int curlen; /* length of current code */
  81034. int nextlen = tree[0].Len; /* length of next code */
  81035. int count = 0; /* repeat count of the current code */
  81036. int max_count = 7; /* max repeat count */
  81037. int min_count = 4; /* min repeat count */
  81038. /* tree[max_code+1].Len = -1; */ /* guard already set */
  81039. if (nextlen == 0) max_count = 138, min_count = 3;
  81040. for (n = 0; n <= max_code; n++) {
  81041. curlen = nextlen; nextlen = tree[n+1].Len;
  81042. if (++count < max_count && curlen == nextlen) {
  81043. continue;
  81044. } else if (count < min_count) {
  81045. do { send_code(s, curlen, s->bl_tree); } while (--count != 0);
  81046. } else if (curlen != 0) {
  81047. if (curlen != prevlen) {
  81048. send_code(s, curlen, s->bl_tree); count--;
  81049. }
  81050. Assert(count >= 3 && count <= 6, " 3_6?");
  81051. send_code(s, REP_3_6, s->bl_tree); send_bits(s, count-3, 2);
  81052. } else if (count <= 10) {
  81053. send_code(s, REPZ_3_10, s->bl_tree); send_bits(s, count-3, 3);
  81054. } else {
  81055. send_code(s, REPZ_11_138, s->bl_tree); send_bits(s, count-11, 7);
  81056. }
  81057. count = 0; prevlen = curlen;
  81058. if (nextlen == 0) {
  81059. max_count = 138, min_count = 3;
  81060. } else if (curlen == nextlen) {
  81061. max_count = 6, min_count = 3;
  81062. } else {
  81063. max_count = 7, min_count = 4;
  81064. }
  81065. }
  81066. }
  81067. /* ===========================================================================
  81068. * Construct the Huffman tree for the bit lengths and return the index in
  81069. * bl_order of the last bit length code to send.
  81070. */
  81071. local int build_bl_tree (deflate_state *s)
  81072. {
  81073. int max_blindex; /* index of last bit length code of non zero freq */
  81074. /* Determine the bit length frequencies for literal and distance trees */
  81075. scan_tree(s, (ct_data *)s->dyn_ltree, s->l_desc.max_code);
  81076. scan_tree(s, (ct_data *)s->dyn_dtree, s->d_desc.max_code);
  81077. /* Build the bit length tree: */
  81078. build_tree(s, (tree_desc *)(&(s->bl_desc)));
  81079. /* opt_len now includes the length of the tree representations, except
  81080. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  81081. */
  81082. /* Determine the number of bit length codes to send. The pkzip format
  81083. * requires that at least 4 bit length codes be sent. (appnote.txt says
  81084. * 3 but the actual value used is 4.)
  81085. */
  81086. for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
  81087. if (s->bl_tree[bl_order[max_blindex]].Len != 0) break;
  81088. }
  81089. /* Update opt_len to include the bit length tree and counts */
  81090. s->opt_len += 3*(max_blindex+1) + 5+5+4;
  81091. Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  81092. s->opt_len, s->static_len));
  81093. return max_blindex;
  81094. }
  81095. /* ===========================================================================
  81096. * Send the header for a block using dynamic Huffman trees: the counts, the
  81097. * lengths of the bit length codes, the literal tree and the distance tree.
  81098. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  81099. */
  81100. local void send_all_trees (deflate_state *s,
  81101. int lcodes, int dcodes, int blcodes) /* number of codes for each tree */
  81102. {
  81103. int rank; /* index in bl_order */
  81104. Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  81105. Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  81106. "too many codes");
  81107. Tracev((stderr, "\nbl counts: "));
  81108. send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
  81109. send_bits(s, dcodes-1, 5);
  81110. send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
  81111. for (rank = 0; rank < blcodes; rank++) {
  81112. Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  81113. send_bits(s, s->bl_tree[bl_order[rank]].Len, 3);
  81114. }
  81115. Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  81116. send_tree(s, (ct_data *)s->dyn_ltree, lcodes-1); /* literal tree */
  81117. Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  81118. send_tree(s, (ct_data *)s->dyn_dtree, dcodes-1); /* distance tree */
  81119. Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  81120. }
  81121. /* ===========================================================================
  81122. * Send a stored block
  81123. */
  81124. void _tr_stored_block (deflate_state *s, charf *buf, ulg stored_len, int eof)
  81125. {
  81126. send_bits(s, (STORED_BLOCK<<1)+eof, 3); /* send block type */
  81127. #ifdef DEBUG
  81128. s->compressed_len = (s->compressed_len + 3 + 7) & (ulg)~7L;
  81129. s->compressed_len += (stored_len + 4) << 3;
  81130. #endif
  81131. copy_block(s, buf, (unsigned)stored_len, 1); /* with header */
  81132. }
  81133. /* ===========================================================================
  81134. * Send one empty static block to give enough lookahead for inflate.
  81135. * This takes 10 bits, of which 7 may remain in the bit buffer.
  81136. * The current inflate code requires 9 bits of lookahead. If the
  81137. * last two codes for the previous block (real code plus EOB) were coded
  81138. * on 5 bits or less, inflate may have only 5+3 bits of lookahead to decode
  81139. * the last real code. In this case we send two empty static blocks instead
  81140. * of one. (There are no problems if the previous block is stored or fixed.)
  81141. * To simplify the code, we assume the worst case of last real code encoded
  81142. * on one bit only.
  81143. */
  81144. void _tr_align (deflate_state *s)
  81145. {
  81146. send_bits(s, STATIC_TREES<<1, 3);
  81147. send_code(s, END_BLOCK, static_ltree);
  81148. #ifdef DEBUG
  81149. s->compressed_len += 10L; /* 3 for block type, 7 for EOB */
  81150. #endif
  81151. bi_flush(s);
  81152. /* Of the 10 bits for the empty block, we have already sent
  81153. * (10 - bi_valid) bits. The lookahead for the last real code (before
  81154. * the EOB of the previous block) was thus at least one plus the length
  81155. * of the EOB plus what we have just sent of the empty static block.
  81156. */
  81157. if (1 + s->last_eob_len + 10 - s->bi_valid < 9) {
  81158. send_bits(s, STATIC_TREES<<1, 3);
  81159. send_code(s, END_BLOCK, static_ltree);
  81160. #ifdef DEBUG
  81161. s->compressed_len += 10L;
  81162. #endif
  81163. bi_flush(s);
  81164. }
  81165. s->last_eob_len = 7;
  81166. }
  81167. /* ===========================================================================
  81168. * Determine the best encoding for the current block: dynamic trees, static
  81169. * trees or store, and output the encoded block to the zip file.
  81170. */
  81171. void _tr_flush_block (deflate_state *s,
  81172. charf *buf, /* input block, or NULL if too old */
  81173. ulg stored_len, /* length of input block */
  81174. int eof) /* true if this is the last block for a file */
  81175. {
  81176. ulg opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  81177. int max_blindex = 0; /* index of last bit length code of non zero freq */
  81178. /* Build the Huffman trees unless a stored block is forced */
  81179. if (s->level > 0) {
  81180. /* Check if the file is binary or text */
  81181. if (stored_len > 0 && s->strm->data_type == Z_UNKNOWN)
  81182. set_data_type(s);
  81183. /* Construct the literal and distance trees */
  81184. build_tree(s, (tree_desc *)(&(s->l_desc)));
  81185. Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  81186. s->static_len));
  81187. build_tree(s, (tree_desc *)(&(s->d_desc)));
  81188. Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  81189. s->static_len));
  81190. /* At this point, opt_len and static_len are the total bit lengths of
  81191. * the compressed block data, excluding the tree representations.
  81192. */
  81193. /* Build the bit length tree for the above two trees, and get the index
  81194. * in bl_order of the last bit length code to send.
  81195. */
  81196. max_blindex = build_bl_tree(s);
  81197. /* Determine the best encoding. Compute the block lengths in bytes. */
  81198. opt_lenb = (s->opt_len+3+7)>>3;
  81199. static_lenb = (s->static_len+3+7)>>3;
  81200. Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  81201. opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  81202. s->last_lit));
  81203. if (static_lenb <= opt_lenb) opt_lenb = static_lenb;
  81204. } else {
  81205. Assert(buf != (char*)0, "lost buf");
  81206. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  81207. }
  81208. #ifdef FORCE_STORED
  81209. if (buf != (char*)0) { /* force stored block */
  81210. #else
  81211. if (stored_len+4 <= opt_lenb && buf != (char*)0) {
  81212. /* 4: two words for the lengths */
  81213. #endif
  81214. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  81215. * Otherwise we can't have processed more than WSIZE input bytes since
  81216. * the last block flush, because compression would have been
  81217. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  81218. * transform a block into a stored block.
  81219. */
  81220. _tr_stored_block(s, buf, stored_len, eof);
  81221. #ifdef FORCE_STATIC
  81222. } else if (static_lenb >= 0) { /* force static trees */
  81223. #else
  81224. } else if (s->strategy == Z_FIXED || static_lenb == opt_lenb) {
  81225. #endif
  81226. send_bits(s, (STATIC_TREES<<1)+eof, 3);
  81227. compress_block(s, (ct_data *)static_ltree, (ct_data *)static_dtree);
  81228. #ifdef DEBUG
  81229. s->compressed_len += 3 + s->static_len;
  81230. #endif
  81231. } else {
  81232. send_bits(s, (DYN_TREES<<1)+eof, 3);
  81233. send_all_trees(s, s->l_desc.max_code+1, s->d_desc.max_code+1,
  81234. max_blindex+1);
  81235. compress_block(s, (ct_data *)s->dyn_ltree, (ct_data *)s->dyn_dtree);
  81236. #ifdef DEBUG
  81237. s->compressed_len += 3 + s->opt_len;
  81238. #endif
  81239. }
  81240. Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  81241. /* The above check is made mod 2^32, for files larger than 512 MB
  81242. * and uLong implemented on 32 bits.
  81243. */
  81244. init_block(s);
  81245. if (eof) {
  81246. bi_windup(s);
  81247. #ifdef DEBUG
  81248. s->compressed_len += 7; /* align on byte boundary */
  81249. #endif
  81250. }
  81251. Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  81252. s->compressed_len-7*eof));
  81253. }
  81254. /* ===========================================================================
  81255. * Save the match info and tally the frequency counts. Return true if
  81256. * the current block must be flushed.
  81257. */
  81258. int _tr_tally (deflate_state *s,
  81259. unsigned dist, /* distance of matched string */
  81260. unsigned lc) /* match length-MIN_MATCH or unmatched char (if dist==0) */
  81261. {
  81262. s->d_buf[s->last_lit] = (ush)dist;
  81263. s->l_buf[s->last_lit++] = (uch)lc;
  81264. if (dist == 0) {
  81265. /* lc is the unmatched char */
  81266. s->dyn_ltree[lc].Freq++;
  81267. } else {
  81268. s->matches++;
  81269. /* Here, lc is the match length - MIN_MATCH */
  81270. dist--; /* dist = match distance - 1 */
  81271. Assert((ush)dist < (ush)MAX_DIST(s) &&
  81272. (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  81273. (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  81274. s->dyn_ltree[_length_code[lc]+LITERALS+1].Freq++;
  81275. s->dyn_dtree[d_code(dist)].Freq++;
  81276. }
  81277. #ifdef TRUNCATE_BLOCK
  81278. /* Try to guess if it is profitable to stop the current block here */
  81279. if ((s->last_lit & 0x1fff) == 0 && s->level > 2) {
  81280. /* Compute an upper bound for the compressed length */
  81281. ulg out_length = (ulg)s->last_lit*8L;
  81282. ulg in_length = (ulg)((long)s->strstart - s->block_start);
  81283. int dcode;
  81284. for (dcode = 0; dcode < D_CODES; dcode++) {
  81285. out_length += (ulg)s->dyn_dtree[dcode].Freq *
  81286. (5L+extra_dbits[dcode]);
  81287. }
  81288. out_length >>= 3;
  81289. Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  81290. s->last_lit, in_length, out_length,
  81291. 100L - out_length*100L/in_length));
  81292. if (s->matches < s->last_lit/2 && out_length < in_length/2) return 1;
  81293. }
  81294. #endif
  81295. return (s->last_lit == s->lit_bufsize-1);
  81296. /* We avoid equality with lit_bufsize because of wraparound at 64K
  81297. * on 16 bit machines and because stored blocks are restricted to
  81298. * 64K-1 bytes.
  81299. */
  81300. }
  81301. /* ===========================================================================
  81302. * Send the block data compressed using the given Huffman trees
  81303. */
  81304. local void compress_block (deflate_state *s,
  81305. ct_data *ltree, /* literal tree */
  81306. ct_data *dtree) /* distance tree */
  81307. {
  81308. unsigned dist; /* distance of matched string */
  81309. int lc; /* match length or unmatched char (if dist == 0) */
  81310. unsigned lx = 0; /* running index in l_buf */
  81311. unsigned code; /* the code to send */
  81312. int extra; /* number of extra bits to send */
  81313. if (s->last_lit != 0) do {
  81314. dist = s->d_buf[lx];
  81315. lc = s->l_buf[lx++];
  81316. if (dist == 0) {
  81317. send_code(s, lc, ltree); /* send a literal byte */
  81318. Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  81319. } else {
  81320. /* Here, lc is the match length - MIN_MATCH */
  81321. code = _length_code[lc];
  81322. send_code(s, code+LITERALS+1, ltree); /* send the length code */
  81323. extra = extra_lbits[code];
  81324. if (extra != 0) {
  81325. lc -= base_length[code];
  81326. send_bits(s, lc, extra); /* send the extra length bits */
  81327. }
  81328. dist--; /* dist is now the match distance - 1 */
  81329. code = d_code(dist);
  81330. Assert (code < D_CODES, "bad d_code");
  81331. send_code(s, code, dtree); /* send the distance code */
  81332. extra = extra_dbits[code];
  81333. if (extra != 0) {
  81334. dist -= base_dist[code];
  81335. send_bits(s, dist, extra); /* send the extra distance bits */
  81336. }
  81337. } /* literal or match pair ? */
  81338. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  81339. Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  81340. "pendingBuf overflow");
  81341. } while (lx < s->last_lit);
  81342. send_code(s, END_BLOCK, ltree);
  81343. s->last_eob_len = ltree[END_BLOCK].Len;
  81344. }
  81345. /* ===========================================================================
  81346. * Set the data type to BINARY or TEXT, using a crude approximation:
  81347. * set it to Z_TEXT if all symbols are either printable characters (33 to 255)
  81348. * or white spaces (9 to 13, or 32); or set it to Z_BINARY otherwise.
  81349. * IN assertion: the fields Freq of dyn_ltree are set.
  81350. */
  81351. local void set_data_type (deflate_state *s)
  81352. {
  81353. int n;
  81354. for (n = 0; n < 9; n++)
  81355. if (s->dyn_ltree[n].Freq != 0)
  81356. break;
  81357. if (n == 9)
  81358. for (n = 14; n < 32; n++)
  81359. if (s->dyn_ltree[n].Freq != 0)
  81360. break;
  81361. s->strm->data_type = (n == 32) ? Z_TEXT : Z_BINARY;
  81362. }
  81363. /* ===========================================================================
  81364. * Reverse the first len bits of a code, using straightforward code (a faster
  81365. * method would use a table)
  81366. * IN assertion: 1 <= len <= 15
  81367. */
  81368. local unsigned bi_reverse (unsigned code, int len)
  81369. {
  81370. register unsigned res = 0;
  81371. do {
  81372. res |= code & 1;
  81373. code >>= 1, res <<= 1;
  81374. } while (--len > 0);
  81375. return res >> 1;
  81376. }
  81377. /* ===========================================================================
  81378. * Flush the bit buffer, keeping at most 7 bits in it.
  81379. */
  81380. local void bi_flush (deflate_state *s)
  81381. {
  81382. if (s->bi_valid == 16) {
  81383. put_short(s, s->bi_buf);
  81384. s->bi_buf = 0;
  81385. s->bi_valid = 0;
  81386. } else if (s->bi_valid >= 8) {
  81387. put_byte(s, (Byte)s->bi_buf);
  81388. s->bi_buf >>= 8;
  81389. s->bi_valid -= 8;
  81390. }
  81391. }
  81392. /* ===========================================================================
  81393. * Flush the bit buffer and align the output on a byte boundary
  81394. */
  81395. local void bi_windup (deflate_state *s)
  81396. {
  81397. if (s->bi_valid > 8) {
  81398. put_short(s, s->bi_buf);
  81399. } else if (s->bi_valid > 0) {
  81400. put_byte(s, (Byte)s->bi_buf);
  81401. }
  81402. s->bi_buf = 0;
  81403. s->bi_valid = 0;
  81404. #ifdef DEBUG
  81405. s->bits_sent = (s->bits_sent+7) & ~7;
  81406. #endif
  81407. }
  81408. /* ===========================================================================
  81409. * Copy a stored block, storing first the length and its
  81410. * one's complement if requested.
  81411. */
  81412. local void copy_block(deflate_state *s,
  81413. charf *buf, /* the input data */
  81414. unsigned len, /* its length */
  81415. int header) /* true if block header must be written */
  81416. {
  81417. bi_windup(s); /* align on byte boundary */
  81418. s->last_eob_len = 8; /* enough lookahead for inflate */
  81419. if (header) {
  81420. put_short(s, (ush)len);
  81421. put_short(s, (ush)~len);
  81422. #ifdef DEBUG
  81423. s->bits_sent += 2*16;
  81424. #endif
  81425. }
  81426. #ifdef DEBUG
  81427. s->bits_sent += (ulg)len<<3;
  81428. #endif
  81429. while (len--) {
  81430. put_byte(s, *buf++);
  81431. }
  81432. }
  81433. /********* End of inlined file: trees.c *********/
  81434. /********* Start of inlined file: zutil.c *********/
  81435. /* @(#) $Id: zutil.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  81436. #ifndef NO_DUMMY_DECL
  81437. struct internal_state {int dummy;}; /* for buggy compilers */
  81438. #endif
  81439. const char * const z_errmsg[10] = {
  81440. "need dictionary", /* Z_NEED_DICT 2 */
  81441. "stream end", /* Z_STREAM_END 1 */
  81442. "", /* Z_OK 0 */
  81443. "file error", /* Z_ERRNO (-1) */
  81444. "stream error", /* Z_STREAM_ERROR (-2) */
  81445. "data error", /* Z_DATA_ERROR (-3) */
  81446. "insufficient memory", /* Z_MEM_ERROR (-4) */
  81447. "buffer error", /* Z_BUF_ERROR (-5) */
  81448. "incompatible version",/* Z_VERSION_ERROR (-6) */
  81449. ""};
  81450. /*const char * ZEXPORT zlibVersion()
  81451. {
  81452. return ZLIB_VERSION;
  81453. }
  81454. uLong ZEXPORT zlibCompileFlags()
  81455. {
  81456. uLong flags;
  81457. flags = 0;
  81458. switch (sizeof(uInt)) {
  81459. case 2: break;
  81460. case 4: flags += 1; break;
  81461. case 8: flags += 2; break;
  81462. default: flags += 3;
  81463. }
  81464. switch (sizeof(uLong)) {
  81465. case 2: break;
  81466. case 4: flags += 1 << 2; break;
  81467. case 8: flags += 2 << 2; break;
  81468. default: flags += 3 << 2;
  81469. }
  81470. switch (sizeof(voidpf)) {
  81471. case 2: break;
  81472. case 4: flags += 1 << 4; break;
  81473. case 8: flags += 2 << 4; break;
  81474. default: flags += 3 << 4;
  81475. }
  81476. switch (sizeof(z_off_t)) {
  81477. case 2: break;
  81478. case 4: flags += 1 << 6; break;
  81479. case 8: flags += 2 << 6; break;
  81480. default: flags += 3 << 6;
  81481. }
  81482. #ifdef DEBUG
  81483. flags += 1 << 8;
  81484. #endif
  81485. #if defined(ASMV) || defined(ASMINF)
  81486. flags += 1 << 9;
  81487. #endif
  81488. #ifdef ZLIB_WINAPI
  81489. flags += 1 << 10;
  81490. #endif
  81491. #ifdef BUILDFIXED
  81492. flags += 1 << 12;
  81493. #endif
  81494. #ifdef DYNAMIC_CRC_TABLE
  81495. flags += 1 << 13;
  81496. #endif
  81497. #ifdef NO_GZCOMPRESS
  81498. flags += 1L << 16;
  81499. #endif
  81500. #ifdef NO_GZIP
  81501. flags += 1L << 17;
  81502. #endif
  81503. #ifdef PKZIP_BUG_WORKAROUND
  81504. flags += 1L << 20;
  81505. #endif
  81506. #ifdef FASTEST
  81507. flags += 1L << 21;
  81508. #endif
  81509. #ifdef STDC
  81510. # ifdef NO_vsnprintf
  81511. flags += 1L << 25;
  81512. # ifdef HAS_vsprintf_void
  81513. flags += 1L << 26;
  81514. # endif
  81515. # else
  81516. # ifdef HAS_vsnprintf_void
  81517. flags += 1L << 26;
  81518. # endif
  81519. # endif
  81520. #else
  81521. flags += 1L << 24;
  81522. # ifdef NO_snprintf
  81523. flags += 1L << 25;
  81524. # ifdef HAS_sprintf_void
  81525. flags += 1L << 26;
  81526. # endif
  81527. # else
  81528. # ifdef HAS_snprintf_void
  81529. flags += 1L << 26;
  81530. # endif
  81531. # endif
  81532. #endif
  81533. return flags;
  81534. }*/
  81535. #ifdef DEBUG
  81536. # ifndef verbose
  81537. # define verbose 0
  81538. # endif
  81539. int z_verbose = verbose;
  81540. void z_error (const char *m)
  81541. {
  81542. fprintf(stderr, "%s\n", m);
  81543. exit(1);
  81544. }
  81545. #endif
  81546. /* exported to allow conversion of error code to string for compress() and
  81547. * uncompress()
  81548. */
  81549. const char * ZEXPORT zError(int err)
  81550. {
  81551. return ERR_MSG(err);
  81552. }
  81553. #if defined(_WIN32_WCE)
  81554. /* The Microsoft C Run-Time Library for Windows CE doesn't have
  81555. * errno. We define it as a global variable to simplify porting.
  81556. * Its value is always 0 and should not be used.
  81557. */
  81558. int errno = 0;
  81559. #endif
  81560. #ifndef HAVE_MEMCPY
  81561. void zmemcpy(dest, source, len)
  81562. Bytef* dest;
  81563. const Bytef* source;
  81564. uInt len;
  81565. {
  81566. if (len == 0) return;
  81567. do {
  81568. *dest++ = *source++; /* ??? to be unrolled */
  81569. } while (--len != 0);
  81570. }
  81571. int zmemcmp(s1, s2, len)
  81572. const Bytef* s1;
  81573. const Bytef* s2;
  81574. uInt len;
  81575. {
  81576. uInt j;
  81577. for (j = 0; j < len; j++) {
  81578. if (s1[j] != s2[j]) return 2*(s1[j] > s2[j])-1;
  81579. }
  81580. return 0;
  81581. }
  81582. void zmemzero(dest, len)
  81583. Bytef* dest;
  81584. uInt len;
  81585. {
  81586. if (len == 0) return;
  81587. do {
  81588. *dest++ = 0; /* ??? to be unrolled */
  81589. } while (--len != 0);
  81590. }
  81591. #endif
  81592. #ifdef SYS16BIT
  81593. #ifdef __TURBOC__
  81594. /* Turbo C in 16-bit mode */
  81595. # define MY_ZCALLOC
  81596. /* Turbo C malloc() does not allow dynamic allocation of 64K bytes
  81597. * and farmalloc(64K) returns a pointer with an offset of 8, so we
  81598. * must fix the pointer. Warning: the pointer must be put back to its
  81599. * original form in order to free it, use zcfree().
  81600. */
  81601. #define MAX_PTR 10
  81602. /* 10*64K = 640K */
  81603. local int next_ptr = 0;
  81604. typedef struct ptr_table_s {
  81605. voidpf org_ptr;
  81606. voidpf new_ptr;
  81607. } ptr_table;
  81608. local ptr_table table[MAX_PTR];
  81609. /* This table is used to remember the original form of pointers
  81610. * to large buffers (64K). Such pointers are normalized with a zero offset.
  81611. * Since MSDOS is not a preemptive multitasking OS, this table is not
  81612. * protected from concurrent access. This hack doesn't work anyway on
  81613. * a protected system like OS/2. Use Microsoft C instead.
  81614. */
  81615. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  81616. {
  81617. voidpf buf = opaque; /* just to make some compilers happy */
  81618. ulg bsize = (ulg)items*size;
  81619. /* If we allocate less than 65520 bytes, we assume that farmalloc
  81620. * will return a usable pointer which doesn't have to be normalized.
  81621. */
  81622. if (bsize < 65520L) {
  81623. buf = farmalloc(bsize);
  81624. if (*(ush*)&buf != 0) return buf;
  81625. } else {
  81626. buf = farmalloc(bsize + 16L);
  81627. }
  81628. if (buf == NULL || next_ptr >= MAX_PTR) return NULL;
  81629. table[next_ptr].org_ptr = buf;
  81630. /* Normalize the pointer to seg:0 */
  81631. *((ush*)&buf+1) += ((ush)((uch*)buf-0) + 15) >> 4;
  81632. *(ush*)&buf = 0;
  81633. table[next_ptr++].new_ptr = buf;
  81634. return buf;
  81635. }
  81636. void zcfree (voidpf opaque, voidpf ptr)
  81637. {
  81638. int n;
  81639. if (*(ush*)&ptr != 0) { /* object < 64K */
  81640. farfree(ptr);
  81641. return;
  81642. }
  81643. /* Find the original pointer */
  81644. for (n = 0; n < next_ptr; n++) {
  81645. if (ptr != table[n].new_ptr) continue;
  81646. farfree(table[n].org_ptr);
  81647. while (++n < next_ptr) {
  81648. table[n-1] = table[n];
  81649. }
  81650. next_ptr--;
  81651. return;
  81652. }
  81653. ptr = opaque; /* just to make some compilers happy */
  81654. Assert(0, "zcfree: ptr not found");
  81655. }
  81656. #endif /* __TURBOC__ */
  81657. #ifdef M_I86
  81658. /* Microsoft C in 16-bit mode */
  81659. # define MY_ZCALLOC
  81660. #if (!defined(_MSC_VER) || (_MSC_VER <= 600))
  81661. # define _halloc halloc
  81662. # define _hfree hfree
  81663. #endif
  81664. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  81665. {
  81666. if (opaque) opaque = 0; /* to make compiler happy */
  81667. return _halloc((long)items, size);
  81668. }
  81669. void zcfree (voidpf opaque, voidpf ptr)
  81670. {
  81671. if (opaque) opaque = 0; /* to make compiler happy */
  81672. _hfree(ptr);
  81673. }
  81674. #endif /* M_I86 */
  81675. #endif /* SYS16BIT */
  81676. #ifndef MY_ZCALLOC /* Any system without a special alloc function */
  81677. #ifndef STDC
  81678. extern voidp malloc OF((uInt size));
  81679. extern voidp calloc OF((uInt items, uInt size));
  81680. extern void free OF((voidpf ptr));
  81681. #endif
  81682. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  81683. {
  81684. if (opaque) items += size - size; /* make compiler happy */
  81685. return sizeof(uInt) > 2 ? (voidpf)malloc(items * size) :
  81686. (voidpf)calloc(items, size);
  81687. }
  81688. void zcfree (voidpf opaque, voidpf ptr)
  81689. {
  81690. free(ptr);
  81691. if (opaque) return; /* make compiler happy */
  81692. }
  81693. #endif /* MY_ZCALLOC */
  81694. /********* End of inlined file: zutil.c *********/
  81695. #undef Byte
  81696. }
  81697. #else
  81698. #include <zlib.h>
  81699. #endif
  81700. }
  81701. #if JUCE_MSVC
  81702. #pragma warning (pop)
  81703. #endif
  81704. BEGIN_JUCE_NAMESPACE
  81705. using namespace zlibNamespace;
  81706. // internal helper object that holds the zlib structures so they don't have to be
  81707. // included publicly.
  81708. class GZIPDecompressHelper
  81709. {
  81710. private:
  81711. z_stream* stream;
  81712. uint8* data;
  81713. int dataSize;
  81714. public:
  81715. bool finished, needsDictionary, error;
  81716. GZIPDecompressHelper (const bool noWrap) throw()
  81717. : data (0),
  81718. dataSize (0),
  81719. finished (false),
  81720. needsDictionary (false),
  81721. error (false)
  81722. {
  81723. stream = (z_stream*) juce_calloc (sizeof (z_stream));
  81724. if (inflateInit2 (stream, (noWrap) ? -MAX_WBITS
  81725. : MAX_WBITS) != Z_OK)
  81726. {
  81727. juce_free (stream);
  81728. stream = 0;
  81729. error = true;
  81730. finished = true;
  81731. }
  81732. }
  81733. ~GZIPDecompressHelper() throw()
  81734. {
  81735. if (stream != 0)
  81736. {
  81737. inflateEnd (stream);
  81738. juce_free (stream);
  81739. }
  81740. }
  81741. bool needsInput() const throw() { return dataSize <= 0; }
  81742. void setInput (uint8* const data_, const int size) throw()
  81743. {
  81744. data = data_;
  81745. dataSize = size;
  81746. }
  81747. int doNextBlock (uint8* const dest, const int destSize) throw()
  81748. {
  81749. if (stream != 0 && data != 0 && ! finished)
  81750. {
  81751. stream->next_in = data;
  81752. stream->next_out = dest;
  81753. stream->avail_in = dataSize;
  81754. stream->avail_out = destSize;
  81755. switch (inflate (stream, Z_PARTIAL_FLUSH))
  81756. {
  81757. case Z_STREAM_END:
  81758. finished = true;
  81759. // deliberate fall-through
  81760. case Z_OK:
  81761. data += dataSize - stream->avail_in;
  81762. dataSize = stream->avail_in;
  81763. return destSize - stream->avail_out;
  81764. case Z_NEED_DICT:
  81765. needsDictionary = true;
  81766. data += dataSize - stream->avail_in;
  81767. dataSize = stream->avail_in;
  81768. break;
  81769. case Z_DATA_ERROR:
  81770. case Z_MEM_ERROR:
  81771. error = true;
  81772. default:
  81773. break;
  81774. }
  81775. }
  81776. return 0;
  81777. }
  81778. };
  81779. const int gzipDecompBufferSize = 32768;
  81780. GZIPDecompressorInputStream::GZIPDecompressorInputStream (InputStream* const sourceStream_,
  81781. const bool deleteSourceWhenDestroyed_,
  81782. const bool noWrap_,
  81783. const int64 uncompressedStreamLength_)
  81784. : sourceStream (sourceStream_),
  81785. uncompressedStreamLength (uncompressedStreamLength_),
  81786. deleteSourceWhenDestroyed (deleteSourceWhenDestroyed_),
  81787. noWrap (noWrap_),
  81788. isEof (false),
  81789. activeBufferSize (0),
  81790. originalSourcePos (sourceStream_->getPosition()),
  81791. currentPos (0)
  81792. {
  81793. buffer = (uint8*) juce_malloc (gzipDecompBufferSize);
  81794. helper = new GZIPDecompressHelper (noWrap_);
  81795. }
  81796. GZIPDecompressorInputStream::~GZIPDecompressorInputStream()
  81797. {
  81798. juce_free (buffer);
  81799. if (deleteSourceWhenDestroyed)
  81800. delete sourceStream;
  81801. GZIPDecompressHelper* const h = (GZIPDecompressHelper*) helper;
  81802. delete h;
  81803. }
  81804. int64 GZIPDecompressorInputStream::getTotalLength()
  81805. {
  81806. return uncompressedStreamLength;
  81807. }
  81808. int GZIPDecompressorInputStream::read (void* destBuffer, int howMany)
  81809. {
  81810. GZIPDecompressHelper* const h = (GZIPDecompressHelper*) helper;
  81811. if ((howMany > 0) && ! isEof)
  81812. {
  81813. jassert (destBuffer != 0);
  81814. if (destBuffer != 0)
  81815. {
  81816. int numRead = 0;
  81817. uint8* d = (uint8*) destBuffer;
  81818. while (! h->error)
  81819. {
  81820. const int n = h->doNextBlock (d, howMany);
  81821. currentPos += n;
  81822. if (n == 0)
  81823. {
  81824. if (h->finished || h->needsDictionary)
  81825. {
  81826. isEof = true;
  81827. return numRead;
  81828. }
  81829. if (h->needsInput())
  81830. {
  81831. activeBufferSize = sourceStream->read (buffer, gzipDecompBufferSize);
  81832. if (activeBufferSize > 0)
  81833. {
  81834. h->setInput ((uint8*) buffer, activeBufferSize);
  81835. }
  81836. else
  81837. {
  81838. isEof = true;
  81839. return numRead;
  81840. }
  81841. }
  81842. }
  81843. else
  81844. {
  81845. numRead += n;
  81846. howMany -= n;
  81847. d += n;
  81848. if (howMany <= 0)
  81849. return numRead;
  81850. }
  81851. }
  81852. }
  81853. }
  81854. return 0;
  81855. }
  81856. bool GZIPDecompressorInputStream::isExhausted()
  81857. {
  81858. const GZIPDecompressHelper* const h = (GZIPDecompressHelper*) helper;
  81859. return h->error || isEof;
  81860. }
  81861. int64 GZIPDecompressorInputStream::getPosition()
  81862. {
  81863. return currentPos;
  81864. }
  81865. bool GZIPDecompressorInputStream::setPosition (int64 newPos)
  81866. {
  81867. if (newPos != currentPos)
  81868. {
  81869. if (newPos > currentPos)
  81870. {
  81871. skipNextBytes (newPos - currentPos);
  81872. }
  81873. else
  81874. {
  81875. // reset the stream and start again..
  81876. GZIPDecompressHelper* const h = (GZIPDecompressHelper*) helper;
  81877. delete h;
  81878. isEof = false;
  81879. activeBufferSize = 0;
  81880. currentPos = 0;
  81881. helper = new GZIPDecompressHelper (noWrap);
  81882. sourceStream->setPosition (originalSourcePos);
  81883. skipNextBytes (newPos);
  81884. }
  81885. }
  81886. return true;
  81887. }
  81888. END_JUCE_NAMESPACE
  81889. /********* End of inlined file: juce_GZIPDecompressorInputStream.cpp *********/
  81890. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  81891. /********* Start of inlined file: juce_FlacAudioFormat.cpp *********/
  81892. #ifdef _MSC_VER
  81893. #include <windows.h>
  81894. #endif
  81895. #if JUCE_USE_FLAC
  81896. #ifdef _MSC_VER
  81897. #pragma warning (disable : 4505)
  81898. #pragma warning (push)
  81899. #endif
  81900. namespace FlacNamespace
  81901. {
  81902. #if JUCE_INCLUDE_FLAC_CODE
  81903. #define FLAC__NO_DLL 1
  81904. #if ! defined (SIZE_MAX)
  81905. #define SIZE_MAX 0xffffffff
  81906. #endif
  81907. #define __STDC_LIMIT_MACROS 1
  81908. /********* Start of inlined file: all.h *********/
  81909. #ifndef FLAC__ALL_H
  81910. #define FLAC__ALL_H
  81911. /********* Start of inlined file: export.h *********/
  81912. #ifndef FLAC__EXPORT_H
  81913. #define FLAC__EXPORT_H
  81914. /** \file include/FLAC/export.h
  81915. *
  81916. * \brief
  81917. * This module contains #defines and symbols for exporting function
  81918. * calls, and providing version information and compiled-in features.
  81919. *
  81920. * See the \link flac_export export \endlink module.
  81921. */
  81922. /** \defgroup flac_export FLAC/export.h: export symbols
  81923. * \ingroup flac
  81924. *
  81925. * \brief
  81926. * This module contains #defines and symbols for exporting function
  81927. * calls, and providing version information and compiled-in features.
  81928. *
  81929. * If you are compiling with MSVC and will link to the static library
  81930. * (libFLAC.lib) you should define FLAC__NO_DLL in your project to
  81931. * make sure the symbols are exported properly.
  81932. *
  81933. * \{
  81934. */
  81935. #if defined(FLAC__NO_DLL) || !defined(_MSC_VER)
  81936. #define FLAC_API
  81937. #else
  81938. #ifdef FLAC_API_EXPORTS
  81939. #define FLAC_API _declspec(dllexport)
  81940. #else
  81941. #define FLAC_API _declspec(dllimport)
  81942. #endif
  81943. #endif
  81944. /** These #defines will mirror the libtool-based library version number, see
  81945. * http://www.gnu.org/software/libtool/manual.html#Libtool-versioning
  81946. */
  81947. #define FLAC_API_VERSION_CURRENT 10
  81948. #define FLAC_API_VERSION_REVISION 0 /**< see above */
  81949. #define FLAC_API_VERSION_AGE 2 /**< see above */
  81950. #ifdef __cplusplus
  81951. extern "C" {
  81952. #endif
  81953. /** \c 1 if the library has been compiled with support for Ogg FLAC, else \c 0. */
  81954. extern FLAC_API int FLAC_API_SUPPORTS_OGG_FLAC;
  81955. #ifdef __cplusplus
  81956. }
  81957. #endif
  81958. /* \} */
  81959. #endif
  81960. /********* End of inlined file: export.h *********/
  81961. /********* Start of inlined file: assert.h *********/
  81962. #ifndef FLAC__ASSERT_H
  81963. #define FLAC__ASSERT_H
  81964. /* we need this since some compilers (like MSVC) leave assert()s on release code (and we don't want to use their ASSERT) */
  81965. #ifdef DEBUG
  81966. #include <assert.h>
  81967. #define FLAC__ASSERT(x) assert(x)
  81968. #define FLAC__ASSERT_DECLARATION(x) x
  81969. #else
  81970. #define FLAC__ASSERT(x)
  81971. #define FLAC__ASSERT_DECLARATION(x)
  81972. #endif
  81973. #endif
  81974. /********* End of inlined file: assert.h *********/
  81975. /********* Start of inlined file: callback.h *********/
  81976. #ifndef FLAC__CALLBACK_H
  81977. #define FLAC__CALLBACK_H
  81978. /********* Start of inlined file: ordinals.h *********/
  81979. #ifndef FLAC__ORDINALS_H
  81980. #define FLAC__ORDINALS_H
  81981. #if !(defined(_MSC_VER) || defined(__BORLANDC__) || defined(__EMX__))
  81982. #include <inttypes.h>
  81983. #endif
  81984. typedef signed char FLAC__int8;
  81985. typedef unsigned char FLAC__uint8;
  81986. #if defined(_MSC_VER) || defined(__BORLANDC__)
  81987. typedef __int16 FLAC__int16;
  81988. typedef __int32 FLAC__int32;
  81989. typedef __int64 FLAC__int64;
  81990. typedef unsigned __int16 FLAC__uint16;
  81991. typedef unsigned __int32 FLAC__uint32;
  81992. typedef unsigned __int64 FLAC__uint64;
  81993. #elif defined(__EMX__)
  81994. typedef short FLAC__int16;
  81995. typedef long FLAC__int32;
  81996. typedef long long FLAC__int64;
  81997. typedef unsigned short FLAC__uint16;
  81998. typedef unsigned long FLAC__uint32;
  81999. typedef unsigned long long FLAC__uint64;
  82000. #else
  82001. typedef int16_t FLAC__int16;
  82002. typedef int32_t FLAC__int32;
  82003. typedef int64_t FLAC__int64;
  82004. typedef uint16_t FLAC__uint16;
  82005. typedef uint32_t FLAC__uint32;
  82006. typedef uint64_t FLAC__uint64;
  82007. #endif
  82008. typedef int FLAC__bool;
  82009. typedef FLAC__uint8 FLAC__byte;
  82010. #ifdef true
  82011. #undef true
  82012. #endif
  82013. #ifdef false
  82014. #undef false
  82015. #endif
  82016. #ifndef __cplusplus
  82017. #define true 1
  82018. #define false 0
  82019. #endif
  82020. #endif
  82021. /********* End of inlined file: ordinals.h *********/
  82022. #include <stdlib.h> /* for size_t */
  82023. /** \file include/FLAC/callback.h
  82024. *
  82025. * \brief
  82026. * This module defines the structures for describing I/O callbacks
  82027. * to the other FLAC interfaces.
  82028. *
  82029. * See the detailed documentation for callbacks in the
  82030. * \link flac_callbacks callbacks \endlink module.
  82031. */
  82032. /** \defgroup flac_callbacks FLAC/callback.h: I/O callback structures
  82033. * \ingroup flac
  82034. *
  82035. * \brief
  82036. * This module defines the structures for describing I/O callbacks
  82037. * to the other FLAC interfaces.
  82038. *
  82039. * The purpose of the I/O callback functions is to create a common way
  82040. * for the metadata interfaces to handle I/O.
  82041. *
  82042. * Originally the metadata interfaces required filenames as the way of
  82043. * specifying FLAC files to operate on. This is problematic in some
  82044. * environments so there is an additional option to specify a set of
  82045. * callbacks for doing I/O on the FLAC file, instead of the filename.
  82046. *
  82047. * In addition to the callbacks, a FLAC__IOHandle type is defined as an
  82048. * opaque structure for a data source.
  82049. *
  82050. * The callback function prototypes are similar (but not identical) to the
  82051. * stdio functions fread, fwrite, fseek, ftell, feof, and fclose. If you use
  82052. * stdio streams to implement the callbacks, you can pass fread, fwrite, and
  82053. * fclose anywhere a FLAC__IOCallback_Read, FLAC__IOCallback_Write, or
  82054. * FLAC__IOCallback_Close is required, and a FILE* anywhere a FLAC__IOHandle
  82055. * is required. \warning You generally CANNOT directly use fseek or ftell
  82056. * for FLAC__IOCallback_Seek or FLAC__IOCallback_Tell since on most systems
  82057. * these use 32-bit offsets and FLAC requires 64-bit offsets to deal with
  82058. * large files. You will have to find an equivalent function (e.g. ftello),
  82059. * or write a wrapper. The same is true for feof() since this is usually
  82060. * implemented as a macro, not as a function whose address can be taken.
  82061. *
  82062. * \{
  82063. */
  82064. #ifdef __cplusplus
  82065. extern "C" {
  82066. #endif
  82067. /** This is the opaque handle type used by the callbacks. Typically
  82068. * this is a \c FILE* or address of a file descriptor.
  82069. */
  82070. typedef void* FLAC__IOHandle;
  82071. /** Signature for the read callback.
  82072. * The signature and semantics match POSIX fread() implementations
  82073. * and can generally be used interchangeably.
  82074. *
  82075. * \param ptr The address of the read buffer.
  82076. * \param size The size of the records to be read.
  82077. * \param nmemb The number of records to be read.
  82078. * \param handle The handle to the data source.
  82079. * \retval size_t
  82080. * The number of records read.
  82081. */
  82082. typedef size_t (*FLAC__IOCallback_Read) (void *ptr, size_t size, size_t nmemb, FLAC__IOHandle handle);
  82083. /** Signature for the write callback.
  82084. * The signature and semantics match POSIX fwrite() implementations
  82085. * and can generally be used interchangeably.
  82086. *
  82087. * \param ptr The address of the write buffer.
  82088. * \param size The size of the records to be written.
  82089. * \param nmemb The number of records to be written.
  82090. * \param handle The handle to the data source.
  82091. * \retval size_t
  82092. * The number of records written.
  82093. */
  82094. typedef size_t (*FLAC__IOCallback_Write) (const void *ptr, size_t size, size_t nmemb, FLAC__IOHandle handle);
  82095. /** Signature for the seek callback.
  82096. * The signature and semantics mostly match POSIX fseek() WITH ONE IMPORTANT
  82097. * EXCEPTION: the offset is a 64-bit type whereas fseek() is generally 'long'
  82098. * and 32-bits wide.
  82099. *
  82100. * \param handle The handle to the data source.
  82101. * \param offset The new position, relative to \a whence
  82102. * \param whence \c SEEK_SET, \c SEEK_CUR, or \c SEEK_END
  82103. * \retval int
  82104. * \c 0 on success, \c -1 on error.
  82105. */
  82106. typedef int (*FLAC__IOCallback_Seek) (FLAC__IOHandle handle, FLAC__int64 offset, int whence);
  82107. /** Signature for the tell callback.
  82108. * The signature and semantics mostly match POSIX ftell() WITH ONE IMPORTANT
  82109. * EXCEPTION: the offset is a 64-bit type whereas ftell() is generally 'long'
  82110. * and 32-bits wide.
  82111. *
  82112. * \param handle The handle to the data source.
  82113. * \retval FLAC__int64
  82114. * The current position on success, \c -1 on error.
  82115. */
  82116. typedef FLAC__int64 (*FLAC__IOCallback_Tell) (FLAC__IOHandle handle);
  82117. /** Signature for the EOF callback.
  82118. * The signature and semantics mostly match POSIX feof() but WATCHOUT:
  82119. * on many systems, feof() is a macro, so in this case a wrapper function
  82120. * must be provided instead.
  82121. *
  82122. * \param handle The handle to the data source.
  82123. * \retval int
  82124. * \c 0 if not at end of file, nonzero if at end of file.
  82125. */
  82126. typedef int (*FLAC__IOCallback_Eof) (FLAC__IOHandle handle);
  82127. /** Signature for the close callback.
  82128. * The signature and semantics match POSIX fclose() implementations
  82129. * and can generally be used interchangeably.
  82130. *
  82131. * \param handle The handle to the data source.
  82132. * \retval int
  82133. * \c 0 on success, \c EOF on error.
  82134. */
  82135. typedef int (*FLAC__IOCallback_Close) (FLAC__IOHandle handle);
  82136. /** A structure for holding a set of callbacks.
  82137. * Each FLAC interface that requires a FLAC__IOCallbacks structure will
  82138. * describe which of the callbacks are required. The ones that are not
  82139. * required may be set to NULL.
  82140. *
  82141. * If the seek requirement for an interface is optional, you can signify that
  82142. * a data sorce is not seekable by setting the \a seek field to \c NULL.
  82143. */
  82144. typedef struct {
  82145. FLAC__IOCallback_Read read;
  82146. FLAC__IOCallback_Write write;
  82147. FLAC__IOCallback_Seek seek;
  82148. FLAC__IOCallback_Tell tell;
  82149. FLAC__IOCallback_Eof eof;
  82150. FLAC__IOCallback_Close close;
  82151. } FLAC__IOCallbacks;
  82152. /* \} */
  82153. #ifdef __cplusplus
  82154. }
  82155. #endif
  82156. #endif
  82157. /********* End of inlined file: callback.h *********/
  82158. /********* Start of inlined file: format.h *********/
  82159. #ifndef FLAC__FORMAT_H
  82160. #define FLAC__FORMAT_H
  82161. #ifdef __cplusplus
  82162. extern "C" {
  82163. #endif
  82164. /** \file include/FLAC/format.h
  82165. *
  82166. * \brief
  82167. * This module contains structure definitions for the representation
  82168. * of FLAC format components in memory. These are the basic
  82169. * structures used by the rest of the interfaces.
  82170. *
  82171. * See the detailed documentation in the
  82172. * \link flac_format format \endlink module.
  82173. */
  82174. /** \defgroup flac_format FLAC/format.h: format components
  82175. * \ingroup flac
  82176. *
  82177. * \brief
  82178. * This module contains structure definitions for the representation
  82179. * of FLAC format components in memory. These are the basic
  82180. * structures used by the rest of the interfaces.
  82181. *
  82182. * First, you should be familiar with the
  82183. * <A HREF="../format.html">FLAC format</A>. Many of the values here
  82184. * follow directly from the specification. As a user of libFLAC, the
  82185. * interesting parts really are the structures that describe the frame
  82186. * header and metadata blocks.
  82187. *
  82188. * The format structures here are very primitive, designed to store
  82189. * information in an efficient way. Reading information from the
  82190. * structures is easy but creating or modifying them directly is
  82191. * more complex. For the most part, as a user of a library, editing
  82192. * is not necessary; however, for metadata blocks it is, so there are
  82193. * convenience functions provided in the \link flac_metadata metadata
  82194. * module \endlink to simplify the manipulation of metadata blocks.
  82195. *
  82196. * \note
  82197. * It's not the best convention, but symbols ending in _LEN are in bits
  82198. * and _LENGTH are in bytes. _LENGTH symbols are \#defines instead of
  82199. * global variables because they are usually used when declaring byte
  82200. * arrays and some compilers require compile-time knowledge of array
  82201. * sizes when declared on the stack.
  82202. *
  82203. * \{
  82204. */
  82205. /*
  82206. Most of the values described in this file are defined by the FLAC
  82207. format specification. There is nothing to tune here.
  82208. */
  82209. /** The largest legal metadata type code. */
  82210. #define FLAC__MAX_METADATA_TYPE_CODE (126u)
  82211. /** The minimum block size, in samples, permitted by the format. */
  82212. #define FLAC__MIN_BLOCK_SIZE (16u)
  82213. /** The maximum block size, in samples, permitted by the format. */
  82214. #define FLAC__MAX_BLOCK_SIZE (65535u)
  82215. /** The maximum block size, in samples, permitted by the FLAC subset for
  82216. * sample rates up to 48kHz. */
  82217. #define FLAC__SUBSET_MAX_BLOCK_SIZE_48000HZ (4608u)
  82218. /** The maximum number of channels permitted by the format. */
  82219. #define FLAC__MAX_CHANNELS (8u)
  82220. /** The minimum sample resolution permitted by the format. */
  82221. #define FLAC__MIN_BITS_PER_SAMPLE (4u)
  82222. /** The maximum sample resolution permitted by the format. */
  82223. #define FLAC__MAX_BITS_PER_SAMPLE (32u)
  82224. /** The maximum sample resolution permitted by libFLAC.
  82225. *
  82226. * \warning
  82227. * FLAC__MAX_BITS_PER_SAMPLE is the limit of the FLAC format. However,
  82228. * the reference encoder/decoder is currently limited to 24 bits because
  82229. * of prevalent 32-bit math, so make sure and use this value when
  82230. * appropriate.
  82231. */
  82232. #define FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE (24u)
  82233. /** The maximum sample rate permitted by the format. The value is
  82234. * ((2 ^ 16) - 1) * 10; see <A HREF="../format.html">FLAC format</A>
  82235. * as to why.
  82236. */
  82237. #define FLAC__MAX_SAMPLE_RATE (655350u)
  82238. /** The maximum LPC order permitted by the format. */
  82239. #define FLAC__MAX_LPC_ORDER (32u)
  82240. /** The maximum LPC order permitted by the FLAC subset for sample rates
  82241. * up to 48kHz. */
  82242. #define FLAC__SUBSET_MAX_LPC_ORDER_48000HZ (12u)
  82243. /** The minimum quantized linear predictor coefficient precision
  82244. * permitted by the format.
  82245. */
  82246. #define FLAC__MIN_QLP_COEFF_PRECISION (5u)
  82247. /** The maximum quantized linear predictor coefficient precision
  82248. * permitted by the format.
  82249. */
  82250. #define FLAC__MAX_QLP_COEFF_PRECISION (15u)
  82251. /** The maximum order of the fixed predictors permitted by the format. */
  82252. #define FLAC__MAX_FIXED_ORDER (4u)
  82253. /** The maximum Rice partition order permitted by the format. */
  82254. #define FLAC__MAX_RICE_PARTITION_ORDER (15u)
  82255. /** The maximum Rice partition order permitted by the FLAC Subset. */
  82256. #define FLAC__SUBSET_MAX_RICE_PARTITION_ORDER (8u)
  82257. /** The version string of the release, stamped onto the libraries and binaries.
  82258. *
  82259. * \note
  82260. * This does not correspond to the shared library version number, which
  82261. * is used to determine binary compatibility.
  82262. */
  82263. extern FLAC_API const char *FLAC__VERSION_STRING;
  82264. /** The vendor string inserted by the encoder into the VORBIS_COMMENT block.
  82265. * This is a NUL-terminated ASCII string; when inserted into the
  82266. * VORBIS_COMMENT the trailing null is stripped.
  82267. */
  82268. extern FLAC_API const char *FLAC__VENDOR_STRING;
  82269. /** The byte string representation of the beginning of a FLAC stream. */
  82270. extern FLAC_API const FLAC__byte FLAC__STREAM_SYNC_STRING[4]; /* = "fLaC" */
  82271. /** The 32-bit integer big-endian representation of the beginning of
  82272. * a FLAC stream.
  82273. */
  82274. extern FLAC_API const unsigned FLAC__STREAM_SYNC; /* = 0x664C6143 */
  82275. /** The length of the FLAC signature in bits. */
  82276. extern FLAC_API const unsigned FLAC__STREAM_SYNC_LEN; /* = 32 bits */
  82277. /** The length of the FLAC signature in bytes. */
  82278. #define FLAC__STREAM_SYNC_LENGTH (4u)
  82279. /*****************************************************************************
  82280. *
  82281. * Subframe structures
  82282. *
  82283. *****************************************************************************/
  82284. /*****************************************************************************/
  82285. /** An enumeration of the available entropy coding methods. */
  82286. typedef enum {
  82287. FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE = 0,
  82288. /**< Residual is coded by partitioning into contexts, each with it's own
  82289. * 4-bit Rice parameter. */
  82290. FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2 = 1
  82291. /**< Residual is coded by partitioning into contexts, each with it's own
  82292. * 5-bit Rice parameter. */
  82293. } FLAC__EntropyCodingMethodType;
  82294. /** Maps a FLAC__EntropyCodingMethodType to a C string.
  82295. *
  82296. * Using a FLAC__EntropyCodingMethodType as the index to this array will
  82297. * give the string equivalent. The contents should not be modified.
  82298. */
  82299. extern FLAC_API const char * const FLAC__EntropyCodingMethodTypeString[];
  82300. /** Contents of a Rice partitioned residual
  82301. */
  82302. typedef struct {
  82303. unsigned *parameters;
  82304. /**< The Rice parameters for each context. */
  82305. unsigned *raw_bits;
  82306. /**< Widths for escape-coded partitions. Will be non-zero for escaped
  82307. * partitions and zero for unescaped partitions.
  82308. */
  82309. unsigned capacity_by_order;
  82310. /**< The capacity of the \a parameters and \a raw_bits arrays
  82311. * specified as an order, i.e. the number of array elements
  82312. * allocated is 2 ^ \a capacity_by_order.
  82313. */
  82314. } FLAC__EntropyCodingMethod_PartitionedRiceContents;
  82315. /** Header for a Rice partitioned residual. (c.f. <A HREF="../format.html#partitioned_rice">format specification</A>)
  82316. */
  82317. typedef struct {
  82318. unsigned order;
  82319. /**< The partition order, i.e. # of contexts = 2 ^ \a order. */
  82320. const FLAC__EntropyCodingMethod_PartitionedRiceContents *contents;
  82321. /**< The context's Rice parameters and/or raw bits. */
  82322. } FLAC__EntropyCodingMethod_PartitionedRice;
  82323. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN; /**< == 4 (bits) */
  82324. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN; /**< == 4 (bits) */
  82325. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN; /**< == 5 (bits) */
  82326. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN; /**< == 5 (bits) */
  82327. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  82328. /**< == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN)-1 */
  82329. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER;
  82330. /**< == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN)-1 */
  82331. /** Header for the entropy coding method. (c.f. <A HREF="../format.html#residual">format specification</A>)
  82332. */
  82333. typedef struct {
  82334. FLAC__EntropyCodingMethodType type;
  82335. union {
  82336. FLAC__EntropyCodingMethod_PartitionedRice partitioned_rice;
  82337. } data;
  82338. } FLAC__EntropyCodingMethod;
  82339. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_TYPE_LEN; /**< == 2 (bits) */
  82340. /*****************************************************************************/
  82341. /** An enumeration of the available subframe types. */
  82342. typedef enum {
  82343. FLAC__SUBFRAME_TYPE_CONSTANT = 0, /**< constant signal */
  82344. FLAC__SUBFRAME_TYPE_VERBATIM = 1, /**< uncompressed signal */
  82345. FLAC__SUBFRAME_TYPE_FIXED = 2, /**< fixed polynomial prediction */
  82346. FLAC__SUBFRAME_TYPE_LPC = 3 /**< linear prediction */
  82347. } FLAC__SubframeType;
  82348. /** Maps a FLAC__SubframeType to a C string.
  82349. *
  82350. * Using a FLAC__SubframeType as the index to this array will
  82351. * give the string equivalent. The contents should not be modified.
  82352. */
  82353. extern FLAC_API const char * const FLAC__SubframeTypeString[];
  82354. /** CONSTANT subframe. (c.f. <A HREF="../format.html#subframe_constant">format specification</A>)
  82355. */
  82356. typedef struct {
  82357. FLAC__int32 value; /**< The constant signal value. */
  82358. } FLAC__Subframe_Constant;
  82359. /** VERBATIM subframe. (c.f. <A HREF="../format.html#subframe_verbatim">format specification</A>)
  82360. */
  82361. typedef struct {
  82362. const FLAC__int32 *data; /**< A pointer to verbatim signal. */
  82363. } FLAC__Subframe_Verbatim;
  82364. /** FIXED subframe. (c.f. <A HREF="../format.html#subframe_fixed">format specification</A>)
  82365. */
  82366. typedef struct {
  82367. FLAC__EntropyCodingMethod entropy_coding_method;
  82368. /**< The residual coding method. */
  82369. unsigned order;
  82370. /**< The polynomial order. */
  82371. FLAC__int32 warmup[FLAC__MAX_FIXED_ORDER];
  82372. /**< Warmup samples to prime the predictor, length == order. */
  82373. const FLAC__int32 *residual;
  82374. /**< The residual signal, length == (blocksize minus order) samples. */
  82375. } FLAC__Subframe_Fixed;
  82376. /** LPC subframe. (c.f. <A HREF="../format.html#subframe_lpc">format specification</A>)
  82377. */
  82378. typedef struct {
  82379. FLAC__EntropyCodingMethod entropy_coding_method;
  82380. /**< The residual coding method. */
  82381. unsigned order;
  82382. /**< The FIR order. */
  82383. unsigned qlp_coeff_precision;
  82384. /**< Quantized FIR filter coefficient precision in bits. */
  82385. int quantization_level;
  82386. /**< The qlp coeff shift needed. */
  82387. FLAC__int32 qlp_coeff[FLAC__MAX_LPC_ORDER];
  82388. /**< FIR filter coefficients. */
  82389. FLAC__int32 warmup[FLAC__MAX_LPC_ORDER];
  82390. /**< Warmup samples to prime the predictor, length == order. */
  82391. const FLAC__int32 *residual;
  82392. /**< The residual signal, length == (blocksize minus order) samples. */
  82393. } FLAC__Subframe_LPC;
  82394. extern FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN; /**< == 4 (bits) */
  82395. extern FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN; /**< == 5 (bits) */
  82396. /** FLAC subframe structure. (c.f. <A HREF="../format.html#subframe">format specification</A>)
  82397. */
  82398. typedef struct {
  82399. FLAC__SubframeType type;
  82400. union {
  82401. FLAC__Subframe_Constant constant;
  82402. FLAC__Subframe_Fixed fixed;
  82403. FLAC__Subframe_LPC lpc;
  82404. FLAC__Subframe_Verbatim verbatim;
  82405. } data;
  82406. unsigned wasted_bits;
  82407. } FLAC__Subframe;
  82408. /** == 1 (bit)
  82409. *
  82410. * This used to be a zero-padding bit (hence the name
  82411. * FLAC__SUBFRAME_ZERO_PAD_LEN) but is now a reserved bit. It still has a
  82412. * mandatory value of \c 0 but in the future may take on the value \c 0 or \c 1
  82413. * to mean something else.
  82414. */
  82415. extern FLAC_API const unsigned FLAC__SUBFRAME_ZERO_PAD_LEN;
  82416. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LEN; /**< == 6 (bits) */
  82417. extern FLAC_API const unsigned FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN; /**< == 1 (bit) */
  82418. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_CONSTANT_BYTE_ALIGNED_MASK; /**< = 0x00 */
  82419. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_VERBATIM_BYTE_ALIGNED_MASK; /**< = 0x02 */
  82420. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_FIXED_BYTE_ALIGNED_MASK; /**< = 0x10 */
  82421. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LPC_BYTE_ALIGNED_MASK; /**< = 0x40 */
  82422. /*****************************************************************************/
  82423. /*****************************************************************************
  82424. *
  82425. * Frame structures
  82426. *
  82427. *****************************************************************************/
  82428. /** An enumeration of the available channel assignments. */
  82429. typedef enum {
  82430. FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT = 0, /**< independent channels */
  82431. FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE = 1, /**< left+side stereo */
  82432. FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE = 2, /**< right+side stereo */
  82433. FLAC__CHANNEL_ASSIGNMENT_MID_SIDE = 3 /**< mid+side stereo */
  82434. } FLAC__ChannelAssignment;
  82435. /** Maps a FLAC__ChannelAssignment to a C string.
  82436. *
  82437. * Using a FLAC__ChannelAssignment as the index to this array will
  82438. * give the string equivalent. The contents should not be modified.
  82439. */
  82440. extern FLAC_API const char * const FLAC__ChannelAssignmentString[];
  82441. /** An enumeration of the possible frame numbering methods. */
  82442. typedef enum {
  82443. FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER, /**< number contains the frame number */
  82444. FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER /**< number contains the sample number of first sample in frame */
  82445. } FLAC__FrameNumberType;
  82446. /** Maps a FLAC__FrameNumberType to a C string.
  82447. *
  82448. * Using a FLAC__FrameNumberType as the index to this array will
  82449. * give the string equivalent. The contents should not be modified.
  82450. */
  82451. extern FLAC_API const char * const FLAC__FrameNumberTypeString[];
  82452. /** FLAC frame header structure. (c.f. <A HREF="../format.html#frame_header">format specification</A>)
  82453. */
  82454. typedef struct {
  82455. unsigned blocksize;
  82456. /**< The number of samples per subframe. */
  82457. unsigned sample_rate;
  82458. /**< The sample rate in Hz. */
  82459. unsigned channels;
  82460. /**< The number of channels (== number of subframes). */
  82461. FLAC__ChannelAssignment channel_assignment;
  82462. /**< The channel assignment for the frame. */
  82463. unsigned bits_per_sample;
  82464. /**< The sample resolution. */
  82465. FLAC__FrameNumberType number_type;
  82466. /**< The numbering scheme used for the frame. As a convenience, the
  82467. * decoder will always convert a frame number to a sample number because
  82468. * the rules are complex. */
  82469. union {
  82470. FLAC__uint32 frame_number;
  82471. FLAC__uint64 sample_number;
  82472. } number;
  82473. /**< The frame number or sample number of first sample in frame;
  82474. * use the \a number_type value to determine which to use. */
  82475. FLAC__uint8 crc;
  82476. /**< CRC-8 (polynomial = x^8 + x^2 + x^1 + x^0, initialized with 0)
  82477. * of the raw frame header bytes, meaning everything before the CRC byte
  82478. * including the sync code.
  82479. */
  82480. } FLAC__FrameHeader;
  82481. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC; /**< == 0x3ffe; the frame header sync code */
  82482. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC_LEN; /**< == 14 (bits) */
  82483. extern FLAC_API const unsigned FLAC__FRAME_HEADER_RESERVED_LEN; /**< == 1 (bits) */
  82484. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN; /**< == 1 (bits) */
  82485. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCK_SIZE_LEN; /**< == 4 (bits) */
  82486. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SAMPLE_RATE_LEN; /**< == 4 (bits) */
  82487. extern FLAC_API const unsigned FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN; /**< == 4 (bits) */
  82488. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN; /**< == 3 (bits) */
  82489. extern FLAC_API const unsigned FLAC__FRAME_HEADER_ZERO_PAD_LEN; /**< == 1 (bit) */
  82490. extern FLAC_API const unsigned FLAC__FRAME_HEADER_CRC_LEN; /**< == 8 (bits) */
  82491. /** FLAC frame footer structure. (c.f. <A HREF="../format.html#frame_footer">format specification</A>)
  82492. */
  82493. typedef struct {
  82494. FLAC__uint16 crc;
  82495. /**< CRC-16 (polynomial = x^16 + x^15 + x^2 + x^0, initialized with
  82496. * 0) of the bytes before the crc, back to and including the frame header
  82497. * sync code.
  82498. */
  82499. } FLAC__FrameFooter;
  82500. extern FLAC_API const unsigned FLAC__FRAME_FOOTER_CRC_LEN; /**< == 16 (bits) */
  82501. /** FLAC frame structure. (c.f. <A HREF="../format.html#frame">format specification</A>)
  82502. */
  82503. typedef struct {
  82504. FLAC__FrameHeader header;
  82505. FLAC__Subframe subframes[FLAC__MAX_CHANNELS];
  82506. FLAC__FrameFooter footer;
  82507. } FLAC__Frame;
  82508. /*****************************************************************************/
  82509. /*****************************************************************************
  82510. *
  82511. * Meta-data structures
  82512. *
  82513. *****************************************************************************/
  82514. /** An enumeration of the available metadata block types. */
  82515. typedef enum {
  82516. FLAC__METADATA_TYPE_STREAMINFO = 0,
  82517. /**< <A HREF="../format.html#metadata_block_streaminfo">STREAMINFO</A> block */
  82518. FLAC__METADATA_TYPE_PADDING = 1,
  82519. /**< <A HREF="../format.html#metadata_block_padding">PADDING</A> block */
  82520. FLAC__METADATA_TYPE_APPLICATION = 2,
  82521. /**< <A HREF="../format.html#metadata_block_application">APPLICATION</A> block */
  82522. FLAC__METADATA_TYPE_SEEKTABLE = 3,
  82523. /**< <A HREF="../format.html#metadata_block_seektable">SEEKTABLE</A> block */
  82524. FLAC__METADATA_TYPE_VORBIS_COMMENT = 4,
  82525. /**< <A HREF="../format.html#metadata_block_vorbis_comment">VORBISCOMMENT</A> block (a.k.a. FLAC tags) */
  82526. FLAC__METADATA_TYPE_CUESHEET = 5,
  82527. /**< <A HREF="../format.html#metadata_block_cuesheet">CUESHEET</A> block */
  82528. FLAC__METADATA_TYPE_PICTURE = 6,
  82529. /**< <A HREF="../format.html#metadata_block_picture">PICTURE</A> block */
  82530. FLAC__METADATA_TYPE_UNDEFINED = 7
  82531. /**< marker to denote beginning of undefined type range; this number will increase as new metadata types are added */
  82532. } FLAC__MetadataType;
  82533. /** Maps a FLAC__MetadataType to a C string.
  82534. *
  82535. * Using a FLAC__MetadataType as the index to this array will
  82536. * give the string equivalent. The contents should not be modified.
  82537. */
  82538. extern FLAC_API const char * const FLAC__MetadataTypeString[];
  82539. /** FLAC STREAMINFO structure. (c.f. <A HREF="../format.html#metadata_block_streaminfo">format specification</A>)
  82540. */
  82541. typedef struct {
  82542. unsigned min_blocksize, max_blocksize;
  82543. unsigned min_framesize, max_framesize;
  82544. unsigned sample_rate;
  82545. unsigned channels;
  82546. unsigned bits_per_sample;
  82547. FLAC__uint64 total_samples;
  82548. FLAC__byte md5sum[16];
  82549. } FLAC__StreamMetadata_StreamInfo;
  82550. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN; /**< == 16 (bits) */
  82551. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN; /**< == 16 (bits) */
  82552. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN; /**< == 24 (bits) */
  82553. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN; /**< == 24 (bits) */
  82554. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN; /**< == 20 (bits) */
  82555. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN; /**< == 3 (bits) */
  82556. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN; /**< == 5 (bits) */
  82557. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN; /**< == 36 (bits) */
  82558. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MD5SUM_LEN; /**< == 128 (bits) */
  82559. /** The total stream length of the STREAMINFO block in bytes. */
  82560. #define FLAC__STREAM_METADATA_STREAMINFO_LENGTH (34u)
  82561. /** FLAC PADDING structure. (c.f. <A HREF="../format.html#metadata_block_padding">format specification</A>)
  82562. */
  82563. typedef struct {
  82564. int dummy;
  82565. /**< Conceptually this is an empty struct since we don't store the
  82566. * padding bytes. Empty structs are not allowed by some C compilers,
  82567. * hence the dummy.
  82568. */
  82569. } FLAC__StreamMetadata_Padding;
  82570. /** FLAC APPLICATION structure. (c.f. <A HREF="../format.html#metadata_block_application">format specification</A>)
  82571. */
  82572. typedef struct {
  82573. FLAC__byte id[4];
  82574. FLAC__byte *data;
  82575. } FLAC__StreamMetadata_Application;
  82576. extern FLAC_API const unsigned FLAC__STREAM_METADATA_APPLICATION_ID_LEN; /**< == 32 (bits) */
  82577. /** SeekPoint structure used in SEEKTABLE blocks. (c.f. <A HREF="../format.html#seekpoint">format specification</A>)
  82578. */
  82579. typedef struct {
  82580. FLAC__uint64 sample_number;
  82581. /**< The sample number of the target frame. */
  82582. FLAC__uint64 stream_offset;
  82583. /**< The offset, in bytes, of the target frame with respect to
  82584. * beginning of the first frame. */
  82585. unsigned frame_samples;
  82586. /**< The number of samples in the target frame. */
  82587. } FLAC__StreamMetadata_SeekPoint;
  82588. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN; /**< == 64 (bits) */
  82589. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN; /**< == 64 (bits) */
  82590. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN; /**< == 16 (bits) */
  82591. /** The total stream length of a seek point in bytes. */
  82592. #define FLAC__STREAM_METADATA_SEEKPOINT_LENGTH (18u)
  82593. /** The value used in the \a sample_number field of
  82594. * FLAC__StreamMetadataSeekPoint used to indicate a placeholder
  82595. * point (== 0xffffffffffffffff).
  82596. */
  82597. extern FLAC_API const FLAC__uint64 FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
  82598. /** FLAC SEEKTABLE structure. (c.f. <A HREF="../format.html#metadata_block_seektable">format specification</A>)
  82599. *
  82600. * \note From the format specification:
  82601. * - The seek points must be sorted by ascending sample number.
  82602. * - Each seek point's sample number must be the first sample of the
  82603. * target frame.
  82604. * - Each seek point's sample number must be unique within the table.
  82605. * - Existence of a SEEKTABLE block implies a correct setting of
  82606. * total_samples in the stream_info block.
  82607. * - Behavior is undefined when more than one SEEKTABLE block is
  82608. * present in a stream.
  82609. */
  82610. typedef struct {
  82611. unsigned num_points;
  82612. FLAC__StreamMetadata_SeekPoint *points;
  82613. } FLAC__StreamMetadata_SeekTable;
  82614. /** Vorbis comment entry structure used in VORBIS_COMMENT blocks. (c.f. <A HREF="../format.html#metadata_block_vorbis_comment">format specification</A>)
  82615. *
  82616. * For convenience, the APIs maintain a trailing NUL character at the end of
  82617. * \a entry which is not counted toward \a length, i.e.
  82618. * \code strlen(entry) == length \endcode
  82619. */
  82620. typedef struct {
  82621. FLAC__uint32 length;
  82622. FLAC__byte *entry;
  82623. } FLAC__StreamMetadata_VorbisComment_Entry;
  82624. extern FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN; /**< == 32 (bits) */
  82625. /** FLAC VORBIS_COMMENT structure. (c.f. <A HREF="../format.html#metadata_block_vorbis_comment">format specification</A>)
  82626. */
  82627. typedef struct {
  82628. FLAC__StreamMetadata_VorbisComment_Entry vendor_string;
  82629. FLAC__uint32 num_comments;
  82630. FLAC__StreamMetadata_VorbisComment_Entry *comments;
  82631. } FLAC__StreamMetadata_VorbisComment;
  82632. extern FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN; /**< == 32 (bits) */
  82633. /** FLAC CUESHEET track index structure. (See the
  82634. * <A HREF="../format.html#cuesheet_track_index">format specification</A> for
  82635. * the full description of each field.)
  82636. */
  82637. typedef struct {
  82638. FLAC__uint64 offset;
  82639. /**< Offset in samples, relative to the track offset, of the index
  82640. * point.
  82641. */
  82642. FLAC__byte number;
  82643. /**< The index point number. */
  82644. } FLAC__StreamMetadata_CueSheet_Index;
  82645. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN; /**< == 64 (bits) */
  82646. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN; /**< == 8 (bits) */
  82647. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN; /**< == 3*8 (bits) */
  82648. /** FLAC CUESHEET track structure. (See the
  82649. * <A HREF="../format.html#cuesheet_track">format specification</A> for
  82650. * the full description of each field.)
  82651. */
  82652. typedef struct {
  82653. FLAC__uint64 offset;
  82654. /**< Track offset in samples, relative to the beginning of the FLAC audio stream. */
  82655. FLAC__byte number;
  82656. /**< The track number. */
  82657. char isrc[13];
  82658. /**< Track ISRC. This is a 12-digit alphanumeric code plus a trailing \c NUL byte */
  82659. unsigned type:1;
  82660. /**< The track type: 0 for audio, 1 for non-audio. */
  82661. unsigned pre_emphasis:1;
  82662. /**< The pre-emphasis flag: 0 for no pre-emphasis, 1 for pre-emphasis. */
  82663. FLAC__byte num_indices;
  82664. /**< The number of track index points. */
  82665. FLAC__StreamMetadata_CueSheet_Index *indices;
  82666. /**< NULL if num_indices == 0, else pointer to array of index points. */
  82667. } FLAC__StreamMetadata_CueSheet_Track;
  82668. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN; /**< == 64 (bits) */
  82669. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN; /**< == 8 (bits) */
  82670. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN; /**< == 12*8 (bits) */
  82671. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN; /**< == 1 (bit) */
  82672. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN; /**< == 1 (bit) */
  82673. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN; /**< == 6+13*8 (bits) */
  82674. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN; /**< == 8 (bits) */
  82675. /** FLAC CUESHEET structure. (See the
  82676. * <A HREF="../format.html#metadata_block_cuesheet">format specification</A>
  82677. * for the full description of each field.)
  82678. */
  82679. typedef struct {
  82680. char media_catalog_number[129];
  82681. /**< Media catalog number, in ASCII printable characters 0x20-0x7e. In
  82682. * general, the media catalog number may be 0 to 128 bytes long; any
  82683. * unused characters should be right-padded with NUL characters.
  82684. */
  82685. FLAC__uint64 lead_in;
  82686. /**< The number of lead-in samples. */
  82687. FLAC__bool is_cd;
  82688. /**< \c true if CUESHEET corresponds to a Compact Disc, else \c false. */
  82689. unsigned num_tracks;
  82690. /**< The number of tracks. */
  82691. FLAC__StreamMetadata_CueSheet_Track *tracks;
  82692. /**< NULL if num_tracks == 0, else pointer to array of tracks. */
  82693. } FLAC__StreamMetadata_CueSheet;
  82694. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN; /**< == 128*8 (bits) */
  82695. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN; /**< == 64 (bits) */
  82696. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN; /**< == 1 (bit) */
  82697. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN; /**< == 7+258*8 (bits) */
  82698. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN; /**< == 8 (bits) */
  82699. /** An enumeration of the PICTURE types (see FLAC__StreamMetadataPicture and id3 v2.4 APIC tag). */
  82700. typedef enum {
  82701. FLAC__STREAM_METADATA_PICTURE_TYPE_OTHER = 0, /**< Other */
  82702. FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD = 1, /**< 32x32 pixels 'file icon' (PNG only) */
  82703. FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON = 2, /**< Other file icon */
  82704. FLAC__STREAM_METADATA_PICTURE_TYPE_FRONT_COVER = 3, /**< Cover (front) */
  82705. FLAC__STREAM_METADATA_PICTURE_TYPE_BACK_COVER = 4, /**< Cover (back) */
  82706. FLAC__STREAM_METADATA_PICTURE_TYPE_LEAFLET_PAGE = 5, /**< Leaflet page */
  82707. FLAC__STREAM_METADATA_PICTURE_TYPE_MEDIA = 6, /**< Media (e.g. label side of CD) */
  82708. FLAC__STREAM_METADATA_PICTURE_TYPE_LEAD_ARTIST = 7, /**< Lead artist/lead performer/soloist */
  82709. FLAC__STREAM_METADATA_PICTURE_TYPE_ARTIST = 8, /**< Artist/performer */
  82710. FLAC__STREAM_METADATA_PICTURE_TYPE_CONDUCTOR = 9, /**< Conductor */
  82711. FLAC__STREAM_METADATA_PICTURE_TYPE_BAND = 10, /**< Band/Orchestra */
  82712. FLAC__STREAM_METADATA_PICTURE_TYPE_COMPOSER = 11, /**< Composer */
  82713. FLAC__STREAM_METADATA_PICTURE_TYPE_LYRICIST = 12, /**< Lyricist/text writer */
  82714. FLAC__STREAM_METADATA_PICTURE_TYPE_RECORDING_LOCATION = 13, /**< Recording Location */
  82715. FLAC__STREAM_METADATA_PICTURE_TYPE_DURING_RECORDING = 14, /**< During recording */
  82716. FLAC__STREAM_METADATA_PICTURE_TYPE_DURING_PERFORMANCE = 15, /**< During performance */
  82717. FLAC__STREAM_METADATA_PICTURE_TYPE_VIDEO_SCREEN_CAPTURE = 16, /**< Movie/video screen capture */
  82718. FLAC__STREAM_METADATA_PICTURE_TYPE_FISH = 17, /**< A bright coloured fish */
  82719. FLAC__STREAM_METADATA_PICTURE_TYPE_ILLUSTRATION = 18, /**< Illustration */
  82720. FLAC__STREAM_METADATA_PICTURE_TYPE_BAND_LOGOTYPE = 19, /**< Band/artist logotype */
  82721. FLAC__STREAM_METADATA_PICTURE_TYPE_PUBLISHER_LOGOTYPE = 20, /**< Publisher/Studio logotype */
  82722. FLAC__STREAM_METADATA_PICTURE_TYPE_UNDEFINED
  82723. } FLAC__StreamMetadata_Picture_Type;
  82724. /** Maps a FLAC__StreamMetadata_Picture_Type to a C string.
  82725. *
  82726. * Using a FLAC__StreamMetadata_Picture_Type as the index to this array
  82727. * will give the string equivalent. The contents should not be
  82728. * modified.
  82729. */
  82730. extern FLAC_API const char * const FLAC__StreamMetadata_Picture_TypeString[];
  82731. /** FLAC PICTURE structure. (See the
  82732. * <A HREF="../format.html#metadata_block_picture">format specification</A>
  82733. * for the full description of each field.)
  82734. */
  82735. typedef struct {
  82736. FLAC__StreamMetadata_Picture_Type type;
  82737. /**< The kind of picture stored. */
  82738. char *mime_type;
  82739. /**< Picture data's MIME type, in ASCII printable characters
  82740. * 0x20-0x7e, NUL terminated. For best compatibility with players,
  82741. * use picture data of MIME type \c image/jpeg or \c image/png. A
  82742. * MIME type of '-->' is also allowed, in which case the picture
  82743. * data should be a complete URL. In file storage, the MIME type is
  82744. * stored as a 32-bit length followed by the ASCII string with no NUL
  82745. * terminator, but is converted to a plain C string in this structure
  82746. * for convenience.
  82747. */
  82748. FLAC__byte *description;
  82749. /**< Picture's description in UTF-8, NUL terminated. In file storage,
  82750. * the description is stored as a 32-bit length followed by the UTF-8
  82751. * string with no NUL terminator, but is converted to a plain C string
  82752. * in this structure for convenience.
  82753. */
  82754. FLAC__uint32 width;
  82755. /**< Picture's width in pixels. */
  82756. FLAC__uint32 height;
  82757. /**< Picture's height in pixels. */
  82758. FLAC__uint32 depth;
  82759. /**< Picture's color depth in bits-per-pixel. */
  82760. FLAC__uint32 colors;
  82761. /**< For indexed palettes (like GIF), picture's number of colors (the
  82762. * number of palette entries), or \c 0 for non-indexed (i.e. 2^depth).
  82763. */
  82764. FLAC__uint32 data_length;
  82765. /**< Length of binary picture data in bytes. */
  82766. FLAC__byte *data;
  82767. /**< Binary picture data. */
  82768. } FLAC__StreamMetadata_Picture;
  82769. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_TYPE_LEN; /**< == 32 (bits) */
  82770. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN; /**< == 32 (bits) */
  82771. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN; /**< == 32 (bits) */
  82772. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN; /**< == 32 (bits) */
  82773. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN; /**< == 32 (bits) */
  82774. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN; /**< == 32 (bits) */
  82775. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_COLORS_LEN; /**< == 32 (bits) */
  82776. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN; /**< == 32 (bits) */
  82777. /** Structure that is used when a metadata block of unknown type is loaded.
  82778. * The contents are opaque. The structure is used only internally to
  82779. * correctly handle unknown metadata.
  82780. */
  82781. typedef struct {
  82782. FLAC__byte *data;
  82783. } FLAC__StreamMetadata_Unknown;
  82784. /** FLAC metadata block structure. (c.f. <A HREF="../format.html#metadata_block">format specification</A>)
  82785. */
  82786. typedef struct {
  82787. FLAC__MetadataType type;
  82788. /**< The type of the metadata block; used determine which member of the
  82789. * \a data union to dereference. If type >= FLAC__METADATA_TYPE_UNDEFINED
  82790. * then \a data.unknown must be used. */
  82791. FLAC__bool is_last;
  82792. /**< \c true if this metadata block is the last, else \a false */
  82793. unsigned length;
  82794. /**< Length, in bytes, of the block data as it appears in the stream. */
  82795. union {
  82796. FLAC__StreamMetadata_StreamInfo stream_info;
  82797. FLAC__StreamMetadata_Padding padding;
  82798. FLAC__StreamMetadata_Application application;
  82799. FLAC__StreamMetadata_SeekTable seek_table;
  82800. FLAC__StreamMetadata_VorbisComment vorbis_comment;
  82801. FLAC__StreamMetadata_CueSheet cue_sheet;
  82802. FLAC__StreamMetadata_Picture picture;
  82803. FLAC__StreamMetadata_Unknown unknown;
  82804. } data;
  82805. /**< Polymorphic block data; use the \a type value to determine which
  82806. * to use. */
  82807. } FLAC__StreamMetadata;
  82808. extern FLAC_API const unsigned FLAC__STREAM_METADATA_IS_LAST_LEN; /**< == 1 (bit) */
  82809. extern FLAC_API const unsigned FLAC__STREAM_METADATA_TYPE_LEN; /**< == 7 (bits) */
  82810. extern FLAC_API const unsigned FLAC__STREAM_METADATA_LENGTH_LEN; /**< == 24 (bits) */
  82811. /** The total stream length of a metadata block header in bytes. */
  82812. #define FLAC__STREAM_METADATA_HEADER_LENGTH (4u)
  82813. /*****************************************************************************/
  82814. /*****************************************************************************
  82815. *
  82816. * Utility functions
  82817. *
  82818. *****************************************************************************/
  82819. /** Tests that a sample rate is valid for FLAC.
  82820. *
  82821. * \param sample_rate The sample rate to test for compliance.
  82822. * \retval FLAC__bool
  82823. * \c true if the given sample rate conforms to the specification, else
  82824. * \c false.
  82825. */
  82826. FLAC_API FLAC__bool FLAC__format_sample_rate_is_valid(unsigned sample_rate);
  82827. /** Tests that a sample rate is valid for the FLAC subset. The subset rules
  82828. * for valid sample rates are slightly more complex since the rate has to
  82829. * be expressible completely in the frame header.
  82830. *
  82831. * \param sample_rate The sample rate to test for compliance.
  82832. * \retval FLAC__bool
  82833. * \c true if the given sample rate conforms to the specification for the
  82834. * subset, else \c false.
  82835. */
  82836. FLAC_API FLAC__bool FLAC__format_sample_rate_is_subset(unsigned sample_rate);
  82837. /** Check a Vorbis comment entry name to see if it conforms to the Vorbis
  82838. * comment specification.
  82839. *
  82840. * Vorbis comment names must be composed only of characters from
  82841. * [0x20-0x3C,0x3E-0x7D].
  82842. *
  82843. * \param name A NUL-terminated string to be checked.
  82844. * \assert
  82845. * \code name != NULL \endcode
  82846. * \retval FLAC__bool
  82847. * \c false if entry name is illegal, else \c true.
  82848. */
  82849. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_name_is_legal(const char *name);
  82850. /** Check a Vorbis comment entry value to see if it conforms to the Vorbis
  82851. * comment specification.
  82852. *
  82853. * Vorbis comment values must be valid UTF-8 sequences.
  82854. *
  82855. * \param value A string to be checked.
  82856. * \param length A the length of \a value in bytes. May be
  82857. * \c (unsigned)(-1) to indicate that \a value is a plain
  82858. * UTF-8 NUL-terminated string.
  82859. * \assert
  82860. * \code value != NULL \endcode
  82861. * \retval FLAC__bool
  82862. * \c false if entry name is illegal, else \c true.
  82863. */
  82864. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_value_is_legal(const FLAC__byte *value, unsigned length);
  82865. /** Check a Vorbis comment entry to see if it conforms to the Vorbis
  82866. * comment specification.
  82867. *
  82868. * Vorbis comment entries must be of the form 'name=value', and 'name' and
  82869. * 'value' must be legal according to
  82870. * FLAC__format_vorbiscomment_entry_name_is_legal() and
  82871. * FLAC__format_vorbiscomment_entry_value_is_legal() respectively.
  82872. *
  82873. * \param entry An entry to be checked.
  82874. * \param length The length of \a entry in bytes.
  82875. * \assert
  82876. * \code value != NULL \endcode
  82877. * \retval FLAC__bool
  82878. * \c false if entry name is illegal, else \c true.
  82879. */
  82880. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_is_legal(const FLAC__byte *entry, unsigned length);
  82881. /** Check a seek table to see if it conforms to the FLAC specification.
  82882. * See the format specification for limits on the contents of the
  82883. * seek table.
  82884. *
  82885. * \param seek_table A pointer to a seek table to be checked.
  82886. * \assert
  82887. * \code seek_table != NULL \endcode
  82888. * \retval FLAC__bool
  82889. * \c false if seek table is illegal, else \c true.
  82890. */
  82891. FLAC_API FLAC__bool FLAC__format_seektable_is_legal(const FLAC__StreamMetadata_SeekTable *seek_table);
  82892. /** Sort a seek table's seek points according to the format specification.
  82893. * This includes a "unique-ification" step to remove duplicates, i.e.
  82894. * seek points with identical \a sample_number values. Duplicate seek
  82895. * points are converted into placeholder points and sorted to the end of
  82896. * the table.
  82897. *
  82898. * \param seek_table A pointer to a seek table to be sorted.
  82899. * \assert
  82900. * \code seek_table != NULL \endcode
  82901. * \retval unsigned
  82902. * The number of duplicate seek points converted into placeholders.
  82903. */
  82904. FLAC_API unsigned FLAC__format_seektable_sort(FLAC__StreamMetadata_SeekTable *seek_table);
  82905. /** Check a cue sheet to see if it conforms to the FLAC specification.
  82906. * See the format specification for limits on the contents of the
  82907. * cue sheet.
  82908. *
  82909. * \param cue_sheet A pointer to an existing cue sheet to be checked.
  82910. * \param check_cd_da_subset If \c true, check CUESHEET against more
  82911. * stringent requirements for a CD-DA (audio) disc.
  82912. * \param violation Address of a pointer to a string. If there is a
  82913. * violation, a pointer to a string explanation of the
  82914. * violation will be returned here. \a violation may be
  82915. * \c NULL if you don't need the returned string. Do not
  82916. * free the returned string; it will always point to static
  82917. * data.
  82918. * \assert
  82919. * \code cue_sheet != NULL \endcode
  82920. * \retval FLAC__bool
  82921. * \c false if cue sheet is illegal, else \c true.
  82922. */
  82923. FLAC_API FLAC__bool FLAC__format_cuesheet_is_legal(const FLAC__StreamMetadata_CueSheet *cue_sheet, FLAC__bool check_cd_da_subset, const char **violation);
  82924. /** Check picture data to see if it conforms to the FLAC specification.
  82925. * See the format specification for limits on the contents of the
  82926. * PICTURE block.
  82927. *
  82928. * \param picture A pointer to existing picture data to be checked.
  82929. * \param violation Address of a pointer to a string. If there is a
  82930. * violation, a pointer to a string explanation of the
  82931. * violation will be returned here. \a violation may be
  82932. * \c NULL if you don't need the returned string. Do not
  82933. * free the returned string; it will always point to static
  82934. * data.
  82935. * \assert
  82936. * \code picture != NULL \endcode
  82937. * \retval FLAC__bool
  82938. * \c false if picture data is illegal, else \c true.
  82939. */
  82940. FLAC_API FLAC__bool FLAC__format_picture_is_legal(const FLAC__StreamMetadata_Picture *picture, const char **violation);
  82941. /* \} */
  82942. #ifdef __cplusplus
  82943. }
  82944. #endif
  82945. #endif
  82946. /********* End of inlined file: format.h *********/
  82947. /********* Start of inlined file: metadata.h *********/
  82948. #ifndef FLAC__METADATA_H
  82949. #define FLAC__METADATA_H
  82950. #include <sys/types.h> /* for off_t */
  82951. /* --------------------------------------------------------------------
  82952. (For an example of how all these routines are used, see the source
  82953. code for the unit tests in src/test_libFLAC/metadata_*.c, or
  82954. metaflac in src/metaflac/)
  82955. ------------------------------------------------------------------*/
  82956. /** \file include/FLAC/metadata.h
  82957. *
  82958. * \brief
  82959. * This module provides functions for creating and manipulating FLAC
  82960. * metadata blocks in memory, and three progressively more powerful
  82961. * interfaces for traversing and editing metadata in FLAC files.
  82962. *
  82963. * See the detailed documentation for each interface in the
  82964. * \link flac_metadata metadata \endlink module.
  82965. */
  82966. /** \defgroup flac_metadata FLAC/metadata.h: metadata interfaces
  82967. * \ingroup flac
  82968. *
  82969. * \brief
  82970. * This module provides functions for creating and manipulating FLAC
  82971. * metadata blocks in memory, and three progressively more powerful
  82972. * interfaces for traversing and editing metadata in native FLAC files.
  82973. * Note that currently only the Chain interface (level 2) supports Ogg
  82974. * FLAC files, and it is read-only i.e. no writing back changed
  82975. * metadata to file.
  82976. *
  82977. * There are three metadata interfaces of increasing complexity:
  82978. *
  82979. * Level 0:
  82980. * Read-only access to the STREAMINFO, VORBIS_COMMENT, CUESHEET, and
  82981. * PICTURE blocks.
  82982. *
  82983. * Level 1:
  82984. * Read-write access to all metadata blocks. This level is write-
  82985. * efficient in most cases (more on this below), and uses less memory
  82986. * than level 2.
  82987. *
  82988. * Level 2:
  82989. * Read-write access to all metadata blocks. This level is write-
  82990. * efficient in all cases, but uses more memory since all metadata for
  82991. * the whole file is read into memory and manipulated before writing
  82992. * out again.
  82993. *
  82994. * What do we mean by efficient? Since FLAC metadata appears at the
  82995. * beginning of the file, when writing metadata back to a FLAC file
  82996. * it is possible to grow or shrink the metadata such that the entire
  82997. * file must be rewritten. However, if the size remains the same during
  82998. * changes or PADDING blocks are utilized, only the metadata needs to be
  82999. * overwritten, which is much faster.
  83000. *
  83001. * Efficient means the whole file is rewritten at most one time, and only
  83002. * when necessary. Level 1 is not efficient only in the case that you
  83003. * cause more than one metadata block to grow or shrink beyond what can
  83004. * be accomodated by padding. In this case you should probably use level
  83005. * 2, which allows you to edit all the metadata for a file in memory and
  83006. * write it out all at once.
  83007. *
  83008. * All levels know how to skip over and not disturb an ID3v2 tag at the
  83009. * front of the file.
  83010. *
  83011. * All levels access files via their filenames. In addition, level 2
  83012. * has additional alternative read and write functions that take an I/O
  83013. * handle and callbacks, for situations where access by filename is not
  83014. * possible.
  83015. *
  83016. * In addition to the three interfaces, this module defines functions for
  83017. * creating and manipulating various metadata objects in memory. As we see
  83018. * from the Format module, FLAC metadata blocks in memory are very primitive
  83019. * structures for storing information in an efficient way. Reading
  83020. * information from the structures is easy but creating or modifying them
  83021. * directly is more complex. The metadata object routines here facilitate
  83022. * this by taking care of the consistency and memory management drudgery.
  83023. *
  83024. * Unless you will be using the level 1 or 2 interfaces to modify existing
  83025. * metadata however, you will not probably not need these.
  83026. *
  83027. * From a dependency standpoint, none of the encoders or decoders require
  83028. * the metadata module. This is so that embedded users can strip out the
  83029. * metadata module from libFLAC to reduce the size and complexity.
  83030. */
  83031. #ifdef __cplusplus
  83032. extern "C" {
  83033. #endif
  83034. /** \defgroup flac_metadata_level0 FLAC/metadata.h: metadata level 0 interface
  83035. * \ingroup flac_metadata
  83036. *
  83037. * \brief
  83038. * The level 0 interface consists of individual routines to read the
  83039. * STREAMINFO, VORBIS_COMMENT, CUESHEET, and PICTURE blocks, requiring
  83040. * only a filename.
  83041. *
  83042. * They try to skip any ID3v2 tag at the head of the file.
  83043. *
  83044. * \{
  83045. */
  83046. /** Read the STREAMINFO metadata block of the given FLAC file. This function
  83047. * will try to skip any ID3v2 tag at the head of the file.
  83048. *
  83049. * \param filename The path to the FLAC file to read.
  83050. * \param streaminfo A pointer to space for the STREAMINFO block. Since
  83051. * FLAC__StreamMetadata is a simple structure with no
  83052. * memory allocation involved, you pass the address of
  83053. * an existing structure. It need not be initialized.
  83054. * \assert
  83055. * \code filename != NULL \endcode
  83056. * \code streaminfo != NULL \endcode
  83057. * \retval FLAC__bool
  83058. * \c true if a valid STREAMINFO block was read from \a filename. Returns
  83059. * \c false if there was a memory allocation error, a file decoder error,
  83060. * or the file contained no STREAMINFO block. (A memory allocation error
  83061. * is possible because this function must set up a file decoder.)
  83062. */
  83063. FLAC_API FLAC__bool FLAC__metadata_get_streaminfo(const char *filename, FLAC__StreamMetadata *streaminfo);
  83064. /** Read the VORBIS_COMMENT metadata block of the given FLAC file. This
  83065. * function will try to skip any ID3v2 tag at the head of the file.
  83066. *
  83067. * \param filename The path to the FLAC file to read.
  83068. * \param tags The address where the returned pointer will be
  83069. * stored. The \a tags object must be deleted by
  83070. * the caller using FLAC__metadata_object_delete().
  83071. * \assert
  83072. * \code filename != NULL \endcode
  83073. * \code tags != NULL \endcode
  83074. * \retval FLAC__bool
  83075. * \c true if a valid VORBIS_COMMENT block was read from \a filename,
  83076. * and \a *tags will be set to the address of the metadata structure.
  83077. * Returns \c false if there was a memory allocation error, a file
  83078. * decoder error, or the file contained no VORBIS_COMMENT block, and
  83079. * \a *tags will be set to \c NULL.
  83080. */
  83081. FLAC_API FLAC__bool FLAC__metadata_get_tags(const char *filename, FLAC__StreamMetadata **tags);
  83082. /** Read the CUESHEET metadata block of the given FLAC file. This
  83083. * function will try to skip any ID3v2 tag at the head of the file.
  83084. *
  83085. * \param filename The path to the FLAC file to read.
  83086. * \param cuesheet The address where the returned pointer will be
  83087. * stored. The \a cuesheet object must be deleted by
  83088. * the caller using FLAC__metadata_object_delete().
  83089. * \assert
  83090. * \code filename != NULL \endcode
  83091. * \code cuesheet != NULL \endcode
  83092. * \retval FLAC__bool
  83093. * \c true if a valid CUESHEET block was read from \a filename,
  83094. * and \a *cuesheet will be set to the address of the metadata
  83095. * structure. Returns \c false if there was a memory allocation
  83096. * error, a file decoder error, or the file contained no CUESHEET
  83097. * block, and \a *cuesheet will be set to \c NULL.
  83098. */
  83099. FLAC_API FLAC__bool FLAC__metadata_get_cuesheet(const char *filename, FLAC__StreamMetadata **cuesheet);
  83100. /** Read a PICTURE metadata block of the given FLAC file. This
  83101. * function will try to skip any ID3v2 tag at the head of the file.
  83102. * Since there can be more than one PICTURE block in a file, this
  83103. * function takes a number of parameters that act as constraints to
  83104. * the search. The PICTURE block with the largest area matching all
  83105. * the constraints will be returned, or \a *picture will be set to
  83106. * \c NULL if there was no such block.
  83107. *
  83108. * \param filename The path to the FLAC file to read.
  83109. * \param picture The address where the returned pointer will be
  83110. * stored. The \a picture object must be deleted by
  83111. * the caller using FLAC__metadata_object_delete().
  83112. * \param type The desired picture type. Use \c -1 to mean
  83113. * "any type".
  83114. * \param mime_type The desired MIME type, e.g. "image/jpeg". The
  83115. * string will be matched exactly. Use \c NULL to
  83116. * mean "any MIME type".
  83117. * \param description The desired description. The string will be
  83118. * matched exactly. Use \c NULL to mean "any
  83119. * description".
  83120. * \param max_width The maximum width in pixels desired. Use
  83121. * \c (unsigned)(-1) to mean "any width".
  83122. * \param max_height The maximum height in pixels desired. Use
  83123. * \c (unsigned)(-1) to mean "any height".
  83124. * \param max_depth The maximum color depth in bits-per-pixel desired.
  83125. * Use \c (unsigned)(-1) to mean "any depth".
  83126. * \param max_colors The maximum number of colors desired. Use
  83127. * \c (unsigned)(-1) to mean "any number of colors".
  83128. * \assert
  83129. * \code filename != NULL \endcode
  83130. * \code picture != NULL \endcode
  83131. * \retval FLAC__bool
  83132. * \c true if a valid PICTURE block was read from \a filename,
  83133. * and \a *picture will be set to the address of the metadata
  83134. * structure. Returns \c false if there was a memory allocation
  83135. * error, a file decoder error, or the file contained no PICTURE
  83136. * block, and \a *picture will be set to \c NULL.
  83137. */
  83138. FLAC_API FLAC__bool FLAC__metadata_get_picture(const char *filename, FLAC__StreamMetadata **picture, FLAC__StreamMetadata_Picture_Type type, const char *mime_type, const FLAC__byte *description, unsigned max_width, unsigned max_height, unsigned max_depth, unsigned max_colors);
  83139. /* \} */
  83140. /** \defgroup flac_metadata_level1 FLAC/metadata.h: metadata level 1 interface
  83141. * \ingroup flac_metadata
  83142. *
  83143. * \brief
  83144. * The level 1 interface provides read-write access to FLAC file metadata and
  83145. * operates directly on the FLAC file.
  83146. *
  83147. * The general usage of this interface is:
  83148. *
  83149. * - Create an iterator using FLAC__metadata_simple_iterator_new()
  83150. * - Attach it to a file using FLAC__metadata_simple_iterator_init() and check
  83151. * the exit code. Call FLAC__metadata_simple_iterator_is_writable() to
  83152. * see if the file is writable, or only read access is allowed.
  83153. * - Use FLAC__metadata_simple_iterator_next() and
  83154. * FLAC__metadata_simple_iterator_prev() to traverse the blocks.
  83155. * This is does not read the actual blocks themselves.
  83156. * FLAC__metadata_simple_iterator_next() is relatively fast.
  83157. * FLAC__metadata_simple_iterator_prev() is slower since it needs to search
  83158. * forward from the front of the file.
  83159. * - Use FLAC__metadata_simple_iterator_get_block_type() or
  83160. * FLAC__metadata_simple_iterator_get_block() to access the actual data at
  83161. * the current iterator position. The returned object is yours to modify
  83162. * and free.
  83163. * - Use FLAC__metadata_simple_iterator_set_block() to write a modified block
  83164. * back. You must have write permission to the original file. Make sure to
  83165. * read the whole comment to FLAC__metadata_simple_iterator_set_block()
  83166. * below.
  83167. * - Use FLAC__metadata_simple_iterator_insert_block_after() to add new blocks.
  83168. * Use the object creation functions from
  83169. * \link flac_metadata_object here \endlink to generate new objects.
  83170. * - Use FLAC__metadata_simple_iterator_delete_block() to remove the block
  83171. * currently referred to by the iterator, or replace it with padding.
  83172. * - Destroy the iterator with FLAC__metadata_simple_iterator_delete() when
  83173. * finished.
  83174. *
  83175. * \note
  83176. * The FLAC file remains open the whole time between
  83177. * FLAC__metadata_simple_iterator_init() and
  83178. * FLAC__metadata_simple_iterator_delete(), so make sure you are not altering
  83179. * the file during this time.
  83180. *
  83181. * \note
  83182. * Do not modify the \a is_last, \a length, or \a type fields of returned
  83183. * FLAC__StreamMetadata objects. These are managed automatically.
  83184. *
  83185. * \note
  83186. * If any of the modification functions
  83187. * (FLAC__metadata_simple_iterator_set_block(),
  83188. * FLAC__metadata_simple_iterator_delete_block(),
  83189. * FLAC__metadata_simple_iterator_insert_block_after(), etc.) return \c false,
  83190. * you should delete the iterator as it may no longer be valid.
  83191. *
  83192. * \{
  83193. */
  83194. struct FLAC__Metadata_SimpleIterator;
  83195. /** The opaque structure definition for the level 1 iterator type.
  83196. * See the
  83197. * \link flac_metadata_level1 metadata level 1 module \endlink
  83198. * for a detailed description.
  83199. */
  83200. typedef struct FLAC__Metadata_SimpleIterator FLAC__Metadata_SimpleIterator;
  83201. /** Status type for FLAC__Metadata_SimpleIterator.
  83202. *
  83203. * The iterator's current status can be obtained by calling FLAC__metadata_simple_iterator_status().
  83204. */
  83205. typedef enum {
  83206. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK = 0,
  83207. /**< The iterator is in the normal OK state */
  83208. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ILLEGAL_INPUT,
  83209. /**< The data passed into a function violated the function's usage criteria */
  83210. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ERROR_OPENING_FILE,
  83211. /**< The iterator could not open the target file */
  83212. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_A_FLAC_FILE,
  83213. /**< The iterator could not find the FLAC signature at the start of the file */
  83214. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_WRITABLE,
  83215. /**< The iterator tried to write to a file that was not writable */
  83216. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_BAD_METADATA,
  83217. /**< The iterator encountered input that does not conform to the FLAC metadata specification */
  83218. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR,
  83219. /**< The iterator encountered an error while reading the FLAC file */
  83220. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR,
  83221. /**< The iterator encountered an error while seeking in the FLAC file */
  83222. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_WRITE_ERROR,
  83223. /**< The iterator encountered an error while writing the FLAC file */
  83224. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_RENAME_ERROR,
  83225. /**< The iterator encountered an error renaming the FLAC file */
  83226. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_UNLINK_ERROR,
  83227. /**< The iterator encountered an error removing the temporary file */
  83228. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR,
  83229. /**< Memory allocation failed */
  83230. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_INTERNAL_ERROR
  83231. /**< The caller violated an assertion or an unexpected error occurred */
  83232. } FLAC__Metadata_SimpleIteratorStatus;
  83233. /** Maps a FLAC__Metadata_SimpleIteratorStatus to a C string.
  83234. *
  83235. * Using a FLAC__Metadata_SimpleIteratorStatus as the index to this array
  83236. * will give the string equivalent. The contents should not be modified.
  83237. */
  83238. extern FLAC_API const char * const FLAC__Metadata_SimpleIteratorStatusString[];
  83239. /** Create a new iterator instance.
  83240. *
  83241. * \retval FLAC__Metadata_SimpleIterator*
  83242. * \c NULL if there was an error allocating memory, else the new instance.
  83243. */
  83244. FLAC_API FLAC__Metadata_SimpleIterator *FLAC__metadata_simple_iterator_new(void);
  83245. /** Free an iterator instance. Deletes the object pointed to by \a iterator.
  83246. *
  83247. * \param iterator A pointer to an existing iterator.
  83248. * \assert
  83249. * \code iterator != NULL \endcode
  83250. */
  83251. FLAC_API void FLAC__metadata_simple_iterator_delete(FLAC__Metadata_SimpleIterator *iterator);
  83252. /** Get the current status of the iterator. Call this after a function
  83253. * returns \c false to get the reason for the error. Also resets the status
  83254. * to FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK.
  83255. *
  83256. * \param iterator A pointer to an existing iterator.
  83257. * \assert
  83258. * \code iterator != NULL \endcode
  83259. * \retval FLAC__Metadata_SimpleIteratorStatus
  83260. * The current status of the iterator.
  83261. */
  83262. FLAC_API FLAC__Metadata_SimpleIteratorStatus FLAC__metadata_simple_iterator_status(FLAC__Metadata_SimpleIterator *iterator);
  83263. /** Initialize the iterator to point to the first metadata block in the
  83264. * given FLAC file.
  83265. *
  83266. * \param iterator A pointer to an existing iterator.
  83267. * \param filename The path to the FLAC file.
  83268. * \param read_only If \c true, the FLAC file will be opened
  83269. * in read-only mode; if \c false, the FLAC
  83270. * file will be opened for edit even if no
  83271. * edits are performed.
  83272. * \param preserve_file_stats If \c true, the owner and modification
  83273. * time will be preserved even if the FLAC
  83274. * file is written to.
  83275. * \assert
  83276. * \code iterator != NULL \endcode
  83277. * \code filename != NULL \endcode
  83278. * \retval FLAC__bool
  83279. * \c false if a memory allocation error occurs, the file can't be
  83280. * opened, or another error occurs, else \c true.
  83281. */
  83282. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_init(FLAC__Metadata_SimpleIterator *iterator, const char *filename, FLAC__bool read_only, FLAC__bool preserve_file_stats);
  83283. /** Returns \c true if the FLAC file is writable. If \c false, calls to
  83284. * FLAC__metadata_simple_iterator_set_block() and
  83285. * FLAC__metadata_simple_iterator_insert_block_after() will fail.
  83286. *
  83287. * \param iterator A pointer to an existing iterator.
  83288. * \assert
  83289. * \code iterator != NULL \endcode
  83290. * \retval FLAC__bool
  83291. * See above.
  83292. */
  83293. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_is_writable(const FLAC__Metadata_SimpleIterator *iterator);
  83294. /** Moves the iterator forward one metadata block, returning \c false if
  83295. * already at the end.
  83296. *
  83297. * \param iterator A pointer to an existing initialized iterator.
  83298. * \assert
  83299. * \code iterator != NULL \endcode
  83300. * \a iterator has been successfully initialized with
  83301. * FLAC__metadata_simple_iterator_init()
  83302. * \retval FLAC__bool
  83303. * \c false if already at the last metadata block of the chain, else
  83304. * \c true.
  83305. */
  83306. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_next(FLAC__Metadata_SimpleIterator *iterator);
  83307. /** Moves the iterator backward one metadata block, returning \c false if
  83308. * already at the beginning.
  83309. *
  83310. * \param iterator A pointer to an existing initialized iterator.
  83311. * \assert
  83312. * \code iterator != NULL \endcode
  83313. * \a iterator has been successfully initialized with
  83314. * FLAC__metadata_simple_iterator_init()
  83315. * \retval FLAC__bool
  83316. * \c false if already at the first metadata block of the chain, else
  83317. * \c true.
  83318. */
  83319. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_prev(FLAC__Metadata_SimpleIterator *iterator);
  83320. /** Returns a flag telling if the current metadata block is the last.
  83321. *
  83322. * \param iterator A pointer to an existing initialized iterator.
  83323. * \assert
  83324. * \code iterator != NULL \endcode
  83325. * \a iterator has been successfully initialized with
  83326. * FLAC__metadata_simple_iterator_init()
  83327. * \retval FLAC__bool
  83328. * \c true if the current metadata block is the last in the file,
  83329. * else \c false.
  83330. */
  83331. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_is_last(const FLAC__Metadata_SimpleIterator *iterator);
  83332. /** Get the offset of the metadata block at the current position. This
  83333. * avoids reading the actual block data which can save time for large
  83334. * blocks.
  83335. *
  83336. * \param iterator A pointer to an existing initialized iterator.
  83337. * \assert
  83338. * \code iterator != NULL \endcode
  83339. * \a iterator has been successfully initialized with
  83340. * FLAC__metadata_simple_iterator_init()
  83341. * \retval off_t
  83342. * The offset of the metadata block at the current iterator position.
  83343. * This is the byte offset relative to the beginning of the file of
  83344. * the current metadata block's header.
  83345. */
  83346. FLAC_API off_t FLAC__metadata_simple_iterator_get_block_offset(const FLAC__Metadata_SimpleIterator *iterator);
  83347. /** Get the type of the metadata block at the current position. This
  83348. * avoids reading the actual block data which can save time for large
  83349. * blocks.
  83350. *
  83351. * \param iterator A pointer to an existing initialized iterator.
  83352. * \assert
  83353. * \code iterator != NULL \endcode
  83354. * \a iterator has been successfully initialized with
  83355. * FLAC__metadata_simple_iterator_init()
  83356. * \retval FLAC__MetadataType
  83357. * The type of the metadata block at the current iterator position.
  83358. */
  83359. FLAC_API FLAC__MetadataType FLAC__metadata_simple_iterator_get_block_type(const FLAC__Metadata_SimpleIterator *iterator);
  83360. /** Get the length of the metadata block at the current position. This
  83361. * avoids reading the actual block data which can save time for large
  83362. * blocks.
  83363. *
  83364. * \param iterator A pointer to an existing initialized iterator.
  83365. * \assert
  83366. * \code iterator != NULL \endcode
  83367. * \a iterator has been successfully initialized with
  83368. * FLAC__metadata_simple_iterator_init()
  83369. * \retval unsigned
  83370. * The length of the metadata block at the current iterator position.
  83371. * The is same length as that in the
  83372. * <a href="http://flac.sourceforge.net/format.html#metadata_block_header">metadata block header</a>,
  83373. * i.e. the length of the metadata body that follows the header.
  83374. */
  83375. FLAC_API unsigned FLAC__metadata_simple_iterator_get_block_length(const FLAC__Metadata_SimpleIterator *iterator);
  83376. /** Get the application ID of the \c APPLICATION block at the current
  83377. * position. This avoids reading the actual block data which can save
  83378. * time for large blocks.
  83379. *
  83380. * \param iterator A pointer to an existing initialized iterator.
  83381. * \param id A pointer to a buffer of at least \c 4 bytes where
  83382. * the ID will be stored.
  83383. * \assert
  83384. * \code iterator != NULL \endcode
  83385. * \code id != NULL \endcode
  83386. * \a iterator has been successfully initialized with
  83387. * FLAC__metadata_simple_iterator_init()
  83388. * \retval FLAC__bool
  83389. * \c true if the ID was successfully read, else \c false, in which
  83390. * case you should check FLAC__metadata_simple_iterator_status() to
  83391. * find out why. If the status is
  83392. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ILLEGAL_INPUT, then the
  83393. * current metadata block is not an \c APPLICATION block. Otherwise
  83394. * if the status is
  83395. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR or
  83396. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR, an I/O error
  83397. * occurred and the iterator can no longer be used.
  83398. */
  83399. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_get_application_id(FLAC__Metadata_SimpleIterator *iterator, FLAC__byte *id);
  83400. /** Get the metadata block at the current position. You can modify the
  83401. * block but must use FLAC__metadata_simple_iterator_set_block() to
  83402. * write it back to the FLAC file.
  83403. *
  83404. * You must call FLAC__metadata_object_delete() on the returned object
  83405. * when you are finished with it.
  83406. *
  83407. * \param iterator A pointer to an existing initialized iterator.
  83408. * \assert
  83409. * \code iterator != NULL \endcode
  83410. * \a iterator has been successfully initialized with
  83411. * FLAC__metadata_simple_iterator_init()
  83412. * \retval FLAC__StreamMetadata*
  83413. * The current metadata block, or \c NULL if there was a memory
  83414. * allocation error.
  83415. */
  83416. FLAC_API FLAC__StreamMetadata *FLAC__metadata_simple_iterator_get_block(FLAC__Metadata_SimpleIterator *iterator);
  83417. /** Write a block back to the FLAC file. This function tries to be
  83418. * as efficient as possible; how the block is actually written is
  83419. * shown by the following:
  83420. *
  83421. * Existing block is a STREAMINFO block and the new block is a
  83422. * STREAMINFO block: the new block is written in place. Make sure
  83423. * you know what you're doing when changing the values of a
  83424. * STREAMINFO block.
  83425. *
  83426. * Existing block is a STREAMINFO block and the new block is a
  83427. * not a STREAMINFO block: this is an error since the first block
  83428. * must be a STREAMINFO block. Returns \c false without altering the
  83429. * file.
  83430. *
  83431. * Existing block is not a STREAMINFO block and the new block is a
  83432. * STREAMINFO block: this is an error since there may be only one
  83433. * STREAMINFO block. Returns \c false without altering the file.
  83434. *
  83435. * Existing block and new block are the same length: the existing
  83436. * block will be replaced by the new block, written in place.
  83437. *
  83438. * Existing block is longer than new block: if use_padding is \c true,
  83439. * the existing block will be overwritten in place with the new
  83440. * block followed by a PADDING block, if possible, to make the total
  83441. * size the same as the existing block. Remember that a padding
  83442. * block requires at least four bytes so if the difference in size
  83443. * between the new block and existing block is less than that, the
  83444. * entire file will have to be rewritten, using the new block's
  83445. * exact size. If use_padding is \c false, the entire file will be
  83446. * rewritten, replacing the existing block by the new block.
  83447. *
  83448. * Existing block is shorter than new block: if use_padding is \c true,
  83449. * the function will try and expand the new block into the following
  83450. * PADDING block, if it exists and doing so won't shrink the PADDING
  83451. * block to less than 4 bytes. If there is no following PADDING
  83452. * block, or it will shrink to less than 4 bytes, or use_padding is
  83453. * \c false, the entire file is rewritten, replacing the existing block
  83454. * with the new block. Note that in this case any following PADDING
  83455. * block is preserved as is.
  83456. *
  83457. * After writing the block, the iterator will remain in the same
  83458. * place, i.e. pointing to the new block.
  83459. *
  83460. * \param iterator A pointer to an existing initialized iterator.
  83461. * \param block The block to set.
  83462. * \param use_padding See above.
  83463. * \assert
  83464. * \code iterator != NULL \endcode
  83465. * \a iterator has been successfully initialized with
  83466. * FLAC__metadata_simple_iterator_init()
  83467. * \code block != NULL \endcode
  83468. * \retval FLAC__bool
  83469. * \c true if successful, else \c false.
  83470. */
  83471. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_set_block(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block, FLAC__bool use_padding);
  83472. /** This is similar to FLAC__metadata_simple_iterator_set_block()
  83473. * except that instead of writing over an existing block, it appends
  83474. * a block after the existing block. \a use_padding is again used to
  83475. * tell the function to try an expand into following padding in an
  83476. * attempt to avoid rewriting the entire file.
  83477. *
  83478. * This function will fail and return \c false if given a STREAMINFO
  83479. * block.
  83480. *
  83481. * After writing the block, the iterator will be pointing to the
  83482. * new block.
  83483. *
  83484. * \param iterator A pointer to an existing initialized iterator.
  83485. * \param block The block to set.
  83486. * \param use_padding See above.
  83487. * \assert
  83488. * \code iterator != NULL \endcode
  83489. * \a iterator has been successfully initialized with
  83490. * FLAC__metadata_simple_iterator_init()
  83491. * \code block != NULL \endcode
  83492. * \retval FLAC__bool
  83493. * \c true if successful, else \c false.
  83494. */
  83495. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_insert_block_after(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block, FLAC__bool use_padding);
  83496. /** Deletes the block at the current position. This will cause the
  83497. * entire FLAC file to be rewritten, unless \a use_padding is \c true,
  83498. * in which case the block will be replaced by an equal-sized PADDING
  83499. * block. The iterator will be left pointing to the block before the
  83500. * one just deleted.
  83501. *
  83502. * You may not delete the STREAMINFO block.
  83503. *
  83504. * \param iterator A pointer to an existing initialized iterator.
  83505. * \param use_padding See above.
  83506. * \assert
  83507. * \code iterator != NULL \endcode
  83508. * \a iterator has been successfully initialized with
  83509. * FLAC__metadata_simple_iterator_init()
  83510. * \retval FLAC__bool
  83511. * \c true if successful, else \c false.
  83512. */
  83513. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_delete_block(FLAC__Metadata_SimpleIterator *iterator, FLAC__bool use_padding);
  83514. /* \} */
  83515. /** \defgroup flac_metadata_level2 FLAC/metadata.h: metadata level 2 interface
  83516. * \ingroup flac_metadata
  83517. *
  83518. * \brief
  83519. * The level 2 interface provides read-write access to FLAC file metadata;
  83520. * all metadata is read into memory, operated on in memory, and then written
  83521. * to file, which is more efficient than level 1 when editing multiple blocks.
  83522. *
  83523. * Currently Ogg FLAC is supported for read only, via
  83524. * FLAC__metadata_chain_read_ogg() but a subsequent
  83525. * FLAC__metadata_chain_write() will fail.
  83526. *
  83527. * The general usage of this interface is:
  83528. *
  83529. * - Create a new chain using FLAC__metadata_chain_new(). A chain is a
  83530. * linked list of FLAC metadata blocks.
  83531. * - Read all metadata into the the chain from a FLAC file using
  83532. * FLAC__metadata_chain_read() or FLAC__metadata_chain_read_ogg() and
  83533. * check the status.
  83534. * - Optionally, consolidate the padding using
  83535. * FLAC__metadata_chain_merge_padding() or
  83536. * FLAC__metadata_chain_sort_padding().
  83537. * - Create a new iterator using FLAC__metadata_iterator_new()
  83538. * - Initialize the iterator to point to the first element in the chain
  83539. * using FLAC__metadata_iterator_init()
  83540. * - Traverse the chain using FLAC__metadata_iterator_next and
  83541. * FLAC__metadata_iterator_prev().
  83542. * - Get a block for reading or modification using
  83543. * FLAC__metadata_iterator_get_block(). The pointer to the object
  83544. * inside the chain is returned, so the block is yours to modify.
  83545. * Changes will be reflected in the FLAC file when you write the
  83546. * chain. You can also add and delete blocks (see functions below).
  83547. * - When done, write out the chain using FLAC__metadata_chain_write().
  83548. * Make sure to read the whole comment to the function below.
  83549. * - Delete the chain using FLAC__metadata_chain_delete().
  83550. *
  83551. * \note
  83552. * Even though the FLAC file is not open while the chain is being
  83553. * manipulated, you must not alter the file externally during
  83554. * this time. The chain assumes the FLAC file will not change
  83555. * between the time of FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg()
  83556. * and FLAC__metadata_chain_write().
  83557. *
  83558. * \note
  83559. * Do not modify the is_last, length, or type fields of returned
  83560. * FLAC__StreamMetadata objects. These are managed automatically.
  83561. *
  83562. * \note
  83563. * The metadata objects returned by FLAC__metadata_iterator_get_block()
  83564. * are owned by the chain; do not FLAC__metadata_object_delete() them.
  83565. * In the same way, blocks passed to FLAC__metadata_iterator_set_block()
  83566. * become owned by the chain and they will be deleted when the chain is
  83567. * deleted.
  83568. *
  83569. * \{
  83570. */
  83571. struct FLAC__Metadata_Chain;
  83572. /** The opaque structure definition for the level 2 chain type.
  83573. */
  83574. typedef struct FLAC__Metadata_Chain FLAC__Metadata_Chain;
  83575. struct FLAC__Metadata_Iterator;
  83576. /** The opaque structure definition for the level 2 iterator type.
  83577. */
  83578. typedef struct FLAC__Metadata_Iterator FLAC__Metadata_Iterator;
  83579. typedef enum {
  83580. FLAC__METADATA_CHAIN_STATUS_OK = 0,
  83581. /**< The chain is in the normal OK state */
  83582. FLAC__METADATA_CHAIN_STATUS_ILLEGAL_INPUT,
  83583. /**< The data passed into a function violated the function's usage criteria */
  83584. FLAC__METADATA_CHAIN_STATUS_ERROR_OPENING_FILE,
  83585. /**< The chain could not open the target file */
  83586. FLAC__METADATA_CHAIN_STATUS_NOT_A_FLAC_FILE,
  83587. /**< The chain could not find the FLAC signature at the start of the file */
  83588. FLAC__METADATA_CHAIN_STATUS_NOT_WRITABLE,
  83589. /**< The chain tried to write to a file that was not writable */
  83590. FLAC__METADATA_CHAIN_STATUS_BAD_METADATA,
  83591. /**< The chain encountered input that does not conform to the FLAC metadata specification */
  83592. FLAC__METADATA_CHAIN_STATUS_READ_ERROR,
  83593. /**< The chain encountered an error while reading the FLAC file */
  83594. FLAC__METADATA_CHAIN_STATUS_SEEK_ERROR,
  83595. /**< The chain encountered an error while seeking in the FLAC file */
  83596. FLAC__METADATA_CHAIN_STATUS_WRITE_ERROR,
  83597. /**< The chain encountered an error while writing the FLAC file */
  83598. FLAC__METADATA_CHAIN_STATUS_RENAME_ERROR,
  83599. /**< The chain encountered an error renaming the FLAC file */
  83600. FLAC__METADATA_CHAIN_STATUS_UNLINK_ERROR,
  83601. /**< The chain encountered an error removing the temporary file */
  83602. FLAC__METADATA_CHAIN_STATUS_MEMORY_ALLOCATION_ERROR,
  83603. /**< Memory allocation failed */
  83604. FLAC__METADATA_CHAIN_STATUS_INTERNAL_ERROR,
  83605. /**< The caller violated an assertion or an unexpected error occurred */
  83606. FLAC__METADATA_CHAIN_STATUS_INVALID_CALLBACKS,
  83607. /**< One or more of the required callbacks was NULL */
  83608. FLAC__METADATA_CHAIN_STATUS_READ_WRITE_MISMATCH,
  83609. /**< FLAC__metadata_chain_write() was called on a chain read by
  83610. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  83611. * or
  83612. * FLAC__metadata_chain_write_with_callbacks()/FLAC__metadata_chain_write_with_callbacks_and_tempfile()
  83613. * was called on a chain read by
  83614. * FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  83615. * Matching read/write methods must always be used. */
  83616. FLAC__METADATA_CHAIN_STATUS_WRONG_WRITE_CALL
  83617. /**< FLAC__metadata_chain_write_with_callbacks() was called when the
  83618. * chain write requires a tempfile; use
  83619. * FLAC__metadata_chain_write_with_callbacks_and_tempfile() instead.
  83620. * Or, FLAC__metadata_chain_write_with_callbacks_and_tempfile() was
  83621. * called when the chain write does not require a tempfile; use
  83622. * FLAC__metadata_chain_write_with_callbacks() instead.
  83623. * Always check FLAC__metadata_chain_check_if_tempfile_needed()
  83624. * before writing via callbacks. */
  83625. } FLAC__Metadata_ChainStatus;
  83626. /** Maps a FLAC__Metadata_ChainStatus to a C string.
  83627. *
  83628. * Using a FLAC__Metadata_ChainStatus as the index to this array
  83629. * will give the string equivalent. The contents should not be modified.
  83630. */
  83631. extern FLAC_API const char * const FLAC__Metadata_ChainStatusString[];
  83632. /*********** FLAC__Metadata_Chain ***********/
  83633. /** Create a new chain instance.
  83634. *
  83635. * \retval FLAC__Metadata_Chain*
  83636. * \c NULL if there was an error allocating memory, else the new instance.
  83637. */
  83638. FLAC_API FLAC__Metadata_Chain *FLAC__metadata_chain_new(void);
  83639. /** Free a chain instance. Deletes the object pointed to by \a chain.
  83640. *
  83641. * \param chain A pointer to an existing chain.
  83642. * \assert
  83643. * \code chain != NULL \endcode
  83644. */
  83645. FLAC_API void FLAC__metadata_chain_delete(FLAC__Metadata_Chain *chain);
  83646. /** Get the current status of the chain. Call this after a function
  83647. * returns \c false to get the reason for the error. Also resets the
  83648. * status to FLAC__METADATA_CHAIN_STATUS_OK.
  83649. *
  83650. * \param chain A pointer to an existing chain.
  83651. * \assert
  83652. * \code chain != NULL \endcode
  83653. * \retval FLAC__Metadata_ChainStatus
  83654. * The current status of the chain.
  83655. */
  83656. FLAC_API FLAC__Metadata_ChainStatus FLAC__metadata_chain_status(FLAC__Metadata_Chain *chain);
  83657. /** Read all metadata from a FLAC file into the chain.
  83658. *
  83659. * \param chain A pointer to an existing chain.
  83660. * \param filename The path to the FLAC file to read.
  83661. * \assert
  83662. * \code chain != NULL \endcode
  83663. * \code filename != NULL \endcode
  83664. * \retval FLAC__bool
  83665. * \c true if a valid list of metadata blocks was read from
  83666. * \a filename, else \c false. On failure, check the status with
  83667. * FLAC__metadata_chain_status().
  83668. */
  83669. FLAC_API FLAC__bool FLAC__metadata_chain_read(FLAC__Metadata_Chain *chain, const char *filename);
  83670. /** Read all metadata from an Ogg FLAC file into the chain.
  83671. *
  83672. * \note Ogg FLAC metadata data writing is not supported yet and
  83673. * FLAC__metadata_chain_write() will fail.
  83674. *
  83675. * \param chain A pointer to an existing chain.
  83676. * \param filename The path to the Ogg FLAC file to read.
  83677. * \assert
  83678. * \code chain != NULL \endcode
  83679. * \code filename != NULL \endcode
  83680. * \retval FLAC__bool
  83681. * \c true if a valid list of metadata blocks was read from
  83682. * \a filename, else \c false. On failure, check the status with
  83683. * FLAC__metadata_chain_status().
  83684. */
  83685. FLAC_API FLAC__bool FLAC__metadata_chain_read_ogg(FLAC__Metadata_Chain *chain, const char *filename);
  83686. /** Read all metadata from a FLAC stream into the chain via I/O callbacks.
  83687. *
  83688. * The \a handle need only be open for reading, but must be seekable.
  83689. * The equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  83690. * for Windows).
  83691. *
  83692. * \param chain A pointer to an existing chain.
  83693. * \param handle The I/O handle of the FLAC stream to read. The
  83694. * handle will NOT be closed after the metadata is read;
  83695. * that is the duty of the caller.
  83696. * \param callbacks
  83697. * A set of callbacks to use for I/O. The mandatory
  83698. * callbacks are \a read, \a seek, and \a tell.
  83699. * \assert
  83700. * \code chain != NULL \endcode
  83701. * \retval FLAC__bool
  83702. * \c true if a valid list of metadata blocks was read from
  83703. * \a handle, else \c false. On failure, check the status with
  83704. * FLAC__metadata_chain_status().
  83705. */
  83706. FLAC_API FLAC__bool FLAC__metadata_chain_read_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  83707. /** Read all metadata from an Ogg FLAC stream into the chain via I/O callbacks.
  83708. *
  83709. * The \a handle need only be open for reading, but must be seekable.
  83710. * The equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  83711. * for Windows).
  83712. *
  83713. * \note Ogg FLAC metadata data writing is not supported yet and
  83714. * FLAC__metadata_chain_write() will fail.
  83715. *
  83716. * \param chain A pointer to an existing chain.
  83717. * \param handle The I/O handle of the Ogg FLAC stream to read. The
  83718. * handle will NOT be closed after the metadata is read;
  83719. * that is the duty of the caller.
  83720. * \param callbacks
  83721. * A set of callbacks to use for I/O. The mandatory
  83722. * callbacks are \a read, \a seek, and \a tell.
  83723. * \assert
  83724. * \code chain != NULL \endcode
  83725. * \retval FLAC__bool
  83726. * \c true if a valid list of metadata blocks was read from
  83727. * \a handle, else \c false. On failure, check the status with
  83728. * FLAC__metadata_chain_status().
  83729. */
  83730. FLAC_API FLAC__bool FLAC__metadata_chain_read_ogg_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  83731. /** Checks if writing the given chain would require the use of a
  83732. * temporary file, or if it could be written in place.
  83733. *
  83734. * Under certain conditions, padding can be utilized so that writing
  83735. * edited metadata back to the FLAC file does not require rewriting the
  83736. * entire file. If rewriting is required, then a temporary workfile is
  83737. * required. When writing metadata using callbacks, you must check
  83738. * this function to know whether to call
  83739. * FLAC__metadata_chain_write_with_callbacks() or
  83740. * FLAC__metadata_chain_write_with_callbacks_and_tempfile(). When
  83741. * writing with FLAC__metadata_chain_write(), the temporary file is
  83742. * handled internally.
  83743. *
  83744. * \param chain A pointer to an existing chain.
  83745. * \param use_padding
  83746. * Whether or not padding will be allowed to be used
  83747. * during the write. The value of \a use_padding given
  83748. * here must match the value later passed to
  83749. * FLAC__metadata_chain_write_with_callbacks() or
  83750. * FLAC__metadata_chain_write_with_callbacks_with_tempfile().
  83751. * \assert
  83752. * \code chain != NULL \endcode
  83753. * \retval FLAC__bool
  83754. * \c true if writing the current chain would require a tempfile, or
  83755. * \c false if metadata can be written in place.
  83756. */
  83757. FLAC_API FLAC__bool FLAC__metadata_chain_check_if_tempfile_needed(FLAC__Metadata_Chain *chain, FLAC__bool use_padding);
  83758. /** Write all metadata out to the FLAC file. This function tries to be as
  83759. * efficient as possible; how the metadata is actually written is shown by
  83760. * the following:
  83761. *
  83762. * If the current chain is the same size as the existing metadata, the new
  83763. * data is written in place.
  83764. *
  83765. * If the current chain is longer than the existing metadata, and
  83766. * \a use_padding is \c true, and the last block is a PADDING block of
  83767. * sufficient length, the function will truncate the final padding block
  83768. * so that the overall size of the metadata is the same as the existing
  83769. * metadata, and then just rewrite the metadata. Otherwise, if not all of
  83770. * the above conditions are met, the entire FLAC file must be rewritten.
  83771. * If you want to use padding this way it is a good idea to call
  83772. * FLAC__metadata_chain_sort_padding() first so that you have the maximum
  83773. * amount of padding to work with, unless you need to preserve ordering
  83774. * of the PADDING blocks for some reason.
  83775. *
  83776. * If the current chain is shorter than the existing metadata, and
  83777. * \a use_padding is \c true, and the final block is a PADDING block, the padding
  83778. * is extended to make the overall size the same as the existing data. If
  83779. * \a use_padding is \c true and the last block is not a PADDING block, a new
  83780. * PADDING block is added to the end of the new data to make it the same
  83781. * size as the existing data (if possible, see the note to
  83782. * FLAC__metadata_simple_iterator_set_block() about the four byte limit)
  83783. * and the new data is written in place. If none of the above apply or
  83784. * \a use_padding is \c false, the entire FLAC file is rewritten.
  83785. *
  83786. * If \a preserve_file_stats is \c true, the owner and modification time will
  83787. * be preserved even if the FLAC file is written.
  83788. *
  83789. * For this write function to be used, the chain must have been read with
  83790. * FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg(), not
  83791. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks().
  83792. *
  83793. * \param chain A pointer to an existing chain.
  83794. * \param use_padding See above.
  83795. * \param preserve_file_stats See above.
  83796. * \assert
  83797. * \code chain != NULL \endcode
  83798. * \retval FLAC__bool
  83799. * \c true if the write succeeded, else \c false. On failure,
  83800. * check the status with FLAC__metadata_chain_status().
  83801. */
  83802. FLAC_API FLAC__bool FLAC__metadata_chain_write(FLAC__Metadata_Chain *chain, FLAC__bool use_padding, FLAC__bool preserve_file_stats);
  83803. /** Write all metadata out to a FLAC stream via callbacks.
  83804. *
  83805. * (See FLAC__metadata_chain_write() for the details on how padding is
  83806. * used to write metadata in place if possible.)
  83807. *
  83808. * The \a handle must be open for updating and be seekable. The
  83809. * equivalent minimum stdio fopen() file mode is \c "r+" (or \c "r+b"
  83810. * for Windows).
  83811. *
  83812. * For this write function to be used, the chain must have been read with
  83813. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  83814. * not FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  83815. * Also, FLAC__metadata_chain_check_if_tempfile_needed() must have returned
  83816. * \c false.
  83817. *
  83818. * \param chain A pointer to an existing chain.
  83819. * \param use_padding See FLAC__metadata_chain_write()
  83820. * \param handle The I/O handle of the FLAC stream to write. The
  83821. * handle will NOT be closed after the metadata is
  83822. * written; that is the duty of the caller.
  83823. * \param callbacks A set of callbacks to use for I/O. The mandatory
  83824. * callbacks are \a write and \a seek.
  83825. * \assert
  83826. * \code chain != NULL \endcode
  83827. * \retval FLAC__bool
  83828. * \c true if the write succeeded, else \c false. On failure,
  83829. * check the status with FLAC__metadata_chain_status().
  83830. */
  83831. FLAC_API FLAC__bool FLAC__metadata_chain_write_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__bool use_padding, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  83832. /** Write all metadata out to a FLAC stream via callbacks.
  83833. *
  83834. * (See FLAC__metadata_chain_write() for the details on how padding is
  83835. * used to write metadata in place if possible.)
  83836. *
  83837. * This version of the write-with-callbacks function must be used when
  83838. * FLAC__metadata_chain_check_if_tempfile_needed() returns true. In
  83839. * this function, you must supply an I/O handle corresponding to the
  83840. * FLAC file to edit, and a temporary handle to which the new FLAC
  83841. * file will be written. It is the caller's job to move this temporary
  83842. * FLAC file on top of the original FLAC file to complete the metadata
  83843. * edit.
  83844. *
  83845. * The \a handle must be open for reading and be seekable. The
  83846. * equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  83847. * for Windows).
  83848. *
  83849. * The \a temp_handle must be open for writing. The
  83850. * equivalent minimum stdio fopen() file mode is \c "w" (or \c "wb"
  83851. * for Windows). It should be an empty stream, or at least positioned
  83852. * at the start-of-file (in which case it is the caller's duty to
  83853. * truncate it on return).
  83854. *
  83855. * For this write function to be used, the chain must have been read with
  83856. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  83857. * not FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  83858. * Also, FLAC__metadata_chain_check_if_tempfile_needed() must have returned
  83859. * \c true.
  83860. *
  83861. * \param chain A pointer to an existing chain.
  83862. * \param use_padding See FLAC__metadata_chain_write()
  83863. * \param handle The I/O handle of the original FLAC stream to read.
  83864. * The handle will NOT be closed after the metadata is
  83865. * written; that is the duty of the caller.
  83866. * \param callbacks A set of callbacks to use for I/O on \a handle.
  83867. * The mandatory callbacks are \a read, \a seek, and
  83868. * \a eof.
  83869. * \param temp_handle The I/O handle of the FLAC stream to write. The
  83870. * handle will NOT be closed after the metadata is
  83871. * written; that is the duty of the caller.
  83872. * \param temp_callbacks
  83873. * A set of callbacks to use for I/O on temp_handle.
  83874. * The only mandatory callback is \a write.
  83875. * \assert
  83876. * \code chain != NULL \endcode
  83877. * \retval FLAC__bool
  83878. * \c true if the write succeeded, else \c false. On failure,
  83879. * check the status with FLAC__metadata_chain_status().
  83880. */
  83881. FLAC_API FLAC__bool FLAC__metadata_chain_write_with_callbacks_and_tempfile(FLAC__Metadata_Chain *chain, FLAC__bool use_padding, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks, FLAC__IOHandle temp_handle, FLAC__IOCallbacks temp_callbacks);
  83882. /** Merge adjacent PADDING blocks into a single block.
  83883. *
  83884. * \note This function does not write to the FLAC file, it only
  83885. * modifies the chain.
  83886. *
  83887. * \warning Any iterator on the current chain will become invalid after this
  83888. * call. You should delete the iterator and get a new one.
  83889. *
  83890. * \param chain A pointer to an existing chain.
  83891. * \assert
  83892. * \code chain != NULL \endcode
  83893. */
  83894. FLAC_API void FLAC__metadata_chain_merge_padding(FLAC__Metadata_Chain *chain);
  83895. /** This function will move all PADDING blocks to the end on the metadata,
  83896. * then merge them into a single block.
  83897. *
  83898. * \note This function does not write to the FLAC file, it only
  83899. * modifies the chain.
  83900. *
  83901. * \warning Any iterator on the current chain will become invalid after this
  83902. * call. You should delete the iterator and get a new one.
  83903. *
  83904. * \param chain A pointer to an existing chain.
  83905. * \assert
  83906. * \code chain != NULL \endcode
  83907. */
  83908. FLAC_API void FLAC__metadata_chain_sort_padding(FLAC__Metadata_Chain *chain);
  83909. /*********** FLAC__Metadata_Iterator ***********/
  83910. /** Create a new iterator instance.
  83911. *
  83912. * \retval FLAC__Metadata_Iterator*
  83913. * \c NULL if there was an error allocating memory, else the new instance.
  83914. */
  83915. FLAC_API FLAC__Metadata_Iterator *FLAC__metadata_iterator_new(void);
  83916. /** Free an iterator instance. Deletes the object pointed to by \a iterator.
  83917. *
  83918. * \param iterator A pointer to an existing iterator.
  83919. * \assert
  83920. * \code iterator != NULL \endcode
  83921. */
  83922. FLAC_API void FLAC__metadata_iterator_delete(FLAC__Metadata_Iterator *iterator);
  83923. /** Initialize the iterator to point to the first metadata block in the
  83924. * given chain.
  83925. *
  83926. * \param iterator A pointer to an existing iterator.
  83927. * \param chain A pointer to an existing and initialized (read) chain.
  83928. * \assert
  83929. * \code iterator != NULL \endcode
  83930. * \code chain != NULL \endcode
  83931. */
  83932. FLAC_API void FLAC__metadata_iterator_init(FLAC__Metadata_Iterator *iterator, FLAC__Metadata_Chain *chain);
  83933. /** Moves the iterator forward one metadata block, returning \c false if
  83934. * already at the end.
  83935. *
  83936. * \param iterator A pointer to an existing initialized iterator.
  83937. * \assert
  83938. * \code iterator != NULL \endcode
  83939. * \a iterator has been successfully initialized with
  83940. * FLAC__metadata_iterator_init()
  83941. * \retval FLAC__bool
  83942. * \c false if already at the last metadata block of the chain, else
  83943. * \c true.
  83944. */
  83945. FLAC_API FLAC__bool FLAC__metadata_iterator_next(FLAC__Metadata_Iterator *iterator);
  83946. /** Moves the iterator backward one metadata block, returning \c false if
  83947. * already at the beginning.
  83948. *
  83949. * \param iterator A pointer to an existing initialized iterator.
  83950. * \assert
  83951. * \code iterator != NULL \endcode
  83952. * \a iterator has been successfully initialized with
  83953. * FLAC__metadata_iterator_init()
  83954. * \retval FLAC__bool
  83955. * \c false if already at the first metadata block of the chain, else
  83956. * \c true.
  83957. */
  83958. FLAC_API FLAC__bool FLAC__metadata_iterator_prev(FLAC__Metadata_Iterator *iterator);
  83959. /** Get the type of the metadata block at the current position.
  83960. *
  83961. * \param iterator A pointer to an existing initialized iterator.
  83962. * \assert
  83963. * \code iterator != NULL \endcode
  83964. * \a iterator has been successfully initialized with
  83965. * FLAC__metadata_iterator_init()
  83966. * \retval FLAC__MetadataType
  83967. * The type of the metadata block at the current iterator position.
  83968. */
  83969. FLAC_API FLAC__MetadataType FLAC__metadata_iterator_get_block_type(const FLAC__Metadata_Iterator *iterator);
  83970. /** Get the metadata block at the current position. You can modify
  83971. * the block in place but must write the chain before the changes
  83972. * are reflected to the FLAC file. You do not need to call
  83973. * FLAC__metadata_iterator_set_block() to reflect the changes;
  83974. * the pointer returned by FLAC__metadata_iterator_get_block()
  83975. * points directly into the chain.
  83976. *
  83977. * \warning
  83978. * Do not call FLAC__metadata_object_delete() on the returned object;
  83979. * to delete a block use FLAC__metadata_iterator_delete_block().
  83980. *
  83981. * \param iterator A pointer to an existing initialized iterator.
  83982. * \assert
  83983. * \code iterator != NULL \endcode
  83984. * \a iterator has been successfully initialized with
  83985. * FLAC__metadata_iterator_init()
  83986. * \retval FLAC__StreamMetadata*
  83987. * The current metadata block.
  83988. */
  83989. FLAC_API FLAC__StreamMetadata *FLAC__metadata_iterator_get_block(FLAC__Metadata_Iterator *iterator);
  83990. /** Set the metadata block at the current position, replacing the existing
  83991. * block. The new block passed in becomes owned by the chain and it will be
  83992. * deleted when the chain is deleted.
  83993. *
  83994. * \param iterator A pointer to an existing initialized iterator.
  83995. * \param block A pointer to a metadata block.
  83996. * \assert
  83997. * \code iterator != NULL \endcode
  83998. * \a iterator has been successfully initialized with
  83999. * FLAC__metadata_iterator_init()
  84000. * \code block != NULL \endcode
  84001. * \retval FLAC__bool
  84002. * \c false if the conditions in the above description are not met, or
  84003. * a memory allocation error occurs, otherwise \c true.
  84004. */
  84005. FLAC_API FLAC__bool FLAC__metadata_iterator_set_block(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  84006. /** Removes the current block from the chain. If \a replace_with_padding is
  84007. * \c true, the block will instead be replaced with a padding block of equal
  84008. * size. You can not delete the STREAMINFO block. The iterator will be
  84009. * left pointing to the block before the one just "deleted", even if
  84010. * \a replace_with_padding is \c true.
  84011. *
  84012. * \param iterator A pointer to an existing initialized iterator.
  84013. * \param replace_with_padding See above.
  84014. * \assert
  84015. * \code iterator != NULL \endcode
  84016. * \a iterator has been successfully initialized with
  84017. * FLAC__metadata_iterator_init()
  84018. * \retval FLAC__bool
  84019. * \c false if the conditions in the above description are not met,
  84020. * otherwise \c true.
  84021. */
  84022. FLAC_API FLAC__bool FLAC__metadata_iterator_delete_block(FLAC__Metadata_Iterator *iterator, FLAC__bool replace_with_padding);
  84023. /** Insert a new block before the current block. You cannot insert a block
  84024. * before the first STREAMINFO block. You cannot insert a STREAMINFO block
  84025. * as there can be only one, the one that already exists at the head when you
  84026. * read in a chain. The chain takes ownership of the new block and it will be
  84027. * deleted when the chain is deleted. The iterator will be left pointing to
  84028. * the new block.
  84029. *
  84030. * \param iterator A pointer to an existing initialized iterator.
  84031. * \param block A pointer to a metadata block to insert.
  84032. * \assert
  84033. * \code iterator != NULL \endcode
  84034. * \a iterator has been successfully initialized with
  84035. * FLAC__metadata_iterator_init()
  84036. * \retval FLAC__bool
  84037. * \c false if the conditions in the above description are not met, or
  84038. * a memory allocation error occurs, otherwise \c true.
  84039. */
  84040. FLAC_API FLAC__bool FLAC__metadata_iterator_insert_block_before(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  84041. /** Insert a new block after the current block. You cannot insert a STREAMINFO
  84042. * block as there can be only one, the one that already exists at the head when
  84043. * you read in a chain. The chain takes ownership of the new block and it will
  84044. * be deleted when the chain is deleted. The iterator will be left pointing to
  84045. * the new block.
  84046. *
  84047. * \param iterator A pointer to an existing initialized iterator.
  84048. * \param block A pointer to a metadata block to insert.
  84049. * \assert
  84050. * \code iterator != NULL \endcode
  84051. * \a iterator has been successfully initialized with
  84052. * FLAC__metadata_iterator_init()
  84053. * \retval FLAC__bool
  84054. * \c false if the conditions in the above description are not met, or
  84055. * a memory allocation error occurs, otherwise \c true.
  84056. */
  84057. FLAC_API FLAC__bool FLAC__metadata_iterator_insert_block_after(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  84058. /* \} */
  84059. /** \defgroup flac_metadata_object FLAC/metadata.h: metadata object methods
  84060. * \ingroup flac_metadata
  84061. *
  84062. * \brief
  84063. * This module contains methods for manipulating FLAC metadata objects.
  84064. *
  84065. * Since many are variable length we have to be careful about the memory
  84066. * management. We decree that all pointers to data in the object are
  84067. * owned by the object and memory-managed by the object.
  84068. *
  84069. * Use the FLAC__metadata_object_new() and FLAC__metadata_object_delete()
  84070. * functions to create all instances. When using the
  84071. * FLAC__metadata_object_set_*() functions to set pointers to data, set
  84072. * \a copy to \c true to have the function make it's own copy of the data, or
  84073. * to \c false to give the object ownership of your data. In the latter case
  84074. * your pointer must be freeable by free() and will be free()d when the object
  84075. * is FLAC__metadata_object_delete()d. It is legal to pass a null pointer as
  84076. * the data pointer to a FLAC__metadata_object_set_*() function as long as
  84077. * the length argument is 0 and the \a copy argument is \c false.
  84078. *
  84079. * The FLAC__metadata_object_new() and FLAC__metadata_object_clone() function
  84080. * will return \c NULL in the case of a memory allocation error, otherwise a new
  84081. * object. The FLAC__metadata_object_set_*() functions return \c false in the
  84082. * case of a memory allocation error.
  84083. *
  84084. * We don't have the convenience of C++ here, so note that the library relies
  84085. * on you to keep the types straight. In other words, if you pass, for
  84086. * example, a FLAC__StreamMetadata* that represents a STREAMINFO block to
  84087. * FLAC__metadata_object_application_set_data(), you will get an assertion
  84088. * failure.
  84089. *
  84090. * For convenience the FLAC__metadata_object_vorbiscomment_*() functions
  84091. * maintain a trailing NUL on each Vorbis comment entry. This is not counted
  84092. * toward the length or stored in the stream, but it can make working with plain
  84093. * comments (those that don't contain embedded-NULs in the value) easier.
  84094. * Entries passed into these functions have trailing NULs added if missing, and
  84095. * returned entries are guaranteed to have a trailing NUL.
  84096. *
  84097. * The FLAC__metadata_object_vorbiscomment_*() functions that take a Vorbis
  84098. * comment entry/name/value will first validate that it complies with the Vorbis
  84099. * comment specification and return false if it does not.
  84100. *
  84101. * There is no need to recalculate the length field on metadata blocks you
  84102. * have modified. They will be calculated automatically before they are
  84103. * written back to a file.
  84104. *
  84105. * \{
  84106. */
  84107. /** Create a new metadata object instance of the given type.
  84108. *
  84109. * The object will be "empty"; i.e. values and data pointers will be \c 0,
  84110. * with the exception of FLAC__METADATA_TYPE_VORBIS_COMMENT, which will have
  84111. * the vendor string set (but zero comments).
  84112. *
  84113. * Do not pass in a value greater than or equal to
  84114. * \a FLAC__METADATA_TYPE_UNDEFINED unless you really know what you're
  84115. * doing.
  84116. *
  84117. * \param type Type of object to create
  84118. * \retval FLAC__StreamMetadata*
  84119. * \c NULL if there was an error allocating memory or the type code is
  84120. * greater than FLAC__MAX_METADATA_TYPE_CODE, else the new instance.
  84121. */
  84122. FLAC_API FLAC__StreamMetadata *FLAC__metadata_object_new(FLAC__MetadataType type);
  84123. /** Create a copy of an existing metadata object.
  84124. *
  84125. * The copy is a "deep" copy, i.e. dynamically allocated data within the
  84126. * object is also copied. The caller takes ownership of the new block and
  84127. * is responsible for freeing it with FLAC__metadata_object_delete().
  84128. *
  84129. * \param object Pointer to object to copy.
  84130. * \assert
  84131. * \code object != NULL \endcode
  84132. * \retval FLAC__StreamMetadata*
  84133. * \c NULL if there was an error allocating memory, else the new instance.
  84134. */
  84135. FLAC_API FLAC__StreamMetadata *FLAC__metadata_object_clone(const FLAC__StreamMetadata *object);
  84136. /** Free a metadata object. Deletes the object pointed to by \a object.
  84137. *
  84138. * The delete is a "deep" delete, i.e. dynamically allocated data within the
  84139. * object is also deleted.
  84140. *
  84141. * \param object A pointer to an existing object.
  84142. * \assert
  84143. * \code object != NULL \endcode
  84144. */
  84145. FLAC_API void FLAC__metadata_object_delete(FLAC__StreamMetadata *object);
  84146. /** Compares two metadata objects.
  84147. *
  84148. * The compare is "deep", i.e. dynamically allocated data within the
  84149. * object is also compared.
  84150. *
  84151. * \param block1 A pointer to an existing object.
  84152. * \param block2 A pointer to an existing object.
  84153. * \assert
  84154. * \code block1 != NULL \endcode
  84155. * \code block2 != NULL \endcode
  84156. * \retval FLAC__bool
  84157. * \c true if objects are identical, else \c false.
  84158. */
  84159. FLAC_API FLAC__bool FLAC__metadata_object_is_equal(const FLAC__StreamMetadata *block1, const FLAC__StreamMetadata *block2);
  84160. /** Sets the application data of an APPLICATION block.
  84161. *
  84162. * If \a copy is \c true, a copy of the data is stored; otherwise, the object
  84163. * takes ownership of the pointer. The existing data will be freed if this
  84164. * function is successful, otherwise the original data will remain if \a copy
  84165. * is \c true and malloc() fails.
  84166. *
  84167. * \note It is safe to pass a const pointer to \a data if \a copy is \c true.
  84168. *
  84169. * \param object A pointer to an existing APPLICATION object.
  84170. * \param data A pointer to the data to set.
  84171. * \param length The length of \a data in bytes.
  84172. * \param copy See above.
  84173. * \assert
  84174. * \code object != NULL \endcode
  84175. * \code object->type == FLAC__METADATA_TYPE_APPLICATION \endcode
  84176. * \code (data != NULL && length > 0) ||
  84177. * (data == NULL && length == 0 && copy == false) \endcode
  84178. * \retval FLAC__bool
  84179. * \c false if \a copy is \c true and malloc() fails, else \c true.
  84180. */
  84181. FLAC_API FLAC__bool FLAC__metadata_object_application_set_data(FLAC__StreamMetadata *object, FLAC__byte *data, unsigned length, FLAC__bool copy);
  84182. /** Resize the seekpoint array.
  84183. *
  84184. * If the size shrinks, elements will truncated; if it grows, new placeholder
  84185. * points will be added to the end.
  84186. *
  84187. * \param object A pointer to an existing SEEKTABLE object.
  84188. * \param new_num_points The desired length of the array; may be \c 0.
  84189. * \assert
  84190. * \code object != NULL \endcode
  84191. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  84192. * \code (object->data.seek_table.points == NULL && object->data.seek_table.num_points == 0) ||
  84193. * (object->data.seek_table.points != NULL && object->data.seek_table.num_points > 0) \endcode
  84194. * \retval FLAC__bool
  84195. * \c false if memory allocation error, else \c true.
  84196. */
  84197. FLAC_API FLAC__bool FLAC__metadata_object_seektable_resize_points(FLAC__StreamMetadata *object, unsigned new_num_points);
  84198. /** Set a seekpoint in a seektable.
  84199. *
  84200. * \param object A pointer to an existing SEEKTABLE object.
  84201. * \param point_num Index into seekpoint array to set.
  84202. * \param point The point to set.
  84203. * \assert
  84204. * \code object != NULL \endcode
  84205. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  84206. * \code object->data.seek_table.num_points > point_num \endcode
  84207. */
  84208. FLAC_API void FLAC__metadata_object_seektable_set_point(FLAC__StreamMetadata *object, unsigned point_num, FLAC__StreamMetadata_SeekPoint point);
  84209. /** Insert a seekpoint into a seektable.
  84210. *
  84211. * \param object A pointer to an existing SEEKTABLE object.
  84212. * \param point_num Index into seekpoint array to set.
  84213. * \param point The point to set.
  84214. * \assert
  84215. * \code object != NULL \endcode
  84216. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  84217. * \code object->data.seek_table.num_points >= point_num \endcode
  84218. * \retval FLAC__bool
  84219. * \c false if memory allocation error, else \c true.
  84220. */
  84221. FLAC_API FLAC__bool FLAC__metadata_object_seektable_insert_point(FLAC__StreamMetadata *object, unsigned point_num, FLAC__StreamMetadata_SeekPoint point);
  84222. /** Delete a seekpoint from a seektable.
  84223. *
  84224. * \param object A pointer to an existing SEEKTABLE object.
  84225. * \param point_num Index into seekpoint array to set.
  84226. * \assert
  84227. * \code object != NULL \endcode
  84228. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  84229. * \code object->data.seek_table.num_points > point_num \endcode
  84230. * \retval FLAC__bool
  84231. * \c false if memory allocation error, else \c true.
  84232. */
  84233. FLAC_API FLAC__bool FLAC__metadata_object_seektable_delete_point(FLAC__StreamMetadata *object, unsigned point_num);
  84234. /** Check a seektable to see if it conforms to the FLAC specification.
  84235. * See the format specification for limits on the contents of the
  84236. * seektable.
  84237. *
  84238. * \param object A pointer to an existing SEEKTABLE object.
  84239. * \assert
  84240. * \code object != NULL \endcode
  84241. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  84242. * \retval FLAC__bool
  84243. * \c false if seek table is illegal, else \c true.
  84244. */
  84245. FLAC_API FLAC__bool FLAC__metadata_object_seektable_is_legal(const FLAC__StreamMetadata *object);
  84246. /** Append a number of placeholder points to the end of a seek table.
  84247. *
  84248. * \note
  84249. * As with the other ..._seektable_template_... functions, you should
  84250. * call FLAC__metadata_object_seektable_template_sort() when finished
  84251. * to make the seek table legal.
  84252. *
  84253. * \param object A pointer to an existing SEEKTABLE object.
  84254. * \param num The number of placeholder points to append.
  84255. * \assert
  84256. * \code object != NULL \endcode
  84257. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  84258. * \retval FLAC__bool
  84259. * \c false if memory allocation fails, else \c true.
  84260. */
  84261. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_placeholders(FLAC__StreamMetadata *object, unsigned num);
  84262. /** Append a specific seek point template to the end of a seek table.
  84263. *
  84264. * \note
  84265. * As with the other ..._seektable_template_... functions, you should
  84266. * call FLAC__metadata_object_seektable_template_sort() when finished
  84267. * to make the seek table legal.
  84268. *
  84269. * \param object A pointer to an existing SEEKTABLE object.
  84270. * \param sample_number The sample number of the seek point template.
  84271. * \assert
  84272. * \code object != NULL \endcode
  84273. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  84274. * \retval FLAC__bool
  84275. * \c false if memory allocation fails, else \c true.
  84276. */
  84277. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_point(FLAC__StreamMetadata *object, FLAC__uint64 sample_number);
  84278. /** Append specific seek point templates to the end of a seek table.
  84279. *
  84280. * \note
  84281. * As with the other ..._seektable_template_... functions, you should
  84282. * call FLAC__metadata_object_seektable_template_sort() when finished
  84283. * to make the seek table legal.
  84284. *
  84285. * \param object A pointer to an existing SEEKTABLE object.
  84286. * \param sample_numbers An array of sample numbers for the seek points.
  84287. * \param num The number of seek point templates to append.
  84288. * \assert
  84289. * \code object != NULL \endcode
  84290. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  84291. * \retval FLAC__bool
  84292. * \c false if memory allocation fails, else \c true.
  84293. */
  84294. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_points(FLAC__StreamMetadata *object, FLAC__uint64 sample_numbers[], unsigned num);
  84295. /** Append a set of evenly-spaced seek point templates to the end of a
  84296. * seek table.
  84297. *
  84298. * \note
  84299. * As with the other ..._seektable_template_... functions, you should
  84300. * call FLAC__metadata_object_seektable_template_sort() when finished
  84301. * to make the seek table legal.
  84302. *
  84303. * \param object A pointer to an existing SEEKTABLE object.
  84304. * \param num The number of placeholder points to append.
  84305. * \param total_samples The total number of samples to be encoded;
  84306. * the seekpoints will be spaced approximately
  84307. * \a total_samples / \a num samples apart.
  84308. * \assert
  84309. * \code object != NULL \endcode
  84310. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  84311. * \code total_samples > 0 \endcode
  84312. * \retval FLAC__bool
  84313. * \c false if memory allocation fails, else \c true.
  84314. */
  84315. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_spaced_points(FLAC__StreamMetadata *object, unsigned num, FLAC__uint64 total_samples);
  84316. /** Append a set of evenly-spaced seek point templates to the end of a
  84317. * seek table.
  84318. *
  84319. * \note
  84320. * As with the other ..._seektable_template_... functions, you should
  84321. * call FLAC__metadata_object_seektable_template_sort() when finished
  84322. * to make the seek table legal.
  84323. *
  84324. * \param object A pointer to an existing SEEKTABLE object.
  84325. * \param samples The number of samples apart to space the placeholder
  84326. * points. The first point will be at sample \c 0, the
  84327. * second at sample \a samples, then 2*\a samples, and
  84328. * so on. As long as \a samples and \a total_samples
  84329. * are greater than \c 0, there will always be at least
  84330. * one seekpoint at sample \c 0.
  84331. * \param total_samples The total number of samples to be encoded;
  84332. * the seekpoints will be spaced
  84333. * \a samples samples apart.
  84334. * \assert
  84335. * \code object != NULL \endcode
  84336. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  84337. * \code samples > 0 \endcode
  84338. * \code total_samples > 0 \endcode
  84339. * \retval FLAC__bool
  84340. * \c false if memory allocation fails, else \c true.
  84341. */
  84342. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_spaced_points_by_samples(FLAC__StreamMetadata *object, unsigned samples, FLAC__uint64 total_samples);
  84343. /** Sort a seek table's seek points according to the format specification,
  84344. * removing duplicates.
  84345. *
  84346. * \param object A pointer to a seek table to be sorted.
  84347. * \param compact If \c false, behaves like FLAC__format_seektable_sort().
  84348. * If \c true, duplicates are deleted and the seek table is
  84349. * shrunk appropriately; the number of placeholder points
  84350. * present in the seek table will be the same after the call
  84351. * as before.
  84352. * \assert
  84353. * \code object != NULL \endcode
  84354. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  84355. * \retval FLAC__bool
  84356. * \c false if realloc() fails, else \c true.
  84357. */
  84358. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_sort(FLAC__StreamMetadata *object, FLAC__bool compact);
  84359. /** Sets the vendor string in a VORBIS_COMMENT block.
  84360. *
  84361. * For convenience, a trailing NUL is added to the entry if it doesn't have
  84362. * one already.
  84363. *
  84364. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  84365. * takes ownership of the \c entry.entry pointer.
  84366. *
  84367. * \note If this function returns \c false, the caller still owns the
  84368. * pointer.
  84369. *
  84370. * \param object A pointer to an existing VORBIS_COMMENT object.
  84371. * \param entry The entry to set the vendor string to.
  84372. * \param copy See above.
  84373. * \assert
  84374. * \code object != NULL \endcode
  84375. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  84376. * \code (entry.entry != NULL && entry.length > 0) ||
  84377. * (entry.entry == NULL && entry.length == 0) \endcode
  84378. * \retval FLAC__bool
  84379. * \c false if memory allocation fails or \a entry does not comply with the
  84380. * Vorbis comment specification, else \c true.
  84381. */
  84382. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_set_vendor_string(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  84383. /** Resize the comment array.
  84384. *
  84385. * If the size shrinks, elements will truncated; if it grows, new empty
  84386. * fields will be added to the end.
  84387. *
  84388. * \param object A pointer to an existing VORBIS_COMMENT object.
  84389. * \param new_num_comments The desired length of the array; may be \c 0.
  84390. * \assert
  84391. * \code object != NULL \endcode
  84392. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  84393. * \code (object->data.vorbis_comment.comments == NULL && object->data.vorbis_comment.num_comments == 0) ||
  84394. * (object->data.vorbis_comment.comments != NULL && object->data.vorbis_comment.num_comments > 0) \endcode
  84395. * \retval FLAC__bool
  84396. * \c false if memory allocation fails, else \c true.
  84397. */
  84398. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_resize_comments(FLAC__StreamMetadata *object, unsigned new_num_comments);
  84399. /** Sets a comment in a VORBIS_COMMENT block.
  84400. *
  84401. * For convenience, a trailing NUL is added to the entry if it doesn't have
  84402. * one already.
  84403. *
  84404. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  84405. * takes ownership of the \c entry.entry pointer.
  84406. *
  84407. * \note If this function returns \c false, the caller still owns the
  84408. * pointer.
  84409. *
  84410. * \param object A pointer to an existing VORBIS_COMMENT object.
  84411. * \param comment_num Index into comment array to set.
  84412. * \param entry The entry to set the comment to.
  84413. * \param copy See above.
  84414. * \assert
  84415. * \code object != NULL \endcode
  84416. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  84417. * \code comment_num < object->data.vorbis_comment.num_comments \endcode
  84418. * \code (entry.entry != NULL && entry.length > 0) ||
  84419. * (entry.entry == NULL && entry.length == 0) \endcode
  84420. * \retval FLAC__bool
  84421. * \c false if memory allocation fails or \a entry does not comply with the
  84422. * Vorbis comment specification, else \c true.
  84423. */
  84424. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_set_comment(FLAC__StreamMetadata *object, unsigned comment_num, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  84425. /** Insert a comment in a VORBIS_COMMENT block at the given index.
  84426. *
  84427. * For convenience, a trailing NUL is added to the entry if it doesn't have
  84428. * one already.
  84429. *
  84430. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  84431. * takes ownership of the \c entry.entry pointer.
  84432. *
  84433. * \note If this function returns \c false, the caller still owns the
  84434. * pointer.
  84435. *
  84436. * \param object A pointer to an existing VORBIS_COMMENT object.
  84437. * \param comment_num The index at which to insert the comment. The comments
  84438. * at and after \a comment_num move right one position.
  84439. * To append a comment to the end, set \a comment_num to
  84440. * \c object->data.vorbis_comment.num_comments .
  84441. * \param entry The comment to insert.
  84442. * \param copy See above.
  84443. * \assert
  84444. * \code object != NULL \endcode
  84445. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  84446. * \code object->data.vorbis_comment.num_comments >= comment_num \endcode
  84447. * \code (entry.entry != NULL && entry.length > 0) ||
  84448. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  84449. * \retval FLAC__bool
  84450. * \c false if memory allocation fails or \a entry does not comply with the
  84451. * Vorbis comment specification, else \c true.
  84452. */
  84453. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_insert_comment(FLAC__StreamMetadata *object, unsigned comment_num, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  84454. /** Appends a comment to a VORBIS_COMMENT block.
  84455. *
  84456. * For convenience, a trailing NUL is added to the entry if it doesn't have
  84457. * one already.
  84458. *
  84459. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  84460. * takes ownership of the \c entry.entry pointer.
  84461. *
  84462. * \note If this function returns \c false, the caller still owns the
  84463. * pointer.
  84464. *
  84465. * \param object A pointer to an existing VORBIS_COMMENT object.
  84466. * \param entry The comment to insert.
  84467. * \param copy See above.
  84468. * \assert
  84469. * \code object != NULL \endcode
  84470. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  84471. * \code (entry.entry != NULL && entry.length > 0) ||
  84472. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  84473. * \retval FLAC__bool
  84474. * \c false if memory allocation fails or \a entry does not comply with the
  84475. * Vorbis comment specification, else \c true.
  84476. */
  84477. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_append_comment(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  84478. /** Replaces comments in a VORBIS_COMMENT block with a new one.
  84479. *
  84480. * For convenience, a trailing NUL is added to the entry if it doesn't have
  84481. * one already.
  84482. *
  84483. * Depending on the the value of \a all, either all or just the first comment
  84484. * whose field name(s) match the given entry's name will be replaced by the
  84485. * given entry. If no comments match, \a entry will simply be appended.
  84486. *
  84487. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  84488. * takes ownership of the \c entry.entry pointer.
  84489. *
  84490. * \note If this function returns \c false, the caller still owns the
  84491. * pointer.
  84492. *
  84493. * \param object A pointer to an existing VORBIS_COMMENT object.
  84494. * \param entry The comment to insert.
  84495. * \param all If \c true, all comments whose field name matches
  84496. * \a entry's field name will be removed, and \a entry will
  84497. * be inserted at the position of the first matching
  84498. * comment. If \c false, only the first comment whose
  84499. * field name matches \a entry's field name will be
  84500. * replaced with \a entry.
  84501. * \param copy See above.
  84502. * \assert
  84503. * \code object != NULL \endcode
  84504. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  84505. * \code (entry.entry != NULL && entry.length > 0) ||
  84506. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  84507. * \retval FLAC__bool
  84508. * \c false if memory allocation fails or \a entry does not comply with the
  84509. * Vorbis comment specification, else \c true.
  84510. */
  84511. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_replace_comment(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool all, FLAC__bool copy);
  84512. /** Delete a comment in a VORBIS_COMMENT block at the given index.
  84513. *
  84514. * \param object A pointer to an existing VORBIS_COMMENT object.
  84515. * \param comment_num The index of the comment to delete.
  84516. * \assert
  84517. * \code object != NULL \endcode
  84518. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  84519. * \code object->data.vorbis_comment.num_comments > comment_num \endcode
  84520. * \retval FLAC__bool
  84521. * \c false if realloc() fails, else \c true.
  84522. */
  84523. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_delete_comment(FLAC__StreamMetadata *object, unsigned comment_num);
  84524. /** Creates a Vorbis comment entry from NUL-terminated name and value strings.
  84525. *
  84526. * On return, the filled-in \a entry->entry pointer will point to malloc()ed
  84527. * memory and shall be owned by the caller. For convenience the entry will
  84528. * have a terminating NUL.
  84529. *
  84530. * \param entry A pointer to a Vorbis comment entry. The entry's
  84531. * \c entry pointer should not point to allocated
  84532. * memory as it will be overwritten.
  84533. * \param field_name The field name in ASCII, \c NUL terminated.
  84534. * \param field_value The field value in UTF-8, \c NUL terminated.
  84535. * \assert
  84536. * \code entry != NULL \endcode
  84537. * \code field_name != NULL \endcode
  84538. * \code field_value != NULL \endcode
  84539. * \retval FLAC__bool
  84540. * \c false if malloc() fails, or if \a field_name or \a field_value does
  84541. * not comply with the Vorbis comment specification, else \c true.
  84542. */
  84543. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_entry_from_name_value_pair(FLAC__StreamMetadata_VorbisComment_Entry *entry, const char *field_name, const char *field_value);
  84544. /** Splits a Vorbis comment entry into NUL-terminated name and value strings.
  84545. *
  84546. * The returned pointers to name and value will be allocated by malloc()
  84547. * and shall be owned by the caller.
  84548. *
  84549. * \param entry An existing Vorbis comment entry.
  84550. * \param field_name The address of where the returned pointer to the
  84551. * field name will be stored.
  84552. * \param field_value The address of where the returned pointer to the
  84553. * field value will be stored.
  84554. * \assert
  84555. * \code (entry.entry != NULL && entry.length > 0) \endcode
  84556. * \code memchr(entry.entry, '=', entry.length) != NULL \endcode
  84557. * \code field_name != NULL \endcode
  84558. * \code field_value != NULL \endcode
  84559. * \retval FLAC__bool
  84560. * \c false if memory allocation fails or \a entry does not comply with the
  84561. * Vorbis comment specification, else \c true.
  84562. */
  84563. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_entry_to_name_value_pair(const FLAC__StreamMetadata_VorbisComment_Entry entry, char **field_name, char **field_value);
  84564. /** Check if the given Vorbis comment entry's field name matches the given
  84565. * field name.
  84566. *
  84567. * \param entry An existing Vorbis comment entry.
  84568. * \param field_name The field name to check.
  84569. * \param field_name_length The length of \a field_name, not including the
  84570. * terminating \c NUL.
  84571. * \assert
  84572. * \code (entry.entry != NULL && entry.length > 0) \endcode
  84573. * \retval FLAC__bool
  84574. * \c true if the field names match, else \c false
  84575. */
  84576. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_entry_matches(const FLAC__StreamMetadata_VorbisComment_Entry entry, const char *field_name, unsigned field_name_length);
  84577. /** Find a Vorbis comment with the given field name.
  84578. *
  84579. * The search begins at entry number \a offset; use an offset of 0 to
  84580. * search from the beginning of the comment array.
  84581. *
  84582. * \param object A pointer to an existing VORBIS_COMMENT object.
  84583. * \param offset The offset into the comment array from where to start
  84584. * the search.
  84585. * \param field_name The field name of the comment to find.
  84586. * \assert
  84587. * \code object != NULL \endcode
  84588. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  84589. * \code field_name != NULL \endcode
  84590. * \retval int
  84591. * The offset in the comment array of the first comment whose field
  84592. * name matches \a field_name, or \c -1 if no match was found.
  84593. */
  84594. FLAC_API int FLAC__metadata_object_vorbiscomment_find_entry_from(const FLAC__StreamMetadata *object, unsigned offset, const char *field_name);
  84595. /** Remove first Vorbis comment matching the given field name.
  84596. *
  84597. * \param object A pointer to an existing VORBIS_COMMENT object.
  84598. * \param field_name The field name of comment to delete.
  84599. * \assert
  84600. * \code object != NULL \endcode
  84601. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  84602. * \retval int
  84603. * \c -1 for memory allocation error, \c 0 for no matching entries,
  84604. * \c 1 for one matching entry deleted.
  84605. */
  84606. FLAC_API int FLAC__metadata_object_vorbiscomment_remove_entry_matching(FLAC__StreamMetadata *object, const char *field_name);
  84607. /** Remove all Vorbis comments matching the given field name.
  84608. *
  84609. * \param object A pointer to an existing VORBIS_COMMENT object.
  84610. * \param field_name The field name of comments to delete.
  84611. * \assert
  84612. * \code object != NULL \endcode
  84613. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  84614. * \retval int
  84615. * \c -1 for memory allocation error, \c 0 for no matching entries,
  84616. * else the number of matching entries deleted.
  84617. */
  84618. FLAC_API int FLAC__metadata_object_vorbiscomment_remove_entries_matching(FLAC__StreamMetadata *object, const char *field_name);
  84619. /** Create a new CUESHEET track instance.
  84620. *
  84621. * The object will be "empty"; i.e. values and data pointers will be \c 0.
  84622. *
  84623. * \retval FLAC__StreamMetadata_CueSheet_Track*
  84624. * \c NULL if there was an error allocating memory, else the new instance.
  84625. */
  84626. FLAC_API FLAC__StreamMetadata_CueSheet_Track *FLAC__metadata_object_cuesheet_track_new(void);
  84627. /** Create a copy of an existing CUESHEET track object.
  84628. *
  84629. * The copy is a "deep" copy, i.e. dynamically allocated data within the
  84630. * object is also copied. The caller takes ownership of the new object and
  84631. * is responsible for freeing it with
  84632. * FLAC__metadata_object_cuesheet_track_delete().
  84633. *
  84634. * \param object Pointer to object to copy.
  84635. * \assert
  84636. * \code object != NULL \endcode
  84637. * \retval FLAC__StreamMetadata_CueSheet_Track*
  84638. * \c NULL if there was an error allocating memory, else the new instance.
  84639. */
  84640. FLAC_API FLAC__StreamMetadata_CueSheet_Track *FLAC__metadata_object_cuesheet_track_clone(const FLAC__StreamMetadata_CueSheet_Track *object);
  84641. /** Delete a CUESHEET track object
  84642. *
  84643. * \param object A pointer to an existing CUESHEET track object.
  84644. * \assert
  84645. * \code object != NULL \endcode
  84646. */
  84647. FLAC_API void FLAC__metadata_object_cuesheet_track_delete(FLAC__StreamMetadata_CueSheet_Track *object);
  84648. /** Resize a track's index point array.
  84649. *
  84650. * If the size shrinks, elements will truncated; if it grows, new blank
  84651. * indices will be added to the end.
  84652. *
  84653. * \param object A pointer to an existing CUESHEET object.
  84654. * \param track_num The index of the track to modify. NOTE: this is not
  84655. * necessarily the same as the track's \a number field.
  84656. * \param new_num_indices The desired length of the array; may be \c 0.
  84657. * \assert
  84658. * \code object != NULL \endcode
  84659. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  84660. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  84661. * \code (object->data.cue_sheet.tracks[track_num].indices == NULL && object->data.cue_sheet.tracks[track_num].num_indices == 0) ||
  84662. * (object->data.cue_sheet.tracks[track_num].indices != NULL && object->data.cue_sheet.tracks[track_num].num_indices > 0) \endcode
  84663. * \retval FLAC__bool
  84664. * \c false if memory allocation error, else \c true.
  84665. */
  84666. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_resize_indices(FLAC__StreamMetadata *object, unsigned track_num, unsigned new_num_indices);
  84667. /** Insert an index point in a CUESHEET track at the given index.
  84668. *
  84669. * \param object A pointer to an existing CUESHEET object.
  84670. * \param track_num The index of the track to modify. NOTE: this is not
  84671. * necessarily the same as the track's \a number field.
  84672. * \param index_num The index into the track's index array at which to
  84673. * insert the index point. NOTE: this is not necessarily
  84674. * the same as the index point's \a number field. The
  84675. * indices at and after \a index_num move right one
  84676. * position. To append an index point to the end, set
  84677. * \a index_num to
  84678. * \c object->data.cue_sheet.tracks[track_num].num_indices .
  84679. * \param index The index point to insert.
  84680. * \assert
  84681. * \code object != NULL \endcode
  84682. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  84683. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  84684. * \code object->data.cue_sheet.tracks[track_num].num_indices >= index_num \endcode
  84685. * \retval FLAC__bool
  84686. * \c false if realloc() fails, else \c true.
  84687. */
  84688. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_insert_index(FLAC__StreamMetadata *object, unsigned track_num, unsigned index_num, FLAC__StreamMetadata_CueSheet_Index index);
  84689. /** Insert a blank index point in a CUESHEET track at the given index.
  84690. *
  84691. * A blank index point is one in which all field values are zero.
  84692. *
  84693. * \param object A pointer to an existing CUESHEET object.
  84694. * \param track_num The index of the track to modify. NOTE: this is not
  84695. * necessarily the same as the track's \a number field.
  84696. * \param index_num The index into the track's index array at which to
  84697. * insert the index point. NOTE: this is not necessarily
  84698. * the same as the index point's \a number field. The
  84699. * indices at and after \a index_num move right one
  84700. * position. To append an index point to the end, set
  84701. * \a index_num to
  84702. * \c object->data.cue_sheet.tracks[track_num].num_indices .
  84703. * \assert
  84704. * \code object != NULL \endcode
  84705. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  84706. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  84707. * \code object->data.cue_sheet.tracks[track_num].num_indices >= index_num \endcode
  84708. * \retval FLAC__bool
  84709. * \c false if realloc() fails, else \c true.
  84710. */
  84711. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_insert_blank_index(FLAC__StreamMetadata *object, unsigned track_num, unsigned index_num);
  84712. /** Delete an index point in a CUESHEET track at the given index.
  84713. *
  84714. * \param object A pointer to an existing CUESHEET object.
  84715. * \param track_num The index into the track array of the track to
  84716. * modify. NOTE: this is not necessarily the same
  84717. * as the track's \a number field.
  84718. * \param index_num The index into the track's index array of the index
  84719. * to delete. NOTE: this is not necessarily the same
  84720. * as the index's \a number field.
  84721. * \assert
  84722. * \code object != NULL \endcode
  84723. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  84724. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  84725. * \code object->data.cue_sheet.tracks[track_num].num_indices > index_num \endcode
  84726. * \retval FLAC__bool
  84727. * \c false if realloc() fails, else \c true.
  84728. */
  84729. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_delete_index(FLAC__StreamMetadata *object, unsigned track_num, unsigned index_num);
  84730. /** Resize the track array.
  84731. *
  84732. * If the size shrinks, elements will truncated; if it grows, new blank
  84733. * tracks will be added to the end.
  84734. *
  84735. * \param object A pointer to an existing CUESHEET object.
  84736. * \param new_num_tracks The desired length of the array; may be \c 0.
  84737. * \assert
  84738. * \code object != NULL \endcode
  84739. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  84740. * \code (object->data.cue_sheet.tracks == NULL && object->data.cue_sheet.num_tracks == 0) ||
  84741. * (object->data.cue_sheet.tracks != NULL && object->data.cue_sheet.num_tracks > 0) \endcode
  84742. * \retval FLAC__bool
  84743. * \c false if memory allocation error, else \c true.
  84744. */
  84745. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_resize_tracks(FLAC__StreamMetadata *object, unsigned new_num_tracks);
  84746. /** Sets a track in a CUESHEET block.
  84747. *
  84748. * If \a copy is \c true, a copy of the track is stored; otherwise, the object
  84749. * takes ownership of the \a track pointer.
  84750. *
  84751. * \param object A pointer to an existing CUESHEET object.
  84752. * \param track_num Index into track array to set. NOTE: this is not
  84753. * necessarily the same as the track's \a number field.
  84754. * \param track The track to set the track to. You may safely pass in
  84755. * a const pointer if \a copy is \c true.
  84756. * \param copy See above.
  84757. * \assert
  84758. * \code object != NULL \endcode
  84759. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  84760. * \code track_num < object->data.cue_sheet.num_tracks \endcode
  84761. * \code (track->indices != NULL && track->num_indices > 0) ||
  84762. * (track->indices == NULL && track->num_indices == 0)
  84763. * \retval FLAC__bool
  84764. * \c false if \a copy is \c true and malloc() fails, else \c true.
  84765. */
  84766. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_set_track(FLAC__StreamMetadata *object, unsigned track_num, FLAC__StreamMetadata_CueSheet_Track *track, FLAC__bool copy);
  84767. /** Insert a track in a CUESHEET block at the given index.
  84768. *
  84769. * If \a copy is \c true, a copy of the track is stored; otherwise, the object
  84770. * takes ownership of the \a track pointer.
  84771. *
  84772. * \param object A pointer to an existing CUESHEET object.
  84773. * \param track_num The index at which to insert the track. NOTE: this
  84774. * is not necessarily the same as the track's \a number
  84775. * field. The tracks at and after \a track_num move right
  84776. * one position. To append a track to the end, set
  84777. * \a track_num to \c object->data.cue_sheet.num_tracks .
  84778. * \param track The track to insert. You may safely pass in a const
  84779. * pointer if \a copy is \c true.
  84780. * \param copy See above.
  84781. * \assert
  84782. * \code object != NULL \endcode
  84783. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  84784. * \code object->data.cue_sheet.num_tracks >= track_num \endcode
  84785. * \retval FLAC__bool
  84786. * \c false if \a copy is \c true and malloc() fails, else \c true.
  84787. */
  84788. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_insert_track(FLAC__StreamMetadata *object, unsigned track_num, FLAC__StreamMetadata_CueSheet_Track *track, FLAC__bool copy);
  84789. /** Insert a blank track in a CUESHEET block at the given index.
  84790. *
  84791. * A blank track is one in which all field values are zero.
  84792. *
  84793. * \param object A pointer to an existing CUESHEET object.
  84794. * \param track_num The index at which to insert the track. NOTE: this
  84795. * is not necessarily the same as the track's \a number
  84796. * field. The tracks at and after \a track_num move right
  84797. * one position. To append a track to the end, set
  84798. * \a track_num to \c object->data.cue_sheet.num_tracks .
  84799. * \assert
  84800. * \code object != NULL \endcode
  84801. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  84802. * \code object->data.cue_sheet.num_tracks >= track_num \endcode
  84803. * \retval FLAC__bool
  84804. * \c false if \a copy is \c true and malloc() fails, else \c true.
  84805. */
  84806. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_insert_blank_track(FLAC__StreamMetadata *object, unsigned track_num);
  84807. /** Delete a track in a CUESHEET block at the given index.
  84808. *
  84809. * \param object A pointer to an existing CUESHEET object.
  84810. * \param track_num The index into the track array of the track to
  84811. * delete. NOTE: this is not necessarily the same
  84812. * as the track's \a number field.
  84813. * \assert
  84814. * \code object != NULL \endcode
  84815. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  84816. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  84817. * \retval FLAC__bool
  84818. * \c false if realloc() fails, else \c true.
  84819. */
  84820. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_delete_track(FLAC__StreamMetadata *object, unsigned track_num);
  84821. /** Check a cue sheet to see if it conforms to the FLAC specification.
  84822. * See the format specification for limits on the contents of the
  84823. * cue sheet.
  84824. *
  84825. * \param object A pointer to an existing CUESHEET object.
  84826. * \param check_cd_da_subset If \c true, check CUESHEET against more
  84827. * stringent requirements for a CD-DA (audio) disc.
  84828. * \param violation Address of a pointer to a string. If there is a
  84829. * violation, a pointer to a string explanation of the
  84830. * violation will be returned here. \a violation may be
  84831. * \c NULL if you don't need the returned string. Do not
  84832. * free the returned string; it will always point to static
  84833. * data.
  84834. * \assert
  84835. * \code object != NULL \endcode
  84836. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  84837. * \retval FLAC__bool
  84838. * \c false if cue sheet is illegal, else \c true.
  84839. */
  84840. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_is_legal(const FLAC__StreamMetadata *object, FLAC__bool check_cd_da_subset, const char **violation);
  84841. /** Calculate and return the CDDB/freedb ID for a cue sheet. The function
  84842. * assumes the cue sheet corresponds to a CD; the result is undefined
  84843. * if the cuesheet's is_cd bit is not set.
  84844. *
  84845. * \param object A pointer to an existing CUESHEET object.
  84846. * \assert
  84847. * \code object != NULL \endcode
  84848. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  84849. * \retval FLAC__uint32
  84850. * The unsigned integer representation of the CDDB/freedb ID
  84851. */
  84852. FLAC_API FLAC__uint32 FLAC__metadata_object_cuesheet_calculate_cddb_id(const FLAC__StreamMetadata *object);
  84853. /** Sets the MIME type of a PICTURE block.
  84854. *
  84855. * If \a copy is \c true, a copy of the string is stored; otherwise, the object
  84856. * takes ownership of the pointer. The existing string will be freed if this
  84857. * function is successful, otherwise the original string will remain if \a copy
  84858. * is \c true and malloc() fails.
  84859. *
  84860. * \note It is safe to pass a const pointer to \a mime_type if \a copy is \c true.
  84861. *
  84862. * \param object A pointer to an existing PICTURE object.
  84863. * \param mime_type A pointer to the MIME type string. The string must be
  84864. * ASCII characters 0x20-0x7e, NUL-terminated. No validation
  84865. * is done.
  84866. * \param copy See above.
  84867. * \assert
  84868. * \code object != NULL \endcode
  84869. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  84870. * \code (mime_type != NULL) \endcode
  84871. * \retval FLAC__bool
  84872. * \c false if \a copy is \c true and malloc() fails, else \c true.
  84873. */
  84874. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_mime_type(FLAC__StreamMetadata *object, char *mime_type, FLAC__bool copy);
  84875. /** Sets the description of a PICTURE block.
  84876. *
  84877. * If \a copy is \c true, a copy of the string is stored; otherwise, the object
  84878. * takes ownership of the pointer. The existing string will be freed if this
  84879. * function is successful, otherwise the original string will remain if \a copy
  84880. * is \c true and malloc() fails.
  84881. *
  84882. * \note It is safe to pass a const pointer to \a description if \a copy is \c true.
  84883. *
  84884. * \param object A pointer to an existing PICTURE object.
  84885. * \param description A pointer to the description string. The string must be
  84886. * valid UTF-8, NUL-terminated. No validation is done.
  84887. * \param copy See above.
  84888. * \assert
  84889. * \code object != NULL \endcode
  84890. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  84891. * \code (description != NULL) \endcode
  84892. * \retval FLAC__bool
  84893. * \c false if \a copy is \c true and malloc() fails, else \c true.
  84894. */
  84895. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_description(FLAC__StreamMetadata *object, FLAC__byte *description, FLAC__bool copy);
  84896. /** Sets the picture data of a PICTURE block.
  84897. *
  84898. * If \a copy is \c true, a copy of the data is stored; otherwise, the object
  84899. * takes ownership of the pointer. Also sets the \a data_length field of the
  84900. * metadata object to what is passed in as the \a length parameter. The
  84901. * existing data will be freed if this function is successful, otherwise the
  84902. * original data and data_length will remain if \a copy is \c true and
  84903. * malloc() fails.
  84904. *
  84905. * \note It is safe to pass a const pointer to \a data if \a copy is \c true.
  84906. *
  84907. * \param object A pointer to an existing PICTURE object.
  84908. * \param data A pointer to the data to set.
  84909. * \param length The length of \a data in bytes.
  84910. * \param copy See above.
  84911. * \assert
  84912. * \code object != NULL \endcode
  84913. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  84914. * \code (data != NULL && length > 0) ||
  84915. * (data == NULL && length == 0 && copy == false) \endcode
  84916. * \retval FLAC__bool
  84917. * \c false if \a copy is \c true and malloc() fails, else \c true.
  84918. */
  84919. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_data(FLAC__StreamMetadata *object, FLAC__byte *data, FLAC__uint32 length, FLAC__bool copy);
  84920. /** Check a PICTURE block to see if it conforms to the FLAC specification.
  84921. * See the format specification for limits on the contents of the
  84922. * PICTURE block.
  84923. *
  84924. * \param object A pointer to existing PICTURE block to be checked.
  84925. * \param violation Address of a pointer to a string. If there is a
  84926. * violation, a pointer to a string explanation of the
  84927. * violation will be returned here. \a violation may be
  84928. * \c NULL if you don't need the returned string. Do not
  84929. * free the returned string; it will always point to static
  84930. * data.
  84931. * \assert
  84932. * \code object != NULL \endcode
  84933. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  84934. * \retval FLAC__bool
  84935. * \c false if PICTURE block is illegal, else \c true.
  84936. */
  84937. FLAC_API FLAC__bool FLAC__metadata_object_picture_is_legal(const FLAC__StreamMetadata *object, const char **violation);
  84938. /* \} */
  84939. #ifdef __cplusplus
  84940. }
  84941. #endif
  84942. #endif
  84943. /********* End of inlined file: metadata.h *********/
  84944. /********* Start of inlined file: stream_decoder.h *********/
  84945. #ifndef FLAC__STREAM_DECODER_H
  84946. #define FLAC__STREAM_DECODER_H
  84947. #include <stdio.h> /* for FILE */
  84948. #ifdef __cplusplus
  84949. extern "C" {
  84950. #endif
  84951. /** \file include/FLAC/stream_decoder.h
  84952. *
  84953. * \brief
  84954. * This module contains the functions which implement the stream
  84955. * decoder.
  84956. *
  84957. * See the detailed documentation in the
  84958. * \link flac_stream_decoder stream decoder \endlink module.
  84959. */
  84960. /** \defgroup flac_decoder FLAC/ \*_decoder.h: decoder interfaces
  84961. * \ingroup flac
  84962. *
  84963. * \brief
  84964. * This module describes the decoder layers provided by libFLAC.
  84965. *
  84966. * The stream decoder can be used to decode complete streams either from
  84967. * the client via callbacks, or directly from a file, depending on how
  84968. * it is initialized. When decoding via callbacks, the client provides
  84969. * callbacks for reading FLAC data and writing decoded samples, and
  84970. * handling metadata and errors. If the client also supplies seek-related
  84971. * callback, the decoder function for sample-accurate seeking within the
  84972. * FLAC input is also available. When decoding from a file, the client
  84973. * needs only supply a filename or open \c FILE* and write/metadata/error
  84974. * callbacks; the rest of the callbacks are supplied internally. For more
  84975. * info see the \link flac_stream_decoder stream decoder \endlink module.
  84976. */
  84977. /** \defgroup flac_stream_decoder FLAC/stream_decoder.h: stream decoder interface
  84978. * \ingroup flac_decoder
  84979. *
  84980. * \brief
  84981. * This module contains the functions which implement the stream
  84982. * decoder.
  84983. *
  84984. * The stream decoder can decode native FLAC, and optionally Ogg FLAC
  84985. * (check FLAC_API_SUPPORTS_OGG_FLAC) streams and files.
  84986. *
  84987. * The basic usage of this decoder is as follows:
  84988. * - The program creates an instance of a decoder using
  84989. * FLAC__stream_decoder_new().
  84990. * - The program overrides the default settings using
  84991. * FLAC__stream_decoder_set_*() functions.
  84992. * - The program initializes the instance to validate the settings and
  84993. * prepare for decoding using
  84994. * - FLAC__stream_decoder_init_stream() or FLAC__stream_decoder_init_FILE()
  84995. * or FLAC__stream_decoder_init_file() for native FLAC,
  84996. * - FLAC__stream_decoder_init_ogg_stream() or FLAC__stream_decoder_init_ogg_FILE()
  84997. * or FLAC__stream_decoder_init_ogg_file() for Ogg FLAC
  84998. * - The program calls the FLAC__stream_decoder_process_*() functions
  84999. * to decode data, which subsequently calls the callbacks.
  85000. * - The program finishes the decoding with FLAC__stream_decoder_finish(),
  85001. * which flushes the input and output and resets the decoder to the
  85002. * uninitialized state.
  85003. * - The instance may be used again or deleted with
  85004. * FLAC__stream_decoder_delete().
  85005. *
  85006. * In more detail, the program will create a new instance by calling
  85007. * FLAC__stream_decoder_new(), then call FLAC__stream_decoder_set_*()
  85008. * functions to override the default decoder options, and call
  85009. * one of the FLAC__stream_decoder_init_*() functions.
  85010. *
  85011. * There are three initialization functions for native FLAC, one for
  85012. * setting up the decoder to decode FLAC data from the client via
  85013. * callbacks, and two for decoding directly from a FLAC file.
  85014. *
  85015. * For decoding via callbacks, use FLAC__stream_decoder_init_stream().
  85016. * You must also supply several callbacks for handling I/O. Some (like
  85017. * seeking) are optional, depending on the capabilities of the input.
  85018. *
  85019. * For decoding directly from a file, use FLAC__stream_decoder_init_FILE()
  85020. * or FLAC__stream_decoder_init_file(). Then you must only supply an open
  85021. * \c FILE* or filename and fewer callbacks; the decoder will handle
  85022. * the other callbacks internally.
  85023. *
  85024. * There are three similarly-named init functions for decoding from Ogg
  85025. * FLAC streams. Check \c FLAC_API_SUPPORTS_OGG_FLAC to find out if the
  85026. * library has been built with Ogg support.
  85027. *
  85028. * Once the decoder is initialized, your program will call one of several
  85029. * functions to start the decoding process:
  85030. *
  85031. * - FLAC__stream_decoder_process_single() - Tells the decoder to process at
  85032. * most one metadata block or audio frame and return, calling either the
  85033. * metadata callback or write callback, respectively, once. If the decoder
  85034. * loses sync it will return with only the error callback being called.
  85035. * - FLAC__stream_decoder_process_until_end_of_metadata() - Tells the decoder
  85036. * to process the stream from the current location and stop upon reaching
  85037. * the first audio frame. The client will get one metadata, write, or error
  85038. * callback per metadata block, audio frame, or sync error, respectively.
  85039. * - FLAC__stream_decoder_process_until_end_of_stream() - Tells the decoder
  85040. * to process the stream from the current location until the read callback
  85041. * returns FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM or
  85042. * FLAC__STREAM_DECODER_READ_STATUS_ABORT. The client will get one metadata,
  85043. * write, or error callback per metadata block, audio frame, or sync error,
  85044. * respectively.
  85045. *
  85046. * When the decoder has finished decoding (normally or through an abort),
  85047. * the instance is finished by calling FLAC__stream_decoder_finish(), which
  85048. * ensures the decoder is in the correct state and frees memory. Then the
  85049. * instance may be deleted with FLAC__stream_decoder_delete() or initialized
  85050. * again to decode another stream.
  85051. *
  85052. * Seeking is exposed through the FLAC__stream_decoder_seek_absolute() method.
  85053. * At any point after the stream decoder has been initialized, the client can
  85054. * call this function to seek to an exact sample within the stream.
  85055. * Subsequently, the first time the write callback is called it will be
  85056. * passed a (possibly partial) block starting at that sample.
  85057. *
  85058. * If the client cannot seek via the callback interface provided, but still
  85059. * has another way of seeking, it can flush the decoder using
  85060. * FLAC__stream_decoder_flush() and start feeding data from the new position
  85061. * through the read callback.
  85062. *
  85063. * The stream decoder also provides MD5 signature checking. If this is
  85064. * turned on before initialization, FLAC__stream_decoder_finish() will
  85065. * report when the decoded MD5 signature does not match the one stored
  85066. * in the STREAMINFO block. MD5 checking is automatically turned off
  85067. * (until the next FLAC__stream_decoder_reset()) if there is no signature
  85068. * in the STREAMINFO block or when a seek is attempted.
  85069. *
  85070. * The FLAC__stream_decoder_set_metadata_*() functions deserve special
  85071. * attention. By default, the decoder only calls the metadata_callback for
  85072. * the STREAMINFO block. These functions allow you to tell the decoder
  85073. * explicitly which blocks to parse and return via the metadata_callback
  85074. * and/or which to skip. Use a FLAC__stream_decoder_set_metadata_respond_all(),
  85075. * FLAC__stream_decoder_set_metadata_ignore() ... or FLAC__stream_decoder_set_metadata_ignore_all(),
  85076. * FLAC__stream_decoder_set_metadata_respond() ... sequence to exactly specify
  85077. * which blocks to return. Remember that metadata blocks can potentially
  85078. * be big (for example, cover art) so filtering out the ones you don't
  85079. * use can reduce the memory requirements of the decoder. Also note the
  85080. * special forms FLAC__stream_decoder_set_metadata_respond_application(id)
  85081. * and FLAC__stream_decoder_set_metadata_ignore_application(id) for
  85082. * filtering APPLICATION blocks based on the application ID.
  85083. *
  85084. * STREAMINFO and SEEKTABLE blocks are always parsed and used internally, but
  85085. * they still can legally be filtered from the metadata_callback.
  85086. *
  85087. * \note
  85088. * The "set" functions may only be called when the decoder is in the
  85089. * state FLAC__STREAM_DECODER_UNINITIALIZED, i.e. after
  85090. * FLAC__stream_decoder_new() or FLAC__stream_decoder_finish(), but
  85091. * before FLAC__stream_decoder_init_*(). If this is the case they will
  85092. * return \c true, otherwise \c false.
  85093. *
  85094. * \note
  85095. * FLAC__stream_decoder_finish() resets all settings to the constructor
  85096. * defaults, including the callbacks.
  85097. *
  85098. * \{
  85099. */
  85100. /** State values for a FLAC__StreamDecoder
  85101. *
  85102. * The decoder's state can be obtained by calling FLAC__stream_decoder_get_state().
  85103. */
  85104. typedef enum {
  85105. FLAC__STREAM_DECODER_SEARCH_FOR_METADATA = 0,
  85106. /**< The decoder is ready to search for metadata. */
  85107. FLAC__STREAM_DECODER_READ_METADATA,
  85108. /**< The decoder is ready to or is in the process of reading metadata. */
  85109. FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC,
  85110. /**< The decoder is ready to or is in the process of searching for the
  85111. * frame sync code.
  85112. */
  85113. FLAC__STREAM_DECODER_READ_FRAME,
  85114. /**< The decoder is ready to or is in the process of reading a frame. */
  85115. FLAC__STREAM_DECODER_END_OF_STREAM,
  85116. /**< The decoder has reached the end of the stream. */
  85117. FLAC__STREAM_DECODER_OGG_ERROR,
  85118. /**< An error occurred in the underlying Ogg layer. */
  85119. FLAC__STREAM_DECODER_SEEK_ERROR,
  85120. /**< An error occurred while seeking. The decoder must be flushed
  85121. * with FLAC__stream_decoder_flush() or reset with
  85122. * FLAC__stream_decoder_reset() before decoding can continue.
  85123. */
  85124. FLAC__STREAM_DECODER_ABORTED,
  85125. /**< The decoder was aborted by the read callback. */
  85126. FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR,
  85127. /**< An error occurred allocating memory. The decoder is in an invalid
  85128. * state and can no longer be used.
  85129. */
  85130. FLAC__STREAM_DECODER_UNINITIALIZED
  85131. /**< The decoder is in the uninitialized state; one of the
  85132. * FLAC__stream_decoder_init_*() functions must be called before samples
  85133. * can be processed.
  85134. */
  85135. } FLAC__StreamDecoderState;
  85136. /** Maps a FLAC__StreamDecoderState to a C string.
  85137. *
  85138. * Using a FLAC__StreamDecoderState as the index to this array
  85139. * will give the string equivalent. The contents should not be modified.
  85140. */
  85141. extern FLAC_API const char * const FLAC__StreamDecoderStateString[];
  85142. /** Possible return values for the FLAC__stream_decoder_init_*() functions.
  85143. */
  85144. typedef enum {
  85145. FLAC__STREAM_DECODER_INIT_STATUS_OK = 0,
  85146. /**< Initialization was successful. */
  85147. FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER,
  85148. /**< The library was not compiled with support for the given container
  85149. * format.
  85150. */
  85151. FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS,
  85152. /**< A required callback was not supplied. */
  85153. FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR,
  85154. /**< An error occurred allocating memory. */
  85155. FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE,
  85156. /**< fopen() failed in FLAC__stream_decoder_init_file() or
  85157. * FLAC__stream_decoder_init_ogg_file(). */
  85158. FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED
  85159. /**< FLAC__stream_decoder_init_*() was called when the decoder was
  85160. * already initialized, usually because
  85161. * FLAC__stream_decoder_finish() was not called.
  85162. */
  85163. } FLAC__StreamDecoderInitStatus;
  85164. /** Maps a FLAC__StreamDecoderInitStatus to a C string.
  85165. *
  85166. * Using a FLAC__StreamDecoderInitStatus as the index to this array
  85167. * will give the string equivalent. The contents should not be modified.
  85168. */
  85169. extern FLAC_API const char * const FLAC__StreamDecoderInitStatusString[];
  85170. /** Return values for the FLAC__StreamDecoder read callback.
  85171. */
  85172. typedef enum {
  85173. FLAC__STREAM_DECODER_READ_STATUS_CONTINUE,
  85174. /**< The read was OK and decoding can continue. */
  85175. FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM,
  85176. /**< The read was attempted while at the end of the stream. Note that
  85177. * the client must only return this value when the read callback was
  85178. * called when already at the end of the stream. Otherwise, if the read
  85179. * itself moves to the end of the stream, the client should still return
  85180. * the data and \c FLAC__STREAM_DECODER_READ_STATUS_CONTINUE, and then on
  85181. * the next read callback it should return
  85182. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM with a byte count
  85183. * of \c 0.
  85184. */
  85185. FLAC__STREAM_DECODER_READ_STATUS_ABORT
  85186. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  85187. } FLAC__StreamDecoderReadStatus;
  85188. /** Maps a FLAC__StreamDecoderReadStatus to a C string.
  85189. *
  85190. * Using a FLAC__StreamDecoderReadStatus as the index to this array
  85191. * will give the string equivalent. The contents should not be modified.
  85192. */
  85193. extern FLAC_API const char * const FLAC__StreamDecoderReadStatusString[];
  85194. /** Return values for the FLAC__StreamDecoder seek callback.
  85195. */
  85196. typedef enum {
  85197. FLAC__STREAM_DECODER_SEEK_STATUS_OK,
  85198. /**< The seek was OK and decoding can continue. */
  85199. FLAC__STREAM_DECODER_SEEK_STATUS_ERROR,
  85200. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  85201. FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  85202. /**< Client does not support seeking. */
  85203. } FLAC__StreamDecoderSeekStatus;
  85204. /** Maps a FLAC__StreamDecoderSeekStatus to a C string.
  85205. *
  85206. * Using a FLAC__StreamDecoderSeekStatus as the index to this array
  85207. * will give the string equivalent. The contents should not be modified.
  85208. */
  85209. extern FLAC_API const char * const FLAC__StreamDecoderSeekStatusString[];
  85210. /** Return values for the FLAC__StreamDecoder tell callback.
  85211. */
  85212. typedef enum {
  85213. FLAC__STREAM_DECODER_TELL_STATUS_OK,
  85214. /**< The tell was OK and decoding can continue. */
  85215. FLAC__STREAM_DECODER_TELL_STATUS_ERROR,
  85216. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  85217. FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  85218. /**< Client does not support telling the position. */
  85219. } FLAC__StreamDecoderTellStatus;
  85220. /** Maps a FLAC__StreamDecoderTellStatus to a C string.
  85221. *
  85222. * Using a FLAC__StreamDecoderTellStatus as the index to this array
  85223. * will give the string equivalent. The contents should not be modified.
  85224. */
  85225. extern FLAC_API const char * const FLAC__StreamDecoderTellStatusString[];
  85226. /** Return values for the FLAC__StreamDecoder length callback.
  85227. */
  85228. typedef enum {
  85229. FLAC__STREAM_DECODER_LENGTH_STATUS_OK,
  85230. /**< The length call was OK and decoding can continue. */
  85231. FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR,
  85232. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  85233. FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  85234. /**< Client does not support reporting the length. */
  85235. } FLAC__StreamDecoderLengthStatus;
  85236. /** Maps a FLAC__StreamDecoderLengthStatus to a C string.
  85237. *
  85238. * Using a FLAC__StreamDecoderLengthStatus as the index to this array
  85239. * will give the string equivalent. The contents should not be modified.
  85240. */
  85241. extern FLAC_API const char * const FLAC__StreamDecoderLengthStatusString[];
  85242. /** Return values for the FLAC__StreamDecoder write callback.
  85243. */
  85244. typedef enum {
  85245. FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE,
  85246. /**< The write was OK and decoding can continue. */
  85247. FLAC__STREAM_DECODER_WRITE_STATUS_ABORT
  85248. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  85249. } FLAC__StreamDecoderWriteStatus;
  85250. /** Maps a FLAC__StreamDecoderWriteStatus to a C string.
  85251. *
  85252. * Using a FLAC__StreamDecoderWriteStatus as the index to this array
  85253. * will give the string equivalent. The contents should not be modified.
  85254. */
  85255. extern FLAC_API const char * const FLAC__StreamDecoderWriteStatusString[];
  85256. /** Possible values passed back to the FLAC__StreamDecoder error callback.
  85257. * \c FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC is the generic catch-
  85258. * all. The rest could be caused by bad sync (false synchronization on
  85259. * data that is not the start of a frame) or corrupted data. The error
  85260. * itself is the decoder's best guess at what happened assuming a correct
  85261. * sync. For example \c FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER
  85262. * could be caused by a correct sync on the start of a frame, but some
  85263. * data in the frame header was corrupted. Or it could be the result of
  85264. * syncing on a point the stream that looked like the starting of a frame
  85265. * but was not. \c FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM
  85266. * could be because the decoder encountered a valid frame made by a future
  85267. * version of the encoder which it cannot parse, or because of a false
  85268. * sync making it appear as though an encountered frame was generated by
  85269. * a future encoder.
  85270. */
  85271. typedef enum {
  85272. FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC,
  85273. /**< An error in the stream caused the decoder to lose synchronization. */
  85274. FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER,
  85275. /**< The decoder encountered a corrupted frame header. */
  85276. FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH,
  85277. /**< The frame's data did not match the CRC in the footer. */
  85278. FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM
  85279. /**< The decoder encountered reserved fields in use in the stream. */
  85280. } FLAC__StreamDecoderErrorStatus;
  85281. /** Maps a FLAC__StreamDecoderErrorStatus to a C string.
  85282. *
  85283. * Using a FLAC__StreamDecoderErrorStatus as the index to this array
  85284. * will give the string equivalent. The contents should not be modified.
  85285. */
  85286. extern FLAC_API const char * const FLAC__StreamDecoderErrorStatusString[];
  85287. /***********************************************************************
  85288. *
  85289. * class FLAC__StreamDecoder
  85290. *
  85291. ***********************************************************************/
  85292. struct FLAC__StreamDecoderProtected;
  85293. struct FLAC__StreamDecoderPrivate;
  85294. /** The opaque structure definition for the stream decoder type.
  85295. * See the \link flac_stream_decoder stream decoder module \endlink
  85296. * for a detailed description.
  85297. */
  85298. typedef struct {
  85299. struct FLAC__StreamDecoderProtected *protected_; /* avoid the C++ keyword 'protected' */
  85300. struct FLAC__StreamDecoderPrivate *private_; /* avoid the C++ keyword 'private' */
  85301. } FLAC__StreamDecoder;
  85302. /** Signature for the read callback.
  85303. *
  85304. * A function pointer matching this signature must be passed to
  85305. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  85306. * called when the decoder needs more input data. The address of the
  85307. * buffer to be filled is supplied, along with the number of bytes the
  85308. * buffer can hold. The callback may choose to supply less data and
  85309. * modify the byte count but must be careful not to overflow the buffer.
  85310. * The callback then returns a status code chosen from
  85311. * FLAC__StreamDecoderReadStatus.
  85312. *
  85313. * Here is an example of a read callback for stdio streams:
  85314. * \code
  85315. * FLAC__StreamDecoderReadStatus read_cb(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  85316. * {
  85317. * FILE *file = ((MyClientData*)client_data)->file;
  85318. * if(*bytes > 0) {
  85319. * *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, file);
  85320. * if(ferror(file))
  85321. * return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  85322. * else if(*bytes == 0)
  85323. * return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  85324. * else
  85325. * return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  85326. * }
  85327. * else
  85328. * return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  85329. * }
  85330. * \endcode
  85331. *
  85332. * \note In general, FLAC__StreamDecoder functions which change the
  85333. * state should not be called on the \a decoder while in the callback.
  85334. *
  85335. * \param decoder The decoder instance calling the callback.
  85336. * \param buffer A pointer to a location for the callee to store
  85337. * data to be decoded.
  85338. * \param bytes A pointer to the size of the buffer. On entry
  85339. * to the callback, it contains the maximum number
  85340. * of bytes that may be stored in \a buffer. The
  85341. * callee must set it to the actual number of bytes
  85342. * stored (0 in case of error or end-of-stream) before
  85343. * returning.
  85344. * \param client_data The callee's client data set through
  85345. * FLAC__stream_decoder_init_*().
  85346. * \retval FLAC__StreamDecoderReadStatus
  85347. * The callee's return status. Note that the callback should return
  85348. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM if and only if
  85349. * zero bytes were read and there is no more data to be read.
  85350. */
  85351. typedef FLAC__StreamDecoderReadStatus (*FLAC__StreamDecoderReadCallback)(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  85352. /** Signature for the seek callback.
  85353. *
  85354. * A function pointer matching this signature may be passed to
  85355. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  85356. * called when the decoder needs to seek the input stream. The decoder
  85357. * will pass the absolute byte offset to seek to, 0 meaning the
  85358. * beginning of the stream.
  85359. *
  85360. * Here is an example of a seek callback for stdio streams:
  85361. * \code
  85362. * FLAC__StreamDecoderSeekStatus seek_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  85363. * {
  85364. * FILE *file = ((MyClientData*)client_data)->file;
  85365. * if(file == stdin)
  85366. * return FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED;
  85367. * else if(fseeko(file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  85368. * return FLAC__STREAM_DECODER_SEEK_STATUS_ERROR;
  85369. * else
  85370. * return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  85371. * }
  85372. * \endcode
  85373. *
  85374. * \note In general, FLAC__StreamDecoder functions which change the
  85375. * state should not be called on the \a decoder while in the callback.
  85376. *
  85377. * \param decoder The decoder instance calling the callback.
  85378. * \param absolute_byte_offset The offset from the beginning of the stream
  85379. * to seek to.
  85380. * \param client_data The callee's client data set through
  85381. * FLAC__stream_decoder_init_*().
  85382. * \retval FLAC__StreamDecoderSeekStatus
  85383. * The callee's return status.
  85384. */
  85385. typedef FLAC__StreamDecoderSeekStatus (*FLAC__StreamDecoderSeekCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  85386. /** Signature for the tell callback.
  85387. *
  85388. * A function pointer matching this signature may be passed to
  85389. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  85390. * called when the decoder wants to know the current position of the
  85391. * stream. The callback should return the byte offset from the
  85392. * beginning of the stream.
  85393. *
  85394. * Here is an example of a tell callback for stdio streams:
  85395. * \code
  85396. * FLAC__StreamDecoderTellStatus tell_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  85397. * {
  85398. * FILE *file = ((MyClientData*)client_data)->file;
  85399. * off_t pos;
  85400. * if(file == stdin)
  85401. * return FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED;
  85402. * else if((pos = ftello(file)) < 0)
  85403. * return FLAC__STREAM_DECODER_TELL_STATUS_ERROR;
  85404. * else {
  85405. * *absolute_byte_offset = (FLAC__uint64)pos;
  85406. * return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  85407. * }
  85408. * }
  85409. * \endcode
  85410. *
  85411. * \note In general, FLAC__StreamDecoder functions which change the
  85412. * state should not be called on the \a decoder while in the callback.
  85413. *
  85414. * \param decoder The decoder instance calling the callback.
  85415. * \param absolute_byte_offset A pointer to storage for the current offset
  85416. * from the beginning of the stream.
  85417. * \param client_data The callee's client data set through
  85418. * FLAC__stream_decoder_init_*().
  85419. * \retval FLAC__StreamDecoderTellStatus
  85420. * The callee's return status.
  85421. */
  85422. typedef FLAC__StreamDecoderTellStatus (*FLAC__StreamDecoderTellCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  85423. /** Signature for the length callback.
  85424. *
  85425. * A function pointer matching this signature may be passed to
  85426. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  85427. * called when the decoder wants to know the total length of the stream
  85428. * in bytes.
  85429. *
  85430. * Here is an example of a length callback for stdio streams:
  85431. * \code
  85432. * FLAC__StreamDecoderLengthStatus length_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data)
  85433. * {
  85434. * FILE *file = ((MyClientData*)client_data)->file;
  85435. * struct stat filestats;
  85436. *
  85437. * if(file == stdin)
  85438. * return FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED;
  85439. * else if(fstat(fileno(file), &filestats) != 0)
  85440. * return FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR;
  85441. * else {
  85442. * *stream_length = (FLAC__uint64)filestats.st_size;
  85443. * return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  85444. * }
  85445. * }
  85446. * \endcode
  85447. *
  85448. * \note In general, FLAC__StreamDecoder functions which change the
  85449. * state should not be called on the \a decoder while in the callback.
  85450. *
  85451. * \param decoder The decoder instance calling the callback.
  85452. * \param stream_length A pointer to storage for the length of the stream
  85453. * in bytes.
  85454. * \param client_data The callee's client data set through
  85455. * FLAC__stream_decoder_init_*().
  85456. * \retval FLAC__StreamDecoderLengthStatus
  85457. * The callee's return status.
  85458. */
  85459. typedef FLAC__StreamDecoderLengthStatus (*FLAC__StreamDecoderLengthCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data);
  85460. /** Signature for the EOF callback.
  85461. *
  85462. * A function pointer matching this signature may be passed to
  85463. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  85464. * called when the decoder needs to know if the end of the stream has
  85465. * been reached.
  85466. *
  85467. * Here is an example of a EOF callback for stdio streams:
  85468. * FLAC__bool eof_cb(const FLAC__StreamDecoder *decoder, void *client_data)
  85469. * \code
  85470. * {
  85471. * FILE *file = ((MyClientData*)client_data)->file;
  85472. * return feof(file)? true : false;
  85473. * }
  85474. * \endcode
  85475. *
  85476. * \note In general, FLAC__StreamDecoder functions which change the
  85477. * state should not be called on the \a decoder while in the callback.
  85478. *
  85479. * \param decoder The decoder instance calling the callback.
  85480. * \param client_data The callee's client data set through
  85481. * FLAC__stream_decoder_init_*().
  85482. * \retval FLAC__bool
  85483. * \c true if the currently at the end of the stream, else \c false.
  85484. */
  85485. typedef FLAC__bool (*FLAC__StreamDecoderEofCallback)(const FLAC__StreamDecoder *decoder, void *client_data);
  85486. /** Signature for the write callback.
  85487. *
  85488. * A function pointer matching this signature must be passed to one of
  85489. * the FLAC__stream_decoder_init_*() functions.
  85490. * The supplied function will be called when the decoder has decoded a
  85491. * single audio frame. The decoder will pass the frame metadata as well
  85492. * as an array of pointers (one for each channel) pointing to the
  85493. * decoded audio.
  85494. *
  85495. * \note In general, FLAC__StreamDecoder functions which change the
  85496. * state should not be called on the \a decoder while in the callback.
  85497. *
  85498. * \param decoder The decoder instance calling the callback.
  85499. * \param frame The description of the decoded frame. See
  85500. * FLAC__Frame.
  85501. * \param buffer An array of pointers to decoded channels of data.
  85502. * Each pointer will point to an array of signed
  85503. * samples of length \a frame->header.blocksize.
  85504. * Channels will be ordered according to the FLAC
  85505. * specification; see the documentation for the
  85506. * <A HREF="../format.html#frame_header">frame header</A>.
  85507. * \param client_data The callee's client data set through
  85508. * FLAC__stream_decoder_init_*().
  85509. * \retval FLAC__StreamDecoderWriteStatus
  85510. * The callee's return status.
  85511. */
  85512. typedef FLAC__StreamDecoderWriteStatus (*FLAC__StreamDecoderWriteCallback)(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
  85513. /** Signature for the metadata callback.
  85514. *
  85515. * A function pointer matching this signature must be passed to one of
  85516. * the FLAC__stream_decoder_init_*() functions.
  85517. * The supplied function will be called when the decoder has decoded a
  85518. * metadata block. In a valid FLAC file there will always be one
  85519. * \c STREAMINFO block, followed by zero or more other metadata blocks.
  85520. * These will be supplied by the decoder in the same order as they
  85521. * appear in the stream and always before the first audio frame (i.e.
  85522. * write callback). The metadata block that is passed in must not be
  85523. * modified, and it doesn't live beyond the callback, so you should make
  85524. * a copy of it with FLAC__metadata_object_clone() if you will need it
  85525. * elsewhere. Since metadata blocks can potentially be large, by
  85526. * default the decoder only calls the metadata callback for the
  85527. * \c STREAMINFO block; you can instruct the decoder to pass or filter
  85528. * other blocks with FLAC__stream_decoder_set_metadata_*() calls.
  85529. *
  85530. * \note In general, FLAC__StreamDecoder functions which change the
  85531. * state should not be called on the \a decoder while in the callback.
  85532. *
  85533. * \param decoder The decoder instance calling the callback.
  85534. * \param metadata The decoded metadata block.
  85535. * \param client_data The callee's client data set through
  85536. * FLAC__stream_decoder_init_*().
  85537. */
  85538. typedef void (*FLAC__StreamDecoderMetadataCallback)(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
  85539. /** Signature for the error callback.
  85540. *
  85541. * A function pointer matching this signature must be passed to one of
  85542. * the FLAC__stream_decoder_init_*() functions.
  85543. * The supplied function will be called whenever an error occurs during
  85544. * decoding.
  85545. *
  85546. * \note In general, FLAC__StreamDecoder functions which change the
  85547. * state should not be called on the \a decoder while in the callback.
  85548. *
  85549. * \param decoder The decoder instance calling the callback.
  85550. * \param status The error encountered by the decoder.
  85551. * \param client_data The callee's client data set through
  85552. * FLAC__stream_decoder_init_*().
  85553. */
  85554. typedef void (*FLAC__StreamDecoderErrorCallback)(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
  85555. /***********************************************************************
  85556. *
  85557. * Class constructor/destructor
  85558. *
  85559. ***********************************************************************/
  85560. /** Create a new stream decoder instance. The instance is created with
  85561. * default settings; see the individual FLAC__stream_decoder_set_*()
  85562. * functions for each setting's default.
  85563. *
  85564. * \retval FLAC__StreamDecoder*
  85565. * \c NULL if there was an error allocating memory, else the new instance.
  85566. */
  85567. FLAC_API FLAC__StreamDecoder *FLAC__stream_decoder_new(void);
  85568. /** Free a decoder instance. Deletes the object pointed to by \a decoder.
  85569. *
  85570. * \param decoder A pointer to an existing decoder.
  85571. * \assert
  85572. * \code decoder != NULL \endcode
  85573. */
  85574. FLAC_API void FLAC__stream_decoder_delete(FLAC__StreamDecoder *decoder);
  85575. /***********************************************************************
  85576. *
  85577. * Public class method prototypes
  85578. *
  85579. ***********************************************************************/
  85580. /** Set the serial number for the FLAC stream within the Ogg container.
  85581. * The default behavior is to use the serial number of the first Ogg
  85582. * page. Setting a serial number here will explicitly specify which
  85583. * stream is to be decoded.
  85584. *
  85585. * \note
  85586. * This does not need to be set for native FLAC decoding.
  85587. *
  85588. * \default \c use serial number of first page
  85589. * \param decoder A decoder instance to set.
  85590. * \param serial_number See above.
  85591. * \assert
  85592. * \code decoder != NULL \endcode
  85593. * \retval FLAC__bool
  85594. * \c false if the decoder is already initialized, else \c true.
  85595. */
  85596. FLAC_API FLAC__bool FLAC__stream_decoder_set_ogg_serial_number(FLAC__StreamDecoder *decoder, long serial_number);
  85597. /** Set the "MD5 signature checking" flag. If \c true, the decoder will
  85598. * compute the MD5 signature of the unencoded audio data while decoding
  85599. * and compare it to the signature from the STREAMINFO block, if it
  85600. * exists, during FLAC__stream_decoder_finish().
  85601. *
  85602. * MD5 signature checking will be turned off (until the next
  85603. * FLAC__stream_decoder_reset()) if there is no signature in the
  85604. * STREAMINFO block or when a seek is attempted.
  85605. *
  85606. * Clients that do not use the MD5 check should leave this off to speed
  85607. * up decoding.
  85608. *
  85609. * \default \c false
  85610. * \param decoder A decoder instance to set.
  85611. * \param value Flag value (see above).
  85612. * \assert
  85613. * \code decoder != NULL \endcode
  85614. * \retval FLAC__bool
  85615. * \c false if the decoder is already initialized, else \c true.
  85616. */
  85617. FLAC_API FLAC__bool FLAC__stream_decoder_set_md5_checking(FLAC__StreamDecoder *decoder, FLAC__bool value);
  85618. /** Direct the decoder to pass on all metadata blocks of type \a type.
  85619. *
  85620. * \default By default, only the \c STREAMINFO block is returned via the
  85621. * metadata callback.
  85622. * \param decoder A decoder instance to set.
  85623. * \param type See above.
  85624. * \assert
  85625. * \code decoder != NULL \endcode
  85626. * \a type is valid
  85627. * \retval FLAC__bool
  85628. * \c false if the decoder is already initialized, else \c true.
  85629. */
  85630. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond(FLAC__StreamDecoder *decoder, FLAC__MetadataType type);
  85631. /** Direct the decoder to pass on all APPLICATION metadata blocks of the
  85632. * given \a id.
  85633. *
  85634. * \default By default, only the \c STREAMINFO block is returned via the
  85635. * metadata callback.
  85636. * \param decoder A decoder instance to set.
  85637. * \param id See above.
  85638. * \assert
  85639. * \code decoder != NULL \endcode
  85640. * \code id != NULL \endcode
  85641. * \retval FLAC__bool
  85642. * \c false if the decoder is already initialized, else \c true.
  85643. */
  85644. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4]);
  85645. /** Direct the decoder to pass on all metadata blocks of any type.
  85646. *
  85647. * \default By default, only the \c STREAMINFO block is returned via the
  85648. * metadata callback.
  85649. * \param decoder A decoder instance to set.
  85650. * \assert
  85651. * \code decoder != NULL \endcode
  85652. * \retval FLAC__bool
  85653. * \c false if the decoder is already initialized, else \c true.
  85654. */
  85655. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_all(FLAC__StreamDecoder *decoder);
  85656. /** Direct the decoder to filter out all metadata blocks of type \a type.
  85657. *
  85658. * \default By default, only the \c STREAMINFO block is returned via the
  85659. * metadata callback.
  85660. * \param decoder A decoder instance to set.
  85661. * \param type See above.
  85662. * \assert
  85663. * \code decoder != NULL \endcode
  85664. * \a type is valid
  85665. * \retval FLAC__bool
  85666. * \c false if the decoder is already initialized, else \c true.
  85667. */
  85668. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore(FLAC__StreamDecoder *decoder, FLAC__MetadataType type);
  85669. /** Direct the decoder to filter out all APPLICATION metadata blocks of
  85670. * the given \a id.
  85671. *
  85672. * \default By default, only the \c STREAMINFO block is returned via the
  85673. * metadata callback.
  85674. * \param decoder A decoder instance to set.
  85675. * \param id See above.
  85676. * \assert
  85677. * \code decoder != NULL \endcode
  85678. * \code id != NULL \endcode
  85679. * \retval FLAC__bool
  85680. * \c false if the decoder is already initialized, else \c true.
  85681. */
  85682. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4]);
  85683. /** Direct the decoder to filter out all metadata blocks of any type.
  85684. *
  85685. * \default By default, only the \c STREAMINFO block is returned via the
  85686. * metadata callback.
  85687. * \param decoder A decoder instance to set.
  85688. * \assert
  85689. * \code decoder != NULL \endcode
  85690. * \retval FLAC__bool
  85691. * \c false if the decoder is already initialized, else \c true.
  85692. */
  85693. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_all(FLAC__StreamDecoder *decoder);
  85694. /** Get the current decoder state.
  85695. *
  85696. * \param decoder A decoder instance to query.
  85697. * \assert
  85698. * \code decoder != NULL \endcode
  85699. * \retval FLAC__StreamDecoderState
  85700. * The current decoder state.
  85701. */
  85702. FLAC_API FLAC__StreamDecoderState FLAC__stream_decoder_get_state(const FLAC__StreamDecoder *decoder);
  85703. /** Get the current decoder state as a C string.
  85704. *
  85705. * \param decoder A decoder instance to query.
  85706. * \assert
  85707. * \code decoder != NULL \endcode
  85708. * \retval const char *
  85709. * The decoder state as a C string. Do not modify the contents.
  85710. */
  85711. FLAC_API const char *FLAC__stream_decoder_get_resolved_state_string(const FLAC__StreamDecoder *decoder);
  85712. /** Get the "MD5 signature checking" flag.
  85713. * This is the value of the setting, not whether or not the decoder is
  85714. * currently checking the MD5 (remember, it can be turned off automatically
  85715. * by a seek). When the decoder is reset the flag will be restored to the
  85716. * value returned by this function.
  85717. *
  85718. * \param decoder A decoder instance to query.
  85719. * \assert
  85720. * \code decoder != NULL \endcode
  85721. * \retval FLAC__bool
  85722. * See above.
  85723. */
  85724. FLAC_API FLAC__bool FLAC__stream_decoder_get_md5_checking(const FLAC__StreamDecoder *decoder);
  85725. /** Get the total number of samples in the stream being decoded.
  85726. * Will only be valid after decoding has started and will contain the
  85727. * value from the \c STREAMINFO block. A value of \c 0 means "unknown".
  85728. *
  85729. * \param decoder A decoder instance to query.
  85730. * \assert
  85731. * \code decoder != NULL \endcode
  85732. * \retval unsigned
  85733. * See above.
  85734. */
  85735. FLAC_API FLAC__uint64 FLAC__stream_decoder_get_total_samples(const FLAC__StreamDecoder *decoder);
  85736. /** Get the current number of channels in the stream being decoded.
  85737. * Will only be valid after decoding has started and will contain the
  85738. * value from the most recently decoded frame header.
  85739. *
  85740. * \param decoder A decoder instance to query.
  85741. * \assert
  85742. * \code decoder != NULL \endcode
  85743. * \retval unsigned
  85744. * See above.
  85745. */
  85746. FLAC_API unsigned FLAC__stream_decoder_get_channels(const FLAC__StreamDecoder *decoder);
  85747. /** Get the current channel assignment in the stream being decoded.
  85748. * Will only be valid after decoding has started and will contain the
  85749. * value from the most recently decoded frame header.
  85750. *
  85751. * \param decoder A decoder instance to query.
  85752. * \assert
  85753. * \code decoder != NULL \endcode
  85754. * \retval FLAC__ChannelAssignment
  85755. * See above.
  85756. */
  85757. FLAC_API FLAC__ChannelAssignment FLAC__stream_decoder_get_channel_assignment(const FLAC__StreamDecoder *decoder);
  85758. /** Get the current sample resolution in the stream being decoded.
  85759. * Will only be valid after decoding has started and will contain the
  85760. * value from the most recently decoded frame header.
  85761. *
  85762. * \param decoder A decoder instance to query.
  85763. * \assert
  85764. * \code decoder != NULL \endcode
  85765. * \retval unsigned
  85766. * See above.
  85767. */
  85768. FLAC_API unsigned FLAC__stream_decoder_get_bits_per_sample(const FLAC__StreamDecoder *decoder);
  85769. /** Get the current sample rate in Hz of the stream being decoded.
  85770. * Will only be valid after decoding has started and will contain the
  85771. * value from the most recently decoded frame header.
  85772. *
  85773. * \param decoder A decoder instance to query.
  85774. * \assert
  85775. * \code decoder != NULL \endcode
  85776. * \retval unsigned
  85777. * See above.
  85778. */
  85779. FLAC_API unsigned FLAC__stream_decoder_get_sample_rate(const FLAC__StreamDecoder *decoder);
  85780. /** Get the current blocksize of the stream being decoded.
  85781. * Will only be valid after decoding has started and will contain the
  85782. * value from the most recently decoded frame header.
  85783. *
  85784. * \param decoder A decoder instance to query.
  85785. * \assert
  85786. * \code decoder != NULL \endcode
  85787. * \retval unsigned
  85788. * See above.
  85789. */
  85790. FLAC_API unsigned FLAC__stream_decoder_get_blocksize(const FLAC__StreamDecoder *decoder);
  85791. /** Returns the decoder's current read position within the stream.
  85792. * The position is the byte offset from the start of the stream.
  85793. * Bytes before this position have been fully decoded. Note that
  85794. * there may still be undecoded bytes in the decoder's read FIFO.
  85795. * The returned position is correct even after a seek.
  85796. *
  85797. * \warning This function currently only works for native FLAC,
  85798. * not Ogg FLAC streams.
  85799. *
  85800. * \param decoder A decoder instance to query.
  85801. * \param position Address at which to return the desired position.
  85802. * \assert
  85803. * \code decoder != NULL \endcode
  85804. * \code position != NULL \endcode
  85805. * \retval FLAC__bool
  85806. * \c true if successful, \c false if the stream is not native FLAC,
  85807. * or there was an error from the 'tell' callback or it returned
  85808. * \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED.
  85809. */
  85810. FLAC_API FLAC__bool FLAC__stream_decoder_get_decode_position(const FLAC__StreamDecoder *decoder, FLAC__uint64 *position);
  85811. /** Initialize the decoder instance to decode native FLAC streams.
  85812. *
  85813. * This flavor of initialization sets up the decoder to decode from a
  85814. * native FLAC stream. I/O is performed via callbacks to the client.
  85815. * For decoding from a plain file via filename or open FILE*,
  85816. * FLAC__stream_decoder_init_file() and FLAC__stream_decoder_init_FILE()
  85817. * provide a simpler interface.
  85818. *
  85819. * This function should be called after FLAC__stream_decoder_new() and
  85820. * FLAC__stream_decoder_set_*() but before any of the
  85821. * FLAC__stream_decoder_process_*() functions. Will set and return the
  85822. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  85823. * if initialization succeeded.
  85824. *
  85825. * \param decoder An uninitialized decoder instance.
  85826. * \param read_callback See FLAC__StreamDecoderReadCallback. This
  85827. * pointer must not be \c NULL.
  85828. * \param seek_callback See FLAC__StreamDecoderSeekCallback. This
  85829. * pointer may be \c NULL if seeking is not
  85830. * supported. If \a seek_callback is not \c NULL then a
  85831. * \a tell_callback, \a length_callback, and \a eof_callback must also be supplied.
  85832. * Alternatively, a dummy seek callback that just
  85833. * returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  85834. * may also be supplied, all though this is slightly
  85835. * less efficient for the decoder.
  85836. * \param tell_callback See FLAC__StreamDecoderTellCallback. This
  85837. * pointer may be \c NULL if not supported by the client. If
  85838. * \a seek_callback is not \c NULL then a
  85839. * \a tell_callback must also be supplied.
  85840. * Alternatively, a dummy tell callback that just
  85841. * returns \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  85842. * may also be supplied, all though this is slightly
  85843. * less efficient for the decoder.
  85844. * \param length_callback See FLAC__StreamDecoderLengthCallback. This
  85845. * pointer may be \c NULL if not supported by the client. If
  85846. * \a seek_callback is not \c NULL then a
  85847. * \a length_callback must also be supplied.
  85848. * Alternatively, a dummy length callback that just
  85849. * returns \c FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  85850. * may also be supplied, all though this is slightly
  85851. * less efficient for the decoder.
  85852. * \param eof_callback See FLAC__StreamDecoderEofCallback. This
  85853. * pointer may be \c NULL if not supported by the client. If
  85854. * \a seek_callback is not \c NULL then a
  85855. * \a eof_callback must also be supplied.
  85856. * Alternatively, a dummy length callback that just
  85857. * returns \c false
  85858. * may also be supplied, all though this is slightly
  85859. * less efficient for the decoder.
  85860. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  85861. * pointer must not be \c NULL.
  85862. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  85863. * pointer may be \c NULL if the callback is not
  85864. * desired.
  85865. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  85866. * pointer must not be \c NULL.
  85867. * \param client_data This value will be supplied to callbacks in their
  85868. * \a client_data argument.
  85869. * \assert
  85870. * \code decoder != NULL \endcode
  85871. * \retval FLAC__StreamDecoderInitStatus
  85872. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  85873. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  85874. */
  85875. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_stream(
  85876. FLAC__StreamDecoder *decoder,
  85877. FLAC__StreamDecoderReadCallback read_callback,
  85878. FLAC__StreamDecoderSeekCallback seek_callback,
  85879. FLAC__StreamDecoderTellCallback tell_callback,
  85880. FLAC__StreamDecoderLengthCallback length_callback,
  85881. FLAC__StreamDecoderEofCallback eof_callback,
  85882. FLAC__StreamDecoderWriteCallback write_callback,
  85883. FLAC__StreamDecoderMetadataCallback metadata_callback,
  85884. FLAC__StreamDecoderErrorCallback error_callback,
  85885. void *client_data
  85886. );
  85887. /** Initialize the decoder instance to decode Ogg FLAC streams.
  85888. *
  85889. * This flavor of initialization sets up the decoder to decode from a
  85890. * FLAC stream in an Ogg container. I/O is performed via callbacks to the
  85891. * client. For decoding from a plain file via filename or open FILE*,
  85892. * FLAC__stream_decoder_init_ogg_file() and FLAC__stream_decoder_init_ogg_FILE()
  85893. * provide a simpler interface.
  85894. *
  85895. * This function should be called after FLAC__stream_decoder_new() and
  85896. * FLAC__stream_decoder_set_*() but before any of the
  85897. * FLAC__stream_decoder_process_*() functions. Will set and return the
  85898. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  85899. * if initialization succeeded.
  85900. *
  85901. * \note Support for Ogg FLAC in the library is optional. If this
  85902. * library has been built without support for Ogg FLAC, this function
  85903. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  85904. *
  85905. * \param decoder An uninitialized decoder instance.
  85906. * \param read_callback See FLAC__StreamDecoderReadCallback. This
  85907. * pointer must not be \c NULL.
  85908. * \param seek_callback See FLAC__StreamDecoderSeekCallback. This
  85909. * pointer may be \c NULL if seeking is not
  85910. * supported. If \a seek_callback is not \c NULL then a
  85911. * \a tell_callback, \a length_callback, and \a eof_callback must also be supplied.
  85912. * Alternatively, a dummy seek callback that just
  85913. * returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  85914. * may also be supplied, all though this is slightly
  85915. * less efficient for the decoder.
  85916. * \param tell_callback See FLAC__StreamDecoderTellCallback. This
  85917. * pointer may be \c NULL if not supported by the client. If
  85918. * \a seek_callback is not \c NULL then a
  85919. * \a tell_callback must also be supplied.
  85920. * Alternatively, a dummy tell callback that just
  85921. * returns \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  85922. * may also be supplied, all though this is slightly
  85923. * less efficient for the decoder.
  85924. * \param length_callback See FLAC__StreamDecoderLengthCallback. This
  85925. * pointer may be \c NULL if not supported by the client. If
  85926. * \a seek_callback is not \c NULL then a
  85927. * \a length_callback must also be supplied.
  85928. * Alternatively, a dummy length callback that just
  85929. * returns \c FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  85930. * may also be supplied, all though this is slightly
  85931. * less efficient for the decoder.
  85932. * \param eof_callback See FLAC__StreamDecoderEofCallback. This
  85933. * pointer may be \c NULL if not supported by the client. If
  85934. * \a seek_callback is not \c NULL then a
  85935. * \a eof_callback must also be supplied.
  85936. * Alternatively, a dummy length callback that just
  85937. * returns \c false
  85938. * may also be supplied, all though this is slightly
  85939. * less efficient for the decoder.
  85940. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  85941. * pointer must not be \c NULL.
  85942. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  85943. * pointer may be \c NULL if the callback is not
  85944. * desired.
  85945. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  85946. * pointer must not be \c NULL.
  85947. * \param client_data This value will be supplied to callbacks in their
  85948. * \a client_data argument.
  85949. * \assert
  85950. * \code decoder != NULL \endcode
  85951. * \retval FLAC__StreamDecoderInitStatus
  85952. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  85953. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  85954. */
  85955. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_stream(
  85956. FLAC__StreamDecoder *decoder,
  85957. FLAC__StreamDecoderReadCallback read_callback,
  85958. FLAC__StreamDecoderSeekCallback seek_callback,
  85959. FLAC__StreamDecoderTellCallback tell_callback,
  85960. FLAC__StreamDecoderLengthCallback length_callback,
  85961. FLAC__StreamDecoderEofCallback eof_callback,
  85962. FLAC__StreamDecoderWriteCallback write_callback,
  85963. FLAC__StreamDecoderMetadataCallback metadata_callback,
  85964. FLAC__StreamDecoderErrorCallback error_callback,
  85965. void *client_data
  85966. );
  85967. /** Initialize the decoder instance to decode native FLAC files.
  85968. *
  85969. * This flavor of initialization sets up the decoder to decode from a
  85970. * plain native FLAC file. For non-stdio streams, you must use
  85971. * FLAC__stream_decoder_init_stream() and provide callbacks for the I/O.
  85972. *
  85973. * This function should be called after FLAC__stream_decoder_new() and
  85974. * FLAC__stream_decoder_set_*() but before any of the
  85975. * FLAC__stream_decoder_process_*() functions. Will set and return the
  85976. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  85977. * if initialization succeeded.
  85978. *
  85979. * \param decoder An uninitialized decoder instance.
  85980. * \param file An open FLAC file. The file should have been
  85981. * opened with mode \c "rb" and rewound. The file
  85982. * becomes owned by the decoder and should not be
  85983. * manipulated by the client while decoding.
  85984. * Unless \a file is \c stdin, it will be closed
  85985. * when FLAC__stream_decoder_finish() is called.
  85986. * Note however that seeking will not work when
  85987. * decoding from \c stdout since it is not seekable.
  85988. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  85989. * pointer must not be \c NULL.
  85990. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  85991. * pointer may be \c NULL if the callback is not
  85992. * desired.
  85993. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  85994. * pointer must not be \c NULL.
  85995. * \param client_data This value will be supplied to callbacks in their
  85996. * \a client_data argument.
  85997. * \assert
  85998. * \code decoder != NULL \endcode
  85999. * \code file != NULL \endcode
  86000. * \retval FLAC__StreamDecoderInitStatus
  86001. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  86002. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  86003. */
  86004. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_FILE(
  86005. FLAC__StreamDecoder *decoder,
  86006. FILE *file,
  86007. FLAC__StreamDecoderWriteCallback write_callback,
  86008. FLAC__StreamDecoderMetadataCallback metadata_callback,
  86009. FLAC__StreamDecoderErrorCallback error_callback,
  86010. void *client_data
  86011. );
  86012. /** Initialize the decoder instance to decode Ogg FLAC files.
  86013. *
  86014. * This flavor of initialization sets up the decoder to decode from a
  86015. * plain Ogg FLAC file. For non-stdio streams, you must use
  86016. * FLAC__stream_decoder_init_ogg_stream() and provide callbacks for the I/O.
  86017. *
  86018. * This function should be called after FLAC__stream_decoder_new() and
  86019. * FLAC__stream_decoder_set_*() but before any of the
  86020. * FLAC__stream_decoder_process_*() functions. Will set and return the
  86021. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  86022. * if initialization succeeded.
  86023. *
  86024. * \note Support for Ogg FLAC in the library is optional. If this
  86025. * library has been built without support for Ogg FLAC, this function
  86026. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  86027. *
  86028. * \param decoder An uninitialized decoder instance.
  86029. * \param file An open FLAC file. The file should have been
  86030. * opened with mode \c "rb" and rewound. The file
  86031. * becomes owned by the decoder and should not be
  86032. * manipulated by the client while decoding.
  86033. * Unless \a file is \c stdin, it will be closed
  86034. * when FLAC__stream_decoder_finish() is called.
  86035. * Note however that seeking will not work when
  86036. * decoding from \c stdout since it is not seekable.
  86037. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  86038. * pointer must not be \c NULL.
  86039. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  86040. * pointer may be \c NULL if the callback is not
  86041. * desired.
  86042. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  86043. * pointer must not be \c NULL.
  86044. * \param client_data This value will be supplied to callbacks in their
  86045. * \a client_data argument.
  86046. * \assert
  86047. * \code decoder != NULL \endcode
  86048. * \code file != NULL \endcode
  86049. * \retval FLAC__StreamDecoderInitStatus
  86050. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  86051. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  86052. */
  86053. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_FILE(
  86054. FLAC__StreamDecoder *decoder,
  86055. FILE *file,
  86056. FLAC__StreamDecoderWriteCallback write_callback,
  86057. FLAC__StreamDecoderMetadataCallback metadata_callback,
  86058. FLAC__StreamDecoderErrorCallback error_callback,
  86059. void *client_data
  86060. );
  86061. /** Initialize the decoder instance to decode native FLAC files.
  86062. *
  86063. * This flavor of initialization sets up the decoder to decode from a plain
  86064. * native FLAC file. If POSIX fopen() semantics are not sufficient, (for
  86065. * example, with Unicode filenames on Windows), you must use
  86066. * FLAC__stream_decoder_init_FILE(), or FLAC__stream_decoder_init_stream()
  86067. * and provide callbacks for the I/O.
  86068. *
  86069. * This function should be called after FLAC__stream_decoder_new() and
  86070. * FLAC__stream_decoder_set_*() but before any of the
  86071. * FLAC__stream_decoder_process_*() functions. Will set and return the
  86072. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  86073. * if initialization succeeded.
  86074. *
  86075. * \param decoder An uninitialized decoder instance.
  86076. * \param filename The name of the file to decode from. The file will
  86077. * be opened with fopen(). Use \c NULL to decode from
  86078. * \c stdin. Note that \c stdin is not seekable.
  86079. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  86080. * pointer must not be \c NULL.
  86081. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  86082. * pointer may be \c NULL if the callback is not
  86083. * desired.
  86084. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  86085. * pointer must not be \c NULL.
  86086. * \param client_data This value will be supplied to callbacks in their
  86087. * \a client_data argument.
  86088. * \assert
  86089. * \code decoder != NULL \endcode
  86090. * \retval FLAC__StreamDecoderInitStatus
  86091. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  86092. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  86093. */
  86094. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_file(
  86095. FLAC__StreamDecoder *decoder,
  86096. const char *filename,
  86097. FLAC__StreamDecoderWriteCallback write_callback,
  86098. FLAC__StreamDecoderMetadataCallback metadata_callback,
  86099. FLAC__StreamDecoderErrorCallback error_callback,
  86100. void *client_data
  86101. );
  86102. /** Initialize the decoder instance to decode Ogg FLAC files.
  86103. *
  86104. * This flavor of initialization sets up the decoder to decode from a plain
  86105. * Ogg FLAC file. If POSIX fopen() semantics are not sufficient, (for
  86106. * example, with Unicode filenames on Windows), you must use
  86107. * FLAC__stream_decoder_init_ogg_FILE(), or FLAC__stream_decoder_init_ogg_stream()
  86108. * and provide callbacks for the I/O.
  86109. *
  86110. * This function should be called after FLAC__stream_decoder_new() and
  86111. * FLAC__stream_decoder_set_*() but before any of the
  86112. * FLAC__stream_decoder_process_*() functions. Will set and return the
  86113. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  86114. * if initialization succeeded.
  86115. *
  86116. * \note Support for Ogg FLAC in the library is optional. If this
  86117. * library has been built without support for Ogg FLAC, this function
  86118. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  86119. *
  86120. * \param decoder An uninitialized decoder instance.
  86121. * \param filename The name of the file to decode from. The file will
  86122. * be opened with fopen(). Use \c NULL to decode from
  86123. * \c stdin. Note that \c stdin is not seekable.
  86124. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  86125. * pointer must not be \c NULL.
  86126. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  86127. * pointer may be \c NULL if the callback is not
  86128. * desired.
  86129. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  86130. * pointer must not be \c NULL.
  86131. * \param client_data This value will be supplied to callbacks in their
  86132. * \a client_data argument.
  86133. * \assert
  86134. * \code decoder != NULL \endcode
  86135. * \retval FLAC__StreamDecoderInitStatus
  86136. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  86137. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  86138. */
  86139. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_file(
  86140. FLAC__StreamDecoder *decoder,
  86141. const char *filename,
  86142. FLAC__StreamDecoderWriteCallback write_callback,
  86143. FLAC__StreamDecoderMetadataCallback metadata_callback,
  86144. FLAC__StreamDecoderErrorCallback error_callback,
  86145. void *client_data
  86146. );
  86147. /** Finish the decoding process.
  86148. * Flushes the decoding buffer, releases resources, resets the decoder
  86149. * settings to their defaults, and returns the decoder state to
  86150. * FLAC__STREAM_DECODER_UNINITIALIZED.
  86151. *
  86152. * In the event of a prematurely-terminated decode, it is not strictly
  86153. * necessary to call this immediately before FLAC__stream_decoder_delete()
  86154. * but it is good practice to match every FLAC__stream_decoder_init_*()
  86155. * with a FLAC__stream_decoder_finish().
  86156. *
  86157. * \param decoder An uninitialized decoder instance.
  86158. * \assert
  86159. * \code decoder != NULL \endcode
  86160. * \retval FLAC__bool
  86161. * \c false if MD5 checking is on AND a STREAMINFO block was available
  86162. * AND the MD5 signature in the STREAMINFO block was non-zero AND the
  86163. * signature does not match the one computed by the decoder; else
  86164. * \c true.
  86165. */
  86166. FLAC_API FLAC__bool FLAC__stream_decoder_finish(FLAC__StreamDecoder *decoder);
  86167. /** Flush the stream input.
  86168. * The decoder's input buffer will be cleared and the state set to
  86169. * \c FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC. This will also turn
  86170. * off MD5 checking.
  86171. *
  86172. * \param decoder A decoder instance.
  86173. * \assert
  86174. * \code decoder != NULL \endcode
  86175. * \retval FLAC__bool
  86176. * \c true if successful, else \c false if a memory allocation
  86177. * error occurs (in which case the state will be set to
  86178. * \c FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR).
  86179. */
  86180. FLAC_API FLAC__bool FLAC__stream_decoder_flush(FLAC__StreamDecoder *decoder);
  86181. /** Reset the decoding process.
  86182. * The decoder's input buffer will be cleared and the state set to
  86183. * \c FLAC__STREAM_DECODER_SEARCH_FOR_METADATA. This is similar to
  86184. * FLAC__stream_decoder_finish() except that the settings are
  86185. * preserved; there is no need to call FLAC__stream_decoder_init_*()
  86186. * before decoding again. MD5 checking will be restored to its original
  86187. * setting.
  86188. *
  86189. * If the decoder is seekable, or was initialized with
  86190. * FLAC__stream_decoder_init*_FILE() or FLAC__stream_decoder_init*_file(),
  86191. * the decoder will also attempt to seek to the beginning of the file.
  86192. * If this rewind fails, this function will return \c false. It follows
  86193. * that FLAC__stream_decoder_reset() cannot be used when decoding from
  86194. * \c stdin.
  86195. *
  86196. * If the decoder was initialized with FLAC__stream_encoder_init*_stream()
  86197. * and is not seekable (i.e. no seek callback was provided or the seek
  86198. * callback returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED), it
  86199. * is the duty of the client to start feeding data from the beginning of
  86200. * the stream on the next FLAC__stream_decoder_process() or
  86201. * FLAC__stream_decoder_process_interleaved() call.
  86202. *
  86203. * \param decoder A decoder instance.
  86204. * \assert
  86205. * \code decoder != NULL \endcode
  86206. * \retval FLAC__bool
  86207. * \c true if successful, else \c false if a memory allocation occurs
  86208. * (in which case the state will be set to
  86209. * \c FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR) or a seek error
  86210. * occurs (the state will be unchanged).
  86211. */
  86212. FLAC_API FLAC__bool FLAC__stream_decoder_reset(FLAC__StreamDecoder *decoder);
  86213. /** Decode one metadata block or audio frame.
  86214. * This version instructs the decoder to decode a either a single metadata
  86215. * block or a single frame and stop, unless the callbacks return a fatal
  86216. * error or the read callback returns
  86217. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  86218. *
  86219. * As the decoder needs more input it will call the read callback.
  86220. * Depending on what was decoded, the metadata or write callback will be
  86221. * called with the decoded metadata block or audio frame.
  86222. *
  86223. * Unless there is a fatal read error or end of stream, this function
  86224. * will return once one whole frame is decoded. In other words, if the
  86225. * stream is not synchronized or points to a corrupt frame header, the
  86226. * decoder will continue to try and resync until it gets to a valid
  86227. * frame, then decode one frame, then return. If the decoder points to
  86228. * a frame whose frame CRC in the frame footer does not match the
  86229. * computed frame CRC, this function will issue a
  86230. * FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH error to the
  86231. * error callback, and return, having decoded one complete, although
  86232. * corrupt, frame. (Such corrupted frames are sent as silence of the
  86233. * correct length to the write callback.)
  86234. *
  86235. * \param decoder An initialized decoder instance.
  86236. * \assert
  86237. * \code decoder != NULL \endcode
  86238. * \retval FLAC__bool
  86239. * \c false if any fatal read, write, or memory allocation error
  86240. * occurred (meaning decoding must stop), else \c true; for more
  86241. * information about the decoder, check the decoder state with
  86242. * FLAC__stream_decoder_get_state().
  86243. */
  86244. FLAC_API FLAC__bool FLAC__stream_decoder_process_single(FLAC__StreamDecoder *decoder);
  86245. /** Decode until the end of the metadata.
  86246. * This version instructs the decoder to decode from the current position
  86247. * and continue until all the metadata has been read, or until the
  86248. * callbacks return a fatal error or the read callback returns
  86249. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  86250. *
  86251. * As the decoder needs more input it will call the read callback.
  86252. * As each metadata block is decoded, the metadata callback will be called
  86253. * with the decoded metadata.
  86254. *
  86255. * \param decoder An initialized decoder instance.
  86256. * \assert
  86257. * \code decoder != NULL \endcode
  86258. * \retval FLAC__bool
  86259. * \c false if any fatal read, write, or memory allocation error
  86260. * occurred (meaning decoding must stop), else \c true; for more
  86261. * information about the decoder, check the decoder state with
  86262. * FLAC__stream_decoder_get_state().
  86263. */
  86264. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_metadata(FLAC__StreamDecoder *decoder);
  86265. /** Decode until the end of the stream.
  86266. * This version instructs the decoder to decode from the current position
  86267. * and continue until the end of stream (the read callback returns
  86268. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM), or until the
  86269. * callbacks return a fatal error.
  86270. *
  86271. * As the decoder needs more input it will call the read callback.
  86272. * As each metadata block and frame is decoded, the metadata or write
  86273. * callback will be called with the decoded metadata or frame.
  86274. *
  86275. * \param decoder An initialized decoder instance.
  86276. * \assert
  86277. * \code decoder != NULL \endcode
  86278. * \retval FLAC__bool
  86279. * \c false if any fatal read, write, or memory allocation error
  86280. * occurred (meaning decoding must stop), else \c true; for more
  86281. * information about the decoder, check the decoder state with
  86282. * FLAC__stream_decoder_get_state().
  86283. */
  86284. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_stream(FLAC__StreamDecoder *decoder);
  86285. /** Skip one audio frame.
  86286. * This version instructs the decoder to 'skip' a single frame and stop,
  86287. * unless the callbacks return a fatal error or the read callback returns
  86288. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  86289. *
  86290. * The decoding flow is the same as what occurs when
  86291. * FLAC__stream_decoder_process_single() is called to process an audio
  86292. * frame, except that this function does not decode the parsed data into
  86293. * PCM or call the write callback. The integrity of the frame is still
  86294. * checked the same way as in the other process functions.
  86295. *
  86296. * This function will return once one whole frame is skipped, in the
  86297. * same way that FLAC__stream_decoder_process_single() will return once
  86298. * one whole frame is decoded.
  86299. *
  86300. * This function can be used in more quickly determining FLAC frame
  86301. * boundaries when decoding of the actual data is not needed, for
  86302. * example when an application is separating a FLAC stream into frames
  86303. * for editing or storing in a container. To do this, the application
  86304. * can use FLAC__stream_decoder_skip_single_frame() to quickly advance
  86305. * to the next frame, then use
  86306. * FLAC__stream_decoder_get_decode_position() to find the new frame
  86307. * boundary.
  86308. *
  86309. * This function should only be called when the stream has advanced
  86310. * past all the metadata, otherwise it will return \c false.
  86311. *
  86312. * \param decoder An initialized decoder instance not in a metadata
  86313. * state.
  86314. * \assert
  86315. * \code decoder != NULL \endcode
  86316. * \retval FLAC__bool
  86317. * \c false if any fatal read, write, or memory allocation error
  86318. * occurred (meaning decoding must stop), or if the decoder
  86319. * is in the FLAC__STREAM_DECODER_SEARCH_FOR_METADATA or
  86320. * FLAC__STREAM_DECODER_READ_METADATA state, else \c true; for more
  86321. * information about the decoder, check the decoder state with
  86322. * FLAC__stream_decoder_get_state().
  86323. */
  86324. FLAC_API FLAC__bool FLAC__stream_decoder_skip_single_frame(FLAC__StreamDecoder *decoder);
  86325. /** Flush the input and seek to an absolute sample.
  86326. * Decoding will resume at the given sample. Note that because of
  86327. * this, the next write callback may contain a partial block. The
  86328. * client must support seeking the input or this function will fail
  86329. * and return \c false. Furthermore, if the decoder state is
  86330. * \c FLAC__STREAM_DECODER_SEEK_ERROR, then the decoder must be flushed
  86331. * with FLAC__stream_decoder_flush() or reset with
  86332. * FLAC__stream_decoder_reset() before decoding can continue.
  86333. *
  86334. * \param decoder A decoder instance.
  86335. * \param sample The target sample number to seek to.
  86336. * \assert
  86337. * \code decoder != NULL \endcode
  86338. * \retval FLAC__bool
  86339. * \c true if successful, else \c false.
  86340. */
  86341. FLAC_API FLAC__bool FLAC__stream_decoder_seek_absolute(FLAC__StreamDecoder *decoder, FLAC__uint64 sample);
  86342. /* \} */
  86343. #ifdef __cplusplus
  86344. }
  86345. #endif
  86346. #endif
  86347. /********* End of inlined file: stream_decoder.h *********/
  86348. /********* Start of inlined file: stream_encoder.h *********/
  86349. #ifndef FLAC__STREAM_ENCODER_H
  86350. #define FLAC__STREAM_ENCODER_H
  86351. #include <stdio.h> /* for FILE */
  86352. #ifdef __cplusplus
  86353. extern "C" {
  86354. #endif
  86355. /** \file include/FLAC/stream_encoder.h
  86356. *
  86357. * \brief
  86358. * This module contains the functions which implement the stream
  86359. * encoder.
  86360. *
  86361. * See the detailed documentation in the
  86362. * \link flac_stream_encoder stream encoder \endlink module.
  86363. */
  86364. /** \defgroup flac_encoder FLAC/ \*_encoder.h: encoder interfaces
  86365. * \ingroup flac
  86366. *
  86367. * \brief
  86368. * This module describes the encoder layers provided by libFLAC.
  86369. *
  86370. * The stream encoder can be used to encode complete streams either to the
  86371. * client via callbacks, or directly to a file, depending on how it is
  86372. * initialized. When encoding via callbacks, the client provides a write
  86373. * callback which will be called whenever FLAC data is ready to be written.
  86374. * If the client also supplies a seek callback, the encoder will also
  86375. * automatically handle the writing back of metadata discovered while
  86376. * encoding, like stream info, seek points offsets, etc. When encoding to
  86377. * a file, the client needs only supply a filename or open \c FILE* and an
  86378. * optional progress callback for periodic notification of progress; the
  86379. * write and seek callbacks are supplied internally. For more info see the
  86380. * \link flac_stream_encoder stream encoder \endlink module.
  86381. */
  86382. /** \defgroup flac_stream_encoder FLAC/stream_encoder.h: stream encoder interface
  86383. * \ingroup flac_encoder
  86384. *
  86385. * \brief
  86386. * This module contains the functions which implement the stream
  86387. * encoder.
  86388. *
  86389. * The stream encoder can encode to native FLAC, and optionally Ogg FLAC
  86390. * (check FLAC_API_SUPPORTS_OGG_FLAC) streams and files.
  86391. *
  86392. * The basic usage of this encoder is as follows:
  86393. * - The program creates an instance of an encoder using
  86394. * FLAC__stream_encoder_new().
  86395. * - The program overrides the default settings using
  86396. * FLAC__stream_encoder_set_*() functions. At a minimum, the following
  86397. * functions should be called:
  86398. * - FLAC__stream_encoder_set_channels()
  86399. * - FLAC__stream_encoder_set_bits_per_sample()
  86400. * - FLAC__stream_encoder_set_sample_rate()
  86401. * - FLAC__stream_encoder_set_ogg_serial_number() (if encoding to Ogg FLAC)
  86402. * - FLAC__stream_encoder_set_total_samples_estimate() (if known)
  86403. * - If the application wants to control the compression level or set its own
  86404. * metadata, then the following should also be called:
  86405. * - FLAC__stream_encoder_set_compression_level()
  86406. * - FLAC__stream_encoder_set_verify()
  86407. * - FLAC__stream_encoder_set_metadata()
  86408. * - The rest of the set functions should only be called if the client needs
  86409. * exact control over how the audio is compressed; thorough understanding
  86410. * of the FLAC format is necessary to achieve good results.
  86411. * - The program initializes the instance to validate the settings and
  86412. * prepare for encoding using
  86413. * - FLAC__stream_encoder_init_stream() or FLAC__stream_encoder_init_FILE()
  86414. * or FLAC__stream_encoder_init_file() for native FLAC
  86415. * - FLAC__stream_encoder_init_ogg_stream() or FLAC__stream_encoder_init_ogg_FILE()
  86416. * or FLAC__stream_encoder_init_ogg_file() for Ogg FLAC
  86417. * - The program calls FLAC__stream_encoder_process() or
  86418. * FLAC__stream_encoder_process_interleaved() to encode data, which
  86419. * subsequently calls the callbacks when there is encoder data ready
  86420. * to be written.
  86421. * - The program finishes the encoding with FLAC__stream_encoder_finish(),
  86422. * which causes the encoder to encode any data still in its input pipe,
  86423. * update the metadata with the final encoding statistics if output
  86424. * seeking is possible, and finally reset the encoder to the
  86425. * uninitialized state.
  86426. * - The instance may be used again or deleted with
  86427. * FLAC__stream_encoder_delete().
  86428. *
  86429. * In more detail, the stream encoder functions similarly to the
  86430. * \link flac_stream_decoder stream decoder \endlink, but has fewer
  86431. * callbacks and more options. Typically the client will create a new
  86432. * instance by calling FLAC__stream_encoder_new(), then set the necessary
  86433. * parameters with FLAC__stream_encoder_set_*(), and initialize it by
  86434. * calling one of the FLAC__stream_encoder_init_*() functions.
  86435. *
  86436. * Unlike the decoders, the stream encoder has many options that can
  86437. * affect the speed and compression ratio. When setting these parameters
  86438. * you should have some basic knowledge of the format (see the
  86439. * <A HREF="../documentation.html#format">user-level documentation</A>
  86440. * or the <A HREF="../format.html">formal description</A>). The
  86441. * FLAC__stream_encoder_set_*() functions themselves do not validate the
  86442. * values as many are interdependent. The FLAC__stream_encoder_init_*()
  86443. * functions will do this, so make sure to pay attention to the state
  86444. * returned by FLAC__stream_encoder_init_*() to make sure that it is
  86445. * FLAC__STREAM_ENCODER_INIT_STATUS_OK. Any parameters that are not set
  86446. * before FLAC__stream_encoder_init_*() will take on the defaults from
  86447. * the constructor.
  86448. *
  86449. * There are three initialization functions for native FLAC, one for
  86450. * setting up the encoder to encode FLAC data to the client via
  86451. * callbacks, and two for encoding directly to a file.
  86452. *
  86453. * For encoding via callbacks, use FLAC__stream_encoder_init_stream().
  86454. * You must also supply a write callback which will be called anytime
  86455. * there is raw encoded data to write. If the client can seek the output
  86456. * it is best to also supply seek and tell callbacks, as this allows the
  86457. * encoder to go back after encoding is finished to write back
  86458. * information that was collected while encoding, like seek point offsets,
  86459. * frame sizes, etc.
  86460. *
  86461. * For encoding directly to a file, use FLAC__stream_encoder_init_FILE()
  86462. * or FLAC__stream_encoder_init_file(). Then you must only supply a
  86463. * filename or open \c FILE*; the encoder will handle all the callbacks
  86464. * internally. You may also supply a progress callback for periodic
  86465. * notification of the encoding progress.
  86466. *
  86467. * There are three similarly-named init functions for encoding to Ogg
  86468. * FLAC streams. Check \c FLAC_API_SUPPORTS_OGG_FLAC to find out if the
  86469. * library has been built with Ogg support.
  86470. *
  86471. * The call to FLAC__stream_encoder_init_*() currently will also immediately
  86472. * call the write callback several times, once with the \c fLaC signature,
  86473. * and once for each encoded metadata block. Note that for Ogg FLAC
  86474. * encoding you will usually get at least twice the number of callbacks than
  86475. * with native FLAC, one for the Ogg page header and one for the page body.
  86476. *
  86477. * After initializing the instance, the client may feed audio data to the
  86478. * encoder in one of two ways:
  86479. *
  86480. * - Channel separate, through FLAC__stream_encoder_process() - The client
  86481. * will pass an array of pointers to buffers, one for each channel, to
  86482. * the encoder, each of the same length. The samples need not be
  86483. * block-aligned, but each channel should have the same number of samples.
  86484. * - Channel interleaved, through
  86485. * FLAC__stream_encoder_process_interleaved() - The client will pass a single
  86486. * pointer to data that is channel-interleaved (i.e. channel0_sample0,
  86487. * channel1_sample0, ... , channelN_sample0, channel0_sample1, ...).
  86488. * Again, the samples need not be block-aligned but they must be
  86489. * sample-aligned, i.e. the first value should be channel0_sample0 and
  86490. * the last value channelN_sampleM.
  86491. *
  86492. * Note that for either process call, each sample in the buffers should be a
  86493. * signed integer, right-justified to the resolution set by
  86494. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the resolution
  86495. * is 16 bits per sample, the samples should all be in the range [-32768,32767].
  86496. *
  86497. * When the client is finished encoding data, it calls
  86498. * FLAC__stream_encoder_finish(), which causes the encoder to encode any
  86499. * data still in its input pipe, and call the metadata callback with the
  86500. * final encoding statistics. Then the instance may be deleted with
  86501. * FLAC__stream_encoder_delete() or initialized again to encode another
  86502. * stream.
  86503. *
  86504. * For programs that write their own metadata, but that do not know the
  86505. * actual metadata until after encoding, it is advantageous to instruct
  86506. * the encoder to write a PADDING block of the correct size, so that
  86507. * instead of rewriting the whole stream after encoding, the program can
  86508. * just overwrite the PADDING block. If only the maximum size of the
  86509. * metadata is known, the program can write a slightly larger padding
  86510. * block, then split it after encoding.
  86511. *
  86512. * Make sure you understand how lengths are calculated. All FLAC metadata
  86513. * blocks have a 4 byte header which contains the type and length. This
  86514. * length does not include the 4 bytes of the header. See the format page
  86515. * for the specification of metadata blocks and their lengths.
  86516. *
  86517. * \note
  86518. * If you are writing the FLAC data to a file via callbacks, make sure it
  86519. * is open for update (e.g. mode "w+" for stdio streams). This is because
  86520. * after the first encoding pass, the encoder will try to seek back to the
  86521. * beginning of the stream, to the STREAMINFO block, to write some data
  86522. * there. (If using FLAC__stream_encoder_init*_file() or
  86523. * FLAC__stream_encoder_init*_FILE(), the file is managed internally.)
  86524. *
  86525. * \note
  86526. * The "set" functions may only be called when the encoder is in the
  86527. * state FLAC__STREAM_ENCODER_UNINITIALIZED, i.e. after
  86528. * FLAC__stream_encoder_new() or FLAC__stream_encoder_finish(), but
  86529. * before FLAC__stream_encoder_init_*(). If this is the case they will
  86530. * return \c true, otherwise \c false.
  86531. *
  86532. * \note
  86533. * FLAC__stream_encoder_finish() resets all settings to the constructor
  86534. * defaults.
  86535. *
  86536. * \{
  86537. */
  86538. /** State values for a FLAC__StreamEncoder.
  86539. *
  86540. * The encoder's state can be obtained by calling FLAC__stream_encoder_get_state().
  86541. *
  86542. * If the encoder gets into any other state besides \c FLAC__STREAM_ENCODER_OK
  86543. * or \c FLAC__STREAM_ENCODER_UNINITIALIZED, it becomes invalid for encoding and
  86544. * must be deleted with FLAC__stream_encoder_delete().
  86545. */
  86546. typedef enum {
  86547. FLAC__STREAM_ENCODER_OK = 0,
  86548. /**< The encoder is in the normal OK state and samples can be processed. */
  86549. FLAC__STREAM_ENCODER_UNINITIALIZED,
  86550. /**< The encoder is in the uninitialized state; one of the
  86551. * FLAC__stream_encoder_init_*() functions must be called before samples
  86552. * can be processed.
  86553. */
  86554. FLAC__STREAM_ENCODER_OGG_ERROR,
  86555. /**< An error occurred in the underlying Ogg layer. */
  86556. FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR,
  86557. /**< An error occurred in the underlying verify stream decoder;
  86558. * check FLAC__stream_encoder_get_verify_decoder_state().
  86559. */
  86560. FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA,
  86561. /**< The verify decoder detected a mismatch between the original
  86562. * audio signal and the decoded audio signal.
  86563. */
  86564. FLAC__STREAM_ENCODER_CLIENT_ERROR,
  86565. /**< One of the callbacks returned a fatal error. */
  86566. FLAC__STREAM_ENCODER_IO_ERROR,
  86567. /**< An I/O error occurred while opening/reading/writing a file.
  86568. * Check \c errno.
  86569. */
  86570. FLAC__STREAM_ENCODER_FRAMING_ERROR,
  86571. /**< An error occurred while writing the stream; usually, the
  86572. * write_callback returned an error.
  86573. */
  86574. FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR
  86575. /**< Memory allocation failed. */
  86576. } FLAC__StreamEncoderState;
  86577. /** Maps a FLAC__StreamEncoderState to a C string.
  86578. *
  86579. * Using a FLAC__StreamEncoderState as the index to this array
  86580. * will give the string equivalent. The contents should not be modified.
  86581. */
  86582. extern FLAC_API const char * const FLAC__StreamEncoderStateString[];
  86583. /** Possible return values for the FLAC__stream_encoder_init_*() functions.
  86584. */
  86585. typedef enum {
  86586. FLAC__STREAM_ENCODER_INIT_STATUS_OK = 0,
  86587. /**< Initialization was successful. */
  86588. FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR,
  86589. /**< General failure to set up encoder; call FLAC__stream_encoder_get_state() for cause. */
  86590. FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER,
  86591. /**< The library was not compiled with support for the given container
  86592. * format.
  86593. */
  86594. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS,
  86595. /**< A required callback was not supplied. */
  86596. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS,
  86597. /**< The encoder has an invalid setting for number of channels. */
  86598. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE,
  86599. /**< The encoder has an invalid setting for bits-per-sample.
  86600. * FLAC supports 4-32 bps but the reference encoder currently supports
  86601. * only up to 24 bps.
  86602. */
  86603. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE,
  86604. /**< The encoder has an invalid setting for the input sample rate. */
  86605. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE,
  86606. /**< The encoder has an invalid setting for the block size. */
  86607. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER,
  86608. /**< The encoder has an invalid setting for the maximum LPC order. */
  86609. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION,
  86610. /**< The encoder has an invalid setting for the precision of the quantized linear predictor coefficients. */
  86611. FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER,
  86612. /**< The specified block size is less than the maximum LPC order. */
  86613. FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE,
  86614. /**< The encoder is bound to the <A HREF="../format.html#subset">Subset</A> but other settings violate it. */
  86615. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA,
  86616. /**< The metadata input to the encoder is invalid, in one of the following ways:
  86617. * - FLAC__stream_encoder_set_metadata() was called with a null pointer but a block count > 0
  86618. * - One of the metadata blocks contains an undefined type
  86619. * - It contains an illegal CUESHEET as checked by FLAC__format_cuesheet_is_legal()
  86620. * - It contains an illegal SEEKTABLE as checked by FLAC__format_seektable_is_legal()
  86621. * - It contains more than one SEEKTABLE block or more than one VORBIS_COMMENT block
  86622. */
  86623. FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED
  86624. /**< FLAC__stream_encoder_init_*() was called when the encoder was
  86625. * already initialized, usually because
  86626. * FLAC__stream_encoder_finish() was not called.
  86627. */
  86628. } FLAC__StreamEncoderInitStatus;
  86629. /** Maps a FLAC__StreamEncoderInitStatus to a C string.
  86630. *
  86631. * Using a FLAC__StreamEncoderInitStatus as the index to this array
  86632. * will give the string equivalent. The contents should not be modified.
  86633. */
  86634. extern FLAC_API const char * const FLAC__StreamEncoderInitStatusString[];
  86635. /** Return values for the FLAC__StreamEncoder read callback.
  86636. */
  86637. typedef enum {
  86638. FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE,
  86639. /**< The read was OK and decoding can continue. */
  86640. FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM,
  86641. /**< The read was attempted at the end of the stream. */
  86642. FLAC__STREAM_ENCODER_READ_STATUS_ABORT,
  86643. /**< An unrecoverable error occurred. */
  86644. FLAC__STREAM_ENCODER_READ_STATUS_UNSUPPORTED
  86645. /**< Client does not support reading back from the output. */
  86646. } FLAC__StreamEncoderReadStatus;
  86647. /** Maps a FLAC__StreamEncoderReadStatus to a C string.
  86648. *
  86649. * Using a FLAC__StreamEncoderReadStatus as the index to this array
  86650. * will give the string equivalent. The contents should not be modified.
  86651. */
  86652. extern FLAC_API const char * const FLAC__StreamEncoderReadStatusString[];
  86653. /** Return values for the FLAC__StreamEncoder write callback.
  86654. */
  86655. typedef enum {
  86656. FLAC__STREAM_ENCODER_WRITE_STATUS_OK = 0,
  86657. /**< The write was OK and encoding can continue. */
  86658. FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR
  86659. /**< An unrecoverable error occurred. The encoder will return from the process call. */
  86660. } FLAC__StreamEncoderWriteStatus;
  86661. /** Maps a FLAC__StreamEncoderWriteStatus to a C string.
  86662. *
  86663. * Using a FLAC__StreamEncoderWriteStatus as the index to this array
  86664. * will give the string equivalent. The contents should not be modified.
  86665. */
  86666. extern FLAC_API const char * const FLAC__StreamEncoderWriteStatusString[];
  86667. /** Return values for the FLAC__StreamEncoder seek callback.
  86668. */
  86669. typedef enum {
  86670. FLAC__STREAM_ENCODER_SEEK_STATUS_OK,
  86671. /**< The seek was OK and encoding can continue. */
  86672. FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR,
  86673. /**< An unrecoverable error occurred. */
  86674. FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  86675. /**< Client does not support seeking. */
  86676. } FLAC__StreamEncoderSeekStatus;
  86677. /** Maps a FLAC__StreamEncoderSeekStatus to a C string.
  86678. *
  86679. * Using a FLAC__StreamEncoderSeekStatus as the index to this array
  86680. * will give the string equivalent. The contents should not be modified.
  86681. */
  86682. extern FLAC_API const char * const FLAC__StreamEncoderSeekStatusString[];
  86683. /** Return values for the FLAC__StreamEncoder tell callback.
  86684. */
  86685. typedef enum {
  86686. FLAC__STREAM_ENCODER_TELL_STATUS_OK,
  86687. /**< The tell was OK and encoding can continue. */
  86688. FLAC__STREAM_ENCODER_TELL_STATUS_ERROR,
  86689. /**< An unrecoverable error occurred. */
  86690. FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  86691. /**< Client does not support seeking. */
  86692. } FLAC__StreamEncoderTellStatus;
  86693. /** Maps a FLAC__StreamEncoderTellStatus to a C string.
  86694. *
  86695. * Using a FLAC__StreamEncoderTellStatus as the index to this array
  86696. * will give the string equivalent. The contents should not be modified.
  86697. */
  86698. extern FLAC_API const char * const FLAC__StreamEncoderTellStatusString[];
  86699. /***********************************************************************
  86700. *
  86701. * class FLAC__StreamEncoder
  86702. *
  86703. ***********************************************************************/
  86704. struct FLAC__StreamEncoderProtected;
  86705. struct FLAC__StreamEncoderPrivate;
  86706. /** The opaque structure definition for the stream encoder type.
  86707. * See the \link flac_stream_encoder stream encoder module \endlink
  86708. * for a detailed description.
  86709. */
  86710. typedef struct {
  86711. struct FLAC__StreamEncoderProtected *protected_; /* avoid the C++ keyword 'protected' */
  86712. struct FLAC__StreamEncoderPrivate *private_; /* avoid the C++ keyword 'private' */
  86713. } FLAC__StreamEncoder;
  86714. /** Signature for the read callback.
  86715. *
  86716. * A function pointer matching this signature must be passed to
  86717. * FLAC__stream_encoder_init_ogg_stream() if seeking is supported.
  86718. * The supplied function will be called when the encoder needs to read back
  86719. * encoded data. This happens during the metadata callback, when the encoder
  86720. * has to read, modify, and rewrite the metadata (e.g. seekpoints) gathered
  86721. * while encoding. The address of the buffer to be filled is supplied, along
  86722. * with the number of bytes the buffer can hold. The callback may choose to
  86723. * supply less data and modify the byte count but must be careful not to
  86724. * overflow the buffer. The callback then returns a status code chosen from
  86725. * FLAC__StreamEncoderReadStatus.
  86726. *
  86727. * Here is an example of a read callback for stdio streams:
  86728. * \code
  86729. * FLAC__StreamEncoderReadStatus read_cb(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  86730. * {
  86731. * FILE *file = ((MyClientData*)client_data)->file;
  86732. * if(*bytes > 0) {
  86733. * *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, file);
  86734. * if(ferror(file))
  86735. * return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  86736. * else if(*bytes == 0)
  86737. * return FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM;
  86738. * else
  86739. * return FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE;
  86740. * }
  86741. * else
  86742. * return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  86743. * }
  86744. * \endcode
  86745. *
  86746. * \note In general, FLAC__StreamEncoder functions which change the
  86747. * state should not be called on the \a encoder while in the callback.
  86748. *
  86749. * \param encoder The encoder instance calling the callback.
  86750. * \param buffer A pointer to a location for the callee to store
  86751. * data to be encoded.
  86752. * \param bytes A pointer to the size of the buffer. On entry
  86753. * to the callback, it contains the maximum number
  86754. * of bytes that may be stored in \a buffer. The
  86755. * callee must set it to the actual number of bytes
  86756. * stored (0 in case of error or end-of-stream) before
  86757. * returning.
  86758. * \param client_data The callee's client data set through
  86759. * FLAC__stream_encoder_set_client_data().
  86760. * \retval FLAC__StreamEncoderReadStatus
  86761. * The callee's return status.
  86762. */
  86763. typedef FLAC__StreamEncoderReadStatus (*FLAC__StreamEncoderReadCallback)(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  86764. /** Signature for the write callback.
  86765. *
  86766. * A function pointer matching this signature must be passed to
  86767. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  86768. * by the encoder anytime there is raw encoded data ready to write. It may
  86769. * include metadata mixed with encoded audio frames and the data is not
  86770. * guaranteed to be aligned on frame or metadata block boundaries.
  86771. *
  86772. * The only duty of the callback is to write out the \a bytes worth of data
  86773. * in \a buffer to the current position in the output stream. The arguments
  86774. * \a samples and \a current_frame are purely informational. If \a samples
  86775. * is greater than \c 0, then \a current_frame will hold the current frame
  86776. * number that is being written; otherwise it indicates that the write
  86777. * callback is being called to write metadata.
  86778. *
  86779. * \note
  86780. * Unlike when writing to native FLAC, when writing to Ogg FLAC the
  86781. * write callback will be called twice when writing each audio
  86782. * frame; once for the page header, and once for the page body.
  86783. * When writing the page header, the \a samples argument to the
  86784. * write callback will be \c 0.
  86785. *
  86786. * \note In general, FLAC__StreamEncoder functions which change the
  86787. * state should not be called on the \a encoder while in the callback.
  86788. *
  86789. * \param encoder The encoder instance calling the callback.
  86790. * \param buffer An array of encoded data of length \a bytes.
  86791. * \param bytes The byte length of \a buffer.
  86792. * \param samples The number of samples encoded by \a buffer.
  86793. * \c 0 has a special meaning; see above.
  86794. * \param current_frame The number of the current frame being encoded.
  86795. * \param client_data The callee's client data set through
  86796. * FLAC__stream_encoder_init_*().
  86797. * \retval FLAC__StreamEncoderWriteStatus
  86798. * The callee's return status.
  86799. */
  86800. typedef FLAC__StreamEncoderWriteStatus (*FLAC__StreamEncoderWriteCallback)(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data);
  86801. /** Signature for the seek callback.
  86802. *
  86803. * A function pointer matching this signature may be passed to
  86804. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  86805. * when the encoder needs to seek the output stream. The encoder will pass
  86806. * the absolute byte offset to seek to, 0 meaning the beginning of the stream.
  86807. *
  86808. * Here is an example of a seek callback for stdio streams:
  86809. * \code
  86810. * FLAC__StreamEncoderSeekStatus seek_cb(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  86811. * {
  86812. * FILE *file = ((MyClientData*)client_data)->file;
  86813. * if(file == stdin)
  86814. * return FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED;
  86815. * else if(fseeko(file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  86816. * return FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR;
  86817. * else
  86818. * return FLAC__STREAM_ENCODER_SEEK_STATUS_OK;
  86819. * }
  86820. * \endcode
  86821. *
  86822. * \note In general, FLAC__StreamEncoder functions which change the
  86823. * state should not be called on the \a encoder while in the callback.
  86824. *
  86825. * \param encoder The encoder instance calling the callback.
  86826. * \param absolute_byte_offset The offset from the beginning of the stream
  86827. * to seek to.
  86828. * \param client_data The callee's client data set through
  86829. * FLAC__stream_encoder_init_*().
  86830. * \retval FLAC__StreamEncoderSeekStatus
  86831. * The callee's return status.
  86832. */
  86833. typedef FLAC__StreamEncoderSeekStatus (*FLAC__StreamEncoderSeekCallback)(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  86834. /** Signature for the tell callback.
  86835. *
  86836. * A function pointer matching this signature may be passed to
  86837. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  86838. * when the encoder needs to know the current position of the output stream.
  86839. *
  86840. * \warning
  86841. * The callback must return the true current byte offset of the output to
  86842. * which the encoder is writing. If you are buffering the output, make
  86843. * sure and take this into account. If you are writing directly to a
  86844. * FILE* from your write callback, ftell() is sufficient. If you are
  86845. * writing directly to a file descriptor from your write callback, you
  86846. * can use lseek(fd, SEEK_CUR, 0). The encoder may later seek back to
  86847. * these points to rewrite metadata after encoding.
  86848. *
  86849. * Here is an example of a tell callback for stdio streams:
  86850. * \code
  86851. * FLAC__StreamEncoderTellStatus tell_cb(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  86852. * {
  86853. * FILE *file = ((MyClientData*)client_data)->file;
  86854. * off_t pos;
  86855. * if(file == stdin)
  86856. * return FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED;
  86857. * else if((pos = ftello(file)) < 0)
  86858. * return FLAC__STREAM_ENCODER_TELL_STATUS_ERROR;
  86859. * else {
  86860. * *absolute_byte_offset = (FLAC__uint64)pos;
  86861. * return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
  86862. * }
  86863. * }
  86864. * \endcode
  86865. *
  86866. * \note In general, FLAC__StreamEncoder functions which change the
  86867. * state should not be called on the \a encoder while in the callback.
  86868. *
  86869. * \param encoder The encoder instance calling the callback.
  86870. * \param absolute_byte_offset The address at which to store the current
  86871. * position of the output.
  86872. * \param client_data The callee's client data set through
  86873. * FLAC__stream_encoder_init_*().
  86874. * \retval FLAC__StreamEncoderTellStatus
  86875. * The callee's return status.
  86876. */
  86877. typedef FLAC__StreamEncoderTellStatus (*FLAC__StreamEncoderTellCallback)(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  86878. /** Signature for the metadata callback.
  86879. *
  86880. * A function pointer matching this signature may be passed to
  86881. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  86882. * once at the end of encoding with the populated STREAMINFO structure. This
  86883. * is so the client can seek back to the beginning of the file and write the
  86884. * STREAMINFO block with the correct statistics after encoding (like
  86885. * minimum/maximum frame size and total samples).
  86886. *
  86887. * \note In general, FLAC__StreamEncoder functions which change the
  86888. * state should not be called on the \a encoder while in the callback.
  86889. *
  86890. * \param encoder The encoder instance calling the callback.
  86891. * \param metadata The final populated STREAMINFO block.
  86892. * \param client_data The callee's client data set through
  86893. * FLAC__stream_encoder_init_*().
  86894. */
  86895. typedef void (*FLAC__StreamEncoderMetadataCallback)(const FLAC__StreamEncoder *encoder, const FLAC__StreamMetadata *metadata, void *client_data);
  86896. /** Signature for the progress callback.
  86897. *
  86898. * A function pointer matching this signature may be passed to
  86899. * FLAC__stream_encoder_init*_file() or FLAC__stream_encoder_init*_FILE().
  86900. * The supplied function will be called when the encoder has finished
  86901. * writing a frame. The \c total_frames_estimate argument to the
  86902. * callback will be based on the value from
  86903. * FLAC__stream_encoder_set_total_samples_estimate().
  86904. *
  86905. * \note In general, FLAC__StreamEncoder functions which change the
  86906. * state should not be called on the \a encoder while in the callback.
  86907. *
  86908. * \param encoder The encoder instance calling the callback.
  86909. * \param bytes_written Bytes written so far.
  86910. * \param samples_written Samples written so far.
  86911. * \param frames_written Frames written so far.
  86912. * \param total_frames_estimate The estimate of the total number of
  86913. * frames to be written.
  86914. * \param client_data The callee's client data set through
  86915. * FLAC__stream_encoder_init_*().
  86916. */
  86917. typedef void (*FLAC__StreamEncoderProgressCallback)(const FLAC__StreamEncoder *encoder, FLAC__uint64 bytes_written, FLAC__uint64 samples_written, unsigned frames_written, unsigned total_frames_estimate, void *client_data);
  86918. /***********************************************************************
  86919. *
  86920. * Class constructor/destructor
  86921. *
  86922. ***********************************************************************/
  86923. /** Create a new stream encoder instance. The instance is created with
  86924. * default settings; see the individual FLAC__stream_encoder_set_*()
  86925. * functions for each setting's default.
  86926. *
  86927. * \retval FLAC__StreamEncoder*
  86928. * \c NULL if there was an error allocating memory, else the new instance.
  86929. */
  86930. FLAC_API FLAC__StreamEncoder *FLAC__stream_encoder_new(void);
  86931. /** Free an encoder instance. Deletes the object pointed to by \a encoder.
  86932. *
  86933. * \param encoder A pointer to an existing encoder.
  86934. * \assert
  86935. * \code encoder != NULL \endcode
  86936. */
  86937. FLAC_API void FLAC__stream_encoder_delete(FLAC__StreamEncoder *encoder);
  86938. /***********************************************************************
  86939. *
  86940. * Public class method prototypes
  86941. *
  86942. ***********************************************************************/
  86943. /** Set the serial number for the FLAC stream to use in the Ogg container.
  86944. *
  86945. * \note
  86946. * This does not need to be set for native FLAC encoding.
  86947. *
  86948. * \note
  86949. * It is recommended to set a serial number explicitly as the default of '0'
  86950. * may collide with other streams.
  86951. *
  86952. * \default \c 0
  86953. * \param encoder An encoder instance to set.
  86954. * \param serial_number See above.
  86955. * \assert
  86956. * \code encoder != NULL \endcode
  86957. * \retval FLAC__bool
  86958. * \c false if the encoder is already initialized, else \c true.
  86959. */
  86960. FLAC_API FLAC__bool FLAC__stream_encoder_set_ogg_serial_number(FLAC__StreamEncoder *encoder, long serial_number);
  86961. /** Set the "verify" flag. If \c true, the encoder will verify it's own
  86962. * encoded output by feeding it through an internal decoder and comparing
  86963. * the original signal against the decoded signal. If a mismatch occurs,
  86964. * the process call will return \c false. Note that this will slow the
  86965. * encoding process by the extra time required for decoding and comparison.
  86966. *
  86967. * \default \c false
  86968. * \param encoder An encoder instance to set.
  86969. * \param value Flag value (see above).
  86970. * \assert
  86971. * \code encoder != NULL \endcode
  86972. * \retval FLAC__bool
  86973. * \c false if the encoder is already initialized, else \c true.
  86974. */
  86975. FLAC_API FLAC__bool FLAC__stream_encoder_set_verify(FLAC__StreamEncoder *encoder, FLAC__bool value);
  86976. /** Set the <A HREF="../format.html#subset">Subset</A> flag. If \c true,
  86977. * the encoder will comply with the Subset and will check the
  86978. * settings during FLAC__stream_encoder_init_*() to see if all settings
  86979. * comply. If \c false, the settings may take advantage of the full
  86980. * range that the format allows.
  86981. *
  86982. * Make sure you know what it entails before setting this to \c false.
  86983. *
  86984. * \default \c true
  86985. * \param encoder An encoder instance to set.
  86986. * \param value Flag value (see above).
  86987. * \assert
  86988. * \code encoder != NULL \endcode
  86989. * \retval FLAC__bool
  86990. * \c false if the encoder is already initialized, else \c true.
  86991. */
  86992. FLAC_API FLAC__bool FLAC__stream_encoder_set_streamable_subset(FLAC__StreamEncoder *encoder, FLAC__bool value);
  86993. /** Set the number of channels to be encoded.
  86994. *
  86995. * \default \c 2
  86996. * \param encoder An encoder instance to set.
  86997. * \param value See above.
  86998. * \assert
  86999. * \code encoder != NULL \endcode
  87000. * \retval FLAC__bool
  87001. * \c false if the encoder is already initialized, else \c true.
  87002. */
  87003. FLAC_API FLAC__bool FLAC__stream_encoder_set_channels(FLAC__StreamEncoder *encoder, unsigned value);
  87004. /** Set the sample resolution of the input to be encoded.
  87005. *
  87006. * \warning
  87007. * Do not feed the encoder data that is wider than the value you
  87008. * set here or you will generate an invalid stream.
  87009. *
  87010. * \default \c 16
  87011. * \param encoder An encoder instance to set.
  87012. * \param value See above.
  87013. * \assert
  87014. * \code encoder != NULL \endcode
  87015. * \retval FLAC__bool
  87016. * \c false if the encoder is already initialized, else \c true.
  87017. */
  87018. FLAC_API FLAC__bool FLAC__stream_encoder_set_bits_per_sample(FLAC__StreamEncoder *encoder, unsigned value);
  87019. /** Set the sample rate (in Hz) of the input to be encoded.
  87020. *
  87021. * \default \c 44100
  87022. * \param encoder An encoder instance to set.
  87023. * \param value See above.
  87024. * \assert
  87025. * \code encoder != NULL \endcode
  87026. * \retval FLAC__bool
  87027. * \c false if the encoder is already initialized, else \c true.
  87028. */
  87029. FLAC_API FLAC__bool FLAC__stream_encoder_set_sample_rate(FLAC__StreamEncoder *encoder, unsigned value);
  87030. /** Set the compression level
  87031. *
  87032. * The compression level is roughly proportional to the amount of effort
  87033. * the encoder expends to compress the file. A higher level usually
  87034. * means more computation but higher compression. The default level is
  87035. * suitable for most applications.
  87036. *
  87037. * Currently the levels range from \c 0 (fastest, least compression) to
  87038. * \c 8 (slowest, most compression). A value larger than \c 8 will be
  87039. * treated as \c 8.
  87040. *
  87041. * This function automatically calls the following other \c _set_
  87042. * functions with appropriate values, so the client does not need to
  87043. * unless it specifically wants to override them:
  87044. * - FLAC__stream_encoder_set_do_mid_side_stereo()
  87045. * - FLAC__stream_encoder_set_loose_mid_side_stereo()
  87046. * - FLAC__stream_encoder_set_apodization()
  87047. * - FLAC__stream_encoder_set_max_lpc_order()
  87048. * - FLAC__stream_encoder_set_qlp_coeff_precision()
  87049. * - FLAC__stream_encoder_set_do_qlp_coeff_prec_search()
  87050. * - FLAC__stream_encoder_set_do_escape_coding()
  87051. * - FLAC__stream_encoder_set_do_exhaustive_model_search()
  87052. * - FLAC__stream_encoder_set_min_residual_partition_order()
  87053. * - FLAC__stream_encoder_set_max_residual_partition_order()
  87054. * - FLAC__stream_encoder_set_rice_parameter_search_dist()
  87055. *
  87056. * The actual values set for each level are:
  87057. * <table>
  87058. * <tr>
  87059. * <td><b>level</b><td>
  87060. * <td>do mid-side stereo<td>
  87061. * <td>loose mid-side stereo<td>
  87062. * <td>apodization<td>
  87063. * <td>max lpc order<td>
  87064. * <td>qlp coeff precision<td>
  87065. * <td>qlp coeff prec search<td>
  87066. * <td>escape coding<td>
  87067. * <td>exhaustive model search<td>
  87068. * <td>min residual partition order<td>
  87069. * <td>max residual partition order<td>
  87070. * <td>rice parameter search dist<td>
  87071. * </tr>
  87072. * <tr> <td><b>0</b><td> <td>false<td> <td>false<td> <td>tukey(0.5)<td> <td>0<td> <td>0<td> <td>false<td> <td>false<td> <td>false<td> <td>0<td> <td>3<td> <td>0<td> </tr>
  87073. * <tr> <td><b>1</b><td> <td>true<td> <td>true<td> <td>tukey(0.5)<td> <td>0<td> <td>0<td> <td>false<td> <td>false<td> <td>false<td> <td>0<td> <td>3<td> <td>0<td> </tr>
  87074. * <tr> <td><b>2</b><td> <td>true<td> <td>false<td> <td>tukey(0.5)<td> <td>0<td> <td>0<td> <td>false<td> <td>false<td> <td>false<td> <td>0<td> <td>3<td> <td>0<td> </tr>
  87075. * <tr> <td><b>3</b><td> <td>false<td> <td>false<td> <td>tukey(0.5)<td> <td>6<td> <td>0<td> <td>false<td> <td>false<td> <td>false<td> <td>0<td> <td>4<td> <td>0<td> </tr>
  87076. * <tr> <td><b>4</b><td> <td>true<td> <td>true<td> <td>tukey(0.5)<td> <td>8<td> <td>0<td> <td>false<td> <td>false<td> <td>false<td> <td>0<td> <td>4<td> <td>0<td> </tr>
  87077. * <tr> <td><b>5</b><td> <td>true<td> <td>false<td> <td>tukey(0.5)<td> <td>8<td> <td>0<td> <td>false<td> <td>false<td> <td>false<td> <td>0<td> <td>5<td> <td>0<td> </tr>
  87078. * <tr> <td><b>6</b><td> <td>true<td> <td>false<td> <td>tukey(0.5)<td> <td>8<td> <td>0<td> <td>false<td> <td>false<td> <td>false<td> <td>0<td> <td>6<td> <td>0<td> </tr>
  87079. * <tr> <td><b>7</b><td> <td>true<td> <td>false<td> <td>tukey(0.5)<td> <td>8<td> <td>0<td> <td>false<td> <td>false<td> <td>true<td> <td>0<td> <td>6<td> <td>0<td> </tr>
  87080. * <tr> <td><b>8</b><td> <td>true<td> <td>false<td> <td>tukey(0.5)<td> <td>12<td> <td>0<td> <td>false<td> <td>false<td> <td>true<td> <td>0<td> <td>6<td> <td>0<td> </tr>
  87081. * </table>
  87082. *
  87083. * \default \c 5
  87084. * \param encoder An encoder instance to set.
  87085. * \param value See above.
  87086. * \assert
  87087. * \code encoder != NULL \endcode
  87088. * \retval FLAC__bool
  87089. * \c false if the encoder is already initialized, else \c true.
  87090. */
  87091. FLAC_API FLAC__bool FLAC__stream_encoder_set_compression_level(FLAC__StreamEncoder *encoder, unsigned value);
  87092. /** Set the blocksize to use while encoding.
  87093. *
  87094. * The number of samples to use per frame. Use \c 0 to let the encoder
  87095. * estimate a blocksize; this is usually best.
  87096. *
  87097. * \default \c 0
  87098. * \param encoder An encoder instance to set.
  87099. * \param value See above.
  87100. * \assert
  87101. * \code encoder != NULL \endcode
  87102. * \retval FLAC__bool
  87103. * \c false if the encoder is already initialized, else \c true.
  87104. */
  87105. FLAC_API FLAC__bool FLAC__stream_encoder_set_blocksize(FLAC__StreamEncoder *encoder, unsigned value);
  87106. /** Set to \c true to enable mid-side encoding on stereo input. The
  87107. * number of channels must be 2 for this to have any effect. Set to
  87108. * \c false to use only independent channel coding.
  87109. *
  87110. * \default \c false
  87111. * \param encoder An encoder instance to set.
  87112. * \param value Flag value (see above).
  87113. * \assert
  87114. * \code encoder != NULL \endcode
  87115. * \retval FLAC__bool
  87116. * \c false if the encoder is already initialized, else \c true.
  87117. */
  87118. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value);
  87119. /** Set to \c true to enable adaptive switching between mid-side and
  87120. * left-right encoding on stereo input. Set to \c false to use
  87121. * exhaustive searching. Setting this to \c true requires
  87122. * FLAC__stream_encoder_set_do_mid_side_stereo() to also be set to
  87123. * \c true in order to have any effect.
  87124. *
  87125. * \default \c false
  87126. * \param encoder An encoder instance to set.
  87127. * \param value Flag value (see above).
  87128. * \assert
  87129. * \code encoder != NULL \endcode
  87130. * \retval FLAC__bool
  87131. * \c false if the encoder is already initialized, else \c true.
  87132. */
  87133. FLAC_API FLAC__bool FLAC__stream_encoder_set_loose_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value);
  87134. /** Sets the apodization function(s) the encoder will use when windowing
  87135. * audio data for LPC analysis.
  87136. *
  87137. * The \a specification is a plain ASCII string which specifies exactly
  87138. * which functions to use. There may be more than one (up to 32),
  87139. * separated by \c ';' characters. Some functions take one or more
  87140. * comma-separated arguments in parentheses.
  87141. *
  87142. * The available functions are \c bartlett, \c bartlett_hann,
  87143. * \c blackman, \c blackman_harris_4term_92db, \c connes, \c flattop,
  87144. * \c gauss(STDDEV), \c hamming, \c hann, \c kaiser_bessel, \c nuttall,
  87145. * \c rectangle, \c triangle, \c tukey(P), \c welch.
  87146. *
  87147. * For \c gauss(STDDEV), STDDEV specifies the standard deviation
  87148. * (0<STDDEV<=0.5).
  87149. *
  87150. * For \c tukey(P), P specifies the fraction of the window that is
  87151. * tapered (0<=P<=1). P=0 corresponds to \c rectangle and P=1
  87152. * corresponds to \c hann.
  87153. *
  87154. * Example specifications are \c "blackman" or
  87155. * \c "hann;triangle;tukey(0.5);tukey(0.25);tukey(0.125)"
  87156. *
  87157. * Any function that is specified erroneously is silently dropped. Up
  87158. * to 32 functions are kept, the rest are dropped. If the specification
  87159. * is empty the encoder defaults to \c "tukey(0.5)".
  87160. *
  87161. * When more than one function is specified, then for every subframe the
  87162. * encoder will try each of them separately and choose the window that
  87163. * results in the smallest compressed subframe.
  87164. *
  87165. * Note that each function specified causes the encoder to occupy a
  87166. * floating point array in which to store the window.
  87167. *
  87168. * \default \c "tukey(0.5)"
  87169. * \param encoder An encoder instance to set.
  87170. * \param specification See above.
  87171. * \assert
  87172. * \code encoder != NULL \endcode
  87173. * \code specification != NULL \endcode
  87174. * \retval FLAC__bool
  87175. * \c false if the encoder is already initialized, else \c true.
  87176. */
  87177. FLAC_API FLAC__bool FLAC__stream_encoder_set_apodization(FLAC__StreamEncoder *encoder, const char *specification);
  87178. /** Set the maximum LPC order, or \c 0 to use only the fixed predictors.
  87179. *
  87180. * \default \c 0
  87181. * \param encoder An encoder instance to set.
  87182. * \param value See above.
  87183. * \assert
  87184. * \code encoder != NULL \endcode
  87185. * \retval FLAC__bool
  87186. * \c false if the encoder is already initialized, else \c true.
  87187. */
  87188. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_lpc_order(FLAC__StreamEncoder *encoder, unsigned value);
  87189. /** Set the precision, in bits, of the quantized linear predictor
  87190. * coefficients, or \c 0 to let the encoder select it based on the
  87191. * blocksize.
  87192. *
  87193. * \note
  87194. * In the current implementation, qlp_coeff_precision + bits_per_sample must
  87195. * be less than 32.
  87196. *
  87197. * \default \c 0
  87198. * \param encoder An encoder instance to set.
  87199. * \param value See above.
  87200. * \assert
  87201. * \code encoder != NULL \endcode
  87202. * \retval FLAC__bool
  87203. * \c false if the encoder is already initialized, else \c true.
  87204. */
  87205. FLAC_API FLAC__bool FLAC__stream_encoder_set_qlp_coeff_precision(FLAC__StreamEncoder *encoder, unsigned value);
  87206. /** Set to \c false to use only the specified quantized linear predictor
  87207. * coefficient precision, or \c true to search neighboring precision
  87208. * values and use the best one.
  87209. *
  87210. * \default \c false
  87211. * \param encoder An encoder instance to set.
  87212. * \param value See above.
  87213. * \assert
  87214. * \code encoder != NULL \endcode
  87215. * \retval FLAC__bool
  87216. * \c false if the encoder is already initialized, else \c true.
  87217. */
  87218. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_qlp_coeff_prec_search(FLAC__StreamEncoder *encoder, FLAC__bool value);
  87219. /** Deprecated. Setting this value has no effect.
  87220. *
  87221. * \default \c false
  87222. * \param encoder An encoder instance to set.
  87223. * \param value See above.
  87224. * \assert
  87225. * \code encoder != NULL \endcode
  87226. * \retval FLAC__bool
  87227. * \c false if the encoder is already initialized, else \c true.
  87228. */
  87229. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_escape_coding(FLAC__StreamEncoder *encoder, FLAC__bool value);
  87230. /** Set to \c false to let the encoder estimate the best model order
  87231. * based on the residual signal energy, or \c true to force the
  87232. * encoder to evaluate all order models and select the best.
  87233. *
  87234. * \default \c false
  87235. * \param encoder An encoder instance to set.
  87236. * \param value See above.
  87237. * \assert
  87238. * \code encoder != NULL \endcode
  87239. * \retval FLAC__bool
  87240. * \c false if the encoder is already initialized, else \c true.
  87241. */
  87242. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_exhaustive_model_search(FLAC__StreamEncoder *encoder, FLAC__bool value);
  87243. /** Set the minimum partition order to search when coding the residual.
  87244. * This is used in tandem with
  87245. * FLAC__stream_encoder_set_max_residual_partition_order().
  87246. *
  87247. * The partition order determines the context size in the residual.
  87248. * The context size will be approximately <tt>blocksize / (2 ^ order)</tt>.
  87249. *
  87250. * Set both min and max values to \c 0 to force a single context,
  87251. * whose Rice parameter is based on the residual signal variance.
  87252. * Otherwise, set a min and max order, and the encoder will search
  87253. * all orders, using the mean of each context for its Rice parameter,
  87254. * and use the best.
  87255. *
  87256. * \default \c 0
  87257. * \param encoder An encoder instance to set.
  87258. * \param value See above.
  87259. * \assert
  87260. * \code encoder != NULL \endcode
  87261. * \retval FLAC__bool
  87262. * \c false if the encoder is already initialized, else \c true.
  87263. */
  87264. FLAC_API FLAC__bool FLAC__stream_encoder_set_min_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value);
  87265. /** Set the maximum partition order to search when coding the residual.
  87266. * This is used in tandem with
  87267. * FLAC__stream_encoder_set_min_residual_partition_order().
  87268. *
  87269. * The partition order determines the context size in the residual.
  87270. * The context size will be approximately <tt>blocksize / (2 ^ order)</tt>.
  87271. *
  87272. * Set both min and max values to \c 0 to force a single context,
  87273. * whose Rice parameter is based on the residual signal variance.
  87274. * Otherwise, set a min and max order, and the encoder will search
  87275. * all orders, using the mean of each context for its Rice parameter,
  87276. * and use the best.
  87277. *
  87278. * \default \c 0
  87279. * \param encoder An encoder instance to set.
  87280. * \param value See above.
  87281. * \assert
  87282. * \code encoder != NULL \endcode
  87283. * \retval FLAC__bool
  87284. * \c false if the encoder is already initialized, else \c true.
  87285. */
  87286. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value);
  87287. /** Deprecated. Setting this value has no effect.
  87288. *
  87289. * \default \c 0
  87290. * \param encoder An encoder instance to set.
  87291. * \param value See above.
  87292. * \assert
  87293. * \code encoder != NULL \endcode
  87294. * \retval FLAC__bool
  87295. * \c false if the encoder is already initialized, else \c true.
  87296. */
  87297. FLAC_API FLAC__bool FLAC__stream_encoder_set_rice_parameter_search_dist(FLAC__StreamEncoder *encoder, unsigned value);
  87298. /** Set an estimate of the total samples that will be encoded.
  87299. * This is merely an estimate and may be set to \c 0 if unknown.
  87300. * This value will be written to the STREAMINFO block before encoding,
  87301. * and can remove the need for the caller to rewrite the value later
  87302. * if the value is known before encoding.
  87303. *
  87304. * \default \c 0
  87305. * \param encoder An encoder instance to set.
  87306. * \param value See above.
  87307. * \assert
  87308. * \code encoder != NULL \endcode
  87309. * \retval FLAC__bool
  87310. * \c false if the encoder is already initialized, else \c true.
  87311. */
  87312. FLAC_API FLAC__bool FLAC__stream_encoder_set_total_samples_estimate(FLAC__StreamEncoder *encoder, FLAC__uint64 value);
  87313. /** Set the metadata blocks to be emitted to the stream before encoding.
  87314. * A value of \c NULL, \c 0 implies no metadata; otherwise, supply an
  87315. * array of pointers to metadata blocks. The array is non-const since
  87316. * the encoder may need to change the \a is_last flag inside them, and
  87317. * in some cases update seek point offsets. Otherwise, the encoder will
  87318. * not modify or free the blocks. It is up to the caller to free the
  87319. * metadata blocks after encoding finishes.
  87320. *
  87321. * \note
  87322. * The encoder stores only copies of the pointers in the \a metadata array;
  87323. * the metadata blocks themselves must survive at least until after
  87324. * FLAC__stream_encoder_finish() returns. Do not free the blocks until then.
  87325. *
  87326. * \note
  87327. * The STREAMINFO block is always written and no STREAMINFO block may
  87328. * occur in the supplied array.
  87329. *
  87330. * \note
  87331. * By default the encoder does not create a SEEKTABLE. If one is supplied
  87332. * in the \a metadata array, but the client has specified that it does not
  87333. * support seeking, then the SEEKTABLE will be written verbatim. However
  87334. * by itself this is not very useful as the client will not know the stream
  87335. * offsets for the seekpoints ahead of time. In order to get a proper
  87336. * seektable the client must support seeking. See next note.
  87337. *
  87338. * \note
  87339. * SEEKTABLE blocks are handled specially. Since you will not know
  87340. * the values for the seek point stream offsets, you should pass in
  87341. * a SEEKTABLE 'template', that is, a SEEKTABLE object with the
  87342. * required sample numbers (or placeholder points), with \c 0 for the
  87343. * \a frame_samples and \a stream_offset fields for each point. If the
  87344. * client has specified that it supports seeking by providing a seek
  87345. * callback to FLAC__stream_encoder_init_stream() or both seek AND read
  87346. * callback to FLAC__stream_encoder_init_ogg_stream() (or by using
  87347. * FLAC__stream_encoder_init*_file() or FLAC__stream_encoder_init*_FILE()),
  87348. * then while it is encoding the encoder will fill the stream offsets in
  87349. * for you and when encoding is finished, it will seek back and write the
  87350. * real values into the SEEKTABLE block in the stream. There are helper
  87351. * routines for manipulating seektable template blocks; see metadata.h:
  87352. * FLAC__metadata_object_seektable_template_*(). If the client does
  87353. * not support seeking, the SEEKTABLE will have inaccurate offsets which
  87354. * will slow down or remove the ability to seek in the FLAC stream.
  87355. *
  87356. * \note
  87357. * The encoder instance \b will modify the first \c SEEKTABLE block
  87358. * as it transforms the template to a valid seektable while encoding,
  87359. * but it is still up to the caller to free all metadata blocks after
  87360. * encoding.
  87361. *
  87362. * \note
  87363. * A VORBIS_COMMENT block may be supplied. The vendor string in it
  87364. * will be ignored. libFLAC will use it's own vendor string. libFLAC
  87365. * will not modify the passed-in VORBIS_COMMENT's vendor string, it
  87366. * will simply write it's own into the stream. If no VORBIS_COMMENT
  87367. * block is present in the \a metadata array, libFLAC will write an
  87368. * empty one, containing only the vendor string.
  87369. *
  87370. * \note The Ogg FLAC mapping requires that the VORBIS_COMMENT block be
  87371. * the second metadata block of the stream. The encoder already supplies
  87372. * the STREAMINFO block automatically. If \a metadata does not contain a
  87373. * VORBIS_COMMENT block, the encoder will supply that too. Otherwise, if
  87374. * \a metadata does contain a VORBIS_COMMENT block and it is not the
  87375. * first, the init function will reorder \a metadata by moving the
  87376. * VORBIS_COMMENT block to the front; the relative ordering of the other
  87377. * blocks will remain as they were.
  87378. *
  87379. * \note The Ogg FLAC mapping limits the number of metadata blocks per
  87380. * stream to \c 65535. If \a num_blocks exceeds this the function will
  87381. * return \c false.
  87382. *
  87383. * \default \c NULL, 0
  87384. * \param encoder An encoder instance to set.
  87385. * \param metadata See above.
  87386. * \param num_blocks See above.
  87387. * \assert
  87388. * \code encoder != NULL \endcode
  87389. * \retval FLAC__bool
  87390. * \c false if the encoder is already initialized, else \c true.
  87391. * \c false if the encoder is already initialized, or if
  87392. * \a num_blocks > 65535 if encoding to Ogg FLAC, else \c true.
  87393. */
  87394. FLAC_API FLAC__bool FLAC__stream_encoder_set_metadata(FLAC__StreamEncoder *encoder, FLAC__StreamMetadata **metadata, unsigned num_blocks);
  87395. /** Get the current encoder state.
  87396. *
  87397. * \param encoder An encoder instance to query.
  87398. * \assert
  87399. * \code encoder != NULL \endcode
  87400. * \retval FLAC__StreamEncoderState
  87401. * The current encoder state.
  87402. */
  87403. FLAC_API FLAC__StreamEncoderState FLAC__stream_encoder_get_state(const FLAC__StreamEncoder *encoder);
  87404. /** Get the state of the verify stream decoder.
  87405. * Useful when the stream encoder state is
  87406. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR.
  87407. *
  87408. * \param encoder An encoder instance to query.
  87409. * \assert
  87410. * \code encoder != NULL \endcode
  87411. * \retval FLAC__StreamDecoderState
  87412. * The verify stream decoder state.
  87413. */
  87414. FLAC_API FLAC__StreamDecoderState FLAC__stream_encoder_get_verify_decoder_state(const FLAC__StreamEncoder *encoder);
  87415. /** Get the current encoder state as a C string.
  87416. * This version automatically resolves
  87417. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR by getting the
  87418. * verify decoder's state.
  87419. *
  87420. * \param encoder A encoder instance to query.
  87421. * \assert
  87422. * \code encoder != NULL \endcode
  87423. * \retval const char *
  87424. * The encoder state as a C string. Do not modify the contents.
  87425. */
  87426. FLAC_API const char *FLAC__stream_encoder_get_resolved_state_string(const FLAC__StreamEncoder *encoder);
  87427. /** Get relevant values about the nature of a verify decoder error.
  87428. * Useful when the stream encoder state is
  87429. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR. The arguments should
  87430. * be addresses in which the stats will be returned, or NULL if value
  87431. * is not desired.
  87432. *
  87433. * \param encoder An encoder instance to query.
  87434. * \param absolute_sample The absolute sample number of the mismatch.
  87435. * \param frame_number The number of the frame in which the mismatch occurred.
  87436. * \param channel The channel in which the mismatch occurred.
  87437. * \param sample The number of the sample (relative to the frame) in
  87438. * which the mismatch occurred.
  87439. * \param expected The expected value for the sample in question.
  87440. * \param got The actual value returned by the decoder.
  87441. * \assert
  87442. * \code encoder != NULL \endcode
  87443. */
  87444. FLAC_API void FLAC__stream_encoder_get_verify_decoder_error_stats(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_sample, unsigned *frame_number, unsigned *channel, unsigned *sample, FLAC__int32 *expected, FLAC__int32 *got);
  87445. /** Get the "verify" flag.
  87446. *
  87447. * \param encoder An encoder instance to query.
  87448. * \assert
  87449. * \code encoder != NULL \endcode
  87450. * \retval FLAC__bool
  87451. * See FLAC__stream_encoder_set_verify().
  87452. */
  87453. FLAC_API FLAC__bool FLAC__stream_encoder_get_verify(const FLAC__StreamEncoder *encoder);
  87454. /** Get the <A HREF="../format.html#subset>Subset</A> flag.
  87455. *
  87456. * \param encoder An encoder instance to query.
  87457. * \assert
  87458. * \code encoder != NULL \endcode
  87459. * \retval FLAC__bool
  87460. * See FLAC__stream_encoder_set_streamable_subset().
  87461. */
  87462. FLAC_API FLAC__bool FLAC__stream_encoder_get_streamable_subset(const FLAC__StreamEncoder *encoder);
  87463. /** Get the number of input channels being processed.
  87464. *
  87465. * \param encoder An encoder instance to query.
  87466. * \assert
  87467. * \code encoder != NULL \endcode
  87468. * \retval unsigned
  87469. * See FLAC__stream_encoder_set_channels().
  87470. */
  87471. FLAC_API unsigned FLAC__stream_encoder_get_channels(const FLAC__StreamEncoder *encoder);
  87472. /** Get the input sample resolution setting.
  87473. *
  87474. * \param encoder An encoder instance to query.
  87475. * \assert
  87476. * \code encoder != NULL \endcode
  87477. * \retval unsigned
  87478. * See FLAC__stream_encoder_set_bits_per_sample().
  87479. */
  87480. FLAC_API unsigned FLAC__stream_encoder_get_bits_per_sample(const FLAC__StreamEncoder *encoder);
  87481. /** Get the input sample rate setting.
  87482. *
  87483. * \param encoder An encoder instance to query.
  87484. * \assert
  87485. * \code encoder != NULL \endcode
  87486. * \retval unsigned
  87487. * See FLAC__stream_encoder_set_sample_rate().
  87488. */
  87489. FLAC_API unsigned FLAC__stream_encoder_get_sample_rate(const FLAC__StreamEncoder *encoder);
  87490. /** Get the blocksize setting.
  87491. *
  87492. * \param encoder An encoder instance to query.
  87493. * \assert
  87494. * \code encoder != NULL \endcode
  87495. * \retval unsigned
  87496. * See FLAC__stream_encoder_set_blocksize().
  87497. */
  87498. FLAC_API unsigned FLAC__stream_encoder_get_blocksize(const FLAC__StreamEncoder *encoder);
  87499. /** Get the "mid/side stereo coding" flag.
  87500. *
  87501. * \param encoder An encoder instance to query.
  87502. * \assert
  87503. * \code encoder != NULL \endcode
  87504. * \retval FLAC__bool
  87505. * See FLAC__stream_encoder_get_do_mid_side_stereo().
  87506. */
  87507. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_mid_side_stereo(const FLAC__StreamEncoder *encoder);
  87508. /** Get the "adaptive mid/side switching" flag.
  87509. *
  87510. * \param encoder An encoder instance to query.
  87511. * \assert
  87512. * \code encoder != NULL \endcode
  87513. * \retval FLAC__bool
  87514. * See FLAC__stream_encoder_set_loose_mid_side_stereo().
  87515. */
  87516. FLAC_API FLAC__bool FLAC__stream_encoder_get_loose_mid_side_stereo(const FLAC__StreamEncoder *encoder);
  87517. /** Get the maximum LPC order setting.
  87518. *
  87519. * \param encoder An encoder instance to query.
  87520. * \assert
  87521. * \code encoder != NULL \endcode
  87522. * \retval unsigned
  87523. * See FLAC__stream_encoder_set_max_lpc_order().
  87524. */
  87525. FLAC_API unsigned FLAC__stream_encoder_get_max_lpc_order(const FLAC__StreamEncoder *encoder);
  87526. /** Get the quantized linear predictor coefficient precision setting.
  87527. *
  87528. * \param encoder An encoder instance to query.
  87529. * \assert
  87530. * \code encoder != NULL \endcode
  87531. * \retval unsigned
  87532. * See FLAC__stream_encoder_set_qlp_coeff_precision().
  87533. */
  87534. FLAC_API unsigned FLAC__stream_encoder_get_qlp_coeff_precision(const FLAC__StreamEncoder *encoder);
  87535. /** Get the qlp coefficient precision search flag.
  87536. *
  87537. * \param encoder An encoder instance to query.
  87538. * \assert
  87539. * \code encoder != NULL \endcode
  87540. * \retval FLAC__bool
  87541. * See FLAC__stream_encoder_set_do_qlp_coeff_prec_search().
  87542. */
  87543. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_qlp_coeff_prec_search(const FLAC__StreamEncoder *encoder);
  87544. /** Get the "escape coding" flag.
  87545. *
  87546. * \param encoder An encoder instance to query.
  87547. * \assert
  87548. * \code encoder != NULL \endcode
  87549. * \retval FLAC__bool
  87550. * See FLAC__stream_encoder_set_do_escape_coding().
  87551. */
  87552. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_escape_coding(const FLAC__StreamEncoder *encoder);
  87553. /** Get the exhaustive model search flag.
  87554. *
  87555. * \param encoder An encoder instance to query.
  87556. * \assert
  87557. * \code encoder != NULL \endcode
  87558. * \retval FLAC__bool
  87559. * See FLAC__stream_encoder_set_do_exhaustive_model_search().
  87560. */
  87561. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_exhaustive_model_search(const FLAC__StreamEncoder *encoder);
  87562. /** Get the minimum residual partition order setting.
  87563. *
  87564. * \param encoder An encoder instance to query.
  87565. * \assert
  87566. * \code encoder != NULL \endcode
  87567. * \retval unsigned
  87568. * See FLAC__stream_encoder_set_min_residual_partition_order().
  87569. */
  87570. FLAC_API unsigned FLAC__stream_encoder_get_min_residual_partition_order(const FLAC__StreamEncoder *encoder);
  87571. /** Get maximum residual partition order setting.
  87572. *
  87573. * \param encoder An encoder instance to query.
  87574. * \assert
  87575. * \code encoder != NULL \endcode
  87576. * \retval unsigned
  87577. * See FLAC__stream_encoder_set_max_residual_partition_order().
  87578. */
  87579. FLAC_API unsigned FLAC__stream_encoder_get_max_residual_partition_order(const FLAC__StreamEncoder *encoder);
  87580. /** Get the Rice parameter search distance setting.
  87581. *
  87582. * \param encoder An encoder instance to query.
  87583. * \assert
  87584. * \code encoder != NULL \endcode
  87585. * \retval unsigned
  87586. * See FLAC__stream_encoder_set_rice_parameter_search_dist().
  87587. */
  87588. FLAC_API unsigned FLAC__stream_encoder_get_rice_parameter_search_dist(const FLAC__StreamEncoder *encoder);
  87589. /** Get the previously set estimate of the total samples to be encoded.
  87590. * The encoder merely mimics back the value given to
  87591. * FLAC__stream_encoder_set_total_samples_estimate() since it has no
  87592. * other way of knowing how many samples the client will encode.
  87593. *
  87594. * \param encoder An encoder instance to set.
  87595. * \assert
  87596. * \code encoder != NULL \endcode
  87597. * \retval FLAC__uint64
  87598. * See FLAC__stream_encoder_get_total_samples_estimate().
  87599. */
  87600. FLAC_API FLAC__uint64 FLAC__stream_encoder_get_total_samples_estimate(const FLAC__StreamEncoder *encoder);
  87601. /** Initialize the encoder instance to encode native FLAC streams.
  87602. *
  87603. * This flavor of initialization sets up the encoder to encode to a
  87604. * native FLAC stream. I/O is performed via callbacks to the client.
  87605. * For encoding to a plain file via filename or open \c FILE*,
  87606. * FLAC__stream_encoder_init_file() and FLAC__stream_encoder_init_FILE()
  87607. * provide a simpler interface.
  87608. *
  87609. * This function should be called after FLAC__stream_encoder_new() and
  87610. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  87611. * or FLAC__stream_encoder_process_interleaved().
  87612. * initialization succeeded.
  87613. *
  87614. * The call to FLAC__stream_encoder_init_stream() currently will also
  87615. * immediately call the write callback several times, once with the \c fLaC
  87616. * signature, and once for each encoded metadata block.
  87617. *
  87618. * \param encoder An uninitialized encoder instance.
  87619. * \param write_callback See FLAC__StreamEncoderWriteCallback. This
  87620. * pointer must not be \c NULL.
  87621. * \param seek_callback See FLAC__StreamEncoderSeekCallback. This
  87622. * pointer may be \c NULL if seeking is not
  87623. * supported. The encoder uses seeking to go back
  87624. * and write some some stream statistics to the
  87625. * STREAMINFO block; this is recommended but not
  87626. * necessary to create a valid FLAC stream. If
  87627. * \a seek_callback is not \c NULL then a
  87628. * \a tell_callback must also be supplied.
  87629. * Alternatively, a dummy seek callback that just
  87630. * returns \c FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  87631. * may also be supplied, all though this is slightly
  87632. * less efficient for the encoder.
  87633. * \param tell_callback See FLAC__StreamEncoderTellCallback. This
  87634. * pointer may be \c NULL if seeking is not
  87635. * supported. If \a seek_callback is \c NULL then
  87636. * this argument will be ignored. If
  87637. * \a seek_callback is not \c NULL then a
  87638. * \a tell_callback must also be supplied.
  87639. * Alternatively, a dummy tell callback that just
  87640. * returns \c FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  87641. * may also be supplied, all though this is slightly
  87642. * less efficient for the encoder.
  87643. * \param metadata_callback See FLAC__StreamEncoderMetadataCallback. This
  87644. * pointer may be \c NULL if the callback is not
  87645. * desired. If the client provides a seek callback,
  87646. * this function is not necessary as the encoder
  87647. * will automatically seek back and update the
  87648. * STREAMINFO block. It may also be \c NULL if the
  87649. * client does not support seeking, since it will
  87650. * have no way of going back to update the
  87651. * STREAMINFO. However the client can still supply
  87652. * a callback if it would like to know the details
  87653. * from the STREAMINFO.
  87654. * \param client_data This value will be supplied to callbacks in their
  87655. * \a client_data argument.
  87656. * \assert
  87657. * \code encoder != NULL \endcode
  87658. * \retval FLAC__StreamEncoderInitStatus
  87659. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  87660. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  87661. */
  87662. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_stream(FLAC__StreamEncoder *encoder, FLAC__StreamEncoderWriteCallback write_callback, FLAC__StreamEncoderSeekCallback seek_callback, FLAC__StreamEncoderTellCallback tell_callback, FLAC__StreamEncoderMetadataCallback metadata_callback, void *client_data);
  87663. /** Initialize the encoder instance to encode Ogg FLAC streams.
  87664. *
  87665. * This flavor of initialization sets up the encoder to encode to a FLAC
  87666. * stream in an Ogg container. I/O is performed via callbacks to the
  87667. * client. For encoding to a plain file via filename or open \c FILE*,
  87668. * FLAC__stream_encoder_init_ogg_file() and FLAC__stream_encoder_init_ogg_FILE()
  87669. * provide a simpler interface.
  87670. *
  87671. * This function should be called after FLAC__stream_encoder_new() and
  87672. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  87673. * or FLAC__stream_encoder_process_interleaved().
  87674. * initialization succeeded.
  87675. *
  87676. * The call to FLAC__stream_encoder_init_ogg_stream() currently will also
  87677. * immediately call the write callback several times to write the metadata
  87678. * packets.
  87679. *
  87680. * \param encoder An uninitialized encoder instance.
  87681. * \param read_callback See FLAC__StreamEncoderReadCallback. This
  87682. * pointer must not be \c NULL if \a seek_callback
  87683. * is non-NULL since they are both needed to be
  87684. * able to write data back to the Ogg FLAC stream
  87685. * in the post-encode phase.
  87686. * \param write_callback See FLAC__StreamEncoderWriteCallback. This
  87687. * pointer must not be \c NULL.
  87688. * \param seek_callback See FLAC__StreamEncoderSeekCallback. This
  87689. * pointer may be \c NULL if seeking is not
  87690. * supported. The encoder uses seeking to go back
  87691. * and write some some stream statistics to the
  87692. * STREAMINFO block; this is recommended but not
  87693. * necessary to create a valid FLAC stream. If
  87694. * \a seek_callback is not \c NULL then a
  87695. * \a tell_callback must also be supplied.
  87696. * Alternatively, a dummy seek callback that just
  87697. * returns \c FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  87698. * may also be supplied, all though this is slightly
  87699. * less efficient for the encoder.
  87700. * \param tell_callback See FLAC__StreamEncoderTellCallback. This
  87701. * pointer may be \c NULL if seeking is not
  87702. * supported. If \a seek_callback is \c NULL then
  87703. * this argument will be ignored. If
  87704. * \a seek_callback is not \c NULL then a
  87705. * \a tell_callback must also be supplied.
  87706. * Alternatively, a dummy tell callback that just
  87707. * returns \c FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  87708. * may also be supplied, all though this is slightly
  87709. * less efficient for the encoder.
  87710. * \param metadata_callback See FLAC__StreamEncoderMetadataCallback. This
  87711. * pointer may be \c NULL if the callback is not
  87712. * desired. If the client provides a seek callback,
  87713. * this function is not necessary as the encoder
  87714. * will automatically seek back and update the
  87715. * STREAMINFO block. It may also be \c NULL if the
  87716. * client does not support seeking, since it will
  87717. * have no way of going back to update the
  87718. * STREAMINFO. However the client can still supply
  87719. * a callback if it would like to know the details
  87720. * from the STREAMINFO.
  87721. * \param client_data This value will be supplied to callbacks in their
  87722. * \a client_data argument.
  87723. * \assert
  87724. * \code encoder != NULL \endcode
  87725. * \retval FLAC__StreamEncoderInitStatus
  87726. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  87727. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  87728. */
  87729. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_stream(FLAC__StreamEncoder *encoder, FLAC__StreamEncoderReadCallback read_callback, FLAC__StreamEncoderWriteCallback write_callback, FLAC__StreamEncoderSeekCallback seek_callback, FLAC__StreamEncoderTellCallback tell_callback, FLAC__StreamEncoderMetadataCallback metadata_callback, void *client_data);
  87730. /** Initialize the encoder instance to encode native FLAC files.
  87731. *
  87732. * This flavor of initialization sets up the encoder to encode to a
  87733. * plain native FLAC file. For non-stdio streams, you must use
  87734. * FLAC__stream_encoder_init_stream() and provide callbacks for the I/O.
  87735. *
  87736. * This function should be called after FLAC__stream_encoder_new() and
  87737. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  87738. * or FLAC__stream_encoder_process_interleaved().
  87739. * initialization succeeded.
  87740. *
  87741. * \param encoder An uninitialized encoder instance.
  87742. * \param file An open file. The file should have been opened
  87743. * with mode \c "w+b" and rewound. The file
  87744. * becomes owned by the encoder and should not be
  87745. * manipulated by the client while encoding.
  87746. * Unless \a file is \c stdout, it will be closed
  87747. * when FLAC__stream_encoder_finish() is called.
  87748. * Note however that a proper SEEKTABLE cannot be
  87749. * created when encoding to \c stdout since it is
  87750. * not seekable.
  87751. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  87752. * pointer may be \c NULL if the callback is not
  87753. * desired.
  87754. * \param client_data This value will be supplied to callbacks in their
  87755. * \a client_data argument.
  87756. * \assert
  87757. * \code encoder != NULL \endcode
  87758. * \code file != NULL \endcode
  87759. * \retval FLAC__StreamEncoderInitStatus
  87760. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  87761. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  87762. */
  87763. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_FILE(FLAC__StreamEncoder *encoder, FILE *file, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  87764. /** Initialize the encoder instance to encode Ogg FLAC files.
  87765. *
  87766. * This flavor of initialization sets up the encoder to encode to a
  87767. * plain Ogg FLAC file. For non-stdio streams, you must use
  87768. * FLAC__stream_encoder_init_ogg_stream() and provide callbacks for the I/O.
  87769. *
  87770. * This function should be called after FLAC__stream_encoder_new() and
  87771. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  87772. * or FLAC__stream_encoder_process_interleaved().
  87773. * initialization succeeded.
  87774. *
  87775. * \param encoder An uninitialized encoder instance.
  87776. * \param file An open file. The file should have been opened
  87777. * with mode \c "w+b" and rewound. The file
  87778. * becomes owned by the encoder and should not be
  87779. * manipulated by the client while encoding.
  87780. * Unless \a file is \c stdout, it will be closed
  87781. * when FLAC__stream_encoder_finish() is called.
  87782. * Note however that a proper SEEKTABLE cannot be
  87783. * created when encoding to \c stdout since it is
  87784. * not seekable.
  87785. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  87786. * pointer may be \c NULL if the callback is not
  87787. * desired.
  87788. * \param client_data This value will be supplied to callbacks in their
  87789. * \a client_data argument.
  87790. * \assert
  87791. * \code encoder != NULL \endcode
  87792. * \code file != NULL \endcode
  87793. * \retval FLAC__StreamEncoderInitStatus
  87794. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  87795. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  87796. */
  87797. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_FILE(FLAC__StreamEncoder *encoder, FILE *file, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  87798. /** Initialize the encoder instance to encode native FLAC files.
  87799. *
  87800. * This flavor of initialization sets up the encoder to encode to a plain
  87801. * FLAC file. If POSIX fopen() semantics are not sufficient (for example,
  87802. * with Unicode filenames on Windows), you must use
  87803. * FLAC__stream_encoder_init_FILE(), or FLAC__stream_encoder_init_stream()
  87804. * and provide callbacks for the I/O.
  87805. *
  87806. * This function should be called after FLAC__stream_encoder_new() and
  87807. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  87808. * or FLAC__stream_encoder_process_interleaved().
  87809. * initialization succeeded.
  87810. *
  87811. * \param encoder An uninitialized encoder instance.
  87812. * \param filename The name of the file to encode to. The file will
  87813. * be opened with fopen(). Use \c NULL to encode to
  87814. * \c stdout. Note however that a proper SEEKTABLE
  87815. * cannot be created when encoding to \c stdout since
  87816. * it is not seekable.
  87817. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  87818. * pointer may be \c NULL if the callback is not
  87819. * desired.
  87820. * \param client_data This value will be supplied to callbacks in their
  87821. * \a client_data argument.
  87822. * \assert
  87823. * \code encoder != NULL \endcode
  87824. * \retval FLAC__StreamEncoderInitStatus
  87825. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  87826. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  87827. */
  87828. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_file(FLAC__StreamEncoder *encoder, const char *filename, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  87829. /** Initialize the encoder instance to encode Ogg FLAC files.
  87830. *
  87831. * This flavor of initialization sets up the encoder to encode to a plain
  87832. * Ogg FLAC file. If POSIX fopen() semantics are not sufficient (for example,
  87833. * with Unicode filenames on Windows), you must use
  87834. * FLAC__stream_encoder_init_ogg_FILE(), or FLAC__stream_encoder_init_ogg_stream()
  87835. * and provide callbacks for the I/O.
  87836. *
  87837. * This function should be called after FLAC__stream_encoder_new() and
  87838. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  87839. * or FLAC__stream_encoder_process_interleaved().
  87840. * initialization succeeded.
  87841. *
  87842. * \param encoder An uninitialized encoder instance.
  87843. * \param filename The name of the file to encode to. The file will
  87844. * be opened with fopen(). Use \c NULL to encode to
  87845. * \c stdout. Note however that a proper SEEKTABLE
  87846. * cannot be created when encoding to \c stdout since
  87847. * it is not seekable.
  87848. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  87849. * pointer may be \c NULL if the callback is not
  87850. * desired.
  87851. * \param client_data This value will be supplied to callbacks in their
  87852. * \a client_data argument.
  87853. * \assert
  87854. * \code encoder != NULL \endcode
  87855. * \retval FLAC__StreamEncoderInitStatus
  87856. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  87857. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  87858. */
  87859. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_file(FLAC__StreamEncoder *encoder, const char *filename, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  87860. /** Finish the encoding process.
  87861. * Flushes the encoding buffer, releases resources, resets the encoder
  87862. * settings to their defaults, and returns the encoder state to
  87863. * FLAC__STREAM_ENCODER_UNINITIALIZED. Note that this can generate
  87864. * one or more write callbacks before returning, and will generate
  87865. * a metadata callback.
  87866. *
  87867. * Note that in the course of processing the last frame, errors can
  87868. * occur, so the caller should be sure to check the return value to
  87869. * ensure the file was encoded properly.
  87870. *
  87871. * In the event of a prematurely-terminated encode, it is not strictly
  87872. * necessary to call this immediately before FLAC__stream_encoder_delete()
  87873. * but it is good practice to match every FLAC__stream_encoder_init_*()
  87874. * with a FLAC__stream_encoder_finish().
  87875. *
  87876. * \param encoder An uninitialized encoder instance.
  87877. * \assert
  87878. * \code encoder != NULL \endcode
  87879. * \retval FLAC__bool
  87880. * \c false if an error occurred processing the last frame; or if verify
  87881. * mode is set (see FLAC__stream_encoder_set_verify()), there was a
  87882. * verify mismatch; else \c true. If \c false, caller should check the
  87883. * state with FLAC__stream_encoder_get_state() for more information
  87884. * about the error.
  87885. */
  87886. FLAC_API FLAC__bool FLAC__stream_encoder_finish(FLAC__StreamEncoder *encoder);
  87887. /** Submit data for encoding.
  87888. * This version allows you to supply the input data via an array of
  87889. * pointers, each pointer pointing to an array of \a samples samples
  87890. * representing one channel. The samples need not be block-aligned,
  87891. * but each channel should have the same number of samples. Each sample
  87892. * should be a signed integer, right-justified to the resolution set by
  87893. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the
  87894. * resolution is 16 bits per sample, the samples should all be in the
  87895. * range [-32768,32767].
  87896. *
  87897. * For applications where channel order is important, channels must
  87898. * follow the order as described in the
  87899. * <A HREF="../format.html#frame_header">frame header</A>.
  87900. *
  87901. * \param encoder An initialized encoder instance in the OK state.
  87902. * \param buffer An array of pointers to each channel's signal.
  87903. * \param samples The number of samples in one channel.
  87904. * \assert
  87905. * \code encoder != NULL \endcode
  87906. * \code FLAC__stream_encoder_get_state(encoder) == FLAC__STREAM_ENCODER_OK \endcode
  87907. * \retval FLAC__bool
  87908. * \c true if successful, else \c false; in this case, check the
  87909. * encoder state with FLAC__stream_encoder_get_state() to see what
  87910. * went wrong.
  87911. */
  87912. FLAC_API FLAC__bool FLAC__stream_encoder_process(FLAC__StreamEncoder *encoder, const FLAC__int32 * const buffer[], unsigned samples);
  87913. /** Submit data for encoding.
  87914. * This version allows you to supply the input data where the channels
  87915. * are interleaved into a single array (i.e. channel0_sample0,
  87916. * channel1_sample0, ... , channelN_sample0, channel0_sample1, ...).
  87917. * The samples need not be block-aligned but they must be
  87918. * sample-aligned, i.e. the first value should be channel0_sample0
  87919. * and the last value channelN_sampleM. Each sample should be a signed
  87920. * integer, right-justified to the resolution set by
  87921. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the
  87922. * resolution is 16 bits per sample, the samples should all be in the
  87923. * range [-32768,32767].
  87924. *
  87925. * For applications where channel order is important, channels must
  87926. * follow the order as described in the
  87927. * <A HREF="../format.html#frame_header">frame header</A>.
  87928. *
  87929. * \param encoder An initialized encoder instance in the OK state.
  87930. * \param buffer An array of channel-interleaved data (see above).
  87931. * \param samples The number of samples in one channel, the same as for
  87932. * FLAC__stream_encoder_process(). For example, if
  87933. * encoding two channels, \c 1000 \a samples corresponds
  87934. * to a \a buffer of 2000 values.
  87935. * \assert
  87936. * \code encoder != NULL \endcode
  87937. * \code FLAC__stream_encoder_get_state(encoder) == FLAC__STREAM_ENCODER_OK \endcode
  87938. * \retval FLAC__bool
  87939. * \c true if successful, else \c false; in this case, check the
  87940. * encoder state with FLAC__stream_encoder_get_state() to see what
  87941. * went wrong.
  87942. */
  87943. FLAC_API FLAC__bool FLAC__stream_encoder_process_interleaved(FLAC__StreamEncoder *encoder, const FLAC__int32 buffer[], unsigned samples);
  87944. /* \} */
  87945. #ifdef __cplusplus
  87946. }
  87947. #endif
  87948. #endif
  87949. /********* End of inlined file: stream_encoder.h *********/
  87950. #ifdef _MSC_VER
  87951. /* OPT: an MSVC built-in would be better */
  87952. static _inline FLAC__uint32 local_swap32_(FLAC__uint32 x)
  87953. {
  87954. x = ((x<<8)&0xFF00FF00) | ((x>>8)&0x00FF00FF);
  87955. return (x>>16) | (x<<16);
  87956. }
  87957. #endif
  87958. #if defined(_MSC_VER) && defined(_X86_)
  87959. /* OPT: an MSVC built-in would be better */
  87960. static void local_swap32_block_(FLAC__uint32 *start, FLAC__uint32 len)
  87961. {
  87962. __asm {
  87963. mov edx, start
  87964. mov ecx, len
  87965. test ecx, ecx
  87966. loop1:
  87967. jz done1
  87968. mov eax, [edx]
  87969. bswap eax
  87970. mov [edx], eax
  87971. add edx, 4
  87972. dec ecx
  87973. jmp short loop1
  87974. done1:
  87975. }
  87976. }
  87977. #endif
  87978. /** \mainpage
  87979. *
  87980. * \section intro Introduction
  87981. *
  87982. * This is the documentation for the FLAC C and C++ APIs. It is
  87983. * highly interconnected; this introduction should give you a top
  87984. * level idea of the structure and how to find the information you
  87985. * need. As a prerequisite you should have at least a basic
  87986. * knowledge of the FLAC format, documented
  87987. * <A HREF="../format.html">here</A>.
  87988. *
  87989. * \section c_api FLAC C API
  87990. *
  87991. * The FLAC C API is the interface to libFLAC, a set of structures
  87992. * describing the components of FLAC streams, and functions for
  87993. * encoding and decoding streams, as well as manipulating FLAC
  87994. * metadata in files. The public include files will be installed
  87995. * in your include area (for example /usr/include/FLAC/...).
  87996. *
  87997. * By writing a little code and linking against libFLAC, it is
  87998. * relatively easy to add FLAC support to another program. The
  87999. * library is licensed under <A HREF="../license.html">Xiph's BSD license</A>.
  88000. * Complete source code of libFLAC as well as the command-line
  88001. * encoder and plugins is available and is a useful source of
  88002. * examples.
  88003. *
  88004. * Aside from encoders and decoders, libFLAC provides a powerful
  88005. * metadata interface for manipulating metadata in FLAC files. It
  88006. * allows the user to add, delete, and modify FLAC metadata blocks
  88007. * and it can automatically take advantage of PADDING blocks to avoid
  88008. * rewriting the entire FLAC file when changing the size of the
  88009. * metadata.
  88010. *
  88011. * libFLAC usually only requires the standard C library and C math
  88012. * library. In particular, threading is not used so there is no
  88013. * dependency on a thread library. However, libFLAC does not use
  88014. * global variables and should be thread-safe.
  88015. *
  88016. * libFLAC also supports encoding to and decoding from Ogg FLAC.
  88017. * However the metadata editing interfaces currently have limited
  88018. * read-only support for Ogg FLAC files.
  88019. *
  88020. * \section cpp_api FLAC C++ API
  88021. *
  88022. * The FLAC C++ API is a set of classes that encapsulate the
  88023. * structures and functions in libFLAC. They provide slightly more
  88024. * functionality with respect to metadata but are otherwise
  88025. * equivalent. For the most part, they share the same usage as
  88026. * their counterparts in libFLAC, and the FLAC C API documentation
  88027. * can be used as a supplement. The public include files
  88028. * for the C++ API will be installed in your include area (for
  88029. * example /usr/include/FLAC++/...).
  88030. *
  88031. * libFLAC++ is also licensed under
  88032. * <A HREF="../license.html">Xiph's BSD license</A>.
  88033. *
  88034. * \section getting_started Getting Started
  88035. *
  88036. * A good starting point for learning the API is to browse through
  88037. * the <A HREF="modules.html">modules</A>. Modules are logical
  88038. * groupings of related functions or classes, which correspond roughly
  88039. * to header files or sections of header files. Each module includes a
  88040. * detailed description of the general usage of its functions or
  88041. * classes.
  88042. *
  88043. * From there you can go on to look at the documentation of
  88044. * individual functions. You can see different views of the individual
  88045. * functions through the links in top bar across this page.
  88046. *
  88047. * If you prefer a more hands-on approach, you can jump right to some
  88048. * <A HREF="../documentation_example_code.html">example code</A>.
  88049. *
  88050. * \section porting_guide Porting Guide
  88051. *
  88052. * Starting with FLAC 1.1.3 a \link porting Porting Guide \endlink
  88053. * has been introduced which gives detailed instructions on how to
  88054. * port your code to newer versions of FLAC.
  88055. *
  88056. * \section embedded_developers Embedded Developers
  88057. *
  88058. * libFLAC has grown larger over time as more functionality has been
  88059. * included, but much of it may be unnecessary for a particular embedded
  88060. * implementation. Unused parts may be pruned by some simple editing of
  88061. * src/libFLAC/Makefile.am. In general, the decoders, encoders, and
  88062. * metadata interface are all independent from each other.
  88063. *
  88064. * It is easiest to just describe the dependencies:
  88065. *
  88066. * - All modules depend on the \link flac_format Format \endlink module.
  88067. * - The decoders and encoders depend on the bitbuffer.
  88068. * - The decoder is independent of the encoder. The encoder uses the
  88069. * decoder because of the verify feature, but this can be removed if
  88070. * not needed.
  88071. * - Parts of the metadata interface require the stream decoder (but not
  88072. * the encoder).
  88073. * - Ogg support is selectable through the compile time macro
  88074. * \c FLAC__HAS_OGG.
  88075. *
  88076. * For example, if your application only requires the stream decoder, no
  88077. * encoder, and no metadata interface, you can remove the stream encoder
  88078. * and the metadata interface, which will greatly reduce the size of the
  88079. * library.
  88080. *
  88081. * Also, there are several places in the libFLAC code with comments marked
  88082. * with "OPT:" where a #define can be changed to enable code that might be
  88083. * faster on a specific platform. Experimenting with these can yield faster
  88084. * binaries.
  88085. */
  88086. /** \defgroup porting Porting Guide for New Versions
  88087. *
  88088. * This module describes differences in the library interfaces from
  88089. * version to version. It assists in the porting of code that uses
  88090. * the libraries to newer versions of FLAC.
  88091. *
  88092. * One simple facility for making porting easier that has been added
  88093. * in FLAC 1.1.3 is a set of \c #defines in \c export.h of each
  88094. * library's includes (e.g. \c include/FLAC/export.h). The
  88095. * \c #defines mirror the libraries'
  88096. * <A HREF="http://www.gnu.org/software/libtool/manual.html#Libtool-versioning">libtool version numbers</A>,
  88097. * e.g. in libFLAC there are \c FLAC_API_VERSION_CURRENT,
  88098. * \c FLAC_API_VERSION_REVISION, and \c FLAC_API_VERSION_AGE.
  88099. * These can be used to support multiple versions of an API during the
  88100. * transition phase, e.g.
  88101. *
  88102. * \code
  88103. * #if !defined(FLAC_API_VERSION_CURRENT) || FLAC_API_VERSION_CURRENT <= 7
  88104. * legacy code
  88105. * #else
  88106. * new code
  88107. * #endif
  88108. * \endcode
  88109. *
  88110. * The the source will work for multiple versions and the legacy code can
  88111. * easily be removed when the transition is complete.
  88112. *
  88113. * Another available symbol is FLAC_API_SUPPORTS_OGG_FLAC (defined in
  88114. * include/FLAC/export.h), which can be used to determine whether or not
  88115. * the library has been compiled with support for Ogg FLAC. This is
  88116. * simpler than trying to call an Ogg init function and catching the
  88117. * error.
  88118. */
  88119. /** \defgroup porting_1_1_2_to_1_1_3 Porting from FLAC 1.1.2 to 1.1.3
  88120. * \ingroup porting
  88121. *
  88122. * \brief
  88123. * This module describes porting from FLAC 1.1.2 to FLAC 1.1.3.
  88124. *
  88125. * The main change between the APIs in 1.1.2 and 1.1.3 is that they have
  88126. * been simplified. First, libOggFLAC has been merged into libFLAC and
  88127. * libOggFLAC++ has been merged into libFLAC++. Second, both the three
  88128. * decoding layers and three encoding layers have been merged into a
  88129. * single stream decoder and stream encoder. That is, the functionality
  88130. * of FLAC__SeekableStreamDecoder and FLAC__FileDecoder has been merged
  88131. * into FLAC__StreamDecoder, and FLAC__SeekableStreamEncoder and
  88132. * FLAC__FileEncoder into FLAC__StreamEncoder. Only the
  88133. * FLAC__StreamDecoder and FLAC__StreamEncoder remain. What this means
  88134. * is there is now a single API that can be used to encode or decode
  88135. * streams to/from native FLAC or Ogg FLAC and the single API can work
  88136. * on both seekable and non-seekable streams.
  88137. *
  88138. * Instead of creating an encoder or decoder of a certain layer, now the
  88139. * client will always create a FLAC__StreamEncoder or
  88140. * FLAC__StreamDecoder. The old layers are now differentiated by the
  88141. * initialization function. For example, for the decoder,
  88142. * FLAC__stream_decoder_init() has been replaced by
  88143. * FLAC__stream_decoder_init_stream(). This init function takes
  88144. * callbacks for the I/O, and the seeking callbacks are optional. This
  88145. * allows the client to use the same object for seekable and
  88146. * non-seekable streams. For decoding a FLAC file directly, the client
  88147. * can use FLAC__stream_decoder_init_file() and pass just a filename
  88148. * and fewer callbacks; most of the other callbacks are supplied
  88149. * internally. For situations where fopen()ing by filename is not
  88150. * possible (e.g. Unicode filenames on Windows) the client can instead
  88151. * open the file itself and supply the FILE* to
  88152. * FLAC__stream_decoder_init_FILE(). The init functions now returns a
  88153. * FLAC__StreamDecoderInitStatus instead of FLAC__StreamDecoderState.
  88154. * Since the callbacks and client data are now passed to the init
  88155. * function, the FLAC__stream_decoder_set_*_callback() functions and
  88156. * FLAC__stream_decoder_set_client_data() are no longer needed. The
  88157. * rest of the calls to the decoder are the same as before.
  88158. *
  88159. * There are counterpart init functions for Ogg FLAC, e.g.
  88160. * FLAC__stream_decoder_init_ogg_stream(). All the rest of the calls
  88161. * and callbacks are the same as for native FLAC.
  88162. *
  88163. * As an example, in FLAC 1.1.2 a seekable stream decoder would have
  88164. * been set up like so:
  88165. *
  88166. * \code
  88167. * FLAC__SeekableStreamDecoder *decoder = FLAC__seekable_stream_decoder_new();
  88168. * if(decoder == NULL) do_something;
  88169. * FLAC__seekable_stream_decoder_set_md5_checking(decoder, true);
  88170. * [... other settings ...]
  88171. * FLAC__seekable_stream_decoder_set_read_callback(decoder, my_read_callback);
  88172. * FLAC__seekable_stream_decoder_set_seek_callback(decoder, my_seek_callback);
  88173. * FLAC__seekable_stream_decoder_set_tell_callback(decoder, my_tell_callback);
  88174. * FLAC__seekable_stream_decoder_set_length_callback(decoder, my_length_callback);
  88175. * FLAC__seekable_stream_decoder_set_eof_callback(decoder, my_eof_callback);
  88176. * FLAC__seekable_stream_decoder_set_write_callback(decoder, my_write_callback);
  88177. * FLAC__seekable_stream_decoder_set_metadata_callback(decoder, my_metadata_callback);
  88178. * FLAC__seekable_stream_decoder_set_error_callback(decoder, my_error_callback);
  88179. * FLAC__seekable_stream_decoder_set_client_data(decoder, my_client_data);
  88180. * if(FLAC__seekable_stream_decoder_init(decoder) != FLAC__SEEKABLE_STREAM_DECODER_OK) do_something;
  88181. * \endcode
  88182. *
  88183. * In FLAC 1.1.3 it is like this:
  88184. *
  88185. * \code
  88186. * FLAC__StreamDecoder *decoder = FLAC__stream_decoder_new();
  88187. * if(decoder == NULL) do_something;
  88188. * FLAC__stream_decoder_set_md5_checking(decoder, true);
  88189. * [... other settings ...]
  88190. * if(FLAC__stream_decoder_init_stream(
  88191. * decoder,
  88192. * my_read_callback,
  88193. * my_seek_callback, // or NULL
  88194. * my_tell_callback, // or NULL
  88195. * my_length_callback, // or NULL
  88196. * my_eof_callback, // or NULL
  88197. * my_write_callback,
  88198. * my_metadata_callback, // or NULL
  88199. * my_error_callback,
  88200. * my_client_data
  88201. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  88202. * \endcode
  88203. *
  88204. * or you could do;
  88205. *
  88206. * \code
  88207. * [...]
  88208. * FILE *file = fopen("somefile.flac","rb");
  88209. * if(file == NULL) do_somthing;
  88210. * if(FLAC__stream_decoder_init_FILE(
  88211. * decoder,
  88212. * file,
  88213. * my_write_callback,
  88214. * my_metadata_callback, // or NULL
  88215. * my_error_callback,
  88216. * my_client_data
  88217. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  88218. * \endcode
  88219. *
  88220. * or just:
  88221. *
  88222. * \code
  88223. * [...]
  88224. * if(FLAC__stream_decoder_init_file(
  88225. * decoder,
  88226. * "somefile.flac",
  88227. * my_write_callback,
  88228. * my_metadata_callback, // or NULL
  88229. * my_error_callback,
  88230. * my_client_data
  88231. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  88232. * \endcode
  88233. *
  88234. * Another small change to the decoder is in how it handles unparseable
  88235. * streams. Before, when the decoder found an unparseable stream
  88236. * (reserved for when the decoder encounters a stream from a future
  88237. * encoder that it can't parse), it changed the state to
  88238. * \c FLAC__STREAM_DECODER_UNPARSEABLE_STREAM. Now the decoder instead
  88239. * drops sync and calls the error callback with a new error code
  88240. * \c FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM. This is
  88241. * more robust. If your error callback does not discriminate on the the
  88242. * error state, your code does not need to be changed.
  88243. *
  88244. * The encoder now has a new setting:
  88245. * FLAC__stream_encoder_set_apodization(). This is for setting the
  88246. * method used to window the data before LPC analysis. You only need to
  88247. * add a call to this function if the default is not suitable. There
  88248. * are also two new convenience functions that may be useful:
  88249. * FLAC__metadata_object_cuesheet_calculate_cddb_id() and
  88250. * FLAC__metadata_get_cuesheet().
  88251. *
  88252. * The \a bytes parameter to FLAC__StreamDecoderReadCallback,
  88253. * FLAC__StreamEncoderReadCallback, and FLAC__StreamEncoderWriteCallback
  88254. * is now \c size_t instead of \c unsigned.
  88255. */
  88256. /** \defgroup porting_1_1_3_to_1_1_4 Porting from FLAC 1.1.3 to 1.1.4
  88257. * \ingroup porting
  88258. *
  88259. * \brief
  88260. * This module describes porting from FLAC 1.1.3 to FLAC 1.1.4.
  88261. *
  88262. * There were no changes to any of the interfaces from 1.1.3 to 1.1.4.
  88263. * There was a slight change in the implementation of
  88264. * FLAC__stream_encoder_set_metadata(); the function now makes a copy
  88265. * of the \a metadata array of pointers so the client no longer needs
  88266. * to maintain it after the call. The objects themselves that are
  88267. * pointed to by the array are still not copied though and must be
  88268. * maintained until the call to FLAC__stream_encoder_finish().
  88269. */
  88270. /** \defgroup porting_1_1_4_to_1_2_0 Porting from FLAC 1.1.4 to 1.2.0
  88271. * \ingroup porting
  88272. *
  88273. * \brief
  88274. * This module describes porting from FLAC 1.1.4 to FLAC 1.2.0.
  88275. *
  88276. * There were only very minor changes to the interfaces from 1.1.4 to 1.2.0.
  88277. * In libFLAC, \c FLAC__format_sample_rate_is_subset() was added.
  88278. * In libFLAC++, \c FLAC::Decoder::Stream::get_decode_position() was added.
  88279. *
  88280. * Finally, value of the constant \c FLAC__FRAME_HEADER_RESERVED_LEN
  88281. * has changed to reflect the conversion of one of the reserved bits
  88282. * into active use. It used to be \c 2 and now is \c 1. However the
  88283. * FLAC frame header length has not changed, so to skip the proper
  88284. * number of bits, use \c FLAC__FRAME_HEADER_RESERVED_LEN +
  88285. * \c FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN
  88286. */
  88287. /** \defgroup flac FLAC C API
  88288. *
  88289. * The FLAC C API is the interface to libFLAC, a set of structures
  88290. * describing the components of FLAC streams, and functions for
  88291. * encoding and decoding streams, as well as manipulating FLAC
  88292. * metadata in files.
  88293. *
  88294. * You should start with the format components as all other modules
  88295. * are dependent on it.
  88296. */
  88297. #endif
  88298. /********* End of inlined file: all.h *********/
  88299. /********* Start of inlined file: bitmath.c *********/
  88300. /********* Start of inlined file: juce_FlacHeader.h *********/
  88301. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  88302. // tasks..
  88303. #define VERSION "1.2.1"
  88304. #define FLAC__NO_DLL 1
  88305. #ifdef _MSC_VER
  88306. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  88307. #endif
  88308. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  88309. #define FLAC__SYS_DARWIN 1
  88310. #endif
  88311. /********* End of inlined file: juce_FlacHeader.h *********/
  88312. #if JUCE_USE_FLAC
  88313. #if HAVE_CONFIG_H
  88314. # include <config.h>
  88315. #endif
  88316. /********* Start of inlined file: bitmath.h *********/
  88317. #ifndef FLAC__PRIVATE__BITMATH_H
  88318. #define FLAC__PRIVATE__BITMATH_H
  88319. unsigned FLAC__bitmath_ilog2(FLAC__uint32 v);
  88320. unsigned FLAC__bitmath_ilog2_wide(FLAC__uint64 v);
  88321. unsigned FLAC__bitmath_silog2(int v);
  88322. unsigned FLAC__bitmath_silog2_wide(FLAC__int64 v);
  88323. #endif
  88324. /********* End of inlined file: bitmath.h *********/
  88325. /* An example of what FLAC__bitmath_ilog2() computes:
  88326. *
  88327. * ilog2( 0) = assertion failure
  88328. * ilog2( 1) = 0
  88329. * ilog2( 2) = 1
  88330. * ilog2( 3) = 1
  88331. * ilog2( 4) = 2
  88332. * ilog2( 5) = 2
  88333. * ilog2( 6) = 2
  88334. * ilog2( 7) = 2
  88335. * ilog2( 8) = 3
  88336. * ilog2( 9) = 3
  88337. * ilog2(10) = 3
  88338. * ilog2(11) = 3
  88339. * ilog2(12) = 3
  88340. * ilog2(13) = 3
  88341. * ilog2(14) = 3
  88342. * ilog2(15) = 3
  88343. * ilog2(16) = 4
  88344. * ilog2(17) = 4
  88345. * ilog2(18) = 4
  88346. */
  88347. unsigned FLAC__bitmath_ilog2(FLAC__uint32 v)
  88348. {
  88349. unsigned l = 0;
  88350. FLAC__ASSERT(v > 0);
  88351. while(v >>= 1)
  88352. l++;
  88353. return l;
  88354. }
  88355. unsigned FLAC__bitmath_ilog2_wide(FLAC__uint64 v)
  88356. {
  88357. unsigned l = 0;
  88358. FLAC__ASSERT(v > 0);
  88359. while(v >>= 1)
  88360. l++;
  88361. return l;
  88362. }
  88363. /* An example of what FLAC__bitmath_silog2() computes:
  88364. *
  88365. * silog2(-10) = 5
  88366. * silog2(- 9) = 5
  88367. * silog2(- 8) = 4
  88368. * silog2(- 7) = 4
  88369. * silog2(- 6) = 4
  88370. * silog2(- 5) = 4
  88371. * silog2(- 4) = 3
  88372. * silog2(- 3) = 3
  88373. * silog2(- 2) = 2
  88374. * silog2(- 1) = 2
  88375. * silog2( 0) = 0
  88376. * silog2( 1) = 2
  88377. * silog2( 2) = 3
  88378. * silog2( 3) = 3
  88379. * silog2( 4) = 4
  88380. * silog2( 5) = 4
  88381. * silog2( 6) = 4
  88382. * silog2( 7) = 4
  88383. * silog2( 8) = 5
  88384. * silog2( 9) = 5
  88385. * silog2( 10) = 5
  88386. */
  88387. unsigned FLAC__bitmath_silog2(int v)
  88388. {
  88389. while(1) {
  88390. if(v == 0) {
  88391. return 0;
  88392. }
  88393. else if(v > 0) {
  88394. unsigned l = 0;
  88395. while(v) {
  88396. l++;
  88397. v >>= 1;
  88398. }
  88399. return l+1;
  88400. }
  88401. else if(v == -1) {
  88402. return 2;
  88403. }
  88404. else {
  88405. v++;
  88406. v = -v;
  88407. }
  88408. }
  88409. }
  88410. unsigned FLAC__bitmath_silog2_wide(FLAC__int64 v)
  88411. {
  88412. while(1) {
  88413. if(v == 0) {
  88414. return 0;
  88415. }
  88416. else if(v > 0) {
  88417. unsigned l = 0;
  88418. while(v) {
  88419. l++;
  88420. v >>= 1;
  88421. }
  88422. return l+1;
  88423. }
  88424. else if(v == -1) {
  88425. return 2;
  88426. }
  88427. else {
  88428. v++;
  88429. v = -v;
  88430. }
  88431. }
  88432. }
  88433. #endif
  88434. /********* End of inlined file: bitmath.c *********/
  88435. /********* Start of inlined file: bitreader.c *********/
  88436. /********* Start of inlined file: juce_FlacHeader.h *********/
  88437. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  88438. // tasks..
  88439. #define VERSION "1.2.1"
  88440. #define FLAC__NO_DLL 1
  88441. #ifdef _MSC_VER
  88442. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  88443. #endif
  88444. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  88445. #define FLAC__SYS_DARWIN 1
  88446. #endif
  88447. /********* End of inlined file: juce_FlacHeader.h *********/
  88448. #if JUCE_USE_FLAC
  88449. #if HAVE_CONFIG_H
  88450. # include <config.h>
  88451. #endif
  88452. #include <stdlib.h> /* for malloc() */
  88453. #include <string.h> /* for memcpy(), memset() */
  88454. #ifdef _MSC_VER
  88455. #include <winsock.h> /* for ntohl() */
  88456. #elif defined FLAC__SYS_DARWIN
  88457. #include <machine/endian.h> /* for ntohl() */
  88458. #elif defined __MINGW32__
  88459. #include <winsock.h> /* for ntohl() */
  88460. #else
  88461. #include <netinet/in.h> /* for ntohl() */
  88462. #endif
  88463. /********* Start of inlined file: bitreader.h *********/
  88464. #ifndef FLAC__PRIVATE__BITREADER_H
  88465. #define FLAC__PRIVATE__BITREADER_H
  88466. #include <stdio.h> /* for FILE */
  88467. /********* Start of inlined file: cpu.h *********/
  88468. #ifndef FLAC__PRIVATE__CPU_H
  88469. #define FLAC__PRIVATE__CPU_H
  88470. #ifdef HAVE_CONFIG_H
  88471. #include <config.h>
  88472. #endif
  88473. typedef enum {
  88474. FLAC__CPUINFO_TYPE_IA32,
  88475. FLAC__CPUINFO_TYPE_PPC,
  88476. FLAC__CPUINFO_TYPE_UNKNOWN
  88477. } FLAC__CPUInfo_Type;
  88478. typedef struct {
  88479. FLAC__bool cpuid;
  88480. FLAC__bool bswap;
  88481. FLAC__bool cmov;
  88482. FLAC__bool mmx;
  88483. FLAC__bool fxsr;
  88484. FLAC__bool sse;
  88485. FLAC__bool sse2;
  88486. FLAC__bool sse3;
  88487. FLAC__bool ssse3;
  88488. FLAC__bool _3dnow;
  88489. FLAC__bool ext3dnow;
  88490. FLAC__bool extmmx;
  88491. } FLAC__CPUInfo_IA32;
  88492. typedef struct {
  88493. FLAC__bool altivec;
  88494. FLAC__bool ppc64;
  88495. } FLAC__CPUInfo_PPC;
  88496. typedef struct {
  88497. FLAC__bool use_asm;
  88498. FLAC__CPUInfo_Type type;
  88499. union {
  88500. FLAC__CPUInfo_IA32 ia32;
  88501. FLAC__CPUInfo_PPC ppc;
  88502. } data;
  88503. } FLAC__CPUInfo;
  88504. void FLAC__cpu_info(FLAC__CPUInfo *info);
  88505. #ifndef FLAC__NO_ASM
  88506. #ifdef FLAC__CPU_IA32
  88507. #ifdef FLAC__HAS_NASM
  88508. FLAC__uint32 FLAC__cpu_have_cpuid_asm_ia32(void);
  88509. void FLAC__cpu_info_asm_ia32(FLAC__uint32 *flags_edx, FLAC__uint32 *flags_ecx);
  88510. FLAC__uint32 FLAC__cpu_info_extended_amd_asm_ia32(void);
  88511. #endif
  88512. #endif
  88513. #endif
  88514. #endif
  88515. /********* End of inlined file: cpu.h *********/
  88516. /*
  88517. * opaque structure definition
  88518. */
  88519. struct FLAC__BitReader;
  88520. typedef struct FLAC__BitReader FLAC__BitReader;
  88521. typedef FLAC__bool (*FLAC__BitReaderReadCallback)(FLAC__byte buffer[], size_t *bytes, void *client_data);
  88522. /*
  88523. * construction, deletion, initialization, etc functions
  88524. */
  88525. FLAC__BitReader *FLAC__bitreader_new(void);
  88526. void FLAC__bitreader_delete(FLAC__BitReader *br);
  88527. FLAC__bool FLAC__bitreader_init(FLAC__BitReader *br, FLAC__CPUInfo cpu, FLAC__BitReaderReadCallback rcb, void *cd);
  88528. void FLAC__bitreader_free(FLAC__BitReader *br); /* does not 'free(br)' */
  88529. FLAC__bool FLAC__bitreader_clear(FLAC__BitReader *br);
  88530. void FLAC__bitreader_dump(const FLAC__BitReader *br, FILE *out);
  88531. /*
  88532. * CRC functions
  88533. */
  88534. void FLAC__bitreader_reset_read_crc16(FLAC__BitReader *br, FLAC__uint16 seed);
  88535. FLAC__uint16 FLAC__bitreader_get_read_crc16(FLAC__BitReader *br);
  88536. /*
  88537. * info functions
  88538. */
  88539. FLAC__bool FLAC__bitreader_is_consumed_byte_aligned(const FLAC__BitReader *br);
  88540. unsigned FLAC__bitreader_bits_left_for_byte_alignment(const FLAC__BitReader *br);
  88541. unsigned FLAC__bitreader_get_input_bits_unconsumed(const FLAC__BitReader *br);
  88542. /*
  88543. * read functions
  88544. */
  88545. FLAC__bool FLAC__bitreader_read_raw_uint32(FLAC__BitReader *br, FLAC__uint32 *val, unsigned bits);
  88546. FLAC__bool FLAC__bitreader_read_raw_int32(FLAC__BitReader *br, FLAC__int32 *val, unsigned bits);
  88547. FLAC__bool FLAC__bitreader_read_raw_uint64(FLAC__BitReader *br, FLAC__uint64 *val, unsigned bits);
  88548. FLAC__bool FLAC__bitreader_read_uint32_little_endian(FLAC__BitReader *br, FLAC__uint32 *val); /*only for bits=32*/
  88549. FLAC__bool FLAC__bitreader_skip_bits_no_crc(FLAC__BitReader *br, unsigned bits); /* WATCHOUT: does not CRC the skipped data! */ /*@@@@ add to unit tests */
  88550. FLAC__bool FLAC__bitreader_skip_byte_block_aligned_no_crc(FLAC__BitReader *br, unsigned nvals); /* WATCHOUT: does not CRC the read data! */
  88551. FLAC__bool FLAC__bitreader_read_byte_block_aligned_no_crc(FLAC__BitReader *br, FLAC__byte *val, unsigned nvals); /* WATCHOUT: does not CRC the read data! */
  88552. FLAC__bool FLAC__bitreader_read_unary_unsigned(FLAC__BitReader *br, unsigned *val);
  88553. FLAC__bool FLAC__bitreader_read_rice_signed(FLAC__BitReader *br, int *val, unsigned parameter);
  88554. FLAC__bool FLAC__bitreader_read_rice_signed_block(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter);
  88555. #ifndef FLAC__NO_ASM
  88556. # ifdef FLAC__CPU_IA32
  88557. # ifdef FLAC__HAS_NASM
  88558. FLAC__bool FLAC__bitreader_read_rice_signed_block_asm_ia32_bswap(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter);
  88559. # endif
  88560. # endif
  88561. #endif
  88562. #if 0 /* UNUSED */
  88563. FLAC__bool FLAC__bitreader_read_golomb_signed(FLAC__BitReader *br, int *val, unsigned parameter);
  88564. FLAC__bool FLAC__bitreader_read_golomb_unsigned(FLAC__BitReader *br, unsigned *val, unsigned parameter);
  88565. #endif
  88566. FLAC__bool FLAC__bitreader_read_utf8_uint32(FLAC__BitReader *br, FLAC__uint32 *val, FLAC__byte *raw, unsigned *rawlen);
  88567. FLAC__bool FLAC__bitreader_read_utf8_uint64(FLAC__BitReader *br, FLAC__uint64 *val, FLAC__byte *raw, unsigned *rawlen);
  88568. FLAC__bool bitreader_read_from_client_(FLAC__BitReader *br);
  88569. #endif
  88570. /********* End of inlined file: bitreader.h *********/
  88571. /********* Start of inlined file: crc.h *********/
  88572. #ifndef FLAC__PRIVATE__CRC_H
  88573. #define FLAC__PRIVATE__CRC_H
  88574. /* 8 bit CRC generator, MSB shifted first
  88575. ** polynomial = x^8 + x^2 + x^1 + x^0
  88576. ** init = 0
  88577. */
  88578. extern FLAC__byte const FLAC__crc8_table[256];
  88579. #define FLAC__CRC8_UPDATE(data, crc) (crc) = FLAC__crc8_table[(crc) ^ (data)];
  88580. void FLAC__crc8_update(const FLAC__byte data, FLAC__uint8 *crc);
  88581. void FLAC__crc8_update_block(const FLAC__byte *data, unsigned len, FLAC__uint8 *crc);
  88582. FLAC__uint8 FLAC__crc8(const FLAC__byte *data, unsigned len);
  88583. /* 16 bit CRC generator, MSB shifted first
  88584. ** polynomial = x^16 + x^15 + x^2 + x^0
  88585. ** init = 0
  88586. */
  88587. extern unsigned FLAC__crc16_table[256];
  88588. #define FLAC__CRC16_UPDATE(data, crc) (((((crc)<<8) & 0xffff) ^ FLAC__crc16_table[((crc)>>8) ^ (data)]))
  88589. /* this alternate may be faster on some systems/compilers */
  88590. #if 0
  88591. #define FLAC__CRC16_UPDATE(data, crc) ((((crc)<<8) ^ FLAC__crc16_table[((crc)>>8) ^ (data)]) & 0xffff)
  88592. #endif
  88593. unsigned FLAC__crc16(const FLAC__byte *data, unsigned len);
  88594. #endif
  88595. /********* End of inlined file: crc.h *********/
  88596. /* Things should be fastest when this matches the machine word size */
  88597. /* WATCHOUT: if you change this you must also change the following #defines down to COUNT_ZERO_MSBS below to match */
  88598. /* WATCHOUT: there are a few places where the code will not work unless brword is >= 32 bits wide */
  88599. /* also, some sections currently only have fast versions for 4 or 8 bytes per word */
  88600. typedef FLAC__uint32 brword;
  88601. #define FLAC__BYTES_PER_WORD 4
  88602. #define FLAC__BITS_PER_WORD 32
  88603. #define FLAC__WORD_ALL_ONES ((FLAC__uint32)0xffffffff)
  88604. /* SWAP_BE_WORD_TO_HOST swaps bytes in a brword (which is always big-endian) if necessary to match host byte order */
  88605. #if WORDS_BIGENDIAN
  88606. #define SWAP_BE_WORD_TO_HOST(x) (x)
  88607. #else
  88608. #if defined (_MSC_VER) && defined (_X86_)
  88609. #define SWAP_BE_WORD_TO_HOST(x) local_swap32_(x)
  88610. #else
  88611. #define SWAP_BE_WORD_TO_HOST(x) ntohl(x)
  88612. #endif
  88613. #endif
  88614. /* counts the # of zero MSBs in a word */
  88615. #define COUNT_ZERO_MSBS(word) ( \
  88616. (word) <= 0xffff ? \
  88617. ( (word) <= 0xff? byte_to_unary_table[word] + 24 : byte_to_unary_table[(word) >> 8] + 16 ) : \
  88618. ( (word) <= 0xffffff? byte_to_unary_table[word >> 16] + 8 : byte_to_unary_table[(word) >> 24] ) \
  88619. )
  88620. /* this alternate might be slightly faster on some systems/compilers: */
  88621. #define COUNT_ZERO_MSBS2(word) ( (word) <= 0xff ? byte_to_unary_table[word] + 24 : ((word) <= 0xffff ? byte_to_unary_table[(word) >> 8] + 16 : ((word) <= 0xffffff ? byte_to_unary_table[(word) >> 16] + 8 : byte_to_unary_table[(word) >> 24])) )
  88622. /*
  88623. * This should be at least twice as large as the largest number of words
  88624. * required to represent any 'number' (in any encoding) you are going to
  88625. * read. With FLAC this is on the order of maybe a few hundred bits.
  88626. * If the buffer is smaller than that, the decoder won't be able to read
  88627. * in a whole number that is in a variable length encoding (e.g. Rice).
  88628. * But to be practical it should be at least 1K bytes.
  88629. *
  88630. * Increase this number to decrease the number of read callbacks, at the
  88631. * expense of using more memory. Or decrease for the reverse effect,
  88632. * keeping in mind the limit from the first paragraph. The optimal size
  88633. * also depends on the CPU cache size and other factors; some twiddling
  88634. * may be necessary to squeeze out the best performance.
  88635. */
  88636. static const unsigned FLAC__BITREADER_DEFAULT_CAPACITY = 65536u / FLAC__BITS_PER_WORD; /* in words */
  88637. static const unsigned char byte_to_unary_table[] = {
  88638. 8, 7, 6, 6, 5, 5, 5, 5, 4, 4, 4, 4, 4, 4, 4, 4,
  88639. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  88640. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  88641. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  88642. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  88643. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  88644. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  88645. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  88646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  88647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  88648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  88649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  88650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  88651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  88652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  88653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
  88654. };
  88655. #ifdef min
  88656. #undef min
  88657. #endif
  88658. #define min(x,y) ((x)<(y)?(x):(y))
  88659. #ifdef max
  88660. #undef max
  88661. #endif
  88662. #define max(x,y) ((x)>(y)?(x):(y))
  88663. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  88664. #ifdef _MSC_VER
  88665. #define FLAC__U64L(x) x
  88666. #else
  88667. #define FLAC__U64L(x) x##LLU
  88668. #endif
  88669. #ifndef FLaC__INLINE
  88670. #define FLaC__INLINE
  88671. #endif
  88672. /* WATCHOUT: assembly routines rely on the order in which these fields are declared */
  88673. struct FLAC__BitReader {
  88674. /* any partially-consumed word at the head will stay right-justified as bits are consumed from the left */
  88675. /* any incomplete word at the tail will be left-justified, and bytes from the read callback are added on the right */
  88676. brword *buffer;
  88677. unsigned capacity; /* in words */
  88678. unsigned words; /* # of completed words in buffer */
  88679. unsigned bytes; /* # of bytes in incomplete word at buffer[words] */
  88680. unsigned consumed_words; /* #words ... */
  88681. unsigned consumed_bits; /* ... + (#bits of head word) already consumed from the front of buffer */
  88682. unsigned read_crc16; /* the running frame CRC */
  88683. unsigned crc16_align; /* the number of bits in the current consumed word that should not be CRC'd */
  88684. FLAC__BitReaderReadCallback read_callback;
  88685. void *client_data;
  88686. FLAC__CPUInfo cpu_info;
  88687. };
  88688. static FLaC__INLINE void crc16_update_word_(FLAC__BitReader *br, brword word)
  88689. {
  88690. register unsigned crc = br->read_crc16;
  88691. #if FLAC__BYTES_PER_WORD == 4
  88692. switch(br->crc16_align) {
  88693. case 0: crc = FLAC__CRC16_UPDATE((unsigned)(word >> 24), crc);
  88694. case 8: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 16) & 0xff), crc);
  88695. case 16: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 8) & 0xff), crc);
  88696. case 24: br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)(word & 0xff), crc);
  88697. }
  88698. #elif FLAC__BYTES_PER_WORD == 8
  88699. switch(br->crc16_align) {
  88700. case 0: crc = FLAC__CRC16_UPDATE((unsigned)(word >> 56), crc);
  88701. case 8: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 48) & 0xff), crc);
  88702. case 16: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 40) & 0xff), crc);
  88703. case 24: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 32) & 0xff), crc);
  88704. case 32: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 24) & 0xff), crc);
  88705. case 40: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 16) & 0xff), crc);
  88706. case 48: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 8) & 0xff), crc);
  88707. case 56: br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)(word & 0xff), crc);
  88708. }
  88709. #else
  88710. for( ; br->crc16_align < FLAC__BITS_PER_WORD; br->crc16_align += 8)
  88711. crc = FLAC__CRC16_UPDATE((unsigned)((word >> (FLAC__BITS_PER_WORD-8-br->crc16_align)) & 0xff), crc);
  88712. br->read_crc16 = crc;
  88713. #endif
  88714. br->crc16_align = 0;
  88715. }
  88716. /* would be static except it needs to be called by asm routines */
  88717. FLAC__bool bitreader_read_from_client_(FLAC__BitReader *br)
  88718. {
  88719. unsigned start, end;
  88720. size_t bytes;
  88721. FLAC__byte *target;
  88722. /* first shift the unconsumed buffer data toward the front as much as possible */
  88723. if(br->consumed_words > 0) {
  88724. start = br->consumed_words;
  88725. end = br->words + (br->bytes? 1:0);
  88726. memmove(br->buffer, br->buffer+start, FLAC__BYTES_PER_WORD * (end - start));
  88727. br->words -= start;
  88728. br->consumed_words = 0;
  88729. }
  88730. /*
  88731. * set the target for reading, taking into account word alignment and endianness
  88732. */
  88733. bytes = (br->capacity - br->words) * FLAC__BYTES_PER_WORD - br->bytes;
  88734. if(bytes == 0)
  88735. return false; /* no space left, buffer is too small; see note for FLAC__BITREADER_DEFAULT_CAPACITY */
  88736. target = ((FLAC__byte*)(br->buffer+br->words)) + br->bytes;
  88737. /* before reading, if the existing reader looks like this (say brword is 32 bits wide)
  88738. * bitstream : 11 22 33 44 55 br->words=1 br->bytes=1 (partial tail word is left-justified)
  88739. * buffer[BE]: 11 22 33 44 55 ?? ?? ?? (shown layed out as bytes sequentially in memory)
  88740. * buffer[LE]: 44 33 22 11 ?? ?? ?? 55 (?? being don't-care)
  88741. * ^^-------target, bytes=3
  88742. * on LE machines, have to byteswap the odd tail word so nothing is
  88743. * overwritten:
  88744. */
  88745. #if WORDS_BIGENDIAN
  88746. #else
  88747. if(br->bytes)
  88748. br->buffer[br->words] = SWAP_BE_WORD_TO_HOST(br->buffer[br->words]);
  88749. #endif
  88750. /* now it looks like:
  88751. * bitstream : 11 22 33 44 55 br->words=1 br->bytes=1
  88752. * buffer[BE]: 11 22 33 44 55 ?? ?? ??
  88753. * buffer[LE]: 44 33 22 11 55 ?? ?? ??
  88754. * ^^-------target, bytes=3
  88755. */
  88756. /* read in the data; note that the callback may return a smaller number of bytes */
  88757. if(!br->read_callback(target, &bytes, br->client_data))
  88758. return false;
  88759. /* after reading bytes 66 77 88 99 AA BB CC DD EE FF from the client:
  88760. * bitstream : 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF
  88761. * buffer[BE]: 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF ??
  88762. * buffer[LE]: 44 33 22 11 55 66 77 88 99 AA BB CC DD EE FF ??
  88763. * now have to byteswap on LE machines:
  88764. */
  88765. #if WORDS_BIGENDIAN
  88766. #else
  88767. end = (br->words*FLAC__BYTES_PER_WORD + br->bytes + bytes + (FLAC__BYTES_PER_WORD-1)) / FLAC__BYTES_PER_WORD;
  88768. # if defined(_MSC_VER) && defined (_X86_) && (FLAC__BYTES_PER_WORD == 4)
  88769. if(br->cpu_info.type == FLAC__CPUINFO_TYPE_IA32 && br->cpu_info.data.ia32.bswap) {
  88770. start = br->words;
  88771. local_swap32_block_(br->buffer + start, end - start);
  88772. }
  88773. else
  88774. # endif
  88775. for(start = br->words; start < end; start++)
  88776. br->buffer[start] = SWAP_BE_WORD_TO_HOST(br->buffer[start]);
  88777. #endif
  88778. /* now it looks like:
  88779. * bitstream : 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF
  88780. * buffer[BE]: 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF ??
  88781. * buffer[LE]: 44 33 22 11 88 77 66 55 CC BB AA 99 ?? FF EE DD
  88782. * finally we'll update the reader values:
  88783. */
  88784. end = br->words*FLAC__BYTES_PER_WORD + br->bytes + bytes;
  88785. br->words = end / FLAC__BYTES_PER_WORD;
  88786. br->bytes = end % FLAC__BYTES_PER_WORD;
  88787. return true;
  88788. }
  88789. /***********************************************************************
  88790. *
  88791. * Class constructor/destructor
  88792. *
  88793. ***********************************************************************/
  88794. FLAC__BitReader *FLAC__bitreader_new(void)
  88795. {
  88796. FLAC__BitReader *br = (FLAC__BitReader*)calloc(1, sizeof(FLAC__BitReader));
  88797. /* calloc() implies:
  88798. memset(br, 0, sizeof(FLAC__BitReader));
  88799. br->buffer = 0;
  88800. br->capacity = 0;
  88801. br->words = br->bytes = 0;
  88802. br->consumed_words = br->consumed_bits = 0;
  88803. br->read_callback = 0;
  88804. br->client_data = 0;
  88805. */
  88806. return br;
  88807. }
  88808. void FLAC__bitreader_delete(FLAC__BitReader *br)
  88809. {
  88810. FLAC__ASSERT(0 != br);
  88811. FLAC__bitreader_free(br);
  88812. free(br);
  88813. }
  88814. /***********************************************************************
  88815. *
  88816. * Public class methods
  88817. *
  88818. ***********************************************************************/
  88819. FLAC__bool FLAC__bitreader_init(FLAC__BitReader *br, FLAC__CPUInfo cpu, FLAC__BitReaderReadCallback rcb, void *cd)
  88820. {
  88821. FLAC__ASSERT(0 != br);
  88822. br->words = br->bytes = 0;
  88823. br->consumed_words = br->consumed_bits = 0;
  88824. br->capacity = FLAC__BITREADER_DEFAULT_CAPACITY;
  88825. br->buffer = (brword*)malloc(sizeof(brword) * br->capacity);
  88826. if(br->buffer == 0)
  88827. return false;
  88828. br->read_callback = rcb;
  88829. br->client_data = cd;
  88830. br->cpu_info = cpu;
  88831. return true;
  88832. }
  88833. void FLAC__bitreader_free(FLAC__BitReader *br)
  88834. {
  88835. FLAC__ASSERT(0 != br);
  88836. if(0 != br->buffer)
  88837. free(br->buffer);
  88838. br->buffer = 0;
  88839. br->capacity = 0;
  88840. br->words = br->bytes = 0;
  88841. br->consumed_words = br->consumed_bits = 0;
  88842. br->read_callback = 0;
  88843. br->client_data = 0;
  88844. }
  88845. FLAC__bool FLAC__bitreader_clear(FLAC__BitReader *br)
  88846. {
  88847. br->words = br->bytes = 0;
  88848. br->consumed_words = br->consumed_bits = 0;
  88849. return true;
  88850. }
  88851. void FLAC__bitreader_dump(const FLAC__BitReader *br, FILE *out)
  88852. {
  88853. unsigned i, j;
  88854. if(br == 0) {
  88855. fprintf(out, "bitreader is NULL\n");
  88856. }
  88857. else {
  88858. fprintf(out, "bitreader: capacity=%u words=%u bytes=%u consumed: words=%u, bits=%u\n", br->capacity, br->words, br->bytes, br->consumed_words, br->consumed_bits);
  88859. for(i = 0; i < br->words; i++) {
  88860. fprintf(out, "%08X: ", i);
  88861. for(j = 0; j < FLAC__BITS_PER_WORD; j++)
  88862. if(i < br->consumed_words || (i == br->consumed_words && j < br->consumed_bits))
  88863. fprintf(out, ".");
  88864. else
  88865. fprintf(out, "%01u", br->buffer[i] & (1 << (FLAC__BITS_PER_WORD-j-1)) ? 1:0);
  88866. fprintf(out, "\n");
  88867. }
  88868. if(br->bytes > 0) {
  88869. fprintf(out, "%08X: ", i);
  88870. for(j = 0; j < br->bytes*8; j++)
  88871. if(i < br->consumed_words || (i == br->consumed_words && j < br->consumed_bits))
  88872. fprintf(out, ".");
  88873. else
  88874. fprintf(out, "%01u", br->buffer[i] & (1 << (br->bytes*8-j-1)) ? 1:0);
  88875. fprintf(out, "\n");
  88876. }
  88877. }
  88878. }
  88879. void FLAC__bitreader_reset_read_crc16(FLAC__BitReader *br, FLAC__uint16 seed)
  88880. {
  88881. FLAC__ASSERT(0 != br);
  88882. FLAC__ASSERT(0 != br->buffer);
  88883. FLAC__ASSERT((br->consumed_bits & 7) == 0);
  88884. br->read_crc16 = (unsigned)seed;
  88885. br->crc16_align = br->consumed_bits;
  88886. }
  88887. FLAC__uint16 FLAC__bitreader_get_read_crc16(FLAC__BitReader *br)
  88888. {
  88889. FLAC__ASSERT(0 != br);
  88890. FLAC__ASSERT(0 != br->buffer);
  88891. FLAC__ASSERT((br->consumed_bits & 7) == 0);
  88892. FLAC__ASSERT(br->crc16_align <= br->consumed_bits);
  88893. /* CRC any tail bytes in a partially-consumed word */
  88894. if(br->consumed_bits) {
  88895. const brword tail = br->buffer[br->consumed_words];
  88896. for( ; br->crc16_align < br->consumed_bits; br->crc16_align += 8)
  88897. br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)((tail >> (FLAC__BITS_PER_WORD-8-br->crc16_align)) & 0xff), br->read_crc16);
  88898. }
  88899. return br->read_crc16;
  88900. }
  88901. FLaC__INLINE FLAC__bool FLAC__bitreader_is_consumed_byte_aligned(const FLAC__BitReader *br)
  88902. {
  88903. return ((br->consumed_bits & 7) == 0);
  88904. }
  88905. FLaC__INLINE unsigned FLAC__bitreader_bits_left_for_byte_alignment(const FLAC__BitReader *br)
  88906. {
  88907. return 8 - (br->consumed_bits & 7);
  88908. }
  88909. FLaC__INLINE unsigned FLAC__bitreader_get_input_bits_unconsumed(const FLAC__BitReader *br)
  88910. {
  88911. return (br->words-br->consumed_words)*FLAC__BITS_PER_WORD + br->bytes*8 - br->consumed_bits;
  88912. }
  88913. FLaC__INLINE FLAC__bool FLAC__bitreader_read_raw_uint32(FLAC__BitReader *br, FLAC__uint32 *val, unsigned bits)
  88914. {
  88915. FLAC__ASSERT(0 != br);
  88916. FLAC__ASSERT(0 != br->buffer);
  88917. FLAC__ASSERT(bits <= 32);
  88918. FLAC__ASSERT((br->capacity*FLAC__BITS_PER_WORD) * 2 >= bits);
  88919. FLAC__ASSERT(br->consumed_words <= br->words);
  88920. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  88921. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  88922. if(bits == 0) { /* OPT: investigate if this can ever happen, maybe change to assertion */
  88923. *val = 0;
  88924. return true;
  88925. }
  88926. while((br->words-br->consumed_words)*FLAC__BITS_PER_WORD + br->bytes*8 - br->consumed_bits < bits) {
  88927. if(!bitreader_read_from_client_(br))
  88928. return false;
  88929. }
  88930. if(br->consumed_words < br->words) { /* if we've not consumed up to a partial tail word... */
  88931. /* OPT: taking out the consumed_bits==0 "else" case below might make things faster if less code allows the compiler to inline this function */
  88932. if(br->consumed_bits) {
  88933. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  88934. const unsigned n = FLAC__BITS_PER_WORD - br->consumed_bits;
  88935. const brword word = br->buffer[br->consumed_words];
  88936. if(bits < n) {
  88937. *val = (word & (FLAC__WORD_ALL_ONES >> br->consumed_bits)) >> (n-bits);
  88938. br->consumed_bits += bits;
  88939. return true;
  88940. }
  88941. *val = word & (FLAC__WORD_ALL_ONES >> br->consumed_bits);
  88942. bits -= n;
  88943. crc16_update_word_(br, word);
  88944. br->consumed_words++;
  88945. br->consumed_bits = 0;
  88946. if(bits) { /* if there are still bits left to read, there have to be less than 32 so they will all be in the next word */
  88947. *val <<= bits;
  88948. *val |= (br->buffer[br->consumed_words] >> (FLAC__BITS_PER_WORD-bits));
  88949. br->consumed_bits = bits;
  88950. }
  88951. return true;
  88952. }
  88953. else {
  88954. const brword word = br->buffer[br->consumed_words];
  88955. if(bits < FLAC__BITS_PER_WORD) {
  88956. *val = word >> (FLAC__BITS_PER_WORD-bits);
  88957. br->consumed_bits = bits;
  88958. return true;
  88959. }
  88960. /* at this point 'bits' must be == FLAC__BITS_PER_WORD; because of previous assertions, it can't be larger */
  88961. *val = word;
  88962. crc16_update_word_(br, word);
  88963. br->consumed_words++;
  88964. return true;
  88965. }
  88966. }
  88967. else {
  88968. /* in this case we're starting our read at a partial tail word;
  88969. * the reader has guaranteed that we have at least 'bits' bits
  88970. * available to read, which makes this case simpler.
  88971. */
  88972. /* OPT: taking out the consumed_bits==0 "else" case below might make things faster if less code allows the compiler to inline this function */
  88973. if(br->consumed_bits) {
  88974. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  88975. FLAC__ASSERT(br->consumed_bits + bits <= br->bytes*8);
  88976. *val = (br->buffer[br->consumed_words] & (FLAC__WORD_ALL_ONES >> br->consumed_bits)) >> (FLAC__BITS_PER_WORD-br->consumed_bits-bits);
  88977. br->consumed_bits += bits;
  88978. return true;
  88979. }
  88980. else {
  88981. *val = br->buffer[br->consumed_words] >> (FLAC__BITS_PER_WORD-bits);
  88982. br->consumed_bits += bits;
  88983. return true;
  88984. }
  88985. }
  88986. }
  88987. FLAC__bool FLAC__bitreader_read_raw_int32(FLAC__BitReader *br, FLAC__int32 *val, unsigned bits)
  88988. {
  88989. /* OPT: inline raw uint32 code here, or make into a macro if possible in the .h file */
  88990. if(!FLAC__bitreader_read_raw_uint32(br, (FLAC__uint32*)val, bits))
  88991. return false;
  88992. /* sign-extend: */
  88993. *val <<= (32-bits);
  88994. *val >>= (32-bits);
  88995. return true;
  88996. }
  88997. FLAC__bool FLAC__bitreader_read_raw_uint64(FLAC__BitReader *br, FLAC__uint64 *val, unsigned bits)
  88998. {
  88999. FLAC__uint32 hi, lo;
  89000. if(bits > 32) {
  89001. if(!FLAC__bitreader_read_raw_uint32(br, &hi, bits-32))
  89002. return false;
  89003. if(!FLAC__bitreader_read_raw_uint32(br, &lo, 32))
  89004. return false;
  89005. *val = hi;
  89006. *val <<= 32;
  89007. *val |= lo;
  89008. }
  89009. else {
  89010. if(!FLAC__bitreader_read_raw_uint32(br, &lo, bits))
  89011. return false;
  89012. *val = lo;
  89013. }
  89014. return true;
  89015. }
  89016. FLaC__INLINE FLAC__bool FLAC__bitreader_read_uint32_little_endian(FLAC__BitReader *br, FLAC__uint32 *val)
  89017. {
  89018. FLAC__uint32 x8, x32 = 0;
  89019. /* this doesn't need to be that fast as currently it is only used for vorbis comments */
  89020. if(!FLAC__bitreader_read_raw_uint32(br, &x32, 8))
  89021. return false;
  89022. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  89023. return false;
  89024. x32 |= (x8 << 8);
  89025. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  89026. return false;
  89027. x32 |= (x8 << 16);
  89028. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  89029. return false;
  89030. x32 |= (x8 << 24);
  89031. *val = x32;
  89032. return true;
  89033. }
  89034. FLAC__bool FLAC__bitreader_skip_bits_no_crc(FLAC__BitReader *br, unsigned bits)
  89035. {
  89036. /*
  89037. * OPT: a faster implementation is possible but probably not that useful
  89038. * since this is only called a couple of times in the metadata readers.
  89039. */
  89040. FLAC__ASSERT(0 != br);
  89041. FLAC__ASSERT(0 != br->buffer);
  89042. if(bits > 0) {
  89043. const unsigned n = br->consumed_bits & 7;
  89044. unsigned m;
  89045. FLAC__uint32 x;
  89046. if(n != 0) {
  89047. m = min(8-n, bits);
  89048. if(!FLAC__bitreader_read_raw_uint32(br, &x, m))
  89049. return false;
  89050. bits -= m;
  89051. }
  89052. m = bits / 8;
  89053. if(m > 0) {
  89054. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(br, m))
  89055. return false;
  89056. bits %= 8;
  89057. }
  89058. if(bits > 0) {
  89059. if(!FLAC__bitreader_read_raw_uint32(br, &x, bits))
  89060. return false;
  89061. }
  89062. }
  89063. return true;
  89064. }
  89065. FLAC__bool FLAC__bitreader_skip_byte_block_aligned_no_crc(FLAC__BitReader *br, unsigned nvals)
  89066. {
  89067. FLAC__uint32 x;
  89068. FLAC__ASSERT(0 != br);
  89069. FLAC__ASSERT(0 != br->buffer);
  89070. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(br));
  89071. /* step 1: skip over partial head word to get word aligned */
  89072. while(nvals && br->consumed_bits) { /* i.e. run until we read 'nvals' bytes or we hit the end of the head word */
  89073. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  89074. return false;
  89075. nvals--;
  89076. }
  89077. if(0 == nvals)
  89078. return true;
  89079. /* step 2: skip whole words in chunks */
  89080. while(nvals >= FLAC__BYTES_PER_WORD) {
  89081. if(br->consumed_words < br->words) {
  89082. br->consumed_words++;
  89083. nvals -= FLAC__BYTES_PER_WORD;
  89084. }
  89085. else if(!bitreader_read_from_client_(br))
  89086. return false;
  89087. }
  89088. /* step 3: skip any remainder from partial tail bytes */
  89089. while(nvals) {
  89090. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  89091. return false;
  89092. nvals--;
  89093. }
  89094. return true;
  89095. }
  89096. FLAC__bool FLAC__bitreader_read_byte_block_aligned_no_crc(FLAC__BitReader *br, FLAC__byte *val, unsigned nvals)
  89097. {
  89098. FLAC__uint32 x;
  89099. FLAC__ASSERT(0 != br);
  89100. FLAC__ASSERT(0 != br->buffer);
  89101. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(br));
  89102. /* step 1: read from partial head word to get word aligned */
  89103. while(nvals && br->consumed_bits) { /* i.e. run until we read 'nvals' bytes or we hit the end of the head word */
  89104. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  89105. return false;
  89106. *val++ = (FLAC__byte)x;
  89107. nvals--;
  89108. }
  89109. if(0 == nvals)
  89110. return true;
  89111. /* step 2: read whole words in chunks */
  89112. while(nvals >= FLAC__BYTES_PER_WORD) {
  89113. if(br->consumed_words < br->words) {
  89114. const brword word = br->buffer[br->consumed_words++];
  89115. #if FLAC__BYTES_PER_WORD == 4
  89116. val[0] = (FLAC__byte)(word >> 24);
  89117. val[1] = (FLAC__byte)(word >> 16);
  89118. val[2] = (FLAC__byte)(word >> 8);
  89119. val[3] = (FLAC__byte)word;
  89120. #elif FLAC__BYTES_PER_WORD == 8
  89121. val[0] = (FLAC__byte)(word >> 56);
  89122. val[1] = (FLAC__byte)(word >> 48);
  89123. val[2] = (FLAC__byte)(word >> 40);
  89124. val[3] = (FLAC__byte)(word >> 32);
  89125. val[4] = (FLAC__byte)(word >> 24);
  89126. val[5] = (FLAC__byte)(word >> 16);
  89127. val[6] = (FLAC__byte)(word >> 8);
  89128. val[7] = (FLAC__byte)word;
  89129. #else
  89130. for(x = 0; x < FLAC__BYTES_PER_WORD; x++)
  89131. val[x] = (FLAC__byte)(word >> (8*(FLAC__BYTES_PER_WORD-x-1)));
  89132. #endif
  89133. val += FLAC__BYTES_PER_WORD;
  89134. nvals -= FLAC__BYTES_PER_WORD;
  89135. }
  89136. else if(!bitreader_read_from_client_(br))
  89137. return false;
  89138. }
  89139. /* step 3: read any remainder from partial tail bytes */
  89140. while(nvals) {
  89141. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  89142. return false;
  89143. *val++ = (FLAC__byte)x;
  89144. nvals--;
  89145. }
  89146. return true;
  89147. }
  89148. FLaC__INLINE FLAC__bool FLAC__bitreader_read_unary_unsigned(FLAC__BitReader *br, unsigned *val)
  89149. #if 0 /* slow but readable version */
  89150. {
  89151. unsigned bit;
  89152. FLAC__ASSERT(0 != br);
  89153. FLAC__ASSERT(0 != br->buffer);
  89154. *val = 0;
  89155. while(1) {
  89156. if(!FLAC__bitreader_read_bit(br, &bit))
  89157. return false;
  89158. if(bit)
  89159. break;
  89160. else
  89161. *val++;
  89162. }
  89163. return true;
  89164. }
  89165. #else
  89166. {
  89167. unsigned i;
  89168. FLAC__ASSERT(0 != br);
  89169. FLAC__ASSERT(0 != br->buffer);
  89170. *val = 0;
  89171. while(1) {
  89172. while(br->consumed_words < br->words) { /* if we've not consumed up to a partial tail word... */
  89173. brword b = br->buffer[br->consumed_words] << br->consumed_bits;
  89174. if(b) {
  89175. i = COUNT_ZERO_MSBS(b);
  89176. *val += i;
  89177. i++;
  89178. br->consumed_bits += i;
  89179. if(br->consumed_bits >= FLAC__BITS_PER_WORD) { /* faster way of testing if(br->consumed_bits == FLAC__BITS_PER_WORD) */
  89180. crc16_update_word_(br, br->buffer[br->consumed_words]);
  89181. br->consumed_words++;
  89182. br->consumed_bits = 0;
  89183. }
  89184. return true;
  89185. }
  89186. else {
  89187. *val += FLAC__BITS_PER_WORD - br->consumed_bits;
  89188. crc16_update_word_(br, br->buffer[br->consumed_words]);
  89189. br->consumed_words++;
  89190. br->consumed_bits = 0;
  89191. /* didn't find stop bit yet, have to keep going... */
  89192. }
  89193. }
  89194. /* at this point we've eaten up all the whole words; have to try
  89195. * reading through any tail bytes before calling the read callback.
  89196. * this is a repeat of the above logic adjusted for the fact we
  89197. * don't have a whole word. note though if the client is feeding
  89198. * us data a byte at a time (unlikely), br->consumed_bits may not
  89199. * be zero.
  89200. */
  89201. if(br->bytes) {
  89202. const unsigned end = br->bytes * 8;
  89203. brword b = (br->buffer[br->consumed_words] & (FLAC__WORD_ALL_ONES << (FLAC__BITS_PER_WORD-end))) << br->consumed_bits;
  89204. if(b) {
  89205. i = COUNT_ZERO_MSBS(b);
  89206. *val += i;
  89207. i++;
  89208. br->consumed_bits += i;
  89209. FLAC__ASSERT(br->consumed_bits < FLAC__BITS_PER_WORD);
  89210. return true;
  89211. }
  89212. else {
  89213. *val += end - br->consumed_bits;
  89214. br->consumed_bits += end;
  89215. FLAC__ASSERT(br->consumed_bits < FLAC__BITS_PER_WORD);
  89216. /* didn't find stop bit yet, have to keep going... */
  89217. }
  89218. }
  89219. if(!bitreader_read_from_client_(br))
  89220. return false;
  89221. }
  89222. }
  89223. #endif
  89224. FLAC__bool FLAC__bitreader_read_rice_signed(FLAC__BitReader *br, int *val, unsigned parameter)
  89225. {
  89226. FLAC__uint32 lsbs = 0, msbs = 0;
  89227. unsigned uval;
  89228. FLAC__ASSERT(0 != br);
  89229. FLAC__ASSERT(0 != br->buffer);
  89230. FLAC__ASSERT(parameter <= 31);
  89231. /* read the unary MSBs and end bit */
  89232. if(!FLAC__bitreader_read_unary_unsigned(br, (unsigned int*) &msbs))
  89233. return false;
  89234. /* read the binary LSBs */
  89235. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, parameter))
  89236. return false;
  89237. /* compose the value */
  89238. uval = (msbs << parameter) | lsbs;
  89239. if(uval & 1)
  89240. *val = -((int)(uval >> 1)) - 1;
  89241. else
  89242. *val = (int)(uval >> 1);
  89243. return true;
  89244. }
  89245. /* this is by far the most heavily used reader call. it ain't pretty but it's fast */
  89246. /* a lot of the logic is copied, then adapted, from FLAC__bitreader_read_unary_unsigned() and FLAC__bitreader_read_raw_uint32() */
  89247. FLAC__bool FLAC__bitreader_read_rice_signed_block(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter)
  89248. /* OPT: possibly faster version for use with MSVC */
  89249. #ifdef _MSC_VER
  89250. {
  89251. unsigned i;
  89252. unsigned uval = 0;
  89253. unsigned bits; /* the # of binary LSBs left to read to finish a rice codeword */
  89254. /* try and get br->consumed_words and br->consumed_bits into register;
  89255. * must remember to flush them back to *br before calling other
  89256. * bitwriter functions that use them, and before returning */
  89257. register unsigned cwords;
  89258. register unsigned cbits;
  89259. FLAC__ASSERT(0 != br);
  89260. FLAC__ASSERT(0 != br->buffer);
  89261. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  89262. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  89263. FLAC__ASSERT(parameter < 32);
  89264. /* the above two asserts also guarantee that the binary part never straddles more that 2 words, so we don't have to loop to read it */
  89265. if(nvals == 0)
  89266. return true;
  89267. cbits = br->consumed_bits;
  89268. cwords = br->consumed_words;
  89269. while(1) {
  89270. /* read unary part */
  89271. while(1) {
  89272. while(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  89273. brword b = br->buffer[cwords] << cbits;
  89274. if(b) {
  89275. #if 0 /* slower, probably due to bad register allocation... */ && defined FLAC__CPU_IA32 && !defined FLAC__NO_ASM && FLAC__BITS_PER_WORD == 32
  89276. __asm {
  89277. bsr eax, b
  89278. not eax
  89279. and eax, 31
  89280. mov i, eax
  89281. }
  89282. #else
  89283. i = COUNT_ZERO_MSBS(b);
  89284. #endif
  89285. uval += i;
  89286. bits = parameter;
  89287. i++;
  89288. cbits += i;
  89289. if(cbits == FLAC__BITS_PER_WORD) {
  89290. crc16_update_word_(br, br->buffer[cwords]);
  89291. cwords++;
  89292. cbits = 0;
  89293. }
  89294. goto break1;
  89295. }
  89296. else {
  89297. uval += FLAC__BITS_PER_WORD - cbits;
  89298. crc16_update_word_(br, br->buffer[cwords]);
  89299. cwords++;
  89300. cbits = 0;
  89301. /* didn't find stop bit yet, have to keep going... */
  89302. }
  89303. }
  89304. /* at this point we've eaten up all the whole words; have to try
  89305. * reading through any tail bytes before calling the read callback.
  89306. * this is a repeat of the above logic adjusted for the fact we
  89307. * don't have a whole word. note though if the client is feeding
  89308. * us data a byte at a time (unlikely), br->consumed_bits may not
  89309. * be zero.
  89310. */
  89311. if(br->bytes) {
  89312. const unsigned end = br->bytes * 8;
  89313. brword b = (br->buffer[cwords] & (FLAC__WORD_ALL_ONES << (FLAC__BITS_PER_WORD-end))) << cbits;
  89314. if(b) {
  89315. i = COUNT_ZERO_MSBS(b);
  89316. uval += i;
  89317. bits = parameter;
  89318. i++;
  89319. cbits += i;
  89320. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  89321. goto break1;
  89322. }
  89323. else {
  89324. uval += end - cbits;
  89325. cbits += end;
  89326. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  89327. /* didn't find stop bit yet, have to keep going... */
  89328. }
  89329. }
  89330. /* flush registers and read; bitreader_read_from_client_() does
  89331. * not touch br->consumed_bits at all but we still need to set
  89332. * it in case it fails and we have to return false.
  89333. */
  89334. br->consumed_bits = cbits;
  89335. br->consumed_words = cwords;
  89336. if(!bitreader_read_from_client_(br))
  89337. return false;
  89338. cwords = br->consumed_words;
  89339. }
  89340. break1:
  89341. /* read binary part */
  89342. FLAC__ASSERT(cwords <= br->words);
  89343. if(bits) {
  89344. while((br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits < bits) {
  89345. /* flush registers and read; bitreader_read_from_client_() does
  89346. * not touch br->consumed_bits at all but we still need to set
  89347. * it in case it fails and we have to return false.
  89348. */
  89349. br->consumed_bits = cbits;
  89350. br->consumed_words = cwords;
  89351. if(!bitreader_read_from_client_(br))
  89352. return false;
  89353. cwords = br->consumed_words;
  89354. }
  89355. if(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  89356. if(cbits) {
  89357. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  89358. const unsigned n = FLAC__BITS_PER_WORD - cbits;
  89359. const brword word = br->buffer[cwords];
  89360. if(bits < n) {
  89361. uval <<= bits;
  89362. uval |= (word & (FLAC__WORD_ALL_ONES >> cbits)) >> (n-bits);
  89363. cbits += bits;
  89364. goto break2;
  89365. }
  89366. uval <<= n;
  89367. uval |= word & (FLAC__WORD_ALL_ONES >> cbits);
  89368. bits -= n;
  89369. crc16_update_word_(br, word);
  89370. cwords++;
  89371. cbits = 0;
  89372. if(bits) { /* if there are still bits left to read, there have to be less than 32 so they will all be in the next word */
  89373. uval <<= bits;
  89374. uval |= (br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits));
  89375. cbits = bits;
  89376. }
  89377. goto break2;
  89378. }
  89379. else {
  89380. FLAC__ASSERT(bits < FLAC__BITS_PER_WORD);
  89381. uval <<= bits;
  89382. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits);
  89383. cbits = bits;
  89384. goto break2;
  89385. }
  89386. }
  89387. else {
  89388. /* in this case we're starting our read at a partial tail word;
  89389. * the reader has guaranteed that we have at least 'bits' bits
  89390. * available to read, which makes this case simpler.
  89391. */
  89392. uval <<= bits;
  89393. if(cbits) {
  89394. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  89395. FLAC__ASSERT(cbits + bits <= br->bytes*8);
  89396. uval |= (br->buffer[cwords] & (FLAC__WORD_ALL_ONES >> cbits)) >> (FLAC__BITS_PER_WORD-cbits-bits);
  89397. cbits += bits;
  89398. goto break2;
  89399. }
  89400. else {
  89401. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits);
  89402. cbits += bits;
  89403. goto break2;
  89404. }
  89405. }
  89406. }
  89407. break2:
  89408. /* compose the value */
  89409. *vals = (int)(uval >> 1 ^ -(int)(uval & 1));
  89410. /* are we done? */
  89411. --nvals;
  89412. if(nvals == 0) {
  89413. br->consumed_bits = cbits;
  89414. br->consumed_words = cwords;
  89415. return true;
  89416. }
  89417. uval = 0;
  89418. ++vals;
  89419. }
  89420. }
  89421. #else
  89422. {
  89423. unsigned i;
  89424. unsigned uval = 0;
  89425. /* try and get br->consumed_words and br->consumed_bits into register;
  89426. * must remember to flush them back to *br before calling other
  89427. * bitwriter functions that use them, and before returning */
  89428. register unsigned cwords;
  89429. register unsigned cbits;
  89430. unsigned ucbits; /* keep track of the number of unconsumed bits in the buffer */
  89431. FLAC__ASSERT(0 != br);
  89432. FLAC__ASSERT(0 != br->buffer);
  89433. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  89434. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  89435. FLAC__ASSERT(parameter < 32);
  89436. /* the above two asserts also guarantee that the binary part never straddles more than 2 words, so we don't have to loop to read it */
  89437. if(nvals == 0)
  89438. return true;
  89439. cbits = br->consumed_bits;
  89440. cwords = br->consumed_words;
  89441. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits;
  89442. while(1) {
  89443. /* read unary part */
  89444. while(1) {
  89445. while(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  89446. brword b = br->buffer[cwords] << cbits;
  89447. if(b) {
  89448. #if 0 /* is not discernably faster... */ && defined FLAC__CPU_IA32 && !defined FLAC__NO_ASM && FLAC__BITS_PER_WORD == 32 && defined __GNUC__
  89449. asm volatile (
  89450. "bsrl %1, %0;"
  89451. "notl %0;"
  89452. "andl $31, %0;"
  89453. : "=r"(i)
  89454. : "r"(b)
  89455. );
  89456. #else
  89457. i = COUNT_ZERO_MSBS(b);
  89458. #endif
  89459. uval += i;
  89460. cbits += i;
  89461. cbits++; /* skip over stop bit */
  89462. if(cbits >= FLAC__BITS_PER_WORD) { /* faster way of testing if(cbits == FLAC__BITS_PER_WORD) */
  89463. crc16_update_word_(br, br->buffer[cwords]);
  89464. cwords++;
  89465. cbits = 0;
  89466. }
  89467. goto break1;
  89468. }
  89469. else {
  89470. uval += FLAC__BITS_PER_WORD - cbits;
  89471. crc16_update_word_(br, br->buffer[cwords]);
  89472. cwords++;
  89473. cbits = 0;
  89474. /* didn't find stop bit yet, have to keep going... */
  89475. }
  89476. }
  89477. /* at this point we've eaten up all the whole words; have to try
  89478. * reading through any tail bytes before calling the read callback.
  89479. * this is a repeat of the above logic adjusted for the fact we
  89480. * don't have a whole word. note though if the client is feeding
  89481. * us data a byte at a time (unlikely), br->consumed_bits may not
  89482. * be zero.
  89483. */
  89484. if(br->bytes) {
  89485. const unsigned end = br->bytes * 8;
  89486. brword b = (br->buffer[cwords] & ~(FLAC__WORD_ALL_ONES >> end)) << cbits;
  89487. if(b) {
  89488. i = COUNT_ZERO_MSBS(b);
  89489. uval += i;
  89490. cbits += i;
  89491. cbits++; /* skip over stop bit */
  89492. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  89493. goto break1;
  89494. }
  89495. else {
  89496. uval += end - cbits;
  89497. cbits += end;
  89498. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  89499. /* didn't find stop bit yet, have to keep going... */
  89500. }
  89501. }
  89502. /* flush registers and read; bitreader_read_from_client_() does
  89503. * not touch br->consumed_bits at all but we still need to set
  89504. * it in case it fails and we have to return false.
  89505. */
  89506. br->consumed_bits = cbits;
  89507. br->consumed_words = cwords;
  89508. if(!bitreader_read_from_client_(br))
  89509. return false;
  89510. cwords = br->consumed_words;
  89511. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits + uval;
  89512. /* + uval to offset our count by the # of unary bits already
  89513. * consumed before the read, because we will add these back
  89514. * in all at once at break1
  89515. */
  89516. }
  89517. break1:
  89518. ucbits -= uval;
  89519. ucbits--; /* account for stop bit */
  89520. /* read binary part */
  89521. FLAC__ASSERT(cwords <= br->words);
  89522. if(parameter) {
  89523. while(ucbits < parameter) {
  89524. /* flush registers and read; bitreader_read_from_client_() does
  89525. * not touch br->consumed_bits at all but we still need to set
  89526. * it in case it fails and we have to return false.
  89527. */
  89528. br->consumed_bits = cbits;
  89529. br->consumed_words = cwords;
  89530. if(!bitreader_read_from_client_(br))
  89531. return false;
  89532. cwords = br->consumed_words;
  89533. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits;
  89534. }
  89535. if(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  89536. if(cbits) {
  89537. /* this also works when consumed_bits==0, it's just slower than necessary for that case */
  89538. const unsigned n = FLAC__BITS_PER_WORD - cbits;
  89539. const brword word = br->buffer[cwords];
  89540. if(parameter < n) {
  89541. uval <<= parameter;
  89542. uval |= (word & (FLAC__WORD_ALL_ONES >> cbits)) >> (n-parameter);
  89543. cbits += parameter;
  89544. }
  89545. else {
  89546. uval <<= n;
  89547. uval |= word & (FLAC__WORD_ALL_ONES >> cbits);
  89548. crc16_update_word_(br, word);
  89549. cwords++;
  89550. cbits = parameter - n;
  89551. if(cbits) { /* parameter > n, i.e. if there are still bits left to read, there have to be less than 32 so they will all be in the next word */
  89552. uval <<= cbits;
  89553. uval |= (br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits));
  89554. }
  89555. }
  89556. }
  89557. else {
  89558. cbits = parameter;
  89559. uval <<= parameter;
  89560. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits);
  89561. }
  89562. }
  89563. else {
  89564. /* in this case we're starting our read at a partial tail word;
  89565. * the reader has guaranteed that we have at least 'parameter'
  89566. * bits available to read, which makes this case simpler.
  89567. */
  89568. uval <<= parameter;
  89569. if(cbits) {
  89570. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  89571. FLAC__ASSERT(cbits + parameter <= br->bytes*8);
  89572. uval |= (br->buffer[cwords] & (FLAC__WORD_ALL_ONES >> cbits)) >> (FLAC__BITS_PER_WORD-cbits-parameter);
  89573. cbits += parameter;
  89574. }
  89575. else {
  89576. cbits = parameter;
  89577. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits);
  89578. }
  89579. }
  89580. }
  89581. ucbits -= parameter;
  89582. /* compose the value */
  89583. *vals = (int)(uval >> 1 ^ -(int)(uval & 1));
  89584. /* are we done? */
  89585. --nvals;
  89586. if(nvals == 0) {
  89587. br->consumed_bits = cbits;
  89588. br->consumed_words = cwords;
  89589. return true;
  89590. }
  89591. uval = 0;
  89592. ++vals;
  89593. }
  89594. }
  89595. #endif
  89596. #if 0 /* UNUSED */
  89597. FLAC__bool FLAC__bitreader_read_golomb_signed(FLAC__BitReader *br, int *val, unsigned parameter)
  89598. {
  89599. FLAC__uint32 lsbs = 0, msbs = 0;
  89600. unsigned bit, uval, k;
  89601. FLAC__ASSERT(0 != br);
  89602. FLAC__ASSERT(0 != br->buffer);
  89603. k = FLAC__bitmath_ilog2(parameter);
  89604. /* read the unary MSBs and end bit */
  89605. if(!FLAC__bitreader_read_unary_unsigned(br, &msbs))
  89606. return false;
  89607. /* read the binary LSBs */
  89608. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, k))
  89609. return false;
  89610. if(parameter == 1u<<k) {
  89611. /* compose the value */
  89612. uval = (msbs << k) | lsbs;
  89613. }
  89614. else {
  89615. unsigned d = (1 << (k+1)) - parameter;
  89616. if(lsbs >= d) {
  89617. if(!FLAC__bitreader_read_bit(br, &bit))
  89618. return false;
  89619. lsbs <<= 1;
  89620. lsbs |= bit;
  89621. lsbs -= d;
  89622. }
  89623. /* compose the value */
  89624. uval = msbs * parameter + lsbs;
  89625. }
  89626. /* unfold unsigned to signed */
  89627. if(uval & 1)
  89628. *val = -((int)(uval >> 1)) - 1;
  89629. else
  89630. *val = (int)(uval >> 1);
  89631. return true;
  89632. }
  89633. FLAC__bool FLAC__bitreader_read_golomb_unsigned(FLAC__BitReader *br, unsigned *val, unsigned parameter)
  89634. {
  89635. FLAC__uint32 lsbs, msbs = 0;
  89636. unsigned bit, k;
  89637. FLAC__ASSERT(0 != br);
  89638. FLAC__ASSERT(0 != br->buffer);
  89639. k = FLAC__bitmath_ilog2(parameter);
  89640. /* read the unary MSBs and end bit */
  89641. if(!FLAC__bitreader_read_unary_unsigned(br, &msbs))
  89642. return false;
  89643. /* read the binary LSBs */
  89644. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, k))
  89645. return false;
  89646. if(parameter == 1u<<k) {
  89647. /* compose the value */
  89648. *val = (msbs << k) | lsbs;
  89649. }
  89650. else {
  89651. unsigned d = (1 << (k+1)) - parameter;
  89652. if(lsbs >= d) {
  89653. if(!FLAC__bitreader_read_bit(br, &bit))
  89654. return false;
  89655. lsbs <<= 1;
  89656. lsbs |= bit;
  89657. lsbs -= d;
  89658. }
  89659. /* compose the value */
  89660. *val = msbs * parameter + lsbs;
  89661. }
  89662. return true;
  89663. }
  89664. #endif /* UNUSED */
  89665. /* on return, if *val == 0xffffffff then the utf-8 sequence was invalid, but the return value will be true */
  89666. FLAC__bool FLAC__bitreader_read_utf8_uint32(FLAC__BitReader *br, FLAC__uint32 *val, FLAC__byte *raw, unsigned *rawlen)
  89667. {
  89668. FLAC__uint32 v = 0;
  89669. FLAC__uint32 x;
  89670. unsigned i;
  89671. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  89672. return false;
  89673. if(raw)
  89674. raw[(*rawlen)++] = (FLAC__byte)x;
  89675. if(!(x & 0x80)) { /* 0xxxxxxx */
  89676. v = x;
  89677. i = 0;
  89678. }
  89679. else if(x & 0xC0 && !(x & 0x20)) { /* 110xxxxx */
  89680. v = x & 0x1F;
  89681. i = 1;
  89682. }
  89683. else if(x & 0xE0 && !(x & 0x10)) { /* 1110xxxx */
  89684. v = x & 0x0F;
  89685. i = 2;
  89686. }
  89687. else if(x & 0xF0 && !(x & 0x08)) { /* 11110xxx */
  89688. v = x & 0x07;
  89689. i = 3;
  89690. }
  89691. else if(x & 0xF8 && !(x & 0x04)) { /* 111110xx */
  89692. v = x & 0x03;
  89693. i = 4;
  89694. }
  89695. else if(x & 0xFC && !(x & 0x02)) { /* 1111110x */
  89696. v = x & 0x01;
  89697. i = 5;
  89698. }
  89699. else {
  89700. *val = 0xffffffff;
  89701. return true;
  89702. }
  89703. for( ; i; i--) {
  89704. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  89705. return false;
  89706. if(raw)
  89707. raw[(*rawlen)++] = (FLAC__byte)x;
  89708. if(!(x & 0x80) || (x & 0x40)) { /* 10xxxxxx */
  89709. *val = 0xffffffff;
  89710. return true;
  89711. }
  89712. v <<= 6;
  89713. v |= (x & 0x3F);
  89714. }
  89715. *val = v;
  89716. return true;
  89717. }
  89718. /* on return, if *val == 0xffffffffffffffff then the utf-8 sequence was invalid, but the return value will be true */
  89719. FLAC__bool FLAC__bitreader_read_utf8_uint64(FLAC__BitReader *br, FLAC__uint64 *val, FLAC__byte *raw, unsigned *rawlen)
  89720. {
  89721. FLAC__uint64 v = 0;
  89722. FLAC__uint32 x;
  89723. unsigned i;
  89724. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  89725. return false;
  89726. if(raw)
  89727. raw[(*rawlen)++] = (FLAC__byte)x;
  89728. if(!(x & 0x80)) { /* 0xxxxxxx */
  89729. v = x;
  89730. i = 0;
  89731. }
  89732. else if(x & 0xC0 && !(x & 0x20)) { /* 110xxxxx */
  89733. v = x & 0x1F;
  89734. i = 1;
  89735. }
  89736. else if(x & 0xE0 && !(x & 0x10)) { /* 1110xxxx */
  89737. v = x & 0x0F;
  89738. i = 2;
  89739. }
  89740. else if(x & 0xF0 && !(x & 0x08)) { /* 11110xxx */
  89741. v = x & 0x07;
  89742. i = 3;
  89743. }
  89744. else if(x & 0xF8 && !(x & 0x04)) { /* 111110xx */
  89745. v = x & 0x03;
  89746. i = 4;
  89747. }
  89748. else if(x & 0xFC && !(x & 0x02)) { /* 1111110x */
  89749. v = x & 0x01;
  89750. i = 5;
  89751. }
  89752. else if(x & 0xFE && !(x & 0x01)) { /* 11111110 */
  89753. v = 0;
  89754. i = 6;
  89755. }
  89756. else {
  89757. *val = FLAC__U64L(0xffffffffffffffff);
  89758. return true;
  89759. }
  89760. for( ; i; i--) {
  89761. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  89762. return false;
  89763. if(raw)
  89764. raw[(*rawlen)++] = (FLAC__byte)x;
  89765. if(!(x & 0x80) || (x & 0x40)) { /* 10xxxxxx */
  89766. *val = FLAC__U64L(0xffffffffffffffff);
  89767. return true;
  89768. }
  89769. v <<= 6;
  89770. v |= (x & 0x3F);
  89771. }
  89772. *val = v;
  89773. return true;
  89774. }
  89775. #endif
  89776. /********* End of inlined file: bitreader.c *********/
  89777. /********* Start of inlined file: bitwriter.c *********/
  89778. /********* Start of inlined file: juce_FlacHeader.h *********/
  89779. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  89780. // tasks..
  89781. #define VERSION "1.2.1"
  89782. #define FLAC__NO_DLL 1
  89783. #ifdef _MSC_VER
  89784. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  89785. #endif
  89786. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  89787. #define FLAC__SYS_DARWIN 1
  89788. #endif
  89789. /********* End of inlined file: juce_FlacHeader.h *********/
  89790. #if JUCE_USE_FLAC
  89791. #if HAVE_CONFIG_H
  89792. # include <config.h>
  89793. #endif
  89794. #include <stdlib.h> /* for malloc() */
  89795. #include <string.h> /* for memcpy(), memset() */
  89796. #ifdef _MSC_VER
  89797. #include <winsock.h> /* for ntohl() */
  89798. #elif defined FLAC__SYS_DARWIN
  89799. #include <machine/endian.h> /* for ntohl() */
  89800. #elif defined __MINGW32__
  89801. #include <winsock.h> /* for ntohl() */
  89802. #else
  89803. #include <netinet/in.h> /* for ntohl() */
  89804. #endif
  89805. #if 0 /* UNUSED */
  89806. #endif
  89807. /********* Start of inlined file: bitwriter.h *********/
  89808. #ifndef FLAC__PRIVATE__BITWRITER_H
  89809. #define FLAC__PRIVATE__BITWRITER_H
  89810. #include <stdio.h> /* for FILE */
  89811. /*
  89812. * opaque structure definition
  89813. */
  89814. struct FLAC__BitWriter;
  89815. typedef struct FLAC__BitWriter FLAC__BitWriter;
  89816. /*
  89817. * construction, deletion, initialization, etc functions
  89818. */
  89819. FLAC__BitWriter *FLAC__bitwriter_new(void);
  89820. void FLAC__bitwriter_delete(FLAC__BitWriter *bw);
  89821. FLAC__bool FLAC__bitwriter_init(FLAC__BitWriter *bw);
  89822. void FLAC__bitwriter_free(FLAC__BitWriter *bw); /* does not 'free(buffer)' */
  89823. void FLAC__bitwriter_clear(FLAC__BitWriter *bw);
  89824. void FLAC__bitwriter_dump(const FLAC__BitWriter *bw, FILE *out);
  89825. /*
  89826. * CRC functions
  89827. *
  89828. * non-const *bw because they have to cal FLAC__bitwriter_get_buffer()
  89829. */
  89830. FLAC__bool FLAC__bitwriter_get_write_crc16(FLAC__BitWriter *bw, FLAC__uint16 *crc);
  89831. FLAC__bool FLAC__bitwriter_get_write_crc8(FLAC__BitWriter *bw, FLAC__byte *crc);
  89832. /*
  89833. * info functions
  89834. */
  89835. FLAC__bool FLAC__bitwriter_is_byte_aligned(const FLAC__BitWriter *bw);
  89836. unsigned FLAC__bitwriter_get_input_bits_unconsumed(const FLAC__BitWriter *bw); /* can be called anytime, returns total # of bits unconsumed */
  89837. /*
  89838. * direct buffer access
  89839. *
  89840. * there may be no calls on the bitwriter between get and release.
  89841. * the bitwriter continues to own the returned buffer.
  89842. * before get, bitwriter MUST be byte aligned: check with FLAC__bitwriter_is_byte_aligned()
  89843. */
  89844. FLAC__bool FLAC__bitwriter_get_buffer(FLAC__BitWriter *bw, const FLAC__byte **buffer, size_t *bytes);
  89845. void FLAC__bitwriter_release_buffer(FLAC__BitWriter *bw);
  89846. /*
  89847. * write functions
  89848. */
  89849. FLAC__bool FLAC__bitwriter_write_zeroes(FLAC__BitWriter *bw, unsigned bits);
  89850. FLAC__bool FLAC__bitwriter_write_raw_uint32(FLAC__BitWriter *bw, FLAC__uint32 val, unsigned bits);
  89851. FLAC__bool FLAC__bitwriter_write_raw_int32(FLAC__BitWriter *bw, FLAC__int32 val, unsigned bits);
  89852. FLAC__bool FLAC__bitwriter_write_raw_uint64(FLAC__BitWriter *bw, FLAC__uint64 val, unsigned bits);
  89853. FLAC__bool FLAC__bitwriter_write_raw_uint32_little_endian(FLAC__BitWriter *bw, FLAC__uint32 val); /*only for bits=32*/
  89854. FLAC__bool FLAC__bitwriter_write_byte_block(FLAC__BitWriter *bw, const FLAC__byte vals[], unsigned nvals);
  89855. FLAC__bool FLAC__bitwriter_write_unary_unsigned(FLAC__BitWriter *bw, unsigned val);
  89856. unsigned FLAC__bitwriter_rice_bits(FLAC__int32 val, unsigned parameter);
  89857. #if 0 /* UNUSED */
  89858. unsigned FLAC__bitwriter_golomb_bits_signed(int val, unsigned parameter);
  89859. unsigned FLAC__bitwriter_golomb_bits_unsigned(unsigned val, unsigned parameter);
  89860. #endif
  89861. FLAC__bool FLAC__bitwriter_write_rice_signed(FLAC__BitWriter *bw, FLAC__int32 val, unsigned parameter);
  89862. FLAC__bool FLAC__bitwriter_write_rice_signed_block(FLAC__BitWriter *bw, const FLAC__int32 *vals, unsigned nvals, unsigned parameter);
  89863. #if 0 /* UNUSED */
  89864. FLAC__bool FLAC__bitwriter_write_golomb_signed(FLAC__BitWriter *bw, int val, unsigned parameter);
  89865. FLAC__bool FLAC__bitwriter_write_golomb_unsigned(FLAC__BitWriter *bw, unsigned val, unsigned parameter);
  89866. #endif
  89867. FLAC__bool FLAC__bitwriter_write_utf8_uint32(FLAC__BitWriter *bw, FLAC__uint32 val);
  89868. FLAC__bool FLAC__bitwriter_write_utf8_uint64(FLAC__BitWriter *bw, FLAC__uint64 val);
  89869. FLAC__bool FLAC__bitwriter_zero_pad_to_byte_boundary(FLAC__BitWriter *bw);
  89870. #endif
  89871. /********* End of inlined file: bitwriter.h *********/
  89872. /********* Start of inlined file: alloc.h *********/
  89873. #ifndef FLAC__SHARE__ALLOC_H
  89874. #define FLAC__SHARE__ALLOC_H
  89875. #if HAVE_CONFIG_H
  89876. # include <config.h>
  89877. #endif
  89878. /* WATCHOUT: for c++ you may have to #define __STDC_LIMIT_MACROS 1 real early
  89879. * before #including this file, otherwise SIZE_MAX might not be defined
  89880. */
  89881. #include <limits.h> /* for SIZE_MAX */
  89882. #if !defined _MSC_VER && !defined __MINGW32__ && !defined __EMX__
  89883. #include <stdint.h> /* for SIZE_MAX in case limits.h didn't get it */
  89884. #endif
  89885. #include <stdlib.h> /* for size_t, malloc(), etc */
  89886. #ifndef SIZE_MAX
  89887. # ifndef SIZE_T_MAX
  89888. # ifdef _MSC_VER
  89889. # define SIZE_T_MAX UINT_MAX
  89890. # else
  89891. # error
  89892. # endif
  89893. # endif
  89894. # define SIZE_MAX SIZE_T_MAX
  89895. #endif
  89896. #ifndef FLaC__INLINE
  89897. #define FLaC__INLINE
  89898. #endif
  89899. /* avoid malloc()ing 0 bytes, see:
  89900. * https://www.securecoding.cert.org/confluence/display/seccode/MEM04-A.+Do+not+make+assumptions+about+the+result+of+allocating+0+bytes?focusedCommentId=5407003
  89901. */
  89902. static FLaC__INLINE void *safe_malloc_(size_t size)
  89903. {
  89904. /* malloc(0) is undefined; FLAC src convention is to always allocate */
  89905. if(!size)
  89906. size++;
  89907. return malloc(size);
  89908. }
  89909. static FLaC__INLINE void *safe_calloc_(size_t nmemb, size_t size)
  89910. {
  89911. if(!nmemb || !size)
  89912. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  89913. return calloc(nmemb, size);
  89914. }
  89915. /*@@@@ there's probably a better way to prevent overflows when allocating untrusted sums but this works for now */
  89916. static FLaC__INLINE void *safe_malloc_add_2op_(size_t size1, size_t size2)
  89917. {
  89918. size2 += size1;
  89919. if(size2 < size1)
  89920. return 0;
  89921. return safe_malloc_(size2);
  89922. }
  89923. static FLaC__INLINE void *safe_malloc_add_3op_(size_t size1, size_t size2, size_t size3)
  89924. {
  89925. size2 += size1;
  89926. if(size2 < size1)
  89927. return 0;
  89928. size3 += size2;
  89929. if(size3 < size2)
  89930. return 0;
  89931. return safe_malloc_(size3);
  89932. }
  89933. static FLaC__INLINE void *safe_malloc_add_4op_(size_t size1, size_t size2, size_t size3, size_t size4)
  89934. {
  89935. size2 += size1;
  89936. if(size2 < size1)
  89937. return 0;
  89938. size3 += size2;
  89939. if(size3 < size2)
  89940. return 0;
  89941. size4 += size3;
  89942. if(size4 < size3)
  89943. return 0;
  89944. return safe_malloc_(size4);
  89945. }
  89946. static FLaC__INLINE void *safe_malloc_mul_2op_(size_t size1, size_t size2)
  89947. #if 0
  89948. needs support for cases where sizeof(size_t) != 4
  89949. {
  89950. /* could be faster #ifdef'ing off SIZEOF_SIZE_T */
  89951. if(sizeof(size_t) == 4) {
  89952. if ((double)size1 * (double)size2 < 4294967296.0)
  89953. return malloc(size1*size2);
  89954. }
  89955. return 0;
  89956. }
  89957. #else
  89958. /* better? */
  89959. {
  89960. if(!size1 || !size2)
  89961. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  89962. if(size1 > SIZE_MAX / size2)
  89963. return 0;
  89964. return malloc(size1*size2);
  89965. }
  89966. #endif
  89967. static FLaC__INLINE void *safe_malloc_mul_3op_(size_t size1, size_t size2, size_t size3)
  89968. {
  89969. if(!size1 || !size2 || !size3)
  89970. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  89971. if(size1 > SIZE_MAX / size2)
  89972. return 0;
  89973. size1 *= size2;
  89974. if(size1 > SIZE_MAX / size3)
  89975. return 0;
  89976. return malloc(size1*size3);
  89977. }
  89978. /* size1*size2 + size3 */
  89979. static FLaC__INLINE void *safe_malloc_mul2add_(size_t size1, size_t size2, size_t size3)
  89980. {
  89981. if(!size1 || !size2)
  89982. return safe_malloc_(size3);
  89983. if(size1 > SIZE_MAX / size2)
  89984. return 0;
  89985. return safe_malloc_add_2op_(size1*size2, size3);
  89986. }
  89987. /* size1 * (size2 + size3) */
  89988. static FLaC__INLINE void *safe_malloc_muladd2_(size_t size1, size_t size2, size_t size3)
  89989. {
  89990. if(!size1 || (!size2 && !size3))
  89991. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  89992. size2 += size3;
  89993. if(size2 < size3)
  89994. return 0;
  89995. return safe_malloc_mul_2op_(size1, size2);
  89996. }
  89997. static FLaC__INLINE void *safe_realloc_add_2op_(void *ptr, size_t size1, size_t size2)
  89998. {
  89999. size2 += size1;
  90000. if(size2 < size1)
  90001. return 0;
  90002. return realloc(ptr, size2);
  90003. }
  90004. static FLaC__INLINE void *safe_realloc_add_3op_(void *ptr, size_t size1, size_t size2, size_t size3)
  90005. {
  90006. size2 += size1;
  90007. if(size2 < size1)
  90008. return 0;
  90009. size3 += size2;
  90010. if(size3 < size2)
  90011. return 0;
  90012. return realloc(ptr, size3);
  90013. }
  90014. static FLaC__INLINE void *safe_realloc_add_4op_(void *ptr, size_t size1, size_t size2, size_t size3, size_t size4)
  90015. {
  90016. size2 += size1;
  90017. if(size2 < size1)
  90018. return 0;
  90019. size3 += size2;
  90020. if(size3 < size2)
  90021. return 0;
  90022. size4 += size3;
  90023. if(size4 < size3)
  90024. return 0;
  90025. return realloc(ptr, size4);
  90026. }
  90027. static FLaC__INLINE void *safe_realloc_mul_2op_(void *ptr, size_t size1, size_t size2)
  90028. {
  90029. if(!size1 || !size2)
  90030. return realloc(ptr, 0); /* preserve POSIX realloc(ptr, 0) semantics */
  90031. if(size1 > SIZE_MAX / size2)
  90032. return 0;
  90033. return realloc(ptr, size1*size2);
  90034. }
  90035. /* size1 * (size2 + size3) */
  90036. static FLaC__INLINE void *safe_realloc_muladd2_(void *ptr, size_t size1, size_t size2, size_t size3)
  90037. {
  90038. if(!size1 || (!size2 && !size3))
  90039. return realloc(ptr, 0); /* preserve POSIX realloc(ptr, 0) semantics */
  90040. size2 += size3;
  90041. if(size2 < size3)
  90042. return 0;
  90043. return safe_realloc_mul_2op_(ptr, size1, size2);
  90044. }
  90045. #endif
  90046. /********* End of inlined file: alloc.h *********/
  90047. /* Things should be fastest when this matches the machine word size */
  90048. /* WATCHOUT: if you change this you must also change the following #defines down to SWAP_BE_WORD_TO_HOST below to match */
  90049. /* WATCHOUT: there are a few places where the code will not work unless bwword is >= 32 bits wide */
  90050. typedef FLAC__uint32 bwword;
  90051. #define FLAC__BYTES_PER_WORD 4
  90052. #define FLAC__BITS_PER_WORD 32
  90053. #define FLAC__WORD_ALL_ONES ((FLAC__uint32)0xffffffff)
  90054. /* SWAP_BE_WORD_TO_HOST swaps bytes in a bwword (which is always big-endian) if necessary to match host byte order */
  90055. #if WORDS_BIGENDIAN
  90056. #define SWAP_BE_WORD_TO_HOST(x) (x)
  90057. #else
  90058. #ifdef _MSC_VER
  90059. #define SWAP_BE_WORD_TO_HOST(x) local_swap32_(x)
  90060. #else
  90061. #define SWAP_BE_WORD_TO_HOST(x) ntohl(x)
  90062. #endif
  90063. #endif
  90064. /*
  90065. * The default capacity here doesn't matter too much. The buffer always grows
  90066. * to hold whatever is written to it. Usually the encoder will stop adding at
  90067. * a frame or metadata block, then write that out and clear the buffer for the
  90068. * next one.
  90069. */
  90070. static const unsigned FLAC__BITWRITER_DEFAULT_CAPACITY = 32768u / sizeof(bwword); /* size in words */
  90071. /* When growing, increment 4K at a time */
  90072. static const unsigned FLAC__BITWRITER_DEFAULT_INCREMENT = 4096u / sizeof(bwword); /* size in words */
  90073. #define FLAC__WORDS_TO_BITS(words) ((words) * FLAC__BITS_PER_WORD)
  90074. #define FLAC__TOTAL_BITS(bw) (FLAC__WORDS_TO_BITS((bw)->words) + (bw)->bits)
  90075. #ifdef min
  90076. #undef min
  90077. #endif
  90078. #define min(x,y) ((x)<(y)?(x):(y))
  90079. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  90080. #ifdef _MSC_VER
  90081. #define FLAC__U64L(x) x
  90082. #else
  90083. #define FLAC__U64L(x) x##LLU
  90084. #endif
  90085. #ifndef FLaC__INLINE
  90086. #define FLaC__INLINE
  90087. #endif
  90088. struct FLAC__BitWriter {
  90089. bwword *buffer;
  90090. bwword accum; /* accumulator; bits are right-justified; when full, accum is appended to buffer */
  90091. unsigned capacity; /* capacity of buffer in words */
  90092. unsigned words; /* # of complete words in buffer */
  90093. unsigned bits; /* # of used bits in accum */
  90094. };
  90095. /* * WATCHOUT: The current implementation only grows the buffer. */
  90096. static FLAC__bool bitwriter_grow_(FLAC__BitWriter *bw, unsigned bits_to_add)
  90097. {
  90098. unsigned new_capacity;
  90099. bwword *new_buffer;
  90100. FLAC__ASSERT(0 != bw);
  90101. FLAC__ASSERT(0 != bw->buffer);
  90102. /* calculate total words needed to store 'bits_to_add' additional bits */
  90103. new_capacity = bw->words + ((bw->bits + bits_to_add + FLAC__BITS_PER_WORD - 1) / FLAC__BITS_PER_WORD);
  90104. /* it's possible (due to pessimism in the growth estimation that
  90105. * leads to this call) that we don't actually need to grow
  90106. */
  90107. if(bw->capacity >= new_capacity)
  90108. return true;
  90109. /* round up capacity increase to the nearest FLAC__BITWRITER_DEFAULT_INCREMENT */
  90110. if((new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT)
  90111. new_capacity += FLAC__BITWRITER_DEFAULT_INCREMENT - ((new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT);
  90112. /* make sure we got everything right */
  90113. FLAC__ASSERT(0 == (new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT);
  90114. FLAC__ASSERT(new_capacity > bw->capacity);
  90115. FLAC__ASSERT(new_capacity >= bw->words + ((bw->bits + bits_to_add + FLAC__BITS_PER_WORD - 1) / FLAC__BITS_PER_WORD));
  90116. new_buffer = (bwword*)safe_realloc_mul_2op_(bw->buffer, sizeof(bwword), /*times*/new_capacity);
  90117. if(new_buffer == 0)
  90118. return false;
  90119. bw->buffer = new_buffer;
  90120. bw->capacity = new_capacity;
  90121. return true;
  90122. }
  90123. /***********************************************************************
  90124. *
  90125. * Class constructor/destructor
  90126. *
  90127. ***********************************************************************/
  90128. FLAC__BitWriter *FLAC__bitwriter_new(void)
  90129. {
  90130. FLAC__BitWriter *bw = (FLAC__BitWriter*)calloc(1, sizeof(FLAC__BitWriter));
  90131. /* note that calloc() sets all members to 0 for us */
  90132. return bw;
  90133. }
  90134. void FLAC__bitwriter_delete(FLAC__BitWriter *bw)
  90135. {
  90136. FLAC__ASSERT(0 != bw);
  90137. FLAC__bitwriter_free(bw);
  90138. free(bw);
  90139. }
  90140. /***********************************************************************
  90141. *
  90142. * Public class methods
  90143. *
  90144. ***********************************************************************/
  90145. FLAC__bool FLAC__bitwriter_init(FLAC__BitWriter *bw)
  90146. {
  90147. FLAC__ASSERT(0 != bw);
  90148. bw->words = bw->bits = 0;
  90149. bw->capacity = FLAC__BITWRITER_DEFAULT_CAPACITY;
  90150. bw->buffer = (bwword*)malloc(sizeof(bwword) * bw->capacity);
  90151. if(bw->buffer == 0)
  90152. return false;
  90153. return true;
  90154. }
  90155. void FLAC__bitwriter_free(FLAC__BitWriter *bw)
  90156. {
  90157. FLAC__ASSERT(0 != bw);
  90158. if(0 != bw->buffer)
  90159. free(bw->buffer);
  90160. bw->buffer = 0;
  90161. bw->capacity = 0;
  90162. bw->words = bw->bits = 0;
  90163. }
  90164. void FLAC__bitwriter_clear(FLAC__BitWriter *bw)
  90165. {
  90166. bw->words = bw->bits = 0;
  90167. }
  90168. void FLAC__bitwriter_dump(const FLAC__BitWriter *bw, FILE *out)
  90169. {
  90170. unsigned i, j;
  90171. if(bw == 0) {
  90172. fprintf(out, "bitwriter is NULL\n");
  90173. }
  90174. else {
  90175. fprintf(out, "bitwriter: capacity=%u words=%u bits=%u total_bits=%u\n", bw->capacity, bw->words, bw->bits, FLAC__TOTAL_BITS(bw));
  90176. for(i = 0; i < bw->words; i++) {
  90177. fprintf(out, "%08X: ", i);
  90178. for(j = 0; j < FLAC__BITS_PER_WORD; j++)
  90179. fprintf(out, "%01u", bw->buffer[i] & (1 << (FLAC__BITS_PER_WORD-j-1)) ? 1:0);
  90180. fprintf(out, "\n");
  90181. }
  90182. if(bw->bits > 0) {
  90183. fprintf(out, "%08X: ", i);
  90184. for(j = 0; j < bw->bits; j++)
  90185. fprintf(out, "%01u", bw->accum & (1 << (bw->bits-j-1)) ? 1:0);
  90186. fprintf(out, "\n");
  90187. }
  90188. }
  90189. }
  90190. FLAC__bool FLAC__bitwriter_get_write_crc16(FLAC__BitWriter *bw, FLAC__uint16 *crc)
  90191. {
  90192. const FLAC__byte *buffer;
  90193. size_t bytes;
  90194. FLAC__ASSERT((bw->bits & 7) == 0); /* assert that we're byte-aligned */
  90195. if(!FLAC__bitwriter_get_buffer(bw, &buffer, &bytes))
  90196. return false;
  90197. *crc = (FLAC__uint16)FLAC__crc16(buffer, bytes);
  90198. FLAC__bitwriter_release_buffer(bw);
  90199. return true;
  90200. }
  90201. FLAC__bool FLAC__bitwriter_get_write_crc8(FLAC__BitWriter *bw, FLAC__byte *crc)
  90202. {
  90203. const FLAC__byte *buffer;
  90204. size_t bytes;
  90205. FLAC__ASSERT((bw->bits & 7) == 0); /* assert that we're byte-aligned */
  90206. if(!FLAC__bitwriter_get_buffer(bw, &buffer, &bytes))
  90207. return false;
  90208. *crc = FLAC__crc8(buffer, bytes);
  90209. FLAC__bitwriter_release_buffer(bw);
  90210. return true;
  90211. }
  90212. FLAC__bool FLAC__bitwriter_is_byte_aligned(const FLAC__BitWriter *bw)
  90213. {
  90214. return ((bw->bits & 7) == 0);
  90215. }
  90216. unsigned FLAC__bitwriter_get_input_bits_unconsumed(const FLAC__BitWriter *bw)
  90217. {
  90218. return FLAC__TOTAL_BITS(bw);
  90219. }
  90220. FLAC__bool FLAC__bitwriter_get_buffer(FLAC__BitWriter *bw, const FLAC__byte **buffer, size_t *bytes)
  90221. {
  90222. FLAC__ASSERT((bw->bits & 7) == 0);
  90223. /* double protection */
  90224. if(bw->bits & 7)
  90225. return false;
  90226. /* if we have bits in the accumulator we have to flush those to the buffer first */
  90227. if(bw->bits) {
  90228. FLAC__ASSERT(bw->words <= bw->capacity);
  90229. if(bw->words == bw->capacity && !bitwriter_grow_(bw, FLAC__BITS_PER_WORD))
  90230. return false;
  90231. /* append bits as complete word to buffer, but don't change bw->accum or bw->bits */
  90232. bw->buffer[bw->words] = SWAP_BE_WORD_TO_HOST(bw->accum << (FLAC__BITS_PER_WORD-bw->bits));
  90233. }
  90234. /* now we can just return what we have */
  90235. *buffer = (FLAC__byte*)bw->buffer;
  90236. *bytes = (FLAC__BYTES_PER_WORD * bw->words) + (bw->bits >> 3);
  90237. return true;
  90238. }
  90239. void FLAC__bitwriter_release_buffer(FLAC__BitWriter *bw)
  90240. {
  90241. /* nothing to do. in the future, strict checking of a 'writer-is-in-
  90242. * get-mode' flag could be added everywhere and then cleared here
  90243. */
  90244. (void)bw;
  90245. }
  90246. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_zeroes(FLAC__BitWriter *bw, unsigned bits)
  90247. {
  90248. unsigned n;
  90249. FLAC__ASSERT(0 != bw);
  90250. FLAC__ASSERT(0 != bw->buffer);
  90251. if(bits == 0)
  90252. return true;
  90253. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+bits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  90254. if(bw->capacity <= bw->words + bits && !bitwriter_grow_(bw, bits))
  90255. return false;
  90256. /* first part gets to word alignment */
  90257. if(bw->bits) {
  90258. n = min(FLAC__BITS_PER_WORD - bw->bits, bits);
  90259. bw->accum <<= n;
  90260. bits -= n;
  90261. bw->bits += n;
  90262. if(bw->bits == FLAC__BITS_PER_WORD) {
  90263. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  90264. bw->bits = 0;
  90265. }
  90266. else
  90267. return true;
  90268. }
  90269. /* do whole words */
  90270. while(bits >= FLAC__BITS_PER_WORD) {
  90271. bw->buffer[bw->words++] = 0;
  90272. bits -= FLAC__BITS_PER_WORD;
  90273. }
  90274. /* do any leftovers */
  90275. if(bits > 0) {
  90276. bw->accum = 0;
  90277. bw->bits = bits;
  90278. }
  90279. return true;
  90280. }
  90281. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint32(FLAC__BitWriter *bw, FLAC__uint32 val, unsigned bits)
  90282. {
  90283. register unsigned left;
  90284. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  90285. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  90286. FLAC__ASSERT(0 != bw);
  90287. FLAC__ASSERT(0 != bw->buffer);
  90288. FLAC__ASSERT(bits <= 32);
  90289. if(bits == 0)
  90290. return true;
  90291. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+bits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  90292. if(bw->capacity <= bw->words + bits && !bitwriter_grow_(bw, bits))
  90293. return false;
  90294. left = FLAC__BITS_PER_WORD - bw->bits;
  90295. if(bits < left) {
  90296. bw->accum <<= bits;
  90297. bw->accum |= val;
  90298. bw->bits += bits;
  90299. }
  90300. else if(bw->bits) { /* WATCHOUT: if bw->bits == 0, left==FLAC__BITS_PER_WORD and bw->accum<<=left is a NOP instead of setting to 0 */
  90301. bw->accum <<= left;
  90302. bw->accum |= val >> (bw->bits = bits - left);
  90303. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  90304. bw->accum = val;
  90305. }
  90306. else {
  90307. bw->accum = val;
  90308. bw->bits = 0;
  90309. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(val);
  90310. }
  90311. return true;
  90312. }
  90313. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_int32(FLAC__BitWriter *bw, FLAC__int32 val, unsigned bits)
  90314. {
  90315. /* zero-out unused bits */
  90316. if(bits < 32)
  90317. val &= (~(0xffffffff << bits));
  90318. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, bits);
  90319. }
  90320. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint64(FLAC__BitWriter *bw, FLAC__uint64 val, unsigned bits)
  90321. {
  90322. /* this could be a little faster but it's not used for much */
  90323. if(bits > 32) {
  90324. return
  90325. FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)(val>>32), bits-32) &&
  90326. FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, 32);
  90327. }
  90328. else
  90329. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, bits);
  90330. }
  90331. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint32_little_endian(FLAC__BitWriter *bw, FLAC__uint32 val)
  90332. {
  90333. /* this doesn't need to be that fast as currently it is only used for vorbis comments */
  90334. if(!FLAC__bitwriter_write_raw_uint32(bw, val & 0xff, 8))
  90335. return false;
  90336. if(!FLAC__bitwriter_write_raw_uint32(bw, (val>>8) & 0xff, 8))
  90337. return false;
  90338. if(!FLAC__bitwriter_write_raw_uint32(bw, (val>>16) & 0xff, 8))
  90339. return false;
  90340. if(!FLAC__bitwriter_write_raw_uint32(bw, val>>24, 8))
  90341. return false;
  90342. return true;
  90343. }
  90344. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_byte_block(FLAC__BitWriter *bw, const FLAC__byte vals[], unsigned nvals)
  90345. {
  90346. unsigned i;
  90347. /* this could be faster but currently we don't need it to be since it's only used for writing metadata */
  90348. for(i = 0; i < nvals; i++) {
  90349. if(!FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)(vals[i]), 8))
  90350. return false;
  90351. }
  90352. return true;
  90353. }
  90354. FLAC__bool FLAC__bitwriter_write_unary_unsigned(FLAC__BitWriter *bw, unsigned val)
  90355. {
  90356. if(val < 32)
  90357. return FLAC__bitwriter_write_raw_uint32(bw, 1, ++val);
  90358. else
  90359. return
  90360. FLAC__bitwriter_write_zeroes(bw, val) &&
  90361. FLAC__bitwriter_write_raw_uint32(bw, 1, 1);
  90362. }
  90363. unsigned FLAC__bitwriter_rice_bits(FLAC__int32 val, unsigned parameter)
  90364. {
  90365. FLAC__uint32 uval;
  90366. FLAC__ASSERT(parameter < sizeof(unsigned)*8);
  90367. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  90368. uval = (val<<1) ^ (val>>31);
  90369. return 1 + parameter + (uval >> parameter);
  90370. }
  90371. #if 0 /* UNUSED */
  90372. unsigned FLAC__bitwriter_golomb_bits_signed(int val, unsigned parameter)
  90373. {
  90374. unsigned bits, msbs, uval;
  90375. unsigned k;
  90376. FLAC__ASSERT(parameter > 0);
  90377. /* fold signed to unsigned */
  90378. if(val < 0)
  90379. uval = (unsigned)(((-(++val)) << 1) + 1);
  90380. else
  90381. uval = (unsigned)(val << 1);
  90382. k = FLAC__bitmath_ilog2(parameter);
  90383. if(parameter == 1u<<k) {
  90384. FLAC__ASSERT(k <= 30);
  90385. msbs = uval >> k;
  90386. bits = 1 + k + msbs;
  90387. }
  90388. else {
  90389. unsigned q, r, d;
  90390. d = (1 << (k+1)) - parameter;
  90391. q = uval / parameter;
  90392. r = uval - (q * parameter);
  90393. bits = 1 + q + k;
  90394. if(r >= d)
  90395. bits++;
  90396. }
  90397. return bits;
  90398. }
  90399. unsigned FLAC__bitwriter_golomb_bits_unsigned(unsigned uval, unsigned parameter)
  90400. {
  90401. unsigned bits, msbs;
  90402. unsigned k;
  90403. FLAC__ASSERT(parameter > 0);
  90404. k = FLAC__bitmath_ilog2(parameter);
  90405. if(parameter == 1u<<k) {
  90406. FLAC__ASSERT(k <= 30);
  90407. msbs = uval >> k;
  90408. bits = 1 + k + msbs;
  90409. }
  90410. else {
  90411. unsigned q, r, d;
  90412. d = (1 << (k+1)) - parameter;
  90413. q = uval / parameter;
  90414. r = uval - (q * parameter);
  90415. bits = 1 + q + k;
  90416. if(r >= d)
  90417. bits++;
  90418. }
  90419. return bits;
  90420. }
  90421. #endif /* UNUSED */
  90422. FLAC__bool FLAC__bitwriter_write_rice_signed(FLAC__BitWriter *bw, FLAC__int32 val, unsigned parameter)
  90423. {
  90424. unsigned total_bits, interesting_bits, msbs;
  90425. FLAC__uint32 uval, pattern;
  90426. FLAC__ASSERT(0 != bw);
  90427. FLAC__ASSERT(0 != bw->buffer);
  90428. FLAC__ASSERT(parameter < 8*sizeof(uval));
  90429. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  90430. uval = (val<<1) ^ (val>>31);
  90431. msbs = uval >> parameter;
  90432. interesting_bits = 1 + parameter;
  90433. total_bits = interesting_bits + msbs;
  90434. pattern = 1 << parameter; /* the unary end bit */
  90435. pattern |= (uval & ((1<<parameter)-1)); /* the binary LSBs */
  90436. if(total_bits <= 32)
  90437. return FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits);
  90438. else
  90439. return
  90440. FLAC__bitwriter_write_zeroes(bw, msbs) && /* write the unary MSBs */
  90441. FLAC__bitwriter_write_raw_uint32(bw, pattern, interesting_bits); /* write the unary end bit and binary LSBs */
  90442. }
  90443. FLAC__bool FLAC__bitwriter_write_rice_signed_block(FLAC__BitWriter *bw, const FLAC__int32 *vals, unsigned nvals, unsigned parameter)
  90444. {
  90445. const FLAC__uint32 mask1 = FLAC__WORD_ALL_ONES << parameter; /* we val|=mask1 to set the stop bit above it... */
  90446. const FLAC__uint32 mask2 = FLAC__WORD_ALL_ONES >> (31-parameter); /* ...then mask off the bits above the stop bit with val&=mask2*/
  90447. FLAC__uint32 uval;
  90448. unsigned left;
  90449. const unsigned lsbits = 1 + parameter;
  90450. unsigned msbits;
  90451. FLAC__ASSERT(0 != bw);
  90452. FLAC__ASSERT(0 != bw->buffer);
  90453. FLAC__ASSERT(parameter < 8*sizeof(bwword)-1);
  90454. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  90455. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  90456. while(nvals) {
  90457. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  90458. uval = (*vals<<1) ^ (*vals>>31);
  90459. msbits = uval >> parameter;
  90460. #if 0 /* OPT: can remove this special case if it doesn't make up for the extra compare (doesn't make a statistically significant difference with msvc or gcc/x86) */
  90461. if(bw->bits && bw->bits + msbits + lsbits <= FLAC__BITS_PER_WORD) { /* i.e. if the whole thing fits in the current bwword */
  90462. /* ^^^ if bw->bits is 0 then we may have filled the buffer and have no free bwword to work in */
  90463. bw->bits = bw->bits + msbits + lsbits;
  90464. uval |= mask1; /* set stop bit */
  90465. uval &= mask2; /* mask off unused top bits */
  90466. /* NOT: bw->accum <<= msbits + lsbits because msbits+lsbits could be 32, then the shift would be a NOP */
  90467. bw->accum <<= msbits;
  90468. bw->accum <<= lsbits;
  90469. bw->accum |= uval;
  90470. if(bw->bits == FLAC__BITS_PER_WORD) {
  90471. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  90472. bw->bits = 0;
  90473. /* burying the capacity check down here means we have to grow the buffer a little if there are more vals to do */
  90474. if(bw->capacity <= bw->words && nvals > 1 && !bitwriter_grow_(bw, 1)) {
  90475. FLAC__ASSERT(bw->capacity == bw->words);
  90476. return false;
  90477. }
  90478. }
  90479. }
  90480. else {
  90481. #elif 1 /*@@@@@@ OPT: try this version with MSVC6 to see if better, not much difference for gcc-4 */
  90482. if(bw->bits && bw->bits + msbits + lsbits < FLAC__BITS_PER_WORD) { /* i.e. if the whole thing fits in the current bwword */
  90483. /* ^^^ if bw->bits is 0 then we may have filled the buffer and have no free bwword to work in */
  90484. bw->bits = bw->bits + msbits + lsbits;
  90485. uval |= mask1; /* set stop bit */
  90486. uval &= mask2; /* mask off unused top bits */
  90487. bw->accum <<= msbits + lsbits;
  90488. bw->accum |= uval;
  90489. }
  90490. else {
  90491. #endif
  90492. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+msbits+lsbits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  90493. /* OPT: pessimism may cause flurry of false calls to grow_ which eat up all savings before it */
  90494. if(bw->capacity <= bw->words + bw->bits + msbits + 1/*lsbits always fit in 1 bwword*/ && !bitwriter_grow_(bw, msbits+lsbits))
  90495. return false;
  90496. if(msbits) {
  90497. /* first part gets to word alignment */
  90498. if(bw->bits) {
  90499. left = FLAC__BITS_PER_WORD - bw->bits;
  90500. if(msbits < left) {
  90501. bw->accum <<= msbits;
  90502. bw->bits += msbits;
  90503. goto break1;
  90504. }
  90505. else {
  90506. bw->accum <<= left;
  90507. msbits -= left;
  90508. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  90509. bw->bits = 0;
  90510. }
  90511. }
  90512. /* do whole words */
  90513. while(msbits >= FLAC__BITS_PER_WORD) {
  90514. bw->buffer[bw->words++] = 0;
  90515. msbits -= FLAC__BITS_PER_WORD;
  90516. }
  90517. /* do any leftovers */
  90518. if(msbits > 0) {
  90519. bw->accum = 0;
  90520. bw->bits = msbits;
  90521. }
  90522. }
  90523. break1:
  90524. uval |= mask1; /* set stop bit */
  90525. uval &= mask2; /* mask off unused top bits */
  90526. left = FLAC__BITS_PER_WORD - bw->bits;
  90527. if(lsbits < left) {
  90528. bw->accum <<= lsbits;
  90529. bw->accum |= uval;
  90530. bw->bits += lsbits;
  90531. }
  90532. else {
  90533. /* if bw->bits == 0, left==FLAC__BITS_PER_WORD which will always
  90534. * be > lsbits (because of previous assertions) so it would have
  90535. * triggered the (lsbits<left) case above.
  90536. */
  90537. FLAC__ASSERT(bw->bits);
  90538. FLAC__ASSERT(left < FLAC__BITS_PER_WORD);
  90539. bw->accum <<= left;
  90540. bw->accum |= uval >> (bw->bits = lsbits - left);
  90541. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  90542. bw->accum = uval;
  90543. }
  90544. #if 1
  90545. }
  90546. #endif
  90547. vals++;
  90548. nvals--;
  90549. }
  90550. return true;
  90551. }
  90552. #if 0 /* UNUSED */
  90553. FLAC__bool FLAC__bitwriter_write_golomb_signed(FLAC__BitWriter *bw, int val, unsigned parameter)
  90554. {
  90555. unsigned total_bits, msbs, uval;
  90556. unsigned k;
  90557. FLAC__ASSERT(0 != bw);
  90558. FLAC__ASSERT(0 != bw->buffer);
  90559. FLAC__ASSERT(parameter > 0);
  90560. /* fold signed to unsigned */
  90561. if(val < 0)
  90562. uval = (unsigned)(((-(++val)) << 1) + 1);
  90563. else
  90564. uval = (unsigned)(val << 1);
  90565. k = FLAC__bitmath_ilog2(parameter);
  90566. if(parameter == 1u<<k) {
  90567. unsigned pattern;
  90568. FLAC__ASSERT(k <= 30);
  90569. msbs = uval >> k;
  90570. total_bits = 1 + k + msbs;
  90571. pattern = 1 << k; /* the unary end bit */
  90572. pattern |= (uval & ((1u<<k)-1)); /* the binary LSBs */
  90573. if(total_bits <= 32) {
  90574. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits))
  90575. return false;
  90576. }
  90577. else {
  90578. /* write the unary MSBs */
  90579. if(!FLAC__bitwriter_write_zeroes(bw, msbs))
  90580. return false;
  90581. /* write the unary end bit and binary LSBs */
  90582. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, k+1))
  90583. return false;
  90584. }
  90585. }
  90586. else {
  90587. unsigned q, r, d;
  90588. d = (1 << (k+1)) - parameter;
  90589. q = uval / parameter;
  90590. r = uval - (q * parameter);
  90591. /* write the unary MSBs */
  90592. if(!FLAC__bitwriter_write_zeroes(bw, q))
  90593. return false;
  90594. /* write the unary end bit */
  90595. if(!FLAC__bitwriter_write_raw_uint32(bw, 1, 1))
  90596. return false;
  90597. /* write the binary LSBs */
  90598. if(r >= d) {
  90599. if(!FLAC__bitwriter_write_raw_uint32(bw, r+d, k+1))
  90600. return false;
  90601. }
  90602. else {
  90603. if(!FLAC__bitwriter_write_raw_uint32(bw, r, k))
  90604. return false;
  90605. }
  90606. }
  90607. return true;
  90608. }
  90609. FLAC__bool FLAC__bitwriter_write_golomb_unsigned(FLAC__BitWriter *bw, unsigned uval, unsigned parameter)
  90610. {
  90611. unsigned total_bits, msbs;
  90612. unsigned k;
  90613. FLAC__ASSERT(0 != bw);
  90614. FLAC__ASSERT(0 != bw->buffer);
  90615. FLAC__ASSERT(parameter > 0);
  90616. k = FLAC__bitmath_ilog2(parameter);
  90617. if(parameter == 1u<<k) {
  90618. unsigned pattern;
  90619. FLAC__ASSERT(k <= 30);
  90620. msbs = uval >> k;
  90621. total_bits = 1 + k + msbs;
  90622. pattern = 1 << k; /* the unary end bit */
  90623. pattern |= (uval & ((1u<<k)-1)); /* the binary LSBs */
  90624. if(total_bits <= 32) {
  90625. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits))
  90626. return false;
  90627. }
  90628. else {
  90629. /* write the unary MSBs */
  90630. if(!FLAC__bitwriter_write_zeroes(bw, msbs))
  90631. return false;
  90632. /* write the unary end bit and binary LSBs */
  90633. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, k+1))
  90634. return false;
  90635. }
  90636. }
  90637. else {
  90638. unsigned q, r, d;
  90639. d = (1 << (k+1)) - parameter;
  90640. q = uval / parameter;
  90641. r = uval - (q * parameter);
  90642. /* write the unary MSBs */
  90643. if(!FLAC__bitwriter_write_zeroes(bw, q))
  90644. return false;
  90645. /* write the unary end bit */
  90646. if(!FLAC__bitwriter_write_raw_uint32(bw, 1, 1))
  90647. return false;
  90648. /* write the binary LSBs */
  90649. if(r >= d) {
  90650. if(!FLAC__bitwriter_write_raw_uint32(bw, r+d, k+1))
  90651. return false;
  90652. }
  90653. else {
  90654. if(!FLAC__bitwriter_write_raw_uint32(bw, r, k))
  90655. return false;
  90656. }
  90657. }
  90658. return true;
  90659. }
  90660. #endif /* UNUSED */
  90661. FLAC__bool FLAC__bitwriter_write_utf8_uint32(FLAC__BitWriter *bw, FLAC__uint32 val)
  90662. {
  90663. FLAC__bool ok = 1;
  90664. FLAC__ASSERT(0 != bw);
  90665. FLAC__ASSERT(0 != bw->buffer);
  90666. FLAC__ASSERT(!(val & 0x80000000)); /* this version only handles 31 bits */
  90667. if(val < 0x80) {
  90668. return FLAC__bitwriter_write_raw_uint32(bw, val, 8);
  90669. }
  90670. else if(val < 0x800) {
  90671. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xC0 | (val>>6), 8);
  90672. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  90673. }
  90674. else if(val < 0x10000) {
  90675. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xE0 | (val>>12), 8);
  90676. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  90677. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  90678. }
  90679. else if(val < 0x200000) {
  90680. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF0 | (val>>18), 8);
  90681. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  90682. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  90683. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  90684. }
  90685. else if(val < 0x4000000) {
  90686. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF8 | (val>>24), 8);
  90687. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>18)&0x3F), 8);
  90688. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  90689. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  90690. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  90691. }
  90692. else {
  90693. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFC | (val>>30), 8);
  90694. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>24)&0x3F), 8);
  90695. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>18)&0x3F), 8);
  90696. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  90697. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  90698. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  90699. }
  90700. return ok;
  90701. }
  90702. FLAC__bool FLAC__bitwriter_write_utf8_uint64(FLAC__BitWriter *bw, FLAC__uint64 val)
  90703. {
  90704. FLAC__bool ok = 1;
  90705. FLAC__ASSERT(0 != bw);
  90706. FLAC__ASSERT(0 != bw->buffer);
  90707. FLAC__ASSERT(!(val & FLAC__U64L(0xFFFFFFF000000000))); /* this version only handles 36 bits */
  90708. if(val < 0x80) {
  90709. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, 8);
  90710. }
  90711. else if(val < 0x800) {
  90712. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xC0 | (FLAC__uint32)(val>>6), 8);
  90713. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  90714. }
  90715. else if(val < 0x10000) {
  90716. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xE0 | (FLAC__uint32)(val>>12), 8);
  90717. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  90718. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  90719. }
  90720. else if(val < 0x200000) {
  90721. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF0 | (FLAC__uint32)(val>>18), 8);
  90722. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  90723. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  90724. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  90725. }
  90726. else if(val < 0x4000000) {
  90727. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF8 | (FLAC__uint32)(val>>24), 8);
  90728. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  90729. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  90730. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  90731. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  90732. }
  90733. else if(val < 0x80000000) {
  90734. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFC | (FLAC__uint32)(val>>30), 8);
  90735. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>24)&0x3F), 8);
  90736. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  90737. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  90738. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  90739. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  90740. }
  90741. else {
  90742. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFE, 8);
  90743. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>30)&0x3F), 8);
  90744. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>24)&0x3F), 8);
  90745. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  90746. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  90747. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  90748. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  90749. }
  90750. return ok;
  90751. }
  90752. FLAC__bool FLAC__bitwriter_zero_pad_to_byte_boundary(FLAC__BitWriter *bw)
  90753. {
  90754. /* 0-pad to byte boundary */
  90755. if(bw->bits & 7u)
  90756. return FLAC__bitwriter_write_zeroes(bw, 8 - (bw->bits & 7u));
  90757. else
  90758. return true;
  90759. }
  90760. #endif
  90761. /********* End of inlined file: bitwriter.c *********/
  90762. /********* Start of inlined file: cpu.c *********/
  90763. /********* Start of inlined file: juce_FlacHeader.h *********/
  90764. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  90765. // tasks..
  90766. #define VERSION "1.2.1"
  90767. #define FLAC__NO_DLL 1
  90768. #ifdef _MSC_VER
  90769. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  90770. #endif
  90771. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  90772. #define FLAC__SYS_DARWIN 1
  90773. #endif
  90774. /********* End of inlined file: juce_FlacHeader.h *********/
  90775. #if JUCE_USE_FLAC
  90776. #if HAVE_CONFIG_H
  90777. # include <config.h>
  90778. #endif
  90779. #include <stdlib.h>
  90780. #include <stdio.h>
  90781. #if defined FLAC__CPU_IA32
  90782. # include <signal.h>
  90783. #elif defined FLAC__CPU_PPC
  90784. # if !defined FLAC__NO_ASM
  90785. # if defined FLAC__SYS_DARWIN
  90786. # include <sys/sysctl.h>
  90787. # include <mach/mach.h>
  90788. # include <mach/mach_host.h>
  90789. # include <mach/host_info.h>
  90790. # include <mach/machine.h>
  90791. # ifndef CPU_SUBTYPE_POWERPC_970
  90792. # define CPU_SUBTYPE_POWERPC_970 ((cpu_subtype_t) 100)
  90793. # endif
  90794. # else /* FLAC__SYS_DARWIN */
  90795. # include <signal.h>
  90796. # include <setjmp.h>
  90797. static sigjmp_buf jmpbuf;
  90798. static volatile sig_atomic_t canjump = 0;
  90799. static void sigill_handler (int sig)
  90800. {
  90801. if (!canjump) {
  90802. signal (sig, SIG_DFL);
  90803. raise (sig);
  90804. }
  90805. canjump = 0;
  90806. siglongjmp (jmpbuf, 1);
  90807. }
  90808. # endif /* FLAC__SYS_DARWIN */
  90809. # endif /* FLAC__NO_ASM */
  90810. #endif /* FLAC__CPU_PPC */
  90811. #if defined (__NetBSD__) || defined(__OpenBSD__)
  90812. #include <sys/param.h>
  90813. #include <sys/sysctl.h>
  90814. #include <machine/cpu.h>
  90815. #endif
  90816. #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
  90817. #include <sys/types.h>
  90818. #include <sys/sysctl.h>
  90819. #endif
  90820. #if defined(__APPLE__)
  90821. /* how to get sysctlbyname()? */
  90822. #endif
  90823. /* these are flags in EDX of CPUID AX=00000001 */
  90824. static const unsigned FLAC__CPUINFO_IA32_CPUID_CMOV = 0x00008000;
  90825. static const unsigned FLAC__CPUINFO_IA32_CPUID_MMX = 0x00800000;
  90826. static const unsigned FLAC__CPUINFO_IA32_CPUID_FXSR = 0x01000000;
  90827. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE = 0x02000000;
  90828. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE2 = 0x04000000;
  90829. /* these are flags in ECX of CPUID AX=00000001 */
  90830. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE3 = 0x00000001;
  90831. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSSE3 = 0x00000200;
  90832. /* these are flags in EDX of CPUID AX=80000001 */
  90833. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_3DNOW = 0x80000000;
  90834. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXT3DNOW = 0x40000000;
  90835. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXTMMX = 0x00400000;
  90836. /*
  90837. * Extra stuff needed for detection of OS support for SSE on IA-32
  90838. */
  90839. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM && !defined FLAC__NO_SSE_OS && !defined FLAC__SSE_OS
  90840. # if defined(__linux__)
  90841. /*
  90842. * If the OS doesn't support SSE, we will get here with a SIGILL. We
  90843. * modify the return address to jump over the offending SSE instruction
  90844. * and also the operation following it that indicates the instruction
  90845. * executed successfully. In this way we use no global variables and
  90846. * stay thread-safe.
  90847. *
  90848. * 3 + 3 + 6:
  90849. * 3 bytes for "xorps xmm0,xmm0"
  90850. * 3 bytes for estimate of how long the follwing "inc var" instruction is
  90851. * 6 bytes extra in case our estimate is wrong
  90852. * 12 bytes puts us in the NOP "landing zone"
  90853. */
  90854. # undef USE_OBSOLETE_SIGCONTEXT_FLAVOR /* #define this to use the older signal handler method */
  90855. # ifdef USE_OBSOLETE_SIGCONTEXT_FLAVOR
  90856. static void sigill_handler_sse_os(int signal, struct sigcontext sc)
  90857. {
  90858. (void)signal;
  90859. sc.eip += 3 + 3 + 6;
  90860. }
  90861. # else
  90862. # include <sys/ucontext.h>
  90863. static void sigill_handler_sse_os(int signal, siginfo_t *si, void *uc)
  90864. {
  90865. (void)signal, (void)si;
  90866. ((ucontext_t*)uc)->uc_mcontext.gregs[14/*REG_EIP*/] += 3 + 3 + 6;
  90867. }
  90868. # endif
  90869. # elif defined(_MSC_VER)
  90870. # include <windows.h>
  90871. # undef USE_TRY_CATCH_FLAVOR /* #define this to use the try/catch method for catching illegal opcode exception */
  90872. # ifdef USE_TRY_CATCH_FLAVOR
  90873. # else
  90874. LONG CALLBACK sigill_handler_sse_os(EXCEPTION_POINTERS *ep)
  90875. {
  90876. if(ep->ExceptionRecord->ExceptionCode == EXCEPTION_ILLEGAL_INSTRUCTION) {
  90877. ep->ContextRecord->Eip += 3 + 3 + 6;
  90878. return EXCEPTION_CONTINUE_EXECUTION;
  90879. }
  90880. return EXCEPTION_CONTINUE_SEARCH;
  90881. }
  90882. # endif
  90883. # endif
  90884. #endif
  90885. void FLAC__cpu_info(FLAC__CPUInfo *info)
  90886. {
  90887. /*
  90888. * IA32-specific
  90889. */
  90890. #ifdef FLAC__CPU_IA32
  90891. info->type = FLAC__CPUINFO_TYPE_IA32;
  90892. #if !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  90893. info->use_asm = true; /* we assume a minimum of 80386 with FLAC__CPU_IA32 */
  90894. info->data.ia32.cpuid = FLAC__cpu_have_cpuid_asm_ia32()? true : false;
  90895. info->data.ia32.bswap = info->data.ia32.cpuid; /* CPUID => BSWAP since it came after */
  90896. info->data.ia32.cmov = false;
  90897. info->data.ia32.mmx = false;
  90898. info->data.ia32.fxsr = false;
  90899. info->data.ia32.sse = false;
  90900. info->data.ia32.sse2 = false;
  90901. info->data.ia32.sse3 = false;
  90902. info->data.ia32.ssse3 = false;
  90903. info->data.ia32._3dnow = false;
  90904. info->data.ia32.ext3dnow = false;
  90905. info->data.ia32.extmmx = false;
  90906. if(info->data.ia32.cpuid) {
  90907. /* http://www.sandpile.org/ia32/cpuid.htm */
  90908. FLAC__uint32 flags_edx, flags_ecx;
  90909. FLAC__cpu_info_asm_ia32(&flags_edx, &flags_ecx);
  90910. info->data.ia32.cmov = (flags_edx & FLAC__CPUINFO_IA32_CPUID_CMOV )? true : false;
  90911. info->data.ia32.mmx = (flags_edx & FLAC__CPUINFO_IA32_CPUID_MMX )? true : false;
  90912. info->data.ia32.fxsr = (flags_edx & FLAC__CPUINFO_IA32_CPUID_FXSR )? true : false;
  90913. info->data.ia32.sse = (flags_edx & FLAC__CPUINFO_IA32_CPUID_SSE )? true : false;
  90914. info->data.ia32.sse2 = (flags_edx & FLAC__CPUINFO_IA32_CPUID_SSE2 )? true : false;
  90915. info->data.ia32.sse3 = (flags_ecx & FLAC__CPUINFO_IA32_CPUID_SSE3 )? true : false;
  90916. info->data.ia32.ssse3 = (flags_ecx & FLAC__CPUINFO_IA32_CPUID_SSSE3)? true : false;
  90917. #ifdef FLAC__USE_3DNOW
  90918. flags_edx = FLAC__cpu_info_extended_amd_asm_ia32();
  90919. info->data.ia32._3dnow = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_3DNOW )? true : false;
  90920. info->data.ia32.ext3dnow = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXT3DNOW)? true : false;
  90921. info->data.ia32.extmmx = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXTMMX )? true : false;
  90922. #else
  90923. info->data.ia32._3dnow = info->data.ia32.ext3dnow = info->data.ia32.extmmx = false;
  90924. #endif
  90925. #ifdef DEBUG
  90926. fprintf(stderr, "CPU info (IA-32):\n");
  90927. fprintf(stderr, " CPUID ...... %c\n", info->data.ia32.cpuid ? 'Y' : 'n');
  90928. fprintf(stderr, " BSWAP ...... %c\n", info->data.ia32.bswap ? 'Y' : 'n');
  90929. fprintf(stderr, " CMOV ....... %c\n", info->data.ia32.cmov ? 'Y' : 'n');
  90930. fprintf(stderr, " MMX ........ %c\n", info->data.ia32.mmx ? 'Y' : 'n');
  90931. fprintf(stderr, " FXSR ....... %c\n", info->data.ia32.fxsr ? 'Y' : 'n');
  90932. fprintf(stderr, " SSE ........ %c\n", info->data.ia32.sse ? 'Y' : 'n');
  90933. fprintf(stderr, " SSE2 ....... %c\n", info->data.ia32.sse2 ? 'Y' : 'n');
  90934. fprintf(stderr, " SSE3 ....... %c\n", info->data.ia32.sse3 ? 'Y' : 'n');
  90935. fprintf(stderr, " SSSE3 ...... %c\n", info->data.ia32.ssse3 ? 'Y' : 'n');
  90936. fprintf(stderr, " 3DNow! ..... %c\n", info->data.ia32._3dnow ? 'Y' : 'n');
  90937. fprintf(stderr, " 3DNow!-ext . %c\n", info->data.ia32.ext3dnow? 'Y' : 'n');
  90938. fprintf(stderr, " 3DNow!-MMX . %c\n", info->data.ia32.extmmx ? 'Y' : 'n');
  90939. #endif
  90940. /*
  90941. * now have to check for OS support of SSE/SSE2
  90942. */
  90943. if(info->data.ia32.fxsr || info->data.ia32.sse || info->data.ia32.sse2) {
  90944. #if defined FLAC__NO_SSE_OS
  90945. /* assume user knows better than us; turn it off */
  90946. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  90947. #elif defined FLAC__SSE_OS
  90948. /* assume user knows better than us; leave as detected above */
  90949. #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__) || defined(__APPLE__)
  90950. int sse = 0;
  90951. size_t len;
  90952. /* at least one of these must work: */
  90953. len = sizeof(sse); sse = sse || (sysctlbyname("hw.instruction_sse", &sse, &len, NULL, 0) == 0 && sse);
  90954. len = sizeof(sse); sse = sse || (sysctlbyname("hw.optional.sse" , &sse, &len, NULL, 0) == 0 && sse); /* __APPLE__ ? */
  90955. if(!sse)
  90956. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  90957. #elif defined(__NetBSD__) || defined (__OpenBSD__)
  90958. # if __NetBSD_Version__ >= 105250000 || (defined __OpenBSD__)
  90959. int val = 0, mib[2] = { CTL_MACHDEP, CPU_SSE };
  90960. size_t len = sizeof(val);
  90961. if(sysctl(mib, 2, &val, &len, NULL, 0) < 0 || !val)
  90962. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  90963. else { /* double-check SSE2 */
  90964. mib[1] = CPU_SSE2;
  90965. len = sizeof(val);
  90966. if(sysctl(mib, 2, &val, &len, NULL, 0) < 0 || !val)
  90967. info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  90968. }
  90969. # else
  90970. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  90971. # endif
  90972. #elif defined(__linux__)
  90973. int sse = 0;
  90974. struct sigaction sigill_save;
  90975. #ifdef USE_OBSOLETE_SIGCONTEXT_FLAVOR
  90976. if(0 == sigaction(SIGILL, NULL, &sigill_save) && signal(SIGILL, (void (*)(int))sigill_handler_sse_os) != SIG_ERR)
  90977. #else
  90978. struct sigaction sigill_sse;
  90979. sigill_sse.sa_sigaction = sigill_handler_sse_os;
  90980. __sigemptyset(&sigill_sse.sa_mask);
  90981. sigill_sse.sa_flags = SA_SIGINFO | SA_RESETHAND; /* SA_RESETHAND just in case our SIGILL return jump breaks, so we don't get stuck in a loop */
  90982. if(0 == sigaction(SIGILL, &sigill_sse, &sigill_save))
  90983. #endif
  90984. {
  90985. /* http://www.ibiblio.org/gferg/ldp/GCC-Inline-Assembly-HOWTO.html */
  90986. /* see sigill_handler_sse_os() for an explanation of the following: */
  90987. asm volatile (
  90988. "xorl %0,%0\n\t" /* for some reason, still need to do this to clear 'sse' var */
  90989. "xorps %%xmm0,%%xmm0\n\t" /* will cause SIGILL if unsupported by OS */
  90990. "incl %0\n\t" /* SIGILL handler will jump over this */
  90991. /* landing zone */
  90992. "nop\n\t" /* SIGILL jump lands here if "inc" is 9 bytes */
  90993. "nop\n\t"
  90994. "nop\n\t"
  90995. "nop\n\t"
  90996. "nop\n\t"
  90997. "nop\n\t"
  90998. "nop\n\t" /* SIGILL jump lands here if "inc" is 3 bytes (expected) */
  90999. "nop\n\t"
  91000. "nop" /* SIGILL jump lands here if "inc" is 1 byte */
  91001. : "=r"(sse)
  91002. : "r"(sse)
  91003. );
  91004. sigaction(SIGILL, &sigill_save, NULL);
  91005. }
  91006. if(!sse)
  91007. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  91008. #elif defined(_MSC_VER)
  91009. # ifdef USE_TRY_CATCH_FLAVOR
  91010. _try {
  91011. __asm {
  91012. # if _MSC_VER <= 1200
  91013. /* VC6 assembler doesn't know SSE, have to emit bytecode instead */
  91014. _emit 0x0F
  91015. _emit 0x57
  91016. _emit 0xC0
  91017. # else
  91018. xorps xmm0,xmm0
  91019. # endif
  91020. }
  91021. }
  91022. _except(EXCEPTION_EXECUTE_HANDLER) {
  91023. if (_exception_code() == STATUS_ILLEGAL_INSTRUCTION)
  91024. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  91025. }
  91026. # else
  91027. int sse = 0;
  91028. LPTOP_LEVEL_EXCEPTION_FILTER save = SetUnhandledExceptionFilter(sigill_handler_sse_os);
  91029. /* see GCC version above for explanation */
  91030. /* http://msdn2.microsoft.com/en-us/library/4ks26t93.aspx */
  91031. /* http://www.codeproject.com/cpp/gccasm.asp */
  91032. /* http://www.hick.org/~mmiller/msvc_inline_asm.html */
  91033. __asm {
  91034. # if _MSC_VER <= 1200
  91035. /* VC6 assembler doesn't know SSE, have to emit bytecode instead */
  91036. _emit 0x0F
  91037. _emit 0x57
  91038. _emit 0xC0
  91039. # else
  91040. xorps xmm0,xmm0
  91041. # endif
  91042. inc sse
  91043. nop
  91044. nop
  91045. nop
  91046. nop
  91047. nop
  91048. nop
  91049. nop
  91050. nop
  91051. nop
  91052. }
  91053. SetUnhandledExceptionFilter(save);
  91054. if(!sse)
  91055. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  91056. # endif
  91057. #else
  91058. /* no way to test, disable to be safe */
  91059. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  91060. #endif
  91061. #ifdef DEBUG
  91062. fprintf(stderr, " SSE OS sup . %c\n", info->data.ia32.sse ? 'Y' : 'n');
  91063. #endif
  91064. }
  91065. }
  91066. #else
  91067. info->use_asm = false;
  91068. #endif
  91069. /*
  91070. * PPC-specific
  91071. */
  91072. #elif defined FLAC__CPU_PPC
  91073. info->type = FLAC__CPUINFO_TYPE_PPC;
  91074. # if !defined FLAC__NO_ASM
  91075. info->use_asm = true;
  91076. # ifdef FLAC__USE_ALTIVEC
  91077. # if defined FLAC__SYS_DARWIN
  91078. {
  91079. int val = 0, mib[2] = { CTL_HW, HW_VECTORUNIT };
  91080. size_t len = sizeof(val);
  91081. info->data.ppc.altivec = !(sysctl(mib, 2, &val, &len, NULL, 0) || !val);
  91082. }
  91083. {
  91084. host_basic_info_data_t hostInfo;
  91085. mach_msg_type_number_t infoCount;
  91086. infoCount = HOST_BASIC_INFO_COUNT;
  91087. host_info(mach_host_self(), HOST_BASIC_INFO, (host_info_t)&hostInfo, &infoCount);
  91088. info->data.ppc.ppc64 = (hostInfo.cpu_type == CPU_TYPE_POWERPC) && (hostInfo.cpu_subtype == CPU_SUBTYPE_POWERPC_970);
  91089. }
  91090. # else /* FLAC__USE_ALTIVEC && !FLAC__SYS_DARWIN */
  91091. {
  91092. /* no Darwin, do it the brute-force way */
  91093. /* @@@@@@ this is not thread-safe; replace with SSE OS method above or remove */
  91094. info->data.ppc.altivec = 0;
  91095. info->data.ppc.ppc64 = 0;
  91096. signal (SIGILL, sigill_handler);
  91097. canjump = 0;
  91098. if (!sigsetjmp (jmpbuf, 1)) {
  91099. canjump = 1;
  91100. asm volatile (
  91101. "mtspr 256, %0\n\t"
  91102. "vand %%v0, %%v0, %%v0"
  91103. :
  91104. : "r" (-1)
  91105. );
  91106. info->data.ppc.altivec = 1;
  91107. }
  91108. canjump = 0;
  91109. if (!sigsetjmp (jmpbuf, 1)) {
  91110. int x = 0;
  91111. canjump = 1;
  91112. /* PPC64 hardware implements the cntlzd instruction */
  91113. asm volatile ("cntlzd %0, %1" : "=r" (x) : "r" (x) );
  91114. info->data.ppc.ppc64 = 1;
  91115. }
  91116. signal (SIGILL, SIG_DFL); /*@@@@@@ should save and restore old signal */
  91117. }
  91118. # endif
  91119. # else /* !FLAC__USE_ALTIVEC */
  91120. info->data.ppc.altivec = 0;
  91121. info->data.ppc.ppc64 = 0;
  91122. # endif
  91123. # else
  91124. info->use_asm = false;
  91125. # endif
  91126. /*
  91127. * unknown CPI
  91128. */
  91129. #else
  91130. info->type = FLAC__CPUINFO_TYPE_UNKNOWN;
  91131. info->use_asm = false;
  91132. #endif
  91133. }
  91134. #endif
  91135. /********* End of inlined file: cpu.c *********/
  91136. /********* Start of inlined file: crc.c *********/
  91137. /********* Start of inlined file: juce_FlacHeader.h *********/
  91138. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  91139. // tasks..
  91140. #define VERSION "1.2.1"
  91141. #define FLAC__NO_DLL 1
  91142. #ifdef _MSC_VER
  91143. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  91144. #endif
  91145. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  91146. #define FLAC__SYS_DARWIN 1
  91147. #endif
  91148. /********* End of inlined file: juce_FlacHeader.h *********/
  91149. #if JUCE_USE_FLAC
  91150. #if HAVE_CONFIG_H
  91151. # include <config.h>
  91152. #endif
  91153. /* CRC-8, poly = x^8 + x^2 + x^1 + x^0, init = 0 */
  91154. FLAC__byte const FLAC__crc8_table[256] = {
  91155. 0x00, 0x07, 0x0E, 0x09, 0x1C, 0x1B, 0x12, 0x15,
  91156. 0x38, 0x3F, 0x36, 0x31, 0x24, 0x23, 0x2A, 0x2D,
  91157. 0x70, 0x77, 0x7E, 0x79, 0x6C, 0x6B, 0x62, 0x65,
  91158. 0x48, 0x4F, 0x46, 0x41, 0x54, 0x53, 0x5A, 0x5D,
  91159. 0xE0, 0xE7, 0xEE, 0xE9, 0xFC, 0xFB, 0xF2, 0xF5,
  91160. 0xD8, 0xDF, 0xD6, 0xD1, 0xC4, 0xC3, 0xCA, 0xCD,
  91161. 0x90, 0x97, 0x9E, 0x99, 0x8C, 0x8B, 0x82, 0x85,
  91162. 0xA8, 0xAF, 0xA6, 0xA1, 0xB4, 0xB3, 0xBA, 0xBD,
  91163. 0xC7, 0xC0, 0xC9, 0xCE, 0xDB, 0xDC, 0xD5, 0xD2,
  91164. 0xFF, 0xF8, 0xF1, 0xF6, 0xE3, 0xE4, 0xED, 0xEA,
  91165. 0xB7, 0xB0, 0xB9, 0xBE, 0xAB, 0xAC, 0xA5, 0xA2,
  91166. 0x8F, 0x88, 0x81, 0x86, 0x93, 0x94, 0x9D, 0x9A,
  91167. 0x27, 0x20, 0x29, 0x2E, 0x3B, 0x3C, 0x35, 0x32,
  91168. 0x1F, 0x18, 0x11, 0x16, 0x03, 0x04, 0x0D, 0x0A,
  91169. 0x57, 0x50, 0x59, 0x5E, 0x4B, 0x4C, 0x45, 0x42,
  91170. 0x6F, 0x68, 0x61, 0x66, 0x73, 0x74, 0x7D, 0x7A,
  91171. 0x89, 0x8E, 0x87, 0x80, 0x95, 0x92, 0x9B, 0x9C,
  91172. 0xB1, 0xB6, 0xBF, 0xB8, 0xAD, 0xAA, 0xA3, 0xA4,
  91173. 0xF9, 0xFE, 0xF7, 0xF0, 0xE5, 0xE2, 0xEB, 0xEC,
  91174. 0xC1, 0xC6, 0xCF, 0xC8, 0xDD, 0xDA, 0xD3, 0xD4,
  91175. 0x69, 0x6E, 0x67, 0x60, 0x75, 0x72, 0x7B, 0x7C,
  91176. 0x51, 0x56, 0x5F, 0x58, 0x4D, 0x4A, 0x43, 0x44,
  91177. 0x19, 0x1E, 0x17, 0x10, 0x05, 0x02, 0x0B, 0x0C,
  91178. 0x21, 0x26, 0x2F, 0x28, 0x3D, 0x3A, 0x33, 0x34,
  91179. 0x4E, 0x49, 0x40, 0x47, 0x52, 0x55, 0x5C, 0x5B,
  91180. 0x76, 0x71, 0x78, 0x7F, 0x6A, 0x6D, 0x64, 0x63,
  91181. 0x3E, 0x39, 0x30, 0x37, 0x22, 0x25, 0x2C, 0x2B,
  91182. 0x06, 0x01, 0x08, 0x0F, 0x1A, 0x1D, 0x14, 0x13,
  91183. 0xAE, 0xA9, 0xA0, 0xA7, 0xB2, 0xB5, 0xBC, 0xBB,
  91184. 0x96, 0x91, 0x98, 0x9F, 0x8A, 0x8D, 0x84, 0x83,
  91185. 0xDE, 0xD9, 0xD0, 0xD7, 0xC2, 0xC5, 0xCC, 0xCB,
  91186. 0xE6, 0xE1, 0xE8, 0xEF, 0xFA, 0xFD, 0xF4, 0xF3
  91187. };
  91188. /* CRC-16, poly = x^16 + x^15 + x^2 + x^0, init = 0 */
  91189. unsigned FLAC__crc16_table[256] = {
  91190. 0x0000, 0x8005, 0x800f, 0x000a, 0x801b, 0x001e, 0x0014, 0x8011,
  91191. 0x8033, 0x0036, 0x003c, 0x8039, 0x0028, 0x802d, 0x8027, 0x0022,
  91192. 0x8063, 0x0066, 0x006c, 0x8069, 0x0078, 0x807d, 0x8077, 0x0072,
  91193. 0x0050, 0x8055, 0x805f, 0x005a, 0x804b, 0x004e, 0x0044, 0x8041,
  91194. 0x80c3, 0x00c6, 0x00cc, 0x80c9, 0x00d8, 0x80dd, 0x80d7, 0x00d2,
  91195. 0x00f0, 0x80f5, 0x80ff, 0x00fa, 0x80eb, 0x00ee, 0x00e4, 0x80e1,
  91196. 0x00a0, 0x80a5, 0x80af, 0x00aa, 0x80bb, 0x00be, 0x00b4, 0x80b1,
  91197. 0x8093, 0x0096, 0x009c, 0x8099, 0x0088, 0x808d, 0x8087, 0x0082,
  91198. 0x8183, 0x0186, 0x018c, 0x8189, 0x0198, 0x819d, 0x8197, 0x0192,
  91199. 0x01b0, 0x81b5, 0x81bf, 0x01ba, 0x81ab, 0x01ae, 0x01a4, 0x81a1,
  91200. 0x01e0, 0x81e5, 0x81ef, 0x01ea, 0x81fb, 0x01fe, 0x01f4, 0x81f1,
  91201. 0x81d3, 0x01d6, 0x01dc, 0x81d9, 0x01c8, 0x81cd, 0x81c7, 0x01c2,
  91202. 0x0140, 0x8145, 0x814f, 0x014a, 0x815b, 0x015e, 0x0154, 0x8151,
  91203. 0x8173, 0x0176, 0x017c, 0x8179, 0x0168, 0x816d, 0x8167, 0x0162,
  91204. 0x8123, 0x0126, 0x012c, 0x8129, 0x0138, 0x813d, 0x8137, 0x0132,
  91205. 0x0110, 0x8115, 0x811f, 0x011a, 0x810b, 0x010e, 0x0104, 0x8101,
  91206. 0x8303, 0x0306, 0x030c, 0x8309, 0x0318, 0x831d, 0x8317, 0x0312,
  91207. 0x0330, 0x8335, 0x833f, 0x033a, 0x832b, 0x032e, 0x0324, 0x8321,
  91208. 0x0360, 0x8365, 0x836f, 0x036a, 0x837b, 0x037e, 0x0374, 0x8371,
  91209. 0x8353, 0x0356, 0x035c, 0x8359, 0x0348, 0x834d, 0x8347, 0x0342,
  91210. 0x03c0, 0x83c5, 0x83cf, 0x03ca, 0x83db, 0x03de, 0x03d4, 0x83d1,
  91211. 0x83f3, 0x03f6, 0x03fc, 0x83f9, 0x03e8, 0x83ed, 0x83e7, 0x03e2,
  91212. 0x83a3, 0x03a6, 0x03ac, 0x83a9, 0x03b8, 0x83bd, 0x83b7, 0x03b2,
  91213. 0x0390, 0x8395, 0x839f, 0x039a, 0x838b, 0x038e, 0x0384, 0x8381,
  91214. 0x0280, 0x8285, 0x828f, 0x028a, 0x829b, 0x029e, 0x0294, 0x8291,
  91215. 0x82b3, 0x02b6, 0x02bc, 0x82b9, 0x02a8, 0x82ad, 0x82a7, 0x02a2,
  91216. 0x82e3, 0x02e6, 0x02ec, 0x82e9, 0x02f8, 0x82fd, 0x82f7, 0x02f2,
  91217. 0x02d0, 0x82d5, 0x82df, 0x02da, 0x82cb, 0x02ce, 0x02c4, 0x82c1,
  91218. 0x8243, 0x0246, 0x024c, 0x8249, 0x0258, 0x825d, 0x8257, 0x0252,
  91219. 0x0270, 0x8275, 0x827f, 0x027a, 0x826b, 0x026e, 0x0264, 0x8261,
  91220. 0x0220, 0x8225, 0x822f, 0x022a, 0x823b, 0x023e, 0x0234, 0x8231,
  91221. 0x8213, 0x0216, 0x021c, 0x8219, 0x0208, 0x820d, 0x8207, 0x0202
  91222. };
  91223. void FLAC__crc8_update(const FLAC__byte data, FLAC__uint8 *crc)
  91224. {
  91225. *crc = FLAC__crc8_table[*crc ^ data];
  91226. }
  91227. void FLAC__crc8_update_block(const FLAC__byte *data, unsigned len, FLAC__uint8 *crc)
  91228. {
  91229. while(len--)
  91230. *crc = FLAC__crc8_table[*crc ^ *data++];
  91231. }
  91232. FLAC__uint8 FLAC__crc8(const FLAC__byte *data, unsigned len)
  91233. {
  91234. FLAC__uint8 crc = 0;
  91235. while(len--)
  91236. crc = FLAC__crc8_table[crc ^ *data++];
  91237. return crc;
  91238. }
  91239. unsigned FLAC__crc16(const FLAC__byte *data, unsigned len)
  91240. {
  91241. unsigned crc = 0;
  91242. while(len--)
  91243. crc = ((crc<<8) ^ FLAC__crc16_table[(crc>>8) ^ *data++]) & 0xffff;
  91244. return crc;
  91245. }
  91246. #endif
  91247. /********* End of inlined file: crc.c *********/
  91248. /********* Start of inlined file: fixed.c *********/
  91249. /********* Start of inlined file: juce_FlacHeader.h *********/
  91250. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  91251. // tasks..
  91252. #define VERSION "1.2.1"
  91253. #define FLAC__NO_DLL 1
  91254. #ifdef _MSC_VER
  91255. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  91256. #endif
  91257. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  91258. #define FLAC__SYS_DARWIN 1
  91259. #endif
  91260. /********* End of inlined file: juce_FlacHeader.h *********/
  91261. #if JUCE_USE_FLAC
  91262. #if HAVE_CONFIG_H
  91263. # include <config.h>
  91264. #endif
  91265. #include <math.h>
  91266. #include <string.h>
  91267. /********* Start of inlined file: fixed.h *********/
  91268. #ifndef FLAC__PRIVATE__FIXED_H
  91269. #define FLAC__PRIVATE__FIXED_H
  91270. #ifdef HAVE_CONFIG_H
  91271. #include <config.h>
  91272. #endif
  91273. /********* Start of inlined file: float.h *********/
  91274. #ifndef FLAC__PRIVATE__FLOAT_H
  91275. #define FLAC__PRIVATE__FLOAT_H
  91276. #ifdef HAVE_CONFIG_H
  91277. #include <config.h>
  91278. #endif
  91279. /*
  91280. * These typedefs make it easier to ensure that integer versions of
  91281. * the library really only contain integer operations. All the code
  91282. * in libFLAC should use FLAC__float and FLAC__double in place of
  91283. * float and double, and be protected by checks of the macro
  91284. * FLAC__INTEGER_ONLY_LIBRARY.
  91285. *
  91286. * FLAC__real is the basic floating point type used in LPC analysis.
  91287. */
  91288. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  91289. typedef double FLAC__double;
  91290. typedef float FLAC__float;
  91291. /*
  91292. * WATCHOUT: changing FLAC__real will change the signatures of many
  91293. * functions that have assembly language equivalents and break them.
  91294. */
  91295. typedef float FLAC__real;
  91296. #else
  91297. /*
  91298. * The convention for FLAC__fixedpoint is to use the upper 16 bits
  91299. * for the integer part and lower 16 bits for the fractional part.
  91300. */
  91301. typedef FLAC__int32 FLAC__fixedpoint;
  91302. extern const FLAC__fixedpoint FLAC__FP_ZERO;
  91303. extern const FLAC__fixedpoint FLAC__FP_ONE_HALF;
  91304. extern const FLAC__fixedpoint FLAC__FP_ONE;
  91305. extern const FLAC__fixedpoint FLAC__FP_LN2;
  91306. extern const FLAC__fixedpoint FLAC__FP_E;
  91307. #define FLAC__fixedpoint_trunc(x) ((x)>>16)
  91308. #define FLAC__fixedpoint_mul(x, y) ( (FLAC__fixedpoint) ( ((FLAC__int64)(x)*(FLAC__int64)(y)) >> 16 ) )
  91309. #define FLAC__fixedpoint_div(x, y) ( (FLAC__fixedpoint) ( ( ((FLAC__int64)(x)<<32) / (FLAC__int64)(y) ) >> 16 ) )
  91310. /*
  91311. * FLAC__fixedpoint_log2()
  91312. * --------------------------------------------------------------------
  91313. * Returns the base-2 logarithm of the fixed-point number 'x' using an
  91314. * algorithm by Knuth for x >= 1.0
  91315. *
  91316. * 'fracbits' is the number of fractional bits of 'x'. 'fracbits' must
  91317. * be < 32 and evenly divisible by 4 (0 is OK but not very precise).
  91318. *
  91319. * 'precision' roughly limits the number of iterations that are done;
  91320. * use (unsigned)(-1) for maximum precision.
  91321. *
  91322. * If 'x' is less than one -- that is, x < (1<<fracbits) -- then this
  91323. * function will punt and return 0.
  91324. *
  91325. * The return value will also have 'fracbits' fractional bits.
  91326. */
  91327. FLAC__uint32 FLAC__fixedpoint_log2(FLAC__uint32 x, unsigned fracbits, unsigned precision);
  91328. #endif
  91329. #endif
  91330. /********* End of inlined file: float.h *********/
  91331. /********* Start of inlined file: format.h *********/
  91332. #ifndef FLAC__PRIVATE__FORMAT_H
  91333. #define FLAC__PRIVATE__FORMAT_H
  91334. unsigned FLAC__format_get_max_rice_partition_order(unsigned blocksize, unsigned predictor_order);
  91335. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize(unsigned blocksize);
  91336. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(unsigned limit, unsigned blocksize, unsigned predictor_order);
  91337. void FLAC__format_entropy_coding_method_partitioned_rice_contents_init(FLAC__EntropyCodingMethod_PartitionedRiceContents *object);
  91338. void FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(FLAC__EntropyCodingMethod_PartitionedRiceContents *object);
  91339. FLAC__bool FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(FLAC__EntropyCodingMethod_PartitionedRiceContents *object, unsigned max_partition_order);
  91340. #endif
  91341. /********* End of inlined file: format.h *********/
  91342. /*
  91343. * FLAC__fixed_compute_best_predictor()
  91344. * --------------------------------------------------------------------
  91345. * Compute the best fixed predictor and the expected bits-per-sample
  91346. * of the residual signal for each order. The _wide() version uses
  91347. * 64-bit integers which is statistically necessary when bits-per-
  91348. * sample + log2(blocksize) > 30
  91349. *
  91350. * IN data[0,data_len-1]
  91351. * IN data_len
  91352. * OUT residual_bits_per_sample[0,FLAC__MAX_FIXED_ORDER]
  91353. */
  91354. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  91355. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  91356. # ifndef FLAC__NO_ASM
  91357. # ifdef FLAC__CPU_IA32
  91358. # ifdef FLAC__HAS_NASM
  91359. unsigned FLAC__fixed_compute_best_predictor_asm_ia32_mmx_cmov(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  91360. # endif
  91361. # endif
  91362. # endif
  91363. unsigned FLAC__fixed_compute_best_predictor_wide(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  91364. #else
  91365. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  91366. unsigned FLAC__fixed_compute_best_predictor_wide(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  91367. #endif
  91368. /*
  91369. * FLAC__fixed_compute_residual()
  91370. * --------------------------------------------------------------------
  91371. * Compute the residual signal obtained from sutracting the predicted
  91372. * signal from the original.
  91373. *
  91374. * IN data[-order,data_len-1] original signal (NOTE THE INDICES!)
  91375. * IN data_len length of original signal
  91376. * IN order <= FLAC__MAX_FIXED_ORDER fixed-predictor order
  91377. * OUT residual[0,data_len-1] residual signal
  91378. */
  91379. void FLAC__fixed_compute_residual(const FLAC__int32 data[], unsigned data_len, unsigned order, FLAC__int32 residual[]);
  91380. /*
  91381. * FLAC__fixed_restore_signal()
  91382. * --------------------------------------------------------------------
  91383. * Restore the original signal by summing the residual and the
  91384. * predictor.
  91385. *
  91386. * IN residual[0,data_len-1] residual signal
  91387. * IN data_len length of original signal
  91388. * IN order <= FLAC__MAX_FIXED_ORDER fixed-predictor order
  91389. * *** IMPORTANT: the caller must pass in the historical samples:
  91390. * IN data[-order,-1] previously-reconstructed historical samples
  91391. * OUT data[0,data_len-1] original signal
  91392. */
  91393. void FLAC__fixed_restore_signal(const FLAC__int32 residual[], unsigned data_len, unsigned order, FLAC__int32 data[]);
  91394. #endif
  91395. /********* End of inlined file: fixed.h *********/
  91396. #ifndef M_LN2
  91397. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  91398. #define M_LN2 0.69314718055994530942
  91399. #endif
  91400. #ifdef min
  91401. #undef min
  91402. #endif
  91403. #define min(x,y) ((x) < (y)? (x) : (y))
  91404. #ifdef local_abs
  91405. #undef local_abs
  91406. #endif
  91407. #define local_abs(x) ((unsigned)((x)<0? -(x) : (x)))
  91408. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  91409. /* rbps stands for residual bits per sample
  91410. *
  91411. * (ln(2) * err)
  91412. * rbps = log (-----------)
  91413. * 2 ( n )
  91414. */
  91415. static FLAC__fixedpoint local__compute_rbps_integerized(FLAC__uint32 err, FLAC__uint32 n)
  91416. {
  91417. FLAC__uint32 rbps;
  91418. unsigned bits; /* the number of bits required to represent a number */
  91419. int fracbits; /* the number of bits of rbps that comprise the fractional part */
  91420. FLAC__ASSERT(sizeof(rbps) == sizeof(FLAC__fixedpoint));
  91421. FLAC__ASSERT(err > 0);
  91422. FLAC__ASSERT(n > 0);
  91423. FLAC__ASSERT(n <= FLAC__MAX_BLOCK_SIZE);
  91424. if(err <= n)
  91425. return 0;
  91426. /*
  91427. * The above two things tell us 1) n fits in 16 bits; 2) err/n > 1.
  91428. * These allow us later to know we won't lose too much precision in the
  91429. * fixed-point division (err<<fracbits)/n.
  91430. */
  91431. fracbits = (8*sizeof(err)) - (FLAC__bitmath_ilog2(err)+1);
  91432. err <<= fracbits;
  91433. err /= n;
  91434. /* err now holds err/n with fracbits fractional bits */
  91435. /*
  91436. * Whittle err down to 16 bits max. 16 significant bits is enough for
  91437. * our purposes.
  91438. */
  91439. FLAC__ASSERT(err > 0);
  91440. bits = FLAC__bitmath_ilog2(err)+1;
  91441. if(bits > 16) {
  91442. err >>= (bits-16);
  91443. fracbits -= (bits-16);
  91444. }
  91445. rbps = (FLAC__uint32)err;
  91446. /* Multiply by fixed-point version of ln(2), with 16 fractional bits */
  91447. rbps *= FLAC__FP_LN2;
  91448. fracbits += 16;
  91449. FLAC__ASSERT(fracbits >= 0);
  91450. /* FLAC__fixedpoint_log2 requires fracbits%4 to be 0 */
  91451. {
  91452. const int f = fracbits & 3;
  91453. if(f) {
  91454. rbps >>= f;
  91455. fracbits -= f;
  91456. }
  91457. }
  91458. rbps = FLAC__fixedpoint_log2(rbps, fracbits, (unsigned)(-1));
  91459. if(rbps == 0)
  91460. return 0;
  91461. /*
  91462. * The return value must have 16 fractional bits. Since the whole part
  91463. * of the base-2 log of a 32 bit number must fit in 5 bits, and fracbits
  91464. * must be >= -3, these assertion allows us to be able to shift rbps
  91465. * left if necessary to get 16 fracbits without losing any bits of the
  91466. * whole part of rbps.
  91467. *
  91468. * There is a slight chance due to accumulated error that the whole part
  91469. * will require 6 bits, so we use 6 in the assertion. Really though as
  91470. * long as it fits in 13 bits (32 - (16 - (-3))) we are fine.
  91471. */
  91472. FLAC__ASSERT((int)FLAC__bitmath_ilog2(rbps)+1 <= fracbits + 6);
  91473. FLAC__ASSERT(fracbits >= -3);
  91474. /* now shift the decimal point into place */
  91475. if(fracbits < 16)
  91476. return rbps << (16-fracbits);
  91477. else if(fracbits > 16)
  91478. return rbps >> (fracbits-16);
  91479. else
  91480. return rbps;
  91481. }
  91482. static FLAC__fixedpoint local__compute_rbps_wide_integerized(FLAC__uint64 err, FLAC__uint32 n)
  91483. {
  91484. FLAC__uint32 rbps;
  91485. unsigned bits; /* the number of bits required to represent a number */
  91486. int fracbits; /* the number of bits of rbps that comprise the fractional part */
  91487. FLAC__ASSERT(sizeof(rbps) == sizeof(FLAC__fixedpoint));
  91488. FLAC__ASSERT(err > 0);
  91489. FLAC__ASSERT(n > 0);
  91490. FLAC__ASSERT(n <= FLAC__MAX_BLOCK_SIZE);
  91491. if(err <= n)
  91492. return 0;
  91493. /*
  91494. * The above two things tell us 1) n fits in 16 bits; 2) err/n > 1.
  91495. * These allow us later to know we won't lose too much precision in the
  91496. * fixed-point division (err<<fracbits)/n.
  91497. */
  91498. fracbits = (8*sizeof(err)) - (FLAC__bitmath_ilog2_wide(err)+1);
  91499. err <<= fracbits;
  91500. err /= n;
  91501. /* err now holds err/n with fracbits fractional bits */
  91502. /*
  91503. * Whittle err down to 16 bits max. 16 significant bits is enough for
  91504. * our purposes.
  91505. */
  91506. FLAC__ASSERT(err > 0);
  91507. bits = FLAC__bitmath_ilog2_wide(err)+1;
  91508. if(bits > 16) {
  91509. err >>= (bits-16);
  91510. fracbits -= (bits-16);
  91511. }
  91512. rbps = (FLAC__uint32)err;
  91513. /* Multiply by fixed-point version of ln(2), with 16 fractional bits */
  91514. rbps *= FLAC__FP_LN2;
  91515. fracbits += 16;
  91516. FLAC__ASSERT(fracbits >= 0);
  91517. /* FLAC__fixedpoint_log2 requires fracbits%4 to be 0 */
  91518. {
  91519. const int f = fracbits & 3;
  91520. if(f) {
  91521. rbps >>= f;
  91522. fracbits -= f;
  91523. }
  91524. }
  91525. rbps = FLAC__fixedpoint_log2(rbps, fracbits, (unsigned)(-1));
  91526. if(rbps == 0)
  91527. return 0;
  91528. /*
  91529. * The return value must have 16 fractional bits. Since the whole part
  91530. * of the base-2 log of a 32 bit number must fit in 5 bits, and fracbits
  91531. * must be >= -3, these assertion allows us to be able to shift rbps
  91532. * left if necessary to get 16 fracbits without losing any bits of the
  91533. * whole part of rbps.
  91534. *
  91535. * There is a slight chance due to accumulated error that the whole part
  91536. * will require 6 bits, so we use 6 in the assertion. Really though as
  91537. * long as it fits in 13 bits (32 - (16 - (-3))) we are fine.
  91538. */
  91539. FLAC__ASSERT((int)FLAC__bitmath_ilog2(rbps)+1 <= fracbits + 6);
  91540. FLAC__ASSERT(fracbits >= -3);
  91541. /* now shift the decimal point into place */
  91542. if(fracbits < 16)
  91543. return rbps << (16-fracbits);
  91544. else if(fracbits > 16)
  91545. return rbps >> (fracbits-16);
  91546. else
  91547. return rbps;
  91548. }
  91549. #endif
  91550. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  91551. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1])
  91552. #else
  91553. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1])
  91554. #endif
  91555. {
  91556. FLAC__int32 last_error_0 = data[-1];
  91557. FLAC__int32 last_error_1 = data[-1] - data[-2];
  91558. FLAC__int32 last_error_2 = last_error_1 - (data[-2] - data[-3]);
  91559. FLAC__int32 last_error_3 = last_error_2 - (data[-2] - 2*data[-3] + data[-4]);
  91560. FLAC__int32 error, save;
  91561. FLAC__uint32 total_error_0 = 0, total_error_1 = 0, total_error_2 = 0, total_error_3 = 0, total_error_4 = 0;
  91562. unsigned i, order;
  91563. for(i = 0; i < data_len; i++) {
  91564. error = data[i] ; total_error_0 += local_abs(error); save = error;
  91565. error -= last_error_0; total_error_1 += local_abs(error); last_error_0 = save; save = error;
  91566. error -= last_error_1; total_error_2 += local_abs(error); last_error_1 = save; save = error;
  91567. error -= last_error_2; total_error_3 += local_abs(error); last_error_2 = save; save = error;
  91568. error -= last_error_3; total_error_4 += local_abs(error); last_error_3 = save;
  91569. }
  91570. if(total_error_0 < min(min(min(total_error_1, total_error_2), total_error_3), total_error_4))
  91571. order = 0;
  91572. else if(total_error_1 < min(min(total_error_2, total_error_3), total_error_4))
  91573. order = 1;
  91574. else if(total_error_2 < min(total_error_3, total_error_4))
  91575. order = 2;
  91576. else if(total_error_3 < total_error_4)
  91577. order = 3;
  91578. else
  91579. order = 4;
  91580. /* Estimate the expected number of bits per residual signal sample. */
  91581. /* 'total_error*' is linearly related to the variance of the residual */
  91582. /* signal, so we use it directly to compute E(|x|) */
  91583. FLAC__ASSERT(data_len > 0 || total_error_0 == 0);
  91584. FLAC__ASSERT(data_len > 0 || total_error_1 == 0);
  91585. FLAC__ASSERT(data_len > 0 || total_error_2 == 0);
  91586. FLAC__ASSERT(data_len > 0 || total_error_3 == 0);
  91587. FLAC__ASSERT(data_len > 0 || total_error_4 == 0);
  91588. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  91589. residual_bits_per_sample[0] = (FLAC__float)((total_error_0 > 0) ? log(M_LN2 * (FLAC__double)total_error_0 / (FLAC__double)data_len) / M_LN2 : 0.0);
  91590. residual_bits_per_sample[1] = (FLAC__float)((total_error_1 > 0) ? log(M_LN2 * (FLAC__double)total_error_1 / (FLAC__double)data_len) / M_LN2 : 0.0);
  91591. residual_bits_per_sample[2] = (FLAC__float)((total_error_2 > 0) ? log(M_LN2 * (FLAC__double)total_error_2 / (FLAC__double)data_len) / M_LN2 : 0.0);
  91592. residual_bits_per_sample[3] = (FLAC__float)((total_error_3 > 0) ? log(M_LN2 * (FLAC__double)total_error_3 / (FLAC__double)data_len) / M_LN2 : 0.0);
  91593. residual_bits_per_sample[4] = (FLAC__float)((total_error_4 > 0) ? log(M_LN2 * (FLAC__double)total_error_4 / (FLAC__double)data_len) / M_LN2 : 0.0);
  91594. #else
  91595. residual_bits_per_sample[0] = (total_error_0 > 0) ? local__compute_rbps_integerized(total_error_0, data_len) : 0;
  91596. residual_bits_per_sample[1] = (total_error_1 > 0) ? local__compute_rbps_integerized(total_error_1, data_len) : 0;
  91597. residual_bits_per_sample[2] = (total_error_2 > 0) ? local__compute_rbps_integerized(total_error_2, data_len) : 0;
  91598. residual_bits_per_sample[3] = (total_error_3 > 0) ? local__compute_rbps_integerized(total_error_3, data_len) : 0;
  91599. residual_bits_per_sample[4] = (total_error_4 > 0) ? local__compute_rbps_integerized(total_error_4, data_len) : 0;
  91600. #endif
  91601. return order;
  91602. }
  91603. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  91604. unsigned FLAC__fixed_compute_best_predictor_wide(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1])
  91605. #else
  91606. unsigned FLAC__fixed_compute_best_predictor_wide(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1])
  91607. #endif
  91608. {
  91609. FLAC__int32 last_error_0 = data[-1];
  91610. FLAC__int32 last_error_1 = data[-1] - data[-2];
  91611. FLAC__int32 last_error_2 = last_error_1 - (data[-2] - data[-3]);
  91612. FLAC__int32 last_error_3 = last_error_2 - (data[-2] - 2*data[-3] + data[-4]);
  91613. FLAC__int32 error, save;
  91614. /* total_error_* are 64-bits to avoid overflow when encoding
  91615. * erratic signals when the bits-per-sample and blocksize are
  91616. * large.
  91617. */
  91618. FLAC__uint64 total_error_0 = 0, total_error_1 = 0, total_error_2 = 0, total_error_3 = 0, total_error_4 = 0;
  91619. unsigned i, order;
  91620. for(i = 0; i < data_len; i++) {
  91621. error = data[i] ; total_error_0 += local_abs(error); save = error;
  91622. error -= last_error_0; total_error_1 += local_abs(error); last_error_0 = save; save = error;
  91623. error -= last_error_1; total_error_2 += local_abs(error); last_error_1 = save; save = error;
  91624. error -= last_error_2; total_error_3 += local_abs(error); last_error_2 = save; save = error;
  91625. error -= last_error_3; total_error_4 += local_abs(error); last_error_3 = save;
  91626. }
  91627. if(total_error_0 < min(min(min(total_error_1, total_error_2), total_error_3), total_error_4))
  91628. order = 0;
  91629. else if(total_error_1 < min(min(total_error_2, total_error_3), total_error_4))
  91630. order = 1;
  91631. else if(total_error_2 < min(total_error_3, total_error_4))
  91632. order = 2;
  91633. else if(total_error_3 < total_error_4)
  91634. order = 3;
  91635. else
  91636. order = 4;
  91637. /* Estimate the expected number of bits per residual signal sample. */
  91638. /* 'total_error*' is linearly related to the variance of the residual */
  91639. /* signal, so we use it directly to compute E(|x|) */
  91640. FLAC__ASSERT(data_len > 0 || total_error_0 == 0);
  91641. FLAC__ASSERT(data_len > 0 || total_error_1 == 0);
  91642. FLAC__ASSERT(data_len > 0 || total_error_2 == 0);
  91643. FLAC__ASSERT(data_len > 0 || total_error_3 == 0);
  91644. FLAC__ASSERT(data_len > 0 || total_error_4 == 0);
  91645. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  91646. #if defined _MSC_VER || defined __MINGW32__
  91647. /* with MSVC you have to spoon feed it the casting */
  91648. residual_bits_per_sample[0] = (FLAC__float)((total_error_0 > 0) ? log(M_LN2 * (FLAC__double)(FLAC__int64)total_error_0 / (FLAC__double)data_len) / M_LN2 : 0.0);
  91649. residual_bits_per_sample[1] = (FLAC__float)((total_error_1 > 0) ? log(M_LN2 * (FLAC__double)(FLAC__int64)total_error_1 / (FLAC__double)data_len) / M_LN2 : 0.0);
  91650. residual_bits_per_sample[2] = (FLAC__float)((total_error_2 > 0) ? log(M_LN2 * (FLAC__double)(FLAC__int64)total_error_2 / (FLAC__double)data_len) / M_LN2 : 0.0);
  91651. residual_bits_per_sample[3] = (FLAC__float)((total_error_3 > 0) ? log(M_LN2 * (FLAC__double)(FLAC__int64)total_error_3 / (FLAC__double)data_len) / M_LN2 : 0.0);
  91652. residual_bits_per_sample[4] = (FLAC__float)((total_error_4 > 0) ? log(M_LN2 * (FLAC__double)(FLAC__int64)total_error_4 / (FLAC__double)data_len) / M_LN2 : 0.0);
  91653. #else
  91654. residual_bits_per_sample[0] = (FLAC__float)((total_error_0 > 0) ? log(M_LN2 * (FLAC__double)total_error_0 / (FLAC__double)data_len) / M_LN2 : 0.0);
  91655. residual_bits_per_sample[1] = (FLAC__float)((total_error_1 > 0) ? log(M_LN2 * (FLAC__double)total_error_1 / (FLAC__double)data_len) / M_LN2 : 0.0);
  91656. residual_bits_per_sample[2] = (FLAC__float)((total_error_2 > 0) ? log(M_LN2 * (FLAC__double)total_error_2 / (FLAC__double)data_len) / M_LN2 : 0.0);
  91657. residual_bits_per_sample[3] = (FLAC__float)((total_error_3 > 0) ? log(M_LN2 * (FLAC__double)total_error_3 / (FLAC__double)data_len) / M_LN2 : 0.0);
  91658. residual_bits_per_sample[4] = (FLAC__float)((total_error_4 > 0) ? log(M_LN2 * (FLAC__double)total_error_4 / (FLAC__double)data_len) / M_LN2 : 0.0);
  91659. #endif
  91660. #else
  91661. residual_bits_per_sample[0] = (total_error_0 > 0) ? local__compute_rbps_wide_integerized(total_error_0, data_len) : 0;
  91662. residual_bits_per_sample[1] = (total_error_1 > 0) ? local__compute_rbps_wide_integerized(total_error_1, data_len) : 0;
  91663. residual_bits_per_sample[2] = (total_error_2 > 0) ? local__compute_rbps_wide_integerized(total_error_2, data_len) : 0;
  91664. residual_bits_per_sample[3] = (total_error_3 > 0) ? local__compute_rbps_wide_integerized(total_error_3, data_len) : 0;
  91665. residual_bits_per_sample[4] = (total_error_4 > 0) ? local__compute_rbps_wide_integerized(total_error_4, data_len) : 0;
  91666. #endif
  91667. return order;
  91668. }
  91669. void FLAC__fixed_compute_residual(const FLAC__int32 data[], unsigned data_len, unsigned order, FLAC__int32 residual[])
  91670. {
  91671. const int idata_len = (int)data_len;
  91672. int i;
  91673. switch(order) {
  91674. case 0:
  91675. FLAC__ASSERT(sizeof(residual[0]) == sizeof(data[0]));
  91676. memcpy(residual, data, sizeof(residual[0])*data_len);
  91677. break;
  91678. case 1:
  91679. for(i = 0; i < idata_len; i++)
  91680. residual[i] = data[i] - data[i-1];
  91681. break;
  91682. case 2:
  91683. for(i = 0; i < idata_len; i++)
  91684. #if 1 /* OPT: may be faster with some compilers on some systems */
  91685. residual[i] = data[i] - (data[i-1] << 1) + data[i-2];
  91686. #else
  91687. residual[i] = data[i] - 2*data[i-1] + data[i-2];
  91688. #endif
  91689. break;
  91690. case 3:
  91691. for(i = 0; i < idata_len; i++)
  91692. #if 1 /* OPT: may be faster with some compilers on some systems */
  91693. residual[i] = data[i] - (((data[i-1]-data[i-2])<<1) + (data[i-1]-data[i-2])) - data[i-3];
  91694. #else
  91695. residual[i] = data[i] - 3*data[i-1] + 3*data[i-2] - data[i-3];
  91696. #endif
  91697. break;
  91698. case 4:
  91699. for(i = 0; i < idata_len; i++)
  91700. #if 1 /* OPT: may be faster with some compilers on some systems */
  91701. residual[i] = data[i] - ((data[i-1]+data[i-3])<<2) + ((data[i-2]<<2) + (data[i-2]<<1)) + data[i-4];
  91702. #else
  91703. residual[i] = data[i] - 4*data[i-1] + 6*data[i-2] - 4*data[i-3] + data[i-4];
  91704. #endif
  91705. break;
  91706. default:
  91707. FLAC__ASSERT(0);
  91708. }
  91709. }
  91710. void FLAC__fixed_restore_signal(const FLAC__int32 residual[], unsigned data_len, unsigned order, FLAC__int32 data[])
  91711. {
  91712. int i, idata_len = (int)data_len;
  91713. switch(order) {
  91714. case 0:
  91715. FLAC__ASSERT(sizeof(residual[0]) == sizeof(data[0]));
  91716. memcpy(data, residual, sizeof(residual[0])*data_len);
  91717. break;
  91718. case 1:
  91719. for(i = 0; i < idata_len; i++)
  91720. data[i] = residual[i] + data[i-1];
  91721. break;
  91722. case 2:
  91723. for(i = 0; i < idata_len; i++)
  91724. #if 1 /* OPT: may be faster with some compilers on some systems */
  91725. data[i] = residual[i] + (data[i-1]<<1) - data[i-2];
  91726. #else
  91727. data[i] = residual[i] + 2*data[i-1] - data[i-2];
  91728. #endif
  91729. break;
  91730. case 3:
  91731. for(i = 0; i < idata_len; i++)
  91732. #if 1 /* OPT: may be faster with some compilers on some systems */
  91733. data[i] = residual[i] + (((data[i-1]-data[i-2])<<1) + (data[i-1]-data[i-2])) + data[i-3];
  91734. #else
  91735. data[i] = residual[i] + 3*data[i-1] - 3*data[i-2] + data[i-3];
  91736. #endif
  91737. break;
  91738. case 4:
  91739. for(i = 0; i < idata_len; i++)
  91740. #if 1 /* OPT: may be faster with some compilers on some systems */
  91741. data[i] = residual[i] + ((data[i-1]+data[i-3])<<2) - ((data[i-2]<<2) + (data[i-2]<<1)) - data[i-4];
  91742. #else
  91743. data[i] = residual[i] + 4*data[i-1] - 6*data[i-2] + 4*data[i-3] - data[i-4];
  91744. #endif
  91745. break;
  91746. default:
  91747. FLAC__ASSERT(0);
  91748. }
  91749. }
  91750. #endif
  91751. /********* End of inlined file: fixed.c *********/
  91752. /********* Start of inlined file: float.c *********/
  91753. /********* Start of inlined file: juce_FlacHeader.h *********/
  91754. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  91755. // tasks..
  91756. #define VERSION "1.2.1"
  91757. #define FLAC__NO_DLL 1
  91758. #ifdef _MSC_VER
  91759. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  91760. #endif
  91761. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  91762. #define FLAC__SYS_DARWIN 1
  91763. #endif
  91764. /********* End of inlined file: juce_FlacHeader.h *********/
  91765. #if JUCE_USE_FLAC
  91766. #if HAVE_CONFIG_H
  91767. # include <config.h>
  91768. #endif
  91769. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  91770. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  91771. #ifdef _MSC_VER
  91772. #define FLAC__U64L(x) x
  91773. #else
  91774. #define FLAC__U64L(x) x##LLU
  91775. #endif
  91776. const FLAC__fixedpoint FLAC__FP_ZERO = 0;
  91777. const FLAC__fixedpoint FLAC__FP_ONE_HALF = 0x00008000;
  91778. const FLAC__fixedpoint FLAC__FP_ONE = 0x00010000;
  91779. const FLAC__fixedpoint FLAC__FP_LN2 = 45426;
  91780. const FLAC__fixedpoint FLAC__FP_E = 178145;
  91781. /* Lookup tables for Knuth's logarithm algorithm */
  91782. #define LOG2_LOOKUP_PRECISION 16
  91783. static const FLAC__uint32 log2_lookup[][LOG2_LOOKUP_PRECISION] = {
  91784. {
  91785. /*
  91786. * 0 fraction bits
  91787. */
  91788. /* undefined */ 0x00000000,
  91789. /* lg(2/1) = */ 0x00000001,
  91790. /* lg(4/3) = */ 0x00000000,
  91791. /* lg(8/7) = */ 0x00000000,
  91792. /* lg(16/15) = */ 0x00000000,
  91793. /* lg(32/31) = */ 0x00000000,
  91794. /* lg(64/63) = */ 0x00000000,
  91795. /* lg(128/127) = */ 0x00000000,
  91796. /* lg(256/255) = */ 0x00000000,
  91797. /* lg(512/511) = */ 0x00000000,
  91798. /* lg(1024/1023) = */ 0x00000000,
  91799. /* lg(2048/2047) = */ 0x00000000,
  91800. /* lg(4096/4095) = */ 0x00000000,
  91801. /* lg(8192/8191) = */ 0x00000000,
  91802. /* lg(16384/16383) = */ 0x00000000,
  91803. /* lg(32768/32767) = */ 0x00000000
  91804. },
  91805. {
  91806. /*
  91807. * 4 fraction bits
  91808. */
  91809. /* undefined */ 0x00000000,
  91810. /* lg(2/1) = */ 0x00000010,
  91811. /* lg(4/3) = */ 0x00000007,
  91812. /* lg(8/7) = */ 0x00000003,
  91813. /* lg(16/15) = */ 0x00000001,
  91814. /* lg(32/31) = */ 0x00000001,
  91815. /* lg(64/63) = */ 0x00000000,
  91816. /* lg(128/127) = */ 0x00000000,
  91817. /* lg(256/255) = */ 0x00000000,
  91818. /* lg(512/511) = */ 0x00000000,
  91819. /* lg(1024/1023) = */ 0x00000000,
  91820. /* lg(2048/2047) = */ 0x00000000,
  91821. /* lg(4096/4095) = */ 0x00000000,
  91822. /* lg(8192/8191) = */ 0x00000000,
  91823. /* lg(16384/16383) = */ 0x00000000,
  91824. /* lg(32768/32767) = */ 0x00000000
  91825. },
  91826. {
  91827. /*
  91828. * 8 fraction bits
  91829. */
  91830. /* undefined */ 0x00000000,
  91831. /* lg(2/1) = */ 0x00000100,
  91832. /* lg(4/3) = */ 0x0000006a,
  91833. /* lg(8/7) = */ 0x00000031,
  91834. /* lg(16/15) = */ 0x00000018,
  91835. /* lg(32/31) = */ 0x0000000c,
  91836. /* lg(64/63) = */ 0x00000006,
  91837. /* lg(128/127) = */ 0x00000003,
  91838. /* lg(256/255) = */ 0x00000001,
  91839. /* lg(512/511) = */ 0x00000001,
  91840. /* lg(1024/1023) = */ 0x00000000,
  91841. /* lg(2048/2047) = */ 0x00000000,
  91842. /* lg(4096/4095) = */ 0x00000000,
  91843. /* lg(8192/8191) = */ 0x00000000,
  91844. /* lg(16384/16383) = */ 0x00000000,
  91845. /* lg(32768/32767) = */ 0x00000000
  91846. },
  91847. {
  91848. /*
  91849. * 12 fraction bits
  91850. */
  91851. /* undefined */ 0x00000000,
  91852. /* lg(2/1) = */ 0x00001000,
  91853. /* lg(4/3) = */ 0x000006a4,
  91854. /* lg(8/7) = */ 0x00000315,
  91855. /* lg(16/15) = */ 0x0000017d,
  91856. /* lg(32/31) = */ 0x000000bc,
  91857. /* lg(64/63) = */ 0x0000005d,
  91858. /* lg(128/127) = */ 0x0000002e,
  91859. /* lg(256/255) = */ 0x00000017,
  91860. /* lg(512/511) = */ 0x0000000c,
  91861. /* lg(1024/1023) = */ 0x00000006,
  91862. /* lg(2048/2047) = */ 0x00000003,
  91863. /* lg(4096/4095) = */ 0x00000001,
  91864. /* lg(8192/8191) = */ 0x00000001,
  91865. /* lg(16384/16383) = */ 0x00000000,
  91866. /* lg(32768/32767) = */ 0x00000000
  91867. },
  91868. {
  91869. /*
  91870. * 16 fraction bits
  91871. */
  91872. /* undefined */ 0x00000000,
  91873. /* lg(2/1) = */ 0x00010000,
  91874. /* lg(4/3) = */ 0x00006a40,
  91875. /* lg(8/7) = */ 0x00003151,
  91876. /* lg(16/15) = */ 0x000017d6,
  91877. /* lg(32/31) = */ 0x00000bba,
  91878. /* lg(64/63) = */ 0x000005d1,
  91879. /* lg(128/127) = */ 0x000002e6,
  91880. /* lg(256/255) = */ 0x00000172,
  91881. /* lg(512/511) = */ 0x000000b9,
  91882. /* lg(1024/1023) = */ 0x0000005c,
  91883. /* lg(2048/2047) = */ 0x0000002e,
  91884. /* lg(4096/4095) = */ 0x00000017,
  91885. /* lg(8192/8191) = */ 0x0000000c,
  91886. /* lg(16384/16383) = */ 0x00000006,
  91887. /* lg(32768/32767) = */ 0x00000003
  91888. },
  91889. {
  91890. /*
  91891. * 20 fraction bits
  91892. */
  91893. /* undefined */ 0x00000000,
  91894. /* lg(2/1) = */ 0x00100000,
  91895. /* lg(4/3) = */ 0x0006a3fe,
  91896. /* lg(8/7) = */ 0x00031513,
  91897. /* lg(16/15) = */ 0x00017d60,
  91898. /* lg(32/31) = */ 0x0000bb9d,
  91899. /* lg(64/63) = */ 0x00005d10,
  91900. /* lg(128/127) = */ 0x00002e59,
  91901. /* lg(256/255) = */ 0x00001721,
  91902. /* lg(512/511) = */ 0x00000b8e,
  91903. /* lg(1024/1023) = */ 0x000005c6,
  91904. /* lg(2048/2047) = */ 0x000002e3,
  91905. /* lg(4096/4095) = */ 0x00000171,
  91906. /* lg(8192/8191) = */ 0x000000b9,
  91907. /* lg(16384/16383) = */ 0x0000005c,
  91908. /* lg(32768/32767) = */ 0x0000002e
  91909. },
  91910. {
  91911. /*
  91912. * 24 fraction bits
  91913. */
  91914. /* undefined */ 0x00000000,
  91915. /* lg(2/1) = */ 0x01000000,
  91916. /* lg(4/3) = */ 0x006a3fe6,
  91917. /* lg(8/7) = */ 0x00315130,
  91918. /* lg(16/15) = */ 0x0017d605,
  91919. /* lg(32/31) = */ 0x000bb9ca,
  91920. /* lg(64/63) = */ 0x0005d0fc,
  91921. /* lg(128/127) = */ 0x0002e58f,
  91922. /* lg(256/255) = */ 0x0001720e,
  91923. /* lg(512/511) = */ 0x0000b8d8,
  91924. /* lg(1024/1023) = */ 0x00005c61,
  91925. /* lg(2048/2047) = */ 0x00002e2d,
  91926. /* lg(4096/4095) = */ 0x00001716,
  91927. /* lg(8192/8191) = */ 0x00000b8b,
  91928. /* lg(16384/16383) = */ 0x000005c5,
  91929. /* lg(32768/32767) = */ 0x000002e3
  91930. },
  91931. {
  91932. /*
  91933. * 28 fraction bits
  91934. */
  91935. /* undefined */ 0x00000000,
  91936. /* lg(2/1) = */ 0x10000000,
  91937. /* lg(4/3) = */ 0x06a3fe5c,
  91938. /* lg(8/7) = */ 0x03151301,
  91939. /* lg(16/15) = */ 0x017d6049,
  91940. /* lg(32/31) = */ 0x00bb9ca6,
  91941. /* lg(64/63) = */ 0x005d0fba,
  91942. /* lg(128/127) = */ 0x002e58f7,
  91943. /* lg(256/255) = */ 0x001720da,
  91944. /* lg(512/511) = */ 0x000b8d87,
  91945. /* lg(1024/1023) = */ 0x0005c60b,
  91946. /* lg(2048/2047) = */ 0x0002e2d7,
  91947. /* lg(4096/4095) = */ 0x00017160,
  91948. /* lg(8192/8191) = */ 0x0000b8ad,
  91949. /* lg(16384/16383) = */ 0x00005c56,
  91950. /* lg(32768/32767) = */ 0x00002e2b
  91951. }
  91952. };
  91953. #if 0
  91954. static const FLAC__uint64 log2_lookup_wide[] = {
  91955. {
  91956. /*
  91957. * 32 fraction bits
  91958. */
  91959. /* undefined */ 0x00000000,
  91960. /* lg(2/1) = */ FLAC__U64L(0x100000000),
  91961. /* lg(4/3) = */ FLAC__U64L(0x6a3fe5c6),
  91962. /* lg(8/7) = */ FLAC__U64L(0x31513015),
  91963. /* lg(16/15) = */ FLAC__U64L(0x17d60497),
  91964. /* lg(32/31) = */ FLAC__U64L(0x0bb9ca65),
  91965. /* lg(64/63) = */ FLAC__U64L(0x05d0fba2),
  91966. /* lg(128/127) = */ FLAC__U64L(0x02e58f74),
  91967. /* lg(256/255) = */ FLAC__U64L(0x01720d9c),
  91968. /* lg(512/511) = */ FLAC__U64L(0x00b8d875),
  91969. /* lg(1024/1023) = */ FLAC__U64L(0x005c60aa),
  91970. /* lg(2048/2047) = */ FLAC__U64L(0x002e2d72),
  91971. /* lg(4096/4095) = */ FLAC__U64L(0x00171600),
  91972. /* lg(8192/8191) = */ FLAC__U64L(0x000b8ad2),
  91973. /* lg(16384/16383) = */ FLAC__U64L(0x0005c55d),
  91974. /* lg(32768/32767) = */ FLAC__U64L(0x0002e2ac)
  91975. },
  91976. {
  91977. /*
  91978. * 48 fraction bits
  91979. */
  91980. /* undefined */ 0x00000000,
  91981. /* lg(2/1) = */ FLAC__U64L(0x1000000000000),
  91982. /* lg(4/3) = */ FLAC__U64L(0x6a3fe5c60429),
  91983. /* lg(8/7) = */ FLAC__U64L(0x315130157f7a),
  91984. /* lg(16/15) = */ FLAC__U64L(0x17d60496cfbb),
  91985. /* lg(32/31) = */ FLAC__U64L(0xbb9ca64ecac),
  91986. /* lg(64/63) = */ FLAC__U64L(0x5d0fba187cd),
  91987. /* lg(128/127) = */ FLAC__U64L(0x2e58f7441ee),
  91988. /* lg(256/255) = */ FLAC__U64L(0x1720d9c06a8),
  91989. /* lg(512/511) = */ FLAC__U64L(0xb8d8752173),
  91990. /* lg(1024/1023) = */ FLAC__U64L(0x5c60aa252e),
  91991. /* lg(2048/2047) = */ FLAC__U64L(0x2e2d71b0d8),
  91992. /* lg(4096/4095) = */ FLAC__U64L(0x1716001719),
  91993. /* lg(8192/8191) = */ FLAC__U64L(0xb8ad1de1b),
  91994. /* lg(16384/16383) = */ FLAC__U64L(0x5c55d640d),
  91995. /* lg(32768/32767) = */ FLAC__U64L(0x2e2abcf52)
  91996. }
  91997. };
  91998. #endif
  91999. FLAC__uint32 FLAC__fixedpoint_log2(FLAC__uint32 x, unsigned fracbits, unsigned precision)
  92000. {
  92001. const FLAC__uint32 ONE = (1u << fracbits);
  92002. const FLAC__uint32 *table = log2_lookup[fracbits >> 2];
  92003. FLAC__ASSERT(fracbits < 32);
  92004. FLAC__ASSERT((fracbits & 0x3) == 0);
  92005. if(x < ONE)
  92006. return 0;
  92007. if(precision > LOG2_LOOKUP_PRECISION)
  92008. precision = LOG2_LOOKUP_PRECISION;
  92009. /* Knuth's algorithm for computing logarithms, optimized for base-2 with lookup tables */
  92010. {
  92011. FLAC__uint32 y = 0;
  92012. FLAC__uint32 z = x >> 1, k = 1;
  92013. while (x > ONE && k < precision) {
  92014. if (x - z >= ONE) {
  92015. x -= z;
  92016. z = x >> k;
  92017. y += table[k];
  92018. }
  92019. else {
  92020. z >>= 1;
  92021. k++;
  92022. }
  92023. }
  92024. return y;
  92025. }
  92026. }
  92027. #endif /* defined FLAC__INTEGER_ONLY_LIBRARY */
  92028. #endif
  92029. /********* End of inlined file: float.c *********/
  92030. /********* Start of inlined file: format.c *********/
  92031. /********* Start of inlined file: juce_FlacHeader.h *********/
  92032. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  92033. // tasks..
  92034. #define VERSION "1.2.1"
  92035. #define FLAC__NO_DLL 1
  92036. #ifdef _MSC_VER
  92037. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  92038. #endif
  92039. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  92040. #define FLAC__SYS_DARWIN 1
  92041. #endif
  92042. /********* End of inlined file: juce_FlacHeader.h *********/
  92043. #if JUCE_USE_FLAC
  92044. #if HAVE_CONFIG_H
  92045. # include <config.h>
  92046. #endif
  92047. #include <stdio.h>
  92048. #include <stdlib.h> /* for qsort() */
  92049. #include <string.h> /* for memset() */
  92050. #ifndef FLaC__INLINE
  92051. #define FLaC__INLINE
  92052. #endif
  92053. #ifdef min
  92054. #undef min
  92055. #endif
  92056. #define min(a,b) ((a)<(b)?(a):(b))
  92057. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  92058. #ifdef _MSC_VER
  92059. #define FLAC__U64L(x) x
  92060. #else
  92061. #define FLAC__U64L(x) x##LLU
  92062. #endif
  92063. /* VERSION should come from configure */
  92064. FLAC_API const char *FLAC__VERSION_STRING = VERSION
  92065. ;
  92066. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINW32__
  92067. /* yet one more hack because of MSVC6: */
  92068. FLAC_API const char *FLAC__VENDOR_STRING = "reference libFLAC 1.2.1 20070917";
  92069. #else
  92070. FLAC_API const char *FLAC__VENDOR_STRING = "reference libFLAC " VERSION " 20070917";
  92071. #endif
  92072. FLAC_API const FLAC__byte FLAC__STREAM_SYNC_STRING[4] = { 'f','L','a','C' };
  92073. FLAC_API const unsigned FLAC__STREAM_SYNC = 0x664C6143;
  92074. FLAC_API const unsigned FLAC__STREAM_SYNC_LEN = 32; /* bits */
  92075. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN = 16; /* bits */
  92076. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN = 16; /* bits */
  92077. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN = 24; /* bits */
  92078. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN = 24; /* bits */
  92079. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN = 20; /* bits */
  92080. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN = 3; /* bits */
  92081. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN = 5; /* bits */
  92082. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN = 36; /* bits */
  92083. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MD5SUM_LEN = 128; /* bits */
  92084. FLAC_API const unsigned FLAC__STREAM_METADATA_APPLICATION_ID_LEN = 32; /* bits */
  92085. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN = 64; /* bits */
  92086. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN = 64; /* bits */
  92087. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN = 16; /* bits */
  92088. FLAC_API const FLAC__uint64 FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER = FLAC__U64L(0xffffffffffffffff);
  92089. FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN = 32; /* bits */
  92090. FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN = 32; /* bits */
  92091. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN = 64; /* bits */
  92092. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN = 8; /* bits */
  92093. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN = 3*8; /* bits */
  92094. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN = 64; /* bits */
  92095. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN = 8; /* bits */
  92096. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN = 12*8; /* bits */
  92097. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN = 1; /* bit */
  92098. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN = 1; /* bit */
  92099. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN = 6+13*8; /* bits */
  92100. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN = 8; /* bits */
  92101. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN = 128*8; /* bits */
  92102. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN = 64; /* bits */
  92103. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN = 1; /* bit */
  92104. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN = 7+258*8; /* bits */
  92105. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN = 8; /* bits */
  92106. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_TYPE_LEN = 32; /* bits */
  92107. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN = 32; /* bits */
  92108. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN = 32; /* bits */
  92109. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN = 32; /* bits */
  92110. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN = 32; /* bits */
  92111. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN = 32; /* bits */
  92112. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_COLORS_LEN = 32; /* bits */
  92113. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN = 32; /* bits */
  92114. FLAC_API const unsigned FLAC__STREAM_METADATA_IS_LAST_LEN = 1; /* bits */
  92115. FLAC_API const unsigned FLAC__STREAM_METADATA_TYPE_LEN = 7; /* bits */
  92116. FLAC_API const unsigned FLAC__STREAM_METADATA_LENGTH_LEN = 24; /* bits */
  92117. FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC = 0x3ffe;
  92118. FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC_LEN = 14; /* bits */
  92119. FLAC_API const unsigned FLAC__FRAME_HEADER_RESERVED_LEN = 1; /* bits */
  92120. FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN = 1; /* bits */
  92121. FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCK_SIZE_LEN = 4; /* bits */
  92122. FLAC_API const unsigned FLAC__FRAME_HEADER_SAMPLE_RATE_LEN = 4; /* bits */
  92123. FLAC_API const unsigned FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN = 4; /* bits */
  92124. FLAC_API const unsigned FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN = 3; /* bits */
  92125. FLAC_API const unsigned FLAC__FRAME_HEADER_ZERO_PAD_LEN = 1; /* bits */
  92126. FLAC_API const unsigned FLAC__FRAME_HEADER_CRC_LEN = 8; /* bits */
  92127. FLAC_API const unsigned FLAC__FRAME_FOOTER_CRC_LEN = 16; /* bits */
  92128. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_TYPE_LEN = 2; /* bits */
  92129. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN = 4; /* bits */
  92130. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN = 4; /* bits */
  92131. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN = 5; /* bits */
  92132. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN = 5; /* bits */
  92133. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER = 15; /* == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN)-1 */
  92134. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER = 31; /* == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN)-1 */
  92135. FLAC_API const char * const FLAC__EntropyCodingMethodTypeString[] = {
  92136. "PARTITIONED_RICE",
  92137. "PARTITIONED_RICE2"
  92138. };
  92139. FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN = 4; /* bits */
  92140. FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN = 5; /* bits */
  92141. FLAC_API const unsigned FLAC__SUBFRAME_ZERO_PAD_LEN = 1; /* bits */
  92142. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LEN = 6; /* bits */
  92143. FLAC_API const unsigned FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN = 1; /* bits */
  92144. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_CONSTANT_BYTE_ALIGNED_MASK = 0x00;
  92145. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_VERBATIM_BYTE_ALIGNED_MASK = 0x02;
  92146. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_FIXED_BYTE_ALIGNED_MASK = 0x10;
  92147. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LPC_BYTE_ALIGNED_MASK = 0x40;
  92148. FLAC_API const char * const FLAC__SubframeTypeString[] = {
  92149. "CONSTANT",
  92150. "VERBATIM",
  92151. "FIXED",
  92152. "LPC"
  92153. };
  92154. FLAC_API const char * const FLAC__ChannelAssignmentString[] = {
  92155. "INDEPENDENT",
  92156. "LEFT_SIDE",
  92157. "RIGHT_SIDE",
  92158. "MID_SIDE"
  92159. };
  92160. FLAC_API const char * const FLAC__FrameNumberTypeString[] = {
  92161. "FRAME_NUMBER_TYPE_FRAME_NUMBER",
  92162. "FRAME_NUMBER_TYPE_SAMPLE_NUMBER"
  92163. };
  92164. FLAC_API const char * const FLAC__MetadataTypeString[] = {
  92165. "STREAMINFO",
  92166. "PADDING",
  92167. "APPLICATION",
  92168. "SEEKTABLE",
  92169. "VORBIS_COMMENT",
  92170. "CUESHEET",
  92171. "PICTURE"
  92172. };
  92173. FLAC_API const char * const FLAC__StreamMetadata_Picture_TypeString[] = {
  92174. "Other",
  92175. "32x32 pixels 'file icon' (PNG only)",
  92176. "Other file icon",
  92177. "Cover (front)",
  92178. "Cover (back)",
  92179. "Leaflet page",
  92180. "Media (e.g. label side of CD)",
  92181. "Lead artist/lead performer/soloist",
  92182. "Artist/performer",
  92183. "Conductor",
  92184. "Band/Orchestra",
  92185. "Composer",
  92186. "Lyricist/text writer",
  92187. "Recording Location",
  92188. "During recording",
  92189. "During performance",
  92190. "Movie/video screen capture",
  92191. "A bright coloured fish",
  92192. "Illustration",
  92193. "Band/artist logotype",
  92194. "Publisher/Studio logotype"
  92195. };
  92196. FLAC_API FLAC__bool FLAC__format_sample_rate_is_valid(unsigned sample_rate)
  92197. {
  92198. if(sample_rate == 0 || sample_rate > FLAC__MAX_SAMPLE_RATE) {
  92199. return false;
  92200. }
  92201. else
  92202. return true;
  92203. }
  92204. FLAC_API FLAC__bool FLAC__format_sample_rate_is_subset(unsigned sample_rate)
  92205. {
  92206. if(
  92207. !FLAC__format_sample_rate_is_valid(sample_rate) ||
  92208. (
  92209. sample_rate >= (1u << 16) &&
  92210. !(sample_rate % 1000 == 0 || sample_rate % 10 == 0)
  92211. )
  92212. ) {
  92213. return false;
  92214. }
  92215. else
  92216. return true;
  92217. }
  92218. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  92219. FLAC_API FLAC__bool FLAC__format_seektable_is_legal(const FLAC__StreamMetadata_SeekTable *seek_table)
  92220. {
  92221. unsigned i;
  92222. FLAC__uint64 prev_sample_number = 0;
  92223. FLAC__bool got_prev = false;
  92224. FLAC__ASSERT(0 != seek_table);
  92225. for(i = 0; i < seek_table->num_points; i++) {
  92226. if(got_prev) {
  92227. if(
  92228. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  92229. seek_table->points[i].sample_number <= prev_sample_number
  92230. )
  92231. return false;
  92232. }
  92233. prev_sample_number = seek_table->points[i].sample_number;
  92234. got_prev = true;
  92235. }
  92236. return true;
  92237. }
  92238. /* used as the sort predicate for qsort() */
  92239. static int seekpoint_compare_(const FLAC__StreamMetadata_SeekPoint *l, const FLAC__StreamMetadata_SeekPoint *r)
  92240. {
  92241. /* we don't just 'return l->sample_number - r->sample_number' since the result (FLAC__int64) might overflow an 'int' */
  92242. if(l->sample_number == r->sample_number)
  92243. return 0;
  92244. else if(l->sample_number < r->sample_number)
  92245. return -1;
  92246. else
  92247. return 1;
  92248. }
  92249. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  92250. FLAC_API unsigned FLAC__format_seektable_sort(FLAC__StreamMetadata_SeekTable *seek_table)
  92251. {
  92252. unsigned i, j;
  92253. FLAC__bool first;
  92254. FLAC__ASSERT(0 != seek_table);
  92255. /* sort the seekpoints */
  92256. qsort(seek_table->points, seek_table->num_points, sizeof(FLAC__StreamMetadata_SeekPoint), (int (*)(const void *, const void *))seekpoint_compare_);
  92257. /* uniquify the seekpoints */
  92258. first = true;
  92259. for(i = j = 0; i < seek_table->num_points; i++) {
  92260. if(seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER) {
  92261. if(!first) {
  92262. if(seek_table->points[i].sample_number == seek_table->points[j-1].sample_number)
  92263. continue;
  92264. }
  92265. }
  92266. first = false;
  92267. seek_table->points[j++] = seek_table->points[i];
  92268. }
  92269. for(i = j; i < seek_table->num_points; i++) {
  92270. seek_table->points[i].sample_number = FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
  92271. seek_table->points[i].stream_offset = 0;
  92272. seek_table->points[i].frame_samples = 0;
  92273. }
  92274. return j;
  92275. }
  92276. /*
  92277. * also disallows non-shortest-form encodings, c.f.
  92278. * http://www.unicode.org/versions/corrigendum1.html
  92279. * and a more clear explanation at the end of this section:
  92280. * http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  92281. */
  92282. static FLaC__INLINE unsigned utf8len_(const FLAC__byte *utf8)
  92283. {
  92284. FLAC__ASSERT(0 != utf8);
  92285. if ((utf8[0] & 0x80) == 0) {
  92286. return 1;
  92287. }
  92288. else if ((utf8[0] & 0xE0) == 0xC0 && (utf8[1] & 0xC0) == 0x80) {
  92289. if ((utf8[0] & 0xFE) == 0xC0) /* overlong sequence check */
  92290. return 0;
  92291. return 2;
  92292. }
  92293. else if ((utf8[0] & 0xF0) == 0xE0 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80) {
  92294. if (utf8[0] == 0xE0 && (utf8[1] & 0xE0) == 0x80) /* overlong sequence check */
  92295. return 0;
  92296. /* illegal surrogates check (U+D800...U+DFFF and U+FFFE...U+FFFF) */
  92297. if (utf8[0] == 0xED && (utf8[1] & 0xE0) == 0xA0) /* D800-DFFF */
  92298. return 0;
  92299. if (utf8[0] == 0xEF && utf8[1] == 0xBF && (utf8[2] & 0xFE) == 0xBE) /* FFFE-FFFF */
  92300. return 0;
  92301. return 3;
  92302. }
  92303. else if ((utf8[0] & 0xF8) == 0xF0 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80 && (utf8[3] & 0xC0) == 0x80) {
  92304. if (utf8[0] == 0xF0 && (utf8[1] & 0xF0) == 0x80) /* overlong sequence check */
  92305. return 0;
  92306. return 4;
  92307. }
  92308. else if ((utf8[0] & 0xFC) == 0xF8 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80 && (utf8[3] & 0xC0) == 0x80 && (utf8[4] & 0xC0) == 0x80) {
  92309. if (utf8[0] == 0xF8 && (utf8[1] & 0xF8) == 0x80) /* overlong sequence check */
  92310. return 0;
  92311. return 5;
  92312. }
  92313. else if ((utf8[0] & 0xFE) == 0xFC && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80 && (utf8[3] & 0xC0) == 0x80 && (utf8[4] & 0xC0) == 0x80 && (utf8[5] & 0xC0) == 0x80) {
  92314. if (utf8[0] == 0xFC && (utf8[1] & 0xFC) == 0x80) /* overlong sequence check */
  92315. return 0;
  92316. return 6;
  92317. }
  92318. else {
  92319. return 0;
  92320. }
  92321. }
  92322. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_name_is_legal(const char *name)
  92323. {
  92324. char c;
  92325. for(c = *name; c; c = *(++name))
  92326. if(c < 0x20 || c == 0x3d || c > 0x7d)
  92327. return false;
  92328. return true;
  92329. }
  92330. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_value_is_legal(const FLAC__byte *value, unsigned length)
  92331. {
  92332. if(length == (unsigned)(-1)) {
  92333. while(*value) {
  92334. unsigned n = utf8len_(value);
  92335. if(n == 0)
  92336. return false;
  92337. value += n;
  92338. }
  92339. }
  92340. else {
  92341. const FLAC__byte *end = value + length;
  92342. while(value < end) {
  92343. unsigned n = utf8len_(value);
  92344. if(n == 0)
  92345. return false;
  92346. value += n;
  92347. }
  92348. if(value != end)
  92349. return false;
  92350. }
  92351. return true;
  92352. }
  92353. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_is_legal(const FLAC__byte *entry, unsigned length)
  92354. {
  92355. const FLAC__byte *s, *end;
  92356. for(s = entry, end = s + length; s < end && *s != '='; s++) {
  92357. if(*s < 0x20 || *s > 0x7D)
  92358. return false;
  92359. }
  92360. if(s == end)
  92361. return false;
  92362. s++; /* skip '=' */
  92363. while(s < end) {
  92364. unsigned n = utf8len_(s);
  92365. if(n == 0)
  92366. return false;
  92367. s += n;
  92368. }
  92369. if(s != end)
  92370. return false;
  92371. return true;
  92372. }
  92373. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  92374. FLAC_API FLAC__bool FLAC__format_cuesheet_is_legal(const FLAC__StreamMetadata_CueSheet *cue_sheet, FLAC__bool check_cd_da_subset, const char **violation)
  92375. {
  92376. unsigned i, j;
  92377. if(check_cd_da_subset) {
  92378. if(cue_sheet->lead_in < 2 * 44100) {
  92379. if(violation) *violation = "CD-DA cue sheet must have a lead-in length of at least 2 seconds";
  92380. return false;
  92381. }
  92382. if(cue_sheet->lead_in % 588 != 0) {
  92383. if(violation) *violation = "CD-DA cue sheet lead-in length must be evenly divisible by 588 samples";
  92384. return false;
  92385. }
  92386. }
  92387. if(cue_sheet->num_tracks == 0) {
  92388. if(violation) *violation = "cue sheet must have at least one track (the lead-out)";
  92389. return false;
  92390. }
  92391. if(check_cd_da_subset && cue_sheet->tracks[cue_sheet->num_tracks-1].number != 170) {
  92392. if(violation) *violation = "CD-DA cue sheet must have a lead-out track number 170 (0xAA)";
  92393. return false;
  92394. }
  92395. for(i = 0; i < cue_sheet->num_tracks; i++) {
  92396. if(cue_sheet->tracks[i].number == 0) {
  92397. if(violation) *violation = "cue sheet may not have a track number 0";
  92398. return false;
  92399. }
  92400. if(check_cd_da_subset) {
  92401. if(!((cue_sheet->tracks[i].number >= 1 && cue_sheet->tracks[i].number <= 99) || cue_sheet->tracks[i].number == 170)) {
  92402. if(violation) *violation = "CD-DA cue sheet track number must be 1-99 or 170";
  92403. return false;
  92404. }
  92405. }
  92406. if(check_cd_da_subset && cue_sheet->tracks[i].offset % 588 != 0) {
  92407. if(violation) {
  92408. if(i == cue_sheet->num_tracks-1) /* the lead-out track... */
  92409. *violation = "CD-DA cue sheet lead-out offset must be evenly divisible by 588 samples";
  92410. else
  92411. *violation = "CD-DA cue sheet track offset must be evenly divisible by 588 samples";
  92412. }
  92413. return false;
  92414. }
  92415. if(i < cue_sheet->num_tracks - 1) {
  92416. if(cue_sheet->tracks[i].num_indices == 0) {
  92417. if(violation) *violation = "cue sheet track must have at least one index point";
  92418. return false;
  92419. }
  92420. if(cue_sheet->tracks[i].indices[0].number > 1) {
  92421. if(violation) *violation = "cue sheet track's first index number must be 0 or 1";
  92422. return false;
  92423. }
  92424. }
  92425. for(j = 0; j < cue_sheet->tracks[i].num_indices; j++) {
  92426. if(check_cd_da_subset && cue_sheet->tracks[i].indices[j].offset % 588 != 0) {
  92427. if(violation) *violation = "CD-DA cue sheet track index offset must be evenly divisible by 588 samples";
  92428. return false;
  92429. }
  92430. if(j > 0) {
  92431. if(cue_sheet->tracks[i].indices[j].number != cue_sheet->tracks[i].indices[j-1].number + 1) {
  92432. if(violation) *violation = "cue sheet track index numbers must increase by 1";
  92433. return false;
  92434. }
  92435. }
  92436. }
  92437. }
  92438. return true;
  92439. }
  92440. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  92441. FLAC_API FLAC__bool FLAC__format_picture_is_legal(const FLAC__StreamMetadata_Picture *picture, const char **violation)
  92442. {
  92443. char *p;
  92444. FLAC__byte *b;
  92445. for(p = picture->mime_type; *p; p++) {
  92446. if(*p < 0x20 || *p > 0x7e) {
  92447. if(violation) *violation = "MIME type string must contain only printable ASCII characters (0x20-0x7e)";
  92448. return false;
  92449. }
  92450. }
  92451. for(b = picture->description; *b; ) {
  92452. unsigned n = utf8len_(b);
  92453. if(n == 0) {
  92454. if(violation) *violation = "description string must be valid UTF-8";
  92455. return false;
  92456. }
  92457. b += n;
  92458. }
  92459. return true;
  92460. }
  92461. /*
  92462. * These routines are private to libFLAC
  92463. */
  92464. unsigned FLAC__format_get_max_rice_partition_order(unsigned blocksize, unsigned predictor_order)
  92465. {
  92466. return
  92467. FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(
  92468. FLAC__format_get_max_rice_partition_order_from_blocksize(blocksize),
  92469. blocksize,
  92470. predictor_order
  92471. );
  92472. }
  92473. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize(unsigned blocksize)
  92474. {
  92475. unsigned max_rice_partition_order = 0;
  92476. while(!(blocksize & 1)) {
  92477. max_rice_partition_order++;
  92478. blocksize >>= 1;
  92479. }
  92480. return min(FLAC__MAX_RICE_PARTITION_ORDER, max_rice_partition_order);
  92481. }
  92482. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(unsigned limit, unsigned blocksize, unsigned predictor_order)
  92483. {
  92484. unsigned max_rice_partition_order = limit;
  92485. while(max_rice_partition_order > 0 && (blocksize >> max_rice_partition_order) <= predictor_order)
  92486. max_rice_partition_order--;
  92487. FLAC__ASSERT(
  92488. (max_rice_partition_order == 0 && blocksize >= predictor_order) ||
  92489. (max_rice_partition_order > 0 && blocksize >> max_rice_partition_order > predictor_order)
  92490. );
  92491. return max_rice_partition_order;
  92492. }
  92493. void FLAC__format_entropy_coding_method_partitioned_rice_contents_init(FLAC__EntropyCodingMethod_PartitionedRiceContents *object)
  92494. {
  92495. FLAC__ASSERT(0 != object);
  92496. object->parameters = 0;
  92497. object->raw_bits = 0;
  92498. object->capacity_by_order = 0;
  92499. }
  92500. void FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(FLAC__EntropyCodingMethod_PartitionedRiceContents *object)
  92501. {
  92502. FLAC__ASSERT(0 != object);
  92503. if(0 != object->parameters)
  92504. free(object->parameters);
  92505. if(0 != object->raw_bits)
  92506. free(object->raw_bits);
  92507. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(object);
  92508. }
  92509. FLAC__bool FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(FLAC__EntropyCodingMethod_PartitionedRiceContents *object, unsigned max_partition_order)
  92510. {
  92511. FLAC__ASSERT(0 != object);
  92512. FLAC__ASSERT(object->capacity_by_order > 0 || (0 == object->parameters && 0 == object->raw_bits));
  92513. if(object->capacity_by_order < max_partition_order) {
  92514. if(0 == (object->parameters = (unsigned*)realloc(object->parameters, sizeof(unsigned)*(1 << max_partition_order))))
  92515. return false;
  92516. if(0 == (object->raw_bits = (unsigned*)realloc(object->raw_bits, sizeof(unsigned)*(1 << max_partition_order))))
  92517. return false;
  92518. memset(object->raw_bits, 0, sizeof(unsigned)*(1 << max_partition_order));
  92519. object->capacity_by_order = max_partition_order;
  92520. }
  92521. return true;
  92522. }
  92523. #endif
  92524. /********* End of inlined file: format.c *********/
  92525. /********* Start of inlined file: lpc_flac.c *********/
  92526. /********* Start of inlined file: juce_FlacHeader.h *********/
  92527. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  92528. // tasks..
  92529. #define VERSION "1.2.1"
  92530. #define FLAC__NO_DLL 1
  92531. #ifdef _MSC_VER
  92532. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  92533. #endif
  92534. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  92535. #define FLAC__SYS_DARWIN 1
  92536. #endif
  92537. /********* End of inlined file: juce_FlacHeader.h *********/
  92538. #if JUCE_USE_FLAC
  92539. #if HAVE_CONFIG_H
  92540. # include <config.h>
  92541. #endif
  92542. #include <math.h>
  92543. /********* Start of inlined file: lpc.h *********/
  92544. #ifndef FLAC__PRIVATE__LPC_H
  92545. #define FLAC__PRIVATE__LPC_H
  92546. #ifdef HAVE_CONFIG_H
  92547. #include <config.h>
  92548. #endif
  92549. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  92550. /*
  92551. * FLAC__lpc_window_data()
  92552. * --------------------------------------------------------------------
  92553. * Applies the given window to the data.
  92554. * OPT: asm implementation
  92555. *
  92556. * IN in[0,data_len-1]
  92557. * IN window[0,data_len-1]
  92558. * OUT out[0,lag-1]
  92559. * IN data_len
  92560. */
  92561. void FLAC__lpc_window_data(const FLAC__int32 in[], const FLAC__real window[], FLAC__real out[], unsigned data_len);
  92562. /*
  92563. * FLAC__lpc_compute_autocorrelation()
  92564. * --------------------------------------------------------------------
  92565. * Compute the autocorrelation for lags between 0 and lag-1.
  92566. * Assumes data[] outside of [0,data_len-1] == 0.
  92567. * Asserts that lag > 0.
  92568. *
  92569. * IN data[0,data_len-1]
  92570. * IN data_len
  92571. * IN 0 < lag <= data_len
  92572. * OUT autoc[0,lag-1]
  92573. */
  92574. void FLAC__lpc_compute_autocorrelation(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  92575. #ifndef FLAC__NO_ASM
  92576. # ifdef FLAC__CPU_IA32
  92577. # ifdef FLAC__HAS_NASM
  92578. void FLAC__lpc_compute_autocorrelation_asm_ia32(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  92579. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_4(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  92580. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_8(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  92581. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_12(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  92582. void FLAC__lpc_compute_autocorrelation_asm_ia32_3dnow(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  92583. # endif
  92584. # endif
  92585. #endif
  92586. /*
  92587. * FLAC__lpc_compute_lp_coefficients()
  92588. * --------------------------------------------------------------------
  92589. * Computes LP coefficients for orders 1..max_order.
  92590. * Do not call if autoc[0] == 0.0. This means the signal is zero
  92591. * and there is no point in calculating a predictor.
  92592. *
  92593. * IN autoc[0,max_order] autocorrelation values
  92594. * IN 0 < max_order <= FLAC__MAX_LPC_ORDER max LP order to compute
  92595. * OUT lp_coeff[0,max_order-1][0,max_order-1] LP coefficients for each order
  92596. * *** IMPORTANT:
  92597. * *** lp_coeff[0,max_order-1][max_order,FLAC__MAX_LPC_ORDER-1] are untouched
  92598. * OUT error[0,max_order-1] error for each order (more
  92599. * specifically, the variance of
  92600. * the error signal times # of
  92601. * samples in the signal)
  92602. *
  92603. * Example: if max_order is 9, the LP coefficients for order 9 will be
  92604. * in lp_coeff[8][0,8], the LP coefficients for order 8 will be
  92605. * in lp_coeff[7][0,7], etc.
  92606. */
  92607. void FLAC__lpc_compute_lp_coefficients(const FLAC__real autoc[], unsigned *max_order, FLAC__real lp_coeff[][FLAC__MAX_LPC_ORDER], FLAC__double error[]);
  92608. /*
  92609. * FLAC__lpc_quantize_coefficients()
  92610. * --------------------------------------------------------------------
  92611. * Quantizes the LP coefficients. NOTE: precision + bits_per_sample
  92612. * must be less than 32 (sizeof(FLAC__int32)*8).
  92613. *
  92614. * IN lp_coeff[0,order-1] LP coefficients
  92615. * IN order LP order
  92616. * IN FLAC__MIN_QLP_COEFF_PRECISION < precision
  92617. * desired precision (in bits, including sign
  92618. * bit) of largest coefficient
  92619. * OUT qlp_coeff[0,order-1] quantized coefficients
  92620. * OUT shift # of bits to shift right to get approximated
  92621. * LP coefficients. NOTE: could be negative.
  92622. * RETURN 0 => quantization OK
  92623. * 1 => coefficients require too much shifting for *shift to
  92624. * fit in the LPC subframe header. 'shift' is unset.
  92625. * 2 => coefficients are all zero, which is bad. 'shift' is
  92626. * unset.
  92627. */
  92628. int FLAC__lpc_quantize_coefficients(const FLAC__real lp_coeff[], unsigned order, unsigned precision, FLAC__int32 qlp_coeff[], int *shift);
  92629. /*
  92630. * FLAC__lpc_compute_residual_from_qlp_coefficients()
  92631. * --------------------------------------------------------------------
  92632. * Compute the residual signal obtained from sutracting the predicted
  92633. * signal from the original.
  92634. *
  92635. * IN data[-order,data_len-1] original signal (NOTE THE INDICES!)
  92636. * IN data_len length of original signal
  92637. * IN qlp_coeff[0,order-1] quantized LP coefficients
  92638. * IN order > 0 LP order
  92639. * IN lp_quantization quantization of LP coefficients in bits
  92640. * OUT residual[0,data_len-1] residual signal
  92641. */
  92642. void FLAC__lpc_compute_residual_from_qlp_coefficients(const FLAC__int32 *data, unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 residual[]);
  92643. void FLAC__lpc_compute_residual_from_qlp_coefficients_wide(const FLAC__int32 *data, unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 residual[]);
  92644. #ifndef FLAC__NO_ASM
  92645. # ifdef FLAC__CPU_IA32
  92646. # ifdef FLAC__HAS_NASM
  92647. void FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32(const FLAC__int32 *data, unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 residual[]);
  92648. void FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx(const FLAC__int32 *data, unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 residual[]);
  92649. # endif
  92650. # endif
  92651. #endif
  92652. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  92653. /*
  92654. * FLAC__lpc_restore_signal()
  92655. * --------------------------------------------------------------------
  92656. * Restore the original signal by summing the residual and the
  92657. * predictor.
  92658. *
  92659. * IN residual[0,data_len-1] residual signal
  92660. * IN data_len length of original signal
  92661. * IN qlp_coeff[0,order-1] quantized LP coefficients
  92662. * IN order > 0 LP order
  92663. * IN lp_quantization quantization of LP coefficients in bits
  92664. * *** IMPORTANT: the caller must pass in the historical samples:
  92665. * IN data[-order,-1] previously-reconstructed historical samples
  92666. * OUT data[0,data_len-1] original signal
  92667. */
  92668. void FLAC__lpc_restore_signal(const FLAC__int32 residual[], unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 data[]);
  92669. void FLAC__lpc_restore_signal_wide(const FLAC__int32 residual[], unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 data[]);
  92670. #ifndef FLAC__NO_ASM
  92671. # ifdef FLAC__CPU_IA32
  92672. # ifdef FLAC__HAS_NASM
  92673. void FLAC__lpc_restore_signal_asm_ia32(const FLAC__int32 residual[], unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 data[]);
  92674. void FLAC__lpc_restore_signal_asm_ia32_mmx(const FLAC__int32 residual[], unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 data[]);
  92675. # endif /* FLAC__HAS_NASM */
  92676. # elif defined FLAC__CPU_PPC
  92677. void FLAC__lpc_restore_signal_asm_ppc_altivec_16(const FLAC__int32 residual[], unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 data[]);
  92678. void FLAC__lpc_restore_signal_asm_ppc_altivec_16_order8(const FLAC__int32 residual[], unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 data[]);
  92679. # endif/* FLAC__CPU_IA32 || FLAC__CPU_PPC */
  92680. #endif /* FLAC__NO_ASM */
  92681. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  92682. /*
  92683. * FLAC__lpc_compute_expected_bits_per_residual_sample()
  92684. * --------------------------------------------------------------------
  92685. * Compute the expected number of bits per residual signal sample
  92686. * based on the LP error (which is related to the residual variance).
  92687. *
  92688. * IN lpc_error >= 0.0 error returned from calculating LP coefficients
  92689. * IN total_samples > 0 # of samples in residual signal
  92690. * RETURN expected bits per sample
  92691. */
  92692. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample(FLAC__double lpc_error, unsigned total_samples);
  92693. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(FLAC__double lpc_error, FLAC__double error_scale);
  92694. /*
  92695. * FLAC__lpc_compute_best_order()
  92696. * --------------------------------------------------------------------
  92697. * Compute the best order from the array of signal errors returned
  92698. * during coefficient computation.
  92699. *
  92700. * IN lpc_error[0,max_order-1] >= 0.0 error returned from calculating LP coefficients
  92701. * IN max_order > 0 max LP order
  92702. * IN total_samples > 0 # of samples in residual signal
  92703. * IN overhead_bits_per_order # of bits overhead for each increased LP order
  92704. * (includes warmup sample size and quantized LP coefficient)
  92705. * RETURN [1,max_order] best order
  92706. */
  92707. unsigned FLAC__lpc_compute_best_order(const FLAC__double lpc_error[], unsigned max_order, unsigned total_samples, unsigned overhead_bits_per_order);
  92708. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  92709. #endif
  92710. /********* End of inlined file: lpc.h *********/
  92711. #if defined DEBUG || defined FLAC__OVERFLOW_DETECT || defined FLAC__OVERFLOW_DETECT_VERBOSE
  92712. #include <stdio.h>
  92713. #endif
  92714. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  92715. #ifndef M_LN2
  92716. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  92717. #define M_LN2 0.69314718055994530942
  92718. #endif
  92719. /* OPT: #undef'ing this may improve the speed on some architectures */
  92720. #define FLAC__LPC_UNROLLED_FILTER_LOOPS
  92721. void FLAC__lpc_window_data(const FLAC__int32 in[], const FLAC__real window[], FLAC__real out[], unsigned data_len)
  92722. {
  92723. unsigned i;
  92724. for(i = 0; i < data_len; i++)
  92725. out[i] = in[i] * window[i];
  92726. }
  92727. void FLAC__lpc_compute_autocorrelation(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[])
  92728. {
  92729. /* a readable, but slower, version */
  92730. #if 0
  92731. FLAC__real d;
  92732. unsigned i;
  92733. FLAC__ASSERT(lag > 0);
  92734. FLAC__ASSERT(lag <= data_len);
  92735. /*
  92736. * Technically we should subtract the mean first like so:
  92737. * for(i = 0; i < data_len; i++)
  92738. * data[i] -= mean;
  92739. * but it appears not to make enough of a difference to matter, and
  92740. * most signals are already closely centered around zero
  92741. */
  92742. while(lag--) {
  92743. for(i = lag, d = 0.0; i < data_len; i++)
  92744. d += data[i] * data[i - lag];
  92745. autoc[lag] = d;
  92746. }
  92747. #endif
  92748. /*
  92749. * this version tends to run faster because of better data locality
  92750. * ('data_len' is usually much larger than 'lag')
  92751. */
  92752. FLAC__real d;
  92753. unsigned sample, coeff;
  92754. const unsigned limit = data_len - lag;
  92755. FLAC__ASSERT(lag > 0);
  92756. FLAC__ASSERT(lag <= data_len);
  92757. for(coeff = 0; coeff < lag; coeff++)
  92758. autoc[coeff] = 0.0;
  92759. for(sample = 0; sample <= limit; sample++) {
  92760. d = data[sample];
  92761. for(coeff = 0; coeff < lag; coeff++)
  92762. autoc[coeff] += d * data[sample+coeff];
  92763. }
  92764. for(; sample < data_len; sample++) {
  92765. d = data[sample];
  92766. for(coeff = 0; coeff < data_len - sample; coeff++)
  92767. autoc[coeff] += d * data[sample+coeff];
  92768. }
  92769. }
  92770. void FLAC__lpc_compute_lp_coefficients(const FLAC__real autoc[], unsigned *max_order, FLAC__real lp_coeff[][FLAC__MAX_LPC_ORDER], FLAC__double error[])
  92771. {
  92772. unsigned i, j;
  92773. FLAC__double r, err, ref[FLAC__MAX_LPC_ORDER], lpc[FLAC__MAX_LPC_ORDER];
  92774. FLAC__ASSERT(0 != max_order);
  92775. FLAC__ASSERT(0 < *max_order);
  92776. FLAC__ASSERT(*max_order <= FLAC__MAX_LPC_ORDER);
  92777. FLAC__ASSERT(autoc[0] != 0.0);
  92778. err = autoc[0];
  92779. for(i = 0; i < *max_order; i++) {
  92780. /* Sum up this iteration's reflection coefficient. */
  92781. r = -autoc[i+1];
  92782. for(j = 0; j < i; j++)
  92783. r -= lpc[j] * autoc[i-j];
  92784. ref[i] = (r/=err);
  92785. /* Update LPC coefficients and total error. */
  92786. lpc[i]=r;
  92787. for(j = 0; j < (i>>1); j++) {
  92788. FLAC__double tmp = lpc[j];
  92789. lpc[j] += r * lpc[i-1-j];
  92790. lpc[i-1-j] += r * tmp;
  92791. }
  92792. if(i & 1)
  92793. lpc[j] += lpc[j] * r;
  92794. err *= (1.0 - r * r);
  92795. /* save this order */
  92796. for(j = 0; j <= i; j++)
  92797. lp_coeff[i][j] = (FLAC__real)(-lpc[j]); /* negate FIR filter coeff to get predictor coeff */
  92798. error[i] = err;
  92799. /* see SF bug #1601812 http://sourceforge.net/tracker/index.php?func=detail&aid=1601812&group_id=13478&atid=113478 */
  92800. if(err == 0.0) {
  92801. *max_order = i+1;
  92802. return;
  92803. }
  92804. }
  92805. }
  92806. int FLAC__lpc_quantize_coefficients(const FLAC__real lp_coeff[], unsigned order, unsigned precision, FLAC__int32 qlp_coeff[], int *shift)
  92807. {
  92808. unsigned i;
  92809. FLAC__double cmax;
  92810. FLAC__int32 qmax, qmin;
  92811. FLAC__ASSERT(precision > 0);
  92812. FLAC__ASSERT(precision >= FLAC__MIN_QLP_COEFF_PRECISION);
  92813. /* drop one bit for the sign; from here on out we consider only |lp_coeff[i]| */
  92814. precision--;
  92815. qmax = 1 << precision;
  92816. qmin = -qmax;
  92817. qmax--;
  92818. /* calc cmax = max( |lp_coeff[i]| ) */
  92819. cmax = 0.0;
  92820. for(i = 0; i < order; i++) {
  92821. const FLAC__double d = fabs(lp_coeff[i]);
  92822. if(d > cmax)
  92823. cmax = d;
  92824. }
  92825. if(cmax <= 0.0) {
  92826. /* => coefficients are all 0, which means our constant-detect didn't work */
  92827. return 2;
  92828. }
  92829. else {
  92830. const int max_shiftlimit = (1 << (FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN-1)) - 1;
  92831. const int min_shiftlimit = -max_shiftlimit - 1;
  92832. int log2cmax;
  92833. (void)frexp(cmax, &log2cmax);
  92834. log2cmax--;
  92835. *shift = (int)precision - log2cmax - 1;
  92836. if(*shift > max_shiftlimit)
  92837. *shift = max_shiftlimit;
  92838. else if(*shift < min_shiftlimit)
  92839. return 1;
  92840. }
  92841. if(*shift >= 0) {
  92842. FLAC__double error = 0.0;
  92843. FLAC__int32 q;
  92844. for(i = 0; i < order; i++) {
  92845. error += lp_coeff[i] * (1 << *shift);
  92846. #if 1 /* unfortunately lround() is C99 */
  92847. if(error >= 0.0)
  92848. q = (FLAC__int32)(error + 0.5);
  92849. else
  92850. q = (FLAC__int32)(error - 0.5);
  92851. #else
  92852. q = lround(error);
  92853. #endif
  92854. #ifdef FLAC__OVERFLOW_DETECT
  92855. if(q > qmax+1) /* we expect q==qmax+1 occasionally due to rounding */
  92856. fprintf(stderr,"FLAC__lpc_quantize_coefficients: quantizer overflow: q>qmax %d>%d shift=%d cmax=%f precision=%u lpc[%u]=%f\n",q,qmax,*shift,cmax,precision+1,i,lp_coeff[i]);
  92857. else if(q < qmin)
  92858. fprintf(stderr,"FLAC__lpc_quantize_coefficients: quantizer overflow: q<qmin %d<%d shift=%d cmax=%f precision=%u lpc[%u]=%f\n",q,qmin,*shift,cmax,precision+1,i,lp_coeff[i]);
  92859. #endif
  92860. if(q > qmax)
  92861. q = qmax;
  92862. else if(q < qmin)
  92863. q = qmin;
  92864. error -= q;
  92865. qlp_coeff[i] = q;
  92866. }
  92867. }
  92868. /* negative shift is very rare but due to design flaw, negative shift is
  92869. * a NOP in the decoder, so it must be handled specially by scaling down
  92870. * coeffs
  92871. */
  92872. else {
  92873. const int nshift = -(*shift);
  92874. FLAC__double error = 0.0;
  92875. FLAC__int32 q;
  92876. #ifdef DEBUG
  92877. fprintf(stderr,"FLAC__lpc_quantize_coefficients: negative shift=%d order=%u cmax=%f\n", *shift, order, cmax);
  92878. #endif
  92879. for(i = 0; i < order; i++) {
  92880. error += lp_coeff[i] / (1 << nshift);
  92881. #if 1 /* unfortunately lround() is C99 */
  92882. if(error >= 0.0)
  92883. q = (FLAC__int32)(error + 0.5);
  92884. else
  92885. q = (FLAC__int32)(error - 0.5);
  92886. #else
  92887. q = lround(error);
  92888. #endif
  92889. #ifdef FLAC__OVERFLOW_DETECT
  92890. if(q > qmax+1) /* we expect q==qmax+1 occasionally due to rounding */
  92891. fprintf(stderr,"FLAC__lpc_quantize_coefficients: quantizer overflow: q>qmax %d>%d shift=%d cmax=%f precision=%u lpc[%u]=%f\n",q,qmax,*shift,cmax,precision+1,i,lp_coeff[i]);
  92892. else if(q < qmin)
  92893. fprintf(stderr,"FLAC__lpc_quantize_coefficients: quantizer overflow: q<qmin %d<%d shift=%d cmax=%f precision=%u lpc[%u]=%f\n",q,qmin,*shift,cmax,precision+1,i,lp_coeff[i]);
  92894. #endif
  92895. if(q > qmax)
  92896. q = qmax;
  92897. else if(q < qmin)
  92898. q = qmin;
  92899. error -= q;
  92900. qlp_coeff[i] = q;
  92901. }
  92902. *shift = 0;
  92903. }
  92904. return 0;
  92905. }
  92906. void FLAC__lpc_compute_residual_from_qlp_coefficients(const FLAC__int32 *data, unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 residual[])
  92907. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  92908. {
  92909. FLAC__int64 sumo;
  92910. unsigned i, j;
  92911. FLAC__int32 sum;
  92912. const FLAC__int32 *history;
  92913. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  92914. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  92915. for(i=0;i<order;i++)
  92916. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  92917. fprintf(stderr,"\n");
  92918. #endif
  92919. FLAC__ASSERT(order > 0);
  92920. for(i = 0; i < data_len; i++) {
  92921. sumo = 0;
  92922. sum = 0;
  92923. history = data;
  92924. for(j = 0; j < order; j++) {
  92925. sum += qlp_coeff[j] * (*(--history));
  92926. sumo += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*history);
  92927. #if defined _MSC_VER
  92928. if(sumo > 2147483647I64 || sumo < -2147483648I64)
  92929. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients: OVERFLOW, i=%u, j=%u, c=%d, d=%d, sumo=%I64d\n",i,j,qlp_coeff[j],*history,sumo);
  92930. #else
  92931. if(sumo > 2147483647ll || sumo < -2147483648ll)
  92932. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients: OVERFLOW, i=%u, j=%u, c=%d, d=%d, sumo=%lld\n",i,j,qlp_coeff[j],*history,(long long)sumo);
  92933. #endif
  92934. }
  92935. *(residual++) = *(data++) - (sum >> lp_quantization);
  92936. }
  92937. /* Here's a slower but clearer version:
  92938. for(i = 0; i < data_len; i++) {
  92939. sum = 0;
  92940. for(j = 0; j < order; j++)
  92941. sum += qlp_coeff[j] * data[i-j-1];
  92942. residual[i] = data[i] - (sum >> lp_quantization);
  92943. }
  92944. */
  92945. }
  92946. #else /* fully unrolled version for normal use */
  92947. {
  92948. int i;
  92949. FLAC__int32 sum;
  92950. FLAC__ASSERT(order > 0);
  92951. FLAC__ASSERT(order <= 32);
  92952. /*
  92953. * We do unique versions up to 12th order since that's the subset limit.
  92954. * Also they are roughly ordered to match frequency of occurrence to
  92955. * minimize branching.
  92956. */
  92957. if(order <= 12) {
  92958. if(order > 8) {
  92959. if(order > 10) {
  92960. if(order == 12) {
  92961. for(i = 0; i < (int)data_len; i++) {
  92962. sum = 0;
  92963. sum += qlp_coeff[11] * data[i-12];
  92964. sum += qlp_coeff[10] * data[i-11];
  92965. sum += qlp_coeff[9] * data[i-10];
  92966. sum += qlp_coeff[8] * data[i-9];
  92967. sum += qlp_coeff[7] * data[i-8];
  92968. sum += qlp_coeff[6] * data[i-7];
  92969. sum += qlp_coeff[5] * data[i-6];
  92970. sum += qlp_coeff[4] * data[i-5];
  92971. sum += qlp_coeff[3] * data[i-4];
  92972. sum += qlp_coeff[2] * data[i-3];
  92973. sum += qlp_coeff[1] * data[i-2];
  92974. sum += qlp_coeff[0] * data[i-1];
  92975. residual[i] = data[i] - (sum >> lp_quantization);
  92976. }
  92977. }
  92978. else { /* order == 11 */
  92979. for(i = 0; i < (int)data_len; i++) {
  92980. sum = 0;
  92981. sum += qlp_coeff[10] * data[i-11];
  92982. sum += qlp_coeff[9] * data[i-10];
  92983. sum += qlp_coeff[8] * data[i-9];
  92984. sum += qlp_coeff[7] * data[i-8];
  92985. sum += qlp_coeff[6] * data[i-7];
  92986. sum += qlp_coeff[5] * data[i-6];
  92987. sum += qlp_coeff[4] * data[i-5];
  92988. sum += qlp_coeff[3] * data[i-4];
  92989. sum += qlp_coeff[2] * data[i-3];
  92990. sum += qlp_coeff[1] * data[i-2];
  92991. sum += qlp_coeff[0] * data[i-1];
  92992. residual[i] = data[i] - (sum >> lp_quantization);
  92993. }
  92994. }
  92995. }
  92996. else {
  92997. if(order == 10) {
  92998. for(i = 0; i < (int)data_len; i++) {
  92999. sum = 0;
  93000. sum += qlp_coeff[9] * data[i-10];
  93001. sum += qlp_coeff[8] * data[i-9];
  93002. sum += qlp_coeff[7] * data[i-8];
  93003. sum += qlp_coeff[6] * data[i-7];
  93004. sum += qlp_coeff[5] * data[i-6];
  93005. sum += qlp_coeff[4] * data[i-5];
  93006. sum += qlp_coeff[3] * data[i-4];
  93007. sum += qlp_coeff[2] * data[i-3];
  93008. sum += qlp_coeff[1] * data[i-2];
  93009. sum += qlp_coeff[0] * data[i-1];
  93010. residual[i] = data[i] - (sum >> lp_quantization);
  93011. }
  93012. }
  93013. else { /* order == 9 */
  93014. for(i = 0; i < (int)data_len; i++) {
  93015. sum = 0;
  93016. sum += qlp_coeff[8] * data[i-9];
  93017. sum += qlp_coeff[7] * data[i-8];
  93018. sum += qlp_coeff[6] * data[i-7];
  93019. sum += qlp_coeff[5] * data[i-6];
  93020. sum += qlp_coeff[4] * data[i-5];
  93021. sum += qlp_coeff[3] * data[i-4];
  93022. sum += qlp_coeff[2] * data[i-3];
  93023. sum += qlp_coeff[1] * data[i-2];
  93024. sum += qlp_coeff[0] * data[i-1];
  93025. residual[i] = data[i] - (sum >> lp_quantization);
  93026. }
  93027. }
  93028. }
  93029. }
  93030. else if(order > 4) {
  93031. if(order > 6) {
  93032. if(order == 8) {
  93033. for(i = 0; i < (int)data_len; i++) {
  93034. sum = 0;
  93035. sum += qlp_coeff[7] * data[i-8];
  93036. sum += qlp_coeff[6] * data[i-7];
  93037. sum += qlp_coeff[5] * data[i-6];
  93038. sum += qlp_coeff[4] * data[i-5];
  93039. sum += qlp_coeff[3] * data[i-4];
  93040. sum += qlp_coeff[2] * data[i-3];
  93041. sum += qlp_coeff[1] * data[i-2];
  93042. sum += qlp_coeff[0] * data[i-1];
  93043. residual[i] = data[i] - (sum >> lp_quantization);
  93044. }
  93045. }
  93046. else { /* order == 7 */
  93047. for(i = 0; i < (int)data_len; i++) {
  93048. sum = 0;
  93049. sum += qlp_coeff[6] * data[i-7];
  93050. sum += qlp_coeff[5] * data[i-6];
  93051. sum += qlp_coeff[4] * data[i-5];
  93052. sum += qlp_coeff[3] * data[i-4];
  93053. sum += qlp_coeff[2] * data[i-3];
  93054. sum += qlp_coeff[1] * data[i-2];
  93055. sum += qlp_coeff[0] * data[i-1];
  93056. residual[i] = data[i] - (sum >> lp_quantization);
  93057. }
  93058. }
  93059. }
  93060. else {
  93061. if(order == 6) {
  93062. for(i = 0; i < (int)data_len; i++) {
  93063. sum = 0;
  93064. sum += qlp_coeff[5] * data[i-6];
  93065. sum += qlp_coeff[4] * data[i-5];
  93066. sum += qlp_coeff[3] * data[i-4];
  93067. sum += qlp_coeff[2] * data[i-3];
  93068. sum += qlp_coeff[1] * data[i-2];
  93069. sum += qlp_coeff[0] * data[i-1];
  93070. residual[i] = data[i] - (sum >> lp_quantization);
  93071. }
  93072. }
  93073. else { /* order == 5 */
  93074. for(i = 0; i < (int)data_len; i++) {
  93075. sum = 0;
  93076. sum += qlp_coeff[4] * data[i-5];
  93077. sum += qlp_coeff[3] * data[i-4];
  93078. sum += qlp_coeff[2] * data[i-3];
  93079. sum += qlp_coeff[1] * data[i-2];
  93080. sum += qlp_coeff[0] * data[i-1];
  93081. residual[i] = data[i] - (sum >> lp_quantization);
  93082. }
  93083. }
  93084. }
  93085. }
  93086. else {
  93087. if(order > 2) {
  93088. if(order == 4) {
  93089. for(i = 0; i < (int)data_len; i++) {
  93090. sum = 0;
  93091. sum += qlp_coeff[3] * data[i-4];
  93092. sum += qlp_coeff[2] * data[i-3];
  93093. sum += qlp_coeff[1] * data[i-2];
  93094. sum += qlp_coeff[0] * data[i-1];
  93095. residual[i] = data[i] - (sum >> lp_quantization);
  93096. }
  93097. }
  93098. else { /* order == 3 */
  93099. for(i = 0; i < (int)data_len; i++) {
  93100. sum = 0;
  93101. sum += qlp_coeff[2] * data[i-3];
  93102. sum += qlp_coeff[1] * data[i-2];
  93103. sum += qlp_coeff[0] * data[i-1];
  93104. residual[i] = data[i] - (sum >> lp_quantization);
  93105. }
  93106. }
  93107. }
  93108. else {
  93109. if(order == 2) {
  93110. for(i = 0; i < (int)data_len; i++) {
  93111. sum = 0;
  93112. sum += qlp_coeff[1] * data[i-2];
  93113. sum += qlp_coeff[0] * data[i-1];
  93114. residual[i] = data[i] - (sum >> lp_quantization);
  93115. }
  93116. }
  93117. else { /* order == 1 */
  93118. for(i = 0; i < (int)data_len; i++)
  93119. residual[i] = data[i] - ((qlp_coeff[0] * data[i-1]) >> lp_quantization);
  93120. }
  93121. }
  93122. }
  93123. }
  93124. else { /* order > 12 */
  93125. for(i = 0; i < (int)data_len; i++) {
  93126. sum = 0;
  93127. switch(order) {
  93128. case 32: sum += qlp_coeff[31] * data[i-32];
  93129. case 31: sum += qlp_coeff[30] * data[i-31];
  93130. case 30: sum += qlp_coeff[29] * data[i-30];
  93131. case 29: sum += qlp_coeff[28] * data[i-29];
  93132. case 28: sum += qlp_coeff[27] * data[i-28];
  93133. case 27: sum += qlp_coeff[26] * data[i-27];
  93134. case 26: sum += qlp_coeff[25] * data[i-26];
  93135. case 25: sum += qlp_coeff[24] * data[i-25];
  93136. case 24: sum += qlp_coeff[23] * data[i-24];
  93137. case 23: sum += qlp_coeff[22] * data[i-23];
  93138. case 22: sum += qlp_coeff[21] * data[i-22];
  93139. case 21: sum += qlp_coeff[20] * data[i-21];
  93140. case 20: sum += qlp_coeff[19] * data[i-20];
  93141. case 19: sum += qlp_coeff[18] * data[i-19];
  93142. case 18: sum += qlp_coeff[17] * data[i-18];
  93143. case 17: sum += qlp_coeff[16] * data[i-17];
  93144. case 16: sum += qlp_coeff[15] * data[i-16];
  93145. case 15: sum += qlp_coeff[14] * data[i-15];
  93146. case 14: sum += qlp_coeff[13] * data[i-14];
  93147. case 13: sum += qlp_coeff[12] * data[i-13];
  93148. sum += qlp_coeff[11] * data[i-12];
  93149. sum += qlp_coeff[10] * data[i-11];
  93150. sum += qlp_coeff[ 9] * data[i-10];
  93151. sum += qlp_coeff[ 8] * data[i- 9];
  93152. sum += qlp_coeff[ 7] * data[i- 8];
  93153. sum += qlp_coeff[ 6] * data[i- 7];
  93154. sum += qlp_coeff[ 5] * data[i- 6];
  93155. sum += qlp_coeff[ 4] * data[i- 5];
  93156. sum += qlp_coeff[ 3] * data[i- 4];
  93157. sum += qlp_coeff[ 2] * data[i- 3];
  93158. sum += qlp_coeff[ 1] * data[i- 2];
  93159. sum += qlp_coeff[ 0] * data[i- 1];
  93160. }
  93161. residual[i] = data[i] - (sum >> lp_quantization);
  93162. }
  93163. }
  93164. }
  93165. #endif
  93166. void FLAC__lpc_compute_residual_from_qlp_coefficients_wide(const FLAC__int32 *data, unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 residual[])
  93167. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  93168. {
  93169. unsigned i, j;
  93170. FLAC__int64 sum;
  93171. const FLAC__int32 *history;
  93172. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  93173. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  93174. for(i=0;i<order;i++)
  93175. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  93176. fprintf(stderr,"\n");
  93177. #endif
  93178. FLAC__ASSERT(order > 0);
  93179. for(i = 0; i < data_len; i++) {
  93180. sum = 0;
  93181. history = data;
  93182. for(j = 0; j < order; j++)
  93183. sum += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*(--history));
  93184. if(FLAC__bitmath_silog2_wide(sum >> lp_quantization) > 32) {
  93185. #if defined _MSC_VER
  93186. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: OVERFLOW, i=%u, sum=%I64d\n", i, sum >> lp_quantization);
  93187. #else
  93188. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: OVERFLOW, i=%u, sum=%lld\n", i, (long long)(sum >> lp_quantization));
  93189. #endif
  93190. break;
  93191. }
  93192. if(FLAC__bitmath_silog2_wide((FLAC__int64)(*data) - (sum >> lp_quantization)) > 32) {
  93193. #if defined _MSC_VER
  93194. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: OVERFLOW, i=%u, data=%d, sum=%I64d, residual=%I64d\n", i, *data, sum >> lp_quantization, (FLAC__int64)(*data) - (sum >> lp_quantization));
  93195. #else
  93196. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: OVERFLOW, i=%u, data=%d, sum=%lld, residual=%lld\n", i, *data, (long long)(sum >> lp_quantization), (long long)((FLAC__int64)(*data) - (sum >> lp_quantization)));
  93197. #endif
  93198. break;
  93199. }
  93200. *(residual++) = *(data++) - (FLAC__int32)(sum >> lp_quantization);
  93201. }
  93202. }
  93203. #else /* fully unrolled version for normal use */
  93204. {
  93205. int i;
  93206. FLAC__int64 sum;
  93207. FLAC__ASSERT(order > 0);
  93208. FLAC__ASSERT(order <= 32);
  93209. /*
  93210. * We do unique versions up to 12th order since that's the subset limit.
  93211. * Also they are roughly ordered to match frequency of occurrence to
  93212. * minimize branching.
  93213. */
  93214. if(order <= 12) {
  93215. if(order > 8) {
  93216. if(order > 10) {
  93217. if(order == 12) {
  93218. for(i = 0; i < (int)data_len; i++) {
  93219. sum = 0;
  93220. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  93221. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  93222. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  93223. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  93224. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  93225. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  93226. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  93227. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  93228. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  93229. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  93230. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  93231. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  93232. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  93233. }
  93234. }
  93235. else { /* order == 11 */
  93236. for(i = 0; i < (int)data_len; i++) {
  93237. sum = 0;
  93238. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  93239. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  93240. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  93241. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  93242. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  93243. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  93244. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  93245. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  93246. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  93247. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  93248. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  93249. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  93250. }
  93251. }
  93252. }
  93253. else {
  93254. if(order == 10) {
  93255. for(i = 0; i < (int)data_len; i++) {
  93256. sum = 0;
  93257. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  93258. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  93259. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  93260. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  93261. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  93262. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  93263. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  93264. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  93265. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  93266. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  93267. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  93268. }
  93269. }
  93270. else { /* order == 9 */
  93271. for(i = 0; i < (int)data_len; i++) {
  93272. sum = 0;
  93273. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  93274. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  93275. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  93276. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  93277. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  93278. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  93279. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  93280. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  93281. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  93282. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  93283. }
  93284. }
  93285. }
  93286. }
  93287. else if(order > 4) {
  93288. if(order > 6) {
  93289. if(order == 8) {
  93290. for(i = 0; i < (int)data_len; i++) {
  93291. sum = 0;
  93292. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  93293. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  93294. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  93295. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  93296. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  93297. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  93298. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  93299. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  93300. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  93301. }
  93302. }
  93303. else { /* order == 7 */
  93304. for(i = 0; i < (int)data_len; i++) {
  93305. sum = 0;
  93306. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  93307. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  93308. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  93309. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  93310. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  93311. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  93312. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  93313. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  93314. }
  93315. }
  93316. }
  93317. else {
  93318. if(order == 6) {
  93319. for(i = 0; i < (int)data_len; i++) {
  93320. sum = 0;
  93321. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  93322. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  93323. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  93324. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  93325. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  93326. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  93327. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  93328. }
  93329. }
  93330. else { /* order == 5 */
  93331. for(i = 0; i < (int)data_len; i++) {
  93332. sum = 0;
  93333. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  93334. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  93335. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  93336. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  93337. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  93338. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  93339. }
  93340. }
  93341. }
  93342. }
  93343. else {
  93344. if(order > 2) {
  93345. if(order == 4) {
  93346. for(i = 0; i < (int)data_len; i++) {
  93347. sum = 0;
  93348. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  93349. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  93350. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  93351. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  93352. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  93353. }
  93354. }
  93355. else { /* order == 3 */
  93356. for(i = 0; i < (int)data_len; i++) {
  93357. sum = 0;
  93358. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  93359. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  93360. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  93361. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  93362. }
  93363. }
  93364. }
  93365. else {
  93366. if(order == 2) {
  93367. for(i = 0; i < (int)data_len; i++) {
  93368. sum = 0;
  93369. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  93370. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  93371. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  93372. }
  93373. }
  93374. else { /* order == 1 */
  93375. for(i = 0; i < (int)data_len; i++)
  93376. residual[i] = data[i] - (FLAC__int32)((qlp_coeff[0] * (FLAC__int64)data[i-1]) >> lp_quantization);
  93377. }
  93378. }
  93379. }
  93380. }
  93381. else { /* order > 12 */
  93382. for(i = 0; i < (int)data_len; i++) {
  93383. sum = 0;
  93384. switch(order) {
  93385. case 32: sum += qlp_coeff[31] * (FLAC__int64)data[i-32];
  93386. case 31: sum += qlp_coeff[30] * (FLAC__int64)data[i-31];
  93387. case 30: sum += qlp_coeff[29] * (FLAC__int64)data[i-30];
  93388. case 29: sum += qlp_coeff[28] * (FLAC__int64)data[i-29];
  93389. case 28: sum += qlp_coeff[27] * (FLAC__int64)data[i-28];
  93390. case 27: sum += qlp_coeff[26] * (FLAC__int64)data[i-27];
  93391. case 26: sum += qlp_coeff[25] * (FLAC__int64)data[i-26];
  93392. case 25: sum += qlp_coeff[24] * (FLAC__int64)data[i-25];
  93393. case 24: sum += qlp_coeff[23] * (FLAC__int64)data[i-24];
  93394. case 23: sum += qlp_coeff[22] * (FLAC__int64)data[i-23];
  93395. case 22: sum += qlp_coeff[21] * (FLAC__int64)data[i-22];
  93396. case 21: sum += qlp_coeff[20] * (FLAC__int64)data[i-21];
  93397. case 20: sum += qlp_coeff[19] * (FLAC__int64)data[i-20];
  93398. case 19: sum += qlp_coeff[18] * (FLAC__int64)data[i-19];
  93399. case 18: sum += qlp_coeff[17] * (FLAC__int64)data[i-18];
  93400. case 17: sum += qlp_coeff[16] * (FLAC__int64)data[i-17];
  93401. case 16: sum += qlp_coeff[15] * (FLAC__int64)data[i-16];
  93402. case 15: sum += qlp_coeff[14] * (FLAC__int64)data[i-15];
  93403. case 14: sum += qlp_coeff[13] * (FLAC__int64)data[i-14];
  93404. case 13: sum += qlp_coeff[12] * (FLAC__int64)data[i-13];
  93405. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  93406. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  93407. sum += qlp_coeff[ 9] * (FLAC__int64)data[i-10];
  93408. sum += qlp_coeff[ 8] * (FLAC__int64)data[i- 9];
  93409. sum += qlp_coeff[ 7] * (FLAC__int64)data[i- 8];
  93410. sum += qlp_coeff[ 6] * (FLAC__int64)data[i- 7];
  93411. sum += qlp_coeff[ 5] * (FLAC__int64)data[i- 6];
  93412. sum += qlp_coeff[ 4] * (FLAC__int64)data[i- 5];
  93413. sum += qlp_coeff[ 3] * (FLAC__int64)data[i- 4];
  93414. sum += qlp_coeff[ 2] * (FLAC__int64)data[i- 3];
  93415. sum += qlp_coeff[ 1] * (FLAC__int64)data[i- 2];
  93416. sum += qlp_coeff[ 0] * (FLAC__int64)data[i- 1];
  93417. }
  93418. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  93419. }
  93420. }
  93421. }
  93422. #endif
  93423. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  93424. void FLAC__lpc_restore_signal(const FLAC__int32 residual[], unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 data[])
  93425. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  93426. {
  93427. FLAC__int64 sumo;
  93428. unsigned i, j;
  93429. FLAC__int32 sum;
  93430. const FLAC__int32 *r = residual, *history;
  93431. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  93432. fprintf(stderr,"FLAC__lpc_restore_signal: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  93433. for(i=0;i<order;i++)
  93434. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  93435. fprintf(stderr,"\n");
  93436. #endif
  93437. FLAC__ASSERT(order > 0);
  93438. for(i = 0; i < data_len; i++) {
  93439. sumo = 0;
  93440. sum = 0;
  93441. history = data;
  93442. for(j = 0; j < order; j++) {
  93443. sum += qlp_coeff[j] * (*(--history));
  93444. sumo += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*history);
  93445. #if defined _MSC_VER
  93446. if(sumo > 2147483647I64 || sumo < -2147483648I64)
  93447. fprintf(stderr,"FLAC__lpc_restore_signal: OVERFLOW, i=%u, j=%u, c=%d, d=%d, sumo=%I64d\n",i,j,qlp_coeff[j],*history,sumo);
  93448. #else
  93449. if(sumo > 2147483647ll || sumo < -2147483648ll)
  93450. fprintf(stderr,"FLAC__lpc_restore_signal: OVERFLOW, i=%u, j=%u, c=%d, d=%d, sumo=%lld\n",i,j,qlp_coeff[j],*history,(long long)sumo);
  93451. #endif
  93452. }
  93453. *(data++) = *(r++) + (sum >> lp_quantization);
  93454. }
  93455. /* Here's a slower but clearer version:
  93456. for(i = 0; i < data_len; i++) {
  93457. sum = 0;
  93458. for(j = 0; j < order; j++)
  93459. sum += qlp_coeff[j] * data[i-j-1];
  93460. data[i] = residual[i] + (sum >> lp_quantization);
  93461. }
  93462. */
  93463. }
  93464. #else /* fully unrolled version for normal use */
  93465. {
  93466. int i;
  93467. FLAC__int32 sum;
  93468. FLAC__ASSERT(order > 0);
  93469. FLAC__ASSERT(order <= 32);
  93470. /*
  93471. * We do unique versions up to 12th order since that's the subset limit.
  93472. * Also they are roughly ordered to match frequency of occurrence to
  93473. * minimize branching.
  93474. */
  93475. if(order <= 12) {
  93476. if(order > 8) {
  93477. if(order > 10) {
  93478. if(order == 12) {
  93479. for(i = 0; i < (int)data_len; i++) {
  93480. sum = 0;
  93481. sum += qlp_coeff[11] * data[i-12];
  93482. sum += qlp_coeff[10] * data[i-11];
  93483. sum += qlp_coeff[9] * data[i-10];
  93484. sum += qlp_coeff[8] * data[i-9];
  93485. sum += qlp_coeff[7] * data[i-8];
  93486. sum += qlp_coeff[6] * data[i-7];
  93487. sum += qlp_coeff[5] * data[i-6];
  93488. sum += qlp_coeff[4] * data[i-5];
  93489. sum += qlp_coeff[3] * data[i-4];
  93490. sum += qlp_coeff[2] * data[i-3];
  93491. sum += qlp_coeff[1] * data[i-2];
  93492. sum += qlp_coeff[0] * data[i-1];
  93493. data[i] = residual[i] + (sum >> lp_quantization);
  93494. }
  93495. }
  93496. else { /* order == 11 */
  93497. for(i = 0; i < (int)data_len; i++) {
  93498. sum = 0;
  93499. sum += qlp_coeff[10] * data[i-11];
  93500. sum += qlp_coeff[9] * data[i-10];
  93501. sum += qlp_coeff[8] * data[i-9];
  93502. sum += qlp_coeff[7] * data[i-8];
  93503. sum += qlp_coeff[6] * data[i-7];
  93504. sum += qlp_coeff[5] * data[i-6];
  93505. sum += qlp_coeff[4] * data[i-5];
  93506. sum += qlp_coeff[3] * data[i-4];
  93507. sum += qlp_coeff[2] * data[i-3];
  93508. sum += qlp_coeff[1] * data[i-2];
  93509. sum += qlp_coeff[0] * data[i-1];
  93510. data[i] = residual[i] + (sum >> lp_quantization);
  93511. }
  93512. }
  93513. }
  93514. else {
  93515. if(order == 10) {
  93516. for(i = 0; i < (int)data_len; i++) {
  93517. sum = 0;
  93518. sum += qlp_coeff[9] * data[i-10];
  93519. sum += qlp_coeff[8] * data[i-9];
  93520. sum += qlp_coeff[7] * data[i-8];
  93521. sum += qlp_coeff[6] * data[i-7];
  93522. sum += qlp_coeff[5] * data[i-6];
  93523. sum += qlp_coeff[4] * data[i-5];
  93524. sum += qlp_coeff[3] * data[i-4];
  93525. sum += qlp_coeff[2] * data[i-3];
  93526. sum += qlp_coeff[1] * data[i-2];
  93527. sum += qlp_coeff[0] * data[i-1];
  93528. data[i] = residual[i] + (sum >> lp_quantization);
  93529. }
  93530. }
  93531. else { /* order == 9 */
  93532. for(i = 0; i < (int)data_len; i++) {
  93533. sum = 0;
  93534. sum += qlp_coeff[8] * data[i-9];
  93535. sum += qlp_coeff[7] * data[i-8];
  93536. sum += qlp_coeff[6] * data[i-7];
  93537. sum += qlp_coeff[5] * data[i-6];
  93538. sum += qlp_coeff[4] * data[i-5];
  93539. sum += qlp_coeff[3] * data[i-4];
  93540. sum += qlp_coeff[2] * data[i-3];
  93541. sum += qlp_coeff[1] * data[i-2];
  93542. sum += qlp_coeff[0] * data[i-1];
  93543. data[i] = residual[i] + (sum >> lp_quantization);
  93544. }
  93545. }
  93546. }
  93547. }
  93548. else if(order > 4) {
  93549. if(order > 6) {
  93550. if(order == 8) {
  93551. for(i = 0; i < (int)data_len; i++) {
  93552. sum = 0;
  93553. sum += qlp_coeff[7] * data[i-8];
  93554. sum += qlp_coeff[6] * data[i-7];
  93555. sum += qlp_coeff[5] * data[i-6];
  93556. sum += qlp_coeff[4] * data[i-5];
  93557. sum += qlp_coeff[3] * data[i-4];
  93558. sum += qlp_coeff[2] * data[i-3];
  93559. sum += qlp_coeff[1] * data[i-2];
  93560. sum += qlp_coeff[0] * data[i-1];
  93561. data[i] = residual[i] + (sum >> lp_quantization);
  93562. }
  93563. }
  93564. else { /* order == 7 */
  93565. for(i = 0; i < (int)data_len; i++) {
  93566. sum = 0;
  93567. sum += qlp_coeff[6] * data[i-7];
  93568. sum += qlp_coeff[5] * data[i-6];
  93569. sum += qlp_coeff[4] * data[i-5];
  93570. sum += qlp_coeff[3] * data[i-4];
  93571. sum += qlp_coeff[2] * data[i-3];
  93572. sum += qlp_coeff[1] * data[i-2];
  93573. sum += qlp_coeff[0] * data[i-1];
  93574. data[i] = residual[i] + (sum >> lp_quantization);
  93575. }
  93576. }
  93577. }
  93578. else {
  93579. if(order == 6) {
  93580. for(i = 0; i < (int)data_len; i++) {
  93581. sum = 0;
  93582. sum += qlp_coeff[5] * data[i-6];
  93583. sum += qlp_coeff[4] * data[i-5];
  93584. sum += qlp_coeff[3] * data[i-4];
  93585. sum += qlp_coeff[2] * data[i-3];
  93586. sum += qlp_coeff[1] * data[i-2];
  93587. sum += qlp_coeff[0] * data[i-1];
  93588. data[i] = residual[i] + (sum >> lp_quantization);
  93589. }
  93590. }
  93591. else { /* order == 5 */
  93592. for(i = 0; i < (int)data_len; i++) {
  93593. sum = 0;
  93594. sum += qlp_coeff[4] * data[i-5];
  93595. sum += qlp_coeff[3] * data[i-4];
  93596. sum += qlp_coeff[2] * data[i-3];
  93597. sum += qlp_coeff[1] * data[i-2];
  93598. sum += qlp_coeff[0] * data[i-1];
  93599. data[i] = residual[i] + (sum >> lp_quantization);
  93600. }
  93601. }
  93602. }
  93603. }
  93604. else {
  93605. if(order > 2) {
  93606. if(order == 4) {
  93607. for(i = 0; i < (int)data_len; i++) {
  93608. sum = 0;
  93609. sum += qlp_coeff[3] * data[i-4];
  93610. sum += qlp_coeff[2] * data[i-3];
  93611. sum += qlp_coeff[1] * data[i-2];
  93612. sum += qlp_coeff[0] * data[i-1];
  93613. data[i] = residual[i] + (sum >> lp_quantization);
  93614. }
  93615. }
  93616. else { /* order == 3 */
  93617. for(i = 0; i < (int)data_len; i++) {
  93618. sum = 0;
  93619. sum += qlp_coeff[2] * data[i-3];
  93620. sum += qlp_coeff[1] * data[i-2];
  93621. sum += qlp_coeff[0] * data[i-1];
  93622. data[i] = residual[i] + (sum >> lp_quantization);
  93623. }
  93624. }
  93625. }
  93626. else {
  93627. if(order == 2) {
  93628. for(i = 0; i < (int)data_len; i++) {
  93629. sum = 0;
  93630. sum += qlp_coeff[1] * data[i-2];
  93631. sum += qlp_coeff[0] * data[i-1];
  93632. data[i] = residual[i] + (sum >> lp_quantization);
  93633. }
  93634. }
  93635. else { /* order == 1 */
  93636. for(i = 0; i < (int)data_len; i++)
  93637. data[i] = residual[i] + ((qlp_coeff[0] * data[i-1]) >> lp_quantization);
  93638. }
  93639. }
  93640. }
  93641. }
  93642. else { /* order > 12 */
  93643. for(i = 0; i < (int)data_len; i++) {
  93644. sum = 0;
  93645. switch(order) {
  93646. case 32: sum += qlp_coeff[31] * data[i-32];
  93647. case 31: sum += qlp_coeff[30] * data[i-31];
  93648. case 30: sum += qlp_coeff[29] * data[i-30];
  93649. case 29: sum += qlp_coeff[28] * data[i-29];
  93650. case 28: sum += qlp_coeff[27] * data[i-28];
  93651. case 27: sum += qlp_coeff[26] * data[i-27];
  93652. case 26: sum += qlp_coeff[25] * data[i-26];
  93653. case 25: sum += qlp_coeff[24] * data[i-25];
  93654. case 24: sum += qlp_coeff[23] * data[i-24];
  93655. case 23: sum += qlp_coeff[22] * data[i-23];
  93656. case 22: sum += qlp_coeff[21] * data[i-22];
  93657. case 21: sum += qlp_coeff[20] * data[i-21];
  93658. case 20: sum += qlp_coeff[19] * data[i-20];
  93659. case 19: sum += qlp_coeff[18] * data[i-19];
  93660. case 18: sum += qlp_coeff[17] * data[i-18];
  93661. case 17: sum += qlp_coeff[16] * data[i-17];
  93662. case 16: sum += qlp_coeff[15] * data[i-16];
  93663. case 15: sum += qlp_coeff[14] * data[i-15];
  93664. case 14: sum += qlp_coeff[13] * data[i-14];
  93665. case 13: sum += qlp_coeff[12] * data[i-13];
  93666. sum += qlp_coeff[11] * data[i-12];
  93667. sum += qlp_coeff[10] * data[i-11];
  93668. sum += qlp_coeff[ 9] * data[i-10];
  93669. sum += qlp_coeff[ 8] * data[i- 9];
  93670. sum += qlp_coeff[ 7] * data[i- 8];
  93671. sum += qlp_coeff[ 6] * data[i- 7];
  93672. sum += qlp_coeff[ 5] * data[i- 6];
  93673. sum += qlp_coeff[ 4] * data[i- 5];
  93674. sum += qlp_coeff[ 3] * data[i- 4];
  93675. sum += qlp_coeff[ 2] * data[i- 3];
  93676. sum += qlp_coeff[ 1] * data[i- 2];
  93677. sum += qlp_coeff[ 0] * data[i- 1];
  93678. }
  93679. data[i] = residual[i] + (sum >> lp_quantization);
  93680. }
  93681. }
  93682. }
  93683. #endif
  93684. void FLAC__lpc_restore_signal_wide(const FLAC__int32 residual[], unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 data[])
  93685. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  93686. {
  93687. unsigned i, j;
  93688. FLAC__int64 sum;
  93689. const FLAC__int32 *r = residual, *history;
  93690. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  93691. fprintf(stderr,"FLAC__lpc_restore_signal_wide: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  93692. for(i=0;i<order;i++)
  93693. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  93694. fprintf(stderr,"\n");
  93695. #endif
  93696. FLAC__ASSERT(order > 0);
  93697. for(i = 0; i < data_len; i++) {
  93698. sum = 0;
  93699. history = data;
  93700. for(j = 0; j < order; j++)
  93701. sum += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*(--history));
  93702. if(FLAC__bitmath_silog2_wide(sum >> lp_quantization) > 32) {
  93703. #ifdef _MSC_VER
  93704. fprintf(stderr,"FLAC__lpc_restore_signal_wide: OVERFLOW, i=%u, sum=%I64d\n", i, sum >> lp_quantization);
  93705. #else
  93706. fprintf(stderr,"FLAC__lpc_restore_signal_wide: OVERFLOW, i=%u, sum=%lld\n", i, (long long)(sum >> lp_quantization));
  93707. #endif
  93708. break;
  93709. }
  93710. if(FLAC__bitmath_silog2_wide((FLAC__int64)(*r) + (sum >> lp_quantization)) > 32) {
  93711. #ifdef _MSC_VER
  93712. fprintf(stderr,"FLAC__lpc_restore_signal_wide: OVERFLOW, i=%u, residual=%d, sum=%I64d, data=%I64d\n", i, *r, sum >> lp_quantization, (FLAC__int64)(*r) + (sum >> lp_quantization));
  93713. #else
  93714. fprintf(stderr,"FLAC__lpc_restore_signal_wide: OVERFLOW, i=%u, residual=%d, sum=%lld, data=%lld\n", i, *r, (long long)(sum >> lp_quantization), (long long)((FLAC__int64)(*r) + (sum >> lp_quantization)));
  93715. #endif
  93716. break;
  93717. }
  93718. *(data++) = *(r++) + (FLAC__int32)(sum >> lp_quantization);
  93719. }
  93720. }
  93721. #else /* fully unrolled version for normal use */
  93722. {
  93723. int i;
  93724. FLAC__int64 sum;
  93725. FLAC__ASSERT(order > 0);
  93726. FLAC__ASSERT(order <= 32);
  93727. /*
  93728. * We do unique versions up to 12th order since that's the subset limit.
  93729. * Also they are roughly ordered to match frequency of occurrence to
  93730. * minimize branching.
  93731. */
  93732. if(order <= 12) {
  93733. if(order > 8) {
  93734. if(order > 10) {
  93735. if(order == 12) {
  93736. for(i = 0; i < (int)data_len; i++) {
  93737. sum = 0;
  93738. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  93739. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  93740. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  93741. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  93742. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  93743. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  93744. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  93745. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  93746. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  93747. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  93748. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  93749. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  93750. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  93751. }
  93752. }
  93753. else { /* order == 11 */
  93754. for(i = 0; i < (int)data_len; i++) {
  93755. sum = 0;
  93756. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  93757. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  93758. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  93759. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  93760. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  93761. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  93762. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  93763. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  93764. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  93765. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  93766. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  93767. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  93768. }
  93769. }
  93770. }
  93771. else {
  93772. if(order == 10) {
  93773. for(i = 0; i < (int)data_len; i++) {
  93774. sum = 0;
  93775. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  93776. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  93777. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  93778. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  93779. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  93780. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  93781. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  93782. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  93783. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  93784. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  93785. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  93786. }
  93787. }
  93788. else { /* order == 9 */
  93789. for(i = 0; i < (int)data_len; i++) {
  93790. sum = 0;
  93791. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  93792. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  93793. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  93794. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  93795. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  93796. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  93797. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  93798. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  93799. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  93800. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  93801. }
  93802. }
  93803. }
  93804. }
  93805. else if(order > 4) {
  93806. if(order > 6) {
  93807. if(order == 8) {
  93808. for(i = 0; i < (int)data_len; i++) {
  93809. sum = 0;
  93810. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  93811. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  93812. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  93813. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  93814. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  93815. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  93816. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  93817. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  93818. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  93819. }
  93820. }
  93821. else { /* order == 7 */
  93822. for(i = 0; i < (int)data_len; i++) {
  93823. sum = 0;
  93824. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  93825. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  93826. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  93827. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  93828. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  93829. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  93830. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  93831. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  93832. }
  93833. }
  93834. }
  93835. else {
  93836. if(order == 6) {
  93837. for(i = 0; i < (int)data_len; i++) {
  93838. sum = 0;
  93839. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  93840. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  93841. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  93842. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  93843. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  93844. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  93845. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  93846. }
  93847. }
  93848. else { /* order == 5 */
  93849. for(i = 0; i < (int)data_len; i++) {
  93850. sum = 0;
  93851. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  93852. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  93853. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  93854. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  93855. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  93856. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  93857. }
  93858. }
  93859. }
  93860. }
  93861. else {
  93862. if(order > 2) {
  93863. if(order == 4) {
  93864. for(i = 0; i < (int)data_len; i++) {
  93865. sum = 0;
  93866. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  93867. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  93868. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  93869. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  93870. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  93871. }
  93872. }
  93873. else { /* order == 3 */
  93874. for(i = 0; i < (int)data_len; i++) {
  93875. sum = 0;
  93876. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  93877. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  93878. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  93879. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  93880. }
  93881. }
  93882. }
  93883. else {
  93884. if(order == 2) {
  93885. for(i = 0; i < (int)data_len; i++) {
  93886. sum = 0;
  93887. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  93888. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  93889. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  93890. }
  93891. }
  93892. else { /* order == 1 */
  93893. for(i = 0; i < (int)data_len; i++)
  93894. data[i] = residual[i] + (FLAC__int32)((qlp_coeff[0] * (FLAC__int64)data[i-1]) >> lp_quantization);
  93895. }
  93896. }
  93897. }
  93898. }
  93899. else { /* order > 12 */
  93900. for(i = 0; i < (int)data_len; i++) {
  93901. sum = 0;
  93902. switch(order) {
  93903. case 32: sum += qlp_coeff[31] * (FLAC__int64)data[i-32];
  93904. case 31: sum += qlp_coeff[30] * (FLAC__int64)data[i-31];
  93905. case 30: sum += qlp_coeff[29] * (FLAC__int64)data[i-30];
  93906. case 29: sum += qlp_coeff[28] * (FLAC__int64)data[i-29];
  93907. case 28: sum += qlp_coeff[27] * (FLAC__int64)data[i-28];
  93908. case 27: sum += qlp_coeff[26] * (FLAC__int64)data[i-27];
  93909. case 26: sum += qlp_coeff[25] * (FLAC__int64)data[i-26];
  93910. case 25: sum += qlp_coeff[24] * (FLAC__int64)data[i-25];
  93911. case 24: sum += qlp_coeff[23] * (FLAC__int64)data[i-24];
  93912. case 23: sum += qlp_coeff[22] * (FLAC__int64)data[i-23];
  93913. case 22: sum += qlp_coeff[21] * (FLAC__int64)data[i-22];
  93914. case 21: sum += qlp_coeff[20] * (FLAC__int64)data[i-21];
  93915. case 20: sum += qlp_coeff[19] * (FLAC__int64)data[i-20];
  93916. case 19: sum += qlp_coeff[18] * (FLAC__int64)data[i-19];
  93917. case 18: sum += qlp_coeff[17] * (FLAC__int64)data[i-18];
  93918. case 17: sum += qlp_coeff[16] * (FLAC__int64)data[i-17];
  93919. case 16: sum += qlp_coeff[15] * (FLAC__int64)data[i-16];
  93920. case 15: sum += qlp_coeff[14] * (FLAC__int64)data[i-15];
  93921. case 14: sum += qlp_coeff[13] * (FLAC__int64)data[i-14];
  93922. case 13: sum += qlp_coeff[12] * (FLAC__int64)data[i-13];
  93923. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  93924. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  93925. sum += qlp_coeff[ 9] * (FLAC__int64)data[i-10];
  93926. sum += qlp_coeff[ 8] * (FLAC__int64)data[i- 9];
  93927. sum += qlp_coeff[ 7] * (FLAC__int64)data[i- 8];
  93928. sum += qlp_coeff[ 6] * (FLAC__int64)data[i- 7];
  93929. sum += qlp_coeff[ 5] * (FLAC__int64)data[i- 6];
  93930. sum += qlp_coeff[ 4] * (FLAC__int64)data[i- 5];
  93931. sum += qlp_coeff[ 3] * (FLAC__int64)data[i- 4];
  93932. sum += qlp_coeff[ 2] * (FLAC__int64)data[i- 3];
  93933. sum += qlp_coeff[ 1] * (FLAC__int64)data[i- 2];
  93934. sum += qlp_coeff[ 0] * (FLAC__int64)data[i- 1];
  93935. }
  93936. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  93937. }
  93938. }
  93939. }
  93940. #endif
  93941. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  93942. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample(FLAC__double lpc_error, unsigned total_samples)
  93943. {
  93944. FLAC__double error_scale;
  93945. FLAC__ASSERT(total_samples > 0);
  93946. error_scale = 0.5 * M_LN2 * M_LN2 / (FLAC__double)total_samples;
  93947. return FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(lpc_error, error_scale);
  93948. }
  93949. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(FLAC__double lpc_error, FLAC__double error_scale)
  93950. {
  93951. if(lpc_error > 0.0) {
  93952. FLAC__double bps = (FLAC__double)0.5 * log(error_scale * lpc_error) / M_LN2;
  93953. if(bps >= 0.0)
  93954. return bps;
  93955. else
  93956. return 0.0;
  93957. }
  93958. else if(lpc_error < 0.0) { /* error should not be negative but can happen due to inadequate floating-point resolution */
  93959. return 1e32;
  93960. }
  93961. else {
  93962. return 0.0;
  93963. }
  93964. }
  93965. unsigned FLAC__lpc_compute_best_order(const FLAC__double lpc_error[], unsigned max_order, unsigned total_samples, unsigned overhead_bits_per_order)
  93966. {
  93967. unsigned order, index, best_index; /* 'index' the index into lpc_error; index==order-1 since lpc_error[0] is for order==1, lpc_error[1] is for order==2, etc */
  93968. FLAC__double bits, best_bits, error_scale;
  93969. FLAC__ASSERT(max_order > 0);
  93970. FLAC__ASSERT(total_samples > 0);
  93971. error_scale = 0.5 * M_LN2 * M_LN2 / (FLAC__double)total_samples;
  93972. best_index = 0;
  93973. best_bits = (unsigned)(-1);
  93974. for(index = 0, order = 1; index < max_order; index++, order++) {
  93975. bits = FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(lpc_error[index], error_scale) * (FLAC__double)(total_samples - order) + (FLAC__double)(order * overhead_bits_per_order);
  93976. if(bits < best_bits) {
  93977. best_index = index;
  93978. best_bits = bits;
  93979. }
  93980. }
  93981. return best_index+1; /* +1 since index of lpc_error[] is order-1 */
  93982. }
  93983. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  93984. #endif
  93985. /********* End of inlined file: lpc_flac.c *********/
  93986. /********* Start of inlined file: md5.c *********/
  93987. /********* Start of inlined file: juce_FlacHeader.h *********/
  93988. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  93989. // tasks..
  93990. #define VERSION "1.2.1"
  93991. #define FLAC__NO_DLL 1
  93992. #ifdef _MSC_VER
  93993. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  93994. #endif
  93995. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  93996. #define FLAC__SYS_DARWIN 1
  93997. #endif
  93998. /********* End of inlined file: juce_FlacHeader.h *********/
  93999. #if JUCE_USE_FLAC
  94000. #if HAVE_CONFIG_H
  94001. # include <config.h>
  94002. #endif
  94003. #include <stdlib.h> /* for malloc() */
  94004. #include <string.h> /* for memcpy() */
  94005. /********* Start of inlined file: md5.h *********/
  94006. #ifndef FLAC__PRIVATE__MD5_H
  94007. #define FLAC__PRIVATE__MD5_H
  94008. /*
  94009. * This is the header file for the MD5 message-digest algorithm.
  94010. * The algorithm is due to Ron Rivest. This code was
  94011. * written by Colin Plumb in 1993, no copyright is claimed.
  94012. * This code is in the public domain; do with it what you wish.
  94013. *
  94014. * Equivalent code is available from RSA Data Security, Inc.
  94015. * This code has been tested against that, and is equivalent,
  94016. * except that you don't need to include two pages of legalese
  94017. * with every copy.
  94018. *
  94019. * To compute the message digest of a chunk of bytes, declare an
  94020. * MD5Context structure, pass it to MD5Init, call MD5Update as
  94021. * needed on buffers full of bytes, and then call MD5Final, which
  94022. * will fill a supplied 16-byte array with the digest.
  94023. *
  94024. * Changed so as no longer to depend on Colin Plumb's `usual.h'
  94025. * header definitions; now uses stuff from dpkg's config.h
  94026. * - Ian Jackson <ijackson@nyx.cs.du.edu>.
  94027. * Still in the public domain.
  94028. *
  94029. * Josh Coalson: made some changes to integrate with libFLAC.
  94030. * Still in the public domain, with no warranty.
  94031. */
  94032. typedef struct {
  94033. FLAC__uint32 in[16];
  94034. FLAC__uint32 buf[4];
  94035. FLAC__uint32 bytes[2];
  94036. FLAC__byte *internal_buf;
  94037. size_t capacity;
  94038. } FLAC__MD5Context;
  94039. void FLAC__MD5Init(FLAC__MD5Context *context);
  94040. void FLAC__MD5Final(FLAC__byte digest[16], FLAC__MD5Context *context);
  94041. FLAC__bool FLAC__MD5Accumulate(FLAC__MD5Context *ctx, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample);
  94042. #endif
  94043. /********* End of inlined file: md5.h *********/
  94044. #ifndef FLaC__INLINE
  94045. #define FLaC__INLINE
  94046. #endif
  94047. /*
  94048. * This code implements the MD5 message-digest algorithm.
  94049. * The algorithm is due to Ron Rivest. This code was
  94050. * written by Colin Plumb in 1993, no copyright is claimed.
  94051. * This code is in the public domain; do with it what you wish.
  94052. *
  94053. * Equivalent code is available from RSA Data Security, Inc.
  94054. * This code has been tested against that, and is equivalent,
  94055. * except that you don't need to include two pages of legalese
  94056. * with every copy.
  94057. *
  94058. * To compute the message digest of a chunk of bytes, declare an
  94059. * MD5Context structure, pass it to MD5Init, call MD5Update as
  94060. * needed on buffers full of bytes, and then call MD5Final, which
  94061. * will fill a supplied 16-byte array with the digest.
  94062. *
  94063. * Changed so as no longer to depend on Colin Plumb's `usual.h' header
  94064. * definitions; now uses stuff from dpkg's config.h.
  94065. * - Ian Jackson <ijackson@nyx.cs.du.edu>.
  94066. * Still in the public domain.
  94067. *
  94068. * Josh Coalson: made some changes to integrate with libFLAC.
  94069. * Still in the public domain.
  94070. */
  94071. /* The four core functions - F1 is optimized somewhat */
  94072. /* #define F1(x, y, z) (x & y | ~x & z) */
  94073. #define F1(x, y, z) (z ^ (x & (y ^ z)))
  94074. #define F2(x, y, z) F1(z, x, y)
  94075. #define F3(x, y, z) (x ^ y ^ z)
  94076. #define F4(x, y, z) (y ^ (x | ~z))
  94077. /* This is the central step in the MD5 algorithm. */
  94078. #define MD5STEP(f,w,x,y,z,in,s) \
  94079. (w += f(x,y,z) + in, w = (w<<s | w>>(32-s)) + x)
  94080. /*
  94081. * The core of the MD5 algorithm, this alters an existing MD5 hash to
  94082. * reflect the addition of 16 longwords of new data. MD5Update blocks
  94083. * the data and converts bytes into longwords for this routine.
  94084. */
  94085. static void FLAC__MD5Transform(FLAC__uint32 buf[4], FLAC__uint32 const in[16])
  94086. {
  94087. register FLAC__uint32 a, b, c, d;
  94088. a = buf[0];
  94089. b = buf[1];
  94090. c = buf[2];
  94091. d = buf[3];
  94092. MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7);
  94093. MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12);
  94094. MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17);
  94095. MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22);
  94096. MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7);
  94097. MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12);
  94098. MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17);
  94099. MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22);
  94100. MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7);
  94101. MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12);
  94102. MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17);
  94103. MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22);
  94104. MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7);
  94105. MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12);
  94106. MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17);
  94107. MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22);
  94108. MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5);
  94109. MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9);
  94110. MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14);
  94111. MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20);
  94112. MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5);
  94113. MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9);
  94114. MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14);
  94115. MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20);
  94116. MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5);
  94117. MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9);
  94118. MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14);
  94119. MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20);
  94120. MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5);
  94121. MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9);
  94122. MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14);
  94123. MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20);
  94124. MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4);
  94125. MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11);
  94126. MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16);
  94127. MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23);
  94128. MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4);
  94129. MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11);
  94130. MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16);
  94131. MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23);
  94132. MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4);
  94133. MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11);
  94134. MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16);
  94135. MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23);
  94136. MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4);
  94137. MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11);
  94138. MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16);
  94139. MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23);
  94140. MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6);
  94141. MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10);
  94142. MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15);
  94143. MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21);
  94144. MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6);
  94145. MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10);
  94146. MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15);
  94147. MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21);
  94148. MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6);
  94149. MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10);
  94150. MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15);
  94151. MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21);
  94152. MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6);
  94153. MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10);
  94154. MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15);
  94155. MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21);
  94156. buf[0] += a;
  94157. buf[1] += b;
  94158. buf[2] += c;
  94159. buf[3] += d;
  94160. }
  94161. #if WORDS_BIGENDIAN
  94162. //@@@@@@ OPT: use bswap/intrinsics
  94163. static void byteSwap(FLAC__uint32 *buf, unsigned words)
  94164. {
  94165. register FLAC__uint32 x;
  94166. do {
  94167. x = *buf;
  94168. x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff);
  94169. *buf++ = (x >> 16) | (x << 16);
  94170. } while (--words);
  94171. }
  94172. static void byteSwapX16(FLAC__uint32 *buf)
  94173. {
  94174. register FLAC__uint32 x;
  94175. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  94176. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  94177. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  94178. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  94179. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  94180. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  94181. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  94182. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  94183. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  94184. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  94185. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  94186. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  94187. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  94188. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  94189. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  94190. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf = (x >> 16) | (x << 16);
  94191. }
  94192. #else
  94193. #define byteSwap(buf, words)
  94194. #define byteSwapX16(buf)
  94195. #endif
  94196. /*
  94197. * Update context to reflect the concatenation of another buffer full
  94198. * of bytes.
  94199. */
  94200. static void FLAC__MD5Update(FLAC__MD5Context *ctx, FLAC__byte const *buf, unsigned len)
  94201. {
  94202. FLAC__uint32 t;
  94203. /* Update byte count */
  94204. t = ctx->bytes[0];
  94205. if ((ctx->bytes[0] = t + len) < t)
  94206. ctx->bytes[1]++; /* Carry from low to high */
  94207. t = 64 - (t & 0x3f); /* Space available in ctx->in (at least 1) */
  94208. if (t > len) {
  94209. memcpy((FLAC__byte *)ctx->in + 64 - t, buf, len);
  94210. return;
  94211. }
  94212. /* First chunk is an odd size */
  94213. memcpy((FLAC__byte *)ctx->in + 64 - t, buf, t);
  94214. byteSwapX16(ctx->in);
  94215. FLAC__MD5Transform(ctx->buf, ctx->in);
  94216. buf += t;
  94217. len -= t;
  94218. /* Process data in 64-byte chunks */
  94219. while (len >= 64) {
  94220. memcpy(ctx->in, buf, 64);
  94221. byteSwapX16(ctx->in);
  94222. FLAC__MD5Transform(ctx->buf, ctx->in);
  94223. buf += 64;
  94224. len -= 64;
  94225. }
  94226. /* Handle any remaining bytes of data. */
  94227. memcpy(ctx->in, buf, len);
  94228. }
  94229. /*
  94230. * Start MD5 accumulation. Set bit count to 0 and buffer to mysterious
  94231. * initialization constants.
  94232. */
  94233. void FLAC__MD5Init(FLAC__MD5Context *ctx)
  94234. {
  94235. ctx->buf[0] = 0x67452301;
  94236. ctx->buf[1] = 0xefcdab89;
  94237. ctx->buf[2] = 0x98badcfe;
  94238. ctx->buf[3] = 0x10325476;
  94239. ctx->bytes[0] = 0;
  94240. ctx->bytes[1] = 0;
  94241. ctx->internal_buf = 0;
  94242. ctx->capacity = 0;
  94243. }
  94244. /*
  94245. * Final wrapup - pad to 64-byte boundary with the bit pattern
  94246. * 1 0* (64-bit count of bits processed, MSB-first)
  94247. */
  94248. void FLAC__MD5Final(FLAC__byte digest[16], FLAC__MD5Context *ctx)
  94249. {
  94250. int count = ctx->bytes[0] & 0x3f; /* Number of bytes in ctx->in */
  94251. FLAC__byte *p = (FLAC__byte *)ctx->in + count;
  94252. /* Set the first char of padding to 0x80. There is always room. */
  94253. *p++ = 0x80;
  94254. /* Bytes of padding needed to make 56 bytes (-8..55) */
  94255. count = 56 - 1 - count;
  94256. if (count < 0) { /* Padding forces an extra block */
  94257. memset(p, 0, count + 8);
  94258. byteSwapX16(ctx->in);
  94259. FLAC__MD5Transform(ctx->buf, ctx->in);
  94260. p = (FLAC__byte *)ctx->in;
  94261. count = 56;
  94262. }
  94263. memset(p, 0, count);
  94264. byteSwap(ctx->in, 14);
  94265. /* Append length in bits and transform */
  94266. ctx->in[14] = ctx->bytes[0] << 3;
  94267. ctx->in[15] = ctx->bytes[1] << 3 | ctx->bytes[0] >> 29;
  94268. FLAC__MD5Transform(ctx->buf, ctx->in);
  94269. byteSwap(ctx->buf, 4);
  94270. memcpy(digest, ctx->buf, 16);
  94271. memset(ctx, 0, sizeof(ctx)); /* In case it's sensitive */
  94272. if(0 != ctx->internal_buf) {
  94273. free(ctx->internal_buf);
  94274. ctx->internal_buf = 0;
  94275. ctx->capacity = 0;
  94276. }
  94277. }
  94278. /*
  94279. * Convert the incoming audio signal to a byte stream
  94280. */
  94281. static void format_input_(FLAC__byte *buf, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample)
  94282. {
  94283. unsigned channel, sample;
  94284. register FLAC__int32 a_word;
  94285. register FLAC__byte *buf_ = buf;
  94286. #if WORDS_BIGENDIAN
  94287. #else
  94288. if(channels == 2 && bytes_per_sample == 2) {
  94289. FLAC__int16 *buf1_ = ((FLAC__int16*)buf_) + 1;
  94290. memcpy(buf_, signal[0], sizeof(FLAC__int32) * samples);
  94291. for(sample = 0; sample < samples; sample++, buf1_+=2)
  94292. *buf1_ = (FLAC__int16)signal[1][sample];
  94293. }
  94294. else if(channels == 1 && bytes_per_sample == 2) {
  94295. FLAC__int16 *buf1_ = (FLAC__int16*)buf_;
  94296. for(sample = 0; sample < samples; sample++)
  94297. *buf1_++ = (FLAC__int16)signal[0][sample];
  94298. }
  94299. else
  94300. #endif
  94301. if(bytes_per_sample == 2) {
  94302. if(channels == 2) {
  94303. for(sample = 0; sample < samples; sample++) {
  94304. a_word = signal[0][sample];
  94305. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  94306. *buf_++ = (FLAC__byte)a_word;
  94307. a_word = signal[1][sample];
  94308. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  94309. *buf_++ = (FLAC__byte)a_word;
  94310. }
  94311. }
  94312. else if(channels == 1) {
  94313. for(sample = 0; sample < samples; sample++) {
  94314. a_word = signal[0][sample];
  94315. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  94316. *buf_++ = (FLAC__byte)a_word;
  94317. }
  94318. }
  94319. else {
  94320. for(sample = 0; sample < samples; sample++) {
  94321. for(channel = 0; channel < channels; channel++) {
  94322. a_word = signal[channel][sample];
  94323. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  94324. *buf_++ = (FLAC__byte)a_word;
  94325. }
  94326. }
  94327. }
  94328. }
  94329. else if(bytes_per_sample == 3) {
  94330. if(channels == 2) {
  94331. for(sample = 0; sample < samples; sample++) {
  94332. a_word = signal[0][sample];
  94333. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  94334. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  94335. *buf_++ = (FLAC__byte)a_word;
  94336. a_word = signal[1][sample];
  94337. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  94338. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  94339. *buf_++ = (FLAC__byte)a_word;
  94340. }
  94341. }
  94342. else if(channels == 1) {
  94343. for(sample = 0; sample < samples; sample++) {
  94344. a_word = signal[0][sample];
  94345. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  94346. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  94347. *buf_++ = (FLAC__byte)a_word;
  94348. }
  94349. }
  94350. else {
  94351. for(sample = 0; sample < samples; sample++) {
  94352. for(channel = 0; channel < channels; channel++) {
  94353. a_word = signal[channel][sample];
  94354. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  94355. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  94356. *buf_++ = (FLAC__byte)a_word;
  94357. }
  94358. }
  94359. }
  94360. }
  94361. else if(bytes_per_sample == 1) {
  94362. if(channels == 2) {
  94363. for(sample = 0; sample < samples; sample++) {
  94364. a_word = signal[0][sample];
  94365. *buf_++ = (FLAC__byte)a_word;
  94366. a_word = signal[1][sample];
  94367. *buf_++ = (FLAC__byte)a_word;
  94368. }
  94369. }
  94370. else if(channels == 1) {
  94371. for(sample = 0; sample < samples; sample++) {
  94372. a_word = signal[0][sample];
  94373. *buf_++ = (FLAC__byte)a_word;
  94374. }
  94375. }
  94376. else {
  94377. for(sample = 0; sample < samples; sample++) {
  94378. for(channel = 0; channel < channels; channel++) {
  94379. a_word = signal[channel][sample];
  94380. *buf_++ = (FLAC__byte)a_word;
  94381. }
  94382. }
  94383. }
  94384. }
  94385. else { /* bytes_per_sample == 4, maybe optimize more later */
  94386. for(sample = 0; sample < samples; sample++) {
  94387. for(channel = 0; channel < channels; channel++) {
  94388. a_word = signal[channel][sample];
  94389. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  94390. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  94391. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  94392. *buf_++ = (FLAC__byte)a_word;
  94393. }
  94394. }
  94395. }
  94396. }
  94397. /*
  94398. * Convert the incoming audio signal to a byte stream and FLAC__MD5Update it.
  94399. */
  94400. FLAC__bool FLAC__MD5Accumulate(FLAC__MD5Context *ctx, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample)
  94401. {
  94402. const size_t bytes_needed = (size_t)channels * (size_t)samples * (size_t)bytes_per_sample;
  94403. /* overflow check */
  94404. if((size_t)channels > SIZE_MAX / (size_t)bytes_per_sample)
  94405. return false;
  94406. if((size_t)channels * (size_t)bytes_per_sample > SIZE_MAX / (size_t)samples)
  94407. return false;
  94408. if(ctx->capacity < bytes_needed) {
  94409. FLAC__byte *tmp = (FLAC__byte*)realloc(ctx->internal_buf, bytes_needed);
  94410. if(0 == tmp) {
  94411. free(ctx->internal_buf);
  94412. if(0 == (ctx->internal_buf = (FLAC__byte*)safe_malloc_(bytes_needed)))
  94413. return false;
  94414. }
  94415. ctx->internal_buf = tmp;
  94416. ctx->capacity = bytes_needed;
  94417. }
  94418. format_input_(ctx->internal_buf, signal, channels, samples, bytes_per_sample);
  94419. FLAC__MD5Update(ctx, ctx->internal_buf, bytes_needed);
  94420. return true;
  94421. }
  94422. #endif
  94423. /********* End of inlined file: md5.c *********/
  94424. /********* Start of inlined file: memory.c *********/
  94425. /********* Start of inlined file: juce_FlacHeader.h *********/
  94426. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  94427. // tasks..
  94428. #define VERSION "1.2.1"
  94429. #define FLAC__NO_DLL 1
  94430. #ifdef _MSC_VER
  94431. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  94432. #endif
  94433. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  94434. #define FLAC__SYS_DARWIN 1
  94435. #endif
  94436. /********* End of inlined file: juce_FlacHeader.h *********/
  94437. #if JUCE_USE_FLAC
  94438. #if HAVE_CONFIG_H
  94439. # include <config.h>
  94440. #endif
  94441. /********* Start of inlined file: memory.h *********/
  94442. #ifndef FLAC__PRIVATE__MEMORY_H
  94443. #define FLAC__PRIVATE__MEMORY_H
  94444. #ifdef HAVE_CONFIG_H
  94445. #include <config.h>
  94446. #endif
  94447. #include <stdlib.h> /* for size_t */
  94448. /* Returns the unaligned address returned by malloc.
  94449. * Use free() on this address to deallocate.
  94450. */
  94451. void *FLAC__memory_alloc_aligned(size_t bytes, void **aligned_address);
  94452. FLAC__bool FLAC__memory_alloc_aligned_int32_array(unsigned elements, FLAC__int32 **unaligned_pointer, FLAC__int32 **aligned_pointer);
  94453. FLAC__bool FLAC__memory_alloc_aligned_uint32_array(unsigned elements, FLAC__uint32 **unaligned_pointer, FLAC__uint32 **aligned_pointer);
  94454. FLAC__bool FLAC__memory_alloc_aligned_uint64_array(unsigned elements, FLAC__uint64 **unaligned_pointer, FLAC__uint64 **aligned_pointer);
  94455. FLAC__bool FLAC__memory_alloc_aligned_unsigned_array(unsigned elements, unsigned **unaligned_pointer, unsigned **aligned_pointer);
  94456. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  94457. FLAC__bool FLAC__memory_alloc_aligned_real_array(unsigned elements, FLAC__real **unaligned_pointer, FLAC__real **aligned_pointer);
  94458. #endif
  94459. #endif
  94460. /********* End of inlined file: memory.h *********/
  94461. void *FLAC__memory_alloc_aligned(size_t bytes, void **aligned_address)
  94462. {
  94463. void *x;
  94464. FLAC__ASSERT(0 != aligned_address);
  94465. #ifdef FLAC__ALIGN_MALLOC_DATA
  94466. /* align on 32-byte (256-bit) boundary */
  94467. x = safe_malloc_add_2op_(bytes, /*+*/31);
  94468. #ifdef SIZEOF_VOIDP
  94469. #if SIZEOF_VOIDP == 4
  94470. /* could do *aligned_address = x + ((unsigned) (32 - (((unsigned)x) & 31))) & 31; */
  94471. *aligned_address = (void*)(((unsigned)x + 31) & -32);
  94472. #elif SIZEOF_VOIDP == 8
  94473. *aligned_address = (void*)(((FLAC__uint64)x + 31) & (FLAC__uint64)(-((FLAC__int64)32)));
  94474. #else
  94475. # error Unsupported sizeof(void*)
  94476. #endif
  94477. #else
  94478. /* there's got to be a better way to do this right for all archs */
  94479. if(sizeof(void*) == sizeof(unsigned))
  94480. *aligned_address = (void*)(((unsigned)x + 31) & -32);
  94481. else if(sizeof(void*) == sizeof(FLAC__uint64))
  94482. *aligned_address = (void*)(((FLAC__uint64)x + 31) & (FLAC__uint64)(-((FLAC__int64)32)));
  94483. else
  94484. return 0;
  94485. #endif
  94486. #else
  94487. x = safe_malloc_(bytes);
  94488. *aligned_address = x;
  94489. #endif
  94490. return x;
  94491. }
  94492. FLAC__bool FLAC__memory_alloc_aligned_int32_array(unsigned elements, FLAC__int32 **unaligned_pointer, FLAC__int32 **aligned_pointer)
  94493. {
  94494. FLAC__int32 *pu; /* unaligned pointer */
  94495. union { /* union needed to comply with C99 pointer aliasing rules */
  94496. FLAC__int32 *pa; /* aligned pointer */
  94497. void *pv; /* aligned pointer alias */
  94498. } u;
  94499. FLAC__ASSERT(elements > 0);
  94500. FLAC__ASSERT(0 != unaligned_pointer);
  94501. FLAC__ASSERT(0 != aligned_pointer);
  94502. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  94503. if((size_t)elements > SIZE_MAX / sizeof(*pu)) /* overflow check */
  94504. return false;
  94505. pu = (FLAC__int32*)FLAC__memory_alloc_aligned(sizeof(*pu) * (size_t)elements, &u.pv);
  94506. if(0 == pu) {
  94507. return false;
  94508. }
  94509. else {
  94510. if(*unaligned_pointer != 0)
  94511. free(*unaligned_pointer);
  94512. *unaligned_pointer = pu;
  94513. *aligned_pointer = u.pa;
  94514. return true;
  94515. }
  94516. }
  94517. FLAC__bool FLAC__memory_alloc_aligned_uint32_array(unsigned elements, FLAC__uint32 **unaligned_pointer, FLAC__uint32 **aligned_pointer)
  94518. {
  94519. FLAC__uint32 *pu; /* unaligned pointer */
  94520. union { /* union needed to comply with C99 pointer aliasing rules */
  94521. FLAC__uint32 *pa; /* aligned pointer */
  94522. void *pv; /* aligned pointer alias */
  94523. } u;
  94524. FLAC__ASSERT(elements > 0);
  94525. FLAC__ASSERT(0 != unaligned_pointer);
  94526. FLAC__ASSERT(0 != aligned_pointer);
  94527. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  94528. if((size_t)elements > SIZE_MAX / sizeof(*pu)) /* overflow check */
  94529. return false;
  94530. pu = (FLAC__uint32*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  94531. if(0 == pu) {
  94532. return false;
  94533. }
  94534. else {
  94535. if(*unaligned_pointer != 0)
  94536. free(*unaligned_pointer);
  94537. *unaligned_pointer = pu;
  94538. *aligned_pointer = u.pa;
  94539. return true;
  94540. }
  94541. }
  94542. FLAC__bool FLAC__memory_alloc_aligned_uint64_array(unsigned elements, FLAC__uint64 **unaligned_pointer, FLAC__uint64 **aligned_pointer)
  94543. {
  94544. FLAC__uint64 *pu; /* unaligned pointer */
  94545. union { /* union needed to comply with C99 pointer aliasing rules */
  94546. FLAC__uint64 *pa; /* aligned pointer */
  94547. void *pv; /* aligned pointer alias */
  94548. } u;
  94549. FLAC__ASSERT(elements > 0);
  94550. FLAC__ASSERT(0 != unaligned_pointer);
  94551. FLAC__ASSERT(0 != aligned_pointer);
  94552. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  94553. if((size_t)elements > SIZE_MAX / sizeof(*pu)) /* overflow check */
  94554. return false;
  94555. pu = (FLAC__uint64*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  94556. if(0 == pu) {
  94557. return false;
  94558. }
  94559. else {
  94560. if(*unaligned_pointer != 0)
  94561. free(*unaligned_pointer);
  94562. *unaligned_pointer = pu;
  94563. *aligned_pointer = u.pa;
  94564. return true;
  94565. }
  94566. }
  94567. FLAC__bool FLAC__memory_alloc_aligned_unsigned_array(unsigned elements, unsigned **unaligned_pointer, unsigned **aligned_pointer)
  94568. {
  94569. unsigned *pu; /* unaligned pointer */
  94570. union { /* union needed to comply with C99 pointer aliasing rules */
  94571. unsigned *pa; /* aligned pointer */
  94572. void *pv; /* aligned pointer alias */
  94573. } u;
  94574. FLAC__ASSERT(elements > 0);
  94575. FLAC__ASSERT(0 != unaligned_pointer);
  94576. FLAC__ASSERT(0 != aligned_pointer);
  94577. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  94578. if((size_t)elements > SIZE_MAX / sizeof(*pu)) /* overflow check */
  94579. return false;
  94580. pu = (unsigned*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  94581. if(0 == pu) {
  94582. return false;
  94583. }
  94584. else {
  94585. if(*unaligned_pointer != 0)
  94586. free(*unaligned_pointer);
  94587. *unaligned_pointer = pu;
  94588. *aligned_pointer = u.pa;
  94589. return true;
  94590. }
  94591. }
  94592. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  94593. FLAC__bool FLAC__memory_alloc_aligned_real_array(unsigned elements, FLAC__real **unaligned_pointer, FLAC__real **aligned_pointer)
  94594. {
  94595. FLAC__real *pu; /* unaligned pointer */
  94596. union { /* union needed to comply with C99 pointer aliasing rules */
  94597. FLAC__real *pa; /* aligned pointer */
  94598. void *pv; /* aligned pointer alias */
  94599. } u;
  94600. FLAC__ASSERT(elements > 0);
  94601. FLAC__ASSERT(0 != unaligned_pointer);
  94602. FLAC__ASSERT(0 != aligned_pointer);
  94603. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  94604. if((size_t)elements > SIZE_MAX / sizeof(*pu)) /* overflow check */
  94605. return false;
  94606. pu = (FLAC__real*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  94607. if(0 == pu) {
  94608. return false;
  94609. }
  94610. else {
  94611. if(*unaligned_pointer != 0)
  94612. free(*unaligned_pointer);
  94613. *unaligned_pointer = pu;
  94614. *aligned_pointer = u.pa;
  94615. return true;
  94616. }
  94617. }
  94618. #endif
  94619. #endif
  94620. /********* End of inlined file: memory.c *********/
  94621. /********* Start of inlined file: stream_decoder.c *********/
  94622. /********* Start of inlined file: juce_FlacHeader.h *********/
  94623. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  94624. // tasks..
  94625. #define VERSION "1.2.1"
  94626. #define FLAC__NO_DLL 1
  94627. #ifdef _MSC_VER
  94628. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  94629. #endif
  94630. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  94631. #define FLAC__SYS_DARWIN 1
  94632. #endif
  94633. /********* End of inlined file: juce_FlacHeader.h *********/
  94634. #if JUCE_USE_FLAC
  94635. #if HAVE_CONFIG_H
  94636. # include <config.h>
  94637. #endif
  94638. #if defined _MSC_VER || defined __MINGW32__
  94639. #include <io.h> /* for _setmode() */
  94640. #include <fcntl.h> /* for _O_BINARY */
  94641. #endif
  94642. #if defined __CYGWIN__ || defined __EMX__
  94643. #include <io.h> /* for setmode(), O_BINARY */
  94644. #include <fcntl.h> /* for _O_BINARY */
  94645. #endif
  94646. #include <stdio.h>
  94647. #include <stdlib.h> /* for malloc() */
  94648. #include <string.h> /* for memset/memcpy() */
  94649. #include <sys/stat.h> /* for stat() */
  94650. #include <sys/types.h> /* for off_t */
  94651. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINGW32__
  94652. #if _MSC_VER <= 1600 || defined __BORLANDC__ /* @@@ [2G limit] */
  94653. #define fseeko fseek
  94654. #define ftello ftell
  94655. #endif
  94656. #endif
  94657. /********* Start of inlined file: stream_decoder.h *********/
  94658. #ifndef FLAC__PROTECTED__STREAM_DECODER_H
  94659. #define FLAC__PROTECTED__STREAM_DECODER_H
  94660. #if FLAC__HAS_OGG
  94661. #include "include/private/ogg_decoder_aspect.h"
  94662. #endif
  94663. typedef struct FLAC__StreamDecoderProtected {
  94664. FLAC__StreamDecoderState state;
  94665. unsigned channels;
  94666. FLAC__ChannelAssignment channel_assignment;
  94667. unsigned bits_per_sample;
  94668. unsigned sample_rate; /* in Hz */
  94669. unsigned blocksize; /* in samples (per channel) */
  94670. FLAC__bool md5_checking; /* if true, generate MD5 signature of decoded data and compare against signature in the STREAMINFO metadata block */
  94671. #if FLAC__HAS_OGG
  94672. FLAC__OggDecoderAspect ogg_decoder_aspect;
  94673. #endif
  94674. } FLAC__StreamDecoderProtected;
  94675. /*
  94676. * return the number of input bytes consumed
  94677. */
  94678. unsigned FLAC__stream_decoder_get_input_bytes_unconsumed(const FLAC__StreamDecoder *decoder);
  94679. #endif
  94680. /********* End of inlined file: stream_decoder.h *********/
  94681. #ifdef max
  94682. #undef max
  94683. #endif
  94684. #define max(a,b) ((a)>(b)?(a):(b))
  94685. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  94686. #ifdef _MSC_VER
  94687. #define FLAC__U64L(x) x
  94688. #else
  94689. #define FLAC__U64L(x) x##LLU
  94690. #endif
  94691. /* technically this should be in an "export.c" but this is convenient enough */
  94692. FLAC_API int FLAC_API_SUPPORTS_OGG_FLAC =
  94693. #if FLAC__HAS_OGG
  94694. 1
  94695. #else
  94696. 0
  94697. #endif
  94698. ;
  94699. /***********************************************************************
  94700. *
  94701. * Private static data
  94702. *
  94703. ***********************************************************************/
  94704. static FLAC__byte ID3V2_TAG_[3] = { 'I', 'D', '3' };
  94705. /***********************************************************************
  94706. *
  94707. * Private class method prototypes
  94708. *
  94709. ***********************************************************************/
  94710. static void set_defaults_dec(FLAC__StreamDecoder *decoder);
  94711. static FILE *get_binary_stdin_(void);
  94712. static FLAC__bool allocate_output_(FLAC__StreamDecoder *decoder, unsigned size, unsigned channels);
  94713. static FLAC__bool has_id_filtered_(FLAC__StreamDecoder *decoder, FLAC__byte *id);
  94714. static FLAC__bool find_metadata_(FLAC__StreamDecoder *decoder);
  94715. static FLAC__bool read_metadata_(FLAC__StreamDecoder *decoder);
  94716. static FLAC__bool read_metadata_streaminfo_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length);
  94717. static FLAC__bool read_metadata_seektable_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length);
  94718. static FLAC__bool read_metadata_vorbiscomment_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_VorbisComment *obj);
  94719. static FLAC__bool read_metadata_cuesheet_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_CueSheet *obj);
  94720. static FLAC__bool read_metadata_picture_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_Picture *obj);
  94721. static FLAC__bool skip_id3v2_tag_(FLAC__StreamDecoder *decoder);
  94722. static FLAC__bool frame_sync_(FLAC__StreamDecoder *decoder);
  94723. static FLAC__bool read_frame_(FLAC__StreamDecoder *decoder, FLAC__bool *got_a_frame, FLAC__bool do_full_decode);
  94724. static FLAC__bool read_frame_header_(FLAC__StreamDecoder *decoder);
  94725. static FLAC__bool read_subframe_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  94726. static FLAC__bool read_subframe_constant_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  94727. static FLAC__bool read_subframe_fixed_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode);
  94728. static FLAC__bool read_subframe_lpc_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode);
  94729. static FLAC__bool read_subframe_verbatim_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  94730. static FLAC__bool read_residual_partitioned_rice_(FLAC__StreamDecoder *decoder, unsigned predictor_order, unsigned partition_order, FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents, FLAC__int32 *residual, FLAC__bool is_extended);
  94731. static FLAC__bool read_zero_padding_(FLAC__StreamDecoder *decoder);
  94732. static FLAC__bool read_callback_(FLAC__byte buffer[], size_t *bytes, void *client_data);
  94733. #if FLAC__HAS_OGG
  94734. static FLAC__StreamDecoderReadStatus read_callback_ogg_aspect_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes);
  94735. static FLAC__OggDecoderAspectReadStatus read_callback_proxy_(const void *void_decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  94736. #endif
  94737. static FLAC__StreamDecoderWriteStatus write_audio_frame_to_client_(FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[]);
  94738. static void send_error_to_client_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status);
  94739. static FLAC__bool seek_to_absolute_sample_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample);
  94740. #if FLAC__HAS_OGG
  94741. static FLAC__bool seek_to_absolute_sample_ogg_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample);
  94742. #endif
  94743. static FLAC__StreamDecoderReadStatus file_read_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  94744. static FLAC__StreamDecoderSeekStatus file_seek_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  94745. static FLAC__StreamDecoderTellStatus file_tell_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  94746. static FLAC__StreamDecoderLengthStatus file_length_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data);
  94747. static FLAC__bool file_eof_callback_(const FLAC__StreamDecoder *decoder, void *client_data);
  94748. /***********************************************************************
  94749. *
  94750. * Private class data
  94751. *
  94752. ***********************************************************************/
  94753. typedef struct FLAC__StreamDecoderPrivate {
  94754. #if FLAC__HAS_OGG
  94755. FLAC__bool is_ogg;
  94756. #endif
  94757. FLAC__StreamDecoderReadCallback read_callback;
  94758. FLAC__StreamDecoderSeekCallback seek_callback;
  94759. FLAC__StreamDecoderTellCallback tell_callback;
  94760. FLAC__StreamDecoderLengthCallback length_callback;
  94761. FLAC__StreamDecoderEofCallback eof_callback;
  94762. FLAC__StreamDecoderWriteCallback write_callback;
  94763. FLAC__StreamDecoderMetadataCallback metadata_callback;
  94764. FLAC__StreamDecoderErrorCallback error_callback;
  94765. /* generic 32-bit datapath: */
  94766. void (*local_lpc_restore_signal)(const FLAC__int32 residual[], unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 data[]);
  94767. /* generic 64-bit datapath: */
  94768. void (*local_lpc_restore_signal_64bit)(const FLAC__int32 residual[], unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 data[]);
  94769. /* for use when the signal is <= 16 bits-per-sample, or <= 15 bits-per-sample on a side channel (which requires 1 extra bit): */
  94770. void (*local_lpc_restore_signal_16bit)(const FLAC__int32 residual[], unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 data[]);
  94771. /* for use when the signal is <= 16 bits-per-sample, or <= 15 bits-per-sample on a side channel (which requires 1 extra bit), AND order <= 8: */
  94772. void (*local_lpc_restore_signal_16bit_order8)(const FLAC__int32 residual[], unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 data[]);
  94773. FLAC__bool (*local_bitreader_read_rice_signed_block)(FLAC__BitReader *br, int* vals, unsigned nvals, unsigned parameter);
  94774. void *client_data;
  94775. FILE *file; /* only used if FLAC__stream_decoder_init_file()/FLAC__stream_decoder_init_file() called, else NULL */
  94776. FLAC__BitReader *input;
  94777. FLAC__int32 *output[FLAC__MAX_CHANNELS];
  94778. FLAC__int32 *residual[FLAC__MAX_CHANNELS]; /* WATCHOUT: these are the aligned pointers; the real pointers that should be free()'d are residual_unaligned[] below */
  94779. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents[FLAC__MAX_CHANNELS];
  94780. unsigned output_capacity, output_channels;
  94781. FLAC__uint32 fixed_block_size, next_fixed_block_size;
  94782. FLAC__uint64 samples_decoded;
  94783. FLAC__bool has_stream_info, has_seek_table;
  94784. FLAC__StreamMetadata stream_info;
  94785. FLAC__StreamMetadata seek_table;
  94786. FLAC__bool metadata_filter[128]; /* MAGIC number 128 == total number of metadata block types == 1 << 7 */
  94787. FLAC__byte *metadata_filter_ids;
  94788. size_t metadata_filter_ids_count, metadata_filter_ids_capacity; /* units for both are IDs, not bytes */
  94789. FLAC__Frame frame;
  94790. FLAC__bool cached; /* true if there is a byte in lookahead */
  94791. FLAC__CPUInfo cpuinfo;
  94792. FLAC__byte header_warmup[2]; /* contains the sync code and reserved bits */
  94793. FLAC__byte lookahead; /* temp storage when we need to look ahead one byte in the stream */
  94794. /* unaligned (original) pointers to allocated data */
  94795. FLAC__int32 *residual_unaligned[FLAC__MAX_CHANNELS];
  94796. FLAC__bool do_md5_checking; /* initially gets protected_->md5_checking but is turned off after a seek or if the metadata has a zero MD5 */
  94797. FLAC__bool internal_reset_hack; /* used only during init() so we can call reset to set up the decoder without rewinding the input */
  94798. FLAC__bool is_seeking;
  94799. FLAC__MD5Context md5context;
  94800. FLAC__byte computed_md5sum[16]; /* this is the sum we computed from the decoded data */
  94801. /* (the rest of these are only used for seeking) */
  94802. FLAC__Frame last_frame; /* holds the info of the last frame we seeked to */
  94803. FLAC__uint64 first_frame_offset; /* hint to the seek routine of where in the stream the first audio frame starts */
  94804. FLAC__uint64 target_sample;
  94805. unsigned unparseable_frame_count; /* used to tell whether we're decoding a future version of FLAC or just got a bad sync */
  94806. #if FLAC__HAS_OGG
  94807. FLAC__bool got_a_frame; /* hack needed in Ogg FLAC seek routine to check when process_single() actually writes a frame */
  94808. #endif
  94809. } FLAC__StreamDecoderPrivate;
  94810. /***********************************************************************
  94811. *
  94812. * Public static class data
  94813. *
  94814. ***********************************************************************/
  94815. FLAC_API const char * const FLAC__StreamDecoderStateString[] = {
  94816. "FLAC__STREAM_DECODER_SEARCH_FOR_METADATA",
  94817. "FLAC__STREAM_DECODER_READ_METADATA",
  94818. "FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC",
  94819. "FLAC__STREAM_DECODER_READ_FRAME",
  94820. "FLAC__STREAM_DECODER_END_OF_STREAM",
  94821. "FLAC__STREAM_DECODER_OGG_ERROR",
  94822. "FLAC__STREAM_DECODER_SEEK_ERROR",
  94823. "FLAC__STREAM_DECODER_ABORTED",
  94824. "FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR",
  94825. "FLAC__STREAM_DECODER_UNINITIALIZED"
  94826. };
  94827. FLAC_API const char * const FLAC__StreamDecoderInitStatusString[] = {
  94828. "FLAC__STREAM_DECODER_INIT_STATUS_OK",
  94829. "FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER",
  94830. "FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS",
  94831. "FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR",
  94832. "FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE",
  94833. "FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED"
  94834. };
  94835. FLAC_API const char * const FLAC__StreamDecoderReadStatusString[] = {
  94836. "FLAC__STREAM_DECODER_READ_STATUS_CONTINUE",
  94837. "FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM",
  94838. "FLAC__STREAM_DECODER_READ_STATUS_ABORT"
  94839. };
  94840. FLAC_API const char * const FLAC__StreamDecoderSeekStatusString[] = {
  94841. "FLAC__STREAM_DECODER_SEEK_STATUS_OK",
  94842. "FLAC__STREAM_DECODER_SEEK_STATUS_ERROR",
  94843. "FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED"
  94844. };
  94845. FLAC_API const char * const FLAC__StreamDecoderTellStatusString[] = {
  94846. "FLAC__STREAM_DECODER_TELL_STATUS_OK",
  94847. "FLAC__STREAM_DECODER_TELL_STATUS_ERROR",
  94848. "FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED"
  94849. };
  94850. FLAC_API const char * const FLAC__StreamDecoderLengthStatusString[] = {
  94851. "FLAC__STREAM_DECODER_LENGTH_STATUS_OK",
  94852. "FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR",
  94853. "FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED"
  94854. };
  94855. FLAC_API const char * const FLAC__StreamDecoderWriteStatusString[] = {
  94856. "FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE",
  94857. "FLAC__STREAM_DECODER_WRITE_STATUS_ABORT"
  94858. };
  94859. FLAC_API const char * const FLAC__StreamDecoderErrorStatusString[] = {
  94860. "FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC",
  94861. "FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER",
  94862. "FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH",
  94863. "FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM"
  94864. };
  94865. /***********************************************************************
  94866. *
  94867. * Class constructor/destructor
  94868. *
  94869. ***********************************************************************/
  94870. FLAC_API FLAC__StreamDecoder *FLAC__stream_decoder_new(void)
  94871. {
  94872. FLAC__StreamDecoder *decoder;
  94873. unsigned i;
  94874. FLAC__ASSERT(sizeof(int) >= 4); /* we want to die right away if this is not true */
  94875. decoder = (FLAC__StreamDecoder*)calloc(1, sizeof(FLAC__StreamDecoder));
  94876. if(decoder == 0) {
  94877. return 0;
  94878. }
  94879. decoder->protected_ = (FLAC__StreamDecoderProtected*)calloc(1, sizeof(FLAC__StreamDecoderProtected));
  94880. if(decoder->protected_ == 0) {
  94881. free(decoder);
  94882. return 0;
  94883. }
  94884. decoder->private_ = (FLAC__StreamDecoderPrivate*)calloc(1, sizeof(FLAC__StreamDecoderPrivate));
  94885. if(decoder->private_ == 0) {
  94886. free(decoder->protected_);
  94887. free(decoder);
  94888. return 0;
  94889. }
  94890. decoder->private_->input = FLAC__bitreader_new();
  94891. if(decoder->private_->input == 0) {
  94892. free(decoder->private_);
  94893. free(decoder->protected_);
  94894. free(decoder);
  94895. return 0;
  94896. }
  94897. decoder->private_->metadata_filter_ids_capacity = 16;
  94898. if(0 == (decoder->private_->metadata_filter_ids = (FLAC__byte*)malloc((FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8) * decoder->private_->metadata_filter_ids_capacity))) {
  94899. FLAC__bitreader_delete(decoder->private_->input);
  94900. free(decoder->private_);
  94901. free(decoder->protected_);
  94902. free(decoder);
  94903. return 0;
  94904. }
  94905. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  94906. decoder->private_->output[i] = 0;
  94907. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  94908. }
  94909. decoder->private_->output_capacity = 0;
  94910. decoder->private_->output_channels = 0;
  94911. decoder->private_->has_seek_table = false;
  94912. for(i = 0; i < FLAC__MAX_CHANNELS; i++)
  94913. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&decoder->private_->partitioned_rice_contents[i]);
  94914. decoder->private_->file = 0;
  94915. set_defaults_dec(decoder);
  94916. decoder->protected_->state = FLAC__STREAM_DECODER_UNINITIALIZED;
  94917. return decoder;
  94918. }
  94919. FLAC_API void FLAC__stream_decoder_delete(FLAC__StreamDecoder *decoder)
  94920. {
  94921. unsigned i;
  94922. FLAC__ASSERT(0 != decoder);
  94923. FLAC__ASSERT(0 != decoder->protected_);
  94924. FLAC__ASSERT(0 != decoder->private_);
  94925. FLAC__ASSERT(0 != decoder->private_->input);
  94926. (void)FLAC__stream_decoder_finish(decoder);
  94927. if(0 != decoder->private_->metadata_filter_ids)
  94928. free(decoder->private_->metadata_filter_ids);
  94929. FLAC__bitreader_delete(decoder->private_->input);
  94930. for(i = 0; i < FLAC__MAX_CHANNELS; i++)
  94931. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&decoder->private_->partitioned_rice_contents[i]);
  94932. free(decoder->private_);
  94933. free(decoder->protected_);
  94934. free(decoder);
  94935. }
  94936. /***********************************************************************
  94937. *
  94938. * Public class methods
  94939. *
  94940. ***********************************************************************/
  94941. static FLAC__StreamDecoderInitStatus init_stream_internal_dec(
  94942. FLAC__StreamDecoder *decoder,
  94943. FLAC__StreamDecoderReadCallback read_callback,
  94944. FLAC__StreamDecoderSeekCallback seek_callback,
  94945. FLAC__StreamDecoderTellCallback tell_callback,
  94946. FLAC__StreamDecoderLengthCallback length_callback,
  94947. FLAC__StreamDecoderEofCallback eof_callback,
  94948. FLAC__StreamDecoderWriteCallback write_callback,
  94949. FLAC__StreamDecoderMetadataCallback metadata_callback,
  94950. FLAC__StreamDecoderErrorCallback error_callback,
  94951. void *client_data,
  94952. FLAC__bool is_ogg
  94953. )
  94954. {
  94955. FLAC__ASSERT(0 != decoder);
  94956. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  94957. return FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED;
  94958. #if !FLAC__HAS_OGG
  94959. if(is_ogg)
  94960. return FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER;
  94961. #endif
  94962. if(
  94963. 0 == read_callback ||
  94964. 0 == write_callback ||
  94965. 0 == error_callback ||
  94966. (seek_callback && (0 == tell_callback || 0 == length_callback || 0 == eof_callback))
  94967. )
  94968. return FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS;
  94969. #if FLAC__HAS_OGG
  94970. decoder->private_->is_ogg = is_ogg;
  94971. if(is_ogg && !FLAC__ogg_decoder_aspect_init(&decoder->protected_->ogg_decoder_aspect))
  94972. return decoder->protected_->state = FLAC__STREAM_DECODER_OGG_ERROR;
  94973. #endif
  94974. /*
  94975. * get the CPU info and set the function pointers
  94976. */
  94977. FLAC__cpu_info(&decoder->private_->cpuinfo);
  94978. /* first default to the non-asm routines */
  94979. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal;
  94980. decoder->private_->local_lpc_restore_signal_64bit = FLAC__lpc_restore_signal_wide;
  94981. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal;
  94982. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal;
  94983. decoder->private_->local_bitreader_read_rice_signed_block = FLAC__bitreader_read_rice_signed_block;
  94984. /* now override with asm where appropriate */
  94985. #ifndef FLAC__NO_ASM
  94986. if(decoder->private_->cpuinfo.use_asm) {
  94987. #ifdef FLAC__CPU_IA32
  94988. FLAC__ASSERT(decoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_IA32);
  94989. #ifdef FLAC__HAS_NASM
  94990. #if 1 /*@@@@@@ OPT: not clearly faster, needs more testing */
  94991. if(decoder->private_->cpuinfo.data.ia32.bswap)
  94992. decoder->private_->local_bitreader_read_rice_signed_block = FLAC__bitreader_read_rice_signed_block_asm_ia32_bswap;
  94993. #endif
  94994. if(decoder->private_->cpuinfo.data.ia32.mmx) {
  94995. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal_asm_ia32;
  94996. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ia32_mmx;
  94997. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ia32_mmx;
  94998. }
  94999. else {
  95000. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal_asm_ia32;
  95001. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ia32;
  95002. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ia32;
  95003. }
  95004. #endif
  95005. #elif defined FLAC__CPU_PPC
  95006. FLAC__ASSERT(decoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_PPC);
  95007. if(decoder->private_->cpuinfo.data.ppc.altivec) {
  95008. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ppc_altivec_16;
  95009. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ppc_altivec_16_order8;
  95010. }
  95011. #endif
  95012. }
  95013. #endif
  95014. /* from here on, errors are fatal */
  95015. if(!FLAC__bitreader_init(decoder->private_->input, decoder->private_->cpuinfo, read_callback_, decoder)) {
  95016. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  95017. return FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR;
  95018. }
  95019. decoder->private_->read_callback = read_callback;
  95020. decoder->private_->seek_callback = seek_callback;
  95021. decoder->private_->tell_callback = tell_callback;
  95022. decoder->private_->length_callback = length_callback;
  95023. decoder->private_->eof_callback = eof_callback;
  95024. decoder->private_->write_callback = write_callback;
  95025. decoder->private_->metadata_callback = metadata_callback;
  95026. decoder->private_->error_callback = error_callback;
  95027. decoder->private_->client_data = client_data;
  95028. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size = 0;
  95029. decoder->private_->samples_decoded = 0;
  95030. decoder->private_->has_stream_info = false;
  95031. decoder->private_->cached = false;
  95032. decoder->private_->do_md5_checking = decoder->protected_->md5_checking;
  95033. decoder->private_->is_seeking = false;
  95034. decoder->private_->internal_reset_hack = true; /* so the following reset does not try to rewind the input */
  95035. if(!FLAC__stream_decoder_reset(decoder)) {
  95036. /* above call sets the state for us */
  95037. return FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR;
  95038. }
  95039. return FLAC__STREAM_DECODER_INIT_STATUS_OK;
  95040. }
  95041. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_stream(
  95042. FLAC__StreamDecoder *decoder,
  95043. FLAC__StreamDecoderReadCallback read_callback,
  95044. FLAC__StreamDecoderSeekCallback seek_callback,
  95045. FLAC__StreamDecoderTellCallback tell_callback,
  95046. FLAC__StreamDecoderLengthCallback length_callback,
  95047. FLAC__StreamDecoderEofCallback eof_callback,
  95048. FLAC__StreamDecoderWriteCallback write_callback,
  95049. FLAC__StreamDecoderMetadataCallback metadata_callback,
  95050. FLAC__StreamDecoderErrorCallback error_callback,
  95051. void *client_data
  95052. )
  95053. {
  95054. return init_stream_internal_dec(
  95055. decoder,
  95056. read_callback,
  95057. seek_callback,
  95058. tell_callback,
  95059. length_callback,
  95060. eof_callback,
  95061. write_callback,
  95062. metadata_callback,
  95063. error_callback,
  95064. client_data,
  95065. /*is_ogg=*/false
  95066. );
  95067. }
  95068. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_stream(
  95069. FLAC__StreamDecoder *decoder,
  95070. FLAC__StreamDecoderReadCallback read_callback,
  95071. FLAC__StreamDecoderSeekCallback seek_callback,
  95072. FLAC__StreamDecoderTellCallback tell_callback,
  95073. FLAC__StreamDecoderLengthCallback length_callback,
  95074. FLAC__StreamDecoderEofCallback eof_callback,
  95075. FLAC__StreamDecoderWriteCallback write_callback,
  95076. FLAC__StreamDecoderMetadataCallback metadata_callback,
  95077. FLAC__StreamDecoderErrorCallback error_callback,
  95078. void *client_data
  95079. )
  95080. {
  95081. return init_stream_internal_dec(
  95082. decoder,
  95083. read_callback,
  95084. seek_callback,
  95085. tell_callback,
  95086. length_callback,
  95087. eof_callback,
  95088. write_callback,
  95089. metadata_callback,
  95090. error_callback,
  95091. client_data,
  95092. /*is_ogg=*/true
  95093. );
  95094. }
  95095. static FLAC__StreamDecoderInitStatus init_FILE_internal_(
  95096. FLAC__StreamDecoder *decoder,
  95097. FILE *file,
  95098. FLAC__StreamDecoderWriteCallback write_callback,
  95099. FLAC__StreamDecoderMetadataCallback metadata_callback,
  95100. FLAC__StreamDecoderErrorCallback error_callback,
  95101. void *client_data,
  95102. FLAC__bool is_ogg
  95103. )
  95104. {
  95105. FLAC__ASSERT(0 != decoder);
  95106. FLAC__ASSERT(0 != file);
  95107. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  95108. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED);
  95109. if(0 == write_callback || 0 == error_callback)
  95110. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS);
  95111. /*
  95112. * To make sure that our file does not go unclosed after an error, we
  95113. * must assign the FILE pointer before any further error can occur in
  95114. * this routine.
  95115. */
  95116. if(file == stdin)
  95117. file = get_binary_stdin_(); /* just to be safe */
  95118. decoder->private_->file = file;
  95119. return init_stream_internal_dec(
  95120. decoder,
  95121. file_read_callback_dec,
  95122. decoder->private_->file == stdin? 0: file_seek_callback_dec,
  95123. decoder->private_->file == stdin? 0: file_tell_callback_dec,
  95124. decoder->private_->file == stdin? 0: file_length_callback_,
  95125. file_eof_callback_,
  95126. write_callback,
  95127. metadata_callback,
  95128. error_callback,
  95129. client_data,
  95130. is_ogg
  95131. );
  95132. }
  95133. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_FILE(
  95134. FLAC__StreamDecoder *decoder,
  95135. FILE *file,
  95136. FLAC__StreamDecoderWriteCallback write_callback,
  95137. FLAC__StreamDecoderMetadataCallback metadata_callback,
  95138. FLAC__StreamDecoderErrorCallback error_callback,
  95139. void *client_data
  95140. )
  95141. {
  95142. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/false);
  95143. }
  95144. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_FILE(
  95145. FLAC__StreamDecoder *decoder,
  95146. FILE *file,
  95147. FLAC__StreamDecoderWriteCallback write_callback,
  95148. FLAC__StreamDecoderMetadataCallback metadata_callback,
  95149. FLAC__StreamDecoderErrorCallback error_callback,
  95150. void *client_data
  95151. )
  95152. {
  95153. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/true);
  95154. }
  95155. static FLAC__StreamDecoderInitStatus init_file_internal_(
  95156. FLAC__StreamDecoder *decoder,
  95157. const char *filename,
  95158. FLAC__StreamDecoderWriteCallback write_callback,
  95159. FLAC__StreamDecoderMetadataCallback metadata_callback,
  95160. FLAC__StreamDecoderErrorCallback error_callback,
  95161. void *client_data,
  95162. FLAC__bool is_ogg
  95163. )
  95164. {
  95165. FILE *file;
  95166. FLAC__ASSERT(0 != decoder);
  95167. /*
  95168. * To make sure that our file does not go unclosed after an error, we
  95169. * have to do the same entrance checks here that are later performed
  95170. * in FLAC__stream_decoder_init_FILE() before the FILE* is assigned.
  95171. */
  95172. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  95173. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED);
  95174. if(0 == write_callback || 0 == error_callback)
  95175. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS);
  95176. file = filename? fopen(filename, "rb") : stdin;
  95177. if(0 == file)
  95178. return FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE;
  95179. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, is_ogg);
  95180. }
  95181. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_file(
  95182. FLAC__StreamDecoder *decoder,
  95183. const char *filename,
  95184. FLAC__StreamDecoderWriteCallback write_callback,
  95185. FLAC__StreamDecoderMetadataCallback metadata_callback,
  95186. FLAC__StreamDecoderErrorCallback error_callback,
  95187. void *client_data
  95188. )
  95189. {
  95190. return init_file_internal_(decoder, filename, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/false);
  95191. }
  95192. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_file(
  95193. FLAC__StreamDecoder *decoder,
  95194. const char *filename,
  95195. FLAC__StreamDecoderWriteCallback write_callback,
  95196. FLAC__StreamDecoderMetadataCallback metadata_callback,
  95197. FLAC__StreamDecoderErrorCallback error_callback,
  95198. void *client_data
  95199. )
  95200. {
  95201. return init_file_internal_(decoder, filename, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/true);
  95202. }
  95203. FLAC_API FLAC__bool FLAC__stream_decoder_finish(FLAC__StreamDecoder *decoder)
  95204. {
  95205. FLAC__bool md5_failed = false;
  95206. unsigned i;
  95207. FLAC__ASSERT(0 != decoder);
  95208. FLAC__ASSERT(0 != decoder->private_);
  95209. FLAC__ASSERT(0 != decoder->protected_);
  95210. if(decoder->protected_->state == FLAC__STREAM_DECODER_UNINITIALIZED)
  95211. return true;
  95212. /* see the comment in FLAC__seekable_stream_decoder_reset() as to why we
  95213. * always call FLAC__MD5Final()
  95214. */
  95215. FLAC__MD5Final(decoder->private_->computed_md5sum, &decoder->private_->md5context);
  95216. if(decoder->private_->has_seek_table && 0 != decoder->private_->seek_table.data.seek_table.points) {
  95217. free(decoder->private_->seek_table.data.seek_table.points);
  95218. decoder->private_->seek_table.data.seek_table.points = 0;
  95219. decoder->private_->has_seek_table = false;
  95220. }
  95221. FLAC__bitreader_free(decoder->private_->input);
  95222. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  95223. /* WATCHOUT:
  95224. * FLAC__lpc_restore_signal_asm_ia32_mmx() requires that the
  95225. * output arrays have a buffer of up to 3 zeroes in front
  95226. * (at negative indices) for alignment purposes; we use 4
  95227. * to keep the data well-aligned.
  95228. */
  95229. if(0 != decoder->private_->output[i]) {
  95230. free(decoder->private_->output[i]-4);
  95231. decoder->private_->output[i] = 0;
  95232. }
  95233. if(0 != decoder->private_->residual_unaligned[i]) {
  95234. free(decoder->private_->residual_unaligned[i]);
  95235. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  95236. }
  95237. }
  95238. decoder->private_->output_capacity = 0;
  95239. decoder->private_->output_channels = 0;
  95240. #if FLAC__HAS_OGG
  95241. if(decoder->private_->is_ogg)
  95242. FLAC__ogg_decoder_aspect_finish(&decoder->protected_->ogg_decoder_aspect);
  95243. #endif
  95244. if(0 != decoder->private_->file) {
  95245. if(decoder->private_->file != stdin)
  95246. fclose(decoder->private_->file);
  95247. decoder->private_->file = 0;
  95248. }
  95249. if(decoder->private_->do_md5_checking) {
  95250. if(memcmp(decoder->private_->stream_info.data.stream_info.md5sum, decoder->private_->computed_md5sum, 16))
  95251. md5_failed = true;
  95252. }
  95253. decoder->private_->is_seeking = false;
  95254. set_defaults_dec(decoder);
  95255. decoder->protected_->state = FLAC__STREAM_DECODER_UNINITIALIZED;
  95256. return !md5_failed;
  95257. }
  95258. FLAC_API FLAC__bool FLAC__stream_decoder_set_ogg_serial_number(FLAC__StreamDecoder *decoder, long value)
  95259. {
  95260. FLAC__ASSERT(0 != decoder);
  95261. FLAC__ASSERT(0 != decoder->private_);
  95262. FLAC__ASSERT(0 != decoder->protected_);
  95263. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  95264. return false;
  95265. #if FLAC__HAS_OGG
  95266. /* can't check decoder->private_->is_ogg since that's not set until init time */
  95267. FLAC__ogg_decoder_aspect_set_serial_number(&decoder->protected_->ogg_decoder_aspect, value);
  95268. return true;
  95269. #else
  95270. (void)value;
  95271. return false;
  95272. #endif
  95273. }
  95274. FLAC_API FLAC__bool FLAC__stream_decoder_set_md5_checking(FLAC__StreamDecoder *decoder, FLAC__bool value)
  95275. {
  95276. FLAC__ASSERT(0 != decoder);
  95277. FLAC__ASSERT(0 != decoder->protected_);
  95278. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  95279. return false;
  95280. decoder->protected_->md5_checking = value;
  95281. return true;
  95282. }
  95283. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond(FLAC__StreamDecoder *decoder, FLAC__MetadataType type)
  95284. {
  95285. FLAC__ASSERT(0 != decoder);
  95286. FLAC__ASSERT(0 != decoder->private_);
  95287. FLAC__ASSERT(0 != decoder->protected_);
  95288. FLAC__ASSERT((unsigned)type <= FLAC__MAX_METADATA_TYPE_CODE);
  95289. /* double protection */
  95290. if((unsigned)type > FLAC__MAX_METADATA_TYPE_CODE)
  95291. return false;
  95292. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  95293. return false;
  95294. decoder->private_->metadata_filter[type] = true;
  95295. if(type == FLAC__METADATA_TYPE_APPLICATION)
  95296. decoder->private_->metadata_filter_ids_count = 0;
  95297. return true;
  95298. }
  95299. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4])
  95300. {
  95301. FLAC__ASSERT(0 != decoder);
  95302. FLAC__ASSERT(0 != decoder->private_);
  95303. FLAC__ASSERT(0 != decoder->protected_);
  95304. FLAC__ASSERT(0 != id);
  95305. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  95306. return false;
  95307. if(decoder->private_->metadata_filter[FLAC__METADATA_TYPE_APPLICATION])
  95308. return true;
  95309. FLAC__ASSERT(0 != decoder->private_->metadata_filter_ids);
  95310. if(decoder->private_->metadata_filter_ids_count == decoder->private_->metadata_filter_ids_capacity) {
  95311. if(0 == (decoder->private_->metadata_filter_ids = (FLAC__byte*)safe_realloc_mul_2op_(decoder->private_->metadata_filter_ids, decoder->private_->metadata_filter_ids_capacity, /*times*/2))) {
  95312. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  95313. return false;
  95314. }
  95315. decoder->private_->metadata_filter_ids_capacity *= 2;
  95316. }
  95317. memcpy(decoder->private_->metadata_filter_ids + decoder->private_->metadata_filter_ids_count * (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8), id, (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8));
  95318. decoder->private_->metadata_filter_ids_count++;
  95319. return true;
  95320. }
  95321. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_all(FLAC__StreamDecoder *decoder)
  95322. {
  95323. unsigned i;
  95324. FLAC__ASSERT(0 != decoder);
  95325. FLAC__ASSERT(0 != decoder->private_);
  95326. FLAC__ASSERT(0 != decoder->protected_);
  95327. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  95328. return false;
  95329. for(i = 0; i < sizeof(decoder->private_->metadata_filter) / sizeof(decoder->private_->metadata_filter[0]); i++)
  95330. decoder->private_->metadata_filter[i] = true;
  95331. decoder->private_->metadata_filter_ids_count = 0;
  95332. return true;
  95333. }
  95334. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore(FLAC__StreamDecoder *decoder, FLAC__MetadataType type)
  95335. {
  95336. FLAC__ASSERT(0 != decoder);
  95337. FLAC__ASSERT(0 != decoder->private_);
  95338. FLAC__ASSERT(0 != decoder->protected_);
  95339. FLAC__ASSERT((unsigned)type <= FLAC__MAX_METADATA_TYPE_CODE);
  95340. /* double protection */
  95341. if((unsigned)type > FLAC__MAX_METADATA_TYPE_CODE)
  95342. return false;
  95343. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  95344. return false;
  95345. decoder->private_->metadata_filter[type] = false;
  95346. if(type == FLAC__METADATA_TYPE_APPLICATION)
  95347. decoder->private_->metadata_filter_ids_count = 0;
  95348. return true;
  95349. }
  95350. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4])
  95351. {
  95352. FLAC__ASSERT(0 != decoder);
  95353. FLAC__ASSERT(0 != decoder->private_);
  95354. FLAC__ASSERT(0 != decoder->protected_);
  95355. FLAC__ASSERT(0 != id);
  95356. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  95357. return false;
  95358. if(!decoder->private_->metadata_filter[FLAC__METADATA_TYPE_APPLICATION])
  95359. return true;
  95360. FLAC__ASSERT(0 != decoder->private_->metadata_filter_ids);
  95361. if(decoder->private_->metadata_filter_ids_count == decoder->private_->metadata_filter_ids_capacity) {
  95362. if(0 == (decoder->private_->metadata_filter_ids = (FLAC__byte*)safe_realloc_mul_2op_(decoder->private_->metadata_filter_ids, decoder->private_->metadata_filter_ids_capacity, /*times*/2))) {
  95363. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  95364. return false;
  95365. }
  95366. decoder->private_->metadata_filter_ids_capacity *= 2;
  95367. }
  95368. memcpy(decoder->private_->metadata_filter_ids + decoder->private_->metadata_filter_ids_count * (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8), id, (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8));
  95369. decoder->private_->metadata_filter_ids_count++;
  95370. return true;
  95371. }
  95372. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_all(FLAC__StreamDecoder *decoder)
  95373. {
  95374. FLAC__ASSERT(0 != decoder);
  95375. FLAC__ASSERT(0 != decoder->private_);
  95376. FLAC__ASSERT(0 != decoder->protected_);
  95377. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  95378. return false;
  95379. memset(decoder->private_->metadata_filter, 0, sizeof(decoder->private_->metadata_filter));
  95380. decoder->private_->metadata_filter_ids_count = 0;
  95381. return true;
  95382. }
  95383. FLAC_API FLAC__StreamDecoderState FLAC__stream_decoder_get_state(const FLAC__StreamDecoder *decoder)
  95384. {
  95385. FLAC__ASSERT(0 != decoder);
  95386. FLAC__ASSERT(0 != decoder->protected_);
  95387. return decoder->protected_->state;
  95388. }
  95389. FLAC_API const char *FLAC__stream_decoder_get_resolved_state_string(const FLAC__StreamDecoder *decoder)
  95390. {
  95391. return FLAC__StreamDecoderStateString[decoder->protected_->state];
  95392. }
  95393. FLAC_API FLAC__bool FLAC__stream_decoder_get_md5_checking(const FLAC__StreamDecoder *decoder)
  95394. {
  95395. FLAC__ASSERT(0 != decoder);
  95396. FLAC__ASSERT(0 != decoder->protected_);
  95397. return decoder->protected_->md5_checking;
  95398. }
  95399. FLAC_API FLAC__uint64 FLAC__stream_decoder_get_total_samples(const FLAC__StreamDecoder *decoder)
  95400. {
  95401. FLAC__ASSERT(0 != decoder);
  95402. FLAC__ASSERT(0 != decoder->protected_);
  95403. return decoder->private_->has_stream_info? decoder->private_->stream_info.data.stream_info.total_samples : 0;
  95404. }
  95405. FLAC_API unsigned FLAC__stream_decoder_get_channels(const FLAC__StreamDecoder *decoder)
  95406. {
  95407. FLAC__ASSERT(0 != decoder);
  95408. FLAC__ASSERT(0 != decoder->protected_);
  95409. return decoder->protected_->channels;
  95410. }
  95411. FLAC_API FLAC__ChannelAssignment FLAC__stream_decoder_get_channel_assignment(const FLAC__StreamDecoder *decoder)
  95412. {
  95413. FLAC__ASSERT(0 != decoder);
  95414. FLAC__ASSERT(0 != decoder->protected_);
  95415. return decoder->protected_->channel_assignment;
  95416. }
  95417. FLAC_API unsigned FLAC__stream_decoder_get_bits_per_sample(const FLAC__StreamDecoder *decoder)
  95418. {
  95419. FLAC__ASSERT(0 != decoder);
  95420. FLAC__ASSERT(0 != decoder->protected_);
  95421. return decoder->protected_->bits_per_sample;
  95422. }
  95423. FLAC_API unsigned FLAC__stream_decoder_get_sample_rate(const FLAC__StreamDecoder *decoder)
  95424. {
  95425. FLAC__ASSERT(0 != decoder);
  95426. FLAC__ASSERT(0 != decoder->protected_);
  95427. return decoder->protected_->sample_rate;
  95428. }
  95429. FLAC_API unsigned FLAC__stream_decoder_get_blocksize(const FLAC__StreamDecoder *decoder)
  95430. {
  95431. FLAC__ASSERT(0 != decoder);
  95432. FLAC__ASSERT(0 != decoder->protected_);
  95433. return decoder->protected_->blocksize;
  95434. }
  95435. FLAC_API FLAC__bool FLAC__stream_decoder_get_decode_position(const FLAC__StreamDecoder *decoder, FLAC__uint64 *position)
  95436. {
  95437. FLAC__ASSERT(0 != decoder);
  95438. FLAC__ASSERT(0 != decoder->private_);
  95439. FLAC__ASSERT(0 != position);
  95440. #if FLAC__HAS_OGG
  95441. if(decoder->private_->is_ogg)
  95442. return false;
  95443. #endif
  95444. if(0 == decoder->private_->tell_callback)
  95445. return false;
  95446. if(decoder->private_->tell_callback(decoder, position, decoder->private_->client_data) != FLAC__STREAM_DECODER_TELL_STATUS_OK)
  95447. return false;
  95448. /* should never happen since all FLAC frames and metadata blocks are byte aligned, but check just in case */
  95449. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input))
  95450. return false;
  95451. FLAC__ASSERT(*position >= FLAC__stream_decoder_get_input_bytes_unconsumed(decoder));
  95452. *position -= FLAC__stream_decoder_get_input_bytes_unconsumed(decoder);
  95453. return true;
  95454. }
  95455. FLAC_API FLAC__bool FLAC__stream_decoder_flush(FLAC__StreamDecoder *decoder)
  95456. {
  95457. FLAC__ASSERT(0 != decoder);
  95458. FLAC__ASSERT(0 != decoder->private_);
  95459. FLAC__ASSERT(0 != decoder->protected_);
  95460. decoder->private_->samples_decoded = 0;
  95461. decoder->private_->do_md5_checking = false;
  95462. #if FLAC__HAS_OGG
  95463. if(decoder->private_->is_ogg)
  95464. FLAC__ogg_decoder_aspect_flush(&decoder->protected_->ogg_decoder_aspect);
  95465. #endif
  95466. if(!FLAC__bitreader_clear(decoder->private_->input)) {
  95467. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  95468. return false;
  95469. }
  95470. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  95471. return true;
  95472. }
  95473. FLAC_API FLAC__bool FLAC__stream_decoder_reset(FLAC__StreamDecoder *decoder)
  95474. {
  95475. FLAC__ASSERT(0 != decoder);
  95476. FLAC__ASSERT(0 != decoder->private_);
  95477. FLAC__ASSERT(0 != decoder->protected_);
  95478. if(!FLAC__stream_decoder_flush(decoder)) {
  95479. /* above call sets the state for us */
  95480. return false;
  95481. }
  95482. #if FLAC__HAS_OGG
  95483. /*@@@ could go in !internal_reset_hack block below */
  95484. if(decoder->private_->is_ogg)
  95485. FLAC__ogg_decoder_aspect_reset(&decoder->protected_->ogg_decoder_aspect);
  95486. #endif
  95487. /* Rewind if necessary. If FLAC__stream_decoder_init() is calling us,
  95488. * (internal_reset_hack) don't try to rewind since we are already at
  95489. * the beginning of the stream and don't want to fail if the input is
  95490. * not seekable.
  95491. */
  95492. if(!decoder->private_->internal_reset_hack) {
  95493. if(decoder->private_->file == stdin)
  95494. return false; /* can't rewind stdin, reset fails */
  95495. if(decoder->private_->seek_callback && decoder->private_->seek_callback(decoder, 0, decoder->private_->client_data) == FLAC__STREAM_DECODER_SEEK_STATUS_ERROR)
  95496. return false; /* seekable and seek fails, reset fails */
  95497. }
  95498. else
  95499. decoder->private_->internal_reset_hack = false;
  95500. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_METADATA;
  95501. decoder->private_->has_stream_info = false;
  95502. if(decoder->private_->has_seek_table && 0 != decoder->private_->seek_table.data.seek_table.points) {
  95503. free(decoder->private_->seek_table.data.seek_table.points);
  95504. decoder->private_->seek_table.data.seek_table.points = 0;
  95505. decoder->private_->has_seek_table = false;
  95506. }
  95507. decoder->private_->do_md5_checking = decoder->protected_->md5_checking;
  95508. /*
  95509. * This goes in reset() and not flush() because according to the spec, a
  95510. * fixed-blocksize stream must stay that way through the whole stream.
  95511. */
  95512. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size = 0;
  95513. /* We initialize the FLAC__MD5Context even though we may never use it. This
  95514. * is because md5 checking may be turned on to start and then turned off if
  95515. * a seek occurs. So we init the context here and finalize it in
  95516. * FLAC__stream_decoder_finish() to make sure things are always cleaned up
  95517. * properly.
  95518. */
  95519. FLAC__MD5Init(&decoder->private_->md5context);
  95520. decoder->private_->first_frame_offset = 0;
  95521. decoder->private_->unparseable_frame_count = 0;
  95522. return true;
  95523. }
  95524. FLAC_API FLAC__bool FLAC__stream_decoder_process_single(FLAC__StreamDecoder *decoder)
  95525. {
  95526. FLAC__bool got_a_frame;
  95527. FLAC__ASSERT(0 != decoder);
  95528. FLAC__ASSERT(0 != decoder->protected_);
  95529. while(1) {
  95530. switch(decoder->protected_->state) {
  95531. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  95532. if(!find_metadata_(decoder))
  95533. return false; /* above function sets the status for us */
  95534. break;
  95535. case FLAC__STREAM_DECODER_READ_METADATA:
  95536. if(!read_metadata_(decoder))
  95537. return false; /* above function sets the status for us */
  95538. else
  95539. return true;
  95540. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  95541. if(!frame_sync_(decoder))
  95542. return true; /* above function sets the status for us */
  95543. break;
  95544. case FLAC__STREAM_DECODER_READ_FRAME:
  95545. if(!read_frame_(decoder, &got_a_frame, /*do_full_decode=*/true))
  95546. return false; /* above function sets the status for us */
  95547. if(got_a_frame)
  95548. return true; /* above function sets the status for us */
  95549. break;
  95550. case FLAC__STREAM_DECODER_END_OF_STREAM:
  95551. case FLAC__STREAM_DECODER_ABORTED:
  95552. return true;
  95553. default:
  95554. FLAC__ASSERT(0);
  95555. return false;
  95556. }
  95557. }
  95558. }
  95559. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_metadata(FLAC__StreamDecoder *decoder)
  95560. {
  95561. FLAC__ASSERT(0 != decoder);
  95562. FLAC__ASSERT(0 != decoder->protected_);
  95563. while(1) {
  95564. switch(decoder->protected_->state) {
  95565. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  95566. if(!find_metadata_(decoder))
  95567. return false; /* above function sets the status for us */
  95568. break;
  95569. case FLAC__STREAM_DECODER_READ_METADATA:
  95570. if(!read_metadata_(decoder))
  95571. return false; /* above function sets the status for us */
  95572. break;
  95573. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  95574. case FLAC__STREAM_DECODER_READ_FRAME:
  95575. case FLAC__STREAM_DECODER_END_OF_STREAM:
  95576. case FLAC__STREAM_DECODER_ABORTED:
  95577. return true;
  95578. default:
  95579. FLAC__ASSERT(0);
  95580. return false;
  95581. }
  95582. }
  95583. }
  95584. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_stream(FLAC__StreamDecoder *decoder)
  95585. {
  95586. FLAC__bool dummy;
  95587. FLAC__ASSERT(0 != decoder);
  95588. FLAC__ASSERT(0 != decoder->protected_);
  95589. while(1) {
  95590. switch(decoder->protected_->state) {
  95591. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  95592. if(!find_metadata_(decoder))
  95593. return false; /* above function sets the status for us */
  95594. break;
  95595. case FLAC__STREAM_DECODER_READ_METADATA:
  95596. if(!read_metadata_(decoder))
  95597. return false; /* above function sets the status for us */
  95598. break;
  95599. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  95600. if(!frame_sync_(decoder))
  95601. return true; /* above function sets the status for us */
  95602. break;
  95603. case FLAC__STREAM_DECODER_READ_FRAME:
  95604. if(!read_frame_(decoder, &dummy, /*do_full_decode=*/true))
  95605. return false; /* above function sets the status for us */
  95606. break;
  95607. case FLAC__STREAM_DECODER_END_OF_STREAM:
  95608. case FLAC__STREAM_DECODER_ABORTED:
  95609. return true;
  95610. default:
  95611. FLAC__ASSERT(0);
  95612. return false;
  95613. }
  95614. }
  95615. }
  95616. FLAC_API FLAC__bool FLAC__stream_decoder_skip_single_frame(FLAC__StreamDecoder *decoder)
  95617. {
  95618. FLAC__bool got_a_frame;
  95619. FLAC__ASSERT(0 != decoder);
  95620. FLAC__ASSERT(0 != decoder->protected_);
  95621. while(1) {
  95622. switch(decoder->protected_->state) {
  95623. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  95624. case FLAC__STREAM_DECODER_READ_METADATA:
  95625. return false; /* above function sets the status for us */
  95626. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  95627. if(!frame_sync_(decoder))
  95628. return true; /* above function sets the status for us */
  95629. break;
  95630. case FLAC__STREAM_DECODER_READ_FRAME:
  95631. if(!read_frame_(decoder, &got_a_frame, /*do_full_decode=*/false))
  95632. return false; /* above function sets the status for us */
  95633. if(got_a_frame)
  95634. return true; /* above function sets the status for us */
  95635. break;
  95636. case FLAC__STREAM_DECODER_END_OF_STREAM:
  95637. case FLAC__STREAM_DECODER_ABORTED:
  95638. return true;
  95639. default:
  95640. FLAC__ASSERT(0);
  95641. return false;
  95642. }
  95643. }
  95644. }
  95645. FLAC_API FLAC__bool FLAC__stream_decoder_seek_absolute(FLAC__StreamDecoder *decoder, FLAC__uint64 sample)
  95646. {
  95647. FLAC__uint64 length;
  95648. FLAC__ASSERT(0 != decoder);
  95649. if(
  95650. decoder->protected_->state != FLAC__STREAM_DECODER_SEARCH_FOR_METADATA &&
  95651. decoder->protected_->state != FLAC__STREAM_DECODER_READ_METADATA &&
  95652. decoder->protected_->state != FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC &&
  95653. decoder->protected_->state != FLAC__STREAM_DECODER_READ_FRAME &&
  95654. decoder->protected_->state != FLAC__STREAM_DECODER_END_OF_STREAM
  95655. )
  95656. return false;
  95657. if(0 == decoder->private_->seek_callback)
  95658. return false;
  95659. FLAC__ASSERT(decoder->private_->seek_callback);
  95660. FLAC__ASSERT(decoder->private_->tell_callback);
  95661. FLAC__ASSERT(decoder->private_->length_callback);
  95662. FLAC__ASSERT(decoder->private_->eof_callback);
  95663. if(FLAC__stream_decoder_get_total_samples(decoder) > 0 && sample >= FLAC__stream_decoder_get_total_samples(decoder))
  95664. return false;
  95665. decoder->private_->is_seeking = true;
  95666. /* turn off md5 checking if a seek is attempted */
  95667. decoder->private_->do_md5_checking = false;
  95668. /* get the file length (currently our algorithm needs to know the length so it's also an error to get FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED) */
  95669. if(decoder->private_->length_callback(decoder, &length, decoder->private_->client_data) != FLAC__STREAM_DECODER_LENGTH_STATUS_OK) {
  95670. decoder->private_->is_seeking = false;
  95671. return false;
  95672. }
  95673. /* if we haven't finished processing the metadata yet, do that so we have the STREAMINFO, SEEK_TABLE, and first_frame_offset */
  95674. if(
  95675. decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_METADATA ||
  95676. decoder->protected_->state == FLAC__STREAM_DECODER_READ_METADATA
  95677. ) {
  95678. if(!FLAC__stream_decoder_process_until_end_of_metadata(decoder)) {
  95679. /* above call sets the state for us */
  95680. decoder->private_->is_seeking = false;
  95681. return false;
  95682. }
  95683. /* check this again in case we didn't know total_samples the first time */
  95684. if(FLAC__stream_decoder_get_total_samples(decoder) > 0 && sample >= FLAC__stream_decoder_get_total_samples(decoder)) {
  95685. decoder->private_->is_seeking = false;
  95686. return false;
  95687. }
  95688. }
  95689. {
  95690. const FLAC__bool ok =
  95691. #if FLAC__HAS_OGG
  95692. decoder->private_->is_ogg?
  95693. seek_to_absolute_sample_ogg_(decoder, length, sample) :
  95694. #endif
  95695. seek_to_absolute_sample_(decoder, length, sample)
  95696. ;
  95697. decoder->private_->is_seeking = false;
  95698. return ok;
  95699. }
  95700. }
  95701. /***********************************************************************
  95702. *
  95703. * Protected class methods
  95704. *
  95705. ***********************************************************************/
  95706. unsigned FLAC__stream_decoder_get_input_bytes_unconsumed(const FLAC__StreamDecoder *decoder)
  95707. {
  95708. FLAC__ASSERT(0 != decoder);
  95709. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  95710. FLAC__ASSERT(!(FLAC__bitreader_get_input_bits_unconsumed(decoder->private_->input) & 7));
  95711. return FLAC__bitreader_get_input_bits_unconsumed(decoder->private_->input) / 8;
  95712. }
  95713. /***********************************************************************
  95714. *
  95715. * Private class methods
  95716. *
  95717. ***********************************************************************/
  95718. void set_defaults_dec(FLAC__StreamDecoder *decoder)
  95719. {
  95720. #if FLAC__HAS_OGG
  95721. decoder->private_->is_ogg = false;
  95722. #endif
  95723. decoder->private_->read_callback = 0;
  95724. decoder->private_->seek_callback = 0;
  95725. decoder->private_->tell_callback = 0;
  95726. decoder->private_->length_callback = 0;
  95727. decoder->private_->eof_callback = 0;
  95728. decoder->private_->write_callback = 0;
  95729. decoder->private_->metadata_callback = 0;
  95730. decoder->private_->error_callback = 0;
  95731. decoder->private_->client_data = 0;
  95732. memset(decoder->private_->metadata_filter, 0, sizeof(decoder->private_->metadata_filter));
  95733. decoder->private_->metadata_filter[FLAC__METADATA_TYPE_STREAMINFO] = true;
  95734. decoder->private_->metadata_filter_ids_count = 0;
  95735. decoder->protected_->md5_checking = false;
  95736. #if FLAC__HAS_OGG
  95737. FLAC__ogg_decoder_aspect_set_defaults(&decoder->protected_->ogg_decoder_aspect);
  95738. #endif
  95739. }
  95740. /*
  95741. * This will forcibly set stdin to binary mode (for OSes that require it)
  95742. */
  95743. FILE *get_binary_stdin_(void)
  95744. {
  95745. /* if something breaks here it is probably due to the presence or
  95746. * absence of an underscore before the identifiers 'setmode',
  95747. * 'fileno', and/or 'O_BINARY'; check your system header files.
  95748. */
  95749. #if defined _MSC_VER || defined __MINGW32__
  95750. _setmode(_fileno(stdin), _O_BINARY);
  95751. #elif defined __CYGWIN__
  95752. /* almost certainly not needed for any modern Cygwin, but let's be safe... */
  95753. setmode(_fileno(stdin), _O_BINARY);
  95754. #elif defined __EMX__
  95755. setmode(fileno(stdin), O_BINARY);
  95756. #endif
  95757. return stdin;
  95758. }
  95759. FLAC__bool allocate_output_(FLAC__StreamDecoder *decoder, unsigned size, unsigned channels)
  95760. {
  95761. unsigned i;
  95762. FLAC__int32 *tmp;
  95763. if(size <= decoder->private_->output_capacity && channels <= decoder->private_->output_channels)
  95764. return true;
  95765. /* simply using realloc() is not practical because the number of channels may change mid-stream */
  95766. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  95767. if(0 != decoder->private_->output[i]) {
  95768. free(decoder->private_->output[i]-4);
  95769. decoder->private_->output[i] = 0;
  95770. }
  95771. if(0 != decoder->private_->residual_unaligned[i]) {
  95772. free(decoder->private_->residual_unaligned[i]);
  95773. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  95774. }
  95775. }
  95776. for(i = 0; i < channels; i++) {
  95777. /* WATCHOUT:
  95778. * FLAC__lpc_restore_signal_asm_ia32_mmx() requires that the
  95779. * output arrays have a buffer of up to 3 zeroes in front
  95780. * (at negative indices) for alignment purposes; we use 4
  95781. * to keep the data well-aligned.
  95782. */
  95783. tmp = (FLAC__int32*)safe_malloc_muladd2_(sizeof(FLAC__int32), /*times (*/size, /*+*/4/*)*/);
  95784. if(tmp == 0) {
  95785. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  95786. return false;
  95787. }
  95788. memset(tmp, 0, sizeof(FLAC__int32)*4);
  95789. decoder->private_->output[i] = tmp + 4;
  95790. /* WATCHOUT:
  95791. * minimum of quadword alignment for PPC vector optimizations is REQUIRED:
  95792. */
  95793. if(!FLAC__memory_alloc_aligned_int32_array(size, &decoder->private_->residual_unaligned[i], &decoder->private_->residual[i])) {
  95794. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  95795. return false;
  95796. }
  95797. }
  95798. decoder->private_->output_capacity = size;
  95799. decoder->private_->output_channels = channels;
  95800. return true;
  95801. }
  95802. FLAC__bool has_id_filtered_(FLAC__StreamDecoder *decoder, FLAC__byte *id)
  95803. {
  95804. size_t i;
  95805. FLAC__ASSERT(0 != decoder);
  95806. FLAC__ASSERT(0 != decoder->private_);
  95807. for(i = 0; i < decoder->private_->metadata_filter_ids_count; i++)
  95808. if(0 == memcmp(decoder->private_->metadata_filter_ids + i * (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8), id, (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8)))
  95809. return true;
  95810. return false;
  95811. }
  95812. FLAC__bool find_metadata_(FLAC__StreamDecoder *decoder)
  95813. {
  95814. FLAC__uint32 x;
  95815. unsigned i, id_;
  95816. FLAC__bool first = true;
  95817. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  95818. for(i = id_ = 0; i < 4; ) {
  95819. if(decoder->private_->cached) {
  95820. x = (FLAC__uint32)decoder->private_->lookahead;
  95821. decoder->private_->cached = false;
  95822. }
  95823. else {
  95824. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  95825. return false; /* read_callback_ sets the state for us */
  95826. }
  95827. if(x == FLAC__STREAM_SYNC_STRING[i]) {
  95828. first = true;
  95829. i++;
  95830. id_ = 0;
  95831. continue;
  95832. }
  95833. if(x == ID3V2_TAG_[id_]) {
  95834. id_++;
  95835. i = 0;
  95836. if(id_ == 3) {
  95837. if(!skip_id3v2_tag_(decoder))
  95838. return false; /* skip_id3v2_tag_ sets the state for us */
  95839. }
  95840. continue;
  95841. }
  95842. id_ = 0;
  95843. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  95844. decoder->private_->header_warmup[0] = (FLAC__byte)x;
  95845. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  95846. return false; /* read_callback_ sets the state for us */
  95847. /* we have to check if we just read two 0xff's in a row; the second may actually be the beginning of the sync code */
  95848. /* else we have to check if the second byte is the end of a sync code */
  95849. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  95850. decoder->private_->lookahead = (FLAC__byte)x;
  95851. decoder->private_->cached = true;
  95852. }
  95853. else if(x >> 2 == 0x3e) { /* MAGIC NUMBER for the last 6 sync bits */
  95854. decoder->private_->header_warmup[1] = (FLAC__byte)x;
  95855. decoder->protected_->state = FLAC__STREAM_DECODER_READ_FRAME;
  95856. return true;
  95857. }
  95858. }
  95859. i = 0;
  95860. if(first) {
  95861. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  95862. first = false;
  95863. }
  95864. }
  95865. decoder->protected_->state = FLAC__STREAM_DECODER_READ_METADATA;
  95866. return true;
  95867. }
  95868. FLAC__bool read_metadata_(FLAC__StreamDecoder *decoder)
  95869. {
  95870. FLAC__bool is_last;
  95871. FLAC__uint32 i, x, type, length;
  95872. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  95873. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_IS_LAST_LEN))
  95874. return false; /* read_callback_ sets the state for us */
  95875. is_last = x? true : false;
  95876. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &type, FLAC__STREAM_METADATA_TYPE_LEN))
  95877. return false; /* read_callback_ sets the state for us */
  95878. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &length, FLAC__STREAM_METADATA_LENGTH_LEN))
  95879. return false; /* read_callback_ sets the state for us */
  95880. if(type == FLAC__METADATA_TYPE_STREAMINFO) {
  95881. if(!read_metadata_streaminfo_(decoder, is_last, length))
  95882. return false;
  95883. decoder->private_->has_stream_info = true;
  95884. if(0 == memcmp(decoder->private_->stream_info.data.stream_info.md5sum, "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0", 16))
  95885. decoder->private_->do_md5_checking = false;
  95886. if(!decoder->private_->is_seeking && decoder->private_->metadata_filter[FLAC__METADATA_TYPE_STREAMINFO] && decoder->private_->metadata_callback)
  95887. decoder->private_->metadata_callback(decoder, &decoder->private_->stream_info, decoder->private_->client_data);
  95888. }
  95889. else if(type == FLAC__METADATA_TYPE_SEEKTABLE) {
  95890. if(!read_metadata_seektable_(decoder, is_last, length))
  95891. return false;
  95892. decoder->private_->has_seek_table = true;
  95893. if(!decoder->private_->is_seeking && decoder->private_->metadata_filter[FLAC__METADATA_TYPE_SEEKTABLE] && decoder->private_->metadata_callback)
  95894. decoder->private_->metadata_callback(decoder, &decoder->private_->seek_table, decoder->private_->client_data);
  95895. }
  95896. else {
  95897. FLAC__bool skip_it = !decoder->private_->metadata_filter[type];
  95898. unsigned real_length = length;
  95899. FLAC__StreamMetadata block;
  95900. block.is_last = is_last;
  95901. block.type = (FLAC__MetadataType)type;
  95902. block.length = length;
  95903. if(type == FLAC__METADATA_TYPE_APPLICATION) {
  95904. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.application.id, FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8))
  95905. return false; /* read_callback_ sets the state for us */
  95906. if(real_length < FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8) { /* underflow check */
  95907. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;/*@@@@@@ maybe wrong error? need to resync?*/
  95908. return false;
  95909. }
  95910. real_length -= FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8;
  95911. if(decoder->private_->metadata_filter_ids_count > 0 && has_id_filtered_(decoder, block.data.application.id))
  95912. skip_it = !skip_it;
  95913. }
  95914. if(skip_it) {
  95915. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, real_length))
  95916. return false; /* read_callback_ sets the state for us */
  95917. }
  95918. else {
  95919. switch(type) {
  95920. case FLAC__METADATA_TYPE_PADDING:
  95921. /* skip the padding bytes */
  95922. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, real_length))
  95923. return false; /* read_callback_ sets the state for us */
  95924. break;
  95925. case FLAC__METADATA_TYPE_APPLICATION:
  95926. /* remember, we read the ID already */
  95927. if(real_length > 0) {
  95928. if(0 == (block.data.application.data = (FLAC__byte*)malloc(real_length))) {
  95929. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  95930. return false;
  95931. }
  95932. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.application.data, real_length))
  95933. return false; /* read_callback_ sets the state for us */
  95934. }
  95935. else
  95936. block.data.application.data = 0;
  95937. break;
  95938. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  95939. if(!read_metadata_vorbiscomment_(decoder, &block.data.vorbis_comment))
  95940. return false;
  95941. break;
  95942. case FLAC__METADATA_TYPE_CUESHEET:
  95943. if(!read_metadata_cuesheet_(decoder, &block.data.cue_sheet))
  95944. return false;
  95945. break;
  95946. case FLAC__METADATA_TYPE_PICTURE:
  95947. if(!read_metadata_picture_(decoder, &block.data.picture))
  95948. return false;
  95949. break;
  95950. case FLAC__METADATA_TYPE_STREAMINFO:
  95951. case FLAC__METADATA_TYPE_SEEKTABLE:
  95952. FLAC__ASSERT(0);
  95953. break;
  95954. default:
  95955. if(real_length > 0) {
  95956. if(0 == (block.data.unknown.data = (FLAC__byte*)malloc(real_length))) {
  95957. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  95958. return false;
  95959. }
  95960. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.unknown.data, real_length))
  95961. return false; /* read_callback_ sets the state for us */
  95962. }
  95963. else
  95964. block.data.unknown.data = 0;
  95965. break;
  95966. }
  95967. if(!decoder->private_->is_seeking && decoder->private_->metadata_callback)
  95968. decoder->private_->metadata_callback(decoder, &block, decoder->private_->client_data);
  95969. /* now we have to free any malloc()ed data in the block */
  95970. switch(type) {
  95971. case FLAC__METADATA_TYPE_PADDING:
  95972. break;
  95973. case FLAC__METADATA_TYPE_APPLICATION:
  95974. if(0 != block.data.application.data)
  95975. free(block.data.application.data);
  95976. break;
  95977. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  95978. if(0 != block.data.vorbis_comment.vendor_string.entry)
  95979. free(block.data.vorbis_comment.vendor_string.entry);
  95980. if(block.data.vorbis_comment.num_comments > 0)
  95981. for(i = 0; i < block.data.vorbis_comment.num_comments; i++)
  95982. if(0 != block.data.vorbis_comment.comments[i].entry)
  95983. free(block.data.vorbis_comment.comments[i].entry);
  95984. if(0 != block.data.vorbis_comment.comments)
  95985. free(block.data.vorbis_comment.comments);
  95986. break;
  95987. case FLAC__METADATA_TYPE_CUESHEET:
  95988. if(block.data.cue_sheet.num_tracks > 0)
  95989. for(i = 0; i < block.data.cue_sheet.num_tracks; i++)
  95990. if(0 != block.data.cue_sheet.tracks[i].indices)
  95991. free(block.data.cue_sheet.tracks[i].indices);
  95992. if(0 != block.data.cue_sheet.tracks)
  95993. free(block.data.cue_sheet.tracks);
  95994. break;
  95995. case FLAC__METADATA_TYPE_PICTURE:
  95996. if(0 != block.data.picture.mime_type)
  95997. free(block.data.picture.mime_type);
  95998. if(0 != block.data.picture.description)
  95999. free(block.data.picture.description);
  96000. if(0 != block.data.picture.data)
  96001. free(block.data.picture.data);
  96002. break;
  96003. case FLAC__METADATA_TYPE_STREAMINFO:
  96004. case FLAC__METADATA_TYPE_SEEKTABLE:
  96005. FLAC__ASSERT(0);
  96006. default:
  96007. if(0 != block.data.unknown.data)
  96008. free(block.data.unknown.data);
  96009. break;
  96010. }
  96011. }
  96012. }
  96013. if(is_last) {
  96014. /* if this fails, it's OK, it's just a hint for the seek routine */
  96015. if(!FLAC__stream_decoder_get_decode_position(decoder, &decoder->private_->first_frame_offset))
  96016. decoder->private_->first_frame_offset = 0;
  96017. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  96018. }
  96019. return true;
  96020. }
  96021. FLAC__bool read_metadata_streaminfo_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length)
  96022. {
  96023. FLAC__uint32 x;
  96024. unsigned bits, used_bits = 0;
  96025. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  96026. decoder->private_->stream_info.type = FLAC__METADATA_TYPE_STREAMINFO;
  96027. decoder->private_->stream_info.is_last = is_last;
  96028. decoder->private_->stream_info.length = length;
  96029. bits = FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN;
  96030. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, bits))
  96031. return false; /* read_callback_ sets the state for us */
  96032. decoder->private_->stream_info.data.stream_info.min_blocksize = x;
  96033. used_bits += bits;
  96034. bits = FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN;
  96035. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN))
  96036. return false; /* read_callback_ sets the state for us */
  96037. decoder->private_->stream_info.data.stream_info.max_blocksize = x;
  96038. used_bits += bits;
  96039. bits = FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN;
  96040. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN))
  96041. return false; /* read_callback_ sets the state for us */
  96042. decoder->private_->stream_info.data.stream_info.min_framesize = x;
  96043. used_bits += bits;
  96044. bits = FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN;
  96045. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN))
  96046. return false; /* read_callback_ sets the state for us */
  96047. decoder->private_->stream_info.data.stream_info.max_framesize = x;
  96048. used_bits += bits;
  96049. bits = FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN;
  96050. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN))
  96051. return false; /* read_callback_ sets the state for us */
  96052. decoder->private_->stream_info.data.stream_info.sample_rate = x;
  96053. used_bits += bits;
  96054. bits = FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN;
  96055. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN))
  96056. return false; /* read_callback_ sets the state for us */
  96057. decoder->private_->stream_info.data.stream_info.channels = x+1;
  96058. used_bits += bits;
  96059. bits = FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN;
  96060. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN))
  96061. return false; /* read_callback_ sets the state for us */
  96062. decoder->private_->stream_info.data.stream_info.bits_per_sample = x+1;
  96063. used_bits += bits;
  96064. bits = FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN;
  96065. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &decoder->private_->stream_info.data.stream_info.total_samples, FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN))
  96066. return false; /* read_callback_ sets the state for us */
  96067. used_bits += bits;
  96068. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, decoder->private_->stream_info.data.stream_info.md5sum, 16))
  96069. return false; /* read_callback_ sets the state for us */
  96070. used_bits += 16*8;
  96071. /* skip the rest of the block */
  96072. FLAC__ASSERT(used_bits % 8 == 0);
  96073. length -= (used_bits / 8);
  96074. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, length))
  96075. return false; /* read_callback_ sets the state for us */
  96076. return true;
  96077. }
  96078. FLAC__bool read_metadata_seektable_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length)
  96079. {
  96080. FLAC__uint32 i, x;
  96081. FLAC__uint64 xx;
  96082. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  96083. decoder->private_->seek_table.type = FLAC__METADATA_TYPE_SEEKTABLE;
  96084. decoder->private_->seek_table.is_last = is_last;
  96085. decoder->private_->seek_table.length = length;
  96086. decoder->private_->seek_table.data.seek_table.num_points = length / FLAC__STREAM_METADATA_SEEKPOINT_LENGTH;
  96087. /* use realloc since we may pass through here several times (e.g. after seeking) */
  96088. if(0 == (decoder->private_->seek_table.data.seek_table.points = (FLAC__StreamMetadata_SeekPoint*)safe_realloc_mul_2op_(decoder->private_->seek_table.data.seek_table.points, decoder->private_->seek_table.data.seek_table.num_points, /*times*/sizeof(FLAC__StreamMetadata_SeekPoint)))) {
  96089. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  96090. return false;
  96091. }
  96092. for(i = 0; i < decoder->private_->seek_table.data.seek_table.num_points; i++) {
  96093. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &xx, FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN))
  96094. return false; /* read_callback_ sets the state for us */
  96095. decoder->private_->seek_table.data.seek_table.points[i].sample_number = xx;
  96096. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &xx, FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN))
  96097. return false; /* read_callback_ sets the state for us */
  96098. decoder->private_->seek_table.data.seek_table.points[i].stream_offset = xx;
  96099. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN))
  96100. return false; /* read_callback_ sets the state for us */
  96101. decoder->private_->seek_table.data.seek_table.points[i].frame_samples = x;
  96102. }
  96103. length -= (decoder->private_->seek_table.data.seek_table.num_points * FLAC__STREAM_METADATA_SEEKPOINT_LENGTH);
  96104. /* if there is a partial point left, skip over it */
  96105. if(length > 0) {
  96106. /*@@@ do a send_error_to_client_() here? there's an argument for either way */
  96107. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, length))
  96108. return false; /* read_callback_ sets the state for us */
  96109. }
  96110. return true;
  96111. }
  96112. FLAC__bool read_metadata_vorbiscomment_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_VorbisComment *obj)
  96113. {
  96114. FLAC__uint32 i;
  96115. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  96116. /* read vendor string */
  96117. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN == 32);
  96118. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->vendor_string.length))
  96119. return false; /* read_callback_ sets the state for us */
  96120. if(obj->vendor_string.length > 0) {
  96121. if(0 == (obj->vendor_string.entry = (FLAC__byte*)safe_malloc_add_2op_(obj->vendor_string.length, /*+*/1))) {
  96122. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  96123. return false;
  96124. }
  96125. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->vendor_string.entry, obj->vendor_string.length))
  96126. return false; /* read_callback_ sets the state for us */
  96127. obj->vendor_string.entry[obj->vendor_string.length] = '\0';
  96128. }
  96129. else
  96130. obj->vendor_string.entry = 0;
  96131. /* read num comments */
  96132. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN == 32);
  96133. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->num_comments))
  96134. return false; /* read_callback_ sets the state for us */
  96135. /* read comments */
  96136. if(obj->num_comments > 0) {
  96137. if(0 == (obj->comments = (FLAC__StreamMetadata_VorbisComment_Entry*)safe_malloc_mul_2op_(obj->num_comments, /*times*/sizeof(FLAC__StreamMetadata_VorbisComment_Entry)))) {
  96138. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  96139. return false;
  96140. }
  96141. for(i = 0; i < obj->num_comments; i++) {
  96142. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN == 32);
  96143. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->comments[i].length))
  96144. return false; /* read_callback_ sets the state for us */
  96145. if(obj->comments[i].length > 0) {
  96146. if(0 == (obj->comments[i].entry = (FLAC__byte*)safe_malloc_add_2op_(obj->comments[i].length, /*+*/1))) {
  96147. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  96148. return false;
  96149. }
  96150. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->comments[i].entry, obj->comments[i].length))
  96151. return false; /* read_callback_ sets the state for us */
  96152. obj->comments[i].entry[obj->comments[i].length] = '\0';
  96153. }
  96154. else
  96155. obj->comments[i].entry = 0;
  96156. }
  96157. }
  96158. else {
  96159. obj->comments = 0;
  96160. }
  96161. return true;
  96162. }
  96163. FLAC__bool read_metadata_cuesheet_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_CueSheet *obj)
  96164. {
  96165. FLAC__uint32 i, j, x;
  96166. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  96167. memset(obj, 0, sizeof(FLAC__StreamMetadata_CueSheet));
  96168. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN % 8 == 0);
  96169. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, (FLAC__byte*)obj->media_catalog_number, FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN/8))
  96170. return false; /* read_callback_ sets the state for us */
  96171. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &obj->lead_in, FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN))
  96172. return false; /* read_callback_ sets the state for us */
  96173. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN))
  96174. return false; /* read_callback_ sets the state for us */
  96175. obj->is_cd = x? true : false;
  96176. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN))
  96177. return false; /* read_callback_ sets the state for us */
  96178. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN))
  96179. return false; /* read_callback_ sets the state for us */
  96180. obj->num_tracks = x;
  96181. if(obj->num_tracks > 0) {
  96182. if(0 == (obj->tracks = (FLAC__StreamMetadata_CueSheet_Track*)safe_calloc_(obj->num_tracks, sizeof(FLAC__StreamMetadata_CueSheet_Track)))) {
  96183. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  96184. return false;
  96185. }
  96186. for(i = 0; i < obj->num_tracks; i++) {
  96187. FLAC__StreamMetadata_CueSheet_Track *track = &obj->tracks[i];
  96188. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &track->offset, FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN))
  96189. return false; /* read_callback_ sets the state for us */
  96190. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN))
  96191. return false; /* read_callback_ sets the state for us */
  96192. track->number = (FLAC__byte)x;
  96193. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN % 8 == 0);
  96194. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, (FLAC__byte*)track->isrc, FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN/8))
  96195. return false; /* read_callback_ sets the state for us */
  96196. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN))
  96197. return false; /* read_callback_ sets the state for us */
  96198. track->type = x;
  96199. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN))
  96200. return false; /* read_callback_ sets the state for us */
  96201. track->pre_emphasis = x;
  96202. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN))
  96203. return false; /* read_callback_ sets the state for us */
  96204. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN))
  96205. return false; /* read_callback_ sets the state for us */
  96206. track->num_indices = (FLAC__byte)x;
  96207. if(track->num_indices > 0) {
  96208. if(0 == (track->indices = (FLAC__StreamMetadata_CueSheet_Index*)safe_calloc_(track->num_indices, sizeof(FLAC__StreamMetadata_CueSheet_Index)))) {
  96209. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  96210. return false;
  96211. }
  96212. for(j = 0; j < track->num_indices; j++) {
  96213. FLAC__StreamMetadata_CueSheet_Index *index = &track->indices[j];
  96214. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &index->offset, FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN))
  96215. return false; /* read_callback_ sets the state for us */
  96216. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN))
  96217. return false; /* read_callback_ sets the state for us */
  96218. index->number = (FLAC__byte)x;
  96219. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN))
  96220. return false; /* read_callback_ sets the state for us */
  96221. }
  96222. }
  96223. }
  96224. }
  96225. return true;
  96226. }
  96227. FLAC__bool read_metadata_picture_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_Picture *obj)
  96228. {
  96229. FLAC__uint32 x;
  96230. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  96231. /* read type */
  96232. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_TYPE_LEN))
  96233. return false; /* read_callback_ sets the state for us */
  96234. obj->type = (FLAC__StreamMetadata_Picture_Type) x;
  96235. /* read MIME type */
  96236. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN))
  96237. return false; /* read_callback_ sets the state for us */
  96238. if(0 == (obj->mime_type = (char*)safe_malloc_add_2op_(x, /*+*/1))) {
  96239. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  96240. return false;
  96241. }
  96242. if(x > 0) {
  96243. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, (FLAC__byte*)obj->mime_type, x))
  96244. return false; /* read_callback_ sets the state for us */
  96245. }
  96246. obj->mime_type[x] = '\0';
  96247. /* read description */
  96248. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN))
  96249. return false; /* read_callback_ sets the state for us */
  96250. if(0 == (obj->description = (FLAC__byte*)safe_malloc_add_2op_(x, /*+*/1))) {
  96251. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  96252. return false;
  96253. }
  96254. if(x > 0) {
  96255. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->description, x))
  96256. return false; /* read_callback_ sets the state for us */
  96257. }
  96258. obj->description[x] = '\0';
  96259. /* read width */
  96260. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->width, FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN))
  96261. return false; /* read_callback_ sets the state for us */
  96262. /* read height */
  96263. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->height, FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN))
  96264. return false; /* read_callback_ sets the state for us */
  96265. /* read depth */
  96266. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->depth, FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN))
  96267. return false; /* read_callback_ sets the state for us */
  96268. /* read colors */
  96269. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->colors, FLAC__STREAM_METADATA_PICTURE_COLORS_LEN))
  96270. return false; /* read_callback_ sets the state for us */
  96271. /* read data */
  96272. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &(obj->data_length), FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN))
  96273. return false; /* read_callback_ sets the state for us */
  96274. if(0 == (obj->data = (FLAC__byte*)safe_malloc_(obj->data_length))) {
  96275. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  96276. return false;
  96277. }
  96278. if(obj->data_length > 0) {
  96279. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->data, obj->data_length))
  96280. return false; /* read_callback_ sets the state for us */
  96281. }
  96282. return true;
  96283. }
  96284. FLAC__bool skip_id3v2_tag_(FLAC__StreamDecoder *decoder)
  96285. {
  96286. FLAC__uint32 x;
  96287. unsigned i, skip;
  96288. /* skip the version and flags bytes */
  96289. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 24))
  96290. return false; /* read_callback_ sets the state for us */
  96291. /* get the size (in bytes) to skip */
  96292. skip = 0;
  96293. for(i = 0; i < 4; i++) {
  96294. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  96295. return false; /* read_callback_ sets the state for us */
  96296. skip <<= 7;
  96297. skip |= (x & 0x7f);
  96298. }
  96299. /* skip the rest of the tag */
  96300. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, skip))
  96301. return false; /* read_callback_ sets the state for us */
  96302. return true;
  96303. }
  96304. FLAC__bool frame_sync_(FLAC__StreamDecoder *decoder)
  96305. {
  96306. FLAC__uint32 x;
  96307. FLAC__bool first = true;
  96308. /* If we know the total number of samples in the stream, stop if we've read that many. */
  96309. /* This will stop us, for example, from wasting time trying to sync on an ID3V1 tag. */
  96310. if(FLAC__stream_decoder_get_total_samples(decoder) > 0) {
  96311. if(decoder->private_->samples_decoded >= FLAC__stream_decoder_get_total_samples(decoder)) {
  96312. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  96313. return true;
  96314. }
  96315. }
  96316. /* make sure we're byte aligned */
  96317. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input)) {
  96318. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__bitreader_bits_left_for_byte_alignment(decoder->private_->input)))
  96319. return false; /* read_callback_ sets the state for us */
  96320. }
  96321. while(1) {
  96322. if(decoder->private_->cached) {
  96323. x = (FLAC__uint32)decoder->private_->lookahead;
  96324. decoder->private_->cached = false;
  96325. }
  96326. else {
  96327. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  96328. return false; /* read_callback_ sets the state for us */
  96329. }
  96330. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  96331. decoder->private_->header_warmup[0] = (FLAC__byte)x;
  96332. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  96333. return false; /* read_callback_ sets the state for us */
  96334. /* we have to check if we just read two 0xff's in a row; the second may actually be the beginning of the sync code */
  96335. /* else we have to check if the second byte is the end of a sync code */
  96336. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  96337. decoder->private_->lookahead = (FLAC__byte)x;
  96338. decoder->private_->cached = true;
  96339. }
  96340. else if(x >> 2 == 0x3e) { /* MAGIC NUMBER for the last 6 sync bits */
  96341. decoder->private_->header_warmup[1] = (FLAC__byte)x;
  96342. decoder->protected_->state = FLAC__STREAM_DECODER_READ_FRAME;
  96343. return true;
  96344. }
  96345. }
  96346. if(first) {
  96347. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  96348. first = false;
  96349. }
  96350. }
  96351. return true;
  96352. }
  96353. FLAC__bool read_frame_(FLAC__StreamDecoder *decoder, FLAC__bool *got_a_frame, FLAC__bool do_full_decode)
  96354. {
  96355. unsigned channel;
  96356. unsigned i;
  96357. FLAC__int32 mid, side;
  96358. unsigned frame_crc; /* the one we calculate from the input stream */
  96359. FLAC__uint32 x;
  96360. *got_a_frame = false;
  96361. /* init the CRC */
  96362. frame_crc = 0;
  96363. frame_crc = FLAC__CRC16_UPDATE(decoder->private_->header_warmup[0], frame_crc);
  96364. frame_crc = FLAC__CRC16_UPDATE(decoder->private_->header_warmup[1], frame_crc);
  96365. FLAC__bitreader_reset_read_crc16(decoder->private_->input, (FLAC__uint16)frame_crc);
  96366. if(!read_frame_header_(decoder))
  96367. return false;
  96368. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means we didn't sync on a valid header */
  96369. return true;
  96370. if(!allocate_output_(decoder, decoder->private_->frame.header.blocksize, decoder->private_->frame.header.channels))
  96371. return false;
  96372. for(channel = 0; channel < decoder->private_->frame.header.channels; channel++) {
  96373. /*
  96374. * first figure the correct bits-per-sample of the subframe
  96375. */
  96376. unsigned bps = decoder->private_->frame.header.bits_per_sample;
  96377. switch(decoder->private_->frame.header.channel_assignment) {
  96378. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  96379. /* no adjustment needed */
  96380. break;
  96381. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  96382. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  96383. if(channel == 1)
  96384. bps++;
  96385. break;
  96386. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  96387. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  96388. if(channel == 0)
  96389. bps++;
  96390. break;
  96391. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  96392. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  96393. if(channel == 1)
  96394. bps++;
  96395. break;
  96396. default:
  96397. FLAC__ASSERT(0);
  96398. }
  96399. /*
  96400. * now read it
  96401. */
  96402. if(!read_subframe_(decoder, channel, bps, do_full_decode))
  96403. return false;
  96404. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  96405. return true;
  96406. }
  96407. if(!read_zero_padding_(decoder))
  96408. return false;
  96409. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption (i.e. "zero bits" were not all zeroes) */
  96410. return true;
  96411. /*
  96412. * Read the frame CRC-16 from the footer and check
  96413. */
  96414. frame_crc = FLAC__bitreader_get_read_crc16(decoder->private_->input);
  96415. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__FRAME_FOOTER_CRC_LEN))
  96416. return false; /* read_callback_ sets the state for us */
  96417. if(frame_crc == x) {
  96418. if(do_full_decode) {
  96419. /* Undo any special channel coding */
  96420. switch(decoder->private_->frame.header.channel_assignment) {
  96421. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  96422. /* do nothing */
  96423. break;
  96424. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  96425. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  96426. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  96427. decoder->private_->output[1][i] = decoder->private_->output[0][i] - decoder->private_->output[1][i];
  96428. break;
  96429. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  96430. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  96431. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  96432. decoder->private_->output[0][i] += decoder->private_->output[1][i];
  96433. break;
  96434. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  96435. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  96436. for(i = 0; i < decoder->private_->frame.header.blocksize; i++) {
  96437. #if 1
  96438. mid = decoder->private_->output[0][i];
  96439. side = decoder->private_->output[1][i];
  96440. mid <<= 1;
  96441. mid |= (side & 1); /* i.e. if 'side' is odd... */
  96442. decoder->private_->output[0][i] = (mid + side) >> 1;
  96443. decoder->private_->output[1][i] = (mid - side) >> 1;
  96444. #else
  96445. /* OPT: without 'side' temp variable */
  96446. mid = (decoder->private_->output[0][i] << 1) | (decoder->private_->output[1][i] & 1); /* i.e. if 'side' is odd... */
  96447. decoder->private_->output[0][i] = (mid + decoder->private_->output[1][i]) >> 1;
  96448. decoder->private_->output[1][i] = (mid - decoder->private_->output[1][i]) >> 1;
  96449. #endif
  96450. }
  96451. break;
  96452. default:
  96453. FLAC__ASSERT(0);
  96454. break;
  96455. }
  96456. }
  96457. }
  96458. else {
  96459. /* Bad frame, emit error and zero the output signal */
  96460. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH);
  96461. if(do_full_decode) {
  96462. for(channel = 0; channel < decoder->private_->frame.header.channels; channel++) {
  96463. memset(decoder->private_->output[channel], 0, sizeof(FLAC__int32) * decoder->private_->frame.header.blocksize);
  96464. }
  96465. }
  96466. }
  96467. *got_a_frame = true;
  96468. /* we wait to update fixed_block_size until here, when we're sure we've got a proper frame and hence a correct blocksize */
  96469. if(decoder->private_->next_fixed_block_size)
  96470. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size;
  96471. /* put the latest values into the public section of the decoder instance */
  96472. decoder->protected_->channels = decoder->private_->frame.header.channels;
  96473. decoder->protected_->channel_assignment = decoder->private_->frame.header.channel_assignment;
  96474. decoder->protected_->bits_per_sample = decoder->private_->frame.header.bits_per_sample;
  96475. decoder->protected_->sample_rate = decoder->private_->frame.header.sample_rate;
  96476. decoder->protected_->blocksize = decoder->private_->frame.header.blocksize;
  96477. FLAC__ASSERT(decoder->private_->frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  96478. decoder->private_->samples_decoded = decoder->private_->frame.header.number.sample_number + decoder->private_->frame.header.blocksize;
  96479. /* write it */
  96480. if(do_full_decode) {
  96481. if(write_audio_frame_to_client_(decoder, &decoder->private_->frame, (const FLAC__int32 * const *)decoder->private_->output) != FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE)
  96482. return false;
  96483. }
  96484. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  96485. return true;
  96486. }
  96487. FLAC__bool read_frame_header_(FLAC__StreamDecoder *decoder)
  96488. {
  96489. FLAC__uint32 x;
  96490. FLAC__uint64 xx;
  96491. unsigned i, blocksize_hint = 0, sample_rate_hint = 0;
  96492. FLAC__byte crc8, raw_header[16]; /* MAGIC NUMBER based on the maximum frame header size, including CRC */
  96493. unsigned raw_header_len;
  96494. FLAC__bool is_unparseable = false;
  96495. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  96496. /* init the raw header with the saved bits from synchronization */
  96497. raw_header[0] = decoder->private_->header_warmup[0];
  96498. raw_header[1] = decoder->private_->header_warmup[1];
  96499. raw_header_len = 2;
  96500. /* check to make sure that reserved bit is 0 */
  96501. if(raw_header[1] & 0x02) /* MAGIC NUMBER */
  96502. is_unparseable = true;
  96503. /*
  96504. * Note that along the way as we read the header, we look for a sync
  96505. * code inside. If we find one it would indicate that our original
  96506. * sync was bad since there cannot be a sync code in a valid header.
  96507. *
  96508. * Three kinds of things can go wrong when reading the frame header:
  96509. * 1) We may have sync'ed incorrectly and not landed on a frame header.
  96510. * If we don't find a sync code, it can end up looking like we read
  96511. * a valid but unparseable header, until getting to the frame header
  96512. * CRC. Even then we could get a false positive on the CRC.
  96513. * 2) We may have sync'ed correctly but on an unparseable frame (from a
  96514. * future encoder).
  96515. * 3) We may be on a damaged frame which appears valid but unparseable.
  96516. *
  96517. * For all these reasons, we try and read a complete frame header as
  96518. * long as it seems valid, even if unparseable, up until the frame
  96519. * header CRC.
  96520. */
  96521. /*
  96522. * read in the raw header as bytes so we can CRC it, and parse it on the way
  96523. */
  96524. for(i = 0; i < 2; i++) {
  96525. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  96526. return false; /* read_callback_ sets the state for us */
  96527. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  96528. /* if we get here it means our original sync was erroneous since the sync code cannot appear in the header */
  96529. decoder->private_->lookahead = (FLAC__byte)x;
  96530. decoder->private_->cached = true;
  96531. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  96532. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  96533. return true;
  96534. }
  96535. raw_header[raw_header_len++] = (FLAC__byte)x;
  96536. }
  96537. switch(x = raw_header[2] >> 4) {
  96538. case 0:
  96539. is_unparseable = true;
  96540. break;
  96541. case 1:
  96542. decoder->private_->frame.header.blocksize = 192;
  96543. break;
  96544. case 2:
  96545. case 3:
  96546. case 4:
  96547. case 5:
  96548. decoder->private_->frame.header.blocksize = 576 << (x-2);
  96549. break;
  96550. case 6:
  96551. case 7:
  96552. blocksize_hint = x;
  96553. break;
  96554. case 8:
  96555. case 9:
  96556. case 10:
  96557. case 11:
  96558. case 12:
  96559. case 13:
  96560. case 14:
  96561. case 15:
  96562. decoder->private_->frame.header.blocksize = 256 << (x-8);
  96563. break;
  96564. default:
  96565. FLAC__ASSERT(0);
  96566. break;
  96567. }
  96568. switch(x = raw_header[2] & 0x0f) {
  96569. case 0:
  96570. if(decoder->private_->has_stream_info)
  96571. decoder->private_->frame.header.sample_rate = decoder->private_->stream_info.data.stream_info.sample_rate;
  96572. else
  96573. is_unparseable = true;
  96574. break;
  96575. case 1:
  96576. decoder->private_->frame.header.sample_rate = 88200;
  96577. break;
  96578. case 2:
  96579. decoder->private_->frame.header.sample_rate = 176400;
  96580. break;
  96581. case 3:
  96582. decoder->private_->frame.header.sample_rate = 192000;
  96583. break;
  96584. case 4:
  96585. decoder->private_->frame.header.sample_rate = 8000;
  96586. break;
  96587. case 5:
  96588. decoder->private_->frame.header.sample_rate = 16000;
  96589. break;
  96590. case 6:
  96591. decoder->private_->frame.header.sample_rate = 22050;
  96592. break;
  96593. case 7:
  96594. decoder->private_->frame.header.sample_rate = 24000;
  96595. break;
  96596. case 8:
  96597. decoder->private_->frame.header.sample_rate = 32000;
  96598. break;
  96599. case 9:
  96600. decoder->private_->frame.header.sample_rate = 44100;
  96601. break;
  96602. case 10:
  96603. decoder->private_->frame.header.sample_rate = 48000;
  96604. break;
  96605. case 11:
  96606. decoder->private_->frame.header.sample_rate = 96000;
  96607. break;
  96608. case 12:
  96609. case 13:
  96610. case 14:
  96611. sample_rate_hint = x;
  96612. break;
  96613. case 15:
  96614. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  96615. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  96616. return true;
  96617. default:
  96618. FLAC__ASSERT(0);
  96619. }
  96620. x = (unsigned)(raw_header[3] >> 4);
  96621. if(x & 8) {
  96622. decoder->private_->frame.header.channels = 2;
  96623. switch(x & 7) {
  96624. case 0:
  96625. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE;
  96626. break;
  96627. case 1:
  96628. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE;
  96629. break;
  96630. case 2:
  96631. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_MID_SIDE;
  96632. break;
  96633. default:
  96634. is_unparseable = true;
  96635. break;
  96636. }
  96637. }
  96638. else {
  96639. decoder->private_->frame.header.channels = (unsigned)x + 1;
  96640. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT;
  96641. }
  96642. switch(x = (unsigned)(raw_header[3] & 0x0e) >> 1) {
  96643. case 0:
  96644. if(decoder->private_->has_stream_info)
  96645. decoder->private_->frame.header.bits_per_sample = decoder->private_->stream_info.data.stream_info.bits_per_sample;
  96646. else
  96647. is_unparseable = true;
  96648. break;
  96649. case 1:
  96650. decoder->private_->frame.header.bits_per_sample = 8;
  96651. break;
  96652. case 2:
  96653. decoder->private_->frame.header.bits_per_sample = 12;
  96654. break;
  96655. case 4:
  96656. decoder->private_->frame.header.bits_per_sample = 16;
  96657. break;
  96658. case 5:
  96659. decoder->private_->frame.header.bits_per_sample = 20;
  96660. break;
  96661. case 6:
  96662. decoder->private_->frame.header.bits_per_sample = 24;
  96663. break;
  96664. case 3:
  96665. case 7:
  96666. is_unparseable = true;
  96667. break;
  96668. default:
  96669. FLAC__ASSERT(0);
  96670. break;
  96671. }
  96672. /* check to make sure that reserved bit is 0 */
  96673. if(raw_header[3] & 0x01) /* MAGIC NUMBER */
  96674. is_unparseable = true;
  96675. /* read the frame's starting sample number (or frame number as the case may be) */
  96676. if(
  96677. raw_header[1] & 0x01 ||
  96678. /*@@@ this clause is a concession to the old way of doing variable blocksize; the only known implementation is flake and can probably be removed without inconveniencing anyone */
  96679. (decoder->private_->has_stream_info && decoder->private_->stream_info.data.stream_info.min_blocksize != decoder->private_->stream_info.data.stream_info.max_blocksize)
  96680. ) { /* variable blocksize */
  96681. if(!FLAC__bitreader_read_utf8_uint64(decoder->private_->input, &xx, raw_header, &raw_header_len))
  96682. return false; /* read_callback_ sets the state for us */
  96683. if(xx == FLAC__U64L(0xffffffffffffffff)) { /* i.e. non-UTF8 code... */
  96684. decoder->private_->lookahead = raw_header[raw_header_len-1]; /* back up as much as we can */
  96685. decoder->private_->cached = true;
  96686. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  96687. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  96688. return true;
  96689. }
  96690. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER;
  96691. decoder->private_->frame.header.number.sample_number = xx;
  96692. }
  96693. else { /* fixed blocksize */
  96694. if(!FLAC__bitreader_read_utf8_uint32(decoder->private_->input, &x, raw_header, &raw_header_len))
  96695. return false; /* read_callback_ sets the state for us */
  96696. if(x == 0xffffffff) { /* i.e. non-UTF8 code... */
  96697. decoder->private_->lookahead = raw_header[raw_header_len-1]; /* back up as much as we can */
  96698. decoder->private_->cached = true;
  96699. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  96700. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  96701. return true;
  96702. }
  96703. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER;
  96704. decoder->private_->frame.header.number.frame_number = x;
  96705. }
  96706. if(blocksize_hint) {
  96707. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  96708. return false; /* read_callback_ sets the state for us */
  96709. raw_header[raw_header_len++] = (FLAC__byte)x;
  96710. if(blocksize_hint == 7) {
  96711. FLAC__uint32 _x;
  96712. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &_x, 8))
  96713. return false; /* read_callback_ sets the state for us */
  96714. raw_header[raw_header_len++] = (FLAC__byte)_x;
  96715. x = (x << 8) | _x;
  96716. }
  96717. decoder->private_->frame.header.blocksize = x+1;
  96718. }
  96719. if(sample_rate_hint) {
  96720. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  96721. return false; /* read_callback_ sets the state for us */
  96722. raw_header[raw_header_len++] = (FLAC__byte)x;
  96723. if(sample_rate_hint != 12) {
  96724. FLAC__uint32 _x;
  96725. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &_x, 8))
  96726. return false; /* read_callback_ sets the state for us */
  96727. raw_header[raw_header_len++] = (FLAC__byte)_x;
  96728. x = (x << 8) | _x;
  96729. }
  96730. if(sample_rate_hint == 12)
  96731. decoder->private_->frame.header.sample_rate = x*1000;
  96732. else if(sample_rate_hint == 13)
  96733. decoder->private_->frame.header.sample_rate = x;
  96734. else
  96735. decoder->private_->frame.header.sample_rate = x*10;
  96736. }
  96737. /* read the CRC-8 byte */
  96738. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  96739. return false; /* read_callback_ sets the state for us */
  96740. crc8 = (FLAC__byte)x;
  96741. if(FLAC__crc8(raw_header, raw_header_len) != crc8) {
  96742. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  96743. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  96744. return true;
  96745. }
  96746. /* calculate the sample number from the frame number if needed */
  96747. decoder->private_->next_fixed_block_size = 0;
  96748. if(decoder->private_->frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER) {
  96749. x = decoder->private_->frame.header.number.frame_number;
  96750. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER;
  96751. if(decoder->private_->fixed_block_size)
  96752. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->fixed_block_size * (FLAC__uint64)x;
  96753. else if(decoder->private_->has_stream_info) {
  96754. if(decoder->private_->stream_info.data.stream_info.min_blocksize == decoder->private_->stream_info.data.stream_info.max_blocksize) {
  96755. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->stream_info.data.stream_info.min_blocksize * (FLAC__uint64)x;
  96756. decoder->private_->next_fixed_block_size = decoder->private_->stream_info.data.stream_info.max_blocksize;
  96757. }
  96758. else
  96759. is_unparseable = true;
  96760. }
  96761. else if(x == 0) {
  96762. decoder->private_->frame.header.number.sample_number = 0;
  96763. decoder->private_->next_fixed_block_size = decoder->private_->frame.header.blocksize;
  96764. }
  96765. else {
  96766. /* can only get here if the stream has invalid frame numbering and no STREAMINFO, so assume it's not the last (possibly short) frame */
  96767. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->frame.header.blocksize * (FLAC__uint64)x;
  96768. }
  96769. }
  96770. if(is_unparseable) {
  96771. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  96772. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  96773. return true;
  96774. }
  96775. return true;
  96776. }
  96777. FLAC__bool read_subframe_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  96778. {
  96779. FLAC__uint32 x;
  96780. FLAC__bool wasted_bits;
  96781. unsigned i;
  96782. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8)) /* MAGIC NUMBER */
  96783. return false; /* read_callback_ sets the state for us */
  96784. wasted_bits = (x & 1);
  96785. x &= 0xfe;
  96786. if(wasted_bits) {
  96787. unsigned u;
  96788. if(!FLAC__bitreader_read_unary_unsigned(decoder->private_->input, &u))
  96789. return false; /* read_callback_ sets the state for us */
  96790. decoder->private_->frame.subframes[channel].wasted_bits = u+1;
  96791. bps -= decoder->private_->frame.subframes[channel].wasted_bits;
  96792. }
  96793. else
  96794. decoder->private_->frame.subframes[channel].wasted_bits = 0;
  96795. /*
  96796. * Lots of magic numbers here
  96797. */
  96798. if(x & 0x80) {
  96799. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  96800. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  96801. return true;
  96802. }
  96803. else if(x == 0) {
  96804. if(!read_subframe_constant_(decoder, channel, bps, do_full_decode))
  96805. return false;
  96806. }
  96807. else if(x == 2) {
  96808. if(!read_subframe_verbatim_(decoder, channel, bps, do_full_decode))
  96809. return false;
  96810. }
  96811. else if(x < 16) {
  96812. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  96813. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  96814. return true;
  96815. }
  96816. else if(x <= 24) {
  96817. if(!read_subframe_fixed_(decoder, channel, bps, (x>>1)&7, do_full_decode))
  96818. return false;
  96819. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  96820. return true;
  96821. }
  96822. else if(x < 64) {
  96823. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  96824. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  96825. return true;
  96826. }
  96827. else {
  96828. if(!read_subframe_lpc_(decoder, channel, bps, ((x>>1)&31)+1, do_full_decode))
  96829. return false;
  96830. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  96831. return true;
  96832. }
  96833. if(wasted_bits && do_full_decode) {
  96834. x = decoder->private_->frame.subframes[channel].wasted_bits;
  96835. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  96836. decoder->private_->output[channel][i] <<= x;
  96837. }
  96838. return true;
  96839. }
  96840. FLAC__bool read_subframe_constant_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  96841. {
  96842. FLAC__Subframe_Constant *subframe = &decoder->private_->frame.subframes[channel].data.constant;
  96843. FLAC__int32 x;
  96844. unsigned i;
  96845. FLAC__int32 *output = decoder->private_->output[channel];
  96846. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_CONSTANT;
  96847. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &x, bps))
  96848. return false; /* read_callback_ sets the state for us */
  96849. subframe->value = x;
  96850. /* decode the subframe */
  96851. if(do_full_decode) {
  96852. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  96853. output[i] = x;
  96854. }
  96855. return true;
  96856. }
  96857. FLAC__bool read_subframe_fixed_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode)
  96858. {
  96859. FLAC__Subframe_Fixed *subframe = &decoder->private_->frame.subframes[channel].data.fixed;
  96860. FLAC__int32 i32;
  96861. FLAC__uint32 u32;
  96862. unsigned u;
  96863. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_FIXED;
  96864. subframe->residual = decoder->private_->residual[channel];
  96865. subframe->order = order;
  96866. /* read warm-up samples */
  96867. for(u = 0; u < order; u++) {
  96868. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, bps))
  96869. return false; /* read_callback_ sets the state for us */
  96870. subframe->warmup[u] = i32;
  96871. }
  96872. /* read entropy coding method info */
  96873. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  96874. return false; /* read_callback_ sets the state for us */
  96875. subframe->entropy_coding_method.type = (FLAC__EntropyCodingMethodType)u32;
  96876. switch(subframe->entropy_coding_method.type) {
  96877. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  96878. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  96879. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  96880. return false; /* read_callback_ sets the state for us */
  96881. subframe->entropy_coding_method.data.partitioned_rice.order = u32;
  96882. subframe->entropy_coding_method.data.partitioned_rice.contents = &decoder->private_->partitioned_rice_contents[channel];
  96883. break;
  96884. default:
  96885. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  96886. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  96887. return true;
  96888. }
  96889. /* read residual */
  96890. switch(subframe->entropy_coding_method.type) {
  96891. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  96892. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  96893. if(!read_residual_partitioned_rice_(decoder, order, subframe->entropy_coding_method.data.partitioned_rice.order, &decoder->private_->partitioned_rice_contents[channel], decoder->private_->residual[channel], /*is_extended=*/subframe->entropy_coding_method.type == FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2))
  96894. return false;
  96895. break;
  96896. default:
  96897. FLAC__ASSERT(0);
  96898. }
  96899. /* decode the subframe */
  96900. if(do_full_decode) {
  96901. memcpy(decoder->private_->output[channel], subframe->warmup, sizeof(FLAC__int32) * order);
  96902. FLAC__fixed_restore_signal(decoder->private_->residual[channel], decoder->private_->frame.header.blocksize-order, order, decoder->private_->output[channel]+order);
  96903. }
  96904. return true;
  96905. }
  96906. FLAC__bool read_subframe_lpc_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode)
  96907. {
  96908. FLAC__Subframe_LPC *subframe = &decoder->private_->frame.subframes[channel].data.lpc;
  96909. FLAC__int32 i32;
  96910. FLAC__uint32 u32;
  96911. unsigned u;
  96912. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_LPC;
  96913. subframe->residual = decoder->private_->residual[channel];
  96914. subframe->order = order;
  96915. /* read warm-up samples */
  96916. for(u = 0; u < order; u++) {
  96917. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, bps))
  96918. return false; /* read_callback_ sets the state for us */
  96919. subframe->warmup[u] = i32;
  96920. }
  96921. /* read qlp coeff precision */
  96922. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN))
  96923. return false; /* read_callback_ sets the state for us */
  96924. if(u32 == (1u << FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN) - 1) {
  96925. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  96926. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  96927. return true;
  96928. }
  96929. subframe->qlp_coeff_precision = u32+1;
  96930. /* read qlp shift */
  96931. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN))
  96932. return false; /* read_callback_ sets the state for us */
  96933. subframe->quantization_level = i32;
  96934. /* read quantized lp coefficiencts */
  96935. for(u = 0; u < order; u++) {
  96936. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, subframe->qlp_coeff_precision))
  96937. return false; /* read_callback_ sets the state for us */
  96938. subframe->qlp_coeff[u] = i32;
  96939. }
  96940. /* read entropy coding method info */
  96941. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  96942. return false; /* read_callback_ sets the state for us */
  96943. subframe->entropy_coding_method.type = (FLAC__EntropyCodingMethodType)u32;
  96944. switch(subframe->entropy_coding_method.type) {
  96945. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  96946. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  96947. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  96948. return false; /* read_callback_ sets the state for us */
  96949. subframe->entropy_coding_method.data.partitioned_rice.order = u32;
  96950. subframe->entropy_coding_method.data.partitioned_rice.contents = &decoder->private_->partitioned_rice_contents[channel];
  96951. break;
  96952. default:
  96953. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  96954. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  96955. return true;
  96956. }
  96957. /* read residual */
  96958. switch(subframe->entropy_coding_method.type) {
  96959. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  96960. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  96961. if(!read_residual_partitioned_rice_(decoder, order, subframe->entropy_coding_method.data.partitioned_rice.order, &decoder->private_->partitioned_rice_contents[channel], decoder->private_->residual[channel], /*is_extended=*/subframe->entropy_coding_method.type == FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2))
  96962. return false;
  96963. break;
  96964. default:
  96965. FLAC__ASSERT(0);
  96966. }
  96967. /* decode the subframe */
  96968. if(do_full_decode) {
  96969. memcpy(decoder->private_->output[channel], subframe->warmup, sizeof(FLAC__int32) * order);
  96970. /*@@@@@@ technically not pessimistic enough, should be more like
  96971. if( (FLAC__uint64)order * ((((FLAC__uint64)1)<<bps)-1) * ((1<<subframe->qlp_coeff_precision)-1) < (((FLAC__uint64)-1) << 32) )
  96972. */
  96973. if(bps + subframe->qlp_coeff_precision + FLAC__bitmath_ilog2(order) <= 32)
  96974. if(bps <= 16 && subframe->qlp_coeff_precision <= 16) {
  96975. if(order <= 8)
  96976. decoder->private_->local_lpc_restore_signal_16bit_order8(decoder->private_->residual[channel], decoder->private_->frame.header.blocksize-order, subframe->qlp_coeff, order, subframe->quantization_level, decoder->private_->output[channel]+order);
  96977. else
  96978. decoder->private_->local_lpc_restore_signal_16bit(decoder->private_->residual[channel], decoder->private_->frame.header.blocksize-order, subframe->qlp_coeff, order, subframe->quantization_level, decoder->private_->output[channel]+order);
  96979. }
  96980. else
  96981. decoder->private_->local_lpc_restore_signal(decoder->private_->residual[channel], decoder->private_->frame.header.blocksize-order, subframe->qlp_coeff, order, subframe->quantization_level, decoder->private_->output[channel]+order);
  96982. else
  96983. decoder->private_->local_lpc_restore_signal_64bit(decoder->private_->residual[channel], decoder->private_->frame.header.blocksize-order, subframe->qlp_coeff, order, subframe->quantization_level, decoder->private_->output[channel]+order);
  96984. }
  96985. return true;
  96986. }
  96987. FLAC__bool read_subframe_verbatim_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  96988. {
  96989. FLAC__Subframe_Verbatim *subframe = &decoder->private_->frame.subframes[channel].data.verbatim;
  96990. FLAC__int32 x, *residual = decoder->private_->residual[channel];
  96991. unsigned i;
  96992. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_VERBATIM;
  96993. subframe->data = residual;
  96994. for(i = 0; i < decoder->private_->frame.header.blocksize; i++) {
  96995. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &x, bps))
  96996. return false; /* read_callback_ sets the state for us */
  96997. residual[i] = x;
  96998. }
  96999. /* decode the subframe */
  97000. if(do_full_decode)
  97001. memcpy(decoder->private_->output[channel], subframe->data, sizeof(FLAC__int32) * decoder->private_->frame.header.blocksize);
  97002. return true;
  97003. }
  97004. FLAC__bool read_residual_partitioned_rice_(FLAC__StreamDecoder *decoder, unsigned predictor_order, unsigned partition_order, FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents, FLAC__int32 *residual, FLAC__bool is_extended)
  97005. {
  97006. FLAC__uint32 rice_parameter;
  97007. int i;
  97008. unsigned partition, sample, u;
  97009. const unsigned partitions = 1u << partition_order;
  97010. const unsigned partition_samples = partition_order > 0? decoder->private_->frame.header.blocksize >> partition_order : decoder->private_->frame.header.blocksize - predictor_order;
  97011. const unsigned plen = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN;
  97012. const unsigned pesc = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  97013. /* sanity checks */
  97014. if(partition_order == 0) {
  97015. if(decoder->private_->frame.header.blocksize < predictor_order) {
  97016. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  97017. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  97018. return true;
  97019. }
  97020. }
  97021. else {
  97022. if(partition_samples < predictor_order) {
  97023. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  97024. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  97025. return true;
  97026. }
  97027. }
  97028. if(!FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(partitioned_rice_contents, max(6, partition_order))) {
  97029. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  97030. return false;
  97031. }
  97032. sample = 0;
  97033. for(partition = 0; partition < partitions; partition++) {
  97034. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &rice_parameter, plen))
  97035. return false; /* read_callback_ sets the state for us */
  97036. partitioned_rice_contents->parameters[partition] = rice_parameter;
  97037. if(rice_parameter < pesc) {
  97038. partitioned_rice_contents->raw_bits[partition] = 0;
  97039. u = (partition_order == 0 || partition > 0)? partition_samples : partition_samples - predictor_order;
  97040. if(!decoder->private_->local_bitreader_read_rice_signed_block(decoder->private_->input, (int*) residual + sample, u, rice_parameter))
  97041. return false; /* read_callback_ sets the state for us */
  97042. sample += u;
  97043. }
  97044. else {
  97045. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  97046. return false; /* read_callback_ sets the state for us */
  97047. partitioned_rice_contents->raw_bits[partition] = rice_parameter;
  97048. for(u = (partition_order == 0 || partition > 0)? 0 : predictor_order; u < partition_samples; u++, sample++) {
  97049. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, (FLAC__int32*) &i, rice_parameter))
  97050. return false; /* read_callback_ sets the state for us */
  97051. residual[sample] = i;
  97052. }
  97053. }
  97054. }
  97055. return true;
  97056. }
  97057. FLAC__bool read_zero_padding_(FLAC__StreamDecoder *decoder)
  97058. {
  97059. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input)) {
  97060. FLAC__uint32 zero = 0;
  97061. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &zero, FLAC__bitreader_bits_left_for_byte_alignment(decoder->private_->input)))
  97062. return false; /* read_callback_ sets the state for us */
  97063. if(zero != 0) {
  97064. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  97065. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  97066. }
  97067. }
  97068. return true;
  97069. }
  97070. FLAC__bool read_callback_(FLAC__byte buffer[], size_t *bytes, void *client_data)
  97071. {
  97072. FLAC__StreamDecoder *decoder = (FLAC__StreamDecoder *)client_data;
  97073. if(
  97074. #if FLAC__HAS_OGG
  97075. /* see [1] HACK NOTE below for why we don't call the eof_callback when decoding Ogg FLAC */
  97076. !decoder->private_->is_ogg &&
  97077. #endif
  97078. decoder->private_->eof_callback && decoder->private_->eof_callback(decoder, decoder->private_->client_data)
  97079. ) {
  97080. *bytes = 0;
  97081. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  97082. return false;
  97083. }
  97084. else if(*bytes > 0) {
  97085. /* While seeking, it is possible for our seek to land in the
  97086. * middle of audio data that looks exactly like a frame header
  97087. * from a future version of an encoder. When that happens, our
  97088. * error callback will get an
  97089. * FLAC__STREAM_DECODER_UNPARSEABLE_STREAM and increment its
  97090. * unparseable_frame_count. But there is a remote possibility
  97091. * that it is properly synced at such a "future-codec frame",
  97092. * so to make sure, we wait to see many "unparseable" errors in
  97093. * a row before bailing out.
  97094. */
  97095. if(decoder->private_->is_seeking && decoder->private_->unparseable_frame_count > 20) {
  97096. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  97097. return false;
  97098. }
  97099. else {
  97100. const FLAC__StreamDecoderReadStatus status =
  97101. #if FLAC__HAS_OGG
  97102. decoder->private_->is_ogg?
  97103. read_callback_ogg_aspect_(decoder, buffer, bytes) :
  97104. #endif
  97105. decoder->private_->read_callback(decoder, buffer, bytes, decoder->private_->client_data)
  97106. ;
  97107. if(status == FLAC__STREAM_DECODER_READ_STATUS_ABORT) {
  97108. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  97109. return false;
  97110. }
  97111. else if(*bytes == 0) {
  97112. if(
  97113. status == FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM ||
  97114. (
  97115. #if FLAC__HAS_OGG
  97116. /* see [1] HACK NOTE below for why we don't call the eof_callback when decoding Ogg FLAC */
  97117. !decoder->private_->is_ogg &&
  97118. #endif
  97119. decoder->private_->eof_callback && decoder->private_->eof_callback(decoder, decoder->private_->client_data)
  97120. )
  97121. ) {
  97122. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  97123. return false;
  97124. }
  97125. else
  97126. return true;
  97127. }
  97128. else
  97129. return true;
  97130. }
  97131. }
  97132. else {
  97133. /* abort to avoid a deadlock */
  97134. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  97135. return false;
  97136. }
  97137. /* [1] @@@ HACK NOTE: The end-of-stream checking has to be hacked around
  97138. * for Ogg FLAC. This is because the ogg decoder aspect can lose sync
  97139. * and at the same time hit the end of the stream (for example, seeking
  97140. * to a point that is after the beginning of the last Ogg page). There
  97141. * is no way to report an Ogg sync loss through the callbacks (see note
  97142. * in read_callback_ogg_aspect_()) so it returns CONTINUE with *bytes==0.
  97143. * So to keep the decoder from stopping at this point we gate the call
  97144. * to the eof_callback and let the Ogg decoder aspect set the
  97145. * end-of-stream state when it is needed.
  97146. */
  97147. }
  97148. #if FLAC__HAS_OGG
  97149. FLAC__StreamDecoderReadStatus read_callback_ogg_aspect_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes)
  97150. {
  97151. switch(FLAC__ogg_decoder_aspect_read_callback_wrapper(&decoder->protected_->ogg_decoder_aspect, buffer, bytes, read_callback_proxy_, decoder, decoder->private_->client_data)) {
  97152. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_OK:
  97153. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  97154. /* we don't really have a way to handle lost sync via read
  97155. * callback so we'll let it pass and let the underlying
  97156. * FLAC decoder catch the error
  97157. */
  97158. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_LOST_SYNC:
  97159. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  97160. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_END_OF_STREAM:
  97161. return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  97162. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_NOT_FLAC:
  97163. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_UNSUPPORTED_MAPPING_VERSION:
  97164. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT:
  97165. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_ERROR:
  97166. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_MEMORY_ALLOCATION_ERROR:
  97167. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  97168. default:
  97169. FLAC__ASSERT(0);
  97170. /* double protection */
  97171. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  97172. }
  97173. }
  97174. FLAC__OggDecoderAspectReadStatus read_callback_proxy_(const void *void_decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  97175. {
  97176. FLAC__StreamDecoder *decoder = (FLAC__StreamDecoder*)void_decoder;
  97177. switch(decoder->private_->read_callback(decoder, buffer, bytes, client_data)) {
  97178. case FLAC__STREAM_DECODER_READ_STATUS_CONTINUE:
  97179. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_OK;
  97180. case FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM:
  97181. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_END_OF_STREAM;
  97182. case FLAC__STREAM_DECODER_READ_STATUS_ABORT:
  97183. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT;
  97184. default:
  97185. /* double protection: */
  97186. FLAC__ASSERT(0);
  97187. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT;
  97188. }
  97189. }
  97190. #endif
  97191. FLAC__StreamDecoderWriteStatus write_audio_frame_to_client_(FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[])
  97192. {
  97193. if(decoder->private_->is_seeking) {
  97194. FLAC__uint64 this_frame_sample = frame->header.number.sample_number;
  97195. FLAC__uint64 next_frame_sample = this_frame_sample + (FLAC__uint64)frame->header.blocksize;
  97196. FLAC__uint64 target_sample = decoder->private_->target_sample;
  97197. FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  97198. #if FLAC__HAS_OGG
  97199. decoder->private_->got_a_frame = true;
  97200. #endif
  97201. decoder->private_->last_frame = *frame; /* save the frame */
  97202. if(this_frame_sample <= target_sample && target_sample < next_frame_sample) { /* we hit our target frame */
  97203. unsigned delta = (unsigned)(target_sample - this_frame_sample);
  97204. /* kick out of seek mode */
  97205. decoder->private_->is_seeking = false;
  97206. /* shift out the samples before target_sample */
  97207. if(delta > 0) {
  97208. unsigned channel;
  97209. const FLAC__int32 *newbuffer[FLAC__MAX_CHANNELS];
  97210. for(channel = 0; channel < frame->header.channels; channel++)
  97211. newbuffer[channel] = buffer[channel] + delta;
  97212. decoder->private_->last_frame.header.blocksize -= delta;
  97213. decoder->private_->last_frame.header.number.sample_number += (FLAC__uint64)delta;
  97214. /* write the relevant samples */
  97215. return decoder->private_->write_callback(decoder, &decoder->private_->last_frame, newbuffer, decoder->private_->client_data);
  97216. }
  97217. else {
  97218. /* write the relevant samples */
  97219. return decoder->private_->write_callback(decoder, frame, buffer, decoder->private_->client_data);
  97220. }
  97221. }
  97222. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  97223. }
  97224. /*
  97225. * If we never got STREAMINFO, turn off MD5 checking to save
  97226. * cycles since we don't have a sum to compare to anyway
  97227. */
  97228. if(!decoder->private_->has_stream_info)
  97229. decoder->private_->do_md5_checking = false;
  97230. if(decoder->private_->do_md5_checking) {
  97231. if(!FLAC__MD5Accumulate(&decoder->private_->md5context, buffer, frame->header.channels, frame->header.blocksize, (frame->header.bits_per_sample+7) / 8))
  97232. return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
  97233. }
  97234. return decoder->private_->write_callback(decoder, frame, buffer, decoder->private_->client_data);
  97235. }
  97236. void send_error_to_client_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status)
  97237. {
  97238. if(!decoder->private_->is_seeking)
  97239. decoder->private_->error_callback(decoder, status, decoder->private_->client_data);
  97240. else if(status == FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM)
  97241. decoder->private_->unparseable_frame_count++;
  97242. }
  97243. FLAC__bool seek_to_absolute_sample_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample)
  97244. {
  97245. FLAC__uint64 first_frame_offset = decoder->private_->first_frame_offset, lower_bound, upper_bound, lower_bound_sample, upper_bound_sample, this_frame_sample;
  97246. FLAC__int64 pos = -1;
  97247. int i;
  97248. unsigned approx_bytes_per_frame;
  97249. FLAC__bool first_seek = true;
  97250. const FLAC__uint64 total_samples = FLAC__stream_decoder_get_total_samples(decoder);
  97251. const unsigned min_blocksize = decoder->private_->stream_info.data.stream_info.min_blocksize;
  97252. const unsigned max_blocksize = decoder->private_->stream_info.data.stream_info.max_blocksize;
  97253. const unsigned max_framesize = decoder->private_->stream_info.data.stream_info.max_framesize;
  97254. const unsigned min_framesize = decoder->private_->stream_info.data.stream_info.min_framesize;
  97255. /* take these from the current frame in case they've changed mid-stream */
  97256. unsigned channels = FLAC__stream_decoder_get_channels(decoder);
  97257. unsigned bps = FLAC__stream_decoder_get_bits_per_sample(decoder);
  97258. const FLAC__StreamMetadata_SeekTable *seek_table = decoder->private_->has_seek_table? &decoder->private_->seek_table.data.seek_table : 0;
  97259. /* use values from stream info if we didn't decode a frame */
  97260. if(channels == 0)
  97261. channels = decoder->private_->stream_info.data.stream_info.channels;
  97262. if(bps == 0)
  97263. bps = decoder->private_->stream_info.data.stream_info.bits_per_sample;
  97264. /* we are just guessing here */
  97265. if(max_framesize > 0)
  97266. approx_bytes_per_frame = (max_framesize + min_framesize) / 2 + 1;
  97267. /*
  97268. * Check if it's a known fixed-blocksize stream. Note that though
  97269. * the spec doesn't allow zeroes in the STREAMINFO block, we may
  97270. * never get a STREAMINFO block when decoding so the value of
  97271. * min_blocksize might be zero.
  97272. */
  97273. else if(min_blocksize == max_blocksize && min_blocksize > 0) {
  97274. /* note there are no () around 'bps/8' to keep precision up since it's an integer calulation */
  97275. approx_bytes_per_frame = min_blocksize * channels * bps/8 + 64;
  97276. }
  97277. else
  97278. approx_bytes_per_frame = 4096 * channels * bps/8 + 64;
  97279. /*
  97280. * First, we set an upper and lower bound on where in the
  97281. * stream we will search. For now we assume the worst case
  97282. * scenario, which is our best guess at the beginning of
  97283. * the first frame and end of the stream.
  97284. */
  97285. lower_bound = first_frame_offset;
  97286. lower_bound_sample = 0;
  97287. upper_bound = stream_length;
  97288. upper_bound_sample = total_samples > 0 ? total_samples : target_sample /*estimate it*/;
  97289. /*
  97290. * Now we refine the bounds if we have a seektable with
  97291. * suitable points. Note that according to the spec they
  97292. * must be ordered by ascending sample number.
  97293. *
  97294. * Note: to protect against invalid seek tables we will ignore points
  97295. * that have frame_samples==0 or sample_number>=total_samples
  97296. */
  97297. if(seek_table) {
  97298. FLAC__uint64 new_lower_bound = lower_bound;
  97299. FLAC__uint64 new_upper_bound = upper_bound;
  97300. FLAC__uint64 new_lower_bound_sample = lower_bound_sample;
  97301. FLAC__uint64 new_upper_bound_sample = upper_bound_sample;
  97302. /* find the closest seek point <= target_sample, if it exists */
  97303. for(i = (int)seek_table->num_points - 1; i >= 0; i--) {
  97304. if(
  97305. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  97306. seek_table->points[i].frame_samples > 0 && /* defense against bad seekpoints */
  97307. (total_samples <= 0 || seek_table->points[i].sample_number < total_samples) && /* defense against bad seekpoints */
  97308. seek_table->points[i].sample_number <= target_sample
  97309. )
  97310. break;
  97311. }
  97312. if(i >= 0) { /* i.e. we found a suitable seek point... */
  97313. new_lower_bound = first_frame_offset + seek_table->points[i].stream_offset;
  97314. new_lower_bound_sample = seek_table->points[i].sample_number;
  97315. }
  97316. /* find the closest seek point > target_sample, if it exists */
  97317. for(i = 0; i < (int)seek_table->num_points; i++) {
  97318. if(
  97319. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  97320. seek_table->points[i].frame_samples > 0 && /* defense against bad seekpoints */
  97321. (total_samples <= 0 || seek_table->points[i].sample_number < total_samples) && /* defense against bad seekpoints */
  97322. seek_table->points[i].sample_number > target_sample
  97323. )
  97324. break;
  97325. }
  97326. if(i < (int)seek_table->num_points) { /* i.e. we found a suitable seek point... */
  97327. new_upper_bound = first_frame_offset + seek_table->points[i].stream_offset;
  97328. new_upper_bound_sample = seek_table->points[i].sample_number;
  97329. }
  97330. /* final protection against unsorted seek tables; keep original values if bogus */
  97331. if(new_upper_bound >= new_lower_bound) {
  97332. lower_bound = new_lower_bound;
  97333. upper_bound = new_upper_bound;
  97334. lower_bound_sample = new_lower_bound_sample;
  97335. upper_bound_sample = new_upper_bound_sample;
  97336. }
  97337. }
  97338. FLAC__ASSERT(upper_bound_sample >= lower_bound_sample);
  97339. /* there are 2 insidious ways that the following equality occurs, which
  97340. * we need to fix:
  97341. * 1) total_samples is 0 (unknown) and target_sample is 0
  97342. * 2) total_samples is 0 (unknown) and target_sample happens to be
  97343. * exactly equal to the last seek point in the seek table; this
  97344. * means there is no seek point above it, and upper_bound_samples
  97345. * remains equal to the estimate (of target_samples) we made above
  97346. * in either case it does not hurt to move upper_bound_sample up by 1
  97347. */
  97348. if(upper_bound_sample == lower_bound_sample)
  97349. upper_bound_sample++;
  97350. decoder->private_->target_sample = target_sample;
  97351. while(1) {
  97352. /* check if the bounds are still ok */
  97353. if (lower_bound_sample >= upper_bound_sample || lower_bound > upper_bound) {
  97354. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  97355. return false;
  97356. }
  97357. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97358. #if defined _MSC_VER || defined __MINGW32__
  97359. /* with VC++ you have to spoon feed it the casting */
  97360. pos = (FLAC__int64)lower_bound + (FLAC__int64)((FLAC__double)(FLAC__int64)(target_sample - lower_bound_sample) / (FLAC__double)(FLAC__int64)(upper_bound_sample - lower_bound_sample) * (FLAC__double)(FLAC__int64)(upper_bound - lower_bound)) - approx_bytes_per_frame;
  97361. #else
  97362. pos = (FLAC__int64)lower_bound + (FLAC__int64)((FLAC__double)(target_sample - lower_bound_sample) / (FLAC__double)(upper_bound_sample - lower_bound_sample) * (FLAC__double)(upper_bound - lower_bound)) - approx_bytes_per_frame;
  97363. #endif
  97364. #else
  97365. /* a little less accurate: */
  97366. if(upper_bound - lower_bound < 0xffffffff)
  97367. pos = (FLAC__int64)lower_bound + (FLAC__int64)(((target_sample - lower_bound_sample) * (upper_bound - lower_bound)) / (upper_bound_sample - lower_bound_sample)) - approx_bytes_per_frame;
  97368. else /* @@@ WATCHOUT, ~2TB limit */
  97369. pos = (FLAC__int64)lower_bound + (FLAC__int64)((((target_sample - lower_bound_sample)>>8) * ((upper_bound - lower_bound)>>8)) / ((upper_bound_sample - lower_bound_sample)>>16)) - approx_bytes_per_frame;
  97370. #endif
  97371. if(pos >= (FLAC__int64)upper_bound)
  97372. pos = (FLAC__int64)upper_bound - 1;
  97373. if(pos < (FLAC__int64)lower_bound)
  97374. pos = (FLAC__int64)lower_bound;
  97375. if(decoder->private_->seek_callback(decoder, (FLAC__uint64)pos, decoder->private_->client_data) != FLAC__STREAM_DECODER_SEEK_STATUS_OK) {
  97376. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  97377. return false;
  97378. }
  97379. if(!FLAC__stream_decoder_flush(decoder)) {
  97380. /* above call sets the state for us */
  97381. return false;
  97382. }
  97383. /* Now we need to get a frame. First we need to reset our
  97384. * unparseable_frame_count; if we get too many unparseable
  97385. * frames in a row, the read callback will return
  97386. * FLAC__STREAM_DECODER_READ_STATUS_ABORT, causing
  97387. * FLAC__stream_decoder_process_single() to return false.
  97388. */
  97389. decoder->private_->unparseable_frame_count = 0;
  97390. if(!FLAC__stream_decoder_process_single(decoder)) {
  97391. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  97392. return false;
  97393. }
  97394. /* our write callback will change the state when it gets to the target frame */
  97395. /* actually, we could have got_a_frame if our decoder is at FLAC__STREAM_DECODER_END_OF_STREAM so we need to check for that also */
  97396. #if 0
  97397. /*@@@@@@ used to be the following; not clear if the check for end of stream is needed anymore */
  97398. if(decoder->protected_->state != FLAC__SEEKABLE_STREAM_DECODER_SEEKING && decoder->protected_->state != FLAC__STREAM_DECODER_END_OF_STREAM)
  97399. break;
  97400. #endif
  97401. if(!decoder->private_->is_seeking)
  97402. break;
  97403. FLAC__ASSERT(decoder->private_->last_frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  97404. this_frame_sample = decoder->private_->last_frame.header.number.sample_number;
  97405. if (0 == decoder->private_->samples_decoded || (this_frame_sample + decoder->private_->last_frame.header.blocksize >= upper_bound_sample && !first_seek)) {
  97406. if (pos == (FLAC__int64)lower_bound) {
  97407. /* can't move back any more than the first frame, something is fatally wrong */
  97408. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  97409. return false;
  97410. }
  97411. /* our last move backwards wasn't big enough, try again */
  97412. approx_bytes_per_frame = approx_bytes_per_frame? approx_bytes_per_frame * 2 : 16;
  97413. continue;
  97414. }
  97415. /* allow one seek over upper bound, so we can get a correct upper_bound_sample for streams with unknown total_samples */
  97416. first_seek = false;
  97417. /* make sure we are not seeking in corrupted stream */
  97418. if (this_frame_sample < lower_bound_sample) {
  97419. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  97420. return false;
  97421. }
  97422. /* we need to narrow the search */
  97423. if(target_sample < this_frame_sample) {
  97424. upper_bound_sample = this_frame_sample + decoder->private_->last_frame.header.blocksize;
  97425. /*@@@@@@ what will decode position be if at end of stream? */
  97426. if(!FLAC__stream_decoder_get_decode_position(decoder, &upper_bound)) {
  97427. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  97428. return false;
  97429. }
  97430. approx_bytes_per_frame = (unsigned)(2 * (upper_bound - pos) / 3 + 16);
  97431. }
  97432. else { /* target_sample >= this_frame_sample + this frame's blocksize */
  97433. lower_bound_sample = this_frame_sample + decoder->private_->last_frame.header.blocksize;
  97434. if(!FLAC__stream_decoder_get_decode_position(decoder, &lower_bound)) {
  97435. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  97436. return false;
  97437. }
  97438. approx_bytes_per_frame = (unsigned)(2 * (lower_bound - pos) / 3 + 16);
  97439. }
  97440. }
  97441. return true;
  97442. }
  97443. #if FLAC__HAS_OGG
  97444. FLAC__bool seek_to_absolute_sample_ogg_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample)
  97445. {
  97446. FLAC__uint64 left_pos = 0, right_pos = stream_length;
  97447. FLAC__uint64 left_sample = 0, right_sample = FLAC__stream_decoder_get_total_samples(decoder);
  97448. FLAC__uint64 this_frame_sample = (FLAC__uint64)0 - 1;
  97449. FLAC__uint64 pos = 0; /* only initialized to avoid compiler warning */
  97450. FLAC__bool did_a_seek;
  97451. unsigned iteration = 0;
  97452. /* In the first iterations, we will calculate the target byte position
  97453. * by the distance from the target sample to left_sample and
  97454. * right_sample (let's call it "proportional search"). After that, we
  97455. * will switch to binary search.
  97456. */
  97457. unsigned BINARY_SEARCH_AFTER_ITERATION = 2;
  97458. /* We will switch to a linear search once our current sample is less
  97459. * than this number of samples ahead of the target sample
  97460. */
  97461. static const FLAC__uint64 LINEAR_SEARCH_WITHIN_SAMPLES = FLAC__MAX_BLOCK_SIZE * 2;
  97462. /* If the total number of samples is unknown, use a large value, and
  97463. * force binary search immediately.
  97464. */
  97465. if(right_sample == 0) {
  97466. right_sample = (FLAC__uint64)(-1);
  97467. BINARY_SEARCH_AFTER_ITERATION = 0;
  97468. }
  97469. decoder->private_->target_sample = target_sample;
  97470. for( ; ; iteration++) {
  97471. if (iteration == 0 || this_frame_sample > target_sample || target_sample - this_frame_sample > LINEAR_SEARCH_WITHIN_SAMPLES) {
  97472. if (iteration >= BINARY_SEARCH_AFTER_ITERATION) {
  97473. pos = (right_pos + left_pos) / 2;
  97474. }
  97475. else {
  97476. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97477. #if defined _MSC_VER || defined __MINGW32__
  97478. /* with MSVC you have to spoon feed it the casting */
  97479. pos = (FLAC__uint64)((FLAC__double)(FLAC__int64)(target_sample - left_sample) / (FLAC__double)(FLAC__int64)(right_sample - left_sample) * (FLAC__double)(FLAC__int64)(right_pos - left_pos));
  97480. #else
  97481. pos = (FLAC__uint64)((FLAC__double)(target_sample - left_sample) / (FLAC__double)(right_sample - left_sample) * (FLAC__double)(right_pos - left_pos));
  97482. #endif
  97483. #else
  97484. /* a little less accurate: */
  97485. if ((target_sample-left_sample <= 0xffffffff) && (right_pos-left_pos <= 0xffffffff))
  97486. pos = (FLAC__int64)(((target_sample-left_sample) * (right_pos-left_pos)) / (right_sample-left_sample));
  97487. else /* @@@ WATCHOUT, ~2TB limit */
  97488. pos = (FLAC__int64)((((target_sample-left_sample)>>8) * ((right_pos-left_pos)>>8)) / ((right_sample-left_sample)>>16));
  97489. #endif
  97490. /* @@@ TODO: might want to limit pos to some distance
  97491. * before EOF, to make sure we land before the last frame,
  97492. * thereby getting a this_frame_sample and so having a better
  97493. * estimate.
  97494. */
  97495. }
  97496. /* physical seek */
  97497. if(decoder->private_->seek_callback((FLAC__StreamDecoder*)decoder, (FLAC__uint64)pos, decoder->private_->client_data) != FLAC__STREAM_DECODER_SEEK_STATUS_OK) {
  97498. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  97499. return false;
  97500. }
  97501. if(!FLAC__stream_decoder_flush(decoder)) {
  97502. /* above call sets the state for us */
  97503. return false;
  97504. }
  97505. did_a_seek = true;
  97506. }
  97507. else
  97508. did_a_seek = false;
  97509. decoder->private_->got_a_frame = false;
  97510. if(!FLAC__stream_decoder_process_single(decoder)) {
  97511. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  97512. return false;
  97513. }
  97514. if(!decoder->private_->got_a_frame) {
  97515. if(did_a_seek) {
  97516. /* this can happen if we seek to a point after the last frame; we drop
  97517. * to binary search right away in this case to avoid any wasted
  97518. * iterations of proportional search.
  97519. */
  97520. right_pos = pos;
  97521. BINARY_SEARCH_AFTER_ITERATION = 0;
  97522. }
  97523. else {
  97524. /* this can probably only happen if total_samples is unknown and the
  97525. * target_sample is past the end of the stream
  97526. */
  97527. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  97528. return false;
  97529. }
  97530. }
  97531. /* our write callback will change the state when it gets to the target frame */
  97532. else if(!decoder->private_->is_seeking) {
  97533. break;
  97534. }
  97535. else {
  97536. this_frame_sample = decoder->private_->last_frame.header.number.sample_number;
  97537. FLAC__ASSERT(decoder->private_->last_frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  97538. if (did_a_seek) {
  97539. if (this_frame_sample <= target_sample) {
  97540. /* The 'equal' case should not happen, since
  97541. * FLAC__stream_decoder_process_single()
  97542. * should recognize that it has hit the
  97543. * target sample and we would exit through
  97544. * the 'break' above.
  97545. */
  97546. FLAC__ASSERT(this_frame_sample != target_sample);
  97547. left_sample = this_frame_sample;
  97548. /* sanity check to avoid infinite loop */
  97549. if (left_pos == pos) {
  97550. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  97551. return false;
  97552. }
  97553. left_pos = pos;
  97554. }
  97555. else if(this_frame_sample > target_sample) {
  97556. right_sample = this_frame_sample;
  97557. /* sanity check to avoid infinite loop */
  97558. if (right_pos == pos) {
  97559. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  97560. return false;
  97561. }
  97562. right_pos = pos;
  97563. }
  97564. }
  97565. }
  97566. }
  97567. return true;
  97568. }
  97569. #endif
  97570. FLAC__StreamDecoderReadStatus file_read_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  97571. {
  97572. (void)client_data;
  97573. if(*bytes > 0) {
  97574. *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, decoder->private_->file);
  97575. if(ferror(decoder->private_->file))
  97576. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  97577. else if(*bytes == 0)
  97578. return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  97579. else
  97580. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  97581. }
  97582. else
  97583. return FLAC__STREAM_DECODER_READ_STATUS_ABORT; /* abort to avoid a deadlock */
  97584. }
  97585. FLAC__StreamDecoderSeekStatus file_seek_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  97586. {
  97587. (void)client_data;
  97588. if(decoder->private_->file == stdin)
  97589. return FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED;
  97590. else if(fseeko(decoder->private_->file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  97591. return FLAC__STREAM_DECODER_SEEK_STATUS_ERROR;
  97592. else
  97593. return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  97594. }
  97595. FLAC__StreamDecoderTellStatus file_tell_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  97596. {
  97597. off_t pos;
  97598. (void)client_data;
  97599. if(decoder->private_->file == stdin)
  97600. return FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED;
  97601. else if((pos = ftello(decoder->private_->file)) < 0)
  97602. return FLAC__STREAM_DECODER_TELL_STATUS_ERROR;
  97603. else {
  97604. *absolute_byte_offset = (FLAC__uint64)pos;
  97605. return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  97606. }
  97607. }
  97608. FLAC__StreamDecoderLengthStatus file_length_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data)
  97609. {
  97610. struct stat filestats;
  97611. (void)client_data;
  97612. if(decoder->private_->file == stdin)
  97613. return FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED;
  97614. else if(fstat(fileno(decoder->private_->file), &filestats) != 0)
  97615. return FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR;
  97616. else {
  97617. *stream_length = (FLAC__uint64)filestats.st_size;
  97618. return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  97619. }
  97620. }
  97621. FLAC__bool file_eof_callback_(const FLAC__StreamDecoder *decoder, void *client_data)
  97622. {
  97623. (void)client_data;
  97624. return feof(decoder->private_->file)? true : false;
  97625. }
  97626. #endif
  97627. /********* End of inlined file: stream_decoder.c *********/
  97628. /********* Start of inlined file: stream_encoder.c *********/
  97629. /********* Start of inlined file: juce_FlacHeader.h *********/
  97630. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  97631. // tasks..
  97632. #define VERSION "1.2.1"
  97633. #define FLAC__NO_DLL 1
  97634. #ifdef _MSC_VER
  97635. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  97636. #endif
  97637. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  97638. #define FLAC__SYS_DARWIN 1
  97639. #endif
  97640. /********* End of inlined file: juce_FlacHeader.h *********/
  97641. #if JUCE_USE_FLAC
  97642. #if HAVE_CONFIG_H
  97643. # include <config.h>
  97644. #endif
  97645. #if defined _MSC_VER || defined __MINGW32__
  97646. #include <io.h> /* for _setmode() */
  97647. #include <fcntl.h> /* for _O_BINARY */
  97648. #endif
  97649. #if defined __CYGWIN__ || defined __EMX__
  97650. #include <io.h> /* for setmode(), O_BINARY */
  97651. #include <fcntl.h> /* for _O_BINARY */
  97652. #endif
  97653. #include <limits.h>
  97654. #include <stdio.h>
  97655. #include <stdlib.h> /* for malloc() */
  97656. #include <string.h> /* for memcpy() */
  97657. #include <sys/types.h> /* for off_t */
  97658. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINGW32__
  97659. #if _MSC_VER <= 1600 || defined __BORLANDC__ /* @@@ [2G limit] */
  97660. #define fseeko fseek
  97661. #define ftello ftell
  97662. #endif
  97663. #endif
  97664. /********* Start of inlined file: stream_encoder.h *********/
  97665. #ifndef FLAC__PROTECTED__STREAM_ENCODER_H
  97666. #define FLAC__PROTECTED__STREAM_ENCODER_H
  97667. #if FLAC__HAS_OGG
  97668. #include "private/ogg_encoder_aspect.h"
  97669. #endif
  97670. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97671. #define FLAC__MAX_APODIZATION_FUNCTIONS 32
  97672. typedef enum {
  97673. FLAC__APODIZATION_BARTLETT,
  97674. FLAC__APODIZATION_BARTLETT_HANN,
  97675. FLAC__APODIZATION_BLACKMAN,
  97676. FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE,
  97677. FLAC__APODIZATION_CONNES,
  97678. FLAC__APODIZATION_FLATTOP,
  97679. FLAC__APODIZATION_GAUSS,
  97680. FLAC__APODIZATION_HAMMING,
  97681. FLAC__APODIZATION_HANN,
  97682. FLAC__APODIZATION_KAISER_BESSEL,
  97683. FLAC__APODIZATION_NUTTALL,
  97684. FLAC__APODIZATION_RECTANGLE,
  97685. FLAC__APODIZATION_TRIANGLE,
  97686. FLAC__APODIZATION_TUKEY,
  97687. FLAC__APODIZATION_WELCH
  97688. } FLAC__ApodizationFunction;
  97689. typedef struct {
  97690. FLAC__ApodizationFunction type;
  97691. union {
  97692. struct {
  97693. FLAC__real stddev;
  97694. } gauss;
  97695. struct {
  97696. FLAC__real p;
  97697. } tukey;
  97698. } parameters;
  97699. } FLAC__ApodizationSpecification;
  97700. #endif // #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97701. typedef struct FLAC__StreamEncoderProtected {
  97702. FLAC__StreamEncoderState state;
  97703. FLAC__bool verify;
  97704. FLAC__bool streamable_subset;
  97705. FLAC__bool do_md5;
  97706. FLAC__bool do_mid_side_stereo;
  97707. FLAC__bool loose_mid_side_stereo;
  97708. unsigned channels;
  97709. unsigned bits_per_sample;
  97710. unsigned sample_rate;
  97711. unsigned blocksize;
  97712. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97713. unsigned num_apodizations;
  97714. FLAC__ApodizationSpecification apodizations[FLAC__MAX_APODIZATION_FUNCTIONS];
  97715. #endif
  97716. unsigned max_lpc_order;
  97717. unsigned qlp_coeff_precision;
  97718. FLAC__bool do_qlp_coeff_prec_search;
  97719. FLAC__bool do_exhaustive_model_search;
  97720. FLAC__bool do_escape_coding;
  97721. unsigned min_residual_partition_order;
  97722. unsigned max_residual_partition_order;
  97723. unsigned rice_parameter_search_dist;
  97724. FLAC__uint64 total_samples_estimate;
  97725. FLAC__StreamMetadata **metadata;
  97726. unsigned num_metadata_blocks;
  97727. FLAC__uint64 streaminfo_offset, seektable_offset, audio_offset;
  97728. #if FLAC__HAS_OGG
  97729. FLAC__OggEncoderAspect ogg_encoder_aspect;
  97730. #endif
  97731. } FLAC__StreamEncoderProtected;
  97732. #endif
  97733. /********* End of inlined file: stream_encoder.h *********/
  97734. #if FLAC__HAS_OGG
  97735. #include "include/private/ogg_helper.h"
  97736. #include "include/private/ogg_mapping.h"
  97737. #endif
  97738. /********* Start of inlined file: stream_encoder_framing.h *********/
  97739. #ifndef FLAC__PRIVATE__STREAM_ENCODER_FRAMING_H
  97740. #define FLAC__PRIVATE__STREAM_ENCODER_FRAMING_H
  97741. FLAC__bool FLAC__add_metadata_block(const FLAC__StreamMetadata *metadata, FLAC__BitWriter *bw);
  97742. FLAC__bool FLAC__frame_add_header(const FLAC__FrameHeader *header, FLAC__BitWriter *bw);
  97743. FLAC__bool FLAC__subframe_add_constant(const FLAC__Subframe_Constant *subframe, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  97744. FLAC__bool FLAC__subframe_add_fixed(const FLAC__Subframe_Fixed *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  97745. FLAC__bool FLAC__subframe_add_lpc(const FLAC__Subframe_LPC *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  97746. FLAC__bool FLAC__subframe_add_verbatim(const FLAC__Subframe_Verbatim *subframe, unsigned samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  97747. #endif
  97748. /********* End of inlined file: stream_encoder_framing.h *********/
  97749. /********* Start of inlined file: window.h *********/
  97750. #ifndef FLAC__PRIVATE__WINDOW_H
  97751. #define FLAC__PRIVATE__WINDOW_H
  97752. #ifdef HAVE_CONFIG_H
  97753. #include <config.h>
  97754. #endif
  97755. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97756. /*
  97757. * FLAC__window_*()
  97758. * --------------------------------------------------------------------
  97759. * Calculates window coefficients according to different apodization
  97760. * functions.
  97761. *
  97762. * OUT window[0,L-1]
  97763. * IN L (number of points in window)
  97764. */
  97765. void FLAC__window_bartlett(FLAC__real *window, const FLAC__int32 L);
  97766. void FLAC__window_bartlett_hann(FLAC__real *window, const FLAC__int32 L);
  97767. void FLAC__window_blackman(FLAC__real *window, const FLAC__int32 L);
  97768. void FLAC__window_blackman_harris_4term_92db_sidelobe(FLAC__real *window, const FLAC__int32 L);
  97769. void FLAC__window_connes(FLAC__real *window, const FLAC__int32 L);
  97770. void FLAC__window_flattop(FLAC__real *window, const FLAC__int32 L);
  97771. void FLAC__window_gauss(FLAC__real *window, const FLAC__int32 L, const FLAC__real stddev); /* 0.0 < stddev <= 0.5 */
  97772. void FLAC__window_hamming(FLAC__real *window, const FLAC__int32 L);
  97773. void FLAC__window_hann(FLAC__real *window, const FLAC__int32 L);
  97774. void FLAC__window_kaiser_bessel(FLAC__real *window, const FLAC__int32 L);
  97775. void FLAC__window_nuttall(FLAC__real *window, const FLAC__int32 L);
  97776. void FLAC__window_rectangle(FLAC__real *window, const FLAC__int32 L);
  97777. void FLAC__window_triangle(FLAC__real *window, const FLAC__int32 L);
  97778. void FLAC__window_tukey(FLAC__real *window, const FLAC__int32 L, const FLAC__real p);
  97779. void FLAC__window_welch(FLAC__real *window, const FLAC__int32 L);
  97780. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  97781. #endif
  97782. /********* End of inlined file: window.h *********/
  97783. #ifndef FLaC__INLINE
  97784. #define FLaC__INLINE
  97785. #endif
  97786. #ifdef min
  97787. #undef min
  97788. #endif
  97789. #define min(x,y) ((x)<(y)?(x):(y))
  97790. #ifdef max
  97791. #undef max
  97792. #endif
  97793. #define max(x,y) ((x)>(y)?(x):(y))
  97794. /* Exact Rice codeword length calculation is off by default. The simple
  97795. * (and fast) estimation (of how many bits a residual value will be
  97796. * encoded with) in this encoder is very good, almost always yielding
  97797. * compression within 0.1% of exact calculation.
  97798. */
  97799. #undef EXACT_RICE_BITS_CALCULATION
  97800. /* Rice parameter searching is off by default. The simple (and fast)
  97801. * parameter estimation in this encoder is very good, almost always
  97802. * yielding compression within 0.1% of the optimal parameters.
  97803. */
  97804. #undef ENABLE_RICE_PARAMETER_SEARCH
  97805. typedef struct {
  97806. FLAC__int32 *data[FLAC__MAX_CHANNELS];
  97807. unsigned size; /* of each data[] in samples */
  97808. unsigned tail;
  97809. } verify_input_fifo;
  97810. typedef struct {
  97811. const FLAC__byte *data;
  97812. unsigned capacity;
  97813. unsigned bytes;
  97814. } verify_output;
  97815. typedef enum {
  97816. ENCODER_IN_MAGIC = 0,
  97817. ENCODER_IN_METADATA = 1,
  97818. ENCODER_IN_AUDIO = 2
  97819. } EncoderStateHint;
  97820. static struct CompressionLevels {
  97821. FLAC__bool do_mid_side_stereo;
  97822. FLAC__bool loose_mid_side_stereo;
  97823. unsigned max_lpc_order;
  97824. unsigned qlp_coeff_precision;
  97825. FLAC__bool do_qlp_coeff_prec_search;
  97826. FLAC__bool do_escape_coding;
  97827. FLAC__bool do_exhaustive_model_search;
  97828. unsigned min_residual_partition_order;
  97829. unsigned max_residual_partition_order;
  97830. unsigned rice_parameter_search_dist;
  97831. } compression_levels_[] = {
  97832. { false, false, 0, 0, false, false, false, 0, 3, 0 },
  97833. { true , true , 0, 0, false, false, false, 0, 3, 0 },
  97834. { true , false, 0, 0, false, false, false, 0, 3, 0 },
  97835. { false, false, 6, 0, false, false, false, 0, 4, 0 },
  97836. { true , true , 8, 0, false, false, false, 0, 4, 0 },
  97837. { true , false, 8, 0, false, false, false, 0, 5, 0 },
  97838. { true , false, 8, 0, false, false, false, 0, 6, 0 },
  97839. { true , false, 8, 0, false, false, true , 0, 6, 0 },
  97840. { true , false, 12, 0, false, false, true , 0, 6, 0 }
  97841. };
  97842. /***********************************************************************
  97843. *
  97844. * Private class method prototypes
  97845. *
  97846. ***********************************************************************/
  97847. static void set_defaults_enc(FLAC__StreamEncoder *encoder);
  97848. static void free_(FLAC__StreamEncoder *encoder);
  97849. static FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_blocksize);
  97850. static FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples, FLAC__bool is_last_block);
  97851. static FLAC__StreamEncoderWriteStatus write_frame_(FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, FLAC__bool is_last_block);
  97852. static void update_metadata_(const FLAC__StreamEncoder *encoder);
  97853. #if FLAC__HAS_OGG
  97854. static void update_ogg_metadata_(FLAC__StreamEncoder *encoder);
  97855. #endif
  97856. static FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block, FLAC__bool is_last_block);
  97857. static FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block);
  97858. static FLAC__bool process_subframe_(
  97859. FLAC__StreamEncoder *encoder,
  97860. unsigned min_partition_order,
  97861. unsigned max_partition_order,
  97862. const FLAC__FrameHeader *frame_header,
  97863. unsigned subframe_bps,
  97864. const FLAC__int32 integer_signal[],
  97865. FLAC__Subframe *subframe[2],
  97866. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
  97867. FLAC__int32 *residual[2],
  97868. unsigned *best_subframe,
  97869. unsigned *best_bits
  97870. );
  97871. static FLAC__bool add_subframe_(
  97872. FLAC__StreamEncoder *encoder,
  97873. unsigned blocksize,
  97874. unsigned subframe_bps,
  97875. const FLAC__Subframe *subframe,
  97876. FLAC__BitWriter *frame
  97877. );
  97878. static unsigned evaluate_constant_subframe_(
  97879. FLAC__StreamEncoder *encoder,
  97880. const FLAC__int32 signal,
  97881. unsigned blocksize,
  97882. unsigned subframe_bps,
  97883. FLAC__Subframe *subframe
  97884. );
  97885. static unsigned evaluate_fixed_subframe_(
  97886. FLAC__StreamEncoder *encoder,
  97887. const FLAC__int32 signal[],
  97888. FLAC__int32 residual[],
  97889. FLAC__uint64 abs_residual_partition_sums[],
  97890. unsigned raw_bits_per_partition[],
  97891. unsigned blocksize,
  97892. unsigned subframe_bps,
  97893. unsigned order,
  97894. unsigned rice_parameter,
  97895. unsigned rice_parameter_limit,
  97896. unsigned min_partition_order,
  97897. unsigned max_partition_order,
  97898. FLAC__bool do_escape_coding,
  97899. unsigned rice_parameter_search_dist,
  97900. FLAC__Subframe *subframe,
  97901. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  97902. );
  97903. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97904. static unsigned evaluate_lpc_subframe_(
  97905. FLAC__StreamEncoder *encoder,
  97906. const FLAC__int32 signal[],
  97907. FLAC__int32 residual[],
  97908. FLAC__uint64 abs_residual_partition_sums[],
  97909. unsigned raw_bits_per_partition[],
  97910. const FLAC__real lp_coeff[],
  97911. unsigned blocksize,
  97912. unsigned subframe_bps,
  97913. unsigned order,
  97914. unsigned qlp_coeff_precision,
  97915. unsigned rice_parameter,
  97916. unsigned rice_parameter_limit,
  97917. unsigned min_partition_order,
  97918. unsigned max_partition_order,
  97919. FLAC__bool do_escape_coding,
  97920. unsigned rice_parameter_search_dist,
  97921. FLAC__Subframe *subframe,
  97922. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  97923. );
  97924. #endif
  97925. static unsigned evaluate_verbatim_subframe_(
  97926. FLAC__StreamEncoder *encoder,
  97927. const FLAC__int32 signal[],
  97928. unsigned blocksize,
  97929. unsigned subframe_bps,
  97930. FLAC__Subframe *subframe
  97931. );
  97932. static unsigned find_best_partition_order_(
  97933. struct FLAC__StreamEncoderPrivate *private_,
  97934. const FLAC__int32 residual[],
  97935. FLAC__uint64 abs_residual_partition_sums[],
  97936. unsigned raw_bits_per_partition[],
  97937. unsigned residual_samples,
  97938. unsigned predictor_order,
  97939. unsigned rice_parameter,
  97940. unsigned rice_parameter_limit,
  97941. unsigned min_partition_order,
  97942. unsigned max_partition_order,
  97943. unsigned bps,
  97944. FLAC__bool do_escape_coding,
  97945. unsigned rice_parameter_search_dist,
  97946. FLAC__EntropyCodingMethod *best_ecm
  97947. );
  97948. static void precompute_partition_info_sums_(
  97949. const FLAC__int32 residual[],
  97950. FLAC__uint64 abs_residual_partition_sums[],
  97951. unsigned residual_samples,
  97952. unsigned predictor_order,
  97953. unsigned min_partition_order,
  97954. unsigned max_partition_order,
  97955. unsigned bps
  97956. );
  97957. static void precompute_partition_info_escapes_(
  97958. const FLAC__int32 residual[],
  97959. unsigned raw_bits_per_partition[],
  97960. unsigned residual_samples,
  97961. unsigned predictor_order,
  97962. unsigned min_partition_order,
  97963. unsigned max_partition_order
  97964. );
  97965. static FLAC__bool set_partitioned_rice_(
  97966. #ifdef EXACT_RICE_BITS_CALCULATION
  97967. const FLAC__int32 residual[],
  97968. #endif
  97969. const FLAC__uint64 abs_residual_partition_sums[],
  97970. const unsigned raw_bits_per_partition[],
  97971. const unsigned residual_samples,
  97972. const unsigned predictor_order,
  97973. const unsigned suggested_rice_parameter,
  97974. const unsigned rice_parameter_limit,
  97975. const unsigned rice_parameter_search_dist,
  97976. const unsigned partition_order,
  97977. const FLAC__bool search_for_escapes,
  97978. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
  97979. unsigned *bits
  97980. );
  97981. static unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples);
  97982. /* verify-related routines: */
  97983. static void append_to_verify_fifo_(
  97984. verify_input_fifo *fifo,
  97985. const FLAC__int32 * const input[],
  97986. unsigned input_offset,
  97987. unsigned channels,
  97988. unsigned wide_samples
  97989. );
  97990. static void append_to_verify_fifo_interleaved_(
  97991. verify_input_fifo *fifo,
  97992. const FLAC__int32 input[],
  97993. unsigned input_offset,
  97994. unsigned channels,
  97995. unsigned wide_samples
  97996. );
  97997. static FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  97998. static FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
  97999. static void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
  98000. static void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
  98001. static FLAC__StreamEncoderReadStatus file_read_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  98002. static FLAC__StreamEncoderSeekStatus file_seek_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  98003. static FLAC__StreamEncoderTellStatus file_tell_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  98004. static FLAC__StreamEncoderWriteStatus file_write_callback_(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data);
  98005. static FILE *get_binary_stdout_(void);
  98006. /***********************************************************************
  98007. *
  98008. * Private class data
  98009. *
  98010. ***********************************************************************/
  98011. typedef struct FLAC__StreamEncoderPrivate {
  98012. unsigned input_capacity; /* current size (in samples) of the signal and residual buffers */
  98013. FLAC__int32 *integer_signal[FLAC__MAX_CHANNELS]; /* the integer version of the input signal */
  98014. FLAC__int32 *integer_signal_mid_side[2]; /* the integer version of the mid-side input signal (stereo only) */
  98015. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98016. FLAC__real *real_signal[FLAC__MAX_CHANNELS]; /* (@@@ currently unused) the floating-point version of the input signal */
  98017. FLAC__real *real_signal_mid_side[2]; /* (@@@ currently unused) the floating-point version of the mid-side input signal (stereo only) */
  98018. FLAC__real *window[FLAC__MAX_APODIZATION_FUNCTIONS]; /* the pre-computed floating-point window for each apodization function */
  98019. FLAC__real *windowed_signal; /* the integer_signal[] * current window[] */
  98020. #endif
  98021. unsigned subframe_bps[FLAC__MAX_CHANNELS]; /* the effective bits per sample of the input signal (stream bps - wasted bits) */
  98022. unsigned subframe_bps_mid_side[2]; /* the effective bits per sample of the mid-side input signal (stream bps - wasted bits + 0/1) */
  98023. FLAC__int32 *residual_workspace[FLAC__MAX_CHANNELS][2]; /* each channel has a candidate and best workspace where the subframe residual signals will be stored */
  98024. FLAC__int32 *residual_workspace_mid_side[2][2];
  98025. FLAC__Subframe subframe_workspace[FLAC__MAX_CHANNELS][2];
  98026. FLAC__Subframe subframe_workspace_mid_side[2][2];
  98027. FLAC__Subframe *subframe_workspace_ptr[FLAC__MAX_CHANNELS][2];
  98028. FLAC__Subframe *subframe_workspace_ptr_mid_side[2][2];
  98029. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace[FLAC__MAX_CHANNELS][2];
  98030. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace_mid_side[FLAC__MAX_CHANNELS][2];
  98031. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr[FLAC__MAX_CHANNELS][2];
  98032. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr_mid_side[FLAC__MAX_CHANNELS][2];
  98033. unsigned best_subframe[FLAC__MAX_CHANNELS]; /* index (0 or 1) into 2nd dimension of the above workspaces */
  98034. unsigned best_subframe_mid_side[2];
  98035. unsigned best_subframe_bits[FLAC__MAX_CHANNELS]; /* size in bits of the best subframe for each channel */
  98036. unsigned best_subframe_bits_mid_side[2];
  98037. FLAC__uint64 *abs_residual_partition_sums; /* workspace where the sum of abs(candidate residual) for each partition is stored */
  98038. unsigned *raw_bits_per_partition; /* workspace where the sum of silog2(candidate residual) for each partition is stored */
  98039. FLAC__BitWriter *frame; /* the current frame being worked on */
  98040. unsigned loose_mid_side_stereo_frames; /* rounded number of frames the encoder will use before trying both independent and mid/side frames again */
  98041. unsigned loose_mid_side_stereo_frame_count; /* number of frames using the current channel assignment */
  98042. FLAC__ChannelAssignment last_channel_assignment;
  98043. FLAC__StreamMetadata streaminfo; /* scratchpad for STREAMINFO as it is built */
  98044. FLAC__StreamMetadata_SeekTable *seek_table; /* pointer into encoder->protected_->metadata_ where the seek table is */
  98045. unsigned current_sample_number;
  98046. unsigned current_frame_number;
  98047. FLAC__MD5Context md5context;
  98048. FLAC__CPUInfo cpuinfo;
  98049. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98050. unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  98051. #else
  98052. unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  98053. #endif
  98054. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98055. void (*local_lpc_compute_autocorrelation)(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  98056. void (*local_lpc_compute_residual_from_qlp_coefficients)(const FLAC__int32 *data, unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 residual[]);
  98057. void (*local_lpc_compute_residual_from_qlp_coefficients_64bit)(const FLAC__int32 *data, unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 residual[]);
  98058. void (*local_lpc_compute_residual_from_qlp_coefficients_16bit)(const FLAC__int32 *data, unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 residual[]);
  98059. #endif
  98060. FLAC__bool use_wide_by_block; /* use slow 64-bit versions of some functions because of the block size */
  98061. FLAC__bool use_wide_by_partition; /* use slow 64-bit versions of some functions because of the min partition order and blocksize */
  98062. FLAC__bool use_wide_by_order; /* use slow 64-bit versions of some functions because of the lpc order */
  98063. FLAC__bool disable_constant_subframes;
  98064. FLAC__bool disable_fixed_subframes;
  98065. FLAC__bool disable_verbatim_subframes;
  98066. #if FLAC__HAS_OGG
  98067. FLAC__bool is_ogg;
  98068. #endif
  98069. FLAC__StreamEncoderReadCallback read_callback; /* currently only needed for Ogg FLAC */
  98070. FLAC__StreamEncoderSeekCallback seek_callback;
  98071. FLAC__StreamEncoderTellCallback tell_callback;
  98072. FLAC__StreamEncoderWriteCallback write_callback;
  98073. FLAC__StreamEncoderMetadataCallback metadata_callback;
  98074. FLAC__StreamEncoderProgressCallback progress_callback;
  98075. void *client_data;
  98076. unsigned first_seekpoint_to_check;
  98077. FILE *file; /* only used when encoding to a file */
  98078. FLAC__uint64 bytes_written;
  98079. FLAC__uint64 samples_written;
  98080. unsigned frames_written;
  98081. unsigned total_frames_estimate;
  98082. /* unaligned (original) pointers to allocated data */
  98083. FLAC__int32 *integer_signal_unaligned[FLAC__MAX_CHANNELS];
  98084. FLAC__int32 *integer_signal_mid_side_unaligned[2];
  98085. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98086. FLAC__real *real_signal_unaligned[FLAC__MAX_CHANNELS]; /* (@@@ currently unused) */
  98087. FLAC__real *real_signal_mid_side_unaligned[2]; /* (@@@ currently unused) */
  98088. FLAC__real *window_unaligned[FLAC__MAX_APODIZATION_FUNCTIONS];
  98089. FLAC__real *windowed_signal_unaligned;
  98090. #endif
  98091. FLAC__int32 *residual_workspace_unaligned[FLAC__MAX_CHANNELS][2];
  98092. FLAC__int32 *residual_workspace_mid_side_unaligned[2][2];
  98093. FLAC__uint64 *abs_residual_partition_sums_unaligned;
  98094. unsigned *raw_bits_per_partition_unaligned;
  98095. /*
  98096. * These fields have been moved here from private function local
  98097. * declarations merely to save stack space during encoding.
  98098. */
  98099. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98100. FLAC__real lp_coeff[FLAC__MAX_LPC_ORDER][FLAC__MAX_LPC_ORDER]; /* from process_subframe_() */
  98101. #endif
  98102. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_extra[2]; /* from find_best_partition_order_() */
  98103. /*
  98104. * The data for the verify section
  98105. */
  98106. struct {
  98107. FLAC__StreamDecoder *decoder;
  98108. EncoderStateHint state_hint;
  98109. FLAC__bool needs_magic_hack;
  98110. verify_input_fifo input_fifo;
  98111. verify_output output;
  98112. struct {
  98113. FLAC__uint64 absolute_sample;
  98114. unsigned frame_number;
  98115. unsigned channel;
  98116. unsigned sample;
  98117. FLAC__int32 expected;
  98118. FLAC__int32 got;
  98119. } error_stats;
  98120. } verify;
  98121. FLAC__bool is_being_deleted; /* if true, call to ..._finish() from ..._delete() will not call the callbacks */
  98122. } FLAC__StreamEncoderPrivate;
  98123. /***********************************************************************
  98124. *
  98125. * Public static class data
  98126. *
  98127. ***********************************************************************/
  98128. FLAC_API const char * const FLAC__StreamEncoderStateString[] = {
  98129. "FLAC__STREAM_ENCODER_OK",
  98130. "FLAC__STREAM_ENCODER_UNINITIALIZED",
  98131. "FLAC__STREAM_ENCODER_OGG_ERROR",
  98132. "FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR",
  98133. "FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA",
  98134. "FLAC__STREAM_ENCODER_CLIENT_ERROR",
  98135. "FLAC__STREAM_ENCODER_IO_ERROR",
  98136. "FLAC__STREAM_ENCODER_FRAMING_ERROR",
  98137. "FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR"
  98138. };
  98139. FLAC_API const char * const FLAC__StreamEncoderInitStatusString[] = {
  98140. "FLAC__STREAM_ENCODER_INIT_STATUS_OK",
  98141. "FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR",
  98142. "FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER",
  98143. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS",
  98144. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS",
  98145. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE",
  98146. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE",
  98147. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE",
  98148. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER",
  98149. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION",
  98150. "FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER",
  98151. "FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE",
  98152. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA",
  98153. "FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED"
  98154. };
  98155. FLAC_API const char * const FLAC__treamEncoderReadStatusString[] = {
  98156. "FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE",
  98157. "FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM",
  98158. "FLAC__STREAM_ENCODER_READ_STATUS_ABORT",
  98159. "FLAC__STREAM_ENCODER_READ_STATUS_UNSUPPORTED"
  98160. };
  98161. FLAC_API const char * const FLAC__StreamEncoderWriteStatusString[] = {
  98162. "FLAC__STREAM_ENCODER_WRITE_STATUS_OK",
  98163. "FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR"
  98164. };
  98165. FLAC_API const char * const FLAC__StreamEncoderSeekStatusString[] = {
  98166. "FLAC__STREAM_ENCODER_SEEK_STATUS_OK",
  98167. "FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR",
  98168. "FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED"
  98169. };
  98170. FLAC_API const char * const FLAC__StreamEncoderTellStatusString[] = {
  98171. "FLAC__STREAM_ENCODER_TELL_STATUS_OK",
  98172. "FLAC__STREAM_ENCODER_TELL_STATUS_ERROR",
  98173. "FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED"
  98174. };
  98175. /* Number of samples that will be overread to watch for end of stream. By
  98176. * 'overread', we mean that the FLAC__stream_encoder_process*() calls will
  98177. * always try to read blocksize+1 samples before encoding a block, so that
  98178. * even if the stream has a total sample count that is an integral multiple
  98179. * of the blocksize, we will still notice when we are encoding the last
  98180. * block. This is needed, for example, to correctly set the end-of-stream
  98181. * marker in Ogg FLAC.
  98182. *
  98183. * WATCHOUT: some parts of the code assert that OVERREAD_ == 1 and there's
  98184. * not really any reason to change it.
  98185. */
  98186. static const unsigned OVERREAD_ = 1;
  98187. /***********************************************************************
  98188. *
  98189. * Class constructor/destructor
  98190. *
  98191. */
  98192. FLAC_API FLAC__StreamEncoder *FLAC__stream_encoder_new(void)
  98193. {
  98194. FLAC__StreamEncoder *encoder;
  98195. unsigned i;
  98196. FLAC__ASSERT(sizeof(int) >= 4); /* we want to die right away if this is not true */
  98197. encoder = (FLAC__StreamEncoder*)calloc(1, sizeof(FLAC__StreamEncoder));
  98198. if(encoder == 0) {
  98199. return 0;
  98200. }
  98201. encoder->protected_ = (FLAC__StreamEncoderProtected*)calloc(1, sizeof(FLAC__StreamEncoderProtected));
  98202. if(encoder->protected_ == 0) {
  98203. free(encoder);
  98204. return 0;
  98205. }
  98206. encoder->private_ = (FLAC__StreamEncoderPrivate*)calloc(1, sizeof(FLAC__StreamEncoderPrivate));
  98207. if(encoder->private_ == 0) {
  98208. free(encoder->protected_);
  98209. free(encoder);
  98210. return 0;
  98211. }
  98212. encoder->private_->frame = FLAC__bitwriter_new();
  98213. if(encoder->private_->frame == 0) {
  98214. free(encoder->private_);
  98215. free(encoder->protected_);
  98216. free(encoder);
  98217. return 0;
  98218. }
  98219. encoder->private_->file = 0;
  98220. set_defaults_enc(encoder);
  98221. encoder->private_->is_being_deleted = false;
  98222. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  98223. encoder->private_->subframe_workspace_ptr[i][0] = &encoder->private_->subframe_workspace[i][0];
  98224. encoder->private_->subframe_workspace_ptr[i][1] = &encoder->private_->subframe_workspace[i][1];
  98225. }
  98226. for(i = 0; i < 2; i++) {
  98227. encoder->private_->subframe_workspace_ptr_mid_side[i][0] = &encoder->private_->subframe_workspace_mid_side[i][0];
  98228. encoder->private_->subframe_workspace_ptr_mid_side[i][1] = &encoder->private_->subframe_workspace_mid_side[i][1];
  98229. }
  98230. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  98231. encoder->private_->partitioned_rice_contents_workspace_ptr[i][0] = &encoder->private_->partitioned_rice_contents_workspace[i][0];
  98232. encoder->private_->partitioned_rice_contents_workspace_ptr[i][1] = &encoder->private_->partitioned_rice_contents_workspace[i][1];
  98233. }
  98234. for(i = 0; i < 2; i++) {
  98235. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][0] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0];
  98236. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][1] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1];
  98237. }
  98238. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  98239. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][0]);
  98240. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][1]);
  98241. }
  98242. for(i = 0; i < 2; i++) {
  98243. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]);
  98244. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]);
  98245. }
  98246. for(i = 0; i < 2; i++)
  98247. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_extra[i]);
  98248. encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
  98249. return encoder;
  98250. }
  98251. FLAC_API void FLAC__stream_encoder_delete(FLAC__StreamEncoder *encoder)
  98252. {
  98253. unsigned i;
  98254. FLAC__ASSERT(0 != encoder);
  98255. FLAC__ASSERT(0 != encoder->protected_);
  98256. FLAC__ASSERT(0 != encoder->private_);
  98257. FLAC__ASSERT(0 != encoder->private_->frame);
  98258. encoder->private_->is_being_deleted = true;
  98259. (void)FLAC__stream_encoder_finish(encoder);
  98260. if(0 != encoder->private_->verify.decoder)
  98261. FLAC__stream_decoder_delete(encoder->private_->verify.decoder);
  98262. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  98263. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace[i][0]);
  98264. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace[i][1]);
  98265. }
  98266. for(i = 0; i < 2; i++) {
  98267. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]);
  98268. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]);
  98269. }
  98270. for(i = 0; i < 2; i++)
  98271. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_extra[i]);
  98272. FLAC__bitwriter_delete(encoder->private_->frame);
  98273. free(encoder->private_);
  98274. free(encoder->protected_);
  98275. free(encoder);
  98276. }
  98277. /***********************************************************************
  98278. *
  98279. * Public class methods
  98280. *
  98281. ***********************************************************************/
  98282. static FLAC__StreamEncoderInitStatus init_stream_internal_enc(
  98283. FLAC__StreamEncoder *encoder,
  98284. FLAC__StreamEncoderReadCallback read_callback,
  98285. FLAC__StreamEncoderWriteCallback write_callback,
  98286. FLAC__StreamEncoderSeekCallback seek_callback,
  98287. FLAC__StreamEncoderTellCallback tell_callback,
  98288. FLAC__StreamEncoderMetadataCallback metadata_callback,
  98289. void *client_data,
  98290. FLAC__bool is_ogg
  98291. )
  98292. {
  98293. unsigned i;
  98294. FLAC__bool metadata_has_seektable, metadata_has_vorbis_comment, metadata_picture_has_type1, metadata_picture_has_type2;
  98295. FLAC__ASSERT(0 != encoder);
  98296. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  98297. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  98298. #if !FLAC__HAS_OGG
  98299. if(is_ogg)
  98300. return FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER;
  98301. #endif
  98302. if(0 == write_callback || (seek_callback && 0 == tell_callback))
  98303. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS;
  98304. if(encoder->protected_->channels == 0 || encoder->protected_->channels > FLAC__MAX_CHANNELS)
  98305. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS;
  98306. if(encoder->protected_->channels != 2) {
  98307. encoder->protected_->do_mid_side_stereo = false;
  98308. encoder->protected_->loose_mid_side_stereo = false;
  98309. }
  98310. else if(!encoder->protected_->do_mid_side_stereo)
  98311. encoder->protected_->loose_mid_side_stereo = false;
  98312. if(encoder->protected_->bits_per_sample >= 32)
  98313. encoder->protected_->do_mid_side_stereo = false; /* since we currenty do 32-bit math, the side channel would have 33 bps and overflow */
  98314. if(encoder->protected_->bits_per_sample < FLAC__MIN_BITS_PER_SAMPLE || encoder->protected_->bits_per_sample > FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE)
  98315. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE;
  98316. if(!FLAC__format_sample_rate_is_valid(encoder->protected_->sample_rate))
  98317. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE;
  98318. if(encoder->protected_->blocksize == 0) {
  98319. if(encoder->protected_->max_lpc_order == 0)
  98320. encoder->protected_->blocksize = 1152;
  98321. else
  98322. encoder->protected_->blocksize = 4096;
  98323. }
  98324. if(encoder->protected_->blocksize < FLAC__MIN_BLOCK_SIZE || encoder->protected_->blocksize > FLAC__MAX_BLOCK_SIZE)
  98325. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE;
  98326. if(encoder->protected_->max_lpc_order > FLAC__MAX_LPC_ORDER)
  98327. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER;
  98328. if(encoder->protected_->blocksize < encoder->protected_->max_lpc_order)
  98329. return FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER;
  98330. if(encoder->protected_->qlp_coeff_precision == 0) {
  98331. if(encoder->protected_->bits_per_sample < 16) {
  98332. /* @@@ need some data about how to set this here w.r.t. blocksize and sample rate */
  98333. /* @@@ until then we'll make a guess */
  98334. encoder->protected_->qlp_coeff_precision = max(FLAC__MIN_QLP_COEFF_PRECISION, 2 + encoder->protected_->bits_per_sample / 2);
  98335. }
  98336. else if(encoder->protected_->bits_per_sample == 16) {
  98337. if(encoder->protected_->blocksize <= 192)
  98338. encoder->protected_->qlp_coeff_precision = 7;
  98339. else if(encoder->protected_->blocksize <= 384)
  98340. encoder->protected_->qlp_coeff_precision = 8;
  98341. else if(encoder->protected_->blocksize <= 576)
  98342. encoder->protected_->qlp_coeff_precision = 9;
  98343. else if(encoder->protected_->blocksize <= 1152)
  98344. encoder->protected_->qlp_coeff_precision = 10;
  98345. else if(encoder->protected_->blocksize <= 2304)
  98346. encoder->protected_->qlp_coeff_precision = 11;
  98347. else if(encoder->protected_->blocksize <= 4608)
  98348. encoder->protected_->qlp_coeff_precision = 12;
  98349. else
  98350. encoder->protected_->qlp_coeff_precision = 13;
  98351. }
  98352. else {
  98353. if(encoder->protected_->blocksize <= 384)
  98354. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION-2;
  98355. else if(encoder->protected_->blocksize <= 1152)
  98356. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION-1;
  98357. else
  98358. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
  98359. }
  98360. FLAC__ASSERT(encoder->protected_->qlp_coeff_precision <= FLAC__MAX_QLP_COEFF_PRECISION);
  98361. }
  98362. else if(encoder->protected_->qlp_coeff_precision < FLAC__MIN_QLP_COEFF_PRECISION || encoder->protected_->qlp_coeff_precision > FLAC__MAX_QLP_COEFF_PRECISION)
  98363. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION;
  98364. if(encoder->protected_->streamable_subset) {
  98365. if(
  98366. encoder->protected_->blocksize != 192 &&
  98367. encoder->protected_->blocksize != 576 &&
  98368. encoder->protected_->blocksize != 1152 &&
  98369. encoder->protected_->blocksize != 2304 &&
  98370. encoder->protected_->blocksize != 4608 &&
  98371. encoder->protected_->blocksize != 256 &&
  98372. encoder->protected_->blocksize != 512 &&
  98373. encoder->protected_->blocksize != 1024 &&
  98374. encoder->protected_->blocksize != 2048 &&
  98375. encoder->protected_->blocksize != 4096 &&
  98376. encoder->protected_->blocksize != 8192 &&
  98377. encoder->protected_->blocksize != 16384
  98378. )
  98379. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  98380. if(!FLAC__format_sample_rate_is_subset(encoder->protected_->sample_rate))
  98381. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  98382. if(
  98383. encoder->protected_->bits_per_sample != 8 &&
  98384. encoder->protected_->bits_per_sample != 12 &&
  98385. encoder->protected_->bits_per_sample != 16 &&
  98386. encoder->protected_->bits_per_sample != 20 &&
  98387. encoder->protected_->bits_per_sample != 24
  98388. )
  98389. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  98390. if(encoder->protected_->max_residual_partition_order > FLAC__SUBSET_MAX_RICE_PARTITION_ORDER)
  98391. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  98392. if(
  98393. encoder->protected_->sample_rate <= 48000 &&
  98394. (
  98395. encoder->protected_->blocksize > FLAC__SUBSET_MAX_BLOCK_SIZE_48000HZ ||
  98396. encoder->protected_->max_lpc_order > FLAC__SUBSET_MAX_LPC_ORDER_48000HZ
  98397. )
  98398. ) {
  98399. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  98400. }
  98401. }
  98402. if(encoder->protected_->max_residual_partition_order >= (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  98403. encoder->protected_->max_residual_partition_order = (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN) - 1;
  98404. if(encoder->protected_->min_residual_partition_order >= encoder->protected_->max_residual_partition_order)
  98405. encoder->protected_->min_residual_partition_order = encoder->protected_->max_residual_partition_order;
  98406. #if FLAC__HAS_OGG
  98407. /* reorder metadata if necessary to ensure that any VORBIS_COMMENT is the first, according to the mapping spec */
  98408. if(is_ogg && 0 != encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 1) {
  98409. unsigned i;
  98410. for(i = 1; i < encoder->protected_->num_metadata_blocks; i++) {
  98411. if(0 != encoder->protected_->metadata[i] && encoder->protected_->metadata[i]->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  98412. FLAC__StreamMetadata *vc = encoder->protected_->metadata[i];
  98413. for( ; i > 0; i--)
  98414. encoder->protected_->metadata[i] = encoder->protected_->metadata[i-1];
  98415. encoder->protected_->metadata[0] = vc;
  98416. break;
  98417. }
  98418. }
  98419. }
  98420. #endif
  98421. /* keep track of any SEEKTABLE block */
  98422. if(0 != encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 0) {
  98423. unsigned i;
  98424. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  98425. if(0 != encoder->protected_->metadata[i] && encoder->protected_->metadata[i]->type == FLAC__METADATA_TYPE_SEEKTABLE) {
  98426. encoder->private_->seek_table = &encoder->protected_->metadata[i]->data.seek_table;
  98427. break; /* take only the first one */
  98428. }
  98429. }
  98430. }
  98431. /* validate metadata */
  98432. if(0 == encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 0)
  98433. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  98434. metadata_has_seektable = false;
  98435. metadata_has_vorbis_comment = false;
  98436. metadata_picture_has_type1 = false;
  98437. metadata_picture_has_type2 = false;
  98438. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  98439. const FLAC__StreamMetadata *m = encoder->protected_->metadata[i];
  98440. if(m->type == FLAC__METADATA_TYPE_STREAMINFO)
  98441. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  98442. else if(m->type == FLAC__METADATA_TYPE_SEEKTABLE) {
  98443. if(metadata_has_seektable) /* only one is allowed */
  98444. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  98445. metadata_has_seektable = true;
  98446. if(!FLAC__format_seektable_is_legal(&m->data.seek_table))
  98447. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  98448. }
  98449. else if(m->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  98450. if(metadata_has_vorbis_comment) /* only one is allowed */
  98451. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  98452. metadata_has_vorbis_comment = true;
  98453. }
  98454. else if(m->type == FLAC__METADATA_TYPE_CUESHEET) {
  98455. if(!FLAC__format_cuesheet_is_legal(&m->data.cue_sheet, m->data.cue_sheet.is_cd, /*violation=*/0))
  98456. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  98457. }
  98458. else if(m->type == FLAC__METADATA_TYPE_PICTURE) {
  98459. if(!FLAC__format_picture_is_legal(&m->data.picture, /*violation=*/0))
  98460. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  98461. if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD) {
  98462. if(metadata_picture_has_type1) /* there should only be 1 per stream */
  98463. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  98464. metadata_picture_has_type1 = true;
  98465. /* standard icon must be 32x32 pixel PNG */
  98466. if(
  98467. m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD &&
  98468. (
  98469. (strcmp(m->data.picture.mime_type, "image/png") && strcmp(m->data.picture.mime_type, "-->")) ||
  98470. m->data.picture.width != 32 ||
  98471. m->data.picture.height != 32
  98472. )
  98473. )
  98474. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  98475. }
  98476. else if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON) {
  98477. if(metadata_picture_has_type2) /* there should only be 1 per stream */
  98478. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  98479. metadata_picture_has_type2 = true;
  98480. }
  98481. }
  98482. }
  98483. encoder->private_->input_capacity = 0;
  98484. for(i = 0; i < encoder->protected_->channels; i++) {
  98485. encoder->private_->integer_signal_unaligned[i] = encoder->private_->integer_signal[i] = 0;
  98486. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98487. encoder->private_->real_signal_unaligned[i] = encoder->private_->real_signal[i] = 0;
  98488. #endif
  98489. }
  98490. for(i = 0; i < 2; i++) {
  98491. encoder->private_->integer_signal_mid_side_unaligned[i] = encoder->private_->integer_signal_mid_side[i] = 0;
  98492. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98493. encoder->private_->real_signal_mid_side_unaligned[i] = encoder->private_->real_signal_mid_side[i] = 0;
  98494. #endif
  98495. }
  98496. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98497. for(i = 0; i < encoder->protected_->num_apodizations; i++)
  98498. encoder->private_->window_unaligned[i] = encoder->private_->window[i] = 0;
  98499. encoder->private_->windowed_signal_unaligned = encoder->private_->windowed_signal = 0;
  98500. #endif
  98501. for(i = 0; i < encoder->protected_->channels; i++) {
  98502. encoder->private_->residual_workspace_unaligned[i][0] = encoder->private_->residual_workspace[i][0] = 0;
  98503. encoder->private_->residual_workspace_unaligned[i][1] = encoder->private_->residual_workspace[i][1] = 0;
  98504. encoder->private_->best_subframe[i] = 0;
  98505. }
  98506. for(i = 0; i < 2; i++) {
  98507. encoder->private_->residual_workspace_mid_side_unaligned[i][0] = encoder->private_->residual_workspace_mid_side[i][0] = 0;
  98508. encoder->private_->residual_workspace_mid_side_unaligned[i][1] = encoder->private_->residual_workspace_mid_side[i][1] = 0;
  98509. encoder->private_->best_subframe_mid_side[i] = 0;
  98510. }
  98511. encoder->private_->abs_residual_partition_sums_unaligned = encoder->private_->abs_residual_partition_sums = 0;
  98512. encoder->private_->raw_bits_per_partition_unaligned = encoder->private_->raw_bits_per_partition = 0;
  98513. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98514. encoder->private_->loose_mid_side_stereo_frames = (unsigned)((FLAC__double)encoder->protected_->sample_rate * 0.4 / (FLAC__double)encoder->protected_->blocksize + 0.5);
  98515. #else
  98516. /* 26214 is the approximate fixed-point equivalent to 0.4 (0.4 * 2^16) */
  98517. /* sample rate can be up to 655350 Hz, and thus use 20 bits, so we do the multiply&divide by hand */
  98518. FLAC__ASSERT(FLAC__MAX_SAMPLE_RATE <= 655350);
  98519. FLAC__ASSERT(FLAC__MAX_BLOCK_SIZE <= 65535);
  98520. FLAC__ASSERT(encoder->protected_->sample_rate <= 655350);
  98521. FLAC__ASSERT(encoder->protected_->blocksize <= 65535);
  98522. encoder->private_->loose_mid_side_stereo_frames = (unsigned)FLAC__fixedpoint_trunc((((FLAC__uint64)(encoder->protected_->sample_rate) * (FLAC__uint64)(26214)) << 16) / (encoder->protected_->blocksize<<16) + FLAC__FP_ONE_HALF);
  98523. #endif
  98524. if(encoder->private_->loose_mid_side_stereo_frames == 0)
  98525. encoder->private_->loose_mid_side_stereo_frames = 1;
  98526. encoder->private_->loose_mid_side_stereo_frame_count = 0;
  98527. encoder->private_->current_sample_number = 0;
  98528. encoder->private_->current_frame_number = 0;
  98529. encoder->private_->use_wide_by_block = (encoder->protected_->bits_per_sample + FLAC__bitmath_ilog2(encoder->protected_->blocksize)+1 > 30);
  98530. encoder->private_->use_wide_by_order = (encoder->protected_->bits_per_sample + FLAC__bitmath_ilog2(max(encoder->protected_->max_lpc_order, FLAC__MAX_FIXED_ORDER))+1 > 30); /*@@@ need to use this? */
  98531. encoder->private_->use_wide_by_partition = (false); /*@@@ need to set this */
  98532. /*
  98533. * get the CPU info and set the function pointers
  98534. */
  98535. FLAC__cpu_info(&encoder->private_->cpuinfo);
  98536. /* first default to the non-asm routines */
  98537. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98538. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation;
  98539. #endif
  98540. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor;
  98541. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98542. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients;
  98543. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit = FLAC__lpc_compute_residual_from_qlp_coefficients_wide;
  98544. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients;
  98545. #endif
  98546. /* now override with asm where appropriate */
  98547. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98548. # ifndef FLAC__NO_ASM
  98549. if(encoder->private_->cpuinfo.use_asm) {
  98550. # ifdef FLAC__CPU_IA32
  98551. FLAC__ASSERT(encoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_IA32);
  98552. # ifdef FLAC__HAS_NASM
  98553. if(encoder->private_->cpuinfo.data.ia32.sse) {
  98554. if(encoder->protected_->max_lpc_order < 4)
  98555. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_4;
  98556. else if(encoder->protected_->max_lpc_order < 8)
  98557. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_8;
  98558. else if(encoder->protected_->max_lpc_order < 12)
  98559. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_12;
  98560. else
  98561. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
  98562. }
  98563. else if(encoder->private_->cpuinfo.data.ia32._3dnow)
  98564. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_3dnow;
  98565. else
  98566. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
  98567. if(encoder->private_->cpuinfo.data.ia32.mmx) {
  98568. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  98569. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx;
  98570. }
  98571. else {
  98572. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  98573. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  98574. }
  98575. if(encoder->private_->cpuinfo.data.ia32.mmx && encoder->private_->cpuinfo.data.ia32.cmov)
  98576. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_asm_ia32_mmx_cmov;
  98577. # endif /* FLAC__HAS_NASM */
  98578. # endif /* FLAC__CPU_IA32 */
  98579. }
  98580. # endif /* !FLAC__NO_ASM */
  98581. #endif /* !FLAC__INTEGER_ONLY_LIBRARY */
  98582. /* finally override based on wide-ness if necessary */
  98583. if(encoder->private_->use_wide_by_block) {
  98584. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_wide;
  98585. }
  98586. /* set state to OK; from here on, errors are fatal and we'll override the state then */
  98587. encoder->protected_->state = FLAC__STREAM_ENCODER_OK;
  98588. #if FLAC__HAS_OGG
  98589. encoder->private_->is_ogg = is_ogg;
  98590. if(is_ogg && !FLAC__ogg_encoder_aspect_init(&encoder->protected_->ogg_encoder_aspect)) {
  98591. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  98592. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  98593. }
  98594. #endif
  98595. encoder->private_->read_callback = read_callback;
  98596. encoder->private_->write_callback = write_callback;
  98597. encoder->private_->seek_callback = seek_callback;
  98598. encoder->private_->tell_callback = tell_callback;
  98599. encoder->private_->metadata_callback = metadata_callback;
  98600. encoder->private_->client_data = client_data;
  98601. if(!resize_buffers_(encoder, encoder->protected_->blocksize)) {
  98602. /* the above function sets the state for us in case of an error */
  98603. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  98604. }
  98605. if(!FLAC__bitwriter_init(encoder->private_->frame)) {
  98606. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  98607. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  98608. }
  98609. /*
  98610. * Set up the verify stuff if necessary
  98611. */
  98612. if(encoder->protected_->verify) {
  98613. /*
  98614. * First, set up the fifo which will hold the
  98615. * original signal to compare against
  98616. */
  98617. encoder->private_->verify.input_fifo.size = encoder->protected_->blocksize+OVERREAD_;
  98618. for(i = 0; i < encoder->protected_->channels; i++) {
  98619. if(0 == (encoder->private_->verify.input_fifo.data[i] = (FLAC__int32*)safe_malloc_mul_2op_(sizeof(FLAC__int32), /*times*/encoder->private_->verify.input_fifo.size))) {
  98620. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  98621. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  98622. }
  98623. }
  98624. encoder->private_->verify.input_fifo.tail = 0;
  98625. /*
  98626. * Now set up a stream decoder for verification
  98627. */
  98628. encoder->private_->verify.decoder = FLAC__stream_decoder_new();
  98629. if(0 == encoder->private_->verify.decoder) {
  98630. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  98631. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  98632. }
  98633. if(FLAC__stream_decoder_init_stream(encoder->private_->verify.decoder, verify_read_callback_, /*seek_callback=*/0, /*tell_callback=*/0, /*length_callback=*/0, /*eof_callback=*/0, verify_write_callback_, verify_metadata_callback_, verify_error_callback_, /*client_data=*/encoder) != FLAC__STREAM_DECODER_INIT_STATUS_OK) {
  98634. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  98635. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  98636. }
  98637. }
  98638. encoder->private_->verify.error_stats.absolute_sample = 0;
  98639. encoder->private_->verify.error_stats.frame_number = 0;
  98640. encoder->private_->verify.error_stats.channel = 0;
  98641. encoder->private_->verify.error_stats.sample = 0;
  98642. encoder->private_->verify.error_stats.expected = 0;
  98643. encoder->private_->verify.error_stats.got = 0;
  98644. /*
  98645. * These must be done before we write any metadata, because that
  98646. * calls the write_callback, which uses these values.
  98647. */
  98648. encoder->private_->first_seekpoint_to_check = 0;
  98649. encoder->private_->samples_written = 0;
  98650. encoder->protected_->streaminfo_offset = 0;
  98651. encoder->protected_->seektable_offset = 0;
  98652. encoder->protected_->audio_offset = 0;
  98653. /*
  98654. * write the stream header
  98655. */
  98656. if(encoder->protected_->verify)
  98657. encoder->private_->verify.state_hint = ENCODER_IN_MAGIC;
  98658. if(!FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, FLAC__STREAM_SYNC, FLAC__STREAM_SYNC_LEN)) {
  98659. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  98660. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  98661. }
  98662. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  98663. /* the above function sets the state for us in case of an error */
  98664. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  98665. }
  98666. /*
  98667. * write the STREAMINFO metadata block
  98668. */
  98669. if(encoder->protected_->verify)
  98670. encoder->private_->verify.state_hint = ENCODER_IN_METADATA;
  98671. encoder->private_->streaminfo.type = FLAC__METADATA_TYPE_STREAMINFO;
  98672. encoder->private_->streaminfo.is_last = false; /* we will have at a minimum a VORBIS_COMMENT afterwards */
  98673. encoder->private_->streaminfo.length = FLAC__STREAM_METADATA_STREAMINFO_LENGTH;
  98674. encoder->private_->streaminfo.data.stream_info.min_blocksize = encoder->protected_->blocksize; /* this encoder uses the same blocksize for the whole stream */
  98675. encoder->private_->streaminfo.data.stream_info.max_blocksize = encoder->protected_->blocksize;
  98676. encoder->private_->streaminfo.data.stream_info.min_framesize = 0; /* we don't know this yet; have to fill it in later */
  98677. encoder->private_->streaminfo.data.stream_info.max_framesize = 0; /* we don't know this yet; have to fill it in later */
  98678. encoder->private_->streaminfo.data.stream_info.sample_rate = encoder->protected_->sample_rate;
  98679. encoder->private_->streaminfo.data.stream_info.channels = encoder->protected_->channels;
  98680. encoder->private_->streaminfo.data.stream_info.bits_per_sample = encoder->protected_->bits_per_sample;
  98681. encoder->private_->streaminfo.data.stream_info.total_samples = encoder->protected_->total_samples_estimate; /* we will replace this later with the real total */
  98682. memset(encoder->private_->streaminfo.data.stream_info.md5sum, 0, 16); /* we don't know this yet; have to fill it in later */
  98683. if(encoder->protected_->do_md5)
  98684. FLAC__MD5Init(&encoder->private_->md5context);
  98685. if(!FLAC__add_metadata_block(&encoder->private_->streaminfo, encoder->private_->frame)) {
  98686. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  98687. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  98688. }
  98689. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  98690. /* the above function sets the state for us in case of an error */
  98691. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  98692. }
  98693. /*
  98694. * Now that the STREAMINFO block is written, we can init this to an
  98695. * absurdly-high value...
  98696. */
  98697. encoder->private_->streaminfo.data.stream_info.min_framesize = (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN) - 1;
  98698. /* ... and clear this to 0 */
  98699. encoder->private_->streaminfo.data.stream_info.total_samples = 0;
  98700. /*
  98701. * Check to see if the supplied metadata contains a VORBIS_COMMENT;
  98702. * if not, we will write an empty one (FLAC__add_metadata_block()
  98703. * automatically supplies the vendor string).
  98704. *
  98705. * WATCHOUT: the Ogg FLAC mapping requires us to write this block after
  98706. * the STREAMINFO. (In the case that metadata_has_vorbis_comment is
  98707. * true it will have already insured that the metadata list is properly
  98708. * ordered.)
  98709. */
  98710. if(!metadata_has_vorbis_comment) {
  98711. FLAC__StreamMetadata vorbis_comment;
  98712. vorbis_comment.type = FLAC__METADATA_TYPE_VORBIS_COMMENT;
  98713. vorbis_comment.is_last = (encoder->protected_->num_metadata_blocks == 0);
  98714. vorbis_comment.length = 4 + 4; /* MAGIC NUMBER */
  98715. vorbis_comment.data.vorbis_comment.vendor_string.length = 0;
  98716. vorbis_comment.data.vorbis_comment.vendor_string.entry = 0;
  98717. vorbis_comment.data.vorbis_comment.num_comments = 0;
  98718. vorbis_comment.data.vorbis_comment.comments = 0;
  98719. if(!FLAC__add_metadata_block(&vorbis_comment, encoder->private_->frame)) {
  98720. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  98721. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  98722. }
  98723. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  98724. /* the above function sets the state for us in case of an error */
  98725. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  98726. }
  98727. }
  98728. /*
  98729. * write the user's metadata blocks
  98730. */
  98731. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  98732. encoder->protected_->metadata[i]->is_last = (i == encoder->protected_->num_metadata_blocks - 1);
  98733. if(!FLAC__add_metadata_block(encoder->protected_->metadata[i], encoder->private_->frame)) {
  98734. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  98735. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  98736. }
  98737. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  98738. /* the above function sets the state for us in case of an error */
  98739. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  98740. }
  98741. }
  98742. /* now that all the metadata is written, we save the stream offset */
  98743. if(encoder->private_->tell_callback && encoder->private_->tell_callback(encoder, &encoder->protected_->audio_offset, encoder->private_->client_data) == FLAC__STREAM_ENCODER_TELL_STATUS_ERROR) { /* FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED just means we didn't get the offset; no error */
  98744. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  98745. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  98746. }
  98747. if(encoder->protected_->verify)
  98748. encoder->private_->verify.state_hint = ENCODER_IN_AUDIO;
  98749. return FLAC__STREAM_ENCODER_INIT_STATUS_OK;
  98750. }
  98751. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_stream(
  98752. FLAC__StreamEncoder *encoder,
  98753. FLAC__StreamEncoderWriteCallback write_callback,
  98754. FLAC__StreamEncoderSeekCallback seek_callback,
  98755. FLAC__StreamEncoderTellCallback tell_callback,
  98756. FLAC__StreamEncoderMetadataCallback metadata_callback,
  98757. void *client_data
  98758. )
  98759. {
  98760. return init_stream_internal_enc(
  98761. encoder,
  98762. /*read_callback=*/0,
  98763. write_callback,
  98764. seek_callback,
  98765. tell_callback,
  98766. metadata_callback,
  98767. client_data,
  98768. /*is_ogg=*/false
  98769. );
  98770. }
  98771. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_stream(
  98772. FLAC__StreamEncoder *encoder,
  98773. FLAC__StreamEncoderReadCallback read_callback,
  98774. FLAC__StreamEncoderWriteCallback write_callback,
  98775. FLAC__StreamEncoderSeekCallback seek_callback,
  98776. FLAC__StreamEncoderTellCallback tell_callback,
  98777. FLAC__StreamEncoderMetadataCallback metadata_callback,
  98778. void *client_data
  98779. )
  98780. {
  98781. return init_stream_internal_enc(
  98782. encoder,
  98783. read_callback,
  98784. write_callback,
  98785. seek_callback,
  98786. tell_callback,
  98787. metadata_callback,
  98788. client_data,
  98789. /*is_ogg=*/true
  98790. );
  98791. }
  98792. static FLAC__StreamEncoderInitStatus init_FILE_internal_enc(
  98793. FLAC__StreamEncoder *encoder,
  98794. FILE *file,
  98795. FLAC__StreamEncoderProgressCallback progress_callback,
  98796. void *client_data,
  98797. FLAC__bool is_ogg
  98798. )
  98799. {
  98800. FLAC__StreamEncoderInitStatus init_status;
  98801. FLAC__ASSERT(0 != encoder);
  98802. FLAC__ASSERT(0 != file);
  98803. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  98804. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  98805. /* double protection */
  98806. if(file == 0) {
  98807. encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
  98808. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  98809. }
  98810. /*
  98811. * To make sure that our file does not go unclosed after an error, we
  98812. * must assign the FILE pointer before any further error can occur in
  98813. * this routine.
  98814. */
  98815. if(file == stdout)
  98816. file = get_binary_stdout_(); /* just to be safe */
  98817. encoder->private_->file = file;
  98818. encoder->private_->progress_callback = progress_callback;
  98819. encoder->private_->bytes_written = 0;
  98820. encoder->private_->samples_written = 0;
  98821. encoder->private_->frames_written = 0;
  98822. init_status = init_stream_internal_enc(
  98823. encoder,
  98824. encoder->private_->file == stdout? 0 : is_ogg? file_read_callback_enc : 0,
  98825. file_write_callback_,
  98826. encoder->private_->file == stdout? 0 : file_seek_callback_enc,
  98827. encoder->private_->file == stdout? 0 : file_tell_callback_enc,
  98828. /*metadata_callback=*/0,
  98829. client_data,
  98830. is_ogg
  98831. );
  98832. if(init_status != FLAC__STREAM_ENCODER_INIT_STATUS_OK) {
  98833. /* the above function sets the state for us in case of an error */
  98834. return init_status;
  98835. }
  98836. {
  98837. unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
  98838. FLAC__ASSERT(blocksize != 0);
  98839. encoder->private_->total_frames_estimate = (unsigned)((FLAC__stream_encoder_get_total_samples_estimate(encoder) + blocksize - 1) / blocksize);
  98840. }
  98841. return init_status;
  98842. }
  98843. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_FILE(
  98844. FLAC__StreamEncoder *encoder,
  98845. FILE *file,
  98846. FLAC__StreamEncoderProgressCallback progress_callback,
  98847. void *client_data
  98848. )
  98849. {
  98850. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, /*is_ogg=*/false);
  98851. }
  98852. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_FILE(
  98853. FLAC__StreamEncoder *encoder,
  98854. FILE *file,
  98855. FLAC__StreamEncoderProgressCallback progress_callback,
  98856. void *client_data
  98857. )
  98858. {
  98859. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, /*is_ogg=*/true);
  98860. }
  98861. static FLAC__StreamEncoderInitStatus init_file_internal_enc(
  98862. FLAC__StreamEncoder *encoder,
  98863. const char *filename,
  98864. FLAC__StreamEncoderProgressCallback progress_callback,
  98865. void *client_data,
  98866. FLAC__bool is_ogg
  98867. )
  98868. {
  98869. FILE *file;
  98870. FLAC__ASSERT(0 != encoder);
  98871. /*
  98872. * To make sure that our file does not go unclosed after an error, we
  98873. * have to do the same entrance checks here that are later performed
  98874. * in FLAC__stream_encoder_init_FILE() before the FILE* is assigned.
  98875. */
  98876. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  98877. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  98878. file = filename? fopen(filename, "w+b") : stdout;
  98879. if(file == 0) {
  98880. encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
  98881. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  98882. }
  98883. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, is_ogg);
  98884. }
  98885. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_file(
  98886. FLAC__StreamEncoder *encoder,
  98887. const char *filename,
  98888. FLAC__StreamEncoderProgressCallback progress_callback,
  98889. void *client_data
  98890. )
  98891. {
  98892. return init_file_internal_enc(encoder, filename, progress_callback, client_data, /*is_ogg=*/false);
  98893. }
  98894. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_file(
  98895. FLAC__StreamEncoder *encoder,
  98896. const char *filename,
  98897. FLAC__StreamEncoderProgressCallback progress_callback,
  98898. void *client_data
  98899. )
  98900. {
  98901. return init_file_internal_enc(encoder, filename, progress_callback, client_data, /*is_ogg=*/true);
  98902. }
  98903. FLAC_API FLAC__bool FLAC__stream_encoder_finish(FLAC__StreamEncoder *encoder)
  98904. {
  98905. FLAC__bool error = false;
  98906. FLAC__ASSERT(0 != encoder);
  98907. FLAC__ASSERT(0 != encoder->private_);
  98908. FLAC__ASSERT(0 != encoder->protected_);
  98909. if(encoder->protected_->state == FLAC__STREAM_ENCODER_UNINITIALIZED)
  98910. return true;
  98911. if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK && !encoder->private_->is_being_deleted) {
  98912. if(encoder->private_->current_sample_number != 0) {
  98913. const FLAC__bool is_fractional_block = encoder->protected_->blocksize != encoder->private_->current_sample_number;
  98914. encoder->protected_->blocksize = encoder->private_->current_sample_number;
  98915. if(!process_frame_(encoder, is_fractional_block, /*is_last_block=*/true))
  98916. error = true;
  98917. }
  98918. }
  98919. if(encoder->protected_->do_md5)
  98920. FLAC__MD5Final(encoder->private_->streaminfo.data.stream_info.md5sum, &encoder->private_->md5context);
  98921. if(!encoder->private_->is_being_deleted) {
  98922. if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK) {
  98923. if(encoder->private_->seek_callback) {
  98924. #if FLAC__HAS_OGG
  98925. if(encoder->private_->is_ogg)
  98926. update_ogg_metadata_(encoder);
  98927. else
  98928. #endif
  98929. update_metadata_(encoder);
  98930. /* check if an error occurred while updating metadata */
  98931. if(encoder->protected_->state != FLAC__STREAM_ENCODER_OK)
  98932. error = true;
  98933. }
  98934. if(encoder->private_->metadata_callback)
  98935. encoder->private_->metadata_callback(encoder, &encoder->private_->streaminfo, encoder->private_->client_data);
  98936. }
  98937. if(encoder->protected_->verify && 0 != encoder->private_->verify.decoder && !FLAC__stream_decoder_finish(encoder->private_->verify.decoder)) {
  98938. if(!error)
  98939. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
  98940. error = true;
  98941. }
  98942. }
  98943. if(0 != encoder->private_->file) {
  98944. if(encoder->private_->file != stdout)
  98945. fclose(encoder->private_->file);
  98946. encoder->private_->file = 0;
  98947. }
  98948. #if FLAC__HAS_OGG
  98949. if(encoder->private_->is_ogg)
  98950. FLAC__ogg_encoder_aspect_finish(&encoder->protected_->ogg_encoder_aspect);
  98951. #endif
  98952. free_(encoder);
  98953. set_defaults_enc(encoder);
  98954. if(!error)
  98955. encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
  98956. return !error;
  98957. }
  98958. FLAC_API FLAC__bool FLAC__stream_encoder_set_ogg_serial_number(FLAC__StreamEncoder *encoder, long value)
  98959. {
  98960. FLAC__ASSERT(0 != encoder);
  98961. FLAC__ASSERT(0 != encoder->private_);
  98962. FLAC__ASSERT(0 != encoder->protected_);
  98963. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  98964. return false;
  98965. #if FLAC__HAS_OGG
  98966. /* can't check encoder->private_->is_ogg since that's not set until init time */
  98967. FLAC__ogg_encoder_aspect_set_serial_number(&encoder->protected_->ogg_encoder_aspect, value);
  98968. return true;
  98969. #else
  98970. (void)value;
  98971. return false;
  98972. #endif
  98973. }
  98974. FLAC_API FLAC__bool FLAC__stream_encoder_set_verify(FLAC__StreamEncoder *encoder, FLAC__bool value)
  98975. {
  98976. FLAC__ASSERT(0 != encoder);
  98977. FLAC__ASSERT(0 != encoder->private_);
  98978. FLAC__ASSERT(0 != encoder->protected_);
  98979. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  98980. return false;
  98981. #ifndef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
  98982. encoder->protected_->verify = value;
  98983. #endif
  98984. return true;
  98985. }
  98986. FLAC_API FLAC__bool FLAC__stream_encoder_set_streamable_subset(FLAC__StreamEncoder *encoder, FLAC__bool value)
  98987. {
  98988. FLAC__ASSERT(0 != encoder);
  98989. FLAC__ASSERT(0 != encoder->private_);
  98990. FLAC__ASSERT(0 != encoder->protected_);
  98991. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  98992. return false;
  98993. encoder->protected_->streamable_subset = value;
  98994. return true;
  98995. }
  98996. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_md5(FLAC__StreamEncoder *encoder, FLAC__bool value)
  98997. {
  98998. FLAC__ASSERT(0 != encoder);
  98999. FLAC__ASSERT(0 != encoder->private_);
  99000. FLAC__ASSERT(0 != encoder->protected_);
  99001. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  99002. return false;
  99003. encoder->protected_->do_md5 = value;
  99004. return true;
  99005. }
  99006. FLAC_API FLAC__bool FLAC__stream_encoder_set_channels(FLAC__StreamEncoder *encoder, unsigned value)
  99007. {
  99008. FLAC__ASSERT(0 != encoder);
  99009. FLAC__ASSERT(0 != encoder->private_);
  99010. FLAC__ASSERT(0 != encoder->protected_);
  99011. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  99012. return false;
  99013. encoder->protected_->channels = value;
  99014. return true;
  99015. }
  99016. FLAC_API FLAC__bool FLAC__stream_encoder_set_bits_per_sample(FLAC__StreamEncoder *encoder, unsigned value)
  99017. {
  99018. FLAC__ASSERT(0 != encoder);
  99019. FLAC__ASSERT(0 != encoder->private_);
  99020. FLAC__ASSERT(0 != encoder->protected_);
  99021. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  99022. return false;
  99023. encoder->protected_->bits_per_sample = value;
  99024. return true;
  99025. }
  99026. FLAC_API FLAC__bool FLAC__stream_encoder_set_sample_rate(FLAC__StreamEncoder *encoder, unsigned value)
  99027. {
  99028. FLAC__ASSERT(0 != encoder);
  99029. FLAC__ASSERT(0 != encoder->private_);
  99030. FLAC__ASSERT(0 != encoder->protected_);
  99031. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  99032. return false;
  99033. encoder->protected_->sample_rate = value;
  99034. return true;
  99035. }
  99036. FLAC_API FLAC__bool FLAC__stream_encoder_set_compression_level(FLAC__StreamEncoder *encoder, unsigned value)
  99037. {
  99038. FLAC__bool ok = true;
  99039. FLAC__ASSERT(0 != encoder);
  99040. FLAC__ASSERT(0 != encoder->private_);
  99041. FLAC__ASSERT(0 != encoder->protected_);
  99042. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  99043. return false;
  99044. if(value >= sizeof(compression_levels_)/sizeof(compression_levels_[0]))
  99045. value = sizeof(compression_levels_)/sizeof(compression_levels_[0]) - 1;
  99046. ok &= FLAC__stream_encoder_set_do_mid_side_stereo (encoder, compression_levels_[value].do_mid_side_stereo);
  99047. ok &= FLAC__stream_encoder_set_loose_mid_side_stereo (encoder, compression_levels_[value].loose_mid_side_stereo);
  99048. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99049. #if 0
  99050. /* was: */
  99051. ok &= FLAC__stream_encoder_set_apodization (encoder, compression_levels_[value].apodization);
  99052. /* but it's too hard to specify the string in a locale-specific way */
  99053. #else
  99054. encoder->protected_->num_apodizations = 1;
  99055. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  99056. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  99057. #endif
  99058. #endif
  99059. ok &= FLAC__stream_encoder_set_max_lpc_order (encoder, compression_levels_[value].max_lpc_order);
  99060. ok &= FLAC__stream_encoder_set_qlp_coeff_precision (encoder, compression_levels_[value].qlp_coeff_precision);
  99061. ok &= FLAC__stream_encoder_set_do_qlp_coeff_prec_search (encoder, compression_levels_[value].do_qlp_coeff_prec_search);
  99062. ok &= FLAC__stream_encoder_set_do_escape_coding (encoder, compression_levels_[value].do_escape_coding);
  99063. ok &= FLAC__stream_encoder_set_do_exhaustive_model_search (encoder, compression_levels_[value].do_exhaustive_model_search);
  99064. ok &= FLAC__stream_encoder_set_min_residual_partition_order(encoder, compression_levels_[value].min_residual_partition_order);
  99065. ok &= FLAC__stream_encoder_set_max_residual_partition_order(encoder, compression_levels_[value].max_residual_partition_order);
  99066. ok &= FLAC__stream_encoder_set_rice_parameter_search_dist (encoder, compression_levels_[value].rice_parameter_search_dist);
  99067. return ok;
  99068. }
  99069. FLAC_API FLAC__bool FLAC__stream_encoder_set_blocksize(FLAC__StreamEncoder *encoder, unsigned value)
  99070. {
  99071. FLAC__ASSERT(0 != encoder);
  99072. FLAC__ASSERT(0 != encoder->private_);
  99073. FLAC__ASSERT(0 != encoder->protected_);
  99074. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  99075. return false;
  99076. encoder->protected_->blocksize = value;
  99077. return true;
  99078. }
  99079. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
  99080. {
  99081. FLAC__ASSERT(0 != encoder);
  99082. FLAC__ASSERT(0 != encoder->private_);
  99083. FLAC__ASSERT(0 != encoder->protected_);
  99084. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  99085. return false;
  99086. encoder->protected_->do_mid_side_stereo = value;
  99087. return true;
  99088. }
  99089. FLAC_API FLAC__bool FLAC__stream_encoder_set_loose_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
  99090. {
  99091. FLAC__ASSERT(0 != encoder);
  99092. FLAC__ASSERT(0 != encoder->private_);
  99093. FLAC__ASSERT(0 != encoder->protected_);
  99094. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  99095. return false;
  99096. encoder->protected_->loose_mid_side_stereo = value;
  99097. return true;
  99098. }
  99099. /*@@@@add to tests*/
  99100. FLAC_API FLAC__bool FLAC__stream_encoder_set_apodization(FLAC__StreamEncoder *encoder, const char *specification)
  99101. {
  99102. FLAC__ASSERT(0 != encoder);
  99103. FLAC__ASSERT(0 != encoder->private_);
  99104. FLAC__ASSERT(0 != encoder->protected_);
  99105. FLAC__ASSERT(0 != specification);
  99106. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  99107. return false;
  99108. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  99109. (void)specification; /* silently ignore since we haven't integerized; will always use a rectangular window */
  99110. #else
  99111. encoder->protected_->num_apodizations = 0;
  99112. while(1) {
  99113. const char *s = strchr(specification, ';');
  99114. const size_t n = s? (size_t)(s - specification) : strlen(specification);
  99115. if (n==8 && 0 == strncmp("bartlett" , specification, n))
  99116. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT;
  99117. else if(n==13 && 0 == strncmp("bartlett_hann", specification, n))
  99118. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT_HANN;
  99119. else if(n==8 && 0 == strncmp("blackman" , specification, n))
  99120. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN;
  99121. else if(n==26 && 0 == strncmp("blackman_harris_4term_92db", specification, n))
  99122. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE;
  99123. else if(n==6 && 0 == strncmp("connes" , specification, n))
  99124. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_CONNES;
  99125. else if(n==7 && 0 == strncmp("flattop" , specification, n))
  99126. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_FLATTOP;
  99127. else if(n>7 && 0 == strncmp("gauss(" , specification, 6)) {
  99128. FLAC__real stddev = (FLAC__real)strtod(specification+6, 0);
  99129. if (stddev > 0.0 && stddev <= 0.5) {
  99130. encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.gauss.stddev = stddev;
  99131. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_GAUSS;
  99132. }
  99133. }
  99134. else if(n==7 && 0 == strncmp("hamming" , specification, n))
  99135. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HAMMING;
  99136. else if(n==4 && 0 == strncmp("hann" , specification, n))
  99137. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HANN;
  99138. else if(n==13 && 0 == strncmp("kaiser_bessel", specification, n))
  99139. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_KAISER_BESSEL;
  99140. else if(n==7 && 0 == strncmp("nuttall" , specification, n))
  99141. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_NUTTALL;
  99142. else if(n==9 && 0 == strncmp("rectangle" , specification, n))
  99143. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_RECTANGLE;
  99144. else if(n==8 && 0 == strncmp("triangle" , specification, n))
  99145. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TRIANGLE;
  99146. else if(n>7 && 0 == strncmp("tukey(" , specification, 6)) {
  99147. FLAC__real p = (FLAC__real)strtod(specification+6, 0);
  99148. if (p >= 0.0 && p <= 1.0) {
  99149. encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.tukey.p = p;
  99150. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TUKEY;
  99151. }
  99152. }
  99153. else if(n==5 && 0 == strncmp("welch" , specification, n))
  99154. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_WELCH;
  99155. if (encoder->protected_->num_apodizations == 32)
  99156. break;
  99157. if (s)
  99158. specification = s+1;
  99159. else
  99160. break;
  99161. }
  99162. if(encoder->protected_->num_apodizations == 0) {
  99163. encoder->protected_->num_apodizations = 1;
  99164. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  99165. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  99166. }
  99167. #endif
  99168. return true;
  99169. }
  99170. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_lpc_order(FLAC__StreamEncoder *encoder, unsigned value)
  99171. {
  99172. FLAC__ASSERT(0 != encoder);
  99173. FLAC__ASSERT(0 != encoder->private_);
  99174. FLAC__ASSERT(0 != encoder->protected_);
  99175. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  99176. return false;
  99177. encoder->protected_->max_lpc_order = value;
  99178. return true;
  99179. }
  99180. FLAC_API FLAC__bool FLAC__stream_encoder_set_qlp_coeff_precision(FLAC__StreamEncoder *encoder, unsigned value)
  99181. {
  99182. FLAC__ASSERT(0 != encoder);
  99183. FLAC__ASSERT(0 != encoder->private_);
  99184. FLAC__ASSERT(0 != encoder->protected_);
  99185. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  99186. return false;
  99187. encoder->protected_->qlp_coeff_precision = value;
  99188. return true;
  99189. }
  99190. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_qlp_coeff_prec_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
  99191. {
  99192. FLAC__ASSERT(0 != encoder);
  99193. FLAC__ASSERT(0 != encoder->private_);
  99194. FLAC__ASSERT(0 != encoder->protected_);
  99195. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  99196. return false;
  99197. encoder->protected_->do_qlp_coeff_prec_search = value;
  99198. return true;
  99199. }
  99200. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_escape_coding(FLAC__StreamEncoder *encoder, FLAC__bool value)
  99201. {
  99202. FLAC__ASSERT(0 != encoder);
  99203. FLAC__ASSERT(0 != encoder->private_);
  99204. FLAC__ASSERT(0 != encoder->protected_);
  99205. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  99206. return false;
  99207. #if 0
  99208. /*@@@ deprecated: */
  99209. encoder->protected_->do_escape_coding = value;
  99210. #else
  99211. (void)value;
  99212. #endif
  99213. return true;
  99214. }
  99215. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_exhaustive_model_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
  99216. {
  99217. FLAC__ASSERT(0 != encoder);
  99218. FLAC__ASSERT(0 != encoder->private_);
  99219. FLAC__ASSERT(0 != encoder->protected_);
  99220. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  99221. return false;
  99222. encoder->protected_->do_exhaustive_model_search = value;
  99223. return true;
  99224. }
  99225. FLAC_API FLAC__bool FLAC__stream_encoder_set_min_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
  99226. {
  99227. FLAC__ASSERT(0 != encoder);
  99228. FLAC__ASSERT(0 != encoder->private_);
  99229. FLAC__ASSERT(0 != encoder->protected_);
  99230. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  99231. return false;
  99232. encoder->protected_->min_residual_partition_order = value;
  99233. return true;
  99234. }
  99235. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
  99236. {
  99237. FLAC__ASSERT(0 != encoder);
  99238. FLAC__ASSERT(0 != encoder->private_);
  99239. FLAC__ASSERT(0 != encoder->protected_);
  99240. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  99241. return false;
  99242. encoder->protected_->max_residual_partition_order = value;
  99243. return true;
  99244. }
  99245. FLAC_API FLAC__bool FLAC__stream_encoder_set_rice_parameter_search_dist(FLAC__StreamEncoder *encoder, unsigned value)
  99246. {
  99247. FLAC__ASSERT(0 != encoder);
  99248. FLAC__ASSERT(0 != encoder->private_);
  99249. FLAC__ASSERT(0 != encoder->protected_);
  99250. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  99251. return false;
  99252. #if 0
  99253. /*@@@ deprecated: */
  99254. encoder->protected_->rice_parameter_search_dist = value;
  99255. #else
  99256. (void)value;
  99257. #endif
  99258. return true;
  99259. }
  99260. FLAC_API FLAC__bool FLAC__stream_encoder_set_total_samples_estimate(FLAC__StreamEncoder *encoder, FLAC__uint64 value)
  99261. {
  99262. FLAC__ASSERT(0 != encoder);
  99263. FLAC__ASSERT(0 != encoder->private_);
  99264. FLAC__ASSERT(0 != encoder->protected_);
  99265. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  99266. return false;
  99267. encoder->protected_->total_samples_estimate = value;
  99268. return true;
  99269. }
  99270. FLAC_API FLAC__bool FLAC__stream_encoder_set_metadata(FLAC__StreamEncoder *encoder, FLAC__StreamMetadata **metadata, unsigned num_blocks)
  99271. {
  99272. FLAC__ASSERT(0 != encoder);
  99273. FLAC__ASSERT(0 != encoder->private_);
  99274. FLAC__ASSERT(0 != encoder->protected_);
  99275. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  99276. return false;
  99277. if(0 == metadata)
  99278. num_blocks = 0;
  99279. if(0 == num_blocks)
  99280. metadata = 0;
  99281. /* realloc() does not do exactly what we want so... */
  99282. if(encoder->protected_->metadata) {
  99283. free(encoder->protected_->metadata);
  99284. encoder->protected_->metadata = 0;
  99285. encoder->protected_->num_metadata_blocks = 0;
  99286. }
  99287. if(num_blocks) {
  99288. FLAC__StreamMetadata **m;
  99289. if(0 == (m = (FLAC__StreamMetadata**)safe_malloc_mul_2op_(sizeof(m[0]), /*times*/num_blocks)))
  99290. return false;
  99291. memcpy(m, metadata, sizeof(m[0]) * num_blocks);
  99292. encoder->protected_->metadata = m;
  99293. encoder->protected_->num_metadata_blocks = num_blocks;
  99294. }
  99295. #if FLAC__HAS_OGG
  99296. if(!FLAC__ogg_encoder_aspect_set_num_metadata(&encoder->protected_->ogg_encoder_aspect, num_blocks))
  99297. return false;
  99298. #endif
  99299. return true;
  99300. }
  99301. /*
  99302. * These three functions are not static, but not publically exposed in
  99303. * include/FLAC/ either. They are used by the test suite.
  99304. */
  99305. FLAC_API FLAC__bool FLAC__stream_encoder_disable_constant_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  99306. {
  99307. FLAC__ASSERT(0 != encoder);
  99308. FLAC__ASSERT(0 != encoder->private_);
  99309. FLAC__ASSERT(0 != encoder->protected_);
  99310. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  99311. return false;
  99312. encoder->private_->disable_constant_subframes = value;
  99313. return true;
  99314. }
  99315. FLAC_API FLAC__bool FLAC__stream_encoder_disable_fixed_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  99316. {
  99317. FLAC__ASSERT(0 != encoder);
  99318. FLAC__ASSERT(0 != encoder->private_);
  99319. FLAC__ASSERT(0 != encoder->protected_);
  99320. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  99321. return false;
  99322. encoder->private_->disable_fixed_subframes = value;
  99323. return true;
  99324. }
  99325. FLAC_API FLAC__bool FLAC__stream_encoder_disable_verbatim_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  99326. {
  99327. FLAC__ASSERT(0 != encoder);
  99328. FLAC__ASSERT(0 != encoder->private_);
  99329. FLAC__ASSERT(0 != encoder->protected_);
  99330. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  99331. return false;
  99332. encoder->private_->disable_verbatim_subframes = value;
  99333. return true;
  99334. }
  99335. FLAC_API FLAC__StreamEncoderState FLAC__stream_encoder_get_state(const FLAC__StreamEncoder *encoder)
  99336. {
  99337. FLAC__ASSERT(0 != encoder);
  99338. FLAC__ASSERT(0 != encoder->private_);
  99339. FLAC__ASSERT(0 != encoder->protected_);
  99340. return encoder->protected_->state;
  99341. }
  99342. FLAC_API FLAC__StreamDecoderState FLAC__stream_encoder_get_verify_decoder_state(const FLAC__StreamEncoder *encoder)
  99343. {
  99344. FLAC__ASSERT(0 != encoder);
  99345. FLAC__ASSERT(0 != encoder->private_);
  99346. FLAC__ASSERT(0 != encoder->protected_);
  99347. if(encoder->protected_->verify)
  99348. return FLAC__stream_decoder_get_state(encoder->private_->verify.decoder);
  99349. else
  99350. return FLAC__STREAM_DECODER_UNINITIALIZED;
  99351. }
  99352. FLAC_API const char *FLAC__stream_encoder_get_resolved_state_string(const FLAC__StreamEncoder *encoder)
  99353. {
  99354. FLAC__ASSERT(0 != encoder);
  99355. FLAC__ASSERT(0 != encoder->private_);
  99356. FLAC__ASSERT(0 != encoder->protected_);
  99357. if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR)
  99358. return FLAC__StreamEncoderStateString[encoder->protected_->state];
  99359. else
  99360. return FLAC__stream_decoder_get_resolved_state_string(encoder->private_->verify.decoder);
  99361. }
  99362. FLAC_API void FLAC__stream_encoder_get_verify_decoder_error_stats(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_sample, unsigned *frame_number, unsigned *channel, unsigned *sample, FLAC__int32 *expected, FLAC__int32 *got)
  99363. {
  99364. FLAC__ASSERT(0 != encoder);
  99365. FLAC__ASSERT(0 != encoder->private_);
  99366. FLAC__ASSERT(0 != encoder->protected_);
  99367. if(0 != absolute_sample)
  99368. *absolute_sample = encoder->private_->verify.error_stats.absolute_sample;
  99369. if(0 != frame_number)
  99370. *frame_number = encoder->private_->verify.error_stats.frame_number;
  99371. if(0 != channel)
  99372. *channel = encoder->private_->verify.error_stats.channel;
  99373. if(0 != sample)
  99374. *sample = encoder->private_->verify.error_stats.sample;
  99375. if(0 != expected)
  99376. *expected = encoder->private_->verify.error_stats.expected;
  99377. if(0 != got)
  99378. *got = encoder->private_->verify.error_stats.got;
  99379. }
  99380. FLAC_API FLAC__bool FLAC__stream_encoder_get_verify(const FLAC__StreamEncoder *encoder)
  99381. {
  99382. FLAC__ASSERT(0 != encoder);
  99383. FLAC__ASSERT(0 != encoder->private_);
  99384. FLAC__ASSERT(0 != encoder->protected_);
  99385. return encoder->protected_->verify;
  99386. }
  99387. FLAC_API FLAC__bool FLAC__stream_encoder_get_streamable_subset(const FLAC__StreamEncoder *encoder)
  99388. {
  99389. FLAC__ASSERT(0 != encoder);
  99390. FLAC__ASSERT(0 != encoder->private_);
  99391. FLAC__ASSERT(0 != encoder->protected_);
  99392. return encoder->protected_->streamable_subset;
  99393. }
  99394. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_md5(const FLAC__StreamEncoder *encoder)
  99395. {
  99396. FLAC__ASSERT(0 != encoder);
  99397. FLAC__ASSERT(0 != encoder->private_);
  99398. FLAC__ASSERT(0 != encoder->protected_);
  99399. return encoder->protected_->do_md5;
  99400. }
  99401. FLAC_API unsigned FLAC__stream_encoder_get_channels(const FLAC__StreamEncoder *encoder)
  99402. {
  99403. FLAC__ASSERT(0 != encoder);
  99404. FLAC__ASSERT(0 != encoder->private_);
  99405. FLAC__ASSERT(0 != encoder->protected_);
  99406. return encoder->protected_->channels;
  99407. }
  99408. FLAC_API unsigned FLAC__stream_encoder_get_bits_per_sample(const FLAC__StreamEncoder *encoder)
  99409. {
  99410. FLAC__ASSERT(0 != encoder);
  99411. FLAC__ASSERT(0 != encoder->private_);
  99412. FLAC__ASSERT(0 != encoder->protected_);
  99413. return encoder->protected_->bits_per_sample;
  99414. }
  99415. FLAC_API unsigned FLAC__stream_encoder_get_sample_rate(const FLAC__StreamEncoder *encoder)
  99416. {
  99417. FLAC__ASSERT(0 != encoder);
  99418. FLAC__ASSERT(0 != encoder->private_);
  99419. FLAC__ASSERT(0 != encoder->protected_);
  99420. return encoder->protected_->sample_rate;
  99421. }
  99422. FLAC_API unsigned FLAC__stream_encoder_get_blocksize(const FLAC__StreamEncoder *encoder)
  99423. {
  99424. FLAC__ASSERT(0 != encoder);
  99425. FLAC__ASSERT(0 != encoder->private_);
  99426. FLAC__ASSERT(0 != encoder->protected_);
  99427. return encoder->protected_->blocksize;
  99428. }
  99429. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_mid_side_stereo(const FLAC__StreamEncoder *encoder)
  99430. {
  99431. FLAC__ASSERT(0 != encoder);
  99432. FLAC__ASSERT(0 != encoder->private_);
  99433. FLAC__ASSERT(0 != encoder->protected_);
  99434. return encoder->protected_->do_mid_side_stereo;
  99435. }
  99436. FLAC_API FLAC__bool FLAC__stream_encoder_get_loose_mid_side_stereo(const FLAC__StreamEncoder *encoder)
  99437. {
  99438. FLAC__ASSERT(0 != encoder);
  99439. FLAC__ASSERT(0 != encoder->private_);
  99440. FLAC__ASSERT(0 != encoder->protected_);
  99441. return encoder->protected_->loose_mid_side_stereo;
  99442. }
  99443. FLAC_API unsigned FLAC__stream_encoder_get_max_lpc_order(const FLAC__StreamEncoder *encoder)
  99444. {
  99445. FLAC__ASSERT(0 != encoder);
  99446. FLAC__ASSERT(0 != encoder->private_);
  99447. FLAC__ASSERT(0 != encoder->protected_);
  99448. return encoder->protected_->max_lpc_order;
  99449. }
  99450. FLAC_API unsigned FLAC__stream_encoder_get_qlp_coeff_precision(const FLAC__StreamEncoder *encoder)
  99451. {
  99452. FLAC__ASSERT(0 != encoder);
  99453. FLAC__ASSERT(0 != encoder->private_);
  99454. FLAC__ASSERT(0 != encoder->protected_);
  99455. return encoder->protected_->qlp_coeff_precision;
  99456. }
  99457. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_qlp_coeff_prec_search(const FLAC__StreamEncoder *encoder)
  99458. {
  99459. FLAC__ASSERT(0 != encoder);
  99460. FLAC__ASSERT(0 != encoder->private_);
  99461. FLAC__ASSERT(0 != encoder->protected_);
  99462. return encoder->protected_->do_qlp_coeff_prec_search;
  99463. }
  99464. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_escape_coding(const FLAC__StreamEncoder *encoder)
  99465. {
  99466. FLAC__ASSERT(0 != encoder);
  99467. FLAC__ASSERT(0 != encoder->private_);
  99468. FLAC__ASSERT(0 != encoder->protected_);
  99469. return encoder->protected_->do_escape_coding;
  99470. }
  99471. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_exhaustive_model_search(const FLAC__StreamEncoder *encoder)
  99472. {
  99473. FLAC__ASSERT(0 != encoder);
  99474. FLAC__ASSERT(0 != encoder->private_);
  99475. FLAC__ASSERT(0 != encoder->protected_);
  99476. return encoder->protected_->do_exhaustive_model_search;
  99477. }
  99478. FLAC_API unsigned FLAC__stream_encoder_get_min_residual_partition_order(const FLAC__StreamEncoder *encoder)
  99479. {
  99480. FLAC__ASSERT(0 != encoder);
  99481. FLAC__ASSERT(0 != encoder->private_);
  99482. FLAC__ASSERT(0 != encoder->protected_);
  99483. return encoder->protected_->min_residual_partition_order;
  99484. }
  99485. FLAC_API unsigned FLAC__stream_encoder_get_max_residual_partition_order(const FLAC__StreamEncoder *encoder)
  99486. {
  99487. FLAC__ASSERT(0 != encoder);
  99488. FLAC__ASSERT(0 != encoder->private_);
  99489. FLAC__ASSERT(0 != encoder->protected_);
  99490. return encoder->protected_->max_residual_partition_order;
  99491. }
  99492. FLAC_API unsigned FLAC__stream_encoder_get_rice_parameter_search_dist(const FLAC__StreamEncoder *encoder)
  99493. {
  99494. FLAC__ASSERT(0 != encoder);
  99495. FLAC__ASSERT(0 != encoder->private_);
  99496. FLAC__ASSERT(0 != encoder->protected_);
  99497. return encoder->protected_->rice_parameter_search_dist;
  99498. }
  99499. FLAC_API FLAC__uint64 FLAC__stream_encoder_get_total_samples_estimate(const FLAC__StreamEncoder *encoder)
  99500. {
  99501. FLAC__ASSERT(0 != encoder);
  99502. FLAC__ASSERT(0 != encoder->private_);
  99503. FLAC__ASSERT(0 != encoder->protected_);
  99504. return encoder->protected_->total_samples_estimate;
  99505. }
  99506. FLAC_API FLAC__bool FLAC__stream_encoder_process(FLAC__StreamEncoder *encoder, const FLAC__int32 * const buffer[], unsigned samples)
  99507. {
  99508. unsigned i, j = 0, channel;
  99509. const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
  99510. FLAC__ASSERT(0 != encoder);
  99511. FLAC__ASSERT(0 != encoder->private_);
  99512. FLAC__ASSERT(0 != encoder->protected_);
  99513. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  99514. do {
  99515. const unsigned n = min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j);
  99516. if(encoder->protected_->verify)
  99517. append_to_verify_fifo_(&encoder->private_->verify.input_fifo, buffer, j, channels, n);
  99518. for(channel = 0; channel < channels; channel++)
  99519. memcpy(&encoder->private_->integer_signal[channel][encoder->private_->current_sample_number], &buffer[channel][j], sizeof(buffer[channel][0]) * n);
  99520. if(encoder->protected_->do_mid_side_stereo) {
  99521. FLAC__ASSERT(channels == 2);
  99522. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  99523. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  99524. encoder->private_->integer_signal_mid_side[1][i] = buffer[0][j] - buffer[1][j];
  99525. encoder->private_->integer_signal_mid_side[0][i] = (buffer[0][j] + buffer[1][j]) >> 1; /* NOTE: not the same as 'mid = (buffer[0][j] + buffer[1][j]) / 2' ! */
  99526. }
  99527. }
  99528. else
  99529. j += n;
  99530. encoder->private_->current_sample_number += n;
  99531. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  99532. if(encoder->private_->current_sample_number > blocksize) {
  99533. FLAC__ASSERT(encoder->private_->current_sample_number == blocksize+OVERREAD_);
  99534. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  99535. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  99536. return false;
  99537. /* move unprocessed overread samples to beginnings of arrays */
  99538. for(channel = 0; channel < channels; channel++)
  99539. encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][blocksize];
  99540. if(encoder->protected_->do_mid_side_stereo) {
  99541. encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][blocksize];
  99542. encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][blocksize];
  99543. }
  99544. encoder->private_->current_sample_number = 1;
  99545. }
  99546. } while(j < samples);
  99547. return true;
  99548. }
  99549. FLAC_API FLAC__bool FLAC__stream_encoder_process_interleaved(FLAC__StreamEncoder *encoder, const FLAC__int32 buffer[], unsigned samples)
  99550. {
  99551. unsigned i, j, k, channel;
  99552. FLAC__int32 x, mid, side;
  99553. const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
  99554. FLAC__ASSERT(0 != encoder);
  99555. FLAC__ASSERT(0 != encoder->private_);
  99556. FLAC__ASSERT(0 != encoder->protected_);
  99557. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  99558. j = k = 0;
  99559. /*
  99560. * we have several flavors of the same basic loop, optimized for
  99561. * different conditions:
  99562. */
  99563. if(encoder->protected_->do_mid_side_stereo && channels == 2) {
  99564. /*
  99565. * stereo coding: unroll channel loop
  99566. */
  99567. do {
  99568. if(encoder->protected_->verify)
  99569. append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j));
  99570. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  99571. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  99572. encoder->private_->integer_signal[0][i] = mid = side = buffer[k++];
  99573. x = buffer[k++];
  99574. encoder->private_->integer_signal[1][i] = x;
  99575. mid += x;
  99576. side -= x;
  99577. mid >>= 1; /* NOTE: not the same as 'mid = (left + right) / 2' ! */
  99578. encoder->private_->integer_signal_mid_side[1][i] = side;
  99579. encoder->private_->integer_signal_mid_side[0][i] = mid;
  99580. }
  99581. encoder->private_->current_sample_number = i;
  99582. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  99583. if(i > blocksize) {
  99584. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  99585. return false;
  99586. /* move unprocessed overread samples to beginnings of arrays */
  99587. FLAC__ASSERT(i == blocksize+OVERREAD_);
  99588. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  99589. encoder->private_->integer_signal[0][0] = encoder->private_->integer_signal[0][blocksize];
  99590. encoder->private_->integer_signal[1][0] = encoder->private_->integer_signal[1][blocksize];
  99591. encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][blocksize];
  99592. encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][blocksize];
  99593. encoder->private_->current_sample_number = 1;
  99594. }
  99595. } while(j < samples);
  99596. }
  99597. else {
  99598. /*
  99599. * independent channel coding: buffer each channel in inner loop
  99600. */
  99601. do {
  99602. if(encoder->protected_->verify)
  99603. append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j));
  99604. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  99605. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  99606. for(channel = 0; channel < channels; channel++)
  99607. encoder->private_->integer_signal[channel][i] = buffer[k++];
  99608. }
  99609. encoder->private_->current_sample_number = i;
  99610. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  99611. if(i > blocksize) {
  99612. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  99613. return false;
  99614. /* move unprocessed overread samples to beginnings of arrays */
  99615. FLAC__ASSERT(i == blocksize+OVERREAD_);
  99616. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  99617. for(channel = 0; channel < channels; channel++)
  99618. encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][blocksize];
  99619. encoder->private_->current_sample_number = 1;
  99620. }
  99621. } while(j < samples);
  99622. }
  99623. return true;
  99624. }
  99625. /***********************************************************************
  99626. *
  99627. * Private class methods
  99628. *
  99629. ***********************************************************************/
  99630. void set_defaults_enc(FLAC__StreamEncoder *encoder)
  99631. {
  99632. FLAC__ASSERT(0 != encoder);
  99633. #ifdef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
  99634. encoder->protected_->verify = true;
  99635. #else
  99636. encoder->protected_->verify = false;
  99637. #endif
  99638. encoder->protected_->streamable_subset = true;
  99639. encoder->protected_->do_md5 = true;
  99640. encoder->protected_->do_mid_side_stereo = false;
  99641. encoder->protected_->loose_mid_side_stereo = false;
  99642. encoder->protected_->channels = 2;
  99643. encoder->protected_->bits_per_sample = 16;
  99644. encoder->protected_->sample_rate = 44100;
  99645. encoder->protected_->blocksize = 0;
  99646. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99647. encoder->protected_->num_apodizations = 1;
  99648. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  99649. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  99650. #endif
  99651. encoder->protected_->max_lpc_order = 0;
  99652. encoder->protected_->qlp_coeff_precision = 0;
  99653. encoder->protected_->do_qlp_coeff_prec_search = false;
  99654. encoder->protected_->do_exhaustive_model_search = false;
  99655. encoder->protected_->do_escape_coding = false;
  99656. encoder->protected_->min_residual_partition_order = 0;
  99657. encoder->protected_->max_residual_partition_order = 0;
  99658. encoder->protected_->rice_parameter_search_dist = 0;
  99659. encoder->protected_->total_samples_estimate = 0;
  99660. encoder->protected_->metadata = 0;
  99661. encoder->protected_->num_metadata_blocks = 0;
  99662. encoder->private_->seek_table = 0;
  99663. encoder->private_->disable_constant_subframes = false;
  99664. encoder->private_->disable_fixed_subframes = false;
  99665. encoder->private_->disable_verbatim_subframes = false;
  99666. #if FLAC__HAS_OGG
  99667. encoder->private_->is_ogg = false;
  99668. #endif
  99669. encoder->private_->read_callback = 0;
  99670. encoder->private_->write_callback = 0;
  99671. encoder->private_->seek_callback = 0;
  99672. encoder->private_->tell_callback = 0;
  99673. encoder->private_->metadata_callback = 0;
  99674. encoder->private_->progress_callback = 0;
  99675. encoder->private_->client_data = 0;
  99676. #if FLAC__HAS_OGG
  99677. FLAC__ogg_encoder_aspect_set_defaults(&encoder->protected_->ogg_encoder_aspect);
  99678. #endif
  99679. }
  99680. void free_(FLAC__StreamEncoder *encoder)
  99681. {
  99682. unsigned i, channel;
  99683. FLAC__ASSERT(0 != encoder);
  99684. if(encoder->protected_->metadata) {
  99685. free(encoder->protected_->metadata);
  99686. encoder->protected_->metadata = 0;
  99687. encoder->protected_->num_metadata_blocks = 0;
  99688. }
  99689. for(i = 0; i < encoder->protected_->channels; i++) {
  99690. if(0 != encoder->private_->integer_signal_unaligned[i]) {
  99691. free(encoder->private_->integer_signal_unaligned[i]);
  99692. encoder->private_->integer_signal_unaligned[i] = 0;
  99693. }
  99694. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99695. if(0 != encoder->private_->real_signal_unaligned[i]) {
  99696. free(encoder->private_->real_signal_unaligned[i]);
  99697. encoder->private_->real_signal_unaligned[i] = 0;
  99698. }
  99699. #endif
  99700. }
  99701. for(i = 0; i < 2; i++) {
  99702. if(0 != encoder->private_->integer_signal_mid_side_unaligned[i]) {
  99703. free(encoder->private_->integer_signal_mid_side_unaligned[i]);
  99704. encoder->private_->integer_signal_mid_side_unaligned[i] = 0;
  99705. }
  99706. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99707. if(0 != encoder->private_->real_signal_mid_side_unaligned[i]) {
  99708. free(encoder->private_->real_signal_mid_side_unaligned[i]);
  99709. encoder->private_->real_signal_mid_side_unaligned[i] = 0;
  99710. }
  99711. #endif
  99712. }
  99713. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99714. for(i = 0; i < encoder->protected_->num_apodizations; i++) {
  99715. if(0 != encoder->private_->window_unaligned[i]) {
  99716. free(encoder->private_->window_unaligned[i]);
  99717. encoder->private_->window_unaligned[i] = 0;
  99718. }
  99719. }
  99720. if(0 != encoder->private_->windowed_signal_unaligned) {
  99721. free(encoder->private_->windowed_signal_unaligned);
  99722. encoder->private_->windowed_signal_unaligned = 0;
  99723. }
  99724. #endif
  99725. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  99726. for(i = 0; i < 2; i++) {
  99727. if(0 != encoder->private_->residual_workspace_unaligned[channel][i]) {
  99728. free(encoder->private_->residual_workspace_unaligned[channel][i]);
  99729. encoder->private_->residual_workspace_unaligned[channel][i] = 0;
  99730. }
  99731. }
  99732. }
  99733. for(channel = 0; channel < 2; channel++) {
  99734. for(i = 0; i < 2; i++) {
  99735. if(0 != encoder->private_->residual_workspace_mid_side_unaligned[channel][i]) {
  99736. free(encoder->private_->residual_workspace_mid_side_unaligned[channel][i]);
  99737. encoder->private_->residual_workspace_mid_side_unaligned[channel][i] = 0;
  99738. }
  99739. }
  99740. }
  99741. if(0 != encoder->private_->abs_residual_partition_sums_unaligned) {
  99742. free(encoder->private_->abs_residual_partition_sums_unaligned);
  99743. encoder->private_->abs_residual_partition_sums_unaligned = 0;
  99744. }
  99745. if(0 != encoder->private_->raw_bits_per_partition_unaligned) {
  99746. free(encoder->private_->raw_bits_per_partition_unaligned);
  99747. encoder->private_->raw_bits_per_partition_unaligned = 0;
  99748. }
  99749. if(encoder->protected_->verify) {
  99750. for(i = 0; i < encoder->protected_->channels; i++) {
  99751. if(0 != encoder->private_->verify.input_fifo.data[i]) {
  99752. free(encoder->private_->verify.input_fifo.data[i]);
  99753. encoder->private_->verify.input_fifo.data[i] = 0;
  99754. }
  99755. }
  99756. }
  99757. FLAC__bitwriter_free(encoder->private_->frame);
  99758. }
  99759. FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_blocksize)
  99760. {
  99761. FLAC__bool ok;
  99762. unsigned i, channel;
  99763. FLAC__ASSERT(new_blocksize > 0);
  99764. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  99765. FLAC__ASSERT(encoder->private_->current_sample_number == 0);
  99766. /* To avoid excessive malloc'ing, we only grow the buffer; no shrinking. */
  99767. if(new_blocksize <= encoder->private_->input_capacity)
  99768. return true;
  99769. ok = true;
  99770. /* WATCHOUT: FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx()
  99771. * requires that the input arrays (in our case the integer signals)
  99772. * have a buffer of up to 3 zeroes in front (at negative indices) for
  99773. * alignment purposes; we use 4 in front to keep the data well-aligned.
  99774. */
  99775. for(i = 0; ok && i < encoder->protected_->channels; i++) {
  99776. ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize+4+OVERREAD_, &encoder->private_->integer_signal_unaligned[i], &encoder->private_->integer_signal[i]);
  99777. memset(encoder->private_->integer_signal[i], 0, sizeof(FLAC__int32)*4);
  99778. encoder->private_->integer_signal[i] += 4;
  99779. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99780. #if 0 /* @@@ currently unused */
  99781. if(encoder->protected_->max_lpc_order > 0)
  99782. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize+OVERREAD_, &encoder->private_->real_signal_unaligned[i], &encoder->private_->real_signal[i]);
  99783. #endif
  99784. #endif
  99785. }
  99786. for(i = 0; ok && i < 2; i++) {
  99787. ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize+4+OVERREAD_, &encoder->private_->integer_signal_mid_side_unaligned[i], &encoder->private_->integer_signal_mid_side[i]);
  99788. memset(encoder->private_->integer_signal_mid_side[i], 0, sizeof(FLAC__int32)*4);
  99789. encoder->private_->integer_signal_mid_side[i] += 4;
  99790. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99791. #if 0 /* @@@ currently unused */
  99792. if(encoder->protected_->max_lpc_order > 0)
  99793. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize+OVERREAD_, &encoder->private_->real_signal_mid_side_unaligned[i], &encoder->private_->real_signal_mid_side[i]);
  99794. #endif
  99795. #endif
  99796. }
  99797. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99798. if(ok && encoder->protected_->max_lpc_order > 0) {
  99799. for(i = 0; ok && i < encoder->protected_->num_apodizations; i++)
  99800. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->window_unaligned[i], &encoder->private_->window[i]);
  99801. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->windowed_signal_unaligned, &encoder->private_->windowed_signal);
  99802. }
  99803. #endif
  99804. for(channel = 0; ok && channel < encoder->protected_->channels; channel++) {
  99805. for(i = 0; ok && i < 2; i++) {
  99806. ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize, &encoder->private_->residual_workspace_unaligned[channel][i], &encoder->private_->residual_workspace[channel][i]);
  99807. }
  99808. }
  99809. for(channel = 0; ok && channel < 2; channel++) {
  99810. for(i = 0; ok && i < 2; i++) {
  99811. ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize, &encoder->private_->residual_workspace_mid_side_unaligned[channel][i], &encoder->private_->residual_workspace_mid_side[channel][i]);
  99812. }
  99813. }
  99814. /* the *2 is an approximation to the series 1 + 1/2 + 1/4 + ... that sums tree occupies in a flat array */
  99815. /*@@@ new_blocksize*2 is too pessimistic, but to fix, we need smarter logic because a smaller new_blocksize can actually increase the # of partitions; would require moving this out into a separate function, then checking its capacity against the need of the current blocksize&min/max_partition_order (and maybe predictor order) */
  99816. ok = ok && FLAC__memory_alloc_aligned_uint64_array(new_blocksize * 2, &encoder->private_->abs_residual_partition_sums_unaligned, &encoder->private_->abs_residual_partition_sums);
  99817. if(encoder->protected_->do_escape_coding)
  99818. ok = ok && FLAC__memory_alloc_aligned_unsigned_array(new_blocksize * 2, &encoder->private_->raw_bits_per_partition_unaligned, &encoder->private_->raw_bits_per_partition);
  99819. /* now adjust the windows if the blocksize has changed */
  99820. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99821. if(ok && new_blocksize != encoder->private_->input_capacity && encoder->protected_->max_lpc_order > 0) {
  99822. for(i = 0; ok && i < encoder->protected_->num_apodizations; i++) {
  99823. switch(encoder->protected_->apodizations[i].type) {
  99824. case FLAC__APODIZATION_BARTLETT:
  99825. FLAC__window_bartlett(encoder->private_->window[i], new_blocksize);
  99826. break;
  99827. case FLAC__APODIZATION_BARTLETT_HANN:
  99828. FLAC__window_bartlett_hann(encoder->private_->window[i], new_blocksize);
  99829. break;
  99830. case FLAC__APODIZATION_BLACKMAN:
  99831. FLAC__window_blackman(encoder->private_->window[i], new_blocksize);
  99832. break;
  99833. case FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE:
  99834. FLAC__window_blackman_harris_4term_92db_sidelobe(encoder->private_->window[i], new_blocksize);
  99835. break;
  99836. case FLAC__APODIZATION_CONNES:
  99837. FLAC__window_connes(encoder->private_->window[i], new_blocksize);
  99838. break;
  99839. case FLAC__APODIZATION_FLATTOP:
  99840. FLAC__window_flattop(encoder->private_->window[i], new_blocksize);
  99841. break;
  99842. case FLAC__APODIZATION_GAUSS:
  99843. FLAC__window_gauss(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.gauss.stddev);
  99844. break;
  99845. case FLAC__APODIZATION_HAMMING:
  99846. FLAC__window_hamming(encoder->private_->window[i], new_blocksize);
  99847. break;
  99848. case FLAC__APODIZATION_HANN:
  99849. FLAC__window_hann(encoder->private_->window[i], new_blocksize);
  99850. break;
  99851. case FLAC__APODIZATION_KAISER_BESSEL:
  99852. FLAC__window_kaiser_bessel(encoder->private_->window[i], new_blocksize);
  99853. break;
  99854. case FLAC__APODIZATION_NUTTALL:
  99855. FLAC__window_nuttall(encoder->private_->window[i], new_blocksize);
  99856. break;
  99857. case FLAC__APODIZATION_RECTANGLE:
  99858. FLAC__window_rectangle(encoder->private_->window[i], new_blocksize);
  99859. break;
  99860. case FLAC__APODIZATION_TRIANGLE:
  99861. FLAC__window_triangle(encoder->private_->window[i], new_blocksize);
  99862. break;
  99863. case FLAC__APODIZATION_TUKEY:
  99864. FLAC__window_tukey(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.tukey.p);
  99865. break;
  99866. case FLAC__APODIZATION_WELCH:
  99867. FLAC__window_welch(encoder->private_->window[i], new_blocksize);
  99868. break;
  99869. default:
  99870. FLAC__ASSERT(0);
  99871. /* double protection */
  99872. FLAC__window_hann(encoder->private_->window[i], new_blocksize);
  99873. break;
  99874. }
  99875. }
  99876. }
  99877. #endif
  99878. if(ok)
  99879. encoder->private_->input_capacity = new_blocksize;
  99880. else
  99881. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  99882. return ok;
  99883. }
  99884. FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples, FLAC__bool is_last_block)
  99885. {
  99886. const FLAC__byte *buffer;
  99887. size_t bytes;
  99888. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
  99889. if(!FLAC__bitwriter_get_buffer(encoder->private_->frame, &buffer, &bytes)) {
  99890. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  99891. return false;
  99892. }
  99893. if(encoder->protected_->verify) {
  99894. encoder->private_->verify.output.data = buffer;
  99895. encoder->private_->verify.output.bytes = bytes;
  99896. if(encoder->private_->verify.state_hint == ENCODER_IN_MAGIC) {
  99897. encoder->private_->verify.needs_magic_hack = true;
  99898. }
  99899. else {
  99900. if(!FLAC__stream_decoder_process_single(encoder->private_->verify.decoder)) {
  99901. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  99902. FLAC__bitwriter_clear(encoder->private_->frame);
  99903. if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA)
  99904. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  99905. return false;
  99906. }
  99907. }
  99908. }
  99909. if(write_frame_(encoder, buffer, bytes, samples, is_last_block) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  99910. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  99911. FLAC__bitwriter_clear(encoder->private_->frame);
  99912. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  99913. return false;
  99914. }
  99915. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  99916. FLAC__bitwriter_clear(encoder->private_->frame);
  99917. if(samples > 0) {
  99918. encoder->private_->streaminfo.data.stream_info.min_framesize = min(bytes, encoder->private_->streaminfo.data.stream_info.min_framesize);
  99919. encoder->private_->streaminfo.data.stream_info.max_framesize = max(bytes, encoder->private_->streaminfo.data.stream_info.max_framesize);
  99920. }
  99921. return true;
  99922. }
  99923. FLAC__StreamEncoderWriteStatus write_frame_(FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, FLAC__bool is_last_block)
  99924. {
  99925. FLAC__StreamEncoderWriteStatus status;
  99926. FLAC__uint64 output_position = 0;
  99927. /* FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED just means we didn't get the offset; no error */
  99928. if(encoder->private_->tell_callback && encoder->private_->tell_callback(encoder, &output_position, encoder->private_->client_data) == FLAC__STREAM_ENCODER_TELL_STATUS_ERROR) {
  99929. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  99930. return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  99931. }
  99932. /*
  99933. * Watch for the STREAMINFO block and first SEEKTABLE block to go by and store their offsets.
  99934. */
  99935. if(samples == 0) {
  99936. FLAC__MetadataType type = (FLAC__MetadataType) (buffer[0] & 0x7f);
  99937. if(type == FLAC__METADATA_TYPE_STREAMINFO)
  99938. encoder->protected_->streaminfo_offset = output_position;
  99939. else if(type == FLAC__METADATA_TYPE_SEEKTABLE && encoder->protected_->seektable_offset == 0)
  99940. encoder->protected_->seektable_offset = output_position;
  99941. }
  99942. /*
  99943. * Mark the current seek point if hit (if audio_offset == 0 that
  99944. * means we're still writing metadata and haven't hit the first
  99945. * frame yet)
  99946. */
  99947. if(0 != encoder->private_->seek_table && encoder->protected_->audio_offset > 0 && encoder->private_->seek_table->num_points > 0) {
  99948. const unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
  99949. const FLAC__uint64 frame_first_sample = encoder->private_->samples_written;
  99950. const FLAC__uint64 frame_last_sample = frame_first_sample + (FLAC__uint64)blocksize - 1;
  99951. FLAC__uint64 test_sample;
  99952. unsigned i;
  99953. for(i = encoder->private_->first_seekpoint_to_check; i < encoder->private_->seek_table->num_points; i++) {
  99954. test_sample = encoder->private_->seek_table->points[i].sample_number;
  99955. if(test_sample > frame_last_sample) {
  99956. break;
  99957. }
  99958. else if(test_sample >= frame_first_sample) {
  99959. encoder->private_->seek_table->points[i].sample_number = frame_first_sample;
  99960. encoder->private_->seek_table->points[i].stream_offset = output_position - encoder->protected_->audio_offset;
  99961. encoder->private_->seek_table->points[i].frame_samples = blocksize;
  99962. encoder->private_->first_seekpoint_to_check++;
  99963. /* DO NOT: "break;" and here's why:
  99964. * The seektable template may contain more than one target
  99965. * sample for any given frame; we will keep looping, generating
  99966. * duplicate seekpoints for them, and we'll clean it up later,
  99967. * just before writing the seektable back to the metadata.
  99968. */
  99969. }
  99970. else {
  99971. encoder->private_->first_seekpoint_to_check++;
  99972. }
  99973. }
  99974. }
  99975. #if FLAC__HAS_OGG
  99976. if(encoder->private_->is_ogg) {
  99977. status = FLAC__ogg_encoder_aspect_write_callback_wrapper(
  99978. &encoder->protected_->ogg_encoder_aspect,
  99979. buffer,
  99980. bytes,
  99981. samples,
  99982. encoder->private_->current_frame_number,
  99983. is_last_block,
  99984. (FLAC__OggEncoderAspectWriteCallbackProxy)encoder->private_->write_callback,
  99985. encoder,
  99986. encoder->private_->client_data
  99987. );
  99988. }
  99989. else
  99990. #endif
  99991. status = encoder->private_->write_callback(encoder, buffer, bytes, samples, encoder->private_->current_frame_number, encoder->private_->client_data);
  99992. if(status == FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  99993. encoder->private_->bytes_written += bytes;
  99994. encoder->private_->samples_written += samples;
  99995. /* we keep a high watermark on the number of frames written because
  99996. * when the encoder goes back to write metadata, 'current_frame'
  99997. * will drop back to 0.
  99998. */
  99999. encoder->private_->frames_written = max(encoder->private_->frames_written, encoder->private_->current_frame_number+1);
  100000. }
  100001. else
  100002. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  100003. return status;
  100004. }
  100005. /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks. */
  100006. void update_metadata_(const FLAC__StreamEncoder *encoder)
  100007. {
  100008. FLAC__byte b[max(6, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
  100009. const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
  100010. const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
  100011. const unsigned min_framesize = metadata->data.stream_info.min_framesize;
  100012. const unsigned max_framesize = metadata->data.stream_info.max_framesize;
  100013. const unsigned bps = metadata->data.stream_info.bits_per_sample;
  100014. FLAC__StreamEncoderSeekStatus seek_status;
  100015. FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
  100016. /* All this is based on intimate knowledge of the stream header
  100017. * layout, but a change to the header format that would break this
  100018. * would also break all streams encoded in the previous format.
  100019. */
  100020. /*
  100021. * Write MD5 signature
  100022. */
  100023. {
  100024. const unsigned md5_offset =
  100025. FLAC__STREAM_METADATA_HEADER_LENGTH +
  100026. (
  100027. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  100028. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  100029. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  100030. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  100031. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  100032. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  100033. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
  100034. FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
  100035. ) / 8;
  100036. if((seek_status = encoder->private_->seek_callback(encoder, encoder->protected_->streaminfo_offset + md5_offset, encoder->private_->client_data)) != FLAC__STREAM_ENCODER_SEEK_STATUS_OK) {
  100037. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  100038. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  100039. return;
  100040. }
  100041. if(encoder->private_->write_callback(encoder, metadata->data.stream_info.md5sum, 16, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  100042. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  100043. return;
  100044. }
  100045. }
  100046. /*
  100047. * Write total samples
  100048. */
  100049. {
  100050. const unsigned total_samples_byte_offset =
  100051. FLAC__STREAM_METADATA_HEADER_LENGTH +
  100052. (
  100053. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  100054. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  100055. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  100056. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  100057. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  100058. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  100059. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
  100060. - 4
  100061. ) / 8;
  100062. b[0] = ((FLAC__byte)(bps-1) << 4) | (FLAC__byte)((samples >> 32) & 0x0F);
  100063. b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
  100064. b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
  100065. b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
  100066. b[4] = (FLAC__byte)(samples & 0xFF);
  100067. if((seek_status = encoder->private_->seek_callback(encoder, encoder->protected_->streaminfo_offset + total_samples_byte_offset, encoder->private_->client_data)) != FLAC__STREAM_ENCODER_SEEK_STATUS_OK) {
  100068. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  100069. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  100070. return;
  100071. }
  100072. if(encoder->private_->write_callback(encoder, b, 5, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  100073. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  100074. return;
  100075. }
  100076. }
  100077. /*
  100078. * Write min/max framesize
  100079. */
  100080. {
  100081. const unsigned min_framesize_offset =
  100082. FLAC__STREAM_METADATA_HEADER_LENGTH +
  100083. (
  100084. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  100085. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
  100086. ) / 8;
  100087. b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
  100088. b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
  100089. b[2] = (FLAC__byte)(min_framesize & 0xFF);
  100090. b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
  100091. b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
  100092. b[5] = (FLAC__byte)(max_framesize & 0xFF);
  100093. if((seek_status = encoder->private_->seek_callback(encoder, encoder->protected_->streaminfo_offset + min_framesize_offset, encoder->private_->client_data)) != FLAC__STREAM_ENCODER_SEEK_STATUS_OK) {
  100094. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  100095. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  100096. return;
  100097. }
  100098. if(encoder->private_->write_callback(encoder, b, 6, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  100099. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  100100. return;
  100101. }
  100102. }
  100103. /*
  100104. * Write seektable
  100105. */
  100106. if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
  100107. unsigned i;
  100108. FLAC__format_seektable_sort(encoder->private_->seek_table);
  100109. FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
  100110. if((seek_status = encoder->private_->seek_callback(encoder, encoder->protected_->seektable_offset + FLAC__STREAM_METADATA_HEADER_LENGTH, encoder->private_->client_data)) != FLAC__STREAM_ENCODER_SEEK_STATUS_OK) {
  100111. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  100112. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  100113. return;
  100114. }
  100115. for(i = 0; i < encoder->private_->seek_table->num_points; i++) {
  100116. FLAC__uint64 xx;
  100117. unsigned x;
  100118. xx = encoder->private_->seek_table->points[i].sample_number;
  100119. b[7] = (FLAC__byte)xx; xx >>= 8;
  100120. b[6] = (FLAC__byte)xx; xx >>= 8;
  100121. b[5] = (FLAC__byte)xx; xx >>= 8;
  100122. b[4] = (FLAC__byte)xx; xx >>= 8;
  100123. b[3] = (FLAC__byte)xx; xx >>= 8;
  100124. b[2] = (FLAC__byte)xx; xx >>= 8;
  100125. b[1] = (FLAC__byte)xx; xx >>= 8;
  100126. b[0] = (FLAC__byte)xx; xx >>= 8;
  100127. xx = encoder->private_->seek_table->points[i].stream_offset;
  100128. b[15] = (FLAC__byte)xx; xx >>= 8;
  100129. b[14] = (FLAC__byte)xx; xx >>= 8;
  100130. b[13] = (FLAC__byte)xx; xx >>= 8;
  100131. b[12] = (FLAC__byte)xx; xx >>= 8;
  100132. b[11] = (FLAC__byte)xx; xx >>= 8;
  100133. b[10] = (FLAC__byte)xx; xx >>= 8;
  100134. b[9] = (FLAC__byte)xx; xx >>= 8;
  100135. b[8] = (FLAC__byte)xx; xx >>= 8;
  100136. x = encoder->private_->seek_table->points[i].frame_samples;
  100137. b[17] = (FLAC__byte)x; x >>= 8;
  100138. b[16] = (FLAC__byte)x; x >>= 8;
  100139. if(encoder->private_->write_callback(encoder, b, 18, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  100140. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  100141. return;
  100142. }
  100143. }
  100144. }
  100145. }
  100146. #if FLAC__HAS_OGG
  100147. /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks. */
  100148. void update_ogg_metadata_(FLAC__StreamEncoder *encoder)
  100149. {
  100150. /* the # of bytes in the 1st packet that precede the STREAMINFO */
  100151. static const unsigned FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH =
  100152. FLAC__OGG_MAPPING_PACKET_TYPE_LENGTH +
  100153. FLAC__OGG_MAPPING_MAGIC_LENGTH +
  100154. FLAC__OGG_MAPPING_VERSION_MAJOR_LENGTH +
  100155. FLAC__OGG_MAPPING_VERSION_MINOR_LENGTH +
  100156. FLAC__OGG_MAPPING_NUM_HEADERS_LENGTH +
  100157. FLAC__STREAM_SYNC_LENGTH
  100158. ;
  100159. FLAC__byte b[max(6, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
  100160. const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
  100161. const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
  100162. const unsigned min_framesize = metadata->data.stream_info.min_framesize;
  100163. const unsigned max_framesize = metadata->data.stream_info.max_framesize;
  100164. ogg_page page;
  100165. FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
  100166. FLAC__ASSERT(0 != encoder->private_->seek_callback);
  100167. /* Pre-check that client supports seeking, since we don't want the
  100168. * ogg_helper code to ever have to deal with this condition.
  100169. */
  100170. if(encoder->private_->seek_callback(encoder, 0, encoder->private_->client_data) == FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED)
  100171. return;
  100172. /* All this is based on intimate knowledge of the stream header
  100173. * layout, but a change to the header format that would break this
  100174. * would also break all streams encoded in the previous format.
  100175. */
  100176. /**
  100177. ** Write STREAMINFO stats
  100178. **/
  100179. simple_ogg_page__init(&page);
  100180. if(!simple_ogg_page__get_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
  100181. simple_ogg_page__clear(&page);
  100182. return; /* state already set */
  100183. }
  100184. /*
  100185. * Write MD5 signature
  100186. */
  100187. {
  100188. const unsigned md5_offset =
  100189. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  100190. FLAC__STREAM_METADATA_HEADER_LENGTH +
  100191. (
  100192. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  100193. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  100194. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  100195. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  100196. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  100197. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  100198. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
  100199. FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
  100200. ) / 8;
  100201. if(md5_offset + 16 > (unsigned)page.body_len) {
  100202. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  100203. simple_ogg_page__clear(&page);
  100204. return;
  100205. }
  100206. memcpy(page.body + md5_offset, metadata->data.stream_info.md5sum, 16);
  100207. }
  100208. /*
  100209. * Write total samples
  100210. */
  100211. {
  100212. const unsigned total_samples_byte_offset =
  100213. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  100214. FLAC__STREAM_METADATA_HEADER_LENGTH +
  100215. (
  100216. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  100217. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  100218. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  100219. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  100220. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  100221. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  100222. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
  100223. - 4
  100224. ) / 8;
  100225. if(total_samples_byte_offset + 5 > (unsigned)page.body_len) {
  100226. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  100227. simple_ogg_page__clear(&page);
  100228. return;
  100229. }
  100230. b[0] = (FLAC__byte)page.body[total_samples_byte_offset] & 0xF0;
  100231. b[0] |= (FLAC__byte)((samples >> 32) & 0x0F);
  100232. b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
  100233. b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
  100234. b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
  100235. b[4] = (FLAC__byte)(samples & 0xFF);
  100236. memcpy(page.body + total_samples_byte_offset, b, 5);
  100237. }
  100238. /*
  100239. * Write min/max framesize
  100240. */
  100241. {
  100242. const unsigned min_framesize_offset =
  100243. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  100244. FLAC__STREAM_METADATA_HEADER_LENGTH +
  100245. (
  100246. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  100247. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
  100248. ) / 8;
  100249. if(min_framesize_offset + 6 > (unsigned)page.body_len) {
  100250. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  100251. simple_ogg_page__clear(&page);
  100252. return;
  100253. }
  100254. b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
  100255. b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
  100256. b[2] = (FLAC__byte)(min_framesize & 0xFF);
  100257. b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
  100258. b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
  100259. b[5] = (FLAC__byte)(max_framesize & 0xFF);
  100260. memcpy(page.body + min_framesize_offset, b, 6);
  100261. }
  100262. if(!simple_ogg_page__set_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
  100263. simple_ogg_page__clear(&page);
  100264. return; /* state already set */
  100265. }
  100266. simple_ogg_page__clear(&page);
  100267. /*
  100268. * Write seektable
  100269. */
  100270. if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
  100271. unsigned i;
  100272. FLAC__byte *p;
  100273. FLAC__format_seektable_sort(encoder->private_->seek_table);
  100274. FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
  100275. simple_ogg_page__init(&page);
  100276. if(!simple_ogg_page__get_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
  100277. simple_ogg_page__clear(&page);
  100278. return; /* state already set */
  100279. }
  100280. if((FLAC__STREAM_METADATA_HEADER_LENGTH + 18*encoder->private_->seek_table->num_points) != (unsigned)page.body_len) {
  100281. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  100282. simple_ogg_page__clear(&page);
  100283. return;
  100284. }
  100285. for(i = 0, p = page.body + FLAC__STREAM_METADATA_HEADER_LENGTH; i < encoder->private_->seek_table->num_points; i++, p += 18) {
  100286. FLAC__uint64 xx;
  100287. unsigned x;
  100288. xx = encoder->private_->seek_table->points[i].sample_number;
  100289. b[7] = (FLAC__byte)xx; xx >>= 8;
  100290. b[6] = (FLAC__byte)xx; xx >>= 8;
  100291. b[5] = (FLAC__byte)xx; xx >>= 8;
  100292. b[4] = (FLAC__byte)xx; xx >>= 8;
  100293. b[3] = (FLAC__byte)xx; xx >>= 8;
  100294. b[2] = (FLAC__byte)xx; xx >>= 8;
  100295. b[1] = (FLAC__byte)xx; xx >>= 8;
  100296. b[0] = (FLAC__byte)xx; xx >>= 8;
  100297. xx = encoder->private_->seek_table->points[i].stream_offset;
  100298. b[15] = (FLAC__byte)xx; xx >>= 8;
  100299. b[14] = (FLAC__byte)xx; xx >>= 8;
  100300. b[13] = (FLAC__byte)xx; xx >>= 8;
  100301. b[12] = (FLAC__byte)xx; xx >>= 8;
  100302. b[11] = (FLAC__byte)xx; xx >>= 8;
  100303. b[10] = (FLAC__byte)xx; xx >>= 8;
  100304. b[9] = (FLAC__byte)xx; xx >>= 8;
  100305. b[8] = (FLAC__byte)xx; xx >>= 8;
  100306. x = encoder->private_->seek_table->points[i].frame_samples;
  100307. b[17] = (FLAC__byte)x; x >>= 8;
  100308. b[16] = (FLAC__byte)x; x >>= 8;
  100309. memcpy(p, b, 18);
  100310. }
  100311. if(!simple_ogg_page__set_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
  100312. simple_ogg_page__clear(&page);
  100313. return; /* state already set */
  100314. }
  100315. simple_ogg_page__clear(&page);
  100316. }
  100317. }
  100318. #endif
  100319. FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block, FLAC__bool is_last_block)
  100320. {
  100321. FLAC__uint16 crc;
  100322. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  100323. /*
  100324. * Accumulate raw signal to the MD5 signature
  100325. */
  100326. if(encoder->protected_->do_md5 && !FLAC__MD5Accumulate(&encoder->private_->md5context, (const FLAC__int32 * const *)encoder->private_->integer_signal, encoder->protected_->channels, encoder->protected_->blocksize, (encoder->protected_->bits_per_sample+7) / 8)) {
  100327. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  100328. return false;
  100329. }
  100330. /*
  100331. * Process the frame header and subframes into the frame bitbuffer
  100332. */
  100333. if(!process_subframes_(encoder, is_fractional_block)) {
  100334. /* the above function sets the state for us in case of an error */
  100335. return false;
  100336. }
  100337. /*
  100338. * Zero-pad the frame to a byte_boundary
  100339. */
  100340. if(!FLAC__bitwriter_zero_pad_to_byte_boundary(encoder->private_->frame)) {
  100341. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  100342. return false;
  100343. }
  100344. /*
  100345. * CRC-16 the whole thing
  100346. */
  100347. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
  100348. if(
  100349. !FLAC__bitwriter_get_write_crc16(encoder->private_->frame, &crc) ||
  100350. !FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, crc, FLAC__FRAME_FOOTER_CRC_LEN)
  100351. ) {
  100352. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  100353. return false;
  100354. }
  100355. /*
  100356. * Write it
  100357. */
  100358. if(!write_bitbuffer_(encoder, encoder->protected_->blocksize, is_last_block)) {
  100359. /* the above function sets the state for us in case of an error */
  100360. return false;
  100361. }
  100362. /*
  100363. * Get ready for the next frame
  100364. */
  100365. encoder->private_->current_sample_number = 0;
  100366. encoder->private_->current_frame_number++;
  100367. encoder->private_->streaminfo.data.stream_info.total_samples += (FLAC__uint64)encoder->protected_->blocksize;
  100368. return true;
  100369. }
  100370. FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block)
  100371. {
  100372. FLAC__FrameHeader frame_header;
  100373. unsigned channel, min_partition_order = encoder->protected_->min_residual_partition_order, max_partition_order;
  100374. FLAC__bool do_independent, do_mid_side;
  100375. /*
  100376. * Calculate the min,max Rice partition orders
  100377. */
  100378. if(is_fractional_block) {
  100379. max_partition_order = 0;
  100380. }
  100381. else {
  100382. max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize(encoder->protected_->blocksize);
  100383. max_partition_order = min(max_partition_order, encoder->protected_->max_residual_partition_order);
  100384. }
  100385. min_partition_order = min(min_partition_order, max_partition_order);
  100386. /*
  100387. * Setup the frame
  100388. */
  100389. frame_header.blocksize = encoder->protected_->blocksize;
  100390. frame_header.sample_rate = encoder->protected_->sample_rate;
  100391. frame_header.channels = encoder->protected_->channels;
  100392. frame_header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT; /* the default unless the encoder determines otherwise */
  100393. frame_header.bits_per_sample = encoder->protected_->bits_per_sample;
  100394. frame_header.number_type = FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER;
  100395. frame_header.number.frame_number = encoder->private_->current_frame_number;
  100396. /*
  100397. * Figure out what channel assignments to try
  100398. */
  100399. if(encoder->protected_->do_mid_side_stereo) {
  100400. if(encoder->protected_->loose_mid_side_stereo) {
  100401. if(encoder->private_->loose_mid_side_stereo_frame_count == 0) {
  100402. do_independent = true;
  100403. do_mid_side = true;
  100404. }
  100405. else {
  100406. do_independent = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT);
  100407. do_mid_side = !do_independent;
  100408. }
  100409. }
  100410. else {
  100411. do_independent = true;
  100412. do_mid_side = true;
  100413. }
  100414. }
  100415. else {
  100416. do_independent = true;
  100417. do_mid_side = false;
  100418. }
  100419. FLAC__ASSERT(do_independent || do_mid_side);
  100420. /*
  100421. * Check for wasted bits; set effective bps for each subframe
  100422. */
  100423. if(do_independent) {
  100424. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  100425. const unsigned w = get_wasted_bits_(encoder->private_->integer_signal[channel], encoder->protected_->blocksize);
  100426. encoder->private_->subframe_workspace[channel][0].wasted_bits = encoder->private_->subframe_workspace[channel][1].wasted_bits = w;
  100427. encoder->private_->subframe_bps[channel] = encoder->protected_->bits_per_sample - w;
  100428. }
  100429. }
  100430. if(do_mid_side) {
  100431. FLAC__ASSERT(encoder->protected_->channels == 2);
  100432. for(channel = 0; channel < 2; channel++) {
  100433. const unsigned w = get_wasted_bits_(encoder->private_->integer_signal_mid_side[channel], encoder->protected_->blocksize);
  100434. encoder->private_->subframe_workspace_mid_side[channel][0].wasted_bits = encoder->private_->subframe_workspace_mid_side[channel][1].wasted_bits = w;
  100435. encoder->private_->subframe_bps_mid_side[channel] = encoder->protected_->bits_per_sample - w + (channel==0? 0:1);
  100436. }
  100437. }
  100438. /*
  100439. * First do a normal encoding pass of each independent channel
  100440. */
  100441. if(do_independent) {
  100442. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  100443. if(!
  100444. process_subframe_(
  100445. encoder,
  100446. min_partition_order,
  100447. max_partition_order,
  100448. &frame_header,
  100449. encoder->private_->subframe_bps[channel],
  100450. encoder->private_->integer_signal[channel],
  100451. encoder->private_->subframe_workspace_ptr[channel],
  100452. encoder->private_->partitioned_rice_contents_workspace_ptr[channel],
  100453. encoder->private_->residual_workspace[channel],
  100454. encoder->private_->best_subframe+channel,
  100455. encoder->private_->best_subframe_bits+channel
  100456. )
  100457. )
  100458. return false;
  100459. }
  100460. }
  100461. /*
  100462. * Now do mid and side channels if requested
  100463. */
  100464. if(do_mid_side) {
  100465. FLAC__ASSERT(encoder->protected_->channels == 2);
  100466. for(channel = 0; channel < 2; channel++) {
  100467. if(!
  100468. process_subframe_(
  100469. encoder,
  100470. min_partition_order,
  100471. max_partition_order,
  100472. &frame_header,
  100473. encoder->private_->subframe_bps_mid_side[channel],
  100474. encoder->private_->integer_signal_mid_side[channel],
  100475. encoder->private_->subframe_workspace_ptr_mid_side[channel],
  100476. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[channel],
  100477. encoder->private_->residual_workspace_mid_side[channel],
  100478. encoder->private_->best_subframe_mid_side+channel,
  100479. encoder->private_->best_subframe_bits_mid_side+channel
  100480. )
  100481. )
  100482. return false;
  100483. }
  100484. }
  100485. /*
  100486. * Compose the frame bitbuffer
  100487. */
  100488. if(do_mid_side) {
  100489. unsigned left_bps = 0, right_bps = 0; /* initialized only to prevent superfluous compiler warning */
  100490. FLAC__Subframe *left_subframe = 0, *right_subframe = 0; /* initialized only to prevent superfluous compiler warning */
  100491. FLAC__ChannelAssignment channel_assignment;
  100492. FLAC__ASSERT(encoder->protected_->channels == 2);
  100493. if(encoder->protected_->loose_mid_side_stereo && encoder->private_->loose_mid_side_stereo_frame_count > 0) {
  100494. channel_assignment = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT? FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT : FLAC__CHANNEL_ASSIGNMENT_MID_SIDE);
  100495. }
  100496. else {
  100497. unsigned bits[4]; /* WATCHOUT - indexed by FLAC__ChannelAssignment */
  100498. unsigned min_bits;
  100499. int ca;
  100500. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT == 0);
  100501. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE == 1);
  100502. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE == 2);
  100503. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_MID_SIDE == 3);
  100504. FLAC__ASSERT(do_independent && do_mid_side);
  100505. /* We have to figure out which channel assignent results in the smallest frame */
  100506. bits[FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT] = encoder->private_->best_subframe_bits [0] + encoder->private_->best_subframe_bits [1];
  100507. bits[FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE ] = encoder->private_->best_subframe_bits [0] + encoder->private_->best_subframe_bits_mid_side[1];
  100508. bits[FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE ] = encoder->private_->best_subframe_bits [1] + encoder->private_->best_subframe_bits_mid_side[1];
  100509. bits[FLAC__CHANNEL_ASSIGNMENT_MID_SIDE ] = encoder->private_->best_subframe_bits_mid_side[0] + encoder->private_->best_subframe_bits_mid_side[1];
  100510. channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT;
  100511. min_bits = bits[channel_assignment];
  100512. for(ca = 1; ca <= 3; ca++) {
  100513. if(bits[ca] < min_bits) {
  100514. min_bits = bits[ca];
  100515. channel_assignment = (FLAC__ChannelAssignment)ca;
  100516. }
  100517. }
  100518. }
  100519. frame_header.channel_assignment = channel_assignment;
  100520. if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
  100521. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  100522. return false;
  100523. }
  100524. switch(channel_assignment) {
  100525. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  100526. left_subframe = &encoder->private_->subframe_workspace [0][encoder->private_->best_subframe [0]];
  100527. right_subframe = &encoder->private_->subframe_workspace [1][encoder->private_->best_subframe [1]];
  100528. break;
  100529. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  100530. left_subframe = &encoder->private_->subframe_workspace [0][encoder->private_->best_subframe [0]];
  100531. right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  100532. break;
  100533. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  100534. left_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  100535. right_subframe = &encoder->private_->subframe_workspace [1][encoder->private_->best_subframe [1]];
  100536. break;
  100537. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  100538. left_subframe = &encoder->private_->subframe_workspace_mid_side[0][encoder->private_->best_subframe_mid_side[0]];
  100539. right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  100540. break;
  100541. default:
  100542. FLAC__ASSERT(0);
  100543. }
  100544. switch(channel_assignment) {
  100545. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  100546. left_bps = encoder->private_->subframe_bps [0];
  100547. right_bps = encoder->private_->subframe_bps [1];
  100548. break;
  100549. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  100550. left_bps = encoder->private_->subframe_bps [0];
  100551. right_bps = encoder->private_->subframe_bps_mid_side[1];
  100552. break;
  100553. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  100554. left_bps = encoder->private_->subframe_bps_mid_side[1];
  100555. right_bps = encoder->private_->subframe_bps [1];
  100556. break;
  100557. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  100558. left_bps = encoder->private_->subframe_bps_mid_side[0];
  100559. right_bps = encoder->private_->subframe_bps_mid_side[1];
  100560. break;
  100561. default:
  100562. FLAC__ASSERT(0);
  100563. }
  100564. /* note that encoder_add_subframe_ sets the state for us in case of an error */
  100565. if(!add_subframe_(encoder, frame_header.blocksize, left_bps , left_subframe , encoder->private_->frame))
  100566. return false;
  100567. if(!add_subframe_(encoder, frame_header.blocksize, right_bps, right_subframe, encoder->private_->frame))
  100568. return false;
  100569. }
  100570. else {
  100571. if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
  100572. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  100573. return false;
  100574. }
  100575. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  100576. if(!add_subframe_(encoder, frame_header.blocksize, encoder->private_->subframe_bps[channel], &encoder->private_->subframe_workspace[channel][encoder->private_->best_subframe[channel]], encoder->private_->frame)) {
  100577. /* the above function sets the state for us in case of an error */
  100578. return false;
  100579. }
  100580. }
  100581. }
  100582. if(encoder->protected_->loose_mid_side_stereo) {
  100583. encoder->private_->loose_mid_side_stereo_frame_count++;
  100584. if(encoder->private_->loose_mid_side_stereo_frame_count >= encoder->private_->loose_mid_side_stereo_frames)
  100585. encoder->private_->loose_mid_side_stereo_frame_count = 0;
  100586. }
  100587. encoder->private_->last_channel_assignment = frame_header.channel_assignment;
  100588. return true;
  100589. }
  100590. FLAC__bool process_subframe_(
  100591. FLAC__StreamEncoder *encoder,
  100592. unsigned min_partition_order,
  100593. unsigned max_partition_order,
  100594. const FLAC__FrameHeader *frame_header,
  100595. unsigned subframe_bps,
  100596. const FLAC__int32 integer_signal[],
  100597. FLAC__Subframe *subframe[2],
  100598. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
  100599. FLAC__int32 *residual[2],
  100600. unsigned *best_subframe,
  100601. unsigned *best_bits
  100602. )
  100603. {
  100604. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  100605. FLAC__float fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
  100606. #else
  100607. FLAC__fixedpoint fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
  100608. #endif
  100609. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  100610. FLAC__double lpc_residual_bits_per_sample;
  100611. FLAC__real autoc[FLAC__MAX_LPC_ORDER+1]; /* WATCHOUT: the size is important even though encoder->protected_->max_lpc_order might be less; some asm routines need all the space */
  100612. FLAC__double lpc_error[FLAC__MAX_LPC_ORDER];
  100613. unsigned min_lpc_order, max_lpc_order, lpc_order;
  100614. unsigned min_qlp_coeff_precision, max_qlp_coeff_precision, qlp_coeff_precision;
  100615. #endif
  100616. unsigned min_fixed_order, max_fixed_order, guess_fixed_order, fixed_order;
  100617. unsigned rice_parameter;
  100618. unsigned _candidate_bits, _best_bits;
  100619. unsigned _best_subframe;
  100620. /* only use RICE2 partitions if stream bps > 16 */
  100621. const unsigned rice_parameter_limit = FLAC__stream_encoder_get_bits_per_sample(encoder) > 16? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  100622. FLAC__ASSERT(frame_header->blocksize > 0);
  100623. /* verbatim subframe is the baseline against which we measure other compressed subframes */
  100624. _best_subframe = 0;
  100625. if(encoder->private_->disable_verbatim_subframes && frame_header->blocksize >= FLAC__MAX_FIXED_ORDER)
  100626. _best_bits = UINT_MAX;
  100627. else
  100628. _best_bits = evaluate_verbatim_subframe_(encoder, integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
  100629. if(frame_header->blocksize >= FLAC__MAX_FIXED_ORDER) {
  100630. unsigned signal_is_constant = false;
  100631. guess_fixed_order = encoder->private_->local_fixed_compute_best_predictor(integer_signal+FLAC__MAX_FIXED_ORDER, frame_header->blocksize-FLAC__MAX_FIXED_ORDER, fixed_residual_bits_per_sample);
  100632. /* check for constant subframe */
  100633. if(
  100634. !encoder->private_->disable_constant_subframes &&
  100635. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  100636. fixed_residual_bits_per_sample[1] == 0.0
  100637. #else
  100638. fixed_residual_bits_per_sample[1] == FLAC__FP_ZERO
  100639. #endif
  100640. ) {
  100641. /* the above means it's possible all samples are the same value; now double-check it: */
  100642. unsigned i;
  100643. signal_is_constant = true;
  100644. for(i = 1; i < frame_header->blocksize; i++) {
  100645. if(integer_signal[0] != integer_signal[i]) {
  100646. signal_is_constant = false;
  100647. break;
  100648. }
  100649. }
  100650. }
  100651. if(signal_is_constant) {
  100652. _candidate_bits = evaluate_constant_subframe_(encoder, integer_signal[0], frame_header->blocksize, subframe_bps, subframe[!_best_subframe]);
  100653. if(_candidate_bits < _best_bits) {
  100654. _best_subframe = !_best_subframe;
  100655. _best_bits = _candidate_bits;
  100656. }
  100657. }
  100658. else {
  100659. if(!encoder->private_->disable_fixed_subframes || (encoder->protected_->max_lpc_order == 0 && _best_bits == UINT_MAX)) {
  100660. /* encode fixed */
  100661. if(encoder->protected_->do_exhaustive_model_search) {
  100662. min_fixed_order = 0;
  100663. max_fixed_order = FLAC__MAX_FIXED_ORDER;
  100664. }
  100665. else {
  100666. min_fixed_order = max_fixed_order = guess_fixed_order;
  100667. }
  100668. if(max_fixed_order >= frame_header->blocksize)
  100669. max_fixed_order = frame_header->blocksize - 1;
  100670. for(fixed_order = min_fixed_order; fixed_order <= max_fixed_order; fixed_order++) {
  100671. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  100672. if(fixed_residual_bits_per_sample[fixed_order] >= (FLAC__float)subframe_bps)
  100673. continue; /* don't even try */
  100674. rice_parameter = (fixed_residual_bits_per_sample[fixed_order] > 0.0)? (unsigned)(fixed_residual_bits_per_sample[fixed_order]+0.5) : 0; /* 0.5 is for rounding */
  100675. #else
  100676. if(FLAC__fixedpoint_trunc(fixed_residual_bits_per_sample[fixed_order]) >= (int)subframe_bps)
  100677. continue; /* don't even try */
  100678. rice_parameter = (fixed_residual_bits_per_sample[fixed_order] > FLAC__FP_ZERO)? (unsigned)FLAC__fixedpoint_trunc(fixed_residual_bits_per_sample[fixed_order]+FLAC__FP_ONE_HALF) : 0; /* 0.5 is for rounding */
  100679. #endif
  100680. rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
  100681. if(rice_parameter >= rice_parameter_limit) {
  100682. #ifdef DEBUG_VERBOSE
  100683. fprintf(stderr, "clipping rice_parameter (%u -> %u) @0\n", rice_parameter, rice_parameter_limit - 1);
  100684. #endif
  100685. rice_parameter = rice_parameter_limit - 1;
  100686. }
  100687. _candidate_bits =
  100688. evaluate_fixed_subframe_(
  100689. encoder,
  100690. integer_signal,
  100691. residual[!_best_subframe],
  100692. encoder->private_->abs_residual_partition_sums,
  100693. encoder->private_->raw_bits_per_partition,
  100694. frame_header->blocksize,
  100695. subframe_bps,
  100696. fixed_order,
  100697. rice_parameter,
  100698. rice_parameter_limit,
  100699. min_partition_order,
  100700. max_partition_order,
  100701. encoder->protected_->do_escape_coding,
  100702. encoder->protected_->rice_parameter_search_dist,
  100703. subframe[!_best_subframe],
  100704. partitioned_rice_contents[!_best_subframe]
  100705. );
  100706. if(_candidate_bits < _best_bits) {
  100707. _best_subframe = !_best_subframe;
  100708. _best_bits = _candidate_bits;
  100709. }
  100710. }
  100711. }
  100712. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  100713. /* encode lpc */
  100714. if(encoder->protected_->max_lpc_order > 0) {
  100715. if(encoder->protected_->max_lpc_order >= frame_header->blocksize)
  100716. max_lpc_order = frame_header->blocksize-1;
  100717. else
  100718. max_lpc_order = encoder->protected_->max_lpc_order;
  100719. if(max_lpc_order > 0) {
  100720. unsigned a;
  100721. for (a = 0; a < encoder->protected_->num_apodizations; a++) {
  100722. FLAC__lpc_window_data(integer_signal, encoder->private_->window[a], encoder->private_->windowed_signal, frame_header->blocksize);
  100723. encoder->private_->local_lpc_compute_autocorrelation(encoder->private_->windowed_signal, frame_header->blocksize, max_lpc_order+1, autoc);
  100724. /* if autoc[0] == 0.0, the signal is constant and we usually won't get here, but it can happen */
  100725. if(autoc[0] != 0.0) {
  100726. FLAC__lpc_compute_lp_coefficients(autoc, &max_lpc_order, encoder->private_->lp_coeff, lpc_error);
  100727. if(encoder->protected_->do_exhaustive_model_search) {
  100728. min_lpc_order = 1;
  100729. }
  100730. else {
  100731. const unsigned guess_lpc_order =
  100732. FLAC__lpc_compute_best_order(
  100733. lpc_error,
  100734. max_lpc_order,
  100735. frame_header->blocksize,
  100736. subframe_bps + (
  100737. encoder->protected_->do_qlp_coeff_prec_search?
  100738. FLAC__MIN_QLP_COEFF_PRECISION : /* have to guess; use the min possible size to avoid accidentally favoring lower orders */
  100739. encoder->protected_->qlp_coeff_precision
  100740. )
  100741. );
  100742. min_lpc_order = max_lpc_order = guess_lpc_order;
  100743. }
  100744. if(max_lpc_order >= frame_header->blocksize)
  100745. max_lpc_order = frame_header->blocksize - 1;
  100746. for(lpc_order = min_lpc_order; lpc_order <= max_lpc_order; lpc_order++) {
  100747. lpc_residual_bits_per_sample = FLAC__lpc_compute_expected_bits_per_residual_sample(lpc_error[lpc_order-1], frame_header->blocksize-lpc_order);
  100748. if(lpc_residual_bits_per_sample >= (FLAC__double)subframe_bps)
  100749. continue; /* don't even try */
  100750. rice_parameter = (lpc_residual_bits_per_sample > 0.0)? (unsigned)(lpc_residual_bits_per_sample+0.5) : 0; /* 0.5 is for rounding */
  100751. rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
  100752. if(rice_parameter >= rice_parameter_limit) {
  100753. #ifdef DEBUG_VERBOSE
  100754. fprintf(stderr, "clipping rice_parameter (%u -> %u) @1\n", rice_parameter, rice_parameter_limit - 1);
  100755. #endif
  100756. rice_parameter = rice_parameter_limit - 1;
  100757. }
  100758. if(encoder->protected_->do_qlp_coeff_prec_search) {
  100759. min_qlp_coeff_precision = FLAC__MIN_QLP_COEFF_PRECISION;
  100760. /* try to ensure a 32-bit datapath throughout for 16bps(+1bps for side channel) or less */
  100761. if(subframe_bps <= 17) {
  100762. max_qlp_coeff_precision = min(32 - subframe_bps - lpc_order, FLAC__MAX_QLP_COEFF_PRECISION);
  100763. max_qlp_coeff_precision = max(max_qlp_coeff_precision, min_qlp_coeff_precision);
  100764. }
  100765. else
  100766. max_qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
  100767. }
  100768. else {
  100769. min_qlp_coeff_precision = max_qlp_coeff_precision = encoder->protected_->qlp_coeff_precision;
  100770. }
  100771. for(qlp_coeff_precision = min_qlp_coeff_precision; qlp_coeff_precision <= max_qlp_coeff_precision; qlp_coeff_precision++) {
  100772. _candidate_bits =
  100773. evaluate_lpc_subframe_(
  100774. encoder,
  100775. integer_signal,
  100776. residual[!_best_subframe],
  100777. encoder->private_->abs_residual_partition_sums,
  100778. encoder->private_->raw_bits_per_partition,
  100779. encoder->private_->lp_coeff[lpc_order-1],
  100780. frame_header->blocksize,
  100781. subframe_bps,
  100782. lpc_order,
  100783. qlp_coeff_precision,
  100784. rice_parameter,
  100785. rice_parameter_limit,
  100786. min_partition_order,
  100787. max_partition_order,
  100788. encoder->protected_->do_escape_coding,
  100789. encoder->protected_->rice_parameter_search_dist,
  100790. subframe[!_best_subframe],
  100791. partitioned_rice_contents[!_best_subframe]
  100792. );
  100793. if(_candidate_bits > 0) { /* if == 0, there was a problem quantizing the lpcoeffs */
  100794. if(_candidate_bits < _best_bits) {
  100795. _best_subframe = !_best_subframe;
  100796. _best_bits = _candidate_bits;
  100797. }
  100798. }
  100799. }
  100800. }
  100801. }
  100802. }
  100803. }
  100804. }
  100805. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  100806. }
  100807. }
  100808. /* under rare circumstances this can happen when all but lpc subframe types are disabled: */
  100809. if(_best_bits == UINT_MAX) {
  100810. FLAC__ASSERT(_best_subframe == 0);
  100811. _best_bits = evaluate_verbatim_subframe_(encoder, integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
  100812. }
  100813. *best_subframe = _best_subframe;
  100814. *best_bits = _best_bits;
  100815. return true;
  100816. }
  100817. FLAC__bool add_subframe_(
  100818. FLAC__StreamEncoder *encoder,
  100819. unsigned blocksize,
  100820. unsigned subframe_bps,
  100821. const FLAC__Subframe *subframe,
  100822. FLAC__BitWriter *frame
  100823. )
  100824. {
  100825. switch(subframe->type) {
  100826. case FLAC__SUBFRAME_TYPE_CONSTANT:
  100827. if(!FLAC__subframe_add_constant(&(subframe->data.constant), subframe_bps, subframe->wasted_bits, frame)) {
  100828. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  100829. return false;
  100830. }
  100831. break;
  100832. case FLAC__SUBFRAME_TYPE_FIXED:
  100833. if(!FLAC__subframe_add_fixed(&(subframe->data.fixed), blocksize - subframe->data.fixed.order, subframe_bps, subframe->wasted_bits, frame)) {
  100834. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  100835. return false;
  100836. }
  100837. break;
  100838. case FLAC__SUBFRAME_TYPE_LPC:
  100839. if(!FLAC__subframe_add_lpc(&(subframe->data.lpc), blocksize - subframe->data.lpc.order, subframe_bps, subframe->wasted_bits, frame)) {
  100840. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  100841. return false;
  100842. }
  100843. break;
  100844. case FLAC__SUBFRAME_TYPE_VERBATIM:
  100845. if(!FLAC__subframe_add_verbatim(&(subframe->data.verbatim), blocksize, subframe_bps, subframe->wasted_bits, frame)) {
  100846. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  100847. return false;
  100848. }
  100849. break;
  100850. default:
  100851. FLAC__ASSERT(0);
  100852. }
  100853. return true;
  100854. }
  100855. #define SPOTCHECK_ESTIMATE 0
  100856. #if SPOTCHECK_ESTIMATE
  100857. static void spotcheck_subframe_estimate_(
  100858. FLAC__StreamEncoder *encoder,
  100859. unsigned blocksize,
  100860. unsigned subframe_bps,
  100861. const FLAC__Subframe *subframe,
  100862. unsigned estimate
  100863. )
  100864. {
  100865. FLAC__bool ret;
  100866. FLAC__BitWriter *frame = FLAC__bitwriter_new();
  100867. if(frame == 0) {
  100868. fprintf(stderr, "EST: can't allocate frame\n");
  100869. return;
  100870. }
  100871. if(!FLAC__bitwriter_init(frame)) {
  100872. fprintf(stderr, "EST: can't init frame\n");
  100873. return;
  100874. }
  100875. ret = add_subframe_(encoder, blocksize, subframe_bps, subframe, frame);
  100876. FLAC__ASSERT(ret);
  100877. {
  100878. const unsigned actual = FLAC__bitwriter_get_input_bits_unconsumed(frame);
  100879. if(estimate != actual)
  100880. fprintf(stderr, "EST: bad, frame#%u sub#%%d type=%8s est=%u, actual=%u, delta=%d\n", encoder->private_->current_frame_number, FLAC__SubframeTypeString[subframe->type], estimate, actual, (int)actual-(int)estimate);
  100881. }
  100882. FLAC__bitwriter_delete(frame);
  100883. }
  100884. #endif
  100885. unsigned evaluate_constant_subframe_(
  100886. FLAC__StreamEncoder *encoder,
  100887. const FLAC__int32 signal,
  100888. unsigned blocksize,
  100889. unsigned subframe_bps,
  100890. FLAC__Subframe *subframe
  100891. )
  100892. {
  100893. unsigned estimate;
  100894. subframe->type = FLAC__SUBFRAME_TYPE_CONSTANT;
  100895. subframe->data.constant.value = signal;
  100896. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + subframe_bps;
  100897. #if SPOTCHECK_ESTIMATE
  100898. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  100899. #else
  100900. (void)encoder, (void)blocksize;
  100901. #endif
  100902. return estimate;
  100903. }
  100904. unsigned evaluate_fixed_subframe_(
  100905. FLAC__StreamEncoder *encoder,
  100906. const FLAC__int32 signal[],
  100907. FLAC__int32 residual[],
  100908. FLAC__uint64 abs_residual_partition_sums[],
  100909. unsigned raw_bits_per_partition[],
  100910. unsigned blocksize,
  100911. unsigned subframe_bps,
  100912. unsigned order,
  100913. unsigned rice_parameter,
  100914. unsigned rice_parameter_limit,
  100915. unsigned min_partition_order,
  100916. unsigned max_partition_order,
  100917. FLAC__bool do_escape_coding,
  100918. unsigned rice_parameter_search_dist,
  100919. FLAC__Subframe *subframe,
  100920. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  100921. )
  100922. {
  100923. unsigned i, residual_bits, estimate;
  100924. const unsigned residual_samples = blocksize - order;
  100925. FLAC__fixed_compute_residual(signal+order, residual_samples, order, residual);
  100926. subframe->type = FLAC__SUBFRAME_TYPE_FIXED;
  100927. subframe->data.fixed.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
  100928. subframe->data.fixed.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
  100929. subframe->data.fixed.residual = residual;
  100930. residual_bits =
  100931. find_best_partition_order_(
  100932. encoder->private_,
  100933. residual,
  100934. abs_residual_partition_sums,
  100935. raw_bits_per_partition,
  100936. residual_samples,
  100937. order,
  100938. rice_parameter,
  100939. rice_parameter_limit,
  100940. min_partition_order,
  100941. max_partition_order,
  100942. subframe_bps,
  100943. do_escape_coding,
  100944. rice_parameter_search_dist,
  100945. &subframe->data.fixed.entropy_coding_method
  100946. );
  100947. subframe->data.fixed.order = order;
  100948. for(i = 0; i < order; i++)
  100949. subframe->data.fixed.warmup[i] = signal[i];
  100950. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + (order * subframe_bps) + residual_bits;
  100951. #if SPOTCHECK_ESTIMATE
  100952. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  100953. #endif
  100954. return estimate;
  100955. }
  100956. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  100957. unsigned evaluate_lpc_subframe_(
  100958. FLAC__StreamEncoder *encoder,
  100959. const FLAC__int32 signal[],
  100960. FLAC__int32 residual[],
  100961. FLAC__uint64 abs_residual_partition_sums[],
  100962. unsigned raw_bits_per_partition[],
  100963. const FLAC__real lp_coeff[],
  100964. unsigned blocksize,
  100965. unsigned subframe_bps,
  100966. unsigned order,
  100967. unsigned qlp_coeff_precision,
  100968. unsigned rice_parameter,
  100969. unsigned rice_parameter_limit,
  100970. unsigned min_partition_order,
  100971. unsigned max_partition_order,
  100972. FLAC__bool do_escape_coding,
  100973. unsigned rice_parameter_search_dist,
  100974. FLAC__Subframe *subframe,
  100975. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  100976. )
  100977. {
  100978. FLAC__int32 qlp_coeff[FLAC__MAX_LPC_ORDER];
  100979. unsigned i, residual_bits, estimate;
  100980. int quantization, ret;
  100981. const unsigned residual_samples = blocksize - order;
  100982. /* try to keep qlp coeff precision such that only 32-bit math is required for decode of <=16bps streams */
  100983. if(subframe_bps <= 16) {
  100984. FLAC__ASSERT(order > 0);
  100985. FLAC__ASSERT(order <= FLAC__MAX_LPC_ORDER);
  100986. qlp_coeff_precision = min(qlp_coeff_precision, 32 - subframe_bps - FLAC__bitmath_ilog2(order));
  100987. }
  100988. ret = FLAC__lpc_quantize_coefficients(lp_coeff, order, qlp_coeff_precision, qlp_coeff, &quantization);
  100989. if(ret != 0)
  100990. return 0; /* this is a hack to indicate to the caller that we can't do lp at this order on this subframe */
  100991. if(subframe_bps + qlp_coeff_precision + FLAC__bitmath_ilog2(order) <= 32)
  100992. if(subframe_bps <= 16 && qlp_coeff_precision <= 16)
  100993. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  100994. else
  100995. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  100996. else
  100997. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  100998. subframe->type = FLAC__SUBFRAME_TYPE_LPC;
  100999. subframe->data.lpc.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
  101000. subframe->data.lpc.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
  101001. subframe->data.lpc.residual = residual;
  101002. residual_bits =
  101003. find_best_partition_order_(
  101004. encoder->private_,
  101005. residual,
  101006. abs_residual_partition_sums,
  101007. raw_bits_per_partition,
  101008. residual_samples,
  101009. order,
  101010. rice_parameter,
  101011. rice_parameter_limit,
  101012. min_partition_order,
  101013. max_partition_order,
  101014. subframe_bps,
  101015. do_escape_coding,
  101016. rice_parameter_search_dist,
  101017. &subframe->data.lpc.entropy_coding_method
  101018. );
  101019. subframe->data.lpc.order = order;
  101020. subframe->data.lpc.qlp_coeff_precision = qlp_coeff_precision;
  101021. subframe->data.lpc.quantization_level = quantization;
  101022. memcpy(subframe->data.lpc.qlp_coeff, qlp_coeff, sizeof(FLAC__int32)*FLAC__MAX_LPC_ORDER);
  101023. for(i = 0; i < order; i++)
  101024. subframe->data.lpc.warmup[i] = signal[i];
  101025. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN + FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN + (order * (qlp_coeff_precision + subframe_bps)) + residual_bits;
  101026. #if SPOTCHECK_ESTIMATE
  101027. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  101028. #endif
  101029. return estimate;
  101030. }
  101031. #endif
  101032. unsigned evaluate_verbatim_subframe_(
  101033. FLAC__StreamEncoder *encoder,
  101034. const FLAC__int32 signal[],
  101035. unsigned blocksize,
  101036. unsigned subframe_bps,
  101037. FLAC__Subframe *subframe
  101038. )
  101039. {
  101040. unsigned estimate;
  101041. subframe->type = FLAC__SUBFRAME_TYPE_VERBATIM;
  101042. subframe->data.verbatim.data = signal;
  101043. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + (blocksize * subframe_bps);
  101044. #if SPOTCHECK_ESTIMATE
  101045. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  101046. #else
  101047. (void)encoder;
  101048. #endif
  101049. return estimate;
  101050. }
  101051. unsigned find_best_partition_order_(
  101052. FLAC__StreamEncoderPrivate *private_,
  101053. const FLAC__int32 residual[],
  101054. FLAC__uint64 abs_residual_partition_sums[],
  101055. unsigned raw_bits_per_partition[],
  101056. unsigned residual_samples,
  101057. unsigned predictor_order,
  101058. unsigned rice_parameter,
  101059. unsigned rice_parameter_limit,
  101060. unsigned min_partition_order,
  101061. unsigned max_partition_order,
  101062. unsigned bps,
  101063. FLAC__bool do_escape_coding,
  101064. unsigned rice_parameter_search_dist,
  101065. FLAC__EntropyCodingMethod *best_ecm
  101066. )
  101067. {
  101068. unsigned residual_bits, best_residual_bits = 0;
  101069. unsigned best_parameters_index = 0;
  101070. unsigned best_partition_order = 0;
  101071. const unsigned blocksize = residual_samples + predictor_order;
  101072. max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(max_partition_order, blocksize, predictor_order);
  101073. min_partition_order = min(min_partition_order, max_partition_order);
  101074. precompute_partition_info_sums_(residual, abs_residual_partition_sums, residual_samples, predictor_order, min_partition_order, max_partition_order, bps);
  101075. if(do_escape_coding)
  101076. precompute_partition_info_escapes_(residual, raw_bits_per_partition, residual_samples, predictor_order, min_partition_order, max_partition_order);
  101077. {
  101078. int partition_order;
  101079. unsigned sum;
  101080. for(partition_order = (int)max_partition_order, sum = 0; partition_order >= (int)min_partition_order; partition_order--) {
  101081. if(!
  101082. set_partitioned_rice_(
  101083. #ifdef EXACT_RICE_BITS_CALCULATION
  101084. residual,
  101085. #endif
  101086. abs_residual_partition_sums+sum,
  101087. raw_bits_per_partition+sum,
  101088. residual_samples,
  101089. predictor_order,
  101090. rice_parameter,
  101091. rice_parameter_limit,
  101092. rice_parameter_search_dist,
  101093. (unsigned)partition_order,
  101094. do_escape_coding,
  101095. &private_->partitioned_rice_contents_extra[!best_parameters_index],
  101096. &residual_bits
  101097. )
  101098. )
  101099. {
  101100. FLAC__ASSERT(best_residual_bits != 0);
  101101. break;
  101102. }
  101103. sum += 1u << partition_order;
  101104. if(best_residual_bits == 0 || residual_bits < best_residual_bits) {
  101105. best_residual_bits = residual_bits;
  101106. best_parameters_index = !best_parameters_index;
  101107. best_partition_order = partition_order;
  101108. }
  101109. }
  101110. }
  101111. best_ecm->data.partitioned_rice.order = best_partition_order;
  101112. {
  101113. /*
  101114. * We are allowed to de-const the pointer based on our special
  101115. * knowledge; it is const to the outside world.
  101116. */
  101117. FLAC__EntropyCodingMethod_PartitionedRiceContents* prc = (FLAC__EntropyCodingMethod_PartitionedRiceContents*)best_ecm->data.partitioned_rice.contents;
  101118. unsigned partition;
  101119. /* save best parameters and raw_bits */
  101120. FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(prc, max(6, best_partition_order));
  101121. memcpy(prc->parameters, private_->partitioned_rice_contents_extra[best_parameters_index].parameters, sizeof(unsigned)*(1<<(best_partition_order)));
  101122. if(do_escape_coding)
  101123. memcpy(prc->raw_bits, private_->partitioned_rice_contents_extra[best_parameters_index].raw_bits, sizeof(unsigned)*(1<<(best_partition_order)));
  101124. /*
  101125. * Now need to check if the type should be changed to
  101126. * FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2 based on the
  101127. * size of the rice parameters.
  101128. */
  101129. for(partition = 0; partition < (1u<<best_partition_order); partition++) {
  101130. if(prc->parameters[partition] >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
  101131. best_ecm->type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2;
  101132. break;
  101133. }
  101134. }
  101135. }
  101136. return best_residual_bits;
  101137. }
  101138. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  101139. extern void precompute_partition_info_sums_32bit_asm_ia32_(
  101140. const FLAC__int32 residual[],
  101141. FLAC__uint64 abs_residual_partition_sums[],
  101142. unsigned blocksize,
  101143. unsigned predictor_order,
  101144. unsigned min_partition_order,
  101145. unsigned max_partition_order
  101146. );
  101147. #endif
  101148. void precompute_partition_info_sums_(
  101149. const FLAC__int32 residual[],
  101150. FLAC__uint64 abs_residual_partition_sums[],
  101151. unsigned residual_samples,
  101152. unsigned predictor_order,
  101153. unsigned min_partition_order,
  101154. unsigned max_partition_order,
  101155. unsigned bps
  101156. )
  101157. {
  101158. const unsigned default_partition_samples = (residual_samples + predictor_order) >> max_partition_order;
  101159. unsigned partitions = 1u << max_partition_order;
  101160. FLAC__ASSERT(default_partition_samples > predictor_order);
  101161. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  101162. /* slightly pessimistic but still catches all common cases */
  101163. /* WATCHOUT: "+ bps" is an assumption that the average residual magnitude will not be more than "bps" bits */
  101164. if(FLAC__bitmath_ilog2(default_partition_samples) + bps < 32) {
  101165. precompute_partition_info_sums_32bit_asm_ia32_(residual, abs_residual_partition_sums, residual_samples + predictor_order, predictor_order, min_partition_order, max_partition_order);
  101166. return;
  101167. }
  101168. #endif
  101169. /* first do max_partition_order */
  101170. {
  101171. unsigned partition, residual_sample, end = (unsigned)(-(int)predictor_order);
  101172. /* slightly pessimistic but still catches all common cases */
  101173. /* WATCHOUT: "+ bps" is an assumption that the average residual magnitude will not be more than "bps" bits */
  101174. if(FLAC__bitmath_ilog2(default_partition_samples) + bps < 32) {
  101175. FLAC__uint32 abs_residual_partition_sum;
  101176. for(partition = residual_sample = 0; partition < partitions; partition++) {
  101177. end += default_partition_samples;
  101178. abs_residual_partition_sum = 0;
  101179. for( ; residual_sample < end; residual_sample++)
  101180. abs_residual_partition_sum += abs(residual[residual_sample]); /* abs(INT_MIN) is undefined, but if the residual is INT_MIN we have bigger problems */
  101181. abs_residual_partition_sums[partition] = abs_residual_partition_sum;
  101182. }
  101183. }
  101184. else { /* have to pessimistically use 64 bits for accumulator */
  101185. FLAC__uint64 abs_residual_partition_sum;
  101186. for(partition = residual_sample = 0; partition < partitions; partition++) {
  101187. end += default_partition_samples;
  101188. abs_residual_partition_sum = 0;
  101189. for( ; residual_sample < end; residual_sample++)
  101190. abs_residual_partition_sum += abs(residual[residual_sample]); /* abs(INT_MIN) is undefined, but if the residual is INT_MIN we have bigger problems */
  101191. abs_residual_partition_sums[partition] = abs_residual_partition_sum;
  101192. }
  101193. }
  101194. }
  101195. /* now merge partitions for lower orders */
  101196. {
  101197. unsigned from_partition = 0, to_partition = partitions;
  101198. int partition_order;
  101199. for(partition_order = (int)max_partition_order - 1; partition_order >= (int)min_partition_order; partition_order--) {
  101200. unsigned i;
  101201. partitions >>= 1;
  101202. for(i = 0; i < partitions; i++) {
  101203. abs_residual_partition_sums[to_partition++] =
  101204. abs_residual_partition_sums[from_partition ] +
  101205. abs_residual_partition_sums[from_partition+1];
  101206. from_partition += 2;
  101207. }
  101208. }
  101209. }
  101210. }
  101211. void precompute_partition_info_escapes_(
  101212. const FLAC__int32 residual[],
  101213. unsigned raw_bits_per_partition[],
  101214. unsigned residual_samples,
  101215. unsigned predictor_order,
  101216. unsigned min_partition_order,
  101217. unsigned max_partition_order
  101218. )
  101219. {
  101220. int partition_order;
  101221. unsigned from_partition, to_partition = 0;
  101222. const unsigned blocksize = residual_samples + predictor_order;
  101223. /* first do max_partition_order */
  101224. for(partition_order = (int)max_partition_order; partition_order >= 0; partition_order--) {
  101225. FLAC__int32 r;
  101226. FLAC__uint32 rmax;
  101227. unsigned partition, partition_sample, partition_samples, residual_sample;
  101228. const unsigned partitions = 1u << partition_order;
  101229. const unsigned default_partition_samples = blocksize >> partition_order;
  101230. FLAC__ASSERT(default_partition_samples > predictor_order);
  101231. for(partition = residual_sample = 0; partition < partitions; partition++) {
  101232. partition_samples = default_partition_samples;
  101233. if(partition == 0)
  101234. partition_samples -= predictor_order;
  101235. rmax = 0;
  101236. for(partition_sample = 0; partition_sample < partition_samples; partition_sample++) {
  101237. r = residual[residual_sample++];
  101238. /* OPT: maybe faster: rmax |= r ^ (r>>31) */
  101239. if(r < 0)
  101240. rmax |= ~r;
  101241. else
  101242. rmax |= r;
  101243. }
  101244. /* now we know all residual values are in the range [-rmax-1,rmax] */
  101245. raw_bits_per_partition[partition] = rmax? FLAC__bitmath_ilog2(rmax) + 2 : 1;
  101246. }
  101247. to_partition = partitions;
  101248. break; /*@@@ yuck, should remove the 'for' loop instead */
  101249. }
  101250. /* now merge partitions for lower orders */
  101251. for(from_partition = 0, --partition_order; partition_order >= (int)min_partition_order; partition_order--) {
  101252. unsigned m;
  101253. unsigned i;
  101254. const unsigned partitions = 1u << partition_order;
  101255. for(i = 0; i < partitions; i++) {
  101256. m = raw_bits_per_partition[from_partition];
  101257. from_partition++;
  101258. raw_bits_per_partition[to_partition] = max(m, raw_bits_per_partition[from_partition]);
  101259. from_partition++;
  101260. to_partition++;
  101261. }
  101262. }
  101263. }
  101264. #ifdef EXACT_RICE_BITS_CALCULATION
  101265. static FLaC__INLINE unsigned count_rice_bits_in_partition_(
  101266. const unsigned rice_parameter,
  101267. const unsigned partition_samples,
  101268. const FLAC__int32 *residual
  101269. )
  101270. {
  101271. unsigned i, partition_bits =
  101272. FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN + /* actually could end up being FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN but err on side of 16bps */
  101273. (1+rice_parameter) * partition_samples /* 1 for unary stop bit + rice_parameter for the binary portion */
  101274. ;
  101275. for(i = 0; i < partition_samples; i++)
  101276. partition_bits += ( (FLAC__uint32)((residual[i]<<1)^(residual[i]>>31)) >> rice_parameter );
  101277. return partition_bits;
  101278. }
  101279. #else
  101280. static FLaC__INLINE unsigned count_rice_bits_in_partition_(
  101281. const unsigned rice_parameter,
  101282. const unsigned partition_samples,
  101283. const FLAC__uint64 abs_residual_partition_sum
  101284. )
  101285. {
  101286. return
  101287. FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN + /* actually could end up being FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN but err on side of 16bps */
  101288. (1+rice_parameter) * partition_samples + /* 1 for unary stop bit + rice_parameter for the binary portion */
  101289. (
  101290. rice_parameter?
  101291. (unsigned)(abs_residual_partition_sum >> (rice_parameter-1)) /* rice_parameter-1 because the real coder sign-folds instead of using a sign bit */
  101292. : (unsigned)(abs_residual_partition_sum << 1) /* can't shift by negative number, so reverse */
  101293. )
  101294. - (partition_samples >> 1)
  101295. /* -(partition_samples>>1) to subtract out extra contributions to the abs_residual_partition_sum.
  101296. * The actual number of bits used is closer to the sum(for all i in the partition) of abs(residual[i])>>(rice_parameter-1)
  101297. * By using the abs_residual_partition sum, we also add in bits in the LSBs that would normally be shifted out.
  101298. * So the subtraction term tries to guess how many extra bits were contributed.
  101299. * If the LSBs are randomly distributed, this should average to 0.5 extra bits per sample.
  101300. */
  101301. ;
  101302. }
  101303. #endif
  101304. FLAC__bool set_partitioned_rice_(
  101305. #ifdef EXACT_RICE_BITS_CALCULATION
  101306. const FLAC__int32 residual[],
  101307. #endif
  101308. const FLAC__uint64 abs_residual_partition_sums[],
  101309. const unsigned raw_bits_per_partition[],
  101310. const unsigned residual_samples,
  101311. const unsigned predictor_order,
  101312. const unsigned suggested_rice_parameter,
  101313. const unsigned rice_parameter_limit,
  101314. const unsigned rice_parameter_search_dist,
  101315. const unsigned partition_order,
  101316. const FLAC__bool search_for_escapes,
  101317. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
  101318. unsigned *bits
  101319. )
  101320. {
  101321. unsigned rice_parameter, partition_bits;
  101322. unsigned best_partition_bits, best_rice_parameter = 0;
  101323. unsigned bits_ = FLAC__ENTROPY_CODING_METHOD_TYPE_LEN + FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN;
  101324. unsigned *parameters, *raw_bits;
  101325. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  101326. unsigned min_rice_parameter, max_rice_parameter;
  101327. #else
  101328. (void)rice_parameter_search_dist;
  101329. #endif
  101330. FLAC__ASSERT(suggested_rice_parameter < FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER);
  101331. FLAC__ASSERT(rice_parameter_limit <= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER);
  101332. FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(partitioned_rice_contents, max(6, partition_order));
  101333. parameters = partitioned_rice_contents->parameters;
  101334. raw_bits = partitioned_rice_contents->raw_bits;
  101335. if(partition_order == 0) {
  101336. best_partition_bits = (unsigned)(-1);
  101337. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  101338. if(rice_parameter_search_dist) {
  101339. if(suggested_rice_parameter < rice_parameter_search_dist)
  101340. min_rice_parameter = 0;
  101341. else
  101342. min_rice_parameter = suggested_rice_parameter - rice_parameter_search_dist;
  101343. max_rice_parameter = suggested_rice_parameter + rice_parameter_search_dist;
  101344. if(max_rice_parameter >= rice_parameter_limit) {
  101345. #ifdef DEBUG_VERBOSE
  101346. fprintf(stderr, "clipping rice_parameter (%u -> %u) @5\n", max_rice_parameter, rice_parameter_limit - 1);
  101347. #endif
  101348. max_rice_parameter = rice_parameter_limit - 1;
  101349. }
  101350. }
  101351. else
  101352. min_rice_parameter = max_rice_parameter = suggested_rice_parameter;
  101353. for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
  101354. #else
  101355. rice_parameter = suggested_rice_parameter;
  101356. #endif
  101357. #ifdef EXACT_RICE_BITS_CALCULATION
  101358. partition_bits = count_rice_bits_in_partition_(rice_parameter, residual_samples, residual);
  101359. #else
  101360. partition_bits = count_rice_bits_in_partition_(rice_parameter, residual_samples, abs_residual_partition_sums[0]);
  101361. #endif
  101362. if(partition_bits < best_partition_bits) {
  101363. best_rice_parameter = rice_parameter;
  101364. best_partition_bits = partition_bits;
  101365. }
  101366. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  101367. }
  101368. #endif
  101369. if(search_for_escapes) {
  101370. partition_bits = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN + FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN + raw_bits_per_partition[0] * residual_samples;
  101371. if(partition_bits <= best_partition_bits) {
  101372. raw_bits[0] = raw_bits_per_partition[0];
  101373. best_rice_parameter = 0; /* will be converted to appropriate escape parameter later */
  101374. best_partition_bits = partition_bits;
  101375. }
  101376. else
  101377. raw_bits[0] = 0;
  101378. }
  101379. parameters[0] = best_rice_parameter;
  101380. bits_ += best_partition_bits;
  101381. }
  101382. else {
  101383. unsigned partition, residual_sample;
  101384. unsigned partition_samples;
  101385. FLAC__uint64 mean, k;
  101386. const unsigned partitions = 1u << partition_order;
  101387. for(partition = residual_sample = 0; partition < partitions; partition++) {
  101388. partition_samples = (residual_samples+predictor_order) >> partition_order;
  101389. if(partition == 0) {
  101390. if(partition_samples <= predictor_order)
  101391. return false;
  101392. else
  101393. partition_samples -= predictor_order;
  101394. }
  101395. mean = abs_residual_partition_sums[partition];
  101396. /* we are basically calculating the size in bits of the
  101397. * average residual magnitude in the partition:
  101398. * rice_parameter = floor(log2(mean/partition_samples))
  101399. * 'mean' is not a good name for the variable, it is
  101400. * actually the sum of magnitudes of all residual values
  101401. * in the partition, so the actual mean is
  101402. * mean/partition_samples
  101403. */
  101404. for(rice_parameter = 0, k = partition_samples; k < mean; rice_parameter++, k <<= 1)
  101405. ;
  101406. if(rice_parameter >= rice_parameter_limit) {
  101407. #ifdef DEBUG_VERBOSE
  101408. fprintf(stderr, "clipping rice_parameter (%u -> %u) @6\n", rice_parameter, rice_parameter_limit - 1);
  101409. #endif
  101410. rice_parameter = rice_parameter_limit - 1;
  101411. }
  101412. best_partition_bits = (unsigned)(-1);
  101413. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  101414. if(rice_parameter_search_dist) {
  101415. if(rice_parameter < rice_parameter_search_dist)
  101416. min_rice_parameter = 0;
  101417. else
  101418. min_rice_parameter = rice_parameter - rice_parameter_search_dist;
  101419. max_rice_parameter = rice_parameter + rice_parameter_search_dist;
  101420. if(max_rice_parameter >= rice_parameter_limit) {
  101421. #ifdef DEBUG_VERBOSE
  101422. fprintf(stderr, "clipping rice_parameter (%u -> %u) @7\n", max_rice_parameter, rice_parameter_limit - 1);
  101423. #endif
  101424. max_rice_parameter = rice_parameter_limit - 1;
  101425. }
  101426. }
  101427. else
  101428. min_rice_parameter = max_rice_parameter = rice_parameter;
  101429. for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
  101430. #endif
  101431. #ifdef EXACT_RICE_BITS_CALCULATION
  101432. partition_bits = count_rice_bits_in_partition_(rice_parameter, partition_samples, residual+residual_sample);
  101433. #else
  101434. partition_bits = count_rice_bits_in_partition_(rice_parameter, partition_samples, abs_residual_partition_sums[partition]);
  101435. #endif
  101436. if(partition_bits < best_partition_bits) {
  101437. best_rice_parameter = rice_parameter;
  101438. best_partition_bits = partition_bits;
  101439. }
  101440. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  101441. }
  101442. #endif
  101443. if(search_for_escapes) {
  101444. partition_bits = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN + FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN + raw_bits_per_partition[partition] * partition_samples;
  101445. if(partition_bits <= best_partition_bits) {
  101446. raw_bits[partition] = raw_bits_per_partition[partition];
  101447. best_rice_parameter = 0; /* will be converted to appropriate escape parameter later */
  101448. best_partition_bits = partition_bits;
  101449. }
  101450. else
  101451. raw_bits[partition] = 0;
  101452. }
  101453. parameters[partition] = best_rice_parameter;
  101454. bits_ += best_partition_bits;
  101455. residual_sample += partition_samples;
  101456. }
  101457. }
  101458. *bits = bits_;
  101459. return true;
  101460. }
  101461. unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples)
  101462. {
  101463. unsigned i, shift;
  101464. FLAC__int32 x = 0;
  101465. for(i = 0; i < samples && !(x&1); i++)
  101466. x |= signal[i];
  101467. if(x == 0) {
  101468. shift = 0;
  101469. }
  101470. else {
  101471. for(shift = 0; !(x&1); shift++)
  101472. x >>= 1;
  101473. }
  101474. if(shift > 0) {
  101475. for(i = 0; i < samples; i++)
  101476. signal[i] >>= shift;
  101477. }
  101478. return shift;
  101479. }
  101480. void append_to_verify_fifo_(verify_input_fifo *fifo, const FLAC__int32 * const input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
  101481. {
  101482. unsigned channel;
  101483. for(channel = 0; channel < channels; channel++)
  101484. memcpy(&fifo->data[channel][fifo->tail], &input[channel][input_offset], sizeof(FLAC__int32) * wide_samples);
  101485. fifo->tail += wide_samples;
  101486. FLAC__ASSERT(fifo->tail <= fifo->size);
  101487. }
  101488. void append_to_verify_fifo_interleaved_(verify_input_fifo *fifo, const FLAC__int32 input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
  101489. {
  101490. unsigned channel;
  101491. unsigned sample, wide_sample;
  101492. unsigned tail = fifo->tail;
  101493. sample = input_offset * channels;
  101494. for(wide_sample = 0; wide_sample < wide_samples; wide_sample++) {
  101495. for(channel = 0; channel < channels; channel++)
  101496. fifo->data[channel][tail] = input[sample++];
  101497. tail++;
  101498. }
  101499. fifo->tail = tail;
  101500. FLAC__ASSERT(fifo->tail <= fifo->size);
  101501. }
  101502. FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  101503. {
  101504. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
  101505. const size_t encoded_bytes = encoder->private_->verify.output.bytes;
  101506. (void)decoder;
  101507. if(encoder->private_->verify.needs_magic_hack) {
  101508. FLAC__ASSERT(*bytes >= FLAC__STREAM_SYNC_LENGTH);
  101509. *bytes = FLAC__STREAM_SYNC_LENGTH;
  101510. memcpy(buffer, FLAC__STREAM_SYNC_STRING, *bytes);
  101511. encoder->private_->verify.needs_magic_hack = false;
  101512. }
  101513. else {
  101514. if(encoded_bytes == 0) {
  101515. /*
  101516. * If we get here, a FIFO underflow has occurred,
  101517. * which means there is a bug somewhere.
  101518. */
  101519. FLAC__ASSERT(0);
  101520. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  101521. }
  101522. else if(encoded_bytes < *bytes)
  101523. *bytes = encoded_bytes;
  101524. memcpy(buffer, encoder->private_->verify.output.data, *bytes);
  101525. encoder->private_->verify.output.data += *bytes;
  101526. encoder->private_->verify.output.bytes -= *bytes;
  101527. }
  101528. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  101529. }
  101530. FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data)
  101531. {
  101532. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder *)client_data;
  101533. unsigned channel;
  101534. const unsigned channels = frame->header.channels;
  101535. const unsigned blocksize = frame->header.blocksize;
  101536. const unsigned bytes_per_block = sizeof(FLAC__int32) * blocksize;
  101537. (void)decoder;
  101538. for(channel = 0; channel < channels; channel++) {
  101539. if(0 != memcmp(buffer[channel], encoder->private_->verify.input_fifo.data[channel], bytes_per_block)) {
  101540. unsigned i, sample = 0;
  101541. FLAC__int32 expect = 0, got = 0;
  101542. for(i = 0; i < blocksize; i++) {
  101543. if(buffer[channel][i] != encoder->private_->verify.input_fifo.data[channel][i]) {
  101544. sample = i;
  101545. expect = (FLAC__int32)encoder->private_->verify.input_fifo.data[channel][i];
  101546. got = (FLAC__int32)buffer[channel][i];
  101547. break;
  101548. }
  101549. }
  101550. FLAC__ASSERT(i < blocksize);
  101551. FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  101552. encoder->private_->verify.error_stats.absolute_sample = frame->header.number.sample_number + sample;
  101553. encoder->private_->verify.error_stats.frame_number = (unsigned)(frame->header.number.sample_number / blocksize);
  101554. encoder->private_->verify.error_stats.channel = channel;
  101555. encoder->private_->verify.error_stats.sample = sample;
  101556. encoder->private_->verify.error_stats.expected = expect;
  101557. encoder->private_->verify.error_stats.got = got;
  101558. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
  101559. return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
  101560. }
  101561. }
  101562. /* dequeue the frame from the fifo */
  101563. encoder->private_->verify.input_fifo.tail -= blocksize;
  101564. FLAC__ASSERT(encoder->private_->verify.input_fifo.tail <= OVERREAD_);
  101565. for(channel = 0; channel < channels; channel++)
  101566. memmove(&encoder->private_->verify.input_fifo.data[channel][0], &encoder->private_->verify.input_fifo.data[channel][blocksize], encoder->private_->verify.input_fifo.tail * sizeof(encoder->private_->verify.input_fifo.data[0][0]));
  101567. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  101568. }
  101569. void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data)
  101570. {
  101571. (void)decoder, (void)metadata, (void)client_data;
  101572. }
  101573. void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
  101574. {
  101575. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
  101576. (void)decoder, (void)status;
  101577. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  101578. }
  101579. FLAC__StreamEncoderReadStatus file_read_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  101580. {
  101581. (void)client_data;
  101582. *bytes = fread(buffer, 1, *bytes, encoder->private_->file);
  101583. if (*bytes == 0) {
  101584. if (feof(encoder->private_->file))
  101585. return FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM;
  101586. else if (ferror(encoder->private_->file))
  101587. return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  101588. }
  101589. return FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE;
  101590. }
  101591. FLAC__StreamEncoderSeekStatus file_seek_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  101592. {
  101593. (void)client_data;
  101594. if(fseeko(encoder->private_->file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  101595. return FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR;
  101596. else
  101597. return FLAC__STREAM_ENCODER_SEEK_STATUS_OK;
  101598. }
  101599. FLAC__StreamEncoderTellStatus file_tell_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  101600. {
  101601. off_t offset;
  101602. (void)client_data;
  101603. offset = ftello(encoder->private_->file);
  101604. if(offset < 0) {
  101605. return FLAC__STREAM_ENCODER_TELL_STATUS_ERROR;
  101606. }
  101607. else {
  101608. *absolute_byte_offset = (FLAC__uint64)offset;
  101609. return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
  101610. }
  101611. }
  101612. #ifdef FLAC__VALGRIND_TESTING
  101613. static size_t local__fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream)
  101614. {
  101615. size_t ret = fwrite(ptr, size, nmemb, stream);
  101616. if(!ferror(stream))
  101617. fflush(stream);
  101618. return ret;
  101619. }
  101620. #else
  101621. #define local__fwrite fwrite
  101622. #endif
  101623. FLAC__StreamEncoderWriteStatus file_write_callback_(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data)
  101624. {
  101625. (void)client_data, (void)current_frame;
  101626. if(local__fwrite(buffer, sizeof(FLAC__byte), bytes, encoder->private_->file) == bytes) {
  101627. FLAC__bool call_it = 0 != encoder->private_->progress_callback && (
  101628. #if FLAC__HAS_OGG
  101629. /* We would like to be able to use 'samples > 0' in the
  101630. * clause here but currently because of the nature of our
  101631. * Ogg writing implementation, 'samples' is always 0 (see
  101632. * ogg_encoder_aspect.c). The downside is extra progress
  101633. * callbacks.
  101634. */
  101635. encoder->private_->is_ogg? true :
  101636. #endif
  101637. samples > 0
  101638. );
  101639. if(call_it) {
  101640. /* NOTE: We have to add +bytes, +samples, and +1 to the stats
  101641. * because at this point in the callback chain, the stats
  101642. * have not been updated. Only after we return and control
  101643. * gets back to write_frame_() are the stats updated
  101644. */
  101645. encoder->private_->progress_callback(encoder, encoder->private_->bytes_written+bytes, encoder->private_->samples_written+samples, encoder->private_->frames_written+(samples?1:0), encoder->private_->total_frames_estimate, encoder->private_->client_data);
  101646. }
  101647. return FLAC__STREAM_ENCODER_WRITE_STATUS_OK;
  101648. }
  101649. else
  101650. return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  101651. }
  101652. /*
  101653. * This will forcibly set stdout to binary mode (for OSes that require it)
  101654. */
  101655. FILE *get_binary_stdout_(void)
  101656. {
  101657. /* if something breaks here it is probably due to the presence or
  101658. * absence of an underscore before the identifiers 'setmode',
  101659. * 'fileno', and/or 'O_BINARY'; check your system header files.
  101660. */
  101661. #if defined _MSC_VER || defined __MINGW32__
  101662. _setmode(_fileno(stdout), _O_BINARY);
  101663. #elif defined __CYGWIN__
  101664. /* almost certainly not needed for any modern Cygwin, but let's be safe... */
  101665. setmode(_fileno(stdout), _O_BINARY);
  101666. #elif defined __EMX__
  101667. setmode(fileno(stdout), O_BINARY);
  101668. #endif
  101669. return stdout;
  101670. }
  101671. #endif
  101672. /********* End of inlined file: stream_encoder.c *********/
  101673. /********* Start of inlined file: stream_encoder_framing.c *********/
  101674. /********* Start of inlined file: juce_FlacHeader.h *********/
  101675. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  101676. // tasks..
  101677. #define VERSION "1.2.1"
  101678. #define FLAC__NO_DLL 1
  101679. #ifdef _MSC_VER
  101680. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  101681. #endif
  101682. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  101683. #define FLAC__SYS_DARWIN 1
  101684. #endif
  101685. /********* End of inlined file: juce_FlacHeader.h *********/
  101686. #if JUCE_USE_FLAC
  101687. #if HAVE_CONFIG_H
  101688. # include <config.h>
  101689. #endif
  101690. #include <stdio.h>
  101691. #include <string.h> /* for strlen() */
  101692. #ifdef max
  101693. #undef max
  101694. #endif
  101695. #define max(x,y) ((x)>(y)?(x):(y))
  101696. static FLAC__bool add_entropy_coding_method_(FLAC__BitWriter *bw, const FLAC__EntropyCodingMethod *method);
  101697. static FLAC__bool add_residual_partitioned_rice_(FLAC__BitWriter *bw, const FLAC__int32 residual[], const unsigned residual_samples, const unsigned predictor_order, const unsigned rice_parameters[], const unsigned raw_bits[], const unsigned partition_order, const FLAC__bool is_extended);
  101698. FLAC__bool FLAC__add_metadata_block(const FLAC__StreamMetadata *metadata, FLAC__BitWriter *bw)
  101699. {
  101700. unsigned i, j;
  101701. const unsigned vendor_string_length = (unsigned)strlen(FLAC__VENDOR_STRING);
  101702. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->is_last, FLAC__STREAM_METADATA_IS_LAST_LEN))
  101703. return false;
  101704. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->type, FLAC__STREAM_METADATA_TYPE_LEN))
  101705. return false;
  101706. /*
  101707. * First, for VORBIS_COMMENTs, adjust the length to reflect our vendor string
  101708. */
  101709. i = metadata->length;
  101710. if(metadata->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  101711. FLAC__ASSERT(metadata->data.vorbis_comment.vendor_string.length == 0 || 0 != metadata->data.vorbis_comment.vendor_string.entry);
  101712. i -= metadata->data.vorbis_comment.vendor_string.length;
  101713. i += vendor_string_length;
  101714. }
  101715. FLAC__ASSERT(i < (1u << FLAC__STREAM_METADATA_LENGTH_LEN));
  101716. if(!FLAC__bitwriter_write_raw_uint32(bw, i, FLAC__STREAM_METADATA_LENGTH_LEN))
  101717. return false;
  101718. switch(metadata->type) {
  101719. case FLAC__METADATA_TYPE_STREAMINFO:
  101720. FLAC__ASSERT(metadata->data.stream_info.min_blocksize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN));
  101721. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.min_blocksize, FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN))
  101722. return false;
  101723. FLAC__ASSERT(metadata->data.stream_info.max_blocksize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN));
  101724. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.max_blocksize, FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN))
  101725. return false;
  101726. FLAC__ASSERT(metadata->data.stream_info.min_framesize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN));
  101727. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.min_framesize, FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN))
  101728. return false;
  101729. FLAC__ASSERT(metadata->data.stream_info.max_framesize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN));
  101730. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.max_framesize, FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN))
  101731. return false;
  101732. FLAC__ASSERT(FLAC__format_sample_rate_is_valid(metadata->data.stream_info.sample_rate));
  101733. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.sample_rate, FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN))
  101734. return false;
  101735. FLAC__ASSERT(metadata->data.stream_info.channels > 0);
  101736. FLAC__ASSERT(metadata->data.stream_info.channels <= (1u << FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN));
  101737. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.channels-1, FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN))
  101738. return false;
  101739. FLAC__ASSERT(metadata->data.stream_info.bits_per_sample > 0);
  101740. FLAC__ASSERT(metadata->data.stream_info.bits_per_sample <= (1u << FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN));
  101741. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.bits_per_sample-1, FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN))
  101742. return false;
  101743. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.stream_info.total_samples, FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN))
  101744. return false;
  101745. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.stream_info.md5sum, 16))
  101746. return false;
  101747. break;
  101748. case FLAC__METADATA_TYPE_PADDING:
  101749. if(!FLAC__bitwriter_write_zeroes(bw, metadata->length * 8))
  101750. return false;
  101751. break;
  101752. case FLAC__METADATA_TYPE_APPLICATION:
  101753. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.application.id, FLAC__STREAM_METADATA_APPLICATION_ID_LEN / 8))
  101754. return false;
  101755. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.application.data, metadata->length - (FLAC__STREAM_METADATA_APPLICATION_ID_LEN / 8)))
  101756. return false;
  101757. break;
  101758. case FLAC__METADATA_TYPE_SEEKTABLE:
  101759. for(i = 0; i < metadata->data.seek_table.num_points; i++) {
  101760. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.seek_table.points[i].sample_number, FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN))
  101761. return false;
  101762. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.seek_table.points[i].stream_offset, FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN))
  101763. return false;
  101764. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.seek_table.points[i].frame_samples, FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN))
  101765. return false;
  101766. }
  101767. break;
  101768. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  101769. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, vendor_string_length))
  101770. return false;
  101771. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)FLAC__VENDOR_STRING, vendor_string_length))
  101772. return false;
  101773. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, metadata->data.vorbis_comment.num_comments))
  101774. return false;
  101775. for(i = 0; i < metadata->data.vorbis_comment.num_comments; i++) {
  101776. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, metadata->data.vorbis_comment.comments[i].length))
  101777. return false;
  101778. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.vorbis_comment.comments[i].entry, metadata->data.vorbis_comment.comments[i].length))
  101779. return false;
  101780. }
  101781. break;
  101782. case FLAC__METADATA_TYPE_CUESHEET:
  101783. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN % 8 == 0);
  101784. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)metadata->data.cue_sheet.media_catalog_number, FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN/8))
  101785. return false;
  101786. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.cue_sheet.lead_in, FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN))
  101787. return false;
  101788. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.cue_sheet.is_cd? 1 : 0, FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN))
  101789. return false;
  101790. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN))
  101791. return false;
  101792. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.cue_sheet.num_tracks, FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN))
  101793. return false;
  101794. for(i = 0; i < metadata->data.cue_sheet.num_tracks; i++) {
  101795. const FLAC__StreamMetadata_CueSheet_Track *track = metadata->data.cue_sheet.tracks + i;
  101796. if(!FLAC__bitwriter_write_raw_uint64(bw, track->offset, FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN))
  101797. return false;
  101798. if(!FLAC__bitwriter_write_raw_uint32(bw, track->number, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN))
  101799. return false;
  101800. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN % 8 == 0);
  101801. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)track->isrc, FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN/8))
  101802. return false;
  101803. if(!FLAC__bitwriter_write_raw_uint32(bw, track->type, FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN))
  101804. return false;
  101805. if(!FLAC__bitwriter_write_raw_uint32(bw, track->pre_emphasis, FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN))
  101806. return false;
  101807. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN))
  101808. return false;
  101809. if(!FLAC__bitwriter_write_raw_uint32(bw, track->num_indices, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN))
  101810. return false;
  101811. for(j = 0; j < track->num_indices; j++) {
  101812. const FLAC__StreamMetadata_CueSheet_Index *index = track->indices + j;
  101813. if(!FLAC__bitwriter_write_raw_uint64(bw, index->offset, FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN))
  101814. return false;
  101815. if(!FLAC__bitwriter_write_raw_uint32(bw, index->number, FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN))
  101816. return false;
  101817. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN))
  101818. return false;
  101819. }
  101820. }
  101821. break;
  101822. case FLAC__METADATA_TYPE_PICTURE:
  101823. {
  101824. size_t len;
  101825. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.type, FLAC__STREAM_METADATA_PICTURE_TYPE_LEN))
  101826. return false;
  101827. len = strlen(metadata->data.picture.mime_type);
  101828. if(!FLAC__bitwriter_write_raw_uint32(bw, len, FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN))
  101829. return false;
  101830. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)metadata->data.picture.mime_type, len))
  101831. return false;
  101832. len = strlen((const char *)metadata->data.picture.description);
  101833. if(!FLAC__bitwriter_write_raw_uint32(bw, len, FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN))
  101834. return false;
  101835. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.picture.description, len))
  101836. return false;
  101837. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.width, FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN))
  101838. return false;
  101839. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.height, FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN))
  101840. return false;
  101841. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.depth, FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN))
  101842. return false;
  101843. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.colors, FLAC__STREAM_METADATA_PICTURE_COLORS_LEN))
  101844. return false;
  101845. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.data_length, FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN))
  101846. return false;
  101847. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.picture.data, metadata->data.picture.data_length))
  101848. return false;
  101849. }
  101850. break;
  101851. default:
  101852. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.unknown.data, metadata->length))
  101853. return false;
  101854. break;
  101855. }
  101856. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(bw));
  101857. return true;
  101858. }
  101859. FLAC__bool FLAC__frame_add_header(const FLAC__FrameHeader *header, FLAC__BitWriter *bw)
  101860. {
  101861. unsigned u, blocksize_hint, sample_rate_hint;
  101862. FLAC__byte crc;
  101863. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(bw));
  101864. if(!FLAC__bitwriter_write_raw_uint32(bw, FLAC__FRAME_HEADER_SYNC, FLAC__FRAME_HEADER_SYNC_LEN))
  101865. return false;
  101866. if(!FLAC__bitwriter_write_raw_uint32(bw, 0, FLAC__FRAME_HEADER_RESERVED_LEN))
  101867. return false;
  101868. if(!FLAC__bitwriter_write_raw_uint32(bw, (header->number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER)? 0 : 1, FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN))
  101869. return false;
  101870. FLAC__ASSERT(header->blocksize > 0 && header->blocksize <= FLAC__MAX_BLOCK_SIZE);
  101871. /* when this assertion holds true, any legal blocksize can be expressed in the frame header */
  101872. FLAC__ASSERT(FLAC__MAX_BLOCK_SIZE <= 65535u);
  101873. blocksize_hint = 0;
  101874. switch(header->blocksize) {
  101875. case 192: u = 1; break;
  101876. case 576: u = 2; break;
  101877. case 1152: u = 3; break;
  101878. case 2304: u = 4; break;
  101879. case 4608: u = 5; break;
  101880. case 256: u = 8; break;
  101881. case 512: u = 9; break;
  101882. case 1024: u = 10; break;
  101883. case 2048: u = 11; break;
  101884. case 4096: u = 12; break;
  101885. case 8192: u = 13; break;
  101886. case 16384: u = 14; break;
  101887. case 32768: u = 15; break;
  101888. default:
  101889. if(header->blocksize <= 0x100)
  101890. blocksize_hint = u = 6;
  101891. else
  101892. blocksize_hint = u = 7;
  101893. break;
  101894. }
  101895. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_BLOCK_SIZE_LEN))
  101896. return false;
  101897. FLAC__ASSERT(FLAC__format_sample_rate_is_valid(header->sample_rate));
  101898. sample_rate_hint = 0;
  101899. switch(header->sample_rate) {
  101900. case 88200: u = 1; break;
  101901. case 176400: u = 2; break;
  101902. case 192000: u = 3; break;
  101903. case 8000: u = 4; break;
  101904. case 16000: u = 5; break;
  101905. case 22050: u = 6; break;
  101906. case 24000: u = 7; break;
  101907. case 32000: u = 8; break;
  101908. case 44100: u = 9; break;
  101909. case 48000: u = 10; break;
  101910. case 96000: u = 11; break;
  101911. default:
  101912. if(header->sample_rate <= 255000 && header->sample_rate % 1000 == 0)
  101913. sample_rate_hint = u = 12;
  101914. else if(header->sample_rate % 10 == 0)
  101915. sample_rate_hint = u = 14;
  101916. else if(header->sample_rate <= 0xffff)
  101917. sample_rate_hint = u = 13;
  101918. else
  101919. u = 0;
  101920. break;
  101921. }
  101922. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_SAMPLE_RATE_LEN))
  101923. return false;
  101924. FLAC__ASSERT(header->channels > 0 && header->channels <= (1u << FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN) && header->channels <= FLAC__MAX_CHANNELS);
  101925. switch(header->channel_assignment) {
  101926. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  101927. u = header->channels - 1;
  101928. break;
  101929. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  101930. FLAC__ASSERT(header->channels == 2);
  101931. u = 8;
  101932. break;
  101933. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  101934. FLAC__ASSERT(header->channels == 2);
  101935. u = 9;
  101936. break;
  101937. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  101938. FLAC__ASSERT(header->channels == 2);
  101939. u = 10;
  101940. break;
  101941. default:
  101942. FLAC__ASSERT(0);
  101943. }
  101944. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN))
  101945. return false;
  101946. FLAC__ASSERT(header->bits_per_sample > 0 && header->bits_per_sample <= (1u << FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN));
  101947. switch(header->bits_per_sample) {
  101948. case 8 : u = 1; break;
  101949. case 12: u = 2; break;
  101950. case 16: u = 4; break;
  101951. case 20: u = 5; break;
  101952. case 24: u = 6; break;
  101953. default: u = 0; break;
  101954. }
  101955. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN))
  101956. return false;
  101957. if(!FLAC__bitwriter_write_raw_uint32(bw, 0, FLAC__FRAME_HEADER_ZERO_PAD_LEN))
  101958. return false;
  101959. if(header->number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER) {
  101960. if(!FLAC__bitwriter_write_utf8_uint32(bw, header->number.frame_number))
  101961. return false;
  101962. }
  101963. else {
  101964. if(!FLAC__bitwriter_write_utf8_uint64(bw, header->number.sample_number))
  101965. return false;
  101966. }
  101967. if(blocksize_hint)
  101968. if(!FLAC__bitwriter_write_raw_uint32(bw, header->blocksize-1, (blocksize_hint==6)? 8:16))
  101969. return false;
  101970. switch(sample_rate_hint) {
  101971. case 12:
  101972. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate / 1000, 8))
  101973. return false;
  101974. break;
  101975. case 13:
  101976. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate, 16))
  101977. return false;
  101978. break;
  101979. case 14:
  101980. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate / 10, 16))
  101981. return false;
  101982. break;
  101983. }
  101984. /* write the CRC */
  101985. if(!FLAC__bitwriter_get_write_crc8(bw, &crc))
  101986. return false;
  101987. if(!FLAC__bitwriter_write_raw_uint32(bw, crc, FLAC__FRAME_HEADER_CRC_LEN))
  101988. return false;
  101989. return true;
  101990. }
  101991. FLAC__bool FLAC__subframe_add_constant(const FLAC__Subframe_Constant *subframe, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  101992. {
  101993. FLAC__bool ok;
  101994. ok =
  101995. FLAC__bitwriter_write_raw_uint32(bw, FLAC__SUBFRAME_TYPE_CONSTANT_BYTE_ALIGNED_MASK | (wasted_bits? 1:0), FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN) &&
  101996. (wasted_bits? FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1) : true) &&
  101997. FLAC__bitwriter_write_raw_int32(bw, subframe->value, subframe_bps)
  101998. ;
  101999. return ok;
  102000. }
  102001. FLAC__bool FLAC__subframe_add_fixed(const FLAC__Subframe_Fixed *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  102002. {
  102003. unsigned i;
  102004. if(!FLAC__bitwriter_write_raw_uint32(bw, FLAC__SUBFRAME_TYPE_FIXED_BYTE_ALIGNED_MASK | (subframe->order<<1) | (wasted_bits? 1:0), FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN))
  102005. return false;
  102006. if(wasted_bits)
  102007. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  102008. return false;
  102009. for(i = 0; i < subframe->order; i++)
  102010. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->warmup[i], subframe_bps))
  102011. return false;
  102012. if(!add_entropy_coding_method_(bw, &subframe->entropy_coding_method))
  102013. return false;
  102014. switch(subframe->entropy_coding_method.type) {
  102015. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  102016. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  102017. if(!add_residual_partitioned_rice_(
  102018. bw,
  102019. subframe->residual,
  102020. residual_samples,
  102021. subframe->order,
  102022. subframe->entropy_coding_method.data.partitioned_rice.contents->parameters,
  102023. subframe->entropy_coding_method.data.partitioned_rice.contents->raw_bits,
  102024. subframe->entropy_coding_method.data.partitioned_rice.order,
  102025. /*is_extended=*/subframe->entropy_coding_method.type == FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2
  102026. ))
  102027. return false;
  102028. break;
  102029. default:
  102030. FLAC__ASSERT(0);
  102031. }
  102032. return true;
  102033. }
  102034. FLAC__bool FLAC__subframe_add_lpc(const FLAC__Subframe_LPC *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  102035. {
  102036. unsigned i;
  102037. if(!FLAC__bitwriter_write_raw_uint32(bw, FLAC__SUBFRAME_TYPE_LPC_BYTE_ALIGNED_MASK | ((subframe->order-1)<<1) | (wasted_bits? 1:0), FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN))
  102038. return false;
  102039. if(wasted_bits)
  102040. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  102041. return false;
  102042. for(i = 0; i < subframe->order; i++)
  102043. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->warmup[i], subframe_bps))
  102044. return false;
  102045. if(!FLAC__bitwriter_write_raw_uint32(bw, subframe->qlp_coeff_precision-1, FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN))
  102046. return false;
  102047. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->quantization_level, FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN))
  102048. return false;
  102049. for(i = 0; i < subframe->order; i++)
  102050. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->qlp_coeff[i], subframe->qlp_coeff_precision))
  102051. return false;
  102052. if(!add_entropy_coding_method_(bw, &subframe->entropy_coding_method))
  102053. return false;
  102054. switch(subframe->entropy_coding_method.type) {
  102055. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  102056. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  102057. if(!add_residual_partitioned_rice_(
  102058. bw,
  102059. subframe->residual,
  102060. residual_samples,
  102061. subframe->order,
  102062. subframe->entropy_coding_method.data.partitioned_rice.contents->parameters,
  102063. subframe->entropy_coding_method.data.partitioned_rice.contents->raw_bits,
  102064. subframe->entropy_coding_method.data.partitioned_rice.order,
  102065. /*is_extended=*/subframe->entropy_coding_method.type == FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2
  102066. ))
  102067. return false;
  102068. break;
  102069. default:
  102070. FLAC__ASSERT(0);
  102071. }
  102072. return true;
  102073. }
  102074. FLAC__bool FLAC__subframe_add_verbatim(const FLAC__Subframe_Verbatim *subframe, unsigned samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  102075. {
  102076. unsigned i;
  102077. const FLAC__int32 *signal = subframe->data;
  102078. if(!FLAC__bitwriter_write_raw_uint32(bw, FLAC__SUBFRAME_TYPE_VERBATIM_BYTE_ALIGNED_MASK | (wasted_bits? 1:0), FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN))
  102079. return false;
  102080. if(wasted_bits)
  102081. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  102082. return false;
  102083. for(i = 0; i < samples; i++)
  102084. if(!FLAC__bitwriter_write_raw_int32(bw, signal[i], subframe_bps))
  102085. return false;
  102086. return true;
  102087. }
  102088. FLAC__bool add_entropy_coding_method_(FLAC__BitWriter *bw, const FLAC__EntropyCodingMethod *method)
  102089. {
  102090. if(!FLAC__bitwriter_write_raw_uint32(bw, method->type, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  102091. return false;
  102092. switch(method->type) {
  102093. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  102094. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  102095. if(!FLAC__bitwriter_write_raw_uint32(bw, method->data.partitioned_rice.order, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  102096. return false;
  102097. break;
  102098. default:
  102099. FLAC__ASSERT(0);
  102100. }
  102101. return true;
  102102. }
  102103. FLAC__bool add_residual_partitioned_rice_(FLAC__BitWriter *bw, const FLAC__int32 residual[], const unsigned residual_samples, const unsigned predictor_order, const unsigned rice_parameters[], const unsigned raw_bits[], const unsigned partition_order, const FLAC__bool is_extended)
  102104. {
  102105. const unsigned plen = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN;
  102106. const unsigned pesc = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  102107. if(partition_order == 0) {
  102108. unsigned i;
  102109. if(raw_bits[0] == 0) {
  102110. if(!FLAC__bitwriter_write_raw_uint32(bw, rice_parameters[0], plen))
  102111. return false;
  102112. if(!FLAC__bitwriter_write_rice_signed_block(bw, residual, residual_samples, rice_parameters[0]))
  102113. return false;
  102114. }
  102115. else {
  102116. FLAC__ASSERT(rice_parameters[0] == 0);
  102117. if(!FLAC__bitwriter_write_raw_uint32(bw, pesc, plen))
  102118. return false;
  102119. if(!FLAC__bitwriter_write_raw_uint32(bw, raw_bits[0], FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  102120. return false;
  102121. for(i = 0; i < residual_samples; i++) {
  102122. if(!FLAC__bitwriter_write_raw_int32(bw, residual[i], raw_bits[0]))
  102123. return false;
  102124. }
  102125. }
  102126. return true;
  102127. }
  102128. else {
  102129. unsigned i, j, k = 0, k_last = 0;
  102130. unsigned partition_samples;
  102131. const unsigned default_partition_samples = (residual_samples+predictor_order) >> partition_order;
  102132. for(i = 0; i < (1u<<partition_order); i++) {
  102133. partition_samples = default_partition_samples;
  102134. if(i == 0)
  102135. partition_samples -= predictor_order;
  102136. k += partition_samples;
  102137. if(raw_bits[i] == 0) {
  102138. if(!FLAC__bitwriter_write_raw_uint32(bw, rice_parameters[i], plen))
  102139. return false;
  102140. if(!FLAC__bitwriter_write_rice_signed_block(bw, residual+k_last, k-k_last, rice_parameters[i]))
  102141. return false;
  102142. }
  102143. else {
  102144. if(!FLAC__bitwriter_write_raw_uint32(bw, pesc, plen))
  102145. return false;
  102146. if(!FLAC__bitwriter_write_raw_uint32(bw, raw_bits[i], FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  102147. return false;
  102148. for(j = k_last; j < k; j++) {
  102149. if(!FLAC__bitwriter_write_raw_int32(bw, residual[j], raw_bits[i]))
  102150. return false;
  102151. }
  102152. }
  102153. k_last = k;
  102154. }
  102155. return true;
  102156. }
  102157. }
  102158. #endif
  102159. /********* End of inlined file: stream_encoder_framing.c *********/
  102160. /********* Start of inlined file: window_flac.c *********/
  102161. /********* Start of inlined file: juce_FlacHeader.h *********/
  102162. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  102163. // tasks..
  102164. #define VERSION "1.2.1"
  102165. #define FLAC__NO_DLL 1
  102166. #ifdef _MSC_VER
  102167. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  102168. #endif
  102169. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  102170. #define FLAC__SYS_DARWIN 1
  102171. #endif
  102172. /********* End of inlined file: juce_FlacHeader.h *********/
  102173. #if JUCE_USE_FLAC
  102174. #if HAVE_CONFIG_H
  102175. # include <config.h>
  102176. #endif
  102177. #include <math.h>
  102178. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102179. #ifndef M_PI
  102180. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  102181. #define M_PI 3.14159265358979323846
  102182. #endif
  102183. void FLAC__window_bartlett(FLAC__real *window, const FLAC__int32 L)
  102184. {
  102185. const FLAC__int32 N = L - 1;
  102186. FLAC__int32 n;
  102187. if (L & 1) {
  102188. for (n = 0; n <= N/2; n++)
  102189. window[n] = 2.0f * n / (float)N;
  102190. for (; n <= N; n++)
  102191. window[n] = 2.0f - 2.0f * n / (float)N;
  102192. }
  102193. else {
  102194. for (n = 0; n <= L/2-1; n++)
  102195. window[n] = 2.0f * n / (float)N;
  102196. for (; n <= N; n++)
  102197. window[n] = 2.0f - 2.0f * (N-n) / (float)N;
  102198. }
  102199. }
  102200. void FLAC__window_bartlett_hann(FLAC__real *window, const FLAC__int32 L)
  102201. {
  102202. const FLAC__int32 N = L - 1;
  102203. FLAC__int32 n;
  102204. for (n = 0; n < L; n++)
  102205. window[n] = (FLAC__real)(0.62f - 0.48f * fabs((float)n/(float)N+0.5f) + 0.38f * cos(2.0f * M_PI * ((float)n/(float)N+0.5f)));
  102206. }
  102207. void FLAC__window_blackman(FLAC__real *window, const FLAC__int32 L)
  102208. {
  102209. const FLAC__int32 N = L - 1;
  102210. FLAC__int32 n;
  102211. for (n = 0; n < L; n++)
  102212. window[n] = (FLAC__real)(0.42f - 0.5f * cos(2.0f * M_PI * n / N) + 0.08f * cos(4.0f * M_PI * n / N));
  102213. }
  102214. /* 4-term -92dB side-lobe */
  102215. void FLAC__window_blackman_harris_4term_92db_sidelobe(FLAC__real *window, const FLAC__int32 L)
  102216. {
  102217. const FLAC__int32 N = L - 1;
  102218. FLAC__int32 n;
  102219. for (n = 0; n <= N; n++)
  102220. window[n] = (FLAC__real)(0.35875f - 0.48829f * cos(2.0f * M_PI * n / N) + 0.14128f * cos(4.0f * M_PI * n / N) - 0.01168f * cos(6.0f * M_PI * n / N));
  102221. }
  102222. void FLAC__window_connes(FLAC__real *window, const FLAC__int32 L)
  102223. {
  102224. const FLAC__int32 N = L - 1;
  102225. const double N2 = (double)N / 2.;
  102226. FLAC__int32 n;
  102227. for (n = 0; n <= N; n++) {
  102228. double k = ((double)n - N2) / N2;
  102229. k = 1.0f - k * k;
  102230. window[n] = (FLAC__real)(k * k);
  102231. }
  102232. }
  102233. void FLAC__window_flattop(FLAC__real *window, const FLAC__int32 L)
  102234. {
  102235. const FLAC__int32 N = L - 1;
  102236. FLAC__int32 n;
  102237. for (n = 0; n < L; n++)
  102238. window[n] = (FLAC__real)(1.0f - 1.93f * cos(2.0f * M_PI * n / N) + 1.29f * cos(4.0f * M_PI * n / N) - 0.388f * cos(6.0f * M_PI * n / N) + 0.0322f * cos(8.0f * M_PI * n / N));
  102239. }
  102240. void FLAC__window_gauss(FLAC__real *window, const FLAC__int32 L, const FLAC__real stddev)
  102241. {
  102242. const FLAC__int32 N = L - 1;
  102243. const double N2 = (double)N / 2.;
  102244. FLAC__int32 n;
  102245. for (n = 0; n <= N; n++) {
  102246. const double k = ((double)n - N2) / (stddev * N2);
  102247. window[n] = (FLAC__real)exp(-0.5f * k * k);
  102248. }
  102249. }
  102250. void FLAC__window_hamming(FLAC__real *window, const FLAC__int32 L)
  102251. {
  102252. const FLAC__int32 N = L - 1;
  102253. FLAC__int32 n;
  102254. for (n = 0; n < L; n++)
  102255. window[n] = (FLAC__real)(0.54f - 0.46f * cos(2.0f * M_PI * n / N));
  102256. }
  102257. void FLAC__window_hann(FLAC__real *window, const FLAC__int32 L)
  102258. {
  102259. const FLAC__int32 N = L - 1;
  102260. FLAC__int32 n;
  102261. for (n = 0; n < L; n++)
  102262. window[n] = (FLAC__real)(0.5f - 0.5f * cos(2.0f * M_PI * n / N));
  102263. }
  102264. void FLAC__window_kaiser_bessel(FLAC__real *window, const FLAC__int32 L)
  102265. {
  102266. const FLAC__int32 N = L - 1;
  102267. FLAC__int32 n;
  102268. for (n = 0; n < L; n++)
  102269. window[n] = (FLAC__real)(0.402f - 0.498f * cos(2.0f * M_PI * n / N) + 0.098f * cos(4.0f * M_PI * n / N) - 0.001f * cos(6.0f * M_PI * n / N));
  102270. }
  102271. void FLAC__window_nuttall(FLAC__real *window, const FLAC__int32 L)
  102272. {
  102273. const FLAC__int32 N = L - 1;
  102274. FLAC__int32 n;
  102275. for (n = 0; n < L; n++)
  102276. window[n] = (FLAC__real)(0.3635819f - 0.4891775f*cos(2.0f*M_PI*n/N) + 0.1365995f*cos(4.0f*M_PI*n/N) - 0.0106411f*cos(6.0f*M_PI*n/N));
  102277. }
  102278. void FLAC__window_rectangle(FLAC__real *window, const FLAC__int32 L)
  102279. {
  102280. FLAC__int32 n;
  102281. for (n = 0; n < L; n++)
  102282. window[n] = 1.0f;
  102283. }
  102284. void FLAC__window_triangle(FLAC__real *window, const FLAC__int32 L)
  102285. {
  102286. FLAC__int32 n;
  102287. if (L & 1) {
  102288. for (n = 1; n <= L+1/2; n++)
  102289. window[n-1] = 2.0f * n / ((float)L + 1.0f);
  102290. for (; n <= L; n++)
  102291. window[n-1] = - (float)(2 * (L - n + 1)) / ((float)L + 1.0f);
  102292. }
  102293. else {
  102294. for (n = 1; n <= L/2; n++)
  102295. window[n-1] = 2.0f * n / (float)L;
  102296. for (; n <= L; n++)
  102297. window[n-1] = ((float)(2 * (L - n)) + 1.0f) / (float)L;
  102298. }
  102299. }
  102300. void FLAC__window_tukey(FLAC__real *window, const FLAC__int32 L, const FLAC__real p)
  102301. {
  102302. if (p <= 0.0)
  102303. FLAC__window_rectangle(window, L);
  102304. else if (p >= 1.0)
  102305. FLAC__window_hann(window, L);
  102306. else {
  102307. const FLAC__int32 Np = (FLAC__int32)(p / 2.0f * L) - 1;
  102308. FLAC__int32 n;
  102309. /* start with rectangle... */
  102310. FLAC__window_rectangle(window, L);
  102311. /* ...replace ends with hann */
  102312. if (Np > 0) {
  102313. for (n = 0; n <= Np; n++) {
  102314. window[n] = (FLAC__real)(0.5f - 0.5f * cos(M_PI * n / Np));
  102315. window[L-Np-1+n] = (FLAC__real)(0.5f - 0.5f * cos(M_PI * (n+Np) / Np));
  102316. }
  102317. }
  102318. }
  102319. }
  102320. void FLAC__window_welch(FLAC__real *window, const FLAC__int32 L)
  102321. {
  102322. const FLAC__int32 N = L - 1;
  102323. const double N2 = (double)N / 2.;
  102324. FLAC__int32 n;
  102325. for (n = 0; n <= N; n++) {
  102326. const double k = ((double)n - N2) / N2;
  102327. window[n] = (FLAC__real)(1.0f - k * k);
  102328. }
  102329. }
  102330. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  102331. #endif
  102332. /********* End of inlined file: window_flac.c *********/
  102333. #else
  102334. #include <FLAC/all.h>
  102335. #endif
  102336. }
  102337. #ifdef _MSC_VER
  102338. #pragma warning (pop)
  102339. #endif
  102340. BEGIN_JUCE_NAMESPACE
  102341. using namespace FlacNamespace;
  102342. #define flacFormatName TRANS("FLAC file")
  102343. static const tchar* const flacExtensions[] = { T(".flac"), 0 };
  102344. class FlacReader : public AudioFormatReader
  102345. {
  102346. FLAC__StreamDecoder* decoder;
  102347. AudioSampleBuffer reservoir;
  102348. int reservoirStart, samplesInReservoir;
  102349. bool ok, scanningForLength;
  102350. public:
  102351. FlacReader (InputStream* const in)
  102352. : AudioFormatReader (in, flacFormatName),
  102353. reservoir (2, 0),
  102354. reservoirStart (0),
  102355. samplesInReservoir (0),
  102356. scanningForLength (false)
  102357. {
  102358. using namespace FlacNamespace;
  102359. lengthInSamples = 0;
  102360. decoder = FLAC__stream_decoder_new();
  102361. ok = FLAC__stream_decoder_init_stream (decoder,
  102362. readCallback_, seekCallback_, tellCallback_, lengthCallback_,
  102363. eofCallback_, writeCallback_, metadataCallback_, errorCallback_,
  102364. (void*) this) == FLAC__STREAM_DECODER_INIT_STATUS_OK;
  102365. if (ok)
  102366. {
  102367. FLAC__stream_decoder_process_until_end_of_metadata (decoder);
  102368. if (lengthInSamples == 0 && sampleRate > 0)
  102369. {
  102370. // the length hasn't been stored in the metadata, so we'll need to
  102371. // work it out the length the hard way, by scanning the whole file..
  102372. scanningForLength = true;
  102373. FLAC__stream_decoder_process_until_end_of_stream (decoder);
  102374. scanningForLength = false;
  102375. const int64 tempLength = lengthInSamples;
  102376. FLAC__stream_decoder_reset (decoder);
  102377. FLAC__stream_decoder_process_until_end_of_metadata (decoder);
  102378. lengthInSamples = tempLength;
  102379. }
  102380. }
  102381. }
  102382. ~FlacReader()
  102383. {
  102384. FLAC__stream_decoder_delete (decoder);
  102385. }
  102386. void useMetadata (const FLAC__StreamMetadata_StreamInfo& info)
  102387. {
  102388. sampleRate = info.sample_rate;
  102389. bitsPerSample = info.bits_per_sample;
  102390. lengthInSamples = (unsigned int) info.total_samples;
  102391. numChannels = info.channels;
  102392. reservoir.setSize (numChannels, 2 * info.max_blocksize, false, false, true);
  102393. }
  102394. // returns the number of samples read
  102395. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  102396. int64 startSampleInFile, int numSamples)
  102397. {
  102398. using namespace FlacNamespace;
  102399. if (! ok)
  102400. return false;
  102401. while (numSamples > 0)
  102402. {
  102403. if (startSampleInFile >= reservoirStart
  102404. && startSampleInFile < reservoirStart + samplesInReservoir)
  102405. {
  102406. const int num = (int) jmin ((int64) numSamples,
  102407. reservoirStart + samplesInReservoir - startSampleInFile);
  102408. jassert (num > 0);
  102409. for (int i = jmin (numDestChannels, reservoir.getNumChannels()); --i >= 0;)
  102410. if (destSamples[i] != 0)
  102411. memcpy (destSamples[i] + startOffsetInDestBuffer,
  102412. reservoir.getSampleData (i, (int) (startSampleInFile - reservoirStart)),
  102413. sizeof (int) * num);
  102414. startOffsetInDestBuffer += num;
  102415. startSampleInFile += num;
  102416. numSamples -= num;
  102417. }
  102418. else
  102419. {
  102420. if (startSampleInFile < reservoirStart
  102421. || startSampleInFile > reservoirStart + jmax (samplesInReservoir, 511))
  102422. {
  102423. samplesInReservoir = 0;
  102424. if (startSampleInFile >= (int) lengthInSamples)
  102425. break;
  102426. // had some problems with flac crashing if the read pos is aligned more
  102427. // accurately than this. Probably fixed in newer versions of the library, though.
  102428. reservoirStart = (int) (startSampleInFile & ~511);
  102429. FLAC__stream_decoder_seek_absolute (decoder, (FLAC__uint64) reservoirStart);
  102430. }
  102431. else
  102432. {
  102433. reservoirStart += samplesInReservoir;
  102434. samplesInReservoir = 0;
  102435. FLAC__stream_decoder_process_single (decoder);
  102436. }
  102437. if (samplesInReservoir == 0)
  102438. break;
  102439. }
  102440. }
  102441. if (numSamples > 0)
  102442. {
  102443. for (int i = numDestChannels; --i >= 0;)
  102444. if (destSamples[i] != 0)
  102445. zeromem (destSamples[i] + startOffsetInDestBuffer,
  102446. sizeof (int) * numSamples);
  102447. }
  102448. return true;
  102449. }
  102450. void useSamples (const FLAC__int32* const buffer[], int numSamples)
  102451. {
  102452. if (scanningForLength)
  102453. {
  102454. lengthInSamples += numSamples;
  102455. }
  102456. else
  102457. {
  102458. if (numSamples > reservoir.getNumSamples())
  102459. reservoir.setSize (numChannels, numSamples, false, false, true);
  102460. const int bitsToShift = 32 - bitsPerSample;
  102461. for (int i = 0; i < (int) numChannels; ++i)
  102462. {
  102463. const FLAC__int32* src = buffer[i];
  102464. int n = i;
  102465. while (src == 0 && n > 0)
  102466. src = buffer [--n];
  102467. if (src != 0)
  102468. {
  102469. int* dest = (int*) reservoir.getSampleData(i);
  102470. for (int j = 0; j < numSamples; ++j)
  102471. dest[j] = src[j] << bitsToShift;
  102472. }
  102473. }
  102474. samplesInReservoir = numSamples;
  102475. }
  102476. }
  102477. static FLAC__StreamDecoderReadStatus readCallback_ (const FLAC__StreamDecoder*, FLAC__byte buffer[], size_t* bytes, void* client_data)
  102478. {
  102479. *bytes = (unsigned int) ((const FlacReader*) client_data)->input->read (buffer, (int) *bytes);
  102480. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  102481. }
  102482. static FLAC__StreamDecoderSeekStatus seekCallback_ (const FLAC__StreamDecoder*, FLAC__uint64 absolute_byte_offset, void* client_data)
  102483. {
  102484. ((const FlacReader*) client_data)->input->setPosition ((int) absolute_byte_offset);
  102485. return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  102486. }
  102487. static FLAC__StreamDecoderTellStatus tellCallback_ (const FLAC__StreamDecoder*, FLAC__uint64* absolute_byte_offset, void* client_data)
  102488. {
  102489. *absolute_byte_offset = ((const FlacReader*) client_data)->input->getPosition();
  102490. return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  102491. }
  102492. static FLAC__StreamDecoderLengthStatus lengthCallback_ (const FLAC__StreamDecoder*, FLAC__uint64* stream_length, void* client_data)
  102493. {
  102494. *stream_length = ((const FlacReader*) client_data)->input->getTotalLength();
  102495. return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  102496. }
  102497. static FLAC__bool eofCallback_ (const FLAC__StreamDecoder*, void* client_data)
  102498. {
  102499. return ((const FlacReader*) client_data)->input->isExhausted();
  102500. }
  102501. static FLAC__StreamDecoderWriteStatus writeCallback_ (const FLAC__StreamDecoder*,
  102502. const FLAC__Frame* frame,
  102503. const FLAC__int32* const buffer[],
  102504. void* client_data)
  102505. {
  102506. ((FlacReader*) client_data)->useSamples (buffer, frame->header.blocksize);
  102507. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  102508. }
  102509. static void metadataCallback_ (const FLAC__StreamDecoder*,
  102510. const FLAC__StreamMetadata* metadata,
  102511. void* client_data)
  102512. {
  102513. ((FlacReader*) client_data)->useMetadata (metadata->data.stream_info);
  102514. }
  102515. static void errorCallback_ (const FLAC__StreamDecoder*, FLAC__StreamDecoderErrorStatus, void*)
  102516. {
  102517. }
  102518. juce_UseDebuggingNewOperator
  102519. };
  102520. class FlacWriter : public AudioFormatWriter
  102521. {
  102522. FLAC__StreamEncoder* encoder;
  102523. MemoryBlock temp;
  102524. public:
  102525. bool ok;
  102526. FlacWriter (OutputStream* const out,
  102527. const double sampleRate,
  102528. const int numChannels,
  102529. const int bitsPerSample_)
  102530. : AudioFormatWriter (out, flacFormatName,
  102531. sampleRate,
  102532. numChannels,
  102533. bitsPerSample_)
  102534. {
  102535. using namespace FlacNamespace;
  102536. encoder = FLAC__stream_encoder_new();
  102537. FLAC__stream_encoder_set_do_mid_side_stereo (encoder, numChannels == 2);
  102538. FLAC__stream_encoder_set_loose_mid_side_stereo (encoder, numChannels == 2);
  102539. FLAC__stream_encoder_set_channels (encoder, numChannels);
  102540. FLAC__stream_encoder_set_bits_per_sample (encoder, jmin (24, bitsPerSample));
  102541. FLAC__stream_encoder_set_sample_rate (encoder, (unsigned int) sampleRate);
  102542. FLAC__stream_encoder_set_blocksize (encoder, 2048);
  102543. FLAC__stream_encoder_set_do_escape_coding (encoder, true);
  102544. ok = FLAC__stream_encoder_init_stream (encoder,
  102545. encodeWriteCallback, encodeSeekCallback,
  102546. encodeTellCallback, encodeMetadataCallback,
  102547. (void*) this) == FLAC__STREAM_ENCODER_INIT_STATUS_OK;
  102548. }
  102549. ~FlacWriter()
  102550. {
  102551. if (ok)
  102552. {
  102553. FLAC__stream_encoder_finish (encoder);
  102554. output->flush();
  102555. }
  102556. else
  102557. {
  102558. output = 0; // to stop the base class deleting this, as it needs to be returned
  102559. // to the caller of createWriter()
  102560. }
  102561. FLAC__stream_encoder_delete (encoder);
  102562. }
  102563. bool write (const int** samplesToWrite, int numSamples)
  102564. {
  102565. if (! ok)
  102566. return false;
  102567. int* buf[3];
  102568. const int bitsToShift = 32 - bitsPerSample;
  102569. if (bitsToShift > 0)
  102570. {
  102571. const int numChannels = (samplesToWrite[1] == 0) ? 1 : 2;
  102572. temp.setSize (sizeof (int) * numSamples * numChannels);
  102573. buf[0] = (int*) temp.getData();
  102574. buf[1] = buf[0] + numSamples;
  102575. buf[2] = 0;
  102576. for (int i = numChannels; --i >= 0;)
  102577. {
  102578. if (samplesToWrite[i] != 0)
  102579. {
  102580. for (int j = 0; j < numSamples; ++j)
  102581. buf [i][j] = (samplesToWrite [i][j] >> bitsToShift);
  102582. }
  102583. }
  102584. samplesToWrite = (const int**) buf;
  102585. }
  102586. return FLAC__stream_encoder_process (encoder,
  102587. (const FLAC__int32**) samplesToWrite,
  102588. numSamples) != 0;
  102589. }
  102590. bool writeData (const void* const data, const int size) const
  102591. {
  102592. return output->write (data, size);
  102593. }
  102594. static void packUint32 (FLAC__uint32 val, FLAC__byte* b, const int bytes)
  102595. {
  102596. b += bytes;
  102597. for (int i = 0; i < bytes; ++i)
  102598. {
  102599. *(--b) = (FLAC__byte) (val & 0xff);
  102600. val >>= 8;
  102601. }
  102602. }
  102603. void writeMetaData (const FLAC__StreamMetadata* metadata)
  102604. {
  102605. using namespace FlacNamespace;
  102606. const FLAC__StreamMetadata_StreamInfo& info = metadata->data.stream_info;
  102607. unsigned char buffer [FLAC__STREAM_METADATA_STREAMINFO_LENGTH];
  102608. const unsigned int channelsMinus1 = info.channels - 1;
  102609. const unsigned int bitsMinus1 = info.bits_per_sample - 1;
  102610. packUint32 (info.min_blocksize, buffer, 2);
  102611. packUint32 (info.max_blocksize, buffer + 2, 2);
  102612. packUint32 (info.min_framesize, buffer + 4, 3);
  102613. packUint32 (info.max_framesize, buffer + 7, 3);
  102614. buffer[10] = (uint8) ((info.sample_rate >> 12) & 0xff);
  102615. buffer[11] = (uint8) ((info.sample_rate >> 4) & 0xff);
  102616. buffer[12] = (uint8) (((info.sample_rate & 0x0f) << 4) | (channelsMinus1 << 1) | (bitsMinus1 >> 4));
  102617. buffer[13] = (FLAC__byte) (((bitsMinus1 & 0x0f) << 4) | (unsigned int) ((info.total_samples >> 32) & 0x0f));
  102618. packUint32 ((FLAC__uint32) info.total_samples, buffer + 14, 4);
  102619. memcpy (buffer + 18, info.md5sum, 16);
  102620. const bool ok = output->setPosition (4);
  102621. (void) ok;
  102622. // if this fails, you've given it an output stream that can't seek! It needs
  102623. // to be able to seek back to write the header
  102624. jassert (ok);
  102625. output->writeIntBigEndian (FLAC__STREAM_METADATA_STREAMINFO_LENGTH);
  102626. output->write (buffer, FLAC__STREAM_METADATA_STREAMINFO_LENGTH);
  102627. }
  102628. static FLAC__StreamEncoderWriteStatus encodeWriteCallback (const FLAC__StreamEncoder*,
  102629. const FLAC__byte buffer[],
  102630. size_t bytes,
  102631. unsigned int /*samples*/,
  102632. unsigned int /*current_frame*/,
  102633. void* client_data)
  102634. {
  102635. using namespace FlacNamespace;
  102636. return ((FlacWriter*) client_data)->writeData (buffer, (int) bytes)
  102637. ? FLAC__STREAM_ENCODER_WRITE_STATUS_OK
  102638. : FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  102639. }
  102640. static FLAC__StreamEncoderSeekStatus encodeSeekCallback (const FLAC__StreamEncoder*, FLAC__uint64, void*)
  102641. {
  102642. return FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED;
  102643. }
  102644. static FLAC__StreamEncoderTellStatus encodeTellCallback (const FLAC__StreamEncoder*, FLAC__uint64*, void*)
  102645. {
  102646. return FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED;
  102647. }
  102648. static void encodeMetadataCallback (const FLAC__StreamEncoder*,
  102649. const FLAC__StreamMetadata* metadata,
  102650. void* client_data)
  102651. {
  102652. ((FlacWriter*) client_data)->writeMetaData (metadata);
  102653. }
  102654. juce_UseDebuggingNewOperator
  102655. };
  102656. FlacAudioFormat::FlacAudioFormat()
  102657. : AudioFormat (flacFormatName, (const tchar**) flacExtensions)
  102658. {
  102659. }
  102660. FlacAudioFormat::~FlacAudioFormat()
  102661. {
  102662. }
  102663. const Array <int> FlacAudioFormat::getPossibleSampleRates()
  102664. {
  102665. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 0 };
  102666. return Array <int> (rates);
  102667. }
  102668. const Array <int> FlacAudioFormat::getPossibleBitDepths()
  102669. {
  102670. const int depths[] = { 16, 24, 0 };
  102671. return Array <int> (depths);
  102672. }
  102673. bool FlacAudioFormat::canDoStereo()
  102674. {
  102675. return true;
  102676. }
  102677. bool FlacAudioFormat::canDoMono()
  102678. {
  102679. return true;
  102680. }
  102681. bool FlacAudioFormat::isCompressed()
  102682. {
  102683. return true;
  102684. }
  102685. AudioFormatReader* FlacAudioFormat::createReaderFor (InputStream* in,
  102686. const bool deleteStreamIfOpeningFails)
  102687. {
  102688. FlacReader* r = new FlacReader (in);
  102689. if (r->sampleRate == 0)
  102690. {
  102691. if (! deleteStreamIfOpeningFails)
  102692. r->input = 0;
  102693. deleteAndZero (r);
  102694. }
  102695. return r;
  102696. }
  102697. AudioFormatWriter* FlacAudioFormat::createWriterFor (OutputStream* out,
  102698. double sampleRate,
  102699. unsigned int numberOfChannels,
  102700. int bitsPerSample,
  102701. const StringPairArray& /*metadataValues*/,
  102702. int /*qualityOptionIndex*/)
  102703. {
  102704. if (getPossibleBitDepths().contains (bitsPerSample))
  102705. {
  102706. FlacWriter* w = new FlacWriter (out,
  102707. sampleRate,
  102708. numberOfChannels,
  102709. bitsPerSample);
  102710. if (! w->ok)
  102711. deleteAndZero (w);
  102712. return w;
  102713. }
  102714. return 0;
  102715. }
  102716. END_JUCE_NAMESPACE
  102717. #endif
  102718. /********* End of inlined file: juce_FlacAudioFormat.cpp *********/
  102719. /********* Start of inlined file: juce_OggVorbisAudioFormat.cpp *********/
  102720. #if JUCE_USE_OGGVORBIS
  102721. #if JUCE_MAC
  102722. #define __MACOSX__ 1
  102723. #endif
  102724. namespace OggVorbisNamespace
  102725. {
  102726. #if JUCE_INCLUDE_OGGVORBIS_CODE
  102727. /********* Start of inlined file: vorbisenc.h *********/
  102728. #ifndef _OV_ENC_H_
  102729. #define _OV_ENC_H_
  102730. #ifdef __cplusplus
  102731. extern "C"
  102732. {
  102733. #endif /* __cplusplus */
  102734. /********* Start of inlined file: codec.h *********/
  102735. #ifndef _vorbis_codec_h_
  102736. #define _vorbis_codec_h_
  102737. #ifdef __cplusplus
  102738. extern "C"
  102739. {
  102740. #endif /* __cplusplus */
  102741. /********* Start of inlined file: ogg.h *********/
  102742. #ifndef _OGG_H
  102743. #define _OGG_H
  102744. #ifdef __cplusplus
  102745. extern "C" {
  102746. #endif
  102747. /********* Start of inlined file: os_types.h *********/
  102748. #ifndef _OS_TYPES_H
  102749. #define _OS_TYPES_H
  102750. /* make it easy on the folks that want to compile the libs with a
  102751. different malloc than stdlib */
  102752. #define _ogg_malloc malloc
  102753. #define _ogg_calloc calloc
  102754. #define _ogg_realloc realloc
  102755. #define _ogg_free free
  102756. #if defined(_WIN32)
  102757. # if defined(__CYGWIN__)
  102758. # include <_G_config.h>
  102759. typedef _G_int64_t ogg_int64_t;
  102760. typedef _G_int32_t ogg_int32_t;
  102761. typedef _G_uint32_t ogg_uint32_t;
  102762. typedef _G_int16_t ogg_int16_t;
  102763. typedef _G_uint16_t ogg_uint16_t;
  102764. # elif defined(__MINGW32__)
  102765. typedef short ogg_int16_t;
  102766. typedef unsigned short ogg_uint16_t;
  102767. typedef int ogg_int32_t;
  102768. typedef unsigned int ogg_uint32_t;
  102769. typedef long long ogg_int64_t;
  102770. typedef unsigned long long ogg_uint64_t;
  102771. # elif defined(__MWERKS__)
  102772. typedef long long ogg_int64_t;
  102773. typedef int ogg_int32_t;
  102774. typedef unsigned int ogg_uint32_t;
  102775. typedef short ogg_int16_t;
  102776. typedef unsigned short ogg_uint16_t;
  102777. # else
  102778. /* MSVC/Borland */
  102779. typedef __int64 ogg_int64_t;
  102780. typedef __int32 ogg_int32_t;
  102781. typedef unsigned __int32 ogg_uint32_t;
  102782. typedef __int16 ogg_int16_t;
  102783. typedef unsigned __int16 ogg_uint16_t;
  102784. # endif
  102785. #elif defined(__MACOS__)
  102786. # include <sys/types.h>
  102787. typedef SInt16 ogg_int16_t;
  102788. typedef UInt16 ogg_uint16_t;
  102789. typedef SInt32 ogg_int32_t;
  102790. typedef UInt32 ogg_uint32_t;
  102791. typedef SInt64 ogg_int64_t;
  102792. #elif defined(__MACOSX__) /* MacOS X Framework build */
  102793. # include <sys/types.h>
  102794. typedef int16_t ogg_int16_t;
  102795. typedef u_int16_t ogg_uint16_t;
  102796. typedef int32_t ogg_int32_t;
  102797. typedef u_int32_t ogg_uint32_t;
  102798. typedef int64_t ogg_int64_t;
  102799. #elif defined(__BEOS__)
  102800. /* Be */
  102801. # include <inttypes.h>
  102802. typedef int16_t ogg_int16_t;
  102803. typedef u_int16_t ogg_uint16_t;
  102804. typedef int32_t ogg_int32_t;
  102805. typedef u_int32_t ogg_uint32_t;
  102806. typedef int64_t ogg_int64_t;
  102807. #elif defined (__EMX__)
  102808. /* OS/2 GCC */
  102809. typedef short ogg_int16_t;
  102810. typedef unsigned short ogg_uint16_t;
  102811. typedef int ogg_int32_t;
  102812. typedef unsigned int ogg_uint32_t;
  102813. typedef long long ogg_int64_t;
  102814. #elif defined (DJGPP)
  102815. /* DJGPP */
  102816. typedef short ogg_int16_t;
  102817. typedef int ogg_int32_t;
  102818. typedef unsigned int ogg_uint32_t;
  102819. typedef long long ogg_int64_t;
  102820. #elif defined(R5900)
  102821. /* PS2 EE */
  102822. typedef long ogg_int64_t;
  102823. typedef int ogg_int32_t;
  102824. typedef unsigned ogg_uint32_t;
  102825. typedef short ogg_int16_t;
  102826. #elif defined(__SYMBIAN32__)
  102827. /* Symbian GCC */
  102828. typedef signed short ogg_int16_t;
  102829. typedef unsigned short ogg_uint16_t;
  102830. typedef signed int ogg_int32_t;
  102831. typedef unsigned int ogg_uint32_t;
  102832. typedef long long int ogg_int64_t;
  102833. #else
  102834. # include <sys/types.h>
  102835. /********* Start of inlined file: config_types.h *********/
  102836. #ifndef __CONFIG_TYPES_H__
  102837. #define __CONFIG_TYPES_H__
  102838. typedef int16_t ogg_int16_t;
  102839. typedef unsigned short ogg_uint16_t;
  102840. typedef int32_t ogg_int32_t;
  102841. typedef unsigned int ogg_uint32_t;
  102842. typedef int64_t ogg_int64_t;
  102843. #endif
  102844. /********* End of inlined file: config_types.h *********/
  102845. #endif
  102846. #endif /* _OS_TYPES_H */
  102847. /********* End of inlined file: os_types.h *********/
  102848. typedef struct {
  102849. long endbyte;
  102850. int endbit;
  102851. unsigned char *buffer;
  102852. unsigned char *ptr;
  102853. long storage;
  102854. } oggpack_buffer;
  102855. /* ogg_page is used to encapsulate the data in one Ogg bitstream page *****/
  102856. typedef struct {
  102857. unsigned char *header;
  102858. long header_len;
  102859. unsigned char *body;
  102860. long body_len;
  102861. } ogg_page;
  102862. ogg_uint32_t ogg_bitreverse(ogg_uint32_t x){
  102863. x= ((x>>16)&0x0000ffffUL) | ((x<<16)&0xffff0000UL);
  102864. x= ((x>> 8)&0x00ff00ffUL) | ((x<< 8)&0xff00ff00UL);
  102865. x= ((x>> 4)&0x0f0f0f0fUL) | ((x<< 4)&0xf0f0f0f0UL);
  102866. x= ((x>> 2)&0x33333333UL) | ((x<< 2)&0xccccccccUL);
  102867. return((x>> 1)&0x55555555UL) | ((x<< 1)&0xaaaaaaaaUL);
  102868. }
  102869. /* ogg_stream_state contains the current encode/decode state of a logical
  102870. Ogg bitstream **********************************************************/
  102871. typedef struct {
  102872. unsigned char *body_data; /* bytes from packet bodies */
  102873. long body_storage; /* storage elements allocated */
  102874. long body_fill; /* elements stored; fill mark */
  102875. long body_returned; /* elements of fill returned */
  102876. int *lacing_vals; /* The values that will go to the segment table */
  102877. ogg_int64_t *granule_vals; /* granulepos values for headers. Not compact
  102878. this way, but it is simple coupled to the
  102879. lacing fifo */
  102880. long lacing_storage;
  102881. long lacing_fill;
  102882. long lacing_packet;
  102883. long lacing_returned;
  102884. unsigned char header[282]; /* working space for header encode */
  102885. int header_fill;
  102886. int e_o_s; /* set when we have buffered the last packet in the
  102887. logical bitstream */
  102888. int b_o_s; /* set after we've written the initial page
  102889. of a logical bitstream */
  102890. long serialno;
  102891. long pageno;
  102892. ogg_int64_t packetno; /* sequence number for decode; the framing
  102893. knows where there's a hole in the data,
  102894. but we need coupling so that the codec
  102895. (which is in a seperate abstraction
  102896. layer) also knows about the gap */
  102897. ogg_int64_t granulepos;
  102898. } ogg_stream_state;
  102899. /* ogg_packet is used to encapsulate the data and metadata belonging
  102900. to a single raw Ogg/Vorbis packet *************************************/
  102901. typedef struct {
  102902. unsigned char *packet;
  102903. long bytes;
  102904. long b_o_s;
  102905. long e_o_s;
  102906. ogg_int64_t granulepos;
  102907. ogg_int64_t packetno; /* sequence number for decode; the framing
  102908. knows where there's a hole in the data,
  102909. but we need coupling so that the codec
  102910. (which is in a seperate abstraction
  102911. layer) also knows about the gap */
  102912. } ogg_packet;
  102913. typedef struct {
  102914. unsigned char *data;
  102915. int storage;
  102916. int fill;
  102917. int returned;
  102918. int unsynced;
  102919. int headerbytes;
  102920. int bodybytes;
  102921. } ogg_sync_state;
  102922. /* Ogg BITSTREAM PRIMITIVES: bitstream ************************/
  102923. extern void oggpack_writeinit(oggpack_buffer *b);
  102924. extern void oggpack_writetrunc(oggpack_buffer *b,long bits);
  102925. extern void oggpack_writealign(oggpack_buffer *b);
  102926. extern void oggpack_writecopy(oggpack_buffer *b,void *source,long bits);
  102927. extern void oggpack_reset(oggpack_buffer *b);
  102928. extern void oggpack_writeclear(oggpack_buffer *b);
  102929. extern void oggpack_readinit(oggpack_buffer *b,unsigned char *buf,int bytes);
  102930. extern void oggpack_write(oggpack_buffer *b,unsigned long value,int bits);
  102931. extern long oggpack_look(oggpack_buffer *b,int bits);
  102932. extern long oggpack_look1(oggpack_buffer *b);
  102933. extern void oggpack_adv(oggpack_buffer *b,int bits);
  102934. extern void oggpack_adv1(oggpack_buffer *b);
  102935. extern long oggpack_read(oggpack_buffer *b,int bits);
  102936. extern long oggpack_read1(oggpack_buffer *b);
  102937. extern long oggpack_bytes(oggpack_buffer *b);
  102938. extern long oggpack_bits(oggpack_buffer *b);
  102939. extern unsigned char *oggpack_get_buffer(oggpack_buffer *b);
  102940. extern void oggpackB_writeinit(oggpack_buffer *b);
  102941. extern void oggpackB_writetrunc(oggpack_buffer *b,long bits);
  102942. extern void oggpackB_writealign(oggpack_buffer *b);
  102943. extern void oggpackB_writecopy(oggpack_buffer *b,void *source,long bits);
  102944. extern void oggpackB_reset(oggpack_buffer *b);
  102945. extern void oggpackB_writeclear(oggpack_buffer *b);
  102946. extern void oggpackB_readinit(oggpack_buffer *b,unsigned char *buf,int bytes);
  102947. extern void oggpackB_write(oggpack_buffer *b,unsigned long value,int bits);
  102948. extern long oggpackB_look(oggpack_buffer *b,int bits);
  102949. extern long oggpackB_look1(oggpack_buffer *b);
  102950. extern void oggpackB_adv(oggpack_buffer *b,int bits);
  102951. extern void oggpackB_adv1(oggpack_buffer *b);
  102952. extern long oggpackB_read(oggpack_buffer *b,int bits);
  102953. extern long oggpackB_read1(oggpack_buffer *b);
  102954. extern long oggpackB_bytes(oggpack_buffer *b);
  102955. extern long oggpackB_bits(oggpack_buffer *b);
  102956. extern unsigned char *oggpackB_get_buffer(oggpack_buffer *b);
  102957. /* Ogg BITSTREAM PRIMITIVES: encoding **************************/
  102958. extern int ogg_stream_packetin(ogg_stream_state *os, ogg_packet *op);
  102959. extern int ogg_stream_pageout(ogg_stream_state *os, ogg_page *og);
  102960. extern int ogg_stream_flush(ogg_stream_state *os, ogg_page *og);
  102961. /* Ogg BITSTREAM PRIMITIVES: decoding **************************/
  102962. extern int ogg_sync_init(ogg_sync_state *oy);
  102963. extern int ogg_sync_clear(ogg_sync_state *oy);
  102964. extern int ogg_sync_reset(ogg_sync_state *oy);
  102965. extern int ogg_sync_destroy(ogg_sync_state *oy);
  102966. extern char *ogg_sync_buffer(ogg_sync_state *oy, long size);
  102967. extern int ogg_sync_wrote(ogg_sync_state *oy, long bytes);
  102968. extern long ogg_sync_pageseek(ogg_sync_state *oy,ogg_page *og);
  102969. extern int ogg_sync_pageout(ogg_sync_state *oy, ogg_page *og);
  102970. extern int ogg_stream_pagein(ogg_stream_state *os, ogg_page *og);
  102971. extern int ogg_stream_packetout(ogg_stream_state *os,ogg_packet *op);
  102972. extern int ogg_stream_packetpeek(ogg_stream_state *os,ogg_packet *op);
  102973. /* Ogg BITSTREAM PRIMITIVES: general ***************************/
  102974. extern int ogg_stream_init(ogg_stream_state *os,int serialno);
  102975. extern int ogg_stream_clear(ogg_stream_state *os);
  102976. extern int ogg_stream_reset(ogg_stream_state *os);
  102977. extern int ogg_stream_reset_serialno(ogg_stream_state *os,int serialno);
  102978. extern int ogg_stream_destroy(ogg_stream_state *os);
  102979. extern int ogg_stream_eos(ogg_stream_state *os);
  102980. extern void ogg_page_checksum_set(ogg_page *og);
  102981. extern int ogg_page_version(ogg_page *og);
  102982. extern int ogg_page_continued(ogg_page *og);
  102983. extern int ogg_page_bos(ogg_page *og);
  102984. extern int ogg_page_eos(ogg_page *og);
  102985. extern ogg_int64_t ogg_page_granulepos(ogg_page *og);
  102986. extern int ogg_page_serialno(ogg_page *og);
  102987. extern long ogg_page_pageno(ogg_page *og);
  102988. extern int ogg_page_packets(ogg_page *og);
  102989. extern void ogg_packet_clear(ogg_packet *op);
  102990. #ifdef __cplusplus
  102991. }
  102992. #endif
  102993. #endif /* _OGG_H */
  102994. /********* End of inlined file: ogg.h *********/
  102995. typedef struct vorbis_info{
  102996. int version;
  102997. int channels;
  102998. long rate;
  102999. /* The below bitrate declarations are *hints*.
  103000. Combinations of the three values carry the following implications:
  103001. all three set to the same value:
  103002. implies a fixed rate bitstream
  103003. only nominal set:
  103004. implies a VBR stream that averages the nominal bitrate. No hard
  103005. upper/lower limit
  103006. upper and or lower set:
  103007. implies a VBR bitstream that obeys the bitrate limits. nominal
  103008. may also be set to give a nominal rate.
  103009. none set:
  103010. the coder does not care to speculate.
  103011. */
  103012. long bitrate_upper;
  103013. long bitrate_nominal;
  103014. long bitrate_lower;
  103015. long bitrate_window;
  103016. void *codec_setup;
  103017. } vorbis_info;
  103018. /* vorbis_dsp_state buffers the current vorbis audio
  103019. analysis/synthesis state. The DSP state belongs to a specific
  103020. logical bitstream ****************************************************/
  103021. typedef struct vorbis_dsp_state{
  103022. int analysisp;
  103023. vorbis_info *vi;
  103024. float **pcm;
  103025. float **pcmret;
  103026. int pcm_storage;
  103027. int pcm_current;
  103028. int pcm_returned;
  103029. int preextrapolate;
  103030. int eofflag;
  103031. long lW;
  103032. long W;
  103033. long nW;
  103034. long centerW;
  103035. ogg_int64_t granulepos;
  103036. ogg_int64_t sequence;
  103037. ogg_int64_t glue_bits;
  103038. ogg_int64_t time_bits;
  103039. ogg_int64_t floor_bits;
  103040. ogg_int64_t res_bits;
  103041. void *backend_state;
  103042. } vorbis_dsp_state;
  103043. typedef struct vorbis_block{
  103044. /* necessary stream state for linking to the framing abstraction */
  103045. float **pcm; /* this is a pointer into local storage */
  103046. oggpack_buffer opb;
  103047. long lW;
  103048. long W;
  103049. long nW;
  103050. int pcmend;
  103051. int mode;
  103052. int eofflag;
  103053. ogg_int64_t granulepos;
  103054. ogg_int64_t sequence;
  103055. vorbis_dsp_state *vd; /* For read-only access of configuration */
  103056. /* local storage to avoid remallocing; it's up to the mapping to
  103057. structure it */
  103058. void *localstore;
  103059. long localtop;
  103060. long localalloc;
  103061. long totaluse;
  103062. struct alloc_chain *reap;
  103063. /* bitmetrics for the frame */
  103064. long glue_bits;
  103065. long time_bits;
  103066. long floor_bits;
  103067. long res_bits;
  103068. void *internal;
  103069. } vorbis_block;
  103070. /* vorbis_block is a single block of data to be processed as part of
  103071. the analysis/synthesis stream; it belongs to a specific logical
  103072. bitstream, but is independant from other vorbis_blocks belonging to
  103073. that logical bitstream. *************************************************/
  103074. struct alloc_chain{
  103075. void *ptr;
  103076. struct alloc_chain *next;
  103077. };
  103078. /* vorbis_info contains all the setup information specific to the
  103079. specific compression/decompression mode in progress (eg,
  103080. psychoacoustic settings, channel setup, options, codebook
  103081. etc). vorbis_info and substructures are in backends.h.
  103082. *********************************************************************/
  103083. /* the comments are not part of vorbis_info so that vorbis_info can be
  103084. static storage */
  103085. typedef struct vorbis_comment{
  103086. /* unlimited user comment fields. libvorbis writes 'libvorbis'
  103087. whatever vendor is set to in encode */
  103088. char **user_comments;
  103089. int *comment_lengths;
  103090. int comments;
  103091. char *vendor;
  103092. } vorbis_comment;
  103093. /* libvorbis encodes in two abstraction layers; first we perform DSP
  103094. and produce a packet (see docs/analysis.txt). The packet is then
  103095. coded into a framed OggSquish bitstream by the second layer (see
  103096. docs/framing.txt). Decode is the reverse process; we sync/frame
  103097. the bitstream and extract individual packets, then decode the
  103098. packet back into PCM audio.
  103099. The extra framing/packetizing is used in streaming formats, such as
  103100. files. Over the net (such as with UDP), the framing and
  103101. packetization aren't necessary as they're provided by the transport
  103102. and the streaming layer is not used */
  103103. /* Vorbis PRIMITIVES: general ***************************************/
  103104. extern void vorbis_info_init(vorbis_info *vi);
  103105. extern void vorbis_info_clear(vorbis_info *vi);
  103106. extern int vorbis_info_blocksize(vorbis_info *vi,int zo);
  103107. extern void vorbis_comment_init(vorbis_comment *vc);
  103108. extern void vorbis_comment_add(vorbis_comment *vc, char *comment);
  103109. extern void vorbis_comment_add_tag(vorbis_comment *vc,
  103110. const char *tag, char *contents);
  103111. extern char *vorbis_comment_query(vorbis_comment *vc, char *tag, int count);
  103112. extern int vorbis_comment_query_count(vorbis_comment *vc, char *tag);
  103113. extern void vorbis_comment_clear(vorbis_comment *vc);
  103114. extern int vorbis_block_init(vorbis_dsp_state *v, vorbis_block *vb);
  103115. extern int vorbis_block_clear(vorbis_block *vb);
  103116. extern void vorbis_dsp_clear(vorbis_dsp_state *v);
  103117. extern double vorbis_granule_time(vorbis_dsp_state *v,
  103118. ogg_int64_t granulepos);
  103119. /* Vorbis PRIMITIVES: analysis/DSP layer ****************************/
  103120. extern int vorbis_analysis_init(vorbis_dsp_state *v,vorbis_info *vi);
  103121. extern int vorbis_commentheader_out(vorbis_comment *vc, ogg_packet *op);
  103122. extern int vorbis_analysis_headerout(vorbis_dsp_state *v,
  103123. vorbis_comment *vc,
  103124. ogg_packet *op,
  103125. ogg_packet *op_comm,
  103126. ogg_packet *op_code);
  103127. extern float **vorbis_analysis_buffer(vorbis_dsp_state *v,int vals);
  103128. extern int vorbis_analysis_wrote(vorbis_dsp_state *v,int vals);
  103129. extern int vorbis_analysis_blockout(vorbis_dsp_state *v,vorbis_block *vb);
  103130. extern int vorbis_analysis(vorbis_block *vb,ogg_packet *op);
  103131. extern int vorbis_bitrate_addblock(vorbis_block *vb);
  103132. extern int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd,
  103133. ogg_packet *op);
  103134. /* Vorbis PRIMITIVES: synthesis layer *******************************/
  103135. extern int vorbis_synthesis_headerin(vorbis_info *vi,vorbis_comment *vc,
  103136. ogg_packet *op);
  103137. extern int vorbis_synthesis_init(vorbis_dsp_state *v,vorbis_info *vi);
  103138. extern int vorbis_synthesis_restart(vorbis_dsp_state *v);
  103139. extern int vorbis_synthesis(vorbis_block *vb,ogg_packet *op);
  103140. extern int vorbis_synthesis_trackonly(vorbis_block *vb,ogg_packet *op);
  103141. extern int vorbis_synthesis_blockin(vorbis_dsp_state *v,vorbis_block *vb);
  103142. extern int vorbis_synthesis_pcmout(vorbis_dsp_state *v,float ***pcm);
  103143. extern int vorbis_synthesis_lapout(vorbis_dsp_state *v,float ***pcm);
  103144. extern int vorbis_synthesis_read(vorbis_dsp_state *v,int samples);
  103145. extern long vorbis_packet_blocksize(vorbis_info *vi,ogg_packet *op);
  103146. extern int vorbis_synthesis_halfrate(vorbis_info *v,int flag);
  103147. extern int vorbis_synthesis_halfrate_p(vorbis_info *v);
  103148. /* Vorbis ERRORS and return codes ***********************************/
  103149. #define OV_FALSE -1
  103150. #define OV_EOF -2
  103151. #define OV_HOLE -3
  103152. #define OV_EREAD -128
  103153. #define OV_EFAULT -129
  103154. #define OV_EIMPL -130
  103155. #define OV_EINVAL -131
  103156. #define OV_ENOTVORBIS -132
  103157. #define OV_EBADHEADER -133
  103158. #define OV_EVERSION -134
  103159. #define OV_ENOTAUDIO -135
  103160. #define OV_EBADPACKET -136
  103161. #define OV_EBADLINK -137
  103162. #define OV_ENOSEEK -138
  103163. #ifdef __cplusplus
  103164. }
  103165. #endif /* __cplusplus */
  103166. #endif
  103167. /********* End of inlined file: codec.h *********/
  103168. extern int vorbis_encode_init(vorbis_info *vi,
  103169. long channels,
  103170. long rate,
  103171. long max_bitrate,
  103172. long nominal_bitrate,
  103173. long min_bitrate);
  103174. extern int vorbis_encode_setup_managed(vorbis_info *vi,
  103175. long channels,
  103176. long rate,
  103177. long max_bitrate,
  103178. long nominal_bitrate,
  103179. long min_bitrate);
  103180. extern int vorbis_encode_setup_vbr(vorbis_info *vi,
  103181. long channels,
  103182. long rate,
  103183. float quality /* quality level from 0. (lo) to 1. (hi) */
  103184. );
  103185. extern int vorbis_encode_init_vbr(vorbis_info *vi,
  103186. long channels,
  103187. long rate,
  103188. float base_quality /* quality level from 0. (lo) to 1. (hi) */
  103189. );
  103190. extern int vorbis_encode_setup_init(vorbis_info *vi);
  103191. extern int vorbis_encode_ctl(vorbis_info *vi,int number,void *arg);
  103192. /* deprecated rate management supported only for compatability */
  103193. #define OV_ECTL_RATEMANAGE_GET 0x10
  103194. #define OV_ECTL_RATEMANAGE_SET 0x11
  103195. #define OV_ECTL_RATEMANAGE_AVG 0x12
  103196. #define OV_ECTL_RATEMANAGE_HARD 0x13
  103197. struct ovectl_ratemanage_arg {
  103198. int management_active;
  103199. long bitrate_hard_min;
  103200. long bitrate_hard_max;
  103201. double bitrate_hard_window;
  103202. long bitrate_av_lo;
  103203. long bitrate_av_hi;
  103204. double bitrate_av_window;
  103205. double bitrate_av_window_center;
  103206. };
  103207. /* new rate setup */
  103208. #define OV_ECTL_RATEMANAGE2_GET 0x14
  103209. #define OV_ECTL_RATEMANAGE2_SET 0x15
  103210. struct ovectl_ratemanage2_arg {
  103211. int management_active;
  103212. long bitrate_limit_min_kbps;
  103213. long bitrate_limit_max_kbps;
  103214. long bitrate_limit_reservoir_bits;
  103215. double bitrate_limit_reservoir_bias;
  103216. long bitrate_average_kbps;
  103217. double bitrate_average_damping;
  103218. };
  103219. #define OV_ECTL_LOWPASS_GET 0x20
  103220. #define OV_ECTL_LOWPASS_SET 0x21
  103221. #define OV_ECTL_IBLOCK_GET 0x30
  103222. #define OV_ECTL_IBLOCK_SET 0x31
  103223. #ifdef __cplusplus
  103224. }
  103225. #endif /* __cplusplus */
  103226. #endif
  103227. /********* End of inlined file: vorbisenc.h *********/
  103228. /********* Start of inlined file: vorbisfile.h *********/
  103229. #ifndef _OV_FILE_H_
  103230. #define _OV_FILE_H_
  103231. #ifdef __cplusplus
  103232. extern "C"
  103233. {
  103234. #endif /* __cplusplus */
  103235. #include <stdio.h>
  103236. /* The function prototypes for the callbacks are basically the same as for
  103237. * the stdio functions fread, fseek, fclose, ftell.
  103238. * The one difference is that the FILE * arguments have been replaced with
  103239. * a void * - this is to be used as a pointer to whatever internal data these
  103240. * functions might need. In the stdio case, it's just a FILE * cast to a void *
  103241. *
  103242. * If you use other functions, check the docs for these functions and return
  103243. * the right values. For seek_func(), you *MUST* return -1 if the stream is
  103244. * unseekable
  103245. */
  103246. typedef struct {
  103247. size_t (*read_func) (void *ptr, size_t size, size_t nmemb, void *datasource);
  103248. int (*seek_func) (void *datasource, ogg_int64_t offset, int whence);
  103249. int (*close_func) (void *datasource);
  103250. long (*tell_func) (void *datasource);
  103251. } ov_callbacks;
  103252. #define NOTOPEN 0
  103253. #define PARTOPEN 1
  103254. #define OPENED 2
  103255. #define STREAMSET 3
  103256. #define INITSET 4
  103257. typedef struct OggVorbis_File {
  103258. void *datasource; /* Pointer to a FILE *, etc. */
  103259. int seekable;
  103260. ogg_int64_t offset;
  103261. ogg_int64_t end;
  103262. ogg_sync_state oy;
  103263. /* If the FILE handle isn't seekable (eg, a pipe), only the current
  103264. stream appears */
  103265. int links;
  103266. ogg_int64_t *offsets;
  103267. ogg_int64_t *dataoffsets;
  103268. long *serialnos;
  103269. ogg_int64_t *pcmlengths; /* overloaded to maintain binary
  103270. compatability; x2 size, stores both
  103271. beginning and end values */
  103272. vorbis_info *vi;
  103273. vorbis_comment *vc;
  103274. /* Decoding working state local storage */
  103275. ogg_int64_t pcm_offset;
  103276. int ready_state;
  103277. long current_serialno;
  103278. int current_link;
  103279. double bittrack;
  103280. double samptrack;
  103281. ogg_stream_state os; /* take physical pages, weld into a logical
  103282. stream of packets */
  103283. vorbis_dsp_state vd; /* central working state for the packet->PCM decoder */
  103284. vorbis_block vb; /* local working space for packet->PCM decode */
  103285. ov_callbacks callbacks;
  103286. } OggVorbis_File;
  103287. extern int ov_clear(OggVorbis_File *vf);
  103288. extern int ov_open(FILE *f,OggVorbis_File *vf,char *initial,long ibytes);
  103289. extern int ov_open_callbacks(void *datasource, OggVorbis_File *vf,
  103290. char *initial, long ibytes, ov_callbacks callbacks);
  103291. extern int ov_test(FILE *f,OggVorbis_File *vf,char *initial,long ibytes);
  103292. extern int ov_test_callbacks(void *datasource, OggVorbis_File *vf,
  103293. char *initial, long ibytes, ov_callbacks callbacks);
  103294. extern int ov_test_open(OggVorbis_File *vf);
  103295. extern long ov_bitrate(OggVorbis_File *vf,int i);
  103296. extern long ov_bitrate_instant(OggVorbis_File *vf);
  103297. extern long ov_streams(OggVorbis_File *vf);
  103298. extern long ov_seekable(OggVorbis_File *vf);
  103299. extern long ov_serialnumber(OggVorbis_File *vf,int i);
  103300. extern ogg_int64_t ov_raw_total(OggVorbis_File *vf,int i);
  103301. extern ogg_int64_t ov_pcm_total(OggVorbis_File *vf,int i);
  103302. extern double ov_time_total(OggVorbis_File *vf,int i);
  103303. extern int ov_raw_seek(OggVorbis_File *vf,ogg_int64_t pos);
  103304. extern int ov_pcm_seek(OggVorbis_File *vf,ogg_int64_t pos);
  103305. extern int ov_pcm_seek_page(OggVorbis_File *vf,ogg_int64_t pos);
  103306. extern int ov_time_seek(OggVorbis_File *vf,double pos);
  103307. extern int ov_time_seek_page(OggVorbis_File *vf,double pos);
  103308. extern int ov_raw_seek_lap(OggVorbis_File *vf,ogg_int64_t pos);
  103309. extern int ov_pcm_seek_lap(OggVorbis_File *vf,ogg_int64_t pos);
  103310. extern int ov_pcm_seek_page_lap(OggVorbis_File *vf,ogg_int64_t pos);
  103311. extern int ov_time_seek_lap(OggVorbis_File *vf,double pos);
  103312. extern int ov_time_seek_page_lap(OggVorbis_File *vf,double pos);
  103313. extern ogg_int64_t ov_raw_tell(OggVorbis_File *vf);
  103314. extern ogg_int64_t ov_pcm_tell(OggVorbis_File *vf);
  103315. extern double ov_time_tell(OggVorbis_File *vf);
  103316. extern vorbis_info *ov_info(OggVorbis_File *vf,int link);
  103317. extern vorbis_comment *ov_comment(OggVorbis_File *vf,int link);
  103318. extern long ov_read_float(OggVorbis_File *vf,float ***pcm_channels,int samples,
  103319. int *bitstream);
  103320. extern long ov_read(OggVorbis_File *vf,char *buffer,int length,
  103321. int bigendianp,int word,int sgned,int *bitstream);
  103322. extern int ov_crosslap(OggVorbis_File *vf1,OggVorbis_File *vf2);
  103323. extern int ov_halfrate(OggVorbis_File *vf,int flag);
  103324. extern int ov_halfrate_p(OggVorbis_File *vf);
  103325. #ifdef __cplusplus
  103326. }
  103327. #endif /* __cplusplus */
  103328. #endif
  103329. /********* End of inlined file: vorbisfile.h *********/
  103330. /********* Start of inlined file: bitwise.c *********/
  103331. /* We're 'LSb' endian; if we write a word but read individual bits,
  103332. then we'll read the lsb first */
  103333. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  103334. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  103335. // tasks..
  103336. #ifdef _MSC_VER
  103337. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  103338. #endif
  103339. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  103340. #if JUCE_USE_OGGVORBIS
  103341. #include <string.h>
  103342. #include <stdlib.h>
  103343. #define BUFFER_INCREMENT 256
  103344. static const unsigned long mask[]=
  103345. {0x00000000,0x00000001,0x00000003,0x00000007,0x0000000f,
  103346. 0x0000001f,0x0000003f,0x0000007f,0x000000ff,0x000001ff,
  103347. 0x000003ff,0x000007ff,0x00000fff,0x00001fff,0x00003fff,
  103348. 0x00007fff,0x0000ffff,0x0001ffff,0x0003ffff,0x0007ffff,
  103349. 0x000fffff,0x001fffff,0x003fffff,0x007fffff,0x00ffffff,
  103350. 0x01ffffff,0x03ffffff,0x07ffffff,0x0fffffff,0x1fffffff,
  103351. 0x3fffffff,0x7fffffff,0xffffffff };
  103352. static const unsigned int mask8B[]=
  103353. {0x00,0x80,0xc0,0xe0,0xf0,0xf8,0xfc,0xfe,0xff};
  103354. void oggpack_writeinit(oggpack_buffer *b){
  103355. memset(b,0,sizeof(*b));
  103356. b->ptr=b->buffer=(unsigned char*) _ogg_malloc(BUFFER_INCREMENT);
  103357. b->buffer[0]='\0';
  103358. b->storage=BUFFER_INCREMENT;
  103359. }
  103360. void oggpackB_writeinit(oggpack_buffer *b){
  103361. oggpack_writeinit(b);
  103362. }
  103363. void oggpack_writetrunc(oggpack_buffer *b,long bits){
  103364. long bytes=bits>>3;
  103365. bits-=bytes*8;
  103366. b->ptr=b->buffer+bytes;
  103367. b->endbit=bits;
  103368. b->endbyte=bytes;
  103369. *b->ptr&=mask[bits];
  103370. }
  103371. void oggpackB_writetrunc(oggpack_buffer *b,long bits){
  103372. long bytes=bits>>3;
  103373. bits-=bytes*8;
  103374. b->ptr=b->buffer+bytes;
  103375. b->endbit=bits;
  103376. b->endbyte=bytes;
  103377. *b->ptr&=mask8B[bits];
  103378. }
  103379. /* Takes only up to 32 bits. */
  103380. void oggpack_write(oggpack_buffer *b,unsigned long value,int bits){
  103381. if(b->endbyte+4>=b->storage){
  103382. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage+BUFFER_INCREMENT);
  103383. b->storage+=BUFFER_INCREMENT;
  103384. b->ptr=b->buffer+b->endbyte;
  103385. }
  103386. value&=mask[bits];
  103387. bits+=b->endbit;
  103388. b->ptr[0]|=value<<b->endbit;
  103389. if(bits>=8){
  103390. b->ptr[1]=(unsigned char)(value>>(8-b->endbit));
  103391. if(bits>=16){
  103392. b->ptr[2]=(unsigned char)(value>>(16-b->endbit));
  103393. if(bits>=24){
  103394. b->ptr[3]=(unsigned char)(value>>(24-b->endbit));
  103395. if(bits>=32){
  103396. if(b->endbit)
  103397. b->ptr[4]=(unsigned char)(value>>(32-b->endbit));
  103398. else
  103399. b->ptr[4]=0;
  103400. }
  103401. }
  103402. }
  103403. }
  103404. b->endbyte+=bits/8;
  103405. b->ptr+=bits/8;
  103406. b->endbit=bits&7;
  103407. }
  103408. /* Takes only up to 32 bits. */
  103409. void oggpackB_write(oggpack_buffer *b,unsigned long value,int bits){
  103410. if(b->endbyte+4>=b->storage){
  103411. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage+BUFFER_INCREMENT);
  103412. b->storage+=BUFFER_INCREMENT;
  103413. b->ptr=b->buffer+b->endbyte;
  103414. }
  103415. value=(value&mask[bits])<<(32-bits);
  103416. bits+=b->endbit;
  103417. b->ptr[0]|=value>>(24+b->endbit);
  103418. if(bits>=8){
  103419. b->ptr[1]=(unsigned char)(value>>(16+b->endbit));
  103420. if(bits>=16){
  103421. b->ptr[2]=(unsigned char)(value>>(8+b->endbit));
  103422. if(bits>=24){
  103423. b->ptr[3]=(unsigned char)(value>>(b->endbit));
  103424. if(bits>=32){
  103425. if(b->endbit)
  103426. b->ptr[4]=(unsigned char)(value<<(8-b->endbit));
  103427. else
  103428. b->ptr[4]=0;
  103429. }
  103430. }
  103431. }
  103432. }
  103433. b->endbyte+=bits/8;
  103434. b->ptr+=bits/8;
  103435. b->endbit=bits&7;
  103436. }
  103437. void oggpack_writealign(oggpack_buffer *b){
  103438. int bits=8-b->endbit;
  103439. if(bits<8)
  103440. oggpack_write(b,0,bits);
  103441. }
  103442. void oggpackB_writealign(oggpack_buffer *b){
  103443. int bits=8-b->endbit;
  103444. if(bits<8)
  103445. oggpackB_write(b,0,bits);
  103446. }
  103447. static void oggpack_writecopy_helper(oggpack_buffer *b,
  103448. void *source,
  103449. long bits,
  103450. void (*w)(oggpack_buffer *,
  103451. unsigned long,
  103452. int),
  103453. int msb){
  103454. unsigned char *ptr=(unsigned char *)source;
  103455. long bytes=bits/8;
  103456. bits-=bytes*8;
  103457. if(b->endbit){
  103458. int i;
  103459. /* unaligned copy. Do it the hard way. */
  103460. for(i=0;i<bytes;i++)
  103461. w(b,(unsigned long)(ptr[i]),8);
  103462. }else{
  103463. /* aligned block copy */
  103464. if(b->endbyte+bytes+1>=b->storage){
  103465. b->storage=b->endbyte+bytes+BUFFER_INCREMENT;
  103466. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage);
  103467. b->ptr=b->buffer+b->endbyte;
  103468. }
  103469. memmove(b->ptr,source,bytes);
  103470. b->ptr+=bytes;
  103471. b->endbyte+=bytes;
  103472. *b->ptr=0;
  103473. }
  103474. if(bits){
  103475. if(msb)
  103476. w(b,(unsigned long)(ptr[bytes]>>(8-bits)),bits);
  103477. else
  103478. w(b,(unsigned long)(ptr[bytes]),bits);
  103479. }
  103480. }
  103481. void oggpack_writecopy(oggpack_buffer *b,void *source,long bits){
  103482. oggpack_writecopy_helper(b,source,bits,oggpack_write,0);
  103483. }
  103484. void oggpackB_writecopy(oggpack_buffer *b,void *source,long bits){
  103485. oggpack_writecopy_helper(b,source,bits,oggpackB_write,1);
  103486. }
  103487. void oggpack_reset(oggpack_buffer *b){
  103488. b->ptr=b->buffer;
  103489. b->buffer[0]=0;
  103490. b->endbit=b->endbyte=0;
  103491. }
  103492. void oggpackB_reset(oggpack_buffer *b){
  103493. oggpack_reset(b);
  103494. }
  103495. void oggpack_writeclear(oggpack_buffer *b){
  103496. _ogg_free(b->buffer);
  103497. memset(b,0,sizeof(*b));
  103498. }
  103499. void oggpackB_writeclear(oggpack_buffer *b){
  103500. oggpack_writeclear(b);
  103501. }
  103502. void oggpack_readinit(oggpack_buffer *b,unsigned char *buf,int bytes){
  103503. memset(b,0,sizeof(*b));
  103504. b->buffer=b->ptr=buf;
  103505. b->storage=bytes;
  103506. }
  103507. void oggpackB_readinit(oggpack_buffer *b,unsigned char *buf,int bytes){
  103508. oggpack_readinit(b,buf,bytes);
  103509. }
  103510. /* Read in bits without advancing the bitptr; bits <= 32 */
  103511. long oggpack_look(oggpack_buffer *b,int bits){
  103512. unsigned long ret;
  103513. unsigned long m=mask[bits];
  103514. bits+=b->endbit;
  103515. if(b->endbyte+4>=b->storage){
  103516. /* not the main path */
  103517. if(b->endbyte*8+bits>b->storage*8)return(-1);
  103518. }
  103519. ret=b->ptr[0]>>b->endbit;
  103520. if(bits>8){
  103521. ret|=b->ptr[1]<<(8-b->endbit);
  103522. if(bits>16){
  103523. ret|=b->ptr[2]<<(16-b->endbit);
  103524. if(bits>24){
  103525. ret|=b->ptr[3]<<(24-b->endbit);
  103526. if(bits>32 && b->endbit)
  103527. ret|=b->ptr[4]<<(32-b->endbit);
  103528. }
  103529. }
  103530. }
  103531. return(m&ret);
  103532. }
  103533. /* Read in bits without advancing the bitptr; bits <= 32 */
  103534. long oggpackB_look(oggpack_buffer *b,int bits){
  103535. unsigned long ret;
  103536. int m=32-bits;
  103537. bits+=b->endbit;
  103538. if(b->endbyte+4>=b->storage){
  103539. /* not the main path */
  103540. if(b->endbyte*8+bits>b->storage*8)return(-1);
  103541. }
  103542. ret=b->ptr[0]<<(24+b->endbit);
  103543. if(bits>8){
  103544. ret|=b->ptr[1]<<(16+b->endbit);
  103545. if(bits>16){
  103546. ret|=b->ptr[2]<<(8+b->endbit);
  103547. if(bits>24){
  103548. ret|=b->ptr[3]<<(b->endbit);
  103549. if(bits>32 && b->endbit)
  103550. ret|=b->ptr[4]>>(8-b->endbit);
  103551. }
  103552. }
  103553. }
  103554. return ((ret&0xffffffff)>>(m>>1))>>((m+1)>>1);
  103555. }
  103556. long oggpack_look1(oggpack_buffer *b){
  103557. if(b->endbyte>=b->storage)return(-1);
  103558. return((b->ptr[0]>>b->endbit)&1);
  103559. }
  103560. long oggpackB_look1(oggpack_buffer *b){
  103561. if(b->endbyte>=b->storage)return(-1);
  103562. return((b->ptr[0]>>(7-b->endbit))&1);
  103563. }
  103564. void oggpack_adv(oggpack_buffer *b,int bits){
  103565. bits+=b->endbit;
  103566. b->ptr+=bits/8;
  103567. b->endbyte+=bits/8;
  103568. b->endbit=bits&7;
  103569. }
  103570. void oggpackB_adv(oggpack_buffer *b,int bits){
  103571. oggpack_adv(b,bits);
  103572. }
  103573. void oggpack_adv1(oggpack_buffer *b){
  103574. if(++(b->endbit)>7){
  103575. b->endbit=0;
  103576. b->ptr++;
  103577. b->endbyte++;
  103578. }
  103579. }
  103580. void oggpackB_adv1(oggpack_buffer *b){
  103581. oggpack_adv1(b);
  103582. }
  103583. /* bits <= 32 */
  103584. long oggpack_read(oggpack_buffer *b,int bits){
  103585. long ret;
  103586. unsigned long m=mask[bits];
  103587. bits+=b->endbit;
  103588. if(b->endbyte+4>=b->storage){
  103589. /* not the main path */
  103590. ret=-1L;
  103591. if(b->endbyte*8+bits>b->storage*8)goto overflow;
  103592. }
  103593. ret=b->ptr[0]>>b->endbit;
  103594. if(bits>8){
  103595. ret|=b->ptr[1]<<(8-b->endbit);
  103596. if(bits>16){
  103597. ret|=b->ptr[2]<<(16-b->endbit);
  103598. if(bits>24){
  103599. ret|=b->ptr[3]<<(24-b->endbit);
  103600. if(bits>32 && b->endbit){
  103601. ret|=b->ptr[4]<<(32-b->endbit);
  103602. }
  103603. }
  103604. }
  103605. }
  103606. ret&=m;
  103607. overflow:
  103608. b->ptr+=bits/8;
  103609. b->endbyte+=bits/8;
  103610. b->endbit=bits&7;
  103611. return(ret);
  103612. }
  103613. /* bits <= 32 */
  103614. long oggpackB_read(oggpack_buffer *b,int bits){
  103615. long ret;
  103616. long m=32-bits;
  103617. bits+=b->endbit;
  103618. if(b->endbyte+4>=b->storage){
  103619. /* not the main path */
  103620. ret=-1L;
  103621. if(b->endbyte*8+bits>b->storage*8)goto overflow;
  103622. }
  103623. ret=b->ptr[0]<<(24+b->endbit);
  103624. if(bits>8){
  103625. ret|=b->ptr[1]<<(16+b->endbit);
  103626. if(bits>16){
  103627. ret|=b->ptr[2]<<(8+b->endbit);
  103628. if(bits>24){
  103629. ret|=b->ptr[3]<<(b->endbit);
  103630. if(bits>32 && b->endbit)
  103631. ret|=b->ptr[4]>>(8-b->endbit);
  103632. }
  103633. }
  103634. }
  103635. ret=((ret&0xffffffffUL)>>(m>>1))>>((m+1)>>1);
  103636. overflow:
  103637. b->ptr+=bits/8;
  103638. b->endbyte+=bits/8;
  103639. b->endbit=bits&7;
  103640. return(ret);
  103641. }
  103642. long oggpack_read1(oggpack_buffer *b){
  103643. long ret;
  103644. if(b->endbyte>=b->storage){
  103645. /* not the main path */
  103646. ret=-1L;
  103647. goto overflow;
  103648. }
  103649. ret=(b->ptr[0]>>b->endbit)&1;
  103650. overflow:
  103651. b->endbit++;
  103652. if(b->endbit>7){
  103653. b->endbit=0;
  103654. b->ptr++;
  103655. b->endbyte++;
  103656. }
  103657. return(ret);
  103658. }
  103659. long oggpackB_read1(oggpack_buffer *b){
  103660. long ret;
  103661. if(b->endbyte>=b->storage){
  103662. /* not the main path */
  103663. ret=-1L;
  103664. goto overflow;
  103665. }
  103666. ret=(b->ptr[0]>>(7-b->endbit))&1;
  103667. overflow:
  103668. b->endbit++;
  103669. if(b->endbit>7){
  103670. b->endbit=0;
  103671. b->ptr++;
  103672. b->endbyte++;
  103673. }
  103674. return(ret);
  103675. }
  103676. long oggpack_bytes(oggpack_buffer *b){
  103677. return(b->endbyte+(b->endbit+7)/8);
  103678. }
  103679. long oggpack_bits(oggpack_buffer *b){
  103680. return(b->endbyte*8+b->endbit);
  103681. }
  103682. long oggpackB_bytes(oggpack_buffer *b){
  103683. return oggpack_bytes(b);
  103684. }
  103685. long oggpackB_bits(oggpack_buffer *b){
  103686. return oggpack_bits(b);
  103687. }
  103688. unsigned char *oggpack_get_buffer(oggpack_buffer *b){
  103689. return(b->buffer);
  103690. }
  103691. unsigned char *oggpackB_get_buffer(oggpack_buffer *b){
  103692. return oggpack_get_buffer(b);
  103693. }
  103694. /* Self test of the bitwise routines; everything else is based on
  103695. them, so they damned well better be solid. */
  103696. #ifdef _V_SELFTEST
  103697. #include <stdio.h>
  103698. static int ilog(unsigned int v){
  103699. int ret=0;
  103700. while(v){
  103701. ret++;
  103702. v>>=1;
  103703. }
  103704. return(ret);
  103705. }
  103706. oggpack_buffer o;
  103707. oggpack_buffer r;
  103708. void report(char *in){
  103709. fprintf(stderr,"%s",in);
  103710. exit(1);
  103711. }
  103712. void cliptest(unsigned long *b,int vals,int bits,int *comp,int compsize){
  103713. long bytes,i;
  103714. unsigned char *buffer;
  103715. oggpack_reset(&o);
  103716. for(i=0;i<vals;i++)
  103717. oggpack_write(&o,b[i],bits?bits:ilog(b[i]));
  103718. buffer=oggpack_get_buffer(&o);
  103719. bytes=oggpack_bytes(&o);
  103720. if(bytes!=compsize)report("wrong number of bytes!\n");
  103721. for(i=0;i<bytes;i++)if(buffer[i]!=comp[i]){
  103722. for(i=0;i<bytes;i++)fprintf(stderr,"%x %x\n",(int)buffer[i],(int)comp[i]);
  103723. report("wrote incorrect value!\n");
  103724. }
  103725. oggpack_readinit(&r,buffer,bytes);
  103726. for(i=0;i<vals;i++){
  103727. int tbit=bits?bits:ilog(b[i]);
  103728. if(oggpack_look(&r,tbit)==-1)
  103729. report("out of data!\n");
  103730. if(oggpack_look(&r,tbit)!=(b[i]&mask[tbit]))
  103731. report("looked at incorrect value!\n");
  103732. if(tbit==1)
  103733. if(oggpack_look1(&r)!=(b[i]&mask[tbit]))
  103734. report("looked at single bit incorrect value!\n");
  103735. if(tbit==1){
  103736. if(oggpack_read1(&r)!=(b[i]&mask[tbit]))
  103737. report("read incorrect single bit value!\n");
  103738. }else{
  103739. if(oggpack_read(&r,tbit)!=(b[i]&mask[tbit]))
  103740. report("read incorrect value!\n");
  103741. }
  103742. }
  103743. if(oggpack_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  103744. }
  103745. void cliptestB(unsigned long *b,int vals,int bits,int *comp,int compsize){
  103746. long bytes,i;
  103747. unsigned char *buffer;
  103748. oggpackB_reset(&o);
  103749. for(i=0;i<vals;i++)
  103750. oggpackB_write(&o,b[i],bits?bits:ilog(b[i]));
  103751. buffer=oggpackB_get_buffer(&o);
  103752. bytes=oggpackB_bytes(&o);
  103753. if(bytes!=compsize)report("wrong number of bytes!\n");
  103754. for(i=0;i<bytes;i++)if(buffer[i]!=comp[i]){
  103755. for(i=0;i<bytes;i++)fprintf(stderr,"%x %x\n",(int)buffer[i],(int)comp[i]);
  103756. report("wrote incorrect value!\n");
  103757. }
  103758. oggpackB_readinit(&r,buffer,bytes);
  103759. for(i=0;i<vals;i++){
  103760. int tbit=bits?bits:ilog(b[i]);
  103761. if(oggpackB_look(&r,tbit)==-1)
  103762. report("out of data!\n");
  103763. if(oggpackB_look(&r,tbit)!=(b[i]&mask[tbit]))
  103764. report("looked at incorrect value!\n");
  103765. if(tbit==1)
  103766. if(oggpackB_look1(&r)!=(b[i]&mask[tbit]))
  103767. report("looked at single bit incorrect value!\n");
  103768. if(tbit==1){
  103769. if(oggpackB_read1(&r)!=(b[i]&mask[tbit]))
  103770. report("read incorrect single bit value!\n");
  103771. }else{
  103772. if(oggpackB_read(&r,tbit)!=(b[i]&mask[tbit]))
  103773. report("read incorrect value!\n");
  103774. }
  103775. }
  103776. if(oggpackB_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  103777. }
  103778. int main(void){
  103779. unsigned char *buffer;
  103780. long bytes,i;
  103781. static unsigned long testbuffer1[]=
  103782. {18,12,103948,4325,543,76,432,52,3,65,4,56,32,42,34,21,1,23,32,546,456,7,
  103783. 567,56,8,8,55,3,52,342,341,4,265,7,67,86,2199,21,7,1,5,1,4};
  103784. int test1size=43;
  103785. static unsigned long testbuffer2[]=
  103786. {216531625L,1237861823,56732452,131,3212421,12325343,34547562,12313212,
  103787. 1233432,534,5,346435231,14436467,7869299,76326614,167548585,
  103788. 85525151,0,12321,1,349528352};
  103789. int test2size=21;
  103790. static unsigned long testbuffer3[]=
  103791. {1,0,14,0,1,0,12,0,1,0,0,0,1,1,0,1,0,1,0,1,0,1,0,1,0,1,0,0,1,1,1,1,1,0,0,1,
  103792. 0,1,30,1,1,1,0,0,1,0,0,0,12,0,11,0,1,0,0,1};
  103793. int test3size=56;
  103794. static unsigned long large[]=
  103795. {2136531625L,2137861823,56732452,131,3212421,12325343,34547562,12313212,
  103796. 1233432,534,5,2146435231,14436467,7869299,76326614,167548585,
  103797. 85525151,0,12321,1,2146528352};
  103798. int onesize=33;
  103799. static int one[33]={146,25,44,151,195,15,153,176,233,131,196,65,85,172,47,40,
  103800. 34,242,223,136,35,222,211,86,171,50,225,135,214,75,172,
  103801. 223,4};
  103802. static int oneB[33]={150,101,131,33,203,15,204,216,105,193,156,65,84,85,222,
  103803. 8,139,145,227,126,34,55,244,171,85,100,39,195,173,18,
  103804. 245,251,128};
  103805. int twosize=6;
  103806. static int two[6]={61,255,255,251,231,29};
  103807. static int twoB[6]={247,63,255,253,249,120};
  103808. int threesize=54;
  103809. static int three[54]={169,2,232,252,91,132,156,36,89,13,123,176,144,32,254,
  103810. 142,224,85,59,121,144,79,124,23,67,90,90,216,79,23,83,
  103811. 58,135,196,61,55,129,183,54,101,100,170,37,127,126,10,
  103812. 100,52,4,14,18,86,77,1};
  103813. static int threeB[54]={206,128,42,153,57,8,183,251,13,89,36,30,32,144,183,
  103814. 130,59,240,121,59,85,223,19,228,180,134,33,107,74,98,
  103815. 233,253,196,135,63,2,110,114,50,155,90,127,37,170,104,
  103816. 200,20,254,4,58,106,176,144,0};
  103817. int foursize=38;
  103818. static int four[38]={18,6,163,252,97,194,104,131,32,1,7,82,137,42,129,11,72,
  103819. 132,60,220,112,8,196,109,64,179,86,9,137,195,208,122,169,
  103820. 28,2,133,0,1};
  103821. static int fourB[38]={36,48,102,83,243,24,52,7,4,35,132,10,145,21,2,93,2,41,
  103822. 1,219,184,16,33,184,54,149,170,132,18,30,29,98,229,67,
  103823. 129,10,4,32};
  103824. int fivesize=45;
  103825. static int five[45]={169,2,126,139,144,172,30,4,80,72,240,59,130,218,73,62,
  103826. 241,24,210,44,4,20,0,248,116,49,135,100,110,130,181,169,
  103827. 84,75,159,2,1,0,132,192,8,0,0,18,22};
  103828. static int fiveB[45]={1,84,145,111,245,100,128,8,56,36,40,71,126,78,213,226,
  103829. 124,105,12,0,133,128,0,162,233,242,67,152,77,205,77,
  103830. 172,150,169,129,79,128,0,6,4,32,0,27,9,0};
  103831. int sixsize=7;
  103832. static int six[7]={17,177,170,242,169,19,148};
  103833. static int sixB[7]={136,141,85,79,149,200,41};
  103834. /* Test read/write together */
  103835. /* Later we test against pregenerated bitstreams */
  103836. oggpack_writeinit(&o);
  103837. fprintf(stderr,"\nSmall preclipped packing (LSb): ");
  103838. cliptest(testbuffer1,test1size,0,one,onesize);
  103839. fprintf(stderr,"ok.");
  103840. fprintf(stderr,"\nNull bit call (LSb): ");
  103841. cliptest(testbuffer3,test3size,0,two,twosize);
  103842. fprintf(stderr,"ok.");
  103843. fprintf(stderr,"\nLarge preclipped packing (LSb): ");
  103844. cliptest(testbuffer2,test2size,0,three,threesize);
  103845. fprintf(stderr,"ok.");
  103846. fprintf(stderr,"\n32 bit preclipped packing (LSb): ");
  103847. oggpack_reset(&o);
  103848. for(i=0;i<test2size;i++)
  103849. oggpack_write(&o,large[i],32);
  103850. buffer=oggpack_get_buffer(&o);
  103851. bytes=oggpack_bytes(&o);
  103852. oggpack_readinit(&r,buffer,bytes);
  103853. for(i=0;i<test2size;i++){
  103854. if(oggpack_look(&r,32)==-1)report("out of data. failed!");
  103855. if(oggpack_look(&r,32)!=large[i]){
  103856. fprintf(stderr,"%ld != %ld (%lx!=%lx):",oggpack_look(&r,32),large[i],
  103857. oggpack_look(&r,32),large[i]);
  103858. report("read incorrect value!\n");
  103859. }
  103860. oggpack_adv(&r,32);
  103861. }
  103862. if(oggpack_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  103863. fprintf(stderr,"ok.");
  103864. fprintf(stderr,"\nSmall unclipped packing (LSb): ");
  103865. cliptest(testbuffer1,test1size,7,four,foursize);
  103866. fprintf(stderr,"ok.");
  103867. fprintf(stderr,"\nLarge unclipped packing (LSb): ");
  103868. cliptest(testbuffer2,test2size,17,five,fivesize);
  103869. fprintf(stderr,"ok.");
  103870. fprintf(stderr,"\nSingle bit unclipped packing (LSb): ");
  103871. cliptest(testbuffer3,test3size,1,six,sixsize);
  103872. fprintf(stderr,"ok.");
  103873. fprintf(stderr,"\nTesting read past end (LSb): ");
  103874. oggpack_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  103875. for(i=0;i<64;i++){
  103876. if(oggpack_read(&r,1)!=0){
  103877. fprintf(stderr,"failed; got -1 prematurely.\n");
  103878. exit(1);
  103879. }
  103880. }
  103881. if(oggpack_look(&r,1)!=-1 ||
  103882. oggpack_read(&r,1)!=-1){
  103883. fprintf(stderr,"failed; read past end without -1.\n");
  103884. exit(1);
  103885. }
  103886. oggpack_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  103887. if(oggpack_read(&r,30)!=0 || oggpack_read(&r,16)!=0){
  103888. fprintf(stderr,"failed 2; got -1 prematurely.\n");
  103889. exit(1);
  103890. }
  103891. if(oggpack_look(&r,18)!=0 ||
  103892. oggpack_look(&r,18)!=0){
  103893. fprintf(stderr,"failed 3; got -1 prematurely.\n");
  103894. exit(1);
  103895. }
  103896. if(oggpack_look(&r,19)!=-1 ||
  103897. oggpack_look(&r,19)!=-1){
  103898. fprintf(stderr,"failed; read past end without -1.\n");
  103899. exit(1);
  103900. }
  103901. if(oggpack_look(&r,32)!=-1 ||
  103902. oggpack_look(&r,32)!=-1){
  103903. fprintf(stderr,"failed; read past end without -1.\n");
  103904. exit(1);
  103905. }
  103906. oggpack_writeclear(&o);
  103907. fprintf(stderr,"ok.\n");
  103908. /********** lazy, cut-n-paste retest with MSb packing ***********/
  103909. /* Test read/write together */
  103910. /* Later we test against pregenerated bitstreams */
  103911. oggpackB_writeinit(&o);
  103912. fprintf(stderr,"\nSmall preclipped packing (MSb): ");
  103913. cliptestB(testbuffer1,test1size,0,oneB,onesize);
  103914. fprintf(stderr,"ok.");
  103915. fprintf(stderr,"\nNull bit call (MSb): ");
  103916. cliptestB(testbuffer3,test3size,0,twoB,twosize);
  103917. fprintf(stderr,"ok.");
  103918. fprintf(stderr,"\nLarge preclipped packing (MSb): ");
  103919. cliptestB(testbuffer2,test2size,0,threeB,threesize);
  103920. fprintf(stderr,"ok.");
  103921. fprintf(stderr,"\n32 bit preclipped packing (MSb): ");
  103922. oggpackB_reset(&o);
  103923. for(i=0;i<test2size;i++)
  103924. oggpackB_write(&o,large[i],32);
  103925. buffer=oggpackB_get_buffer(&o);
  103926. bytes=oggpackB_bytes(&o);
  103927. oggpackB_readinit(&r,buffer,bytes);
  103928. for(i=0;i<test2size;i++){
  103929. if(oggpackB_look(&r,32)==-1)report("out of data. failed!");
  103930. if(oggpackB_look(&r,32)!=large[i]){
  103931. fprintf(stderr,"%ld != %ld (%lx!=%lx):",oggpackB_look(&r,32),large[i],
  103932. oggpackB_look(&r,32),large[i]);
  103933. report("read incorrect value!\n");
  103934. }
  103935. oggpackB_adv(&r,32);
  103936. }
  103937. if(oggpackB_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  103938. fprintf(stderr,"ok.");
  103939. fprintf(stderr,"\nSmall unclipped packing (MSb): ");
  103940. cliptestB(testbuffer1,test1size,7,fourB,foursize);
  103941. fprintf(stderr,"ok.");
  103942. fprintf(stderr,"\nLarge unclipped packing (MSb): ");
  103943. cliptestB(testbuffer2,test2size,17,fiveB,fivesize);
  103944. fprintf(stderr,"ok.");
  103945. fprintf(stderr,"\nSingle bit unclipped packing (MSb): ");
  103946. cliptestB(testbuffer3,test3size,1,sixB,sixsize);
  103947. fprintf(stderr,"ok.");
  103948. fprintf(stderr,"\nTesting read past end (MSb): ");
  103949. oggpackB_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  103950. for(i=0;i<64;i++){
  103951. if(oggpackB_read(&r,1)!=0){
  103952. fprintf(stderr,"failed; got -1 prematurely.\n");
  103953. exit(1);
  103954. }
  103955. }
  103956. if(oggpackB_look(&r,1)!=-1 ||
  103957. oggpackB_read(&r,1)!=-1){
  103958. fprintf(stderr,"failed; read past end without -1.\n");
  103959. exit(1);
  103960. }
  103961. oggpackB_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  103962. if(oggpackB_read(&r,30)!=0 || oggpackB_read(&r,16)!=0){
  103963. fprintf(stderr,"failed 2; got -1 prematurely.\n");
  103964. exit(1);
  103965. }
  103966. if(oggpackB_look(&r,18)!=0 ||
  103967. oggpackB_look(&r,18)!=0){
  103968. fprintf(stderr,"failed 3; got -1 prematurely.\n");
  103969. exit(1);
  103970. }
  103971. if(oggpackB_look(&r,19)!=-1 ||
  103972. oggpackB_look(&r,19)!=-1){
  103973. fprintf(stderr,"failed; read past end without -1.\n");
  103974. exit(1);
  103975. }
  103976. if(oggpackB_look(&r,32)!=-1 ||
  103977. oggpackB_look(&r,32)!=-1){
  103978. fprintf(stderr,"failed; read past end without -1.\n");
  103979. exit(1);
  103980. }
  103981. oggpackB_writeclear(&o);
  103982. fprintf(stderr,"ok.\n\n");
  103983. return(0);
  103984. }
  103985. #endif /* _V_SELFTEST */
  103986. #undef BUFFER_INCREMENT
  103987. #endif
  103988. /********* End of inlined file: bitwise.c *********/
  103989. /********* Start of inlined file: framing.c *********/
  103990. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  103991. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  103992. // tasks..
  103993. #ifdef _MSC_VER
  103994. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  103995. #endif
  103996. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  103997. #if JUCE_USE_OGGVORBIS
  103998. #include <stdlib.h>
  103999. #include <string.h>
  104000. /* A complete description of Ogg framing exists in docs/framing.html */
  104001. int ogg_page_version(ogg_page *og){
  104002. return((int)(og->header[4]));
  104003. }
  104004. int ogg_page_continued(ogg_page *og){
  104005. return((int)(og->header[5]&0x01));
  104006. }
  104007. int ogg_page_bos(ogg_page *og){
  104008. return((int)(og->header[5]&0x02));
  104009. }
  104010. int ogg_page_eos(ogg_page *og){
  104011. return((int)(og->header[5]&0x04));
  104012. }
  104013. ogg_int64_t ogg_page_granulepos(ogg_page *og){
  104014. unsigned char *page=og->header;
  104015. ogg_int64_t granulepos=page[13]&(0xff);
  104016. granulepos= (granulepos<<8)|(page[12]&0xff);
  104017. granulepos= (granulepos<<8)|(page[11]&0xff);
  104018. granulepos= (granulepos<<8)|(page[10]&0xff);
  104019. granulepos= (granulepos<<8)|(page[9]&0xff);
  104020. granulepos= (granulepos<<8)|(page[8]&0xff);
  104021. granulepos= (granulepos<<8)|(page[7]&0xff);
  104022. granulepos= (granulepos<<8)|(page[6]&0xff);
  104023. return(granulepos);
  104024. }
  104025. int ogg_page_serialno(ogg_page *og){
  104026. return(og->header[14] |
  104027. (og->header[15]<<8) |
  104028. (og->header[16]<<16) |
  104029. (og->header[17]<<24));
  104030. }
  104031. long ogg_page_pageno(ogg_page *og){
  104032. return(og->header[18] |
  104033. (og->header[19]<<8) |
  104034. (og->header[20]<<16) |
  104035. (og->header[21]<<24));
  104036. }
  104037. /* returns the number of packets that are completed on this page (if
  104038. the leading packet is begun on a previous page, but ends on this
  104039. page, it's counted */
  104040. /* NOTE:
  104041. If a page consists of a packet begun on a previous page, and a new
  104042. packet begun (but not completed) on this page, the return will be:
  104043. ogg_page_packets(page) ==1,
  104044. ogg_page_continued(page) !=0
  104045. If a page happens to be a single packet that was begun on a
  104046. previous page, and spans to the next page (in the case of a three or
  104047. more page packet), the return will be:
  104048. ogg_page_packets(page) ==0,
  104049. ogg_page_continued(page) !=0
  104050. */
  104051. int ogg_page_packets(ogg_page *og){
  104052. int i,n=og->header[26],count=0;
  104053. for(i=0;i<n;i++)
  104054. if(og->header[27+i]<255)count++;
  104055. return(count);
  104056. }
  104057. #if 0
  104058. /* helper to initialize lookup for direct-table CRC (illustrative; we
  104059. use the static init below) */
  104060. static ogg_uint32_t _ogg_crc_entry(unsigned long index){
  104061. int i;
  104062. unsigned long r;
  104063. r = index << 24;
  104064. for (i=0; i<8; i++)
  104065. if (r & 0x80000000UL)
  104066. r = (r << 1) ^ 0x04c11db7; /* The same as the ethernet generator
  104067. polynomial, although we use an
  104068. unreflected alg and an init/final
  104069. of 0, not 0xffffffff */
  104070. else
  104071. r<<=1;
  104072. return (r & 0xffffffffUL);
  104073. }
  104074. #endif
  104075. static const ogg_uint32_t crc_lookup[256]={
  104076. 0x00000000,0x04c11db7,0x09823b6e,0x0d4326d9,
  104077. 0x130476dc,0x17c56b6b,0x1a864db2,0x1e475005,
  104078. 0x2608edb8,0x22c9f00f,0x2f8ad6d6,0x2b4bcb61,
  104079. 0x350c9b64,0x31cd86d3,0x3c8ea00a,0x384fbdbd,
  104080. 0x4c11db70,0x48d0c6c7,0x4593e01e,0x4152fda9,
  104081. 0x5f15adac,0x5bd4b01b,0x569796c2,0x52568b75,
  104082. 0x6a1936c8,0x6ed82b7f,0x639b0da6,0x675a1011,
  104083. 0x791d4014,0x7ddc5da3,0x709f7b7a,0x745e66cd,
  104084. 0x9823b6e0,0x9ce2ab57,0x91a18d8e,0x95609039,
  104085. 0x8b27c03c,0x8fe6dd8b,0x82a5fb52,0x8664e6e5,
  104086. 0xbe2b5b58,0xbaea46ef,0xb7a96036,0xb3687d81,
  104087. 0xad2f2d84,0xa9ee3033,0xa4ad16ea,0xa06c0b5d,
  104088. 0xd4326d90,0xd0f37027,0xddb056fe,0xd9714b49,
  104089. 0xc7361b4c,0xc3f706fb,0xceb42022,0xca753d95,
  104090. 0xf23a8028,0xf6fb9d9f,0xfbb8bb46,0xff79a6f1,
  104091. 0xe13ef6f4,0xe5ffeb43,0xe8bccd9a,0xec7dd02d,
  104092. 0x34867077,0x30476dc0,0x3d044b19,0x39c556ae,
  104093. 0x278206ab,0x23431b1c,0x2e003dc5,0x2ac12072,
  104094. 0x128e9dcf,0x164f8078,0x1b0ca6a1,0x1fcdbb16,
  104095. 0x018aeb13,0x054bf6a4,0x0808d07d,0x0cc9cdca,
  104096. 0x7897ab07,0x7c56b6b0,0x71159069,0x75d48dde,
  104097. 0x6b93dddb,0x6f52c06c,0x6211e6b5,0x66d0fb02,
  104098. 0x5e9f46bf,0x5a5e5b08,0x571d7dd1,0x53dc6066,
  104099. 0x4d9b3063,0x495a2dd4,0x44190b0d,0x40d816ba,
  104100. 0xaca5c697,0xa864db20,0xa527fdf9,0xa1e6e04e,
  104101. 0xbfa1b04b,0xbb60adfc,0xb6238b25,0xb2e29692,
  104102. 0x8aad2b2f,0x8e6c3698,0x832f1041,0x87ee0df6,
  104103. 0x99a95df3,0x9d684044,0x902b669d,0x94ea7b2a,
  104104. 0xe0b41de7,0xe4750050,0xe9362689,0xedf73b3e,
  104105. 0xf3b06b3b,0xf771768c,0xfa325055,0xfef34de2,
  104106. 0xc6bcf05f,0xc27dede8,0xcf3ecb31,0xcbffd686,
  104107. 0xd5b88683,0xd1799b34,0xdc3abded,0xd8fba05a,
  104108. 0x690ce0ee,0x6dcdfd59,0x608edb80,0x644fc637,
  104109. 0x7a089632,0x7ec98b85,0x738aad5c,0x774bb0eb,
  104110. 0x4f040d56,0x4bc510e1,0x46863638,0x42472b8f,
  104111. 0x5c007b8a,0x58c1663d,0x558240e4,0x51435d53,
  104112. 0x251d3b9e,0x21dc2629,0x2c9f00f0,0x285e1d47,
  104113. 0x36194d42,0x32d850f5,0x3f9b762c,0x3b5a6b9b,
  104114. 0x0315d626,0x07d4cb91,0x0a97ed48,0x0e56f0ff,
  104115. 0x1011a0fa,0x14d0bd4d,0x19939b94,0x1d528623,
  104116. 0xf12f560e,0xf5ee4bb9,0xf8ad6d60,0xfc6c70d7,
  104117. 0xe22b20d2,0xe6ea3d65,0xeba91bbc,0xef68060b,
  104118. 0xd727bbb6,0xd3e6a601,0xdea580d8,0xda649d6f,
  104119. 0xc423cd6a,0xc0e2d0dd,0xcda1f604,0xc960ebb3,
  104120. 0xbd3e8d7e,0xb9ff90c9,0xb4bcb610,0xb07daba7,
  104121. 0xae3afba2,0xaafbe615,0xa7b8c0cc,0xa379dd7b,
  104122. 0x9b3660c6,0x9ff77d71,0x92b45ba8,0x9675461f,
  104123. 0x8832161a,0x8cf30bad,0x81b02d74,0x857130c3,
  104124. 0x5d8a9099,0x594b8d2e,0x5408abf7,0x50c9b640,
  104125. 0x4e8ee645,0x4a4ffbf2,0x470cdd2b,0x43cdc09c,
  104126. 0x7b827d21,0x7f436096,0x7200464f,0x76c15bf8,
  104127. 0x68860bfd,0x6c47164a,0x61043093,0x65c52d24,
  104128. 0x119b4be9,0x155a565e,0x18197087,0x1cd86d30,
  104129. 0x029f3d35,0x065e2082,0x0b1d065b,0x0fdc1bec,
  104130. 0x3793a651,0x3352bbe6,0x3e119d3f,0x3ad08088,
  104131. 0x2497d08d,0x2056cd3a,0x2d15ebe3,0x29d4f654,
  104132. 0xc5a92679,0xc1683bce,0xcc2b1d17,0xc8ea00a0,
  104133. 0xd6ad50a5,0xd26c4d12,0xdf2f6bcb,0xdbee767c,
  104134. 0xe3a1cbc1,0xe760d676,0xea23f0af,0xeee2ed18,
  104135. 0xf0a5bd1d,0xf464a0aa,0xf9278673,0xfde69bc4,
  104136. 0x89b8fd09,0x8d79e0be,0x803ac667,0x84fbdbd0,
  104137. 0x9abc8bd5,0x9e7d9662,0x933eb0bb,0x97ffad0c,
  104138. 0xafb010b1,0xab710d06,0xa6322bdf,0xa2f33668,
  104139. 0xbcb4666d,0xb8757bda,0xb5365d03,0xb1f740b4};
  104140. /* init the encode/decode logical stream state */
  104141. int ogg_stream_init(ogg_stream_state *os,int serialno){
  104142. if(os){
  104143. memset(os,0,sizeof(*os));
  104144. os->body_storage=16*1024;
  104145. os->body_data=(unsigned char*) _ogg_malloc(os->body_storage*sizeof(*os->body_data));
  104146. os->lacing_storage=1024;
  104147. os->lacing_vals=(int*) _ogg_malloc(os->lacing_storage*sizeof(*os->lacing_vals));
  104148. os->granule_vals=(ogg_int64_t*) _ogg_malloc(os->lacing_storage*sizeof(*os->granule_vals));
  104149. os->serialno=serialno;
  104150. return(0);
  104151. }
  104152. return(-1);
  104153. }
  104154. /* _clear does not free os, only the non-flat storage within */
  104155. int ogg_stream_clear(ogg_stream_state *os){
  104156. if(os){
  104157. if(os->body_data)_ogg_free(os->body_data);
  104158. if(os->lacing_vals)_ogg_free(os->lacing_vals);
  104159. if(os->granule_vals)_ogg_free(os->granule_vals);
  104160. memset(os,0,sizeof(*os));
  104161. }
  104162. return(0);
  104163. }
  104164. int ogg_stream_destroy(ogg_stream_state *os){
  104165. if(os){
  104166. ogg_stream_clear(os);
  104167. _ogg_free(os);
  104168. }
  104169. return(0);
  104170. }
  104171. /* Helpers for ogg_stream_encode; this keeps the structure and
  104172. what's happening fairly clear */
  104173. static void _os_body_expand(ogg_stream_state *os,int needed){
  104174. if(os->body_storage<=os->body_fill+needed){
  104175. os->body_storage+=(needed+1024);
  104176. os->body_data=(unsigned char*) _ogg_realloc(os->body_data,os->body_storage*sizeof(*os->body_data));
  104177. }
  104178. }
  104179. static void _os_lacing_expand(ogg_stream_state *os,int needed){
  104180. if(os->lacing_storage<=os->lacing_fill+needed){
  104181. os->lacing_storage+=(needed+32);
  104182. os->lacing_vals=(int*)_ogg_realloc(os->lacing_vals,os->lacing_storage*sizeof(*os->lacing_vals));
  104183. os->granule_vals=(ogg_int64_t*)_ogg_realloc(os->granule_vals,os->lacing_storage*sizeof(*os->granule_vals));
  104184. }
  104185. }
  104186. /* checksum the page */
  104187. /* Direct table CRC; note that this will be faster in the future if we
  104188. perform the checksum silmultaneously with other copies */
  104189. void ogg_page_checksum_set(ogg_page *og){
  104190. if(og){
  104191. ogg_uint32_t crc_reg=0;
  104192. int i;
  104193. /* safety; needed for API behavior, but not framing code */
  104194. og->header[22]=0;
  104195. og->header[23]=0;
  104196. og->header[24]=0;
  104197. og->header[25]=0;
  104198. for(i=0;i<og->header_len;i++)
  104199. crc_reg=(crc_reg<<8)^crc_lookup[((crc_reg >> 24)&0xff)^og->header[i]];
  104200. for(i=0;i<og->body_len;i++)
  104201. crc_reg=(crc_reg<<8)^crc_lookup[((crc_reg >> 24)&0xff)^og->body[i]];
  104202. og->header[22]=(unsigned char)(crc_reg&0xff);
  104203. og->header[23]=(unsigned char)((crc_reg>>8)&0xff);
  104204. og->header[24]=(unsigned char)((crc_reg>>16)&0xff);
  104205. og->header[25]=(unsigned char)((crc_reg>>24)&0xff);
  104206. }
  104207. }
  104208. /* submit data to the internal buffer of the framing engine */
  104209. int ogg_stream_packetin(ogg_stream_state *os,ogg_packet *op){
  104210. int lacing_vals=op->bytes/255+1,i;
  104211. if(os->body_returned){
  104212. /* advance packet data according to the body_returned pointer. We
  104213. had to keep it around to return a pointer into the buffer last
  104214. call */
  104215. os->body_fill-=os->body_returned;
  104216. if(os->body_fill)
  104217. memmove(os->body_data,os->body_data+os->body_returned,
  104218. os->body_fill);
  104219. os->body_returned=0;
  104220. }
  104221. /* make sure we have the buffer storage */
  104222. _os_body_expand(os,op->bytes);
  104223. _os_lacing_expand(os,lacing_vals);
  104224. /* Copy in the submitted packet. Yes, the copy is a waste; this is
  104225. the liability of overly clean abstraction for the time being. It
  104226. will actually be fairly easy to eliminate the extra copy in the
  104227. future */
  104228. memcpy(os->body_data+os->body_fill,op->packet,op->bytes);
  104229. os->body_fill+=op->bytes;
  104230. /* Store lacing vals for this packet */
  104231. for(i=0;i<lacing_vals-1;i++){
  104232. os->lacing_vals[os->lacing_fill+i]=255;
  104233. os->granule_vals[os->lacing_fill+i]=os->granulepos;
  104234. }
  104235. os->lacing_vals[os->lacing_fill+i]=(op->bytes)%255;
  104236. os->granulepos=os->granule_vals[os->lacing_fill+i]=op->granulepos;
  104237. /* flag the first segment as the beginning of the packet */
  104238. os->lacing_vals[os->lacing_fill]|= 0x100;
  104239. os->lacing_fill+=lacing_vals;
  104240. /* for the sake of completeness */
  104241. os->packetno++;
  104242. if(op->e_o_s)os->e_o_s=1;
  104243. return(0);
  104244. }
  104245. /* This will flush remaining packets into a page (returning nonzero),
  104246. even if there is not enough data to trigger a flush normally
  104247. (undersized page). If there are no packets or partial packets to
  104248. flush, ogg_stream_flush returns 0. Note that ogg_stream_flush will
  104249. try to flush a normal sized page like ogg_stream_pageout; a call to
  104250. ogg_stream_flush does not guarantee that all packets have flushed.
  104251. Only a return value of 0 from ogg_stream_flush indicates all packet
  104252. data is flushed into pages.
  104253. since ogg_stream_flush will flush the last page in a stream even if
  104254. it's undersized, you almost certainly want to use ogg_stream_pageout
  104255. (and *not* ogg_stream_flush) unless you specifically need to flush
  104256. an page regardless of size in the middle of a stream. */
  104257. int ogg_stream_flush(ogg_stream_state *os,ogg_page *og){
  104258. int i;
  104259. int vals=0;
  104260. int maxvals=(os->lacing_fill>255?255:os->lacing_fill);
  104261. int bytes=0;
  104262. long acc=0;
  104263. ogg_int64_t granule_pos=-1;
  104264. if(maxvals==0)return(0);
  104265. /* construct a page */
  104266. /* decide how many segments to include */
  104267. /* If this is the initial header case, the first page must only include
  104268. the initial header packet */
  104269. if(os->b_o_s==0){ /* 'initial header page' case */
  104270. granule_pos=0;
  104271. for(vals=0;vals<maxvals;vals++){
  104272. if((os->lacing_vals[vals]&0x0ff)<255){
  104273. vals++;
  104274. break;
  104275. }
  104276. }
  104277. }else{
  104278. for(vals=0;vals<maxvals;vals++){
  104279. if(acc>4096)break;
  104280. acc+=os->lacing_vals[vals]&0x0ff;
  104281. if((os->lacing_vals[vals]&0xff)<255)
  104282. granule_pos=os->granule_vals[vals];
  104283. }
  104284. }
  104285. /* construct the header in temp storage */
  104286. memcpy(os->header,"OggS",4);
  104287. /* stream structure version */
  104288. os->header[4]=0x00;
  104289. /* continued packet flag? */
  104290. os->header[5]=0x00;
  104291. if((os->lacing_vals[0]&0x100)==0)os->header[5]|=0x01;
  104292. /* first page flag? */
  104293. if(os->b_o_s==0)os->header[5]|=0x02;
  104294. /* last page flag? */
  104295. if(os->e_o_s && os->lacing_fill==vals)os->header[5]|=0x04;
  104296. os->b_o_s=1;
  104297. /* 64 bits of PCM position */
  104298. for(i=6;i<14;i++){
  104299. os->header[i]=(unsigned char)(granule_pos&0xff);
  104300. granule_pos>>=8;
  104301. }
  104302. /* 32 bits of stream serial number */
  104303. {
  104304. long serialno=os->serialno;
  104305. for(i=14;i<18;i++){
  104306. os->header[i]=(unsigned char)(serialno&0xff);
  104307. serialno>>=8;
  104308. }
  104309. }
  104310. /* 32 bits of page counter (we have both counter and page header
  104311. because this val can roll over) */
  104312. if(os->pageno==-1)os->pageno=0; /* because someone called
  104313. stream_reset; this would be a
  104314. strange thing to do in an
  104315. encode stream, but it has
  104316. plausible uses */
  104317. {
  104318. long pageno=os->pageno++;
  104319. for(i=18;i<22;i++){
  104320. os->header[i]=(unsigned char)(pageno&0xff);
  104321. pageno>>=8;
  104322. }
  104323. }
  104324. /* zero for computation; filled in later */
  104325. os->header[22]=0;
  104326. os->header[23]=0;
  104327. os->header[24]=0;
  104328. os->header[25]=0;
  104329. /* segment table */
  104330. os->header[26]=(unsigned char)(vals&0xff);
  104331. for(i=0;i<vals;i++)
  104332. bytes+=os->header[i+27]=(unsigned char)(os->lacing_vals[i]&0xff);
  104333. /* set pointers in the ogg_page struct */
  104334. og->header=os->header;
  104335. og->header_len=os->header_fill=vals+27;
  104336. og->body=os->body_data+os->body_returned;
  104337. og->body_len=bytes;
  104338. /* advance the lacing data and set the body_returned pointer */
  104339. os->lacing_fill-=vals;
  104340. memmove(os->lacing_vals,os->lacing_vals+vals,os->lacing_fill*sizeof(*os->lacing_vals));
  104341. memmove(os->granule_vals,os->granule_vals+vals,os->lacing_fill*sizeof(*os->granule_vals));
  104342. os->body_returned+=bytes;
  104343. /* calculate the checksum */
  104344. ogg_page_checksum_set(og);
  104345. /* done */
  104346. return(1);
  104347. }
  104348. /* This constructs pages from buffered packet segments. The pointers
  104349. returned are to static buffers; do not free. The returned buffers are
  104350. good only until the next call (using the same ogg_stream_state) */
  104351. int ogg_stream_pageout(ogg_stream_state *os, ogg_page *og){
  104352. if((os->e_o_s&&os->lacing_fill) || /* 'were done, now flush' case */
  104353. os->body_fill-os->body_returned > 4096 ||/* 'page nominal size' case */
  104354. os->lacing_fill>=255 || /* 'segment table full' case */
  104355. (os->lacing_fill&&!os->b_o_s)){ /* 'initial header page' case */
  104356. return(ogg_stream_flush(os,og));
  104357. }
  104358. /* not enough data to construct a page and not end of stream */
  104359. return(0);
  104360. }
  104361. int ogg_stream_eos(ogg_stream_state *os){
  104362. return os->e_o_s;
  104363. }
  104364. /* DECODING PRIMITIVES: packet streaming layer **********************/
  104365. /* This has two layers to place more of the multi-serialno and paging
  104366. control in the application's hands. First, we expose a data buffer
  104367. using ogg_sync_buffer(). The app either copies into the
  104368. buffer, or passes it directly to read(), etc. We then call
  104369. ogg_sync_wrote() to tell how many bytes we just added.
  104370. Pages are returned (pointers into the buffer in ogg_sync_state)
  104371. by ogg_sync_pageout(). The page is then submitted to
  104372. ogg_stream_pagein() along with the appropriate
  104373. ogg_stream_state* (ie, matching serialno). We then get raw
  104374. packets out calling ogg_stream_packetout() with a
  104375. ogg_stream_state. */
  104376. /* initialize the struct to a known state */
  104377. int ogg_sync_init(ogg_sync_state *oy){
  104378. if(oy){
  104379. memset(oy,0,sizeof(*oy));
  104380. }
  104381. return(0);
  104382. }
  104383. /* clear non-flat storage within */
  104384. int ogg_sync_clear(ogg_sync_state *oy){
  104385. if(oy){
  104386. if(oy->data)_ogg_free(oy->data);
  104387. ogg_sync_init(oy);
  104388. }
  104389. return(0);
  104390. }
  104391. int ogg_sync_destroy(ogg_sync_state *oy){
  104392. if(oy){
  104393. ogg_sync_clear(oy);
  104394. _ogg_free(oy);
  104395. }
  104396. return(0);
  104397. }
  104398. char *ogg_sync_buffer(ogg_sync_state *oy, long size){
  104399. /* first, clear out any space that has been previously returned */
  104400. if(oy->returned){
  104401. oy->fill-=oy->returned;
  104402. if(oy->fill>0)
  104403. memmove(oy->data,oy->data+oy->returned,oy->fill);
  104404. oy->returned=0;
  104405. }
  104406. if(size>oy->storage-oy->fill){
  104407. /* We need to extend the internal buffer */
  104408. long newsize=size+oy->fill+4096; /* an extra page to be nice */
  104409. if(oy->data)
  104410. oy->data=(unsigned char*) _ogg_realloc(oy->data,newsize);
  104411. else
  104412. oy->data=(unsigned char*) _ogg_malloc(newsize);
  104413. oy->storage=newsize;
  104414. }
  104415. /* expose a segment at least as large as requested at the fill mark */
  104416. return((char *)oy->data+oy->fill);
  104417. }
  104418. int ogg_sync_wrote(ogg_sync_state *oy, long bytes){
  104419. if(oy->fill+bytes>oy->storage)return(-1);
  104420. oy->fill+=bytes;
  104421. return(0);
  104422. }
  104423. /* sync the stream. This is meant to be useful for finding page
  104424. boundaries.
  104425. return values for this:
  104426. -n) skipped n bytes
  104427. 0) page not ready; more data (no bytes skipped)
  104428. n) page synced at current location; page length n bytes
  104429. */
  104430. long ogg_sync_pageseek(ogg_sync_state *oy,ogg_page *og){
  104431. unsigned char *page=oy->data+oy->returned;
  104432. unsigned char *next;
  104433. long bytes=oy->fill-oy->returned;
  104434. if(oy->headerbytes==0){
  104435. int headerbytes,i;
  104436. if(bytes<27)return(0); /* not enough for a header */
  104437. /* verify capture pattern */
  104438. if(memcmp(page,"OggS",4))goto sync_fail;
  104439. headerbytes=page[26]+27;
  104440. if(bytes<headerbytes)return(0); /* not enough for header + seg table */
  104441. /* count up body length in the segment table */
  104442. for(i=0;i<page[26];i++)
  104443. oy->bodybytes+=page[27+i];
  104444. oy->headerbytes=headerbytes;
  104445. }
  104446. if(oy->bodybytes+oy->headerbytes>bytes)return(0);
  104447. /* The whole test page is buffered. Verify the checksum */
  104448. {
  104449. /* Grab the checksum bytes, set the header field to zero */
  104450. char chksum[4];
  104451. ogg_page log;
  104452. memcpy(chksum,page+22,4);
  104453. memset(page+22,0,4);
  104454. /* set up a temp page struct and recompute the checksum */
  104455. log.header=page;
  104456. log.header_len=oy->headerbytes;
  104457. log.body=page+oy->headerbytes;
  104458. log.body_len=oy->bodybytes;
  104459. ogg_page_checksum_set(&log);
  104460. /* Compare */
  104461. if(memcmp(chksum,page+22,4)){
  104462. /* D'oh. Mismatch! Corrupt page (or miscapture and not a page
  104463. at all) */
  104464. /* replace the computed checksum with the one actually read in */
  104465. memcpy(page+22,chksum,4);
  104466. /* Bad checksum. Lose sync */
  104467. goto sync_fail;
  104468. }
  104469. }
  104470. /* yes, have a whole page all ready to go */
  104471. {
  104472. unsigned char *page=oy->data+oy->returned;
  104473. long bytes;
  104474. if(og){
  104475. og->header=page;
  104476. og->header_len=oy->headerbytes;
  104477. og->body=page+oy->headerbytes;
  104478. og->body_len=oy->bodybytes;
  104479. }
  104480. oy->unsynced=0;
  104481. oy->returned+=(bytes=oy->headerbytes+oy->bodybytes);
  104482. oy->headerbytes=0;
  104483. oy->bodybytes=0;
  104484. return(bytes);
  104485. }
  104486. sync_fail:
  104487. oy->headerbytes=0;
  104488. oy->bodybytes=0;
  104489. /* search for possible capture */
  104490. next=(unsigned char*)memchr(page+1,'O',bytes-1);
  104491. if(!next)
  104492. next=oy->data+oy->fill;
  104493. oy->returned=next-oy->data;
  104494. return(-(next-page));
  104495. }
  104496. /* sync the stream and get a page. Keep trying until we find a page.
  104497. Supress 'sync errors' after reporting the first.
  104498. return values:
  104499. -1) recapture (hole in data)
  104500. 0) need more data
  104501. 1) page returned
  104502. Returns pointers into buffered data; invalidated by next call to
  104503. _stream, _clear, _init, or _buffer */
  104504. int ogg_sync_pageout(ogg_sync_state *oy, ogg_page *og){
  104505. /* all we need to do is verify a page at the head of the stream
  104506. buffer. If it doesn't verify, we look for the next potential
  104507. frame */
  104508. for(;;){
  104509. long ret=ogg_sync_pageseek(oy,og);
  104510. if(ret>0){
  104511. /* have a page */
  104512. return(1);
  104513. }
  104514. if(ret==0){
  104515. /* need more data */
  104516. return(0);
  104517. }
  104518. /* head did not start a synced page... skipped some bytes */
  104519. if(!oy->unsynced){
  104520. oy->unsynced=1;
  104521. return(-1);
  104522. }
  104523. /* loop. keep looking */
  104524. }
  104525. }
  104526. /* add the incoming page to the stream state; we decompose the page
  104527. into packet segments here as well. */
  104528. int ogg_stream_pagein(ogg_stream_state *os, ogg_page *og){
  104529. unsigned char *header=og->header;
  104530. unsigned char *body=og->body;
  104531. long bodysize=og->body_len;
  104532. int segptr=0;
  104533. int version=ogg_page_version(og);
  104534. int continued=ogg_page_continued(og);
  104535. int bos=ogg_page_bos(og);
  104536. int eos=ogg_page_eos(og);
  104537. ogg_int64_t granulepos=ogg_page_granulepos(og);
  104538. int serialno=ogg_page_serialno(og);
  104539. long pageno=ogg_page_pageno(og);
  104540. int segments=header[26];
  104541. /* clean up 'returned data' */
  104542. {
  104543. long lr=os->lacing_returned;
  104544. long br=os->body_returned;
  104545. /* body data */
  104546. if(br){
  104547. os->body_fill-=br;
  104548. if(os->body_fill)
  104549. memmove(os->body_data,os->body_data+br,os->body_fill);
  104550. os->body_returned=0;
  104551. }
  104552. if(lr){
  104553. /* segment table */
  104554. if(os->lacing_fill-lr){
  104555. memmove(os->lacing_vals,os->lacing_vals+lr,
  104556. (os->lacing_fill-lr)*sizeof(*os->lacing_vals));
  104557. memmove(os->granule_vals,os->granule_vals+lr,
  104558. (os->lacing_fill-lr)*sizeof(*os->granule_vals));
  104559. }
  104560. os->lacing_fill-=lr;
  104561. os->lacing_packet-=lr;
  104562. os->lacing_returned=0;
  104563. }
  104564. }
  104565. /* check the serial number */
  104566. if(serialno!=os->serialno)return(-1);
  104567. if(version>0)return(-1);
  104568. _os_lacing_expand(os,segments+1);
  104569. /* are we in sequence? */
  104570. if(pageno!=os->pageno){
  104571. int i;
  104572. /* unroll previous partial packet (if any) */
  104573. for(i=os->lacing_packet;i<os->lacing_fill;i++)
  104574. os->body_fill-=os->lacing_vals[i]&0xff;
  104575. os->lacing_fill=os->lacing_packet;
  104576. /* make a note of dropped data in segment table */
  104577. if(os->pageno!=-1){
  104578. os->lacing_vals[os->lacing_fill++]=0x400;
  104579. os->lacing_packet++;
  104580. }
  104581. }
  104582. /* are we a 'continued packet' page? If so, we may need to skip
  104583. some segments */
  104584. if(continued){
  104585. if(os->lacing_fill<1 ||
  104586. os->lacing_vals[os->lacing_fill-1]==0x400){
  104587. bos=0;
  104588. for(;segptr<segments;segptr++){
  104589. int val=header[27+segptr];
  104590. body+=val;
  104591. bodysize-=val;
  104592. if(val<255){
  104593. segptr++;
  104594. break;
  104595. }
  104596. }
  104597. }
  104598. }
  104599. if(bodysize){
  104600. _os_body_expand(os,bodysize);
  104601. memcpy(os->body_data+os->body_fill,body,bodysize);
  104602. os->body_fill+=bodysize;
  104603. }
  104604. {
  104605. int saved=-1;
  104606. while(segptr<segments){
  104607. int val=header[27+segptr];
  104608. os->lacing_vals[os->lacing_fill]=val;
  104609. os->granule_vals[os->lacing_fill]=-1;
  104610. if(bos){
  104611. os->lacing_vals[os->lacing_fill]|=0x100;
  104612. bos=0;
  104613. }
  104614. if(val<255)saved=os->lacing_fill;
  104615. os->lacing_fill++;
  104616. segptr++;
  104617. if(val<255)os->lacing_packet=os->lacing_fill;
  104618. }
  104619. /* set the granulepos on the last granuleval of the last full packet */
  104620. if(saved!=-1){
  104621. os->granule_vals[saved]=granulepos;
  104622. }
  104623. }
  104624. if(eos){
  104625. os->e_o_s=1;
  104626. if(os->lacing_fill>0)
  104627. os->lacing_vals[os->lacing_fill-1]|=0x200;
  104628. }
  104629. os->pageno=pageno+1;
  104630. return(0);
  104631. }
  104632. /* clear things to an initial state. Good to call, eg, before seeking */
  104633. int ogg_sync_reset(ogg_sync_state *oy){
  104634. oy->fill=0;
  104635. oy->returned=0;
  104636. oy->unsynced=0;
  104637. oy->headerbytes=0;
  104638. oy->bodybytes=0;
  104639. return(0);
  104640. }
  104641. int ogg_stream_reset(ogg_stream_state *os){
  104642. os->body_fill=0;
  104643. os->body_returned=0;
  104644. os->lacing_fill=0;
  104645. os->lacing_packet=0;
  104646. os->lacing_returned=0;
  104647. os->header_fill=0;
  104648. os->e_o_s=0;
  104649. os->b_o_s=0;
  104650. os->pageno=-1;
  104651. os->packetno=0;
  104652. os->granulepos=0;
  104653. return(0);
  104654. }
  104655. int ogg_stream_reset_serialno(ogg_stream_state *os,int serialno){
  104656. ogg_stream_reset(os);
  104657. os->serialno=serialno;
  104658. return(0);
  104659. }
  104660. static int _packetout(ogg_stream_state *os,ogg_packet *op,int adv){
  104661. /* The last part of decode. We have the stream broken into packet
  104662. segments. Now we need to group them into packets (or return the
  104663. out of sync markers) */
  104664. int ptr=os->lacing_returned;
  104665. if(os->lacing_packet<=ptr)return(0);
  104666. if(os->lacing_vals[ptr]&0x400){
  104667. /* we need to tell the codec there's a gap; it might need to
  104668. handle previous packet dependencies. */
  104669. os->lacing_returned++;
  104670. os->packetno++;
  104671. return(-1);
  104672. }
  104673. if(!op && !adv)return(1); /* just using peek as an inexpensive way
  104674. to ask if there's a whole packet
  104675. waiting */
  104676. /* Gather the whole packet. We'll have no holes or a partial packet */
  104677. {
  104678. int size=os->lacing_vals[ptr]&0xff;
  104679. int bytes=size;
  104680. int eos=os->lacing_vals[ptr]&0x200; /* last packet of the stream? */
  104681. int bos=os->lacing_vals[ptr]&0x100; /* first packet of the stream? */
  104682. while(size==255){
  104683. int val=os->lacing_vals[++ptr];
  104684. size=val&0xff;
  104685. if(val&0x200)eos=0x200;
  104686. bytes+=size;
  104687. }
  104688. if(op){
  104689. op->e_o_s=eos;
  104690. op->b_o_s=bos;
  104691. op->packet=os->body_data+os->body_returned;
  104692. op->packetno=os->packetno;
  104693. op->granulepos=os->granule_vals[ptr];
  104694. op->bytes=bytes;
  104695. }
  104696. if(adv){
  104697. os->body_returned+=bytes;
  104698. os->lacing_returned=ptr+1;
  104699. os->packetno++;
  104700. }
  104701. }
  104702. return(1);
  104703. }
  104704. int ogg_stream_packetout(ogg_stream_state *os,ogg_packet *op){
  104705. return _packetout(os,op,1);
  104706. }
  104707. int ogg_stream_packetpeek(ogg_stream_state *os,ogg_packet *op){
  104708. return _packetout(os,op,0);
  104709. }
  104710. void ogg_packet_clear(ogg_packet *op) {
  104711. _ogg_free(op->packet);
  104712. memset(op, 0, sizeof(*op));
  104713. }
  104714. #ifdef _V_SELFTEST
  104715. #include <stdio.h>
  104716. ogg_stream_state os_en, os_de;
  104717. ogg_sync_state oy;
  104718. void checkpacket(ogg_packet *op,int len, int no, int pos){
  104719. long j;
  104720. static int sequence=0;
  104721. static int lastno=0;
  104722. if(op->bytes!=len){
  104723. fprintf(stderr,"incorrect packet length!\n");
  104724. exit(1);
  104725. }
  104726. if(op->granulepos!=pos){
  104727. fprintf(stderr,"incorrect packet position!\n");
  104728. exit(1);
  104729. }
  104730. /* packet number just follows sequence/gap; adjust the input number
  104731. for that */
  104732. if(no==0){
  104733. sequence=0;
  104734. }else{
  104735. sequence++;
  104736. if(no>lastno+1)
  104737. sequence++;
  104738. }
  104739. lastno=no;
  104740. if(op->packetno!=sequence){
  104741. fprintf(stderr,"incorrect packet sequence %ld != %d\n",
  104742. (long)(op->packetno),sequence);
  104743. exit(1);
  104744. }
  104745. /* Test data */
  104746. for(j=0;j<op->bytes;j++)
  104747. if(op->packet[j]!=((j+no)&0xff)){
  104748. fprintf(stderr,"body data mismatch (1) at pos %ld: %x!=%lx!\n\n",
  104749. j,op->packet[j],(j+no)&0xff);
  104750. exit(1);
  104751. }
  104752. }
  104753. void check_page(unsigned char *data,const int *header,ogg_page *og){
  104754. long j;
  104755. /* Test data */
  104756. for(j=0;j<og->body_len;j++)
  104757. if(og->body[j]!=data[j]){
  104758. fprintf(stderr,"body data mismatch (2) at pos %ld: %x!=%x!\n\n",
  104759. j,data[j],og->body[j]);
  104760. exit(1);
  104761. }
  104762. /* Test header */
  104763. for(j=0;j<og->header_len;j++){
  104764. if(og->header[j]!=header[j]){
  104765. fprintf(stderr,"header content mismatch at pos %ld:\n",j);
  104766. for(j=0;j<header[26]+27;j++)
  104767. fprintf(stderr," (%ld)%02x:%02x",j,header[j],og->header[j]);
  104768. fprintf(stderr,"\n");
  104769. exit(1);
  104770. }
  104771. }
  104772. if(og->header_len!=header[26]+27){
  104773. fprintf(stderr,"header length incorrect! (%ld!=%d)\n",
  104774. og->header_len,header[26]+27);
  104775. exit(1);
  104776. }
  104777. }
  104778. void print_header(ogg_page *og){
  104779. int j;
  104780. fprintf(stderr,"\nHEADER:\n");
  104781. fprintf(stderr," capture: %c %c %c %c version: %d flags: %x\n",
  104782. og->header[0],og->header[1],og->header[2],og->header[3],
  104783. (int)og->header[4],(int)og->header[5]);
  104784. fprintf(stderr," granulepos: %d serialno: %d pageno: %ld\n",
  104785. (og->header[9]<<24)|(og->header[8]<<16)|
  104786. (og->header[7]<<8)|og->header[6],
  104787. (og->header[17]<<24)|(og->header[16]<<16)|
  104788. (og->header[15]<<8)|og->header[14],
  104789. ((long)(og->header[21])<<24)|(og->header[20]<<16)|
  104790. (og->header[19]<<8)|og->header[18]);
  104791. fprintf(stderr," checksum: %02x:%02x:%02x:%02x\n segments: %d (",
  104792. (int)og->header[22],(int)og->header[23],
  104793. (int)og->header[24],(int)og->header[25],
  104794. (int)og->header[26]);
  104795. for(j=27;j<og->header_len;j++)
  104796. fprintf(stderr,"%d ",(int)og->header[j]);
  104797. fprintf(stderr,")\n\n");
  104798. }
  104799. void copy_page(ogg_page *og){
  104800. unsigned char *temp=_ogg_malloc(og->header_len);
  104801. memcpy(temp,og->header,og->header_len);
  104802. og->header=temp;
  104803. temp=_ogg_malloc(og->body_len);
  104804. memcpy(temp,og->body,og->body_len);
  104805. og->body=temp;
  104806. }
  104807. void free_page(ogg_page *og){
  104808. _ogg_free (og->header);
  104809. _ogg_free (og->body);
  104810. }
  104811. void error(void){
  104812. fprintf(stderr,"error!\n");
  104813. exit(1);
  104814. }
  104815. /* 17 only */
  104816. const int head1_0[] = {0x4f,0x67,0x67,0x53,0,0x06,
  104817. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  104818. 0x01,0x02,0x03,0x04,0,0,0,0,
  104819. 0x15,0xed,0xec,0x91,
  104820. 1,
  104821. 17};
  104822. /* 17, 254, 255, 256, 500, 510, 600 byte, pad */
  104823. const int head1_1[] = {0x4f,0x67,0x67,0x53,0,0x02,
  104824. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  104825. 0x01,0x02,0x03,0x04,0,0,0,0,
  104826. 0x59,0x10,0x6c,0x2c,
  104827. 1,
  104828. 17};
  104829. const int head2_1[] = {0x4f,0x67,0x67,0x53,0,0x04,
  104830. 0x07,0x18,0x00,0x00,0x00,0x00,0x00,0x00,
  104831. 0x01,0x02,0x03,0x04,1,0,0,0,
  104832. 0x89,0x33,0x85,0xce,
  104833. 13,
  104834. 254,255,0,255,1,255,245,255,255,0,
  104835. 255,255,90};
  104836. /* nil packets; beginning,middle,end */
  104837. const int head1_2[] = {0x4f,0x67,0x67,0x53,0,0x02,
  104838. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  104839. 0x01,0x02,0x03,0x04,0,0,0,0,
  104840. 0xff,0x7b,0x23,0x17,
  104841. 1,
  104842. 0};
  104843. const int head2_2[] = {0x4f,0x67,0x67,0x53,0,0x04,
  104844. 0x07,0x28,0x00,0x00,0x00,0x00,0x00,0x00,
  104845. 0x01,0x02,0x03,0x04,1,0,0,0,
  104846. 0x5c,0x3f,0x66,0xcb,
  104847. 17,
  104848. 17,254,255,0,0,255,1,0,255,245,255,255,0,
  104849. 255,255,90,0};
  104850. /* large initial packet */
  104851. const int head1_3[] = {0x4f,0x67,0x67,0x53,0,0x02,
  104852. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  104853. 0x01,0x02,0x03,0x04,0,0,0,0,
  104854. 0x01,0x27,0x31,0xaa,
  104855. 18,
  104856. 255,255,255,255,255,255,255,255,
  104857. 255,255,255,255,255,255,255,255,255,10};
  104858. const int head2_3[] = {0x4f,0x67,0x67,0x53,0,0x04,
  104859. 0x07,0x08,0x00,0x00,0x00,0x00,0x00,0x00,
  104860. 0x01,0x02,0x03,0x04,1,0,0,0,
  104861. 0x7f,0x4e,0x8a,0xd2,
  104862. 4,
  104863. 255,4,255,0};
  104864. /* continuing packet test */
  104865. const int head1_4[] = {0x4f,0x67,0x67,0x53,0,0x02,
  104866. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  104867. 0x01,0x02,0x03,0x04,0,0,0,0,
  104868. 0xff,0x7b,0x23,0x17,
  104869. 1,
  104870. 0};
  104871. const int head2_4[] = {0x4f,0x67,0x67,0x53,0,0x00,
  104872. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  104873. 0x01,0x02,0x03,0x04,1,0,0,0,
  104874. 0x54,0x05,0x51,0xc8,
  104875. 17,
  104876. 255,255,255,255,255,255,255,255,
  104877. 255,255,255,255,255,255,255,255,255};
  104878. const int head3_4[] = {0x4f,0x67,0x67,0x53,0,0x05,
  104879. 0x07,0x0c,0x00,0x00,0x00,0x00,0x00,0x00,
  104880. 0x01,0x02,0x03,0x04,2,0,0,0,
  104881. 0xc8,0xc3,0xcb,0xed,
  104882. 5,
  104883. 10,255,4,255,0};
  104884. /* page with the 255 segment limit */
  104885. const int head1_5[] = {0x4f,0x67,0x67,0x53,0,0x02,
  104886. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  104887. 0x01,0x02,0x03,0x04,0,0,0,0,
  104888. 0xff,0x7b,0x23,0x17,
  104889. 1,
  104890. 0};
  104891. const int head2_5[] = {0x4f,0x67,0x67,0x53,0,0x00,
  104892. 0x07,0xfc,0x03,0x00,0x00,0x00,0x00,0x00,
  104893. 0x01,0x02,0x03,0x04,1,0,0,0,
  104894. 0xed,0x2a,0x2e,0xa7,
  104895. 255,
  104896. 10,10,10,10,10,10,10,10,
  104897. 10,10,10,10,10,10,10,10,
  104898. 10,10,10,10,10,10,10,10,
  104899. 10,10,10,10,10,10,10,10,
  104900. 10,10,10,10,10,10,10,10,
  104901. 10,10,10,10,10,10,10,10,
  104902. 10,10,10,10,10,10,10,10,
  104903. 10,10,10,10,10,10,10,10,
  104904. 10,10,10,10,10,10,10,10,
  104905. 10,10,10,10,10,10,10,10,
  104906. 10,10,10,10,10,10,10,10,
  104907. 10,10,10,10,10,10,10,10,
  104908. 10,10,10,10,10,10,10,10,
  104909. 10,10,10,10,10,10,10,10,
  104910. 10,10,10,10,10,10,10,10,
  104911. 10,10,10,10,10,10,10,10,
  104912. 10,10,10,10,10,10,10,10,
  104913. 10,10,10,10,10,10,10,10,
  104914. 10,10,10,10,10,10,10,10,
  104915. 10,10,10,10,10,10,10,10,
  104916. 10,10,10,10,10,10,10,10,
  104917. 10,10,10,10,10,10,10,10,
  104918. 10,10,10,10,10,10,10,10,
  104919. 10,10,10,10,10,10,10,10,
  104920. 10,10,10,10,10,10,10,10,
  104921. 10,10,10,10,10,10,10,10,
  104922. 10,10,10,10,10,10,10,10,
  104923. 10,10,10,10,10,10,10,10,
  104924. 10,10,10,10,10,10,10,10,
  104925. 10,10,10,10,10,10,10,10,
  104926. 10,10,10,10,10,10,10,10,
  104927. 10,10,10,10,10,10,10};
  104928. const int head3_5[] = {0x4f,0x67,0x67,0x53,0,0x04,
  104929. 0x07,0x00,0x04,0x00,0x00,0x00,0x00,0x00,
  104930. 0x01,0x02,0x03,0x04,2,0,0,0,
  104931. 0x6c,0x3b,0x82,0x3d,
  104932. 1,
  104933. 50};
  104934. /* packet that overspans over an entire page */
  104935. const int head1_6[] = {0x4f,0x67,0x67,0x53,0,0x02,
  104936. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  104937. 0x01,0x02,0x03,0x04,0,0,0,0,
  104938. 0xff,0x7b,0x23,0x17,
  104939. 1,
  104940. 0};
  104941. const int head2_6[] = {0x4f,0x67,0x67,0x53,0,0x00,
  104942. 0x07,0x04,0x00,0x00,0x00,0x00,0x00,0x00,
  104943. 0x01,0x02,0x03,0x04,1,0,0,0,
  104944. 0x3c,0xd9,0x4d,0x3f,
  104945. 17,
  104946. 100,255,255,255,255,255,255,255,255,
  104947. 255,255,255,255,255,255,255,255};
  104948. const int head3_6[] = {0x4f,0x67,0x67,0x53,0,0x01,
  104949. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  104950. 0x01,0x02,0x03,0x04,2,0,0,0,
  104951. 0x01,0xd2,0xe5,0xe5,
  104952. 17,
  104953. 255,255,255,255,255,255,255,255,
  104954. 255,255,255,255,255,255,255,255,255};
  104955. const int head4_6[] = {0x4f,0x67,0x67,0x53,0,0x05,
  104956. 0x07,0x10,0x00,0x00,0x00,0x00,0x00,0x00,
  104957. 0x01,0x02,0x03,0x04,3,0,0,0,
  104958. 0xef,0xdd,0x88,0xde,
  104959. 7,
  104960. 255,255,75,255,4,255,0};
  104961. /* packet that overspans over an entire page */
  104962. const int head1_7[] = {0x4f,0x67,0x67,0x53,0,0x02,
  104963. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  104964. 0x01,0x02,0x03,0x04,0,0,0,0,
  104965. 0xff,0x7b,0x23,0x17,
  104966. 1,
  104967. 0};
  104968. const int head2_7[] = {0x4f,0x67,0x67,0x53,0,0x00,
  104969. 0x07,0x04,0x00,0x00,0x00,0x00,0x00,0x00,
  104970. 0x01,0x02,0x03,0x04,1,0,0,0,
  104971. 0x3c,0xd9,0x4d,0x3f,
  104972. 17,
  104973. 100,255,255,255,255,255,255,255,255,
  104974. 255,255,255,255,255,255,255,255};
  104975. const int head3_7[] = {0x4f,0x67,0x67,0x53,0,0x05,
  104976. 0x07,0x08,0x00,0x00,0x00,0x00,0x00,0x00,
  104977. 0x01,0x02,0x03,0x04,2,0,0,0,
  104978. 0xd4,0xe0,0x60,0xe5,
  104979. 1,0};
  104980. void test_pack(const int *pl, const int **headers, int byteskip,
  104981. int pageskip, int packetskip){
  104982. unsigned char *data=_ogg_malloc(1024*1024); /* for scripted test cases only */
  104983. long inptr=0;
  104984. long outptr=0;
  104985. long deptr=0;
  104986. long depacket=0;
  104987. long granule_pos=7,pageno=0;
  104988. int i,j,packets,pageout=pageskip;
  104989. int eosflag=0;
  104990. int bosflag=0;
  104991. int byteskipcount=0;
  104992. ogg_stream_reset(&os_en);
  104993. ogg_stream_reset(&os_de);
  104994. ogg_sync_reset(&oy);
  104995. for(packets=0;packets<packetskip;packets++)
  104996. depacket+=pl[packets];
  104997. for(packets=0;;packets++)if(pl[packets]==-1)break;
  104998. for(i=0;i<packets;i++){
  104999. /* construct a test packet */
  105000. ogg_packet op;
  105001. int len=pl[i];
  105002. op.packet=data+inptr;
  105003. op.bytes=len;
  105004. op.e_o_s=(pl[i+1]<0?1:0);
  105005. op.granulepos=granule_pos;
  105006. granule_pos+=1024;
  105007. for(j=0;j<len;j++)data[inptr++]=i+j;
  105008. /* submit the test packet */
  105009. ogg_stream_packetin(&os_en,&op);
  105010. /* retrieve any finished pages */
  105011. {
  105012. ogg_page og;
  105013. while(ogg_stream_pageout(&os_en,&og)){
  105014. /* We have a page. Check it carefully */
  105015. fprintf(stderr,"%ld, ",pageno);
  105016. if(headers[pageno]==NULL){
  105017. fprintf(stderr,"coded too many pages!\n");
  105018. exit(1);
  105019. }
  105020. check_page(data+outptr,headers[pageno],&og);
  105021. outptr+=og.body_len;
  105022. pageno++;
  105023. if(pageskip){
  105024. bosflag=1;
  105025. pageskip--;
  105026. deptr+=og.body_len;
  105027. }
  105028. /* have a complete page; submit it to sync/decode */
  105029. {
  105030. ogg_page og_de;
  105031. ogg_packet op_de,op_de2;
  105032. char *buf=ogg_sync_buffer(&oy,og.header_len+og.body_len);
  105033. char *next=buf;
  105034. byteskipcount+=og.header_len;
  105035. if(byteskipcount>byteskip){
  105036. memcpy(next,og.header,byteskipcount-byteskip);
  105037. next+=byteskipcount-byteskip;
  105038. byteskipcount=byteskip;
  105039. }
  105040. byteskipcount+=og.body_len;
  105041. if(byteskipcount>byteskip){
  105042. memcpy(next,og.body,byteskipcount-byteskip);
  105043. next+=byteskipcount-byteskip;
  105044. byteskipcount=byteskip;
  105045. }
  105046. ogg_sync_wrote(&oy,next-buf);
  105047. while(1){
  105048. int ret=ogg_sync_pageout(&oy,&og_de);
  105049. if(ret==0)break;
  105050. if(ret<0)continue;
  105051. /* got a page. Happy happy. Verify that it's good. */
  105052. fprintf(stderr,"(%ld), ",pageout);
  105053. check_page(data+deptr,headers[pageout],&og_de);
  105054. deptr+=og_de.body_len;
  105055. pageout++;
  105056. /* submit it to deconstitution */
  105057. ogg_stream_pagein(&os_de,&og_de);
  105058. /* packets out? */
  105059. while(ogg_stream_packetpeek(&os_de,&op_de2)>0){
  105060. ogg_stream_packetpeek(&os_de,NULL);
  105061. ogg_stream_packetout(&os_de,&op_de); /* just catching them all */
  105062. /* verify peek and out match */
  105063. if(memcmp(&op_de,&op_de2,sizeof(op_de))){
  105064. fprintf(stderr,"packetout != packetpeek! pos=%ld\n",
  105065. depacket);
  105066. exit(1);
  105067. }
  105068. /* verify the packet! */
  105069. /* check data */
  105070. if(memcmp(data+depacket,op_de.packet,op_de.bytes)){
  105071. fprintf(stderr,"packet data mismatch in decode! pos=%ld\n",
  105072. depacket);
  105073. exit(1);
  105074. }
  105075. /* check bos flag */
  105076. if(bosflag==0 && op_de.b_o_s==0){
  105077. fprintf(stderr,"b_o_s flag not set on packet!\n");
  105078. exit(1);
  105079. }
  105080. if(bosflag && op_de.b_o_s){
  105081. fprintf(stderr,"b_o_s flag incorrectly set on packet!\n");
  105082. exit(1);
  105083. }
  105084. bosflag=1;
  105085. depacket+=op_de.bytes;
  105086. /* check eos flag */
  105087. if(eosflag){
  105088. fprintf(stderr,"Multiple decoded packets with eos flag!\n");
  105089. exit(1);
  105090. }
  105091. if(op_de.e_o_s)eosflag=1;
  105092. /* check granulepos flag */
  105093. if(op_de.granulepos!=-1){
  105094. fprintf(stderr," granule:%ld ",(long)op_de.granulepos);
  105095. }
  105096. }
  105097. }
  105098. }
  105099. }
  105100. }
  105101. }
  105102. _ogg_free(data);
  105103. if(headers[pageno]!=NULL){
  105104. fprintf(stderr,"did not write last page!\n");
  105105. exit(1);
  105106. }
  105107. if(headers[pageout]!=NULL){
  105108. fprintf(stderr,"did not decode last page!\n");
  105109. exit(1);
  105110. }
  105111. if(inptr!=outptr){
  105112. fprintf(stderr,"encoded page data incomplete!\n");
  105113. exit(1);
  105114. }
  105115. if(inptr!=deptr){
  105116. fprintf(stderr,"decoded page data incomplete!\n");
  105117. exit(1);
  105118. }
  105119. if(inptr!=depacket){
  105120. fprintf(stderr,"decoded packet data incomplete!\n");
  105121. exit(1);
  105122. }
  105123. if(!eosflag){
  105124. fprintf(stderr,"Never got a packet with EOS set!\n");
  105125. exit(1);
  105126. }
  105127. fprintf(stderr,"ok.\n");
  105128. }
  105129. int main(void){
  105130. ogg_stream_init(&os_en,0x04030201);
  105131. ogg_stream_init(&os_de,0x04030201);
  105132. ogg_sync_init(&oy);
  105133. /* Exercise each code path in the framing code. Also verify that
  105134. the checksums are working. */
  105135. {
  105136. /* 17 only */
  105137. const int packets[]={17, -1};
  105138. const int *headret[]={head1_0,NULL};
  105139. fprintf(stderr,"testing single page encoding... ");
  105140. test_pack(packets,headret,0,0,0);
  105141. }
  105142. {
  105143. /* 17, 254, 255, 256, 500, 510, 600 byte, pad */
  105144. const int packets[]={17, 254, 255, 256, 500, 510, 600, -1};
  105145. const int *headret[]={head1_1,head2_1,NULL};
  105146. fprintf(stderr,"testing basic page encoding... ");
  105147. test_pack(packets,headret,0,0,0);
  105148. }
  105149. {
  105150. /* nil packets; beginning,middle,end */
  105151. const int packets[]={0,17, 254, 255, 0, 256, 0, 500, 510, 600, 0, -1};
  105152. const int *headret[]={head1_2,head2_2,NULL};
  105153. fprintf(stderr,"testing basic nil packets... ");
  105154. test_pack(packets,headret,0,0,0);
  105155. }
  105156. {
  105157. /* large initial packet */
  105158. const int packets[]={4345,259,255,-1};
  105159. const int *headret[]={head1_3,head2_3,NULL};
  105160. fprintf(stderr,"testing initial-packet lacing > 4k... ");
  105161. test_pack(packets,headret,0,0,0);
  105162. }
  105163. {
  105164. /* continuing packet test */
  105165. const int packets[]={0,4345,259,255,-1};
  105166. const int *headret[]={head1_4,head2_4,head3_4,NULL};
  105167. fprintf(stderr,"testing single packet page span... ");
  105168. test_pack(packets,headret,0,0,0);
  105169. }
  105170. /* page with the 255 segment limit */
  105171. {
  105172. const int packets[]={0,10,10,10,10,10,10,10,10,
  105173. 10,10,10,10,10,10,10,10,
  105174. 10,10,10,10,10,10,10,10,
  105175. 10,10,10,10,10,10,10,10,
  105176. 10,10,10,10,10,10,10,10,
  105177. 10,10,10,10,10,10,10,10,
  105178. 10,10,10,10,10,10,10,10,
  105179. 10,10,10,10,10,10,10,10,
  105180. 10,10,10,10,10,10,10,10,
  105181. 10,10,10,10,10,10,10,10,
  105182. 10,10,10,10,10,10,10,10,
  105183. 10,10,10,10,10,10,10,10,
  105184. 10,10,10,10,10,10,10,10,
  105185. 10,10,10,10,10,10,10,10,
  105186. 10,10,10,10,10,10,10,10,
  105187. 10,10,10,10,10,10,10,10,
  105188. 10,10,10,10,10,10,10,10,
  105189. 10,10,10,10,10,10,10,10,
  105190. 10,10,10,10,10,10,10,10,
  105191. 10,10,10,10,10,10,10,10,
  105192. 10,10,10,10,10,10,10,10,
  105193. 10,10,10,10,10,10,10,10,
  105194. 10,10,10,10,10,10,10,10,
  105195. 10,10,10,10,10,10,10,10,
  105196. 10,10,10,10,10,10,10,10,
  105197. 10,10,10,10,10,10,10,10,
  105198. 10,10,10,10,10,10,10,10,
  105199. 10,10,10,10,10,10,10,10,
  105200. 10,10,10,10,10,10,10,10,
  105201. 10,10,10,10,10,10,10,10,
  105202. 10,10,10,10,10,10,10,10,
  105203. 10,10,10,10,10,10,10,50,-1};
  105204. const int *headret[]={head1_5,head2_5,head3_5,NULL};
  105205. fprintf(stderr,"testing max packet segments... ");
  105206. test_pack(packets,headret,0,0,0);
  105207. }
  105208. {
  105209. /* packet that overspans over an entire page */
  105210. const int packets[]={0,100,9000,259,255,-1};
  105211. const int *headret[]={head1_6,head2_6,head3_6,head4_6,NULL};
  105212. fprintf(stderr,"testing very large packets... ");
  105213. test_pack(packets,headret,0,0,0);
  105214. }
  105215. {
  105216. /* test for the libogg 1.1.1 resync in large continuation bug
  105217. found by Josh Coalson) */
  105218. const int packets[]={0,100,9000,259,255,-1};
  105219. const int *headret[]={head1_6,head2_6,head3_6,head4_6,NULL};
  105220. fprintf(stderr,"testing continuation resync in very large packets... ");
  105221. test_pack(packets,headret,100,2,3);
  105222. }
  105223. {
  105224. /* term only page. why not? */
  105225. const int packets[]={0,100,4080,-1};
  105226. const int *headret[]={head1_7,head2_7,head3_7,NULL};
  105227. fprintf(stderr,"testing zero data page (1 nil packet)... ");
  105228. test_pack(packets,headret,0,0,0);
  105229. }
  105230. {
  105231. /* build a bunch of pages for testing */
  105232. unsigned char *data=_ogg_malloc(1024*1024);
  105233. int pl[]={0,100,4079,2956,2057,76,34,912,0,234,1000,1000,1000,300,-1};
  105234. int inptr=0,i,j;
  105235. ogg_page og[5];
  105236. ogg_stream_reset(&os_en);
  105237. for(i=0;pl[i]!=-1;i++){
  105238. ogg_packet op;
  105239. int len=pl[i];
  105240. op.packet=data+inptr;
  105241. op.bytes=len;
  105242. op.e_o_s=(pl[i+1]<0?1:0);
  105243. op.granulepos=(i+1)*1000;
  105244. for(j=0;j<len;j++)data[inptr++]=i+j;
  105245. ogg_stream_packetin(&os_en,&op);
  105246. }
  105247. _ogg_free(data);
  105248. /* retrieve finished pages */
  105249. for(i=0;i<5;i++){
  105250. if(ogg_stream_pageout(&os_en,&og[i])==0){
  105251. fprintf(stderr,"Too few pages output building sync tests!\n");
  105252. exit(1);
  105253. }
  105254. copy_page(&og[i]);
  105255. }
  105256. /* Test lost pages on pagein/packetout: no rollback */
  105257. {
  105258. ogg_page temp;
  105259. ogg_packet test;
  105260. fprintf(stderr,"Testing loss of pages... ");
  105261. ogg_sync_reset(&oy);
  105262. ogg_stream_reset(&os_de);
  105263. for(i=0;i<5;i++){
  105264. memcpy(ogg_sync_buffer(&oy,og[i].header_len),og[i].header,
  105265. og[i].header_len);
  105266. ogg_sync_wrote(&oy,og[i].header_len);
  105267. memcpy(ogg_sync_buffer(&oy,og[i].body_len),og[i].body,og[i].body_len);
  105268. ogg_sync_wrote(&oy,og[i].body_len);
  105269. }
  105270. ogg_sync_pageout(&oy,&temp);
  105271. ogg_stream_pagein(&os_de,&temp);
  105272. ogg_sync_pageout(&oy,&temp);
  105273. ogg_stream_pagein(&os_de,&temp);
  105274. ogg_sync_pageout(&oy,&temp);
  105275. /* skip */
  105276. ogg_sync_pageout(&oy,&temp);
  105277. ogg_stream_pagein(&os_de,&temp);
  105278. /* do we get the expected results/packets? */
  105279. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  105280. checkpacket(&test,0,0,0);
  105281. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  105282. checkpacket(&test,100,1,-1);
  105283. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  105284. checkpacket(&test,4079,2,3000);
  105285. if(ogg_stream_packetout(&os_de,&test)!=-1){
  105286. fprintf(stderr,"Error: loss of page did not return error\n");
  105287. exit(1);
  105288. }
  105289. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  105290. checkpacket(&test,76,5,-1);
  105291. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  105292. checkpacket(&test,34,6,-1);
  105293. fprintf(stderr,"ok.\n");
  105294. }
  105295. /* Test lost pages on pagein/packetout: rollback with continuation */
  105296. {
  105297. ogg_page temp;
  105298. ogg_packet test;
  105299. fprintf(stderr,"Testing loss of pages (rollback required)... ");
  105300. ogg_sync_reset(&oy);
  105301. ogg_stream_reset(&os_de);
  105302. for(i=0;i<5;i++){
  105303. memcpy(ogg_sync_buffer(&oy,og[i].header_len),og[i].header,
  105304. og[i].header_len);
  105305. ogg_sync_wrote(&oy,og[i].header_len);
  105306. memcpy(ogg_sync_buffer(&oy,og[i].body_len),og[i].body,og[i].body_len);
  105307. ogg_sync_wrote(&oy,og[i].body_len);
  105308. }
  105309. ogg_sync_pageout(&oy,&temp);
  105310. ogg_stream_pagein(&os_de,&temp);
  105311. ogg_sync_pageout(&oy,&temp);
  105312. ogg_stream_pagein(&os_de,&temp);
  105313. ogg_sync_pageout(&oy,&temp);
  105314. ogg_stream_pagein(&os_de,&temp);
  105315. ogg_sync_pageout(&oy,&temp);
  105316. /* skip */
  105317. ogg_sync_pageout(&oy,&temp);
  105318. ogg_stream_pagein(&os_de,&temp);
  105319. /* do we get the expected results/packets? */
  105320. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  105321. checkpacket(&test,0,0,0);
  105322. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  105323. checkpacket(&test,100,1,-1);
  105324. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  105325. checkpacket(&test,4079,2,3000);
  105326. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  105327. checkpacket(&test,2956,3,4000);
  105328. if(ogg_stream_packetout(&os_de,&test)!=-1){
  105329. fprintf(stderr,"Error: loss of page did not return error\n");
  105330. exit(1);
  105331. }
  105332. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  105333. checkpacket(&test,300,13,14000);
  105334. fprintf(stderr,"ok.\n");
  105335. }
  105336. /* the rest only test sync */
  105337. {
  105338. ogg_page og_de;
  105339. /* Test fractional page inputs: incomplete capture */
  105340. fprintf(stderr,"Testing sync on partial inputs... ");
  105341. ogg_sync_reset(&oy);
  105342. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  105343. 3);
  105344. ogg_sync_wrote(&oy,3);
  105345. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  105346. /* Test fractional page inputs: incomplete fixed header */
  105347. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+3,
  105348. 20);
  105349. ogg_sync_wrote(&oy,20);
  105350. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  105351. /* Test fractional page inputs: incomplete header */
  105352. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+23,
  105353. 5);
  105354. ogg_sync_wrote(&oy,5);
  105355. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  105356. /* Test fractional page inputs: incomplete body */
  105357. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+28,
  105358. og[1].header_len-28);
  105359. ogg_sync_wrote(&oy,og[1].header_len-28);
  105360. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  105361. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,1000);
  105362. ogg_sync_wrote(&oy,1000);
  105363. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  105364. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body+1000,
  105365. og[1].body_len-1000);
  105366. ogg_sync_wrote(&oy,og[1].body_len-1000);
  105367. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  105368. fprintf(stderr,"ok.\n");
  105369. }
  105370. /* Test fractional page inputs: page + incomplete capture */
  105371. {
  105372. ogg_page og_de;
  105373. fprintf(stderr,"Testing sync on 1+partial inputs... ");
  105374. ogg_sync_reset(&oy);
  105375. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  105376. og[1].header_len);
  105377. ogg_sync_wrote(&oy,og[1].header_len);
  105378. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  105379. og[1].body_len);
  105380. ogg_sync_wrote(&oy,og[1].body_len);
  105381. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  105382. 20);
  105383. ogg_sync_wrote(&oy,20);
  105384. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  105385. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  105386. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+20,
  105387. og[1].header_len-20);
  105388. ogg_sync_wrote(&oy,og[1].header_len-20);
  105389. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  105390. og[1].body_len);
  105391. ogg_sync_wrote(&oy,og[1].body_len);
  105392. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  105393. fprintf(stderr,"ok.\n");
  105394. }
  105395. /* Test recapture: garbage + page */
  105396. {
  105397. ogg_page og_de;
  105398. fprintf(stderr,"Testing search for capture... ");
  105399. ogg_sync_reset(&oy);
  105400. /* 'garbage' */
  105401. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  105402. og[1].body_len);
  105403. ogg_sync_wrote(&oy,og[1].body_len);
  105404. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  105405. og[1].header_len);
  105406. ogg_sync_wrote(&oy,og[1].header_len);
  105407. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  105408. og[1].body_len);
  105409. ogg_sync_wrote(&oy,og[1].body_len);
  105410. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  105411. 20);
  105412. ogg_sync_wrote(&oy,20);
  105413. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  105414. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  105415. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  105416. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header+20,
  105417. og[2].header_len-20);
  105418. ogg_sync_wrote(&oy,og[2].header_len-20);
  105419. memcpy(ogg_sync_buffer(&oy,og[2].body_len),og[2].body,
  105420. og[2].body_len);
  105421. ogg_sync_wrote(&oy,og[2].body_len);
  105422. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  105423. fprintf(stderr,"ok.\n");
  105424. }
  105425. /* Test recapture: page + garbage + page */
  105426. {
  105427. ogg_page og_de;
  105428. fprintf(stderr,"Testing recapture... ");
  105429. ogg_sync_reset(&oy);
  105430. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  105431. og[1].header_len);
  105432. ogg_sync_wrote(&oy,og[1].header_len);
  105433. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  105434. og[1].body_len);
  105435. ogg_sync_wrote(&oy,og[1].body_len);
  105436. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  105437. og[2].header_len);
  105438. ogg_sync_wrote(&oy,og[2].header_len);
  105439. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  105440. og[2].header_len);
  105441. ogg_sync_wrote(&oy,og[2].header_len);
  105442. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  105443. memcpy(ogg_sync_buffer(&oy,og[2].body_len),og[2].body,
  105444. og[2].body_len-5);
  105445. ogg_sync_wrote(&oy,og[2].body_len-5);
  105446. memcpy(ogg_sync_buffer(&oy,og[3].header_len),og[3].header,
  105447. og[3].header_len);
  105448. ogg_sync_wrote(&oy,og[3].header_len);
  105449. memcpy(ogg_sync_buffer(&oy,og[3].body_len),og[3].body,
  105450. og[3].body_len);
  105451. ogg_sync_wrote(&oy,og[3].body_len);
  105452. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  105453. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  105454. fprintf(stderr,"ok.\n");
  105455. }
  105456. /* Free page data that was previously copied */
  105457. {
  105458. for(i=0;i<5;i++){
  105459. free_page(&og[i]);
  105460. }
  105461. }
  105462. }
  105463. return(0);
  105464. }
  105465. #endif
  105466. #endif
  105467. /********* End of inlined file: framing.c *********/
  105468. /********* Start of inlined file: analysis.c *********/
  105469. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  105470. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  105471. // tasks..
  105472. #ifdef _MSC_VER
  105473. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  105474. #endif
  105475. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  105476. #if JUCE_USE_OGGVORBIS
  105477. #include <stdio.h>
  105478. #include <string.h>
  105479. #include <math.h>
  105480. /********* Start of inlined file: codec_internal.h *********/
  105481. #ifndef _V_CODECI_H_
  105482. #define _V_CODECI_H_
  105483. /********* Start of inlined file: envelope.h *********/
  105484. #ifndef _V_ENVELOPE_
  105485. #define _V_ENVELOPE_
  105486. /********* Start of inlined file: mdct.h *********/
  105487. #ifndef _OGG_mdct_H_
  105488. #define _OGG_mdct_H_
  105489. /*#define MDCT_INTEGERIZED <- be warned there could be some hurt left here*/
  105490. #ifdef MDCT_INTEGERIZED
  105491. #define DATA_TYPE int
  105492. #define REG_TYPE register int
  105493. #define TRIGBITS 14
  105494. #define cPI3_8 6270
  105495. #define cPI2_8 11585
  105496. #define cPI1_8 15137
  105497. #define FLOAT_CONV(x) ((int)((x)*(1<<TRIGBITS)+.5))
  105498. #define MULT_NORM(x) ((x)>>TRIGBITS)
  105499. #define HALVE(x) ((x)>>1)
  105500. #else
  105501. #define DATA_TYPE float
  105502. #define REG_TYPE float
  105503. #define cPI3_8 .38268343236508977175F
  105504. #define cPI2_8 .70710678118654752441F
  105505. #define cPI1_8 .92387953251128675613F
  105506. #define FLOAT_CONV(x) (x)
  105507. #define MULT_NORM(x) (x)
  105508. #define HALVE(x) ((x)*.5f)
  105509. #endif
  105510. typedef struct {
  105511. int n;
  105512. int log2n;
  105513. DATA_TYPE *trig;
  105514. int *bitrev;
  105515. DATA_TYPE scale;
  105516. } mdct_lookup;
  105517. extern void mdct_init(mdct_lookup *lookup,int n);
  105518. extern void mdct_clear(mdct_lookup *l);
  105519. extern void mdct_forward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out);
  105520. extern void mdct_backward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out);
  105521. #endif
  105522. /********* End of inlined file: mdct.h *********/
  105523. #define VE_PRE 16
  105524. #define VE_WIN 4
  105525. #define VE_POST 2
  105526. #define VE_AMP (VE_PRE+VE_POST-1)
  105527. #define VE_BANDS 7
  105528. #define VE_NEARDC 15
  105529. #define VE_MINSTRETCH 2 /* a bit less than short block */
  105530. #define VE_MAXSTRETCH 12 /* one-third full block */
  105531. typedef struct {
  105532. float ampbuf[VE_AMP];
  105533. int ampptr;
  105534. float nearDC[VE_NEARDC];
  105535. float nearDC_acc;
  105536. float nearDC_partialacc;
  105537. int nearptr;
  105538. } envelope_filter_state;
  105539. typedef struct {
  105540. int begin;
  105541. int end;
  105542. float *window;
  105543. float total;
  105544. } envelope_band;
  105545. typedef struct {
  105546. int ch;
  105547. int winlength;
  105548. int searchstep;
  105549. float minenergy;
  105550. mdct_lookup mdct;
  105551. float *mdct_win;
  105552. envelope_band band[VE_BANDS];
  105553. envelope_filter_state *filter;
  105554. int stretch;
  105555. int *mark;
  105556. long storage;
  105557. long current;
  105558. long curmark;
  105559. long cursor;
  105560. } envelope_lookup;
  105561. extern void _ve_envelope_init(envelope_lookup *e,vorbis_info *vi);
  105562. extern void _ve_envelope_clear(envelope_lookup *e);
  105563. extern long _ve_envelope_search(vorbis_dsp_state *v);
  105564. extern void _ve_envelope_shift(envelope_lookup *e,long shift);
  105565. extern int _ve_envelope_mark(vorbis_dsp_state *v);
  105566. #endif
  105567. /********* End of inlined file: envelope.h *********/
  105568. /********* Start of inlined file: codebook.h *********/
  105569. #ifndef _V_CODEBOOK_H_
  105570. #define _V_CODEBOOK_H_
  105571. /* This structure encapsulates huffman and VQ style encoding books; it
  105572. doesn't do anything specific to either.
  105573. valuelist/quantlist are nonNULL (and q_* significant) only if
  105574. there's entry->value mapping to be done.
  105575. If encode-side mapping must be done (and thus the entry needs to be
  105576. hunted), the auxiliary encode pointer will point to a decision
  105577. tree. This is true of both VQ and huffman, but is mostly useful
  105578. with VQ.
  105579. */
  105580. typedef struct static_codebook{
  105581. long dim; /* codebook dimensions (elements per vector) */
  105582. long entries; /* codebook entries */
  105583. long *lengthlist; /* codeword lengths in bits */
  105584. /* mapping ***************************************************************/
  105585. int maptype; /* 0=none
  105586. 1=implicitly populated values from map column
  105587. 2=listed arbitrary values */
  105588. /* The below does a linear, single monotonic sequence mapping. */
  105589. long q_min; /* packed 32 bit float; quant value 0 maps to minval */
  105590. long q_delta; /* packed 32 bit float; val 1 - val 0 == delta */
  105591. int q_quant; /* bits: 0 < quant <= 16 */
  105592. int q_sequencep; /* bitflag */
  105593. long *quantlist; /* map == 1: (int)(entries^(1/dim)) element column map
  105594. map == 2: list of dim*entries quantized entry vals
  105595. */
  105596. /* encode helpers ********************************************************/
  105597. struct encode_aux_nearestmatch *nearest_tree;
  105598. struct encode_aux_threshmatch *thresh_tree;
  105599. struct encode_aux_pigeonhole *pigeon_tree;
  105600. int allocedp;
  105601. } static_codebook;
  105602. /* this structures an arbitrary trained book to quickly find the
  105603. nearest cell match */
  105604. typedef struct encode_aux_nearestmatch{
  105605. /* pre-calculated partitioning tree */
  105606. long *ptr0;
  105607. long *ptr1;
  105608. long *p; /* decision points (each is an entry) */
  105609. long *q; /* decision points (each is an entry) */
  105610. long aux; /* number of tree entries */
  105611. long alloc;
  105612. } encode_aux_nearestmatch;
  105613. /* assumes a maptype of 1; encode side only, so that's OK */
  105614. typedef struct encode_aux_threshmatch{
  105615. float *quantthresh;
  105616. long *quantmap;
  105617. int quantvals;
  105618. int threshvals;
  105619. } encode_aux_threshmatch;
  105620. typedef struct encode_aux_pigeonhole{
  105621. float min;
  105622. float del;
  105623. int mapentries;
  105624. int quantvals;
  105625. long *pigeonmap;
  105626. long fittotal;
  105627. long *fitlist;
  105628. long *fitmap;
  105629. long *fitlength;
  105630. } encode_aux_pigeonhole;
  105631. typedef struct codebook{
  105632. long dim; /* codebook dimensions (elements per vector) */
  105633. long entries; /* codebook entries */
  105634. long used_entries; /* populated codebook entries */
  105635. const static_codebook *c;
  105636. /* for encode, the below are entry-ordered, fully populated */
  105637. /* for decode, the below are ordered by bitreversed codeword and only
  105638. used entries are populated */
  105639. float *valuelist; /* list of dim*entries actual entry values */
  105640. ogg_uint32_t *codelist; /* list of bitstream codewords for each entry */
  105641. int *dec_index; /* only used if sparseness collapsed */
  105642. char *dec_codelengths;
  105643. ogg_uint32_t *dec_firsttable;
  105644. int dec_firsttablen;
  105645. int dec_maxlength;
  105646. } codebook;
  105647. extern void vorbis_staticbook_clear(static_codebook *b);
  105648. extern void vorbis_staticbook_destroy(static_codebook *b);
  105649. extern int vorbis_book_init_encode(codebook *dest,const static_codebook *source);
  105650. extern int vorbis_book_init_decode(codebook *dest,const static_codebook *source);
  105651. extern void vorbis_book_clear(codebook *b);
  105652. extern float *_book_unquantize(const static_codebook *b,int n,int *map);
  105653. extern float *_book_logdist(const static_codebook *b,float *vals);
  105654. extern float _float32_unpack(long val);
  105655. extern long _float32_pack(float val);
  105656. extern int _best(codebook *book, float *a, int step);
  105657. extern int _ilog(unsigned int v);
  105658. extern long _book_maptype1_quantvals(const static_codebook *b);
  105659. extern int vorbis_book_besterror(codebook *book,float *a,int step,int addmul);
  105660. extern long vorbis_book_codeword(codebook *book,int entry);
  105661. extern long vorbis_book_codelen(codebook *book,int entry);
  105662. extern int vorbis_staticbook_pack(const static_codebook *c,oggpack_buffer *b);
  105663. extern int vorbis_staticbook_unpack(oggpack_buffer *b,static_codebook *c);
  105664. extern int vorbis_book_encode(codebook *book, int a, oggpack_buffer *b);
  105665. extern int vorbis_book_errorv(codebook *book, float *a);
  105666. extern int vorbis_book_encodev(codebook *book, int best,float *a,
  105667. oggpack_buffer *b);
  105668. extern long vorbis_book_decode(codebook *book, oggpack_buffer *b);
  105669. extern long vorbis_book_decodevs_add(codebook *book, float *a,
  105670. oggpack_buffer *b,int n);
  105671. extern long vorbis_book_decodev_set(codebook *book, float *a,
  105672. oggpack_buffer *b,int n);
  105673. extern long vorbis_book_decodev_add(codebook *book, float *a,
  105674. oggpack_buffer *b,int n);
  105675. extern long vorbis_book_decodevv_add(codebook *book, float **a,
  105676. long off,int ch,
  105677. oggpack_buffer *b,int n);
  105678. #endif
  105679. /********* End of inlined file: codebook.h *********/
  105680. #define BLOCKTYPE_IMPULSE 0
  105681. #define BLOCKTYPE_PADDING 1
  105682. #define BLOCKTYPE_TRANSITION 0
  105683. #define BLOCKTYPE_LONG 1
  105684. #define PACKETBLOBS 15
  105685. typedef struct vorbis_block_internal{
  105686. float **pcmdelay; /* this is a pointer into local storage */
  105687. float ampmax;
  105688. int blocktype;
  105689. oggpack_buffer *packetblob[PACKETBLOBS]; /* initialized, must be freed;
  105690. blob [PACKETBLOBS/2] points to
  105691. the oggpack_buffer in the
  105692. main vorbis_block */
  105693. } vorbis_block_internal;
  105694. typedef void vorbis_look_floor;
  105695. typedef void vorbis_look_residue;
  105696. typedef void vorbis_look_transform;
  105697. /* mode ************************************************************/
  105698. typedef struct {
  105699. int blockflag;
  105700. int windowtype;
  105701. int transformtype;
  105702. int mapping;
  105703. } vorbis_info_mode;
  105704. typedef void vorbis_info_floor;
  105705. typedef void vorbis_info_residue;
  105706. typedef void vorbis_info_mapping;
  105707. /********* Start of inlined file: psy.h *********/
  105708. #ifndef _V_PSY_H_
  105709. #define _V_PSY_H_
  105710. /********* Start of inlined file: smallft.h *********/
  105711. #ifndef _V_SMFT_H_
  105712. #define _V_SMFT_H_
  105713. typedef struct {
  105714. int n;
  105715. float *trigcache;
  105716. int *splitcache;
  105717. } drft_lookup;
  105718. extern void drft_forward(drft_lookup *l,float *data);
  105719. extern void drft_backward(drft_lookup *l,float *data);
  105720. extern void drft_init(drft_lookup *l,int n);
  105721. extern void drft_clear(drft_lookup *l);
  105722. #endif
  105723. /********* End of inlined file: smallft.h *********/
  105724. /********* Start of inlined file: backends.h *********/
  105725. /* this is exposed up here because we need it for static modes.
  105726. Lookups for each backend aren't exposed because there's no reason
  105727. to do so */
  105728. #ifndef _vorbis_backend_h_
  105729. #define _vorbis_backend_h_
  105730. /* this would all be simpler/shorter with templates, but.... */
  105731. /* Floor backend generic *****************************************/
  105732. typedef struct{
  105733. void (*pack) (vorbis_info_floor *,oggpack_buffer *);
  105734. vorbis_info_floor *(*unpack)(vorbis_info *,oggpack_buffer *);
  105735. vorbis_look_floor *(*look) (vorbis_dsp_state *,vorbis_info_floor *);
  105736. void (*free_info) (vorbis_info_floor *);
  105737. void (*free_look) (vorbis_look_floor *);
  105738. void *(*inverse1) (struct vorbis_block *,vorbis_look_floor *);
  105739. int (*inverse2) (struct vorbis_block *,vorbis_look_floor *,
  105740. void *buffer,float *);
  105741. } vorbis_func_floor;
  105742. typedef struct{
  105743. int order;
  105744. long rate;
  105745. long barkmap;
  105746. int ampbits;
  105747. int ampdB;
  105748. int numbooks; /* <= 16 */
  105749. int books[16];
  105750. float lessthan; /* encode-only config setting hacks for libvorbis */
  105751. float greaterthan; /* encode-only config setting hacks for libvorbis */
  105752. } vorbis_info_floor0;
  105753. #define VIF_POSIT 63
  105754. #define VIF_CLASS 16
  105755. #define VIF_PARTS 31
  105756. typedef struct{
  105757. int partitions; /* 0 to 31 */
  105758. int partitionclass[VIF_PARTS]; /* 0 to 15 */
  105759. int class_dim[VIF_CLASS]; /* 1 to 8 */
  105760. int class_subs[VIF_CLASS]; /* 0,1,2,3 (bits: 1<<n poss) */
  105761. int class_book[VIF_CLASS]; /* subs ^ dim entries */
  105762. int class_subbook[VIF_CLASS][8]; /* [VIF_CLASS][subs] */
  105763. int mult; /* 1 2 3 or 4 */
  105764. int postlist[VIF_POSIT+2]; /* first two implicit */
  105765. /* encode side analysis parameters */
  105766. float maxover;
  105767. float maxunder;
  105768. float maxerr;
  105769. float twofitweight;
  105770. float twofitatten;
  105771. int n;
  105772. } vorbis_info_floor1;
  105773. /* Residue backend generic *****************************************/
  105774. typedef struct{
  105775. void (*pack) (vorbis_info_residue *,oggpack_buffer *);
  105776. vorbis_info_residue *(*unpack)(vorbis_info *,oggpack_buffer *);
  105777. vorbis_look_residue *(*look) (vorbis_dsp_state *,
  105778. vorbis_info_residue *);
  105779. void (*free_info) (vorbis_info_residue *);
  105780. void (*free_look) (vorbis_look_residue *);
  105781. long **(*classx) (struct vorbis_block *,vorbis_look_residue *,
  105782. float **,int *,int);
  105783. int (*forward) (oggpack_buffer *,struct vorbis_block *,
  105784. vorbis_look_residue *,
  105785. float **,float **,int *,int,long **);
  105786. int (*inverse) (struct vorbis_block *,vorbis_look_residue *,
  105787. float **,int *,int);
  105788. } vorbis_func_residue;
  105789. typedef struct vorbis_info_residue0{
  105790. /* block-partitioned VQ coded straight residue */
  105791. long begin;
  105792. long end;
  105793. /* first stage (lossless partitioning) */
  105794. int grouping; /* group n vectors per partition */
  105795. int partitions; /* possible codebooks for a partition */
  105796. int groupbook; /* huffbook for partitioning */
  105797. int secondstages[64]; /* expanded out to pointers in lookup */
  105798. int booklist[256]; /* list of second stage books */
  105799. float classmetric1[64];
  105800. float classmetric2[64];
  105801. } vorbis_info_residue0;
  105802. /* Mapping backend generic *****************************************/
  105803. typedef struct{
  105804. void (*pack) (vorbis_info *,vorbis_info_mapping *,
  105805. oggpack_buffer *);
  105806. vorbis_info_mapping *(*unpack)(vorbis_info *,oggpack_buffer *);
  105807. void (*free_info) (vorbis_info_mapping *);
  105808. int (*forward) (struct vorbis_block *vb);
  105809. int (*inverse) (struct vorbis_block *vb,vorbis_info_mapping *);
  105810. } vorbis_func_mapping;
  105811. typedef struct vorbis_info_mapping0{
  105812. int submaps; /* <= 16 */
  105813. int chmuxlist[256]; /* up to 256 channels in a Vorbis stream */
  105814. int floorsubmap[16]; /* [mux] submap to floors */
  105815. int residuesubmap[16]; /* [mux] submap to residue */
  105816. int coupling_steps;
  105817. int coupling_mag[256];
  105818. int coupling_ang[256];
  105819. } vorbis_info_mapping0;
  105820. #endif
  105821. /********* End of inlined file: backends.h *********/
  105822. #ifndef EHMER_MAX
  105823. #define EHMER_MAX 56
  105824. #endif
  105825. /* psychoacoustic setup ********************************************/
  105826. #define P_BANDS 17 /* 62Hz to 16kHz */
  105827. #define P_LEVELS 8 /* 30dB to 100dB */
  105828. #define P_LEVEL_0 30. /* 30 dB */
  105829. #define P_NOISECURVES 3
  105830. #define NOISE_COMPAND_LEVELS 40
  105831. typedef struct vorbis_info_psy{
  105832. int blockflag;
  105833. float ath_adjatt;
  105834. float ath_maxatt;
  105835. float tone_masteratt[P_NOISECURVES];
  105836. float tone_centerboost;
  105837. float tone_decay;
  105838. float tone_abs_limit;
  105839. float toneatt[P_BANDS];
  105840. int noisemaskp;
  105841. float noisemaxsupp;
  105842. float noisewindowlo;
  105843. float noisewindowhi;
  105844. int noisewindowlomin;
  105845. int noisewindowhimin;
  105846. int noisewindowfixed;
  105847. float noiseoff[P_NOISECURVES][P_BANDS];
  105848. float noisecompand[NOISE_COMPAND_LEVELS];
  105849. float max_curve_dB;
  105850. int normal_channel_p;
  105851. int normal_point_p;
  105852. int normal_start;
  105853. int normal_partition;
  105854. double normal_thresh;
  105855. } vorbis_info_psy;
  105856. typedef struct{
  105857. int eighth_octave_lines;
  105858. /* for block long/short tuning; encode only */
  105859. float preecho_thresh[VE_BANDS];
  105860. float postecho_thresh[VE_BANDS];
  105861. float stretch_penalty;
  105862. float preecho_minenergy;
  105863. float ampmax_att_per_sec;
  105864. /* channel coupling config */
  105865. int coupling_pkHz[PACKETBLOBS];
  105866. int coupling_pointlimit[2][PACKETBLOBS];
  105867. int coupling_prepointamp[PACKETBLOBS];
  105868. int coupling_postpointamp[PACKETBLOBS];
  105869. int sliding_lowpass[2][PACKETBLOBS];
  105870. } vorbis_info_psy_global;
  105871. typedef struct {
  105872. float ampmax;
  105873. int channels;
  105874. vorbis_info_psy_global *gi;
  105875. int coupling_pointlimit[2][P_NOISECURVES];
  105876. } vorbis_look_psy_global;
  105877. typedef struct {
  105878. int n;
  105879. struct vorbis_info_psy *vi;
  105880. float ***tonecurves;
  105881. float **noiseoffset;
  105882. float *ath;
  105883. long *octave; /* in n.ocshift format */
  105884. long *bark;
  105885. long firstoc;
  105886. long shiftoc;
  105887. int eighth_octave_lines; /* power of two, please */
  105888. int total_octave_lines;
  105889. long rate; /* cache it */
  105890. float m_val; /* Masking compensation value */
  105891. } vorbis_look_psy;
  105892. extern void _vp_psy_init(vorbis_look_psy *p,vorbis_info_psy *vi,
  105893. vorbis_info_psy_global *gi,int n,long rate);
  105894. extern void _vp_psy_clear(vorbis_look_psy *p);
  105895. extern void *_vi_psy_dup(void *source);
  105896. extern void _vi_psy_free(vorbis_info_psy *i);
  105897. extern vorbis_info_psy *_vi_psy_copy(vorbis_info_psy *i);
  105898. extern void _vp_remove_floor(vorbis_look_psy *p,
  105899. float *mdct,
  105900. int *icodedflr,
  105901. float *residue,
  105902. int sliding_lowpass);
  105903. extern void _vp_noisemask(vorbis_look_psy *p,
  105904. float *logmdct,
  105905. float *logmask);
  105906. extern void _vp_tonemask(vorbis_look_psy *p,
  105907. float *logfft,
  105908. float *logmask,
  105909. float global_specmax,
  105910. float local_specmax);
  105911. extern void _vp_offset_and_mix(vorbis_look_psy *p,
  105912. float *noise,
  105913. float *tone,
  105914. int offset_select,
  105915. float *logmask,
  105916. float *mdct,
  105917. float *logmdct);
  105918. extern float _vp_ampmax_decay(float amp,vorbis_dsp_state *vd);
  105919. extern float **_vp_quantize_couple_memo(vorbis_block *vb,
  105920. vorbis_info_psy_global *g,
  105921. vorbis_look_psy *p,
  105922. vorbis_info_mapping0 *vi,
  105923. float **mdct);
  105924. extern void _vp_couple(int blobno,
  105925. vorbis_info_psy_global *g,
  105926. vorbis_look_psy *p,
  105927. vorbis_info_mapping0 *vi,
  105928. float **res,
  105929. float **mag_memo,
  105930. int **mag_sort,
  105931. int **ifloor,
  105932. int *nonzero,
  105933. int sliding_lowpass);
  105934. extern void _vp_noise_normalize(vorbis_look_psy *p,
  105935. float *in,float *out,int *sortedindex);
  105936. extern void _vp_noise_normalize_sort(vorbis_look_psy *p,
  105937. float *magnitudes,int *sortedindex);
  105938. extern int **_vp_quantize_couple_sort(vorbis_block *vb,
  105939. vorbis_look_psy *p,
  105940. vorbis_info_mapping0 *vi,
  105941. float **mags);
  105942. extern void hf_reduction(vorbis_info_psy_global *g,
  105943. vorbis_look_psy *p,
  105944. vorbis_info_mapping0 *vi,
  105945. float **mdct);
  105946. #endif
  105947. /********* End of inlined file: psy.h *********/
  105948. /********* Start of inlined file: bitrate.h *********/
  105949. #ifndef _V_BITRATE_H_
  105950. #define _V_BITRATE_H_
  105951. /********* Start of inlined file: os.h *********/
  105952. #ifndef _OS_H
  105953. #define _OS_H
  105954. /********************************************************************
  105955. * *
  105956. * THIS FILE IS PART OF THE OggVorbis SOFTWARE CODEC SOURCE CODE. *
  105957. * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS *
  105958. * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE *
  105959. * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. *
  105960. * *
  105961. * THE OggVorbis SOURCE CODE IS (C) COPYRIGHT 1994-2002 *
  105962. * by the XIPHOPHORUS Company http://www.xiph.org/ *
  105963. * *
  105964. ********************************************************************
  105965. function: #ifdef jail to whip a few platforms into the UNIX ideal.
  105966. last mod: $Id: os.h,v 1.1 2007/06/07 17:49:18 jules_rms Exp $
  105967. ********************************************************************/
  105968. #ifdef HAVE_CONFIG_H
  105969. #include "config.h"
  105970. #endif
  105971. #include <math.h>
  105972. /********* Start of inlined file: misc.h *********/
  105973. #ifndef _V_RANDOM_H_
  105974. #define _V_RANDOM_H_
  105975. extern int analysis_noisy;
  105976. extern void *_vorbis_block_alloc(vorbis_block *vb,long bytes);
  105977. extern void _vorbis_block_ripcord(vorbis_block *vb);
  105978. extern void _analysis_output(char *base,int i,float *v,int n,int bark,int dB,
  105979. ogg_int64_t off);
  105980. #ifdef DEBUG_MALLOC
  105981. #define _VDBG_GRAPHFILE "malloc.m"
  105982. extern void *_VDBG_malloc(void *ptr,long bytes,char *file,long line);
  105983. extern void _VDBG_free(void *ptr,char *file,long line);
  105984. #ifndef MISC_C
  105985. #undef _ogg_malloc
  105986. #undef _ogg_calloc
  105987. #undef _ogg_realloc
  105988. #undef _ogg_free
  105989. #define _ogg_malloc(x) _VDBG_malloc(NULL,(x),__FILE__,__LINE__)
  105990. #define _ogg_calloc(x,y) _VDBG_malloc(NULL,(x)*(y),__FILE__,__LINE__)
  105991. #define _ogg_realloc(x,y) _VDBG_malloc((x),(y),__FILE__,__LINE__)
  105992. #define _ogg_free(x) _VDBG_free((x),__FILE__,__LINE__)
  105993. #endif
  105994. #endif
  105995. #endif
  105996. /********* End of inlined file: misc.h *********/
  105997. #ifndef _V_IFDEFJAIL_H_
  105998. # define _V_IFDEFJAIL_H_
  105999. # ifdef __GNUC__
  106000. # define STIN static __inline__
  106001. # elif _WIN32
  106002. # define STIN static __inline
  106003. # else
  106004. # define STIN static
  106005. # endif
  106006. #ifdef DJGPP
  106007. # define rint(x) (floor((x)+0.5f))
  106008. #endif
  106009. #ifndef M_PI
  106010. # define M_PI (3.1415926536f)
  106011. #endif
  106012. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  106013. # include <malloc.h>
  106014. # define rint(x) (floor((x)+0.5f))
  106015. # define NO_FLOAT_MATH_LIB
  106016. # define FAST_HYPOT(a, b) sqrt((a)*(a) + (b)*(b))
  106017. #endif
  106018. #if defined(__SYMBIAN32__) && defined(__WINS__)
  106019. void *_alloca(size_t size);
  106020. # define alloca _alloca
  106021. #endif
  106022. #ifndef FAST_HYPOT
  106023. # define FAST_HYPOT hypot
  106024. #endif
  106025. #endif
  106026. #ifdef HAVE_ALLOCA_H
  106027. # include <alloca.h>
  106028. #endif
  106029. #ifdef USE_MEMORY_H
  106030. # include <memory.h>
  106031. #endif
  106032. #ifndef min
  106033. # define min(x,y) ((x)>(y)?(y):(x))
  106034. #endif
  106035. #ifndef max
  106036. # define max(x,y) ((x)<(y)?(y):(x))
  106037. #endif
  106038. #if defined(__i386__) && defined(__GNUC__) && !defined(__BEOS__)
  106039. # define VORBIS_FPU_CONTROL
  106040. /* both GCC and MSVC are kinda stupid about rounding/casting to int.
  106041. Because of encapsulation constraints (GCC can't see inside the asm
  106042. block and so we end up doing stupid things like a store/load that
  106043. is collectively a noop), we do it this way */
  106044. /* we must set up the fpu before this works!! */
  106045. typedef ogg_int16_t vorbis_fpu_control;
  106046. static inline void vorbis_fpu_setround(vorbis_fpu_control *fpu){
  106047. ogg_int16_t ret;
  106048. ogg_int16_t temp;
  106049. __asm__ __volatile__("fnstcw %0\n\t"
  106050. "movw %0,%%dx\n\t"
  106051. "orw $62463,%%dx\n\t"
  106052. "movw %%dx,%1\n\t"
  106053. "fldcw %1\n\t":"=m"(ret):"m"(temp): "dx");
  106054. *fpu=ret;
  106055. }
  106056. static inline void vorbis_fpu_restore(vorbis_fpu_control fpu){
  106057. __asm__ __volatile__("fldcw %0":: "m"(fpu));
  106058. }
  106059. /* assumes the FPU is in round mode! */
  106060. static inline int vorbis_ftoi(double f){ /* yes, double! Otherwise,
  106061. we get extra fst/fld to
  106062. truncate precision */
  106063. int i;
  106064. __asm__("fistl %0": "=m"(i) : "t"(f));
  106065. return(i);
  106066. }
  106067. #endif
  106068. #if defined(_WIN32) && defined(_X86_) && !defined(__GNUC__) && !defined(__BORLANDC__)
  106069. # define VORBIS_FPU_CONTROL
  106070. typedef ogg_int16_t vorbis_fpu_control;
  106071. static __inline int vorbis_ftoi(double f){
  106072. int i;
  106073. __asm{
  106074. fld f
  106075. fistp i
  106076. }
  106077. return i;
  106078. }
  106079. static __inline void vorbis_fpu_setround(vorbis_fpu_control *fpu){
  106080. }
  106081. static __inline void vorbis_fpu_restore(vorbis_fpu_control fpu){
  106082. }
  106083. #endif
  106084. #ifndef VORBIS_FPU_CONTROL
  106085. typedef int vorbis_fpu_control;
  106086. static int vorbis_ftoi(double f){
  106087. return (int)(f+.5);
  106088. }
  106089. /* We don't have special code for this compiler/arch, so do it the slow way */
  106090. # define vorbis_fpu_setround(vorbis_fpu_control) {}
  106091. # define vorbis_fpu_restore(vorbis_fpu_control) {}
  106092. #endif
  106093. #endif /* _OS_H */
  106094. /********* End of inlined file: os.h *********/
  106095. /* encode side bitrate tracking */
  106096. typedef struct bitrate_manager_state {
  106097. int managed;
  106098. long avg_reservoir;
  106099. long minmax_reservoir;
  106100. long avg_bitsper;
  106101. long min_bitsper;
  106102. long max_bitsper;
  106103. long short_per_long;
  106104. double avgfloat;
  106105. vorbis_block *vb;
  106106. int choice;
  106107. } bitrate_manager_state;
  106108. typedef struct bitrate_manager_info{
  106109. long avg_rate;
  106110. long min_rate;
  106111. long max_rate;
  106112. long reservoir_bits;
  106113. double reservoir_bias;
  106114. double slew_damp;
  106115. } bitrate_manager_info;
  106116. extern void vorbis_bitrate_init(vorbis_info *vi,bitrate_manager_state *bs);
  106117. extern void vorbis_bitrate_clear(bitrate_manager_state *bs);
  106118. extern int vorbis_bitrate_managed(vorbis_block *vb);
  106119. extern int vorbis_bitrate_addblock(vorbis_block *vb);
  106120. extern int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd, ogg_packet *op);
  106121. #endif
  106122. /********* End of inlined file: bitrate.h *********/
  106123. static int ilog(unsigned int v){
  106124. int ret=0;
  106125. while(v){
  106126. ret++;
  106127. v>>=1;
  106128. }
  106129. return(ret);
  106130. }
  106131. static int ilog2(unsigned int v){
  106132. int ret=0;
  106133. if(v)--v;
  106134. while(v){
  106135. ret++;
  106136. v>>=1;
  106137. }
  106138. return(ret);
  106139. }
  106140. typedef struct private_state {
  106141. /* local lookup storage */
  106142. envelope_lookup *ve; /* envelope lookup */
  106143. int window[2];
  106144. vorbis_look_transform **transform[2]; /* block, type */
  106145. drft_lookup fft_look[2];
  106146. int modebits;
  106147. vorbis_look_floor **flr;
  106148. vorbis_look_residue **residue;
  106149. vorbis_look_psy *psy;
  106150. vorbis_look_psy_global *psy_g_look;
  106151. /* local storage, only used on the encoding side. This way the
  106152. application does not need to worry about freeing some packets'
  106153. memory and not others'; packet storage is always tracked.
  106154. Cleared next call to a _dsp_ function */
  106155. unsigned char *header;
  106156. unsigned char *header1;
  106157. unsigned char *header2;
  106158. bitrate_manager_state bms;
  106159. ogg_int64_t sample_count;
  106160. } private_state;
  106161. /* codec_setup_info contains all the setup information specific to the
  106162. specific compression/decompression mode in progress (eg,
  106163. psychoacoustic settings, channel setup, options, codebook
  106164. etc).
  106165. *********************************************************************/
  106166. /********* Start of inlined file: highlevel.h *********/
  106167. typedef struct highlevel_byblocktype {
  106168. double tone_mask_setting;
  106169. double tone_peaklimit_setting;
  106170. double noise_bias_setting;
  106171. double noise_compand_setting;
  106172. } highlevel_byblocktype;
  106173. typedef struct highlevel_encode_setup {
  106174. void *setup;
  106175. int set_in_stone;
  106176. double base_setting;
  106177. double long_setting;
  106178. double short_setting;
  106179. double impulse_noisetune;
  106180. int managed;
  106181. long bitrate_min;
  106182. long bitrate_av;
  106183. double bitrate_av_damp;
  106184. long bitrate_max;
  106185. long bitrate_reservoir;
  106186. double bitrate_reservoir_bias;
  106187. int impulse_block_p;
  106188. int noise_normalize_p;
  106189. double stereo_point_setting;
  106190. double lowpass_kHz;
  106191. double ath_floating_dB;
  106192. double ath_absolute_dB;
  106193. double amplitude_track_dBpersec;
  106194. double trigger_setting;
  106195. highlevel_byblocktype block[4]; /* padding, impulse, transition, long */
  106196. } highlevel_encode_setup;
  106197. /********* End of inlined file: highlevel.h *********/
  106198. typedef struct codec_setup_info {
  106199. /* Vorbis supports only short and long blocks, but allows the
  106200. encoder to choose the sizes */
  106201. long blocksizes[2];
  106202. /* modes are the primary means of supporting on-the-fly different
  106203. blocksizes, different channel mappings (LR or M/A),
  106204. different residue backends, etc. Each mode consists of a
  106205. blocksize flag and a mapping (along with the mapping setup */
  106206. int modes;
  106207. int maps;
  106208. int floors;
  106209. int residues;
  106210. int books;
  106211. int psys; /* encode only */
  106212. vorbis_info_mode *mode_param[64];
  106213. int map_type[64];
  106214. vorbis_info_mapping *map_param[64];
  106215. int floor_type[64];
  106216. vorbis_info_floor *floor_param[64];
  106217. int residue_type[64];
  106218. vorbis_info_residue *residue_param[64];
  106219. static_codebook *book_param[256];
  106220. codebook *fullbooks;
  106221. vorbis_info_psy *psy_param[4]; /* encode only */
  106222. vorbis_info_psy_global psy_g_param;
  106223. bitrate_manager_info bi;
  106224. highlevel_encode_setup hi; /* used only by vorbisenc.c. It's a
  106225. highly redundant structure, but
  106226. improves clarity of program flow. */
  106227. int halfrate_flag; /* painless downsample for decode */
  106228. } codec_setup_info;
  106229. extern vorbis_look_psy_global *_vp_global_look(vorbis_info *vi);
  106230. extern void _vp_global_free(vorbis_look_psy_global *look);
  106231. #endif
  106232. /********* End of inlined file: codec_internal.h *********/
  106233. /********* Start of inlined file: registry.h *********/
  106234. #ifndef _V_REG_H_
  106235. #define _V_REG_H_
  106236. #define VI_TRANSFORMB 1
  106237. #define VI_WINDOWB 1
  106238. #define VI_TIMEB 1
  106239. #define VI_FLOORB 2
  106240. #define VI_RESB 3
  106241. #define VI_MAPB 1
  106242. extern vorbis_func_floor *_floor_P[];
  106243. extern vorbis_func_residue *_residue_P[];
  106244. extern vorbis_func_mapping *_mapping_P[];
  106245. #endif
  106246. /********* End of inlined file: registry.h *********/
  106247. /********* Start of inlined file: scales.h *********/
  106248. #ifndef _V_SCALES_H_
  106249. #define _V_SCALES_H_
  106250. #include <math.h>
  106251. /* 20log10(x) */
  106252. #define VORBIS_IEEE_FLOAT32 1
  106253. #ifdef VORBIS_IEEE_FLOAT32
  106254. static float unitnorm(float x){
  106255. union {
  106256. ogg_uint32_t i;
  106257. float f;
  106258. } ix;
  106259. ix.f = x;
  106260. ix.i = (ix.i & 0x80000000U) | (0x3f800000U);
  106261. return ix.f;
  106262. }
  106263. /* Segher was off (too high) by ~ .3 decibel. Center the conversion correctly. */
  106264. static float todB(const float *x){
  106265. union {
  106266. ogg_uint32_t i;
  106267. float f;
  106268. } ix;
  106269. ix.f = *x;
  106270. ix.i = ix.i&0x7fffffff;
  106271. return (float)(ix.i * 7.17711438e-7f -764.6161886f);
  106272. }
  106273. #define todB_nn(x) todB(x)
  106274. #else
  106275. static float unitnorm(float x){
  106276. if(x<0)return(-1.f);
  106277. return(1.f);
  106278. }
  106279. #define todB(x) (*(x)==0?-400.f:log(*(x)**(x))*4.34294480f)
  106280. #define todB_nn(x) (*(x)==0.f?-400.f:log(*(x))*8.6858896f)
  106281. #endif
  106282. #define fromdB(x) (exp((x)*.11512925f))
  106283. /* The bark scale equations are approximations, since the original
  106284. table was somewhat hand rolled. The below are chosen to have the
  106285. best possible fit to the rolled tables, thus their somewhat odd
  106286. appearance (these are more accurate and over a longer range than
  106287. the oft-quoted bark equations found in the texts I have). The
  106288. approximations are valid from 0 - 30kHz (nyquist) or so.
  106289. all f in Hz, z in Bark */
  106290. #define toBARK(n) (13.1f*atan(.00074f*(n))+2.24f*atan((n)*(n)*1.85e-8f)+1e-4f*(n))
  106291. #define fromBARK(z) (102.f*(z)-2.f*pow(z,2.f)+.4f*pow(z,3.f)+pow(1.46f,z)-1.f)
  106292. #define toMEL(n) (log(1.f+(n)*.001f)*1442.695f)
  106293. #define fromMEL(m) (1000.f*exp((m)/1442.695f)-1000.f)
  106294. /* Frequency to octave. We arbitrarily declare 63.5 Hz to be octave
  106295. 0.0 */
  106296. #define toOC(n) (log(n)*1.442695f-5.965784f)
  106297. #define fromOC(o) (exp(((o)+5.965784f)*.693147f))
  106298. #endif
  106299. /********* End of inlined file: scales.h *********/
  106300. int analysis_noisy=1;
  106301. /* decides between modes, dispatches to the appropriate mapping. */
  106302. int vorbis_analysis(vorbis_block *vb, ogg_packet *op){
  106303. int ret,i;
  106304. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  106305. vb->glue_bits=0;
  106306. vb->time_bits=0;
  106307. vb->floor_bits=0;
  106308. vb->res_bits=0;
  106309. /* first things first. Make sure encode is ready */
  106310. for(i=0;i<PACKETBLOBS;i++)
  106311. oggpack_reset(vbi->packetblob[i]);
  106312. /* we only have one mapping type (0), and we let the mapping code
  106313. itself figure out what soft mode to use. This allows easier
  106314. bitrate management */
  106315. if((ret=_mapping_P[0]->forward(vb)))
  106316. return(ret);
  106317. if(op){
  106318. if(vorbis_bitrate_managed(vb))
  106319. /* The app is using a bitmanaged mode... but not using the
  106320. bitrate management interface. */
  106321. return(OV_EINVAL);
  106322. op->packet=oggpack_get_buffer(&vb->opb);
  106323. op->bytes=oggpack_bytes(&vb->opb);
  106324. op->b_o_s=0;
  106325. op->e_o_s=vb->eofflag;
  106326. op->granulepos=vb->granulepos;
  106327. op->packetno=vb->sequence; /* for sake of completeness */
  106328. }
  106329. return(0);
  106330. }
  106331. /* there was no great place to put this.... */
  106332. void _analysis_output_always(const char *base,int i,float *v,int n,int bark,int dB,ogg_int64_t off){
  106333. int j;
  106334. FILE *of;
  106335. char buffer[80];
  106336. /* if(i==5870){*/
  106337. sprintf(buffer,"%s_%d.m",base,i);
  106338. of=fopen(buffer,"w");
  106339. if(!of)perror("failed to open data dump file");
  106340. for(j=0;j<n;j++){
  106341. if(bark){
  106342. float b=toBARK((4000.f*j/n)+.25);
  106343. fprintf(of,"%f ",b);
  106344. }else
  106345. if(off!=0)
  106346. fprintf(of,"%f ",(double)(j+off)/8000.);
  106347. else
  106348. fprintf(of,"%f ",(double)j);
  106349. if(dB){
  106350. float val;
  106351. if(v[j]==0.)
  106352. val=-140.;
  106353. else
  106354. val=todB(v+j);
  106355. fprintf(of,"%f\n",val);
  106356. }else{
  106357. fprintf(of,"%f\n",v[j]);
  106358. }
  106359. }
  106360. fclose(of);
  106361. /* } */
  106362. }
  106363. void _analysis_output(char *base,int i,float *v,int n,int bark,int dB,
  106364. ogg_int64_t off){
  106365. if(analysis_noisy)_analysis_output_always(base,i,v,n,bark,dB,off);
  106366. }
  106367. #endif
  106368. /********* End of inlined file: analysis.c *********/
  106369. /********* Start of inlined file: bitrate.c *********/
  106370. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  106371. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  106372. // tasks..
  106373. #ifdef _MSC_VER
  106374. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  106375. #endif
  106376. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  106377. #if JUCE_USE_OGGVORBIS
  106378. #include <stdlib.h>
  106379. #include <string.h>
  106380. #include <math.h>
  106381. /* compute bitrate tracking setup */
  106382. void vorbis_bitrate_init(vorbis_info *vi,bitrate_manager_state *bm){
  106383. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  106384. bitrate_manager_info *bi=&ci->bi;
  106385. memset(bm,0,sizeof(*bm));
  106386. if(bi && (bi->reservoir_bits>0)){
  106387. long ratesamples=vi->rate;
  106388. int halfsamples=ci->blocksizes[0]>>1;
  106389. bm->short_per_long=ci->blocksizes[1]/ci->blocksizes[0];
  106390. bm->managed=1;
  106391. bm->avg_bitsper= rint(1.*bi->avg_rate*halfsamples/ratesamples);
  106392. bm->min_bitsper= rint(1.*bi->min_rate*halfsamples/ratesamples);
  106393. bm->max_bitsper= rint(1.*bi->max_rate*halfsamples/ratesamples);
  106394. bm->avgfloat=PACKETBLOBS/2;
  106395. /* not a necessary fix, but one that leads to a more balanced
  106396. typical initialization */
  106397. {
  106398. long desired_fill=bi->reservoir_bits*bi->reservoir_bias;
  106399. bm->minmax_reservoir=desired_fill;
  106400. bm->avg_reservoir=desired_fill;
  106401. }
  106402. }
  106403. }
  106404. void vorbis_bitrate_clear(bitrate_manager_state *bm){
  106405. memset(bm,0,sizeof(*bm));
  106406. return;
  106407. }
  106408. int vorbis_bitrate_managed(vorbis_block *vb){
  106409. vorbis_dsp_state *vd=vb->vd;
  106410. private_state *b=(private_state*)vd->backend_state;
  106411. bitrate_manager_state *bm=&b->bms;
  106412. if(bm && bm->managed)return(1);
  106413. return(0);
  106414. }
  106415. /* finish taking in the block we just processed */
  106416. int vorbis_bitrate_addblock(vorbis_block *vb){
  106417. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  106418. vorbis_dsp_state *vd=vb->vd;
  106419. private_state *b=(private_state*)vd->backend_state;
  106420. bitrate_manager_state *bm=&b->bms;
  106421. vorbis_info *vi=vd->vi;
  106422. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  106423. bitrate_manager_info *bi=&ci->bi;
  106424. int choice=rint(bm->avgfloat);
  106425. long this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  106426. long min_target_bits=(vb->W?bm->min_bitsper*bm->short_per_long:bm->min_bitsper);
  106427. long max_target_bits=(vb->W?bm->max_bitsper*bm->short_per_long:bm->max_bitsper);
  106428. int samples=ci->blocksizes[vb->W]>>1;
  106429. long desired_fill=bi->reservoir_bits*bi->reservoir_bias;
  106430. if(!bm->managed){
  106431. /* not a bitrate managed stream, but for API simplicity, we'll
  106432. buffer the packet to keep the code path clean */
  106433. if(bm->vb)return(-1); /* one has been submitted without
  106434. being claimed */
  106435. bm->vb=vb;
  106436. return(0);
  106437. }
  106438. bm->vb=vb;
  106439. /* look ahead for avg floater */
  106440. if(bm->avg_bitsper>0){
  106441. double slew=0.;
  106442. long avg_target_bits=(vb->W?bm->avg_bitsper*bm->short_per_long:bm->avg_bitsper);
  106443. double slewlimit= 15./bi->slew_damp;
  106444. /* choosing a new floater:
  106445. if we're over target, we slew down
  106446. if we're under target, we slew up
  106447. choose slew as follows: look through packetblobs of this frame
  106448. and set slew as the first in the appropriate direction that
  106449. gives us the slew we want. This may mean no slew if delta is
  106450. already favorable.
  106451. Then limit slew to slew max */
  106452. if(bm->avg_reservoir+(this_bits-avg_target_bits)>desired_fill){
  106453. while(choice>0 && this_bits>avg_target_bits &&
  106454. bm->avg_reservoir+(this_bits-avg_target_bits)>desired_fill){
  106455. choice--;
  106456. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  106457. }
  106458. }else if(bm->avg_reservoir+(this_bits-avg_target_bits)<desired_fill){
  106459. while(choice+1<PACKETBLOBS && this_bits<avg_target_bits &&
  106460. bm->avg_reservoir+(this_bits-avg_target_bits)<desired_fill){
  106461. choice++;
  106462. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  106463. }
  106464. }
  106465. slew=rint(choice-bm->avgfloat)/samples*vi->rate;
  106466. if(slew<-slewlimit)slew=-slewlimit;
  106467. if(slew>slewlimit)slew=slewlimit;
  106468. choice=rint(bm->avgfloat+= slew/vi->rate*samples);
  106469. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  106470. }
  106471. /* enforce min(if used) on the current floater (if used) */
  106472. if(bm->min_bitsper>0){
  106473. /* do we need to force the bitrate up? */
  106474. if(this_bits<min_target_bits){
  106475. while(bm->minmax_reservoir-(min_target_bits-this_bits)<0){
  106476. choice++;
  106477. if(choice>=PACKETBLOBS)break;
  106478. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  106479. }
  106480. }
  106481. }
  106482. /* enforce max (if used) on the current floater (if used) */
  106483. if(bm->max_bitsper>0){
  106484. /* do we need to force the bitrate down? */
  106485. if(this_bits>max_target_bits){
  106486. while(bm->minmax_reservoir+(this_bits-max_target_bits)>bi->reservoir_bits){
  106487. choice--;
  106488. if(choice<0)break;
  106489. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  106490. }
  106491. }
  106492. }
  106493. /* Choice of packetblobs now made based on floater, and min/max
  106494. requirements. Now boundary check extreme choices */
  106495. if(choice<0){
  106496. /* choosing a smaller packetblob is insufficient to trim bitrate.
  106497. frame will need to be truncated */
  106498. long maxsize=(max_target_bits+(bi->reservoir_bits-bm->minmax_reservoir))/8;
  106499. bm->choice=choice=0;
  106500. if(oggpack_bytes(vbi->packetblob[choice])>maxsize){
  106501. oggpack_writetrunc(vbi->packetblob[choice],maxsize*8);
  106502. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  106503. }
  106504. }else{
  106505. long minsize=(min_target_bits-bm->minmax_reservoir+7)/8;
  106506. if(choice>=PACKETBLOBS)
  106507. choice=PACKETBLOBS-1;
  106508. bm->choice=choice;
  106509. /* prop up bitrate according to demand. pad this frame out with zeroes */
  106510. minsize-=oggpack_bytes(vbi->packetblob[choice]);
  106511. while(minsize-->0)oggpack_write(vbi->packetblob[choice],0,8);
  106512. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  106513. }
  106514. /* now we have the final packet and the final packet size. Update statistics */
  106515. /* min and max reservoir */
  106516. if(bm->min_bitsper>0 || bm->max_bitsper>0){
  106517. if(max_target_bits>0 && this_bits>max_target_bits){
  106518. bm->minmax_reservoir+=(this_bits-max_target_bits);
  106519. }else if(min_target_bits>0 && this_bits<min_target_bits){
  106520. bm->minmax_reservoir+=(this_bits-min_target_bits);
  106521. }else{
  106522. /* inbetween; we want to take reservoir toward but not past desired_fill */
  106523. if(bm->minmax_reservoir>desired_fill){
  106524. if(max_target_bits>0){ /* logical bulletproofing against initialization state */
  106525. bm->minmax_reservoir+=(this_bits-max_target_bits);
  106526. if(bm->minmax_reservoir<desired_fill)bm->minmax_reservoir=desired_fill;
  106527. }else{
  106528. bm->minmax_reservoir=desired_fill;
  106529. }
  106530. }else{
  106531. if(min_target_bits>0){ /* logical bulletproofing against initialization state */
  106532. bm->minmax_reservoir+=(this_bits-min_target_bits);
  106533. if(bm->minmax_reservoir>desired_fill)bm->minmax_reservoir=desired_fill;
  106534. }else{
  106535. bm->minmax_reservoir=desired_fill;
  106536. }
  106537. }
  106538. }
  106539. }
  106540. /* avg reservoir */
  106541. if(bm->avg_bitsper>0){
  106542. long avg_target_bits=(vb->W?bm->avg_bitsper*bm->short_per_long:bm->avg_bitsper);
  106543. bm->avg_reservoir+=this_bits-avg_target_bits;
  106544. }
  106545. return(0);
  106546. }
  106547. int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd,ogg_packet *op){
  106548. private_state *b=(private_state*)vd->backend_state;
  106549. bitrate_manager_state *bm=&b->bms;
  106550. vorbis_block *vb=bm->vb;
  106551. int choice=PACKETBLOBS/2;
  106552. if(!vb)return 0;
  106553. if(op){
  106554. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  106555. if(vorbis_bitrate_managed(vb))
  106556. choice=bm->choice;
  106557. op->packet=oggpack_get_buffer(vbi->packetblob[choice]);
  106558. op->bytes=oggpack_bytes(vbi->packetblob[choice]);
  106559. op->b_o_s=0;
  106560. op->e_o_s=vb->eofflag;
  106561. op->granulepos=vb->granulepos;
  106562. op->packetno=vb->sequence; /* for sake of completeness */
  106563. }
  106564. bm->vb=0;
  106565. return(1);
  106566. }
  106567. #endif
  106568. /********* End of inlined file: bitrate.c *********/
  106569. /********* Start of inlined file: block.c *********/
  106570. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  106571. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  106572. // tasks..
  106573. #ifdef _MSC_VER
  106574. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  106575. #endif
  106576. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  106577. #if JUCE_USE_OGGVORBIS
  106578. #include <stdio.h>
  106579. #include <stdlib.h>
  106580. #include <string.h>
  106581. /********* Start of inlined file: window.h *********/
  106582. #ifndef _V_WINDOW_
  106583. #define _V_WINDOW_
  106584. extern float *_vorbis_window_get(int n);
  106585. extern void _vorbis_apply_window(float *d,int *winno,long *blocksizes,
  106586. int lW,int W,int nW);
  106587. #endif
  106588. /********* End of inlined file: window.h *********/
  106589. /********* Start of inlined file: lpc.h *********/
  106590. #ifndef _V_LPC_H_
  106591. #define _V_LPC_H_
  106592. /* simple linear scale LPC code */
  106593. extern float vorbis_lpc_from_data(float *data,float *lpc,int n,int m);
  106594. extern void vorbis_lpc_predict(float *coeff,float *prime,int m,
  106595. float *data,long n);
  106596. #endif
  106597. /********* End of inlined file: lpc.h *********/
  106598. /* pcm accumulator examples (not exhaustive):
  106599. <-------------- lW ---------------->
  106600. <--------------- W ---------------->
  106601. : .....|..... _______________ |
  106602. : .''' | '''_--- | |\ |
  106603. :.....''' |_____--- '''......| | \_______|
  106604. :.................|__________________|_______|__|______|
  106605. |<------ Sl ------>| > Sr < |endW
  106606. |beginSl |endSl | |endSr
  106607. |beginW |endlW |beginSr
  106608. |< lW >|
  106609. <--------------- W ---------------->
  106610. | | .. ______________ |
  106611. | | ' `/ | ---_ |
  106612. |___.'___/`. | ---_____|
  106613. |_______|__|_______|_________________|
  106614. | >|Sl|< |<------ Sr ----->|endW
  106615. | | |endSl |beginSr |endSr
  106616. |beginW | |endlW
  106617. mult[0] |beginSl mult[n]
  106618. <-------------- lW ----------------->
  106619. |<--W-->|
  106620. : .............. ___ | |
  106621. : .''' |`/ \ | |
  106622. :.....''' |/`....\|...|
  106623. :.........................|___|___|___|
  106624. |Sl |Sr |endW
  106625. | | |endSr
  106626. | |beginSr
  106627. | |endSl
  106628. |beginSl
  106629. |beginW
  106630. */
  106631. /* block abstraction setup *********************************************/
  106632. #ifndef WORD_ALIGN
  106633. #define WORD_ALIGN 8
  106634. #endif
  106635. int vorbis_block_init(vorbis_dsp_state *v, vorbis_block *vb){
  106636. int i;
  106637. memset(vb,0,sizeof(*vb));
  106638. vb->vd=v;
  106639. vb->localalloc=0;
  106640. vb->localstore=NULL;
  106641. if(v->analysisp){
  106642. vorbis_block_internal *vbi=(vorbis_block_internal*)
  106643. (vb->internal=(vorbis_block_internal*)_ogg_calloc(1,sizeof(vorbis_block_internal)));
  106644. vbi->ampmax=-9999;
  106645. for(i=0;i<PACKETBLOBS;i++){
  106646. if(i==PACKETBLOBS/2){
  106647. vbi->packetblob[i]=&vb->opb;
  106648. }else{
  106649. vbi->packetblob[i]=
  106650. (oggpack_buffer*) _ogg_calloc(1,sizeof(oggpack_buffer));
  106651. }
  106652. oggpack_writeinit(vbi->packetblob[i]);
  106653. }
  106654. }
  106655. return(0);
  106656. }
  106657. void *_vorbis_block_alloc(vorbis_block *vb,long bytes){
  106658. bytes=(bytes+(WORD_ALIGN-1)) & ~(WORD_ALIGN-1);
  106659. if(bytes+vb->localtop>vb->localalloc){
  106660. /* can't just _ogg_realloc... there are outstanding pointers */
  106661. if(vb->localstore){
  106662. struct alloc_chain *link=(struct alloc_chain*)_ogg_malloc(sizeof(*link));
  106663. vb->totaluse+=vb->localtop;
  106664. link->next=vb->reap;
  106665. link->ptr=vb->localstore;
  106666. vb->reap=link;
  106667. }
  106668. /* highly conservative */
  106669. vb->localalloc=bytes;
  106670. vb->localstore=_ogg_malloc(vb->localalloc);
  106671. vb->localtop=0;
  106672. }
  106673. {
  106674. void *ret=(void *)(((char *)vb->localstore)+vb->localtop);
  106675. vb->localtop+=bytes;
  106676. return ret;
  106677. }
  106678. }
  106679. /* reap the chain, pull the ripcord */
  106680. void _vorbis_block_ripcord(vorbis_block *vb){
  106681. /* reap the chain */
  106682. struct alloc_chain *reap=vb->reap;
  106683. while(reap){
  106684. struct alloc_chain *next=reap->next;
  106685. _ogg_free(reap->ptr);
  106686. memset(reap,0,sizeof(*reap));
  106687. _ogg_free(reap);
  106688. reap=next;
  106689. }
  106690. /* consolidate storage */
  106691. if(vb->totaluse){
  106692. vb->localstore=_ogg_realloc(vb->localstore,vb->totaluse+vb->localalloc);
  106693. vb->localalloc+=vb->totaluse;
  106694. vb->totaluse=0;
  106695. }
  106696. /* pull the ripcord */
  106697. vb->localtop=0;
  106698. vb->reap=NULL;
  106699. }
  106700. int vorbis_block_clear(vorbis_block *vb){
  106701. int i;
  106702. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  106703. _vorbis_block_ripcord(vb);
  106704. if(vb->localstore)_ogg_free(vb->localstore);
  106705. if(vbi){
  106706. for(i=0;i<PACKETBLOBS;i++){
  106707. oggpack_writeclear(vbi->packetblob[i]);
  106708. if(i!=PACKETBLOBS/2)_ogg_free(vbi->packetblob[i]);
  106709. }
  106710. _ogg_free(vbi);
  106711. }
  106712. memset(vb,0,sizeof(*vb));
  106713. return(0);
  106714. }
  106715. /* Analysis side code, but directly related to blocking. Thus it's
  106716. here and not in analysis.c (which is for analysis transforms only).
  106717. The init is here because some of it is shared */
  106718. static int _vds_shared_init(vorbis_dsp_state *v,vorbis_info *vi,int encp){
  106719. int i;
  106720. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  106721. private_state *b=NULL;
  106722. int hs;
  106723. if(ci==NULL) return 1;
  106724. hs=ci->halfrate_flag;
  106725. memset(v,0,sizeof(*v));
  106726. b=(private_state*) (v->backend_state=(private_state*)_ogg_calloc(1,sizeof(*b)));
  106727. v->vi=vi;
  106728. b->modebits=ilog2(ci->modes);
  106729. b->transform[0]=(vorbis_look_transform**)_ogg_calloc(VI_TRANSFORMB,sizeof(*b->transform[0]));
  106730. b->transform[1]=(vorbis_look_transform**)_ogg_calloc(VI_TRANSFORMB,sizeof(*b->transform[1]));
  106731. /* MDCT is tranform 0 */
  106732. b->transform[0][0]=_ogg_calloc(1,sizeof(mdct_lookup));
  106733. b->transform[1][0]=_ogg_calloc(1,sizeof(mdct_lookup));
  106734. mdct_init((mdct_lookup*)b->transform[0][0],ci->blocksizes[0]>>hs);
  106735. mdct_init((mdct_lookup*)b->transform[1][0],ci->blocksizes[1]>>hs);
  106736. /* Vorbis I uses only window type 0 */
  106737. b->window[0]=ilog2(ci->blocksizes[0])-6;
  106738. b->window[1]=ilog2(ci->blocksizes[1])-6;
  106739. if(encp){ /* encode/decode differ here */
  106740. /* analysis always needs an fft */
  106741. drft_init(&b->fft_look[0],ci->blocksizes[0]);
  106742. drft_init(&b->fft_look[1],ci->blocksizes[1]);
  106743. /* finish the codebooks */
  106744. if(!ci->fullbooks){
  106745. ci->fullbooks=(codebook*) _ogg_calloc(ci->books,sizeof(*ci->fullbooks));
  106746. for(i=0;i<ci->books;i++)
  106747. vorbis_book_init_encode(ci->fullbooks+i,ci->book_param[i]);
  106748. }
  106749. b->psy=(vorbis_look_psy*)_ogg_calloc(ci->psys,sizeof(*b->psy));
  106750. for(i=0;i<ci->psys;i++){
  106751. _vp_psy_init(b->psy+i,
  106752. ci->psy_param[i],
  106753. &ci->psy_g_param,
  106754. ci->blocksizes[ci->psy_param[i]->blockflag]/2,
  106755. vi->rate);
  106756. }
  106757. v->analysisp=1;
  106758. }else{
  106759. /* finish the codebooks */
  106760. if(!ci->fullbooks){
  106761. ci->fullbooks=(codebook*) _ogg_calloc(ci->books,sizeof(*ci->fullbooks));
  106762. for(i=0;i<ci->books;i++){
  106763. vorbis_book_init_decode(ci->fullbooks+i,ci->book_param[i]);
  106764. /* decode codebooks are now standalone after init */
  106765. vorbis_staticbook_destroy(ci->book_param[i]);
  106766. ci->book_param[i]=NULL;
  106767. }
  106768. }
  106769. }
  106770. /* initialize the storage vectors. blocksize[1] is small for encode,
  106771. but the correct size for decode */
  106772. v->pcm_storage=ci->blocksizes[1];
  106773. v->pcm=(float**)_ogg_malloc(vi->channels*sizeof(*v->pcm));
  106774. v->pcmret=(float**)_ogg_malloc(vi->channels*sizeof(*v->pcmret));
  106775. {
  106776. int i;
  106777. for(i=0;i<vi->channels;i++)
  106778. v->pcm[i]=(float*)_ogg_calloc(v->pcm_storage,sizeof(*v->pcm[i]));
  106779. }
  106780. /* all 1 (large block) or 0 (small block) */
  106781. /* explicitly set for the sake of clarity */
  106782. v->lW=0; /* previous window size */
  106783. v->W=0; /* current window size */
  106784. /* all vector indexes */
  106785. v->centerW=ci->blocksizes[1]/2;
  106786. v->pcm_current=v->centerW;
  106787. /* initialize all the backend lookups */
  106788. b->flr=(vorbis_look_floor**)_ogg_calloc(ci->floors,sizeof(*b->flr));
  106789. b->residue=(vorbis_look_residue**)_ogg_calloc(ci->residues,sizeof(*b->residue));
  106790. for(i=0;i<ci->floors;i++)
  106791. b->flr[i]=_floor_P[ci->floor_type[i]]->
  106792. look(v,ci->floor_param[i]);
  106793. for(i=0;i<ci->residues;i++)
  106794. b->residue[i]=_residue_P[ci->residue_type[i]]->
  106795. look(v,ci->residue_param[i]);
  106796. return 0;
  106797. }
  106798. /* arbitrary settings and spec-mandated numbers get filled in here */
  106799. int vorbis_analysis_init(vorbis_dsp_state *v,vorbis_info *vi){
  106800. private_state *b=NULL;
  106801. if(_vds_shared_init(v,vi,1))return 1;
  106802. b=(private_state*)v->backend_state;
  106803. b->psy_g_look=_vp_global_look(vi);
  106804. /* Initialize the envelope state storage */
  106805. b->ve=(envelope_lookup*)_ogg_calloc(1,sizeof(*b->ve));
  106806. _ve_envelope_init(b->ve,vi);
  106807. vorbis_bitrate_init(vi,&b->bms);
  106808. /* compressed audio packets start after the headers
  106809. with sequence number 3 */
  106810. v->sequence=3;
  106811. return(0);
  106812. }
  106813. void vorbis_dsp_clear(vorbis_dsp_state *v){
  106814. int i;
  106815. if(v){
  106816. vorbis_info *vi=v->vi;
  106817. codec_setup_info *ci=(codec_setup_info*)(vi?vi->codec_setup:NULL);
  106818. private_state *b=(private_state*)v->backend_state;
  106819. if(b){
  106820. if(b->ve){
  106821. _ve_envelope_clear(b->ve);
  106822. _ogg_free(b->ve);
  106823. }
  106824. if(b->transform[0]){
  106825. mdct_clear((mdct_lookup*) b->transform[0][0]);
  106826. _ogg_free(b->transform[0][0]);
  106827. _ogg_free(b->transform[0]);
  106828. }
  106829. if(b->transform[1]){
  106830. mdct_clear((mdct_lookup*) b->transform[1][0]);
  106831. _ogg_free(b->transform[1][0]);
  106832. _ogg_free(b->transform[1]);
  106833. }
  106834. if(b->flr){
  106835. for(i=0;i<ci->floors;i++)
  106836. _floor_P[ci->floor_type[i]]->
  106837. free_look(b->flr[i]);
  106838. _ogg_free(b->flr);
  106839. }
  106840. if(b->residue){
  106841. for(i=0;i<ci->residues;i++)
  106842. _residue_P[ci->residue_type[i]]->
  106843. free_look(b->residue[i]);
  106844. _ogg_free(b->residue);
  106845. }
  106846. if(b->psy){
  106847. for(i=0;i<ci->psys;i++)
  106848. _vp_psy_clear(b->psy+i);
  106849. _ogg_free(b->psy);
  106850. }
  106851. if(b->psy_g_look)_vp_global_free(b->psy_g_look);
  106852. vorbis_bitrate_clear(&b->bms);
  106853. drft_clear(&b->fft_look[0]);
  106854. drft_clear(&b->fft_look[1]);
  106855. }
  106856. if(v->pcm){
  106857. for(i=0;i<vi->channels;i++)
  106858. if(v->pcm[i])_ogg_free(v->pcm[i]);
  106859. _ogg_free(v->pcm);
  106860. if(v->pcmret)_ogg_free(v->pcmret);
  106861. }
  106862. if(b){
  106863. /* free header, header1, header2 */
  106864. if(b->header)_ogg_free(b->header);
  106865. if(b->header1)_ogg_free(b->header1);
  106866. if(b->header2)_ogg_free(b->header2);
  106867. _ogg_free(b);
  106868. }
  106869. memset(v,0,sizeof(*v));
  106870. }
  106871. }
  106872. float **vorbis_analysis_buffer(vorbis_dsp_state *v, int vals){
  106873. int i;
  106874. vorbis_info *vi=v->vi;
  106875. private_state *b=(private_state*)v->backend_state;
  106876. /* free header, header1, header2 */
  106877. if(b->header)_ogg_free(b->header);b->header=NULL;
  106878. if(b->header1)_ogg_free(b->header1);b->header1=NULL;
  106879. if(b->header2)_ogg_free(b->header2);b->header2=NULL;
  106880. /* Do we have enough storage space for the requested buffer? If not,
  106881. expand the PCM (and envelope) storage */
  106882. if(v->pcm_current+vals>=v->pcm_storage){
  106883. v->pcm_storage=v->pcm_current+vals*2;
  106884. for(i=0;i<vi->channels;i++){
  106885. v->pcm[i]=(float*)_ogg_realloc(v->pcm[i],v->pcm_storage*sizeof(*v->pcm[i]));
  106886. }
  106887. }
  106888. for(i=0;i<vi->channels;i++)
  106889. v->pcmret[i]=v->pcm[i]+v->pcm_current;
  106890. return(v->pcmret);
  106891. }
  106892. static void _preextrapolate_helper(vorbis_dsp_state *v){
  106893. int i;
  106894. int order=32;
  106895. float *lpc=(float*)alloca(order*sizeof(*lpc));
  106896. float *work=(float*)alloca(v->pcm_current*sizeof(*work));
  106897. long j;
  106898. v->preextrapolate=1;
  106899. if(v->pcm_current-v->centerW>order*2){ /* safety */
  106900. for(i=0;i<v->vi->channels;i++){
  106901. /* need to run the extrapolation in reverse! */
  106902. for(j=0;j<v->pcm_current;j++)
  106903. work[j]=v->pcm[i][v->pcm_current-j-1];
  106904. /* prime as above */
  106905. vorbis_lpc_from_data(work,lpc,v->pcm_current-v->centerW,order);
  106906. /* run the predictor filter */
  106907. vorbis_lpc_predict(lpc,work+v->pcm_current-v->centerW-order,
  106908. order,
  106909. work+v->pcm_current-v->centerW,
  106910. v->centerW);
  106911. for(j=0;j<v->pcm_current;j++)
  106912. v->pcm[i][v->pcm_current-j-1]=work[j];
  106913. }
  106914. }
  106915. }
  106916. /* call with val<=0 to set eof */
  106917. int vorbis_analysis_wrote(vorbis_dsp_state *v, int vals){
  106918. vorbis_info *vi=v->vi;
  106919. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  106920. if(vals<=0){
  106921. int order=32;
  106922. int i;
  106923. float *lpc=(float*) alloca(order*sizeof(*lpc));
  106924. /* if it wasn't done earlier (very short sample) */
  106925. if(!v->preextrapolate)
  106926. _preextrapolate_helper(v);
  106927. /* We're encoding the end of the stream. Just make sure we have
  106928. [at least] a few full blocks of zeroes at the end. */
  106929. /* actually, we don't want zeroes; that could drop a large
  106930. amplitude off a cliff, creating spread spectrum noise that will
  106931. suck to encode. Extrapolate for the sake of cleanliness. */
  106932. vorbis_analysis_buffer(v,ci->blocksizes[1]*3);
  106933. v->eofflag=v->pcm_current;
  106934. v->pcm_current+=ci->blocksizes[1]*3;
  106935. for(i=0;i<vi->channels;i++){
  106936. if(v->eofflag>order*2){
  106937. /* extrapolate with LPC to fill in */
  106938. long n;
  106939. /* make a predictor filter */
  106940. n=v->eofflag;
  106941. if(n>ci->blocksizes[1])n=ci->blocksizes[1];
  106942. vorbis_lpc_from_data(v->pcm[i]+v->eofflag-n,lpc,n,order);
  106943. /* run the predictor filter */
  106944. vorbis_lpc_predict(lpc,v->pcm[i]+v->eofflag-order,order,
  106945. v->pcm[i]+v->eofflag,v->pcm_current-v->eofflag);
  106946. }else{
  106947. /* not enough data to extrapolate (unlikely to happen due to
  106948. guarding the overlap, but bulletproof in case that
  106949. assumtion goes away). zeroes will do. */
  106950. memset(v->pcm[i]+v->eofflag,0,
  106951. (v->pcm_current-v->eofflag)*sizeof(*v->pcm[i]));
  106952. }
  106953. }
  106954. }else{
  106955. if(v->pcm_current+vals>v->pcm_storage)
  106956. return(OV_EINVAL);
  106957. v->pcm_current+=vals;
  106958. /* we may want to reverse extrapolate the beginning of a stream
  106959. too... in case we're beginning on a cliff! */
  106960. /* clumsy, but simple. It only runs once, so simple is good. */
  106961. if(!v->preextrapolate && v->pcm_current-v->centerW>ci->blocksizes[1])
  106962. _preextrapolate_helper(v);
  106963. }
  106964. return(0);
  106965. }
  106966. /* do the deltas, envelope shaping, pre-echo and determine the size of
  106967. the next block on which to continue analysis */
  106968. int vorbis_analysis_blockout(vorbis_dsp_state *v,vorbis_block *vb){
  106969. int i;
  106970. vorbis_info *vi=v->vi;
  106971. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  106972. private_state *b=(private_state*)v->backend_state;
  106973. vorbis_look_psy_global *g=b->psy_g_look;
  106974. long beginW=v->centerW-ci->blocksizes[v->W]/2,centerNext;
  106975. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  106976. /* check to see if we're started... */
  106977. if(!v->preextrapolate)return(0);
  106978. /* check to see if we're done... */
  106979. if(v->eofflag==-1)return(0);
  106980. /* By our invariant, we have lW, W and centerW set. Search for
  106981. the next boundary so we can determine nW (the next window size)
  106982. which lets us compute the shape of the current block's window */
  106983. /* we do an envelope search even on a single blocksize; we may still
  106984. be throwing more bits at impulses, and envelope search handles
  106985. marking impulses too. */
  106986. {
  106987. long bp=_ve_envelope_search(v);
  106988. if(bp==-1){
  106989. if(v->eofflag==0)return(0); /* not enough data currently to search for a
  106990. full long block */
  106991. v->nW=0;
  106992. }else{
  106993. if(ci->blocksizes[0]==ci->blocksizes[1])
  106994. v->nW=0;
  106995. else
  106996. v->nW=bp;
  106997. }
  106998. }
  106999. centerNext=v->centerW+ci->blocksizes[v->W]/4+ci->blocksizes[v->nW]/4;
  107000. {
  107001. /* center of next block + next block maximum right side. */
  107002. long blockbound=centerNext+ci->blocksizes[v->nW]/2;
  107003. if(v->pcm_current<blockbound)return(0); /* not enough data yet;
  107004. although this check is
  107005. less strict that the
  107006. _ve_envelope_search,
  107007. the search is not run
  107008. if we only use one
  107009. block size */
  107010. }
  107011. /* fill in the block. Note that for a short window, lW and nW are *short*
  107012. regardless of actual settings in the stream */
  107013. _vorbis_block_ripcord(vb);
  107014. vb->lW=v->lW;
  107015. vb->W=v->W;
  107016. vb->nW=v->nW;
  107017. if(v->W){
  107018. if(!v->lW || !v->nW){
  107019. vbi->blocktype=BLOCKTYPE_TRANSITION;
  107020. /*fprintf(stderr,"-");*/
  107021. }else{
  107022. vbi->blocktype=BLOCKTYPE_LONG;
  107023. /*fprintf(stderr,"_");*/
  107024. }
  107025. }else{
  107026. if(_ve_envelope_mark(v)){
  107027. vbi->blocktype=BLOCKTYPE_IMPULSE;
  107028. /*fprintf(stderr,"|");*/
  107029. }else{
  107030. vbi->blocktype=BLOCKTYPE_PADDING;
  107031. /*fprintf(stderr,".");*/
  107032. }
  107033. }
  107034. vb->vd=v;
  107035. vb->sequence=v->sequence++;
  107036. vb->granulepos=v->granulepos;
  107037. vb->pcmend=ci->blocksizes[v->W];
  107038. /* copy the vectors; this uses the local storage in vb */
  107039. /* this tracks 'strongest peak' for later psychoacoustics */
  107040. /* moved to the global psy state; clean this mess up */
  107041. if(vbi->ampmax>g->ampmax)g->ampmax=vbi->ampmax;
  107042. g->ampmax=_vp_ampmax_decay(g->ampmax,v);
  107043. vbi->ampmax=g->ampmax;
  107044. vb->pcm=(float**)_vorbis_block_alloc(vb,sizeof(*vb->pcm)*vi->channels);
  107045. vbi->pcmdelay=(float**)_vorbis_block_alloc(vb,sizeof(*vbi->pcmdelay)*vi->channels);
  107046. for(i=0;i<vi->channels;i++){
  107047. vbi->pcmdelay[i]=
  107048. (float*) _vorbis_block_alloc(vb,(vb->pcmend+beginW)*sizeof(*vbi->pcmdelay[i]));
  107049. memcpy(vbi->pcmdelay[i],v->pcm[i],(vb->pcmend+beginW)*sizeof(*vbi->pcmdelay[i]));
  107050. vb->pcm[i]=vbi->pcmdelay[i]+beginW;
  107051. /* before we added the delay
  107052. vb->pcm[i]=_vorbis_block_alloc(vb,vb->pcmend*sizeof(*vb->pcm[i]));
  107053. memcpy(vb->pcm[i],v->pcm[i]+beginW,ci->blocksizes[v->W]*sizeof(*vb->pcm[i]));
  107054. */
  107055. }
  107056. /* handle eof detection: eof==0 means that we've not yet received EOF
  107057. eof>0 marks the last 'real' sample in pcm[]
  107058. eof<0 'no more to do'; doesn't get here */
  107059. if(v->eofflag){
  107060. if(v->centerW>=v->eofflag){
  107061. v->eofflag=-1;
  107062. vb->eofflag=1;
  107063. return(1);
  107064. }
  107065. }
  107066. /* advance storage vectors and clean up */
  107067. {
  107068. int new_centerNext=ci->blocksizes[1]/2;
  107069. int movementW=centerNext-new_centerNext;
  107070. if(movementW>0){
  107071. _ve_envelope_shift(b->ve,movementW);
  107072. v->pcm_current-=movementW;
  107073. for(i=0;i<vi->channels;i++)
  107074. memmove(v->pcm[i],v->pcm[i]+movementW,
  107075. v->pcm_current*sizeof(*v->pcm[i]));
  107076. v->lW=v->W;
  107077. v->W=v->nW;
  107078. v->centerW=new_centerNext;
  107079. if(v->eofflag){
  107080. v->eofflag-=movementW;
  107081. if(v->eofflag<=0)v->eofflag=-1;
  107082. /* do not add padding to end of stream! */
  107083. if(v->centerW>=v->eofflag){
  107084. v->granulepos+=movementW-(v->centerW-v->eofflag);
  107085. }else{
  107086. v->granulepos+=movementW;
  107087. }
  107088. }else{
  107089. v->granulepos+=movementW;
  107090. }
  107091. }
  107092. }
  107093. /* done */
  107094. return(1);
  107095. }
  107096. int vorbis_synthesis_restart(vorbis_dsp_state *v){
  107097. vorbis_info *vi=v->vi;
  107098. codec_setup_info *ci;
  107099. int hs;
  107100. if(!v->backend_state)return -1;
  107101. if(!vi)return -1;
  107102. ci=(codec_setup_info*) vi->codec_setup;
  107103. if(!ci)return -1;
  107104. hs=ci->halfrate_flag;
  107105. v->centerW=ci->blocksizes[1]>>(hs+1);
  107106. v->pcm_current=v->centerW>>hs;
  107107. v->pcm_returned=-1;
  107108. v->granulepos=-1;
  107109. v->sequence=-1;
  107110. v->eofflag=0;
  107111. ((private_state *)(v->backend_state))->sample_count=-1;
  107112. return(0);
  107113. }
  107114. int vorbis_synthesis_init(vorbis_dsp_state *v,vorbis_info *vi){
  107115. if(_vds_shared_init(v,vi,0)) return 1;
  107116. vorbis_synthesis_restart(v);
  107117. return 0;
  107118. }
  107119. /* Unlike in analysis, the window is only partially applied for each
  107120. block. The time domain envelope is not yet handled at the point of
  107121. calling (as it relies on the previous block). */
  107122. int vorbis_synthesis_blockin(vorbis_dsp_state *v,vorbis_block *vb){
  107123. vorbis_info *vi=v->vi;
  107124. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  107125. private_state *b=(private_state*)v->backend_state;
  107126. int hs=ci->halfrate_flag;
  107127. int i,j;
  107128. if(!vb)return(OV_EINVAL);
  107129. if(v->pcm_current>v->pcm_returned && v->pcm_returned!=-1)return(OV_EINVAL);
  107130. v->lW=v->W;
  107131. v->W=vb->W;
  107132. v->nW=-1;
  107133. if((v->sequence==-1)||
  107134. (v->sequence+1 != vb->sequence)){
  107135. v->granulepos=-1; /* out of sequence; lose count */
  107136. b->sample_count=-1;
  107137. }
  107138. v->sequence=vb->sequence;
  107139. if(vb->pcm){ /* no pcm to process if vorbis_synthesis_trackonly
  107140. was called on block */
  107141. int n=ci->blocksizes[v->W]>>(hs+1);
  107142. int n0=ci->blocksizes[0]>>(hs+1);
  107143. int n1=ci->blocksizes[1]>>(hs+1);
  107144. int thisCenter;
  107145. int prevCenter;
  107146. v->glue_bits+=vb->glue_bits;
  107147. v->time_bits+=vb->time_bits;
  107148. v->floor_bits+=vb->floor_bits;
  107149. v->res_bits+=vb->res_bits;
  107150. if(v->centerW){
  107151. thisCenter=n1;
  107152. prevCenter=0;
  107153. }else{
  107154. thisCenter=0;
  107155. prevCenter=n1;
  107156. }
  107157. /* v->pcm is now used like a two-stage double buffer. We don't want
  107158. to have to constantly shift *or* adjust memory usage. Don't
  107159. accept a new block until the old is shifted out */
  107160. for(j=0;j<vi->channels;j++){
  107161. /* the overlap/add section */
  107162. if(v->lW){
  107163. if(v->W){
  107164. /* large/large */
  107165. float *w=_vorbis_window_get(b->window[1]-hs);
  107166. float *pcm=v->pcm[j]+prevCenter;
  107167. float *p=vb->pcm[j];
  107168. for(i=0;i<n1;i++)
  107169. pcm[i]=pcm[i]*w[n1-i-1] + p[i]*w[i];
  107170. }else{
  107171. /* large/small */
  107172. float *w=_vorbis_window_get(b->window[0]-hs);
  107173. float *pcm=v->pcm[j]+prevCenter+n1/2-n0/2;
  107174. float *p=vb->pcm[j];
  107175. for(i=0;i<n0;i++)
  107176. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  107177. }
  107178. }else{
  107179. if(v->W){
  107180. /* small/large */
  107181. float *w=_vorbis_window_get(b->window[0]-hs);
  107182. float *pcm=v->pcm[j]+prevCenter;
  107183. float *p=vb->pcm[j]+n1/2-n0/2;
  107184. for(i=0;i<n0;i++)
  107185. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  107186. for(;i<n1/2+n0/2;i++)
  107187. pcm[i]=p[i];
  107188. }else{
  107189. /* small/small */
  107190. float *w=_vorbis_window_get(b->window[0]-hs);
  107191. float *pcm=v->pcm[j]+prevCenter;
  107192. float *p=vb->pcm[j];
  107193. for(i=0;i<n0;i++)
  107194. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  107195. }
  107196. }
  107197. /* the copy section */
  107198. {
  107199. float *pcm=v->pcm[j]+thisCenter;
  107200. float *p=vb->pcm[j]+n;
  107201. for(i=0;i<n;i++)
  107202. pcm[i]=p[i];
  107203. }
  107204. }
  107205. if(v->centerW)
  107206. v->centerW=0;
  107207. else
  107208. v->centerW=n1;
  107209. /* deal with initial packet state; we do this using the explicit
  107210. pcm_returned==-1 flag otherwise we're sensitive to first block
  107211. being short or long */
  107212. if(v->pcm_returned==-1){
  107213. v->pcm_returned=thisCenter;
  107214. v->pcm_current=thisCenter;
  107215. }else{
  107216. v->pcm_returned=prevCenter;
  107217. v->pcm_current=prevCenter+
  107218. ((ci->blocksizes[v->lW]/4+
  107219. ci->blocksizes[v->W]/4)>>hs);
  107220. }
  107221. }
  107222. /* track the frame number... This is for convenience, but also
  107223. making sure our last packet doesn't end with added padding. If
  107224. the last packet is partial, the number of samples we'll have to
  107225. return will be past the vb->granulepos.
  107226. This is not foolproof! It will be confused if we begin
  107227. decoding at the last page after a seek or hole. In that case,
  107228. we don't have a starting point to judge where the last frame
  107229. is. For this reason, vorbisfile will always try to make sure
  107230. it reads the last two marked pages in proper sequence */
  107231. if(b->sample_count==-1){
  107232. b->sample_count=0;
  107233. }else{
  107234. b->sample_count+=ci->blocksizes[v->lW]/4+ci->blocksizes[v->W]/4;
  107235. }
  107236. if(v->granulepos==-1){
  107237. if(vb->granulepos!=-1){ /* only set if we have a position to set to */
  107238. v->granulepos=vb->granulepos;
  107239. /* is this a short page? */
  107240. if(b->sample_count>v->granulepos){
  107241. /* corner case; if this is both the first and last audio page,
  107242. then spec says the end is cut, not beginning */
  107243. if(vb->eofflag){
  107244. /* trim the end */
  107245. /* no preceeding granulepos; assume we started at zero (we'd
  107246. have to in a short single-page stream) */
  107247. /* granulepos could be -1 due to a seek, but that would result
  107248. in a long count, not short count */
  107249. v->pcm_current-=(b->sample_count-v->granulepos)>>hs;
  107250. }else{
  107251. /* trim the beginning */
  107252. v->pcm_returned+=(b->sample_count-v->granulepos)>>hs;
  107253. if(v->pcm_returned>v->pcm_current)
  107254. v->pcm_returned=v->pcm_current;
  107255. }
  107256. }
  107257. }
  107258. }else{
  107259. v->granulepos+=ci->blocksizes[v->lW]/4+ci->blocksizes[v->W]/4;
  107260. if(vb->granulepos!=-1 && v->granulepos!=vb->granulepos){
  107261. if(v->granulepos>vb->granulepos){
  107262. long extra=v->granulepos-vb->granulepos;
  107263. if(extra)
  107264. if(vb->eofflag){
  107265. /* partial last frame. Strip the extra samples off */
  107266. v->pcm_current-=extra>>hs;
  107267. } /* else {Shouldn't happen *unless* the bitstream is out of
  107268. spec. Either way, believe the bitstream } */
  107269. } /* else {Shouldn't happen *unless* the bitstream is out of
  107270. spec. Either way, believe the bitstream } */
  107271. v->granulepos=vb->granulepos;
  107272. }
  107273. }
  107274. /* Update, cleanup */
  107275. if(vb->eofflag)v->eofflag=1;
  107276. return(0);
  107277. }
  107278. /* pcm==NULL indicates we just want the pending samples, no more */
  107279. int vorbis_synthesis_pcmout(vorbis_dsp_state *v,float ***pcm){
  107280. vorbis_info *vi=v->vi;
  107281. if(v->pcm_returned>-1 && v->pcm_returned<v->pcm_current){
  107282. if(pcm){
  107283. int i;
  107284. for(i=0;i<vi->channels;i++)
  107285. v->pcmret[i]=v->pcm[i]+v->pcm_returned;
  107286. *pcm=v->pcmret;
  107287. }
  107288. return(v->pcm_current-v->pcm_returned);
  107289. }
  107290. return(0);
  107291. }
  107292. int vorbis_synthesis_read(vorbis_dsp_state *v,int n){
  107293. if(n && v->pcm_returned+n>v->pcm_current)return(OV_EINVAL);
  107294. v->pcm_returned+=n;
  107295. return(0);
  107296. }
  107297. /* intended for use with a specific vorbisfile feature; we want access
  107298. to the [usually synthetic/postextrapolated] buffer and lapping at
  107299. the end of a decode cycle, specifically, a half-short-block worth.
  107300. This funtion works like pcmout above, except it will also expose
  107301. this implicit buffer data not normally decoded. */
  107302. int vorbis_synthesis_lapout(vorbis_dsp_state *v,float ***pcm){
  107303. vorbis_info *vi=v->vi;
  107304. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  107305. int hs=ci->halfrate_flag;
  107306. int n=ci->blocksizes[v->W]>>(hs+1);
  107307. int n0=ci->blocksizes[0]>>(hs+1);
  107308. int n1=ci->blocksizes[1]>>(hs+1);
  107309. int i,j;
  107310. if(v->pcm_returned<0)return 0;
  107311. /* our returned data ends at pcm_returned; because the synthesis pcm
  107312. buffer is a two-fragment ring, that means our data block may be
  107313. fragmented by buffering, wrapping or a short block not filling
  107314. out a buffer. To simplify things, we unfragment if it's at all
  107315. possibly needed. Otherwise, we'd need to call lapout more than
  107316. once as well as hold additional dsp state. Opt for
  107317. simplicity. */
  107318. /* centerW was advanced by blockin; it would be the center of the
  107319. *next* block */
  107320. if(v->centerW==n1){
  107321. /* the data buffer wraps; swap the halves */
  107322. /* slow, sure, small */
  107323. for(j=0;j<vi->channels;j++){
  107324. float *p=v->pcm[j];
  107325. for(i=0;i<n1;i++){
  107326. float temp=p[i];
  107327. p[i]=p[i+n1];
  107328. p[i+n1]=temp;
  107329. }
  107330. }
  107331. v->pcm_current-=n1;
  107332. v->pcm_returned-=n1;
  107333. v->centerW=0;
  107334. }
  107335. /* solidify buffer into contiguous space */
  107336. if((v->lW^v->W)==1){
  107337. /* long/short or short/long */
  107338. for(j=0;j<vi->channels;j++){
  107339. float *s=v->pcm[j];
  107340. float *d=v->pcm[j]+(n1-n0)/2;
  107341. for(i=(n1+n0)/2-1;i>=0;--i)
  107342. d[i]=s[i];
  107343. }
  107344. v->pcm_returned+=(n1-n0)/2;
  107345. v->pcm_current+=(n1-n0)/2;
  107346. }else{
  107347. if(v->lW==0){
  107348. /* short/short */
  107349. for(j=0;j<vi->channels;j++){
  107350. float *s=v->pcm[j];
  107351. float *d=v->pcm[j]+n1-n0;
  107352. for(i=n0-1;i>=0;--i)
  107353. d[i]=s[i];
  107354. }
  107355. v->pcm_returned+=n1-n0;
  107356. v->pcm_current+=n1-n0;
  107357. }
  107358. }
  107359. if(pcm){
  107360. int i;
  107361. for(i=0;i<vi->channels;i++)
  107362. v->pcmret[i]=v->pcm[i]+v->pcm_returned;
  107363. *pcm=v->pcmret;
  107364. }
  107365. return(n1+n-v->pcm_returned);
  107366. }
  107367. float *vorbis_window(vorbis_dsp_state *v,int W){
  107368. vorbis_info *vi=v->vi;
  107369. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  107370. int hs=ci->halfrate_flag;
  107371. private_state *b=(private_state*)v->backend_state;
  107372. if(b->window[W]-1<0)return NULL;
  107373. return _vorbis_window_get(b->window[W]-hs);
  107374. }
  107375. #endif
  107376. /********* End of inlined file: block.c *********/
  107377. /********* Start of inlined file: codebook.c *********/
  107378. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  107379. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  107380. // tasks..
  107381. #ifdef _MSC_VER
  107382. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  107383. #endif
  107384. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  107385. #if JUCE_USE_OGGVORBIS
  107386. #include <stdlib.h>
  107387. #include <string.h>
  107388. #include <math.h>
  107389. /* packs the given codebook into the bitstream **************************/
  107390. int vorbis_staticbook_pack(const static_codebook *c,oggpack_buffer *opb){
  107391. long i,j;
  107392. int ordered=0;
  107393. /* first the basic parameters */
  107394. oggpack_write(opb,0x564342,24);
  107395. oggpack_write(opb,c->dim,16);
  107396. oggpack_write(opb,c->entries,24);
  107397. /* pack the codewords. There are two packings; length ordered and
  107398. length random. Decide between the two now. */
  107399. for(i=1;i<c->entries;i++)
  107400. if(c->lengthlist[i-1]==0 || c->lengthlist[i]<c->lengthlist[i-1])break;
  107401. if(i==c->entries)ordered=1;
  107402. if(ordered){
  107403. /* length ordered. We only need to say how many codewords of
  107404. each length. The actual codewords are generated
  107405. deterministically */
  107406. long count=0;
  107407. oggpack_write(opb,1,1); /* ordered */
  107408. oggpack_write(opb,c->lengthlist[0]-1,5); /* 1 to 32 */
  107409. for(i=1;i<c->entries;i++){
  107410. long thisx=c->lengthlist[i];
  107411. long last=c->lengthlist[i-1];
  107412. if(thisx>last){
  107413. for(j=last;j<thisx;j++){
  107414. oggpack_write(opb,i-count,_ilog(c->entries-count));
  107415. count=i;
  107416. }
  107417. }
  107418. }
  107419. oggpack_write(opb,i-count,_ilog(c->entries-count));
  107420. }else{
  107421. /* length random. Again, we don't code the codeword itself, just
  107422. the length. This time, though, we have to encode each length */
  107423. oggpack_write(opb,0,1); /* unordered */
  107424. /* algortihmic mapping has use for 'unused entries', which we tag
  107425. here. The algorithmic mapping happens as usual, but the unused
  107426. entry has no codeword. */
  107427. for(i=0;i<c->entries;i++)
  107428. if(c->lengthlist[i]==0)break;
  107429. if(i==c->entries){
  107430. oggpack_write(opb,0,1); /* no unused entries */
  107431. for(i=0;i<c->entries;i++)
  107432. oggpack_write(opb,c->lengthlist[i]-1,5);
  107433. }else{
  107434. oggpack_write(opb,1,1); /* we have unused entries; thus we tag */
  107435. for(i=0;i<c->entries;i++){
  107436. if(c->lengthlist[i]==0){
  107437. oggpack_write(opb,0,1);
  107438. }else{
  107439. oggpack_write(opb,1,1);
  107440. oggpack_write(opb,c->lengthlist[i]-1,5);
  107441. }
  107442. }
  107443. }
  107444. }
  107445. /* is the entry number the desired return value, or do we have a
  107446. mapping? If we have a mapping, what type? */
  107447. oggpack_write(opb,c->maptype,4);
  107448. switch(c->maptype){
  107449. case 0:
  107450. /* no mapping */
  107451. break;
  107452. case 1:case 2:
  107453. /* implicitly populated value mapping */
  107454. /* explicitly populated value mapping */
  107455. if(!c->quantlist){
  107456. /* no quantlist? error */
  107457. return(-1);
  107458. }
  107459. /* values that define the dequantization */
  107460. oggpack_write(opb,c->q_min,32);
  107461. oggpack_write(opb,c->q_delta,32);
  107462. oggpack_write(opb,c->q_quant-1,4);
  107463. oggpack_write(opb,c->q_sequencep,1);
  107464. {
  107465. int quantvals;
  107466. switch(c->maptype){
  107467. case 1:
  107468. /* a single column of (c->entries/c->dim) quantized values for
  107469. building a full value list algorithmically (square lattice) */
  107470. quantvals=_book_maptype1_quantvals(c);
  107471. break;
  107472. case 2:
  107473. /* every value (c->entries*c->dim total) specified explicitly */
  107474. quantvals=c->entries*c->dim;
  107475. break;
  107476. default: /* NOT_REACHABLE */
  107477. quantvals=-1;
  107478. }
  107479. /* quantized values */
  107480. for(i=0;i<quantvals;i++)
  107481. oggpack_write(opb,labs(c->quantlist[i]),c->q_quant);
  107482. }
  107483. break;
  107484. default:
  107485. /* error case; we don't have any other map types now */
  107486. return(-1);
  107487. }
  107488. return(0);
  107489. }
  107490. /* unpacks a codebook from the packet buffer into the codebook struct,
  107491. readies the codebook auxiliary structures for decode *************/
  107492. int vorbis_staticbook_unpack(oggpack_buffer *opb,static_codebook *s){
  107493. long i,j;
  107494. memset(s,0,sizeof(*s));
  107495. s->allocedp=1;
  107496. /* make sure alignment is correct */
  107497. if(oggpack_read(opb,24)!=0x564342)goto _eofout;
  107498. /* first the basic parameters */
  107499. s->dim=oggpack_read(opb,16);
  107500. s->entries=oggpack_read(opb,24);
  107501. if(s->entries==-1)goto _eofout;
  107502. /* codeword ordering.... length ordered or unordered? */
  107503. switch((int)oggpack_read(opb,1)){
  107504. case 0:
  107505. /* unordered */
  107506. s->lengthlist=(long*)_ogg_malloc(sizeof(*s->lengthlist)*s->entries);
  107507. /* allocated but unused entries? */
  107508. if(oggpack_read(opb,1)){
  107509. /* yes, unused entries */
  107510. for(i=0;i<s->entries;i++){
  107511. if(oggpack_read(opb,1)){
  107512. long num=oggpack_read(opb,5);
  107513. if(num==-1)goto _eofout;
  107514. s->lengthlist[i]=num+1;
  107515. }else
  107516. s->lengthlist[i]=0;
  107517. }
  107518. }else{
  107519. /* all entries used; no tagging */
  107520. for(i=0;i<s->entries;i++){
  107521. long num=oggpack_read(opb,5);
  107522. if(num==-1)goto _eofout;
  107523. s->lengthlist[i]=num+1;
  107524. }
  107525. }
  107526. break;
  107527. case 1:
  107528. /* ordered */
  107529. {
  107530. long length=oggpack_read(opb,5)+1;
  107531. s->lengthlist=(long*)_ogg_malloc(sizeof(*s->lengthlist)*s->entries);
  107532. for(i=0;i<s->entries;){
  107533. long num=oggpack_read(opb,_ilog(s->entries-i));
  107534. if(num==-1)goto _eofout;
  107535. for(j=0;j<num && i<s->entries;j++,i++)
  107536. s->lengthlist[i]=length;
  107537. length++;
  107538. }
  107539. }
  107540. break;
  107541. default:
  107542. /* EOF */
  107543. return(-1);
  107544. }
  107545. /* Do we have a mapping to unpack? */
  107546. switch((s->maptype=oggpack_read(opb,4))){
  107547. case 0:
  107548. /* no mapping */
  107549. break;
  107550. case 1: case 2:
  107551. /* implicitly populated value mapping */
  107552. /* explicitly populated value mapping */
  107553. s->q_min=oggpack_read(opb,32);
  107554. s->q_delta=oggpack_read(opb,32);
  107555. s->q_quant=oggpack_read(opb,4)+1;
  107556. s->q_sequencep=oggpack_read(opb,1);
  107557. {
  107558. int quantvals=0;
  107559. switch(s->maptype){
  107560. case 1:
  107561. quantvals=_book_maptype1_quantvals(s);
  107562. break;
  107563. case 2:
  107564. quantvals=s->entries*s->dim;
  107565. break;
  107566. }
  107567. /* quantized values */
  107568. s->quantlist=(long*)_ogg_malloc(sizeof(*s->quantlist)*quantvals);
  107569. for(i=0;i<quantvals;i++)
  107570. s->quantlist[i]=oggpack_read(opb,s->q_quant);
  107571. if(quantvals&&s->quantlist[quantvals-1]==-1)goto _eofout;
  107572. }
  107573. break;
  107574. default:
  107575. goto _errout;
  107576. }
  107577. /* all set */
  107578. return(0);
  107579. _errout:
  107580. _eofout:
  107581. vorbis_staticbook_clear(s);
  107582. return(-1);
  107583. }
  107584. /* returns the number of bits ************************************************/
  107585. int vorbis_book_encode(codebook *book, int a, oggpack_buffer *b){
  107586. oggpack_write(b,book->codelist[a],book->c->lengthlist[a]);
  107587. return(book->c->lengthlist[a]);
  107588. }
  107589. /* One the encode side, our vector writers are each designed for a
  107590. specific purpose, and the encoder is not flexible without modification:
  107591. The LSP vector coder uses a single stage nearest-match with no
  107592. interleave, so no step and no error return. This is specced by floor0
  107593. and doesn't change.
  107594. Residue0 encoding interleaves, uses multiple stages, and each stage
  107595. peels of a specific amount of resolution from a lattice (thus we want
  107596. to match by threshold, not nearest match). Residue doesn't *have* to
  107597. be encoded that way, but to change it, one will need to add more
  107598. infrastructure on the encode side (decode side is specced and simpler) */
  107599. /* floor0 LSP (single stage, non interleaved, nearest match) */
  107600. /* returns entry number and *modifies a* to the quantization value *****/
  107601. int vorbis_book_errorv(codebook *book,float *a){
  107602. int dim=book->dim,k;
  107603. int best=_best(book,a,1);
  107604. for(k=0;k<dim;k++)
  107605. a[k]=(book->valuelist+best*dim)[k];
  107606. return(best);
  107607. }
  107608. /* returns the number of bits and *modifies a* to the quantization value *****/
  107609. int vorbis_book_encodev(codebook *book,int best,float *a,oggpack_buffer *b){
  107610. int k,dim=book->dim;
  107611. for(k=0;k<dim;k++)
  107612. a[k]=(book->valuelist+best*dim)[k];
  107613. return(vorbis_book_encode(book,best,b));
  107614. }
  107615. /* the 'eliminate the decode tree' optimization actually requires the
  107616. codewords to be MSb first, not LSb. This is an annoying inelegancy
  107617. (and one of the first places where carefully thought out design
  107618. turned out to be wrong; Vorbis II and future Ogg codecs should go
  107619. to an MSb bitpacker), but not actually the huge hit it appears to
  107620. be. The first-stage decode table catches most words so that
  107621. bitreverse is not in the main execution path. */
  107622. STIN long decode_packed_entry_number(codebook *book, oggpack_buffer *b){
  107623. int read=book->dec_maxlength;
  107624. long lo,hi;
  107625. long lok = oggpack_look(b,book->dec_firsttablen);
  107626. if (lok >= 0) {
  107627. long entry = book->dec_firsttable[lok];
  107628. if(entry&0x80000000UL){
  107629. lo=(entry>>15)&0x7fff;
  107630. hi=book->used_entries-(entry&0x7fff);
  107631. }else{
  107632. oggpack_adv(b, book->dec_codelengths[entry-1]);
  107633. return(entry-1);
  107634. }
  107635. }else{
  107636. lo=0;
  107637. hi=book->used_entries;
  107638. }
  107639. lok = oggpack_look(b, read);
  107640. while(lok<0 && read>1)
  107641. lok = oggpack_look(b, --read);
  107642. if(lok<0)return -1;
  107643. /* bisect search for the codeword in the ordered list */
  107644. {
  107645. ogg_uint32_t testword=ogg_bitreverse((ogg_uint32_t)lok);
  107646. while(hi-lo>1){
  107647. long p=(hi-lo)>>1;
  107648. long test=book->codelist[lo+p]>testword;
  107649. lo+=p&(test-1);
  107650. hi-=p&(-test);
  107651. }
  107652. if(book->dec_codelengths[lo]<=read){
  107653. oggpack_adv(b, book->dec_codelengths[lo]);
  107654. return(lo);
  107655. }
  107656. }
  107657. oggpack_adv(b, read);
  107658. return(-1);
  107659. }
  107660. /* Decode side is specced and easier, because we don't need to find
  107661. matches using different criteria; we simply read and map. There are
  107662. two things we need to do 'depending':
  107663. We may need to support interleave. We don't really, but it's
  107664. convenient to do it here rather than rebuild the vector later.
  107665. Cascades may be additive or multiplicitive; this is not inherent in
  107666. the codebook, but set in the code using the codebook. Like
  107667. interleaving, it's easiest to do it here.
  107668. addmul==0 -> declarative (set the value)
  107669. addmul==1 -> additive
  107670. addmul==2 -> multiplicitive */
  107671. /* returns the [original, not compacted] entry number or -1 on eof *********/
  107672. long vorbis_book_decode(codebook *book, oggpack_buffer *b){
  107673. long packed_entry=decode_packed_entry_number(book,b);
  107674. if(packed_entry>=0)
  107675. return(book->dec_index[packed_entry]);
  107676. /* if there's no dec_index, the codebook unpacking isn't collapsed */
  107677. return(packed_entry);
  107678. }
  107679. /* returns 0 on OK or -1 on eof *************************************/
  107680. long vorbis_book_decodevs_add(codebook *book,float *a,oggpack_buffer *b,int n){
  107681. int step=n/book->dim;
  107682. long *entry = (long*)alloca(sizeof(*entry)*step);
  107683. float **t = (float**)alloca(sizeof(*t)*step);
  107684. int i,j,o;
  107685. for (i = 0; i < step; i++) {
  107686. entry[i]=decode_packed_entry_number(book,b);
  107687. if(entry[i]==-1)return(-1);
  107688. t[i] = book->valuelist+entry[i]*book->dim;
  107689. }
  107690. for(i=0,o=0;i<book->dim;i++,o+=step)
  107691. for (j=0;j<step;j++)
  107692. a[o+j]+=t[j][i];
  107693. return(0);
  107694. }
  107695. long vorbis_book_decodev_add(codebook *book,float *a,oggpack_buffer *b,int n){
  107696. int i,j,entry;
  107697. float *t;
  107698. if(book->dim>8){
  107699. for(i=0;i<n;){
  107700. entry = decode_packed_entry_number(book,b);
  107701. if(entry==-1)return(-1);
  107702. t = book->valuelist+entry*book->dim;
  107703. for (j=0;j<book->dim;)
  107704. a[i++]+=t[j++];
  107705. }
  107706. }else{
  107707. for(i=0;i<n;){
  107708. entry = decode_packed_entry_number(book,b);
  107709. if(entry==-1)return(-1);
  107710. t = book->valuelist+entry*book->dim;
  107711. j=0;
  107712. switch((int)book->dim){
  107713. case 8:
  107714. a[i++]+=t[j++];
  107715. case 7:
  107716. a[i++]+=t[j++];
  107717. case 6:
  107718. a[i++]+=t[j++];
  107719. case 5:
  107720. a[i++]+=t[j++];
  107721. case 4:
  107722. a[i++]+=t[j++];
  107723. case 3:
  107724. a[i++]+=t[j++];
  107725. case 2:
  107726. a[i++]+=t[j++];
  107727. case 1:
  107728. a[i++]+=t[j++];
  107729. case 0:
  107730. break;
  107731. }
  107732. }
  107733. }
  107734. return(0);
  107735. }
  107736. long vorbis_book_decodev_set(codebook *book,float *a,oggpack_buffer *b,int n){
  107737. int i,j,entry;
  107738. float *t;
  107739. for(i=0;i<n;){
  107740. entry = decode_packed_entry_number(book,b);
  107741. if(entry==-1)return(-1);
  107742. t = book->valuelist+entry*book->dim;
  107743. for (j=0;j<book->dim;)
  107744. a[i++]=t[j++];
  107745. }
  107746. return(0);
  107747. }
  107748. long vorbis_book_decodevv_add(codebook *book,float **a,long offset,int ch,
  107749. oggpack_buffer *b,int n){
  107750. long i,j,entry;
  107751. int chptr=0;
  107752. for(i=offset/ch;i<(offset+n)/ch;){
  107753. entry = decode_packed_entry_number(book,b);
  107754. if(entry==-1)return(-1);
  107755. {
  107756. const float *t = book->valuelist+entry*book->dim;
  107757. for (j=0;j<book->dim;j++){
  107758. a[chptr++][i]+=t[j];
  107759. if(chptr==ch){
  107760. chptr=0;
  107761. i++;
  107762. }
  107763. }
  107764. }
  107765. }
  107766. return(0);
  107767. }
  107768. #ifdef _V_SELFTEST
  107769. /* Simple enough; pack a few candidate codebooks, unpack them. Code a
  107770. number of vectors through (keeping track of the quantized values),
  107771. and decode using the unpacked book. quantized version of in should
  107772. exactly equal out */
  107773. #include <stdio.h>
  107774. #include "vorbis/book/lsp20_0.vqh"
  107775. #include "vorbis/book/res0a_13.vqh"
  107776. #define TESTSIZE 40
  107777. float test1[TESTSIZE]={
  107778. 0.105939f,
  107779. 0.215373f,
  107780. 0.429117f,
  107781. 0.587974f,
  107782. 0.181173f,
  107783. 0.296583f,
  107784. 0.515707f,
  107785. 0.715261f,
  107786. 0.162327f,
  107787. 0.263834f,
  107788. 0.342876f,
  107789. 0.406025f,
  107790. 0.103571f,
  107791. 0.223561f,
  107792. 0.368513f,
  107793. 0.540313f,
  107794. 0.136672f,
  107795. 0.395882f,
  107796. 0.587183f,
  107797. 0.652476f,
  107798. 0.114338f,
  107799. 0.417300f,
  107800. 0.525486f,
  107801. 0.698679f,
  107802. 0.147492f,
  107803. 0.324481f,
  107804. 0.643089f,
  107805. 0.757582f,
  107806. 0.139556f,
  107807. 0.215795f,
  107808. 0.324559f,
  107809. 0.399387f,
  107810. 0.120236f,
  107811. 0.267420f,
  107812. 0.446940f,
  107813. 0.608760f,
  107814. 0.115587f,
  107815. 0.287234f,
  107816. 0.571081f,
  107817. 0.708603f,
  107818. };
  107819. float test3[TESTSIZE]={
  107820. 0,1,-2,3,4,-5,6,7,8,9,
  107821. 8,-2,7,-1,4,6,8,3,1,-9,
  107822. 10,11,12,13,14,15,26,17,18,19,
  107823. 30,-25,-30,-1,-5,-32,4,3,-2,0};
  107824. static_codebook *testlist[]={&_vq_book_lsp20_0,
  107825. &_vq_book_res0a_13,NULL};
  107826. float *testvec[]={test1,test3};
  107827. int main(){
  107828. oggpack_buffer write;
  107829. oggpack_buffer read;
  107830. long ptr=0,i;
  107831. oggpack_writeinit(&write);
  107832. fprintf(stderr,"Testing codebook abstraction...:\n");
  107833. while(testlist[ptr]){
  107834. codebook c;
  107835. static_codebook s;
  107836. float *qv=alloca(sizeof(*qv)*TESTSIZE);
  107837. float *iv=alloca(sizeof(*iv)*TESTSIZE);
  107838. memcpy(qv,testvec[ptr],sizeof(*qv)*TESTSIZE);
  107839. memset(iv,0,sizeof(*iv)*TESTSIZE);
  107840. fprintf(stderr,"\tpacking/coding %ld... ",ptr);
  107841. /* pack the codebook, write the testvector */
  107842. oggpack_reset(&write);
  107843. vorbis_book_init_encode(&c,testlist[ptr]); /* get it into memory
  107844. we can write */
  107845. vorbis_staticbook_pack(testlist[ptr],&write);
  107846. fprintf(stderr,"Codebook size %ld bytes... ",oggpack_bytes(&write));
  107847. for(i=0;i<TESTSIZE;i+=c.dim){
  107848. int best=_best(&c,qv+i,1);
  107849. vorbis_book_encodev(&c,best,qv+i,&write);
  107850. }
  107851. vorbis_book_clear(&c);
  107852. fprintf(stderr,"OK.\n");
  107853. fprintf(stderr,"\tunpacking/decoding %ld... ",ptr);
  107854. /* transfer the write data to a read buffer and unpack/read */
  107855. oggpack_readinit(&read,oggpack_get_buffer(&write),oggpack_bytes(&write));
  107856. if(vorbis_staticbook_unpack(&read,&s)){
  107857. fprintf(stderr,"Error unpacking codebook.\n");
  107858. exit(1);
  107859. }
  107860. if(vorbis_book_init_decode(&c,&s)){
  107861. fprintf(stderr,"Error initializing codebook.\n");
  107862. exit(1);
  107863. }
  107864. for(i=0;i<TESTSIZE;i+=c.dim)
  107865. if(vorbis_book_decodev_set(&c,iv+i,&read,c.dim)==-1){
  107866. fprintf(stderr,"Error reading codebook test data (EOP).\n");
  107867. exit(1);
  107868. }
  107869. for(i=0;i<TESTSIZE;i++)
  107870. if(fabs(qv[i]-iv[i])>.000001){
  107871. fprintf(stderr,"read (%g) != written (%g) at position (%ld)\n",
  107872. iv[i],qv[i],i);
  107873. exit(1);
  107874. }
  107875. fprintf(stderr,"OK\n");
  107876. ptr++;
  107877. }
  107878. /* The above is the trivial stuff; now try unquantizing a log scale codebook */
  107879. exit(0);
  107880. }
  107881. #endif
  107882. #endif
  107883. /********* End of inlined file: codebook.c *********/
  107884. /********* Start of inlined file: envelope.c *********/
  107885. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  107886. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  107887. // tasks..
  107888. #ifdef _MSC_VER
  107889. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  107890. #endif
  107891. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  107892. #if JUCE_USE_OGGVORBIS
  107893. #include <stdlib.h>
  107894. #include <string.h>
  107895. #include <stdio.h>
  107896. #include <math.h>
  107897. void _ve_envelope_init(envelope_lookup *e,vorbis_info *vi){
  107898. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  107899. vorbis_info_psy_global *gi=&ci->psy_g_param;
  107900. int ch=vi->channels;
  107901. int i,j;
  107902. int n=e->winlength=128;
  107903. e->searchstep=64; /* not random */
  107904. e->minenergy=gi->preecho_minenergy;
  107905. e->ch=ch;
  107906. e->storage=128;
  107907. e->cursor=ci->blocksizes[1]/2;
  107908. e->mdct_win=(float*)_ogg_calloc(n,sizeof(*e->mdct_win));
  107909. mdct_init(&e->mdct,n);
  107910. for(i=0;i<n;i++){
  107911. e->mdct_win[i]=sin(i/(n-1.)*M_PI);
  107912. e->mdct_win[i]*=e->mdct_win[i];
  107913. }
  107914. /* magic follows */
  107915. e->band[0].begin=2; e->band[0].end=4;
  107916. e->band[1].begin=4; e->band[1].end=5;
  107917. e->band[2].begin=6; e->band[2].end=6;
  107918. e->band[3].begin=9; e->band[3].end=8;
  107919. e->band[4].begin=13; e->band[4].end=8;
  107920. e->band[5].begin=17; e->band[5].end=8;
  107921. e->band[6].begin=22; e->band[6].end=8;
  107922. for(j=0;j<VE_BANDS;j++){
  107923. n=e->band[j].end;
  107924. e->band[j].window=(float*)_ogg_malloc(n*sizeof(*e->band[0].window));
  107925. for(i=0;i<n;i++){
  107926. e->band[j].window[i]=sin((i+.5)/n*M_PI);
  107927. e->band[j].total+=e->band[j].window[i];
  107928. }
  107929. e->band[j].total=1./e->band[j].total;
  107930. }
  107931. e->filter=(envelope_filter_state*)_ogg_calloc(VE_BANDS*ch,sizeof(*e->filter));
  107932. e->mark=(int*)_ogg_calloc(e->storage,sizeof(*e->mark));
  107933. }
  107934. void _ve_envelope_clear(envelope_lookup *e){
  107935. int i;
  107936. mdct_clear(&e->mdct);
  107937. for(i=0;i<VE_BANDS;i++)
  107938. _ogg_free(e->band[i].window);
  107939. _ogg_free(e->mdct_win);
  107940. _ogg_free(e->filter);
  107941. _ogg_free(e->mark);
  107942. memset(e,0,sizeof(*e));
  107943. }
  107944. /* fairly straight threshhold-by-band based until we find something
  107945. that works better and isn't patented. */
  107946. static int _ve_amp(envelope_lookup *ve,
  107947. vorbis_info_psy_global *gi,
  107948. float *data,
  107949. envelope_band *bands,
  107950. envelope_filter_state *filters,
  107951. long pos){
  107952. long n=ve->winlength;
  107953. int ret=0;
  107954. long i,j;
  107955. float decay;
  107956. /* we want to have a 'minimum bar' for energy, else we're just
  107957. basing blocks on quantization noise that outweighs the signal
  107958. itself (for low power signals) */
  107959. float minV=ve->minenergy;
  107960. float *vec=(float*) alloca(n*sizeof(*vec));
  107961. /* stretch is used to gradually lengthen the number of windows
  107962. considered prevoius-to-potential-trigger */
  107963. int stretch=max(VE_MINSTRETCH,ve->stretch/2);
  107964. float penalty=gi->stretch_penalty-(ve->stretch/2-VE_MINSTRETCH);
  107965. if(penalty<0.f)penalty=0.f;
  107966. if(penalty>gi->stretch_penalty)penalty=gi->stretch_penalty;
  107967. /*_analysis_output_always("lpcm",seq2,data,n,0,0,
  107968. totalshift+pos*ve->searchstep);*/
  107969. /* window and transform */
  107970. for(i=0;i<n;i++)
  107971. vec[i]=data[i]*ve->mdct_win[i];
  107972. mdct_forward(&ve->mdct,vec,vec);
  107973. /*_analysis_output_always("mdct",seq2,vec,n/2,0,1,0); */
  107974. /* near-DC spreading function; this has nothing to do with
  107975. psychoacoustics, just sidelobe leakage and window size */
  107976. {
  107977. float temp=vec[0]*vec[0]+.7*vec[1]*vec[1]+.2*vec[2]*vec[2];
  107978. int ptr=filters->nearptr;
  107979. /* the accumulation is regularly refreshed from scratch to avoid
  107980. floating point creep */
  107981. if(ptr==0){
  107982. decay=filters->nearDC_acc=filters->nearDC_partialacc+temp;
  107983. filters->nearDC_partialacc=temp;
  107984. }else{
  107985. decay=filters->nearDC_acc+=temp;
  107986. filters->nearDC_partialacc+=temp;
  107987. }
  107988. filters->nearDC_acc-=filters->nearDC[ptr];
  107989. filters->nearDC[ptr]=temp;
  107990. decay*=(1./(VE_NEARDC+1));
  107991. filters->nearptr++;
  107992. if(filters->nearptr>=VE_NEARDC)filters->nearptr=0;
  107993. decay=todB(&decay)*.5-15.f;
  107994. }
  107995. /* perform spreading and limiting, also smooth the spectrum. yes,
  107996. the MDCT results in all real coefficients, but it still *behaves*
  107997. like real/imaginary pairs */
  107998. for(i=0;i<n/2;i+=2){
  107999. float val=vec[i]*vec[i]+vec[i+1]*vec[i+1];
  108000. val=todB(&val)*.5f;
  108001. if(val<decay)val=decay;
  108002. if(val<minV)val=minV;
  108003. vec[i>>1]=val;
  108004. decay-=8.;
  108005. }
  108006. /*_analysis_output_always("spread",seq2++,vec,n/4,0,0,0);*/
  108007. /* perform preecho/postecho triggering by band */
  108008. for(j=0;j<VE_BANDS;j++){
  108009. float acc=0.;
  108010. float valmax,valmin;
  108011. /* accumulate amplitude */
  108012. for(i=0;i<bands[j].end;i++)
  108013. acc+=vec[i+bands[j].begin]*bands[j].window[i];
  108014. acc*=bands[j].total;
  108015. /* convert amplitude to delta */
  108016. {
  108017. int p,thisx=filters[j].ampptr;
  108018. float postmax,postmin,premax=-99999.f,premin=99999.f;
  108019. p=thisx;
  108020. p--;
  108021. if(p<0)p+=VE_AMP;
  108022. postmax=max(acc,filters[j].ampbuf[p]);
  108023. postmin=min(acc,filters[j].ampbuf[p]);
  108024. for(i=0;i<stretch;i++){
  108025. p--;
  108026. if(p<0)p+=VE_AMP;
  108027. premax=max(premax,filters[j].ampbuf[p]);
  108028. premin=min(premin,filters[j].ampbuf[p]);
  108029. }
  108030. valmin=postmin-premin;
  108031. valmax=postmax-premax;
  108032. /*filters[j].markers[pos]=valmax;*/
  108033. filters[j].ampbuf[thisx]=acc;
  108034. filters[j].ampptr++;
  108035. if(filters[j].ampptr>=VE_AMP)filters[j].ampptr=0;
  108036. }
  108037. /* look at min/max, decide trigger */
  108038. if(valmax>gi->preecho_thresh[j]+penalty){
  108039. ret|=1;
  108040. ret|=4;
  108041. }
  108042. if(valmin<gi->postecho_thresh[j]-penalty)ret|=2;
  108043. }
  108044. return(ret);
  108045. }
  108046. #if 0
  108047. static int seq=0;
  108048. static ogg_int64_t totalshift=-1024;
  108049. #endif
  108050. long _ve_envelope_search(vorbis_dsp_state *v){
  108051. vorbis_info *vi=v->vi;
  108052. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  108053. vorbis_info_psy_global *gi=&ci->psy_g_param;
  108054. envelope_lookup *ve=((private_state *)(v->backend_state))->ve;
  108055. long i,j;
  108056. int first=ve->current/ve->searchstep;
  108057. int last=v->pcm_current/ve->searchstep-VE_WIN;
  108058. if(first<0)first=0;
  108059. /* make sure we have enough storage to match the PCM */
  108060. if(last+VE_WIN+VE_POST>ve->storage){
  108061. ve->storage=last+VE_WIN+VE_POST; /* be sure */
  108062. ve->mark=(int*)_ogg_realloc(ve->mark,ve->storage*sizeof(*ve->mark));
  108063. }
  108064. for(j=first;j<last;j++){
  108065. int ret=0;
  108066. ve->stretch++;
  108067. if(ve->stretch>VE_MAXSTRETCH*2)
  108068. ve->stretch=VE_MAXSTRETCH*2;
  108069. for(i=0;i<ve->ch;i++){
  108070. float *pcm=v->pcm[i]+ve->searchstep*(j);
  108071. ret|=_ve_amp(ve,gi,pcm,ve->band,ve->filter+i*VE_BANDS,j);
  108072. }
  108073. ve->mark[j+VE_POST]=0;
  108074. if(ret&1){
  108075. ve->mark[j]=1;
  108076. ve->mark[j+1]=1;
  108077. }
  108078. if(ret&2){
  108079. ve->mark[j]=1;
  108080. if(j>0)ve->mark[j-1]=1;
  108081. }
  108082. if(ret&4)ve->stretch=-1;
  108083. }
  108084. ve->current=last*ve->searchstep;
  108085. {
  108086. long centerW=v->centerW;
  108087. long testW=
  108088. centerW+
  108089. ci->blocksizes[v->W]/4+
  108090. ci->blocksizes[1]/2+
  108091. ci->blocksizes[0]/4;
  108092. j=ve->cursor;
  108093. while(j<ve->current-(ve->searchstep)){/* account for postecho
  108094. working back one window */
  108095. if(j>=testW)return(1);
  108096. ve->cursor=j;
  108097. if(ve->mark[j/ve->searchstep]){
  108098. if(j>centerW){
  108099. #if 0
  108100. if(j>ve->curmark){
  108101. float *marker=alloca(v->pcm_current*sizeof(*marker));
  108102. int l,m;
  108103. memset(marker,0,sizeof(*marker)*v->pcm_current);
  108104. fprintf(stderr,"mark! seq=%d, cursor:%fs time:%fs\n",
  108105. seq,
  108106. (totalshift+ve->cursor)/44100.,
  108107. (totalshift+j)/44100.);
  108108. _analysis_output_always("pcmL",seq,v->pcm[0],v->pcm_current,0,0,totalshift);
  108109. _analysis_output_always("pcmR",seq,v->pcm[1],v->pcm_current,0,0,totalshift);
  108110. _analysis_output_always("markL",seq,v->pcm[0],j,0,0,totalshift);
  108111. _analysis_output_always("markR",seq,v->pcm[1],j,0,0,totalshift);
  108112. for(m=0;m<VE_BANDS;m++){
  108113. char buf[80];
  108114. sprintf(buf,"delL%d",m);
  108115. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->filter[m].markers[l]*.1;
  108116. _analysis_output_always(buf,seq,marker,v->pcm_current,0,0,totalshift);
  108117. }
  108118. for(m=0;m<VE_BANDS;m++){
  108119. char buf[80];
  108120. sprintf(buf,"delR%d",m);
  108121. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->filter[m+VE_BANDS].markers[l]*.1;
  108122. _analysis_output_always(buf,seq,marker,v->pcm_current,0,0,totalshift);
  108123. }
  108124. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->mark[l]*.4;
  108125. _analysis_output_always("mark",seq,marker,v->pcm_current,0,0,totalshift);
  108126. seq++;
  108127. }
  108128. #endif
  108129. ve->curmark=j;
  108130. if(j>=testW)return(1);
  108131. return(0);
  108132. }
  108133. }
  108134. j+=ve->searchstep;
  108135. }
  108136. }
  108137. return(-1);
  108138. }
  108139. int _ve_envelope_mark(vorbis_dsp_state *v){
  108140. envelope_lookup *ve=((private_state *)(v->backend_state))->ve;
  108141. vorbis_info *vi=v->vi;
  108142. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  108143. long centerW=v->centerW;
  108144. long beginW=centerW-ci->blocksizes[v->W]/4;
  108145. long endW=centerW+ci->blocksizes[v->W]/4;
  108146. if(v->W){
  108147. beginW-=ci->blocksizes[v->lW]/4;
  108148. endW+=ci->blocksizes[v->nW]/4;
  108149. }else{
  108150. beginW-=ci->blocksizes[0]/4;
  108151. endW+=ci->blocksizes[0]/4;
  108152. }
  108153. if(ve->curmark>=beginW && ve->curmark<endW)return(1);
  108154. {
  108155. long first=beginW/ve->searchstep;
  108156. long last=endW/ve->searchstep;
  108157. long i;
  108158. for(i=first;i<last;i++)
  108159. if(ve->mark[i])return(1);
  108160. }
  108161. return(0);
  108162. }
  108163. void _ve_envelope_shift(envelope_lookup *e,long shift){
  108164. int smallsize=e->current/e->searchstep+VE_POST; /* adjust for placing marks
  108165. ahead of ve->current */
  108166. int smallshift=shift/e->searchstep;
  108167. memmove(e->mark,e->mark+smallshift,(smallsize-smallshift)*sizeof(*e->mark));
  108168. #if 0
  108169. for(i=0;i<VE_BANDS*e->ch;i++)
  108170. memmove(e->filter[i].markers,
  108171. e->filter[i].markers+smallshift,
  108172. (1024-smallshift)*sizeof(*(*e->filter).markers));
  108173. totalshift+=shift;
  108174. #endif
  108175. e->current-=shift;
  108176. if(e->curmark>=0)
  108177. e->curmark-=shift;
  108178. e->cursor-=shift;
  108179. }
  108180. #endif
  108181. /********* End of inlined file: envelope.c *********/
  108182. /********* Start of inlined file: floor0.c *********/
  108183. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  108184. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  108185. // tasks..
  108186. #ifdef _MSC_VER
  108187. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  108188. #endif
  108189. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  108190. #if JUCE_USE_OGGVORBIS
  108191. #include <stdlib.h>
  108192. #include <string.h>
  108193. #include <math.h>
  108194. /********* Start of inlined file: lsp.h *********/
  108195. #ifndef _V_LSP_H_
  108196. #define _V_LSP_H_
  108197. extern int vorbis_lpc_to_lsp(float *lpc,float *lsp,int m);
  108198. extern void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,
  108199. float *lsp,int m,
  108200. float amp,float ampoffset);
  108201. #endif
  108202. /********* End of inlined file: lsp.h *********/
  108203. #include <stdio.h>
  108204. typedef struct {
  108205. int ln;
  108206. int m;
  108207. int **linearmap;
  108208. int n[2];
  108209. vorbis_info_floor0 *vi;
  108210. long bits;
  108211. long frames;
  108212. } vorbis_look_floor0;
  108213. /***********************************************/
  108214. static void floor0_free_info(vorbis_info_floor *i){
  108215. vorbis_info_floor0 *info=(vorbis_info_floor0 *)i;
  108216. if(info){
  108217. memset(info,0,sizeof(*info));
  108218. _ogg_free(info);
  108219. }
  108220. }
  108221. static void floor0_free_look(vorbis_look_floor *i){
  108222. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  108223. if(look){
  108224. if(look->linearmap){
  108225. if(look->linearmap[0])_ogg_free(look->linearmap[0]);
  108226. if(look->linearmap[1])_ogg_free(look->linearmap[1]);
  108227. _ogg_free(look->linearmap);
  108228. }
  108229. memset(look,0,sizeof(*look));
  108230. _ogg_free(look);
  108231. }
  108232. }
  108233. static vorbis_info_floor *floor0_unpack (vorbis_info *vi,oggpack_buffer *opb){
  108234. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  108235. int j;
  108236. vorbis_info_floor0 *info=(vorbis_info_floor0*)_ogg_malloc(sizeof(*info));
  108237. info->order=oggpack_read(opb,8);
  108238. info->rate=oggpack_read(opb,16);
  108239. info->barkmap=oggpack_read(opb,16);
  108240. info->ampbits=oggpack_read(opb,6);
  108241. info->ampdB=oggpack_read(opb,8);
  108242. info->numbooks=oggpack_read(opb,4)+1;
  108243. if(info->order<1)goto err_out;
  108244. if(info->rate<1)goto err_out;
  108245. if(info->barkmap<1)goto err_out;
  108246. if(info->numbooks<1)goto err_out;
  108247. for(j=0;j<info->numbooks;j++){
  108248. info->books[j]=oggpack_read(opb,8);
  108249. if(info->books[j]<0 || info->books[j]>=ci->books)goto err_out;
  108250. }
  108251. return(info);
  108252. err_out:
  108253. floor0_free_info(info);
  108254. return(NULL);
  108255. }
  108256. /* initialize Bark scale and normalization lookups. We could do this
  108257. with static tables, but Vorbis allows a number of possible
  108258. combinations, so it's best to do it computationally.
  108259. The below is authoritative in terms of defining scale mapping.
  108260. Note that the scale depends on the sampling rate as well as the
  108261. linear block and mapping sizes */
  108262. static void floor0_map_lazy_init(vorbis_block *vb,
  108263. vorbis_info_floor *infoX,
  108264. vorbis_look_floor0 *look){
  108265. if(!look->linearmap[vb->W]){
  108266. vorbis_dsp_state *vd=vb->vd;
  108267. vorbis_info *vi=vd->vi;
  108268. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  108269. vorbis_info_floor0 *info=(vorbis_info_floor0 *)infoX;
  108270. int W=vb->W;
  108271. int n=ci->blocksizes[W]/2,j;
  108272. /* we choose a scaling constant so that:
  108273. floor(bark(rate/2-1)*C)=mapped-1
  108274. floor(bark(rate/2)*C)=mapped */
  108275. float scale=look->ln/toBARK(info->rate/2.f);
  108276. /* the mapping from a linear scale to a smaller bark scale is
  108277. straightforward. We do *not* make sure that the linear mapping
  108278. does not skip bark-scale bins; the decoder simply skips them and
  108279. the encoder may do what it wishes in filling them. They're
  108280. necessary in some mapping combinations to keep the scale spacing
  108281. accurate */
  108282. look->linearmap[W]=(int*)_ogg_malloc((n+1)*sizeof(**look->linearmap));
  108283. for(j=0;j<n;j++){
  108284. int val=floor( toBARK((info->rate/2.f)/n*j)
  108285. *scale); /* bark numbers represent band edges */
  108286. if(val>=look->ln)val=look->ln-1; /* guard against the approximation */
  108287. look->linearmap[W][j]=val;
  108288. }
  108289. look->linearmap[W][j]=-1;
  108290. look->n[W]=n;
  108291. }
  108292. }
  108293. static vorbis_look_floor *floor0_look(vorbis_dsp_state *vd,
  108294. vorbis_info_floor *i){
  108295. vorbis_info_floor0 *info=(vorbis_info_floor0*)i;
  108296. vorbis_look_floor0 *look=(vorbis_look_floor0*)_ogg_calloc(1,sizeof(*look));
  108297. look->m=info->order;
  108298. look->ln=info->barkmap;
  108299. look->vi=info;
  108300. look->linearmap=(int**)_ogg_calloc(2,sizeof(*look->linearmap));
  108301. return look;
  108302. }
  108303. static void *floor0_inverse1(vorbis_block *vb,vorbis_look_floor *i){
  108304. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  108305. vorbis_info_floor0 *info=look->vi;
  108306. int j,k;
  108307. int ampraw=oggpack_read(&vb->opb,info->ampbits);
  108308. if(ampraw>0){ /* also handles the -1 out of data case */
  108309. long maxval=(1<<info->ampbits)-1;
  108310. float amp=(float)ampraw/maxval*info->ampdB;
  108311. int booknum=oggpack_read(&vb->opb,_ilog(info->numbooks));
  108312. if(booknum!=-1 && booknum<info->numbooks){ /* be paranoid */
  108313. codec_setup_info *ci=(codec_setup_info *)vb->vd->vi->codec_setup;
  108314. codebook *b=ci->fullbooks+info->books[booknum];
  108315. float last=0.f;
  108316. /* the additional b->dim is a guard against any possible stack
  108317. smash; b->dim is provably more than we can overflow the
  108318. vector */
  108319. float *lsp=(float*)_vorbis_block_alloc(vb,sizeof(*lsp)*(look->m+b->dim+1));
  108320. for(j=0;j<look->m;j+=b->dim)
  108321. if(vorbis_book_decodev_set(b,lsp+j,&vb->opb,b->dim)==-1)goto eop;
  108322. for(j=0;j<look->m;){
  108323. for(k=0;k<b->dim;k++,j++)lsp[j]+=last;
  108324. last=lsp[j-1];
  108325. }
  108326. lsp[look->m]=amp;
  108327. return(lsp);
  108328. }
  108329. }
  108330. eop:
  108331. return(NULL);
  108332. }
  108333. static int floor0_inverse2(vorbis_block *vb,vorbis_look_floor *i,
  108334. void *memo,float *out){
  108335. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  108336. vorbis_info_floor0 *info=look->vi;
  108337. floor0_map_lazy_init(vb,info,look);
  108338. if(memo){
  108339. float *lsp=(float *)memo;
  108340. float amp=lsp[look->m];
  108341. /* take the coefficients back to a spectral envelope curve */
  108342. vorbis_lsp_to_curve(out,
  108343. look->linearmap[vb->W],
  108344. look->n[vb->W],
  108345. look->ln,
  108346. lsp,look->m,amp,(float)info->ampdB);
  108347. return(1);
  108348. }
  108349. memset(out,0,sizeof(*out)*look->n[vb->W]);
  108350. return(0);
  108351. }
  108352. /* export hooks */
  108353. vorbis_func_floor floor0_exportbundle={
  108354. NULL,&floor0_unpack,&floor0_look,&floor0_free_info,
  108355. &floor0_free_look,&floor0_inverse1,&floor0_inverse2
  108356. };
  108357. #endif
  108358. /********* End of inlined file: floor0.c *********/
  108359. /********* Start of inlined file: floor1.c *********/
  108360. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  108361. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  108362. // tasks..
  108363. #ifdef _MSC_VER
  108364. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  108365. #endif
  108366. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  108367. #if JUCE_USE_OGGVORBIS
  108368. #include <stdlib.h>
  108369. #include <string.h>
  108370. #include <math.h>
  108371. #include <stdio.h>
  108372. #define floor1_rangedB 140 /* floor 1 fixed at -140dB to 0dB range */
  108373. typedef struct {
  108374. int sorted_index[VIF_POSIT+2];
  108375. int forward_index[VIF_POSIT+2];
  108376. int reverse_index[VIF_POSIT+2];
  108377. int hineighbor[VIF_POSIT];
  108378. int loneighbor[VIF_POSIT];
  108379. int posts;
  108380. int n;
  108381. int quant_q;
  108382. vorbis_info_floor1 *vi;
  108383. long phrasebits;
  108384. long postbits;
  108385. long frames;
  108386. } vorbis_look_floor1;
  108387. typedef struct lsfit_acc{
  108388. long x0;
  108389. long x1;
  108390. long xa;
  108391. long ya;
  108392. long x2a;
  108393. long y2a;
  108394. long xya;
  108395. long an;
  108396. } lsfit_acc;
  108397. /***********************************************/
  108398. static void floor1_free_info(vorbis_info_floor *i){
  108399. vorbis_info_floor1 *info=(vorbis_info_floor1 *)i;
  108400. if(info){
  108401. memset(info,0,sizeof(*info));
  108402. _ogg_free(info);
  108403. }
  108404. }
  108405. static void floor1_free_look(vorbis_look_floor *i){
  108406. vorbis_look_floor1 *look=(vorbis_look_floor1 *)i;
  108407. if(look){
  108408. /*fprintf(stderr,"floor 1 bit usage %f:%f (%f total)\n",
  108409. (float)look->phrasebits/look->frames,
  108410. (float)look->postbits/look->frames,
  108411. (float)(look->postbits+look->phrasebits)/look->frames);*/
  108412. memset(look,0,sizeof(*look));
  108413. _ogg_free(look);
  108414. }
  108415. }
  108416. static void floor1_pack (vorbis_info_floor *i,oggpack_buffer *opb){
  108417. vorbis_info_floor1 *info=(vorbis_info_floor1 *)i;
  108418. int j,k;
  108419. int count=0;
  108420. int rangebits;
  108421. int maxposit=info->postlist[1];
  108422. int maxclass=-1;
  108423. /* save out partitions */
  108424. oggpack_write(opb,info->partitions,5); /* only 0 to 31 legal */
  108425. for(j=0;j<info->partitions;j++){
  108426. oggpack_write(opb,info->partitionclass[j],4); /* only 0 to 15 legal */
  108427. if(maxclass<info->partitionclass[j])maxclass=info->partitionclass[j];
  108428. }
  108429. /* save out partition classes */
  108430. for(j=0;j<maxclass+1;j++){
  108431. oggpack_write(opb,info->class_dim[j]-1,3); /* 1 to 8 */
  108432. oggpack_write(opb,info->class_subs[j],2); /* 0 to 3 */
  108433. if(info->class_subs[j])oggpack_write(opb,info->class_book[j],8);
  108434. for(k=0;k<(1<<info->class_subs[j]);k++)
  108435. oggpack_write(opb,info->class_subbook[j][k]+1,8);
  108436. }
  108437. /* save out the post list */
  108438. oggpack_write(opb,info->mult-1,2); /* only 1,2,3,4 legal now */
  108439. oggpack_write(opb,ilog2(maxposit),4);
  108440. rangebits=ilog2(maxposit);
  108441. for(j=0,k=0;j<info->partitions;j++){
  108442. count+=info->class_dim[info->partitionclass[j]];
  108443. for(;k<count;k++)
  108444. oggpack_write(opb,info->postlist[k+2],rangebits);
  108445. }
  108446. }
  108447. static vorbis_info_floor *floor1_unpack (vorbis_info *vi,oggpack_buffer *opb){
  108448. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  108449. int j,k,count=0,maxclass=-1,rangebits;
  108450. vorbis_info_floor1 *info=(vorbis_info_floor1*)_ogg_calloc(1,sizeof(*info));
  108451. /* read partitions */
  108452. info->partitions=oggpack_read(opb,5); /* only 0 to 31 legal */
  108453. for(j=0;j<info->partitions;j++){
  108454. info->partitionclass[j]=oggpack_read(opb,4); /* only 0 to 15 legal */
  108455. if(maxclass<info->partitionclass[j])maxclass=info->partitionclass[j];
  108456. }
  108457. /* read partition classes */
  108458. for(j=0;j<maxclass+1;j++){
  108459. info->class_dim[j]=oggpack_read(opb,3)+1; /* 1 to 8 */
  108460. info->class_subs[j]=oggpack_read(opb,2); /* 0,1,2,3 bits */
  108461. if(info->class_subs[j]<0)
  108462. goto err_out;
  108463. if(info->class_subs[j])info->class_book[j]=oggpack_read(opb,8);
  108464. if(info->class_book[j]<0 || info->class_book[j]>=ci->books)
  108465. goto err_out;
  108466. for(k=0;k<(1<<info->class_subs[j]);k++){
  108467. info->class_subbook[j][k]=oggpack_read(opb,8)-1;
  108468. if(info->class_subbook[j][k]<-1 || info->class_subbook[j][k]>=ci->books)
  108469. goto err_out;
  108470. }
  108471. }
  108472. /* read the post list */
  108473. info->mult=oggpack_read(opb,2)+1; /* only 1,2,3,4 legal now */
  108474. rangebits=oggpack_read(opb,4);
  108475. for(j=0,k=0;j<info->partitions;j++){
  108476. count+=info->class_dim[info->partitionclass[j]];
  108477. for(;k<count;k++){
  108478. int t=info->postlist[k+2]=oggpack_read(opb,rangebits);
  108479. if(t<0 || t>=(1<<rangebits))
  108480. goto err_out;
  108481. }
  108482. }
  108483. info->postlist[0]=0;
  108484. info->postlist[1]=1<<rangebits;
  108485. return(info);
  108486. err_out:
  108487. floor1_free_info(info);
  108488. return(NULL);
  108489. }
  108490. static int icomp(const void *a,const void *b){
  108491. return(**(int **)a-**(int **)b);
  108492. }
  108493. static vorbis_look_floor *floor1_look(vorbis_dsp_state *vd,
  108494. vorbis_info_floor *in){
  108495. int *sortpointer[VIF_POSIT+2];
  108496. vorbis_info_floor1 *info=(vorbis_info_floor1*)in;
  108497. vorbis_look_floor1 *look=(vorbis_look_floor1*)_ogg_calloc(1,sizeof(*look));
  108498. int i,j,n=0;
  108499. look->vi=info;
  108500. look->n=info->postlist[1];
  108501. /* we drop each position value in-between already decoded values,
  108502. and use linear interpolation to predict each new value past the
  108503. edges. The positions are read in the order of the position
  108504. list... we precompute the bounding positions in the lookup. Of
  108505. course, the neighbors can change (if a position is declined), but
  108506. this is an initial mapping */
  108507. for(i=0;i<info->partitions;i++)n+=info->class_dim[info->partitionclass[i]];
  108508. n+=2;
  108509. look->posts=n;
  108510. /* also store a sorted position index */
  108511. for(i=0;i<n;i++)sortpointer[i]=info->postlist+i;
  108512. qsort(sortpointer,n,sizeof(*sortpointer),icomp);
  108513. /* points from sort order back to range number */
  108514. for(i=0;i<n;i++)look->forward_index[i]=sortpointer[i]-info->postlist;
  108515. /* points from range order to sorted position */
  108516. for(i=0;i<n;i++)look->reverse_index[look->forward_index[i]]=i;
  108517. /* we actually need the post values too */
  108518. for(i=0;i<n;i++)look->sorted_index[i]=info->postlist[look->forward_index[i]];
  108519. /* quantize values to multiplier spec */
  108520. switch(info->mult){
  108521. case 1: /* 1024 -> 256 */
  108522. look->quant_q=256;
  108523. break;
  108524. case 2: /* 1024 -> 128 */
  108525. look->quant_q=128;
  108526. break;
  108527. case 3: /* 1024 -> 86 */
  108528. look->quant_q=86;
  108529. break;
  108530. case 4: /* 1024 -> 64 */
  108531. look->quant_q=64;
  108532. break;
  108533. }
  108534. /* discover our neighbors for decode where we don't use fit flags
  108535. (that would push the neighbors outward) */
  108536. for(i=0;i<n-2;i++){
  108537. int lo=0;
  108538. int hi=1;
  108539. int lx=0;
  108540. int hx=look->n;
  108541. int currentx=info->postlist[i+2];
  108542. for(j=0;j<i+2;j++){
  108543. int x=info->postlist[j];
  108544. if(x>lx && x<currentx){
  108545. lo=j;
  108546. lx=x;
  108547. }
  108548. if(x<hx && x>currentx){
  108549. hi=j;
  108550. hx=x;
  108551. }
  108552. }
  108553. look->loneighbor[i]=lo;
  108554. look->hineighbor[i]=hi;
  108555. }
  108556. return(look);
  108557. }
  108558. static int render_point(int x0,int x1,int y0,int y1,int x){
  108559. y0&=0x7fff; /* mask off flag */
  108560. y1&=0x7fff;
  108561. {
  108562. int dy=y1-y0;
  108563. int adx=x1-x0;
  108564. int ady=abs(dy);
  108565. int err=ady*(x-x0);
  108566. int off=err/adx;
  108567. if(dy<0)return(y0-off);
  108568. return(y0+off);
  108569. }
  108570. }
  108571. static int vorbis_dBquant(const float *x){
  108572. int i= *x*7.3142857f+1023.5f;
  108573. if(i>1023)return(1023);
  108574. if(i<0)return(0);
  108575. return i;
  108576. }
  108577. static float FLOOR1_fromdB_LOOKUP[256]={
  108578. 1.0649863e-07F, 1.1341951e-07F, 1.2079015e-07F, 1.2863978e-07F,
  108579. 1.3699951e-07F, 1.4590251e-07F, 1.5538408e-07F, 1.6548181e-07F,
  108580. 1.7623575e-07F, 1.8768855e-07F, 1.9988561e-07F, 2.128753e-07F,
  108581. 2.2670913e-07F, 2.4144197e-07F, 2.5713223e-07F, 2.7384213e-07F,
  108582. 2.9163793e-07F, 3.1059021e-07F, 3.3077411e-07F, 3.5226968e-07F,
  108583. 3.7516214e-07F, 3.9954229e-07F, 4.2550680e-07F, 4.5315863e-07F,
  108584. 4.8260743e-07F, 5.1396998e-07F, 5.4737065e-07F, 5.8294187e-07F,
  108585. 6.2082472e-07F, 6.6116941e-07F, 7.0413592e-07F, 7.4989464e-07F,
  108586. 7.9862701e-07F, 8.5052630e-07F, 9.0579828e-07F, 9.6466216e-07F,
  108587. 1.0273513e-06F, 1.0941144e-06F, 1.1652161e-06F, 1.2409384e-06F,
  108588. 1.3215816e-06F, 1.4074654e-06F, 1.4989305e-06F, 1.5963394e-06F,
  108589. 1.7000785e-06F, 1.8105592e-06F, 1.9282195e-06F, 2.0535261e-06F,
  108590. 2.1869758e-06F, 2.3290978e-06F, 2.4804557e-06F, 2.6416497e-06F,
  108591. 2.8133190e-06F, 2.9961443e-06F, 3.1908506e-06F, 3.3982101e-06F,
  108592. 3.6190449e-06F, 3.8542308e-06F, 4.1047004e-06F, 4.3714470e-06F,
  108593. 4.6555282e-06F, 4.9580707e-06F, 5.2802740e-06F, 5.6234160e-06F,
  108594. 5.9888572e-06F, 6.3780469e-06F, 6.7925283e-06F, 7.2339451e-06F,
  108595. 7.7040476e-06F, 8.2047000e-06F, 8.7378876e-06F, 9.3057248e-06F,
  108596. 9.9104632e-06F, 1.0554501e-05F, 1.1240392e-05F, 1.1970856e-05F,
  108597. 1.2748789e-05F, 1.3577278e-05F, 1.4459606e-05F, 1.5399272e-05F,
  108598. 1.6400004e-05F, 1.7465768e-05F, 1.8600792e-05F, 1.9809576e-05F,
  108599. 2.1096914e-05F, 2.2467911e-05F, 2.3928002e-05F, 2.5482978e-05F,
  108600. 2.7139006e-05F, 2.8902651e-05F, 3.0780908e-05F, 3.2781225e-05F,
  108601. 3.4911534e-05F, 3.7180282e-05F, 3.9596466e-05F, 4.2169667e-05F,
  108602. 4.4910090e-05F, 4.7828601e-05F, 5.0936773e-05F, 5.4246931e-05F,
  108603. 5.7772202e-05F, 6.1526565e-05F, 6.5524908e-05F, 6.9783085e-05F,
  108604. 7.4317983e-05F, 7.9147585e-05F, 8.4291040e-05F, 8.9768747e-05F,
  108605. 9.5602426e-05F, 0.00010181521F, 0.00010843174F, 0.00011547824F,
  108606. 0.00012298267F, 0.00013097477F, 0.00013948625F, 0.00014855085F,
  108607. 0.00015820453F, 0.00016848555F, 0.00017943469F, 0.00019109536F,
  108608. 0.00020351382F, 0.00021673929F, 0.00023082423F, 0.00024582449F,
  108609. 0.00026179955F, 0.00027881276F, 0.00029693158F, 0.00031622787F,
  108610. 0.00033677814F, 0.00035866388F, 0.00038197188F, 0.00040679456F,
  108611. 0.00043323036F, 0.00046138411F, 0.00049136745F, 0.00052329927F,
  108612. 0.00055730621F, 0.00059352311F, 0.00063209358F, 0.00067317058F,
  108613. 0.00071691700F, 0.00076350630F, 0.00081312324F, 0.00086596457F,
  108614. 0.00092223983F, 0.00098217216F, 0.0010459992F, 0.0011139742F,
  108615. 0.0011863665F, 0.0012634633F, 0.0013455702F, 0.0014330129F,
  108616. 0.0015261382F, 0.0016253153F, 0.0017309374F, 0.0018434235F,
  108617. 0.0019632195F, 0.0020908006F, 0.0022266726F, 0.0023713743F,
  108618. 0.0025254795F, 0.0026895994F, 0.0028643847F, 0.0030505286F,
  108619. 0.0032487691F, 0.0034598925F, 0.0036847358F, 0.0039241906F,
  108620. 0.0041792066F, 0.0044507950F, 0.0047400328F, 0.0050480668F,
  108621. 0.0053761186F, 0.0057254891F, 0.0060975636F, 0.0064938176F,
  108622. 0.0069158225F, 0.0073652516F, 0.0078438871F, 0.0083536271F,
  108623. 0.0088964928F, 0.009474637F, 0.010090352F, 0.010746080F,
  108624. 0.011444421F, 0.012188144F, 0.012980198F, 0.013823725F,
  108625. 0.014722068F, 0.015678791F, 0.016697687F, 0.017782797F,
  108626. 0.018938423F, 0.020169149F, 0.021479854F, 0.022875735F,
  108627. 0.024362330F, 0.025945531F, 0.027631618F, 0.029427276F,
  108628. 0.031339626F, 0.033376252F, 0.035545228F, 0.037855157F,
  108629. 0.040315199F, 0.042935108F, 0.045725273F, 0.048696758F,
  108630. 0.051861348F, 0.055231591F, 0.058820850F, 0.062643361F,
  108631. 0.066714279F, 0.071049749F, 0.075666962F, 0.080584227F,
  108632. 0.085821044F, 0.091398179F, 0.097337747F, 0.10366330F,
  108633. 0.11039993F, 0.11757434F, 0.12521498F, 0.13335215F,
  108634. 0.14201813F, 0.15124727F, 0.16107617F, 0.17154380F,
  108635. 0.18269168F, 0.19456402F, 0.20720788F, 0.22067342F,
  108636. 0.23501402F, 0.25028656F, 0.26655159F, 0.28387361F,
  108637. 0.30232132F, 0.32196786F, 0.34289114F, 0.36517414F,
  108638. 0.38890521F, 0.41417847F, 0.44109412F, 0.46975890F,
  108639. 0.50028648F, 0.53279791F, 0.56742212F, 0.60429640F,
  108640. 0.64356699F, 0.68538959F, 0.72993007F, 0.77736504F,
  108641. 0.82788260F, 0.88168307F, 0.9389798F, 1.F,
  108642. };
  108643. static void render_line(int x0,int x1,int y0,int y1,float *d){
  108644. int dy=y1-y0;
  108645. int adx=x1-x0;
  108646. int ady=abs(dy);
  108647. int base=dy/adx;
  108648. int sy=(dy<0?base-1:base+1);
  108649. int x=x0;
  108650. int y=y0;
  108651. int err=0;
  108652. ady-=abs(base*adx);
  108653. d[x]*=FLOOR1_fromdB_LOOKUP[y];
  108654. while(++x<x1){
  108655. err=err+ady;
  108656. if(err>=adx){
  108657. err-=adx;
  108658. y+=sy;
  108659. }else{
  108660. y+=base;
  108661. }
  108662. d[x]*=FLOOR1_fromdB_LOOKUP[y];
  108663. }
  108664. }
  108665. static void render_line0(int x0,int x1,int y0,int y1,int *d){
  108666. int dy=y1-y0;
  108667. int adx=x1-x0;
  108668. int ady=abs(dy);
  108669. int base=dy/adx;
  108670. int sy=(dy<0?base-1:base+1);
  108671. int x=x0;
  108672. int y=y0;
  108673. int err=0;
  108674. ady-=abs(base*adx);
  108675. d[x]=y;
  108676. while(++x<x1){
  108677. err=err+ady;
  108678. if(err>=adx){
  108679. err-=adx;
  108680. y+=sy;
  108681. }else{
  108682. y+=base;
  108683. }
  108684. d[x]=y;
  108685. }
  108686. }
  108687. /* the floor has already been filtered to only include relevant sections */
  108688. static int accumulate_fit(const float *flr,const float *mdct,
  108689. int x0, int x1,lsfit_acc *a,
  108690. int n,vorbis_info_floor1 *info){
  108691. long i;
  108692. long xa=0,ya=0,x2a=0,y2a=0,xya=0,na=0, xb=0,yb=0,x2b=0,y2b=0,xyb=0,nb=0;
  108693. memset(a,0,sizeof(*a));
  108694. a->x0=x0;
  108695. a->x1=x1;
  108696. if(x1>=n)x1=n-1;
  108697. for(i=x0;i<=x1;i++){
  108698. int quantized=vorbis_dBquant(flr+i);
  108699. if(quantized){
  108700. if(mdct[i]+info->twofitatten>=flr[i]){
  108701. xa += i;
  108702. ya += quantized;
  108703. x2a += i*i;
  108704. y2a += quantized*quantized;
  108705. xya += i*quantized;
  108706. na++;
  108707. }else{
  108708. xb += i;
  108709. yb += quantized;
  108710. x2b += i*i;
  108711. y2b += quantized*quantized;
  108712. xyb += i*quantized;
  108713. nb++;
  108714. }
  108715. }
  108716. }
  108717. xb+=xa;
  108718. yb+=ya;
  108719. x2b+=x2a;
  108720. y2b+=y2a;
  108721. xyb+=xya;
  108722. nb+=na;
  108723. /* weight toward the actually used frequencies if we meet the threshhold */
  108724. {
  108725. int weight=nb*info->twofitweight/(na+1);
  108726. a->xa=xa*weight+xb;
  108727. a->ya=ya*weight+yb;
  108728. a->x2a=x2a*weight+x2b;
  108729. a->y2a=y2a*weight+y2b;
  108730. a->xya=xya*weight+xyb;
  108731. a->an=na*weight+nb;
  108732. }
  108733. return(na);
  108734. }
  108735. static void fit_line(lsfit_acc *a,int fits,int *y0,int *y1){
  108736. long x=0,y=0,x2=0,y2=0,xy=0,an=0,i;
  108737. long x0=a[0].x0;
  108738. long x1=a[fits-1].x1;
  108739. for(i=0;i<fits;i++){
  108740. x+=a[i].xa;
  108741. y+=a[i].ya;
  108742. x2+=a[i].x2a;
  108743. y2+=a[i].y2a;
  108744. xy+=a[i].xya;
  108745. an+=a[i].an;
  108746. }
  108747. if(*y0>=0){
  108748. x+= x0;
  108749. y+= *y0;
  108750. x2+= x0 * x0;
  108751. y2+= *y0 * *y0;
  108752. xy+= *y0 * x0;
  108753. an++;
  108754. }
  108755. if(*y1>=0){
  108756. x+= x1;
  108757. y+= *y1;
  108758. x2+= x1 * x1;
  108759. y2+= *y1 * *y1;
  108760. xy+= *y1 * x1;
  108761. an++;
  108762. }
  108763. if(an){
  108764. /* need 64 bit multiplies, which C doesn't give portably as int */
  108765. double fx=x;
  108766. double fy=y;
  108767. double fx2=x2;
  108768. double fxy=xy;
  108769. double denom=1./(an*fx2-fx*fx);
  108770. double a=(fy*fx2-fxy*fx)*denom;
  108771. double b=(an*fxy-fx*fy)*denom;
  108772. *y0=rint(a+b*x0);
  108773. *y1=rint(a+b*x1);
  108774. /* limit to our range! */
  108775. if(*y0>1023)*y0=1023;
  108776. if(*y1>1023)*y1=1023;
  108777. if(*y0<0)*y0=0;
  108778. if(*y1<0)*y1=0;
  108779. }else{
  108780. *y0=0;
  108781. *y1=0;
  108782. }
  108783. }
  108784. /*static void fit_line_point(lsfit_acc *a,int fits,int *y0,int *y1){
  108785. long y=0;
  108786. int i;
  108787. for(i=0;i<fits && y==0;i++)
  108788. y+=a[i].ya;
  108789. *y0=*y1=y;
  108790. }*/
  108791. static int inspect_error(int x0,int x1,int y0,int y1,const float *mask,
  108792. const float *mdct,
  108793. vorbis_info_floor1 *info){
  108794. int dy=y1-y0;
  108795. int adx=x1-x0;
  108796. int ady=abs(dy);
  108797. int base=dy/adx;
  108798. int sy=(dy<0?base-1:base+1);
  108799. int x=x0;
  108800. int y=y0;
  108801. int err=0;
  108802. int val=vorbis_dBquant(mask+x);
  108803. int mse=0;
  108804. int n=0;
  108805. ady-=abs(base*adx);
  108806. mse=(y-val);
  108807. mse*=mse;
  108808. n++;
  108809. if(mdct[x]+info->twofitatten>=mask[x]){
  108810. if(y+info->maxover<val)return(1);
  108811. if(y-info->maxunder>val)return(1);
  108812. }
  108813. while(++x<x1){
  108814. err=err+ady;
  108815. if(err>=adx){
  108816. err-=adx;
  108817. y+=sy;
  108818. }else{
  108819. y+=base;
  108820. }
  108821. val=vorbis_dBquant(mask+x);
  108822. mse+=((y-val)*(y-val));
  108823. n++;
  108824. if(mdct[x]+info->twofitatten>=mask[x]){
  108825. if(val){
  108826. if(y+info->maxover<val)return(1);
  108827. if(y-info->maxunder>val)return(1);
  108828. }
  108829. }
  108830. }
  108831. if(info->maxover*info->maxover/n>info->maxerr)return(0);
  108832. if(info->maxunder*info->maxunder/n>info->maxerr)return(0);
  108833. if(mse/n>info->maxerr)return(1);
  108834. return(0);
  108835. }
  108836. static int post_Y(int *A,int *B,int pos){
  108837. if(A[pos]<0)
  108838. return B[pos];
  108839. if(B[pos]<0)
  108840. return A[pos];
  108841. return (A[pos]+B[pos])>>1;
  108842. }
  108843. int *floor1_fit(vorbis_block *vb,void *look_,
  108844. const float *logmdct, /* in */
  108845. const float *logmask){
  108846. long i,j;
  108847. vorbis_look_floor1 *look = (vorbis_look_floor1*) look_;
  108848. vorbis_info_floor1 *info=look->vi;
  108849. long n=look->n;
  108850. long posts=look->posts;
  108851. long nonzero=0;
  108852. lsfit_acc fits[VIF_POSIT+1];
  108853. int fit_valueA[VIF_POSIT+2]; /* index by range list position */
  108854. int fit_valueB[VIF_POSIT+2]; /* index by range list position */
  108855. int loneighbor[VIF_POSIT+2]; /* sorted index of range list position (+2) */
  108856. int hineighbor[VIF_POSIT+2];
  108857. int *output=NULL;
  108858. int memo[VIF_POSIT+2];
  108859. for(i=0;i<posts;i++)fit_valueA[i]=-200; /* mark all unused */
  108860. for(i=0;i<posts;i++)fit_valueB[i]=-200; /* mark all unused */
  108861. for(i=0;i<posts;i++)loneighbor[i]=0; /* 0 for the implicit 0 post */
  108862. for(i=0;i<posts;i++)hineighbor[i]=1; /* 1 for the implicit post at n */
  108863. for(i=0;i<posts;i++)memo[i]=-1; /* no neighbor yet */
  108864. /* quantize the relevant floor points and collect them into line fit
  108865. structures (one per minimal division) at the same time */
  108866. if(posts==0){
  108867. nonzero+=accumulate_fit(logmask,logmdct,0,n,fits,n,info);
  108868. }else{
  108869. for(i=0;i<posts-1;i++)
  108870. nonzero+=accumulate_fit(logmask,logmdct,look->sorted_index[i],
  108871. look->sorted_index[i+1],fits+i,
  108872. n,info);
  108873. }
  108874. if(nonzero){
  108875. /* start by fitting the implicit base case.... */
  108876. int y0=-200;
  108877. int y1=-200;
  108878. fit_line(fits,posts-1,&y0,&y1);
  108879. fit_valueA[0]=y0;
  108880. fit_valueB[0]=y0;
  108881. fit_valueB[1]=y1;
  108882. fit_valueA[1]=y1;
  108883. /* Non degenerate case */
  108884. /* start progressive splitting. This is a greedy, non-optimal
  108885. algorithm, but simple and close enough to the best
  108886. answer. */
  108887. for(i=2;i<posts;i++){
  108888. int sortpos=look->reverse_index[i];
  108889. int ln=loneighbor[sortpos];
  108890. int hn=hineighbor[sortpos];
  108891. /* eliminate repeat searches of a particular range with a memo */
  108892. if(memo[ln]!=hn){
  108893. /* haven't performed this error search yet */
  108894. int lsortpos=look->reverse_index[ln];
  108895. int hsortpos=look->reverse_index[hn];
  108896. memo[ln]=hn;
  108897. {
  108898. /* A note: we want to bound/minimize *local*, not global, error */
  108899. int lx=info->postlist[ln];
  108900. int hx=info->postlist[hn];
  108901. int ly=post_Y(fit_valueA,fit_valueB,ln);
  108902. int hy=post_Y(fit_valueA,fit_valueB,hn);
  108903. if(ly==-1 || hy==-1){
  108904. exit(1);
  108905. }
  108906. if(inspect_error(lx,hx,ly,hy,logmask,logmdct,info)){
  108907. /* outside error bounds/begin search area. Split it. */
  108908. int ly0=-200;
  108909. int ly1=-200;
  108910. int hy0=-200;
  108911. int hy1=-200;
  108912. fit_line(fits+lsortpos,sortpos-lsortpos,&ly0,&ly1);
  108913. fit_line(fits+sortpos,hsortpos-sortpos,&hy0,&hy1);
  108914. /* store new edge values */
  108915. fit_valueB[ln]=ly0;
  108916. if(ln==0)fit_valueA[ln]=ly0;
  108917. fit_valueA[i]=ly1;
  108918. fit_valueB[i]=hy0;
  108919. fit_valueA[hn]=hy1;
  108920. if(hn==1)fit_valueB[hn]=hy1;
  108921. if(ly1>=0 || hy0>=0){
  108922. /* store new neighbor values */
  108923. for(j=sortpos-1;j>=0;j--)
  108924. if(hineighbor[j]==hn)
  108925. hineighbor[j]=i;
  108926. else
  108927. break;
  108928. for(j=sortpos+1;j<posts;j++)
  108929. if(loneighbor[j]==ln)
  108930. loneighbor[j]=i;
  108931. else
  108932. break;
  108933. }
  108934. }else{
  108935. fit_valueA[i]=-200;
  108936. fit_valueB[i]=-200;
  108937. }
  108938. }
  108939. }
  108940. }
  108941. output=(int*)_vorbis_block_alloc(vb,sizeof(*output)*posts);
  108942. output[0]=post_Y(fit_valueA,fit_valueB,0);
  108943. output[1]=post_Y(fit_valueA,fit_valueB,1);
  108944. /* fill in posts marked as not using a fit; we will zero
  108945. back out to 'unused' when encoding them so long as curve
  108946. interpolation doesn't force them into use */
  108947. for(i=2;i<posts;i++){
  108948. int ln=look->loneighbor[i-2];
  108949. int hn=look->hineighbor[i-2];
  108950. int x0=info->postlist[ln];
  108951. int x1=info->postlist[hn];
  108952. int y0=output[ln];
  108953. int y1=output[hn];
  108954. int predicted=render_point(x0,x1,y0,y1,info->postlist[i]);
  108955. int vx=post_Y(fit_valueA,fit_valueB,i);
  108956. if(vx>=0 && predicted!=vx){
  108957. output[i]=vx;
  108958. }else{
  108959. output[i]= predicted|0x8000;
  108960. }
  108961. }
  108962. }
  108963. return(output);
  108964. }
  108965. int *floor1_interpolate_fit(vorbis_block *vb,void *look_,
  108966. int *A,int *B,
  108967. int del){
  108968. long i;
  108969. vorbis_look_floor1* look = (vorbis_look_floor1*) look_;
  108970. long posts=look->posts;
  108971. int *output=NULL;
  108972. if(A && B){
  108973. output=(int*)_vorbis_block_alloc(vb,sizeof(*output)*posts);
  108974. for(i=0;i<posts;i++){
  108975. output[i]=((65536-del)*(A[i]&0x7fff)+del*(B[i]&0x7fff)+32768)>>16;
  108976. if(A[i]&0x8000 && B[i]&0x8000)output[i]|=0x8000;
  108977. }
  108978. }
  108979. return(output);
  108980. }
  108981. int floor1_encode(oggpack_buffer *opb,vorbis_block *vb,
  108982. void*look_,
  108983. int *post,int *ilogmask){
  108984. long i,j;
  108985. vorbis_look_floor1 *look = (vorbis_look_floor1 *) look_;
  108986. vorbis_info_floor1 *info=look->vi;
  108987. long posts=look->posts;
  108988. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  108989. int out[VIF_POSIT+2];
  108990. static_codebook **sbooks=ci->book_param;
  108991. codebook *books=ci->fullbooks;
  108992. static long seq=0;
  108993. /* quantize values to multiplier spec */
  108994. if(post){
  108995. for(i=0;i<posts;i++){
  108996. int val=post[i]&0x7fff;
  108997. switch(info->mult){
  108998. case 1: /* 1024 -> 256 */
  108999. val>>=2;
  109000. break;
  109001. case 2: /* 1024 -> 128 */
  109002. val>>=3;
  109003. break;
  109004. case 3: /* 1024 -> 86 */
  109005. val/=12;
  109006. break;
  109007. case 4: /* 1024 -> 64 */
  109008. val>>=4;
  109009. break;
  109010. }
  109011. post[i]=val | (post[i]&0x8000);
  109012. }
  109013. out[0]=post[0];
  109014. out[1]=post[1];
  109015. /* find prediction values for each post and subtract them */
  109016. for(i=2;i<posts;i++){
  109017. int ln=look->loneighbor[i-2];
  109018. int hn=look->hineighbor[i-2];
  109019. int x0=info->postlist[ln];
  109020. int x1=info->postlist[hn];
  109021. int y0=post[ln];
  109022. int y1=post[hn];
  109023. int predicted=render_point(x0,x1,y0,y1,info->postlist[i]);
  109024. if((post[i]&0x8000) || (predicted==post[i])){
  109025. post[i]=predicted|0x8000; /* in case there was roundoff jitter
  109026. in interpolation */
  109027. out[i]=0;
  109028. }else{
  109029. int headroom=(look->quant_q-predicted<predicted?
  109030. look->quant_q-predicted:predicted);
  109031. int val=post[i]-predicted;
  109032. /* at this point the 'deviation' value is in the range +/- max
  109033. range, but the real, unique range can always be mapped to
  109034. only [0-maxrange). So we want to wrap the deviation into
  109035. this limited range, but do it in the way that least screws
  109036. an essentially gaussian probability distribution. */
  109037. if(val<0)
  109038. if(val<-headroom)
  109039. val=headroom-val-1;
  109040. else
  109041. val=-1-(val<<1);
  109042. else
  109043. if(val>=headroom)
  109044. val= val+headroom;
  109045. else
  109046. val<<=1;
  109047. out[i]=val;
  109048. post[ln]&=0x7fff;
  109049. post[hn]&=0x7fff;
  109050. }
  109051. }
  109052. /* we have everything we need. pack it out */
  109053. /* mark nontrivial floor */
  109054. oggpack_write(opb,1,1);
  109055. /* beginning/end post */
  109056. look->frames++;
  109057. look->postbits+=ilog(look->quant_q-1)*2;
  109058. oggpack_write(opb,out[0],ilog(look->quant_q-1));
  109059. oggpack_write(opb,out[1],ilog(look->quant_q-1));
  109060. /* partition by partition */
  109061. for(i=0,j=2;i<info->partitions;i++){
  109062. int classx=info->partitionclass[i];
  109063. int cdim=info->class_dim[classx];
  109064. int csubbits=info->class_subs[classx];
  109065. int csub=1<<csubbits;
  109066. int bookas[8]={0,0,0,0,0,0,0,0};
  109067. int cval=0;
  109068. int cshift=0;
  109069. int k,l;
  109070. /* generate the partition's first stage cascade value */
  109071. if(csubbits){
  109072. int maxval[8];
  109073. for(k=0;k<csub;k++){
  109074. int booknum=info->class_subbook[classx][k];
  109075. if(booknum<0){
  109076. maxval[k]=1;
  109077. }else{
  109078. maxval[k]=sbooks[info->class_subbook[classx][k]]->entries;
  109079. }
  109080. }
  109081. for(k=0;k<cdim;k++){
  109082. for(l=0;l<csub;l++){
  109083. int val=out[j+k];
  109084. if(val<maxval[l]){
  109085. bookas[k]=l;
  109086. break;
  109087. }
  109088. }
  109089. cval|= bookas[k]<<cshift;
  109090. cshift+=csubbits;
  109091. }
  109092. /* write it */
  109093. look->phrasebits+=
  109094. vorbis_book_encode(books+info->class_book[classx],cval,opb);
  109095. #ifdef TRAIN_FLOOR1
  109096. {
  109097. FILE *of;
  109098. char buffer[80];
  109099. sprintf(buffer,"line_%dx%ld_class%d.vqd",
  109100. vb->pcmend/2,posts-2,class);
  109101. of=fopen(buffer,"a");
  109102. fprintf(of,"%d\n",cval);
  109103. fclose(of);
  109104. }
  109105. #endif
  109106. }
  109107. /* write post values */
  109108. for(k=0;k<cdim;k++){
  109109. int book=info->class_subbook[classx][bookas[k]];
  109110. if(book>=0){
  109111. /* hack to allow training with 'bad' books */
  109112. if(out[j+k]<(books+book)->entries)
  109113. look->postbits+=vorbis_book_encode(books+book,
  109114. out[j+k],opb);
  109115. /*else
  109116. fprintf(stderr,"+!");*/
  109117. #ifdef TRAIN_FLOOR1
  109118. {
  109119. FILE *of;
  109120. char buffer[80];
  109121. sprintf(buffer,"line_%dx%ld_%dsub%d.vqd",
  109122. vb->pcmend/2,posts-2,class,bookas[k]);
  109123. of=fopen(buffer,"a");
  109124. fprintf(of,"%d\n",out[j+k]);
  109125. fclose(of);
  109126. }
  109127. #endif
  109128. }
  109129. }
  109130. j+=cdim;
  109131. }
  109132. {
  109133. /* generate quantized floor equivalent to what we'd unpack in decode */
  109134. /* render the lines */
  109135. int hx=0;
  109136. int lx=0;
  109137. int ly=post[0]*info->mult;
  109138. for(j=1;j<look->posts;j++){
  109139. int current=look->forward_index[j];
  109140. int hy=post[current]&0x7fff;
  109141. if(hy==post[current]){
  109142. hy*=info->mult;
  109143. hx=info->postlist[current];
  109144. render_line0(lx,hx,ly,hy,ilogmask);
  109145. lx=hx;
  109146. ly=hy;
  109147. }
  109148. }
  109149. for(j=hx;j<vb->pcmend/2;j++)ilogmask[j]=ly; /* be certain */
  109150. seq++;
  109151. return(1);
  109152. }
  109153. }else{
  109154. oggpack_write(opb,0,1);
  109155. memset(ilogmask,0,vb->pcmend/2*sizeof(*ilogmask));
  109156. seq++;
  109157. return(0);
  109158. }
  109159. }
  109160. static void *floor1_inverse1(vorbis_block *vb,vorbis_look_floor *in){
  109161. vorbis_look_floor1 *look=(vorbis_look_floor1 *)in;
  109162. vorbis_info_floor1 *info=look->vi;
  109163. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  109164. int i,j,k;
  109165. codebook *books=ci->fullbooks;
  109166. /* unpack wrapped/predicted values from stream */
  109167. if(oggpack_read(&vb->opb,1)==1){
  109168. int *fit_value=(int*)_vorbis_block_alloc(vb,(look->posts)*sizeof(*fit_value));
  109169. fit_value[0]=oggpack_read(&vb->opb,ilog(look->quant_q-1));
  109170. fit_value[1]=oggpack_read(&vb->opb,ilog(look->quant_q-1));
  109171. /* partition by partition */
  109172. for(i=0,j=2;i<info->partitions;i++){
  109173. int classx=info->partitionclass[i];
  109174. int cdim=info->class_dim[classx];
  109175. int csubbits=info->class_subs[classx];
  109176. int csub=1<<csubbits;
  109177. int cval=0;
  109178. /* decode the partition's first stage cascade value */
  109179. if(csubbits){
  109180. cval=vorbis_book_decode(books+info->class_book[classx],&vb->opb);
  109181. if(cval==-1)goto eop;
  109182. }
  109183. for(k=0;k<cdim;k++){
  109184. int book=info->class_subbook[classx][cval&(csub-1)];
  109185. cval>>=csubbits;
  109186. if(book>=0){
  109187. if((fit_value[j+k]=vorbis_book_decode(books+book,&vb->opb))==-1)
  109188. goto eop;
  109189. }else{
  109190. fit_value[j+k]=0;
  109191. }
  109192. }
  109193. j+=cdim;
  109194. }
  109195. /* unwrap positive values and reconsitute via linear interpolation */
  109196. for(i=2;i<look->posts;i++){
  109197. int predicted=render_point(info->postlist[look->loneighbor[i-2]],
  109198. info->postlist[look->hineighbor[i-2]],
  109199. fit_value[look->loneighbor[i-2]],
  109200. fit_value[look->hineighbor[i-2]],
  109201. info->postlist[i]);
  109202. int hiroom=look->quant_q-predicted;
  109203. int loroom=predicted;
  109204. int room=(hiroom<loroom?hiroom:loroom)<<1;
  109205. int val=fit_value[i];
  109206. if(val){
  109207. if(val>=room){
  109208. if(hiroom>loroom){
  109209. val = val-loroom;
  109210. }else{
  109211. val = -1-(val-hiroom);
  109212. }
  109213. }else{
  109214. if(val&1){
  109215. val= -((val+1)>>1);
  109216. }else{
  109217. val>>=1;
  109218. }
  109219. }
  109220. fit_value[i]=val+predicted;
  109221. fit_value[look->loneighbor[i-2]]&=0x7fff;
  109222. fit_value[look->hineighbor[i-2]]&=0x7fff;
  109223. }else{
  109224. fit_value[i]=predicted|0x8000;
  109225. }
  109226. }
  109227. return(fit_value);
  109228. }
  109229. eop:
  109230. return(NULL);
  109231. }
  109232. static int floor1_inverse2(vorbis_block *vb,vorbis_look_floor *in,void *memo,
  109233. float *out){
  109234. vorbis_look_floor1 *look=(vorbis_look_floor1 *)in;
  109235. vorbis_info_floor1 *info=look->vi;
  109236. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  109237. int n=ci->blocksizes[vb->W]/2;
  109238. int j;
  109239. if(memo){
  109240. /* render the lines */
  109241. int *fit_value=(int *)memo;
  109242. int hx=0;
  109243. int lx=0;
  109244. int ly=fit_value[0]*info->mult;
  109245. for(j=1;j<look->posts;j++){
  109246. int current=look->forward_index[j];
  109247. int hy=fit_value[current]&0x7fff;
  109248. if(hy==fit_value[current]){
  109249. hy*=info->mult;
  109250. hx=info->postlist[current];
  109251. render_line(lx,hx,ly,hy,out);
  109252. lx=hx;
  109253. ly=hy;
  109254. }
  109255. }
  109256. for(j=hx;j<n;j++)out[j]*=FLOOR1_fromdB_LOOKUP[ly]; /* be certain */
  109257. return(1);
  109258. }
  109259. memset(out,0,sizeof(*out)*n);
  109260. return(0);
  109261. }
  109262. /* export hooks */
  109263. vorbis_func_floor floor1_exportbundle={
  109264. &floor1_pack,&floor1_unpack,&floor1_look,&floor1_free_info,
  109265. &floor1_free_look,&floor1_inverse1,&floor1_inverse2
  109266. };
  109267. #endif
  109268. /********* End of inlined file: floor1.c *********/
  109269. /********* Start of inlined file: info.c *********/
  109270. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  109271. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  109272. // tasks..
  109273. #ifdef _MSC_VER
  109274. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  109275. #endif
  109276. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  109277. #if JUCE_USE_OGGVORBIS
  109278. /* general handling of the header and the vorbis_info structure (and
  109279. substructures) */
  109280. #include <stdlib.h>
  109281. #include <string.h>
  109282. #include <ctype.h>
  109283. static void _v_writestring(oggpack_buffer *o, const char *s, int bytes){
  109284. while(bytes--){
  109285. oggpack_write(o,*s++,8);
  109286. }
  109287. }
  109288. static void _v_readstring(oggpack_buffer *o,char *buf,int bytes){
  109289. while(bytes--){
  109290. *buf++=oggpack_read(o,8);
  109291. }
  109292. }
  109293. void vorbis_comment_init(vorbis_comment *vc){
  109294. memset(vc,0,sizeof(*vc));
  109295. }
  109296. void vorbis_comment_add(vorbis_comment *vc,char *comment){
  109297. vc->user_comments=(char**)_ogg_realloc(vc->user_comments,
  109298. (vc->comments+2)*sizeof(*vc->user_comments));
  109299. vc->comment_lengths=(int*)_ogg_realloc(vc->comment_lengths,
  109300. (vc->comments+2)*sizeof(*vc->comment_lengths));
  109301. vc->comment_lengths[vc->comments]=strlen(comment);
  109302. vc->user_comments[vc->comments]=(char*)_ogg_malloc(vc->comment_lengths[vc->comments]+1);
  109303. strcpy(vc->user_comments[vc->comments], comment);
  109304. vc->comments++;
  109305. vc->user_comments[vc->comments]=NULL;
  109306. }
  109307. void vorbis_comment_add_tag(vorbis_comment *vc, const char *tag, char *contents){
  109308. char *comment=(char*)alloca(strlen(tag)+strlen(contents)+2); /* +2 for = and \0 */
  109309. strcpy(comment, tag);
  109310. strcat(comment, "=");
  109311. strcat(comment, contents);
  109312. vorbis_comment_add(vc, comment);
  109313. }
  109314. /* This is more or less the same as strncasecmp - but that doesn't exist
  109315. * everywhere, and this is a fairly trivial function, so we include it */
  109316. static int tagcompare(const char *s1, const char *s2, int n){
  109317. int c=0;
  109318. while(c < n){
  109319. if(toupper(s1[c]) != toupper(s2[c]))
  109320. return !0;
  109321. c++;
  109322. }
  109323. return 0;
  109324. }
  109325. char *vorbis_comment_query(vorbis_comment *vc, char *tag, int count){
  109326. long i;
  109327. int found = 0;
  109328. int taglen = strlen(tag)+1; /* +1 for the = we append */
  109329. char *fulltag = (char*)alloca(taglen+ 1);
  109330. strcpy(fulltag, tag);
  109331. strcat(fulltag, "=");
  109332. for(i=0;i<vc->comments;i++){
  109333. if(!tagcompare(vc->user_comments[i], fulltag, taglen)){
  109334. if(count == found)
  109335. /* We return a pointer to the data, not a copy */
  109336. return vc->user_comments[i] + taglen;
  109337. else
  109338. found++;
  109339. }
  109340. }
  109341. return NULL; /* didn't find anything */
  109342. }
  109343. int vorbis_comment_query_count(vorbis_comment *vc, char *tag){
  109344. int i,count=0;
  109345. int taglen = strlen(tag)+1; /* +1 for the = we append */
  109346. char *fulltag = (char*)alloca(taglen+1);
  109347. strcpy(fulltag,tag);
  109348. strcat(fulltag, "=");
  109349. for(i=0;i<vc->comments;i++){
  109350. if(!tagcompare(vc->user_comments[i], fulltag, taglen))
  109351. count++;
  109352. }
  109353. return count;
  109354. }
  109355. void vorbis_comment_clear(vorbis_comment *vc){
  109356. if(vc){
  109357. long i;
  109358. for(i=0;i<vc->comments;i++)
  109359. if(vc->user_comments[i])_ogg_free(vc->user_comments[i]);
  109360. if(vc->user_comments)_ogg_free(vc->user_comments);
  109361. if(vc->comment_lengths)_ogg_free(vc->comment_lengths);
  109362. if(vc->vendor)_ogg_free(vc->vendor);
  109363. }
  109364. memset(vc,0,sizeof(*vc));
  109365. }
  109366. /* blocksize 0 is guaranteed to be short, 1 is guarantted to be long.
  109367. They may be equal, but short will never ge greater than long */
  109368. int vorbis_info_blocksize(vorbis_info *vi,int zo){
  109369. codec_setup_info *ci = (codec_setup_info*)vi->codec_setup;
  109370. return ci ? ci->blocksizes[zo] : -1;
  109371. }
  109372. /* used by synthesis, which has a full, alloced vi */
  109373. void vorbis_info_init(vorbis_info *vi){
  109374. memset(vi,0,sizeof(*vi));
  109375. vi->codec_setup=_ogg_calloc(1,sizeof(codec_setup_info));
  109376. }
  109377. void vorbis_info_clear(vorbis_info *vi){
  109378. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  109379. int i;
  109380. if(ci){
  109381. for(i=0;i<ci->modes;i++)
  109382. if(ci->mode_param[i])_ogg_free(ci->mode_param[i]);
  109383. for(i=0;i<ci->maps;i++) /* unpack does the range checking */
  109384. _mapping_P[ci->map_type[i]]->free_info(ci->map_param[i]);
  109385. for(i=0;i<ci->floors;i++) /* unpack does the range checking */
  109386. _floor_P[ci->floor_type[i]]->free_info(ci->floor_param[i]);
  109387. for(i=0;i<ci->residues;i++) /* unpack does the range checking */
  109388. _residue_P[ci->residue_type[i]]->free_info(ci->residue_param[i]);
  109389. for(i=0;i<ci->books;i++){
  109390. if(ci->book_param[i]){
  109391. /* knows if the book was not alloced */
  109392. vorbis_staticbook_destroy(ci->book_param[i]);
  109393. }
  109394. if(ci->fullbooks)
  109395. vorbis_book_clear(ci->fullbooks+i);
  109396. }
  109397. if(ci->fullbooks)
  109398. _ogg_free(ci->fullbooks);
  109399. for(i=0;i<ci->psys;i++)
  109400. _vi_psy_free(ci->psy_param[i]);
  109401. _ogg_free(ci);
  109402. }
  109403. memset(vi,0,sizeof(*vi));
  109404. }
  109405. /* Header packing/unpacking ********************************************/
  109406. static int _vorbis_unpack_info(vorbis_info *vi,oggpack_buffer *opb){
  109407. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  109408. if(!ci)return(OV_EFAULT);
  109409. vi->version=oggpack_read(opb,32);
  109410. if(vi->version!=0)return(OV_EVERSION);
  109411. vi->channels=oggpack_read(opb,8);
  109412. vi->rate=oggpack_read(opb,32);
  109413. vi->bitrate_upper=oggpack_read(opb,32);
  109414. vi->bitrate_nominal=oggpack_read(opb,32);
  109415. vi->bitrate_lower=oggpack_read(opb,32);
  109416. ci->blocksizes[0]=1<<oggpack_read(opb,4);
  109417. ci->blocksizes[1]=1<<oggpack_read(opb,4);
  109418. if(vi->rate<1)goto err_out;
  109419. if(vi->channels<1)goto err_out;
  109420. if(ci->blocksizes[0]<8)goto err_out;
  109421. if(ci->blocksizes[1]<ci->blocksizes[0])goto err_out;
  109422. if(oggpack_read(opb,1)!=1)goto err_out; /* EOP check */
  109423. return(0);
  109424. err_out:
  109425. vorbis_info_clear(vi);
  109426. return(OV_EBADHEADER);
  109427. }
  109428. static int _vorbis_unpack_comment(vorbis_comment *vc,oggpack_buffer *opb){
  109429. int i;
  109430. int vendorlen=oggpack_read(opb,32);
  109431. if(vendorlen<0)goto err_out;
  109432. vc->vendor=(char*)_ogg_calloc(vendorlen+1,1);
  109433. _v_readstring(opb,vc->vendor,vendorlen);
  109434. vc->comments=oggpack_read(opb,32);
  109435. if(vc->comments<0)goto err_out;
  109436. vc->user_comments=(char**)_ogg_calloc(vc->comments+1,sizeof(*vc->user_comments));
  109437. vc->comment_lengths=(int*)_ogg_calloc(vc->comments+1, sizeof(*vc->comment_lengths));
  109438. for(i=0;i<vc->comments;i++){
  109439. int len=oggpack_read(opb,32);
  109440. if(len<0)goto err_out;
  109441. vc->comment_lengths[i]=len;
  109442. vc->user_comments[i]=(char*)_ogg_calloc(len+1,1);
  109443. _v_readstring(opb,vc->user_comments[i],len);
  109444. }
  109445. if(oggpack_read(opb,1)!=1)goto err_out; /* EOP check */
  109446. return(0);
  109447. err_out:
  109448. vorbis_comment_clear(vc);
  109449. return(OV_EBADHEADER);
  109450. }
  109451. /* all of the real encoding details are here. The modes, books,
  109452. everything */
  109453. static int _vorbis_unpack_books(vorbis_info *vi,oggpack_buffer *opb){
  109454. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  109455. int i;
  109456. if(!ci)return(OV_EFAULT);
  109457. /* codebooks */
  109458. ci->books=oggpack_read(opb,8)+1;
  109459. /*ci->book_param=_ogg_calloc(ci->books,sizeof(*ci->book_param));*/
  109460. for(i=0;i<ci->books;i++){
  109461. ci->book_param[i]=(static_codebook*)_ogg_calloc(1,sizeof(*ci->book_param[i]));
  109462. if(vorbis_staticbook_unpack(opb,ci->book_param[i]))goto err_out;
  109463. }
  109464. /* time backend settings; hooks are unused */
  109465. {
  109466. int times=oggpack_read(opb,6)+1;
  109467. for(i=0;i<times;i++){
  109468. int test=oggpack_read(opb,16);
  109469. if(test<0 || test>=VI_TIMEB)goto err_out;
  109470. }
  109471. }
  109472. /* floor backend settings */
  109473. ci->floors=oggpack_read(opb,6)+1;
  109474. /*ci->floor_type=_ogg_malloc(ci->floors*sizeof(*ci->floor_type));*/
  109475. /*ci->floor_param=_ogg_calloc(ci->floors,sizeof(void *));*/
  109476. for(i=0;i<ci->floors;i++){
  109477. ci->floor_type[i]=oggpack_read(opb,16);
  109478. if(ci->floor_type[i]<0 || ci->floor_type[i]>=VI_FLOORB)goto err_out;
  109479. ci->floor_param[i]=_floor_P[ci->floor_type[i]]->unpack(vi,opb);
  109480. if(!ci->floor_param[i])goto err_out;
  109481. }
  109482. /* residue backend settings */
  109483. ci->residues=oggpack_read(opb,6)+1;
  109484. /*ci->residue_type=_ogg_malloc(ci->residues*sizeof(*ci->residue_type));*/
  109485. /*ci->residue_param=_ogg_calloc(ci->residues,sizeof(void *));*/
  109486. for(i=0;i<ci->residues;i++){
  109487. ci->residue_type[i]=oggpack_read(opb,16);
  109488. if(ci->residue_type[i]<0 || ci->residue_type[i]>=VI_RESB)goto err_out;
  109489. ci->residue_param[i]=_residue_P[ci->residue_type[i]]->unpack(vi,opb);
  109490. if(!ci->residue_param[i])goto err_out;
  109491. }
  109492. /* map backend settings */
  109493. ci->maps=oggpack_read(opb,6)+1;
  109494. /*ci->map_type=_ogg_malloc(ci->maps*sizeof(*ci->map_type));*/
  109495. /*ci->map_param=_ogg_calloc(ci->maps,sizeof(void *));*/
  109496. for(i=0;i<ci->maps;i++){
  109497. ci->map_type[i]=oggpack_read(opb,16);
  109498. if(ci->map_type[i]<0 || ci->map_type[i]>=VI_MAPB)goto err_out;
  109499. ci->map_param[i]=_mapping_P[ci->map_type[i]]->unpack(vi,opb);
  109500. if(!ci->map_param[i])goto err_out;
  109501. }
  109502. /* mode settings */
  109503. ci->modes=oggpack_read(opb,6)+1;
  109504. /*vi->mode_param=_ogg_calloc(vi->modes,sizeof(void *));*/
  109505. for(i=0;i<ci->modes;i++){
  109506. ci->mode_param[i]=(vorbis_info_mode*)_ogg_calloc(1,sizeof(*ci->mode_param[i]));
  109507. ci->mode_param[i]->blockflag=oggpack_read(opb,1);
  109508. ci->mode_param[i]->windowtype=oggpack_read(opb,16);
  109509. ci->mode_param[i]->transformtype=oggpack_read(opb,16);
  109510. ci->mode_param[i]->mapping=oggpack_read(opb,8);
  109511. if(ci->mode_param[i]->windowtype>=VI_WINDOWB)goto err_out;
  109512. if(ci->mode_param[i]->transformtype>=VI_WINDOWB)goto err_out;
  109513. if(ci->mode_param[i]->mapping>=ci->maps)goto err_out;
  109514. }
  109515. if(oggpack_read(opb,1)!=1)goto err_out; /* top level EOP check */
  109516. return(0);
  109517. err_out:
  109518. vorbis_info_clear(vi);
  109519. return(OV_EBADHEADER);
  109520. }
  109521. /* The Vorbis header is in three packets; the initial small packet in
  109522. the first page that identifies basic parameters, a second packet
  109523. with bitstream comments and a third packet that holds the
  109524. codebook. */
  109525. int vorbis_synthesis_headerin(vorbis_info *vi,vorbis_comment *vc,ogg_packet *op){
  109526. oggpack_buffer opb;
  109527. if(op){
  109528. oggpack_readinit(&opb,op->packet,op->bytes);
  109529. /* Which of the three types of header is this? */
  109530. /* Also verify header-ness, vorbis */
  109531. {
  109532. char buffer[6];
  109533. int packtype=oggpack_read(&opb,8);
  109534. memset(buffer,0,6);
  109535. _v_readstring(&opb,buffer,6);
  109536. if(memcmp(buffer,"vorbis",6)){
  109537. /* not a vorbis header */
  109538. return(OV_ENOTVORBIS);
  109539. }
  109540. switch(packtype){
  109541. case 0x01: /* least significant *bit* is read first */
  109542. if(!op->b_o_s){
  109543. /* Not the initial packet */
  109544. return(OV_EBADHEADER);
  109545. }
  109546. if(vi->rate!=0){
  109547. /* previously initialized info header */
  109548. return(OV_EBADHEADER);
  109549. }
  109550. return(_vorbis_unpack_info(vi,&opb));
  109551. case 0x03: /* least significant *bit* is read first */
  109552. if(vi->rate==0){
  109553. /* um... we didn't get the initial header */
  109554. return(OV_EBADHEADER);
  109555. }
  109556. return(_vorbis_unpack_comment(vc,&opb));
  109557. case 0x05: /* least significant *bit* is read first */
  109558. if(vi->rate==0 || vc->vendor==NULL){
  109559. /* um... we didn;t get the initial header or comments yet */
  109560. return(OV_EBADHEADER);
  109561. }
  109562. return(_vorbis_unpack_books(vi,&opb));
  109563. default:
  109564. /* Not a valid vorbis header type */
  109565. return(OV_EBADHEADER);
  109566. break;
  109567. }
  109568. }
  109569. }
  109570. return(OV_EBADHEADER);
  109571. }
  109572. /* pack side **********************************************************/
  109573. static int _vorbis_pack_info(oggpack_buffer *opb,vorbis_info *vi){
  109574. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  109575. if(!ci)return(OV_EFAULT);
  109576. /* preamble */
  109577. oggpack_write(opb,0x01,8);
  109578. _v_writestring(opb,"vorbis", 6);
  109579. /* basic information about the stream */
  109580. oggpack_write(opb,0x00,32);
  109581. oggpack_write(opb,vi->channels,8);
  109582. oggpack_write(opb,vi->rate,32);
  109583. oggpack_write(opb,vi->bitrate_upper,32);
  109584. oggpack_write(opb,vi->bitrate_nominal,32);
  109585. oggpack_write(opb,vi->bitrate_lower,32);
  109586. oggpack_write(opb,ilog2(ci->blocksizes[0]),4);
  109587. oggpack_write(opb,ilog2(ci->blocksizes[1]),4);
  109588. oggpack_write(opb,1,1);
  109589. return(0);
  109590. }
  109591. static int _vorbis_pack_comment(oggpack_buffer *opb,vorbis_comment *vc){
  109592. char temp[]="Xiph.Org libVorbis I 20050304";
  109593. int bytes = strlen(temp);
  109594. /* preamble */
  109595. oggpack_write(opb,0x03,8);
  109596. _v_writestring(opb,"vorbis", 6);
  109597. /* vendor */
  109598. oggpack_write(opb,bytes,32);
  109599. _v_writestring(opb,temp, bytes);
  109600. /* comments */
  109601. oggpack_write(opb,vc->comments,32);
  109602. if(vc->comments){
  109603. int i;
  109604. for(i=0;i<vc->comments;i++){
  109605. if(vc->user_comments[i]){
  109606. oggpack_write(opb,vc->comment_lengths[i],32);
  109607. _v_writestring(opb,vc->user_comments[i], vc->comment_lengths[i]);
  109608. }else{
  109609. oggpack_write(opb,0,32);
  109610. }
  109611. }
  109612. }
  109613. oggpack_write(opb,1,1);
  109614. return(0);
  109615. }
  109616. static int _vorbis_pack_books(oggpack_buffer *opb,vorbis_info *vi){
  109617. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  109618. int i;
  109619. if(!ci)return(OV_EFAULT);
  109620. oggpack_write(opb,0x05,8);
  109621. _v_writestring(opb,"vorbis", 6);
  109622. /* books */
  109623. oggpack_write(opb,ci->books-1,8);
  109624. for(i=0;i<ci->books;i++)
  109625. if(vorbis_staticbook_pack(ci->book_param[i],opb))goto err_out;
  109626. /* times; hook placeholders */
  109627. oggpack_write(opb,0,6);
  109628. oggpack_write(opb,0,16);
  109629. /* floors */
  109630. oggpack_write(opb,ci->floors-1,6);
  109631. for(i=0;i<ci->floors;i++){
  109632. oggpack_write(opb,ci->floor_type[i],16);
  109633. if(_floor_P[ci->floor_type[i]]->pack)
  109634. _floor_P[ci->floor_type[i]]->pack(ci->floor_param[i],opb);
  109635. else
  109636. goto err_out;
  109637. }
  109638. /* residues */
  109639. oggpack_write(opb,ci->residues-1,6);
  109640. for(i=0;i<ci->residues;i++){
  109641. oggpack_write(opb,ci->residue_type[i],16);
  109642. _residue_P[ci->residue_type[i]]->pack(ci->residue_param[i],opb);
  109643. }
  109644. /* maps */
  109645. oggpack_write(opb,ci->maps-1,6);
  109646. for(i=0;i<ci->maps;i++){
  109647. oggpack_write(opb,ci->map_type[i],16);
  109648. _mapping_P[ci->map_type[i]]->pack(vi,ci->map_param[i],opb);
  109649. }
  109650. /* modes */
  109651. oggpack_write(opb,ci->modes-1,6);
  109652. for(i=0;i<ci->modes;i++){
  109653. oggpack_write(opb,ci->mode_param[i]->blockflag,1);
  109654. oggpack_write(opb,ci->mode_param[i]->windowtype,16);
  109655. oggpack_write(opb,ci->mode_param[i]->transformtype,16);
  109656. oggpack_write(opb,ci->mode_param[i]->mapping,8);
  109657. }
  109658. oggpack_write(opb,1,1);
  109659. return(0);
  109660. err_out:
  109661. return(-1);
  109662. }
  109663. int vorbis_commentheader_out(vorbis_comment *vc,
  109664. ogg_packet *op){
  109665. oggpack_buffer opb;
  109666. oggpack_writeinit(&opb);
  109667. if(_vorbis_pack_comment(&opb,vc)) return OV_EIMPL;
  109668. op->packet = (unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  109669. memcpy(op->packet, opb.buffer, oggpack_bytes(&opb));
  109670. op->bytes=oggpack_bytes(&opb);
  109671. op->b_o_s=0;
  109672. op->e_o_s=0;
  109673. op->granulepos=0;
  109674. op->packetno=1;
  109675. return 0;
  109676. }
  109677. int vorbis_analysis_headerout(vorbis_dsp_state *v,
  109678. vorbis_comment *vc,
  109679. ogg_packet *op,
  109680. ogg_packet *op_comm,
  109681. ogg_packet *op_code){
  109682. int ret=OV_EIMPL;
  109683. vorbis_info *vi=v->vi;
  109684. oggpack_buffer opb;
  109685. private_state *b=(private_state*)v->backend_state;
  109686. if(!b){
  109687. ret=OV_EFAULT;
  109688. goto err_out;
  109689. }
  109690. /* first header packet **********************************************/
  109691. oggpack_writeinit(&opb);
  109692. if(_vorbis_pack_info(&opb,vi))goto err_out;
  109693. /* build the packet */
  109694. if(b->header)_ogg_free(b->header);
  109695. b->header=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  109696. memcpy(b->header,opb.buffer,oggpack_bytes(&opb));
  109697. op->packet=b->header;
  109698. op->bytes=oggpack_bytes(&opb);
  109699. op->b_o_s=1;
  109700. op->e_o_s=0;
  109701. op->granulepos=0;
  109702. op->packetno=0;
  109703. /* second header packet (comments) **********************************/
  109704. oggpack_reset(&opb);
  109705. if(_vorbis_pack_comment(&opb,vc))goto err_out;
  109706. if(b->header1)_ogg_free(b->header1);
  109707. b->header1=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  109708. memcpy(b->header1,opb.buffer,oggpack_bytes(&opb));
  109709. op_comm->packet=b->header1;
  109710. op_comm->bytes=oggpack_bytes(&opb);
  109711. op_comm->b_o_s=0;
  109712. op_comm->e_o_s=0;
  109713. op_comm->granulepos=0;
  109714. op_comm->packetno=1;
  109715. /* third header packet (modes/codebooks) ****************************/
  109716. oggpack_reset(&opb);
  109717. if(_vorbis_pack_books(&opb,vi))goto err_out;
  109718. if(b->header2)_ogg_free(b->header2);
  109719. b->header2=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  109720. memcpy(b->header2,opb.buffer,oggpack_bytes(&opb));
  109721. op_code->packet=b->header2;
  109722. op_code->bytes=oggpack_bytes(&opb);
  109723. op_code->b_o_s=0;
  109724. op_code->e_o_s=0;
  109725. op_code->granulepos=0;
  109726. op_code->packetno=2;
  109727. oggpack_writeclear(&opb);
  109728. return(0);
  109729. err_out:
  109730. oggpack_writeclear(&opb);
  109731. memset(op,0,sizeof(*op));
  109732. memset(op_comm,0,sizeof(*op_comm));
  109733. memset(op_code,0,sizeof(*op_code));
  109734. if(b->header)_ogg_free(b->header);
  109735. if(b->header1)_ogg_free(b->header1);
  109736. if(b->header2)_ogg_free(b->header2);
  109737. b->header=NULL;
  109738. b->header1=NULL;
  109739. b->header2=NULL;
  109740. return(ret);
  109741. }
  109742. double vorbis_granule_time(vorbis_dsp_state *v,ogg_int64_t granulepos){
  109743. if(granulepos>=0)
  109744. return((double)granulepos/v->vi->rate);
  109745. return(-1);
  109746. }
  109747. #endif
  109748. /********* End of inlined file: info.c *********/
  109749. /********* Start of inlined file: lpc.c *********/
  109750. /* Some of these routines (autocorrelator, LPC coefficient estimator)
  109751. are derived from code written by Jutta Degener and Carsten Bormann;
  109752. thus we include their copyright below. The entirety of this file
  109753. is freely redistributable on the condition that both of these
  109754. copyright notices are preserved without modification. */
  109755. /* Preserved Copyright: *********************************************/
  109756. /* Copyright 1992, 1993, 1994 by Jutta Degener and Carsten Bormann,
  109757. Technische Universita"t Berlin
  109758. Any use of this software is permitted provided that this notice is not
  109759. removed and that neither the authors nor the Technische Universita"t
  109760. Berlin are deemed to have made any representations as to the
  109761. suitability of this software for any purpose nor are held responsible
  109762. for any defects of this software. THERE IS ABSOLUTELY NO WARRANTY FOR
  109763. THIS SOFTWARE.
  109764. As a matter of courtesy, the authors request to be informed about uses
  109765. this software has found, about bugs in this software, and about any
  109766. improvements that may be of general interest.
  109767. Berlin, 28.11.1994
  109768. Jutta Degener
  109769. Carsten Bormann
  109770. *********************************************************************/
  109771. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  109772. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  109773. // tasks..
  109774. #ifdef _MSC_VER
  109775. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  109776. #endif
  109777. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  109778. #if JUCE_USE_OGGVORBIS
  109779. #include <stdlib.h>
  109780. #include <string.h>
  109781. #include <math.h>
  109782. /* Autocorrelation LPC coeff generation algorithm invented by
  109783. N. Levinson in 1947, modified by J. Durbin in 1959. */
  109784. /* Input : n elements of time doamin data
  109785. Output: m lpc coefficients, excitation energy */
  109786. float vorbis_lpc_from_data(float *data,float *lpci,int n,int m){
  109787. double *aut=(double*)alloca(sizeof(*aut)*(m+1));
  109788. double *lpc=(double*)alloca(sizeof(*lpc)*(m));
  109789. double error;
  109790. int i,j;
  109791. /* autocorrelation, p+1 lag coefficients */
  109792. j=m+1;
  109793. while(j--){
  109794. double d=0; /* double needed for accumulator depth */
  109795. for(i=j;i<n;i++)d+=(double)data[i]*data[i-j];
  109796. aut[j]=d;
  109797. }
  109798. /* Generate lpc coefficients from autocorr values */
  109799. error=aut[0];
  109800. for(i=0;i<m;i++){
  109801. double r= -aut[i+1];
  109802. if(error==0){
  109803. memset(lpci,0,m*sizeof(*lpci));
  109804. return 0;
  109805. }
  109806. /* Sum up this iteration's reflection coefficient; note that in
  109807. Vorbis we don't save it. If anyone wants to recycle this code
  109808. and needs reflection coefficients, save the results of 'r' from
  109809. each iteration. */
  109810. for(j=0;j<i;j++)r-=lpc[j]*aut[i-j];
  109811. r/=error;
  109812. /* Update LPC coefficients and total error */
  109813. lpc[i]=r;
  109814. for(j=0;j<i/2;j++){
  109815. double tmp=lpc[j];
  109816. lpc[j]+=r*lpc[i-1-j];
  109817. lpc[i-1-j]+=r*tmp;
  109818. }
  109819. if(i%2)lpc[j]+=lpc[j]*r;
  109820. error*=1.f-r*r;
  109821. }
  109822. for(j=0;j<m;j++)lpci[j]=(float)lpc[j];
  109823. /* we need the error value to know how big an impulse to hit the
  109824. filter with later */
  109825. return error;
  109826. }
  109827. void vorbis_lpc_predict(float *coeff,float *prime,int m,
  109828. float *data,long n){
  109829. /* in: coeff[0...m-1] LPC coefficients
  109830. prime[0...m-1] initial values (allocated size of n+m-1)
  109831. out: data[0...n-1] data samples */
  109832. long i,j,o,p;
  109833. float y;
  109834. float *work=(float*)alloca(sizeof(*work)*(m+n));
  109835. if(!prime)
  109836. for(i=0;i<m;i++)
  109837. work[i]=0.f;
  109838. else
  109839. for(i=0;i<m;i++)
  109840. work[i]=prime[i];
  109841. for(i=0;i<n;i++){
  109842. y=0;
  109843. o=i;
  109844. p=m;
  109845. for(j=0;j<m;j++)
  109846. y-=work[o++]*coeff[--p];
  109847. data[i]=work[o]=y;
  109848. }
  109849. }
  109850. #endif
  109851. /********* End of inlined file: lpc.c *********/
  109852. /********* Start of inlined file: lsp.c *********/
  109853. /* Note that the lpc-lsp conversion finds the roots of polynomial with
  109854. an iterative root polisher (CACM algorithm 283). It *is* possible
  109855. to confuse this algorithm into not converging; that should only
  109856. happen with absurdly closely spaced roots (very sharp peaks in the
  109857. LPC f response) which in turn should be impossible in our use of
  109858. the code. If this *does* happen anyway, it's a bug in the floor
  109859. finder; find the cause of the confusion (probably a single bin
  109860. spike or accidental near-float-limit resolution problems) and
  109861. correct it. */
  109862. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  109863. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  109864. // tasks..
  109865. #ifdef _MSC_VER
  109866. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  109867. #endif
  109868. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  109869. #if JUCE_USE_OGGVORBIS
  109870. #include <math.h>
  109871. #include <string.h>
  109872. #include <stdlib.h>
  109873. /********* Start of inlined file: lookup.h *********/
  109874. #ifndef _V_LOOKUP_H_
  109875. #ifdef FLOAT_LOOKUP
  109876. extern float vorbis_coslook(float a);
  109877. extern float vorbis_invsqlook(float a);
  109878. extern float vorbis_invsq2explook(int a);
  109879. extern float vorbis_fromdBlook(float a);
  109880. #endif
  109881. #ifdef INT_LOOKUP
  109882. extern long vorbis_invsqlook_i(long a,long e);
  109883. extern long vorbis_coslook_i(long a);
  109884. extern float vorbis_fromdBlook_i(long a);
  109885. #endif
  109886. #endif
  109887. /********* End of inlined file: lookup.h *********/
  109888. /* three possible LSP to f curve functions; the exact computation
  109889. (float), a lookup based float implementation, and an integer
  109890. implementation. The float lookup is likely the optimal choice on
  109891. any machine with an FPU. The integer implementation is *not* fixed
  109892. point (due to the need for a large dynamic range and thus a
  109893. seperately tracked exponent) and thus much more complex than the
  109894. relatively simple float implementations. It's mostly for future
  109895. work on a fully fixed point implementation for processors like the
  109896. ARM family. */
  109897. /* undefine both for the 'old' but more precise implementation */
  109898. #define FLOAT_LOOKUP
  109899. #undef INT_LOOKUP
  109900. #ifdef FLOAT_LOOKUP
  109901. /********* Start of inlined file: lookup.c *********/
  109902. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  109903. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  109904. // tasks..
  109905. #ifdef _MSC_VER
  109906. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  109907. #endif
  109908. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  109909. #if JUCE_USE_OGGVORBIS
  109910. #include <math.h>
  109911. /********* Start of inlined file: lookup.h *********/
  109912. #ifndef _V_LOOKUP_H_
  109913. #ifdef FLOAT_LOOKUP
  109914. extern float vorbis_coslook(float a);
  109915. extern float vorbis_invsqlook(float a);
  109916. extern float vorbis_invsq2explook(int a);
  109917. extern float vorbis_fromdBlook(float a);
  109918. #endif
  109919. #ifdef INT_LOOKUP
  109920. extern long vorbis_invsqlook_i(long a,long e);
  109921. extern long vorbis_coslook_i(long a);
  109922. extern float vorbis_fromdBlook_i(long a);
  109923. #endif
  109924. #endif
  109925. /********* End of inlined file: lookup.h *********/
  109926. /********* Start of inlined file: lookup_data.h *********/
  109927. #ifndef _V_LOOKUP_DATA_H_
  109928. #ifdef FLOAT_LOOKUP
  109929. #define COS_LOOKUP_SZ 128
  109930. static float COS_LOOKUP[COS_LOOKUP_SZ+1]={
  109931. +1.0000000000000f,+0.9996988186962f,+0.9987954562052f,+0.9972904566787f,
  109932. +0.9951847266722f,+0.9924795345987f,+0.9891765099648f,+0.9852776423889f,
  109933. +0.9807852804032f,+0.9757021300385f,+0.9700312531945f,+0.9637760657954f,
  109934. +0.9569403357322f,+0.9495281805930f,+0.9415440651830f,+0.9329927988347f,
  109935. +0.9238795325113f,+0.9142097557035f,+0.9039892931234f,+0.8932243011955f,
  109936. +0.8819212643484f,+0.8700869911087f,+0.8577286100003f,+0.8448535652497f,
  109937. +0.8314696123025f,+0.8175848131516f,+0.8032075314806f,+0.7883464276266f,
  109938. +0.7730104533627f,+0.7572088465065f,+0.7409511253550f,+0.7242470829515f,
  109939. +0.7071067811865f,+0.6895405447371f,+0.6715589548470f,+0.6531728429538f,
  109940. +0.6343932841636f,+0.6152315905806f,+0.5956993044924f,+0.5758081914178f,
  109941. +0.5555702330196f,+0.5349976198871f,+0.5141027441932f,+0.4928981922298f,
  109942. +0.4713967368260f,+0.4496113296546f,+0.4275550934303f,+0.4052413140050f,
  109943. +0.3826834323651f,+0.3598950365350f,+0.3368898533922f,+0.3136817403989f,
  109944. +0.2902846772545f,+0.2667127574749f,+0.2429801799033f,+0.2191012401569f,
  109945. +0.1950903220161f,+0.1709618887603f,+0.1467304744554f,+0.1224106751992f,
  109946. +0.0980171403296f,+0.0735645635997f,+0.0490676743274f,+0.0245412285229f,
  109947. +0.0000000000000f,-0.0245412285229f,-0.0490676743274f,-0.0735645635997f,
  109948. -0.0980171403296f,-0.1224106751992f,-0.1467304744554f,-0.1709618887603f,
  109949. -0.1950903220161f,-0.2191012401569f,-0.2429801799033f,-0.2667127574749f,
  109950. -0.2902846772545f,-0.3136817403989f,-0.3368898533922f,-0.3598950365350f,
  109951. -0.3826834323651f,-0.4052413140050f,-0.4275550934303f,-0.4496113296546f,
  109952. -0.4713967368260f,-0.4928981922298f,-0.5141027441932f,-0.5349976198871f,
  109953. -0.5555702330196f,-0.5758081914178f,-0.5956993044924f,-0.6152315905806f,
  109954. -0.6343932841636f,-0.6531728429538f,-0.6715589548470f,-0.6895405447371f,
  109955. -0.7071067811865f,-0.7242470829515f,-0.7409511253550f,-0.7572088465065f,
  109956. -0.7730104533627f,-0.7883464276266f,-0.8032075314806f,-0.8175848131516f,
  109957. -0.8314696123025f,-0.8448535652497f,-0.8577286100003f,-0.8700869911087f,
  109958. -0.8819212643484f,-0.8932243011955f,-0.9039892931234f,-0.9142097557035f,
  109959. -0.9238795325113f,-0.9329927988347f,-0.9415440651830f,-0.9495281805930f,
  109960. -0.9569403357322f,-0.9637760657954f,-0.9700312531945f,-0.9757021300385f,
  109961. -0.9807852804032f,-0.9852776423889f,-0.9891765099648f,-0.9924795345987f,
  109962. -0.9951847266722f,-0.9972904566787f,-0.9987954562052f,-0.9996988186962f,
  109963. -1.0000000000000f,
  109964. };
  109965. #define INVSQ_LOOKUP_SZ 32
  109966. static float INVSQ_LOOKUP[INVSQ_LOOKUP_SZ+1]={
  109967. 1.414213562373f,1.392621247646f,1.371988681140f,1.352246807566f,
  109968. 1.333333333333f,1.315191898443f,1.297771369046f,1.281025230441f,
  109969. 1.264911064067f,1.249390095109f,1.234426799697f,1.219988562661f,
  109970. 1.206045378311f,1.192569588000f,1.179535649239f,1.166919931983f,
  109971. 1.154700538379f,1.142857142857f,1.131370849898f,1.120224067222f,
  109972. 1.109400392450f,1.098884511590f,1.088662107904f,1.078719779941f,
  109973. 1.069044967650f,1.059625885652f,1.050451462878f,1.041511287847f,
  109974. 1.032795558989f,1.024295039463f,1.016001016002f,1.007905261358f,
  109975. 1.000000000000f,
  109976. };
  109977. #define INVSQ2EXP_LOOKUP_MIN (-32)
  109978. #define INVSQ2EXP_LOOKUP_MAX 32
  109979. static float INVSQ2EXP_LOOKUP[INVSQ2EXP_LOOKUP_MAX-\
  109980. INVSQ2EXP_LOOKUP_MIN+1]={
  109981. 65536.f, 46340.95001f, 32768.f, 23170.47501f,
  109982. 16384.f, 11585.2375f, 8192.f, 5792.618751f,
  109983. 4096.f, 2896.309376f, 2048.f, 1448.154688f,
  109984. 1024.f, 724.0773439f, 512.f, 362.038672f,
  109985. 256.f, 181.019336f, 128.f, 90.50966799f,
  109986. 64.f, 45.254834f, 32.f, 22.627417f,
  109987. 16.f, 11.3137085f, 8.f, 5.656854249f,
  109988. 4.f, 2.828427125f, 2.f, 1.414213562f,
  109989. 1.f, 0.7071067812f, 0.5f, 0.3535533906f,
  109990. 0.25f, 0.1767766953f, 0.125f, 0.08838834765f,
  109991. 0.0625f, 0.04419417382f, 0.03125f, 0.02209708691f,
  109992. 0.015625f, 0.01104854346f, 0.0078125f, 0.005524271728f,
  109993. 0.00390625f, 0.002762135864f, 0.001953125f, 0.001381067932f,
  109994. 0.0009765625f, 0.000690533966f, 0.00048828125f, 0.000345266983f,
  109995. 0.000244140625f,0.0001726334915f,0.0001220703125f,8.631674575e-05f,
  109996. 6.103515625e-05f,4.315837288e-05f,3.051757812e-05f,2.157918644e-05f,
  109997. 1.525878906e-05f,
  109998. };
  109999. #endif
  110000. #define FROMdB_LOOKUP_SZ 35
  110001. #define FROMdB2_LOOKUP_SZ 32
  110002. #define FROMdB_SHIFT 5
  110003. #define FROMdB2_SHIFT 3
  110004. #define FROMdB2_MASK 31
  110005. static float FROMdB_LOOKUP[FROMdB_LOOKUP_SZ]={
  110006. 1.f, 0.6309573445f, 0.3981071706f, 0.2511886432f,
  110007. 0.1584893192f, 0.1f, 0.06309573445f, 0.03981071706f,
  110008. 0.02511886432f, 0.01584893192f, 0.01f, 0.006309573445f,
  110009. 0.003981071706f, 0.002511886432f, 0.001584893192f, 0.001f,
  110010. 0.0006309573445f,0.0003981071706f,0.0002511886432f,0.0001584893192f,
  110011. 0.0001f,6.309573445e-05f,3.981071706e-05f,2.511886432e-05f,
  110012. 1.584893192e-05f, 1e-05f,6.309573445e-06f,3.981071706e-06f,
  110013. 2.511886432e-06f,1.584893192e-06f, 1e-06f,6.309573445e-07f,
  110014. 3.981071706e-07f,2.511886432e-07f,1.584893192e-07f,
  110015. };
  110016. static float FROMdB2_LOOKUP[FROMdB2_LOOKUP_SZ]={
  110017. 0.9928302478f, 0.9786445908f, 0.9646616199f, 0.9508784391f,
  110018. 0.9372921937f, 0.92390007f, 0.9106992942f, 0.8976871324f,
  110019. 0.8848608897f, 0.8722179097f, 0.8597555737f, 0.8474713009f,
  110020. 0.835362547f, 0.8234268041f, 0.8116616003f, 0.8000644989f,
  110021. 0.7886330981f, 0.7773650302f, 0.7662579617f, 0.755309592f,
  110022. 0.7445176537f, 0.7338799116f, 0.7233941627f, 0.7130582353f,
  110023. 0.7028699885f, 0.6928273125f, 0.6829281272f, 0.6731703824f,
  110024. 0.6635520573f, 0.6540711597f, 0.6447257262f, 0.6355138211f,
  110025. };
  110026. #ifdef INT_LOOKUP
  110027. #define INVSQ_LOOKUP_I_SHIFT 10
  110028. #define INVSQ_LOOKUP_I_MASK 1023
  110029. static long INVSQ_LOOKUP_I[64+1]={
  110030. 92682l, 91966l, 91267l, 90583l,
  110031. 89915l, 89261l, 88621l, 87995l,
  110032. 87381l, 86781l, 86192l, 85616l,
  110033. 85051l, 84497l, 83953l, 83420l,
  110034. 82897l, 82384l, 81880l, 81385l,
  110035. 80899l, 80422l, 79953l, 79492l,
  110036. 79039l, 78594l, 78156l, 77726l,
  110037. 77302l, 76885l, 76475l, 76072l,
  110038. 75674l, 75283l, 74898l, 74519l,
  110039. 74146l, 73778l, 73415l, 73058l,
  110040. 72706l, 72359l, 72016l, 71679l,
  110041. 71347l, 71019l, 70695l, 70376l,
  110042. 70061l, 69750l, 69444l, 69141l,
  110043. 68842l, 68548l, 68256l, 67969l,
  110044. 67685l, 67405l, 67128l, 66855l,
  110045. 66585l, 66318l, 66054l, 65794l,
  110046. 65536l,
  110047. };
  110048. #define COS_LOOKUP_I_SHIFT 9
  110049. #define COS_LOOKUP_I_MASK 511
  110050. #define COS_LOOKUP_I_SZ 128
  110051. static long COS_LOOKUP_I[COS_LOOKUP_I_SZ+1]={
  110052. 16384l, 16379l, 16364l, 16340l,
  110053. 16305l, 16261l, 16207l, 16143l,
  110054. 16069l, 15986l, 15893l, 15791l,
  110055. 15679l, 15557l, 15426l, 15286l,
  110056. 15137l, 14978l, 14811l, 14635l,
  110057. 14449l, 14256l, 14053l, 13842l,
  110058. 13623l, 13395l, 13160l, 12916l,
  110059. 12665l, 12406l, 12140l, 11866l,
  110060. 11585l, 11297l, 11003l, 10702l,
  110061. 10394l, 10080l, 9760l, 9434l,
  110062. 9102l, 8765l, 8423l, 8076l,
  110063. 7723l, 7366l, 7005l, 6639l,
  110064. 6270l, 5897l, 5520l, 5139l,
  110065. 4756l, 4370l, 3981l, 3590l,
  110066. 3196l, 2801l, 2404l, 2006l,
  110067. 1606l, 1205l, 804l, 402l,
  110068. 0l, -401l, -803l, -1204l,
  110069. -1605l, -2005l, -2403l, -2800l,
  110070. -3195l, -3589l, -3980l, -4369l,
  110071. -4755l, -5138l, -5519l, -5896l,
  110072. -6269l, -6638l, -7004l, -7365l,
  110073. -7722l, -8075l, -8422l, -8764l,
  110074. -9101l, -9433l, -9759l, -10079l,
  110075. -10393l, -10701l, -11002l, -11296l,
  110076. -11584l, -11865l, -12139l, -12405l,
  110077. -12664l, -12915l, -13159l, -13394l,
  110078. -13622l, -13841l, -14052l, -14255l,
  110079. -14448l, -14634l, -14810l, -14977l,
  110080. -15136l, -15285l, -15425l, -15556l,
  110081. -15678l, -15790l, -15892l, -15985l,
  110082. -16068l, -16142l, -16206l, -16260l,
  110083. -16304l, -16339l, -16363l, -16378l,
  110084. -16383l,
  110085. };
  110086. #endif
  110087. #endif
  110088. /********* End of inlined file: lookup_data.h *********/
  110089. #ifdef FLOAT_LOOKUP
  110090. /* interpolated lookup based cos function, domain 0 to PI only */
  110091. float vorbis_coslook(float a){
  110092. double d=a*(.31830989*(float)COS_LOOKUP_SZ);
  110093. int i=vorbis_ftoi(d-.5);
  110094. return COS_LOOKUP[i]+ (d-i)*(COS_LOOKUP[i+1]-COS_LOOKUP[i]);
  110095. }
  110096. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  110097. float vorbis_invsqlook(float a){
  110098. double d=a*(2.f*(float)INVSQ_LOOKUP_SZ)-(float)INVSQ_LOOKUP_SZ;
  110099. int i=vorbis_ftoi(d-.5f);
  110100. return INVSQ_LOOKUP[i]+ (d-i)*(INVSQ_LOOKUP[i+1]-INVSQ_LOOKUP[i]);
  110101. }
  110102. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  110103. float vorbis_invsq2explook(int a){
  110104. return INVSQ2EXP_LOOKUP[a-INVSQ2EXP_LOOKUP_MIN];
  110105. }
  110106. #include <stdio.h>
  110107. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  110108. float vorbis_fromdBlook(float a){
  110109. int i=vorbis_ftoi(a*((float)(-(1<<FROMdB2_SHIFT)))-.5f);
  110110. return (i<0)?1.f:
  110111. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  110112. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  110113. }
  110114. #endif
  110115. #ifdef INT_LOOKUP
  110116. /* interpolated 1./sqrt(p) where .5 <= a < 1. (.100000... to .111111...) in
  110117. 16.16 format
  110118. returns in m.8 format */
  110119. long vorbis_invsqlook_i(long a,long e){
  110120. long i=(a&0x7fff)>>(INVSQ_LOOKUP_I_SHIFT-1);
  110121. long d=(a&INVSQ_LOOKUP_I_MASK)<<(16-INVSQ_LOOKUP_I_SHIFT); /* 0.16 */
  110122. long val=INVSQ_LOOKUP_I[i]- /* 1.16 */
  110123. (((INVSQ_LOOKUP_I[i]-INVSQ_LOOKUP_I[i+1])* /* 0.16 */
  110124. d)>>16); /* result 1.16 */
  110125. e+=32;
  110126. if(e&1)val=(val*5792)>>13; /* multiply val by 1/sqrt(2) */
  110127. e=(e>>1)-8;
  110128. return(val>>e);
  110129. }
  110130. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  110131. /* a is in n.12 format */
  110132. float vorbis_fromdBlook_i(long a){
  110133. int i=(-a)>>(12-FROMdB2_SHIFT);
  110134. return (i<0)?1.f:
  110135. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  110136. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  110137. }
  110138. /* interpolated lookup based cos function, domain 0 to PI only */
  110139. /* a is in 0.16 format, where 0==0, 2^^16-1==PI, return 0.14 */
  110140. long vorbis_coslook_i(long a){
  110141. int i=a>>COS_LOOKUP_I_SHIFT;
  110142. int d=a&COS_LOOKUP_I_MASK;
  110143. return COS_LOOKUP_I[i]- ((d*(COS_LOOKUP_I[i]-COS_LOOKUP_I[i+1]))>>
  110144. COS_LOOKUP_I_SHIFT);
  110145. }
  110146. #endif
  110147. #endif
  110148. /********* End of inlined file: lookup.c *********/
  110149. /* catch this in the build system; we #include for
  110150. compilers (like gcc) that can't inline across
  110151. modules */
  110152. /* side effect: changes *lsp to cosines of lsp */
  110153. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  110154. float amp,float ampoffset){
  110155. int i;
  110156. float wdel=M_PI/ln;
  110157. vorbis_fpu_control fpu;
  110158. (void) fpu; // to avoid an unused variable warning
  110159. vorbis_fpu_setround(&fpu);
  110160. for(i=0;i<m;i++)lsp[i]=vorbis_coslook(lsp[i]);
  110161. i=0;
  110162. while(i<n){
  110163. int k=map[i];
  110164. int qexp;
  110165. float p=.7071067812f;
  110166. float q=.7071067812f;
  110167. float w=vorbis_coslook(wdel*k);
  110168. float *ftmp=lsp;
  110169. int c=m>>1;
  110170. do{
  110171. q*=ftmp[0]-w;
  110172. p*=ftmp[1]-w;
  110173. ftmp+=2;
  110174. }while(--c);
  110175. if(m&1){
  110176. /* odd order filter; slightly assymetric */
  110177. /* the last coefficient */
  110178. q*=ftmp[0]-w;
  110179. q*=q;
  110180. p*=p*(1.f-w*w);
  110181. }else{
  110182. /* even order filter; still symmetric */
  110183. q*=q*(1.f+w);
  110184. p*=p*(1.f-w);
  110185. }
  110186. q=frexp(p+q,&qexp);
  110187. q=vorbis_fromdBlook(amp*
  110188. vorbis_invsqlook(q)*
  110189. vorbis_invsq2explook(qexp+m)-
  110190. ampoffset);
  110191. do{
  110192. curve[i++]*=q;
  110193. }while(map[i]==k);
  110194. }
  110195. vorbis_fpu_restore(fpu);
  110196. }
  110197. #else
  110198. #ifdef INT_LOOKUP
  110199. /********* Start of inlined file: lookup.c *********/
  110200. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  110201. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  110202. // tasks..
  110203. #ifdef _MSC_VER
  110204. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  110205. #endif
  110206. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  110207. #if JUCE_USE_OGGVORBIS
  110208. #include <math.h>
  110209. /********* Start of inlined file: lookup.h *********/
  110210. #ifndef _V_LOOKUP_H_
  110211. #ifdef FLOAT_LOOKUP
  110212. extern float vorbis_coslook(float a);
  110213. extern float vorbis_invsqlook(float a);
  110214. extern float vorbis_invsq2explook(int a);
  110215. extern float vorbis_fromdBlook(float a);
  110216. #endif
  110217. #ifdef INT_LOOKUP
  110218. extern long vorbis_invsqlook_i(long a,long e);
  110219. extern long vorbis_coslook_i(long a);
  110220. extern float vorbis_fromdBlook_i(long a);
  110221. #endif
  110222. #endif
  110223. /********* End of inlined file: lookup.h *********/
  110224. /********* Start of inlined file: lookup_data.h *********/
  110225. #ifndef _V_LOOKUP_DATA_H_
  110226. #ifdef FLOAT_LOOKUP
  110227. #define COS_LOOKUP_SZ 128
  110228. static float COS_LOOKUP[COS_LOOKUP_SZ+1]={
  110229. +1.0000000000000f,+0.9996988186962f,+0.9987954562052f,+0.9972904566787f,
  110230. +0.9951847266722f,+0.9924795345987f,+0.9891765099648f,+0.9852776423889f,
  110231. +0.9807852804032f,+0.9757021300385f,+0.9700312531945f,+0.9637760657954f,
  110232. +0.9569403357322f,+0.9495281805930f,+0.9415440651830f,+0.9329927988347f,
  110233. +0.9238795325113f,+0.9142097557035f,+0.9039892931234f,+0.8932243011955f,
  110234. +0.8819212643484f,+0.8700869911087f,+0.8577286100003f,+0.8448535652497f,
  110235. +0.8314696123025f,+0.8175848131516f,+0.8032075314806f,+0.7883464276266f,
  110236. +0.7730104533627f,+0.7572088465065f,+0.7409511253550f,+0.7242470829515f,
  110237. +0.7071067811865f,+0.6895405447371f,+0.6715589548470f,+0.6531728429538f,
  110238. +0.6343932841636f,+0.6152315905806f,+0.5956993044924f,+0.5758081914178f,
  110239. +0.5555702330196f,+0.5349976198871f,+0.5141027441932f,+0.4928981922298f,
  110240. +0.4713967368260f,+0.4496113296546f,+0.4275550934303f,+0.4052413140050f,
  110241. +0.3826834323651f,+0.3598950365350f,+0.3368898533922f,+0.3136817403989f,
  110242. +0.2902846772545f,+0.2667127574749f,+0.2429801799033f,+0.2191012401569f,
  110243. +0.1950903220161f,+0.1709618887603f,+0.1467304744554f,+0.1224106751992f,
  110244. +0.0980171403296f,+0.0735645635997f,+0.0490676743274f,+0.0245412285229f,
  110245. +0.0000000000000f,-0.0245412285229f,-0.0490676743274f,-0.0735645635997f,
  110246. -0.0980171403296f,-0.1224106751992f,-0.1467304744554f,-0.1709618887603f,
  110247. -0.1950903220161f,-0.2191012401569f,-0.2429801799033f,-0.2667127574749f,
  110248. -0.2902846772545f,-0.3136817403989f,-0.3368898533922f,-0.3598950365350f,
  110249. -0.3826834323651f,-0.4052413140050f,-0.4275550934303f,-0.4496113296546f,
  110250. -0.4713967368260f,-0.4928981922298f,-0.5141027441932f,-0.5349976198871f,
  110251. -0.5555702330196f,-0.5758081914178f,-0.5956993044924f,-0.6152315905806f,
  110252. -0.6343932841636f,-0.6531728429538f,-0.6715589548470f,-0.6895405447371f,
  110253. -0.7071067811865f,-0.7242470829515f,-0.7409511253550f,-0.7572088465065f,
  110254. -0.7730104533627f,-0.7883464276266f,-0.8032075314806f,-0.8175848131516f,
  110255. -0.8314696123025f,-0.8448535652497f,-0.8577286100003f,-0.8700869911087f,
  110256. -0.8819212643484f,-0.8932243011955f,-0.9039892931234f,-0.9142097557035f,
  110257. -0.9238795325113f,-0.9329927988347f,-0.9415440651830f,-0.9495281805930f,
  110258. -0.9569403357322f,-0.9637760657954f,-0.9700312531945f,-0.9757021300385f,
  110259. -0.9807852804032f,-0.9852776423889f,-0.9891765099648f,-0.9924795345987f,
  110260. -0.9951847266722f,-0.9972904566787f,-0.9987954562052f,-0.9996988186962f,
  110261. -1.0000000000000f,
  110262. };
  110263. #define INVSQ_LOOKUP_SZ 32
  110264. static float INVSQ_LOOKUP[INVSQ_LOOKUP_SZ+1]={
  110265. 1.414213562373f,1.392621247646f,1.371988681140f,1.352246807566f,
  110266. 1.333333333333f,1.315191898443f,1.297771369046f,1.281025230441f,
  110267. 1.264911064067f,1.249390095109f,1.234426799697f,1.219988562661f,
  110268. 1.206045378311f,1.192569588000f,1.179535649239f,1.166919931983f,
  110269. 1.154700538379f,1.142857142857f,1.131370849898f,1.120224067222f,
  110270. 1.109400392450f,1.098884511590f,1.088662107904f,1.078719779941f,
  110271. 1.069044967650f,1.059625885652f,1.050451462878f,1.041511287847f,
  110272. 1.032795558989f,1.024295039463f,1.016001016002f,1.007905261358f,
  110273. 1.000000000000f,
  110274. };
  110275. #define INVSQ2EXP_LOOKUP_MIN (-32)
  110276. #define INVSQ2EXP_LOOKUP_MAX 32
  110277. static float INVSQ2EXP_LOOKUP[INVSQ2EXP_LOOKUP_MAX-\
  110278. INVSQ2EXP_LOOKUP_MIN+1]={
  110279. 65536.f, 46340.95001f, 32768.f, 23170.47501f,
  110280. 16384.f, 11585.2375f, 8192.f, 5792.618751f,
  110281. 4096.f, 2896.309376f, 2048.f, 1448.154688f,
  110282. 1024.f, 724.0773439f, 512.f, 362.038672f,
  110283. 256.f, 181.019336f, 128.f, 90.50966799f,
  110284. 64.f, 45.254834f, 32.f, 22.627417f,
  110285. 16.f, 11.3137085f, 8.f, 5.656854249f,
  110286. 4.f, 2.828427125f, 2.f, 1.414213562f,
  110287. 1.f, 0.7071067812f, 0.5f, 0.3535533906f,
  110288. 0.25f, 0.1767766953f, 0.125f, 0.08838834765f,
  110289. 0.0625f, 0.04419417382f, 0.03125f, 0.02209708691f,
  110290. 0.015625f, 0.01104854346f, 0.0078125f, 0.005524271728f,
  110291. 0.00390625f, 0.002762135864f, 0.001953125f, 0.001381067932f,
  110292. 0.0009765625f, 0.000690533966f, 0.00048828125f, 0.000345266983f,
  110293. 0.000244140625f,0.0001726334915f,0.0001220703125f,8.631674575e-05f,
  110294. 6.103515625e-05f,4.315837288e-05f,3.051757812e-05f,2.157918644e-05f,
  110295. 1.525878906e-05f,
  110296. };
  110297. #endif
  110298. #define FROMdB_LOOKUP_SZ 35
  110299. #define FROMdB2_LOOKUP_SZ 32
  110300. #define FROMdB_SHIFT 5
  110301. #define FROMdB2_SHIFT 3
  110302. #define FROMdB2_MASK 31
  110303. static float FROMdB_LOOKUP[FROMdB_LOOKUP_SZ]={
  110304. 1.f, 0.6309573445f, 0.3981071706f, 0.2511886432f,
  110305. 0.1584893192f, 0.1f, 0.06309573445f, 0.03981071706f,
  110306. 0.02511886432f, 0.01584893192f, 0.01f, 0.006309573445f,
  110307. 0.003981071706f, 0.002511886432f, 0.001584893192f, 0.001f,
  110308. 0.0006309573445f,0.0003981071706f,0.0002511886432f,0.0001584893192f,
  110309. 0.0001f,6.309573445e-05f,3.981071706e-05f,2.511886432e-05f,
  110310. 1.584893192e-05f, 1e-05f,6.309573445e-06f,3.981071706e-06f,
  110311. 2.511886432e-06f,1.584893192e-06f, 1e-06f,6.309573445e-07f,
  110312. 3.981071706e-07f,2.511886432e-07f,1.584893192e-07f,
  110313. };
  110314. static float FROMdB2_LOOKUP[FROMdB2_LOOKUP_SZ]={
  110315. 0.9928302478f, 0.9786445908f, 0.9646616199f, 0.9508784391f,
  110316. 0.9372921937f, 0.92390007f, 0.9106992942f, 0.8976871324f,
  110317. 0.8848608897f, 0.8722179097f, 0.8597555737f, 0.8474713009f,
  110318. 0.835362547f, 0.8234268041f, 0.8116616003f, 0.8000644989f,
  110319. 0.7886330981f, 0.7773650302f, 0.7662579617f, 0.755309592f,
  110320. 0.7445176537f, 0.7338799116f, 0.7233941627f, 0.7130582353f,
  110321. 0.7028699885f, 0.6928273125f, 0.6829281272f, 0.6731703824f,
  110322. 0.6635520573f, 0.6540711597f, 0.6447257262f, 0.6355138211f,
  110323. };
  110324. #ifdef INT_LOOKUP
  110325. #define INVSQ_LOOKUP_I_SHIFT 10
  110326. #define INVSQ_LOOKUP_I_MASK 1023
  110327. static long INVSQ_LOOKUP_I[64+1]={
  110328. 92682l, 91966l, 91267l, 90583l,
  110329. 89915l, 89261l, 88621l, 87995l,
  110330. 87381l, 86781l, 86192l, 85616l,
  110331. 85051l, 84497l, 83953l, 83420l,
  110332. 82897l, 82384l, 81880l, 81385l,
  110333. 80899l, 80422l, 79953l, 79492l,
  110334. 79039l, 78594l, 78156l, 77726l,
  110335. 77302l, 76885l, 76475l, 76072l,
  110336. 75674l, 75283l, 74898l, 74519l,
  110337. 74146l, 73778l, 73415l, 73058l,
  110338. 72706l, 72359l, 72016l, 71679l,
  110339. 71347l, 71019l, 70695l, 70376l,
  110340. 70061l, 69750l, 69444l, 69141l,
  110341. 68842l, 68548l, 68256l, 67969l,
  110342. 67685l, 67405l, 67128l, 66855l,
  110343. 66585l, 66318l, 66054l, 65794l,
  110344. 65536l,
  110345. };
  110346. #define COS_LOOKUP_I_SHIFT 9
  110347. #define COS_LOOKUP_I_MASK 511
  110348. #define COS_LOOKUP_I_SZ 128
  110349. static long COS_LOOKUP_I[COS_LOOKUP_I_SZ+1]={
  110350. 16384l, 16379l, 16364l, 16340l,
  110351. 16305l, 16261l, 16207l, 16143l,
  110352. 16069l, 15986l, 15893l, 15791l,
  110353. 15679l, 15557l, 15426l, 15286l,
  110354. 15137l, 14978l, 14811l, 14635l,
  110355. 14449l, 14256l, 14053l, 13842l,
  110356. 13623l, 13395l, 13160l, 12916l,
  110357. 12665l, 12406l, 12140l, 11866l,
  110358. 11585l, 11297l, 11003l, 10702l,
  110359. 10394l, 10080l, 9760l, 9434l,
  110360. 9102l, 8765l, 8423l, 8076l,
  110361. 7723l, 7366l, 7005l, 6639l,
  110362. 6270l, 5897l, 5520l, 5139l,
  110363. 4756l, 4370l, 3981l, 3590l,
  110364. 3196l, 2801l, 2404l, 2006l,
  110365. 1606l, 1205l, 804l, 402l,
  110366. 0l, -401l, -803l, -1204l,
  110367. -1605l, -2005l, -2403l, -2800l,
  110368. -3195l, -3589l, -3980l, -4369l,
  110369. -4755l, -5138l, -5519l, -5896l,
  110370. -6269l, -6638l, -7004l, -7365l,
  110371. -7722l, -8075l, -8422l, -8764l,
  110372. -9101l, -9433l, -9759l, -10079l,
  110373. -10393l, -10701l, -11002l, -11296l,
  110374. -11584l, -11865l, -12139l, -12405l,
  110375. -12664l, -12915l, -13159l, -13394l,
  110376. -13622l, -13841l, -14052l, -14255l,
  110377. -14448l, -14634l, -14810l, -14977l,
  110378. -15136l, -15285l, -15425l, -15556l,
  110379. -15678l, -15790l, -15892l, -15985l,
  110380. -16068l, -16142l, -16206l, -16260l,
  110381. -16304l, -16339l, -16363l, -16378l,
  110382. -16383l,
  110383. };
  110384. #endif
  110385. #endif
  110386. /********* End of inlined file: lookup_data.h *********/
  110387. #ifdef FLOAT_LOOKUP
  110388. /* interpolated lookup based cos function, domain 0 to PI only */
  110389. float vorbis_coslook(float a){
  110390. double d=a*(.31830989*(float)COS_LOOKUP_SZ);
  110391. int i=vorbis_ftoi(d-.5);
  110392. return COS_LOOKUP[i]+ (d-i)*(COS_LOOKUP[i+1]-COS_LOOKUP[i]);
  110393. }
  110394. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  110395. float vorbis_invsqlook(float a){
  110396. double d=a*(2.f*(float)INVSQ_LOOKUP_SZ)-(float)INVSQ_LOOKUP_SZ;
  110397. int i=vorbis_ftoi(d-.5f);
  110398. return INVSQ_LOOKUP[i]+ (d-i)*(INVSQ_LOOKUP[i+1]-INVSQ_LOOKUP[i]);
  110399. }
  110400. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  110401. float vorbis_invsq2explook(int a){
  110402. return INVSQ2EXP_LOOKUP[a-INVSQ2EXP_LOOKUP_MIN];
  110403. }
  110404. #include <stdio.h>
  110405. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  110406. float vorbis_fromdBlook(float a){
  110407. int i=vorbis_ftoi(a*((float)(-(1<<FROMdB2_SHIFT)))-.5f);
  110408. return (i<0)?1.f:
  110409. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  110410. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  110411. }
  110412. #endif
  110413. #ifdef INT_LOOKUP
  110414. /* interpolated 1./sqrt(p) where .5 <= a < 1. (.100000... to .111111...) in
  110415. 16.16 format
  110416. returns in m.8 format */
  110417. long vorbis_invsqlook_i(long a,long e){
  110418. long i=(a&0x7fff)>>(INVSQ_LOOKUP_I_SHIFT-1);
  110419. long d=(a&INVSQ_LOOKUP_I_MASK)<<(16-INVSQ_LOOKUP_I_SHIFT); /* 0.16 */
  110420. long val=INVSQ_LOOKUP_I[i]- /* 1.16 */
  110421. (((INVSQ_LOOKUP_I[i]-INVSQ_LOOKUP_I[i+1])* /* 0.16 */
  110422. d)>>16); /* result 1.16 */
  110423. e+=32;
  110424. if(e&1)val=(val*5792)>>13; /* multiply val by 1/sqrt(2) */
  110425. e=(e>>1)-8;
  110426. return(val>>e);
  110427. }
  110428. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  110429. /* a is in n.12 format */
  110430. float vorbis_fromdBlook_i(long a){
  110431. int i=(-a)>>(12-FROMdB2_SHIFT);
  110432. return (i<0)?1.f:
  110433. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  110434. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  110435. }
  110436. /* interpolated lookup based cos function, domain 0 to PI only */
  110437. /* a is in 0.16 format, where 0==0, 2^^16-1==PI, return 0.14 */
  110438. long vorbis_coslook_i(long a){
  110439. int i=a>>COS_LOOKUP_I_SHIFT;
  110440. int d=a&COS_LOOKUP_I_MASK;
  110441. return COS_LOOKUP_I[i]- ((d*(COS_LOOKUP_I[i]-COS_LOOKUP_I[i+1]))>>
  110442. COS_LOOKUP_I_SHIFT);
  110443. }
  110444. #endif
  110445. #endif
  110446. /********* End of inlined file: lookup.c *********/
  110447. /* catch this in the build system; we #include for
  110448. compilers (like gcc) that can't inline across
  110449. modules */
  110450. static int MLOOP_1[64]={
  110451. 0,10,11,11, 12,12,12,12, 13,13,13,13, 13,13,13,13,
  110452. 14,14,14,14, 14,14,14,14, 14,14,14,14, 14,14,14,14,
  110453. 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
  110454. 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
  110455. };
  110456. static int MLOOP_2[64]={
  110457. 0,4,5,5, 6,6,6,6, 7,7,7,7, 7,7,7,7,
  110458. 8,8,8,8, 8,8,8,8, 8,8,8,8, 8,8,8,8,
  110459. 9,9,9,9, 9,9,9,9, 9,9,9,9, 9,9,9,9,
  110460. 9,9,9,9, 9,9,9,9, 9,9,9,9, 9,9,9,9,
  110461. };
  110462. static int MLOOP_3[8]={0,1,2,2,3,3,3,3};
  110463. /* side effect: changes *lsp to cosines of lsp */
  110464. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  110465. float amp,float ampoffset){
  110466. /* 0 <= m < 256 */
  110467. /* set up for using all int later */
  110468. int i;
  110469. int ampoffseti=rint(ampoffset*4096.f);
  110470. int ampi=rint(amp*16.f);
  110471. long *ilsp=alloca(m*sizeof(*ilsp));
  110472. for(i=0;i<m;i++)ilsp[i]=vorbis_coslook_i(lsp[i]/M_PI*65536.f+.5f);
  110473. i=0;
  110474. while(i<n){
  110475. int j,k=map[i];
  110476. unsigned long pi=46341; /* 2**-.5 in 0.16 */
  110477. unsigned long qi=46341;
  110478. int qexp=0,shift;
  110479. long wi=vorbis_coslook_i(k*65536/ln);
  110480. qi*=labs(ilsp[0]-wi);
  110481. pi*=labs(ilsp[1]-wi);
  110482. for(j=3;j<m;j+=2){
  110483. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  110484. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  110485. shift=MLOOP_3[(pi|qi)>>16];
  110486. qi=(qi>>shift)*labs(ilsp[j-1]-wi);
  110487. pi=(pi>>shift)*labs(ilsp[j]-wi);
  110488. qexp+=shift;
  110489. }
  110490. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  110491. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  110492. shift=MLOOP_3[(pi|qi)>>16];
  110493. /* pi,qi normalized collectively, both tracked using qexp */
  110494. if(m&1){
  110495. /* odd order filter; slightly assymetric */
  110496. /* the last coefficient */
  110497. qi=(qi>>shift)*labs(ilsp[j-1]-wi);
  110498. pi=(pi>>shift)<<14;
  110499. qexp+=shift;
  110500. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  110501. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  110502. shift=MLOOP_3[(pi|qi)>>16];
  110503. pi>>=shift;
  110504. qi>>=shift;
  110505. qexp+=shift-14*((m+1)>>1);
  110506. pi=((pi*pi)>>16);
  110507. qi=((qi*qi)>>16);
  110508. qexp=qexp*2+m;
  110509. pi*=(1<<14)-((wi*wi)>>14);
  110510. qi+=pi>>14;
  110511. }else{
  110512. /* even order filter; still symmetric */
  110513. /* p*=p(1-w), q*=q(1+w), let normalization drift because it isn't
  110514. worth tracking step by step */
  110515. pi>>=shift;
  110516. qi>>=shift;
  110517. qexp+=shift-7*m;
  110518. pi=((pi*pi)>>16);
  110519. qi=((qi*qi)>>16);
  110520. qexp=qexp*2+m;
  110521. pi*=(1<<14)-wi;
  110522. qi*=(1<<14)+wi;
  110523. qi=(qi+pi)>>14;
  110524. }
  110525. /* we've let the normalization drift because it wasn't important;
  110526. however, for the lookup, things must be normalized again. We
  110527. need at most one right shift or a number of left shifts */
  110528. if(qi&0xffff0000){ /* checks for 1.xxxxxxxxxxxxxxxx */
  110529. qi>>=1; qexp++;
  110530. }else
  110531. while(qi && !(qi&0x8000)){ /* checks for 0.0xxxxxxxxxxxxxxx or less*/
  110532. qi<<=1; qexp--;
  110533. }
  110534. amp=vorbis_fromdBlook_i(ampi* /* n.4 */
  110535. vorbis_invsqlook_i(qi,qexp)-
  110536. /* m.8, m+n<=8 */
  110537. ampoffseti); /* 8.12[0] */
  110538. curve[i]*=amp;
  110539. while(map[++i]==k)curve[i]*=amp;
  110540. }
  110541. }
  110542. #else
  110543. /* old, nonoptimized but simple version for any poor sap who needs to
  110544. figure out what the hell this code does, or wants the other
  110545. fraction of a dB precision */
  110546. /* side effect: changes *lsp to cosines of lsp */
  110547. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  110548. float amp,float ampoffset){
  110549. int i;
  110550. float wdel=M_PI/ln;
  110551. for(i=0;i<m;i++)lsp[i]=2.f*cos(lsp[i]);
  110552. i=0;
  110553. while(i<n){
  110554. int j,k=map[i];
  110555. float p=.5f;
  110556. float q=.5f;
  110557. float w=2.f*cos(wdel*k);
  110558. for(j=1;j<m;j+=2){
  110559. q *= w-lsp[j-1];
  110560. p *= w-lsp[j];
  110561. }
  110562. if(j==m){
  110563. /* odd order filter; slightly assymetric */
  110564. /* the last coefficient */
  110565. q*=w-lsp[j-1];
  110566. p*=p*(4.f-w*w);
  110567. q*=q;
  110568. }else{
  110569. /* even order filter; still symmetric */
  110570. p*=p*(2.f-w);
  110571. q*=q*(2.f+w);
  110572. }
  110573. q=fromdB(amp/sqrt(p+q)-ampoffset);
  110574. curve[i]*=q;
  110575. while(map[++i]==k)curve[i]*=q;
  110576. }
  110577. }
  110578. #endif
  110579. #endif
  110580. static void cheby(float *g, int ord) {
  110581. int i, j;
  110582. g[0] *= .5f;
  110583. for(i=2; i<= ord; i++) {
  110584. for(j=ord; j >= i; j--) {
  110585. g[j-2] -= g[j];
  110586. g[j] += g[j];
  110587. }
  110588. }
  110589. }
  110590. static int comp(const void *a,const void *b){
  110591. return (*(float *)a<*(float *)b)-(*(float *)a>*(float *)b);
  110592. }
  110593. /* Newton-Raphson-Maehly actually functioned as a decent root finder,
  110594. but there are root sets for which it gets into limit cycles
  110595. (exacerbated by zero suppression) and fails. We can't afford to
  110596. fail, even if the failure is 1 in 100,000,000, so we now use
  110597. Laguerre and later polish with Newton-Raphson (which can then
  110598. afford to fail) */
  110599. #define EPSILON 10e-7
  110600. static int Laguerre_With_Deflation(float *a,int ord,float *r){
  110601. int i,m;
  110602. double lastdelta=0.f;
  110603. double *defl=(double*)alloca(sizeof(*defl)*(ord+1));
  110604. for(i=0;i<=ord;i++)defl[i]=a[i];
  110605. for(m=ord;m>0;m--){
  110606. double newx=0.f,delta;
  110607. /* iterate a root */
  110608. while(1){
  110609. double p=defl[m],pp=0.f,ppp=0.f,denom;
  110610. /* eval the polynomial and its first two derivatives */
  110611. for(i=m;i>0;i--){
  110612. ppp = newx*ppp + pp;
  110613. pp = newx*pp + p;
  110614. p = newx*p + defl[i-1];
  110615. }
  110616. /* Laguerre's method */
  110617. denom=(m-1) * ((m-1)*pp*pp - m*p*ppp);
  110618. if(denom<0)
  110619. return(-1); /* complex root! The LPC generator handed us a bad filter */
  110620. if(pp>0){
  110621. denom = pp + sqrt(denom);
  110622. if(denom<EPSILON)denom=EPSILON;
  110623. }else{
  110624. denom = pp - sqrt(denom);
  110625. if(denom>-(EPSILON))denom=-(EPSILON);
  110626. }
  110627. delta = m*p/denom;
  110628. newx -= delta;
  110629. if(delta<0.f)delta*=-1;
  110630. if(fabs(delta/newx)<10e-12)break;
  110631. lastdelta=delta;
  110632. }
  110633. r[m-1]=newx;
  110634. /* forward deflation */
  110635. for(i=m;i>0;i--)
  110636. defl[i-1]+=newx*defl[i];
  110637. defl++;
  110638. }
  110639. return(0);
  110640. }
  110641. /* for spit-and-polish only */
  110642. static int Newton_Raphson(float *a,int ord,float *r){
  110643. int i, k, count=0;
  110644. double error=1.f;
  110645. double *root=(double*)alloca(ord*sizeof(*root));
  110646. for(i=0; i<ord;i++) root[i] = r[i];
  110647. while(error>1e-20){
  110648. error=0;
  110649. for(i=0; i<ord; i++) { /* Update each point. */
  110650. double pp=0.,delta;
  110651. double rooti=root[i];
  110652. double p=a[ord];
  110653. for(k=ord-1; k>= 0; k--) {
  110654. pp= pp* rooti + p;
  110655. p = p * rooti + a[k];
  110656. }
  110657. delta = p/pp;
  110658. root[i] -= delta;
  110659. error+= delta*delta;
  110660. }
  110661. if(count>40)return(-1);
  110662. count++;
  110663. }
  110664. /* Replaced the original bubble sort with a real sort. With your
  110665. help, we can eliminate the bubble sort in our lifetime. --Monty */
  110666. for(i=0; i<ord;i++) r[i] = root[i];
  110667. return(0);
  110668. }
  110669. /* Convert lpc coefficients to lsp coefficients */
  110670. int vorbis_lpc_to_lsp(float *lpc,float *lsp,int m){
  110671. int order2=(m+1)>>1;
  110672. int g1_order,g2_order;
  110673. float *g1=(float*)alloca(sizeof(*g1)*(order2+1));
  110674. float *g2=(float*)alloca(sizeof(*g2)*(order2+1));
  110675. float *g1r=(float*)alloca(sizeof(*g1r)*(order2+1));
  110676. float *g2r=(float*)alloca(sizeof(*g2r)*(order2+1));
  110677. int i;
  110678. /* even and odd are slightly different base cases */
  110679. g1_order=(m+1)>>1;
  110680. g2_order=(m) >>1;
  110681. /* Compute the lengths of the x polynomials. */
  110682. /* Compute the first half of K & R F1 & F2 polynomials. */
  110683. /* Compute half of the symmetric and antisymmetric polynomials. */
  110684. /* Remove the roots at +1 and -1. */
  110685. g1[g1_order] = 1.f;
  110686. for(i=1;i<=g1_order;i++) g1[g1_order-i] = lpc[i-1]+lpc[m-i];
  110687. g2[g2_order] = 1.f;
  110688. for(i=1;i<=g2_order;i++) g2[g2_order-i] = lpc[i-1]-lpc[m-i];
  110689. if(g1_order>g2_order){
  110690. for(i=2; i<=g2_order;i++) g2[g2_order-i] += g2[g2_order-i+2];
  110691. }else{
  110692. for(i=1; i<=g1_order;i++) g1[g1_order-i] -= g1[g1_order-i+1];
  110693. for(i=1; i<=g2_order;i++) g2[g2_order-i] += g2[g2_order-i+1];
  110694. }
  110695. /* Convert into polynomials in cos(alpha) */
  110696. cheby(g1,g1_order);
  110697. cheby(g2,g2_order);
  110698. /* Find the roots of the 2 even polynomials.*/
  110699. if(Laguerre_With_Deflation(g1,g1_order,g1r) ||
  110700. Laguerre_With_Deflation(g2,g2_order,g2r))
  110701. return(-1);
  110702. Newton_Raphson(g1,g1_order,g1r); /* if it fails, it leaves g1r alone */
  110703. Newton_Raphson(g2,g2_order,g2r); /* if it fails, it leaves g2r alone */
  110704. qsort(g1r,g1_order,sizeof(*g1r),comp);
  110705. qsort(g2r,g2_order,sizeof(*g2r),comp);
  110706. for(i=0;i<g1_order;i++)
  110707. lsp[i*2] = acos(g1r[i]);
  110708. for(i=0;i<g2_order;i++)
  110709. lsp[i*2+1] = acos(g2r[i]);
  110710. return(0);
  110711. }
  110712. #endif
  110713. /********* End of inlined file: lsp.c *********/
  110714. /********* Start of inlined file: mapping0.c *********/
  110715. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  110716. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  110717. // tasks..
  110718. #ifdef _MSC_VER
  110719. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  110720. #endif
  110721. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  110722. #if JUCE_USE_OGGVORBIS
  110723. #include <stdlib.h>
  110724. #include <stdio.h>
  110725. #include <string.h>
  110726. #include <math.h>
  110727. /* simplistic, wasteful way of doing this (unique lookup for each
  110728. mode/submapping); there should be a central repository for
  110729. identical lookups. That will require minor work, so I'm putting it
  110730. off as low priority.
  110731. Why a lookup for each backend in a given mode? Because the
  110732. blocksize is set by the mode, and low backend lookups may require
  110733. parameters from other areas of the mode/mapping */
  110734. static void mapping0_free_info(vorbis_info_mapping *i){
  110735. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)i;
  110736. if(info){
  110737. memset(info,0,sizeof(*info));
  110738. _ogg_free(info);
  110739. }
  110740. }
  110741. static int ilog3(unsigned int v){
  110742. int ret=0;
  110743. if(v)--v;
  110744. while(v){
  110745. ret++;
  110746. v>>=1;
  110747. }
  110748. return(ret);
  110749. }
  110750. static void mapping0_pack(vorbis_info *vi,vorbis_info_mapping *vm,
  110751. oggpack_buffer *opb){
  110752. int i;
  110753. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)vm;
  110754. /* another 'we meant to do it this way' hack... up to beta 4, we
  110755. packed 4 binary zeros here to signify one submapping in use. We
  110756. now redefine that to mean four bitflags that indicate use of
  110757. deeper features; bit0:submappings, bit1:coupling,
  110758. bit2,3:reserved. This is backward compatable with all actual uses
  110759. of the beta code. */
  110760. if(info->submaps>1){
  110761. oggpack_write(opb,1,1);
  110762. oggpack_write(opb,info->submaps-1,4);
  110763. }else
  110764. oggpack_write(opb,0,1);
  110765. if(info->coupling_steps>0){
  110766. oggpack_write(opb,1,1);
  110767. oggpack_write(opb,info->coupling_steps-1,8);
  110768. for(i=0;i<info->coupling_steps;i++){
  110769. oggpack_write(opb,info->coupling_mag[i],ilog3(vi->channels));
  110770. oggpack_write(opb,info->coupling_ang[i],ilog3(vi->channels));
  110771. }
  110772. }else
  110773. oggpack_write(opb,0,1);
  110774. oggpack_write(opb,0,2); /* 2,3:reserved */
  110775. /* we don't write the channel submappings if we only have one... */
  110776. if(info->submaps>1){
  110777. for(i=0;i<vi->channels;i++)
  110778. oggpack_write(opb,info->chmuxlist[i],4);
  110779. }
  110780. for(i=0;i<info->submaps;i++){
  110781. oggpack_write(opb,0,8); /* time submap unused */
  110782. oggpack_write(opb,info->floorsubmap[i],8);
  110783. oggpack_write(opb,info->residuesubmap[i],8);
  110784. }
  110785. }
  110786. /* also responsible for range checking */
  110787. static vorbis_info_mapping *mapping0_unpack(vorbis_info *vi,oggpack_buffer *opb){
  110788. int i;
  110789. vorbis_info_mapping0 *info=(vorbis_info_mapping0*)_ogg_calloc(1,sizeof(*info));
  110790. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  110791. memset(info,0,sizeof(*info));
  110792. if(oggpack_read(opb,1))
  110793. info->submaps=oggpack_read(opb,4)+1;
  110794. else
  110795. info->submaps=1;
  110796. if(oggpack_read(opb,1)){
  110797. info->coupling_steps=oggpack_read(opb,8)+1;
  110798. for(i=0;i<info->coupling_steps;i++){
  110799. int testM=info->coupling_mag[i]=oggpack_read(opb,ilog3(vi->channels));
  110800. int testA=info->coupling_ang[i]=oggpack_read(opb,ilog3(vi->channels));
  110801. if(testM<0 ||
  110802. testA<0 ||
  110803. testM==testA ||
  110804. testM>=vi->channels ||
  110805. testA>=vi->channels) goto err_out;
  110806. }
  110807. }
  110808. if(oggpack_read(opb,2)>0)goto err_out; /* 2,3:reserved */
  110809. if(info->submaps>1){
  110810. for(i=0;i<vi->channels;i++){
  110811. info->chmuxlist[i]=oggpack_read(opb,4);
  110812. if(info->chmuxlist[i]>=info->submaps)goto err_out;
  110813. }
  110814. }
  110815. for(i=0;i<info->submaps;i++){
  110816. oggpack_read(opb,8); /* time submap unused */
  110817. info->floorsubmap[i]=oggpack_read(opb,8);
  110818. if(info->floorsubmap[i]>=ci->floors)goto err_out;
  110819. info->residuesubmap[i]=oggpack_read(opb,8);
  110820. if(info->residuesubmap[i]>=ci->residues)goto err_out;
  110821. }
  110822. return info;
  110823. err_out:
  110824. mapping0_free_info(info);
  110825. return(NULL);
  110826. }
  110827. #if 0
  110828. static long seq=0;
  110829. static ogg_int64_t total=0;
  110830. static float FLOOR1_fromdB_LOOKUP[256]={
  110831. 1.0649863e-07F, 1.1341951e-07F, 1.2079015e-07F, 1.2863978e-07F,
  110832. 1.3699951e-07F, 1.4590251e-07F, 1.5538408e-07F, 1.6548181e-07F,
  110833. 1.7623575e-07F, 1.8768855e-07F, 1.9988561e-07F, 2.128753e-07F,
  110834. 2.2670913e-07F, 2.4144197e-07F, 2.5713223e-07F, 2.7384213e-07F,
  110835. 2.9163793e-07F, 3.1059021e-07F, 3.3077411e-07F, 3.5226968e-07F,
  110836. 3.7516214e-07F, 3.9954229e-07F, 4.2550680e-07F, 4.5315863e-07F,
  110837. 4.8260743e-07F, 5.1396998e-07F, 5.4737065e-07F, 5.8294187e-07F,
  110838. 6.2082472e-07F, 6.6116941e-07F, 7.0413592e-07F, 7.4989464e-07F,
  110839. 7.9862701e-07F, 8.5052630e-07F, 9.0579828e-07F, 9.6466216e-07F,
  110840. 1.0273513e-06F, 1.0941144e-06F, 1.1652161e-06F, 1.2409384e-06F,
  110841. 1.3215816e-06F, 1.4074654e-06F, 1.4989305e-06F, 1.5963394e-06F,
  110842. 1.7000785e-06F, 1.8105592e-06F, 1.9282195e-06F, 2.0535261e-06F,
  110843. 2.1869758e-06F, 2.3290978e-06F, 2.4804557e-06F, 2.6416497e-06F,
  110844. 2.8133190e-06F, 2.9961443e-06F, 3.1908506e-06F, 3.3982101e-06F,
  110845. 3.6190449e-06F, 3.8542308e-06F, 4.1047004e-06F, 4.3714470e-06F,
  110846. 4.6555282e-06F, 4.9580707e-06F, 5.2802740e-06F, 5.6234160e-06F,
  110847. 5.9888572e-06F, 6.3780469e-06F, 6.7925283e-06F, 7.2339451e-06F,
  110848. 7.7040476e-06F, 8.2047000e-06F, 8.7378876e-06F, 9.3057248e-06F,
  110849. 9.9104632e-06F, 1.0554501e-05F, 1.1240392e-05F, 1.1970856e-05F,
  110850. 1.2748789e-05F, 1.3577278e-05F, 1.4459606e-05F, 1.5399272e-05F,
  110851. 1.6400004e-05F, 1.7465768e-05F, 1.8600792e-05F, 1.9809576e-05F,
  110852. 2.1096914e-05F, 2.2467911e-05F, 2.3928002e-05F, 2.5482978e-05F,
  110853. 2.7139006e-05F, 2.8902651e-05F, 3.0780908e-05F, 3.2781225e-05F,
  110854. 3.4911534e-05F, 3.7180282e-05F, 3.9596466e-05F, 4.2169667e-05F,
  110855. 4.4910090e-05F, 4.7828601e-05F, 5.0936773e-05F, 5.4246931e-05F,
  110856. 5.7772202e-05F, 6.1526565e-05F, 6.5524908e-05F, 6.9783085e-05F,
  110857. 7.4317983e-05F, 7.9147585e-05F, 8.4291040e-05F, 8.9768747e-05F,
  110858. 9.5602426e-05F, 0.00010181521F, 0.00010843174F, 0.00011547824F,
  110859. 0.00012298267F, 0.00013097477F, 0.00013948625F, 0.00014855085F,
  110860. 0.00015820453F, 0.00016848555F, 0.00017943469F, 0.00019109536F,
  110861. 0.00020351382F, 0.00021673929F, 0.00023082423F, 0.00024582449F,
  110862. 0.00026179955F, 0.00027881276F, 0.00029693158F, 0.00031622787F,
  110863. 0.00033677814F, 0.00035866388F, 0.00038197188F, 0.00040679456F,
  110864. 0.00043323036F, 0.00046138411F, 0.00049136745F, 0.00052329927F,
  110865. 0.00055730621F, 0.00059352311F, 0.00063209358F, 0.00067317058F,
  110866. 0.00071691700F, 0.00076350630F, 0.00081312324F, 0.00086596457F,
  110867. 0.00092223983F, 0.00098217216F, 0.0010459992F, 0.0011139742F,
  110868. 0.0011863665F, 0.0012634633F, 0.0013455702F, 0.0014330129F,
  110869. 0.0015261382F, 0.0016253153F, 0.0017309374F, 0.0018434235F,
  110870. 0.0019632195F, 0.0020908006F, 0.0022266726F, 0.0023713743F,
  110871. 0.0025254795F, 0.0026895994F, 0.0028643847F, 0.0030505286F,
  110872. 0.0032487691F, 0.0034598925F, 0.0036847358F, 0.0039241906F,
  110873. 0.0041792066F, 0.0044507950F, 0.0047400328F, 0.0050480668F,
  110874. 0.0053761186F, 0.0057254891F, 0.0060975636F, 0.0064938176F,
  110875. 0.0069158225F, 0.0073652516F, 0.0078438871F, 0.0083536271F,
  110876. 0.0088964928F, 0.009474637F, 0.010090352F, 0.010746080F,
  110877. 0.011444421F, 0.012188144F, 0.012980198F, 0.013823725F,
  110878. 0.014722068F, 0.015678791F, 0.016697687F, 0.017782797F,
  110879. 0.018938423F, 0.020169149F, 0.021479854F, 0.022875735F,
  110880. 0.024362330F, 0.025945531F, 0.027631618F, 0.029427276F,
  110881. 0.031339626F, 0.033376252F, 0.035545228F, 0.037855157F,
  110882. 0.040315199F, 0.042935108F, 0.045725273F, 0.048696758F,
  110883. 0.051861348F, 0.055231591F, 0.058820850F, 0.062643361F,
  110884. 0.066714279F, 0.071049749F, 0.075666962F, 0.080584227F,
  110885. 0.085821044F, 0.091398179F, 0.097337747F, 0.10366330F,
  110886. 0.11039993F, 0.11757434F, 0.12521498F, 0.13335215F,
  110887. 0.14201813F, 0.15124727F, 0.16107617F, 0.17154380F,
  110888. 0.18269168F, 0.19456402F, 0.20720788F, 0.22067342F,
  110889. 0.23501402F, 0.25028656F, 0.26655159F, 0.28387361F,
  110890. 0.30232132F, 0.32196786F, 0.34289114F, 0.36517414F,
  110891. 0.38890521F, 0.41417847F, 0.44109412F, 0.46975890F,
  110892. 0.50028648F, 0.53279791F, 0.56742212F, 0.60429640F,
  110893. 0.64356699F, 0.68538959F, 0.72993007F, 0.77736504F,
  110894. 0.82788260F, 0.88168307F, 0.9389798F, 1.F,
  110895. };
  110896. #endif
  110897. extern int *floor1_fit(vorbis_block *vb,void *look,
  110898. const float *logmdct, /* in */
  110899. const float *logmask);
  110900. extern int *floor1_interpolate_fit(vorbis_block *vb,void *look,
  110901. int *A,int *B,
  110902. int del);
  110903. extern int floor1_encode(oggpack_buffer *opb,vorbis_block *vb,
  110904. void*look,
  110905. int *post,int *ilogmask);
  110906. static int mapping0_forward(vorbis_block *vb){
  110907. vorbis_dsp_state *vd=vb->vd;
  110908. vorbis_info *vi=vd->vi;
  110909. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  110910. private_state *b=(private_state*)vb->vd->backend_state;
  110911. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  110912. int n=vb->pcmend;
  110913. int i,j,k;
  110914. int *nonzero = (int*) alloca(sizeof(*nonzero)*vi->channels);
  110915. float **gmdct = (float**) _vorbis_block_alloc(vb,vi->channels*sizeof(*gmdct));
  110916. int **ilogmaskch= (int**) _vorbis_block_alloc(vb,vi->channels*sizeof(*ilogmaskch));
  110917. int ***floor_posts = (int***) _vorbis_block_alloc(vb,vi->channels*sizeof(*floor_posts));
  110918. float global_ampmax=vbi->ampmax;
  110919. float *local_ampmax=(float*)alloca(sizeof(*local_ampmax)*vi->channels);
  110920. int blocktype=vbi->blocktype;
  110921. int modenumber=vb->W;
  110922. vorbis_info_mapping0 *info=(vorbis_info_mapping0*)ci->map_param[modenumber];
  110923. vorbis_look_psy *psy_look=
  110924. b->psy+blocktype+(vb->W?2:0);
  110925. vb->mode=modenumber;
  110926. for(i=0;i<vi->channels;i++){
  110927. float scale=4.f/n;
  110928. float scale_dB;
  110929. float *pcm =vb->pcm[i];
  110930. float *logfft =pcm;
  110931. gmdct[i]=(float*)_vorbis_block_alloc(vb,n/2*sizeof(**gmdct));
  110932. scale_dB=todB(&scale) + .345; /* + .345 is a hack; the original
  110933. todB estimation used on IEEE 754
  110934. compliant machines had a bug that
  110935. returned dB values about a third
  110936. of a decibel too high. The bug
  110937. was harmless because tunings
  110938. implicitly took that into
  110939. account. However, fixing the bug
  110940. in the estimator requires
  110941. changing all the tunings as well.
  110942. For now, it's easier to sync
  110943. things back up here, and
  110944. recalibrate the tunings in the
  110945. next major model upgrade. */
  110946. #if 0
  110947. if(vi->channels==2)
  110948. if(i==0)
  110949. _analysis_output("pcmL",seq,pcm,n,0,0,total-n/2);
  110950. else
  110951. _analysis_output("pcmR",seq,pcm,n,0,0,total-n/2);
  110952. #endif
  110953. /* window the PCM data */
  110954. _vorbis_apply_window(pcm,b->window,ci->blocksizes,vb->lW,vb->W,vb->nW);
  110955. #if 0
  110956. if(vi->channels==2)
  110957. if(i==0)
  110958. _analysis_output("windowedL",seq,pcm,n,0,0,total-n/2);
  110959. else
  110960. _analysis_output("windowedR",seq,pcm,n,0,0,total-n/2);
  110961. #endif
  110962. /* transform the PCM data */
  110963. /* only MDCT right now.... */
  110964. mdct_forward((mdct_lookup*) b->transform[vb->W][0],pcm,gmdct[i]);
  110965. /* FFT yields more accurate tonal estimation (not phase sensitive) */
  110966. drft_forward(&b->fft_look[vb->W],pcm);
  110967. logfft[0]=scale_dB+todB(pcm) + .345; /* + .345 is a hack; the
  110968. original todB estimation used on
  110969. IEEE 754 compliant machines had a
  110970. bug that returned dB values about
  110971. a third of a decibel too high.
  110972. The bug was harmless because
  110973. tunings implicitly took that into
  110974. account. However, fixing the bug
  110975. in the estimator requires
  110976. changing all the tunings as well.
  110977. For now, it's easier to sync
  110978. things back up here, and
  110979. recalibrate the tunings in the
  110980. next major model upgrade. */
  110981. local_ampmax[i]=logfft[0];
  110982. for(j=1;j<n-1;j+=2){
  110983. float temp=pcm[j]*pcm[j]+pcm[j+1]*pcm[j+1];
  110984. temp=logfft[(j+1)>>1]=scale_dB+.5f*todB(&temp) + .345; /* +
  110985. .345 is a hack; the original todB
  110986. estimation used on IEEE 754
  110987. compliant machines had a bug that
  110988. returned dB values about a third
  110989. of a decibel too high. The bug
  110990. was harmless because tunings
  110991. implicitly took that into
  110992. account. However, fixing the bug
  110993. in the estimator requires
  110994. changing all the tunings as well.
  110995. For now, it's easier to sync
  110996. things back up here, and
  110997. recalibrate the tunings in the
  110998. next major model upgrade. */
  110999. if(temp>local_ampmax[i])local_ampmax[i]=temp;
  111000. }
  111001. if(local_ampmax[i]>0.f)local_ampmax[i]=0.f;
  111002. if(local_ampmax[i]>global_ampmax)global_ampmax=local_ampmax[i];
  111003. #if 0
  111004. if(vi->channels==2){
  111005. if(i==0){
  111006. _analysis_output("fftL",seq,logfft,n/2,1,0,0);
  111007. }else{
  111008. _analysis_output("fftR",seq,logfft,n/2,1,0,0);
  111009. }
  111010. }
  111011. #endif
  111012. }
  111013. {
  111014. float *noise = (float*) _vorbis_block_alloc(vb,n/2*sizeof(*noise));
  111015. float *tone = (float*) _vorbis_block_alloc(vb,n/2*sizeof(*tone));
  111016. for(i=0;i<vi->channels;i++){
  111017. /* the encoder setup assumes that all the modes used by any
  111018. specific bitrate tweaking use the same floor */
  111019. int submap=info->chmuxlist[i];
  111020. /* the following makes things clearer to *me* anyway */
  111021. float *mdct =gmdct[i];
  111022. float *logfft =vb->pcm[i];
  111023. float *logmdct =logfft+n/2;
  111024. float *logmask =logfft;
  111025. vb->mode=modenumber;
  111026. floor_posts[i]=(int**) _vorbis_block_alloc(vb,PACKETBLOBS*sizeof(**floor_posts));
  111027. memset(floor_posts[i],0,sizeof(**floor_posts)*PACKETBLOBS);
  111028. for(j=0;j<n/2;j++)
  111029. logmdct[j]=todB(mdct+j) + .345; /* + .345 is a hack; the original
  111030. todB estimation used on IEEE 754
  111031. compliant machines had a bug that
  111032. returned dB values about a third
  111033. of a decibel too high. The bug
  111034. was harmless because tunings
  111035. implicitly took that into
  111036. account. However, fixing the bug
  111037. in the estimator requires
  111038. changing all the tunings as well.
  111039. For now, it's easier to sync
  111040. things back up here, and
  111041. recalibrate the tunings in the
  111042. next major model upgrade. */
  111043. #if 0
  111044. if(vi->channels==2){
  111045. if(i==0)
  111046. _analysis_output("mdctL",seq,logmdct,n/2,1,0,0);
  111047. else
  111048. _analysis_output("mdctR",seq,logmdct,n/2,1,0,0);
  111049. }else{
  111050. _analysis_output("mdct",seq,logmdct,n/2,1,0,0);
  111051. }
  111052. #endif
  111053. /* first step; noise masking. Not only does 'noise masking'
  111054. give us curves from which we can decide how much resolution
  111055. to give noise parts of the spectrum, it also implicitly hands
  111056. us a tonality estimate (the larger the value in the
  111057. 'noise_depth' vector, the more tonal that area is) */
  111058. _vp_noisemask(psy_look,
  111059. logmdct,
  111060. noise); /* noise does not have by-frequency offset
  111061. bias applied yet */
  111062. #if 0
  111063. if(vi->channels==2){
  111064. if(i==0)
  111065. _analysis_output("noiseL",seq,noise,n/2,1,0,0);
  111066. else
  111067. _analysis_output("noiseR",seq,noise,n/2,1,0,0);
  111068. }
  111069. #endif
  111070. /* second step: 'all the other crap'; all the stuff that isn't
  111071. computed/fit for bitrate management goes in the second psy
  111072. vector. This includes tone masking, peak limiting and ATH */
  111073. _vp_tonemask(psy_look,
  111074. logfft,
  111075. tone,
  111076. global_ampmax,
  111077. local_ampmax[i]);
  111078. #if 0
  111079. if(vi->channels==2){
  111080. if(i==0)
  111081. _analysis_output("toneL",seq,tone,n/2,1,0,0);
  111082. else
  111083. _analysis_output("toneR",seq,tone,n/2,1,0,0);
  111084. }
  111085. #endif
  111086. /* third step; we offset the noise vectors, overlay tone
  111087. masking. We then do a floor1-specific line fit. If we're
  111088. performing bitrate management, the line fit is performed
  111089. multiple times for up/down tweakage on demand. */
  111090. #if 0
  111091. {
  111092. float aotuv[psy_look->n];
  111093. #endif
  111094. _vp_offset_and_mix(psy_look,
  111095. noise,
  111096. tone,
  111097. 1,
  111098. logmask,
  111099. mdct,
  111100. logmdct);
  111101. #if 0
  111102. if(vi->channels==2){
  111103. if(i==0)
  111104. _analysis_output("aotuvM1_L",seq,aotuv,psy_look->n,1,1,0);
  111105. else
  111106. _analysis_output("aotuvM1_R",seq,aotuv,psy_look->n,1,1,0);
  111107. }
  111108. }
  111109. #endif
  111110. #if 0
  111111. if(vi->channels==2){
  111112. if(i==0)
  111113. _analysis_output("mask1L",seq,logmask,n/2,1,0,0);
  111114. else
  111115. _analysis_output("mask1R",seq,logmask,n/2,1,0,0);
  111116. }
  111117. #endif
  111118. /* this algorithm is hardwired to floor 1 for now; abort out if
  111119. we're *not* floor1. This won't happen unless someone has
  111120. broken the encode setup lib. Guard it anyway. */
  111121. if(ci->floor_type[info->floorsubmap[submap]]!=1)return(-1);
  111122. floor_posts[i][PACKETBLOBS/2]=
  111123. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  111124. logmdct,
  111125. logmask);
  111126. /* are we managing bitrate? If so, perform two more fits for
  111127. later rate tweaking (fits represent hi/lo) */
  111128. if(vorbis_bitrate_managed(vb) && floor_posts[i][PACKETBLOBS/2]){
  111129. /* higher rate by way of lower noise curve */
  111130. _vp_offset_and_mix(psy_look,
  111131. noise,
  111132. tone,
  111133. 2,
  111134. logmask,
  111135. mdct,
  111136. logmdct);
  111137. #if 0
  111138. if(vi->channels==2){
  111139. if(i==0)
  111140. _analysis_output("mask2L",seq,logmask,n/2,1,0,0);
  111141. else
  111142. _analysis_output("mask2R",seq,logmask,n/2,1,0,0);
  111143. }
  111144. #endif
  111145. floor_posts[i][PACKETBLOBS-1]=
  111146. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  111147. logmdct,
  111148. logmask);
  111149. /* lower rate by way of higher noise curve */
  111150. _vp_offset_and_mix(psy_look,
  111151. noise,
  111152. tone,
  111153. 0,
  111154. logmask,
  111155. mdct,
  111156. logmdct);
  111157. #if 0
  111158. if(vi->channels==2)
  111159. if(i==0)
  111160. _analysis_output("mask0L",seq,logmask,n/2,1,0,0);
  111161. else
  111162. _analysis_output("mask0R",seq,logmask,n/2,1,0,0);
  111163. #endif
  111164. floor_posts[i][0]=
  111165. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  111166. logmdct,
  111167. logmask);
  111168. /* we also interpolate a range of intermediate curves for
  111169. intermediate rates */
  111170. for(k=1;k<PACKETBLOBS/2;k++)
  111171. floor_posts[i][k]=
  111172. floor1_interpolate_fit(vb,b->flr[info->floorsubmap[submap]],
  111173. floor_posts[i][0],
  111174. floor_posts[i][PACKETBLOBS/2],
  111175. k*65536/(PACKETBLOBS/2));
  111176. for(k=PACKETBLOBS/2+1;k<PACKETBLOBS-1;k++)
  111177. floor_posts[i][k]=
  111178. floor1_interpolate_fit(vb,b->flr[info->floorsubmap[submap]],
  111179. floor_posts[i][PACKETBLOBS/2],
  111180. floor_posts[i][PACKETBLOBS-1],
  111181. (k-PACKETBLOBS/2)*65536/(PACKETBLOBS/2));
  111182. }
  111183. }
  111184. }
  111185. vbi->ampmax=global_ampmax;
  111186. /*
  111187. the next phases are performed once for vbr-only and PACKETBLOB
  111188. times for bitrate managed modes.
  111189. 1) encode actual mode being used
  111190. 2) encode the floor for each channel, compute coded mask curve/res
  111191. 3) normalize and couple.
  111192. 4) encode residue
  111193. 5) save packet bytes to the packetblob vector
  111194. */
  111195. /* iterate over the many masking curve fits we've created */
  111196. {
  111197. float **res_bundle=(float**) alloca(sizeof(*res_bundle)*vi->channels);
  111198. float **couple_bundle=(float**) alloca(sizeof(*couple_bundle)*vi->channels);
  111199. int *zerobundle=(int*) alloca(sizeof(*zerobundle)*vi->channels);
  111200. int **sortindex=(int**) alloca(sizeof(*sortindex)*vi->channels);
  111201. float **mag_memo;
  111202. int **mag_sort;
  111203. if(info->coupling_steps){
  111204. mag_memo=_vp_quantize_couple_memo(vb,
  111205. &ci->psy_g_param,
  111206. psy_look,
  111207. info,
  111208. gmdct);
  111209. mag_sort=_vp_quantize_couple_sort(vb,
  111210. psy_look,
  111211. info,
  111212. mag_memo);
  111213. hf_reduction(&ci->psy_g_param,
  111214. psy_look,
  111215. info,
  111216. mag_memo);
  111217. }
  111218. memset(sortindex,0,sizeof(*sortindex)*vi->channels);
  111219. if(psy_look->vi->normal_channel_p){
  111220. for(i=0;i<vi->channels;i++){
  111221. float *mdct =gmdct[i];
  111222. sortindex[i]=(int*) alloca(sizeof(**sortindex)*n/2);
  111223. _vp_noise_normalize_sort(psy_look,mdct,sortindex[i]);
  111224. }
  111225. }
  111226. for(k=(vorbis_bitrate_managed(vb)?0:PACKETBLOBS/2);
  111227. k<=(vorbis_bitrate_managed(vb)?PACKETBLOBS-1:PACKETBLOBS/2);
  111228. k++){
  111229. oggpack_buffer *opb=vbi->packetblob[k];
  111230. /* start out our new packet blob with packet type and mode */
  111231. /* Encode the packet type */
  111232. oggpack_write(opb,0,1);
  111233. /* Encode the modenumber */
  111234. /* Encode frame mode, pre,post windowsize, then dispatch */
  111235. oggpack_write(opb,modenumber,b->modebits);
  111236. if(vb->W){
  111237. oggpack_write(opb,vb->lW,1);
  111238. oggpack_write(opb,vb->nW,1);
  111239. }
  111240. /* encode floor, compute masking curve, sep out residue */
  111241. for(i=0;i<vi->channels;i++){
  111242. int submap=info->chmuxlist[i];
  111243. float *mdct =gmdct[i];
  111244. float *res =vb->pcm[i];
  111245. int *ilogmask=ilogmaskch[i]=
  111246. (int*) _vorbis_block_alloc(vb,n/2*sizeof(**gmdct));
  111247. nonzero[i]=floor1_encode(opb,vb,b->flr[info->floorsubmap[submap]],
  111248. floor_posts[i][k],
  111249. ilogmask);
  111250. #if 0
  111251. {
  111252. char buf[80];
  111253. sprintf(buf,"maskI%c%d",i?'R':'L',k);
  111254. float work[n/2];
  111255. for(j=0;j<n/2;j++)
  111256. work[j]=FLOOR1_fromdB_LOOKUP[ilogmask[j]];
  111257. _analysis_output(buf,seq,work,n/2,1,1,0);
  111258. }
  111259. #endif
  111260. _vp_remove_floor(psy_look,
  111261. mdct,
  111262. ilogmask,
  111263. res,
  111264. ci->psy_g_param.sliding_lowpass[vb->W][k]);
  111265. _vp_noise_normalize(psy_look,res,res+n/2,sortindex[i]);
  111266. #if 0
  111267. {
  111268. char buf[80];
  111269. float work[n/2];
  111270. for(j=0;j<n/2;j++)
  111271. work[j]=FLOOR1_fromdB_LOOKUP[ilogmask[j]]*(res+n/2)[j];
  111272. sprintf(buf,"resI%c%d",i?'R':'L',k);
  111273. _analysis_output(buf,seq,work,n/2,1,1,0);
  111274. }
  111275. #endif
  111276. }
  111277. /* our iteration is now based on masking curve, not prequant and
  111278. coupling. Only one prequant/coupling step */
  111279. /* quantize/couple */
  111280. /* incomplete implementation that assumes the tree is all depth
  111281. one, or no tree at all */
  111282. if(info->coupling_steps){
  111283. _vp_couple(k,
  111284. &ci->psy_g_param,
  111285. psy_look,
  111286. info,
  111287. vb->pcm,
  111288. mag_memo,
  111289. mag_sort,
  111290. ilogmaskch,
  111291. nonzero,
  111292. ci->psy_g_param.sliding_lowpass[vb->W][k]);
  111293. }
  111294. /* classify and encode by submap */
  111295. for(i=0;i<info->submaps;i++){
  111296. int ch_in_bundle=0;
  111297. long **classifications;
  111298. int resnum=info->residuesubmap[i];
  111299. for(j=0;j<vi->channels;j++){
  111300. if(info->chmuxlist[j]==i){
  111301. zerobundle[ch_in_bundle]=0;
  111302. if(nonzero[j])zerobundle[ch_in_bundle]=1;
  111303. res_bundle[ch_in_bundle]=vb->pcm[j];
  111304. couple_bundle[ch_in_bundle++]=vb->pcm[j]+n/2;
  111305. }
  111306. }
  111307. classifications=_residue_P[ci->residue_type[resnum]]->
  111308. classx(vb,b->residue[resnum],couple_bundle,zerobundle,ch_in_bundle);
  111309. _residue_P[ci->residue_type[resnum]]->
  111310. forward(opb,vb,b->residue[resnum],
  111311. couple_bundle,NULL,zerobundle,ch_in_bundle,classifications);
  111312. }
  111313. /* ok, done encoding. Next protopacket. */
  111314. }
  111315. }
  111316. #if 0
  111317. seq++;
  111318. total+=ci->blocksizes[vb->W]/4+ci->blocksizes[vb->nW]/4;
  111319. #endif
  111320. return(0);
  111321. }
  111322. static int mapping0_inverse(vorbis_block *vb,vorbis_info_mapping *l){
  111323. vorbis_dsp_state *vd=vb->vd;
  111324. vorbis_info *vi=vd->vi;
  111325. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  111326. private_state *b=(private_state*)vd->backend_state;
  111327. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)l;
  111328. int i,j;
  111329. long n=vb->pcmend=ci->blocksizes[vb->W];
  111330. float **pcmbundle=(float**) alloca(sizeof(*pcmbundle)*vi->channels);
  111331. int *zerobundle=(int*) alloca(sizeof(*zerobundle)*vi->channels);
  111332. int *nonzero =(int*) alloca(sizeof(*nonzero)*vi->channels);
  111333. void **floormemo=(void**) alloca(sizeof(*floormemo)*vi->channels);
  111334. /* recover the spectral envelope; store it in the PCM vector for now */
  111335. for(i=0;i<vi->channels;i++){
  111336. int submap=info->chmuxlist[i];
  111337. floormemo[i]=_floor_P[ci->floor_type[info->floorsubmap[submap]]]->
  111338. inverse1(vb,b->flr[info->floorsubmap[submap]]);
  111339. if(floormemo[i])
  111340. nonzero[i]=1;
  111341. else
  111342. nonzero[i]=0;
  111343. memset(vb->pcm[i],0,sizeof(*vb->pcm[i])*n/2);
  111344. }
  111345. /* channel coupling can 'dirty' the nonzero listing */
  111346. for(i=0;i<info->coupling_steps;i++){
  111347. if(nonzero[info->coupling_mag[i]] ||
  111348. nonzero[info->coupling_ang[i]]){
  111349. nonzero[info->coupling_mag[i]]=1;
  111350. nonzero[info->coupling_ang[i]]=1;
  111351. }
  111352. }
  111353. /* recover the residue into our working vectors */
  111354. for(i=0;i<info->submaps;i++){
  111355. int ch_in_bundle=0;
  111356. for(j=0;j<vi->channels;j++){
  111357. if(info->chmuxlist[j]==i){
  111358. if(nonzero[j])
  111359. zerobundle[ch_in_bundle]=1;
  111360. else
  111361. zerobundle[ch_in_bundle]=0;
  111362. pcmbundle[ch_in_bundle++]=vb->pcm[j];
  111363. }
  111364. }
  111365. _residue_P[ci->residue_type[info->residuesubmap[i]]]->
  111366. inverse(vb,b->residue[info->residuesubmap[i]],
  111367. pcmbundle,zerobundle,ch_in_bundle);
  111368. }
  111369. /* channel coupling */
  111370. for(i=info->coupling_steps-1;i>=0;i--){
  111371. float *pcmM=vb->pcm[info->coupling_mag[i]];
  111372. float *pcmA=vb->pcm[info->coupling_ang[i]];
  111373. for(j=0;j<n/2;j++){
  111374. float mag=pcmM[j];
  111375. float ang=pcmA[j];
  111376. if(mag>0)
  111377. if(ang>0){
  111378. pcmM[j]=mag;
  111379. pcmA[j]=mag-ang;
  111380. }else{
  111381. pcmA[j]=mag;
  111382. pcmM[j]=mag+ang;
  111383. }
  111384. else
  111385. if(ang>0){
  111386. pcmM[j]=mag;
  111387. pcmA[j]=mag+ang;
  111388. }else{
  111389. pcmA[j]=mag;
  111390. pcmM[j]=mag-ang;
  111391. }
  111392. }
  111393. }
  111394. /* compute and apply spectral envelope */
  111395. for(i=0;i<vi->channels;i++){
  111396. float *pcm=vb->pcm[i];
  111397. int submap=info->chmuxlist[i];
  111398. _floor_P[ci->floor_type[info->floorsubmap[submap]]]->
  111399. inverse2(vb,b->flr[info->floorsubmap[submap]],
  111400. floormemo[i],pcm);
  111401. }
  111402. /* transform the PCM data; takes PCM vector, vb; modifies PCM vector */
  111403. /* only MDCT right now.... */
  111404. for(i=0;i<vi->channels;i++){
  111405. float *pcm=vb->pcm[i];
  111406. mdct_backward((mdct_lookup*) b->transform[vb->W][0],pcm,pcm);
  111407. }
  111408. /* all done! */
  111409. return(0);
  111410. }
  111411. /* export hooks */
  111412. vorbis_func_mapping mapping0_exportbundle={
  111413. &mapping0_pack,
  111414. &mapping0_unpack,
  111415. &mapping0_free_info,
  111416. &mapping0_forward,
  111417. &mapping0_inverse
  111418. };
  111419. #endif
  111420. /********* End of inlined file: mapping0.c *********/
  111421. /********* Start of inlined file: mdct.c *********/
  111422. /* this can also be run as an integer transform by uncommenting a
  111423. define in mdct.h; the integerization is a first pass and although
  111424. it's likely stable for Vorbis, the dynamic range is constrained and
  111425. roundoff isn't done (so it's noisy). Consider it functional, but
  111426. only a starting point. There's no point on a machine with an FPU */
  111427. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  111428. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  111429. // tasks..
  111430. #ifdef _MSC_VER
  111431. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  111432. #endif
  111433. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  111434. #if JUCE_USE_OGGVORBIS
  111435. #include <stdio.h>
  111436. #include <stdlib.h>
  111437. #include <string.h>
  111438. #include <math.h>
  111439. /* build lookups for trig functions; also pre-figure scaling and
  111440. some window function algebra. */
  111441. void mdct_init(mdct_lookup *lookup,int n){
  111442. int *bitrev=(int*) _ogg_malloc(sizeof(*bitrev)*(n/4));
  111443. DATA_TYPE *T=(DATA_TYPE*) _ogg_malloc(sizeof(*T)*(n+n/4));
  111444. int i;
  111445. int n2=n>>1;
  111446. int log2n=lookup->log2n=rint(log((float)n)/log(2.f));
  111447. lookup->n=n;
  111448. lookup->trig=T;
  111449. lookup->bitrev=bitrev;
  111450. /* trig lookups... */
  111451. for(i=0;i<n/4;i++){
  111452. T[i*2]=FLOAT_CONV(cos((M_PI/n)*(4*i)));
  111453. T[i*2+1]=FLOAT_CONV(-sin((M_PI/n)*(4*i)));
  111454. T[n2+i*2]=FLOAT_CONV(cos((M_PI/(2*n))*(2*i+1)));
  111455. T[n2+i*2+1]=FLOAT_CONV(sin((M_PI/(2*n))*(2*i+1)));
  111456. }
  111457. for(i=0;i<n/8;i++){
  111458. T[n+i*2]=FLOAT_CONV(cos((M_PI/n)*(4*i+2))*.5);
  111459. T[n+i*2+1]=FLOAT_CONV(-sin((M_PI/n)*(4*i+2))*.5);
  111460. }
  111461. /* bitreverse lookup... */
  111462. {
  111463. int mask=(1<<(log2n-1))-1,i,j;
  111464. int msb=1<<(log2n-2);
  111465. for(i=0;i<n/8;i++){
  111466. int acc=0;
  111467. for(j=0;msb>>j;j++)
  111468. if((msb>>j)&i)acc|=1<<j;
  111469. bitrev[i*2]=((~acc)&mask)-1;
  111470. bitrev[i*2+1]=acc;
  111471. }
  111472. }
  111473. lookup->scale=FLOAT_CONV(4.f/n);
  111474. }
  111475. /* 8 point butterfly (in place, 4 register) */
  111476. STIN void mdct_butterfly_8(DATA_TYPE *x){
  111477. REG_TYPE r0 = x[6] + x[2];
  111478. REG_TYPE r1 = x[6] - x[2];
  111479. REG_TYPE r2 = x[4] + x[0];
  111480. REG_TYPE r3 = x[4] - x[0];
  111481. x[6] = r0 + r2;
  111482. x[4] = r0 - r2;
  111483. r0 = x[5] - x[1];
  111484. r2 = x[7] - x[3];
  111485. x[0] = r1 + r0;
  111486. x[2] = r1 - r0;
  111487. r0 = x[5] + x[1];
  111488. r1 = x[7] + x[3];
  111489. x[3] = r2 + r3;
  111490. x[1] = r2 - r3;
  111491. x[7] = r1 + r0;
  111492. x[5] = r1 - r0;
  111493. }
  111494. /* 16 point butterfly (in place, 4 register) */
  111495. STIN void mdct_butterfly_16(DATA_TYPE *x){
  111496. REG_TYPE r0 = x[1] - x[9];
  111497. REG_TYPE r1 = x[0] - x[8];
  111498. x[8] += x[0];
  111499. x[9] += x[1];
  111500. x[0] = MULT_NORM((r0 + r1) * cPI2_8);
  111501. x[1] = MULT_NORM((r0 - r1) * cPI2_8);
  111502. r0 = x[3] - x[11];
  111503. r1 = x[10] - x[2];
  111504. x[10] += x[2];
  111505. x[11] += x[3];
  111506. x[2] = r0;
  111507. x[3] = r1;
  111508. r0 = x[12] - x[4];
  111509. r1 = x[13] - x[5];
  111510. x[12] += x[4];
  111511. x[13] += x[5];
  111512. x[4] = MULT_NORM((r0 - r1) * cPI2_8);
  111513. x[5] = MULT_NORM((r0 + r1) * cPI2_8);
  111514. r0 = x[14] - x[6];
  111515. r1 = x[15] - x[7];
  111516. x[14] += x[6];
  111517. x[15] += x[7];
  111518. x[6] = r0;
  111519. x[7] = r1;
  111520. mdct_butterfly_8(x);
  111521. mdct_butterfly_8(x+8);
  111522. }
  111523. /* 32 point butterfly (in place, 4 register) */
  111524. STIN void mdct_butterfly_32(DATA_TYPE *x){
  111525. REG_TYPE r0 = x[30] - x[14];
  111526. REG_TYPE r1 = x[31] - x[15];
  111527. x[30] += x[14];
  111528. x[31] += x[15];
  111529. x[14] = r0;
  111530. x[15] = r1;
  111531. r0 = x[28] - x[12];
  111532. r1 = x[29] - x[13];
  111533. x[28] += x[12];
  111534. x[29] += x[13];
  111535. x[12] = MULT_NORM( r0 * cPI1_8 - r1 * cPI3_8 );
  111536. x[13] = MULT_NORM( r0 * cPI3_8 + r1 * cPI1_8 );
  111537. r0 = x[26] - x[10];
  111538. r1 = x[27] - x[11];
  111539. x[26] += x[10];
  111540. x[27] += x[11];
  111541. x[10] = MULT_NORM(( r0 - r1 ) * cPI2_8);
  111542. x[11] = MULT_NORM(( r0 + r1 ) * cPI2_8);
  111543. r0 = x[24] - x[8];
  111544. r1 = x[25] - x[9];
  111545. x[24] += x[8];
  111546. x[25] += x[9];
  111547. x[8] = MULT_NORM( r0 * cPI3_8 - r1 * cPI1_8 );
  111548. x[9] = MULT_NORM( r1 * cPI3_8 + r0 * cPI1_8 );
  111549. r0 = x[22] - x[6];
  111550. r1 = x[7] - x[23];
  111551. x[22] += x[6];
  111552. x[23] += x[7];
  111553. x[6] = r1;
  111554. x[7] = r0;
  111555. r0 = x[4] - x[20];
  111556. r1 = x[5] - x[21];
  111557. x[20] += x[4];
  111558. x[21] += x[5];
  111559. x[4] = MULT_NORM( r1 * cPI1_8 + r0 * cPI3_8 );
  111560. x[5] = MULT_NORM( r1 * cPI3_8 - r0 * cPI1_8 );
  111561. r0 = x[2] - x[18];
  111562. r1 = x[3] - x[19];
  111563. x[18] += x[2];
  111564. x[19] += x[3];
  111565. x[2] = MULT_NORM(( r1 + r0 ) * cPI2_8);
  111566. x[3] = MULT_NORM(( r1 - r0 ) * cPI2_8);
  111567. r0 = x[0] - x[16];
  111568. r1 = x[1] - x[17];
  111569. x[16] += x[0];
  111570. x[17] += x[1];
  111571. x[0] = MULT_NORM( r1 * cPI3_8 + r0 * cPI1_8 );
  111572. x[1] = MULT_NORM( r1 * cPI1_8 - r0 * cPI3_8 );
  111573. mdct_butterfly_16(x);
  111574. mdct_butterfly_16(x+16);
  111575. }
  111576. /* N point first stage butterfly (in place, 2 register) */
  111577. STIN void mdct_butterfly_first(DATA_TYPE *T,
  111578. DATA_TYPE *x,
  111579. int points){
  111580. DATA_TYPE *x1 = x + points - 8;
  111581. DATA_TYPE *x2 = x + (points>>1) - 8;
  111582. REG_TYPE r0;
  111583. REG_TYPE r1;
  111584. do{
  111585. r0 = x1[6] - x2[6];
  111586. r1 = x1[7] - x2[7];
  111587. x1[6] += x2[6];
  111588. x1[7] += x2[7];
  111589. x2[6] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  111590. x2[7] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  111591. r0 = x1[4] - x2[4];
  111592. r1 = x1[5] - x2[5];
  111593. x1[4] += x2[4];
  111594. x1[5] += x2[5];
  111595. x2[4] = MULT_NORM(r1 * T[5] + r0 * T[4]);
  111596. x2[5] = MULT_NORM(r1 * T[4] - r0 * T[5]);
  111597. r0 = x1[2] - x2[2];
  111598. r1 = x1[3] - x2[3];
  111599. x1[2] += x2[2];
  111600. x1[3] += x2[3];
  111601. x2[2] = MULT_NORM(r1 * T[9] + r0 * T[8]);
  111602. x2[3] = MULT_NORM(r1 * T[8] - r0 * T[9]);
  111603. r0 = x1[0] - x2[0];
  111604. r1 = x1[1] - x2[1];
  111605. x1[0] += x2[0];
  111606. x1[1] += x2[1];
  111607. x2[0] = MULT_NORM(r1 * T[13] + r0 * T[12]);
  111608. x2[1] = MULT_NORM(r1 * T[12] - r0 * T[13]);
  111609. x1-=8;
  111610. x2-=8;
  111611. T+=16;
  111612. }while(x2>=x);
  111613. }
  111614. /* N/stage point generic N stage butterfly (in place, 2 register) */
  111615. STIN void mdct_butterfly_generic(DATA_TYPE *T,
  111616. DATA_TYPE *x,
  111617. int points,
  111618. int trigint){
  111619. DATA_TYPE *x1 = x + points - 8;
  111620. DATA_TYPE *x2 = x + (points>>1) - 8;
  111621. REG_TYPE r0;
  111622. REG_TYPE r1;
  111623. do{
  111624. r0 = x1[6] - x2[6];
  111625. r1 = x1[7] - x2[7];
  111626. x1[6] += x2[6];
  111627. x1[7] += x2[7];
  111628. x2[6] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  111629. x2[7] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  111630. T+=trigint;
  111631. r0 = x1[4] - x2[4];
  111632. r1 = x1[5] - x2[5];
  111633. x1[4] += x2[4];
  111634. x1[5] += x2[5];
  111635. x2[4] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  111636. x2[5] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  111637. T+=trigint;
  111638. r0 = x1[2] - x2[2];
  111639. r1 = x1[3] - x2[3];
  111640. x1[2] += x2[2];
  111641. x1[3] += x2[3];
  111642. x2[2] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  111643. x2[3] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  111644. T+=trigint;
  111645. r0 = x1[0] - x2[0];
  111646. r1 = x1[1] - x2[1];
  111647. x1[0] += x2[0];
  111648. x1[1] += x2[1];
  111649. x2[0] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  111650. x2[1] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  111651. T+=trigint;
  111652. x1-=8;
  111653. x2-=8;
  111654. }while(x2>=x);
  111655. }
  111656. STIN void mdct_butterflies(mdct_lookup *init,
  111657. DATA_TYPE *x,
  111658. int points){
  111659. DATA_TYPE *T=init->trig;
  111660. int stages=init->log2n-5;
  111661. int i,j;
  111662. if(--stages>0){
  111663. mdct_butterfly_first(T,x,points);
  111664. }
  111665. for(i=1;--stages>0;i++){
  111666. for(j=0;j<(1<<i);j++)
  111667. mdct_butterfly_generic(T,x+(points>>i)*j,points>>i,4<<i);
  111668. }
  111669. for(j=0;j<points;j+=32)
  111670. mdct_butterfly_32(x+j);
  111671. }
  111672. void mdct_clear(mdct_lookup *l){
  111673. if(l){
  111674. if(l->trig)_ogg_free(l->trig);
  111675. if(l->bitrev)_ogg_free(l->bitrev);
  111676. memset(l,0,sizeof(*l));
  111677. }
  111678. }
  111679. STIN void mdct_bitreverse(mdct_lookup *init,
  111680. DATA_TYPE *x){
  111681. int n = init->n;
  111682. int *bit = init->bitrev;
  111683. DATA_TYPE *w0 = x;
  111684. DATA_TYPE *w1 = x = w0+(n>>1);
  111685. DATA_TYPE *T = init->trig+n;
  111686. do{
  111687. DATA_TYPE *x0 = x+bit[0];
  111688. DATA_TYPE *x1 = x+bit[1];
  111689. REG_TYPE r0 = x0[1] - x1[1];
  111690. REG_TYPE r1 = x0[0] + x1[0];
  111691. REG_TYPE r2 = MULT_NORM(r1 * T[0] + r0 * T[1]);
  111692. REG_TYPE r3 = MULT_NORM(r1 * T[1] - r0 * T[0]);
  111693. w1 -= 4;
  111694. r0 = HALVE(x0[1] + x1[1]);
  111695. r1 = HALVE(x0[0] - x1[0]);
  111696. w0[0] = r0 + r2;
  111697. w1[2] = r0 - r2;
  111698. w0[1] = r1 + r3;
  111699. w1[3] = r3 - r1;
  111700. x0 = x+bit[2];
  111701. x1 = x+bit[3];
  111702. r0 = x0[1] - x1[1];
  111703. r1 = x0[0] + x1[0];
  111704. r2 = MULT_NORM(r1 * T[2] + r0 * T[3]);
  111705. r3 = MULT_NORM(r1 * T[3] - r0 * T[2]);
  111706. r0 = HALVE(x0[1] + x1[1]);
  111707. r1 = HALVE(x0[0] - x1[0]);
  111708. w0[2] = r0 + r2;
  111709. w1[0] = r0 - r2;
  111710. w0[3] = r1 + r3;
  111711. w1[1] = r3 - r1;
  111712. T += 4;
  111713. bit += 4;
  111714. w0 += 4;
  111715. }while(w0<w1);
  111716. }
  111717. void mdct_backward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out){
  111718. int n=init->n;
  111719. int n2=n>>1;
  111720. int n4=n>>2;
  111721. /* rotate */
  111722. DATA_TYPE *iX = in+n2-7;
  111723. DATA_TYPE *oX = out+n2+n4;
  111724. DATA_TYPE *T = init->trig+n4;
  111725. do{
  111726. oX -= 4;
  111727. oX[0] = MULT_NORM(-iX[2] * T[3] - iX[0] * T[2]);
  111728. oX[1] = MULT_NORM (iX[0] * T[3] - iX[2] * T[2]);
  111729. oX[2] = MULT_NORM(-iX[6] * T[1] - iX[4] * T[0]);
  111730. oX[3] = MULT_NORM (iX[4] * T[1] - iX[6] * T[0]);
  111731. iX -= 8;
  111732. T += 4;
  111733. }while(iX>=in);
  111734. iX = in+n2-8;
  111735. oX = out+n2+n4;
  111736. T = init->trig+n4;
  111737. do{
  111738. T -= 4;
  111739. oX[0] = MULT_NORM (iX[4] * T[3] + iX[6] * T[2]);
  111740. oX[1] = MULT_NORM (iX[4] * T[2] - iX[6] * T[3]);
  111741. oX[2] = MULT_NORM (iX[0] * T[1] + iX[2] * T[0]);
  111742. oX[3] = MULT_NORM (iX[0] * T[0] - iX[2] * T[1]);
  111743. iX -= 8;
  111744. oX += 4;
  111745. }while(iX>=in);
  111746. mdct_butterflies(init,out+n2,n2);
  111747. mdct_bitreverse(init,out);
  111748. /* roatate + window */
  111749. {
  111750. DATA_TYPE *oX1=out+n2+n4;
  111751. DATA_TYPE *oX2=out+n2+n4;
  111752. DATA_TYPE *iX =out;
  111753. T =init->trig+n2;
  111754. do{
  111755. oX1-=4;
  111756. oX1[3] = MULT_NORM (iX[0] * T[1] - iX[1] * T[0]);
  111757. oX2[0] = -MULT_NORM (iX[0] * T[0] + iX[1] * T[1]);
  111758. oX1[2] = MULT_NORM (iX[2] * T[3] - iX[3] * T[2]);
  111759. oX2[1] = -MULT_NORM (iX[2] * T[2] + iX[3] * T[3]);
  111760. oX1[1] = MULT_NORM (iX[4] * T[5] - iX[5] * T[4]);
  111761. oX2[2] = -MULT_NORM (iX[4] * T[4] + iX[5] * T[5]);
  111762. oX1[0] = MULT_NORM (iX[6] * T[7] - iX[7] * T[6]);
  111763. oX2[3] = -MULT_NORM (iX[6] * T[6] + iX[7] * T[7]);
  111764. oX2+=4;
  111765. iX += 8;
  111766. T += 8;
  111767. }while(iX<oX1);
  111768. iX=out+n2+n4;
  111769. oX1=out+n4;
  111770. oX2=oX1;
  111771. do{
  111772. oX1-=4;
  111773. iX-=4;
  111774. oX2[0] = -(oX1[3] = iX[3]);
  111775. oX2[1] = -(oX1[2] = iX[2]);
  111776. oX2[2] = -(oX1[1] = iX[1]);
  111777. oX2[3] = -(oX1[0] = iX[0]);
  111778. oX2+=4;
  111779. }while(oX2<iX);
  111780. iX=out+n2+n4;
  111781. oX1=out+n2+n4;
  111782. oX2=out+n2;
  111783. do{
  111784. oX1-=4;
  111785. oX1[0]= iX[3];
  111786. oX1[1]= iX[2];
  111787. oX1[2]= iX[1];
  111788. oX1[3]= iX[0];
  111789. iX+=4;
  111790. }while(oX1>oX2);
  111791. }
  111792. }
  111793. void mdct_forward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out){
  111794. int n=init->n;
  111795. int n2=n>>1;
  111796. int n4=n>>2;
  111797. int n8=n>>3;
  111798. DATA_TYPE *w=(DATA_TYPE*) alloca(n*sizeof(*w)); /* forward needs working space */
  111799. DATA_TYPE *w2=w+n2;
  111800. /* rotate */
  111801. /* window + rotate + step 1 */
  111802. REG_TYPE r0;
  111803. REG_TYPE r1;
  111804. DATA_TYPE *x0=in+n2+n4;
  111805. DATA_TYPE *x1=x0+1;
  111806. DATA_TYPE *T=init->trig+n2;
  111807. int i=0;
  111808. for(i=0;i<n8;i+=2){
  111809. x0 -=4;
  111810. T-=2;
  111811. r0= x0[2] + x1[0];
  111812. r1= x0[0] + x1[2];
  111813. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  111814. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  111815. x1 +=4;
  111816. }
  111817. x1=in+1;
  111818. for(;i<n2-n8;i+=2){
  111819. T-=2;
  111820. x0 -=4;
  111821. r0= x0[2] - x1[0];
  111822. r1= x0[0] - x1[2];
  111823. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  111824. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  111825. x1 +=4;
  111826. }
  111827. x0=in+n;
  111828. for(;i<n2;i+=2){
  111829. T-=2;
  111830. x0 -=4;
  111831. r0= -x0[2] - x1[0];
  111832. r1= -x0[0] - x1[2];
  111833. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  111834. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  111835. x1 +=4;
  111836. }
  111837. mdct_butterflies(init,w+n2,n2);
  111838. mdct_bitreverse(init,w);
  111839. /* roatate + window */
  111840. T=init->trig+n2;
  111841. x0=out+n2;
  111842. for(i=0;i<n4;i++){
  111843. x0--;
  111844. out[i] =MULT_NORM((w[0]*T[0]+w[1]*T[1])*init->scale);
  111845. x0[0] =MULT_NORM((w[0]*T[1]-w[1]*T[0])*init->scale);
  111846. w+=2;
  111847. T+=2;
  111848. }
  111849. }
  111850. #endif
  111851. /********* End of inlined file: mdct.c *********/
  111852. /********* Start of inlined file: psy.c *********/
  111853. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  111854. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  111855. // tasks..
  111856. #ifdef _MSC_VER
  111857. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  111858. #endif
  111859. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  111860. #if JUCE_USE_OGGVORBIS
  111861. #include <stdlib.h>
  111862. #include <math.h>
  111863. #include <string.h>
  111864. /********* Start of inlined file: masking.h *********/
  111865. #ifndef _V_MASKING_H_
  111866. #define _V_MASKING_H_
  111867. /* more detailed ATH; the bass if flat to save stressing the floor
  111868. overly for only a bin or two of savings. */
  111869. #define MAX_ATH 88
  111870. static float ATH[]={
  111871. /*15*/ -51, -52, -53, -54, -55, -56, -57, -58,
  111872. /*31*/ -59, -60, -61, -62, -63, -64, -65, -66,
  111873. /*63*/ -67, -68, -69, -70, -71, -72, -73, -74,
  111874. /*125*/ -75, -76, -77, -78, -80, -81, -82, -83,
  111875. /*250*/ -84, -85, -86, -87, -88, -88, -89, -89,
  111876. /*500*/ -90, -91, -91, -92, -93, -94, -95, -96,
  111877. /*1k*/ -96, -97, -98, -98, -99, -99,-100,-100,
  111878. /*2k*/ -101,-102,-103,-104,-106,-107,-107,-107,
  111879. /*4k*/ -107,-105,-103,-102,-101, -99, -98, -96,
  111880. /*8k*/ -95, -95, -96, -97, -96, -95, -93, -90,
  111881. /*16k*/ -80, -70, -50, -40, -30, -30, -30, -30
  111882. };
  111883. /* The tone masking curves from Ehmer's and Fielder's papers have been
  111884. replaced by an empirically collected data set. The previously
  111885. published values were, far too often, simply on crack. */
  111886. #define EHMER_OFFSET 16
  111887. #define EHMER_MAX 56
  111888. /* masking tones from -50 to 0dB, 62.5 through 16kHz at half octaves
  111889. test tones from -2 octaves to +5 octaves sampled at eighth octaves */
  111890. /* (Vorbis 0dB, the loudest possible tone, is assumed to be ~100dB SPL
  111891. for collection of these curves) */
  111892. static float tonemasks[P_BANDS][6][EHMER_MAX]={
  111893. /* 62.5 Hz */
  111894. {{ -60, -60, -60, -60, -60, -60, -60, -60,
  111895. -60, -60, -60, -60, -62, -62, -65, -73,
  111896. -69, -68, -68, -67, -70, -70, -72, -74,
  111897. -75, -79, -79, -80, -83, -88, -93, -100,
  111898. -110, -999, -999, -999, -999, -999, -999, -999,
  111899. -999, -999, -999, -999, -999, -999, -999, -999,
  111900. -999, -999, -999, -999, -999, -999, -999, -999},
  111901. { -48, -48, -48, -48, -48, -48, -48, -48,
  111902. -48, -48, -48, -48, -48, -53, -61, -66,
  111903. -66, -68, -67, -70, -76, -76, -72, -73,
  111904. -75, -76, -78, -79, -83, -88, -93, -100,
  111905. -110, -999, -999, -999, -999, -999, -999, -999,
  111906. -999, -999, -999, -999, -999, -999, -999, -999,
  111907. -999, -999, -999, -999, -999, -999, -999, -999},
  111908. { -37, -37, -37, -37, -37, -37, -37, -37,
  111909. -38, -40, -42, -46, -48, -53, -55, -62,
  111910. -65, -58, -56, -56, -61, -60, -65, -67,
  111911. -69, -71, -77, -77, -78, -80, -82, -84,
  111912. -88, -93, -98, -106, -112, -999, -999, -999,
  111913. -999, -999, -999, -999, -999, -999, -999, -999,
  111914. -999, -999, -999, -999, -999, -999, -999, -999},
  111915. { -25, -25, -25, -25, -25, -25, -25, -25,
  111916. -25, -26, -27, -29, -32, -38, -48, -52,
  111917. -52, -50, -48, -48, -51, -52, -54, -60,
  111918. -67, -67, -66, -68, -69, -73, -73, -76,
  111919. -80, -81, -81, -85, -85, -86, -88, -93,
  111920. -100, -110, -999, -999, -999, -999, -999, -999,
  111921. -999, -999, -999, -999, -999, -999, -999, -999},
  111922. { -16, -16, -16, -16, -16, -16, -16, -16,
  111923. -17, -19, -20, -22, -26, -28, -31, -40,
  111924. -47, -39, -39, -40, -42, -43, -47, -51,
  111925. -57, -52, -55, -55, -60, -58, -62, -63,
  111926. -70, -67, -69, -72, -73, -77, -80, -82,
  111927. -83, -87, -90, -94, -98, -104, -115, -999,
  111928. -999, -999, -999, -999, -999, -999, -999, -999},
  111929. { -8, -8, -8, -8, -8, -8, -8, -8,
  111930. -8, -8, -10, -11, -15, -19, -25, -30,
  111931. -34, -31, -30, -31, -29, -32, -35, -42,
  111932. -48, -42, -44, -46, -50, -50, -51, -52,
  111933. -59, -54, -55, -55, -58, -62, -63, -66,
  111934. -72, -73, -76, -75, -78, -80, -80, -81,
  111935. -84, -88, -90, -94, -98, -101, -106, -110}},
  111936. /* 88Hz */
  111937. {{ -66, -66, -66, -66, -66, -66, -66, -66,
  111938. -66, -66, -66, -66, -66, -67, -67, -67,
  111939. -76, -72, -71, -74, -76, -76, -75, -78,
  111940. -79, -79, -81, -83, -86, -89, -93, -97,
  111941. -100, -105, -110, -999, -999, -999, -999, -999,
  111942. -999, -999, -999, -999, -999, -999, -999, -999,
  111943. -999, -999, -999, -999, -999, -999, -999, -999},
  111944. { -47, -47, -47, -47, -47, -47, -47, -47,
  111945. -47, -47, -47, -48, -51, -55, -59, -66,
  111946. -66, -66, -67, -66, -68, -69, -70, -74,
  111947. -79, -77, -77, -78, -80, -81, -82, -84,
  111948. -86, -88, -91, -95, -100, -108, -116, -999,
  111949. -999, -999, -999, -999, -999, -999, -999, -999,
  111950. -999, -999, -999, -999, -999, -999, -999, -999},
  111951. { -36, -36, -36, -36, -36, -36, -36, -36,
  111952. -36, -37, -37, -41, -44, -48, -51, -58,
  111953. -62, -60, -57, -59, -59, -60, -63, -65,
  111954. -72, -71, -70, -72, -74, -77, -76, -78,
  111955. -81, -81, -80, -83, -86, -91, -96, -100,
  111956. -105, -110, -999, -999, -999, -999, -999, -999,
  111957. -999, -999, -999, -999, -999, -999, -999, -999},
  111958. { -28, -28, -28, -28, -28, -28, -28, -28,
  111959. -28, -30, -32, -32, -33, -35, -41, -49,
  111960. -50, -49, -47, -48, -48, -52, -51, -57,
  111961. -65, -61, -59, -61, -64, -69, -70, -74,
  111962. -77, -77, -78, -81, -84, -85, -87, -90,
  111963. -92, -96, -100, -107, -112, -999, -999, -999,
  111964. -999, -999, -999, -999, -999, -999, -999, -999},
  111965. { -19, -19, -19, -19, -19, -19, -19, -19,
  111966. -20, -21, -23, -27, -30, -35, -36, -41,
  111967. -46, -44, -42, -40, -41, -41, -43, -48,
  111968. -55, -53, -52, -53, -56, -59, -58, -60,
  111969. -67, -66, -69, -71, -72, -75, -79, -81,
  111970. -84, -87, -90, -93, -97, -101, -107, -114,
  111971. -999, -999, -999, -999, -999, -999, -999, -999},
  111972. { -9, -9, -9, -9, -9, -9, -9, -9,
  111973. -11, -12, -12, -15, -16, -20, -23, -30,
  111974. -37, -34, -33, -34, -31, -32, -32, -38,
  111975. -47, -44, -41, -40, -47, -49, -46, -46,
  111976. -58, -50, -50, -54, -58, -62, -64, -67,
  111977. -67, -70, -72, -76, -79, -83, -87, -91,
  111978. -96, -100, -104, -110, -999, -999, -999, -999}},
  111979. /* 125 Hz */
  111980. {{ -62, -62, -62, -62, -62, -62, -62, -62,
  111981. -62, -62, -63, -64, -66, -67, -66, -68,
  111982. -75, -72, -76, -75, -76, -78, -79, -82,
  111983. -84, -85, -90, -94, -101, -110, -999, -999,
  111984. -999, -999, -999, -999, -999, -999, -999, -999,
  111985. -999, -999, -999, -999, -999, -999, -999, -999,
  111986. -999, -999, -999, -999, -999, -999, -999, -999},
  111987. { -59, -59, -59, -59, -59, -59, -59, -59,
  111988. -59, -59, -59, -60, -60, -61, -63, -66,
  111989. -71, -68, -70, -70, -71, -72, -72, -75,
  111990. -81, -78, -79, -82, -83, -86, -90, -97,
  111991. -103, -113, -999, -999, -999, -999, -999, -999,
  111992. -999, -999, -999, -999, -999, -999, -999, -999,
  111993. -999, -999, -999, -999, -999, -999, -999, -999},
  111994. { -53, -53, -53, -53, -53, -53, -53, -53,
  111995. -53, -54, -55, -57, -56, -57, -55, -61,
  111996. -65, -60, -60, -62, -63, -63, -66, -68,
  111997. -74, -73, -75, -75, -78, -80, -80, -82,
  111998. -85, -90, -96, -101, -108, -999, -999, -999,
  111999. -999, -999, -999, -999, -999, -999, -999, -999,
  112000. -999, -999, -999, -999, -999, -999, -999, -999},
  112001. { -46, -46, -46, -46, -46, -46, -46, -46,
  112002. -46, -46, -47, -47, -47, -47, -48, -51,
  112003. -57, -51, -49, -50, -51, -53, -54, -59,
  112004. -66, -60, -62, -67, -67, -70, -72, -75,
  112005. -76, -78, -81, -85, -88, -94, -97, -104,
  112006. -112, -999, -999, -999, -999, -999, -999, -999,
  112007. -999, -999, -999, -999, -999, -999, -999, -999},
  112008. { -36, -36, -36, -36, -36, -36, -36, -36,
  112009. -39, -41, -42, -42, -39, -38, -41, -43,
  112010. -52, -44, -40, -39, -37, -37, -40, -47,
  112011. -54, -50, -48, -50, -55, -61, -59, -62,
  112012. -66, -66, -66, -69, -69, -73, -74, -74,
  112013. -75, -77, -79, -82, -87, -91, -95, -100,
  112014. -108, -115, -999, -999, -999, -999, -999, -999},
  112015. { -28, -26, -24, -22, -20, -20, -23, -29,
  112016. -30, -31, -28, -27, -28, -28, -28, -35,
  112017. -40, -33, -32, -29, -30, -30, -30, -37,
  112018. -45, -41, -37, -38, -45, -47, -47, -48,
  112019. -53, -49, -48, -50, -49, -49, -51, -52,
  112020. -58, -56, -57, -56, -60, -61, -62, -70,
  112021. -72, -74, -78, -83, -88, -93, -100, -106}},
  112022. /* 177 Hz */
  112023. {{-999, -999, -999, -999, -999, -999, -999, -999,
  112024. -999, -110, -105, -100, -95, -91, -87, -83,
  112025. -80, -78, -76, -78, -78, -81, -83, -85,
  112026. -86, -85, -86, -87, -90, -97, -107, -999,
  112027. -999, -999, -999, -999, -999, -999, -999, -999,
  112028. -999, -999, -999, -999, -999, -999, -999, -999,
  112029. -999, -999, -999, -999, -999, -999, -999, -999},
  112030. {-999, -999, -999, -110, -105, -100, -95, -90,
  112031. -85, -81, -77, -73, -70, -67, -67, -68,
  112032. -75, -73, -70, -69, -70, -72, -75, -79,
  112033. -84, -83, -84, -86, -88, -89, -89, -93,
  112034. -98, -105, -112, -999, -999, -999, -999, -999,
  112035. -999, -999, -999, -999, -999, -999, -999, -999,
  112036. -999, -999, -999, -999, -999, -999, -999, -999},
  112037. {-105, -100, -95, -90, -85, -80, -76, -71,
  112038. -68, -68, -65, -63, -63, -62, -62, -64,
  112039. -65, -64, -61, -62, -63, -64, -66, -68,
  112040. -73, -73, -74, -75, -76, -81, -83, -85,
  112041. -88, -89, -92, -95, -100, -108, -999, -999,
  112042. -999, -999, -999, -999, -999, -999, -999, -999,
  112043. -999, -999, -999, -999, -999, -999, -999, -999},
  112044. { -80, -75, -71, -68, -65, -63, -62, -61,
  112045. -61, -61, -61, -59, -56, -57, -53, -50,
  112046. -58, -52, -50, -50, -52, -53, -54, -58,
  112047. -67, -63, -67, -68, -72, -75, -78, -80,
  112048. -81, -81, -82, -85, -89, -90, -93, -97,
  112049. -101, -107, -114, -999, -999, -999, -999, -999,
  112050. -999, -999, -999, -999, -999, -999, -999, -999},
  112051. { -65, -61, -59, -57, -56, -55, -55, -56,
  112052. -56, -57, -55, -53, -52, -47, -44, -44,
  112053. -50, -44, -41, -39, -39, -42, -40, -46,
  112054. -51, -49, -50, -53, -54, -63, -60, -61,
  112055. -62, -66, -66, -66, -70, -73, -74, -75,
  112056. -76, -75, -79, -85, -89, -91, -96, -102,
  112057. -110, -999, -999, -999, -999, -999, -999, -999},
  112058. { -52, -50, -49, -49, -48, -48, -48, -49,
  112059. -50, -50, -49, -46, -43, -39, -35, -33,
  112060. -38, -36, -32, -29, -32, -32, -32, -35,
  112061. -44, -39, -38, -38, -46, -50, -45, -46,
  112062. -53, -50, -50, -50, -54, -54, -53, -53,
  112063. -56, -57, -59, -66, -70, -72, -74, -79,
  112064. -83, -85, -90, -97, -114, -999, -999, -999}},
  112065. /* 250 Hz */
  112066. {{-999, -999, -999, -999, -999, -999, -110, -105,
  112067. -100, -95, -90, -86, -80, -75, -75, -79,
  112068. -80, -79, -80, -81, -82, -88, -95, -103,
  112069. -110, -999, -999, -999, -999, -999, -999, -999,
  112070. -999, -999, -999, -999, -999, -999, -999, -999,
  112071. -999, -999, -999, -999, -999, -999, -999, -999,
  112072. -999, -999, -999, -999, -999, -999, -999, -999},
  112073. {-999, -999, -999, -999, -108, -103, -98, -93,
  112074. -88, -83, -79, -78, -75, -71, -67, -68,
  112075. -73, -73, -72, -73, -75, -77, -80, -82,
  112076. -88, -93, -100, -107, -114, -999, -999, -999,
  112077. -999, -999, -999, -999, -999, -999, -999, -999,
  112078. -999, -999, -999, -999, -999, -999, -999, -999,
  112079. -999, -999, -999, -999, -999, -999, -999, -999},
  112080. {-999, -999, -999, -110, -105, -101, -96, -90,
  112081. -86, -81, -77, -73, -69, -66, -61, -62,
  112082. -66, -64, -62, -65, -66, -70, -72, -76,
  112083. -81, -80, -84, -90, -95, -102, -110, -999,
  112084. -999, -999, -999, -999, -999, -999, -999, -999,
  112085. -999, -999, -999, -999, -999, -999, -999, -999,
  112086. -999, -999, -999, -999, -999, -999, -999, -999},
  112087. {-999, -999, -999, -107, -103, -97, -92, -88,
  112088. -83, -79, -74, -70, -66, -59, -53, -58,
  112089. -62, -55, -54, -54, -54, -58, -61, -62,
  112090. -72, -70, -72, -75, -78, -80, -81, -80,
  112091. -83, -83, -88, -93, -100, -107, -115, -999,
  112092. -999, -999, -999, -999, -999, -999, -999, -999,
  112093. -999, -999, -999, -999, -999, -999, -999, -999},
  112094. {-999, -999, -999, -105, -100, -95, -90, -85,
  112095. -80, -75, -70, -66, -62, -56, -48, -44,
  112096. -48, -46, -46, -43, -46, -48, -48, -51,
  112097. -58, -58, -59, -60, -62, -62, -61, -61,
  112098. -65, -64, -65, -68, -70, -74, -75, -78,
  112099. -81, -86, -95, -110, -999, -999, -999, -999,
  112100. -999, -999, -999, -999, -999, -999, -999, -999},
  112101. {-999, -999, -105, -100, -95, -90, -85, -80,
  112102. -75, -70, -65, -61, -55, -49, -39, -33,
  112103. -40, -35, -32, -38, -40, -33, -35, -37,
  112104. -46, -41, -45, -44, -46, -42, -45, -46,
  112105. -52, -50, -50, -50, -54, -54, -55, -57,
  112106. -62, -64, -66, -68, -70, -76, -81, -90,
  112107. -100, -110, -999, -999, -999, -999, -999, -999}},
  112108. /* 354 hz */
  112109. {{-999, -999, -999, -999, -999, -999, -999, -999,
  112110. -105, -98, -90, -85, -82, -83, -80, -78,
  112111. -84, -79, -80, -83, -87, -89, -91, -93,
  112112. -99, -106, -117, -999, -999, -999, -999, -999,
  112113. -999, -999, -999, -999, -999, -999, -999, -999,
  112114. -999, -999, -999, -999, -999, -999, -999, -999,
  112115. -999, -999, -999, -999, -999, -999, -999, -999},
  112116. {-999, -999, -999, -999, -999, -999, -999, -999,
  112117. -105, -98, -90, -85, -80, -75, -70, -68,
  112118. -74, -72, -74, -77, -80, -82, -85, -87,
  112119. -92, -89, -91, -95, -100, -106, -112, -999,
  112120. -999, -999, -999, -999, -999, -999, -999, -999,
  112121. -999, -999, -999, -999, -999, -999, -999, -999,
  112122. -999, -999, -999, -999, -999, -999, -999, -999},
  112123. {-999, -999, -999, -999, -999, -999, -999, -999,
  112124. -105, -98, -90, -83, -75, -71, -63, -64,
  112125. -67, -62, -64, -67, -70, -73, -77, -81,
  112126. -84, -83, -85, -89, -90, -93, -98, -104,
  112127. -109, -114, -999, -999, -999, -999, -999, -999,
  112128. -999, -999, -999, -999, -999, -999, -999, -999,
  112129. -999, -999, -999, -999, -999, -999, -999, -999},
  112130. {-999, -999, -999, -999, -999, -999, -999, -999,
  112131. -103, -96, -88, -81, -75, -68, -58, -54,
  112132. -56, -54, -56, -56, -58, -60, -63, -66,
  112133. -74, -69, -72, -72, -75, -74, -77, -81,
  112134. -81, -82, -84, -87, -93, -96, -99, -104,
  112135. -110, -999, -999, -999, -999, -999, -999, -999,
  112136. -999, -999, -999, -999, -999, -999, -999, -999},
  112137. {-999, -999, -999, -999, -999, -108, -102, -96,
  112138. -91, -85, -80, -74, -68, -60, -51, -46,
  112139. -48, -46, -43, -45, -47, -47, -49, -48,
  112140. -56, -53, -55, -58, -57, -63, -58, -60,
  112141. -66, -64, -67, -70, -70, -74, -77, -84,
  112142. -86, -89, -91, -93, -94, -101, -109, -118,
  112143. -999, -999, -999, -999, -999, -999, -999, -999},
  112144. {-999, -999, -999, -108, -103, -98, -93, -88,
  112145. -83, -78, -73, -68, -60, -53, -44, -35,
  112146. -38, -38, -34, -34, -36, -40, -41, -44,
  112147. -51, -45, -46, -47, -46, -54, -50, -49,
  112148. -50, -50, -50, -51, -54, -57, -58, -60,
  112149. -66, -66, -66, -64, -65, -68, -77, -82,
  112150. -87, -95, -110, -999, -999, -999, -999, -999}},
  112151. /* 500 Hz */
  112152. {{-999, -999, -999, -999, -999, -999, -999, -999,
  112153. -107, -102, -97, -92, -87, -83, -78, -75,
  112154. -82, -79, -83, -85, -89, -92, -95, -98,
  112155. -101, -105, -109, -113, -999, -999, -999, -999,
  112156. -999, -999, -999, -999, -999, -999, -999, -999,
  112157. -999, -999, -999, -999, -999, -999, -999, -999,
  112158. -999, -999, -999, -999, -999, -999, -999, -999},
  112159. {-999, -999, -999, -999, -999, -999, -999, -106,
  112160. -100, -95, -90, -86, -81, -78, -74, -69,
  112161. -74, -74, -76, -79, -83, -84, -86, -89,
  112162. -92, -97, -93, -100, -103, -107, -110, -999,
  112163. -999, -999, -999, -999, -999, -999, -999, -999,
  112164. -999, -999, -999, -999, -999, -999, -999, -999,
  112165. -999, -999, -999, -999, -999, -999, -999, -999},
  112166. {-999, -999, -999, -999, -999, -999, -106, -100,
  112167. -95, -90, -87, -83, -80, -75, -69, -60,
  112168. -66, -66, -68, -70, -74, -78, -79, -81,
  112169. -81, -83, -84, -87, -93, -96, -99, -103,
  112170. -107, -110, -999, -999, -999, -999, -999, -999,
  112171. -999, -999, -999, -999, -999, -999, -999, -999,
  112172. -999, -999, -999, -999, -999, -999, -999, -999},
  112173. {-999, -999, -999, -999, -999, -108, -103, -98,
  112174. -93, -89, -85, -82, -78, -71, -62, -55,
  112175. -58, -58, -54, -54, -55, -59, -61, -62,
  112176. -70, -66, -66, -67, -70, -72, -75, -78,
  112177. -84, -84, -84, -88, -91, -90, -95, -98,
  112178. -102, -103, -106, -110, -999, -999, -999, -999,
  112179. -999, -999, -999, -999, -999, -999, -999, -999},
  112180. {-999, -999, -999, -999, -108, -103, -98, -94,
  112181. -90, -87, -82, -79, -73, -67, -58, -47,
  112182. -50, -45, -41, -45, -48, -44, -44, -49,
  112183. -54, -51, -48, -47, -49, -50, -51, -57,
  112184. -58, -60, -63, -69, -70, -69, -71, -74,
  112185. -78, -82, -90, -95, -101, -105, -110, -999,
  112186. -999, -999, -999, -999, -999, -999, -999, -999},
  112187. {-999, -999, -999, -105, -101, -97, -93, -90,
  112188. -85, -80, -77, -72, -65, -56, -48, -37,
  112189. -40, -36, -34, -40, -50, -47, -38, -41,
  112190. -47, -38, -35, -39, -38, -43, -40, -45,
  112191. -50, -45, -44, -47, -50, -55, -48, -48,
  112192. -52, -66, -70, -76, -82, -90, -97, -105,
  112193. -110, -999, -999, -999, -999, -999, -999, -999}},
  112194. /* 707 Hz */
  112195. {{-999, -999, -999, -999, -999, -999, -999, -999,
  112196. -999, -108, -103, -98, -93, -86, -79, -76,
  112197. -83, -81, -85, -87, -89, -93, -98, -102,
  112198. -107, -112, -999, -999, -999, -999, -999, -999,
  112199. -999, -999, -999, -999, -999, -999, -999, -999,
  112200. -999, -999, -999, -999, -999, -999, -999, -999,
  112201. -999, -999, -999, -999, -999, -999, -999, -999},
  112202. {-999, -999, -999, -999, -999, -999, -999, -999,
  112203. -999, -108, -103, -98, -93, -86, -79, -71,
  112204. -77, -74, -77, -79, -81, -84, -85, -90,
  112205. -92, -93, -92, -98, -101, -108, -112, -999,
  112206. -999, -999, -999, -999, -999, -999, -999, -999,
  112207. -999, -999, -999, -999, -999, -999, -999, -999,
  112208. -999, -999, -999, -999, -999, -999, -999, -999},
  112209. {-999, -999, -999, -999, -999, -999, -999, -999,
  112210. -108, -103, -98, -93, -87, -78, -68, -65,
  112211. -66, -62, -65, -67, -70, -73, -75, -78,
  112212. -82, -82, -83, -84, -91, -93, -98, -102,
  112213. -106, -110, -999, -999, -999, -999, -999, -999,
  112214. -999, -999, -999, -999, -999, -999, -999, -999,
  112215. -999, -999, -999, -999, -999, -999, -999, -999},
  112216. {-999, -999, -999, -999, -999, -999, -999, -999,
  112217. -105, -100, -95, -90, -82, -74, -62, -57,
  112218. -58, -56, -51, -52, -52, -54, -54, -58,
  112219. -66, -59, -60, -63, -66, -69, -73, -79,
  112220. -83, -84, -80, -81, -81, -82, -88, -92,
  112221. -98, -105, -113, -999, -999, -999, -999, -999,
  112222. -999, -999, -999, -999, -999, -999, -999, -999},
  112223. {-999, -999, -999, -999, -999, -999, -999, -107,
  112224. -102, -97, -92, -84, -79, -69, -57, -47,
  112225. -52, -47, -44, -45, -50, -52, -42, -42,
  112226. -53, -43, -43, -48, -51, -56, -55, -52,
  112227. -57, -59, -61, -62, -67, -71, -78, -83,
  112228. -86, -94, -98, -103, -110, -999, -999, -999,
  112229. -999, -999, -999, -999, -999, -999, -999, -999},
  112230. {-999, -999, -999, -999, -999, -999, -105, -100,
  112231. -95, -90, -84, -78, -70, -61, -51, -41,
  112232. -40, -38, -40, -46, -52, -51, -41, -40,
  112233. -46, -40, -38, -38, -41, -46, -41, -46,
  112234. -47, -43, -43, -45, -41, -45, -56, -67,
  112235. -68, -83, -87, -90, -95, -102, -107, -113,
  112236. -999, -999, -999, -999, -999, -999, -999, -999}},
  112237. /* 1000 Hz */
  112238. {{-999, -999, -999, -999, -999, -999, -999, -999,
  112239. -999, -109, -105, -101, -96, -91, -84, -77,
  112240. -82, -82, -85, -89, -94, -100, -106, -110,
  112241. -999, -999, -999, -999, -999, -999, -999, -999,
  112242. -999, -999, -999, -999, -999, -999, -999, -999,
  112243. -999, -999, -999, -999, -999, -999, -999, -999,
  112244. -999, -999, -999, -999, -999, -999, -999, -999},
  112245. {-999, -999, -999, -999, -999, -999, -999, -999,
  112246. -999, -106, -103, -98, -92, -85, -80, -71,
  112247. -75, -72, -76, -80, -84, -86, -89, -93,
  112248. -100, -107, -113, -999, -999, -999, -999, -999,
  112249. -999, -999, -999, -999, -999, -999, -999, -999,
  112250. -999, -999, -999, -999, -999, -999, -999, -999,
  112251. -999, -999, -999, -999, -999, -999, -999, -999},
  112252. {-999, -999, -999, -999, -999, -999, -999, -107,
  112253. -104, -101, -97, -92, -88, -84, -80, -64,
  112254. -66, -63, -64, -66, -69, -73, -77, -83,
  112255. -83, -86, -91, -98, -104, -111, -999, -999,
  112256. -999, -999, -999, -999, -999, -999, -999, -999,
  112257. -999, -999, -999, -999, -999, -999, -999, -999,
  112258. -999, -999, -999, -999, -999, -999, -999, -999},
  112259. {-999, -999, -999, -999, -999, -999, -999, -107,
  112260. -104, -101, -97, -92, -90, -84, -74, -57,
  112261. -58, -52, -55, -54, -50, -52, -50, -52,
  112262. -63, -62, -69, -76, -77, -78, -78, -79,
  112263. -82, -88, -94, -100, -106, -111, -999, -999,
  112264. -999, -999, -999, -999, -999, -999, -999, -999,
  112265. -999, -999, -999, -999, -999, -999, -999, -999},
  112266. {-999, -999, -999, -999, -999, -999, -106, -102,
  112267. -98, -95, -90, -85, -83, -78, -70, -50,
  112268. -50, -41, -44, -49, -47, -50, -50, -44,
  112269. -55, -46, -47, -48, -48, -54, -49, -49,
  112270. -58, -62, -71, -81, -87, -92, -97, -102,
  112271. -108, -114, -999, -999, -999, -999, -999, -999,
  112272. -999, -999, -999, -999, -999, -999, -999, -999},
  112273. {-999, -999, -999, -999, -999, -999, -106, -102,
  112274. -98, -95, -90, -85, -83, -78, -70, -45,
  112275. -43, -41, -47, -50, -51, -50, -49, -45,
  112276. -47, -41, -44, -41, -39, -43, -38, -37,
  112277. -40, -41, -44, -50, -58, -65, -73, -79,
  112278. -85, -92, -97, -101, -105, -109, -113, -999,
  112279. -999, -999, -999, -999, -999, -999, -999, -999}},
  112280. /* 1414 Hz */
  112281. {{-999, -999, -999, -999, -999, -999, -999, -999,
  112282. -999, -999, -999, -107, -100, -95, -87, -81,
  112283. -85, -83, -88, -93, -100, -107, -114, -999,
  112284. -999, -999, -999, -999, -999, -999, -999, -999,
  112285. -999, -999, -999, -999, -999, -999, -999, -999,
  112286. -999, -999, -999, -999, -999, -999, -999, -999,
  112287. -999, -999, -999, -999, -999, -999, -999, -999},
  112288. {-999, -999, -999, -999, -999, -999, -999, -999,
  112289. -999, -999, -107, -101, -95, -88, -83, -76,
  112290. -73, -72, -79, -84, -90, -95, -100, -105,
  112291. -110, -115, -999, -999, -999, -999, -999, -999,
  112292. -999, -999, -999, -999, -999, -999, -999, -999,
  112293. -999, -999, -999, -999, -999, -999, -999, -999,
  112294. -999, -999, -999, -999, -999, -999, -999, -999},
  112295. {-999, -999, -999, -999, -999, -999, -999, -999,
  112296. -999, -999, -104, -98, -92, -87, -81, -70,
  112297. -65, -62, -67, -71, -74, -80, -85, -91,
  112298. -95, -99, -103, -108, -111, -114, -999, -999,
  112299. -999, -999, -999, -999, -999, -999, -999, -999,
  112300. -999, -999, -999, -999, -999, -999, -999, -999,
  112301. -999, -999, -999, -999, -999, -999, -999, -999},
  112302. {-999, -999, -999, -999, -999, -999, -999, -999,
  112303. -999, -999, -103, -97, -90, -85, -76, -60,
  112304. -56, -54, -60, -62, -61, -56, -63, -65,
  112305. -73, -74, -77, -75, -78, -81, -86, -87,
  112306. -88, -91, -94, -98, -103, -110, -999, -999,
  112307. -999, -999, -999, -999, -999, -999, -999, -999,
  112308. -999, -999, -999, -999, -999, -999, -999, -999},
  112309. {-999, -999, -999, -999, -999, -999, -999, -105,
  112310. -100, -97, -92, -86, -81, -79, -70, -57,
  112311. -51, -47, -51, -58, -60, -56, -53, -50,
  112312. -58, -52, -50, -50, -53, -55, -64, -69,
  112313. -71, -85, -82, -78, -81, -85, -95, -102,
  112314. -112, -999, -999, -999, -999, -999, -999, -999,
  112315. -999, -999, -999, -999, -999, -999, -999, -999},
  112316. {-999, -999, -999, -999, -999, -999, -999, -105,
  112317. -100, -97, -92, -85, -83, -79, -72, -49,
  112318. -40, -43, -43, -54, -56, -51, -50, -40,
  112319. -43, -38, -36, -35, -37, -38, -37, -44,
  112320. -54, -60, -57, -60, -70, -75, -84, -92,
  112321. -103, -112, -999, -999, -999, -999, -999, -999,
  112322. -999, -999, -999, -999, -999, -999, -999, -999}},
  112323. /* 2000 Hz */
  112324. {{-999, -999, -999, -999, -999, -999, -999, -999,
  112325. -999, -999, -999, -110, -102, -95, -89, -82,
  112326. -83, -84, -90, -92, -99, -107, -113, -999,
  112327. -999, -999, -999, -999, -999, -999, -999, -999,
  112328. -999, -999, -999, -999, -999, -999, -999, -999,
  112329. -999, -999, -999, -999, -999, -999, -999, -999,
  112330. -999, -999, -999, -999, -999, -999, -999, -999},
  112331. {-999, -999, -999, -999, -999, -999, -999, -999,
  112332. -999, -999, -107, -101, -95, -89, -83, -72,
  112333. -74, -78, -85, -88, -88, -90, -92, -98,
  112334. -105, -111, -999, -999, -999, -999, -999, -999,
  112335. -999, -999, -999, -999, -999, -999, -999, -999,
  112336. -999, -999, -999, -999, -999, -999, -999, -999,
  112337. -999, -999, -999, -999, -999, -999, -999, -999},
  112338. {-999, -999, -999, -999, -999, -999, -999, -999,
  112339. -999, -109, -103, -97, -93, -87, -81, -70,
  112340. -70, -67, -75, -73, -76, -79, -81, -83,
  112341. -88, -89, -97, -103, -110, -999, -999, -999,
  112342. -999, -999, -999, -999, -999, -999, -999, -999,
  112343. -999, -999, -999, -999, -999, -999, -999, -999,
  112344. -999, -999, -999, -999, -999, -999, -999, -999},
  112345. {-999, -999, -999, -999, -999, -999, -999, -999,
  112346. -999, -107, -100, -94, -88, -83, -75, -63,
  112347. -59, -59, -63, -66, -60, -62, -67, -67,
  112348. -77, -76, -81, -88, -86, -92, -96, -102,
  112349. -109, -116, -999, -999, -999, -999, -999, -999,
  112350. -999, -999, -999, -999, -999, -999, -999, -999,
  112351. -999, -999, -999, -999, -999, -999, -999, -999},
  112352. {-999, -999, -999, -999, -999, -999, -999, -999,
  112353. -999, -105, -98, -92, -86, -81, -73, -56,
  112354. -52, -47, -55, -60, -58, -52, -51, -45,
  112355. -49, -50, -53, -54, -61, -71, -70, -69,
  112356. -78, -79, -87, -90, -96, -104, -112, -999,
  112357. -999, -999, -999, -999, -999, -999, -999, -999,
  112358. -999, -999, -999, -999, -999, -999, -999, -999},
  112359. {-999, -999, -999, -999, -999, -999, -999, -999,
  112360. -999, -103, -96, -90, -86, -78, -70, -51,
  112361. -42, -47, -48, -55, -54, -54, -53, -42,
  112362. -35, -28, -33, -38, -37, -44, -47, -49,
  112363. -54, -63, -68, -78, -82, -89, -94, -99,
  112364. -104, -109, -114, -999, -999, -999, -999, -999,
  112365. -999, -999, -999, -999, -999, -999, -999, -999}},
  112366. /* 2828 Hz */
  112367. {{-999, -999, -999, -999, -999, -999, -999, -999,
  112368. -999, -999, -999, -999, -110, -100, -90, -79,
  112369. -85, -81, -82, -82, -89, -94, -99, -103,
  112370. -109, -115, -999, -999, -999, -999, -999, -999,
  112371. -999, -999, -999, -999, -999, -999, -999, -999,
  112372. -999, -999, -999, -999, -999, -999, -999, -999,
  112373. -999, -999, -999, -999, -999, -999, -999, -999},
  112374. {-999, -999, -999, -999, -999, -999, -999, -999,
  112375. -999, -999, -999, -999, -105, -97, -85, -72,
  112376. -74, -70, -70, -70, -76, -85, -91, -93,
  112377. -97, -103, -109, -115, -999, -999, -999, -999,
  112378. -999, -999, -999, -999, -999, -999, -999, -999,
  112379. -999, -999, -999, -999, -999, -999, -999, -999,
  112380. -999, -999, -999, -999, -999, -999, -999, -999},
  112381. {-999, -999, -999, -999, -999, -999, -999, -999,
  112382. -999, -999, -999, -999, -112, -93, -81, -68,
  112383. -62, -60, -60, -57, -63, -70, -77, -82,
  112384. -90, -93, -98, -104, -109, -113, -999, -999,
  112385. -999, -999, -999, -999, -999, -999, -999, -999,
  112386. -999, -999, -999, -999, -999, -999, -999, -999,
  112387. -999, -999, -999, -999, -999, -999, -999, -999},
  112388. {-999, -999, -999, -999, -999, -999, -999, -999,
  112389. -999, -999, -999, -113, -100, -93, -84, -63,
  112390. -58, -48, -53, -54, -52, -52, -57, -64,
  112391. -66, -76, -83, -81, -85, -85, -90, -95,
  112392. -98, -101, -103, -106, -108, -111, -999, -999,
  112393. -999, -999, -999, -999, -999, -999, -999, -999,
  112394. -999, -999, -999, -999, -999, -999, -999, -999},
  112395. {-999, -999, -999, -999, -999, -999, -999, -999,
  112396. -999, -999, -999, -105, -95, -86, -74, -53,
  112397. -50, -38, -43, -49, -43, -42, -39, -39,
  112398. -46, -52, -57, -56, -72, -69, -74, -81,
  112399. -87, -92, -94, -97, -99, -102, -105, -108,
  112400. -999, -999, -999, -999, -999, -999, -999, -999,
  112401. -999, -999, -999, -999, -999, -999, -999, -999},
  112402. {-999, -999, -999, -999, -999, -999, -999, -999,
  112403. -999, -999, -108, -99, -90, -76, -66, -45,
  112404. -43, -41, -44, -47, -43, -47, -40, -30,
  112405. -31, -31, -39, -33, -40, -41, -43, -53,
  112406. -59, -70, -73, -77, -79, -82, -84, -87,
  112407. -999, -999, -999, -999, -999, -999, -999, -999,
  112408. -999, -999, -999, -999, -999, -999, -999, -999}},
  112409. /* 4000 Hz */
  112410. {{-999, -999, -999, -999, -999, -999, -999, -999,
  112411. -999, -999, -999, -999, -999, -110, -91, -76,
  112412. -75, -85, -93, -98, -104, -110, -999, -999,
  112413. -999, -999, -999, -999, -999, -999, -999, -999,
  112414. -999, -999, -999, -999, -999, -999, -999, -999,
  112415. -999, -999, -999, -999, -999, -999, -999, -999,
  112416. -999, -999, -999, -999, -999, -999, -999, -999},
  112417. {-999, -999, -999, -999, -999, -999, -999, -999,
  112418. -999, -999, -999, -999, -999, -110, -91, -70,
  112419. -70, -75, -86, -89, -94, -98, -101, -106,
  112420. -110, -999, -999, -999, -999, -999, -999, -999,
  112421. -999, -999, -999, -999, -999, -999, -999, -999,
  112422. -999, -999, -999, -999, -999, -999, -999, -999,
  112423. -999, -999, -999, -999, -999, -999, -999, -999},
  112424. {-999, -999, -999, -999, -999, -999, -999, -999,
  112425. -999, -999, -999, -999, -110, -95, -80, -60,
  112426. -65, -64, -74, -83, -88, -91, -95, -99,
  112427. -103, -107, -110, -999, -999, -999, -999, -999,
  112428. -999, -999, -999, -999, -999, -999, -999, -999,
  112429. -999, -999, -999, -999, -999, -999, -999, -999,
  112430. -999, -999, -999, -999, -999, -999, -999, -999},
  112431. {-999, -999, -999, -999, -999, -999, -999, -999,
  112432. -999, -999, -999, -999, -110, -95, -80, -58,
  112433. -55, -49, -66, -68, -71, -78, -78, -80,
  112434. -88, -85, -89, -97, -100, -105, -110, -999,
  112435. -999, -999, -999, -999, -999, -999, -999, -999,
  112436. -999, -999, -999, -999, -999, -999, -999, -999,
  112437. -999, -999, -999, -999, -999, -999, -999, -999},
  112438. {-999, -999, -999, -999, -999, -999, -999, -999,
  112439. -999, -999, -999, -999, -110, -95, -80, -53,
  112440. -52, -41, -59, -59, -49, -58, -56, -63,
  112441. -86, -79, -90, -93, -98, -103, -107, -112,
  112442. -999, -999, -999, -999, -999, -999, -999, -999,
  112443. -999, -999, -999, -999, -999, -999, -999, -999,
  112444. -999, -999, -999, -999, -999, -999, -999, -999},
  112445. {-999, -999, -999, -999, -999, -999, -999, -999,
  112446. -999, -999, -999, -110, -97, -91, -73, -45,
  112447. -40, -33, -53, -61, -49, -54, -50, -50,
  112448. -60, -52, -67, -74, -81, -92, -96, -100,
  112449. -105, -110, -999, -999, -999, -999, -999, -999,
  112450. -999, -999, -999, -999, -999, -999, -999, -999,
  112451. -999, -999, -999, -999, -999, -999, -999, -999}},
  112452. /* 5657 Hz */
  112453. {{-999, -999, -999, -999, -999, -999, -999, -999,
  112454. -999, -999, -999, -113, -106, -99, -92, -77,
  112455. -80, -88, -97, -106, -115, -999, -999, -999,
  112456. -999, -999, -999, -999, -999, -999, -999, -999,
  112457. -999, -999, -999, -999, -999, -999, -999, -999,
  112458. -999, -999, -999, -999, -999, -999, -999, -999,
  112459. -999, -999, -999, -999, -999, -999, -999, -999},
  112460. {-999, -999, -999, -999, -999, -999, -999, -999,
  112461. -999, -999, -116, -109, -102, -95, -89, -74,
  112462. -72, -88, -87, -95, -102, -109, -116, -999,
  112463. -999, -999, -999, -999, -999, -999, -999, -999,
  112464. -999, -999, -999, -999, -999, -999, -999, -999,
  112465. -999, -999, -999, -999, -999, -999, -999, -999,
  112466. -999, -999, -999, -999, -999, -999, -999, -999},
  112467. {-999, -999, -999, -999, -999, -999, -999, -999,
  112468. -999, -999, -116, -109, -102, -95, -89, -75,
  112469. -66, -74, -77, -78, -86, -87, -90, -96,
  112470. -105, -115, -999, -999, -999, -999, -999, -999,
  112471. -999, -999, -999, -999, -999, -999, -999, -999,
  112472. -999, -999, -999, -999, -999, -999, -999, -999,
  112473. -999, -999, -999, -999, -999, -999, -999, -999},
  112474. {-999, -999, -999, -999, -999, -999, -999, -999,
  112475. -999, -999, -115, -108, -101, -94, -88, -66,
  112476. -56, -61, -70, -65, -78, -72, -83, -84,
  112477. -93, -98, -105, -110, -999, -999, -999, -999,
  112478. -999, -999, -999, -999, -999, -999, -999, -999,
  112479. -999, -999, -999, -999, -999, -999, -999, -999,
  112480. -999, -999, -999, -999, -999, -999, -999, -999},
  112481. {-999, -999, -999, -999, -999, -999, -999, -999,
  112482. -999, -999, -110, -105, -95, -89, -82, -57,
  112483. -52, -52, -59, -56, -59, -58, -69, -67,
  112484. -88, -82, -82, -89, -94, -100, -108, -999,
  112485. -999, -999, -999, -999, -999, -999, -999, -999,
  112486. -999, -999, -999, -999, -999, -999, -999, -999,
  112487. -999, -999, -999, -999, -999, -999, -999, -999},
  112488. {-999, -999, -999, -999, -999, -999, -999, -999,
  112489. -999, -110, -101, -96, -90, -83, -77, -54,
  112490. -43, -38, -50, -48, -52, -48, -42, -42,
  112491. -51, -52, -53, -59, -65, -71, -78, -85,
  112492. -95, -999, -999, -999, -999, -999, -999, -999,
  112493. -999, -999, -999, -999, -999, -999, -999, -999,
  112494. -999, -999, -999, -999, -999, -999, -999, -999}},
  112495. /* 8000 Hz */
  112496. {{-999, -999, -999, -999, -999, -999, -999, -999,
  112497. -999, -999, -999, -999, -120, -105, -86, -68,
  112498. -78, -79, -90, -100, -110, -999, -999, -999,
  112499. -999, -999, -999, -999, -999, -999, -999, -999,
  112500. -999, -999, -999, -999, -999, -999, -999, -999,
  112501. -999, -999, -999, -999, -999, -999, -999, -999,
  112502. -999, -999, -999, -999, -999, -999, -999, -999},
  112503. {-999, -999, -999, -999, -999, -999, -999, -999,
  112504. -999, -999, -999, -999, -120, -105, -86, -66,
  112505. -73, -77, -88, -96, -105, -115, -999, -999,
  112506. -999, -999, -999, -999, -999, -999, -999, -999,
  112507. -999, -999, -999, -999, -999, -999, -999, -999,
  112508. -999, -999, -999, -999, -999, -999, -999, -999,
  112509. -999, -999, -999, -999, -999, -999, -999, -999},
  112510. {-999, -999, -999, -999, -999, -999, -999, -999,
  112511. -999, -999, -999, -120, -105, -92, -80, -61,
  112512. -64, -68, -80, -87, -92, -100, -110, -999,
  112513. -999, -999, -999, -999, -999, -999, -999, -999,
  112514. -999, -999, -999, -999, -999, -999, -999, -999,
  112515. -999, -999, -999, -999, -999, -999, -999, -999,
  112516. -999, -999, -999, -999, -999, -999, -999, -999},
  112517. {-999, -999, -999, -999, -999, -999, -999, -999,
  112518. -999, -999, -999, -120, -104, -91, -79, -52,
  112519. -60, -54, -64, -69, -77, -80, -82, -84,
  112520. -85, -87, -88, -90, -999, -999, -999, -999,
  112521. -999, -999, -999, -999, -999, -999, -999, -999,
  112522. -999, -999, -999, -999, -999, -999, -999, -999,
  112523. -999, -999, -999, -999, -999, -999, -999, -999},
  112524. {-999, -999, -999, -999, -999, -999, -999, -999,
  112525. -999, -999, -999, -118, -100, -87, -77, -49,
  112526. -50, -44, -58, -61, -61, -67, -65, -62,
  112527. -62, -62, -65, -68, -999, -999, -999, -999,
  112528. -999, -999, -999, -999, -999, -999, -999, -999,
  112529. -999, -999, -999, -999, -999, -999, -999, -999,
  112530. -999, -999, -999, -999, -999, -999, -999, -999},
  112531. {-999, -999, -999, -999, -999, -999, -999, -999,
  112532. -999, -999, -999, -115, -98, -84, -62, -49,
  112533. -44, -38, -46, -49, -49, -46, -39, -37,
  112534. -39, -40, -42, -43, -999, -999, -999, -999,
  112535. -999, -999, -999, -999, -999, -999, -999, -999,
  112536. -999, -999, -999, -999, -999, -999, -999, -999,
  112537. -999, -999, -999, -999, -999, -999, -999, -999}},
  112538. /* 11314 Hz */
  112539. {{-999, -999, -999, -999, -999, -999, -999, -999,
  112540. -999, -999, -999, -999, -999, -110, -88, -74,
  112541. -77, -82, -82, -85, -90, -94, -99, -104,
  112542. -999, -999, -999, -999, -999, -999, -999, -999,
  112543. -999, -999, -999, -999, -999, -999, -999, -999,
  112544. -999, -999, -999, -999, -999, -999, -999, -999,
  112545. -999, -999, -999, -999, -999, -999, -999, -999},
  112546. {-999, -999, -999, -999, -999, -999, -999, -999,
  112547. -999, -999, -999, -999, -999, -110, -88, -66,
  112548. -70, -81, -80, -81, -84, -88, -91, -93,
  112549. -999, -999, -999, -999, -999, -999, -999, -999,
  112550. -999, -999, -999, -999, -999, -999, -999, -999,
  112551. -999, -999, -999, -999, -999, -999, -999, -999,
  112552. -999, -999, -999, -999, -999, -999, -999, -999},
  112553. {-999, -999, -999, -999, -999, -999, -999, -999,
  112554. -999, -999, -999, -999, -999, -110, -88, -61,
  112555. -63, -70, -71, -74, -77, -80, -83, -85,
  112556. -999, -999, -999, -999, -999, -999, -999, -999,
  112557. -999, -999, -999, -999, -999, -999, -999, -999,
  112558. -999, -999, -999, -999, -999, -999, -999, -999,
  112559. -999, -999, -999, -999, -999, -999, -999, -999},
  112560. {-999, -999, -999, -999, -999, -999, -999, -999,
  112561. -999, -999, -999, -999, -999, -110, -86, -62,
  112562. -63, -62, -62, -58, -52, -50, -50, -52,
  112563. -54, -999, -999, -999, -999, -999, -999, -999,
  112564. -999, -999, -999, -999, -999, -999, -999, -999,
  112565. -999, -999, -999, -999, -999, -999, -999, -999,
  112566. -999, -999, -999, -999, -999, -999, -999, -999},
  112567. {-999, -999, -999, -999, -999, -999, -999, -999,
  112568. -999, -999, -999, -999, -118, -108, -84, -53,
  112569. -50, -50, -50, -55, -47, -45, -40, -40,
  112570. -40, -999, -999, -999, -999, -999, -999, -999,
  112571. -999, -999, -999, -999, -999, -999, -999, -999,
  112572. -999, -999, -999, -999, -999, -999, -999, -999,
  112573. -999, -999, -999, -999, -999, -999, -999, -999},
  112574. {-999, -999, -999, -999, -999, -999, -999, -999,
  112575. -999, -999, -999, -999, -118, -100, -73, -43,
  112576. -37, -42, -43, -53, -38, -37, -35, -35,
  112577. -38, -999, -999, -999, -999, -999, -999, -999,
  112578. -999, -999, -999, -999, -999, -999, -999, -999,
  112579. -999, -999, -999, -999, -999, -999, -999, -999,
  112580. -999, -999, -999, -999, -999, -999, -999, -999}},
  112581. /* 16000 Hz */
  112582. {{-999, -999, -999, -999, -999, -999, -999, -999,
  112583. -999, -999, -999, -110, -100, -91, -84, -74,
  112584. -80, -80, -80, -80, -80, -999, -999, -999,
  112585. -999, -999, -999, -999, -999, -999, -999, -999,
  112586. -999, -999, -999, -999, -999, -999, -999, -999,
  112587. -999, -999, -999, -999, -999, -999, -999, -999,
  112588. -999, -999, -999, -999, -999, -999, -999, -999},
  112589. {-999, -999, -999, -999, -999, -999, -999, -999,
  112590. -999, -999, -999, -110, -100, -91, -84, -74,
  112591. -68, -68, -68, -68, -68, -999, -999, -999,
  112592. -999, -999, -999, -999, -999, -999, -999, -999,
  112593. -999, -999, -999, -999, -999, -999, -999, -999,
  112594. -999, -999, -999, -999, -999, -999, -999, -999,
  112595. -999, -999, -999, -999, -999, -999, -999, -999},
  112596. {-999, -999, -999, -999, -999, -999, -999, -999,
  112597. -999, -999, -999, -110, -100, -86, -78, -70,
  112598. -60, -45, -30, -21, -999, -999, -999, -999,
  112599. -999, -999, -999, -999, -999, -999, -999, -999,
  112600. -999, -999, -999, -999, -999, -999, -999, -999,
  112601. -999, -999, -999, -999, -999, -999, -999, -999,
  112602. -999, -999, -999, -999, -999, -999, -999, -999},
  112603. {-999, -999, -999, -999, -999, -999, -999, -999,
  112604. -999, -999, -999, -110, -100, -87, -78, -67,
  112605. -48, -38, -29, -21, -999, -999, -999, -999,
  112606. -999, -999, -999, -999, -999, -999, -999, -999,
  112607. -999, -999, -999, -999, -999, -999, -999, -999,
  112608. -999, -999, -999, -999, -999, -999, -999, -999,
  112609. -999, -999, -999, -999, -999, -999, -999, -999},
  112610. {-999, -999, -999, -999, -999, -999, -999, -999,
  112611. -999, -999, -999, -110, -100, -86, -69, -56,
  112612. -45, -35, -33, -29, -999, -999, -999, -999,
  112613. -999, -999, -999, -999, -999, -999, -999, -999,
  112614. -999, -999, -999, -999, -999, -999, -999, -999,
  112615. -999, -999, -999, -999, -999, -999, -999, -999,
  112616. -999, -999, -999, -999, -999, -999, -999, -999},
  112617. {-999, -999, -999, -999, -999, -999, -999, -999,
  112618. -999, -999, -999, -110, -100, -83, -71, -48,
  112619. -27, -38, -37, -34, -999, -999, -999, -999,
  112620. -999, -999, -999, -999, -999, -999, -999, -999,
  112621. -999, -999, -999, -999, -999, -999, -999, -999,
  112622. -999, -999, -999, -999, -999, -999, -999, -999,
  112623. -999, -999, -999, -999, -999, -999, -999, -999}}
  112624. };
  112625. #endif
  112626. /********* End of inlined file: masking.h *********/
  112627. #define NEGINF -9999.f
  112628. static double stereo_threshholds[]={0.0, .5, 1.0, 1.5, 2.5, 4.5, 8.5, 16.5, 9e10};
  112629. static double stereo_threshholds_limited[]={0.0, .5, 1.0, 1.5, 2.0, 2.5, 4.5, 8.5, 9e10};
  112630. vorbis_look_psy_global *_vp_global_look(vorbis_info *vi){
  112631. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112632. vorbis_info_psy_global *gi=&ci->psy_g_param;
  112633. vorbis_look_psy_global *look=(vorbis_look_psy_global*)_ogg_calloc(1,sizeof(*look));
  112634. look->channels=vi->channels;
  112635. look->ampmax=-9999.;
  112636. look->gi=gi;
  112637. return(look);
  112638. }
  112639. void _vp_global_free(vorbis_look_psy_global *look){
  112640. if(look){
  112641. memset(look,0,sizeof(*look));
  112642. _ogg_free(look);
  112643. }
  112644. }
  112645. void _vi_gpsy_free(vorbis_info_psy_global *i){
  112646. if(i){
  112647. memset(i,0,sizeof(*i));
  112648. _ogg_free(i);
  112649. }
  112650. }
  112651. void _vi_psy_free(vorbis_info_psy *i){
  112652. if(i){
  112653. memset(i,0,sizeof(*i));
  112654. _ogg_free(i);
  112655. }
  112656. }
  112657. static void min_curve(float *c,
  112658. float *c2){
  112659. int i;
  112660. for(i=0;i<EHMER_MAX;i++)if(c2[i]<c[i])c[i]=c2[i];
  112661. }
  112662. static void max_curve(float *c,
  112663. float *c2){
  112664. int i;
  112665. for(i=0;i<EHMER_MAX;i++)if(c2[i]>c[i])c[i]=c2[i];
  112666. }
  112667. static void attenuate_curve(float *c,float att){
  112668. int i;
  112669. for(i=0;i<EHMER_MAX;i++)
  112670. c[i]+=att;
  112671. }
  112672. static float ***setup_tone_curves(float curveatt_dB[P_BANDS],float binHz,int n,
  112673. float center_boost, float center_decay_rate){
  112674. int i,j,k,m;
  112675. float ath[EHMER_MAX];
  112676. float workc[P_BANDS][P_LEVELS][EHMER_MAX];
  112677. float athc[P_LEVELS][EHMER_MAX];
  112678. float *brute_buffer=(float*) alloca(n*sizeof(*brute_buffer));
  112679. float ***ret=(float***) _ogg_malloc(sizeof(*ret)*P_BANDS);
  112680. memset(workc,0,sizeof(workc));
  112681. for(i=0;i<P_BANDS;i++){
  112682. /* we add back in the ATH to avoid low level curves falling off to
  112683. -infinity and unnecessarily cutting off high level curves in the
  112684. curve limiting (last step). */
  112685. /* A half-band's settings must be valid over the whole band, and
  112686. it's better to mask too little than too much */
  112687. int ath_offset=i*4;
  112688. for(j=0;j<EHMER_MAX;j++){
  112689. float min=999.;
  112690. for(k=0;k<4;k++)
  112691. if(j+k+ath_offset<MAX_ATH){
  112692. if(min>ATH[j+k+ath_offset])min=ATH[j+k+ath_offset];
  112693. }else{
  112694. if(min>ATH[MAX_ATH-1])min=ATH[MAX_ATH-1];
  112695. }
  112696. ath[j]=min;
  112697. }
  112698. /* copy curves into working space, replicate the 50dB curve to 30
  112699. and 40, replicate the 100dB curve to 110 */
  112700. for(j=0;j<6;j++)
  112701. memcpy(workc[i][j+2],tonemasks[i][j],EHMER_MAX*sizeof(*tonemasks[i][j]));
  112702. memcpy(workc[i][0],tonemasks[i][0],EHMER_MAX*sizeof(*tonemasks[i][0]));
  112703. memcpy(workc[i][1],tonemasks[i][0],EHMER_MAX*sizeof(*tonemasks[i][0]));
  112704. /* apply centered curve boost/decay */
  112705. for(j=0;j<P_LEVELS;j++){
  112706. for(k=0;k<EHMER_MAX;k++){
  112707. float adj=center_boost+abs(EHMER_OFFSET-k)*center_decay_rate;
  112708. if(adj<0. && center_boost>0)adj=0.;
  112709. if(adj>0. && center_boost<0)adj=0.;
  112710. workc[i][j][k]+=adj;
  112711. }
  112712. }
  112713. /* normalize curves so the driving amplitude is 0dB */
  112714. /* make temp curves with the ATH overlayed */
  112715. for(j=0;j<P_LEVELS;j++){
  112716. attenuate_curve(workc[i][j],curveatt_dB[i]+100.-(j<2?2:j)*10.-P_LEVEL_0);
  112717. memcpy(athc[j],ath,EHMER_MAX*sizeof(**athc));
  112718. attenuate_curve(athc[j],+100.-j*10.f-P_LEVEL_0);
  112719. max_curve(athc[j],workc[i][j]);
  112720. }
  112721. /* Now limit the louder curves.
  112722. the idea is this: We don't know what the playback attenuation
  112723. will be; 0dB SL moves every time the user twiddles the volume
  112724. knob. So that means we have to use a single 'most pessimal' curve
  112725. for all masking amplitudes, right? Wrong. The *loudest* sound
  112726. can be in (we assume) a range of ...+100dB] SL. However, sounds
  112727. 20dB down will be in a range ...+80], 40dB down is from ...+60],
  112728. etc... */
  112729. for(j=1;j<P_LEVELS;j++){
  112730. min_curve(athc[j],athc[j-1]);
  112731. min_curve(workc[i][j],athc[j]);
  112732. }
  112733. }
  112734. for(i=0;i<P_BANDS;i++){
  112735. int hi_curve,lo_curve,bin;
  112736. ret[i]=(float**)_ogg_malloc(sizeof(**ret)*P_LEVELS);
  112737. /* low frequency curves are measured with greater resolution than
  112738. the MDCT/FFT will actually give us; we want the curve applied
  112739. to the tone data to be pessimistic and thus apply the minimum
  112740. masking possible for a given bin. That means that a single bin
  112741. could span more than one octave and that the curve will be a
  112742. composite of multiple octaves. It also may mean that a single
  112743. bin may span > an eighth of an octave and that the eighth
  112744. octave values may also be composited. */
  112745. /* which octave curves will we be compositing? */
  112746. bin=floor(fromOC(i*.5)/binHz);
  112747. lo_curve= ceil(toOC(bin*binHz+1)*2);
  112748. hi_curve= floor(toOC((bin+1)*binHz)*2);
  112749. if(lo_curve>i)lo_curve=i;
  112750. if(lo_curve<0)lo_curve=0;
  112751. if(hi_curve>=P_BANDS)hi_curve=P_BANDS-1;
  112752. for(m=0;m<P_LEVELS;m++){
  112753. ret[i][m]=(float*)_ogg_malloc(sizeof(***ret)*(EHMER_MAX+2));
  112754. for(j=0;j<n;j++)brute_buffer[j]=999.;
  112755. /* render the curve into bins, then pull values back into curve.
  112756. The point is that any inherent subsampling aliasing results in
  112757. a safe minimum */
  112758. for(k=lo_curve;k<=hi_curve;k++){
  112759. int l=0;
  112760. for(j=0;j<EHMER_MAX;j++){
  112761. int lo_bin= fromOC(j*.125+k*.5-2.0625)/binHz;
  112762. int hi_bin= fromOC(j*.125+k*.5-1.9375)/binHz+1;
  112763. if(lo_bin<0)lo_bin=0;
  112764. if(lo_bin>n)lo_bin=n;
  112765. if(lo_bin<l)l=lo_bin;
  112766. if(hi_bin<0)hi_bin=0;
  112767. if(hi_bin>n)hi_bin=n;
  112768. for(;l<hi_bin && l<n;l++)
  112769. if(brute_buffer[l]>workc[k][m][j])
  112770. brute_buffer[l]=workc[k][m][j];
  112771. }
  112772. for(;l<n;l++)
  112773. if(brute_buffer[l]>workc[k][m][EHMER_MAX-1])
  112774. brute_buffer[l]=workc[k][m][EHMER_MAX-1];
  112775. }
  112776. /* be equally paranoid about being valid up to next half ocatve */
  112777. if(i+1<P_BANDS){
  112778. int l=0;
  112779. k=i+1;
  112780. for(j=0;j<EHMER_MAX;j++){
  112781. int lo_bin= fromOC(j*.125+i*.5-2.0625)/binHz;
  112782. int hi_bin= fromOC(j*.125+i*.5-1.9375)/binHz+1;
  112783. if(lo_bin<0)lo_bin=0;
  112784. if(lo_bin>n)lo_bin=n;
  112785. if(lo_bin<l)l=lo_bin;
  112786. if(hi_bin<0)hi_bin=0;
  112787. if(hi_bin>n)hi_bin=n;
  112788. for(;l<hi_bin && l<n;l++)
  112789. if(brute_buffer[l]>workc[k][m][j])
  112790. brute_buffer[l]=workc[k][m][j];
  112791. }
  112792. for(;l<n;l++)
  112793. if(brute_buffer[l]>workc[k][m][EHMER_MAX-1])
  112794. brute_buffer[l]=workc[k][m][EHMER_MAX-1];
  112795. }
  112796. for(j=0;j<EHMER_MAX;j++){
  112797. int bin=fromOC(j*.125+i*.5-2.)/binHz;
  112798. if(bin<0){
  112799. ret[i][m][j+2]=-999.;
  112800. }else{
  112801. if(bin>=n){
  112802. ret[i][m][j+2]=-999.;
  112803. }else{
  112804. ret[i][m][j+2]=brute_buffer[bin];
  112805. }
  112806. }
  112807. }
  112808. /* add fenceposts */
  112809. for(j=0;j<EHMER_OFFSET;j++)
  112810. if(ret[i][m][j+2]>-200.f)break;
  112811. ret[i][m][0]=j;
  112812. for(j=EHMER_MAX-1;j>EHMER_OFFSET+1;j--)
  112813. if(ret[i][m][j+2]>-200.f)
  112814. break;
  112815. ret[i][m][1]=j;
  112816. }
  112817. }
  112818. return(ret);
  112819. }
  112820. void _vp_psy_init(vorbis_look_psy *p,vorbis_info_psy *vi,
  112821. vorbis_info_psy_global *gi,int n,long rate){
  112822. long i,j,lo=-99,hi=1;
  112823. long maxoc;
  112824. memset(p,0,sizeof(*p));
  112825. p->eighth_octave_lines=gi->eighth_octave_lines;
  112826. p->shiftoc=rint(log(gi->eighth_octave_lines*8.f)/log(2.f))-1;
  112827. p->firstoc=toOC(.25f*rate*.5/n)*(1<<(p->shiftoc+1))-gi->eighth_octave_lines;
  112828. maxoc=toOC((n+.25f)*rate*.5/n)*(1<<(p->shiftoc+1))+.5f;
  112829. p->total_octave_lines=maxoc-p->firstoc+1;
  112830. p->ath=(float*)_ogg_malloc(n*sizeof(*p->ath));
  112831. p->octave=(long*)_ogg_malloc(n*sizeof(*p->octave));
  112832. p->bark=(long*)_ogg_malloc(n*sizeof(*p->bark));
  112833. p->vi=vi;
  112834. p->n=n;
  112835. p->rate=rate;
  112836. /* AoTuV HF weighting */
  112837. p->m_val = 1.;
  112838. if(rate < 26000) p->m_val = 0;
  112839. else if(rate < 38000) p->m_val = .94; /* 32kHz */
  112840. else if(rate > 46000) p->m_val = 1.275; /* 48kHz */
  112841. /* set up the lookups for a given blocksize and sample rate */
  112842. for(i=0,j=0;i<MAX_ATH-1;i++){
  112843. int endpos=rint(fromOC((i+1)*.125-2.)*2*n/rate);
  112844. float base=ATH[i];
  112845. if(j<endpos){
  112846. float delta=(ATH[i+1]-base)/(endpos-j);
  112847. for(;j<endpos && j<n;j++){
  112848. p->ath[j]=base+100.;
  112849. base+=delta;
  112850. }
  112851. }
  112852. }
  112853. for(i=0;i<n;i++){
  112854. float bark=toBARK(rate/(2*n)*i);
  112855. for(;lo+vi->noisewindowlomin<i &&
  112856. toBARK(rate/(2*n)*lo)<(bark-vi->noisewindowlo);lo++);
  112857. for(;hi<=n && (hi<i+vi->noisewindowhimin ||
  112858. toBARK(rate/(2*n)*hi)<(bark+vi->noisewindowhi));hi++);
  112859. p->bark[i]=((lo-1)<<16)+(hi-1);
  112860. }
  112861. for(i=0;i<n;i++)
  112862. p->octave[i]=toOC((i+.25f)*.5*rate/n)*(1<<(p->shiftoc+1))+.5f;
  112863. p->tonecurves=setup_tone_curves(vi->toneatt,rate*.5/n,n,
  112864. vi->tone_centerboost,vi->tone_decay);
  112865. /* set up rolling noise median */
  112866. p->noiseoffset=(float**)_ogg_malloc(P_NOISECURVES*sizeof(*p->noiseoffset));
  112867. for(i=0;i<P_NOISECURVES;i++)
  112868. p->noiseoffset[i]=(float*)_ogg_malloc(n*sizeof(**p->noiseoffset));
  112869. for(i=0;i<n;i++){
  112870. float halfoc=toOC((i+.5)*rate/(2.*n))*2.;
  112871. int inthalfoc;
  112872. float del;
  112873. if(halfoc<0)halfoc=0;
  112874. if(halfoc>=P_BANDS-1)halfoc=P_BANDS-1;
  112875. inthalfoc=(int)halfoc;
  112876. del=halfoc-inthalfoc;
  112877. for(j=0;j<P_NOISECURVES;j++)
  112878. p->noiseoffset[j][i]=
  112879. p->vi->noiseoff[j][inthalfoc]*(1.-del) +
  112880. p->vi->noiseoff[j][inthalfoc+1]*del;
  112881. }
  112882. #if 0
  112883. {
  112884. static int ls=0;
  112885. _analysis_output_always("noiseoff0",ls,p->noiseoffset[0],n,1,0,0);
  112886. _analysis_output_always("noiseoff1",ls,p->noiseoffset[1],n,1,0,0);
  112887. _analysis_output_always("noiseoff2",ls++,p->noiseoffset[2],n,1,0,0);
  112888. }
  112889. #endif
  112890. }
  112891. void _vp_psy_clear(vorbis_look_psy *p){
  112892. int i,j;
  112893. if(p){
  112894. if(p->ath)_ogg_free(p->ath);
  112895. if(p->octave)_ogg_free(p->octave);
  112896. if(p->bark)_ogg_free(p->bark);
  112897. if(p->tonecurves){
  112898. for(i=0;i<P_BANDS;i++){
  112899. for(j=0;j<P_LEVELS;j++){
  112900. _ogg_free(p->tonecurves[i][j]);
  112901. }
  112902. _ogg_free(p->tonecurves[i]);
  112903. }
  112904. _ogg_free(p->tonecurves);
  112905. }
  112906. if(p->noiseoffset){
  112907. for(i=0;i<P_NOISECURVES;i++){
  112908. _ogg_free(p->noiseoffset[i]);
  112909. }
  112910. _ogg_free(p->noiseoffset);
  112911. }
  112912. memset(p,0,sizeof(*p));
  112913. }
  112914. }
  112915. /* octave/(8*eighth_octave_lines) x scale and dB y scale */
  112916. static void seed_curve(float *seed,
  112917. const float **curves,
  112918. float amp,
  112919. int oc, int n,
  112920. int linesper,float dBoffset){
  112921. int i,post1;
  112922. int seedptr;
  112923. const float *posts,*curve;
  112924. int choice=(int)((amp+dBoffset-P_LEVEL_0)*.1f);
  112925. choice=max(choice,0);
  112926. choice=min(choice,P_LEVELS-1);
  112927. posts=curves[choice];
  112928. curve=posts+2;
  112929. post1=(int)posts[1];
  112930. seedptr=oc+(posts[0]-EHMER_OFFSET)*linesper-(linesper>>1);
  112931. for(i=posts[0];i<post1;i++){
  112932. if(seedptr>0){
  112933. float lin=amp+curve[i];
  112934. if(seed[seedptr]<lin)seed[seedptr]=lin;
  112935. }
  112936. seedptr+=linesper;
  112937. if(seedptr>=n)break;
  112938. }
  112939. }
  112940. static void seed_loop(vorbis_look_psy *p,
  112941. const float ***curves,
  112942. const float *f,
  112943. const float *flr,
  112944. float *seed,
  112945. float specmax){
  112946. vorbis_info_psy *vi=p->vi;
  112947. long n=p->n,i;
  112948. float dBoffset=vi->max_curve_dB-specmax;
  112949. /* prime the working vector with peak values */
  112950. for(i=0;i<n;i++){
  112951. float max=f[i];
  112952. long oc=p->octave[i];
  112953. while(i+1<n && p->octave[i+1]==oc){
  112954. i++;
  112955. if(f[i]>max)max=f[i];
  112956. }
  112957. if(max+6.f>flr[i]){
  112958. oc=oc>>p->shiftoc;
  112959. if(oc>=P_BANDS)oc=P_BANDS-1;
  112960. if(oc<0)oc=0;
  112961. seed_curve(seed,
  112962. curves[oc],
  112963. max,
  112964. p->octave[i]-p->firstoc,
  112965. p->total_octave_lines,
  112966. p->eighth_octave_lines,
  112967. dBoffset);
  112968. }
  112969. }
  112970. }
  112971. static void seed_chase(float *seeds, int linesper, long n){
  112972. long *posstack=(long*)alloca(n*sizeof(*posstack));
  112973. float *ampstack=(float*)alloca(n*sizeof(*ampstack));
  112974. long stack=0;
  112975. long pos=0;
  112976. long i;
  112977. for(i=0;i<n;i++){
  112978. if(stack<2){
  112979. posstack[stack]=i;
  112980. ampstack[stack++]=seeds[i];
  112981. }else{
  112982. while(1){
  112983. if(seeds[i]<ampstack[stack-1]){
  112984. posstack[stack]=i;
  112985. ampstack[stack++]=seeds[i];
  112986. break;
  112987. }else{
  112988. if(i<posstack[stack-1]+linesper){
  112989. if(stack>1 && ampstack[stack-1]<=ampstack[stack-2] &&
  112990. i<posstack[stack-2]+linesper){
  112991. /* we completely overlap, making stack-1 irrelevant. pop it */
  112992. stack--;
  112993. continue;
  112994. }
  112995. }
  112996. posstack[stack]=i;
  112997. ampstack[stack++]=seeds[i];
  112998. break;
  112999. }
  113000. }
  113001. }
  113002. }
  113003. /* the stack now contains only the positions that are relevant. Scan
  113004. 'em straight through */
  113005. for(i=0;i<stack;i++){
  113006. long endpos;
  113007. if(i<stack-1 && ampstack[i+1]>ampstack[i]){
  113008. endpos=posstack[i+1];
  113009. }else{
  113010. endpos=posstack[i]+linesper+1; /* +1 is important, else bin 0 is
  113011. discarded in short frames */
  113012. }
  113013. if(endpos>n)endpos=n;
  113014. for(;pos<endpos;pos++)
  113015. seeds[pos]=ampstack[i];
  113016. }
  113017. /* there. Linear time. I now remember this was on a problem set I
  113018. had in Grad Skool... I didn't solve it at the time ;-) */
  113019. }
  113020. /* bleaugh, this is more complicated than it needs to be */
  113021. #include<stdio.h>
  113022. static void max_seeds(vorbis_look_psy *p,
  113023. float *seed,
  113024. float *flr){
  113025. long n=p->total_octave_lines;
  113026. int linesper=p->eighth_octave_lines;
  113027. long linpos=0;
  113028. long pos;
  113029. seed_chase(seed,linesper,n); /* for masking */
  113030. pos=p->octave[0]-p->firstoc-(linesper>>1);
  113031. while(linpos+1<p->n){
  113032. float minV=seed[pos];
  113033. long end=((p->octave[linpos]+p->octave[linpos+1])>>1)-p->firstoc;
  113034. if(minV>p->vi->tone_abs_limit)minV=p->vi->tone_abs_limit;
  113035. while(pos+1<=end){
  113036. pos++;
  113037. if((seed[pos]>NEGINF && seed[pos]<minV) || minV==NEGINF)
  113038. minV=seed[pos];
  113039. }
  113040. end=pos+p->firstoc;
  113041. for(;linpos<p->n && p->octave[linpos]<=end;linpos++)
  113042. if(flr[linpos]<minV)flr[linpos]=minV;
  113043. }
  113044. {
  113045. float minV=seed[p->total_octave_lines-1];
  113046. for(;linpos<p->n;linpos++)
  113047. if(flr[linpos]<minV)flr[linpos]=minV;
  113048. }
  113049. }
  113050. static void bark_noise_hybridmp(int n,const long *b,
  113051. const float *f,
  113052. float *noise,
  113053. const float offset,
  113054. const int fixed){
  113055. float *N=(float*) alloca(n*sizeof(*N));
  113056. float *X=(float*) alloca(n*sizeof(*N));
  113057. float *XX=(float*) alloca(n*sizeof(*N));
  113058. float *Y=(float*) alloca(n*sizeof(*N));
  113059. float *XY=(float*) alloca(n*sizeof(*N));
  113060. float tN, tX, tXX, tY, tXY;
  113061. int i;
  113062. int lo, hi;
  113063. float R, A, B, D;
  113064. float w, x, y;
  113065. tN = tX = tXX = tY = tXY = 0.f;
  113066. y = f[0] + offset;
  113067. if (y < 1.f) y = 1.f;
  113068. w = y * y * .5;
  113069. tN += w;
  113070. tX += w;
  113071. tY += w * y;
  113072. N[0] = tN;
  113073. X[0] = tX;
  113074. XX[0] = tXX;
  113075. Y[0] = tY;
  113076. XY[0] = tXY;
  113077. for (i = 1, x = 1.f; i < n; i++, x += 1.f) {
  113078. y = f[i] + offset;
  113079. if (y < 1.f) y = 1.f;
  113080. w = y * y;
  113081. tN += w;
  113082. tX += w * x;
  113083. tXX += w * x * x;
  113084. tY += w * y;
  113085. tXY += w * x * y;
  113086. N[i] = tN;
  113087. X[i] = tX;
  113088. XX[i] = tXX;
  113089. Y[i] = tY;
  113090. XY[i] = tXY;
  113091. }
  113092. for (i = 0, x = 0.f;; i++, x += 1.f) {
  113093. lo = b[i] >> 16;
  113094. if( lo>=0 ) break;
  113095. hi = b[i] & 0xffff;
  113096. tN = N[hi] + N[-lo];
  113097. tX = X[hi] - X[-lo];
  113098. tXX = XX[hi] + XX[-lo];
  113099. tY = Y[hi] + Y[-lo];
  113100. tXY = XY[hi] - XY[-lo];
  113101. A = tY * tXX - tX * tXY;
  113102. B = tN * tXY - tX * tY;
  113103. D = tN * tXX - tX * tX;
  113104. R = (A + x * B) / D;
  113105. if (R < 0.f)
  113106. R = 0.f;
  113107. noise[i] = R - offset;
  113108. }
  113109. for ( ;; i++, x += 1.f) {
  113110. lo = b[i] >> 16;
  113111. hi = b[i] & 0xffff;
  113112. if(hi>=n)break;
  113113. tN = N[hi] - N[lo];
  113114. tX = X[hi] - X[lo];
  113115. tXX = XX[hi] - XX[lo];
  113116. tY = Y[hi] - Y[lo];
  113117. tXY = XY[hi] - XY[lo];
  113118. A = tY * tXX - tX * tXY;
  113119. B = tN * tXY - tX * tY;
  113120. D = tN * tXX - tX * tX;
  113121. R = (A + x * B) / D;
  113122. if (R < 0.f) R = 0.f;
  113123. noise[i] = R - offset;
  113124. }
  113125. for ( ; i < n; i++, x += 1.f) {
  113126. R = (A + x * B) / D;
  113127. if (R < 0.f) R = 0.f;
  113128. noise[i] = R - offset;
  113129. }
  113130. if (fixed <= 0) return;
  113131. for (i = 0, x = 0.f;; i++, x += 1.f) {
  113132. hi = i + fixed / 2;
  113133. lo = hi - fixed;
  113134. if(lo>=0)break;
  113135. tN = N[hi] + N[-lo];
  113136. tX = X[hi] - X[-lo];
  113137. tXX = XX[hi] + XX[-lo];
  113138. tY = Y[hi] + Y[-lo];
  113139. tXY = XY[hi] - XY[-lo];
  113140. A = tY * tXX - tX * tXY;
  113141. B = tN * tXY - tX * tY;
  113142. D = tN * tXX - tX * tX;
  113143. R = (A + x * B) / D;
  113144. if (R - offset < noise[i]) noise[i] = R - offset;
  113145. }
  113146. for ( ;; i++, x += 1.f) {
  113147. hi = i + fixed / 2;
  113148. lo = hi - fixed;
  113149. if(hi>=n)break;
  113150. tN = N[hi] - N[lo];
  113151. tX = X[hi] - X[lo];
  113152. tXX = XX[hi] - XX[lo];
  113153. tY = Y[hi] - Y[lo];
  113154. tXY = XY[hi] - XY[lo];
  113155. A = tY * tXX - tX * tXY;
  113156. B = tN * tXY - tX * tY;
  113157. D = tN * tXX - tX * tX;
  113158. R = (A + x * B) / D;
  113159. if (R - offset < noise[i]) noise[i] = R - offset;
  113160. }
  113161. for ( ; i < n; i++, x += 1.f) {
  113162. R = (A + x * B) / D;
  113163. if (R - offset < noise[i]) noise[i] = R - offset;
  113164. }
  113165. }
  113166. static float FLOOR1_fromdB_INV_LOOKUP[256]={
  113167. 0.F, 8.81683e+06F, 8.27882e+06F, 7.77365e+06F,
  113168. 7.29930e+06F, 6.85389e+06F, 6.43567e+06F, 6.04296e+06F,
  113169. 5.67422e+06F, 5.32798e+06F, 5.00286e+06F, 4.69759e+06F,
  113170. 4.41094e+06F, 4.14178e+06F, 3.88905e+06F, 3.65174e+06F,
  113171. 3.42891e+06F, 3.21968e+06F, 3.02321e+06F, 2.83873e+06F,
  113172. 2.66551e+06F, 2.50286e+06F, 2.35014e+06F, 2.20673e+06F,
  113173. 2.07208e+06F, 1.94564e+06F, 1.82692e+06F, 1.71544e+06F,
  113174. 1.61076e+06F, 1.51247e+06F, 1.42018e+06F, 1.33352e+06F,
  113175. 1.25215e+06F, 1.17574e+06F, 1.10400e+06F, 1.03663e+06F,
  113176. 973377.F, 913981.F, 858210.F, 805842.F,
  113177. 756669.F, 710497.F, 667142.F, 626433.F,
  113178. 588208.F, 552316.F, 518613.F, 486967.F,
  113179. 457252.F, 429351.F, 403152.F, 378551.F,
  113180. 355452.F, 333762.F, 313396.F, 294273.F,
  113181. 276316.F, 259455.F, 243623.F, 228757.F,
  113182. 214798.F, 201691.F, 189384.F, 177828.F,
  113183. 166977.F, 156788.F, 147221.F, 138237.F,
  113184. 129802.F, 121881.F, 114444.F, 107461.F,
  113185. 100903.F, 94746.3F, 88964.9F, 83536.2F,
  113186. 78438.8F, 73652.5F, 69158.2F, 64938.1F,
  113187. 60975.6F, 57254.9F, 53761.2F, 50480.6F,
  113188. 47400.3F, 44507.9F, 41792.0F, 39241.9F,
  113189. 36847.3F, 34598.9F, 32487.7F, 30505.3F,
  113190. 28643.8F, 26896.0F, 25254.8F, 23713.7F,
  113191. 22266.7F, 20908.0F, 19632.2F, 18434.2F,
  113192. 17309.4F, 16253.1F, 15261.4F, 14330.1F,
  113193. 13455.7F, 12634.6F, 11863.7F, 11139.7F,
  113194. 10460.0F, 9821.72F, 9222.39F, 8659.64F,
  113195. 8131.23F, 7635.06F, 7169.17F, 6731.70F,
  113196. 6320.93F, 5935.23F, 5573.06F, 5232.99F,
  113197. 4913.67F, 4613.84F, 4332.30F, 4067.94F,
  113198. 3819.72F, 3586.64F, 3367.78F, 3162.28F,
  113199. 2969.31F, 2788.13F, 2617.99F, 2458.24F,
  113200. 2308.24F, 2167.39F, 2035.14F, 1910.95F,
  113201. 1794.35F, 1684.85F, 1582.04F, 1485.51F,
  113202. 1394.86F, 1309.75F, 1229.83F, 1154.78F,
  113203. 1084.32F, 1018.15F, 956.024F, 897.687F,
  113204. 842.910F, 791.475F, 743.179F, 697.830F,
  113205. 655.249F, 615.265F, 577.722F, 542.469F,
  113206. 509.367F, 478.286F, 449.101F, 421.696F,
  113207. 395.964F, 371.803F, 349.115F, 327.812F,
  113208. 307.809F, 289.026F, 271.390F, 254.830F,
  113209. 239.280F, 224.679F, 210.969F, 198.096F,
  113210. 186.008F, 174.658F, 164.000F, 153.993F,
  113211. 144.596F, 135.773F, 127.488F, 119.708F,
  113212. 112.404F, 105.545F, 99.1046F, 93.0572F,
  113213. 87.3788F, 82.0469F, 77.0404F, 72.3394F,
  113214. 67.9252F, 63.7804F, 59.8885F, 56.2341F,
  113215. 52.8027F, 49.5807F, 46.5553F, 43.7144F,
  113216. 41.0470F, 38.5423F, 36.1904F, 33.9821F,
  113217. 31.9085F, 29.9614F, 28.1332F, 26.4165F,
  113218. 24.8045F, 23.2910F, 21.8697F, 20.5352F,
  113219. 19.2822F, 18.1056F, 17.0008F, 15.9634F,
  113220. 14.9893F, 14.0746F, 13.2158F, 12.4094F,
  113221. 11.6522F, 10.9411F, 10.2735F, 9.64662F,
  113222. 9.05798F, 8.50526F, 7.98626F, 7.49894F,
  113223. 7.04135F, 6.61169F, 6.20824F, 5.82941F,
  113224. 5.47370F, 5.13970F, 4.82607F, 4.53158F,
  113225. 4.25507F, 3.99542F, 3.75162F, 3.52269F,
  113226. 3.30774F, 3.10590F, 2.91638F, 2.73842F,
  113227. 2.57132F, 2.41442F, 2.26709F, 2.12875F,
  113228. 1.99885F, 1.87688F, 1.76236F, 1.65482F,
  113229. 1.55384F, 1.45902F, 1.36999F, 1.28640F,
  113230. 1.20790F, 1.13419F, 1.06499F, 1.F
  113231. };
  113232. void _vp_remove_floor(vorbis_look_psy *p,
  113233. float *mdct,
  113234. int *codedflr,
  113235. float *residue,
  113236. int sliding_lowpass){
  113237. int i,n=p->n;
  113238. if(sliding_lowpass>n)sliding_lowpass=n;
  113239. for(i=0;i<sliding_lowpass;i++){
  113240. residue[i]=
  113241. mdct[i]*FLOOR1_fromdB_INV_LOOKUP[codedflr[i]];
  113242. }
  113243. for(;i<n;i++)
  113244. residue[i]=0.;
  113245. }
  113246. void _vp_noisemask(vorbis_look_psy *p,
  113247. float *logmdct,
  113248. float *logmask){
  113249. int i,n=p->n;
  113250. float *work=(float*) alloca(n*sizeof(*work));
  113251. bark_noise_hybridmp(n,p->bark,logmdct,logmask,
  113252. 140.,-1);
  113253. for(i=0;i<n;i++)work[i]=logmdct[i]-logmask[i];
  113254. bark_noise_hybridmp(n,p->bark,work,logmask,0.,
  113255. p->vi->noisewindowfixed);
  113256. for(i=0;i<n;i++)work[i]=logmdct[i]-work[i];
  113257. #if 0
  113258. {
  113259. static int seq=0;
  113260. float work2[n];
  113261. for(i=0;i<n;i++){
  113262. work2[i]=logmask[i]+work[i];
  113263. }
  113264. if(seq&1)
  113265. _analysis_output("median2R",seq/2,work,n,1,0,0);
  113266. else
  113267. _analysis_output("median2L",seq/2,work,n,1,0,0);
  113268. if(seq&1)
  113269. _analysis_output("envelope2R",seq/2,work2,n,1,0,0);
  113270. else
  113271. _analysis_output("envelope2L",seq/2,work2,n,1,0,0);
  113272. seq++;
  113273. }
  113274. #endif
  113275. for(i=0;i<n;i++){
  113276. int dB=logmask[i]+.5;
  113277. if(dB>=NOISE_COMPAND_LEVELS)dB=NOISE_COMPAND_LEVELS-1;
  113278. if(dB<0)dB=0;
  113279. logmask[i]= work[i]+p->vi->noisecompand[dB];
  113280. }
  113281. }
  113282. void _vp_tonemask(vorbis_look_psy *p,
  113283. float *logfft,
  113284. float *logmask,
  113285. float global_specmax,
  113286. float local_specmax){
  113287. int i,n=p->n;
  113288. float *seed=(float*) alloca(sizeof(*seed)*p->total_octave_lines);
  113289. float att=local_specmax+p->vi->ath_adjatt;
  113290. for(i=0;i<p->total_octave_lines;i++)seed[i]=NEGINF;
  113291. /* set the ATH (floating below localmax, not global max by a
  113292. specified att) */
  113293. if(att<p->vi->ath_maxatt)att=p->vi->ath_maxatt;
  113294. for(i=0;i<n;i++)
  113295. logmask[i]=p->ath[i]+att;
  113296. /* tone masking */
  113297. seed_loop(p,(const float ***)p->tonecurves,logfft,logmask,seed,global_specmax);
  113298. max_seeds(p,seed,logmask);
  113299. }
  113300. void _vp_offset_and_mix(vorbis_look_psy *p,
  113301. float *noise,
  113302. float *tone,
  113303. int offset_select,
  113304. float *logmask,
  113305. float *mdct,
  113306. float *logmdct){
  113307. int i,n=p->n;
  113308. float de, coeffi, cx;/* AoTuV */
  113309. float toneatt=p->vi->tone_masteratt[offset_select];
  113310. cx = p->m_val;
  113311. for(i=0;i<n;i++){
  113312. float val= noise[i]+p->noiseoffset[offset_select][i];
  113313. if(val>p->vi->noisemaxsupp)val=p->vi->noisemaxsupp;
  113314. logmask[i]=max(val,tone[i]+toneatt);
  113315. /* AoTuV */
  113316. /** @ M1 **
  113317. The following codes improve a noise problem.
  113318. A fundamental idea uses the value of masking and carries out
  113319. the relative compensation of the MDCT.
  113320. However, this code is not perfect and all noise problems cannot be solved.
  113321. by Aoyumi @ 2004/04/18
  113322. */
  113323. if(offset_select == 1) {
  113324. coeffi = -17.2; /* coeffi is a -17.2dB threshold */
  113325. val = val - logmdct[i]; /* val == mdct line value relative to floor in dB */
  113326. if(val > coeffi){
  113327. /* mdct value is > -17.2 dB below floor */
  113328. de = 1.0-((val-coeffi)*0.005*cx);
  113329. /* pro-rated attenuation:
  113330. -0.00 dB boost if mdct value is -17.2dB (relative to floor)
  113331. -0.77 dB boost if mdct value is 0dB (relative to floor)
  113332. -1.64 dB boost if mdct value is +17.2dB (relative to floor)
  113333. etc... */
  113334. if(de < 0) de = 0.0001;
  113335. }else
  113336. /* mdct value is <= -17.2 dB below floor */
  113337. de = 1.0-((val-coeffi)*0.0003*cx);
  113338. /* pro-rated attenuation:
  113339. +0.00 dB atten if mdct value is -17.2dB (relative to floor)
  113340. +0.45 dB atten if mdct value is -34.4dB (relative to floor)
  113341. etc... */
  113342. mdct[i] *= de;
  113343. }
  113344. }
  113345. }
  113346. float _vp_ampmax_decay(float amp,vorbis_dsp_state *vd){
  113347. vorbis_info *vi=vd->vi;
  113348. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  113349. vorbis_info_psy_global *gi=&ci->psy_g_param;
  113350. int n=ci->blocksizes[vd->W]/2;
  113351. float secs=(float)n/vi->rate;
  113352. amp+=secs*gi->ampmax_att_per_sec;
  113353. if(amp<-9999)amp=-9999;
  113354. return(amp);
  113355. }
  113356. static void couple_lossless(float A, float B,
  113357. float *qA, float *qB){
  113358. int test1=fabs(*qA)>fabs(*qB);
  113359. test1-= fabs(*qA)<fabs(*qB);
  113360. if(!test1)test1=((fabs(A)>fabs(B))<<1)-1;
  113361. if(test1==1){
  113362. *qB=(*qA>0.f?*qA-*qB:*qB-*qA);
  113363. }else{
  113364. float temp=*qB;
  113365. *qB=(*qB>0.f?*qA-*qB:*qB-*qA);
  113366. *qA=temp;
  113367. }
  113368. if(*qB>fabs(*qA)*1.9999f){
  113369. *qB= -fabs(*qA)*2.f;
  113370. *qA= -*qA;
  113371. }
  113372. }
  113373. static float hypot_lookup[32]={
  113374. -0.009935, -0.011245, -0.012726, -0.014397,
  113375. -0.016282, -0.018407, -0.020800, -0.023494,
  113376. -0.026522, -0.029923, -0.033737, -0.038010,
  113377. -0.042787, -0.048121, -0.054064, -0.060671,
  113378. -0.068000, -0.076109, -0.085054, -0.094892,
  113379. -0.105675, -0.117451, -0.130260, -0.144134,
  113380. -0.159093, -0.175146, -0.192286, -0.210490,
  113381. -0.229718, -0.249913, -0.271001, -0.292893};
  113382. static void precomputed_couple_point(float premag,
  113383. int floorA,int floorB,
  113384. float *mag, float *ang){
  113385. int test=(floorA>floorB)-1;
  113386. int offset=31-abs(floorA-floorB);
  113387. float floormag=hypot_lookup[((offset<0)-1)&offset]+1.f;
  113388. floormag*=FLOOR1_fromdB_INV_LOOKUP[(floorB&test)|(floorA&(~test))];
  113389. *mag=premag*floormag;
  113390. *ang=0.f;
  113391. }
  113392. /* just like below, this is currently set up to only do
  113393. single-step-depth coupling. Otherwise, we'd have to do more
  113394. copying (which will be inevitable later) */
  113395. /* doing the real circular magnitude calculation is audibly superior
  113396. to (A+B)/sqrt(2) */
  113397. static float dipole_hypot(float a, float b){
  113398. if(a>0.){
  113399. if(b>0.)return sqrt(a*a+b*b);
  113400. if(a>-b)return sqrt(a*a-b*b);
  113401. return -sqrt(b*b-a*a);
  113402. }
  113403. if(b<0.)return -sqrt(a*a+b*b);
  113404. if(-a>b)return -sqrt(a*a-b*b);
  113405. return sqrt(b*b-a*a);
  113406. }
  113407. static float round_hypot(float a, float b){
  113408. if(a>0.){
  113409. if(b>0.)return sqrt(a*a+b*b);
  113410. if(a>-b)return sqrt(a*a+b*b);
  113411. return -sqrt(b*b+a*a);
  113412. }
  113413. if(b<0.)return -sqrt(a*a+b*b);
  113414. if(-a>b)return -sqrt(a*a+b*b);
  113415. return sqrt(b*b+a*a);
  113416. }
  113417. /* revert to round hypot for now */
  113418. float **_vp_quantize_couple_memo(vorbis_block *vb,
  113419. vorbis_info_psy_global *g,
  113420. vorbis_look_psy *p,
  113421. vorbis_info_mapping0 *vi,
  113422. float **mdct){
  113423. int i,j,n=p->n;
  113424. float **ret=(float**) _vorbis_block_alloc(vb,vi->coupling_steps*sizeof(*ret));
  113425. int limit=g->coupling_pointlimit[p->vi->blockflag][PACKETBLOBS/2];
  113426. for(i=0;i<vi->coupling_steps;i++){
  113427. float *mdctM=mdct[vi->coupling_mag[i]];
  113428. float *mdctA=mdct[vi->coupling_ang[i]];
  113429. ret[i]=(float*) _vorbis_block_alloc(vb,n*sizeof(**ret));
  113430. for(j=0;j<limit;j++)
  113431. ret[i][j]=dipole_hypot(mdctM[j],mdctA[j]);
  113432. for(;j<n;j++)
  113433. ret[i][j]=round_hypot(mdctM[j],mdctA[j]);
  113434. }
  113435. return(ret);
  113436. }
  113437. /* this is for per-channel noise normalization */
  113438. static int apsort(const void *a, const void *b){
  113439. float f1=fabs(**(float**)a);
  113440. float f2=fabs(**(float**)b);
  113441. return (f1<f2)-(f1>f2);
  113442. }
  113443. int **_vp_quantize_couple_sort(vorbis_block *vb,
  113444. vorbis_look_psy *p,
  113445. vorbis_info_mapping0 *vi,
  113446. float **mags){
  113447. if(p->vi->normal_point_p){
  113448. int i,j,k,n=p->n;
  113449. int **ret=(int**) _vorbis_block_alloc(vb,vi->coupling_steps*sizeof(*ret));
  113450. int partition=p->vi->normal_partition;
  113451. float **work=(float**) alloca(sizeof(*work)*partition);
  113452. for(i=0;i<vi->coupling_steps;i++){
  113453. ret[i]=(int*) _vorbis_block_alloc(vb,n*sizeof(**ret));
  113454. for(j=0;j<n;j+=partition){
  113455. for(k=0;k<partition;k++)work[k]=mags[i]+k+j;
  113456. qsort(work,partition,sizeof(*work),apsort);
  113457. for(k=0;k<partition;k++)ret[i][k+j]=work[k]-mags[i];
  113458. }
  113459. }
  113460. return(ret);
  113461. }
  113462. return(NULL);
  113463. }
  113464. void _vp_noise_normalize_sort(vorbis_look_psy *p,
  113465. float *magnitudes,int *sortedindex){
  113466. int i,j,n=p->n;
  113467. vorbis_info_psy *vi=p->vi;
  113468. int partition=vi->normal_partition;
  113469. float **work=(float**) alloca(sizeof(*work)*partition);
  113470. int start=vi->normal_start;
  113471. for(j=start;j<n;j+=partition){
  113472. if(j+partition>n)partition=n-j;
  113473. for(i=0;i<partition;i++)work[i]=magnitudes+i+j;
  113474. qsort(work,partition,sizeof(*work),apsort);
  113475. for(i=0;i<partition;i++){
  113476. sortedindex[i+j-start]=work[i]-magnitudes;
  113477. }
  113478. }
  113479. }
  113480. void _vp_noise_normalize(vorbis_look_psy *p,
  113481. float *in,float *out,int *sortedindex){
  113482. int flag=0,i,j=0,n=p->n;
  113483. vorbis_info_psy *vi=p->vi;
  113484. int partition=vi->normal_partition;
  113485. int start=vi->normal_start;
  113486. if(start>n)start=n;
  113487. if(vi->normal_channel_p){
  113488. for(;j<start;j++)
  113489. out[j]=rint(in[j]);
  113490. for(;j+partition<=n;j+=partition){
  113491. float acc=0.;
  113492. int k;
  113493. for(i=j;i<j+partition;i++)
  113494. acc+=in[i]*in[i];
  113495. for(i=0;i<partition;i++){
  113496. k=sortedindex[i+j-start];
  113497. if(in[k]*in[k]>=.25f){
  113498. out[k]=rint(in[k]);
  113499. acc-=in[k]*in[k];
  113500. flag=1;
  113501. }else{
  113502. if(acc<vi->normal_thresh)break;
  113503. out[k]=unitnorm(in[k]);
  113504. acc-=1.;
  113505. }
  113506. }
  113507. for(;i<partition;i++){
  113508. k=sortedindex[i+j-start];
  113509. out[k]=0.;
  113510. }
  113511. }
  113512. }
  113513. for(;j<n;j++)
  113514. out[j]=rint(in[j]);
  113515. }
  113516. void _vp_couple(int blobno,
  113517. vorbis_info_psy_global *g,
  113518. vorbis_look_psy *p,
  113519. vorbis_info_mapping0 *vi,
  113520. float **res,
  113521. float **mag_memo,
  113522. int **mag_sort,
  113523. int **ifloor,
  113524. int *nonzero,
  113525. int sliding_lowpass){
  113526. int i,j,k,n=p->n;
  113527. /* perform any requested channel coupling */
  113528. /* point stereo can only be used in a first stage (in this encoder)
  113529. because of the dependency on floor lookups */
  113530. for(i=0;i<vi->coupling_steps;i++){
  113531. /* once we're doing multistage coupling in which a channel goes
  113532. through more than one coupling step, the floor vector
  113533. magnitudes will also have to be recalculated an propogated
  113534. along with PCM. Right now, we're not (that will wait until 5.1
  113535. most likely), so the code isn't here yet. The memory management
  113536. here is all assuming single depth couplings anyway. */
  113537. /* make sure coupling a zero and a nonzero channel results in two
  113538. nonzero channels. */
  113539. if(nonzero[vi->coupling_mag[i]] ||
  113540. nonzero[vi->coupling_ang[i]]){
  113541. float *rM=res[vi->coupling_mag[i]];
  113542. float *rA=res[vi->coupling_ang[i]];
  113543. float *qM=rM+n;
  113544. float *qA=rA+n;
  113545. int *floorM=ifloor[vi->coupling_mag[i]];
  113546. int *floorA=ifloor[vi->coupling_ang[i]];
  113547. float prepoint=stereo_threshholds[g->coupling_prepointamp[blobno]];
  113548. float postpoint=stereo_threshholds[g->coupling_postpointamp[blobno]];
  113549. int partition=(p->vi->normal_point_p?p->vi->normal_partition:p->n);
  113550. int limit=g->coupling_pointlimit[p->vi->blockflag][blobno];
  113551. int pointlimit=limit;
  113552. nonzero[vi->coupling_mag[i]]=1;
  113553. nonzero[vi->coupling_ang[i]]=1;
  113554. /* The threshold of a stereo is changed with the size of n */
  113555. if(n > 1000)
  113556. postpoint=stereo_threshholds_limited[g->coupling_postpointamp[blobno]];
  113557. for(j=0;j<p->n;j+=partition){
  113558. float acc=0.f;
  113559. for(k=0;k<partition;k++){
  113560. int l=k+j;
  113561. if(l<sliding_lowpass){
  113562. if((l>=limit && fabs(rM[l])<postpoint && fabs(rA[l])<postpoint) ||
  113563. (fabs(rM[l])<prepoint && fabs(rA[l])<prepoint)){
  113564. precomputed_couple_point(mag_memo[i][l],
  113565. floorM[l],floorA[l],
  113566. qM+l,qA+l);
  113567. if(rint(qM[l])==0.f)acc+=qM[l]*qM[l];
  113568. }else{
  113569. couple_lossless(rM[l],rA[l],qM+l,qA+l);
  113570. }
  113571. }else{
  113572. qM[l]=0.;
  113573. qA[l]=0.;
  113574. }
  113575. }
  113576. if(p->vi->normal_point_p){
  113577. for(k=0;k<partition && acc>=p->vi->normal_thresh;k++){
  113578. int l=mag_sort[i][j+k];
  113579. if(l<sliding_lowpass && l>=pointlimit && rint(qM[l])==0.f){
  113580. qM[l]=unitnorm(qM[l]);
  113581. acc-=1.f;
  113582. }
  113583. }
  113584. }
  113585. }
  113586. }
  113587. }
  113588. }
  113589. /* AoTuV */
  113590. /** @ M2 **
  113591. The boost problem by the combination of noise normalization and point stereo is eased.
  113592. However, this is a temporary patch.
  113593. by Aoyumi @ 2004/04/18
  113594. */
  113595. void hf_reduction(vorbis_info_psy_global *g,
  113596. vorbis_look_psy *p,
  113597. vorbis_info_mapping0 *vi,
  113598. float **mdct){
  113599. int i,j,n=p->n, de=0.3*p->m_val;
  113600. int limit=g->coupling_pointlimit[p->vi->blockflag][PACKETBLOBS/2];
  113601. for(i=0; i<vi->coupling_steps; i++){
  113602. /* for(j=start; j<limit; j++){} // ???*/
  113603. for(j=limit; j<n; j++)
  113604. mdct[i][j] *= (1.0 - de*((float)(j-limit) / (float)(n-limit)));
  113605. }
  113606. }
  113607. #endif
  113608. /********* End of inlined file: psy.c *********/
  113609. /********* Start of inlined file: registry.c *********/
  113610. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  113611. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  113612. // tasks..
  113613. #ifdef _MSC_VER
  113614. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  113615. #endif
  113616. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  113617. #if JUCE_USE_OGGVORBIS
  113618. /* seems like major overkill now; the backend numbers will grow into
  113619. the infrastructure soon enough */
  113620. extern vorbis_func_floor floor0_exportbundle;
  113621. extern vorbis_func_floor floor1_exportbundle;
  113622. extern vorbis_func_residue residue0_exportbundle;
  113623. extern vorbis_func_residue residue1_exportbundle;
  113624. extern vorbis_func_residue residue2_exportbundle;
  113625. extern vorbis_func_mapping mapping0_exportbundle;
  113626. vorbis_func_floor *_floor_P[]={
  113627. &floor0_exportbundle,
  113628. &floor1_exportbundle,
  113629. };
  113630. vorbis_func_residue *_residue_P[]={
  113631. &residue0_exportbundle,
  113632. &residue1_exportbundle,
  113633. &residue2_exportbundle,
  113634. };
  113635. vorbis_func_mapping *_mapping_P[]={
  113636. &mapping0_exportbundle,
  113637. };
  113638. #endif
  113639. /********* End of inlined file: registry.c *********/
  113640. /********* Start of inlined file: res0.c *********/
  113641. /* Slow, slow, slow, simpleminded and did I mention it was slow? The
  113642. encode/decode loops are coded for clarity and performance is not
  113643. yet even a nagging little idea lurking in the shadows. Oh and BTW,
  113644. it's slow. */
  113645. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  113646. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  113647. // tasks..
  113648. #ifdef _MSC_VER
  113649. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  113650. #endif
  113651. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  113652. #if JUCE_USE_OGGVORBIS
  113653. #include <stdlib.h>
  113654. #include <string.h>
  113655. #include <math.h>
  113656. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  113657. #include <stdio.h>
  113658. #endif
  113659. typedef struct {
  113660. vorbis_info_residue0 *info;
  113661. int parts;
  113662. int stages;
  113663. codebook *fullbooks;
  113664. codebook *phrasebook;
  113665. codebook ***partbooks;
  113666. int partvals;
  113667. int **decodemap;
  113668. long postbits;
  113669. long phrasebits;
  113670. long frames;
  113671. #if defined(TRAIN_RES) || defined(TRAIN_RESAUX)
  113672. int train_seq;
  113673. long *training_data[8][64];
  113674. float training_max[8][64];
  113675. float training_min[8][64];
  113676. float tmin;
  113677. float tmax;
  113678. #endif
  113679. } vorbis_look_residue0;
  113680. void res0_free_info(vorbis_info_residue *i){
  113681. vorbis_info_residue0 *info=(vorbis_info_residue0 *)i;
  113682. if(info){
  113683. memset(info,0,sizeof(*info));
  113684. _ogg_free(info);
  113685. }
  113686. }
  113687. void res0_free_look(vorbis_look_residue *i){
  113688. int j;
  113689. if(i){
  113690. vorbis_look_residue0 *look=(vorbis_look_residue0 *)i;
  113691. #ifdef TRAIN_RES
  113692. {
  113693. int j,k,l;
  113694. for(j=0;j<look->parts;j++){
  113695. /*fprintf(stderr,"partition %d: ",j);*/
  113696. for(k=0;k<8;k++)
  113697. if(look->training_data[k][j]){
  113698. char buffer[80];
  113699. FILE *of;
  113700. codebook *statebook=look->partbooks[j][k];
  113701. /* long and short into the same bucket by current convention */
  113702. sprintf(buffer,"res_part%d_pass%d.vqd",j,k);
  113703. of=fopen(buffer,"a");
  113704. for(l=0;l<statebook->entries;l++)
  113705. fprintf(of,"%d:%ld\n",l,look->training_data[k][j][l]);
  113706. fclose(of);
  113707. /*fprintf(stderr,"%d(%.2f|%.2f) ",k,
  113708. look->training_min[k][j],look->training_max[k][j]);*/
  113709. _ogg_free(look->training_data[k][j]);
  113710. look->training_data[k][j]=NULL;
  113711. }
  113712. /*fprintf(stderr,"\n");*/
  113713. }
  113714. }
  113715. fprintf(stderr,"min/max residue: %g::%g\n",look->tmin,look->tmax);
  113716. /*fprintf(stderr,"residue bit usage %f:%f (%f total)\n",
  113717. (float)look->phrasebits/look->frames,
  113718. (float)look->postbits/look->frames,
  113719. (float)(look->postbits+look->phrasebits)/look->frames);*/
  113720. #endif
  113721. /*vorbis_info_residue0 *info=look->info;
  113722. fprintf(stderr,
  113723. "%ld frames encoded in %ld phrasebits and %ld residue bits "
  113724. "(%g/frame) \n",look->frames,look->phrasebits,
  113725. look->resbitsflat,
  113726. (look->phrasebits+look->resbitsflat)/(float)look->frames);
  113727. for(j=0;j<look->parts;j++){
  113728. long acc=0;
  113729. fprintf(stderr,"\t[%d] == ",j);
  113730. for(k=0;k<look->stages;k++)
  113731. if((info->secondstages[j]>>k)&1){
  113732. fprintf(stderr,"%ld,",look->resbits[j][k]);
  113733. acc+=look->resbits[j][k];
  113734. }
  113735. fprintf(stderr,":: (%ld vals) %1.2fbits/sample\n",look->resvals[j],
  113736. acc?(float)acc/(look->resvals[j]*info->grouping):0);
  113737. }
  113738. fprintf(stderr,"\n");*/
  113739. for(j=0;j<look->parts;j++)
  113740. if(look->partbooks[j])_ogg_free(look->partbooks[j]);
  113741. _ogg_free(look->partbooks);
  113742. for(j=0;j<look->partvals;j++)
  113743. _ogg_free(look->decodemap[j]);
  113744. _ogg_free(look->decodemap);
  113745. memset(look,0,sizeof(*look));
  113746. _ogg_free(look);
  113747. }
  113748. }
  113749. static int icount(unsigned int v){
  113750. int ret=0;
  113751. while(v){
  113752. ret+=v&1;
  113753. v>>=1;
  113754. }
  113755. return(ret);
  113756. }
  113757. void res0_pack(vorbis_info_residue *vr,oggpack_buffer *opb){
  113758. vorbis_info_residue0 *info=(vorbis_info_residue0 *)vr;
  113759. int j,acc=0;
  113760. oggpack_write(opb,info->begin,24);
  113761. oggpack_write(opb,info->end,24);
  113762. oggpack_write(opb,info->grouping-1,24); /* residue vectors to group and
  113763. code with a partitioned book */
  113764. oggpack_write(opb,info->partitions-1,6); /* possible partition choices */
  113765. oggpack_write(opb,info->groupbook,8); /* group huffman book */
  113766. /* secondstages is a bitmask; as encoding progresses pass by pass, a
  113767. bitmask of one indicates this partition class has bits to write
  113768. this pass */
  113769. for(j=0;j<info->partitions;j++){
  113770. if(ilog(info->secondstages[j])>3){
  113771. /* yes, this is a minor hack due to not thinking ahead */
  113772. oggpack_write(opb,info->secondstages[j],3);
  113773. oggpack_write(opb,1,1);
  113774. oggpack_write(opb,info->secondstages[j]>>3,5);
  113775. }else
  113776. oggpack_write(opb,info->secondstages[j],4); /* trailing zero */
  113777. acc+=icount(info->secondstages[j]);
  113778. }
  113779. for(j=0;j<acc;j++)
  113780. oggpack_write(opb,info->booklist[j],8);
  113781. }
  113782. /* vorbis_info is for range checking */
  113783. vorbis_info_residue *res0_unpack(vorbis_info *vi,oggpack_buffer *opb){
  113784. int j,acc=0;
  113785. vorbis_info_residue0 *info=(vorbis_info_residue0*) _ogg_calloc(1,sizeof(*info));
  113786. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  113787. info->begin=oggpack_read(opb,24);
  113788. info->end=oggpack_read(opb,24);
  113789. info->grouping=oggpack_read(opb,24)+1;
  113790. info->partitions=oggpack_read(opb,6)+1;
  113791. info->groupbook=oggpack_read(opb,8);
  113792. for(j=0;j<info->partitions;j++){
  113793. int cascade=oggpack_read(opb,3);
  113794. if(oggpack_read(opb,1))
  113795. cascade|=(oggpack_read(opb,5)<<3);
  113796. info->secondstages[j]=cascade;
  113797. acc+=icount(cascade);
  113798. }
  113799. for(j=0;j<acc;j++)
  113800. info->booklist[j]=oggpack_read(opb,8);
  113801. if(info->groupbook>=ci->books)goto errout;
  113802. for(j=0;j<acc;j++)
  113803. if(info->booklist[j]>=ci->books)goto errout;
  113804. return(info);
  113805. errout:
  113806. res0_free_info(info);
  113807. return(NULL);
  113808. }
  113809. vorbis_look_residue *res0_look(vorbis_dsp_state *vd,
  113810. vorbis_info_residue *vr){
  113811. vorbis_info_residue0 *info=(vorbis_info_residue0 *)vr;
  113812. vorbis_look_residue0 *look=(vorbis_look_residue0 *)_ogg_calloc(1,sizeof(*look));
  113813. codec_setup_info *ci=(codec_setup_info*)vd->vi->codec_setup;
  113814. int j,k,acc=0;
  113815. int dim;
  113816. int maxstage=0;
  113817. look->info=info;
  113818. look->parts=info->partitions;
  113819. look->fullbooks=ci->fullbooks;
  113820. look->phrasebook=ci->fullbooks+info->groupbook;
  113821. dim=look->phrasebook->dim;
  113822. look->partbooks=(codebook***)_ogg_calloc(look->parts,sizeof(*look->partbooks));
  113823. for(j=0;j<look->parts;j++){
  113824. int stages=ilog(info->secondstages[j]);
  113825. if(stages){
  113826. if(stages>maxstage)maxstage=stages;
  113827. look->partbooks[j]=(codebook**) _ogg_calloc(stages,sizeof(*look->partbooks[j]));
  113828. for(k=0;k<stages;k++)
  113829. if(info->secondstages[j]&(1<<k)){
  113830. look->partbooks[j][k]=ci->fullbooks+info->booklist[acc++];
  113831. #ifdef TRAIN_RES
  113832. look->training_data[k][j]=_ogg_calloc(look->partbooks[j][k]->entries,
  113833. sizeof(***look->training_data));
  113834. #endif
  113835. }
  113836. }
  113837. }
  113838. look->partvals=rint(pow((float)look->parts,(float)dim));
  113839. look->stages=maxstage;
  113840. look->decodemap=(int**)_ogg_malloc(look->partvals*sizeof(*look->decodemap));
  113841. for(j=0;j<look->partvals;j++){
  113842. long val=j;
  113843. long mult=look->partvals/look->parts;
  113844. look->decodemap[j]=(int*)_ogg_malloc(dim*sizeof(*look->decodemap[j]));
  113845. for(k=0;k<dim;k++){
  113846. long deco=val/mult;
  113847. val-=deco*mult;
  113848. mult/=look->parts;
  113849. look->decodemap[j][k]=deco;
  113850. }
  113851. }
  113852. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  113853. {
  113854. static int train_seq=0;
  113855. look->train_seq=train_seq++;
  113856. }
  113857. #endif
  113858. return(look);
  113859. }
  113860. /* break an abstraction and copy some code for performance purposes */
  113861. static int local_book_besterror(codebook *book,float *a){
  113862. int dim=book->dim,i,k,o;
  113863. int best=0;
  113864. encode_aux_threshmatch *tt=book->c->thresh_tree;
  113865. /* find the quant val of each scalar */
  113866. for(k=0,o=dim;k<dim;++k){
  113867. float val=a[--o];
  113868. i=tt->threshvals>>1;
  113869. if(val<tt->quantthresh[i]){
  113870. if(val<tt->quantthresh[i-1]){
  113871. for(--i;i>0;--i)
  113872. if(val>=tt->quantthresh[i-1])
  113873. break;
  113874. }
  113875. }else{
  113876. for(++i;i<tt->threshvals-1;++i)
  113877. if(val<tt->quantthresh[i])break;
  113878. }
  113879. best=(best*tt->quantvals)+tt->quantmap[i];
  113880. }
  113881. /* regular lattices are easy :-) */
  113882. if(book->c->lengthlist[best]<=0){
  113883. const static_codebook *c=book->c;
  113884. int i,j;
  113885. float bestf=0.f;
  113886. float *e=book->valuelist;
  113887. best=-1;
  113888. for(i=0;i<book->entries;i++){
  113889. if(c->lengthlist[i]>0){
  113890. float thisx=0.f;
  113891. for(j=0;j<dim;j++){
  113892. float val=(e[j]-a[j]);
  113893. thisx+=val*val;
  113894. }
  113895. if(best==-1 || thisx<bestf){
  113896. bestf=thisx;
  113897. best=i;
  113898. }
  113899. }
  113900. e+=dim;
  113901. }
  113902. }
  113903. {
  113904. float *ptr=book->valuelist+best*dim;
  113905. for(i=0;i<dim;i++)
  113906. *a++ -= *ptr++;
  113907. }
  113908. return(best);
  113909. }
  113910. static int _encodepart(oggpack_buffer *opb,float *vec, int n,
  113911. codebook *book,long *acc){
  113912. int i,bits=0;
  113913. int dim=book->dim;
  113914. int step=n/dim;
  113915. for(i=0;i<step;i++){
  113916. int entry=local_book_besterror(book,vec+i*dim);
  113917. #ifdef TRAIN_RES
  113918. acc[entry]++;
  113919. #endif
  113920. bits+=vorbis_book_encode(book,entry,opb);
  113921. }
  113922. return(bits);
  113923. }
  113924. static long **_01class(vorbis_block *vb,vorbis_look_residue *vl,
  113925. float **in,int ch){
  113926. long i,j,k;
  113927. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  113928. vorbis_info_residue0 *info=look->info;
  113929. /* move all this setup out later */
  113930. int samples_per_partition=info->grouping;
  113931. int possible_partitions=info->partitions;
  113932. int n=info->end-info->begin;
  113933. int partvals=n/samples_per_partition;
  113934. long **partword=(long**)_vorbis_block_alloc(vb,ch*sizeof(*partword));
  113935. float scale=100./samples_per_partition;
  113936. /* we find the partition type for each partition of each
  113937. channel. We'll go back and do the interleaved encoding in a
  113938. bit. For now, clarity */
  113939. for(i=0;i<ch;i++){
  113940. partword[i]=(long*)_vorbis_block_alloc(vb,n/samples_per_partition*sizeof(*partword[i]));
  113941. memset(partword[i],0,n/samples_per_partition*sizeof(*partword[i]));
  113942. }
  113943. for(i=0;i<partvals;i++){
  113944. int offset=i*samples_per_partition+info->begin;
  113945. for(j=0;j<ch;j++){
  113946. float max=0.;
  113947. float ent=0.;
  113948. for(k=0;k<samples_per_partition;k++){
  113949. if(fabs(in[j][offset+k])>max)max=fabs(in[j][offset+k]);
  113950. ent+=fabs(rint(in[j][offset+k]));
  113951. }
  113952. ent*=scale;
  113953. for(k=0;k<possible_partitions-1;k++)
  113954. if(max<=info->classmetric1[k] &&
  113955. (info->classmetric2[k]<0 || (int)ent<info->classmetric2[k]))
  113956. break;
  113957. partword[j][i]=k;
  113958. }
  113959. }
  113960. #ifdef TRAIN_RESAUX
  113961. {
  113962. FILE *of;
  113963. char buffer[80];
  113964. for(i=0;i<ch;i++){
  113965. sprintf(buffer,"resaux_%d.vqd",look->train_seq);
  113966. of=fopen(buffer,"a");
  113967. for(j=0;j<partvals;j++)
  113968. fprintf(of,"%ld, ",partword[i][j]);
  113969. fprintf(of,"\n");
  113970. fclose(of);
  113971. }
  113972. }
  113973. #endif
  113974. look->frames++;
  113975. return(partword);
  113976. }
  113977. /* designed for stereo or other modes where the partition size is an
  113978. integer multiple of the number of channels encoded in the current
  113979. submap */
  113980. static long **_2class(vorbis_block *vb,vorbis_look_residue *vl,float **in,
  113981. int ch){
  113982. long i,j,k,l;
  113983. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  113984. vorbis_info_residue0 *info=look->info;
  113985. /* move all this setup out later */
  113986. int samples_per_partition=info->grouping;
  113987. int possible_partitions=info->partitions;
  113988. int n=info->end-info->begin;
  113989. int partvals=n/samples_per_partition;
  113990. long **partword=(long**)_vorbis_block_alloc(vb,sizeof(*partword));
  113991. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  113992. FILE *of;
  113993. char buffer[80];
  113994. #endif
  113995. partword[0]=(long*)_vorbis_block_alloc(vb,n*ch/samples_per_partition*sizeof(*partword[0]));
  113996. memset(partword[0],0,n*ch/samples_per_partition*sizeof(*partword[0]));
  113997. for(i=0,l=info->begin/ch;i<partvals;i++){
  113998. float magmax=0.f;
  113999. float angmax=0.f;
  114000. for(j=0;j<samples_per_partition;j+=ch){
  114001. if(fabs(in[0][l])>magmax)magmax=fabs(in[0][l]);
  114002. for(k=1;k<ch;k++)
  114003. if(fabs(in[k][l])>angmax)angmax=fabs(in[k][l]);
  114004. l++;
  114005. }
  114006. for(j=0;j<possible_partitions-1;j++)
  114007. if(magmax<=info->classmetric1[j] &&
  114008. angmax<=info->classmetric2[j])
  114009. break;
  114010. partword[0][i]=j;
  114011. }
  114012. #ifdef TRAIN_RESAUX
  114013. sprintf(buffer,"resaux_%d.vqd",look->train_seq);
  114014. of=fopen(buffer,"a");
  114015. for(i=0;i<partvals;i++)
  114016. fprintf(of,"%ld, ",partword[0][i]);
  114017. fprintf(of,"\n");
  114018. fclose(of);
  114019. #endif
  114020. look->frames++;
  114021. return(partword);
  114022. }
  114023. static int _01forward(oggpack_buffer *opb,
  114024. vorbis_block *vb,vorbis_look_residue *vl,
  114025. float **in,int ch,
  114026. long **partword,
  114027. int (*encode)(oggpack_buffer *,float *,int,
  114028. codebook *,long *)){
  114029. long i,j,k,s;
  114030. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  114031. vorbis_info_residue0 *info=look->info;
  114032. /* move all this setup out later */
  114033. int samples_per_partition=info->grouping;
  114034. int possible_partitions=info->partitions;
  114035. int partitions_per_word=look->phrasebook->dim;
  114036. int n=info->end-info->begin;
  114037. int partvals=n/samples_per_partition;
  114038. long resbits[128];
  114039. long resvals[128];
  114040. #ifdef TRAIN_RES
  114041. for(i=0;i<ch;i++)
  114042. for(j=info->begin;j<info->end;j++){
  114043. if(in[i][j]>look->tmax)look->tmax=in[i][j];
  114044. if(in[i][j]<look->tmin)look->tmin=in[i][j];
  114045. }
  114046. #endif
  114047. memset(resbits,0,sizeof(resbits));
  114048. memset(resvals,0,sizeof(resvals));
  114049. /* we code the partition words for each channel, then the residual
  114050. words for a partition per channel until we've written all the
  114051. residual words for that partition word. Then write the next
  114052. partition channel words... */
  114053. for(s=0;s<look->stages;s++){
  114054. for(i=0;i<partvals;){
  114055. /* first we encode a partition codeword for each channel */
  114056. if(s==0){
  114057. for(j=0;j<ch;j++){
  114058. long val=partword[j][i];
  114059. for(k=1;k<partitions_per_word;k++){
  114060. val*=possible_partitions;
  114061. if(i+k<partvals)
  114062. val+=partword[j][i+k];
  114063. }
  114064. /* training hack */
  114065. if(val<look->phrasebook->entries)
  114066. look->phrasebits+=vorbis_book_encode(look->phrasebook,val,opb);
  114067. #if 0 /*def TRAIN_RES*/
  114068. else
  114069. fprintf(stderr,"!");
  114070. #endif
  114071. }
  114072. }
  114073. /* now we encode interleaved residual values for the partitions */
  114074. for(k=0;k<partitions_per_word && i<partvals;k++,i++){
  114075. long offset=i*samples_per_partition+info->begin;
  114076. for(j=0;j<ch;j++){
  114077. if(s==0)resvals[partword[j][i]]+=samples_per_partition;
  114078. if(info->secondstages[partword[j][i]]&(1<<s)){
  114079. codebook *statebook=look->partbooks[partword[j][i]][s];
  114080. if(statebook){
  114081. int ret;
  114082. long *accumulator=NULL;
  114083. #ifdef TRAIN_RES
  114084. accumulator=look->training_data[s][partword[j][i]];
  114085. {
  114086. int l;
  114087. float *samples=in[j]+offset;
  114088. for(l=0;l<samples_per_partition;l++){
  114089. if(samples[l]<look->training_min[s][partword[j][i]])
  114090. look->training_min[s][partword[j][i]]=samples[l];
  114091. if(samples[l]>look->training_max[s][partword[j][i]])
  114092. look->training_max[s][partword[j][i]]=samples[l];
  114093. }
  114094. }
  114095. #endif
  114096. ret=encode(opb,in[j]+offset,samples_per_partition,
  114097. statebook,accumulator);
  114098. look->postbits+=ret;
  114099. resbits[partword[j][i]]+=ret;
  114100. }
  114101. }
  114102. }
  114103. }
  114104. }
  114105. }
  114106. /*{
  114107. long total=0;
  114108. long totalbits=0;
  114109. fprintf(stderr,"%d :: ",vb->mode);
  114110. for(k=0;k<possible_partitions;k++){
  114111. fprintf(stderr,"%ld/%1.2g, ",resvals[k],(float)resbits[k]/resvals[k]);
  114112. total+=resvals[k];
  114113. totalbits+=resbits[k];
  114114. }
  114115. fprintf(stderr,":: %ld:%1.2g\n",total,(double)totalbits/total);
  114116. }*/
  114117. return(0);
  114118. }
  114119. /* a truncated packet here just means 'stop working'; it's not an error */
  114120. static int _01inverse(vorbis_block *vb,vorbis_look_residue *vl,
  114121. float **in,int ch,
  114122. long (*decodepart)(codebook *, float *,
  114123. oggpack_buffer *,int)){
  114124. long i,j,k,l,s;
  114125. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  114126. vorbis_info_residue0 *info=look->info;
  114127. /* move all this setup out later */
  114128. int samples_per_partition=info->grouping;
  114129. int partitions_per_word=look->phrasebook->dim;
  114130. int n=info->end-info->begin;
  114131. int partvals=n/samples_per_partition;
  114132. int partwords=(partvals+partitions_per_word-1)/partitions_per_word;
  114133. int ***partword=(int***)alloca(ch*sizeof(*partword));
  114134. for(j=0;j<ch;j++)
  114135. partword[j]=(int**)_vorbis_block_alloc(vb,partwords*sizeof(*partword[j]));
  114136. for(s=0;s<look->stages;s++){
  114137. /* each loop decodes on partition codeword containing
  114138. partitions_pre_word partitions */
  114139. for(i=0,l=0;i<partvals;l++){
  114140. if(s==0){
  114141. /* fetch the partition word for each channel */
  114142. for(j=0;j<ch;j++){
  114143. int temp=vorbis_book_decode(look->phrasebook,&vb->opb);
  114144. if(temp==-1)goto eopbreak;
  114145. partword[j][l]=look->decodemap[temp];
  114146. if(partword[j][l]==NULL)goto errout;
  114147. }
  114148. }
  114149. /* now we decode residual values for the partitions */
  114150. for(k=0;k<partitions_per_word && i<partvals;k++,i++)
  114151. for(j=0;j<ch;j++){
  114152. long offset=info->begin+i*samples_per_partition;
  114153. if(info->secondstages[partword[j][l][k]]&(1<<s)){
  114154. codebook *stagebook=look->partbooks[partword[j][l][k]][s];
  114155. if(stagebook){
  114156. if(decodepart(stagebook,in[j]+offset,&vb->opb,
  114157. samples_per_partition)==-1)goto eopbreak;
  114158. }
  114159. }
  114160. }
  114161. }
  114162. }
  114163. errout:
  114164. eopbreak:
  114165. return(0);
  114166. }
  114167. #if 0
  114168. /* residue 0 and 1 are just slight variants of one another. 0 is
  114169. interleaved, 1 is not */
  114170. long **res0_class(vorbis_block *vb,vorbis_look_residue *vl,
  114171. float **in,int *nonzero,int ch){
  114172. /* we encode only the nonzero parts of a bundle */
  114173. int i,used=0;
  114174. for(i=0;i<ch;i++)
  114175. if(nonzero[i])
  114176. in[used++]=in[i];
  114177. if(used)
  114178. /*return(_01class(vb,vl,in,used,_interleaved_testhack));*/
  114179. return(_01class(vb,vl,in,used));
  114180. else
  114181. return(0);
  114182. }
  114183. int res0_forward(vorbis_block *vb,vorbis_look_residue *vl,
  114184. float **in,float **out,int *nonzero,int ch,
  114185. long **partword){
  114186. /* we encode only the nonzero parts of a bundle */
  114187. int i,j,used=0,n=vb->pcmend/2;
  114188. for(i=0;i<ch;i++)
  114189. if(nonzero[i]){
  114190. if(out)
  114191. for(j=0;j<n;j++)
  114192. out[i][j]+=in[i][j];
  114193. in[used++]=in[i];
  114194. }
  114195. if(used){
  114196. int ret=_01forward(vb,vl,in,used,partword,
  114197. _interleaved_encodepart);
  114198. if(out){
  114199. used=0;
  114200. for(i=0;i<ch;i++)
  114201. if(nonzero[i]){
  114202. for(j=0;j<n;j++)
  114203. out[i][j]-=in[used][j];
  114204. used++;
  114205. }
  114206. }
  114207. return(ret);
  114208. }else{
  114209. return(0);
  114210. }
  114211. }
  114212. #endif
  114213. int res0_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  114214. float **in,int *nonzero,int ch){
  114215. int i,used=0;
  114216. for(i=0;i<ch;i++)
  114217. if(nonzero[i])
  114218. in[used++]=in[i];
  114219. if(used)
  114220. return(_01inverse(vb,vl,in,used,vorbis_book_decodevs_add));
  114221. else
  114222. return(0);
  114223. }
  114224. int res1_forward(oggpack_buffer *opb,vorbis_block *vb,vorbis_look_residue *vl,
  114225. float **in,float **out,int *nonzero,int ch,
  114226. long **partword){
  114227. int i,j,used=0,n=vb->pcmend/2;
  114228. for(i=0;i<ch;i++)
  114229. if(nonzero[i]){
  114230. if(out)
  114231. for(j=0;j<n;j++)
  114232. out[i][j]+=in[i][j];
  114233. in[used++]=in[i];
  114234. }
  114235. if(used){
  114236. int ret=_01forward(opb,vb,vl,in,used,partword,_encodepart);
  114237. if(out){
  114238. used=0;
  114239. for(i=0;i<ch;i++)
  114240. if(nonzero[i]){
  114241. for(j=0;j<n;j++)
  114242. out[i][j]-=in[used][j];
  114243. used++;
  114244. }
  114245. }
  114246. return(ret);
  114247. }else{
  114248. return(0);
  114249. }
  114250. }
  114251. long **res1_class(vorbis_block *vb,vorbis_look_residue *vl,
  114252. float **in,int *nonzero,int ch){
  114253. int i,used=0;
  114254. for(i=0;i<ch;i++)
  114255. if(nonzero[i])
  114256. in[used++]=in[i];
  114257. if(used)
  114258. return(_01class(vb,vl,in,used));
  114259. else
  114260. return(0);
  114261. }
  114262. int res1_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  114263. float **in,int *nonzero,int ch){
  114264. int i,used=0;
  114265. for(i=0;i<ch;i++)
  114266. if(nonzero[i])
  114267. in[used++]=in[i];
  114268. if(used)
  114269. return(_01inverse(vb,vl,in,used,vorbis_book_decodev_add));
  114270. else
  114271. return(0);
  114272. }
  114273. long **res2_class(vorbis_block *vb,vorbis_look_residue *vl,
  114274. float **in,int *nonzero,int ch){
  114275. int i,used=0;
  114276. for(i=0;i<ch;i++)
  114277. if(nonzero[i])used++;
  114278. if(used)
  114279. return(_2class(vb,vl,in,ch));
  114280. else
  114281. return(0);
  114282. }
  114283. /* res2 is slightly more different; all the channels are interleaved
  114284. into a single vector and encoded. */
  114285. int res2_forward(oggpack_buffer *opb,
  114286. vorbis_block *vb,vorbis_look_residue *vl,
  114287. float **in,float **out,int *nonzero,int ch,
  114288. long **partword){
  114289. long i,j,k,n=vb->pcmend/2,used=0;
  114290. /* don't duplicate the code; use a working vector hack for now and
  114291. reshape ourselves into a single channel res1 */
  114292. /* ugly; reallocs for each coupling pass :-( */
  114293. float *work=(float*)_vorbis_block_alloc(vb,ch*n*sizeof(*work));
  114294. for(i=0;i<ch;i++){
  114295. float *pcm=in[i];
  114296. if(nonzero[i])used++;
  114297. for(j=0,k=i;j<n;j++,k+=ch)
  114298. work[k]=pcm[j];
  114299. }
  114300. if(used){
  114301. int ret=_01forward(opb,vb,vl,&work,1,partword,_encodepart);
  114302. /* update the sofar vector */
  114303. if(out){
  114304. for(i=0;i<ch;i++){
  114305. float *pcm=in[i];
  114306. float *sofar=out[i];
  114307. for(j=0,k=i;j<n;j++,k+=ch)
  114308. sofar[j]+=pcm[j]-work[k];
  114309. }
  114310. }
  114311. return(ret);
  114312. }else{
  114313. return(0);
  114314. }
  114315. }
  114316. /* duplicate code here as speed is somewhat more important */
  114317. int res2_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  114318. float **in,int *nonzero,int ch){
  114319. long i,k,l,s;
  114320. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  114321. vorbis_info_residue0 *info=look->info;
  114322. /* move all this setup out later */
  114323. int samples_per_partition=info->grouping;
  114324. int partitions_per_word=look->phrasebook->dim;
  114325. int n=info->end-info->begin;
  114326. int partvals=n/samples_per_partition;
  114327. int partwords=(partvals+partitions_per_word-1)/partitions_per_word;
  114328. int **partword=(int**)_vorbis_block_alloc(vb,partwords*sizeof(*partword));
  114329. for(i=0;i<ch;i++)if(nonzero[i])break;
  114330. if(i==ch)return(0); /* no nonzero vectors */
  114331. for(s=0;s<look->stages;s++){
  114332. for(i=0,l=0;i<partvals;l++){
  114333. if(s==0){
  114334. /* fetch the partition word */
  114335. int temp=vorbis_book_decode(look->phrasebook,&vb->opb);
  114336. if(temp==-1)goto eopbreak;
  114337. partword[l]=look->decodemap[temp];
  114338. if(partword[l]==NULL)goto errout;
  114339. }
  114340. /* now we decode residual values for the partitions */
  114341. for(k=0;k<partitions_per_word && i<partvals;k++,i++)
  114342. if(info->secondstages[partword[l][k]]&(1<<s)){
  114343. codebook *stagebook=look->partbooks[partword[l][k]][s];
  114344. if(stagebook){
  114345. if(vorbis_book_decodevv_add(stagebook,in,
  114346. i*samples_per_partition+info->begin,ch,
  114347. &vb->opb,samples_per_partition)==-1)
  114348. goto eopbreak;
  114349. }
  114350. }
  114351. }
  114352. }
  114353. errout:
  114354. eopbreak:
  114355. return(0);
  114356. }
  114357. vorbis_func_residue residue0_exportbundle={
  114358. NULL,
  114359. &res0_unpack,
  114360. &res0_look,
  114361. &res0_free_info,
  114362. &res0_free_look,
  114363. NULL,
  114364. NULL,
  114365. &res0_inverse
  114366. };
  114367. vorbis_func_residue residue1_exportbundle={
  114368. &res0_pack,
  114369. &res0_unpack,
  114370. &res0_look,
  114371. &res0_free_info,
  114372. &res0_free_look,
  114373. &res1_class,
  114374. &res1_forward,
  114375. &res1_inverse
  114376. };
  114377. vorbis_func_residue residue2_exportbundle={
  114378. &res0_pack,
  114379. &res0_unpack,
  114380. &res0_look,
  114381. &res0_free_info,
  114382. &res0_free_look,
  114383. &res2_class,
  114384. &res2_forward,
  114385. &res2_inverse
  114386. };
  114387. #endif
  114388. /********* End of inlined file: res0.c *********/
  114389. /********* Start of inlined file: sharedbook.c *********/
  114390. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  114391. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  114392. // tasks..
  114393. #ifdef _MSC_VER
  114394. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  114395. #endif
  114396. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  114397. #if JUCE_USE_OGGVORBIS
  114398. #include <stdlib.h>
  114399. #include <math.h>
  114400. #include <string.h>
  114401. /**** pack/unpack helpers ******************************************/
  114402. int _ilog(unsigned int v){
  114403. int ret=0;
  114404. while(v){
  114405. ret++;
  114406. v>>=1;
  114407. }
  114408. return(ret);
  114409. }
  114410. /* 32 bit float (not IEEE; nonnormalized mantissa +
  114411. biased exponent) : neeeeeee eeemmmmm mmmmmmmm mmmmmmmm
  114412. Why not IEEE? It's just not that important here. */
  114413. #define VQ_FEXP 10
  114414. #define VQ_FMAN 21
  114415. #define VQ_FEXP_BIAS 768 /* bias toward values smaller than 1. */
  114416. /* doesn't currently guard under/overflow */
  114417. long _float32_pack(float val){
  114418. int sign=0;
  114419. long exp;
  114420. long mant;
  114421. if(val<0){
  114422. sign=0x80000000;
  114423. val= -val;
  114424. }
  114425. exp= floor(log(val)/log(2.f));
  114426. mant=rint(ldexp(val,(VQ_FMAN-1)-exp));
  114427. exp=(exp+VQ_FEXP_BIAS)<<VQ_FMAN;
  114428. return(sign|exp|mant);
  114429. }
  114430. float _float32_unpack(long val){
  114431. double mant=val&0x1fffff;
  114432. int sign=val&0x80000000;
  114433. long exp =(val&0x7fe00000L)>>VQ_FMAN;
  114434. if(sign)mant= -mant;
  114435. return(ldexp(mant,exp-(VQ_FMAN-1)-VQ_FEXP_BIAS));
  114436. }
  114437. /* given a list of word lengths, generate a list of codewords. Works
  114438. for length ordered or unordered, always assigns the lowest valued
  114439. codewords first. Extended to handle unused entries (length 0) */
  114440. ogg_uint32_t *_make_words(long *l,long n,long sparsecount){
  114441. long i,j,count=0;
  114442. ogg_uint32_t marker[33];
  114443. ogg_uint32_t *r=(ogg_uint32_t*)_ogg_malloc((sparsecount?sparsecount:n)*sizeof(*r));
  114444. memset(marker,0,sizeof(marker));
  114445. for(i=0;i<n;i++){
  114446. long length=l[i];
  114447. if(length>0){
  114448. ogg_uint32_t entry=marker[length];
  114449. /* when we claim a node for an entry, we also claim the nodes
  114450. below it (pruning off the imagined tree that may have dangled
  114451. from it) as well as blocking the use of any nodes directly
  114452. above for leaves */
  114453. /* update ourself */
  114454. if(length<32 && (entry>>length)){
  114455. /* error condition; the lengths must specify an overpopulated tree */
  114456. _ogg_free(r);
  114457. return(NULL);
  114458. }
  114459. r[count++]=entry;
  114460. /* Look to see if the next shorter marker points to the node
  114461. above. if so, update it and repeat. */
  114462. {
  114463. for(j=length;j>0;j--){
  114464. if(marker[j]&1){
  114465. /* have to jump branches */
  114466. if(j==1)
  114467. marker[1]++;
  114468. else
  114469. marker[j]=marker[j-1]<<1;
  114470. break; /* invariant says next upper marker would already
  114471. have been moved if it was on the same path */
  114472. }
  114473. marker[j]++;
  114474. }
  114475. }
  114476. /* prune the tree; the implicit invariant says all the longer
  114477. markers were dangling from our just-taken node. Dangle them
  114478. from our *new* node. */
  114479. for(j=length+1;j<33;j++)
  114480. if((marker[j]>>1) == entry){
  114481. entry=marker[j];
  114482. marker[j]=marker[j-1]<<1;
  114483. }else
  114484. break;
  114485. }else
  114486. if(sparsecount==0)count++;
  114487. }
  114488. /* bitreverse the words because our bitwise packer/unpacker is LSb
  114489. endian */
  114490. for(i=0,count=0;i<n;i++){
  114491. ogg_uint32_t temp=0;
  114492. for(j=0;j<l[i];j++){
  114493. temp<<=1;
  114494. temp|=(r[count]>>j)&1;
  114495. }
  114496. if(sparsecount){
  114497. if(l[i])
  114498. r[count++]=temp;
  114499. }else
  114500. r[count++]=temp;
  114501. }
  114502. return(r);
  114503. }
  114504. /* there might be a straightforward one-line way to do the below
  114505. that's portable and totally safe against roundoff, but I haven't
  114506. thought of it. Therefore, we opt on the side of caution */
  114507. long _book_maptype1_quantvals(const static_codebook *b){
  114508. long vals=floor(pow((float)b->entries,1.f/b->dim));
  114509. /* the above *should* be reliable, but we'll not assume that FP is
  114510. ever reliable when bitstream sync is at stake; verify via integer
  114511. means that vals really is the greatest value of dim for which
  114512. vals^b->bim <= b->entries */
  114513. /* treat the above as an initial guess */
  114514. while(1){
  114515. long acc=1;
  114516. long acc1=1;
  114517. int i;
  114518. for(i=0;i<b->dim;i++){
  114519. acc*=vals;
  114520. acc1*=vals+1;
  114521. }
  114522. if(acc<=b->entries && acc1>b->entries){
  114523. return(vals);
  114524. }else{
  114525. if(acc>b->entries){
  114526. vals--;
  114527. }else{
  114528. vals++;
  114529. }
  114530. }
  114531. }
  114532. }
  114533. /* unpack the quantized list of values for encode/decode ***********/
  114534. /* we need to deal with two map types: in map type 1, the values are
  114535. generated algorithmically (each column of the vector counts through
  114536. the values in the quant vector). in map type 2, all the values came
  114537. in in an explicit list. Both value lists must be unpacked */
  114538. float *_book_unquantize(const static_codebook *b,int n,int *sparsemap){
  114539. long j,k,count=0;
  114540. if(b->maptype==1 || b->maptype==2){
  114541. int quantvals;
  114542. float mindel=_float32_unpack(b->q_min);
  114543. float delta=_float32_unpack(b->q_delta);
  114544. float *r=(float*)_ogg_calloc(n*b->dim,sizeof(*r));
  114545. /* maptype 1 and 2 both use a quantized value vector, but
  114546. different sizes */
  114547. switch(b->maptype){
  114548. case 1:
  114549. /* most of the time, entries%dimensions == 0, but we need to be
  114550. well defined. We define that the possible vales at each
  114551. scalar is values == entries/dim. If entries%dim != 0, we'll
  114552. have 'too few' values (values*dim<entries), which means that
  114553. we'll have 'left over' entries; left over entries use zeroed
  114554. values (and are wasted). So don't generate codebooks like
  114555. that */
  114556. quantvals=_book_maptype1_quantvals(b);
  114557. for(j=0;j<b->entries;j++){
  114558. if((sparsemap && b->lengthlist[j]) || !sparsemap){
  114559. float last=0.f;
  114560. int indexdiv=1;
  114561. for(k=0;k<b->dim;k++){
  114562. int index= (j/indexdiv)%quantvals;
  114563. float val=b->quantlist[index];
  114564. val=fabs(val)*delta+mindel+last;
  114565. if(b->q_sequencep)last=val;
  114566. if(sparsemap)
  114567. r[sparsemap[count]*b->dim+k]=val;
  114568. else
  114569. r[count*b->dim+k]=val;
  114570. indexdiv*=quantvals;
  114571. }
  114572. count++;
  114573. }
  114574. }
  114575. break;
  114576. case 2:
  114577. for(j=0;j<b->entries;j++){
  114578. if((sparsemap && b->lengthlist[j]) || !sparsemap){
  114579. float last=0.f;
  114580. for(k=0;k<b->dim;k++){
  114581. float val=b->quantlist[j*b->dim+k];
  114582. val=fabs(val)*delta+mindel+last;
  114583. if(b->q_sequencep)last=val;
  114584. if(sparsemap)
  114585. r[sparsemap[count]*b->dim+k]=val;
  114586. else
  114587. r[count*b->dim+k]=val;
  114588. }
  114589. count++;
  114590. }
  114591. }
  114592. break;
  114593. }
  114594. return(r);
  114595. }
  114596. return(NULL);
  114597. }
  114598. void vorbis_staticbook_clear(static_codebook *b){
  114599. if(b->allocedp){
  114600. if(b->quantlist)_ogg_free(b->quantlist);
  114601. if(b->lengthlist)_ogg_free(b->lengthlist);
  114602. if(b->nearest_tree){
  114603. _ogg_free(b->nearest_tree->ptr0);
  114604. _ogg_free(b->nearest_tree->ptr1);
  114605. _ogg_free(b->nearest_tree->p);
  114606. _ogg_free(b->nearest_tree->q);
  114607. memset(b->nearest_tree,0,sizeof(*b->nearest_tree));
  114608. _ogg_free(b->nearest_tree);
  114609. }
  114610. if(b->thresh_tree){
  114611. _ogg_free(b->thresh_tree->quantthresh);
  114612. _ogg_free(b->thresh_tree->quantmap);
  114613. memset(b->thresh_tree,0,sizeof(*b->thresh_tree));
  114614. _ogg_free(b->thresh_tree);
  114615. }
  114616. memset(b,0,sizeof(*b));
  114617. }
  114618. }
  114619. void vorbis_staticbook_destroy(static_codebook *b){
  114620. if(b->allocedp){
  114621. vorbis_staticbook_clear(b);
  114622. _ogg_free(b);
  114623. }
  114624. }
  114625. void vorbis_book_clear(codebook *b){
  114626. /* static book is not cleared; we're likely called on the lookup and
  114627. the static codebook belongs to the info struct */
  114628. if(b->valuelist)_ogg_free(b->valuelist);
  114629. if(b->codelist)_ogg_free(b->codelist);
  114630. if(b->dec_index)_ogg_free(b->dec_index);
  114631. if(b->dec_codelengths)_ogg_free(b->dec_codelengths);
  114632. if(b->dec_firsttable)_ogg_free(b->dec_firsttable);
  114633. memset(b,0,sizeof(*b));
  114634. }
  114635. int vorbis_book_init_encode(codebook *c,const static_codebook *s){
  114636. memset(c,0,sizeof(*c));
  114637. c->c=s;
  114638. c->entries=s->entries;
  114639. c->used_entries=s->entries;
  114640. c->dim=s->dim;
  114641. c->codelist=_make_words(s->lengthlist,s->entries,0);
  114642. c->valuelist=_book_unquantize(s,s->entries,NULL);
  114643. return(0);
  114644. }
  114645. static int sort32a(const void *a,const void *b){
  114646. return ( **(ogg_uint32_t **)a>**(ogg_uint32_t **)b)-
  114647. ( **(ogg_uint32_t **)a<**(ogg_uint32_t **)b);
  114648. }
  114649. /* decode codebook arrangement is more heavily optimized than encode */
  114650. int vorbis_book_init_decode(codebook *c,const static_codebook *s){
  114651. int i,j,n=0,tabn;
  114652. int *sortindex;
  114653. memset(c,0,sizeof(*c));
  114654. /* count actually used entries */
  114655. for(i=0;i<s->entries;i++)
  114656. if(s->lengthlist[i]>0)
  114657. n++;
  114658. c->entries=s->entries;
  114659. c->used_entries=n;
  114660. c->dim=s->dim;
  114661. /* two different remappings go on here.
  114662. First, we collapse the likely sparse codebook down only to
  114663. actually represented values/words. This collapsing needs to be
  114664. indexed as map-valueless books are used to encode original entry
  114665. positions as integers.
  114666. Second, we reorder all vectors, including the entry index above,
  114667. by sorted bitreversed codeword to allow treeless decode. */
  114668. {
  114669. /* perform sort */
  114670. ogg_uint32_t *codes=_make_words(s->lengthlist,s->entries,c->used_entries);
  114671. ogg_uint32_t **codep=(ogg_uint32_t**)alloca(sizeof(*codep)*n);
  114672. if(codes==NULL)goto err_out;
  114673. for(i=0;i<n;i++){
  114674. codes[i]=ogg_bitreverse(codes[i]);
  114675. codep[i]=codes+i;
  114676. }
  114677. qsort(codep,n,sizeof(*codep),sort32a);
  114678. sortindex=(int*)alloca(n*sizeof(*sortindex));
  114679. c->codelist=(ogg_uint32_t*)_ogg_malloc(n*sizeof(*c->codelist));
  114680. /* the index is a reverse index */
  114681. for(i=0;i<n;i++){
  114682. int position=codep[i]-codes;
  114683. sortindex[position]=i;
  114684. }
  114685. for(i=0;i<n;i++)
  114686. c->codelist[sortindex[i]]=codes[i];
  114687. _ogg_free(codes);
  114688. }
  114689. c->valuelist=_book_unquantize(s,n,sortindex);
  114690. c->dec_index=(int*)_ogg_malloc(n*sizeof(*c->dec_index));
  114691. for(n=0,i=0;i<s->entries;i++)
  114692. if(s->lengthlist[i]>0)
  114693. c->dec_index[sortindex[n++]]=i;
  114694. c->dec_codelengths=(char*)_ogg_malloc(n*sizeof(*c->dec_codelengths));
  114695. for(n=0,i=0;i<s->entries;i++)
  114696. if(s->lengthlist[i]>0)
  114697. c->dec_codelengths[sortindex[n++]]=s->lengthlist[i];
  114698. c->dec_firsttablen=_ilog(c->used_entries)-4; /* this is magic */
  114699. if(c->dec_firsttablen<5)c->dec_firsttablen=5;
  114700. if(c->dec_firsttablen>8)c->dec_firsttablen=8;
  114701. tabn=1<<c->dec_firsttablen;
  114702. c->dec_firsttable=(ogg_uint32_t*)_ogg_calloc(tabn,sizeof(*c->dec_firsttable));
  114703. c->dec_maxlength=0;
  114704. for(i=0;i<n;i++){
  114705. if(c->dec_maxlength<c->dec_codelengths[i])
  114706. c->dec_maxlength=c->dec_codelengths[i];
  114707. if(c->dec_codelengths[i]<=c->dec_firsttablen){
  114708. ogg_uint32_t orig=ogg_bitreverse(c->codelist[i]);
  114709. for(j=0;j<(1<<(c->dec_firsttablen-c->dec_codelengths[i]));j++)
  114710. c->dec_firsttable[orig|(j<<c->dec_codelengths[i])]=i+1;
  114711. }
  114712. }
  114713. /* now fill in 'unused' entries in the firsttable with hi/lo search
  114714. hints for the non-direct-hits */
  114715. {
  114716. ogg_uint32_t mask=0xfffffffeUL<<(31-c->dec_firsttablen);
  114717. long lo=0,hi=0;
  114718. for(i=0;i<tabn;i++){
  114719. ogg_uint32_t word=i<<(32-c->dec_firsttablen);
  114720. if(c->dec_firsttable[ogg_bitreverse(word)]==0){
  114721. while((lo+1)<n && c->codelist[lo+1]<=word)lo++;
  114722. while( hi<n && word>=(c->codelist[hi]&mask))hi++;
  114723. /* we only actually have 15 bits per hint to play with here.
  114724. In order to overflow gracefully (nothing breaks, efficiency
  114725. just drops), encode as the difference from the extremes. */
  114726. {
  114727. unsigned long loval=lo;
  114728. unsigned long hival=n-hi;
  114729. if(loval>0x7fff)loval=0x7fff;
  114730. if(hival>0x7fff)hival=0x7fff;
  114731. c->dec_firsttable[ogg_bitreverse(word)]=
  114732. 0x80000000UL | (loval<<15) | hival;
  114733. }
  114734. }
  114735. }
  114736. }
  114737. return(0);
  114738. err_out:
  114739. vorbis_book_clear(c);
  114740. return(-1);
  114741. }
  114742. static float _dist(int el,float *ref, float *b,int step){
  114743. int i;
  114744. float acc=0.f;
  114745. for(i=0;i<el;i++){
  114746. float val=(ref[i]-b[i*step]);
  114747. acc+=val*val;
  114748. }
  114749. return(acc);
  114750. }
  114751. int _best(codebook *book, float *a, int step){
  114752. encode_aux_threshmatch *tt=book->c->thresh_tree;
  114753. #if 0
  114754. encode_aux_nearestmatch *nt=book->c->nearest_tree;
  114755. encode_aux_pigeonhole *pt=book->c->pigeon_tree;
  114756. #endif
  114757. int dim=book->dim;
  114758. int k,o;
  114759. /*int savebest=-1;
  114760. float saverr;*/
  114761. /* do we have a threshhold encode hint? */
  114762. if(tt){
  114763. int index=0,i;
  114764. /* find the quant val of each scalar */
  114765. for(k=0,o=step*(dim-1);k<dim;k++,o-=step){
  114766. i=tt->threshvals>>1;
  114767. if(a[o]<tt->quantthresh[i]){
  114768. for(;i>0;i--)
  114769. if(a[o]>=tt->quantthresh[i-1])
  114770. break;
  114771. }else{
  114772. for(i++;i<tt->threshvals-1;i++)
  114773. if(a[o]<tt->quantthresh[i])break;
  114774. }
  114775. index=(index*tt->quantvals)+tt->quantmap[i];
  114776. }
  114777. /* regular lattices are easy :-) */
  114778. if(book->c->lengthlist[index]>0) /* is this unused? If so, we'll
  114779. use a decision tree after all
  114780. and fall through*/
  114781. return(index);
  114782. }
  114783. #if 0
  114784. /* do we have a pigeonhole encode hint? */
  114785. if(pt){
  114786. const static_codebook *c=book->c;
  114787. int i,besti=-1;
  114788. float best=0.f;
  114789. int entry=0;
  114790. /* dealing with sequentialness is a pain in the ass */
  114791. if(c->q_sequencep){
  114792. int pv;
  114793. long mul=1;
  114794. float qlast=0;
  114795. for(k=0,o=0;k<dim;k++,o+=step){
  114796. pv=(int)((a[o]-qlast-pt->min)/pt->del);
  114797. if(pv<0 || pv>=pt->mapentries)break;
  114798. entry+=pt->pigeonmap[pv]*mul;
  114799. mul*=pt->quantvals;
  114800. qlast+=pv*pt->del+pt->min;
  114801. }
  114802. }else{
  114803. for(k=0,o=step*(dim-1);k<dim;k++,o-=step){
  114804. int pv=(int)((a[o]-pt->min)/pt->del);
  114805. if(pv<0 || pv>=pt->mapentries)break;
  114806. entry=entry*pt->quantvals+pt->pigeonmap[pv];
  114807. }
  114808. }
  114809. /* must be within the pigeonholable range; if we quant outside (or
  114810. in an entry that we define no list for), brute force it */
  114811. if(k==dim && pt->fitlength[entry]){
  114812. /* search the abbreviated list */
  114813. long *list=pt->fitlist+pt->fitmap[entry];
  114814. for(i=0;i<pt->fitlength[entry];i++){
  114815. float this=_dist(dim,book->valuelist+list[i]*dim,a,step);
  114816. if(besti==-1 || this<best){
  114817. best=this;
  114818. besti=list[i];
  114819. }
  114820. }
  114821. return(besti);
  114822. }
  114823. }
  114824. if(nt){
  114825. /* optimized using the decision tree */
  114826. while(1){
  114827. float c=0.f;
  114828. float *p=book->valuelist+nt->p[ptr];
  114829. float *q=book->valuelist+nt->q[ptr];
  114830. for(k=0,o=0;k<dim;k++,o+=step)
  114831. c+=(p[k]-q[k])*(a[o]-(p[k]+q[k])*.5);
  114832. if(c>0.f) /* in A */
  114833. ptr= -nt->ptr0[ptr];
  114834. else /* in B */
  114835. ptr= -nt->ptr1[ptr];
  114836. if(ptr<=0)break;
  114837. }
  114838. return(-ptr);
  114839. }
  114840. #endif
  114841. /* brute force it! */
  114842. {
  114843. const static_codebook *c=book->c;
  114844. int i,besti=-1;
  114845. float best=0.f;
  114846. float *e=book->valuelist;
  114847. for(i=0;i<book->entries;i++){
  114848. if(c->lengthlist[i]>0){
  114849. float thisx=_dist(dim,e,a,step);
  114850. if(besti==-1 || thisx<best){
  114851. best=thisx;
  114852. besti=i;
  114853. }
  114854. }
  114855. e+=dim;
  114856. }
  114857. /*if(savebest!=-1 && savebest!=besti){
  114858. fprintf(stderr,"brute force/pigeonhole disagreement:\n"
  114859. "original:");
  114860. for(i=0;i<dim*step;i+=step)fprintf(stderr,"%g,",a[i]);
  114861. fprintf(stderr,"\n"
  114862. "pigeonhole (entry %d, err %g):",savebest,saverr);
  114863. for(i=0;i<dim;i++)fprintf(stderr,"%g,",
  114864. (book->valuelist+savebest*dim)[i]);
  114865. fprintf(stderr,"\n"
  114866. "bruteforce (entry %d, err %g):",besti,best);
  114867. for(i=0;i<dim;i++)fprintf(stderr,"%g,",
  114868. (book->valuelist+besti*dim)[i]);
  114869. fprintf(stderr,"\n");
  114870. }*/
  114871. return(besti);
  114872. }
  114873. }
  114874. long vorbis_book_codeword(codebook *book,int entry){
  114875. if(book->c) /* only use with encode; decode optimizations are
  114876. allowed to break this */
  114877. return book->codelist[entry];
  114878. return -1;
  114879. }
  114880. long vorbis_book_codelen(codebook *book,int entry){
  114881. if(book->c) /* only use with encode; decode optimizations are
  114882. allowed to break this */
  114883. return book->c->lengthlist[entry];
  114884. return -1;
  114885. }
  114886. #ifdef _V_SELFTEST
  114887. /* Unit tests of the dequantizer; this stuff will be OK
  114888. cross-platform, I simply want to be sure that special mapping cases
  114889. actually work properly; a bug could go unnoticed for a while */
  114890. #include <stdio.h>
  114891. /* cases:
  114892. no mapping
  114893. full, explicit mapping
  114894. algorithmic mapping
  114895. nonsequential
  114896. sequential
  114897. */
  114898. static long full_quantlist1[]={0,1,2,3, 4,5,6,7, 8,3,6,1};
  114899. static long partial_quantlist1[]={0,7,2};
  114900. /* no mapping */
  114901. static_codebook test1={
  114902. 4,16,
  114903. NULL,
  114904. 0,
  114905. 0,0,0,0,
  114906. NULL,
  114907. NULL,NULL
  114908. };
  114909. static float *test1_result=NULL;
  114910. /* linear, full mapping, nonsequential */
  114911. static_codebook test2={
  114912. 4,3,
  114913. NULL,
  114914. 2,
  114915. -533200896,1611661312,4,0,
  114916. full_quantlist1,
  114917. NULL,NULL
  114918. };
  114919. static float test2_result[]={-3,-2,-1,0, 1,2,3,4, 5,0,3,-2};
  114920. /* linear, full mapping, sequential */
  114921. static_codebook test3={
  114922. 4,3,
  114923. NULL,
  114924. 2,
  114925. -533200896,1611661312,4,1,
  114926. full_quantlist1,
  114927. NULL,NULL
  114928. };
  114929. static float test3_result[]={-3,-5,-6,-6, 1,3,6,10, 5,5,8,6};
  114930. /* linear, algorithmic mapping, nonsequential */
  114931. static_codebook test4={
  114932. 3,27,
  114933. NULL,
  114934. 1,
  114935. -533200896,1611661312,4,0,
  114936. partial_quantlist1,
  114937. NULL,NULL
  114938. };
  114939. static float test4_result[]={-3,-3,-3, 4,-3,-3, -1,-3,-3,
  114940. -3, 4,-3, 4, 4,-3, -1, 4,-3,
  114941. -3,-1,-3, 4,-1,-3, -1,-1,-3,
  114942. -3,-3, 4, 4,-3, 4, -1,-3, 4,
  114943. -3, 4, 4, 4, 4, 4, -1, 4, 4,
  114944. -3,-1, 4, 4,-1, 4, -1,-1, 4,
  114945. -3,-3,-1, 4,-3,-1, -1,-3,-1,
  114946. -3, 4,-1, 4, 4,-1, -1, 4,-1,
  114947. -3,-1,-1, 4,-1,-1, -1,-1,-1};
  114948. /* linear, algorithmic mapping, sequential */
  114949. static_codebook test5={
  114950. 3,27,
  114951. NULL,
  114952. 1,
  114953. -533200896,1611661312,4,1,
  114954. partial_quantlist1,
  114955. NULL,NULL
  114956. };
  114957. static float test5_result[]={-3,-6,-9, 4, 1,-2, -1,-4,-7,
  114958. -3, 1,-2, 4, 8, 5, -1, 3, 0,
  114959. -3,-4,-7, 4, 3, 0, -1,-2,-5,
  114960. -3,-6,-2, 4, 1, 5, -1,-4, 0,
  114961. -3, 1, 5, 4, 8,12, -1, 3, 7,
  114962. -3,-4, 0, 4, 3, 7, -1,-2, 2,
  114963. -3,-6,-7, 4, 1, 0, -1,-4,-5,
  114964. -3, 1, 0, 4, 8, 7, -1, 3, 2,
  114965. -3,-4,-5, 4, 3, 2, -1,-2,-3};
  114966. void run_test(static_codebook *b,float *comp){
  114967. float *out=_book_unquantize(b,b->entries,NULL);
  114968. int i;
  114969. if(comp){
  114970. if(!out){
  114971. fprintf(stderr,"_book_unquantize incorrectly returned NULL\n");
  114972. exit(1);
  114973. }
  114974. for(i=0;i<b->entries*b->dim;i++)
  114975. if(fabs(out[i]-comp[i])>.0001){
  114976. fprintf(stderr,"disagreement in unquantized and reference data:\n"
  114977. "position %d, %g != %g\n",i,out[i],comp[i]);
  114978. exit(1);
  114979. }
  114980. }else{
  114981. if(out){
  114982. fprintf(stderr,"_book_unquantize returned a value array: \n"
  114983. " correct result should have been NULL\n");
  114984. exit(1);
  114985. }
  114986. }
  114987. }
  114988. int main(){
  114989. /* run the nine dequant tests, and compare to the hand-rolled results */
  114990. fprintf(stderr,"Dequant test 1... ");
  114991. run_test(&test1,test1_result);
  114992. fprintf(stderr,"OK\nDequant test 2... ");
  114993. run_test(&test2,test2_result);
  114994. fprintf(stderr,"OK\nDequant test 3... ");
  114995. run_test(&test3,test3_result);
  114996. fprintf(stderr,"OK\nDequant test 4... ");
  114997. run_test(&test4,test4_result);
  114998. fprintf(stderr,"OK\nDequant test 5... ");
  114999. run_test(&test5,test5_result);
  115000. fprintf(stderr,"OK\n\n");
  115001. return(0);
  115002. }
  115003. #endif
  115004. #endif
  115005. /********* End of inlined file: sharedbook.c *********/
  115006. /********* Start of inlined file: smallft.c *********/
  115007. /* FFT implementation from OggSquish, minus cosine transforms,
  115008. * minus all but radix 2/4 case. In Vorbis we only need this
  115009. * cut-down version.
  115010. *
  115011. * To do more than just power-of-two sized vectors, see the full
  115012. * version I wrote for NetLib.
  115013. *
  115014. * Note that the packing is a little strange; rather than the FFT r/i
  115015. * packing following R_0, I_n, R_1, I_1, R_2, I_2 ... R_n-1, I_n-1,
  115016. * it follows R_0, R_1, I_1, R_2, I_2 ... R_n-1, I_n-1, I_n like the
  115017. * FORTRAN version
  115018. */
  115019. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  115020. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  115021. // tasks..
  115022. #ifdef _MSC_VER
  115023. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  115024. #endif
  115025. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  115026. #if JUCE_USE_OGGVORBIS
  115027. #include <stdlib.h>
  115028. #include <string.h>
  115029. #include <math.h>
  115030. static void drfti1(int n, float *wa, int *ifac){
  115031. static int ntryh[4] = { 4,2,3,5 };
  115032. static float tpi = 6.28318530717958648f;
  115033. float arg,argh,argld,fi;
  115034. int ntry=0,i,j=-1;
  115035. int k1, l1, l2, ib;
  115036. int ld, ii, ip, is, nq, nr;
  115037. int ido, ipm, nfm1;
  115038. int nl=n;
  115039. int nf=0;
  115040. L101:
  115041. j++;
  115042. if (j < 4)
  115043. ntry=ntryh[j];
  115044. else
  115045. ntry+=2;
  115046. L104:
  115047. nq=nl/ntry;
  115048. nr=nl-ntry*nq;
  115049. if (nr!=0) goto L101;
  115050. nf++;
  115051. ifac[nf+1]=ntry;
  115052. nl=nq;
  115053. if(ntry!=2)goto L107;
  115054. if(nf==1)goto L107;
  115055. for (i=1;i<nf;i++){
  115056. ib=nf-i+1;
  115057. ifac[ib+1]=ifac[ib];
  115058. }
  115059. ifac[2] = 2;
  115060. L107:
  115061. if(nl!=1)goto L104;
  115062. ifac[0]=n;
  115063. ifac[1]=nf;
  115064. argh=tpi/n;
  115065. is=0;
  115066. nfm1=nf-1;
  115067. l1=1;
  115068. if(nfm1==0)return;
  115069. for (k1=0;k1<nfm1;k1++){
  115070. ip=ifac[k1+2];
  115071. ld=0;
  115072. l2=l1*ip;
  115073. ido=n/l2;
  115074. ipm=ip-1;
  115075. for (j=0;j<ipm;j++){
  115076. ld+=l1;
  115077. i=is;
  115078. argld=(float)ld*argh;
  115079. fi=0.f;
  115080. for (ii=2;ii<ido;ii+=2){
  115081. fi+=1.f;
  115082. arg=fi*argld;
  115083. wa[i++]=cos(arg);
  115084. wa[i++]=sin(arg);
  115085. }
  115086. is+=ido;
  115087. }
  115088. l1=l2;
  115089. }
  115090. }
  115091. static void fdrffti(int n, float *wsave, int *ifac){
  115092. if (n == 1) return;
  115093. drfti1(n, wsave+n, ifac);
  115094. }
  115095. static void dradf2(int ido,int l1,float *cc,float *ch,float *wa1){
  115096. int i,k;
  115097. float ti2,tr2;
  115098. int t0,t1,t2,t3,t4,t5,t6;
  115099. t1=0;
  115100. t0=(t2=l1*ido);
  115101. t3=ido<<1;
  115102. for(k=0;k<l1;k++){
  115103. ch[t1<<1]=cc[t1]+cc[t2];
  115104. ch[(t1<<1)+t3-1]=cc[t1]-cc[t2];
  115105. t1+=ido;
  115106. t2+=ido;
  115107. }
  115108. if(ido<2)return;
  115109. if(ido==2)goto L105;
  115110. t1=0;
  115111. t2=t0;
  115112. for(k=0;k<l1;k++){
  115113. t3=t2;
  115114. t4=(t1<<1)+(ido<<1);
  115115. t5=t1;
  115116. t6=t1+t1;
  115117. for(i=2;i<ido;i+=2){
  115118. t3+=2;
  115119. t4-=2;
  115120. t5+=2;
  115121. t6+=2;
  115122. tr2=wa1[i-2]*cc[t3-1]+wa1[i-1]*cc[t3];
  115123. ti2=wa1[i-2]*cc[t3]-wa1[i-1]*cc[t3-1];
  115124. ch[t6]=cc[t5]+ti2;
  115125. ch[t4]=ti2-cc[t5];
  115126. ch[t6-1]=cc[t5-1]+tr2;
  115127. ch[t4-1]=cc[t5-1]-tr2;
  115128. }
  115129. t1+=ido;
  115130. t2+=ido;
  115131. }
  115132. if(ido%2==1)return;
  115133. L105:
  115134. t3=(t2=(t1=ido)-1);
  115135. t2+=t0;
  115136. for(k=0;k<l1;k++){
  115137. ch[t1]=-cc[t2];
  115138. ch[t1-1]=cc[t3];
  115139. t1+=ido<<1;
  115140. t2+=ido;
  115141. t3+=ido;
  115142. }
  115143. }
  115144. static void dradf4(int ido,int l1,float *cc,float *ch,float *wa1,
  115145. float *wa2,float *wa3){
  115146. static float hsqt2 = .70710678118654752f;
  115147. int i,k,t0,t1,t2,t3,t4,t5,t6;
  115148. float ci2,ci3,ci4,cr2,cr3,cr4,ti1,ti2,ti3,ti4,tr1,tr2,tr3,tr4;
  115149. t0=l1*ido;
  115150. t1=t0;
  115151. t4=t1<<1;
  115152. t2=t1+(t1<<1);
  115153. t3=0;
  115154. for(k=0;k<l1;k++){
  115155. tr1=cc[t1]+cc[t2];
  115156. tr2=cc[t3]+cc[t4];
  115157. ch[t5=t3<<2]=tr1+tr2;
  115158. ch[(ido<<2)+t5-1]=tr2-tr1;
  115159. ch[(t5+=(ido<<1))-1]=cc[t3]-cc[t4];
  115160. ch[t5]=cc[t2]-cc[t1];
  115161. t1+=ido;
  115162. t2+=ido;
  115163. t3+=ido;
  115164. t4+=ido;
  115165. }
  115166. if(ido<2)return;
  115167. if(ido==2)goto L105;
  115168. t1=0;
  115169. for(k=0;k<l1;k++){
  115170. t2=t1;
  115171. t4=t1<<2;
  115172. t5=(t6=ido<<1)+t4;
  115173. for(i=2;i<ido;i+=2){
  115174. t3=(t2+=2);
  115175. t4+=2;
  115176. t5-=2;
  115177. t3+=t0;
  115178. cr2=wa1[i-2]*cc[t3-1]+wa1[i-1]*cc[t3];
  115179. ci2=wa1[i-2]*cc[t3]-wa1[i-1]*cc[t3-1];
  115180. t3+=t0;
  115181. cr3=wa2[i-2]*cc[t3-1]+wa2[i-1]*cc[t3];
  115182. ci3=wa2[i-2]*cc[t3]-wa2[i-1]*cc[t3-1];
  115183. t3+=t0;
  115184. cr4=wa3[i-2]*cc[t3-1]+wa3[i-1]*cc[t3];
  115185. ci4=wa3[i-2]*cc[t3]-wa3[i-1]*cc[t3-1];
  115186. tr1=cr2+cr4;
  115187. tr4=cr4-cr2;
  115188. ti1=ci2+ci4;
  115189. ti4=ci2-ci4;
  115190. ti2=cc[t2]+ci3;
  115191. ti3=cc[t2]-ci3;
  115192. tr2=cc[t2-1]+cr3;
  115193. tr3=cc[t2-1]-cr3;
  115194. ch[t4-1]=tr1+tr2;
  115195. ch[t4]=ti1+ti2;
  115196. ch[t5-1]=tr3-ti4;
  115197. ch[t5]=tr4-ti3;
  115198. ch[t4+t6-1]=ti4+tr3;
  115199. ch[t4+t6]=tr4+ti3;
  115200. ch[t5+t6-1]=tr2-tr1;
  115201. ch[t5+t6]=ti1-ti2;
  115202. }
  115203. t1+=ido;
  115204. }
  115205. if(ido&1)return;
  115206. L105:
  115207. t2=(t1=t0+ido-1)+(t0<<1);
  115208. t3=ido<<2;
  115209. t4=ido;
  115210. t5=ido<<1;
  115211. t6=ido;
  115212. for(k=0;k<l1;k++){
  115213. ti1=-hsqt2*(cc[t1]+cc[t2]);
  115214. tr1=hsqt2*(cc[t1]-cc[t2]);
  115215. ch[t4-1]=tr1+cc[t6-1];
  115216. ch[t4+t5-1]=cc[t6-1]-tr1;
  115217. ch[t4]=ti1-cc[t1+t0];
  115218. ch[t4+t5]=ti1+cc[t1+t0];
  115219. t1+=ido;
  115220. t2+=ido;
  115221. t4+=t3;
  115222. t6+=ido;
  115223. }
  115224. }
  115225. static void dradfg(int ido,int ip,int l1,int idl1,float *cc,float *c1,
  115226. float *c2,float *ch,float *ch2,float *wa){
  115227. static float tpi=6.283185307179586f;
  115228. int idij,ipph,i,j,k,l,ic,ik,is;
  115229. int t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10;
  115230. float dc2,ai1,ai2,ar1,ar2,ds2;
  115231. int nbd;
  115232. float dcp,arg,dsp,ar1h,ar2h;
  115233. int idp2,ipp2;
  115234. arg=tpi/(float)ip;
  115235. dcp=cos(arg);
  115236. dsp=sin(arg);
  115237. ipph=(ip+1)>>1;
  115238. ipp2=ip;
  115239. idp2=ido;
  115240. nbd=(ido-1)>>1;
  115241. t0=l1*ido;
  115242. t10=ip*ido;
  115243. if(ido==1)goto L119;
  115244. for(ik=0;ik<idl1;ik++)ch2[ik]=c2[ik];
  115245. t1=0;
  115246. for(j=1;j<ip;j++){
  115247. t1+=t0;
  115248. t2=t1;
  115249. for(k=0;k<l1;k++){
  115250. ch[t2]=c1[t2];
  115251. t2+=ido;
  115252. }
  115253. }
  115254. is=-ido;
  115255. t1=0;
  115256. if(nbd>l1){
  115257. for(j=1;j<ip;j++){
  115258. t1+=t0;
  115259. is+=ido;
  115260. t2= -ido+t1;
  115261. for(k=0;k<l1;k++){
  115262. idij=is-1;
  115263. t2+=ido;
  115264. t3=t2;
  115265. for(i=2;i<ido;i+=2){
  115266. idij+=2;
  115267. t3+=2;
  115268. ch[t3-1]=wa[idij-1]*c1[t3-1]+wa[idij]*c1[t3];
  115269. ch[t3]=wa[idij-1]*c1[t3]-wa[idij]*c1[t3-1];
  115270. }
  115271. }
  115272. }
  115273. }else{
  115274. for(j=1;j<ip;j++){
  115275. is+=ido;
  115276. idij=is-1;
  115277. t1+=t0;
  115278. t2=t1;
  115279. for(i=2;i<ido;i+=2){
  115280. idij+=2;
  115281. t2+=2;
  115282. t3=t2;
  115283. for(k=0;k<l1;k++){
  115284. ch[t3-1]=wa[idij-1]*c1[t3-1]+wa[idij]*c1[t3];
  115285. ch[t3]=wa[idij-1]*c1[t3]-wa[idij]*c1[t3-1];
  115286. t3+=ido;
  115287. }
  115288. }
  115289. }
  115290. }
  115291. t1=0;
  115292. t2=ipp2*t0;
  115293. if(nbd<l1){
  115294. for(j=1;j<ipph;j++){
  115295. t1+=t0;
  115296. t2-=t0;
  115297. t3=t1;
  115298. t4=t2;
  115299. for(i=2;i<ido;i+=2){
  115300. t3+=2;
  115301. t4+=2;
  115302. t5=t3-ido;
  115303. t6=t4-ido;
  115304. for(k=0;k<l1;k++){
  115305. t5+=ido;
  115306. t6+=ido;
  115307. c1[t5-1]=ch[t5-1]+ch[t6-1];
  115308. c1[t6-1]=ch[t5]-ch[t6];
  115309. c1[t5]=ch[t5]+ch[t6];
  115310. c1[t6]=ch[t6-1]-ch[t5-1];
  115311. }
  115312. }
  115313. }
  115314. }else{
  115315. for(j=1;j<ipph;j++){
  115316. t1+=t0;
  115317. t2-=t0;
  115318. t3=t1;
  115319. t4=t2;
  115320. for(k=0;k<l1;k++){
  115321. t5=t3;
  115322. t6=t4;
  115323. for(i=2;i<ido;i+=2){
  115324. t5+=2;
  115325. t6+=2;
  115326. c1[t5-1]=ch[t5-1]+ch[t6-1];
  115327. c1[t6-1]=ch[t5]-ch[t6];
  115328. c1[t5]=ch[t5]+ch[t6];
  115329. c1[t6]=ch[t6-1]-ch[t5-1];
  115330. }
  115331. t3+=ido;
  115332. t4+=ido;
  115333. }
  115334. }
  115335. }
  115336. L119:
  115337. for(ik=0;ik<idl1;ik++)c2[ik]=ch2[ik];
  115338. t1=0;
  115339. t2=ipp2*idl1;
  115340. for(j=1;j<ipph;j++){
  115341. t1+=t0;
  115342. t2-=t0;
  115343. t3=t1-ido;
  115344. t4=t2-ido;
  115345. for(k=0;k<l1;k++){
  115346. t3+=ido;
  115347. t4+=ido;
  115348. c1[t3]=ch[t3]+ch[t4];
  115349. c1[t4]=ch[t4]-ch[t3];
  115350. }
  115351. }
  115352. ar1=1.f;
  115353. ai1=0.f;
  115354. t1=0;
  115355. t2=ipp2*idl1;
  115356. t3=(ip-1)*idl1;
  115357. for(l=1;l<ipph;l++){
  115358. t1+=idl1;
  115359. t2-=idl1;
  115360. ar1h=dcp*ar1-dsp*ai1;
  115361. ai1=dcp*ai1+dsp*ar1;
  115362. ar1=ar1h;
  115363. t4=t1;
  115364. t5=t2;
  115365. t6=t3;
  115366. t7=idl1;
  115367. for(ik=0;ik<idl1;ik++){
  115368. ch2[t4++]=c2[ik]+ar1*c2[t7++];
  115369. ch2[t5++]=ai1*c2[t6++];
  115370. }
  115371. dc2=ar1;
  115372. ds2=ai1;
  115373. ar2=ar1;
  115374. ai2=ai1;
  115375. t4=idl1;
  115376. t5=(ipp2-1)*idl1;
  115377. for(j=2;j<ipph;j++){
  115378. t4+=idl1;
  115379. t5-=idl1;
  115380. ar2h=dc2*ar2-ds2*ai2;
  115381. ai2=dc2*ai2+ds2*ar2;
  115382. ar2=ar2h;
  115383. t6=t1;
  115384. t7=t2;
  115385. t8=t4;
  115386. t9=t5;
  115387. for(ik=0;ik<idl1;ik++){
  115388. ch2[t6++]+=ar2*c2[t8++];
  115389. ch2[t7++]+=ai2*c2[t9++];
  115390. }
  115391. }
  115392. }
  115393. t1=0;
  115394. for(j=1;j<ipph;j++){
  115395. t1+=idl1;
  115396. t2=t1;
  115397. for(ik=0;ik<idl1;ik++)ch2[ik]+=c2[t2++];
  115398. }
  115399. if(ido<l1)goto L132;
  115400. t1=0;
  115401. t2=0;
  115402. for(k=0;k<l1;k++){
  115403. t3=t1;
  115404. t4=t2;
  115405. for(i=0;i<ido;i++)cc[t4++]=ch[t3++];
  115406. t1+=ido;
  115407. t2+=t10;
  115408. }
  115409. goto L135;
  115410. L132:
  115411. for(i=0;i<ido;i++){
  115412. t1=i;
  115413. t2=i;
  115414. for(k=0;k<l1;k++){
  115415. cc[t2]=ch[t1];
  115416. t1+=ido;
  115417. t2+=t10;
  115418. }
  115419. }
  115420. L135:
  115421. t1=0;
  115422. t2=ido<<1;
  115423. t3=0;
  115424. t4=ipp2*t0;
  115425. for(j=1;j<ipph;j++){
  115426. t1+=t2;
  115427. t3+=t0;
  115428. t4-=t0;
  115429. t5=t1;
  115430. t6=t3;
  115431. t7=t4;
  115432. for(k=0;k<l1;k++){
  115433. cc[t5-1]=ch[t6];
  115434. cc[t5]=ch[t7];
  115435. t5+=t10;
  115436. t6+=ido;
  115437. t7+=ido;
  115438. }
  115439. }
  115440. if(ido==1)return;
  115441. if(nbd<l1)goto L141;
  115442. t1=-ido;
  115443. t3=0;
  115444. t4=0;
  115445. t5=ipp2*t0;
  115446. for(j=1;j<ipph;j++){
  115447. t1+=t2;
  115448. t3+=t2;
  115449. t4+=t0;
  115450. t5-=t0;
  115451. t6=t1;
  115452. t7=t3;
  115453. t8=t4;
  115454. t9=t5;
  115455. for(k=0;k<l1;k++){
  115456. for(i=2;i<ido;i+=2){
  115457. ic=idp2-i;
  115458. cc[i+t7-1]=ch[i+t8-1]+ch[i+t9-1];
  115459. cc[ic+t6-1]=ch[i+t8-1]-ch[i+t9-1];
  115460. cc[i+t7]=ch[i+t8]+ch[i+t9];
  115461. cc[ic+t6]=ch[i+t9]-ch[i+t8];
  115462. }
  115463. t6+=t10;
  115464. t7+=t10;
  115465. t8+=ido;
  115466. t9+=ido;
  115467. }
  115468. }
  115469. return;
  115470. L141:
  115471. t1=-ido;
  115472. t3=0;
  115473. t4=0;
  115474. t5=ipp2*t0;
  115475. for(j=1;j<ipph;j++){
  115476. t1+=t2;
  115477. t3+=t2;
  115478. t4+=t0;
  115479. t5-=t0;
  115480. for(i=2;i<ido;i+=2){
  115481. t6=idp2+t1-i;
  115482. t7=i+t3;
  115483. t8=i+t4;
  115484. t9=i+t5;
  115485. for(k=0;k<l1;k++){
  115486. cc[t7-1]=ch[t8-1]+ch[t9-1];
  115487. cc[t6-1]=ch[t8-1]-ch[t9-1];
  115488. cc[t7]=ch[t8]+ch[t9];
  115489. cc[t6]=ch[t9]-ch[t8];
  115490. t6+=t10;
  115491. t7+=t10;
  115492. t8+=ido;
  115493. t9+=ido;
  115494. }
  115495. }
  115496. }
  115497. }
  115498. static void drftf1(int n,float *c,float *ch,float *wa,int *ifac){
  115499. int i,k1,l1,l2;
  115500. int na,kh,nf;
  115501. int ip,iw,ido,idl1,ix2,ix3;
  115502. nf=ifac[1];
  115503. na=1;
  115504. l2=n;
  115505. iw=n;
  115506. for(k1=0;k1<nf;k1++){
  115507. kh=nf-k1;
  115508. ip=ifac[kh+1];
  115509. l1=l2/ip;
  115510. ido=n/l2;
  115511. idl1=ido*l1;
  115512. iw-=(ip-1)*ido;
  115513. na=1-na;
  115514. if(ip!=4)goto L102;
  115515. ix2=iw+ido;
  115516. ix3=ix2+ido;
  115517. if(na!=0)
  115518. dradf4(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1);
  115519. else
  115520. dradf4(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1);
  115521. goto L110;
  115522. L102:
  115523. if(ip!=2)goto L104;
  115524. if(na!=0)goto L103;
  115525. dradf2(ido,l1,c,ch,wa+iw-1);
  115526. goto L110;
  115527. L103:
  115528. dradf2(ido,l1,ch,c,wa+iw-1);
  115529. goto L110;
  115530. L104:
  115531. if(ido==1)na=1-na;
  115532. if(na!=0)goto L109;
  115533. dradfg(ido,ip,l1,idl1,c,c,c,ch,ch,wa+iw-1);
  115534. na=1;
  115535. goto L110;
  115536. L109:
  115537. dradfg(ido,ip,l1,idl1,ch,ch,ch,c,c,wa+iw-1);
  115538. na=0;
  115539. L110:
  115540. l2=l1;
  115541. }
  115542. if(na==1)return;
  115543. for(i=0;i<n;i++)c[i]=ch[i];
  115544. }
  115545. static void dradb2(int ido,int l1,float *cc,float *ch,float *wa1){
  115546. int i,k,t0,t1,t2,t3,t4,t5,t6;
  115547. float ti2,tr2;
  115548. t0=l1*ido;
  115549. t1=0;
  115550. t2=0;
  115551. t3=(ido<<1)-1;
  115552. for(k=0;k<l1;k++){
  115553. ch[t1]=cc[t2]+cc[t3+t2];
  115554. ch[t1+t0]=cc[t2]-cc[t3+t2];
  115555. t2=(t1+=ido)<<1;
  115556. }
  115557. if(ido<2)return;
  115558. if(ido==2)goto L105;
  115559. t1=0;
  115560. t2=0;
  115561. for(k=0;k<l1;k++){
  115562. t3=t1;
  115563. t5=(t4=t2)+(ido<<1);
  115564. t6=t0+t1;
  115565. for(i=2;i<ido;i+=2){
  115566. t3+=2;
  115567. t4+=2;
  115568. t5-=2;
  115569. t6+=2;
  115570. ch[t3-1]=cc[t4-1]+cc[t5-1];
  115571. tr2=cc[t4-1]-cc[t5-1];
  115572. ch[t3]=cc[t4]-cc[t5];
  115573. ti2=cc[t4]+cc[t5];
  115574. ch[t6-1]=wa1[i-2]*tr2-wa1[i-1]*ti2;
  115575. ch[t6]=wa1[i-2]*ti2+wa1[i-1]*tr2;
  115576. }
  115577. t2=(t1+=ido)<<1;
  115578. }
  115579. if(ido%2==1)return;
  115580. L105:
  115581. t1=ido-1;
  115582. t2=ido-1;
  115583. for(k=0;k<l1;k++){
  115584. ch[t1]=cc[t2]+cc[t2];
  115585. ch[t1+t0]=-(cc[t2+1]+cc[t2+1]);
  115586. t1+=ido;
  115587. t2+=ido<<1;
  115588. }
  115589. }
  115590. static void dradb3(int ido,int l1,float *cc,float *ch,float *wa1,
  115591. float *wa2){
  115592. static float taur = -.5f;
  115593. static float taui = .8660254037844386f;
  115594. int i,k,t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10;
  115595. float ci2,ci3,di2,di3,cr2,cr3,dr2,dr3,ti2,tr2;
  115596. t0=l1*ido;
  115597. t1=0;
  115598. t2=t0<<1;
  115599. t3=ido<<1;
  115600. t4=ido+(ido<<1);
  115601. t5=0;
  115602. for(k=0;k<l1;k++){
  115603. tr2=cc[t3-1]+cc[t3-1];
  115604. cr2=cc[t5]+(taur*tr2);
  115605. ch[t1]=cc[t5]+tr2;
  115606. ci3=taui*(cc[t3]+cc[t3]);
  115607. ch[t1+t0]=cr2-ci3;
  115608. ch[t1+t2]=cr2+ci3;
  115609. t1+=ido;
  115610. t3+=t4;
  115611. t5+=t4;
  115612. }
  115613. if(ido==1)return;
  115614. t1=0;
  115615. t3=ido<<1;
  115616. for(k=0;k<l1;k++){
  115617. t7=t1+(t1<<1);
  115618. t6=(t5=t7+t3);
  115619. t8=t1;
  115620. t10=(t9=t1+t0)+t0;
  115621. for(i=2;i<ido;i+=2){
  115622. t5+=2;
  115623. t6-=2;
  115624. t7+=2;
  115625. t8+=2;
  115626. t9+=2;
  115627. t10+=2;
  115628. tr2=cc[t5-1]+cc[t6-1];
  115629. cr2=cc[t7-1]+(taur*tr2);
  115630. ch[t8-1]=cc[t7-1]+tr2;
  115631. ti2=cc[t5]-cc[t6];
  115632. ci2=cc[t7]+(taur*ti2);
  115633. ch[t8]=cc[t7]+ti2;
  115634. cr3=taui*(cc[t5-1]-cc[t6-1]);
  115635. ci3=taui*(cc[t5]+cc[t6]);
  115636. dr2=cr2-ci3;
  115637. dr3=cr2+ci3;
  115638. di2=ci2+cr3;
  115639. di3=ci2-cr3;
  115640. ch[t9-1]=wa1[i-2]*dr2-wa1[i-1]*di2;
  115641. ch[t9]=wa1[i-2]*di2+wa1[i-1]*dr2;
  115642. ch[t10-1]=wa2[i-2]*dr3-wa2[i-1]*di3;
  115643. ch[t10]=wa2[i-2]*di3+wa2[i-1]*dr3;
  115644. }
  115645. t1+=ido;
  115646. }
  115647. }
  115648. static void dradb4(int ido,int l1,float *cc,float *ch,float *wa1,
  115649. float *wa2,float *wa3){
  115650. static float sqrt2=1.414213562373095f;
  115651. int i,k,t0,t1,t2,t3,t4,t5,t6,t7,t8;
  115652. float ci2,ci3,ci4,cr2,cr3,cr4,ti1,ti2,ti3,ti4,tr1,tr2,tr3,tr4;
  115653. t0=l1*ido;
  115654. t1=0;
  115655. t2=ido<<2;
  115656. t3=0;
  115657. t6=ido<<1;
  115658. for(k=0;k<l1;k++){
  115659. t4=t3+t6;
  115660. t5=t1;
  115661. tr3=cc[t4-1]+cc[t4-1];
  115662. tr4=cc[t4]+cc[t4];
  115663. tr1=cc[t3]-cc[(t4+=t6)-1];
  115664. tr2=cc[t3]+cc[t4-1];
  115665. ch[t5]=tr2+tr3;
  115666. ch[t5+=t0]=tr1-tr4;
  115667. ch[t5+=t0]=tr2-tr3;
  115668. ch[t5+=t0]=tr1+tr4;
  115669. t1+=ido;
  115670. t3+=t2;
  115671. }
  115672. if(ido<2)return;
  115673. if(ido==2)goto L105;
  115674. t1=0;
  115675. for(k=0;k<l1;k++){
  115676. t5=(t4=(t3=(t2=t1<<2)+t6))+t6;
  115677. t7=t1;
  115678. for(i=2;i<ido;i+=2){
  115679. t2+=2;
  115680. t3+=2;
  115681. t4-=2;
  115682. t5-=2;
  115683. t7+=2;
  115684. ti1=cc[t2]+cc[t5];
  115685. ti2=cc[t2]-cc[t5];
  115686. ti3=cc[t3]-cc[t4];
  115687. tr4=cc[t3]+cc[t4];
  115688. tr1=cc[t2-1]-cc[t5-1];
  115689. tr2=cc[t2-1]+cc[t5-1];
  115690. ti4=cc[t3-1]-cc[t4-1];
  115691. tr3=cc[t3-1]+cc[t4-1];
  115692. ch[t7-1]=tr2+tr3;
  115693. cr3=tr2-tr3;
  115694. ch[t7]=ti2+ti3;
  115695. ci3=ti2-ti3;
  115696. cr2=tr1-tr4;
  115697. cr4=tr1+tr4;
  115698. ci2=ti1+ti4;
  115699. ci4=ti1-ti4;
  115700. ch[(t8=t7+t0)-1]=wa1[i-2]*cr2-wa1[i-1]*ci2;
  115701. ch[t8]=wa1[i-2]*ci2+wa1[i-1]*cr2;
  115702. ch[(t8+=t0)-1]=wa2[i-2]*cr3-wa2[i-1]*ci3;
  115703. ch[t8]=wa2[i-2]*ci3+wa2[i-1]*cr3;
  115704. ch[(t8+=t0)-1]=wa3[i-2]*cr4-wa3[i-1]*ci4;
  115705. ch[t8]=wa3[i-2]*ci4+wa3[i-1]*cr4;
  115706. }
  115707. t1+=ido;
  115708. }
  115709. if(ido%2 == 1)return;
  115710. L105:
  115711. t1=ido;
  115712. t2=ido<<2;
  115713. t3=ido-1;
  115714. t4=ido+(ido<<1);
  115715. for(k=0;k<l1;k++){
  115716. t5=t3;
  115717. ti1=cc[t1]+cc[t4];
  115718. ti2=cc[t4]-cc[t1];
  115719. tr1=cc[t1-1]-cc[t4-1];
  115720. tr2=cc[t1-1]+cc[t4-1];
  115721. ch[t5]=tr2+tr2;
  115722. ch[t5+=t0]=sqrt2*(tr1-ti1);
  115723. ch[t5+=t0]=ti2+ti2;
  115724. ch[t5+=t0]=-sqrt2*(tr1+ti1);
  115725. t3+=ido;
  115726. t1+=t2;
  115727. t4+=t2;
  115728. }
  115729. }
  115730. static void dradbg(int ido,int ip,int l1,int idl1,float *cc,float *c1,
  115731. float *c2,float *ch,float *ch2,float *wa){
  115732. static float tpi=6.283185307179586f;
  115733. int idij,ipph,i,j,k,l,ik,is,t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10,
  115734. t11,t12;
  115735. float dc2,ai1,ai2,ar1,ar2,ds2;
  115736. int nbd;
  115737. float dcp,arg,dsp,ar1h,ar2h;
  115738. int ipp2;
  115739. t10=ip*ido;
  115740. t0=l1*ido;
  115741. arg=tpi/(float)ip;
  115742. dcp=cos(arg);
  115743. dsp=sin(arg);
  115744. nbd=(ido-1)>>1;
  115745. ipp2=ip;
  115746. ipph=(ip+1)>>1;
  115747. if(ido<l1)goto L103;
  115748. t1=0;
  115749. t2=0;
  115750. for(k=0;k<l1;k++){
  115751. t3=t1;
  115752. t4=t2;
  115753. for(i=0;i<ido;i++){
  115754. ch[t3]=cc[t4];
  115755. t3++;
  115756. t4++;
  115757. }
  115758. t1+=ido;
  115759. t2+=t10;
  115760. }
  115761. goto L106;
  115762. L103:
  115763. t1=0;
  115764. for(i=0;i<ido;i++){
  115765. t2=t1;
  115766. t3=t1;
  115767. for(k=0;k<l1;k++){
  115768. ch[t2]=cc[t3];
  115769. t2+=ido;
  115770. t3+=t10;
  115771. }
  115772. t1++;
  115773. }
  115774. L106:
  115775. t1=0;
  115776. t2=ipp2*t0;
  115777. t7=(t5=ido<<1);
  115778. for(j=1;j<ipph;j++){
  115779. t1+=t0;
  115780. t2-=t0;
  115781. t3=t1;
  115782. t4=t2;
  115783. t6=t5;
  115784. for(k=0;k<l1;k++){
  115785. ch[t3]=cc[t6-1]+cc[t6-1];
  115786. ch[t4]=cc[t6]+cc[t6];
  115787. t3+=ido;
  115788. t4+=ido;
  115789. t6+=t10;
  115790. }
  115791. t5+=t7;
  115792. }
  115793. if (ido == 1)goto L116;
  115794. if(nbd<l1)goto L112;
  115795. t1=0;
  115796. t2=ipp2*t0;
  115797. t7=0;
  115798. for(j=1;j<ipph;j++){
  115799. t1+=t0;
  115800. t2-=t0;
  115801. t3=t1;
  115802. t4=t2;
  115803. t7+=(ido<<1);
  115804. t8=t7;
  115805. for(k=0;k<l1;k++){
  115806. t5=t3;
  115807. t6=t4;
  115808. t9=t8;
  115809. t11=t8;
  115810. for(i=2;i<ido;i+=2){
  115811. t5+=2;
  115812. t6+=2;
  115813. t9+=2;
  115814. t11-=2;
  115815. ch[t5-1]=cc[t9-1]+cc[t11-1];
  115816. ch[t6-1]=cc[t9-1]-cc[t11-1];
  115817. ch[t5]=cc[t9]-cc[t11];
  115818. ch[t6]=cc[t9]+cc[t11];
  115819. }
  115820. t3+=ido;
  115821. t4+=ido;
  115822. t8+=t10;
  115823. }
  115824. }
  115825. goto L116;
  115826. L112:
  115827. t1=0;
  115828. t2=ipp2*t0;
  115829. t7=0;
  115830. for(j=1;j<ipph;j++){
  115831. t1+=t0;
  115832. t2-=t0;
  115833. t3=t1;
  115834. t4=t2;
  115835. t7+=(ido<<1);
  115836. t8=t7;
  115837. t9=t7;
  115838. for(i=2;i<ido;i+=2){
  115839. t3+=2;
  115840. t4+=2;
  115841. t8+=2;
  115842. t9-=2;
  115843. t5=t3;
  115844. t6=t4;
  115845. t11=t8;
  115846. t12=t9;
  115847. for(k=0;k<l1;k++){
  115848. ch[t5-1]=cc[t11-1]+cc[t12-1];
  115849. ch[t6-1]=cc[t11-1]-cc[t12-1];
  115850. ch[t5]=cc[t11]-cc[t12];
  115851. ch[t6]=cc[t11]+cc[t12];
  115852. t5+=ido;
  115853. t6+=ido;
  115854. t11+=t10;
  115855. t12+=t10;
  115856. }
  115857. }
  115858. }
  115859. L116:
  115860. ar1=1.f;
  115861. ai1=0.f;
  115862. t1=0;
  115863. t9=(t2=ipp2*idl1);
  115864. t3=(ip-1)*idl1;
  115865. for(l=1;l<ipph;l++){
  115866. t1+=idl1;
  115867. t2-=idl1;
  115868. ar1h=dcp*ar1-dsp*ai1;
  115869. ai1=dcp*ai1+dsp*ar1;
  115870. ar1=ar1h;
  115871. t4=t1;
  115872. t5=t2;
  115873. t6=0;
  115874. t7=idl1;
  115875. t8=t3;
  115876. for(ik=0;ik<idl1;ik++){
  115877. c2[t4++]=ch2[t6++]+ar1*ch2[t7++];
  115878. c2[t5++]=ai1*ch2[t8++];
  115879. }
  115880. dc2=ar1;
  115881. ds2=ai1;
  115882. ar2=ar1;
  115883. ai2=ai1;
  115884. t6=idl1;
  115885. t7=t9-idl1;
  115886. for(j=2;j<ipph;j++){
  115887. t6+=idl1;
  115888. t7-=idl1;
  115889. ar2h=dc2*ar2-ds2*ai2;
  115890. ai2=dc2*ai2+ds2*ar2;
  115891. ar2=ar2h;
  115892. t4=t1;
  115893. t5=t2;
  115894. t11=t6;
  115895. t12=t7;
  115896. for(ik=0;ik<idl1;ik++){
  115897. c2[t4++]+=ar2*ch2[t11++];
  115898. c2[t5++]+=ai2*ch2[t12++];
  115899. }
  115900. }
  115901. }
  115902. t1=0;
  115903. for(j=1;j<ipph;j++){
  115904. t1+=idl1;
  115905. t2=t1;
  115906. for(ik=0;ik<idl1;ik++)ch2[ik]+=ch2[t2++];
  115907. }
  115908. t1=0;
  115909. t2=ipp2*t0;
  115910. for(j=1;j<ipph;j++){
  115911. t1+=t0;
  115912. t2-=t0;
  115913. t3=t1;
  115914. t4=t2;
  115915. for(k=0;k<l1;k++){
  115916. ch[t3]=c1[t3]-c1[t4];
  115917. ch[t4]=c1[t3]+c1[t4];
  115918. t3+=ido;
  115919. t4+=ido;
  115920. }
  115921. }
  115922. if(ido==1)goto L132;
  115923. if(nbd<l1)goto L128;
  115924. t1=0;
  115925. t2=ipp2*t0;
  115926. for(j=1;j<ipph;j++){
  115927. t1+=t0;
  115928. t2-=t0;
  115929. t3=t1;
  115930. t4=t2;
  115931. for(k=0;k<l1;k++){
  115932. t5=t3;
  115933. t6=t4;
  115934. for(i=2;i<ido;i+=2){
  115935. t5+=2;
  115936. t6+=2;
  115937. ch[t5-1]=c1[t5-1]-c1[t6];
  115938. ch[t6-1]=c1[t5-1]+c1[t6];
  115939. ch[t5]=c1[t5]+c1[t6-1];
  115940. ch[t6]=c1[t5]-c1[t6-1];
  115941. }
  115942. t3+=ido;
  115943. t4+=ido;
  115944. }
  115945. }
  115946. goto L132;
  115947. L128:
  115948. t1=0;
  115949. t2=ipp2*t0;
  115950. for(j=1;j<ipph;j++){
  115951. t1+=t0;
  115952. t2-=t0;
  115953. t3=t1;
  115954. t4=t2;
  115955. for(i=2;i<ido;i+=2){
  115956. t3+=2;
  115957. t4+=2;
  115958. t5=t3;
  115959. t6=t4;
  115960. for(k=0;k<l1;k++){
  115961. ch[t5-1]=c1[t5-1]-c1[t6];
  115962. ch[t6-1]=c1[t5-1]+c1[t6];
  115963. ch[t5]=c1[t5]+c1[t6-1];
  115964. ch[t6]=c1[t5]-c1[t6-1];
  115965. t5+=ido;
  115966. t6+=ido;
  115967. }
  115968. }
  115969. }
  115970. L132:
  115971. if(ido==1)return;
  115972. for(ik=0;ik<idl1;ik++)c2[ik]=ch2[ik];
  115973. t1=0;
  115974. for(j=1;j<ip;j++){
  115975. t2=(t1+=t0);
  115976. for(k=0;k<l1;k++){
  115977. c1[t2]=ch[t2];
  115978. t2+=ido;
  115979. }
  115980. }
  115981. if(nbd>l1)goto L139;
  115982. is= -ido-1;
  115983. t1=0;
  115984. for(j=1;j<ip;j++){
  115985. is+=ido;
  115986. t1+=t0;
  115987. idij=is;
  115988. t2=t1;
  115989. for(i=2;i<ido;i+=2){
  115990. t2+=2;
  115991. idij+=2;
  115992. t3=t2;
  115993. for(k=0;k<l1;k++){
  115994. c1[t3-1]=wa[idij-1]*ch[t3-1]-wa[idij]*ch[t3];
  115995. c1[t3]=wa[idij-1]*ch[t3]+wa[idij]*ch[t3-1];
  115996. t3+=ido;
  115997. }
  115998. }
  115999. }
  116000. return;
  116001. L139:
  116002. is= -ido-1;
  116003. t1=0;
  116004. for(j=1;j<ip;j++){
  116005. is+=ido;
  116006. t1+=t0;
  116007. t2=t1;
  116008. for(k=0;k<l1;k++){
  116009. idij=is;
  116010. t3=t2;
  116011. for(i=2;i<ido;i+=2){
  116012. idij+=2;
  116013. t3+=2;
  116014. c1[t3-1]=wa[idij-1]*ch[t3-1]-wa[idij]*ch[t3];
  116015. c1[t3]=wa[idij-1]*ch[t3]+wa[idij]*ch[t3-1];
  116016. }
  116017. t2+=ido;
  116018. }
  116019. }
  116020. }
  116021. static void drftb1(int n, float *c, float *ch, float *wa, int *ifac){
  116022. int i,k1,l1,l2;
  116023. int na;
  116024. int nf,ip,iw,ix2,ix3,ido,idl1;
  116025. nf=ifac[1];
  116026. na=0;
  116027. l1=1;
  116028. iw=1;
  116029. for(k1=0;k1<nf;k1++){
  116030. ip=ifac[k1 + 2];
  116031. l2=ip*l1;
  116032. ido=n/l2;
  116033. idl1=ido*l1;
  116034. if(ip!=4)goto L103;
  116035. ix2=iw+ido;
  116036. ix3=ix2+ido;
  116037. if(na!=0)
  116038. dradb4(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1);
  116039. else
  116040. dradb4(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1);
  116041. na=1-na;
  116042. goto L115;
  116043. L103:
  116044. if(ip!=2)goto L106;
  116045. if(na!=0)
  116046. dradb2(ido,l1,ch,c,wa+iw-1);
  116047. else
  116048. dradb2(ido,l1,c,ch,wa+iw-1);
  116049. na=1-na;
  116050. goto L115;
  116051. L106:
  116052. if(ip!=3)goto L109;
  116053. ix2=iw+ido;
  116054. if(na!=0)
  116055. dradb3(ido,l1,ch,c,wa+iw-1,wa+ix2-1);
  116056. else
  116057. dradb3(ido,l1,c,ch,wa+iw-1,wa+ix2-1);
  116058. na=1-na;
  116059. goto L115;
  116060. L109:
  116061. /* The radix five case can be translated later..... */
  116062. /* if(ip!=5)goto L112;
  116063. ix2=iw+ido;
  116064. ix3=ix2+ido;
  116065. ix4=ix3+ido;
  116066. if(na!=0)
  116067. dradb5(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1,wa+ix4-1);
  116068. else
  116069. dradb5(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1,wa+ix4-1);
  116070. na=1-na;
  116071. goto L115;
  116072. L112:*/
  116073. if(na!=0)
  116074. dradbg(ido,ip,l1,idl1,ch,ch,ch,c,c,wa+iw-1);
  116075. else
  116076. dradbg(ido,ip,l1,idl1,c,c,c,ch,ch,wa+iw-1);
  116077. if(ido==1)na=1-na;
  116078. L115:
  116079. l1=l2;
  116080. iw+=(ip-1)*ido;
  116081. }
  116082. if(na==0)return;
  116083. for(i=0;i<n;i++)c[i]=ch[i];
  116084. }
  116085. void drft_forward(drft_lookup *l,float *data){
  116086. if(l->n==1)return;
  116087. drftf1(l->n,data,l->trigcache,l->trigcache+l->n,l->splitcache);
  116088. }
  116089. void drft_backward(drft_lookup *l,float *data){
  116090. if (l->n==1)return;
  116091. drftb1(l->n,data,l->trigcache,l->trigcache+l->n,l->splitcache);
  116092. }
  116093. void drft_init(drft_lookup *l,int n){
  116094. l->n=n;
  116095. l->trigcache=(float*)_ogg_calloc(3*n,sizeof(*l->trigcache));
  116096. l->splitcache=(int*)_ogg_calloc(32,sizeof(*l->splitcache));
  116097. fdrffti(n, l->trigcache, l->splitcache);
  116098. }
  116099. void drft_clear(drft_lookup *l){
  116100. if(l){
  116101. if(l->trigcache)_ogg_free(l->trigcache);
  116102. if(l->splitcache)_ogg_free(l->splitcache);
  116103. memset(l,0,sizeof(*l));
  116104. }
  116105. }
  116106. #endif
  116107. /********* End of inlined file: smallft.c *********/
  116108. /********* Start of inlined file: synthesis.c *********/
  116109. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  116110. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  116111. // tasks..
  116112. #ifdef _MSC_VER
  116113. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  116114. #endif
  116115. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  116116. #if JUCE_USE_OGGVORBIS
  116117. #include <stdio.h>
  116118. int vorbis_synthesis(vorbis_block *vb,ogg_packet *op){
  116119. vorbis_dsp_state *vd=vb->vd;
  116120. private_state *b=(private_state*)vd->backend_state;
  116121. vorbis_info *vi=vd->vi;
  116122. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  116123. oggpack_buffer *opb=&vb->opb;
  116124. int type,mode,i;
  116125. /* first things first. Make sure decode is ready */
  116126. _vorbis_block_ripcord(vb);
  116127. oggpack_readinit(opb,op->packet,op->bytes);
  116128. /* Check the packet type */
  116129. if(oggpack_read(opb,1)!=0){
  116130. /* Oops. This is not an audio data packet */
  116131. return(OV_ENOTAUDIO);
  116132. }
  116133. /* read our mode and pre/post windowsize */
  116134. mode=oggpack_read(opb,b->modebits);
  116135. if(mode==-1)return(OV_EBADPACKET);
  116136. vb->mode=mode;
  116137. vb->W=ci->mode_param[mode]->blockflag;
  116138. if(vb->W){
  116139. /* this doesn;t get mapped through mode selection as it's used
  116140. only for window selection */
  116141. vb->lW=oggpack_read(opb,1);
  116142. vb->nW=oggpack_read(opb,1);
  116143. if(vb->nW==-1) return(OV_EBADPACKET);
  116144. }else{
  116145. vb->lW=0;
  116146. vb->nW=0;
  116147. }
  116148. /* more setup */
  116149. vb->granulepos=op->granulepos;
  116150. vb->sequence=op->packetno;
  116151. vb->eofflag=op->e_o_s;
  116152. /* alloc pcm passback storage */
  116153. vb->pcmend=ci->blocksizes[vb->W];
  116154. vb->pcm=(float**)_vorbis_block_alloc(vb,sizeof(*vb->pcm)*vi->channels);
  116155. for(i=0;i<vi->channels;i++)
  116156. vb->pcm[i]=(float*)_vorbis_block_alloc(vb,vb->pcmend*sizeof(*vb->pcm[i]));
  116157. /* unpack_header enforces range checking */
  116158. type=ci->map_type[ci->mode_param[mode]->mapping];
  116159. return(_mapping_P[type]->inverse(vb,ci->map_param[ci->mode_param[mode]->
  116160. mapping]));
  116161. }
  116162. /* used to track pcm position without actually performing decode.
  116163. Useful for sequential 'fast forward' */
  116164. int vorbis_synthesis_trackonly(vorbis_block *vb,ogg_packet *op){
  116165. vorbis_dsp_state *vd=vb->vd;
  116166. private_state *b=(private_state*)vd->backend_state;
  116167. vorbis_info *vi=vd->vi;
  116168. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  116169. oggpack_buffer *opb=&vb->opb;
  116170. int mode;
  116171. /* first things first. Make sure decode is ready */
  116172. _vorbis_block_ripcord(vb);
  116173. oggpack_readinit(opb,op->packet,op->bytes);
  116174. /* Check the packet type */
  116175. if(oggpack_read(opb,1)!=0){
  116176. /* Oops. This is not an audio data packet */
  116177. return(OV_ENOTAUDIO);
  116178. }
  116179. /* read our mode and pre/post windowsize */
  116180. mode=oggpack_read(opb,b->modebits);
  116181. if(mode==-1)return(OV_EBADPACKET);
  116182. vb->mode=mode;
  116183. vb->W=ci->mode_param[mode]->blockflag;
  116184. if(vb->W){
  116185. vb->lW=oggpack_read(opb,1);
  116186. vb->nW=oggpack_read(opb,1);
  116187. if(vb->nW==-1) return(OV_EBADPACKET);
  116188. }else{
  116189. vb->lW=0;
  116190. vb->nW=0;
  116191. }
  116192. /* more setup */
  116193. vb->granulepos=op->granulepos;
  116194. vb->sequence=op->packetno;
  116195. vb->eofflag=op->e_o_s;
  116196. /* no pcm */
  116197. vb->pcmend=0;
  116198. vb->pcm=NULL;
  116199. return(0);
  116200. }
  116201. long vorbis_packet_blocksize(vorbis_info *vi,ogg_packet *op){
  116202. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  116203. oggpack_buffer opb;
  116204. int mode;
  116205. oggpack_readinit(&opb,op->packet,op->bytes);
  116206. /* Check the packet type */
  116207. if(oggpack_read(&opb,1)!=0){
  116208. /* Oops. This is not an audio data packet */
  116209. return(OV_ENOTAUDIO);
  116210. }
  116211. {
  116212. int modebits=0;
  116213. int v=ci->modes;
  116214. while(v>1){
  116215. modebits++;
  116216. v>>=1;
  116217. }
  116218. /* read our mode and pre/post windowsize */
  116219. mode=oggpack_read(&opb,modebits);
  116220. }
  116221. if(mode==-1)return(OV_EBADPACKET);
  116222. return(ci->blocksizes[ci->mode_param[mode]->blockflag]);
  116223. }
  116224. int vorbis_synthesis_halfrate(vorbis_info *vi,int flag){
  116225. /* set / clear half-sample-rate mode */
  116226. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  116227. /* right now, our MDCT can't handle < 64 sample windows. */
  116228. if(ci->blocksizes[0]<=64 && flag)return -1;
  116229. ci->halfrate_flag=(flag?1:0);
  116230. return 0;
  116231. }
  116232. int vorbis_synthesis_halfrate_p(vorbis_info *vi){
  116233. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  116234. return ci->halfrate_flag;
  116235. }
  116236. #endif
  116237. /********* End of inlined file: synthesis.c *********/
  116238. /********* Start of inlined file: vorbisenc.c *********/
  116239. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  116240. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  116241. // tasks..
  116242. #ifdef _MSC_VER
  116243. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  116244. #endif
  116245. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  116246. #if JUCE_USE_OGGVORBIS
  116247. #include <stdlib.h>
  116248. #include <string.h>
  116249. #include <math.h>
  116250. /* careful with this; it's using static array sizing to make managing
  116251. all the modes a little less annoying. If we use a residue backend
  116252. with > 12 partition types, or a different division of iteration,
  116253. this needs to be updated. */
  116254. typedef struct {
  116255. static_codebook *books[12][3];
  116256. } static_bookblock;
  116257. typedef struct {
  116258. int res_type;
  116259. int limit_type; /* 0 lowpass limited, 1 point stereo limited */
  116260. vorbis_info_residue0 *res;
  116261. static_codebook *book_aux;
  116262. static_codebook *book_aux_managed;
  116263. static_bookblock *books_base;
  116264. static_bookblock *books_base_managed;
  116265. } vorbis_residue_template;
  116266. typedef struct {
  116267. vorbis_info_mapping0 *map;
  116268. vorbis_residue_template *res;
  116269. } vorbis_mapping_template;
  116270. typedef struct vp_adjblock{
  116271. int block[P_BANDS];
  116272. } vp_adjblock;
  116273. typedef struct {
  116274. int data[NOISE_COMPAND_LEVELS];
  116275. } compandblock;
  116276. /* high level configuration information for setting things up
  116277. step-by-step with the detailed vorbis_encode_ctl interface.
  116278. There's a fair amount of redundancy such that interactive setup
  116279. does not directly deal with any vorbis_info or codec_setup_info
  116280. initialization; it's all stored (until full init) in this highlevel
  116281. setup, then flushed out to the real codec setup structs later. */
  116282. typedef struct {
  116283. int att[P_NOISECURVES];
  116284. float boost;
  116285. float decay;
  116286. } att3;
  116287. typedef struct { int data[P_NOISECURVES]; } adj3;
  116288. typedef struct {
  116289. int pre[PACKETBLOBS];
  116290. int post[PACKETBLOBS];
  116291. float kHz[PACKETBLOBS];
  116292. float lowpasskHz[PACKETBLOBS];
  116293. } adj_stereo;
  116294. typedef struct {
  116295. int lo;
  116296. int hi;
  116297. int fixed;
  116298. } noiseguard;
  116299. typedef struct {
  116300. int data[P_NOISECURVES][17];
  116301. } noise3;
  116302. typedef struct {
  116303. int mappings;
  116304. double *rate_mapping;
  116305. double *quality_mapping;
  116306. int coupling_restriction;
  116307. long samplerate_min_restriction;
  116308. long samplerate_max_restriction;
  116309. int *blocksize_short;
  116310. int *blocksize_long;
  116311. att3 *psy_tone_masteratt;
  116312. int *psy_tone_0dB;
  116313. int *psy_tone_dBsuppress;
  116314. vp_adjblock *psy_tone_adj_impulse;
  116315. vp_adjblock *psy_tone_adj_long;
  116316. vp_adjblock *psy_tone_adj_other;
  116317. noiseguard *psy_noiseguards;
  116318. noise3 *psy_noise_bias_impulse;
  116319. noise3 *psy_noise_bias_padding;
  116320. noise3 *psy_noise_bias_trans;
  116321. noise3 *psy_noise_bias_long;
  116322. int *psy_noise_dBsuppress;
  116323. compandblock *psy_noise_compand;
  116324. double *psy_noise_compand_short_mapping;
  116325. double *psy_noise_compand_long_mapping;
  116326. int *psy_noise_normal_start[2];
  116327. int *psy_noise_normal_partition[2];
  116328. double *psy_noise_normal_thresh;
  116329. int *psy_ath_float;
  116330. int *psy_ath_abs;
  116331. double *psy_lowpass;
  116332. vorbis_info_psy_global *global_params;
  116333. double *global_mapping;
  116334. adj_stereo *stereo_modes;
  116335. static_codebook ***floor_books;
  116336. vorbis_info_floor1 *floor_params;
  116337. int *floor_short_mapping;
  116338. int *floor_long_mapping;
  116339. vorbis_mapping_template *maps;
  116340. } ve_setup_data_template;
  116341. /* a few static coder conventions */
  116342. static vorbis_info_mode _mode_template[2]={
  116343. {0,0,0,0},
  116344. {1,0,0,1}
  116345. };
  116346. static vorbis_info_mapping0 _map_nominal[2]={
  116347. {1, {0,0}, {0}, {0}, 1,{0},{1}},
  116348. {1, {0,0}, {1}, {1}, 1,{0},{1}}
  116349. };
  116350. /********* Start of inlined file: setup_44.h *********/
  116351. /********* Start of inlined file: floor_all.h *********/
  116352. /********* Start of inlined file: floor_books.h *********/
  116353. static long _huff_lengthlist_line_256x7_0sub1[] = {
  116354. 0, 2, 3, 3, 3, 3, 4, 3, 4,
  116355. };
  116356. static static_codebook _huff_book_line_256x7_0sub1 = {
  116357. 1, 9,
  116358. _huff_lengthlist_line_256x7_0sub1,
  116359. 0, 0, 0, 0, 0,
  116360. NULL,
  116361. NULL,
  116362. NULL,
  116363. NULL,
  116364. 0
  116365. };
  116366. static long _huff_lengthlist_line_256x7_0sub2[] = {
  116367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 3, 4, 3, 5, 3,
  116368. 6, 3, 6, 4, 6, 4, 7, 5, 7,
  116369. };
  116370. static static_codebook _huff_book_line_256x7_0sub2 = {
  116371. 1, 25,
  116372. _huff_lengthlist_line_256x7_0sub2,
  116373. 0, 0, 0, 0, 0,
  116374. NULL,
  116375. NULL,
  116376. NULL,
  116377. NULL,
  116378. 0
  116379. };
  116380. static long _huff_lengthlist_line_256x7_0sub3[] = {
  116381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 5, 2, 5, 3, 5, 3,
  116383. 6, 3, 6, 4, 7, 6, 7, 8, 7, 9, 8, 9, 9, 9,10, 9,
  116384. 11,13,11,13,10,10,13,13,13,13,13,13,12,12,12,12,
  116385. };
  116386. static static_codebook _huff_book_line_256x7_0sub3 = {
  116387. 1, 64,
  116388. _huff_lengthlist_line_256x7_0sub3,
  116389. 0, 0, 0, 0, 0,
  116390. NULL,
  116391. NULL,
  116392. NULL,
  116393. NULL,
  116394. 0
  116395. };
  116396. static long _huff_lengthlist_line_256x7_1sub1[] = {
  116397. 0, 3, 3, 3, 3, 2, 4, 3, 4,
  116398. };
  116399. static static_codebook _huff_book_line_256x7_1sub1 = {
  116400. 1, 9,
  116401. _huff_lengthlist_line_256x7_1sub1,
  116402. 0, 0, 0, 0, 0,
  116403. NULL,
  116404. NULL,
  116405. NULL,
  116406. NULL,
  116407. 0
  116408. };
  116409. static long _huff_lengthlist_line_256x7_1sub2[] = {
  116410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 3, 4, 3, 4, 4,
  116411. 5, 4, 6, 5, 6, 7, 6, 8, 8,
  116412. };
  116413. static static_codebook _huff_book_line_256x7_1sub2 = {
  116414. 1, 25,
  116415. _huff_lengthlist_line_256x7_1sub2,
  116416. 0, 0, 0, 0, 0,
  116417. NULL,
  116418. NULL,
  116419. NULL,
  116420. NULL,
  116421. 0
  116422. };
  116423. static long _huff_lengthlist_line_256x7_1sub3[] = {
  116424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 2, 4, 3, 6, 3, 7,
  116426. 3, 8, 5, 8, 6, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  116427. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7,
  116428. };
  116429. static static_codebook _huff_book_line_256x7_1sub3 = {
  116430. 1, 64,
  116431. _huff_lengthlist_line_256x7_1sub3,
  116432. 0, 0, 0, 0, 0,
  116433. NULL,
  116434. NULL,
  116435. NULL,
  116436. NULL,
  116437. 0
  116438. };
  116439. static long _huff_lengthlist_line_256x7_class0[] = {
  116440. 7, 5, 5, 9, 9, 6, 6, 9,12, 8, 7, 8,11, 8, 9,15,
  116441. 6, 3, 3, 7, 7, 4, 3, 6, 9, 6, 5, 6, 8, 6, 8,15,
  116442. 8, 5, 5, 9, 8, 5, 4, 6,10, 7, 5, 5,11, 8, 7,15,
  116443. 14,15,13,13,13,13, 8,11,15,10, 7, 6,11, 9,10,15,
  116444. };
  116445. static static_codebook _huff_book_line_256x7_class0 = {
  116446. 1, 64,
  116447. _huff_lengthlist_line_256x7_class0,
  116448. 0, 0, 0, 0, 0,
  116449. NULL,
  116450. NULL,
  116451. NULL,
  116452. NULL,
  116453. 0
  116454. };
  116455. static long _huff_lengthlist_line_256x7_class1[] = {
  116456. 5, 6, 8,15, 6, 9,10,15,10,11,12,15,15,15,15,15,
  116457. 4, 6, 7,15, 6, 7, 8,15, 9, 8, 9,15,15,15,15,15,
  116458. 6, 8, 9,15, 7, 7, 8,15,10, 9,10,15,15,15,15,15,
  116459. 15,13,15,15,15,10,11,15,15,13,13,15,15,15,15,15,
  116460. 4, 6, 7,15, 6, 8, 9,15,10,10,12,15,15,15,15,15,
  116461. 2, 5, 6,15, 5, 6, 7,15, 8, 6, 7,15,15,15,15,15,
  116462. 5, 6, 8,15, 5, 6, 7,15, 9, 6, 7,15,15,15,15,15,
  116463. 14,12,13,15,12,10,11,15,15,15,15,15,15,15,15,15,
  116464. 7, 8, 9,15, 9,10,10,15,15,14,14,15,15,15,15,15,
  116465. 5, 6, 7,15, 7, 8, 9,15,12, 9,10,15,15,15,15,15,
  116466. 7, 7, 9,15, 7, 7, 8,15,12, 8, 9,15,15,15,15,15,
  116467. 13,13,14,15,12,11,12,15,15,15,15,15,15,15,15,15,
  116468. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,
  116469. 13,13,13,15,15,15,15,15,15,15,15,15,15,15,15,15,
  116470. 15,12,13,15,15,12,13,15,15,14,15,15,15,15,15,15,
  116471. 15,15,15,15,15,15,13,15,15,15,15,15,15,15,15,15,
  116472. };
  116473. static static_codebook _huff_book_line_256x7_class1 = {
  116474. 1, 256,
  116475. _huff_lengthlist_line_256x7_class1,
  116476. 0, 0, 0, 0, 0,
  116477. NULL,
  116478. NULL,
  116479. NULL,
  116480. NULL,
  116481. 0
  116482. };
  116483. static long _huff_lengthlist_line_512x17_0sub0[] = {
  116484. 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
  116485. 5, 6, 5, 6, 6, 6, 6, 5, 6, 6, 7, 6, 7, 6, 7, 6,
  116486. 7, 6, 8, 7, 8, 7, 8, 7, 8, 7, 8, 7, 9, 7, 9, 7,
  116487. 9, 7, 9, 8, 9, 8,10, 8,10, 8,10, 7,10, 6,10, 8,
  116488. 10, 8,11, 7,10, 7,11, 8,11,11,12,12,11,11,12,11,
  116489. 13,11,13,11,13,12,15,12,13,13,14,14,14,14,14,15,
  116490. 15,15,16,14,17,19,19,18,18,18,18,18,18,18,18,18,
  116491. 18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,
  116492. };
  116493. static static_codebook _huff_book_line_512x17_0sub0 = {
  116494. 1, 128,
  116495. _huff_lengthlist_line_512x17_0sub0,
  116496. 0, 0, 0, 0, 0,
  116497. NULL,
  116498. NULL,
  116499. NULL,
  116500. NULL,
  116501. 0
  116502. };
  116503. static long _huff_lengthlist_line_512x17_1sub0[] = {
  116504. 2, 4, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  116505. 6, 5, 6, 6, 7, 6, 7, 6, 8, 7, 8, 7, 8, 7, 8, 7,
  116506. };
  116507. static static_codebook _huff_book_line_512x17_1sub0 = {
  116508. 1, 32,
  116509. _huff_lengthlist_line_512x17_1sub0,
  116510. 0, 0, 0, 0, 0,
  116511. NULL,
  116512. NULL,
  116513. NULL,
  116514. NULL,
  116515. 0
  116516. };
  116517. static long _huff_lengthlist_line_512x17_1sub1[] = {
  116518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116520. 4, 3, 5, 3, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 6, 5,
  116521. 6, 5, 7, 5, 8, 6, 8, 6, 8, 6, 8, 6, 8, 7, 9, 7,
  116522. 9, 7,11, 9,11,11,12,11,14,12,14,16,14,16,13,16,
  116523. 14,16,12,15,13,16,14,16,13,14,12,15,13,15,13,13,
  116524. 13,15,12,14,14,15,13,15,12,15,15,15,15,15,15,15,
  116525. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,
  116526. };
  116527. static static_codebook _huff_book_line_512x17_1sub1 = {
  116528. 1, 128,
  116529. _huff_lengthlist_line_512x17_1sub1,
  116530. 0, 0, 0, 0, 0,
  116531. NULL,
  116532. NULL,
  116533. NULL,
  116534. NULL,
  116535. 0
  116536. };
  116537. static long _huff_lengthlist_line_512x17_2sub1[] = {
  116538. 0, 4, 5, 4, 4, 4, 5, 4, 4, 4, 5, 4, 5, 4, 5, 3,
  116539. 5, 3,
  116540. };
  116541. static static_codebook _huff_book_line_512x17_2sub1 = {
  116542. 1, 18,
  116543. _huff_lengthlist_line_512x17_2sub1,
  116544. 0, 0, 0, 0, 0,
  116545. NULL,
  116546. NULL,
  116547. NULL,
  116548. NULL,
  116549. 0
  116550. };
  116551. static long _huff_lengthlist_line_512x17_2sub2[] = {
  116552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116553. 0, 0, 4, 3, 4, 3, 4, 4, 5, 4, 5, 4, 6, 4, 6, 5,
  116554. 6, 5, 7, 5, 7, 6, 8, 6, 8, 6, 8, 7, 8, 7, 9, 7,
  116555. 9, 8,
  116556. };
  116557. static static_codebook _huff_book_line_512x17_2sub2 = {
  116558. 1, 50,
  116559. _huff_lengthlist_line_512x17_2sub2,
  116560. 0, 0, 0, 0, 0,
  116561. NULL,
  116562. NULL,
  116563. NULL,
  116564. NULL,
  116565. 0
  116566. };
  116567. static long _huff_lengthlist_line_512x17_2sub3[] = {
  116568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116571. 0, 0, 3, 3, 3, 3, 4, 3, 4, 4, 5, 5, 6, 6, 7, 7,
  116572. 7, 8, 8,11, 8, 9, 9, 9,10,11,11,11, 9,10,10,11,
  116573. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,
  116574. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  116575. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  116576. };
  116577. static static_codebook _huff_book_line_512x17_2sub3 = {
  116578. 1, 128,
  116579. _huff_lengthlist_line_512x17_2sub3,
  116580. 0, 0, 0, 0, 0,
  116581. NULL,
  116582. NULL,
  116583. NULL,
  116584. NULL,
  116585. 0
  116586. };
  116587. static long _huff_lengthlist_line_512x17_3sub1[] = {
  116588. 0, 4, 4, 4, 4, 4, 4, 3, 4, 4, 4, 4, 4, 5, 4, 5,
  116589. 5, 5,
  116590. };
  116591. static static_codebook _huff_book_line_512x17_3sub1 = {
  116592. 1, 18,
  116593. _huff_lengthlist_line_512x17_3sub1,
  116594. 0, 0, 0, 0, 0,
  116595. NULL,
  116596. NULL,
  116597. NULL,
  116598. NULL,
  116599. 0
  116600. };
  116601. static long _huff_lengthlist_line_512x17_3sub2[] = {
  116602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116603. 0, 0, 2, 3, 3, 4, 3, 5, 4, 6, 4, 6, 5, 7, 6, 7,
  116604. 6, 8, 6, 8, 7, 9, 8,10, 8,12, 9,13,10,15,10,15,
  116605. 11,14,
  116606. };
  116607. static static_codebook _huff_book_line_512x17_3sub2 = {
  116608. 1, 50,
  116609. _huff_lengthlist_line_512x17_3sub2,
  116610. 0, 0, 0, 0, 0,
  116611. NULL,
  116612. NULL,
  116613. NULL,
  116614. NULL,
  116615. 0
  116616. };
  116617. static long _huff_lengthlist_line_512x17_3sub3[] = {
  116618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116621. 0, 0, 4, 8, 4, 8, 4, 8, 4, 8, 5, 8, 5, 8, 6, 8,
  116622. 4, 8, 4, 8, 5, 8, 5, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  116623. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  116624. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  116625. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  116626. };
  116627. static static_codebook _huff_book_line_512x17_3sub3 = {
  116628. 1, 128,
  116629. _huff_lengthlist_line_512x17_3sub3,
  116630. 0, 0, 0, 0, 0,
  116631. NULL,
  116632. NULL,
  116633. NULL,
  116634. NULL,
  116635. 0
  116636. };
  116637. static long _huff_lengthlist_line_512x17_class1[] = {
  116638. 1, 2, 3, 6, 5, 4, 7, 7,
  116639. };
  116640. static static_codebook _huff_book_line_512x17_class1 = {
  116641. 1, 8,
  116642. _huff_lengthlist_line_512x17_class1,
  116643. 0, 0, 0, 0, 0,
  116644. NULL,
  116645. NULL,
  116646. NULL,
  116647. NULL,
  116648. 0
  116649. };
  116650. static long _huff_lengthlist_line_512x17_class2[] = {
  116651. 3, 3, 3,14, 5, 4, 4,11, 8, 6, 6,10,17,12,11,17,
  116652. 6, 5, 5,15, 5, 3, 4,11, 8, 5, 5, 8,16, 9,10,14,
  116653. 10, 8, 9,17, 8, 6, 6,13,10, 7, 7,10,16,11,13,14,
  116654. 17,17,17,17,17,16,16,16,16,15,16,16,16,16,16,16,
  116655. };
  116656. static static_codebook _huff_book_line_512x17_class2 = {
  116657. 1, 64,
  116658. _huff_lengthlist_line_512x17_class2,
  116659. 0, 0, 0, 0, 0,
  116660. NULL,
  116661. NULL,
  116662. NULL,
  116663. NULL,
  116664. 0
  116665. };
  116666. static long _huff_lengthlist_line_512x17_class3[] = {
  116667. 2, 4, 6,17, 4, 5, 7,17, 8, 7,10,17,17,17,17,17,
  116668. 3, 4, 6,15, 3, 3, 6,15, 7, 6, 9,17,17,17,17,17,
  116669. 6, 8,10,17, 6, 6, 8,16, 9, 8,10,17,17,15,16,17,
  116670. 17,17,17,17,12,15,15,16,12,15,15,16,16,16,16,16,
  116671. };
  116672. static static_codebook _huff_book_line_512x17_class3 = {
  116673. 1, 64,
  116674. _huff_lengthlist_line_512x17_class3,
  116675. 0, 0, 0, 0, 0,
  116676. NULL,
  116677. NULL,
  116678. NULL,
  116679. NULL,
  116680. 0
  116681. };
  116682. static long _huff_lengthlist_line_128x4_class0[] = {
  116683. 7, 7, 7,11, 6, 6, 7,11, 7, 6, 6,10,12,10,10,13,
  116684. 7, 7, 8,11, 7, 7, 7,11, 7, 6, 7,10,11,10,10,13,
  116685. 10,10, 9,12, 9, 9, 9,11, 8, 8, 8,11,13,11,10,14,
  116686. 15,15,14,15,15,14,13,14,15,12,12,17,17,17,17,17,
  116687. 7, 7, 6, 9, 6, 6, 6, 9, 7, 6, 6, 8,11,11,10,12,
  116688. 7, 7, 7, 9, 7, 6, 6, 9, 7, 6, 6, 9,13,10,10,11,
  116689. 10, 9, 8,10, 9, 8, 8,10, 8, 8, 7, 9,13,12,10,11,
  116690. 17,14,14,13,15,14,12,13,17,13,12,15,17,17,14,17,
  116691. 7, 6, 6, 7, 6, 6, 5, 7, 6, 6, 6, 6,11, 9, 9, 9,
  116692. 7, 7, 6, 7, 7, 6, 6, 7, 6, 6, 6, 6,10, 9, 8, 9,
  116693. 10, 9, 8, 8, 9, 8, 7, 8, 8, 7, 6, 8,11,10, 9,10,
  116694. 17,17,12,15,15,15,12,14,14,14,10,12,15,13,12,13,
  116695. 11,10, 8,10,11,10, 8, 8,10, 9, 7, 7,10, 9, 9,11,
  116696. 11,11, 9,10,11,10, 8, 9,10, 8, 6, 8,10, 9, 9,11,
  116697. 14,13,10,12,12,11,10,10, 8, 7, 8,10,10,11,11,12,
  116698. 17,17,15,17,17,17,17,17,17,13,12,17,17,17,14,17,
  116699. };
  116700. static static_codebook _huff_book_line_128x4_class0 = {
  116701. 1, 256,
  116702. _huff_lengthlist_line_128x4_class0,
  116703. 0, 0, 0, 0, 0,
  116704. NULL,
  116705. NULL,
  116706. NULL,
  116707. NULL,
  116708. 0
  116709. };
  116710. static long _huff_lengthlist_line_128x4_0sub0[] = {
  116711. 2, 2, 2, 2,
  116712. };
  116713. static static_codebook _huff_book_line_128x4_0sub0 = {
  116714. 1, 4,
  116715. _huff_lengthlist_line_128x4_0sub0,
  116716. 0, 0, 0, 0, 0,
  116717. NULL,
  116718. NULL,
  116719. NULL,
  116720. NULL,
  116721. 0
  116722. };
  116723. static long _huff_lengthlist_line_128x4_0sub1[] = {
  116724. 0, 0, 0, 0, 3, 2, 3, 2, 3, 3,
  116725. };
  116726. static static_codebook _huff_book_line_128x4_0sub1 = {
  116727. 1, 10,
  116728. _huff_lengthlist_line_128x4_0sub1,
  116729. 0, 0, 0, 0, 0,
  116730. NULL,
  116731. NULL,
  116732. NULL,
  116733. NULL,
  116734. 0
  116735. };
  116736. static long _huff_lengthlist_line_128x4_0sub2[] = {
  116737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 4, 3, 4, 3,
  116738. 4, 4, 5, 4, 5, 4, 6, 5, 6,
  116739. };
  116740. static static_codebook _huff_book_line_128x4_0sub2 = {
  116741. 1, 25,
  116742. _huff_lengthlist_line_128x4_0sub2,
  116743. 0, 0, 0, 0, 0,
  116744. NULL,
  116745. NULL,
  116746. NULL,
  116747. NULL,
  116748. 0
  116749. };
  116750. static long _huff_lengthlist_line_128x4_0sub3[] = {
  116751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 4, 3, 5, 3, 5, 3,
  116753. 5, 4, 6, 5, 6, 5, 7, 6, 6, 7, 7, 9, 9,11,11,16,
  116754. 11,14,10,11,11,13,16,15,15,15,15,15,15,15,15,15,
  116755. };
  116756. static static_codebook _huff_book_line_128x4_0sub3 = {
  116757. 1, 64,
  116758. _huff_lengthlist_line_128x4_0sub3,
  116759. 0, 0, 0, 0, 0,
  116760. NULL,
  116761. NULL,
  116762. NULL,
  116763. NULL,
  116764. 0
  116765. };
  116766. static long _huff_lengthlist_line_256x4_class0[] = {
  116767. 6, 7, 7,12, 6, 6, 7,12, 7, 6, 6,10,15,12,11,13,
  116768. 7, 7, 8,13, 7, 7, 8,12, 7, 7, 7,11,12,12,11,13,
  116769. 10, 9, 9,11, 9, 9, 9,10,10, 8, 8,12,14,12,12,14,
  116770. 11,11,12,14,11,12,11,15,15,12,13,15,15,15,15,15,
  116771. 6, 6, 7,10, 6, 6, 6,11, 7, 6, 6, 9,14,12,11,13,
  116772. 7, 7, 7,10, 6, 6, 7, 9, 7, 7, 6,10,13,12,10,12,
  116773. 9, 9, 9,11, 9, 9, 8, 9, 9, 8, 8,10,13,12,10,12,
  116774. 12,12,11,13,12,12,11,12,15,13,12,15,15,15,14,14,
  116775. 6, 6, 6, 8, 6, 6, 5, 6, 7, 7, 6, 5,11,10, 9, 8,
  116776. 7, 6, 6, 7, 6, 6, 5, 6, 7, 7, 6, 6,11,10, 9, 8,
  116777. 8, 8, 8, 9, 8, 8, 7, 8, 8, 8, 6, 7,11,10, 9, 9,
  116778. 14,11,10,14,14,11,10,15,13,11, 9,11,15,12,12,11,
  116779. 11, 9, 8, 8,10, 9, 8, 9,11,10, 9, 8,12,11,12,11,
  116780. 13,10, 8, 9,11,10, 8, 9,10, 9, 8, 9,10, 8,12,12,
  116781. 15,11,10,10,13,11,10,10, 8, 8, 7,12,10, 9,11,12,
  116782. 15,12,11,15,13,11,11,15,12,14,11,13,15,15,13,13,
  116783. };
  116784. static static_codebook _huff_book_line_256x4_class0 = {
  116785. 1, 256,
  116786. _huff_lengthlist_line_256x4_class0,
  116787. 0, 0, 0, 0, 0,
  116788. NULL,
  116789. NULL,
  116790. NULL,
  116791. NULL,
  116792. 0
  116793. };
  116794. static long _huff_lengthlist_line_256x4_0sub0[] = {
  116795. 2, 2, 2, 2,
  116796. };
  116797. static static_codebook _huff_book_line_256x4_0sub0 = {
  116798. 1, 4,
  116799. _huff_lengthlist_line_256x4_0sub0,
  116800. 0, 0, 0, 0, 0,
  116801. NULL,
  116802. NULL,
  116803. NULL,
  116804. NULL,
  116805. 0
  116806. };
  116807. static long _huff_lengthlist_line_256x4_0sub1[] = {
  116808. 0, 0, 0, 0, 2, 2, 3, 3, 3, 3,
  116809. };
  116810. static static_codebook _huff_book_line_256x4_0sub1 = {
  116811. 1, 10,
  116812. _huff_lengthlist_line_256x4_0sub1,
  116813. 0, 0, 0, 0, 0,
  116814. NULL,
  116815. NULL,
  116816. NULL,
  116817. NULL,
  116818. 0
  116819. };
  116820. static long _huff_lengthlist_line_256x4_0sub2[] = {
  116821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 3, 4, 3, 4, 3,
  116822. 5, 3, 5, 4, 5, 4, 6, 4, 6,
  116823. };
  116824. static static_codebook _huff_book_line_256x4_0sub2 = {
  116825. 1, 25,
  116826. _huff_lengthlist_line_256x4_0sub2,
  116827. 0, 0, 0, 0, 0,
  116828. NULL,
  116829. NULL,
  116830. NULL,
  116831. NULL,
  116832. 0
  116833. };
  116834. static long _huff_lengthlist_line_256x4_0sub3[] = {
  116835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 4, 3, 5, 3, 5, 3,
  116837. 6, 4, 7, 4, 7, 5, 7, 6, 7, 6, 7, 8,10,13,13,13,
  116838. 13,13,13,13,13,13,13,13,13,13,13,12,12,12,12,12,
  116839. };
  116840. static static_codebook _huff_book_line_256x4_0sub3 = {
  116841. 1, 64,
  116842. _huff_lengthlist_line_256x4_0sub3,
  116843. 0, 0, 0, 0, 0,
  116844. NULL,
  116845. NULL,
  116846. NULL,
  116847. NULL,
  116848. 0
  116849. };
  116850. static long _huff_lengthlist_line_128x7_class0[] = {
  116851. 10, 7, 8,13, 9, 6, 7,11,10, 8, 8,12,17,17,17,17,
  116852. 7, 5, 5, 9, 6, 4, 4, 8, 8, 5, 5, 8,16,14,13,16,
  116853. 7, 5, 5, 7, 6, 3, 3, 5, 8, 5, 4, 7,14,12,12,15,
  116854. 10, 7, 8, 9, 7, 5, 5, 6, 9, 6, 5, 5,15,12, 9,10,
  116855. };
  116856. static static_codebook _huff_book_line_128x7_class0 = {
  116857. 1, 64,
  116858. _huff_lengthlist_line_128x7_class0,
  116859. 0, 0, 0, 0, 0,
  116860. NULL,
  116861. NULL,
  116862. NULL,
  116863. NULL,
  116864. 0
  116865. };
  116866. static long _huff_lengthlist_line_128x7_class1[] = {
  116867. 8,13,17,17, 8,11,17,17,11,13,17,17,17,17,17,17,
  116868. 6,10,16,17, 6,10,15,17, 8,10,16,17,17,17,17,17,
  116869. 9,13,15,17, 8,11,17,17,10,12,17,17,17,17,17,17,
  116870. 17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,
  116871. 6,11,15,17, 7,10,15,17, 8,10,17,17,17,15,17,17,
  116872. 4, 8,13,17, 4, 7,13,17, 6, 8,15,17,16,15,17,17,
  116873. 6,11,15,17, 6, 9,13,17, 8,10,17,17,15,17,17,17,
  116874. 16,17,17,17,12,14,15,17,13,14,15,17,17,17,17,17,
  116875. 5,10,14,17, 5, 9,14,17, 7, 9,15,17,15,15,17,17,
  116876. 3, 7,12,17, 3, 6,11,17, 5, 7,13,17,12,12,17,17,
  116877. 5, 9,14,17, 3, 7,11,17, 5, 8,13,17,13,11,16,17,
  116878. 12,17,17,17, 9,14,15,17,10,11,14,17,16,14,17,17,
  116879. 8,12,17,17, 8,12,17,17,10,12,17,17,17,17,17,17,
  116880. 5,10,17,17, 5, 9,15,17, 7, 9,17,17,13,13,17,17,
  116881. 7,11,17,17, 6,10,15,17, 7, 9,15,17,12,11,17,17,
  116882. 12,15,17,17,11,14,17,17,11,10,15,17,17,16,17,17,
  116883. };
  116884. static static_codebook _huff_book_line_128x7_class1 = {
  116885. 1, 256,
  116886. _huff_lengthlist_line_128x7_class1,
  116887. 0, 0, 0, 0, 0,
  116888. NULL,
  116889. NULL,
  116890. NULL,
  116891. NULL,
  116892. 0
  116893. };
  116894. static long _huff_lengthlist_line_128x7_0sub1[] = {
  116895. 0, 3, 3, 3, 3, 3, 3, 3, 3,
  116896. };
  116897. static static_codebook _huff_book_line_128x7_0sub1 = {
  116898. 1, 9,
  116899. _huff_lengthlist_line_128x7_0sub1,
  116900. 0, 0, 0, 0, 0,
  116901. NULL,
  116902. NULL,
  116903. NULL,
  116904. NULL,
  116905. 0
  116906. };
  116907. static long _huff_lengthlist_line_128x7_0sub2[] = {
  116908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 4, 4, 4, 4,
  116909. 5, 4, 5, 4, 5, 4, 6, 4, 6,
  116910. };
  116911. static static_codebook _huff_book_line_128x7_0sub2 = {
  116912. 1, 25,
  116913. _huff_lengthlist_line_128x7_0sub2,
  116914. 0, 0, 0, 0, 0,
  116915. NULL,
  116916. NULL,
  116917. NULL,
  116918. NULL,
  116919. 0
  116920. };
  116921. static long _huff_lengthlist_line_128x7_0sub3[] = {
  116922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 5, 3, 5, 3, 5, 4,
  116924. 5, 4, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  116925. 7, 8, 9,11,13,13,13,13,13,13,13,13,13,13,13,13,
  116926. };
  116927. static static_codebook _huff_book_line_128x7_0sub3 = {
  116928. 1, 64,
  116929. _huff_lengthlist_line_128x7_0sub3,
  116930. 0, 0, 0, 0, 0,
  116931. NULL,
  116932. NULL,
  116933. NULL,
  116934. NULL,
  116935. 0
  116936. };
  116937. static long _huff_lengthlist_line_128x7_1sub1[] = {
  116938. 0, 3, 3, 2, 3, 3, 4, 3, 4,
  116939. };
  116940. static static_codebook _huff_book_line_128x7_1sub1 = {
  116941. 1, 9,
  116942. _huff_lengthlist_line_128x7_1sub1,
  116943. 0, 0, 0, 0, 0,
  116944. NULL,
  116945. NULL,
  116946. NULL,
  116947. NULL,
  116948. 0
  116949. };
  116950. static long _huff_lengthlist_line_128x7_1sub2[] = {
  116951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 3, 6, 3, 6, 3,
  116952. 6, 3, 7, 3, 8, 4, 9, 4, 9,
  116953. };
  116954. static static_codebook _huff_book_line_128x7_1sub2 = {
  116955. 1, 25,
  116956. _huff_lengthlist_line_128x7_1sub2,
  116957. 0, 0, 0, 0, 0,
  116958. NULL,
  116959. NULL,
  116960. NULL,
  116961. NULL,
  116962. 0
  116963. };
  116964. static long _huff_lengthlist_line_128x7_1sub3[] = {
  116965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 7, 2, 7, 3, 8, 4,
  116967. 9, 5, 9, 8,10,11,11,12,14,14,14,14,14,14,14,14,
  116968. 14,14,14,14,14,14,14,14,14,14,14,14,13,13,13,13,
  116969. };
  116970. static static_codebook _huff_book_line_128x7_1sub3 = {
  116971. 1, 64,
  116972. _huff_lengthlist_line_128x7_1sub3,
  116973. 0, 0, 0, 0, 0,
  116974. NULL,
  116975. NULL,
  116976. NULL,
  116977. NULL,
  116978. 0
  116979. };
  116980. static long _huff_lengthlist_line_128x11_class1[] = {
  116981. 1, 6, 3, 7, 2, 4, 5, 7,
  116982. };
  116983. static static_codebook _huff_book_line_128x11_class1 = {
  116984. 1, 8,
  116985. _huff_lengthlist_line_128x11_class1,
  116986. 0, 0, 0, 0, 0,
  116987. NULL,
  116988. NULL,
  116989. NULL,
  116990. NULL,
  116991. 0
  116992. };
  116993. static long _huff_lengthlist_line_128x11_class2[] = {
  116994. 1, 6,12,16, 4,12,15,16, 9,15,16,16,16,16,16,16,
  116995. 2, 5,11,16, 5,11,13,16, 9,13,16,16,16,16,16,16,
  116996. 4, 8,12,16, 5, 9,12,16, 9,13,15,16,16,16,16,16,
  116997. 15,16,16,16,11,14,13,16,12,15,16,16,16,16,16,15,
  116998. };
  116999. static static_codebook _huff_book_line_128x11_class2 = {
  117000. 1, 64,
  117001. _huff_lengthlist_line_128x11_class2,
  117002. 0, 0, 0, 0, 0,
  117003. NULL,
  117004. NULL,
  117005. NULL,
  117006. NULL,
  117007. 0
  117008. };
  117009. static long _huff_lengthlist_line_128x11_class3[] = {
  117010. 7, 6, 9,17, 7, 6, 8,17,12, 9,11,16,16,16,16,16,
  117011. 5, 4, 7,16, 5, 3, 6,14, 9, 6, 8,15,16,16,16,16,
  117012. 5, 4, 6,13, 3, 2, 4,11, 7, 4, 6,13,16,11,10,14,
  117013. 12,12,12,16, 9, 7,10,15,12, 9,11,16,16,15,15,16,
  117014. };
  117015. static static_codebook _huff_book_line_128x11_class3 = {
  117016. 1, 64,
  117017. _huff_lengthlist_line_128x11_class3,
  117018. 0, 0, 0, 0, 0,
  117019. NULL,
  117020. NULL,
  117021. NULL,
  117022. NULL,
  117023. 0
  117024. };
  117025. static long _huff_lengthlist_line_128x11_0sub0[] = {
  117026. 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  117027. 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 6, 6, 6, 7, 6,
  117028. 7, 6, 7, 6, 7, 6, 7, 6, 7, 6, 8, 6, 8, 6, 8, 7,
  117029. 8, 7, 8, 7, 8, 7, 9, 7, 9, 8, 9, 8, 9, 8,10, 8,
  117030. 10, 9,10, 9,10, 9,11, 9,11, 9,10,10,11,10,11,10,
  117031. 11,11,11,11,11,11,12,13,14,14,14,15,15,16,16,16,
  117032. 17,15,16,15,16,16,17,17,16,17,17,17,17,17,17,17,
  117033. 17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,
  117034. };
  117035. static static_codebook _huff_book_line_128x11_0sub0 = {
  117036. 1, 128,
  117037. _huff_lengthlist_line_128x11_0sub0,
  117038. 0, 0, 0, 0, 0,
  117039. NULL,
  117040. NULL,
  117041. NULL,
  117042. NULL,
  117043. 0
  117044. };
  117045. static long _huff_lengthlist_line_128x11_1sub0[] = {
  117046. 2, 5, 5, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5, 5, 5, 5,
  117047. 6, 5, 6, 5, 6, 5, 7, 6, 7, 6, 7, 6, 8, 6, 8, 6,
  117048. };
  117049. static static_codebook _huff_book_line_128x11_1sub0 = {
  117050. 1, 32,
  117051. _huff_lengthlist_line_128x11_1sub0,
  117052. 0, 0, 0, 0, 0,
  117053. NULL,
  117054. NULL,
  117055. NULL,
  117056. NULL,
  117057. 0
  117058. };
  117059. static long _huff_lengthlist_line_128x11_1sub1[] = {
  117060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117062. 5, 3, 5, 3, 6, 4, 6, 4, 7, 4, 7, 4, 7, 4, 8, 4,
  117063. 8, 4, 9, 5, 9, 5, 9, 5, 9, 6,10, 6,10, 6,11, 7,
  117064. 10, 7,10, 8,11, 9,11, 9,11,10,11,11,12,11,11,12,
  117065. 15,15,12,14,11,14,12,14,11,14,13,14,12,14,11,14,
  117066. 11,14,12,14,11,14,11,14,13,13,14,14,14,14,14,14,
  117067. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  117068. };
  117069. static static_codebook _huff_book_line_128x11_1sub1 = {
  117070. 1, 128,
  117071. _huff_lengthlist_line_128x11_1sub1,
  117072. 0, 0, 0, 0, 0,
  117073. NULL,
  117074. NULL,
  117075. NULL,
  117076. NULL,
  117077. 0
  117078. };
  117079. static long _huff_lengthlist_line_128x11_2sub1[] = {
  117080. 0, 4, 5, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4, 4, 4,
  117081. 5, 5,
  117082. };
  117083. static static_codebook _huff_book_line_128x11_2sub1 = {
  117084. 1, 18,
  117085. _huff_lengthlist_line_128x11_2sub1,
  117086. 0, 0, 0, 0, 0,
  117087. NULL,
  117088. NULL,
  117089. NULL,
  117090. NULL,
  117091. 0
  117092. };
  117093. static long _huff_lengthlist_line_128x11_2sub2[] = {
  117094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117095. 0, 0, 3, 3, 3, 4, 4, 4, 4, 5, 4, 5, 4, 6, 5, 7,
  117096. 5, 7, 6, 8, 6, 8, 6, 9, 7, 9, 7,10, 7, 9, 8,11,
  117097. 8,11,
  117098. };
  117099. static static_codebook _huff_book_line_128x11_2sub2 = {
  117100. 1, 50,
  117101. _huff_lengthlist_line_128x11_2sub2,
  117102. 0, 0, 0, 0, 0,
  117103. NULL,
  117104. NULL,
  117105. NULL,
  117106. NULL,
  117107. 0
  117108. };
  117109. static long _huff_lengthlist_line_128x11_2sub3[] = {
  117110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117113. 0, 0, 4, 8, 3, 8, 4, 8, 4, 8, 6, 8, 5, 8, 4, 8,
  117114. 4, 8, 6, 8, 7, 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  117115. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  117116. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  117117. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  117118. };
  117119. static static_codebook _huff_book_line_128x11_2sub3 = {
  117120. 1, 128,
  117121. _huff_lengthlist_line_128x11_2sub3,
  117122. 0, 0, 0, 0, 0,
  117123. NULL,
  117124. NULL,
  117125. NULL,
  117126. NULL,
  117127. 0
  117128. };
  117129. static long _huff_lengthlist_line_128x11_3sub1[] = {
  117130. 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 4,
  117131. 5, 4,
  117132. };
  117133. static static_codebook _huff_book_line_128x11_3sub1 = {
  117134. 1, 18,
  117135. _huff_lengthlist_line_128x11_3sub1,
  117136. 0, 0, 0, 0, 0,
  117137. NULL,
  117138. NULL,
  117139. NULL,
  117140. NULL,
  117141. 0
  117142. };
  117143. static long _huff_lengthlist_line_128x11_3sub2[] = {
  117144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117145. 0, 0, 5, 3, 5, 4, 6, 4, 6, 4, 7, 4, 7, 4, 8, 4,
  117146. 8, 4, 9, 4, 9, 4,10, 4,10, 5,10, 5,11, 5,12, 6,
  117147. 12, 6,
  117148. };
  117149. static static_codebook _huff_book_line_128x11_3sub2 = {
  117150. 1, 50,
  117151. _huff_lengthlist_line_128x11_3sub2,
  117152. 0, 0, 0, 0, 0,
  117153. NULL,
  117154. NULL,
  117155. NULL,
  117156. NULL,
  117157. 0
  117158. };
  117159. static long _huff_lengthlist_line_128x11_3sub3[] = {
  117160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117163. 0, 0, 7, 1, 6, 3, 7, 3, 8, 4, 8, 5, 8, 8, 8, 9,
  117164. 7, 8, 8, 7, 7, 7, 8, 9,10, 9, 9,10,10,10,10,10,
  117165. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  117166. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  117167. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  117168. };
  117169. static static_codebook _huff_book_line_128x11_3sub3 = {
  117170. 1, 128,
  117171. _huff_lengthlist_line_128x11_3sub3,
  117172. 0, 0, 0, 0, 0,
  117173. NULL,
  117174. NULL,
  117175. NULL,
  117176. NULL,
  117177. 0
  117178. };
  117179. static long _huff_lengthlist_line_128x17_class1[] = {
  117180. 1, 3, 4, 7, 2, 5, 6, 7,
  117181. };
  117182. static static_codebook _huff_book_line_128x17_class1 = {
  117183. 1, 8,
  117184. _huff_lengthlist_line_128x17_class1,
  117185. 0, 0, 0, 0, 0,
  117186. NULL,
  117187. NULL,
  117188. NULL,
  117189. NULL,
  117190. 0
  117191. };
  117192. static long _huff_lengthlist_line_128x17_class2[] = {
  117193. 1, 4,10,19, 3, 8,13,19, 7,12,19,19,19,19,19,19,
  117194. 2, 6,11,19, 8,13,19,19, 9,11,19,19,19,19,19,19,
  117195. 6, 7,13,19, 9,13,19,19,10,13,18,18,18,18,18,18,
  117196. 18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,
  117197. };
  117198. static static_codebook _huff_book_line_128x17_class2 = {
  117199. 1, 64,
  117200. _huff_lengthlist_line_128x17_class2,
  117201. 0, 0, 0, 0, 0,
  117202. NULL,
  117203. NULL,
  117204. NULL,
  117205. NULL,
  117206. 0
  117207. };
  117208. static long _huff_lengthlist_line_128x17_class3[] = {
  117209. 3, 6,10,17, 4, 8,11,20, 8,10,11,20,20,20,20,20,
  117210. 2, 4, 8,18, 4, 6, 8,17, 7, 8,10,20,20,17,20,20,
  117211. 3, 5, 8,17, 3, 4, 6,17, 8, 8,10,17,17,12,16,20,
  117212. 13,13,15,20,10,10,12,20,15,14,15,20,20,20,19,19,
  117213. };
  117214. static static_codebook _huff_book_line_128x17_class3 = {
  117215. 1, 64,
  117216. _huff_lengthlist_line_128x17_class3,
  117217. 0, 0, 0, 0, 0,
  117218. NULL,
  117219. NULL,
  117220. NULL,
  117221. NULL,
  117222. 0
  117223. };
  117224. static long _huff_lengthlist_line_128x17_0sub0[] = {
  117225. 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  117226. 7, 5, 7, 5, 7, 5, 7, 5, 7, 5, 7, 5, 8, 5, 8, 5,
  117227. 8, 5, 8, 5, 8, 6, 8, 6, 8, 6, 9, 6, 9, 6, 9, 6,
  117228. 9, 6, 9, 7, 9, 7, 9, 7, 9, 7,10, 7,10, 8,10, 8,
  117229. 10, 8,10, 8,10, 8,11, 8,11, 8,11, 8,11, 8,11, 9,
  117230. 12, 9,12, 9,12, 9,12, 9,12,10,12,10,13,11,13,11,
  117231. 14,12,14,13,15,14,16,14,17,15,18,16,20,20,20,20,
  117232. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  117233. };
  117234. static static_codebook _huff_book_line_128x17_0sub0 = {
  117235. 1, 128,
  117236. _huff_lengthlist_line_128x17_0sub0,
  117237. 0, 0, 0, 0, 0,
  117238. NULL,
  117239. NULL,
  117240. NULL,
  117241. NULL,
  117242. 0
  117243. };
  117244. static long _huff_lengthlist_line_128x17_1sub0[] = {
  117245. 2, 5, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  117246. 6, 5, 6, 5, 7, 6, 7, 6, 7, 6, 8, 6, 9, 7, 9, 7,
  117247. };
  117248. static static_codebook _huff_book_line_128x17_1sub0 = {
  117249. 1, 32,
  117250. _huff_lengthlist_line_128x17_1sub0,
  117251. 0, 0, 0, 0, 0,
  117252. NULL,
  117253. NULL,
  117254. NULL,
  117255. NULL,
  117256. 0
  117257. };
  117258. static long _huff_lengthlist_line_128x17_1sub1[] = {
  117259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117261. 4, 3, 5, 3, 5, 3, 6, 3, 6, 4, 6, 4, 7, 4, 7, 5,
  117262. 8, 5, 8, 6, 9, 7, 9, 7, 9, 8,10, 9,10, 9,11,10,
  117263. 11,11,11,11,11,11,12,12,12,13,12,13,12,14,12,15,
  117264. 12,14,12,16,13,17,13,17,14,17,14,16,13,17,14,17,
  117265. 14,17,15,17,15,15,16,17,17,17,17,17,17,17,17,17,
  117266. 17,17,17,17,17,17,16,16,16,16,16,16,16,16,16,16,
  117267. };
  117268. static static_codebook _huff_book_line_128x17_1sub1 = {
  117269. 1, 128,
  117270. _huff_lengthlist_line_128x17_1sub1,
  117271. 0, 0, 0, 0, 0,
  117272. NULL,
  117273. NULL,
  117274. NULL,
  117275. NULL,
  117276. 0
  117277. };
  117278. static long _huff_lengthlist_line_128x17_2sub1[] = {
  117279. 0, 4, 5, 4, 6, 4, 8, 3, 9, 3, 9, 2, 9, 3, 8, 4,
  117280. 9, 4,
  117281. };
  117282. static static_codebook _huff_book_line_128x17_2sub1 = {
  117283. 1, 18,
  117284. _huff_lengthlist_line_128x17_2sub1,
  117285. 0, 0, 0, 0, 0,
  117286. NULL,
  117287. NULL,
  117288. NULL,
  117289. NULL,
  117290. 0
  117291. };
  117292. static long _huff_lengthlist_line_128x17_2sub2[] = {
  117293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117294. 0, 0, 5, 1, 5, 3, 5, 3, 5, 4, 7, 5,10, 7,10, 7,
  117295. 12,10,14,10,14, 9,14,11,14,14,14,13,13,13,13,13,
  117296. 13,13,
  117297. };
  117298. static static_codebook _huff_book_line_128x17_2sub2 = {
  117299. 1, 50,
  117300. _huff_lengthlist_line_128x17_2sub2,
  117301. 0, 0, 0, 0, 0,
  117302. NULL,
  117303. NULL,
  117304. NULL,
  117305. NULL,
  117306. 0
  117307. };
  117308. static long _huff_lengthlist_line_128x17_2sub3[] = {
  117309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117312. 0, 0, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  117313. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 6, 6,
  117314. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  117315. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  117316. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  117317. };
  117318. static static_codebook _huff_book_line_128x17_2sub3 = {
  117319. 1, 128,
  117320. _huff_lengthlist_line_128x17_2sub3,
  117321. 0, 0, 0, 0, 0,
  117322. NULL,
  117323. NULL,
  117324. NULL,
  117325. NULL,
  117326. 0
  117327. };
  117328. static long _huff_lengthlist_line_128x17_3sub1[] = {
  117329. 0, 4, 4, 4, 4, 4, 4, 4, 5, 3, 5, 3, 5, 4, 6, 4,
  117330. 6, 4,
  117331. };
  117332. static static_codebook _huff_book_line_128x17_3sub1 = {
  117333. 1, 18,
  117334. _huff_lengthlist_line_128x17_3sub1,
  117335. 0, 0, 0, 0, 0,
  117336. NULL,
  117337. NULL,
  117338. NULL,
  117339. NULL,
  117340. 0
  117341. };
  117342. static long _huff_lengthlist_line_128x17_3sub2[] = {
  117343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117344. 0, 0, 5, 3, 6, 3, 6, 4, 7, 4, 7, 4, 7, 4, 8, 4,
  117345. 8, 4, 8, 4, 8, 4, 9, 4, 9, 5,10, 5,10, 7,10, 8,
  117346. 10, 8,
  117347. };
  117348. static static_codebook _huff_book_line_128x17_3sub2 = {
  117349. 1, 50,
  117350. _huff_lengthlist_line_128x17_3sub2,
  117351. 0, 0, 0, 0, 0,
  117352. NULL,
  117353. NULL,
  117354. NULL,
  117355. NULL,
  117356. 0
  117357. };
  117358. static long _huff_lengthlist_line_128x17_3sub3[] = {
  117359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117362. 0, 0, 3, 2, 4, 3, 4, 4, 4, 5, 4, 7, 5, 8, 5,11,
  117363. 6,10, 6,12, 7,12, 7,12, 8,12, 8,12,10,12,12,12,
  117364. 12,12,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  117365. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  117366. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  117367. };
  117368. static static_codebook _huff_book_line_128x17_3sub3 = {
  117369. 1, 128,
  117370. _huff_lengthlist_line_128x17_3sub3,
  117371. 0, 0, 0, 0, 0,
  117372. NULL,
  117373. NULL,
  117374. NULL,
  117375. NULL,
  117376. 0
  117377. };
  117378. static long _huff_lengthlist_line_1024x27_class1[] = {
  117379. 2,10, 8,14, 7,12,11,14, 1, 5, 3, 7, 4, 9, 7,13,
  117380. };
  117381. static static_codebook _huff_book_line_1024x27_class1 = {
  117382. 1, 16,
  117383. _huff_lengthlist_line_1024x27_class1,
  117384. 0, 0, 0, 0, 0,
  117385. NULL,
  117386. NULL,
  117387. NULL,
  117388. NULL,
  117389. 0
  117390. };
  117391. static long _huff_lengthlist_line_1024x27_class2[] = {
  117392. 1, 4, 2, 6, 3, 7, 5, 7,
  117393. };
  117394. static static_codebook _huff_book_line_1024x27_class2 = {
  117395. 1, 8,
  117396. _huff_lengthlist_line_1024x27_class2,
  117397. 0, 0, 0, 0, 0,
  117398. NULL,
  117399. NULL,
  117400. NULL,
  117401. NULL,
  117402. 0
  117403. };
  117404. static long _huff_lengthlist_line_1024x27_class3[] = {
  117405. 1, 5, 7,21, 5, 8, 9,21,10, 9,12,20,20,16,20,20,
  117406. 4, 8, 9,20, 6, 8, 9,20,11,11,13,20,20,15,17,20,
  117407. 9,11,14,20, 8,10,15,20,11,13,15,20,20,20,20,20,
  117408. 20,20,20,20,13,20,20,20,18,18,20,20,20,20,20,20,
  117409. 3, 6, 8,20, 6, 7, 9,20,10, 9,12,20,20,20,20,20,
  117410. 5, 7, 9,20, 6, 6, 9,20,10, 9,12,20,20,20,20,20,
  117411. 8,10,13,20, 8, 9,12,20,11,10,12,20,20,20,20,20,
  117412. 18,20,20,20,15,17,18,20,18,17,18,20,20,20,20,20,
  117413. 7,10,12,20, 8, 9,11,20,14,13,14,20,20,20,20,20,
  117414. 6, 9,12,20, 7, 8,11,20,12,11,13,20,20,20,20,20,
  117415. 9,11,15,20, 8,10,14,20,12,11,14,20,20,20,20,20,
  117416. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  117417. 11,16,18,20,15,15,17,20,20,17,20,20,20,20,20,20,
  117418. 9,14,16,20,12,12,15,20,17,15,18,20,20,20,20,20,
  117419. 16,19,18,20,15,16,20,20,17,17,20,20,20,20,20,20,
  117420. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  117421. };
  117422. static static_codebook _huff_book_line_1024x27_class3 = {
  117423. 1, 256,
  117424. _huff_lengthlist_line_1024x27_class3,
  117425. 0, 0, 0, 0, 0,
  117426. NULL,
  117427. NULL,
  117428. NULL,
  117429. NULL,
  117430. 0
  117431. };
  117432. static long _huff_lengthlist_line_1024x27_class4[] = {
  117433. 2, 3, 7,13, 4, 4, 7,15, 8, 6, 9,17,21,16,15,21,
  117434. 2, 5, 7,11, 5, 5, 7,14, 9, 7,10,16,17,15,16,21,
  117435. 4, 7,10,17, 7, 7, 9,15,11, 9,11,16,21,18,15,21,
  117436. 18,21,21,21,15,17,17,19,21,19,18,20,21,21,21,20,
  117437. };
  117438. static static_codebook _huff_book_line_1024x27_class4 = {
  117439. 1, 64,
  117440. _huff_lengthlist_line_1024x27_class4,
  117441. 0, 0, 0, 0, 0,
  117442. NULL,
  117443. NULL,
  117444. NULL,
  117445. NULL,
  117446. 0
  117447. };
  117448. static long _huff_lengthlist_line_1024x27_0sub0[] = {
  117449. 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  117450. 6, 5, 6, 5, 6, 5, 6, 5, 7, 5, 7, 5, 7, 5, 7, 5,
  117451. 8, 6, 8, 6, 8, 6, 9, 6, 9, 6,10, 6,10, 6,11, 6,
  117452. 11, 7,11, 7,12, 7,12, 7,12, 7,12, 7,12, 7,12, 7,
  117453. 12, 7,12, 8,13, 8,12, 8,12, 8,13, 8,13, 9,13, 9,
  117454. 13, 9,13, 9,12,10,12,10,13,10,14,11,14,12,14,13,
  117455. 14,13,14,14,15,16,15,15,15,14,15,17,21,22,22,21,
  117456. 22,22,22,22,22,22,21,21,21,21,21,21,21,21,21,21,
  117457. };
  117458. static static_codebook _huff_book_line_1024x27_0sub0 = {
  117459. 1, 128,
  117460. _huff_lengthlist_line_1024x27_0sub0,
  117461. 0, 0, 0, 0, 0,
  117462. NULL,
  117463. NULL,
  117464. NULL,
  117465. NULL,
  117466. 0
  117467. };
  117468. static long _huff_lengthlist_line_1024x27_1sub0[] = {
  117469. 2, 5, 5, 4, 5, 4, 5, 4, 5, 4, 6, 5, 6, 5, 6, 5,
  117470. 6, 5, 7, 5, 7, 6, 8, 6, 8, 6, 8, 6, 9, 6, 9, 6,
  117471. };
  117472. static static_codebook _huff_book_line_1024x27_1sub0 = {
  117473. 1, 32,
  117474. _huff_lengthlist_line_1024x27_1sub0,
  117475. 0, 0, 0, 0, 0,
  117476. NULL,
  117477. NULL,
  117478. NULL,
  117479. NULL,
  117480. 0
  117481. };
  117482. static long _huff_lengthlist_line_1024x27_1sub1[] = {
  117483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117485. 8, 5, 8, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 4,
  117486. 9, 4, 9, 4, 9, 4, 8, 4, 8, 4, 9, 5, 9, 5, 9, 5,
  117487. 9, 5, 9, 6,10, 6,10, 7,10, 8,11, 9,11,11,12,13,
  117488. 12,14,13,15,13,15,14,16,14,17,15,17,15,15,16,16,
  117489. 15,16,16,16,15,18,16,15,17,17,19,19,19,19,19,19,
  117490. 19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,
  117491. };
  117492. static static_codebook _huff_book_line_1024x27_1sub1 = {
  117493. 1, 128,
  117494. _huff_lengthlist_line_1024x27_1sub1,
  117495. 0, 0, 0, 0, 0,
  117496. NULL,
  117497. NULL,
  117498. NULL,
  117499. NULL,
  117500. 0
  117501. };
  117502. static long _huff_lengthlist_line_1024x27_2sub0[] = {
  117503. 1, 5, 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  117504. 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 9, 8,10, 9,10, 9,
  117505. };
  117506. static static_codebook _huff_book_line_1024x27_2sub0 = {
  117507. 1, 32,
  117508. _huff_lengthlist_line_1024x27_2sub0,
  117509. 0, 0, 0, 0, 0,
  117510. NULL,
  117511. NULL,
  117512. NULL,
  117513. NULL,
  117514. 0
  117515. };
  117516. static long _huff_lengthlist_line_1024x27_2sub1[] = {
  117517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117519. 4, 3, 4, 3, 4, 4, 5, 4, 5, 4, 5, 5, 6, 5, 6, 5,
  117520. 7, 5, 7, 6, 7, 6, 8, 7, 8, 7, 8, 7, 9, 8, 9, 9,
  117521. 9, 9,10,10,10,11, 9,12, 9,12, 9,15,10,14, 9,13,
  117522. 10,13,10,12,10,12,10,13,10,12,11,13,11,14,12,13,
  117523. 13,14,14,13,14,15,14,16,13,13,14,16,16,16,16,16,
  117524. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,15,15,
  117525. };
  117526. static static_codebook _huff_book_line_1024x27_2sub1 = {
  117527. 1, 128,
  117528. _huff_lengthlist_line_1024x27_2sub1,
  117529. 0, 0, 0, 0, 0,
  117530. NULL,
  117531. NULL,
  117532. NULL,
  117533. NULL,
  117534. 0
  117535. };
  117536. static long _huff_lengthlist_line_1024x27_3sub1[] = {
  117537. 0, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4, 4, 4, 4, 5,
  117538. 5, 5,
  117539. };
  117540. static static_codebook _huff_book_line_1024x27_3sub1 = {
  117541. 1, 18,
  117542. _huff_lengthlist_line_1024x27_3sub1,
  117543. 0, 0, 0, 0, 0,
  117544. NULL,
  117545. NULL,
  117546. NULL,
  117547. NULL,
  117548. 0
  117549. };
  117550. static long _huff_lengthlist_line_1024x27_3sub2[] = {
  117551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117552. 0, 0, 3, 3, 4, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5, 6,
  117553. 5, 7, 5, 8, 6, 8, 6, 9, 7,10, 7,10, 8,10, 8,11,
  117554. 9,11,
  117555. };
  117556. static static_codebook _huff_book_line_1024x27_3sub2 = {
  117557. 1, 50,
  117558. _huff_lengthlist_line_1024x27_3sub2,
  117559. 0, 0, 0, 0, 0,
  117560. NULL,
  117561. NULL,
  117562. NULL,
  117563. NULL,
  117564. 0
  117565. };
  117566. static long _huff_lengthlist_line_1024x27_3sub3[] = {
  117567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117570. 0, 0, 3, 7, 3, 8, 3,10, 3, 8, 3, 9, 3, 8, 4, 9,
  117571. 4, 9, 5, 9, 6,10, 6, 9, 7,11, 7,12, 9,13,10,13,
  117572. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  117573. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  117574. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  117575. };
  117576. static static_codebook _huff_book_line_1024x27_3sub3 = {
  117577. 1, 128,
  117578. _huff_lengthlist_line_1024x27_3sub3,
  117579. 0, 0, 0, 0, 0,
  117580. NULL,
  117581. NULL,
  117582. NULL,
  117583. NULL,
  117584. 0
  117585. };
  117586. static long _huff_lengthlist_line_1024x27_4sub1[] = {
  117587. 0, 4, 5, 4, 5, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4,
  117588. 5, 4,
  117589. };
  117590. static static_codebook _huff_book_line_1024x27_4sub1 = {
  117591. 1, 18,
  117592. _huff_lengthlist_line_1024x27_4sub1,
  117593. 0, 0, 0, 0, 0,
  117594. NULL,
  117595. NULL,
  117596. NULL,
  117597. NULL,
  117598. 0
  117599. };
  117600. static long _huff_lengthlist_line_1024x27_4sub2[] = {
  117601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117602. 0, 0, 4, 2, 4, 2, 5, 3, 5, 4, 6, 6, 6, 7, 7, 8,
  117603. 7, 8, 7, 8, 7, 9, 8, 9, 8, 9, 8,10, 8,11, 9,12,
  117604. 9,12,
  117605. };
  117606. static static_codebook _huff_book_line_1024x27_4sub2 = {
  117607. 1, 50,
  117608. _huff_lengthlist_line_1024x27_4sub2,
  117609. 0, 0, 0, 0, 0,
  117610. NULL,
  117611. NULL,
  117612. NULL,
  117613. NULL,
  117614. 0
  117615. };
  117616. static long _huff_lengthlist_line_1024x27_4sub3[] = {
  117617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117620. 0, 0, 2, 5, 2, 6, 3, 6, 4, 7, 4, 7, 5, 9, 5,11,
  117621. 6,11, 6,11, 7,11, 6,11, 6,11, 9,11, 8,11,11,11,
  117622. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  117623. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  117624. 11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,
  117625. };
  117626. static static_codebook _huff_book_line_1024x27_4sub3 = {
  117627. 1, 128,
  117628. _huff_lengthlist_line_1024x27_4sub3,
  117629. 0, 0, 0, 0, 0,
  117630. NULL,
  117631. NULL,
  117632. NULL,
  117633. NULL,
  117634. 0
  117635. };
  117636. static long _huff_lengthlist_line_2048x27_class1[] = {
  117637. 2, 6, 8, 9, 7,11,13,13, 1, 3, 5, 5, 6, 6,12,10,
  117638. };
  117639. static static_codebook _huff_book_line_2048x27_class1 = {
  117640. 1, 16,
  117641. _huff_lengthlist_line_2048x27_class1,
  117642. 0, 0, 0, 0, 0,
  117643. NULL,
  117644. NULL,
  117645. NULL,
  117646. NULL,
  117647. 0
  117648. };
  117649. static long _huff_lengthlist_line_2048x27_class2[] = {
  117650. 1, 2, 3, 6, 4, 7, 5, 7,
  117651. };
  117652. static static_codebook _huff_book_line_2048x27_class2 = {
  117653. 1, 8,
  117654. _huff_lengthlist_line_2048x27_class2,
  117655. 0, 0, 0, 0, 0,
  117656. NULL,
  117657. NULL,
  117658. NULL,
  117659. NULL,
  117660. 0
  117661. };
  117662. static long _huff_lengthlist_line_2048x27_class3[] = {
  117663. 3, 3, 6,16, 5, 5, 7,16, 9, 8,11,16,16,16,16,16,
  117664. 5, 5, 8,16, 5, 5, 7,16, 8, 7, 9,16,16,16,16,16,
  117665. 9, 9,12,16, 6, 8,11,16, 9,10,11,16,16,16,16,16,
  117666. 16,16,16,16,13,16,16,16,15,16,16,16,16,16,16,16,
  117667. 5, 4, 7,16, 6, 5, 8,16, 9, 8,10,16,16,16,16,16,
  117668. 5, 5, 7,15, 5, 4, 6,15, 7, 6, 8,16,16,16,16,16,
  117669. 9, 9,11,15, 7, 7, 9,16, 8, 8, 9,16,16,16,16,16,
  117670. 16,16,16,16,15,15,15,16,15,15,14,16,16,16,16,16,
  117671. 8, 8,11,16, 8, 9,10,16,11,10,14,16,16,16,16,16,
  117672. 6, 8,10,16, 6, 7,10,16, 8, 8,11,16,14,16,16,16,
  117673. 10,11,14,16, 9, 9,11,16,10,10,11,16,16,16,16,16,
  117674. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  117675. 16,16,16,16,15,16,16,16,16,16,16,16,16,16,16,16,
  117676. 12,16,15,16,12,14,16,16,16,16,16,16,16,16,16,16,
  117677. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  117678. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  117679. };
  117680. static static_codebook _huff_book_line_2048x27_class3 = {
  117681. 1, 256,
  117682. _huff_lengthlist_line_2048x27_class3,
  117683. 0, 0, 0, 0, 0,
  117684. NULL,
  117685. NULL,
  117686. NULL,
  117687. NULL,
  117688. 0
  117689. };
  117690. static long _huff_lengthlist_line_2048x27_class4[] = {
  117691. 2, 4, 7,13, 4, 5, 7,15, 8, 7,10,16,16,14,16,16,
  117692. 2, 4, 7,16, 3, 4, 7,14, 8, 8,10,16,16,16,15,16,
  117693. 6, 8,11,16, 7, 7, 9,16,11, 9,13,16,16,16,15,16,
  117694. 16,16,16,16,14,16,16,16,16,16,16,16,16,16,16,16,
  117695. };
  117696. static static_codebook _huff_book_line_2048x27_class4 = {
  117697. 1, 64,
  117698. _huff_lengthlist_line_2048x27_class4,
  117699. 0, 0, 0, 0, 0,
  117700. NULL,
  117701. NULL,
  117702. NULL,
  117703. NULL,
  117704. 0
  117705. };
  117706. static long _huff_lengthlist_line_2048x27_0sub0[] = {
  117707. 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  117708. 6, 5, 7, 5, 7, 5, 7, 5, 8, 5, 8, 5, 8, 5, 9, 5,
  117709. 9, 6,10, 6,10, 6,11, 6,11, 6,11, 6,11, 6,11, 6,
  117710. 11, 6,11, 6,12, 7,11, 7,11, 7,11, 7,11, 7,10, 7,
  117711. 11, 7,11, 7,12, 7,11, 8,11, 8,11, 8,11, 8,13, 8,
  117712. 12, 9,11, 9,11, 9,11,10,12,10,12, 9,12,10,12,11,
  117713. 14,12,16,12,12,11,14,16,17,17,17,17,17,17,17,17,
  117714. 17,17,17,17,17,17,17,17,17,17,17,17,16,16,16,16,
  117715. };
  117716. static static_codebook _huff_book_line_2048x27_0sub0 = {
  117717. 1, 128,
  117718. _huff_lengthlist_line_2048x27_0sub0,
  117719. 0, 0, 0, 0, 0,
  117720. NULL,
  117721. NULL,
  117722. NULL,
  117723. NULL,
  117724. 0
  117725. };
  117726. static long _huff_lengthlist_line_2048x27_1sub0[] = {
  117727. 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5,
  117728. 5, 5, 6, 6, 6, 6, 6, 6, 7, 6, 7, 6, 7, 6, 7, 6,
  117729. };
  117730. static static_codebook _huff_book_line_2048x27_1sub0 = {
  117731. 1, 32,
  117732. _huff_lengthlist_line_2048x27_1sub0,
  117733. 0, 0, 0, 0, 0,
  117734. NULL,
  117735. NULL,
  117736. NULL,
  117737. NULL,
  117738. 0
  117739. };
  117740. static long _huff_lengthlist_line_2048x27_1sub1[] = {
  117741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117743. 6, 5, 7, 5, 7, 4, 7, 4, 8, 4, 8, 4, 8, 4, 8, 3,
  117744. 8, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 5, 9, 5, 9, 6,
  117745. 9, 7, 9, 8, 9, 9, 9,10, 9,11, 9,14, 9,15,10,15,
  117746. 10,15,10,15,10,15,11,15,10,14,12,14,11,14,13,14,
  117747. 13,15,15,15,12,15,15,15,13,15,13,15,13,15,15,15,
  117748. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,14,
  117749. };
  117750. static static_codebook _huff_book_line_2048x27_1sub1 = {
  117751. 1, 128,
  117752. _huff_lengthlist_line_2048x27_1sub1,
  117753. 0, 0, 0, 0, 0,
  117754. NULL,
  117755. NULL,
  117756. NULL,
  117757. NULL,
  117758. 0
  117759. };
  117760. static long _huff_lengthlist_line_2048x27_2sub0[] = {
  117761. 2, 4, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  117762. 6, 5, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  117763. };
  117764. static static_codebook _huff_book_line_2048x27_2sub0 = {
  117765. 1, 32,
  117766. _huff_lengthlist_line_2048x27_2sub0,
  117767. 0, 0, 0, 0, 0,
  117768. NULL,
  117769. NULL,
  117770. NULL,
  117771. NULL,
  117772. 0
  117773. };
  117774. static long _huff_lengthlist_line_2048x27_2sub1[] = {
  117775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117777. 3, 4, 3, 4, 3, 4, 4, 5, 4, 5, 5, 5, 6, 6, 6, 7,
  117778. 6, 8, 6, 8, 6, 9, 7,10, 7,10, 7,10, 7,12, 7,12,
  117779. 7,12, 9,12,11,12,10,12,10,12,11,12,12,12,10,12,
  117780. 10,12,10,12, 9,12,11,12,12,12,12,12,11,12,11,12,
  117781. 12,12,12,12,12,12,12,12,10,10,12,12,12,12,12,10,
  117782. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  117783. };
  117784. static static_codebook _huff_book_line_2048x27_2sub1 = {
  117785. 1, 128,
  117786. _huff_lengthlist_line_2048x27_2sub1,
  117787. 0, 0, 0, 0, 0,
  117788. NULL,
  117789. NULL,
  117790. NULL,
  117791. NULL,
  117792. 0
  117793. };
  117794. static long _huff_lengthlist_line_2048x27_3sub1[] = {
  117795. 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
  117796. 5, 5,
  117797. };
  117798. static static_codebook _huff_book_line_2048x27_3sub1 = {
  117799. 1, 18,
  117800. _huff_lengthlist_line_2048x27_3sub1,
  117801. 0, 0, 0, 0, 0,
  117802. NULL,
  117803. NULL,
  117804. NULL,
  117805. NULL,
  117806. 0
  117807. };
  117808. static long _huff_lengthlist_line_2048x27_3sub2[] = {
  117809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117810. 0, 0, 3, 3, 3, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 6,
  117811. 6, 7, 6, 7, 6, 8, 6, 9, 7, 9, 7, 9, 9,11, 9,12,
  117812. 10,12,
  117813. };
  117814. static static_codebook _huff_book_line_2048x27_3sub2 = {
  117815. 1, 50,
  117816. _huff_lengthlist_line_2048x27_3sub2,
  117817. 0, 0, 0, 0, 0,
  117818. NULL,
  117819. NULL,
  117820. NULL,
  117821. NULL,
  117822. 0
  117823. };
  117824. static long _huff_lengthlist_line_2048x27_3sub3[] = {
  117825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117828. 0, 0, 3, 6, 3, 7, 3, 7, 5, 7, 7, 7, 7, 7, 6, 7,
  117829. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  117830. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  117831. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  117832. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  117833. };
  117834. static static_codebook _huff_book_line_2048x27_3sub3 = {
  117835. 1, 128,
  117836. _huff_lengthlist_line_2048x27_3sub3,
  117837. 0, 0, 0, 0, 0,
  117838. NULL,
  117839. NULL,
  117840. NULL,
  117841. NULL,
  117842. 0
  117843. };
  117844. static long _huff_lengthlist_line_2048x27_4sub1[] = {
  117845. 0, 3, 4, 4, 4, 4, 4, 4, 4, 4, 5, 4, 5, 4, 5, 4,
  117846. 4, 5,
  117847. };
  117848. static static_codebook _huff_book_line_2048x27_4sub1 = {
  117849. 1, 18,
  117850. _huff_lengthlist_line_2048x27_4sub1,
  117851. 0, 0, 0, 0, 0,
  117852. NULL,
  117853. NULL,
  117854. NULL,
  117855. NULL,
  117856. 0
  117857. };
  117858. static long _huff_lengthlist_line_2048x27_4sub2[] = {
  117859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117860. 0, 0, 3, 2, 4, 3, 4, 4, 4, 5, 5, 6, 5, 6, 5, 7,
  117861. 6, 6, 6, 7, 7, 7, 8, 9, 9, 9,12,10,11,10,10,12,
  117862. 10,10,
  117863. };
  117864. static static_codebook _huff_book_line_2048x27_4sub2 = {
  117865. 1, 50,
  117866. _huff_lengthlist_line_2048x27_4sub2,
  117867. 0, 0, 0, 0, 0,
  117868. NULL,
  117869. NULL,
  117870. NULL,
  117871. NULL,
  117872. 0
  117873. };
  117874. static long _huff_lengthlist_line_2048x27_4sub3[] = {
  117875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117878. 0, 0, 3, 6, 5, 7, 5, 7, 7, 7, 7, 7, 5, 7, 5, 7,
  117879. 5, 7, 5, 7, 7, 7, 7, 7, 4, 7, 7, 7, 7, 7, 7, 7,
  117880. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  117881. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  117882. 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  117883. };
  117884. static static_codebook _huff_book_line_2048x27_4sub3 = {
  117885. 1, 128,
  117886. _huff_lengthlist_line_2048x27_4sub3,
  117887. 0, 0, 0, 0, 0,
  117888. NULL,
  117889. NULL,
  117890. NULL,
  117891. NULL,
  117892. 0
  117893. };
  117894. static long _huff_lengthlist_line_256x4low_class0[] = {
  117895. 4, 5, 6,11, 5, 5, 6,10, 7, 7, 6, 6,14,13, 9, 9,
  117896. 6, 6, 6,10, 6, 6, 6, 9, 8, 7, 7, 9,14,12, 8,11,
  117897. 8, 7, 7,11, 8, 8, 7,11, 9, 9, 7, 9,13,11, 9,13,
  117898. 19,19,18,19,15,16,16,19,11,11,10,13,10,10, 9,15,
  117899. 5, 5, 6,13, 6, 6, 6,11, 8, 7, 6, 7,14,11,10,11,
  117900. 6, 6, 6,12, 7, 6, 6,11, 8, 7, 7,11,13,11, 9,11,
  117901. 9, 7, 6,12, 8, 7, 6,12, 9, 8, 8,11,13,10, 7,13,
  117902. 19,19,17,19,17,14,14,19,12,10, 8,12,13,10, 9,16,
  117903. 7, 8, 7,12, 7, 7, 7,11, 8, 7, 7, 8,12,12,11,11,
  117904. 8, 8, 7,12, 8, 7, 6,11, 8, 7, 7,10,10,11,10,11,
  117905. 9, 8, 8,13, 9, 8, 7,12,10, 9, 7,11, 9, 8, 7,11,
  117906. 18,18,15,18,18,16,17,18,15,11,10,18,11, 9, 9,18,
  117907. 16,16,13,16,12,11,10,16,12,11, 9, 6,15,12,11,13,
  117908. 16,16,14,14,13,11,12,16,12, 9, 9,13,13,10,10,12,
  117909. 17,18,17,17,14,15,14,16,14,12,14,15,12,10,11,12,
  117910. 18,18,18,18,18,18,18,18,18,12,13,18,16,11, 9,18,
  117911. };
  117912. static static_codebook _huff_book_line_256x4low_class0 = {
  117913. 1, 256,
  117914. _huff_lengthlist_line_256x4low_class0,
  117915. 0, 0, 0, 0, 0,
  117916. NULL,
  117917. NULL,
  117918. NULL,
  117919. NULL,
  117920. 0
  117921. };
  117922. static long _huff_lengthlist_line_256x4low_0sub0[] = {
  117923. 1, 3, 2, 3,
  117924. };
  117925. static static_codebook _huff_book_line_256x4low_0sub0 = {
  117926. 1, 4,
  117927. _huff_lengthlist_line_256x4low_0sub0,
  117928. 0, 0, 0, 0, 0,
  117929. NULL,
  117930. NULL,
  117931. NULL,
  117932. NULL,
  117933. 0
  117934. };
  117935. static long _huff_lengthlist_line_256x4low_0sub1[] = {
  117936. 0, 0, 0, 0, 2, 3, 2, 3, 3, 3,
  117937. };
  117938. static static_codebook _huff_book_line_256x4low_0sub1 = {
  117939. 1, 10,
  117940. _huff_lengthlist_line_256x4low_0sub1,
  117941. 0, 0, 0, 0, 0,
  117942. NULL,
  117943. NULL,
  117944. NULL,
  117945. NULL,
  117946. 0
  117947. };
  117948. static long _huff_lengthlist_line_256x4low_0sub2[] = {
  117949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 4, 3, 4,
  117950. 4, 4, 4, 4, 5, 5, 5, 6, 6,
  117951. };
  117952. static static_codebook _huff_book_line_256x4low_0sub2 = {
  117953. 1, 25,
  117954. _huff_lengthlist_line_256x4low_0sub2,
  117955. 0, 0, 0, 0, 0,
  117956. NULL,
  117957. NULL,
  117958. NULL,
  117959. NULL,
  117960. 0
  117961. };
  117962. static long _huff_lengthlist_line_256x4low_0sub3[] = {
  117963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 2, 4, 3, 5, 4,
  117965. 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 7, 7, 8, 6, 9,
  117966. 7,12,11,16,13,16,12,15,13,15,12,14,12,15,15,15,
  117967. };
  117968. static static_codebook _huff_book_line_256x4low_0sub3 = {
  117969. 1, 64,
  117970. _huff_lengthlist_line_256x4low_0sub3,
  117971. 0, 0, 0, 0, 0,
  117972. NULL,
  117973. NULL,
  117974. NULL,
  117975. NULL,
  117976. 0
  117977. };
  117978. /********* End of inlined file: floor_books.h *********/
  117979. static static_codebook *_floor_128x4_books[]={
  117980. &_huff_book_line_128x4_class0,
  117981. &_huff_book_line_128x4_0sub0,
  117982. &_huff_book_line_128x4_0sub1,
  117983. &_huff_book_line_128x4_0sub2,
  117984. &_huff_book_line_128x4_0sub3,
  117985. };
  117986. static static_codebook *_floor_256x4_books[]={
  117987. &_huff_book_line_256x4_class0,
  117988. &_huff_book_line_256x4_0sub0,
  117989. &_huff_book_line_256x4_0sub1,
  117990. &_huff_book_line_256x4_0sub2,
  117991. &_huff_book_line_256x4_0sub3,
  117992. };
  117993. static static_codebook *_floor_128x7_books[]={
  117994. &_huff_book_line_128x7_class0,
  117995. &_huff_book_line_128x7_class1,
  117996. &_huff_book_line_128x7_0sub1,
  117997. &_huff_book_line_128x7_0sub2,
  117998. &_huff_book_line_128x7_0sub3,
  117999. &_huff_book_line_128x7_1sub1,
  118000. &_huff_book_line_128x7_1sub2,
  118001. &_huff_book_line_128x7_1sub3,
  118002. };
  118003. static static_codebook *_floor_256x7_books[]={
  118004. &_huff_book_line_256x7_class0,
  118005. &_huff_book_line_256x7_class1,
  118006. &_huff_book_line_256x7_0sub1,
  118007. &_huff_book_line_256x7_0sub2,
  118008. &_huff_book_line_256x7_0sub3,
  118009. &_huff_book_line_256x7_1sub1,
  118010. &_huff_book_line_256x7_1sub2,
  118011. &_huff_book_line_256x7_1sub3,
  118012. };
  118013. static static_codebook *_floor_128x11_books[]={
  118014. &_huff_book_line_128x11_class1,
  118015. &_huff_book_line_128x11_class2,
  118016. &_huff_book_line_128x11_class3,
  118017. &_huff_book_line_128x11_0sub0,
  118018. &_huff_book_line_128x11_1sub0,
  118019. &_huff_book_line_128x11_1sub1,
  118020. &_huff_book_line_128x11_2sub1,
  118021. &_huff_book_line_128x11_2sub2,
  118022. &_huff_book_line_128x11_2sub3,
  118023. &_huff_book_line_128x11_3sub1,
  118024. &_huff_book_line_128x11_3sub2,
  118025. &_huff_book_line_128x11_3sub3,
  118026. };
  118027. static static_codebook *_floor_128x17_books[]={
  118028. &_huff_book_line_128x17_class1,
  118029. &_huff_book_line_128x17_class2,
  118030. &_huff_book_line_128x17_class3,
  118031. &_huff_book_line_128x17_0sub0,
  118032. &_huff_book_line_128x17_1sub0,
  118033. &_huff_book_line_128x17_1sub1,
  118034. &_huff_book_line_128x17_2sub1,
  118035. &_huff_book_line_128x17_2sub2,
  118036. &_huff_book_line_128x17_2sub3,
  118037. &_huff_book_line_128x17_3sub1,
  118038. &_huff_book_line_128x17_3sub2,
  118039. &_huff_book_line_128x17_3sub3,
  118040. };
  118041. static static_codebook *_floor_256x4low_books[]={
  118042. &_huff_book_line_256x4low_class0,
  118043. &_huff_book_line_256x4low_0sub0,
  118044. &_huff_book_line_256x4low_0sub1,
  118045. &_huff_book_line_256x4low_0sub2,
  118046. &_huff_book_line_256x4low_0sub3,
  118047. };
  118048. static static_codebook *_floor_1024x27_books[]={
  118049. &_huff_book_line_1024x27_class1,
  118050. &_huff_book_line_1024x27_class2,
  118051. &_huff_book_line_1024x27_class3,
  118052. &_huff_book_line_1024x27_class4,
  118053. &_huff_book_line_1024x27_0sub0,
  118054. &_huff_book_line_1024x27_1sub0,
  118055. &_huff_book_line_1024x27_1sub1,
  118056. &_huff_book_line_1024x27_2sub0,
  118057. &_huff_book_line_1024x27_2sub1,
  118058. &_huff_book_line_1024x27_3sub1,
  118059. &_huff_book_line_1024x27_3sub2,
  118060. &_huff_book_line_1024x27_3sub3,
  118061. &_huff_book_line_1024x27_4sub1,
  118062. &_huff_book_line_1024x27_4sub2,
  118063. &_huff_book_line_1024x27_4sub3,
  118064. };
  118065. static static_codebook *_floor_2048x27_books[]={
  118066. &_huff_book_line_2048x27_class1,
  118067. &_huff_book_line_2048x27_class2,
  118068. &_huff_book_line_2048x27_class3,
  118069. &_huff_book_line_2048x27_class4,
  118070. &_huff_book_line_2048x27_0sub0,
  118071. &_huff_book_line_2048x27_1sub0,
  118072. &_huff_book_line_2048x27_1sub1,
  118073. &_huff_book_line_2048x27_2sub0,
  118074. &_huff_book_line_2048x27_2sub1,
  118075. &_huff_book_line_2048x27_3sub1,
  118076. &_huff_book_line_2048x27_3sub2,
  118077. &_huff_book_line_2048x27_3sub3,
  118078. &_huff_book_line_2048x27_4sub1,
  118079. &_huff_book_line_2048x27_4sub2,
  118080. &_huff_book_line_2048x27_4sub3,
  118081. };
  118082. static static_codebook *_floor_512x17_books[]={
  118083. &_huff_book_line_512x17_class1,
  118084. &_huff_book_line_512x17_class2,
  118085. &_huff_book_line_512x17_class3,
  118086. &_huff_book_line_512x17_0sub0,
  118087. &_huff_book_line_512x17_1sub0,
  118088. &_huff_book_line_512x17_1sub1,
  118089. &_huff_book_line_512x17_2sub1,
  118090. &_huff_book_line_512x17_2sub2,
  118091. &_huff_book_line_512x17_2sub3,
  118092. &_huff_book_line_512x17_3sub1,
  118093. &_huff_book_line_512x17_3sub2,
  118094. &_huff_book_line_512x17_3sub3,
  118095. };
  118096. static static_codebook **_floor_books[10]={
  118097. _floor_128x4_books,
  118098. _floor_256x4_books,
  118099. _floor_128x7_books,
  118100. _floor_256x7_books,
  118101. _floor_128x11_books,
  118102. _floor_128x17_books,
  118103. _floor_256x4low_books,
  118104. _floor_1024x27_books,
  118105. _floor_2048x27_books,
  118106. _floor_512x17_books,
  118107. };
  118108. static vorbis_info_floor1 _floor[10]={
  118109. /* 128 x 4 */
  118110. {
  118111. 1,{0},{4},{2},{0},
  118112. {{1,2,3,4}},
  118113. 4,{0,128, 33,8,16,70},
  118114. 60,30,500, 1.,18., -1
  118115. },
  118116. /* 256 x 4 */
  118117. {
  118118. 1,{0},{4},{2},{0},
  118119. {{1,2,3,4}},
  118120. 4,{0,256, 66,16,32,140},
  118121. 60,30,500, 1.,18., -1
  118122. },
  118123. /* 128 x 7 */
  118124. {
  118125. 2,{0,1},{3,4},{2,2},{0,1},
  118126. {{-1,2,3,4},{-1,5,6,7}},
  118127. 4,{0,128, 14,4,58, 2,8,28,90},
  118128. 60,30,500, 1.,18., -1
  118129. },
  118130. /* 256 x 7 */
  118131. {
  118132. 2,{0,1},{3,4},{2,2},{0,1},
  118133. {{-1,2,3,4},{-1,5,6,7}},
  118134. 4,{0,256, 28,8,116, 4,16,56,180},
  118135. 60,30,500, 1.,18., -1
  118136. },
  118137. /* 128 x 11 */
  118138. {
  118139. 4,{0,1,2,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  118140. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  118141. 2,{0,128, 8,33, 4,16,70, 2,6,12, 23,46,90},
  118142. 60,30,500, 1,18., -1
  118143. },
  118144. /* 128 x 17 */
  118145. {
  118146. 6,{0,1,1,2,3,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  118147. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  118148. 2,{0,128, 12,46, 4,8,16, 23,33,70, 2,6,10, 14,19,28, 39,58,90},
  118149. 60,30,500, 1,18., -1
  118150. },
  118151. /* 256 x 4 (low bitrate version) */
  118152. {
  118153. 1,{0},{4},{2},{0},
  118154. {{1,2,3,4}},
  118155. 4,{0,256, 66,16,32,140},
  118156. 60,30,500, 1.,18., -1
  118157. },
  118158. /* 1024 x 27 */
  118159. {
  118160. 8,{0,1,2,2,3,3,4,4},{3,4,3,4,3},{0,1,1,2,2},{-1,0,1,2,3},
  118161. {{4},{5,6},{7,8},{-1,9,10,11},{-1,12,13,14}},
  118162. 2,{0,1024, 93,23,372, 6,46,186,750, 14,33,65, 130,260,556,
  118163. 3,10,18,28, 39,55,79,111, 158,220,312, 464,650,850},
  118164. 60,30,500, 3,18., -1 /* lowpass */
  118165. },
  118166. /* 2048 x 27 */
  118167. {
  118168. 8,{0,1,2,2,3,3,4,4},{3,4,3,4,3},{0,1,1,2,2},{-1,0,1,2,3},
  118169. {{4},{5,6},{7,8},{-1,9,10,11},{-1,12,13,14}},
  118170. 2,{0,2048, 186,46,744, 12,92,372,1500, 28,66,130, 260,520,1112,
  118171. 6,20,36,56, 78,110,158,222, 316,440,624, 928,1300,1700},
  118172. 60,30,500, 3,18., -1 /* lowpass */
  118173. },
  118174. /* 512 x 17 */
  118175. {
  118176. 6,{0,1,1,2,3,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  118177. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  118178. 2,{0,512, 46,186, 16,33,65, 93,130,278,
  118179. 7,23,39, 55,79,110, 156,232,360},
  118180. 60,30,500, 1,18., -1 /* lowpass! */
  118181. },
  118182. };
  118183. /********* End of inlined file: floor_all.h *********/
  118184. /********* Start of inlined file: residue_44.h *********/
  118185. /********* Start of inlined file: res_books_stereo.h *********/
  118186. static long _vq_quantlist__16c0_s_p1_0[] = {
  118187. 1,
  118188. 0,
  118189. 2,
  118190. };
  118191. static long _vq_lengthlist__16c0_s_p1_0[] = {
  118192. 1, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  118193. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118197. 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0,
  118198. 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118202. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  118203. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  118238. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0,
  118239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10,10, 0, 0, 0,
  118243. 0, 0, 0, 9, 9,12, 0, 0, 0, 0, 0, 0,10,12,11, 0,
  118244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10,10, 0, 0,
  118248. 0, 0, 0, 0, 9,12,10, 0, 0, 0, 0, 0, 0,10,11,12,
  118249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118283. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0,
  118284. 0, 0, 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118288. 0, 0, 0, 7,10,10, 0, 0, 0, 0, 0, 0,10,12,11, 0,
  118289. 0, 0, 0, 0, 0, 9,10,12, 0, 0, 0, 0, 0, 0, 0, 0,
  118290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118293. 0, 0, 0, 0, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,12,
  118294. 0, 0, 0, 0, 0, 0, 9,12, 9, 0, 0, 0, 0, 0, 0, 0,
  118295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118602. 0,
  118603. };
  118604. static float _vq_quantthresh__16c0_s_p1_0[] = {
  118605. -0.5, 0.5,
  118606. };
  118607. static long _vq_quantmap__16c0_s_p1_0[] = {
  118608. 1, 0, 2,
  118609. };
  118610. static encode_aux_threshmatch _vq_auxt__16c0_s_p1_0 = {
  118611. _vq_quantthresh__16c0_s_p1_0,
  118612. _vq_quantmap__16c0_s_p1_0,
  118613. 3,
  118614. 3
  118615. };
  118616. static static_codebook _16c0_s_p1_0 = {
  118617. 8, 6561,
  118618. _vq_lengthlist__16c0_s_p1_0,
  118619. 1, -535822336, 1611661312, 2, 0,
  118620. _vq_quantlist__16c0_s_p1_0,
  118621. NULL,
  118622. &_vq_auxt__16c0_s_p1_0,
  118623. NULL,
  118624. 0
  118625. };
  118626. static long _vq_quantlist__16c0_s_p2_0[] = {
  118627. 2,
  118628. 1,
  118629. 3,
  118630. 0,
  118631. 4,
  118632. };
  118633. static long _vq_lengthlist__16c0_s_p2_0[] = {
  118634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118673. 0,
  118674. };
  118675. static float _vq_quantthresh__16c0_s_p2_0[] = {
  118676. -1.5, -0.5, 0.5, 1.5,
  118677. };
  118678. static long _vq_quantmap__16c0_s_p2_0[] = {
  118679. 3, 1, 0, 2, 4,
  118680. };
  118681. static encode_aux_threshmatch _vq_auxt__16c0_s_p2_0 = {
  118682. _vq_quantthresh__16c0_s_p2_0,
  118683. _vq_quantmap__16c0_s_p2_0,
  118684. 5,
  118685. 5
  118686. };
  118687. static static_codebook _16c0_s_p2_0 = {
  118688. 4, 625,
  118689. _vq_lengthlist__16c0_s_p2_0,
  118690. 1, -533725184, 1611661312, 3, 0,
  118691. _vq_quantlist__16c0_s_p2_0,
  118692. NULL,
  118693. &_vq_auxt__16c0_s_p2_0,
  118694. NULL,
  118695. 0
  118696. };
  118697. static long _vq_quantlist__16c0_s_p3_0[] = {
  118698. 2,
  118699. 1,
  118700. 3,
  118701. 0,
  118702. 4,
  118703. };
  118704. static long _vq_lengthlist__16c0_s_p3_0[] = {
  118705. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 7, 6, 0, 0,
  118707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118708. 0, 0, 4, 6, 6, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  118710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118711. 0, 0, 0, 0, 6, 6, 6, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  118712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118744. 0,
  118745. };
  118746. static float _vq_quantthresh__16c0_s_p3_0[] = {
  118747. -1.5, -0.5, 0.5, 1.5,
  118748. };
  118749. static long _vq_quantmap__16c0_s_p3_0[] = {
  118750. 3, 1, 0, 2, 4,
  118751. };
  118752. static encode_aux_threshmatch _vq_auxt__16c0_s_p3_0 = {
  118753. _vq_quantthresh__16c0_s_p3_0,
  118754. _vq_quantmap__16c0_s_p3_0,
  118755. 5,
  118756. 5
  118757. };
  118758. static static_codebook _16c0_s_p3_0 = {
  118759. 4, 625,
  118760. _vq_lengthlist__16c0_s_p3_0,
  118761. 1, -533725184, 1611661312, 3, 0,
  118762. _vq_quantlist__16c0_s_p3_0,
  118763. NULL,
  118764. &_vq_auxt__16c0_s_p3_0,
  118765. NULL,
  118766. 0
  118767. };
  118768. static long _vq_quantlist__16c0_s_p4_0[] = {
  118769. 4,
  118770. 3,
  118771. 5,
  118772. 2,
  118773. 6,
  118774. 1,
  118775. 7,
  118776. 0,
  118777. 8,
  118778. };
  118779. static long _vq_lengthlist__16c0_s_p4_0[] = {
  118780. 1, 3, 2, 7, 8, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  118781. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  118782. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  118783. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  118784. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118785. 0,
  118786. };
  118787. static float _vq_quantthresh__16c0_s_p4_0[] = {
  118788. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  118789. };
  118790. static long _vq_quantmap__16c0_s_p4_0[] = {
  118791. 7, 5, 3, 1, 0, 2, 4, 6,
  118792. 8,
  118793. };
  118794. static encode_aux_threshmatch _vq_auxt__16c0_s_p4_0 = {
  118795. _vq_quantthresh__16c0_s_p4_0,
  118796. _vq_quantmap__16c0_s_p4_0,
  118797. 9,
  118798. 9
  118799. };
  118800. static static_codebook _16c0_s_p4_0 = {
  118801. 2, 81,
  118802. _vq_lengthlist__16c0_s_p4_0,
  118803. 1, -531628032, 1611661312, 4, 0,
  118804. _vq_quantlist__16c0_s_p4_0,
  118805. NULL,
  118806. &_vq_auxt__16c0_s_p4_0,
  118807. NULL,
  118808. 0
  118809. };
  118810. static long _vq_quantlist__16c0_s_p5_0[] = {
  118811. 4,
  118812. 3,
  118813. 5,
  118814. 2,
  118815. 6,
  118816. 1,
  118817. 7,
  118818. 0,
  118819. 8,
  118820. };
  118821. static long _vq_lengthlist__16c0_s_p5_0[] = {
  118822. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  118823. 8, 8, 0, 0, 0, 7, 7, 7, 7, 8, 8, 0, 0, 0, 7, 7,
  118824. 8, 8, 9, 9, 0, 0, 0, 7, 7, 8, 8, 9, 9, 0, 0, 0,
  118825. 8, 9, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  118826. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  118827. 10,
  118828. };
  118829. static float _vq_quantthresh__16c0_s_p5_0[] = {
  118830. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  118831. };
  118832. static long _vq_quantmap__16c0_s_p5_0[] = {
  118833. 7, 5, 3, 1, 0, 2, 4, 6,
  118834. 8,
  118835. };
  118836. static encode_aux_threshmatch _vq_auxt__16c0_s_p5_0 = {
  118837. _vq_quantthresh__16c0_s_p5_0,
  118838. _vq_quantmap__16c0_s_p5_0,
  118839. 9,
  118840. 9
  118841. };
  118842. static static_codebook _16c0_s_p5_0 = {
  118843. 2, 81,
  118844. _vq_lengthlist__16c0_s_p5_0,
  118845. 1, -531628032, 1611661312, 4, 0,
  118846. _vq_quantlist__16c0_s_p5_0,
  118847. NULL,
  118848. &_vq_auxt__16c0_s_p5_0,
  118849. NULL,
  118850. 0
  118851. };
  118852. static long _vq_quantlist__16c0_s_p6_0[] = {
  118853. 8,
  118854. 7,
  118855. 9,
  118856. 6,
  118857. 10,
  118858. 5,
  118859. 11,
  118860. 4,
  118861. 12,
  118862. 3,
  118863. 13,
  118864. 2,
  118865. 14,
  118866. 1,
  118867. 15,
  118868. 0,
  118869. 16,
  118870. };
  118871. static long _vq_lengthlist__16c0_s_p6_0[] = {
  118872. 1, 3, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  118873. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,11,
  118874. 11,11, 0, 0, 0, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  118875. 11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  118876. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  118877. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  118878. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  118879. 10,11,11,12,12,12,13, 0, 0, 0, 9, 9, 9, 9,10,10,
  118880. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,10,10,10,
  118881. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  118882. 10,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0, 0, 9,
  118883. 9,10,10,11,11,12,12,13,13,13,14, 0, 0, 0, 0, 0,
  118884. 10,10,10,11,11,11,12,12,13,13,13,14, 0, 0, 0, 0,
  118885. 0, 0, 0,10,10,11,11,12,12,13,13,14,14, 0, 0, 0,
  118886. 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0, 0,
  118887. 0, 0, 0, 0, 0,11,11,12,12,12,13,13,14,15,14, 0,
  118888. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,14,14,15,
  118889. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,14,13,14,
  118890. 14,
  118891. };
  118892. static float _vq_quantthresh__16c0_s_p6_0[] = {
  118893. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  118894. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  118895. };
  118896. static long _vq_quantmap__16c0_s_p6_0[] = {
  118897. 15, 13, 11, 9, 7, 5, 3, 1,
  118898. 0, 2, 4, 6, 8, 10, 12, 14,
  118899. 16,
  118900. };
  118901. static encode_aux_threshmatch _vq_auxt__16c0_s_p6_0 = {
  118902. _vq_quantthresh__16c0_s_p6_0,
  118903. _vq_quantmap__16c0_s_p6_0,
  118904. 17,
  118905. 17
  118906. };
  118907. static static_codebook _16c0_s_p6_0 = {
  118908. 2, 289,
  118909. _vq_lengthlist__16c0_s_p6_0,
  118910. 1, -529530880, 1611661312, 5, 0,
  118911. _vq_quantlist__16c0_s_p6_0,
  118912. NULL,
  118913. &_vq_auxt__16c0_s_p6_0,
  118914. NULL,
  118915. 0
  118916. };
  118917. static long _vq_quantlist__16c0_s_p7_0[] = {
  118918. 1,
  118919. 0,
  118920. 2,
  118921. };
  118922. static long _vq_lengthlist__16c0_s_p7_0[] = {
  118923. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,11,10,10,11,
  118924. 11,10, 4, 7, 7,10,10,10,11,10,10, 6,10,10,11,11,
  118925. 11,11,11,10, 6, 9, 9,11,12,12,11, 9, 9, 6, 9,10,
  118926. 11,12,12,11, 9,10, 7,11,11,11,11,11,12,13,12, 6,
  118927. 9,10,11,10,10,12,13,13, 6,10, 9,11,10,10,11,12,
  118928. 13,
  118929. };
  118930. static float _vq_quantthresh__16c0_s_p7_0[] = {
  118931. -5.5, 5.5,
  118932. };
  118933. static long _vq_quantmap__16c0_s_p7_0[] = {
  118934. 1, 0, 2,
  118935. };
  118936. static encode_aux_threshmatch _vq_auxt__16c0_s_p7_0 = {
  118937. _vq_quantthresh__16c0_s_p7_0,
  118938. _vq_quantmap__16c0_s_p7_0,
  118939. 3,
  118940. 3
  118941. };
  118942. static static_codebook _16c0_s_p7_0 = {
  118943. 4, 81,
  118944. _vq_lengthlist__16c0_s_p7_0,
  118945. 1, -529137664, 1618345984, 2, 0,
  118946. _vq_quantlist__16c0_s_p7_0,
  118947. NULL,
  118948. &_vq_auxt__16c0_s_p7_0,
  118949. NULL,
  118950. 0
  118951. };
  118952. static long _vq_quantlist__16c0_s_p7_1[] = {
  118953. 5,
  118954. 4,
  118955. 6,
  118956. 3,
  118957. 7,
  118958. 2,
  118959. 8,
  118960. 1,
  118961. 9,
  118962. 0,
  118963. 10,
  118964. };
  118965. static long _vq_lengthlist__16c0_s_p7_1[] = {
  118966. 1, 3, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7,
  118967. 8, 8, 8, 9, 9, 9,10,10,10, 6, 7, 8, 8, 8, 8, 9,
  118968. 8,10,10,10, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10, 7,
  118969. 7, 8, 8, 9, 9, 8, 9,10,10,10, 8, 8, 9, 9, 9, 9,
  118970. 9, 9,11,11,11, 8, 8, 9, 9, 9, 9, 9,10,10,11,11,
  118971. 9, 9, 9, 9, 9, 9, 9,10,11,11,11,10,11, 9, 9, 9,
  118972. 9,10, 9,11,11,11,10,11,10,10, 9, 9,10,10,11,11,
  118973. 11,11,11, 9, 9, 9, 9,10,10,
  118974. };
  118975. static float _vq_quantthresh__16c0_s_p7_1[] = {
  118976. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  118977. 3.5, 4.5,
  118978. };
  118979. static long _vq_quantmap__16c0_s_p7_1[] = {
  118980. 9, 7, 5, 3, 1, 0, 2, 4,
  118981. 6, 8, 10,
  118982. };
  118983. static encode_aux_threshmatch _vq_auxt__16c0_s_p7_1 = {
  118984. _vq_quantthresh__16c0_s_p7_1,
  118985. _vq_quantmap__16c0_s_p7_1,
  118986. 11,
  118987. 11
  118988. };
  118989. static static_codebook _16c0_s_p7_1 = {
  118990. 2, 121,
  118991. _vq_lengthlist__16c0_s_p7_1,
  118992. 1, -531365888, 1611661312, 4, 0,
  118993. _vq_quantlist__16c0_s_p7_1,
  118994. NULL,
  118995. &_vq_auxt__16c0_s_p7_1,
  118996. NULL,
  118997. 0
  118998. };
  118999. static long _vq_quantlist__16c0_s_p8_0[] = {
  119000. 6,
  119001. 5,
  119002. 7,
  119003. 4,
  119004. 8,
  119005. 3,
  119006. 9,
  119007. 2,
  119008. 10,
  119009. 1,
  119010. 11,
  119011. 0,
  119012. 12,
  119013. };
  119014. static long _vq_lengthlist__16c0_s_p8_0[] = {
  119015. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8,10,10, 6, 5, 6,
  119016. 8, 8, 8, 8, 8, 8, 8, 9,10,10, 7, 6, 6, 8, 8, 8,
  119017. 8, 8, 8, 8, 8,10,10, 0, 8, 8, 8, 8, 9, 8, 9, 9,
  119018. 9,10,10,10, 0, 9, 8, 8, 8, 9, 9, 8, 8, 9, 9,10,
  119019. 10, 0,12,11, 8, 8, 9, 9, 9, 9,10,10,11,10, 0,12,
  119020. 13, 8, 8, 9,10, 9, 9,11,11,11,12, 0, 0, 0, 8, 8,
  119021. 8, 8,10, 9,12,13,12,14, 0, 0, 0, 8, 8, 8, 9,10,
  119022. 10,12,12,13,14, 0, 0, 0,13,13, 9, 9,11,11, 0, 0,
  119023. 14, 0, 0, 0, 0,14,14,10,10,12,11,12,14,14,14, 0,
  119024. 0, 0, 0, 0,11,11,13,13,14,13,14,14, 0, 0, 0, 0,
  119025. 0,12,13,13,12,13,14,14,14,
  119026. };
  119027. static float _vq_quantthresh__16c0_s_p8_0[] = {
  119028. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  119029. 12.5, 17.5, 22.5, 27.5,
  119030. };
  119031. static long _vq_quantmap__16c0_s_p8_0[] = {
  119032. 11, 9, 7, 5, 3, 1, 0, 2,
  119033. 4, 6, 8, 10, 12,
  119034. };
  119035. static encode_aux_threshmatch _vq_auxt__16c0_s_p8_0 = {
  119036. _vq_quantthresh__16c0_s_p8_0,
  119037. _vq_quantmap__16c0_s_p8_0,
  119038. 13,
  119039. 13
  119040. };
  119041. static static_codebook _16c0_s_p8_0 = {
  119042. 2, 169,
  119043. _vq_lengthlist__16c0_s_p8_0,
  119044. 1, -526516224, 1616117760, 4, 0,
  119045. _vq_quantlist__16c0_s_p8_0,
  119046. NULL,
  119047. &_vq_auxt__16c0_s_p8_0,
  119048. NULL,
  119049. 0
  119050. };
  119051. static long _vq_quantlist__16c0_s_p8_1[] = {
  119052. 2,
  119053. 1,
  119054. 3,
  119055. 0,
  119056. 4,
  119057. };
  119058. static long _vq_lengthlist__16c0_s_p8_1[] = {
  119059. 1, 4, 3, 5, 5, 7, 7, 7, 6, 6, 7, 7, 7, 5, 5, 7,
  119060. 7, 7, 6, 6, 7, 7, 7, 6, 6,
  119061. };
  119062. static float _vq_quantthresh__16c0_s_p8_1[] = {
  119063. -1.5, -0.5, 0.5, 1.5,
  119064. };
  119065. static long _vq_quantmap__16c0_s_p8_1[] = {
  119066. 3, 1, 0, 2, 4,
  119067. };
  119068. static encode_aux_threshmatch _vq_auxt__16c0_s_p8_1 = {
  119069. _vq_quantthresh__16c0_s_p8_1,
  119070. _vq_quantmap__16c0_s_p8_1,
  119071. 5,
  119072. 5
  119073. };
  119074. static static_codebook _16c0_s_p8_1 = {
  119075. 2, 25,
  119076. _vq_lengthlist__16c0_s_p8_1,
  119077. 1, -533725184, 1611661312, 3, 0,
  119078. _vq_quantlist__16c0_s_p8_1,
  119079. NULL,
  119080. &_vq_auxt__16c0_s_p8_1,
  119081. NULL,
  119082. 0
  119083. };
  119084. static long _vq_quantlist__16c0_s_p9_0[] = {
  119085. 1,
  119086. 0,
  119087. 2,
  119088. };
  119089. static long _vq_lengthlist__16c0_s_p9_0[] = {
  119090. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  119091. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  119092. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  119093. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  119094. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  119095. 7,
  119096. };
  119097. static float _vq_quantthresh__16c0_s_p9_0[] = {
  119098. -157.5, 157.5,
  119099. };
  119100. static long _vq_quantmap__16c0_s_p9_0[] = {
  119101. 1, 0, 2,
  119102. };
  119103. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_0 = {
  119104. _vq_quantthresh__16c0_s_p9_0,
  119105. _vq_quantmap__16c0_s_p9_0,
  119106. 3,
  119107. 3
  119108. };
  119109. static static_codebook _16c0_s_p9_0 = {
  119110. 4, 81,
  119111. _vq_lengthlist__16c0_s_p9_0,
  119112. 1, -518803456, 1628680192, 2, 0,
  119113. _vq_quantlist__16c0_s_p9_0,
  119114. NULL,
  119115. &_vq_auxt__16c0_s_p9_0,
  119116. NULL,
  119117. 0
  119118. };
  119119. static long _vq_quantlist__16c0_s_p9_1[] = {
  119120. 7,
  119121. 6,
  119122. 8,
  119123. 5,
  119124. 9,
  119125. 4,
  119126. 10,
  119127. 3,
  119128. 11,
  119129. 2,
  119130. 12,
  119131. 1,
  119132. 13,
  119133. 0,
  119134. 14,
  119135. };
  119136. static long _vq_lengthlist__16c0_s_p9_1[] = {
  119137. 1, 5, 5, 5, 5, 9,11,11,10,10,10,10,10,10,10, 7,
  119138. 6, 6, 6, 6,10,10,10,10,10,10,10,10,10,10, 7, 6,
  119139. 6, 6, 6,10, 9,10,10,10,10,10,10,10,10,10, 7, 7,
  119140. 8, 9,10,10,10,10,10,10,10,10,10,10,10, 8, 7,10,
  119141. 10,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,
  119142. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  119143. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  119144. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  119145. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  119146. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  119147. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  119148. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  119149. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  119150. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  119151. 10,
  119152. };
  119153. static float _vq_quantthresh__16c0_s_p9_1[] = {
  119154. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  119155. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  119156. };
  119157. static long _vq_quantmap__16c0_s_p9_1[] = {
  119158. 13, 11, 9, 7, 5, 3, 1, 0,
  119159. 2, 4, 6, 8, 10, 12, 14,
  119160. };
  119161. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_1 = {
  119162. _vq_quantthresh__16c0_s_p9_1,
  119163. _vq_quantmap__16c0_s_p9_1,
  119164. 15,
  119165. 15
  119166. };
  119167. static static_codebook _16c0_s_p9_1 = {
  119168. 2, 225,
  119169. _vq_lengthlist__16c0_s_p9_1,
  119170. 1, -520986624, 1620377600, 4, 0,
  119171. _vq_quantlist__16c0_s_p9_1,
  119172. NULL,
  119173. &_vq_auxt__16c0_s_p9_1,
  119174. NULL,
  119175. 0
  119176. };
  119177. static long _vq_quantlist__16c0_s_p9_2[] = {
  119178. 10,
  119179. 9,
  119180. 11,
  119181. 8,
  119182. 12,
  119183. 7,
  119184. 13,
  119185. 6,
  119186. 14,
  119187. 5,
  119188. 15,
  119189. 4,
  119190. 16,
  119191. 3,
  119192. 17,
  119193. 2,
  119194. 18,
  119195. 1,
  119196. 19,
  119197. 0,
  119198. 20,
  119199. };
  119200. static long _vq_lengthlist__16c0_s_p9_2[] = {
  119201. 1, 5, 5, 7, 8, 8, 7, 9, 9, 9,12,12,11,12,12,10,
  119202. 10,11,12,12,12,11,12,12, 8, 9, 8, 7, 9,10,10,11,
  119203. 11,10,11,12,10,12,10,12,12,12,11,12,11, 9, 8, 8,
  119204. 9,10, 9, 8, 9,10,12,12,11,11,12,11,10,11,12,11,
  119205. 12,12, 8, 9, 9, 9,10,11,12,11,12,11,11,11,11,12,
  119206. 12,11,11,12,12,11,11, 9, 9, 8, 9, 9,11, 9, 9,10,
  119207. 9,11,11,11,11,12,11,11,10,12,12,12, 9,12,11,10,
  119208. 11,11,11,11,12,12,12,11,11,11,12,10,12,12,12,10,
  119209. 10, 9,10, 9,10,10, 9, 9, 9,10,10,12,10,11,11, 9,
  119210. 11,11,10,11,11,11,10,10,10, 9, 9,10,10, 9, 9,10,
  119211. 11,11,10,11,10,11,10,11,11,10,11,11,11,10, 9,10,
  119212. 10, 9,10, 9, 9,11, 9, 9,11,10,10,11,11,10,10,11,
  119213. 10,11, 8, 9,11,11,10, 9,10,11,11,10,11,11,10,10,
  119214. 10,11,10, 9,10,10,11, 9,10,10, 9,11,10,10,10,10,
  119215. 11,10,11,11, 9,11,10,11,10,10,11,11,10,10,10, 9,
  119216. 10,10,11,11,11, 9,10,10,10,10,10,11,10,10,10, 9,
  119217. 10,10,11,10,10,10,10,10, 9,10,11,10,10,10,10,11,
  119218. 11,11,10,10,10,10,10,11,10,11,10,11,10,10,10, 9,
  119219. 11,11,10,10,10,11,11,10,10,10,10,10,10,10,10,11,
  119220. 11, 9,10,10,10,11,10,11,10,10,10,11, 9,10,11,10,
  119221. 11,10,10, 9,10,10,10,11,10,11,10,10,10,10,10,11,
  119222. 11,10,11,11,10,10,11,11,10, 9, 9,10,10,10,10,10,
  119223. 9,11, 9,10,10,10,11,11,10,10,10,10,11,11,11,10,
  119224. 9, 9,10,10,11,10,10,10,10,10,11,11,11,10,10,10,
  119225. 11,11,11, 9,10,10,10,10, 9,10, 9,10,11,10,11,10,
  119226. 10,11,11,10,11,11,11,11,11,10,11,10,10,10, 9,11,
  119227. 11,10,11,11,11,11,11,11,11,11,11,10,11,10,10,10,
  119228. 10,11,10,10,11, 9,10,10,10,
  119229. };
  119230. static float _vq_quantthresh__16c0_s_p9_2[] = {
  119231. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  119232. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  119233. 6.5, 7.5, 8.5, 9.5,
  119234. };
  119235. static long _vq_quantmap__16c0_s_p9_2[] = {
  119236. 19, 17, 15, 13, 11, 9, 7, 5,
  119237. 3, 1, 0, 2, 4, 6, 8, 10,
  119238. 12, 14, 16, 18, 20,
  119239. };
  119240. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_2 = {
  119241. _vq_quantthresh__16c0_s_p9_2,
  119242. _vq_quantmap__16c0_s_p9_2,
  119243. 21,
  119244. 21
  119245. };
  119246. static static_codebook _16c0_s_p9_2 = {
  119247. 2, 441,
  119248. _vq_lengthlist__16c0_s_p9_2,
  119249. 1, -529268736, 1611661312, 5, 0,
  119250. _vq_quantlist__16c0_s_p9_2,
  119251. NULL,
  119252. &_vq_auxt__16c0_s_p9_2,
  119253. NULL,
  119254. 0
  119255. };
  119256. static long _huff_lengthlist__16c0_s_single[] = {
  119257. 3, 4,19, 7, 9, 7, 8,11, 9,12, 4, 1,19, 6, 7, 7,
  119258. 8,10,11,13,18,18,18,18,18,18,18,18,18,18, 8, 6,
  119259. 18, 8, 9, 9,11,12,14,18, 9, 6,18, 9, 7, 8, 9,11,
  119260. 12,18, 7, 6,18, 8, 7, 7, 7, 9,11,17, 8, 8,18, 9,
  119261. 7, 6, 6, 8,11,17,10,10,18,12, 9, 8, 7, 9,12,18,
  119262. 13,15,18,15,13,11,10,11,15,18,14,18,18,18,18,18,
  119263. 16,16,18,18,
  119264. };
  119265. static static_codebook _huff_book__16c0_s_single = {
  119266. 2, 100,
  119267. _huff_lengthlist__16c0_s_single,
  119268. 0, 0, 0, 0, 0,
  119269. NULL,
  119270. NULL,
  119271. NULL,
  119272. NULL,
  119273. 0
  119274. };
  119275. static long _huff_lengthlist__16c1_s_long[] = {
  119276. 2, 5,20, 7,10, 7, 8,10,11,11, 4, 2,20, 5, 8, 6,
  119277. 7, 9,10,10,20,20,20,20,19,19,19,19,19,19, 7, 5,
  119278. 19, 6,10, 7, 9,11,13,17,11, 8,19,10, 7, 7, 8,10,
  119279. 11,15, 7, 5,19, 7, 7, 5, 6, 9,11,16, 7, 6,19, 8,
  119280. 7, 6, 6, 7, 9,13, 9, 9,19,11, 9, 8, 6, 7, 8,13,
  119281. 12,14,19,16,13,10, 9, 8, 9,13,14,17,19,18,18,17,
  119282. 12,11,11,13,
  119283. };
  119284. static static_codebook _huff_book__16c1_s_long = {
  119285. 2, 100,
  119286. _huff_lengthlist__16c1_s_long,
  119287. 0, 0, 0, 0, 0,
  119288. NULL,
  119289. NULL,
  119290. NULL,
  119291. NULL,
  119292. 0
  119293. };
  119294. static long _vq_quantlist__16c1_s_p1_0[] = {
  119295. 1,
  119296. 0,
  119297. 2,
  119298. };
  119299. static long _vq_lengthlist__16c1_s_p1_0[] = {
  119300. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  119301. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119305. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  119306. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119310. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  119311. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 0,
  119346. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  119347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  119351. 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  119352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  119356. 0, 0, 0, 0, 8,11, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  119357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119391. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  119392. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119396. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  119397. 0, 0, 0, 0, 0, 8, 9,11, 0, 0, 0, 0, 0, 0, 0, 0,
  119398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119401. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  119402. 0, 0, 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0, 0,
  119403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119710. 0,
  119711. };
  119712. static float _vq_quantthresh__16c1_s_p1_0[] = {
  119713. -0.5, 0.5,
  119714. };
  119715. static long _vq_quantmap__16c1_s_p1_0[] = {
  119716. 1, 0, 2,
  119717. };
  119718. static encode_aux_threshmatch _vq_auxt__16c1_s_p1_0 = {
  119719. _vq_quantthresh__16c1_s_p1_0,
  119720. _vq_quantmap__16c1_s_p1_0,
  119721. 3,
  119722. 3
  119723. };
  119724. static static_codebook _16c1_s_p1_0 = {
  119725. 8, 6561,
  119726. _vq_lengthlist__16c1_s_p1_0,
  119727. 1, -535822336, 1611661312, 2, 0,
  119728. _vq_quantlist__16c1_s_p1_0,
  119729. NULL,
  119730. &_vq_auxt__16c1_s_p1_0,
  119731. NULL,
  119732. 0
  119733. };
  119734. static long _vq_quantlist__16c1_s_p2_0[] = {
  119735. 2,
  119736. 1,
  119737. 3,
  119738. 0,
  119739. 4,
  119740. };
  119741. static long _vq_lengthlist__16c1_s_p2_0[] = {
  119742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119781. 0,
  119782. };
  119783. static float _vq_quantthresh__16c1_s_p2_0[] = {
  119784. -1.5, -0.5, 0.5, 1.5,
  119785. };
  119786. static long _vq_quantmap__16c1_s_p2_0[] = {
  119787. 3, 1, 0, 2, 4,
  119788. };
  119789. static encode_aux_threshmatch _vq_auxt__16c1_s_p2_0 = {
  119790. _vq_quantthresh__16c1_s_p2_0,
  119791. _vq_quantmap__16c1_s_p2_0,
  119792. 5,
  119793. 5
  119794. };
  119795. static static_codebook _16c1_s_p2_0 = {
  119796. 4, 625,
  119797. _vq_lengthlist__16c1_s_p2_0,
  119798. 1, -533725184, 1611661312, 3, 0,
  119799. _vq_quantlist__16c1_s_p2_0,
  119800. NULL,
  119801. &_vq_auxt__16c1_s_p2_0,
  119802. NULL,
  119803. 0
  119804. };
  119805. static long _vq_quantlist__16c1_s_p3_0[] = {
  119806. 2,
  119807. 1,
  119808. 3,
  119809. 0,
  119810. 4,
  119811. };
  119812. static long _vq_lengthlist__16c1_s_p3_0[] = {
  119813. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  119815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119816. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 7, 7, 9, 9,
  119818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119819. 0, 0, 0, 0, 6, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  119820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119852. 0,
  119853. };
  119854. static float _vq_quantthresh__16c1_s_p3_0[] = {
  119855. -1.5, -0.5, 0.5, 1.5,
  119856. };
  119857. static long _vq_quantmap__16c1_s_p3_0[] = {
  119858. 3, 1, 0, 2, 4,
  119859. };
  119860. static encode_aux_threshmatch _vq_auxt__16c1_s_p3_0 = {
  119861. _vq_quantthresh__16c1_s_p3_0,
  119862. _vq_quantmap__16c1_s_p3_0,
  119863. 5,
  119864. 5
  119865. };
  119866. static static_codebook _16c1_s_p3_0 = {
  119867. 4, 625,
  119868. _vq_lengthlist__16c1_s_p3_0,
  119869. 1, -533725184, 1611661312, 3, 0,
  119870. _vq_quantlist__16c1_s_p3_0,
  119871. NULL,
  119872. &_vq_auxt__16c1_s_p3_0,
  119873. NULL,
  119874. 0
  119875. };
  119876. static long _vq_quantlist__16c1_s_p4_0[] = {
  119877. 4,
  119878. 3,
  119879. 5,
  119880. 2,
  119881. 6,
  119882. 1,
  119883. 7,
  119884. 0,
  119885. 8,
  119886. };
  119887. static long _vq_lengthlist__16c1_s_p4_0[] = {
  119888. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  119889. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  119890. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  119891. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 9, 0, 0, 0, 0, 0,
  119892. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119893. 0,
  119894. };
  119895. static float _vq_quantthresh__16c1_s_p4_0[] = {
  119896. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  119897. };
  119898. static long _vq_quantmap__16c1_s_p4_0[] = {
  119899. 7, 5, 3, 1, 0, 2, 4, 6,
  119900. 8,
  119901. };
  119902. static encode_aux_threshmatch _vq_auxt__16c1_s_p4_0 = {
  119903. _vq_quantthresh__16c1_s_p4_0,
  119904. _vq_quantmap__16c1_s_p4_0,
  119905. 9,
  119906. 9
  119907. };
  119908. static static_codebook _16c1_s_p4_0 = {
  119909. 2, 81,
  119910. _vq_lengthlist__16c1_s_p4_0,
  119911. 1, -531628032, 1611661312, 4, 0,
  119912. _vq_quantlist__16c1_s_p4_0,
  119913. NULL,
  119914. &_vq_auxt__16c1_s_p4_0,
  119915. NULL,
  119916. 0
  119917. };
  119918. static long _vq_quantlist__16c1_s_p5_0[] = {
  119919. 4,
  119920. 3,
  119921. 5,
  119922. 2,
  119923. 6,
  119924. 1,
  119925. 7,
  119926. 0,
  119927. 8,
  119928. };
  119929. static long _vq_lengthlist__16c1_s_p5_0[] = {
  119930. 1, 3, 3, 5, 5, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  119931. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 8, 8,
  119932. 8, 8, 9, 9, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  119933. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  119934. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  119935. 10,
  119936. };
  119937. static float _vq_quantthresh__16c1_s_p5_0[] = {
  119938. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  119939. };
  119940. static long _vq_quantmap__16c1_s_p5_0[] = {
  119941. 7, 5, 3, 1, 0, 2, 4, 6,
  119942. 8,
  119943. };
  119944. static encode_aux_threshmatch _vq_auxt__16c1_s_p5_0 = {
  119945. _vq_quantthresh__16c1_s_p5_0,
  119946. _vq_quantmap__16c1_s_p5_0,
  119947. 9,
  119948. 9
  119949. };
  119950. static static_codebook _16c1_s_p5_0 = {
  119951. 2, 81,
  119952. _vq_lengthlist__16c1_s_p5_0,
  119953. 1, -531628032, 1611661312, 4, 0,
  119954. _vq_quantlist__16c1_s_p5_0,
  119955. NULL,
  119956. &_vq_auxt__16c1_s_p5_0,
  119957. NULL,
  119958. 0
  119959. };
  119960. static long _vq_quantlist__16c1_s_p6_0[] = {
  119961. 8,
  119962. 7,
  119963. 9,
  119964. 6,
  119965. 10,
  119966. 5,
  119967. 11,
  119968. 4,
  119969. 12,
  119970. 3,
  119971. 13,
  119972. 2,
  119973. 14,
  119974. 1,
  119975. 15,
  119976. 0,
  119977. 16,
  119978. };
  119979. static long _vq_lengthlist__16c1_s_p6_0[] = {
  119980. 1, 3, 3, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,12,
  119981. 12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  119982. 12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  119983. 11,12,12, 0, 0, 0, 8, 8, 8, 9,10, 9,10,10,10,10,
  119984. 11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,11,
  119985. 11,11,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  119986. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  119987. 10,11,11,12,12,13,13, 0, 0, 0, 9, 9, 9, 9,10,10,
  119988. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  119989. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  119990. 10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0, 9,
  119991. 9,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0,
  119992. 10,10,11,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0,
  119993. 0, 0, 0,10,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  119994. 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0, 0,
  119995. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0,
  119996. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  119997. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  119998. 14,
  119999. };
  120000. static float _vq_quantthresh__16c1_s_p6_0[] = {
  120001. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  120002. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  120003. };
  120004. static long _vq_quantmap__16c1_s_p6_0[] = {
  120005. 15, 13, 11, 9, 7, 5, 3, 1,
  120006. 0, 2, 4, 6, 8, 10, 12, 14,
  120007. 16,
  120008. };
  120009. static encode_aux_threshmatch _vq_auxt__16c1_s_p6_0 = {
  120010. _vq_quantthresh__16c1_s_p6_0,
  120011. _vq_quantmap__16c1_s_p6_0,
  120012. 17,
  120013. 17
  120014. };
  120015. static static_codebook _16c1_s_p6_0 = {
  120016. 2, 289,
  120017. _vq_lengthlist__16c1_s_p6_0,
  120018. 1, -529530880, 1611661312, 5, 0,
  120019. _vq_quantlist__16c1_s_p6_0,
  120020. NULL,
  120021. &_vq_auxt__16c1_s_p6_0,
  120022. NULL,
  120023. 0
  120024. };
  120025. static long _vq_quantlist__16c1_s_p7_0[] = {
  120026. 1,
  120027. 0,
  120028. 2,
  120029. };
  120030. static long _vq_lengthlist__16c1_s_p7_0[] = {
  120031. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,10, 9,10,10,
  120032. 10, 9, 4, 7, 7,10,10,10,11,10,10, 6,10,10,11,11,
  120033. 11,11,10,10, 6,10, 9,11,11,11,11,10,10, 6,10,10,
  120034. 11,11,11,11,10,10, 7,11,11,11,11,11,12,12,11, 6,
  120035. 10,10,11,10,10,11,11,11, 6,10,10,10,11,10,11,11,
  120036. 11,
  120037. };
  120038. static float _vq_quantthresh__16c1_s_p7_0[] = {
  120039. -5.5, 5.5,
  120040. };
  120041. static long _vq_quantmap__16c1_s_p7_0[] = {
  120042. 1, 0, 2,
  120043. };
  120044. static encode_aux_threshmatch _vq_auxt__16c1_s_p7_0 = {
  120045. _vq_quantthresh__16c1_s_p7_0,
  120046. _vq_quantmap__16c1_s_p7_0,
  120047. 3,
  120048. 3
  120049. };
  120050. static static_codebook _16c1_s_p7_0 = {
  120051. 4, 81,
  120052. _vq_lengthlist__16c1_s_p7_0,
  120053. 1, -529137664, 1618345984, 2, 0,
  120054. _vq_quantlist__16c1_s_p7_0,
  120055. NULL,
  120056. &_vq_auxt__16c1_s_p7_0,
  120057. NULL,
  120058. 0
  120059. };
  120060. static long _vq_quantlist__16c1_s_p7_1[] = {
  120061. 5,
  120062. 4,
  120063. 6,
  120064. 3,
  120065. 7,
  120066. 2,
  120067. 8,
  120068. 1,
  120069. 9,
  120070. 0,
  120071. 10,
  120072. };
  120073. static long _vq_lengthlist__16c1_s_p7_1[] = {
  120074. 2, 3, 3, 5, 6, 7, 7, 7, 7, 8, 8,10,10,10, 6, 6,
  120075. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  120076. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  120077. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  120078. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  120079. 8, 8, 8, 8, 8, 8, 9, 9,10,10,10,10,10, 8, 8, 8,
  120080. 8, 9, 9,10,10,10,10,10, 9, 9, 8, 8, 9, 9,10,10,
  120081. 10,10,10, 8, 8, 8, 8, 9, 9,
  120082. };
  120083. static float _vq_quantthresh__16c1_s_p7_1[] = {
  120084. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  120085. 3.5, 4.5,
  120086. };
  120087. static long _vq_quantmap__16c1_s_p7_1[] = {
  120088. 9, 7, 5, 3, 1, 0, 2, 4,
  120089. 6, 8, 10,
  120090. };
  120091. static encode_aux_threshmatch _vq_auxt__16c1_s_p7_1 = {
  120092. _vq_quantthresh__16c1_s_p7_1,
  120093. _vq_quantmap__16c1_s_p7_1,
  120094. 11,
  120095. 11
  120096. };
  120097. static static_codebook _16c1_s_p7_1 = {
  120098. 2, 121,
  120099. _vq_lengthlist__16c1_s_p7_1,
  120100. 1, -531365888, 1611661312, 4, 0,
  120101. _vq_quantlist__16c1_s_p7_1,
  120102. NULL,
  120103. &_vq_auxt__16c1_s_p7_1,
  120104. NULL,
  120105. 0
  120106. };
  120107. static long _vq_quantlist__16c1_s_p8_0[] = {
  120108. 6,
  120109. 5,
  120110. 7,
  120111. 4,
  120112. 8,
  120113. 3,
  120114. 9,
  120115. 2,
  120116. 10,
  120117. 1,
  120118. 11,
  120119. 0,
  120120. 12,
  120121. };
  120122. static long _vq_lengthlist__16c1_s_p8_0[] = {
  120123. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 6, 5, 5,
  120124. 7, 8, 8, 9, 8, 8, 9, 9,10,11, 6, 5, 5, 8, 8, 9,
  120125. 9, 8, 8, 9,10,10,11, 0, 8, 8, 8, 9, 9, 9, 9, 9,
  120126. 10,10,11,11, 0, 9, 9, 9, 8, 9, 9, 9, 9,10,10,11,
  120127. 11, 0,13,13, 9, 9,10,10,10,10,11,11,12,12, 0,14,
  120128. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  120129. 9, 9,11,11,12,12,13,12, 0, 0, 0,10,10, 9, 9,10,
  120130. 10,12,12,13,13, 0, 0, 0,13,14,11,10,11,11,12,12,
  120131. 13,14, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  120132. 0, 0, 0, 0,12,12,12,12,13,13,14,15, 0, 0, 0, 0,
  120133. 0,12,12,12,12,13,13,14,15,
  120134. };
  120135. static float _vq_quantthresh__16c1_s_p8_0[] = {
  120136. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  120137. 12.5, 17.5, 22.5, 27.5,
  120138. };
  120139. static long _vq_quantmap__16c1_s_p8_0[] = {
  120140. 11, 9, 7, 5, 3, 1, 0, 2,
  120141. 4, 6, 8, 10, 12,
  120142. };
  120143. static encode_aux_threshmatch _vq_auxt__16c1_s_p8_0 = {
  120144. _vq_quantthresh__16c1_s_p8_0,
  120145. _vq_quantmap__16c1_s_p8_0,
  120146. 13,
  120147. 13
  120148. };
  120149. static static_codebook _16c1_s_p8_0 = {
  120150. 2, 169,
  120151. _vq_lengthlist__16c1_s_p8_0,
  120152. 1, -526516224, 1616117760, 4, 0,
  120153. _vq_quantlist__16c1_s_p8_0,
  120154. NULL,
  120155. &_vq_auxt__16c1_s_p8_0,
  120156. NULL,
  120157. 0
  120158. };
  120159. static long _vq_quantlist__16c1_s_p8_1[] = {
  120160. 2,
  120161. 1,
  120162. 3,
  120163. 0,
  120164. 4,
  120165. };
  120166. static long _vq_lengthlist__16c1_s_p8_1[] = {
  120167. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  120168. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  120169. };
  120170. static float _vq_quantthresh__16c1_s_p8_1[] = {
  120171. -1.5, -0.5, 0.5, 1.5,
  120172. };
  120173. static long _vq_quantmap__16c1_s_p8_1[] = {
  120174. 3, 1, 0, 2, 4,
  120175. };
  120176. static encode_aux_threshmatch _vq_auxt__16c1_s_p8_1 = {
  120177. _vq_quantthresh__16c1_s_p8_1,
  120178. _vq_quantmap__16c1_s_p8_1,
  120179. 5,
  120180. 5
  120181. };
  120182. static static_codebook _16c1_s_p8_1 = {
  120183. 2, 25,
  120184. _vq_lengthlist__16c1_s_p8_1,
  120185. 1, -533725184, 1611661312, 3, 0,
  120186. _vq_quantlist__16c1_s_p8_1,
  120187. NULL,
  120188. &_vq_auxt__16c1_s_p8_1,
  120189. NULL,
  120190. 0
  120191. };
  120192. static long _vq_quantlist__16c1_s_p9_0[] = {
  120193. 6,
  120194. 5,
  120195. 7,
  120196. 4,
  120197. 8,
  120198. 3,
  120199. 9,
  120200. 2,
  120201. 10,
  120202. 1,
  120203. 11,
  120204. 0,
  120205. 12,
  120206. };
  120207. static long _vq_lengthlist__16c1_s_p9_0[] = {
  120208. 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  120209. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  120210. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  120211. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  120212. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  120213. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  120214. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  120215. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  120216. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  120217. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  120218. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  120219. };
  120220. static float _vq_quantthresh__16c1_s_p9_0[] = {
  120221. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  120222. 787.5, 1102.5, 1417.5, 1732.5,
  120223. };
  120224. static long _vq_quantmap__16c1_s_p9_0[] = {
  120225. 11, 9, 7, 5, 3, 1, 0, 2,
  120226. 4, 6, 8, 10, 12,
  120227. };
  120228. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_0 = {
  120229. _vq_quantthresh__16c1_s_p9_0,
  120230. _vq_quantmap__16c1_s_p9_0,
  120231. 13,
  120232. 13
  120233. };
  120234. static static_codebook _16c1_s_p9_0 = {
  120235. 2, 169,
  120236. _vq_lengthlist__16c1_s_p9_0,
  120237. 1, -513964032, 1628680192, 4, 0,
  120238. _vq_quantlist__16c1_s_p9_0,
  120239. NULL,
  120240. &_vq_auxt__16c1_s_p9_0,
  120241. NULL,
  120242. 0
  120243. };
  120244. static long _vq_quantlist__16c1_s_p9_1[] = {
  120245. 7,
  120246. 6,
  120247. 8,
  120248. 5,
  120249. 9,
  120250. 4,
  120251. 10,
  120252. 3,
  120253. 11,
  120254. 2,
  120255. 12,
  120256. 1,
  120257. 13,
  120258. 0,
  120259. 14,
  120260. };
  120261. static long _vq_lengthlist__16c1_s_p9_1[] = {
  120262. 1, 4, 4, 4, 4, 8, 8,12,13,14,14,14,14,14,14, 6,
  120263. 6, 6, 6, 6,10, 9,14,14,14,14,14,14,14,14, 7, 6,
  120264. 5, 6, 6,10, 9,12,13,13,13,13,13,13,13,13, 7, 7,
  120265. 9, 9,11,11,12,13,13,13,13,13,13,13,13, 7, 7, 8,
  120266. 8,11,12,13,13,13,13,13,13,13,13,13,12,12,10,10,
  120267. 13,12,13,13,13,13,13,13,13,13,13,12,12,10,10,13,
  120268. 13,13,13,13,13,13,13,13,13,13,13,13,13,12,13,12,
  120269. 13,13,13,13,13,13,13,13,13,13,13,13,12,13,13,13,
  120270. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  120271. 13,13,13,13,13,13,13,13,13,13,13,13,12,13,13,13,
  120272. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  120273. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  120274. 13,13,13,13,13,13,13,13,13,12,13,13,13,13,13,13,
  120275. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  120276. 13,
  120277. };
  120278. static float _vq_quantthresh__16c1_s_p9_1[] = {
  120279. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  120280. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  120281. };
  120282. static long _vq_quantmap__16c1_s_p9_1[] = {
  120283. 13, 11, 9, 7, 5, 3, 1, 0,
  120284. 2, 4, 6, 8, 10, 12, 14,
  120285. };
  120286. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_1 = {
  120287. _vq_quantthresh__16c1_s_p9_1,
  120288. _vq_quantmap__16c1_s_p9_1,
  120289. 15,
  120290. 15
  120291. };
  120292. static static_codebook _16c1_s_p9_1 = {
  120293. 2, 225,
  120294. _vq_lengthlist__16c1_s_p9_1,
  120295. 1, -520986624, 1620377600, 4, 0,
  120296. _vq_quantlist__16c1_s_p9_1,
  120297. NULL,
  120298. &_vq_auxt__16c1_s_p9_1,
  120299. NULL,
  120300. 0
  120301. };
  120302. static long _vq_quantlist__16c1_s_p9_2[] = {
  120303. 10,
  120304. 9,
  120305. 11,
  120306. 8,
  120307. 12,
  120308. 7,
  120309. 13,
  120310. 6,
  120311. 14,
  120312. 5,
  120313. 15,
  120314. 4,
  120315. 16,
  120316. 3,
  120317. 17,
  120318. 2,
  120319. 18,
  120320. 1,
  120321. 19,
  120322. 0,
  120323. 20,
  120324. };
  120325. static long _vq_lengthlist__16c1_s_p9_2[] = {
  120326. 1, 4, 4, 6, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9,10,
  120327. 10,10, 9,10,10,11,12,12, 8, 8, 8, 8, 9, 9, 9, 9,
  120328. 10,10,10,10,10,11,11,10,12,11,11,13,11, 7, 7, 8,
  120329. 8, 8, 8, 9, 9, 9,10,10,10,10, 9,10,10,11,11,12,
  120330. 11,11, 8, 8, 8, 8, 9, 9,10,10,10,10,11,11,11,11,
  120331. 11,11,11,12,11,12,12, 8, 8, 9, 9, 9, 9, 9,10,10,
  120332. 10,10,10,10,11,11,11,11,11,11,12,11, 9, 9, 9, 9,
  120333. 10,10,10,10,11,10,11,11,11,11,11,11,12,12,12,12,
  120334. 11, 9, 9, 9, 9,10,10,10,10,11,11,11,11,11,11,11,
  120335. 11,11,12,12,12,13, 9,10,10, 9,11,10,10,10,10,11,
  120336. 11,11,11,11,10,11,12,11,12,12,11,12,11,10, 9,10,
  120337. 10,11,10,11,11,11,11,11,11,11,11,11,12,12,11,12,
  120338. 12,12,10,10,10,11,10,11,11,11,11,11,11,11,11,11,
  120339. 11,11,12,13,12,12,11, 9,10,10,11,11,10,11,11,11,
  120340. 12,11,11,11,11,11,12,12,13,13,12,13,10,10,12,10,
  120341. 11,11,11,11,11,11,11,11,11,12,12,11,13,12,12,12,
  120342. 12,13,12,11,11,11,11,11,11,12,11,12,11,11,11,11,
  120343. 12,12,13,12,11,12,12,11,11,11,11,11,12,11,11,11,
  120344. 11,12,11,11,12,11,12,13,13,12,12,12,12,11,11,11,
  120345. 11,11,12,11,11,12,11,12,11,11,11,11,13,12,12,12,
  120346. 12,13,11,11,11,12,12,11,11,11,12,11,12,12,12,11,
  120347. 12,13,12,11,11,12,12,11,12,11,11,11,12,12,11,12,
  120348. 11,11,11,12,12,12,12,13,12,13,12,12,12,12,11,11,
  120349. 12,11,11,11,11,11,11,12,12,12,13,12,11,13,13,12,
  120350. 12,11,12,10,11,11,11,11,12,11,12,12,11,12,12,13,
  120351. 12,12,13,12,12,12,12,12,11,12,12,12,11,12,11,11,
  120352. 11,12,13,12,13,13,13,13,13,12,13,13,12,12,13,11,
  120353. 11,11,11,11,12,11,11,12,11,
  120354. };
  120355. static float _vq_quantthresh__16c1_s_p9_2[] = {
  120356. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  120357. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  120358. 6.5, 7.5, 8.5, 9.5,
  120359. };
  120360. static long _vq_quantmap__16c1_s_p9_2[] = {
  120361. 19, 17, 15, 13, 11, 9, 7, 5,
  120362. 3, 1, 0, 2, 4, 6, 8, 10,
  120363. 12, 14, 16, 18, 20,
  120364. };
  120365. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_2 = {
  120366. _vq_quantthresh__16c1_s_p9_2,
  120367. _vq_quantmap__16c1_s_p9_2,
  120368. 21,
  120369. 21
  120370. };
  120371. static static_codebook _16c1_s_p9_2 = {
  120372. 2, 441,
  120373. _vq_lengthlist__16c1_s_p9_2,
  120374. 1, -529268736, 1611661312, 5, 0,
  120375. _vq_quantlist__16c1_s_p9_2,
  120376. NULL,
  120377. &_vq_auxt__16c1_s_p9_2,
  120378. NULL,
  120379. 0
  120380. };
  120381. static long _huff_lengthlist__16c1_s_short[] = {
  120382. 5, 6,17, 8,12, 9,10,10,12,13, 5, 2,17, 4, 9, 5,
  120383. 7, 8,11,13,16,16,16,16,16,16,16,16,16,16, 6, 4,
  120384. 16, 5,10, 5, 7,10,14,16,13, 9,16,11, 8, 7, 8, 9,
  120385. 13,16, 7, 4,16, 5, 7, 4, 6, 8,11,13, 8, 6,16, 7,
  120386. 8, 5, 5, 7, 9,13, 9, 8,16, 9, 8, 6, 6, 7, 9,13,
  120387. 11,11,16,10,10, 7, 7, 7, 9,13,13,13,16,13,13, 9,
  120388. 9, 9,10,13,
  120389. };
  120390. static static_codebook _huff_book__16c1_s_short = {
  120391. 2, 100,
  120392. _huff_lengthlist__16c1_s_short,
  120393. 0, 0, 0, 0, 0,
  120394. NULL,
  120395. NULL,
  120396. NULL,
  120397. NULL,
  120398. 0
  120399. };
  120400. static long _huff_lengthlist__16c2_s_long[] = {
  120401. 4, 7, 9, 9, 9, 8, 9,10,15,19, 5, 4, 5, 6, 7, 7,
  120402. 8, 9,14,16, 6, 5, 4, 5, 6, 7, 8,10,12,19, 7, 6,
  120403. 5, 4, 5, 6, 7, 9,11,18, 8, 7, 6, 5, 5, 5, 7, 9,
  120404. 10,17, 8, 7, 7, 5, 5, 5, 6, 7,12,18, 8, 8, 8, 7,
  120405. 7, 5, 5, 7,12,18, 8, 9,10, 9, 9, 7, 6, 7,12,17,
  120406. 14,18,16,16,15,12,11,10,12,18,15,17,18,18,18,15,
  120407. 14,14,16,18,
  120408. };
  120409. static static_codebook _huff_book__16c2_s_long = {
  120410. 2, 100,
  120411. _huff_lengthlist__16c2_s_long,
  120412. 0, 0, 0, 0, 0,
  120413. NULL,
  120414. NULL,
  120415. NULL,
  120416. NULL,
  120417. 0
  120418. };
  120419. static long _vq_quantlist__16c2_s_p1_0[] = {
  120420. 1,
  120421. 0,
  120422. 2,
  120423. };
  120424. static long _vq_lengthlist__16c2_s_p1_0[] = {
  120425. 1, 3, 3, 0, 0, 0, 0, 0, 0, 4, 5, 5, 0, 0, 0, 0,
  120426. 0, 0, 4, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120430. 0,
  120431. };
  120432. static float _vq_quantthresh__16c2_s_p1_0[] = {
  120433. -0.5, 0.5,
  120434. };
  120435. static long _vq_quantmap__16c2_s_p1_0[] = {
  120436. 1, 0, 2,
  120437. };
  120438. static encode_aux_threshmatch _vq_auxt__16c2_s_p1_0 = {
  120439. _vq_quantthresh__16c2_s_p1_0,
  120440. _vq_quantmap__16c2_s_p1_0,
  120441. 3,
  120442. 3
  120443. };
  120444. static static_codebook _16c2_s_p1_0 = {
  120445. 4, 81,
  120446. _vq_lengthlist__16c2_s_p1_0,
  120447. 1, -535822336, 1611661312, 2, 0,
  120448. _vq_quantlist__16c2_s_p1_0,
  120449. NULL,
  120450. &_vq_auxt__16c2_s_p1_0,
  120451. NULL,
  120452. 0
  120453. };
  120454. static long _vq_quantlist__16c2_s_p2_0[] = {
  120455. 2,
  120456. 1,
  120457. 3,
  120458. 0,
  120459. 4,
  120460. };
  120461. static long _vq_lengthlist__16c2_s_p2_0[] = {
  120462. 2, 4, 3, 7, 7, 0, 0, 0, 7, 8, 0, 0, 0, 8, 8, 0,
  120463. 0, 0, 8, 8, 0, 0, 0, 8, 8, 4, 5, 4, 8, 8, 0, 0,
  120464. 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 9, 9, 0, 0, 0,
  120465. 9, 9, 4, 4, 5, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8,
  120466. 8, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 7, 8, 8,10,10,
  120467. 0, 0, 0,12,11, 0, 0, 0,11,11, 0, 0, 0,14,13, 0,
  120468. 0, 0,14,13, 7, 8, 8, 9,10, 0, 0, 0,11,12, 0, 0,
  120469. 0,11,11, 0, 0, 0,14,14, 0, 0, 0,13,14, 0, 0, 0,
  120470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120474. 0, 0, 0, 0, 0, 0, 0, 0, 8, 8, 8,11,11, 0, 0, 0,
  120475. 11,11, 0, 0, 0,12,11, 0, 0, 0,12,12, 0, 0, 0,13,
  120476. 13, 8, 8, 8,11,11, 0, 0, 0,11,11, 0, 0, 0,11,12,
  120477. 0, 0, 0,12,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0,
  120478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120482. 0, 0, 0, 0, 0, 8, 8, 8,12,11, 0, 0, 0,12,11, 0,
  120483. 0, 0,11,11, 0, 0, 0,13,13, 0, 0, 0,13,12, 8, 8,
  120484. 8,11,12, 0, 0, 0,11,12, 0, 0, 0,11,11, 0, 0, 0,
  120485. 13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120490. 0, 0, 8, 9, 9,14,13, 0, 0, 0,13,12, 0, 0, 0,13,
  120491. 13, 0, 0, 0,13,12, 0, 0, 0,13,13, 8, 9, 9,13,14,
  120492. 0, 0, 0,12,13, 0, 0, 0,13,13, 0, 0, 0,12,13, 0,
  120493. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8,
  120498. 9, 9,14,13, 0, 0, 0,13,13, 0, 0, 0,13,12, 0, 0,
  120499. 0,13,13, 0, 0, 0,13,12, 8, 9, 9,14,14, 0, 0, 0,
  120500. 13,13, 0, 0, 0,12,13, 0, 0, 0,13,13, 0, 0, 0,12,
  120501. 13,
  120502. };
  120503. static float _vq_quantthresh__16c2_s_p2_0[] = {
  120504. -1.5, -0.5, 0.5, 1.5,
  120505. };
  120506. static long _vq_quantmap__16c2_s_p2_0[] = {
  120507. 3, 1, 0, 2, 4,
  120508. };
  120509. static encode_aux_threshmatch _vq_auxt__16c2_s_p2_0 = {
  120510. _vq_quantthresh__16c2_s_p2_0,
  120511. _vq_quantmap__16c2_s_p2_0,
  120512. 5,
  120513. 5
  120514. };
  120515. static static_codebook _16c2_s_p2_0 = {
  120516. 4, 625,
  120517. _vq_lengthlist__16c2_s_p2_0,
  120518. 1, -533725184, 1611661312, 3, 0,
  120519. _vq_quantlist__16c2_s_p2_0,
  120520. NULL,
  120521. &_vq_auxt__16c2_s_p2_0,
  120522. NULL,
  120523. 0
  120524. };
  120525. static long _vq_quantlist__16c2_s_p3_0[] = {
  120526. 4,
  120527. 3,
  120528. 5,
  120529. 2,
  120530. 6,
  120531. 1,
  120532. 7,
  120533. 0,
  120534. 8,
  120535. };
  120536. static long _vq_lengthlist__16c2_s_p3_0[] = {
  120537. 1, 3, 3, 6, 6, 7, 7, 8, 8, 0, 0, 0, 6, 6, 7, 7,
  120538. 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  120539. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  120540. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 9, 9,10,10, 0,
  120541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120542. 0,
  120543. };
  120544. static float _vq_quantthresh__16c2_s_p3_0[] = {
  120545. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  120546. };
  120547. static long _vq_quantmap__16c2_s_p3_0[] = {
  120548. 7, 5, 3, 1, 0, 2, 4, 6,
  120549. 8,
  120550. };
  120551. static encode_aux_threshmatch _vq_auxt__16c2_s_p3_0 = {
  120552. _vq_quantthresh__16c2_s_p3_0,
  120553. _vq_quantmap__16c2_s_p3_0,
  120554. 9,
  120555. 9
  120556. };
  120557. static static_codebook _16c2_s_p3_0 = {
  120558. 2, 81,
  120559. _vq_lengthlist__16c2_s_p3_0,
  120560. 1, -531628032, 1611661312, 4, 0,
  120561. _vq_quantlist__16c2_s_p3_0,
  120562. NULL,
  120563. &_vq_auxt__16c2_s_p3_0,
  120564. NULL,
  120565. 0
  120566. };
  120567. static long _vq_quantlist__16c2_s_p4_0[] = {
  120568. 8,
  120569. 7,
  120570. 9,
  120571. 6,
  120572. 10,
  120573. 5,
  120574. 11,
  120575. 4,
  120576. 12,
  120577. 3,
  120578. 13,
  120579. 2,
  120580. 14,
  120581. 1,
  120582. 15,
  120583. 0,
  120584. 16,
  120585. };
  120586. static long _vq_lengthlist__16c2_s_p4_0[] = {
  120587. 2, 3, 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9,10,
  120588. 10, 0, 0, 0, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  120589. 11,11, 0, 0, 0, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  120590. 10,10,11, 0, 0, 0, 6, 6, 8, 8, 8, 8, 9, 9,10,10,
  120591. 10,11,11,11, 0, 0, 0, 6, 6, 8, 8, 9, 9, 9, 9,10,
  120592. 10,11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,
  120593. 10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9,
  120594. 9,10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  120595. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8, 8, 9,
  120596. 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 0, 0,
  120597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120605. 0,
  120606. };
  120607. static float _vq_quantthresh__16c2_s_p4_0[] = {
  120608. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  120609. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  120610. };
  120611. static long _vq_quantmap__16c2_s_p4_0[] = {
  120612. 15, 13, 11, 9, 7, 5, 3, 1,
  120613. 0, 2, 4, 6, 8, 10, 12, 14,
  120614. 16,
  120615. };
  120616. static encode_aux_threshmatch _vq_auxt__16c2_s_p4_0 = {
  120617. _vq_quantthresh__16c2_s_p4_0,
  120618. _vq_quantmap__16c2_s_p4_0,
  120619. 17,
  120620. 17
  120621. };
  120622. static static_codebook _16c2_s_p4_0 = {
  120623. 2, 289,
  120624. _vq_lengthlist__16c2_s_p4_0,
  120625. 1, -529530880, 1611661312, 5, 0,
  120626. _vq_quantlist__16c2_s_p4_0,
  120627. NULL,
  120628. &_vq_auxt__16c2_s_p4_0,
  120629. NULL,
  120630. 0
  120631. };
  120632. static long _vq_quantlist__16c2_s_p5_0[] = {
  120633. 1,
  120634. 0,
  120635. 2,
  120636. };
  120637. static long _vq_lengthlist__16c2_s_p5_0[] = {
  120638. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 6,10,10,10,10,
  120639. 10,10, 4, 7, 6,10,10,10,10,10,10, 5, 9, 9, 9,12,
  120640. 11,10,11,12, 7,10,10,12,12,12,12,12,12, 7,10,10,
  120641. 11,12,12,12,12,13, 6,10,10,10,12,12,10,12,12, 7,
  120642. 10,10,11,13,12,12,12,12, 7,10,10,11,12,12,12,12,
  120643. 12,
  120644. };
  120645. static float _vq_quantthresh__16c2_s_p5_0[] = {
  120646. -5.5, 5.5,
  120647. };
  120648. static long _vq_quantmap__16c2_s_p5_0[] = {
  120649. 1, 0, 2,
  120650. };
  120651. static encode_aux_threshmatch _vq_auxt__16c2_s_p5_0 = {
  120652. _vq_quantthresh__16c2_s_p5_0,
  120653. _vq_quantmap__16c2_s_p5_0,
  120654. 3,
  120655. 3
  120656. };
  120657. static static_codebook _16c2_s_p5_0 = {
  120658. 4, 81,
  120659. _vq_lengthlist__16c2_s_p5_0,
  120660. 1, -529137664, 1618345984, 2, 0,
  120661. _vq_quantlist__16c2_s_p5_0,
  120662. NULL,
  120663. &_vq_auxt__16c2_s_p5_0,
  120664. NULL,
  120665. 0
  120666. };
  120667. static long _vq_quantlist__16c2_s_p5_1[] = {
  120668. 5,
  120669. 4,
  120670. 6,
  120671. 3,
  120672. 7,
  120673. 2,
  120674. 8,
  120675. 1,
  120676. 9,
  120677. 0,
  120678. 10,
  120679. };
  120680. static long _vq_lengthlist__16c2_s_p5_1[] = {
  120681. 2, 3, 3, 6, 6, 7, 7, 7, 7, 8, 8,11,11,11, 6, 6,
  120682. 7, 7, 8, 8, 8, 8,11,11,11, 6, 6, 7, 7, 8, 8, 8,
  120683. 8,11,11,11, 6, 6, 8, 8, 8, 8, 9, 9,11,11,11, 6,
  120684. 6, 8, 8, 8, 8, 9, 9,11,11,11, 7, 7, 8, 8, 8, 8,
  120685. 8, 8,11,11,11, 7, 7, 8, 8, 8, 8, 8, 9,11,11,11,
  120686. 8, 8, 8, 8, 8, 8, 8, 8,11,11,11,11,11, 8, 8, 8,
  120687. 8, 8, 8,11,11,11,11,11, 8, 8, 8, 8, 8, 8,11,11,
  120688. 11,11,11, 7, 7, 8, 8, 8, 8,
  120689. };
  120690. static float _vq_quantthresh__16c2_s_p5_1[] = {
  120691. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  120692. 3.5, 4.5,
  120693. };
  120694. static long _vq_quantmap__16c2_s_p5_1[] = {
  120695. 9, 7, 5, 3, 1, 0, 2, 4,
  120696. 6, 8, 10,
  120697. };
  120698. static encode_aux_threshmatch _vq_auxt__16c2_s_p5_1 = {
  120699. _vq_quantthresh__16c2_s_p5_1,
  120700. _vq_quantmap__16c2_s_p5_1,
  120701. 11,
  120702. 11
  120703. };
  120704. static static_codebook _16c2_s_p5_1 = {
  120705. 2, 121,
  120706. _vq_lengthlist__16c2_s_p5_1,
  120707. 1, -531365888, 1611661312, 4, 0,
  120708. _vq_quantlist__16c2_s_p5_1,
  120709. NULL,
  120710. &_vq_auxt__16c2_s_p5_1,
  120711. NULL,
  120712. 0
  120713. };
  120714. static long _vq_quantlist__16c2_s_p6_0[] = {
  120715. 6,
  120716. 5,
  120717. 7,
  120718. 4,
  120719. 8,
  120720. 3,
  120721. 9,
  120722. 2,
  120723. 10,
  120724. 1,
  120725. 11,
  120726. 0,
  120727. 12,
  120728. };
  120729. static long _vq_lengthlist__16c2_s_p6_0[] = {
  120730. 1, 4, 4, 7, 6, 8, 8, 9, 9,10,10,11,11, 5, 5, 5,
  120731. 7, 7, 9, 9, 9, 9,11,11,12,12, 6, 5, 5, 7, 7, 9,
  120732. 9,10,10,11,11,12,12, 0, 6, 6, 7, 7, 9, 9,10,10,
  120733. 11,11,12,12, 0, 7, 7, 7, 7, 9, 9,10,10,11,12,12,
  120734. 12, 0,11,11, 8, 8,10,10,11,11,12,12,13,13, 0,11,
  120735. 12, 8, 8,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  120736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120740. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120741. };
  120742. static float _vq_quantthresh__16c2_s_p6_0[] = {
  120743. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  120744. 12.5, 17.5, 22.5, 27.5,
  120745. };
  120746. static long _vq_quantmap__16c2_s_p6_0[] = {
  120747. 11, 9, 7, 5, 3, 1, 0, 2,
  120748. 4, 6, 8, 10, 12,
  120749. };
  120750. static encode_aux_threshmatch _vq_auxt__16c2_s_p6_0 = {
  120751. _vq_quantthresh__16c2_s_p6_0,
  120752. _vq_quantmap__16c2_s_p6_0,
  120753. 13,
  120754. 13
  120755. };
  120756. static static_codebook _16c2_s_p6_0 = {
  120757. 2, 169,
  120758. _vq_lengthlist__16c2_s_p6_0,
  120759. 1, -526516224, 1616117760, 4, 0,
  120760. _vq_quantlist__16c2_s_p6_0,
  120761. NULL,
  120762. &_vq_auxt__16c2_s_p6_0,
  120763. NULL,
  120764. 0
  120765. };
  120766. static long _vq_quantlist__16c2_s_p6_1[] = {
  120767. 2,
  120768. 1,
  120769. 3,
  120770. 0,
  120771. 4,
  120772. };
  120773. static long _vq_lengthlist__16c2_s_p6_1[] = {
  120774. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  120775. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  120776. };
  120777. static float _vq_quantthresh__16c2_s_p6_1[] = {
  120778. -1.5, -0.5, 0.5, 1.5,
  120779. };
  120780. static long _vq_quantmap__16c2_s_p6_1[] = {
  120781. 3, 1, 0, 2, 4,
  120782. };
  120783. static encode_aux_threshmatch _vq_auxt__16c2_s_p6_1 = {
  120784. _vq_quantthresh__16c2_s_p6_1,
  120785. _vq_quantmap__16c2_s_p6_1,
  120786. 5,
  120787. 5
  120788. };
  120789. static static_codebook _16c2_s_p6_1 = {
  120790. 2, 25,
  120791. _vq_lengthlist__16c2_s_p6_1,
  120792. 1, -533725184, 1611661312, 3, 0,
  120793. _vq_quantlist__16c2_s_p6_1,
  120794. NULL,
  120795. &_vq_auxt__16c2_s_p6_1,
  120796. NULL,
  120797. 0
  120798. };
  120799. static long _vq_quantlist__16c2_s_p7_0[] = {
  120800. 6,
  120801. 5,
  120802. 7,
  120803. 4,
  120804. 8,
  120805. 3,
  120806. 9,
  120807. 2,
  120808. 10,
  120809. 1,
  120810. 11,
  120811. 0,
  120812. 12,
  120813. };
  120814. static long _vq_lengthlist__16c2_s_p7_0[] = {
  120815. 1, 4, 4, 7, 7, 8, 8, 9, 9,10,10,11,11, 5, 5, 5,
  120816. 8, 8, 9, 9,10,10,11,11,12,12, 6, 5, 5, 8, 8, 9,
  120817. 9,10,10,11,11,12,13,18, 6, 6, 7, 7, 9, 9,10,10,
  120818. 12,12,13,13,18, 6, 6, 7, 7, 9, 9,10,10,12,12,13,
  120819. 13,18,11,10, 8, 8,10,10,11,11,12,12,13,13,18,11,
  120820. 11, 8, 8,10,10,11,11,12,13,13,13,18,18,18,10,11,
  120821. 11,11,12,12,13,13,14,14,18,18,18,11,11,11,11,12,
  120822. 12,13,13,14,14,18,18,18,14,14,12,12,12,12,14,14,
  120823. 15,14,18,18,18,15,15,11,12,12,12,13,13,15,15,18,
  120824. 18,18,18,18,13,13,13,13,13,14,17,16,18,18,18,18,
  120825. 18,13,14,13,13,14,13,15,14,
  120826. };
  120827. static float _vq_quantthresh__16c2_s_p7_0[] = {
  120828. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  120829. 27.5, 38.5, 49.5, 60.5,
  120830. };
  120831. static long _vq_quantmap__16c2_s_p7_0[] = {
  120832. 11, 9, 7, 5, 3, 1, 0, 2,
  120833. 4, 6, 8, 10, 12,
  120834. };
  120835. static encode_aux_threshmatch _vq_auxt__16c2_s_p7_0 = {
  120836. _vq_quantthresh__16c2_s_p7_0,
  120837. _vq_quantmap__16c2_s_p7_0,
  120838. 13,
  120839. 13
  120840. };
  120841. static static_codebook _16c2_s_p7_0 = {
  120842. 2, 169,
  120843. _vq_lengthlist__16c2_s_p7_0,
  120844. 1, -523206656, 1618345984, 4, 0,
  120845. _vq_quantlist__16c2_s_p7_0,
  120846. NULL,
  120847. &_vq_auxt__16c2_s_p7_0,
  120848. NULL,
  120849. 0
  120850. };
  120851. static long _vq_quantlist__16c2_s_p7_1[] = {
  120852. 5,
  120853. 4,
  120854. 6,
  120855. 3,
  120856. 7,
  120857. 2,
  120858. 8,
  120859. 1,
  120860. 9,
  120861. 0,
  120862. 10,
  120863. };
  120864. static long _vq_lengthlist__16c2_s_p7_1[] = {
  120865. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 7, 9, 9, 9, 6, 6,
  120866. 7, 7, 8, 8, 8, 8, 9, 9, 9, 6, 6, 7, 7, 8, 8, 8,
  120867. 8, 9, 9, 9, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 7,
  120868. 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8,
  120869. 8, 8, 9, 9, 9, 7, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  120870. 7, 7, 8, 8, 7, 7, 8, 8, 9, 9, 9, 9, 9, 7, 7, 7,
  120871. 7, 8, 8, 9, 9, 9, 9, 9, 8, 8, 7, 7, 8, 8, 9, 9,
  120872. 9, 9, 9, 7, 7, 7, 7, 8, 8,
  120873. };
  120874. static float _vq_quantthresh__16c2_s_p7_1[] = {
  120875. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  120876. 3.5, 4.5,
  120877. };
  120878. static long _vq_quantmap__16c2_s_p7_1[] = {
  120879. 9, 7, 5, 3, 1, 0, 2, 4,
  120880. 6, 8, 10,
  120881. };
  120882. static encode_aux_threshmatch _vq_auxt__16c2_s_p7_1 = {
  120883. _vq_quantthresh__16c2_s_p7_1,
  120884. _vq_quantmap__16c2_s_p7_1,
  120885. 11,
  120886. 11
  120887. };
  120888. static static_codebook _16c2_s_p7_1 = {
  120889. 2, 121,
  120890. _vq_lengthlist__16c2_s_p7_1,
  120891. 1, -531365888, 1611661312, 4, 0,
  120892. _vq_quantlist__16c2_s_p7_1,
  120893. NULL,
  120894. &_vq_auxt__16c2_s_p7_1,
  120895. NULL,
  120896. 0
  120897. };
  120898. static long _vq_quantlist__16c2_s_p8_0[] = {
  120899. 7,
  120900. 6,
  120901. 8,
  120902. 5,
  120903. 9,
  120904. 4,
  120905. 10,
  120906. 3,
  120907. 11,
  120908. 2,
  120909. 12,
  120910. 1,
  120911. 13,
  120912. 0,
  120913. 14,
  120914. };
  120915. static long _vq_lengthlist__16c2_s_p8_0[] = {
  120916. 1, 4, 4, 7, 6, 7, 7, 6, 6, 8, 8, 9, 9,10,10, 6,
  120917. 6, 6, 8, 8, 9, 8, 8, 8, 9, 9,11,10,11,11, 7, 6,
  120918. 6, 8, 8, 9, 8, 7, 7, 9, 9,10,10,12,11,14, 8, 8,
  120919. 8, 9, 9, 9, 9, 9,10, 9,10,10,11,13,14, 8, 8, 8,
  120920. 8, 9, 9, 8, 8, 9, 9,10,10,11,12,14,13,11, 9, 9,
  120921. 9, 9, 9, 9, 9,10,11,10,13,12,14,11,13, 8, 9, 9,
  120922. 9, 9, 9,10,10,11,10,13,12,14,14,14, 8, 9, 9, 9,
  120923. 11,11,11,11,11,12,13,13,14,14,14, 9, 8, 9, 9,10,
  120924. 10,12,10,11,12,12,14,14,14,14,11,12,10,10,12,12,
  120925. 12,12,13,14,12,12,14,14,14,12,12, 9,10,11,11,12,
  120926. 14,12,14,14,14,14,14,14,14,14,11,11,12,11,12,14,
  120927. 14,14,14,14,14,14,14,14,14,12,11,11,11,11,14,14,
  120928. 14,14,14,14,14,14,14,14,14,14,13,12,14,14,14,14,
  120929. 14,14,14,14,14,14,14,14,14,12,12,12,13,14,14,13,
  120930. 13,
  120931. };
  120932. static float _vq_quantthresh__16c2_s_p8_0[] = {
  120933. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  120934. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  120935. };
  120936. static long _vq_quantmap__16c2_s_p8_0[] = {
  120937. 13, 11, 9, 7, 5, 3, 1, 0,
  120938. 2, 4, 6, 8, 10, 12, 14,
  120939. };
  120940. static encode_aux_threshmatch _vq_auxt__16c2_s_p8_0 = {
  120941. _vq_quantthresh__16c2_s_p8_0,
  120942. _vq_quantmap__16c2_s_p8_0,
  120943. 15,
  120944. 15
  120945. };
  120946. static static_codebook _16c2_s_p8_0 = {
  120947. 2, 225,
  120948. _vq_lengthlist__16c2_s_p8_0,
  120949. 1, -520986624, 1620377600, 4, 0,
  120950. _vq_quantlist__16c2_s_p8_0,
  120951. NULL,
  120952. &_vq_auxt__16c2_s_p8_0,
  120953. NULL,
  120954. 0
  120955. };
  120956. static long _vq_quantlist__16c2_s_p8_1[] = {
  120957. 10,
  120958. 9,
  120959. 11,
  120960. 8,
  120961. 12,
  120962. 7,
  120963. 13,
  120964. 6,
  120965. 14,
  120966. 5,
  120967. 15,
  120968. 4,
  120969. 16,
  120970. 3,
  120971. 17,
  120972. 2,
  120973. 18,
  120974. 1,
  120975. 19,
  120976. 0,
  120977. 20,
  120978. };
  120979. static long _vq_lengthlist__16c2_s_p8_1[] = {
  120980. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 8,
  120981. 8, 8, 8, 8, 8,11,12,11, 7, 7, 8, 8, 8, 8, 9, 9,
  120982. 9, 9, 9, 9, 9, 9, 9,10, 9, 9,11,11,10, 7, 7, 8,
  120983. 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  120984. 11,11, 8, 7, 8, 8, 9, 9, 9, 9, 9, 9,10,10, 9,10,
  120985. 10, 9,10,10,11,11,12, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  120986. 9, 9, 9,10, 9,10,10,10,10,11,11,11, 8, 8, 9, 9,
  120987. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,11,
  120988. 11, 8, 8, 9, 8, 9, 9, 9, 9,10, 9, 9, 9,10,10,10,
  120989. 10, 9,10,11,11,11, 9, 9, 9, 9,10, 9, 9, 9,10,10,
  120990. 9,10, 9,10,10,10,10,10,11,12,11,11,11, 9, 9, 9,
  120991. 9, 9,10,10, 9,10,10,10,10,10,10,10,10,12,11,13,
  120992. 13,11, 9, 9, 9, 9,10,10, 9,10,10,10,10,11,10,10,
  120993. 10,10,11,12,11,12,11, 9, 9, 9,10,10, 9,10,10,10,
  120994. 10,10,10,10,10,10,10,11,11,11,12,11, 9,10,10,10,
  120995. 10,10,10,10,10,10,10,10,10,10,10,10,11,12,12,12,
  120996. 11,11,11,10, 9,10,10,10,10,10,10,10,10,11,10,10,
  120997. 10,11,11,11,11,11,11,11,10,10,10,11,10,10,10,10,
  120998. 10,10,10,10,10,10,11,11,11,11,12,12,11,10,10,10,
  120999. 10,10,10,10,10,11,10,10,10,11,10,12,11,11,12,11,
  121000. 11,11,10,10,10,10,10,11,10,10,10,10,10,11,10,10,
  121001. 11,11,11,12,11,12,11,11,12,10,10,10,10,10,10,10,
  121002. 11,10,10,11,10,12,11,11,11,12,11,11,11,11,10,10,
  121003. 10,10,10,10,10,11,11,11,10,11,12,11,11,11,12,11,
  121004. 12,11,12,10,11,10,10,10,10,11,10,10,10,10,10,10,
  121005. 12,11,11,11,11,11,12,12,10,10,10,10,10,11,10,10,
  121006. 11,10,11,11,11,11,11,11,11,11,11,11,11,11,12,11,
  121007. 10,11,10,10,10,10,10,10,10,
  121008. };
  121009. static float _vq_quantthresh__16c2_s_p8_1[] = {
  121010. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  121011. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  121012. 6.5, 7.5, 8.5, 9.5,
  121013. };
  121014. static long _vq_quantmap__16c2_s_p8_1[] = {
  121015. 19, 17, 15, 13, 11, 9, 7, 5,
  121016. 3, 1, 0, 2, 4, 6, 8, 10,
  121017. 12, 14, 16, 18, 20,
  121018. };
  121019. static encode_aux_threshmatch _vq_auxt__16c2_s_p8_1 = {
  121020. _vq_quantthresh__16c2_s_p8_1,
  121021. _vq_quantmap__16c2_s_p8_1,
  121022. 21,
  121023. 21
  121024. };
  121025. static static_codebook _16c2_s_p8_1 = {
  121026. 2, 441,
  121027. _vq_lengthlist__16c2_s_p8_1,
  121028. 1, -529268736, 1611661312, 5, 0,
  121029. _vq_quantlist__16c2_s_p8_1,
  121030. NULL,
  121031. &_vq_auxt__16c2_s_p8_1,
  121032. NULL,
  121033. 0
  121034. };
  121035. static long _vq_quantlist__16c2_s_p9_0[] = {
  121036. 6,
  121037. 5,
  121038. 7,
  121039. 4,
  121040. 8,
  121041. 3,
  121042. 9,
  121043. 2,
  121044. 10,
  121045. 1,
  121046. 11,
  121047. 0,
  121048. 12,
  121049. };
  121050. static long _vq_lengthlist__16c2_s_p9_0[] = {
  121051. 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  121052. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  121053. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  121054. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  121055. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  121056. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  121057. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  121058. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  121059. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  121060. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  121061. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  121062. };
  121063. static float _vq_quantthresh__16c2_s_p9_0[] = {
  121064. -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5, 465.5, 1396.5,
  121065. 2327.5, 3258.5, 4189.5, 5120.5,
  121066. };
  121067. static long _vq_quantmap__16c2_s_p9_0[] = {
  121068. 11, 9, 7, 5, 3, 1, 0, 2,
  121069. 4, 6, 8, 10, 12,
  121070. };
  121071. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_0 = {
  121072. _vq_quantthresh__16c2_s_p9_0,
  121073. _vq_quantmap__16c2_s_p9_0,
  121074. 13,
  121075. 13
  121076. };
  121077. static static_codebook _16c2_s_p9_0 = {
  121078. 2, 169,
  121079. _vq_lengthlist__16c2_s_p9_0,
  121080. 1, -510275072, 1631393792, 4, 0,
  121081. _vq_quantlist__16c2_s_p9_0,
  121082. NULL,
  121083. &_vq_auxt__16c2_s_p9_0,
  121084. NULL,
  121085. 0
  121086. };
  121087. static long _vq_quantlist__16c2_s_p9_1[] = {
  121088. 8,
  121089. 7,
  121090. 9,
  121091. 6,
  121092. 10,
  121093. 5,
  121094. 11,
  121095. 4,
  121096. 12,
  121097. 3,
  121098. 13,
  121099. 2,
  121100. 14,
  121101. 1,
  121102. 15,
  121103. 0,
  121104. 16,
  121105. };
  121106. static long _vq_lengthlist__16c2_s_p9_1[] = {
  121107. 1, 5, 5, 9, 8, 7, 7, 7, 6,10,11,11,11,11,11,11,
  121108. 11, 8, 7, 6, 8, 8,10, 9,10,10,10, 9,11,10,10,10,
  121109. 10,10, 8, 6, 6, 8, 8, 9, 8, 9, 8, 9,10,10,10,10,
  121110. 10,10,10,10, 8,10, 9, 9, 9, 9,10,10,10,10,10,10,
  121111. 10,10,10,10,10, 8, 9, 9, 9,10,10, 9,10,10,10,10,
  121112. 10,10,10,10,10,10,10,10, 9, 8, 9, 9,10,10,10,10,
  121113. 10,10,10,10,10,10,10,10, 9, 8, 8, 9, 9,10,10,10,
  121114. 10,10,10,10,10,10,10,10,10,10, 9,10, 9, 9,10,10,
  121115. 10,10,10,10,10,10,10,10,10,10,10, 9, 8, 9, 9,10,
  121116. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  121117. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121118. 8,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121119. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121120. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121121. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121122. 10,10,10,10, 9,10, 9,10,10,10,10,10,10,10,10,10,
  121123. 10,10,10,10,10,10,10,10,10, 9,10,10,10,10,10,10,
  121124. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121125. 10,
  121126. };
  121127. static float _vq_quantthresh__16c2_s_p9_1[] = {
  121128. -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5, -24.5,
  121129. 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5, 367.5,
  121130. };
  121131. static long _vq_quantmap__16c2_s_p9_1[] = {
  121132. 15, 13, 11, 9, 7, 5, 3, 1,
  121133. 0, 2, 4, 6, 8, 10, 12, 14,
  121134. 16,
  121135. };
  121136. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_1 = {
  121137. _vq_quantthresh__16c2_s_p9_1,
  121138. _vq_quantmap__16c2_s_p9_1,
  121139. 17,
  121140. 17
  121141. };
  121142. static static_codebook _16c2_s_p9_1 = {
  121143. 2, 289,
  121144. _vq_lengthlist__16c2_s_p9_1,
  121145. 1, -518488064, 1622704128, 5, 0,
  121146. _vq_quantlist__16c2_s_p9_1,
  121147. NULL,
  121148. &_vq_auxt__16c2_s_p9_1,
  121149. NULL,
  121150. 0
  121151. };
  121152. static long _vq_quantlist__16c2_s_p9_2[] = {
  121153. 13,
  121154. 12,
  121155. 14,
  121156. 11,
  121157. 15,
  121158. 10,
  121159. 16,
  121160. 9,
  121161. 17,
  121162. 8,
  121163. 18,
  121164. 7,
  121165. 19,
  121166. 6,
  121167. 20,
  121168. 5,
  121169. 21,
  121170. 4,
  121171. 22,
  121172. 3,
  121173. 23,
  121174. 2,
  121175. 24,
  121176. 1,
  121177. 25,
  121178. 0,
  121179. 26,
  121180. };
  121181. static long _vq_lengthlist__16c2_s_p9_2[] = {
  121182. 1, 4, 4, 5, 5, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  121183. 7, 7, 7, 7, 8, 7, 8, 7, 7, 4, 4,
  121184. };
  121185. static float _vq_quantthresh__16c2_s_p9_2[] = {
  121186. -12.5, -11.5, -10.5, -9.5, -8.5, -7.5, -6.5, -5.5,
  121187. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  121188. 3.5, 4.5, 5.5, 6.5, 7.5, 8.5, 9.5, 10.5,
  121189. 11.5, 12.5,
  121190. };
  121191. static long _vq_quantmap__16c2_s_p9_2[] = {
  121192. 25, 23, 21, 19, 17, 15, 13, 11,
  121193. 9, 7, 5, 3, 1, 0, 2, 4,
  121194. 6, 8, 10, 12, 14, 16, 18, 20,
  121195. 22, 24, 26,
  121196. };
  121197. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_2 = {
  121198. _vq_quantthresh__16c2_s_p9_2,
  121199. _vq_quantmap__16c2_s_p9_2,
  121200. 27,
  121201. 27
  121202. };
  121203. static static_codebook _16c2_s_p9_2 = {
  121204. 1, 27,
  121205. _vq_lengthlist__16c2_s_p9_2,
  121206. 1, -528875520, 1611661312, 5, 0,
  121207. _vq_quantlist__16c2_s_p9_2,
  121208. NULL,
  121209. &_vq_auxt__16c2_s_p9_2,
  121210. NULL,
  121211. 0
  121212. };
  121213. static long _huff_lengthlist__16c2_s_short[] = {
  121214. 7,10,11,11,11,14,15,15,17,14, 8, 6, 7, 7, 8, 9,
  121215. 11,11,14,17, 9, 6, 6, 6, 7, 7,10,11,15,16, 9, 6,
  121216. 6, 4, 4, 5, 8, 9,12,16,10, 6, 6, 4, 4, 4, 6, 9,
  121217. 13,16,10, 7, 6, 5, 4, 3, 5, 7,13,16,11, 9, 8, 7,
  121218. 6, 5, 5, 6,12,15,10,10,10, 9, 7, 6, 6, 7,11,15,
  121219. 13,13,13,13,11,10,10, 9,12,16,16,16,16,14,16,15,
  121220. 15,12,14,14,
  121221. };
  121222. static static_codebook _huff_book__16c2_s_short = {
  121223. 2, 100,
  121224. _huff_lengthlist__16c2_s_short,
  121225. 0, 0, 0, 0, 0,
  121226. NULL,
  121227. NULL,
  121228. NULL,
  121229. NULL,
  121230. 0
  121231. };
  121232. static long _vq_quantlist__8c0_s_p1_0[] = {
  121233. 1,
  121234. 0,
  121235. 2,
  121236. };
  121237. static long _vq_lengthlist__8c0_s_p1_0[] = {
  121238. 1, 5, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  121239. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121243. 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 9, 0, 0, 0,
  121244. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121248. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  121249. 0, 0, 0, 0, 7, 9, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  121284. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  121285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10, 9, 0, 0, 0,
  121289. 0, 0, 0, 8, 9,11, 0, 0, 0, 0, 0, 0, 9,11,11, 0,
  121290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9,10, 0, 0,
  121294. 0, 0, 0, 0, 9,11,10, 0, 0, 0, 0, 0, 0, 9,11,11,
  121295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121329. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  121330. 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121334. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,11, 0,
  121335. 0, 0, 0, 0, 0, 9,10,11, 0, 0, 0, 0, 0, 0, 0, 0,
  121336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121339. 0, 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,11,11,
  121340. 0, 0, 0, 0, 0, 0, 8,11, 9, 0, 0, 0, 0, 0, 0, 0,
  121341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121648. 0,
  121649. };
  121650. static float _vq_quantthresh__8c0_s_p1_0[] = {
  121651. -0.5, 0.5,
  121652. };
  121653. static long _vq_quantmap__8c0_s_p1_0[] = {
  121654. 1, 0, 2,
  121655. };
  121656. static encode_aux_threshmatch _vq_auxt__8c0_s_p1_0 = {
  121657. _vq_quantthresh__8c0_s_p1_0,
  121658. _vq_quantmap__8c0_s_p1_0,
  121659. 3,
  121660. 3
  121661. };
  121662. static static_codebook _8c0_s_p1_0 = {
  121663. 8, 6561,
  121664. _vq_lengthlist__8c0_s_p1_0,
  121665. 1, -535822336, 1611661312, 2, 0,
  121666. _vq_quantlist__8c0_s_p1_0,
  121667. NULL,
  121668. &_vq_auxt__8c0_s_p1_0,
  121669. NULL,
  121670. 0
  121671. };
  121672. static long _vq_quantlist__8c0_s_p2_0[] = {
  121673. 2,
  121674. 1,
  121675. 3,
  121676. 0,
  121677. 4,
  121678. };
  121679. static long _vq_lengthlist__8c0_s_p2_0[] = {
  121680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121719. 0,
  121720. };
  121721. static float _vq_quantthresh__8c0_s_p2_0[] = {
  121722. -1.5, -0.5, 0.5, 1.5,
  121723. };
  121724. static long _vq_quantmap__8c0_s_p2_0[] = {
  121725. 3, 1, 0, 2, 4,
  121726. };
  121727. static encode_aux_threshmatch _vq_auxt__8c0_s_p2_0 = {
  121728. _vq_quantthresh__8c0_s_p2_0,
  121729. _vq_quantmap__8c0_s_p2_0,
  121730. 5,
  121731. 5
  121732. };
  121733. static static_codebook _8c0_s_p2_0 = {
  121734. 4, 625,
  121735. _vq_lengthlist__8c0_s_p2_0,
  121736. 1, -533725184, 1611661312, 3, 0,
  121737. _vq_quantlist__8c0_s_p2_0,
  121738. NULL,
  121739. &_vq_auxt__8c0_s_p2_0,
  121740. NULL,
  121741. 0
  121742. };
  121743. static long _vq_quantlist__8c0_s_p3_0[] = {
  121744. 2,
  121745. 1,
  121746. 3,
  121747. 0,
  121748. 4,
  121749. };
  121750. static long _vq_lengthlist__8c0_s_p3_0[] = {
  121751. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 6, 7, 7, 0, 0,
  121753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121754. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 8, 8,
  121756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121757. 0, 0, 0, 0, 6, 7, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  121758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121790. 0,
  121791. };
  121792. static float _vq_quantthresh__8c0_s_p3_0[] = {
  121793. -1.5, -0.5, 0.5, 1.5,
  121794. };
  121795. static long _vq_quantmap__8c0_s_p3_0[] = {
  121796. 3, 1, 0, 2, 4,
  121797. };
  121798. static encode_aux_threshmatch _vq_auxt__8c0_s_p3_0 = {
  121799. _vq_quantthresh__8c0_s_p3_0,
  121800. _vq_quantmap__8c0_s_p3_0,
  121801. 5,
  121802. 5
  121803. };
  121804. static static_codebook _8c0_s_p3_0 = {
  121805. 4, 625,
  121806. _vq_lengthlist__8c0_s_p3_0,
  121807. 1, -533725184, 1611661312, 3, 0,
  121808. _vq_quantlist__8c0_s_p3_0,
  121809. NULL,
  121810. &_vq_auxt__8c0_s_p3_0,
  121811. NULL,
  121812. 0
  121813. };
  121814. static long _vq_quantlist__8c0_s_p4_0[] = {
  121815. 4,
  121816. 3,
  121817. 5,
  121818. 2,
  121819. 6,
  121820. 1,
  121821. 7,
  121822. 0,
  121823. 8,
  121824. };
  121825. static long _vq_lengthlist__8c0_s_p4_0[] = {
  121826. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  121827. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  121828. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  121829. 8, 8, 0, 0, 0, 0, 0, 0, 0, 9, 8, 0, 0, 0, 0, 0,
  121830. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121831. 0,
  121832. };
  121833. static float _vq_quantthresh__8c0_s_p4_0[] = {
  121834. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  121835. };
  121836. static long _vq_quantmap__8c0_s_p4_0[] = {
  121837. 7, 5, 3, 1, 0, 2, 4, 6,
  121838. 8,
  121839. };
  121840. static encode_aux_threshmatch _vq_auxt__8c0_s_p4_0 = {
  121841. _vq_quantthresh__8c0_s_p4_0,
  121842. _vq_quantmap__8c0_s_p4_0,
  121843. 9,
  121844. 9
  121845. };
  121846. static static_codebook _8c0_s_p4_0 = {
  121847. 2, 81,
  121848. _vq_lengthlist__8c0_s_p4_0,
  121849. 1, -531628032, 1611661312, 4, 0,
  121850. _vq_quantlist__8c0_s_p4_0,
  121851. NULL,
  121852. &_vq_auxt__8c0_s_p4_0,
  121853. NULL,
  121854. 0
  121855. };
  121856. static long _vq_quantlist__8c0_s_p5_0[] = {
  121857. 4,
  121858. 3,
  121859. 5,
  121860. 2,
  121861. 6,
  121862. 1,
  121863. 7,
  121864. 0,
  121865. 8,
  121866. };
  121867. static long _vq_lengthlist__8c0_s_p5_0[] = {
  121868. 1, 3, 3, 5, 5, 7, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  121869. 8, 8, 0, 0, 0, 7, 7, 7, 7, 8, 9, 0, 0, 0, 8, 8,
  121870. 8, 8, 9, 9, 0, 0, 0, 8, 8, 8, 8, 9, 9, 0, 0, 0,
  121871. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  121872. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  121873. 10,
  121874. };
  121875. static float _vq_quantthresh__8c0_s_p5_0[] = {
  121876. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  121877. };
  121878. static long _vq_quantmap__8c0_s_p5_0[] = {
  121879. 7, 5, 3, 1, 0, 2, 4, 6,
  121880. 8,
  121881. };
  121882. static encode_aux_threshmatch _vq_auxt__8c0_s_p5_0 = {
  121883. _vq_quantthresh__8c0_s_p5_0,
  121884. _vq_quantmap__8c0_s_p5_0,
  121885. 9,
  121886. 9
  121887. };
  121888. static static_codebook _8c0_s_p5_0 = {
  121889. 2, 81,
  121890. _vq_lengthlist__8c0_s_p5_0,
  121891. 1, -531628032, 1611661312, 4, 0,
  121892. _vq_quantlist__8c0_s_p5_0,
  121893. NULL,
  121894. &_vq_auxt__8c0_s_p5_0,
  121895. NULL,
  121896. 0
  121897. };
  121898. static long _vq_quantlist__8c0_s_p6_0[] = {
  121899. 8,
  121900. 7,
  121901. 9,
  121902. 6,
  121903. 10,
  121904. 5,
  121905. 11,
  121906. 4,
  121907. 12,
  121908. 3,
  121909. 13,
  121910. 2,
  121911. 14,
  121912. 1,
  121913. 15,
  121914. 0,
  121915. 16,
  121916. };
  121917. static long _vq_lengthlist__8c0_s_p6_0[] = {
  121918. 1, 3, 3, 6, 6, 8, 8, 9, 9, 8, 8,10, 9,10,10,11,
  121919. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  121920. 11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  121921. 11,12,11, 0, 0, 0, 8, 8, 9, 9,10,10, 9, 9,10,10,
  121922. 11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10, 9, 9,11,
  121923. 10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,10,10,
  121924. 11,11,11,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,10,
  121925. 10,11,11,12,12,13,13, 0, 0, 0,10,10,10,10,11,11,
  121926. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,10, 9,10,
  121927. 11,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  121928. 10, 9,10,11,12,12,13,13,14,13, 0, 0, 0, 0, 0, 9,
  121929. 9, 9,10,10,10,11,11,13,12,13,13, 0, 0, 0, 0, 0,
  121930. 10,10,10,10,11,11,12,12,13,13,14,14, 0, 0, 0, 0,
  121931. 0, 0, 0,10,10,11,11,12,12,13,13,13,14, 0, 0, 0,
  121932. 0, 0, 0, 0,11,11,11,11,12,12,13,14,14,14, 0, 0,
  121933. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,14,13, 0,
  121934. 0, 0, 0, 0, 0, 0,11,11,12,12,13,13,14,14,14,14,
  121935. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  121936. 14,
  121937. };
  121938. static float _vq_quantthresh__8c0_s_p6_0[] = {
  121939. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  121940. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  121941. };
  121942. static long _vq_quantmap__8c0_s_p6_0[] = {
  121943. 15, 13, 11, 9, 7, 5, 3, 1,
  121944. 0, 2, 4, 6, 8, 10, 12, 14,
  121945. 16,
  121946. };
  121947. static encode_aux_threshmatch _vq_auxt__8c0_s_p6_0 = {
  121948. _vq_quantthresh__8c0_s_p6_0,
  121949. _vq_quantmap__8c0_s_p6_0,
  121950. 17,
  121951. 17
  121952. };
  121953. static static_codebook _8c0_s_p6_0 = {
  121954. 2, 289,
  121955. _vq_lengthlist__8c0_s_p6_0,
  121956. 1, -529530880, 1611661312, 5, 0,
  121957. _vq_quantlist__8c0_s_p6_0,
  121958. NULL,
  121959. &_vq_auxt__8c0_s_p6_0,
  121960. NULL,
  121961. 0
  121962. };
  121963. static long _vq_quantlist__8c0_s_p7_0[] = {
  121964. 1,
  121965. 0,
  121966. 2,
  121967. };
  121968. static long _vq_lengthlist__8c0_s_p7_0[] = {
  121969. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,11, 9,10,12,
  121970. 9,10, 4, 7, 7,10,10,10,11, 9, 9, 6,11,10,11,11,
  121971. 12,11,11,11, 6,10,10,11,11,12,11,10,10, 6, 9,10,
  121972. 11,11,11,11,10,10, 7,10,11,12,11,11,12,11,12, 6,
  121973. 9, 9,10, 9, 9,11,10,10, 6, 9, 9,10,10,10,11,10,
  121974. 10,
  121975. };
  121976. static float _vq_quantthresh__8c0_s_p7_0[] = {
  121977. -5.5, 5.5,
  121978. };
  121979. static long _vq_quantmap__8c0_s_p7_0[] = {
  121980. 1, 0, 2,
  121981. };
  121982. static encode_aux_threshmatch _vq_auxt__8c0_s_p7_0 = {
  121983. _vq_quantthresh__8c0_s_p7_0,
  121984. _vq_quantmap__8c0_s_p7_0,
  121985. 3,
  121986. 3
  121987. };
  121988. static static_codebook _8c0_s_p7_0 = {
  121989. 4, 81,
  121990. _vq_lengthlist__8c0_s_p7_0,
  121991. 1, -529137664, 1618345984, 2, 0,
  121992. _vq_quantlist__8c0_s_p7_0,
  121993. NULL,
  121994. &_vq_auxt__8c0_s_p7_0,
  121995. NULL,
  121996. 0
  121997. };
  121998. static long _vq_quantlist__8c0_s_p7_1[] = {
  121999. 5,
  122000. 4,
  122001. 6,
  122002. 3,
  122003. 7,
  122004. 2,
  122005. 8,
  122006. 1,
  122007. 9,
  122008. 0,
  122009. 10,
  122010. };
  122011. static long _vq_lengthlist__8c0_s_p7_1[] = {
  122012. 1, 3, 3, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10, 7, 7,
  122013. 8, 8, 9, 9, 9, 9,10,10, 9, 7, 7, 8, 8, 9, 9, 9,
  122014. 9,10,10,10, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10, 8,
  122015. 8, 9, 9, 9, 9, 8, 9,10,10,10, 8, 8, 9, 9, 9,10,
  122016. 10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,10,11,10,11,
  122017. 9, 9, 9, 9,10,10,10,10,11,11,11,10,10, 9, 9,10,
  122018. 10,10, 9,11,10,10,10,10,10,10, 9, 9,10,10,11,11,
  122019. 10,10,10, 9, 9, 9,10,10,10,
  122020. };
  122021. static float _vq_quantthresh__8c0_s_p7_1[] = {
  122022. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  122023. 3.5, 4.5,
  122024. };
  122025. static long _vq_quantmap__8c0_s_p7_1[] = {
  122026. 9, 7, 5, 3, 1, 0, 2, 4,
  122027. 6, 8, 10,
  122028. };
  122029. static encode_aux_threshmatch _vq_auxt__8c0_s_p7_1 = {
  122030. _vq_quantthresh__8c0_s_p7_1,
  122031. _vq_quantmap__8c0_s_p7_1,
  122032. 11,
  122033. 11
  122034. };
  122035. static static_codebook _8c0_s_p7_1 = {
  122036. 2, 121,
  122037. _vq_lengthlist__8c0_s_p7_1,
  122038. 1, -531365888, 1611661312, 4, 0,
  122039. _vq_quantlist__8c0_s_p7_1,
  122040. NULL,
  122041. &_vq_auxt__8c0_s_p7_1,
  122042. NULL,
  122043. 0
  122044. };
  122045. static long _vq_quantlist__8c0_s_p8_0[] = {
  122046. 6,
  122047. 5,
  122048. 7,
  122049. 4,
  122050. 8,
  122051. 3,
  122052. 9,
  122053. 2,
  122054. 10,
  122055. 1,
  122056. 11,
  122057. 0,
  122058. 12,
  122059. };
  122060. static long _vq_lengthlist__8c0_s_p8_0[] = {
  122061. 1, 4, 4, 7, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 6, 6,
  122062. 7, 7, 8, 8, 7, 7, 8, 9,10,10, 7, 6, 6, 7, 7, 8,
  122063. 7, 7, 7, 9, 9,10,12, 0, 8, 8, 8, 8, 8, 9, 8, 8,
  122064. 9, 9,10,10, 0, 8, 8, 8, 8, 8, 9, 8, 9, 9, 9,11,
  122065. 10, 0, 0,13, 9, 8, 9, 9, 9, 9,10,10,11,11, 0,13,
  122066. 0, 9, 9, 9, 9, 9, 9,11,10,11,11, 0, 0, 0, 8, 9,
  122067. 10, 9,10,10,13,11,12,12, 0, 0, 0, 8, 9, 9, 9,10,
  122068. 10,13,12,12,13, 0, 0, 0,12, 0,10,10,12,11,10,11,
  122069. 12,12, 0, 0, 0,13,13,10,10,10,11,12, 0,13, 0, 0,
  122070. 0, 0, 0, 0,13,11, 0,12,12,12,13,12, 0, 0, 0, 0,
  122071. 0, 0,13,13,11,13,13,11,12,
  122072. };
  122073. static float _vq_quantthresh__8c0_s_p8_0[] = {
  122074. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  122075. 12.5, 17.5, 22.5, 27.5,
  122076. };
  122077. static long _vq_quantmap__8c0_s_p8_0[] = {
  122078. 11, 9, 7, 5, 3, 1, 0, 2,
  122079. 4, 6, 8, 10, 12,
  122080. };
  122081. static encode_aux_threshmatch _vq_auxt__8c0_s_p8_0 = {
  122082. _vq_quantthresh__8c0_s_p8_0,
  122083. _vq_quantmap__8c0_s_p8_0,
  122084. 13,
  122085. 13
  122086. };
  122087. static static_codebook _8c0_s_p8_0 = {
  122088. 2, 169,
  122089. _vq_lengthlist__8c0_s_p8_0,
  122090. 1, -526516224, 1616117760, 4, 0,
  122091. _vq_quantlist__8c0_s_p8_0,
  122092. NULL,
  122093. &_vq_auxt__8c0_s_p8_0,
  122094. NULL,
  122095. 0
  122096. };
  122097. static long _vq_quantlist__8c0_s_p8_1[] = {
  122098. 2,
  122099. 1,
  122100. 3,
  122101. 0,
  122102. 4,
  122103. };
  122104. static long _vq_lengthlist__8c0_s_p8_1[] = {
  122105. 1, 3, 4, 5, 5, 7, 6, 6, 6, 5, 7, 7, 7, 6, 6, 7,
  122106. 7, 7, 6, 6, 7, 7, 7, 6, 6,
  122107. };
  122108. static float _vq_quantthresh__8c0_s_p8_1[] = {
  122109. -1.5, -0.5, 0.5, 1.5,
  122110. };
  122111. static long _vq_quantmap__8c0_s_p8_1[] = {
  122112. 3, 1, 0, 2, 4,
  122113. };
  122114. static encode_aux_threshmatch _vq_auxt__8c0_s_p8_1 = {
  122115. _vq_quantthresh__8c0_s_p8_1,
  122116. _vq_quantmap__8c0_s_p8_1,
  122117. 5,
  122118. 5
  122119. };
  122120. static static_codebook _8c0_s_p8_1 = {
  122121. 2, 25,
  122122. _vq_lengthlist__8c0_s_p8_1,
  122123. 1, -533725184, 1611661312, 3, 0,
  122124. _vq_quantlist__8c0_s_p8_1,
  122125. NULL,
  122126. &_vq_auxt__8c0_s_p8_1,
  122127. NULL,
  122128. 0
  122129. };
  122130. static long _vq_quantlist__8c0_s_p9_0[] = {
  122131. 1,
  122132. 0,
  122133. 2,
  122134. };
  122135. static long _vq_lengthlist__8c0_s_p9_0[] = {
  122136. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  122137. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  122138. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122139. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122140. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122141. 7,
  122142. };
  122143. static float _vq_quantthresh__8c0_s_p9_0[] = {
  122144. -157.5, 157.5,
  122145. };
  122146. static long _vq_quantmap__8c0_s_p9_0[] = {
  122147. 1, 0, 2,
  122148. };
  122149. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_0 = {
  122150. _vq_quantthresh__8c0_s_p9_0,
  122151. _vq_quantmap__8c0_s_p9_0,
  122152. 3,
  122153. 3
  122154. };
  122155. static static_codebook _8c0_s_p9_0 = {
  122156. 4, 81,
  122157. _vq_lengthlist__8c0_s_p9_0,
  122158. 1, -518803456, 1628680192, 2, 0,
  122159. _vq_quantlist__8c0_s_p9_0,
  122160. NULL,
  122161. &_vq_auxt__8c0_s_p9_0,
  122162. NULL,
  122163. 0
  122164. };
  122165. static long _vq_quantlist__8c0_s_p9_1[] = {
  122166. 7,
  122167. 6,
  122168. 8,
  122169. 5,
  122170. 9,
  122171. 4,
  122172. 10,
  122173. 3,
  122174. 11,
  122175. 2,
  122176. 12,
  122177. 1,
  122178. 13,
  122179. 0,
  122180. 14,
  122181. };
  122182. static long _vq_lengthlist__8c0_s_p9_1[] = {
  122183. 1, 4, 4, 5, 5,10, 8,11,11,11,11,11,11,11,11, 6,
  122184. 6, 6, 7, 6,11,10,11,11,11,11,11,11,11,11, 7, 5,
  122185. 6, 6, 6, 8, 7,11,11,11,11,11,11,11,11,11, 7, 8,
  122186. 8, 8, 9, 9,11,11,11,11,11,11,11,11,11, 9, 8, 7,
  122187. 8, 9,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
  122188. 11,11,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
  122189. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  122190. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  122191. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  122192. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  122193. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  122194. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  122195. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  122196. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  122197. 11,
  122198. };
  122199. static float _vq_quantthresh__8c0_s_p9_1[] = {
  122200. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  122201. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  122202. };
  122203. static long _vq_quantmap__8c0_s_p9_1[] = {
  122204. 13, 11, 9, 7, 5, 3, 1, 0,
  122205. 2, 4, 6, 8, 10, 12, 14,
  122206. };
  122207. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_1 = {
  122208. _vq_quantthresh__8c0_s_p9_1,
  122209. _vq_quantmap__8c0_s_p9_1,
  122210. 15,
  122211. 15
  122212. };
  122213. static static_codebook _8c0_s_p9_1 = {
  122214. 2, 225,
  122215. _vq_lengthlist__8c0_s_p9_1,
  122216. 1, -520986624, 1620377600, 4, 0,
  122217. _vq_quantlist__8c0_s_p9_1,
  122218. NULL,
  122219. &_vq_auxt__8c0_s_p9_1,
  122220. NULL,
  122221. 0
  122222. };
  122223. static long _vq_quantlist__8c0_s_p9_2[] = {
  122224. 10,
  122225. 9,
  122226. 11,
  122227. 8,
  122228. 12,
  122229. 7,
  122230. 13,
  122231. 6,
  122232. 14,
  122233. 5,
  122234. 15,
  122235. 4,
  122236. 16,
  122237. 3,
  122238. 17,
  122239. 2,
  122240. 18,
  122241. 1,
  122242. 19,
  122243. 0,
  122244. 20,
  122245. };
  122246. static long _vq_lengthlist__8c0_s_p9_2[] = {
  122247. 1, 5, 5, 7, 7, 8, 7, 8, 8,10,10, 9, 9,10,10,10,
  122248. 11,11,10,12,11,12,12,12, 9, 8, 8, 8, 8, 8, 9,10,
  122249. 10,10,10,11,11,11,10,11,11,12,12,11,12, 8, 8, 7,
  122250. 7, 8, 9,10,10,10, 9,10,10, 9,10,10,11,11,11,11,
  122251. 11,11, 9, 9, 9, 9, 8, 9,10,10,11,10,10,11,11,12,
  122252. 10,10,12,12,11,11,10, 9, 9,10, 8, 9,10,10,10, 9,
  122253. 10,10,11,11,10,11,10,10,10,12,12,12, 9,10, 9,10,
  122254. 9, 9,10,10,11,11,11,11,10,10,10,11,12,11,12,11,
  122255. 12,10,11,10,11, 9,10, 9,10, 9,10,10, 9,10,10,11,
  122256. 10,11,11,11,11,12,11, 9,10,10,10,10,11,11,11,11,
  122257. 11,10,11,11,11,11,10,12,10,12,12,11,12,10,10,11,
  122258. 10, 9,11,10,11, 9,10,11,10,10,10,11,11,11,11,12,
  122259. 12,10, 9, 9,11,10, 9,12,11,10,12,12,11,11,11,11,
  122260. 10,11,11,12,11,10,12, 9,11,10,11,10,10,11,10,11,
  122261. 9,10,10,10,11,12,11,11,12,11,10,10,11,11, 9,10,
  122262. 10,12,10,11,10,10,10, 9,10,10,10,10, 9,10,10,11,
  122263. 11,11,11,12,11,10,10,10,10,11,11,10,11,11, 9,11,
  122264. 10,12,10,12,11,10,11,10,10,10,11,10,10,11,11,10,
  122265. 11,10,10,10,10,11,11,12,10,10,10,11,10,11,12,11,
  122266. 10,11,10,10,11,11,10,12,10, 9,10,10,11,11,11,10,
  122267. 12,10,10,11,11,11,10,10,11,10,10,10,11,10,11,10,
  122268. 12,11,11,10,10,10,12,10,10,11, 9,10,11,11,11,10,
  122269. 10,11,10,10, 9,11,11,12,12,11,12,11,11,11,11,11,
  122270. 11, 9,10,11,10,12,10,10,10,10,11,10,10,11,10,10,
  122271. 12,10,10,10,10,10, 9,12,10,10,10,10,12, 9,11,10,
  122272. 10,11,10,12,12,10,12,12,12,10,10,10,10, 9,10,11,
  122273. 10,10,12,10,10,12,11,10,11,10,10,12,11,10,12,10,
  122274. 10,11, 9,11,10, 9,10, 9,10,
  122275. };
  122276. static float _vq_quantthresh__8c0_s_p9_2[] = {
  122277. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  122278. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  122279. 6.5, 7.5, 8.5, 9.5,
  122280. };
  122281. static long _vq_quantmap__8c0_s_p9_2[] = {
  122282. 19, 17, 15, 13, 11, 9, 7, 5,
  122283. 3, 1, 0, 2, 4, 6, 8, 10,
  122284. 12, 14, 16, 18, 20,
  122285. };
  122286. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_2 = {
  122287. _vq_quantthresh__8c0_s_p9_2,
  122288. _vq_quantmap__8c0_s_p9_2,
  122289. 21,
  122290. 21
  122291. };
  122292. static static_codebook _8c0_s_p9_2 = {
  122293. 2, 441,
  122294. _vq_lengthlist__8c0_s_p9_2,
  122295. 1, -529268736, 1611661312, 5, 0,
  122296. _vq_quantlist__8c0_s_p9_2,
  122297. NULL,
  122298. &_vq_auxt__8c0_s_p9_2,
  122299. NULL,
  122300. 0
  122301. };
  122302. static long _huff_lengthlist__8c0_s_single[] = {
  122303. 4, 5,18, 7,10, 6, 7, 8, 9,10, 5, 2,18, 5, 7, 5,
  122304. 6, 7, 8,11,17,17,17,17,17,17,17,17,17,17, 7, 4,
  122305. 17, 6, 9, 6, 8,10,12,15,11, 7,17, 9, 6, 6, 7, 9,
  122306. 11,15, 6, 4,17, 6, 6, 4, 5, 8,11,16, 6, 6,17, 8,
  122307. 6, 5, 6, 9,13,16, 8, 9,17,11, 9, 8, 8,11,13,17,
  122308. 9,12,17,15,14,13,12,13,14,17,12,15,17,17,17,17,
  122309. 17,16,17,17,
  122310. };
  122311. static static_codebook _huff_book__8c0_s_single = {
  122312. 2, 100,
  122313. _huff_lengthlist__8c0_s_single,
  122314. 0, 0, 0, 0, 0,
  122315. NULL,
  122316. NULL,
  122317. NULL,
  122318. NULL,
  122319. 0
  122320. };
  122321. static long _vq_quantlist__8c1_s_p1_0[] = {
  122322. 1,
  122323. 0,
  122324. 2,
  122325. };
  122326. static long _vq_lengthlist__8c1_s_p1_0[] = {
  122327. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  122328. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122332. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 8, 9, 0, 0, 0,
  122333. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122337. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  122338. 0, 0, 0, 0, 7, 9, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  122373. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  122374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  122378. 0, 0, 0, 8, 8,10, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  122379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  122383. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  122384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122418. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  122419. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122423. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  122424. 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  122425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122428. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  122429. 0, 0, 0, 0, 0, 0, 8,10, 8, 0, 0, 0, 0, 0, 0, 0,
  122430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122737. 0,
  122738. };
  122739. static float _vq_quantthresh__8c1_s_p1_0[] = {
  122740. -0.5, 0.5,
  122741. };
  122742. static long _vq_quantmap__8c1_s_p1_0[] = {
  122743. 1, 0, 2,
  122744. };
  122745. static encode_aux_threshmatch _vq_auxt__8c1_s_p1_0 = {
  122746. _vq_quantthresh__8c1_s_p1_0,
  122747. _vq_quantmap__8c1_s_p1_0,
  122748. 3,
  122749. 3
  122750. };
  122751. static static_codebook _8c1_s_p1_0 = {
  122752. 8, 6561,
  122753. _vq_lengthlist__8c1_s_p1_0,
  122754. 1, -535822336, 1611661312, 2, 0,
  122755. _vq_quantlist__8c1_s_p1_0,
  122756. NULL,
  122757. &_vq_auxt__8c1_s_p1_0,
  122758. NULL,
  122759. 0
  122760. };
  122761. static long _vq_quantlist__8c1_s_p2_0[] = {
  122762. 2,
  122763. 1,
  122764. 3,
  122765. 0,
  122766. 4,
  122767. };
  122768. static long _vq_lengthlist__8c1_s_p2_0[] = {
  122769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122808. 0,
  122809. };
  122810. static float _vq_quantthresh__8c1_s_p2_0[] = {
  122811. -1.5, -0.5, 0.5, 1.5,
  122812. };
  122813. static long _vq_quantmap__8c1_s_p2_0[] = {
  122814. 3, 1, 0, 2, 4,
  122815. };
  122816. static encode_aux_threshmatch _vq_auxt__8c1_s_p2_0 = {
  122817. _vq_quantthresh__8c1_s_p2_0,
  122818. _vq_quantmap__8c1_s_p2_0,
  122819. 5,
  122820. 5
  122821. };
  122822. static static_codebook _8c1_s_p2_0 = {
  122823. 4, 625,
  122824. _vq_lengthlist__8c1_s_p2_0,
  122825. 1, -533725184, 1611661312, 3, 0,
  122826. _vq_quantlist__8c1_s_p2_0,
  122827. NULL,
  122828. &_vq_auxt__8c1_s_p2_0,
  122829. NULL,
  122830. 0
  122831. };
  122832. static long _vq_quantlist__8c1_s_p3_0[] = {
  122833. 2,
  122834. 1,
  122835. 3,
  122836. 0,
  122837. 4,
  122838. };
  122839. static long _vq_lengthlist__8c1_s_p3_0[] = {
  122840. 2, 4, 4, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  122842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122843. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 7, 7,
  122845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122846. 0, 0, 0, 0, 6, 6, 6, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  122847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122879. 0,
  122880. };
  122881. static float _vq_quantthresh__8c1_s_p3_0[] = {
  122882. -1.5, -0.5, 0.5, 1.5,
  122883. };
  122884. static long _vq_quantmap__8c1_s_p3_0[] = {
  122885. 3, 1, 0, 2, 4,
  122886. };
  122887. static encode_aux_threshmatch _vq_auxt__8c1_s_p3_0 = {
  122888. _vq_quantthresh__8c1_s_p3_0,
  122889. _vq_quantmap__8c1_s_p3_0,
  122890. 5,
  122891. 5
  122892. };
  122893. static static_codebook _8c1_s_p3_0 = {
  122894. 4, 625,
  122895. _vq_lengthlist__8c1_s_p3_0,
  122896. 1, -533725184, 1611661312, 3, 0,
  122897. _vq_quantlist__8c1_s_p3_0,
  122898. NULL,
  122899. &_vq_auxt__8c1_s_p3_0,
  122900. NULL,
  122901. 0
  122902. };
  122903. static long _vq_quantlist__8c1_s_p4_0[] = {
  122904. 4,
  122905. 3,
  122906. 5,
  122907. 2,
  122908. 6,
  122909. 1,
  122910. 7,
  122911. 0,
  122912. 8,
  122913. };
  122914. static long _vq_lengthlist__8c1_s_p4_0[] = {
  122915. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  122916. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  122917. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  122918. 8, 8, 0, 0, 0, 0, 0, 0, 0, 9, 8, 0, 0, 0, 0, 0,
  122919. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122920. 0,
  122921. };
  122922. static float _vq_quantthresh__8c1_s_p4_0[] = {
  122923. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  122924. };
  122925. static long _vq_quantmap__8c1_s_p4_0[] = {
  122926. 7, 5, 3, 1, 0, 2, 4, 6,
  122927. 8,
  122928. };
  122929. static encode_aux_threshmatch _vq_auxt__8c1_s_p4_0 = {
  122930. _vq_quantthresh__8c1_s_p4_0,
  122931. _vq_quantmap__8c1_s_p4_0,
  122932. 9,
  122933. 9
  122934. };
  122935. static static_codebook _8c1_s_p4_0 = {
  122936. 2, 81,
  122937. _vq_lengthlist__8c1_s_p4_0,
  122938. 1, -531628032, 1611661312, 4, 0,
  122939. _vq_quantlist__8c1_s_p4_0,
  122940. NULL,
  122941. &_vq_auxt__8c1_s_p4_0,
  122942. NULL,
  122943. 0
  122944. };
  122945. static long _vq_quantlist__8c1_s_p5_0[] = {
  122946. 4,
  122947. 3,
  122948. 5,
  122949. 2,
  122950. 6,
  122951. 1,
  122952. 7,
  122953. 0,
  122954. 8,
  122955. };
  122956. static long _vq_lengthlist__8c1_s_p5_0[] = {
  122957. 1, 3, 3, 4, 5, 6, 6, 8, 8, 0, 0, 0, 8, 8, 7, 7,
  122958. 9, 9, 0, 0, 0, 8, 8, 7, 7, 9, 9, 0, 0, 0, 9,10,
  122959. 8, 8, 9, 9, 0, 0, 0,10,10, 8, 8, 9, 9, 0, 0, 0,
  122960. 11,10, 8, 8,10,10, 0, 0, 0,11,11, 8, 8,10,10, 0,
  122961. 0, 0,12,12, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  122962. 10,
  122963. };
  122964. static float _vq_quantthresh__8c1_s_p5_0[] = {
  122965. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  122966. };
  122967. static long _vq_quantmap__8c1_s_p5_0[] = {
  122968. 7, 5, 3, 1, 0, 2, 4, 6,
  122969. 8,
  122970. };
  122971. static encode_aux_threshmatch _vq_auxt__8c1_s_p5_0 = {
  122972. _vq_quantthresh__8c1_s_p5_0,
  122973. _vq_quantmap__8c1_s_p5_0,
  122974. 9,
  122975. 9
  122976. };
  122977. static static_codebook _8c1_s_p5_0 = {
  122978. 2, 81,
  122979. _vq_lengthlist__8c1_s_p5_0,
  122980. 1, -531628032, 1611661312, 4, 0,
  122981. _vq_quantlist__8c1_s_p5_0,
  122982. NULL,
  122983. &_vq_auxt__8c1_s_p5_0,
  122984. NULL,
  122985. 0
  122986. };
  122987. static long _vq_quantlist__8c1_s_p6_0[] = {
  122988. 8,
  122989. 7,
  122990. 9,
  122991. 6,
  122992. 10,
  122993. 5,
  122994. 11,
  122995. 4,
  122996. 12,
  122997. 3,
  122998. 13,
  122999. 2,
  123000. 14,
  123001. 1,
  123002. 15,
  123003. 0,
  123004. 16,
  123005. };
  123006. static long _vq_lengthlist__8c1_s_p6_0[] = {
  123007. 1, 3, 3, 5, 5, 8, 8, 8, 8, 9, 9,10,10,11,11,11,
  123008. 11, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,11,
  123009. 12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  123010. 11,12,12, 0, 0, 0, 9, 9, 8, 8,10,10,10,10,11,11,
  123011. 12,12,12,12, 0, 0, 0, 9, 9, 8, 8,10,10,10,10,11,
  123012. 11,12,12,12,12, 0, 0, 0,10,10, 9, 9,10,10,10,10,
  123013. 11,11,12,12,13,13, 0, 0, 0,10,10, 9, 9,10,10,10,
  123014. 10,11,11,12,12,13,13, 0, 0, 0,11,11, 9, 9,10,10,
  123015. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  123016. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  123017. 10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0, 9,
  123018. 9,10,10,11,11,12,11,12,12,13,13, 0, 0, 0, 0, 0,
  123019. 10,10,11,11,11,11,12,12,13,12,13,13, 0, 0, 0, 0,
  123020. 0, 0, 0,11,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  123021. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  123022. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,13, 0,
  123023. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  123024. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  123025. 14,
  123026. };
  123027. static float _vq_quantthresh__8c1_s_p6_0[] = {
  123028. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  123029. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  123030. };
  123031. static long _vq_quantmap__8c1_s_p6_0[] = {
  123032. 15, 13, 11, 9, 7, 5, 3, 1,
  123033. 0, 2, 4, 6, 8, 10, 12, 14,
  123034. 16,
  123035. };
  123036. static encode_aux_threshmatch _vq_auxt__8c1_s_p6_0 = {
  123037. _vq_quantthresh__8c1_s_p6_0,
  123038. _vq_quantmap__8c1_s_p6_0,
  123039. 17,
  123040. 17
  123041. };
  123042. static static_codebook _8c1_s_p6_0 = {
  123043. 2, 289,
  123044. _vq_lengthlist__8c1_s_p6_0,
  123045. 1, -529530880, 1611661312, 5, 0,
  123046. _vq_quantlist__8c1_s_p6_0,
  123047. NULL,
  123048. &_vq_auxt__8c1_s_p6_0,
  123049. NULL,
  123050. 0
  123051. };
  123052. static long _vq_quantlist__8c1_s_p7_0[] = {
  123053. 1,
  123054. 0,
  123055. 2,
  123056. };
  123057. static long _vq_lengthlist__8c1_s_p7_0[] = {
  123058. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,10,
  123059. 9, 9, 5, 7, 7,10, 9, 9,10, 9, 9, 6,10,10,10,10,
  123060. 10,11,10,10, 6, 9, 9,10, 9,10,11,10,10, 6, 9, 9,
  123061. 10, 9, 9,11, 9,10, 7,10,10,11,11,11,11,10,10, 6,
  123062. 9, 9,10,10,10,11, 9, 9, 6, 9, 9,10,10,10,10, 9,
  123063. 9,
  123064. };
  123065. static float _vq_quantthresh__8c1_s_p7_0[] = {
  123066. -5.5, 5.5,
  123067. };
  123068. static long _vq_quantmap__8c1_s_p7_0[] = {
  123069. 1, 0, 2,
  123070. };
  123071. static encode_aux_threshmatch _vq_auxt__8c1_s_p7_0 = {
  123072. _vq_quantthresh__8c1_s_p7_0,
  123073. _vq_quantmap__8c1_s_p7_0,
  123074. 3,
  123075. 3
  123076. };
  123077. static static_codebook _8c1_s_p7_0 = {
  123078. 4, 81,
  123079. _vq_lengthlist__8c1_s_p7_0,
  123080. 1, -529137664, 1618345984, 2, 0,
  123081. _vq_quantlist__8c1_s_p7_0,
  123082. NULL,
  123083. &_vq_auxt__8c1_s_p7_0,
  123084. NULL,
  123085. 0
  123086. };
  123087. static long _vq_quantlist__8c1_s_p7_1[] = {
  123088. 5,
  123089. 4,
  123090. 6,
  123091. 3,
  123092. 7,
  123093. 2,
  123094. 8,
  123095. 1,
  123096. 9,
  123097. 0,
  123098. 10,
  123099. };
  123100. static long _vq_lengthlist__8c1_s_p7_1[] = {
  123101. 2, 3, 3, 5, 5, 7, 7, 7, 7, 7, 7,10,10, 9, 7, 7,
  123102. 7, 7, 8, 8, 8, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8, 8,
  123103. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  123104. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  123105. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  123106. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  123107. 8, 8, 8,10,10,10,10,10, 8, 8, 8, 8, 8, 8,10,10,
  123108. 10,10,10, 8, 8, 8, 8, 8, 8,
  123109. };
  123110. static float _vq_quantthresh__8c1_s_p7_1[] = {
  123111. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  123112. 3.5, 4.5,
  123113. };
  123114. static long _vq_quantmap__8c1_s_p7_1[] = {
  123115. 9, 7, 5, 3, 1, 0, 2, 4,
  123116. 6, 8, 10,
  123117. };
  123118. static encode_aux_threshmatch _vq_auxt__8c1_s_p7_1 = {
  123119. _vq_quantthresh__8c1_s_p7_1,
  123120. _vq_quantmap__8c1_s_p7_1,
  123121. 11,
  123122. 11
  123123. };
  123124. static static_codebook _8c1_s_p7_1 = {
  123125. 2, 121,
  123126. _vq_lengthlist__8c1_s_p7_1,
  123127. 1, -531365888, 1611661312, 4, 0,
  123128. _vq_quantlist__8c1_s_p7_1,
  123129. NULL,
  123130. &_vq_auxt__8c1_s_p7_1,
  123131. NULL,
  123132. 0
  123133. };
  123134. static long _vq_quantlist__8c1_s_p8_0[] = {
  123135. 6,
  123136. 5,
  123137. 7,
  123138. 4,
  123139. 8,
  123140. 3,
  123141. 9,
  123142. 2,
  123143. 10,
  123144. 1,
  123145. 11,
  123146. 0,
  123147. 12,
  123148. };
  123149. static long _vq_lengthlist__8c1_s_p8_0[] = {
  123150. 1, 4, 4, 6, 6, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5,
  123151. 7, 7, 8, 8, 8, 8, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  123152. 8, 9, 9,10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  123153. 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  123154. 11, 0,12,12, 9, 9, 9, 9,10, 9,10,11,11,11, 0,13,
  123155. 12, 9, 8, 9, 9,10,10,11,11,12,11, 0, 0, 0, 9, 9,
  123156. 9, 9,10,10,11,11,12,12, 0, 0, 0,10,10, 9, 9,10,
  123157. 10,11,11,12,12, 0, 0, 0,13,13,10,10,11,11,12,11,
  123158. 13,12, 0, 0, 0,14,14,10,10,11,10,11,11,12,12, 0,
  123159. 0, 0, 0, 0,12,12,11,11,12,12,13,13, 0, 0, 0, 0,
  123160. 0,12,12,11,10,12,11,13,12,
  123161. };
  123162. static float _vq_quantthresh__8c1_s_p8_0[] = {
  123163. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  123164. 12.5, 17.5, 22.5, 27.5,
  123165. };
  123166. static long _vq_quantmap__8c1_s_p8_0[] = {
  123167. 11, 9, 7, 5, 3, 1, 0, 2,
  123168. 4, 6, 8, 10, 12,
  123169. };
  123170. static encode_aux_threshmatch _vq_auxt__8c1_s_p8_0 = {
  123171. _vq_quantthresh__8c1_s_p8_0,
  123172. _vq_quantmap__8c1_s_p8_0,
  123173. 13,
  123174. 13
  123175. };
  123176. static static_codebook _8c1_s_p8_0 = {
  123177. 2, 169,
  123178. _vq_lengthlist__8c1_s_p8_0,
  123179. 1, -526516224, 1616117760, 4, 0,
  123180. _vq_quantlist__8c1_s_p8_0,
  123181. NULL,
  123182. &_vq_auxt__8c1_s_p8_0,
  123183. NULL,
  123184. 0
  123185. };
  123186. static long _vq_quantlist__8c1_s_p8_1[] = {
  123187. 2,
  123188. 1,
  123189. 3,
  123190. 0,
  123191. 4,
  123192. };
  123193. static long _vq_lengthlist__8c1_s_p8_1[] = {
  123194. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  123195. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  123196. };
  123197. static float _vq_quantthresh__8c1_s_p8_1[] = {
  123198. -1.5, -0.5, 0.5, 1.5,
  123199. };
  123200. static long _vq_quantmap__8c1_s_p8_1[] = {
  123201. 3, 1, 0, 2, 4,
  123202. };
  123203. static encode_aux_threshmatch _vq_auxt__8c1_s_p8_1 = {
  123204. _vq_quantthresh__8c1_s_p8_1,
  123205. _vq_quantmap__8c1_s_p8_1,
  123206. 5,
  123207. 5
  123208. };
  123209. static static_codebook _8c1_s_p8_1 = {
  123210. 2, 25,
  123211. _vq_lengthlist__8c1_s_p8_1,
  123212. 1, -533725184, 1611661312, 3, 0,
  123213. _vq_quantlist__8c1_s_p8_1,
  123214. NULL,
  123215. &_vq_auxt__8c1_s_p8_1,
  123216. NULL,
  123217. 0
  123218. };
  123219. static long _vq_quantlist__8c1_s_p9_0[] = {
  123220. 6,
  123221. 5,
  123222. 7,
  123223. 4,
  123224. 8,
  123225. 3,
  123226. 9,
  123227. 2,
  123228. 10,
  123229. 1,
  123230. 11,
  123231. 0,
  123232. 12,
  123233. };
  123234. static long _vq_lengthlist__8c1_s_p9_0[] = {
  123235. 1, 3, 3,10,10,10,10,10,10,10,10,10,10, 5, 6, 6,
  123236. 10,10,10,10,10,10,10,10,10,10, 6, 7, 8,10,10,10,
  123237. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123238. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123239. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123240. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123241. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123242. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123243. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123244. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123245. 10,10,10,10,10, 9, 9, 9, 9,
  123246. };
  123247. static float _vq_quantthresh__8c1_s_p9_0[] = {
  123248. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  123249. 787.5, 1102.5, 1417.5, 1732.5,
  123250. };
  123251. static long _vq_quantmap__8c1_s_p9_0[] = {
  123252. 11, 9, 7, 5, 3, 1, 0, 2,
  123253. 4, 6, 8, 10, 12,
  123254. };
  123255. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_0 = {
  123256. _vq_quantthresh__8c1_s_p9_0,
  123257. _vq_quantmap__8c1_s_p9_0,
  123258. 13,
  123259. 13
  123260. };
  123261. static static_codebook _8c1_s_p9_0 = {
  123262. 2, 169,
  123263. _vq_lengthlist__8c1_s_p9_0,
  123264. 1, -513964032, 1628680192, 4, 0,
  123265. _vq_quantlist__8c1_s_p9_0,
  123266. NULL,
  123267. &_vq_auxt__8c1_s_p9_0,
  123268. NULL,
  123269. 0
  123270. };
  123271. static long _vq_quantlist__8c1_s_p9_1[] = {
  123272. 7,
  123273. 6,
  123274. 8,
  123275. 5,
  123276. 9,
  123277. 4,
  123278. 10,
  123279. 3,
  123280. 11,
  123281. 2,
  123282. 12,
  123283. 1,
  123284. 13,
  123285. 0,
  123286. 14,
  123287. };
  123288. static long _vq_lengthlist__8c1_s_p9_1[] = {
  123289. 1, 4, 4, 5, 5, 7, 7, 9, 9,11,11,12,12,13,13, 6,
  123290. 5, 5, 6, 6, 9, 9,10,10,12,12,12,13,15,14, 6, 5,
  123291. 5, 7, 7, 9, 9,10,10,12,12,12,13,14,13,17, 7, 7,
  123292. 8, 8,10,10,11,11,12,13,13,13,13,13,17, 7, 7, 8,
  123293. 8,10,10,11,11,13,13,13,13,14,14,17,11,11, 9, 9,
  123294. 11,11,12,12,12,13,13,14,15,13,17,12,12, 9, 9,11,
  123295. 11,12,12,13,13,13,13,14,16,17,17,17,11,12,12,12,
  123296. 13,13,13,14,15,14,15,15,17,17,17,12,12,11,11,13,
  123297. 13,14,14,15,14,15,15,17,17,17,15,15,13,13,14,14,
  123298. 15,14,15,15,16,15,17,17,17,15,15,13,13,13,14,14,
  123299. 15,15,15,15,16,17,17,17,17,16,14,15,14,14,15,14,
  123300. 14,15,15,15,17,17,17,17,17,14,14,16,14,15,15,15,
  123301. 15,15,15,17,17,17,17,17,17,16,16,15,17,15,15,14,
  123302. 17,15,17,16,17,17,17,17,16,15,14,15,15,15,15,15,
  123303. 15,
  123304. };
  123305. static float _vq_quantthresh__8c1_s_p9_1[] = {
  123306. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  123307. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  123308. };
  123309. static long _vq_quantmap__8c1_s_p9_1[] = {
  123310. 13, 11, 9, 7, 5, 3, 1, 0,
  123311. 2, 4, 6, 8, 10, 12, 14,
  123312. };
  123313. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_1 = {
  123314. _vq_quantthresh__8c1_s_p9_1,
  123315. _vq_quantmap__8c1_s_p9_1,
  123316. 15,
  123317. 15
  123318. };
  123319. static static_codebook _8c1_s_p9_1 = {
  123320. 2, 225,
  123321. _vq_lengthlist__8c1_s_p9_1,
  123322. 1, -520986624, 1620377600, 4, 0,
  123323. _vq_quantlist__8c1_s_p9_1,
  123324. NULL,
  123325. &_vq_auxt__8c1_s_p9_1,
  123326. NULL,
  123327. 0
  123328. };
  123329. static long _vq_quantlist__8c1_s_p9_2[] = {
  123330. 10,
  123331. 9,
  123332. 11,
  123333. 8,
  123334. 12,
  123335. 7,
  123336. 13,
  123337. 6,
  123338. 14,
  123339. 5,
  123340. 15,
  123341. 4,
  123342. 16,
  123343. 3,
  123344. 17,
  123345. 2,
  123346. 18,
  123347. 1,
  123348. 19,
  123349. 0,
  123350. 20,
  123351. };
  123352. static long _vq_lengthlist__8c1_s_p9_2[] = {
  123353. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9,
  123354. 9, 9, 9, 9, 9,11,11,12, 7, 7, 7, 7, 8, 8, 9, 9,
  123355. 9, 9,10,10,10,10,10,10,10,10,11,11,11, 7, 7, 7,
  123356. 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,11,
  123357. 11,12, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,10,
  123358. 10,10,10,10,11,11,11, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  123359. 9,10,10,10,10,10,10,10,10,11,11,11, 8, 8, 8, 8,
  123360. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,11,11,
  123361. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,
  123362. 10,10,10,11,12,11, 9, 9, 8, 9, 9, 9, 9, 9,10,10,
  123363. 10,10,10,10,10,10,10,10,11,11,11,11,11, 8, 8, 9,
  123364. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,11,12,11,
  123365. 12,11, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  123366. 10,10,11,11,11,11,11, 9, 9, 9, 9,10,10,10,10,10,
  123367. 10,10,10,10,10,10,10,12,11,12,11,11, 9, 9, 9,10,
  123368. 10,10,10,10,10,10,10,10,10,10,10,10,12,11,11,11,
  123369. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123370. 11,11,11,12,11,11,12,11,10,10,10,10,10,10,10,10,
  123371. 10,10,10,10,11,10,11,11,11,11,11,11,11,10,10,10,
  123372. 10,10,10,10,10,10,10,10,10,10,10,11,11,12,11,12,
  123373. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123374. 11,11,12,11,12,11,11,11,11,10,10,10,10,10,10,10,
  123375. 10,10,10,10,10,11,11,12,11,11,12,11,11,12,10,10,
  123376. 11,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  123377. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,12,
  123378. 12,11,12,11,11,12,12,12,11,11,10,10,10,10,10,10,
  123379. 10,10,10,11,12,12,11,12,12,11,12,11,11,11,11,10,
  123380. 10,10,10,10,10,10,10,10,10,
  123381. };
  123382. static float _vq_quantthresh__8c1_s_p9_2[] = {
  123383. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  123384. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  123385. 6.5, 7.5, 8.5, 9.5,
  123386. };
  123387. static long _vq_quantmap__8c1_s_p9_2[] = {
  123388. 19, 17, 15, 13, 11, 9, 7, 5,
  123389. 3, 1, 0, 2, 4, 6, 8, 10,
  123390. 12, 14, 16, 18, 20,
  123391. };
  123392. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_2 = {
  123393. _vq_quantthresh__8c1_s_p9_2,
  123394. _vq_quantmap__8c1_s_p9_2,
  123395. 21,
  123396. 21
  123397. };
  123398. static static_codebook _8c1_s_p9_2 = {
  123399. 2, 441,
  123400. _vq_lengthlist__8c1_s_p9_2,
  123401. 1, -529268736, 1611661312, 5, 0,
  123402. _vq_quantlist__8c1_s_p9_2,
  123403. NULL,
  123404. &_vq_auxt__8c1_s_p9_2,
  123405. NULL,
  123406. 0
  123407. };
  123408. static long _huff_lengthlist__8c1_s_single[] = {
  123409. 4, 6,18, 8,11, 8, 8, 9, 9,10, 4, 4,18, 5, 9, 5,
  123410. 6, 7, 8,10,18,18,18,18,17,17,17,17,17,17, 7, 5,
  123411. 17, 6,11, 6, 7, 8, 9,12,12, 9,17,12, 8, 8, 9,10,
  123412. 10,13, 7, 5,17, 6, 8, 4, 5, 6, 8,10, 6, 5,17, 6,
  123413. 8, 5, 4, 5, 7, 9, 7, 7,17, 8, 9, 6, 5, 5, 6, 8,
  123414. 8, 8,17, 9,11, 8, 6, 6, 6, 7, 9,10,17,12,12,10,
  123415. 9, 7, 7, 8,
  123416. };
  123417. static static_codebook _huff_book__8c1_s_single = {
  123418. 2, 100,
  123419. _huff_lengthlist__8c1_s_single,
  123420. 0, 0, 0, 0, 0,
  123421. NULL,
  123422. NULL,
  123423. NULL,
  123424. NULL,
  123425. 0
  123426. };
  123427. static long _huff_lengthlist__44c2_s_long[] = {
  123428. 6, 6,12,10,10,10, 9,10,12,12, 6, 1,10, 5, 6, 6,
  123429. 7, 9,11,14,12, 9, 8,11, 7, 8, 9,11,13,15,10, 5,
  123430. 12, 7, 8, 7, 9,12,14,15,10, 6, 7, 8, 5, 6, 7, 9,
  123431. 12,14, 9, 6, 8, 7, 6, 6, 7, 9,12,12, 9, 7, 9, 9,
  123432. 7, 6, 6, 7,10,10,10, 9,10,11, 8, 7, 6, 6, 8,10,
  123433. 12,11,13,13,11,10, 8, 8, 8,10,11,13,15,15,14,13,
  123434. 10, 8, 8, 9,
  123435. };
  123436. static static_codebook _huff_book__44c2_s_long = {
  123437. 2, 100,
  123438. _huff_lengthlist__44c2_s_long,
  123439. 0, 0, 0, 0, 0,
  123440. NULL,
  123441. NULL,
  123442. NULL,
  123443. NULL,
  123444. 0
  123445. };
  123446. static long _vq_quantlist__44c2_s_p1_0[] = {
  123447. 1,
  123448. 0,
  123449. 2,
  123450. };
  123451. static long _vq_lengthlist__44c2_s_p1_0[] = {
  123452. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  123453. 0, 0, 5, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123457. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  123458. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123462. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  123463. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  123498. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  123499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  123503. 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  123504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0, 0,
  123508. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  123509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123543. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  123544. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123548. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  123549. 0, 0, 0, 0, 0, 8, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0,
  123550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123553. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  123554. 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  123555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123862. 0,
  123863. };
  123864. static float _vq_quantthresh__44c2_s_p1_0[] = {
  123865. -0.5, 0.5,
  123866. };
  123867. static long _vq_quantmap__44c2_s_p1_0[] = {
  123868. 1, 0, 2,
  123869. };
  123870. static encode_aux_threshmatch _vq_auxt__44c2_s_p1_0 = {
  123871. _vq_quantthresh__44c2_s_p1_0,
  123872. _vq_quantmap__44c2_s_p1_0,
  123873. 3,
  123874. 3
  123875. };
  123876. static static_codebook _44c2_s_p1_0 = {
  123877. 8, 6561,
  123878. _vq_lengthlist__44c2_s_p1_0,
  123879. 1, -535822336, 1611661312, 2, 0,
  123880. _vq_quantlist__44c2_s_p1_0,
  123881. NULL,
  123882. &_vq_auxt__44c2_s_p1_0,
  123883. NULL,
  123884. 0
  123885. };
  123886. static long _vq_quantlist__44c2_s_p2_0[] = {
  123887. 2,
  123888. 1,
  123889. 3,
  123890. 0,
  123891. 4,
  123892. };
  123893. static long _vq_lengthlist__44c2_s_p2_0[] = {
  123894. 1, 4, 4, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0,
  123895. 8, 8, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 0, 0, 0, 8,
  123896. 8, 0, 0, 0, 8, 8, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0,
  123897. 0, 0, 4, 6, 6, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8, 0,
  123898. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123903. 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,11,11, 0, 0,
  123904. 0,11,11, 0, 0, 0,12,11, 0, 0, 0, 0, 0, 0, 0, 7,
  123905. 8, 8, 0, 0, 0,10,11, 0, 0, 0,11,11, 0, 0, 0,11,
  123906. 12, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123911. 0, 0, 0, 6, 8, 8, 0, 0, 0,11,11, 0, 0, 0,11,11,
  123912. 0, 0, 0,12,12, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0,
  123913. 0, 0,10,11, 0, 0, 0,10,11, 0, 0, 0,11,11, 0, 0,
  123914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123919. 8, 9, 9, 0, 0, 0,11,12, 0, 0, 0,11,12, 0, 0, 0,
  123920. 12,11, 0, 0, 0, 0, 0, 0, 0, 8,10, 9, 0, 0, 0,12,
  123921. 11, 0, 0, 0,12,11, 0, 0, 0,11,12, 0, 0, 0, 0, 0,
  123922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123933. 0,
  123934. };
  123935. static float _vq_quantthresh__44c2_s_p2_0[] = {
  123936. -1.5, -0.5, 0.5, 1.5,
  123937. };
  123938. static long _vq_quantmap__44c2_s_p2_0[] = {
  123939. 3, 1, 0, 2, 4,
  123940. };
  123941. static encode_aux_threshmatch _vq_auxt__44c2_s_p2_0 = {
  123942. _vq_quantthresh__44c2_s_p2_0,
  123943. _vq_quantmap__44c2_s_p2_0,
  123944. 5,
  123945. 5
  123946. };
  123947. static static_codebook _44c2_s_p2_0 = {
  123948. 4, 625,
  123949. _vq_lengthlist__44c2_s_p2_0,
  123950. 1, -533725184, 1611661312, 3, 0,
  123951. _vq_quantlist__44c2_s_p2_0,
  123952. NULL,
  123953. &_vq_auxt__44c2_s_p2_0,
  123954. NULL,
  123955. 0
  123956. };
  123957. static long _vq_quantlist__44c2_s_p3_0[] = {
  123958. 2,
  123959. 1,
  123960. 3,
  123961. 0,
  123962. 4,
  123963. };
  123964. static long _vq_lengthlist__44c2_s_p3_0[] = {
  123965. 2, 4, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  123967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123968. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  123970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123971. 0, 0, 0, 0, 6, 6, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  123972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124004. 0,
  124005. };
  124006. static float _vq_quantthresh__44c2_s_p3_0[] = {
  124007. -1.5, -0.5, 0.5, 1.5,
  124008. };
  124009. static long _vq_quantmap__44c2_s_p3_0[] = {
  124010. 3, 1, 0, 2, 4,
  124011. };
  124012. static encode_aux_threshmatch _vq_auxt__44c2_s_p3_0 = {
  124013. _vq_quantthresh__44c2_s_p3_0,
  124014. _vq_quantmap__44c2_s_p3_0,
  124015. 5,
  124016. 5
  124017. };
  124018. static static_codebook _44c2_s_p3_0 = {
  124019. 4, 625,
  124020. _vq_lengthlist__44c2_s_p3_0,
  124021. 1, -533725184, 1611661312, 3, 0,
  124022. _vq_quantlist__44c2_s_p3_0,
  124023. NULL,
  124024. &_vq_auxt__44c2_s_p3_0,
  124025. NULL,
  124026. 0
  124027. };
  124028. static long _vq_quantlist__44c2_s_p4_0[] = {
  124029. 4,
  124030. 3,
  124031. 5,
  124032. 2,
  124033. 6,
  124034. 1,
  124035. 7,
  124036. 0,
  124037. 8,
  124038. };
  124039. static long _vq_lengthlist__44c2_s_p4_0[] = {
  124040. 1, 3, 3, 6, 6, 0, 0, 0, 0, 0, 6, 6, 6, 6, 0, 0,
  124041. 0, 0, 0, 6, 6, 6, 6, 0, 0, 0, 0, 0, 7, 7, 6, 6,
  124042. 0, 0, 0, 0, 0, 0, 0, 6, 7, 0, 0, 0, 0, 0, 0, 0,
  124043. 7, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  124044. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124045. 0,
  124046. };
  124047. static float _vq_quantthresh__44c2_s_p4_0[] = {
  124048. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  124049. };
  124050. static long _vq_quantmap__44c2_s_p4_0[] = {
  124051. 7, 5, 3, 1, 0, 2, 4, 6,
  124052. 8,
  124053. };
  124054. static encode_aux_threshmatch _vq_auxt__44c2_s_p4_0 = {
  124055. _vq_quantthresh__44c2_s_p4_0,
  124056. _vq_quantmap__44c2_s_p4_0,
  124057. 9,
  124058. 9
  124059. };
  124060. static static_codebook _44c2_s_p4_0 = {
  124061. 2, 81,
  124062. _vq_lengthlist__44c2_s_p4_0,
  124063. 1, -531628032, 1611661312, 4, 0,
  124064. _vq_quantlist__44c2_s_p4_0,
  124065. NULL,
  124066. &_vq_auxt__44c2_s_p4_0,
  124067. NULL,
  124068. 0
  124069. };
  124070. static long _vq_quantlist__44c2_s_p5_0[] = {
  124071. 4,
  124072. 3,
  124073. 5,
  124074. 2,
  124075. 6,
  124076. 1,
  124077. 7,
  124078. 0,
  124079. 8,
  124080. };
  124081. static long _vq_lengthlist__44c2_s_p5_0[] = {
  124082. 1, 3, 3, 6, 6, 7, 7, 9, 9, 0, 7, 7, 7, 7, 7, 7,
  124083. 9, 9, 0, 7, 7, 7, 7, 7, 7, 9, 9, 0, 8, 8, 7, 7,
  124084. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  124085. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  124086. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  124087. 11,
  124088. };
  124089. static float _vq_quantthresh__44c2_s_p5_0[] = {
  124090. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  124091. };
  124092. static long _vq_quantmap__44c2_s_p5_0[] = {
  124093. 7, 5, 3, 1, 0, 2, 4, 6,
  124094. 8,
  124095. };
  124096. static encode_aux_threshmatch _vq_auxt__44c2_s_p5_0 = {
  124097. _vq_quantthresh__44c2_s_p5_0,
  124098. _vq_quantmap__44c2_s_p5_0,
  124099. 9,
  124100. 9
  124101. };
  124102. static static_codebook _44c2_s_p5_0 = {
  124103. 2, 81,
  124104. _vq_lengthlist__44c2_s_p5_0,
  124105. 1, -531628032, 1611661312, 4, 0,
  124106. _vq_quantlist__44c2_s_p5_0,
  124107. NULL,
  124108. &_vq_auxt__44c2_s_p5_0,
  124109. NULL,
  124110. 0
  124111. };
  124112. static long _vq_quantlist__44c2_s_p6_0[] = {
  124113. 8,
  124114. 7,
  124115. 9,
  124116. 6,
  124117. 10,
  124118. 5,
  124119. 11,
  124120. 4,
  124121. 12,
  124122. 3,
  124123. 13,
  124124. 2,
  124125. 14,
  124126. 1,
  124127. 15,
  124128. 0,
  124129. 16,
  124130. };
  124131. static long _vq_lengthlist__44c2_s_p6_0[] = {
  124132. 1, 4, 3, 6, 6, 8, 8, 9, 9, 9, 9, 9, 9,10,10,11,
  124133. 11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  124134. 12,11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  124135. 11,11,12, 0, 8, 8, 7, 7, 9, 9,10,10, 9, 9,10,10,
  124136. 11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10, 9,10,
  124137. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  124138. 11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  124139. 10,11,11,12,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  124140. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  124141. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  124142. 10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  124143. 9,10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  124144. 10,10,10,10,11,11,12,12,13,12,13,13, 0, 0, 0, 0,
  124145. 0, 0, 0,10,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  124146. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  124147. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0,
  124148. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  124149. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  124150. 14,
  124151. };
  124152. static float _vq_quantthresh__44c2_s_p6_0[] = {
  124153. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  124154. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  124155. };
  124156. static long _vq_quantmap__44c2_s_p6_0[] = {
  124157. 15, 13, 11, 9, 7, 5, 3, 1,
  124158. 0, 2, 4, 6, 8, 10, 12, 14,
  124159. 16,
  124160. };
  124161. static encode_aux_threshmatch _vq_auxt__44c2_s_p6_0 = {
  124162. _vq_quantthresh__44c2_s_p6_0,
  124163. _vq_quantmap__44c2_s_p6_0,
  124164. 17,
  124165. 17
  124166. };
  124167. static static_codebook _44c2_s_p6_0 = {
  124168. 2, 289,
  124169. _vq_lengthlist__44c2_s_p6_0,
  124170. 1, -529530880, 1611661312, 5, 0,
  124171. _vq_quantlist__44c2_s_p6_0,
  124172. NULL,
  124173. &_vq_auxt__44c2_s_p6_0,
  124174. NULL,
  124175. 0
  124176. };
  124177. static long _vq_quantlist__44c2_s_p7_0[] = {
  124178. 1,
  124179. 0,
  124180. 2,
  124181. };
  124182. static long _vq_lengthlist__44c2_s_p7_0[] = {
  124183. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  124184. 9, 9, 4, 7, 7,10, 9, 9,10, 9, 9, 7,10,10,11,10,
  124185. 11,11,10,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  124186. 11,10,11,11,10,10, 7,11,10,11,11,11,12,11,11, 6,
  124187. 9, 9,11,10,10,11,11,10, 6, 9, 9,11,10,10,12,10,
  124188. 11,
  124189. };
  124190. static float _vq_quantthresh__44c2_s_p7_0[] = {
  124191. -5.5, 5.5,
  124192. };
  124193. static long _vq_quantmap__44c2_s_p7_0[] = {
  124194. 1, 0, 2,
  124195. };
  124196. static encode_aux_threshmatch _vq_auxt__44c2_s_p7_0 = {
  124197. _vq_quantthresh__44c2_s_p7_0,
  124198. _vq_quantmap__44c2_s_p7_0,
  124199. 3,
  124200. 3
  124201. };
  124202. static static_codebook _44c2_s_p7_0 = {
  124203. 4, 81,
  124204. _vq_lengthlist__44c2_s_p7_0,
  124205. 1, -529137664, 1618345984, 2, 0,
  124206. _vq_quantlist__44c2_s_p7_0,
  124207. NULL,
  124208. &_vq_auxt__44c2_s_p7_0,
  124209. NULL,
  124210. 0
  124211. };
  124212. static long _vq_quantlist__44c2_s_p7_1[] = {
  124213. 5,
  124214. 4,
  124215. 6,
  124216. 3,
  124217. 7,
  124218. 2,
  124219. 8,
  124220. 1,
  124221. 9,
  124222. 0,
  124223. 10,
  124224. };
  124225. static long _vq_lengthlist__44c2_s_p7_1[] = {
  124226. 2, 3, 4, 6, 6, 7, 7, 7, 7, 7, 7, 9, 7, 7, 6, 6,
  124227. 7, 7, 8, 8, 8, 8, 9, 6, 6, 6, 6, 7, 7, 8, 8, 8,
  124228. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  124229. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  124230. 8, 8,10,10,10, 7, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  124231. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  124232. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  124233. 10,10,10, 8, 8, 8, 8, 8, 8,
  124234. };
  124235. static float _vq_quantthresh__44c2_s_p7_1[] = {
  124236. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  124237. 3.5, 4.5,
  124238. };
  124239. static long _vq_quantmap__44c2_s_p7_1[] = {
  124240. 9, 7, 5, 3, 1, 0, 2, 4,
  124241. 6, 8, 10,
  124242. };
  124243. static encode_aux_threshmatch _vq_auxt__44c2_s_p7_1 = {
  124244. _vq_quantthresh__44c2_s_p7_1,
  124245. _vq_quantmap__44c2_s_p7_1,
  124246. 11,
  124247. 11
  124248. };
  124249. static static_codebook _44c2_s_p7_1 = {
  124250. 2, 121,
  124251. _vq_lengthlist__44c2_s_p7_1,
  124252. 1, -531365888, 1611661312, 4, 0,
  124253. _vq_quantlist__44c2_s_p7_1,
  124254. NULL,
  124255. &_vq_auxt__44c2_s_p7_1,
  124256. NULL,
  124257. 0
  124258. };
  124259. static long _vq_quantlist__44c2_s_p8_0[] = {
  124260. 6,
  124261. 5,
  124262. 7,
  124263. 4,
  124264. 8,
  124265. 3,
  124266. 9,
  124267. 2,
  124268. 10,
  124269. 1,
  124270. 11,
  124271. 0,
  124272. 12,
  124273. };
  124274. static long _vq_lengthlist__44c2_s_p8_0[] = {
  124275. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 6, 5, 5,
  124276. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 6, 5, 7, 7, 8,
  124277. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  124278. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  124279. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  124280. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  124281. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  124282. 11,12,12,12,12, 0, 0, 0,14,14,10,11,11,11,12,12,
  124283. 13,13, 0, 0, 0,14,14,11,10,11,11,13,12,13,13, 0,
  124284. 0, 0, 0, 0,12,12,11,12,13,12,14,14, 0, 0, 0, 0,
  124285. 0,12,12,12,12,13,12,14,14,
  124286. };
  124287. static float _vq_quantthresh__44c2_s_p8_0[] = {
  124288. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  124289. 12.5, 17.5, 22.5, 27.5,
  124290. };
  124291. static long _vq_quantmap__44c2_s_p8_0[] = {
  124292. 11, 9, 7, 5, 3, 1, 0, 2,
  124293. 4, 6, 8, 10, 12,
  124294. };
  124295. static encode_aux_threshmatch _vq_auxt__44c2_s_p8_0 = {
  124296. _vq_quantthresh__44c2_s_p8_0,
  124297. _vq_quantmap__44c2_s_p8_0,
  124298. 13,
  124299. 13
  124300. };
  124301. static static_codebook _44c2_s_p8_0 = {
  124302. 2, 169,
  124303. _vq_lengthlist__44c2_s_p8_0,
  124304. 1, -526516224, 1616117760, 4, 0,
  124305. _vq_quantlist__44c2_s_p8_0,
  124306. NULL,
  124307. &_vq_auxt__44c2_s_p8_0,
  124308. NULL,
  124309. 0
  124310. };
  124311. static long _vq_quantlist__44c2_s_p8_1[] = {
  124312. 2,
  124313. 1,
  124314. 3,
  124315. 0,
  124316. 4,
  124317. };
  124318. static long _vq_lengthlist__44c2_s_p8_1[] = {
  124319. 2, 4, 4, 5, 4, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  124320. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  124321. };
  124322. static float _vq_quantthresh__44c2_s_p8_1[] = {
  124323. -1.5, -0.5, 0.5, 1.5,
  124324. };
  124325. static long _vq_quantmap__44c2_s_p8_1[] = {
  124326. 3, 1, 0, 2, 4,
  124327. };
  124328. static encode_aux_threshmatch _vq_auxt__44c2_s_p8_1 = {
  124329. _vq_quantthresh__44c2_s_p8_1,
  124330. _vq_quantmap__44c2_s_p8_1,
  124331. 5,
  124332. 5
  124333. };
  124334. static static_codebook _44c2_s_p8_1 = {
  124335. 2, 25,
  124336. _vq_lengthlist__44c2_s_p8_1,
  124337. 1, -533725184, 1611661312, 3, 0,
  124338. _vq_quantlist__44c2_s_p8_1,
  124339. NULL,
  124340. &_vq_auxt__44c2_s_p8_1,
  124341. NULL,
  124342. 0
  124343. };
  124344. static long _vq_quantlist__44c2_s_p9_0[] = {
  124345. 6,
  124346. 5,
  124347. 7,
  124348. 4,
  124349. 8,
  124350. 3,
  124351. 9,
  124352. 2,
  124353. 10,
  124354. 1,
  124355. 11,
  124356. 0,
  124357. 12,
  124358. };
  124359. static long _vq_lengthlist__44c2_s_p9_0[] = {
  124360. 1, 5, 4,12,12,12,12,12,12,12,12,12,12, 4, 9, 8,
  124361. 11,11,11,11,11,11,11,11,11,11, 2, 8, 7,11,11,11,
  124362. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  124363. 11,11,11,11,11,11,10,11,11,11,11,11,11,11,11,11,
  124364. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  124365. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  124366. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  124367. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  124368. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  124369. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  124370. 11,11,11,11,11,11,11,11,11,
  124371. };
  124372. static float _vq_quantthresh__44c2_s_p9_0[] = {
  124373. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  124374. 552.5, 773.5, 994.5, 1215.5,
  124375. };
  124376. static long _vq_quantmap__44c2_s_p9_0[] = {
  124377. 11, 9, 7, 5, 3, 1, 0, 2,
  124378. 4, 6, 8, 10, 12,
  124379. };
  124380. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_0 = {
  124381. _vq_quantthresh__44c2_s_p9_0,
  124382. _vq_quantmap__44c2_s_p9_0,
  124383. 13,
  124384. 13
  124385. };
  124386. static static_codebook _44c2_s_p9_0 = {
  124387. 2, 169,
  124388. _vq_lengthlist__44c2_s_p9_0,
  124389. 1, -514541568, 1627103232, 4, 0,
  124390. _vq_quantlist__44c2_s_p9_0,
  124391. NULL,
  124392. &_vq_auxt__44c2_s_p9_0,
  124393. NULL,
  124394. 0
  124395. };
  124396. static long _vq_quantlist__44c2_s_p9_1[] = {
  124397. 6,
  124398. 5,
  124399. 7,
  124400. 4,
  124401. 8,
  124402. 3,
  124403. 9,
  124404. 2,
  124405. 10,
  124406. 1,
  124407. 11,
  124408. 0,
  124409. 12,
  124410. };
  124411. static long _vq_lengthlist__44c2_s_p9_1[] = {
  124412. 1, 4, 4, 6, 6, 7, 6, 8, 8,10, 9,10,10, 6, 5, 5,
  124413. 7, 7, 8, 7,10, 9,11,11,12,13, 6, 5, 5, 7, 7, 8,
  124414. 8,10,10,11,11,13,13,18, 8, 8, 8, 8, 9, 9,10,10,
  124415. 12,12,12,13,18, 8, 8, 8, 8, 9, 9,10,10,12,12,13,
  124416. 13,18,11,11, 8, 8,10,10,11,11,12,11,13,12,18,11,
  124417. 11, 9, 7,10,10,11,11,11,12,12,13,17,17,17,10,10,
  124418. 11,11,12,12,12,10,12,12,17,17,17,11,10,11,10,13,
  124419. 12,11,12,12,12,17,17,17,15,14,11,11,12,11,13,10,
  124420. 13,12,17,17,17,14,14,12,10,11,11,13,13,13,13,17,
  124421. 17,16,17,16,13,13,12,10,13,10,14,13,17,16,17,16,
  124422. 17,13,12,12,10,13,11,14,14,
  124423. };
  124424. static float _vq_quantthresh__44c2_s_p9_1[] = {
  124425. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  124426. 42.5, 59.5, 76.5, 93.5,
  124427. };
  124428. static long _vq_quantmap__44c2_s_p9_1[] = {
  124429. 11, 9, 7, 5, 3, 1, 0, 2,
  124430. 4, 6, 8, 10, 12,
  124431. };
  124432. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_1 = {
  124433. _vq_quantthresh__44c2_s_p9_1,
  124434. _vq_quantmap__44c2_s_p9_1,
  124435. 13,
  124436. 13
  124437. };
  124438. static static_codebook _44c2_s_p9_1 = {
  124439. 2, 169,
  124440. _vq_lengthlist__44c2_s_p9_1,
  124441. 1, -522616832, 1620115456, 4, 0,
  124442. _vq_quantlist__44c2_s_p9_1,
  124443. NULL,
  124444. &_vq_auxt__44c2_s_p9_1,
  124445. NULL,
  124446. 0
  124447. };
  124448. static long _vq_quantlist__44c2_s_p9_2[] = {
  124449. 8,
  124450. 7,
  124451. 9,
  124452. 6,
  124453. 10,
  124454. 5,
  124455. 11,
  124456. 4,
  124457. 12,
  124458. 3,
  124459. 13,
  124460. 2,
  124461. 14,
  124462. 1,
  124463. 15,
  124464. 0,
  124465. 16,
  124466. };
  124467. static long _vq_lengthlist__44c2_s_p9_2[] = {
  124468. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8,
  124469. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  124470. 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9,
  124471. 9, 9, 9,10, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  124472. 9, 9, 9, 9,10,10,10, 8, 7, 8, 8, 8, 8, 9, 9, 9,
  124473. 9, 9, 9, 9, 9,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  124474. 9, 9,10, 9, 9, 9,10,11,10, 8, 8, 8, 8, 9, 9, 9,
  124475. 9, 9, 9, 9,10,10,10,10,11,10, 8, 8, 9, 9, 9, 9,
  124476. 9, 9,10, 9, 9,10, 9,10,11,10,11,11,11, 8, 8, 9,
  124477. 9, 9, 9, 9, 9, 9, 9,10,10,11,11,11,11,11, 9, 9,
  124478. 9, 9, 9, 9,10, 9, 9, 9,10,10,11,11,11,11,11, 9,
  124479. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,11,11,11,11,11,
  124480. 9, 9, 9, 9,10,10, 9, 9, 9,10,10,10,11,11,11,11,
  124481. 11,11,11, 9, 9, 9,10, 9, 9,10,10,10,10,11,11,10,
  124482. 11,11,11,11,10, 9,10,10, 9, 9, 9, 9,10,10,11,10,
  124483. 11,11,11,11,11, 9, 9, 9, 9,10, 9,10,10,10,10,11,
  124484. 10,11,11,11,11,11,10,10, 9, 9,10, 9,10,10,10,10,
  124485. 10,10,10,11,11,11,11,11,11, 9, 9,10, 9,10, 9,10,
  124486. 10,
  124487. };
  124488. static float _vq_quantthresh__44c2_s_p9_2[] = {
  124489. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  124490. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  124491. };
  124492. static long _vq_quantmap__44c2_s_p9_2[] = {
  124493. 15, 13, 11, 9, 7, 5, 3, 1,
  124494. 0, 2, 4, 6, 8, 10, 12, 14,
  124495. 16,
  124496. };
  124497. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_2 = {
  124498. _vq_quantthresh__44c2_s_p9_2,
  124499. _vq_quantmap__44c2_s_p9_2,
  124500. 17,
  124501. 17
  124502. };
  124503. static static_codebook _44c2_s_p9_2 = {
  124504. 2, 289,
  124505. _vq_lengthlist__44c2_s_p9_2,
  124506. 1, -529530880, 1611661312, 5, 0,
  124507. _vq_quantlist__44c2_s_p9_2,
  124508. NULL,
  124509. &_vq_auxt__44c2_s_p9_2,
  124510. NULL,
  124511. 0
  124512. };
  124513. static long _huff_lengthlist__44c2_s_short[] = {
  124514. 11, 9,13,12,12,11,12,12,13,15, 8, 2,11, 4, 8, 5,
  124515. 7,10,12,15,13, 7,10, 9, 8, 8,10,13,17,17,11, 4,
  124516. 12, 5, 9, 5, 8,11,14,16,12, 6, 8, 7, 6, 6, 8,11,
  124517. 13,16,11, 4, 9, 5, 6, 4, 6,10,13,16,11, 6,11, 7,
  124518. 7, 6, 7,10,13,15,13, 9,12, 9, 8, 6, 8,10,12,14,
  124519. 14,10,10, 8, 6, 5, 6, 9,11,13,15,11,11, 9, 6, 5,
  124520. 6, 8, 9,12,
  124521. };
  124522. static static_codebook _huff_book__44c2_s_short = {
  124523. 2, 100,
  124524. _huff_lengthlist__44c2_s_short,
  124525. 0, 0, 0, 0, 0,
  124526. NULL,
  124527. NULL,
  124528. NULL,
  124529. NULL,
  124530. 0
  124531. };
  124532. static long _huff_lengthlist__44c3_s_long[] = {
  124533. 5, 6,11,11,11,11,10,10,12,11, 5, 2,11, 5, 6, 6,
  124534. 7, 9,11,13,13,10, 7,11, 6, 7, 8, 9,10,12,11, 5,
  124535. 11, 6, 8, 7, 9,11,14,15,11, 6, 6, 8, 4, 5, 7, 8,
  124536. 10,13,10, 5, 7, 7, 5, 5, 6, 8,10,11,10, 7, 7, 8,
  124537. 6, 5, 5, 7, 9, 9,11, 8, 8,11, 8, 7, 6, 6, 7, 9,
  124538. 12,11,10,13, 9, 9, 7, 7, 7, 9,11,13,12,15,12,11,
  124539. 9, 8, 8, 8,
  124540. };
  124541. static static_codebook _huff_book__44c3_s_long = {
  124542. 2, 100,
  124543. _huff_lengthlist__44c3_s_long,
  124544. 0, 0, 0, 0, 0,
  124545. NULL,
  124546. NULL,
  124547. NULL,
  124548. NULL,
  124549. 0
  124550. };
  124551. static long _vq_quantlist__44c3_s_p1_0[] = {
  124552. 1,
  124553. 0,
  124554. 2,
  124555. };
  124556. static long _vq_lengthlist__44c3_s_p1_0[] = {
  124557. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  124558. 0, 0, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124562. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  124563. 0, 0, 0, 6, 7, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124567. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  124568. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  124603. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  124604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  124608. 0, 0, 0, 8, 8, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  124609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0, 0,
  124613. 0, 0, 0, 0, 7, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  124614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124648. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  124649. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124653. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  124654. 0, 0, 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0,
  124655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124658. 0, 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  124659. 0, 0, 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 0,
  124660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124967. 0,
  124968. };
  124969. static float _vq_quantthresh__44c3_s_p1_0[] = {
  124970. -0.5, 0.5,
  124971. };
  124972. static long _vq_quantmap__44c3_s_p1_0[] = {
  124973. 1, 0, 2,
  124974. };
  124975. static encode_aux_threshmatch _vq_auxt__44c3_s_p1_0 = {
  124976. _vq_quantthresh__44c3_s_p1_0,
  124977. _vq_quantmap__44c3_s_p1_0,
  124978. 3,
  124979. 3
  124980. };
  124981. static static_codebook _44c3_s_p1_0 = {
  124982. 8, 6561,
  124983. _vq_lengthlist__44c3_s_p1_0,
  124984. 1, -535822336, 1611661312, 2, 0,
  124985. _vq_quantlist__44c3_s_p1_0,
  124986. NULL,
  124987. &_vq_auxt__44c3_s_p1_0,
  124988. NULL,
  124989. 0
  124990. };
  124991. static long _vq_quantlist__44c3_s_p2_0[] = {
  124992. 2,
  124993. 1,
  124994. 3,
  124995. 0,
  124996. 4,
  124997. };
  124998. static long _vq_lengthlist__44c3_s_p2_0[] = {
  124999. 2, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  125000. 7, 8, 0, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 7,
  125001. 7, 0, 0, 0, 7, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  125002. 0, 0, 5, 6, 6, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0,
  125003. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125008. 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0,
  125009. 0, 7, 7, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5,
  125010. 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9,
  125011. 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125016. 0, 0, 0, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7,
  125017. 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0,
  125018. 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9, 9, 0, 0,
  125019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125024. 8,10,10, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 0, 0, 0,
  125025. 10,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0, 9,
  125026. 9, 0, 0, 0, 9, 9, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  125027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125038. 0,
  125039. };
  125040. static float _vq_quantthresh__44c3_s_p2_0[] = {
  125041. -1.5, -0.5, 0.5, 1.5,
  125042. };
  125043. static long _vq_quantmap__44c3_s_p2_0[] = {
  125044. 3, 1, 0, 2, 4,
  125045. };
  125046. static encode_aux_threshmatch _vq_auxt__44c3_s_p2_0 = {
  125047. _vq_quantthresh__44c3_s_p2_0,
  125048. _vq_quantmap__44c3_s_p2_0,
  125049. 5,
  125050. 5
  125051. };
  125052. static static_codebook _44c3_s_p2_0 = {
  125053. 4, 625,
  125054. _vq_lengthlist__44c3_s_p2_0,
  125055. 1, -533725184, 1611661312, 3, 0,
  125056. _vq_quantlist__44c3_s_p2_0,
  125057. NULL,
  125058. &_vq_auxt__44c3_s_p2_0,
  125059. NULL,
  125060. 0
  125061. };
  125062. static long _vq_quantlist__44c3_s_p3_0[] = {
  125063. 2,
  125064. 1,
  125065. 3,
  125066. 0,
  125067. 4,
  125068. };
  125069. static long _vq_lengthlist__44c3_s_p3_0[] = {
  125070. 2, 4, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  125072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125073. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  125075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125076. 0, 0, 0, 0, 6, 6, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  125077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125109. 0,
  125110. };
  125111. static float _vq_quantthresh__44c3_s_p3_0[] = {
  125112. -1.5, -0.5, 0.5, 1.5,
  125113. };
  125114. static long _vq_quantmap__44c3_s_p3_0[] = {
  125115. 3, 1, 0, 2, 4,
  125116. };
  125117. static encode_aux_threshmatch _vq_auxt__44c3_s_p3_0 = {
  125118. _vq_quantthresh__44c3_s_p3_0,
  125119. _vq_quantmap__44c3_s_p3_0,
  125120. 5,
  125121. 5
  125122. };
  125123. static static_codebook _44c3_s_p3_0 = {
  125124. 4, 625,
  125125. _vq_lengthlist__44c3_s_p3_0,
  125126. 1, -533725184, 1611661312, 3, 0,
  125127. _vq_quantlist__44c3_s_p3_0,
  125128. NULL,
  125129. &_vq_auxt__44c3_s_p3_0,
  125130. NULL,
  125131. 0
  125132. };
  125133. static long _vq_quantlist__44c3_s_p4_0[] = {
  125134. 4,
  125135. 3,
  125136. 5,
  125137. 2,
  125138. 6,
  125139. 1,
  125140. 7,
  125141. 0,
  125142. 8,
  125143. };
  125144. static long _vq_lengthlist__44c3_s_p4_0[] = {
  125145. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  125146. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  125147. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  125148. 7, 8, 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0,
  125149. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125150. 0,
  125151. };
  125152. static float _vq_quantthresh__44c3_s_p4_0[] = {
  125153. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  125154. };
  125155. static long _vq_quantmap__44c3_s_p4_0[] = {
  125156. 7, 5, 3, 1, 0, 2, 4, 6,
  125157. 8,
  125158. };
  125159. static encode_aux_threshmatch _vq_auxt__44c3_s_p4_0 = {
  125160. _vq_quantthresh__44c3_s_p4_0,
  125161. _vq_quantmap__44c3_s_p4_0,
  125162. 9,
  125163. 9
  125164. };
  125165. static static_codebook _44c3_s_p4_0 = {
  125166. 2, 81,
  125167. _vq_lengthlist__44c3_s_p4_0,
  125168. 1, -531628032, 1611661312, 4, 0,
  125169. _vq_quantlist__44c3_s_p4_0,
  125170. NULL,
  125171. &_vq_auxt__44c3_s_p4_0,
  125172. NULL,
  125173. 0
  125174. };
  125175. static long _vq_quantlist__44c3_s_p5_0[] = {
  125176. 4,
  125177. 3,
  125178. 5,
  125179. 2,
  125180. 6,
  125181. 1,
  125182. 7,
  125183. 0,
  125184. 8,
  125185. };
  125186. static long _vq_lengthlist__44c3_s_p5_0[] = {
  125187. 1, 3, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 7, 8,
  125188. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  125189. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  125190. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  125191. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  125192. 11,
  125193. };
  125194. static float _vq_quantthresh__44c3_s_p5_0[] = {
  125195. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  125196. };
  125197. static long _vq_quantmap__44c3_s_p5_0[] = {
  125198. 7, 5, 3, 1, 0, 2, 4, 6,
  125199. 8,
  125200. };
  125201. static encode_aux_threshmatch _vq_auxt__44c3_s_p5_0 = {
  125202. _vq_quantthresh__44c3_s_p5_0,
  125203. _vq_quantmap__44c3_s_p5_0,
  125204. 9,
  125205. 9
  125206. };
  125207. static static_codebook _44c3_s_p5_0 = {
  125208. 2, 81,
  125209. _vq_lengthlist__44c3_s_p5_0,
  125210. 1, -531628032, 1611661312, 4, 0,
  125211. _vq_quantlist__44c3_s_p5_0,
  125212. NULL,
  125213. &_vq_auxt__44c3_s_p5_0,
  125214. NULL,
  125215. 0
  125216. };
  125217. static long _vq_quantlist__44c3_s_p6_0[] = {
  125218. 8,
  125219. 7,
  125220. 9,
  125221. 6,
  125222. 10,
  125223. 5,
  125224. 11,
  125225. 4,
  125226. 12,
  125227. 3,
  125228. 13,
  125229. 2,
  125230. 14,
  125231. 1,
  125232. 15,
  125233. 0,
  125234. 16,
  125235. };
  125236. static long _vq_lengthlist__44c3_s_p6_0[] = {
  125237. 2, 3, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  125238. 10, 0, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  125239. 11,11, 0, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  125240. 10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  125241. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  125242. 10,11,11,11,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  125243. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9,
  125244. 9,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  125245. 10,10,11,10,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  125246. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 8,
  125247. 9, 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8,
  125248. 8, 9, 9,10,10,11,11,12,11,12,12, 0, 0, 0, 0, 0,
  125249. 9,10,10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0,
  125250. 0, 0, 0,10,10,10,10,11,11,12,12,13,13, 0, 0, 0,
  125251. 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0, 0,
  125252. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  125253. 0, 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,13,
  125254. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,
  125255. 13,
  125256. };
  125257. static float _vq_quantthresh__44c3_s_p6_0[] = {
  125258. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  125259. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  125260. };
  125261. static long _vq_quantmap__44c3_s_p6_0[] = {
  125262. 15, 13, 11, 9, 7, 5, 3, 1,
  125263. 0, 2, 4, 6, 8, 10, 12, 14,
  125264. 16,
  125265. };
  125266. static encode_aux_threshmatch _vq_auxt__44c3_s_p6_0 = {
  125267. _vq_quantthresh__44c3_s_p6_0,
  125268. _vq_quantmap__44c3_s_p6_0,
  125269. 17,
  125270. 17
  125271. };
  125272. static static_codebook _44c3_s_p6_0 = {
  125273. 2, 289,
  125274. _vq_lengthlist__44c3_s_p6_0,
  125275. 1, -529530880, 1611661312, 5, 0,
  125276. _vq_quantlist__44c3_s_p6_0,
  125277. NULL,
  125278. &_vq_auxt__44c3_s_p6_0,
  125279. NULL,
  125280. 0
  125281. };
  125282. static long _vq_quantlist__44c3_s_p7_0[] = {
  125283. 1,
  125284. 0,
  125285. 2,
  125286. };
  125287. static long _vq_lengthlist__44c3_s_p7_0[] = {
  125288. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  125289. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  125290. 10,12,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  125291. 11,10,10,11,10,10, 7,11,11,11,11,11,12,11,11, 6,
  125292. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  125293. 10,
  125294. };
  125295. static float _vq_quantthresh__44c3_s_p7_0[] = {
  125296. -5.5, 5.5,
  125297. };
  125298. static long _vq_quantmap__44c3_s_p7_0[] = {
  125299. 1, 0, 2,
  125300. };
  125301. static encode_aux_threshmatch _vq_auxt__44c3_s_p7_0 = {
  125302. _vq_quantthresh__44c3_s_p7_0,
  125303. _vq_quantmap__44c3_s_p7_0,
  125304. 3,
  125305. 3
  125306. };
  125307. static static_codebook _44c3_s_p7_0 = {
  125308. 4, 81,
  125309. _vq_lengthlist__44c3_s_p7_0,
  125310. 1, -529137664, 1618345984, 2, 0,
  125311. _vq_quantlist__44c3_s_p7_0,
  125312. NULL,
  125313. &_vq_auxt__44c3_s_p7_0,
  125314. NULL,
  125315. 0
  125316. };
  125317. static long _vq_quantlist__44c3_s_p7_1[] = {
  125318. 5,
  125319. 4,
  125320. 6,
  125321. 3,
  125322. 7,
  125323. 2,
  125324. 8,
  125325. 1,
  125326. 9,
  125327. 0,
  125328. 10,
  125329. };
  125330. static long _vq_lengthlist__44c3_s_p7_1[] = {
  125331. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  125332. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  125333. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  125334. 7, 8, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  125335. 8, 8,10,10,10, 7, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  125336. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  125337. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 9, 8,10,10,
  125338. 10,10,10, 8, 8, 8, 8, 8, 8,
  125339. };
  125340. static float _vq_quantthresh__44c3_s_p7_1[] = {
  125341. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  125342. 3.5, 4.5,
  125343. };
  125344. static long _vq_quantmap__44c3_s_p7_1[] = {
  125345. 9, 7, 5, 3, 1, 0, 2, 4,
  125346. 6, 8, 10,
  125347. };
  125348. static encode_aux_threshmatch _vq_auxt__44c3_s_p7_1 = {
  125349. _vq_quantthresh__44c3_s_p7_1,
  125350. _vq_quantmap__44c3_s_p7_1,
  125351. 11,
  125352. 11
  125353. };
  125354. static static_codebook _44c3_s_p7_1 = {
  125355. 2, 121,
  125356. _vq_lengthlist__44c3_s_p7_1,
  125357. 1, -531365888, 1611661312, 4, 0,
  125358. _vq_quantlist__44c3_s_p7_1,
  125359. NULL,
  125360. &_vq_auxt__44c3_s_p7_1,
  125361. NULL,
  125362. 0
  125363. };
  125364. static long _vq_quantlist__44c3_s_p8_0[] = {
  125365. 6,
  125366. 5,
  125367. 7,
  125368. 4,
  125369. 8,
  125370. 3,
  125371. 9,
  125372. 2,
  125373. 10,
  125374. 1,
  125375. 11,
  125376. 0,
  125377. 12,
  125378. };
  125379. static long _vq_lengthlist__44c3_s_p8_0[] = {
  125380. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  125381. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5, 7, 7, 8,
  125382. 8, 8, 8, 9, 9,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  125383. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  125384. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,12, 0,13,
  125385. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  125386. 10,10,11,11,12,12,12,12, 0, 0, 0,10,10,10,10,11,
  125387. 11,12,12,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  125388. 13,13, 0, 0, 0,14,14,11,11,11,11,12,12,13,13, 0,
  125389. 0, 0, 0, 0,12,12,12,12,13,13,14,13, 0, 0, 0, 0,
  125390. 0,13,13,12,12,13,12,14,13,
  125391. };
  125392. static float _vq_quantthresh__44c3_s_p8_0[] = {
  125393. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  125394. 12.5, 17.5, 22.5, 27.5,
  125395. };
  125396. static long _vq_quantmap__44c3_s_p8_0[] = {
  125397. 11, 9, 7, 5, 3, 1, 0, 2,
  125398. 4, 6, 8, 10, 12,
  125399. };
  125400. static encode_aux_threshmatch _vq_auxt__44c3_s_p8_0 = {
  125401. _vq_quantthresh__44c3_s_p8_0,
  125402. _vq_quantmap__44c3_s_p8_0,
  125403. 13,
  125404. 13
  125405. };
  125406. static static_codebook _44c3_s_p8_0 = {
  125407. 2, 169,
  125408. _vq_lengthlist__44c3_s_p8_0,
  125409. 1, -526516224, 1616117760, 4, 0,
  125410. _vq_quantlist__44c3_s_p8_0,
  125411. NULL,
  125412. &_vq_auxt__44c3_s_p8_0,
  125413. NULL,
  125414. 0
  125415. };
  125416. static long _vq_quantlist__44c3_s_p8_1[] = {
  125417. 2,
  125418. 1,
  125419. 3,
  125420. 0,
  125421. 4,
  125422. };
  125423. static long _vq_lengthlist__44c3_s_p8_1[] = {
  125424. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 4, 5, 5, 5, 6,
  125425. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  125426. };
  125427. static float _vq_quantthresh__44c3_s_p8_1[] = {
  125428. -1.5, -0.5, 0.5, 1.5,
  125429. };
  125430. static long _vq_quantmap__44c3_s_p8_1[] = {
  125431. 3, 1, 0, 2, 4,
  125432. };
  125433. static encode_aux_threshmatch _vq_auxt__44c3_s_p8_1 = {
  125434. _vq_quantthresh__44c3_s_p8_1,
  125435. _vq_quantmap__44c3_s_p8_1,
  125436. 5,
  125437. 5
  125438. };
  125439. static static_codebook _44c3_s_p8_1 = {
  125440. 2, 25,
  125441. _vq_lengthlist__44c3_s_p8_1,
  125442. 1, -533725184, 1611661312, 3, 0,
  125443. _vq_quantlist__44c3_s_p8_1,
  125444. NULL,
  125445. &_vq_auxt__44c3_s_p8_1,
  125446. NULL,
  125447. 0
  125448. };
  125449. static long _vq_quantlist__44c3_s_p9_0[] = {
  125450. 6,
  125451. 5,
  125452. 7,
  125453. 4,
  125454. 8,
  125455. 3,
  125456. 9,
  125457. 2,
  125458. 10,
  125459. 1,
  125460. 11,
  125461. 0,
  125462. 12,
  125463. };
  125464. static long _vq_lengthlist__44c3_s_p9_0[] = {
  125465. 1, 4, 4,12,12,12,12,12,12,12,12,12,12, 4, 9, 8,
  125466. 12,12,12,12,12,12,12,12,12,12, 2, 9, 7,12,12,12,
  125467. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  125468. 12,12,12,12,12,12,11,12,12,12,12,12,12,12,12,12,
  125469. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  125470. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  125471. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  125472. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  125473. 12,12,12,12,12,12,12,12,12,12,11,11,11,11,11,11,
  125474. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  125475. 11,11,11,11,11,11,11,11,11,
  125476. };
  125477. static float _vq_quantthresh__44c3_s_p9_0[] = {
  125478. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  125479. 637.5, 892.5, 1147.5, 1402.5,
  125480. };
  125481. static long _vq_quantmap__44c3_s_p9_0[] = {
  125482. 11, 9, 7, 5, 3, 1, 0, 2,
  125483. 4, 6, 8, 10, 12,
  125484. };
  125485. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_0 = {
  125486. _vq_quantthresh__44c3_s_p9_0,
  125487. _vq_quantmap__44c3_s_p9_0,
  125488. 13,
  125489. 13
  125490. };
  125491. static static_codebook _44c3_s_p9_0 = {
  125492. 2, 169,
  125493. _vq_lengthlist__44c3_s_p9_0,
  125494. 1, -514332672, 1627381760, 4, 0,
  125495. _vq_quantlist__44c3_s_p9_0,
  125496. NULL,
  125497. &_vq_auxt__44c3_s_p9_0,
  125498. NULL,
  125499. 0
  125500. };
  125501. static long _vq_quantlist__44c3_s_p9_1[] = {
  125502. 7,
  125503. 6,
  125504. 8,
  125505. 5,
  125506. 9,
  125507. 4,
  125508. 10,
  125509. 3,
  125510. 11,
  125511. 2,
  125512. 12,
  125513. 1,
  125514. 13,
  125515. 0,
  125516. 14,
  125517. };
  125518. static long _vq_lengthlist__44c3_s_p9_1[] = {
  125519. 1, 4, 4, 6, 6, 7, 7, 8, 7, 9, 9,10,10,10,10, 6,
  125520. 5, 5, 7, 7, 8, 8,10, 8,11,10,12,12,13,13, 6, 5,
  125521. 5, 7, 7, 8, 8,10, 9,11,11,12,12,13,12,18, 8, 8,
  125522. 8, 8, 9, 9,10, 9,11,10,12,12,13,13,18, 8, 8, 8,
  125523. 8, 9, 9,10,10,11,11,13,12,14,13,18,11,11, 9, 9,
  125524. 10,10,11,11,11,12,13,12,13,14,18,11,11, 9, 8,11,
  125525. 10,11,11,11,11,12,12,14,13,18,18,18,10,11,10,11,
  125526. 12,12,12,12,13,12,14,13,18,18,18,10,11,11, 9,12,
  125527. 11,12,12,12,13,13,13,18,18,17,14,14,11,11,12,12,
  125528. 13,12,14,12,14,13,18,18,18,14,14,11,10,12, 9,12,
  125529. 13,13,13,13,13,18,18,17,16,18,13,13,12,12,13,11,
  125530. 14,12,14,14,17,18,18,17,18,13,12,13,10,12,11,14,
  125531. 14,14,14,17,18,18,18,18,15,16,12,12,13,10,14,12,
  125532. 14,15,18,18,18,16,17,16,14,12,11,13,10,13,13,14,
  125533. 15,
  125534. };
  125535. static float _vq_quantthresh__44c3_s_p9_1[] = {
  125536. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  125537. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  125538. };
  125539. static long _vq_quantmap__44c3_s_p9_1[] = {
  125540. 13, 11, 9, 7, 5, 3, 1, 0,
  125541. 2, 4, 6, 8, 10, 12, 14,
  125542. };
  125543. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_1 = {
  125544. _vq_quantthresh__44c3_s_p9_1,
  125545. _vq_quantmap__44c3_s_p9_1,
  125546. 15,
  125547. 15
  125548. };
  125549. static static_codebook _44c3_s_p9_1 = {
  125550. 2, 225,
  125551. _vq_lengthlist__44c3_s_p9_1,
  125552. 1, -522338304, 1620115456, 4, 0,
  125553. _vq_quantlist__44c3_s_p9_1,
  125554. NULL,
  125555. &_vq_auxt__44c3_s_p9_1,
  125556. NULL,
  125557. 0
  125558. };
  125559. static long _vq_quantlist__44c3_s_p9_2[] = {
  125560. 8,
  125561. 7,
  125562. 9,
  125563. 6,
  125564. 10,
  125565. 5,
  125566. 11,
  125567. 4,
  125568. 12,
  125569. 3,
  125570. 13,
  125571. 2,
  125572. 14,
  125573. 1,
  125574. 15,
  125575. 0,
  125576. 16,
  125577. };
  125578. static long _vq_lengthlist__44c3_s_p9_2[] = {
  125579. 2, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8,
  125580. 8,10, 6, 6, 7, 7, 8, 7, 8, 8, 8, 8, 8, 9, 9, 9,
  125581. 9, 9,10, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  125582. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  125583. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 9, 9, 9, 9,
  125584. 9, 9, 9, 9, 9,11,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  125585. 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  125586. 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 9, 9, 9, 9, 9,
  125587. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,11,11, 9, 9, 9,
  125588. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,11, 9, 9,
  125589. 9, 9, 9, 9,10,10, 9, 9,10, 9,11,10,11,11,11, 9,
  125590. 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,11,11,11,11,11,
  125591. 9, 9, 9, 9,10,10, 9, 9, 9, 9,10, 9,11,11,11,11,
  125592. 11,11,11, 9, 9, 9, 9, 9, 9,10,10,10,10,11,11,11,
  125593. 11,11,11,11,10, 9,10,10, 9,10, 9, 9,10, 9,11,10,
  125594. 10,11,11,11,11, 9,10, 9, 9, 9, 9,10,10,10,10,11,
  125595. 11,11,11,11,11,10,10,10, 9, 9,10, 9,10, 9,10,10,
  125596. 10,10,11,11,11,11,11,11,11, 9, 9, 9, 9, 9,10,10,
  125597. 10,
  125598. };
  125599. static float _vq_quantthresh__44c3_s_p9_2[] = {
  125600. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  125601. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  125602. };
  125603. static long _vq_quantmap__44c3_s_p9_2[] = {
  125604. 15, 13, 11, 9, 7, 5, 3, 1,
  125605. 0, 2, 4, 6, 8, 10, 12, 14,
  125606. 16,
  125607. };
  125608. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_2 = {
  125609. _vq_quantthresh__44c3_s_p9_2,
  125610. _vq_quantmap__44c3_s_p9_2,
  125611. 17,
  125612. 17
  125613. };
  125614. static static_codebook _44c3_s_p9_2 = {
  125615. 2, 289,
  125616. _vq_lengthlist__44c3_s_p9_2,
  125617. 1, -529530880, 1611661312, 5, 0,
  125618. _vq_quantlist__44c3_s_p9_2,
  125619. NULL,
  125620. &_vq_auxt__44c3_s_p9_2,
  125621. NULL,
  125622. 0
  125623. };
  125624. static long _huff_lengthlist__44c3_s_short[] = {
  125625. 10, 9,13,11,14,10,12,13,13,14, 7, 2,12, 5,10, 5,
  125626. 7,10,12,14,12, 6, 9, 8, 7, 7, 9,11,13,16,10, 4,
  125627. 12, 5,10, 6, 8,12,14,16,12, 6, 8, 7, 6, 5, 7,11,
  125628. 12,16,10, 4, 8, 5, 6, 4, 6, 9,13,16,10, 6,10, 7,
  125629. 7, 6, 7, 9,13,15,12, 9,11, 9, 8, 6, 7,10,12,14,
  125630. 14,11,10, 9, 6, 5, 6, 9,11,13,15,13,11,10, 6, 5,
  125631. 6, 8, 9,11,
  125632. };
  125633. static static_codebook _huff_book__44c3_s_short = {
  125634. 2, 100,
  125635. _huff_lengthlist__44c3_s_short,
  125636. 0, 0, 0, 0, 0,
  125637. NULL,
  125638. NULL,
  125639. NULL,
  125640. NULL,
  125641. 0
  125642. };
  125643. static long _huff_lengthlist__44c4_s_long[] = {
  125644. 4, 7,11,11,11,11,10,11,12,11, 5, 2,11, 5, 6, 6,
  125645. 7, 9,11,12,11, 9, 6,10, 6, 7, 8, 9,10,11,11, 5,
  125646. 11, 7, 8, 8, 9,11,13,14,11, 6, 5, 8, 4, 5, 7, 8,
  125647. 10,11,10, 6, 7, 7, 5, 5, 6, 8, 9,11,10, 7, 8, 9,
  125648. 6, 6, 6, 7, 8, 9,11, 9, 9,11, 7, 7, 6, 6, 7, 9,
  125649. 12,12,10,13, 9, 8, 7, 7, 7, 8,11,13,11,14,11,10,
  125650. 9, 8, 7, 7,
  125651. };
  125652. static static_codebook _huff_book__44c4_s_long = {
  125653. 2, 100,
  125654. _huff_lengthlist__44c4_s_long,
  125655. 0, 0, 0, 0, 0,
  125656. NULL,
  125657. NULL,
  125658. NULL,
  125659. NULL,
  125660. 0
  125661. };
  125662. static long _vq_quantlist__44c4_s_p1_0[] = {
  125663. 1,
  125664. 0,
  125665. 2,
  125666. };
  125667. static long _vq_lengthlist__44c4_s_p1_0[] = {
  125668. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  125669. 0, 0, 5, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125673. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  125674. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125678. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  125679. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  125714. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  125715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  125719. 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  125720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0, 0,
  125724. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  125725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125759. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  125760. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125764. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  125765. 0, 0, 0, 0, 0, 8, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0,
  125766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125769. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  125770. 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  125771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126078. 0,
  126079. };
  126080. static float _vq_quantthresh__44c4_s_p1_0[] = {
  126081. -0.5, 0.5,
  126082. };
  126083. static long _vq_quantmap__44c4_s_p1_0[] = {
  126084. 1, 0, 2,
  126085. };
  126086. static encode_aux_threshmatch _vq_auxt__44c4_s_p1_0 = {
  126087. _vq_quantthresh__44c4_s_p1_0,
  126088. _vq_quantmap__44c4_s_p1_0,
  126089. 3,
  126090. 3
  126091. };
  126092. static static_codebook _44c4_s_p1_0 = {
  126093. 8, 6561,
  126094. _vq_lengthlist__44c4_s_p1_0,
  126095. 1, -535822336, 1611661312, 2, 0,
  126096. _vq_quantlist__44c4_s_p1_0,
  126097. NULL,
  126098. &_vq_auxt__44c4_s_p1_0,
  126099. NULL,
  126100. 0
  126101. };
  126102. static long _vq_quantlist__44c4_s_p2_0[] = {
  126103. 2,
  126104. 1,
  126105. 3,
  126106. 0,
  126107. 4,
  126108. };
  126109. static long _vq_lengthlist__44c4_s_p2_0[] = {
  126110. 2, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  126111. 7, 7, 0, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 7,
  126112. 7, 0, 0, 0, 7, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  126113. 0, 0, 5, 6, 6, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0,
  126114. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126119. 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 7, 7, 0, 0,
  126120. 0, 7, 7, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5,
  126121. 7, 8, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9,
  126122. 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126127. 0, 0, 0, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7,
  126128. 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0,
  126129. 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9, 9, 0, 0,
  126130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126135. 7,10,10, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 0, 0, 0,
  126136. 10,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0, 9,
  126137. 9, 0, 0, 0, 9, 9, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  126138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126149. 0,
  126150. };
  126151. static float _vq_quantthresh__44c4_s_p2_0[] = {
  126152. -1.5, -0.5, 0.5, 1.5,
  126153. };
  126154. static long _vq_quantmap__44c4_s_p2_0[] = {
  126155. 3, 1, 0, 2, 4,
  126156. };
  126157. static encode_aux_threshmatch _vq_auxt__44c4_s_p2_0 = {
  126158. _vq_quantthresh__44c4_s_p2_0,
  126159. _vq_quantmap__44c4_s_p2_0,
  126160. 5,
  126161. 5
  126162. };
  126163. static static_codebook _44c4_s_p2_0 = {
  126164. 4, 625,
  126165. _vq_lengthlist__44c4_s_p2_0,
  126166. 1, -533725184, 1611661312, 3, 0,
  126167. _vq_quantlist__44c4_s_p2_0,
  126168. NULL,
  126169. &_vq_auxt__44c4_s_p2_0,
  126170. NULL,
  126171. 0
  126172. };
  126173. static long _vq_quantlist__44c4_s_p3_0[] = {
  126174. 2,
  126175. 1,
  126176. 3,
  126177. 0,
  126178. 4,
  126179. };
  126180. static long _vq_lengthlist__44c4_s_p3_0[] = {
  126181. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 4, 6, 6, 0, 0,
  126183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126184. 0, 0, 4, 4, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  126186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126187. 0, 0, 0, 0, 6, 6, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  126188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126220. 0,
  126221. };
  126222. static float _vq_quantthresh__44c4_s_p3_0[] = {
  126223. -1.5, -0.5, 0.5, 1.5,
  126224. };
  126225. static long _vq_quantmap__44c4_s_p3_0[] = {
  126226. 3, 1, 0, 2, 4,
  126227. };
  126228. static encode_aux_threshmatch _vq_auxt__44c4_s_p3_0 = {
  126229. _vq_quantthresh__44c4_s_p3_0,
  126230. _vq_quantmap__44c4_s_p3_0,
  126231. 5,
  126232. 5
  126233. };
  126234. static static_codebook _44c4_s_p3_0 = {
  126235. 4, 625,
  126236. _vq_lengthlist__44c4_s_p3_0,
  126237. 1, -533725184, 1611661312, 3, 0,
  126238. _vq_quantlist__44c4_s_p3_0,
  126239. NULL,
  126240. &_vq_auxt__44c4_s_p3_0,
  126241. NULL,
  126242. 0
  126243. };
  126244. static long _vq_quantlist__44c4_s_p4_0[] = {
  126245. 4,
  126246. 3,
  126247. 5,
  126248. 2,
  126249. 6,
  126250. 1,
  126251. 7,
  126252. 0,
  126253. 8,
  126254. };
  126255. static long _vq_lengthlist__44c4_s_p4_0[] = {
  126256. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  126257. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  126258. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  126259. 7, 8, 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0,
  126260. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126261. 0,
  126262. };
  126263. static float _vq_quantthresh__44c4_s_p4_0[] = {
  126264. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  126265. };
  126266. static long _vq_quantmap__44c4_s_p4_0[] = {
  126267. 7, 5, 3, 1, 0, 2, 4, 6,
  126268. 8,
  126269. };
  126270. static encode_aux_threshmatch _vq_auxt__44c4_s_p4_0 = {
  126271. _vq_quantthresh__44c4_s_p4_0,
  126272. _vq_quantmap__44c4_s_p4_0,
  126273. 9,
  126274. 9
  126275. };
  126276. static static_codebook _44c4_s_p4_0 = {
  126277. 2, 81,
  126278. _vq_lengthlist__44c4_s_p4_0,
  126279. 1, -531628032, 1611661312, 4, 0,
  126280. _vq_quantlist__44c4_s_p4_0,
  126281. NULL,
  126282. &_vq_auxt__44c4_s_p4_0,
  126283. NULL,
  126284. 0
  126285. };
  126286. static long _vq_quantlist__44c4_s_p5_0[] = {
  126287. 4,
  126288. 3,
  126289. 5,
  126290. 2,
  126291. 6,
  126292. 1,
  126293. 7,
  126294. 0,
  126295. 8,
  126296. };
  126297. static long _vq_lengthlist__44c4_s_p5_0[] = {
  126298. 2, 3, 3, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  126299. 9, 9, 0, 4, 5, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7,
  126300. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10, 9, 0, 0, 0,
  126301. 9, 8, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  126302. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,10,
  126303. 10,
  126304. };
  126305. static float _vq_quantthresh__44c4_s_p5_0[] = {
  126306. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  126307. };
  126308. static long _vq_quantmap__44c4_s_p5_0[] = {
  126309. 7, 5, 3, 1, 0, 2, 4, 6,
  126310. 8,
  126311. };
  126312. static encode_aux_threshmatch _vq_auxt__44c4_s_p5_0 = {
  126313. _vq_quantthresh__44c4_s_p5_0,
  126314. _vq_quantmap__44c4_s_p5_0,
  126315. 9,
  126316. 9
  126317. };
  126318. static static_codebook _44c4_s_p5_0 = {
  126319. 2, 81,
  126320. _vq_lengthlist__44c4_s_p5_0,
  126321. 1, -531628032, 1611661312, 4, 0,
  126322. _vq_quantlist__44c4_s_p5_0,
  126323. NULL,
  126324. &_vq_auxt__44c4_s_p5_0,
  126325. NULL,
  126326. 0
  126327. };
  126328. static long _vq_quantlist__44c4_s_p6_0[] = {
  126329. 8,
  126330. 7,
  126331. 9,
  126332. 6,
  126333. 10,
  126334. 5,
  126335. 11,
  126336. 4,
  126337. 12,
  126338. 3,
  126339. 13,
  126340. 2,
  126341. 14,
  126342. 1,
  126343. 15,
  126344. 0,
  126345. 16,
  126346. };
  126347. static long _vq_lengthlist__44c4_s_p6_0[] = {
  126348. 2, 4, 4, 6, 6, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,
  126349. 11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,
  126350. 11,11, 0, 4, 4, 7, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  126351. 11,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  126352. 11,11,11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  126353. 10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  126354. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9,
  126355. 9,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  126356. 10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  126357. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,
  126358. 9,10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9,
  126359. 9, 9, 9,10,10,11,11,11,12,12,12, 0, 0, 0, 0, 0,
  126360. 10,10,10,10,11,11,11,11,12,12,13,12, 0, 0, 0, 0,
  126361. 0, 0, 0,10,10,11,11,11,11,12,12,12,12, 0, 0, 0,
  126362. 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0, 0,
  126363. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  126364. 0, 0, 0, 0, 0, 0,12,12,12,12,12,12,13,13,13,13,
  126365. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,12,13,13,
  126366. 13,
  126367. };
  126368. static float _vq_quantthresh__44c4_s_p6_0[] = {
  126369. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  126370. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  126371. };
  126372. static long _vq_quantmap__44c4_s_p6_0[] = {
  126373. 15, 13, 11, 9, 7, 5, 3, 1,
  126374. 0, 2, 4, 6, 8, 10, 12, 14,
  126375. 16,
  126376. };
  126377. static encode_aux_threshmatch _vq_auxt__44c4_s_p6_0 = {
  126378. _vq_quantthresh__44c4_s_p6_0,
  126379. _vq_quantmap__44c4_s_p6_0,
  126380. 17,
  126381. 17
  126382. };
  126383. static static_codebook _44c4_s_p6_0 = {
  126384. 2, 289,
  126385. _vq_lengthlist__44c4_s_p6_0,
  126386. 1, -529530880, 1611661312, 5, 0,
  126387. _vq_quantlist__44c4_s_p6_0,
  126388. NULL,
  126389. &_vq_auxt__44c4_s_p6_0,
  126390. NULL,
  126391. 0
  126392. };
  126393. static long _vq_quantlist__44c4_s_p7_0[] = {
  126394. 1,
  126395. 0,
  126396. 2,
  126397. };
  126398. static long _vq_lengthlist__44c4_s_p7_0[] = {
  126399. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  126400. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  126401. 10,11,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  126402. 11,10,10,11,10,10, 7,11,11,12,11,11,12,11,11, 6,
  126403. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  126404. 10,
  126405. };
  126406. static float _vq_quantthresh__44c4_s_p7_0[] = {
  126407. -5.5, 5.5,
  126408. };
  126409. static long _vq_quantmap__44c4_s_p7_0[] = {
  126410. 1, 0, 2,
  126411. };
  126412. static encode_aux_threshmatch _vq_auxt__44c4_s_p7_0 = {
  126413. _vq_quantthresh__44c4_s_p7_0,
  126414. _vq_quantmap__44c4_s_p7_0,
  126415. 3,
  126416. 3
  126417. };
  126418. static static_codebook _44c4_s_p7_0 = {
  126419. 4, 81,
  126420. _vq_lengthlist__44c4_s_p7_0,
  126421. 1, -529137664, 1618345984, 2, 0,
  126422. _vq_quantlist__44c4_s_p7_0,
  126423. NULL,
  126424. &_vq_auxt__44c4_s_p7_0,
  126425. NULL,
  126426. 0
  126427. };
  126428. static long _vq_quantlist__44c4_s_p7_1[] = {
  126429. 5,
  126430. 4,
  126431. 6,
  126432. 3,
  126433. 7,
  126434. 2,
  126435. 8,
  126436. 1,
  126437. 9,
  126438. 0,
  126439. 10,
  126440. };
  126441. static long _vq_lengthlist__44c4_s_p7_1[] = {
  126442. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  126443. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  126444. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  126445. 7, 8, 8, 8, 8, 8, 8,10,10,10, 8, 7, 8, 8, 8, 8,
  126446. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  126447. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  126448. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 9, 8,10,10,
  126449. 10,10,10, 8, 8, 8, 8, 9, 9,
  126450. };
  126451. static float _vq_quantthresh__44c4_s_p7_1[] = {
  126452. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  126453. 3.5, 4.5,
  126454. };
  126455. static long _vq_quantmap__44c4_s_p7_1[] = {
  126456. 9, 7, 5, 3, 1, 0, 2, 4,
  126457. 6, 8, 10,
  126458. };
  126459. static encode_aux_threshmatch _vq_auxt__44c4_s_p7_1 = {
  126460. _vq_quantthresh__44c4_s_p7_1,
  126461. _vq_quantmap__44c4_s_p7_1,
  126462. 11,
  126463. 11
  126464. };
  126465. static static_codebook _44c4_s_p7_1 = {
  126466. 2, 121,
  126467. _vq_lengthlist__44c4_s_p7_1,
  126468. 1, -531365888, 1611661312, 4, 0,
  126469. _vq_quantlist__44c4_s_p7_1,
  126470. NULL,
  126471. &_vq_auxt__44c4_s_p7_1,
  126472. NULL,
  126473. 0
  126474. };
  126475. static long _vq_quantlist__44c4_s_p8_0[] = {
  126476. 6,
  126477. 5,
  126478. 7,
  126479. 4,
  126480. 8,
  126481. 3,
  126482. 9,
  126483. 2,
  126484. 10,
  126485. 1,
  126486. 11,
  126487. 0,
  126488. 12,
  126489. };
  126490. static long _vq_lengthlist__44c4_s_p8_0[] = {
  126491. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  126492. 7, 7, 8, 8, 8, 8, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  126493. 8, 9, 9,10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  126494. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  126495. 11, 0,12,12, 9, 9, 9, 9,10,10,10,10,11,11, 0,13,
  126496. 13, 9, 9,10, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  126497. 10,10,10,10,11,11,12,12, 0, 0, 0,10,10,10,10,10,
  126498. 10,11,11,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  126499. 12,12, 0, 0, 0,14,14,11,11,11,11,12,12,12,13, 0,
  126500. 0, 0, 0, 0,12,12,12,12,12,12,13,13, 0, 0, 0, 0,
  126501. 0,13,12,12,12,12,12,13,13,
  126502. };
  126503. static float _vq_quantthresh__44c4_s_p8_0[] = {
  126504. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  126505. 12.5, 17.5, 22.5, 27.5,
  126506. };
  126507. static long _vq_quantmap__44c4_s_p8_0[] = {
  126508. 11, 9, 7, 5, 3, 1, 0, 2,
  126509. 4, 6, 8, 10, 12,
  126510. };
  126511. static encode_aux_threshmatch _vq_auxt__44c4_s_p8_0 = {
  126512. _vq_quantthresh__44c4_s_p8_0,
  126513. _vq_quantmap__44c4_s_p8_0,
  126514. 13,
  126515. 13
  126516. };
  126517. static static_codebook _44c4_s_p8_0 = {
  126518. 2, 169,
  126519. _vq_lengthlist__44c4_s_p8_0,
  126520. 1, -526516224, 1616117760, 4, 0,
  126521. _vq_quantlist__44c4_s_p8_0,
  126522. NULL,
  126523. &_vq_auxt__44c4_s_p8_0,
  126524. NULL,
  126525. 0
  126526. };
  126527. static long _vq_quantlist__44c4_s_p8_1[] = {
  126528. 2,
  126529. 1,
  126530. 3,
  126531. 0,
  126532. 4,
  126533. };
  126534. static long _vq_lengthlist__44c4_s_p8_1[] = {
  126535. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 5, 4, 5, 5, 6,
  126536. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  126537. };
  126538. static float _vq_quantthresh__44c4_s_p8_1[] = {
  126539. -1.5, -0.5, 0.5, 1.5,
  126540. };
  126541. static long _vq_quantmap__44c4_s_p8_1[] = {
  126542. 3, 1, 0, 2, 4,
  126543. };
  126544. static encode_aux_threshmatch _vq_auxt__44c4_s_p8_1 = {
  126545. _vq_quantthresh__44c4_s_p8_1,
  126546. _vq_quantmap__44c4_s_p8_1,
  126547. 5,
  126548. 5
  126549. };
  126550. static static_codebook _44c4_s_p8_1 = {
  126551. 2, 25,
  126552. _vq_lengthlist__44c4_s_p8_1,
  126553. 1, -533725184, 1611661312, 3, 0,
  126554. _vq_quantlist__44c4_s_p8_1,
  126555. NULL,
  126556. &_vq_auxt__44c4_s_p8_1,
  126557. NULL,
  126558. 0
  126559. };
  126560. static long _vq_quantlist__44c4_s_p9_0[] = {
  126561. 6,
  126562. 5,
  126563. 7,
  126564. 4,
  126565. 8,
  126566. 3,
  126567. 9,
  126568. 2,
  126569. 10,
  126570. 1,
  126571. 11,
  126572. 0,
  126573. 12,
  126574. };
  126575. static long _vq_lengthlist__44c4_s_p9_0[] = {
  126576. 1, 3, 3,12,12,12,12,12,12,12,12,12,12, 4, 7, 7,
  126577. 12,12,12,12,12,12,12,12,12,12, 3, 8, 8,12,12,12,
  126578. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  126579. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  126580. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  126581. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  126582. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  126583. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  126584. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  126585. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  126586. 12,12,12,12,12,12,12,12,12,
  126587. };
  126588. static float _vq_quantthresh__44c4_s_p9_0[] = {
  126589. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  126590. 787.5, 1102.5, 1417.5, 1732.5,
  126591. };
  126592. static long _vq_quantmap__44c4_s_p9_0[] = {
  126593. 11, 9, 7, 5, 3, 1, 0, 2,
  126594. 4, 6, 8, 10, 12,
  126595. };
  126596. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_0 = {
  126597. _vq_quantthresh__44c4_s_p9_0,
  126598. _vq_quantmap__44c4_s_p9_0,
  126599. 13,
  126600. 13
  126601. };
  126602. static static_codebook _44c4_s_p9_0 = {
  126603. 2, 169,
  126604. _vq_lengthlist__44c4_s_p9_0,
  126605. 1, -513964032, 1628680192, 4, 0,
  126606. _vq_quantlist__44c4_s_p9_0,
  126607. NULL,
  126608. &_vq_auxt__44c4_s_p9_0,
  126609. NULL,
  126610. 0
  126611. };
  126612. static long _vq_quantlist__44c4_s_p9_1[] = {
  126613. 7,
  126614. 6,
  126615. 8,
  126616. 5,
  126617. 9,
  126618. 4,
  126619. 10,
  126620. 3,
  126621. 11,
  126622. 2,
  126623. 12,
  126624. 1,
  126625. 13,
  126626. 0,
  126627. 14,
  126628. };
  126629. static long _vq_lengthlist__44c4_s_p9_1[] = {
  126630. 1, 4, 4, 5, 5, 7, 7, 9, 8,10, 9,10,10,10,10, 6,
  126631. 5, 5, 7, 7, 9, 8,10, 9,11,10,12,12,13,13, 6, 5,
  126632. 5, 7, 7, 9, 9,10,10,11,11,12,12,12,13,19, 8, 8,
  126633. 8, 8, 9, 9,10,10,12,11,12,12,13,13,19, 8, 8, 8,
  126634. 8, 9, 9,11,11,12,12,13,13,13,13,19,12,12, 9, 9,
  126635. 11,11,11,11,12,11,13,12,13,13,18,12,12, 9, 9,11,
  126636. 10,11,11,12,12,12,13,13,14,19,18,18,11,11,11,11,
  126637. 12,12,13,12,13,13,14,14,16,18,18,11,11,11,10,12,
  126638. 11,13,13,13,13,13,14,17,18,18,14,15,11,12,12,13,
  126639. 13,13,13,14,14,14,18,18,18,15,15,12,10,13,10,13,
  126640. 13,13,13,13,14,18,17,18,17,18,12,13,12,13,13,13,
  126641. 14,14,16,14,18,17,18,18,17,13,12,13,10,12,12,14,
  126642. 14,14,14,17,18,18,18,18,14,15,12,12,13,12,14,14,
  126643. 15,15,18,18,18,17,18,15,14,12,11,12,12,14,14,14,
  126644. 15,
  126645. };
  126646. static float _vq_quantthresh__44c4_s_p9_1[] = {
  126647. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  126648. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  126649. };
  126650. static long _vq_quantmap__44c4_s_p9_1[] = {
  126651. 13, 11, 9, 7, 5, 3, 1, 0,
  126652. 2, 4, 6, 8, 10, 12, 14,
  126653. };
  126654. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_1 = {
  126655. _vq_quantthresh__44c4_s_p9_1,
  126656. _vq_quantmap__44c4_s_p9_1,
  126657. 15,
  126658. 15
  126659. };
  126660. static static_codebook _44c4_s_p9_1 = {
  126661. 2, 225,
  126662. _vq_lengthlist__44c4_s_p9_1,
  126663. 1, -520986624, 1620377600, 4, 0,
  126664. _vq_quantlist__44c4_s_p9_1,
  126665. NULL,
  126666. &_vq_auxt__44c4_s_p9_1,
  126667. NULL,
  126668. 0
  126669. };
  126670. static long _vq_quantlist__44c4_s_p9_2[] = {
  126671. 10,
  126672. 9,
  126673. 11,
  126674. 8,
  126675. 12,
  126676. 7,
  126677. 13,
  126678. 6,
  126679. 14,
  126680. 5,
  126681. 15,
  126682. 4,
  126683. 16,
  126684. 3,
  126685. 17,
  126686. 2,
  126687. 18,
  126688. 1,
  126689. 19,
  126690. 0,
  126691. 20,
  126692. };
  126693. static long _vq_lengthlist__44c4_s_p9_2[] = {
  126694. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  126695. 8, 9, 9, 9, 9,11, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  126696. 9, 9, 9, 9, 9, 9,10,10,10,10,11, 6, 6, 7, 7, 8,
  126697. 8, 8, 8, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,11,
  126698. 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  126699. 10,10,10,10,12,11,11, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  126700. 9,10,10,10,10,10,10,10,10,12,11,12, 8, 8, 8, 8,
  126701. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,11,
  126702. 11, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,10,10,10,10,
  126703. 10,10,10,11,11,12, 9, 9, 9, 9, 9, 9,10, 9,10,10,
  126704. 10,10,10,10,10,10,10,10,11,11,11,11,11, 9, 9, 9,
  126705. 9,10,10,10,10,10,10,10,10,10,10,10,10,11,12,11,
  126706. 11,11, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  126707. 10,10,11,11,11,11,11, 9, 9, 9, 9,10,10,10,10,10,
  126708. 10,10,10,10,10,10,10,11,11,11,12,12,10,10,10,10,
  126709. 10,10,10,10,10,10,10,10,10,10,10,10,11,12,11,12,
  126710. 11,11,11, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  126711. 10,11,12,11,11,11,11,11,10,10,10,10,10,10,10,10,
  126712. 10,10,10,10,10,10,11,11,11,12,11,11,11,10,10,10,
  126713. 10,10,10,10,10,10,10,10,10,10,10,12,11,11,12,11,
  126714. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  126715. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  126716. 10,10,10,10,10,11,11,11,11,12,12,11,11,11,11,11,
  126717. 11,11,10,10,10,10,10,10,10,10,12,12,12,11,11,11,
  126718. 12,11,11,11,10,10,10,10,10,10,10,10,10,10,10,12,
  126719. 11,12,12,12,12,12,11,12,11,11,10,10,10,10,10,10,
  126720. 10,10,10,10,12,12,12,12,11,11,11,11,11,11,11,10,
  126721. 10,10,10,10,10,10,10,10,10,
  126722. };
  126723. static float _vq_quantthresh__44c4_s_p9_2[] = {
  126724. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  126725. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  126726. 6.5, 7.5, 8.5, 9.5,
  126727. };
  126728. static long _vq_quantmap__44c4_s_p9_2[] = {
  126729. 19, 17, 15, 13, 11, 9, 7, 5,
  126730. 3, 1, 0, 2, 4, 6, 8, 10,
  126731. 12, 14, 16, 18, 20,
  126732. };
  126733. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_2 = {
  126734. _vq_quantthresh__44c4_s_p9_2,
  126735. _vq_quantmap__44c4_s_p9_2,
  126736. 21,
  126737. 21
  126738. };
  126739. static static_codebook _44c4_s_p9_2 = {
  126740. 2, 441,
  126741. _vq_lengthlist__44c4_s_p9_2,
  126742. 1, -529268736, 1611661312, 5, 0,
  126743. _vq_quantlist__44c4_s_p9_2,
  126744. NULL,
  126745. &_vq_auxt__44c4_s_p9_2,
  126746. NULL,
  126747. 0
  126748. };
  126749. static long _huff_lengthlist__44c4_s_short[] = {
  126750. 4, 7,14,10,15,10,12,15,16,15, 4, 2,11, 5,10, 6,
  126751. 8,11,14,14,14,10, 7,11, 6, 8,10,11,13,15, 9, 4,
  126752. 11, 5, 9, 6, 9,12,14,15,14, 9, 6, 9, 4, 5, 7,10,
  126753. 12,13, 9, 5, 7, 6, 5, 5, 7,10,13,13,10, 8, 9, 8,
  126754. 7, 6, 8,10,14,14,13,11,10,10, 7, 7, 8,11,14,15,
  126755. 13,12, 9, 9, 6, 5, 7,10,14,17,15,13,11,10, 6, 6,
  126756. 7, 9,12,17,
  126757. };
  126758. static static_codebook _huff_book__44c4_s_short = {
  126759. 2, 100,
  126760. _huff_lengthlist__44c4_s_short,
  126761. 0, 0, 0, 0, 0,
  126762. NULL,
  126763. NULL,
  126764. NULL,
  126765. NULL,
  126766. 0
  126767. };
  126768. static long _huff_lengthlist__44c5_s_long[] = {
  126769. 3, 8, 9,13,10,12,12,12,12,12, 6, 4, 6, 8, 6, 8,
  126770. 10,10,11,12, 8, 5, 4,10, 4, 7, 8, 9,10,11,13, 8,
  126771. 10, 8, 9, 9,11,12,13,14,10, 6, 4, 9, 3, 5, 6, 8,
  126772. 10,11,11, 8, 6, 9, 5, 5, 6, 7, 9,11,12, 9, 7,11,
  126773. 6, 6, 6, 7, 8,10,12,11, 9,12, 7, 7, 6, 6, 7, 9,
  126774. 13,12,10,13, 9, 8, 7, 7, 7, 8,11,15,11,15,11,10,
  126775. 9, 8, 7, 7,
  126776. };
  126777. static static_codebook _huff_book__44c5_s_long = {
  126778. 2, 100,
  126779. _huff_lengthlist__44c5_s_long,
  126780. 0, 0, 0, 0, 0,
  126781. NULL,
  126782. NULL,
  126783. NULL,
  126784. NULL,
  126785. 0
  126786. };
  126787. static long _vq_quantlist__44c5_s_p1_0[] = {
  126788. 1,
  126789. 0,
  126790. 2,
  126791. };
  126792. static long _vq_lengthlist__44c5_s_p1_0[] = {
  126793. 2, 4, 4, 0, 0, 0, 0, 0, 0, 4, 7, 7, 0, 0, 0, 0,
  126794. 0, 0, 4, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126798. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  126799. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126803. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  126804. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 7, 7, 0, 0, 0, 0,
  126839. 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  126840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  126844. 0, 0, 0, 9,10,11, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  126845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  126849. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  126850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126884. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  126885. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126889. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  126890. 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  126891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126894. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  126895. 0, 0, 0, 0, 0, 0, 9,11,10, 0, 0, 0, 0, 0, 0, 0,
  126896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127203. 0,
  127204. };
  127205. static float _vq_quantthresh__44c5_s_p1_0[] = {
  127206. -0.5, 0.5,
  127207. };
  127208. static long _vq_quantmap__44c5_s_p1_0[] = {
  127209. 1, 0, 2,
  127210. };
  127211. static encode_aux_threshmatch _vq_auxt__44c5_s_p1_0 = {
  127212. _vq_quantthresh__44c5_s_p1_0,
  127213. _vq_quantmap__44c5_s_p1_0,
  127214. 3,
  127215. 3
  127216. };
  127217. static static_codebook _44c5_s_p1_0 = {
  127218. 8, 6561,
  127219. _vq_lengthlist__44c5_s_p1_0,
  127220. 1, -535822336, 1611661312, 2, 0,
  127221. _vq_quantlist__44c5_s_p1_0,
  127222. NULL,
  127223. &_vq_auxt__44c5_s_p1_0,
  127224. NULL,
  127225. 0
  127226. };
  127227. static long _vq_quantlist__44c5_s_p2_0[] = {
  127228. 2,
  127229. 1,
  127230. 3,
  127231. 0,
  127232. 4,
  127233. };
  127234. static long _vq_lengthlist__44c5_s_p2_0[] = {
  127235. 2, 4, 4, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  127236. 8, 7, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 0, 0, 0, 8,
  127237. 8, 0, 0, 0, 8, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  127238. 0, 0, 4, 6, 6, 0, 0, 0, 8, 8, 0, 0, 0, 7, 8, 0,
  127239. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127244. 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 8, 8, 0, 0,
  127245. 0, 8, 8, 0, 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 5,
  127246. 7, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0,10,
  127247. 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127252. 0, 0, 0, 5, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8,
  127253. 0, 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0,
  127254. 0, 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0,10,10, 0, 0,
  127255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127260. 8,10,10, 0, 0, 0,10,10, 0, 0, 0, 9,10, 0, 0, 0,
  127261. 11,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0,10,
  127262. 10, 0, 0, 0,10,10, 0, 0, 0,10,11, 0, 0, 0, 0, 0,
  127263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127274. 0,
  127275. };
  127276. static float _vq_quantthresh__44c5_s_p2_0[] = {
  127277. -1.5, -0.5, 0.5, 1.5,
  127278. };
  127279. static long _vq_quantmap__44c5_s_p2_0[] = {
  127280. 3, 1, 0, 2, 4,
  127281. };
  127282. static encode_aux_threshmatch _vq_auxt__44c5_s_p2_0 = {
  127283. _vq_quantthresh__44c5_s_p2_0,
  127284. _vq_quantmap__44c5_s_p2_0,
  127285. 5,
  127286. 5
  127287. };
  127288. static static_codebook _44c5_s_p2_0 = {
  127289. 4, 625,
  127290. _vq_lengthlist__44c5_s_p2_0,
  127291. 1, -533725184, 1611661312, 3, 0,
  127292. _vq_quantlist__44c5_s_p2_0,
  127293. NULL,
  127294. &_vq_auxt__44c5_s_p2_0,
  127295. NULL,
  127296. 0
  127297. };
  127298. static long _vq_quantlist__44c5_s_p3_0[] = {
  127299. 2,
  127300. 1,
  127301. 3,
  127302. 0,
  127303. 4,
  127304. };
  127305. static long _vq_lengthlist__44c5_s_p3_0[] = {
  127306. 2, 4, 3, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 6, 6, 0, 0,
  127308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127309. 0, 0, 3, 5, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 8, 8,
  127311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127312. 0, 0, 0, 0, 5, 6, 6, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  127313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127345. 0,
  127346. };
  127347. static float _vq_quantthresh__44c5_s_p3_0[] = {
  127348. -1.5, -0.5, 0.5, 1.5,
  127349. };
  127350. static long _vq_quantmap__44c5_s_p3_0[] = {
  127351. 3, 1, 0, 2, 4,
  127352. };
  127353. static encode_aux_threshmatch _vq_auxt__44c5_s_p3_0 = {
  127354. _vq_quantthresh__44c5_s_p3_0,
  127355. _vq_quantmap__44c5_s_p3_0,
  127356. 5,
  127357. 5
  127358. };
  127359. static static_codebook _44c5_s_p3_0 = {
  127360. 4, 625,
  127361. _vq_lengthlist__44c5_s_p3_0,
  127362. 1, -533725184, 1611661312, 3, 0,
  127363. _vq_quantlist__44c5_s_p3_0,
  127364. NULL,
  127365. &_vq_auxt__44c5_s_p3_0,
  127366. NULL,
  127367. 0
  127368. };
  127369. static long _vq_quantlist__44c5_s_p4_0[] = {
  127370. 4,
  127371. 3,
  127372. 5,
  127373. 2,
  127374. 6,
  127375. 1,
  127376. 7,
  127377. 0,
  127378. 8,
  127379. };
  127380. static long _vq_lengthlist__44c5_s_p4_0[] = {
  127381. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  127382. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  127383. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  127384. 7, 7, 0, 0, 0, 0, 0, 0, 0, 8, 7, 0, 0, 0, 0, 0,
  127385. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127386. 0,
  127387. };
  127388. static float _vq_quantthresh__44c5_s_p4_0[] = {
  127389. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  127390. };
  127391. static long _vq_quantmap__44c5_s_p4_0[] = {
  127392. 7, 5, 3, 1, 0, 2, 4, 6,
  127393. 8,
  127394. };
  127395. static encode_aux_threshmatch _vq_auxt__44c5_s_p4_0 = {
  127396. _vq_quantthresh__44c5_s_p4_0,
  127397. _vq_quantmap__44c5_s_p4_0,
  127398. 9,
  127399. 9
  127400. };
  127401. static static_codebook _44c5_s_p4_0 = {
  127402. 2, 81,
  127403. _vq_lengthlist__44c5_s_p4_0,
  127404. 1, -531628032, 1611661312, 4, 0,
  127405. _vq_quantlist__44c5_s_p4_0,
  127406. NULL,
  127407. &_vq_auxt__44c5_s_p4_0,
  127408. NULL,
  127409. 0
  127410. };
  127411. static long _vq_quantlist__44c5_s_p5_0[] = {
  127412. 4,
  127413. 3,
  127414. 5,
  127415. 2,
  127416. 6,
  127417. 1,
  127418. 7,
  127419. 0,
  127420. 8,
  127421. };
  127422. static long _vq_lengthlist__44c5_s_p5_0[] = {
  127423. 2, 4, 3, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  127424. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7,
  127425. 7, 7, 9, 9, 0, 0, 0, 7, 6, 7, 7, 9, 9, 0, 0, 0,
  127426. 8, 8, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  127427. 0, 0, 9, 9, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  127428. 10,
  127429. };
  127430. static float _vq_quantthresh__44c5_s_p5_0[] = {
  127431. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  127432. };
  127433. static long _vq_quantmap__44c5_s_p5_0[] = {
  127434. 7, 5, 3, 1, 0, 2, 4, 6,
  127435. 8,
  127436. };
  127437. static encode_aux_threshmatch _vq_auxt__44c5_s_p5_0 = {
  127438. _vq_quantthresh__44c5_s_p5_0,
  127439. _vq_quantmap__44c5_s_p5_0,
  127440. 9,
  127441. 9
  127442. };
  127443. static static_codebook _44c5_s_p5_0 = {
  127444. 2, 81,
  127445. _vq_lengthlist__44c5_s_p5_0,
  127446. 1, -531628032, 1611661312, 4, 0,
  127447. _vq_quantlist__44c5_s_p5_0,
  127448. NULL,
  127449. &_vq_auxt__44c5_s_p5_0,
  127450. NULL,
  127451. 0
  127452. };
  127453. static long _vq_quantlist__44c5_s_p6_0[] = {
  127454. 8,
  127455. 7,
  127456. 9,
  127457. 6,
  127458. 10,
  127459. 5,
  127460. 11,
  127461. 4,
  127462. 12,
  127463. 3,
  127464. 13,
  127465. 2,
  127466. 14,
  127467. 1,
  127468. 15,
  127469. 0,
  127470. 16,
  127471. };
  127472. static long _vq_lengthlist__44c5_s_p6_0[] = {
  127473. 2, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,11,
  127474. 11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,
  127475. 12,12, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  127476. 11,12,12, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  127477. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  127478. 10,11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10,10,
  127479. 11,11,11,11,12,12, 0, 0, 0, 7, 7, 8, 9,10,10,10,
  127480. 10,11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,
  127481. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  127482. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  127483. 10,10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9,
  127484. 9, 9,10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0,
  127485. 10,10,10,10,11,11,11,12,12,12,13,13, 0, 0, 0, 0,
  127486. 0, 0, 0,10,10,11,11,11,11,12,12,13,13, 0, 0, 0,
  127487. 0, 0, 0, 0,11,11,11,11,12,12,12,13,13,13, 0, 0,
  127488. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  127489. 0, 0, 0, 0, 0, 0,12,12,12,12,13,12,13,13,13,13,
  127490. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,
  127491. 13,
  127492. };
  127493. static float _vq_quantthresh__44c5_s_p6_0[] = {
  127494. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  127495. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  127496. };
  127497. static long _vq_quantmap__44c5_s_p6_0[] = {
  127498. 15, 13, 11, 9, 7, 5, 3, 1,
  127499. 0, 2, 4, 6, 8, 10, 12, 14,
  127500. 16,
  127501. };
  127502. static encode_aux_threshmatch _vq_auxt__44c5_s_p6_0 = {
  127503. _vq_quantthresh__44c5_s_p6_0,
  127504. _vq_quantmap__44c5_s_p6_0,
  127505. 17,
  127506. 17
  127507. };
  127508. static static_codebook _44c5_s_p6_0 = {
  127509. 2, 289,
  127510. _vq_lengthlist__44c5_s_p6_0,
  127511. 1, -529530880, 1611661312, 5, 0,
  127512. _vq_quantlist__44c5_s_p6_0,
  127513. NULL,
  127514. &_vq_auxt__44c5_s_p6_0,
  127515. NULL,
  127516. 0
  127517. };
  127518. static long _vq_quantlist__44c5_s_p7_0[] = {
  127519. 1,
  127520. 0,
  127521. 2,
  127522. };
  127523. static long _vq_lengthlist__44c5_s_p7_0[] = {
  127524. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  127525. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  127526. 10,11,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  127527. 11,10,10,11,10,10, 7,11,11,12,11,11,12,11,11, 6,
  127528. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  127529. 10,
  127530. };
  127531. static float _vq_quantthresh__44c5_s_p7_0[] = {
  127532. -5.5, 5.5,
  127533. };
  127534. static long _vq_quantmap__44c5_s_p7_0[] = {
  127535. 1, 0, 2,
  127536. };
  127537. static encode_aux_threshmatch _vq_auxt__44c5_s_p7_0 = {
  127538. _vq_quantthresh__44c5_s_p7_0,
  127539. _vq_quantmap__44c5_s_p7_0,
  127540. 3,
  127541. 3
  127542. };
  127543. static static_codebook _44c5_s_p7_0 = {
  127544. 4, 81,
  127545. _vq_lengthlist__44c5_s_p7_0,
  127546. 1, -529137664, 1618345984, 2, 0,
  127547. _vq_quantlist__44c5_s_p7_0,
  127548. NULL,
  127549. &_vq_auxt__44c5_s_p7_0,
  127550. NULL,
  127551. 0
  127552. };
  127553. static long _vq_quantlist__44c5_s_p7_1[] = {
  127554. 5,
  127555. 4,
  127556. 6,
  127557. 3,
  127558. 7,
  127559. 2,
  127560. 8,
  127561. 1,
  127562. 9,
  127563. 0,
  127564. 10,
  127565. };
  127566. static long _vq_lengthlist__44c5_s_p7_1[] = {
  127567. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6,
  127568. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  127569. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  127570. 7, 8, 8, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  127571. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  127572. 8, 8, 8, 8, 8, 8, 8, 9,10,10,10,10,10, 8, 8, 8,
  127573. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  127574. 10,10,10, 8, 8, 8, 8, 8, 8,
  127575. };
  127576. static float _vq_quantthresh__44c5_s_p7_1[] = {
  127577. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  127578. 3.5, 4.5,
  127579. };
  127580. static long _vq_quantmap__44c5_s_p7_1[] = {
  127581. 9, 7, 5, 3, 1, 0, 2, 4,
  127582. 6, 8, 10,
  127583. };
  127584. static encode_aux_threshmatch _vq_auxt__44c5_s_p7_1 = {
  127585. _vq_quantthresh__44c5_s_p7_1,
  127586. _vq_quantmap__44c5_s_p7_1,
  127587. 11,
  127588. 11
  127589. };
  127590. static static_codebook _44c5_s_p7_1 = {
  127591. 2, 121,
  127592. _vq_lengthlist__44c5_s_p7_1,
  127593. 1, -531365888, 1611661312, 4, 0,
  127594. _vq_quantlist__44c5_s_p7_1,
  127595. NULL,
  127596. &_vq_auxt__44c5_s_p7_1,
  127597. NULL,
  127598. 0
  127599. };
  127600. static long _vq_quantlist__44c5_s_p8_0[] = {
  127601. 6,
  127602. 5,
  127603. 7,
  127604. 4,
  127605. 8,
  127606. 3,
  127607. 9,
  127608. 2,
  127609. 10,
  127610. 1,
  127611. 11,
  127612. 0,
  127613. 12,
  127614. };
  127615. static long _vq_lengthlist__44c5_s_p8_0[] = {
  127616. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  127617. 7, 7, 8, 8, 8, 9,10,10,10,10, 7, 5, 5, 7, 7, 8,
  127618. 8, 9, 9,10,10,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  127619. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  127620. 11, 0,12,12, 9, 9, 9,10,10,10,10,10,11,11, 0,13,
  127621. 13, 9, 9, 9, 9,10,10,11,11,11,11, 0, 0, 0,10,10,
  127622. 10,10,10,10,11,11,11,11, 0, 0, 0,10,10,10,10,10,
  127623. 10,11,11,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  127624. 12,12, 0, 0, 0,14,14,11,11,11,11,12,12,12,12, 0,
  127625. 0, 0, 0, 0,12,12,12,12,12,12,13,13, 0, 0, 0, 0,
  127626. 0,12,12,12,12,12,12,13,13,
  127627. };
  127628. static float _vq_quantthresh__44c5_s_p8_0[] = {
  127629. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  127630. 12.5, 17.5, 22.5, 27.5,
  127631. };
  127632. static long _vq_quantmap__44c5_s_p8_0[] = {
  127633. 11, 9, 7, 5, 3, 1, 0, 2,
  127634. 4, 6, 8, 10, 12,
  127635. };
  127636. static encode_aux_threshmatch _vq_auxt__44c5_s_p8_0 = {
  127637. _vq_quantthresh__44c5_s_p8_0,
  127638. _vq_quantmap__44c5_s_p8_0,
  127639. 13,
  127640. 13
  127641. };
  127642. static static_codebook _44c5_s_p8_0 = {
  127643. 2, 169,
  127644. _vq_lengthlist__44c5_s_p8_0,
  127645. 1, -526516224, 1616117760, 4, 0,
  127646. _vq_quantlist__44c5_s_p8_0,
  127647. NULL,
  127648. &_vq_auxt__44c5_s_p8_0,
  127649. NULL,
  127650. 0
  127651. };
  127652. static long _vq_quantlist__44c5_s_p8_1[] = {
  127653. 2,
  127654. 1,
  127655. 3,
  127656. 0,
  127657. 4,
  127658. };
  127659. static long _vq_lengthlist__44c5_s_p8_1[] = {
  127660. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 4, 5, 5, 5, 6,
  127661. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  127662. };
  127663. static float _vq_quantthresh__44c5_s_p8_1[] = {
  127664. -1.5, -0.5, 0.5, 1.5,
  127665. };
  127666. static long _vq_quantmap__44c5_s_p8_1[] = {
  127667. 3, 1, 0, 2, 4,
  127668. };
  127669. static encode_aux_threshmatch _vq_auxt__44c5_s_p8_1 = {
  127670. _vq_quantthresh__44c5_s_p8_1,
  127671. _vq_quantmap__44c5_s_p8_1,
  127672. 5,
  127673. 5
  127674. };
  127675. static static_codebook _44c5_s_p8_1 = {
  127676. 2, 25,
  127677. _vq_lengthlist__44c5_s_p8_1,
  127678. 1, -533725184, 1611661312, 3, 0,
  127679. _vq_quantlist__44c5_s_p8_1,
  127680. NULL,
  127681. &_vq_auxt__44c5_s_p8_1,
  127682. NULL,
  127683. 0
  127684. };
  127685. static long _vq_quantlist__44c5_s_p9_0[] = {
  127686. 7,
  127687. 6,
  127688. 8,
  127689. 5,
  127690. 9,
  127691. 4,
  127692. 10,
  127693. 3,
  127694. 11,
  127695. 2,
  127696. 12,
  127697. 1,
  127698. 13,
  127699. 0,
  127700. 14,
  127701. };
  127702. static long _vq_lengthlist__44c5_s_p9_0[] = {
  127703. 1, 3, 3,13,13,13,13,13,13,13,13,13,13,13,13, 4,
  127704. 7, 7,13,13,13,13,13,13,13,13,13,13,13,13, 3, 8,
  127705. 6,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  127706. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  127707. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  127708. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  127709. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  127710. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  127711. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  127712. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  127713. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  127714. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  127715. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  127716. 13,13,13,13,13,13,13,13,13,12,12,12,12,12,12,12,
  127717. 12,
  127718. };
  127719. static float _vq_quantthresh__44c5_s_p9_0[] = {
  127720. -2320.5, -1963.5, -1606.5, -1249.5, -892.5, -535.5, -178.5, 178.5,
  127721. 535.5, 892.5, 1249.5, 1606.5, 1963.5, 2320.5,
  127722. };
  127723. static long _vq_quantmap__44c5_s_p9_0[] = {
  127724. 13, 11, 9, 7, 5, 3, 1, 0,
  127725. 2, 4, 6, 8, 10, 12, 14,
  127726. };
  127727. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_0 = {
  127728. _vq_quantthresh__44c5_s_p9_0,
  127729. _vq_quantmap__44c5_s_p9_0,
  127730. 15,
  127731. 15
  127732. };
  127733. static static_codebook _44c5_s_p9_0 = {
  127734. 2, 225,
  127735. _vq_lengthlist__44c5_s_p9_0,
  127736. 1, -512522752, 1628852224, 4, 0,
  127737. _vq_quantlist__44c5_s_p9_0,
  127738. NULL,
  127739. &_vq_auxt__44c5_s_p9_0,
  127740. NULL,
  127741. 0
  127742. };
  127743. static long _vq_quantlist__44c5_s_p9_1[] = {
  127744. 8,
  127745. 7,
  127746. 9,
  127747. 6,
  127748. 10,
  127749. 5,
  127750. 11,
  127751. 4,
  127752. 12,
  127753. 3,
  127754. 13,
  127755. 2,
  127756. 14,
  127757. 1,
  127758. 15,
  127759. 0,
  127760. 16,
  127761. };
  127762. static long _vq_lengthlist__44c5_s_p9_1[] = {
  127763. 1, 4, 4, 5, 5, 7, 7, 9, 8,10, 9,10,10,11,10,11,
  127764. 11, 6, 5, 5, 7, 7, 8, 9,10,10,11,10,12,11,12,11,
  127765. 13,12, 6, 5, 5, 7, 7, 9, 9,10,10,11,11,12,12,13,
  127766. 12,13,13,18, 8, 8, 8, 8, 9, 9,10,11,11,11,12,11,
  127767. 13,11,13,12,18, 8, 8, 8, 8,10,10,11,11,12,12,13,
  127768. 13,13,13,13,14,18,12,12, 9, 9,11,11,11,11,12,12,
  127769. 13,12,13,12,13,13,20,13,12, 9, 9,11,11,11,11,12,
  127770. 12,13,13,13,14,14,13,20,18,19,11,12,11,11,12,12,
  127771. 13,13,13,13,13,13,14,13,18,19,19,12,11,11,11,12,
  127772. 12,13,12,13,13,13,14,14,13,18,17,19,14,15,12,12,
  127773. 12,13,13,13,14,14,14,14,14,14,19,19,19,16,15,12,
  127774. 11,13,12,14,14,14,13,13,14,14,14,19,18,19,18,19,
  127775. 13,13,13,13,14,14,14,13,14,14,14,14,18,17,19,19,
  127776. 19,13,13,13,11,13,11,13,14,14,14,14,14,19,17,17,
  127777. 18,18,16,16,13,13,13,13,14,13,15,15,14,14,19,19,
  127778. 17,17,18,16,16,13,11,14,10,13,12,14,14,14,14,19,
  127779. 19,19,19,19,18,17,13,14,13,11,14,13,14,14,15,15,
  127780. 19,19,19,17,19,18,18,14,13,12,11,14,11,15,15,15,
  127781. 15,
  127782. };
  127783. static float _vq_quantthresh__44c5_s_p9_1[] = {
  127784. -157.5, -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5,
  127785. 10.5, 31.5, 52.5, 73.5, 94.5, 115.5, 136.5, 157.5,
  127786. };
  127787. static long _vq_quantmap__44c5_s_p9_1[] = {
  127788. 15, 13, 11, 9, 7, 5, 3, 1,
  127789. 0, 2, 4, 6, 8, 10, 12, 14,
  127790. 16,
  127791. };
  127792. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_1 = {
  127793. _vq_quantthresh__44c5_s_p9_1,
  127794. _vq_quantmap__44c5_s_p9_1,
  127795. 17,
  127796. 17
  127797. };
  127798. static static_codebook _44c5_s_p9_1 = {
  127799. 2, 289,
  127800. _vq_lengthlist__44c5_s_p9_1,
  127801. 1, -520814592, 1620377600, 5, 0,
  127802. _vq_quantlist__44c5_s_p9_1,
  127803. NULL,
  127804. &_vq_auxt__44c5_s_p9_1,
  127805. NULL,
  127806. 0
  127807. };
  127808. static long _vq_quantlist__44c5_s_p9_2[] = {
  127809. 10,
  127810. 9,
  127811. 11,
  127812. 8,
  127813. 12,
  127814. 7,
  127815. 13,
  127816. 6,
  127817. 14,
  127818. 5,
  127819. 15,
  127820. 4,
  127821. 16,
  127822. 3,
  127823. 17,
  127824. 2,
  127825. 18,
  127826. 1,
  127827. 19,
  127828. 0,
  127829. 20,
  127830. };
  127831. static long _vq_lengthlist__44c5_s_p9_2[] = {
  127832. 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  127833. 8, 8, 8, 8, 9,11, 5, 6, 7, 7, 8, 7, 8, 8, 8, 8,
  127834. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11, 5, 5, 7, 7, 7,
  127835. 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  127836. 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  127837. 9,10, 9,10,11,11,11, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  127838. 9, 9, 9,10,10,10,10,10,10,11,11,11, 8, 8, 8, 8,
  127839. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,11,11,
  127840. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,
  127841. 10,10,10,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  127842. 10,10,10,10,10,10,10,10,11,11,11,11,11, 9, 9, 9,
  127843. 9, 9, 9,10, 9,10,10,10,10,10,10,10,10,11,11,11,
  127844. 11,11, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,
  127845. 10,10,11,11,11,11,11, 9, 9, 9, 9, 9, 9,10,10,10,
  127846. 10,10,10,10,10,10,10,11,11,11,11,11, 9, 9,10, 9,
  127847. 10,10,10,10,10,10,10,10,10,10,10,10,11,11,11,11,
  127848. 11,11,11, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  127849. 10,11,11,11,11,11,11,11,10,10,10,10,10,10,10,10,
  127850. 10,10,10,10,10,10,11,11,11,11,11,11,11,10,10,10,
  127851. 10,10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,
  127852. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127853. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  127854. 10,10,10,10,10,11,11,11,11,11,11,11,11,11,10,10,
  127855. 10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  127856. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,11,
  127857. 11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,10,
  127858. 10,10,10,10,11,11,11,11,11,11,11,11,11,11,11,10,
  127859. 10,10,10,10,10,10,10,10,10,
  127860. };
  127861. static float _vq_quantthresh__44c5_s_p9_2[] = {
  127862. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  127863. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  127864. 6.5, 7.5, 8.5, 9.5,
  127865. };
  127866. static long _vq_quantmap__44c5_s_p9_2[] = {
  127867. 19, 17, 15, 13, 11, 9, 7, 5,
  127868. 3, 1, 0, 2, 4, 6, 8, 10,
  127869. 12, 14, 16, 18, 20,
  127870. };
  127871. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_2 = {
  127872. _vq_quantthresh__44c5_s_p9_2,
  127873. _vq_quantmap__44c5_s_p9_2,
  127874. 21,
  127875. 21
  127876. };
  127877. static static_codebook _44c5_s_p9_2 = {
  127878. 2, 441,
  127879. _vq_lengthlist__44c5_s_p9_2,
  127880. 1, -529268736, 1611661312, 5, 0,
  127881. _vq_quantlist__44c5_s_p9_2,
  127882. NULL,
  127883. &_vq_auxt__44c5_s_p9_2,
  127884. NULL,
  127885. 0
  127886. };
  127887. static long _huff_lengthlist__44c5_s_short[] = {
  127888. 5, 8,10,14,11,11,12,16,15,17, 5, 5, 7, 9, 7, 8,
  127889. 10,13,17,17, 7, 5, 5,10, 5, 7, 8,11,13,15,10, 8,
  127890. 10, 8, 8, 8,11,15,18,18, 8, 5, 5, 8, 3, 4, 6,10,
  127891. 14,16, 9, 7, 6, 7, 4, 3, 5, 9,14,18,10, 9, 8,10,
  127892. 6, 5, 6, 9,14,18,12,12,11,12, 8, 7, 8,11,14,18,
  127893. 14,13,12,10, 7, 5, 6, 9,14,18,14,14,13,10, 6, 5,
  127894. 6, 8,11,16,
  127895. };
  127896. static static_codebook _huff_book__44c5_s_short = {
  127897. 2, 100,
  127898. _huff_lengthlist__44c5_s_short,
  127899. 0, 0, 0, 0, 0,
  127900. NULL,
  127901. NULL,
  127902. NULL,
  127903. NULL,
  127904. 0
  127905. };
  127906. static long _huff_lengthlist__44c6_s_long[] = {
  127907. 3, 8,11,13,14,14,13,13,16,14, 6, 3, 4, 7, 9, 9,
  127908. 10,11,14,13,10, 4, 3, 5, 7, 7, 9,10,13,15,12, 7,
  127909. 4, 4, 6, 6, 8,10,13,15,12, 8, 6, 6, 6, 6, 8,10,
  127910. 13,14,11, 9, 7, 6, 6, 6, 7, 8,12,11,13,10, 9, 8,
  127911. 7, 6, 6, 7,11,11,13,11,10, 9, 9, 7, 7, 6,10,11,
  127912. 13,13,13,13,13,11, 9, 8,10,12,12,15,15,16,15,12,
  127913. 11,10,10,12,
  127914. };
  127915. static static_codebook _huff_book__44c6_s_long = {
  127916. 2, 100,
  127917. _huff_lengthlist__44c6_s_long,
  127918. 0, 0, 0, 0, 0,
  127919. NULL,
  127920. NULL,
  127921. NULL,
  127922. NULL,
  127923. 0
  127924. };
  127925. static long _vq_quantlist__44c6_s_p1_0[] = {
  127926. 1,
  127927. 0,
  127928. 2,
  127929. };
  127930. static long _vq_lengthlist__44c6_s_p1_0[] = {
  127931. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 8, 7, 0, 9, 9, 0,
  127932. 9, 8, 5, 7, 8, 0, 9, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  127933. 0, 0, 0, 0, 5, 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  127934. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  127935. 9, 9, 0, 8, 8, 0, 8, 8, 5, 9, 9, 0, 8, 8, 0, 8,
  127936. 8,
  127937. };
  127938. static float _vq_quantthresh__44c6_s_p1_0[] = {
  127939. -0.5, 0.5,
  127940. };
  127941. static long _vq_quantmap__44c6_s_p1_0[] = {
  127942. 1, 0, 2,
  127943. };
  127944. static encode_aux_threshmatch _vq_auxt__44c6_s_p1_0 = {
  127945. _vq_quantthresh__44c6_s_p1_0,
  127946. _vq_quantmap__44c6_s_p1_0,
  127947. 3,
  127948. 3
  127949. };
  127950. static static_codebook _44c6_s_p1_0 = {
  127951. 4, 81,
  127952. _vq_lengthlist__44c6_s_p1_0,
  127953. 1, -535822336, 1611661312, 2, 0,
  127954. _vq_quantlist__44c6_s_p1_0,
  127955. NULL,
  127956. &_vq_auxt__44c6_s_p1_0,
  127957. NULL,
  127958. 0
  127959. };
  127960. static long _vq_quantlist__44c6_s_p2_0[] = {
  127961. 2,
  127962. 1,
  127963. 3,
  127964. 0,
  127965. 4,
  127966. };
  127967. static long _vq_lengthlist__44c6_s_p2_0[] = {
  127968. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  127969. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  127970. 8,10,10, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  127971. 11,11, 5, 7, 7, 9, 9, 0, 8, 8,10,10, 0, 7, 8, 9,
  127972. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,11,
  127973. 0,11,11,12,12, 0,11,10,12,12, 0,13,14,14,14, 0,
  127974. 0, 0,14,13, 8, 9, 9,11,11, 0,11,11,12,12, 0,10,
  127975. 11,12,12, 0,14,13,14,14, 0, 0, 0,13,14, 0, 0, 0,
  127976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127977. 0, 0, 0, 0, 0, 0, 5, 8, 7,11,10, 0, 7, 7,10,10,
  127978. 0, 7, 7,10,10, 0, 9, 9,11,10, 0, 0, 0,11,11, 5,
  127979. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  127980. 9,10,11, 0, 0, 0,11,11, 8,10, 9,12,12, 0,10,10,
  127981. 12,12, 0,10,10,12,12, 0,12,12,13,13, 0, 0, 0,13,
  127982. 13, 8, 9,10,12,12, 0,10,10,11,12, 0,10,10,12,12,
  127983. 0,12,12,13,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0,
  127984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127985. 0, 0, 0, 5, 8, 8,11,11, 0, 7, 7,10,10, 0, 7, 7,
  127986. 10,10, 0, 9, 9,10,11, 0, 0, 0,11,10, 5, 8, 8,11,
  127987. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,11,11,
  127988. 0, 0, 0,10,11, 8,10,10,12,12, 0,10,10,12,12, 0,
  127989. 10,10,12,12, 0,12,13,13,13, 0, 0, 0,14,13, 8,10,
  127990. 10,12,12, 0,10,10,12,12, 0,10,10,12,12, 0,13,12,
  127991. 13,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127993. 7,10,10,14,13, 0, 9, 9,13,12, 0, 9, 9,12,12, 0,
  127994. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,14, 0, 9,
  127995. 9,12,13, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  127996. 12,12, 9,11,11,14,13, 0,11,10,14,13, 0,11,11,13,
  127997. 13, 0,12,12,13,13, 0, 0, 0,13,13, 9,11,11,13,14,
  127998. 0,10,11,13,14, 0,11,11,13,13, 0,12,12,13,13, 0,
  127999. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  128004. 11,11,14,14, 0,11,11,13,13, 0,11,10,13,13, 0,12,
  128005. 12,13,13, 0, 0, 0,13,13, 9,11,11,14,14, 0,11,11,
  128006. 13,13, 0,10,11,13,13, 0,12,12,14,13, 0, 0, 0,13,
  128007. 13,
  128008. };
  128009. static float _vq_quantthresh__44c6_s_p2_0[] = {
  128010. -1.5, -0.5, 0.5, 1.5,
  128011. };
  128012. static long _vq_quantmap__44c6_s_p2_0[] = {
  128013. 3, 1, 0, 2, 4,
  128014. };
  128015. static encode_aux_threshmatch _vq_auxt__44c6_s_p2_0 = {
  128016. _vq_quantthresh__44c6_s_p2_0,
  128017. _vq_quantmap__44c6_s_p2_0,
  128018. 5,
  128019. 5
  128020. };
  128021. static static_codebook _44c6_s_p2_0 = {
  128022. 4, 625,
  128023. _vq_lengthlist__44c6_s_p2_0,
  128024. 1, -533725184, 1611661312, 3, 0,
  128025. _vq_quantlist__44c6_s_p2_0,
  128026. NULL,
  128027. &_vq_auxt__44c6_s_p2_0,
  128028. NULL,
  128029. 0
  128030. };
  128031. static long _vq_quantlist__44c6_s_p3_0[] = {
  128032. 4,
  128033. 3,
  128034. 5,
  128035. 2,
  128036. 6,
  128037. 1,
  128038. 7,
  128039. 0,
  128040. 8,
  128041. };
  128042. static long _vq_lengthlist__44c6_s_p3_0[] = {
  128043. 2, 3, 4, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  128044. 9,10, 0, 4, 4, 6, 6, 7, 7,10, 9, 0, 5, 5, 7, 7,
  128045. 8, 8,10,10, 0, 0, 0, 7, 6, 8, 8,10,10, 0, 0, 0,
  128046. 7, 7, 9, 9,11,11, 0, 0, 0, 7, 7, 9, 9,11,11, 0,
  128047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128048. 0,
  128049. };
  128050. static float _vq_quantthresh__44c6_s_p3_0[] = {
  128051. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  128052. };
  128053. static long _vq_quantmap__44c6_s_p3_0[] = {
  128054. 7, 5, 3, 1, 0, 2, 4, 6,
  128055. 8,
  128056. };
  128057. static encode_aux_threshmatch _vq_auxt__44c6_s_p3_0 = {
  128058. _vq_quantthresh__44c6_s_p3_0,
  128059. _vq_quantmap__44c6_s_p3_0,
  128060. 9,
  128061. 9
  128062. };
  128063. static static_codebook _44c6_s_p3_0 = {
  128064. 2, 81,
  128065. _vq_lengthlist__44c6_s_p3_0,
  128066. 1, -531628032, 1611661312, 4, 0,
  128067. _vq_quantlist__44c6_s_p3_0,
  128068. NULL,
  128069. &_vq_auxt__44c6_s_p3_0,
  128070. NULL,
  128071. 0
  128072. };
  128073. static long _vq_quantlist__44c6_s_p4_0[] = {
  128074. 8,
  128075. 7,
  128076. 9,
  128077. 6,
  128078. 10,
  128079. 5,
  128080. 11,
  128081. 4,
  128082. 12,
  128083. 3,
  128084. 13,
  128085. 2,
  128086. 14,
  128087. 1,
  128088. 15,
  128089. 0,
  128090. 16,
  128091. };
  128092. static long _vq_lengthlist__44c6_s_p4_0[] = {
  128093. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9,10,10,
  128094. 10, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,
  128095. 11,11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,
  128096. 10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  128097. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  128098. 10,11,11,11,11, 0, 0, 0, 7, 7, 9, 9,10,10,10,10,
  128099. 11,11,11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10,
  128100. 10,11,11,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  128101. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8, 8, 9,
  128102. 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 0, 0,
  128103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128111. 0,
  128112. };
  128113. static float _vq_quantthresh__44c6_s_p4_0[] = {
  128114. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  128115. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  128116. };
  128117. static long _vq_quantmap__44c6_s_p4_0[] = {
  128118. 15, 13, 11, 9, 7, 5, 3, 1,
  128119. 0, 2, 4, 6, 8, 10, 12, 14,
  128120. 16,
  128121. };
  128122. static encode_aux_threshmatch _vq_auxt__44c6_s_p4_0 = {
  128123. _vq_quantthresh__44c6_s_p4_0,
  128124. _vq_quantmap__44c6_s_p4_0,
  128125. 17,
  128126. 17
  128127. };
  128128. static static_codebook _44c6_s_p4_0 = {
  128129. 2, 289,
  128130. _vq_lengthlist__44c6_s_p4_0,
  128131. 1, -529530880, 1611661312, 5, 0,
  128132. _vq_quantlist__44c6_s_p4_0,
  128133. NULL,
  128134. &_vq_auxt__44c6_s_p4_0,
  128135. NULL,
  128136. 0
  128137. };
  128138. static long _vq_quantlist__44c6_s_p5_0[] = {
  128139. 1,
  128140. 0,
  128141. 2,
  128142. };
  128143. static long _vq_lengthlist__44c6_s_p5_0[] = {
  128144. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 6, 9, 9,10,10,
  128145. 10, 9, 4, 6, 6, 9,10, 9,10, 9,10, 6, 9, 9,10,12,
  128146. 11,10,11,11, 7,10, 9,11,12,12,12,12,12, 7,10,10,
  128147. 11,12,12,12,12,12, 6,10,10,10,12,12,11,12,12, 7,
  128148. 9,10,11,12,12,12,12,12, 7,10, 9,12,12,12,12,12,
  128149. 12,
  128150. };
  128151. static float _vq_quantthresh__44c6_s_p5_0[] = {
  128152. -5.5, 5.5,
  128153. };
  128154. static long _vq_quantmap__44c6_s_p5_0[] = {
  128155. 1, 0, 2,
  128156. };
  128157. static encode_aux_threshmatch _vq_auxt__44c6_s_p5_0 = {
  128158. _vq_quantthresh__44c6_s_p5_0,
  128159. _vq_quantmap__44c6_s_p5_0,
  128160. 3,
  128161. 3
  128162. };
  128163. static static_codebook _44c6_s_p5_0 = {
  128164. 4, 81,
  128165. _vq_lengthlist__44c6_s_p5_0,
  128166. 1, -529137664, 1618345984, 2, 0,
  128167. _vq_quantlist__44c6_s_p5_0,
  128168. NULL,
  128169. &_vq_auxt__44c6_s_p5_0,
  128170. NULL,
  128171. 0
  128172. };
  128173. static long _vq_quantlist__44c6_s_p5_1[] = {
  128174. 5,
  128175. 4,
  128176. 6,
  128177. 3,
  128178. 7,
  128179. 2,
  128180. 8,
  128181. 1,
  128182. 9,
  128183. 0,
  128184. 10,
  128185. };
  128186. static long _vq_lengthlist__44c6_s_p5_1[] = {
  128187. 3, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6,
  128188. 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6, 7, 7, 8, 8, 8,
  128189. 8,11, 6, 6, 6, 6, 8, 8, 8, 8, 9, 9,11,11,11, 6,
  128190. 6, 7, 8, 8, 8, 8, 9,11,11,11, 7, 7, 8, 8, 8, 8,
  128191. 8, 8,11,11,11, 7, 7, 8, 8, 8, 8, 8, 8,11,11,11,
  128192. 8, 8, 8, 8, 8, 8, 8, 8,11,11,11,10,10, 8, 8, 8,
  128193. 8, 8, 8,11,11,11,10,10, 8, 8, 8, 8, 8, 8,11,11,
  128194. 11,10,10, 7, 7, 8, 8, 8, 8,
  128195. };
  128196. static float _vq_quantthresh__44c6_s_p5_1[] = {
  128197. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  128198. 3.5, 4.5,
  128199. };
  128200. static long _vq_quantmap__44c6_s_p5_1[] = {
  128201. 9, 7, 5, 3, 1, 0, 2, 4,
  128202. 6, 8, 10,
  128203. };
  128204. static encode_aux_threshmatch _vq_auxt__44c6_s_p5_1 = {
  128205. _vq_quantthresh__44c6_s_p5_1,
  128206. _vq_quantmap__44c6_s_p5_1,
  128207. 11,
  128208. 11
  128209. };
  128210. static static_codebook _44c6_s_p5_1 = {
  128211. 2, 121,
  128212. _vq_lengthlist__44c6_s_p5_1,
  128213. 1, -531365888, 1611661312, 4, 0,
  128214. _vq_quantlist__44c6_s_p5_1,
  128215. NULL,
  128216. &_vq_auxt__44c6_s_p5_1,
  128217. NULL,
  128218. 0
  128219. };
  128220. static long _vq_quantlist__44c6_s_p6_0[] = {
  128221. 6,
  128222. 5,
  128223. 7,
  128224. 4,
  128225. 8,
  128226. 3,
  128227. 9,
  128228. 2,
  128229. 10,
  128230. 1,
  128231. 11,
  128232. 0,
  128233. 12,
  128234. };
  128235. static long _vq_lengthlist__44c6_s_p6_0[] = {
  128236. 1, 4, 4, 6, 6, 8, 8, 8, 8,10, 9,10,10, 6, 5, 5,
  128237. 7, 7, 9, 9, 9, 9,10,10,11,11, 6, 5, 5, 7, 7, 9,
  128238. 9,10, 9,11,10,11,11, 0, 6, 6, 7, 7, 9, 9,10,10,
  128239. 11,11,12,12, 0, 7, 7, 7, 7, 9, 9,10,10,11,11,12,
  128240. 12, 0,11,11, 8, 8,10,10,11,11,12,12,12,12, 0,11,
  128241. 12, 9, 8,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  128242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128246. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128247. };
  128248. static float _vq_quantthresh__44c6_s_p6_0[] = {
  128249. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  128250. 12.5, 17.5, 22.5, 27.5,
  128251. };
  128252. static long _vq_quantmap__44c6_s_p6_0[] = {
  128253. 11, 9, 7, 5, 3, 1, 0, 2,
  128254. 4, 6, 8, 10, 12,
  128255. };
  128256. static encode_aux_threshmatch _vq_auxt__44c6_s_p6_0 = {
  128257. _vq_quantthresh__44c6_s_p6_0,
  128258. _vq_quantmap__44c6_s_p6_0,
  128259. 13,
  128260. 13
  128261. };
  128262. static static_codebook _44c6_s_p6_0 = {
  128263. 2, 169,
  128264. _vq_lengthlist__44c6_s_p6_0,
  128265. 1, -526516224, 1616117760, 4, 0,
  128266. _vq_quantlist__44c6_s_p6_0,
  128267. NULL,
  128268. &_vq_auxt__44c6_s_p6_0,
  128269. NULL,
  128270. 0
  128271. };
  128272. static long _vq_quantlist__44c6_s_p6_1[] = {
  128273. 2,
  128274. 1,
  128275. 3,
  128276. 0,
  128277. 4,
  128278. };
  128279. static long _vq_lengthlist__44c6_s_p6_1[] = {
  128280. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  128281. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  128282. };
  128283. static float _vq_quantthresh__44c6_s_p6_1[] = {
  128284. -1.5, -0.5, 0.5, 1.5,
  128285. };
  128286. static long _vq_quantmap__44c6_s_p6_1[] = {
  128287. 3, 1, 0, 2, 4,
  128288. };
  128289. static encode_aux_threshmatch _vq_auxt__44c6_s_p6_1 = {
  128290. _vq_quantthresh__44c6_s_p6_1,
  128291. _vq_quantmap__44c6_s_p6_1,
  128292. 5,
  128293. 5
  128294. };
  128295. static static_codebook _44c6_s_p6_1 = {
  128296. 2, 25,
  128297. _vq_lengthlist__44c6_s_p6_1,
  128298. 1, -533725184, 1611661312, 3, 0,
  128299. _vq_quantlist__44c6_s_p6_1,
  128300. NULL,
  128301. &_vq_auxt__44c6_s_p6_1,
  128302. NULL,
  128303. 0
  128304. };
  128305. static long _vq_quantlist__44c6_s_p7_0[] = {
  128306. 6,
  128307. 5,
  128308. 7,
  128309. 4,
  128310. 8,
  128311. 3,
  128312. 9,
  128313. 2,
  128314. 10,
  128315. 1,
  128316. 11,
  128317. 0,
  128318. 12,
  128319. };
  128320. static long _vq_lengthlist__44c6_s_p7_0[] = {
  128321. 1, 4, 4, 6, 6, 8, 8, 8, 8,10,10,11,10, 6, 5, 5,
  128322. 7, 7, 8, 8, 9, 9,10,10,12,11, 6, 5, 5, 7, 7, 8,
  128323. 8, 9, 9,10,10,12,11,21, 7, 7, 7, 7, 9, 9,10,10,
  128324. 11,11,12,12,21, 7, 7, 7, 7, 9, 9,10,10,11,11,12,
  128325. 12,21,12,12, 9, 9,10,10,11,11,11,11,12,12,21,12,
  128326. 12, 9, 9,10,10,11,11,12,12,12,12,21,21,21,11,11,
  128327. 10,10,11,12,12,12,13,13,21,21,21,11,11,10,10,12,
  128328. 12,12,12,13,13,21,21,21,15,15,11,11,12,12,13,13,
  128329. 13,13,21,21,21,15,16,11,11,12,12,13,13,14,14,21,
  128330. 21,21,21,20,13,13,13,13,13,13,14,14,20,20,20,20,
  128331. 20,13,13,13,13,13,13,14,14,
  128332. };
  128333. static float _vq_quantthresh__44c6_s_p7_0[] = {
  128334. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  128335. 27.5, 38.5, 49.5, 60.5,
  128336. };
  128337. static long _vq_quantmap__44c6_s_p7_0[] = {
  128338. 11, 9, 7, 5, 3, 1, 0, 2,
  128339. 4, 6, 8, 10, 12,
  128340. };
  128341. static encode_aux_threshmatch _vq_auxt__44c6_s_p7_0 = {
  128342. _vq_quantthresh__44c6_s_p7_0,
  128343. _vq_quantmap__44c6_s_p7_0,
  128344. 13,
  128345. 13
  128346. };
  128347. static static_codebook _44c6_s_p7_0 = {
  128348. 2, 169,
  128349. _vq_lengthlist__44c6_s_p7_0,
  128350. 1, -523206656, 1618345984, 4, 0,
  128351. _vq_quantlist__44c6_s_p7_0,
  128352. NULL,
  128353. &_vq_auxt__44c6_s_p7_0,
  128354. NULL,
  128355. 0
  128356. };
  128357. static long _vq_quantlist__44c6_s_p7_1[] = {
  128358. 5,
  128359. 4,
  128360. 6,
  128361. 3,
  128362. 7,
  128363. 2,
  128364. 8,
  128365. 1,
  128366. 9,
  128367. 0,
  128368. 10,
  128369. };
  128370. static long _vq_lengthlist__44c6_s_p7_1[] = {
  128371. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 9, 5, 5, 6, 6,
  128372. 7, 7, 7, 7, 8, 7, 8, 5, 5, 6, 6, 7, 7, 7, 7, 7,
  128373. 7, 9, 6, 6, 7, 7, 7, 7, 8, 7, 7, 8, 9, 9, 9, 7,
  128374. 7, 7, 7, 7, 7, 7, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8,
  128375. 8, 8, 9, 9, 9, 7, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  128376. 8, 8, 8, 8, 7, 7, 8, 8, 9, 9, 9, 9, 8, 8, 8, 7,
  128377. 7, 8, 8, 9, 9, 9, 8, 8, 8, 8, 7, 7, 8, 8, 9, 9,
  128378. 9, 8, 8, 7, 7, 7, 7, 8, 8,
  128379. };
  128380. static float _vq_quantthresh__44c6_s_p7_1[] = {
  128381. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  128382. 3.5, 4.5,
  128383. };
  128384. static long _vq_quantmap__44c6_s_p7_1[] = {
  128385. 9, 7, 5, 3, 1, 0, 2, 4,
  128386. 6, 8, 10,
  128387. };
  128388. static encode_aux_threshmatch _vq_auxt__44c6_s_p7_1 = {
  128389. _vq_quantthresh__44c6_s_p7_1,
  128390. _vq_quantmap__44c6_s_p7_1,
  128391. 11,
  128392. 11
  128393. };
  128394. static static_codebook _44c6_s_p7_1 = {
  128395. 2, 121,
  128396. _vq_lengthlist__44c6_s_p7_1,
  128397. 1, -531365888, 1611661312, 4, 0,
  128398. _vq_quantlist__44c6_s_p7_1,
  128399. NULL,
  128400. &_vq_auxt__44c6_s_p7_1,
  128401. NULL,
  128402. 0
  128403. };
  128404. static long _vq_quantlist__44c6_s_p8_0[] = {
  128405. 7,
  128406. 6,
  128407. 8,
  128408. 5,
  128409. 9,
  128410. 4,
  128411. 10,
  128412. 3,
  128413. 11,
  128414. 2,
  128415. 12,
  128416. 1,
  128417. 13,
  128418. 0,
  128419. 14,
  128420. };
  128421. static long _vq_lengthlist__44c6_s_p8_0[] = {
  128422. 1, 4, 4, 7, 7, 8, 8, 7, 7, 8, 7, 9, 8,10, 9, 6,
  128423. 5, 5, 8, 8, 9, 9, 8, 8, 9, 9,11,10,11,10, 6, 5,
  128424. 5, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,11,18, 8, 8,
  128425. 9, 8,10,10, 9, 9,10,10,10,10,11,10,18, 8, 8, 9,
  128426. 9,10,10, 9, 9,10,10,11,11,12,12,18,12,13, 9,10,
  128427. 10,10, 9,10,10,10,11,11,12,11,18,13,13, 9, 9,10,
  128428. 10,10,10,10,10,11,11,12,12,18,18,18,10,10, 9, 9,
  128429. 11,11,11,11,11,12,12,12,18,18,18,10, 9,10, 9,11,
  128430. 10,11,11,11,11,13,12,18,18,18,14,13,10,10,11,11,
  128431. 12,12,12,12,12,12,18,18,18,14,13,10,10,11,10,12,
  128432. 12,12,12,12,12,18,18,18,18,18,12,12,11,11,12,12,
  128433. 13,13,13,14,18,18,18,18,18,12,12,11,11,12,11,13,
  128434. 13,14,13,18,18,18,18,18,16,16,11,12,12,13,13,13,
  128435. 14,13,18,18,18,18,18,16,15,12,11,12,11,13,11,15,
  128436. 14,
  128437. };
  128438. static float _vq_quantthresh__44c6_s_p8_0[] = {
  128439. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  128440. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  128441. };
  128442. static long _vq_quantmap__44c6_s_p8_0[] = {
  128443. 13, 11, 9, 7, 5, 3, 1, 0,
  128444. 2, 4, 6, 8, 10, 12, 14,
  128445. };
  128446. static encode_aux_threshmatch _vq_auxt__44c6_s_p8_0 = {
  128447. _vq_quantthresh__44c6_s_p8_0,
  128448. _vq_quantmap__44c6_s_p8_0,
  128449. 15,
  128450. 15
  128451. };
  128452. static static_codebook _44c6_s_p8_0 = {
  128453. 2, 225,
  128454. _vq_lengthlist__44c6_s_p8_0,
  128455. 1, -520986624, 1620377600, 4, 0,
  128456. _vq_quantlist__44c6_s_p8_0,
  128457. NULL,
  128458. &_vq_auxt__44c6_s_p8_0,
  128459. NULL,
  128460. 0
  128461. };
  128462. static long _vq_quantlist__44c6_s_p8_1[] = {
  128463. 10,
  128464. 9,
  128465. 11,
  128466. 8,
  128467. 12,
  128468. 7,
  128469. 13,
  128470. 6,
  128471. 14,
  128472. 5,
  128473. 15,
  128474. 4,
  128475. 16,
  128476. 3,
  128477. 17,
  128478. 2,
  128479. 18,
  128480. 1,
  128481. 19,
  128482. 0,
  128483. 20,
  128484. };
  128485. static long _vq_lengthlist__44c6_s_p8_1[] = {
  128486. 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 8,
  128487. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,
  128488. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  128489. 8, 8, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,10,
  128490. 7, 7, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  128491. 9, 9, 9, 9,10,11,11, 8, 7, 8, 8, 8, 9, 9, 9, 9,
  128492. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,11, 8, 8, 8, 8,
  128493. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,
  128494. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  128495. 9, 9, 9,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  128496. 9, 9, 9, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9, 9,
  128497. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,11,
  128498. 11,11, 9, 9, 9, 9, 9, 9,10, 9, 9,10, 9,10, 9, 9,
  128499. 10, 9,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,10,10,
  128500. 10,10, 9,10,10, 9,10,11,11,11,11,11, 9, 9, 9, 9,
  128501. 10,10,10, 9,10,10,10,10, 9,10,10, 9,11,11,11,11,
  128502. 11,11,11, 9, 9, 9, 9,10,10,10,10, 9,10,10,10,10,
  128503. 10,11,11,11,11,11,11,11,10, 9,10,10,10,10,10,10,
  128504. 10, 9,10, 9,10,10,11,11,11,11,11,11,11,10, 9,10,
  128505. 9,10,10, 9,10,10,10,10,10,10,10,11,11,11,11,11,
  128506. 11,11,10,10,10,10,10,10,10, 9,10,10,10,10,10, 9,
  128507. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  128508. 10,10,10,10,10,11,11,11,11,11,11,11,11,11,10,10,
  128509. 10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  128510. 11,11,11,10,10,10,10,10,10,10,10,10, 9,10,10,11,
  128511. 11,11,11,11,11,11,11,11,10,10,10, 9,10,10,10,10,
  128512. 10,10,10,10,10,11,11,11,11,11,11,11,11,10,11, 9,
  128513. 10,10,10,10,10,10,10,10,10,
  128514. };
  128515. static float _vq_quantthresh__44c6_s_p8_1[] = {
  128516. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  128517. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  128518. 6.5, 7.5, 8.5, 9.5,
  128519. };
  128520. static long _vq_quantmap__44c6_s_p8_1[] = {
  128521. 19, 17, 15, 13, 11, 9, 7, 5,
  128522. 3, 1, 0, 2, 4, 6, 8, 10,
  128523. 12, 14, 16, 18, 20,
  128524. };
  128525. static encode_aux_threshmatch _vq_auxt__44c6_s_p8_1 = {
  128526. _vq_quantthresh__44c6_s_p8_1,
  128527. _vq_quantmap__44c6_s_p8_1,
  128528. 21,
  128529. 21
  128530. };
  128531. static static_codebook _44c6_s_p8_1 = {
  128532. 2, 441,
  128533. _vq_lengthlist__44c6_s_p8_1,
  128534. 1, -529268736, 1611661312, 5, 0,
  128535. _vq_quantlist__44c6_s_p8_1,
  128536. NULL,
  128537. &_vq_auxt__44c6_s_p8_1,
  128538. NULL,
  128539. 0
  128540. };
  128541. static long _vq_quantlist__44c6_s_p9_0[] = {
  128542. 6,
  128543. 5,
  128544. 7,
  128545. 4,
  128546. 8,
  128547. 3,
  128548. 9,
  128549. 2,
  128550. 10,
  128551. 1,
  128552. 11,
  128553. 0,
  128554. 12,
  128555. };
  128556. static long _vq_lengthlist__44c6_s_p9_0[] = {
  128557. 1, 3, 3,11,11,11,11,11,11,11,11,11,11, 4, 7, 7,
  128558. 11,11,11,11,11,11,11,11,11,11, 5, 8, 9,11,11,11,
  128559. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128560. 11,11,11,11,11,10,10,10,10,10,10,10,10,10,10,10,
  128561. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  128562. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  128563. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  128564. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  128565. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  128566. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  128567. 10,10,10,10,10,10,10,10,10,
  128568. };
  128569. static float _vq_quantthresh__44c6_s_p9_0[] = {
  128570. -3503.5, -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5,
  128571. 1592.5, 2229.5, 2866.5, 3503.5,
  128572. };
  128573. static long _vq_quantmap__44c6_s_p9_0[] = {
  128574. 11, 9, 7, 5, 3, 1, 0, 2,
  128575. 4, 6, 8, 10, 12,
  128576. };
  128577. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_0 = {
  128578. _vq_quantthresh__44c6_s_p9_0,
  128579. _vq_quantmap__44c6_s_p9_0,
  128580. 13,
  128581. 13
  128582. };
  128583. static static_codebook _44c6_s_p9_0 = {
  128584. 2, 169,
  128585. _vq_lengthlist__44c6_s_p9_0,
  128586. 1, -511845376, 1630791680, 4, 0,
  128587. _vq_quantlist__44c6_s_p9_0,
  128588. NULL,
  128589. &_vq_auxt__44c6_s_p9_0,
  128590. NULL,
  128591. 0
  128592. };
  128593. static long _vq_quantlist__44c6_s_p9_1[] = {
  128594. 6,
  128595. 5,
  128596. 7,
  128597. 4,
  128598. 8,
  128599. 3,
  128600. 9,
  128601. 2,
  128602. 10,
  128603. 1,
  128604. 11,
  128605. 0,
  128606. 12,
  128607. };
  128608. static long _vq_lengthlist__44c6_s_p9_1[] = {
  128609. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8, 8, 8, 6, 6, 6,
  128610. 8, 8, 8, 8, 8, 7, 9, 8,10,10, 5, 6, 6, 8, 8, 9,
  128611. 9, 8, 8,10,10,10,10,16, 9, 9, 9, 9, 9, 9, 9, 8,
  128612. 10, 9,11,11,16, 8, 9, 9, 9, 9, 9, 9, 9,10,10,11,
  128613. 11,16,13,13, 9, 9,10, 9, 9,10,11,11,11,12,16,13,
  128614. 14, 9, 8,10, 8, 9, 9,10,10,12,11,16,14,16, 9, 9,
  128615. 9, 9,11,11,12,11,12,11,16,16,16, 9, 7, 9, 6,11,
  128616. 11,11,10,11,11,16,16,16,11,12, 9,10,11,11,12,11,
  128617. 13,13,16,16,16,12,11,10, 7,12,10,12,12,12,12,16,
  128618. 16,15,16,16,10,11,10,11,13,13,14,12,16,16,16,15,
  128619. 15,12,10,11,11,13,11,12,13,
  128620. };
  128621. static float _vq_quantthresh__44c6_s_p9_1[] = {
  128622. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  128623. 122.5, 171.5, 220.5, 269.5,
  128624. };
  128625. static long _vq_quantmap__44c6_s_p9_1[] = {
  128626. 11, 9, 7, 5, 3, 1, 0, 2,
  128627. 4, 6, 8, 10, 12,
  128628. };
  128629. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_1 = {
  128630. _vq_quantthresh__44c6_s_p9_1,
  128631. _vq_quantmap__44c6_s_p9_1,
  128632. 13,
  128633. 13
  128634. };
  128635. static static_codebook _44c6_s_p9_1 = {
  128636. 2, 169,
  128637. _vq_lengthlist__44c6_s_p9_1,
  128638. 1, -518889472, 1622704128, 4, 0,
  128639. _vq_quantlist__44c6_s_p9_1,
  128640. NULL,
  128641. &_vq_auxt__44c6_s_p9_1,
  128642. NULL,
  128643. 0
  128644. };
  128645. static long _vq_quantlist__44c6_s_p9_2[] = {
  128646. 24,
  128647. 23,
  128648. 25,
  128649. 22,
  128650. 26,
  128651. 21,
  128652. 27,
  128653. 20,
  128654. 28,
  128655. 19,
  128656. 29,
  128657. 18,
  128658. 30,
  128659. 17,
  128660. 31,
  128661. 16,
  128662. 32,
  128663. 15,
  128664. 33,
  128665. 14,
  128666. 34,
  128667. 13,
  128668. 35,
  128669. 12,
  128670. 36,
  128671. 11,
  128672. 37,
  128673. 10,
  128674. 38,
  128675. 9,
  128676. 39,
  128677. 8,
  128678. 40,
  128679. 7,
  128680. 41,
  128681. 6,
  128682. 42,
  128683. 5,
  128684. 43,
  128685. 4,
  128686. 44,
  128687. 3,
  128688. 45,
  128689. 2,
  128690. 46,
  128691. 1,
  128692. 47,
  128693. 0,
  128694. 48,
  128695. };
  128696. static long _vq_lengthlist__44c6_s_p9_2[] = {
  128697. 2, 4, 3, 4, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  128698. 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  128699. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  128700. 7,
  128701. };
  128702. static float _vq_quantthresh__44c6_s_p9_2[] = {
  128703. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  128704. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  128705. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  128706. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  128707. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  128708. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  128709. };
  128710. static long _vq_quantmap__44c6_s_p9_2[] = {
  128711. 47, 45, 43, 41, 39, 37, 35, 33,
  128712. 31, 29, 27, 25, 23, 21, 19, 17,
  128713. 15, 13, 11, 9, 7, 5, 3, 1,
  128714. 0, 2, 4, 6, 8, 10, 12, 14,
  128715. 16, 18, 20, 22, 24, 26, 28, 30,
  128716. 32, 34, 36, 38, 40, 42, 44, 46,
  128717. 48,
  128718. };
  128719. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_2 = {
  128720. _vq_quantthresh__44c6_s_p9_2,
  128721. _vq_quantmap__44c6_s_p9_2,
  128722. 49,
  128723. 49
  128724. };
  128725. static static_codebook _44c6_s_p9_2 = {
  128726. 1, 49,
  128727. _vq_lengthlist__44c6_s_p9_2,
  128728. 1, -526909440, 1611661312, 6, 0,
  128729. _vq_quantlist__44c6_s_p9_2,
  128730. NULL,
  128731. &_vq_auxt__44c6_s_p9_2,
  128732. NULL,
  128733. 0
  128734. };
  128735. static long _huff_lengthlist__44c6_s_short[] = {
  128736. 3, 9,11,11,13,14,19,17,17,19, 5, 4, 5, 8,10,10,
  128737. 13,16,18,19, 7, 4, 4, 5, 8, 9,12,14,17,19, 8, 6,
  128738. 5, 5, 7, 7,10,13,16,18,10, 8, 7, 6, 5, 5, 8,11,
  128739. 17,19,11, 9, 7, 7, 5, 4, 5, 8,17,19,13,11, 8, 7,
  128740. 7, 5, 5, 7,16,18,14,13, 8, 6, 6, 5, 5, 7,16,18,
  128741. 18,16,10, 8, 8, 7, 7, 9,16,18,18,18,12,10,10, 9,
  128742. 9,10,17,18,
  128743. };
  128744. static static_codebook _huff_book__44c6_s_short = {
  128745. 2, 100,
  128746. _huff_lengthlist__44c6_s_short,
  128747. 0, 0, 0, 0, 0,
  128748. NULL,
  128749. NULL,
  128750. NULL,
  128751. NULL,
  128752. 0
  128753. };
  128754. static long _huff_lengthlist__44c7_s_long[] = {
  128755. 3, 8,11,13,15,14,14,13,15,14, 6, 4, 5, 7, 9,10,
  128756. 11,11,14,13,10, 4, 3, 5, 7, 8, 9,10,13,13,12, 7,
  128757. 4, 4, 5, 6, 8, 9,12,14,13, 9, 6, 5, 5, 6, 8, 9,
  128758. 12,14,12, 9, 7, 6, 5, 5, 6, 8,11,11,12,11, 9, 8,
  128759. 7, 6, 6, 7,10,11,13,11,10, 9, 8, 7, 6, 6, 9,11,
  128760. 13,13,12,12,12,10, 9, 8, 9,11,12,14,15,15,14,12,
  128761. 11,10,10,12,
  128762. };
  128763. static static_codebook _huff_book__44c7_s_long = {
  128764. 2, 100,
  128765. _huff_lengthlist__44c7_s_long,
  128766. 0, 0, 0, 0, 0,
  128767. NULL,
  128768. NULL,
  128769. NULL,
  128770. NULL,
  128771. 0
  128772. };
  128773. static long _vq_quantlist__44c7_s_p1_0[] = {
  128774. 1,
  128775. 0,
  128776. 2,
  128777. };
  128778. static long _vq_lengthlist__44c7_s_p1_0[] = {
  128779. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 8, 7, 0, 9, 9, 0,
  128780. 9, 8, 5, 7, 8, 0, 9, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  128781. 0, 0, 0, 0, 5, 9, 9, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  128782. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  128783. 9, 9, 0, 8, 8, 0, 8, 8, 5, 8, 9, 0, 8, 8, 0, 8,
  128784. 8,
  128785. };
  128786. static float _vq_quantthresh__44c7_s_p1_0[] = {
  128787. -0.5, 0.5,
  128788. };
  128789. static long _vq_quantmap__44c7_s_p1_0[] = {
  128790. 1, 0, 2,
  128791. };
  128792. static encode_aux_threshmatch _vq_auxt__44c7_s_p1_0 = {
  128793. _vq_quantthresh__44c7_s_p1_0,
  128794. _vq_quantmap__44c7_s_p1_0,
  128795. 3,
  128796. 3
  128797. };
  128798. static static_codebook _44c7_s_p1_0 = {
  128799. 4, 81,
  128800. _vq_lengthlist__44c7_s_p1_0,
  128801. 1, -535822336, 1611661312, 2, 0,
  128802. _vq_quantlist__44c7_s_p1_0,
  128803. NULL,
  128804. &_vq_auxt__44c7_s_p1_0,
  128805. NULL,
  128806. 0
  128807. };
  128808. static long _vq_quantlist__44c7_s_p2_0[] = {
  128809. 2,
  128810. 1,
  128811. 3,
  128812. 0,
  128813. 4,
  128814. };
  128815. static long _vq_lengthlist__44c7_s_p2_0[] = {
  128816. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  128817. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  128818. 8,10,10, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  128819. 11,11, 5, 7, 7, 9, 9, 0, 8, 8,10,10, 0, 7, 8, 9,
  128820. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,10,
  128821. 0,11,11,12,12, 0,11,10,12,12, 0,13,14,14,14, 0,
  128822. 0, 0,14,13, 8, 9, 9,10,11, 0,11,11,12,12, 0,10,
  128823. 11,12,12, 0,13,13,14,14, 0, 0, 0,13,14, 0, 0, 0,
  128824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128825. 0, 0, 0, 0, 0, 0, 5, 8, 7,11,10, 0, 7, 7,10,10,
  128826. 0, 7, 7,10,10, 0, 9, 9,11,10, 0, 0, 0,11,11, 5,
  128827. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  128828. 9,10,11, 0, 0, 0,11,11, 8,10, 9,12,12, 0,10,10,
  128829. 12,12, 0,10,10,12,12, 0,12,12,13,13, 0, 0, 0,13,
  128830. 13, 8, 9,10,12,12, 0,10,10,12,12, 0,10,10,11,12,
  128831. 0,12,12,13,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0,
  128832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128833. 0, 0, 0, 5, 8, 8,11,11, 0, 7, 7,10,10, 0, 7, 7,
  128834. 10,10, 0, 9, 9,10,11, 0, 0, 0,11,10, 5, 8, 8,10,
  128835. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,11,10,
  128836. 0, 0, 0,10,11, 9,10,10,12,12, 0,10,10,12,12, 0,
  128837. 10,10,12,12, 0,12,13,13,13, 0, 0, 0,13,12, 9,10,
  128838. 10,12,12, 0,10,10,12,12, 0,10,10,12,12, 0,13,12,
  128839. 13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128841. 7,10,10,14,13, 0, 9, 9,12,12, 0, 9, 9,12,12, 0,
  128842. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,14, 0, 9,
  128843. 9,12,13, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  128844. 12,12, 9,11,11,14,13, 0,11,10,13,12, 0,11,11,13,
  128845. 13, 0,12,12,13,13, 0, 0, 0,13,13, 9,11,11,13,14,
  128846. 0,10,11,12,13, 0,11,11,13,13, 0,12,12,13,13, 0,
  128847. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  128852. 11,11,14,14, 0,10,11,13,13, 0,11,10,13,13, 0,12,
  128853. 12,13,13, 0, 0, 0,13,12, 9,11,11,14,14, 0,11,10,
  128854. 13,13, 0,10,11,13,13, 0,12,12,14,13, 0, 0, 0,13,
  128855. 13,
  128856. };
  128857. static float _vq_quantthresh__44c7_s_p2_0[] = {
  128858. -1.5, -0.5, 0.5, 1.5,
  128859. };
  128860. static long _vq_quantmap__44c7_s_p2_0[] = {
  128861. 3, 1, 0, 2, 4,
  128862. };
  128863. static encode_aux_threshmatch _vq_auxt__44c7_s_p2_0 = {
  128864. _vq_quantthresh__44c7_s_p2_0,
  128865. _vq_quantmap__44c7_s_p2_0,
  128866. 5,
  128867. 5
  128868. };
  128869. static static_codebook _44c7_s_p2_0 = {
  128870. 4, 625,
  128871. _vq_lengthlist__44c7_s_p2_0,
  128872. 1, -533725184, 1611661312, 3, 0,
  128873. _vq_quantlist__44c7_s_p2_0,
  128874. NULL,
  128875. &_vq_auxt__44c7_s_p2_0,
  128876. NULL,
  128877. 0
  128878. };
  128879. static long _vq_quantlist__44c7_s_p3_0[] = {
  128880. 4,
  128881. 3,
  128882. 5,
  128883. 2,
  128884. 6,
  128885. 1,
  128886. 7,
  128887. 0,
  128888. 8,
  128889. };
  128890. static long _vq_lengthlist__44c7_s_p3_0[] = {
  128891. 2, 4, 4, 5, 5, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  128892. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 6, 6,
  128893. 8, 8,10,10, 0, 0, 0, 6, 6, 8, 8,10,10, 0, 0, 0,
  128894. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0,
  128895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128896. 0,
  128897. };
  128898. static float _vq_quantthresh__44c7_s_p3_0[] = {
  128899. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  128900. };
  128901. static long _vq_quantmap__44c7_s_p3_0[] = {
  128902. 7, 5, 3, 1, 0, 2, 4, 6,
  128903. 8,
  128904. };
  128905. static encode_aux_threshmatch _vq_auxt__44c7_s_p3_0 = {
  128906. _vq_quantthresh__44c7_s_p3_0,
  128907. _vq_quantmap__44c7_s_p3_0,
  128908. 9,
  128909. 9
  128910. };
  128911. static static_codebook _44c7_s_p3_0 = {
  128912. 2, 81,
  128913. _vq_lengthlist__44c7_s_p3_0,
  128914. 1, -531628032, 1611661312, 4, 0,
  128915. _vq_quantlist__44c7_s_p3_0,
  128916. NULL,
  128917. &_vq_auxt__44c7_s_p3_0,
  128918. NULL,
  128919. 0
  128920. };
  128921. static long _vq_quantlist__44c7_s_p4_0[] = {
  128922. 8,
  128923. 7,
  128924. 9,
  128925. 6,
  128926. 10,
  128927. 5,
  128928. 11,
  128929. 4,
  128930. 12,
  128931. 3,
  128932. 13,
  128933. 2,
  128934. 14,
  128935. 1,
  128936. 15,
  128937. 0,
  128938. 16,
  128939. };
  128940. static long _vq_lengthlist__44c7_s_p4_0[] = {
  128941. 3, 4, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  128942. 11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,
  128943. 12,12, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  128944. 11,12,12, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,
  128945. 11,12,12,12, 0, 0, 0, 6, 6, 8, 7, 9, 9, 9, 9,10,
  128946. 10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,
  128947. 11,11,12,12,13,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,
  128948. 10,11,11,12,12,12,13, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  128949. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  128950. 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 0, 0,
  128951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128959. 0,
  128960. };
  128961. static float _vq_quantthresh__44c7_s_p4_0[] = {
  128962. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  128963. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  128964. };
  128965. static long _vq_quantmap__44c7_s_p4_0[] = {
  128966. 15, 13, 11, 9, 7, 5, 3, 1,
  128967. 0, 2, 4, 6, 8, 10, 12, 14,
  128968. 16,
  128969. };
  128970. static encode_aux_threshmatch _vq_auxt__44c7_s_p4_0 = {
  128971. _vq_quantthresh__44c7_s_p4_0,
  128972. _vq_quantmap__44c7_s_p4_0,
  128973. 17,
  128974. 17
  128975. };
  128976. static static_codebook _44c7_s_p4_0 = {
  128977. 2, 289,
  128978. _vq_lengthlist__44c7_s_p4_0,
  128979. 1, -529530880, 1611661312, 5, 0,
  128980. _vq_quantlist__44c7_s_p4_0,
  128981. NULL,
  128982. &_vq_auxt__44c7_s_p4_0,
  128983. NULL,
  128984. 0
  128985. };
  128986. static long _vq_quantlist__44c7_s_p5_0[] = {
  128987. 1,
  128988. 0,
  128989. 2,
  128990. };
  128991. static long _vq_lengthlist__44c7_s_p5_0[] = {
  128992. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 7,10,10,10,10,
  128993. 10, 9, 4, 6, 6,10,10,10,10, 9,10, 5,10,10, 9,11,
  128994. 12,10,11,12, 7,10,10,11,12,12,12,12,12, 7,10,10,
  128995. 11,12,12,12,12,12, 6,10,10,10,12,12,11,12,12, 7,
  128996. 10,10,12,12,12,12,11,12, 7,10,10,11,12,12,12,12,
  128997. 12,
  128998. };
  128999. static float _vq_quantthresh__44c7_s_p5_0[] = {
  129000. -5.5, 5.5,
  129001. };
  129002. static long _vq_quantmap__44c7_s_p5_0[] = {
  129003. 1, 0, 2,
  129004. };
  129005. static encode_aux_threshmatch _vq_auxt__44c7_s_p5_0 = {
  129006. _vq_quantthresh__44c7_s_p5_0,
  129007. _vq_quantmap__44c7_s_p5_0,
  129008. 3,
  129009. 3
  129010. };
  129011. static static_codebook _44c7_s_p5_0 = {
  129012. 4, 81,
  129013. _vq_lengthlist__44c7_s_p5_0,
  129014. 1, -529137664, 1618345984, 2, 0,
  129015. _vq_quantlist__44c7_s_p5_0,
  129016. NULL,
  129017. &_vq_auxt__44c7_s_p5_0,
  129018. NULL,
  129019. 0
  129020. };
  129021. static long _vq_quantlist__44c7_s_p5_1[] = {
  129022. 5,
  129023. 4,
  129024. 6,
  129025. 3,
  129026. 7,
  129027. 2,
  129028. 8,
  129029. 1,
  129030. 9,
  129031. 0,
  129032. 10,
  129033. };
  129034. static long _vq_lengthlist__44c7_s_p5_1[] = {
  129035. 3, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6,
  129036. 7, 7, 8, 8, 9, 9,11, 4, 4, 6, 6, 7, 7, 8, 8, 9,
  129037. 9,12, 5, 5, 6, 6, 7, 7, 9, 9, 9, 9,12,12,12, 6,
  129038. 6, 7, 7, 9, 9, 9, 9,11,11,11, 7, 7, 7, 7, 8, 8,
  129039. 9, 9,11,11,11, 7, 7, 7, 7, 8, 8, 9, 9,11,11,11,
  129040. 7, 7, 8, 8, 8, 8, 9, 9,11,11,11,11,11, 8, 8, 8,
  129041. 8, 8, 9,11,11,11,11,11, 8, 8, 8, 8, 8, 8,11,11,
  129042. 11,11,11, 7, 7, 8, 8, 8, 8,
  129043. };
  129044. static float _vq_quantthresh__44c7_s_p5_1[] = {
  129045. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  129046. 3.5, 4.5,
  129047. };
  129048. static long _vq_quantmap__44c7_s_p5_1[] = {
  129049. 9, 7, 5, 3, 1, 0, 2, 4,
  129050. 6, 8, 10,
  129051. };
  129052. static encode_aux_threshmatch _vq_auxt__44c7_s_p5_1 = {
  129053. _vq_quantthresh__44c7_s_p5_1,
  129054. _vq_quantmap__44c7_s_p5_1,
  129055. 11,
  129056. 11
  129057. };
  129058. static static_codebook _44c7_s_p5_1 = {
  129059. 2, 121,
  129060. _vq_lengthlist__44c7_s_p5_1,
  129061. 1, -531365888, 1611661312, 4, 0,
  129062. _vq_quantlist__44c7_s_p5_1,
  129063. NULL,
  129064. &_vq_auxt__44c7_s_p5_1,
  129065. NULL,
  129066. 0
  129067. };
  129068. static long _vq_quantlist__44c7_s_p6_0[] = {
  129069. 6,
  129070. 5,
  129071. 7,
  129072. 4,
  129073. 8,
  129074. 3,
  129075. 9,
  129076. 2,
  129077. 10,
  129078. 1,
  129079. 11,
  129080. 0,
  129081. 12,
  129082. };
  129083. static long _vq_lengthlist__44c7_s_p6_0[] = {
  129084. 1, 4, 4, 6, 6, 7, 7, 8, 7, 9, 8,10,10, 6, 5, 5,
  129085. 7, 7, 8, 8, 9, 9, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  129086. 8, 9, 9,10,10,11,11, 0, 7, 7, 7, 7, 9, 8, 9, 9,
  129087. 10,10,11,11, 0, 8, 8, 7, 7, 8, 9, 9, 9,10,10,11,
  129088. 11, 0,11,11, 9, 9,10,10,11,10,11,11,12,12, 0,12,
  129089. 12, 9, 9,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0,
  129090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129094. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129095. };
  129096. static float _vq_quantthresh__44c7_s_p6_0[] = {
  129097. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  129098. 12.5, 17.5, 22.5, 27.5,
  129099. };
  129100. static long _vq_quantmap__44c7_s_p6_0[] = {
  129101. 11, 9, 7, 5, 3, 1, 0, 2,
  129102. 4, 6, 8, 10, 12,
  129103. };
  129104. static encode_aux_threshmatch _vq_auxt__44c7_s_p6_0 = {
  129105. _vq_quantthresh__44c7_s_p6_0,
  129106. _vq_quantmap__44c7_s_p6_0,
  129107. 13,
  129108. 13
  129109. };
  129110. static static_codebook _44c7_s_p6_0 = {
  129111. 2, 169,
  129112. _vq_lengthlist__44c7_s_p6_0,
  129113. 1, -526516224, 1616117760, 4, 0,
  129114. _vq_quantlist__44c7_s_p6_0,
  129115. NULL,
  129116. &_vq_auxt__44c7_s_p6_0,
  129117. NULL,
  129118. 0
  129119. };
  129120. static long _vq_quantlist__44c7_s_p6_1[] = {
  129121. 2,
  129122. 1,
  129123. 3,
  129124. 0,
  129125. 4,
  129126. };
  129127. static long _vq_lengthlist__44c7_s_p6_1[] = {
  129128. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  129129. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  129130. };
  129131. static float _vq_quantthresh__44c7_s_p6_1[] = {
  129132. -1.5, -0.5, 0.5, 1.5,
  129133. };
  129134. static long _vq_quantmap__44c7_s_p6_1[] = {
  129135. 3, 1, 0, 2, 4,
  129136. };
  129137. static encode_aux_threshmatch _vq_auxt__44c7_s_p6_1 = {
  129138. _vq_quantthresh__44c7_s_p6_1,
  129139. _vq_quantmap__44c7_s_p6_1,
  129140. 5,
  129141. 5
  129142. };
  129143. static static_codebook _44c7_s_p6_1 = {
  129144. 2, 25,
  129145. _vq_lengthlist__44c7_s_p6_1,
  129146. 1, -533725184, 1611661312, 3, 0,
  129147. _vq_quantlist__44c7_s_p6_1,
  129148. NULL,
  129149. &_vq_auxt__44c7_s_p6_1,
  129150. NULL,
  129151. 0
  129152. };
  129153. static long _vq_quantlist__44c7_s_p7_0[] = {
  129154. 6,
  129155. 5,
  129156. 7,
  129157. 4,
  129158. 8,
  129159. 3,
  129160. 9,
  129161. 2,
  129162. 10,
  129163. 1,
  129164. 11,
  129165. 0,
  129166. 12,
  129167. };
  129168. static long _vq_lengthlist__44c7_s_p7_0[] = {
  129169. 1, 4, 4, 6, 6, 7, 8, 9, 9,10,10,12,11, 6, 5, 5,
  129170. 7, 7, 8, 8, 9,10,11,11,12,12, 7, 5, 5, 7, 7, 8,
  129171. 8,10,10,11,11,12,12,20, 7, 7, 7, 7, 8, 9,10,10,
  129172. 11,11,12,13,20, 7, 7, 7, 7, 9, 9,10,10,11,12,13,
  129173. 13,20,11,11, 8, 8, 9, 9,11,11,12,12,13,13,20,11,
  129174. 11, 8, 8, 9, 9,11,11,12,12,13,13,20,20,20,10,10,
  129175. 10,10,12,12,13,13,13,13,20,20,20,10,10,10,10,12,
  129176. 12,13,13,13,14,20,20,20,14,14,11,11,12,12,13,13,
  129177. 14,14,20,20,20,14,14,11,11,12,12,13,13,14,14,20,
  129178. 20,20,20,19,13,13,13,13,14,14,15,14,19,19,19,19,
  129179. 19,13,13,13,13,14,14,15,15,
  129180. };
  129181. static float _vq_quantthresh__44c7_s_p7_0[] = {
  129182. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  129183. 27.5, 38.5, 49.5, 60.5,
  129184. };
  129185. static long _vq_quantmap__44c7_s_p7_0[] = {
  129186. 11, 9, 7, 5, 3, 1, 0, 2,
  129187. 4, 6, 8, 10, 12,
  129188. };
  129189. static encode_aux_threshmatch _vq_auxt__44c7_s_p7_0 = {
  129190. _vq_quantthresh__44c7_s_p7_0,
  129191. _vq_quantmap__44c7_s_p7_0,
  129192. 13,
  129193. 13
  129194. };
  129195. static static_codebook _44c7_s_p7_0 = {
  129196. 2, 169,
  129197. _vq_lengthlist__44c7_s_p7_0,
  129198. 1, -523206656, 1618345984, 4, 0,
  129199. _vq_quantlist__44c7_s_p7_0,
  129200. NULL,
  129201. &_vq_auxt__44c7_s_p7_0,
  129202. NULL,
  129203. 0
  129204. };
  129205. static long _vq_quantlist__44c7_s_p7_1[] = {
  129206. 5,
  129207. 4,
  129208. 6,
  129209. 3,
  129210. 7,
  129211. 2,
  129212. 8,
  129213. 1,
  129214. 9,
  129215. 0,
  129216. 10,
  129217. };
  129218. static long _vq_lengthlist__44c7_s_p7_1[] = {
  129219. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 8, 6, 6, 7, 7,
  129220. 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  129221. 7, 8, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7,
  129222. 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  129223. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  129224. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  129225. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  129226. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  129227. };
  129228. static float _vq_quantthresh__44c7_s_p7_1[] = {
  129229. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  129230. 3.5, 4.5,
  129231. };
  129232. static long _vq_quantmap__44c7_s_p7_1[] = {
  129233. 9, 7, 5, 3, 1, 0, 2, 4,
  129234. 6, 8, 10,
  129235. };
  129236. static encode_aux_threshmatch _vq_auxt__44c7_s_p7_1 = {
  129237. _vq_quantthresh__44c7_s_p7_1,
  129238. _vq_quantmap__44c7_s_p7_1,
  129239. 11,
  129240. 11
  129241. };
  129242. static static_codebook _44c7_s_p7_1 = {
  129243. 2, 121,
  129244. _vq_lengthlist__44c7_s_p7_1,
  129245. 1, -531365888, 1611661312, 4, 0,
  129246. _vq_quantlist__44c7_s_p7_1,
  129247. NULL,
  129248. &_vq_auxt__44c7_s_p7_1,
  129249. NULL,
  129250. 0
  129251. };
  129252. static long _vq_quantlist__44c7_s_p8_0[] = {
  129253. 7,
  129254. 6,
  129255. 8,
  129256. 5,
  129257. 9,
  129258. 4,
  129259. 10,
  129260. 3,
  129261. 11,
  129262. 2,
  129263. 12,
  129264. 1,
  129265. 13,
  129266. 0,
  129267. 14,
  129268. };
  129269. static long _vq_lengthlist__44c7_s_p8_0[] = {
  129270. 1, 4, 4, 7, 7, 8, 8, 8, 7, 9, 8, 9, 9,10,10, 6,
  129271. 5, 5, 7, 7, 9, 9, 8, 8,10, 9,11,10,12,11, 6, 5,
  129272. 5, 8, 7, 9, 9, 8, 8,10,10,11,11,12,11,19, 8, 8,
  129273. 8, 8,10,10, 9, 9,10,10,11,11,12,11,19, 8, 8, 8,
  129274. 8,10,10, 9, 9,10,10,11,11,12,12,19,12,12, 9, 9,
  129275. 10,10, 9,10,10,10,11,11,12,12,19,12,12, 9, 9,10,
  129276. 10,10,10,10,10,12,12,12,12,19,19,19, 9, 9, 9, 9,
  129277. 11,10,11,11,12,11,13,13,19,19,19, 9, 9, 9, 9,11,
  129278. 10,11,11,11,12,13,13,19,19,19,13,13,10,10,11,11,
  129279. 12,12,12,12,13,12,19,19,19,14,13,10,10,11,11,12,
  129280. 12,12,13,13,13,19,19,19,19,19,12,12,12,11,12,13,
  129281. 14,13,13,13,19,19,19,19,19,12,12,12,11,12,12,13,
  129282. 14,13,14,19,19,19,19,19,16,16,12,13,12,13,13,14,
  129283. 15,14,19,18,18,18,18,16,15,12,11,12,11,14,12,14,
  129284. 14,
  129285. };
  129286. static float _vq_quantthresh__44c7_s_p8_0[] = {
  129287. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  129288. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  129289. };
  129290. static long _vq_quantmap__44c7_s_p8_0[] = {
  129291. 13, 11, 9, 7, 5, 3, 1, 0,
  129292. 2, 4, 6, 8, 10, 12, 14,
  129293. };
  129294. static encode_aux_threshmatch _vq_auxt__44c7_s_p8_0 = {
  129295. _vq_quantthresh__44c7_s_p8_0,
  129296. _vq_quantmap__44c7_s_p8_0,
  129297. 15,
  129298. 15
  129299. };
  129300. static static_codebook _44c7_s_p8_0 = {
  129301. 2, 225,
  129302. _vq_lengthlist__44c7_s_p8_0,
  129303. 1, -520986624, 1620377600, 4, 0,
  129304. _vq_quantlist__44c7_s_p8_0,
  129305. NULL,
  129306. &_vq_auxt__44c7_s_p8_0,
  129307. NULL,
  129308. 0
  129309. };
  129310. static long _vq_quantlist__44c7_s_p8_1[] = {
  129311. 10,
  129312. 9,
  129313. 11,
  129314. 8,
  129315. 12,
  129316. 7,
  129317. 13,
  129318. 6,
  129319. 14,
  129320. 5,
  129321. 15,
  129322. 4,
  129323. 16,
  129324. 3,
  129325. 17,
  129326. 2,
  129327. 18,
  129328. 1,
  129329. 19,
  129330. 0,
  129331. 20,
  129332. };
  129333. static long _vq_lengthlist__44c7_s_p8_1[] = {
  129334. 3, 5, 5, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  129335. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  129336. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  129337. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  129338. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  129339. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  129340. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 9,
  129341. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  129342. 10, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  129343. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  129344. 9, 9, 9, 9, 9, 9, 9, 9,10,11,10,10,10, 9, 9, 9,
  129345. 9, 9, 9, 9, 9, 9, 9,10, 9, 9,10, 9, 9,10,11,10,
  129346. 11,10, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,10, 9, 9,
  129347. 9, 9,11,10,11,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9,
  129348. 10, 9, 9,10, 9, 9,10,11,10,10,11,10, 9, 9, 9, 9,
  129349. 9,10,10, 9,10,10,10,10, 9,10,10,10,10,10,10,11,
  129350. 11,11,10, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,
  129351. 10,10,10,11,11,10,10,10,10,10,10,10,10,10,10,10,
  129352. 10, 9,10,10, 9,10,11,11,10,11,10,11,10, 9,10,10,
  129353. 9,10,10,10,10,10,10,10,10,10,10,11,11,11,11,10,
  129354. 11,11,10,10,10,10,10,10, 9,10, 9,10,10, 9,10, 9,
  129355. 10,10,10,11,10,11,10,11,11,10,10,10,10,10,10, 9,
  129356. 10,10,10,10,10,10,10,11,10,10,10,10,10,10,10,10,
  129357. 10,10,10,10,10,10,10,10,10,10,10,10,10,11,10,11,
  129358. 11,10,10,10,10, 9, 9,10,10, 9, 9,10, 9,10,10,10,
  129359. 10,11,11,10,10,10,10,10,10,10, 9, 9,10,10,10, 9,
  129360. 9,10,10,10,10,10,11,10,11,10,10,10,10,10,10, 9,
  129361. 10,10,10,10,10,10,10,10,10,
  129362. };
  129363. static float _vq_quantthresh__44c7_s_p8_1[] = {
  129364. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  129365. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  129366. 6.5, 7.5, 8.5, 9.5,
  129367. };
  129368. static long _vq_quantmap__44c7_s_p8_1[] = {
  129369. 19, 17, 15, 13, 11, 9, 7, 5,
  129370. 3, 1, 0, 2, 4, 6, 8, 10,
  129371. 12, 14, 16, 18, 20,
  129372. };
  129373. static encode_aux_threshmatch _vq_auxt__44c7_s_p8_1 = {
  129374. _vq_quantthresh__44c7_s_p8_1,
  129375. _vq_quantmap__44c7_s_p8_1,
  129376. 21,
  129377. 21
  129378. };
  129379. static static_codebook _44c7_s_p8_1 = {
  129380. 2, 441,
  129381. _vq_lengthlist__44c7_s_p8_1,
  129382. 1, -529268736, 1611661312, 5, 0,
  129383. _vq_quantlist__44c7_s_p8_1,
  129384. NULL,
  129385. &_vq_auxt__44c7_s_p8_1,
  129386. NULL,
  129387. 0
  129388. };
  129389. static long _vq_quantlist__44c7_s_p9_0[] = {
  129390. 6,
  129391. 5,
  129392. 7,
  129393. 4,
  129394. 8,
  129395. 3,
  129396. 9,
  129397. 2,
  129398. 10,
  129399. 1,
  129400. 11,
  129401. 0,
  129402. 12,
  129403. };
  129404. static long _vq_lengthlist__44c7_s_p9_0[] = {
  129405. 1, 3, 3,11,11,11,11,11,11,11,11,11,11, 4, 6, 6,
  129406. 11,11,11,11,11,11,11,11,11,11, 4, 7, 7,11,11,11,
  129407. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  129408. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  129409. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  129410. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  129411. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  129412. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  129413. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  129414. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  129415. 11,11,11,11,11,11,11,11,11,
  129416. };
  129417. static float _vq_quantthresh__44c7_s_p9_0[] = {
  129418. -3503.5, -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5,
  129419. 1592.5, 2229.5, 2866.5, 3503.5,
  129420. };
  129421. static long _vq_quantmap__44c7_s_p9_0[] = {
  129422. 11, 9, 7, 5, 3, 1, 0, 2,
  129423. 4, 6, 8, 10, 12,
  129424. };
  129425. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_0 = {
  129426. _vq_quantthresh__44c7_s_p9_0,
  129427. _vq_quantmap__44c7_s_p9_0,
  129428. 13,
  129429. 13
  129430. };
  129431. static static_codebook _44c7_s_p9_0 = {
  129432. 2, 169,
  129433. _vq_lengthlist__44c7_s_p9_0,
  129434. 1, -511845376, 1630791680, 4, 0,
  129435. _vq_quantlist__44c7_s_p9_0,
  129436. NULL,
  129437. &_vq_auxt__44c7_s_p9_0,
  129438. NULL,
  129439. 0
  129440. };
  129441. static long _vq_quantlist__44c7_s_p9_1[] = {
  129442. 6,
  129443. 5,
  129444. 7,
  129445. 4,
  129446. 8,
  129447. 3,
  129448. 9,
  129449. 2,
  129450. 10,
  129451. 1,
  129452. 11,
  129453. 0,
  129454. 12,
  129455. };
  129456. static long _vq_lengthlist__44c7_s_p9_1[] = {
  129457. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8, 8, 8, 6, 6, 6,
  129458. 8, 8, 9, 8, 8, 7, 9, 8,11,10, 5, 6, 6, 8, 8, 9,
  129459. 8, 8, 8,10, 9,11,11,16, 8, 8, 9, 8, 9, 9, 9, 8,
  129460. 10, 9,11,10,16, 8, 8, 9, 9,10,10, 9, 9,10,10,11,
  129461. 11,16,13,13, 9, 9,10,10, 9,10,11,11,12,11,16,13,
  129462. 13, 9, 8,10, 9,10,10,10,10,11,11,16,14,16, 8, 9,
  129463. 9, 9,11,10,11,11,12,11,16,16,16, 9, 7,10, 7,11,
  129464. 10,11,11,12,11,16,16,16,12,12, 9,10,11,11,12,11,
  129465. 12,12,16,16,16,12,10,10, 7,11, 8,12,11,12,12,16,
  129466. 16,15,16,16,11,12,10,10,12,11,12,12,16,16,16,15,
  129467. 15,11,11,10,10,12,12,12,12,
  129468. };
  129469. static float _vq_quantthresh__44c7_s_p9_1[] = {
  129470. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  129471. 122.5, 171.5, 220.5, 269.5,
  129472. };
  129473. static long _vq_quantmap__44c7_s_p9_1[] = {
  129474. 11, 9, 7, 5, 3, 1, 0, 2,
  129475. 4, 6, 8, 10, 12,
  129476. };
  129477. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_1 = {
  129478. _vq_quantthresh__44c7_s_p9_1,
  129479. _vq_quantmap__44c7_s_p9_1,
  129480. 13,
  129481. 13
  129482. };
  129483. static static_codebook _44c7_s_p9_1 = {
  129484. 2, 169,
  129485. _vq_lengthlist__44c7_s_p9_1,
  129486. 1, -518889472, 1622704128, 4, 0,
  129487. _vq_quantlist__44c7_s_p9_1,
  129488. NULL,
  129489. &_vq_auxt__44c7_s_p9_1,
  129490. NULL,
  129491. 0
  129492. };
  129493. static long _vq_quantlist__44c7_s_p9_2[] = {
  129494. 24,
  129495. 23,
  129496. 25,
  129497. 22,
  129498. 26,
  129499. 21,
  129500. 27,
  129501. 20,
  129502. 28,
  129503. 19,
  129504. 29,
  129505. 18,
  129506. 30,
  129507. 17,
  129508. 31,
  129509. 16,
  129510. 32,
  129511. 15,
  129512. 33,
  129513. 14,
  129514. 34,
  129515. 13,
  129516. 35,
  129517. 12,
  129518. 36,
  129519. 11,
  129520. 37,
  129521. 10,
  129522. 38,
  129523. 9,
  129524. 39,
  129525. 8,
  129526. 40,
  129527. 7,
  129528. 41,
  129529. 6,
  129530. 42,
  129531. 5,
  129532. 43,
  129533. 4,
  129534. 44,
  129535. 3,
  129536. 45,
  129537. 2,
  129538. 46,
  129539. 1,
  129540. 47,
  129541. 0,
  129542. 48,
  129543. };
  129544. static long _vq_lengthlist__44c7_s_p9_2[] = {
  129545. 2, 4, 3, 4, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  129546. 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  129547. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  129548. 7,
  129549. };
  129550. static float _vq_quantthresh__44c7_s_p9_2[] = {
  129551. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  129552. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  129553. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  129554. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  129555. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  129556. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  129557. };
  129558. static long _vq_quantmap__44c7_s_p9_2[] = {
  129559. 47, 45, 43, 41, 39, 37, 35, 33,
  129560. 31, 29, 27, 25, 23, 21, 19, 17,
  129561. 15, 13, 11, 9, 7, 5, 3, 1,
  129562. 0, 2, 4, 6, 8, 10, 12, 14,
  129563. 16, 18, 20, 22, 24, 26, 28, 30,
  129564. 32, 34, 36, 38, 40, 42, 44, 46,
  129565. 48,
  129566. };
  129567. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_2 = {
  129568. _vq_quantthresh__44c7_s_p9_2,
  129569. _vq_quantmap__44c7_s_p9_2,
  129570. 49,
  129571. 49
  129572. };
  129573. static static_codebook _44c7_s_p9_2 = {
  129574. 1, 49,
  129575. _vq_lengthlist__44c7_s_p9_2,
  129576. 1, -526909440, 1611661312, 6, 0,
  129577. _vq_quantlist__44c7_s_p9_2,
  129578. NULL,
  129579. &_vq_auxt__44c7_s_p9_2,
  129580. NULL,
  129581. 0
  129582. };
  129583. static long _huff_lengthlist__44c7_s_short[] = {
  129584. 4,11,12,14,15,15,17,17,18,18, 5, 6, 6, 8, 9,10,
  129585. 13,17,18,19, 7, 5, 4, 6, 8, 9,11,15,19,19, 8, 6,
  129586. 5, 5, 6, 7,11,14,16,17, 9, 7, 7, 6, 7, 7,10,13,
  129587. 15,19,10, 8, 7, 6, 7, 6, 7, 9,14,16,12,10, 9, 7,
  129588. 7, 6, 4, 5,10,15,14,13,11, 7, 6, 6, 4, 2, 7,13,
  129589. 16,16,15, 9, 8, 8, 8, 6, 9,13,19,19,17,12,11,10,
  129590. 10, 9,11,14,
  129591. };
  129592. static static_codebook _huff_book__44c7_s_short = {
  129593. 2, 100,
  129594. _huff_lengthlist__44c7_s_short,
  129595. 0, 0, 0, 0, 0,
  129596. NULL,
  129597. NULL,
  129598. NULL,
  129599. NULL,
  129600. 0
  129601. };
  129602. static long _huff_lengthlist__44c8_s_long[] = {
  129603. 3, 8,12,13,14,14,14,13,14,14, 6, 4, 5, 8,10,10,
  129604. 11,11,14,13, 9, 5, 4, 5, 7, 8, 9,10,13,13,12, 7,
  129605. 5, 4, 5, 6, 8, 9,12,13,13, 9, 6, 5, 5, 5, 7, 9,
  129606. 11,14,12,10, 7, 6, 5, 4, 6, 7,10,11,12,11, 9, 8,
  129607. 7, 5, 5, 6,10,10,13,12,10, 9, 8, 6, 6, 5, 8,10,
  129608. 14,13,12,12,11,10, 9, 7, 8,10,12,13,14,14,13,12,
  129609. 11, 9, 9,10,
  129610. };
  129611. static static_codebook _huff_book__44c8_s_long = {
  129612. 2, 100,
  129613. _huff_lengthlist__44c8_s_long,
  129614. 0, 0, 0, 0, 0,
  129615. NULL,
  129616. NULL,
  129617. NULL,
  129618. NULL,
  129619. 0
  129620. };
  129621. static long _vq_quantlist__44c8_s_p1_0[] = {
  129622. 1,
  129623. 0,
  129624. 2,
  129625. };
  129626. static long _vq_lengthlist__44c8_s_p1_0[] = {
  129627. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 7, 7, 0, 9, 8, 0,
  129628. 9, 8, 6, 7, 7, 0, 8, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  129629. 0, 0, 0, 0, 5, 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  129630. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  129631. 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9, 0, 8, 8, 0, 8,
  129632. 8,
  129633. };
  129634. static float _vq_quantthresh__44c8_s_p1_0[] = {
  129635. -0.5, 0.5,
  129636. };
  129637. static long _vq_quantmap__44c8_s_p1_0[] = {
  129638. 1, 0, 2,
  129639. };
  129640. static encode_aux_threshmatch _vq_auxt__44c8_s_p1_0 = {
  129641. _vq_quantthresh__44c8_s_p1_0,
  129642. _vq_quantmap__44c8_s_p1_0,
  129643. 3,
  129644. 3
  129645. };
  129646. static static_codebook _44c8_s_p1_0 = {
  129647. 4, 81,
  129648. _vq_lengthlist__44c8_s_p1_0,
  129649. 1, -535822336, 1611661312, 2, 0,
  129650. _vq_quantlist__44c8_s_p1_0,
  129651. NULL,
  129652. &_vq_auxt__44c8_s_p1_0,
  129653. NULL,
  129654. 0
  129655. };
  129656. static long _vq_quantlist__44c8_s_p2_0[] = {
  129657. 2,
  129658. 1,
  129659. 3,
  129660. 0,
  129661. 4,
  129662. };
  129663. static long _vq_lengthlist__44c8_s_p2_0[] = {
  129664. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  129665. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  129666. 7,10, 9, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  129667. 11,11, 5, 7, 7, 9, 9, 0, 7, 8, 9,10, 0, 7, 8, 9,
  129668. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,10,
  129669. 0,11,10,12,11, 0,11,10,12,12, 0,13,13,14,14, 0,
  129670. 0, 0,14,13, 8, 9, 9,10,11, 0,10,11,12,12, 0,10,
  129671. 11,12,12, 0,13,13,14,14, 0, 0, 0,13,14, 0, 0, 0,
  129672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129673. 0, 0, 0, 0, 0, 0, 5, 8, 7,11,10, 0, 7, 7,10,10,
  129674. 0, 7, 7,10,10, 0, 9, 9,10,10, 0, 0, 0,11,10, 5,
  129675. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  129676. 9,10,10, 0, 0, 0,10,10, 8,10, 9,12,12, 0,10,10,
  129677. 12,11, 0,10,10,12,12, 0,12,12,13,12, 0, 0, 0,13,
  129678. 12, 8, 9,10,12,12, 0,10,10,11,12, 0,10,10,11,12,
  129679. 0,12,12,13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0,
  129680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129681. 0, 0, 0, 6, 8, 7,11,10, 0, 7, 7,10,10, 0, 7, 7,
  129682. 10,10, 0, 9, 9,10,11, 0, 0, 0,10,10, 6, 7, 8,10,
  129683. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,10,10,
  129684. 0, 0, 0,10,10, 9,10, 9,12,12, 0,10,10,12,12, 0,
  129685. 10,10,12,11, 0,12,12,13,13, 0, 0, 0,13,12, 8, 9,
  129686. 10,12,12, 0,10,10,12,12, 0,10,10,11,12, 0,12,12,
  129687. 13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129689. 7,10,10,13,13, 0, 9, 9,12,12, 0, 9, 9,12,12, 0,
  129690. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,13, 0, 9,
  129691. 9,12,12, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  129692. 12,12, 9,11,11,14,13, 0,10,10,13,12, 0,11,10,13,
  129693. 12, 0,12,12,13,12, 0, 0, 0,13,13, 9,11,11,13,14,
  129694. 0,10,11,12,13, 0,10,11,13,13, 0,12,12,12,13, 0,
  129695. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  129700. 11,11,14,14, 0,10,11,13,13, 0,11,10,13,13, 0,11,
  129701. 12,13,13, 0, 0, 0,13,12, 9,11,11,14,14, 0,11,10,
  129702. 13,13, 0,10,11,13,13, 0,12,12,13,13, 0, 0, 0,12,
  129703. 13,
  129704. };
  129705. static float _vq_quantthresh__44c8_s_p2_0[] = {
  129706. -1.5, -0.5, 0.5, 1.5,
  129707. };
  129708. static long _vq_quantmap__44c8_s_p2_0[] = {
  129709. 3, 1, 0, 2, 4,
  129710. };
  129711. static encode_aux_threshmatch _vq_auxt__44c8_s_p2_0 = {
  129712. _vq_quantthresh__44c8_s_p2_0,
  129713. _vq_quantmap__44c8_s_p2_0,
  129714. 5,
  129715. 5
  129716. };
  129717. static static_codebook _44c8_s_p2_0 = {
  129718. 4, 625,
  129719. _vq_lengthlist__44c8_s_p2_0,
  129720. 1, -533725184, 1611661312, 3, 0,
  129721. _vq_quantlist__44c8_s_p2_0,
  129722. NULL,
  129723. &_vq_auxt__44c8_s_p2_0,
  129724. NULL,
  129725. 0
  129726. };
  129727. static long _vq_quantlist__44c8_s_p3_0[] = {
  129728. 4,
  129729. 3,
  129730. 5,
  129731. 2,
  129732. 6,
  129733. 1,
  129734. 7,
  129735. 0,
  129736. 8,
  129737. };
  129738. static long _vq_lengthlist__44c8_s_p3_0[] = {
  129739. 2, 4, 4, 5, 5, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  129740. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 6, 6,
  129741. 8, 8,10,10, 0, 0, 0, 6, 6, 8, 8,10,10, 0, 0, 0,
  129742. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0,
  129743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129744. 0,
  129745. };
  129746. static float _vq_quantthresh__44c8_s_p3_0[] = {
  129747. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  129748. };
  129749. static long _vq_quantmap__44c8_s_p3_0[] = {
  129750. 7, 5, 3, 1, 0, 2, 4, 6,
  129751. 8,
  129752. };
  129753. static encode_aux_threshmatch _vq_auxt__44c8_s_p3_0 = {
  129754. _vq_quantthresh__44c8_s_p3_0,
  129755. _vq_quantmap__44c8_s_p3_0,
  129756. 9,
  129757. 9
  129758. };
  129759. static static_codebook _44c8_s_p3_0 = {
  129760. 2, 81,
  129761. _vq_lengthlist__44c8_s_p3_0,
  129762. 1, -531628032, 1611661312, 4, 0,
  129763. _vq_quantlist__44c8_s_p3_0,
  129764. NULL,
  129765. &_vq_auxt__44c8_s_p3_0,
  129766. NULL,
  129767. 0
  129768. };
  129769. static long _vq_quantlist__44c8_s_p4_0[] = {
  129770. 8,
  129771. 7,
  129772. 9,
  129773. 6,
  129774. 10,
  129775. 5,
  129776. 11,
  129777. 4,
  129778. 12,
  129779. 3,
  129780. 13,
  129781. 2,
  129782. 14,
  129783. 1,
  129784. 15,
  129785. 0,
  129786. 16,
  129787. };
  129788. static long _vq_lengthlist__44c8_s_p4_0[] = {
  129789. 3, 4, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  129790. 11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 8,10,10,11,11,
  129791. 11,11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  129792. 11,11,11, 0, 6, 5, 6, 6, 7, 7, 9, 9, 9, 9,10,10,
  129793. 11,11,12,12, 0, 0, 0, 6, 6, 7, 7, 9, 9, 9, 9,10,
  129794. 10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,
  129795. 11,11,11,12,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,
  129796. 10,11,11,11,12,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  129797. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  129798. 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 0, 0,
  129799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129807. 0,
  129808. };
  129809. static float _vq_quantthresh__44c8_s_p4_0[] = {
  129810. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  129811. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  129812. };
  129813. static long _vq_quantmap__44c8_s_p4_0[] = {
  129814. 15, 13, 11, 9, 7, 5, 3, 1,
  129815. 0, 2, 4, 6, 8, 10, 12, 14,
  129816. 16,
  129817. };
  129818. static encode_aux_threshmatch _vq_auxt__44c8_s_p4_0 = {
  129819. _vq_quantthresh__44c8_s_p4_0,
  129820. _vq_quantmap__44c8_s_p4_0,
  129821. 17,
  129822. 17
  129823. };
  129824. static static_codebook _44c8_s_p4_0 = {
  129825. 2, 289,
  129826. _vq_lengthlist__44c8_s_p4_0,
  129827. 1, -529530880, 1611661312, 5, 0,
  129828. _vq_quantlist__44c8_s_p4_0,
  129829. NULL,
  129830. &_vq_auxt__44c8_s_p4_0,
  129831. NULL,
  129832. 0
  129833. };
  129834. static long _vq_quantlist__44c8_s_p5_0[] = {
  129835. 1,
  129836. 0,
  129837. 2,
  129838. };
  129839. static long _vq_lengthlist__44c8_s_p5_0[] = {
  129840. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 7, 6,10,10,10,10,
  129841. 10,10, 4, 6, 6,10,10,10,10, 9,10, 5,10,10, 9,11,
  129842. 11,10,11,11, 7,10,10,11,12,12,12,12,12, 7,10,10,
  129843. 11,12,12,12,12,12, 6,10,10,10,12,12,10,12,12, 7,
  129844. 10,10,11,12,12,12,12,12, 7,10,10,11,12,12,12,12,
  129845. 12,
  129846. };
  129847. static float _vq_quantthresh__44c8_s_p5_0[] = {
  129848. -5.5, 5.5,
  129849. };
  129850. static long _vq_quantmap__44c8_s_p5_0[] = {
  129851. 1, 0, 2,
  129852. };
  129853. static encode_aux_threshmatch _vq_auxt__44c8_s_p5_0 = {
  129854. _vq_quantthresh__44c8_s_p5_0,
  129855. _vq_quantmap__44c8_s_p5_0,
  129856. 3,
  129857. 3
  129858. };
  129859. static static_codebook _44c8_s_p5_0 = {
  129860. 4, 81,
  129861. _vq_lengthlist__44c8_s_p5_0,
  129862. 1, -529137664, 1618345984, 2, 0,
  129863. _vq_quantlist__44c8_s_p5_0,
  129864. NULL,
  129865. &_vq_auxt__44c8_s_p5_0,
  129866. NULL,
  129867. 0
  129868. };
  129869. static long _vq_quantlist__44c8_s_p5_1[] = {
  129870. 5,
  129871. 4,
  129872. 6,
  129873. 3,
  129874. 7,
  129875. 2,
  129876. 8,
  129877. 1,
  129878. 9,
  129879. 0,
  129880. 10,
  129881. };
  129882. static long _vq_lengthlist__44c8_s_p5_1[] = {
  129883. 3, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 5, 6, 6,
  129884. 7, 7, 8, 8, 8, 8,11, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  129885. 9,12, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,12,12,12, 6,
  129886. 6, 7, 7, 8, 8, 9, 9,11,11,11, 6, 6, 7, 7, 8, 8,
  129887. 8, 8,11,11,11, 6, 6, 7, 7, 8, 8, 8, 8,11,11,11,
  129888. 7, 7, 7, 8, 8, 8, 8, 8,11,11,11,11,11, 7, 7, 8,
  129889. 8, 8, 8,11,11,11,11,11, 7, 7, 7, 7, 8, 8,11,11,
  129890. 11,11,11, 7, 7, 7, 7, 8, 8,
  129891. };
  129892. static float _vq_quantthresh__44c8_s_p5_1[] = {
  129893. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  129894. 3.5, 4.5,
  129895. };
  129896. static long _vq_quantmap__44c8_s_p5_1[] = {
  129897. 9, 7, 5, 3, 1, 0, 2, 4,
  129898. 6, 8, 10,
  129899. };
  129900. static encode_aux_threshmatch _vq_auxt__44c8_s_p5_1 = {
  129901. _vq_quantthresh__44c8_s_p5_1,
  129902. _vq_quantmap__44c8_s_p5_1,
  129903. 11,
  129904. 11
  129905. };
  129906. static static_codebook _44c8_s_p5_1 = {
  129907. 2, 121,
  129908. _vq_lengthlist__44c8_s_p5_1,
  129909. 1, -531365888, 1611661312, 4, 0,
  129910. _vq_quantlist__44c8_s_p5_1,
  129911. NULL,
  129912. &_vq_auxt__44c8_s_p5_1,
  129913. NULL,
  129914. 0
  129915. };
  129916. static long _vq_quantlist__44c8_s_p6_0[] = {
  129917. 6,
  129918. 5,
  129919. 7,
  129920. 4,
  129921. 8,
  129922. 3,
  129923. 9,
  129924. 2,
  129925. 10,
  129926. 1,
  129927. 11,
  129928. 0,
  129929. 12,
  129930. };
  129931. static long _vq_lengthlist__44c8_s_p6_0[] = {
  129932. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  129933. 7, 7, 8, 8, 9, 9,10,10,11,11, 6, 5, 5, 7, 7, 8,
  129934. 8, 9, 9,10,10,11,11, 0, 7, 7, 7, 7, 9, 9,10,10,
  129935. 10,10,11,11, 0, 7, 7, 7, 7, 9, 9,10,10,10,10,11,
  129936. 11, 0,11,11, 9, 9,10,10,11,11,11,11,12,12, 0,12,
  129937. 12, 9, 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0,
  129938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129942. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129943. };
  129944. static float _vq_quantthresh__44c8_s_p6_0[] = {
  129945. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  129946. 12.5, 17.5, 22.5, 27.5,
  129947. };
  129948. static long _vq_quantmap__44c8_s_p6_0[] = {
  129949. 11, 9, 7, 5, 3, 1, 0, 2,
  129950. 4, 6, 8, 10, 12,
  129951. };
  129952. static encode_aux_threshmatch _vq_auxt__44c8_s_p6_0 = {
  129953. _vq_quantthresh__44c8_s_p6_0,
  129954. _vq_quantmap__44c8_s_p6_0,
  129955. 13,
  129956. 13
  129957. };
  129958. static static_codebook _44c8_s_p6_0 = {
  129959. 2, 169,
  129960. _vq_lengthlist__44c8_s_p6_0,
  129961. 1, -526516224, 1616117760, 4, 0,
  129962. _vq_quantlist__44c8_s_p6_0,
  129963. NULL,
  129964. &_vq_auxt__44c8_s_p6_0,
  129965. NULL,
  129966. 0
  129967. };
  129968. static long _vq_quantlist__44c8_s_p6_1[] = {
  129969. 2,
  129970. 1,
  129971. 3,
  129972. 0,
  129973. 4,
  129974. };
  129975. static long _vq_lengthlist__44c8_s_p6_1[] = {
  129976. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  129977. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  129978. };
  129979. static float _vq_quantthresh__44c8_s_p6_1[] = {
  129980. -1.5, -0.5, 0.5, 1.5,
  129981. };
  129982. static long _vq_quantmap__44c8_s_p6_1[] = {
  129983. 3, 1, 0, 2, 4,
  129984. };
  129985. static encode_aux_threshmatch _vq_auxt__44c8_s_p6_1 = {
  129986. _vq_quantthresh__44c8_s_p6_1,
  129987. _vq_quantmap__44c8_s_p6_1,
  129988. 5,
  129989. 5
  129990. };
  129991. static static_codebook _44c8_s_p6_1 = {
  129992. 2, 25,
  129993. _vq_lengthlist__44c8_s_p6_1,
  129994. 1, -533725184, 1611661312, 3, 0,
  129995. _vq_quantlist__44c8_s_p6_1,
  129996. NULL,
  129997. &_vq_auxt__44c8_s_p6_1,
  129998. NULL,
  129999. 0
  130000. };
  130001. static long _vq_quantlist__44c8_s_p7_0[] = {
  130002. 6,
  130003. 5,
  130004. 7,
  130005. 4,
  130006. 8,
  130007. 3,
  130008. 9,
  130009. 2,
  130010. 10,
  130011. 1,
  130012. 11,
  130013. 0,
  130014. 12,
  130015. };
  130016. static long _vq_lengthlist__44c8_s_p7_0[] = {
  130017. 1, 4, 4, 6, 6, 8, 7, 9, 9,10,10,12,12, 6, 5, 5,
  130018. 7, 7, 8, 8,10,10,11,11,12,12, 7, 5, 5, 7, 7, 8,
  130019. 8,10,10,11,11,12,12,21, 7, 7, 7, 7, 8, 9,10,10,
  130020. 11,11,12,12,21, 7, 7, 7, 7, 9, 9,10,10,12,12,13,
  130021. 13,21,11,11, 8, 8, 9, 9,11,11,12,12,13,13,21,11,
  130022. 11, 8, 8, 9, 9,11,11,12,12,13,13,21,21,21,10,10,
  130023. 10,10,11,11,12,13,13,13,21,21,21,10,10,10,10,11,
  130024. 11,13,13,14,13,21,21,21,13,13,11,11,12,12,13,13,
  130025. 14,14,21,21,21,14,14,11,11,12,12,13,13,14,14,21,
  130026. 21,21,21,20,13,13,13,12,14,14,16,15,20,20,20,20,
  130027. 20,13,13,13,13,14,13,15,15,
  130028. };
  130029. static float _vq_quantthresh__44c8_s_p7_0[] = {
  130030. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  130031. 27.5, 38.5, 49.5, 60.5,
  130032. };
  130033. static long _vq_quantmap__44c8_s_p7_0[] = {
  130034. 11, 9, 7, 5, 3, 1, 0, 2,
  130035. 4, 6, 8, 10, 12,
  130036. };
  130037. static encode_aux_threshmatch _vq_auxt__44c8_s_p7_0 = {
  130038. _vq_quantthresh__44c8_s_p7_0,
  130039. _vq_quantmap__44c8_s_p7_0,
  130040. 13,
  130041. 13
  130042. };
  130043. static static_codebook _44c8_s_p7_0 = {
  130044. 2, 169,
  130045. _vq_lengthlist__44c8_s_p7_0,
  130046. 1, -523206656, 1618345984, 4, 0,
  130047. _vq_quantlist__44c8_s_p7_0,
  130048. NULL,
  130049. &_vq_auxt__44c8_s_p7_0,
  130050. NULL,
  130051. 0
  130052. };
  130053. static long _vq_quantlist__44c8_s_p7_1[] = {
  130054. 5,
  130055. 4,
  130056. 6,
  130057. 3,
  130058. 7,
  130059. 2,
  130060. 8,
  130061. 1,
  130062. 9,
  130063. 0,
  130064. 10,
  130065. };
  130066. static long _vq_lengthlist__44c8_s_p7_1[] = {
  130067. 4, 5, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 7,
  130068. 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  130069. 7, 8, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7,
  130070. 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  130071. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  130072. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  130073. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  130074. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  130075. };
  130076. static float _vq_quantthresh__44c8_s_p7_1[] = {
  130077. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  130078. 3.5, 4.5,
  130079. };
  130080. static long _vq_quantmap__44c8_s_p7_1[] = {
  130081. 9, 7, 5, 3, 1, 0, 2, 4,
  130082. 6, 8, 10,
  130083. };
  130084. static encode_aux_threshmatch _vq_auxt__44c8_s_p7_1 = {
  130085. _vq_quantthresh__44c8_s_p7_1,
  130086. _vq_quantmap__44c8_s_p7_1,
  130087. 11,
  130088. 11
  130089. };
  130090. static static_codebook _44c8_s_p7_1 = {
  130091. 2, 121,
  130092. _vq_lengthlist__44c8_s_p7_1,
  130093. 1, -531365888, 1611661312, 4, 0,
  130094. _vq_quantlist__44c8_s_p7_1,
  130095. NULL,
  130096. &_vq_auxt__44c8_s_p7_1,
  130097. NULL,
  130098. 0
  130099. };
  130100. static long _vq_quantlist__44c8_s_p8_0[] = {
  130101. 7,
  130102. 6,
  130103. 8,
  130104. 5,
  130105. 9,
  130106. 4,
  130107. 10,
  130108. 3,
  130109. 11,
  130110. 2,
  130111. 12,
  130112. 1,
  130113. 13,
  130114. 0,
  130115. 14,
  130116. };
  130117. static long _vq_lengthlist__44c8_s_p8_0[] = {
  130118. 1, 4, 4, 7, 6, 8, 8, 8, 7, 9, 8,10,10,11,10, 6,
  130119. 5, 5, 7, 7, 9, 9, 8, 8,10,10,11,11,12,11, 6, 5,
  130120. 5, 7, 7, 9, 9, 9, 9,10,10,11,11,12,12,20, 8, 8,
  130121. 8, 8, 9, 9, 9, 9,10,10,11,11,12,12,20, 8, 8, 8,
  130122. 8,10, 9, 9, 9,10,10,11,11,12,12,20,12,12, 9, 9,
  130123. 10,10,10,10,10,11,12,12,12,12,20,12,12, 9, 9,10,
  130124. 10,10,10,11,11,12,12,13,13,20,20,20, 9, 9, 9, 9,
  130125. 11,10,11,11,12,12,12,13,20,19,19, 9, 9, 9, 9,11,
  130126. 11,11,12,12,12,13,13,19,19,19,13,13,10,10,11,11,
  130127. 12,12,13,13,13,13,19,19,19,14,13,11,10,11,11,12,
  130128. 12,12,13,13,13,19,19,19,19,19,12,12,12,12,13,13,
  130129. 13,13,14,13,19,19,19,19,19,12,12,12,11,12,12,13,
  130130. 14,14,14,19,19,19,19,19,16,15,13,12,13,13,13,14,
  130131. 14,14,19,19,19,19,19,17,17,13,12,13,11,14,13,15,
  130132. 15,
  130133. };
  130134. static float _vq_quantthresh__44c8_s_p8_0[] = {
  130135. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  130136. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  130137. };
  130138. static long _vq_quantmap__44c8_s_p8_0[] = {
  130139. 13, 11, 9, 7, 5, 3, 1, 0,
  130140. 2, 4, 6, 8, 10, 12, 14,
  130141. };
  130142. static encode_aux_threshmatch _vq_auxt__44c8_s_p8_0 = {
  130143. _vq_quantthresh__44c8_s_p8_0,
  130144. _vq_quantmap__44c8_s_p8_0,
  130145. 15,
  130146. 15
  130147. };
  130148. static static_codebook _44c8_s_p8_0 = {
  130149. 2, 225,
  130150. _vq_lengthlist__44c8_s_p8_0,
  130151. 1, -520986624, 1620377600, 4, 0,
  130152. _vq_quantlist__44c8_s_p8_0,
  130153. NULL,
  130154. &_vq_auxt__44c8_s_p8_0,
  130155. NULL,
  130156. 0
  130157. };
  130158. static long _vq_quantlist__44c8_s_p8_1[] = {
  130159. 10,
  130160. 9,
  130161. 11,
  130162. 8,
  130163. 12,
  130164. 7,
  130165. 13,
  130166. 6,
  130167. 14,
  130168. 5,
  130169. 15,
  130170. 4,
  130171. 16,
  130172. 3,
  130173. 17,
  130174. 2,
  130175. 18,
  130176. 1,
  130177. 19,
  130178. 0,
  130179. 20,
  130180. };
  130181. static long _vq_lengthlist__44c8_s_p8_1[] = {
  130182. 4, 5, 5, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  130183. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  130184. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  130185. 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  130186. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  130187. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  130188. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 9,
  130189. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  130190. 10, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  130191. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  130192. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  130193. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  130194. 10,10, 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9, 9, 9,
  130195. 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  130196. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9,
  130197. 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,10,10,10,10,
  130198. 10,10,10, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  130199. 9,10,10,10,10,10,10,10, 9,10,10, 9,10,10,10,10,
  130200. 9,10, 9,10,10, 9,10,10,10,10,10,10,10, 9,10,10,
  130201. 10,10,10,10, 9, 9,10,10, 9,10,10,10,10,10,10,10,
  130202. 10,10,10,10,10,10,10,10, 9, 9, 9,10, 9, 9, 9, 9,
  130203. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  130204. 10, 9,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  130205. 10,10,10,10, 9, 9,10, 9, 9, 9,10,10,10,10,10,10,
  130206. 10,10,10,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9,10,10,
  130207. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9,10, 9,
  130208. 9,10, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  130209. 10, 9, 9,10,10, 9,10, 9, 9,
  130210. };
  130211. static float _vq_quantthresh__44c8_s_p8_1[] = {
  130212. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  130213. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  130214. 6.5, 7.5, 8.5, 9.5,
  130215. };
  130216. static long _vq_quantmap__44c8_s_p8_1[] = {
  130217. 19, 17, 15, 13, 11, 9, 7, 5,
  130218. 3, 1, 0, 2, 4, 6, 8, 10,
  130219. 12, 14, 16, 18, 20,
  130220. };
  130221. static encode_aux_threshmatch _vq_auxt__44c8_s_p8_1 = {
  130222. _vq_quantthresh__44c8_s_p8_1,
  130223. _vq_quantmap__44c8_s_p8_1,
  130224. 21,
  130225. 21
  130226. };
  130227. static static_codebook _44c8_s_p8_1 = {
  130228. 2, 441,
  130229. _vq_lengthlist__44c8_s_p8_1,
  130230. 1, -529268736, 1611661312, 5, 0,
  130231. _vq_quantlist__44c8_s_p8_1,
  130232. NULL,
  130233. &_vq_auxt__44c8_s_p8_1,
  130234. NULL,
  130235. 0
  130236. };
  130237. static long _vq_quantlist__44c8_s_p9_0[] = {
  130238. 8,
  130239. 7,
  130240. 9,
  130241. 6,
  130242. 10,
  130243. 5,
  130244. 11,
  130245. 4,
  130246. 12,
  130247. 3,
  130248. 13,
  130249. 2,
  130250. 14,
  130251. 1,
  130252. 15,
  130253. 0,
  130254. 16,
  130255. };
  130256. static long _vq_lengthlist__44c8_s_p9_0[] = {
  130257. 1, 4, 3,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130258. 11, 4, 7, 7,11,11,11,11,11,11,11,11,11,11,11,11,
  130259. 11,11, 4, 8,11,11,11,11,11,11,11,11,11,11,11,11,
  130260. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130261. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130262. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130263. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130264. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130265. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130266. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130267. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130268. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130269. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130270. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130271. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  130272. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  130273. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  130274. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  130275. 10,
  130276. };
  130277. static float _vq_quantthresh__44c8_s_p9_0[] = {
  130278. -6982.5, -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5,
  130279. 465.5, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5, 6982.5,
  130280. };
  130281. static long _vq_quantmap__44c8_s_p9_0[] = {
  130282. 15, 13, 11, 9, 7, 5, 3, 1,
  130283. 0, 2, 4, 6, 8, 10, 12, 14,
  130284. 16,
  130285. };
  130286. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_0 = {
  130287. _vq_quantthresh__44c8_s_p9_0,
  130288. _vq_quantmap__44c8_s_p9_0,
  130289. 17,
  130290. 17
  130291. };
  130292. static static_codebook _44c8_s_p9_0 = {
  130293. 2, 289,
  130294. _vq_lengthlist__44c8_s_p9_0,
  130295. 1, -509798400, 1631393792, 5, 0,
  130296. _vq_quantlist__44c8_s_p9_0,
  130297. NULL,
  130298. &_vq_auxt__44c8_s_p9_0,
  130299. NULL,
  130300. 0
  130301. };
  130302. static long _vq_quantlist__44c8_s_p9_1[] = {
  130303. 9,
  130304. 8,
  130305. 10,
  130306. 7,
  130307. 11,
  130308. 6,
  130309. 12,
  130310. 5,
  130311. 13,
  130312. 4,
  130313. 14,
  130314. 3,
  130315. 15,
  130316. 2,
  130317. 16,
  130318. 1,
  130319. 17,
  130320. 0,
  130321. 18,
  130322. };
  130323. static long _vq_lengthlist__44c8_s_p9_1[] = {
  130324. 1, 4, 4, 7, 6, 7, 7, 7, 7, 8, 8, 9, 9,10,10,10,
  130325. 10,11,11, 6, 6, 6, 8, 8, 9, 8, 8, 7,10, 8,11,10,
  130326. 12,11,12,12,13,13, 5, 5, 6, 8, 8, 9, 9, 8, 8,10,
  130327. 9,11,11,12,12,13,13,13,13,17, 8, 8, 9, 9, 9, 9,
  130328. 9, 9,10, 9,12,10,12,12,13,12,13,13,17, 9, 8, 9,
  130329. 9, 9, 9, 9, 9,10,10,12,12,12,12,13,13,13,13,17,
  130330. 13,13, 9, 9,10,10,10,10,11,11,12,11,13,12,13,13,
  130331. 14,15,17,13,13, 9, 8,10, 9,10,10,11,11,12,12,14,
  130332. 13,15,13,14,15,17,17,17, 9,10, 9,10,11,11,12,12,
  130333. 12,12,13,13,14,14,15,15,17,17,17, 9, 8, 9, 8,11,
  130334. 11,12,12,12,12,14,13,14,14,14,15,17,17,17,12,14,
  130335. 9,10,11,11,12,12,14,13,13,14,15,13,15,15,17,17,
  130336. 17,13,11,10, 8,11, 9,13,12,13,13,13,13,13,14,14,
  130337. 14,17,17,17,17,17,11,12,11,11,13,13,14,13,15,14,
  130338. 13,15,16,15,17,17,17,17,17,11,11,12, 8,13,12,14,
  130339. 13,17,14,15,14,15,14,17,17,17,17,17,15,15,12,12,
  130340. 12,12,13,14,14,14,15,14,17,14,17,17,17,17,17,16,
  130341. 17,12,12,13,12,13,13,14,14,14,14,14,14,17,17,17,
  130342. 17,17,17,17,14,14,13,12,13,13,15,15,14,13,15,17,
  130343. 17,17,17,17,17,17,17,13,14,13,13,13,13,14,15,15,
  130344. 15,14,15,17,17,17,17,17,17,17,16,15,13,14,13,13,
  130345. 14,14,15,14,14,16,17,17,17,17,17,17,17,16,16,13,
  130346. 14,13,13,14,14,15,14,15,14,
  130347. };
  130348. static float _vq_quantthresh__44c8_s_p9_1[] = {
  130349. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  130350. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  130351. 367.5, 416.5,
  130352. };
  130353. static long _vq_quantmap__44c8_s_p9_1[] = {
  130354. 17, 15, 13, 11, 9, 7, 5, 3,
  130355. 1, 0, 2, 4, 6, 8, 10, 12,
  130356. 14, 16, 18,
  130357. };
  130358. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_1 = {
  130359. _vq_quantthresh__44c8_s_p9_1,
  130360. _vq_quantmap__44c8_s_p9_1,
  130361. 19,
  130362. 19
  130363. };
  130364. static static_codebook _44c8_s_p9_1 = {
  130365. 2, 361,
  130366. _vq_lengthlist__44c8_s_p9_1,
  130367. 1, -518287360, 1622704128, 5, 0,
  130368. _vq_quantlist__44c8_s_p9_1,
  130369. NULL,
  130370. &_vq_auxt__44c8_s_p9_1,
  130371. NULL,
  130372. 0
  130373. };
  130374. static long _vq_quantlist__44c8_s_p9_2[] = {
  130375. 24,
  130376. 23,
  130377. 25,
  130378. 22,
  130379. 26,
  130380. 21,
  130381. 27,
  130382. 20,
  130383. 28,
  130384. 19,
  130385. 29,
  130386. 18,
  130387. 30,
  130388. 17,
  130389. 31,
  130390. 16,
  130391. 32,
  130392. 15,
  130393. 33,
  130394. 14,
  130395. 34,
  130396. 13,
  130397. 35,
  130398. 12,
  130399. 36,
  130400. 11,
  130401. 37,
  130402. 10,
  130403. 38,
  130404. 9,
  130405. 39,
  130406. 8,
  130407. 40,
  130408. 7,
  130409. 41,
  130410. 6,
  130411. 42,
  130412. 5,
  130413. 43,
  130414. 4,
  130415. 44,
  130416. 3,
  130417. 45,
  130418. 2,
  130419. 46,
  130420. 1,
  130421. 47,
  130422. 0,
  130423. 48,
  130424. };
  130425. static long _vq_lengthlist__44c8_s_p9_2[] = {
  130426. 2, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  130427. 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  130428. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  130429. 7,
  130430. };
  130431. static float _vq_quantthresh__44c8_s_p9_2[] = {
  130432. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  130433. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  130434. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  130435. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  130436. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  130437. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  130438. };
  130439. static long _vq_quantmap__44c8_s_p9_2[] = {
  130440. 47, 45, 43, 41, 39, 37, 35, 33,
  130441. 31, 29, 27, 25, 23, 21, 19, 17,
  130442. 15, 13, 11, 9, 7, 5, 3, 1,
  130443. 0, 2, 4, 6, 8, 10, 12, 14,
  130444. 16, 18, 20, 22, 24, 26, 28, 30,
  130445. 32, 34, 36, 38, 40, 42, 44, 46,
  130446. 48,
  130447. };
  130448. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_2 = {
  130449. _vq_quantthresh__44c8_s_p9_2,
  130450. _vq_quantmap__44c8_s_p9_2,
  130451. 49,
  130452. 49
  130453. };
  130454. static static_codebook _44c8_s_p9_2 = {
  130455. 1, 49,
  130456. _vq_lengthlist__44c8_s_p9_2,
  130457. 1, -526909440, 1611661312, 6, 0,
  130458. _vq_quantlist__44c8_s_p9_2,
  130459. NULL,
  130460. &_vq_auxt__44c8_s_p9_2,
  130461. NULL,
  130462. 0
  130463. };
  130464. static long _huff_lengthlist__44c8_s_short[] = {
  130465. 4,11,13,14,15,15,18,17,19,17, 5, 6, 8, 9,10,10,
  130466. 12,15,19,19, 6, 6, 6, 6, 8, 8,11,14,18,19, 8, 6,
  130467. 5, 4, 6, 7,10,13,16,17, 9, 7, 6, 5, 6, 7, 9,12,
  130468. 15,19,10, 8, 7, 6, 6, 6, 7, 9,13,15,12,10, 9, 8,
  130469. 7, 6, 4, 5,10,15,13,13,11, 8, 6, 6, 4, 2, 7,12,
  130470. 17,15,16,10, 8, 8, 7, 6, 9,12,19,18,17,13,11,10,
  130471. 10, 9,11,14,
  130472. };
  130473. static static_codebook _huff_book__44c8_s_short = {
  130474. 2, 100,
  130475. _huff_lengthlist__44c8_s_short,
  130476. 0, 0, 0, 0, 0,
  130477. NULL,
  130478. NULL,
  130479. NULL,
  130480. NULL,
  130481. 0
  130482. };
  130483. static long _huff_lengthlist__44c9_s_long[] = {
  130484. 3, 8,12,14,15,15,15,13,15,15, 6, 5, 8,10,12,12,
  130485. 13,12,14,13,10, 6, 5, 6, 8, 9,11,11,13,13,13, 8,
  130486. 5, 4, 5, 6, 8,10,11,13,14,10, 7, 5, 4, 5, 7, 9,
  130487. 11,12,13,11, 8, 6, 5, 4, 5, 7, 9,11,12,11,10, 8,
  130488. 7, 5, 4, 5, 9,10,13,13,11,10, 8, 6, 5, 4, 7, 9,
  130489. 15,14,13,12,10, 9, 8, 7, 8, 9,12,12,14,13,12,11,
  130490. 10, 9, 8, 9,
  130491. };
  130492. static static_codebook _huff_book__44c9_s_long = {
  130493. 2, 100,
  130494. _huff_lengthlist__44c9_s_long,
  130495. 0, 0, 0, 0, 0,
  130496. NULL,
  130497. NULL,
  130498. NULL,
  130499. NULL,
  130500. 0
  130501. };
  130502. static long _vq_quantlist__44c9_s_p1_0[] = {
  130503. 1,
  130504. 0,
  130505. 2,
  130506. };
  130507. static long _vq_lengthlist__44c9_s_p1_0[] = {
  130508. 1, 5, 5, 0, 5, 5, 0, 5, 5, 6, 8, 8, 0, 9, 8, 0,
  130509. 9, 8, 6, 8, 8, 0, 8, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  130510. 0, 0, 0, 0, 5, 8, 8, 0, 7, 7, 0, 8, 8, 5, 8, 8,
  130511. 0, 7, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  130512. 9, 8, 0, 8, 8, 0, 7, 7, 5, 8, 9, 0, 8, 8, 0, 7,
  130513. 7,
  130514. };
  130515. static float _vq_quantthresh__44c9_s_p1_0[] = {
  130516. -0.5, 0.5,
  130517. };
  130518. static long _vq_quantmap__44c9_s_p1_0[] = {
  130519. 1, 0, 2,
  130520. };
  130521. static encode_aux_threshmatch _vq_auxt__44c9_s_p1_0 = {
  130522. _vq_quantthresh__44c9_s_p1_0,
  130523. _vq_quantmap__44c9_s_p1_0,
  130524. 3,
  130525. 3
  130526. };
  130527. static static_codebook _44c9_s_p1_0 = {
  130528. 4, 81,
  130529. _vq_lengthlist__44c9_s_p1_0,
  130530. 1, -535822336, 1611661312, 2, 0,
  130531. _vq_quantlist__44c9_s_p1_0,
  130532. NULL,
  130533. &_vq_auxt__44c9_s_p1_0,
  130534. NULL,
  130535. 0
  130536. };
  130537. static long _vq_quantlist__44c9_s_p2_0[] = {
  130538. 2,
  130539. 1,
  130540. 3,
  130541. 0,
  130542. 4,
  130543. };
  130544. static long _vq_lengthlist__44c9_s_p2_0[] = {
  130545. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  130546. 7, 7, 9, 9, 0, 0, 0, 9, 9, 6, 7, 7, 9, 8, 0, 8,
  130547. 8, 9, 9, 0, 8, 7, 9, 9, 0, 9,10,10,10, 0, 0, 0,
  130548. 11,10, 6, 7, 7, 8, 9, 0, 8, 8, 9, 9, 0, 7, 8, 9,
  130549. 9, 0,10, 9,11,10, 0, 0, 0,10,10, 8, 9, 8,10,10,
  130550. 0,10,10,12,11, 0,10,10,11,11, 0,12,13,13,13, 0,
  130551. 0, 0,13,12, 8, 8, 9,10,10, 0,10,10,11,12, 0,10,
  130552. 10,11,11, 0,13,12,13,13, 0, 0, 0,13,13, 0, 0, 0,
  130553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130554. 0, 0, 0, 0, 0, 0, 6, 8, 7,10,10, 0, 7, 7,10, 9,
  130555. 0, 7, 7,10,10, 0, 9, 9,10,10, 0, 0, 0,10,10, 6,
  130556. 7, 8,10,10, 0, 7, 7, 9,10, 0, 7, 7,10,10, 0, 9,
  130557. 9,10,10, 0, 0, 0,10,10, 8, 9, 9,11,11, 0,10,10,
  130558. 11,11, 0,10,10,11,11, 0,12,12,12,12, 0, 0, 0,12,
  130559. 12, 8, 9,10,11,11, 0, 9,10,11,11, 0,10,10,11,11,
  130560. 0,12,12,12,12, 0, 0, 0,12,12, 0, 0, 0, 0, 0, 0,
  130561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130562. 0, 0, 0, 5, 8, 7,10,10, 0, 7, 7,10,10, 0, 7, 7,
  130563. 10, 9, 0, 9, 9,10,10, 0, 0, 0,10,10, 6, 7, 8,10,
  130564. 10, 0, 7, 7,10,10, 0, 7, 7, 9,10, 0, 9, 9,10,10,
  130565. 0, 0, 0,10,10, 8,10, 9,12,11, 0,10,10,12,11, 0,
  130566. 10, 9,11,11, 0,11,12,12,12, 0, 0, 0,12,12, 8, 9,
  130567. 10,11,12, 0,10,10,11,11, 0, 9,10,11,11, 0,12,11,
  130568. 12,12, 0, 0, 0,12,12, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130570. 7,10, 9,12,12, 0, 9, 9,12,11, 0, 9, 9,11,11, 0,
  130571. 10,10,12,11, 0, 0, 0,11,12, 7, 9,10,12,12, 0, 9,
  130572. 9,11,12, 0, 9, 9,11,11, 0,10,10,11,12, 0, 0, 0,
  130573. 11,11, 9,11,10,13,12, 0,10,10,12,12, 0,10,10,12,
  130574. 12, 0,11,11,12,12, 0, 0, 0,13,12, 9,10,11,12,13,
  130575. 0,10,10,12,12, 0,10,10,12,12, 0,11,12,12,12, 0,
  130576. 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  130581. 11,10,13,13, 0,10,10,12,12, 0,10,10,12,12, 0,11,
  130582. 12,12,12, 0, 0, 0,12,12, 9,10,11,13,13, 0,10,10,
  130583. 12,12, 0,10,10,12,12, 0,12,11,13,12, 0, 0, 0,12,
  130584. 12,
  130585. };
  130586. static float _vq_quantthresh__44c9_s_p2_0[] = {
  130587. -1.5, -0.5, 0.5, 1.5,
  130588. };
  130589. static long _vq_quantmap__44c9_s_p2_0[] = {
  130590. 3, 1, 0, 2, 4,
  130591. };
  130592. static encode_aux_threshmatch _vq_auxt__44c9_s_p2_0 = {
  130593. _vq_quantthresh__44c9_s_p2_0,
  130594. _vq_quantmap__44c9_s_p2_0,
  130595. 5,
  130596. 5
  130597. };
  130598. static static_codebook _44c9_s_p2_0 = {
  130599. 4, 625,
  130600. _vq_lengthlist__44c9_s_p2_0,
  130601. 1, -533725184, 1611661312, 3, 0,
  130602. _vq_quantlist__44c9_s_p2_0,
  130603. NULL,
  130604. &_vq_auxt__44c9_s_p2_0,
  130605. NULL,
  130606. 0
  130607. };
  130608. static long _vq_quantlist__44c9_s_p3_0[] = {
  130609. 4,
  130610. 3,
  130611. 5,
  130612. 2,
  130613. 6,
  130614. 1,
  130615. 7,
  130616. 0,
  130617. 8,
  130618. };
  130619. static long _vq_lengthlist__44c9_s_p3_0[] = {
  130620. 3, 4, 4, 5, 5, 6, 6, 8, 8, 0, 4, 4, 5, 5, 6, 7,
  130621. 8, 8, 0, 4, 4, 5, 5, 7, 7, 8, 8, 0, 5, 5, 6, 6,
  130622. 7, 7, 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0,
  130623. 7, 7, 8, 8, 9, 9, 0, 0, 0, 7, 7, 8, 8, 9, 9, 0,
  130624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130625. 0,
  130626. };
  130627. static float _vq_quantthresh__44c9_s_p3_0[] = {
  130628. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  130629. };
  130630. static long _vq_quantmap__44c9_s_p3_0[] = {
  130631. 7, 5, 3, 1, 0, 2, 4, 6,
  130632. 8,
  130633. };
  130634. static encode_aux_threshmatch _vq_auxt__44c9_s_p3_0 = {
  130635. _vq_quantthresh__44c9_s_p3_0,
  130636. _vq_quantmap__44c9_s_p3_0,
  130637. 9,
  130638. 9
  130639. };
  130640. static static_codebook _44c9_s_p3_0 = {
  130641. 2, 81,
  130642. _vq_lengthlist__44c9_s_p3_0,
  130643. 1, -531628032, 1611661312, 4, 0,
  130644. _vq_quantlist__44c9_s_p3_0,
  130645. NULL,
  130646. &_vq_auxt__44c9_s_p3_0,
  130647. NULL,
  130648. 0
  130649. };
  130650. static long _vq_quantlist__44c9_s_p4_0[] = {
  130651. 8,
  130652. 7,
  130653. 9,
  130654. 6,
  130655. 10,
  130656. 5,
  130657. 11,
  130658. 4,
  130659. 12,
  130660. 3,
  130661. 13,
  130662. 2,
  130663. 14,
  130664. 1,
  130665. 15,
  130666. 0,
  130667. 16,
  130668. };
  130669. static long _vq_lengthlist__44c9_s_p4_0[] = {
  130670. 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,10,
  130671. 10, 0, 5, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  130672. 11,11, 0, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  130673. 10,11,11, 0, 6, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,
  130674. 11,11,11,12, 0, 0, 0, 6, 6, 7, 7, 8, 8, 9, 9,10,
  130675. 10,11,11,12,12, 0, 0, 0, 7, 7, 7, 7, 9, 9, 9, 9,
  130676. 10,10,11,11,12,12, 0, 0, 0, 7, 7, 7, 8, 9, 9, 9,
  130677. 9,10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  130678. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  130679. 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 0, 0,
  130680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130688. 0,
  130689. };
  130690. static float _vq_quantthresh__44c9_s_p4_0[] = {
  130691. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  130692. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  130693. };
  130694. static long _vq_quantmap__44c9_s_p4_0[] = {
  130695. 15, 13, 11, 9, 7, 5, 3, 1,
  130696. 0, 2, 4, 6, 8, 10, 12, 14,
  130697. 16,
  130698. };
  130699. static encode_aux_threshmatch _vq_auxt__44c9_s_p4_0 = {
  130700. _vq_quantthresh__44c9_s_p4_0,
  130701. _vq_quantmap__44c9_s_p4_0,
  130702. 17,
  130703. 17
  130704. };
  130705. static static_codebook _44c9_s_p4_0 = {
  130706. 2, 289,
  130707. _vq_lengthlist__44c9_s_p4_0,
  130708. 1, -529530880, 1611661312, 5, 0,
  130709. _vq_quantlist__44c9_s_p4_0,
  130710. NULL,
  130711. &_vq_auxt__44c9_s_p4_0,
  130712. NULL,
  130713. 0
  130714. };
  130715. static long _vq_quantlist__44c9_s_p5_0[] = {
  130716. 1,
  130717. 0,
  130718. 2,
  130719. };
  130720. static long _vq_lengthlist__44c9_s_p5_0[] = {
  130721. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 7, 6, 9,10,10,10,
  130722. 10, 9, 4, 6, 7, 9,10,10,10, 9,10, 5, 9, 9, 9,11,
  130723. 11,10,11,11, 7,10, 9,11,12,11,12,12,12, 7, 9,10,
  130724. 11,11,12,12,12,12, 6,10,10,10,12,12,10,12,11, 7,
  130725. 10,10,11,12,12,11,12,12, 7,10,10,11,12,12,12,12,
  130726. 12,
  130727. };
  130728. static float _vq_quantthresh__44c9_s_p5_0[] = {
  130729. -5.5, 5.5,
  130730. };
  130731. static long _vq_quantmap__44c9_s_p5_0[] = {
  130732. 1, 0, 2,
  130733. };
  130734. static encode_aux_threshmatch _vq_auxt__44c9_s_p5_0 = {
  130735. _vq_quantthresh__44c9_s_p5_0,
  130736. _vq_quantmap__44c9_s_p5_0,
  130737. 3,
  130738. 3
  130739. };
  130740. static static_codebook _44c9_s_p5_0 = {
  130741. 4, 81,
  130742. _vq_lengthlist__44c9_s_p5_0,
  130743. 1, -529137664, 1618345984, 2, 0,
  130744. _vq_quantlist__44c9_s_p5_0,
  130745. NULL,
  130746. &_vq_auxt__44c9_s_p5_0,
  130747. NULL,
  130748. 0
  130749. };
  130750. static long _vq_quantlist__44c9_s_p5_1[] = {
  130751. 5,
  130752. 4,
  130753. 6,
  130754. 3,
  130755. 7,
  130756. 2,
  130757. 8,
  130758. 1,
  130759. 9,
  130760. 0,
  130761. 10,
  130762. };
  130763. static long _vq_lengthlist__44c9_s_p5_1[] = {
  130764. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7,11, 5, 5, 6, 6,
  130765. 7, 7, 7, 7, 8, 8,11, 5, 5, 6, 6, 7, 7, 7, 7, 8,
  130766. 8,11, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11,11,11, 6,
  130767. 6, 7, 7, 7, 8, 8, 8,11,11,11, 6, 6, 7, 7, 7, 8,
  130768. 8, 8,11,11,11, 6, 6, 7, 7, 7, 7, 8, 8,11,11,11,
  130769. 7, 7, 7, 7, 7, 7, 8, 8,11,11,11,10,10, 7, 7, 7,
  130770. 7, 8, 8,11,11,11,11,11, 7, 7, 7, 7, 7, 7,11,11,
  130771. 11,11,11, 7, 7, 7, 7, 7, 7,
  130772. };
  130773. static float _vq_quantthresh__44c9_s_p5_1[] = {
  130774. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  130775. 3.5, 4.5,
  130776. };
  130777. static long _vq_quantmap__44c9_s_p5_1[] = {
  130778. 9, 7, 5, 3, 1, 0, 2, 4,
  130779. 6, 8, 10,
  130780. };
  130781. static encode_aux_threshmatch _vq_auxt__44c9_s_p5_1 = {
  130782. _vq_quantthresh__44c9_s_p5_1,
  130783. _vq_quantmap__44c9_s_p5_1,
  130784. 11,
  130785. 11
  130786. };
  130787. static static_codebook _44c9_s_p5_1 = {
  130788. 2, 121,
  130789. _vq_lengthlist__44c9_s_p5_1,
  130790. 1, -531365888, 1611661312, 4, 0,
  130791. _vq_quantlist__44c9_s_p5_1,
  130792. NULL,
  130793. &_vq_auxt__44c9_s_p5_1,
  130794. NULL,
  130795. 0
  130796. };
  130797. static long _vq_quantlist__44c9_s_p6_0[] = {
  130798. 6,
  130799. 5,
  130800. 7,
  130801. 4,
  130802. 8,
  130803. 3,
  130804. 9,
  130805. 2,
  130806. 10,
  130807. 1,
  130808. 11,
  130809. 0,
  130810. 12,
  130811. };
  130812. static long _vq_lengthlist__44c9_s_p6_0[] = {
  130813. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 5, 4, 4,
  130814. 6, 6, 8, 8, 9, 9, 9, 9,10,10, 6, 4, 4, 6, 6, 8,
  130815. 8, 9, 9, 9, 9,10,10, 0, 6, 6, 7, 7, 8, 8, 9, 9,
  130816. 10,10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  130817. 11, 0,10,10, 8, 8, 9, 9,10,10,11,11,12,12, 0,11,
  130818. 11, 8, 8, 9, 9,10,10,11,11,12,12, 0, 0, 0, 0, 0,
  130819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130823. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130824. };
  130825. static float _vq_quantthresh__44c9_s_p6_0[] = {
  130826. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  130827. 12.5, 17.5, 22.5, 27.5,
  130828. };
  130829. static long _vq_quantmap__44c9_s_p6_0[] = {
  130830. 11, 9, 7, 5, 3, 1, 0, 2,
  130831. 4, 6, 8, 10, 12,
  130832. };
  130833. static encode_aux_threshmatch _vq_auxt__44c9_s_p6_0 = {
  130834. _vq_quantthresh__44c9_s_p6_0,
  130835. _vq_quantmap__44c9_s_p6_0,
  130836. 13,
  130837. 13
  130838. };
  130839. static static_codebook _44c9_s_p6_0 = {
  130840. 2, 169,
  130841. _vq_lengthlist__44c9_s_p6_0,
  130842. 1, -526516224, 1616117760, 4, 0,
  130843. _vq_quantlist__44c9_s_p6_0,
  130844. NULL,
  130845. &_vq_auxt__44c9_s_p6_0,
  130846. NULL,
  130847. 0
  130848. };
  130849. static long _vq_quantlist__44c9_s_p6_1[] = {
  130850. 2,
  130851. 1,
  130852. 3,
  130853. 0,
  130854. 4,
  130855. };
  130856. static long _vq_lengthlist__44c9_s_p6_1[] = {
  130857. 4, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5,
  130858. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  130859. };
  130860. static float _vq_quantthresh__44c9_s_p6_1[] = {
  130861. -1.5, -0.5, 0.5, 1.5,
  130862. };
  130863. static long _vq_quantmap__44c9_s_p6_1[] = {
  130864. 3, 1, 0, 2, 4,
  130865. };
  130866. static encode_aux_threshmatch _vq_auxt__44c9_s_p6_1 = {
  130867. _vq_quantthresh__44c9_s_p6_1,
  130868. _vq_quantmap__44c9_s_p6_1,
  130869. 5,
  130870. 5
  130871. };
  130872. static static_codebook _44c9_s_p6_1 = {
  130873. 2, 25,
  130874. _vq_lengthlist__44c9_s_p6_1,
  130875. 1, -533725184, 1611661312, 3, 0,
  130876. _vq_quantlist__44c9_s_p6_1,
  130877. NULL,
  130878. &_vq_auxt__44c9_s_p6_1,
  130879. NULL,
  130880. 0
  130881. };
  130882. static long _vq_quantlist__44c9_s_p7_0[] = {
  130883. 6,
  130884. 5,
  130885. 7,
  130886. 4,
  130887. 8,
  130888. 3,
  130889. 9,
  130890. 2,
  130891. 10,
  130892. 1,
  130893. 11,
  130894. 0,
  130895. 12,
  130896. };
  130897. static long _vq_lengthlist__44c9_s_p7_0[] = {
  130898. 2, 4, 4, 6, 6, 7, 7, 8, 8,10,10,11,11, 6, 4, 4,
  130899. 6, 6, 8, 8, 9, 9,10,10,12,12, 6, 4, 5, 6, 6, 8,
  130900. 8, 9, 9,10,10,12,12,20, 6, 6, 6, 6, 8, 8, 9,10,
  130901. 11,11,12,12,20, 6, 6, 6, 6, 8, 8,10,10,11,11,12,
  130902. 12,20,10,10, 7, 7, 9, 9,10,10,11,11,12,12,20,11,
  130903. 11, 7, 7, 9, 9,10,10,11,11,12,12,20,20,20, 9, 9,
  130904. 9, 9,11,11,12,12,13,13,20,20,20, 9, 9, 9, 9,11,
  130905. 11,12,12,13,13,20,20,20,13,13,10,10,11,11,12,13,
  130906. 13,13,20,20,20,13,13,10,10,11,11,12,13,13,13,20,
  130907. 20,20,20,19,12,12,12,12,13,13,14,15,19,19,19,19,
  130908. 19,12,12,12,12,13,13,14,14,
  130909. };
  130910. static float _vq_quantthresh__44c9_s_p7_0[] = {
  130911. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  130912. 27.5, 38.5, 49.5, 60.5,
  130913. };
  130914. static long _vq_quantmap__44c9_s_p7_0[] = {
  130915. 11, 9, 7, 5, 3, 1, 0, 2,
  130916. 4, 6, 8, 10, 12,
  130917. };
  130918. static encode_aux_threshmatch _vq_auxt__44c9_s_p7_0 = {
  130919. _vq_quantthresh__44c9_s_p7_0,
  130920. _vq_quantmap__44c9_s_p7_0,
  130921. 13,
  130922. 13
  130923. };
  130924. static static_codebook _44c9_s_p7_0 = {
  130925. 2, 169,
  130926. _vq_lengthlist__44c9_s_p7_0,
  130927. 1, -523206656, 1618345984, 4, 0,
  130928. _vq_quantlist__44c9_s_p7_0,
  130929. NULL,
  130930. &_vq_auxt__44c9_s_p7_0,
  130931. NULL,
  130932. 0
  130933. };
  130934. static long _vq_quantlist__44c9_s_p7_1[] = {
  130935. 5,
  130936. 4,
  130937. 6,
  130938. 3,
  130939. 7,
  130940. 2,
  130941. 8,
  130942. 1,
  130943. 9,
  130944. 0,
  130945. 10,
  130946. };
  130947. static long _vq_lengthlist__44c9_s_p7_1[] = {
  130948. 5, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6,
  130949. 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  130950. 7, 8, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 6,
  130951. 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  130952. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  130953. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  130954. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  130955. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  130956. };
  130957. static float _vq_quantthresh__44c9_s_p7_1[] = {
  130958. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  130959. 3.5, 4.5,
  130960. };
  130961. static long _vq_quantmap__44c9_s_p7_1[] = {
  130962. 9, 7, 5, 3, 1, 0, 2, 4,
  130963. 6, 8, 10,
  130964. };
  130965. static encode_aux_threshmatch _vq_auxt__44c9_s_p7_1 = {
  130966. _vq_quantthresh__44c9_s_p7_1,
  130967. _vq_quantmap__44c9_s_p7_1,
  130968. 11,
  130969. 11
  130970. };
  130971. static static_codebook _44c9_s_p7_1 = {
  130972. 2, 121,
  130973. _vq_lengthlist__44c9_s_p7_1,
  130974. 1, -531365888, 1611661312, 4, 0,
  130975. _vq_quantlist__44c9_s_p7_1,
  130976. NULL,
  130977. &_vq_auxt__44c9_s_p7_1,
  130978. NULL,
  130979. 0
  130980. };
  130981. static long _vq_quantlist__44c9_s_p8_0[] = {
  130982. 7,
  130983. 6,
  130984. 8,
  130985. 5,
  130986. 9,
  130987. 4,
  130988. 10,
  130989. 3,
  130990. 11,
  130991. 2,
  130992. 12,
  130993. 1,
  130994. 13,
  130995. 0,
  130996. 14,
  130997. };
  130998. static long _vq_lengthlist__44c9_s_p8_0[] = {
  130999. 1, 4, 4, 7, 6, 8, 8, 8, 8, 9, 9,10,10,11,10, 6,
  131000. 5, 5, 7, 7, 9, 9, 8, 9,10,10,11,11,12,12, 6, 5,
  131001. 5, 7, 7, 9, 9, 9, 9,10,10,11,11,12,12,21, 7, 8,
  131002. 8, 8, 9, 9, 9, 9,10,10,11,11,12,12,21, 8, 8, 8,
  131003. 8, 9, 9, 9, 9,10,10,11,11,12,12,21,11,12, 9, 9,
  131004. 10,10,10,10,10,11,11,12,12,12,21,12,12, 9, 8,10,
  131005. 10,10,10,11,11,12,12,13,13,21,21,21, 9, 9, 9, 9,
  131006. 11,11,11,11,12,12,12,13,21,20,20, 9, 9, 9, 9,10,
  131007. 11,11,11,12,12,13,13,20,20,20,13,13,10,10,11,11,
  131008. 12,12,13,13,13,13,20,20,20,13,13,10,10,11,11,12,
  131009. 12,13,13,13,13,20,20,20,20,20,12,12,12,12,12,12,
  131010. 13,13,14,14,20,20,20,20,20,12,12,12,11,13,12,13,
  131011. 13,14,14,20,20,20,20,20,15,16,13,12,13,13,14,13,
  131012. 14,14,20,20,20,20,20,16,15,12,12,13,12,14,13,14,
  131013. 14,
  131014. };
  131015. static float _vq_quantthresh__44c9_s_p8_0[] = {
  131016. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  131017. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  131018. };
  131019. static long _vq_quantmap__44c9_s_p8_0[] = {
  131020. 13, 11, 9, 7, 5, 3, 1, 0,
  131021. 2, 4, 6, 8, 10, 12, 14,
  131022. };
  131023. static encode_aux_threshmatch _vq_auxt__44c9_s_p8_0 = {
  131024. _vq_quantthresh__44c9_s_p8_0,
  131025. _vq_quantmap__44c9_s_p8_0,
  131026. 15,
  131027. 15
  131028. };
  131029. static static_codebook _44c9_s_p8_0 = {
  131030. 2, 225,
  131031. _vq_lengthlist__44c9_s_p8_0,
  131032. 1, -520986624, 1620377600, 4, 0,
  131033. _vq_quantlist__44c9_s_p8_0,
  131034. NULL,
  131035. &_vq_auxt__44c9_s_p8_0,
  131036. NULL,
  131037. 0
  131038. };
  131039. static long _vq_quantlist__44c9_s_p8_1[] = {
  131040. 10,
  131041. 9,
  131042. 11,
  131043. 8,
  131044. 12,
  131045. 7,
  131046. 13,
  131047. 6,
  131048. 14,
  131049. 5,
  131050. 15,
  131051. 4,
  131052. 16,
  131053. 3,
  131054. 17,
  131055. 2,
  131056. 18,
  131057. 1,
  131058. 19,
  131059. 0,
  131060. 20,
  131061. };
  131062. static long _vq_lengthlist__44c9_s_p8_1[] = {
  131063. 4, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  131064. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  131065. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  131066. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  131067. 7, 7, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  131068. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  131069. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8,
  131070. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  131071. 10, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  131072. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  131073. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  131074. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  131075. 10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  131076. 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  131077. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9,
  131078. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10,10,10,10,
  131079. 10,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9, 9, 9, 9, 9,
  131080. 9,10,10,10,10,10,10,10, 9, 9, 9,10,10,10,10,10,
  131081. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10, 9, 9,10,
  131082. 9,10, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  131083. 10,10,10,10, 9, 9,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  131084. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  131085. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  131086. 10,10, 9, 9,10, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  131087. 10,10,10,10,10, 9, 9,10,10, 9, 9,10, 9, 9, 9,10,
  131088. 10,10,10,10,10,10,10,10,10,10, 9, 9,10, 9, 9, 9,
  131089. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10, 9,
  131090. 9, 9, 9,10, 9, 9, 9, 9, 9,
  131091. };
  131092. static float _vq_quantthresh__44c9_s_p8_1[] = {
  131093. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  131094. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  131095. 6.5, 7.5, 8.5, 9.5,
  131096. };
  131097. static long _vq_quantmap__44c9_s_p8_1[] = {
  131098. 19, 17, 15, 13, 11, 9, 7, 5,
  131099. 3, 1, 0, 2, 4, 6, 8, 10,
  131100. 12, 14, 16, 18, 20,
  131101. };
  131102. static encode_aux_threshmatch _vq_auxt__44c9_s_p8_1 = {
  131103. _vq_quantthresh__44c9_s_p8_1,
  131104. _vq_quantmap__44c9_s_p8_1,
  131105. 21,
  131106. 21
  131107. };
  131108. static static_codebook _44c9_s_p8_1 = {
  131109. 2, 441,
  131110. _vq_lengthlist__44c9_s_p8_1,
  131111. 1, -529268736, 1611661312, 5, 0,
  131112. _vq_quantlist__44c9_s_p8_1,
  131113. NULL,
  131114. &_vq_auxt__44c9_s_p8_1,
  131115. NULL,
  131116. 0
  131117. };
  131118. static long _vq_quantlist__44c9_s_p9_0[] = {
  131119. 9,
  131120. 8,
  131121. 10,
  131122. 7,
  131123. 11,
  131124. 6,
  131125. 12,
  131126. 5,
  131127. 13,
  131128. 4,
  131129. 14,
  131130. 3,
  131131. 15,
  131132. 2,
  131133. 16,
  131134. 1,
  131135. 17,
  131136. 0,
  131137. 18,
  131138. };
  131139. static long _vq_lengthlist__44c9_s_p9_0[] = {
  131140. 1, 4, 3,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131141. 12,12,12, 4, 5, 6,12,12,12,12,12,12,12,12,12,12,
  131142. 12,12,12,12,12,12, 4, 6, 6,12,12,12,12,12,12,12,
  131143. 12,12,12,12,12,12,12,12,12,12,12,11,12,12,12,12,
  131144. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131145. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131146. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131147. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131148. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131149. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131150. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131151. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131152. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131153. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131154. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131155. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131156. 12,12,12,12,12,12,12,12,12,12,11,11,11,11,11,11,
  131157. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  131158. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  131159. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  131160. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  131161. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  131162. 11,11,11,11,11,11,11,11,11,
  131163. };
  131164. static float _vq_quantthresh__44c9_s_p9_0[] = {
  131165. -7913.5, -6982.5, -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5,
  131166. -465.5, 465.5, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5,
  131167. 6982.5, 7913.5,
  131168. };
  131169. static long _vq_quantmap__44c9_s_p9_0[] = {
  131170. 17, 15, 13, 11, 9, 7, 5, 3,
  131171. 1, 0, 2, 4, 6, 8, 10, 12,
  131172. 14, 16, 18,
  131173. };
  131174. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_0 = {
  131175. _vq_quantthresh__44c9_s_p9_0,
  131176. _vq_quantmap__44c9_s_p9_0,
  131177. 19,
  131178. 19
  131179. };
  131180. static static_codebook _44c9_s_p9_0 = {
  131181. 2, 361,
  131182. _vq_lengthlist__44c9_s_p9_0,
  131183. 1, -508535424, 1631393792, 5, 0,
  131184. _vq_quantlist__44c9_s_p9_0,
  131185. NULL,
  131186. &_vq_auxt__44c9_s_p9_0,
  131187. NULL,
  131188. 0
  131189. };
  131190. static long _vq_quantlist__44c9_s_p9_1[] = {
  131191. 9,
  131192. 8,
  131193. 10,
  131194. 7,
  131195. 11,
  131196. 6,
  131197. 12,
  131198. 5,
  131199. 13,
  131200. 4,
  131201. 14,
  131202. 3,
  131203. 15,
  131204. 2,
  131205. 16,
  131206. 1,
  131207. 17,
  131208. 0,
  131209. 18,
  131210. };
  131211. static long _vq_lengthlist__44c9_s_p9_1[] = {
  131212. 1, 4, 4, 7, 7, 7, 7, 8, 7, 9, 8, 9, 9,10,10,11,
  131213. 11,11,11, 6, 5, 5, 8, 8, 9, 9, 9, 8,10, 9,11,10,
  131214. 12,12,13,12,13,13, 5, 5, 5, 8, 8, 9, 9, 9, 9,10,
  131215. 10,11,11,12,12,13,12,13,13,17, 8, 8, 9, 9, 9, 9,
  131216. 9, 9,10,10,12,11,13,12,13,13,13,13,18, 8, 8, 9,
  131217. 9, 9, 9, 9, 9,11,11,12,12,13,13,13,13,13,13,17,
  131218. 13,12, 9, 9,10,10,10,10,11,11,12,12,12,13,13,13,
  131219. 14,14,18,13,12, 9, 9,10,10,10,10,11,11,12,12,13,
  131220. 13,13,14,14,14,17,18,18,10,10,10,10,11,11,11,12,
  131221. 12,12,14,13,14,13,13,14,18,18,18,10, 9,10, 9,11,
  131222. 11,12,12,12,12,13,13,15,14,14,14,18,18,16,13,14,
  131223. 10,11,11,11,12,13,13,13,13,14,13,13,14,14,18,18,
  131224. 18,14,12,11, 9,11,10,13,12,13,13,13,14,14,14,13,
  131225. 14,18,18,17,18,18,11,12,12,12,13,13,14,13,14,14,
  131226. 13,14,14,14,18,18,18,18,17,12,10,12, 9,13,11,13,
  131227. 14,14,14,14,14,15,14,18,18,17,17,18,14,15,12,13,
  131228. 13,13,14,13,14,14,15,14,15,14,18,17,18,18,18,15,
  131229. 15,12,10,14,10,14,14,13,13,14,14,14,14,18,16,18,
  131230. 18,18,18,17,14,14,13,14,14,13,13,14,14,14,15,15,
  131231. 18,18,18,18,17,17,17,14,14,14,12,14,13,14,14,15,
  131232. 14,15,14,18,18,18,18,18,18,18,17,16,13,13,13,14,
  131233. 14,14,14,15,16,15,18,18,18,18,18,18,18,17,17,13,
  131234. 13,13,13,14,13,14,15,15,15,
  131235. };
  131236. static float _vq_quantthresh__44c9_s_p9_1[] = {
  131237. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  131238. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  131239. 367.5, 416.5,
  131240. };
  131241. static long _vq_quantmap__44c9_s_p9_1[] = {
  131242. 17, 15, 13, 11, 9, 7, 5, 3,
  131243. 1, 0, 2, 4, 6, 8, 10, 12,
  131244. 14, 16, 18,
  131245. };
  131246. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_1 = {
  131247. _vq_quantthresh__44c9_s_p9_1,
  131248. _vq_quantmap__44c9_s_p9_1,
  131249. 19,
  131250. 19
  131251. };
  131252. static static_codebook _44c9_s_p9_1 = {
  131253. 2, 361,
  131254. _vq_lengthlist__44c9_s_p9_1,
  131255. 1, -518287360, 1622704128, 5, 0,
  131256. _vq_quantlist__44c9_s_p9_1,
  131257. NULL,
  131258. &_vq_auxt__44c9_s_p9_1,
  131259. NULL,
  131260. 0
  131261. };
  131262. static long _vq_quantlist__44c9_s_p9_2[] = {
  131263. 24,
  131264. 23,
  131265. 25,
  131266. 22,
  131267. 26,
  131268. 21,
  131269. 27,
  131270. 20,
  131271. 28,
  131272. 19,
  131273. 29,
  131274. 18,
  131275. 30,
  131276. 17,
  131277. 31,
  131278. 16,
  131279. 32,
  131280. 15,
  131281. 33,
  131282. 14,
  131283. 34,
  131284. 13,
  131285. 35,
  131286. 12,
  131287. 36,
  131288. 11,
  131289. 37,
  131290. 10,
  131291. 38,
  131292. 9,
  131293. 39,
  131294. 8,
  131295. 40,
  131296. 7,
  131297. 41,
  131298. 6,
  131299. 42,
  131300. 5,
  131301. 43,
  131302. 4,
  131303. 44,
  131304. 3,
  131305. 45,
  131306. 2,
  131307. 46,
  131308. 1,
  131309. 47,
  131310. 0,
  131311. 48,
  131312. };
  131313. static long _vq_lengthlist__44c9_s_p9_2[] = {
  131314. 2, 4, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  131315. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  131316. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  131317. 7,
  131318. };
  131319. static float _vq_quantthresh__44c9_s_p9_2[] = {
  131320. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  131321. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  131322. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  131323. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  131324. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  131325. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  131326. };
  131327. static long _vq_quantmap__44c9_s_p9_2[] = {
  131328. 47, 45, 43, 41, 39, 37, 35, 33,
  131329. 31, 29, 27, 25, 23, 21, 19, 17,
  131330. 15, 13, 11, 9, 7, 5, 3, 1,
  131331. 0, 2, 4, 6, 8, 10, 12, 14,
  131332. 16, 18, 20, 22, 24, 26, 28, 30,
  131333. 32, 34, 36, 38, 40, 42, 44, 46,
  131334. 48,
  131335. };
  131336. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_2 = {
  131337. _vq_quantthresh__44c9_s_p9_2,
  131338. _vq_quantmap__44c9_s_p9_2,
  131339. 49,
  131340. 49
  131341. };
  131342. static static_codebook _44c9_s_p9_2 = {
  131343. 1, 49,
  131344. _vq_lengthlist__44c9_s_p9_2,
  131345. 1, -526909440, 1611661312, 6, 0,
  131346. _vq_quantlist__44c9_s_p9_2,
  131347. NULL,
  131348. &_vq_auxt__44c9_s_p9_2,
  131349. NULL,
  131350. 0
  131351. };
  131352. static long _huff_lengthlist__44c9_s_short[] = {
  131353. 5,13,18,16,17,17,19,18,19,19, 5, 7,10,11,12,12,
  131354. 13,16,17,18, 6, 6, 7, 7, 9, 9,10,14,17,19, 8, 7,
  131355. 6, 5, 6, 7, 9,12,19,17, 8, 7, 7, 6, 5, 6, 8,11,
  131356. 15,19, 9, 8, 7, 6, 5, 5, 6, 8,13,15,11,10, 8, 8,
  131357. 7, 5, 4, 4,10,14,12,13,11, 9, 7, 6, 4, 2, 6,12,
  131358. 18,16,16,13, 8, 7, 7, 5, 8,13,16,17,18,15,11, 9,
  131359. 9, 8,10,13,
  131360. };
  131361. static static_codebook _huff_book__44c9_s_short = {
  131362. 2, 100,
  131363. _huff_lengthlist__44c9_s_short,
  131364. 0, 0, 0, 0, 0,
  131365. NULL,
  131366. NULL,
  131367. NULL,
  131368. NULL,
  131369. 0
  131370. };
  131371. static long _huff_lengthlist__44c0_s_long[] = {
  131372. 5, 4, 8, 9, 8, 9,10,12,15, 4, 1, 5, 5, 6, 8,11,
  131373. 12,12, 8, 5, 8, 9, 9,11,13,12,12, 9, 5, 8, 5, 7,
  131374. 9,12,13,13, 8, 6, 8, 7, 7, 9,11,11,11, 9, 7, 9,
  131375. 7, 7, 7, 7,10,12,10,10,11, 9, 8, 7, 7, 9,11,11,
  131376. 12,13,12,11, 9, 8, 9,11,13,16,16,15,15,12,10,11,
  131377. 12,
  131378. };
  131379. static static_codebook _huff_book__44c0_s_long = {
  131380. 2, 81,
  131381. _huff_lengthlist__44c0_s_long,
  131382. 0, 0, 0, 0, 0,
  131383. NULL,
  131384. NULL,
  131385. NULL,
  131386. NULL,
  131387. 0
  131388. };
  131389. static long _vq_quantlist__44c0_s_p1_0[] = {
  131390. 1,
  131391. 0,
  131392. 2,
  131393. };
  131394. static long _vq_lengthlist__44c0_s_p1_0[] = {
  131395. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  131396. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131400. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  131401. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131405. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  131406. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  131441. 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  131442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  131446. 0, 0, 0, 9,10,11, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  131447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  131451. 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  131452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131486. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  131487. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131491. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  131492. 0, 0, 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0, 0, 0,
  131493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131496. 0, 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,10,11,
  131497. 0, 0, 0, 0, 0, 0, 9,11,10, 0, 0, 0, 0, 0, 0, 0,
  131498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131805. 0,
  131806. };
  131807. static float _vq_quantthresh__44c0_s_p1_0[] = {
  131808. -0.5, 0.5,
  131809. };
  131810. static long _vq_quantmap__44c0_s_p1_0[] = {
  131811. 1, 0, 2,
  131812. };
  131813. static encode_aux_threshmatch _vq_auxt__44c0_s_p1_0 = {
  131814. _vq_quantthresh__44c0_s_p1_0,
  131815. _vq_quantmap__44c0_s_p1_0,
  131816. 3,
  131817. 3
  131818. };
  131819. static static_codebook _44c0_s_p1_0 = {
  131820. 8, 6561,
  131821. _vq_lengthlist__44c0_s_p1_0,
  131822. 1, -535822336, 1611661312, 2, 0,
  131823. _vq_quantlist__44c0_s_p1_0,
  131824. NULL,
  131825. &_vq_auxt__44c0_s_p1_0,
  131826. NULL,
  131827. 0
  131828. };
  131829. static long _vq_quantlist__44c0_s_p2_0[] = {
  131830. 2,
  131831. 1,
  131832. 3,
  131833. 0,
  131834. 4,
  131835. };
  131836. static long _vq_lengthlist__44c0_s_p2_0[] = {
  131837. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 6, 0, 0,
  131839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131840. 0, 0, 4, 5, 6, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  131842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131843. 0, 0, 0, 0, 6, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  131844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131876. 0,
  131877. };
  131878. static float _vq_quantthresh__44c0_s_p2_0[] = {
  131879. -1.5, -0.5, 0.5, 1.5,
  131880. };
  131881. static long _vq_quantmap__44c0_s_p2_0[] = {
  131882. 3, 1, 0, 2, 4,
  131883. };
  131884. static encode_aux_threshmatch _vq_auxt__44c0_s_p2_0 = {
  131885. _vq_quantthresh__44c0_s_p2_0,
  131886. _vq_quantmap__44c0_s_p2_0,
  131887. 5,
  131888. 5
  131889. };
  131890. static static_codebook _44c0_s_p2_0 = {
  131891. 4, 625,
  131892. _vq_lengthlist__44c0_s_p2_0,
  131893. 1, -533725184, 1611661312, 3, 0,
  131894. _vq_quantlist__44c0_s_p2_0,
  131895. NULL,
  131896. &_vq_auxt__44c0_s_p2_0,
  131897. NULL,
  131898. 0
  131899. };
  131900. static long _vq_quantlist__44c0_s_p3_0[] = {
  131901. 4,
  131902. 3,
  131903. 5,
  131904. 2,
  131905. 6,
  131906. 1,
  131907. 7,
  131908. 0,
  131909. 8,
  131910. };
  131911. static long _vq_lengthlist__44c0_s_p3_0[] = {
  131912. 1, 3, 2, 8, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  131913. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  131914. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  131915. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  131916. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131917. 0,
  131918. };
  131919. static float _vq_quantthresh__44c0_s_p3_0[] = {
  131920. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  131921. };
  131922. static long _vq_quantmap__44c0_s_p3_0[] = {
  131923. 7, 5, 3, 1, 0, 2, 4, 6,
  131924. 8,
  131925. };
  131926. static encode_aux_threshmatch _vq_auxt__44c0_s_p3_0 = {
  131927. _vq_quantthresh__44c0_s_p3_0,
  131928. _vq_quantmap__44c0_s_p3_0,
  131929. 9,
  131930. 9
  131931. };
  131932. static static_codebook _44c0_s_p3_0 = {
  131933. 2, 81,
  131934. _vq_lengthlist__44c0_s_p3_0,
  131935. 1, -531628032, 1611661312, 4, 0,
  131936. _vq_quantlist__44c0_s_p3_0,
  131937. NULL,
  131938. &_vq_auxt__44c0_s_p3_0,
  131939. NULL,
  131940. 0
  131941. };
  131942. static long _vq_quantlist__44c0_s_p4_0[] = {
  131943. 4,
  131944. 3,
  131945. 5,
  131946. 2,
  131947. 6,
  131948. 1,
  131949. 7,
  131950. 0,
  131951. 8,
  131952. };
  131953. static long _vq_lengthlist__44c0_s_p4_0[] = {
  131954. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  131955. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  131956. 7, 8, 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0,
  131957. 9, 9, 8, 8,10,10, 0, 0, 0, 8, 9, 8, 8,10,10, 0,
  131958. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  131959. 10,
  131960. };
  131961. static float _vq_quantthresh__44c0_s_p4_0[] = {
  131962. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  131963. };
  131964. static long _vq_quantmap__44c0_s_p4_0[] = {
  131965. 7, 5, 3, 1, 0, 2, 4, 6,
  131966. 8,
  131967. };
  131968. static encode_aux_threshmatch _vq_auxt__44c0_s_p4_0 = {
  131969. _vq_quantthresh__44c0_s_p4_0,
  131970. _vq_quantmap__44c0_s_p4_0,
  131971. 9,
  131972. 9
  131973. };
  131974. static static_codebook _44c0_s_p4_0 = {
  131975. 2, 81,
  131976. _vq_lengthlist__44c0_s_p4_0,
  131977. 1, -531628032, 1611661312, 4, 0,
  131978. _vq_quantlist__44c0_s_p4_0,
  131979. NULL,
  131980. &_vq_auxt__44c0_s_p4_0,
  131981. NULL,
  131982. 0
  131983. };
  131984. static long _vq_quantlist__44c0_s_p5_0[] = {
  131985. 8,
  131986. 7,
  131987. 9,
  131988. 6,
  131989. 10,
  131990. 5,
  131991. 11,
  131992. 4,
  131993. 12,
  131994. 3,
  131995. 13,
  131996. 2,
  131997. 14,
  131998. 1,
  131999. 15,
  132000. 0,
  132001. 16,
  132002. };
  132003. static long _vq_lengthlist__44c0_s_p5_0[] = {
  132004. 1, 4, 3, 6, 6, 8, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  132005. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9, 9,10,10,10,
  132006. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  132007. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  132008. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  132009. 10,11,11,11,11, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,10,
  132010. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,
  132011. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  132012. 10,10,11,11,11,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  132013. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,
  132014. 10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  132015. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  132016. 10,10,11,11,11,11,11,12,12,12,13,13, 0, 0, 0, 0,
  132017. 0, 0, 0,11,10,11,11,11,11,12,12,13,13, 0, 0, 0,
  132018. 0, 0, 0, 0,11,11,12,11,12,12,12,12,13,13, 0, 0,
  132019. 0, 0, 0, 0, 0,11,11,11,12,12,12,12,13,13,13, 0,
  132020. 0, 0, 0, 0, 0, 0,12,12,12,12,12,13,13,13,14,14,
  132021. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  132022. 14,
  132023. };
  132024. static float _vq_quantthresh__44c0_s_p5_0[] = {
  132025. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  132026. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  132027. };
  132028. static long _vq_quantmap__44c0_s_p5_0[] = {
  132029. 15, 13, 11, 9, 7, 5, 3, 1,
  132030. 0, 2, 4, 6, 8, 10, 12, 14,
  132031. 16,
  132032. };
  132033. static encode_aux_threshmatch _vq_auxt__44c0_s_p5_0 = {
  132034. _vq_quantthresh__44c0_s_p5_0,
  132035. _vq_quantmap__44c0_s_p5_0,
  132036. 17,
  132037. 17
  132038. };
  132039. static static_codebook _44c0_s_p5_0 = {
  132040. 2, 289,
  132041. _vq_lengthlist__44c0_s_p5_0,
  132042. 1, -529530880, 1611661312, 5, 0,
  132043. _vq_quantlist__44c0_s_p5_0,
  132044. NULL,
  132045. &_vq_auxt__44c0_s_p5_0,
  132046. NULL,
  132047. 0
  132048. };
  132049. static long _vq_quantlist__44c0_s_p6_0[] = {
  132050. 1,
  132051. 0,
  132052. 2,
  132053. };
  132054. static long _vq_lengthlist__44c0_s_p6_0[] = {
  132055. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,10,
  132056. 9, 9, 4, 6, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  132057. 11,12,10,11, 6, 9, 9,11,10,11,11,10,10, 6, 9, 9,
  132058. 11,10,11,11,10,10, 7,11,10,12,11,11,11,11,11, 7,
  132059. 9, 9,10,10,10,11,11,10, 6, 9, 9,11,10,10,11,10,
  132060. 10,
  132061. };
  132062. static float _vq_quantthresh__44c0_s_p6_0[] = {
  132063. -5.5, 5.5,
  132064. };
  132065. static long _vq_quantmap__44c0_s_p6_0[] = {
  132066. 1, 0, 2,
  132067. };
  132068. static encode_aux_threshmatch _vq_auxt__44c0_s_p6_0 = {
  132069. _vq_quantthresh__44c0_s_p6_0,
  132070. _vq_quantmap__44c0_s_p6_0,
  132071. 3,
  132072. 3
  132073. };
  132074. static static_codebook _44c0_s_p6_0 = {
  132075. 4, 81,
  132076. _vq_lengthlist__44c0_s_p6_0,
  132077. 1, -529137664, 1618345984, 2, 0,
  132078. _vq_quantlist__44c0_s_p6_0,
  132079. NULL,
  132080. &_vq_auxt__44c0_s_p6_0,
  132081. NULL,
  132082. 0
  132083. };
  132084. static long _vq_quantlist__44c0_s_p6_1[] = {
  132085. 5,
  132086. 4,
  132087. 6,
  132088. 3,
  132089. 7,
  132090. 2,
  132091. 8,
  132092. 1,
  132093. 9,
  132094. 0,
  132095. 10,
  132096. };
  132097. static long _vq_lengthlist__44c0_s_p6_1[] = {
  132098. 2, 3, 3, 6, 6, 7, 7, 7, 7, 7, 8,10,10,10, 6, 6,
  132099. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  132100. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  132101. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 7, 8, 8, 8, 8,
  132102. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  132103. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  132104. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  132105. 10,10,10, 8, 8, 8, 8, 8, 8,
  132106. };
  132107. static float _vq_quantthresh__44c0_s_p6_1[] = {
  132108. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  132109. 3.5, 4.5,
  132110. };
  132111. static long _vq_quantmap__44c0_s_p6_1[] = {
  132112. 9, 7, 5, 3, 1, 0, 2, 4,
  132113. 6, 8, 10,
  132114. };
  132115. static encode_aux_threshmatch _vq_auxt__44c0_s_p6_1 = {
  132116. _vq_quantthresh__44c0_s_p6_1,
  132117. _vq_quantmap__44c0_s_p6_1,
  132118. 11,
  132119. 11
  132120. };
  132121. static static_codebook _44c0_s_p6_1 = {
  132122. 2, 121,
  132123. _vq_lengthlist__44c0_s_p6_1,
  132124. 1, -531365888, 1611661312, 4, 0,
  132125. _vq_quantlist__44c0_s_p6_1,
  132126. NULL,
  132127. &_vq_auxt__44c0_s_p6_1,
  132128. NULL,
  132129. 0
  132130. };
  132131. static long _vq_quantlist__44c0_s_p7_0[] = {
  132132. 6,
  132133. 5,
  132134. 7,
  132135. 4,
  132136. 8,
  132137. 3,
  132138. 9,
  132139. 2,
  132140. 10,
  132141. 1,
  132142. 11,
  132143. 0,
  132144. 12,
  132145. };
  132146. static long _vq_lengthlist__44c0_s_p7_0[] = {
  132147. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  132148. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 6, 7, 7, 8,
  132149. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  132150. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  132151. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  132152. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  132153. 10,10,11,11,11,11,12,12, 0, 0, 0,10,10, 9, 9,11,
  132154. 11,11,12,12,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  132155. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  132156. 0, 0, 0, 0,11,11,11,11,13,12,13,13, 0, 0, 0, 0,
  132157. 0,12,12,11,11,12,12,13,13,
  132158. };
  132159. static float _vq_quantthresh__44c0_s_p7_0[] = {
  132160. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  132161. 12.5, 17.5, 22.5, 27.5,
  132162. };
  132163. static long _vq_quantmap__44c0_s_p7_0[] = {
  132164. 11, 9, 7, 5, 3, 1, 0, 2,
  132165. 4, 6, 8, 10, 12,
  132166. };
  132167. static encode_aux_threshmatch _vq_auxt__44c0_s_p7_0 = {
  132168. _vq_quantthresh__44c0_s_p7_0,
  132169. _vq_quantmap__44c0_s_p7_0,
  132170. 13,
  132171. 13
  132172. };
  132173. static static_codebook _44c0_s_p7_0 = {
  132174. 2, 169,
  132175. _vq_lengthlist__44c0_s_p7_0,
  132176. 1, -526516224, 1616117760, 4, 0,
  132177. _vq_quantlist__44c0_s_p7_0,
  132178. NULL,
  132179. &_vq_auxt__44c0_s_p7_0,
  132180. NULL,
  132181. 0
  132182. };
  132183. static long _vq_quantlist__44c0_s_p7_1[] = {
  132184. 2,
  132185. 1,
  132186. 3,
  132187. 0,
  132188. 4,
  132189. };
  132190. static long _vq_lengthlist__44c0_s_p7_1[] = {
  132191. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  132192. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  132193. };
  132194. static float _vq_quantthresh__44c0_s_p7_1[] = {
  132195. -1.5, -0.5, 0.5, 1.5,
  132196. };
  132197. static long _vq_quantmap__44c0_s_p7_1[] = {
  132198. 3, 1, 0, 2, 4,
  132199. };
  132200. static encode_aux_threshmatch _vq_auxt__44c0_s_p7_1 = {
  132201. _vq_quantthresh__44c0_s_p7_1,
  132202. _vq_quantmap__44c0_s_p7_1,
  132203. 5,
  132204. 5
  132205. };
  132206. static static_codebook _44c0_s_p7_1 = {
  132207. 2, 25,
  132208. _vq_lengthlist__44c0_s_p7_1,
  132209. 1, -533725184, 1611661312, 3, 0,
  132210. _vq_quantlist__44c0_s_p7_1,
  132211. NULL,
  132212. &_vq_auxt__44c0_s_p7_1,
  132213. NULL,
  132214. 0
  132215. };
  132216. static long _vq_quantlist__44c0_s_p8_0[] = {
  132217. 2,
  132218. 1,
  132219. 3,
  132220. 0,
  132221. 4,
  132222. };
  132223. static long _vq_lengthlist__44c0_s_p8_0[] = {
  132224. 1, 5, 5,10,10, 6, 9, 8,10,10, 6,10, 9,10,10,10,
  132225. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132226. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132227. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132228. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132229. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132230. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132231. 10,10,10,10,10,10,10,10,10,10,10,10,10, 8,10,10,
  132232. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132233. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132234. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132235. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132236. 10,10,10,10,10,10,10,10,11,11,11,11,11,11,11,11,
  132237. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132238. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132239. 11,11,11,11,11,11,11,11,11,11,10,11,11,11,11,11,
  132240. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132241. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132242. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132243. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132244. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132245. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132246. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132247. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132248. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132249. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132250. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132251. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132252. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132253. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132254. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132255. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132256. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132257. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132258. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132259. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132260. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132261. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132262. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132263. 11,
  132264. };
  132265. static float _vq_quantthresh__44c0_s_p8_0[] = {
  132266. -331.5, -110.5, 110.5, 331.5,
  132267. };
  132268. static long _vq_quantmap__44c0_s_p8_0[] = {
  132269. 3, 1, 0, 2, 4,
  132270. };
  132271. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_0 = {
  132272. _vq_quantthresh__44c0_s_p8_0,
  132273. _vq_quantmap__44c0_s_p8_0,
  132274. 5,
  132275. 5
  132276. };
  132277. static static_codebook _44c0_s_p8_0 = {
  132278. 4, 625,
  132279. _vq_lengthlist__44c0_s_p8_0,
  132280. 1, -518283264, 1627103232, 3, 0,
  132281. _vq_quantlist__44c0_s_p8_0,
  132282. NULL,
  132283. &_vq_auxt__44c0_s_p8_0,
  132284. NULL,
  132285. 0
  132286. };
  132287. static long _vq_quantlist__44c0_s_p8_1[] = {
  132288. 6,
  132289. 5,
  132290. 7,
  132291. 4,
  132292. 8,
  132293. 3,
  132294. 9,
  132295. 2,
  132296. 10,
  132297. 1,
  132298. 11,
  132299. 0,
  132300. 12,
  132301. };
  132302. static long _vq_lengthlist__44c0_s_p8_1[] = {
  132303. 1, 4, 4, 6, 6, 7, 7, 9, 9,11,12,13,12, 6, 5, 5,
  132304. 7, 7, 8, 8,10, 9,12,12,12,12, 6, 5, 5, 7, 7, 8,
  132305. 8,10, 9,12,11,11,13,16, 7, 7, 8, 8, 9, 9,10,10,
  132306. 12,12,13,12,16, 7, 7, 8, 7, 9, 9,10,10,11,12,12,
  132307. 13,16,10,10, 8, 8,10,10,11,12,12,12,13,13,16,11,
  132308. 10, 8, 7,11,10,11,11,12,11,13,13,16,16,16,10,10,
  132309. 10,10,11,11,13,12,13,13,16,16,16,11, 9,11, 9,15,
  132310. 13,12,13,13,13,16,16,16,15,13,11,11,12,13,12,12,
  132311. 14,13,16,16,16,14,13,11,11,13,12,14,13,13,13,16,
  132312. 16,16,16,16,13,13,13,12,14,13,14,14,16,16,16,16,
  132313. 16,13,13,12,12,14,14,15,13,
  132314. };
  132315. static float _vq_quantthresh__44c0_s_p8_1[] = {
  132316. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  132317. 42.5, 59.5, 76.5, 93.5,
  132318. };
  132319. static long _vq_quantmap__44c0_s_p8_1[] = {
  132320. 11, 9, 7, 5, 3, 1, 0, 2,
  132321. 4, 6, 8, 10, 12,
  132322. };
  132323. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_1 = {
  132324. _vq_quantthresh__44c0_s_p8_1,
  132325. _vq_quantmap__44c0_s_p8_1,
  132326. 13,
  132327. 13
  132328. };
  132329. static static_codebook _44c0_s_p8_1 = {
  132330. 2, 169,
  132331. _vq_lengthlist__44c0_s_p8_1,
  132332. 1, -522616832, 1620115456, 4, 0,
  132333. _vq_quantlist__44c0_s_p8_1,
  132334. NULL,
  132335. &_vq_auxt__44c0_s_p8_1,
  132336. NULL,
  132337. 0
  132338. };
  132339. static long _vq_quantlist__44c0_s_p8_2[] = {
  132340. 8,
  132341. 7,
  132342. 9,
  132343. 6,
  132344. 10,
  132345. 5,
  132346. 11,
  132347. 4,
  132348. 12,
  132349. 3,
  132350. 13,
  132351. 2,
  132352. 14,
  132353. 1,
  132354. 15,
  132355. 0,
  132356. 16,
  132357. };
  132358. static long _vq_lengthlist__44c0_s_p8_2[] = {
  132359. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  132360. 8,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  132361. 9, 9,10,10,10, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  132362. 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  132363. 9,10, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  132364. 9,10, 9, 9,10,10,10,10, 8, 8, 8, 8, 9, 8, 9, 9,
  132365. 9, 9, 9,10, 9,10,10,10,10, 7, 7, 8, 8, 9, 9, 9,
  132366. 9, 9, 9,10, 9,10,10,10,10,10, 8, 8, 8, 9, 9, 9,
  132367. 9, 9, 9, 9,10,10,10, 9,11,10,10,10,10, 8, 8, 9,
  132368. 9, 9, 9, 9,10, 9, 9, 9,10,10,10,10,11,11, 9, 9,
  132369. 9, 9, 9, 9, 9, 9,10, 9, 9,10,11,10,10,11,11, 9,
  132370. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,11,10,11,11,
  132371. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,10,10,11,
  132372. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  132373. 11,11,11,11, 9,10, 9,10, 9, 9, 9, 9,10, 9,10,11,
  132374. 10,11,10,10,10,10,10, 9, 9, 9,10, 9, 9, 9,10,11,
  132375. 11,10,11,11,10,11,10,10,10, 9, 9, 9, 9,10, 9, 9,
  132376. 10,11,10,11,11,11,11,10,11,10,10, 9,10, 9, 9, 9,
  132377. 10,
  132378. };
  132379. static float _vq_quantthresh__44c0_s_p8_2[] = {
  132380. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  132381. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  132382. };
  132383. static long _vq_quantmap__44c0_s_p8_2[] = {
  132384. 15, 13, 11, 9, 7, 5, 3, 1,
  132385. 0, 2, 4, 6, 8, 10, 12, 14,
  132386. 16,
  132387. };
  132388. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_2 = {
  132389. _vq_quantthresh__44c0_s_p8_2,
  132390. _vq_quantmap__44c0_s_p8_2,
  132391. 17,
  132392. 17
  132393. };
  132394. static static_codebook _44c0_s_p8_2 = {
  132395. 2, 289,
  132396. _vq_lengthlist__44c0_s_p8_2,
  132397. 1, -529530880, 1611661312, 5, 0,
  132398. _vq_quantlist__44c0_s_p8_2,
  132399. NULL,
  132400. &_vq_auxt__44c0_s_p8_2,
  132401. NULL,
  132402. 0
  132403. };
  132404. static long _huff_lengthlist__44c0_s_short[] = {
  132405. 9, 8,12,11,12,13,14,14,16, 6, 1, 5, 6, 6, 9,12,
  132406. 14,17, 9, 4, 5, 9, 7, 9,13,15,16, 8, 5, 8, 6, 8,
  132407. 10,13,17,17, 9, 6, 7, 7, 8, 9,13,15,17,11, 8, 9,
  132408. 9, 9,10,12,16,16,13, 7, 8, 7, 7, 9,12,14,15,13,
  132409. 6, 7, 5, 5, 7,10,13,13,14, 7, 8, 5, 6, 7, 9,10,
  132410. 12,
  132411. };
  132412. static static_codebook _huff_book__44c0_s_short = {
  132413. 2, 81,
  132414. _huff_lengthlist__44c0_s_short,
  132415. 0, 0, 0, 0, 0,
  132416. NULL,
  132417. NULL,
  132418. NULL,
  132419. NULL,
  132420. 0
  132421. };
  132422. static long _huff_lengthlist__44c0_sm_long[] = {
  132423. 5, 4, 9,10, 9,10,11,12,13, 4, 1, 5, 7, 7, 9,11,
  132424. 12,14, 8, 5, 7, 9, 8,10,13,13,13,10, 7, 9, 4, 6,
  132425. 7,10,12,14, 9, 6, 7, 6, 6, 7,10,12,12, 9, 8, 9,
  132426. 7, 6, 7, 8,11,12,11,11,11, 9, 8, 7, 8,10,12,12,
  132427. 13,14,12,11, 9, 9, 9,12,12,17,17,15,16,12,10,11,
  132428. 13,
  132429. };
  132430. static static_codebook _huff_book__44c0_sm_long = {
  132431. 2, 81,
  132432. _huff_lengthlist__44c0_sm_long,
  132433. 0, 0, 0, 0, 0,
  132434. NULL,
  132435. NULL,
  132436. NULL,
  132437. NULL,
  132438. 0
  132439. };
  132440. static long _vq_quantlist__44c0_sm_p1_0[] = {
  132441. 1,
  132442. 0,
  132443. 2,
  132444. };
  132445. static long _vq_lengthlist__44c0_sm_p1_0[] = {
  132446. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  132447. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132451. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  132452. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132456. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  132457. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 0,
  132492. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  132493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  132497. 0, 0, 0, 9,10,10, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  132498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  132502. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  132503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132537. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  132538. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132542. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  132543. 0, 0, 0, 0, 0, 9, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  132544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132547. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  132548. 0, 0, 0, 0, 0, 0, 9,10,10, 0, 0, 0, 0, 0, 0, 0,
  132549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132856. 0,
  132857. };
  132858. static float _vq_quantthresh__44c0_sm_p1_0[] = {
  132859. -0.5, 0.5,
  132860. };
  132861. static long _vq_quantmap__44c0_sm_p1_0[] = {
  132862. 1, 0, 2,
  132863. };
  132864. static encode_aux_threshmatch _vq_auxt__44c0_sm_p1_0 = {
  132865. _vq_quantthresh__44c0_sm_p1_0,
  132866. _vq_quantmap__44c0_sm_p1_0,
  132867. 3,
  132868. 3
  132869. };
  132870. static static_codebook _44c0_sm_p1_0 = {
  132871. 8, 6561,
  132872. _vq_lengthlist__44c0_sm_p1_0,
  132873. 1, -535822336, 1611661312, 2, 0,
  132874. _vq_quantlist__44c0_sm_p1_0,
  132875. NULL,
  132876. &_vq_auxt__44c0_sm_p1_0,
  132877. NULL,
  132878. 0
  132879. };
  132880. static long _vq_quantlist__44c0_sm_p2_0[] = {
  132881. 2,
  132882. 1,
  132883. 3,
  132884. 0,
  132885. 4,
  132886. };
  132887. static long _vq_lengthlist__44c0_sm_p2_0[] = {
  132888. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  132890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132891. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  132893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132894. 0, 0, 0, 0, 7, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  132895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132927. 0,
  132928. };
  132929. static float _vq_quantthresh__44c0_sm_p2_0[] = {
  132930. -1.5, -0.5, 0.5, 1.5,
  132931. };
  132932. static long _vq_quantmap__44c0_sm_p2_0[] = {
  132933. 3, 1, 0, 2, 4,
  132934. };
  132935. static encode_aux_threshmatch _vq_auxt__44c0_sm_p2_0 = {
  132936. _vq_quantthresh__44c0_sm_p2_0,
  132937. _vq_quantmap__44c0_sm_p2_0,
  132938. 5,
  132939. 5
  132940. };
  132941. static static_codebook _44c0_sm_p2_0 = {
  132942. 4, 625,
  132943. _vq_lengthlist__44c0_sm_p2_0,
  132944. 1, -533725184, 1611661312, 3, 0,
  132945. _vq_quantlist__44c0_sm_p2_0,
  132946. NULL,
  132947. &_vq_auxt__44c0_sm_p2_0,
  132948. NULL,
  132949. 0
  132950. };
  132951. static long _vq_quantlist__44c0_sm_p3_0[] = {
  132952. 4,
  132953. 3,
  132954. 5,
  132955. 2,
  132956. 6,
  132957. 1,
  132958. 7,
  132959. 0,
  132960. 8,
  132961. };
  132962. static long _vq_lengthlist__44c0_sm_p3_0[] = {
  132963. 1, 3, 3, 7, 7, 0, 0, 0, 0, 0, 5, 4, 7, 7, 0, 0,
  132964. 0, 0, 0, 5, 5, 7, 7, 0, 0, 0, 0, 0, 6, 7, 8, 8,
  132965. 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  132966. 9,10, 0, 0, 0, 0, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0,
  132967. 0, 0,11,11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132968. 0,
  132969. };
  132970. static float _vq_quantthresh__44c0_sm_p3_0[] = {
  132971. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  132972. };
  132973. static long _vq_quantmap__44c0_sm_p3_0[] = {
  132974. 7, 5, 3, 1, 0, 2, 4, 6,
  132975. 8,
  132976. };
  132977. static encode_aux_threshmatch _vq_auxt__44c0_sm_p3_0 = {
  132978. _vq_quantthresh__44c0_sm_p3_0,
  132979. _vq_quantmap__44c0_sm_p3_0,
  132980. 9,
  132981. 9
  132982. };
  132983. static static_codebook _44c0_sm_p3_0 = {
  132984. 2, 81,
  132985. _vq_lengthlist__44c0_sm_p3_0,
  132986. 1, -531628032, 1611661312, 4, 0,
  132987. _vq_quantlist__44c0_sm_p3_0,
  132988. NULL,
  132989. &_vq_auxt__44c0_sm_p3_0,
  132990. NULL,
  132991. 0
  132992. };
  132993. static long _vq_quantlist__44c0_sm_p4_0[] = {
  132994. 4,
  132995. 3,
  132996. 5,
  132997. 2,
  132998. 6,
  132999. 1,
  133000. 7,
  133001. 0,
  133002. 8,
  133003. };
  133004. static long _vq_lengthlist__44c0_sm_p4_0[] = {
  133005. 1, 4, 3, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 8, 7,
  133006. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  133007. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  133008. 9, 9, 9, 9,11,11, 0, 0, 0, 9, 9, 9, 9,11,11, 0,
  133009. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  133010. 11,
  133011. };
  133012. static float _vq_quantthresh__44c0_sm_p4_0[] = {
  133013. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  133014. };
  133015. static long _vq_quantmap__44c0_sm_p4_0[] = {
  133016. 7, 5, 3, 1, 0, 2, 4, 6,
  133017. 8,
  133018. };
  133019. static encode_aux_threshmatch _vq_auxt__44c0_sm_p4_0 = {
  133020. _vq_quantthresh__44c0_sm_p4_0,
  133021. _vq_quantmap__44c0_sm_p4_0,
  133022. 9,
  133023. 9
  133024. };
  133025. static static_codebook _44c0_sm_p4_0 = {
  133026. 2, 81,
  133027. _vq_lengthlist__44c0_sm_p4_0,
  133028. 1, -531628032, 1611661312, 4, 0,
  133029. _vq_quantlist__44c0_sm_p4_0,
  133030. NULL,
  133031. &_vq_auxt__44c0_sm_p4_0,
  133032. NULL,
  133033. 0
  133034. };
  133035. static long _vq_quantlist__44c0_sm_p5_0[] = {
  133036. 8,
  133037. 7,
  133038. 9,
  133039. 6,
  133040. 10,
  133041. 5,
  133042. 11,
  133043. 4,
  133044. 12,
  133045. 3,
  133046. 13,
  133047. 2,
  133048. 14,
  133049. 1,
  133050. 15,
  133051. 0,
  133052. 16,
  133053. };
  133054. static long _vq_lengthlist__44c0_sm_p5_0[] = {
  133055. 1, 4, 4, 6, 6, 8, 8, 8, 8, 8, 8, 9, 9,10,10,11,
  133056. 11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,11,
  133057. 11,11, 0, 5, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  133058. 11,11,11, 0, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,
  133059. 11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,
  133060. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  133061. 11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  133062. 10,11,11,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  133063. 10,10,11,11,12,12,12,13, 0, 0, 0, 0, 0, 9, 9,10,
  133064. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  133065. 10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  133066. 9,10,10,11,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  133067. 10,10,10,10,11,11,12,12,12,13,13,13, 0, 0, 0, 0,
  133068. 0, 0, 0,10,10,11,11,12,12,12,13,13,13, 0, 0, 0,
  133069. 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0, 0,
  133070. 0, 0, 0, 0, 0,11,11,12,11,12,12,13,13,13,13, 0,
  133071. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  133072. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  133073. 14,
  133074. };
  133075. static float _vq_quantthresh__44c0_sm_p5_0[] = {
  133076. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  133077. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  133078. };
  133079. static long _vq_quantmap__44c0_sm_p5_0[] = {
  133080. 15, 13, 11, 9, 7, 5, 3, 1,
  133081. 0, 2, 4, 6, 8, 10, 12, 14,
  133082. 16,
  133083. };
  133084. static encode_aux_threshmatch _vq_auxt__44c0_sm_p5_0 = {
  133085. _vq_quantthresh__44c0_sm_p5_0,
  133086. _vq_quantmap__44c0_sm_p5_0,
  133087. 17,
  133088. 17
  133089. };
  133090. static static_codebook _44c0_sm_p5_0 = {
  133091. 2, 289,
  133092. _vq_lengthlist__44c0_sm_p5_0,
  133093. 1, -529530880, 1611661312, 5, 0,
  133094. _vq_quantlist__44c0_sm_p5_0,
  133095. NULL,
  133096. &_vq_auxt__44c0_sm_p5_0,
  133097. NULL,
  133098. 0
  133099. };
  133100. static long _vq_quantlist__44c0_sm_p6_0[] = {
  133101. 1,
  133102. 0,
  133103. 2,
  133104. };
  133105. static long _vq_lengthlist__44c0_sm_p6_0[] = {
  133106. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  133107. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  133108. 11,11,10,10, 6, 9, 9,11,11,10,11,10,10, 6, 9, 9,
  133109. 11,10,11,11,10,10, 7,11,10,11,11,11,11,11,11, 6,
  133110. 9, 9,11,10,10,11,11,10, 6, 9, 9,11,10,10,11,10,
  133111. 11,
  133112. };
  133113. static float _vq_quantthresh__44c0_sm_p6_0[] = {
  133114. -5.5, 5.5,
  133115. };
  133116. static long _vq_quantmap__44c0_sm_p6_0[] = {
  133117. 1, 0, 2,
  133118. };
  133119. static encode_aux_threshmatch _vq_auxt__44c0_sm_p6_0 = {
  133120. _vq_quantthresh__44c0_sm_p6_0,
  133121. _vq_quantmap__44c0_sm_p6_0,
  133122. 3,
  133123. 3
  133124. };
  133125. static static_codebook _44c0_sm_p6_0 = {
  133126. 4, 81,
  133127. _vq_lengthlist__44c0_sm_p6_0,
  133128. 1, -529137664, 1618345984, 2, 0,
  133129. _vq_quantlist__44c0_sm_p6_0,
  133130. NULL,
  133131. &_vq_auxt__44c0_sm_p6_0,
  133132. NULL,
  133133. 0
  133134. };
  133135. static long _vq_quantlist__44c0_sm_p6_1[] = {
  133136. 5,
  133137. 4,
  133138. 6,
  133139. 3,
  133140. 7,
  133141. 2,
  133142. 8,
  133143. 1,
  133144. 9,
  133145. 0,
  133146. 10,
  133147. };
  133148. static long _vq_lengthlist__44c0_sm_p6_1[] = {
  133149. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 8, 9, 5, 5, 6, 6,
  133150. 7, 7, 8, 8, 8, 8, 9, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  133151. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  133152. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  133153. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  133154. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  133155. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  133156. 10,10,10, 8, 8, 8, 8, 8, 8,
  133157. };
  133158. static float _vq_quantthresh__44c0_sm_p6_1[] = {
  133159. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  133160. 3.5, 4.5,
  133161. };
  133162. static long _vq_quantmap__44c0_sm_p6_1[] = {
  133163. 9, 7, 5, 3, 1, 0, 2, 4,
  133164. 6, 8, 10,
  133165. };
  133166. static encode_aux_threshmatch _vq_auxt__44c0_sm_p6_1 = {
  133167. _vq_quantthresh__44c0_sm_p6_1,
  133168. _vq_quantmap__44c0_sm_p6_1,
  133169. 11,
  133170. 11
  133171. };
  133172. static static_codebook _44c0_sm_p6_1 = {
  133173. 2, 121,
  133174. _vq_lengthlist__44c0_sm_p6_1,
  133175. 1, -531365888, 1611661312, 4, 0,
  133176. _vq_quantlist__44c0_sm_p6_1,
  133177. NULL,
  133178. &_vq_auxt__44c0_sm_p6_1,
  133179. NULL,
  133180. 0
  133181. };
  133182. static long _vq_quantlist__44c0_sm_p7_0[] = {
  133183. 6,
  133184. 5,
  133185. 7,
  133186. 4,
  133187. 8,
  133188. 3,
  133189. 9,
  133190. 2,
  133191. 10,
  133192. 1,
  133193. 11,
  133194. 0,
  133195. 12,
  133196. };
  133197. static long _vq_lengthlist__44c0_sm_p7_0[] = {
  133198. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  133199. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 6, 5, 7, 7, 8,
  133200. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  133201. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  133202. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  133203. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0, 9,10,
  133204. 10,10,11,11,12,11,12,12, 0, 0, 0,10,10, 9, 9,11,
  133205. 11,12,12,12,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  133206. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  133207. 0, 0, 0, 0,11,12,11,11,13,12,13,13, 0, 0, 0, 0,
  133208. 0,12,12,11,11,13,12,14,14,
  133209. };
  133210. static float _vq_quantthresh__44c0_sm_p7_0[] = {
  133211. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  133212. 12.5, 17.5, 22.5, 27.5,
  133213. };
  133214. static long _vq_quantmap__44c0_sm_p7_0[] = {
  133215. 11, 9, 7, 5, 3, 1, 0, 2,
  133216. 4, 6, 8, 10, 12,
  133217. };
  133218. static encode_aux_threshmatch _vq_auxt__44c0_sm_p7_0 = {
  133219. _vq_quantthresh__44c0_sm_p7_0,
  133220. _vq_quantmap__44c0_sm_p7_0,
  133221. 13,
  133222. 13
  133223. };
  133224. static static_codebook _44c0_sm_p7_0 = {
  133225. 2, 169,
  133226. _vq_lengthlist__44c0_sm_p7_0,
  133227. 1, -526516224, 1616117760, 4, 0,
  133228. _vq_quantlist__44c0_sm_p7_0,
  133229. NULL,
  133230. &_vq_auxt__44c0_sm_p7_0,
  133231. NULL,
  133232. 0
  133233. };
  133234. static long _vq_quantlist__44c0_sm_p7_1[] = {
  133235. 2,
  133236. 1,
  133237. 3,
  133238. 0,
  133239. 4,
  133240. };
  133241. static long _vq_lengthlist__44c0_sm_p7_1[] = {
  133242. 2, 4, 4, 4, 4, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  133243. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  133244. };
  133245. static float _vq_quantthresh__44c0_sm_p7_1[] = {
  133246. -1.5, -0.5, 0.5, 1.5,
  133247. };
  133248. static long _vq_quantmap__44c0_sm_p7_1[] = {
  133249. 3, 1, 0, 2, 4,
  133250. };
  133251. static encode_aux_threshmatch _vq_auxt__44c0_sm_p7_1 = {
  133252. _vq_quantthresh__44c0_sm_p7_1,
  133253. _vq_quantmap__44c0_sm_p7_1,
  133254. 5,
  133255. 5
  133256. };
  133257. static static_codebook _44c0_sm_p7_1 = {
  133258. 2, 25,
  133259. _vq_lengthlist__44c0_sm_p7_1,
  133260. 1, -533725184, 1611661312, 3, 0,
  133261. _vq_quantlist__44c0_sm_p7_1,
  133262. NULL,
  133263. &_vq_auxt__44c0_sm_p7_1,
  133264. NULL,
  133265. 0
  133266. };
  133267. static long _vq_quantlist__44c0_sm_p8_0[] = {
  133268. 4,
  133269. 3,
  133270. 5,
  133271. 2,
  133272. 6,
  133273. 1,
  133274. 7,
  133275. 0,
  133276. 8,
  133277. };
  133278. static long _vq_lengthlist__44c0_sm_p8_0[] = {
  133279. 1, 3, 3,11,11,11,11,11,11, 3, 7, 6,11,11,11,11,
  133280. 11,11, 4, 8, 7,11,11,11,11,11,11,11,11,11,11,11,
  133281. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133282. 11,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  133283. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  133284. 12,
  133285. };
  133286. static float _vq_quantthresh__44c0_sm_p8_0[] = {
  133287. -773.5, -552.5, -331.5, -110.5, 110.5, 331.5, 552.5, 773.5,
  133288. };
  133289. static long _vq_quantmap__44c0_sm_p8_0[] = {
  133290. 7, 5, 3, 1, 0, 2, 4, 6,
  133291. 8,
  133292. };
  133293. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_0 = {
  133294. _vq_quantthresh__44c0_sm_p8_0,
  133295. _vq_quantmap__44c0_sm_p8_0,
  133296. 9,
  133297. 9
  133298. };
  133299. static static_codebook _44c0_sm_p8_0 = {
  133300. 2, 81,
  133301. _vq_lengthlist__44c0_sm_p8_0,
  133302. 1, -516186112, 1627103232, 4, 0,
  133303. _vq_quantlist__44c0_sm_p8_0,
  133304. NULL,
  133305. &_vq_auxt__44c0_sm_p8_0,
  133306. NULL,
  133307. 0
  133308. };
  133309. static long _vq_quantlist__44c0_sm_p8_1[] = {
  133310. 6,
  133311. 5,
  133312. 7,
  133313. 4,
  133314. 8,
  133315. 3,
  133316. 9,
  133317. 2,
  133318. 10,
  133319. 1,
  133320. 11,
  133321. 0,
  133322. 12,
  133323. };
  133324. static long _vq_lengthlist__44c0_sm_p8_1[] = {
  133325. 1, 4, 4, 6, 6, 7, 7, 9, 9,10,11,12,12, 6, 5, 5,
  133326. 7, 7, 8, 8,10,10,12,11,12,12, 6, 5, 5, 7, 7, 8,
  133327. 8,10,10,12,11,12,12,17, 7, 7, 8, 8, 9, 9,10,10,
  133328. 12,12,13,13,18, 7, 7, 8, 7, 9, 9,10,10,12,12,12,
  133329. 13,19,10,10, 8, 8,10,10,11,11,12,12,13,14,19,11,
  133330. 10, 8, 7,10,10,11,11,12,12,13,12,19,19,19,10,10,
  133331. 10,10,11,11,12,12,13,13,19,19,19,11, 9,11, 9,14,
  133332. 12,13,12,13,13,19,20,18,13,14,11,11,12,12,13,13,
  133333. 14,13,20,20,20,15,13,11,10,13,11,13,13,14,13,20,
  133334. 20,20,20,20,13,14,12,12,13,13,13,13,20,20,20,20,
  133335. 20,13,13,12,12,16,13,15,13,
  133336. };
  133337. static float _vq_quantthresh__44c0_sm_p8_1[] = {
  133338. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  133339. 42.5, 59.5, 76.5, 93.5,
  133340. };
  133341. static long _vq_quantmap__44c0_sm_p8_1[] = {
  133342. 11, 9, 7, 5, 3, 1, 0, 2,
  133343. 4, 6, 8, 10, 12,
  133344. };
  133345. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_1 = {
  133346. _vq_quantthresh__44c0_sm_p8_1,
  133347. _vq_quantmap__44c0_sm_p8_1,
  133348. 13,
  133349. 13
  133350. };
  133351. static static_codebook _44c0_sm_p8_1 = {
  133352. 2, 169,
  133353. _vq_lengthlist__44c0_sm_p8_1,
  133354. 1, -522616832, 1620115456, 4, 0,
  133355. _vq_quantlist__44c0_sm_p8_1,
  133356. NULL,
  133357. &_vq_auxt__44c0_sm_p8_1,
  133358. NULL,
  133359. 0
  133360. };
  133361. static long _vq_quantlist__44c0_sm_p8_2[] = {
  133362. 8,
  133363. 7,
  133364. 9,
  133365. 6,
  133366. 10,
  133367. 5,
  133368. 11,
  133369. 4,
  133370. 12,
  133371. 3,
  133372. 13,
  133373. 2,
  133374. 14,
  133375. 1,
  133376. 15,
  133377. 0,
  133378. 16,
  133379. };
  133380. static long _vq_lengthlist__44c0_sm_p8_2[] = {
  133381. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  133382. 8,10, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  133383. 9, 9,10, 6, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  133384. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  133385. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  133386. 9,10, 9, 9,10,10,10,11, 8, 8, 8, 8, 9, 9, 9, 9,
  133387. 9, 9, 9,10, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  133388. 9, 9, 9, 9, 9,10,10,11,10,10, 8, 8, 9, 9, 9, 9,
  133389. 9, 9, 9, 9, 9, 9,10,10,10,10,10,11,11, 8, 8, 9,
  133390. 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,11,11,11, 9, 9,
  133391. 9, 9, 9, 9, 9, 9,10, 9,10, 9,11,11,10,11,11, 9,
  133392. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,11,10,11,11,
  133393. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,10,11,11,
  133394. 11,11,11, 9, 9,10, 9, 9, 9, 9, 9, 9, 9,10,11,10,
  133395. 11,11,11,11,10,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  133396. 11,11,11,11,11, 9,10, 9, 9, 9, 9, 9, 9, 9, 9,11,
  133397. 11,10,11,11,11,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  133398. 10,11,10,11,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,
  133399. 9,
  133400. };
  133401. static float _vq_quantthresh__44c0_sm_p8_2[] = {
  133402. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  133403. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  133404. };
  133405. static long _vq_quantmap__44c0_sm_p8_2[] = {
  133406. 15, 13, 11, 9, 7, 5, 3, 1,
  133407. 0, 2, 4, 6, 8, 10, 12, 14,
  133408. 16,
  133409. };
  133410. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_2 = {
  133411. _vq_quantthresh__44c0_sm_p8_2,
  133412. _vq_quantmap__44c0_sm_p8_2,
  133413. 17,
  133414. 17
  133415. };
  133416. static static_codebook _44c0_sm_p8_2 = {
  133417. 2, 289,
  133418. _vq_lengthlist__44c0_sm_p8_2,
  133419. 1, -529530880, 1611661312, 5, 0,
  133420. _vq_quantlist__44c0_sm_p8_2,
  133421. NULL,
  133422. &_vq_auxt__44c0_sm_p8_2,
  133423. NULL,
  133424. 0
  133425. };
  133426. static long _huff_lengthlist__44c0_sm_short[] = {
  133427. 6, 6,12,13,13,14,16,17,17, 4, 2, 5, 8, 7, 9,12,
  133428. 15,15, 9, 4, 5, 9, 7, 9,12,16,18,11, 6, 7, 4, 6,
  133429. 8,11,14,18,10, 5, 6, 5, 5, 7,10,14,17,10, 5, 7,
  133430. 7, 6, 7,10,13,16,11, 5, 7, 7, 7, 8,10,12,15,13,
  133431. 6, 7, 5, 5, 7, 9,12,13,16, 8, 9, 6, 6, 7, 9,10,
  133432. 12,
  133433. };
  133434. static static_codebook _huff_book__44c0_sm_short = {
  133435. 2, 81,
  133436. _huff_lengthlist__44c0_sm_short,
  133437. 0, 0, 0, 0, 0,
  133438. NULL,
  133439. NULL,
  133440. NULL,
  133441. NULL,
  133442. 0
  133443. };
  133444. static long _huff_lengthlist__44c1_s_long[] = {
  133445. 5, 5, 9,10, 9, 9,10,11,12, 5, 1, 5, 6, 6, 7,10,
  133446. 12,14, 9, 5, 6, 8, 8,10,12,14,14,10, 5, 8, 5, 6,
  133447. 8,11,13,14, 9, 5, 7, 6, 6, 8,10,12,11, 9, 7, 9,
  133448. 7, 6, 6, 7,10,10,10, 9,12, 9, 8, 7, 7,10,12,11,
  133449. 11,13,12,10, 9, 8, 9,11,11,14,15,15,13,11, 9, 9,
  133450. 11,
  133451. };
  133452. static static_codebook _huff_book__44c1_s_long = {
  133453. 2, 81,
  133454. _huff_lengthlist__44c1_s_long,
  133455. 0, 0, 0, 0, 0,
  133456. NULL,
  133457. NULL,
  133458. NULL,
  133459. NULL,
  133460. 0
  133461. };
  133462. static long _vq_quantlist__44c1_s_p1_0[] = {
  133463. 1,
  133464. 0,
  133465. 2,
  133466. };
  133467. static long _vq_lengthlist__44c1_s_p1_0[] = {
  133468. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 6, 0, 0, 0, 0,
  133469. 0, 0, 5, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133473. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  133474. 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133478. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  133479. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 7, 7, 0, 0, 0, 0,
  133514. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  133515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  133519. 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  133520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0, 0,
  133524. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  133525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133559. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  133560. 0, 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133564. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8,10, 9, 0,
  133565. 0, 0, 0, 0, 0, 8, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0,
  133566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133569. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  133570. 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  133571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133878. 0,
  133879. };
  133880. static float _vq_quantthresh__44c1_s_p1_0[] = {
  133881. -0.5, 0.5,
  133882. };
  133883. static long _vq_quantmap__44c1_s_p1_0[] = {
  133884. 1, 0, 2,
  133885. };
  133886. static encode_aux_threshmatch _vq_auxt__44c1_s_p1_0 = {
  133887. _vq_quantthresh__44c1_s_p1_0,
  133888. _vq_quantmap__44c1_s_p1_0,
  133889. 3,
  133890. 3
  133891. };
  133892. static static_codebook _44c1_s_p1_0 = {
  133893. 8, 6561,
  133894. _vq_lengthlist__44c1_s_p1_0,
  133895. 1, -535822336, 1611661312, 2, 0,
  133896. _vq_quantlist__44c1_s_p1_0,
  133897. NULL,
  133898. &_vq_auxt__44c1_s_p1_0,
  133899. NULL,
  133900. 0
  133901. };
  133902. static long _vq_quantlist__44c1_s_p2_0[] = {
  133903. 2,
  133904. 1,
  133905. 3,
  133906. 0,
  133907. 4,
  133908. };
  133909. static long _vq_lengthlist__44c1_s_p2_0[] = {
  133910. 2, 3, 4, 6, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  133912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133913. 0, 0, 4, 4, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 8, 8,
  133915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133916. 0, 0, 0, 0, 6, 6, 6, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  133917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133949. 0,
  133950. };
  133951. static float _vq_quantthresh__44c1_s_p2_0[] = {
  133952. -1.5, -0.5, 0.5, 1.5,
  133953. };
  133954. static long _vq_quantmap__44c1_s_p2_0[] = {
  133955. 3, 1, 0, 2, 4,
  133956. };
  133957. static encode_aux_threshmatch _vq_auxt__44c1_s_p2_0 = {
  133958. _vq_quantthresh__44c1_s_p2_0,
  133959. _vq_quantmap__44c1_s_p2_0,
  133960. 5,
  133961. 5
  133962. };
  133963. static static_codebook _44c1_s_p2_0 = {
  133964. 4, 625,
  133965. _vq_lengthlist__44c1_s_p2_0,
  133966. 1, -533725184, 1611661312, 3, 0,
  133967. _vq_quantlist__44c1_s_p2_0,
  133968. NULL,
  133969. &_vq_auxt__44c1_s_p2_0,
  133970. NULL,
  133971. 0
  133972. };
  133973. static long _vq_quantlist__44c1_s_p3_0[] = {
  133974. 4,
  133975. 3,
  133976. 5,
  133977. 2,
  133978. 6,
  133979. 1,
  133980. 7,
  133981. 0,
  133982. 8,
  133983. };
  133984. static long _vq_lengthlist__44c1_s_p3_0[] = {
  133985. 1, 3, 2, 7, 7, 0, 0, 0, 0, 0,13,13, 6, 6, 0, 0,
  133986. 0, 0, 0,12, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  133987. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  133988. 8, 9, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  133989. 0, 0,11,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133990. 0,
  133991. };
  133992. static float _vq_quantthresh__44c1_s_p3_0[] = {
  133993. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  133994. };
  133995. static long _vq_quantmap__44c1_s_p3_0[] = {
  133996. 7, 5, 3, 1, 0, 2, 4, 6,
  133997. 8,
  133998. };
  133999. static encode_aux_threshmatch _vq_auxt__44c1_s_p3_0 = {
  134000. _vq_quantthresh__44c1_s_p3_0,
  134001. _vq_quantmap__44c1_s_p3_0,
  134002. 9,
  134003. 9
  134004. };
  134005. static static_codebook _44c1_s_p3_0 = {
  134006. 2, 81,
  134007. _vq_lengthlist__44c1_s_p3_0,
  134008. 1, -531628032, 1611661312, 4, 0,
  134009. _vq_quantlist__44c1_s_p3_0,
  134010. NULL,
  134011. &_vq_auxt__44c1_s_p3_0,
  134012. NULL,
  134013. 0
  134014. };
  134015. static long _vq_quantlist__44c1_s_p4_0[] = {
  134016. 4,
  134017. 3,
  134018. 5,
  134019. 2,
  134020. 6,
  134021. 1,
  134022. 7,
  134023. 0,
  134024. 8,
  134025. };
  134026. static long _vq_lengthlist__44c1_s_p4_0[] = {
  134027. 1, 3, 3, 6, 5, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  134028. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  134029. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  134030. 9, 9, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  134031. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  134032. 11,
  134033. };
  134034. static float _vq_quantthresh__44c1_s_p4_0[] = {
  134035. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  134036. };
  134037. static long _vq_quantmap__44c1_s_p4_0[] = {
  134038. 7, 5, 3, 1, 0, 2, 4, 6,
  134039. 8,
  134040. };
  134041. static encode_aux_threshmatch _vq_auxt__44c1_s_p4_0 = {
  134042. _vq_quantthresh__44c1_s_p4_0,
  134043. _vq_quantmap__44c1_s_p4_0,
  134044. 9,
  134045. 9
  134046. };
  134047. static static_codebook _44c1_s_p4_0 = {
  134048. 2, 81,
  134049. _vq_lengthlist__44c1_s_p4_0,
  134050. 1, -531628032, 1611661312, 4, 0,
  134051. _vq_quantlist__44c1_s_p4_0,
  134052. NULL,
  134053. &_vq_auxt__44c1_s_p4_0,
  134054. NULL,
  134055. 0
  134056. };
  134057. static long _vq_quantlist__44c1_s_p5_0[] = {
  134058. 8,
  134059. 7,
  134060. 9,
  134061. 6,
  134062. 10,
  134063. 5,
  134064. 11,
  134065. 4,
  134066. 12,
  134067. 3,
  134068. 13,
  134069. 2,
  134070. 14,
  134071. 1,
  134072. 15,
  134073. 0,
  134074. 16,
  134075. };
  134076. static long _vq_lengthlist__44c1_s_p5_0[] = {
  134077. 1, 4, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  134078. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  134079. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  134080. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  134081. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  134082. 10,11,11,12,11, 0, 0, 0, 8, 8, 9, 9, 9,10,10,10,
  134083. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10, 9,10,
  134084. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  134085. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  134086. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  134087. 10,10,10,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  134088. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  134089. 10,10,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0,
  134090. 0, 0, 0,10,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  134091. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,13, 0, 0,
  134092. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0,
  134093. 0, 0, 0, 0, 0, 0,12,12,12,12,12,12,13,13,14,14,
  134094. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  134095. 14,
  134096. };
  134097. static float _vq_quantthresh__44c1_s_p5_0[] = {
  134098. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  134099. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  134100. };
  134101. static long _vq_quantmap__44c1_s_p5_0[] = {
  134102. 15, 13, 11, 9, 7, 5, 3, 1,
  134103. 0, 2, 4, 6, 8, 10, 12, 14,
  134104. 16,
  134105. };
  134106. static encode_aux_threshmatch _vq_auxt__44c1_s_p5_0 = {
  134107. _vq_quantthresh__44c1_s_p5_0,
  134108. _vq_quantmap__44c1_s_p5_0,
  134109. 17,
  134110. 17
  134111. };
  134112. static static_codebook _44c1_s_p5_0 = {
  134113. 2, 289,
  134114. _vq_lengthlist__44c1_s_p5_0,
  134115. 1, -529530880, 1611661312, 5, 0,
  134116. _vq_quantlist__44c1_s_p5_0,
  134117. NULL,
  134118. &_vq_auxt__44c1_s_p5_0,
  134119. NULL,
  134120. 0
  134121. };
  134122. static long _vq_quantlist__44c1_s_p6_0[] = {
  134123. 1,
  134124. 0,
  134125. 2,
  134126. };
  134127. static long _vq_lengthlist__44c1_s_p6_0[] = {
  134128. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  134129. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 6,10,10,11,11,
  134130. 11,11,10,10, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  134131. 11,10,11,11,10,10, 7,11,10,11,11,11,12,11,11, 7,
  134132. 9, 9,11,10,10,11,11,10, 6, 9, 9,10,10,10,12,10,
  134133. 11,
  134134. };
  134135. static float _vq_quantthresh__44c1_s_p6_0[] = {
  134136. -5.5, 5.5,
  134137. };
  134138. static long _vq_quantmap__44c1_s_p6_0[] = {
  134139. 1, 0, 2,
  134140. };
  134141. static encode_aux_threshmatch _vq_auxt__44c1_s_p6_0 = {
  134142. _vq_quantthresh__44c1_s_p6_0,
  134143. _vq_quantmap__44c1_s_p6_0,
  134144. 3,
  134145. 3
  134146. };
  134147. static static_codebook _44c1_s_p6_0 = {
  134148. 4, 81,
  134149. _vq_lengthlist__44c1_s_p6_0,
  134150. 1, -529137664, 1618345984, 2, 0,
  134151. _vq_quantlist__44c1_s_p6_0,
  134152. NULL,
  134153. &_vq_auxt__44c1_s_p6_0,
  134154. NULL,
  134155. 0
  134156. };
  134157. static long _vq_quantlist__44c1_s_p6_1[] = {
  134158. 5,
  134159. 4,
  134160. 6,
  134161. 3,
  134162. 7,
  134163. 2,
  134164. 8,
  134165. 1,
  134166. 9,
  134167. 0,
  134168. 10,
  134169. };
  134170. static long _vq_lengthlist__44c1_s_p6_1[] = {
  134171. 2, 3, 3, 6, 6, 7, 7, 7, 7, 8, 8,10,10,10, 6, 6,
  134172. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  134173. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  134174. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  134175. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  134176. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  134177. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  134178. 10,10,10, 8, 8, 8, 8, 8, 8,
  134179. };
  134180. static float _vq_quantthresh__44c1_s_p6_1[] = {
  134181. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  134182. 3.5, 4.5,
  134183. };
  134184. static long _vq_quantmap__44c1_s_p6_1[] = {
  134185. 9, 7, 5, 3, 1, 0, 2, 4,
  134186. 6, 8, 10,
  134187. };
  134188. static encode_aux_threshmatch _vq_auxt__44c1_s_p6_1 = {
  134189. _vq_quantthresh__44c1_s_p6_1,
  134190. _vq_quantmap__44c1_s_p6_1,
  134191. 11,
  134192. 11
  134193. };
  134194. static static_codebook _44c1_s_p6_1 = {
  134195. 2, 121,
  134196. _vq_lengthlist__44c1_s_p6_1,
  134197. 1, -531365888, 1611661312, 4, 0,
  134198. _vq_quantlist__44c1_s_p6_1,
  134199. NULL,
  134200. &_vq_auxt__44c1_s_p6_1,
  134201. NULL,
  134202. 0
  134203. };
  134204. static long _vq_quantlist__44c1_s_p7_0[] = {
  134205. 6,
  134206. 5,
  134207. 7,
  134208. 4,
  134209. 8,
  134210. 3,
  134211. 9,
  134212. 2,
  134213. 10,
  134214. 1,
  134215. 11,
  134216. 0,
  134217. 12,
  134218. };
  134219. static long _vq_lengthlist__44c1_s_p7_0[] = {
  134220. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 9, 7, 5, 6,
  134221. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5, 7, 7, 8,
  134222. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  134223. 10,10,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  134224. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,11,11, 0,13,
  134225. 13, 9, 9, 9, 9,10,10,11,11,11,11, 0, 0, 0,10,10,
  134226. 10,10,11,11,12,11,12,12, 0, 0, 0,10,10,10, 9,11,
  134227. 11,12,11,13,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  134228. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  134229. 0, 0, 0, 0,11,12,11,11,12,12,14,13, 0, 0, 0, 0,
  134230. 0,12,11,11,11,13,10,14,13,
  134231. };
  134232. static float _vq_quantthresh__44c1_s_p7_0[] = {
  134233. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  134234. 12.5, 17.5, 22.5, 27.5,
  134235. };
  134236. static long _vq_quantmap__44c1_s_p7_0[] = {
  134237. 11, 9, 7, 5, 3, 1, 0, 2,
  134238. 4, 6, 8, 10, 12,
  134239. };
  134240. static encode_aux_threshmatch _vq_auxt__44c1_s_p7_0 = {
  134241. _vq_quantthresh__44c1_s_p7_0,
  134242. _vq_quantmap__44c1_s_p7_0,
  134243. 13,
  134244. 13
  134245. };
  134246. static static_codebook _44c1_s_p7_0 = {
  134247. 2, 169,
  134248. _vq_lengthlist__44c1_s_p7_0,
  134249. 1, -526516224, 1616117760, 4, 0,
  134250. _vq_quantlist__44c1_s_p7_0,
  134251. NULL,
  134252. &_vq_auxt__44c1_s_p7_0,
  134253. NULL,
  134254. 0
  134255. };
  134256. static long _vq_quantlist__44c1_s_p7_1[] = {
  134257. 2,
  134258. 1,
  134259. 3,
  134260. 0,
  134261. 4,
  134262. };
  134263. static long _vq_lengthlist__44c1_s_p7_1[] = {
  134264. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  134265. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  134266. };
  134267. static float _vq_quantthresh__44c1_s_p7_1[] = {
  134268. -1.5, -0.5, 0.5, 1.5,
  134269. };
  134270. static long _vq_quantmap__44c1_s_p7_1[] = {
  134271. 3, 1, 0, 2, 4,
  134272. };
  134273. static encode_aux_threshmatch _vq_auxt__44c1_s_p7_1 = {
  134274. _vq_quantthresh__44c1_s_p7_1,
  134275. _vq_quantmap__44c1_s_p7_1,
  134276. 5,
  134277. 5
  134278. };
  134279. static static_codebook _44c1_s_p7_1 = {
  134280. 2, 25,
  134281. _vq_lengthlist__44c1_s_p7_1,
  134282. 1, -533725184, 1611661312, 3, 0,
  134283. _vq_quantlist__44c1_s_p7_1,
  134284. NULL,
  134285. &_vq_auxt__44c1_s_p7_1,
  134286. NULL,
  134287. 0
  134288. };
  134289. static long _vq_quantlist__44c1_s_p8_0[] = {
  134290. 6,
  134291. 5,
  134292. 7,
  134293. 4,
  134294. 8,
  134295. 3,
  134296. 9,
  134297. 2,
  134298. 10,
  134299. 1,
  134300. 11,
  134301. 0,
  134302. 12,
  134303. };
  134304. static long _vq_lengthlist__44c1_s_p8_0[] = {
  134305. 1, 4, 3,10,10,10,10,10,10,10,10,10,10, 4, 8, 6,
  134306. 10,10,10,10,10,10,10,10,10,10, 4, 8, 7,10,10,10,
  134307. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  134308. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  134309. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  134310. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  134311. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  134312. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  134313. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  134314. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  134315. 10,10,10,10,10,10,10,10,10,
  134316. };
  134317. static float _vq_quantthresh__44c1_s_p8_0[] = {
  134318. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  134319. 552.5, 773.5, 994.5, 1215.5,
  134320. };
  134321. static long _vq_quantmap__44c1_s_p8_0[] = {
  134322. 11, 9, 7, 5, 3, 1, 0, 2,
  134323. 4, 6, 8, 10, 12,
  134324. };
  134325. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_0 = {
  134326. _vq_quantthresh__44c1_s_p8_0,
  134327. _vq_quantmap__44c1_s_p8_0,
  134328. 13,
  134329. 13
  134330. };
  134331. static static_codebook _44c1_s_p8_0 = {
  134332. 2, 169,
  134333. _vq_lengthlist__44c1_s_p8_0,
  134334. 1, -514541568, 1627103232, 4, 0,
  134335. _vq_quantlist__44c1_s_p8_0,
  134336. NULL,
  134337. &_vq_auxt__44c1_s_p8_0,
  134338. NULL,
  134339. 0
  134340. };
  134341. static long _vq_quantlist__44c1_s_p8_1[] = {
  134342. 6,
  134343. 5,
  134344. 7,
  134345. 4,
  134346. 8,
  134347. 3,
  134348. 9,
  134349. 2,
  134350. 10,
  134351. 1,
  134352. 11,
  134353. 0,
  134354. 12,
  134355. };
  134356. static long _vq_lengthlist__44c1_s_p8_1[] = {
  134357. 1, 4, 4, 6, 5, 7, 7, 9, 9,10,10,12,12, 6, 5, 5,
  134358. 7, 7, 8, 8,10,10,12,11,12,12, 6, 5, 5, 7, 7, 8,
  134359. 8,10,10,11,11,12,12,15, 7, 7, 8, 8, 9, 9,11,11,
  134360. 12,12,13,12,15, 8, 8, 8, 7, 9, 9,10,10,12,12,13,
  134361. 13,16,11,10, 8, 8,10,10,11,11,12,12,13,13,16,11,
  134362. 11, 9, 8,11,10,11,11,12,12,13,12,16,16,16,10,11,
  134363. 10,11,12,12,12,12,13,13,16,16,16,11, 9,11, 9,14,
  134364. 12,12,12,13,13,16,16,16,12,14,11,12,12,12,13,13,
  134365. 14,13,16,16,16,15,13,12,10,13,10,13,14,13,13,16,
  134366. 16,16,16,16,13,14,12,13,13,12,13,13,16,16,16,16,
  134367. 16,13,12,12,11,14,12,15,13,
  134368. };
  134369. static float _vq_quantthresh__44c1_s_p8_1[] = {
  134370. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  134371. 42.5, 59.5, 76.5, 93.5,
  134372. };
  134373. static long _vq_quantmap__44c1_s_p8_1[] = {
  134374. 11, 9, 7, 5, 3, 1, 0, 2,
  134375. 4, 6, 8, 10, 12,
  134376. };
  134377. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_1 = {
  134378. _vq_quantthresh__44c1_s_p8_1,
  134379. _vq_quantmap__44c1_s_p8_1,
  134380. 13,
  134381. 13
  134382. };
  134383. static static_codebook _44c1_s_p8_1 = {
  134384. 2, 169,
  134385. _vq_lengthlist__44c1_s_p8_1,
  134386. 1, -522616832, 1620115456, 4, 0,
  134387. _vq_quantlist__44c1_s_p8_1,
  134388. NULL,
  134389. &_vq_auxt__44c1_s_p8_1,
  134390. NULL,
  134391. 0
  134392. };
  134393. static long _vq_quantlist__44c1_s_p8_2[] = {
  134394. 8,
  134395. 7,
  134396. 9,
  134397. 6,
  134398. 10,
  134399. 5,
  134400. 11,
  134401. 4,
  134402. 12,
  134403. 3,
  134404. 13,
  134405. 2,
  134406. 14,
  134407. 1,
  134408. 15,
  134409. 0,
  134410. 16,
  134411. };
  134412. static long _vq_lengthlist__44c1_s_p8_2[] = {
  134413. 2, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  134414. 8,10,10,10, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  134415. 9, 9,10,10,10, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  134416. 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  134417. 9,10, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  134418. 9,10, 9, 9,10,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  134419. 9, 9,10, 9, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  134420. 9, 9, 9, 9, 9,10,10,11,11,11, 8, 8, 9, 9, 9, 9,
  134421. 9, 9, 9, 9, 9, 9,10,10,10,10,11,11,11, 8, 8, 9,
  134422. 9, 9, 9,10, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9,
  134423. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,11, 9,
  134424. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,11,10,11,11,
  134425. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10,10,11,11,
  134426. 11,11,11, 9, 9, 9,10, 9, 9, 9, 9, 9, 9,10,11,11,
  134427. 11,11,11,11,10,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  134428. 11,11,11,11,11, 9,10, 9, 9, 9, 9,10, 9, 9, 9,11,
  134429. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9,10, 9,
  134430. 11,11,10,11,11,11,11,10,11, 9, 9, 9, 9, 9, 9, 9,
  134431. 9,
  134432. };
  134433. static float _vq_quantthresh__44c1_s_p8_2[] = {
  134434. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  134435. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  134436. };
  134437. static long _vq_quantmap__44c1_s_p8_2[] = {
  134438. 15, 13, 11, 9, 7, 5, 3, 1,
  134439. 0, 2, 4, 6, 8, 10, 12, 14,
  134440. 16,
  134441. };
  134442. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_2 = {
  134443. _vq_quantthresh__44c1_s_p8_2,
  134444. _vq_quantmap__44c1_s_p8_2,
  134445. 17,
  134446. 17
  134447. };
  134448. static static_codebook _44c1_s_p8_2 = {
  134449. 2, 289,
  134450. _vq_lengthlist__44c1_s_p8_2,
  134451. 1, -529530880, 1611661312, 5, 0,
  134452. _vq_quantlist__44c1_s_p8_2,
  134453. NULL,
  134454. &_vq_auxt__44c1_s_p8_2,
  134455. NULL,
  134456. 0
  134457. };
  134458. static long _huff_lengthlist__44c1_s_short[] = {
  134459. 6, 8,13,12,13,14,15,16,16, 4, 2, 4, 7, 6, 8,11,
  134460. 13,15,10, 4, 4, 8, 6, 8,11,14,17,11, 5, 6, 5, 6,
  134461. 8,12,14,17,11, 5, 5, 6, 5, 7,10,13,16,12, 6, 7,
  134462. 8, 7, 8,10,13,15,13, 8, 8, 7, 7, 8,10,12,15,15,
  134463. 7, 7, 5, 5, 7, 9,12,14,15, 8, 8, 6, 6, 7, 8,10,
  134464. 11,
  134465. };
  134466. static static_codebook _huff_book__44c1_s_short = {
  134467. 2, 81,
  134468. _huff_lengthlist__44c1_s_short,
  134469. 0, 0, 0, 0, 0,
  134470. NULL,
  134471. NULL,
  134472. NULL,
  134473. NULL,
  134474. 0
  134475. };
  134476. static long _huff_lengthlist__44c1_sm_long[] = {
  134477. 5, 4, 8,10, 9, 9,10,11,12, 4, 2, 5, 6, 6, 8,10,
  134478. 11,13, 8, 4, 6, 8, 7, 9,12,12,14,10, 6, 8, 4, 5,
  134479. 6, 9,11,12, 9, 5, 6, 5, 5, 6, 9,11,11, 9, 7, 9,
  134480. 6, 5, 5, 7,10,10,10, 9,11, 8, 7, 6, 7, 9,11,11,
  134481. 12,13,10,10, 9, 8, 9,11,11,15,15,12,13,11, 9,10,
  134482. 11,
  134483. };
  134484. static static_codebook _huff_book__44c1_sm_long = {
  134485. 2, 81,
  134486. _huff_lengthlist__44c1_sm_long,
  134487. 0, 0, 0, 0, 0,
  134488. NULL,
  134489. NULL,
  134490. NULL,
  134491. NULL,
  134492. 0
  134493. };
  134494. static long _vq_quantlist__44c1_sm_p1_0[] = {
  134495. 1,
  134496. 0,
  134497. 2,
  134498. };
  134499. static long _vq_lengthlist__44c1_sm_p1_0[] = {
  134500. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  134501. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134505. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  134506. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134510. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  134511. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 0,
  134546. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  134547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  134551. 0, 0, 0, 9, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  134552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  134556. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  134557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134591. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  134592. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134596. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  134597. 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  134598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134601. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  134602. 0, 0, 0, 0, 0, 0, 9,10, 9, 0, 0, 0, 0, 0, 0, 0,
  134603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134910. 0,
  134911. };
  134912. static float _vq_quantthresh__44c1_sm_p1_0[] = {
  134913. -0.5, 0.5,
  134914. };
  134915. static long _vq_quantmap__44c1_sm_p1_0[] = {
  134916. 1, 0, 2,
  134917. };
  134918. static encode_aux_threshmatch _vq_auxt__44c1_sm_p1_0 = {
  134919. _vq_quantthresh__44c1_sm_p1_0,
  134920. _vq_quantmap__44c1_sm_p1_0,
  134921. 3,
  134922. 3
  134923. };
  134924. static static_codebook _44c1_sm_p1_0 = {
  134925. 8, 6561,
  134926. _vq_lengthlist__44c1_sm_p1_0,
  134927. 1, -535822336, 1611661312, 2, 0,
  134928. _vq_quantlist__44c1_sm_p1_0,
  134929. NULL,
  134930. &_vq_auxt__44c1_sm_p1_0,
  134931. NULL,
  134932. 0
  134933. };
  134934. static long _vq_quantlist__44c1_sm_p2_0[] = {
  134935. 2,
  134936. 1,
  134937. 3,
  134938. 0,
  134939. 4,
  134940. };
  134941. static long _vq_lengthlist__44c1_sm_p2_0[] = {
  134942. 2, 3, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  134944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134945. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  134947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134948. 0, 0, 0, 0, 6, 6, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  134949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134981. 0,
  134982. };
  134983. static float _vq_quantthresh__44c1_sm_p2_0[] = {
  134984. -1.5, -0.5, 0.5, 1.5,
  134985. };
  134986. static long _vq_quantmap__44c1_sm_p2_0[] = {
  134987. 3, 1, 0, 2, 4,
  134988. };
  134989. static encode_aux_threshmatch _vq_auxt__44c1_sm_p2_0 = {
  134990. _vq_quantthresh__44c1_sm_p2_0,
  134991. _vq_quantmap__44c1_sm_p2_0,
  134992. 5,
  134993. 5
  134994. };
  134995. static static_codebook _44c1_sm_p2_0 = {
  134996. 4, 625,
  134997. _vq_lengthlist__44c1_sm_p2_0,
  134998. 1, -533725184, 1611661312, 3, 0,
  134999. _vq_quantlist__44c1_sm_p2_0,
  135000. NULL,
  135001. &_vq_auxt__44c1_sm_p2_0,
  135002. NULL,
  135003. 0
  135004. };
  135005. static long _vq_quantlist__44c1_sm_p3_0[] = {
  135006. 4,
  135007. 3,
  135008. 5,
  135009. 2,
  135010. 6,
  135011. 1,
  135012. 7,
  135013. 0,
  135014. 8,
  135015. };
  135016. static long _vq_lengthlist__44c1_sm_p3_0[] = {
  135017. 1, 3, 3, 7, 7, 0, 0, 0, 0, 0, 5, 5, 6, 6, 0, 0,
  135018. 0, 0, 0, 5, 5, 7, 7, 0, 0, 0, 0, 0, 7, 7, 7, 7,
  135019. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  135020. 8, 9, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  135021. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135022. 0,
  135023. };
  135024. static float _vq_quantthresh__44c1_sm_p3_0[] = {
  135025. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  135026. };
  135027. static long _vq_quantmap__44c1_sm_p3_0[] = {
  135028. 7, 5, 3, 1, 0, 2, 4, 6,
  135029. 8,
  135030. };
  135031. static encode_aux_threshmatch _vq_auxt__44c1_sm_p3_0 = {
  135032. _vq_quantthresh__44c1_sm_p3_0,
  135033. _vq_quantmap__44c1_sm_p3_0,
  135034. 9,
  135035. 9
  135036. };
  135037. static static_codebook _44c1_sm_p3_0 = {
  135038. 2, 81,
  135039. _vq_lengthlist__44c1_sm_p3_0,
  135040. 1, -531628032, 1611661312, 4, 0,
  135041. _vq_quantlist__44c1_sm_p3_0,
  135042. NULL,
  135043. &_vq_auxt__44c1_sm_p3_0,
  135044. NULL,
  135045. 0
  135046. };
  135047. static long _vq_quantlist__44c1_sm_p4_0[] = {
  135048. 4,
  135049. 3,
  135050. 5,
  135051. 2,
  135052. 6,
  135053. 1,
  135054. 7,
  135055. 0,
  135056. 8,
  135057. };
  135058. static long _vq_lengthlist__44c1_sm_p4_0[] = {
  135059. 1, 3, 3, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7, 8, 8,
  135060. 9, 9, 0, 6, 6, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  135061. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  135062. 8, 8, 9, 9,11,11, 0, 0, 0, 9, 9, 9, 9,11,11, 0,
  135063. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  135064. 11,
  135065. };
  135066. static float _vq_quantthresh__44c1_sm_p4_0[] = {
  135067. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  135068. };
  135069. static long _vq_quantmap__44c1_sm_p4_0[] = {
  135070. 7, 5, 3, 1, 0, 2, 4, 6,
  135071. 8,
  135072. };
  135073. static encode_aux_threshmatch _vq_auxt__44c1_sm_p4_0 = {
  135074. _vq_quantthresh__44c1_sm_p4_0,
  135075. _vq_quantmap__44c1_sm_p4_0,
  135076. 9,
  135077. 9
  135078. };
  135079. static static_codebook _44c1_sm_p4_0 = {
  135080. 2, 81,
  135081. _vq_lengthlist__44c1_sm_p4_0,
  135082. 1, -531628032, 1611661312, 4, 0,
  135083. _vq_quantlist__44c1_sm_p4_0,
  135084. NULL,
  135085. &_vq_auxt__44c1_sm_p4_0,
  135086. NULL,
  135087. 0
  135088. };
  135089. static long _vq_quantlist__44c1_sm_p5_0[] = {
  135090. 8,
  135091. 7,
  135092. 9,
  135093. 6,
  135094. 10,
  135095. 5,
  135096. 11,
  135097. 4,
  135098. 12,
  135099. 3,
  135100. 13,
  135101. 2,
  135102. 14,
  135103. 1,
  135104. 15,
  135105. 0,
  135106. 16,
  135107. };
  135108. static long _vq_lengthlist__44c1_sm_p5_0[] = {
  135109. 2, 3, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  135110. 11, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,
  135111. 11,11, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,
  135112. 10,11,11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  135113. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  135114. 10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9,10,10,
  135115. 10,11,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9,10,
  135116. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  135117. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  135118. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  135119. 9, 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  135120. 9, 9, 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  135121. 9, 9,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0,
  135122. 0, 0, 0,10,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  135123. 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0, 0,
  135124. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0,
  135125. 0, 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14,
  135126. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  135127. 14,
  135128. };
  135129. static float _vq_quantthresh__44c1_sm_p5_0[] = {
  135130. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  135131. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  135132. };
  135133. static long _vq_quantmap__44c1_sm_p5_0[] = {
  135134. 15, 13, 11, 9, 7, 5, 3, 1,
  135135. 0, 2, 4, 6, 8, 10, 12, 14,
  135136. 16,
  135137. };
  135138. static encode_aux_threshmatch _vq_auxt__44c1_sm_p5_0 = {
  135139. _vq_quantthresh__44c1_sm_p5_0,
  135140. _vq_quantmap__44c1_sm_p5_0,
  135141. 17,
  135142. 17
  135143. };
  135144. static static_codebook _44c1_sm_p5_0 = {
  135145. 2, 289,
  135146. _vq_lengthlist__44c1_sm_p5_0,
  135147. 1, -529530880, 1611661312, 5, 0,
  135148. _vq_quantlist__44c1_sm_p5_0,
  135149. NULL,
  135150. &_vq_auxt__44c1_sm_p5_0,
  135151. NULL,
  135152. 0
  135153. };
  135154. static long _vq_quantlist__44c1_sm_p6_0[] = {
  135155. 1,
  135156. 0,
  135157. 2,
  135158. };
  135159. static long _vq_lengthlist__44c1_sm_p6_0[] = {
  135160. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  135161. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  135162. 11,11,10,10, 6, 9, 9,11,11,10,11,10,10, 6, 9, 9,
  135163. 11,10,11,11,10,10, 7,11,11,11,11,11,11,11,11, 6,
  135164. 9, 9,11,10,10,11,11,10, 6, 9, 9,10,10,10,11,10,
  135165. 11,
  135166. };
  135167. static float _vq_quantthresh__44c1_sm_p6_0[] = {
  135168. -5.5, 5.5,
  135169. };
  135170. static long _vq_quantmap__44c1_sm_p6_0[] = {
  135171. 1, 0, 2,
  135172. };
  135173. static encode_aux_threshmatch _vq_auxt__44c1_sm_p6_0 = {
  135174. _vq_quantthresh__44c1_sm_p6_0,
  135175. _vq_quantmap__44c1_sm_p6_0,
  135176. 3,
  135177. 3
  135178. };
  135179. static static_codebook _44c1_sm_p6_0 = {
  135180. 4, 81,
  135181. _vq_lengthlist__44c1_sm_p6_0,
  135182. 1, -529137664, 1618345984, 2, 0,
  135183. _vq_quantlist__44c1_sm_p6_0,
  135184. NULL,
  135185. &_vq_auxt__44c1_sm_p6_0,
  135186. NULL,
  135187. 0
  135188. };
  135189. static long _vq_quantlist__44c1_sm_p6_1[] = {
  135190. 5,
  135191. 4,
  135192. 6,
  135193. 3,
  135194. 7,
  135195. 2,
  135196. 8,
  135197. 1,
  135198. 9,
  135199. 0,
  135200. 10,
  135201. };
  135202. static long _vq_lengthlist__44c1_sm_p6_1[] = {
  135203. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  135204. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  135205. 8,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  135206. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  135207. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  135208. 8, 8, 8, 8, 8, 8, 9, 8,10,10,10,10,10, 8, 8, 8,
  135209. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  135210. 10,10,10, 8, 8, 8, 8, 8, 8,
  135211. };
  135212. static float _vq_quantthresh__44c1_sm_p6_1[] = {
  135213. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  135214. 3.5, 4.5,
  135215. };
  135216. static long _vq_quantmap__44c1_sm_p6_1[] = {
  135217. 9, 7, 5, 3, 1, 0, 2, 4,
  135218. 6, 8, 10,
  135219. };
  135220. static encode_aux_threshmatch _vq_auxt__44c1_sm_p6_1 = {
  135221. _vq_quantthresh__44c1_sm_p6_1,
  135222. _vq_quantmap__44c1_sm_p6_1,
  135223. 11,
  135224. 11
  135225. };
  135226. static static_codebook _44c1_sm_p6_1 = {
  135227. 2, 121,
  135228. _vq_lengthlist__44c1_sm_p6_1,
  135229. 1, -531365888, 1611661312, 4, 0,
  135230. _vq_quantlist__44c1_sm_p6_1,
  135231. NULL,
  135232. &_vq_auxt__44c1_sm_p6_1,
  135233. NULL,
  135234. 0
  135235. };
  135236. static long _vq_quantlist__44c1_sm_p7_0[] = {
  135237. 6,
  135238. 5,
  135239. 7,
  135240. 4,
  135241. 8,
  135242. 3,
  135243. 9,
  135244. 2,
  135245. 10,
  135246. 1,
  135247. 11,
  135248. 0,
  135249. 12,
  135250. };
  135251. static long _vq_lengthlist__44c1_sm_p7_0[] = {
  135252. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  135253. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 6, 7, 7, 8,
  135254. 8, 8, 8, 9, 9,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  135255. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  135256. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  135257. 13, 9, 9, 9, 9,10,10,11,11,12,12, 0, 0, 0, 9,10,
  135258. 9,10,11,11,12,11,13,12, 0, 0, 0,10,10, 9, 9,11,
  135259. 11,12,12,13,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  135260. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  135261. 0, 0, 0, 0,11,12,11,11,12,13,14,13, 0, 0, 0, 0,
  135262. 0,12,12,11,11,13,12,14,13,
  135263. };
  135264. static float _vq_quantthresh__44c1_sm_p7_0[] = {
  135265. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  135266. 12.5, 17.5, 22.5, 27.5,
  135267. };
  135268. static long _vq_quantmap__44c1_sm_p7_0[] = {
  135269. 11, 9, 7, 5, 3, 1, 0, 2,
  135270. 4, 6, 8, 10, 12,
  135271. };
  135272. static encode_aux_threshmatch _vq_auxt__44c1_sm_p7_0 = {
  135273. _vq_quantthresh__44c1_sm_p7_0,
  135274. _vq_quantmap__44c1_sm_p7_0,
  135275. 13,
  135276. 13
  135277. };
  135278. static static_codebook _44c1_sm_p7_0 = {
  135279. 2, 169,
  135280. _vq_lengthlist__44c1_sm_p7_0,
  135281. 1, -526516224, 1616117760, 4, 0,
  135282. _vq_quantlist__44c1_sm_p7_0,
  135283. NULL,
  135284. &_vq_auxt__44c1_sm_p7_0,
  135285. NULL,
  135286. 0
  135287. };
  135288. static long _vq_quantlist__44c1_sm_p7_1[] = {
  135289. 2,
  135290. 1,
  135291. 3,
  135292. 0,
  135293. 4,
  135294. };
  135295. static long _vq_lengthlist__44c1_sm_p7_1[] = {
  135296. 2, 4, 4, 4, 5, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  135297. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  135298. };
  135299. static float _vq_quantthresh__44c1_sm_p7_1[] = {
  135300. -1.5, -0.5, 0.5, 1.5,
  135301. };
  135302. static long _vq_quantmap__44c1_sm_p7_1[] = {
  135303. 3, 1, 0, 2, 4,
  135304. };
  135305. static encode_aux_threshmatch _vq_auxt__44c1_sm_p7_1 = {
  135306. _vq_quantthresh__44c1_sm_p7_1,
  135307. _vq_quantmap__44c1_sm_p7_1,
  135308. 5,
  135309. 5
  135310. };
  135311. static static_codebook _44c1_sm_p7_1 = {
  135312. 2, 25,
  135313. _vq_lengthlist__44c1_sm_p7_1,
  135314. 1, -533725184, 1611661312, 3, 0,
  135315. _vq_quantlist__44c1_sm_p7_1,
  135316. NULL,
  135317. &_vq_auxt__44c1_sm_p7_1,
  135318. NULL,
  135319. 0
  135320. };
  135321. static long _vq_quantlist__44c1_sm_p8_0[] = {
  135322. 6,
  135323. 5,
  135324. 7,
  135325. 4,
  135326. 8,
  135327. 3,
  135328. 9,
  135329. 2,
  135330. 10,
  135331. 1,
  135332. 11,
  135333. 0,
  135334. 12,
  135335. };
  135336. static long _vq_lengthlist__44c1_sm_p8_0[] = {
  135337. 1, 3, 3,13,13,13,13,13,13,13,13,13,13, 3, 6, 6,
  135338. 13,13,13,13,13,13,13,13,13,13, 4, 8, 7,13,13,13,
  135339. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  135340. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  135341. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  135342. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  135343. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  135344. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  135345. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  135346. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  135347. 13,13,13,13,13,13,13,13,13,
  135348. };
  135349. static float _vq_quantthresh__44c1_sm_p8_0[] = {
  135350. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  135351. 552.5, 773.5, 994.5, 1215.5,
  135352. };
  135353. static long _vq_quantmap__44c1_sm_p8_0[] = {
  135354. 11, 9, 7, 5, 3, 1, 0, 2,
  135355. 4, 6, 8, 10, 12,
  135356. };
  135357. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_0 = {
  135358. _vq_quantthresh__44c1_sm_p8_0,
  135359. _vq_quantmap__44c1_sm_p8_0,
  135360. 13,
  135361. 13
  135362. };
  135363. static static_codebook _44c1_sm_p8_0 = {
  135364. 2, 169,
  135365. _vq_lengthlist__44c1_sm_p8_0,
  135366. 1, -514541568, 1627103232, 4, 0,
  135367. _vq_quantlist__44c1_sm_p8_0,
  135368. NULL,
  135369. &_vq_auxt__44c1_sm_p8_0,
  135370. NULL,
  135371. 0
  135372. };
  135373. static long _vq_quantlist__44c1_sm_p8_1[] = {
  135374. 6,
  135375. 5,
  135376. 7,
  135377. 4,
  135378. 8,
  135379. 3,
  135380. 9,
  135381. 2,
  135382. 10,
  135383. 1,
  135384. 11,
  135385. 0,
  135386. 12,
  135387. };
  135388. static long _vq_lengthlist__44c1_sm_p8_1[] = {
  135389. 1, 4, 4, 6, 6, 7, 7, 9, 9,10,11,12,12, 6, 5, 5,
  135390. 7, 7, 8, 7,10,10,11,11,12,12, 6, 5, 5, 7, 7, 8,
  135391. 8,10,10,11,11,12,12,16, 7, 7, 8, 8, 9, 9,11,11,
  135392. 12,12,13,13,17, 7, 7, 8, 7, 9, 9,11,10,12,12,13,
  135393. 13,19,11,10, 8, 8,10,10,11,11,12,12,13,13,19,11,
  135394. 11, 9, 7,11,10,11,11,12,12,13,12,19,19,19,10,10,
  135395. 10,10,11,12,12,12,13,14,18,19,19,11, 9,11, 9,13,
  135396. 12,12,12,13,13,19,20,19,13,15,11,11,12,12,13,13,
  135397. 14,13,18,19,20,15,13,12,10,13,10,13,13,13,14,20,
  135398. 20,20,20,20,13,14,12,12,13,12,13,13,20,20,20,20,
  135399. 20,13,12,12,12,14,12,14,13,
  135400. };
  135401. static float _vq_quantthresh__44c1_sm_p8_1[] = {
  135402. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  135403. 42.5, 59.5, 76.5, 93.5,
  135404. };
  135405. static long _vq_quantmap__44c1_sm_p8_1[] = {
  135406. 11, 9, 7, 5, 3, 1, 0, 2,
  135407. 4, 6, 8, 10, 12,
  135408. };
  135409. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_1 = {
  135410. _vq_quantthresh__44c1_sm_p8_1,
  135411. _vq_quantmap__44c1_sm_p8_1,
  135412. 13,
  135413. 13
  135414. };
  135415. static static_codebook _44c1_sm_p8_1 = {
  135416. 2, 169,
  135417. _vq_lengthlist__44c1_sm_p8_1,
  135418. 1, -522616832, 1620115456, 4, 0,
  135419. _vq_quantlist__44c1_sm_p8_1,
  135420. NULL,
  135421. &_vq_auxt__44c1_sm_p8_1,
  135422. NULL,
  135423. 0
  135424. };
  135425. static long _vq_quantlist__44c1_sm_p8_2[] = {
  135426. 8,
  135427. 7,
  135428. 9,
  135429. 6,
  135430. 10,
  135431. 5,
  135432. 11,
  135433. 4,
  135434. 12,
  135435. 3,
  135436. 13,
  135437. 2,
  135438. 14,
  135439. 1,
  135440. 15,
  135441. 0,
  135442. 16,
  135443. };
  135444. static long _vq_lengthlist__44c1_sm_p8_2[] = {
  135445. 2, 5, 5, 6, 6, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  135446. 8,10, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  135447. 9, 9,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  135448. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  135449. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  135450. 9, 9, 9, 9, 9,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  135451. 9, 9,10,10, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  135452. 9, 9, 9, 9, 9,10,10,11,10,10, 8, 8, 9, 9, 9, 9,
  135453. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,11,11, 8, 8, 9,
  135454. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9,
  135455. 9, 9, 9, 9, 9, 9,10, 9,10, 9,11,11,11,11,11, 9,
  135456. 8, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,10,11,11,
  135457. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,11,11,
  135458. 11,11,11, 9, 9,10, 9, 9, 9, 9,10, 9,10,10,11,10,
  135459. 11,11,11,11, 9,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  135460. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,
  135461. 11,10,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9,10, 9,
  135462. 10,11,10,11,11,11,11,11,11, 9, 9,10, 9, 9, 9, 9,
  135463. 9,
  135464. };
  135465. static float _vq_quantthresh__44c1_sm_p8_2[] = {
  135466. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  135467. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  135468. };
  135469. static long _vq_quantmap__44c1_sm_p8_2[] = {
  135470. 15, 13, 11, 9, 7, 5, 3, 1,
  135471. 0, 2, 4, 6, 8, 10, 12, 14,
  135472. 16,
  135473. };
  135474. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_2 = {
  135475. _vq_quantthresh__44c1_sm_p8_2,
  135476. _vq_quantmap__44c1_sm_p8_2,
  135477. 17,
  135478. 17
  135479. };
  135480. static static_codebook _44c1_sm_p8_2 = {
  135481. 2, 289,
  135482. _vq_lengthlist__44c1_sm_p8_2,
  135483. 1, -529530880, 1611661312, 5, 0,
  135484. _vq_quantlist__44c1_sm_p8_2,
  135485. NULL,
  135486. &_vq_auxt__44c1_sm_p8_2,
  135487. NULL,
  135488. 0
  135489. };
  135490. static long _huff_lengthlist__44c1_sm_short[] = {
  135491. 4, 7,13,14,14,15,16,18,18, 4, 2, 5, 8, 7, 9,12,
  135492. 15,15,10, 4, 5,10, 6, 8,11,15,17,12, 5, 7, 5, 6,
  135493. 8,11,14,17,11, 5, 6, 6, 5, 6, 9,13,17,12, 6, 7,
  135494. 6, 5, 6, 8,12,14,14, 7, 8, 6, 6, 7, 9,11,14,14,
  135495. 8, 9, 6, 5, 6, 9,11,13,16,10,10, 7, 6, 7, 8,10,
  135496. 11,
  135497. };
  135498. static static_codebook _huff_book__44c1_sm_short = {
  135499. 2, 81,
  135500. _huff_lengthlist__44c1_sm_short,
  135501. 0, 0, 0, 0, 0,
  135502. NULL,
  135503. NULL,
  135504. NULL,
  135505. NULL,
  135506. 0
  135507. };
  135508. static long _huff_lengthlist__44cn1_s_long[] = {
  135509. 4, 4, 7, 8, 7, 8,10,12,17, 3, 1, 6, 6, 7, 8,10,
  135510. 12,15, 7, 6, 9, 9, 9,11,12,14,17, 8, 6, 9, 6, 7,
  135511. 9,11,13,17, 7, 6, 9, 7, 7, 8, 9,12,15, 8, 8,10,
  135512. 8, 7, 7, 7,10,14, 9,10,12,10, 8, 8, 8,10,14,11,
  135513. 13,15,13,12,11,11,12,16,17,18,18,19,20,18,16,16,
  135514. 20,
  135515. };
  135516. static static_codebook _huff_book__44cn1_s_long = {
  135517. 2, 81,
  135518. _huff_lengthlist__44cn1_s_long,
  135519. 0, 0, 0, 0, 0,
  135520. NULL,
  135521. NULL,
  135522. NULL,
  135523. NULL,
  135524. 0
  135525. };
  135526. static long _vq_quantlist__44cn1_s_p1_0[] = {
  135527. 1,
  135528. 0,
  135529. 2,
  135530. };
  135531. static long _vq_lengthlist__44cn1_s_p1_0[] = {
  135532. 1, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  135533. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135537. 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0,
  135538. 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135542. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7,10, 9, 0, 0,
  135543. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  135578. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8, 9,10, 0, 0,
  135579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10,10, 0, 0, 0,
  135583. 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0,10,11,11, 0,
  135584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10,10, 0, 0,
  135588. 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0,10,11,11,
  135589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135623. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0,
  135624. 0, 0, 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135628. 0, 0, 0, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,11, 0,
  135629. 0, 0, 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0, 0, 0,
  135630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135633. 0, 0, 0, 0, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,11,
  135634. 0, 0, 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0, 0,
  135635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135942. 0,
  135943. };
  135944. static float _vq_quantthresh__44cn1_s_p1_0[] = {
  135945. -0.5, 0.5,
  135946. };
  135947. static long _vq_quantmap__44cn1_s_p1_0[] = {
  135948. 1, 0, 2,
  135949. };
  135950. static encode_aux_threshmatch _vq_auxt__44cn1_s_p1_0 = {
  135951. _vq_quantthresh__44cn1_s_p1_0,
  135952. _vq_quantmap__44cn1_s_p1_0,
  135953. 3,
  135954. 3
  135955. };
  135956. static static_codebook _44cn1_s_p1_0 = {
  135957. 8, 6561,
  135958. _vq_lengthlist__44cn1_s_p1_0,
  135959. 1, -535822336, 1611661312, 2, 0,
  135960. _vq_quantlist__44cn1_s_p1_0,
  135961. NULL,
  135962. &_vq_auxt__44cn1_s_p1_0,
  135963. NULL,
  135964. 0
  135965. };
  135966. static long _vq_quantlist__44cn1_s_p2_0[] = {
  135967. 2,
  135968. 1,
  135969. 3,
  135970. 0,
  135971. 4,
  135972. };
  135973. static long _vq_lengthlist__44cn1_s_p2_0[] = {
  135974. 1, 4, 4, 7, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  135976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135977. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  135979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135980. 0, 0, 0, 0, 6, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  135981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136013. 0,
  136014. };
  136015. static float _vq_quantthresh__44cn1_s_p2_0[] = {
  136016. -1.5, -0.5, 0.5, 1.5,
  136017. };
  136018. static long _vq_quantmap__44cn1_s_p2_0[] = {
  136019. 3, 1, 0, 2, 4,
  136020. };
  136021. static encode_aux_threshmatch _vq_auxt__44cn1_s_p2_0 = {
  136022. _vq_quantthresh__44cn1_s_p2_0,
  136023. _vq_quantmap__44cn1_s_p2_0,
  136024. 5,
  136025. 5
  136026. };
  136027. static static_codebook _44cn1_s_p2_0 = {
  136028. 4, 625,
  136029. _vq_lengthlist__44cn1_s_p2_0,
  136030. 1, -533725184, 1611661312, 3, 0,
  136031. _vq_quantlist__44cn1_s_p2_0,
  136032. NULL,
  136033. &_vq_auxt__44cn1_s_p2_0,
  136034. NULL,
  136035. 0
  136036. };
  136037. static long _vq_quantlist__44cn1_s_p3_0[] = {
  136038. 4,
  136039. 3,
  136040. 5,
  136041. 2,
  136042. 6,
  136043. 1,
  136044. 7,
  136045. 0,
  136046. 8,
  136047. };
  136048. static long _vq_lengthlist__44cn1_s_p3_0[] = {
  136049. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  136050. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  136051. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  136052. 9, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  136053. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136054. 0,
  136055. };
  136056. static float _vq_quantthresh__44cn1_s_p3_0[] = {
  136057. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  136058. };
  136059. static long _vq_quantmap__44cn1_s_p3_0[] = {
  136060. 7, 5, 3, 1, 0, 2, 4, 6,
  136061. 8,
  136062. };
  136063. static encode_aux_threshmatch _vq_auxt__44cn1_s_p3_0 = {
  136064. _vq_quantthresh__44cn1_s_p3_0,
  136065. _vq_quantmap__44cn1_s_p3_0,
  136066. 9,
  136067. 9
  136068. };
  136069. static static_codebook _44cn1_s_p3_0 = {
  136070. 2, 81,
  136071. _vq_lengthlist__44cn1_s_p3_0,
  136072. 1, -531628032, 1611661312, 4, 0,
  136073. _vq_quantlist__44cn1_s_p3_0,
  136074. NULL,
  136075. &_vq_auxt__44cn1_s_p3_0,
  136076. NULL,
  136077. 0
  136078. };
  136079. static long _vq_quantlist__44cn1_s_p4_0[] = {
  136080. 4,
  136081. 3,
  136082. 5,
  136083. 2,
  136084. 6,
  136085. 1,
  136086. 7,
  136087. 0,
  136088. 8,
  136089. };
  136090. static long _vq_lengthlist__44cn1_s_p4_0[] = {
  136091. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 6, 6, 7, 7,
  136092. 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  136093. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  136094. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  136095. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  136096. 11,
  136097. };
  136098. static float _vq_quantthresh__44cn1_s_p4_0[] = {
  136099. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  136100. };
  136101. static long _vq_quantmap__44cn1_s_p4_0[] = {
  136102. 7, 5, 3, 1, 0, 2, 4, 6,
  136103. 8,
  136104. };
  136105. static encode_aux_threshmatch _vq_auxt__44cn1_s_p4_0 = {
  136106. _vq_quantthresh__44cn1_s_p4_0,
  136107. _vq_quantmap__44cn1_s_p4_0,
  136108. 9,
  136109. 9
  136110. };
  136111. static static_codebook _44cn1_s_p4_0 = {
  136112. 2, 81,
  136113. _vq_lengthlist__44cn1_s_p4_0,
  136114. 1, -531628032, 1611661312, 4, 0,
  136115. _vq_quantlist__44cn1_s_p4_0,
  136116. NULL,
  136117. &_vq_auxt__44cn1_s_p4_0,
  136118. NULL,
  136119. 0
  136120. };
  136121. static long _vq_quantlist__44cn1_s_p5_0[] = {
  136122. 8,
  136123. 7,
  136124. 9,
  136125. 6,
  136126. 10,
  136127. 5,
  136128. 11,
  136129. 4,
  136130. 12,
  136131. 3,
  136132. 13,
  136133. 2,
  136134. 14,
  136135. 1,
  136136. 15,
  136137. 0,
  136138. 16,
  136139. };
  136140. static long _vq_lengthlist__44cn1_s_p5_0[] = {
  136141. 1, 4, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,10,
  136142. 10, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  136143. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  136144. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  136145. 11,11,11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  136146. 10,11,11,11,11, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,10,
  136147. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,
  136148. 10,10,11,11,11,12,12, 0, 0, 0, 9, 9,10, 9,10,10,
  136149. 10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  136150. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  136151. 10,10,10,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  136152. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  136153. 10,10,11,10,11,11,11,12,13,12,13,13, 0, 0, 0, 0,
  136154. 0, 0, 0,11,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  136155. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  136156. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0,
  136157. 0, 0, 0, 0, 0, 0,12,12,12,13,13,13,13,13,14,14,
  136158. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,12,13,13,14,
  136159. 14,
  136160. };
  136161. static float _vq_quantthresh__44cn1_s_p5_0[] = {
  136162. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  136163. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  136164. };
  136165. static long _vq_quantmap__44cn1_s_p5_0[] = {
  136166. 15, 13, 11, 9, 7, 5, 3, 1,
  136167. 0, 2, 4, 6, 8, 10, 12, 14,
  136168. 16,
  136169. };
  136170. static encode_aux_threshmatch _vq_auxt__44cn1_s_p5_0 = {
  136171. _vq_quantthresh__44cn1_s_p5_0,
  136172. _vq_quantmap__44cn1_s_p5_0,
  136173. 17,
  136174. 17
  136175. };
  136176. static static_codebook _44cn1_s_p5_0 = {
  136177. 2, 289,
  136178. _vq_lengthlist__44cn1_s_p5_0,
  136179. 1, -529530880, 1611661312, 5, 0,
  136180. _vq_quantlist__44cn1_s_p5_0,
  136181. NULL,
  136182. &_vq_auxt__44cn1_s_p5_0,
  136183. NULL,
  136184. 0
  136185. };
  136186. static long _vq_quantlist__44cn1_s_p6_0[] = {
  136187. 1,
  136188. 0,
  136189. 2,
  136190. };
  136191. static long _vq_lengthlist__44cn1_s_p6_0[] = {
  136192. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 6, 6,10, 9, 9,11,
  136193. 9, 9, 4, 6, 6,10, 9, 9,10, 9, 9, 7,10,10,11,11,
  136194. 11,12,11,11, 7, 9, 9,11,11,10,11,10,10, 7, 9, 9,
  136195. 11,10,11,11,10,10, 7,10,10,11,11,11,12,11,11, 7,
  136196. 9, 9,11,10,10,11,10,10, 7, 9, 9,11,10,10,11,10,
  136197. 10,
  136198. };
  136199. static float _vq_quantthresh__44cn1_s_p6_0[] = {
  136200. -5.5, 5.5,
  136201. };
  136202. static long _vq_quantmap__44cn1_s_p6_0[] = {
  136203. 1, 0, 2,
  136204. };
  136205. static encode_aux_threshmatch _vq_auxt__44cn1_s_p6_0 = {
  136206. _vq_quantthresh__44cn1_s_p6_0,
  136207. _vq_quantmap__44cn1_s_p6_0,
  136208. 3,
  136209. 3
  136210. };
  136211. static static_codebook _44cn1_s_p6_0 = {
  136212. 4, 81,
  136213. _vq_lengthlist__44cn1_s_p6_0,
  136214. 1, -529137664, 1618345984, 2, 0,
  136215. _vq_quantlist__44cn1_s_p6_0,
  136216. NULL,
  136217. &_vq_auxt__44cn1_s_p6_0,
  136218. NULL,
  136219. 0
  136220. };
  136221. static long _vq_quantlist__44cn1_s_p6_1[] = {
  136222. 5,
  136223. 4,
  136224. 6,
  136225. 3,
  136226. 7,
  136227. 2,
  136228. 8,
  136229. 1,
  136230. 9,
  136231. 0,
  136232. 10,
  136233. };
  136234. static long _vq_lengthlist__44cn1_s_p6_1[] = {
  136235. 1, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,10, 7, 6,
  136236. 8, 8, 8, 8, 8, 8,10,10,10, 7, 6, 7, 7, 8, 8, 8,
  136237. 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  136238. 7, 8, 8, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 9, 9,
  136239. 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,
  136240. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  136241. 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,10,
  136242. 10,10,10, 9, 9, 9, 9, 9, 9,
  136243. };
  136244. static float _vq_quantthresh__44cn1_s_p6_1[] = {
  136245. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  136246. 3.5, 4.5,
  136247. };
  136248. static long _vq_quantmap__44cn1_s_p6_1[] = {
  136249. 9, 7, 5, 3, 1, 0, 2, 4,
  136250. 6, 8, 10,
  136251. };
  136252. static encode_aux_threshmatch _vq_auxt__44cn1_s_p6_1 = {
  136253. _vq_quantthresh__44cn1_s_p6_1,
  136254. _vq_quantmap__44cn1_s_p6_1,
  136255. 11,
  136256. 11
  136257. };
  136258. static static_codebook _44cn1_s_p6_1 = {
  136259. 2, 121,
  136260. _vq_lengthlist__44cn1_s_p6_1,
  136261. 1, -531365888, 1611661312, 4, 0,
  136262. _vq_quantlist__44cn1_s_p6_1,
  136263. NULL,
  136264. &_vq_auxt__44cn1_s_p6_1,
  136265. NULL,
  136266. 0
  136267. };
  136268. static long _vq_quantlist__44cn1_s_p7_0[] = {
  136269. 6,
  136270. 5,
  136271. 7,
  136272. 4,
  136273. 8,
  136274. 3,
  136275. 9,
  136276. 2,
  136277. 10,
  136278. 1,
  136279. 11,
  136280. 0,
  136281. 12,
  136282. };
  136283. static long _vq_lengthlist__44cn1_s_p7_0[] = {
  136284. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  136285. 7, 7, 8, 8, 8, 8, 9, 9,11,11, 7, 5, 5, 7, 7, 8,
  136286. 8, 8, 8, 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  136287. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  136288. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,11,12, 0,13,
  136289. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  136290. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  136291. 11,12,12,13,12, 0, 0, 0,14,14,11,10,11,12,12,13,
  136292. 13,14, 0, 0, 0,15,15,11,11,12,11,12,12,14,13, 0,
  136293. 0, 0, 0, 0,12,12,12,12,13,13,14,14, 0, 0, 0, 0,
  136294. 0,13,13,12,12,13,13,13,14,
  136295. };
  136296. static float _vq_quantthresh__44cn1_s_p7_0[] = {
  136297. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  136298. 12.5, 17.5, 22.5, 27.5,
  136299. };
  136300. static long _vq_quantmap__44cn1_s_p7_0[] = {
  136301. 11, 9, 7, 5, 3, 1, 0, 2,
  136302. 4, 6, 8, 10, 12,
  136303. };
  136304. static encode_aux_threshmatch _vq_auxt__44cn1_s_p7_0 = {
  136305. _vq_quantthresh__44cn1_s_p7_0,
  136306. _vq_quantmap__44cn1_s_p7_0,
  136307. 13,
  136308. 13
  136309. };
  136310. static static_codebook _44cn1_s_p7_0 = {
  136311. 2, 169,
  136312. _vq_lengthlist__44cn1_s_p7_0,
  136313. 1, -526516224, 1616117760, 4, 0,
  136314. _vq_quantlist__44cn1_s_p7_0,
  136315. NULL,
  136316. &_vq_auxt__44cn1_s_p7_0,
  136317. NULL,
  136318. 0
  136319. };
  136320. static long _vq_quantlist__44cn1_s_p7_1[] = {
  136321. 2,
  136322. 1,
  136323. 3,
  136324. 0,
  136325. 4,
  136326. };
  136327. static long _vq_lengthlist__44cn1_s_p7_1[] = {
  136328. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  136329. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  136330. };
  136331. static float _vq_quantthresh__44cn1_s_p7_1[] = {
  136332. -1.5, -0.5, 0.5, 1.5,
  136333. };
  136334. static long _vq_quantmap__44cn1_s_p7_1[] = {
  136335. 3, 1, 0, 2, 4,
  136336. };
  136337. static encode_aux_threshmatch _vq_auxt__44cn1_s_p7_1 = {
  136338. _vq_quantthresh__44cn1_s_p7_1,
  136339. _vq_quantmap__44cn1_s_p7_1,
  136340. 5,
  136341. 5
  136342. };
  136343. static static_codebook _44cn1_s_p7_1 = {
  136344. 2, 25,
  136345. _vq_lengthlist__44cn1_s_p7_1,
  136346. 1, -533725184, 1611661312, 3, 0,
  136347. _vq_quantlist__44cn1_s_p7_1,
  136348. NULL,
  136349. &_vq_auxt__44cn1_s_p7_1,
  136350. NULL,
  136351. 0
  136352. };
  136353. static long _vq_quantlist__44cn1_s_p8_0[] = {
  136354. 2,
  136355. 1,
  136356. 3,
  136357. 0,
  136358. 4,
  136359. };
  136360. static long _vq_lengthlist__44cn1_s_p8_0[] = {
  136361. 1, 7, 7,11,11, 8,11,11,11,11, 4,11, 3,11,11,11,
  136362. 11,11,11,11,11,11,11,11,11,11,11,10,11,11,11,11,
  136363. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136364. 11,11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,
  136365. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136366. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136367. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136368. 11,11,11,11,11,11,11,11,11,11,11,11,11, 7,11,11,
  136369. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136370. 11,11,11,11,11,11,10,11,11,11,11,11,11,11,11,11,
  136371. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,
  136372. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136373. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136374. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136375. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136376. 11,11,11,11,11,11,11,11,11,11, 8,11,11,11,11,11,
  136377. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136378. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136379. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136380. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136381. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136382. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136383. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136384. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136385. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136386. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136387. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136388. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136389. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136390. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136391. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136392. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136393. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136394. 11,11,11,11,11,11,11,12,12,12,12,12,12,12,12,12,
  136395. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  136396. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  136397. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  136398. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  136399. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  136400. 12,
  136401. };
  136402. static float _vq_quantthresh__44cn1_s_p8_0[] = {
  136403. -331.5, -110.5, 110.5, 331.5,
  136404. };
  136405. static long _vq_quantmap__44cn1_s_p8_0[] = {
  136406. 3, 1, 0, 2, 4,
  136407. };
  136408. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_0 = {
  136409. _vq_quantthresh__44cn1_s_p8_0,
  136410. _vq_quantmap__44cn1_s_p8_0,
  136411. 5,
  136412. 5
  136413. };
  136414. static static_codebook _44cn1_s_p8_0 = {
  136415. 4, 625,
  136416. _vq_lengthlist__44cn1_s_p8_0,
  136417. 1, -518283264, 1627103232, 3, 0,
  136418. _vq_quantlist__44cn1_s_p8_0,
  136419. NULL,
  136420. &_vq_auxt__44cn1_s_p8_0,
  136421. NULL,
  136422. 0
  136423. };
  136424. static long _vq_quantlist__44cn1_s_p8_1[] = {
  136425. 6,
  136426. 5,
  136427. 7,
  136428. 4,
  136429. 8,
  136430. 3,
  136431. 9,
  136432. 2,
  136433. 10,
  136434. 1,
  136435. 11,
  136436. 0,
  136437. 12,
  136438. };
  136439. static long _vq_lengthlist__44cn1_s_p8_1[] = {
  136440. 1, 4, 4, 6, 6, 8, 8, 9,10,10,11,11,11, 6, 5, 5,
  136441. 7, 7, 8, 8, 9,10, 9,11,11,12, 5, 5, 5, 7, 7, 8,
  136442. 9,10,10,12,12,14,13,15, 7, 7, 8, 8, 9,10,11,11,
  136443. 10,12,10,11,15, 7, 8, 8, 8, 9, 9,11,11,13,12,12,
  136444. 13,15,10,10, 8, 8,10,10,12,12,11,14,10,10,15,11,
  136445. 11, 8, 8,10,10,12,13,13,14,15,13,15,15,15,10,10,
  136446. 10,10,12,12,13,12,13,10,15,15,15,10,10,11,10,13,
  136447. 11,13,13,15,13,15,15,15,13,13,10,11,11,11,12,10,
  136448. 14,11,15,15,14,14,13,10,10,12,11,13,13,14,14,15,
  136449. 15,15,15,15,11,11,11,11,12,11,15,12,15,15,15,15,
  136450. 15,12,12,11,11,14,12,13,14,
  136451. };
  136452. static float _vq_quantthresh__44cn1_s_p8_1[] = {
  136453. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  136454. 42.5, 59.5, 76.5, 93.5,
  136455. };
  136456. static long _vq_quantmap__44cn1_s_p8_1[] = {
  136457. 11, 9, 7, 5, 3, 1, 0, 2,
  136458. 4, 6, 8, 10, 12,
  136459. };
  136460. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_1 = {
  136461. _vq_quantthresh__44cn1_s_p8_1,
  136462. _vq_quantmap__44cn1_s_p8_1,
  136463. 13,
  136464. 13
  136465. };
  136466. static static_codebook _44cn1_s_p8_1 = {
  136467. 2, 169,
  136468. _vq_lengthlist__44cn1_s_p8_1,
  136469. 1, -522616832, 1620115456, 4, 0,
  136470. _vq_quantlist__44cn1_s_p8_1,
  136471. NULL,
  136472. &_vq_auxt__44cn1_s_p8_1,
  136473. NULL,
  136474. 0
  136475. };
  136476. static long _vq_quantlist__44cn1_s_p8_2[] = {
  136477. 8,
  136478. 7,
  136479. 9,
  136480. 6,
  136481. 10,
  136482. 5,
  136483. 11,
  136484. 4,
  136485. 12,
  136486. 3,
  136487. 13,
  136488. 2,
  136489. 14,
  136490. 1,
  136491. 15,
  136492. 0,
  136493. 16,
  136494. };
  136495. static long _vq_lengthlist__44cn1_s_p8_2[] = {
  136496. 3, 4, 3, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  136497. 9,10,11,11, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  136498. 9, 9,10,10,10, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  136499. 9, 9, 9,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9,
  136500. 9, 9,10, 9,10,11,10, 7, 6, 7, 7, 8, 8, 9, 9, 9,
  136501. 9, 9, 9, 9,10,10,10,11, 7, 7, 8, 8, 8, 8, 9, 9,
  136502. 9, 9, 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 8, 9,
  136503. 9, 9, 9, 9, 9, 9,10,11,11,11, 8, 8, 8, 8, 8, 8,
  136504. 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,11, 8, 8, 8,
  136505. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,11,11, 9, 9,
  136506. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,10,11,11, 9,
  136507. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,11,10,11,11,
  136508. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,
  136509. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,11,11,
  136510. 10,11,11,11, 9,10,10, 9, 9, 9, 9, 9, 9, 9,10,11,
  136511. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  136512. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  136513. 11,11,11,10,11,11,11,11,11, 9, 9, 9,10, 9, 9, 9,
  136514. 9,
  136515. };
  136516. static float _vq_quantthresh__44cn1_s_p8_2[] = {
  136517. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  136518. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  136519. };
  136520. static long _vq_quantmap__44cn1_s_p8_2[] = {
  136521. 15, 13, 11, 9, 7, 5, 3, 1,
  136522. 0, 2, 4, 6, 8, 10, 12, 14,
  136523. 16,
  136524. };
  136525. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_2 = {
  136526. _vq_quantthresh__44cn1_s_p8_2,
  136527. _vq_quantmap__44cn1_s_p8_2,
  136528. 17,
  136529. 17
  136530. };
  136531. static static_codebook _44cn1_s_p8_2 = {
  136532. 2, 289,
  136533. _vq_lengthlist__44cn1_s_p8_2,
  136534. 1, -529530880, 1611661312, 5, 0,
  136535. _vq_quantlist__44cn1_s_p8_2,
  136536. NULL,
  136537. &_vq_auxt__44cn1_s_p8_2,
  136538. NULL,
  136539. 0
  136540. };
  136541. static long _huff_lengthlist__44cn1_s_short[] = {
  136542. 10, 9,12,15,12,13,16,14,16, 7, 1, 5,14, 7,10,13,
  136543. 16,16, 9, 4, 6,16, 8,11,16,16,16,14, 4, 7,16, 9,
  136544. 12,14,16,16,10, 5, 7,14, 9,12,14,15,15,13, 8, 9,
  136545. 14,10,12,13,14,15,13, 9, 9, 7, 6, 8,11,12,12,14,
  136546. 8, 8, 5, 4, 5, 8,11,12,16,10,10, 6, 5, 6, 8, 9,
  136547. 10,
  136548. };
  136549. static static_codebook _huff_book__44cn1_s_short = {
  136550. 2, 81,
  136551. _huff_lengthlist__44cn1_s_short,
  136552. 0, 0, 0, 0, 0,
  136553. NULL,
  136554. NULL,
  136555. NULL,
  136556. NULL,
  136557. 0
  136558. };
  136559. static long _huff_lengthlist__44cn1_sm_long[] = {
  136560. 3, 3, 8, 8, 8, 8,10,12,14, 3, 2, 6, 7, 7, 8,10,
  136561. 12,16, 7, 6, 7, 9, 8,10,12,14,16, 8, 6, 8, 4, 5,
  136562. 7, 9,11,13, 7, 6, 8, 5, 6, 7, 9,11,14, 8, 8,10,
  136563. 7, 7, 6, 8,10,13, 9,11,12, 9, 9, 7, 8,10,12,10,
  136564. 13,15,11,11,10, 9,10,13,13,16,17,14,15,14,13,14,
  136565. 17,
  136566. };
  136567. static static_codebook _huff_book__44cn1_sm_long = {
  136568. 2, 81,
  136569. _huff_lengthlist__44cn1_sm_long,
  136570. 0, 0, 0, 0, 0,
  136571. NULL,
  136572. NULL,
  136573. NULL,
  136574. NULL,
  136575. 0
  136576. };
  136577. static long _vq_quantlist__44cn1_sm_p1_0[] = {
  136578. 1,
  136579. 0,
  136580. 2,
  136581. };
  136582. static long _vq_lengthlist__44cn1_sm_p1_0[] = {
  136583. 1, 4, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  136584. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136588. 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0,
  136589. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136593. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  136594. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  136629. 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  136630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10, 9, 0, 0, 0,
  136634. 0, 0, 0, 9, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  136635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  136639. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  136640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136674. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  136675. 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136679. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  136680. 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  136681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136684. 0, 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10,
  136685. 0, 0, 0, 0, 0, 0, 9,10, 9, 0, 0, 0, 0, 0, 0, 0,
  136686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136993. 0,
  136994. };
  136995. static float _vq_quantthresh__44cn1_sm_p1_0[] = {
  136996. -0.5, 0.5,
  136997. };
  136998. static long _vq_quantmap__44cn1_sm_p1_0[] = {
  136999. 1, 0, 2,
  137000. };
  137001. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p1_0 = {
  137002. _vq_quantthresh__44cn1_sm_p1_0,
  137003. _vq_quantmap__44cn1_sm_p1_0,
  137004. 3,
  137005. 3
  137006. };
  137007. static static_codebook _44cn1_sm_p1_0 = {
  137008. 8, 6561,
  137009. _vq_lengthlist__44cn1_sm_p1_0,
  137010. 1, -535822336, 1611661312, 2, 0,
  137011. _vq_quantlist__44cn1_sm_p1_0,
  137012. NULL,
  137013. &_vq_auxt__44cn1_sm_p1_0,
  137014. NULL,
  137015. 0
  137016. };
  137017. static long _vq_quantlist__44cn1_sm_p2_0[] = {
  137018. 2,
  137019. 1,
  137020. 3,
  137021. 0,
  137022. 4,
  137023. };
  137024. static long _vq_lengthlist__44cn1_sm_p2_0[] = {
  137025. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  137027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137028. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  137030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137031. 0, 0, 0, 0, 7, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  137032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137064. 0,
  137065. };
  137066. static float _vq_quantthresh__44cn1_sm_p2_0[] = {
  137067. -1.5, -0.5, 0.5, 1.5,
  137068. };
  137069. static long _vq_quantmap__44cn1_sm_p2_0[] = {
  137070. 3, 1, 0, 2, 4,
  137071. };
  137072. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p2_0 = {
  137073. _vq_quantthresh__44cn1_sm_p2_0,
  137074. _vq_quantmap__44cn1_sm_p2_0,
  137075. 5,
  137076. 5
  137077. };
  137078. static static_codebook _44cn1_sm_p2_0 = {
  137079. 4, 625,
  137080. _vq_lengthlist__44cn1_sm_p2_0,
  137081. 1, -533725184, 1611661312, 3, 0,
  137082. _vq_quantlist__44cn1_sm_p2_0,
  137083. NULL,
  137084. &_vq_auxt__44cn1_sm_p2_0,
  137085. NULL,
  137086. 0
  137087. };
  137088. static long _vq_quantlist__44cn1_sm_p3_0[] = {
  137089. 4,
  137090. 3,
  137091. 5,
  137092. 2,
  137093. 6,
  137094. 1,
  137095. 7,
  137096. 0,
  137097. 8,
  137098. };
  137099. static long _vq_lengthlist__44cn1_sm_p3_0[] = {
  137100. 1, 3, 4, 7, 7, 0, 0, 0, 0, 0, 4, 4, 7, 7, 0, 0,
  137101. 0, 0, 0, 4, 5, 7, 7, 0, 0, 0, 0, 0, 6, 7, 8, 8,
  137102. 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  137103. 9, 9, 0, 0, 0, 0, 0, 0, 0,10, 9, 0, 0, 0, 0, 0,
  137104. 0, 0,11,11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137105. 0,
  137106. };
  137107. static float _vq_quantthresh__44cn1_sm_p3_0[] = {
  137108. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  137109. };
  137110. static long _vq_quantmap__44cn1_sm_p3_0[] = {
  137111. 7, 5, 3, 1, 0, 2, 4, 6,
  137112. 8,
  137113. };
  137114. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p3_0 = {
  137115. _vq_quantthresh__44cn1_sm_p3_0,
  137116. _vq_quantmap__44cn1_sm_p3_0,
  137117. 9,
  137118. 9
  137119. };
  137120. static static_codebook _44cn1_sm_p3_0 = {
  137121. 2, 81,
  137122. _vq_lengthlist__44cn1_sm_p3_0,
  137123. 1, -531628032, 1611661312, 4, 0,
  137124. _vq_quantlist__44cn1_sm_p3_0,
  137125. NULL,
  137126. &_vq_auxt__44cn1_sm_p3_0,
  137127. NULL,
  137128. 0
  137129. };
  137130. static long _vq_quantlist__44cn1_sm_p4_0[] = {
  137131. 4,
  137132. 3,
  137133. 5,
  137134. 2,
  137135. 6,
  137136. 1,
  137137. 7,
  137138. 0,
  137139. 8,
  137140. };
  137141. static long _vq_lengthlist__44cn1_sm_p4_0[] = {
  137142. 1, 4, 3, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 8, 7,
  137143. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  137144. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  137145. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  137146. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  137147. 11,
  137148. };
  137149. static float _vq_quantthresh__44cn1_sm_p4_0[] = {
  137150. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  137151. };
  137152. static long _vq_quantmap__44cn1_sm_p4_0[] = {
  137153. 7, 5, 3, 1, 0, 2, 4, 6,
  137154. 8,
  137155. };
  137156. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p4_0 = {
  137157. _vq_quantthresh__44cn1_sm_p4_0,
  137158. _vq_quantmap__44cn1_sm_p4_0,
  137159. 9,
  137160. 9
  137161. };
  137162. static static_codebook _44cn1_sm_p4_0 = {
  137163. 2, 81,
  137164. _vq_lengthlist__44cn1_sm_p4_0,
  137165. 1, -531628032, 1611661312, 4, 0,
  137166. _vq_quantlist__44cn1_sm_p4_0,
  137167. NULL,
  137168. &_vq_auxt__44cn1_sm_p4_0,
  137169. NULL,
  137170. 0
  137171. };
  137172. static long _vq_quantlist__44cn1_sm_p5_0[] = {
  137173. 8,
  137174. 7,
  137175. 9,
  137176. 6,
  137177. 10,
  137178. 5,
  137179. 11,
  137180. 4,
  137181. 12,
  137182. 3,
  137183. 13,
  137184. 2,
  137185. 14,
  137186. 1,
  137187. 15,
  137188. 0,
  137189. 16,
  137190. };
  137191. static long _vq_lengthlist__44cn1_sm_p5_0[] = {
  137192. 1, 4, 4, 6, 6, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,
  137193. 11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  137194. 12,12, 0, 6, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  137195. 11,12,12, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  137196. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,11,
  137197. 11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  137198. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  137199. 10,11,11,12,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  137200. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  137201. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  137202. 10,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0, 0, 9,
  137203. 9,10,10,11,11,12,12,12,13,13,13, 0, 0, 0, 0, 0,
  137204. 10,10,11,11,11,11,12,12,13,13,14,14, 0, 0, 0, 0,
  137205. 0, 0, 0,11,11,11,11,12,12,13,13,14,14, 0, 0, 0,
  137206. 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0, 0,
  137207. 0, 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0,
  137208. 0, 0, 0, 0, 0, 0,12,12,12,13,13,13,14,14,14,14,
  137209. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,14,14,14,
  137210. 14,
  137211. };
  137212. static float _vq_quantthresh__44cn1_sm_p5_0[] = {
  137213. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  137214. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  137215. };
  137216. static long _vq_quantmap__44cn1_sm_p5_0[] = {
  137217. 15, 13, 11, 9, 7, 5, 3, 1,
  137218. 0, 2, 4, 6, 8, 10, 12, 14,
  137219. 16,
  137220. };
  137221. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p5_0 = {
  137222. _vq_quantthresh__44cn1_sm_p5_0,
  137223. _vq_quantmap__44cn1_sm_p5_0,
  137224. 17,
  137225. 17
  137226. };
  137227. static static_codebook _44cn1_sm_p5_0 = {
  137228. 2, 289,
  137229. _vq_lengthlist__44cn1_sm_p5_0,
  137230. 1, -529530880, 1611661312, 5, 0,
  137231. _vq_quantlist__44cn1_sm_p5_0,
  137232. NULL,
  137233. &_vq_auxt__44cn1_sm_p5_0,
  137234. NULL,
  137235. 0
  137236. };
  137237. static long _vq_quantlist__44cn1_sm_p6_0[] = {
  137238. 1,
  137239. 0,
  137240. 2,
  137241. };
  137242. static long _vq_lengthlist__44cn1_sm_p6_0[] = {
  137243. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 6,10, 9, 9,11,
  137244. 9, 9, 4, 6, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  137245. 11,11,11,10, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  137246. 11,10,11,11,10,10, 7,11,11,11,11,11,12,11,11, 7,
  137247. 9, 9,11,10,10,12,10,10, 7, 9, 9,11,10,10,11,10,
  137248. 10,
  137249. };
  137250. static float _vq_quantthresh__44cn1_sm_p6_0[] = {
  137251. -5.5, 5.5,
  137252. };
  137253. static long _vq_quantmap__44cn1_sm_p6_0[] = {
  137254. 1, 0, 2,
  137255. };
  137256. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p6_0 = {
  137257. _vq_quantthresh__44cn1_sm_p6_0,
  137258. _vq_quantmap__44cn1_sm_p6_0,
  137259. 3,
  137260. 3
  137261. };
  137262. static static_codebook _44cn1_sm_p6_0 = {
  137263. 4, 81,
  137264. _vq_lengthlist__44cn1_sm_p6_0,
  137265. 1, -529137664, 1618345984, 2, 0,
  137266. _vq_quantlist__44cn1_sm_p6_0,
  137267. NULL,
  137268. &_vq_auxt__44cn1_sm_p6_0,
  137269. NULL,
  137270. 0
  137271. };
  137272. static long _vq_quantlist__44cn1_sm_p6_1[] = {
  137273. 5,
  137274. 4,
  137275. 6,
  137276. 3,
  137277. 7,
  137278. 2,
  137279. 8,
  137280. 1,
  137281. 9,
  137282. 0,
  137283. 10,
  137284. };
  137285. static long _vq_lengthlist__44cn1_sm_p6_1[] = {
  137286. 2, 4, 4, 5, 5, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  137287. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  137288. 8,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  137289. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  137290. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  137291. 8, 8, 8, 8, 8, 8, 9, 9,10,10,10,10,10, 8, 8, 8,
  137292. 8, 9, 9,10,10,10,10,10, 9, 9, 9, 9, 8, 9,10,10,
  137293. 10,10,10, 8, 9, 8, 8, 9, 8,
  137294. };
  137295. static float _vq_quantthresh__44cn1_sm_p6_1[] = {
  137296. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  137297. 3.5, 4.5,
  137298. };
  137299. static long _vq_quantmap__44cn1_sm_p6_1[] = {
  137300. 9, 7, 5, 3, 1, 0, 2, 4,
  137301. 6, 8, 10,
  137302. };
  137303. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p6_1 = {
  137304. _vq_quantthresh__44cn1_sm_p6_1,
  137305. _vq_quantmap__44cn1_sm_p6_1,
  137306. 11,
  137307. 11
  137308. };
  137309. static static_codebook _44cn1_sm_p6_1 = {
  137310. 2, 121,
  137311. _vq_lengthlist__44cn1_sm_p6_1,
  137312. 1, -531365888, 1611661312, 4, 0,
  137313. _vq_quantlist__44cn1_sm_p6_1,
  137314. NULL,
  137315. &_vq_auxt__44cn1_sm_p6_1,
  137316. NULL,
  137317. 0
  137318. };
  137319. static long _vq_quantlist__44cn1_sm_p7_0[] = {
  137320. 6,
  137321. 5,
  137322. 7,
  137323. 4,
  137324. 8,
  137325. 3,
  137326. 9,
  137327. 2,
  137328. 10,
  137329. 1,
  137330. 11,
  137331. 0,
  137332. 12,
  137333. };
  137334. static long _vq_lengthlist__44cn1_sm_p7_0[] = {
  137335. 1, 4, 4, 6, 6, 7, 7, 7, 7, 9, 9,10,10, 7, 5, 5,
  137336. 7, 7, 8, 8, 8, 8,10, 9,11,10, 7, 5, 5, 7, 7, 8,
  137337. 8, 8, 8, 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  137338. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  137339. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,12,12, 0,13,
  137340. 13, 9, 9, 9, 9,10,10,11,11,12,12, 0, 0, 0,10,10,
  137341. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  137342. 11,12,12,12,12, 0, 0, 0,14,14,11,11,11,11,12,13,
  137343. 13,13, 0, 0, 0,14,14,11,10,11,11,12,12,13,13, 0,
  137344. 0, 0, 0, 0,12,12,12,12,13,13,13,14, 0, 0, 0, 0,
  137345. 0,13,12,12,12,13,13,13,14,
  137346. };
  137347. static float _vq_quantthresh__44cn1_sm_p7_0[] = {
  137348. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  137349. 12.5, 17.5, 22.5, 27.5,
  137350. };
  137351. static long _vq_quantmap__44cn1_sm_p7_0[] = {
  137352. 11, 9, 7, 5, 3, 1, 0, 2,
  137353. 4, 6, 8, 10, 12,
  137354. };
  137355. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p7_0 = {
  137356. _vq_quantthresh__44cn1_sm_p7_0,
  137357. _vq_quantmap__44cn1_sm_p7_0,
  137358. 13,
  137359. 13
  137360. };
  137361. static static_codebook _44cn1_sm_p7_0 = {
  137362. 2, 169,
  137363. _vq_lengthlist__44cn1_sm_p7_0,
  137364. 1, -526516224, 1616117760, 4, 0,
  137365. _vq_quantlist__44cn1_sm_p7_0,
  137366. NULL,
  137367. &_vq_auxt__44cn1_sm_p7_0,
  137368. NULL,
  137369. 0
  137370. };
  137371. static long _vq_quantlist__44cn1_sm_p7_1[] = {
  137372. 2,
  137373. 1,
  137374. 3,
  137375. 0,
  137376. 4,
  137377. };
  137378. static long _vq_lengthlist__44cn1_sm_p7_1[] = {
  137379. 2, 4, 4, 4, 5, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  137380. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  137381. };
  137382. static float _vq_quantthresh__44cn1_sm_p7_1[] = {
  137383. -1.5, -0.5, 0.5, 1.5,
  137384. };
  137385. static long _vq_quantmap__44cn1_sm_p7_1[] = {
  137386. 3, 1, 0, 2, 4,
  137387. };
  137388. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p7_1 = {
  137389. _vq_quantthresh__44cn1_sm_p7_1,
  137390. _vq_quantmap__44cn1_sm_p7_1,
  137391. 5,
  137392. 5
  137393. };
  137394. static static_codebook _44cn1_sm_p7_1 = {
  137395. 2, 25,
  137396. _vq_lengthlist__44cn1_sm_p7_1,
  137397. 1, -533725184, 1611661312, 3, 0,
  137398. _vq_quantlist__44cn1_sm_p7_1,
  137399. NULL,
  137400. &_vq_auxt__44cn1_sm_p7_1,
  137401. NULL,
  137402. 0
  137403. };
  137404. static long _vq_quantlist__44cn1_sm_p8_0[] = {
  137405. 4,
  137406. 3,
  137407. 5,
  137408. 2,
  137409. 6,
  137410. 1,
  137411. 7,
  137412. 0,
  137413. 8,
  137414. };
  137415. static long _vq_lengthlist__44cn1_sm_p8_0[] = {
  137416. 1, 4, 4,12,11,13,13,14,14, 4, 7, 7,11,13,14,14,
  137417. 14,14, 3, 8, 3,14,14,14,14,14,14,14,10,12,14,14,
  137418. 14,14,14,14,14,14, 5,14, 8,14,14,14,14,14,12,14,
  137419. 13,14,14,14,14,14,14,14,13,14,10,14,14,14,14,14,
  137420. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  137421. 14,
  137422. };
  137423. static float _vq_quantthresh__44cn1_sm_p8_0[] = {
  137424. -773.5, -552.5, -331.5, -110.5, 110.5, 331.5, 552.5, 773.5,
  137425. };
  137426. static long _vq_quantmap__44cn1_sm_p8_0[] = {
  137427. 7, 5, 3, 1, 0, 2, 4, 6,
  137428. 8,
  137429. };
  137430. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_0 = {
  137431. _vq_quantthresh__44cn1_sm_p8_0,
  137432. _vq_quantmap__44cn1_sm_p8_0,
  137433. 9,
  137434. 9
  137435. };
  137436. static static_codebook _44cn1_sm_p8_0 = {
  137437. 2, 81,
  137438. _vq_lengthlist__44cn1_sm_p8_0,
  137439. 1, -516186112, 1627103232, 4, 0,
  137440. _vq_quantlist__44cn1_sm_p8_0,
  137441. NULL,
  137442. &_vq_auxt__44cn1_sm_p8_0,
  137443. NULL,
  137444. 0
  137445. };
  137446. static long _vq_quantlist__44cn1_sm_p8_1[] = {
  137447. 6,
  137448. 5,
  137449. 7,
  137450. 4,
  137451. 8,
  137452. 3,
  137453. 9,
  137454. 2,
  137455. 10,
  137456. 1,
  137457. 11,
  137458. 0,
  137459. 12,
  137460. };
  137461. static long _vq_lengthlist__44cn1_sm_p8_1[] = {
  137462. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,11,11,11, 6, 5, 5,
  137463. 7, 7, 8, 8,10,10,10,11,11,11, 6, 5, 5, 7, 7, 8,
  137464. 8,10,10,11,12,12,12,14, 7, 7, 7, 8, 9, 9,11,11,
  137465. 11,12,11,12,17, 7, 7, 8, 7, 9, 9,11,11,12,12,12,
  137466. 12,14,11,11, 8, 8,10,10,11,12,12,13,11,12,14,11,
  137467. 11, 8, 8,10,10,11,12,12,13,13,12,14,15,14,10,10,
  137468. 10,10,11,12,12,12,12,11,14,13,16,10,10,10, 9,12,
  137469. 11,12,12,13,14,14,15,14,14,13,10,10,11,11,12,11,
  137470. 13,11,14,12,15,13,14,11,10,12,10,12,12,13,13,13,
  137471. 13,14,15,15,12,12,11,11,12,11,13,12,14,14,14,14,
  137472. 17,12,12,11,10,13,11,13,13,
  137473. };
  137474. static float _vq_quantthresh__44cn1_sm_p8_1[] = {
  137475. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  137476. 42.5, 59.5, 76.5, 93.5,
  137477. };
  137478. static long _vq_quantmap__44cn1_sm_p8_1[] = {
  137479. 11, 9, 7, 5, 3, 1, 0, 2,
  137480. 4, 6, 8, 10, 12,
  137481. };
  137482. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_1 = {
  137483. _vq_quantthresh__44cn1_sm_p8_1,
  137484. _vq_quantmap__44cn1_sm_p8_1,
  137485. 13,
  137486. 13
  137487. };
  137488. static static_codebook _44cn1_sm_p8_1 = {
  137489. 2, 169,
  137490. _vq_lengthlist__44cn1_sm_p8_1,
  137491. 1, -522616832, 1620115456, 4, 0,
  137492. _vq_quantlist__44cn1_sm_p8_1,
  137493. NULL,
  137494. &_vq_auxt__44cn1_sm_p8_1,
  137495. NULL,
  137496. 0
  137497. };
  137498. static long _vq_quantlist__44cn1_sm_p8_2[] = {
  137499. 8,
  137500. 7,
  137501. 9,
  137502. 6,
  137503. 10,
  137504. 5,
  137505. 11,
  137506. 4,
  137507. 12,
  137508. 3,
  137509. 13,
  137510. 2,
  137511. 14,
  137512. 1,
  137513. 15,
  137514. 0,
  137515. 16,
  137516. };
  137517. static long _vq_lengthlist__44cn1_sm_p8_2[] = {
  137518. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  137519. 9,10, 6, 6, 6, 6, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  137520. 9, 9,10, 6, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  137521. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  137522. 9, 9, 9, 9,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9,
  137523. 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 8, 8, 9, 9,
  137524. 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 8, 8, 9,
  137525. 9, 9, 9, 9, 9, 9, 9,11,10,11, 8, 8, 8, 8, 8, 8,
  137526. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,11,11, 8, 8, 8,
  137527. 8, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,11, 9, 9,
  137528. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,10,11,11, 9,
  137529. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,10,11,11,
  137530. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,
  137531. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,
  137532. 11,11,11,11, 9,10,10,10, 9, 9, 9, 9, 9, 9,11,10,
  137533. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  137534. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  137535. 10,11,11,11,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,
  137536. 9,
  137537. };
  137538. static float _vq_quantthresh__44cn1_sm_p8_2[] = {
  137539. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  137540. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  137541. };
  137542. static long _vq_quantmap__44cn1_sm_p8_2[] = {
  137543. 15, 13, 11, 9, 7, 5, 3, 1,
  137544. 0, 2, 4, 6, 8, 10, 12, 14,
  137545. 16,
  137546. };
  137547. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_2 = {
  137548. _vq_quantthresh__44cn1_sm_p8_2,
  137549. _vq_quantmap__44cn1_sm_p8_2,
  137550. 17,
  137551. 17
  137552. };
  137553. static static_codebook _44cn1_sm_p8_2 = {
  137554. 2, 289,
  137555. _vq_lengthlist__44cn1_sm_p8_2,
  137556. 1, -529530880, 1611661312, 5, 0,
  137557. _vq_quantlist__44cn1_sm_p8_2,
  137558. NULL,
  137559. &_vq_auxt__44cn1_sm_p8_2,
  137560. NULL,
  137561. 0
  137562. };
  137563. static long _huff_lengthlist__44cn1_sm_short[] = {
  137564. 5, 6,12,14,12,14,16,17,18, 4, 2, 5,11, 7,10,12,
  137565. 14,15, 9, 4, 5,11, 7,10,13,15,18,15, 6, 7, 5, 6,
  137566. 8,11,13,16,11, 5, 6, 5, 5, 6, 9,13,15,12, 5, 7,
  137567. 6, 5, 6, 9,12,14,12, 6, 7, 8, 6, 7, 9,12,13,14,
  137568. 8, 8, 7, 5, 5, 8,10,12,16, 9, 9, 8, 6, 6, 7, 9,
  137569. 9,
  137570. };
  137571. static static_codebook _huff_book__44cn1_sm_short = {
  137572. 2, 81,
  137573. _huff_lengthlist__44cn1_sm_short,
  137574. 0, 0, 0, 0, 0,
  137575. NULL,
  137576. NULL,
  137577. NULL,
  137578. NULL,
  137579. 0
  137580. };
  137581. /********* End of inlined file: res_books_stereo.h *********/
  137582. /***** residue backends *********************************************/
  137583. static vorbis_info_residue0 _residue_44_low={
  137584. 0,-1, -1, 9,-1,
  137585. /* 0 1 2 3 4 5 6 7 */
  137586. {0},
  137587. {-1},
  137588. { .5, 1.5, 2.5, 2.5, 4.5, 8.5, 16.5, 32.5},
  137589. { .5, .5, .5, 999., 4.5, 8.5, 16.5, 32.5},
  137590. };
  137591. static vorbis_info_residue0 _residue_44_mid={
  137592. 0,-1, -1, 10,-1,
  137593. /* 0 1 2 3 4 5 6 7 8 */
  137594. {0},
  137595. {-1},
  137596. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 8.5, 16.5, 32.5},
  137597. { .5, .5, 999., .5, 999., 4.5, 8.5, 16.5, 32.5},
  137598. };
  137599. static vorbis_info_residue0 _residue_44_high={
  137600. 0,-1, -1, 10,-1,
  137601. /* 0 1 2 3 4 5 6 7 8 */
  137602. {0},
  137603. {-1},
  137604. { .5, 1.5, 2.5, 4.5, 8.5, 16.5, 32.5, 71.5,157.5},
  137605. { .5, 1.5, 2.5, 3.5, 4.5, 8.5, 16.5, 71.5,157.5},
  137606. };
  137607. static static_bookblock _resbook_44s_n1={
  137608. {
  137609. {0},{0,0,&_44cn1_s_p1_0},{0,0,&_44cn1_s_p2_0},
  137610. {0,0,&_44cn1_s_p3_0},{0,0,&_44cn1_s_p4_0},{0,0,&_44cn1_s_p5_0},
  137611. {&_44cn1_s_p6_0,&_44cn1_s_p6_1},{&_44cn1_s_p7_0,&_44cn1_s_p7_1},
  137612. {&_44cn1_s_p8_0,&_44cn1_s_p8_1,&_44cn1_s_p8_2}
  137613. }
  137614. };
  137615. static static_bookblock _resbook_44sm_n1={
  137616. {
  137617. {0},{0,0,&_44cn1_sm_p1_0},{0,0,&_44cn1_sm_p2_0},
  137618. {0,0,&_44cn1_sm_p3_0},{0,0,&_44cn1_sm_p4_0},{0,0,&_44cn1_sm_p5_0},
  137619. {&_44cn1_sm_p6_0,&_44cn1_sm_p6_1},{&_44cn1_sm_p7_0,&_44cn1_sm_p7_1},
  137620. {&_44cn1_sm_p8_0,&_44cn1_sm_p8_1,&_44cn1_sm_p8_2}
  137621. }
  137622. };
  137623. static static_bookblock _resbook_44s_0={
  137624. {
  137625. {0},{0,0,&_44c0_s_p1_0},{0,0,&_44c0_s_p2_0},
  137626. {0,0,&_44c0_s_p3_0},{0,0,&_44c0_s_p4_0},{0,0,&_44c0_s_p5_0},
  137627. {&_44c0_s_p6_0,&_44c0_s_p6_1},{&_44c0_s_p7_0,&_44c0_s_p7_1},
  137628. {&_44c0_s_p8_0,&_44c0_s_p8_1,&_44c0_s_p8_2}
  137629. }
  137630. };
  137631. static static_bookblock _resbook_44sm_0={
  137632. {
  137633. {0},{0,0,&_44c0_sm_p1_0},{0,0,&_44c0_sm_p2_0},
  137634. {0,0,&_44c0_sm_p3_0},{0,0,&_44c0_sm_p4_0},{0,0,&_44c0_sm_p5_0},
  137635. {&_44c0_sm_p6_0,&_44c0_sm_p6_1},{&_44c0_sm_p7_0,&_44c0_sm_p7_1},
  137636. {&_44c0_sm_p8_0,&_44c0_sm_p8_1,&_44c0_sm_p8_2}
  137637. }
  137638. };
  137639. static static_bookblock _resbook_44s_1={
  137640. {
  137641. {0},{0,0,&_44c1_s_p1_0},{0,0,&_44c1_s_p2_0},
  137642. {0,0,&_44c1_s_p3_0},{0,0,&_44c1_s_p4_0},{0,0,&_44c1_s_p5_0},
  137643. {&_44c1_s_p6_0,&_44c1_s_p6_1},{&_44c1_s_p7_0,&_44c1_s_p7_1},
  137644. {&_44c1_s_p8_0,&_44c1_s_p8_1,&_44c1_s_p8_2}
  137645. }
  137646. };
  137647. static static_bookblock _resbook_44sm_1={
  137648. {
  137649. {0},{0,0,&_44c1_sm_p1_0},{0,0,&_44c1_sm_p2_0},
  137650. {0,0,&_44c1_sm_p3_0},{0,0,&_44c1_sm_p4_0},{0,0,&_44c1_sm_p5_0},
  137651. {&_44c1_sm_p6_0,&_44c1_sm_p6_1},{&_44c1_sm_p7_0,&_44c1_sm_p7_1},
  137652. {&_44c1_sm_p8_0,&_44c1_sm_p8_1,&_44c1_sm_p8_2}
  137653. }
  137654. };
  137655. static static_bookblock _resbook_44s_2={
  137656. {
  137657. {0},{0,0,&_44c2_s_p1_0},{0,0,&_44c2_s_p2_0},{0,0,&_44c2_s_p3_0},
  137658. {0,0,&_44c2_s_p4_0},{0,0,&_44c2_s_p5_0},{0,0,&_44c2_s_p6_0},
  137659. {&_44c2_s_p7_0,&_44c2_s_p7_1},{&_44c2_s_p8_0,&_44c2_s_p8_1},
  137660. {&_44c2_s_p9_0,&_44c2_s_p9_1,&_44c2_s_p9_2}
  137661. }
  137662. };
  137663. static static_bookblock _resbook_44s_3={
  137664. {
  137665. {0},{0,0,&_44c3_s_p1_0},{0,0,&_44c3_s_p2_0},{0,0,&_44c3_s_p3_0},
  137666. {0,0,&_44c3_s_p4_0},{0,0,&_44c3_s_p5_0},{0,0,&_44c3_s_p6_0},
  137667. {&_44c3_s_p7_0,&_44c3_s_p7_1},{&_44c3_s_p8_0,&_44c3_s_p8_1},
  137668. {&_44c3_s_p9_0,&_44c3_s_p9_1,&_44c3_s_p9_2}
  137669. }
  137670. };
  137671. static static_bookblock _resbook_44s_4={
  137672. {
  137673. {0},{0,0,&_44c4_s_p1_0},{0,0,&_44c4_s_p2_0},{0,0,&_44c4_s_p3_0},
  137674. {0,0,&_44c4_s_p4_0},{0,0,&_44c4_s_p5_0},{0,0,&_44c4_s_p6_0},
  137675. {&_44c4_s_p7_0,&_44c4_s_p7_1},{&_44c4_s_p8_0,&_44c4_s_p8_1},
  137676. {&_44c4_s_p9_0,&_44c4_s_p9_1,&_44c4_s_p9_2}
  137677. }
  137678. };
  137679. static static_bookblock _resbook_44s_5={
  137680. {
  137681. {0},{0,0,&_44c5_s_p1_0},{0,0,&_44c5_s_p2_0},{0,0,&_44c5_s_p3_0},
  137682. {0,0,&_44c5_s_p4_0},{0,0,&_44c5_s_p5_0},{0,0,&_44c5_s_p6_0},
  137683. {&_44c5_s_p7_0,&_44c5_s_p7_1},{&_44c5_s_p8_0,&_44c5_s_p8_1},
  137684. {&_44c5_s_p9_0,&_44c5_s_p9_1,&_44c5_s_p9_2}
  137685. }
  137686. };
  137687. static static_bookblock _resbook_44s_6={
  137688. {
  137689. {0},{0,0,&_44c6_s_p1_0},{0,0,&_44c6_s_p2_0},{0,0,&_44c6_s_p3_0},
  137690. {0,0,&_44c6_s_p4_0},
  137691. {&_44c6_s_p5_0,&_44c6_s_p5_1},
  137692. {&_44c6_s_p6_0,&_44c6_s_p6_1},
  137693. {&_44c6_s_p7_0,&_44c6_s_p7_1},
  137694. {&_44c6_s_p8_0,&_44c6_s_p8_1},
  137695. {&_44c6_s_p9_0,&_44c6_s_p9_1,&_44c6_s_p9_2}
  137696. }
  137697. };
  137698. static static_bookblock _resbook_44s_7={
  137699. {
  137700. {0},{0,0,&_44c7_s_p1_0},{0,0,&_44c7_s_p2_0},{0,0,&_44c7_s_p3_0},
  137701. {0,0,&_44c7_s_p4_0},
  137702. {&_44c7_s_p5_0,&_44c7_s_p5_1},
  137703. {&_44c7_s_p6_0,&_44c7_s_p6_1},
  137704. {&_44c7_s_p7_0,&_44c7_s_p7_1},
  137705. {&_44c7_s_p8_0,&_44c7_s_p8_1},
  137706. {&_44c7_s_p9_0,&_44c7_s_p9_1,&_44c7_s_p9_2}
  137707. }
  137708. };
  137709. static static_bookblock _resbook_44s_8={
  137710. {
  137711. {0},{0,0,&_44c8_s_p1_0},{0,0,&_44c8_s_p2_0},{0,0,&_44c8_s_p3_0},
  137712. {0,0,&_44c8_s_p4_0},
  137713. {&_44c8_s_p5_0,&_44c8_s_p5_1},
  137714. {&_44c8_s_p6_0,&_44c8_s_p6_1},
  137715. {&_44c8_s_p7_0,&_44c8_s_p7_1},
  137716. {&_44c8_s_p8_0,&_44c8_s_p8_1},
  137717. {&_44c8_s_p9_0,&_44c8_s_p9_1,&_44c8_s_p9_2}
  137718. }
  137719. };
  137720. static static_bookblock _resbook_44s_9={
  137721. {
  137722. {0},{0,0,&_44c9_s_p1_0},{0,0,&_44c9_s_p2_0},{0,0,&_44c9_s_p3_0},
  137723. {0,0,&_44c9_s_p4_0},
  137724. {&_44c9_s_p5_0,&_44c9_s_p5_1},
  137725. {&_44c9_s_p6_0,&_44c9_s_p6_1},
  137726. {&_44c9_s_p7_0,&_44c9_s_p7_1},
  137727. {&_44c9_s_p8_0,&_44c9_s_p8_1},
  137728. {&_44c9_s_p9_0,&_44c9_s_p9_1,&_44c9_s_p9_2}
  137729. }
  137730. };
  137731. static vorbis_residue_template _res_44s_n1[]={
  137732. {2,0, &_residue_44_low,
  137733. &_huff_book__44cn1_s_short,&_huff_book__44cn1_sm_short,
  137734. &_resbook_44s_n1,&_resbook_44sm_n1},
  137735. {2,0, &_residue_44_low,
  137736. &_huff_book__44cn1_s_long,&_huff_book__44cn1_sm_long,
  137737. &_resbook_44s_n1,&_resbook_44sm_n1}
  137738. };
  137739. static vorbis_residue_template _res_44s_0[]={
  137740. {2,0, &_residue_44_low,
  137741. &_huff_book__44c0_s_short,&_huff_book__44c0_sm_short,
  137742. &_resbook_44s_0,&_resbook_44sm_0},
  137743. {2,0, &_residue_44_low,
  137744. &_huff_book__44c0_s_long,&_huff_book__44c0_sm_long,
  137745. &_resbook_44s_0,&_resbook_44sm_0}
  137746. };
  137747. static vorbis_residue_template _res_44s_1[]={
  137748. {2,0, &_residue_44_low,
  137749. &_huff_book__44c1_s_short,&_huff_book__44c1_sm_short,
  137750. &_resbook_44s_1,&_resbook_44sm_1},
  137751. {2,0, &_residue_44_low,
  137752. &_huff_book__44c1_s_long,&_huff_book__44c1_sm_long,
  137753. &_resbook_44s_1,&_resbook_44sm_1}
  137754. };
  137755. static vorbis_residue_template _res_44s_2[]={
  137756. {2,0, &_residue_44_mid,
  137757. &_huff_book__44c2_s_short,&_huff_book__44c2_s_short,
  137758. &_resbook_44s_2,&_resbook_44s_2},
  137759. {2,0, &_residue_44_mid,
  137760. &_huff_book__44c2_s_long,&_huff_book__44c2_s_long,
  137761. &_resbook_44s_2,&_resbook_44s_2}
  137762. };
  137763. static vorbis_residue_template _res_44s_3[]={
  137764. {2,0, &_residue_44_mid,
  137765. &_huff_book__44c3_s_short,&_huff_book__44c3_s_short,
  137766. &_resbook_44s_3,&_resbook_44s_3},
  137767. {2,0, &_residue_44_mid,
  137768. &_huff_book__44c3_s_long,&_huff_book__44c3_s_long,
  137769. &_resbook_44s_3,&_resbook_44s_3}
  137770. };
  137771. static vorbis_residue_template _res_44s_4[]={
  137772. {2,0, &_residue_44_mid,
  137773. &_huff_book__44c4_s_short,&_huff_book__44c4_s_short,
  137774. &_resbook_44s_4,&_resbook_44s_4},
  137775. {2,0, &_residue_44_mid,
  137776. &_huff_book__44c4_s_long,&_huff_book__44c4_s_long,
  137777. &_resbook_44s_4,&_resbook_44s_4}
  137778. };
  137779. static vorbis_residue_template _res_44s_5[]={
  137780. {2,0, &_residue_44_mid,
  137781. &_huff_book__44c5_s_short,&_huff_book__44c5_s_short,
  137782. &_resbook_44s_5,&_resbook_44s_5},
  137783. {2,0, &_residue_44_mid,
  137784. &_huff_book__44c5_s_long,&_huff_book__44c5_s_long,
  137785. &_resbook_44s_5,&_resbook_44s_5}
  137786. };
  137787. static vorbis_residue_template _res_44s_6[]={
  137788. {2,0, &_residue_44_high,
  137789. &_huff_book__44c6_s_short,&_huff_book__44c6_s_short,
  137790. &_resbook_44s_6,&_resbook_44s_6},
  137791. {2,0, &_residue_44_high,
  137792. &_huff_book__44c6_s_long,&_huff_book__44c6_s_long,
  137793. &_resbook_44s_6,&_resbook_44s_6}
  137794. };
  137795. static vorbis_residue_template _res_44s_7[]={
  137796. {2,0, &_residue_44_high,
  137797. &_huff_book__44c7_s_short,&_huff_book__44c7_s_short,
  137798. &_resbook_44s_7,&_resbook_44s_7},
  137799. {2,0, &_residue_44_high,
  137800. &_huff_book__44c7_s_long,&_huff_book__44c7_s_long,
  137801. &_resbook_44s_7,&_resbook_44s_7}
  137802. };
  137803. static vorbis_residue_template _res_44s_8[]={
  137804. {2,0, &_residue_44_high,
  137805. &_huff_book__44c8_s_short,&_huff_book__44c8_s_short,
  137806. &_resbook_44s_8,&_resbook_44s_8},
  137807. {2,0, &_residue_44_high,
  137808. &_huff_book__44c8_s_long,&_huff_book__44c8_s_long,
  137809. &_resbook_44s_8,&_resbook_44s_8}
  137810. };
  137811. static vorbis_residue_template _res_44s_9[]={
  137812. {2,0, &_residue_44_high,
  137813. &_huff_book__44c9_s_short,&_huff_book__44c9_s_short,
  137814. &_resbook_44s_9,&_resbook_44s_9},
  137815. {2,0, &_residue_44_high,
  137816. &_huff_book__44c9_s_long,&_huff_book__44c9_s_long,
  137817. &_resbook_44s_9,&_resbook_44s_9}
  137818. };
  137819. static vorbis_mapping_template _mapres_template_44_stereo[]={
  137820. { _map_nominal, _res_44s_n1 }, /* -1 */
  137821. { _map_nominal, _res_44s_0 }, /* 0 */
  137822. { _map_nominal, _res_44s_1 }, /* 1 */
  137823. { _map_nominal, _res_44s_2 }, /* 2 */
  137824. { _map_nominal, _res_44s_3 }, /* 3 */
  137825. { _map_nominal, _res_44s_4 }, /* 4 */
  137826. { _map_nominal, _res_44s_5 }, /* 5 */
  137827. { _map_nominal, _res_44s_6 }, /* 6 */
  137828. { _map_nominal, _res_44s_7 }, /* 7 */
  137829. { _map_nominal, _res_44s_8 }, /* 8 */
  137830. { _map_nominal, _res_44s_9 }, /* 9 */
  137831. };
  137832. /********* End of inlined file: residue_44.h *********/
  137833. /********* Start of inlined file: psych_44.h *********/
  137834. /* preecho trigger settings *****************************************/
  137835. static vorbis_info_psy_global _psy_global_44[5]={
  137836. {8, /* lines per eighth octave */
  137837. {20.f,14.f,12.f,12.f,12.f,12.f,12.f},
  137838. {-60.f,-30.f,-40.f,-40.f,-40.f,-40.f,-40.f}, 2,-75.f,
  137839. -6.f,
  137840. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  137841. },
  137842. {8, /* lines per eighth octave */
  137843. {14.f,10.f,10.f,10.f,10.f,10.f,10.f},
  137844. {-40.f,-30.f,-25.f,-25.f,-25.f,-25.f,-25.f}, 2,-80.f,
  137845. -6.f,
  137846. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  137847. },
  137848. {8, /* lines per eighth octave */
  137849. {12.f,10.f,10.f,10.f,10.f,10.f,10.f},
  137850. {-20.f,-20.f,-15.f,-15.f,-15.f,-15.f,-15.f}, 0,-80.f,
  137851. -6.f,
  137852. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  137853. },
  137854. {8, /* lines per eighth octave */
  137855. {10.f,8.f,8.f,8.f,8.f,8.f,8.f},
  137856. {-20.f,-15.f,-12.f,-12.f,-12.f,-12.f,-12.f}, 0,-80.f,
  137857. -6.f,
  137858. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  137859. },
  137860. {8, /* lines per eighth octave */
  137861. {10.f,6.f,6.f,6.f,6.f,6.f,6.f},
  137862. {-15.f,-15.f,-12.f,-12.f,-12.f,-12.f,-12.f}, 0,-85.f,
  137863. -6.f,
  137864. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  137865. },
  137866. };
  137867. /* noise compander lookups * low, mid, high quality ****************/
  137868. static compandblock _psy_compand_44[6]={
  137869. /* sub-mode Z short */
  137870. {{
  137871. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  137872. 8, 9,10,11,12,13,14, 15, /* 15dB */
  137873. 16,17,18,19,20,21,22, 23, /* 23dB */
  137874. 24,25,26,27,28,29,30, 31, /* 31dB */
  137875. 32,33,34,35,36,37,38, 39, /* 39dB */
  137876. }},
  137877. /* mode_Z nominal short */
  137878. {{
  137879. 0, 1, 2, 3, 4, 5, 6, 6, /* 7dB */
  137880. 7, 7, 7, 7, 6, 6, 6, 7, /* 15dB */
  137881. 7, 8, 9,10,11,12,13, 14, /* 23dB */
  137882. 15,16,17,17,17,18,18, 19, /* 31dB */
  137883. 19,19,20,21,22,23,24, 25, /* 39dB */
  137884. }},
  137885. /* mode A short */
  137886. {{
  137887. 0, 1, 2, 3, 4, 5, 5, 5, /* 7dB */
  137888. 6, 6, 6, 5, 4, 4, 4, 4, /* 15dB */
  137889. 4, 4, 5, 5, 5, 6, 6, 6, /* 23dB */
  137890. 7, 7, 7, 8, 8, 8, 9, 10, /* 31dB */
  137891. 11,12,13,14,15,16,17, 18, /* 39dB */
  137892. }},
  137893. /* sub-mode Z long */
  137894. {{
  137895. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  137896. 8, 9,10,11,12,13,14, 15, /* 15dB */
  137897. 16,17,18,19,20,21,22, 23, /* 23dB */
  137898. 24,25,26,27,28,29,30, 31, /* 31dB */
  137899. 32,33,34,35,36,37,38, 39, /* 39dB */
  137900. }},
  137901. /* mode_Z nominal long */
  137902. {{
  137903. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  137904. 8, 9,10,11,12,12,13, 13, /* 15dB */
  137905. 13,14,14,14,15,15,15, 15, /* 23dB */
  137906. 16,16,17,17,17,18,18, 19, /* 31dB */
  137907. 19,19,20,21,22,23,24, 25, /* 39dB */
  137908. }},
  137909. /* mode A long */
  137910. {{
  137911. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  137912. 8, 8, 7, 6, 5, 4, 4, 4, /* 15dB */
  137913. 4, 4, 5, 5, 5, 6, 6, 6, /* 23dB */
  137914. 7, 7, 7, 8, 8, 8, 9, 10, /* 31dB */
  137915. 11,12,13,14,15,16,17, 18, /* 39dB */
  137916. }}
  137917. };
  137918. /* tonal masking curve level adjustments *************************/
  137919. static vp_adjblock _vp_tonemask_adj_longblock[12]={
  137920. /* 63 125 250 500 1 2 4 8 16 */
  137921. {{ -3, -8,-13,-15,-10,-10,-10,-10,-10,-10,-10, 0, 0, 0, 0, 0, 0}}, /* -1 */
  137922. /* {{-15,-15,-15,-15,-10, -8, -4, -2, 0, 0, 0, 10, 0, 0, 0, 0, 0}}, 0 */
  137923. {{ -4,-10,-14,-16,-15,-14,-13,-12,-12,-12,-11, -1, -1, -1, -1, -1, 0}}, /* 0 */
  137924. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 5, 0, 0, 0, 0, 0}}, 1 */
  137925. {{ -6,-12,-14,-16,-15,-15,-14,-13,-13,-12,-12, -2, -2, -1, -1, -1, 0}}, /* 1 */
  137926. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 2 */
  137927. {{-12,-13,-14,-16,-16,-16,-15,-14,-13,-12,-12, -6, -3, -1, -1, -1, 0}}, /* 2 */
  137928. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 3 */
  137929. {{-15,-15,-15,-16,-16,-16,-16,-14,-13,-13,-13,-10, -4, -2, -1, -1, 0}}, /* 3 */
  137930. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, *//* 4 */
  137931. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 4 */
  137932. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 5 */
  137933. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 5 */
  137934. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 6 */
  137935. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -8, -4, -2, -2, 0}}, /* 6 */
  137936. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 7 */
  137937. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 7 */
  137938. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 8 */
  137939. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 8 */
  137940. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 9 */
  137941. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 9 */
  137942. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 10 */
  137943. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 10 */
  137944. };
  137945. static vp_adjblock _vp_tonemask_adj_otherblock[12]={
  137946. /* 63 125 250 500 1 2 4 8 16 */
  137947. {{ -3, -8,-13,-15,-10,-10, -9, -9, -9, -9, -9, 1, 1, 1, 1, 1, 1}}, /* -1 */
  137948. /* {{-20,-20,-20,-20,-14,-12,-10, -8, -4, 0, 0, 10, 0, 0, 0, 0, 0}}, 0 */
  137949. {{ -4,-10,-14,-16,-14,-13,-12,-12,-11,-11,-10, 0, 0, 0, 0, 0, 0}}, /* 0 */
  137950. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 5, 0, 0, 0, 0, 0}}, 1 */
  137951. {{ -6,-12,-14,-16,-15,-15,-14,-13,-13,-12,-12, -2, -2, -1, 0, 0, 0}}, /* 1 */
  137952. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 2 */
  137953. {{-12,-13,-14,-16,-16,-16,-15,-14,-13,-12,-12, -5, -2, -1, 0, 0, 0}}, /* 2 */
  137954. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 3 */
  137955. {{-15,-15,-15,-16,-16,-16,-16,-14,-13,-13,-13,-10, -4, -2, 0, 0, 0}}, /* 3 */
  137956. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 4 */
  137957. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 4 */
  137958. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 5 */
  137959. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 5 */
  137960. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 6 */
  137961. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -8, -4, -2, -2, 0}}, /* 6 */
  137962. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 7 */
  137963. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 7 */
  137964. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 8 */
  137965. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 8 */
  137966. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 9 */
  137967. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 9 */
  137968. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 10 */
  137969. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 10 */
  137970. };
  137971. /* noise bias (transition block) */
  137972. static noise3 _psy_noisebias_trans[12]={
  137973. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  137974. /* -1 */
  137975. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  137976. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  137977. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  137978. /* 0
  137979. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  137980. {-30,-30,-30,-30,-26,-22,-20,-14, -8, -4, 0, 0, 0, 0, 2, 4, 10},
  137981. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -4, -4, -4, -2}}},*/
  137982. {{{-15,-15,-15,-15,-15,-12, -6, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  137983. {-30,-30,-30,-30,-26,-22,-20,-14, -8, -4, 0, 0, 0, 0, 2, 3, 6},
  137984. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -4, -4, -4, -2}}},
  137985. /* 1
  137986. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  137987. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 8},
  137988. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},*/
  137989. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  137990. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 1, 4},
  137991. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},
  137992. /* 2
  137993. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  137994. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 6},
  137995. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}}, */
  137996. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  137997. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -2, -1, 0, 3},
  137998. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -7, -4}}},
  137999. /* 3
  138000. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  138001. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 6},
  138002. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  138003. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  138004. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -2, 0, 2},
  138005. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  138006. /* 4
  138007. {{{-20,-20,-20,-20,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  138008. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 5},
  138009. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  138010. {{{-20,-20,-20,-20,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  138011. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -2, -1, 1},
  138012. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  138013. /* 5
  138014. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  138015. {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -4, -4, -4, -4, -2, -1, 2},
  138016. {-34,-34,-34,-34,-30,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}}, */
  138017. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  138018. {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -4, -4, -4, -4, -3, -1, 0},
  138019. {-34,-34,-34,-34,-30,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}},
  138020. /* 6
  138021. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  138022. {-32,-32,-32,-32,-28,-24,-24,-18,-14, -8, -6, -6, -6, -6, -4, -2, 1},
  138023. {-34,-34,-34,-34,-30,-26,-24,-18,-17,-15,-15,-15,-15,-13,-13,-12, -8}}},*/
  138024. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  138025. {-32,-32,-32,-32,-28,-24,-24,-18,-14, -8, -6, -6, -6, -6, -5, -2, 0},
  138026. {-34,-34,-34,-34,-30,-26,-26,-24,-22,-19,-19,-19,-19,-18,-17,-16,-12}}},
  138027. /* 7
  138028. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  138029. {-32,-32,-32,-32,-28,-24,-24,-18,-14,-12,-10, -8, -8, -8, -6, -4, 0},
  138030. {-34,-34,-34,-34,-30,-26,-26,-24,-22,-19,-19,-19,-19,-18,-17,-16,-12}}},*/
  138031. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  138032. {-32,-32,-32,-32,-28,-24,-24,-24,-18,-14,-12,-10,-10,-10, -8, -6, -2},
  138033. {-34,-34,-34,-34,-30,-26,-26,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},
  138034. /* 8
  138035. {{{-24,-24,-24,-24,-22,-20,-15,-10, -8, -2, 0, 0, 0, 1, 2, 3, 7},
  138036. {-36,-36,-36,-36,-30,-30,-30,-24,-18,-14,-12,-10,-10,-10, -8, -6, -2},
  138037. {-36,-36,-36,-36,-34,-30,-28,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},*/
  138038. {{{-24,-24,-24,-24,-22,-20,-15,-10, -8, -2, 0, 0, 0, 1, 2, 3, 7},
  138039. {-36,-36,-36,-36,-30,-30,-30,-24,-20,-16,-16,-16,-16,-14,-12,-10, -7},
  138040. {-36,-36,-36,-36,-34,-30,-28,-26,-24,-30,-30,-30,-30,-30,-30,-24,-20}}},
  138041. /* 9
  138042. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  138043. {-36,-36,-36,-36,-34,-32,-32,-28,-20,-16,-16,-16,-16,-14,-12,-10, -7},
  138044. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},*/
  138045. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  138046. {-38,-38,-38,-38,-36,-34,-34,-30,-24,-20,-20,-20,-20,-18,-16,-12,-10},
  138047. {-40,-40,-40,-40,-40,-40,-40,-38,-35,-35,-35,-35,-35,-35,-35,-35,-30}}},
  138048. /* 10 */
  138049. {{{-30,-30,-30,-30,-30,-30,-30,-28,-20,-14,-14,-14,-14,-14,-14,-12,-10},
  138050. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-30,-30,-30,-30,-30,-30,-20},
  138051. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  138052. };
  138053. /* noise bias (long block) */
  138054. static noise3 _psy_noisebias_long[12]={
  138055. /*63 125 250 500 1k 2k 4k 8k 16k*/
  138056. /* -1 */
  138057. {{{-10,-10,-10,-10,-10, -4, 0, 0, 0, 6, 6, 6, 6, 10, 10, 12, 20},
  138058. {-20,-20,-20,-20,-20,-20,-10, -2, 0, 0, 0, 0, 0, 2, 4, 6, 15},
  138059. {-20,-20,-20,-20,-20,-20,-20,-10, -6, -6, -6, -6, -6, -4, -4, -4, -2}}},
  138060. /* 0 */
  138061. /* {{{-10,-10,-10,-10,-10,-10, -8, 2, 2, 2, 4, 4, 5, 5, 5, 8, 10},
  138062. {-20,-20,-20,-20,-20,-20,-20,-14, -6, 0, 0, 0, 0, 0, 2, 4, 10},
  138063. {-20,-20,-20,-20,-20,-20,-20,-14, -8, -6, -6, -6, -6, -4, -4, -4, -2}}},*/
  138064. {{{-10,-10,-10,-10,-10,-10, -8, 2, 2, 2, 4, 4, 5, 5, 5, 8, 10},
  138065. {-20,-20,-20,-20,-20,-20,-20,-14, -6, 0, 0, 0, 0, 0, 2, 3, 6},
  138066. {-20,-20,-20,-20,-20,-20,-20,-14, -8, -6, -6, -6, -6, -4, -4, -4, -2}}},
  138067. /* 1 */
  138068. /* {{{-10,-10,-10,-10,-10,-10, -8, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  138069. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 8},
  138070. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},*/
  138071. {{{-10,-10,-10,-10,-10,-10, -8, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  138072. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 1, 4},
  138073. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},
  138074. /* 2 */
  138075. /* {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  138076. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 6},
  138077. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  138078. {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  138079. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -2, -1, 0, 3},
  138080. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  138081. /* 3 */
  138082. /* {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  138083. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 6},
  138084. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  138085. {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  138086. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -2, 0, 2},
  138087. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -5}}},
  138088. /* 4 */
  138089. /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  138090. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 5},
  138091. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  138092. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  138093. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -2, -1, 1},
  138094. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -7}}},
  138095. /* 5 */
  138096. /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  138097. {-22,-22,-22,-22,-22,-22,-22,-16,-12, -6, -4, -4, -4, -4, -2, -1, 2},
  138098. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}},*/
  138099. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  138100. {-22,-22,-22,-22,-22,-22,-22,-16,-12, -6, -4, -4, -4, -4, -3, -1, 0},
  138101. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -8}}},
  138102. /* 6 */
  138103. /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  138104. {-24,-24,-24,-24,-24,-24,-24,-18,-14, -8, -6, -6, -6, -6, -4, -2, 1},
  138105. {-26,-26,-26,-26,-26,-26,-26,-18,-16,-15,-15,-15,-15,-13,-13,-12, -8}}},*/
  138106. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  138107. {-24,-24,-24,-24,-24,-24,-24,-18,-14, -8, -6, -6, -6, -6, -5, -2, 0},
  138108. {-26,-26,-26,-26,-26,-26,-26,-18,-16,-15,-15,-15,-15,-13,-13,-12,-10}}},
  138109. /* 7 */
  138110. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  138111. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-10, -8, -8, -8, -8, -6, -4, 0},
  138112. {-26,-26,-26,-26,-26,-26,-26,-22,-20,-19,-19,-19,-19,-18,-17,-16,-12}}},
  138113. /* 8 */
  138114. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 0, 0, 0, 0, 1, 2, 3, 7},
  138115. {-26,-26,-26,-26,-26,-26,-26,-20,-16,-12,-10,-10,-10,-10, -8, -6, -2},
  138116. {-28,-28,-28,-28,-28,-28,-28,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},
  138117. /* 9 */
  138118. {{{-22,-22,-22,-22,-22,-22,-22,-18,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  138119. {-26,-26,-26,-26,-26,-26,-26,-22,-18,-16,-16,-16,-16,-14,-12,-10, -7},
  138120. {-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},
  138121. /* 10 */
  138122. {{{-24,-24,-24,-24,-24,-24,-24,-24,-24,-18,-14,-14,-14,-14,-14,-12,-10},
  138123. {-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-20},
  138124. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  138125. };
  138126. /* noise bias (impulse block) */
  138127. static noise3 _psy_noisebias_impulse[12]={
  138128. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  138129. /* -1 */
  138130. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  138131. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  138132. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  138133. /* 0 */
  138134. /* {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 4, 8, 8, 8, 10, 12, 14, 20},
  138135. {-30,-30,-30,-30,-26,-22,-20,-14, -6, -2, 0, 0, 0, 0, 2, 4, 10},
  138136. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},*/
  138137. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 4, 8, 8, 8, 10, 12, 14, 20},
  138138. {-30,-30,-30,-30,-26,-22,-20,-14, -6, -2, 0, 0, 0, 0, 2, 3, 6},
  138139. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  138140. /* 1 */
  138141. {{{-12,-12,-12,-12,-12, -8, -6, -4, 0, 4, 4, 4, 4, 10, 12, 14, 20},
  138142. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -4, -4, -2, -2, -2, -2, 2},
  138143. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8,-10,-10, -8, -8, -8, -6, -4}}},
  138144. /* 2 */
  138145. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  138146. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  138147. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  138148. /* 3 */
  138149. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 6, 8, 8, 14},
  138150. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  138151. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  138152. /* 4 */
  138153. {{{-16,-16,-16,-16,-16,-12,-10, -6, -2, 0, 0, 0, 0, 4, 6, 6, 12},
  138154. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  138155. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  138156. /* 5 */
  138157. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  138158. {-32,-32,-32,-32,-28,-24,-22,-16,-10, -6, -8, -8, -6, -6, -6, -4, -2},
  138159. {-34,-34,-34,-34,-30,-26,-24,-18,-14,-12,-12,-12,-12,-12,-10, -9, -5}}},
  138160. /* 6
  138161. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  138162. {-34,-34,-34,-34,-30,-30,-24,-20,-12,-12,-14,-14,-10, -9, -8, -6, -4},
  138163. {-34,-34,-34,-34,-34,-30,-26,-20,-16,-15,-15,-15,-15,-15,-13,-12, -8}}},*/
  138164. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  138165. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-16,-16,-16,-16,-16,-14,-14,-12},
  138166. {-36,-36,-36,-36,-36,-34,-28,-24,-20,-20,-20,-20,-20,-20,-20,-18,-16}}},
  138167. /* 7 */
  138168. /* {{{-22,-22,-22,-22,-22,-20,-14,-10, -6, 0, 0, 0, 0, 4, 4, 6, 11},
  138169. {-34,-34,-34,-34,-30,-30,-24,-20,-14,-14,-16,-16,-14,-12,-10,-10,-10},
  138170. {-34,-34,-34,-34,-32,-32,-30,-24,-20,-19,-19,-19,-19,-19,-17,-16,-12}}},*/
  138171. {{{-22,-22,-22,-22,-22,-20,-14,-10, -6, 0, 0, 0, 0, 4, 4, 6, 11},
  138172. {-34,-34,-34,-34,-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-24,-22},
  138173. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-30,-24}}},
  138174. /* 8 */
  138175. /* {{{-24,-24,-24,-24,-24,-22,-14,-10, -6, -1, -1, -1, -1, 3, 3, 5, 10},
  138176. {-34,-34,-34,-34,-30,-30,-30,-24,-20,-20,-20,-20,-20,-18,-16,-16,-14},
  138177. {-36,-36,-36,-36,-36,-34,-28,-24,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},*/
  138178. {{{-24,-24,-24,-24,-24,-22,-14,-10, -6, -1, -1, -1, -1, 3, 3, 5, 10},
  138179. {-34,-34,-34,-34,-34,-32,-32,-30,-26,-26,-26,-26,-26,-26,-26,-26,-24},
  138180. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-30,-24}}},
  138181. /* 9 */
  138182. /* {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  138183. {-36,-36,-36,-36,-34,-32,-32,-30,-26,-26,-26,-26,-26,-22,-20,-20,-18},
  138184. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},*/
  138185. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  138186. {-36,-36,-36,-36,-34,-32,-32,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26},
  138187. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},
  138188. /* 10 */
  138189. {{{-30,-30,-30,-30,-30,-26,-24,-24,-24,-20,-16,-16,-16,-16,-16,-14,-12},
  138190. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-30,-30,-30,-30,-30,-30,-26},
  138191. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  138192. };
  138193. /* noise bias (padding block) */
  138194. static noise3 _psy_noisebias_padding[12]={
  138195. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  138196. /* -1 */
  138197. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  138198. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  138199. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  138200. /* 0 */
  138201. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  138202. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, 2, 3, 6, 6, 8, 10},
  138203. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -4, -4, -4, -4, -2, 0, 2}}},
  138204. /* 1 */
  138205. {{{-12,-12,-12,-12,-12, -8, -6, -4, 0, 4, 4, 4, 4, 10, 12, 14, 20},
  138206. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, 0, 0, 0, 2, 2, 4, 8},
  138207. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -6, -4, -2, 0}}},
  138208. /* 2 */
  138209. /* {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  138210. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, 0, 0, 0, 2, 2, 4, 8},
  138211. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},*/
  138212. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  138213. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, 0, 0, 2, 6},
  138214. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  138215. /* 3 */
  138216. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 6, 8, 8, 14},
  138217. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, 0, 0, 2, 6},
  138218. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  138219. /* 4 */
  138220. {{{-16,-16,-16,-16,-16,-12,-10, -6, -2, 0, 0, 0, 0, 4, 6, 6, 12},
  138221. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, -1, 0, 2, 6},
  138222. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  138223. /* 5 */
  138224. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  138225. {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -3, -3, -3, -3, -2, 0, 4},
  138226. {-34,-34,-34,-34,-30,-26,-24,-18,-14,-10,-10,-10,-10,-10, -8, -5, -3}}},
  138227. /* 6 */
  138228. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  138229. {-34,-34,-34,-34,-30,-30,-24,-20,-14, -8, -4, -4, -4, -4, -3, -1, 4},
  138230. {-34,-34,-34,-34,-34,-30,-26,-20,-16,-13,-13,-13,-13,-13,-11, -8, -6}}},
  138231. /* 7 */
  138232. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  138233. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-10, -8, -6, -6, -6, -5, -3, 1},
  138234. {-34,-34,-34,-34,-32,-32,-28,-22,-18,-16,-16,-16,-16,-16,-14,-12,-10}}},
  138235. /* 8 */
  138236. {{{-22,-22,-22,-22,-22,-20,-14,-10, -4, 0, 0, 0, 0, 3, 5, 5, 11},
  138237. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-12,-10, -8, -8, -8, -7, -5, -2},
  138238. {-36,-36,-36,-36,-36,-34,-28,-22,-20,-20,-20,-20,-20,-20,-20,-16,-14}}},
  138239. /* 9 */
  138240. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -2, -2, -2, -2, 0, 2, 6},
  138241. {-36,-36,-36,-36,-34,-32,-32,-24,-16,-12,-12,-12,-12,-12,-10, -8, -5},
  138242. {-40,-40,-40,-40,-40,-40,-40,-32,-26,-24,-24,-24,-24,-24,-24,-20,-18}}},
  138243. /* 10 */
  138244. {{{-30,-30,-30,-30,-30,-26,-24,-24,-24,-20,-12,-12,-12,-12,-12,-10, -8},
  138245. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-25,-25,-25,-25,-25,-25,-15},
  138246. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  138247. };
  138248. static noiseguard _psy_noiseguards_44[4]={
  138249. {3,3,15},
  138250. {3,3,15},
  138251. {10,10,100},
  138252. {10,10,100},
  138253. };
  138254. static int _psy_tone_suppress[12]={
  138255. -20,-20,-20,-20,-20,-24,-30,-40,-40,-45,-45,-45,
  138256. };
  138257. static int _psy_tone_0dB[12]={
  138258. 90,90,95,95,95,95,105,105,105,105,105,105,
  138259. };
  138260. static int _psy_noise_suppress[12]={
  138261. -20,-20,-24,-24,-24,-24,-30,-40,-40,-45,-45,-45,
  138262. };
  138263. static vorbis_info_psy _psy_info_template={
  138264. /* blockflag */
  138265. -1,
  138266. /* ath_adjatt, ath_maxatt */
  138267. -140.,-140.,
  138268. /* tonemask att boost/decay,suppr,curves */
  138269. {0.f,0.f,0.f}, 0.,0., -40.f, {0.},
  138270. /*noisemaskp,supp, low/high window, low/hi guard, minimum */
  138271. 1, -0.f, .5f, .5f, 0,0,0,
  138272. /* noiseoffset*3, noisecompand, max_curve_dB */
  138273. {{-1},{-1},{-1}},{-1},105.f,
  138274. /* noise normalization - channel_p, point_p, start, partition, thresh. */
  138275. 0,0,-1,-1,0.,
  138276. };
  138277. /* ath ****************/
  138278. static int _psy_ath_floater[12]={
  138279. -100,-100,-100,-100,-100,-100,-105,-105,-105,-105,-110,-120,
  138280. };
  138281. static int _psy_ath_abs[12]={
  138282. -130,-130,-130,-130,-140,-140,-140,-140,-140,-140,-140,-150,
  138283. };
  138284. /* stereo setup. These don't map directly to quality level, there's
  138285. an additional indirection as several of the below may be used in a
  138286. single bitmanaged stream
  138287. ****************/
  138288. /* various stereo possibilities */
  138289. /* stereo mode by base quality level */
  138290. static adj_stereo _psy_stereo_modes_44[12]={
  138291. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 -1 */
  138292. {{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 2, 1, 0, 0, 0, 0},
  138293. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 5, 4, 3},
  138294. { 1, 2, 3, 4, 4, 4, 4, 4, 4, 5, 6, 7, 8, 8, 8},
  138295. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},
  138296. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 0 */
  138297. /*{{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 2, 1, 0, 0, 0, 0},
  138298. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 5, 4, 3},
  138299. { 1, 2, 3, 4, 5, 5, 6, 6, 6, 6, 6, 7, 8, 8, 8},
  138300. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  138301. {{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 1, 0, 0, 0, 0, 0},
  138302. { 8, 8, 8, 8, 6, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3},
  138303. { 1, 2, 3, 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  138304. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},
  138305. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 1 */
  138306. {{ 3, 3, 3, 3, 3, 3, 3, 3, 2, 1, 0, 0, 0, 0, 0},
  138307. { 8, 8, 8, 8, 6, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3},
  138308. { 1, 2, 3, 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  138309. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  138310. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 2 */
  138311. /* {{ 3, 3, 3, 3, 3, 3, 2, 2, 2, 1, 0, 0, 0, 0, 0},
  138312. { 8, 8, 8, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3, 2, 1},
  138313. { 3, 4, 4, 4, 5, 6, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  138314. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}}, */
  138315. {{ 3, 3, 3, 3, 3, 3, 3, 2, 1, 1, 0, 0, 0, 0, 0},
  138316. { 8, 8, 6, 6, 5, 5, 4, 4, 4, 4, 4, 4, 3, 2, 1},
  138317. { 3, 4, 4, 5, 5, 6, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  138318. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  138319. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 3 */
  138320. {{ 2, 2, 2, 2, 2, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0},
  138321. { 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 2, 1},
  138322. { 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 10, 10, 10, 10, 10},
  138323. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  138324. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 4 */
  138325. {{ 2, 2, 2, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  138326. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 3, 2, 1, 0},
  138327. { 6, 6, 6, 8, 8, 8, 8, 8, 8, 8, 10, 10, 10, 10, 10},
  138328. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  138329. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 5 */
  138330. /* {{ 2, 2, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  138331. { 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0},
  138332. { 6, 6, 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  138333. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  138334. {{ 2, 2, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  138335. { 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0},
  138336. { 6, 7, 8, 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12},
  138337. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  138338. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 6 */
  138339. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  138340. { 3, 3, 3, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  138341. { 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  138342. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}}, */
  138343. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  138344. { 3, 3, 3, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  138345. { 8, 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  138346. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  138347. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 7 */
  138348. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  138349. { 3, 3, 3, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  138350. { 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  138351. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  138352. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  138353. { 3, 3, 3, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  138354. { 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  138355. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  138356. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 8 */
  138357. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  138358. { 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  138359. { 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  138360. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  138361. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  138362. { 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  138363. { 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  138364. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  138365. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 9 */
  138366. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  138367. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  138368. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  138369. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  138370. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 10 */
  138371. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  138372. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  138373. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  138374. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  138375. };
  138376. /* tone master attenuation by base quality mode and bitrate tweak */
  138377. static att3 _psy_tone_masteratt_44[12]={
  138378. {{ 35, 21, 9}, 0, 0}, /* -1 */
  138379. {{ 30, 20, 8}, -2, 1.25}, /* 0 */
  138380. /* {{ 25, 14, 4}, 0, 0}, *//* 1 */
  138381. {{ 25, 12, 2}, 0, 0}, /* 1 */
  138382. /* {{ 20, 10, -2}, 0, 0}, *//* 2 */
  138383. {{ 20, 9, -3}, 0, 0}, /* 2 */
  138384. {{ 20, 9, -4}, 0, 0}, /* 3 */
  138385. {{ 20, 9, -4}, 0, 0}, /* 4 */
  138386. {{ 20, 6, -6}, 0, 0}, /* 5 */
  138387. {{ 20, 3, -10}, 0, 0}, /* 6 */
  138388. {{ 18, 1, -14}, 0, 0}, /* 7 */
  138389. {{ 18, 0, -16}, 0, 0}, /* 8 */
  138390. {{ 18, -2, -16}, 0, 0}, /* 9 */
  138391. {{ 12, -2, -20}, 0, 0}, /* 10 */
  138392. };
  138393. /* lowpass by mode **************/
  138394. static double _psy_lowpass_44[12]={
  138395. /* 15.1,15.8,16.5,17.9,20.5,48.,999.,999.,999.,999.,999. */
  138396. 13.9,15.1,15.8,16.5,17.2,18.9,20.1,48.,999.,999.,999.,999.
  138397. };
  138398. /* noise normalization **********/
  138399. static int _noise_start_short_44[11]={
  138400. /* 16,16,16,16,32,32,9999,9999,9999,9999 */
  138401. 32,16,16,16,32,9999,9999,9999,9999,9999,9999
  138402. };
  138403. static int _noise_start_long_44[11]={
  138404. /* 128,128,128,256,512,512,9999,9999,9999,9999 */
  138405. 256,128,128,256,512,9999,9999,9999,9999,9999,9999
  138406. };
  138407. static int _noise_part_short_44[11]={
  138408. 8,8,8,8,8,8,8,8,8,8,8
  138409. };
  138410. static int _noise_part_long_44[11]={
  138411. 32,32,32,32,32,32,32,32,32,32,32
  138412. };
  138413. static double _noise_thresh_44[11]={
  138414. /* .2,.2,.3,.4,.5,.5,9999.,9999.,9999.,9999., */
  138415. .2,.2,.2,.4,.6,9999.,9999.,9999.,9999.,9999.,9999.,
  138416. };
  138417. static double _noise_thresh_5only[2]={
  138418. .5,.5,
  138419. };
  138420. /********* End of inlined file: psych_44.h *********/
  138421. static double rate_mapping_44_stereo[12]={
  138422. 22500.,32000.,40000.,48000.,56000.,64000.,
  138423. 80000.,96000.,112000.,128000.,160000.,250001.
  138424. };
  138425. static double quality_mapping_44[12]={
  138426. -.1,.0,.1,.2,.3,.4,.5,.6,.7,.8,.9,1.0
  138427. };
  138428. static int blocksize_short_44[11]={
  138429. 512,256,256,256,256,256,256,256,256,256,256
  138430. };
  138431. static int blocksize_long_44[11]={
  138432. 4096,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048
  138433. };
  138434. static double _psy_compand_short_mapping[12]={
  138435. 0.5, 1., 1., 1.3, 1.6, 2., 2., 2., 2., 2., 2., 2.
  138436. };
  138437. static double _psy_compand_long_mapping[12]={
  138438. 3.5, 4., 4., 4.3, 4.6, 5., 5., 5., 5., 5., 5., 5.
  138439. };
  138440. static double _global_mapping_44[12]={
  138441. /* 1., 1., 1.5, 2., 2., 2.5, 2.7, 3.0, 3.5, 4., 4. */
  138442. 0., 1., 1., 1.5, 2., 2., 2.5, 2.7, 3.0, 3.7, 4., 4.
  138443. };
  138444. static int _floor_short_mapping_44[11]={
  138445. 1,0,0,2,2,4,5,5,5,5,5
  138446. };
  138447. static int _floor_long_mapping_44[11]={
  138448. 8,7,7,7,7,7,7,7,7,7,7
  138449. };
  138450. ve_setup_data_template ve_setup_44_stereo={
  138451. 11,
  138452. rate_mapping_44_stereo,
  138453. quality_mapping_44,
  138454. 2,
  138455. 40000,
  138456. 50000,
  138457. blocksize_short_44,
  138458. blocksize_long_44,
  138459. _psy_tone_masteratt_44,
  138460. _psy_tone_0dB,
  138461. _psy_tone_suppress,
  138462. _vp_tonemask_adj_otherblock,
  138463. _vp_tonemask_adj_longblock,
  138464. _vp_tonemask_adj_otherblock,
  138465. _psy_noiseguards_44,
  138466. _psy_noisebias_impulse,
  138467. _psy_noisebias_padding,
  138468. _psy_noisebias_trans,
  138469. _psy_noisebias_long,
  138470. _psy_noise_suppress,
  138471. _psy_compand_44,
  138472. _psy_compand_short_mapping,
  138473. _psy_compand_long_mapping,
  138474. {_noise_start_short_44,_noise_start_long_44},
  138475. {_noise_part_short_44,_noise_part_long_44},
  138476. _noise_thresh_44,
  138477. _psy_ath_floater,
  138478. _psy_ath_abs,
  138479. _psy_lowpass_44,
  138480. _psy_global_44,
  138481. _global_mapping_44,
  138482. _psy_stereo_modes_44,
  138483. _floor_books,
  138484. _floor,
  138485. _floor_short_mapping_44,
  138486. _floor_long_mapping_44,
  138487. _mapres_template_44_stereo
  138488. };
  138489. /********* End of inlined file: setup_44.h *********/
  138490. /********* Start of inlined file: setup_44u.h *********/
  138491. /********* Start of inlined file: residue_44u.h *********/
  138492. /********* Start of inlined file: res_books_uncoupled.h *********/
  138493. static long _vq_quantlist__16u0__p1_0[] = {
  138494. 1,
  138495. 0,
  138496. 2,
  138497. };
  138498. static long _vq_lengthlist__16u0__p1_0[] = {
  138499. 1, 4, 4, 5, 7, 7, 5, 7, 8, 5, 8, 8, 8,10,10, 8,
  138500. 10,11, 5, 8, 8, 8,10,10, 8,10,10, 4, 9, 9, 9,12,
  138501. 11, 8,11,11, 8,12,11,10,12,14,10,13,13, 7,11,11,
  138502. 10,14,12,11,14,14, 4, 9, 9, 8,11,11, 9,11,12, 7,
  138503. 11,11,10,13,14,10,12,14, 8,11,12,10,14,14,10,13,
  138504. 12,
  138505. };
  138506. static float _vq_quantthresh__16u0__p1_0[] = {
  138507. -0.5, 0.5,
  138508. };
  138509. static long _vq_quantmap__16u0__p1_0[] = {
  138510. 1, 0, 2,
  138511. };
  138512. static encode_aux_threshmatch _vq_auxt__16u0__p1_0 = {
  138513. _vq_quantthresh__16u0__p1_0,
  138514. _vq_quantmap__16u0__p1_0,
  138515. 3,
  138516. 3
  138517. };
  138518. static static_codebook _16u0__p1_0 = {
  138519. 4, 81,
  138520. _vq_lengthlist__16u0__p1_0,
  138521. 1, -535822336, 1611661312, 2, 0,
  138522. _vq_quantlist__16u0__p1_0,
  138523. NULL,
  138524. &_vq_auxt__16u0__p1_0,
  138525. NULL,
  138526. 0
  138527. };
  138528. static long _vq_quantlist__16u0__p2_0[] = {
  138529. 1,
  138530. 0,
  138531. 2,
  138532. };
  138533. static long _vq_lengthlist__16u0__p2_0[] = {
  138534. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 9, 7,
  138535. 8, 9, 5, 7, 7, 7, 9, 8, 7, 9, 7, 4, 7, 7, 7, 9,
  138536. 9, 7, 8, 8, 6, 9, 8, 7, 8,11, 9,11,10, 6, 8, 9,
  138537. 8,11, 8, 9,10,11, 4, 7, 7, 7, 8, 8, 7, 9, 9, 6,
  138538. 9, 8, 9,11,10, 8, 8,11, 6, 8, 9, 9,10,11, 8,11,
  138539. 8,
  138540. };
  138541. static float _vq_quantthresh__16u0__p2_0[] = {
  138542. -0.5, 0.5,
  138543. };
  138544. static long _vq_quantmap__16u0__p2_0[] = {
  138545. 1, 0, 2,
  138546. };
  138547. static encode_aux_threshmatch _vq_auxt__16u0__p2_0 = {
  138548. _vq_quantthresh__16u0__p2_0,
  138549. _vq_quantmap__16u0__p2_0,
  138550. 3,
  138551. 3
  138552. };
  138553. static static_codebook _16u0__p2_0 = {
  138554. 4, 81,
  138555. _vq_lengthlist__16u0__p2_0,
  138556. 1, -535822336, 1611661312, 2, 0,
  138557. _vq_quantlist__16u0__p2_0,
  138558. NULL,
  138559. &_vq_auxt__16u0__p2_0,
  138560. NULL,
  138561. 0
  138562. };
  138563. static long _vq_quantlist__16u0__p3_0[] = {
  138564. 2,
  138565. 1,
  138566. 3,
  138567. 0,
  138568. 4,
  138569. };
  138570. static long _vq_lengthlist__16u0__p3_0[] = {
  138571. 1, 5, 5, 7, 7, 6, 7, 7, 8, 8, 6, 7, 8, 8, 8, 8,
  138572. 9, 9,11,11, 8, 9, 9,11,11, 6, 9, 8,10,10, 8,10,
  138573. 10,11,11, 8,10,10,11,11,10,11,10,13,12, 9,11,10,
  138574. 13,13, 6, 8, 9,10,10, 8,10,10,11,11, 8,10,10,11,
  138575. 11, 9,10,11,13,12,10,10,11,12,12, 8,11,11,14,13,
  138576. 10,12,11,15,13, 9,12,11,15,14,12,14,13,16,14,12,
  138577. 13,13,17,14, 8,11,11,13,14, 9,11,12,14,15,10,11,
  138578. 12,13,15,11,13,13,14,16,12,13,14,14,16, 5, 9, 9,
  138579. 11,11, 9,11,11,12,12, 8,11,11,12,12,11,12,12,15,
  138580. 14,10,12,12,15,15, 8,11,11,13,12,10,12,12,13,13,
  138581. 10,12,12,14,13,12,12,13,14,15,11,13,13,17,16, 7,
  138582. 11,11,13,13,10,12,12,14,13,10,12,12,13,14,12,13,
  138583. 12,15,14,11,13,13,15,14, 9,12,12,16,15,11,13,13,
  138584. 17,16,10,13,13,16,16,13,14,15,15,16,13,15,14,19,
  138585. 17, 9,12,12,14,16,11,13,13,15,16,10,13,13,17,16,
  138586. 13,14,13,17,15,12,15,15,16,17, 5, 9, 9,11,11, 8,
  138587. 11,11,13,12, 9,11,11,12,12,10,12,12,14,15,11,12,
  138588. 12,14,14, 7,11,10,13,12,10,12,12,14,13,10,11,12,
  138589. 13,13,11,13,13,15,16,12,12,13,15,15, 7,11,11,13,
  138590. 13,10,13,13,14,14,10,12,12,13,13,11,13,13,16,15,
  138591. 12,13,13,15,14, 9,12,12,15,15,10,13,13,17,16,11,
  138592. 12,13,15,15,12,15,14,18,18,13,14,14,16,17, 9,12,
  138593. 12,15,16,10,13,13,15,16,11,13,13,15,16,13,15,15,
  138594. 17,17,13,15,14,16,15, 7,11,11,15,16,10,13,12,16,
  138595. 17,10,12,13,15,17,15,16,16,18,17,13,15,15,17,18,
  138596. 8,12,12,16,16,11,13,14,17,18,11,13,13,18,16,15,
  138597. 17,16,17,19,14,15,15,17,16, 8,12,12,16,15,11,14,
  138598. 13,18,17,11,13,14,18,17,15,16,16,18,17,13,16,16,
  138599. 18,18,11,15,14,18,17,13,14,15,18, 0,12,15,15, 0,
  138600. 17,17,16,17,17,18,14,16,18,18, 0,11,14,14,17, 0,
  138601. 12,15,14,17,19,12,15,14,18, 0,15,18,16, 0,17,14,
  138602. 18,16,18, 0, 7,11,11,16,15,10,12,12,18,16,10,13,
  138603. 13,16,15,13,15,14,17,17,14,16,16,19,18, 8,12,12,
  138604. 16,16,11,13,13,18,16,11,13,14,17,16,14,15,15,19,
  138605. 18,15,16,16, 0,19, 8,12,12,16,17,11,13,13,17,17,
  138606. 11,14,13,17,17,13,15,15,17,19,15,17,17,19, 0,11,
  138607. 14,15,19,17,12,15,16,18,18,12,14,15,19,17,14,16,
  138608. 17, 0,18,16,16,19,17, 0,11,14,14,18,19,12,15,14,
  138609. 17,17,13,16,14,17,16,14,17,16,18,18,15,18,15, 0,
  138610. 18,
  138611. };
  138612. static float _vq_quantthresh__16u0__p3_0[] = {
  138613. -1.5, -0.5, 0.5, 1.5,
  138614. };
  138615. static long _vq_quantmap__16u0__p3_0[] = {
  138616. 3, 1, 0, 2, 4,
  138617. };
  138618. static encode_aux_threshmatch _vq_auxt__16u0__p3_0 = {
  138619. _vq_quantthresh__16u0__p3_0,
  138620. _vq_quantmap__16u0__p3_0,
  138621. 5,
  138622. 5
  138623. };
  138624. static static_codebook _16u0__p3_0 = {
  138625. 4, 625,
  138626. _vq_lengthlist__16u0__p3_0,
  138627. 1, -533725184, 1611661312, 3, 0,
  138628. _vq_quantlist__16u0__p3_0,
  138629. NULL,
  138630. &_vq_auxt__16u0__p3_0,
  138631. NULL,
  138632. 0
  138633. };
  138634. static long _vq_quantlist__16u0__p4_0[] = {
  138635. 2,
  138636. 1,
  138637. 3,
  138638. 0,
  138639. 4,
  138640. };
  138641. static long _vq_lengthlist__16u0__p4_0[] = {
  138642. 3, 5, 5, 8, 8, 6, 6, 6, 9, 9, 6, 6, 6, 9, 9, 9,
  138643. 10, 9,11,11, 9, 9, 9,11,11, 6, 7, 7,10,10, 7, 7,
  138644. 8,10,10, 7, 7, 8,10,10,10,10,10,11,12, 9,10,10,
  138645. 11,12, 6, 7, 7,10,10, 7, 8, 7,10,10, 7, 8, 7,10,
  138646. 10,10,11,10,12,11,10,10,10,13,10, 9,10,10,12,12,
  138647. 10,11,10,14,12, 9,11,11,13,13,11,12,13,13,13,11,
  138648. 12,12,15,13, 9,10,10,12,13, 9,11,10,12,13,10,10,
  138649. 11,12,13,11,12,12,12,13,11,12,12,13,13, 5, 7, 7,
  138650. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,12,
  138651. 13,10,10,11,12,12, 6, 8, 8,11,10, 7, 8, 9,10,12,
  138652. 8, 9, 9,11,11,11,10,11,11,12,10,11,11,13,12, 7,
  138653. 8, 8,10,11, 8, 9, 8,11,10, 8, 9, 9,11,11,10,12,
  138654. 10,13,11,10,11,11,13,13,10,11,10,14,13,10,10,11,
  138655. 13,13,10,12,11,14,13,12,11,13,12,13,13,12,13,14,
  138656. 14,10,11,11,13,13,10,11,10,12,13,10,12,12,12,14,
  138657. 12,12,12,14,12,12,13,12,17,15, 5, 7, 7,10,10, 7,
  138658. 8, 8,10,10, 7, 8, 8,11,10,10,10,11,12,12,10,11,
  138659. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  138660. 10,11,11,11,11,12,12,10,10,11,12,13, 6, 8, 8,10,
  138661. 11, 8, 9, 9,11,11, 7, 9, 7,11,10,10,12,12,13,13,
  138662. 11,11,10,13,11, 9,11,10,14,13,11,11,11,15,13,10,
  138663. 10,11,13,13,12,13,13,14,14,12,11,12,12,13,10,11,
  138664. 11,12,13,10,11,12,13,13,10,11,10,13,12,12,12,13,
  138665. 14, 0,12,13,11,13,11, 8,10,10,13,13,10,11,11,14,
  138666. 13,10,11,11,13,12,13,14,14,14,15,12,12,12,15,14,
  138667. 9,11,10,13,12,10,10,11,13,14,11,11,11,15,12,13,
  138668. 12,14,15,16,13,13,13,14,13, 9,11,11,12,12,10,12,
  138669. 11,13,13,10,11,11,13,14,13,13,13,15,15,13,13,14,
  138670. 17,15,11,12,12,14,14,10,11,12,13,15,12,13,13, 0,
  138671. 15,13,11,14,12,16,14,16,14, 0,15,11,12,12,14,16,
  138672. 11,13,12,16,15,12,13,13,14,15,12,14,12,15,13,15,
  138673. 14,14,16,16, 8,10,10,13,13,10,11,10,13,14,10,11,
  138674. 11,13,13,13,13,12,14,14,14,13,13,16,17, 9,10,10,
  138675. 12,14,10,12,11,14,13,10,11,12,13,14,12,12,12,15,
  138676. 15,13,13,13,14,14, 9,10,10,13,13,10,11,12,12,14,
  138677. 10,11,10,13,13,13,13,13,14,16,13,13,13,14,14,11,
  138678. 12,13,15,13,12,14,13,14,16,12,12,13,13,14,13,14,
  138679. 14,17,15,13,12,17,13,16,11,12,13,14,15,12,13,14,
  138680. 14,17,11,12,11,14,14,13,16,14,16, 0,14,15,11,15,
  138681. 11,
  138682. };
  138683. static float _vq_quantthresh__16u0__p4_0[] = {
  138684. -1.5, -0.5, 0.5, 1.5,
  138685. };
  138686. static long _vq_quantmap__16u0__p4_0[] = {
  138687. 3, 1, 0, 2, 4,
  138688. };
  138689. static encode_aux_threshmatch _vq_auxt__16u0__p4_0 = {
  138690. _vq_quantthresh__16u0__p4_0,
  138691. _vq_quantmap__16u0__p4_0,
  138692. 5,
  138693. 5
  138694. };
  138695. static static_codebook _16u0__p4_0 = {
  138696. 4, 625,
  138697. _vq_lengthlist__16u0__p4_0,
  138698. 1, -533725184, 1611661312, 3, 0,
  138699. _vq_quantlist__16u0__p4_0,
  138700. NULL,
  138701. &_vq_auxt__16u0__p4_0,
  138702. NULL,
  138703. 0
  138704. };
  138705. static long _vq_quantlist__16u0__p5_0[] = {
  138706. 4,
  138707. 3,
  138708. 5,
  138709. 2,
  138710. 6,
  138711. 1,
  138712. 7,
  138713. 0,
  138714. 8,
  138715. };
  138716. static long _vq_lengthlist__16u0__p5_0[] = {
  138717. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  138718. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  138719. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,11, 7, 8, 8,
  138720. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  138721. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,10,11,11,12,
  138722. 12,
  138723. };
  138724. static float _vq_quantthresh__16u0__p5_0[] = {
  138725. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  138726. };
  138727. static long _vq_quantmap__16u0__p5_0[] = {
  138728. 7, 5, 3, 1, 0, 2, 4, 6,
  138729. 8,
  138730. };
  138731. static encode_aux_threshmatch _vq_auxt__16u0__p5_0 = {
  138732. _vq_quantthresh__16u0__p5_0,
  138733. _vq_quantmap__16u0__p5_0,
  138734. 9,
  138735. 9
  138736. };
  138737. static static_codebook _16u0__p5_0 = {
  138738. 2, 81,
  138739. _vq_lengthlist__16u0__p5_0,
  138740. 1, -531628032, 1611661312, 4, 0,
  138741. _vq_quantlist__16u0__p5_0,
  138742. NULL,
  138743. &_vq_auxt__16u0__p5_0,
  138744. NULL,
  138745. 0
  138746. };
  138747. static long _vq_quantlist__16u0__p6_0[] = {
  138748. 6,
  138749. 5,
  138750. 7,
  138751. 4,
  138752. 8,
  138753. 3,
  138754. 9,
  138755. 2,
  138756. 10,
  138757. 1,
  138758. 11,
  138759. 0,
  138760. 12,
  138761. };
  138762. static long _vq_lengthlist__16u0__p6_0[] = {
  138763. 1, 4, 4, 7, 7,10,10,12,12,13,13,18,17, 3, 6, 6,
  138764. 9, 9,11,11,13,13,14,14,18,17, 3, 6, 6, 9, 9,11,
  138765. 11,13,13,14,14,17,18, 7, 9, 9,11,11,13,13,14,14,
  138766. 15,15, 0, 0, 7, 9, 9,11,11,13,13,14,14,15,16,19,
  138767. 18,10,11,11,13,13,14,14,16,15,17,18, 0, 0,10,11,
  138768. 11,13,13,14,14,15,15,16,18, 0, 0,11,13,13,14,14,
  138769. 15,15,17,17, 0,19, 0, 0,11,13,13,14,14,14,15,16,
  138770. 18, 0,19, 0, 0,13,14,14,15,15,18,17,18,18, 0,19,
  138771. 0, 0,13,14,14,15,16,16,16,18,18,19, 0, 0, 0,16,
  138772. 17,17, 0,17,19,19, 0,19, 0, 0, 0, 0,16,19,16,17,
  138773. 18, 0,19, 0, 0, 0, 0, 0, 0,
  138774. };
  138775. static float _vq_quantthresh__16u0__p6_0[] = {
  138776. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  138777. 12.5, 17.5, 22.5, 27.5,
  138778. };
  138779. static long _vq_quantmap__16u0__p6_0[] = {
  138780. 11, 9, 7, 5, 3, 1, 0, 2,
  138781. 4, 6, 8, 10, 12,
  138782. };
  138783. static encode_aux_threshmatch _vq_auxt__16u0__p6_0 = {
  138784. _vq_quantthresh__16u0__p6_0,
  138785. _vq_quantmap__16u0__p6_0,
  138786. 13,
  138787. 13
  138788. };
  138789. static static_codebook _16u0__p6_0 = {
  138790. 2, 169,
  138791. _vq_lengthlist__16u0__p6_0,
  138792. 1, -526516224, 1616117760, 4, 0,
  138793. _vq_quantlist__16u0__p6_0,
  138794. NULL,
  138795. &_vq_auxt__16u0__p6_0,
  138796. NULL,
  138797. 0
  138798. };
  138799. static long _vq_quantlist__16u0__p6_1[] = {
  138800. 2,
  138801. 1,
  138802. 3,
  138803. 0,
  138804. 4,
  138805. };
  138806. static long _vq_lengthlist__16u0__p6_1[] = {
  138807. 1, 4, 5, 6, 6, 4, 6, 6, 6, 6, 4, 6, 6, 6, 6, 6,
  138808. 6, 6, 7, 7, 6, 6, 6, 7, 7,
  138809. };
  138810. static float _vq_quantthresh__16u0__p6_1[] = {
  138811. -1.5, -0.5, 0.5, 1.5,
  138812. };
  138813. static long _vq_quantmap__16u0__p6_1[] = {
  138814. 3, 1, 0, 2, 4,
  138815. };
  138816. static encode_aux_threshmatch _vq_auxt__16u0__p6_1 = {
  138817. _vq_quantthresh__16u0__p6_1,
  138818. _vq_quantmap__16u0__p6_1,
  138819. 5,
  138820. 5
  138821. };
  138822. static static_codebook _16u0__p6_1 = {
  138823. 2, 25,
  138824. _vq_lengthlist__16u0__p6_1,
  138825. 1, -533725184, 1611661312, 3, 0,
  138826. _vq_quantlist__16u0__p6_1,
  138827. NULL,
  138828. &_vq_auxt__16u0__p6_1,
  138829. NULL,
  138830. 0
  138831. };
  138832. static long _vq_quantlist__16u0__p7_0[] = {
  138833. 1,
  138834. 0,
  138835. 2,
  138836. };
  138837. static long _vq_lengthlist__16u0__p7_0[] = {
  138838. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  138839. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  138840. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  138841. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  138842. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  138843. 7,
  138844. };
  138845. static float _vq_quantthresh__16u0__p7_0[] = {
  138846. -157.5, 157.5,
  138847. };
  138848. static long _vq_quantmap__16u0__p7_0[] = {
  138849. 1, 0, 2,
  138850. };
  138851. static encode_aux_threshmatch _vq_auxt__16u0__p7_0 = {
  138852. _vq_quantthresh__16u0__p7_0,
  138853. _vq_quantmap__16u0__p7_0,
  138854. 3,
  138855. 3
  138856. };
  138857. static static_codebook _16u0__p7_0 = {
  138858. 4, 81,
  138859. _vq_lengthlist__16u0__p7_0,
  138860. 1, -518803456, 1628680192, 2, 0,
  138861. _vq_quantlist__16u0__p7_0,
  138862. NULL,
  138863. &_vq_auxt__16u0__p7_0,
  138864. NULL,
  138865. 0
  138866. };
  138867. static long _vq_quantlist__16u0__p7_1[] = {
  138868. 7,
  138869. 6,
  138870. 8,
  138871. 5,
  138872. 9,
  138873. 4,
  138874. 10,
  138875. 3,
  138876. 11,
  138877. 2,
  138878. 12,
  138879. 1,
  138880. 13,
  138881. 0,
  138882. 14,
  138883. };
  138884. static long _vq_lengthlist__16u0__p7_1[] = {
  138885. 1, 5, 5, 6, 5, 9,10,11,11,10,10,10,10,10,10, 5,
  138886. 8, 8, 8,10,10,10,10,10,10,10,10,10,10,10, 5, 8,
  138887. 9, 9, 9,10,10,10,10,10,10,10,10,10,10, 5,10, 8,
  138888. 10,10,10,10,10,10,10,10,10,10,10,10, 4, 8, 9,10,
  138889. 10,10,10,10,10,10,10,10,10,10,10, 9,10,10,10,10,
  138890. 10,10,10,10,10,10,10,10,10,10, 9,10,10,10,10,10,
  138891. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138892. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138893. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138894. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138895. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138896. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138897. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138898. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138899. 10,
  138900. };
  138901. static float _vq_quantthresh__16u0__p7_1[] = {
  138902. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  138903. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  138904. };
  138905. static long _vq_quantmap__16u0__p7_1[] = {
  138906. 13, 11, 9, 7, 5, 3, 1, 0,
  138907. 2, 4, 6, 8, 10, 12, 14,
  138908. };
  138909. static encode_aux_threshmatch _vq_auxt__16u0__p7_1 = {
  138910. _vq_quantthresh__16u0__p7_1,
  138911. _vq_quantmap__16u0__p7_1,
  138912. 15,
  138913. 15
  138914. };
  138915. static static_codebook _16u0__p7_1 = {
  138916. 2, 225,
  138917. _vq_lengthlist__16u0__p7_1,
  138918. 1, -520986624, 1620377600, 4, 0,
  138919. _vq_quantlist__16u0__p7_1,
  138920. NULL,
  138921. &_vq_auxt__16u0__p7_1,
  138922. NULL,
  138923. 0
  138924. };
  138925. static long _vq_quantlist__16u0__p7_2[] = {
  138926. 10,
  138927. 9,
  138928. 11,
  138929. 8,
  138930. 12,
  138931. 7,
  138932. 13,
  138933. 6,
  138934. 14,
  138935. 5,
  138936. 15,
  138937. 4,
  138938. 16,
  138939. 3,
  138940. 17,
  138941. 2,
  138942. 18,
  138943. 1,
  138944. 19,
  138945. 0,
  138946. 20,
  138947. };
  138948. static long _vq_lengthlist__16u0__p7_2[] = {
  138949. 1, 6, 6, 7, 8, 7, 7,10, 9,10, 9,11,10, 9,11,10,
  138950. 9, 9, 9, 9,10, 6, 8, 7, 9, 9, 8, 8,10,10, 9,11,
  138951. 11,12,12,10, 9,11, 9,12,10, 9, 6, 9, 8, 9,12, 8,
  138952. 8,11, 9,11,11,12,11,12,12,10,11,11,10,10,11, 7,
  138953. 10, 9, 9, 9, 9, 9,10, 9,10, 9,10,10,12,10,10,10,
  138954. 11,12,10,10, 7, 9, 9, 9,10, 9, 9,10,10, 9, 9, 9,
  138955. 11,11,10,10,10,10, 9, 9,12, 7, 9,10, 9,11, 9,10,
  138956. 9,10,11,11,11,10,11,12, 9,12,11,10,10,10, 7, 9,
  138957. 9, 9, 9,10,12,10, 9,11,12,10,11,12,12,11, 9,10,
  138958. 11,10,11, 7, 9,10,10,11,10, 9,10,11,11,11,10,12,
  138959. 12,12,11,11,10,11,11,12, 8, 9,10,12,11,10,10,12,
  138960. 12,12,12,12,10,11,11, 9,11,10,12,11,11, 8, 9,10,
  138961. 10,11,12,11,11,10,10,10,12,12,12, 9,10,12,12,12,
  138962. 12,12, 8,10,11,10,10,12, 9,11,12,12,11,12,12,12,
  138963. 12,10,12,10,10,10,10, 8,12,11,11,11,10,10,11,12,
  138964. 12,12,12,11,12,12,12,11,11,11,12,10, 9,10,10,12,
  138965. 10,12,10,12,12,10,10,10,11,12,12,12,11,12,12,12,
  138966. 11,10,11,12,12,12,11,12,12,11,12,12,11,12,12,12,
  138967. 12,11,12,12,10,10,10,10,11,11,12,11,12,12,12,12,
  138968. 12,12,12,11,12,11,10,11,11,12,11,11, 9,10,10,10,
  138969. 12,10,10,11, 9,11,12,11,12,11,12,12,10,11,10,12,
  138970. 9, 9, 9,12,11,10,11,10,12,10,12,10,12,12,12,11,
  138971. 11,11,11,11,10, 9,10,10,11,10,11,11,12,11,10,11,
  138972. 12,12,12,11,11, 9,12,10,12, 9,10,12,10,10,11,10,
  138973. 11,11,12,11,10,11,10,11,11,11,11,12,11,11,10, 9,
  138974. 10,10,10, 9,11,11,10, 9,12,10,11,12,11,12,12,11,
  138975. 12,11,12,11,10,11,10,12,11,12,11,12,11,12,10,11,
  138976. 10,10,12,11,10,11,11,11,10,
  138977. };
  138978. static float _vq_quantthresh__16u0__p7_2[] = {
  138979. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  138980. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  138981. 6.5, 7.5, 8.5, 9.5,
  138982. };
  138983. static long _vq_quantmap__16u0__p7_2[] = {
  138984. 19, 17, 15, 13, 11, 9, 7, 5,
  138985. 3, 1, 0, 2, 4, 6, 8, 10,
  138986. 12, 14, 16, 18, 20,
  138987. };
  138988. static encode_aux_threshmatch _vq_auxt__16u0__p7_2 = {
  138989. _vq_quantthresh__16u0__p7_2,
  138990. _vq_quantmap__16u0__p7_2,
  138991. 21,
  138992. 21
  138993. };
  138994. static static_codebook _16u0__p7_2 = {
  138995. 2, 441,
  138996. _vq_lengthlist__16u0__p7_2,
  138997. 1, -529268736, 1611661312, 5, 0,
  138998. _vq_quantlist__16u0__p7_2,
  138999. NULL,
  139000. &_vq_auxt__16u0__p7_2,
  139001. NULL,
  139002. 0
  139003. };
  139004. static long _huff_lengthlist__16u0__single[] = {
  139005. 3, 5, 8, 7,14, 8, 9,19, 5, 2, 5, 5, 9, 6, 9,19,
  139006. 8, 4, 5, 7, 8, 9,13,19, 7, 4, 6, 5, 9, 6, 9,19,
  139007. 12, 8, 7, 9,10,11,13,19, 8, 5, 8, 6, 9, 6, 7,19,
  139008. 8, 8,10, 7, 7, 4, 5,19,12,17,19,15,18,13,11,18,
  139009. };
  139010. static static_codebook _huff_book__16u0__single = {
  139011. 2, 64,
  139012. _huff_lengthlist__16u0__single,
  139013. 0, 0, 0, 0, 0,
  139014. NULL,
  139015. NULL,
  139016. NULL,
  139017. NULL,
  139018. 0
  139019. };
  139020. static long _huff_lengthlist__16u1__long[] = {
  139021. 3, 6,10, 8,12, 8,14, 8,14,19, 5, 3, 5, 5, 7, 6,
  139022. 11, 7,16,19, 7, 5, 6, 7, 7, 9,11,12,19,19, 6, 4,
  139023. 7, 5, 7, 6,10, 7,18,18, 8, 6, 7, 7, 7, 7, 8, 9,
  139024. 18,18, 7, 5, 8, 5, 7, 5, 8, 6,18,18,12, 9,10, 9,
  139025. 9, 9, 8, 9,18,18, 8, 7,10, 6, 8, 5, 6, 4,11,18,
  139026. 11,15,16,12,11, 8, 8, 6, 9,18,14,18,18,18,16,16,
  139027. 16,13,16,18,
  139028. };
  139029. static static_codebook _huff_book__16u1__long = {
  139030. 2, 100,
  139031. _huff_lengthlist__16u1__long,
  139032. 0, 0, 0, 0, 0,
  139033. NULL,
  139034. NULL,
  139035. NULL,
  139036. NULL,
  139037. 0
  139038. };
  139039. static long _vq_quantlist__16u1__p1_0[] = {
  139040. 1,
  139041. 0,
  139042. 2,
  139043. };
  139044. static long _vq_lengthlist__16u1__p1_0[] = {
  139045. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 7, 7,10,10, 7,
  139046. 9,10, 5, 7, 8, 7,10, 9, 7,10,10, 5, 8, 8, 8,10,
  139047. 10, 8,10,10, 7,10,10,10,11,12,10,12,13, 7,10,10,
  139048. 9,13,11,10,12,13, 5, 8, 8, 8,10,10, 8,10,10, 7,
  139049. 10,10,10,12,12, 9,11,12, 7,10,11,10,12,12,10,13,
  139050. 11,
  139051. };
  139052. static float _vq_quantthresh__16u1__p1_0[] = {
  139053. -0.5, 0.5,
  139054. };
  139055. static long _vq_quantmap__16u1__p1_0[] = {
  139056. 1, 0, 2,
  139057. };
  139058. static encode_aux_threshmatch _vq_auxt__16u1__p1_0 = {
  139059. _vq_quantthresh__16u1__p1_0,
  139060. _vq_quantmap__16u1__p1_0,
  139061. 3,
  139062. 3
  139063. };
  139064. static static_codebook _16u1__p1_0 = {
  139065. 4, 81,
  139066. _vq_lengthlist__16u1__p1_0,
  139067. 1, -535822336, 1611661312, 2, 0,
  139068. _vq_quantlist__16u1__p1_0,
  139069. NULL,
  139070. &_vq_auxt__16u1__p1_0,
  139071. NULL,
  139072. 0
  139073. };
  139074. static long _vq_quantlist__16u1__p2_0[] = {
  139075. 1,
  139076. 0,
  139077. 2,
  139078. };
  139079. static long _vq_lengthlist__16u1__p2_0[] = {
  139080. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 7, 8, 6,
  139081. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 7, 5, 6, 6, 6, 8,
  139082. 8, 6, 8, 8, 6, 8, 8, 7, 7,10, 8, 9, 9, 6, 8, 8,
  139083. 7, 9, 8, 8, 9,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  139084. 8, 8, 8,10, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 7,10,
  139085. 8,
  139086. };
  139087. static float _vq_quantthresh__16u1__p2_0[] = {
  139088. -0.5, 0.5,
  139089. };
  139090. static long _vq_quantmap__16u1__p2_0[] = {
  139091. 1, 0, 2,
  139092. };
  139093. static encode_aux_threshmatch _vq_auxt__16u1__p2_0 = {
  139094. _vq_quantthresh__16u1__p2_0,
  139095. _vq_quantmap__16u1__p2_0,
  139096. 3,
  139097. 3
  139098. };
  139099. static static_codebook _16u1__p2_0 = {
  139100. 4, 81,
  139101. _vq_lengthlist__16u1__p2_0,
  139102. 1, -535822336, 1611661312, 2, 0,
  139103. _vq_quantlist__16u1__p2_0,
  139104. NULL,
  139105. &_vq_auxt__16u1__p2_0,
  139106. NULL,
  139107. 0
  139108. };
  139109. static long _vq_quantlist__16u1__p3_0[] = {
  139110. 2,
  139111. 1,
  139112. 3,
  139113. 0,
  139114. 4,
  139115. };
  139116. static long _vq_lengthlist__16u1__p3_0[] = {
  139117. 1, 5, 5, 8, 8, 6, 7, 7, 9, 9, 5, 7, 7, 9, 9, 9,
  139118. 10, 9,11,11, 9, 9,10,11,11, 6, 8, 8,10,10, 8, 9,
  139119. 10,11,11, 8, 9,10,11,11,10,11,11,12,13,10,11,11,
  139120. 13,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10, 9,11,
  139121. 11,10,11,11,13,13,10,11,11,13,12, 9,11,11,14,13,
  139122. 10,12,12,15,14,10,12,11,14,13,12,13,13,15,15,12,
  139123. 13,13,16,14, 9,11,11,13,14,10,11,12,14,14,10,12,
  139124. 12,14,15,12,13,13,14,15,12,13,14,15,16, 5, 8, 8,
  139125. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  139126. 14,11,12,12,14,14, 8,10,10,12,12, 9,11,12,12,13,
  139127. 10,12,12,13,13,12,12,13,14,15,11,13,13,15,15, 7,
  139128. 10,10,12,12, 9,12,11,13,12,10,11,12,13,13,12,13,
  139129. 12,15,14,11,12,13,15,15,10,12,12,15,14,11,13,13,
  139130. 16,15,11,13,13,16,15,14,13,14,15,16,13,15,15,17,
  139131. 17,10,12,12,14,15,11,12,12,15,15,11,13,13,15,16,
  139132. 13,15,13,16,15,13,15,15,16,17, 5, 8, 8,11,11, 8,
  139133. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  139134. 12,14,14, 7,10,10,12,12,10,12,12,14,13, 9,11,12,
  139135. 12,13,12,13,13,15,15,12,12,13,13,15, 7,10,10,12,
  139136. 13,10,11,12,13,13,10,12,11,13,13,11,13,13,15,15,
  139137. 12,13,12,15,14, 9,12,12,15,14,11,13,13,15,15,11,
  139138. 12,13,15,15,13,14,14,17,19,13,13,14,16,16,10,12,
  139139. 12,14,15,11,13,13,15,16,11,13,12,16,15,13,15,15,
  139140. 17,18,14,15,13,16,15, 8,11,11,15,14,10,12,12,16,
  139141. 15,10,12,12,16,16,14,15,15,18,17,13,14,15,16,18,
  139142. 9,12,12,15,15,11,12,14,16,17,11,13,13,16,15,15,
  139143. 15,15,17,18,14,15,16,17,17, 9,12,12,15,15,11,14,
  139144. 13,16,16,11,13,13,16,16,15,16,15,17,18,14,16,15,
  139145. 17,16,12,14,14,17,16,12,14,15,18,17,13,15,15,17,
  139146. 17,15,15,18,16,20,15,16,17,18,18,11,14,14,16,17,
  139147. 13,15,14,18,17,13,15,15,17,17,15,17,15,18,17,15,
  139148. 17,16,19,18, 8,11,11,14,15,10,12,12,15,15,10,12,
  139149. 12,16,16,13,14,14,17,16,14,15,15,17,17, 9,12,12,
  139150. 15,16,11,13,13,16,16,11,12,13,16,16,14,16,15,20,
  139151. 17,14,16,16,17,17, 9,12,12,15,16,11,13,13,16,17,
  139152. 11,13,13,17,16,14,15,15,17,18,15,15,15,18,18,11,
  139153. 14,14,17,16,13,15,15,17,17,13,14,14,18,17,15,16,
  139154. 16,18,19,15,15,17,17,19,11,14,14,16,17,13,15,14,
  139155. 17,19,13,15,14,18,17,15,17,16,18,18,15,17,15,18,
  139156. 16,
  139157. };
  139158. static float _vq_quantthresh__16u1__p3_0[] = {
  139159. -1.5, -0.5, 0.5, 1.5,
  139160. };
  139161. static long _vq_quantmap__16u1__p3_0[] = {
  139162. 3, 1, 0, 2, 4,
  139163. };
  139164. static encode_aux_threshmatch _vq_auxt__16u1__p3_0 = {
  139165. _vq_quantthresh__16u1__p3_0,
  139166. _vq_quantmap__16u1__p3_0,
  139167. 5,
  139168. 5
  139169. };
  139170. static static_codebook _16u1__p3_0 = {
  139171. 4, 625,
  139172. _vq_lengthlist__16u1__p3_0,
  139173. 1, -533725184, 1611661312, 3, 0,
  139174. _vq_quantlist__16u1__p3_0,
  139175. NULL,
  139176. &_vq_auxt__16u1__p3_0,
  139177. NULL,
  139178. 0
  139179. };
  139180. static long _vq_quantlist__16u1__p4_0[] = {
  139181. 2,
  139182. 1,
  139183. 3,
  139184. 0,
  139185. 4,
  139186. };
  139187. static long _vq_lengthlist__16u1__p4_0[] = {
  139188. 4, 5, 5, 8, 8, 6, 6, 7, 9, 9, 6, 6, 6, 9, 9, 9,
  139189. 10, 9,11,11, 9, 9,10,11,11, 6, 7, 7,10, 9, 7, 7,
  139190. 8, 9,10, 7, 7, 8,10,10,10,10,10,10,12, 9, 9,10,
  139191. 11,12, 6, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 7,10,
  139192. 10, 9,10, 9,12,11,10,10, 9,12,10, 9,10,10,12,11,
  139193. 10,10,10,12,12, 9,10,10,12,12,12,11,12,13,13,11,
  139194. 11,12,12,13, 9,10,10,11,12, 9,10,10,12,12,10,10,
  139195. 10,12,12,11,12,11,14,13,11,12,12,14,13, 5, 7, 7,
  139196. 10,10, 7, 8, 8,10,10, 7, 8, 7,10,10,10,10,10,12,
  139197. 12,10,10,10,12,12, 6, 8, 7,10,10, 7, 7, 9,10,11,
  139198. 8, 9, 9,11,10,10,10,11,11,13,10,10,11,12,13, 6,
  139199. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,10,11,10,11,
  139200. 10,13,11,10,11,10,12,12,10,11,10,12,11,10,10,10,
  139201. 12,13,10,11,11,13,12,11,11,13,11,14,12,12,13,14,
  139202. 14, 9,10,10,12,13,10,11,10,13,12,10,11,11,12,13,
  139203. 11,12,11,14,12,12,13,13,15,14, 5, 7, 7,10,10, 7,
  139204. 7, 8,10,10, 7, 8, 8,10,10,10,10,10,11,12,10,10,
  139205. 10,12,12, 7, 8, 8,10,10, 8, 9, 8,11,10, 7, 8, 9,
  139206. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 7, 8,10,
  139207. 10, 8, 8, 9,10,11, 7, 9, 7,11,10,10,11,11,13,12,
  139208. 11,11,10,13,11, 9,10,10,12,12,10,11,11,13,12,10,
  139209. 10,11,12,12,12,13,13,14,14,11,11,12,12,14,10,10,
  139210. 11,12,12,10,11,11,12,13,10,10,10,13,12,12,13,13,
  139211. 15,14,12,13,10,14,11, 8,10,10,12,12,10,11,10,13,
  139212. 13, 9,10,10,12,12,12,13,13,15,14,11,12,12,13,13,
  139213. 9,10,10,13,12,10,10,11,13,13,10,11,10,13,12,12,
  139214. 12,13,14,15,12,13,12,15,13, 9,10,10,12,13,10,11,
  139215. 10,13,12,10,10,11,12,13,12,14,12,15,13,12,12,13,
  139216. 14,15,11,12,11,14,13,11,11,12,14,15,12,13,12,15,
  139217. 14,13,11,15,11,16,13,14,14,16,15,11,12,12,14,14,
  139218. 11,12,11,14,13,12,12,13,14,15,13,14,12,16,12,14,
  139219. 14,14,15,15, 8,10,10,12,12, 9,10,10,12,12,10,10,
  139220. 11,13,13,11,12,12,13,13,12,13,13,14,15, 9,10,10,
  139221. 13,12,10,11,11,13,12,10,10,11,13,13,12,13,12,15,
  139222. 14,12,12,13,13,16, 9, 9,10,12,13,10,10,11,12,13,
  139223. 10,11,10,13,13,12,12,13,13,15,13,13,12,15,13,11,
  139224. 12,12,14,14,12,13,12,15,14,11,11,12,13,14,14,14,
  139225. 14,16,15,13,12,15,12,16,11,11,12,13,14,12,13,13,
  139226. 14,15,10,12,11,14,13,14,15,14,16,16,13,14,11,15,
  139227. 11,
  139228. };
  139229. static float _vq_quantthresh__16u1__p4_0[] = {
  139230. -1.5, -0.5, 0.5, 1.5,
  139231. };
  139232. static long _vq_quantmap__16u1__p4_0[] = {
  139233. 3, 1, 0, 2, 4,
  139234. };
  139235. static encode_aux_threshmatch _vq_auxt__16u1__p4_0 = {
  139236. _vq_quantthresh__16u1__p4_0,
  139237. _vq_quantmap__16u1__p4_0,
  139238. 5,
  139239. 5
  139240. };
  139241. static static_codebook _16u1__p4_0 = {
  139242. 4, 625,
  139243. _vq_lengthlist__16u1__p4_0,
  139244. 1, -533725184, 1611661312, 3, 0,
  139245. _vq_quantlist__16u1__p4_0,
  139246. NULL,
  139247. &_vq_auxt__16u1__p4_0,
  139248. NULL,
  139249. 0
  139250. };
  139251. static long _vq_quantlist__16u1__p5_0[] = {
  139252. 4,
  139253. 3,
  139254. 5,
  139255. 2,
  139256. 6,
  139257. 1,
  139258. 7,
  139259. 0,
  139260. 8,
  139261. };
  139262. static long _vq_lengthlist__16u1__p5_0[] = {
  139263. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  139264. 10,10, 4, 5, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  139265. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 7, 8, 8,
  139266. 10, 9,11,11,12,11, 7, 8, 8, 9, 9,11,11,12,12, 9,
  139267. 10,10,11,11,12,12,13,12, 9,10,10,11,11,12,12,12,
  139268. 13,
  139269. };
  139270. static float _vq_quantthresh__16u1__p5_0[] = {
  139271. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  139272. };
  139273. static long _vq_quantmap__16u1__p5_0[] = {
  139274. 7, 5, 3, 1, 0, 2, 4, 6,
  139275. 8,
  139276. };
  139277. static encode_aux_threshmatch _vq_auxt__16u1__p5_0 = {
  139278. _vq_quantthresh__16u1__p5_0,
  139279. _vq_quantmap__16u1__p5_0,
  139280. 9,
  139281. 9
  139282. };
  139283. static static_codebook _16u1__p5_0 = {
  139284. 2, 81,
  139285. _vq_lengthlist__16u1__p5_0,
  139286. 1, -531628032, 1611661312, 4, 0,
  139287. _vq_quantlist__16u1__p5_0,
  139288. NULL,
  139289. &_vq_auxt__16u1__p5_0,
  139290. NULL,
  139291. 0
  139292. };
  139293. static long _vq_quantlist__16u1__p6_0[] = {
  139294. 4,
  139295. 3,
  139296. 5,
  139297. 2,
  139298. 6,
  139299. 1,
  139300. 7,
  139301. 0,
  139302. 8,
  139303. };
  139304. static long _vq_lengthlist__16u1__p6_0[] = {
  139305. 3, 4, 4, 6, 6, 7, 7, 9, 9, 4, 4, 4, 6, 6, 8, 8,
  139306. 9, 9, 4, 4, 4, 6, 6, 7, 7, 9, 9, 6, 6, 6, 7, 7,
  139307. 8, 8,10, 9, 6, 6, 6, 7, 7, 8, 8, 9,10, 7, 8, 7,
  139308. 8, 8, 9, 9,10,10, 7, 8, 8, 8, 8, 9, 9,10,10, 9,
  139309. 9, 9,10,10,10,10,11,11, 9, 9, 9,10,10,10,10,11,
  139310. 11,
  139311. };
  139312. static float _vq_quantthresh__16u1__p6_0[] = {
  139313. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  139314. };
  139315. static long _vq_quantmap__16u1__p6_0[] = {
  139316. 7, 5, 3, 1, 0, 2, 4, 6,
  139317. 8,
  139318. };
  139319. static encode_aux_threshmatch _vq_auxt__16u1__p6_0 = {
  139320. _vq_quantthresh__16u1__p6_0,
  139321. _vq_quantmap__16u1__p6_0,
  139322. 9,
  139323. 9
  139324. };
  139325. static static_codebook _16u1__p6_0 = {
  139326. 2, 81,
  139327. _vq_lengthlist__16u1__p6_0,
  139328. 1, -531628032, 1611661312, 4, 0,
  139329. _vq_quantlist__16u1__p6_0,
  139330. NULL,
  139331. &_vq_auxt__16u1__p6_0,
  139332. NULL,
  139333. 0
  139334. };
  139335. static long _vq_quantlist__16u1__p7_0[] = {
  139336. 1,
  139337. 0,
  139338. 2,
  139339. };
  139340. static long _vq_lengthlist__16u1__p7_0[] = {
  139341. 1, 4, 4, 4, 8, 8, 4, 8, 8, 5,11, 9, 8,12,11, 8,
  139342. 12,11, 5,10,11, 8,11,12, 8,11,12, 4,11,11,11,14,
  139343. 13,10,13,13, 8,14,13,12,14,16,12,16,15, 8,14,14,
  139344. 13,16,14,12,15,16, 4,11,11,10,14,13,11,14,14, 8,
  139345. 15,14,12,15,15,12,14,16, 8,14,14,11,16,15,12,15,
  139346. 13,
  139347. };
  139348. static float _vq_quantthresh__16u1__p7_0[] = {
  139349. -5.5, 5.5,
  139350. };
  139351. static long _vq_quantmap__16u1__p7_0[] = {
  139352. 1, 0, 2,
  139353. };
  139354. static encode_aux_threshmatch _vq_auxt__16u1__p7_0 = {
  139355. _vq_quantthresh__16u1__p7_0,
  139356. _vq_quantmap__16u1__p7_0,
  139357. 3,
  139358. 3
  139359. };
  139360. static static_codebook _16u1__p7_0 = {
  139361. 4, 81,
  139362. _vq_lengthlist__16u1__p7_0,
  139363. 1, -529137664, 1618345984, 2, 0,
  139364. _vq_quantlist__16u1__p7_0,
  139365. NULL,
  139366. &_vq_auxt__16u1__p7_0,
  139367. NULL,
  139368. 0
  139369. };
  139370. static long _vq_quantlist__16u1__p7_1[] = {
  139371. 5,
  139372. 4,
  139373. 6,
  139374. 3,
  139375. 7,
  139376. 2,
  139377. 8,
  139378. 1,
  139379. 9,
  139380. 0,
  139381. 10,
  139382. };
  139383. static long _vq_lengthlist__16u1__p7_1[] = {
  139384. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 6, 5, 7, 7,
  139385. 8, 8, 8, 8, 8, 8, 4, 5, 6, 7, 7, 8, 8, 8, 8, 8,
  139386. 8, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  139387. 8, 8, 8, 9, 9, 9, 9, 7, 8, 8, 8, 8, 9, 9, 9,10,
  139388. 9,10, 7, 8, 8, 8, 8, 9, 9, 9, 9,10, 9, 8, 8, 8,
  139389. 9, 9,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9,10,
  139390. 10,10,10, 8, 8, 8, 9, 9, 9,10,10,10,10,10, 8, 8,
  139391. 8, 9, 9,10,10,10,10,10,10,
  139392. };
  139393. static float _vq_quantthresh__16u1__p7_1[] = {
  139394. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  139395. 3.5, 4.5,
  139396. };
  139397. static long _vq_quantmap__16u1__p7_1[] = {
  139398. 9, 7, 5, 3, 1, 0, 2, 4,
  139399. 6, 8, 10,
  139400. };
  139401. static encode_aux_threshmatch _vq_auxt__16u1__p7_1 = {
  139402. _vq_quantthresh__16u1__p7_1,
  139403. _vq_quantmap__16u1__p7_1,
  139404. 11,
  139405. 11
  139406. };
  139407. static static_codebook _16u1__p7_1 = {
  139408. 2, 121,
  139409. _vq_lengthlist__16u1__p7_1,
  139410. 1, -531365888, 1611661312, 4, 0,
  139411. _vq_quantlist__16u1__p7_1,
  139412. NULL,
  139413. &_vq_auxt__16u1__p7_1,
  139414. NULL,
  139415. 0
  139416. };
  139417. static long _vq_quantlist__16u1__p8_0[] = {
  139418. 5,
  139419. 4,
  139420. 6,
  139421. 3,
  139422. 7,
  139423. 2,
  139424. 8,
  139425. 1,
  139426. 9,
  139427. 0,
  139428. 10,
  139429. };
  139430. static long _vq_lengthlist__16u1__p8_0[] = {
  139431. 1, 4, 4, 5, 5, 8, 8,10,10,12,12, 4, 7, 7, 8, 8,
  139432. 9, 9,12,11,14,13, 4, 7, 7, 7, 8, 9,10,11,11,13,
  139433. 12, 5, 8, 8, 9, 9,11,11,12,13,15,14, 5, 7, 8, 9,
  139434. 9,11,11,13,13,17,15, 8, 9,10,11,11,12,13,17,14,
  139435. 17,16, 8,10, 9,11,11,12,12,13,15,15,17,10,11,11,
  139436. 12,13,14,15,15,16,16,17, 9,11,11,12,12,14,15,17,
  139437. 15,15,16,11,14,12,14,15,16,15,16,16,16,15,11,13,
  139438. 13,14,14,15,15,16,16,15,16,
  139439. };
  139440. static float _vq_quantthresh__16u1__p8_0[] = {
  139441. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  139442. 38.5, 49.5,
  139443. };
  139444. static long _vq_quantmap__16u1__p8_0[] = {
  139445. 9, 7, 5, 3, 1, 0, 2, 4,
  139446. 6, 8, 10,
  139447. };
  139448. static encode_aux_threshmatch _vq_auxt__16u1__p8_0 = {
  139449. _vq_quantthresh__16u1__p8_0,
  139450. _vq_quantmap__16u1__p8_0,
  139451. 11,
  139452. 11
  139453. };
  139454. static static_codebook _16u1__p8_0 = {
  139455. 2, 121,
  139456. _vq_lengthlist__16u1__p8_0,
  139457. 1, -524582912, 1618345984, 4, 0,
  139458. _vq_quantlist__16u1__p8_0,
  139459. NULL,
  139460. &_vq_auxt__16u1__p8_0,
  139461. NULL,
  139462. 0
  139463. };
  139464. static long _vq_quantlist__16u1__p8_1[] = {
  139465. 5,
  139466. 4,
  139467. 6,
  139468. 3,
  139469. 7,
  139470. 2,
  139471. 8,
  139472. 1,
  139473. 9,
  139474. 0,
  139475. 10,
  139476. };
  139477. static long _vq_lengthlist__16u1__p8_1[] = {
  139478. 2, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 4, 6, 6, 7, 7,
  139479. 8, 7, 8, 8, 8, 8, 4, 6, 6, 7, 7, 7, 7, 8, 8, 8,
  139480. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 9, 6, 7, 7, 7,
  139481. 7, 8, 8, 8, 8, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9,
  139482. 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  139483. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  139484. 9, 9, 9, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  139485. 8, 9, 9, 9, 9, 9, 9, 9, 9,
  139486. };
  139487. static float _vq_quantthresh__16u1__p8_1[] = {
  139488. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  139489. 3.5, 4.5,
  139490. };
  139491. static long _vq_quantmap__16u1__p8_1[] = {
  139492. 9, 7, 5, 3, 1, 0, 2, 4,
  139493. 6, 8, 10,
  139494. };
  139495. static encode_aux_threshmatch _vq_auxt__16u1__p8_1 = {
  139496. _vq_quantthresh__16u1__p8_1,
  139497. _vq_quantmap__16u1__p8_1,
  139498. 11,
  139499. 11
  139500. };
  139501. static static_codebook _16u1__p8_1 = {
  139502. 2, 121,
  139503. _vq_lengthlist__16u1__p8_1,
  139504. 1, -531365888, 1611661312, 4, 0,
  139505. _vq_quantlist__16u1__p8_1,
  139506. NULL,
  139507. &_vq_auxt__16u1__p8_1,
  139508. NULL,
  139509. 0
  139510. };
  139511. static long _vq_quantlist__16u1__p9_0[] = {
  139512. 7,
  139513. 6,
  139514. 8,
  139515. 5,
  139516. 9,
  139517. 4,
  139518. 10,
  139519. 3,
  139520. 11,
  139521. 2,
  139522. 12,
  139523. 1,
  139524. 13,
  139525. 0,
  139526. 14,
  139527. };
  139528. static long _vq_lengthlist__16u1__p9_0[] = {
  139529. 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  139530. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  139531. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  139532. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  139533. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  139534. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  139535. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  139536. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  139537. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  139538. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  139539. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  139540. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  139541. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  139542. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  139543. 8,
  139544. };
  139545. static float _vq_quantthresh__16u1__p9_0[] = {
  139546. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  139547. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  139548. };
  139549. static long _vq_quantmap__16u1__p9_0[] = {
  139550. 13, 11, 9, 7, 5, 3, 1, 0,
  139551. 2, 4, 6, 8, 10, 12, 14,
  139552. };
  139553. static encode_aux_threshmatch _vq_auxt__16u1__p9_0 = {
  139554. _vq_quantthresh__16u1__p9_0,
  139555. _vq_quantmap__16u1__p9_0,
  139556. 15,
  139557. 15
  139558. };
  139559. static static_codebook _16u1__p9_0 = {
  139560. 2, 225,
  139561. _vq_lengthlist__16u1__p9_0,
  139562. 1, -514071552, 1627381760, 4, 0,
  139563. _vq_quantlist__16u1__p9_0,
  139564. NULL,
  139565. &_vq_auxt__16u1__p9_0,
  139566. NULL,
  139567. 0
  139568. };
  139569. static long _vq_quantlist__16u1__p9_1[] = {
  139570. 7,
  139571. 6,
  139572. 8,
  139573. 5,
  139574. 9,
  139575. 4,
  139576. 10,
  139577. 3,
  139578. 11,
  139579. 2,
  139580. 12,
  139581. 1,
  139582. 13,
  139583. 0,
  139584. 14,
  139585. };
  139586. static long _vq_lengthlist__16u1__p9_1[] = {
  139587. 1, 6, 5, 9, 9,10,10, 6, 7, 9, 9,10,10,10,10, 5,
  139588. 10, 8,10, 8,10,10, 8, 8,10, 9,10,10,10,10, 5, 8,
  139589. 9,10,10,10,10, 8,10,10,10,10,10,10,10, 9,10,10,
  139590. 10,10,10,10, 9, 9,10,10,10,10,10,10, 9, 9, 8, 9,
  139591. 10,10,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  139592. 10,10,10,10,10,10,10,10,10,10,10, 8,10,10,10,10,
  139593. 10,10,10,10,10,10,10,10,10, 6, 8, 8,10,10,10, 8,
  139594. 10,10,10,10,10,10,10,10, 5, 8, 8,10,10,10, 9, 9,
  139595. 10,10,10,10,10,10,10,10, 9,10,10,10,10,10,10,10,
  139596. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  139597. 10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  139598. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  139599. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  139600. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  139601. 9,
  139602. };
  139603. static float _vq_quantthresh__16u1__p9_1[] = {
  139604. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  139605. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  139606. };
  139607. static long _vq_quantmap__16u1__p9_1[] = {
  139608. 13, 11, 9, 7, 5, 3, 1, 0,
  139609. 2, 4, 6, 8, 10, 12, 14,
  139610. };
  139611. static encode_aux_threshmatch _vq_auxt__16u1__p9_1 = {
  139612. _vq_quantthresh__16u1__p9_1,
  139613. _vq_quantmap__16u1__p9_1,
  139614. 15,
  139615. 15
  139616. };
  139617. static static_codebook _16u1__p9_1 = {
  139618. 2, 225,
  139619. _vq_lengthlist__16u1__p9_1,
  139620. 1, -522338304, 1620115456, 4, 0,
  139621. _vq_quantlist__16u1__p9_1,
  139622. NULL,
  139623. &_vq_auxt__16u1__p9_1,
  139624. NULL,
  139625. 0
  139626. };
  139627. static long _vq_quantlist__16u1__p9_2[] = {
  139628. 8,
  139629. 7,
  139630. 9,
  139631. 6,
  139632. 10,
  139633. 5,
  139634. 11,
  139635. 4,
  139636. 12,
  139637. 3,
  139638. 13,
  139639. 2,
  139640. 14,
  139641. 1,
  139642. 15,
  139643. 0,
  139644. 16,
  139645. };
  139646. static long _vq_lengthlist__16u1__p9_2[] = {
  139647. 1, 6, 6, 7, 8, 8,11,10, 9, 9,11, 9,10, 9,11,11,
  139648. 9, 6, 7, 6,11, 8,11, 9,10,10,11, 9,11,10,10,10,
  139649. 11, 9, 5, 7, 7, 8, 8,10,11, 8, 8,11, 9, 9,10,11,
  139650. 9,10,11, 8, 9, 6, 8, 8, 9, 9,10,10,11,11,11, 9,
  139651. 11,10, 9,11, 8, 8, 8, 9, 8, 9,10,11, 9, 9,11,11,
  139652. 10, 9, 9,11,10, 8,11, 8, 9, 8,11, 9,10, 9,10,11,
  139653. 11,10,10, 9,10,10, 8, 8, 9,10,10,10, 9,11, 9,10,
  139654. 11,11,11,11,10, 9,11, 9, 9,11,11,10, 8,11,11,11,
  139655. 9,10,10,11,10,11,11, 9,11,10, 9,11,10,10,10,10,
  139656. 9,11,10,11,10, 9, 9,10,11, 9, 8,10,11,11,10,10,
  139657. 11, 9,11,10,11,11,10,11, 9, 9, 8,10, 8, 9,11, 9,
  139658. 8,10,10, 9,11,10,11,10,11, 9,11, 8,10,11,11,11,
  139659. 11,10,10,11,11,11,11,10,11,11,10, 9, 8,10,10, 9,
  139660. 11,10,11,11,11, 9, 9, 9,11,11,11,10,10, 9, 9,10,
  139661. 9,11,11,11,11, 8,10,11,10,11,11,10,11,11, 9, 9,
  139662. 9,10, 9,11, 9,11,11,11,11,11,10,11,11,10,11,10,
  139663. 11,11, 9,11,10,11,10, 9,10, 9,10,10,11,11,11,11,
  139664. 9,10, 9,10,11,11,10,11,11,11,11,11,11,10,11,11,
  139665. 10,
  139666. };
  139667. static float _vq_quantthresh__16u1__p9_2[] = {
  139668. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  139669. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  139670. };
  139671. static long _vq_quantmap__16u1__p9_2[] = {
  139672. 15, 13, 11, 9, 7, 5, 3, 1,
  139673. 0, 2, 4, 6, 8, 10, 12, 14,
  139674. 16,
  139675. };
  139676. static encode_aux_threshmatch _vq_auxt__16u1__p9_2 = {
  139677. _vq_quantthresh__16u1__p9_2,
  139678. _vq_quantmap__16u1__p9_2,
  139679. 17,
  139680. 17
  139681. };
  139682. static static_codebook _16u1__p9_2 = {
  139683. 2, 289,
  139684. _vq_lengthlist__16u1__p9_2,
  139685. 1, -529530880, 1611661312, 5, 0,
  139686. _vq_quantlist__16u1__p9_2,
  139687. NULL,
  139688. &_vq_auxt__16u1__p9_2,
  139689. NULL,
  139690. 0
  139691. };
  139692. static long _huff_lengthlist__16u1__short[] = {
  139693. 5, 7,10, 9,11,10,15,11,13,16, 6, 4, 6, 6, 7, 7,
  139694. 10, 9,12,16,10, 6, 5, 6, 6, 7,10,11,16,16, 9, 6,
  139695. 7, 6, 7, 7,10, 8,14,16,11, 6, 5, 4, 5, 6, 8, 9,
  139696. 15,16, 9, 6, 6, 5, 6, 6, 9, 8,14,16,12, 7, 6, 6,
  139697. 5, 6, 6, 7,13,16, 8, 6, 7, 6, 5, 5, 4, 4,11,16,
  139698. 9, 8, 9, 9, 7, 7, 6, 5,13,16,14,14,16,15,16,15,
  139699. 16,16,16,16,
  139700. };
  139701. static static_codebook _huff_book__16u1__short = {
  139702. 2, 100,
  139703. _huff_lengthlist__16u1__short,
  139704. 0, 0, 0, 0, 0,
  139705. NULL,
  139706. NULL,
  139707. NULL,
  139708. NULL,
  139709. 0
  139710. };
  139711. static long _huff_lengthlist__16u2__long[] = {
  139712. 5, 7,10,10,10,11,11,13,18,19, 6, 5, 5, 6, 7, 8,
  139713. 9,12,19,19, 8, 5, 4, 4, 6, 7, 9,13,19,19, 8, 5,
  139714. 4, 4, 5, 6, 8,12,17,19, 7, 5, 5, 4, 4, 5, 7,12,
  139715. 18,18, 8, 7, 7, 6, 5, 5, 6,10,18,18, 9, 9, 9, 8,
  139716. 6, 5, 6, 9,18,18,11,13,13,13, 8, 7, 7, 9,16,18,
  139717. 13,17,18,16,11, 9, 9, 9,17,18,15,18,18,18,15,13,
  139718. 13,14,18,18,
  139719. };
  139720. static static_codebook _huff_book__16u2__long = {
  139721. 2, 100,
  139722. _huff_lengthlist__16u2__long,
  139723. 0, 0, 0, 0, 0,
  139724. NULL,
  139725. NULL,
  139726. NULL,
  139727. NULL,
  139728. 0
  139729. };
  139730. static long _huff_lengthlist__16u2__short[] = {
  139731. 8,11,12,12,14,15,16,16,16,16, 9, 7, 7, 8, 9,11,
  139732. 13,14,16,16,13, 7, 6, 6, 7, 9,12,13,15,16,15, 7,
  139733. 6, 5, 4, 6,10,11,14,16,12, 8, 7, 4, 2, 4, 7,10,
  139734. 14,16,11, 9, 7, 5, 3, 4, 6, 9,14,16,11,10, 9, 7,
  139735. 5, 5, 6, 9,16,16,10,10, 9, 8, 6, 6, 7,10,16,16,
  139736. 11,11,11,10,10,10,11,14,16,16,16,14,14,13,14,16,
  139737. 16,16,16,16,
  139738. };
  139739. static static_codebook _huff_book__16u2__short = {
  139740. 2, 100,
  139741. _huff_lengthlist__16u2__short,
  139742. 0, 0, 0, 0, 0,
  139743. NULL,
  139744. NULL,
  139745. NULL,
  139746. NULL,
  139747. 0
  139748. };
  139749. static long _vq_quantlist__16u2_p1_0[] = {
  139750. 1,
  139751. 0,
  139752. 2,
  139753. };
  139754. static long _vq_lengthlist__16u2_p1_0[] = {
  139755. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 7, 9, 9, 7,
  139756. 9, 9, 5, 7, 7, 7, 9, 9, 7, 9, 9, 5, 7, 7, 8, 9,
  139757. 9, 7, 9, 9, 7, 9, 9, 9,10,10, 9,10,10, 7, 9, 9,
  139758. 9,10,10, 9,10,11, 5, 7, 8, 8, 9, 9, 8, 9, 9, 7,
  139759. 9, 9, 9,10,10, 9, 9,10, 7, 9, 9, 9,10,10, 9,11,
  139760. 10,
  139761. };
  139762. static float _vq_quantthresh__16u2_p1_0[] = {
  139763. -0.5, 0.5,
  139764. };
  139765. static long _vq_quantmap__16u2_p1_0[] = {
  139766. 1, 0, 2,
  139767. };
  139768. static encode_aux_threshmatch _vq_auxt__16u2_p1_0 = {
  139769. _vq_quantthresh__16u2_p1_0,
  139770. _vq_quantmap__16u2_p1_0,
  139771. 3,
  139772. 3
  139773. };
  139774. static static_codebook _16u2_p1_0 = {
  139775. 4, 81,
  139776. _vq_lengthlist__16u2_p1_0,
  139777. 1, -535822336, 1611661312, 2, 0,
  139778. _vq_quantlist__16u2_p1_0,
  139779. NULL,
  139780. &_vq_auxt__16u2_p1_0,
  139781. NULL,
  139782. 0
  139783. };
  139784. static long _vq_quantlist__16u2_p2_0[] = {
  139785. 2,
  139786. 1,
  139787. 3,
  139788. 0,
  139789. 4,
  139790. };
  139791. static long _vq_lengthlist__16u2_p2_0[] = {
  139792. 3, 5, 5, 8, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 9,
  139793. 10, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  139794. 8,10,10, 7, 8, 8,10,10,10,10,10,12,12, 9,10,10,
  139795. 11,12, 5, 7, 7, 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,
  139796. 10, 9,10,10,12,11,10,10,10,12,12, 9,10,10,12,12,
  139797. 10,11,10,13,12, 9,10,10,12,12,12,12,12,14,14,11,
  139798. 12,12,13,14, 9,10,10,12,12, 9,10,10,12,12,10,10,
  139799. 10,12,12,11,12,12,14,13,12,13,12,14,14, 5, 7, 7,
  139800. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,12,
  139801. 12,10,10,11,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  139802. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,12,13, 7,
  139803. 8, 8,10,10, 8, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  139804. 10,13,12,10,11,11,13,13, 9,11,10,13,13,10,11,11,
  139805. 13,13,10,11,11,13,13,12,12,13,13,15,12,12,13,14,
  139806. 15, 9,10,10,12,12,10,11,10,13,12,10,11,11,13,13,
  139807. 11,13,11,14,13,12,13,13,15,15, 5, 7, 7, 9, 9, 7,
  139808. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,12,10,10,
  139809. 11,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11, 8, 8, 9,
  139810. 10,11,10,11,11,13,13,10,10,11,12,13, 7, 8, 8,10,
  139811. 11, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,12,
  139812. 11,11,11,13,12, 9,10,10,12,12,10,11,11,13,13,10,
  139813. 10,11,12,13,12,13,13,15,14,11,11,13,12,14,10,10,
  139814. 11,13,13,10,11,11,13,13,10,11,11,13,13,12,13,13,
  139815. 14,14,12,13,12,14,13, 8,10, 9,12,12, 9,11,10,13,
  139816. 13, 9,10,10,12,13,12,13,13,14,14,12,12,13,14,14,
  139817. 9,11,10,13,13,10,11,11,13,13,10,11,11,13,13,12,
  139818. 13,13,15,15,13,13,13,14,15, 9,10,10,12,13,10,11,
  139819. 10,13,12,10,11,11,13,13,12,13,12,15,14,13,13,13,
  139820. 14,15,11,12,12,15,14,12,12,13,15,15,12,13,13,15,
  139821. 14,14,13,15,14,16,13,14,15,16,16,11,12,12,14,14,
  139822. 11,12,12,15,14,12,13,13,15,15,13,14,13,16,14,14,
  139823. 14,14,16,16, 8, 9, 9,12,12, 9,10,10,13,12, 9,10,
  139824. 10,13,13,12,12,12,14,14,12,12,13,15,15, 9,10,10,
  139825. 13,12,10,11,11,13,13,10,10,11,13,14,12,13,13,15,
  139826. 15,12,12,13,14,15, 9,10,10,13,13,10,11,11,13,13,
  139827. 10,11,11,13,13,12,13,13,14,14,13,14,13,15,14,11,
  139828. 12,12,14,14,12,13,13,15,14,11,12,12,14,15,14,14,
  139829. 14,16,15,13,12,14,14,16,11,12,13,14,15,12,13,13,
  139830. 14,16,12,13,12,15,14,13,15,14,16,16,14,15,13,16,
  139831. 13,
  139832. };
  139833. static float _vq_quantthresh__16u2_p2_0[] = {
  139834. -1.5, -0.5, 0.5, 1.5,
  139835. };
  139836. static long _vq_quantmap__16u2_p2_0[] = {
  139837. 3, 1, 0, 2, 4,
  139838. };
  139839. static encode_aux_threshmatch _vq_auxt__16u2_p2_0 = {
  139840. _vq_quantthresh__16u2_p2_0,
  139841. _vq_quantmap__16u2_p2_0,
  139842. 5,
  139843. 5
  139844. };
  139845. static static_codebook _16u2_p2_0 = {
  139846. 4, 625,
  139847. _vq_lengthlist__16u2_p2_0,
  139848. 1, -533725184, 1611661312, 3, 0,
  139849. _vq_quantlist__16u2_p2_0,
  139850. NULL,
  139851. &_vq_auxt__16u2_p2_0,
  139852. NULL,
  139853. 0
  139854. };
  139855. static long _vq_quantlist__16u2_p3_0[] = {
  139856. 4,
  139857. 3,
  139858. 5,
  139859. 2,
  139860. 6,
  139861. 1,
  139862. 7,
  139863. 0,
  139864. 8,
  139865. };
  139866. static long _vq_lengthlist__16u2_p3_0[] = {
  139867. 2, 4, 4, 6, 6, 7, 7, 9, 9, 4, 5, 5, 6, 6, 8, 7,
  139868. 9, 9, 4, 5, 5, 6, 6, 7, 8, 9, 9, 6, 6, 6, 7, 7,
  139869. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8, 9,10, 7, 8, 7,
  139870. 8, 8, 9, 9,10,10, 7, 8, 8, 8, 8, 9, 9,10,10, 9,
  139871. 9, 9,10, 9,10,10,11,11, 9, 9, 9,10,10,10,10,11,
  139872. 11,
  139873. };
  139874. static float _vq_quantthresh__16u2_p3_0[] = {
  139875. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  139876. };
  139877. static long _vq_quantmap__16u2_p3_0[] = {
  139878. 7, 5, 3, 1, 0, 2, 4, 6,
  139879. 8,
  139880. };
  139881. static encode_aux_threshmatch _vq_auxt__16u2_p3_0 = {
  139882. _vq_quantthresh__16u2_p3_0,
  139883. _vq_quantmap__16u2_p3_0,
  139884. 9,
  139885. 9
  139886. };
  139887. static static_codebook _16u2_p3_0 = {
  139888. 2, 81,
  139889. _vq_lengthlist__16u2_p3_0,
  139890. 1, -531628032, 1611661312, 4, 0,
  139891. _vq_quantlist__16u2_p3_0,
  139892. NULL,
  139893. &_vq_auxt__16u2_p3_0,
  139894. NULL,
  139895. 0
  139896. };
  139897. static long _vq_quantlist__16u2_p4_0[] = {
  139898. 8,
  139899. 7,
  139900. 9,
  139901. 6,
  139902. 10,
  139903. 5,
  139904. 11,
  139905. 4,
  139906. 12,
  139907. 3,
  139908. 13,
  139909. 2,
  139910. 14,
  139911. 1,
  139912. 15,
  139913. 0,
  139914. 16,
  139915. };
  139916. static long _vq_lengthlist__16u2_p4_0[] = {
  139917. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,11,
  139918. 11, 5, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  139919. 12,11, 5, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  139920. 11,12,12, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  139921. 11,11,12,12, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,
  139922. 10,11,11,12,12, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,
  139923. 11,11,12,12,12,12, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  139924. 10,11,11,11,12,12,12, 9, 9, 9, 9, 9, 9,10,10,10,
  139925. 10,10,11,11,12,12,13,13, 8, 9, 9, 9, 9,10, 9,10,
  139926. 10,10,10,11,11,12,12,13,13, 9, 9, 9, 9, 9,10,10,
  139927. 10,10,11,11,11,12,12,12,13,13, 9, 9, 9, 9, 9,10,
  139928. 10,10,10,11,11,12,11,12,12,13,13,10,10,10,10,10,
  139929. 11,11,11,11,11,12,12,12,12,13,13,14,10,10,10,10,
  139930. 10,11,11,11,11,12,11,12,12,13,12,13,13,11,11,11,
  139931. 11,11,12,12,12,12,12,12,13,13,13,13,14,14,11,11,
  139932. 11,11,11,12,12,12,12,12,12,13,12,13,13,14,14,11,
  139933. 12,12,12,12,12,12,13,13,13,13,13,13,14,14,14,14,
  139934. 11,12,12,12,12,12,12,13,13,13,13,14,13,14,14,14,
  139935. 14,
  139936. };
  139937. static float _vq_quantthresh__16u2_p4_0[] = {
  139938. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  139939. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  139940. };
  139941. static long _vq_quantmap__16u2_p4_0[] = {
  139942. 15, 13, 11, 9, 7, 5, 3, 1,
  139943. 0, 2, 4, 6, 8, 10, 12, 14,
  139944. 16,
  139945. };
  139946. static encode_aux_threshmatch _vq_auxt__16u2_p4_0 = {
  139947. _vq_quantthresh__16u2_p4_0,
  139948. _vq_quantmap__16u2_p4_0,
  139949. 17,
  139950. 17
  139951. };
  139952. static static_codebook _16u2_p4_0 = {
  139953. 2, 289,
  139954. _vq_lengthlist__16u2_p4_0,
  139955. 1, -529530880, 1611661312, 5, 0,
  139956. _vq_quantlist__16u2_p4_0,
  139957. NULL,
  139958. &_vq_auxt__16u2_p4_0,
  139959. NULL,
  139960. 0
  139961. };
  139962. static long _vq_quantlist__16u2_p5_0[] = {
  139963. 1,
  139964. 0,
  139965. 2,
  139966. };
  139967. static long _vq_lengthlist__16u2_p5_0[] = {
  139968. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 7,10, 9, 7,
  139969. 10, 9, 5, 8, 9, 7, 9,10, 7, 9,10, 4, 9, 9, 9,11,
  139970. 11, 8,11,11, 7,11,11,10,10,13,10,14,13, 7,11,11,
  139971. 10,13,11,10,13,14, 5, 9, 9, 8,11,11, 9,11,11, 7,
  139972. 11,11,10,14,13,10,12,14, 7,11,11,10,13,13,10,13,
  139973. 10,
  139974. };
  139975. static float _vq_quantthresh__16u2_p5_0[] = {
  139976. -5.5, 5.5,
  139977. };
  139978. static long _vq_quantmap__16u2_p5_0[] = {
  139979. 1, 0, 2,
  139980. };
  139981. static encode_aux_threshmatch _vq_auxt__16u2_p5_0 = {
  139982. _vq_quantthresh__16u2_p5_0,
  139983. _vq_quantmap__16u2_p5_0,
  139984. 3,
  139985. 3
  139986. };
  139987. static static_codebook _16u2_p5_0 = {
  139988. 4, 81,
  139989. _vq_lengthlist__16u2_p5_0,
  139990. 1, -529137664, 1618345984, 2, 0,
  139991. _vq_quantlist__16u2_p5_0,
  139992. NULL,
  139993. &_vq_auxt__16u2_p5_0,
  139994. NULL,
  139995. 0
  139996. };
  139997. static long _vq_quantlist__16u2_p5_1[] = {
  139998. 5,
  139999. 4,
  140000. 6,
  140001. 3,
  140002. 7,
  140003. 2,
  140004. 8,
  140005. 1,
  140006. 9,
  140007. 0,
  140008. 10,
  140009. };
  140010. static long _vq_lengthlist__16u2_p5_1[] = {
  140011. 2, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 5, 5, 5, 7, 7,
  140012. 7, 7, 8, 8, 8, 8, 5, 5, 6, 7, 7, 7, 7, 8, 8, 8,
  140013. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  140014. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 9, 9,
  140015. 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  140016. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  140017. 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  140018. 8, 8, 8, 9, 9, 9, 9, 9, 9,
  140019. };
  140020. static float _vq_quantthresh__16u2_p5_1[] = {
  140021. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  140022. 3.5, 4.5,
  140023. };
  140024. static long _vq_quantmap__16u2_p5_1[] = {
  140025. 9, 7, 5, 3, 1, 0, 2, 4,
  140026. 6, 8, 10,
  140027. };
  140028. static encode_aux_threshmatch _vq_auxt__16u2_p5_1 = {
  140029. _vq_quantthresh__16u2_p5_1,
  140030. _vq_quantmap__16u2_p5_1,
  140031. 11,
  140032. 11
  140033. };
  140034. static static_codebook _16u2_p5_1 = {
  140035. 2, 121,
  140036. _vq_lengthlist__16u2_p5_1,
  140037. 1, -531365888, 1611661312, 4, 0,
  140038. _vq_quantlist__16u2_p5_1,
  140039. NULL,
  140040. &_vq_auxt__16u2_p5_1,
  140041. NULL,
  140042. 0
  140043. };
  140044. static long _vq_quantlist__16u2_p6_0[] = {
  140045. 6,
  140046. 5,
  140047. 7,
  140048. 4,
  140049. 8,
  140050. 3,
  140051. 9,
  140052. 2,
  140053. 10,
  140054. 1,
  140055. 11,
  140056. 0,
  140057. 12,
  140058. };
  140059. static long _vq_lengthlist__16u2_p6_0[] = {
  140060. 1, 4, 4, 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 6, 6,
  140061. 8, 8, 9, 9, 9, 9,10,10,12,11, 4, 6, 6, 8, 8, 9,
  140062. 9, 9, 9,10,10,11,12, 7, 8, 8, 9, 9,10,10,10,10,
  140063. 12,12,13,12, 7, 8, 8, 9, 9,10,10,10,10,11,12,12,
  140064. 12, 8, 9, 9,10,10,11,11,11,11,12,12,13,13, 8, 9,
  140065. 9,10,10,11,11,11,11,12,13,13,13, 8, 9, 9,10,10,
  140066. 11,11,12,12,13,13,14,14, 8, 9, 9,10,10,11,11,12,
  140067. 12,13,13,14,14, 9,10,10,11,12,13,12,13,14,14,14,
  140068. 14,14, 9,10,10,11,12,12,13,13,13,14,14,14,14,10,
  140069. 11,11,12,12,13,13,14,14,15,15,15,15,10,11,11,12,
  140070. 12,13,13,14,14,14,14,15,15,
  140071. };
  140072. static float _vq_quantthresh__16u2_p6_0[] = {
  140073. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  140074. 12.5, 17.5, 22.5, 27.5,
  140075. };
  140076. static long _vq_quantmap__16u2_p6_0[] = {
  140077. 11, 9, 7, 5, 3, 1, 0, 2,
  140078. 4, 6, 8, 10, 12,
  140079. };
  140080. static encode_aux_threshmatch _vq_auxt__16u2_p6_0 = {
  140081. _vq_quantthresh__16u2_p6_0,
  140082. _vq_quantmap__16u2_p6_0,
  140083. 13,
  140084. 13
  140085. };
  140086. static static_codebook _16u2_p6_0 = {
  140087. 2, 169,
  140088. _vq_lengthlist__16u2_p6_0,
  140089. 1, -526516224, 1616117760, 4, 0,
  140090. _vq_quantlist__16u2_p6_0,
  140091. NULL,
  140092. &_vq_auxt__16u2_p6_0,
  140093. NULL,
  140094. 0
  140095. };
  140096. static long _vq_quantlist__16u2_p6_1[] = {
  140097. 2,
  140098. 1,
  140099. 3,
  140100. 0,
  140101. 4,
  140102. };
  140103. static long _vq_lengthlist__16u2_p6_1[] = {
  140104. 2, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
  140105. 5, 5, 6, 6, 5, 5, 5, 6, 6,
  140106. };
  140107. static float _vq_quantthresh__16u2_p6_1[] = {
  140108. -1.5, -0.5, 0.5, 1.5,
  140109. };
  140110. static long _vq_quantmap__16u2_p6_1[] = {
  140111. 3, 1, 0, 2, 4,
  140112. };
  140113. static encode_aux_threshmatch _vq_auxt__16u2_p6_1 = {
  140114. _vq_quantthresh__16u2_p6_1,
  140115. _vq_quantmap__16u2_p6_1,
  140116. 5,
  140117. 5
  140118. };
  140119. static static_codebook _16u2_p6_1 = {
  140120. 2, 25,
  140121. _vq_lengthlist__16u2_p6_1,
  140122. 1, -533725184, 1611661312, 3, 0,
  140123. _vq_quantlist__16u2_p6_1,
  140124. NULL,
  140125. &_vq_auxt__16u2_p6_1,
  140126. NULL,
  140127. 0
  140128. };
  140129. static long _vq_quantlist__16u2_p7_0[] = {
  140130. 6,
  140131. 5,
  140132. 7,
  140133. 4,
  140134. 8,
  140135. 3,
  140136. 9,
  140137. 2,
  140138. 10,
  140139. 1,
  140140. 11,
  140141. 0,
  140142. 12,
  140143. };
  140144. static long _vq_lengthlist__16u2_p7_0[] = {
  140145. 1, 4, 4, 7, 7, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 6,
  140146. 9, 9, 9, 9, 9, 9,10,10,11,11, 4, 6, 6, 8, 9, 9,
  140147. 9, 9, 9,10,11,12,11, 7, 8, 9,10,10,10,10,11,10,
  140148. 11,12,12,13, 7, 9, 9,10,10,10,10,10,10,11,12,13,
  140149. 13, 7, 9, 8,10,10,11,11,11,12,12,13,13,14, 7, 9,
  140150. 9,10,10,11,11,11,12,13,13,13,13, 8, 9, 9,10,11,
  140151. 11,12,12,12,13,13,13,13, 8, 9, 9,10,11,11,11,12,
  140152. 12,13,13,14,14, 9,10,10,12,11,12,13,13,13,14,13,
  140153. 13,13, 9,10,10,11,11,12,12,13,14,13,13,14,13,10,
  140154. 11,11,12,13,14,14,14,15,14,14,14,14,10,11,11,12,
  140155. 12,13,13,13,14,14,14,15,14,
  140156. };
  140157. static float _vq_quantthresh__16u2_p7_0[] = {
  140158. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  140159. 27.5, 38.5, 49.5, 60.5,
  140160. };
  140161. static long _vq_quantmap__16u2_p7_0[] = {
  140162. 11, 9, 7, 5, 3, 1, 0, 2,
  140163. 4, 6, 8, 10, 12,
  140164. };
  140165. static encode_aux_threshmatch _vq_auxt__16u2_p7_0 = {
  140166. _vq_quantthresh__16u2_p7_0,
  140167. _vq_quantmap__16u2_p7_0,
  140168. 13,
  140169. 13
  140170. };
  140171. static static_codebook _16u2_p7_0 = {
  140172. 2, 169,
  140173. _vq_lengthlist__16u2_p7_0,
  140174. 1, -523206656, 1618345984, 4, 0,
  140175. _vq_quantlist__16u2_p7_0,
  140176. NULL,
  140177. &_vq_auxt__16u2_p7_0,
  140178. NULL,
  140179. 0
  140180. };
  140181. static long _vq_quantlist__16u2_p7_1[] = {
  140182. 5,
  140183. 4,
  140184. 6,
  140185. 3,
  140186. 7,
  140187. 2,
  140188. 8,
  140189. 1,
  140190. 9,
  140191. 0,
  140192. 10,
  140193. };
  140194. static long _vq_lengthlist__16u2_p7_1[] = {
  140195. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  140196. 7, 7, 7, 7, 8, 8, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8,
  140197. 8, 6, 6, 7, 7, 7, 8, 7, 8, 8, 8, 8, 6, 7, 7, 7,
  140198. 7, 7, 7, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  140199. 8, 8, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7,
  140200. 8, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8,
  140201. 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  140202. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  140203. };
  140204. static float _vq_quantthresh__16u2_p7_1[] = {
  140205. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  140206. 3.5, 4.5,
  140207. };
  140208. static long _vq_quantmap__16u2_p7_1[] = {
  140209. 9, 7, 5, 3, 1, 0, 2, 4,
  140210. 6, 8, 10,
  140211. };
  140212. static encode_aux_threshmatch _vq_auxt__16u2_p7_1 = {
  140213. _vq_quantthresh__16u2_p7_1,
  140214. _vq_quantmap__16u2_p7_1,
  140215. 11,
  140216. 11
  140217. };
  140218. static static_codebook _16u2_p7_1 = {
  140219. 2, 121,
  140220. _vq_lengthlist__16u2_p7_1,
  140221. 1, -531365888, 1611661312, 4, 0,
  140222. _vq_quantlist__16u2_p7_1,
  140223. NULL,
  140224. &_vq_auxt__16u2_p7_1,
  140225. NULL,
  140226. 0
  140227. };
  140228. static long _vq_quantlist__16u2_p8_0[] = {
  140229. 7,
  140230. 6,
  140231. 8,
  140232. 5,
  140233. 9,
  140234. 4,
  140235. 10,
  140236. 3,
  140237. 11,
  140238. 2,
  140239. 12,
  140240. 1,
  140241. 13,
  140242. 0,
  140243. 14,
  140244. };
  140245. static long _vq_lengthlist__16u2_p8_0[] = {
  140246. 1, 5, 5, 7, 7, 8, 8, 7, 7, 8, 8,10, 9,11,11, 4,
  140247. 6, 6, 8, 8,10, 9, 9, 8, 9, 9,10,10,12,14, 4, 6,
  140248. 7, 8, 9, 9,10, 9, 8, 9, 9,10,12,12,11, 7, 8, 8,
  140249. 10,10,10,10, 9, 9,10,10,11,13,13,12, 7, 8, 8, 9,
  140250. 11,11,10, 9, 9,11,10,12,11,11,14, 8, 9, 9,11,10,
  140251. 11,11,10,10,11,11,13,12,14,12, 8, 9, 9,11,12,11,
  140252. 11,10,10,12,11,12,12,12,14, 7, 8, 8, 9, 9,10,10,
  140253. 10,11,12,11,13,13,14,12, 7, 8, 9, 9, 9,10,10,11,
  140254. 11,11,12,12,14,14,14, 8,10, 9,10,11,11,11,11,14,
  140255. 12,12,13,14,14,13, 9, 9, 9,10,11,11,11,12,12,12,
  140256. 14,12,14,13,14,10,10,10,12,11,12,11,14,13,14,13,
  140257. 14,14,13,14, 9,10,10,11,12,11,13,12,13,13,14,14,
  140258. 14,13,14,10,13,13,12,12,11,12,14,13,14,13,14,12,
  140259. 14,13,10,11,11,12,11,12,12,14,14,14,13,14,14,14,
  140260. 14,
  140261. };
  140262. static float _vq_quantthresh__16u2_p8_0[] = {
  140263. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  140264. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  140265. };
  140266. static long _vq_quantmap__16u2_p8_0[] = {
  140267. 13, 11, 9, 7, 5, 3, 1, 0,
  140268. 2, 4, 6, 8, 10, 12, 14,
  140269. };
  140270. static encode_aux_threshmatch _vq_auxt__16u2_p8_0 = {
  140271. _vq_quantthresh__16u2_p8_0,
  140272. _vq_quantmap__16u2_p8_0,
  140273. 15,
  140274. 15
  140275. };
  140276. static static_codebook _16u2_p8_0 = {
  140277. 2, 225,
  140278. _vq_lengthlist__16u2_p8_0,
  140279. 1, -520986624, 1620377600, 4, 0,
  140280. _vq_quantlist__16u2_p8_0,
  140281. NULL,
  140282. &_vq_auxt__16u2_p8_0,
  140283. NULL,
  140284. 0
  140285. };
  140286. static long _vq_quantlist__16u2_p8_1[] = {
  140287. 10,
  140288. 9,
  140289. 11,
  140290. 8,
  140291. 12,
  140292. 7,
  140293. 13,
  140294. 6,
  140295. 14,
  140296. 5,
  140297. 15,
  140298. 4,
  140299. 16,
  140300. 3,
  140301. 17,
  140302. 2,
  140303. 18,
  140304. 1,
  140305. 19,
  140306. 0,
  140307. 20,
  140308. };
  140309. static long _vq_lengthlist__16u2_p8_1[] = {
  140310. 2, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10, 9,10, 9, 9,
  140311. 9,10,10,10,10, 5, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,
  140312. 10, 9,10,10,10,10,10,10,11,10, 5, 6, 6, 7, 7, 8,
  140313. 8, 8, 9, 9,10,10,10,10,10,10,10,10,10,10,10, 7,
  140314. 7, 7, 8, 8, 9, 8, 9, 9,10, 9,10,10,10,10,10,10,
  140315. 11,10,11,10, 7, 7, 7, 8, 8, 8, 9, 9, 9,10, 9,10,
  140316. 10,10,10,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9,
  140317. 10, 9,10,10,10,10,10,10,10,11,10,10,11,10, 8, 8,
  140318. 8, 8, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,
  140319. 11,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  140320. 11,10,11,10,11,10,11,10, 8, 9, 9, 9, 9, 9,10,10,
  140321. 10,10,10,10,10,10,10,10,11,11,10,10,10, 9,10, 9,
  140322. 9,10,10,10,11,10,10,10,10,10,10,10,10,11,11,11,
  140323. 11,11, 9, 9, 9,10, 9,10,10,10,10,10,10,11,10,11,
  140324. 10,11,11,11,11,10,10, 9,10, 9,10,10,10,10,11,10,
  140325. 10,10,10,10,11,10,11,10,11,10,10,11, 9,10,10,10,
  140326. 10,10,10,10,10,10,11,10,10,11,11,10,11,11,11,11,
  140327. 11, 9, 9,10,10,10,10,10,11,10,10,11,10,10,11,10,
  140328. 10,11,11,11,11,11, 9,10,10,10,10,10,10,10,11,10,
  140329. 11,10,11,10,11,11,11,11,11,10,11,10,10,10,10,10,
  140330. 10,10,10,10,11,11,11,11,11,11,11,11,11,10,11,11,
  140331. 10,10,10,10,10,11,10,10,10,11,10,11,11,11,11,10,
  140332. 12,11,11,11,10,10,10,10,10,10,11,10,10,10,11,11,
  140333. 12,11,11,11,11,11,11,11,11,11,10,10,10,11,10,11,
  140334. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,
  140335. 10,10,11,10,11,10,10,11,11,11,11,11,11,11,11,11,
  140336. 11,11,11,10,10,10,10,10,10,10,11,11,10,11,11,10,
  140337. 11,11,10,11,11,11,10,11,11,
  140338. };
  140339. static float _vq_quantthresh__16u2_p8_1[] = {
  140340. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  140341. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  140342. 6.5, 7.5, 8.5, 9.5,
  140343. };
  140344. static long _vq_quantmap__16u2_p8_1[] = {
  140345. 19, 17, 15, 13, 11, 9, 7, 5,
  140346. 3, 1, 0, 2, 4, 6, 8, 10,
  140347. 12, 14, 16, 18, 20,
  140348. };
  140349. static encode_aux_threshmatch _vq_auxt__16u2_p8_1 = {
  140350. _vq_quantthresh__16u2_p8_1,
  140351. _vq_quantmap__16u2_p8_1,
  140352. 21,
  140353. 21
  140354. };
  140355. static static_codebook _16u2_p8_1 = {
  140356. 2, 441,
  140357. _vq_lengthlist__16u2_p8_1,
  140358. 1, -529268736, 1611661312, 5, 0,
  140359. _vq_quantlist__16u2_p8_1,
  140360. NULL,
  140361. &_vq_auxt__16u2_p8_1,
  140362. NULL,
  140363. 0
  140364. };
  140365. static long _vq_quantlist__16u2_p9_0[] = {
  140366. 5586,
  140367. 4655,
  140368. 6517,
  140369. 3724,
  140370. 7448,
  140371. 2793,
  140372. 8379,
  140373. 1862,
  140374. 9310,
  140375. 931,
  140376. 10241,
  140377. 0,
  140378. 11172,
  140379. 5521,
  140380. 5651,
  140381. };
  140382. static long _vq_lengthlist__16u2_p9_0[] = {
  140383. 1,10,10,10,10,10,10,10,10,10,10,10,10, 5, 4,10,
  140384. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  140385. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  140386. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  140387. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  140388. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  140389. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  140390. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  140391. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  140392. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  140393. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  140394. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  140395. 10,10,10, 4,10,10,10,10,10,10,10,10,10,10,10,10,
  140396. 6, 6, 5,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 5,
  140397. 5,
  140398. };
  140399. static float _vq_quantthresh__16u2_p9_0[] = {
  140400. -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -498, -32.5, 32.5,
  140401. 498, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5,
  140402. };
  140403. static long _vq_quantmap__16u2_p9_0[] = {
  140404. 11, 9, 7, 5, 3, 1, 13, 0,
  140405. 14, 2, 4, 6, 8, 10, 12,
  140406. };
  140407. static encode_aux_threshmatch _vq_auxt__16u2_p9_0 = {
  140408. _vq_quantthresh__16u2_p9_0,
  140409. _vq_quantmap__16u2_p9_0,
  140410. 15,
  140411. 15
  140412. };
  140413. static static_codebook _16u2_p9_0 = {
  140414. 2, 225,
  140415. _vq_lengthlist__16u2_p9_0,
  140416. 1, -510275072, 1611661312, 14, 0,
  140417. _vq_quantlist__16u2_p9_0,
  140418. NULL,
  140419. &_vq_auxt__16u2_p9_0,
  140420. NULL,
  140421. 0
  140422. };
  140423. static long _vq_quantlist__16u2_p9_1[] = {
  140424. 392,
  140425. 343,
  140426. 441,
  140427. 294,
  140428. 490,
  140429. 245,
  140430. 539,
  140431. 196,
  140432. 588,
  140433. 147,
  140434. 637,
  140435. 98,
  140436. 686,
  140437. 49,
  140438. 735,
  140439. 0,
  140440. 784,
  140441. 388,
  140442. 396,
  140443. };
  140444. static long _vq_lengthlist__16u2_p9_1[] = {
  140445. 1,12,10,12,10,12,10,12,11,12,12,12,12,12,12,12,
  140446. 12, 5, 5, 9,10,12,11,11,12,12,12,12,12,12,12,12,
  140447. 12,12,12,12,10, 9, 9,11, 9,11,11,12,11,12,12,12,
  140448. 12,12,12,12,12,12,12, 8, 8,10,11, 9,12,11,12,12,
  140449. 12,12,12,12,12,12,12,12,12,12, 9, 8,10,11,12,11,
  140450. 12,11,12,12,12,12,12,12,12,12,12,12,12, 8, 9,11,
  140451. 11,10,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  140452. 9,10,11,12,11,12,11,12,12,12,12,12,12,12,12,12,
  140453. 12,12,12, 9, 9,11,12,12,12,12,12,12,12,12,12,12,
  140454. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  140455. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  140456. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  140457. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  140458. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  140459. 12,12,12,12,11,11,11,11,11,11,11,11,11,11,11,11,
  140460. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140461. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140462. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140463. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140464. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140465. 11,11,11, 5, 8, 9, 9, 8,11, 9,11,11,11,11,11,11,
  140466. 11,11,11,11, 5, 5, 4, 8, 8, 8, 8,10, 9,10,10,11,
  140467. 11,11,11,11,11,11,11, 5, 4,
  140468. };
  140469. static float _vq_quantthresh__16u2_p9_1[] = {
  140470. -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5, -26.5,
  140471. -2, 2, 26.5, 73.5, 122.5, 171.5, 220.5, 269.5,
  140472. 318.5, 367.5,
  140473. };
  140474. static long _vq_quantmap__16u2_p9_1[] = {
  140475. 15, 13, 11, 9, 7, 5, 3, 1,
  140476. 17, 0, 18, 2, 4, 6, 8, 10,
  140477. 12, 14, 16,
  140478. };
  140479. static encode_aux_threshmatch _vq_auxt__16u2_p9_1 = {
  140480. _vq_quantthresh__16u2_p9_1,
  140481. _vq_quantmap__16u2_p9_1,
  140482. 19,
  140483. 19
  140484. };
  140485. static static_codebook _16u2_p9_1 = {
  140486. 2, 361,
  140487. _vq_lengthlist__16u2_p9_1,
  140488. 1, -518488064, 1611661312, 10, 0,
  140489. _vq_quantlist__16u2_p9_1,
  140490. NULL,
  140491. &_vq_auxt__16u2_p9_1,
  140492. NULL,
  140493. 0
  140494. };
  140495. static long _vq_quantlist__16u2_p9_2[] = {
  140496. 24,
  140497. 23,
  140498. 25,
  140499. 22,
  140500. 26,
  140501. 21,
  140502. 27,
  140503. 20,
  140504. 28,
  140505. 19,
  140506. 29,
  140507. 18,
  140508. 30,
  140509. 17,
  140510. 31,
  140511. 16,
  140512. 32,
  140513. 15,
  140514. 33,
  140515. 14,
  140516. 34,
  140517. 13,
  140518. 35,
  140519. 12,
  140520. 36,
  140521. 11,
  140522. 37,
  140523. 10,
  140524. 38,
  140525. 9,
  140526. 39,
  140527. 8,
  140528. 40,
  140529. 7,
  140530. 41,
  140531. 6,
  140532. 42,
  140533. 5,
  140534. 43,
  140535. 4,
  140536. 44,
  140537. 3,
  140538. 45,
  140539. 2,
  140540. 46,
  140541. 1,
  140542. 47,
  140543. 0,
  140544. 48,
  140545. };
  140546. static long _vq_lengthlist__16u2_p9_2[] = {
  140547. 1, 3, 3, 4, 7, 7, 7, 8, 7, 7, 7, 7, 8, 8, 8, 8,
  140548. 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 9, 9, 8, 9, 9,
  140549. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,12,12,10,
  140550. 11,
  140551. };
  140552. static float _vq_quantthresh__16u2_p9_2[] = {
  140553. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  140554. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  140555. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  140556. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  140557. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  140558. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  140559. };
  140560. static long _vq_quantmap__16u2_p9_2[] = {
  140561. 47, 45, 43, 41, 39, 37, 35, 33,
  140562. 31, 29, 27, 25, 23, 21, 19, 17,
  140563. 15, 13, 11, 9, 7, 5, 3, 1,
  140564. 0, 2, 4, 6, 8, 10, 12, 14,
  140565. 16, 18, 20, 22, 24, 26, 28, 30,
  140566. 32, 34, 36, 38, 40, 42, 44, 46,
  140567. 48,
  140568. };
  140569. static encode_aux_threshmatch _vq_auxt__16u2_p9_2 = {
  140570. _vq_quantthresh__16u2_p9_2,
  140571. _vq_quantmap__16u2_p9_2,
  140572. 49,
  140573. 49
  140574. };
  140575. static static_codebook _16u2_p9_2 = {
  140576. 1, 49,
  140577. _vq_lengthlist__16u2_p9_2,
  140578. 1, -526909440, 1611661312, 6, 0,
  140579. _vq_quantlist__16u2_p9_2,
  140580. NULL,
  140581. &_vq_auxt__16u2_p9_2,
  140582. NULL,
  140583. 0
  140584. };
  140585. static long _vq_quantlist__8u0__p1_0[] = {
  140586. 1,
  140587. 0,
  140588. 2,
  140589. };
  140590. static long _vq_lengthlist__8u0__p1_0[] = {
  140591. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  140592. 10,10, 5, 8, 8, 7,10,10, 8,10,10, 4, 9, 8, 8,11,
  140593. 11, 8,11,11, 7,11,11,10,11,13,10,13,13, 7,11,11,
  140594. 10,13,12,10,13,13, 5, 9, 8, 8,11,11, 8,11,11, 7,
  140595. 11,11, 9,13,13,10,12,13, 7,11,11,10,13,13,10,13,
  140596. 11,
  140597. };
  140598. static float _vq_quantthresh__8u0__p1_0[] = {
  140599. -0.5, 0.5,
  140600. };
  140601. static long _vq_quantmap__8u0__p1_0[] = {
  140602. 1, 0, 2,
  140603. };
  140604. static encode_aux_threshmatch _vq_auxt__8u0__p1_0 = {
  140605. _vq_quantthresh__8u0__p1_0,
  140606. _vq_quantmap__8u0__p1_0,
  140607. 3,
  140608. 3
  140609. };
  140610. static static_codebook _8u0__p1_0 = {
  140611. 4, 81,
  140612. _vq_lengthlist__8u0__p1_0,
  140613. 1, -535822336, 1611661312, 2, 0,
  140614. _vq_quantlist__8u0__p1_0,
  140615. NULL,
  140616. &_vq_auxt__8u0__p1_0,
  140617. NULL,
  140618. 0
  140619. };
  140620. static long _vq_quantlist__8u0__p2_0[] = {
  140621. 1,
  140622. 0,
  140623. 2,
  140624. };
  140625. static long _vq_lengthlist__8u0__p2_0[] = {
  140626. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 6, 7, 8, 6,
  140627. 7, 8, 5, 7, 7, 6, 8, 8, 7, 9, 7, 5, 7, 7, 7, 9,
  140628. 9, 7, 8, 8, 6, 9, 8, 7, 7,10, 8,10,10, 6, 8, 8,
  140629. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 9, 6,
  140630. 8, 8, 8,10,10, 8, 8,10, 6, 8, 9, 8,10,10, 7,10,
  140631. 8,
  140632. };
  140633. static float _vq_quantthresh__8u0__p2_0[] = {
  140634. -0.5, 0.5,
  140635. };
  140636. static long _vq_quantmap__8u0__p2_0[] = {
  140637. 1, 0, 2,
  140638. };
  140639. static encode_aux_threshmatch _vq_auxt__8u0__p2_0 = {
  140640. _vq_quantthresh__8u0__p2_0,
  140641. _vq_quantmap__8u0__p2_0,
  140642. 3,
  140643. 3
  140644. };
  140645. static static_codebook _8u0__p2_0 = {
  140646. 4, 81,
  140647. _vq_lengthlist__8u0__p2_0,
  140648. 1, -535822336, 1611661312, 2, 0,
  140649. _vq_quantlist__8u0__p2_0,
  140650. NULL,
  140651. &_vq_auxt__8u0__p2_0,
  140652. NULL,
  140653. 0
  140654. };
  140655. static long _vq_quantlist__8u0__p3_0[] = {
  140656. 2,
  140657. 1,
  140658. 3,
  140659. 0,
  140660. 4,
  140661. };
  140662. static long _vq_lengthlist__8u0__p3_0[] = {
  140663. 1, 5, 5, 7, 7, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  140664. 10, 9,11,11, 8, 9, 9,11,11, 6, 8, 8,10,10, 8,10,
  140665. 10,11,11, 8,10,10,11,11,10,11,11,12,12,10,11,11,
  140666. 12,13, 6, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  140667. 11, 9,10,11,12,12,10,11,11,12,12, 8,11,11,14,13,
  140668. 10,12,11,15,13,10,12,11,14,14,12,13,12,16,14,12,
  140669. 14,12,16,15, 8,11,11,13,14,10,11,12,13,15,10,11,
  140670. 12,13,15,11,12,13,14,15,12,12,14,14,16, 5, 8, 8,
  140671. 11,11, 9,11,11,12,12, 8,10,11,12,12,11,12,12,15,
  140672. 14,11,12,12,14,14, 7,11,10,13,12,10,11,12,13,14,
  140673. 10,12,12,14,13,12,13,13,14,15,12,13,13,15,15, 7,
  140674. 10,11,12,13,10,12,11,14,13,10,12,13,13,15,12,13,
  140675. 12,14,14,11,13,13,15,16, 9,12,12,15,14,11,13,13,
  140676. 15,16,11,13,13,16,16,13,14,15,15,15,12,14,15,17,
  140677. 16, 9,12,12,14,15,11,13,13,15,16,11,13,13,16,18,
  140678. 13,14,14,17,16,13,15,15,17,18, 5, 8, 9,11,11, 8,
  140679. 11,11,12,12, 8,10,11,12,12,11,12,12,14,14,11,12,
  140680. 12,14,15, 7,11,10,12,13,10,12,12,14,13,10,11,12,
  140681. 13,14,11,13,13,15,14,12,13,13,14,15, 7,10,11,13,
  140682. 13,10,12,12,13,14,10,12,12,13,13,11,13,13,16,16,
  140683. 12,13,13,15,14, 9,12,12,16,15,10,13,13,15,15,11,
  140684. 13,13,17,15,12,15,15,18,17,13,14,14,15,16, 9,12,
  140685. 12,15,15,11,13,13,15,16,11,13,13,15,15,12,15,15,
  140686. 16,16,13,15,14,17,15, 7,11,11,15,15,10,13,13,16,
  140687. 15,10,13,13,15,16,14,15,15,17,19,13,15,14,15,18,
  140688. 9,12,12,16,16,11,13,14,17,16,11,13,13,17,16,15,
  140689. 15,16,17,19,13,15,16, 0,18, 9,12,12,16,15,11,14,
  140690. 13,17,17,11,13,14,16,16,15,16,16,19,18,13,15,15,
  140691. 17,19,11,14,14,19,16,12,14,15, 0,18,12,16,15,18,
  140692. 17,15,15,18,16,19,14,15,17,19,19,11,14,14,18,19,
  140693. 13,15,14,19,19,12,16,15,18,17,15,17,15, 0,16,14,
  140694. 17,16,19, 0, 7,11,11,14,14,10,12,12,15,15,10,13,
  140695. 13,16,15,13,15,15,17, 0,14,15,15,16,19, 9,12,12,
  140696. 16,16,11,14,14,16,16,11,13,13,16,16,14,17,16,19,
  140697. 0,14,18,17,17,19, 9,12,12,15,16,11,13,13,15,17,
  140698. 12,14,13,19,16,13,15,15,17,19,15,17,16,17,19,11,
  140699. 14,14,19,16,12,15,15,19,17,13,14,15,17,19,14,16,
  140700. 17,19,19,16,15,16,17,19,11,15,14,16,16,12,15,15,
  140701. 19, 0,12,14,15,19,19,14,16,16, 0,18,15,19,14,18,
  140702. 16,
  140703. };
  140704. static float _vq_quantthresh__8u0__p3_0[] = {
  140705. -1.5, -0.5, 0.5, 1.5,
  140706. };
  140707. static long _vq_quantmap__8u0__p3_0[] = {
  140708. 3, 1, 0, 2, 4,
  140709. };
  140710. static encode_aux_threshmatch _vq_auxt__8u0__p3_0 = {
  140711. _vq_quantthresh__8u0__p3_0,
  140712. _vq_quantmap__8u0__p3_0,
  140713. 5,
  140714. 5
  140715. };
  140716. static static_codebook _8u0__p3_0 = {
  140717. 4, 625,
  140718. _vq_lengthlist__8u0__p3_0,
  140719. 1, -533725184, 1611661312, 3, 0,
  140720. _vq_quantlist__8u0__p3_0,
  140721. NULL,
  140722. &_vq_auxt__8u0__p3_0,
  140723. NULL,
  140724. 0
  140725. };
  140726. static long _vq_quantlist__8u0__p4_0[] = {
  140727. 2,
  140728. 1,
  140729. 3,
  140730. 0,
  140731. 4,
  140732. };
  140733. static long _vq_lengthlist__8u0__p4_0[] = {
  140734. 3, 5, 5, 8, 8, 5, 6, 7, 9, 9, 6, 7, 6, 9, 9, 9,
  140735. 9, 9,10,11, 9, 9, 9,11,10, 6, 7, 7,10,10, 7, 7,
  140736. 8,10,10, 7, 8, 8,10,10,10,10,10,10,11, 9,10,10,
  140737. 11,12, 6, 7, 7,10,10, 7, 8, 8,10,10, 7, 8, 7,10,
  140738. 10, 9,10,10,12,11,10,10,10,11,10, 9,10,10,12,11,
  140739. 10,10,10,13,11, 9,10,10,12,12,11,11,12,12,13,11,
  140740. 11,11,12,13, 9,10,10,12,12,10,10,11,12,12,10,10,
  140741. 11,12,12,11,11,11,13,13,11,12,12,13,13, 5, 7, 7,
  140742. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,11,12,
  140743. 12,10,11,10,12,12, 7, 8, 8,11,11, 7, 8, 9,10,11,
  140744. 8, 9, 9,11,11,11,10,11,10,12,10,11,11,12,13, 7,
  140745. 8, 8,10,11, 8, 9, 8,12,10, 8, 9, 9,11,12,10,11,
  140746. 10,13,11,10,11,11,13,12, 9,11,10,13,12,10,10,11,
  140747. 12,12,10,11,11,13,13,12,10,13,11,14,11,12,12,15,
  140748. 13, 9,11,11,13,13,10,11,11,13,12,10,11,11,12,14,
  140749. 12,13,11,14,12,12,12,12,14,14, 5, 7, 7,10,10, 7,
  140750. 8, 8,10,10, 7, 8, 8,11,10,10,11,11,12,12,10,11,
  140751. 10,12,12, 7, 8, 8,10,11, 8, 9, 9,12,11, 8, 8, 9,
  140752. 10,11,10,11,11,12,13,11,10,11,11,13, 6, 8, 8,10,
  140753. 11, 8, 9, 9,11,11, 7, 9, 7,11,10,10,11,11,12,12,
  140754. 10,11,10,13,10, 9,11,10,13,12,10,12,11,13,13,10,
  140755. 10,11,12,13,11,12,13,15,14,11,11,13,12,13, 9,10,
  140756. 11,12,13,10,11,11,12,13,10,11,10,13,12,12,13,13,
  140757. 13,14,12,12,11,14,11, 8,10,10,12,13,10,11,11,13,
  140758. 13,10,11,10,13,13,12,13,14,15,14,12,12,12,14,13,
  140759. 9,10,10,13,12,10,10,12,13,13,10,11,11,15,12,12,
  140760. 12,13,15,14,12,13,13,15,13, 9,10,11,12,13,10,12,
  140761. 10,13,12,10,11,11,12,13,12,14,12,15,13,12,12,12,
  140762. 15,14,11,12,11,14,13,11,11,12,14,14,12,13,13,14,
  140763. 13,13,11,15,11,15,14,14,14,16,15,11,12,12,13,14,
  140764. 11,13,11,14,14,12,12,13,14,15,12,14,12,15,12,13,
  140765. 15,14,16,15, 8,10,10,12,12,10,10,10,12,13,10,11,
  140766. 11,13,13,12,12,12,13,14,13,13,13,15,15, 9,10,10,
  140767. 12,12,10,11,11,13,12,10,10,11,13,13,12,12,12,14,
  140768. 14,12,12,13,15,14, 9,10,10,13,12,10,10,12,12,13,
  140769. 10,11,10,13,13,12,13,13,14,14,12,13,12,14,13,11,
  140770. 12,12,14,13,12,13,12,14,14,10,12,12,14,14,14,14,
  140771. 14,16,14,13,12,14,12,15,10,12,12,14,15,12,13,13,
  140772. 14,16,11,12,11,15,14,13,14,14,14,15,13,14,11,14,
  140773. 12,
  140774. };
  140775. static float _vq_quantthresh__8u0__p4_0[] = {
  140776. -1.5, -0.5, 0.5, 1.5,
  140777. };
  140778. static long _vq_quantmap__8u0__p4_0[] = {
  140779. 3, 1, 0, 2, 4,
  140780. };
  140781. static encode_aux_threshmatch _vq_auxt__8u0__p4_0 = {
  140782. _vq_quantthresh__8u0__p4_0,
  140783. _vq_quantmap__8u0__p4_0,
  140784. 5,
  140785. 5
  140786. };
  140787. static static_codebook _8u0__p4_0 = {
  140788. 4, 625,
  140789. _vq_lengthlist__8u0__p4_0,
  140790. 1, -533725184, 1611661312, 3, 0,
  140791. _vq_quantlist__8u0__p4_0,
  140792. NULL,
  140793. &_vq_auxt__8u0__p4_0,
  140794. NULL,
  140795. 0
  140796. };
  140797. static long _vq_quantlist__8u0__p5_0[] = {
  140798. 4,
  140799. 3,
  140800. 5,
  140801. 2,
  140802. 6,
  140803. 1,
  140804. 7,
  140805. 0,
  140806. 8,
  140807. };
  140808. static long _vq_lengthlist__8u0__p5_0[] = {
  140809. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 7, 8, 8,
  140810. 10,10, 4, 6, 6, 8, 8, 8, 8,10,10, 6, 8, 8, 9, 9,
  140811. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 7, 8, 8,
  140812. 9, 9,10,10,12,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  140813. 10,10,11,11,11,12,12,12, 9,10,10,11,11,12,12,12,
  140814. 12,
  140815. };
  140816. static float _vq_quantthresh__8u0__p5_0[] = {
  140817. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  140818. };
  140819. static long _vq_quantmap__8u0__p5_0[] = {
  140820. 7, 5, 3, 1, 0, 2, 4, 6,
  140821. 8,
  140822. };
  140823. static encode_aux_threshmatch _vq_auxt__8u0__p5_0 = {
  140824. _vq_quantthresh__8u0__p5_0,
  140825. _vq_quantmap__8u0__p5_0,
  140826. 9,
  140827. 9
  140828. };
  140829. static static_codebook _8u0__p5_0 = {
  140830. 2, 81,
  140831. _vq_lengthlist__8u0__p5_0,
  140832. 1, -531628032, 1611661312, 4, 0,
  140833. _vq_quantlist__8u0__p5_0,
  140834. NULL,
  140835. &_vq_auxt__8u0__p5_0,
  140836. NULL,
  140837. 0
  140838. };
  140839. static long _vq_quantlist__8u0__p6_0[] = {
  140840. 6,
  140841. 5,
  140842. 7,
  140843. 4,
  140844. 8,
  140845. 3,
  140846. 9,
  140847. 2,
  140848. 10,
  140849. 1,
  140850. 11,
  140851. 0,
  140852. 12,
  140853. };
  140854. static long _vq_lengthlist__8u0__p6_0[] = {
  140855. 1, 4, 4, 7, 7, 9, 9,11,11,12,12,16,16, 3, 6, 6,
  140856. 9, 9,11,11,12,12,13,14,18,16, 3, 6, 7, 9, 9,11,
  140857. 11,13,12,14,14,17,16, 7, 9, 9,11,11,12,12,14,14,
  140858. 14,14,17,16, 7, 9, 9,11,11,13,12,13,13,14,14,17,
  140859. 0, 9,11,11,12,13,14,14,14,13,15,14,17,17, 9,11,
  140860. 11,12,12,14,14,13,14,14,15, 0, 0,11,12,12,15,14,
  140861. 15,14,15,14,15,16,17, 0,11,12,13,13,13,14,14,15,
  140862. 14,15,15, 0, 0,12,14,14,15,15,14,16,15,15,17,16,
  140863. 0,18,13,14,14,15,14,15,14,15,16,17,16, 0, 0,17,
  140864. 17,18, 0,16,18,16, 0, 0, 0,17, 0, 0,16, 0, 0,16,
  140865. 16, 0,15, 0,17, 0, 0, 0, 0,
  140866. };
  140867. static float _vq_quantthresh__8u0__p6_0[] = {
  140868. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  140869. 12.5, 17.5, 22.5, 27.5,
  140870. };
  140871. static long _vq_quantmap__8u0__p6_0[] = {
  140872. 11, 9, 7, 5, 3, 1, 0, 2,
  140873. 4, 6, 8, 10, 12,
  140874. };
  140875. static encode_aux_threshmatch _vq_auxt__8u0__p6_0 = {
  140876. _vq_quantthresh__8u0__p6_0,
  140877. _vq_quantmap__8u0__p6_0,
  140878. 13,
  140879. 13
  140880. };
  140881. static static_codebook _8u0__p6_0 = {
  140882. 2, 169,
  140883. _vq_lengthlist__8u0__p6_0,
  140884. 1, -526516224, 1616117760, 4, 0,
  140885. _vq_quantlist__8u0__p6_0,
  140886. NULL,
  140887. &_vq_auxt__8u0__p6_0,
  140888. NULL,
  140889. 0
  140890. };
  140891. static long _vq_quantlist__8u0__p6_1[] = {
  140892. 2,
  140893. 1,
  140894. 3,
  140895. 0,
  140896. 4,
  140897. };
  140898. static long _vq_lengthlist__8u0__p6_1[] = {
  140899. 1, 4, 4, 6, 6, 4, 6, 5, 7, 7, 4, 5, 6, 7, 7, 6,
  140900. 7, 7, 7, 7, 6, 7, 7, 7, 7,
  140901. };
  140902. static float _vq_quantthresh__8u0__p6_1[] = {
  140903. -1.5, -0.5, 0.5, 1.5,
  140904. };
  140905. static long _vq_quantmap__8u0__p6_1[] = {
  140906. 3, 1, 0, 2, 4,
  140907. };
  140908. static encode_aux_threshmatch _vq_auxt__8u0__p6_1 = {
  140909. _vq_quantthresh__8u0__p6_1,
  140910. _vq_quantmap__8u0__p6_1,
  140911. 5,
  140912. 5
  140913. };
  140914. static static_codebook _8u0__p6_1 = {
  140915. 2, 25,
  140916. _vq_lengthlist__8u0__p6_1,
  140917. 1, -533725184, 1611661312, 3, 0,
  140918. _vq_quantlist__8u0__p6_1,
  140919. NULL,
  140920. &_vq_auxt__8u0__p6_1,
  140921. NULL,
  140922. 0
  140923. };
  140924. static long _vq_quantlist__8u0__p7_0[] = {
  140925. 1,
  140926. 0,
  140927. 2,
  140928. };
  140929. static long _vq_lengthlist__8u0__p7_0[] = {
  140930. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  140931. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  140932. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  140933. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  140934. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  140935. 7,
  140936. };
  140937. static float _vq_quantthresh__8u0__p7_0[] = {
  140938. -157.5, 157.5,
  140939. };
  140940. static long _vq_quantmap__8u0__p7_0[] = {
  140941. 1, 0, 2,
  140942. };
  140943. static encode_aux_threshmatch _vq_auxt__8u0__p7_0 = {
  140944. _vq_quantthresh__8u0__p7_0,
  140945. _vq_quantmap__8u0__p7_0,
  140946. 3,
  140947. 3
  140948. };
  140949. static static_codebook _8u0__p7_0 = {
  140950. 4, 81,
  140951. _vq_lengthlist__8u0__p7_0,
  140952. 1, -518803456, 1628680192, 2, 0,
  140953. _vq_quantlist__8u0__p7_0,
  140954. NULL,
  140955. &_vq_auxt__8u0__p7_0,
  140956. NULL,
  140957. 0
  140958. };
  140959. static long _vq_quantlist__8u0__p7_1[] = {
  140960. 7,
  140961. 6,
  140962. 8,
  140963. 5,
  140964. 9,
  140965. 4,
  140966. 10,
  140967. 3,
  140968. 11,
  140969. 2,
  140970. 12,
  140971. 1,
  140972. 13,
  140973. 0,
  140974. 14,
  140975. };
  140976. static long _vq_lengthlist__8u0__p7_1[] = {
  140977. 1, 5, 5, 5, 5,10,10,11,11,11,11,11,11,11,11, 5,
  140978. 7, 6, 8, 8, 9,10,11,11,11,11,11,11,11,11, 6, 6,
  140979. 7, 9, 7,11,10,11,11,11,11,11,11,11,11, 5, 6, 6,
  140980. 11, 8,11,11,11,11,11,11,11,11,11,11, 5, 6, 6, 9,
  140981. 10,11,10,11,11,11,11,11,11,11,11, 7,10,10,11,11,
  140982. 11,11,11,11,11,11,11,11,11,11, 7,11, 8,11,11,11,
  140983. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140984. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140985. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140986. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140987. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140988. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140989. 11,11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,
  140990. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  140991. 10,
  140992. };
  140993. static float _vq_quantthresh__8u0__p7_1[] = {
  140994. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  140995. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  140996. };
  140997. static long _vq_quantmap__8u0__p7_1[] = {
  140998. 13, 11, 9, 7, 5, 3, 1, 0,
  140999. 2, 4, 6, 8, 10, 12, 14,
  141000. };
  141001. static encode_aux_threshmatch _vq_auxt__8u0__p7_1 = {
  141002. _vq_quantthresh__8u0__p7_1,
  141003. _vq_quantmap__8u0__p7_1,
  141004. 15,
  141005. 15
  141006. };
  141007. static static_codebook _8u0__p7_1 = {
  141008. 2, 225,
  141009. _vq_lengthlist__8u0__p7_1,
  141010. 1, -520986624, 1620377600, 4, 0,
  141011. _vq_quantlist__8u0__p7_1,
  141012. NULL,
  141013. &_vq_auxt__8u0__p7_1,
  141014. NULL,
  141015. 0
  141016. };
  141017. static long _vq_quantlist__8u0__p7_2[] = {
  141018. 10,
  141019. 9,
  141020. 11,
  141021. 8,
  141022. 12,
  141023. 7,
  141024. 13,
  141025. 6,
  141026. 14,
  141027. 5,
  141028. 15,
  141029. 4,
  141030. 16,
  141031. 3,
  141032. 17,
  141033. 2,
  141034. 18,
  141035. 1,
  141036. 19,
  141037. 0,
  141038. 20,
  141039. };
  141040. static long _vq_lengthlist__8u0__p7_2[] = {
  141041. 1, 6, 5, 7, 7, 9, 9, 9, 9,10,12,12,10,11,11,10,
  141042. 11,11,11,10,11, 6, 8, 8, 9, 9,10,10, 9,10,11,11,
  141043. 10,11,11,11,11,10,11,11,11,11, 6, 7, 8, 9, 9, 9,
  141044. 10,11,10,11,12,11,10,11,11,11,11,11,11,12,10, 8,
  141045. 9, 9,10, 9,10,10, 9,10,10,10,10,10, 9,10,10,10,
  141046. 10, 9,10,10, 9, 9, 9, 9,10,10, 9, 9,10,10,11,10,
  141047. 9,12,10,11,10, 9,10,10,10, 8, 9, 9,10, 9,10, 9,
  141048. 9,10,10, 9,10, 9,11,10,10,10,10,10, 9,10, 8, 8,
  141049. 9, 9,10, 9,11, 9, 8, 9, 9,10,11,10,10,10,11,12,
  141050. 9, 9,11, 8, 9, 8,11,10,11,10,10, 9,11,10,10,10,
  141051. 10,10,10,10,11,11,11,11, 8, 9, 9, 9,10,10,10,11,
  141052. 11,12,11,12,11,10,10,10,12,11,11,11,10, 8,10, 9,
  141053. 11,10,10,11,12,10,11,12,11,11,12,11,12,12,10,11,
  141054. 11,10, 9, 9,10,11,12,10,10,10,11,10,11,11,10,12,
  141055. 12,10,11,10,11,12,10, 9,10,10,11,10,11,11,11,11,
  141056. 11,12,11,11,11, 9,11,10,11,10,11,10, 9, 9,10,11,
  141057. 11,11,10,10,11,12,12,11,12,11,11,11,12,12,12,12,
  141058. 11, 9,11,11,12,10,11,11,11,11,11,11,12,11,11,12,
  141059. 11,11,11,10,11,11, 9,11,10,11,11,11,10,10,10,11,
  141060. 11,11,12,10,11,10,11,11,11,11,12, 9,11,10,11,11,
  141061. 10,10,11,11, 9,11,11,12,10,10,10,10,10,11,11,10,
  141062. 9,10,11,11,12,11,10,10,12,11,11,12,11,12,11,11,
  141063. 10,10,11,11,10,12,11,10,11,10,11,10,10,10,11,11,
  141064. 10,10,11,11,11,11,10,10,10,12,11,11,11,11,10, 9,
  141065. 10,11,11,11,12,11,11,11,12,10,11,11,11, 9,10,11,
  141066. 11,11,11,11,11,10,10,11,11,12,11,10,11,12,11,10,
  141067. 10,11, 9,10,11,11,11,11,11,10,11,11,10,12,11,11,
  141068. 11,12,11,11,11,10,10,11,11,
  141069. };
  141070. static float _vq_quantthresh__8u0__p7_2[] = {
  141071. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  141072. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  141073. 6.5, 7.5, 8.5, 9.5,
  141074. };
  141075. static long _vq_quantmap__8u0__p7_2[] = {
  141076. 19, 17, 15, 13, 11, 9, 7, 5,
  141077. 3, 1, 0, 2, 4, 6, 8, 10,
  141078. 12, 14, 16, 18, 20,
  141079. };
  141080. static encode_aux_threshmatch _vq_auxt__8u0__p7_2 = {
  141081. _vq_quantthresh__8u0__p7_2,
  141082. _vq_quantmap__8u0__p7_2,
  141083. 21,
  141084. 21
  141085. };
  141086. static static_codebook _8u0__p7_2 = {
  141087. 2, 441,
  141088. _vq_lengthlist__8u0__p7_2,
  141089. 1, -529268736, 1611661312, 5, 0,
  141090. _vq_quantlist__8u0__p7_2,
  141091. NULL,
  141092. &_vq_auxt__8u0__p7_2,
  141093. NULL,
  141094. 0
  141095. };
  141096. static long _huff_lengthlist__8u0__single[] = {
  141097. 4, 7,11, 9,12, 8, 7,10, 6, 4, 5, 5, 7, 5, 6,16,
  141098. 9, 5, 5, 6, 7, 7, 9,16, 7, 4, 6, 5, 7, 5, 7,17,
  141099. 10, 7, 7, 8, 7, 7, 8,18, 7, 5, 6, 4, 5, 4, 5,15,
  141100. 7, 6, 7, 5, 6, 4, 5,15,12,13,18,12,17,11, 9,17,
  141101. };
  141102. static static_codebook _huff_book__8u0__single = {
  141103. 2, 64,
  141104. _huff_lengthlist__8u0__single,
  141105. 0, 0, 0, 0, 0,
  141106. NULL,
  141107. NULL,
  141108. NULL,
  141109. NULL,
  141110. 0
  141111. };
  141112. static long _vq_quantlist__8u1__p1_0[] = {
  141113. 1,
  141114. 0,
  141115. 2,
  141116. };
  141117. static long _vq_lengthlist__8u1__p1_0[] = {
  141118. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 7, 9,10, 7,
  141119. 9, 9, 5, 8, 8, 7,10, 9, 7, 9, 9, 5, 8, 8, 8,10,
  141120. 10, 8,10,10, 7,10,10, 9,10,12,10,12,12, 7,10,10,
  141121. 9,12,11,10,12,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  141122. 10,10,10,12,12, 9,11,12, 7,10,10,10,12,12, 9,12,
  141123. 10,
  141124. };
  141125. static float _vq_quantthresh__8u1__p1_0[] = {
  141126. -0.5, 0.5,
  141127. };
  141128. static long _vq_quantmap__8u1__p1_0[] = {
  141129. 1, 0, 2,
  141130. };
  141131. static encode_aux_threshmatch _vq_auxt__8u1__p1_0 = {
  141132. _vq_quantthresh__8u1__p1_0,
  141133. _vq_quantmap__8u1__p1_0,
  141134. 3,
  141135. 3
  141136. };
  141137. static static_codebook _8u1__p1_0 = {
  141138. 4, 81,
  141139. _vq_lengthlist__8u1__p1_0,
  141140. 1, -535822336, 1611661312, 2, 0,
  141141. _vq_quantlist__8u1__p1_0,
  141142. NULL,
  141143. &_vq_auxt__8u1__p1_0,
  141144. NULL,
  141145. 0
  141146. };
  141147. static long _vq_quantlist__8u1__p2_0[] = {
  141148. 1,
  141149. 0,
  141150. 2,
  141151. };
  141152. static long _vq_lengthlist__8u1__p2_0[] = {
  141153. 3, 4, 5, 5, 6, 6, 5, 6, 6, 5, 7, 6, 6, 7, 8, 6,
  141154. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 7, 5, 6, 6, 7, 8,
  141155. 8, 6, 7, 7, 6, 8, 7, 7, 7, 9, 8, 9, 9, 6, 7, 8,
  141156. 7, 9, 7, 8, 9, 9, 5, 6, 6, 6, 7, 7, 7, 8, 8, 6,
  141157. 8, 7, 8, 9, 9, 7, 7, 9, 6, 7, 8, 8, 9, 9, 7, 9,
  141158. 7,
  141159. };
  141160. static float _vq_quantthresh__8u1__p2_0[] = {
  141161. -0.5, 0.5,
  141162. };
  141163. static long _vq_quantmap__8u1__p2_0[] = {
  141164. 1, 0, 2,
  141165. };
  141166. static encode_aux_threshmatch _vq_auxt__8u1__p2_0 = {
  141167. _vq_quantthresh__8u1__p2_0,
  141168. _vq_quantmap__8u1__p2_0,
  141169. 3,
  141170. 3
  141171. };
  141172. static static_codebook _8u1__p2_0 = {
  141173. 4, 81,
  141174. _vq_lengthlist__8u1__p2_0,
  141175. 1, -535822336, 1611661312, 2, 0,
  141176. _vq_quantlist__8u1__p2_0,
  141177. NULL,
  141178. &_vq_auxt__8u1__p2_0,
  141179. NULL,
  141180. 0
  141181. };
  141182. static long _vq_quantlist__8u1__p3_0[] = {
  141183. 2,
  141184. 1,
  141185. 3,
  141186. 0,
  141187. 4,
  141188. };
  141189. static long _vq_lengthlist__8u1__p3_0[] = {
  141190. 1, 5, 5, 7, 7, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  141191. 10, 9,11,11, 9, 9, 9,11,11, 6, 8, 8,10,10, 8,10,
  141192. 10,11,11, 8, 9,10,11,11,10,11,11,12,12,10,11,11,
  141193. 12,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10, 9,11,
  141194. 11,10,11,11,12,12,10,11,11,12,12, 9,11,11,14,13,
  141195. 10,12,11,14,14,10,12,11,14,13,12,13,13,15,14,12,
  141196. 13,13,15,14, 8,11,11,13,14,10,11,12,13,15,10,11,
  141197. 12,14,14,12,13,13,14,15,12,13,13,14,15, 5, 8, 8,
  141198. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  141199. 13,11,12,12,13,14, 8,10,10,12,12, 9,11,12,13,14,
  141200. 10,12,12,13,13,12,12,13,14,14,11,13,13,15,15, 7,
  141201. 10,10,12,12, 9,12,11,14,12,10,11,12,13,14,12,13,
  141202. 12,14,14,12,13,13,15,16,10,12,12,15,14,11,12,13,
  141203. 15,15,11,13,13,15,16,14,14,15,15,16,13,14,15,17,
  141204. 15, 9,12,12,14,15,11,13,12,15,15,11,13,13,15,15,
  141205. 13,14,13,15,14,13,14,14,17, 0, 5, 8, 8,11,11, 8,
  141206. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  141207. 12,14,14, 7,10,10,12,12,10,12,12,13,13, 9,11,12,
  141208. 12,13,11,12,13,15,15,11,12,13,14,15, 8,10,10,12,
  141209. 12,10,12,11,13,13,10,12,11,13,13,11,13,13,15,14,
  141210. 12,13,12,15,13, 9,12,12,14,14,11,13,13,16,15,11,
  141211. 12,13,16,15,13,14,15,16,16,13,13,15,15,16,10,12,
  141212. 12,15,14,11,13,13,14,16,11,13,13,15,16,13,15,15,
  141213. 16,17,13,15,14,16,15, 8,11,11,14,15,10,12,12,15,
  141214. 15,10,12,12,15,16,14,15,15,16,17,13,14,14,16,16,
  141215. 9,12,12,15,15,11,13,14,15,17,11,13,13,15,16,14,
  141216. 15,16,19,17,13,15,15, 0,17, 9,12,12,15,15,11,14,
  141217. 13,16,15,11,13,13,15,16,15,15,15,18,17,13,15,15,
  141218. 17,17,11,15,14,18,16,12,14,15,17,17,12,15,15,18,
  141219. 18,15,15,16,15,19,14,16,16, 0, 0,11,14,14,16,17,
  141220. 12,15,14,18,17,12,15,15,18,18,15,17,15,18,16,14,
  141221. 16,16,18,18, 7,11,11,14,14,10,12,12,15,15,10,12,
  141222. 13,15,15,13,14,15,16,16,14,15,15,18,18, 9,12,12,
  141223. 15,15,11,13,13,16,15,11,12,13,16,16,14,15,15,17,
  141224. 16,15,16,16,17,17, 9,12,12,15,15,11,13,13,15,17,
  141225. 11,14,13,16,15,13,15,15,17,17,15,15,15,18,17,11,
  141226. 14,14,17,15,12,14,15,17,18,13,13,15,17,17,14,16,
  141227. 16,19,18,16,15,17,17, 0,11,14,14,17,17,12,15,15,
  141228. 18, 0,12,15,14,18,16,14,17,17,19, 0,16,18,15, 0,
  141229. 16,
  141230. };
  141231. static float _vq_quantthresh__8u1__p3_0[] = {
  141232. -1.5, -0.5, 0.5, 1.5,
  141233. };
  141234. static long _vq_quantmap__8u1__p3_0[] = {
  141235. 3, 1, 0, 2, 4,
  141236. };
  141237. static encode_aux_threshmatch _vq_auxt__8u1__p3_0 = {
  141238. _vq_quantthresh__8u1__p3_0,
  141239. _vq_quantmap__8u1__p3_0,
  141240. 5,
  141241. 5
  141242. };
  141243. static static_codebook _8u1__p3_0 = {
  141244. 4, 625,
  141245. _vq_lengthlist__8u1__p3_0,
  141246. 1, -533725184, 1611661312, 3, 0,
  141247. _vq_quantlist__8u1__p3_0,
  141248. NULL,
  141249. &_vq_auxt__8u1__p3_0,
  141250. NULL,
  141251. 0
  141252. };
  141253. static long _vq_quantlist__8u1__p4_0[] = {
  141254. 2,
  141255. 1,
  141256. 3,
  141257. 0,
  141258. 4,
  141259. };
  141260. static long _vq_lengthlist__8u1__p4_0[] = {
  141261. 4, 5, 5, 9, 9, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 9,
  141262. 9, 9,11,11, 9, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 7,
  141263. 8, 9,10, 7, 7, 8, 9,10, 9, 9,10,10,11, 9, 9,10,
  141264. 10,12, 6, 7, 7, 9, 9, 7, 8, 7,10, 9, 7, 8, 7,10,
  141265. 9, 9,10, 9,12,11,10,10, 9,12,10, 9,10,10,12,11,
  141266. 9,10,10,12,11, 9,10,10,12,12,11,11,12,12,13,11,
  141267. 11,12,12,13, 9, 9,10,12,11, 9,10,10,12,12,10,10,
  141268. 10,12,12,11,12,11,13,12,11,12,11,13,12, 6, 7, 7,
  141269. 9, 9, 7, 8, 8,10,10, 7, 8, 7,10, 9,10,10,10,12,
  141270. 12,10,10,10,12,11, 7, 8, 7,10,10, 7, 7, 9,10,11,
  141271. 8, 9, 9,11,10,10,10,11,10,12,10,10,11,12,12, 7,
  141272. 8, 8,10,10, 7, 9, 8,11,10, 8, 8, 9,11,11,10,11,
  141273. 10,12,11,10,11,11,12,12, 9,10,10,12,12, 9,10,10,
  141274. 12,12,10,11,11,13,12,11,10,12,10,14,12,12,12,13,
  141275. 14, 9,10,10,12,12, 9,11,10,12,12,10,11,11,12,12,
  141276. 11,12,11,14,12,12,12,12,14,14, 5, 7, 7, 9, 9, 7,
  141277. 7, 7, 9,10, 7, 8, 8,10,10,10,10,10,11,11,10,10,
  141278. 10,12,12, 7, 8, 8,10,10, 8, 9, 8,11,10, 7, 8, 9,
  141279. 10,11,10,10,10,11,12,10,10,11,11,13, 6, 7, 8,10,
  141280. 10, 8, 9, 9,10,10, 7, 9, 7,11,10,10,11,10,12,12,
  141281. 10,11,10,12,10, 9,10,10,12,12,10,11,11,13,12, 9,
  141282. 10,10,12,12,12,12,12,14,13,11,11,12,11,14, 9,10,
  141283. 10,11,12,10,11,11,12,13, 9,10,10,12,12,12,12,12,
  141284. 14,13,11,12,10,14,11, 9, 9,10,11,12, 9,10,10,12,
  141285. 12, 9,10,10,12,12,12,12,12,14,14,11,12,12,13,12,
  141286. 9,10, 9,12,12, 9,10,11,12,13,10,11,10,13,11,12,
  141287. 12,13,13,14,12,12,12,13,13, 9,10,10,12,12,10,11,
  141288. 10,13,12,10,10,11,12,13,12,13,12,14,13,12,12,12,
  141289. 13,14,11,12,11,14,13,10,10,11,13,13,12,12,12,14,
  141290. 13,12,10,14,10,15,13,14,14,14,14,11,11,12,13,14,
  141291. 10,12,11,13,13,12,12,12,13,15,12,13,11,15,12,13,
  141292. 13,14,14,14, 9,10, 9,12,12, 9,10,10,12,12,10,10,
  141293. 10,12,12,11,11,12,12,13,12,12,12,14,14, 9,10,10,
  141294. 12,12,10,11,10,13,12,10,10,11,12,13,12,12,12,14,
  141295. 13,12,12,13,13,14, 9,10,10,12,13,10,10,11,11,12,
  141296. 9,11,10,13,12,12,12,12,13,14,12,13,12,14,13,11,
  141297. 12,11,13,13,12,13,12,14,13,10,11,12,13,13,13,13,
  141298. 13,14,15,12,11,14,12,14,11,11,12,12,13,12,12,12,
  141299. 13,14,10,12,10,14,13,13,13,13,14,15,12,14,11,15,
  141300. 10,
  141301. };
  141302. static float _vq_quantthresh__8u1__p4_0[] = {
  141303. -1.5, -0.5, 0.5, 1.5,
  141304. };
  141305. static long _vq_quantmap__8u1__p4_0[] = {
  141306. 3, 1, 0, 2, 4,
  141307. };
  141308. static encode_aux_threshmatch _vq_auxt__8u1__p4_0 = {
  141309. _vq_quantthresh__8u1__p4_0,
  141310. _vq_quantmap__8u1__p4_0,
  141311. 5,
  141312. 5
  141313. };
  141314. static static_codebook _8u1__p4_0 = {
  141315. 4, 625,
  141316. _vq_lengthlist__8u1__p4_0,
  141317. 1, -533725184, 1611661312, 3, 0,
  141318. _vq_quantlist__8u1__p4_0,
  141319. NULL,
  141320. &_vq_auxt__8u1__p4_0,
  141321. NULL,
  141322. 0
  141323. };
  141324. static long _vq_quantlist__8u1__p5_0[] = {
  141325. 4,
  141326. 3,
  141327. 5,
  141328. 2,
  141329. 6,
  141330. 1,
  141331. 7,
  141332. 0,
  141333. 8,
  141334. };
  141335. static long _vq_lengthlist__8u1__p5_0[] = {
  141336. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 5, 8, 7, 8, 8,
  141337. 10,10, 4, 6, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  141338. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 8, 8, 8,
  141339. 9, 9,10,10,12,11, 8, 8, 8, 9, 9,10,10,11,11, 9,
  141340. 10,10,11,11,11,11,13,12, 9,10,10,11,11,12,12,12,
  141341. 13,
  141342. };
  141343. static float _vq_quantthresh__8u1__p5_0[] = {
  141344. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  141345. };
  141346. static long _vq_quantmap__8u1__p5_0[] = {
  141347. 7, 5, 3, 1, 0, 2, 4, 6,
  141348. 8,
  141349. };
  141350. static encode_aux_threshmatch _vq_auxt__8u1__p5_0 = {
  141351. _vq_quantthresh__8u1__p5_0,
  141352. _vq_quantmap__8u1__p5_0,
  141353. 9,
  141354. 9
  141355. };
  141356. static static_codebook _8u1__p5_0 = {
  141357. 2, 81,
  141358. _vq_lengthlist__8u1__p5_0,
  141359. 1, -531628032, 1611661312, 4, 0,
  141360. _vq_quantlist__8u1__p5_0,
  141361. NULL,
  141362. &_vq_auxt__8u1__p5_0,
  141363. NULL,
  141364. 0
  141365. };
  141366. static long _vq_quantlist__8u1__p6_0[] = {
  141367. 4,
  141368. 3,
  141369. 5,
  141370. 2,
  141371. 6,
  141372. 1,
  141373. 7,
  141374. 0,
  141375. 8,
  141376. };
  141377. static long _vq_lengthlist__8u1__p6_0[] = {
  141378. 3, 4, 4, 6, 6, 7, 7, 9, 9, 4, 4, 5, 6, 6, 7, 7,
  141379. 9, 9, 4, 4, 4, 6, 6, 7, 7, 9, 9, 6, 6, 6, 7, 7,
  141380. 8, 8, 9, 9, 6, 6, 6, 7, 7, 8, 8, 9, 9, 7, 7, 7,
  141381. 8, 8, 8, 9,10,10, 7, 7, 7, 8, 8, 9, 8,10,10, 9,
  141382. 9, 9, 9, 9,10,10,10,10, 9, 9, 9, 9, 9,10,10,10,
  141383. 10,
  141384. };
  141385. static float _vq_quantthresh__8u1__p6_0[] = {
  141386. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  141387. };
  141388. static long _vq_quantmap__8u1__p6_0[] = {
  141389. 7, 5, 3, 1, 0, 2, 4, 6,
  141390. 8,
  141391. };
  141392. static encode_aux_threshmatch _vq_auxt__8u1__p6_0 = {
  141393. _vq_quantthresh__8u1__p6_0,
  141394. _vq_quantmap__8u1__p6_0,
  141395. 9,
  141396. 9
  141397. };
  141398. static static_codebook _8u1__p6_0 = {
  141399. 2, 81,
  141400. _vq_lengthlist__8u1__p6_0,
  141401. 1, -531628032, 1611661312, 4, 0,
  141402. _vq_quantlist__8u1__p6_0,
  141403. NULL,
  141404. &_vq_auxt__8u1__p6_0,
  141405. NULL,
  141406. 0
  141407. };
  141408. static long _vq_quantlist__8u1__p7_0[] = {
  141409. 1,
  141410. 0,
  141411. 2,
  141412. };
  141413. static long _vq_lengthlist__8u1__p7_0[] = {
  141414. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 9, 8,10,10, 8,
  141415. 10,10, 5, 9, 9, 7,10,10, 8,10,10, 4,10,10, 9,12,
  141416. 12, 9,11,11, 7,12,11,10,11,13,10,13,13, 7,12,12,
  141417. 10,13,12,10,13,13, 4,10,10, 9,12,12, 9,12,12, 7,
  141418. 12,12,10,13,13,10,12,13, 7,11,12,10,13,13,10,13,
  141419. 11,
  141420. };
  141421. static float _vq_quantthresh__8u1__p7_0[] = {
  141422. -5.5, 5.5,
  141423. };
  141424. static long _vq_quantmap__8u1__p7_0[] = {
  141425. 1, 0, 2,
  141426. };
  141427. static encode_aux_threshmatch _vq_auxt__8u1__p7_0 = {
  141428. _vq_quantthresh__8u1__p7_0,
  141429. _vq_quantmap__8u1__p7_0,
  141430. 3,
  141431. 3
  141432. };
  141433. static static_codebook _8u1__p7_0 = {
  141434. 4, 81,
  141435. _vq_lengthlist__8u1__p7_0,
  141436. 1, -529137664, 1618345984, 2, 0,
  141437. _vq_quantlist__8u1__p7_0,
  141438. NULL,
  141439. &_vq_auxt__8u1__p7_0,
  141440. NULL,
  141441. 0
  141442. };
  141443. static long _vq_quantlist__8u1__p7_1[] = {
  141444. 5,
  141445. 4,
  141446. 6,
  141447. 3,
  141448. 7,
  141449. 2,
  141450. 8,
  141451. 1,
  141452. 9,
  141453. 0,
  141454. 10,
  141455. };
  141456. static long _vq_lengthlist__8u1__p7_1[] = {
  141457. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 7,
  141458. 8, 8, 9, 9, 9, 9, 4, 5, 5, 7, 7, 8, 8, 9, 9, 9,
  141459. 9, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  141460. 8, 8, 8, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  141461. 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 9, 9,
  141462. 9, 9, 9, 9,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  141463. 10,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10, 8, 9,
  141464. 9, 9, 9, 9, 9,10,10,10,10,
  141465. };
  141466. static float _vq_quantthresh__8u1__p7_1[] = {
  141467. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  141468. 3.5, 4.5,
  141469. };
  141470. static long _vq_quantmap__8u1__p7_1[] = {
  141471. 9, 7, 5, 3, 1, 0, 2, 4,
  141472. 6, 8, 10,
  141473. };
  141474. static encode_aux_threshmatch _vq_auxt__8u1__p7_1 = {
  141475. _vq_quantthresh__8u1__p7_1,
  141476. _vq_quantmap__8u1__p7_1,
  141477. 11,
  141478. 11
  141479. };
  141480. static static_codebook _8u1__p7_1 = {
  141481. 2, 121,
  141482. _vq_lengthlist__8u1__p7_1,
  141483. 1, -531365888, 1611661312, 4, 0,
  141484. _vq_quantlist__8u1__p7_1,
  141485. NULL,
  141486. &_vq_auxt__8u1__p7_1,
  141487. NULL,
  141488. 0
  141489. };
  141490. static long _vq_quantlist__8u1__p8_0[] = {
  141491. 5,
  141492. 4,
  141493. 6,
  141494. 3,
  141495. 7,
  141496. 2,
  141497. 8,
  141498. 1,
  141499. 9,
  141500. 0,
  141501. 10,
  141502. };
  141503. static long _vq_lengthlist__8u1__p8_0[] = {
  141504. 1, 4, 4, 6, 6, 8, 8,10,10,11,11, 4, 6, 6, 7, 7,
  141505. 9, 9,11,11,13,12, 4, 6, 6, 7, 7, 9, 9,11,11,12,
  141506. 12, 6, 7, 7, 9, 9,11,11,12,12,13,13, 6, 7, 7, 9,
  141507. 9,11,11,12,12,13,13, 8, 9, 9,11,11,12,12,13,13,
  141508. 14,14, 8, 9, 9,11,11,12,12,13,13,14,14, 9,11,11,
  141509. 12,12,13,13,14,14,15,15, 9,11,11,12,12,13,13,14,
  141510. 14,15,14,11,12,12,13,13,14,14,15,15,16,16,11,12,
  141511. 12,13,13,14,14,15,15,15,15,
  141512. };
  141513. static float _vq_quantthresh__8u1__p8_0[] = {
  141514. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  141515. 38.5, 49.5,
  141516. };
  141517. static long _vq_quantmap__8u1__p8_0[] = {
  141518. 9, 7, 5, 3, 1, 0, 2, 4,
  141519. 6, 8, 10,
  141520. };
  141521. static encode_aux_threshmatch _vq_auxt__8u1__p8_0 = {
  141522. _vq_quantthresh__8u1__p8_0,
  141523. _vq_quantmap__8u1__p8_0,
  141524. 11,
  141525. 11
  141526. };
  141527. static static_codebook _8u1__p8_0 = {
  141528. 2, 121,
  141529. _vq_lengthlist__8u1__p8_0,
  141530. 1, -524582912, 1618345984, 4, 0,
  141531. _vq_quantlist__8u1__p8_0,
  141532. NULL,
  141533. &_vq_auxt__8u1__p8_0,
  141534. NULL,
  141535. 0
  141536. };
  141537. static long _vq_quantlist__8u1__p8_1[] = {
  141538. 5,
  141539. 4,
  141540. 6,
  141541. 3,
  141542. 7,
  141543. 2,
  141544. 8,
  141545. 1,
  141546. 9,
  141547. 0,
  141548. 10,
  141549. };
  141550. static long _vq_lengthlist__8u1__p8_1[] = {
  141551. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 5, 6, 6, 7, 7,
  141552. 7, 7, 8, 8, 8, 8, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8,
  141553. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  141554. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  141555. 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  141556. 8, 8, 8, 8, 9, 8, 9, 9, 7, 8, 8, 8, 8, 8, 8, 9,
  141557. 8, 9, 9, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8,
  141558. 8, 8, 8, 8, 8, 9, 9, 9, 9,
  141559. };
  141560. static float _vq_quantthresh__8u1__p8_1[] = {
  141561. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  141562. 3.5, 4.5,
  141563. };
  141564. static long _vq_quantmap__8u1__p8_1[] = {
  141565. 9, 7, 5, 3, 1, 0, 2, 4,
  141566. 6, 8, 10,
  141567. };
  141568. static encode_aux_threshmatch _vq_auxt__8u1__p8_1 = {
  141569. _vq_quantthresh__8u1__p8_1,
  141570. _vq_quantmap__8u1__p8_1,
  141571. 11,
  141572. 11
  141573. };
  141574. static static_codebook _8u1__p8_1 = {
  141575. 2, 121,
  141576. _vq_lengthlist__8u1__p8_1,
  141577. 1, -531365888, 1611661312, 4, 0,
  141578. _vq_quantlist__8u1__p8_1,
  141579. NULL,
  141580. &_vq_auxt__8u1__p8_1,
  141581. NULL,
  141582. 0
  141583. };
  141584. static long _vq_quantlist__8u1__p9_0[] = {
  141585. 7,
  141586. 6,
  141587. 8,
  141588. 5,
  141589. 9,
  141590. 4,
  141591. 10,
  141592. 3,
  141593. 11,
  141594. 2,
  141595. 12,
  141596. 1,
  141597. 13,
  141598. 0,
  141599. 14,
  141600. };
  141601. static long _vq_lengthlist__8u1__p9_0[] = {
  141602. 1, 4, 4,11,11,11,11,11,11,11,11,11,11,11,11, 3,
  141603. 11, 8,11,11,11,11,11,11,11,11,11,11,11,11, 3, 9,
  141604. 9,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141605. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141606. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141607. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141608. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141609. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141610. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141611. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141612. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141613. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141614. 11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,
  141615. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  141616. 10,
  141617. };
  141618. static float _vq_quantthresh__8u1__p9_0[] = {
  141619. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  141620. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  141621. };
  141622. static long _vq_quantmap__8u1__p9_0[] = {
  141623. 13, 11, 9, 7, 5, 3, 1, 0,
  141624. 2, 4, 6, 8, 10, 12, 14,
  141625. };
  141626. static encode_aux_threshmatch _vq_auxt__8u1__p9_0 = {
  141627. _vq_quantthresh__8u1__p9_0,
  141628. _vq_quantmap__8u1__p9_0,
  141629. 15,
  141630. 15
  141631. };
  141632. static static_codebook _8u1__p9_0 = {
  141633. 2, 225,
  141634. _vq_lengthlist__8u1__p9_0,
  141635. 1, -514071552, 1627381760, 4, 0,
  141636. _vq_quantlist__8u1__p9_0,
  141637. NULL,
  141638. &_vq_auxt__8u1__p9_0,
  141639. NULL,
  141640. 0
  141641. };
  141642. static long _vq_quantlist__8u1__p9_1[] = {
  141643. 7,
  141644. 6,
  141645. 8,
  141646. 5,
  141647. 9,
  141648. 4,
  141649. 10,
  141650. 3,
  141651. 11,
  141652. 2,
  141653. 12,
  141654. 1,
  141655. 13,
  141656. 0,
  141657. 14,
  141658. };
  141659. static long _vq_lengthlist__8u1__p9_1[] = {
  141660. 1, 4, 4, 7, 7, 9, 9, 7, 7, 8, 8,10,10,11,11, 4,
  141661. 7, 7, 9, 9,10,10, 8, 8,10,10,10,11,10,11, 4, 7,
  141662. 7, 9, 9,10,10, 8, 8,10, 9,11,11,11,11, 7, 9, 9,
  141663. 12,12,11,12,10,10,11,10,12,11,11,11, 7, 9, 9,11,
  141664. 11,13,12, 9, 9,11,10,11,11,12,11, 9,10,10,12,12,
  141665. 14,14,10,10,11,12,12,11,11,11, 9,10,11,11,13,14,
  141666. 13,10,11,11,11,12,11,12,12, 7, 8, 8,10, 9,11,10,
  141667. 11,12,12,11,12,14,12,13, 7, 8, 8, 9,10,10,11,12,
  141668. 12,12,11,12,12,12,13, 9, 9, 9,11,11,13,12,12,12,
  141669. 12,11,12,12,13,12, 8,10,10,11,10,11,12,12,12,12,
  141670. 12,12,14,12,12, 9,11,11,11,12,12,12,12,13,13,12,
  141671. 12,13,13,12,10,11,11,12,11,12,12,12,11,12,13,12,
  141672. 12,12,13,11,11,12,12,12,13,12,12,11,12,13,13,12,
  141673. 12,13,12,11,12,12,13,13,12,13,12,13,13,13,13,14,
  141674. 13,
  141675. };
  141676. static float _vq_quantthresh__8u1__p9_1[] = {
  141677. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  141678. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  141679. };
  141680. static long _vq_quantmap__8u1__p9_1[] = {
  141681. 13, 11, 9, 7, 5, 3, 1, 0,
  141682. 2, 4, 6, 8, 10, 12, 14,
  141683. };
  141684. static encode_aux_threshmatch _vq_auxt__8u1__p9_1 = {
  141685. _vq_quantthresh__8u1__p9_1,
  141686. _vq_quantmap__8u1__p9_1,
  141687. 15,
  141688. 15
  141689. };
  141690. static static_codebook _8u1__p9_1 = {
  141691. 2, 225,
  141692. _vq_lengthlist__8u1__p9_1,
  141693. 1, -522338304, 1620115456, 4, 0,
  141694. _vq_quantlist__8u1__p9_1,
  141695. NULL,
  141696. &_vq_auxt__8u1__p9_1,
  141697. NULL,
  141698. 0
  141699. };
  141700. static long _vq_quantlist__8u1__p9_2[] = {
  141701. 8,
  141702. 7,
  141703. 9,
  141704. 6,
  141705. 10,
  141706. 5,
  141707. 11,
  141708. 4,
  141709. 12,
  141710. 3,
  141711. 13,
  141712. 2,
  141713. 14,
  141714. 1,
  141715. 15,
  141716. 0,
  141717. 16,
  141718. };
  141719. static long _vq_lengthlist__8u1__p9_2[] = {
  141720. 2, 5, 4, 6, 6, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  141721. 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  141722. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  141723. 9, 9, 9, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  141724. 9,10,10, 9, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  141725. 9, 9, 9,10,10, 8, 8, 8, 9, 9, 9, 9,10,10,10, 9,
  141726. 10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  141727. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,10,
  141728. 10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,10,10,
  141729. 10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,
  141730. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  141731. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,10,
  141732. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  141733. 9,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  141734. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,10,
  141735. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  141736. 10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  141737. 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  141738. 10,
  141739. };
  141740. static float _vq_quantthresh__8u1__p9_2[] = {
  141741. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  141742. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  141743. };
  141744. static long _vq_quantmap__8u1__p9_2[] = {
  141745. 15, 13, 11, 9, 7, 5, 3, 1,
  141746. 0, 2, 4, 6, 8, 10, 12, 14,
  141747. 16,
  141748. };
  141749. static encode_aux_threshmatch _vq_auxt__8u1__p9_2 = {
  141750. _vq_quantthresh__8u1__p9_2,
  141751. _vq_quantmap__8u1__p9_2,
  141752. 17,
  141753. 17
  141754. };
  141755. static static_codebook _8u1__p9_2 = {
  141756. 2, 289,
  141757. _vq_lengthlist__8u1__p9_2,
  141758. 1, -529530880, 1611661312, 5, 0,
  141759. _vq_quantlist__8u1__p9_2,
  141760. NULL,
  141761. &_vq_auxt__8u1__p9_2,
  141762. NULL,
  141763. 0
  141764. };
  141765. static long _huff_lengthlist__8u1__single[] = {
  141766. 4, 7,13, 9,15, 9,16, 8,10,13, 7, 5, 8, 6, 9, 7,
  141767. 10, 7,10,11,11, 6, 7, 8, 8, 9, 9, 9,12,16, 8, 5,
  141768. 8, 6, 8, 6, 9, 7,10,12,11, 7, 7, 7, 6, 7, 7, 7,
  141769. 11,15, 7, 5, 8, 6, 7, 5, 7, 6, 9,13,13, 9, 9, 8,
  141770. 6, 6, 5, 5, 9,14, 8, 6, 8, 6, 6, 4, 5, 3, 5,13,
  141771. 9, 9,11, 8,10, 7, 8, 4, 5,12,11,16,17,15,17,12,
  141772. 13, 8, 8,15,
  141773. };
  141774. static static_codebook _huff_book__8u1__single = {
  141775. 2, 100,
  141776. _huff_lengthlist__8u1__single,
  141777. 0, 0, 0, 0, 0,
  141778. NULL,
  141779. NULL,
  141780. NULL,
  141781. NULL,
  141782. 0
  141783. };
  141784. static long _huff_lengthlist__44u0__long[] = {
  141785. 5, 8,13,10,17,11,11,15, 7, 2, 4, 5, 8, 7, 9,16,
  141786. 13, 4, 3, 5, 6, 8,11,20,10, 4, 5, 5, 7, 6, 8,18,
  141787. 15, 7, 6, 7, 8,10,14,20,10, 6, 7, 6, 9, 7, 8,17,
  141788. 9, 8,10, 8,10, 5, 4,11,12,17,19,14,16,10, 7,12,
  141789. };
  141790. static static_codebook _huff_book__44u0__long = {
  141791. 2, 64,
  141792. _huff_lengthlist__44u0__long,
  141793. 0, 0, 0, 0, 0,
  141794. NULL,
  141795. NULL,
  141796. NULL,
  141797. NULL,
  141798. 0
  141799. };
  141800. static long _vq_quantlist__44u0__p1_0[] = {
  141801. 1,
  141802. 0,
  141803. 2,
  141804. };
  141805. static long _vq_lengthlist__44u0__p1_0[] = {
  141806. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  141807. 10,10, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  141808. 11, 8,11,11, 8,12,11,11,13,13,11,13,14, 7,11,11,
  141809. 10,13,12,11,13,14, 4, 8, 8, 8,11,11, 8,11,12, 8,
  141810. 11,11,11,13,13,10,12,13, 8,11,11,11,14,13,11,14,
  141811. 13,
  141812. };
  141813. static float _vq_quantthresh__44u0__p1_0[] = {
  141814. -0.5, 0.5,
  141815. };
  141816. static long _vq_quantmap__44u0__p1_0[] = {
  141817. 1, 0, 2,
  141818. };
  141819. static encode_aux_threshmatch _vq_auxt__44u0__p1_0 = {
  141820. _vq_quantthresh__44u0__p1_0,
  141821. _vq_quantmap__44u0__p1_0,
  141822. 3,
  141823. 3
  141824. };
  141825. static static_codebook _44u0__p1_0 = {
  141826. 4, 81,
  141827. _vq_lengthlist__44u0__p1_0,
  141828. 1, -535822336, 1611661312, 2, 0,
  141829. _vq_quantlist__44u0__p1_0,
  141830. NULL,
  141831. &_vq_auxt__44u0__p1_0,
  141832. NULL,
  141833. 0
  141834. };
  141835. static long _vq_quantlist__44u0__p2_0[] = {
  141836. 1,
  141837. 0,
  141838. 2,
  141839. };
  141840. static long _vq_lengthlist__44u0__p2_0[] = {
  141841. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  141842. 8, 8, 5, 7, 7, 6, 8, 8, 7, 8, 8, 4, 7, 7, 7, 8,
  141843. 8, 7, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  141844. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 8, 6,
  141845. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  141846. 9,
  141847. };
  141848. static float _vq_quantthresh__44u0__p2_0[] = {
  141849. -0.5, 0.5,
  141850. };
  141851. static long _vq_quantmap__44u0__p2_0[] = {
  141852. 1, 0, 2,
  141853. };
  141854. static encode_aux_threshmatch _vq_auxt__44u0__p2_0 = {
  141855. _vq_quantthresh__44u0__p2_0,
  141856. _vq_quantmap__44u0__p2_0,
  141857. 3,
  141858. 3
  141859. };
  141860. static static_codebook _44u0__p2_0 = {
  141861. 4, 81,
  141862. _vq_lengthlist__44u0__p2_0,
  141863. 1, -535822336, 1611661312, 2, 0,
  141864. _vq_quantlist__44u0__p2_0,
  141865. NULL,
  141866. &_vq_auxt__44u0__p2_0,
  141867. NULL,
  141868. 0
  141869. };
  141870. static long _vq_quantlist__44u0__p3_0[] = {
  141871. 2,
  141872. 1,
  141873. 3,
  141874. 0,
  141875. 4,
  141876. };
  141877. static long _vq_lengthlist__44u0__p3_0[] = {
  141878. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  141879. 10, 9,12,12, 9, 9,10,12,12, 6, 8, 8,11,10, 8,10,
  141880. 10,11,11, 8, 9,10,11,11,10,11,11,14,13,10,11,11,
  141881. 13,13, 5, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  141882. 11,10,11,11,13,13,10,11,11,13,13, 9,11,11,15,14,
  141883. 10,12,12,15,14,10,12,11,15,14,13,14,14,16,16,12,
  141884. 14,13,17,15, 9,11,11,14,15,10,11,12,14,16,10,11,
  141885. 12,14,16,12,13,14,16,16,13,13,15,15,18, 5, 8, 8,
  141886. 11,11, 8,10,10,12,12, 8,10,10,12,13,11,12,12,14,
  141887. 14,11,12,12,15,15, 8,10,10,13,13,10,12,12,13,13,
  141888. 10,12,12,14,14,12,13,13,15,15,12,13,13,16,16, 7,
  141889. 10,10,12,12,10,12,11,13,13,10,12,12,13,14,12,13,
  141890. 12,15,14,12,13,13,16,16,10,12,12,17,16,12,13,13,
  141891. 16,15,11,13,13,17,17,15,15,15,16,17,14,15,15,19,
  141892. 19,10,12,12,15,16,11,13,12,15,18,11,13,13,16,16,
  141893. 14,15,15,17,17,14,15,15,17,19, 5, 8, 8,11,11, 8,
  141894. 10,10,12,12, 8,10,10,12,12,11,12,12,16,15,11,12,
  141895. 12,14,15, 7,10,10,13,13,10,12,12,14,13,10,11,12,
  141896. 13,13,12,13,13,16,16,12,12,13,15,15, 8,10,10,13,
  141897. 13,10,12,12,14,14,10,12,12,13,13,12,13,13,16,16,
  141898. 12,13,13,15,15,10,12,12,16,15,11,13,13,17,16,11,
  141899. 12,13,16,15,13,15,15,19,17,14,15,14,17,16,10,12,
  141900. 12,16,16,11,13,13,16,17,12,13,13,15,17,14,15,15,
  141901. 17,19,14,15,15,17,17, 8,11,11,16,16,10,13,12,17,
  141902. 17,10,12,13,16,16,15,17,16,20,19,14,15,17,18,19,
  141903. 9,12,12,16,17,11,13,14,17,18,11,13,13,19,18,16,
  141904. 17,18,19,19,15,16,16,19,19, 9,12,12,16,17,11,14,
  141905. 13,18,17,11,13,13,17,17,16,17,16,20,19,14,16,16,
  141906. 18,18,12,15,15,19,17,14,15,16, 0,20,13,15,16,20,
  141907. 17,18,16,20, 0, 0,15,16,19,20, 0,12,15,14,18,19,
  141908. 13,16,15,20,19,13,16,15,20,18,17,18,17, 0,20,16,
  141909. 17,16, 0, 0, 8,11,11,16,15,10,12,12,17,17,10,13,
  141910. 13,17,16,14,16,15,18,20,15,16,16,19,19, 9,12,12,
  141911. 16,16,11,13,13,17,16,11,13,14,17,18,15,15,16,20,
  141912. 20,16,16,17,19,19, 9,13,12,16,17,11,14,13,17,17,
  141913. 11,14,14,18,17,14,16,15,18,19,16,17,18,18,19,12,
  141914. 14,15,19,18,13,15,16,18, 0,13,14,15, 0, 0,16,16,
  141915. 17,20, 0,17,17,20,20, 0,12,15,15,19,20,13,15,15,
  141916. 0, 0,14,16,15, 0, 0,15,18,16, 0, 0,17,18,16, 0,
  141917. 19,
  141918. };
  141919. static float _vq_quantthresh__44u0__p3_0[] = {
  141920. -1.5, -0.5, 0.5, 1.5,
  141921. };
  141922. static long _vq_quantmap__44u0__p3_0[] = {
  141923. 3, 1, 0, 2, 4,
  141924. };
  141925. static encode_aux_threshmatch _vq_auxt__44u0__p3_0 = {
  141926. _vq_quantthresh__44u0__p3_0,
  141927. _vq_quantmap__44u0__p3_0,
  141928. 5,
  141929. 5
  141930. };
  141931. static static_codebook _44u0__p3_0 = {
  141932. 4, 625,
  141933. _vq_lengthlist__44u0__p3_0,
  141934. 1, -533725184, 1611661312, 3, 0,
  141935. _vq_quantlist__44u0__p3_0,
  141936. NULL,
  141937. &_vq_auxt__44u0__p3_0,
  141938. NULL,
  141939. 0
  141940. };
  141941. static long _vq_quantlist__44u0__p4_0[] = {
  141942. 2,
  141943. 1,
  141944. 3,
  141945. 0,
  141946. 4,
  141947. };
  141948. static long _vq_lengthlist__44u0__p4_0[] = {
  141949. 4, 5, 5, 9, 9, 5, 6, 6, 9, 9, 5, 6, 6, 9, 9, 9,
  141950. 10, 9,12,12, 9, 9,10,12,12, 5, 7, 7,10,10, 7, 7,
  141951. 8,10,10, 6, 7, 8,10,10,10,10,10,11,13,10, 9,10,
  141952. 12,13, 5, 7, 7,10,10, 6, 8, 7,10,10, 7, 8, 7,10,
  141953. 10, 9,10,10,12,12,10,10,10,13,11, 9,10,10,13,13,
  141954. 10,11,10,13,13,10,10,10,13,13,12,12,13,14,14,12,
  141955. 12,13,14,14, 9,10,10,13,13,10,10,10,13,13,10,10,
  141956. 10,13,13,12,13,12,15,14,12,13,12,15,15, 5, 7, 6,
  141957. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,13,
  141958. 13,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,10,11,
  141959. 8, 9, 9,11,11,11,10,11,11,14,11,11,11,13,13, 6,
  141960. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  141961. 10,14,11,10,11,11,13,13,10,11,11,14,13,10,10,11,
  141962. 14,13,10,11,11,14,14,12,11,13,12,16,13,14,14,15,
  141963. 15,10,10,11,13,14,10,11,10,14,13,10,11,11,14,14,
  141964. 12,13,12,15,13,13,13,14,15,16, 5, 7, 7,10,10, 7,
  141965. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,13,13,10,10,
  141966. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  141967. 10,11,10,11,11,13,13,10,10,11,11,13, 6, 8, 8,10,
  141968. 11, 8, 9, 9,11,11, 8, 9, 8,12,10,10,11,11,13,13,
  141969. 10,11,10,14,11,10,10,10,14,13,10,11,11,14,13,10,
  141970. 10,11,13,13,12,14,14,16,16,12,12,13,13,15,10,11,
  141971. 11,13,14,10,11,11,14,15,10,11,10,13,13,13,14,13,
  141972. 16,16,12,13,11,15,12, 9,10,10,13,13,10,11,11,14,
  141973. 13,10,10,11,13,14,13,14,13,16,16,13,13,13,15,16,
  141974. 9,10,10,13,13,10,10,11,13,14,10,11,11,15,13,13,
  141975. 13,14,14,18,13,13,14,16,15, 9,10,10,13,14,10,11,
  141976. 10,14,13,10,11,11,13,14,13,14,13,16,15,13,13,14,
  141977. 15,16,12,13,12,16,14,11,11,13,15,15,13,14,13,16,
  141978. 15,15,12,16,12,17,14,15,15,17,17,12,13,13,14,16,
  141979. 11,13,11,16,15,12,13,14,15,16,14,15,13, 0,14,14,
  141980. 16,16, 0, 0, 9,10,10,13,13,10,11,10,14,14,10,11,
  141981. 11,13,13,12,13,13,14,16,13,14,14,16,16, 9,10,10,
  141982. 14,14,11,11,11,14,13,10,10,11,14,14,13,13,13,16,
  141983. 16,13,13,14,14,17, 9,10,10,13,14,10,11,11,13,15,
  141984. 10,11,10,14,14,13,13,13,14,17,13,14,13,17,14,12,
  141985. 13,13,16,14,13,14,13,16,15,12,12,13,15,16,15,15,
  141986. 16,18,16,15,13,15,14, 0,12,12,13,14,16,13,13,14,
  141987. 15,16,11,12,11,16,14,15,16,16,17,17,14,15,12,17,
  141988. 12,
  141989. };
  141990. static float _vq_quantthresh__44u0__p4_0[] = {
  141991. -1.5, -0.5, 0.5, 1.5,
  141992. };
  141993. static long _vq_quantmap__44u0__p4_0[] = {
  141994. 3, 1, 0, 2, 4,
  141995. };
  141996. static encode_aux_threshmatch _vq_auxt__44u0__p4_0 = {
  141997. _vq_quantthresh__44u0__p4_0,
  141998. _vq_quantmap__44u0__p4_0,
  141999. 5,
  142000. 5
  142001. };
  142002. static static_codebook _44u0__p4_0 = {
  142003. 4, 625,
  142004. _vq_lengthlist__44u0__p4_0,
  142005. 1, -533725184, 1611661312, 3, 0,
  142006. _vq_quantlist__44u0__p4_0,
  142007. NULL,
  142008. &_vq_auxt__44u0__p4_0,
  142009. NULL,
  142010. 0
  142011. };
  142012. static long _vq_quantlist__44u0__p5_0[] = {
  142013. 4,
  142014. 3,
  142015. 5,
  142016. 2,
  142017. 6,
  142018. 1,
  142019. 7,
  142020. 0,
  142021. 8,
  142022. };
  142023. static long _vq_lengthlist__44u0__p5_0[] = {
  142024. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  142025. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  142026. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,10, 7, 8, 8,
  142027. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  142028. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,11,11,11,12,
  142029. 12,
  142030. };
  142031. static float _vq_quantthresh__44u0__p5_0[] = {
  142032. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  142033. };
  142034. static long _vq_quantmap__44u0__p5_0[] = {
  142035. 7, 5, 3, 1, 0, 2, 4, 6,
  142036. 8,
  142037. };
  142038. static encode_aux_threshmatch _vq_auxt__44u0__p5_0 = {
  142039. _vq_quantthresh__44u0__p5_0,
  142040. _vq_quantmap__44u0__p5_0,
  142041. 9,
  142042. 9
  142043. };
  142044. static static_codebook _44u0__p5_0 = {
  142045. 2, 81,
  142046. _vq_lengthlist__44u0__p5_0,
  142047. 1, -531628032, 1611661312, 4, 0,
  142048. _vq_quantlist__44u0__p5_0,
  142049. NULL,
  142050. &_vq_auxt__44u0__p5_0,
  142051. NULL,
  142052. 0
  142053. };
  142054. static long _vq_quantlist__44u0__p6_0[] = {
  142055. 6,
  142056. 5,
  142057. 7,
  142058. 4,
  142059. 8,
  142060. 3,
  142061. 9,
  142062. 2,
  142063. 10,
  142064. 1,
  142065. 11,
  142066. 0,
  142067. 12,
  142068. };
  142069. static long _vq_lengthlist__44u0__p6_0[] = {
  142070. 1, 4, 4, 6, 6, 8, 8,10, 9,11,10,14,13, 4, 6, 5,
  142071. 8, 8, 9, 9,11,10,11,11,14,14, 4, 5, 6, 8, 8, 9,
  142072. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  142073. 12,12,16,15, 7, 8, 8, 9, 9,10,10,11,11,12,12,15,
  142074. 15, 9,10,10,10,10,11,11,12,12,12,12,15,15, 9,10,
  142075. 9,10,11,11,11,12,12,12,13,15,15,10,10,11,11,11,
  142076. 12,12,13,12,13,13,16,15,10,11,11,11,11,12,12,13,
  142077. 12,13,13,16,17,11,11,12,12,12,13,13,13,14,14,15,
  142078. 17,17,11,11,12,12,12,13,13,13,14,14,14,16,18,14,
  142079. 15,15,15,15,16,16,16,16,17,18, 0, 0,14,15,15,15,
  142080. 15,17,16,17,18,17,17,18, 0,
  142081. };
  142082. static float _vq_quantthresh__44u0__p6_0[] = {
  142083. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  142084. 12.5, 17.5, 22.5, 27.5,
  142085. };
  142086. static long _vq_quantmap__44u0__p6_0[] = {
  142087. 11, 9, 7, 5, 3, 1, 0, 2,
  142088. 4, 6, 8, 10, 12,
  142089. };
  142090. static encode_aux_threshmatch _vq_auxt__44u0__p6_0 = {
  142091. _vq_quantthresh__44u0__p6_0,
  142092. _vq_quantmap__44u0__p6_0,
  142093. 13,
  142094. 13
  142095. };
  142096. static static_codebook _44u0__p6_0 = {
  142097. 2, 169,
  142098. _vq_lengthlist__44u0__p6_0,
  142099. 1, -526516224, 1616117760, 4, 0,
  142100. _vq_quantlist__44u0__p6_0,
  142101. NULL,
  142102. &_vq_auxt__44u0__p6_0,
  142103. NULL,
  142104. 0
  142105. };
  142106. static long _vq_quantlist__44u0__p6_1[] = {
  142107. 2,
  142108. 1,
  142109. 3,
  142110. 0,
  142111. 4,
  142112. };
  142113. static long _vq_lengthlist__44u0__p6_1[] = {
  142114. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  142115. 6, 6, 6, 6, 5, 6, 6, 6, 6,
  142116. };
  142117. static float _vq_quantthresh__44u0__p6_1[] = {
  142118. -1.5, -0.5, 0.5, 1.5,
  142119. };
  142120. static long _vq_quantmap__44u0__p6_1[] = {
  142121. 3, 1, 0, 2, 4,
  142122. };
  142123. static encode_aux_threshmatch _vq_auxt__44u0__p6_1 = {
  142124. _vq_quantthresh__44u0__p6_1,
  142125. _vq_quantmap__44u0__p6_1,
  142126. 5,
  142127. 5
  142128. };
  142129. static static_codebook _44u0__p6_1 = {
  142130. 2, 25,
  142131. _vq_lengthlist__44u0__p6_1,
  142132. 1, -533725184, 1611661312, 3, 0,
  142133. _vq_quantlist__44u0__p6_1,
  142134. NULL,
  142135. &_vq_auxt__44u0__p6_1,
  142136. NULL,
  142137. 0
  142138. };
  142139. static long _vq_quantlist__44u0__p7_0[] = {
  142140. 2,
  142141. 1,
  142142. 3,
  142143. 0,
  142144. 4,
  142145. };
  142146. static long _vq_lengthlist__44u0__p7_0[] = {
  142147. 1, 4, 4,11,11, 9,11,11,11,11,11,11,11,11,11,11,
  142148. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142149. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142150. 11,11, 9,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142151. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142152. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142153. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142154. 11,11,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
  142155. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142156. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142157. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142158. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142159. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142160. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142161. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142162. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142163. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142164. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142165. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142166. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142167. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142168. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142169. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142170. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142171. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142172. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142173. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142174. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142175. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142176. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142177. 11,11,11,11,11,11,10,10,10,10,10,10,10,10,10,10,
  142178. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  142179. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  142180. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  142181. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  142182. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  142183. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  142184. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  142185. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  142186. 10,
  142187. };
  142188. static float _vq_quantthresh__44u0__p7_0[] = {
  142189. -253.5, -84.5, 84.5, 253.5,
  142190. };
  142191. static long _vq_quantmap__44u0__p7_0[] = {
  142192. 3, 1, 0, 2, 4,
  142193. };
  142194. static encode_aux_threshmatch _vq_auxt__44u0__p7_0 = {
  142195. _vq_quantthresh__44u0__p7_0,
  142196. _vq_quantmap__44u0__p7_0,
  142197. 5,
  142198. 5
  142199. };
  142200. static static_codebook _44u0__p7_0 = {
  142201. 4, 625,
  142202. _vq_lengthlist__44u0__p7_0,
  142203. 1, -518709248, 1626677248, 3, 0,
  142204. _vq_quantlist__44u0__p7_0,
  142205. NULL,
  142206. &_vq_auxt__44u0__p7_0,
  142207. NULL,
  142208. 0
  142209. };
  142210. static long _vq_quantlist__44u0__p7_1[] = {
  142211. 6,
  142212. 5,
  142213. 7,
  142214. 4,
  142215. 8,
  142216. 3,
  142217. 9,
  142218. 2,
  142219. 10,
  142220. 1,
  142221. 11,
  142222. 0,
  142223. 12,
  142224. };
  142225. static long _vq_lengthlist__44u0__p7_1[] = {
  142226. 1, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 9, 9, 5, 7, 7,
  142227. 8, 7, 7, 7, 9, 8,10, 9,10,11, 5, 7, 7, 8, 8, 7,
  142228. 7, 8, 9,10,10,11,11, 6, 8, 8, 9, 9, 9, 9,11,10,
  142229. 12,12,15,12, 6, 8, 8, 9, 9, 9, 9,11,11,12,11,14,
  142230. 12, 7, 8, 8,10,10,12,12,13,13,13,15,13,13, 7, 8,
  142231. 8,10,10,11,11,13,12,14,15,15,15, 9,10,10,11,12,
  142232. 13,13,14,15,14,15,14,15, 8,10,10,12,12,14,14,15,
  142233. 14,14,15,15,14,10,12,12,14,14,15,14,15,15,15,14,
  142234. 15,15,10,12,12,13,14,15,14,15,15,14,15,15,15,12,
  142235. 15,13,15,14,15,15,15,15,15,15,15,15,13,13,15,15,
  142236. 15,15,15,15,15,15,15,15,15,
  142237. };
  142238. static float _vq_quantthresh__44u0__p7_1[] = {
  142239. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  142240. 32.5, 45.5, 58.5, 71.5,
  142241. };
  142242. static long _vq_quantmap__44u0__p7_1[] = {
  142243. 11, 9, 7, 5, 3, 1, 0, 2,
  142244. 4, 6, 8, 10, 12,
  142245. };
  142246. static encode_aux_threshmatch _vq_auxt__44u0__p7_1 = {
  142247. _vq_quantthresh__44u0__p7_1,
  142248. _vq_quantmap__44u0__p7_1,
  142249. 13,
  142250. 13
  142251. };
  142252. static static_codebook _44u0__p7_1 = {
  142253. 2, 169,
  142254. _vq_lengthlist__44u0__p7_1,
  142255. 1, -523010048, 1618608128, 4, 0,
  142256. _vq_quantlist__44u0__p7_1,
  142257. NULL,
  142258. &_vq_auxt__44u0__p7_1,
  142259. NULL,
  142260. 0
  142261. };
  142262. static long _vq_quantlist__44u0__p7_2[] = {
  142263. 6,
  142264. 5,
  142265. 7,
  142266. 4,
  142267. 8,
  142268. 3,
  142269. 9,
  142270. 2,
  142271. 10,
  142272. 1,
  142273. 11,
  142274. 0,
  142275. 12,
  142276. };
  142277. static long _vq_lengthlist__44u0__p7_2[] = {
  142278. 2, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 5, 5, 6,
  142279. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 5, 6, 5, 7, 7, 8,
  142280. 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8, 8, 8, 8, 9, 8,
  142281. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  142282. 9, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 7, 8,
  142283. 8, 9, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 9, 8, 9, 9,
  142284. 9, 9, 9, 9, 9, 9,10,10, 8, 8, 9, 9, 9, 9, 9, 9,
  142285. 9, 9,10, 9,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  142286. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  142287. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  142288. 9, 9, 9,10, 9, 9,10,10, 9,
  142289. };
  142290. static float _vq_quantthresh__44u0__p7_2[] = {
  142291. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  142292. 2.5, 3.5, 4.5, 5.5,
  142293. };
  142294. static long _vq_quantmap__44u0__p7_2[] = {
  142295. 11, 9, 7, 5, 3, 1, 0, 2,
  142296. 4, 6, 8, 10, 12,
  142297. };
  142298. static encode_aux_threshmatch _vq_auxt__44u0__p7_2 = {
  142299. _vq_quantthresh__44u0__p7_2,
  142300. _vq_quantmap__44u0__p7_2,
  142301. 13,
  142302. 13
  142303. };
  142304. static static_codebook _44u0__p7_2 = {
  142305. 2, 169,
  142306. _vq_lengthlist__44u0__p7_2,
  142307. 1, -531103744, 1611661312, 4, 0,
  142308. _vq_quantlist__44u0__p7_2,
  142309. NULL,
  142310. &_vq_auxt__44u0__p7_2,
  142311. NULL,
  142312. 0
  142313. };
  142314. static long _huff_lengthlist__44u0__short[] = {
  142315. 12,13,14,13,17,12,15,17, 5, 5, 6,10,10,11,15,16,
  142316. 4, 3, 3, 7, 5, 7,10,16, 7, 7, 7,10, 9,11,12,16,
  142317. 6, 5, 5, 9, 5, 6,10,16, 8, 7, 7, 9, 6, 7, 9,16,
  142318. 11, 7, 3, 6, 4, 5, 8,16,12, 9, 4, 8, 5, 7, 9,16,
  142319. };
  142320. static static_codebook _huff_book__44u0__short = {
  142321. 2, 64,
  142322. _huff_lengthlist__44u0__short,
  142323. 0, 0, 0, 0, 0,
  142324. NULL,
  142325. NULL,
  142326. NULL,
  142327. NULL,
  142328. 0
  142329. };
  142330. static long _huff_lengthlist__44u1__long[] = {
  142331. 5, 8,13,10,17,11,11,15, 7, 2, 4, 5, 8, 7, 9,16,
  142332. 13, 4, 3, 5, 6, 8,11,20,10, 4, 5, 5, 7, 6, 8,18,
  142333. 15, 7, 6, 7, 8,10,14,20,10, 6, 7, 6, 9, 7, 8,17,
  142334. 9, 8,10, 8,10, 5, 4,11,12,17,19,14,16,10, 7,12,
  142335. };
  142336. static static_codebook _huff_book__44u1__long = {
  142337. 2, 64,
  142338. _huff_lengthlist__44u1__long,
  142339. 0, 0, 0, 0, 0,
  142340. NULL,
  142341. NULL,
  142342. NULL,
  142343. NULL,
  142344. 0
  142345. };
  142346. static long _vq_quantlist__44u1__p1_0[] = {
  142347. 1,
  142348. 0,
  142349. 2,
  142350. };
  142351. static long _vq_lengthlist__44u1__p1_0[] = {
  142352. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  142353. 10,10, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  142354. 11, 8,11,11, 8,12,11,11,13,13,11,13,14, 7,11,11,
  142355. 10,13,12,11,13,14, 4, 8, 8, 8,11,11, 8,11,12, 8,
  142356. 11,11,11,13,13,10,12,13, 8,11,11,11,14,13,11,14,
  142357. 13,
  142358. };
  142359. static float _vq_quantthresh__44u1__p1_0[] = {
  142360. -0.5, 0.5,
  142361. };
  142362. static long _vq_quantmap__44u1__p1_0[] = {
  142363. 1, 0, 2,
  142364. };
  142365. static encode_aux_threshmatch _vq_auxt__44u1__p1_0 = {
  142366. _vq_quantthresh__44u1__p1_0,
  142367. _vq_quantmap__44u1__p1_0,
  142368. 3,
  142369. 3
  142370. };
  142371. static static_codebook _44u1__p1_0 = {
  142372. 4, 81,
  142373. _vq_lengthlist__44u1__p1_0,
  142374. 1, -535822336, 1611661312, 2, 0,
  142375. _vq_quantlist__44u1__p1_0,
  142376. NULL,
  142377. &_vq_auxt__44u1__p1_0,
  142378. NULL,
  142379. 0
  142380. };
  142381. static long _vq_quantlist__44u1__p2_0[] = {
  142382. 1,
  142383. 0,
  142384. 2,
  142385. };
  142386. static long _vq_lengthlist__44u1__p2_0[] = {
  142387. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  142388. 8, 8, 5, 7, 7, 6, 8, 8, 7, 8, 8, 4, 7, 7, 7, 8,
  142389. 8, 7, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  142390. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 8, 6,
  142391. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  142392. 9,
  142393. };
  142394. static float _vq_quantthresh__44u1__p2_0[] = {
  142395. -0.5, 0.5,
  142396. };
  142397. static long _vq_quantmap__44u1__p2_0[] = {
  142398. 1, 0, 2,
  142399. };
  142400. static encode_aux_threshmatch _vq_auxt__44u1__p2_0 = {
  142401. _vq_quantthresh__44u1__p2_0,
  142402. _vq_quantmap__44u1__p2_0,
  142403. 3,
  142404. 3
  142405. };
  142406. static static_codebook _44u1__p2_0 = {
  142407. 4, 81,
  142408. _vq_lengthlist__44u1__p2_0,
  142409. 1, -535822336, 1611661312, 2, 0,
  142410. _vq_quantlist__44u1__p2_0,
  142411. NULL,
  142412. &_vq_auxt__44u1__p2_0,
  142413. NULL,
  142414. 0
  142415. };
  142416. static long _vq_quantlist__44u1__p3_0[] = {
  142417. 2,
  142418. 1,
  142419. 3,
  142420. 0,
  142421. 4,
  142422. };
  142423. static long _vq_lengthlist__44u1__p3_0[] = {
  142424. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  142425. 10, 9,12,12, 9, 9,10,12,12, 6, 8, 8,11,10, 8,10,
  142426. 10,11,11, 8, 9,10,11,11,10,11,11,14,13,10,11,11,
  142427. 13,13, 5, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  142428. 11,10,11,11,13,13,10,11,11,13,13, 9,11,11,15,14,
  142429. 10,12,12,15,14,10,12,11,15,14,13,14,14,16,16,12,
  142430. 14,13,17,15, 9,11,11,14,15,10,11,12,14,16,10,11,
  142431. 12,14,16,12,13,14,16,16,13,13,15,15,18, 5, 8, 8,
  142432. 11,11, 8,10,10,12,12, 8,10,10,12,13,11,12,12,14,
  142433. 14,11,12,12,15,15, 8,10,10,13,13,10,12,12,13,13,
  142434. 10,12,12,14,14,12,13,13,15,15,12,13,13,16,16, 7,
  142435. 10,10,12,12,10,12,11,13,13,10,12,12,13,14,12,13,
  142436. 12,15,14,12,13,13,16,16,10,12,12,17,16,12,13,13,
  142437. 16,15,11,13,13,17,17,15,15,15,16,17,14,15,15,19,
  142438. 19,10,12,12,15,16,11,13,12,15,18,11,13,13,16,16,
  142439. 14,15,15,17,17,14,15,15,17,19, 5, 8, 8,11,11, 8,
  142440. 10,10,12,12, 8,10,10,12,12,11,12,12,16,15,11,12,
  142441. 12,14,15, 7,10,10,13,13,10,12,12,14,13,10,11,12,
  142442. 13,13,12,13,13,16,16,12,12,13,15,15, 8,10,10,13,
  142443. 13,10,12,12,14,14,10,12,12,13,13,12,13,13,16,16,
  142444. 12,13,13,15,15,10,12,12,16,15,11,13,13,17,16,11,
  142445. 12,13,16,15,13,15,15,19,17,14,15,14,17,16,10,12,
  142446. 12,16,16,11,13,13,16,17,12,13,13,15,17,14,15,15,
  142447. 17,19,14,15,15,17,17, 8,11,11,16,16,10,13,12,17,
  142448. 17,10,12,13,16,16,15,17,16,20,19,14,15,17,18,19,
  142449. 9,12,12,16,17,11,13,14,17,18,11,13,13,19,18,16,
  142450. 17,18,19,19,15,16,16,19,19, 9,12,12,16,17,11,14,
  142451. 13,18,17,11,13,13,17,17,16,17,16,20,19,14,16,16,
  142452. 18,18,12,15,15,19,17,14,15,16, 0,20,13,15,16,20,
  142453. 17,18,16,20, 0, 0,15,16,19,20, 0,12,15,14,18,19,
  142454. 13,16,15,20,19,13,16,15,20,18,17,18,17, 0,20,16,
  142455. 17,16, 0, 0, 8,11,11,16,15,10,12,12,17,17,10,13,
  142456. 13,17,16,14,16,15,18,20,15,16,16,19,19, 9,12,12,
  142457. 16,16,11,13,13,17,16,11,13,14,17,18,15,15,16,20,
  142458. 20,16,16,17,19,19, 9,13,12,16,17,11,14,13,17,17,
  142459. 11,14,14,18,17,14,16,15,18,19,16,17,18,18,19,12,
  142460. 14,15,19,18,13,15,16,18, 0,13,14,15, 0, 0,16,16,
  142461. 17,20, 0,17,17,20,20, 0,12,15,15,19,20,13,15,15,
  142462. 0, 0,14,16,15, 0, 0,15,18,16, 0, 0,17,18,16, 0,
  142463. 19,
  142464. };
  142465. static float _vq_quantthresh__44u1__p3_0[] = {
  142466. -1.5, -0.5, 0.5, 1.5,
  142467. };
  142468. static long _vq_quantmap__44u1__p3_0[] = {
  142469. 3, 1, 0, 2, 4,
  142470. };
  142471. static encode_aux_threshmatch _vq_auxt__44u1__p3_0 = {
  142472. _vq_quantthresh__44u1__p3_0,
  142473. _vq_quantmap__44u1__p3_0,
  142474. 5,
  142475. 5
  142476. };
  142477. static static_codebook _44u1__p3_0 = {
  142478. 4, 625,
  142479. _vq_lengthlist__44u1__p3_0,
  142480. 1, -533725184, 1611661312, 3, 0,
  142481. _vq_quantlist__44u1__p3_0,
  142482. NULL,
  142483. &_vq_auxt__44u1__p3_0,
  142484. NULL,
  142485. 0
  142486. };
  142487. static long _vq_quantlist__44u1__p4_0[] = {
  142488. 2,
  142489. 1,
  142490. 3,
  142491. 0,
  142492. 4,
  142493. };
  142494. static long _vq_lengthlist__44u1__p4_0[] = {
  142495. 4, 5, 5, 9, 9, 5, 6, 6, 9, 9, 5, 6, 6, 9, 9, 9,
  142496. 10, 9,12,12, 9, 9,10,12,12, 5, 7, 7,10,10, 7, 7,
  142497. 8,10,10, 6, 7, 8,10,10,10,10,10,11,13,10, 9,10,
  142498. 12,13, 5, 7, 7,10,10, 6, 8, 7,10,10, 7, 8, 7,10,
  142499. 10, 9,10,10,12,12,10,10,10,13,11, 9,10,10,13,13,
  142500. 10,11,10,13,13,10,10,10,13,13,12,12,13,14,14,12,
  142501. 12,13,14,14, 9,10,10,13,13,10,10,10,13,13,10,10,
  142502. 10,13,13,12,13,12,15,14,12,13,12,15,15, 5, 7, 6,
  142503. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,13,
  142504. 13,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,10,11,
  142505. 8, 9, 9,11,11,11,10,11,11,14,11,11,11,13,13, 6,
  142506. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  142507. 10,14,11,10,11,11,13,13,10,11,11,14,13,10,10,11,
  142508. 14,13,10,11,11,14,14,12,11,13,12,16,13,14,14,15,
  142509. 15,10,10,11,13,14,10,11,10,14,13,10,11,11,14,14,
  142510. 12,13,12,15,13,13,13,14,15,16, 5, 7, 7,10,10, 7,
  142511. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,13,13,10,10,
  142512. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  142513. 10,11,10,11,11,13,13,10,10,11,11,13, 6, 8, 8,10,
  142514. 11, 8, 9, 9,11,11, 8, 9, 8,12,10,10,11,11,13,13,
  142515. 10,11,10,14,11,10,10,10,14,13,10,11,11,14,13,10,
  142516. 10,11,13,13,12,14,14,16,16,12,12,13,13,15,10,11,
  142517. 11,13,14,10,11,11,14,15,10,11,10,13,13,13,14,13,
  142518. 16,16,12,13,11,15,12, 9,10,10,13,13,10,11,11,14,
  142519. 13,10,10,11,13,14,13,14,13,16,16,13,13,13,15,16,
  142520. 9,10,10,13,13,10,10,11,13,14,10,11,11,15,13,13,
  142521. 13,14,14,18,13,13,14,16,15, 9,10,10,13,14,10,11,
  142522. 10,14,13,10,11,11,13,14,13,14,13,16,15,13,13,14,
  142523. 15,16,12,13,12,16,14,11,11,13,15,15,13,14,13,16,
  142524. 15,15,12,16,12,17,14,15,15,17,17,12,13,13,14,16,
  142525. 11,13,11,16,15,12,13,14,15,16,14,15,13, 0,14,14,
  142526. 16,16, 0, 0, 9,10,10,13,13,10,11,10,14,14,10,11,
  142527. 11,13,13,12,13,13,14,16,13,14,14,16,16, 9,10,10,
  142528. 14,14,11,11,11,14,13,10,10,11,14,14,13,13,13,16,
  142529. 16,13,13,14,14,17, 9,10,10,13,14,10,11,11,13,15,
  142530. 10,11,10,14,14,13,13,13,14,17,13,14,13,17,14,12,
  142531. 13,13,16,14,13,14,13,16,15,12,12,13,15,16,15,15,
  142532. 16,18,16,15,13,15,14, 0,12,12,13,14,16,13,13,14,
  142533. 15,16,11,12,11,16,14,15,16,16,17,17,14,15,12,17,
  142534. 12,
  142535. };
  142536. static float _vq_quantthresh__44u1__p4_0[] = {
  142537. -1.5, -0.5, 0.5, 1.5,
  142538. };
  142539. static long _vq_quantmap__44u1__p4_0[] = {
  142540. 3, 1, 0, 2, 4,
  142541. };
  142542. static encode_aux_threshmatch _vq_auxt__44u1__p4_0 = {
  142543. _vq_quantthresh__44u1__p4_0,
  142544. _vq_quantmap__44u1__p4_0,
  142545. 5,
  142546. 5
  142547. };
  142548. static static_codebook _44u1__p4_0 = {
  142549. 4, 625,
  142550. _vq_lengthlist__44u1__p4_0,
  142551. 1, -533725184, 1611661312, 3, 0,
  142552. _vq_quantlist__44u1__p4_0,
  142553. NULL,
  142554. &_vq_auxt__44u1__p4_0,
  142555. NULL,
  142556. 0
  142557. };
  142558. static long _vq_quantlist__44u1__p5_0[] = {
  142559. 4,
  142560. 3,
  142561. 5,
  142562. 2,
  142563. 6,
  142564. 1,
  142565. 7,
  142566. 0,
  142567. 8,
  142568. };
  142569. static long _vq_lengthlist__44u1__p5_0[] = {
  142570. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  142571. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  142572. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,10, 7, 8, 8,
  142573. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  142574. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,11,11,11,12,
  142575. 12,
  142576. };
  142577. static float _vq_quantthresh__44u1__p5_0[] = {
  142578. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  142579. };
  142580. static long _vq_quantmap__44u1__p5_0[] = {
  142581. 7, 5, 3, 1, 0, 2, 4, 6,
  142582. 8,
  142583. };
  142584. static encode_aux_threshmatch _vq_auxt__44u1__p5_0 = {
  142585. _vq_quantthresh__44u1__p5_0,
  142586. _vq_quantmap__44u1__p5_0,
  142587. 9,
  142588. 9
  142589. };
  142590. static static_codebook _44u1__p5_0 = {
  142591. 2, 81,
  142592. _vq_lengthlist__44u1__p5_0,
  142593. 1, -531628032, 1611661312, 4, 0,
  142594. _vq_quantlist__44u1__p5_0,
  142595. NULL,
  142596. &_vq_auxt__44u1__p5_0,
  142597. NULL,
  142598. 0
  142599. };
  142600. static long _vq_quantlist__44u1__p6_0[] = {
  142601. 6,
  142602. 5,
  142603. 7,
  142604. 4,
  142605. 8,
  142606. 3,
  142607. 9,
  142608. 2,
  142609. 10,
  142610. 1,
  142611. 11,
  142612. 0,
  142613. 12,
  142614. };
  142615. static long _vq_lengthlist__44u1__p6_0[] = {
  142616. 1, 4, 4, 6, 6, 8, 8,10, 9,11,10,14,13, 4, 6, 5,
  142617. 8, 8, 9, 9,11,10,11,11,14,14, 4, 5, 6, 8, 8, 9,
  142618. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  142619. 12,12,16,15, 7, 8, 8, 9, 9,10,10,11,11,12,12,15,
  142620. 15, 9,10,10,10,10,11,11,12,12,12,12,15,15, 9,10,
  142621. 9,10,11,11,11,12,12,12,13,15,15,10,10,11,11,11,
  142622. 12,12,13,12,13,13,16,15,10,11,11,11,11,12,12,13,
  142623. 12,13,13,16,17,11,11,12,12,12,13,13,13,14,14,15,
  142624. 17,17,11,11,12,12,12,13,13,13,14,14,14,16,18,14,
  142625. 15,15,15,15,16,16,16,16,17,18, 0, 0,14,15,15,15,
  142626. 15,17,16,17,18,17,17,18, 0,
  142627. };
  142628. static float _vq_quantthresh__44u1__p6_0[] = {
  142629. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  142630. 12.5, 17.5, 22.5, 27.5,
  142631. };
  142632. static long _vq_quantmap__44u1__p6_0[] = {
  142633. 11, 9, 7, 5, 3, 1, 0, 2,
  142634. 4, 6, 8, 10, 12,
  142635. };
  142636. static encode_aux_threshmatch _vq_auxt__44u1__p6_0 = {
  142637. _vq_quantthresh__44u1__p6_0,
  142638. _vq_quantmap__44u1__p6_0,
  142639. 13,
  142640. 13
  142641. };
  142642. static static_codebook _44u1__p6_0 = {
  142643. 2, 169,
  142644. _vq_lengthlist__44u1__p6_0,
  142645. 1, -526516224, 1616117760, 4, 0,
  142646. _vq_quantlist__44u1__p6_0,
  142647. NULL,
  142648. &_vq_auxt__44u1__p6_0,
  142649. NULL,
  142650. 0
  142651. };
  142652. static long _vq_quantlist__44u1__p6_1[] = {
  142653. 2,
  142654. 1,
  142655. 3,
  142656. 0,
  142657. 4,
  142658. };
  142659. static long _vq_lengthlist__44u1__p6_1[] = {
  142660. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  142661. 6, 6, 6, 6, 5, 6, 6, 6, 6,
  142662. };
  142663. static float _vq_quantthresh__44u1__p6_1[] = {
  142664. -1.5, -0.5, 0.5, 1.5,
  142665. };
  142666. static long _vq_quantmap__44u1__p6_1[] = {
  142667. 3, 1, 0, 2, 4,
  142668. };
  142669. static encode_aux_threshmatch _vq_auxt__44u1__p6_1 = {
  142670. _vq_quantthresh__44u1__p6_1,
  142671. _vq_quantmap__44u1__p6_1,
  142672. 5,
  142673. 5
  142674. };
  142675. static static_codebook _44u1__p6_1 = {
  142676. 2, 25,
  142677. _vq_lengthlist__44u1__p6_1,
  142678. 1, -533725184, 1611661312, 3, 0,
  142679. _vq_quantlist__44u1__p6_1,
  142680. NULL,
  142681. &_vq_auxt__44u1__p6_1,
  142682. NULL,
  142683. 0
  142684. };
  142685. static long _vq_quantlist__44u1__p7_0[] = {
  142686. 3,
  142687. 2,
  142688. 4,
  142689. 1,
  142690. 5,
  142691. 0,
  142692. 6,
  142693. };
  142694. static long _vq_lengthlist__44u1__p7_0[] = {
  142695. 1, 3, 2, 9, 9, 7, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  142696. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  142697. 9, 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  142698. 8,
  142699. };
  142700. static float _vq_quantthresh__44u1__p7_0[] = {
  142701. -422.5, -253.5, -84.5, 84.5, 253.5, 422.5,
  142702. };
  142703. static long _vq_quantmap__44u1__p7_0[] = {
  142704. 5, 3, 1, 0, 2, 4, 6,
  142705. };
  142706. static encode_aux_threshmatch _vq_auxt__44u1__p7_0 = {
  142707. _vq_quantthresh__44u1__p7_0,
  142708. _vq_quantmap__44u1__p7_0,
  142709. 7,
  142710. 7
  142711. };
  142712. static static_codebook _44u1__p7_0 = {
  142713. 2, 49,
  142714. _vq_lengthlist__44u1__p7_0,
  142715. 1, -518017024, 1626677248, 3, 0,
  142716. _vq_quantlist__44u1__p7_0,
  142717. NULL,
  142718. &_vq_auxt__44u1__p7_0,
  142719. NULL,
  142720. 0
  142721. };
  142722. static long _vq_quantlist__44u1__p7_1[] = {
  142723. 6,
  142724. 5,
  142725. 7,
  142726. 4,
  142727. 8,
  142728. 3,
  142729. 9,
  142730. 2,
  142731. 10,
  142732. 1,
  142733. 11,
  142734. 0,
  142735. 12,
  142736. };
  142737. static long _vq_lengthlist__44u1__p7_1[] = {
  142738. 1, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 9, 9, 5, 7, 7,
  142739. 8, 7, 7, 7, 9, 8,10, 9,10,11, 5, 7, 7, 8, 8, 7,
  142740. 7, 8, 9,10,10,11,11, 6, 8, 8, 9, 9, 9, 9,11,10,
  142741. 12,12,15,12, 6, 8, 8, 9, 9, 9, 9,11,11,12,11,14,
  142742. 12, 7, 8, 8,10,10,12,12,13,13,13,15,13,13, 7, 8,
  142743. 8,10,10,11,11,13,12,14,15,15,15, 9,10,10,11,12,
  142744. 13,13,14,15,14,15,14,15, 8,10,10,12,12,14,14,15,
  142745. 14,14,15,15,14,10,12,12,14,14,15,14,15,15,15,14,
  142746. 15,15,10,12,12,13,14,15,14,15,15,14,15,15,15,12,
  142747. 15,13,15,14,15,15,15,15,15,15,15,15,13,13,15,15,
  142748. 15,15,15,15,15,15,15,15,15,
  142749. };
  142750. static float _vq_quantthresh__44u1__p7_1[] = {
  142751. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  142752. 32.5, 45.5, 58.5, 71.5,
  142753. };
  142754. static long _vq_quantmap__44u1__p7_1[] = {
  142755. 11, 9, 7, 5, 3, 1, 0, 2,
  142756. 4, 6, 8, 10, 12,
  142757. };
  142758. static encode_aux_threshmatch _vq_auxt__44u1__p7_1 = {
  142759. _vq_quantthresh__44u1__p7_1,
  142760. _vq_quantmap__44u1__p7_1,
  142761. 13,
  142762. 13
  142763. };
  142764. static static_codebook _44u1__p7_1 = {
  142765. 2, 169,
  142766. _vq_lengthlist__44u1__p7_1,
  142767. 1, -523010048, 1618608128, 4, 0,
  142768. _vq_quantlist__44u1__p7_1,
  142769. NULL,
  142770. &_vq_auxt__44u1__p7_1,
  142771. NULL,
  142772. 0
  142773. };
  142774. static long _vq_quantlist__44u1__p7_2[] = {
  142775. 6,
  142776. 5,
  142777. 7,
  142778. 4,
  142779. 8,
  142780. 3,
  142781. 9,
  142782. 2,
  142783. 10,
  142784. 1,
  142785. 11,
  142786. 0,
  142787. 12,
  142788. };
  142789. static long _vq_lengthlist__44u1__p7_2[] = {
  142790. 2, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 5, 5, 6,
  142791. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 5, 6, 5, 7, 7, 8,
  142792. 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8, 8, 8, 8, 9, 8,
  142793. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  142794. 9, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 7, 8,
  142795. 8, 9, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 9, 8, 9, 9,
  142796. 9, 9, 9, 9, 9, 9,10,10, 8, 8, 9, 9, 9, 9, 9, 9,
  142797. 9, 9,10, 9,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  142798. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  142799. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  142800. 9, 9, 9,10, 9, 9,10,10, 9,
  142801. };
  142802. static float _vq_quantthresh__44u1__p7_2[] = {
  142803. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  142804. 2.5, 3.5, 4.5, 5.5,
  142805. };
  142806. static long _vq_quantmap__44u1__p7_2[] = {
  142807. 11, 9, 7, 5, 3, 1, 0, 2,
  142808. 4, 6, 8, 10, 12,
  142809. };
  142810. static encode_aux_threshmatch _vq_auxt__44u1__p7_2 = {
  142811. _vq_quantthresh__44u1__p7_2,
  142812. _vq_quantmap__44u1__p7_2,
  142813. 13,
  142814. 13
  142815. };
  142816. static static_codebook _44u1__p7_2 = {
  142817. 2, 169,
  142818. _vq_lengthlist__44u1__p7_2,
  142819. 1, -531103744, 1611661312, 4, 0,
  142820. _vq_quantlist__44u1__p7_2,
  142821. NULL,
  142822. &_vq_auxt__44u1__p7_2,
  142823. NULL,
  142824. 0
  142825. };
  142826. static long _huff_lengthlist__44u1__short[] = {
  142827. 12,13,14,13,17,12,15,17, 5, 5, 6,10,10,11,15,16,
  142828. 4, 3, 3, 7, 5, 7,10,16, 7, 7, 7,10, 9,11,12,16,
  142829. 6, 5, 5, 9, 5, 6,10,16, 8, 7, 7, 9, 6, 7, 9,16,
  142830. 11, 7, 3, 6, 4, 5, 8,16,12, 9, 4, 8, 5, 7, 9,16,
  142831. };
  142832. static static_codebook _huff_book__44u1__short = {
  142833. 2, 64,
  142834. _huff_lengthlist__44u1__short,
  142835. 0, 0, 0, 0, 0,
  142836. NULL,
  142837. NULL,
  142838. NULL,
  142839. NULL,
  142840. 0
  142841. };
  142842. static long _huff_lengthlist__44u2__long[] = {
  142843. 5, 9,14,12,15,13,10,13, 7, 4, 5, 6, 8, 7, 8,12,
  142844. 13, 4, 3, 5, 5, 6, 9,15,12, 6, 5, 6, 6, 6, 7,14,
  142845. 14, 7, 4, 6, 4, 6, 8,15,12, 6, 6, 5, 5, 5, 6,14,
  142846. 9, 7, 8, 6, 7, 5, 4,10,10,13,14,14,15,10, 6, 8,
  142847. };
  142848. static static_codebook _huff_book__44u2__long = {
  142849. 2, 64,
  142850. _huff_lengthlist__44u2__long,
  142851. 0, 0, 0, 0, 0,
  142852. NULL,
  142853. NULL,
  142854. NULL,
  142855. NULL,
  142856. 0
  142857. };
  142858. static long _vq_quantlist__44u2__p1_0[] = {
  142859. 1,
  142860. 0,
  142861. 2,
  142862. };
  142863. static long _vq_lengthlist__44u2__p1_0[] = {
  142864. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  142865. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  142866. 11, 8,11,11, 8,11,11,11,13,14,11,13,13, 7,11,11,
  142867. 10,13,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 8,
  142868. 11,11,11,14,13,10,12,13, 8,11,11,11,13,13,11,13,
  142869. 13,
  142870. };
  142871. static float _vq_quantthresh__44u2__p1_0[] = {
  142872. -0.5, 0.5,
  142873. };
  142874. static long _vq_quantmap__44u2__p1_0[] = {
  142875. 1, 0, 2,
  142876. };
  142877. static encode_aux_threshmatch _vq_auxt__44u2__p1_0 = {
  142878. _vq_quantthresh__44u2__p1_0,
  142879. _vq_quantmap__44u2__p1_0,
  142880. 3,
  142881. 3
  142882. };
  142883. static static_codebook _44u2__p1_0 = {
  142884. 4, 81,
  142885. _vq_lengthlist__44u2__p1_0,
  142886. 1, -535822336, 1611661312, 2, 0,
  142887. _vq_quantlist__44u2__p1_0,
  142888. NULL,
  142889. &_vq_auxt__44u2__p1_0,
  142890. NULL,
  142891. 0
  142892. };
  142893. static long _vq_quantlist__44u2__p2_0[] = {
  142894. 1,
  142895. 0,
  142896. 2,
  142897. };
  142898. static long _vq_lengthlist__44u2__p2_0[] = {
  142899. 2, 5, 5, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  142900. 8, 8, 5, 6, 6, 6, 8, 7, 7, 8, 8, 5, 6, 6, 7, 8,
  142901. 8, 6, 8, 8, 6, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  142902. 7,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  142903. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  142904. 9,
  142905. };
  142906. static float _vq_quantthresh__44u2__p2_0[] = {
  142907. -0.5, 0.5,
  142908. };
  142909. static long _vq_quantmap__44u2__p2_0[] = {
  142910. 1, 0, 2,
  142911. };
  142912. static encode_aux_threshmatch _vq_auxt__44u2__p2_0 = {
  142913. _vq_quantthresh__44u2__p2_0,
  142914. _vq_quantmap__44u2__p2_0,
  142915. 3,
  142916. 3
  142917. };
  142918. static static_codebook _44u2__p2_0 = {
  142919. 4, 81,
  142920. _vq_lengthlist__44u2__p2_0,
  142921. 1, -535822336, 1611661312, 2, 0,
  142922. _vq_quantlist__44u2__p2_0,
  142923. NULL,
  142924. &_vq_auxt__44u2__p2_0,
  142925. NULL,
  142926. 0
  142927. };
  142928. static long _vq_quantlist__44u2__p3_0[] = {
  142929. 2,
  142930. 1,
  142931. 3,
  142932. 0,
  142933. 4,
  142934. };
  142935. static long _vq_lengthlist__44u2__p3_0[] = {
  142936. 2, 4, 4, 7, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  142937. 9, 9,12,11, 8, 9, 9,11,12, 5, 7, 7,10,10, 7, 9,
  142938. 9,11,11, 7, 9, 9,10,11,10,11,11,13,13, 9,10,11,
  142939. 12,13, 5, 7, 7,10,10, 7, 9, 9,11,10, 7, 9, 9,11,
  142940. 11, 9,11,10,13,13,10,11,11,13,13, 8,10,10,14,13,
  142941. 10,11,11,15,14, 9,11,11,15,14,13,14,13,16,14,12,
  142942. 13,13,15,16, 8,10,10,13,14, 9,11,11,14,15,10,11,
  142943. 11,14,15,12,13,13,15,15,12,13,14,15,16, 5, 7, 7,
  142944. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,12,10,11,11,14,
  142945. 13,10,11,11,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  142946. 9,11,11,13,13,12,13,12,14,14,11,12,13,15,15, 7,
  142947. 9, 9,12,12, 8,11,10,13,12, 9,11,11,13,13,11,13,
  142948. 12,15,13,11,13,13,15,16, 9,12,11,15,15,11,12,12,
  142949. 16,15,11,12,13,16,16,13,14,15,16,15,13,15,15,17,
  142950. 17, 9,11,11,14,15,10,12,12,15,15,11,13,12,15,16,
  142951. 13,15,14,16,16,13,15,15,17,19, 5, 7, 7,10,10, 7,
  142952. 9, 9,12,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  142953. 11,13,14, 7, 9, 9,12,12, 9,11,11,13,13, 9,10,11,
  142954. 12,13,11,13,12,16,15,11,12,12,14,15, 7, 9, 9,12,
  142955. 12, 9,11,11,13,13, 9,11,11,13,12,11,13,12,15,16,
  142956. 12,13,13,15,14, 9,11,11,15,14,11,13,12,16,15,10,
  142957. 11,12,15,15,13,14,14,18,17,13,14,14,15,17,10,11,
  142958. 11,14,15,11,13,12,15,17,11,13,12,15,16,13,15,14,
  142959. 18,17,14,15,15,16,18, 7,10,10,14,14,10,12,12,15,
  142960. 15,10,12,12,15,15,14,15,15,18,17,13,15,15,16,16,
  142961. 9,11,11,16,15,11,13,13,16,18,11,13,13,16,16,15,
  142962. 16,16, 0, 0,14,15,16,18,17, 9,11,11,15,15,10,13,
  142963. 12,17,16,11,12,13,16,17,14,15,16,19,19,14,15,15,
  142964. 0,20,12,14,14, 0, 0,13,14,16,19,18,13,15,16,20,
  142965. 17,16,18, 0, 0, 0,15,16,17,18,19,11,14,14, 0,19,
  142966. 12,15,14,17,17,13,15,15, 0, 0,16,17,15,20,19,15,
  142967. 17,16,19, 0, 8,10,10,14,15,10,12,11,15,15,10,11,
  142968. 12,16,15,13,14,14,19,17,14,15,15, 0, 0, 9,11,11,
  142969. 16,15,11,13,13,17,16,10,12,13,16,17,14,15,15,18,
  142970. 18,14,15,16,20,19, 9,12,12, 0,15,11,13,13,16,17,
  142971. 11,13,13,19,17,14,16,16,18,17,15,16,16,17,19,11,
  142972. 14,14,18,18,13,14,15, 0, 0,12,14,15,19,18,15,16,
  142973. 19, 0,19,15,16,19,19,17,12,14,14,16,19,13,15,15,
  142974. 0,17,13,15,14,18,18,15,16,15, 0,18,16,17,17, 0,
  142975. 0,
  142976. };
  142977. static float _vq_quantthresh__44u2__p3_0[] = {
  142978. -1.5, -0.5, 0.5, 1.5,
  142979. };
  142980. static long _vq_quantmap__44u2__p3_0[] = {
  142981. 3, 1, 0, 2, 4,
  142982. };
  142983. static encode_aux_threshmatch _vq_auxt__44u2__p3_0 = {
  142984. _vq_quantthresh__44u2__p3_0,
  142985. _vq_quantmap__44u2__p3_0,
  142986. 5,
  142987. 5
  142988. };
  142989. static static_codebook _44u2__p3_0 = {
  142990. 4, 625,
  142991. _vq_lengthlist__44u2__p3_0,
  142992. 1, -533725184, 1611661312, 3, 0,
  142993. _vq_quantlist__44u2__p3_0,
  142994. NULL,
  142995. &_vq_auxt__44u2__p3_0,
  142996. NULL,
  142997. 0
  142998. };
  142999. static long _vq_quantlist__44u2__p4_0[] = {
  143000. 2,
  143001. 1,
  143002. 3,
  143003. 0,
  143004. 4,
  143005. };
  143006. static long _vq_lengthlist__44u2__p4_0[] = {
  143007. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  143008. 9, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  143009. 8,10,10, 7, 7, 8,10,10,10,10,10,11,12, 9,10,10,
  143010. 11,12, 5, 7, 7, 9, 9, 6, 8, 7,10,10, 7, 8, 8,10,
  143011. 10, 9,10,10,12,11, 9,10,10,12,11, 9,10,10,12,12,
  143012. 10,10,10,13,12, 9,10,10,12,13,12,12,12,14,14,11,
  143013. 12,12,13,14, 9,10,10,12,12, 9,10,10,12,13,10,10,
  143014. 10,12,13,11,12,12,14,13,12,12,12,14,13, 5, 7, 7,
  143015. 10, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  143016. 12,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  143017. 8, 9, 9,11,11,10,11,11,12,13,10,11,11,13,13, 6,
  143018. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  143019. 10,13,11,10,11,11,13,13, 9,10,10,13,13,10,11,11,
  143020. 13,13,10,11,11,14,13,12,11,13,12,15,12,13,13,15,
  143021. 15, 9,10,10,12,13,10,11,10,13,13,10,11,11,13,13,
  143022. 12,13,11,15,13,12,13,13,15,15, 5, 7, 7, 9,10, 7,
  143023. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,12,10,10,
  143024. 11,12,12, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  143025. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  143026. 11, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,11,13,13,
  143027. 10,11,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  143028. 10,11,13,13,12,13,13,15,15,12,11,13,12,14, 9,10,
  143029. 10,12,13,10,11,11,13,14,10,11,11,13,13,12,13,13,
  143030. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  143031. 13, 9,10,10,13,13,12,13,13,15,15,12,12,12,14,14,
  143032. 9,10,10,13,13,10,11,11,13,14,10,11,11,14,12,13,
  143033. 13,14,14,16,12,13,13,15,14, 9,10,10,13,13,10,11,
  143034. 10,14,13,10,11,11,13,14,12,14,13,16,14,13,13,13,
  143035. 14,15,11,13,12,15,14,11,12,13,14,15,12,13,13,16,
  143036. 15,14,12,15,12,16,14,15,15,17,16,11,12,12,14,15,
  143037. 11,13,11,15,14,12,13,13,15,16,13,15,12,17,13,14,
  143038. 15,15,16,16, 8, 9, 9,12,12, 9,10,10,13,13, 9,10,
  143039. 10,13,13,12,13,12,14,14,12,13,13,15,15, 9,10,10,
  143040. 13,13,10,11,11,14,13,10,10,11,13,14,12,13,13,15,
  143041. 14,12,12,14,14,16, 9,10,10,13,13,10,11,11,13,14,
  143042. 10,11,11,14,13,13,13,13,15,15,13,14,13,16,14,11,
  143043. 12,12,14,14,12,13,13,16,15,11,12,13,14,15,14,15,
  143044. 15,16,16,14,13,15,13,17,11,12,12,14,15,12,13,13,
  143045. 15,16,11,13,12,15,15,14,15,14,16,16,14,15,12,17,
  143046. 13,
  143047. };
  143048. static float _vq_quantthresh__44u2__p4_0[] = {
  143049. -1.5, -0.5, 0.5, 1.5,
  143050. };
  143051. static long _vq_quantmap__44u2__p4_0[] = {
  143052. 3, 1, 0, 2, 4,
  143053. };
  143054. static encode_aux_threshmatch _vq_auxt__44u2__p4_0 = {
  143055. _vq_quantthresh__44u2__p4_0,
  143056. _vq_quantmap__44u2__p4_0,
  143057. 5,
  143058. 5
  143059. };
  143060. static static_codebook _44u2__p4_0 = {
  143061. 4, 625,
  143062. _vq_lengthlist__44u2__p4_0,
  143063. 1, -533725184, 1611661312, 3, 0,
  143064. _vq_quantlist__44u2__p4_0,
  143065. NULL,
  143066. &_vq_auxt__44u2__p4_0,
  143067. NULL,
  143068. 0
  143069. };
  143070. static long _vq_quantlist__44u2__p5_0[] = {
  143071. 4,
  143072. 3,
  143073. 5,
  143074. 2,
  143075. 6,
  143076. 1,
  143077. 7,
  143078. 0,
  143079. 8,
  143080. };
  143081. static long _vq_lengthlist__44u2__p5_0[] = {
  143082. 1, 4, 4, 7, 7, 8, 8, 9, 9, 4, 6, 5, 8, 8, 8, 8,
  143083. 10,10, 4, 5, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  143084. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 8, 8, 8,
  143085. 9, 9,10,11,12,12, 8, 8, 8, 9, 9,10,10,12,12,10,
  143086. 10,10,11,11,12,12,13,13,10,10,10,11,11,12,12,13,
  143087. 13,
  143088. };
  143089. static float _vq_quantthresh__44u2__p5_0[] = {
  143090. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  143091. };
  143092. static long _vq_quantmap__44u2__p5_0[] = {
  143093. 7, 5, 3, 1, 0, 2, 4, 6,
  143094. 8,
  143095. };
  143096. static encode_aux_threshmatch _vq_auxt__44u2__p5_0 = {
  143097. _vq_quantthresh__44u2__p5_0,
  143098. _vq_quantmap__44u2__p5_0,
  143099. 9,
  143100. 9
  143101. };
  143102. static static_codebook _44u2__p5_0 = {
  143103. 2, 81,
  143104. _vq_lengthlist__44u2__p5_0,
  143105. 1, -531628032, 1611661312, 4, 0,
  143106. _vq_quantlist__44u2__p5_0,
  143107. NULL,
  143108. &_vq_auxt__44u2__p5_0,
  143109. NULL,
  143110. 0
  143111. };
  143112. static long _vq_quantlist__44u2__p6_0[] = {
  143113. 6,
  143114. 5,
  143115. 7,
  143116. 4,
  143117. 8,
  143118. 3,
  143119. 9,
  143120. 2,
  143121. 10,
  143122. 1,
  143123. 11,
  143124. 0,
  143125. 12,
  143126. };
  143127. static long _vq_lengthlist__44u2__p6_0[] = {
  143128. 1, 4, 4, 6, 6, 8, 8,10,10,11,11,14,13, 4, 6, 5,
  143129. 8, 8, 9, 9,11,10,12,11,15,14, 4, 5, 6, 8, 8, 9,
  143130. 9,11,11,11,11,14,14, 6, 8, 8,10, 9,11,11,11,11,
  143131. 12,12,15,15, 6, 8, 8, 9, 9,11,11,11,12,12,12,15,
  143132. 15, 8,10,10,11,11,11,11,12,12,13,13,15,16, 8,10,
  143133. 10,11,11,11,11,12,12,13,13,16,16,10,11,11,12,12,
  143134. 12,12,13,13,13,13,17,16,10,11,11,12,12,12,12,13,
  143135. 13,13,14,16,17,11,12,12,13,13,13,13,14,14,15,14,
  143136. 18,17,11,12,12,13,13,13,13,14,14,14,15,19,18,14,
  143137. 15,15,15,15,16,16,18,19,18,18, 0, 0,14,15,15,16,
  143138. 15,17,17,16,18,17,18, 0, 0,
  143139. };
  143140. static float _vq_quantthresh__44u2__p6_0[] = {
  143141. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  143142. 12.5, 17.5, 22.5, 27.5,
  143143. };
  143144. static long _vq_quantmap__44u2__p6_0[] = {
  143145. 11, 9, 7, 5, 3, 1, 0, 2,
  143146. 4, 6, 8, 10, 12,
  143147. };
  143148. static encode_aux_threshmatch _vq_auxt__44u2__p6_0 = {
  143149. _vq_quantthresh__44u2__p6_0,
  143150. _vq_quantmap__44u2__p6_0,
  143151. 13,
  143152. 13
  143153. };
  143154. static static_codebook _44u2__p6_0 = {
  143155. 2, 169,
  143156. _vq_lengthlist__44u2__p6_0,
  143157. 1, -526516224, 1616117760, 4, 0,
  143158. _vq_quantlist__44u2__p6_0,
  143159. NULL,
  143160. &_vq_auxt__44u2__p6_0,
  143161. NULL,
  143162. 0
  143163. };
  143164. static long _vq_quantlist__44u2__p6_1[] = {
  143165. 2,
  143166. 1,
  143167. 3,
  143168. 0,
  143169. 4,
  143170. };
  143171. static long _vq_lengthlist__44u2__p6_1[] = {
  143172. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  143173. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  143174. };
  143175. static float _vq_quantthresh__44u2__p6_1[] = {
  143176. -1.5, -0.5, 0.5, 1.5,
  143177. };
  143178. static long _vq_quantmap__44u2__p6_1[] = {
  143179. 3, 1, 0, 2, 4,
  143180. };
  143181. static encode_aux_threshmatch _vq_auxt__44u2__p6_1 = {
  143182. _vq_quantthresh__44u2__p6_1,
  143183. _vq_quantmap__44u2__p6_1,
  143184. 5,
  143185. 5
  143186. };
  143187. static static_codebook _44u2__p6_1 = {
  143188. 2, 25,
  143189. _vq_lengthlist__44u2__p6_1,
  143190. 1, -533725184, 1611661312, 3, 0,
  143191. _vq_quantlist__44u2__p6_1,
  143192. NULL,
  143193. &_vq_auxt__44u2__p6_1,
  143194. NULL,
  143195. 0
  143196. };
  143197. static long _vq_quantlist__44u2__p7_0[] = {
  143198. 4,
  143199. 3,
  143200. 5,
  143201. 2,
  143202. 6,
  143203. 1,
  143204. 7,
  143205. 0,
  143206. 8,
  143207. };
  143208. static long _vq_lengthlist__44u2__p7_0[] = {
  143209. 1, 3, 2,12,12,12,12,12,12, 4,12,12,12,12,12,12,
  143210. 12,12, 5,12,12,12,12,12,12,12,12,12,12,11,11,11,
  143211. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143212. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143213. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143214. 11,
  143215. };
  143216. static float _vq_quantthresh__44u2__p7_0[] = {
  143217. -591.5, -422.5, -253.5, -84.5, 84.5, 253.5, 422.5, 591.5,
  143218. };
  143219. static long _vq_quantmap__44u2__p7_0[] = {
  143220. 7, 5, 3, 1, 0, 2, 4, 6,
  143221. 8,
  143222. };
  143223. static encode_aux_threshmatch _vq_auxt__44u2__p7_0 = {
  143224. _vq_quantthresh__44u2__p7_0,
  143225. _vq_quantmap__44u2__p7_0,
  143226. 9,
  143227. 9
  143228. };
  143229. static static_codebook _44u2__p7_0 = {
  143230. 2, 81,
  143231. _vq_lengthlist__44u2__p7_0,
  143232. 1, -516612096, 1626677248, 4, 0,
  143233. _vq_quantlist__44u2__p7_0,
  143234. NULL,
  143235. &_vq_auxt__44u2__p7_0,
  143236. NULL,
  143237. 0
  143238. };
  143239. static long _vq_quantlist__44u2__p7_1[] = {
  143240. 6,
  143241. 5,
  143242. 7,
  143243. 4,
  143244. 8,
  143245. 3,
  143246. 9,
  143247. 2,
  143248. 10,
  143249. 1,
  143250. 11,
  143251. 0,
  143252. 12,
  143253. };
  143254. static long _vq_lengthlist__44u2__p7_1[] = {
  143255. 1, 4, 4, 7, 6, 7, 6, 8, 7, 9, 7, 9, 8, 4, 7, 6,
  143256. 8, 8, 9, 8,10, 9,10,10,11,11, 4, 7, 7, 8, 8, 8,
  143257. 8, 9,10,11,11,11,11, 6, 8, 8,10,10,10,10,11,11,
  143258. 12,12,12,12, 7, 8, 8,10,10,10,10,11,11,12,12,13,
  143259. 13, 7, 9, 9,11,10,12,12,13,13,14,13,14,14, 7, 9,
  143260. 9,10,11,11,12,13,13,13,13,16,14, 9,10,10,12,12,
  143261. 13,13,14,14,15,16,15,16, 9,10,10,12,12,12,13,14,
  143262. 14,14,15,16,15,10,12,12,13,13,15,13,16,16,15,17,
  143263. 17,17,10,11,11,12,14,14,14,15,15,17,17,15,17,11,
  143264. 12,12,14,14,14,15,15,15,17,16,17,17,10,12,12,13,
  143265. 14,14,14,17,15,17,17,17,17,
  143266. };
  143267. static float _vq_quantthresh__44u2__p7_1[] = {
  143268. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  143269. 32.5, 45.5, 58.5, 71.5,
  143270. };
  143271. static long _vq_quantmap__44u2__p7_1[] = {
  143272. 11, 9, 7, 5, 3, 1, 0, 2,
  143273. 4, 6, 8, 10, 12,
  143274. };
  143275. static encode_aux_threshmatch _vq_auxt__44u2__p7_1 = {
  143276. _vq_quantthresh__44u2__p7_1,
  143277. _vq_quantmap__44u2__p7_1,
  143278. 13,
  143279. 13
  143280. };
  143281. static static_codebook _44u2__p7_1 = {
  143282. 2, 169,
  143283. _vq_lengthlist__44u2__p7_1,
  143284. 1, -523010048, 1618608128, 4, 0,
  143285. _vq_quantlist__44u2__p7_1,
  143286. NULL,
  143287. &_vq_auxt__44u2__p7_1,
  143288. NULL,
  143289. 0
  143290. };
  143291. static long _vq_quantlist__44u2__p7_2[] = {
  143292. 6,
  143293. 5,
  143294. 7,
  143295. 4,
  143296. 8,
  143297. 3,
  143298. 9,
  143299. 2,
  143300. 10,
  143301. 1,
  143302. 11,
  143303. 0,
  143304. 12,
  143305. };
  143306. static long _vq_lengthlist__44u2__p7_2[] = {
  143307. 2, 5, 5, 6, 6, 7, 7, 8, 7, 8, 8, 8, 8, 5, 6, 6,
  143308. 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 5, 6, 6, 7, 7, 8,
  143309. 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7, 8, 8, 8, 8, 8,
  143310. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  143311. 9, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 7, 8,
  143312. 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 9,
  143313. 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  143314. 9, 9, 9, 9, 9, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143315. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8,
  143316. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9, 9,
  143317. 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143318. };
  143319. static float _vq_quantthresh__44u2__p7_2[] = {
  143320. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  143321. 2.5, 3.5, 4.5, 5.5,
  143322. };
  143323. static long _vq_quantmap__44u2__p7_2[] = {
  143324. 11, 9, 7, 5, 3, 1, 0, 2,
  143325. 4, 6, 8, 10, 12,
  143326. };
  143327. static encode_aux_threshmatch _vq_auxt__44u2__p7_2 = {
  143328. _vq_quantthresh__44u2__p7_2,
  143329. _vq_quantmap__44u2__p7_2,
  143330. 13,
  143331. 13
  143332. };
  143333. static static_codebook _44u2__p7_2 = {
  143334. 2, 169,
  143335. _vq_lengthlist__44u2__p7_2,
  143336. 1, -531103744, 1611661312, 4, 0,
  143337. _vq_quantlist__44u2__p7_2,
  143338. NULL,
  143339. &_vq_auxt__44u2__p7_2,
  143340. NULL,
  143341. 0
  143342. };
  143343. static long _huff_lengthlist__44u2__short[] = {
  143344. 13,15,17,17,15,15,12,17,11, 9, 7,10,10, 9,12,17,
  143345. 10, 6, 3, 6, 5, 7,10,17,15,10, 6, 9, 8, 9,11,17,
  143346. 15, 8, 4, 7, 3, 5, 9,16,16,10, 5, 8, 4, 5, 8,16,
  143347. 13,11, 5, 8, 3, 3, 5,14,13,12, 7,10, 5, 5, 7,14,
  143348. };
  143349. static static_codebook _huff_book__44u2__short = {
  143350. 2, 64,
  143351. _huff_lengthlist__44u2__short,
  143352. 0, 0, 0, 0, 0,
  143353. NULL,
  143354. NULL,
  143355. NULL,
  143356. NULL,
  143357. 0
  143358. };
  143359. static long _huff_lengthlist__44u3__long[] = {
  143360. 6, 9,13,12,14,11,10,13, 8, 4, 5, 7, 8, 7, 8,12,
  143361. 11, 4, 3, 5, 5, 7, 9,14,11, 6, 5, 6, 6, 6, 7,13,
  143362. 13, 7, 5, 6, 4, 5, 7,14,11, 7, 6, 6, 5, 5, 6,13,
  143363. 9, 7, 8, 6, 7, 5, 3, 9, 9,12,13,12,14,10, 6, 7,
  143364. };
  143365. static static_codebook _huff_book__44u3__long = {
  143366. 2, 64,
  143367. _huff_lengthlist__44u3__long,
  143368. 0, 0, 0, 0, 0,
  143369. NULL,
  143370. NULL,
  143371. NULL,
  143372. NULL,
  143373. 0
  143374. };
  143375. static long _vq_quantlist__44u3__p1_0[] = {
  143376. 1,
  143377. 0,
  143378. 2,
  143379. };
  143380. static long _vq_lengthlist__44u3__p1_0[] = {
  143381. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  143382. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  143383. 11, 8,11,11, 8,11,11,11,13,14,11,14,14, 8,11,11,
  143384. 10,14,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 7,
  143385. 11,11,11,14,14,10,12,14, 8,11,11,11,14,14,11,14,
  143386. 13,
  143387. };
  143388. static float _vq_quantthresh__44u3__p1_0[] = {
  143389. -0.5, 0.5,
  143390. };
  143391. static long _vq_quantmap__44u3__p1_0[] = {
  143392. 1, 0, 2,
  143393. };
  143394. static encode_aux_threshmatch _vq_auxt__44u3__p1_0 = {
  143395. _vq_quantthresh__44u3__p1_0,
  143396. _vq_quantmap__44u3__p1_0,
  143397. 3,
  143398. 3
  143399. };
  143400. static static_codebook _44u3__p1_0 = {
  143401. 4, 81,
  143402. _vq_lengthlist__44u3__p1_0,
  143403. 1, -535822336, 1611661312, 2, 0,
  143404. _vq_quantlist__44u3__p1_0,
  143405. NULL,
  143406. &_vq_auxt__44u3__p1_0,
  143407. NULL,
  143408. 0
  143409. };
  143410. static long _vq_quantlist__44u3__p2_0[] = {
  143411. 1,
  143412. 0,
  143413. 2,
  143414. };
  143415. static long _vq_lengthlist__44u3__p2_0[] = {
  143416. 2, 5, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  143417. 8, 8, 5, 6, 6, 6, 8, 8, 7, 8, 8, 5, 7, 6, 7, 8,
  143418. 8, 6, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  143419. 8,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  143420. 8, 8, 8,10,10, 8, 8,10, 7, 8, 8, 8,10,10, 8,10,
  143421. 9,
  143422. };
  143423. static float _vq_quantthresh__44u3__p2_0[] = {
  143424. -0.5, 0.5,
  143425. };
  143426. static long _vq_quantmap__44u3__p2_0[] = {
  143427. 1, 0, 2,
  143428. };
  143429. static encode_aux_threshmatch _vq_auxt__44u3__p2_0 = {
  143430. _vq_quantthresh__44u3__p2_0,
  143431. _vq_quantmap__44u3__p2_0,
  143432. 3,
  143433. 3
  143434. };
  143435. static static_codebook _44u3__p2_0 = {
  143436. 4, 81,
  143437. _vq_lengthlist__44u3__p2_0,
  143438. 1, -535822336, 1611661312, 2, 0,
  143439. _vq_quantlist__44u3__p2_0,
  143440. NULL,
  143441. &_vq_auxt__44u3__p2_0,
  143442. NULL,
  143443. 0
  143444. };
  143445. static long _vq_quantlist__44u3__p3_0[] = {
  143446. 2,
  143447. 1,
  143448. 3,
  143449. 0,
  143450. 4,
  143451. };
  143452. static long _vq_lengthlist__44u3__p3_0[] = {
  143453. 2, 4, 4, 7, 7, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  143454. 9, 9,12,12, 8, 9, 9,11,12, 5, 7, 7,10,10, 7, 9,
  143455. 9,11,11, 7, 9, 9,10,11,10,11,11,13,13, 9,10,11,
  143456. 13,13, 5, 7, 7,10,10, 7, 9, 9,11,10, 7, 9, 9,11,
  143457. 11, 9,11,10,13,13,10,11,11,14,13, 8,10,10,14,13,
  143458. 10,11,11,15,14, 9,11,11,14,14,13,14,13,16,16,12,
  143459. 13,13,15,15, 8,10,10,13,14, 9,11,11,14,14,10,11,
  143460. 11,14,15,12,13,13,15,15,13,14,14,15,16, 5, 7, 7,
  143461. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,12,10,11,11,14,
  143462. 14,10,11,11,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  143463. 9,11,11,13,13,12,12,13,15,15,11,12,13,15,16, 7,
  143464. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,13,11,13,
  143465. 12,15,13,11,13,13,15,16, 9,12,11,15,14,11,12,13,
  143466. 16,15,11,13,13,15,16,14,14,15,17,16,13,15,16, 0,
  143467. 17, 9,11,11,15,15,10,13,12,15,15,11,13,13,15,16,
  143468. 13,15,13,16,15,14,16,15, 0,19, 5, 7, 7,10,10, 7,
  143469. 9, 9,11,11, 7, 9, 9,11,11,10,12,11,14,14,10,11,
  143470. 12,14,14, 7, 9, 9,12,12, 9,11,11,14,13, 9,10,11,
  143471. 12,13,11,13,13,16,16,11,12,13,13,16, 7, 9, 9,12,
  143472. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,15,15,
  143473. 12,13,12,15,14, 9,11,11,15,14,11,13,12,16,16,10,
  143474. 12,12,15,15,13,15,15,17,19,13,14,15,16,17,10,12,
  143475. 12,15,15,11,13,13,16,16,11,13,13,15,16,13,15,15,
  143476. 0, 0,14,15,15,16,16, 8,10,10,14,14,10,12,12,15,
  143477. 15,10,12,11,15,16,14,15,15,19,20,13,14,14,18,16,
  143478. 9,11,11,15,15,11,13,13,17,16,11,13,13,16,16,15,
  143479. 17,17,20,20,14,15,16,17,20, 9,11,11,15,15,10,13,
  143480. 12,16,15,11,13,13,15,17,14,16,15,18, 0,14,16,15,
  143481. 18,20,12,14,14, 0, 0,14,14,16, 0, 0,13,16,15, 0,
  143482. 0,17,17,18, 0, 0,16,17,19,19, 0,12,14,14,18, 0,
  143483. 12,16,14, 0,17,13,15,15,18, 0,16,18,17, 0,17,16,
  143484. 18,17, 0, 0, 7,10,10,14,14,10,12,11,15,15,10,12,
  143485. 12,16,15,13,15,15,18, 0,14,15,15,17, 0, 9,11,11,
  143486. 15,15,11,13,13,16,16,11,12,13,16,16,14,15,16,17,
  143487. 17,14,16,16,16,18, 9,11,12,16,16,11,13,13,17,17,
  143488. 11,14,13,20,17,15,16,16,19, 0,15,16,17, 0,19,11,
  143489. 13,14,17,16,14,15,15,20,18,13,14,15,17,19,16,18,
  143490. 18, 0,20,16,16,19,17, 0,12,15,14,17, 0,14,15,15,
  143491. 18,19,13,16,15,19,20,15,18,18, 0,20,17, 0,16, 0,
  143492. 0,
  143493. };
  143494. static float _vq_quantthresh__44u3__p3_0[] = {
  143495. -1.5, -0.5, 0.5, 1.5,
  143496. };
  143497. static long _vq_quantmap__44u3__p3_0[] = {
  143498. 3, 1, 0, 2, 4,
  143499. };
  143500. static encode_aux_threshmatch _vq_auxt__44u3__p3_0 = {
  143501. _vq_quantthresh__44u3__p3_0,
  143502. _vq_quantmap__44u3__p3_0,
  143503. 5,
  143504. 5
  143505. };
  143506. static static_codebook _44u3__p3_0 = {
  143507. 4, 625,
  143508. _vq_lengthlist__44u3__p3_0,
  143509. 1, -533725184, 1611661312, 3, 0,
  143510. _vq_quantlist__44u3__p3_0,
  143511. NULL,
  143512. &_vq_auxt__44u3__p3_0,
  143513. NULL,
  143514. 0
  143515. };
  143516. static long _vq_quantlist__44u3__p4_0[] = {
  143517. 2,
  143518. 1,
  143519. 3,
  143520. 0,
  143521. 4,
  143522. };
  143523. static long _vq_lengthlist__44u3__p4_0[] = {
  143524. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  143525. 9, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  143526. 8,10,10, 7, 7, 8,10,10, 9,10,10,11,12, 9,10,10,
  143527. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  143528. 10, 9,10, 9,12,11, 9,10,10,12,11, 9,10, 9,12,12,
  143529. 9,10,10,13,12, 9,10,10,12,13,12,12,12,14,14,11,
  143530. 12,12,13,14, 9, 9,10,12,12, 9,10,10,12,12, 9,10,
  143531. 10,12,13,11,12,11,14,13,12,12,12,14,13, 5, 7, 7,
  143532. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  143533. 12, 9,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  143534. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,13,13, 6,
  143535. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  143536. 10,13,11,10,11,11,13,13, 9,11,10,13,12,10,11,11,
  143537. 13,13,10,11,11,13,13,12,12,13,12,15,12,13,13,15,
  143538. 15, 9,10,10,12,13,10,11,10,13,12,10,11,11,13,14,
  143539. 12,13,11,15,13,12,13,13,15,15, 5, 7, 7, 9, 9, 7,
  143540. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12,10,10,
  143541. 11,12,12, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  143542. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  143543. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,13,
  143544. 11,11,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  143545. 10,11,12,13,12,13,13,15,15,12,11,13,13,14, 9,10,
  143546. 11,12,13,10,11,11,13,13,10,11,11,13,13,12,13,13,
  143547. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  143548. 13, 9,10,10,13,13,12,13,13,15,14,12,12,12,14,13,
  143549. 9,10,10,13,12,10,11,11,13,13,10,11,11,14,12,13,
  143550. 13,14,14,16,12,13,13,15,15, 9,10,10,13,13,10,11,
  143551. 10,14,13,10,11,11,13,14,12,14,13,15,14,13,13,13,
  143552. 15,15,11,13,12,15,14,11,12,13,14,15,12,13,13,16,
  143553. 14,14,12,15,12,16,14,15,15,17,15,11,12,12,14,14,
  143554. 11,13,11,15,14,12,13,13,15,15,13,15,12,17,13,14,
  143555. 15,15,16,16, 8, 9, 9,12,12, 9,10,10,12,13, 9,10,
  143556. 10,13,13,12,12,12,14,14,12,13,13,15,15, 9,10,10,
  143557. 13,12,10,11,11,14,13,10,10,11,13,14,12,13,13,15,
  143558. 15,12,12,13,14,16, 9,10,10,13,13,10,11,11,13,14,
  143559. 10,11,11,14,13,12,13,13,14,15,13,14,13,16,14,11,
  143560. 12,12,14,14,12,13,13,15,14,11,12,13,14,15,14,15,
  143561. 15,16,16,13,13,15,13,16,11,12,12,14,15,12,13,13,
  143562. 14,15,11,13,12,15,14,14,15,15,16,16,14,15,12,16,
  143563. 13,
  143564. };
  143565. static float _vq_quantthresh__44u3__p4_0[] = {
  143566. -1.5, -0.5, 0.5, 1.5,
  143567. };
  143568. static long _vq_quantmap__44u3__p4_0[] = {
  143569. 3, 1, 0, 2, 4,
  143570. };
  143571. static encode_aux_threshmatch _vq_auxt__44u3__p4_0 = {
  143572. _vq_quantthresh__44u3__p4_0,
  143573. _vq_quantmap__44u3__p4_0,
  143574. 5,
  143575. 5
  143576. };
  143577. static static_codebook _44u3__p4_0 = {
  143578. 4, 625,
  143579. _vq_lengthlist__44u3__p4_0,
  143580. 1, -533725184, 1611661312, 3, 0,
  143581. _vq_quantlist__44u3__p4_0,
  143582. NULL,
  143583. &_vq_auxt__44u3__p4_0,
  143584. NULL,
  143585. 0
  143586. };
  143587. static long _vq_quantlist__44u3__p5_0[] = {
  143588. 4,
  143589. 3,
  143590. 5,
  143591. 2,
  143592. 6,
  143593. 1,
  143594. 7,
  143595. 0,
  143596. 8,
  143597. };
  143598. static long _vq_lengthlist__44u3__p5_0[] = {
  143599. 2, 3, 3, 6, 6, 7, 7, 9, 9, 4, 5, 5, 7, 7, 8, 8,
  143600. 10,10, 4, 5, 5, 7, 7, 8, 8,10,10, 6, 7, 7, 8, 8,
  143601. 9, 9,11,10, 6, 7, 7, 8, 8, 9, 9,10,10, 7, 8, 8,
  143602. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  143603. 10,10,11,10,11,11,12,12, 9,10,10,10,10,11,11,12,
  143604. 12,
  143605. };
  143606. static float _vq_quantthresh__44u3__p5_0[] = {
  143607. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  143608. };
  143609. static long _vq_quantmap__44u3__p5_0[] = {
  143610. 7, 5, 3, 1, 0, 2, 4, 6,
  143611. 8,
  143612. };
  143613. static encode_aux_threshmatch _vq_auxt__44u3__p5_0 = {
  143614. _vq_quantthresh__44u3__p5_0,
  143615. _vq_quantmap__44u3__p5_0,
  143616. 9,
  143617. 9
  143618. };
  143619. static static_codebook _44u3__p5_0 = {
  143620. 2, 81,
  143621. _vq_lengthlist__44u3__p5_0,
  143622. 1, -531628032, 1611661312, 4, 0,
  143623. _vq_quantlist__44u3__p5_0,
  143624. NULL,
  143625. &_vq_auxt__44u3__p5_0,
  143626. NULL,
  143627. 0
  143628. };
  143629. static long _vq_quantlist__44u3__p6_0[] = {
  143630. 6,
  143631. 5,
  143632. 7,
  143633. 4,
  143634. 8,
  143635. 3,
  143636. 9,
  143637. 2,
  143638. 10,
  143639. 1,
  143640. 11,
  143641. 0,
  143642. 12,
  143643. };
  143644. static long _vq_lengthlist__44u3__p6_0[] = {
  143645. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,11,13,14, 4, 6, 5,
  143646. 8, 8, 9, 9,10,10,11,11,14,14, 4, 6, 6, 8, 8, 9,
  143647. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  143648. 12,12,15,15, 6, 8, 8, 9, 9,10,11,11,11,12,12,15,
  143649. 15, 8, 9, 9,11,10,11,11,12,12,13,13,15,16, 8, 9,
  143650. 9,10,11,11,11,12,12,13,13,16,16,10,10,11,11,11,
  143651. 12,12,13,13,13,14,17,16, 9,10,11,12,11,12,12,13,
  143652. 13,13,13,16,18,11,12,11,12,12,13,13,13,14,15,14,
  143653. 17,17,11,11,12,12,12,13,13,13,14,14,15,18,17,14,
  143654. 15,15,15,15,16,16,17,17,19,18, 0,20,14,15,14,15,
  143655. 15,16,16,16,17,18,16,20,18,
  143656. };
  143657. static float _vq_quantthresh__44u3__p6_0[] = {
  143658. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  143659. 12.5, 17.5, 22.5, 27.5,
  143660. };
  143661. static long _vq_quantmap__44u3__p6_0[] = {
  143662. 11, 9, 7, 5, 3, 1, 0, 2,
  143663. 4, 6, 8, 10, 12,
  143664. };
  143665. static encode_aux_threshmatch _vq_auxt__44u3__p6_0 = {
  143666. _vq_quantthresh__44u3__p6_0,
  143667. _vq_quantmap__44u3__p6_0,
  143668. 13,
  143669. 13
  143670. };
  143671. static static_codebook _44u3__p6_0 = {
  143672. 2, 169,
  143673. _vq_lengthlist__44u3__p6_0,
  143674. 1, -526516224, 1616117760, 4, 0,
  143675. _vq_quantlist__44u3__p6_0,
  143676. NULL,
  143677. &_vq_auxt__44u3__p6_0,
  143678. NULL,
  143679. 0
  143680. };
  143681. static long _vq_quantlist__44u3__p6_1[] = {
  143682. 2,
  143683. 1,
  143684. 3,
  143685. 0,
  143686. 4,
  143687. };
  143688. static long _vq_lengthlist__44u3__p6_1[] = {
  143689. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  143690. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  143691. };
  143692. static float _vq_quantthresh__44u3__p6_1[] = {
  143693. -1.5, -0.5, 0.5, 1.5,
  143694. };
  143695. static long _vq_quantmap__44u3__p6_1[] = {
  143696. 3, 1, 0, 2, 4,
  143697. };
  143698. static encode_aux_threshmatch _vq_auxt__44u3__p6_1 = {
  143699. _vq_quantthresh__44u3__p6_1,
  143700. _vq_quantmap__44u3__p6_1,
  143701. 5,
  143702. 5
  143703. };
  143704. static static_codebook _44u3__p6_1 = {
  143705. 2, 25,
  143706. _vq_lengthlist__44u3__p6_1,
  143707. 1, -533725184, 1611661312, 3, 0,
  143708. _vq_quantlist__44u3__p6_1,
  143709. NULL,
  143710. &_vq_auxt__44u3__p6_1,
  143711. NULL,
  143712. 0
  143713. };
  143714. static long _vq_quantlist__44u3__p7_0[] = {
  143715. 4,
  143716. 3,
  143717. 5,
  143718. 2,
  143719. 6,
  143720. 1,
  143721. 7,
  143722. 0,
  143723. 8,
  143724. };
  143725. static long _vq_lengthlist__44u3__p7_0[] = {
  143726. 1, 3, 3,10,10,10,10,10,10, 4,10,10,10,10,10,10,
  143727. 10,10, 4,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  143728. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143729. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143730. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143731. 9,
  143732. };
  143733. static float _vq_quantthresh__44u3__p7_0[] = {
  143734. -892.5, -637.5, -382.5, -127.5, 127.5, 382.5, 637.5, 892.5,
  143735. };
  143736. static long _vq_quantmap__44u3__p7_0[] = {
  143737. 7, 5, 3, 1, 0, 2, 4, 6,
  143738. 8,
  143739. };
  143740. static encode_aux_threshmatch _vq_auxt__44u3__p7_0 = {
  143741. _vq_quantthresh__44u3__p7_0,
  143742. _vq_quantmap__44u3__p7_0,
  143743. 9,
  143744. 9
  143745. };
  143746. static static_codebook _44u3__p7_0 = {
  143747. 2, 81,
  143748. _vq_lengthlist__44u3__p7_0,
  143749. 1, -515907584, 1627381760, 4, 0,
  143750. _vq_quantlist__44u3__p7_0,
  143751. NULL,
  143752. &_vq_auxt__44u3__p7_0,
  143753. NULL,
  143754. 0
  143755. };
  143756. static long _vq_quantlist__44u3__p7_1[] = {
  143757. 7,
  143758. 6,
  143759. 8,
  143760. 5,
  143761. 9,
  143762. 4,
  143763. 10,
  143764. 3,
  143765. 11,
  143766. 2,
  143767. 12,
  143768. 1,
  143769. 13,
  143770. 0,
  143771. 14,
  143772. };
  143773. static long _vq_lengthlist__44u3__p7_1[] = {
  143774. 1, 4, 4, 6, 6, 7, 6, 8, 7, 9, 8,10, 9,11,11, 4,
  143775. 7, 7, 8, 7, 9, 9,10,10,11,11,11,11,12,12, 4, 7,
  143776. 7, 7, 7, 9, 9,10,10,11,11,12,12,12,11, 6, 8, 8,
  143777. 9, 9,10,10,11,11,12,12,13,12,13,13, 6, 8, 8, 9,
  143778. 9,10,11,11,11,12,12,13,14,13,13, 8, 9, 9,11,11,
  143779. 12,12,12,13,14,13,14,14,14,15, 8, 9, 9,11,11,11,
  143780. 12,13,14,13,14,15,17,14,15, 9,10,10,12,12,13,13,
  143781. 13,14,15,15,15,16,16,16, 9,11,11,12,12,13,13,14,
  143782. 14,14,15,16,16,16,16,10,12,12,13,13,14,14,15,15,
  143783. 15,16,17,17,17,17,10,12,11,13,13,15,14,15,14,16,
  143784. 17,16,16,16,16,11,13,12,14,14,14,14,15,16,17,16,
  143785. 17,17,17,17,11,13,12,14,14,14,15,17,16,17,17,17,
  143786. 17,17,17,12,13,13,15,16,15,16,17,17,16,16,17,17,
  143787. 17,17,12,13,13,15,15,15,16,17,17,17,16,17,16,17,
  143788. 17,
  143789. };
  143790. static float _vq_quantthresh__44u3__p7_1[] = {
  143791. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  143792. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  143793. };
  143794. static long _vq_quantmap__44u3__p7_1[] = {
  143795. 13, 11, 9, 7, 5, 3, 1, 0,
  143796. 2, 4, 6, 8, 10, 12, 14,
  143797. };
  143798. static encode_aux_threshmatch _vq_auxt__44u3__p7_1 = {
  143799. _vq_quantthresh__44u3__p7_1,
  143800. _vq_quantmap__44u3__p7_1,
  143801. 15,
  143802. 15
  143803. };
  143804. static static_codebook _44u3__p7_1 = {
  143805. 2, 225,
  143806. _vq_lengthlist__44u3__p7_1,
  143807. 1, -522338304, 1620115456, 4, 0,
  143808. _vq_quantlist__44u3__p7_1,
  143809. NULL,
  143810. &_vq_auxt__44u3__p7_1,
  143811. NULL,
  143812. 0
  143813. };
  143814. static long _vq_quantlist__44u3__p7_2[] = {
  143815. 8,
  143816. 7,
  143817. 9,
  143818. 6,
  143819. 10,
  143820. 5,
  143821. 11,
  143822. 4,
  143823. 12,
  143824. 3,
  143825. 13,
  143826. 2,
  143827. 14,
  143828. 1,
  143829. 15,
  143830. 0,
  143831. 16,
  143832. };
  143833. static long _vq_lengthlist__44u3__p7_2[] = {
  143834. 2, 5, 5, 7, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  143835. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  143836. 10,10, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9,
  143837. 9,10, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  143838. 10,10,10,10, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  143839. 9,10,10,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  143840. 10,10,10,10,10,10, 7, 8, 8, 9, 8, 9, 9, 9, 9,10,
  143841. 9,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  143842. 9,10,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9,10,
  143843. 9,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,
  143844. 9,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  143845. 9,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10, 9,
  143846. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10,
  143847. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  143848. 10,10,10,10,10,10,10,10,10,10,10,10,10,11, 9,10,
  143849. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,11, 9,
  143850. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143851. 9,10,10,10,10,10,10,10,10,10,10,10,11,11,11,10,
  143852. 11,
  143853. };
  143854. static float _vq_quantthresh__44u3__p7_2[] = {
  143855. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  143856. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  143857. };
  143858. static long _vq_quantmap__44u3__p7_2[] = {
  143859. 15, 13, 11, 9, 7, 5, 3, 1,
  143860. 0, 2, 4, 6, 8, 10, 12, 14,
  143861. 16,
  143862. };
  143863. static encode_aux_threshmatch _vq_auxt__44u3__p7_2 = {
  143864. _vq_quantthresh__44u3__p7_2,
  143865. _vq_quantmap__44u3__p7_2,
  143866. 17,
  143867. 17
  143868. };
  143869. static static_codebook _44u3__p7_2 = {
  143870. 2, 289,
  143871. _vq_lengthlist__44u3__p7_2,
  143872. 1, -529530880, 1611661312, 5, 0,
  143873. _vq_quantlist__44u3__p7_2,
  143874. NULL,
  143875. &_vq_auxt__44u3__p7_2,
  143876. NULL,
  143877. 0
  143878. };
  143879. static long _huff_lengthlist__44u3__short[] = {
  143880. 14,14,14,15,13,15,12,16,10, 8, 7, 9, 9, 8,12,16,
  143881. 10, 5, 4, 6, 5, 6, 9,16,14, 8, 6, 8, 7, 8,10,16,
  143882. 14, 7, 4, 6, 3, 5, 8,16,15, 9, 5, 7, 4, 4, 7,16,
  143883. 13,10, 6, 7, 4, 3, 4,13,13,12, 7, 9, 5, 5, 6,12,
  143884. };
  143885. static static_codebook _huff_book__44u3__short = {
  143886. 2, 64,
  143887. _huff_lengthlist__44u3__short,
  143888. 0, 0, 0, 0, 0,
  143889. NULL,
  143890. NULL,
  143891. NULL,
  143892. NULL,
  143893. 0
  143894. };
  143895. static long _huff_lengthlist__44u4__long[] = {
  143896. 3, 8,12,12,13,12,11,13, 5, 4, 6, 7, 8, 8, 9,13,
  143897. 9, 5, 4, 5, 5, 7, 9,13, 9, 6, 5, 6, 6, 7, 8,12,
  143898. 12, 7, 5, 6, 4, 5, 8,13,11, 7, 6, 6, 5, 5, 6,12,
  143899. 10, 8, 8, 7, 7, 5, 3, 8,10,12,13,12,12, 9, 6, 7,
  143900. };
  143901. static static_codebook _huff_book__44u4__long = {
  143902. 2, 64,
  143903. _huff_lengthlist__44u4__long,
  143904. 0, 0, 0, 0, 0,
  143905. NULL,
  143906. NULL,
  143907. NULL,
  143908. NULL,
  143909. 0
  143910. };
  143911. static long _vq_quantlist__44u4__p1_0[] = {
  143912. 1,
  143913. 0,
  143914. 2,
  143915. };
  143916. static long _vq_lengthlist__44u4__p1_0[] = {
  143917. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  143918. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  143919. 11, 8,11,11, 8,11,11,11,13,14,11,15,14, 8,11,11,
  143920. 10,13,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 7,
  143921. 11,11,11,15,14,10,12,14, 8,11,11,11,14,14,11,14,
  143922. 13,
  143923. };
  143924. static float _vq_quantthresh__44u4__p1_0[] = {
  143925. -0.5, 0.5,
  143926. };
  143927. static long _vq_quantmap__44u4__p1_0[] = {
  143928. 1, 0, 2,
  143929. };
  143930. static encode_aux_threshmatch _vq_auxt__44u4__p1_0 = {
  143931. _vq_quantthresh__44u4__p1_0,
  143932. _vq_quantmap__44u4__p1_0,
  143933. 3,
  143934. 3
  143935. };
  143936. static static_codebook _44u4__p1_0 = {
  143937. 4, 81,
  143938. _vq_lengthlist__44u4__p1_0,
  143939. 1, -535822336, 1611661312, 2, 0,
  143940. _vq_quantlist__44u4__p1_0,
  143941. NULL,
  143942. &_vq_auxt__44u4__p1_0,
  143943. NULL,
  143944. 0
  143945. };
  143946. static long _vq_quantlist__44u4__p2_0[] = {
  143947. 1,
  143948. 0,
  143949. 2,
  143950. };
  143951. static long _vq_lengthlist__44u4__p2_0[] = {
  143952. 2, 5, 5, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  143953. 8, 8, 5, 6, 6, 6, 8, 8, 7, 8, 8, 5, 7, 6, 6, 8,
  143954. 8, 6, 8, 8, 6, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  143955. 8,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 6, 8, 8, 6,
  143956. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  143957. 9,
  143958. };
  143959. static float _vq_quantthresh__44u4__p2_0[] = {
  143960. -0.5, 0.5,
  143961. };
  143962. static long _vq_quantmap__44u4__p2_0[] = {
  143963. 1, 0, 2,
  143964. };
  143965. static encode_aux_threshmatch _vq_auxt__44u4__p2_0 = {
  143966. _vq_quantthresh__44u4__p2_0,
  143967. _vq_quantmap__44u4__p2_0,
  143968. 3,
  143969. 3
  143970. };
  143971. static static_codebook _44u4__p2_0 = {
  143972. 4, 81,
  143973. _vq_lengthlist__44u4__p2_0,
  143974. 1, -535822336, 1611661312, 2, 0,
  143975. _vq_quantlist__44u4__p2_0,
  143976. NULL,
  143977. &_vq_auxt__44u4__p2_0,
  143978. NULL,
  143979. 0
  143980. };
  143981. static long _vq_quantlist__44u4__p3_0[] = {
  143982. 2,
  143983. 1,
  143984. 3,
  143985. 0,
  143986. 4,
  143987. };
  143988. static long _vq_lengthlist__44u4__p3_0[] = {
  143989. 2, 4, 4, 8, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  143990. 10, 9,12,12, 8, 9,10,12,12, 5, 7, 7,10,10, 7, 9,
  143991. 9,11,11, 7, 9, 9,11,11,10,12,11,14,14, 9,10,11,
  143992. 13,14, 5, 7, 7,10,10, 7, 9, 9,11,11, 7, 9, 9,11,
  143993. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,14,13,
  143994. 10,12,12,15,14, 9,11,11,15,14,13,14,14,17,17,12,
  143995. 14,14,16,16, 8,10,10,14,14, 9,11,11,14,15,10,12,
  143996. 12,14,15,12,14,13,16,16,13,14,15,15,18, 4, 7, 7,
  143997. 10,10, 7, 9, 9,12,11, 7, 9, 9,11,12,10,12,11,15,
  143998. 14,10,11,12,14,15, 7, 9, 9,12,12, 9,11,12,13,13,
  143999. 9,11,12,13,13,12,13,13,15,16,11,13,13,15,16, 7,
  144000. 9, 9,12,12, 9,11,10,13,12, 9,11,12,13,14,11,13,
  144001. 12,16,14,12,13,13,15,16,10,12,12,16,15,11,13,13,
  144002. 17,16,11,13,13,17,16,14,15,15,17,17,14,16,16,18,
  144003. 20, 9,11,11,15,16,11,13,12,16,16,11,13,13,16,17,
  144004. 14,15,14,18,16,14,16,16,17,20, 5, 7, 7,10,10, 7,
  144005. 9, 9,12,11, 7, 9,10,11,12,10,12,11,15,15,10,12,
  144006. 12,14,14, 7, 9, 9,12,12, 9,12,11,14,13, 9,10,11,
  144007. 12,13,12,13,14,16,16,11,12,13,14,16, 7, 9, 9,12,
  144008. 12, 9,12,11,13,13, 9,12,11,13,13,11,13,13,16,16,
  144009. 12,13,13,16,15, 9,11,11,16,14,11,13,13,16,16,11,
  144010. 12,13,16,16,14,16,16,17,17,13,14,15,16,17,10,12,
  144011. 12,15,15,11,13,13,16,17,11,13,13,16,16,14,16,15,
  144012. 19,19,14,15,15,17,18, 8,10,10,14,14,10,12,12,15,
  144013. 15,10,12,12,16,16,14,16,15,20,19,13,15,15,17,16,
  144014. 9,12,12,16,16,11,13,13,16,18,11,14,13,16,17,16,
  144015. 17,16,20, 0,15,16,18,18,20, 9,11,11,15,15,11,14,
  144016. 12,17,16,11,13,13,17,17,15,17,15,20,20,14,16,16,
  144017. 17, 0,13,15,14,18,16,14,15,16, 0,18,14,16,16, 0,
  144018. 0,18,16, 0, 0,20,16,18,18, 0, 0,12,14,14,17,18,
  144019. 13,15,14,20,18,14,16,15,19,19,16,20,16, 0,18,16,
  144020. 19,17,19, 0, 8,10,10,14,14,10,12,12,16,15,10,12,
  144021. 12,16,16,13,15,15,18,17,14,16,16,19, 0, 9,11,11,
  144022. 16,15,11,14,13,18,17,11,12,13,17,18,14,17,16,18,
  144023. 18,15,16,17,18,18, 9,12,12,16,16,11,13,13,16,18,
  144024. 11,14,13,17,17,15,16,16,18,20,16,17,17,20,20,12,
  144025. 14,14,18,17,14,16,16, 0,19,13,14,15,18, 0,16, 0,
  144026. 0, 0, 0,16,16, 0,19,20,13,15,14, 0, 0,14,16,16,
  144027. 18,19,14,16,15, 0,20,16,20,18, 0,20,17,20,17, 0,
  144028. 0,
  144029. };
  144030. static float _vq_quantthresh__44u4__p3_0[] = {
  144031. -1.5, -0.5, 0.5, 1.5,
  144032. };
  144033. static long _vq_quantmap__44u4__p3_0[] = {
  144034. 3, 1, 0, 2, 4,
  144035. };
  144036. static encode_aux_threshmatch _vq_auxt__44u4__p3_0 = {
  144037. _vq_quantthresh__44u4__p3_0,
  144038. _vq_quantmap__44u4__p3_0,
  144039. 5,
  144040. 5
  144041. };
  144042. static static_codebook _44u4__p3_0 = {
  144043. 4, 625,
  144044. _vq_lengthlist__44u4__p3_0,
  144045. 1, -533725184, 1611661312, 3, 0,
  144046. _vq_quantlist__44u4__p3_0,
  144047. NULL,
  144048. &_vq_auxt__44u4__p3_0,
  144049. NULL,
  144050. 0
  144051. };
  144052. static long _vq_quantlist__44u4__p4_0[] = {
  144053. 2,
  144054. 1,
  144055. 3,
  144056. 0,
  144057. 4,
  144058. };
  144059. static long _vq_lengthlist__44u4__p4_0[] = {
  144060. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  144061. 9, 9,11,11, 8, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  144062. 8,10,10, 7, 7, 8,10,10, 9,10,10,11,12, 9,10,10,
  144063. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  144064. 10, 9,10,10,12,11, 9,10,10,12,11, 9,10, 9,12,12,
  144065. 9,10,10,13,12, 9,10,10,12,12,12,12,12,14,14,11,
  144066. 12,12,13,14, 9, 9,10,12,12, 9,10,10,13,13, 9,10,
  144067. 10,12,13,11,12,12,14,13,11,12,12,14,14, 5, 7, 7,
  144068. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  144069. 12, 9,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  144070. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,13,13, 6,
  144071. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  144072. 10,13,11,10,11,11,13,13, 9,11,10,13,12,10,11,11,
  144073. 13,14,10,11,11,14,13,12,12,13,12,15,12,13,13,15,
  144074. 15, 9,10,10,12,13,10,11,10,13,12,10,11,11,13,14,
  144075. 12,13,11,15,13,13,13,13,15,15, 5, 7, 7, 9, 9, 7,
  144076. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12,10,10,
  144077. 11,12,13, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  144078. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  144079. 11, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,11,13,13,
  144080. 11,12,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  144081. 10,11,12,13,12,13,13,15,15,12,11,13,13,14, 9,10,
  144082. 11,12,13,10,11,11,13,14,10,11,11,13,13,12,13,13,
  144083. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  144084. 13, 9,10,10,13,13,12,13,13,15,15,12,12,12,14,14,
  144085. 9,10,10,13,13,10,11,11,13,14,10,11,11,14,13,13,
  144086. 13,14,14,16,13,13,13,15,15, 9,10,10,13,13,10,11,
  144087. 10,14,13,10,11,11,13,14,12,14,13,16,14,12,13,13,
  144088. 14,15,11,12,12,15,14,11,12,13,14,15,12,13,13,16,
  144089. 15,14,12,15,12,16,14,15,15,16,16,11,12,12,14,14,
  144090. 11,13,12,15,14,12,13,13,15,16,13,15,13,17,13,14,
  144091. 15,15,16,17, 8, 9, 9,12,12, 9,10,10,12,13, 9,10,
  144092. 10,13,13,12,12,12,14,14,12,13,13,15,15, 9,10,10,
  144093. 13,12,10,11,11,14,13,10,10,11,13,14,13,13,13,15,
  144094. 15,12,13,14,14,16, 9,10,10,13,13,10,11,11,13,14,
  144095. 10,11,11,14,14,13,13,13,15,15,13,14,13,16,14,11,
  144096. 12,12,15,14,12,13,13,16,15,11,12,13,14,15,14,15,
  144097. 15,17,16,13,13,15,13,16,11,12,13,14,15,13,13,13,
  144098. 15,16,11,13,12,15,14,14,15,15,16,16,14,15,12,17,
  144099. 13,
  144100. };
  144101. static float _vq_quantthresh__44u4__p4_0[] = {
  144102. -1.5, -0.5, 0.5, 1.5,
  144103. };
  144104. static long _vq_quantmap__44u4__p4_0[] = {
  144105. 3, 1, 0, 2, 4,
  144106. };
  144107. static encode_aux_threshmatch _vq_auxt__44u4__p4_0 = {
  144108. _vq_quantthresh__44u4__p4_0,
  144109. _vq_quantmap__44u4__p4_0,
  144110. 5,
  144111. 5
  144112. };
  144113. static static_codebook _44u4__p4_0 = {
  144114. 4, 625,
  144115. _vq_lengthlist__44u4__p4_0,
  144116. 1, -533725184, 1611661312, 3, 0,
  144117. _vq_quantlist__44u4__p4_0,
  144118. NULL,
  144119. &_vq_auxt__44u4__p4_0,
  144120. NULL,
  144121. 0
  144122. };
  144123. static long _vq_quantlist__44u4__p5_0[] = {
  144124. 4,
  144125. 3,
  144126. 5,
  144127. 2,
  144128. 6,
  144129. 1,
  144130. 7,
  144131. 0,
  144132. 8,
  144133. };
  144134. static long _vq_lengthlist__44u4__p5_0[] = {
  144135. 2, 3, 3, 6, 6, 7, 7, 9, 9, 4, 5, 5, 7, 7, 8, 8,
  144136. 10, 9, 4, 5, 5, 7, 7, 8, 8,10,10, 6, 7, 7, 8, 8,
  144137. 9, 9,11,10, 6, 7, 7, 8, 8, 9, 9,10,11, 7, 8, 8,
  144138. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  144139. 10,10,11,10,11,11,12,12, 9,10,10,10,11,11,11,12,
  144140. 12,
  144141. };
  144142. static float _vq_quantthresh__44u4__p5_0[] = {
  144143. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  144144. };
  144145. static long _vq_quantmap__44u4__p5_0[] = {
  144146. 7, 5, 3, 1, 0, 2, 4, 6,
  144147. 8,
  144148. };
  144149. static encode_aux_threshmatch _vq_auxt__44u4__p5_0 = {
  144150. _vq_quantthresh__44u4__p5_0,
  144151. _vq_quantmap__44u4__p5_0,
  144152. 9,
  144153. 9
  144154. };
  144155. static static_codebook _44u4__p5_0 = {
  144156. 2, 81,
  144157. _vq_lengthlist__44u4__p5_0,
  144158. 1, -531628032, 1611661312, 4, 0,
  144159. _vq_quantlist__44u4__p5_0,
  144160. NULL,
  144161. &_vq_auxt__44u4__p5_0,
  144162. NULL,
  144163. 0
  144164. };
  144165. static long _vq_quantlist__44u4__p6_0[] = {
  144166. 6,
  144167. 5,
  144168. 7,
  144169. 4,
  144170. 8,
  144171. 3,
  144172. 9,
  144173. 2,
  144174. 10,
  144175. 1,
  144176. 11,
  144177. 0,
  144178. 12,
  144179. };
  144180. static long _vq_lengthlist__44u4__p6_0[] = {
  144181. 1, 4, 4, 6, 6, 8, 8, 9, 9,11,10,13,13, 4, 6, 5,
  144182. 8, 8, 9, 9,10,10,11,11,14,14, 4, 6, 6, 8, 8, 9,
  144183. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  144184. 12,12,15,15, 6, 8, 8, 9, 9,10,11,11,11,12,12,15,
  144185. 15, 8, 9, 9,11,10,11,11,12,12,13,13,16,16, 8, 9,
  144186. 9,10,10,11,11,12,12,13,13,16,16,10,10,10,12,11,
  144187. 12,12,13,13,14,14,16,16,10,10,10,11,12,12,12,13,
  144188. 13,13,14,16,17,11,12,11,12,12,13,13,14,14,15,14,
  144189. 18,17,11,11,12,12,12,13,13,14,14,14,15,19,18,14,
  144190. 15,14,15,15,17,16,17,17,17,17,21, 0,14,15,15,16,
  144191. 16,16,16,17,17,18,17,20,21,
  144192. };
  144193. static float _vq_quantthresh__44u4__p6_0[] = {
  144194. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  144195. 12.5, 17.5, 22.5, 27.5,
  144196. };
  144197. static long _vq_quantmap__44u4__p6_0[] = {
  144198. 11, 9, 7, 5, 3, 1, 0, 2,
  144199. 4, 6, 8, 10, 12,
  144200. };
  144201. static encode_aux_threshmatch _vq_auxt__44u4__p6_0 = {
  144202. _vq_quantthresh__44u4__p6_0,
  144203. _vq_quantmap__44u4__p6_0,
  144204. 13,
  144205. 13
  144206. };
  144207. static static_codebook _44u4__p6_0 = {
  144208. 2, 169,
  144209. _vq_lengthlist__44u4__p6_0,
  144210. 1, -526516224, 1616117760, 4, 0,
  144211. _vq_quantlist__44u4__p6_0,
  144212. NULL,
  144213. &_vq_auxt__44u4__p6_0,
  144214. NULL,
  144215. 0
  144216. };
  144217. static long _vq_quantlist__44u4__p6_1[] = {
  144218. 2,
  144219. 1,
  144220. 3,
  144221. 0,
  144222. 4,
  144223. };
  144224. static long _vq_lengthlist__44u4__p6_1[] = {
  144225. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  144226. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  144227. };
  144228. static float _vq_quantthresh__44u4__p6_1[] = {
  144229. -1.5, -0.5, 0.5, 1.5,
  144230. };
  144231. static long _vq_quantmap__44u4__p6_1[] = {
  144232. 3, 1, 0, 2, 4,
  144233. };
  144234. static encode_aux_threshmatch _vq_auxt__44u4__p6_1 = {
  144235. _vq_quantthresh__44u4__p6_1,
  144236. _vq_quantmap__44u4__p6_1,
  144237. 5,
  144238. 5
  144239. };
  144240. static static_codebook _44u4__p6_1 = {
  144241. 2, 25,
  144242. _vq_lengthlist__44u4__p6_1,
  144243. 1, -533725184, 1611661312, 3, 0,
  144244. _vq_quantlist__44u4__p6_1,
  144245. NULL,
  144246. &_vq_auxt__44u4__p6_1,
  144247. NULL,
  144248. 0
  144249. };
  144250. static long _vq_quantlist__44u4__p7_0[] = {
  144251. 6,
  144252. 5,
  144253. 7,
  144254. 4,
  144255. 8,
  144256. 3,
  144257. 9,
  144258. 2,
  144259. 10,
  144260. 1,
  144261. 11,
  144262. 0,
  144263. 12,
  144264. };
  144265. static long _vq_lengthlist__44u4__p7_0[] = {
  144266. 1, 3, 3,12,12,12,12,12,12,12,12,12,12, 3,12,11,
  144267. 12,12,12,12,12,12,12,12,12,12, 4,11,10,12,12,12,
  144268. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144269. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144270. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144271. 12,12,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144272. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144273. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144274. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144275. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144276. 11,11,11,11,11,11,11,11,11,
  144277. };
  144278. static float _vq_quantthresh__44u4__p7_0[] = {
  144279. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  144280. 637.5, 892.5, 1147.5, 1402.5,
  144281. };
  144282. static long _vq_quantmap__44u4__p7_0[] = {
  144283. 11, 9, 7, 5, 3, 1, 0, 2,
  144284. 4, 6, 8, 10, 12,
  144285. };
  144286. static encode_aux_threshmatch _vq_auxt__44u4__p7_0 = {
  144287. _vq_quantthresh__44u4__p7_0,
  144288. _vq_quantmap__44u4__p7_0,
  144289. 13,
  144290. 13
  144291. };
  144292. static static_codebook _44u4__p7_0 = {
  144293. 2, 169,
  144294. _vq_lengthlist__44u4__p7_0,
  144295. 1, -514332672, 1627381760, 4, 0,
  144296. _vq_quantlist__44u4__p7_0,
  144297. NULL,
  144298. &_vq_auxt__44u4__p7_0,
  144299. NULL,
  144300. 0
  144301. };
  144302. static long _vq_quantlist__44u4__p7_1[] = {
  144303. 7,
  144304. 6,
  144305. 8,
  144306. 5,
  144307. 9,
  144308. 4,
  144309. 10,
  144310. 3,
  144311. 11,
  144312. 2,
  144313. 12,
  144314. 1,
  144315. 13,
  144316. 0,
  144317. 14,
  144318. };
  144319. static long _vq_lengthlist__44u4__p7_1[] = {
  144320. 1, 4, 4, 6, 6, 7, 7, 9, 8,10, 8,10, 9,11,11, 4,
  144321. 7, 6, 8, 7, 9, 9,10,10,11,10,11,10,12,10, 4, 6,
  144322. 7, 8, 8, 9, 9,10,10,11,11,11,11,12,12, 6, 8, 8,
  144323. 10, 9,11,10,12,11,12,12,12,12,13,13, 6, 8, 8,10,
  144324. 10,10,11,11,11,12,12,13,12,13,13, 8, 9, 9,11,11,
  144325. 12,11,12,12,13,13,13,13,13,13, 8, 9, 9,11,11,11,
  144326. 12,12,12,13,13,13,13,13,13, 9,10,10,12,11,13,13,
  144327. 13,13,14,13,13,14,14,14, 9,10,11,11,12,12,13,13,
  144328. 13,13,13,14,15,14,14,10,11,11,12,12,13,13,14,14,
  144329. 14,14,14,15,16,16,10,11,11,12,13,13,13,13,15,14,
  144330. 14,15,16,15,16,10,12,12,13,13,14,14,14,15,15,15,
  144331. 15,15,15,16,11,12,12,13,13,14,14,14,15,15,15,16,
  144332. 15,17,16,11,12,12,13,13,13,15,15,14,16,16,16,16,
  144333. 16,17,11,12,12,13,13,14,14,15,14,15,15,17,17,16,
  144334. 16,
  144335. };
  144336. static float _vq_quantthresh__44u4__p7_1[] = {
  144337. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  144338. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  144339. };
  144340. static long _vq_quantmap__44u4__p7_1[] = {
  144341. 13, 11, 9, 7, 5, 3, 1, 0,
  144342. 2, 4, 6, 8, 10, 12, 14,
  144343. };
  144344. static encode_aux_threshmatch _vq_auxt__44u4__p7_1 = {
  144345. _vq_quantthresh__44u4__p7_1,
  144346. _vq_quantmap__44u4__p7_1,
  144347. 15,
  144348. 15
  144349. };
  144350. static static_codebook _44u4__p7_1 = {
  144351. 2, 225,
  144352. _vq_lengthlist__44u4__p7_1,
  144353. 1, -522338304, 1620115456, 4, 0,
  144354. _vq_quantlist__44u4__p7_1,
  144355. NULL,
  144356. &_vq_auxt__44u4__p7_1,
  144357. NULL,
  144358. 0
  144359. };
  144360. static long _vq_quantlist__44u4__p7_2[] = {
  144361. 8,
  144362. 7,
  144363. 9,
  144364. 6,
  144365. 10,
  144366. 5,
  144367. 11,
  144368. 4,
  144369. 12,
  144370. 3,
  144371. 13,
  144372. 2,
  144373. 14,
  144374. 1,
  144375. 15,
  144376. 0,
  144377. 16,
  144378. };
  144379. static long _vq_lengthlist__44u4__p7_2[] = {
  144380. 2, 5, 5, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  144381. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  144382. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  144383. 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  144384. 10,10,10,10, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  144385. 9,10, 9,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  144386. 10,10,10,10,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  144387. 9,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  144388. 10,10,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9,
  144389. 10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,10,
  144390. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  144391. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,10,
  144392. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  144393. 10,10,10,10,10,10,10,10,10,11,10,10,10, 9, 9, 9,
  144394. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  144395. 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  144396. 10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144397. 9,10, 9,10,10,10,10,10,10,10,10,10,10,11,10,10,
  144398. 10,
  144399. };
  144400. static float _vq_quantthresh__44u4__p7_2[] = {
  144401. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  144402. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  144403. };
  144404. static long _vq_quantmap__44u4__p7_2[] = {
  144405. 15, 13, 11, 9, 7, 5, 3, 1,
  144406. 0, 2, 4, 6, 8, 10, 12, 14,
  144407. 16,
  144408. };
  144409. static encode_aux_threshmatch _vq_auxt__44u4__p7_2 = {
  144410. _vq_quantthresh__44u4__p7_2,
  144411. _vq_quantmap__44u4__p7_2,
  144412. 17,
  144413. 17
  144414. };
  144415. static static_codebook _44u4__p7_2 = {
  144416. 2, 289,
  144417. _vq_lengthlist__44u4__p7_2,
  144418. 1, -529530880, 1611661312, 5, 0,
  144419. _vq_quantlist__44u4__p7_2,
  144420. NULL,
  144421. &_vq_auxt__44u4__p7_2,
  144422. NULL,
  144423. 0
  144424. };
  144425. static long _huff_lengthlist__44u4__short[] = {
  144426. 14,17,15,17,16,14,13,16,10, 7, 7,10,13,10,15,16,
  144427. 9, 4, 4, 6, 5, 7, 9,16,12, 8, 7, 8, 8, 8,11,16,
  144428. 14, 7, 4, 6, 3, 5, 8,15,13, 8, 5, 7, 4, 5, 7,16,
  144429. 12, 9, 6, 8, 3, 3, 5,16,14,13, 7,10, 5, 5, 7,15,
  144430. };
  144431. static static_codebook _huff_book__44u4__short = {
  144432. 2, 64,
  144433. _huff_lengthlist__44u4__short,
  144434. 0, 0, 0, 0, 0,
  144435. NULL,
  144436. NULL,
  144437. NULL,
  144438. NULL,
  144439. 0
  144440. };
  144441. static long _huff_lengthlist__44u5__long[] = {
  144442. 3, 8,13,12,14,12,16,11,13,14, 5, 4, 5, 6, 7, 8,
  144443. 10, 9,12,15,10, 5, 5, 5, 6, 8, 9, 9,13,15,10, 5,
  144444. 5, 6, 6, 7, 8, 8,11,13,12, 7, 5, 6, 4, 6, 7, 7,
  144445. 11,14,11, 7, 7, 6, 6, 6, 7, 6,10,14,14, 9, 8, 8,
  144446. 6, 7, 7, 7,11,16,11, 8, 8, 7, 6, 6, 7, 4, 7,12,
  144447. 10,10,12,10,10, 9,10, 5, 6, 9,10,12,15,13,14,14,
  144448. 14, 8, 7, 8,
  144449. };
  144450. static static_codebook _huff_book__44u5__long = {
  144451. 2, 100,
  144452. _huff_lengthlist__44u5__long,
  144453. 0, 0, 0, 0, 0,
  144454. NULL,
  144455. NULL,
  144456. NULL,
  144457. NULL,
  144458. 0
  144459. };
  144460. static long _vq_quantlist__44u5__p1_0[] = {
  144461. 1,
  144462. 0,
  144463. 2,
  144464. };
  144465. static long _vq_lengthlist__44u5__p1_0[] = {
  144466. 1, 4, 4, 5, 8, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  144467. 9,10, 5, 8, 8, 7,10, 9, 8,10,10, 5, 8, 8, 8,10,
  144468. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  144469. 10,13,11,10,13,13, 4, 8, 8, 8,11,10, 8,10,10, 7,
  144470. 10,10,10,13,13,10,11,13, 8,10,11,10,13,13,10,13,
  144471. 12,
  144472. };
  144473. static float _vq_quantthresh__44u5__p1_0[] = {
  144474. -0.5, 0.5,
  144475. };
  144476. static long _vq_quantmap__44u5__p1_0[] = {
  144477. 1, 0, 2,
  144478. };
  144479. static encode_aux_threshmatch _vq_auxt__44u5__p1_0 = {
  144480. _vq_quantthresh__44u5__p1_0,
  144481. _vq_quantmap__44u5__p1_0,
  144482. 3,
  144483. 3
  144484. };
  144485. static static_codebook _44u5__p1_0 = {
  144486. 4, 81,
  144487. _vq_lengthlist__44u5__p1_0,
  144488. 1, -535822336, 1611661312, 2, 0,
  144489. _vq_quantlist__44u5__p1_0,
  144490. NULL,
  144491. &_vq_auxt__44u5__p1_0,
  144492. NULL,
  144493. 0
  144494. };
  144495. static long _vq_quantlist__44u5__p2_0[] = {
  144496. 1,
  144497. 0,
  144498. 2,
  144499. };
  144500. static long _vq_lengthlist__44u5__p2_0[] = {
  144501. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  144502. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  144503. 8, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 8, 7,
  144504. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  144505. 8, 7, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  144506. 9,
  144507. };
  144508. static float _vq_quantthresh__44u5__p2_0[] = {
  144509. -0.5, 0.5,
  144510. };
  144511. static long _vq_quantmap__44u5__p2_0[] = {
  144512. 1, 0, 2,
  144513. };
  144514. static encode_aux_threshmatch _vq_auxt__44u5__p2_0 = {
  144515. _vq_quantthresh__44u5__p2_0,
  144516. _vq_quantmap__44u5__p2_0,
  144517. 3,
  144518. 3
  144519. };
  144520. static static_codebook _44u5__p2_0 = {
  144521. 4, 81,
  144522. _vq_lengthlist__44u5__p2_0,
  144523. 1, -535822336, 1611661312, 2, 0,
  144524. _vq_quantlist__44u5__p2_0,
  144525. NULL,
  144526. &_vq_auxt__44u5__p2_0,
  144527. NULL,
  144528. 0
  144529. };
  144530. static long _vq_quantlist__44u5__p3_0[] = {
  144531. 2,
  144532. 1,
  144533. 3,
  144534. 0,
  144535. 4,
  144536. };
  144537. static long _vq_lengthlist__44u5__p3_0[] = {
  144538. 2, 4, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  144539. 10, 9,13,12, 8, 9,10,12,12, 5, 7, 7,10,10, 7, 9,
  144540. 9,11,11, 6, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  144541. 13,14, 5, 7, 7, 9,10, 7, 9, 8,11,11, 7, 9, 9,11,
  144542. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,13,13,
  144543. 10,11,11,15,14, 9,11,11,14,14,13,14,14,17,16,12,
  144544. 13,13,15,16, 8,10,10,13,13, 9,11,11,14,15,10,11,
  144545. 11,14,15,12,14,13,16,16,13,15,14,15,17, 5, 7, 7,
  144546. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,
  144547. 14,10,11,12,14,14, 7, 9, 9,12,11, 9,11,11,13,13,
  144548. 9,11,11,13,13,12,13,13,15,16,11,12,13,15,16, 6,
  144549. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,14,11,13,
  144550. 12,16,14,11,13,13,16,17,10,12,11,15,15,11,13,13,
  144551. 16,16,11,13,13,17,16,14,15,15,17,17,14,16,16,17,
  144552. 18, 9,11,11,14,15,10,12,12,15,15,11,13,13,16,17,
  144553. 13,15,13,17,15,14,15,16,18, 0, 5, 7, 7,10,10, 7,
  144554. 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  144555. 12,14,15, 6, 9, 9,12,11, 9,11,11,13,13, 8,10,11,
  144556. 12,13,11,13,13,16,15,11,12,13,14,15, 7, 9, 9,11,
  144557. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,15,16,
  144558. 11,13,13,15,14, 9,11,11,15,14,11,13,13,17,15,10,
  144559. 12,12,15,15,14,16,16,17,17,13,13,15,15,17,10,11,
  144560. 12,15,15,11,13,13,16,16,11,13,13,15,15,14,15,15,
  144561. 18,18,14,15,15,17,17, 8,10,10,13,13,10,12,11,15,
  144562. 15,10,11,12,15,15,14,15,15,18,18,13,14,14,18,18,
  144563. 9,11,11,15,16,11,13,13,17,17,11,13,13,16,16,15,
  144564. 15,16,17, 0,14,15,17, 0, 0, 9,11,11,15,15,10,13,
  144565. 12,18,16,11,13,13,15,16,14,16,15,20,20,14,15,16,
  144566. 17, 0,13,14,14,20,16,14,15,16,19,18,14,15,15,19,
  144567. 0,18,16, 0,20,20,16,18,18, 0, 0,12,14,14,18,18,
  144568. 13,15,14,18,16,14,15,16,18,20,16,19,16, 0,17,17,
  144569. 18,18,19, 0, 8,10,10,14,14,10,11,11,14,15,10,11,
  144570. 12,15,15,13,15,14,19,17,13,15,15,17, 0, 9,11,11,
  144571. 16,15,11,13,13,16,16,10,12,13,15,17,14,16,16,18,
  144572. 18,14,15,15,18, 0, 9,11,11,15,15,11,13,13,16,17,
  144573. 11,13,13,18,17,14,18,16,18,18,15,17,17,18, 0,12,
  144574. 14,14,18,18,14,15,15,20, 0,13,14,15,17, 0,16,18,
  144575. 17, 0, 0,16,16, 0,17,20,12,14,14,18,18,14,16,15,
  144576. 0,18,14,16,15,18, 0,16,19,17, 0, 0,17,18,16, 0,
  144577. 0,
  144578. };
  144579. static float _vq_quantthresh__44u5__p3_0[] = {
  144580. -1.5, -0.5, 0.5, 1.5,
  144581. };
  144582. static long _vq_quantmap__44u5__p3_0[] = {
  144583. 3, 1, 0, 2, 4,
  144584. };
  144585. static encode_aux_threshmatch _vq_auxt__44u5__p3_0 = {
  144586. _vq_quantthresh__44u5__p3_0,
  144587. _vq_quantmap__44u5__p3_0,
  144588. 5,
  144589. 5
  144590. };
  144591. static static_codebook _44u5__p3_0 = {
  144592. 4, 625,
  144593. _vq_lengthlist__44u5__p3_0,
  144594. 1, -533725184, 1611661312, 3, 0,
  144595. _vq_quantlist__44u5__p3_0,
  144596. NULL,
  144597. &_vq_auxt__44u5__p3_0,
  144598. NULL,
  144599. 0
  144600. };
  144601. static long _vq_quantlist__44u5__p4_0[] = {
  144602. 2,
  144603. 1,
  144604. 3,
  144605. 0,
  144606. 4,
  144607. };
  144608. static long _vq_lengthlist__44u5__p4_0[] = {
  144609. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  144610. 9, 9,11,11, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  144611. 8,10,10, 6, 7, 8, 9,10, 9,10,10,11,12, 9, 9,10,
  144612. 11,12, 6, 7, 7, 9, 9, 6, 8, 7,10, 9, 7, 8, 8,10,
  144613. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,12,11,
  144614. 9,10,10,12,12, 9,10,10,12,12,11,12,12,13,14,11,
  144615. 11,12,13,14, 8, 9, 9,11,12, 9,10,10,12,12, 9,10,
  144616. 10,12,12,11,12,11,14,13,11,12,12,13,13, 5, 7, 7,
  144617. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  144618. 12, 9,10,10,12,12, 7, 8, 8,10,10, 8, 8, 9,10,11,
  144619. 8, 9, 9,11,11,10,10,11,11,13,10,11,11,12,13, 6,
  144620. 7, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  144621. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  144622. 12,13,10,11,11,13,13,12,11,13,12,15,12,13,13,14,
  144623. 15, 9,10,10,12,12, 9,11,10,13,12,10,11,11,13,13,
  144624. 11,13,11,14,12,12,13,13,14,15, 5, 7, 7, 9, 9, 7,
  144625. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,
  144626. 10,12,12, 6, 8, 7,10,10, 8, 9, 9,11,11, 7, 8, 9,
  144627. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 8, 8,10,
  144628. 10, 8, 9, 9,11,11, 8, 9, 8,11,10,10,11,11,13,12,
  144629. 10,11,10,13,11, 9,10,10,12,12,10,11,11,13,12, 9,
  144630. 10,10,12,13,12,13,13,14,15,11,11,13,12,14, 9,10,
  144631. 10,12,12,10,11,11,13,13,10,11,10,13,12,12,13,13,
  144632. 14,14,12,13,11,14,12, 8, 9, 9,12,12, 9,10,10,12,
  144633. 12, 9,10,10,12,12,12,12,12,14,14,11,12,12,14,13,
  144634. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,12,12,
  144635. 12,13,14,15,12,13,13,15,14, 9,10,10,12,12,10,11,
  144636. 10,13,12,10,11,11,12,13,12,13,12,15,13,12,13,13,
  144637. 14,15,11,12,12,14,13,11,12,12,14,15,12,13,13,15,
  144638. 14,13,12,14,12,16,13,14,14,15,15,11,11,12,14,14,
  144639. 11,12,11,14,13,12,13,13,14,15,13,14,12,16,12,14,
  144640. 14,15,16,16, 8, 9, 9,11,12, 9,10,10,12,12, 9,10,
  144641. 10,12,13,11,12,12,13,13,12,12,13,14,14, 9,10,10,
  144642. 12,12,10,11,10,13,12,10,10,11,12,13,12,13,13,15,
  144643. 14,12,12,13,13,15, 9,10,10,12,13,10,11,11,12,13,
  144644. 10,11,11,13,13,12,13,13,14,15,12,13,12,15,14,11,
  144645. 12,11,14,13,12,13,13,15,14,11,11,12,13,14,14,15,
  144646. 14,16,15,13,12,14,13,16,11,12,12,13,14,12,13,13,
  144647. 14,15,11,12,11,14,14,14,14,14,15,16,13,15,12,16,
  144648. 12,
  144649. };
  144650. static float _vq_quantthresh__44u5__p4_0[] = {
  144651. -1.5, -0.5, 0.5, 1.5,
  144652. };
  144653. static long _vq_quantmap__44u5__p4_0[] = {
  144654. 3, 1, 0, 2, 4,
  144655. };
  144656. static encode_aux_threshmatch _vq_auxt__44u5__p4_0 = {
  144657. _vq_quantthresh__44u5__p4_0,
  144658. _vq_quantmap__44u5__p4_0,
  144659. 5,
  144660. 5
  144661. };
  144662. static static_codebook _44u5__p4_0 = {
  144663. 4, 625,
  144664. _vq_lengthlist__44u5__p4_0,
  144665. 1, -533725184, 1611661312, 3, 0,
  144666. _vq_quantlist__44u5__p4_0,
  144667. NULL,
  144668. &_vq_auxt__44u5__p4_0,
  144669. NULL,
  144670. 0
  144671. };
  144672. static long _vq_quantlist__44u5__p5_0[] = {
  144673. 4,
  144674. 3,
  144675. 5,
  144676. 2,
  144677. 6,
  144678. 1,
  144679. 7,
  144680. 0,
  144681. 8,
  144682. };
  144683. static long _vq_lengthlist__44u5__p5_0[] = {
  144684. 2, 3, 3, 6, 6, 8, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  144685. 11,10, 3, 5, 5, 7, 8, 8, 8,10,11, 6, 8, 7,10, 9,
  144686. 10,10,11,11, 6, 7, 8, 9, 9, 9,10,11,12, 8, 8, 8,
  144687. 10,10,11,11,13,12, 8, 8, 9, 9,10,11,11,12,13,10,
  144688. 11,10,12,11,13,12,14,14,10,10,11,11,12,12,13,14,
  144689. 14,
  144690. };
  144691. static float _vq_quantthresh__44u5__p5_0[] = {
  144692. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  144693. };
  144694. static long _vq_quantmap__44u5__p5_0[] = {
  144695. 7, 5, 3, 1, 0, 2, 4, 6,
  144696. 8,
  144697. };
  144698. static encode_aux_threshmatch _vq_auxt__44u5__p5_0 = {
  144699. _vq_quantthresh__44u5__p5_0,
  144700. _vq_quantmap__44u5__p5_0,
  144701. 9,
  144702. 9
  144703. };
  144704. static static_codebook _44u5__p5_0 = {
  144705. 2, 81,
  144706. _vq_lengthlist__44u5__p5_0,
  144707. 1, -531628032, 1611661312, 4, 0,
  144708. _vq_quantlist__44u5__p5_0,
  144709. NULL,
  144710. &_vq_auxt__44u5__p5_0,
  144711. NULL,
  144712. 0
  144713. };
  144714. static long _vq_quantlist__44u5__p6_0[] = {
  144715. 4,
  144716. 3,
  144717. 5,
  144718. 2,
  144719. 6,
  144720. 1,
  144721. 7,
  144722. 0,
  144723. 8,
  144724. };
  144725. static long _vq_lengthlist__44u5__p6_0[] = {
  144726. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  144727. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  144728. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8,10,10, 7, 7, 7,
  144729. 8, 8, 9, 9,11,10, 7, 7, 7, 8, 8, 9, 9,10,11, 9,
  144730. 9, 9,10,10,11,10,11,11, 9, 9, 9,10,10,11,10,11,
  144731. 11,
  144732. };
  144733. static float _vq_quantthresh__44u5__p6_0[] = {
  144734. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  144735. };
  144736. static long _vq_quantmap__44u5__p6_0[] = {
  144737. 7, 5, 3, 1, 0, 2, 4, 6,
  144738. 8,
  144739. };
  144740. static encode_aux_threshmatch _vq_auxt__44u5__p6_0 = {
  144741. _vq_quantthresh__44u5__p6_0,
  144742. _vq_quantmap__44u5__p6_0,
  144743. 9,
  144744. 9
  144745. };
  144746. static static_codebook _44u5__p6_0 = {
  144747. 2, 81,
  144748. _vq_lengthlist__44u5__p6_0,
  144749. 1, -531628032, 1611661312, 4, 0,
  144750. _vq_quantlist__44u5__p6_0,
  144751. NULL,
  144752. &_vq_auxt__44u5__p6_0,
  144753. NULL,
  144754. 0
  144755. };
  144756. static long _vq_quantlist__44u5__p7_0[] = {
  144757. 1,
  144758. 0,
  144759. 2,
  144760. };
  144761. static long _vq_lengthlist__44u5__p7_0[] = {
  144762. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 9, 8,11,10, 7,
  144763. 11,10, 5, 9, 9, 7,10,10, 8,10,11, 4, 9, 9, 9,12,
  144764. 12, 9,12,12, 8,12,12,11,12,12,10,12,13, 7,12,12,
  144765. 11,12,12,10,12,13, 4, 9, 9, 9,12,12, 9,12,12, 7,
  144766. 12,11,10,13,13,11,12,12, 7,12,12,10,13,13,11,12,
  144767. 12,
  144768. };
  144769. static float _vq_quantthresh__44u5__p7_0[] = {
  144770. -5.5, 5.5,
  144771. };
  144772. static long _vq_quantmap__44u5__p7_0[] = {
  144773. 1, 0, 2,
  144774. };
  144775. static encode_aux_threshmatch _vq_auxt__44u5__p7_0 = {
  144776. _vq_quantthresh__44u5__p7_0,
  144777. _vq_quantmap__44u5__p7_0,
  144778. 3,
  144779. 3
  144780. };
  144781. static static_codebook _44u5__p7_0 = {
  144782. 4, 81,
  144783. _vq_lengthlist__44u5__p7_0,
  144784. 1, -529137664, 1618345984, 2, 0,
  144785. _vq_quantlist__44u5__p7_0,
  144786. NULL,
  144787. &_vq_auxt__44u5__p7_0,
  144788. NULL,
  144789. 0
  144790. };
  144791. static long _vq_quantlist__44u5__p7_1[] = {
  144792. 5,
  144793. 4,
  144794. 6,
  144795. 3,
  144796. 7,
  144797. 2,
  144798. 8,
  144799. 1,
  144800. 9,
  144801. 0,
  144802. 10,
  144803. };
  144804. static long _vq_lengthlist__44u5__p7_1[] = {
  144805. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 7,
  144806. 8, 8, 9, 8, 8, 9, 4, 5, 5, 7, 7, 8, 8, 9, 9, 8,
  144807. 9, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  144808. 8, 9, 9, 9, 9, 9, 9, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  144809. 9, 9, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9,
  144810. 9, 9, 9, 9,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  144811. 10,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10, 8, 9,
  144812. 9, 9, 9, 9, 9,10,10,10,10,
  144813. };
  144814. static float _vq_quantthresh__44u5__p7_1[] = {
  144815. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  144816. 3.5, 4.5,
  144817. };
  144818. static long _vq_quantmap__44u5__p7_1[] = {
  144819. 9, 7, 5, 3, 1, 0, 2, 4,
  144820. 6, 8, 10,
  144821. };
  144822. static encode_aux_threshmatch _vq_auxt__44u5__p7_1 = {
  144823. _vq_quantthresh__44u5__p7_1,
  144824. _vq_quantmap__44u5__p7_1,
  144825. 11,
  144826. 11
  144827. };
  144828. static static_codebook _44u5__p7_1 = {
  144829. 2, 121,
  144830. _vq_lengthlist__44u5__p7_1,
  144831. 1, -531365888, 1611661312, 4, 0,
  144832. _vq_quantlist__44u5__p7_1,
  144833. NULL,
  144834. &_vq_auxt__44u5__p7_1,
  144835. NULL,
  144836. 0
  144837. };
  144838. static long _vq_quantlist__44u5__p8_0[] = {
  144839. 5,
  144840. 4,
  144841. 6,
  144842. 3,
  144843. 7,
  144844. 2,
  144845. 8,
  144846. 1,
  144847. 9,
  144848. 0,
  144849. 10,
  144850. };
  144851. static long _vq_lengthlist__44u5__p8_0[] = {
  144852. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7,
  144853. 9, 9,10,10,11,11, 4, 6, 6, 7, 7, 9, 9,10,10,11,
  144854. 11, 6, 8, 7, 9, 9,10,10,11,11,13,12, 6, 8, 8, 9,
  144855. 9,10,10,11,11,12,13, 8, 9, 9,10,10,12,12,13,12,
  144856. 14,13, 8, 9, 9,10,10,12,12,13,13,14,14, 9,11,11,
  144857. 12,12,13,13,14,14,15,14, 9,11,11,12,12,13,13,14,
  144858. 14,15,14,11,12,12,13,13,14,14,15,14,15,14,11,11,
  144859. 12,13,13,14,14,14,14,15,15,
  144860. };
  144861. static float _vq_quantthresh__44u5__p8_0[] = {
  144862. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  144863. 38.5, 49.5,
  144864. };
  144865. static long _vq_quantmap__44u5__p8_0[] = {
  144866. 9, 7, 5, 3, 1, 0, 2, 4,
  144867. 6, 8, 10,
  144868. };
  144869. static encode_aux_threshmatch _vq_auxt__44u5__p8_0 = {
  144870. _vq_quantthresh__44u5__p8_0,
  144871. _vq_quantmap__44u5__p8_0,
  144872. 11,
  144873. 11
  144874. };
  144875. static static_codebook _44u5__p8_0 = {
  144876. 2, 121,
  144877. _vq_lengthlist__44u5__p8_0,
  144878. 1, -524582912, 1618345984, 4, 0,
  144879. _vq_quantlist__44u5__p8_0,
  144880. NULL,
  144881. &_vq_auxt__44u5__p8_0,
  144882. NULL,
  144883. 0
  144884. };
  144885. static long _vq_quantlist__44u5__p8_1[] = {
  144886. 5,
  144887. 4,
  144888. 6,
  144889. 3,
  144890. 7,
  144891. 2,
  144892. 8,
  144893. 1,
  144894. 9,
  144895. 0,
  144896. 10,
  144897. };
  144898. static long _vq_lengthlist__44u5__p8_1[] = {
  144899. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 5, 7, 6,
  144900. 7, 7, 8, 8, 8, 8, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  144901. 8, 6, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 6, 6, 7, 7,
  144902. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  144903. 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8,
  144904. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  144905. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  144906. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  144907. };
  144908. static float _vq_quantthresh__44u5__p8_1[] = {
  144909. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  144910. 3.5, 4.5,
  144911. };
  144912. static long _vq_quantmap__44u5__p8_1[] = {
  144913. 9, 7, 5, 3, 1, 0, 2, 4,
  144914. 6, 8, 10,
  144915. };
  144916. static encode_aux_threshmatch _vq_auxt__44u5__p8_1 = {
  144917. _vq_quantthresh__44u5__p8_1,
  144918. _vq_quantmap__44u5__p8_1,
  144919. 11,
  144920. 11
  144921. };
  144922. static static_codebook _44u5__p8_1 = {
  144923. 2, 121,
  144924. _vq_lengthlist__44u5__p8_1,
  144925. 1, -531365888, 1611661312, 4, 0,
  144926. _vq_quantlist__44u5__p8_1,
  144927. NULL,
  144928. &_vq_auxt__44u5__p8_1,
  144929. NULL,
  144930. 0
  144931. };
  144932. static long _vq_quantlist__44u5__p9_0[] = {
  144933. 6,
  144934. 5,
  144935. 7,
  144936. 4,
  144937. 8,
  144938. 3,
  144939. 9,
  144940. 2,
  144941. 10,
  144942. 1,
  144943. 11,
  144944. 0,
  144945. 12,
  144946. };
  144947. static long _vq_lengthlist__44u5__p9_0[] = {
  144948. 1, 3, 2,12,10,13,13,13,13,13,13,13,13, 4, 9, 9,
  144949. 13,13,13,13,13,13,13,13,13,13, 5,10, 9,13,13,13,
  144950. 13,13,13,13,13,13,13,12,13,13,13,13,13,13,13,13,
  144951. 13,13,13,13,11,13,13,13,13,13,13,13,13,13,13,13,
  144952. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  144953. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  144954. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  144955. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  144956. 13,13,13,13,13,13,13,13,13,13,13,13,13,12,12,12,
  144957. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144958. 12,12,12,12,12,12,12,12,12,
  144959. };
  144960. static float _vq_quantthresh__44u5__p9_0[] = {
  144961. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  144962. 637.5, 892.5, 1147.5, 1402.5,
  144963. };
  144964. static long _vq_quantmap__44u5__p9_0[] = {
  144965. 11, 9, 7, 5, 3, 1, 0, 2,
  144966. 4, 6, 8, 10, 12,
  144967. };
  144968. static encode_aux_threshmatch _vq_auxt__44u5__p9_0 = {
  144969. _vq_quantthresh__44u5__p9_0,
  144970. _vq_quantmap__44u5__p9_0,
  144971. 13,
  144972. 13
  144973. };
  144974. static static_codebook _44u5__p9_0 = {
  144975. 2, 169,
  144976. _vq_lengthlist__44u5__p9_0,
  144977. 1, -514332672, 1627381760, 4, 0,
  144978. _vq_quantlist__44u5__p9_0,
  144979. NULL,
  144980. &_vq_auxt__44u5__p9_0,
  144981. NULL,
  144982. 0
  144983. };
  144984. static long _vq_quantlist__44u5__p9_1[] = {
  144985. 7,
  144986. 6,
  144987. 8,
  144988. 5,
  144989. 9,
  144990. 4,
  144991. 10,
  144992. 3,
  144993. 11,
  144994. 2,
  144995. 12,
  144996. 1,
  144997. 13,
  144998. 0,
  144999. 14,
  145000. };
  145001. static long _vq_lengthlist__44u5__p9_1[] = {
  145002. 1, 4, 4, 7, 7, 8, 8, 8, 7, 8, 7, 9, 8, 9, 9, 4,
  145003. 7, 6, 9, 8,10,10, 9, 8, 9, 9, 9, 9, 9, 8, 5, 6,
  145004. 6, 8, 9,10,10, 9, 9, 9,10,10,10,10,11, 7, 8, 8,
  145005. 10,10,11,11,10,10,11,11,11,12,11,11, 7, 8, 8,10,
  145006. 10,11,11,10,10,11,11,12,11,11,11, 8, 9, 9,11,11,
  145007. 12,12,11,11,12,11,12,12,12,12, 8, 9,10,11,11,12,
  145008. 12,11,11,12,12,12,12,12,12, 8, 9, 9,10,10,12,11,
  145009. 12,12,12,12,12,12,12,13, 8, 9, 9,11,11,11,11,12,
  145010. 12,12,12,13,12,13,13, 9,10,10,11,11,12,12,12,13,
  145011. 12,13,13,13,14,13, 9,10,10,11,11,12,12,12,13,13,
  145012. 12,13,13,14,13, 9,11,10,12,11,13,12,12,13,13,13,
  145013. 13,13,13,14, 9,10,10,12,12,12,12,12,13,13,13,13,
  145014. 13,14,14,10,11,11,12,12,12,13,13,13,14,14,13,14,
  145015. 14,14,10,11,11,12,12,12,12,13,12,13,14,13,14,14,
  145016. 14,
  145017. };
  145018. static float _vq_quantthresh__44u5__p9_1[] = {
  145019. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  145020. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  145021. };
  145022. static long _vq_quantmap__44u5__p9_1[] = {
  145023. 13, 11, 9, 7, 5, 3, 1, 0,
  145024. 2, 4, 6, 8, 10, 12, 14,
  145025. };
  145026. static encode_aux_threshmatch _vq_auxt__44u5__p9_1 = {
  145027. _vq_quantthresh__44u5__p9_1,
  145028. _vq_quantmap__44u5__p9_1,
  145029. 15,
  145030. 15
  145031. };
  145032. static static_codebook _44u5__p9_1 = {
  145033. 2, 225,
  145034. _vq_lengthlist__44u5__p9_1,
  145035. 1, -522338304, 1620115456, 4, 0,
  145036. _vq_quantlist__44u5__p9_1,
  145037. NULL,
  145038. &_vq_auxt__44u5__p9_1,
  145039. NULL,
  145040. 0
  145041. };
  145042. static long _vq_quantlist__44u5__p9_2[] = {
  145043. 8,
  145044. 7,
  145045. 9,
  145046. 6,
  145047. 10,
  145048. 5,
  145049. 11,
  145050. 4,
  145051. 12,
  145052. 3,
  145053. 13,
  145054. 2,
  145055. 14,
  145056. 1,
  145057. 15,
  145058. 0,
  145059. 16,
  145060. };
  145061. static long _vq_lengthlist__44u5__p9_2[] = {
  145062. 2, 5, 5, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  145063. 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  145064. 9, 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  145065. 9, 9, 9, 7, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  145066. 9, 9, 9, 9, 7, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  145067. 9, 9, 9, 9, 9, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  145068. 9,10, 9,10,10,10, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  145069. 9, 9,10, 9,10, 9,10, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  145070. 9,10, 9,10,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  145071. 9,10, 9,10,10,10,10,10,10, 9, 9, 9, 9, 9,10, 9,
  145072. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,
  145073. 9,10, 9,10, 9,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  145074. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  145075. 9, 9,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  145076. 9,10,10, 9,10,10,10,10,10,10,10,10,10,10, 9, 9,
  145077. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  145078. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  145079. 9, 9, 9,10, 9,10,10,10,10,10,10,10,10,10,10,10,
  145080. 10,
  145081. };
  145082. static float _vq_quantthresh__44u5__p9_2[] = {
  145083. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  145084. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  145085. };
  145086. static long _vq_quantmap__44u5__p9_2[] = {
  145087. 15, 13, 11, 9, 7, 5, 3, 1,
  145088. 0, 2, 4, 6, 8, 10, 12, 14,
  145089. 16,
  145090. };
  145091. static encode_aux_threshmatch _vq_auxt__44u5__p9_2 = {
  145092. _vq_quantthresh__44u5__p9_2,
  145093. _vq_quantmap__44u5__p9_2,
  145094. 17,
  145095. 17
  145096. };
  145097. static static_codebook _44u5__p9_2 = {
  145098. 2, 289,
  145099. _vq_lengthlist__44u5__p9_2,
  145100. 1, -529530880, 1611661312, 5, 0,
  145101. _vq_quantlist__44u5__p9_2,
  145102. NULL,
  145103. &_vq_auxt__44u5__p9_2,
  145104. NULL,
  145105. 0
  145106. };
  145107. static long _huff_lengthlist__44u5__short[] = {
  145108. 4,10,17,13,17,13,17,17,17,17, 3, 6, 8, 9,11, 9,
  145109. 15,12,16,17, 6, 5, 5, 7, 7, 8,10,11,17,17, 7, 8,
  145110. 7, 9, 9,10,13,13,17,17, 8, 6, 5, 7, 4, 7, 5, 8,
  145111. 14,17, 9, 9, 8, 9, 7, 9, 8,10,16,17,12,10, 7, 8,
  145112. 4, 7, 4, 7,16,17,12,11, 9,10, 6, 9, 5, 7,14,17,
  145113. 14,13,10,15, 4, 8, 3, 5,14,17,17,14,11,15, 6,10,
  145114. 6, 8,15,17,
  145115. };
  145116. static static_codebook _huff_book__44u5__short = {
  145117. 2, 100,
  145118. _huff_lengthlist__44u5__short,
  145119. 0, 0, 0, 0, 0,
  145120. NULL,
  145121. NULL,
  145122. NULL,
  145123. NULL,
  145124. 0
  145125. };
  145126. static long _huff_lengthlist__44u6__long[] = {
  145127. 3, 9,14,13,14,13,16,12,13,14, 5, 4, 6, 6, 8, 9,
  145128. 11,10,12,15,10, 5, 5, 6, 6, 8,10,10,13,16,10, 6,
  145129. 6, 6, 6, 8, 9, 9,12,14,13, 7, 6, 6, 4, 6, 6, 7,
  145130. 11,14,10, 7, 7, 7, 6, 6, 6, 7,10,13,15,10, 9, 8,
  145131. 5, 6, 5, 6,10,14,10, 9, 8, 8, 6, 6, 5, 4, 6,11,
  145132. 11,11,12,11,10, 9, 9, 5, 5, 9,10,12,15,13,13,13,
  145133. 13, 8, 7, 7,
  145134. };
  145135. static static_codebook _huff_book__44u6__long = {
  145136. 2, 100,
  145137. _huff_lengthlist__44u6__long,
  145138. 0, 0, 0, 0, 0,
  145139. NULL,
  145140. NULL,
  145141. NULL,
  145142. NULL,
  145143. 0
  145144. };
  145145. static long _vq_quantlist__44u6__p1_0[] = {
  145146. 1,
  145147. 0,
  145148. 2,
  145149. };
  145150. static long _vq_lengthlist__44u6__p1_0[] = {
  145151. 1, 4, 4, 4, 8, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  145152. 9,10, 5, 8, 8, 7,10, 9, 8,10,10, 5, 8, 8, 8,10,
  145153. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  145154. 10,13,11,10,13,13, 5, 8, 8, 8,11,10, 8,10,10, 7,
  145155. 10,10,10,13,13,10,11,13, 8,10,11,10,13,13,10,13,
  145156. 12,
  145157. };
  145158. static float _vq_quantthresh__44u6__p1_0[] = {
  145159. -0.5, 0.5,
  145160. };
  145161. static long _vq_quantmap__44u6__p1_0[] = {
  145162. 1, 0, 2,
  145163. };
  145164. static encode_aux_threshmatch _vq_auxt__44u6__p1_0 = {
  145165. _vq_quantthresh__44u6__p1_0,
  145166. _vq_quantmap__44u6__p1_0,
  145167. 3,
  145168. 3
  145169. };
  145170. static static_codebook _44u6__p1_0 = {
  145171. 4, 81,
  145172. _vq_lengthlist__44u6__p1_0,
  145173. 1, -535822336, 1611661312, 2, 0,
  145174. _vq_quantlist__44u6__p1_0,
  145175. NULL,
  145176. &_vq_auxt__44u6__p1_0,
  145177. NULL,
  145178. 0
  145179. };
  145180. static long _vq_quantlist__44u6__p2_0[] = {
  145181. 1,
  145182. 0,
  145183. 2,
  145184. };
  145185. static long _vq_lengthlist__44u6__p2_0[] = {
  145186. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  145187. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  145188. 8, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 7, 7,
  145189. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  145190. 8, 8, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  145191. 9,
  145192. };
  145193. static float _vq_quantthresh__44u6__p2_0[] = {
  145194. -0.5, 0.5,
  145195. };
  145196. static long _vq_quantmap__44u6__p2_0[] = {
  145197. 1, 0, 2,
  145198. };
  145199. static encode_aux_threshmatch _vq_auxt__44u6__p2_0 = {
  145200. _vq_quantthresh__44u6__p2_0,
  145201. _vq_quantmap__44u6__p2_0,
  145202. 3,
  145203. 3
  145204. };
  145205. static static_codebook _44u6__p2_0 = {
  145206. 4, 81,
  145207. _vq_lengthlist__44u6__p2_0,
  145208. 1, -535822336, 1611661312, 2, 0,
  145209. _vq_quantlist__44u6__p2_0,
  145210. NULL,
  145211. &_vq_auxt__44u6__p2_0,
  145212. NULL,
  145213. 0
  145214. };
  145215. static long _vq_quantlist__44u6__p3_0[] = {
  145216. 2,
  145217. 1,
  145218. 3,
  145219. 0,
  145220. 4,
  145221. };
  145222. static long _vq_lengthlist__44u6__p3_0[] = {
  145223. 2, 5, 4, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  145224. 9, 9,13,12, 8, 9,10,12,13, 5, 7, 7,10, 9, 7, 9,
  145225. 9,11,11, 7, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  145226. 13,14, 5, 7, 7, 9,10, 6, 9, 8,11,11, 7, 9, 9,11,
  145227. 11, 9,11,10,14,13,10,11,11,14,13, 8,10,10,13,13,
  145228. 10,11,11,15,15, 9,11,11,14,14,13,14,14,17,16,12,
  145229. 13,14,16,16, 8,10,10,13,14, 9,11,11,14,15,10,11,
  145230. 12,14,15,12,14,13,16,15,13,14,14,15,17, 5, 7, 7,
  145231. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,12,11,14,
  145232. 14,10,11,11,14,14, 7, 9, 9,12,11, 9,11,11,13,13,
  145233. 9,11,11,13,13,11,13,13,14,15,11,12,13,15,16, 6,
  145234. 9, 9,11,12, 8,11,10,13,12, 9,11,11,13,14,11,13,
  145235. 12,16,14,11,13,13,15,16,10,12,11,14,15,11,13,13,
  145236. 15,17,11,13,13,17,16,15,15,16,17,16,14,15,16,18,
  145237. 0, 9,11,11,14,15,10,12,12,16,15,11,13,13,16,16,
  145238. 13,15,14,18,15,14,16,16, 0, 0, 5, 7, 7,10,10, 7,
  145239. 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  145240. 12,14,14, 6, 9, 9,11,11, 9,11,11,13,13, 8,10,11,
  145241. 12,13,11,13,13,16,15,11,12,13,14,16, 7, 9, 9,11,
  145242. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,16,15,
  145243. 11,13,12,15,15, 9,11,11,15,14,11,13,13,17,16,10,
  145244. 12,13,15,16,14,16,16, 0,18,14,14,15,15,17,10,11,
  145245. 12,15,15,11,13,13,16,16,11,13,13,16,16,14,16,16,
  145246. 19,17,14,15,15,17,17, 8,10,10,14,14,10,12,11,15,
  145247. 15,10,11,12,16,15,14,15,15,18,20,13,14,16,17,18,
  145248. 9,11,11,15,16,11,13,13,17,17,11,13,13,17,16,15,
  145249. 16,16, 0, 0,15,16,16, 0, 0, 9,11,11,15,15,10,13,
  145250. 12,17,15,11,13,13,17,16,15,17,15,20,19,15,16,16,
  145251. 19, 0,13,15,14, 0,17,14,15,16, 0,20,15,16,16, 0,
  145252. 19,17,18, 0, 0, 0,16,17,18, 0, 0,12,14,14,19,18,
  145253. 13,15,14, 0,17,14,15,16,19,19,16,18,16, 0,19,19,
  145254. 20,17,20, 0, 8,10,10,13,14,10,11,11,15,15,10,12,
  145255. 12,15,16,14,15,14,19,16,14,15,15, 0,18, 9,11,11,
  145256. 16,15,11,13,13, 0,16,11,12,13,16,17,14,16,17, 0,
  145257. 19,15,16,16,18, 0, 9,11,11,15,16,11,13,13,16,16,
  145258. 11,14,13,18,17,15,16,16,18,20,15,17,19, 0, 0,12,
  145259. 14,14,17,17,14,16,15, 0, 0,13,14,15,19, 0,16,18,
  145260. 20, 0, 0,16,16,18,18, 0,12,14,14,17,20,14,16,16,
  145261. 19, 0,14,16,14, 0,20,16,20,17, 0, 0,17, 0,15, 0,
  145262. 19,
  145263. };
  145264. static float _vq_quantthresh__44u6__p3_0[] = {
  145265. -1.5, -0.5, 0.5, 1.5,
  145266. };
  145267. static long _vq_quantmap__44u6__p3_0[] = {
  145268. 3, 1, 0, 2, 4,
  145269. };
  145270. static encode_aux_threshmatch _vq_auxt__44u6__p3_0 = {
  145271. _vq_quantthresh__44u6__p3_0,
  145272. _vq_quantmap__44u6__p3_0,
  145273. 5,
  145274. 5
  145275. };
  145276. static static_codebook _44u6__p3_0 = {
  145277. 4, 625,
  145278. _vq_lengthlist__44u6__p3_0,
  145279. 1, -533725184, 1611661312, 3, 0,
  145280. _vq_quantlist__44u6__p3_0,
  145281. NULL,
  145282. &_vq_auxt__44u6__p3_0,
  145283. NULL,
  145284. 0
  145285. };
  145286. static long _vq_quantlist__44u6__p4_0[] = {
  145287. 2,
  145288. 1,
  145289. 3,
  145290. 0,
  145291. 4,
  145292. };
  145293. static long _vq_lengthlist__44u6__p4_0[] = {
  145294. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  145295. 9, 9,11,11, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  145296. 8,10,10, 7, 7, 8, 9,10, 9,10,10,11,11, 9, 9,10,
  145297. 11,12, 6, 7, 7, 9, 9, 7, 8, 7,10, 9, 7, 8, 8,10,
  145298. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,11,11,
  145299. 9,10,10,12,12, 9,10,10,12,12,11,12,12,14,13,11,
  145300. 11,12,13,13, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  145301. 10,12,12,11,12,11,13,12,11,12,12,13,13, 5, 7, 7,
  145302. 9, 9, 7, 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,
  145303. 11, 9,10,10,11,12, 7, 8, 8,10,10, 8, 8, 9,11,11,
  145304. 8, 9, 9,11,11,10,10,11,12,13,10,10,11,12,12, 6,
  145305. 7, 7,10,10, 7, 9, 8,11,10, 8, 8, 9,10,11,10,11,
  145306. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  145307. 13,13,10,11,11,12,13,12,12,12,13,14,12,12,13,14,
  145308. 14, 9,10,10,12,12, 9,10,10,13,12,10,11,11,13,13,
  145309. 11,12,11,14,12,12,13,13,14,14, 6, 7, 7, 9, 9, 7,
  145310. 8, 7,10,10, 7, 8, 8,10,10, 9,10,10,12,11, 9,10,
  145311. 10,11,12, 6, 7, 7,10,10, 8, 9, 8,11,10, 7, 8, 9,
  145312. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 8, 8,10,
  145313. 10, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,10,13,12,
  145314. 10,11,11,13,12, 9,10,10,12,12,10,11,11,13,12, 9,
  145315. 10,10,12,13,12,13,12,14,14,11,11,12,12,14, 9,10,
  145316. 10,12,12,10,11,11,13,13,10,11,10,13,12,12,12,12,
  145317. 14,14,12,13,12,14,13, 8, 9, 9,11,11, 9,10,10,12,
  145318. 12, 9,10,10,12,12,11,12,12,14,13,11,12,12,13,14,
  145319. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,13,12,
  145320. 12,13,14,15,12,12,13,14,14, 9,10,10,12,12, 9,11,
  145321. 10,13,12,10,10,11,12,13,12,13,12,14,13,12,12,13,
  145322. 14,15,11,12,12,14,13,11,12,12,14,14,12,13,13,14,
  145323. 14,13,13,14,14,16,13,14,14,15,15,11,12,11,13,13,
  145324. 11,12,11,14,13,12,12,13,14,15,12,14,12,15,12,13,
  145325. 14,15,15,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  145326. 10,12,12,11,12,12,14,13,11,12,12,13,13, 9,10,10,
  145327. 12,12,10,11,10,13,12, 9,10,11,12,13,12,13,12,14,
  145328. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,13,13,
  145329. 10,11,11,13,13,12,13,12,14,14,12,13,13,14,14,11,
  145330. 11,11,13,13,12,13,12,14,14,11,11,12,13,14,14,14,
  145331. 14,16,15,12,12,14,12,15,11,12,12,13,14,12,13,13,
  145332. 14,15,11,12,12,14,14,13,14,14,16,16,13,14,13,16,
  145333. 13,
  145334. };
  145335. static float _vq_quantthresh__44u6__p4_0[] = {
  145336. -1.5, -0.5, 0.5, 1.5,
  145337. };
  145338. static long _vq_quantmap__44u6__p4_0[] = {
  145339. 3, 1, 0, 2, 4,
  145340. };
  145341. static encode_aux_threshmatch _vq_auxt__44u6__p4_0 = {
  145342. _vq_quantthresh__44u6__p4_0,
  145343. _vq_quantmap__44u6__p4_0,
  145344. 5,
  145345. 5
  145346. };
  145347. static static_codebook _44u6__p4_0 = {
  145348. 4, 625,
  145349. _vq_lengthlist__44u6__p4_0,
  145350. 1, -533725184, 1611661312, 3, 0,
  145351. _vq_quantlist__44u6__p4_0,
  145352. NULL,
  145353. &_vq_auxt__44u6__p4_0,
  145354. NULL,
  145355. 0
  145356. };
  145357. static long _vq_quantlist__44u6__p5_0[] = {
  145358. 4,
  145359. 3,
  145360. 5,
  145361. 2,
  145362. 6,
  145363. 1,
  145364. 7,
  145365. 0,
  145366. 8,
  145367. };
  145368. static long _vq_lengthlist__44u6__p5_0[] = {
  145369. 2, 3, 3, 6, 6, 8, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  145370. 11,11, 3, 5, 5, 7, 8, 8, 8,11,11, 6, 8, 7, 9, 9,
  145371. 10, 9,12,11, 6, 7, 8, 9, 9, 9,10,11,12, 8, 8, 8,
  145372. 10, 9,12,11,13,13, 8, 8, 9, 9,10,11,12,13,13,10,
  145373. 11,11,12,12,13,13,14,14,10,10,11,11,12,13,13,14,
  145374. 14,
  145375. };
  145376. static float _vq_quantthresh__44u6__p5_0[] = {
  145377. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  145378. };
  145379. static long _vq_quantmap__44u6__p5_0[] = {
  145380. 7, 5, 3, 1, 0, 2, 4, 6,
  145381. 8,
  145382. };
  145383. static encode_aux_threshmatch _vq_auxt__44u6__p5_0 = {
  145384. _vq_quantthresh__44u6__p5_0,
  145385. _vq_quantmap__44u6__p5_0,
  145386. 9,
  145387. 9
  145388. };
  145389. static static_codebook _44u6__p5_0 = {
  145390. 2, 81,
  145391. _vq_lengthlist__44u6__p5_0,
  145392. 1, -531628032, 1611661312, 4, 0,
  145393. _vq_quantlist__44u6__p5_0,
  145394. NULL,
  145395. &_vq_auxt__44u6__p5_0,
  145396. NULL,
  145397. 0
  145398. };
  145399. static long _vq_quantlist__44u6__p6_0[] = {
  145400. 4,
  145401. 3,
  145402. 5,
  145403. 2,
  145404. 6,
  145405. 1,
  145406. 7,
  145407. 0,
  145408. 8,
  145409. };
  145410. static long _vq_lengthlist__44u6__p6_0[] = {
  145411. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  145412. 9, 9, 4, 4, 5, 6, 6, 7, 8, 9, 9, 5, 6, 6, 7, 7,
  145413. 8, 8,10,10, 5, 6, 6, 7, 7, 8, 8,10,10, 7, 8, 7,
  145414. 8, 8,10, 9,11,11, 7, 7, 8, 8, 8, 9,10,10,11, 9,
  145415. 9, 9,10,10,11,11,12,11, 9, 9, 9,10,10,11,11,11,
  145416. 12,
  145417. };
  145418. static float _vq_quantthresh__44u6__p6_0[] = {
  145419. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  145420. };
  145421. static long _vq_quantmap__44u6__p6_0[] = {
  145422. 7, 5, 3, 1, 0, 2, 4, 6,
  145423. 8,
  145424. };
  145425. static encode_aux_threshmatch _vq_auxt__44u6__p6_0 = {
  145426. _vq_quantthresh__44u6__p6_0,
  145427. _vq_quantmap__44u6__p6_0,
  145428. 9,
  145429. 9
  145430. };
  145431. static static_codebook _44u6__p6_0 = {
  145432. 2, 81,
  145433. _vq_lengthlist__44u6__p6_0,
  145434. 1, -531628032, 1611661312, 4, 0,
  145435. _vq_quantlist__44u6__p6_0,
  145436. NULL,
  145437. &_vq_auxt__44u6__p6_0,
  145438. NULL,
  145439. 0
  145440. };
  145441. static long _vq_quantlist__44u6__p7_0[] = {
  145442. 1,
  145443. 0,
  145444. 2,
  145445. };
  145446. static long _vq_lengthlist__44u6__p7_0[] = {
  145447. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 7,10,10, 8,
  145448. 10,10, 5, 8, 9, 7,10,10, 7,10, 9, 4, 8, 8, 9,11,
  145449. 11, 8,11,11, 7,11,11,10,10,13,10,13,13, 7,11,11,
  145450. 10,13,12,10,13,13, 5, 9, 8, 8,11,11, 9,11,11, 7,
  145451. 11,11,10,13,13,10,12,13, 7,11,11,10,13,13, 9,13,
  145452. 10,
  145453. };
  145454. static float _vq_quantthresh__44u6__p7_0[] = {
  145455. -5.5, 5.5,
  145456. };
  145457. static long _vq_quantmap__44u6__p7_0[] = {
  145458. 1, 0, 2,
  145459. };
  145460. static encode_aux_threshmatch _vq_auxt__44u6__p7_0 = {
  145461. _vq_quantthresh__44u6__p7_0,
  145462. _vq_quantmap__44u6__p7_0,
  145463. 3,
  145464. 3
  145465. };
  145466. static static_codebook _44u6__p7_0 = {
  145467. 4, 81,
  145468. _vq_lengthlist__44u6__p7_0,
  145469. 1, -529137664, 1618345984, 2, 0,
  145470. _vq_quantlist__44u6__p7_0,
  145471. NULL,
  145472. &_vq_auxt__44u6__p7_0,
  145473. NULL,
  145474. 0
  145475. };
  145476. static long _vq_quantlist__44u6__p7_1[] = {
  145477. 5,
  145478. 4,
  145479. 6,
  145480. 3,
  145481. 7,
  145482. 2,
  145483. 8,
  145484. 1,
  145485. 9,
  145486. 0,
  145487. 10,
  145488. };
  145489. static long _vq_lengthlist__44u6__p7_1[] = {
  145490. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 6,
  145491. 8, 8, 8, 8, 8, 8, 4, 5, 5, 6, 7, 8, 8, 8, 8, 8,
  145492. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  145493. 7, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 9, 9,
  145494. 9, 9, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  145495. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  145496. 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  145497. 8, 8, 8, 9, 9, 9, 9, 9, 9,
  145498. };
  145499. static float _vq_quantthresh__44u6__p7_1[] = {
  145500. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  145501. 3.5, 4.5,
  145502. };
  145503. static long _vq_quantmap__44u6__p7_1[] = {
  145504. 9, 7, 5, 3, 1, 0, 2, 4,
  145505. 6, 8, 10,
  145506. };
  145507. static encode_aux_threshmatch _vq_auxt__44u6__p7_1 = {
  145508. _vq_quantthresh__44u6__p7_1,
  145509. _vq_quantmap__44u6__p7_1,
  145510. 11,
  145511. 11
  145512. };
  145513. static static_codebook _44u6__p7_1 = {
  145514. 2, 121,
  145515. _vq_lengthlist__44u6__p7_1,
  145516. 1, -531365888, 1611661312, 4, 0,
  145517. _vq_quantlist__44u6__p7_1,
  145518. NULL,
  145519. &_vq_auxt__44u6__p7_1,
  145520. NULL,
  145521. 0
  145522. };
  145523. static long _vq_quantlist__44u6__p8_0[] = {
  145524. 5,
  145525. 4,
  145526. 6,
  145527. 3,
  145528. 7,
  145529. 2,
  145530. 8,
  145531. 1,
  145532. 9,
  145533. 0,
  145534. 10,
  145535. };
  145536. static long _vq_lengthlist__44u6__p8_0[] = {
  145537. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7,
  145538. 9, 9,10,10,11,11, 4, 6, 6, 7, 7, 9, 9,10,10,11,
  145539. 11, 6, 8, 8, 9, 9,10,10,11,11,12,12, 6, 8, 8, 9,
  145540. 9,10,10,11,11,12,12, 8, 9, 9,10,10,11,11,12,12,
  145541. 13,13, 8, 9, 9,10,10,11,11,12,12,13,13,10,10,10,
  145542. 11,11,13,13,13,13,15,14, 9,10,10,12,11,12,13,13,
  145543. 13,14,15,11,12,12,13,13,13,13,15,14,15,15,11,11,
  145544. 12,13,13,14,14,14,15,15,15,
  145545. };
  145546. static float _vq_quantthresh__44u6__p8_0[] = {
  145547. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  145548. 38.5, 49.5,
  145549. };
  145550. static long _vq_quantmap__44u6__p8_0[] = {
  145551. 9, 7, 5, 3, 1, 0, 2, 4,
  145552. 6, 8, 10,
  145553. };
  145554. static encode_aux_threshmatch _vq_auxt__44u6__p8_0 = {
  145555. _vq_quantthresh__44u6__p8_0,
  145556. _vq_quantmap__44u6__p8_0,
  145557. 11,
  145558. 11
  145559. };
  145560. static static_codebook _44u6__p8_0 = {
  145561. 2, 121,
  145562. _vq_lengthlist__44u6__p8_0,
  145563. 1, -524582912, 1618345984, 4, 0,
  145564. _vq_quantlist__44u6__p8_0,
  145565. NULL,
  145566. &_vq_auxt__44u6__p8_0,
  145567. NULL,
  145568. 0
  145569. };
  145570. static long _vq_quantlist__44u6__p8_1[] = {
  145571. 5,
  145572. 4,
  145573. 6,
  145574. 3,
  145575. 7,
  145576. 2,
  145577. 8,
  145578. 1,
  145579. 9,
  145580. 0,
  145581. 10,
  145582. };
  145583. static long _vq_lengthlist__44u6__p8_1[] = {
  145584. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 5, 7, 7,
  145585. 7, 7, 8, 7, 8, 8, 5, 5, 6, 6, 7, 7, 7, 7, 7, 8,
  145586. 8, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 6, 6, 7, 7,
  145587. 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  145588. 8, 8, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7,
  145589. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  145590. 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  145591. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  145592. };
  145593. static float _vq_quantthresh__44u6__p8_1[] = {
  145594. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  145595. 3.5, 4.5,
  145596. };
  145597. static long _vq_quantmap__44u6__p8_1[] = {
  145598. 9, 7, 5, 3, 1, 0, 2, 4,
  145599. 6, 8, 10,
  145600. };
  145601. static encode_aux_threshmatch _vq_auxt__44u6__p8_1 = {
  145602. _vq_quantthresh__44u6__p8_1,
  145603. _vq_quantmap__44u6__p8_1,
  145604. 11,
  145605. 11
  145606. };
  145607. static static_codebook _44u6__p8_1 = {
  145608. 2, 121,
  145609. _vq_lengthlist__44u6__p8_1,
  145610. 1, -531365888, 1611661312, 4, 0,
  145611. _vq_quantlist__44u6__p8_1,
  145612. NULL,
  145613. &_vq_auxt__44u6__p8_1,
  145614. NULL,
  145615. 0
  145616. };
  145617. static long _vq_quantlist__44u6__p9_0[] = {
  145618. 7,
  145619. 6,
  145620. 8,
  145621. 5,
  145622. 9,
  145623. 4,
  145624. 10,
  145625. 3,
  145626. 11,
  145627. 2,
  145628. 12,
  145629. 1,
  145630. 13,
  145631. 0,
  145632. 14,
  145633. };
  145634. static long _vq_lengthlist__44u6__p9_0[] = {
  145635. 1, 3, 2, 9, 8,15,15,15,15,15,15,15,15,15,15, 4,
  145636. 8, 9,13,14,14,14,14,14,14,14,14,14,14,14, 5, 8,
  145637. 9,14,14,14,14,14,14,14,14,14,14,14,14,11,14,14,
  145638. 14,14,14,14,14,14,14,14,14,14,14,14,11,14,14,14,
  145639. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  145640. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  145641. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  145642. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  145643. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  145644. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  145645. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  145646. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  145647. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  145648. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  145649. 14,
  145650. };
  145651. static float _vq_quantthresh__44u6__p9_0[] = {
  145652. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  145653. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  145654. };
  145655. static long _vq_quantmap__44u6__p9_0[] = {
  145656. 13, 11, 9, 7, 5, 3, 1, 0,
  145657. 2, 4, 6, 8, 10, 12, 14,
  145658. };
  145659. static encode_aux_threshmatch _vq_auxt__44u6__p9_0 = {
  145660. _vq_quantthresh__44u6__p9_0,
  145661. _vq_quantmap__44u6__p9_0,
  145662. 15,
  145663. 15
  145664. };
  145665. static static_codebook _44u6__p9_0 = {
  145666. 2, 225,
  145667. _vq_lengthlist__44u6__p9_0,
  145668. 1, -514071552, 1627381760, 4, 0,
  145669. _vq_quantlist__44u6__p9_0,
  145670. NULL,
  145671. &_vq_auxt__44u6__p9_0,
  145672. NULL,
  145673. 0
  145674. };
  145675. static long _vq_quantlist__44u6__p9_1[] = {
  145676. 7,
  145677. 6,
  145678. 8,
  145679. 5,
  145680. 9,
  145681. 4,
  145682. 10,
  145683. 3,
  145684. 11,
  145685. 2,
  145686. 12,
  145687. 1,
  145688. 13,
  145689. 0,
  145690. 14,
  145691. };
  145692. static long _vq_lengthlist__44u6__p9_1[] = {
  145693. 1, 4, 4, 7, 7, 8, 9, 8, 8, 9, 8, 9, 8, 9, 9, 4,
  145694. 7, 6, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 4, 7,
  145695. 6, 9, 9,10,10, 9, 9,10,10,10,10,11,11, 7, 9, 8,
  145696. 10,10,11,11,10,10,11,11,11,11,11,11, 7, 8, 9,10,
  145697. 10,11,11,10,10,11,11,11,11,11,12, 8,10,10,11,11,
  145698. 12,12,11,11,12,12,12,12,13,12, 8,10,10,11,11,12,
  145699. 11,11,11,11,12,12,12,12,13, 8, 9, 9,11,10,11,11,
  145700. 12,12,12,12,13,12,13,12, 8, 9, 9,11,11,11,11,12,
  145701. 12,12,12,12,13,13,13, 9,10,10,11,12,12,12,12,12,
  145702. 13,13,13,13,13,13, 9,10,10,11,11,12,12,12,12,13,
  145703. 13,13,13,14,13,10,10,10,12,11,12,12,13,13,13,13,
  145704. 13,13,13,13,10,10,11,11,11,12,12,13,13,13,13,13,
  145705. 13,13,13,10,11,11,12,12,13,12,12,13,13,13,13,13,
  145706. 13,14,10,11,11,12,12,13,12,13,13,13,14,13,13,14,
  145707. 13,
  145708. };
  145709. static float _vq_quantthresh__44u6__p9_1[] = {
  145710. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  145711. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  145712. };
  145713. static long _vq_quantmap__44u6__p9_1[] = {
  145714. 13, 11, 9, 7, 5, 3, 1, 0,
  145715. 2, 4, 6, 8, 10, 12, 14,
  145716. };
  145717. static encode_aux_threshmatch _vq_auxt__44u6__p9_1 = {
  145718. _vq_quantthresh__44u6__p9_1,
  145719. _vq_quantmap__44u6__p9_1,
  145720. 15,
  145721. 15
  145722. };
  145723. static static_codebook _44u6__p9_1 = {
  145724. 2, 225,
  145725. _vq_lengthlist__44u6__p9_1,
  145726. 1, -522338304, 1620115456, 4, 0,
  145727. _vq_quantlist__44u6__p9_1,
  145728. NULL,
  145729. &_vq_auxt__44u6__p9_1,
  145730. NULL,
  145731. 0
  145732. };
  145733. static long _vq_quantlist__44u6__p9_2[] = {
  145734. 8,
  145735. 7,
  145736. 9,
  145737. 6,
  145738. 10,
  145739. 5,
  145740. 11,
  145741. 4,
  145742. 12,
  145743. 3,
  145744. 13,
  145745. 2,
  145746. 14,
  145747. 1,
  145748. 15,
  145749. 0,
  145750. 16,
  145751. };
  145752. static long _vq_lengthlist__44u6__p9_2[] = {
  145753. 3, 5, 5, 7, 7, 8, 8, 8, 8, 8, 8, 9, 8, 8, 9, 9,
  145754. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  145755. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9,
  145756. 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  145757. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  145758. 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  145759. 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  145760. 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  145761. 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  145762. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9, 9, 9, 9, 9,
  145763. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 8, 9, 9, 9, 9, 9,
  145764. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  145765. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9, 9, 9, 9, 9,
  145766. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,
  145767. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10, 9, 9, 9,
  145768. 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10, 9, 9,10, 9,
  145769. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,10, 9,10,10,
  145770. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10,10, 9, 9,
  145771. 10,
  145772. };
  145773. static float _vq_quantthresh__44u6__p9_2[] = {
  145774. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  145775. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  145776. };
  145777. static long _vq_quantmap__44u6__p9_2[] = {
  145778. 15, 13, 11, 9, 7, 5, 3, 1,
  145779. 0, 2, 4, 6, 8, 10, 12, 14,
  145780. 16,
  145781. };
  145782. static encode_aux_threshmatch _vq_auxt__44u6__p9_2 = {
  145783. _vq_quantthresh__44u6__p9_2,
  145784. _vq_quantmap__44u6__p9_2,
  145785. 17,
  145786. 17
  145787. };
  145788. static static_codebook _44u6__p9_2 = {
  145789. 2, 289,
  145790. _vq_lengthlist__44u6__p9_2,
  145791. 1, -529530880, 1611661312, 5, 0,
  145792. _vq_quantlist__44u6__p9_2,
  145793. NULL,
  145794. &_vq_auxt__44u6__p9_2,
  145795. NULL,
  145796. 0
  145797. };
  145798. static long _huff_lengthlist__44u6__short[] = {
  145799. 4,11,16,13,17,13,17,16,17,17, 4, 7, 9, 9,13,10,
  145800. 16,12,16,17, 7, 6, 5, 7, 8, 9,12,12,16,17, 6, 9,
  145801. 7, 9,10,10,15,15,17,17, 6, 7, 5, 7, 5, 7, 7,10,
  145802. 16,17, 7, 9, 8, 9, 8,10,11,11,15,17, 7, 7, 7, 8,
  145803. 5, 8, 8, 9,15,17, 8, 7, 9, 9, 7, 8, 7, 2, 7,15,
  145804. 14,13,13,15, 5,10, 4, 3, 6,17,17,15,13,17, 7,11,
  145805. 7, 6, 9,16,
  145806. };
  145807. static static_codebook _huff_book__44u6__short = {
  145808. 2, 100,
  145809. _huff_lengthlist__44u6__short,
  145810. 0, 0, 0, 0, 0,
  145811. NULL,
  145812. NULL,
  145813. NULL,
  145814. NULL,
  145815. 0
  145816. };
  145817. static long _huff_lengthlist__44u7__long[] = {
  145818. 3, 9,14,13,15,14,16,13,13,14, 5, 5, 7, 7, 8, 9,
  145819. 11,10,12,15,10, 6, 5, 6, 6, 9,10,10,13,16,10, 6,
  145820. 6, 6, 6, 8, 9, 9,12,15,14, 7, 6, 6, 5, 6, 6, 8,
  145821. 12,15,10, 8, 7, 7, 6, 7, 7, 7,11,13,14,10, 9, 8,
  145822. 5, 6, 4, 5, 9,12,10, 9, 9, 8, 6, 6, 5, 3, 6,11,
  145823. 12,11,12,12,10, 9, 8, 5, 5, 8,10,11,15,13,13,13,
  145824. 12, 8, 6, 7,
  145825. };
  145826. static static_codebook _huff_book__44u7__long = {
  145827. 2, 100,
  145828. _huff_lengthlist__44u7__long,
  145829. 0, 0, 0, 0, 0,
  145830. NULL,
  145831. NULL,
  145832. NULL,
  145833. NULL,
  145834. 0
  145835. };
  145836. static long _vq_quantlist__44u7__p1_0[] = {
  145837. 1,
  145838. 0,
  145839. 2,
  145840. };
  145841. static long _vq_lengthlist__44u7__p1_0[] = {
  145842. 1, 4, 4, 4, 7, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  145843. 10,10, 5, 8, 8, 7,10,10, 8,10,10, 5, 8, 8, 8,11,
  145844. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  145845. 10,13,12,10,13,13, 5, 8, 8, 8,11,10, 8,10,11, 7,
  145846. 10,10,10,13,13,10,12,13, 8,11,11,10,13,13,10,13,
  145847. 12,
  145848. };
  145849. static float _vq_quantthresh__44u7__p1_0[] = {
  145850. -0.5, 0.5,
  145851. };
  145852. static long _vq_quantmap__44u7__p1_0[] = {
  145853. 1, 0, 2,
  145854. };
  145855. static encode_aux_threshmatch _vq_auxt__44u7__p1_0 = {
  145856. _vq_quantthresh__44u7__p1_0,
  145857. _vq_quantmap__44u7__p1_0,
  145858. 3,
  145859. 3
  145860. };
  145861. static static_codebook _44u7__p1_0 = {
  145862. 4, 81,
  145863. _vq_lengthlist__44u7__p1_0,
  145864. 1, -535822336, 1611661312, 2, 0,
  145865. _vq_quantlist__44u7__p1_0,
  145866. NULL,
  145867. &_vq_auxt__44u7__p1_0,
  145868. NULL,
  145869. 0
  145870. };
  145871. static long _vq_quantlist__44u7__p2_0[] = {
  145872. 1,
  145873. 0,
  145874. 2,
  145875. };
  145876. static long _vq_lengthlist__44u7__p2_0[] = {
  145877. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  145878. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  145879. 7, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 8, 7,
  145880. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  145881. 8, 8, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  145882. 9,
  145883. };
  145884. static float _vq_quantthresh__44u7__p2_0[] = {
  145885. -0.5, 0.5,
  145886. };
  145887. static long _vq_quantmap__44u7__p2_0[] = {
  145888. 1, 0, 2,
  145889. };
  145890. static encode_aux_threshmatch _vq_auxt__44u7__p2_0 = {
  145891. _vq_quantthresh__44u7__p2_0,
  145892. _vq_quantmap__44u7__p2_0,
  145893. 3,
  145894. 3
  145895. };
  145896. static static_codebook _44u7__p2_0 = {
  145897. 4, 81,
  145898. _vq_lengthlist__44u7__p2_0,
  145899. 1, -535822336, 1611661312, 2, 0,
  145900. _vq_quantlist__44u7__p2_0,
  145901. NULL,
  145902. &_vq_auxt__44u7__p2_0,
  145903. NULL,
  145904. 0
  145905. };
  145906. static long _vq_quantlist__44u7__p3_0[] = {
  145907. 2,
  145908. 1,
  145909. 3,
  145910. 0,
  145911. 4,
  145912. };
  145913. static long _vq_lengthlist__44u7__p3_0[] = {
  145914. 2, 5, 4, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  145915. 9, 9,13,12, 8, 9,10,12,13, 5, 7, 7,10, 9, 7, 9,
  145916. 9,11,11, 6, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  145917. 13,14, 5, 7, 7, 9, 9, 7, 9, 8,11,11, 7, 9, 9,11,
  145918. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,14,13,
  145919. 10,11,12,15,14, 9,11,11,15,14,13,14,14,16,16,12,
  145920. 13,14,17,16, 8,10,10,13,13, 9,11,11,14,15,10,11,
  145921. 12,14,15,12,14,13,16,16,13,14,15,15,17, 5, 7, 7,
  145922. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,12,11,15,
  145923. 14,10,11,12,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  145924. 9,11,11,13,13,11,13,13,14,17,11,13,13,15,16, 6,
  145925. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,13,11,13,
  145926. 12,16,14,11,13,13,16,16,10,12,12,15,15,11,13,13,
  145927. 16,16,11,13,13,16,15,14,16,17,17,19,14,16,16,18,
  145928. 0, 9,11,11,14,15,10,13,12,16,15,11,13,13,16,16,
  145929. 14,15,14, 0,16,14,16,16,18, 0, 5, 7, 7,10,10, 7,
  145930. 9, 9,12,11, 7, 9, 9,11,12,10,11,11,15,14,10,11,
  145931. 12,14,14, 6, 9, 9,11,11, 9,11,11,13,13, 8,10,11,
  145932. 12,13,11,13,13,17,15,11,12,13,14,15, 7, 9, 9,11,
  145933. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,12,16,16,
  145934. 11,13,13,15,14, 9,11,11,14,15,11,13,13,16,15,10,
  145935. 12,13,16,16,15,16,16, 0, 0,14,13,15,16,18,10,11,
  145936. 11,15,15,11,13,14,16,18,11,13,13,16,15,15,16,16,
  145937. 19, 0,14,15,15,16,16, 8,10,10,13,13,10,12,11,16,
  145938. 15,10,11,11,16,15,13,15,16,18, 0,13,14,15,17,17,
  145939. 9,11,11,15,15,11,13,13,16,18,11,13,13,16,17,15,
  145940. 16,16, 0, 0,15,18,16, 0,17, 9,11,11,15,15,11,13,
  145941. 12,17,15,11,13,14,16,17,15,18,15, 0,17,15,16,16,
  145942. 18,19,13,15,14, 0,18,14,16,16,19,18,14,16,15,19,
  145943. 19,16,18,19, 0, 0,16,17, 0, 0, 0,12,14,14,17,17,
  145944. 13,16,14, 0,18,14,16,15,18, 0,16,18,16,19,17,18,
  145945. 19,17, 0, 0, 8,10,10,14,14, 9,12,11,15,15,10,11,
  145946. 12,15,17,13,15,15,18,16,14,16,15,18,17, 9,11,11,
  145947. 16,15,11,13,13, 0,16,11,12,13,16,15,15,16,16, 0,
  145948. 17,15,15,16,18,17, 9,12,11,15,17,11,13,13,16,16,
  145949. 11,14,13,16,16,15,15,16,18,19,16,18,16, 0, 0,12,
  145950. 14,14, 0,16,14,16,16, 0,18,13,14,15,16, 0,17,16,
  145951. 18, 0, 0,16,16,17,19, 0,13,14,14,17, 0,14,17,16,
  145952. 0,19,14,15,15,18,19,17,16,18, 0, 0,15,19,16, 0,
  145953. 0,
  145954. };
  145955. static float _vq_quantthresh__44u7__p3_0[] = {
  145956. -1.5, -0.5, 0.5, 1.5,
  145957. };
  145958. static long _vq_quantmap__44u7__p3_0[] = {
  145959. 3, 1, 0, 2, 4,
  145960. };
  145961. static encode_aux_threshmatch _vq_auxt__44u7__p3_0 = {
  145962. _vq_quantthresh__44u7__p3_0,
  145963. _vq_quantmap__44u7__p3_0,
  145964. 5,
  145965. 5
  145966. };
  145967. static static_codebook _44u7__p3_0 = {
  145968. 4, 625,
  145969. _vq_lengthlist__44u7__p3_0,
  145970. 1, -533725184, 1611661312, 3, 0,
  145971. _vq_quantlist__44u7__p3_0,
  145972. NULL,
  145973. &_vq_auxt__44u7__p3_0,
  145974. NULL,
  145975. 0
  145976. };
  145977. static long _vq_quantlist__44u7__p4_0[] = {
  145978. 2,
  145979. 1,
  145980. 3,
  145981. 0,
  145982. 4,
  145983. };
  145984. static long _vq_lengthlist__44u7__p4_0[] = {
  145985. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  145986. 9, 9,11,11, 8, 9, 9,10,11, 6, 7, 7, 9, 9, 7, 8,
  145987. 8,10,10, 6, 7, 8, 9,10, 9,10,10,12,12, 9, 9,10,
  145988. 11,12, 6, 7, 7, 9, 9, 6, 8, 7,10, 9, 7, 8, 8,10,
  145989. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,11,11,
  145990. 9,10,10,12,12, 9,10,10,12,12,11,12,12,13,14,11,
  145991. 11,12,13,13, 8, 9, 9,11,11, 9,10,10,12,11, 9,10,
  145992. 10,12,12,11,12,11,13,13,11,12,12,13,13, 6, 7, 7,
  145993. 9, 9, 7, 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,
  145994. 11, 9,10,10,12,12, 7, 8, 8,10,10, 8, 8, 9,11,11,
  145995. 8, 9, 9,11,11,10,11,11,12,12,10,10,11,12,13, 6,
  145996. 7, 7,10,10, 7, 9, 8,11,10, 8, 8, 9,10,11,10,11,
  145997. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  145998. 13,13,10,11,11,13,12,12,12,13,13,14,12,12,13,14,
  145999. 14, 9,10,10,12,12, 9,10,10,12,12,10,11,11,13,13,
  146000. 11,12,11,14,12,12,13,13,14,14, 6, 7, 7, 9, 9, 7,
  146001. 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,11, 9,10,
  146002. 10,11,12, 6, 7, 7,10,10, 8, 9, 8,11,10, 7, 8, 9,
  146003. 10,11,10,11,11,13,12,10,10,11,11,13, 7, 8, 8,10,
  146004. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,10,13,12,
  146005. 10,11,11,12,12, 9,10,10,12,12,10,11,11,13,12, 9,
  146006. 10,10,12,13,12,13,12,14,14,11,11,12,12,14, 9,10,
  146007. 10,12,12,10,11,11,13,13,10,11,11,13,13,12,13,12,
  146008. 14,14,12,13,12,14,13, 8, 9, 9,11,11, 9,10,10,12,
  146009. 12, 9,10,10,12,12,11,12,12,14,13,11,12,12,13,13,
  146010. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,12,12,
  146011. 13,13,14,14,12,12,13,14,14, 9,10,10,12,12, 9,11,
  146012. 10,13,12,10,10,11,12,13,11,13,12,14,13,12,12,13,
  146013. 14,14,11,12,12,13,13,11,12,13,14,14,12,13,13,14,
  146014. 14,13,13,14,14,16,13,14,14,16,16,11,11,11,13,13,
  146015. 11,12,11,14,13,12,12,13,14,15,13,14,12,16,13,14,
  146016. 14,14,15,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  146017. 10,12,12,11,12,12,14,13,11,12,12,13,14, 9,10,10,
  146018. 12,12,10,11,10,13,12, 9,10,11,12,13,12,13,12,14,
  146019. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,12,13,
  146020. 10,11,11,13,13,12,13,12,14,14,12,13,13,14,14,11,
  146021. 12,12,13,13,12,13,12,14,14,11,11,12,13,14,13,15,
  146022. 14,16,15,13,12,14,13,16,11,12,12,13,13,12,13,13,
  146023. 14,14,12,12,12,14,14,13,14,14,15,15,13,14,13,16,
  146024. 14,
  146025. };
  146026. static float _vq_quantthresh__44u7__p4_0[] = {
  146027. -1.5, -0.5, 0.5, 1.5,
  146028. };
  146029. static long _vq_quantmap__44u7__p4_0[] = {
  146030. 3, 1, 0, 2, 4,
  146031. };
  146032. static encode_aux_threshmatch _vq_auxt__44u7__p4_0 = {
  146033. _vq_quantthresh__44u7__p4_0,
  146034. _vq_quantmap__44u7__p4_0,
  146035. 5,
  146036. 5
  146037. };
  146038. static static_codebook _44u7__p4_0 = {
  146039. 4, 625,
  146040. _vq_lengthlist__44u7__p4_0,
  146041. 1, -533725184, 1611661312, 3, 0,
  146042. _vq_quantlist__44u7__p4_0,
  146043. NULL,
  146044. &_vq_auxt__44u7__p4_0,
  146045. NULL,
  146046. 0
  146047. };
  146048. static long _vq_quantlist__44u7__p5_0[] = {
  146049. 4,
  146050. 3,
  146051. 5,
  146052. 2,
  146053. 6,
  146054. 1,
  146055. 7,
  146056. 0,
  146057. 8,
  146058. };
  146059. static long _vq_lengthlist__44u7__p5_0[] = {
  146060. 2, 3, 3, 6, 6, 7, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  146061. 11,11, 3, 5, 5, 7, 7, 8, 9,11,11, 6, 8, 7, 9, 9,
  146062. 10,10,12,12, 6, 7, 8, 9,10,10,10,12,12, 8, 8, 8,
  146063. 10,10,12,11,13,13, 8, 8, 9,10,10,11,11,13,13,10,
  146064. 11,11,12,12,13,13,14,14,10,11,11,12,12,13,13,14,
  146065. 14,
  146066. };
  146067. static float _vq_quantthresh__44u7__p5_0[] = {
  146068. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  146069. };
  146070. static long _vq_quantmap__44u7__p5_0[] = {
  146071. 7, 5, 3, 1, 0, 2, 4, 6,
  146072. 8,
  146073. };
  146074. static encode_aux_threshmatch _vq_auxt__44u7__p5_0 = {
  146075. _vq_quantthresh__44u7__p5_0,
  146076. _vq_quantmap__44u7__p5_0,
  146077. 9,
  146078. 9
  146079. };
  146080. static static_codebook _44u7__p5_0 = {
  146081. 2, 81,
  146082. _vq_lengthlist__44u7__p5_0,
  146083. 1, -531628032, 1611661312, 4, 0,
  146084. _vq_quantlist__44u7__p5_0,
  146085. NULL,
  146086. &_vq_auxt__44u7__p5_0,
  146087. NULL,
  146088. 0
  146089. };
  146090. static long _vq_quantlist__44u7__p6_0[] = {
  146091. 4,
  146092. 3,
  146093. 5,
  146094. 2,
  146095. 6,
  146096. 1,
  146097. 7,
  146098. 0,
  146099. 8,
  146100. };
  146101. static long _vq_lengthlist__44u7__p6_0[] = {
  146102. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 8, 7,
  146103. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  146104. 8, 8,10,10, 5, 6, 6, 7, 7, 8, 8,10,10, 7, 8, 7,
  146105. 8, 8,10, 9,11,11, 7, 7, 8, 8, 8, 9,10,11,11, 9,
  146106. 9, 9,10,10,11,10,12,11, 9, 9, 9,10,10,11,11,11,
  146107. 12,
  146108. };
  146109. static float _vq_quantthresh__44u7__p6_0[] = {
  146110. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  146111. };
  146112. static long _vq_quantmap__44u7__p6_0[] = {
  146113. 7, 5, 3, 1, 0, 2, 4, 6,
  146114. 8,
  146115. };
  146116. static encode_aux_threshmatch _vq_auxt__44u7__p6_0 = {
  146117. _vq_quantthresh__44u7__p6_0,
  146118. _vq_quantmap__44u7__p6_0,
  146119. 9,
  146120. 9
  146121. };
  146122. static static_codebook _44u7__p6_0 = {
  146123. 2, 81,
  146124. _vq_lengthlist__44u7__p6_0,
  146125. 1, -531628032, 1611661312, 4, 0,
  146126. _vq_quantlist__44u7__p6_0,
  146127. NULL,
  146128. &_vq_auxt__44u7__p6_0,
  146129. NULL,
  146130. 0
  146131. };
  146132. static long _vq_quantlist__44u7__p7_0[] = {
  146133. 1,
  146134. 0,
  146135. 2,
  146136. };
  146137. static long _vq_lengthlist__44u7__p7_0[] = {
  146138. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 8, 9, 9, 7,
  146139. 10,10, 5, 8, 9, 7, 9,10, 8, 9, 9, 4, 9, 9, 9,11,
  146140. 10, 8,10,10, 7,11,10,10,10,12,10,12,12, 7,10,10,
  146141. 10,12,11,10,12,12, 5, 9, 9, 8,10,10, 9,11,11, 7,
  146142. 11,10,10,12,12,10,11,12, 7,10,11,10,12,12,10,12,
  146143. 10,
  146144. };
  146145. static float _vq_quantthresh__44u7__p7_0[] = {
  146146. -5.5, 5.5,
  146147. };
  146148. static long _vq_quantmap__44u7__p7_0[] = {
  146149. 1, 0, 2,
  146150. };
  146151. static encode_aux_threshmatch _vq_auxt__44u7__p7_0 = {
  146152. _vq_quantthresh__44u7__p7_0,
  146153. _vq_quantmap__44u7__p7_0,
  146154. 3,
  146155. 3
  146156. };
  146157. static static_codebook _44u7__p7_0 = {
  146158. 4, 81,
  146159. _vq_lengthlist__44u7__p7_0,
  146160. 1, -529137664, 1618345984, 2, 0,
  146161. _vq_quantlist__44u7__p7_0,
  146162. NULL,
  146163. &_vq_auxt__44u7__p7_0,
  146164. NULL,
  146165. 0
  146166. };
  146167. static long _vq_quantlist__44u7__p7_1[] = {
  146168. 5,
  146169. 4,
  146170. 6,
  146171. 3,
  146172. 7,
  146173. 2,
  146174. 8,
  146175. 1,
  146176. 9,
  146177. 0,
  146178. 10,
  146179. };
  146180. static long _vq_lengthlist__44u7__p7_1[] = {
  146181. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 6, 6,
  146182. 8, 7, 8, 8, 8, 8, 4, 5, 5, 6, 6, 7, 8, 8, 8, 8,
  146183. 8, 6, 7, 6, 7, 7, 8, 8, 9, 9, 9, 9, 6, 6, 7, 7,
  146184. 7, 8, 8, 9, 9, 9, 9, 7, 8, 7, 8, 8, 9, 9, 9, 9,
  146185. 9, 9, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8,
  146186. 9, 9, 9, 9,10, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  146187. 9, 9,10, 8, 8, 8, 9, 9, 9, 9,10, 9,10,10, 8, 8,
  146188. 8, 9, 9, 9, 9, 9,10,10,10,
  146189. };
  146190. static float _vq_quantthresh__44u7__p7_1[] = {
  146191. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  146192. 3.5, 4.5,
  146193. };
  146194. static long _vq_quantmap__44u7__p7_1[] = {
  146195. 9, 7, 5, 3, 1, 0, 2, 4,
  146196. 6, 8, 10,
  146197. };
  146198. static encode_aux_threshmatch _vq_auxt__44u7__p7_1 = {
  146199. _vq_quantthresh__44u7__p7_1,
  146200. _vq_quantmap__44u7__p7_1,
  146201. 11,
  146202. 11
  146203. };
  146204. static static_codebook _44u7__p7_1 = {
  146205. 2, 121,
  146206. _vq_lengthlist__44u7__p7_1,
  146207. 1, -531365888, 1611661312, 4, 0,
  146208. _vq_quantlist__44u7__p7_1,
  146209. NULL,
  146210. &_vq_auxt__44u7__p7_1,
  146211. NULL,
  146212. 0
  146213. };
  146214. static long _vq_quantlist__44u7__p8_0[] = {
  146215. 5,
  146216. 4,
  146217. 6,
  146218. 3,
  146219. 7,
  146220. 2,
  146221. 8,
  146222. 1,
  146223. 9,
  146224. 0,
  146225. 10,
  146226. };
  146227. static long _vq_lengthlist__44u7__p8_0[] = {
  146228. 1, 4, 4, 6, 6, 8, 8,10,10,11,11, 4, 6, 6, 7, 7,
  146229. 9, 9,11,10,12,12, 5, 6, 5, 7, 7, 9, 9,10,11,12,
  146230. 12, 6, 7, 7, 8, 8,10,10,11,11,13,13, 6, 7, 7, 8,
  146231. 8,10,10,11,12,13,13, 8, 9, 9,10,10,11,11,12,12,
  146232. 14,14, 8, 9, 9,10,10,11,11,12,12,14,14,10,10,10,
  146233. 11,11,13,12,14,14,15,15,10,10,10,12,12,13,13,14,
  146234. 14,15,15,11,12,12,13,13,14,14,15,14,16,15,11,12,
  146235. 12,13,13,14,14,15,15,15,16,
  146236. };
  146237. static float _vq_quantthresh__44u7__p8_0[] = {
  146238. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  146239. 38.5, 49.5,
  146240. };
  146241. static long _vq_quantmap__44u7__p8_0[] = {
  146242. 9, 7, 5, 3, 1, 0, 2, 4,
  146243. 6, 8, 10,
  146244. };
  146245. static encode_aux_threshmatch _vq_auxt__44u7__p8_0 = {
  146246. _vq_quantthresh__44u7__p8_0,
  146247. _vq_quantmap__44u7__p8_0,
  146248. 11,
  146249. 11
  146250. };
  146251. static static_codebook _44u7__p8_0 = {
  146252. 2, 121,
  146253. _vq_lengthlist__44u7__p8_0,
  146254. 1, -524582912, 1618345984, 4, 0,
  146255. _vq_quantlist__44u7__p8_0,
  146256. NULL,
  146257. &_vq_auxt__44u7__p8_0,
  146258. NULL,
  146259. 0
  146260. };
  146261. static long _vq_quantlist__44u7__p8_1[] = {
  146262. 5,
  146263. 4,
  146264. 6,
  146265. 3,
  146266. 7,
  146267. 2,
  146268. 8,
  146269. 1,
  146270. 9,
  146271. 0,
  146272. 10,
  146273. };
  146274. static long _vq_lengthlist__44u7__p8_1[] = {
  146275. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  146276. 7, 7, 7, 7, 7, 7, 5, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  146277. 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 6, 7, 7, 7,
  146278. 7, 7, 7, 7, 7, 8, 8, 7, 7, 7, 7, 7, 8, 7, 8, 8,
  146279. 8, 8, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  146280. 7, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8,
  146281. 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 7,
  146282. 7, 8, 8, 8, 8, 8, 8, 8, 8,
  146283. };
  146284. static float _vq_quantthresh__44u7__p8_1[] = {
  146285. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  146286. 3.5, 4.5,
  146287. };
  146288. static long _vq_quantmap__44u7__p8_1[] = {
  146289. 9, 7, 5, 3, 1, 0, 2, 4,
  146290. 6, 8, 10,
  146291. };
  146292. static encode_aux_threshmatch _vq_auxt__44u7__p8_1 = {
  146293. _vq_quantthresh__44u7__p8_1,
  146294. _vq_quantmap__44u7__p8_1,
  146295. 11,
  146296. 11
  146297. };
  146298. static static_codebook _44u7__p8_1 = {
  146299. 2, 121,
  146300. _vq_lengthlist__44u7__p8_1,
  146301. 1, -531365888, 1611661312, 4, 0,
  146302. _vq_quantlist__44u7__p8_1,
  146303. NULL,
  146304. &_vq_auxt__44u7__p8_1,
  146305. NULL,
  146306. 0
  146307. };
  146308. static long _vq_quantlist__44u7__p9_0[] = {
  146309. 5,
  146310. 4,
  146311. 6,
  146312. 3,
  146313. 7,
  146314. 2,
  146315. 8,
  146316. 1,
  146317. 9,
  146318. 0,
  146319. 10,
  146320. };
  146321. static long _vq_lengthlist__44u7__p9_0[] = {
  146322. 1, 3, 3,10,10,10,10,10,10,10,10, 4,10,10,10,10,
  146323. 10,10,10,10,10,10, 4,10,10,10,10,10,10,10,10,10,
  146324. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146325. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146326. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146327. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146328. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  146329. 9, 9, 9, 9, 9, 9, 9, 9, 9,
  146330. };
  146331. static float _vq_quantthresh__44u7__p9_0[] = {
  146332. -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5, 1592.5,
  146333. 2229.5, 2866.5,
  146334. };
  146335. static long _vq_quantmap__44u7__p9_0[] = {
  146336. 9, 7, 5, 3, 1, 0, 2, 4,
  146337. 6, 8, 10,
  146338. };
  146339. static encode_aux_threshmatch _vq_auxt__44u7__p9_0 = {
  146340. _vq_quantthresh__44u7__p9_0,
  146341. _vq_quantmap__44u7__p9_0,
  146342. 11,
  146343. 11
  146344. };
  146345. static static_codebook _44u7__p9_0 = {
  146346. 2, 121,
  146347. _vq_lengthlist__44u7__p9_0,
  146348. 1, -512171520, 1630791680, 4, 0,
  146349. _vq_quantlist__44u7__p9_0,
  146350. NULL,
  146351. &_vq_auxt__44u7__p9_0,
  146352. NULL,
  146353. 0
  146354. };
  146355. static long _vq_quantlist__44u7__p9_1[] = {
  146356. 6,
  146357. 5,
  146358. 7,
  146359. 4,
  146360. 8,
  146361. 3,
  146362. 9,
  146363. 2,
  146364. 10,
  146365. 1,
  146366. 11,
  146367. 0,
  146368. 12,
  146369. };
  146370. static long _vq_lengthlist__44u7__p9_1[] = {
  146371. 1, 4, 4, 6, 5, 8, 6, 9, 8,10, 9,11,10, 4, 6, 6,
  146372. 8, 8, 9, 9,11,10,11,11,11,11, 4, 6, 6, 8, 8,10,
  146373. 9,11,11,11,11,11,12, 6, 8, 8,10,10,11,11,12,12,
  146374. 13,12,13,13, 6, 8, 8,10,10,11,11,12,12,12,13,14,
  146375. 13, 8,10,10,11,11,12,13,14,14,14,14,15,15, 8,10,
  146376. 10,11,12,12,13,13,14,14,14,14,15, 9,11,11,13,13,
  146377. 14,14,15,14,16,15,17,15, 9,11,11,12,13,14,14,15,
  146378. 14,15,15,15,16,10,12,12,13,14,15,15,15,15,16,17,
  146379. 16,17,10,13,12,13,14,14,16,16,16,16,15,16,17,11,
  146380. 13,13,14,15,14,17,15,16,17,17,17,17,11,13,13,14,
  146381. 15,15,15,15,17,17,16,17,16,
  146382. };
  146383. static float _vq_quantthresh__44u7__p9_1[] = {
  146384. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  146385. 122.5, 171.5, 220.5, 269.5,
  146386. };
  146387. static long _vq_quantmap__44u7__p9_1[] = {
  146388. 11, 9, 7, 5, 3, 1, 0, 2,
  146389. 4, 6, 8, 10, 12,
  146390. };
  146391. static encode_aux_threshmatch _vq_auxt__44u7__p9_1 = {
  146392. _vq_quantthresh__44u7__p9_1,
  146393. _vq_quantmap__44u7__p9_1,
  146394. 13,
  146395. 13
  146396. };
  146397. static static_codebook _44u7__p9_1 = {
  146398. 2, 169,
  146399. _vq_lengthlist__44u7__p9_1,
  146400. 1, -518889472, 1622704128, 4, 0,
  146401. _vq_quantlist__44u7__p9_1,
  146402. NULL,
  146403. &_vq_auxt__44u7__p9_1,
  146404. NULL,
  146405. 0
  146406. };
  146407. static long _vq_quantlist__44u7__p9_2[] = {
  146408. 24,
  146409. 23,
  146410. 25,
  146411. 22,
  146412. 26,
  146413. 21,
  146414. 27,
  146415. 20,
  146416. 28,
  146417. 19,
  146418. 29,
  146419. 18,
  146420. 30,
  146421. 17,
  146422. 31,
  146423. 16,
  146424. 32,
  146425. 15,
  146426. 33,
  146427. 14,
  146428. 34,
  146429. 13,
  146430. 35,
  146431. 12,
  146432. 36,
  146433. 11,
  146434. 37,
  146435. 10,
  146436. 38,
  146437. 9,
  146438. 39,
  146439. 8,
  146440. 40,
  146441. 7,
  146442. 41,
  146443. 6,
  146444. 42,
  146445. 5,
  146446. 43,
  146447. 4,
  146448. 44,
  146449. 3,
  146450. 45,
  146451. 2,
  146452. 46,
  146453. 1,
  146454. 47,
  146455. 0,
  146456. 48,
  146457. };
  146458. static long _vq_lengthlist__44u7__p9_2[] = {
  146459. 2, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6,
  146460. 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  146461. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  146462. 8,
  146463. };
  146464. static float _vq_quantthresh__44u7__p9_2[] = {
  146465. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  146466. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  146467. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  146468. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  146469. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  146470. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  146471. };
  146472. static long _vq_quantmap__44u7__p9_2[] = {
  146473. 47, 45, 43, 41, 39, 37, 35, 33,
  146474. 31, 29, 27, 25, 23, 21, 19, 17,
  146475. 15, 13, 11, 9, 7, 5, 3, 1,
  146476. 0, 2, 4, 6, 8, 10, 12, 14,
  146477. 16, 18, 20, 22, 24, 26, 28, 30,
  146478. 32, 34, 36, 38, 40, 42, 44, 46,
  146479. 48,
  146480. };
  146481. static encode_aux_threshmatch _vq_auxt__44u7__p9_2 = {
  146482. _vq_quantthresh__44u7__p9_2,
  146483. _vq_quantmap__44u7__p9_2,
  146484. 49,
  146485. 49
  146486. };
  146487. static static_codebook _44u7__p9_2 = {
  146488. 1, 49,
  146489. _vq_lengthlist__44u7__p9_2,
  146490. 1, -526909440, 1611661312, 6, 0,
  146491. _vq_quantlist__44u7__p9_2,
  146492. NULL,
  146493. &_vq_auxt__44u7__p9_2,
  146494. NULL,
  146495. 0
  146496. };
  146497. static long _huff_lengthlist__44u7__short[] = {
  146498. 5,12,17,16,16,17,17,17,17,17, 4, 7,11,11,12, 9,
  146499. 17,10,17,17, 7, 7, 8, 9, 7, 9,11,10,15,17, 7, 9,
  146500. 10,11,10,12,14,12,16,17, 7, 8, 5, 7, 4, 7, 7, 8,
  146501. 16,16, 6,10, 9,10, 7,10,11,11,16,17, 6, 8, 8, 9,
  146502. 5, 7, 5, 8,16,17, 5, 5, 8, 7, 6, 7, 7, 6, 6,14,
  146503. 12,10,12,11, 7,11, 4, 4, 2, 7,17,15,15,15, 8,15,
  146504. 6, 8, 5, 9,
  146505. };
  146506. static static_codebook _huff_book__44u7__short = {
  146507. 2, 100,
  146508. _huff_lengthlist__44u7__short,
  146509. 0, 0, 0, 0, 0,
  146510. NULL,
  146511. NULL,
  146512. NULL,
  146513. NULL,
  146514. 0
  146515. };
  146516. static long _huff_lengthlist__44u8__long[] = {
  146517. 3, 9,13,14,14,15,14,14,15,15, 5, 4, 6, 8,10,12,
  146518. 12,14,15,15, 9, 5, 4, 5, 8,10,11,13,16,16,10, 7,
  146519. 4, 3, 5, 7, 9,11,13,13,10, 9, 7, 4, 4, 6, 8,10,
  146520. 12,14,13,11, 9, 6, 5, 5, 6, 8,12,14,13,11,10, 8,
  146521. 7, 6, 6, 7,10,14,13,11,12,10, 8, 7, 6, 6, 9,13,
  146522. 12,11,14,12,11, 9, 8, 7, 9,11,11,12,14,13,14,11,
  146523. 10, 8, 8, 9,
  146524. };
  146525. static static_codebook _huff_book__44u8__long = {
  146526. 2, 100,
  146527. _huff_lengthlist__44u8__long,
  146528. 0, 0, 0, 0, 0,
  146529. NULL,
  146530. NULL,
  146531. NULL,
  146532. NULL,
  146533. 0
  146534. };
  146535. static long _huff_lengthlist__44u8__short[] = {
  146536. 6,14,18,18,17,17,17,17,17,17, 4, 7, 9, 9,10,13,
  146537. 15,17,17,17, 6, 7, 5, 6, 8,11,16,17,16,17, 5, 7,
  146538. 5, 4, 6,10,14,17,17,17, 6, 6, 6, 5, 7,10,13,16,
  146539. 17,17, 7, 6, 7, 7, 7, 8, 7,10,15,16,12, 9, 9, 6,
  146540. 6, 5, 3, 5,11,15,14,14,13, 5, 5, 7, 3, 4, 8,15,
  146541. 17,17,13, 7, 7,10, 6, 6,10,15,17,17,16,10,11,14,
  146542. 10,10,15,17,
  146543. };
  146544. static static_codebook _huff_book__44u8__short = {
  146545. 2, 100,
  146546. _huff_lengthlist__44u8__short,
  146547. 0, 0, 0, 0, 0,
  146548. NULL,
  146549. NULL,
  146550. NULL,
  146551. NULL,
  146552. 0
  146553. };
  146554. static long _vq_quantlist__44u8_p1_0[] = {
  146555. 1,
  146556. 0,
  146557. 2,
  146558. };
  146559. static long _vq_lengthlist__44u8_p1_0[] = {
  146560. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 8, 9, 9, 7,
  146561. 9, 9, 5, 7, 7, 7, 9, 9, 8, 9, 9, 5, 7, 7, 7, 9,
  146562. 9, 7, 9, 9, 7, 9, 9, 9,10,11, 9,11,10, 7, 9, 9,
  146563. 9,11,10, 9,10,11, 5, 7, 7, 7, 9, 9, 7, 9, 9, 7,
  146564. 9, 9, 9,11,10, 9,10,10, 8, 9, 9, 9,11,11, 9,11,
  146565. 10,
  146566. };
  146567. static float _vq_quantthresh__44u8_p1_0[] = {
  146568. -0.5, 0.5,
  146569. };
  146570. static long _vq_quantmap__44u8_p1_0[] = {
  146571. 1, 0, 2,
  146572. };
  146573. static encode_aux_threshmatch _vq_auxt__44u8_p1_0 = {
  146574. _vq_quantthresh__44u8_p1_0,
  146575. _vq_quantmap__44u8_p1_0,
  146576. 3,
  146577. 3
  146578. };
  146579. static static_codebook _44u8_p1_0 = {
  146580. 4, 81,
  146581. _vq_lengthlist__44u8_p1_0,
  146582. 1, -535822336, 1611661312, 2, 0,
  146583. _vq_quantlist__44u8_p1_0,
  146584. NULL,
  146585. &_vq_auxt__44u8_p1_0,
  146586. NULL,
  146587. 0
  146588. };
  146589. static long _vq_quantlist__44u8_p2_0[] = {
  146590. 2,
  146591. 1,
  146592. 3,
  146593. 0,
  146594. 4,
  146595. };
  146596. static long _vq_lengthlist__44u8_p2_0[] = {
  146597. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  146598. 9, 9,11,11, 8, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  146599. 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,10,
  146600. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  146601. 10, 9,10, 9,12,11, 9,10,10,12,12, 8, 9, 9,12,11,
  146602. 9,10,10,12,12, 9,10,10,12,12,11,12,12,14,14,11,
  146603. 11,12,13,14, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  146604. 10,12,12,11,12,11,13,13,11,12,12,14,14, 5, 7, 7,
  146605. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  146606. 12, 9,10,10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  146607. 8, 9, 9,11,11,10,11,11,12,13,10,11,11,12,13, 6,
  146608. 8, 8,10,10, 8, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  146609. 10,13,12,10,11,11,13,13, 9,10,10,12,12,10,11,11,
  146610. 13,13,10,11,11,13,13,12,12,13,13,14,12,13,13,14,
  146611. 14, 9,10,10,12,12,10,11,10,13,12,10,11,11,13,13,
  146612. 11,13,12,14,13,12,13,13,14,14, 5, 7, 7, 9, 9, 7,
  146613. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,
  146614. 10,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11, 8, 8, 9,
  146615. 10,11,10,11,11,13,13,10,10,11,12,13, 7, 8, 8,10,
  146616. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,13,
  146617. 10,11,11,13,12, 9,10,10,12,12,10,11,11,13,13,10,
  146618. 10,11,12,13,12,13,13,14,14,12,12,13,13,14, 9,10,
  146619. 10,12,12,10,11,11,13,13,10,11,11,13,13,12,13,13,
  146620. 15,14,12,13,13,14,13, 8, 9, 9,11,11, 9,10,10,12,
  146621. 12, 9,10,10,12,12,12,12,12,14,13,11,12,12,14,14,
  146622. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,13,12,
  146623. 13,13,14,15,12,13,13,14,15, 9,10,10,12,12,10,11,
  146624. 10,13,12,10,11,11,13,13,12,13,12,15,14,12,13,13,
  146625. 14,15,11,12,12,14,14,12,13,13,14,14,12,13,13,15,
  146626. 14,14,14,14,14,16,14,14,15,16,16,11,12,12,14,14,
  146627. 11,12,12,14,14,12,13,13,14,15,13,14,13,16,14,14,
  146628. 14,14,16,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  146629. 10,12,12,11,12,12,14,13,11,12,12,14,14, 9,10,10,
  146630. 12,12,10,11,11,13,13,10,10,11,12,13,12,13,13,15,
  146631. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,13,13,
  146632. 10,11,11,13,13,12,13,13,14,14,12,13,13,15,14,11,
  146633. 12,12,14,13,12,13,13,15,14,11,12,12,13,14,14,15,
  146634. 14,16,15,13,13,14,13,16,11,12,12,14,14,12,13,13,
  146635. 14,15,12,13,12,15,14,14,14,14,16,15,14,15,13,16,
  146636. 14,
  146637. };
  146638. static float _vq_quantthresh__44u8_p2_0[] = {
  146639. -1.5, -0.5, 0.5, 1.5,
  146640. };
  146641. static long _vq_quantmap__44u8_p2_0[] = {
  146642. 3, 1, 0, 2, 4,
  146643. };
  146644. static encode_aux_threshmatch _vq_auxt__44u8_p2_0 = {
  146645. _vq_quantthresh__44u8_p2_0,
  146646. _vq_quantmap__44u8_p2_0,
  146647. 5,
  146648. 5
  146649. };
  146650. static static_codebook _44u8_p2_0 = {
  146651. 4, 625,
  146652. _vq_lengthlist__44u8_p2_0,
  146653. 1, -533725184, 1611661312, 3, 0,
  146654. _vq_quantlist__44u8_p2_0,
  146655. NULL,
  146656. &_vq_auxt__44u8_p2_0,
  146657. NULL,
  146658. 0
  146659. };
  146660. static long _vq_quantlist__44u8_p3_0[] = {
  146661. 4,
  146662. 3,
  146663. 5,
  146664. 2,
  146665. 6,
  146666. 1,
  146667. 7,
  146668. 0,
  146669. 8,
  146670. };
  146671. static long _vq_lengthlist__44u8_p3_0[] = {
  146672. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  146673. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  146674. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8,10,10, 7, 7, 7,
  146675. 8, 8, 9, 9,11,10, 7, 7, 7, 8, 8, 9, 9,10,11, 9,
  146676. 9, 9,10,10,11,10,12,11, 9, 9, 9, 9,10,11,11,11,
  146677. 12,
  146678. };
  146679. static float _vq_quantthresh__44u8_p3_0[] = {
  146680. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  146681. };
  146682. static long _vq_quantmap__44u8_p3_0[] = {
  146683. 7, 5, 3, 1, 0, 2, 4, 6,
  146684. 8,
  146685. };
  146686. static encode_aux_threshmatch _vq_auxt__44u8_p3_0 = {
  146687. _vq_quantthresh__44u8_p3_0,
  146688. _vq_quantmap__44u8_p3_0,
  146689. 9,
  146690. 9
  146691. };
  146692. static static_codebook _44u8_p3_0 = {
  146693. 2, 81,
  146694. _vq_lengthlist__44u8_p3_0,
  146695. 1, -531628032, 1611661312, 4, 0,
  146696. _vq_quantlist__44u8_p3_0,
  146697. NULL,
  146698. &_vq_auxt__44u8_p3_0,
  146699. NULL,
  146700. 0
  146701. };
  146702. static long _vq_quantlist__44u8_p4_0[] = {
  146703. 8,
  146704. 7,
  146705. 9,
  146706. 6,
  146707. 10,
  146708. 5,
  146709. 11,
  146710. 4,
  146711. 12,
  146712. 3,
  146713. 13,
  146714. 2,
  146715. 14,
  146716. 1,
  146717. 15,
  146718. 0,
  146719. 16,
  146720. };
  146721. static long _vq_lengthlist__44u8_p4_0[] = {
  146722. 4, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,11,11,11,
  146723. 11, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,
  146724. 12,12, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  146725. 11,12,12, 6, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  146726. 11,11,12,12, 6, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,
  146727. 10,11,11,12,12, 7, 7, 7, 8, 8, 9, 8,10, 9,10, 9,
  146728. 11,10,12,11,13,12, 7, 7, 7, 8, 8, 8, 9, 9,10, 9,
  146729. 10,10,11,11,12,12,13, 8, 8, 8, 9, 9, 9, 9,10,10,
  146730. 11,10,11,11,12,12,13,13, 8, 8, 8, 9, 9, 9,10,10,
  146731. 10,10,11,11,11,12,12,12,13, 8, 9, 9, 9, 9,10, 9,
  146732. 11,10,11,11,12,11,13,12,13,13, 8, 9, 9, 9, 9, 9,
  146733. 10,10,11,11,11,11,12,12,13,13,13,10,10,10,10,10,
  146734. 11,10,11,11,12,11,13,12,13,13,14,13,10,10,10,10,
  146735. 10,10,11,11,11,11,12,12,13,13,13,13,14,11,11,11,
  146736. 11,11,12,11,12,12,13,12,13,13,14,13,14,14,11,11,
  146737. 11,11,11,11,12,12,12,12,13,13,13,13,14,14,14,11,
  146738. 12,12,12,12,13,12,13,12,13,13,14,13,14,14,14,14,
  146739. 11,12,12,12,12,12,12,13,13,13,13,13,14,14,14,14,
  146740. 14,
  146741. };
  146742. static float _vq_quantthresh__44u8_p4_0[] = {
  146743. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  146744. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  146745. };
  146746. static long _vq_quantmap__44u8_p4_0[] = {
  146747. 15, 13, 11, 9, 7, 5, 3, 1,
  146748. 0, 2, 4, 6, 8, 10, 12, 14,
  146749. 16,
  146750. };
  146751. static encode_aux_threshmatch _vq_auxt__44u8_p4_0 = {
  146752. _vq_quantthresh__44u8_p4_0,
  146753. _vq_quantmap__44u8_p4_0,
  146754. 17,
  146755. 17
  146756. };
  146757. static static_codebook _44u8_p4_0 = {
  146758. 2, 289,
  146759. _vq_lengthlist__44u8_p4_0,
  146760. 1, -529530880, 1611661312, 5, 0,
  146761. _vq_quantlist__44u8_p4_0,
  146762. NULL,
  146763. &_vq_auxt__44u8_p4_0,
  146764. NULL,
  146765. 0
  146766. };
  146767. static long _vq_quantlist__44u8_p5_0[] = {
  146768. 1,
  146769. 0,
  146770. 2,
  146771. };
  146772. static long _vq_lengthlist__44u8_p5_0[] = {
  146773. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8, 9, 9, 7,
  146774. 9, 9, 5, 8, 8, 7, 9, 9, 8, 9, 9, 5, 8, 8, 8,10,
  146775. 10, 8,10,10, 7,10,10, 9,10,12, 9,12,11, 7,10,10,
  146776. 9,11,10, 9,11,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  146777. 10,10, 9,11,11, 9,10,11, 7,10,10, 9,11,11,10,12,
  146778. 10,
  146779. };
  146780. static float _vq_quantthresh__44u8_p5_0[] = {
  146781. -5.5, 5.5,
  146782. };
  146783. static long _vq_quantmap__44u8_p5_0[] = {
  146784. 1, 0, 2,
  146785. };
  146786. static encode_aux_threshmatch _vq_auxt__44u8_p5_0 = {
  146787. _vq_quantthresh__44u8_p5_0,
  146788. _vq_quantmap__44u8_p5_0,
  146789. 3,
  146790. 3
  146791. };
  146792. static static_codebook _44u8_p5_0 = {
  146793. 4, 81,
  146794. _vq_lengthlist__44u8_p5_0,
  146795. 1, -529137664, 1618345984, 2, 0,
  146796. _vq_quantlist__44u8_p5_0,
  146797. NULL,
  146798. &_vq_auxt__44u8_p5_0,
  146799. NULL,
  146800. 0
  146801. };
  146802. static long _vq_quantlist__44u8_p5_1[] = {
  146803. 5,
  146804. 4,
  146805. 6,
  146806. 3,
  146807. 7,
  146808. 2,
  146809. 8,
  146810. 1,
  146811. 9,
  146812. 0,
  146813. 10,
  146814. };
  146815. static long _vq_lengthlist__44u8_p5_1[] = {
  146816. 4, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 5, 5, 5, 6, 6,
  146817. 7, 7, 8, 8, 8, 8, 5, 5, 5, 6, 6, 7, 7, 7, 8, 8,
  146818. 8, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 6, 6, 6, 7,
  146819. 7, 7, 7, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  146820. 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 7, 8, 7,
  146821. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  146822. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 8, 8,
  146823. 8, 8, 8, 8, 8, 8, 8, 9, 9,
  146824. };
  146825. static float _vq_quantthresh__44u8_p5_1[] = {
  146826. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  146827. 3.5, 4.5,
  146828. };
  146829. static long _vq_quantmap__44u8_p5_1[] = {
  146830. 9, 7, 5, 3, 1, 0, 2, 4,
  146831. 6, 8, 10,
  146832. };
  146833. static encode_aux_threshmatch _vq_auxt__44u8_p5_1 = {
  146834. _vq_quantthresh__44u8_p5_1,
  146835. _vq_quantmap__44u8_p5_1,
  146836. 11,
  146837. 11
  146838. };
  146839. static static_codebook _44u8_p5_1 = {
  146840. 2, 121,
  146841. _vq_lengthlist__44u8_p5_1,
  146842. 1, -531365888, 1611661312, 4, 0,
  146843. _vq_quantlist__44u8_p5_1,
  146844. NULL,
  146845. &_vq_auxt__44u8_p5_1,
  146846. NULL,
  146847. 0
  146848. };
  146849. static long _vq_quantlist__44u8_p6_0[] = {
  146850. 6,
  146851. 5,
  146852. 7,
  146853. 4,
  146854. 8,
  146855. 3,
  146856. 9,
  146857. 2,
  146858. 10,
  146859. 1,
  146860. 11,
  146861. 0,
  146862. 12,
  146863. };
  146864. static long _vq_lengthlist__44u8_p6_0[] = {
  146865. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 5,
  146866. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7, 8,
  146867. 8, 8, 8, 9, 9,10,10, 6, 7, 7, 7, 8, 8, 8, 8, 9,
  146868. 9,10,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 8,10, 9,11,
  146869. 10, 7, 8, 8, 8, 8, 8, 9, 9, 9,10,10,11,11, 7, 8,
  146870. 8, 8, 8, 9, 8, 9, 9,10,10,11,11, 8, 8, 8, 9, 9,
  146871. 9, 9, 9,10,10,10,11,11, 8, 8, 8, 9, 9, 9, 9,10,
  146872. 9,10,10,11,11, 9, 9, 9, 9,10,10,10,10,10,10,11,
  146873. 11,12, 9, 9, 9,10, 9,10,10,10,10,11,10,12,11,10,
  146874. 10,10,10,10,11,11,11,11,11,12,12,12,10,10,10,10,
  146875. 11,11,11,11,11,12,11,12,12,
  146876. };
  146877. static float _vq_quantthresh__44u8_p6_0[] = {
  146878. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  146879. 12.5, 17.5, 22.5, 27.5,
  146880. };
  146881. static long _vq_quantmap__44u8_p6_0[] = {
  146882. 11, 9, 7, 5, 3, 1, 0, 2,
  146883. 4, 6, 8, 10, 12,
  146884. };
  146885. static encode_aux_threshmatch _vq_auxt__44u8_p6_0 = {
  146886. _vq_quantthresh__44u8_p6_0,
  146887. _vq_quantmap__44u8_p6_0,
  146888. 13,
  146889. 13
  146890. };
  146891. static static_codebook _44u8_p6_0 = {
  146892. 2, 169,
  146893. _vq_lengthlist__44u8_p6_0,
  146894. 1, -526516224, 1616117760, 4, 0,
  146895. _vq_quantlist__44u8_p6_0,
  146896. NULL,
  146897. &_vq_auxt__44u8_p6_0,
  146898. NULL,
  146899. 0
  146900. };
  146901. static long _vq_quantlist__44u8_p6_1[] = {
  146902. 2,
  146903. 1,
  146904. 3,
  146905. 0,
  146906. 4,
  146907. };
  146908. static long _vq_lengthlist__44u8_p6_1[] = {
  146909. 3, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  146910. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  146911. };
  146912. static float _vq_quantthresh__44u8_p6_1[] = {
  146913. -1.5, -0.5, 0.5, 1.5,
  146914. };
  146915. static long _vq_quantmap__44u8_p6_1[] = {
  146916. 3, 1, 0, 2, 4,
  146917. };
  146918. static encode_aux_threshmatch _vq_auxt__44u8_p6_1 = {
  146919. _vq_quantthresh__44u8_p6_1,
  146920. _vq_quantmap__44u8_p6_1,
  146921. 5,
  146922. 5
  146923. };
  146924. static static_codebook _44u8_p6_1 = {
  146925. 2, 25,
  146926. _vq_lengthlist__44u8_p6_1,
  146927. 1, -533725184, 1611661312, 3, 0,
  146928. _vq_quantlist__44u8_p6_1,
  146929. NULL,
  146930. &_vq_auxt__44u8_p6_1,
  146931. NULL,
  146932. 0
  146933. };
  146934. static long _vq_quantlist__44u8_p7_0[] = {
  146935. 6,
  146936. 5,
  146937. 7,
  146938. 4,
  146939. 8,
  146940. 3,
  146941. 9,
  146942. 2,
  146943. 10,
  146944. 1,
  146945. 11,
  146946. 0,
  146947. 12,
  146948. };
  146949. static long _vq_lengthlist__44u8_p7_0[] = {
  146950. 1, 4, 5, 6, 6, 7, 7, 8, 8,10,10,11,11, 5, 6, 6,
  146951. 7, 7, 8, 8, 9, 9,11,10,12,11, 5, 6, 6, 7, 7, 8,
  146952. 8, 9, 9,10,11,11,12, 6, 7, 7, 8, 8, 9, 9,10,10,
  146953. 11,11,12,12, 6, 7, 7, 8, 8, 9, 9,10,10,11,12,13,
  146954. 12, 7, 8, 8, 9, 9,10,10,11,11,12,12,13,13, 8, 8,
  146955. 8, 9, 9,10,10,11,11,12,12,13,13, 9, 9, 9,10,10,
  146956. 11,11,12,12,13,13,14,14, 9, 9, 9,10,10,11,11,12,
  146957. 12,13,13,14,14,10,11,11,12,11,13,12,13,13,14,14,
  146958. 15,15,10,11,11,11,12,12,13,13,14,14,14,15,15,11,
  146959. 12,12,13,13,14,13,15,14,15,15,16,15,11,11,12,13,
  146960. 13,13,14,14,14,15,15,15,16,
  146961. };
  146962. static float _vq_quantthresh__44u8_p7_0[] = {
  146963. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  146964. 27.5, 38.5, 49.5, 60.5,
  146965. };
  146966. static long _vq_quantmap__44u8_p7_0[] = {
  146967. 11, 9, 7, 5, 3, 1, 0, 2,
  146968. 4, 6, 8, 10, 12,
  146969. };
  146970. static encode_aux_threshmatch _vq_auxt__44u8_p7_0 = {
  146971. _vq_quantthresh__44u8_p7_0,
  146972. _vq_quantmap__44u8_p7_0,
  146973. 13,
  146974. 13
  146975. };
  146976. static static_codebook _44u8_p7_0 = {
  146977. 2, 169,
  146978. _vq_lengthlist__44u8_p7_0,
  146979. 1, -523206656, 1618345984, 4, 0,
  146980. _vq_quantlist__44u8_p7_0,
  146981. NULL,
  146982. &_vq_auxt__44u8_p7_0,
  146983. NULL,
  146984. 0
  146985. };
  146986. static long _vq_quantlist__44u8_p7_1[] = {
  146987. 5,
  146988. 4,
  146989. 6,
  146990. 3,
  146991. 7,
  146992. 2,
  146993. 8,
  146994. 1,
  146995. 9,
  146996. 0,
  146997. 10,
  146998. };
  146999. static long _vq_lengthlist__44u8_p7_1[] = {
  147000. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  147001. 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7, 7, 7, 7, 7, 7,
  147002. 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 6, 7, 7, 7,
  147003. 7, 7, 7, 7, 7, 7, 8, 7, 7, 7, 7, 7, 7, 7, 8, 8,
  147004. 8, 8, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 7, 7, 7,
  147005. 8, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8,
  147006. 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 7,
  147007. 7, 8, 8, 8, 8, 8, 8, 8, 8,
  147008. };
  147009. static float _vq_quantthresh__44u8_p7_1[] = {
  147010. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  147011. 3.5, 4.5,
  147012. };
  147013. static long _vq_quantmap__44u8_p7_1[] = {
  147014. 9, 7, 5, 3, 1, 0, 2, 4,
  147015. 6, 8, 10,
  147016. };
  147017. static encode_aux_threshmatch _vq_auxt__44u8_p7_1 = {
  147018. _vq_quantthresh__44u8_p7_1,
  147019. _vq_quantmap__44u8_p7_1,
  147020. 11,
  147021. 11
  147022. };
  147023. static static_codebook _44u8_p7_1 = {
  147024. 2, 121,
  147025. _vq_lengthlist__44u8_p7_1,
  147026. 1, -531365888, 1611661312, 4, 0,
  147027. _vq_quantlist__44u8_p7_1,
  147028. NULL,
  147029. &_vq_auxt__44u8_p7_1,
  147030. NULL,
  147031. 0
  147032. };
  147033. static long _vq_quantlist__44u8_p8_0[] = {
  147034. 7,
  147035. 6,
  147036. 8,
  147037. 5,
  147038. 9,
  147039. 4,
  147040. 10,
  147041. 3,
  147042. 11,
  147043. 2,
  147044. 12,
  147045. 1,
  147046. 13,
  147047. 0,
  147048. 14,
  147049. };
  147050. static long _vq_lengthlist__44u8_p8_0[] = {
  147051. 1, 4, 4, 7, 7, 8, 8, 8, 7, 9, 8,10, 9,11,10, 4,
  147052. 6, 6, 8, 8,10, 9, 9, 9,10,10,11,10,12,10, 4, 6,
  147053. 6, 8, 8,10,10, 9, 9,10,10,11,11,11,12, 7, 8, 8,
  147054. 10,10,11,11,11,10,12,11,12,12,13,11, 7, 8, 8,10,
  147055. 10,11,11,10,10,11,11,12,12,13,13, 8,10,10,11,11,
  147056. 12,11,12,11,13,12,13,12,14,13, 8,10, 9,11,11,12,
  147057. 12,12,12,12,12,13,13,14,13, 8, 9, 9,11,10,12,11,
  147058. 13,12,13,13,14,13,14,13, 8, 9, 9,10,11,12,12,12,
  147059. 12,13,13,14,15,14,14, 9,10,10,12,11,13,12,13,13,
  147060. 14,13,14,14,14,14, 9,10,10,12,12,12,12,13,13,14,
  147061. 14,14,15,14,14,10,11,11,13,12,13,12,14,14,14,14,
  147062. 14,14,15,15,10,11,11,12,12,13,13,14,14,14,15,15,
  147063. 14,16,15,11,12,12,13,12,14,14,14,13,15,14,15,15,
  147064. 15,17,11,12,12,13,13,14,14,14,15,15,14,15,15,14,
  147065. 17,
  147066. };
  147067. static float _vq_quantthresh__44u8_p8_0[] = {
  147068. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  147069. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  147070. };
  147071. static long _vq_quantmap__44u8_p8_0[] = {
  147072. 13, 11, 9, 7, 5, 3, 1, 0,
  147073. 2, 4, 6, 8, 10, 12, 14,
  147074. };
  147075. static encode_aux_threshmatch _vq_auxt__44u8_p8_0 = {
  147076. _vq_quantthresh__44u8_p8_0,
  147077. _vq_quantmap__44u8_p8_0,
  147078. 15,
  147079. 15
  147080. };
  147081. static static_codebook _44u8_p8_0 = {
  147082. 2, 225,
  147083. _vq_lengthlist__44u8_p8_0,
  147084. 1, -520986624, 1620377600, 4, 0,
  147085. _vq_quantlist__44u8_p8_0,
  147086. NULL,
  147087. &_vq_auxt__44u8_p8_0,
  147088. NULL,
  147089. 0
  147090. };
  147091. static long _vq_quantlist__44u8_p8_1[] = {
  147092. 10,
  147093. 9,
  147094. 11,
  147095. 8,
  147096. 12,
  147097. 7,
  147098. 13,
  147099. 6,
  147100. 14,
  147101. 5,
  147102. 15,
  147103. 4,
  147104. 16,
  147105. 3,
  147106. 17,
  147107. 2,
  147108. 18,
  147109. 1,
  147110. 19,
  147111. 0,
  147112. 20,
  147113. };
  147114. static long _vq_lengthlist__44u8_p8_1[] = {
  147115. 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  147116. 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  147117. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 5, 6, 6, 7, 7, 8,
  147118. 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 7,
  147119. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147120. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  147121. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9,
  147122. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10, 8, 8,
  147123. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,
  147124. 10, 9,10, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,
  147125. 10,10,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9, 9,
  147126. 9, 9, 9, 9, 9, 9,10,10,10,10, 9,10,10, 9, 9, 9,
  147127. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  147128. 10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,
  147129. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9,10, 9,
  147130. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  147131. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,
  147132. 10, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  147133. 10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  147134. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  147135. 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  147136. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  147137. 10,10,10,10,10, 9, 9, 9,10, 9,10,10,10,10,10,10,
  147138. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  147139. 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  147140. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  147141. 10,10,10,10, 9, 9, 9,10, 9,10, 9,10,10,10,10,10,
  147142. 10,10,10,10,10,10,10,10,10,
  147143. };
  147144. static float _vq_quantthresh__44u8_p8_1[] = {
  147145. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  147146. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  147147. 6.5, 7.5, 8.5, 9.5,
  147148. };
  147149. static long _vq_quantmap__44u8_p8_1[] = {
  147150. 19, 17, 15, 13, 11, 9, 7, 5,
  147151. 3, 1, 0, 2, 4, 6, 8, 10,
  147152. 12, 14, 16, 18, 20,
  147153. };
  147154. static encode_aux_threshmatch _vq_auxt__44u8_p8_1 = {
  147155. _vq_quantthresh__44u8_p8_1,
  147156. _vq_quantmap__44u8_p8_1,
  147157. 21,
  147158. 21
  147159. };
  147160. static static_codebook _44u8_p8_1 = {
  147161. 2, 441,
  147162. _vq_lengthlist__44u8_p8_1,
  147163. 1, -529268736, 1611661312, 5, 0,
  147164. _vq_quantlist__44u8_p8_1,
  147165. NULL,
  147166. &_vq_auxt__44u8_p8_1,
  147167. NULL,
  147168. 0
  147169. };
  147170. static long _vq_quantlist__44u8_p9_0[] = {
  147171. 4,
  147172. 3,
  147173. 5,
  147174. 2,
  147175. 6,
  147176. 1,
  147177. 7,
  147178. 0,
  147179. 8,
  147180. };
  147181. static long _vq_lengthlist__44u8_p9_0[] = {
  147182. 1, 3, 3, 9, 9, 9, 9, 9, 9, 4, 9, 9, 9, 9, 9, 9,
  147183. 9, 9, 5, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147184. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147185. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147186. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8,
  147187. 8,
  147188. };
  147189. static float _vq_quantthresh__44u8_p9_0[] = {
  147190. -3258.5, -2327.5, -1396.5, -465.5, 465.5, 1396.5, 2327.5, 3258.5,
  147191. };
  147192. static long _vq_quantmap__44u8_p9_0[] = {
  147193. 7, 5, 3, 1, 0, 2, 4, 6,
  147194. 8,
  147195. };
  147196. static encode_aux_threshmatch _vq_auxt__44u8_p9_0 = {
  147197. _vq_quantthresh__44u8_p9_0,
  147198. _vq_quantmap__44u8_p9_0,
  147199. 9,
  147200. 9
  147201. };
  147202. static static_codebook _44u8_p9_0 = {
  147203. 2, 81,
  147204. _vq_lengthlist__44u8_p9_0,
  147205. 1, -511895552, 1631393792, 4, 0,
  147206. _vq_quantlist__44u8_p9_0,
  147207. NULL,
  147208. &_vq_auxt__44u8_p9_0,
  147209. NULL,
  147210. 0
  147211. };
  147212. static long _vq_quantlist__44u8_p9_1[] = {
  147213. 9,
  147214. 8,
  147215. 10,
  147216. 7,
  147217. 11,
  147218. 6,
  147219. 12,
  147220. 5,
  147221. 13,
  147222. 4,
  147223. 14,
  147224. 3,
  147225. 15,
  147226. 2,
  147227. 16,
  147228. 1,
  147229. 17,
  147230. 0,
  147231. 18,
  147232. };
  147233. static long _vq_lengthlist__44u8_p9_1[] = {
  147234. 1, 4, 4, 7, 7, 8, 7, 8, 6, 9, 7,10, 8,11,10,11,
  147235. 11,11,11, 4, 7, 6, 9, 9,10, 9, 9, 9,10,10,11,10,
  147236. 11,10,11,11,13,11, 4, 7, 7, 9, 9, 9, 9, 9, 9,10,
  147237. 10,11,10,11,11,11,12,11,12, 7, 9, 8,11,11,11,11,
  147238. 10,10,11,11,12,12,12,12,12,12,14,13, 7, 8, 9,10,
  147239. 11,11,11,10,10,11,11,11,11,12,12,14,12,13,14, 8,
  147240. 9, 9,11,11,11,11,11,11,12,12,14,12,15,14,14,14,
  147241. 15,14, 8, 9, 9,11,11,11,11,12,11,12,12,13,13,13,
  147242. 13,13,13,14,14, 8, 9, 9,11,10,12,11,12,12,13,13,
  147243. 13,13,15,14,14,14,16,16, 8, 9, 9,10,11,11,12,12,
  147244. 12,13,13,13,14,14,14,15,16,15,15, 9,10,10,11,12,
  147245. 12,13,13,13,14,14,16,14,14,16,16,16,16,15, 9,10,
  147246. 10,11,11,12,13,13,14,15,14,16,14,15,16,16,16,16,
  147247. 15,10,11,11,12,13,13,14,15,15,15,15,15,16,15,16,
  147248. 15,16,15,15,10,11,11,13,13,14,13,13,15,14,15,15,
  147249. 16,15,15,15,16,15,16,10,12,12,14,14,14,14,14,16,
  147250. 16,15,15,15,16,16,16,16,16,16,11,12,12,14,14,14,
  147251. 14,15,15,16,15,16,15,16,15,16,16,16,16,12,12,13,
  147252. 14,14,15,16,16,16,16,16,16,15,16,16,16,16,16,16,
  147253. 12,13,13,14,14,14,14,15,16,15,16,16,16,16,16,16,
  147254. 16,16,16,12,13,14,14,14,16,15,16,15,16,16,16,16,
  147255. 16,16,16,16,16,16,12,14,13,14,15,15,15,16,15,16,
  147256. 16,15,16,16,16,16,16,16,16,
  147257. };
  147258. static float _vq_quantthresh__44u8_p9_1[] = {
  147259. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  147260. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  147261. 367.5, 416.5,
  147262. };
  147263. static long _vq_quantmap__44u8_p9_1[] = {
  147264. 17, 15, 13, 11, 9, 7, 5, 3,
  147265. 1, 0, 2, 4, 6, 8, 10, 12,
  147266. 14, 16, 18,
  147267. };
  147268. static encode_aux_threshmatch _vq_auxt__44u8_p9_1 = {
  147269. _vq_quantthresh__44u8_p9_1,
  147270. _vq_quantmap__44u8_p9_1,
  147271. 19,
  147272. 19
  147273. };
  147274. static static_codebook _44u8_p9_1 = {
  147275. 2, 361,
  147276. _vq_lengthlist__44u8_p9_1,
  147277. 1, -518287360, 1622704128, 5, 0,
  147278. _vq_quantlist__44u8_p9_1,
  147279. NULL,
  147280. &_vq_auxt__44u8_p9_1,
  147281. NULL,
  147282. 0
  147283. };
  147284. static long _vq_quantlist__44u8_p9_2[] = {
  147285. 24,
  147286. 23,
  147287. 25,
  147288. 22,
  147289. 26,
  147290. 21,
  147291. 27,
  147292. 20,
  147293. 28,
  147294. 19,
  147295. 29,
  147296. 18,
  147297. 30,
  147298. 17,
  147299. 31,
  147300. 16,
  147301. 32,
  147302. 15,
  147303. 33,
  147304. 14,
  147305. 34,
  147306. 13,
  147307. 35,
  147308. 12,
  147309. 36,
  147310. 11,
  147311. 37,
  147312. 10,
  147313. 38,
  147314. 9,
  147315. 39,
  147316. 8,
  147317. 40,
  147318. 7,
  147319. 41,
  147320. 6,
  147321. 42,
  147322. 5,
  147323. 43,
  147324. 4,
  147325. 44,
  147326. 3,
  147327. 45,
  147328. 2,
  147329. 46,
  147330. 1,
  147331. 47,
  147332. 0,
  147333. 48,
  147334. };
  147335. static long _vq_lengthlist__44u8_p9_2[] = {
  147336. 2, 3, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  147337. 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  147338. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  147339. 7,
  147340. };
  147341. static float _vq_quantthresh__44u8_p9_2[] = {
  147342. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  147343. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  147344. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  147345. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  147346. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  147347. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  147348. };
  147349. static long _vq_quantmap__44u8_p9_2[] = {
  147350. 47, 45, 43, 41, 39, 37, 35, 33,
  147351. 31, 29, 27, 25, 23, 21, 19, 17,
  147352. 15, 13, 11, 9, 7, 5, 3, 1,
  147353. 0, 2, 4, 6, 8, 10, 12, 14,
  147354. 16, 18, 20, 22, 24, 26, 28, 30,
  147355. 32, 34, 36, 38, 40, 42, 44, 46,
  147356. 48,
  147357. };
  147358. static encode_aux_threshmatch _vq_auxt__44u8_p9_2 = {
  147359. _vq_quantthresh__44u8_p9_2,
  147360. _vq_quantmap__44u8_p9_2,
  147361. 49,
  147362. 49
  147363. };
  147364. static static_codebook _44u8_p9_2 = {
  147365. 1, 49,
  147366. _vq_lengthlist__44u8_p9_2,
  147367. 1, -526909440, 1611661312, 6, 0,
  147368. _vq_quantlist__44u8_p9_2,
  147369. NULL,
  147370. &_vq_auxt__44u8_p9_2,
  147371. NULL,
  147372. 0
  147373. };
  147374. static long _huff_lengthlist__44u9__long[] = {
  147375. 3, 9,13,13,14,15,14,14,15,15, 5, 5, 9,10,12,12,
  147376. 13,14,16,15,10, 6, 6, 6, 8,11,12,13,16,15,11, 7,
  147377. 5, 3, 5, 8,10,12,15,15,10,10, 7, 4, 3, 5, 8,10,
  147378. 12,12,12,12, 9, 7, 5, 4, 6, 8,10,13,13,12,11, 9,
  147379. 7, 5, 5, 6, 9,12,14,12,12,10, 8, 6, 6, 6, 7,11,
  147380. 13,12,14,13,10, 8, 7, 7, 7,10,11,11,12,13,12,11,
  147381. 10, 8, 8, 9,
  147382. };
  147383. static static_codebook _huff_book__44u9__long = {
  147384. 2, 100,
  147385. _huff_lengthlist__44u9__long,
  147386. 0, 0, 0, 0, 0,
  147387. NULL,
  147388. NULL,
  147389. NULL,
  147390. NULL,
  147391. 0
  147392. };
  147393. static long _huff_lengthlist__44u9__short[] = {
  147394. 9,16,18,18,17,17,17,17,17,17, 5, 8,11,12,11,12,
  147395. 17,17,16,16, 6, 6, 8, 8, 9,10,14,15,16,16, 6, 7,
  147396. 7, 4, 6, 9,13,16,16,16, 6, 6, 7, 4, 5, 8,11,15,
  147397. 17,16, 7, 6, 7, 6, 6, 8, 9,10,14,16,11, 8, 8, 7,
  147398. 6, 6, 3, 4,10,15,14,12,12,10, 5, 6, 3, 3, 8,13,
  147399. 15,17,15,11, 6, 8, 6, 6, 9,14,17,15,15,12, 8,10,
  147400. 9, 9,12,15,
  147401. };
  147402. static static_codebook _huff_book__44u9__short = {
  147403. 2, 100,
  147404. _huff_lengthlist__44u9__short,
  147405. 0, 0, 0, 0, 0,
  147406. NULL,
  147407. NULL,
  147408. NULL,
  147409. NULL,
  147410. 0
  147411. };
  147412. static long _vq_quantlist__44u9_p1_0[] = {
  147413. 1,
  147414. 0,
  147415. 2,
  147416. };
  147417. static long _vq_lengthlist__44u9_p1_0[] = {
  147418. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 7, 9, 9, 7,
  147419. 9, 9, 5, 7, 7, 7, 9, 9, 7, 9, 9, 5, 7, 7, 7, 9,
  147420. 9, 7, 9, 9, 8, 9, 9, 9,10,11, 9,11,11, 7, 9, 9,
  147421. 9,11,10, 9,11,11, 5, 7, 7, 7, 9, 9, 8, 9,10, 7,
  147422. 9, 9, 9,11,11, 9,10,11, 7, 9,10, 9,11,11, 9,11,
  147423. 10,
  147424. };
  147425. static float _vq_quantthresh__44u9_p1_0[] = {
  147426. -0.5, 0.5,
  147427. };
  147428. static long _vq_quantmap__44u9_p1_0[] = {
  147429. 1, 0, 2,
  147430. };
  147431. static encode_aux_threshmatch _vq_auxt__44u9_p1_0 = {
  147432. _vq_quantthresh__44u9_p1_0,
  147433. _vq_quantmap__44u9_p1_0,
  147434. 3,
  147435. 3
  147436. };
  147437. static static_codebook _44u9_p1_0 = {
  147438. 4, 81,
  147439. _vq_lengthlist__44u9_p1_0,
  147440. 1, -535822336, 1611661312, 2, 0,
  147441. _vq_quantlist__44u9_p1_0,
  147442. NULL,
  147443. &_vq_auxt__44u9_p1_0,
  147444. NULL,
  147445. 0
  147446. };
  147447. static long _vq_quantlist__44u9_p2_0[] = {
  147448. 2,
  147449. 1,
  147450. 3,
  147451. 0,
  147452. 4,
  147453. };
  147454. static long _vq_lengthlist__44u9_p2_0[] = {
  147455. 3, 5, 5, 8, 8, 5, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  147456. 9, 9,11,10, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  147457. 8,10,10, 7, 8, 8, 9,10, 9,10,10,11,11, 9, 9,10,
  147458. 11,11, 6, 7, 7, 9, 9, 7, 8, 8,10, 9, 7, 8, 8,10,
  147459. 10, 9,10, 9,11,11, 9,10,10,11,11, 8, 9, 9,11,11,
  147460. 9,10,10,12,11, 9,10,10,11,12,11,11,11,13,13,11,
  147461. 11,11,12,13, 8, 9, 9,11,11, 9,10,10,11,11, 9,10,
  147462. 10,12,11,11,12,11,13,12,11,11,12,13,13, 6, 7, 7,
  147463. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  147464. 11, 9,10,10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  147465. 8, 9, 9,10,10,10,11,11,12,12,10,10,11,12,12, 7,
  147466. 8, 8,10,10, 8, 9, 8,10,10, 8, 9, 9,10,10,10,11,
  147467. 10,12,11,10,10,11,12,12, 9,10,10,11,12,10,11,11,
  147468. 12,12,10,11,10,12,12,12,12,12,13,13,11,12,12,13,
  147469. 13, 9,10,10,11,11, 9,10,10,12,12,10,11,11,12,13,
  147470. 11,12,11,13,12,12,12,12,13,14, 6, 7, 7, 9, 9, 7,
  147471. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,11,11, 9,10,
  147472. 10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,10, 8, 8, 9,
  147473. 10,10,10,11,10,12,12,10,10,11,11,12, 7, 8, 8,10,
  147474. 10, 8, 9, 9,10,10, 8, 9, 9,10,10,10,11,10,12,12,
  147475. 10,11,10,12,12, 9,10,10,12,11,10,11,11,12,12, 9,
  147476. 10,10,12,12,12,12,12,13,13,11,11,12,12,14, 9,10,
  147477. 10,11,12,10,11,11,12,12,10,11,11,12,12,11,12,12,
  147478. 14,14,12,12,12,13,13, 8, 9, 9,11,11, 9,10,10,12,
  147479. 11, 9,10,10,12,12,11,12,11,13,13,11,11,12,13,13,
  147480. 9,10,10,12,12,10,11,11,12,12,10,11,11,12,12,12,
  147481. 12,12,14,14,12,12,12,13,13, 9,10,10,12,11,10,11,
  147482. 10,12,12,10,11,11,12,12,11,12,12,14,13,12,12,12,
  147483. 13,14,11,12,11,13,13,11,12,12,13,13,12,12,12,14,
  147484. 14,13,13,13,13,15,13,13,14,15,15,11,11,11,13,13,
  147485. 11,12,11,13,13,11,12,12,13,13,12,13,12,15,13,13,
  147486. 13,14,14,15, 8, 9, 9,11,11, 9,10,10,11,12, 9,10,
  147487. 10,11,12,11,12,11,13,13,11,12,12,13,13, 9,10,10,
  147488. 11,12,10,11,10,12,12,10,10,11,12,13,12,12,12,14,
  147489. 13,11,12,12,13,14, 9,10,10,12,12,10,11,11,12,12,
  147490. 10,11,11,12,12,12,12,12,14,13,12,12,12,14,13,11,
  147491. 11,11,13,13,11,12,12,14,13,11,11,12,13,13,13,13,
  147492. 13,15,14,12,12,13,13,15,11,12,12,13,13,12,12,12,
  147493. 13,14,11,12,12,13,13,13,13,14,14,15,13,13,13,14,
  147494. 14,
  147495. };
  147496. static float _vq_quantthresh__44u9_p2_0[] = {
  147497. -1.5, -0.5, 0.5, 1.5,
  147498. };
  147499. static long _vq_quantmap__44u9_p2_0[] = {
  147500. 3, 1, 0, 2, 4,
  147501. };
  147502. static encode_aux_threshmatch _vq_auxt__44u9_p2_0 = {
  147503. _vq_quantthresh__44u9_p2_0,
  147504. _vq_quantmap__44u9_p2_0,
  147505. 5,
  147506. 5
  147507. };
  147508. static static_codebook _44u9_p2_0 = {
  147509. 4, 625,
  147510. _vq_lengthlist__44u9_p2_0,
  147511. 1, -533725184, 1611661312, 3, 0,
  147512. _vq_quantlist__44u9_p2_0,
  147513. NULL,
  147514. &_vq_auxt__44u9_p2_0,
  147515. NULL,
  147516. 0
  147517. };
  147518. static long _vq_quantlist__44u9_p3_0[] = {
  147519. 4,
  147520. 3,
  147521. 5,
  147522. 2,
  147523. 6,
  147524. 1,
  147525. 7,
  147526. 0,
  147527. 8,
  147528. };
  147529. static long _vq_lengthlist__44u9_p3_0[] = {
  147530. 3, 4, 4, 5, 5, 7, 7, 8, 8, 4, 5, 5, 6, 6, 7, 7,
  147531. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  147532. 8, 8, 9, 9, 5, 6, 6, 7, 7, 8, 8, 9, 9, 7, 7, 7,
  147533. 8, 8, 9, 9,10,10, 7, 7, 7, 8, 8, 9, 9,10,10, 8,
  147534. 9, 9,10, 9,10,10,11,11, 8, 9, 9, 9,10,10,10,11,
  147535. 11,
  147536. };
  147537. static float _vq_quantthresh__44u9_p3_0[] = {
  147538. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  147539. };
  147540. static long _vq_quantmap__44u9_p3_0[] = {
  147541. 7, 5, 3, 1, 0, 2, 4, 6,
  147542. 8,
  147543. };
  147544. static encode_aux_threshmatch _vq_auxt__44u9_p3_0 = {
  147545. _vq_quantthresh__44u9_p3_0,
  147546. _vq_quantmap__44u9_p3_0,
  147547. 9,
  147548. 9
  147549. };
  147550. static static_codebook _44u9_p3_0 = {
  147551. 2, 81,
  147552. _vq_lengthlist__44u9_p3_0,
  147553. 1, -531628032, 1611661312, 4, 0,
  147554. _vq_quantlist__44u9_p3_0,
  147555. NULL,
  147556. &_vq_auxt__44u9_p3_0,
  147557. NULL,
  147558. 0
  147559. };
  147560. static long _vq_quantlist__44u9_p4_0[] = {
  147561. 8,
  147562. 7,
  147563. 9,
  147564. 6,
  147565. 10,
  147566. 5,
  147567. 11,
  147568. 4,
  147569. 12,
  147570. 3,
  147571. 13,
  147572. 2,
  147573. 14,
  147574. 1,
  147575. 15,
  147576. 0,
  147577. 16,
  147578. };
  147579. static long _vq_lengthlist__44u9_p4_0[] = {
  147580. 4, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  147581. 11, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  147582. 11,11, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  147583. 10,11,11, 6, 6, 6, 7, 6, 7, 7, 8, 8, 9, 9,10,10,
  147584. 11,11,12,11, 6, 6, 6, 6, 7, 7, 7, 8, 8, 9, 9,10,
  147585. 10,11,11,11,12, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,
  147586. 10,10,11,11,12,12, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  147587. 9,10,10,11,11,12,12, 8, 8, 8, 8, 8, 9, 8,10, 9,
  147588. 10,10,11,10,12,11,13,12, 8, 8, 8, 8, 8, 9, 9, 9,
  147589. 10,10,10,10,11,11,12,12,12, 8, 8, 8, 9, 9, 9, 9,
  147590. 10,10,11,10,12,11,12,12,13,12, 8, 8, 8, 9, 9, 9,
  147591. 9,10,10,10,11,11,11,12,12,12,13, 9, 9, 9,10,10,
  147592. 10,10,11,10,11,11,12,11,13,12,13,13, 9, 9,10,10,
  147593. 10,10,10,10,11,11,11,11,12,12,13,13,13,10,11,10,
  147594. 11,11,11,11,12,11,12,12,13,12,13,13,14,13,10,10,
  147595. 10,11,11,11,11,11,12,12,12,12,13,13,13,13,14,11,
  147596. 11,11,12,11,12,12,12,12,13,13,13,13,14,13,14,14,
  147597. 11,11,11,11,12,12,12,12,12,12,13,13,13,13,14,14,
  147598. 14,
  147599. };
  147600. static float _vq_quantthresh__44u9_p4_0[] = {
  147601. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  147602. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  147603. };
  147604. static long _vq_quantmap__44u9_p4_0[] = {
  147605. 15, 13, 11, 9, 7, 5, 3, 1,
  147606. 0, 2, 4, 6, 8, 10, 12, 14,
  147607. 16,
  147608. };
  147609. static encode_aux_threshmatch _vq_auxt__44u9_p4_0 = {
  147610. _vq_quantthresh__44u9_p4_0,
  147611. _vq_quantmap__44u9_p4_0,
  147612. 17,
  147613. 17
  147614. };
  147615. static static_codebook _44u9_p4_0 = {
  147616. 2, 289,
  147617. _vq_lengthlist__44u9_p4_0,
  147618. 1, -529530880, 1611661312, 5, 0,
  147619. _vq_quantlist__44u9_p4_0,
  147620. NULL,
  147621. &_vq_auxt__44u9_p4_0,
  147622. NULL,
  147623. 0
  147624. };
  147625. static long _vq_quantlist__44u9_p5_0[] = {
  147626. 1,
  147627. 0,
  147628. 2,
  147629. };
  147630. static long _vq_lengthlist__44u9_p5_0[] = {
  147631. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8, 9, 9, 7,
  147632. 9, 9, 5, 8, 8, 7, 9, 9, 8, 9, 9, 5, 8, 8, 8,10,
  147633. 10, 8,10,10, 7,10,10, 9,10,12, 9,11,11, 7,10,10,
  147634. 9,11,10, 9,11,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  147635. 10,10, 9,12,11, 9,10,11, 7,10,10, 9,11,11,10,12,
  147636. 10,
  147637. };
  147638. static float _vq_quantthresh__44u9_p5_0[] = {
  147639. -5.5, 5.5,
  147640. };
  147641. static long _vq_quantmap__44u9_p5_0[] = {
  147642. 1, 0, 2,
  147643. };
  147644. static encode_aux_threshmatch _vq_auxt__44u9_p5_0 = {
  147645. _vq_quantthresh__44u9_p5_0,
  147646. _vq_quantmap__44u9_p5_0,
  147647. 3,
  147648. 3
  147649. };
  147650. static static_codebook _44u9_p5_0 = {
  147651. 4, 81,
  147652. _vq_lengthlist__44u9_p5_0,
  147653. 1, -529137664, 1618345984, 2, 0,
  147654. _vq_quantlist__44u9_p5_0,
  147655. NULL,
  147656. &_vq_auxt__44u9_p5_0,
  147657. NULL,
  147658. 0
  147659. };
  147660. static long _vq_quantlist__44u9_p5_1[] = {
  147661. 5,
  147662. 4,
  147663. 6,
  147664. 3,
  147665. 7,
  147666. 2,
  147667. 8,
  147668. 1,
  147669. 9,
  147670. 0,
  147671. 10,
  147672. };
  147673. static long _vq_lengthlist__44u9_p5_1[] = {
  147674. 5, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 6, 6,
  147675. 7, 7, 7, 7, 8, 7, 5, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  147676. 7, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 6, 6, 6, 7,
  147677. 7, 7, 7, 7, 7, 8, 8, 7, 7, 7, 7, 7, 8, 7, 8, 8,
  147678. 8, 8, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  147679. 8, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 8, 8, 8, 8,
  147680. 8, 8, 8, 7, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  147681. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  147682. };
  147683. static float _vq_quantthresh__44u9_p5_1[] = {
  147684. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  147685. 3.5, 4.5,
  147686. };
  147687. static long _vq_quantmap__44u9_p5_1[] = {
  147688. 9, 7, 5, 3, 1, 0, 2, 4,
  147689. 6, 8, 10,
  147690. };
  147691. static encode_aux_threshmatch _vq_auxt__44u9_p5_1 = {
  147692. _vq_quantthresh__44u9_p5_1,
  147693. _vq_quantmap__44u9_p5_1,
  147694. 11,
  147695. 11
  147696. };
  147697. static static_codebook _44u9_p5_1 = {
  147698. 2, 121,
  147699. _vq_lengthlist__44u9_p5_1,
  147700. 1, -531365888, 1611661312, 4, 0,
  147701. _vq_quantlist__44u9_p5_1,
  147702. NULL,
  147703. &_vq_auxt__44u9_p5_1,
  147704. NULL,
  147705. 0
  147706. };
  147707. static long _vq_quantlist__44u9_p6_0[] = {
  147708. 6,
  147709. 5,
  147710. 7,
  147711. 4,
  147712. 8,
  147713. 3,
  147714. 9,
  147715. 2,
  147716. 10,
  147717. 1,
  147718. 11,
  147719. 0,
  147720. 12,
  147721. };
  147722. static long _vq_lengthlist__44u9_p6_0[] = {
  147723. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 5,
  147724. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 5, 6, 7, 7, 8,
  147725. 8, 8, 8, 9, 9,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  147726. 10,10,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,10,
  147727. 10, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,11, 7, 8,
  147728. 8, 8, 8, 9, 9, 9, 9,10,10,11,11, 8, 8, 8, 9, 9,
  147729. 9, 9, 9,10,10,10,11,11, 8, 8, 8, 9, 9, 9, 9,10,
  147730. 9,10,10,11,11, 9, 9, 9,10,10,10,10,10,11,11,11,
  147731. 11,12, 9, 9, 9,10,10,10,10,10,10,11,10,12,11,10,
  147732. 10,10,10,10,11,11,11,11,11,12,12,12,10,10,10,10,
  147733. 10,11,11,11,11,12,11,12,12,
  147734. };
  147735. static float _vq_quantthresh__44u9_p6_0[] = {
  147736. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  147737. 12.5, 17.5, 22.5, 27.5,
  147738. };
  147739. static long _vq_quantmap__44u9_p6_0[] = {
  147740. 11, 9, 7, 5, 3, 1, 0, 2,
  147741. 4, 6, 8, 10, 12,
  147742. };
  147743. static encode_aux_threshmatch _vq_auxt__44u9_p6_0 = {
  147744. _vq_quantthresh__44u9_p6_0,
  147745. _vq_quantmap__44u9_p6_0,
  147746. 13,
  147747. 13
  147748. };
  147749. static static_codebook _44u9_p6_0 = {
  147750. 2, 169,
  147751. _vq_lengthlist__44u9_p6_0,
  147752. 1, -526516224, 1616117760, 4, 0,
  147753. _vq_quantlist__44u9_p6_0,
  147754. NULL,
  147755. &_vq_auxt__44u9_p6_0,
  147756. NULL,
  147757. 0
  147758. };
  147759. static long _vq_quantlist__44u9_p6_1[] = {
  147760. 2,
  147761. 1,
  147762. 3,
  147763. 0,
  147764. 4,
  147765. };
  147766. static long _vq_lengthlist__44u9_p6_1[] = {
  147767. 4, 4, 4, 5, 5, 4, 5, 4, 5, 5, 4, 4, 5, 5, 5, 5,
  147768. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  147769. };
  147770. static float _vq_quantthresh__44u9_p6_1[] = {
  147771. -1.5, -0.5, 0.5, 1.5,
  147772. };
  147773. static long _vq_quantmap__44u9_p6_1[] = {
  147774. 3, 1, 0, 2, 4,
  147775. };
  147776. static encode_aux_threshmatch _vq_auxt__44u9_p6_1 = {
  147777. _vq_quantthresh__44u9_p6_1,
  147778. _vq_quantmap__44u9_p6_1,
  147779. 5,
  147780. 5
  147781. };
  147782. static static_codebook _44u9_p6_1 = {
  147783. 2, 25,
  147784. _vq_lengthlist__44u9_p6_1,
  147785. 1, -533725184, 1611661312, 3, 0,
  147786. _vq_quantlist__44u9_p6_1,
  147787. NULL,
  147788. &_vq_auxt__44u9_p6_1,
  147789. NULL,
  147790. 0
  147791. };
  147792. static long _vq_quantlist__44u9_p7_0[] = {
  147793. 6,
  147794. 5,
  147795. 7,
  147796. 4,
  147797. 8,
  147798. 3,
  147799. 9,
  147800. 2,
  147801. 10,
  147802. 1,
  147803. 11,
  147804. 0,
  147805. 12,
  147806. };
  147807. static long _vq_lengthlist__44u9_p7_0[] = {
  147808. 1, 4, 5, 6, 6, 7, 7, 8, 9,10,10,11,11, 5, 6, 6,
  147809. 7, 7, 8, 8, 9, 9,10,10,11,11, 5, 6, 6, 7, 7, 8,
  147810. 8, 9, 9,10,10,11,11, 6, 7, 7, 8, 8, 9, 9,10,10,
  147811. 11,11,12,12, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,12,
  147812. 12, 8, 8, 8, 9, 9,10,10,11,11,12,12,13,13, 8, 8,
  147813. 8, 9, 9,10,10,11,11,12,12,13,13, 9, 9, 9,10,10,
  147814. 11,11,12,12,13,13,13,13, 9, 9, 9,10,10,11,11,12,
  147815. 12,13,13,14,14,10,10,10,11,11,12,12,13,13,14,13,
  147816. 15,14,10,10,10,11,11,12,12,13,13,14,14,14,14,11,
  147817. 11,12,12,12,13,13,14,14,14,14,15,15,11,11,12,12,
  147818. 12,13,13,14,14,14,15,15,15,
  147819. };
  147820. static float _vq_quantthresh__44u9_p7_0[] = {
  147821. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  147822. 27.5, 38.5, 49.5, 60.5,
  147823. };
  147824. static long _vq_quantmap__44u9_p7_0[] = {
  147825. 11, 9, 7, 5, 3, 1, 0, 2,
  147826. 4, 6, 8, 10, 12,
  147827. };
  147828. static encode_aux_threshmatch _vq_auxt__44u9_p7_0 = {
  147829. _vq_quantthresh__44u9_p7_0,
  147830. _vq_quantmap__44u9_p7_0,
  147831. 13,
  147832. 13
  147833. };
  147834. static static_codebook _44u9_p7_0 = {
  147835. 2, 169,
  147836. _vq_lengthlist__44u9_p7_0,
  147837. 1, -523206656, 1618345984, 4, 0,
  147838. _vq_quantlist__44u9_p7_0,
  147839. NULL,
  147840. &_vq_auxt__44u9_p7_0,
  147841. NULL,
  147842. 0
  147843. };
  147844. static long _vq_quantlist__44u9_p7_1[] = {
  147845. 5,
  147846. 4,
  147847. 6,
  147848. 3,
  147849. 7,
  147850. 2,
  147851. 8,
  147852. 1,
  147853. 9,
  147854. 0,
  147855. 10,
  147856. };
  147857. static long _vq_lengthlist__44u9_p7_1[] = {
  147858. 5, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 7, 7,
  147859. 7, 7, 7, 7, 7, 7, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7,
  147860. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 6, 7, 7, 7,
  147861. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  147862. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  147863. 7, 7, 7, 7, 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  147864. 7, 8, 8, 7, 7, 7, 7, 7, 7, 7, 8, 7, 8, 8, 7, 7,
  147865. 7, 7, 7, 7, 7, 8, 8, 8, 8,
  147866. };
  147867. static float _vq_quantthresh__44u9_p7_1[] = {
  147868. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  147869. 3.5, 4.5,
  147870. };
  147871. static long _vq_quantmap__44u9_p7_1[] = {
  147872. 9, 7, 5, 3, 1, 0, 2, 4,
  147873. 6, 8, 10,
  147874. };
  147875. static encode_aux_threshmatch _vq_auxt__44u9_p7_1 = {
  147876. _vq_quantthresh__44u9_p7_1,
  147877. _vq_quantmap__44u9_p7_1,
  147878. 11,
  147879. 11
  147880. };
  147881. static static_codebook _44u9_p7_1 = {
  147882. 2, 121,
  147883. _vq_lengthlist__44u9_p7_1,
  147884. 1, -531365888, 1611661312, 4, 0,
  147885. _vq_quantlist__44u9_p7_1,
  147886. NULL,
  147887. &_vq_auxt__44u9_p7_1,
  147888. NULL,
  147889. 0
  147890. };
  147891. static long _vq_quantlist__44u9_p8_0[] = {
  147892. 7,
  147893. 6,
  147894. 8,
  147895. 5,
  147896. 9,
  147897. 4,
  147898. 10,
  147899. 3,
  147900. 11,
  147901. 2,
  147902. 12,
  147903. 1,
  147904. 13,
  147905. 0,
  147906. 14,
  147907. };
  147908. static long _vq_lengthlist__44u9_p8_0[] = {
  147909. 1, 4, 4, 7, 7, 8, 8, 8, 8, 9, 9,10, 9,11,10, 4,
  147910. 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,10,12,10, 4, 6,
  147911. 6, 8, 8, 9,10, 9, 9,10,10,11,11,12,12, 7, 8, 8,
  147912. 10,10,11,11,10,10,11,11,12,12,13,12, 7, 8, 8,10,
  147913. 10,11,11,10,10,11,11,12,12,12,13, 8,10, 9,11,11,
  147914. 12,12,11,11,12,12,13,13,14,13, 8, 9, 9,11,11,12,
  147915. 12,11,12,12,12,13,13,14,13, 8, 9, 9,10,10,12,11,
  147916. 13,12,13,13,14,13,15,14, 8, 9, 9,10,10,11,12,12,
  147917. 12,13,13,13,14,14,14, 9,10,10,12,11,13,12,13,13,
  147918. 14,13,14,14,14,15, 9,10,10,11,12,12,12,13,13,14,
  147919. 14,14,15,15,15,10,11,11,12,12,13,13,14,14,14,14,
  147920. 15,14,16,15,10,11,11,12,12,13,13,13,14,14,14,14,
  147921. 14,15,16,11,12,12,13,13,14,13,14,14,15,14,15,16,
  147922. 16,16,11,12,12,13,13,14,13,14,14,15,15,15,16,15,
  147923. 15,
  147924. };
  147925. static float _vq_quantthresh__44u9_p8_0[] = {
  147926. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  147927. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  147928. };
  147929. static long _vq_quantmap__44u9_p8_0[] = {
  147930. 13, 11, 9, 7, 5, 3, 1, 0,
  147931. 2, 4, 6, 8, 10, 12, 14,
  147932. };
  147933. static encode_aux_threshmatch _vq_auxt__44u9_p8_0 = {
  147934. _vq_quantthresh__44u9_p8_0,
  147935. _vq_quantmap__44u9_p8_0,
  147936. 15,
  147937. 15
  147938. };
  147939. static static_codebook _44u9_p8_0 = {
  147940. 2, 225,
  147941. _vq_lengthlist__44u9_p8_0,
  147942. 1, -520986624, 1620377600, 4, 0,
  147943. _vq_quantlist__44u9_p8_0,
  147944. NULL,
  147945. &_vq_auxt__44u9_p8_0,
  147946. NULL,
  147947. 0
  147948. };
  147949. static long _vq_quantlist__44u9_p8_1[] = {
  147950. 10,
  147951. 9,
  147952. 11,
  147953. 8,
  147954. 12,
  147955. 7,
  147956. 13,
  147957. 6,
  147958. 14,
  147959. 5,
  147960. 15,
  147961. 4,
  147962. 16,
  147963. 3,
  147964. 17,
  147965. 2,
  147966. 18,
  147967. 1,
  147968. 19,
  147969. 0,
  147970. 20,
  147971. };
  147972. static long _vq_lengthlist__44u9_p8_1[] = {
  147973. 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  147974. 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  147975. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8,
  147976. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 7,
  147977. 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  147978. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  147979. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9,
  147980. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10, 8, 8,
  147981. 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147982. 9,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147983. 10, 9,10, 9,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9,
  147984. 9, 9, 9, 9, 9,10,10, 9,10,10,10,10,10, 9, 9, 9,
  147985. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  147986. 10,10, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  147987. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147988. 9, 9,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  147989. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  147990. 10, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  147991. 10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  147992. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  147993. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  147994. 9, 9, 9, 9,10, 9, 9,10,10,10,10,10,10,10,10,10,
  147995. 10,10,10,10,10, 9, 9, 9,10, 9,10, 9,10,10,10,10,
  147996. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10, 9,10,
  147997. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  147998. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  147999. 10,10,10,10, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  148000. 10,10,10,10,10,10,10,10,10,
  148001. };
  148002. static float _vq_quantthresh__44u9_p8_1[] = {
  148003. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  148004. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  148005. 6.5, 7.5, 8.5, 9.5,
  148006. };
  148007. static long _vq_quantmap__44u9_p8_1[] = {
  148008. 19, 17, 15, 13, 11, 9, 7, 5,
  148009. 3, 1, 0, 2, 4, 6, 8, 10,
  148010. 12, 14, 16, 18, 20,
  148011. };
  148012. static encode_aux_threshmatch _vq_auxt__44u9_p8_1 = {
  148013. _vq_quantthresh__44u9_p8_1,
  148014. _vq_quantmap__44u9_p8_1,
  148015. 21,
  148016. 21
  148017. };
  148018. static static_codebook _44u9_p8_1 = {
  148019. 2, 441,
  148020. _vq_lengthlist__44u9_p8_1,
  148021. 1, -529268736, 1611661312, 5, 0,
  148022. _vq_quantlist__44u9_p8_1,
  148023. NULL,
  148024. &_vq_auxt__44u9_p8_1,
  148025. NULL,
  148026. 0
  148027. };
  148028. static long _vq_quantlist__44u9_p9_0[] = {
  148029. 7,
  148030. 6,
  148031. 8,
  148032. 5,
  148033. 9,
  148034. 4,
  148035. 10,
  148036. 3,
  148037. 11,
  148038. 2,
  148039. 12,
  148040. 1,
  148041. 13,
  148042. 0,
  148043. 14,
  148044. };
  148045. static long _vq_lengthlist__44u9_p9_0[] = {
  148046. 1, 3, 3,11,11,11,11,11,11,11,11,11,11,11,11, 4,
  148047. 10,11,11,11,11,11,11,11,11,11,11,11,11,11, 4,10,
  148048. 10,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148049. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148050. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148051. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148052. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148053. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148054. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148055. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148056. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148057. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148058. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  148059. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  148060. 10,
  148061. };
  148062. static float _vq_quantthresh__44u9_p9_0[] = {
  148063. -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5, 465.5,
  148064. 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5,
  148065. };
  148066. static long _vq_quantmap__44u9_p9_0[] = {
  148067. 13, 11, 9, 7, 5, 3, 1, 0,
  148068. 2, 4, 6, 8, 10, 12, 14,
  148069. };
  148070. static encode_aux_threshmatch _vq_auxt__44u9_p9_0 = {
  148071. _vq_quantthresh__44u9_p9_0,
  148072. _vq_quantmap__44u9_p9_0,
  148073. 15,
  148074. 15
  148075. };
  148076. static static_codebook _44u9_p9_0 = {
  148077. 2, 225,
  148078. _vq_lengthlist__44u9_p9_0,
  148079. 1, -510036736, 1631393792, 4, 0,
  148080. _vq_quantlist__44u9_p9_0,
  148081. NULL,
  148082. &_vq_auxt__44u9_p9_0,
  148083. NULL,
  148084. 0
  148085. };
  148086. static long _vq_quantlist__44u9_p9_1[] = {
  148087. 9,
  148088. 8,
  148089. 10,
  148090. 7,
  148091. 11,
  148092. 6,
  148093. 12,
  148094. 5,
  148095. 13,
  148096. 4,
  148097. 14,
  148098. 3,
  148099. 15,
  148100. 2,
  148101. 16,
  148102. 1,
  148103. 17,
  148104. 0,
  148105. 18,
  148106. };
  148107. static long _vq_lengthlist__44u9_p9_1[] = {
  148108. 1, 4, 4, 7, 7, 8, 7, 8, 7, 9, 8,10, 9,10,10,11,
  148109. 11,12,12, 4, 7, 6, 9, 9,10, 9, 9, 8,10,10,11,10,
  148110. 12,10,13,12,13,12, 4, 6, 6, 9, 9, 9, 9, 9, 9,10,
  148111. 10,11,11,11,12,12,12,12,12, 7, 9, 8,11,10,10,10,
  148112. 11,10,11,11,12,12,13,12,13,13,13,13, 7, 8, 9,10,
  148113. 10,11,11,10,10,11,11,11,12,13,13,13,13,14,14, 8,
  148114. 9, 9,11,11,12,11,12,12,13,12,12,13,13,14,15,14,
  148115. 14,14, 8, 9, 9,10,11,11,11,12,12,13,12,13,13,14,
  148116. 14,14,15,14,16, 8, 9, 9,11,10,12,12,12,12,15,13,
  148117. 13,13,17,14,15,15,15,14, 8, 9, 9,10,11,11,12,13,
  148118. 12,13,13,13,14,15,14,14,14,16,15, 9,11,10,12,12,
  148119. 13,13,13,13,14,14,16,15,14,14,14,15,15,17, 9,10,
  148120. 10,11,11,13,13,13,14,14,13,15,14,15,14,15,16,15,
  148121. 16,10,11,11,12,12,13,14,15,14,15,14,14,15,17,16,
  148122. 15,15,17,17,10,12,11,13,12,14,14,13,14,15,15,15,
  148123. 15,16,17,17,15,17,16,11,12,12,14,13,15,14,15,16,
  148124. 17,15,17,15,17,15,15,16,17,15,11,11,12,14,14,14,
  148125. 14,14,15,15,16,15,17,17,17,16,17,16,15,12,12,13,
  148126. 14,14,14,15,14,15,15,16,16,17,16,17,15,17,17,16,
  148127. 12,14,12,14,14,15,15,15,14,14,16,16,16,15,16,16,
  148128. 15,17,15,12,13,13,14,15,14,15,17,15,17,16,17,17,
  148129. 17,16,17,16,17,17,12,13,13,14,16,15,15,15,16,15,
  148130. 17,17,15,17,15,17,16,16,17,
  148131. };
  148132. static float _vq_quantthresh__44u9_p9_1[] = {
  148133. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  148134. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  148135. 367.5, 416.5,
  148136. };
  148137. static long _vq_quantmap__44u9_p9_1[] = {
  148138. 17, 15, 13, 11, 9, 7, 5, 3,
  148139. 1, 0, 2, 4, 6, 8, 10, 12,
  148140. 14, 16, 18,
  148141. };
  148142. static encode_aux_threshmatch _vq_auxt__44u9_p9_1 = {
  148143. _vq_quantthresh__44u9_p9_1,
  148144. _vq_quantmap__44u9_p9_1,
  148145. 19,
  148146. 19
  148147. };
  148148. static static_codebook _44u9_p9_1 = {
  148149. 2, 361,
  148150. _vq_lengthlist__44u9_p9_1,
  148151. 1, -518287360, 1622704128, 5, 0,
  148152. _vq_quantlist__44u9_p9_1,
  148153. NULL,
  148154. &_vq_auxt__44u9_p9_1,
  148155. NULL,
  148156. 0
  148157. };
  148158. static long _vq_quantlist__44u9_p9_2[] = {
  148159. 24,
  148160. 23,
  148161. 25,
  148162. 22,
  148163. 26,
  148164. 21,
  148165. 27,
  148166. 20,
  148167. 28,
  148168. 19,
  148169. 29,
  148170. 18,
  148171. 30,
  148172. 17,
  148173. 31,
  148174. 16,
  148175. 32,
  148176. 15,
  148177. 33,
  148178. 14,
  148179. 34,
  148180. 13,
  148181. 35,
  148182. 12,
  148183. 36,
  148184. 11,
  148185. 37,
  148186. 10,
  148187. 38,
  148188. 9,
  148189. 39,
  148190. 8,
  148191. 40,
  148192. 7,
  148193. 41,
  148194. 6,
  148195. 42,
  148196. 5,
  148197. 43,
  148198. 4,
  148199. 44,
  148200. 3,
  148201. 45,
  148202. 2,
  148203. 46,
  148204. 1,
  148205. 47,
  148206. 0,
  148207. 48,
  148208. };
  148209. static long _vq_lengthlist__44u9_p9_2[] = {
  148210. 2, 4, 4, 5, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6,
  148211. 6, 6, 6, 7, 6, 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  148212. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  148213. 7,
  148214. };
  148215. static float _vq_quantthresh__44u9_p9_2[] = {
  148216. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  148217. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  148218. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  148219. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  148220. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  148221. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  148222. };
  148223. static long _vq_quantmap__44u9_p9_2[] = {
  148224. 47, 45, 43, 41, 39, 37, 35, 33,
  148225. 31, 29, 27, 25, 23, 21, 19, 17,
  148226. 15, 13, 11, 9, 7, 5, 3, 1,
  148227. 0, 2, 4, 6, 8, 10, 12, 14,
  148228. 16, 18, 20, 22, 24, 26, 28, 30,
  148229. 32, 34, 36, 38, 40, 42, 44, 46,
  148230. 48,
  148231. };
  148232. static encode_aux_threshmatch _vq_auxt__44u9_p9_2 = {
  148233. _vq_quantthresh__44u9_p9_2,
  148234. _vq_quantmap__44u9_p9_2,
  148235. 49,
  148236. 49
  148237. };
  148238. static static_codebook _44u9_p9_2 = {
  148239. 1, 49,
  148240. _vq_lengthlist__44u9_p9_2,
  148241. 1, -526909440, 1611661312, 6, 0,
  148242. _vq_quantlist__44u9_p9_2,
  148243. NULL,
  148244. &_vq_auxt__44u9_p9_2,
  148245. NULL,
  148246. 0
  148247. };
  148248. static long _huff_lengthlist__44un1__long[] = {
  148249. 5, 6,12, 9,14, 9, 9,19, 6, 1, 5, 5, 8, 7, 9,19,
  148250. 12, 4, 4, 7, 7, 9,11,18, 9, 5, 6, 6, 8, 7, 8,17,
  148251. 14, 8, 7, 8, 8,10,12,18, 9, 6, 8, 6, 8, 6, 8,18,
  148252. 9, 8,11, 8,11, 7, 5,15,16,18,18,18,17,15,11,18,
  148253. };
  148254. static static_codebook _huff_book__44un1__long = {
  148255. 2, 64,
  148256. _huff_lengthlist__44un1__long,
  148257. 0, 0, 0, 0, 0,
  148258. NULL,
  148259. NULL,
  148260. NULL,
  148261. NULL,
  148262. 0
  148263. };
  148264. static long _vq_quantlist__44un1__p1_0[] = {
  148265. 1,
  148266. 0,
  148267. 2,
  148268. };
  148269. static long _vq_lengthlist__44un1__p1_0[] = {
  148270. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  148271. 10,11, 5, 8, 8, 8,11,10, 8,11,10, 4, 9, 9, 8,11,
  148272. 11, 8,11,11, 8,12,11,10,12,14,11,13,13, 7,11,11,
  148273. 10,13,11,11,13,14, 4, 8, 9, 8,11,11, 8,11,12, 7,
  148274. 11,11,11,14,13,10,11,13, 8,11,12,11,13,13,10,14,
  148275. 12,
  148276. };
  148277. static float _vq_quantthresh__44un1__p1_0[] = {
  148278. -0.5, 0.5,
  148279. };
  148280. static long _vq_quantmap__44un1__p1_0[] = {
  148281. 1, 0, 2,
  148282. };
  148283. static encode_aux_threshmatch _vq_auxt__44un1__p1_0 = {
  148284. _vq_quantthresh__44un1__p1_0,
  148285. _vq_quantmap__44un1__p1_0,
  148286. 3,
  148287. 3
  148288. };
  148289. static static_codebook _44un1__p1_0 = {
  148290. 4, 81,
  148291. _vq_lengthlist__44un1__p1_0,
  148292. 1, -535822336, 1611661312, 2, 0,
  148293. _vq_quantlist__44un1__p1_0,
  148294. NULL,
  148295. &_vq_auxt__44un1__p1_0,
  148296. NULL,
  148297. 0
  148298. };
  148299. static long _vq_quantlist__44un1__p2_0[] = {
  148300. 1,
  148301. 0,
  148302. 2,
  148303. };
  148304. static long _vq_lengthlist__44un1__p2_0[] = {
  148305. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  148306. 7, 9, 5, 7, 7, 6, 8, 7, 7, 9, 8, 4, 7, 7, 7, 9,
  148307. 8, 7, 8, 8, 7, 9, 8, 8, 8,10, 9,10,10, 6, 8, 8,
  148308. 7,10, 8, 9,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 9, 6,
  148309. 8, 8, 9,10,10, 7, 8,10, 6, 8, 9, 9,10,10, 8,10,
  148310. 8,
  148311. };
  148312. static float _vq_quantthresh__44un1__p2_0[] = {
  148313. -0.5, 0.5,
  148314. };
  148315. static long _vq_quantmap__44un1__p2_0[] = {
  148316. 1, 0, 2,
  148317. };
  148318. static encode_aux_threshmatch _vq_auxt__44un1__p2_0 = {
  148319. _vq_quantthresh__44un1__p2_0,
  148320. _vq_quantmap__44un1__p2_0,
  148321. 3,
  148322. 3
  148323. };
  148324. static static_codebook _44un1__p2_0 = {
  148325. 4, 81,
  148326. _vq_lengthlist__44un1__p2_0,
  148327. 1, -535822336, 1611661312, 2, 0,
  148328. _vq_quantlist__44un1__p2_0,
  148329. NULL,
  148330. &_vq_auxt__44un1__p2_0,
  148331. NULL,
  148332. 0
  148333. };
  148334. static long _vq_quantlist__44un1__p3_0[] = {
  148335. 2,
  148336. 1,
  148337. 3,
  148338. 0,
  148339. 4,
  148340. };
  148341. static long _vq_lengthlist__44un1__p3_0[] = {
  148342. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  148343. 10, 9,12,12, 9, 9,10,11,12, 6, 8, 8,10,10, 8,10,
  148344. 10,11,11, 8, 9,10,11,11,10,11,11,13,13,10,11,11,
  148345. 12,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10,10,11,
  148346. 11,10,11,11,13,12,10,11,11,13,12, 9,11,11,15,13,
  148347. 10,12,11,15,13,10,11,11,15,14,12,14,13,16,15,12,
  148348. 13,13,17,16, 9,11,11,13,15,10,11,12,14,15,10,11,
  148349. 12,14,15,12,13,13,15,16,12,13,13,16,16, 5, 8, 8,
  148350. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  148351. 14,11,12,12,14,14, 8,11,10,13,12,10,11,12,12,13,
  148352. 10,12,12,13,13,12,12,13,13,15,11,12,13,15,14, 7,
  148353. 10,10,12,12, 9,12,11,13,12,10,12,12,13,14,12,13,
  148354. 12,15,13,11,13,12,14,15,10,12,12,16,14,11,12,12,
  148355. 16,15,11,13,12,17,16,13,13,15,15,17,13,15,15,20,
  148356. 17,10,12,12,14,16,11,12,12,15,15,11,13,13,15,18,
  148357. 13,14,13,15,15,13,15,14,16,16, 5, 8, 8,11,11, 8,
  148358. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  148359. 12,14,15, 7,10,10,13,12,10,12,12,14,13, 9,10,12,
  148360. 12,13,11,13,13,15,15,11,12,13,13,15, 8,10,10,12,
  148361. 13,10,12,12,13,13,10,12,11,13,13,11,13,12,15,15,
  148362. 12,13,12,15,13,10,12,12,16,14,11,12,12,16,15,10,
  148363. 12,12,16,14,14,15,14,18,16,13,13,14,15,16,10,12,
  148364. 12,14,16,11,13,13,16,16,11,13,12,14,16,13,15,15,
  148365. 18,18,13,15,13,16,14, 8,11,11,16,16,10,13,13,17,
  148366. 16,10,12,12,16,15,14,16,15,20,17,13,14,14,17,17,
  148367. 9,12,12,16,16,11,13,14,16,17,11,13,13,16,16,15,
  148368. 15,19,18, 0,14,15,15,18,18, 9,12,12,17,16,11,13,
  148369. 12,17,16,11,12,13,15,17,15,16,15, 0,19,14,15,14,
  148370. 19,18,12,14,14, 0,16,13,14,14,19,18,13,15,16,17,
  148371. 16,15,15,17,18, 0,14,16,16,19, 0,12,14,14,16,18,
  148372. 13,15,13,17,18,13,15,14,17,18,15,18,14,18,18,16,
  148373. 17,16, 0,17, 8,11,11,15,15,10,12,12,16,16,10,13,
  148374. 13,16,16,13,15,14,17,17,14,15,17,17,18, 9,12,12,
  148375. 16,15,11,13,13,16,16,11,12,13,17,17,14,14,15,17,
  148376. 17,14,15,16, 0,18, 9,12,12,16,17,11,13,13,16,17,
  148377. 11,14,13,18,17,14,16,14,17,17,15,17,17,18,18,12,
  148378. 14,14, 0,16,13,15,15,19, 0,12,13,15, 0, 0,14,17,
  148379. 16,19, 0,16,15,18,18, 0,12,14,14,17, 0,13,14,14,
  148380. 17, 0,13,15,14, 0,18,15,16,16, 0,18,15,18,15, 0,
  148381. 17,
  148382. };
  148383. static float _vq_quantthresh__44un1__p3_0[] = {
  148384. -1.5, -0.5, 0.5, 1.5,
  148385. };
  148386. static long _vq_quantmap__44un1__p3_0[] = {
  148387. 3, 1, 0, 2, 4,
  148388. };
  148389. static encode_aux_threshmatch _vq_auxt__44un1__p3_0 = {
  148390. _vq_quantthresh__44un1__p3_0,
  148391. _vq_quantmap__44un1__p3_0,
  148392. 5,
  148393. 5
  148394. };
  148395. static static_codebook _44un1__p3_0 = {
  148396. 4, 625,
  148397. _vq_lengthlist__44un1__p3_0,
  148398. 1, -533725184, 1611661312, 3, 0,
  148399. _vq_quantlist__44un1__p3_0,
  148400. NULL,
  148401. &_vq_auxt__44un1__p3_0,
  148402. NULL,
  148403. 0
  148404. };
  148405. static long _vq_quantlist__44un1__p4_0[] = {
  148406. 2,
  148407. 1,
  148408. 3,
  148409. 0,
  148410. 4,
  148411. };
  148412. static long _vq_lengthlist__44un1__p4_0[] = {
  148413. 3, 5, 5, 9, 9, 5, 6, 6,10, 9, 5, 6, 6, 9,10,10,
  148414. 10,10,12,11, 9,10,10,12,12, 5, 7, 7,10,10, 7, 7,
  148415. 8,10,11, 7, 7, 8,10,11,10,10,11,11,13,10,10,11,
  148416. 11,13, 6, 7, 7,10,10, 7, 8, 7,11,10, 7, 8, 7,10,
  148417. 10,10,11, 9,13,11,10,11,10,13,11,10,10,10,14,13,
  148418. 10,11,11,14,13,10,10,11,13,14,12,12,13,15,15,12,
  148419. 12,13,13,14,10,10,10,12,13,10,11,10,13,13,10,11,
  148420. 11,13,13,12,13,12,14,13,12,13,13,14,13, 5, 7, 7,
  148421. 10,10, 7, 8, 8,11,10, 7, 8, 8,10,10,11,11,11,13,
  148422. 13,10,11,11,12,12, 7, 8, 8,11,11, 7, 8, 9,10,12,
  148423. 8, 9, 9,11,11,11,10,12,11,14,11,11,12,13,13, 6,
  148424. 8, 8,10,11, 7, 9, 7,12,10, 8, 9,10,11,12,10,12,
  148425. 10,14,11,11,12,11,13,13,10,11,11,14,14,10,10,11,
  148426. 13,14,11,12,12,15,13,12,11,14,12,16,12,13,14,15,
  148427. 16,10,10,11,13,14,10,11,10,14,12,11,12,12,13,14,
  148428. 12,13,11,15,12,14,14,14,15,15, 5, 7, 7,10,10, 7,
  148429. 8, 8,10,10, 7, 8, 8,10,11,10,11,10,12,12,10,11,
  148430. 11,12,13, 6, 8, 8,11,11, 8, 9, 9,12,11, 7, 7, 9,
  148431. 10,12,11,11,11,12,13,11,10,12,11,15, 7, 8, 8,11,
  148432. 11, 8, 9, 9,11,11, 7, 9, 8,12,10,11,12,11,13,12,
  148433. 11,12,10,15,11,10,11,10,14,12,11,12,11,14,13,10,
  148434. 10,11,13,14,13,13,13,17,15,12,11,14,12,15,10,10,
  148435. 11,13,14,11,12,12,14,14,10,11,10,14,13,13,14,13,
  148436. 16,17,12,14,11,16,12, 9,10,10,14,13,10,11,10,14,
  148437. 14,10,11,11,13,13,13,14,14,16,15,12,13,13,14,14,
  148438. 9,11,10,14,13,10,10,12,13,14,11,12,11,14,13,13,
  148439. 14,14,14,15,13,14,14,15,15, 9,10,11,13,14,10,11,
  148440. 10,15,13,11,11,12,12,15,13,14,12,15,14,13,13,14,
  148441. 14,15,12,13,12,16,14,11,11,12,15,14,13,15,13,16,
  148442. 14,13,12,15,12,17,15,16,15,16,16,12,12,13,13,15,
  148443. 11,13,11,15,14,13,13,14,15,17,13,14,12, 0,13,14,
  148444. 15,14,15, 0, 9,10,10,13,13,10,11,11,13,13,10,11,
  148445. 11,13,13,12,13,12,14,14,13,14,14,15,17, 9,10,10,
  148446. 13,13,11,12,11,15,12,10,10,11,13,16,13,14,13,15,
  148447. 14,13,13,14,15,16,10,10,11,13,14,11,11,12,13,14,
  148448. 10,12,11,14,14,13,13,13,14,15,13,15,13,16,15,12,
  148449. 13,12,15,13,12,15,13,15,15,11,11,13,14,15,15,15,
  148450. 15,15,17,13,12,14,13,17,12,12,14,14,15,13,13,14,
  148451. 14,16,11,13,11,16,15,14,16,16,17, 0,14,13,11,16,
  148452. 12,
  148453. };
  148454. static float _vq_quantthresh__44un1__p4_0[] = {
  148455. -1.5, -0.5, 0.5, 1.5,
  148456. };
  148457. static long _vq_quantmap__44un1__p4_0[] = {
  148458. 3, 1, 0, 2, 4,
  148459. };
  148460. static encode_aux_threshmatch _vq_auxt__44un1__p4_0 = {
  148461. _vq_quantthresh__44un1__p4_0,
  148462. _vq_quantmap__44un1__p4_0,
  148463. 5,
  148464. 5
  148465. };
  148466. static static_codebook _44un1__p4_0 = {
  148467. 4, 625,
  148468. _vq_lengthlist__44un1__p4_0,
  148469. 1, -533725184, 1611661312, 3, 0,
  148470. _vq_quantlist__44un1__p4_0,
  148471. NULL,
  148472. &_vq_auxt__44un1__p4_0,
  148473. NULL,
  148474. 0
  148475. };
  148476. static long _vq_quantlist__44un1__p5_0[] = {
  148477. 4,
  148478. 3,
  148479. 5,
  148480. 2,
  148481. 6,
  148482. 1,
  148483. 7,
  148484. 0,
  148485. 8,
  148486. };
  148487. static long _vq_lengthlist__44un1__p5_0[] = {
  148488. 1, 4, 4, 7, 7, 8, 8, 9, 9, 4, 6, 5, 8, 7, 8, 8,
  148489. 10, 9, 4, 6, 6, 8, 8, 8, 8,10,10, 7, 8, 7, 9, 9,
  148490. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,11, 8, 8, 8,
  148491. 9, 9,10,10,11,11, 8, 8, 8, 9, 9,10,10,11,11, 9,
  148492. 10,10,11,10,11,11,12,12, 9,10,10,10,11,11,11,12,
  148493. 12,
  148494. };
  148495. static float _vq_quantthresh__44un1__p5_0[] = {
  148496. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  148497. };
  148498. static long _vq_quantmap__44un1__p5_0[] = {
  148499. 7, 5, 3, 1, 0, 2, 4, 6,
  148500. 8,
  148501. };
  148502. static encode_aux_threshmatch _vq_auxt__44un1__p5_0 = {
  148503. _vq_quantthresh__44un1__p5_0,
  148504. _vq_quantmap__44un1__p5_0,
  148505. 9,
  148506. 9
  148507. };
  148508. static static_codebook _44un1__p5_0 = {
  148509. 2, 81,
  148510. _vq_lengthlist__44un1__p5_0,
  148511. 1, -531628032, 1611661312, 4, 0,
  148512. _vq_quantlist__44un1__p5_0,
  148513. NULL,
  148514. &_vq_auxt__44un1__p5_0,
  148515. NULL,
  148516. 0
  148517. };
  148518. static long _vq_quantlist__44un1__p6_0[] = {
  148519. 6,
  148520. 5,
  148521. 7,
  148522. 4,
  148523. 8,
  148524. 3,
  148525. 9,
  148526. 2,
  148527. 10,
  148528. 1,
  148529. 11,
  148530. 0,
  148531. 12,
  148532. };
  148533. static long _vq_lengthlist__44un1__p6_0[] = {
  148534. 1, 4, 4, 6, 6, 8, 8,10,10,11,11,15,15, 4, 5, 5,
  148535. 8, 8, 9, 9,11,11,12,12,16,16, 4, 5, 6, 8, 8, 9,
  148536. 9,11,11,12,12,14,14, 7, 8, 8, 9, 9,10,10,11,12,
  148537. 13,13,16,17, 7, 8, 8, 9, 9,10,10,12,12,12,13,15,
  148538. 15, 9,10,10,10,10,11,11,12,12,13,13,15,16, 9, 9,
  148539. 9,10,10,11,11,13,12,13,13,17,17,10,11,11,11,12,
  148540. 12,12,13,13,14,15, 0,18,10,11,11,12,12,12,13,14,
  148541. 13,14,14,17,16,11,12,12,13,13,14,14,14,14,15,16,
  148542. 17,16,11,12,12,13,13,14,14,14,14,15,15,17,17,14,
  148543. 15,15,16,16,16,17,17,16, 0,17, 0,18,14,15,15,16,
  148544. 16, 0,15,18,18, 0,16, 0, 0,
  148545. };
  148546. static float _vq_quantthresh__44un1__p6_0[] = {
  148547. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  148548. 12.5, 17.5, 22.5, 27.5,
  148549. };
  148550. static long _vq_quantmap__44un1__p6_0[] = {
  148551. 11, 9, 7, 5, 3, 1, 0, 2,
  148552. 4, 6, 8, 10, 12,
  148553. };
  148554. static encode_aux_threshmatch _vq_auxt__44un1__p6_0 = {
  148555. _vq_quantthresh__44un1__p6_0,
  148556. _vq_quantmap__44un1__p6_0,
  148557. 13,
  148558. 13
  148559. };
  148560. static static_codebook _44un1__p6_0 = {
  148561. 2, 169,
  148562. _vq_lengthlist__44un1__p6_0,
  148563. 1, -526516224, 1616117760, 4, 0,
  148564. _vq_quantlist__44un1__p6_0,
  148565. NULL,
  148566. &_vq_auxt__44un1__p6_0,
  148567. NULL,
  148568. 0
  148569. };
  148570. static long _vq_quantlist__44un1__p6_1[] = {
  148571. 2,
  148572. 1,
  148573. 3,
  148574. 0,
  148575. 4,
  148576. };
  148577. static long _vq_lengthlist__44un1__p6_1[] = {
  148578. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 6, 5, 5,
  148579. 6, 5, 6, 6, 5, 6, 6, 6, 6,
  148580. };
  148581. static float _vq_quantthresh__44un1__p6_1[] = {
  148582. -1.5, -0.5, 0.5, 1.5,
  148583. };
  148584. static long _vq_quantmap__44un1__p6_1[] = {
  148585. 3, 1, 0, 2, 4,
  148586. };
  148587. static encode_aux_threshmatch _vq_auxt__44un1__p6_1 = {
  148588. _vq_quantthresh__44un1__p6_1,
  148589. _vq_quantmap__44un1__p6_1,
  148590. 5,
  148591. 5
  148592. };
  148593. static static_codebook _44un1__p6_1 = {
  148594. 2, 25,
  148595. _vq_lengthlist__44un1__p6_1,
  148596. 1, -533725184, 1611661312, 3, 0,
  148597. _vq_quantlist__44un1__p6_1,
  148598. NULL,
  148599. &_vq_auxt__44un1__p6_1,
  148600. NULL,
  148601. 0
  148602. };
  148603. static long _vq_quantlist__44un1__p7_0[] = {
  148604. 2,
  148605. 1,
  148606. 3,
  148607. 0,
  148608. 4,
  148609. };
  148610. static long _vq_lengthlist__44un1__p7_0[] = {
  148611. 1, 5, 3,11,11,11,11,11,11,11, 8,11,11,11,11,11,
  148612. 11,11,11,11,11,11,11,11,11,10,11,11,11,11,11,11,
  148613. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148614. 11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148615. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148616. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148617. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148618. 11,11,11,11,11,11,11,11,11,11,11,11,11, 8,11,11,
  148619. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148620. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148621. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,
  148622. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148623. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148624. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148625. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148626. 11,11,11,11,11,11,11,11,11,11, 7,11,11,11,11,11,
  148627. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148628. 11,11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,
  148629. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148630. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148631. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148632. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148633. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148634. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148635. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148636. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148637. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148638. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148639. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148640. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148641. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148642. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148643. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148644. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148645. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148646. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148647. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  148648. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  148649. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  148650. 10,
  148651. };
  148652. static float _vq_quantthresh__44un1__p7_0[] = {
  148653. -253.5, -84.5, 84.5, 253.5,
  148654. };
  148655. static long _vq_quantmap__44un1__p7_0[] = {
  148656. 3, 1, 0, 2, 4,
  148657. };
  148658. static encode_aux_threshmatch _vq_auxt__44un1__p7_0 = {
  148659. _vq_quantthresh__44un1__p7_0,
  148660. _vq_quantmap__44un1__p7_0,
  148661. 5,
  148662. 5
  148663. };
  148664. static static_codebook _44un1__p7_0 = {
  148665. 4, 625,
  148666. _vq_lengthlist__44un1__p7_0,
  148667. 1, -518709248, 1626677248, 3, 0,
  148668. _vq_quantlist__44un1__p7_0,
  148669. NULL,
  148670. &_vq_auxt__44un1__p7_0,
  148671. NULL,
  148672. 0
  148673. };
  148674. static long _vq_quantlist__44un1__p7_1[] = {
  148675. 6,
  148676. 5,
  148677. 7,
  148678. 4,
  148679. 8,
  148680. 3,
  148681. 9,
  148682. 2,
  148683. 10,
  148684. 1,
  148685. 11,
  148686. 0,
  148687. 12,
  148688. };
  148689. static long _vq_lengthlist__44un1__p7_1[] = {
  148690. 1, 4, 4, 6, 6, 6, 6, 9, 8, 9, 8, 8, 8, 5, 7, 7,
  148691. 7, 7, 8, 8, 8,10, 8,10, 8, 9, 5, 7, 7, 8, 7, 7,
  148692. 8,10,10,11,10,12,11, 7, 8, 8, 9, 9, 9,10,11,11,
  148693. 11,11,11,11, 7, 8, 8, 8, 9, 9, 9,10,10,10,11,11,
  148694. 12, 7, 8, 8, 9, 9,10,11,11,12,11,12,11,11, 7, 8,
  148695. 8, 9, 9,10,10,11,11,11,12,12,11, 8,10,10,10,10,
  148696. 11,11,14,11,12,12,12,13, 9,10,10,10,10,12,11,14,
  148697. 11,14,11,12,13,10,11,11,11,11,13,11,14,14,13,13,
  148698. 13,14,11,11,11,12,11,12,12,12,13,14,14,13,14,12,
  148699. 11,12,12,12,12,13,13,13,14,13,14,14,11,12,12,14,
  148700. 12,13,13,12,13,13,14,14,14,
  148701. };
  148702. static float _vq_quantthresh__44un1__p7_1[] = {
  148703. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  148704. 32.5, 45.5, 58.5, 71.5,
  148705. };
  148706. static long _vq_quantmap__44un1__p7_1[] = {
  148707. 11, 9, 7, 5, 3, 1, 0, 2,
  148708. 4, 6, 8, 10, 12,
  148709. };
  148710. static encode_aux_threshmatch _vq_auxt__44un1__p7_1 = {
  148711. _vq_quantthresh__44un1__p7_1,
  148712. _vq_quantmap__44un1__p7_1,
  148713. 13,
  148714. 13
  148715. };
  148716. static static_codebook _44un1__p7_1 = {
  148717. 2, 169,
  148718. _vq_lengthlist__44un1__p7_1,
  148719. 1, -523010048, 1618608128, 4, 0,
  148720. _vq_quantlist__44un1__p7_1,
  148721. NULL,
  148722. &_vq_auxt__44un1__p7_1,
  148723. NULL,
  148724. 0
  148725. };
  148726. static long _vq_quantlist__44un1__p7_2[] = {
  148727. 6,
  148728. 5,
  148729. 7,
  148730. 4,
  148731. 8,
  148732. 3,
  148733. 9,
  148734. 2,
  148735. 10,
  148736. 1,
  148737. 11,
  148738. 0,
  148739. 12,
  148740. };
  148741. static long _vq_lengthlist__44un1__p7_2[] = {
  148742. 3, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9, 9, 8, 4, 5, 5,
  148743. 6, 6, 8, 8, 9, 8, 9, 9, 9, 9, 4, 5, 5, 7, 6, 8,
  148744. 8, 8, 8, 9, 8, 9, 8, 6, 7, 7, 7, 8, 8, 8, 9, 9,
  148745. 9, 9, 9, 9, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  148746. 9, 7, 8, 8, 8, 8, 9, 8, 9, 9,10, 9, 9,10, 7, 8,
  148747. 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10, 8, 9, 9, 9, 9,
  148748. 9, 9, 9, 9,10,10, 9,10, 8, 9, 9, 9, 9, 9, 9, 9,
  148749. 9, 9, 9,10,10, 9, 9, 9,10, 9, 9,10, 9, 9,10,10,
  148750. 10,10, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10, 9,
  148751. 9, 9,10, 9, 9,10,10, 9,10,10,10,10, 9, 9, 9,10,
  148752. 9, 9, 9,10,10,10,10,10,10,
  148753. };
  148754. static float _vq_quantthresh__44un1__p7_2[] = {
  148755. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  148756. 2.5, 3.5, 4.5, 5.5,
  148757. };
  148758. static long _vq_quantmap__44un1__p7_2[] = {
  148759. 11, 9, 7, 5, 3, 1, 0, 2,
  148760. 4, 6, 8, 10, 12,
  148761. };
  148762. static encode_aux_threshmatch _vq_auxt__44un1__p7_2 = {
  148763. _vq_quantthresh__44un1__p7_2,
  148764. _vq_quantmap__44un1__p7_2,
  148765. 13,
  148766. 13
  148767. };
  148768. static static_codebook _44un1__p7_2 = {
  148769. 2, 169,
  148770. _vq_lengthlist__44un1__p7_2,
  148771. 1, -531103744, 1611661312, 4, 0,
  148772. _vq_quantlist__44un1__p7_2,
  148773. NULL,
  148774. &_vq_auxt__44un1__p7_2,
  148775. NULL,
  148776. 0
  148777. };
  148778. static long _huff_lengthlist__44un1__short[] = {
  148779. 12,12,14,12,14,14,14,14,12, 6, 6, 8, 9, 9,11,14,
  148780. 12, 4, 2, 6, 6, 7,11,14,13, 6, 5, 7, 8, 9,11,14,
  148781. 13, 8, 5, 8, 6, 8,12,14,12, 7, 7, 8, 8, 8,10,14,
  148782. 12, 6, 3, 4, 4, 4, 7,14,11, 7, 4, 6, 6, 6, 8,14,
  148783. };
  148784. static static_codebook _huff_book__44un1__short = {
  148785. 2, 64,
  148786. _huff_lengthlist__44un1__short,
  148787. 0, 0, 0, 0, 0,
  148788. NULL,
  148789. NULL,
  148790. NULL,
  148791. NULL,
  148792. 0
  148793. };
  148794. /********* End of inlined file: res_books_uncoupled.h *********/
  148795. /***** residue backends *********************************************/
  148796. static vorbis_info_residue0 _residue_44_low_un={
  148797. 0,-1, -1, 8,-1,
  148798. {0},
  148799. {-1},
  148800. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 28.5},
  148801. { -1, 25, -1, 45, -1, -1, -1}
  148802. };
  148803. static vorbis_info_residue0 _residue_44_mid_un={
  148804. 0,-1, -1, 10,-1,
  148805. /* 0 1 2 3 4 5 6 7 8 9 */
  148806. {0},
  148807. {-1},
  148808. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 4.5, 16.5, 60.5},
  148809. { -1, 30, -1, 50, -1, 80, -1, -1, -1}
  148810. };
  148811. static vorbis_info_residue0 _residue_44_hi_un={
  148812. 0,-1, -1, 10,-1,
  148813. /* 0 1 2 3 4 5 6 7 8 9 */
  148814. {0},
  148815. {-1},
  148816. { .5, 1.5, 2.5, 4.5, 8.5, 16.5, 32.5, 71.5,157.5},
  148817. { -1, -1, -1, -1, -1, -1, -1, -1, -1}
  148818. };
  148819. /* mapping conventions:
  148820. only one submap (this would change for efficient 5.1 support for example)*/
  148821. /* Four psychoacoustic profiles are used, one for each blocktype */
  148822. static vorbis_info_mapping0 _map_nominal_u[2]={
  148823. {1, {0,0}, {0}, {0}, 0,{0},{0}},
  148824. {1, {0,0}, {1}, {1}, 0,{0},{0}}
  148825. };
  148826. static static_bookblock _resbook_44u_n1={
  148827. {
  148828. {0},
  148829. {0,0,&_44un1__p1_0},
  148830. {0,0,&_44un1__p2_0},
  148831. {0,0,&_44un1__p3_0},
  148832. {0,0,&_44un1__p4_0},
  148833. {0,0,&_44un1__p5_0},
  148834. {&_44un1__p6_0,&_44un1__p6_1},
  148835. {&_44un1__p7_0,&_44un1__p7_1,&_44un1__p7_2}
  148836. }
  148837. };
  148838. static static_bookblock _resbook_44u_0={
  148839. {
  148840. {0},
  148841. {0,0,&_44u0__p1_0},
  148842. {0,0,&_44u0__p2_0},
  148843. {0,0,&_44u0__p3_0},
  148844. {0,0,&_44u0__p4_0},
  148845. {0,0,&_44u0__p5_0},
  148846. {&_44u0__p6_0,&_44u0__p6_1},
  148847. {&_44u0__p7_0,&_44u0__p7_1,&_44u0__p7_2}
  148848. }
  148849. };
  148850. static static_bookblock _resbook_44u_1={
  148851. {
  148852. {0},
  148853. {0,0,&_44u1__p1_0},
  148854. {0,0,&_44u1__p2_0},
  148855. {0,0,&_44u1__p3_0},
  148856. {0,0,&_44u1__p4_0},
  148857. {0,0,&_44u1__p5_0},
  148858. {&_44u1__p6_0,&_44u1__p6_1},
  148859. {&_44u1__p7_0,&_44u1__p7_1,&_44u1__p7_2}
  148860. }
  148861. };
  148862. static static_bookblock _resbook_44u_2={
  148863. {
  148864. {0},
  148865. {0,0,&_44u2__p1_0},
  148866. {0,0,&_44u2__p2_0},
  148867. {0,0,&_44u2__p3_0},
  148868. {0,0,&_44u2__p4_0},
  148869. {0,0,&_44u2__p5_0},
  148870. {&_44u2__p6_0,&_44u2__p6_1},
  148871. {&_44u2__p7_0,&_44u2__p7_1,&_44u2__p7_2}
  148872. }
  148873. };
  148874. static static_bookblock _resbook_44u_3={
  148875. {
  148876. {0},
  148877. {0,0,&_44u3__p1_0},
  148878. {0,0,&_44u3__p2_0},
  148879. {0,0,&_44u3__p3_0},
  148880. {0,0,&_44u3__p4_0},
  148881. {0,0,&_44u3__p5_0},
  148882. {&_44u3__p6_0,&_44u3__p6_1},
  148883. {&_44u3__p7_0,&_44u3__p7_1,&_44u3__p7_2}
  148884. }
  148885. };
  148886. static static_bookblock _resbook_44u_4={
  148887. {
  148888. {0},
  148889. {0,0,&_44u4__p1_0},
  148890. {0,0,&_44u4__p2_0},
  148891. {0,0,&_44u4__p3_0},
  148892. {0,0,&_44u4__p4_0},
  148893. {0,0,&_44u4__p5_0},
  148894. {&_44u4__p6_0,&_44u4__p6_1},
  148895. {&_44u4__p7_0,&_44u4__p7_1,&_44u4__p7_2}
  148896. }
  148897. };
  148898. static static_bookblock _resbook_44u_5={
  148899. {
  148900. {0},
  148901. {0,0,&_44u5__p1_0},
  148902. {0,0,&_44u5__p2_0},
  148903. {0,0,&_44u5__p3_0},
  148904. {0,0,&_44u5__p4_0},
  148905. {0,0,&_44u5__p5_0},
  148906. {0,0,&_44u5__p6_0},
  148907. {&_44u5__p7_0,&_44u5__p7_1},
  148908. {&_44u5__p8_0,&_44u5__p8_1},
  148909. {&_44u5__p9_0,&_44u5__p9_1,&_44u5__p9_2}
  148910. }
  148911. };
  148912. static static_bookblock _resbook_44u_6={
  148913. {
  148914. {0},
  148915. {0,0,&_44u6__p1_0},
  148916. {0,0,&_44u6__p2_0},
  148917. {0,0,&_44u6__p3_0},
  148918. {0,0,&_44u6__p4_0},
  148919. {0,0,&_44u6__p5_0},
  148920. {0,0,&_44u6__p6_0},
  148921. {&_44u6__p7_0,&_44u6__p7_1},
  148922. {&_44u6__p8_0,&_44u6__p8_1},
  148923. {&_44u6__p9_0,&_44u6__p9_1,&_44u6__p9_2}
  148924. }
  148925. };
  148926. static static_bookblock _resbook_44u_7={
  148927. {
  148928. {0},
  148929. {0,0,&_44u7__p1_0},
  148930. {0,0,&_44u7__p2_0},
  148931. {0,0,&_44u7__p3_0},
  148932. {0,0,&_44u7__p4_0},
  148933. {0,0,&_44u7__p5_0},
  148934. {0,0,&_44u7__p6_0},
  148935. {&_44u7__p7_0,&_44u7__p7_1},
  148936. {&_44u7__p8_0,&_44u7__p8_1},
  148937. {&_44u7__p9_0,&_44u7__p9_1,&_44u7__p9_2}
  148938. }
  148939. };
  148940. static static_bookblock _resbook_44u_8={
  148941. {
  148942. {0},
  148943. {0,0,&_44u8_p1_0},
  148944. {0,0,&_44u8_p2_0},
  148945. {0,0,&_44u8_p3_0},
  148946. {0,0,&_44u8_p4_0},
  148947. {&_44u8_p5_0,&_44u8_p5_1},
  148948. {&_44u8_p6_0,&_44u8_p6_1},
  148949. {&_44u8_p7_0,&_44u8_p7_1},
  148950. {&_44u8_p8_0,&_44u8_p8_1},
  148951. {&_44u8_p9_0,&_44u8_p9_1,&_44u8_p9_2}
  148952. }
  148953. };
  148954. static static_bookblock _resbook_44u_9={
  148955. {
  148956. {0},
  148957. {0,0,&_44u9_p1_0},
  148958. {0,0,&_44u9_p2_0},
  148959. {0,0,&_44u9_p3_0},
  148960. {0,0,&_44u9_p4_0},
  148961. {&_44u9_p5_0,&_44u9_p5_1},
  148962. {&_44u9_p6_0,&_44u9_p6_1},
  148963. {&_44u9_p7_0,&_44u9_p7_1},
  148964. {&_44u9_p8_0,&_44u9_p8_1},
  148965. {&_44u9_p9_0,&_44u9_p9_1,&_44u9_p9_2}
  148966. }
  148967. };
  148968. static vorbis_residue_template _res_44u_n1[]={
  148969. {1,0, &_residue_44_low_un,
  148970. &_huff_book__44un1__short,&_huff_book__44un1__short,
  148971. &_resbook_44u_n1,&_resbook_44u_n1},
  148972. {1,0, &_residue_44_low_un,
  148973. &_huff_book__44un1__long,&_huff_book__44un1__long,
  148974. &_resbook_44u_n1,&_resbook_44u_n1}
  148975. };
  148976. static vorbis_residue_template _res_44u_0[]={
  148977. {1,0, &_residue_44_low_un,
  148978. &_huff_book__44u0__short,&_huff_book__44u0__short,
  148979. &_resbook_44u_0,&_resbook_44u_0},
  148980. {1,0, &_residue_44_low_un,
  148981. &_huff_book__44u0__long,&_huff_book__44u0__long,
  148982. &_resbook_44u_0,&_resbook_44u_0}
  148983. };
  148984. static vorbis_residue_template _res_44u_1[]={
  148985. {1,0, &_residue_44_low_un,
  148986. &_huff_book__44u1__short,&_huff_book__44u1__short,
  148987. &_resbook_44u_1,&_resbook_44u_1},
  148988. {1,0, &_residue_44_low_un,
  148989. &_huff_book__44u1__long,&_huff_book__44u1__long,
  148990. &_resbook_44u_1,&_resbook_44u_1}
  148991. };
  148992. static vorbis_residue_template _res_44u_2[]={
  148993. {1,0, &_residue_44_low_un,
  148994. &_huff_book__44u2__short,&_huff_book__44u2__short,
  148995. &_resbook_44u_2,&_resbook_44u_2},
  148996. {1,0, &_residue_44_low_un,
  148997. &_huff_book__44u2__long,&_huff_book__44u2__long,
  148998. &_resbook_44u_2,&_resbook_44u_2}
  148999. };
  149000. static vorbis_residue_template _res_44u_3[]={
  149001. {1,0, &_residue_44_low_un,
  149002. &_huff_book__44u3__short,&_huff_book__44u3__short,
  149003. &_resbook_44u_3,&_resbook_44u_3},
  149004. {1,0, &_residue_44_low_un,
  149005. &_huff_book__44u3__long,&_huff_book__44u3__long,
  149006. &_resbook_44u_3,&_resbook_44u_3}
  149007. };
  149008. static vorbis_residue_template _res_44u_4[]={
  149009. {1,0, &_residue_44_low_un,
  149010. &_huff_book__44u4__short,&_huff_book__44u4__short,
  149011. &_resbook_44u_4,&_resbook_44u_4},
  149012. {1,0, &_residue_44_low_un,
  149013. &_huff_book__44u4__long,&_huff_book__44u4__long,
  149014. &_resbook_44u_4,&_resbook_44u_4}
  149015. };
  149016. static vorbis_residue_template _res_44u_5[]={
  149017. {1,0, &_residue_44_mid_un,
  149018. &_huff_book__44u5__short,&_huff_book__44u5__short,
  149019. &_resbook_44u_5,&_resbook_44u_5},
  149020. {1,0, &_residue_44_mid_un,
  149021. &_huff_book__44u5__long,&_huff_book__44u5__long,
  149022. &_resbook_44u_5,&_resbook_44u_5}
  149023. };
  149024. static vorbis_residue_template _res_44u_6[]={
  149025. {1,0, &_residue_44_mid_un,
  149026. &_huff_book__44u6__short,&_huff_book__44u6__short,
  149027. &_resbook_44u_6,&_resbook_44u_6},
  149028. {1,0, &_residue_44_mid_un,
  149029. &_huff_book__44u6__long,&_huff_book__44u6__long,
  149030. &_resbook_44u_6,&_resbook_44u_6}
  149031. };
  149032. static vorbis_residue_template _res_44u_7[]={
  149033. {1,0, &_residue_44_mid_un,
  149034. &_huff_book__44u7__short,&_huff_book__44u7__short,
  149035. &_resbook_44u_7,&_resbook_44u_7},
  149036. {1,0, &_residue_44_mid_un,
  149037. &_huff_book__44u7__long,&_huff_book__44u7__long,
  149038. &_resbook_44u_7,&_resbook_44u_7}
  149039. };
  149040. static vorbis_residue_template _res_44u_8[]={
  149041. {1,0, &_residue_44_hi_un,
  149042. &_huff_book__44u8__short,&_huff_book__44u8__short,
  149043. &_resbook_44u_8,&_resbook_44u_8},
  149044. {1,0, &_residue_44_hi_un,
  149045. &_huff_book__44u8__long,&_huff_book__44u8__long,
  149046. &_resbook_44u_8,&_resbook_44u_8}
  149047. };
  149048. static vorbis_residue_template _res_44u_9[]={
  149049. {1,0, &_residue_44_hi_un,
  149050. &_huff_book__44u9__short,&_huff_book__44u9__short,
  149051. &_resbook_44u_9,&_resbook_44u_9},
  149052. {1,0, &_residue_44_hi_un,
  149053. &_huff_book__44u9__long,&_huff_book__44u9__long,
  149054. &_resbook_44u_9,&_resbook_44u_9}
  149055. };
  149056. static vorbis_mapping_template _mapres_template_44_uncoupled[]={
  149057. { _map_nominal_u, _res_44u_n1 }, /* -1 */
  149058. { _map_nominal_u, _res_44u_0 }, /* 0 */
  149059. { _map_nominal_u, _res_44u_1 }, /* 1 */
  149060. { _map_nominal_u, _res_44u_2 }, /* 2 */
  149061. { _map_nominal_u, _res_44u_3 }, /* 3 */
  149062. { _map_nominal_u, _res_44u_4 }, /* 4 */
  149063. { _map_nominal_u, _res_44u_5 }, /* 5 */
  149064. { _map_nominal_u, _res_44u_6 }, /* 6 */
  149065. { _map_nominal_u, _res_44u_7 }, /* 7 */
  149066. { _map_nominal_u, _res_44u_8 }, /* 8 */
  149067. { _map_nominal_u, _res_44u_9 }, /* 9 */
  149068. };
  149069. /********* End of inlined file: residue_44u.h *********/
  149070. static double rate_mapping_44_un[12]={
  149071. 32000.,48000.,60000.,70000.,80000.,86000.,
  149072. 96000.,110000.,120000.,140000.,160000.,240001.
  149073. };
  149074. ve_setup_data_template ve_setup_44_uncoupled={
  149075. 11,
  149076. rate_mapping_44_un,
  149077. quality_mapping_44,
  149078. -1,
  149079. 40000,
  149080. 50000,
  149081. blocksize_short_44,
  149082. blocksize_long_44,
  149083. _psy_tone_masteratt_44,
  149084. _psy_tone_0dB,
  149085. _psy_tone_suppress,
  149086. _vp_tonemask_adj_otherblock,
  149087. _vp_tonemask_adj_longblock,
  149088. _vp_tonemask_adj_otherblock,
  149089. _psy_noiseguards_44,
  149090. _psy_noisebias_impulse,
  149091. _psy_noisebias_padding,
  149092. _psy_noisebias_trans,
  149093. _psy_noisebias_long,
  149094. _psy_noise_suppress,
  149095. _psy_compand_44,
  149096. _psy_compand_short_mapping,
  149097. _psy_compand_long_mapping,
  149098. {_noise_start_short_44,_noise_start_long_44},
  149099. {_noise_part_short_44,_noise_part_long_44},
  149100. _noise_thresh_44,
  149101. _psy_ath_floater,
  149102. _psy_ath_abs,
  149103. _psy_lowpass_44,
  149104. _psy_global_44,
  149105. _global_mapping_44,
  149106. NULL,
  149107. _floor_books,
  149108. _floor,
  149109. _floor_short_mapping_44,
  149110. _floor_long_mapping_44,
  149111. _mapres_template_44_uncoupled
  149112. };
  149113. /********* End of inlined file: setup_44u.h *********/
  149114. /********* Start of inlined file: setup_32.h *********/
  149115. static double rate_mapping_32[12]={
  149116. 18000.,28000.,35000.,45000.,56000.,60000.,
  149117. 75000.,90000.,100000.,115000.,150000.,190000.,
  149118. };
  149119. static double rate_mapping_32_un[12]={
  149120. 30000.,42000.,52000.,64000.,72000.,78000.,
  149121. 86000.,92000.,110000.,120000.,140000.,190000.,
  149122. };
  149123. static double _psy_lowpass_32[12]={
  149124. 12.3,13.,13.,14.,15.,99.,99.,99.,99.,99.,99.,99.
  149125. };
  149126. ve_setup_data_template ve_setup_32_stereo={
  149127. 11,
  149128. rate_mapping_32,
  149129. quality_mapping_44,
  149130. 2,
  149131. 26000,
  149132. 40000,
  149133. blocksize_short_44,
  149134. blocksize_long_44,
  149135. _psy_tone_masteratt_44,
  149136. _psy_tone_0dB,
  149137. _psy_tone_suppress,
  149138. _vp_tonemask_adj_otherblock,
  149139. _vp_tonemask_adj_longblock,
  149140. _vp_tonemask_adj_otherblock,
  149141. _psy_noiseguards_44,
  149142. _psy_noisebias_impulse,
  149143. _psy_noisebias_padding,
  149144. _psy_noisebias_trans,
  149145. _psy_noisebias_long,
  149146. _psy_noise_suppress,
  149147. _psy_compand_44,
  149148. _psy_compand_short_mapping,
  149149. _psy_compand_long_mapping,
  149150. {_noise_start_short_44,_noise_start_long_44},
  149151. {_noise_part_short_44,_noise_part_long_44},
  149152. _noise_thresh_44,
  149153. _psy_ath_floater,
  149154. _psy_ath_abs,
  149155. _psy_lowpass_32,
  149156. _psy_global_44,
  149157. _global_mapping_44,
  149158. _psy_stereo_modes_44,
  149159. _floor_books,
  149160. _floor,
  149161. _floor_short_mapping_44,
  149162. _floor_long_mapping_44,
  149163. _mapres_template_44_stereo
  149164. };
  149165. ve_setup_data_template ve_setup_32_uncoupled={
  149166. 11,
  149167. rate_mapping_32_un,
  149168. quality_mapping_44,
  149169. -1,
  149170. 26000,
  149171. 40000,
  149172. blocksize_short_44,
  149173. blocksize_long_44,
  149174. _psy_tone_masteratt_44,
  149175. _psy_tone_0dB,
  149176. _psy_tone_suppress,
  149177. _vp_tonemask_adj_otherblock,
  149178. _vp_tonemask_adj_longblock,
  149179. _vp_tonemask_adj_otherblock,
  149180. _psy_noiseguards_44,
  149181. _psy_noisebias_impulse,
  149182. _psy_noisebias_padding,
  149183. _psy_noisebias_trans,
  149184. _psy_noisebias_long,
  149185. _psy_noise_suppress,
  149186. _psy_compand_44,
  149187. _psy_compand_short_mapping,
  149188. _psy_compand_long_mapping,
  149189. {_noise_start_short_44,_noise_start_long_44},
  149190. {_noise_part_short_44,_noise_part_long_44},
  149191. _noise_thresh_44,
  149192. _psy_ath_floater,
  149193. _psy_ath_abs,
  149194. _psy_lowpass_32,
  149195. _psy_global_44,
  149196. _global_mapping_44,
  149197. NULL,
  149198. _floor_books,
  149199. _floor,
  149200. _floor_short_mapping_44,
  149201. _floor_long_mapping_44,
  149202. _mapres_template_44_uncoupled
  149203. };
  149204. /********* End of inlined file: setup_32.h *********/
  149205. /********* Start of inlined file: setup_8.h *********/
  149206. /********* Start of inlined file: psych_8.h *********/
  149207. static att3 _psy_tone_masteratt_8[3]={
  149208. {{ 32, 25, 12}, 0, 0}, /* 0 */
  149209. {{ 30, 25, 12}, 0, 0}, /* 0 */
  149210. {{ 20, 0, -14}, 0, 0}, /* 0 */
  149211. };
  149212. static vp_adjblock _vp_tonemask_adj_8[3]={
  149213. /* adjust for mode zero */
  149214. /* 63 125 250 500 1 2 4 8 16 */
  149215. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0,10, 0, 0,99,99,99}}, /* 1 */
  149216. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0,10, 0, 0,99,99,99}}, /* 1 */
  149217. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0, 0, 0, 0,99,99,99}}, /* 1 */
  149218. };
  149219. static noise3 _psy_noisebias_8[3]={
  149220. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  149221. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 8, 8, 8, 10, 10, 99, 99, 99},
  149222. {-10,-10,-10,-10, -5, -5, -5, 0, 0, 4, 4, 4, 4, 4, 99, 99, 99},
  149223. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  149224. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 8, 8, 8, 10, 10, 99, 99, 99},
  149225. {-10,-10,-10,-10,-10,-10, -5, -5, -5, 0, 0, 0, 0, 0, 99, 99, 99},
  149226. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  149227. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 99, 99, 99},
  149228. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10, 99, 99, 99},
  149229. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24, 99, 99, 99}}},
  149230. };
  149231. /* stereo mode by base quality level */
  149232. static adj_stereo _psy_stereo_modes_8[3]={
  149233. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 */
  149234. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  149235. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  149236. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  149237. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  149238. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  149239. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  149240. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  149241. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  149242. {{ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  149243. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  149244. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  149245. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  149246. };
  149247. static noiseguard _psy_noiseguards_8[2]={
  149248. {10,10,-1},
  149249. {10,10,-1},
  149250. };
  149251. static compandblock _psy_compand_8[2]={
  149252. {{
  149253. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  149254. 8, 8, 9, 9,10,10,11, 11, /* 15dB */
  149255. 12,12,13,13,14,14,15, 15, /* 23dB */
  149256. 16,16,17,17,17,18,18, 19, /* 31dB */
  149257. 19,19,20,21,22,23,24, 25, /* 39dB */
  149258. }},
  149259. {{
  149260. 0, 1, 2, 3, 4, 5, 6, 6, /* 7dB */
  149261. 7, 7, 6, 6, 5, 5, 4, 4, /* 15dB */
  149262. 3, 3, 3, 4, 5, 6, 7, 8, /* 23dB */
  149263. 9,10,11,12,13,14,15, 16, /* 31dB */
  149264. 17,18,19,20,21,22,23, 24, /* 39dB */
  149265. }},
  149266. };
  149267. static double _psy_lowpass_8[3]={3.,4.,4.};
  149268. static int _noise_start_8[2]={
  149269. 64,64,
  149270. };
  149271. static int _noise_part_8[2]={
  149272. 8,8,
  149273. };
  149274. static int _psy_ath_floater_8[3]={
  149275. -100,-100,-105,
  149276. };
  149277. static int _psy_ath_abs_8[3]={
  149278. -130,-130,-140,
  149279. };
  149280. /********* End of inlined file: psych_8.h *********/
  149281. /********* Start of inlined file: residue_8.h *********/
  149282. /***** residue backends *********************************************/
  149283. static static_bookblock _resbook_8s_0={
  149284. {
  149285. {0},{0,0,&_8c0_s_p1_0},{0,0,&_8c0_s_p2_0},{0,0,&_8c0_s_p3_0},
  149286. {0,0,&_8c0_s_p4_0},{0,0,&_8c0_s_p5_0},{0,0,&_8c0_s_p6_0},
  149287. {&_8c0_s_p7_0,&_8c0_s_p7_1},{&_8c0_s_p8_0,&_8c0_s_p8_1},
  149288. {&_8c0_s_p9_0,&_8c0_s_p9_1,&_8c0_s_p9_2}
  149289. }
  149290. };
  149291. static static_bookblock _resbook_8s_1={
  149292. {
  149293. {0},{0,0,&_8c1_s_p1_0},{0,0,&_8c1_s_p2_0},{0,0,&_8c1_s_p3_0},
  149294. {0,0,&_8c1_s_p4_0},{0,0,&_8c1_s_p5_0},{0,0,&_8c1_s_p6_0},
  149295. {&_8c1_s_p7_0,&_8c1_s_p7_1},{&_8c1_s_p8_0,&_8c1_s_p8_1},
  149296. {&_8c1_s_p9_0,&_8c1_s_p9_1,&_8c1_s_p9_2}
  149297. }
  149298. };
  149299. static vorbis_residue_template _res_8s_0[]={
  149300. {2,0, &_residue_44_mid,
  149301. &_huff_book__8c0_s_single,&_huff_book__8c0_s_single,
  149302. &_resbook_8s_0,&_resbook_8s_0},
  149303. };
  149304. static vorbis_residue_template _res_8s_1[]={
  149305. {2,0, &_residue_44_mid,
  149306. &_huff_book__8c1_s_single,&_huff_book__8c1_s_single,
  149307. &_resbook_8s_1,&_resbook_8s_1},
  149308. };
  149309. static vorbis_mapping_template _mapres_template_8_stereo[2]={
  149310. { _map_nominal, _res_8s_0 }, /* 0 */
  149311. { _map_nominal, _res_8s_1 }, /* 1 */
  149312. };
  149313. static static_bookblock _resbook_8u_0={
  149314. {
  149315. {0},
  149316. {0,0,&_8u0__p1_0},
  149317. {0,0,&_8u0__p2_0},
  149318. {0,0,&_8u0__p3_0},
  149319. {0,0,&_8u0__p4_0},
  149320. {0,0,&_8u0__p5_0},
  149321. {&_8u0__p6_0,&_8u0__p6_1},
  149322. {&_8u0__p7_0,&_8u0__p7_1,&_8u0__p7_2}
  149323. }
  149324. };
  149325. static static_bookblock _resbook_8u_1={
  149326. {
  149327. {0},
  149328. {0,0,&_8u1__p1_0},
  149329. {0,0,&_8u1__p2_0},
  149330. {0,0,&_8u1__p3_0},
  149331. {0,0,&_8u1__p4_0},
  149332. {0,0,&_8u1__p5_0},
  149333. {0,0,&_8u1__p6_0},
  149334. {&_8u1__p7_0,&_8u1__p7_1},
  149335. {&_8u1__p8_0,&_8u1__p8_1},
  149336. {&_8u1__p9_0,&_8u1__p9_1,&_8u1__p9_2}
  149337. }
  149338. };
  149339. static vorbis_residue_template _res_8u_0[]={
  149340. {1,0, &_residue_44_low_un,
  149341. &_huff_book__8u0__single,&_huff_book__8u0__single,
  149342. &_resbook_8u_0,&_resbook_8u_0},
  149343. };
  149344. static vorbis_residue_template _res_8u_1[]={
  149345. {1,0, &_residue_44_mid_un,
  149346. &_huff_book__8u1__single,&_huff_book__8u1__single,
  149347. &_resbook_8u_1,&_resbook_8u_1},
  149348. };
  149349. static vorbis_mapping_template _mapres_template_8_uncoupled[2]={
  149350. { _map_nominal_u, _res_8u_0 }, /* 0 */
  149351. { _map_nominal_u, _res_8u_1 }, /* 1 */
  149352. };
  149353. /********* End of inlined file: residue_8.h *********/
  149354. static int blocksize_8[2]={
  149355. 512,512
  149356. };
  149357. static int _floor_mapping_8[2]={
  149358. 6,6,
  149359. };
  149360. static double rate_mapping_8[3]={
  149361. 6000.,9000.,32000.,
  149362. };
  149363. static double rate_mapping_8_uncoupled[3]={
  149364. 8000.,14000.,42000.,
  149365. };
  149366. static double quality_mapping_8[3]={
  149367. -.1,.0,1.
  149368. };
  149369. static double _psy_compand_8_mapping[3]={ 0., 1., 1.};
  149370. static double _global_mapping_8[3]={ 1., 2., 3. };
  149371. ve_setup_data_template ve_setup_8_stereo={
  149372. 2,
  149373. rate_mapping_8,
  149374. quality_mapping_8,
  149375. 2,
  149376. 8000,
  149377. 9000,
  149378. blocksize_8,
  149379. blocksize_8,
  149380. _psy_tone_masteratt_8,
  149381. _psy_tone_0dB,
  149382. _psy_tone_suppress,
  149383. _vp_tonemask_adj_8,
  149384. NULL,
  149385. _vp_tonemask_adj_8,
  149386. _psy_noiseguards_8,
  149387. _psy_noisebias_8,
  149388. _psy_noisebias_8,
  149389. NULL,
  149390. NULL,
  149391. _psy_noise_suppress,
  149392. _psy_compand_8,
  149393. _psy_compand_8_mapping,
  149394. NULL,
  149395. {_noise_start_8,_noise_start_8},
  149396. {_noise_part_8,_noise_part_8},
  149397. _noise_thresh_5only,
  149398. _psy_ath_floater_8,
  149399. _psy_ath_abs_8,
  149400. _psy_lowpass_8,
  149401. _psy_global_44,
  149402. _global_mapping_8,
  149403. _psy_stereo_modes_8,
  149404. _floor_books,
  149405. _floor,
  149406. _floor_mapping_8,
  149407. NULL,
  149408. _mapres_template_8_stereo
  149409. };
  149410. ve_setup_data_template ve_setup_8_uncoupled={
  149411. 2,
  149412. rate_mapping_8_uncoupled,
  149413. quality_mapping_8,
  149414. -1,
  149415. 8000,
  149416. 9000,
  149417. blocksize_8,
  149418. blocksize_8,
  149419. _psy_tone_masteratt_8,
  149420. _psy_tone_0dB,
  149421. _psy_tone_suppress,
  149422. _vp_tonemask_adj_8,
  149423. NULL,
  149424. _vp_tonemask_adj_8,
  149425. _psy_noiseguards_8,
  149426. _psy_noisebias_8,
  149427. _psy_noisebias_8,
  149428. NULL,
  149429. NULL,
  149430. _psy_noise_suppress,
  149431. _psy_compand_8,
  149432. _psy_compand_8_mapping,
  149433. NULL,
  149434. {_noise_start_8,_noise_start_8},
  149435. {_noise_part_8,_noise_part_8},
  149436. _noise_thresh_5only,
  149437. _psy_ath_floater_8,
  149438. _psy_ath_abs_8,
  149439. _psy_lowpass_8,
  149440. _psy_global_44,
  149441. _global_mapping_8,
  149442. _psy_stereo_modes_8,
  149443. _floor_books,
  149444. _floor,
  149445. _floor_mapping_8,
  149446. NULL,
  149447. _mapres_template_8_uncoupled
  149448. };
  149449. /********* End of inlined file: setup_8.h *********/
  149450. /********* Start of inlined file: setup_11.h *********/
  149451. /********* Start of inlined file: psych_11.h *********/
  149452. static double _psy_lowpass_11[3]={4.5,5.5,30.,};
  149453. static att3 _psy_tone_masteratt_11[3]={
  149454. {{ 30, 25, 12}, 0, 0}, /* 0 */
  149455. {{ 30, 25, 12}, 0, 0}, /* 0 */
  149456. {{ 20, 0, -14}, 0, 0}, /* 0 */
  149457. };
  149458. static vp_adjblock _vp_tonemask_adj_11[3]={
  149459. /* adjust for mode zero */
  149460. /* 63 125 250 500 1 2 4 8 16 */
  149461. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 2, 0,99,99,99}}, /* 0 */
  149462. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 5, 0, 0,99,99,99}}, /* 1 */
  149463. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 0, 0, 0,99,99,99}}, /* 2 */
  149464. };
  149465. static noise3 _psy_noisebias_11[3]={
  149466. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  149467. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 10, 10, 12, 12, 12, 99, 99, 99},
  149468. {-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 4, 5, 5, 10, 99, 99, 99},
  149469. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  149470. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 10, 10, 12, 12, 12, 99, 99, 99},
  149471. {-15,-15,-15,-15,-10,-10, -5, -5, -5, 0, 0, 0, 0, 0, 99, 99, 99},
  149472. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  149473. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 99, 99, 99},
  149474. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10, 99, 99, 99},
  149475. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24, 99, 99, 99}}},
  149476. };
  149477. static double _noise_thresh_11[3]={ .3,.5,.5 };
  149478. /********* End of inlined file: psych_11.h *********/
  149479. static int blocksize_11[2]={
  149480. 512,512
  149481. };
  149482. static int _floor_mapping_11[2]={
  149483. 6,6,
  149484. };
  149485. static double rate_mapping_11[3]={
  149486. 8000.,13000.,44000.,
  149487. };
  149488. static double rate_mapping_11_uncoupled[3]={
  149489. 12000.,20000.,50000.,
  149490. };
  149491. static double quality_mapping_11[3]={
  149492. -.1,.0,1.
  149493. };
  149494. ve_setup_data_template ve_setup_11_stereo={
  149495. 2,
  149496. rate_mapping_11,
  149497. quality_mapping_11,
  149498. 2,
  149499. 9000,
  149500. 15000,
  149501. blocksize_11,
  149502. blocksize_11,
  149503. _psy_tone_masteratt_11,
  149504. _psy_tone_0dB,
  149505. _psy_tone_suppress,
  149506. _vp_tonemask_adj_11,
  149507. NULL,
  149508. _vp_tonemask_adj_11,
  149509. _psy_noiseguards_8,
  149510. _psy_noisebias_11,
  149511. _psy_noisebias_11,
  149512. NULL,
  149513. NULL,
  149514. _psy_noise_suppress,
  149515. _psy_compand_8,
  149516. _psy_compand_8_mapping,
  149517. NULL,
  149518. {_noise_start_8,_noise_start_8},
  149519. {_noise_part_8,_noise_part_8},
  149520. _noise_thresh_11,
  149521. _psy_ath_floater_8,
  149522. _psy_ath_abs_8,
  149523. _psy_lowpass_11,
  149524. _psy_global_44,
  149525. _global_mapping_8,
  149526. _psy_stereo_modes_8,
  149527. _floor_books,
  149528. _floor,
  149529. _floor_mapping_11,
  149530. NULL,
  149531. _mapres_template_8_stereo
  149532. };
  149533. ve_setup_data_template ve_setup_11_uncoupled={
  149534. 2,
  149535. rate_mapping_11_uncoupled,
  149536. quality_mapping_11,
  149537. -1,
  149538. 9000,
  149539. 15000,
  149540. blocksize_11,
  149541. blocksize_11,
  149542. _psy_tone_masteratt_11,
  149543. _psy_tone_0dB,
  149544. _psy_tone_suppress,
  149545. _vp_tonemask_adj_11,
  149546. NULL,
  149547. _vp_tonemask_adj_11,
  149548. _psy_noiseguards_8,
  149549. _psy_noisebias_11,
  149550. _psy_noisebias_11,
  149551. NULL,
  149552. NULL,
  149553. _psy_noise_suppress,
  149554. _psy_compand_8,
  149555. _psy_compand_8_mapping,
  149556. NULL,
  149557. {_noise_start_8,_noise_start_8},
  149558. {_noise_part_8,_noise_part_8},
  149559. _noise_thresh_11,
  149560. _psy_ath_floater_8,
  149561. _psy_ath_abs_8,
  149562. _psy_lowpass_11,
  149563. _psy_global_44,
  149564. _global_mapping_8,
  149565. _psy_stereo_modes_8,
  149566. _floor_books,
  149567. _floor,
  149568. _floor_mapping_11,
  149569. NULL,
  149570. _mapres_template_8_uncoupled
  149571. };
  149572. /********* End of inlined file: setup_11.h *********/
  149573. /********* Start of inlined file: setup_16.h *********/
  149574. /********* Start of inlined file: psych_16.h *********/
  149575. /* stereo mode by base quality level */
  149576. static adj_stereo _psy_stereo_modes_16[4]={
  149577. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 */
  149578. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  149579. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  149580. { 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 4, 4},
  149581. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  149582. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  149583. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  149584. { 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 4, 4, 4, 4, 4},
  149585. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  149586. {{ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  149587. { 5, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  149588. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  149589. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  149590. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  149591. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  149592. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8},
  149593. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  149594. };
  149595. static double _psy_lowpass_16[4]={6.5,8,30.,99.};
  149596. static att3 _psy_tone_masteratt_16[4]={
  149597. {{ 30, 25, 12}, 0, 0}, /* 0 */
  149598. {{ 25, 22, 12}, 0, 0}, /* 0 */
  149599. {{ 20, 12, 0}, 0, 0}, /* 0 */
  149600. {{ 15, 0, -14}, 0, 0}, /* 0 */
  149601. };
  149602. static vp_adjblock _vp_tonemask_adj_16[4]={
  149603. /* adjust for mode zero */
  149604. /* 63 125 250 500 1 2 4 8 16 */
  149605. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 0, 0, 0, 0, 0}}, /* 0 */
  149606. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 0, 0, 0, 0, 0}}, /* 1 */
  149607. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, /* 2 */
  149608. {{-30,-30,-30,-30,-30,-26,-20,-10, -5, 0, 0, 0, 0, 0, 0, 0, 0}}, /* 2 */
  149609. };
  149610. static noise3 _psy_noisebias_16_short[4]={
  149611. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  149612. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 10, 10, 10, 10, 12, 12, 14, 20},
  149613. {-15,-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 5, 5, 6, 8, 8, 15},
  149614. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  149615. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 6, 6, 6, 6, 8, 10, 12, 20},
  149616. {-15,-15,-15,-15,-15,-15,-15,-10, -5, -5, -5, 4, 5, 6, 8, 8, 15},
  149617. {-30,-30,-30,-30,-30,-24,-20,-14,-10,-10,-10,-10,-10,-10,-10,-10,-10}}},
  149618. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 12},
  149619. {-20,-20,-20,-20,-16,-12,-20,-14,-10,-10, -8, 0, 0, 0, 0, 2, 5},
  149620. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  149621. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  149622. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10,-10,-10, -6},
  149623. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  149624. };
  149625. static noise3 _psy_noisebias_16_impulse[4]={
  149626. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  149627. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 10, 10, 10, 10, 12, 12, 14, 20},
  149628. {-15,-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 5, 5, 6, 8, 8, 15},
  149629. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  149630. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 4, 4, 4, 5, 5, 6, 8, 15},
  149631. {-15,-15,-15,-15,-15,-15,-15,-10, -5, -5, -5, 0, 0, 0, 0, 4, 10},
  149632. {-30,-30,-30,-30,-30,-24,-20,-14,-10,-10,-10,-10,-10,-10,-10,-10,-10}}},
  149633. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 4, 10},
  149634. {-20,-20,-20,-20,-16,-12,-20,-14,-10,-10,-10,-10,-10,-10,-10, -7, -5},
  149635. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  149636. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  149637. {-30,-30,-30,-30,-26,-22,-20,-18,-18,-18,-20,-20,-20,-20,-20,-20,-16},
  149638. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  149639. };
  149640. static noise3 _psy_noisebias_16[4]={
  149641. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  149642. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 6, 8, 8, 10, 10, 10, 14, 20},
  149643. {-10,-10,-10,-10,-10, -5, -2, -2, 0, 0, 0, 4, 5, 6, 8, 8, 15},
  149644. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  149645. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 6, 6, 6, 6, 8, 10, 12, 20},
  149646. {-15,-15,-15,-15,-15,-10, -5, -5, 0, 0, 0, 4, 5, 6, 8, 8, 15},
  149647. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  149648. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 12},
  149649. {-20,-20,-20,-20,-16,-12,-20,-10, -5, -5, 0, 0, 0, 0, 0, 2, 5},
  149650. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  149651. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  149652. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10,-10,-10, -6},
  149653. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  149654. };
  149655. static double _noise_thresh_16[4]={ .3,.5,.5,.5 };
  149656. static int _noise_start_16[3]={ 256,256,9999 };
  149657. static int _noise_part_16[4]={ 8,8,8,8 };
  149658. static int _psy_ath_floater_16[4]={
  149659. -100,-100,-100,-105,
  149660. };
  149661. static int _psy_ath_abs_16[4]={
  149662. -130,-130,-130,-140,
  149663. };
  149664. /********* End of inlined file: psych_16.h *********/
  149665. /********* Start of inlined file: residue_16.h *********/
  149666. /***** residue backends *********************************************/
  149667. static static_bookblock _resbook_16s_0={
  149668. {
  149669. {0},
  149670. {0,0,&_16c0_s_p1_0},
  149671. {0,0,&_16c0_s_p2_0},
  149672. {0,0,&_16c0_s_p3_0},
  149673. {0,0,&_16c0_s_p4_0},
  149674. {0,0,&_16c0_s_p5_0},
  149675. {0,0,&_16c0_s_p6_0},
  149676. {&_16c0_s_p7_0,&_16c0_s_p7_1},
  149677. {&_16c0_s_p8_0,&_16c0_s_p8_1},
  149678. {&_16c0_s_p9_0,&_16c0_s_p9_1,&_16c0_s_p9_2}
  149679. }
  149680. };
  149681. static static_bookblock _resbook_16s_1={
  149682. {
  149683. {0},
  149684. {0,0,&_16c1_s_p1_0},
  149685. {0,0,&_16c1_s_p2_0},
  149686. {0,0,&_16c1_s_p3_0},
  149687. {0,0,&_16c1_s_p4_0},
  149688. {0,0,&_16c1_s_p5_0},
  149689. {0,0,&_16c1_s_p6_0},
  149690. {&_16c1_s_p7_0,&_16c1_s_p7_1},
  149691. {&_16c1_s_p8_0,&_16c1_s_p8_1},
  149692. {&_16c1_s_p9_0,&_16c1_s_p9_1,&_16c1_s_p9_2}
  149693. }
  149694. };
  149695. static static_bookblock _resbook_16s_2={
  149696. {
  149697. {0},
  149698. {0,0,&_16c2_s_p1_0},
  149699. {0,0,&_16c2_s_p2_0},
  149700. {0,0,&_16c2_s_p3_0},
  149701. {0,0,&_16c2_s_p4_0},
  149702. {&_16c2_s_p5_0,&_16c2_s_p5_1},
  149703. {&_16c2_s_p6_0,&_16c2_s_p6_1},
  149704. {&_16c2_s_p7_0,&_16c2_s_p7_1},
  149705. {&_16c2_s_p8_0,&_16c2_s_p8_1},
  149706. {&_16c2_s_p9_0,&_16c2_s_p9_1,&_16c2_s_p9_2}
  149707. }
  149708. };
  149709. static vorbis_residue_template _res_16s_0[]={
  149710. {2,0, &_residue_44_mid,
  149711. &_huff_book__16c0_s_single,&_huff_book__16c0_s_single,
  149712. &_resbook_16s_0,&_resbook_16s_0},
  149713. };
  149714. static vorbis_residue_template _res_16s_1[]={
  149715. {2,0, &_residue_44_mid,
  149716. &_huff_book__16c1_s_short,&_huff_book__16c1_s_short,
  149717. &_resbook_16s_1,&_resbook_16s_1},
  149718. {2,0, &_residue_44_mid,
  149719. &_huff_book__16c1_s_long,&_huff_book__16c1_s_long,
  149720. &_resbook_16s_1,&_resbook_16s_1}
  149721. };
  149722. static vorbis_residue_template _res_16s_2[]={
  149723. {2,0, &_residue_44_high,
  149724. &_huff_book__16c2_s_short,&_huff_book__16c2_s_short,
  149725. &_resbook_16s_2,&_resbook_16s_2},
  149726. {2,0, &_residue_44_high,
  149727. &_huff_book__16c2_s_long,&_huff_book__16c2_s_long,
  149728. &_resbook_16s_2,&_resbook_16s_2}
  149729. };
  149730. static vorbis_mapping_template _mapres_template_16_stereo[3]={
  149731. { _map_nominal, _res_16s_0 }, /* 0 */
  149732. { _map_nominal, _res_16s_1 }, /* 1 */
  149733. { _map_nominal, _res_16s_2 }, /* 2 */
  149734. };
  149735. static static_bookblock _resbook_16u_0={
  149736. {
  149737. {0},
  149738. {0,0,&_16u0__p1_0},
  149739. {0,0,&_16u0__p2_0},
  149740. {0,0,&_16u0__p3_0},
  149741. {0,0,&_16u0__p4_0},
  149742. {0,0,&_16u0__p5_0},
  149743. {&_16u0__p6_0,&_16u0__p6_1},
  149744. {&_16u0__p7_0,&_16u0__p7_1,&_16u0__p7_2}
  149745. }
  149746. };
  149747. static static_bookblock _resbook_16u_1={
  149748. {
  149749. {0},
  149750. {0,0,&_16u1__p1_0},
  149751. {0,0,&_16u1__p2_0},
  149752. {0,0,&_16u1__p3_0},
  149753. {0,0,&_16u1__p4_0},
  149754. {0,0,&_16u1__p5_0},
  149755. {0,0,&_16u1__p6_0},
  149756. {&_16u1__p7_0,&_16u1__p7_1},
  149757. {&_16u1__p8_0,&_16u1__p8_1},
  149758. {&_16u1__p9_0,&_16u1__p9_1,&_16u1__p9_2}
  149759. }
  149760. };
  149761. static static_bookblock _resbook_16u_2={
  149762. {
  149763. {0},
  149764. {0,0,&_16u2_p1_0},
  149765. {0,0,&_16u2_p2_0},
  149766. {0,0,&_16u2_p3_0},
  149767. {0,0,&_16u2_p4_0},
  149768. {&_16u2_p5_0,&_16u2_p5_1},
  149769. {&_16u2_p6_0,&_16u2_p6_1},
  149770. {&_16u2_p7_0,&_16u2_p7_1},
  149771. {&_16u2_p8_0,&_16u2_p8_1},
  149772. {&_16u2_p9_0,&_16u2_p9_1,&_16u2_p9_2}
  149773. }
  149774. };
  149775. static vorbis_residue_template _res_16u_0[]={
  149776. {1,0, &_residue_44_low_un,
  149777. &_huff_book__16u0__single,&_huff_book__16u0__single,
  149778. &_resbook_16u_0,&_resbook_16u_0},
  149779. };
  149780. static vorbis_residue_template _res_16u_1[]={
  149781. {1,0, &_residue_44_mid_un,
  149782. &_huff_book__16u1__short,&_huff_book__16u1__short,
  149783. &_resbook_16u_1,&_resbook_16u_1},
  149784. {1,0, &_residue_44_mid_un,
  149785. &_huff_book__16u1__long,&_huff_book__16u1__long,
  149786. &_resbook_16u_1,&_resbook_16u_1}
  149787. };
  149788. static vorbis_residue_template _res_16u_2[]={
  149789. {1,0, &_residue_44_hi_un,
  149790. &_huff_book__16u2__short,&_huff_book__16u2__short,
  149791. &_resbook_16u_2,&_resbook_16u_2},
  149792. {1,0, &_residue_44_hi_un,
  149793. &_huff_book__16u2__long,&_huff_book__16u2__long,
  149794. &_resbook_16u_2,&_resbook_16u_2}
  149795. };
  149796. static vorbis_mapping_template _mapres_template_16_uncoupled[3]={
  149797. { _map_nominal_u, _res_16u_0 }, /* 0 */
  149798. { _map_nominal_u, _res_16u_1 }, /* 1 */
  149799. { _map_nominal_u, _res_16u_2 }, /* 2 */
  149800. };
  149801. /********* End of inlined file: residue_16.h *********/
  149802. static int blocksize_16_short[3]={
  149803. 1024,512,512
  149804. };
  149805. static int blocksize_16_long[3]={
  149806. 1024,1024,1024
  149807. };
  149808. static int _floor_mapping_16_short[3]={
  149809. 9,3,3
  149810. };
  149811. static int _floor_mapping_16[3]={
  149812. 9,9,9
  149813. };
  149814. static double rate_mapping_16[4]={
  149815. 12000.,20000.,44000.,86000.
  149816. };
  149817. static double rate_mapping_16_uncoupled[4]={
  149818. 16000.,28000.,64000.,100000.
  149819. };
  149820. static double _global_mapping_16[4]={ 1., 2., 3., 4. };
  149821. static double quality_mapping_16[4]={ -.1,.05,.5,1. };
  149822. static double _psy_compand_16_mapping[4]={ 0., .8, 1., 1.};
  149823. ve_setup_data_template ve_setup_16_stereo={
  149824. 3,
  149825. rate_mapping_16,
  149826. quality_mapping_16,
  149827. 2,
  149828. 15000,
  149829. 19000,
  149830. blocksize_16_short,
  149831. blocksize_16_long,
  149832. _psy_tone_masteratt_16,
  149833. _psy_tone_0dB,
  149834. _psy_tone_suppress,
  149835. _vp_tonemask_adj_16,
  149836. _vp_tonemask_adj_16,
  149837. _vp_tonemask_adj_16,
  149838. _psy_noiseguards_8,
  149839. _psy_noisebias_16_impulse,
  149840. _psy_noisebias_16_short,
  149841. _psy_noisebias_16_short,
  149842. _psy_noisebias_16,
  149843. _psy_noise_suppress,
  149844. _psy_compand_8,
  149845. _psy_compand_16_mapping,
  149846. _psy_compand_16_mapping,
  149847. {_noise_start_16,_noise_start_16},
  149848. { _noise_part_16, _noise_part_16},
  149849. _noise_thresh_16,
  149850. _psy_ath_floater_16,
  149851. _psy_ath_abs_16,
  149852. _psy_lowpass_16,
  149853. _psy_global_44,
  149854. _global_mapping_16,
  149855. _psy_stereo_modes_16,
  149856. _floor_books,
  149857. _floor,
  149858. _floor_mapping_16_short,
  149859. _floor_mapping_16,
  149860. _mapres_template_16_stereo
  149861. };
  149862. ve_setup_data_template ve_setup_16_uncoupled={
  149863. 3,
  149864. rate_mapping_16_uncoupled,
  149865. quality_mapping_16,
  149866. -1,
  149867. 15000,
  149868. 19000,
  149869. blocksize_16_short,
  149870. blocksize_16_long,
  149871. _psy_tone_masteratt_16,
  149872. _psy_tone_0dB,
  149873. _psy_tone_suppress,
  149874. _vp_tonemask_adj_16,
  149875. _vp_tonemask_adj_16,
  149876. _vp_tonemask_adj_16,
  149877. _psy_noiseguards_8,
  149878. _psy_noisebias_16_impulse,
  149879. _psy_noisebias_16_short,
  149880. _psy_noisebias_16_short,
  149881. _psy_noisebias_16,
  149882. _psy_noise_suppress,
  149883. _psy_compand_8,
  149884. _psy_compand_16_mapping,
  149885. _psy_compand_16_mapping,
  149886. {_noise_start_16,_noise_start_16},
  149887. { _noise_part_16, _noise_part_16},
  149888. _noise_thresh_16,
  149889. _psy_ath_floater_16,
  149890. _psy_ath_abs_16,
  149891. _psy_lowpass_16,
  149892. _psy_global_44,
  149893. _global_mapping_16,
  149894. _psy_stereo_modes_16,
  149895. _floor_books,
  149896. _floor,
  149897. _floor_mapping_16_short,
  149898. _floor_mapping_16,
  149899. _mapres_template_16_uncoupled
  149900. };
  149901. /********* End of inlined file: setup_16.h *********/
  149902. /********* Start of inlined file: setup_22.h *********/
  149903. static double rate_mapping_22[4]={
  149904. 15000.,20000.,44000.,86000.
  149905. };
  149906. static double rate_mapping_22_uncoupled[4]={
  149907. 16000.,28000.,50000.,90000.
  149908. };
  149909. static double _psy_lowpass_22[4]={9.5,11.,30.,99.};
  149910. ve_setup_data_template ve_setup_22_stereo={
  149911. 3,
  149912. rate_mapping_22,
  149913. quality_mapping_16,
  149914. 2,
  149915. 19000,
  149916. 26000,
  149917. blocksize_16_short,
  149918. blocksize_16_long,
  149919. _psy_tone_masteratt_16,
  149920. _psy_tone_0dB,
  149921. _psy_tone_suppress,
  149922. _vp_tonemask_adj_16,
  149923. _vp_tonemask_adj_16,
  149924. _vp_tonemask_adj_16,
  149925. _psy_noiseguards_8,
  149926. _psy_noisebias_16_impulse,
  149927. _psy_noisebias_16_short,
  149928. _psy_noisebias_16_short,
  149929. _psy_noisebias_16,
  149930. _psy_noise_suppress,
  149931. _psy_compand_8,
  149932. _psy_compand_8_mapping,
  149933. _psy_compand_8_mapping,
  149934. {_noise_start_16,_noise_start_16},
  149935. { _noise_part_16, _noise_part_16},
  149936. _noise_thresh_16,
  149937. _psy_ath_floater_16,
  149938. _psy_ath_abs_16,
  149939. _psy_lowpass_22,
  149940. _psy_global_44,
  149941. _global_mapping_16,
  149942. _psy_stereo_modes_16,
  149943. _floor_books,
  149944. _floor,
  149945. _floor_mapping_16_short,
  149946. _floor_mapping_16,
  149947. _mapres_template_16_stereo
  149948. };
  149949. ve_setup_data_template ve_setup_22_uncoupled={
  149950. 3,
  149951. rate_mapping_22_uncoupled,
  149952. quality_mapping_16,
  149953. -1,
  149954. 19000,
  149955. 26000,
  149956. blocksize_16_short,
  149957. blocksize_16_long,
  149958. _psy_tone_masteratt_16,
  149959. _psy_tone_0dB,
  149960. _psy_tone_suppress,
  149961. _vp_tonemask_adj_16,
  149962. _vp_tonemask_adj_16,
  149963. _vp_tonemask_adj_16,
  149964. _psy_noiseguards_8,
  149965. _psy_noisebias_16_impulse,
  149966. _psy_noisebias_16_short,
  149967. _psy_noisebias_16_short,
  149968. _psy_noisebias_16,
  149969. _psy_noise_suppress,
  149970. _psy_compand_8,
  149971. _psy_compand_8_mapping,
  149972. _psy_compand_8_mapping,
  149973. {_noise_start_16,_noise_start_16},
  149974. { _noise_part_16, _noise_part_16},
  149975. _noise_thresh_16,
  149976. _psy_ath_floater_16,
  149977. _psy_ath_abs_16,
  149978. _psy_lowpass_22,
  149979. _psy_global_44,
  149980. _global_mapping_16,
  149981. _psy_stereo_modes_16,
  149982. _floor_books,
  149983. _floor,
  149984. _floor_mapping_16_short,
  149985. _floor_mapping_16,
  149986. _mapres_template_16_uncoupled
  149987. };
  149988. /********* End of inlined file: setup_22.h *********/
  149989. /********* Start of inlined file: setup_X.h *********/
  149990. static double rate_mapping_X[12]={
  149991. -1.,-1.,-1.,-1.,-1.,-1.,
  149992. -1.,-1.,-1.,-1.,-1.,-1.
  149993. };
  149994. ve_setup_data_template ve_setup_X_stereo={
  149995. 11,
  149996. rate_mapping_X,
  149997. quality_mapping_44,
  149998. 2,
  149999. 50000,
  150000. 200000,
  150001. blocksize_short_44,
  150002. blocksize_long_44,
  150003. _psy_tone_masteratt_44,
  150004. _psy_tone_0dB,
  150005. _psy_tone_suppress,
  150006. _vp_tonemask_adj_otherblock,
  150007. _vp_tonemask_adj_longblock,
  150008. _vp_tonemask_adj_otherblock,
  150009. _psy_noiseguards_44,
  150010. _psy_noisebias_impulse,
  150011. _psy_noisebias_padding,
  150012. _psy_noisebias_trans,
  150013. _psy_noisebias_long,
  150014. _psy_noise_suppress,
  150015. _psy_compand_44,
  150016. _psy_compand_short_mapping,
  150017. _psy_compand_long_mapping,
  150018. {_noise_start_short_44,_noise_start_long_44},
  150019. {_noise_part_short_44,_noise_part_long_44},
  150020. _noise_thresh_44,
  150021. _psy_ath_floater,
  150022. _psy_ath_abs,
  150023. _psy_lowpass_44,
  150024. _psy_global_44,
  150025. _global_mapping_44,
  150026. _psy_stereo_modes_44,
  150027. _floor_books,
  150028. _floor,
  150029. _floor_short_mapping_44,
  150030. _floor_long_mapping_44,
  150031. _mapres_template_44_stereo
  150032. };
  150033. ve_setup_data_template ve_setup_X_uncoupled={
  150034. 11,
  150035. rate_mapping_X,
  150036. quality_mapping_44,
  150037. -1,
  150038. 50000,
  150039. 200000,
  150040. blocksize_short_44,
  150041. blocksize_long_44,
  150042. _psy_tone_masteratt_44,
  150043. _psy_tone_0dB,
  150044. _psy_tone_suppress,
  150045. _vp_tonemask_adj_otherblock,
  150046. _vp_tonemask_adj_longblock,
  150047. _vp_tonemask_adj_otherblock,
  150048. _psy_noiseguards_44,
  150049. _psy_noisebias_impulse,
  150050. _psy_noisebias_padding,
  150051. _psy_noisebias_trans,
  150052. _psy_noisebias_long,
  150053. _psy_noise_suppress,
  150054. _psy_compand_44,
  150055. _psy_compand_short_mapping,
  150056. _psy_compand_long_mapping,
  150057. {_noise_start_short_44,_noise_start_long_44},
  150058. {_noise_part_short_44,_noise_part_long_44},
  150059. _noise_thresh_44,
  150060. _psy_ath_floater,
  150061. _psy_ath_abs,
  150062. _psy_lowpass_44,
  150063. _psy_global_44,
  150064. _global_mapping_44,
  150065. NULL,
  150066. _floor_books,
  150067. _floor,
  150068. _floor_short_mapping_44,
  150069. _floor_long_mapping_44,
  150070. _mapres_template_44_uncoupled
  150071. };
  150072. ve_setup_data_template ve_setup_XX_stereo={
  150073. 2,
  150074. rate_mapping_X,
  150075. quality_mapping_8,
  150076. 2,
  150077. 0,
  150078. 8000,
  150079. blocksize_8,
  150080. blocksize_8,
  150081. _psy_tone_masteratt_8,
  150082. _psy_tone_0dB,
  150083. _psy_tone_suppress,
  150084. _vp_tonemask_adj_8,
  150085. NULL,
  150086. _vp_tonemask_adj_8,
  150087. _psy_noiseguards_8,
  150088. _psy_noisebias_8,
  150089. _psy_noisebias_8,
  150090. NULL,
  150091. NULL,
  150092. _psy_noise_suppress,
  150093. _psy_compand_8,
  150094. _psy_compand_8_mapping,
  150095. NULL,
  150096. {_noise_start_8,_noise_start_8},
  150097. {_noise_part_8,_noise_part_8},
  150098. _noise_thresh_5only,
  150099. _psy_ath_floater_8,
  150100. _psy_ath_abs_8,
  150101. _psy_lowpass_8,
  150102. _psy_global_44,
  150103. _global_mapping_8,
  150104. _psy_stereo_modes_8,
  150105. _floor_books,
  150106. _floor,
  150107. _floor_mapping_8,
  150108. NULL,
  150109. _mapres_template_8_stereo
  150110. };
  150111. ve_setup_data_template ve_setup_XX_uncoupled={
  150112. 2,
  150113. rate_mapping_X,
  150114. quality_mapping_8,
  150115. -1,
  150116. 0,
  150117. 8000,
  150118. blocksize_8,
  150119. blocksize_8,
  150120. _psy_tone_masteratt_8,
  150121. _psy_tone_0dB,
  150122. _psy_tone_suppress,
  150123. _vp_tonemask_adj_8,
  150124. NULL,
  150125. _vp_tonemask_adj_8,
  150126. _psy_noiseguards_8,
  150127. _psy_noisebias_8,
  150128. _psy_noisebias_8,
  150129. NULL,
  150130. NULL,
  150131. _psy_noise_suppress,
  150132. _psy_compand_8,
  150133. _psy_compand_8_mapping,
  150134. NULL,
  150135. {_noise_start_8,_noise_start_8},
  150136. {_noise_part_8,_noise_part_8},
  150137. _noise_thresh_5only,
  150138. _psy_ath_floater_8,
  150139. _psy_ath_abs_8,
  150140. _psy_lowpass_8,
  150141. _psy_global_44,
  150142. _global_mapping_8,
  150143. _psy_stereo_modes_8,
  150144. _floor_books,
  150145. _floor,
  150146. _floor_mapping_8,
  150147. NULL,
  150148. _mapres_template_8_uncoupled
  150149. };
  150150. /********* End of inlined file: setup_X.h *********/
  150151. static ve_setup_data_template *setup_list[]={
  150152. &ve_setup_44_stereo,
  150153. &ve_setup_44_uncoupled,
  150154. &ve_setup_32_stereo,
  150155. &ve_setup_32_uncoupled,
  150156. &ve_setup_22_stereo,
  150157. &ve_setup_22_uncoupled,
  150158. &ve_setup_16_stereo,
  150159. &ve_setup_16_uncoupled,
  150160. &ve_setup_11_stereo,
  150161. &ve_setup_11_uncoupled,
  150162. &ve_setup_8_stereo,
  150163. &ve_setup_8_uncoupled,
  150164. &ve_setup_X_stereo,
  150165. &ve_setup_X_uncoupled,
  150166. &ve_setup_XX_stereo,
  150167. &ve_setup_XX_uncoupled,
  150168. 0
  150169. };
  150170. static int vorbis_encode_toplevel_setup(vorbis_info *vi,int ch,long rate){
  150171. if(vi && vi->codec_setup){
  150172. vi->version=0;
  150173. vi->channels=ch;
  150174. vi->rate=rate;
  150175. return(0);
  150176. }
  150177. return(OV_EINVAL);
  150178. }
  150179. static void vorbis_encode_floor_setup(vorbis_info *vi,double s,int block,
  150180. static_codebook ***books,
  150181. vorbis_info_floor1 *in,
  150182. int *x){
  150183. int i,k,is=s;
  150184. vorbis_info_floor1 *f=(vorbis_info_floor1*) _ogg_calloc(1,sizeof(*f));
  150185. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  150186. memcpy(f,in+x[is],sizeof(*f));
  150187. /* fill in the lowpass field, even if it's temporary */
  150188. f->n=ci->blocksizes[block]>>1;
  150189. /* books */
  150190. {
  150191. int partitions=f->partitions;
  150192. int maxclass=-1;
  150193. int maxbook=-1;
  150194. for(i=0;i<partitions;i++)
  150195. if(f->partitionclass[i]>maxclass)maxclass=f->partitionclass[i];
  150196. for(i=0;i<=maxclass;i++){
  150197. if(f->class_book[i]>maxbook)maxbook=f->class_book[i];
  150198. f->class_book[i]+=ci->books;
  150199. for(k=0;k<(1<<f->class_subs[i]);k++){
  150200. if(f->class_subbook[i][k]>maxbook)maxbook=f->class_subbook[i][k];
  150201. if(f->class_subbook[i][k]>=0)f->class_subbook[i][k]+=ci->books;
  150202. }
  150203. }
  150204. for(i=0;i<=maxbook;i++)
  150205. ci->book_param[ci->books++]=books[x[is]][i];
  150206. }
  150207. /* for now, we're only using floor 1 */
  150208. ci->floor_type[ci->floors]=1;
  150209. ci->floor_param[ci->floors]=f;
  150210. ci->floors++;
  150211. return;
  150212. }
  150213. static void vorbis_encode_global_psych_setup(vorbis_info *vi,double s,
  150214. vorbis_info_psy_global *in,
  150215. double *x){
  150216. int i,is=s;
  150217. double ds=s-is;
  150218. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  150219. vorbis_info_psy_global *g=&ci->psy_g_param;
  150220. memcpy(g,in+(int)x[is],sizeof(*g));
  150221. ds=x[is]*(1.-ds)+x[is+1]*ds;
  150222. is=(int)ds;
  150223. ds-=is;
  150224. if(ds==0 && is>0){
  150225. is--;
  150226. ds=1.;
  150227. }
  150228. /* interpolate the trigger threshholds */
  150229. for(i=0;i<4;i++){
  150230. g->preecho_thresh[i]=in[is].preecho_thresh[i]*(1.-ds)+in[is+1].preecho_thresh[i]*ds;
  150231. g->postecho_thresh[i]=in[is].postecho_thresh[i]*(1.-ds)+in[is+1].postecho_thresh[i]*ds;
  150232. }
  150233. g->ampmax_att_per_sec=ci->hi.amplitude_track_dBpersec;
  150234. return;
  150235. }
  150236. static void vorbis_encode_global_stereo(vorbis_info *vi,
  150237. highlevel_encode_setup *hi,
  150238. adj_stereo *p){
  150239. float s=hi->stereo_point_setting;
  150240. int i,is=s;
  150241. double ds=s-is;
  150242. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  150243. vorbis_info_psy_global *g=&ci->psy_g_param;
  150244. if(p){
  150245. memcpy(g->coupling_prepointamp,p[is].pre,sizeof(*p[is].pre)*PACKETBLOBS);
  150246. memcpy(g->coupling_postpointamp,p[is].post,sizeof(*p[is].post)*PACKETBLOBS);
  150247. if(hi->managed){
  150248. /* interpolate the kHz threshholds */
  150249. for(i=0;i<PACKETBLOBS;i++){
  150250. float kHz=p[is].kHz[i]*(1.-ds)+p[is+1].kHz[i]*ds;
  150251. g->coupling_pointlimit[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  150252. g->coupling_pointlimit[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  150253. g->coupling_pkHz[i]=kHz;
  150254. kHz=p[is].lowpasskHz[i]*(1.-ds)+p[is+1].lowpasskHz[i]*ds;
  150255. g->sliding_lowpass[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  150256. g->sliding_lowpass[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  150257. }
  150258. }else{
  150259. float kHz=p[is].kHz[PACKETBLOBS/2]*(1.-ds)+p[is+1].kHz[PACKETBLOBS/2]*ds;
  150260. for(i=0;i<PACKETBLOBS;i++){
  150261. g->coupling_pointlimit[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  150262. g->coupling_pointlimit[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  150263. g->coupling_pkHz[i]=kHz;
  150264. }
  150265. kHz=p[is].lowpasskHz[PACKETBLOBS/2]*(1.-ds)+p[is+1].lowpasskHz[PACKETBLOBS/2]*ds;
  150266. for(i=0;i<PACKETBLOBS;i++){
  150267. g->sliding_lowpass[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  150268. g->sliding_lowpass[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  150269. }
  150270. }
  150271. }else{
  150272. for(i=0;i<PACKETBLOBS;i++){
  150273. g->sliding_lowpass[0][i]=ci->blocksizes[0];
  150274. g->sliding_lowpass[1][i]=ci->blocksizes[1];
  150275. }
  150276. }
  150277. return;
  150278. }
  150279. static void vorbis_encode_psyset_setup(vorbis_info *vi,double s,
  150280. int *nn_start,
  150281. int *nn_partition,
  150282. double *nn_thresh,
  150283. int block){
  150284. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  150285. vorbis_info_psy *p=ci->psy_param[block];
  150286. highlevel_encode_setup *hi=&ci->hi;
  150287. int is=s;
  150288. if(block>=ci->psys)
  150289. ci->psys=block+1;
  150290. if(!p){
  150291. p=(vorbis_info_psy*)_ogg_calloc(1,sizeof(*p));
  150292. ci->psy_param[block]=p;
  150293. }
  150294. memcpy(p,&_psy_info_template,sizeof(*p));
  150295. p->blockflag=block>>1;
  150296. if(hi->noise_normalize_p){
  150297. p->normal_channel_p=1;
  150298. p->normal_point_p=1;
  150299. p->normal_start=nn_start[is];
  150300. p->normal_partition=nn_partition[is];
  150301. p->normal_thresh=nn_thresh[is];
  150302. }
  150303. return;
  150304. }
  150305. static void vorbis_encode_tonemask_setup(vorbis_info *vi,double s,int block,
  150306. att3 *att,
  150307. int *max,
  150308. vp_adjblock *in){
  150309. int i,is=s;
  150310. double ds=s-is;
  150311. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  150312. vorbis_info_psy *p=ci->psy_param[block];
  150313. /* 0 and 2 are only used by bitmanagement, but there's no harm to always
  150314. filling the values in here */
  150315. p->tone_masteratt[0]=att[is].att[0]*(1.-ds)+att[is+1].att[0]*ds;
  150316. p->tone_masteratt[1]=att[is].att[1]*(1.-ds)+att[is+1].att[1]*ds;
  150317. p->tone_masteratt[2]=att[is].att[2]*(1.-ds)+att[is+1].att[2]*ds;
  150318. p->tone_centerboost=att[is].boost*(1.-ds)+att[is+1].boost*ds;
  150319. p->tone_decay=att[is].decay*(1.-ds)+att[is+1].decay*ds;
  150320. p->max_curve_dB=max[is]*(1.-ds)+max[is+1]*ds;
  150321. for(i=0;i<P_BANDS;i++)
  150322. p->toneatt[i]=in[is].block[i]*(1.-ds)+in[is+1].block[i]*ds;
  150323. return;
  150324. }
  150325. static void vorbis_encode_compand_setup(vorbis_info *vi,double s,int block,
  150326. compandblock *in, double *x){
  150327. int i,is=s;
  150328. double ds=s-is;
  150329. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  150330. vorbis_info_psy *p=ci->psy_param[block];
  150331. ds=x[is]*(1.-ds)+x[is+1]*ds;
  150332. is=(int)ds;
  150333. ds-=is;
  150334. if(ds==0 && is>0){
  150335. is--;
  150336. ds=1.;
  150337. }
  150338. /* interpolate the compander settings */
  150339. for(i=0;i<NOISE_COMPAND_LEVELS;i++)
  150340. p->noisecompand[i]=in[is].data[i]*(1.-ds)+in[is+1].data[i]*ds;
  150341. return;
  150342. }
  150343. static void vorbis_encode_peak_setup(vorbis_info *vi,double s,int block,
  150344. int *suppress){
  150345. int is=s;
  150346. double ds=s-is;
  150347. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  150348. vorbis_info_psy *p=ci->psy_param[block];
  150349. p->tone_abs_limit=suppress[is]*(1.-ds)+suppress[is+1]*ds;
  150350. return;
  150351. }
  150352. static void vorbis_encode_noisebias_setup(vorbis_info *vi,double s,int block,
  150353. int *suppress,
  150354. noise3 *in,
  150355. noiseguard *guard,
  150356. double userbias){
  150357. int i,is=s,j;
  150358. double ds=s-is;
  150359. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  150360. vorbis_info_psy *p=ci->psy_param[block];
  150361. p->noisemaxsupp=suppress[is]*(1.-ds)+suppress[is+1]*ds;
  150362. p->noisewindowlomin=guard[block].lo;
  150363. p->noisewindowhimin=guard[block].hi;
  150364. p->noisewindowfixed=guard[block].fixed;
  150365. for(j=0;j<P_NOISECURVES;j++)
  150366. for(i=0;i<P_BANDS;i++)
  150367. p->noiseoff[j][i]=in[is].data[j][i]*(1.-ds)+in[is+1].data[j][i]*ds;
  150368. /* impulse blocks may take a user specified bias to boost the
  150369. nominal/high noise encoding depth */
  150370. for(j=0;j<P_NOISECURVES;j++){
  150371. float min=p->noiseoff[j][0]+6; /* the lowest it can go */
  150372. for(i=0;i<P_BANDS;i++){
  150373. p->noiseoff[j][i]+=userbias;
  150374. if(p->noiseoff[j][i]<min)p->noiseoff[j][i]=min;
  150375. }
  150376. }
  150377. return;
  150378. }
  150379. static void vorbis_encode_ath_setup(vorbis_info *vi,int block){
  150380. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  150381. vorbis_info_psy *p=ci->psy_param[block];
  150382. p->ath_adjatt=ci->hi.ath_floating_dB;
  150383. p->ath_maxatt=ci->hi.ath_absolute_dB;
  150384. return;
  150385. }
  150386. static int book_dup_or_new(codec_setup_info *ci,static_codebook *book){
  150387. int i;
  150388. for(i=0;i<ci->books;i++)
  150389. if(ci->book_param[i]==book)return(i);
  150390. return(ci->books++);
  150391. }
  150392. static void vorbis_encode_blocksize_setup(vorbis_info *vi,double s,
  150393. int *shortb,int *longb){
  150394. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  150395. int is=s;
  150396. int blockshort=shortb[is];
  150397. int blocklong=longb[is];
  150398. ci->blocksizes[0]=blockshort;
  150399. ci->blocksizes[1]=blocklong;
  150400. }
  150401. static void vorbis_encode_residue_setup(vorbis_info *vi,
  150402. int number, int block,
  150403. vorbis_residue_template *res){
  150404. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  150405. int i,n;
  150406. vorbis_info_residue0 *r=(vorbis_info_residue0*)(ci->residue_param[number]=
  150407. (vorbis_info_residue0*)_ogg_malloc(sizeof(*r)));
  150408. memcpy(r,res->res,sizeof(*r));
  150409. if(ci->residues<=number)ci->residues=number+1;
  150410. switch(ci->blocksizes[block]){
  150411. case 64:case 128:case 256:
  150412. r->grouping=16;
  150413. break;
  150414. default:
  150415. r->grouping=32;
  150416. break;
  150417. }
  150418. ci->residue_type[number]=res->res_type;
  150419. /* to be adjusted by lowpass/pointlimit later */
  150420. n=r->end=ci->blocksizes[block]>>1;
  150421. if(res->res_type==2)
  150422. n=r->end*=vi->channels;
  150423. /* fill in all the books */
  150424. {
  150425. int booklist=0,k;
  150426. if(ci->hi.managed){
  150427. for(i=0;i<r->partitions;i++)
  150428. for(k=0;k<3;k++)
  150429. if(res->books_base_managed->books[i][k])
  150430. r->secondstages[i]|=(1<<k);
  150431. r->groupbook=book_dup_or_new(ci,res->book_aux_managed);
  150432. ci->book_param[r->groupbook]=res->book_aux_managed;
  150433. for(i=0;i<r->partitions;i++){
  150434. for(k=0;k<3;k++){
  150435. if(res->books_base_managed->books[i][k]){
  150436. int bookid=book_dup_or_new(ci,res->books_base_managed->books[i][k]);
  150437. r->booklist[booklist++]=bookid;
  150438. ci->book_param[bookid]=res->books_base_managed->books[i][k];
  150439. }
  150440. }
  150441. }
  150442. }else{
  150443. for(i=0;i<r->partitions;i++)
  150444. for(k=0;k<3;k++)
  150445. if(res->books_base->books[i][k])
  150446. r->secondstages[i]|=(1<<k);
  150447. r->groupbook=book_dup_or_new(ci,res->book_aux);
  150448. ci->book_param[r->groupbook]=res->book_aux;
  150449. for(i=0;i<r->partitions;i++){
  150450. for(k=0;k<3;k++){
  150451. if(res->books_base->books[i][k]){
  150452. int bookid=book_dup_or_new(ci,res->books_base->books[i][k]);
  150453. r->booklist[booklist++]=bookid;
  150454. ci->book_param[bookid]=res->books_base->books[i][k];
  150455. }
  150456. }
  150457. }
  150458. }
  150459. }
  150460. /* lowpass setup/pointlimit */
  150461. {
  150462. double freq=ci->hi.lowpass_kHz*1000.;
  150463. vorbis_info_floor1 *f=(vorbis_info_floor1*)ci->floor_param[block]; /* by convention */
  150464. double nyq=vi->rate/2.;
  150465. long blocksize=ci->blocksizes[block]>>1;
  150466. /* lowpass needs to be set in the floor and the residue. */
  150467. if(freq>nyq)freq=nyq;
  150468. /* in the floor, the granularity can be very fine; it doesn't alter
  150469. the encoding structure, only the samples used to fit the floor
  150470. approximation */
  150471. f->n=freq/nyq*blocksize;
  150472. /* this res may by limited by the maximum pointlimit of the mode,
  150473. not the lowpass. the floor is always lowpass limited. */
  150474. if(res->limit_type){
  150475. if(ci->hi.managed)
  150476. freq=ci->psy_g_param.coupling_pkHz[PACKETBLOBS-1]*1000.;
  150477. else
  150478. freq=ci->psy_g_param.coupling_pkHz[PACKETBLOBS/2]*1000.;
  150479. if(freq>nyq)freq=nyq;
  150480. }
  150481. /* in the residue, we're constrained, physically, by partition
  150482. boundaries. We still lowpass 'wherever', but we have to round up
  150483. here to next boundary, or the vorbis spec will round it *down* to
  150484. previous boundary in encode/decode */
  150485. if(ci->residue_type[block]==2)
  150486. r->end=(int)((freq/nyq*blocksize*2)/r->grouping+.9)* /* round up only if we're well past */
  150487. r->grouping;
  150488. else
  150489. r->end=(int)((freq/nyq*blocksize)/r->grouping+.9)* /* round up only if we're well past */
  150490. r->grouping;
  150491. }
  150492. }
  150493. /* we assume two maps in this encoder */
  150494. static void vorbis_encode_map_n_res_setup(vorbis_info *vi,double s,
  150495. vorbis_mapping_template *maps){
  150496. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  150497. int i,j,is=s,modes=2;
  150498. vorbis_info_mapping0 *map=maps[is].map;
  150499. vorbis_info_mode *mode=_mode_template;
  150500. vorbis_residue_template *res=maps[is].res;
  150501. if(ci->blocksizes[0]==ci->blocksizes[1])modes=1;
  150502. for(i=0;i<modes;i++){
  150503. ci->map_param[i]=_ogg_calloc(1,sizeof(*map));
  150504. ci->mode_param[i]=(vorbis_info_mode*)_ogg_calloc(1,sizeof(*mode));
  150505. memcpy(ci->mode_param[i],mode+i,sizeof(*_mode_template));
  150506. if(i>=ci->modes)ci->modes=i+1;
  150507. ci->map_type[i]=0;
  150508. memcpy(ci->map_param[i],map+i,sizeof(*map));
  150509. if(i>=ci->maps)ci->maps=i+1;
  150510. for(j=0;j<map[i].submaps;j++)
  150511. vorbis_encode_residue_setup(vi,map[i].residuesubmap[j],i
  150512. ,res+map[i].residuesubmap[j]);
  150513. }
  150514. }
  150515. static double setting_to_approx_bitrate(vorbis_info *vi){
  150516. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  150517. highlevel_encode_setup *hi=&ci->hi;
  150518. ve_setup_data_template *setup=(ve_setup_data_template *)hi->setup;
  150519. int is=hi->base_setting;
  150520. double ds=hi->base_setting-is;
  150521. int ch=vi->channels;
  150522. double *r=setup->rate_mapping;
  150523. if(r==NULL)
  150524. return(-1);
  150525. return((r[is]*(1.-ds)+r[is+1]*ds)*ch);
  150526. }
  150527. static void get_setup_template(vorbis_info *vi,
  150528. long ch,long srate,
  150529. double req,int q_or_bitrate){
  150530. int i=0,j;
  150531. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  150532. highlevel_encode_setup *hi=&ci->hi;
  150533. if(q_or_bitrate)req/=ch;
  150534. while(setup_list[i]){
  150535. if(setup_list[i]->coupling_restriction==-1 ||
  150536. setup_list[i]->coupling_restriction==ch){
  150537. if(srate>=setup_list[i]->samplerate_min_restriction &&
  150538. srate<=setup_list[i]->samplerate_max_restriction){
  150539. int mappings=setup_list[i]->mappings;
  150540. double *map=(q_or_bitrate?
  150541. setup_list[i]->rate_mapping:
  150542. setup_list[i]->quality_mapping);
  150543. /* the template matches. Does the requested quality mode
  150544. fall within this template's modes? */
  150545. if(req<map[0]){++i;continue;}
  150546. if(req>map[setup_list[i]->mappings]){++i;continue;}
  150547. for(j=0;j<mappings;j++)
  150548. if(req>=map[j] && req<map[j+1])break;
  150549. /* an all-points match */
  150550. hi->setup=setup_list[i];
  150551. if(j==mappings)
  150552. hi->base_setting=j-.001;
  150553. else{
  150554. float low=map[j];
  150555. float high=map[j+1];
  150556. float del=(req-low)/(high-low);
  150557. hi->base_setting=j+del;
  150558. }
  150559. return;
  150560. }
  150561. }
  150562. i++;
  150563. }
  150564. hi->setup=NULL;
  150565. }
  150566. /* encoders will need to use vorbis_info_init beforehand and call
  150567. vorbis_info clear when all done */
  150568. /* two interfaces; this, more detailed one, and later a convenience
  150569. layer on top */
  150570. /* the final setup call */
  150571. int vorbis_encode_setup_init(vorbis_info *vi){
  150572. int i0=0,singleblock=0;
  150573. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  150574. ve_setup_data_template *setup=NULL;
  150575. highlevel_encode_setup *hi=&ci->hi;
  150576. if(ci==NULL)return(OV_EINVAL);
  150577. if(!hi->impulse_block_p)i0=1;
  150578. /* too low/high an ATH floater is nonsensical, but doesn't break anything */
  150579. if(hi->ath_floating_dB>-80)hi->ath_floating_dB=-80;
  150580. if(hi->ath_floating_dB<-200)hi->ath_floating_dB=-200;
  150581. /* again, bound this to avoid the app shooting itself int he foot
  150582. too badly */
  150583. if(hi->amplitude_track_dBpersec>0.)hi->amplitude_track_dBpersec=0.;
  150584. if(hi->amplitude_track_dBpersec<-99999.)hi->amplitude_track_dBpersec=-99999.;
  150585. /* get the appropriate setup template; matches the fetch in previous
  150586. stages */
  150587. setup=(ve_setup_data_template *)hi->setup;
  150588. if(setup==NULL)return(OV_EINVAL);
  150589. hi->set_in_stone=1;
  150590. /* choose block sizes from configured sizes as well as paying
  150591. attention to long_block_p and short_block_p. If the configured
  150592. short and long blocks are the same length, we set long_block_p
  150593. and unset short_block_p */
  150594. vorbis_encode_blocksize_setup(vi,hi->base_setting,
  150595. setup->blocksize_short,
  150596. setup->blocksize_long);
  150597. if(ci->blocksizes[0]==ci->blocksizes[1])singleblock=1;
  150598. /* floor setup; choose proper floor params. Allocated on the floor
  150599. stack in order; if we alloc only long floor, it's 0 */
  150600. vorbis_encode_floor_setup(vi,hi->short_setting,0,
  150601. setup->floor_books,
  150602. setup->floor_params,
  150603. setup->floor_short_mapping);
  150604. if(!singleblock)
  150605. vorbis_encode_floor_setup(vi,hi->long_setting,1,
  150606. setup->floor_books,
  150607. setup->floor_params,
  150608. setup->floor_long_mapping);
  150609. /* setup of [mostly] short block detection and stereo*/
  150610. vorbis_encode_global_psych_setup(vi,hi->trigger_setting,
  150611. setup->global_params,
  150612. setup->global_mapping);
  150613. vorbis_encode_global_stereo(vi,hi,setup->stereo_modes);
  150614. /* basic psych setup and noise normalization */
  150615. vorbis_encode_psyset_setup(vi,hi->short_setting,
  150616. setup->psy_noise_normal_start[0],
  150617. setup->psy_noise_normal_partition[0],
  150618. setup->psy_noise_normal_thresh,
  150619. 0);
  150620. vorbis_encode_psyset_setup(vi,hi->short_setting,
  150621. setup->psy_noise_normal_start[0],
  150622. setup->psy_noise_normal_partition[0],
  150623. setup->psy_noise_normal_thresh,
  150624. 1);
  150625. if(!singleblock){
  150626. vorbis_encode_psyset_setup(vi,hi->long_setting,
  150627. setup->psy_noise_normal_start[1],
  150628. setup->psy_noise_normal_partition[1],
  150629. setup->psy_noise_normal_thresh,
  150630. 2);
  150631. vorbis_encode_psyset_setup(vi,hi->long_setting,
  150632. setup->psy_noise_normal_start[1],
  150633. setup->psy_noise_normal_partition[1],
  150634. setup->psy_noise_normal_thresh,
  150635. 3);
  150636. }
  150637. /* tone masking setup */
  150638. vorbis_encode_tonemask_setup(vi,hi->block[i0].tone_mask_setting,0,
  150639. setup->psy_tone_masteratt,
  150640. setup->psy_tone_0dB,
  150641. setup->psy_tone_adj_impulse);
  150642. vorbis_encode_tonemask_setup(vi,hi->block[1].tone_mask_setting,1,
  150643. setup->psy_tone_masteratt,
  150644. setup->psy_tone_0dB,
  150645. setup->psy_tone_adj_other);
  150646. if(!singleblock){
  150647. vorbis_encode_tonemask_setup(vi,hi->block[2].tone_mask_setting,2,
  150648. setup->psy_tone_masteratt,
  150649. setup->psy_tone_0dB,
  150650. setup->psy_tone_adj_other);
  150651. vorbis_encode_tonemask_setup(vi,hi->block[3].tone_mask_setting,3,
  150652. setup->psy_tone_masteratt,
  150653. setup->psy_tone_0dB,
  150654. setup->psy_tone_adj_long);
  150655. }
  150656. /* noise companding setup */
  150657. vorbis_encode_compand_setup(vi,hi->block[i0].noise_compand_setting,0,
  150658. setup->psy_noise_compand,
  150659. setup->psy_noise_compand_short_mapping);
  150660. vorbis_encode_compand_setup(vi,hi->block[1].noise_compand_setting,1,
  150661. setup->psy_noise_compand,
  150662. setup->psy_noise_compand_short_mapping);
  150663. if(!singleblock){
  150664. vorbis_encode_compand_setup(vi,hi->block[2].noise_compand_setting,2,
  150665. setup->psy_noise_compand,
  150666. setup->psy_noise_compand_long_mapping);
  150667. vorbis_encode_compand_setup(vi,hi->block[3].noise_compand_setting,3,
  150668. setup->psy_noise_compand,
  150669. setup->psy_noise_compand_long_mapping);
  150670. }
  150671. /* peak guarding setup */
  150672. vorbis_encode_peak_setup(vi,hi->block[i0].tone_peaklimit_setting,0,
  150673. setup->psy_tone_dBsuppress);
  150674. vorbis_encode_peak_setup(vi,hi->block[1].tone_peaklimit_setting,1,
  150675. setup->psy_tone_dBsuppress);
  150676. if(!singleblock){
  150677. vorbis_encode_peak_setup(vi,hi->block[2].tone_peaklimit_setting,2,
  150678. setup->psy_tone_dBsuppress);
  150679. vorbis_encode_peak_setup(vi,hi->block[3].tone_peaklimit_setting,3,
  150680. setup->psy_tone_dBsuppress);
  150681. }
  150682. /* noise bias setup */
  150683. vorbis_encode_noisebias_setup(vi,hi->block[i0].noise_bias_setting,0,
  150684. setup->psy_noise_dBsuppress,
  150685. setup->psy_noise_bias_impulse,
  150686. setup->psy_noiseguards,
  150687. (i0==0?hi->impulse_noisetune:0.));
  150688. vorbis_encode_noisebias_setup(vi,hi->block[1].noise_bias_setting,1,
  150689. setup->psy_noise_dBsuppress,
  150690. setup->psy_noise_bias_padding,
  150691. setup->psy_noiseguards,0.);
  150692. if(!singleblock){
  150693. vorbis_encode_noisebias_setup(vi,hi->block[2].noise_bias_setting,2,
  150694. setup->psy_noise_dBsuppress,
  150695. setup->psy_noise_bias_trans,
  150696. setup->psy_noiseguards,0.);
  150697. vorbis_encode_noisebias_setup(vi,hi->block[3].noise_bias_setting,3,
  150698. setup->psy_noise_dBsuppress,
  150699. setup->psy_noise_bias_long,
  150700. setup->psy_noiseguards,0.);
  150701. }
  150702. vorbis_encode_ath_setup(vi,0);
  150703. vorbis_encode_ath_setup(vi,1);
  150704. if(!singleblock){
  150705. vorbis_encode_ath_setup(vi,2);
  150706. vorbis_encode_ath_setup(vi,3);
  150707. }
  150708. vorbis_encode_map_n_res_setup(vi,hi->base_setting,setup->maps);
  150709. /* set bitrate readonlies and management */
  150710. if(hi->bitrate_av>0)
  150711. vi->bitrate_nominal=hi->bitrate_av;
  150712. else{
  150713. vi->bitrate_nominal=setting_to_approx_bitrate(vi);
  150714. }
  150715. vi->bitrate_lower=hi->bitrate_min;
  150716. vi->bitrate_upper=hi->bitrate_max;
  150717. if(hi->bitrate_av)
  150718. vi->bitrate_window=(double)hi->bitrate_reservoir/hi->bitrate_av;
  150719. else
  150720. vi->bitrate_window=0.;
  150721. if(hi->managed){
  150722. ci->bi.avg_rate=hi->bitrate_av;
  150723. ci->bi.min_rate=hi->bitrate_min;
  150724. ci->bi.max_rate=hi->bitrate_max;
  150725. ci->bi.reservoir_bits=hi->bitrate_reservoir;
  150726. ci->bi.reservoir_bias=
  150727. hi->bitrate_reservoir_bias;
  150728. ci->bi.slew_damp=hi->bitrate_av_damp;
  150729. }
  150730. return(0);
  150731. }
  150732. static int vorbis_encode_setup_setting(vorbis_info *vi,
  150733. long channels,
  150734. long rate){
  150735. int ret=0,i,is;
  150736. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  150737. highlevel_encode_setup *hi=&ci->hi;
  150738. ve_setup_data_template *setup=(ve_setup_data_template*) hi->setup;
  150739. double ds;
  150740. ret=vorbis_encode_toplevel_setup(vi,channels,rate);
  150741. if(ret)return(ret);
  150742. is=hi->base_setting;
  150743. ds=hi->base_setting-is;
  150744. hi->short_setting=hi->base_setting;
  150745. hi->long_setting=hi->base_setting;
  150746. hi->managed=0;
  150747. hi->impulse_block_p=1;
  150748. hi->noise_normalize_p=1;
  150749. hi->stereo_point_setting=hi->base_setting;
  150750. hi->lowpass_kHz=
  150751. setup->psy_lowpass[is]*(1.-ds)+setup->psy_lowpass[is+1]*ds;
  150752. hi->ath_floating_dB=setup->psy_ath_float[is]*(1.-ds)+
  150753. setup->psy_ath_float[is+1]*ds;
  150754. hi->ath_absolute_dB=setup->psy_ath_abs[is]*(1.-ds)+
  150755. setup->psy_ath_abs[is+1]*ds;
  150756. hi->amplitude_track_dBpersec=-6.;
  150757. hi->trigger_setting=hi->base_setting;
  150758. for(i=0;i<4;i++){
  150759. hi->block[i].tone_mask_setting=hi->base_setting;
  150760. hi->block[i].tone_peaklimit_setting=hi->base_setting;
  150761. hi->block[i].noise_bias_setting=hi->base_setting;
  150762. hi->block[i].noise_compand_setting=hi->base_setting;
  150763. }
  150764. return(ret);
  150765. }
  150766. int vorbis_encode_setup_vbr(vorbis_info *vi,
  150767. long channels,
  150768. long rate,
  150769. float quality){
  150770. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  150771. highlevel_encode_setup *hi=&ci->hi;
  150772. quality+=.0000001;
  150773. if(quality>=1.)quality=.9999;
  150774. get_setup_template(vi,channels,rate,quality,0);
  150775. if(!hi->setup)return OV_EIMPL;
  150776. return vorbis_encode_setup_setting(vi,channels,rate);
  150777. }
  150778. int vorbis_encode_init_vbr(vorbis_info *vi,
  150779. long channels,
  150780. long rate,
  150781. float base_quality /* 0. to 1. */
  150782. ){
  150783. int ret=0;
  150784. ret=vorbis_encode_setup_vbr(vi,channels,rate,base_quality);
  150785. if(ret){
  150786. vorbis_info_clear(vi);
  150787. return ret;
  150788. }
  150789. ret=vorbis_encode_setup_init(vi);
  150790. if(ret)
  150791. vorbis_info_clear(vi);
  150792. return(ret);
  150793. }
  150794. int vorbis_encode_setup_managed(vorbis_info *vi,
  150795. long channels,
  150796. long rate,
  150797. long max_bitrate,
  150798. long nominal_bitrate,
  150799. long min_bitrate){
  150800. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  150801. highlevel_encode_setup *hi=&ci->hi;
  150802. double tnominal=nominal_bitrate;
  150803. int ret=0;
  150804. if(nominal_bitrate<=0.){
  150805. if(max_bitrate>0.){
  150806. if(min_bitrate>0.)
  150807. nominal_bitrate=(max_bitrate+min_bitrate)*.5;
  150808. else
  150809. nominal_bitrate=max_bitrate*.875;
  150810. }else{
  150811. if(min_bitrate>0.){
  150812. nominal_bitrate=min_bitrate;
  150813. }else{
  150814. return(OV_EINVAL);
  150815. }
  150816. }
  150817. }
  150818. get_setup_template(vi,channels,rate,nominal_bitrate,1);
  150819. if(!hi->setup)return OV_EIMPL;
  150820. ret=vorbis_encode_setup_setting(vi,channels,rate);
  150821. if(ret){
  150822. vorbis_info_clear(vi);
  150823. return ret;
  150824. }
  150825. /* initialize management with sane defaults */
  150826. hi->managed=1;
  150827. hi->bitrate_min=min_bitrate;
  150828. hi->bitrate_max=max_bitrate;
  150829. hi->bitrate_av=tnominal;
  150830. hi->bitrate_av_damp=1.5f; /* full range in no less than 1.5 second */
  150831. hi->bitrate_reservoir=nominal_bitrate*2;
  150832. hi->bitrate_reservoir_bias=.1; /* bias toward hoarding bits */
  150833. return(ret);
  150834. }
  150835. int vorbis_encode_init(vorbis_info *vi,
  150836. long channels,
  150837. long rate,
  150838. long max_bitrate,
  150839. long nominal_bitrate,
  150840. long min_bitrate){
  150841. int ret=vorbis_encode_setup_managed(vi,channels,rate,
  150842. max_bitrate,
  150843. nominal_bitrate,
  150844. min_bitrate);
  150845. if(ret){
  150846. vorbis_info_clear(vi);
  150847. return(ret);
  150848. }
  150849. ret=vorbis_encode_setup_init(vi);
  150850. if(ret)
  150851. vorbis_info_clear(vi);
  150852. return(ret);
  150853. }
  150854. int vorbis_encode_ctl(vorbis_info *vi,int number,void *arg){
  150855. if(vi){
  150856. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  150857. highlevel_encode_setup *hi=&ci->hi;
  150858. int setp=(number&0xf); /* a read request has a low nibble of 0 */
  150859. if(setp && hi->set_in_stone)return(OV_EINVAL);
  150860. switch(number){
  150861. /* now deprecated *****************/
  150862. case OV_ECTL_RATEMANAGE_GET:
  150863. {
  150864. struct ovectl_ratemanage_arg *ai=
  150865. (struct ovectl_ratemanage_arg *)arg;
  150866. ai->management_active=hi->managed;
  150867. ai->bitrate_hard_window=ai->bitrate_av_window=
  150868. (double)hi->bitrate_reservoir/vi->rate;
  150869. ai->bitrate_av_window_center=1.;
  150870. ai->bitrate_hard_min=hi->bitrate_min;
  150871. ai->bitrate_hard_max=hi->bitrate_max;
  150872. ai->bitrate_av_lo=hi->bitrate_av;
  150873. ai->bitrate_av_hi=hi->bitrate_av;
  150874. }
  150875. return(0);
  150876. /* now deprecated *****************/
  150877. case OV_ECTL_RATEMANAGE_SET:
  150878. {
  150879. struct ovectl_ratemanage_arg *ai=
  150880. (struct ovectl_ratemanage_arg *)arg;
  150881. if(ai==NULL){
  150882. hi->managed=0;
  150883. }else{
  150884. hi->managed=ai->management_active;
  150885. vorbis_encode_ctl(vi,OV_ECTL_RATEMANAGE_AVG,arg);
  150886. vorbis_encode_ctl(vi,OV_ECTL_RATEMANAGE_HARD,arg);
  150887. }
  150888. }
  150889. return 0;
  150890. /* now deprecated *****************/
  150891. case OV_ECTL_RATEMANAGE_AVG:
  150892. {
  150893. struct ovectl_ratemanage_arg *ai=
  150894. (struct ovectl_ratemanage_arg *)arg;
  150895. if(ai==NULL){
  150896. hi->bitrate_av=0;
  150897. }else{
  150898. hi->bitrate_av=(ai->bitrate_av_lo+ai->bitrate_av_hi)*.5;
  150899. }
  150900. }
  150901. return(0);
  150902. /* now deprecated *****************/
  150903. case OV_ECTL_RATEMANAGE_HARD:
  150904. {
  150905. struct ovectl_ratemanage_arg *ai=
  150906. (struct ovectl_ratemanage_arg *)arg;
  150907. if(ai==NULL){
  150908. hi->bitrate_min=0;
  150909. hi->bitrate_max=0;
  150910. }else{
  150911. hi->bitrate_min=ai->bitrate_hard_min;
  150912. hi->bitrate_max=ai->bitrate_hard_max;
  150913. hi->bitrate_reservoir=ai->bitrate_hard_window*
  150914. (hi->bitrate_max+hi->bitrate_min)*.5;
  150915. }
  150916. if(hi->bitrate_reservoir<128.)
  150917. hi->bitrate_reservoir=128.;
  150918. }
  150919. return(0);
  150920. /* replacement ratemanage interface */
  150921. case OV_ECTL_RATEMANAGE2_GET:
  150922. {
  150923. struct ovectl_ratemanage2_arg *ai=
  150924. (struct ovectl_ratemanage2_arg *)arg;
  150925. if(ai==NULL)return OV_EINVAL;
  150926. ai->management_active=hi->managed;
  150927. ai->bitrate_limit_min_kbps=hi->bitrate_min/1000;
  150928. ai->bitrate_limit_max_kbps=hi->bitrate_max/1000;
  150929. ai->bitrate_average_kbps=hi->bitrate_av/1000;
  150930. ai->bitrate_average_damping=hi->bitrate_av_damp;
  150931. ai->bitrate_limit_reservoir_bits=hi->bitrate_reservoir;
  150932. ai->bitrate_limit_reservoir_bias=hi->bitrate_reservoir_bias;
  150933. }
  150934. return (0);
  150935. case OV_ECTL_RATEMANAGE2_SET:
  150936. {
  150937. struct ovectl_ratemanage2_arg *ai=
  150938. (struct ovectl_ratemanage2_arg *)arg;
  150939. if(ai==NULL){
  150940. hi->managed=0;
  150941. }else{
  150942. /* sanity check; only catch invariant violations */
  150943. if(ai->bitrate_limit_min_kbps>0 &&
  150944. ai->bitrate_average_kbps>0 &&
  150945. ai->bitrate_limit_min_kbps>ai->bitrate_average_kbps)
  150946. return OV_EINVAL;
  150947. if(ai->bitrate_limit_max_kbps>0 &&
  150948. ai->bitrate_average_kbps>0 &&
  150949. ai->bitrate_limit_max_kbps<ai->bitrate_average_kbps)
  150950. return OV_EINVAL;
  150951. if(ai->bitrate_limit_min_kbps>0 &&
  150952. ai->bitrate_limit_max_kbps>0 &&
  150953. ai->bitrate_limit_min_kbps>ai->bitrate_limit_max_kbps)
  150954. return OV_EINVAL;
  150955. if(ai->bitrate_average_damping <= 0.)
  150956. return OV_EINVAL;
  150957. if(ai->bitrate_limit_reservoir_bits < 0)
  150958. return OV_EINVAL;
  150959. if(ai->bitrate_limit_reservoir_bias < 0.)
  150960. return OV_EINVAL;
  150961. if(ai->bitrate_limit_reservoir_bias > 1.)
  150962. return OV_EINVAL;
  150963. hi->managed=ai->management_active;
  150964. hi->bitrate_min=ai->bitrate_limit_min_kbps * 1000;
  150965. hi->bitrate_max=ai->bitrate_limit_max_kbps * 1000;
  150966. hi->bitrate_av=ai->bitrate_average_kbps * 1000;
  150967. hi->bitrate_av_damp=ai->bitrate_average_damping;
  150968. hi->bitrate_reservoir=ai->bitrate_limit_reservoir_bits;
  150969. hi->bitrate_reservoir_bias=ai->bitrate_limit_reservoir_bias;
  150970. }
  150971. }
  150972. return 0;
  150973. case OV_ECTL_LOWPASS_GET:
  150974. {
  150975. double *farg=(double *)arg;
  150976. *farg=hi->lowpass_kHz;
  150977. }
  150978. return(0);
  150979. case OV_ECTL_LOWPASS_SET:
  150980. {
  150981. double *farg=(double *)arg;
  150982. hi->lowpass_kHz=*farg;
  150983. if(hi->lowpass_kHz<2.)hi->lowpass_kHz=2.;
  150984. if(hi->lowpass_kHz>99.)hi->lowpass_kHz=99.;
  150985. }
  150986. return(0);
  150987. case OV_ECTL_IBLOCK_GET:
  150988. {
  150989. double *farg=(double *)arg;
  150990. *farg=hi->impulse_noisetune;
  150991. }
  150992. return(0);
  150993. case OV_ECTL_IBLOCK_SET:
  150994. {
  150995. double *farg=(double *)arg;
  150996. hi->impulse_noisetune=*farg;
  150997. if(hi->impulse_noisetune>0.)hi->impulse_noisetune=0.;
  150998. if(hi->impulse_noisetune<-15.)hi->impulse_noisetune=-15.;
  150999. }
  151000. return(0);
  151001. }
  151002. return(OV_EIMPL);
  151003. }
  151004. return(OV_EINVAL);
  151005. }
  151006. #endif
  151007. /********* End of inlined file: vorbisenc.c *********/
  151008. /********* Start of inlined file: vorbisfile.c *********/
  151009. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  151010. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  151011. // tasks..
  151012. #ifdef _MSC_VER
  151013. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  151014. #endif
  151015. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  151016. #if JUCE_USE_OGGVORBIS
  151017. #include <stdlib.h>
  151018. #include <stdio.h>
  151019. #include <errno.h>
  151020. #include <string.h>
  151021. #include <math.h>
  151022. /* A 'chained bitstream' is a Vorbis bitstream that contains more than
  151023. one logical bitstream arranged end to end (the only form of Ogg
  151024. multiplexing allowed in a Vorbis bitstream; grouping [parallel
  151025. multiplexing] is not allowed in Vorbis) */
  151026. /* A Vorbis file can be played beginning to end (streamed) without
  151027. worrying ahead of time about chaining (see decoder_example.c). If
  151028. we have the whole file, however, and want random access
  151029. (seeking/scrubbing) or desire to know the total length/time of a
  151030. file, we need to account for the possibility of chaining. */
  151031. /* We can handle things a number of ways; we can determine the entire
  151032. bitstream structure right off the bat, or find pieces on demand.
  151033. This example determines and caches structure for the entire
  151034. bitstream, but builds a virtual decoder on the fly when moving
  151035. between links in the chain. */
  151036. /* There are also different ways to implement seeking. Enough
  151037. information exists in an Ogg bitstream to seek to
  151038. sample-granularity positions in the output. Or, one can seek by
  151039. picking some portion of the stream roughly in the desired area if
  151040. we only want coarse navigation through the stream. */
  151041. /*************************************************************************
  151042. * Many, many internal helpers. The intention is not to be confusing;
  151043. * rampant duplication and monolithic function implementation would be
  151044. * harder to understand anyway. The high level functions are last. Begin
  151045. * grokking near the end of the file */
  151046. /* read a little more data from the file/pipe into the ogg_sync framer
  151047. */
  151048. #define CHUNKSIZE 8500 /* a shade over 8k; anyone using pages well
  151049. over 8k gets what they deserve */
  151050. static long _get_data(OggVorbis_File *vf){
  151051. errno=0;
  151052. if(vf->datasource){
  151053. char *buffer=ogg_sync_buffer(&vf->oy,CHUNKSIZE);
  151054. long bytes=(vf->callbacks.read_func)(buffer,1,CHUNKSIZE,vf->datasource);
  151055. if(bytes>0)ogg_sync_wrote(&vf->oy,bytes);
  151056. if(bytes==0 && errno)return(-1);
  151057. return(bytes);
  151058. }else
  151059. return(0);
  151060. }
  151061. /* save a tiny smidge of verbosity to make the code more readable */
  151062. static void _seek_helper(OggVorbis_File *vf,ogg_int64_t offset){
  151063. if(vf->datasource){
  151064. (vf->callbacks.seek_func)(vf->datasource, offset, SEEK_SET);
  151065. vf->offset=offset;
  151066. ogg_sync_reset(&vf->oy);
  151067. }else{
  151068. /* shouldn't happen unless someone writes a broken callback */
  151069. return;
  151070. }
  151071. }
  151072. /* The read/seek functions track absolute position within the stream */
  151073. /* from the head of the stream, get the next page. boundary specifies
  151074. if the function is allowed to fetch more data from the stream (and
  151075. how much) or only use internally buffered data.
  151076. boundary: -1) unbounded search
  151077. 0) read no additional data; use cached only
  151078. n) search for a new page beginning for n bytes
  151079. return: <0) did not find a page (OV_FALSE, OV_EOF, OV_EREAD)
  151080. n) found a page at absolute offset n */
  151081. static ogg_int64_t _get_next_page(OggVorbis_File *vf,ogg_page *og,
  151082. ogg_int64_t boundary){
  151083. if(boundary>0)boundary+=vf->offset;
  151084. while(1){
  151085. long more;
  151086. if(boundary>0 && vf->offset>=boundary)return(OV_FALSE);
  151087. more=ogg_sync_pageseek(&vf->oy,og);
  151088. if(more<0){
  151089. /* skipped n bytes */
  151090. vf->offset-=more;
  151091. }else{
  151092. if(more==0){
  151093. /* send more paramedics */
  151094. if(!boundary)return(OV_FALSE);
  151095. {
  151096. long ret=_get_data(vf);
  151097. if(ret==0)return(OV_EOF);
  151098. if(ret<0)return(OV_EREAD);
  151099. }
  151100. }else{
  151101. /* got a page. Return the offset at the page beginning,
  151102. advance the internal offset past the page end */
  151103. ogg_int64_t ret=vf->offset;
  151104. vf->offset+=more;
  151105. return(ret);
  151106. }
  151107. }
  151108. }
  151109. }
  151110. /* find the latest page beginning before the current stream cursor
  151111. position. Much dirtier than the above as Ogg doesn't have any
  151112. backward search linkage. no 'readp' as it will certainly have to
  151113. read. */
  151114. /* returns offset or OV_EREAD, OV_FAULT */
  151115. static ogg_int64_t _get_prev_page(OggVorbis_File *vf,ogg_page *og){
  151116. ogg_int64_t begin=vf->offset;
  151117. ogg_int64_t end=begin;
  151118. ogg_int64_t ret;
  151119. ogg_int64_t offset=-1;
  151120. while(offset==-1){
  151121. begin-=CHUNKSIZE;
  151122. if(begin<0)
  151123. begin=0;
  151124. _seek_helper(vf,begin);
  151125. while(vf->offset<end){
  151126. ret=_get_next_page(vf,og,end-vf->offset);
  151127. if(ret==OV_EREAD)return(OV_EREAD);
  151128. if(ret<0){
  151129. break;
  151130. }else{
  151131. offset=ret;
  151132. }
  151133. }
  151134. }
  151135. /* we have the offset. Actually snork and hold the page now */
  151136. _seek_helper(vf,offset);
  151137. ret=_get_next_page(vf,og,CHUNKSIZE);
  151138. if(ret<0)
  151139. /* this shouldn't be possible */
  151140. return(OV_EFAULT);
  151141. return(offset);
  151142. }
  151143. /* finds each bitstream link one at a time using a bisection search
  151144. (has to begin by knowing the offset of the lb's initial page).
  151145. Recurses for each link so it can alloc the link storage after
  151146. finding them all, then unroll and fill the cache at the same time */
  151147. static int _bisect_forward_serialno(OggVorbis_File *vf,
  151148. ogg_int64_t begin,
  151149. ogg_int64_t searched,
  151150. ogg_int64_t end,
  151151. long currentno,
  151152. long m){
  151153. ogg_int64_t endsearched=end;
  151154. ogg_int64_t next=end;
  151155. ogg_page og;
  151156. ogg_int64_t ret;
  151157. /* the below guards against garbage seperating the last and
  151158. first pages of two links. */
  151159. while(searched<endsearched){
  151160. ogg_int64_t bisect;
  151161. if(endsearched-searched<CHUNKSIZE){
  151162. bisect=searched;
  151163. }else{
  151164. bisect=(searched+endsearched)/2;
  151165. }
  151166. _seek_helper(vf,bisect);
  151167. ret=_get_next_page(vf,&og,-1);
  151168. if(ret==OV_EREAD)return(OV_EREAD);
  151169. if(ret<0 || ogg_page_serialno(&og)!=currentno){
  151170. endsearched=bisect;
  151171. if(ret>=0)next=ret;
  151172. }else{
  151173. searched=ret+og.header_len+og.body_len;
  151174. }
  151175. }
  151176. _seek_helper(vf,next);
  151177. ret=_get_next_page(vf,&og,-1);
  151178. if(ret==OV_EREAD)return(OV_EREAD);
  151179. if(searched>=end || ret<0){
  151180. vf->links=m+1;
  151181. vf->offsets=(ogg_int64_t*)_ogg_malloc((vf->links+1)*sizeof(*vf->offsets));
  151182. vf->serialnos=(long*)_ogg_malloc(vf->links*sizeof(*vf->serialnos));
  151183. vf->offsets[m+1]=searched;
  151184. }else{
  151185. ret=_bisect_forward_serialno(vf,next,vf->offset,
  151186. end,ogg_page_serialno(&og),m+1);
  151187. if(ret==OV_EREAD)return(OV_EREAD);
  151188. }
  151189. vf->offsets[m]=begin;
  151190. vf->serialnos[m]=currentno;
  151191. return(0);
  151192. }
  151193. /* uses the local ogg_stream storage in vf; this is important for
  151194. non-streaming input sources */
  151195. static int _fetch_headers(OggVorbis_File *vf,vorbis_info *vi,vorbis_comment *vc,
  151196. long *serialno,ogg_page *og_ptr){
  151197. ogg_page og;
  151198. ogg_packet op;
  151199. int i,ret;
  151200. if(!og_ptr){
  151201. ogg_int64_t llret=_get_next_page(vf,&og,CHUNKSIZE);
  151202. if(llret==OV_EREAD)return(OV_EREAD);
  151203. if(llret<0)return OV_ENOTVORBIS;
  151204. og_ptr=&og;
  151205. }
  151206. ogg_stream_reset_serialno(&vf->os,ogg_page_serialno(og_ptr));
  151207. if(serialno)*serialno=vf->os.serialno;
  151208. vf->ready_state=STREAMSET;
  151209. /* extract the initial header from the first page and verify that the
  151210. Ogg bitstream is in fact Vorbis data */
  151211. vorbis_info_init(vi);
  151212. vorbis_comment_init(vc);
  151213. i=0;
  151214. while(i<3){
  151215. ogg_stream_pagein(&vf->os,og_ptr);
  151216. while(i<3){
  151217. int result=ogg_stream_packetout(&vf->os,&op);
  151218. if(result==0)break;
  151219. if(result==-1){
  151220. ret=OV_EBADHEADER;
  151221. goto bail_header;
  151222. }
  151223. if((ret=vorbis_synthesis_headerin(vi,vc,&op))){
  151224. goto bail_header;
  151225. }
  151226. i++;
  151227. }
  151228. if(i<3)
  151229. if(_get_next_page(vf,og_ptr,CHUNKSIZE)<0){
  151230. ret=OV_EBADHEADER;
  151231. goto bail_header;
  151232. }
  151233. }
  151234. return 0;
  151235. bail_header:
  151236. vorbis_info_clear(vi);
  151237. vorbis_comment_clear(vc);
  151238. vf->ready_state=OPENED;
  151239. return ret;
  151240. }
  151241. /* last step of the OggVorbis_File initialization; get all the
  151242. vorbis_info structs and PCM positions. Only called by the seekable
  151243. initialization (local stream storage is hacked slightly; pay
  151244. attention to how that's done) */
  151245. /* this is void and does not propogate errors up because we want to be
  151246. able to open and use damaged bitstreams as well as we can. Just
  151247. watch out for missing information for links in the OggVorbis_File
  151248. struct */
  151249. static void _prefetch_all_headers(OggVorbis_File *vf, ogg_int64_t dataoffset){
  151250. ogg_page og;
  151251. int i;
  151252. ogg_int64_t ret;
  151253. vf->vi=(vorbis_info*) _ogg_realloc(vf->vi,vf->links*sizeof(*vf->vi));
  151254. vf->vc=(vorbis_comment*) _ogg_realloc(vf->vc,vf->links*sizeof(*vf->vc));
  151255. vf->dataoffsets=(ogg_int64_t*) _ogg_malloc(vf->links*sizeof(*vf->dataoffsets));
  151256. vf->pcmlengths=(ogg_int64_t*) _ogg_malloc(vf->links*2*sizeof(*vf->pcmlengths));
  151257. for(i=0;i<vf->links;i++){
  151258. if(i==0){
  151259. /* we already grabbed the initial header earlier. Just set the offset */
  151260. vf->dataoffsets[i]=dataoffset;
  151261. _seek_helper(vf,dataoffset);
  151262. }else{
  151263. /* seek to the location of the initial header */
  151264. _seek_helper(vf,vf->offsets[i]);
  151265. if(_fetch_headers(vf,vf->vi+i,vf->vc+i,NULL,NULL)<0){
  151266. vf->dataoffsets[i]=-1;
  151267. }else{
  151268. vf->dataoffsets[i]=vf->offset;
  151269. }
  151270. }
  151271. /* fetch beginning PCM offset */
  151272. if(vf->dataoffsets[i]!=-1){
  151273. ogg_int64_t accumulated=0;
  151274. long lastblock=-1;
  151275. int result;
  151276. ogg_stream_reset_serialno(&vf->os,vf->serialnos[i]);
  151277. while(1){
  151278. ogg_packet op;
  151279. ret=_get_next_page(vf,&og,-1);
  151280. if(ret<0)
  151281. /* this should not be possible unless the file is
  151282. truncated/mangled */
  151283. break;
  151284. if(ogg_page_serialno(&og)!=vf->serialnos[i])
  151285. break;
  151286. /* count blocksizes of all frames in the page */
  151287. ogg_stream_pagein(&vf->os,&og);
  151288. while((result=ogg_stream_packetout(&vf->os,&op))){
  151289. if(result>0){ /* ignore holes */
  151290. long thisblock=vorbis_packet_blocksize(vf->vi+i,&op);
  151291. if(lastblock!=-1)
  151292. accumulated+=(lastblock+thisblock)>>2;
  151293. lastblock=thisblock;
  151294. }
  151295. }
  151296. if(ogg_page_granulepos(&og)!=-1){
  151297. /* pcm offset of last packet on the first audio page */
  151298. accumulated= ogg_page_granulepos(&og)-accumulated;
  151299. break;
  151300. }
  151301. }
  151302. /* less than zero? This is a stream with samples trimmed off
  151303. the beginning, a normal occurrence; set the offset to zero */
  151304. if(accumulated<0)accumulated=0;
  151305. vf->pcmlengths[i*2]=accumulated;
  151306. }
  151307. /* get the PCM length of this link. To do this,
  151308. get the last page of the stream */
  151309. {
  151310. ogg_int64_t end=vf->offsets[i+1];
  151311. _seek_helper(vf,end);
  151312. while(1){
  151313. ret=_get_prev_page(vf,&og);
  151314. if(ret<0){
  151315. /* this should not be possible */
  151316. vorbis_info_clear(vf->vi+i);
  151317. vorbis_comment_clear(vf->vc+i);
  151318. break;
  151319. }
  151320. if(ogg_page_granulepos(&og)!=-1){
  151321. vf->pcmlengths[i*2+1]=ogg_page_granulepos(&og)-vf->pcmlengths[i*2];
  151322. break;
  151323. }
  151324. vf->offset=ret;
  151325. }
  151326. }
  151327. }
  151328. }
  151329. static int _make_decode_ready(OggVorbis_File *vf){
  151330. if(vf->ready_state>STREAMSET)return 0;
  151331. if(vf->ready_state<STREAMSET)return OV_EFAULT;
  151332. if(vf->seekable){
  151333. if(vorbis_synthesis_init(&vf->vd,vf->vi+vf->current_link))
  151334. return OV_EBADLINK;
  151335. }else{
  151336. if(vorbis_synthesis_init(&vf->vd,vf->vi))
  151337. return OV_EBADLINK;
  151338. }
  151339. vorbis_block_init(&vf->vd,&vf->vb);
  151340. vf->ready_state=INITSET;
  151341. vf->bittrack=0.f;
  151342. vf->samptrack=0.f;
  151343. return 0;
  151344. }
  151345. static int _open_seekable2(OggVorbis_File *vf){
  151346. long serialno=vf->current_serialno;
  151347. ogg_int64_t dataoffset=vf->offset, end;
  151348. ogg_page og;
  151349. /* we're partially open and have a first link header state in
  151350. storage in vf */
  151351. /* we can seek, so set out learning all about this file */
  151352. (vf->callbacks.seek_func)(vf->datasource,0,SEEK_END);
  151353. vf->offset=vf->end=(vf->callbacks.tell_func)(vf->datasource);
  151354. /* We get the offset for the last page of the physical bitstream.
  151355. Most OggVorbis files will contain a single logical bitstream */
  151356. end=_get_prev_page(vf,&og);
  151357. if(end<0)return(end);
  151358. /* more than one logical bitstream? */
  151359. if(ogg_page_serialno(&og)!=serialno){
  151360. /* Chained bitstream. Bisect-search each logical bitstream
  151361. section. Do so based on serial number only */
  151362. if(_bisect_forward_serialno(vf,0,0,end+1,serialno,0)<0)return(OV_EREAD);
  151363. }else{
  151364. /* Only one logical bitstream */
  151365. if(_bisect_forward_serialno(vf,0,end,end+1,serialno,0))return(OV_EREAD);
  151366. }
  151367. /* the initial header memory is referenced by vf after; don't free it */
  151368. _prefetch_all_headers(vf,dataoffset);
  151369. return(ov_raw_seek(vf,0));
  151370. }
  151371. /* clear out the current logical bitstream decoder */
  151372. static void _decode_clear(OggVorbis_File *vf){
  151373. vorbis_dsp_clear(&vf->vd);
  151374. vorbis_block_clear(&vf->vb);
  151375. vf->ready_state=OPENED;
  151376. }
  151377. /* fetch and process a packet. Handles the case where we're at a
  151378. bitstream boundary and dumps the decoding machine. If the decoding
  151379. machine is unloaded, it loads it. It also keeps pcm_offset up to
  151380. date (seek and read both use this. seek uses a special hack with
  151381. readp).
  151382. return: <0) error, OV_HOLE (lost packet) or OV_EOF
  151383. 0) need more data (only if readp==0)
  151384. 1) got a packet
  151385. */
  151386. static int _fetch_and_process_packet(OggVorbis_File *vf,
  151387. ogg_packet *op_in,
  151388. int readp,
  151389. int spanp){
  151390. ogg_page og;
  151391. /* handle one packet. Try to fetch it from current stream state */
  151392. /* extract packets from page */
  151393. while(1){
  151394. /* process a packet if we can. If the machine isn't loaded,
  151395. neither is a page */
  151396. if(vf->ready_state==INITSET){
  151397. while(1) {
  151398. ogg_packet op;
  151399. ogg_packet *op_ptr=(op_in?op_in:&op);
  151400. int result=ogg_stream_packetout(&vf->os,op_ptr);
  151401. ogg_int64_t granulepos;
  151402. op_in=NULL;
  151403. if(result==-1)return(OV_HOLE); /* hole in the data. */
  151404. if(result>0){
  151405. /* got a packet. process it */
  151406. granulepos=op_ptr->granulepos;
  151407. if(!vorbis_synthesis(&vf->vb,op_ptr)){ /* lazy check for lazy
  151408. header handling. The
  151409. header packets aren't
  151410. audio, so if/when we
  151411. submit them,
  151412. vorbis_synthesis will
  151413. reject them */
  151414. /* suck in the synthesis data and track bitrate */
  151415. {
  151416. int oldsamples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  151417. /* for proper use of libvorbis within libvorbisfile,
  151418. oldsamples will always be zero. */
  151419. if(oldsamples)return(OV_EFAULT);
  151420. vorbis_synthesis_blockin(&vf->vd,&vf->vb);
  151421. vf->samptrack+=vorbis_synthesis_pcmout(&vf->vd,NULL)-oldsamples;
  151422. vf->bittrack+=op_ptr->bytes*8;
  151423. }
  151424. /* update the pcm offset. */
  151425. if(granulepos!=-1 && !op_ptr->e_o_s){
  151426. int link=(vf->seekable?vf->current_link:0);
  151427. int i,samples;
  151428. /* this packet has a pcm_offset on it (the last packet
  151429. completed on a page carries the offset) After processing
  151430. (above), we know the pcm position of the *last* sample
  151431. ready to be returned. Find the offset of the *first*
  151432. As an aside, this trick is inaccurate if we begin
  151433. reading anew right at the last page; the end-of-stream
  151434. granulepos declares the last frame in the stream, and the
  151435. last packet of the last page may be a partial frame.
  151436. So, we need a previous granulepos from an in-sequence page
  151437. to have a reference point. Thus the !op_ptr->e_o_s clause
  151438. above */
  151439. if(vf->seekable && link>0)
  151440. granulepos-=vf->pcmlengths[link*2];
  151441. if(granulepos<0)granulepos=0; /* actually, this
  151442. shouldn't be possible
  151443. here unless the stream
  151444. is very broken */
  151445. samples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  151446. granulepos-=samples;
  151447. for(i=0;i<link;i++)
  151448. granulepos+=vf->pcmlengths[i*2+1];
  151449. vf->pcm_offset=granulepos;
  151450. }
  151451. return(1);
  151452. }
  151453. }
  151454. else
  151455. break;
  151456. }
  151457. }
  151458. if(vf->ready_state>=OPENED){
  151459. ogg_int64_t ret;
  151460. if(!readp)return(0);
  151461. if((ret=_get_next_page(vf,&og,-1))<0){
  151462. return(OV_EOF); /* eof.
  151463. leave unitialized */
  151464. }
  151465. /* bitrate tracking; add the header's bytes here, the body bytes
  151466. are done by packet above */
  151467. vf->bittrack+=og.header_len*8;
  151468. /* has our decoding just traversed a bitstream boundary? */
  151469. if(vf->ready_state==INITSET){
  151470. if(vf->current_serialno!=ogg_page_serialno(&og)){
  151471. if(!spanp)
  151472. return(OV_EOF);
  151473. _decode_clear(vf);
  151474. if(!vf->seekable){
  151475. vorbis_info_clear(vf->vi);
  151476. vorbis_comment_clear(vf->vc);
  151477. }
  151478. }
  151479. }
  151480. }
  151481. /* Do we need to load a new machine before submitting the page? */
  151482. /* This is different in the seekable and non-seekable cases.
  151483. In the seekable case, we already have all the header
  151484. information loaded and cached; we just initialize the machine
  151485. with it and continue on our merry way.
  151486. In the non-seekable (streaming) case, we'll only be at a
  151487. boundary if we just left the previous logical bitstream and
  151488. we're now nominally at the header of the next bitstream
  151489. */
  151490. if(vf->ready_state!=INITSET){
  151491. int link;
  151492. if(vf->ready_state<STREAMSET){
  151493. if(vf->seekable){
  151494. vf->current_serialno=ogg_page_serialno(&og);
  151495. /* match the serialno to bitstream section. We use this rather than
  151496. offset positions to avoid problems near logical bitstream
  151497. boundaries */
  151498. for(link=0;link<vf->links;link++)
  151499. if(vf->serialnos[link]==vf->current_serialno)break;
  151500. if(link==vf->links)return(OV_EBADLINK); /* sign of a bogus
  151501. stream. error out,
  151502. leave machine
  151503. uninitialized */
  151504. vf->current_link=link;
  151505. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  151506. vf->ready_state=STREAMSET;
  151507. }else{
  151508. /* we're streaming */
  151509. /* fetch the three header packets, build the info struct */
  151510. int ret=_fetch_headers(vf,vf->vi,vf->vc,&vf->current_serialno,&og);
  151511. if(ret)return(ret);
  151512. vf->current_link++;
  151513. link=0;
  151514. }
  151515. }
  151516. {
  151517. int ret=_make_decode_ready(vf);
  151518. if(ret<0)return ret;
  151519. }
  151520. }
  151521. ogg_stream_pagein(&vf->os,&og);
  151522. }
  151523. }
  151524. /* if, eg, 64 bit stdio is configured by default, this will build with
  151525. fseek64 */
  151526. static int _fseek64_wrap(FILE *f,ogg_int64_t off,int whence){
  151527. if(f==NULL)return(-1);
  151528. return fseek(f,off,whence);
  151529. }
  151530. static int _ov_open1(void *f,OggVorbis_File *vf,char *initial,
  151531. long ibytes, ov_callbacks callbacks){
  151532. int offsettest=(f?callbacks.seek_func(f,0,SEEK_CUR):-1);
  151533. int ret;
  151534. memset(vf,0,sizeof(*vf));
  151535. vf->datasource=f;
  151536. vf->callbacks = callbacks;
  151537. /* init the framing state */
  151538. ogg_sync_init(&vf->oy);
  151539. /* perhaps some data was previously read into a buffer for testing
  151540. against other stream types. Allow initialization from this
  151541. previously read data (as we may be reading from a non-seekable
  151542. stream) */
  151543. if(initial){
  151544. char *buffer=ogg_sync_buffer(&vf->oy,ibytes);
  151545. memcpy(buffer,initial,ibytes);
  151546. ogg_sync_wrote(&vf->oy,ibytes);
  151547. }
  151548. /* can we seek? Stevens suggests the seek test was portable */
  151549. if(offsettest!=-1)vf->seekable=1;
  151550. /* No seeking yet; Set up a 'single' (current) logical bitstream
  151551. entry for partial open */
  151552. vf->links=1;
  151553. vf->vi=(vorbis_info*) _ogg_calloc(vf->links,sizeof(*vf->vi));
  151554. vf->vc=(vorbis_comment*) _ogg_calloc(vf->links,sizeof(*vf->vc));
  151555. ogg_stream_init(&vf->os,-1); /* fill in the serialno later */
  151556. /* Try to fetch the headers, maintaining all the storage */
  151557. if((ret=_fetch_headers(vf,vf->vi,vf->vc,&vf->current_serialno,NULL))<0){
  151558. vf->datasource=NULL;
  151559. ov_clear(vf);
  151560. }else
  151561. vf->ready_state=PARTOPEN;
  151562. return(ret);
  151563. }
  151564. static int _ov_open2(OggVorbis_File *vf){
  151565. if(vf->ready_state != PARTOPEN) return OV_EINVAL;
  151566. vf->ready_state=OPENED;
  151567. if(vf->seekable){
  151568. int ret=_open_seekable2(vf);
  151569. if(ret){
  151570. vf->datasource=NULL;
  151571. ov_clear(vf);
  151572. }
  151573. return(ret);
  151574. }else
  151575. vf->ready_state=STREAMSET;
  151576. return 0;
  151577. }
  151578. /* clear out the OggVorbis_File struct */
  151579. int ov_clear(OggVorbis_File *vf){
  151580. if(vf){
  151581. vorbis_block_clear(&vf->vb);
  151582. vorbis_dsp_clear(&vf->vd);
  151583. ogg_stream_clear(&vf->os);
  151584. if(vf->vi && vf->links){
  151585. int i;
  151586. for(i=0;i<vf->links;i++){
  151587. vorbis_info_clear(vf->vi+i);
  151588. vorbis_comment_clear(vf->vc+i);
  151589. }
  151590. _ogg_free(vf->vi);
  151591. _ogg_free(vf->vc);
  151592. }
  151593. if(vf->dataoffsets)_ogg_free(vf->dataoffsets);
  151594. if(vf->pcmlengths)_ogg_free(vf->pcmlengths);
  151595. if(vf->serialnos)_ogg_free(vf->serialnos);
  151596. if(vf->offsets)_ogg_free(vf->offsets);
  151597. ogg_sync_clear(&vf->oy);
  151598. if(vf->datasource)(vf->callbacks.close_func)(vf->datasource);
  151599. memset(vf,0,sizeof(*vf));
  151600. }
  151601. #ifdef DEBUG_LEAKS
  151602. _VDBG_dump();
  151603. #endif
  151604. return(0);
  151605. }
  151606. /* inspects the OggVorbis file and finds/documents all the logical
  151607. bitstreams contained in it. Tries to be tolerant of logical
  151608. bitstream sections that are truncated/woogie.
  151609. return: -1) error
  151610. 0) OK
  151611. */
  151612. int ov_open_callbacks(void *f,OggVorbis_File *vf,char *initial,long ibytes,
  151613. ov_callbacks callbacks){
  151614. int ret=_ov_open1(f,vf,initial,ibytes,callbacks);
  151615. if(ret)return ret;
  151616. return _ov_open2(vf);
  151617. }
  151618. int ov_open(FILE *f,OggVorbis_File *vf,char *initial,long ibytes){
  151619. ov_callbacks callbacks = {
  151620. (size_t (*)(void *, size_t, size_t, void *)) fread,
  151621. (int (*)(void *, ogg_int64_t, int)) _fseek64_wrap,
  151622. (int (*)(void *)) fclose,
  151623. (long (*)(void *)) ftell
  151624. };
  151625. return ov_open_callbacks((void *)f, vf, initial, ibytes, callbacks);
  151626. }
  151627. /* cheap hack for game usage where downsampling is desirable; there's
  151628. no need for SRC as we can just do it cheaply in libvorbis. */
  151629. int ov_halfrate(OggVorbis_File *vf,int flag){
  151630. int i;
  151631. if(vf->vi==NULL)return OV_EINVAL;
  151632. if(!vf->seekable)return OV_EINVAL;
  151633. if(vf->ready_state>=STREAMSET)
  151634. _decode_clear(vf); /* clear out stream state; later on libvorbis
  151635. will be able to swap this on the fly, but
  151636. for now dumping the decode machine is needed
  151637. to reinit the MDCT lookups. 1.1 libvorbis
  151638. is planned to be able to switch on the fly */
  151639. for(i=0;i<vf->links;i++){
  151640. if(vorbis_synthesis_halfrate(vf->vi+i,flag)){
  151641. ov_halfrate(vf,0);
  151642. return OV_EINVAL;
  151643. }
  151644. }
  151645. return 0;
  151646. }
  151647. int ov_halfrate_p(OggVorbis_File *vf){
  151648. if(vf->vi==NULL)return OV_EINVAL;
  151649. return vorbis_synthesis_halfrate_p(vf->vi);
  151650. }
  151651. /* Only partially open the vorbis file; test for Vorbisness, and load
  151652. the headers for the first chain. Do not seek (although test for
  151653. seekability). Use ov_test_open to finish opening the file, else
  151654. ov_clear to close/free it. Same return codes as open. */
  151655. int ov_test_callbacks(void *f,OggVorbis_File *vf,char *initial,long ibytes,
  151656. ov_callbacks callbacks)
  151657. {
  151658. return _ov_open1(f,vf,initial,ibytes,callbacks);
  151659. }
  151660. int ov_test(FILE *f,OggVorbis_File *vf,char *initial,long ibytes){
  151661. ov_callbacks callbacks = {
  151662. (size_t (*)(void *, size_t, size_t, void *)) fread,
  151663. (int (*)(void *, ogg_int64_t, int)) _fseek64_wrap,
  151664. (int (*)(void *)) fclose,
  151665. (long (*)(void *)) ftell
  151666. };
  151667. return ov_test_callbacks((void *)f, vf, initial, ibytes, callbacks);
  151668. }
  151669. int ov_test_open(OggVorbis_File *vf){
  151670. if(vf->ready_state!=PARTOPEN)return(OV_EINVAL);
  151671. return _ov_open2(vf);
  151672. }
  151673. /* How many logical bitstreams in this physical bitstream? */
  151674. long ov_streams(OggVorbis_File *vf){
  151675. return vf->links;
  151676. }
  151677. /* Is the FILE * associated with vf seekable? */
  151678. long ov_seekable(OggVorbis_File *vf){
  151679. return vf->seekable;
  151680. }
  151681. /* returns the bitrate for a given logical bitstream or the entire
  151682. physical bitstream. If the file is open for random access, it will
  151683. find the *actual* average bitrate. If the file is streaming, it
  151684. returns the nominal bitrate (if set) else the average of the
  151685. upper/lower bounds (if set) else -1 (unset).
  151686. If you want the actual bitrate field settings, get them from the
  151687. vorbis_info structs */
  151688. long ov_bitrate(OggVorbis_File *vf,int i){
  151689. if(vf->ready_state<OPENED)return(OV_EINVAL);
  151690. if(i>=vf->links)return(OV_EINVAL);
  151691. if(!vf->seekable && i!=0)return(ov_bitrate(vf,0));
  151692. if(i<0){
  151693. ogg_int64_t bits=0;
  151694. int i;
  151695. float br;
  151696. for(i=0;i<vf->links;i++)
  151697. bits+=(vf->offsets[i+1]-vf->dataoffsets[i])*8;
  151698. /* This once read: return(rint(bits/ov_time_total(vf,-1)));
  151699. * gcc 3.x on x86 miscompiled this at optimisation level 2 and above,
  151700. * so this is slightly transformed to make it work.
  151701. */
  151702. br = bits/ov_time_total(vf,-1);
  151703. return(rint(br));
  151704. }else{
  151705. if(vf->seekable){
  151706. /* return the actual bitrate */
  151707. return(rint((vf->offsets[i+1]-vf->dataoffsets[i])*8/ov_time_total(vf,i)));
  151708. }else{
  151709. /* return nominal if set */
  151710. if(vf->vi[i].bitrate_nominal>0){
  151711. return vf->vi[i].bitrate_nominal;
  151712. }else{
  151713. if(vf->vi[i].bitrate_upper>0){
  151714. if(vf->vi[i].bitrate_lower>0){
  151715. return (vf->vi[i].bitrate_upper+vf->vi[i].bitrate_lower)/2;
  151716. }else{
  151717. return vf->vi[i].bitrate_upper;
  151718. }
  151719. }
  151720. return(OV_FALSE);
  151721. }
  151722. }
  151723. }
  151724. }
  151725. /* returns the actual bitrate since last call. returns -1 if no
  151726. additional data to offer since last call (or at beginning of stream),
  151727. EINVAL if stream is only partially open
  151728. */
  151729. long ov_bitrate_instant(OggVorbis_File *vf){
  151730. int link=(vf->seekable?vf->current_link:0);
  151731. long ret;
  151732. if(vf->ready_state<OPENED)return(OV_EINVAL);
  151733. if(vf->samptrack==0)return(OV_FALSE);
  151734. ret=vf->bittrack/vf->samptrack*vf->vi[link].rate+.5;
  151735. vf->bittrack=0.f;
  151736. vf->samptrack=0.f;
  151737. return(ret);
  151738. }
  151739. /* Guess */
  151740. long ov_serialnumber(OggVorbis_File *vf,int i){
  151741. if(i>=vf->links)return(ov_serialnumber(vf,vf->links-1));
  151742. if(!vf->seekable && i>=0)return(ov_serialnumber(vf,-1));
  151743. if(i<0){
  151744. return(vf->current_serialno);
  151745. }else{
  151746. return(vf->serialnos[i]);
  151747. }
  151748. }
  151749. /* returns: total raw (compressed) length of content if i==-1
  151750. raw (compressed) length of that logical bitstream for i==0 to n
  151751. OV_EINVAL if the stream is not seekable (we can't know the length)
  151752. or if stream is only partially open
  151753. */
  151754. ogg_int64_t ov_raw_total(OggVorbis_File *vf,int i){
  151755. if(vf->ready_state<OPENED)return(OV_EINVAL);
  151756. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  151757. if(i<0){
  151758. ogg_int64_t acc=0;
  151759. int i;
  151760. for(i=0;i<vf->links;i++)
  151761. acc+=ov_raw_total(vf,i);
  151762. return(acc);
  151763. }else{
  151764. return(vf->offsets[i+1]-vf->offsets[i]);
  151765. }
  151766. }
  151767. /* returns: total PCM length (samples) of content if i==-1 PCM length
  151768. (samples) of that logical bitstream for i==0 to n
  151769. OV_EINVAL if the stream is not seekable (we can't know the
  151770. length) or only partially open
  151771. */
  151772. ogg_int64_t ov_pcm_total(OggVorbis_File *vf,int i){
  151773. if(vf->ready_state<OPENED)return(OV_EINVAL);
  151774. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  151775. if(i<0){
  151776. ogg_int64_t acc=0;
  151777. int i;
  151778. for(i=0;i<vf->links;i++)
  151779. acc+=ov_pcm_total(vf,i);
  151780. return(acc);
  151781. }else{
  151782. return(vf->pcmlengths[i*2+1]);
  151783. }
  151784. }
  151785. /* returns: total seconds of content if i==-1
  151786. seconds in that logical bitstream for i==0 to n
  151787. OV_EINVAL if the stream is not seekable (we can't know the
  151788. length) or only partially open
  151789. */
  151790. double ov_time_total(OggVorbis_File *vf,int i){
  151791. if(vf->ready_state<OPENED)return(OV_EINVAL);
  151792. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  151793. if(i<0){
  151794. double acc=0;
  151795. int i;
  151796. for(i=0;i<vf->links;i++)
  151797. acc+=ov_time_total(vf,i);
  151798. return(acc);
  151799. }else{
  151800. return((double)(vf->pcmlengths[i*2+1])/vf->vi[i].rate);
  151801. }
  151802. }
  151803. /* seek to an offset relative to the *compressed* data. This also
  151804. scans packets to update the PCM cursor. It will cross a logical
  151805. bitstream boundary, but only if it can't get any packets out of the
  151806. tail of the bitstream we seek to (so no surprises).
  151807. returns zero on success, nonzero on failure */
  151808. int ov_raw_seek(OggVorbis_File *vf,ogg_int64_t pos){
  151809. ogg_stream_state work_os;
  151810. if(vf->ready_state<OPENED)return(OV_EINVAL);
  151811. if(!vf->seekable)
  151812. return(OV_ENOSEEK); /* don't dump machine if we can't seek */
  151813. if(pos<0 || pos>vf->end)return(OV_EINVAL);
  151814. /* don't yet clear out decoding machine (if it's initialized), in
  151815. the case we're in the same link. Restart the decode lapping, and
  151816. let _fetch_and_process_packet deal with a potential bitstream
  151817. boundary */
  151818. vf->pcm_offset=-1;
  151819. ogg_stream_reset_serialno(&vf->os,
  151820. vf->current_serialno); /* must set serialno */
  151821. vorbis_synthesis_restart(&vf->vd);
  151822. _seek_helper(vf,pos);
  151823. /* we need to make sure the pcm_offset is set, but we don't want to
  151824. advance the raw cursor past good packets just to get to the first
  151825. with a granulepos. That's not equivalent behavior to beginning
  151826. decoding as immediately after the seek position as possible.
  151827. So, a hack. We use two stream states; a local scratch state and
  151828. the shared vf->os stream state. We use the local state to
  151829. scan, and the shared state as a buffer for later decode.
  151830. Unfortuantely, on the last page we still advance to last packet
  151831. because the granulepos on the last page is not necessarily on a
  151832. packet boundary, and we need to make sure the granpos is
  151833. correct.
  151834. */
  151835. {
  151836. ogg_page og;
  151837. ogg_packet op;
  151838. int lastblock=0;
  151839. int accblock=0;
  151840. int thisblock;
  151841. int eosflag;
  151842. ogg_stream_init(&work_os,vf->current_serialno); /* get the memory ready */
  151843. ogg_stream_reset(&work_os); /* eliminate the spurious OV_HOLE
  151844. return from not necessarily
  151845. starting from the beginning */
  151846. while(1){
  151847. if(vf->ready_state>=STREAMSET){
  151848. /* snarf/scan a packet if we can */
  151849. int result=ogg_stream_packetout(&work_os,&op);
  151850. if(result>0){
  151851. if(vf->vi[vf->current_link].codec_setup){
  151852. thisblock=vorbis_packet_blocksize(vf->vi+vf->current_link,&op);
  151853. if(thisblock<0){
  151854. ogg_stream_packetout(&vf->os,NULL);
  151855. thisblock=0;
  151856. }else{
  151857. if(eosflag)
  151858. ogg_stream_packetout(&vf->os,NULL);
  151859. else
  151860. if(lastblock)accblock+=(lastblock+thisblock)>>2;
  151861. }
  151862. if(op.granulepos!=-1){
  151863. int i,link=vf->current_link;
  151864. ogg_int64_t granulepos=op.granulepos-vf->pcmlengths[link*2];
  151865. if(granulepos<0)granulepos=0;
  151866. for(i=0;i<link;i++)
  151867. granulepos+=vf->pcmlengths[i*2+1];
  151868. vf->pcm_offset=granulepos-accblock;
  151869. break;
  151870. }
  151871. lastblock=thisblock;
  151872. continue;
  151873. }else
  151874. ogg_stream_packetout(&vf->os,NULL);
  151875. }
  151876. }
  151877. if(!lastblock){
  151878. if(_get_next_page(vf,&og,-1)<0){
  151879. vf->pcm_offset=ov_pcm_total(vf,-1);
  151880. break;
  151881. }
  151882. }else{
  151883. /* huh? Bogus stream with packets but no granulepos */
  151884. vf->pcm_offset=-1;
  151885. break;
  151886. }
  151887. /* has our decoding just traversed a bitstream boundary? */
  151888. if(vf->ready_state>=STREAMSET)
  151889. if(vf->current_serialno!=ogg_page_serialno(&og)){
  151890. _decode_clear(vf); /* clear out stream state */
  151891. ogg_stream_clear(&work_os);
  151892. }
  151893. if(vf->ready_state<STREAMSET){
  151894. int link;
  151895. vf->current_serialno=ogg_page_serialno(&og);
  151896. for(link=0;link<vf->links;link++)
  151897. if(vf->serialnos[link]==vf->current_serialno)break;
  151898. if(link==vf->links)goto seek_error; /* sign of a bogus stream.
  151899. error out, leave
  151900. machine uninitialized */
  151901. vf->current_link=link;
  151902. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  151903. ogg_stream_reset_serialno(&work_os,vf->current_serialno);
  151904. vf->ready_state=STREAMSET;
  151905. }
  151906. ogg_stream_pagein(&vf->os,&og);
  151907. ogg_stream_pagein(&work_os,&og);
  151908. eosflag=ogg_page_eos(&og);
  151909. }
  151910. }
  151911. ogg_stream_clear(&work_os);
  151912. vf->bittrack=0.f;
  151913. vf->samptrack=0.f;
  151914. return(0);
  151915. seek_error:
  151916. /* dump the machine so we're in a known state */
  151917. vf->pcm_offset=-1;
  151918. ogg_stream_clear(&work_os);
  151919. _decode_clear(vf);
  151920. return OV_EBADLINK;
  151921. }
  151922. /* Page granularity seek (faster than sample granularity because we
  151923. don't do the last bit of decode to find a specific sample).
  151924. Seek to the last [granule marked] page preceeding the specified pos
  151925. location, such that decoding past the returned point will quickly
  151926. arrive at the requested position. */
  151927. int ov_pcm_seek_page(OggVorbis_File *vf,ogg_int64_t pos){
  151928. int link=-1;
  151929. ogg_int64_t result=0;
  151930. ogg_int64_t total=ov_pcm_total(vf,-1);
  151931. if(vf->ready_state<OPENED)return(OV_EINVAL);
  151932. if(!vf->seekable)return(OV_ENOSEEK);
  151933. if(pos<0 || pos>total)return(OV_EINVAL);
  151934. /* which bitstream section does this pcm offset occur in? */
  151935. for(link=vf->links-1;link>=0;link--){
  151936. total-=vf->pcmlengths[link*2+1];
  151937. if(pos>=total)break;
  151938. }
  151939. /* search within the logical bitstream for the page with the highest
  151940. pcm_pos preceeding (or equal to) pos. There is a danger here;
  151941. missing pages or incorrect frame number information in the
  151942. bitstream could make our task impossible. Account for that (it
  151943. would be an error condition) */
  151944. /* new search algorithm by HB (Nicholas Vinen) */
  151945. {
  151946. ogg_int64_t end=vf->offsets[link+1];
  151947. ogg_int64_t begin=vf->offsets[link];
  151948. ogg_int64_t begintime = vf->pcmlengths[link*2];
  151949. ogg_int64_t endtime = vf->pcmlengths[link*2+1]+begintime;
  151950. ogg_int64_t target=pos-total+begintime;
  151951. ogg_int64_t best=begin;
  151952. ogg_page og;
  151953. while(begin<end){
  151954. ogg_int64_t bisect;
  151955. if(end-begin<CHUNKSIZE){
  151956. bisect=begin;
  151957. }else{
  151958. /* take a (pretty decent) guess. */
  151959. bisect=begin +
  151960. (target-begintime)*(end-begin)/(endtime-begintime) - CHUNKSIZE;
  151961. if(bisect<=begin)
  151962. bisect=begin+1;
  151963. }
  151964. _seek_helper(vf,bisect);
  151965. while(begin<end){
  151966. result=_get_next_page(vf,&og,end-vf->offset);
  151967. if(result==OV_EREAD) goto seek_error;
  151968. if(result<0){
  151969. if(bisect<=begin+1)
  151970. end=begin; /* found it */
  151971. else{
  151972. if(bisect==0) goto seek_error;
  151973. bisect-=CHUNKSIZE;
  151974. if(bisect<=begin)bisect=begin+1;
  151975. _seek_helper(vf,bisect);
  151976. }
  151977. }else{
  151978. ogg_int64_t granulepos=ogg_page_granulepos(&og);
  151979. if(granulepos==-1)continue;
  151980. if(granulepos<target){
  151981. best=result; /* raw offset of packet with granulepos */
  151982. begin=vf->offset; /* raw offset of next page */
  151983. begintime=granulepos;
  151984. if(target-begintime>44100)break;
  151985. bisect=begin; /* *not* begin + 1 */
  151986. }else{
  151987. if(bisect<=begin+1)
  151988. end=begin; /* found it */
  151989. else{
  151990. if(end==vf->offset){ /* we're pretty close - we'd be stuck in */
  151991. end=result;
  151992. bisect-=CHUNKSIZE; /* an endless loop otherwise. */
  151993. if(bisect<=begin)bisect=begin+1;
  151994. _seek_helper(vf,bisect);
  151995. }else{
  151996. end=result;
  151997. endtime=granulepos;
  151998. break;
  151999. }
  152000. }
  152001. }
  152002. }
  152003. }
  152004. }
  152005. /* found our page. seek to it, update pcm offset. Easier case than
  152006. raw_seek, don't keep packets preceeding granulepos. */
  152007. {
  152008. ogg_page og;
  152009. ogg_packet op;
  152010. /* seek */
  152011. _seek_helper(vf,best);
  152012. vf->pcm_offset=-1;
  152013. if(_get_next_page(vf,&og,-1)<0)return(OV_EOF); /* shouldn't happen */
  152014. if(link!=vf->current_link){
  152015. /* Different link; dump entire decode machine */
  152016. _decode_clear(vf);
  152017. vf->current_link=link;
  152018. vf->current_serialno=ogg_page_serialno(&og);
  152019. vf->ready_state=STREAMSET;
  152020. }else{
  152021. vorbis_synthesis_restart(&vf->vd);
  152022. }
  152023. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  152024. ogg_stream_pagein(&vf->os,&og);
  152025. /* pull out all but last packet; the one with granulepos */
  152026. while(1){
  152027. result=ogg_stream_packetpeek(&vf->os,&op);
  152028. if(result==0){
  152029. /* !!! the packet finishing this page originated on a
  152030. preceeding page. Keep fetching previous pages until we
  152031. get one with a granulepos or without the 'continued' flag
  152032. set. Then just use raw_seek for simplicity. */
  152033. _seek_helper(vf,best);
  152034. while(1){
  152035. result=_get_prev_page(vf,&og);
  152036. if(result<0) goto seek_error;
  152037. if(ogg_page_granulepos(&og)>-1 ||
  152038. !ogg_page_continued(&og)){
  152039. return ov_raw_seek(vf,result);
  152040. }
  152041. vf->offset=result;
  152042. }
  152043. }
  152044. if(result<0){
  152045. result = OV_EBADPACKET;
  152046. goto seek_error;
  152047. }
  152048. if(op.granulepos!=-1){
  152049. vf->pcm_offset=op.granulepos-vf->pcmlengths[vf->current_link*2];
  152050. if(vf->pcm_offset<0)vf->pcm_offset=0;
  152051. vf->pcm_offset+=total;
  152052. break;
  152053. }else
  152054. result=ogg_stream_packetout(&vf->os,NULL);
  152055. }
  152056. }
  152057. }
  152058. /* verify result */
  152059. if(vf->pcm_offset>pos || pos>ov_pcm_total(vf,-1)){
  152060. result=OV_EFAULT;
  152061. goto seek_error;
  152062. }
  152063. vf->bittrack=0.f;
  152064. vf->samptrack=0.f;
  152065. return(0);
  152066. seek_error:
  152067. /* dump machine so we're in a known state */
  152068. vf->pcm_offset=-1;
  152069. _decode_clear(vf);
  152070. return (int)result;
  152071. }
  152072. /* seek to a sample offset relative to the decompressed pcm stream
  152073. returns zero on success, nonzero on failure */
  152074. int ov_pcm_seek(OggVorbis_File *vf,ogg_int64_t pos){
  152075. int thisblock,lastblock=0;
  152076. int ret=ov_pcm_seek_page(vf,pos);
  152077. if(ret<0)return(ret);
  152078. if((ret=_make_decode_ready(vf)))return ret;
  152079. /* discard leading packets we don't need for the lapping of the
  152080. position we want; don't decode them */
  152081. while(1){
  152082. ogg_packet op;
  152083. ogg_page og;
  152084. int ret=ogg_stream_packetpeek(&vf->os,&op);
  152085. if(ret>0){
  152086. thisblock=vorbis_packet_blocksize(vf->vi+vf->current_link,&op);
  152087. if(thisblock<0){
  152088. ogg_stream_packetout(&vf->os,NULL);
  152089. continue; /* non audio packet */
  152090. }
  152091. if(lastblock)vf->pcm_offset+=(lastblock+thisblock)>>2;
  152092. if(vf->pcm_offset+((thisblock+
  152093. vorbis_info_blocksize(vf->vi,1))>>2)>=pos)break;
  152094. /* remove the packet from packet queue and track its granulepos */
  152095. ogg_stream_packetout(&vf->os,NULL);
  152096. vorbis_synthesis_trackonly(&vf->vb,&op); /* set up a vb with
  152097. only tracking, no
  152098. pcm_decode */
  152099. vorbis_synthesis_blockin(&vf->vd,&vf->vb);
  152100. /* end of logical stream case is hard, especially with exact
  152101. length positioning. */
  152102. if(op.granulepos>-1){
  152103. int i;
  152104. /* always believe the stream markers */
  152105. vf->pcm_offset=op.granulepos-vf->pcmlengths[vf->current_link*2];
  152106. if(vf->pcm_offset<0)vf->pcm_offset=0;
  152107. for(i=0;i<vf->current_link;i++)
  152108. vf->pcm_offset+=vf->pcmlengths[i*2+1];
  152109. }
  152110. lastblock=thisblock;
  152111. }else{
  152112. if(ret<0 && ret!=OV_HOLE)break;
  152113. /* suck in a new page */
  152114. if(_get_next_page(vf,&og,-1)<0)break;
  152115. if(vf->current_serialno!=ogg_page_serialno(&og))_decode_clear(vf);
  152116. if(vf->ready_state<STREAMSET){
  152117. int link;
  152118. vf->current_serialno=ogg_page_serialno(&og);
  152119. for(link=0;link<vf->links;link++)
  152120. if(vf->serialnos[link]==vf->current_serialno)break;
  152121. if(link==vf->links)return(OV_EBADLINK);
  152122. vf->current_link=link;
  152123. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  152124. vf->ready_state=STREAMSET;
  152125. ret=_make_decode_ready(vf);
  152126. if(ret)return ret;
  152127. lastblock=0;
  152128. }
  152129. ogg_stream_pagein(&vf->os,&og);
  152130. }
  152131. }
  152132. vf->bittrack=0.f;
  152133. vf->samptrack=0.f;
  152134. /* discard samples until we reach the desired position. Crossing a
  152135. logical bitstream boundary with abandon is OK. */
  152136. while(vf->pcm_offset<pos){
  152137. ogg_int64_t target=pos-vf->pcm_offset;
  152138. long samples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  152139. if(samples>target)samples=target;
  152140. vorbis_synthesis_read(&vf->vd,samples);
  152141. vf->pcm_offset+=samples;
  152142. if(samples<target)
  152143. if(_fetch_and_process_packet(vf,NULL,1,1)<=0)
  152144. vf->pcm_offset=ov_pcm_total(vf,-1); /* eof */
  152145. }
  152146. return 0;
  152147. }
  152148. /* seek to a playback time relative to the decompressed pcm stream
  152149. returns zero on success, nonzero on failure */
  152150. int ov_time_seek(OggVorbis_File *vf,double seconds){
  152151. /* translate time to PCM position and call ov_pcm_seek */
  152152. int link=-1;
  152153. ogg_int64_t pcm_total=ov_pcm_total(vf,-1);
  152154. double time_total=ov_time_total(vf,-1);
  152155. if(vf->ready_state<OPENED)return(OV_EINVAL);
  152156. if(!vf->seekable)return(OV_ENOSEEK);
  152157. if(seconds<0 || seconds>time_total)return(OV_EINVAL);
  152158. /* which bitstream section does this time offset occur in? */
  152159. for(link=vf->links-1;link>=0;link--){
  152160. pcm_total-=vf->pcmlengths[link*2+1];
  152161. time_total-=ov_time_total(vf,link);
  152162. if(seconds>=time_total)break;
  152163. }
  152164. /* enough information to convert time offset to pcm offset */
  152165. {
  152166. ogg_int64_t target=pcm_total+(seconds-time_total)*vf->vi[link].rate;
  152167. return(ov_pcm_seek(vf,target));
  152168. }
  152169. }
  152170. /* page-granularity version of ov_time_seek
  152171. returns zero on success, nonzero on failure */
  152172. int ov_time_seek_page(OggVorbis_File *vf,double seconds){
  152173. /* translate time to PCM position and call ov_pcm_seek */
  152174. int link=-1;
  152175. ogg_int64_t pcm_total=ov_pcm_total(vf,-1);
  152176. double time_total=ov_time_total(vf,-1);
  152177. if(vf->ready_state<OPENED)return(OV_EINVAL);
  152178. if(!vf->seekable)return(OV_ENOSEEK);
  152179. if(seconds<0 || seconds>time_total)return(OV_EINVAL);
  152180. /* which bitstream section does this time offset occur in? */
  152181. for(link=vf->links-1;link>=0;link--){
  152182. pcm_total-=vf->pcmlengths[link*2+1];
  152183. time_total-=ov_time_total(vf,link);
  152184. if(seconds>=time_total)break;
  152185. }
  152186. /* enough information to convert time offset to pcm offset */
  152187. {
  152188. ogg_int64_t target=pcm_total+(seconds-time_total)*vf->vi[link].rate;
  152189. return(ov_pcm_seek_page(vf,target));
  152190. }
  152191. }
  152192. /* tell the current stream offset cursor. Note that seek followed by
  152193. tell will likely not give the set offset due to caching */
  152194. ogg_int64_t ov_raw_tell(OggVorbis_File *vf){
  152195. if(vf->ready_state<OPENED)return(OV_EINVAL);
  152196. return(vf->offset);
  152197. }
  152198. /* return PCM offset (sample) of next PCM sample to be read */
  152199. ogg_int64_t ov_pcm_tell(OggVorbis_File *vf){
  152200. if(vf->ready_state<OPENED)return(OV_EINVAL);
  152201. return(vf->pcm_offset);
  152202. }
  152203. /* return time offset (seconds) of next PCM sample to be read */
  152204. double ov_time_tell(OggVorbis_File *vf){
  152205. int link=0;
  152206. ogg_int64_t pcm_total=0;
  152207. double time_total=0.f;
  152208. if(vf->ready_state<OPENED)return(OV_EINVAL);
  152209. if(vf->seekable){
  152210. pcm_total=ov_pcm_total(vf,-1);
  152211. time_total=ov_time_total(vf,-1);
  152212. /* which bitstream section does this time offset occur in? */
  152213. for(link=vf->links-1;link>=0;link--){
  152214. pcm_total-=vf->pcmlengths[link*2+1];
  152215. time_total-=ov_time_total(vf,link);
  152216. if(vf->pcm_offset>=pcm_total)break;
  152217. }
  152218. }
  152219. return((double)time_total+(double)(vf->pcm_offset-pcm_total)/vf->vi[link].rate);
  152220. }
  152221. /* link: -1) return the vorbis_info struct for the bitstream section
  152222. currently being decoded
  152223. 0-n) to request information for a specific bitstream section
  152224. In the case of a non-seekable bitstream, any call returns the
  152225. current bitstream. NULL in the case that the machine is not
  152226. initialized */
  152227. vorbis_info *ov_info(OggVorbis_File *vf,int link){
  152228. if(vf->seekable){
  152229. if(link<0)
  152230. if(vf->ready_state>=STREAMSET)
  152231. return vf->vi+vf->current_link;
  152232. else
  152233. return vf->vi;
  152234. else
  152235. if(link>=vf->links)
  152236. return NULL;
  152237. else
  152238. return vf->vi+link;
  152239. }else{
  152240. return vf->vi;
  152241. }
  152242. }
  152243. /* grr, strong typing, grr, no templates/inheritence, grr */
  152244. vorbis_comment *ov_comment(OggVorbis_File *vf,int link){
  152245. if(vf->seekable){
  152246. if(link<0)
  152247. if(vf->ready_state>=STREAMSET)
  152248. return vf->vc+vf->current_link;
  152249. else
  152250. return vf->vc;
  152251. else
  152252. if(link>=vf->links)
  152253. return NULL;
  152254. else
  152255. return vf->vc+link;
  152256. }else{
  152257. return vf->vc;
  152258. }
  152259. }
  152260. static int host_is_big_endian() {
  152261. ogg_int32_t pattern = 0xfeedface; /* deadbeef */
  152262. unsigned char *bytewise = (unsigned char *)&pattern;
  152263. if (bytewise[0] == 0xfe) return 1;
  152264. return 0;
  152265. }
  152266. /* up to this point, everything could more or less hide the multiple
  152267. logical bitstream nature of chaining from the toplevel application
  152268. if the toplevel application didn't particularly care. However, at
  152269. the point that we actually read audio back, the multiple-section
  152270. nature must surface: Multiple bitstream sections do not necessarily
  152271. have to have the same number of channels or sampling rate.
  152272. ov_read returns the sequential logical bitstream number currently
  152273. being decoded along with the PCM data in order that the toplevel
  152274. application can take action on channel/sample rate changes. This
  152275. number will be incremented even for streamed (non-seekable) streams
  152276. (for seekable streams, it represents the actual logical bitstream
  152277. index within the physical bitstream. Note that the accessor
  152278. functions above are aware of this dichotomy).
  152279. input values: buffer) a buffer to hold packed PCM data for return
  152280. length) the byte length requested to be placed into buffer
  152281. bigendianp) should the data be packed LSB first (0) or
  152282. MSB first (1)
  152283. word) word size for output. currently 1 (byte) or
  152284. 2 (16 bit short)
  152285. return values: <0) error/hole in data (OV_HOLE), partial open (OV_EINVAL)
  152286. 0) EOF
  152287. n) number of bytes of PCM actually returned. The
  152288. below works on a packet-by-packet basis, so the
  152289. return length is not related to the 'length' passed
  152290. in, just guaranteed to fit.
  152291. *section) set to the logical bitstream number */
  152292. long ov_read(OggVorbis_File *vf,char *buffer,int length,
  152293. int bigendianp,int word,int sgned,int *bitstream){
  152294. int i,j;
  152295. int host_endian = host_is_big_endian();
  152296. float **pcm;
  152297. long samples;
  152298. if(vf->ready_state<OPENED)return(OV_EINVAL);
  152299. while(1){
  152300. if(vf->ready_state==INITSET){
  152301. samples=vorbis_synthesis_pcmout(&vf->vd,&pcm);
  152302. if(samples)break;
  152303. }
  152304. /* suck in another packet */
  152305. {
  152306. int ret=_fetch_and_process_packet(vf,NULL,1,1);
  152307. if(ret==OV_EOF)
  152308. return(0);
  152309. if(ret<=0)
  152310. return(ret);
  152311. }
  152312. }
  152313. if(samples>0){
  152314. /* yay! proceed to pack data into the byte buffer */
  152315. long channels=ov_info(vf,-1)->channels;
  152316. long bytespersample=word * channels;
  152317. vorbis_fpu_control fpu;
  152318. (void) fpu; // (to avoid a warning about it being unused)
  152319. if(samples>length/bytespersample)samples=length/bytespersample;
  152320. if(samples <= 0)
  152321. return OV_EINVAL;
  152322. /* a tight loop to pack each size */
  152323. {
  152324. int val;
  152325. if(word==1){
  152326. int off=(sgned?0:128);
  152327. vorbis_fpu_setround(&fpu);
  152328. for(j=0;j<samples;j++)
  152329. for(i=0;i<channels;i++){
  152330. val=vorbis_ftoi(pcm[i][j]*128.f);
  152331. if(val>127)val=127;
  152332. else if(val<-128)val=-128;
  152333. *buffer++=val+off;
  152334. }
  152335. vorbis_fpu_restore(fpu);
  152336. }else{
  152337. int off=(sgned?0:32768);
  152338. if(host_endian==bigendianp){
  152339. if(sgned){
  152340. vorbis_fpu_setround(&fpu);
  152341. for(i=0;i<channels;i++) { /* It's faster in this order */
  152342. float *src=pcm[i];
  152343. short *dest=((short *)buffer)+i;
  152344. for(j=0;j<samples;j++) {
  152345. val=vorbis_ftoi(src[j]*32768.f);
  152346. if(val>32767)val=32767;
  152347. else if(val<-32768)val=-32768;
  152348. *dest=val;
  152349. dest+=channels;
  152350. }
  152351. }
  152352. vorbis_fpu_restore(fpu);
  152353. }else{
  152354. vorbis_fpu_setround(&fpu);
  152355. for(i=0;i<channels;i++) {
  152356. float *src=pcm[i];
  152357. short *dest=((short *)buffer)+i;
  152358. for(j=0;j<samples;j++) {
  152359. val=vorbis_ftoi(src[j]*32768.f);
  152360. if(val>32767)val=32767;
  152361. else if(val<-32768)val=-32768;
  152362. *dest=val+off;
  152363. dest+=channels;
  152364. }
  152365. }
  152366. vorbis_fpu_restore(fpu);
  152367. }
  152368. }else if(bigendianp){
  152369. vorbis_fpu_setround(&fpu);
  152370. for(j=0;j<samples;j++)
  152371. for(i=0;i<channels;i++){
  152372. val=vorbis_ftoi(pcm[i][j]*32768.f);
  152373. if(val>32767)val=32767;
  152374. else if(val<-32768)val=-32768;
  152375. val+=off;
  152376. *buffer++=(val>>8);
  152377. *buffer++=(val&0xff);
  152378. }
  152379. vorbis_fpu_restore(fpu);
  152380. }else{
  152381. int val;
  152382. vorbis_fpu_setround(&fpu);
  152383. for(j=0;j<samples;j++)
  152384. for(i=0;i<channels;i++){
  152385. val=vorbis_ftoi(pcm[i][j]*32768.f);
  152386. if(val>32767)val=32767;
  152387. else if(val<-32768)val=-32768;
  152388. val+=off;
  152389. *buffer++=(val&0xff);
  152390. *buffer++=(val>>8);
  152391. }
  152392. vorbis_fpu_restore(fpu);
  152393. }
  152394. }
  152395. }
  152396. vorbis_synthesis_read(&vf->vd,samples);
  152397. vf->pcm_offset+=samples;
  152398. if(bitstream)*bitstream=vf->current_link;
  152399. return(samples*bytespersample);
  152400. }else{
  152401. return(samples);
  152402. }
  152403. }
  152404. /* input values: pcm_channels) a float vector per channel of output
  152405. length) the sample length being read by the app
  152406. return values: <0) error/hole in data (OV_HOLE), partial open (OV_EINVAL)
  152407. 0) EOF
  152408. n) number of samples of PCM actually returned. The
  152409. below works on a packet-by-packet basis, so the
  152410. return length is not related to the 'length' passed
  152411. in, just guaranteed to fit.
  152412. *section) set to the logical bitstream number */
  152413. long ov_read_float(OggVorbis_File *vf,float ***pcm_channels,int length,
  152414. int *bitstream){
  152415. if(vf->ready_state<OPENED)return(OV_EINVAL);
  152416. while(1){
  152417. if(vf->ready_state==INITSET){
  152418. float **pcm;
  152419. long samples=vorbis_synthesis_pcmout(&vf->vd,&pcm);
  152420. if(samples){
  152421. if(pcm_channels)*pcm_channels=pcm;
  152422. if(samples>length)samples=length;
  152423. vorbis_synthesis_read(&vf->vd,samples);
  152424. vf->pcm_offset+=samples;
  152425. if(bitstream)*bitstream=vf->current_link;
  152426. return samples;
  152427. }
  152428. }
  152429. /* suck in another packet */
  152430. {
  152431. int ret=_fetch_and_process_packet(vf,NULL,1,1);
  152432. if(ret==OV_EOF)return(0);
  152433. if(ret<=0)return(ret);
  152434. }
  152435. }
  152436. }
  152437. extern float *vorbis_window(vorbis_dsp_state *v,int W);
  152438. extern void _analysis_output_always(const char *base,int i,float *v,int n,int bark,int dB,
  152439. ogg_int64_t off);
  152440. static void _ov_splice(float **pcm,float **lappcm,
  152441. int n1, int n2,
  152442. int ch1, int ch2,
  152443. float *w1, float *w2){
  152444. int i,j;
  152445. float *w=w1;
  152446. int n=n1;
  152447. if(n1>n2){
  152448. n=n2;
  152449. w=w2;
  152450. }
  152451. /* splice */
  152452. for(j=0;j<ch1 && j<ch2;j++){
  152453. float *s=lappcm[j];
  152454. float *d=pcm[j];
  152455. for(i=0;i<n;i++){
  152456. float wd=w[i]*w[i];
  152457. float ws=1.-wd;
  152458. d[i]=d[i]*wd + s[i]*ws;
  152459. }
  152460. }
  152461. /* window from zero */
  152462. for(;j<ch2;j++){
  152463. float *d=pcm[j];
  152464. for(i=0;i<n;i++){
  152465. float wd=w[i]*w[i];
  152466. d[i]=d[i]*wd;
  152467. }
  152468. }
  152469. }
  152470. /* make sure vf is INITSET */
  152471. static int _ov_initset(OggVorbis_File *vf){
  152472. while(1){
  152473. if(vf->ready_state==INITSET)break;
  152474. /* suck in another packet */
  152475. {
  152476. int ret=_fetch_and_process_packet(vf,NULL,1,0);
  152477. if(ret<0 && ret!=OV_HOLE)return(ret);
  152478. }
  152479. }
  152480. return 0;
  152481. }
  152482. /* make sure vf is INITSET and that we have a primed buffer; if
  152483. we're crosslapping at a stream section boundary, this also makes
  152484. sure we're sanity checking against the right stream information */
  152485. static int _ov_initprime(OggVorbis_File *vf){
  152486. vorbis_dsp_state *vd=&vf->vd;
  152487. while(1){
  152488. if(vf->ready_state==INITSET)
  152489. if(vorbis_synthesis_pcmout(vd,NULL))break;
  152490. /* suck in another packet */
  152491. {
  152492. int ret=_fetch_and_process_packet(vf,NULL,1,0);
  152493. if(ret<0 && ret!=OV_HOLE)return(ret);
  152494. }
  152495. }
  152496. return 0;
  152497. }
  152498. /* grab enough data for lapping from vf; this may be in the form of
  152499. unreturned, already-decoded pcm, remaining PCM we will need to
  152500. decode, or synthetic postextrapolation from last packets. */
  152501. static void _ov_getlap(OggVorbis_File *vf,vorbis_info *vi,vorbis_dsp_state *vd,
  152502. float **lappcm,int lapsize){
  152503. int lapcount=0,i;
  152504. float **pcm;
  152505. /* try first to decode the lapping data */
  152506. while(lapcount<lapsize){
  152507. int samples=vorbis_synthesis_pcmout(vd,&pcm);
  152508. if(samples){
  152509. if(samples>lapsize-lapcount)samples=lapsize-lapcount;
  152510. for(i=0;i<vi->channels;i++)
  152511. memcpy(lappcm[i]+lapcount,pcm[i],sizeof(**pcm)*samples);
  152512. lapcount+=samples;
  152513. vorbis_synthesis_read(vd,samples);
  152514. }else{
  152515. /* suck in another packet */
  152516. int ret=_fetch_and_process_packet(vf,NULL,1,0); /* do *not* span */
  152517. if(ret==OV_EOF)break;
  152518. }
  152519. }
  152520. if(lapcount<lapsize){
  152521. /* failed to get lapping data from normal decode; pry it from the
  152522. postextrapolation buffering, or the second half of the MDCT
  152523. from the last packet */
  152524. int samples=vorbis_synthesis_lapout(&vf->vd,&pcm);
  152525. if(samples==0){
  152526. for(i=0;i<vi->channels;i++)
  152527. memset(lappcm[i]+lapcount,0,sizeof(**pcm)*lapsize-lapcount);
  152528. lapcount=lapsize;
  152529. }else{
  152530. if(samples>lapsize-lapcount)samples=lapsize-lapcount;
  152531. for(i=0;i<vi->channels;i++)
  152532. memcpy(lappcm[i]+lapcount,pcm[i],sizeof(**pcm)*samples);
  152533. lapcount+=samples;
  152534. }
  152535. }
  152536. }
  152537. /* this sets up crosslapping of a sample by using trailing data from
  152538. sample 1 and lapping it into the windowing buffer of sample 2 */
  152539. int ov_crosslap(OggVorbis_File *vf1, OggVorbis_File *vf2){
  152540. vorbis_info *vi1,*vi2;
  152541. float **lappcm;
  152542. float **pcm;
  152543. float *w1,*w2;
  152544. int n1,n2,i,ret,hs1,hs2;
  152545. if(vf1==vf2)return(0); /* degenerate case */
  152546. if(vf1->ready_state<OPENED)return(OV_EINVAL);
  152547. if(vf2->ready_state<OPENED)return(OV_EINVAL);
  152548. /* the relevant overlap buffers must be pre-checked and pre-primed
  152549. before looking at settings in the event that priming would cross
  152550. a bitstream boundary. So, do it now */
  152551. ret=_ov_initset(vf1);
  152552. if(ret)return(ret);
  152553. ret=_ov_initprime(vf2);
  152554. if(ret)return(ret);
  152555. vi1=ov_info(vf1,-1);
  152556. vi2=ov_info(vf2,-1);
  152557. hs1=ov_halfrate_p(vf1);
  152558. hs2=ov_halfrate_p(vf2);
  152559. lappcm=(float**) alloca(sizeof(*lappcm)*vi1->channels);
  152560. n1=vorbis_info_blocksize(vi1,0)>>(1+hs1);
  152561. n2=vorbis_info_blocksize(vi2,0)>>(1+hs2);
  152562. w1=vorbis_window(&vf1->vd,0);
  152563. w2=vorbis_window(&vf2->vd,0);
  152564. for(i=0;i<vi1->channels;i++)
  152565. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  152566. _ov_getlap(vf1,vi1,&vf1->vd,lappcm,n1);
  152567. /* have a lapping buffer from vf1; now to splice it into the lapping
  152568. buffer of vf2 */
  152569. /* consolidate and expose the buffer. */
  152570. vorbis_synthesis_lapout(&vf2->vd,&pcm);
  152571. _analysis_output_always("pcmL",0,pcm[0],n1*2,0,0,0);
  152572. _analysis_output_always("pcmR",0,pcm[1],n1*2,0,0,0);
  152573. /* splice */
  152574. _ov_splice(pcm,lappcm,n1,n2,vi1->channels,vi2->channels,w1,w2);
  152575. /* done */
  152576. return(0);
  152577. }
  152578. static int _ov_64_seek_lap(OggVorbis_File *vf,ogg_int64_t pos,
  152579. int (*localseek)(OggVorbis_File *,ogg_int64_t)){
  152580. vorbis_info *vi;
  152581. float **lappcm;
  152582. float **pcm;
  152583. float *w1,*w2;
  152584. int n1,n2,ch1,ch2,hs;
  152585. int i,ret;
  152586. if(vf->ready_state<OPENED)return(OV_EINVAL);
  152587. ret=_ov_initset(vf);
  152588. if(ret)return(ret);
  152589. vi=ov_info(vf,-1);
  152590. hs=ov_halfrate_p(vf);
  152591. ch1=vi->channels;
  152592. n1=vorbis_info_blocksize(vi,0)>>(1+hs);
  152593. w1=vorbis_window(&vf->vd,0); /* window arrays from libvorbis are
  152594. persistent; even if the decode state
  152595. from this link gets dumped, this
  152596. window array continues to exist */
  152597. lappcm=(float**) alloca(sizeof(*lappcm)*ch1);
  152598. for(i=0;i<ch1;i++)
  152599. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  152600. _ov_getlap(vf,vi,&vf->vd,lappcm,n1);
  152601. /* have lapping data; seek and prime the buffer */
  152602. ret=localseek(vf,pos);
  152603. if(ret)return ret;
  152604. ret=_ov_initprime(vf);
  152605. if(ret)return(ret);
  152606. /* Guard against cross-link changes; they're perfectly legal */
  152607. vi=ov_info(vf,-1);
  152608. ch2=vi->channels;
  152609. n2=vorbis_info_blocksize(vi,0)>>(1+hs);
  152610. w2=vorbis_window(&vf->vd,0);
  152611. /* consolidate and expose the buffer. */
  152612. vorbis_synthesis_lapout(&vf->vd,&pcm);
  152613. /* splice */
  152614. _ov_splice(pcm,lappcm,n1,n2,ch1,ch2,w1,w2);
  152615. /* done */
  152616. return(0);
  152617. }
  152618. int ov_raw_seek_lap(OggVorbis_File *vf,ogg_int64_t pos){
  152619. return _ov_64_seek_lap(vf,pos,ov_raw_seek);
  152620. }
  152621. int ov_pcm_seek_lap(OggVorbis_File *vf,ogg_int64_t pos){
  152622. return _ov_64_seek_lap(vf,pos,ov_pcm_seek);
  152623. }
  152624. int ov_pcm_seek_page_lap(OggVorbis_File *vf,ogg_int64_t pos){
  152625. return _ov_64_seek_lap(vf,pos,ov_pcm_seek_page);
  152626. }
  152627. static int _ov_d_seek_lap(OggVorbis_File *vf,double pos,
  152628. int (*localseek)(OggVorbis_File *,double)){
  152629. vorbis_info *vi;
  152630. float **lappcm;
  152631. float **pcm;
  152632. float *w1,*w2;
  152633. int n1,n2,ch1,ch2,hs;
  152634. int i,ret;
  152635. if(vf->ready_state<OPENED)return(OV_EINVAL);
  152636. ret=_ov_initset(vf);
  152637. if(ret)return(ret);
  152638. vi=ov_info(vf,-1);
  152639. hs=ov_halfrate_p(vf);
  152640. ch1=vi->channels;
  152641. n1=vorbis_info_blocksize(vi,0)>>(1+hs);
  152642. w1=vorbis_window(&vf->vd,0); /* window arrays from libvorbis are
  152643. persistent; even if the decode state
  152644. from this link gets dumped, this
  152645. window array continues to exist */
  152646. lappcm=(float**) alloca(sizeof(*lappcm)*ch1);
  152647. for(i=0;i<ch1;i++)
  152648. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  152649. _ov_getlap(vf,vi,&vf->vd,lappcm,n1);
  152650. /* have lapping data; seek and prime the buffer */
  152651. ret=localseek(vf,pos);
  152652. if(ret)return ret;
  152653. ret=_ov_initprime(vf);
  152654. if(ret)return(ret);
  152655. /* Guard against cross-link changes; they're perfectly legal */
  152656. vi=ov_info(vf,-1);
  152657. ch2=vi->channels;
  152658. n2=vorbis_info_blocksize(vi,0)>>(1+hs);
  152659. w2=vorbis_window(&vf->vd,0);
  152660. /* consolidate and expose the buffer. */
  152661. vorbis_synthesis_lapout(&vf->vd,&pcm);
  152662. /* splice */
  152663. _ov_splice(pcm,lappcm,n1,n2,ch1,ch2,w1,w2);
  152664. /* done */
  152665. return(0);
  152666. }
  152667. int ov_time_seek_lap(OggVorbis_File *vf,double pos){
  152668. return _ov_d_seek_lap(vf,pos,ov_time_seek);
  152669. }
  152670. int ov_time_seek_page_lap(OggVorbis_File *vf,double pos){
  152671. return _ov_d_seek_lap(vf,pos,ov_time_seek_page);
  152672. }
  152673. #endif
  152674. /********* End of inlined file: vorbisfile.c *********/
  152675. /********* Start of inlined file: window.c *********/
  152676. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  152677. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  152678. // tasks..
  152679. #ifdef _MSC_VER
  152680. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  152681. #endif
  152682. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  152683. #if JUCE_USE_OGGVORBIS
  152684. #include <stdlib.h>
  152685. #include <math.h>
  152686. static float vwin64[32] = {
  152687. 0.0009460463F, 0.0085006468F, 0.0235352254F, 0.0458950567F,
  152688. 0.0753351908F, 0.1115073077F, 0.1539457973F, 0.2020557475F,
  152689. 0.2551056759F, 0.3122276645F, 0.3724270287F, 0.4346027792F,
  152690. 0.4975789974F, 0.5601459521F, 0.6211085051F, 0.6793382689F,
  152691. 0.7338252629F, 0.7837245849F, 0.8283939355F, 0.8674186656F,
  152692. 0.9006222429F, 0.9280614787F, 0.9500073081F, 0.9669131782F,
  152693. 0.9793740220F, 0.9880792941F, 0.9937636139F, 0.9971582668F,
  152694. 0.9989462667F, 0.9997230082F, 0.9999638688F, 0.9999995525F,
  152695. };
  152696. static float vwin128[64] = {
  152697. 0.0002365472F, 0.0021280687F, 0.0059065254F, 0.0115626550F,
  152698. 0.0190823442F, 0.0284463735F, 0.0396300935F, 0.0526030430F,
  152699. 0.0673285281F, 0.0837631763F, 0.1018564887F, 0.1215504095F,
  152700. 0.1427789367F, 0.1654677960F, 0.1895342001F, 0.2148867160F,
  152701. 0.2414252576F, 0.2690412240F, 0.2976177952F, 0.3270303960F,
  152702. 0.3571473350F, 0.3878306189F, 0.4189369387F, 0.4503188188F,
  152703. 0.4818259135F, 0.5133064334F, 0.5446086751F, 0.5755826278F,
  152704. 0.6060816248F, 0.6359640047F, 0.6650947483F, 0.6933470543F,
  152705. 0.7206038179F, 0.7467589810F, 0.7717187213F, 0.7954024542F,
  152706. 0.8177436264F, 0.8386902831F, 0.8582053981F, 0.8762669622F,
  152707. 0.8928678298F, 0.9080153310F, 0.9217306608F, 0.9340480615F,
  152708. 0.9450138200F, 0.9546851041F, 0.9631286621F, 0.9704194171F,
  152709. 0.9766389810F, 0.9818741197F, 0.9862151938F, 0.9897546035F,
  152710. 0.9925852598F, 0.9947991032F, 0.9964856900F, 0.9977308602F,
  152711. 0.9986155015F, 0.9992144193F, 0.9995953200F, 0.9998179155F,
  152712. 0.9999331503F, 0.9999825563F, 0.9999977357F, 0.9999999720F,
  152713. };
  152714. static float vwin256[128] = {
  152715. 0.0000591390F, 0.0005321979F, 0.0014780301F, 0.0028960636F,
  152716. 0.0047854363F, 0.0071449926F, 0.0099732775F, 0.0132685298F,
  152717. 0.0170286741F, 0.0212513119F, 0.0259337111F, 0.0310727950F,
  152718. 0.0366651302F, 0.0427069140F, 0.0491939614F, 0.0561216907F,
  152719. 0.0634851102F, 0.0712788035F, 0.0794969160F, 0.0881331402F,
  152720. 0.0971807028F, 0.1066323515F, 0.1164803426F, 0.1267164297F,
  152721. 0.1373318534F, 0.1483173323F, 0.1596630553F, 0.1713586755F,
  152722. 0.1833933062F, 0.1957555184F, 0.2084333404F, 0.2214142599F,
  152723. 0.2346852280F, 0.2482326664F, 0.2620424757F, 0.2761000481F,
  152724. 0.2903902813F, 0.3048975959F, 0.3196059553F, 0.3344988887F,
  152725. 0.3495595160F, 0.3647705766F, 0.3801144597F, 0.3955732382F,
  152726. 0.4111287047F, 0.4267624093F, 0.4424557009F, 0.4581897696F,
  152727. 0.4739456913F, 0.4897044744F, 0.5054471075F, 0.5211546088F,
  152728. 0.5368080763F, 0.5523887395F, 0.5678780103F, 0.5832575361F,
  152729. 0.5985092508F, 0.6136154277F, 0.6285587300F, 0.6433222619F,
  152730. 0.6578896175F, 0.6722449294F, 0.6863729144F, 0.7002589187F,
  152731. 0.7138889597F, 0.7272497662F, 0.7403288154F, 0.7531143679F,
  152732. 0.7655954985F, 0.7777621249F, 0.7896050322F, 0.8011158947F,
  152733. 0.8122872932F, 0.8231127294F, 0.8335866365F, 0.8437043850F,
  152734. 0.8534622861F, 0.8628575905F, 0.8718884835F, 0.8805540765F,
  152735. 0.8888543947F, 0.8967903616F, 0.9043637797F, 0.9115773078F,
  152736. 0.9184344360F, 0.9249394562F, 0.9310974312F, 0.9369141608F,
  152737. 0.9423961446F, 0.9475505439F, 0.9523851406F, 0.9569082947F,
  152738. 0.9611289005F, 0.9650563408F, 0.9687004405F, 0.9720714191F,
  152739. 0.9751798427F, 0.9780365753F, 0.9806527301F, 0.9830396204F,
  152740. 0.9852087111F, 0.9871715701F, 0.9889398207F, 0.9905250941F,
  152741. 0.9919389832F, 0.9931929973F, 0.9942985174F, 0.9952667537F,
  152742. 0.9961087037F, 0.9968351119F, 0.9974564312F, 0.9979827858F,
  152743. 0.9984239359F, 0.9987892441F, 0.9990876435F, 0.9993276081F,
  152744. 0.9995171241F, 0.9996636648F, 0.9997741654F, 0.9998550016F,
  152745. 0.9999119692F, 0.9999502656F, 0.9999744742F, 0.9999885497F,
  152746. 0.9999958064F, 0.9999989077F, 0.9999998584F, 0.9999999983F,
  152747. };
  152748. static float vwin512[256] = {
  152749. 0.0000147849F, 0.0001330607F, 0.0003695946F, 0.0007243509F,
  152750. 0.0011972759F, 0.0017882983F, 0.0024973285F, 0.0033242588F,
  152751. 0.0042689632F, 0.0053312973F, 0.0065110982F, 0.0078081841F,
  152752. 0.0092223540F, 0.0107533880F, 0.0124010466F, 0.0141650703F,
  152753. 0.0160451800F, 0.0180410758F, 0.0201524373F, 0.0223789233F,
  152754. 0.0247201710F, 0.0271757958F, 0.0297453914F, 0.0324285286F,
  152755. 0.0352247556F, 0.0381335972F, 0.0411545545F, 0.0442871045F,
  152756. 0.0475306997F, 0.0508847676F, 0.0543487103F, 0.0579219038F,
  152757. 0.0616036982F, 0.0653934164F, 0.0692903546F, 0.0732937809F,
  152758. 0.0774029356F, 0.0816170305F, 0.0859352485F, 0.0903567428F,
  152759. 0.0948806375F, 0.0995060259F, 0.1042319712F, 0.1090575056F,
  152760. 0.1139816300F, 0.1190033137F, 0.1241214941F, 0.1293350764F,
  152761. 0.1346429333F, 0.1400439046F, 0.1455367974F, 0.1511203852F,
  152762. 0.1567934083F, 0.1625545735F, 0.1684025537F, 0.1743359881F,
  152763. 0.1803534820F, 0.1864536069F, 0.1926349000F, 0.1988958650F,
  152764. 0.2052349715F, 0.2116506555F, 0.2181413191F, 0.2247053313F,
  152765. 0.2313410275F, 0.2380467105F, 0.2448206500F, 0.2516610835F,
  152766. 0.2585662164F, 0.2655342226F, 0.2725632448F, 0.2796513950F,
  152767. 0.2867967551F, 0.2939973773F, 0.3012512852F, 0.3085564739F,
  152768. 0.3159109111F, 0.3233125375F, 0.3307592680F, 0.3382489922F,
  152769. 0.3457795756F, 0.3533488602F, 0.3609546657F, 0.3685947904F,
  152770. 0.3762670121F, 0.3839690896F, 0.3916987634F, 0.3994537572F,
  152771. 0.4072317788F, 0.4150305215F, 0.4228476653F, 0.4306808783F,
  152772. 0.4385278181F, 0.4463861329F, 0.4542534630F, 0.4621274424F,
  152773. 0.4700057001F, 0.4778858615F, 0.4857655502F, 0.4936423891F,
  152774. 0.5015140023F, 0.5093780165F, 0.5172320626F, 0.5250737772F,
  152775. 0.5329008043F, 0.5407107971F, 0.5485014192F, 0.5562703465F,
  152776. 0.5640152688F, 0.5717338914F, 0.5794239366F, 0.5870831457F,
  152777. 0.5947092801F, 0.6023001235F, 0.6098534829F, 0.6173671907F,
  152778. 0.6248391059F, 0.6322671161F, 0.6396491384F, 0.6469831217F,
  152779. 0.6542670475F, 0.6614989319F, 0.6686768267F, 0.6757988210F,
  152780. 0.6828630426F, 0.6898676592F, 0.6968108799F, 0.7036909564F,
  152781. 0.7105061843F, 0.7172549043F, 0.7239355032F, 0.7305464154F,
  152782. 0.7370861235F, 0.7435531598F, 0.7499461068F, 0.7562635986F,
  152783. 0.7625043214F, 0.7686670148F, 0.7747504721F, 0.7807535410F,
  152784. 0.7866751247F, 0.7925141825F, 0.7982697296F, 0.8039408387F,
  152785. 0.8095266395F, 0.8150263196F, 0.8204391248F, 0.8257643590F,
  152786. 0.8310013848F, 0.8361496236F, 0.8412085555F, 0.8461777194F,
  152787. 0.8510567129F, 0.8558451924F, 0.8605428730F, 0.8651495278F,
  152788. 0.8696649882F, 0.8740891432F, 0.8784219392F, 0.8826633797F,
  152789. 0.8868135244F, 0.8908724888F, 0.8948404441F, 0.8987176157F,
  152790. 0.9025042831F, 0.9062007791F, 0.9098074886F, 0.9133248482F,
  152791. 0.9167533451F, 0.9200935163F, 0.9233459472F, 0.9265112712F,
  152792. 0.9295901680F, 0.9325833632F, 0.9354916263F, 0.9383157705F,
  152793. 0.9410566504F, 0.9437151618F, 0.9462922398F, 0.9487888576F,
  152794. 0.9512060252F, 0.9535447882F, 0.9558062262F, 0.9579914516F,
  152795. 0.9601016078F, 0.9621378683F, 0.9641014348F, 0.9659935361F,
  152796. 0.9678154261F, 0.9695683830F, 0.9712537071F, 0.9728727198F,
  152797. 0.9744267618F, 0.9759171916F, 0.9773453842F, 0.9787127293F,
  152798. 0.9800206298F, 0.9812705006F, 0.9824637665F, 0.9836018613F,
  152799. 0.9846862258F, 0.9857183066F, 0.9866995544F, 0.9876314227F,
  152800. 0.9885153662F, 0.9893528393F, 0.9901452948F, 0.9908941823F,
  152801. 0.9916009470F, 0.9922670279F, 0.9928938570F, 0.9934828574F,
  152802. 0.9940354423F, 0.9945530133F, 0.9950369595F, 0.9954886562F,
  152803. 0.9959094633F, 0.9963007242F, 0.9966637649F, 0.9969998925F,
  152804. 0.9973103939F, 0.9975965351F, 0.9978595598F, 0.9981006885F,
  152805. 0.9983211172F, 0.9985220166F, 0.9987045311F, 0.9988697776F,
  152806. 0.9990188449F, 0.9991527924F, 0.9992726499F, 0.9993794157F,
  152807. 0.9994740570F, 0.9995575079F, 0.9996306699F, 0.9996944099F,
  152808. 0.9997495605F, 0.9997969190F, 0.9998372465F, 0.9998712678F,
  152809. 0.9998996704F, 0.9999231041F, 0.9999421807F, 0.9999574732F,
  152810. 0.9999695157F, 0.9999788026F, 0.9999857885F, 0.9999908879F,
  152811. 0.9999944746F, 0.9999968817F, 0.9999984010F, 0.9999992833F,
  152812. 0.9999997377F, 0.9999999317F, 0.9999999911F, 0.9999999999F,
  152813. };
  152814. static float vwin1024[512] = {
  152815. 0.0000036962F, 0.0000332659F, 0.0000924041F, 0.0001811086F,
  152816. 0.0002993761F, 0.0004472021F, 0.0006245811F, 0.0008315063F,
  152817. 0.0010679699F, 0.0013339631F, 0.0016294757F, 0.0019544965F,
  152818. 0.0023090133F, 0.0026930125F, 0.0031064797F, 0.0035493989F,
  152819. 0.0040217533F, 0.0045235250F, 0.0050546946F, 0.0056152418F,
  152820. 0.0062051451F, 0.0068243817F, 0.0074729278F, 0.0081507582F,
  152821. 0.0088578466F, 0.0095941655F, 0.0103596863F, 0.0111543789F,
  152822. 0.0119782122F, 0.0128311538F, 0.0137131701F, 0.0146242260F,
  152823. 0.0155642855F, 0.0165333111F, 0.0175312640F, 0.0185581042F,
  152824. 0.0196137903F, 0.0206982797F, 0.0218115284F, 0.0229534910F,
  152825. 0.0241241208F, 0.0253233698F, 0.0265511886F, 0.0278075263F,
  152826. 0.0290923308F, 0.0304055484F, 0.0317471241F, 0.0331170013F,
  152827. 0.0345151222F, 0.0359414274F, 0.0373958560F, 0.0388783456F,
  152828. 0.0403888325F, 0.0419272511F, 0.0434935347F, 0.0450876148F,
  152829. 0.0467094213F, 0.0483588828F, 0.0500359261F, 0.0517404765F,
  152830. 0.0534724575F, 0.0552317913F, 0.0570183983F, 0.0588321971F,
  152831. 0.0606731048F, 0.0625410369F, 0.0644359070F, 0.0663576272F,
  152832. 0.0683061077F, 0.0702812571F, 0.0722829821F, 0.0743111878F,
  152833. 0.0763657775F, 0.0784466526F, 0.0805537129F, 0.0826868561F,
  152834. 0.0848459782F, 0.0870309736F, 0.0892417345F, 0.0914781514F,
  152835. 0.0937401128F, 0.0960275056F, 0.0983402145F, 0.1006781223F,
  152836. 0.1030411101F, 0.1054290568F, 0.1078418397F, 0.1102793336F,
  152837. 0.1127414119F, 0.1152279457F, 0.1177388042F, 0.1202738544F,
  152838. 0.1228329618F, 0.1254159892F, 0.1280227980F, 0.1306532471F,
  152839. 0.1333071937F, 0.1359844927F, 0.1386849970F, 0.1414085575F,
  152840. 0.1441550230F, 0.1469242403F, 0.1497160539F, 0.1525303063F,
  152841. 0.1553668381F, 0.1582254875F, 0.1611060909F, 0.1640084822F,
  152842. 0.1669324936F, 0.1698779549F, 0.1728446939F, 0.1758325362F,
  152843. 0.1788413055F, 0.1818708232F, 0.1849209084F, 0.1879913785F,
  152844. 0.1910820485F, 0.1941927312F, 0.1973232376F, 0.2004733764F,
  152845. 0.2036429541F, 0.2068317752F, 0.2100396421F, 0.2132663552F,
  152846. 0.2165117125F, 0.2197755102F, 0.2230575422F, 0.2263576007F,
  152847. 0.2296754753F, 0.2330109540F, 0.2363638225F, 0.2397338646F,
  152848. 0.2431208619F, 0.2465245941F, 0.2499448389F, 0.2533813719F,
  152849. 0.2568339669F, 0.2603023956F, 0.2637864277F, 0.2672858312F,
  152850. 0.2708003718F, 0.2743298135F, 0.2778739186F, 0.2814324472F,
  152851. 0.2850051576F, 0.2885918065F, 0.2921921485F, 0.2958059366F,
  152852. 0.2994329219F, 0.3030728538F, 0.3067254799F, 0.3103905462F,
  152853. 0.3140677969F, 0.3177569747F, 0.3214578205F, 0.3251700736F,
  152854. 0.3288934718F, 0.3326277513F, 0.3363726468F, 0.3401278914F,
  152855. 0.3438932168F, 0.3476683533F, 0.3514530297F, 0.3552469734F,
  152856. 0.3590499106F, 0.3628615659F, 0.3666816630F, 0.3705099239F,
  152857. 0.3743460698F, 0.3781898204F, 0.3820408945F, 0.3858990095F,
  152858. 0.3897638820F, 0.3936352274F, 0.3975127601F, 0.4013961936F,
  152859. 0.4052852405F, 0.4091796123F, 0.4130790198F, 0.4169831732F,
  152860. 0.4208917815F, 0.4248045534F, 0.4287211965F, 0.4326414181F,
  152861. 0.4365649248F, 0.4404914225F, 0.4444206167F, 0.4483522125F,
  152862. 0.4522859146F, 0.4562214270F, 0.4601584538F, 0.4640966984F,
  152863. 0.4680358644F, 0.4719756548F, 0.4759157726F, 0.4798559209F,
  152864. 0.4837958024F, 0.4877351199F, 0.4916735765F, 0.4956108751F,
  152865. 0.4995467188F, 0.5034808109F, 0.5074128550F, 0.5113425550F,
  152866. 0.5152696149F, 0.5191937395F, 0.5231146336F, 0.5270320028F,
  152867. 0.5309455530F, 0.5348549910F, 0.5387600239F, 0.5426603597F,
  152868. 0.5465557070F, 0.5504457754F, 0.5543302752F, 0.5582089175F,
  152869. 0.5620814145F, 0.5659474793F, 0.5698068262F, 0.5736591704F,
  152870. 0.5775042283F, 0.5813417176F, 0.5851713571F, 0.5889928670F,
  152871. 0.5928059689F, 0.5966103856F, 0.6004058415F, 0.6041920626F,
  152872. 0.6079687761F, 0.6117357113F, 0.6154925986F, 0.6192391705F,
  152873. 0.6229751612F, 0.6267003064F, 0.6304143441F, 0.6341170137F,
  152874. 0.6378080569F, 0.6414872173F, 0.6451542405F, 0.6488088741F,
  152875. 0.6524508681F, 0.6560799742F, 0.6596959469F, 0.6632985424F,
  152876. 0.6668875197F, 0.6704626398F, 0.6740236662F, 0.6775703649F,
  152877. 0.6811025043F, 0.6846198554F, 0.6881221916F, 0.6916092892F,
  152878. 0.6950809269F, 0.6985368861F, 0.7019769510F, 0.7054009085F,
  152879. 0.7088085484F, 0.7121996632F, 0.7155740484F, 0.7189315023F,
  152880. 0.7222718263F, 0.7255948245F, 0.7289003043F, 0.7321880760F,
  152881. 0.7354579530F, 0.7387097518F, 0.7419432921F, 0.7451583966F,
  152882. 0.7483548915F, 0.7515326059F, 0.7546913723F, 0.7578310265F,
  152883. 0.7609514077F, 0.7640523581F, 0.7671337237F, 0.7701953535F,
  152884. 0.7732371001F, 0.7762588195F, 0.7792603711F, 0.7822416178F,
  152885. 0.7852024259F, 0.7881426654F, 0.7910622097F, 0.7939609356F,
  152886. 0.7968387237F, 0.7996954579F, 0.8025310261F, 0.8053453193F,
  152887. 0.8081382324F, 0.8109096638F, 0.8136595156F, 0.8163876936F,
  152888. 0.8190941071F, 0.8217786690F, 0.8244412960F, 0.8270819086F,
  152889. 0.8297004305F, 0.8322967896F, 0.8348709171F, 0.8374227481F,
  152890. 0.8399522213F, 0.8424592789F, 0.8449438672F, 0.8474059356F,
  152891. 0.8498454378F, 0.8522623306F, 0.8546565748F, 0.8570281348F,
  152892. 0.8593769787F, 0.8617030779F, 0.8640064080F, 0.8662869477F,
  152893. 0.8685446796F, 0.8707795899F, 0.8729916682F, 0.8751809079F,
  152894. 0.8773473059F, 0.8794908626F, 0.8816115819F, 0.8837094713F,
  152895. 0.8857845418F, 0.8878368079F, 0.8898662874F, 0.8918730019F,
  152896. 0.8938569760F, 0.8958182380F, 0.8977568194F, 0.8996727552F,
  152897. 0.9015660837F, 0.9034368465F, 0.9052850885F, 0.9071108577F,
  152898. 0.9089142057F, 0.9106951869F, 0.9124538591F, 0.9141902832F,
  152899. 0.9159045233F, 0.9175966464F, 0.9192667228F, 0.9209148257F,
  152900. 0.9225410313F, 0.9241454187F, 0.9257280701F, 0.9272890704F,
  152901. 0.9288285075F, 0.9303464720F, 0.9318430576F, 0.9333183603F,
  152902. 0.9347724792F, 0.9362055158F, 0.9376175745F, 0.9390087622F,
  152903. 0.9403791881F, 0.9417289644F, 0.9430582055F, 0.9443670283F,
  152904. 0.9456555521F, 0.9469238986F, 0.9481721917F, 0.9494005577F,
  152905. 0.9506091252F, 0.9517980248F, 0.9529673894F, 0.9541173540F,
  152906. 0.9552480557F, 0.9563596334F, 0.9574522282F, 0.9585259830F,
  152907. 0.9595810428F, 0.9606175542F, 0.9616356656F, 0.9626355274F,
  152908. 0.9636172915F, 0.9645811114F, 0.9655271425F, 0.9664555414F,
  152909. 0.9673664664F, 0.9682600774F, 0.9691365355F, 0.9699960034F,
  152910. 0.9708386448F, 0.9716646250F, 0.9724741103F, 0.9732672685F,
  152911. 0.9740442683F, 0.9748052795F, 0.9755504729F, 0.9762800205F,
  152912. 0.9769940950F, 0.9776928703F, 0.9783765210F, 0.9790452223F,
  152913. 0.9796991504F, 0.9803384823F, 0.9809633954F, 0.9815740679F,
  152914. 0.9821706784F, 0.9827534063F, 0.9833224312F, 0.9838779332F,
  152915. 0.9844200928F, 0.9849490910F, 0.9854651087F, 0.9859683274F,
  152916. 0.9864589286F, 0.9869370940F, 0.9874030054F, 0.9878568447F,
  152917. 0.9882987937F, 0.9887290343F, 0.9891477481F, 0.9895551169F,
  152918. 0.9899513220F, 0.9903365446F, 0.9907109658F, 0.9910747662F,
  152919. 0.9914281260F, 0.9917712252F, 0.9921042433F, 0.9924273593F,
  152920. 0.9927407516F, 0.9930445982F, 0.9933390763F, 0.9936243626F,
  152921. 0.9939006331F, 0.9941680631F, 0.9944268269F, 0.9946770982F,
  152922. 0.9949190498F, 0.9951528537F, 0.9953786808F, 0.9955967011F,
  152923. 0.9958070836F, 0.9960099963F, 0.9962056061F, 0.9963940787F,
  152924. 0.9965755786F, 0.9967502693F, 0.9969183129F, 0.9970798704F,
  152925. 0.9972351013F, 0.9973841640F, 0.9975272151F, 0.9976644103F,
  152926. 0.9977959036F, 0.9979218476F, 0.9980423932F, 0.9981576901F,
  152927. 0.9982678862F, 0.9983731278F, 0.9984735596F, 0.9985693247F,
  152928. 0.9986605645F, 0.9987474186F, 0.9988300248F, 0.9989085193F,
  152929. 0.9989830364F, 0.9990537085F, 0.9991206662F, 0.9991840382F,
  152930. 0.9992439513F, 0.9993005303F, 0.9993538982F, 0.9994041757F,
  152931. 0.9994514817F, 0.9994959330F, 0.9995376444F, 0.9995767286F,
  152932. 0.9996132960F, 0.9996474550F, 0.9996793121F, 0.9997089710F,
  152933. 0.9997365339F, 0.9997621003F, 0.9997857677F, 0.9998076311F,
  152934. 0.9998277836F, 0.9998463156F, 0.9998633155F, 0.9998788692F,
  152935. 0.9998930603F, 0.9999059701F, 0.9999176774F, 0.9999282586F,
  152936. 0.9999377880F, 0.9999463370F, 0.9999539749F, 0.9999607685F,
  152937. 0.9999667820F, 0.9999720773F, 0.9999767136F, 0.9999807479F,
  152938. 0.9999842344F, 0.9999872249F, 0.9999897688F, 0.9999919127F,
  152939. 0.9999937009F, 0.9999951749F, 0.9999963738F, 0.9999973342F,
  152940. 0.9999980900F, 0.9999986724F, 0.9999991103F, 0.9999994297F,
  152941. 0.9999996543F, 0.9999998049F, 0.9999999000F, 0.9999999552F,
  152942. 0.9999999836F, 0.9999999957F, 0.9999999994F, 1.0000000000F,
  152943. };
  152944. static float vwin2048[1024] = {
  152945. 0.0000009241F, 0.0000083165F, 0.0000231014F, 0.0000452785F,
  152946. 0.0000748476F, 0.0001118085F, 0.0001561608F, 0.0002079041F,
  152947. 0.0002670379F, 0.0003335617F, 0.0004074748F, 0.0004887765F,
  152948. 0.0005774661F, 0.0006735427F, 0.0007770054F, 0.0008878533F,
  152949. 0.0010060853F, 0.0011317002F, 0.0012646969F, 0.0014050742F,
  152950. 0.0015528307F, 0.0017079650F, 0.0018704756F, 0.0020403610F,
  152951. 0.0022176196F, 0.0024022497F, 0.0025942495F, 0.0027936173F,
  152952. 0.0030003511F, 0.0032144490F, 0.0034359088F, 0.0036647286F,
  152953. 0.0039009061F, 0.0041444391F, 0.0043953253F, 0.0046535621F,
  152954. 0.0049191472F, 0.0051920781F, 0.0054723520F, 0.0057599664F,
  152955. 0.0060549184F, 0.0063572052F, 0.0066668239F, 0.0069837715F,
  152956. 0.0073080449F, 0.0076396410F, 0.0079785566F, 0.0083247884F,
  152957. 0.0086783330F, 0.0090391871F, 0.0094073470F, 0.0097828092F,
  152958. 0.0101655700F, 0.0105556258F, 0.0109529726F, 0.0113576065F,
  152959. 0.0117695237F, 0.0121887200F, 0.0126151913F, 0.0130489335F,
  152960. 0.0134899422F, 0.0139382130F, 0.0143937415F, 0.0148565233F,
  152961. 0.0153265536F, 0.0158038279F, 0.0162883413F, 0.0167800889F,
  152962. 0.0172790660F, 0.0177852675F, 0.0182986882F, 0.0188193231F,
  152963. 0.0193471668F, 0.0198822141F, 0.0204244594F, 0.0209738974F,
  152964. 0.0215305225F, 0.0220943289F, 0.0226653109F, 0.0232434627F,
  152965. 0.0238287784F, 0.0244212519F, 0.0250208772F, 0.0256276481F,
  152966. 0.0262415582F, 0.0268626014F, 0.0274907711F, 0.0281260608F,
  152967. 0.0287684638F, 0.0294179736F, 0.0300745833F, 0.0307382859F,
  152968. 0.0314090747F, 0.0320869424F, 0.0327718819F, 0.0334638860F,
  152969. 0.0341629474F, 0.0348690586F, 0.0355822122F, 0.0363024004F,
  152970. 0.0370296157F, 0.0377638502F, 0.0385050960F, 0.0392533451F,
  152971. 0.0400085896F, 0.0407708211F, 0.0415400315F, 0.0423162123F,
  152972. 0.0430993552F, 0.0438894515F, 0.0446864926F, 0.0454904698F,
  152973. 0.0463013742F, 0.0471191969F, 0.0479439288F, 0.0487755607F,
  152974. 0.0496140836F, 0.0504594879F, 0.0513117642F, 0.0521709031F,
  152975. 0.0530368949F, 0.0539097297F, 0.0547893979F, 0.0556758894F,
  152976. 0.0565691941F, 0.0574693019F, 0.0583762026F, 0.0592898858F,
  152977. 0.0602103410F, 0.0611375576F, 0.0620715250F, 0.0630122324F,
  152978. 0.0639596688F, 0.0649138234F, 0.0658746848F, 0.0668422421F,
  152979. 0.0678164838F, 0.0687973985F, 0.0697849746F, 0.0707792005F,
  152980. 0.0717800645F, 0.0727875547F, 0.0738016591F, 0.0748223656F,
  152981. 0.0758496620F, 0.0768835359F, 0.0779239751F, 0.0789709668F,
  152982. 0.0800244985F, 0.0810845574F, 0.0821511306F, 0.0832242052F,
  152983. 0.0843037679F, 0.0853898056F, 0.0864823050F, 0.0875812525F,
  152984. 0.0886866347F, 0.0897984378F, 0.0909166480F, 0.0920412513F,
  152985. 0.0931722338F, 0.0943095813F, 0.0954532795F, 0.0966033140F,
  152986. 0.0977596702F, 0.0989223336F, 0.1000912894F, 0.1012665227F,
  152987. 0.1024480185F, 0.1036357616F, 0.1048297369F, 0.1060299290F,
  152988. 0.1072363224F, 0.1084489014F, 0.1096676504F, 0.1108925534F,
  152989. 0.1121235946F, 0.1133607577F, 0.1146040267F, 0.1158533850F,
  152990. 0.1171088163F, 0.1183703040F, 0.1196378312F, 0.1209113812F,
  152991. 0.1221909370F, 0.1234764815F, 0.1247679974F, 0.1260654674F,
  152992. 0.1273688740F, 0.1286781995F, 0.1299934263F, 0.1313145365F,
  152993. 0.1326415121F, 0.1339743349F, 0.1353129866F, 0.1366574490F,
  152994. 0.1380077035F, 0.1393637315F, 0.1407255141F, 0.1420930325F,
  152995. 0.1434662677F, 0.1448452004F, 0.1462298115F, 0.1476200814F,
  152996. 0.1490159906F, 0.1504175195F, 0.1518246482F, 0.1532373569F,
  152997. 0.1546556253F, 0.1560794333F, 0.1575087606F, 0.1589435866F,
  152998. 0.1603838909F, 0.1618296526F, 0.1632808509F, 0.1647374648F,
  152999. 0.1661994731F, 0.1676668546F, 0.1691395880F, 0.1706176516F,
  153000. 0.1721010238F, 0.1735896829F, 0.1750836068F, 0.1765827736F,
  153001. 0.1780871610F, 0.1795967468F, 0.1811115084F, 0.1826314234F,
  153002. 0.1841564689F, 0.1856866221F, 0.1872218600F, 0.1887621595F,
  153003. 0.1903074974F, 0.1918578503F, 0.1934131947F, 0.1949735068F,
  153004. 0.1965387630F, 0.1981089393F, 0.1996840117F, 0.2012639560F,
  153005. 0.2028487479F, 0.2044383630F, 0.2060327766F, 0.2076319642F,
  153006. 0.2092359007F, 0.2108445614F, 0.2124579211F, 0.2140759545F,
  153007. 0.2156986364F, 0.2173259411F, 0.2189578432F, 0.2205943168F,
  153008. 0.2222353361F, 0.2238808751F, 0.2255309076F, 0.2271854073F,
  153009. 0.2288443480F, 0.2305077030F, 0.2321754457F, 0.2338475493F,
  153010. 0.2355239869F, 0.2372047315F, 0.2388897560F, 0.2405790329F,
  153011. 0.2422725350F, 0.2439702347F, 0.2456721043F, 0.2473781159F,
  153012. 0.2490882418F, 0.2508024539F, 0.2525207240F, 0.2542430237F,
  153013. 0.2559693248F, 0.2576995986F, 0.2594338166F, 0.2611719498F,
  153014. 0.2629139695F, 0.2646598466F, 0.2664095520F, 0.2681630564F,
  153015. 0.2699203304F, 0.2716813445F, 0.2734460691F, 0.2752144744F,
  153016. 0.2769865307F, 0.2787622079F, 0.2805414760F, 0.2823243047F,
  153017. 0.2841106637F, 0.2859005227F, 0.2876938509F, 0.2894906179F,
  153018. 0.2912907928F, 0.2930943447F, 0.2949012426F, 0.2967114554F,
  153019. 0.2985249520F, 0.3003417009F, 0.3021616708F, 0.3039848301F,
  153020. 0.3058111471F, 0.3076405901F, 0.3094731273F, 0.3113087266F,
  153021. 0.3131473560F, 0.3149889833F, 0.3168335762F, 0.3186811024F,
  153022. 0.3205315294F, 0.3223848245F, 0.3242409552F, 0.3260998886F,
  153023. 0.3279615918F, 0.3298260319F, 0.3316931758F, 0.3335629903F,
  153024. 0.3354354423F, 0.3373104982F, 0.3391881247F, 0.3410682882F,
  153025. 0.3429509551F, 0.3448360917F, 0.3467236642F, 0.3486136387F,
  153026. 0.3505059811F, 0.3524006575F, 0.3542976336F, 0.3561968753F,
  153027. 0.3580983482F, 0.3600020179F, 0.3619078499F, 0.3638158096F,
  153028. 0.3657258625F, 0.3676379737F, 0.3695521086F, 0.3714682321F,
  153029. 0.3733863094F, 0.3753063055F, 0.3772281852F, 0.3791519134F,
  153030. 0.3810774548F, 0.3830047742F, 0.3849338362F, 0.3868646053F,
  153031. 0.3887970459F, 0.3907311227F, 0.3926667998F, 0.3946040417F,
  153032. 0.3965428125F, 0.3984830765F, 0.4004247978F, 0.4023679403F,
  153033. 0.4043124683F, 0.4062583455F, 0.4082055359F, 0.4101540034F,
  153034. 0.4121037117F, 0.4140546246F, 0.4160067058F, 0.4179599190F,
  153035. 0.4199142277F, 0.4218695956F, 0.4238259861F, 0.4257833627F,
  153036. 0.4277416888F, 0.4297009279F, 0.4316610433F, 0.4336219983F,
  153037. 0.4355837562F, 0.4375462803F, 0.4395095337F, 0.4414734797F,
  153038. 0.4434380815F, 0.4454033021F, 0.4473691046F, 0.4493354521F,
  153039. 0.4513023078F, 0.4532696345F, 0.4552373954F, 0.4572055533F,
  153040. 0.4591740713F, 0.4611429123F, 0.4631120393F, 0.4650814151F,
  153041. 0.4670510028F, 0.4690207650F, 0.4709906649F, 0.4729606651F,
  153042. 0.4749307287F, 0.4769008185F, 0.4788708972F, 0.4808409279F,
  153043. 0.4828108732F, 0.4847806962F, 0.4867503597F, 0.4887198264F,
  153044. 0.4906890593F, 0.4926580213F, 0.4946266753F, 0.4965949840F,
  153045. 0.4985629105F, 0.5005304176F, 0.5024974683F, 0.5044640255F,
  153046. 0.5064300522F, 0.5083955114F, 0.5103603659F, 0.5123245790F,
  153047. 0.5142881136F, 0.5162509328F, 0.5182129997F, 0.5201742774F,
  153048. 0.5221347290F, 0.5240943178F, 0.5260530070F, 0.5280107598F,
  153049. 0.5299675395F, 0.5319233095F, 0.5338780330F, 0.5358316736F,
  153050. 0.5377841946F, 0.5397355596F, 0.5416857320F, 0.5436346755F,
  153051. 0.5455823538F, 0.5475287304F, 0.5494737691F, 0.5514174337F,
  153052. 0.5533596881F, 0.5553004962F, 0.5572398218F, 0.5591776291F,
  153053. 0.5611138821F, 0.5630485449F, 0.5649815818F, 0.5669129570F,
  153054. 0.5688426349F, 0.5707705799F, 0.5726967564F, 0.5746211290F,
  153055. 0.5765436624F, 0.5784643212F, 0.5803830702F, 0.5822998743F,
  153056. 0.5842146984F, 0.5861275076F, 0.5880382669F, 0.5899469416F,
  153057. 0.5918534968F, 0.5937578981F, 0.5956601107F, 0.5975601004F,
  153058. 0.5994578326F, 0.6013532732F, 0.6032463880F, 0.6051371429F,
  153059. 0.6070255039F, 0.6089114372F, 0.6107949090F, 0.6126758856F,
  153060. 0.6145543334F, 0.6164302191F, 0.6183035092F, 0.6201741706F,
  153061. 0.6220421700F, 0.6239074745F, 0.6257700513F, 0.6276298674F,
  153062. 0.6294868903F, 0.6313410873F, 0.6331924262F, 0.6350408745F,
  153063. 0.6368864001F, 0.6387289710F, 0.6405685552F, 0.6424051209F,
  153064. 0.6442386364F, 0.6460690702F, 0.6478963910F, 0.6497205673F,
  153065. 0.6515415682F, 0.6533593625F, 0.6551739194F, 0.6569852082F,
  153066. 0.6587931984F, 0.6605978593F, 0.6623991609F, 0.6641970728F,
  153067. 0.6659915652F, 0.6677826081F, 0.6695701718F, 0.6713542268F,
  153068. 0.6731347437F, 0.6749116932F, 0.6766850461F, 0.6784547736F,
  153069. 0.6802208469F, 0.6819832374F, 0.6837419164F, 0.6854968559F,
  153070. 0.6872480275F, 0.6889954034F, 0.6907389556F, 0.6924786566F,
  153071. 0.6942144788F, 0.6959463950F, 0.6976743780F, 0.6993984008F,
  153072. 0.7011184365F, 0.7028344587F, 0.7045464407F, 0.7062543564F,
  153073. 0.7079581796F, 0.7096578844F, 0.7113534450F, 0.7130448359F,
  153074. 0.7147320316F, 0.7164150070F, 0.7180937371F, 0.7197681970F,
  153075. 0.7214383620F, 0.7231042077F, 0.7247657098F, 0.7264228443F,
  153076. 0.7280755871F, 0.7297239147F, 0.7313678035F, 0.7330072301F,
  153077. 0.7346421715F, 0.7362726046F, 0.7378985069F, 0.7395198556F,
  153078. 0.7411366285F, 0.7427488034F, 0.7443563584F, 0.7459592717F,
  153079. 0.7475575218F, 0.7491510873F, 0.7507399471F, 0.7523240803F,
  153080. 0.7539034661F, 0.7554780839F, 0.7570479136F, 0.7586129349F,
  153081. 0.7601731279F, 0.7617284730F, 0.7632789506F, 0.7648245416F,
  153082. 0.7663652267F, 0.7679009872F, 0.7694318044F, 0.7709576599F,
  153083. 0.7724785354F, 0.7739944130F, 0.7755052749F, 0.7770111035F,
  153084. 0.7785118815F, 0.7800075916F, 0.7814982170F, 0.7829837410F,
  153085. 0.7844641472F, 0.7859394191F, 0.7874095408F, 0.7888744965F,
  153086. 0.7903342706F, 0.7917888476F, 0.7932382124F, 0.7946823501F,
  153087. 0.7961212460F, 0.7975548855F, 0.7989832544F, 0.8004063386F,
  153088. 0.8018241244F, 0.8032365981F, 0.8046437463F, 0.8060455560F,
  153089. 0.8074420141F, 0.8088331080F, 0.8102188253F, 0.8115991536F,
  153090. 0.8129740810F, 0.8143435957F, 0.8157076861F, 0.8170663409F,
  153091. 0.8184195489F, 0.8197672994F, 0.8211095817F, 0.8224463853F,
  153092. 0.8237777001F, 0.8251035161F, 0.8264238235F, 0.8277386129F,
  153093. 0.8290478750F, 0.8303516008F, 0.8316497814F, 0.8329424083F,
  153094. 0.8342294731F, 0.8355109677F, 0.8367868841F, 0.8380572148F,
  153095. 0.8393219523F, 0.8405810893F, 0.8418346190F, 0.8430825345F,
  153096. 0.8443248294F, 0.8455614974F, 0.8467925323F, 0.8480179285F,
  153097. 0.8492376802F, 0.8504517822F, 0.8516602292F, 0.8528630164F,
  153098. 0.8540601391F, 0.8552515928F, 0.8564373733F, 0.8576174766F,
  153099. 0.8587918990F, 0.8599606368F, 0.8611236868F, 0.8622810460F,
  153100. 0.8634327113F, 0.8645786802F, 0.8657189504F, 0.8668535195F,
  153101. 0.8679823857F, 0.8691055472F, 0.8702230025F, 0.8713347503F,
  153102. 0.8724407896F, 0.8735411194F, 0.8746357394F, 0.8757246489F,
  153103. 0.8768078479F, 0.8778853364F, 0.8789571146F, 0.8800231832F,
  153104. 0.8810835427F, 0.8821381942F, 0.8831871387F, 0.8842303777F,
  153105. 0.8852679127F, 0.8862997456F, 0.8873258784F, 0.8883463132F,
  153106. 0.8893610527F, 0.8903700994F, 0.8913734562F, 0.8923711263F,
  153107. 0.8933631129F, 0.8943494196F, 0.8953300500F, 0.8963050083F,
  153108. 0.8972742985F, 0.8982379249F, 0.8991958922F, 0.9001482052F,
  153109. 0.9010948688F, 0.9020358883F, 0.9029712690F, 0.9039010165F,
  153110. 0.9048251367F, 0.9057436357F, 0.9066565195F, 0.9075637946F,
  153111. 0.9084654678F, 0.9093615456F, 0.9102520353F, 0.9111369440F,
  153112. 0.9120162792F, 0.9128900484F, 0.9137582595F, 0.9146209204F,
  153113. 0.9154780394F, 0.9163296248F, 0.9171756853F, 0.9180162296F,
  153114. 0.9188512667F, 0.9196808057F, 0.9205048559F, 0.9213234270F,
  153115. 0.9221365285F, 0.9229441704F, 0.9237463629F, 0.9245431160F,
  153116. 0.9253344404F, 0.9261203465F, 0.9269008453F, 0.9276759477F,
  153117. 0.9284456648F, 0.9292100080F, 0.9299689889F, 0.9307226190F,
  153118. 0.9314709103F, 0.9322138747F, 0.9329515245F, 0.9336838721F,
  153119. 0.9344109300F, 0.9351327108F, 0.9358492275F, 0.9365604931F,
  153120. 0.9372665208F, 0.9379673239F, 0.9386629160F, 0.9393533107F,
  153121. 0.9400385220F, 0.9407185637F, 0.9413934501F, 0.9420631954F,
  153122. 0.9427278141F, 0.9433873208F, 0.9440417304F, 0.9446910576F,
  153123. 0.9453353176F, 0.9459745255F, 0.9466086968F, 0.9472378469F,
  153124. 0.9478619915F, 0.9484811463F, 0.9490953274F, 0.9497045506F,
  153125. 0.9503088323F, 0.9509081888F, 0.9515026365F, 0.9520921921F,
  153126. 0.9526768723F, 0.9532566940F, 0.9538316742F, 0.9544018300F,
  153127. 0.9549671786F, 0.9555277375F, 0.9560835241F, 0.9566345562F,
  153128. 0.9571808513F, 0.9577224275F, 0.9582593027F, 0.9587914949F,
  153129. 0.9593190225F, 0.9598419038F, 0.9603601571F, 0.9608738012F,
  153130. 0.9613828546F, 0.9618873361F, 0.9623872646F, 0.9628826591F,
  153131. 0.9633735388F, 0.9638599227F, 0.9643418303F, 0.9648192808F,
  153132. 0.9652922939F, 0.9657608890F, 0.9662250860F, 0.9666849046F,
  153133. 0.9671403646F, 0.9675914861F, 0.9680382891F, 0.9684807937F,
  153134. 0.9689190202F, 0.9693529890F, 0.9697827203F, 0.9702082347F,
  153135. 0.9706295529F, 0.9710466953F, 0.9714596828F, 0.9718685362F,
  153136. 0.9722732762F, 0.9726739240F, 0.9730705005F, 0.9734630267F,
  153137. 0.9738515239F, 0.9742360134F, 0.9746165163F, 0.9749930540F,
  153138. 0.9753656481F, 0.9757343198F, 0.9760990909F, 0.9764599829F,
  153139. 0.9768170175F, 0.9771702164F, 0.9775196013F, 0.9778651941F,
  153140. 0.9782070167F, 0.9785450909F, 0.9788794388F, 0.9792100824F,
  153141. 0.9795370437F, 0.9798603449F, 0.9801800080F, 0.9804960554F,
  153142. 0.9808085092F, 0.9811173916F, 0.9814227251F, 0.9817245318F,
  153143. 0.9820228343F, 0.9823176549F, 0.9826090160F, 0.9828969402F,
  153144. 0.9831814498F, 0.9834625674F, 0.9837403156F, 0.9840147169F,
  153145. 0.9842857939F, 0.9845535692F, 0.9848180654F, 0.9850793052F,
  153146. 0.9853373113F, 0.9855921062F, 0.9858437127F, 0.9860921535F,
  153147. 0.9863374512F, 0.9865796287F, 0.9868187085F, 0.9870547136F,
  153148. 0.9872876664F, 0.9875175899F, 0.9877445067F, 0.9879684396F,
  153149. 0.9881894112F, 0.9884074444F, 0.9886225619F, 0.9888347863F,
  153150. 0.9890441404F, 0.9892506468F, 0.9894543284F, 0.9896552077F,
  153151. 0.9898533074F, 0.9900486502F, 0.9902412587F, 0.9904311555F,
  153152. 0.9906183633F, 0.9908029045F, 0.9909848019F, 0.9911640779F,
  153153. 0.9913407550F, 0.9915148557F, 0.9916864025F, 0.9918554179F,
  153154. 0.9920219241F, 0.9921859437F, 0.9923474989F, 0.9925066120F,
  153155. 0.9926633054F, 0.9928176012F, 0.9929695218F, 0.9931190891F,
  153156. 0.9932663254F, 0.9934112527F, 0.9935538932F, 0.9936942686F,
  153157. 0.9938324012F, 0.9939683126F, 0.9941020248F, 0.9942335597F,
  153158. 0.9943629388F, 0.9944901841F, 0.9946153170F, 0.9947383593F,
  153159. 0.9948593325F, 0.9949782579F, 0.9950951572F, 0.9952100516F,
  153160. 0.9953229625F, 0.9954339111F, 0.9955429186F, 0.9956500062F,
  153161. 0.9957551948F, 0.9958585056F, 0.9959599593F, 0.9960595769F,
  153162. 0.9961573792F, 0.9962533869F, 0.9963476206F, 0.9964401009F,
  153163. 0.9965308483F, 0.9966198833F, 0.9967072261F, 0.9967928971F,
  153164. 0.9968769164F, 0.9969593041F, 0.9970400804F, 0.9971192651F,
  153165. 0.9971968781F, 0.9972729391F, 0.9973474680F, 0.9974204842F,
  153166. 0.9974920074F, 0.9975620569F, 0.9976306521F, 0.9976978122F,
  153167. 0.9977635565F, 0.9978279039F, 0.9978908736F, 0.9979524842F,
  153168. 0.9980127547F, 0.9980717037F, 0.9981293499F, 0.9981857116F,
  153169. 0.9982408073F, 0.9982946554F, 0.9983472739F, 0.9983986810F,
  153170. 0.9984488947F, 0.9984979328F, 0.9985458132F, 0.9985925534F,
  153171. 0.9986381711F, 0.9986826838F, 0.9987261086F, 0.9987684630F,
  153172. 0.9988097640F, 0.9988500286F, 0.9988892738F, 0.9989275163F,
  153173. 0.9989647727F, 0.9990010597F, 0.9990363938F, 0.9990707911F,
  153174. 0.9991042679F, 0.9991368404F, 0.9991685244F, 0.9991993358F,
  153175. 0.9992292905F, 0.9992584038F, 0.9992866914F, 0.9993141686F,
  153176. 0.9993408506F, 0.9993667526F, 0.9993918895F, 0.9994162761F,
  153177. 0.9994399273F, 0.9994628576F, 0.9994850815F, 0.9995066133F,
  153178. 0.9995274672F, 0.9995476574F, 0.9995671978F, 0.9995861021F,
  153179. 0.9996043841F, 0.9996220573F, 0.9996391352F, 0.9996556310F,
  153180. 0.9996715579F, 0.9996869288F, 0.9997017568F, 0.9997160543F,
  153181. 0.9997298342F, 0.9997431088F, 0.9997558905F, 0.9997681914F,
  153182. 0.9997800236F, 0.9997913990F, 0.9998023292F, 0.9998128261F,
  153183. 0.9998229009F, 0.9998325650F, 0.9998418296F, 0.9998507058F,
  153184. 0.9998592044F, 0.9998673362F, 0.9998751117F, 0.9998825415F,
  153185. 0.9998896358F, 0.9998964047F, 0.9999028584F, 0.9999090066F,
  153186. 0.9999148590F, 0.9999204253F, 0.9999257148F, 0.9999307368F,
  153187. 0.9999355003F, 0.9999400144F, 0.9999442878F, 0.9999483293F,
  153188. 0.9999521472F, 0.9999557499F, 0.9999591457F, 0.9999623426F,
  153189. 0.9999653483F, 0.9999681708F, 0.9999708175F, 0.9999732959F,
  153190. 0.9999756132F, 0.9999777765F, 0.9999797928F, 0.9999816688F,
  153191. 0.9999834113F, 0.9999850266F, 0.9999865211F, 0.9999879009F,
  153192. 0.9999891721F, 0.9999903405F, 0.9999914118F, 0.9999923914F,
  153193. 0.9999932849F, 0.9999940972F, 0.9999948336F, 0.9999954989F,
  153194. 0.9999960978F, 0.9999966349F, 0.9999971146F, 0.9999975411F,
  153195. 0.9999979185F, 0.9999982507F, 0.9999985414F, 0.9999987944F,
  153196. 0.9999990129F, 0.9999992003F, 0.9999993596F, 0.9999994939F,
  153197. 0.9999996059F, 0.9999996981F, 0.9999997732F, 0.9999998333F,
  153198. 0.9999998805F, 0.9999999170F, 0.9999999444F, 0.9999999643F,
  153199. 0.9999999784F, 0.9999999878F, 0.9999999937F, 0.9999999972F,
  153200. 0.9999999990F, 0.9999999997F, 1.0000000000F, 1.0000000000F,
  153201. };
  153202. static float vwin4096[2048] = {
  153203. 0.0000002310F, 0.0000020791F, 0.0000057754F, 0.0000113197F,
  153204. 0.0000187121F, 0.0000279526F, 0.0000390412F, 0.0000519777F,
  153205. 0.0000667623F, 0.0000833949F, 0.0001018753F, 0.0001222036F,
  153206. 0.0001443798F, 0.0001684037F, 0.0001942754F, 0.0002219947F,
  153207. 0.0002515616F, 0.0002829761F, 0.0003162380F, 0.0003513472F,
  153208. 0.0003883038F, 0.0004271076F, 0.0004677584F, 0.0005102563F,
  153209. 0.0005546011F, 0.0006007928F, 0.0006488311F, 0.0006987160F,
  153210. 0.0007504474F, 0.0008040251F, 0.0008594490F, 0.0009167191F,
  153211. 0.0009758351F, 0.0010367969F, 0.0010996044F, 0.0011642574F,
  153212. 0.0012307558F, 0.0012990994F, 0.0013692880F, 0.0014413216F,
  153213. 0.0015151998F, 0.0015909226F, 0.0016684898F, 0.0017479011F,
  153214. 0.0018291565F, 0.0019122556F, 0.0019971983F, 0.0020839845F,
  153215. 0.0021726138F, 0.0022630861F, 0.0023554012F, 0.0024495588F,
  153216. 0.0025455588F, 0.0026434008F, 0.0027430847F, 0.0028446103F,
  153217. 0.0029479772F, 0.0030531853F, 0.0031602342F, 0.0032691238F,
  153218. 0.0033798538F, 0.0034924239F, 0.0036068338F, 0.0037230833F,
  153219. 0.0038411721F, 0.0039610999F, 0.0040828664F, 0.0042064714F,
  153220. 0.0043319145F, 0.0044591954F, 0.0045883139F, 0.0047192696F,
  153221. 0.0048520622F, 0.0049866914F, 0.0051231569F, 0.0052614583F,
  153222. 0.0054015953F, 0.0055435676F, 0.0056873748F, 0.0058330166F,
  153223. 0.0059804926F, 0.0061298026F, 0.0062809460F, 0.0064339226F,
  153224. 0.0065887320F, 0.0067453738F, 0.0069038476F, 0.0070641531F,
  153225. 0.0072262899F, 0.0073902575F, 0.0075560556F, 0.0077236838F,
  153226. 0.0078931417F, 0.0080644288F, 0.0082375447F, 0.0084124891F,
  153227. 0.0085892615F, 0.0087678614F, 0.0089482885F, 0.0091305422F,
  153228. 0.0093146223F, 0.0095005281F, 0.0096882592F, 0.0098778153F,
  153229. 0.0100691958F, 0.0102624002F, 0.0104574281F, 0.0106542791F,
  153230. 0.0108529525F, 0.0110534480F, 0.0112557651F, 0.0114599032F,
  153231. 0.0116658618F, 0.0118736405F, 0.0120832387F, 0.0122946560F,
  153232. 0.0125078917F, 0.0127229454F, 0.0129398166F, 0.0131585046F,
  153233. 0.0133790090F, 0.0136013292F, 0.0138254647F, 0.0140514149F,
  153234. 0.0142791792F, 0.0145087572F, 0.0147401481F, 0.0149733515F,
  153235. 0.0152083667F, 0.0154451932F, 0.0156838304F, 0.0159242777F,
  153236. 0.0161665345F, 0.0164106001F, 0.0166564741F, 0.0169041557F,
  153237. 0.0171536443F, 0.0174049393F, 0.0176580401F, 0.0179129461F,
  153238. 0.0181696565F, 0.0184281708F, 0.0186884883F, 0.0189506084F,
  153239. 0.0192145303F, 0.0194802535F, 0.0197477772F, 0.0200171008F,
  153240. 0.0202882236F, 0.0205611449F, 0.0208358639F, 0.0211123801F,
  153241. 0.0213906927F, 0.0216708011F, 0.0219527043F, 0.0222364019F,
  153242. 0.0225218930F, 0.0228091769F, 0.0230982529F, 0.0233891203F,
  153243. 0.0236817782F, 0.0239762259F, 0.0242724628F, 0.0245704880F,
  153244. 0.0248703007F, 0.0251719002F, 0.0254752858F, 0.0257804565F,
  153245. 0.0260874117F, 0.0263961506F, 0.0267066722F, 0.0270189760F,
  153246. 0.0273330609F, 0.0276489263F, 0.0279665712F, 0.0282859949F,
  153247. 0.0286071966F, 0.0289301753F, 0.0292549303F, 0.0295814607F,
  153248. 0.0299097656F, 0.0302398442F, 0.0305716957F, 0.0309053191F,
  153249. 0.0312407135F, 0.0315778782F, 0.0319168122F, 0.0322575145F,
  153250. 0.0325999844F, 0.0329442209F, 0.0332902231F, 0.0336379900F,
  153251. 0.0339875208F, 0.0343388146F, 0.0346918703F, 0.0350466871F,
  153252. 0.0354032640F, 0.0357616000F, 0.0361216943F, 0.0364835458F,
  153253. 0.0368471535F, 0.0372125166F, 0.0375796339F, 0.0379485046F,
  153254. 0.0383191276F, 0.0386915020F, 0.0390656267F, 0.0394415008F,
  153255. 0.0398191231F, 0.0401984927F, 0.0405796086F, 0.0409624698F,
  153256. 0.0413470751F, 0.0417334235F, 0.0421215141F, 0.0425113457F,
  153257. 0.0429029172F, 0.0432962277F, 0.0436912760F, 0.0440880610F,
  153258. 0.0444865817F, 0.0448868370F, 0.0452888257F, 0.0456925468F,
  153259. 0.0460979992F, 0.0465051816F, 0.0469140931F, 0.0473247325F,
  153260. 0.0477370986F, 0.0481511902F, 0.0485670064F, 0.0489845458F,
  153261. 0.0494038074F, 0.0498247899F, 0.0502474922F, 0.0506719131F,
  153262. 0.0510980514F, 0.0515259060F, 0.0519554756F, 0.0523867590F,
  153263. 0.0528197550F, 0.0532544624F, 0.0536908800F, 0.0541290066F,
  153264. 0.0545688408F, 0.0550103815F, 0.0554536274F, 0.0558985772F,
  153265. 0.0563452297F, 0.0567935837F, 0.0572436377F, 0.0576953907F,
  153266. 0.0581488412F, 0.0586039880F, 0.0590608297F, 0.0595193651F,
  153267. 0.0599795929F, 0.0604415117F, 0.0609051202F, 0.0613704170F,
  153268. 0.0618374009F, 0.0623060704F, 0.0627764243F, 0.0632484611F,
  153269. 0.0637221795F, 0.0641975781F, 0.0646746555F, 0.0651534104F,
  153270. 0.0656338413F, 0.0661159469F, 0.0665997257F, 0.0670851763F,
  153271. 0.0675722973F, 0.0680610873F, 0.0685515448F, 0.0690436684F,
  153272. 0.0695374567F, 0.0700329081F, 0.0705300213F, 0.0710287947F,
  153273. 0.0715292269F, 0.0720313163F, 0.0725350616F, 0.0730404612F,
  153274. 0.0735475136F, 0.0740562172F, 0.0745665707F, 0.0750785723F,
  153275. 0.0755922207F, 0.0761075143F, 0.0766244515F, 0.0771430307F,
  153276. 0.0776632505F, 0.0781851092F, 0.0787086052F, 0.0792337371F,
  153277. 0.0797605032F, 0.0802889018F, 0.0808189315F, 0.0813505905F,
  153278. 0.0818838773F, 0.0824187903F, 0.0829553277F, 0.0834934881F,
  153279. 0.0840332697F, 0.0845746708F, 0.0851176899F, 0.0856623252F,
  153280. 0.0862085751F, 0.0867564379F, 0.0873059119F, 0.0878569954F,
  153281. 0.0884096867F, 0.0889639840F, 0.0895198858F, 0.0900773902F,
  153282. 0.0906364955F, 0.0911972000F, 0.0917595019F, 0.0923233995F,
  153283. 0.0928888909F, 0.0934559745F, 0.0940246485F, 0.0945949110F,
  153284. 0.0951667604F, 0.0957401946F, 0.0963152121F, 0.0968918109F,
  153285. 0.0974699893F, 0.0980497454F, 0.0986310773F, 0.0992139832F,
  153286. 0.0997984614F, 0.1003845098F, 0.1009721267F, 0.1015613101F,
  153287. 0.1021520582F, 0.1027443692F, 0.1033382410F, 0.1039336718F,
  153288. 0.1045306597F, 0.1051292027F, 0.1057292990F, 0.1063309466F,
  153289. 0.1069341435F, 0.1075388878F, 0.1081451776F, 0.1087530108F,
  153290. 0.1093623856F, 0.1099732998F, 0.1105857516F, 0.1111997389F,
  153291. 0.1118152597F, 0.1124323121F, 0.1130508939F, 0.1136710032F,
  153292. 0.1142926379F, 0.1149157960F, 0.1155404755F, 0.1161666742F,
  153293. 0.1167943901F, 0.1174236211F, 0.1180543652F, 0.1186866202F,
  153294. 0.1193203841F, 0.1199556548F, 0.1205924300F, 0.1212307078F,
  153295. 0.1218704860F, 0.1225117624F, 0.1231545349F, 0.1237988013F,
  153296. 0.1244445596F, 0.1250918074F, 0.1257405427F, 0.1263907632F,
  153297. 0.1270424667F, 0.1276956512F, 0.1283503142F, 0.1290064537F,
  153298. 0.1296640674F, 0.1303231530F, 0.1309837084F, 0.1316457312F,
  153299. 0.1323092193F, 0.1329741703F, 0.1336405820F, 0.1343084520F,
  153300. 0.1349777782F, 0.1356485582F, 0.1363207897F, 0.1369944704F,
  153301. 0.1376695979F, 0.1383461700F, 0.1390241842F, 0.1397036384F,
  153302. 0.1403845300F, 0.1410668567F, 0.1417506162F, 0.1424358061F,
  153303. 0.1431224240F, 0.1438104674F, 0.1444999341F, 0.1451908216F,
  153304. 0.1458831274F, 0.1465768492F, 0.1472719844F, 0.1479685308F,
  153305. 0.1486664857F, 0.1493658468F, 0.1500666115F, 0.1507687775F,
  153306. 0.1514723422F, 0.1521773031F, 0.1528836577F, 0.1535914035F,
  153307. 0.1543005380F, 0.1550110587F, 0.1557229631F, 0.1564362485F,
  153308. 0.1571509124F, 0.1578669524F, 0.1585843657F, 0.1593031499F,
  153309. 0.1600233024F, 0.1607448205F, 0.1614677017F, 0.1621919433F,
  153310. 0.1629175428F, 0.1636444975F, 0.1643728047F, 0.1651024619F,
  153311. 0.1658334665F, 0.1665658156F, 0.1672995067F, 0.1680345371F,
  153312. 0.1687709041F, 0.1695086050F, 0.1702476372F, 0.1709879978F,
  153313. 0.1717296843F, 0.1724726938F, 0.1732170237F, 0.1739626711F,
  153314. 0.1747096335F, 0.1754579079F, 0.1762074916F, 0.1769583819F,
  153315. 0.1777105760F, 0.1784640710F, 0.1792188642F, 0.1799749529F,
  153316. 0.1807323340F, 0.1814910049F, 0.1822509628F, 0.1830122046F,
  153317. 0.1837747277F, 0.1845385292F, 0.1853036062F, 0.1860699558F,
  153318. 0.1868375751F, 0.1876064613F, 0.1883766114F, 0.1891480226F,
  153319. 0.1899206919F, 0.1906946164F, 0.1914697932F, 0.1922462194F,
  153320. 0.1930238919F, 0.1938028079F, 0.1945829643F, 0.1953643583F,
  153321. 0.1961469868F, 0.1969308468F, 0.1977159353F, 0.1985022494F,
  153322. 0.1992897859F, 0.2000785420F, 0.2008685145F, 0.2016597005F,
  153323. 0.2024520968F, 0.2032457005F, 0.2040405084F, 0.2048365175F,
  153324. 0.2056337247F, 0.2064321269F, 0.2072317211F, 0.2080325041F,
  153325. 0.2088344727F, 0.2096376240F, 0.2104419547F, 0.2112474618F,
  153326. 0.2120541420F, 0.2128619923F, 0.2136710094F, 0.2144811902F,
  153327. 0.2152925315F, 0.2161050301F, 0.2169186829F, 0.2177334866F,
  153328. 0.2185494381F, 0.2193665340F, 0.2201847712F, 0.2210041465F,
  153329. 0.2218246565F, 0.2226462981F, 0.2234690680F, 0.2242929629F,
  153330. 0.2251179796F, 0.2259441147F, 0.2267713650F, 0.2275997272F,
  153331. 0.2284291979F, 0.2292597739F, 0.2300914518F, 0.2309242283F,
  153332. 0.2317581001F, 0.2325930638F, 0.2334291160F, 0.2342662534F,
  153333. 0.2351044727F, 0.2359437703F, 0.2367841431F, 0.2376255875F,
  153334. 0.2384681001F, 0.2393116776F, 0.2401563165F, 0.2410020134F,
  153335. 0.2418487649F, 0.2426965675F, 0.2435454178F, 0.2443953122F,
  153336. 0.2452462474F, 0.2460982199F, 0.2469512262F, 0.2478052628F,
  153337. 0.2486603262F, 0.2495164129F, 0.2503735194F, 0.2512316421F,
  153338. 0.2520907776F, 0.2529509222F, 0.2538120726F, 0.2546742250F,
  153339. 0.2555373760F, 0.2564015219F, 0.2572666593F, 0.2581327845F,
  153340. 0.2589998939F, 0.2598679840F, 0.2607370510F, 0.2616070916F,
  153341. 0.2624781019F, 0.2633500783F, 0.2642230173F, 0.2650969152F,
  153342. 0.2659717684F, 0.2668475731F, 0.2677243257F, 0.2686020226F,
  153343. 0.2694806601F, 0.2703602344F, 0.2712407419F, 0.2721221789F,
  153344. 0.2730045417F, 0.2738878265F, 0.2747720297F, 0.2756571474F,
  153345. 0.2765431760F, 0.2774301117F, 0.2783179508F, 0.2792066895F,
  153346. 0.2800963240F, 0.2809868505F, 0.2818782654F, 0.2827705647F,
  153347. 0.2836637447F, 0.2845578016F, 0.2854527315F, 0.2863485307F,
  153348. 0.2872451953F, 0.2881427215F, 0.2890411055F, 0.2899403433F,
  153349. 0.2908404312F, 0.2917413654F, 0.2926431418F, 0.2935457567F,
  153350. 0.2944492061F, 0.2953534863F, 0.2962585932F, 0.2971645230F,
  153351. 0.2980712717F, 0.2989788356F, 0.2998872105F, 0.3007963927F,
  153352. 0.3017063781F, 0.3026171629F, 0.3035287430F, 0.3044411145F,
  153353. 0.3053542736F, 0.3062682161F, 0.3071829381F, 0.3080984356F,
  153354. 0.3090147047F, 0.3099317413F, 0.3108495414F, 0.3117681011F,
  153355. 0.3126874163F, 0.3136074830F, 0.3145282972F, 0.3154498548F,
  153356. 0.3163721517F, 0.3172951841F, 0.3182189477F, 0.3191434385F,
  153357. 0.3200686525F, 0.3209945856F, 0.3219212336F, 0.3228485927F,
  153358. 0.3237766585F, 0.3247054271F, 0.3256348943F, 0.3265650560F,
  153359. 0.3274959081F, 0.3284274465F, 0.3293596671F, 0.3302925657F,
  153360. 0.3312261382F, 0.3321603804F, 0.3330952882F, 0.3340308574F,
  153361. 0.3349670838F, 0.3359039634F, 0.3368414919F, 0.3377796651F,
  153362. 0.3387184789F, 0.3396579290F, 0.3405980113F, 0.3415387216F,
  153363. 0.3424800556F, 0.3434220091F, 0.3443645779F, 0.3453077578F,
  153364. 0.3462515446F, 0.3471959340F, 0.3481409217F, 0.3490865036F,
  153365. 0.3500326754F, 0.3509794328F, 0.3519267715F, 0.3528746873F,
  153366. 0.3538231759F, 0.3547722330F, 0.3557218544F, 0.3566720357F,
  153367. 0.3576227727F, 0.3585740610F, 0.3595258964F, 0.3604782745F,
  153368. 0.3614311910F, 0.3623846417F, 0.3633386221F, 0.3642931280F,
  153369. 0.3652481549F, 0.3662036987F, 0.3671597548F, 0.3681163191F,
  153370. 0.3690733870F, 0.3700309544F, 0.3709890167F, 0.3719475696F,
  153371. 0.3729066089F, 0.3738661299F, 0.3748261285F, 0.3757866002F,
  153372. 0.3767475406F, 0.3777089453F, 0.3786708100F, 0.3796331302F,
  153373. 0.3805959014F, 0.3815591194F, 0.3825227796F, 0.3834868777F,
  153374. 0.3844514093F, 0.3854163698F, 0.3863817549F, 0.3873475601F,
  153375. 0.3883137810F, 0.3892804131F, 0.3902474521F, 0.3912148933F,
  153376. 0.3921827325F, 0.3931509650F, 0.3941195865F, 0.3950885925F,
  153377. 0.3960579785F, 0.3970277400F, 0.3979978725F, 0.3989683716F,
  153378. 0.3999392328F, 0.4009104516F, 0.4018820234F, 0.4028539438F,
  153379. 0.4038262084F, 0.4047988125F, 0.4057717516F, 0.4067450214F,
  153380. 0.4077186172F, 0.4086925345F, 0.4096667688F, 0.4106413155F,
  153381. 0.4116161703F, 0.4125913284F, 0.4135667854F, 0.4145425368F,
  153382. 0.4155185780F, 0.4164949044F, 0.4174715116F, 0.4184483949F,
  153383. 0.4194255498F, 0.4204029718F, 0.4213806563F, 0.4223585987F,
  153384. 0.4233367946F, 0.4243152392F, 0.4252939281F, 0.4262728566F,
  153385. 0.4272520202F, 0.4282314144F, 0.4292110345F, 0.4301908760F,
  153386. 0.4311709343F, 0.4321512047F, 0.4331316828F, 0.4341123639F,
  153387. 0.4350932435F, 0.4360743168F, 0.4370555794F, 0.4380370267F,
  153388. 0.4390186540F, 0.4400004567F, 0.4409824303F, 0.4419645701F,
  153389. 0.4429468716F, 0.4439293300F, 0.4449119409F, 0.4458946996F,
  153390. 0.4468776014F, 0.4478606418F, 0.4488438162F, 0.4498271199F,
  153391. 0.4508105483F, 0.4517940967F, 0.4527777607F, 0.4537615355F,
  153392. 0.4547454165F, 0.4557293991F, 0.4567134786F, 0.4576976505F,
  153393. 0.4586819101F, 0.4596662527F, 0.4606506738F, 0.4616351687F,
  153394. 0.4626197328F, 0.4636043614F, 0.4645890499F, 0.4655737936F,
  153395. 0.4665585880F, 0.4675434284F, 0.4685283101F, 0.4695132286F,
  153396. 0.4704981791F, 0.4714831570F, 0.4724681577F, 0.4734531766F,
  153397. 0.4744382089F, 0.4754232501F, 0.4764082956F, 0.4773933406F,
  153398. 0.4783783806F, 0.4793634108F, 0.4803484267F, 0.4813334237F,
  153399. 0.4823183969F, 0.4833033419F, 0.4842882540F, 0.4852731285F,
  153400. 0.4862579608F, 0.4872427462F, 0.4882274802F, 0.4892121580F,
  153401. 0.4901967751F, 0.4911813267F, 0.4921658083F, 0.4931502151F,
  153402. 0.4941345427F, 0.4951187863F, 0.4961029412F, 0.4970870029F,
  153403. 0.4980709667F, 0.4990548280F, 0.5000385822F, 0.5010222245F,
  153404. 0.5020057505F, 0.5029891553F, 0.5039724345F, 0.5049555834F,
  153405. 0.5059385973F, 0.5069214716F, 0.5079042018F, 0.5088867831F,
  153406. 0.5098692110F, 0.5108514808F, 0.5118335879F, 0.5128155277F,
  153407. 0.5137972956F, 0.5147788869F, 0.5157602971F, 0.5167415215F,
  153408. 0.5177225555F, 0.5187033945F, 0.5196840339F, 0.5206644692F,
  153409. 0.5216446956F, 0.5226247086F, 0.5236045035F, 0.5245840759F,
  153410. 0.5255634211F, 0.5265425344F, 0.5275214114F, 0.5285000474F,
  153411. 0.5294784378F, 0.5304565781F, 0.5314344637F, 0.5324120899F,
  153412. 0.5333894522F, 0.5343665461F, 0.5353433670F, 0.5363199102F,
  153413. 0.5372961713F, 0.5382721457F, 0.5392478287F, 0.5402232159F,
  153414. 0.5411983027F, 0.5421730845F, 0.5431475569F, 0.5441217151F,
  153415. 0.5450955548F, 0.5460690714F, 0.5470422602F, 0.5480151169F,
  153416. 0.5489876368F, 0.5499598155F, 0.5509316484F, 0.5519031310F,
  153417. 0.5528742587F, 0.5538450271F, 0.5548154317F, 0.5557854680F,
  153418. 0.5567551314F, 0.5577244174F, 0.5586933216F, 0.5596618395F,
  153419. 0.5606299665F, 0.5615976983F, 0.5625650302F, 0.5635319580F,
  153420. 0.5644984770F, 0.5654645828F, 0.5664302709F, 0.5673955370F,
  153421. 0.5683603765F, 0.5693247850F, 0.5702887580F, 0.5712522912F,
  153422. 0.5722153800F, 0.5731780200F, 0.5741402069F, 0.5751019362F,
  153423. 0.5760632034F, 0.5770240042F, 0.5779843341F, 0.5789441889F,
  153424. 0.5799035639F, 0.5808624549F, 0.5818208575F, 0.5827787673F,
  153425. 0.5837361800F, 0.5846930910F, 0.5856494961F, 0.5866053910F,
  153426. 0.5875607712F, 0.5885156324F, 0.5894699703F, 0.5904237804F,
  153427. 0.5913770586F, 0.5923298004F, 0.5932820016F, 0.5942336578F,
  153428. 0.5951847646F, 0.5961353179F, 0.5970853132F, 0.5980347464F,
  153429. 0.5989836131F, 0.5999319090F, 0.6008796298F, 0.6018267713F,
  153430. 0.6027733292F, 0.6037192993F, 0.6046646773F, 0.6056094589F,
  153431. 0.6065536400F, 0.6074972162F, 0.6084401833F, 0.6093825372F,
  153432. 0.6103242736F, 0.6112653884F, 0.6122058772F, 0.6131457359F,
  153433. 0.6140849604F, 0.6150235464F, 0.6159614897F, 0.6168987862F,
  153434. 0.6178354318F, 0.6187714223F, 0.6197067535F, 0.6206414213F,
  153435. 0.6215754215F, 0.6225087501F, 0.6234414028F, 0.6243733757F,
  153436. 0.6253046646F, 0.6262352654F, 0.6271651739F, 0.6280943862F,
  153437. 0.6290228982F, 0.6299507057F, 0.6308778048F, 0.6318041913F,
  153438. 0.6327298612F, 0.6336548105F, 0.6345790352F, 0.6355025312F,
  153439. 0.6364252945F, 0.6373473211F, 0.6382686070F, 0.6391891483F,
  153440. 0.6401089409F, 0.6410279808F, 0.6419462642F, 0.6428637869F,
  153441. 0.6437805452F, 0.6446965350F, 0.6456117524F, 0.6465261935F,
  153442. 0.6474398544F, 0.6483527311F, 0.6492648197F, 0.6501761165F,
  153443. 0.6510866174F, 0.6519963186F, 0.6529052162F, 0.6538133064F,
  153444. 0.6547205854F, 0.6556270492F, 0.6565326941F, 0.6574375162F,
  153445. 0.6583415117F, 0.6592446769F, 0.6601470079F, 0.6610485009F,
  153446. 0.6619491521F, 0.6628489578F, 0.6637479143F, 0.6646460177F,
  153447. 0.6655432643F, 0.6664396505F, 0.6673351724F, 0.6682298264F,
  153448. 0.6691236087F, 0.6700165157F, 0.6709085436F, 0.6717996889F,
  153449. 0.6726899478F, 0.6735793167F, 0.6744677918F, 0.6753553697F,
  153450. 0.6762420466F, 0.6771278190F, 0.6780126832F, 0.6788966357F,
  153451. 0.6797796728F, 0.6806617909F, 0.6815429866F, 0.6824232562F,
  153452. 0.6833025961F, 0.6841810030F, 0.6850584731F, 0.6859350031F,
  153453. 0.6868105894F, 0.6876852284F, 0.6885589168F, 0.6894316510F,
  153454. 0.6903034275F, 0.6911742430F, 0.6920440939F, 0.6929129769F,
  153455. 0.6937808884F, 0.6946478251F, 0.6955137837F, 0.6963787606F,
  153456. 0.6972427525F, 0.6981057560F, 0.6989677678F, 0.6998287845F,
  153457. 0.7006888028F, 0.7015478194F, 0.7024058309F, 0.7032628340F,
  153458. 0.7041188254F, 0.7049738019F, 0.7058277601F, 0.7066806969F,
  153459. 0.7075326089F, 0.7083834929F, 0.7092333457F, 0.7100821640F,
  153460. 0.7109299447F, 0.7117766846F, 0.7126223804F, 0.7134670291F,
  153461. 0.7143106273F, 0.7151531721F, 0.7159946602F, 0.7168350885F,
  153462. 0.7176744539F, 0.7185127534F, 0.7193499837F, 0.7201861418F,
  153463. 0.7210212247F, 0.7218552293F, 0.7226881526F, 0.7235199914F,
  153464. 0.7243507428F, 0.7251804039F, 0.7260089715F, 0.7268364426F,
  153465. 0.7276628144F, 0.7284880839F, 0.7293122481F, 0.7301353040F,
  153466. 0.7309572487F, 0.7317780794F, 0.7325977930F, 0.7334163868F,
  153467. 0.7342338579F, 0.7350502033F, 0.7358654202F, 0.7366795059F,
  153468. 0.7374924573F, 0.7383042718F, 0.7391149465F, 0.7399244787F,
  153469. 0.7407328655F, 0.7415401041F, 0.7423461920F, 0.7431511261F,
  153470. 0.7439549040F, 0.7447575227F, 0.7455589797F, 0.7463592723F,
  153471. 0.7471583976F, 0.7479563532F, 0.7487531363F, 0.7495487443F,
  153472. 0.7503431745F, 0.7511364244F, 0.7519284913F, 0.7527193726F,
  153473. 0.7535090658F, 0.7542975683F, 0.7550848776F, 0.7558709910F,
  153474. 0.7566559062F, 0.7574396205F, 0.7582221314F, 0.7590034366F,
  153475. 0.7597835334F, 0.7605624194F, 0.7613400923F, 0.7621165495F,
  153476. 0.7628917886F, 0.7636658072F, 0.7644386030F, 0.7652101735F,
  153477. 0.7659805164F, 0.7667496292F, 0.7675175098F, 0.7682841556F,
  153478. 0.7690495645F, 0.7698137341F, 0.7705766622F, 0.7713383463F,
  153479. 0.7720987844F, 0.7728579741F, 0.7736159132F, 0.7743725994F,
  153480. 0.7751280306F, 0.7758822046F, 0.7766351192F, 0.7773867722F,
  153481. 0.7781371614F, 0.7788862848F, 0.7796341401F, 0.7803807253F,
  153482. 0.7811260383F, 0.7818700769F, 0.7826128392F, 0.7833543230F,
  153483. 0.7840945263F, 0.7848334471F, 0.7855710833F, 0.7863074330F,
  153484. 0.7870424941F, 0.7877762647F, 0.7885087428F, 0.7892399264F,
  153485. 0.7899698137F, 0.7906984026F, 0.7914256914F, 0.7921516780F,
  153486. 0.7928763607F, 0.7935997375F, 0.7943218065F, 0.7950425661F,
  153487. 0.7957620142F, 0.7964801492F, 0.7971969692F, 0.7979124724F,
  153488. 0.7986266570F, 0.7993395214F, 0.8000510638F, 0.8007612823F,
  153489. 0.8014701754F, 0.8021777413F, 0.8028839784F, 0.8035888849F,
  153490. 0.8042924592F, 0.8049946997F, 0.8056956048F, 0.8063951727F,
  153491. 0.8070934020F, 0.8077902910F, 0.8084858381F, 0.8091800419F,
  153492. 0.8098729007F, 0.8105644130F, 0.8112545774F, 0.8119433922F,
  153493. 0.8126308561F, 0.8133169676F, 0.8140017251F, 0.8146851272F,
  153494. 0.8153671726F, 0.8160478598F, 0.8167271874F, 0.8174051539F,
  153495. 0.8180817582F, 0.8187569986F, 0.8194308741F, 0.8201033831F,
  153496. 0.8207745244F, 0.8214442966F, 0.8221126986F, 0.8227797290F,
  153497. 0.8234453865F, 0.8241096700F, 0.8247725781F, 0.8254341097F,
  153498. 0.8260942636F, 0.8267530385F, 0.8274104334F, 0.8280664470F,
  153499. 0.8287210782F, 0.8293743259F, 0.8300261889F, 0.8306766662F,
  153500. 0.8313257566F, 0.8319734591F, 0.8326197727F, 0.8332646963F,
  153501. 0.8339082288F, 0.8345503692F, 0.8351911167F, 0.8358304700F,
  153502. 0.8364684284F, 0.8371049907F, 0.8377401562F, 0.8383739238F,
  153503. 0.8390062927F, 0.8396372618F, 0.8402668305F, 0.8408949977F,
  153504. 0.8415217626F, 0.8421471245F, 0.8427710823F, 0.8433936354F,
  153505. 0.8440147830F, 0.8446345242F, 0.8452528582F, 0.8458697844F,
  153506. 0.8464853020F, 0.8470994102F, 0.8477121084F, 0.8483233958F,
  153507. 0.8489332718F, 0.8495417356F, 0.8501487866F, 0.8507544243F,
  153508. 0.8513586479F, 0.8519614568F, 0.8525628505F, 0.8531628283F,
  153509. 0.8537613897F, 0.8543585341F, 0.8549542611F, 0.8555485699F,
  153510. 0.8561414603F, 0.8567329315F, 0.8573229832F, 0.8579116149F,
  153511. 0.8584988262F, 0.8590846165F, 0.8596689855F, 0.8602519327F,
  153512. 0.8608334577F, 0.8614135603F, 0.8619922399F, 0.8625694962F,
  153513. 0.8631453289F, 0.8637197377F, 0.8642927222F, 0.8648642821F,
  153514. 0.8654344172F, 0.8660031272F, 0.8665704118F, 0.8671362708F,
  153515. 0.8677007039F, 0.8682637109F, 0.8688252917F, 0.8693854460F,
  153516. 0.8699441737F, 0.8705014745F, 0.8710573485F, 0.8716117953F,
  153517. 0.8721648150F, 0.8727164073F, 0.8732665723F, 0.8738153098F,
  153518. 0.8743626197F, 0.8749085021F, 0.8754529569F, 0.8759959840F,
  153519. 0.8765375835F, 0.8770777553F, 0.8776164996F, 0.8781538162F,
  153520. 0.8786897054F, 0.8792241670F, 0.8797572013F, 0.8802888082F,
  153521. 0.8808189880F, 0.8813477407F, 0.8818750664F, 0.8824009653F,
  153522. 0.8829254375F, 0.8834484833F, 0.8839701028F, 0.8844902961F,
  153523. 0.8850090636F, 0.8855264054F, 0.8860423218F, 0.8865568131F,
  153524. 0.8870698794F, 0.8875815212F, 0.8880917386F, 0.8886005319F,
  153525. 0.8891079016F, 0.8896138479F, 0.8901183712F, 0.8906214719F,
  153526. 0.8911231503F, 0.8916234067F, 0.8921222417F, 0.8926196556F,
  153527. 0.8931156489F, 0.8936102219F, 0.8941033752F, 0.8945951092F,
  153528. 0.8950854244F, 0.8955743212F, 0.8960618003F, 0.8965478621F,
  153529. 0.8970325071F, 0.8975157359F, 0.8979975490F, 0.8984779471F,
  153530. 0.8989569307F, 0.8994345004F, 0.8999106568F, 0.9003854005F,
  153531. 0.9008587323F, 0.9013306526F, 0.9018011623F, 0.9022702619F,
  153532. 0.9027379521F, 0.9032042337F, 0.9036691074F, 0.9041325739F,
  153533. 0.9045946339F, 0.9050552882F, 0.9055145376F, 0.9059723828F,
  153534. 0.9064288246F, 0.9068838638F, 0.9073375013F, 0.9077897379F,
  153535. 0.9082405743F, 0.9086900115F, 0.9091380503F, 0.9095846917F,
  153536. 0.9100299364F, 0.9104737854F, 0.9109162397F, 0.9113573001F,
  153537. 0.9117969675F, 0.9122352430F, 0.9126721275F, 0.9131076219F,
  153538. 0.9135417273F, 0.9139744447F, 0.9144057750F, 0.9148357194F,
  153539. 0.9152642787F, 0.9156914542F, 0.9161172468F, 0.9165416576F,
  153540. 0.9169646877F, 0.9173863382F, 0.9178066102F, 0.9182255048F,
  153541. 0.9186430232F, 0.9190591665F, 0.9194739359F, 0.9198873324F,
  153542. 0.9202993574F, 0.9207100120F, 0.9211192973F, 0.9215272147F,
  153543. 0.9219337653F, 0.9223389504F, 0.9227427713F, 0.9231452290F,
  153544. 0.9235463251F, 0.9239460607F, 0.9243444371F, 0.9247414557F,
  153545. 0.9251371177F, 0.9255314245F, 0.9259243774F, 0.9263159778F,
  153546. 0.9267062270F, 0.9270951264F, 0.9274826774F, 0.9278688814F,
  153547. 0.9282537398F, 0.9286372540F, 0.9290194254F, 0.9294002555F,
  153548. 0.9297797458F, 0.9301578976F, 0.9305347125F, 0.9309101919F,
  153549. 0.9312843373F, 0.9316571503F, 0.9320286323F, 0.9323987849F,
  153550. 0.9327676097F, 0.9331351080F, 0.9335012816F, 0.9338661320F,
  153551. 0.9342296607F, 0.9345918694F, 0.9349527596F, 0.9353123330F,
  153552. 0.9356705911F, 0.9360275357F, 0.9363831683F, 0.9367374905F,
  153553. 0.9370905042F, 0.9374422108F, 0.9377926122F, 0.9381417099F,
  153554. 0.9384895057F, 0.9388360014F, 0.9391811985F, 0.9395250989F,
  153555. 0.9398677043F, 0.9402090165F, 0.9405490371F, 0.9408877680F,
  153556. 0.9412252110F, 0.9415613678F, 0.9418962402F, 0.9422298301F,
  153557. 0.9425621392F, 0.9428931695F, 0.9432229226F, 0.9435514005F,
  153558. 0.9438786050F, 0.9442045381F, 0.9445292014F, 0.9448525971F,
  153559. 0.9451747268F, 0.9454955926F, 0.9458151963F, 0.9461335399F,
  153560. 0.9464506253F, 0.9467664545F, 0.9470810293F, 0.9473943517F,
  153561. 0.9477064238F, 0.9480172474F, 0.9483268246F, 0.9486351573F,
  153562. 0.9489422475F, 0.9492480973F, 0.9495527087F, 0.9498560837F,
  153563. 0.9501582243F, 0.9504591325F, 0.9507588105F, 0.9510572603F,
  153564. 0.9513544839F, 0.9516504834F, 0.9519452609F, 0.9522388186F,
  153565. 0.9525311584F, 0.9528222826F, 0.9531121932F, 0.9534008923F,
  153566. 0.9536883821F, 0.9539746647F, 0.9542597424F, 0.9545436171F,
  153567. 0.9548262912F, 0.9551077667F, 0.9553880459F, 0.9556671309F,
  153568. 0.9559450239F, 0.9562217272F, 0.9564972429F, 0.9567715733F,
  153569. 0.9570447206F, 0.9573166871F, 0.9575874749F, 0.9578570863F,
  153570. 0.9581255236F, 0.9583927890F, 0.9586588849F, 0.9589238134F,
  153571. 0.9591875769F, 0.9594501777F, 0.9597116180F, 0.9599719003F,
  153572. 0.9602310267F, 0.9604889995F, 0.9607458213F, 0.9610014942F,
  153573. 0.9612560206F, 0.9615094028F, 0.9617616433F, 0.9620127443F,
  153574. 0.9622627083F, 0.9625115376F, 0.9627592345F, 0.9630058016F,
  153575. 0.9632512411F, 0.9634955555F, 0.9637387471F, 0.9639808185F,
  153576. 0.9642217720F, 0.9644616100F, 0.9647003349F, 0.9649379493F,
  153577. 0.9651744556F, 0.9654098561F, 0.9656441534F, 0.9658773499F,
  153578. 0.9661094480F, 0.9663404504F, 0.9665703593F, 0.9667991774F,
  153579. 0.9670269071F, 0.9672535509F, 0.9674791114F, 0.9677035909F,
  153580. 0.9679269921F, 0.9681493174F, 0.9683705694F, 0.9685907506F,
  153581. 0.9688098636F, 0.9690279108F, 0.9692448948F, 0.9694608182F,
  153582. 0.9696756836F, 0.9698894934F, 0.9701022503F, 0.9703139569F,
  153583. 0.9705246156F, 0.9707342291F, 0.9709428000F, 0.9711503309F,
  153584. 0.9713568243F, 0.9715622829F, 0.9717667093F, 0.9719701060F,
  153585. 0.9721724757F, 0.9723738210F, 0.9725741446F, 0.9727734490F,
  153586. 0.9729717369F, 0.9731690109F, 0.9733652737F, 0.9735605279F,
  153587. 0.9737547762F, 0.9739480212F, 0.9741402656F, 0.9743315120F,
  153588. 0.9745217631F, 0.9747110216F, 0.9748992901F, 0.9750865714F,
  153589. 0.9752728681F, 0.9754581829F, 0.9756425184F, 0.9758258775F,
  153590. 0.9760082627F, 0.9761896768F, 0.9763701224F, 0.9765496024F,
  153591. 0.9767281193F, 0.9769056760F, 0.9770822751F, 0.9772579193F,
  153592. 0.9774326114F, 0.9776063542F, 0.9777791502F, 0.9779510023F,
  153593. 0.9781219133F, 0.9782918858F, 0.9784609226F, 0.9786290264F,
  153594. 0.9787962000F, 0.9789624461F, 0.9791277676F, 0.9792921671F,
  153595. 0.9794556474F, 0.9796182113F, 0.9797798615F, 0.9799406009F,
  153596. 0.9801004321F, 0.9802593580F, 0.9804173813F, 0.9805745049F,
  153597. 0.9807307314F, 0.9808860637F, 0.9810405046F, 0.9811940568F,
  153598. 0.9813467232F, 0.9814985065F, 0.9816494095F, 0.9817994351F,
  153599. 0.9819485860F, 0.9820968650F, 0.9822442750F, 0.9823908186F,
  153600. 0.9825364988F, 0.9826813184F, 0.9828252801F, 0.9829683868F,
  153601. 0.9831106413F, 0.9832520463F, 0.9833926048F, 0.9835323195F,
  153602. 0.9836711932F, 0.9838092288F, 0.9839464291F, 0.9840827969F,
  153603. 0.9842183351F, 0.9843530464F, 0.9844869337F, 0.9846199998F,
  153604. 0.9847522475F, 0.9848836798F, 0.9850142993F, 0.9851441090F,
  153605. 0.9852731117F, 0.9854013101F, 0.9855287073F, 0.9856553058F,
  153606. 0.9857811087F, 0.9859061188F, 0.9860303388F, 0.9861537717F,
  153607. 0.9862764202F, 0.9863982872F, 0.9865193756F, 0.9866396882F,
  153608. 0.9867592277F, 0.9868779972F, 0.9869959993F, 0.9871132370F,
  153609. 0.9872297131F, 0.9873454304F, 0.9874603918F, 0.9875746001F,
  153610. 0.9876880581F, 0.9878007688F, 0.9879127348F, 0.9880239592F,
  153611. 0.9881344447F, 0.9882441941F, 0.9883532104F, 0.9884614962F,
  153612. 0.9885690546F, 0.9886758883F, 0.9887820001F, 0.9888873930F,
  153613. 0.9889920697F, 0.9890960331F, 0.9891992859F, 0.9893018312F,
  153614. 0.9894036716F, 0.9895048100F, 0.9896052493F, 0.9897049923F,
  153615. 0.9898040418F, 0.9899024006F, 0.9900000717F, 0.9900970577F,
  153616. 0.9901933616F, 0.9902889862F, 0.9903839343F, 0.9904782087F,
  153617. 0.9905718122F, 0.9906647477F, 0.9907570180F, 0.9908486259F,
  153618. 0.9909395742F, 0.9910298658F, 0.9911195034F, 0.9912084899F,
  153619. 0.9912968281F, 0.9913845208F, 0.9914715708F, 0.9915579810F,
  153620. 0.9916437540F, 0.9917288928F, 0.9918134001F, 0.9918972788F,
  153621. 0.9919805316F, 0.9920631613F, 0.9921451707F, 0.9922265626F,
  153622. 0.9923073399F, 0.9923875052F, 0.9924670615F, 0.9925460114F,
  153623. 0.9926243577F, 0.9927021033F, 0.9927792508F, 0.9928558032F,
  153624. 0.9929317631F, 0.9930071333F, 0.9930819167F, 0.9931561158F,
  153625. 0.9932297337F, 0.9933027728F, 0.9933752362F, 0.9934471264F,
  153626. 0.9935184462F, 0.9935891985F, 0.9936593859F, 0.9937290112F,
  153627. 0.9937980771F, 0.9938665864F, 0.9939345418F, 0.9940019460F,
  153628. 0.9940688018F, 0.9941351118F, 0.9942008789F, 0.9942661057F,
  153629. 0.9943307950F, 0.9943949494F, 0.9944585717F, 0.9945216645F,
  153630. 0.9945842307F, 0.9946462728F, 0.9947077936F, 0.9947687957F,
  153631. 0.9948292820F, 0.9948892550F, 0.9949487174F, 0.9950076719F,
  153632. 0.9950661212F, 0.9951240679F, 0.9951815148F, 0.9952384645F,
  153633. 0.9952949196F, 0.9953508828F, 0.9954063568F, 0.9954613442F,
  153634. 0.9955158476F, 0.9955698697F, 0.9956234132F, 0.9956764806F,
  153635. 0.9957290746F, 0.9957811978F, 0.9958328528F, 0.9958840423F,
  153636. 0.9959347688F, 0.9959850351F, 0.9960348435F, 0.9960841969F,
  153637. 0.9961330977F, 0.9961815486F, 0.9962295521F, 0.9962771108F,
  153638. 0.9963242274F, 0.9963709043F, 0.9964171441F, 0.9964629494F,
  153639. 0.9965083228F, 0.9965532668F, 0.9965977840F, 0.9966418768F,
  153640. 0.9966855479F, 0.9967287998F, 0.9967716350F, 0.9968140559F,
  153641. 0.9968560653F, 0.9968976655F, 0.9969388591F, 0.9969796485F,
  153642. 0.9970200363F, 0.9970600250F, 0.9970996170F, 0.9971388149F,
  153643. 0.9971776211F, 0.9972160380F, 0.9972540683F, 0.9972917142F,
  153644. 0.9973289783F, 0.9973658631F, 0.9974023709F, 0.9974385042F,
  153645. 0.9974742655F, 0.9975096571F, 0.9975446816F, 0.9975793413F,
  153646. 0.9976136386F, 0.9976475759F, 0.9976811557F, 0.9977143803F,
  153647. 0.9977472521F, 0.9977797736F, 0.9978119470F, 0.9978437748F,
  153648. 0.9978752593F, 0.9979064029F, 0.9979372079F, 0.9979676768F,
  153649. 0.9979978117F, 0.9980276151F, 0.9980570893F, 0.9980862367F,
  153650. 0.9981150595F, 0.9981435600F, 0.9981717406F, 0.9981996035F,
  153651. 0.9982271511F, 0.9982543856F, 0.9982813093F, 0.9983079246F,
  153652. 0.9983342336F, 0.9983602386F, 0.9983859418F, 0.9984113456F,
  153653. 0.9984364522F, 0.9984612638F, 0.9984857825F, 0.9985100108F,
  153654. 0.9985339507F, 0.9985576044F, 0.9985809743F, 0.9986040624F,
  153655. 0.9986268710F, 0.9986494022F, 0.9986716583F, 0.9986936413F,
  153656. 0.9987153535F, 0.9987367969F, 0.9987579738F, 0.9987788864F,
  153657. 0.9987995366F, 0.9988199267F, 0.9988400587F, 0.9988599348F,
  153658. 0.9988795572F, 0.9988989278F, 0.9989180487F, 0.9989369222F,
  153659. 0.9989555501F, 0.9989739347F, 0.9989920780F, 0.9990099820F,
  153660. 0.9990276487F, 0.9990450803F, 0.9990622787F, 0.9990792460F,
  153661. 0.9990959841F, 0.9991124952F, 0.9991287812F, 0.9991448440F,
  153662. 0.9991606858F, 0.9991763084F, 0.9991917139F, 0.9992069042F,
  153663. 0.9992218813F, 0.9992366471F, 0.9992512035F, 0.9992655525F,
  153664. 0.9992796961F, 0.9992936361F, 0.9993073744F, 0.9993209131F,
  153665. 0.9993342538F, 0.9993473987F, 0.9993603494F, 0.9993731080F,
  153666. 0.9993856762F, 0.9993980559F, 0.9994102490F, 0.9994222573F,
  153667. 0.9994340827F, 0.9994457269F, 0.9994571918F, 0.9994684793F,
  153668. 0.9994795910F, 0.9994905288F, 0.9995012945F, 0.9995118898F,
  153669. 0.9995223165F, 0.9995325765F, 0.9995426713F, 0.9995526029F,
  153670. 0.9995623728F, 0.9995719829F, 0.9995814349F, 0.9995907304F,
  153671. 0.9995998712F, 0.9996088590F, 0.9996176954F, 0.9996263821F,
  153672. 0.9996349208F, 0.9996433132F, 0.9996515609F, 0.9996596656F,
  153673. 0.9996676288F, 0.9996754522F, 0.9996831375F, 0.9996906862F,
  153674. 0.9996981000F, 0.9997053804F, 0.9997125290F, 0.9997195474F,
  153675. 0.9997264371F, 0.9997331998F, 0.9997398369F, 0.9997463500F,
  153676. 0.9997527406F, 0.9997590103F, 0.9997651606F, 0.9997711930F,
  153677. 0.9997771089F, 0.9997829098F, 0.9997885973F, 0.9997941728F,
  153678. 0.9997996378F, 0.9998049936F, 0.9998102419F, 0.9998153839F,
  153679. 0.9998204211F, 0.9998253550F, 0.9998301868F, 0.9998349182F,
  153680. 0.9998395503F, 0.9998440847F, 0.9998485226F, 0.9998528654F,
  153681. 0.9998571146F, 0.9998612713F, 0.9998653370F, 0.9998693130F,
  153682. 0.9998732007F, 0.9998770012F, 0.9998807159F, 0.9998843461F,
  153683. 0.9998878931F, 0.9998913581F, 0.9998947424F, 0.9998980473F,
  153684. 0.9999012740F, 0.9999044237F, 0.9999074976F, 0.9999104971F,
  153685. 0.9999134231F, 0.9999162771F, 0.9999190601F, 0.9999217733F,
  153686. 0.9999244179F, 0.9999269950F, 0.9999295058F, 0.9999319515F,
  153687. 0.9999343332F, 0.9999366519F, 0.9999389088F, 0.9999411050F,
  153688. 0.9999432416F, 0.9999453196F, 0.9999473402F, 0.9999493044F,
  153689. 0.9999512132F, 0.9999530677F, 0.9999548690F, 0.9999566180F,
  153690. 0.9999583157F, 0.9999599633F, 0.9999615616F, 0.9999631116F,
  153691. 0.9999646144F, 0.9999660709F, 0.9999674820F, 0.9999688487F,
  153692. 0.9999701719F, 0.9999714526F, 0.9999726917F, 0.9999738900F,
  153693. 0.9999750486F, 0.9999761682F, 0.9999772497F, 0.9999782941F,
  153694. 0.9999793021F, 0.9999802747F, 0.9999812126F, 0.9999821167F,
  153695. 0.9999829878F, 0.9999838268F, 0.9999846343F, 0.9999854113F,
  153696. 0.9999861584F, 0.9999868765F, 0.9999875664F, 0.9999882287F,
  153697. 0.9999888642F, 0.9999894736F, 0.9999900577F, 0.9999906172F,
  153698. 0.9999911528F, 0.9999916651F, 0.9999921548F, 0.9999926227F,
  153699. 0.9999930693F, 0.9999934954F, 0.9999939015F, 0.9999942883F,
  153700. 0.9999946564F, 0.9999950064F, 0.9999953390F, 0.9999956547F,
  153701. 0.9999959541F, 0.9999962377F, 0.9999965062F, 0.9999967601F,
  153702. 0.9999969998F, 0.9999972260F, 0.9999974392F, 0.9999976399F,
  153703. 0.9999978285F, 0.9999980056F, 0.9999981716F, 0.9999983271F,
  153704. 0.9999984724F, 0.9999986081F, 0.9999987345F, 0.9999988521F,
  153705. 0.9999989613F, 0.9999990625F, 0.9999991562F, 0.9999992426F,
  153706. 0.9999993223F, 0.9999993954F, 0.9999994625F, 0.9999995239F,
  153707. 0.9999995798F, 0.9999996307F, 0.9999996768F, 0.9999997184F,
  153708. 0.9999997559F, 0.9999997895F, 0.9999998195F, 0.9999998462F,
  153709. 0.9999998698F, 0.9999998906F, 0.9999999088F, 0.9999999246F,
  153710. 0.9999999383F, 0.9999999500F, 0.9999999600F, 0.9999999684F,
  153711. 0.9999999754F, 0.9999999811F, 0.9999999858F, 0.9999999896F,
  153712. 0.9999999925F, 0.9999999948F, 0.9999999965F, 0.9999999978F,
  153713. 0.9999999986F, 0.9999999992F, 0.9999999996F, 0.9999999998F,
  153714. 0.9999999999F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  153715. };
  153716. static float vwin8192[4096] = {
  153717. 0.0000000578F, 0.0000005198F, 0.0000014438F, 0.0000028299F,
  153718. 0.0000046780F, 0.0000069882F, 0.0000097604F, 0.0000129945F,
  153719. 0.0000166908F, 0.0000208490F, 0.0000254692F, 0.0000305515F,
  153720. 0.0000360958F, 0.0000421021F, 0.0000485704F, 0.0000555006F,
  153721. 0.0000628929F, 0.0000707472F, 0.0000790635F, 0.0000878417F,
  153722. 0.0000970820F, 0.0001067842F, 0.0001169483F, 0.0001275744F,
  153723. 0.0001386625F, 0.0001502126F, 0.0001622245F, 0.0001746984F,
  153724. 0.0001876343F, 0.0002010320F, 0.0002148917F, 0.0002292132F,
  153725. 0.0002439967F, 0.0002592421F, 0.0002749493F, 0.0002911184F,
  153726. 0.0003077493F, 0.0003248421F, 0.0003423967F, 0.0003604132F,
  153727. 0.0003788915F, 0.0003978316F, 0.0004172335F, 0.0004370971F,
  153728. 0.0004574226F, 0.0004782098F, 0.0004994587F, 0.0005211694F,
  153729. 0.0005433418F, 0.0005659759F, 0.0005890717F, 0.0006126292F,
  153730. 0.0006366484F, 0.0006611292F, 0.0006860716F, 0.0007114757F,
  153731. 0.0007373414F, 0.0007636687F, 0.0007904576F, 0.0008177080F,
  153732. 0.0008454200F, 0.0008735935F, 0.0009022285F, 0.0009313250F,
  153733. 0.0009608830F, 0.0009909025F, 0.0010213834F, 0.0010523257F,
  153734. 0.0010837295F, 0.0011155946F, 0.0011479211F, 0.0011807090F,
  153735. 0.0012139582F, 0.0012476687F, 0.0012818405F, 0.0013164736F,
  153736. 0.0013515679F, 0.0013871235F, 0.0014231402F, 0.0014596182F,
  153737. 0.0014965573F, 0.0015339576F, 0.0015718190F, 0.0016101415F,
  153738. 0.0016489251F, 0.0016881698F, 0.0017278754F, 0.0017680421F,
  153739. 0.0018086698F, 0.0018497584F, 0.0018913080F, 0.0019333185F,
  153740. 0.0019757898F, 0.0020187221F, 0.0020621151F, 0.0021059690F,
  153741. 0.0021502837F, 0.0021950591F, 0.0022402953F, 0.0022859921F,
  153742. 0.0023321497F, 0.0023787679F, 0.0024258467F, 0.0024733861F,
  153743. 0.0025213861F, 0.0025698466F, 0.0026187676F, 0.0026681491F,
  153744. 0.0027179911F, 0.0027682935F, 0.0028190562F, 0.0028702794F,
  153745. 0.0029219628F, 0.0029741066F, 0.0030267107F, 0.0030797749F,
  153746. 0.0031332994F, 0.0031872841F, 0.0032417289F, 0.0032966338F,
  153747. 0.0033519988F, 0.0034078238F, 0.0034641089F, 0.0035208539F,
  153748. 0.0035780589F, 0.0036357237F, 0.0036938485F, 0.0037524331F,
  153749. 0.0038114775F, 0.0038709817F, 0.0039309456F, 0.0039913692F,
  153750. 0.0040522524F, 0.0041135953F, 0.0041753978F, 0.0042376599F,
  153751. 0.0043003814F, 0.0043635624F, 0.0044272029F, 0.0044913028F,
  153752. 0.0045558620F, 0.0046208806F, 0.0046863585F, 0.0047522955F,
  153753. 0.0048186919F, 0.0048855473F, 0.0049528619F, 0.0050206356F,
  153754. 0.0050888684F, 0.0051575601F, 0.0052267108F, 0.0052963204F,
  153755. 0.0053663890F, 0.0054369163F, 0.0055079025F, 0.0055793474F,
  153756. 0.0056512510F, 0.0057236133F, 0.0057964342F, 0.0058697137F,
  153757. 0.0059434517F, 0.0060176482F, 0.0060923032F, 0.0061674166F,
  153758. 0.0062429883F, 0.0063190183F, 0.0063955066F, 0.0064724532F,
  153759. 0.0065498579F, 0.0066277207F, 0.0067060416F, 0.0067848205F,
  153760. 0.0068640575F, 0.0069437523F, 0.0070239051F, 0.0071045157F,
  153761. 0.0071855840F, 0.0072671102F, 0.0073490940F, 0.0074315355F,
  153762. 0.0075144345F, 0.0075977911F, 0.0076816052F, 0.0077658768F,
  153763. 0.0078506057F, 0.0079357920F, 0.0080214355F, 0.0081075363F,
  153764. 0.0081940943F, 0.0082811094F, 0.0083685816F, 0.0084565108F,
  153765. 0.0085448970F, 0.0086337401F, 0.0087230401F, 0.0088127969F,
  153766. 0.0089030104F, 0.0089936807F, 0.0090848076F, 0.0091763911F,
  153767. 0.0092684311F, 0.0093609276F, 0.0094538805F, 0.0095472898F,
  153768. 0.0096411554F, 0.0097354772F, 0.0098302552F, 0.0099254894F,
  153769. 0.0100211796F, 0.0101173259F, 0.0102139281F, 0.0103109863F,
  153770. 0.0104085002F, 0.0105064700F, 0.0106048955F, 0.0107037766F,
  153771. 0.0108031133F, 0.0109029056F, 0.0110031534F, 0.0111038565F,
  153772. 0.0112050151F, 0.0113066289F, 0.0114086980F, 0.0115112222F,
  153773. 0.0116142015F, 0.0117176359F, 0.0118215252F, 0.0119258695F,
  153774. 0.0120306686F, 0.0121359225F, 0.0122416312F, 0.0123477944F,
  153775. 0.0124544123F, 0.0125614847F, 0.0126690116F, 0.0127769928F,
  153776. 0.0128854284F, 0.0129943182F, 0.0131036623F, 0.0132134604F,
  153777. 0.0133237126F, 0.0134344188F, 0.0135455790F, 0.0136571929F,
  153778. 0.0137692607F, 0.0138817821F, 0.0139947572F, 0.0141081859F,
  153779. 0.0142220681F, 0.0143364037F, 0.0144511927F, 0.0145664350F,
  153780. 0.0146821304F, 0.0147982791F, 0.0149148808F, 0.0150319355F,
  153781. 0.0151494431F, 0.0152674036F, 0.0153858168F, 0.0155046828F,
  153782. 0.0156240014F, 0.0157437726F, 0.0158639962F, 0.0159846723F,
  153783. 0.0161058007F, 0.0162273814F, 0.0163494142F, 0.0164718991F,
  153784. 0.0165948361F, 0.0167182250F, 0.0168420658F, 0.0169663584F,
  153785. 0.0170911027F, 0.0172162987F, 0.0173419462F, 0.0174680452F,
  153786. 0.0175945956F, 0.0177215974F, 0.0178490504F, 0.0179769545F,
  153787. 0.0181053098F, 0.0182341160F, 0.0183633732F, 0.0184930812F,
  153788. 0.0186232399F, 0.0187538494F, 0.0188849094F, 0.0190164200F,
  153789. 0.0191483809F, 0.0192807923F, 0.0194136539F, 0.0195469656F,
  153790. 0.0196807275F, 0.0198149394F, 0.0199496012F, 0.0200847128F,
  153791. 0.0202202742F, 0.0203562853F, 0.0204927460F, 0.0206296561F,
  153792. 0.0207670157F, 0.0209048245F, 0.0210430826F, 0.0211817899F,
  153793. 0.0213209462F, 0.0214605515F, 0.0216006057F, 0.0217411086F,
  153794. 0.0218820603F, 0.0220234605F, 0.0221653093F, 0.0223076066F,
  153795. 0.0224503521F, 0.0225935459F, 0.0227371879F, 0.0228812779F,
  153796. 0.0230258160F, 0.0231708018F, 0.0233162355F, 0.0234621169F,
  153797. 0.0236084459F, 0.0237552224F, 0.0239024462F, 0.0240501175F,
  153798. 0.0241982359F, 0.0243468015F, 0.0244958141F, 0.0246452736F,
  153799. 0.0247951800F, 0.0249455331F, 0.0250963329F, 0.0252475792F,
  153800. 0.0253992720F, 0.0255514111F, 0.0257039965F, 0.0258570281F,
  153801. 0.0260105057F, 0.0261644293F, 0.0263187987F, 0.0264736139F,
  153802. 0.0266288747F, 0.0267845811F, 0.0269407330F, 0.0270973302F,
  153803. 0.0272543727F, 0.0274118604F, 0.0275697930F, 0.0277281707F,
  153804. 0.0278869932F, 0.0280462604F, 0.0282059723F, 0.0283661287F,
  153805. 0.0285267295F, 0.0286877747F, 0.0288492641F, 0.0290111976F,
  153806. 0.0291735751F, 0.0293363965F, 0.0294996617F, 0.0296633706F,
  153807. 0.0298275231F, 0.0299921190F, 0.0301571583F, 0.0303226409F,
  153808. 0.0304885667F, 0.0306549354F, 0.0308217472F, 0.0309890017F,
  153809. 0.0311566989F, 0.0313248388F, 0.0314934211F, 0.0316624459F,
  153810. 0.0318319128F, 0.0320018220F, 0.0321721732F, 0.0323429663F,
  153811. 0.0325142013F, 0.0326858779F, 0.0328579962F, 0.0330305559F,
  153812. 0.0332035570F, 0.0333769994F, 0.0335508829F, 0.0337252074F,
  153813. 0.0338999728F, 0.0340751790F, 0.0342508259F, 0.0344269134F,
  153814. 0.0346034412F, 0.0347804094F, 0.0349578178F, 0.0351356663F,
  153815. 0.0353139548F, 0.0354926831F, 0.0356718511F, 0.0358514588F,
  153816. 0.0360315059F, 0.0362119924F, 0.0363929182F, 0.0365742831F,
  153817. 0.0367560870F, 0.0369383297F, 0.0371210113F, 0.0373041315F,
  153818. 0.0374876902F, 0.0376716873F, 0.0378561226F, 0.0380409961F,
  153819. 0.0382263077F, 0.0384120571F, 0.0385982443F, 0.0387848691F,
  153820. 0.0389719315F, 0.0391594313F, 0.0393473683F, 0.0395357425F,
  153821. 0.0397245537F, 0.0399138017F, 0.0401034866F, 0.0402936080F,
  153822. 0.0404841660F, 0.0406751603F, 0.0408665909F, 0.0410584576F,
  153823. 0.0412507603F, 0.0414434988F, 0.0416366731F, 0.0418302829F,
  153824. 0.0420243282F, 0.0422188088F, 0.0424137246F, 0.0426090755F,
  153825. 0.0428048613F, 0.0430010819F, 0.0431977371F, 0.0433948269F,
  153826. 0.0435923511F, 0.0437903095F, 0.0439887020F, 0.0441875285F,
  153827. 0.0443867889F, 0.0445864830F, 0.0447866106F, 0.0449871717F,
  153828. 0.0451881661F, 0.0453895936F, 0.0455914542F, 0.0457937477F,
  153829. 0.0459964738F, 0.0461996326F, 0.0464032239F, 0.0466072475F,
  153830. 0.0468117032F, 0.0470165910F, 0.0472219107F, 0.0474276622F,
  153831. 0.0476338452F, 0.0478404597F, 0.0480475056F, 0.0482549827F,
  153832. 0.0484628907F, 0.0486712297F, 0.0488799994F, 0.0490891998F,
  153833. 0.0492988306F, 0.0495088917F, 0.0497193830F, 0.0499303043F,
  153834. 0.0501416554F, 0.0503534363F, 0.0505656468F, 0.0507782867F,
  153835. 0.0509913559F, 0.0512048542F, 0.0514187815F, 0.0516331376F,
  153836. 0.0518479225F, 0.0520631358F, 0.0522787775F, 0.0524948475F,
  153837. 0.0527113455F, 0.0529282715F, 0.0531456252F, 0.0533634066F,
  153838. 0.0535816154F, 0.0538002515F, 0.0540193148F, 0.0542388051F,
  153839. 0.0544587222F, 0.0546790660F, 0.0548998364F, 0.0551210331F,
  153840. 0.0553426561F, 0.0555647051F, 0.0557871801F, 0.0560100807F,
  153841. 0.0562334070F, 0.0564571587F, 0.0566813357F, 0.0569059378F,
  153842. 0.0571309649F, 0.0573564168F, 0.0575822933F, 0.0578085942F,
  153843. 0.0580353195F, 0.0582624689F, 0.0584900423F, 0.0587180396F,
  153844. 0.0589464605F, 0.0591753049F, 0.0594045726F, 0.0596342635F,
  153845. 0.0598643774F, 0.0600949141F, 0.0603258735F, 0.0605572555F,
  153846. 0.0607890597F, 0.0610212862F, 0.0612539346F, 0.0614870049F,
  153847. 0.0617204968F, 0.0619544103F, 0.0621887451F, 0.0624235010F,
  153848. 0.0626586780F, 0.0628942758F, 0.0631302942F, 0.0633667331F,
  153849. 0.0636035923F, 0.0638408717F, 0.0640785710F, 0.0643166901F,
  153850. 0.0645552288F, 0.0647941870F, 0.0650335645F, 0.0652733610F,
  153851. 0.0655135765F, 0.0657542108F, 0.0659952636F, 0.0662367348F,
  153852. 0.0664786242F, 0.0667209316F, 0.0669636570F, 0.0672068000F,
  153853. 0.0674503605F, 0.0676943384F, 0.0679387334F, 0.0681835454F,
  153854. 0.0684287742F, 0.0686744196F, 0.0689204814F, 0.0691669595F,
  153855. 0.0694138536F, 0.0696611637F, 0.0699088894F, 0.0701570307F,
  153856. 0.0704055873F, 0.0706545590F, 0.0709039458F, 0.0711537473F,
  153857. 0.0714039634F, 0.0716545939F, 0.0719056387F, 0.0721570975F,
  153858. 0.0724089702F, 0.0726612565F, 0.0729139563F, 0.0731670694F,
  153859. 0.0734205956F, 0.0736745347F, 0.0739288866F, 0.0741836510F,
  153860. 0.0744388277F, 0.0746944166F, 0.0749504175F, 0.0752068301F,
  153861. 0.0754636543F, 0.0757208899F, 0.0759785367F, 0.0762365946F,
  153862. 0.0764950632F, 0.0767539424F, 0.0770132320F, 0.0772729319F,
  153863. 0.0775330418F, 0.0777935616F, 0.0780544909F, 0.0783158298F,
  153864. 0.0785775778F, 0.0788397349F, 0.0791023009F, 0.0793652755F,
  153865. 0.0796286585F, 0.0798924498F, 0.0801566492F, 0.0804212564F,
  153866. 0.0806862712F, 0.0809516935F, 0.0812175231F, 0.0814837597F,
  153867. 0.0817504031F, 0.0820174532F, 0.0822849097F, 0.0825527724F,
  153868. 0.0828210412F, 0.0830897158F, 0.0833587960F, 0.0836282816F,
  153869. 0.0838981724F, 0.0841684682F, 0.0844391688F, 0.0847102740F,
  153870. 0.0849817835F, 0.0852536973F, 0.0855260150F, 0.0857987364F,
  153871. 0.0860718614F, 0.0863453897F, 0.0866193211F, 0.0868936554F,
  153872. 0.0871683924F, 0.0874435319F, 0.0877190737F, 0.0879950175F,
  153873. 0.0882713632F, 0.0885481105F, 0.0888252592F, 0.0891028091F,
  153874. 0.0893807600F, 0.0896591117F, 0.0899378639F, 0.0902170165F,
  153875. 0.0904965692F, 0.0907765218F, 0.0910568740F, 0.0913376258F,
  153876. 0.0916187767F, 0.0919003268F, 0.0921822756F, 0.0924646230F,
  153877. 0.0927473687F, 0.0930305126F, 0.0933140545F, 0.0935979940F,
  153878. 0.0938823310F, 0.0941670653F, 0.0944521966F, 0.0947377247F,
  153879. 0.0950236494F, 0.0953099704F, 0.0955966876F, 0.0958838007F,
  153880. 0.0961713094F, 0.0964592136F, 0.0967475131F, 0.0970362075F,
  153881. 0.0973252967F, 0.0976147805F, 0.0979046585F, 0.0981949307F,
  153882. 0.0984855967F, 0.0987766563F, 0.0990681093F, 0.0993599555F,
  153883. 0.0996521945F, 0.0999448263F, 0.1002378506F, 0.1005312671F,
  153884. 0.1008250755F, 0.1011192757F, 0.1014138675F, 0.1017088505F,
  153885. 0.1020042246F, 0.1022999895F, 0.1025961450F, 0.1028926909F,
  153886. 0.1031896268F, 0.1034869526F, 0.1037846680F, 0.1040827729F,
  153887. 0.1043812668F, 0.1046801497F, 0.1049794213F, 0.1052790813F,
  153888. 0.1055791294F, 0.1058795656F, 0.1061803894F, 0.1064816006F,
  153889. 0.1067831991F, 0.1070851846F, 0.1073875568F, 0.1076903155F,
  153890. 0.1079934604F, 0.1082969913F, 0.1086009079F, 0.1089052101F,
  153891. 0.1092098975F, 0.1095149699F, 0.1098204270F, 0.1101262687F,
  153892. 0.1104324946F, 0.1107391045F, 0.1110460982F, 0.1113534754F,
  153893. 0.1116612359F, 0.1119693793F, 0.1122779055F, 0.1125868142F,
  153894. 0.1128961052F, 0.1132057781F, 0.1135158328F, 0.1138262690F,
  153895. 0.1141370863F, 0.1144482847F, 0.1147598638F, 0.1150718233F,
  153896. 0.1153841631F, 0.1156968828F, 0.1160099822F, 0.1163234610F,
  153897. 0.1166373190F, 0.1169515559F, 0.1172661714F, 0.1175811654F,
  153898. 0.1178965374F, 0.1182122874F, 0.1185284149F, 0.1188449198F,
  153899. 0.1191618018F, 0.1194790606F, 0.1197966960F, 0.1201147076F,
  153900. 0.1204330953F, 0.1207518587F, 0.1210709976F, 0.1213905118F,
  153901. 0.1217104009F, 0.1220306647F, 0.1223513029F, 0.1226723153F,
  153902. 0.1229937016F, 0.1233154615F, 0.1236375948F, 0.1239601011F,
  153903. 0.1242829803F, 0.1246062319F, 0.1249298559F, 0.1252538518F,
  153904. 0.1255782195F, 0.1259029586F, 0.1262280689F, 0.1265535501F,
  153905. 0.1268794019F, 0.1272056241F, 0.1275322163F, 0.1278591784F,
  153906. 0.1281865099F, 0.1285142108F, 0.1288422805F, 0.1291707190F,
  153907. 0.1294995259F, 0.1298287009F, 0.1301582437F, 0.1304881542F,
  153908. 0.1308184319F, 0.1311490766F, 0.1314800881F, 0.1318114660F,
  153909. 0.1321432100F, 0.1324753200F, 0.1328077955F, 0.1331406364F,
  153910. 0.1334738422F, 0.1338074129F, 0.1341413479F, 0.1344756472F,
  153911. 0.1348103103F, 0.1351453370F, 0.1354807270F, 0.1358164801F,
  153912. 0.1361525959F, 0.1364890741F, 0.1368259145F, 0.1371631167F,
  153913. 0.1375006805F, 0.1378386056F, 0.1381768917F, 0.1385155384F,
  153914. 0.1388545456F, 0.1391939129F, 0.1395336400F, 0.1398737266F,
  153915. 0.1402141724F, 0.1405549772F, 0.1408961406F, 0.1412376623F,
  153916. 0.1415795421F, 0.1419217797F, 0.1422643746F, 0.1426073268F,
  153917. 0.1429506358F, 0.1432943013F, 0.1436383231F, 0.1439827008F,
  153918. 0.1443274342F, 0.1446725229F, 0.1450179667F, 0.1453637652F,
  153919. 0.1457099181F, 0.1460564252F, 0.1464032861F, 0.1467505006F,
  153920. 0.1470980682F, 0.1474459888F, 0.1477942620F, 0.1481428875F,
  153921. 0.1484918651F, 0.1488411942F, 0.1491908748F, 0.1495409065F,
  153922. 0.1498912889F, 0.1502420218F, 0.1505931048F, 0.1509445376F,
  153923. 0.1512963200F, 0.1516484516F, 0.1520009321F, 0.1523537612F,
  153924. 0.1527069385F, 0.1530604638F, 0.1534143368F, 0.1537685571F,
  153925. 0.1541231244F, 0.1544780384F, 0.1548332987F, 0.1551889052F,
  153926. 0.1555448574F, 0.1559011550F, 0.1562577978F, 0.1566147853F,
  153927. 0.1569721173F, 0.1573297935F, 0.1576878135F, 0.1580461771F,
  153928. 0.1584048838F, 0.1587639334F, 0.1591233255F, 0.1594830599F,
  153929. 0.1598431361F, 0.1602035540F, 0.1605643131F, 0.1609254131F,
  153930. 0.1612868537F, 0.1616486346F, 0.1620107555F, 0.1623732160F,
  153931. 0.1627360158F, 0.1630991545F, 0.1634626319F, 0.1638264476F,
  153932. 0.1641906013F, 0.1645550926F, 0.1649199212F, 0.1652850869F,
  153933. 0.1656505892F, 0.1660164278F, 0.1663826024F, 0.1667491127F,
  153934. 0.1671159583F, 0.1674831388F, 0.1678506541F, 0.1682185036F,
  153935. 0.1685866872F, 0.1689552044F, 0.1693240549F, 0.1696932384F,
  153936. 0.1700627545F, 0.1704326029F, 0.1708027833F, 0.1711732952F,
  153937. 0.1715441385F, 0.1719153127F, 0.1722868175F, 0.1726586526F,
  153938. 0.1730308176F, 0.1734033121F, 0.1737761359F, 0.1741492886F,
  153939. 0.1745227698F, 0.1748965792F, 0.1752707164F, 0.1756451812F,
  153940. 0.1760199731F, 0.1763950918F, 0.1767705370F, 0.1771463083F,
  153941. 0.1775224054F, 0.1778988279F, 0.1782755754F, 0.1786526477F,
  153942. 0.1790300444F, 0.1794077651F, 0.1797858094F, 0.1801641771F,
  153943. 0.1805428677F, 0.1809218810F, 0.1813012165F, 0.1816808739F,
  153944. 0.1820608528F, 0.1824411530F, 0.1828217739F, 0.1832027154F,
  153945. 0.1835839770F, 0.1839655584F, 0.1843474592F, 0.1847296790F,
  153946. 0.1851122175F, 0.1854950744F, 0.1858782492F, 0.1862617417F,
  153947. 0.1866455514F, 0.1870296780F, 0.1874141211F, 0.1877988804F,
  153948. 0.1881839555F, 0.1885693461F, 0.1889550517F, 0.1893410721F,
  153949. 0.1897274068F, 0.1901140555F, 0.1905010178F, 0.1908882933F,
  153950. 0.1912758818F, 0.1916637828F, 0.1920519959F, 0.1924405208F,
  153951. 0.1928293571F, 0.1932185044F, 0.1936079625F, 0.1939977308F,
  153952. 0.1943878091F, 0.1947781969F, 0.1951688939F, 0.1955598998F,
  153953. 0.1959512141F, 0.1963428364F, 0.1967347665F, 0.1971270038F,
  153954. 0.1975195482F, 0.1979123990F, 0.1983055561F, 0.1986990190F,
  153955. 0.1990927873F, 0.1994868607F, 0.1998812388F, 0.2002759212F,
  153956. 0.2006709075F, 0.2010661974F, 0.2014617904F, 0.2018576862F,
  153957. 0.2022538844F, 0.2026503847F, 0.2030471865F, 0.2034442897F,
  153958. 0.2038416937F, 0.2042393982F, 0.2046374028F, 0.2050357071F,
  153959. 0.2054343107F, 0.2058332133F, 0.2062324145F, 0.2066319138F,
  153960. 0.2070317110F, 0.2074318055F, 0.2078321970F, 0.2082328852F,
  153961. 0.2086338696F, 0.2090351498F, 0.2094367255F, 0.2098385962F,
  153962. 0.2102407617F, 0.2106432213F, 0.2110459749F, 0.2114490220F,
  153963. 0.2118523621F, 0.2122559950F, 0.2126599202F, 0.2130641373F,
  153964. 0.2134686459F, 0.2138734456F, 0.2142785361F, 0.2146839168F,
  153965. 0.2150895875F, 0.2154955478F, 0.2159017972F, 0.2163083353F,
  153966. 0.2167151617F, 0.2171222761F, 0.2175296780F, 0.2179373670F,
  153967. 0.2183453428F, 0.2187536049F, 0.2191621529F, 0.2195709864F,
  153968. 0.2199801051F, 0.2203895085F, 0.2207991961F, 0.2212091677F,
  153969. 0.2216194228F, 0.2220299610F, 0.2224407818F, 0.2228518850F,
  153970. 0.2232632699F, 0.2236749364F, 0.2240868839F, 0.2244991121F,
  153971. 0.2249116204F, 0.2253244086F, 0.2257374763F, 0.2261508229F,
  153972. 0.2265644481F, 0.2269783514F, 0.2273925326F, 0.2278069911F,
  153973. 0.2282217265F, 0.2286367384F, 0.2290520265F, 0.2294675902F,
  153974. 0.2298834292F, 0.2302995431F, 0.2307159314F, 0.2311325937F,
  153975. 0.2315495297F, 0.2319667388F, 0.2323842207F, 0.2328019749F,
  153976. 0.2332200011F, 0.2336382988F, 0.2340568675F, 0.2344757070F,
  153977. 0.2348948166F, 0.2353141961F, 0.2357338450F, 0.2361537629F,
  153978. 0.2365739493F, 0.2369944038F, 0.2374151261F, 0.2378361156F,
  153979. 0.2382573720F, 0.2386788948F, 0.2391006836F, 0.2395227380F,
  153980. 0.2399450575F, 0.2403676417F, 0.2407904902F, 0.2412136026F,
  153981. 0.2416369783F, 0.2420606171F, 0.2424845185F, 0.2429086820F,
  153982. 0.2433331072F, 0.2437577936F, 0.2441827409F, 0.2446079486F,
  153983. 0.2450334163F, 0.2454591435F, 0.2458851298F, 0.2463113747F,
  153984. 0.2467378779F, 0.2471646389F, 0.2475916573F, 0.2480189325F,
  153985. 0.2484464643F, 0.2488742521F, 0.2493022955F, 0.2497305940F,
  153986. 0.2501591473F, 0.2505879549F, 0.2510170163F, 0.2514463311F,
  153987. 0.2518758989F, 0.2523057193F, 0.2527357916F, 0.2531661157F,
  153988. 0.2535966909F, 0.2540275169F, 0.2544585931F, 0.2548899193F,
  153989. 0.2553214948F, 0.2557533193F, 0.2561853924F, 0.2566177135F,
  153990. 0.2570502822F, 0.2574830981F, 0.2579161608F, 0.2583494697F,
  153991. 0.2587830245F, 0.2592168246F, 0.2596508697F, 0.2600851593F,
  153992. 0.2605196929F, 0.2609544701F, 0.2613894904F, 0.2618247534F,
  153993. 0.2622602586F, 0.2626960055F, 0.2631319938F, 0.2635682230F,
  153994. 0.2640046925F, 0.2644414021F, 0.2648783511F, 0.2653155391F,
  153995. 0.2657529657F, 0.2661906305F, 0.2666285329F, 0.2670666725F,
  153996. 0.2675050489F, 0.2679436616F, 0.2683825101F, 0.2688215940F,
  153997. 0.2692609127F, 0.2697004660F, 0.2701402532F, 0.2705802739F,
  153998. 0.2710205278F, 0.2714610142F, 0.2719017327F, 0.2723426830F,
  153999. 0.2727838644F, 0.2732252766F, 0.2736669191F, 0.2741087914F,
  154000. 0.2745508930F, 0.2749932235F, 0.2754357824F, 0.2758785693F,
  154001. 0.2763215837F, 0.2767648251F, 0.2772082930F, 0.2776519870F,
  154002. 0.2780959066F, 0.2785400513F, 0.2789844207F, 0.2794290143F,
  154003. 0.2798738316F, 0.2803188722F, 0.2807641355F, 0.2812096211F,
  154004. 0.2816553286F, 0.2821012574F, 0.2825474071F, 0.2829937773F,
  154005. 0.2834403673F, 0.2838871768F, 0.2843342053F, 0.2847814523F,
  154006. 0.2852289174F, 0.2856765999F, 0.2861244996F, 0.2865726159F,
  154007. 0.2870209482F, 0.2874694962F, 0.2879182594F, 0.2883672372F,
  154008. 0.2888164293F, 0.2892658350F, 0.2897154540F, 0.2901652858F,
  154009. 0.2906153298F, 0.2910655856F, 0.2915160527F, 0.2919667306F,
  154010. 0.2924176189F, 0.2928687171F, 0.2933200246F, 0.2937715409F,
  154011. 0.2942232657F, 0.2946751984F, 0.2951273386F, 0.2955796856F,
  154012. 0.2960322391F, 0.2964849986F, 0.2969379636F, 0.2973911335F,
  154013. 0.2978445080F, 0.2982980864F, 0.2987518684F, 0.2992058534F,
  154014. 0.2996600409F, 0.3001144305F, 0.3005690217F, 0.3010238139F,
  154015. 0.3014788067F, 0.3019339995F, 0.3023893920F, 0.3028449835F,
  154016. 0.3033007736F, 0.3037567618F, 0.3042129477F, 0.3046693306F,
  154017. 0.3051259102F, 0.3055826859F, 0.3060396572F, 0.3064968236F,
  154018. 0.3069541847F, 0.3074117399F, 0.3078694887F, 0.3083274307F,
  154019. 0.3087855653F, 0.3092438920F, 0.3097024104F, 0.3101611199F,
  154020. 0.3106200200F, 0.3110791103F, 0.3115383902F, 0.3119978592F,
  154021. 0.3124575169F, 0.3129173627F, 0.3133773961F, 0.3138376166F,
  154022. 0.3142980238F, 0.3147586170F, 0.3152193959F, 0.3156803598F,
  154023. 0.3161415084F, 0.3166028410F, 0.3170643573F, 0.3175260566F,
  154024. 0.3179879384F, 0.3184500023F, 0.3189122478F, 0.3193746743F,
  154025. 0.3198372814F, 0.3203000685F, 0.3207630351F, 0.3212261807F,
  154026. 0.3216895048F, 0.3221530069F, 0.3226166865F, 0.3230805430F,
  154027. 0.3235445760F, 0.3240087849F, 0.3244731693F, 0.3249377285F,
  154028. 0.3254024622F, 0.3258673698F, 0.3263324507F, 0.3267977045F,
  154029. 0.3272631306F, 0.3277287286F, 0.3281944978F, 0.3286604379F,
  154030. 0.3291265482F, 0.3295928284F, 0.3300592777F, 0.3305258958F,
  154031. 0.3309926821F, 0.3314596361F, 0.3319267573F, 0.3323940451F,
  154032. 0.3328614990F, 0.3333291186F, 0.3337969033F, 0.3342648525F,
  154033. 0.3347329658F, 0.3352012427F, 0.3356696825F, 0.3361382849F,
  154034. 0.3366070492F, 0.3370759749F, 0.3375450616F, 0.3380143087F,
  154035. 0.3384837156F, 0.3389532819F, 0.3394230071F, 0.3398928905F,
  154036. 0.3403629317F, 0.3408331302F, 0.3413034854F, 0.3417739967F,
  154037. 0.3422446638F, 0.3427154860F, 0.3431864628F, 0.3436575938F,
  154038. 0.3441288782F, 0.3446003158F, 0.3450719058F, 0.3455436478F,
  154039. 0.3460155412F, 0.3464875856F, 0.3469597804F, 0.3474321250F,
  154040. 0.3479046189F, 0.3483772617F, 0.3488500527F, 0.3493229914F,
  154041. 0.3497960774F, 0.3502693100F, 0.3507426887F, 0.3512162131F,
  154042. 0.3516898825F, 0.3521636965F, 0.3526376545F, 0.3531117559F,
  154043. 0.3535860003F, 0.3540603870F, 0.3545349157F, 0.3550095856F,
  154044. 0.3554843964F, 0.3559593474F, 0.3564344381F, 0.3569096680F,
  154045. 0.3573850366F, 0.3578605432F, 0.3583361875F, 0.3588119687F,
  154046. 0.3592878865F, 0.3597639402F, 0.3602401293F, 0.3607164533F,
  154047. 0.3611929117F, 0.3616695038F, 0.3621462292F, 0.3626230873F,
  154048. 0.3631000776F, 0.3635771995F, 0.3640544525F, 0.3645318360F,
  154049. 0.3650093496F, 0.3654869926F, 0.3659647645F, 0.3664426648F,
  154050. 0.3669206930F, 0.3673988484F, 0.3678771306F, 0.3683555390F,
  154051. 0.3688340731F, 0.3693127322F, 0.3697915160F, 0.3702704237F,
  154052. 0.3707494549F, 0.3712286091F, 0.3717078857F, 0.3721872840F,
  154053. 0.3726668037F, 0.3731464441F, 0.3736262047F, 0.3741060850F,
  154054. 0.3745860843F, 0.3750662023F, 0.3755464382F, 0.3760267915F,
  154055. 0.3765072618F, 0.3769878484F, 0.3774685509F, 0.3779493686F,
  154056. 0.3784303010F, 0.3789113475F, 0.3793925076F, 0.3798737809F,
  154057. 0.3803551666F, 0.3808366642F, 0.3813182733F, 0.3817999932F,
  154058. 0.3822818234F, 0.3827637633F, 0.3832458124F, 0.3837279702F,
  154059. 0.3842102360F, 0.3846926093F, 0.3851750897F, 0.3856576764F,
  154060. 0.3861403690F, 0.3866231670F, 0.3871060696F, 0.3875890765F,
  154061. 0.3880721870F, 0.3885554007F, 0.3890387168F, 0.3895221349F,
  154062. 0.3900056544F, 0.3904892748F, 0.3909729955F, 0.3914568160F,
  154063. 0.3919407356F, 0.3924247539F, 0.3929088702F, 0.3933930841F,
  154064. 0.3938773949F, 0.3943618021F, 0.3948463052F, 0.3953309035F,
  154065. 0.3958155966F, 0.3963003838F, 0.3967852646F, 0.3972702385F,
  154066. 0.3977553048F, 0.3982404631F, 0.3987257127F, 0.3992110531F,
  154067. 0.3996964838F, 0.4001820041F, 0.4006676136F, 0.4011533116F,
  154068. 0.4016390976F, 0.4021249710F, 0.4026109313F, 0.4030969779F,
  154069. 0.4035831102F, 0.4040693277F, 0.4045556299F, 0.4050420160F,
  154070. 0.4055284857F, 0.4060150383F, 0.4065016732F, 0.4069883899F,
  154071. 0.4074751879F, 0.4079620665F, 0.4084490252F, 0.4089360635F,
  154072. 0.4094231807F, 0.4099103763F, 0.4103976498F, 0.4108850005F,
  154073. 0.4113724280F, 0.4118599315F, 0.4123475107F, 0.4128351648F,
  154074. 0.4133228934F, 0.4138106959F, 0.4142985716F, 0.4147865201F,
  154075. 0.4152745408F, 0.4157626330F, 0.4162507963F, 0.4167390301F,
  154076. 0.4172273337F, 0.4177157067F, 0.4182041484F, 0.4186926583F,
  154077. 0.4191812359F, 0.4196698805F, 0.4201585915F, 0.4206473685F,
  154078. 0.4211362108F, 0.4216251179F, 0.4221140892F, 0.4226031241F,
  154079. 0.4230922221F, 0.4235813826F, 0.4240706050F, 0.4245598887F,
  154080. 0.4250492332F, 0.4255386379F, 0.4260281022F, 0.4265176256F,
  154081. 0.4270072075F, 0.4274968473F, 0.4279865445F, 0.4284762984F,
  154082. 0.4289661086F, 0.4294559743F, 0.4299458951F, 0.4304358704F,
  154083. 0.4309258996F, 0.4314159822F, 0.4319061175F, 0.4323963050F,
  154084. 0.4328865441F, 0.4333768342F, 0.4338671749F, 0.4343575654F,
  154085. 0.4348480052F, 0.4353384938F, 0.4358290306F, 0.4363196149F,
  154086. 0.4368102463F, 0.4373009241F, 0.4377916478F, 0.4382824168F,
  154087. 0.4387732305F, 0.4392640884F, 0.4397549899F, 0.4402459343F,
  154088. 0.4407369212F, 0.4412279499F, 0.4417190198F, 0.4422101305F,
  154089. 0.4427012813F, 0.4431924717F, 0.4436837010F, 0.4441749686F,
  154090. 0.4446662742F, 0.4451576169F, 0.4456489963F, 0.4461404118F,
  154091. 0.4466318628F, 0.4471233487F, 0.4476148690F, 0.4481064230F,
  154092. 0.4485980103F, 0.4490896302F, 0.4495812821F, 0.4500729654F,
  154093. 0.4505646797F, 0.4510564243F, 0.4515481986F, 0.4520400021F,
  154094. 0.4525318341F, 0.4530236942F, 0.4535155816F, 0.4540074959F,
  154095. 0.4544994365F, 0.4549914028F, 0.4554833941F, 0.4559754100F,
  154096. 0.4564674499F, 0.4569595131F, 0.4574515991F, 0.4579437074F,
  154097. 0.4584358372F, 0.4589279881F, 0.4594201595F, 0.4599123508F,
  154098. 0.4604045615F, 0.4608967908F, 0.4613890383F, 0.4618813034F,
  154099. 0.4623735855F, 0.4628658841F, 0.4633581984F, 0.4638505281F,
  154100. 0.4643428724F, 0.4648352308F, 0.4653276028F, 0.4658199877F,
  154101. 0.4663123849F, 0.4668047940F, 0.4672972143F, 0.4677896451F,
  154102. 0.4682820861F, 0.4687745365F, 0.4692669958F, 0.4697594634F,
  154103. 0.4702519387F, 0.4707444211F, 0.4712369102F, 0.4717294052F,
  154104. 0.4722219056F, 0.4727144109F, 0.4732069204F, 0.4736994336F,
  154105. 0.4741919498F, 0.4746844686F, 0.4751769893F, 0.4756695113F,
  154106. 0.4761620341F, 0.4766545571F, 0.4771470797F, 0.4776396013F,
  154107. 0.4781321213F, 0.4786246392F, 0.4791171544F, 0.4796096663F,
  154108. 0.4801021744F, 0.4805946779F, 0.4810871765F, 0.4815796694F,
  154109. 0.4820721561F, 0.4825646360F, 0.4830571086F, 0.4835495732F,
  154110. 0.4840420293F, 0.4845344763F, 0.4850269136F, 0.4855193407F,
  154111. 0.4860117569F, 0.4865041617F, 0.4869965545F, 0.4874889347F,
  154112. 0.4879813018F, 0.4884736551F, 0.4889659941F, 0.4894583182F,
  154113. 0.4899506268F, 0.4904429193F, 0.4909351952F, 0.4914274538F,
  154114. 0.4919196947F, 0.4924119172F, 0.4929041207F, 0.4933963046F,
  154115. 0.4938884685F, 0.4943806116F, 0.4948727335F, 0.4953648335F,
  154116. 0.4958569110F, 0.4963489656F, 0.4968409965F, 0.4973330032F,
  154117. 0.4978249852F, 0.4983169419F, 0.4988088726F, 0.4993007768F,
  154118. 0.4997926539F, 0.5002845034F, 0.5007763247F, 0.5012681171F,
  154119. 0.5017598801F, 0.5022516132F, 0.5027433157F, 0.5032349871F,
  154120. 0.5037266268F, 0.5042182341F, 0.5047098086F, 0.5052013497F,
  154121. 0.5056928567F, 0.5061843292F, 0.5066757664F, 0.5071671679F,
  154122. 0.5076585330F, 0.5081498613F, 0.5086411520F, 0.5091324047F,
  154123. 0.5096236187F, 0.5101147934F, 0.5106059284F, 0.5110970230F,
  154124. 0.5115880766F, 0.5120790887F, 0.5125700587F, 0.5130609860F,
  154125. 0.5135518700F, 0.5140427102F, 0.5145335059F, 0.5150242566F,
  154126. 0.5155149618F, 0.5160056208F, 0.5164962331F, 0.5169867980F,
  154127. 0.5174773151F, 0.5179677837F, 0.5184582033F, 0.5189485733F,
  154128. 0.5194388931F, 0.5199291621F, 0.5204193798F, 0.5209095455F,
  154129. 0.5213996588F, 0.5218897190F, 0.5223797256F, 0.5228696779F,
  154130. 0.5233595755F, 0.5238494177F, 0.5243392039F, 0.5248289337F,
  154131. 0.5253186063F, 0.5258082213F, 0.5262977781F, 0.5267872760F,
  154132. 0.5272767146F, 0.5277660932F, 0.5282554112F, 0.5287446682F,
  154133. 0.5292338635F, 0.5297229965F, 0.5302120667F, 0.5307010736F,
  154134. 0.5311900164F, 0.5316788947F, 0.5321677079F, 0.5326564554F,
  154135. 0.5331451366F, 0.5336337511F, 0.5341222981F, 0.5346107771F,
  154136. 0.5350991876F, 0.5355875290F, 0.5360758007F, 0.5365640021F,
  154137. 0.5370521327F, 0.5375401920F, 0.5380281792F, 0.5385160939F,
  154138. 0.5390039355F, 0.5394917034F, 0.5399793971F, 0.5404670159F,
  154139. 0.5409545594F, 0.5414420269F, 0.5419294179F, 0.5424167318F,
  154140. 0.5429039680F, 0.5433911261F, 0.5438782053F, 0.5443652051F,
  154141. 0.5448521250F, 0.5453389644F, 0.5458257228F, 0.5463123995F,
  154142. 0.5467989940F, 0.5472855057F, 0.5477719341F, 0.5482582786F,
  154143. 0.5487445387F, 0.5492307137F, 0.5497168031F, 0.5502028063F,
  154144. 0.5506887228F, 0.5511745520F, 0.5516602934F, 0.5521459463F,
  154145. 0.5526315103F, 0.5531169847F, 0.5536023690F, 0.5540876626F,
  154146. 0.5545728649F, 0.5550579755F, 0.5555429937F, 0.5560279189F,
  154147. 0.5565127507F, 0.5569974884F, 0.5574821315F, 0.5579666794F,
  154148. 0.5584511316F, 0.5589354875F, 0.5594197465F, 0.5599039080F,
  154149. 0.5603879716F, 0.5608719367F, 0.5613558026F, 0.5618395689F,
  154150. 0.5623232350F, 0.5628068002F, 0.5632902642F, 0.5637736262F,
  154151. 0.5642568858F, 0.5647400423F, 0.5652230953F, 0.5657060442F,
  154152. 0.5661888883F, 0.5666716272F, 0.5671542603F, 0.5676367870F,
  154153. 0.5681192069F, 0.5686015192F, 0.5690837235F, 0.5695658192F,
  154154. 0.5700478058F, 0.5705296827F, 0.5710114494F, 0.5714931052F,
  154155. 0.5719746497F, 0.5724560822F, 0.5729374023F, 0.5734186094F,
  154156. 0.5738997029F, 0.5743806823F, 0.5748615470F, 0.5753422965F,
  154157. 0.5758229301F, 0.5763034475F, 0.5767838480F, 0.5772641310F,
  154158. 0.5777442960F, 0.5782243426F, 0.5787042700F, 0.5791840778F,
  154159. 0.5796637654F, 0.5801433322F, 0.5806227778F, 0.5811021016F,
  154160. 0.5815813029F, 0.5820603814F, 0.5825393363F, 0.5830181673F,
  154161. 0.5834968737F, 0.5839754549F, 0.5844539105F, 0.5849322399F,
  154162. 0.5854104425F, 0.5858885179F, 0.5863664653F, 0.5868442844F,
  154163. 0.5873219746F, 0.5877995353F, 0.5882769660F, 0.5887542661F,
  154164. 0.5892314351F, 0.5897084724F, 0.5901853776F, 0.5906621500F,
  154165. 0.5911387892F, 0.5916152945F, 0.5920916655F, 0.5925679016F,
  154166. 0.5930440022F, 0.5935199669F, 0.5939957950F, 0.5944714861F,
  154167. 0.5949470396F, 0.5954224550F, 0.5958977317F, 0.5963728692F,
  154168. 0.5968478669F, 0.5973227244F, 0.5977974411F, 0.5982720163F,
  154169. 0.5987464497F, 0.5992207407F, 0.5996948887F, 0.6001688932F,
  154170. 0.6006427537F, 0.6011164696F, 0.6015900405F, 0.6020634657F,
  154171. 0.6025367447F, 0.6030098770F, 0.6034828621F, 0.6039556995F,
  154172. 0.6044283885F, 0.6049009288F, 0.6053733196F, 0.6058455606F,
  154173. 0.6063176512F, 0.6067895909F, 0.6072613790F, 0.6077330152F,
  154174. 0.6082044989F, 0.6086758295F, 0.6091470065F, 0.6096180294F,
  154175. 0.6100888977F, 0.6105596108F, 0.6110301682F, 0.6115005694F,
  154176. 0.6119708139F, 0.6124409011F, 0.6129108305F, 0.6133806017F,
  154177. 0.6138502139F, 0.6143196669F, 0.6147889599F, 0.6152580926F,
  154178. 0.6157270643F, 0.6161958746F, 0.6166645230F, 0.6171330088F,
  154179. 0.6176013317F, 0.6180694910F, 0.6185374863F, 0.6190053171F,
  154180. 0.6194729827F, 0.6199404828F, 0.6204078167F, 0.6208749841F,
  154181. 0.6213419842F, 0.6218088168F, 0.6222754811F, 0.6227419768F,
  154182. 0.6232083032F, 0.6236744600F, 0.6241404465F, 0.6246062622F,
  154183. 0.6250719067F, 0.6255373795F, 0.6260026799F, 0.6264678076F,
  154184. 0.6269327619F, 0.6273975425F, 0.6278621487F, 0.6283265800F,
  154185. 0.6287908361F, 0.6292549163F, 0.6297188201F, 0.6301825471F,
  154186. 0.6306460966F, 0.6311094683F, 0.6315726617F, 0.6320356761F,
  154187. 0.6324985111F, 0.6329611662F, 0.6334236410F, 0.6338859348F,
  154188. 0.6343480472F, 0.6348099777F, 0.6352717257F, 0.6357332909F,
  154189. 0.6361946726F, 0.6366558704F, 0.6371168837F, 0.6375777122F,
  154190. 0.6380383552F, 0.6384988123F, 0.6389590830F, 0.6394191668F,
  154191. 0.6398790631F, 0.6403387716F, 0.6407982916F, 0.6412576228F,
  154192. 0.6417167645F, 0.6421757163F, 0.6426344778F, 0.6430930483F,
  154193. 0.6435514275F, 0.6440096149F, 0.6444676098F, 0.6449254119F,
  154194. 0.6453830207F, 0.6458404356F, 0.6462976562F, 0.6467546820F,
  154195. 0.6472115125F, 0.6476681472F, 0.6481245856F, 0.6485808273F,
  154196. 0.6490368717F, 0.6494927183F, 0.6499483667F, 0.6504038164F,
  154197. 0.6508590670F, 0.6513141178F, 0.6517689684F, 0.6522236185F,
  154198. 0.6526780673F, 0.6531323146F, 0.6535863598F, 0.6540402024F,
  154199. 0.6544938419F, 0.6549472779F, 0.6554005099F, 0.6558535373F,
  154200. 0.6563063598F, 0.6567589769F, 0.6572113880F, 0.6576635927F,
  154201. 0.6581155906F, 0.6585673810F, 0.6590189637F, 0.6594703380F,
  154202. 0.6599215035F, 0.6603724598F, 0.6608232064F, 0.6612737427F,
  154203. 0.6617240684F, 0.6621741829F, 0.6626240859F, 0.6630737767F,
  154204. 0.6635232550F, 0.6639725202F, 0.6644215720F, 0.6648704098F,
  154205. 0.6653190332F, 0.6657674417F, 0.6662156348F, 0.6666636121F,
  154206. 0.6671113731F, 0.6675589174F, 0.6680062445F, 0.6684533538F,
  154207. 0.6689002450F, 0.6693469177F, 0.6697933712F, 0.6702396052F,
  154208. 0.6706856193F, 0.6711314129F, 0.6715769855F, 0.6720223369F,
  154209. 0.6724674664F, 0.6729123736F, 0.6733570581F, 0.6738015194F,
  154210. 0.6742457570F, 0.6746897706F, 0.6751335596F, 0.6755771236F,
  154211. 0.6760204621F, 0.6764635747F, 0.6769064609F, 0.6773491204F,
  154212. 0.6777915525F, 0.6782337570F, 0.6786757332F, 0.6791174809F,
  154213. 0.6795589995F, 0.6800002886F, 0.6804413477F, 0.6808821765F,
  154214. 0.6813227743F, 0.6817631409F, 0.6822032758F, 0.6826431785F,
  154215. 0.6830828485F, 0.6835222855F, 0.6839614890F, 0.6844004585F,
  154216. 0.6848391936F, 0.6852776939F, 0.6857159589F, 0.6861539883F,
  154217. 0.6865917815F, 0.6870293381F, 0.6874666576F, 0.6879037398F,
  154218. 0.6883405840F, 0.6887771899F, 0.6892135571F, 0.6896496850F,
  154219. 0.6900855733F, 0.6905212216F, 0.6909566294F, 0.6913917963F,
  154220. 0.6918267218F, 0.6922614055F, 0.6926958471F, 0.6931300459F,
  154221. 0.6935640018F, 0.6939977141F, 0.6944311825F, 0.6948644066F,
  154222. 0.6952973859F, 0.6957301200F, 0.6961626085F, 0.6965948510F,
  154223. 0.6970268470F, 0.6974585961F, 0.6978900980F, 0.6983213521F,
  154224. 0.6987523580F, 0.6991831154F, 0.6996136238F, 0.7000438828F,
  154225. 0.7004738921F, 0.7009036510F, 0.7013331594F, 0.7017624166F,
  154226. 0.7021914224F, 0.7026201763F, 0.7030486779F, 0.7034769268F,
  154227. 0.7039049226F, 0.7043326648F, 0.7047601531F, 0.7051873870F,
  154228. 0.7056143662F, 0.7060410902F, 0.7064675586F, 0.7068937711F,
  154229. 0.7073197271F, 0.7077454264F, 0.7081708684F, 0.7085960529F,
  154230. 0.7090209793F, 0.7094456474F, 0.7098700566F, 0.7102942066F,
  154231. 0.7107180970F, 0.7111417274F, 0.7115650974F, 0.7119882066F,
  154232. 0.7124110545F, 0.7128336409F, 0.7132559653F, 0.7136780272F,
  154233. 0.7140998264F, 0.7145213624F, 0.7149426348F, 0.7153636433F,
  154234. 0.7157843874F, 0.7162048668F, 0.7166250810F, 0.7170450296F,
  154235. 0.7174647124F, 0.7178841289F, 0.7183032786F, 0.7187221613F,
  154236. 0.7191407765F, 0.7195591239F, 0.7199772030F, 0.7203950135F,
  154237. 0.7208125550F, 0.7212298271F, 0.7216468294F, 0.7220635616F,
  154238. 0.7224800233F, 0.7228962140F, 0.7233121335F, 0.7237277813F,
  154239. 0.7241431571F, 0.7245582604F, 0.7249730910F, 0.7253876484F,
  154240. 0.7258019322F, 0.7262159422F, 0.7266296778F, 0.7270431388F,
  154241. 0.7274563247F, 0.7278692353F, 0.7282818700F, 0.7286942287F,
  154242. 0.7291063108F, 0.7295181160F, 0.7299296440F, 0.7303408944F,
  154243. 0.7307518669F, 0.7311625609F, 0.7315729763F, 0.7319831126F,
  154244. 0.7323929695F, 0.7328025466F, 0.7332118435F, 0.7336208600F,
  154245. 0.7340295955F, 0.7344380499F, 0.7348462226F, 0.7352541134F,
  154246. 0.7356617220F, 0.7360690478F, 0.7364760907F, 0.7368828502F,
  154247. 0.7372893259F, 0.7376955176F, 0.7381014249F, 0.7385070475F,
  154248. 0.7389123849F, 0.7393174368F, 0.7397222029F, 0.7401266829F,
  154249. 0.7405308763F, 0.7409347829F, 0.7413384023F, 0.7417417341F,
  154250. 0.7421447780F, 0.7425475338F, 0.7429500009F, 0.7433521791F,
  154251. 0.7437540681F, 0.7441556674F, 0.7445569769F, 0.7449579960F,
  154252. 0.7453587245F, 0.7457591621F, 0.7461593084F, 0.7465591631F,
  154253. 0.7469587259F, 0.7473579963F, 0.7477569741F, 0.7481556590F,
  154254. 0.7485540506F, 0.7489521486F, 0.7493499526F, 0.7497474623F,
  154255. 0.7501446775F, 0.7505415977F, 0.7509382227F, 0.7513345521F,
  154256. 0.7517305856F, 0.7521263229F, 0.7525217636F, 0.7529169074F,
  154257. 0.7533117541F, 0.7537063032F, 0.7541005545F, 0.7544945076F,
  154258. 0.7548881623F, 0.7552815182F, 0.7556745749F, 0.7560673323F,
  154259. 0.7564597899F, 0.7568519474F, 0.7572438046F, 0.7576353611F,
  154260. 0.7580266166F, 0.7584175708F, 0.7588082235F, 0.7591985741F,
  154261. 0.7595886226F, 0.7599783685F, 0.7603678116F, 0.7607569515F,
  154262. 0.7611457879F, 0.7615343206F, 0.7619225493F, 0.7623104735F,
  154263. 0.7626980931F, 0.7630854078F, 0.7634724171F, 0.7638591209F,
  154264. 0.7642455188F, 0.7646316106F, 0.7650173959F, 0.7654028744F,
  154265. 0.7657880459F, 0.7661729100F, 0.7665574664F, 0.7669417150F,
  154266. 0.7673256553F, 0.7677092871F, 0.7680926100F, 0.7684756239F,
  154267. 0.7688583284F, 0.7692407232F, 0.7696228080F, 0.7700045826F,
  154268. 0.7703860467F, 0.7707671999F, 0.7711480420F, 0.7715285728F,
  154269. 0.7719087918F, 0.7722886989F, 0.7726682938F, 0.7730475762F,
  154270. 0.7734265458F, 0.7738052023F, 0.7741835454F, 0.7745615750F,
  154271. 0.7749392906F, 0.7753166921F, 0.7756937791F, 0.7760705514F,
  154272. 0.7764470087F, 0.7768231508F, 0.7771989773F, 0.7775744880F,
  154273. 0.7779496827F, 0.7783245610F, 0.7786991227F, 0.7790733676F,
  154274. 0.7794472953F, 0.7798209056F, 0.7801941982F, 0.7805671729F,
  154275. 0.7809398294F, 0.7813121675F, 0.7816841869F, 0.7820558873F,
  154276. 0.7824272684F, 0.7827983301F, 0.7831690720F, 0.7835394940F,
  154277. 0.7839095957F, 0.7842793768F, 0.7846488373F, 0.7850179767F,
  154278. 0.7853867948F, 0.7857552914F, 0.7861234663F, 0.7864913191F,
  154279. 0.7868588497F, 0.7872260578F, 0.7875929431F, 0.7879595055F,
  154280. 0.7883257445F, 0.7886916601F, 0.7890572520F, 0.7894225198F,
  154281. 0.7897874635F, 0.7901520827F, 0.7905163772F, 0.7908803468F,
  154282. 0.7912439912F, 0.7916073102F, 0.7919703035F, 0.7923329710F,
  154283. 0.7926953124F, 0.7930573274F, 0.7934190158F, 0.7937803774F,
  154284. 0.7941414120F, 0.7945021193F, 0.7948624991F, 0.7952225511F,
  154285. 0.7955822752F, 0.7959416711F, 0.7963007387F, 0.7966594775F,
  154286. 0.7970178875F, 0.7973759685F, 0.7977337201F, 0.7980911422F,
  154287. 0.7984482346F, 0.7988049970F, 0.7991614292F, 0.7995175310F,
  154288. 0.7998733022F, 0.8002287426F, 0.8005838519F, 0.8009386299F,
  154289. 0.8012930765F, 0.8016471914F, 0.8020009744F, 0.8023544253F,
  154290. 0.8027075438F, 0.8030603298F, 0.8034127831F, 0.8037649035F,
  154291. 0.8041166906F, 0.8044681445F, 0.8048192647F, 0.8051700512F,
  154292. 0.8055205038F, 0.8058706222F, 0.8062204062F, 0.8065698556F,
  154293. 0.8069189702F, 0.8072677499F, 0.8076161944F, 0.8079643036F,
  154294. 0.8083120772F, 0.8086595151F, 0.8090066170F, 0.8093533827F,
  154295. 0.8096998122F, 0.8100459051F, 0.8103916613F, 0.8107370806F,
  154296. 0.8110821628F, 0.8114269077F, 0.8117713151F, 0.8121153849F,
  154297. 0.8124591169F, 0.8128025108F, 0.8131455666F, 0.8134882839F,
  154298. 0.8138306627F, 0.8141727027F, 0.8145144038F, 0.8148557658F,
  154299. 0.8151967886F, 0.8155374718F, 0.8158778154F, 0.8162178192F,
  154300. 0.8165574830F, 0.8168968067F, 0.8172357900F, 0.8175744328F,
  154301. 0.8179127349F, 0.8182506962F, 0.8185883164F, 0.8189255955F,
  154302. 0.8192625332F, 0.8195991295F, 0.8199353840F, 0.8202712967F,
  154303. 0.8206068673F, 0.8209420958F, 0.8212769820F, 0.8216115256F,
  154304. 0.8219457266F, 0.8222795848F, 0.8226131000F, 0.8229462721F,
  154305. 0.8232791009F, 0.8236115863F, 0.8239437280F, 0.8242755260F,
  154306. 0.8246069801F, 0.8249380901F, 0.8252688559F, 0.8255992774F,
  154307. 0.8259293544F, 0.8262590867F, 0.8265884741F, 0.8269175167F,
  154308. 0.8272462141F, 0.8275745663F, 0.8279025732F, 0.8282302344F,
  154309. 0.8285575501F, 0.8288845199F, 0.8292111437F, 0.8295374215F,
  154310. 0.8298633530F, 0.8301889382F, 0.8305141768F, 0.8308390688F,
  154311. 0.8311636141F, 0.8314878124F, 0.8318116637F, 0.8321351678F,
  154312. 0.8324583246F, 0.8327811340F, 0.8331035957F, 0.8334257098F,
  154313. 0.8337474761F, 0.8340688944F, 0.8343899647F, 0.8347106867F,
  154314. 0.8350310605F, 0.8353510857F, 0.8356707624F, 0.8359900904F,
  154315. 0.8363090696F, 0.8366276999F, 0.8369459811F, 0.8372639131F,
  154316. 0.8375814958F, 0.8378987292F, 0.8382156130F, 0.8385321472F,
  154317. 0.8388483316F, 0.8391641662F, 0.8394796508F, 0.8397947853F,
  154318. 0.8401095697F, 0.8404240037F, 0.8407380873F, 0.8410518204F,
  154319. 0.8413652029F, 0.8416782347F, 0.8419909156F, 0.8423032456F,
  154320. 0.8426152245F, 0.8429268523F, 0.8432381289F, 0.8435490541F,
  154321. 0.8438596279F, 0.8441698502F, 0.8444797208F, 0.8447892396F,
  154322. 0.8450984067F, 0.8454072218F, 0.8457156849F, 0.8460237959F,
  154323. 0.8463315547F, 0.8466389612F, 0.8469460154F, 0.8472527170F,
  154324. 0.8475590661F, 0.8478650625F, 0.8481707063F, 0.8484759971F,
  154325. 0.8487809351F, 0.8490855201F, 0.8493897521F, 0.8496936308F,
  154326. 0.8499971564F, 0.8503003286F, 0.8506031474F, 0.8509056128F,
  154327. 0.8512077246F, 0.8515094828F, 0.8518108872F, 0.8521119379F,
  154328. 0.8524126348F, 0.8527129777F, 0.8530129666F, 0.8533126015F,
  154329. 0.8536118822F, 0.8539108087F, 0.8542093809F, 0.8545075988F,
  154330. 0.8548054623F, 0.8551029712F, 0.8554001257F, 0.8556969255F,
  154331. 0.8559933707F, 0.8562894611F, 0.8565851968F, 0.8568805775F,
  154332. 0.8571756034F, 0.8574702743F, 0.8577645902F, 0.8580585509F,
  154333. 0.8583521566F, 0.8586454070F, 0.8589383021F, 0.8592308420F,
  154334. 0.8595230265F, 0.8598148556F, 0.8601063292F, 0.8603974473F,
  154335. 0.8606882098F, 0.8609786167F, 0.8612686680F, 0.8615583636F,
  154336. 0.8618477034F, 0.8621366874F, 0.8624253156F, 0.8627135878F,
  154337. 0.8630015042F, 0.8632890646F, 0.8635762690F, 0.8638631173F,
  154338. 0.8641496096F, 0.8644357457F, 0.8647215257F, 0.8650069495F,
  154339. 0.8652920171F, 0.8655767283F, 0.8658610833F, 0.8661450820F,
  154340. 0.8664287243F, 0.8667120102F, 0.8669949397F, 0.8672775127F,
  154341. 0.8675597293F, 0.8678415894F, 0.8681230929F, 0.8684042398F,
  154342. 0.8686850302F, 0.8689654640F, 0.8692455412F, 0.8695252617F,
  154343. 0.8698046255F, 0.8700836327F, 0.8703622831F, 0.8706405768F,
  154344. 0.8709185138F, 0.8711960940F, 0.8714733174F, 0.8717501840F,
  154345. 0.8720266939F, 0.8723028469F, 0.8725786430F, 0.8728540824F,
  154346. 0.8731291648F, 0.8734038905F, 0.8736782592F, 0.8739522711F,
  154347. 0.8742259261F, 0.8744992242F, 0.8747721653F, 0.8750447496F,
  154348. 0.8753169770F, 0.8755888475F, 0.8758603611F, 0.8761315177F,
  154349. 0.8764023175F, 0.8766727603F, 0.8769428462F, 0.8772125752F,
  154350. 0.8774819474F, 0.8777509626F, 0.8780196209F, 0.8782879224F,
  154351. 0.8785558669F, 0.8788234546F, 0.8790906854F, 0.8793575594F,
  154352. 0.8796240765F, 0.8798902368F, 0.8801560403F, 0.8804214870F,
  154353. 0.8806865768F, 0.8809513099F, 0.8812156863F, 0.8814797059F,
  154354. 0.8817433687F, 0.8820066749F, 0.8822696243F, 0.8825322171F,
  154355. 0.8827944532F, 0.8830563327F, 0.8833178556F, 0.8835790219F,
  154356. 0.8838398316F, 0.8841002848F, 0.8843603815F, 0.8846201217F,
  154357. 0.8848795054F, 0.8851385327F, 0.8853972036F, 0.8856555182F,
  154358. 0.8859134764F, 0.8861710783F, 0.8864283239F, 0.8866852133F,
  154359. 0.8869417464F, 0.8871979234F, 0.8874537443F, 0.8877092090F,
  154360. 0.8879643177F, 0.8882190704F, 0.8884734671F, 0.8887275078F,
  154361. 0.8889811927F, 0.8892345216F, 0.8894874948F, 0.8897401122F,
  154362. 0.8899923738F, 0.8902442798F, 0.8904958301F, 0.8907470248F,
  154363. 0.8909978640F, 0.8912483477F, 0.8914984759F, 0.8917482487F,
  154364. 0.8919976662F, 0.8922467284F, 0.8924954353F, 0.8927437871F,
  154365. 0.8929917837F, 0.8932394252F, 0.8934867118F, 0.8937336433F,
  154366. 0.8939802199F, 0.8942264417F, 0.8944723087F, 0.8947178210F,
  154367. 0.8949629785F, 0.8952077815F, 0.8954522299F, 0.8956963239F,
  154368. 0.8959400634F, 0.8961834486F, 0.8964264795F, 0.8966691561F,
  154369. 0.8969114786F, 0.8971534470F, 0.8973950614F, 0.8976363219F,
  154370. 0.8978772284F, 0.8981177812F, 0.8983579802F, 0.8985978256F,
  154371. 0.8988373174F, 0.8990764556F, 0.8993152405F, 0.8995536720F,
  154372. 0.8997917502F, 0.9000294751F, 0.9002668470F, 0.9005038658F,
  154373. 0.9007405317F, 0.9009768446F, 0.9012128048F, 0.9014484123F,
  154374. 0.9016836671F, 0.9019185693F, 0.9021531191F, 0.9023873165F,
  154375. 0.9026211616F, 0.9028546546F, 0.9030877954F, 0.9033205841F,
  154376. 0.9035530210F, 0.9037851059F, 0.9040168392F, 0.9042482207F,
  154377. 0.9044792507F, 0.9047099293F, 0.9049402564F, 0.9051702323F,
  154378. 0.9053998569F, 0.9056291305F, 0.9058580531F, 0.9060866248F,
  154379. 0.9063148457F, 0.9065427159F, 0.9067702355F, 0.9069974046F,
  154380. 0.9072242233F, 0.9074506917F, 0.9076768100F, 0.9079025782F,
  154381. 0.9081279964F, 0.9083530647F, 0.9085777833F, 0.9088021523F,
  154382. 0.9090261717F, 0.9092498417F, 0.9094731623F, 0.9096961338F,
  154383. 0.9099187561F, 0.9101410295F, 0.9103629540F, 0.9105845297F,
  154384. 0.9108057568F, 0.9110266354F, 0.9112471656F, 0.9114673475F,
  154385. 0.9116871812F, 0.9119066668F, 0.9121258046F, 0.9123445945F,
  154386. 0.9125630367F, 0.9127811314F, 0.9129988786F, 0.9132162785F,
  154387. 0.9134333312F, 0.9136500368F, 0.9138663954F, 0.9140824073F,
  154388. 0.9142980724F, 0.9145133910F, 0.9147283632F, 0.9149429890F,
  154389. 0.9151572687F, 0.9153712023F, 0.9155847900F, 0.9157980319F,
  154390. 0.9160109282F, 0.9162234790F, 0.9164356844F, 0.9166475445F,
  154391. 0.9168590595F, 0.9170702296F, 0.9172810548F, 0.9174915354F,
  154392. 0.9177016714F, 0.9179114629F, 0.9181209102F, 0.9183300134F,
  154393. 0.9185387726F, 0.9187471879F, 0.9189552595F, 0.9191629876F,
  154394. 0.9193703723F, 0.9195774136F, 0.9197841119F, 0.9199904672F,
  154395. 0.9201964797F, 0.9204021495F, 0.9206074767F, 0.9208124616F,
  154396. 0.9210171043F, 0.9212214049F, 0.9214253636F, 0.9216289805F,
  154397. 0.9218322558F, 0.9220351896F, 0.9222377821F, 0.9224400335F,
  154398. 0.9226419439F, 0.9228435134F, 0.9230447423F, 0.9232456307F,
  154399. 0.9234461787F, 0.9236463865F, 0.9238462543F, 0.9240457822F,
  154400. 0.9242449704F, 0.9244438190F, 0.9246423282F, 0.9248404983F,
  154401. 0.9250383293F, 0.9252358214F, 0.9254329747F, 0.9256297896F,
  154402. 0.9258262660F, 0.9260224042F, 0.9262182044F, 0.9264136667F,
  154403. 0.9266087913F, 0.9268035783F, 0.9269980280F, 0.9271921405F,
  154404. 0.9273859160F, 0.9275793546F, 0.9277724566F, 0.9279652221F,
  154405. 0.9281576513F, 0.9283497443F, 0.9285415014F, 0.9287329227F,
  154406. 0.9289240084F, 0.9291147586F, 0.9293051737F, 0.9294952536F,
  154407. 0.9296849987F, 0.9298744091F, 0.9300634850F, 0.9302522266F,
  154408. 0.9304406340F, 0.9306287074F, 0.9308164471F, 0.9310038532F,
  154409. 0.9311909259F, 0.9313776654F, 0.9315640719F, 0.9317501455F,
  154410. 0.9319358865F, 0.9321212951F, 0.9323063713F, 0.9324911155F,
  154411. 0.9326755279F, 0.9328596085F, 0.9330433577F, 0.9332267756F,
  154412. 0.9334098623F, 0.9335926182F, 0.9337750434F, 0.9339571380F,
  154413. 0.9341389023F, 0.9343203366F, 0.9345014409F, 0.9346822155F,
  154414. 0.9348626606F, 0.9350427763F, 0.9352225630F, 0.9354020207F,
  154415. 0.9355811498F, 0.9357599503F, 0.9359384226F, 0.9361165667F,
  154416. 0.9362943830F, 0.9364718716F, 0.9366490327F, 0.9368258666F,
  154417. 0.9370023733F, 0.9371785533F, 0.9373544066F, 0.9375299335F,
  154418. 0.9377051341F, 0.9378800087F, 0.9380545576F, 0.9382287809F,
  154419. 0.9384026787F, 0.9385762515F, 0.9387494993F, 0.9389224223F,
  154420. 0.9390950209F, 0.9392672951F, 0.9394392453F, 0.9396108716F,
  154421. 0.9397821743F, 0.9399531536F, 0.9401238096F, 0.9402941427F,
  154422. 0.9404641530F, 0.9406338407F, 0.9408032061F, 0.9409722495F,
  154423. 0.9411409709F, 0.9413093707F, 0.9414774491F, 0.9416452062F,
  154424. 0.9418126424F, 0.9419797579F, 0.9421465528F, 0.9423130274F,
  154425. 0.9424791819F, 0.9426450166F, 0.9428105317F, 0.9429757274F,
  154426. 0.9431406039F, 0.9433051616F, 0.9434694005F, 0.9436333209F,
  154427. 0.9437969232F, 0.9439602074F, 0.9441231739F, 0.9442858229F,
  154428. 0.9444481545F, 0.9446101691F, 0.9447718669F, 0.9449332481F,
  154429. 0.9450943129F, 0.9452550617F, 0.9454154945F, 0.9455756118F,
  154430. 0.9457354136F, 0.9458949003F, 0.9460540721F, 0.9462129292F,
  154431. 0.9463714719F, 0.9465297003F, 0.9466876149F, 0.9468452157F,
  154432. 0.9470025031F, 0.9471594772F, 0.9473161384F, 0.9474724869F,
  154433. 0.9476285229F, 0.9477842466F, 0.9479396584F, 0.9480947585F,
  154434. 0.9482495470F, 0.9484040243F, 0.9485581906F, 0.9487120462F,
  154435. 0.9488655913F, 0.9490188262F, 0.9491717511F, 0.9493243662F,
  154436. 0.9494766718F, 0.9496286683F, 0.9497803557F, 0.9499317345F,
  154437. 0.9500828047F, 0.9502335668F, 0.9503840209F, 0.9505341673F,
  154438. 0.9506840062F, 0.9508335380F, 0.9509827629F, 0.9511316810F,
  154439. 0.9512802928F, 0.9514285984F, 0.9515765982F, 0.9517242923F,
  154440. 0.9518716810F, 0.9520187646F, 0.9521655434F, 0.9523120176F,
  154441. 0.9524581875F, 0.9526040534F, 0.9527496154F, 0.9528948739F,
  154442. 0.9530398292F, 0.9531844814F, 0.9533288310F, 0.9534728780F,
  154443. 0.9536166229F, 0.9537600659F, 0.9539032071F, 0.9540460470F,
  154444. 0.9541885858F, 0.9543308237F, 0.9544727611F, 0.9546143981F,
  154445. 0.9547557351F, 0.9548967723F, 0.9550375100F, 0.9551779485F,
  154446. 0.9553180881F, 0.9554579290F, 0.9555974714F, 0.9557367158F,
  154447. 0.9558756623F, 0.9560143112F, 0.9561526628F, 0.9562907174F,
  154448. 0.9564284752F, 0.9565659366F, 0.9567031017F, 0.9568399710F,
  154449. 0.9569765446F, 0.9571128229F, 0.9572488061F, 0.9573844944F,
  154450. 0.9575198883F, 0.9576549879F, 0.9577897936F, 0.9579243056F,
  154451. 0.9580585242F, 0.9581924497F, 0.9583260824F, 0.9584594226F,
  154452. 0.9585924705F, 0.9587252264F, 0.9588576906F, 0.9589898634F,
  154453. 0.9591217452F, 0.9592533360F, 0.9593846364F, 0.9595156465F,
  154454. 0.9596463666F, 0.9597767971F, 0.9599069382F, 0.9600367901F,
  154455. 0.9601663533F, 0.9602956279F, 0.9604246143F, 0.9605533128F,
  154456. 0.9606817236F, 0.9608098471F, 0.9609376835F, 0.9610652332F,
  154457. 0.9611924963F, 0.9613194733F, 0.9614461644F, 0.9615725699F,
  154458. 0.9616986901F, 0.9618245253F, 0.9619500757F, 0.9620753418F,
  154459. 0.9622003238F, 0.9623250219F, 0.9624494365F, 0.9625735679F,
  154460. 0.9626974163F, 0.9628209821F, 0.9629442656F, 0.9630672671F,
  154461. 0.9631899868F, 0.9633124251F, 0.9634345822F, 0.9635564585F,
  154462. 0.9636780543F, 0.9637993699F, 0.9639204056F, 0.9640411616F,
  154463. 0.9641616383F, 0.9642818359F, 0.9644017549F, 0.9645213955F,
  154464. 0.9646407579F, 0.9647598426F, 0.9648786497F, 0.9649971797F,
  154465. 0.9651154328F, 0.9652334092F, 0.9653511095F, 0.9654685337F,
  154466. 0.9655856823F, 0.9657025556F, 0.9658191538F, 0.9659354773F,
  154467. 0.9660515263F, 0.9661673013F, 0.9662828024F, 0.9663980300F,
  154468. 0.9665129845F, 0.9666276660F, 0.9667420750F, 0.9668562118F,
  154469. 0.9669700766F, 0.9670836698F, 0.9671969917F, 0.9673100425F,
  154470. 0.9674228227F, 0.9675353325F, 0.9676475722F, 0.9677595422F,
  154471. 0.9678712428F, 0.9679826742F, 0.9680938368F, 0.9682047309F,
  154472. 0.9683153569F, 0.9684257150F, 0.9685358056F, 0.9686456289F,
  154473. 0.9687551853F, 0.9688644752F, 0.9689734987F, 0.9690822564F,
  154474. 0.9691907483F, 0.9692989750F, 0.9694069367F, 0.9695146337F,
  154475. 0.9696220663F, 0.9697292349F, 0.9698361398F, 0.9699427813F,
  154476. 0.9700491597F, 0.9701552754F, 0.9702611286F, 0.9703667197F,
  154477. 0.9704720490F, 0.9705771169F, 0.9706819236F, 0.9707864695F,
  154478. 0.9708907549F, 0.9709947802F, 0.9710985456F, 0.9712020514F,
  154479. 0.9713052981F, 0.9714082859F, 0.9715110151F, 0.9716134862F,
  154480. 0.9717156993F, 0.9718176549F, 0.9719193532F, 0.9720207946F,
  154481. 0.9721219794F, 0.9722229080F, 0.9723235806F, 0.9724239976F,
  154482. 0.9725241593F, 0.9726240661F, 0.9727237183F, 0.9728231161F,
  154483. 0.9729222601F, 0.9730211503F, 0.9731197873F, 0.9732181713F,
  154484. 0.9733163027F, 0.9734141817F, 0.9735118088F, 0.9736091842F,
  154485. 0.9737063083F, 0.9738031814F, 0.9738998039F, 0.9739961760F,
  154486. 0.9740922981F, 0.9741881706F, 0.9742837938F, 0.9743791680F,
  154487. 0.9744742935F, 0.9745691707F, 0.9746637999F, 0.9747581814F,
  154488. 0.9748523157F, 0.9749462029F, 0.9750398435F, 0.9751332378F,
  154489. 0.9752263861F, 0.9753192887F, 0.9754119461F, 0.9755043585F,
  154490. 0.9755965262F, 0.9756884496F, 0.9757801291F, 0.9758715650F,
  154491. 0.9759627575F, 0.9760537071F, 0.9761444141F, 0.9762348789F,
  154492. 0.9763251016F, 0.9764150828F, 0.9765048228F, 0.9765943218F,
  154493. 0.9766835802F, 0.9767725984F, 0.9768613767F, 0.9769499154F,
  154494. 0.9770382149F, 0.9771262755F, 0.9772140976F, 0.9773016815F,
  154495. 0.9773890275F, 0.9774761360F, 0.9775630073F, 0.9776496418F,
  154496. 0.9777360398F, 0.9778222016F, 0.9779081277F, 0.9779938182F,
  154497. 0.9780792736F, 0.9781644943F, 0.9782494805F, 0.9783342326F,
  154498. 0.9784187509F, 0.9785030359F, 0.9785870877F, 0.9786709069F,
  154499. 0.9787544936F, 0.9788378484F, 0.9789209714F, 0.9790038631F,
  154500. 0.9790865238F, 0.9791689538F, 0.9792511535F, 0.9793331232F,
  154501. 0.9794148633F, 0.9794963742F, 0.9795776561F, 0.9796587094F,
  154502. 0.9797395345F, 0.9798201316F, 0.9799005013F, 0.9799806437F,
  154503. 0.9800605593F, 0.9801402483F, 0.9802197112F, 0.9802989483F,
  154504. 0.9803779600F, 0.9804567465F, 0.9805353082F, 0.9806136455F,
  154505. 0.9806917587F, 0.9807696482F, 0.9808473143F, 0.9809247574F,
  154506. 0.9810019778F, 0.9810789759F, 0.9811557519F, 0.9812323064F,
  154507. 0.9813086395F, 0.9813847517F, 0.9814606433F, 0.9815363147F,
  154508. 0.9816117662F, 0.9816869981F, 0.9817620108F, 0.9818368047F,
  154509. 0.9819113801F, 0.9819857374F, 0.9820598769F, 0.9821337989F,
  154510. 0.9822075038F, 0.9822809920F, 0.9823542638F, 0.9824273195F,
  154511. 0.9825001596F, 0.9825727843F, 0.9826451940F, 0.9827173891F,
  154512. 0.9827893700F, 0.9828611368F, 0.9829326901F, 0.9830040302F,
  154513. 0.9830751574F, 0.9831460720F, 0.9832167745F, 0.9832872652F,
  154514. 0.9833575444F, 0.9834276124F, 0.9834974697F, 0.9835671166F,
  154515. 0.9836365535F, 0.9837057806F, 0.9837747983F, 0.9838436071F,
  154516. 0.9839122072F, 0.9839805990F, 0.9840487829F, 0.9841167591F,
  154517. 0.9841845282F, 0.9842520903F, 0.9843194459F, 0.9843865953F,
  154518. 0.9844535389F, 0.9845202771F, 0.9845868101F, 0.9846531383F,
  154519. 0.9847192622F, 0.9847851820F, 0.9848508980F, 0.9849164108F,
  154520. 0.9849817205F, 0.9850468276F, 0.9851117324F, 0.9851764352F,
  154521. 0.9852409365F, 0.9853052366F, 0.9853693358F, 0.9854332344F,
  154522. 0.9854969330F, 0.9855604317F, 0.9856237309F, 0.9856868310F,
  154523. 0.9857497325F, 0.9858124355F, 0.9858749404F, 0.9859372477F,
  154524. 0.9859993577F, 0.9860612707F, 0.9861229871F, 0.9861845072F,
  154525. 0.9862458315F, 0.9863069601F, 0.9863678936F, 0.9864286322F,
  154526. 0.9864891764F, 0.9865495264F, 0.9866096826F, 0.9866696454F,
  154527. 0.9867294152F, 0.9867889922F, 0.9868483769F, 0.9869075695F,
  154528. 0.9869665706F, 0.9870253803F, 0.9870839991F, 0.9871424273F,
  154529. 0.9872006653F, 0.9872587135F, 0.9873165721F, 0.9873742415F,
  154530. 0.9874317222F, 0.9874890144F, 0.9875461185F, 0.9876030348F,
  154531. 0.9876597638F, 0.9877163057F, 0.9877726610F, 0.9878288300F,
  154532. 0.9878848130F, 0.9879406104F, 0.9879962225F, 0.9880516497F,
  154533. 0.9881068924F, 0.9881619509F, 0.9882168256F, 0.9882715168F,
  154534. 0.9883260249F, 0.9883803502F, 0.9884344931F, 0.9884884539F,
  154535. 0.9885422331F, 0.9885958309F, 0.9886492477F, 0.9887024838F,
  154536. 0.9887555397F, 0.9888084157F, 0.9888611120F, 0.9889136292F,
  154537. 0.9889659675F, 0.9890181273F, 0.9890701089F, 0.9891219128F,
  154538. 0.9891735392F, 0.9892249885F, 0.9892762610F, 0.9893273572F,
  154539. 0.9893782774F, 0.9894290219F, 0.9894795911F, 0.9895299853F,
  154540. 0.9895802049F, 0.9896302502F, 0.9896801217F, 0.9897298196F,
  154541. 0.9897793443F, 0.9898286961F, 0.9898778755F, 0.9899268828F,
  154542. 0.9899757183F, 0.9900243823F, 0.9900728753F, 0.9901211976F,
  154543. 0.9901693495F, 0.9902173314F, 0.9902651436F, 0.9903127865F,
  154544. 0.9903602605F, 0.9904075659F, 0.9904547031F, 0.9905016723F,
  154545. 0.9905484740F, 0.9905951086F, 0.9906415763F, 0.9906878775F,
  154546. 0.9907340126F, 0.9907799819F, 0.9908257858F, 0.9908714247F,
  154547. 0.9909168988F, 0.9909622086F, 0.9910073543F, 0.9910523364F,
  154548. 0.9910971552F, 0.9911418110F, 0.9911863042F, 0.9912306351F,
  154549. 0.9912748042F, 0.9913188117F, 0.9913626580F, 0.9914063435F,
  154550. 0.9914498684F, 0.9914932333F, 0.9915364383F, 0.9915794839F,
  154551. 0.9916223703F, 0.9916650981F, 0.9917076674F, 0.9917500787F,
  154552. 0.9917923323F, 0.9918344286F, 0.9918763679F, 0.9919181505F,
  154553. 0.9919597769F, 0.9920012473F, 0.9920425621F, 0.9920837217F,
  154554. 0.9921247263F, 0.9921655765F, 0.9922062724F, 0.9922468145F,
  154555. 0.9922872030F, 0.9923274385F, 0.9923675211F, 0.9924074513F,
  154556. 0.9924472294F, 0.9924868557F, 0.9925263306F, 0.9925656544F,
  154557. 0.9926048275F, 0.9926438503F, 0.9926827230F, 0.9927214461F,
  154558. 0.9927600199F, 0.9927984446F, 0.9928367208F, 0.9928748486F,
  154559. 0.9929128285F, 0.9929506608F, 0.9929883459F, 0.9930258841F,
  154560. 0.9930632757F, 0.9931005211F, 0.9931376207F, 0.9931745747F,
  154561. 0.9932113836F, 0.9932480476F, 0.9932845671F, 0.9933209425F,
  154562. 0.9933571742F, 0.9933932623F, 0.9934292074F, 0.9934650097F,
  154563. 0.9935006696F, 0.9935361874F, 0.9935715635F, 0.9936067982F,
  154564. 0.9936418919F, 0.9936768448F, 0.9937116574F, 0.9937463300F,
  154565. 0.9937808629F, 0.9938152565F, 0.9938495111F, 0.9938836271F,
  154566. 0.9939176047F, 0.9939514444F, 0.9939851465F, 0.9940187112F,
  154567. 0.9940521391F, 0.9940854303F, 0.9941185853F, 0.9941516044F,
  154568. 0.9941844879F, 0.9942172361F, 0.9942498495F, 0.9942823283F,
  154569. 0.9943146729F, 0.9943468836F, 0.9943789608F, 0.9944109047F,
  154570. 0.9944427158F, 0.9944743944F, 0.9945059408F, 0.9945373553F,
  154571. 0.9945686384F, 0.9945997902F, 0.9946308112F, 0.9946617017F,
  154572. 0.9946924621F, 0.9947230926F, 0.9947535937F, 0.9947839656F,
  154573. 0.9948142086F, 0.9948443232F, 0.9948743097F, 0.9949041683F,
  154574. 0.9949338995F, 0.9949635035F, 0.9949929807F, 0.9950223315F,
  154575. 0.9950515561F, 0.9950806549F, 0.9951096282F, 0.9951384764F,
  154576. 0.9951671998F, 0.9951957987F, 0.9952242735F, 0.9952526245F,
  154577. 0.9952808520F, 0.9953089564F, 0.9953369380F, 0.9953647971F,
  154578. 0.9953925340F, 0.9954201491F, 0.9954476428F, 0.9954750153F,
  154579. 0.9955022670F, 0.9955293981F, 0.9955564092F, 0.9955833003F,
  154580. 0.9956100720F, 0.9956367245F, 0.9956632582F, 0.9956896733F,
  154581. 0.9957159703F, 0.9957421494F, 0.9957682110F, 0.9957941553F,
  154582. 0.9958199828F, 0.9958456937F, 0.9958712884F, 0.9958967672F,
  154583. 0.9959221305F, 0.9959473784F, 0.9959725115F, 0.9959975300F,
  154584. 0.9960224342F, 0.9960472244F, 0.9960719011F, 0.9960964644F,
  154585. 0.9961209148F, 0.9961452525F, 0.9961694779F, 0.9961935913F,
  154586. 0.9962175930F, 0.9962414834F, 0.9962652627F, 0.9962889313F,
  154587. 0.9963124895F, 0.9963359377F, 0.9963592761F, 0.9963825051F,
  154588. 0.9964056250F, 0.9964286361F, 0.9964515387F, 0.9964743332F,
  154589. 0.9964970198F, 0.9965195990F, 0.9965420709F, 0.9965644360F,
  154590. 0.9965866946F, 0.9966088469F, 0.9966308932F, 0.9966528340F,
  154591. 0.9966746695F, 0.9966964001F, 0.9967180260F, 0.9967395475F,
  154592. 0.9967609651F, 0.9967822789F, 0.9968034894F, 0.9968245968F,
  154593. 0.9968456014F, 0.9968665036F, 0.9968873037F, 0.9969080019F,
  154594. 0.9969285987F, 0.9969490942F, 0.9969694889F, 0.9969897830F,
  154595. 0.9970099769F, 0.9970300708F, 0.9970500651F, 0.9970699601F,
  154596. 0.9970897561F, 0.9971094533F, 0.9971290522F, 0.9971485531F,
  154597. 0.9971679561F, 0.9971872617F, 0.9972064702F, 0.9972255818F,
  154598. 0.9972445968F, 0.9972635157F, 0.9972823386F, 0.9973010659F,
  154599. 0.9973196980F, 0.9973382350F, 0.9973566773F, 0.9973750253F,
  154600. 0.9973932791F, 0.9974114392F, 0.9974295059F, 0.9974474793F,
  154601. 0.9974653599F, 0.9974831480F, 0.9975008438F, 0.9975184476F,
  154602. 0.9975359598F, 0.9975533806F, 0.9975707104F, 0.9975879495F,
  154603. 0.9976050981F, 0.9976221566F, 0.9976391252F, 0.9976560043F,
  154604. 0.9976727941F, 0.9976894950F, 0.9977061073F, 0.9977226312F,
  154605. 0.9977390671F, 0.9977554152F, 0.9977716759F, 0.9977878495F,
  154606. 0.9978039361F, 0.9978199363F, 0.9978358501F, 0.9978516780F,
  154607. 0.9978674202F, 0.9978830771F, 0.9978986488F, 0.9979141358F,
  154608. 0.9979295383F, 0.9979448566F, 0.9979600909F, 0.9979752417F,
  154609. 0.9979903091F, 0.9980052936F, 0.9980201952F, 0.9980350145F,
  154610. 0.9980497515F, 0.9980644067F, 0.9980789804F, 0.9980934727F,
  154611. 0.9981078841F, 0.9981222147F, 0.9981364649F, 0.9981506350F,
  154612. 0.9981647253F, 0.9981787360F, 0.9981926674F, 0.9982065199F,
  154613. 0.9982202936F, 0.9982339890F, 0.9982476062F, 0.9982611456F,
  154614. 0.9982746074F, 0.9982879920F, 0.9983012996F, 0.9983145304F,
  154615. 0.9983276849F, 0.9983407632F, 0.9983537657F, 0.9983666926F,
  154616. 0.9983795442F, 0.9983923208F, 0.9984050226F, 0.9984176501F,
  154617. 0.9984302033F, 0.9984426827F, 0.9984550884F, 0.9984674208F,
  154618. 0.9984796802F, 0.9984918667F, 0.9985039808F, 0.9985160227F,
  154619. 0.9985279926F, 0.9985398909F, 0.9985517177F, 0.9985634734F,
  154620. 0.9985751583F, 0.9985867727F, 0.9985983167F, 0.9986097907F,
  154621. 0.9986211949F, 0.9986325297F, 0.9986437953F, 0.9986549919F,
  154622. 0.9986661199F, 0.9986771795F, 0.9986881710F, 0.9986990946F,
  154623. 0.9987099507F, 0.9987207394F, 0.9987314611F, 0.9987421161F,
  154624. 0.9987527045F, 0.9987632267F, 0.9987736829F, 0.9987840734F,
  154625. 0.9987943985F, 0.9988046584F, 0.9988148534F, 0.9988249838F,
  154626. 0.9988350498F, 0.9988450516F, 0.9988549897F, 0.9988648641F,
  154627. 0.9988746753F, 0.9988844233F, 0.9988941086F, 0.9989037313F,
  154628. 0.9989132918F, 0.9989227902F, 0.9989322269F, 0.9989416021F,
  154629. 0.9989509160F, 0.9989601690F, 0.9989693613F, 0.9989784931F,
  154630. 0.9989875647F, 0.9989965763F, 0.9990055283F, 0.9990144208F,
  154631. 0.9990232541F, 0.9990320286F, 0.9990407443F, 0.9990494016F,
  154632. 0.9990580008F, 0.9990665421F, 0.9990750257F, 0.9990834519F,
  154633. 0.9990918209F, 0.9991001331F, 0.9991083886F, 0.9991165877F,
  154634. 0.9991247307F, 0.9991328177F, 0.9991408491F, 0.9991488251F,
  154635. 0.9991567460F, 0.9991646119F, 0.9991724232F, 0.9991801801F,
  154636. 0.9991878828F, 0.9991955316F, 0.9992031267F, 0.9992106684F,
  154637. 0.9992181569F, 0.9992255925F, 0.9992329753F, 0.9992403057F,
  154638. 0.9992475839F, 0.9992548101F, 0.9992619846F, 0.9992691076F,
  154639. 0.9992761793F, 0.9992832001F, 0.9992901701F, 0.9992970895F,
  154640. 0.9993039587F, 0.9993107777F, 0.9993175470F, 0.9993242667F,
  154641. 0.9993309371F, 0.9993375583F, 0.9993441307F, 0.9993506545F,
  154642. 0.9993571298F, 0.9993635570F, 0.9993699362F, 0.9993762678F,
  154643. 0.9993825519F, 0.9993887887F, 0.9993949785F, 0.9994011216F,
  154644. 0.9994072181F, 0.9994132683F, 0.9994192725F, 0.9994252307F,
  154645. 0.9994311434F, 0.9994370107F, 0.9994428327F, 0.9994486099F,
  154646. 0.9994543423F, 0.9994600303F, 0.9994656739F, 0.9994712736F,
  154647. 0.9994768294F, 0.9994823417F, 0.9994878105F, 0.9994932363F,
  154648. 0.9994986191F, 0.9995039592F, 0.9995092568F, 0.9995145122F,
  154649. 0.9995197256F, 0.9995248971F, 0.9995300270F, 0.9995351156F,
  154650. 0.9995401630F, 0.9995451695F, 0.9995501352F, 0.9995550604F,
  154651. 0.9995599454F, 0.9995647903F, 0.9995695953F, 0.9995743607F,
  154652. 0.9995790866F, 0.9995837734F, 0.9995884211F, 0.9995930300F,
  154653. 0.9995976004F, 0.9996021324F, 0.9996066263F, 0.9996110822F,
  154654. 0.9996155004F, 0.9996198810F, 0.9996242244F, 0.9996285306F,
  154655. 0.9996327999F, 0.9996370326F, 0.9996412287F, 0.9996453886F,
  154656. 0.9996495125F, 0.9996536004F, 0.9996576527F, 0.9996616696F,
  154657. 0.9996656512F, 0.9996695977F, 0.9996735094F, 0.9996773865F,
  154658. 0.9996812291F, 0.9996850374F, 0.9996888118F, 0.9996925523F,
  154659. 0.9996962591F, 0.9996999325F, 0.9997035727F, 0.9997071798F,
  154660. 0.9997107541F, 0.9997142957F, 0.9997178049F, 0.9997212818F,
  154661. 0.9997247266F, 0.9997281396F, 0.9997315209F, 0.9997348708F,
  154662. 0.9997381893F, 0.9997414767F, 0.9997447333F, 0.9997479591F,
  154663. 0.9997511544F, 0.9997543194F, 0.9997574542F, 0.9997605591F,
  154664. 0.9997636342F, 0.9997666797F, 0.9997696958F, 0.9997726828F,
  154665. 0.9997756407F, 0.9997785698F, 0.9997814703F, 0.9997843423F,
  154666. 0.9997871860F, 0.9997900016F, 0.9997927894F, 0.9997955494F,
  154667. 0.9997982818F, 0.9998009869F, 0.9998036648F, 0.9998063157F,
  154668. 0.9998089398F, 0.9998115373F, 0.9998141082F, 0.9998166529F,
  154669. 0.9998191715F, 0.9998216642F, 0.9998241311F, 0.9998265724F,
  154670. 0.9998289884F, 0.9998313790F, 0.9998337447F, 0.9998360854F,
  154671. 0.9998384015F, 0.9998406930F, 0.9998429602F, 0.9998452031F,
  154672. 0.9998474221F, 0.9998496171F, 0.9998517885F, 0.9998539364F,
  154673. 0.9998560610F, 0.9998581624F, 0.9998602407F, 0.9998622962F,
  154674. 0.9998643291F, 0.9998663394F, 0.9998683274F, 0.9998702932F,
  154675. 0.9998722370F, 0.9998741589F, 0.9998760591F, 0.9998779378F,
  154676. 0.9998797952F, 0.9998816313F, 0.9998834464F, 0.9998852406F,
  154677. 0.9998870141F, 0.9998887670F, 0.9998904995F, 0.9998922117F,
  154678. 0.9998939039F, 0.9998955761F, 0.9998972285F, 0.9998988613F,
  154679. 0.9999004746F, 0.9999020686F, 0.9999036434F, 0.9999051992F,
  154680. 0.9999067362F, 0.9999082544F, 0.9999097541F, 0.9999112354F,
  154681. 0.9999126984F, 0.9999141433F, 0.9999155703F, 0.9999169794F,
  154682. 0.9999183709F, 0.9999197449F, 0.9999211014F, 0.9999224408F,
  154683. 0.9999237631F, 0.9999250684F, 0.9999263570F, 0.9999276289F,
  154684. 0.9999288843F, 0.9999301233F, 0.9999313461F, 0.9999325529F,
  154685. 0.9999337437F, 0.9999349187F, 0.9999360780F, 0.9999372218F,
  154686. 0.9999383503F, 0.9999394635F, 0.9999405616F, 0.9999416447F,
  154687. 0.9999427129F, 0.9999437665F, 0.9999448055F, 0.9999458301F,
  154688. 0.9999468404F, 0.9999478365F, 0.9999488185F, 0.9999497867F,
  154689. 0.9999507411F, 0.9999516819F, 0.9999526091F, 0.9999535230F,
  154690. 0.9999544236F, 0.9999553111F, 0.9999561856F, 0.9999570472F,
  154691. 0.9999578960F, 0.9999587323F, 0.9999595560F, 0.9999603674F,
  154692. 0.9999611666F, 0.9999619536F, 0.9999627286F, 0.9999634917F,
  154693. 0.9999642431F, 0.9999649828F, 0.9999657110F, 0.9999664278F,
  154694. 0.9999671334F, 0.9999678278F, 0.9999685111F, 0.9999691835F,
  154695. 0.9999698451F, 0.9999704960F, 0.9999711364F, 0.9999717662F,
  154696. 0.9999723858F, 0.9999729950F, 0.9999735942F, 0.9999741834F,
  154697. 0.9999747626F, 0.9999753321F, 0.9999758919F, 0.9999764421F,
  154698. 0.9999769828F, 0.9999775143F, 0.9999780364F, 0.9999785495F,
  154699. 0.9999790535F, 0.9999795485F, 0.9999800348F, 0.9999805124F,
  154700. 0.9999809813F, 0.9999814417F, 0.9999818938F, 0.9999823375F,
  154701. 0.9999827731F, 0.9999832005F, 0.9999836200F, 0.9999840316F,
  154702. 0.9999844353F, 0.9999848314F, 0.9999852199F, 0.9999856008F,
  154703. 0.9999859744F, 0.9999863407F, 0.9999866997F, 0.9999870516F,
  154704. 0.9999873965F, 0.9999877345F, 0.9999880656F, 0.9999883900F,
  154705. 0.9999887078F, 0.9999890190F, 0.9999893237F, 0.9999896220F,
  154706. 0.9999899140F, 0.9999901999F, 0.9999904796F, 0.9999907533F,
  154707. 0.9999910211F, 0.9999912830F, 0.9999915391F, 0.9999917896F,
  154708. 0.9999920345F, 0.9999922738F, 0.9999925077F, 0.9999927363F,
  154709. 0.9999929596F, 0.9999931777F, 0.9999933907F, 0.9999935987F,
  154710. 0.9999938018F, 0.9999940000F, 0.9999941934F, 0.9999943820F,
  154711. 0.9999945661F, 0.9999947456F, 0.9999949206F, 0.9999950912F,
  154712. 0.9999952575F, 0.9999954195F, 0.9999955773F, 0.9999957311F,
  154713. 0.9999958807F, 0.9999960265F, 0.9999961683F, 0.9999963063F,
  154714. 0.9999964405F, 0.9999965710F, 0.9999966979F, 0.9999968213F,
  154715. 0.9999969412F, 0.9999970576F, 0.9999971707F, 0.9999972805F,
  154716. 0.9999973871F, 0.9999974905F, 0.9999975909F, 0.9999976881F,
  154717. 0.9999977824F, 0.9999978738F, 0.9999979624F, 0.9999980481F,
  154718. 0.9999981311F, 0.9999982115F, 0.9999982892F, 0.9999983644F,
  154719. 0.9999984370F, 0.9999985072F, 0.9999985750F, 0.9999986405F,
  154720. 0.9999987037F, 0.9999987647F, 0.9999988235F, 0.9999988802F,
  154721. 0.9999989348F, 0.9999989873F, 0.9999990379F, 0.9999990866F,
  154722. 0.9999991334F, 0.9999991784F, 0.9999992217F, 0.9999992632F,
  154723. 0.9999993030F, 0.9999993411F, 0.9999993777F, 0.9999994128F,
  154724. 0.9999994463F, 0.9999994784F, 0.9999995091F, 0.9999995384F,
  154725. 0.9999995663F, 0.9999995930F, 0.9999996184F, 0.9999996426F,
  154726. 0.9999996657F, 0.9999996876F, 0.9999997084F, 0.9999997282F,
  154727. 0.9999997469F, 0.9999997647F, 0.9999997815F, 0.9999997973F,
  154728. 0.9999998123F, 0.9999998265F, 0.9999998398F, 0.9999998524F,
  154729. 0.9999998642F, 0.9999998753F, 0.9999998857F, 0.9999998954F,
  154730. 0.9999999045F, 0.9999999130F, 0.9999999209F, 0.9999999282F,
  154731. 0.9999999351F, 0.9999999414F, 0.9999999472F, 0.9999999526F,
  154732. 0.9999999576F, 0.9999999622F, 0.9999999664F, 0.9999999702F,
  154733. 0.9999999737F, 0.9999999769F, 0.9999999798F, 0.9999999824F,
  154734. 0.9999999847F, 0.9999999868F, 0.9999999887F, 0.9999999904F,
  154735. 0.9999999919F, 0.9999999932F, 0.9999999943F, 0.9999999953F,
  154736. 0.9999999961F, 0.9999999969F, 0.9999999975F, 0.9999999980F,
  154737. 0.9999999985F, 0.9999999988F, 0.9999999991F, 0.9999999993F,
  154738. 0.9999999995F, 0.9999999997F, 0.9999999998F, 0.9999999999F,
  154739. 0.9999999999F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  154740. 1.0000000000F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  154741. };
  154742. static float *vwin[8] = {
  154743. vwin64,
  154744. vwin128,
  154745. vwin256,
  154746. vwin512,
  154747. vwin1024,
  154748. vwin2048,
  154749. vwin4096,
  154750. vwin8192,
  154751. };
  154752. float *_vorbis_window_get(int n){
  154753. return vwin[n];
  154754. }
  154755. void _vorbis_apply_window(float *d,int *winno,long *blocksizes,
  154756. int lW,int W,int nW){
  154757. lW=(W?lW:0);
  154758. nW=(W?nW:0);
  154759. {
  154760. float *windowLW=vwin[winno[lW]];
  154761. float *windowNW=vwin[winno[nW]];
  154762. long n=blocksizes[W];
  154763. long ln=blocksizes[lW];
  154764. long rn=blocksizes[nW];
  154765. long leftbegin=n/4-ln/4;
  154766. long leftend=leftbegin+ln/2;
  154767. long rightbegin=n/2+n/4-rn/4;
  154768. long rightend=rightbegin+rn/2;
  154769. int i,p;
  154770. for(i=0;i<leftbegin;i++)
  154771. d[i]=0.f;
  154772. for(p=0;i<leftend;i++,p++)
  154773. d[i]*=windowLW[p];
  154774. for(i=rightbegin,p=rn/2-1;i<rightend;i++,p--)
  154775. d[i]*=windowNW[p];
  154776. for(;i<n;i++)
  154777. d[i]=0.f;
  154778. }
  154779. }
  154780. #endif
  154781. /********* End of inlined file: window.c *********/
  154782. #else
  154783. #include <vorbis/vorbisenc.h>
  154784. #include <vorbis/codec.h>
  154785. #include <vorbis/vorbisfile.h>
  154786. #endif
  154787. }
  154788. BEGIN_JUCE_NAMESPACE
  154789. using namespace OggVorbisNamespace;
  154790. #define oggFormatName TRANS("Ogg-Vorbis file")
  154791. static const tchar* const oggExtensions[] = { T(".ogg"), 0 };
  154792. class OggReader : public AudioFormatReader
  154793. {
  154794. OggVorbis_File ovFile;
  154795. ov_callbacks callbacks;
  154796. AudioSampleBuffer reservoir;
  154797. int reservoirStart, samplesInReservoir;
  154798. public:
  154799. OggReader (InputStream* const inp)
  154800. : AudioFormatReader (inp, oggFormatName),
  154801. reservoir (2, 4096),
  154802. reservoirStart (0),
  154803. samplesInReservoir (0)
  154804. {
  154805. sampleRate = 0;
  154806. usesFloatingPointData = true;
  154807. callbacks.read_func = &oggReadCallback;
  154808. callbacks.seek_func = &oggSeekCallback;
  154809. callbacks.close_func = &oggCloseCallback;
  154810. callbacks.tell_func = &oggTellCallback;
  154811. const int err = ov_open_callbacks (input, &ovFile, 0, 0, callbacks);
  154812. if (err == 0)
  154813. {
  154814. vorbis_info* info = ov_info (&ovFile, -1);
  154815. lengthInSamples = (uint32) ov_pcm_total (&ovFile, -1);
  154816. numChannels = info->channels;
  154817. bitsPerSample = 16;
  154818. sampleRate = info->rate;
  154819. reservoir.setSize (numChannels,
  154820. (int) jmin (lengthInSamples, (int64) reservoir.getNumSamples()));
  154821. }
  154822. }
  154823. ~OggReader()
  154824. {
  154825. ov_clear (&ovFile);
  154826. }
  154827. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  154828. int64 startSampleInFile, int numSamples)
  154829. {
  154830. while (numSamples > 0)
  154831. {
  154832. const int numAvailable = reservoirStart + samplesInReservoir - startSampleInFile;
  154833. if (startSampleInFile >= reservoirStart && numAvailable > 0)
  154834. {
  154835. // got a few samples overlapping, so use them before seeking..
  154836. const int numToUse = jmin (numSamples, numAvailable);
  154837. for (int i = jmin (numDestChannels, reservoir.getNumChannels()); --i >= 0;)
  154838. if (destSamples[i] != 0)
  154839. memcpy (destSamples[i] + startOffsetInDestBuffer,
  154840. reservoir.getSampleData (i, (int) (startSampleInFile - reservoirStart)),
  154841. sizeof (float) * numToUse);
  154842. startSampleInFile += numToUse;
  154843. numSamples -= numToUse;
  154844. startOffsetInDestBuffer += numToUse;
  154845. if (numSamples == 0)
  154846. break;
  154847. }
  154848. if (startSampleInFile < reservoirStart
  154849. || startSampleInFile + numSamples > reservoirStart + samplesInReservoir)
  154850. {
  154851. // buffer miss, so refill the reservoir
  154852. int bitStream = 0;
  154853. reservoirStart = jmax (0, (int) startSampleInFile);
  154854. samplesInReservoir = reservoir.getNumSamples();
  154855. if (reservoirStart != (int) ov_pcm_tell (&ovFile))
  154856. ov_pcm_seek (&ovFile, reservoirStart);
  154857. int offset = 0;
  154858. int numToRead = samplesInReservoir;
  154859. while (numToRead > 0)
  154860. {
  154861. float** dataIn = 0;
  154862. const int samps = ov_read_float (&ovFile, &dataIn, numToRead, &bitStream);
  154863. if (samps == 0)
  154864. break;
  154865. jassert (samps <= numToRead);
  154866. for (int i = jmin (numChannels, reservoir.getNumChannels()); --i >= 0;)
  154867. {
  154868. memcpy (reservoir.getSampleData (i, offset),
  154869. dataIn[i],
  154870. sizeof (float) * samps);
  154871. }
  154872. numToRead -= samps;
  154873. offset += samps;
  154874. }
  154875. if (numToRead > 0)
  154876. reservoir.clear (offset, numToRead);
  154877. }
  154878. }
  154879. if (numSamples > 0)
  154880. {
  154881. for (int i = numDestChannels; --i >= 0;)
  154882. if (destSamples[i] != 0)
  154883. zeromem (destSamples[i] + startOffsetInDestBuffer,
  154884. sizeof (int) * numSamples);
  154885. }
  154886. return true;
  154887. }
  154888. static size_t oggReadCallback (void* ptr, size_t size, size_t nmemb, void* datasource)
  154889. {
  154890. return (size_t) (((InputStream*) datasource)->read (ptr, (int) (size * nmemb)) / size);
  154891. }
  154892. static int oggSeekCallback (void* datasource, ogg_int64_t offset, int whence)
  154893. {
  154894. InputStream* const in = (InputStream*) datasource;
  154895. if (whence == SEEK_CUR)
  154896. offset += in->getPosition();
  154897. else if (whence == SEEK_END)
  154898. offset += in->getTotalLength();
  154899. in->setPosition (offset);
  154900. return 0;
  154901. }
  154902. static int oggCloseCallback (void*)
  154903. {
  154904. return 0;
  154905. }
  154906. static long oggTellCallback (void* datasource)
  154907. {
  154908. return (long) ((InputStream*) datasource)->getPosition();
  154909. }
  154910. juce_UseDebuggingNewOperator
  154911. };
  154912. class OggWriter : public AudioFormatWriter
  154913. {
  154914. ogg_stream_state os;
  154915. ogg_page og;
  154916. ogg_packet op;
  154917. vorbis_info vi;
  154918. vorbis_comment vc;
  154919. vorbis_dsp_state vd;
  154920. vorbis_block vb;
  154921. public:
  154922. bool ok;
  154923. OggWriter (OutputStream* const out,
  154924. const double sampleRate,
  154925. const int numChannels,
  154926. const int bitsPerSample,
  154927. const int qualityIndex)
  154928. : AudioFormatWriter (out, oggFormatName,
  154929. sampleRate,
  154930. numChannels,
  154931. bitsPerSample)
  154932. {
  154933. ok = false;
  154934. vorbis_info_init (&vi);
  154935. if (vorbis_encode_init_vbr (&vi,
  154936. numChannels,
  154937. (int) sampleRate,
  154938. jlimit (0.0f, 1.0f, qualityIndex * 0.5f)) == 0)
  154939. {
  154940. vorbis_comment_init (&vc);
  154941. if (JUCEApplication::getInstance() != 0)
  154942. vorbis_comment_add_tag (&vc, "ENCODER",
  154943. (char*) (const char*) JUCEApplication::getInstance()->getApplicationName());
  154944. vorbis_analysis_init (&vd, &vi);
  154945. vorbis_block_init (&vd, &vb);
  154946. ogg_stream_init (&os, Random::getSystemRandom().nextInt());
  154947. ogg_packet header;
  154948. ogg_packet header_comm;
  154949. ogg_packet header_code;
  154950. vorbis_analysis_headerout (&vd, &vc, &header, &header_comm, &header_code);
  154951. ogg_stream_packetin (&os, &header);
  154952. ogg_stream_packetin (&os, &header_comm);
  154953. ogg_stream_packetin (&os, &header_code);
  154954. for (;;)
  154955. {
  154956. if (ogg_stream_flush (&os, &og) == 0)
  154957. break;
  154958. output->write (og.header, og.header_len);
  154959. output->write (og.body, og.body_len);
  154960. }
  154961. ok = true;
  154962. }
  154963. }
  154964. ~OggWriter()
  154965. {
  154966. if (ok)
  154967. {
  154968. // write a zero-length packet to show ogg that we're finished..
  154969. write (0, 0);
  154970. ogg_stream_clear (&os);
  154971. vorbis_block_clear (&vb);
  154972. vorbis_dsp_clear (&vd);
  154973. vorbis_comment_clear (&vc);
  154974. vorbis_info_clear (&vi);
  154975. output->flush();
  154976. }
  154977. else
  154978. {
  154979. vorbis_info_clear (&vi);
  154980. output = 0; // to stop the base class deleting this, as it needs to be returned
  154981. // to the caller of createWriter()
  154982. }
  154983. }
  154984. bool write (const int** samplesToWrite, int numSamples)
  154985. {
  154986. if (! ok)
  154987. return false;
  154988. if (numSamples > 0)
  154989. {
  154990. const double gain = 1.0 / 0x80000000u;
  154991. float** const vorbisBuffer = vorbis_analysis_buffer (&vd, numSamples);
  154992. for (int i = numChannels; --i >= 0;)
  154993. {
  154994. float* const dst = vorbisBuffer[i];
  154995. const int* const src = samplesToWrite [i];
  154996. if (src != 0 && dst != 0)
  154997. {
  154998. for (int j = 0; j < numSamples; ++j)
  154999. dst[j] = (float) (src[j] * gain);
  155000. }
  155001. }
  155002. }
  155003. vorbis_analysis_wrote (&vd, numSamples);
  155004. while (vorbis_analysis_blockout (&vd, &vb) == 1)
  155005. {
  155006. vorbis_analysis (&vb, 0);
  155007. vorbis_bitrate_addblock (&vb);
  155008. while (vorbis_bitrate_flushpacket (&vd, &op))
  155009. {
  155010. ogg_stream_packetin (&os, &op);
  155011. for (;;)
  155012. {
  155013. if (ogg_stream_pageout (&os, &og) == 0)
  155014. break;
  155015. output->write (og.header, og.header_len);
  155016. output->write (og.body, og.body_len);
  155017. if (ogg_page_eos (&og))
  155018. break;
  155019. }
  155020. }
  155021. }
  155022. return true;
  155023. }
  155024. juce_UseDebuggingNewOperator
  155025. };
  155026. OggVorbisAudioFormat::OggVorbisAudioFormat()
  155027. : AudioFormat (oggFormatName, (const tchar**) oggExtensions)
  155028. {
  155029. }
  155030. OggVorbisAudioFormat::~OggVorbisAudioFormat()
  155031. {
  155032. }
  155033. const Array <int> OggVorbisAudioFormat::getPossibleSampleRates()
  155034. {
  155035. const int rates[] = { 22050, 32000, 44100, 48000, 0 };
  155036. return Array <int> (rates);
  155037. }
  155038. const Array <int> OggVorbisAudioFormat::getPossibleBitDepths()
  155039. {
  155040. Array <int> depths;
  155041. depths.add (32);
  155042. return depths;
  155043. }
  155044. bool OggVorbisAudioFormat::canDoStereo()
  155045. {
  155046. return true;
  155047. }
  155048. bool OggVorbisAudioFormat::canDoMono()
  155049. {
  155050. return true;
  155051. }
  155052. AudioFormatReader* OggVorbisAudioFormat::createReaderFor (InputStream* in,
  155053. const bool deleteStreamIfOpeningFails)
  155054. {
  155055. OggReader* r = new OggReader (in);
  155056. if (r->sampleRate == 0)
  155057. {
  155058. if (! deleteStreamIfOpeningFails)
  155059. r->input = 0;
  155060. deleteAndZero (r);
  155061. }
  155062. return r;
  155063. }
  155064. AudioFormatWriter* OggVorbisAudioFormat::createWriterFor (OutputStream* out,
  155065. double sampleRate,
  155066. unsigned int numChannels,
  155067. int bitsPerSample,
  155068. const StringPairArray& /*metadataValues*/,
  155069. int qualityOptionIndex)
  155070. {
  155071. OggWriter* w = new OggWriter (out,
  155072. sampleRate,
  155073. numChannels,
  155074. bitsPerSample,
  155075. qualityOptionIndex);
  155076. if (! w->ok)
  155077. deleteAndZero (w);
  155078. return w;
  155079. }
  155080. bool OggVorbisAudioFormat::isCompressed()
  155081. {
  155082. return true;
  155083. }
  155084. const StringArray OggVorbisAudioFormat::getQualityOptions()
  155085. {
  155086. StringArray s;
  155087. s.add ("Low Quality");
  155088. s.add ("Medium Quality");
  155089. s.add ("High Quality");
  155090. return s;
  155091. }
  155092. int OggVorbisAudioFormat::estimateOggFileQuality (const File& source)
  155093. {
  155094. FileInputStream* const in = source.createInputStream();
  155095. if (in != 0)
  155096. {
  155097. AudioFormatReader* const r = createReaderFor (in, true);
  155098. if (r != 0)
  155099. {
  155100. const int64 numSamps = r->lengthInSamples;
  155101. delete r;
  155102. const int64 fileNumSamps = source.getSize() / 4;
  155103. const double ratio = numSamps / (double) fileNumSamps;
  155104. if (ratio > 12.0)
  155105. return 0;
  155106. else if (ratio > 6.0)
  155107. return 1;
  155108. else
  155109. return 2;
  155110. }
  155111. }
  155112. return 1;
  155113. }
  155114. END_JUCE_NAMESPACE
  155115. #endif
  155116. /********* End of inlined file: juce_OggVorbisAudioFormat.cpp *********/
  155117. /********* Start of inlined file: juce_JPEGLoader.cpp *********/
  155118. #if JUCE_MSVC
  155119. #pragma warning (push)
  155120. #endif
  155121. namespace jpeglibNamespace
  155122. {
  155123. #if JUCE_INCLUDE_JPEGLIB_CODE
  155124. extern "C"
  155125. {
  155126. #define JPEG_INTERNALS
  155127. #undef FAR
  155128. /********* Start of inlined file: jpeglib.h *********/
  155129. #ifndef JPEGLIB_H
  155130. #define JPEGLIB_H
  155131. /*
  155132. * First we include the configuration files that record how this
  155133. * installation of the JPEG library is set up. jconfig.h can be
  155134. * generated automatically for many systems. jmorecfg.h contains
  155135. * manual configuration options that most people need not worry about.
  155136. */
  155137. #ifndef JCONFIG_INCLUDED /* in case jinclude.h already did */
  155138. /********* Start of inlined file: jconfig.h *********/
  155139. /* see jconfig.doc for explanations */
  155140. // disable all the warnings under MSVC
  155141. #ifdef _MSC_VER
  155142. #pragma warning (disable: 4996 4267 4100 4127 4702 4244)
  155143. #endif
  155144. #ifdef __BORLANDC__
  155145. #pragma warn -8057
  155146. #pragma warn -8019
  155147. #pragma warn -8004
  155148. #pragma warn -8008
  155149. #endif
  155150. #define HAVE_PROTOTYPES
  155151. #define HAVE_UNSIGNED_CHAR
  155152. #define HAVE_UNSIGNED_SHORT
  155153. /* #define void char */
  155154. /* #define const */
  155155. #undef CHAR_IS_UNSIGNED
  155156. #define HAVE_STDDEF_H
  155157. #define HAVE_STDLIB_H
  155158. #undef NEED_BSD_STRINGS
  155159. #undef NEED_SYS_TYPES_H
  155160. #undef NEED_FAR_POINTERS /* we presume a 32-bit flat memory model */
  155161. #undef NEED_SHORT_EXTERNAL_NAMES
  155162. #undef INCOMPLETE_TYPES_BROKEN
  155163. /* Define "boolean" as unsigned char, not int, per Windows custom */
  155164. #ifndef __RPCNDR_H__ /* don't conflict if rpcndr.h already read */
  155165. typedef unsigned char boolean;
  155166. #endif
  155167. #define HAVE_BOOLEAN /* prevent jmorecfg.h from redefining it */
  155168. #ifdef JPEG_INTERNALS
  155169. #undef RIGHT_SHIFT_IS_UNSIGNED
  155170. #endif /* JPEG_INTERNALS */
  155171. #ifdef JPEG_CJPEG_DJPEG
  155172. #define BMP_SUPPORTED /* BMP image file format */
  155173. #define GIF_SUPPORTED /* GIF image file format */
  155174. #define PPM_SUPPORTED /* PBMPLUS PPM/PGM image file format */
  155175. #undef RLE_SUPPORTED /* Utah RLE image file format */
  155176. #define TARGA_SUPPORTED /* Targa image file format */
  155177. #define TWO_FILE_COMMANDLINE /* optional */
  155178. #define USE_SETMODE /* Microsoft has setmode() */
  155179. #undef NEED_SIGNAL_CATCHER
  155180. #undef DONT_USE_B_MODE
  155181. #undef PROGRESS_REPORT /* optional */
  155182. #endif /* JPEG_CJPEG_DJPEG */
  155183. /********* End of inlined file: jconfig.h *********/
  155184. /* widely used configuration options */
  155185. #endif
  155186. /********* Start of inlined file: jmorecfg.h *********/
  155187. /*
  155188. * Define BITS_IN_JSAMPLE as either
  155189. * 8 for 8-bit sample values (the usual setting)
  155190. * 12 for 12-bit sample values
  155191. * Only 8 and 12 are legal data precisions for lossy JPEG according to the
  155192. * JPEG standard, and the IJG code does not support anything else!
  155193. * We do not support run-time selection of data precision, sorry.
  155194. */
  155195. #define BITS_IN_JSAMPLE 8 /* use 8 or 12 */
  155196. /*
  155197. * Maximum number of components (color channels) allowed in JPEG image.
  155198. * To meet the letter of the JPEG spec, set this to 255. However, darn
  155199. * few applications need more than 4 channels (maybe 5 for CMYK + alpha
  155200. * mask). We recommend 10 as a reasonable compromise; use 4 if you are
  155201. * really short on memory. (Each allowed component costs a hundred or so
  155202. * bytes of storage, whether actually used in an image or not.)
  155203. */
  155204. #define MAX_COMPONENTS 10 /* maximum number of image components */
  155205. /*
  155206. * Basic data types.
  155207. * You may need to change these if you have a machine with unusual data
  155208. * type sizes; for example, "char" not 8 bits, "short" not 16 bits,
  155209. * or "long" not 32 bits. We don't care whether "int" is 16 or 32 bits,
  155210. * but it had better be at least 16.
  155211. */
  155212. /* Representation of a single sample (pixel element value).
  155213. * We frequently allocate large arrays of these, so it's important to keep
  155214. * them small. But if you have memory to burn and access to char or short
  155215. * arrays is very slow on your hardware, you might want to change these.
  155216. */
  155217. #if BITS_IN_JSAMPLE == 8
  155218. /* JSAMPLE should be the smallest type that will hold the values 0..255.
  155219. * You can use a signed char by having GETJSAMPLE mask it with 0xFF.
  155220. */
  155221. #ifdef HAVE_UNSIGNED_CHAR
  155222. typedef unsigned char JSAMPLE;
  155223. #define GETJSAMPLE(value) ((int) (value))
  155224. #else /* not HAVE_UNSIGNED_CHAR */
  155225. typedef char JSAMPLE;
  155226. #ifdef CHAR_IS_UNSIGNED
  155227. #define GETJSAMPLE(value) ((int) (value))
  155228. #else
  155229. #define GETJSAMPLE(value) ((int) (value) & 0xFF)
  155230. #endif /* CHAR_IS_UNSIGNED */
  155231. #endif /* HAVE_UNSIGNED_CHAR */
  155232. #define MAXJSAMPLE 255
  155233. #define CENTERJSAMPLE 128
  155234. #endif /* BITS_IN_JSAMPLE == 8 */
  155235. #if BITS_IN_JSAMPLE == 12
  155236. /* JSAMPLE should be the smallest type that will hold the values 0..4095.
  155237. * On nearly all machines "short" will do nicely.
  155238. */
  155239. typedef short JSAMPLE;
  155240. #define GETJSAMPLE(value) ((int) (value))
  155241. #define MAXJSAMPLE 4095
  155242. #define CENTERJSAMPLE 2048
  155243. #endif /* BITS_IN_JSAMPLE == 12 */
  155244. /* Representation of a DCT frequency coefficient.
  155245. * This should be a signed value of at least 16 bits; "short" is usually OK.
  155246. * Again, we allocate large arrays of these, but you can change to int
  155247. * if you have memory to burn and "short" is really slow.
  155248. */
  155249. typedef short JCOEF;
  155250. /* Compressed datastreams are represented as arrays of JOCTET.
  155251. * These must be EXACTLY 8 bits wide, at least once they are written to
  155252. * external storage. Note that when using the stdio data source/destination
  155253. * managers, this is also the data type passed to fread/fwrite.
  155254. */
  155255. #ifdef HAVE_UNSIGNED_CHAR
  155256. typedef unsigned char JOCTET;
  155257. #define GETJOCTET(value) (value)
  155258. #else /* not HAVE_UNSIGNED_CHAR */
  155259. typedef char JOCTET;
  155260. #ifdef CHAR_IS_UNSIGNED
  155261. #define GETJOCTET(value) (value)
  155262. #else
  155263. #define GETJOCTET(value) ((value) & 0xFF)
  155264. #endif /* CHAR_IS_UNSIGNED */
  155265. #endif /* HAVE_UNSIGNED_CHAR */
  155266. /* These typedefs are used for various table entries and so forth.
  155267. * They must be at least as wide as specified; but making them too big
  155268. * won't cost a huge amount of memory, so we don't provide special
  155269. * extraction code like we did for JSAMPLE. (In other words, these
  155270. * typedefs live at a different point on the speed/space tradeoff curve.)
  155271. */
  155272. /* UINT8 must hold at least the values 0..255. */
  155273. #ifdef HAVE_UNSIGNED_CHAR
  155274. typedef unsigned char UINT8;
  155275. #else /* not HAVE_UNSIGNED_CHAR */
  155276. #ifdef CHAR_IS_UNSIGNED
  155277. typedef char UINT8;
  155278. #else /* not CHAR_IS_UNSIGNED */
  155279. typedef short UINT8;
  155280. #endif /* CHAR_IS_UNSIGNED */
  155281. #endif /* HAVE_UNSIGNED_CHAR */
  155282. /* UINT16 must hold at least the values 0..65535. */
  155283. #ifdef HAVE_UNSIGNED_SHORT
  155284. typedef unsigned short UINT16;
  155285. #else /* not HAVE_UNSIGNED_SHORT */
  155286. typedef unsigned int UINT16;
  155287. #endif /* HAVE_UNSIGNED_SHORT */
  155288. /* INT16 must hold at least the values -32768..32767. */
  155289. #ifndef XMD_H /* X11/xmd.h correctly defines INT16 */
  155290. typedef short INT16;
  155291. #endif
  155292. /* INT32 must hold at least signed 32-bit values. */
  155293. #ifndef XMD_H /* X11/xmd.h correctly defines INT32 */
  155294. typedef long INT32;
  155295. #endif
  155296. /* Datatype used for image dimensions. The JPEG standard only supports
  155297. * images up to 64K*64K due to 16-bit fields in SOF markers. Therefore
  155298. * "unsigned int" is sufficient on all machines. However, if you need to
  155299. * handle larger images and you don't mind deviating from the spec, you
  155300. * can change this datatype.
  155301. */
  155302. typedef unsigned int JDIMENSION;
  155303. #define JPEG_MAX_DIMENSION 65500L /* a tad under 64K to prevent overflows */
  155304. /* These macros are used in all function definitions and extern declarations.
  155305. * You could modify them if you need to change function linkage conventions;
  155306. * in particular, you'll need to do that to make the library a Windows DLL.
  155307. * Another application is to make all functions global for use with debuggers
  155308. * or code profilers that require it.
  155309. */
  155310. /* a function called through method pointers: */
  155311. #define METHODDEF(type) static type
  155312. /* a function used only in its module: */
  155313. #define LOCAL(type) static type
  155314. /* a function referenced thru EXTERNs: */
  155315. #define GLOBAL(type) type
  155316. /* a reference to a GLOBAL function: */
  155317. #define EXTERN(type) extern type
  155318. /* This macro is used to declare a "method", that is, a function pointer.
  155319. * We want to supply prototype parameters if the compiler can cope.
  155320. * Note that the arglist parameter must be parenthesized!
  155321. * Again, you can customize this if you need special linkage keywords.
  155322. */
  155323. #ifdef HAVE_PROTOTYPES
  155324. #define JMETHOD(type,methodname,arglist) type (*methodname) arglist
  155325. #else
  155326. #define JMETHOD(type,methodname,arglist) type (*methodname) ()
  155327. #endif
  155328. /* Here is the pseudo-keyword for declaring pointers that must be "far"
  155329. * on 80x86 machines. Most of the specialized coding for 80x86 is handled
  155330. * by just saying "FAR *" where such a pointer is needed. In a few places
  155331. * explicit coding is needed; see uses of the NEED_FAR_POINTERS symbol.
  155332. */
  155333. #ifdef NEED_FAR_POINTERS
  155334. #define FAR far
  155335. #else
  155336. #define FAR
  155337. #endif
  155338. /*
  155339. * On a few systems, type boolean and/or its values FALSE, TRUE may appear
  155340. * in standard header files. Or you may have conflicts with application-
  155341. * specific header files that you want to include together with these files.
  155342. * Defining HAVE_BOOLEAN before including jpeglib.h should make it work.
  155343. */
  155344. #ifndef HAVE_BOOLEAN
  155345. typedef int boolean;
  155346. #endif
  155347. #ifndef FALSE /* in case these macros already exist */
  155348. #define FALSE 0 /* values of boolean */
  155349. #endif
  155350. #ifndef TRUE
  155351. #define TRUE 1
  155352. #endif
  155353. /*
  155354. * The remaining options affect code selection within the JPEG library,
  155355. * but they don't need to be visible to most applications using the library.
  155356. * To minimize application namespace pollution, the symbols won't be
  155357. * defined unless JPEG_INTERNALS or JPEG_INTERNAL_OPTIONS has been defined.
  155358. */
  155359. #ifdef JPEG_INTERNALS
  155360. #define JPEG_INTERNAL_OPTIONS
  155361. #endif
  155362. #ifdef JPEG_INTERNAL_OPTIONS
  155363. /*
  155364. * These defines indicate whether to include various optional functions.
  155365. * Undefining some of these symbols will produce a smaller but less capable
  155366. * library. Note that you can leave certain source files out of the
  155367. * compilation/linking process if you've #undef'd the corresponding symbols.
  155368. * (You may HAVE to do that if your compiler doesn't like null source files.)
  155369. */
  155370. /* Arithmetic coding is unsupported for legal reasons. Complaints to IBM. */
  155371. /* Capability options common to encoder and decoder: */
  155372. #define DCT_ISLOW_SUPPORTED /* slow but accurate integer algorithm */
  155373. #define DCT_IFAST_SUPPORTED /* faster, less accurate integer method */
  155374. #define DCT_FLOAT_SUPPORTED /* floating-point: accurate, fast on fast HW */
  155375. /* Encoder capability options: */
  155376. #undef C_ARITH_CODING_SUPPORTED /* Arithmetic coding back end? */
  155377. #define C_MULTISCAN_FILES_SUPPORTED /* Multiple-scan JPEG files? */
  155378. #define C_PROGRESSIVE_SUPPORTED /* Progressive JPEG? (Requires MULTISCAN)*/
  155379. #define ENTROPY_OPT_SUPPORTED /* Optimization of entropy coding parms? */
  155380. /* Note: if you selected 12-bit data precision, it is dangerous to turn off
  155381. * ENTROPY_OPT_SUPPORTED. The standard Huffman tables are only good for 8-bit
  155382. * precision, so jchuff.c normally uses entropy optimization to compute
  155383. * usable tables for higher precision. If you don't want to do optimization,
  155384. * you'll have to supply different default Huffman tables.
  155385. * The exact same statements apply for progressive JPEG: the default tables
  155386. * don't work for progressive mode. (This may get fixed, however.)
  155387. */
  155388. #define INPUT_SMOOTHING_SUPPORTED /* Input image smoothing option? */
  155389. /* Decoder capability options: */
  155390. #undef D_ARITH_CODING_SUPPORTED /* Arithmetic coding back end? */
  155391. #define D_MULTISCAN_FILES_SUPPORTED /* Multiple-scan JPEG files? */
  155392. #define D_PROGRESSIVE_SUPPORTED /* Progressive JPEG? (Requires MULTISCAN)*/
  155393. #define SAVE_MARKERS_SUPPORTED /* jpeg_save_markers() needed? */
  155394. #define BLOCK_SMOOTHING_SUPPORTED /* Block smoothing? (Progressive only) */
  155395. #define IDCT_SCALING_SUPPORTED /* Output rescaling via IDCT? */
  155396. #undef UPSAMPLE_SCALING_SUPPORTED /* Output rescaling at upsample stage? */
  155397. #define UPSAMPLE_MERGING_SUPPORTED /* Fast path for sloppy upsampling? */
  155398. #define QUANT_1PASS_SUPPORTED /* 1-pass color quantization? */
  155399. #define QUANT_2PASS_SUPPORTED /* 2-pass color quantization? */
  155400. /* more capability options later, no doubt */
  155401. /*
  155402. * Ordering of RGB data in scanlines passed to or from the application.
  155403. * If your application wants to deal with data in the order B,G,R, just
  155404. * change these macros. You can also deal with formats such as R,G,B,X
  155405. * (one extra byte per pixel) by changing RGB_PIXELSIZE. Note that changing
  155406. * the offsets will also change the order in which colormap data is organized.
  155407. * RESTRICTIONS:
  155408. * 1. The sample applications cjpeg,djpeg do NOT support modified RGB formats.
  155409. * 2. These macros only affect RGB<=>YCbCr color conversion, so they are not
  155410. * useful if you are using JPEG color spaces other than YCbCr or grayscale.
  155411. * 3. The color quantizer modules will not behave desirably if RGB_PIXELSIZE
  155412. * is not 3 (they don't understand about dummy color components!). So you
  155413. * can't use color quantization if you change that value.
  155414. */
  155415. #define RGB_RED 0 /* Offset of Red in an RGB scanline element */
  155416. #define RGB_GREEN 1 /* Offset of Green */
  155417. #define RGB_BLUE 2 /* Offset of Blue */
  155418. #define RGB_PIXELSIZE 3 /* JSAMPLEs per RGB scanline element */
  155419. /* Definitions for speed-related optimizations. */
  155420. /* If your compiler supports inline functions, define INLINE
  155421. * as the inline keyword; otherwise define it as empty.
  155422. */
  155423. #ifndef INLINE
  155424. #ifdef __GNUC__ /* for instance, GNU C knows about inline */
  155425. #define INLINE __inline__
  155426. #endif
  155427. #ifndef INLINE
  155428. #define INLINE /* default is to define it as empty */
  155429. #endif
  155430. #endif
  155431. /* On some machines (notably 68000 series) "int" is 32 bits, but multiplying
  155432. * two 16-bit shorts is faster than multiplying two ints. Define MULTIPLIER
  155433. * as short on such a machine. MULTIPLIER must be at least 16 bits wide.
  155434. */
  155435. #ifndef MULTIPLIER
  155436. #define MULTIPLIER int /* type for fastest integer multiply */
  155437. #endif
  155438. /* FAST_FLOAT should be either float or double, whichever is done faster
  155439. * by your compiler. (Note that this type is only used in the floating point
  155440. * DCT routines, so it only matters if you've defined DCT_FLOAT_SUPPORTED.)
  155441. * Typically, float is faster in ANSI C compilers, while double is faster in
  155442. * pre-ANSI compilers (because they insist on converting to double anyway).
  155443. * The code below therefore chooses float if we have ANSI-style prototypes.
  155444. */
  155445. #ifndef FAST_FLOAT
  155446. #ifdef HAVE_PROTOTYPES
  155447. #define FAST_FLOAT float
  155448. #else
  155449. #define FAST_FLOAT double
  155450. #endif
  155451. #endif
  155452. #endif /* JPEG_INTERNAL_OPTIONS */
  155453. /********* End of inlined file: jmorecfg.h *********/
  155454. /* seldom changed options */
  155455. /* Version ID for the JPEG library.
  155456. * Might be useful for tests like "#if JPEG_LIB_VERSION >= 60".
  155457. */
  155458. #define JPEG_LIB_VERSION 62 /* Version 6b */
  155459. /* Various constants determining the sizes of things.
  155460. * All of these are specified by the JPEG standard, so don't change them
  155461. * if you want to be compatible.
  155462. */
  155463. #define DCTSIZE 8 /* The basic DCT block is 8x8 samples */
  155464. #define DCTSIZE2 64 /* DCTSIZE squared; # of elements in a block */
  155465. #define NUM_QUANT_TBLS 4 /* Quantization tables are numbered 0..3 */
  155466. #define NUM_HUFF_TBLS 4 /* Huffman tables are numbered 0..3 */
  155467. #define NUM_ARITH_TBLS 16 /* Arith-coding tables are numbered 0..15 */
  155468. #define MAX_COMPS_IN_SCAN 4 /* JPEG limit on # of components in one scan */
  155469. #define MAX_SAMP_FACTOR 4 /* JPEG limit on sampling factors */
  155470. /* Unfortunately, some bozo at Adobe saw no reason to be bound by the standard;
  155471. * the PostScript DCT filter can emit files with many more than 10 blocks/MCU.
  155472. * If you happen to run across such a file, you can up D_MAX_BLOCKS_IN_MCU
  155473. * to handle it. We even let you do this from the jconfig.h file. However,
  155474. * we strongly discourage changing C_MAX_BLOCKS_IN_MCU; just because Adobe
  155475. * sometimes emits noncompliant files doesn't mean you should too.
  155476. */
  155477. #define C_MAX_BLOCKS_IN_MCU 10 /* compressor's limit on blocks per MCU */
  155478. #ifndef D_MAX_BLOCKS_IN_MCU
  155479. #define D_MAX_BLOCKS_IN_MCU 10 /* decompressor's limit on blocks per MCU */
  155480. #endif
  155481. /* Data structures for images (arrays of samples and of DCT coefficients).
  155482. * On 80x86 machines, the image arrays are too big for near pointers,
  155483. * but the pointer arrays can fit in near memory.
  155484. */
  155485. typedef JSAMPLE FAR *JSAMPROW; /* ptr to one image row of pixel samples. */
  155486. typedef JSAMPROW *JSAMPARRAY; /* ptr to some rows (a 2-D sample array) */
  155487. typedef JSAMPARRAY *JSAMPIMAGE; /* a 3-D sample array: top index is color */
  155488. typedef JCOEF JBLOCK[DCTSIZE2]; /* one block of coefficients */
  155489. typedef JBLOCK FAR *JBLOCKROW; /* pointer to one row of coefficient blocks */
  155490. typedef JBLOCKROW *JBLOCKARRAY; /* a 2-D array of coefficient blocks */
  155491. typedef JBLOCKARRAY *JBLOCKIMAGE; /* a 3-D array of coefficient blocks */
  155492. typedef JCOEF FAR *JCOEFPTR; /* useful in a couple of places */
  155493. /* Types for JPEG compression parameters and working tables. */
  155494. /* DCT coefficient quantization tables. */
  155495. typedef struct {
  155496. /* This array gives the coefficient quantizers in natural array order
  155497. * (not the zigzag order in which they are stored in a JPEG DQT marker).
  155498. * CAUTION: IJG versions prior to v6a kept this array in zigzag order.
  155499. */
  155500. UINT16 quantval[DCTSIZE2]; /* quantization step for each coefficient */
  155501. /* This field is used only during compression. It's initialized FALSE when
  155502. * the table is created, and set TRUE when it's been output to the file.
  155503. * You could suppress output of a table by setting this to TRUE.
  155504. * (See jpeg_suppress_tables for an example.)
  155505. */
  155506. boolean sent_table; /* TRUE when table has been output */
  155507. } JQUANT_TBL;
  155508. /* Huffman coding tables. */
  155509. typedef struct {
  155510. /* These two fields directly represent the contents of a JPEG DHT marker */
  155511. UINT8 bits[17]; /* bits[k] = # of symbols with codes of */
  155512. /* length k bits; bits[0] is unused */
  155513. UINT8 huffval[256]; /* The symbols, in order of incr code length */
  155514. /* This field is used only during compression. It's initialized FALSE when
  155515. * the table is created, and set TRUE when it's been output to the file.
  155516. * You could suppress output of a table by setting this to TRUE.
  155517. * (See jpeg_suppress_tables for an example.)
  155518. */
  155519. boolean sent_table; /* TRUE when table has been output */
  155520. } JHUFF_TBL;
  155521. /* Basic info about one component (color channel). */
  155522. typedef struct {
  155523. /* These values are fixed over the whole image. */
  155524. /* For compression, they must be supplied by parameter setup; */
  155525. /* for decompression, they are read from the SOF marker. */
  155526. int component_id; /* identifier for this component (0..255) */
  155527. int component_index; /* its index in SOF or cinfo->comp_info[] */
  155528. int h_samp_factor; /* horizontal sampling factor (1..4) */
  155529. int v_samp_factor; /* vertical sampling factor (1..4) */
  155530. int quant_tbl_no; /* quantization table selector (0..3) */
  155531. /* These values may vary between scans. */
  155532. /* For compression, they must be supplied by parameter setup; */
  155533. /* for decompression, they are read from the SOS marker. */
  155534. /* The decompressor output side may not use these variables. */
  155535. int dc_tbl_no; /* DC entropy table selector (0..3) */
  155536. int ac_tbl_no; /* AC entropy table selector (0..3) */
  155537. /* Remaining fields should be treated as private by applications. */
  155538. /* These values are computed during compression or decompression startup: */
  155539. /* Component's size in DCT blocks.
  155540. * Any dummy blocks added to complete an MCU are not counted; therefore
  155541. * these values do not depend on whether a scan is interleaved or not.
  155542. */
  155543. JDIMENSION width_in_blocks;
  155544. JDIMENSION height_in_blocks;
  155545. /* Size of a DCT block in samples. Always DCTSIZE for compression.
  155546. * For decompression this is the size of the output from one DCT block,
  155547. * reflecting any scaling we choose to apply during the IDCT step.
  155548. * Values of 1,2,4,8 are likely to be supported. Note that different
  155549. * components may receive different IDCT scalings.
  155550. */
  155551. int DCT_scaled_size;
  155552. /* The downsampled dimensions are the component's actual, unpadded number
  155553. * of samples at the main buffer (preprocessing/compression interface), thus
  155554. * downsampled_width = ceil(image_width * Hi/Hmax)
  155555. * and similarly for height. For decompression, IDCT scaling is included, so
  155556. * downsampled_width = ceil(image_width * Hi/Hmax * DCT_scaled_size/DCTSIZE)
  155557. */
  155558. JDIMENSION downsampled_width; /* actual width in samples */
  155559. JDIMENSION downsampled_height; /* actual height in samples */
  155560. /* This flag is used only for decompression. In cases where some of the
  155561. * components will be ignored (eg grayscale output from YCbCr image),
  155562. * we can skip most computations for the unused components.
  155563. */
  155564. boolean component_needed; /* do we need the value of this component? */
  155565. /* These values are computed before starting a scan of the component. */
  155566. /* The decompressor output side may not use these variables. */
  155567. int MCU_width; /* number of blocks per MCU, horizontally */
  155568. int MCU_height; /* number of blocks per MCU, vertically */
  155569. int MCU_blocks; /* MCU_width * MCU_height */
  155570. int MCU_sample_width; /* MCU width in samples, MCU_width*DCT_scaled_size */
  155571. int last_col_width; /* # of non-dummy blocks across in last MCU */
  155572. int last_row_height; /* # of non-dummy blocks down in last MCU */
  155573. /* Saved quantization table for component; NULL if none yet saved.
  155574. * See jdinput.c comments about the need for this information.
  155575. * This field is currently used only for decompression.
  155576. */
  155577. JQUANT_TBL * quant_table;
  155578. /* Private per-component storage for DCT or IDCT subsystem. */
  155579. void * dct_table;
  155580. } jpeg_component_info;
  155581. /* The script for encoding a multiple-scan file is an array of these: */
  155582. typedef struct {
  155583. int comps_in_scan; /* number of components encoded in this scan */
  155584. int component_index[MAX_COMPS_IN_SCAN]; /* their SOF/comp_info[] indexes */
  155585. int Ss, Se; /* progressive JPEG spectral selection parms */
  155586. int Ah, Al; /* progressive JPEG successive approx. parms */
  155587. } jpeg_scan_info;
  155588. /* The decompressor can save APPn and COM markers in a list of these: */
  155589. typedef struct jpeg_marker_struct FAR * jpeg_saved_marker_ptr;
  155590. struct jpeg_marker_struct {
  155591. jpeg_saved_marker_ptr next; /* next in list, or NULL */
  155592. UINT8 marker; /* marker code: JPEG_COM, or JPEG_APP0+n */
  155593. unsigned int original_length; /* # bytes of data in the file */
  155594. unsigned int data_length; /* # bytes of data saved at data[] */
  155595. JOCTET FAR * data; /* the data contained in the marker */
  155596. /* the marker length word is not counted in data_length or original_length */
  155597. };
  155598. /* Known color spaces. */
  155599. typedef enum {
  155600. JCS_UNKNOWN, /* error/unspecified */
  155601. JCS_GRAYSCALE, /* monochrome */
  155602. JCS_RGB, /* red/green/blue */
  155603. JCS_YCbCr, /* Y/Cb/Cr (also known as YUV) */
  155604. JCS_CMYK, /* C/M/Y/K */
  155605. JCS_YCCK /* Y/Cb/Cr/K */
  155606. } J_COLOR_SPACE;
  155607. /* DCT/IDCT algorithm options. */
  155608. typedef enum {
  155609. JDCT_ISLOW, /* slow but accurate integer algorithm */
  155610. JDCT_IFAST, /* faster, less accurate integer method */
  155611. JDCT_FLOAT /* floating-point: accurate, fast on fast HW */
  155612. } J_DCT_METHOD;
  155613. #ifndef JDCT_DEFAULT /* may be overridden in jconfig.h */
  155614. #define JDCT_DEFAULT JDCT_ISLOW
  155615. #endif
  155616. #ifndef JDCT_FASTEST /* may be overridden in jconfig.h */
  155617. #define JDCT_FASTEST JDCT_IFAST
  155618. #endif
  155619. /* Dithering options for decompression. */
  155620. typedef enum {
  155621. JDITHER_NONE, /* no dithering */
  155622. JDITHER_ORDERED, /* simple ordered dither */
  155623. JDITHER_FS /* Floyd-Steinberg error diffusion dither */
  155624. } J_DITHER_MODE;
  155625. /* Common fields between JPEG compression and decompression master structs. */
  155626. #define jpeg_common_fields \
  155627. struct jpeg_error_mgr * err; /* Error handler module */\
  155628. struct jpeg_memory_mgr * mem; /* Memory manager module */\
  155629. struct jpeg_progress_mgr * progress; /* Progress monitor, or NULL if none */\
  155630. void * client_data; /* Available for use by application */\
  155631. boolean is_decompressor; /* So common code can tell which is which */\
  155632. int global_state /* For checking call sequence validity */
  155633. /* Routines that are to be used by both halves of the library are declared
  155634. * to receive a pointer to this structure. There are no actual instances of
  155635. * jpeg_common_struct, only of jpeg_compress_struct and jpeg_decompress_struct.
  155636. */
  155637. struct jpeg_common_struct {
  155638. jpeg_common_fields; /* Fields common to both master struct types */
  155639. /* Additional fields follow in an actual jpeg_compress_struct or
  155640. * jpeg_decompress_struct. All three structs must agree on these
  155641. * initial fields! (This would be a lot cleaner in C++.)
  155642. */
  155643. };
  155644. typedef struct jpeg_common_struct * j_common_ptr;
  155645. typedef struct jpeg_compress_struct * j_compress_ptr;
  155646. typedef struct jpeg_decompress_struct * j_decompress_ptr;
  155647. /* Master record for a compression instance */
  155648. struct jpeg_compress_struct {
  155649. jpeg_common_fields; /* Fields shared with jpeg_decompress_struct */
  155650. /* Destination for compressed data */
  155651. struct jpeg_destination_mgr * dest;
  155652. /* Description of source image --- these fields must be filled in by
  155653. * outer application before starting compression. in_color_space must
  155654. * be correct before you can even call jpeg_set_defaults().
  155655. */
  155656. JDIMENSION image_width; /* input image width */
  155657. JDIMENSION image_height; /* input image height */
  155658. int input_components; /* # of color components in input image */
  155659. J_COLOR_SPACE in_color_space; /* colorspace of input image */
  155660. double input_gamma; /* image gamma of input image */
  155661. /* Compression parameters --- these fields must be set before calling
  155662. * jpeg_start_compress(). We recommend calling jpeg_set_defaults() to
  155663. * initialize everything to reasonable defaults, then changing anything
  155664. * the application specifically wants to change. That way you won't get
  155665. * burnt when new parameters are added. Also note that there are several
  155666. * helper routines to simplify changing parameters.
  155667. */
  155668. int data_precision; /* bits of precision in image data */
  155669. int num_components; /* # of color components in JPEG image */
  155670. J_COLOR_SPACE jpeg_color_space; /* colorspace of JPEG image */
  155671. jpeg_component_info * comp_info;
  155672. /* comp_info[i] describes component that appears i'th in SOF */
  155673. JQUANT_TBL * quant_tbl_ptrs[NUM_QUANT_TBLS];
  155674. /* ptrs to coefficient quantization tables, or NULL if not defined */
  155675. JHUFF_TBL * dc_huff_tbl_ptrs[NUM_HUFF_TBLS];
  155676. JHUFF_TBL * ac_huff_tbl_ptrs[NUM_HUFF_TBLS];
  155677. /* ptrs to Huffman coding tables, or NULL if not defined */
  155678. UINT8 arith_dc_L[NUM_ARITH_TBLS]; /* L values for DC arith-coding tables */
  155679. UINT8 arith_dc_U[NUM_ARITH_TBLS]; /* U values for DC arith-coding tables */
  155680. UINT8 arith_ac_K[NUM_ARITH_TBLS]; /* Kx values for AC arith-coding tables */
  155681. int num_scans; /* # of entries in scan_info array */
  155682. const jpeg_scan_info * scan_info; /* script for multi-scan file, or NULL */
  155683. /* The default value of scan_info is NULL, which causes a single-scan
  155684. * sequential JPEG file to be emitted. To create a multi-scan file,
  155685. * set num_scans and scan_info to point to an array of scan definitions.
  155686. */
  155687. boolean raw_data_in; /* TRUE=caller supplies downsampled data */
  155688. boolean arith_code; /* TRUE=arithmetic coding, FALSE=Huffman */
  155689. boolean optimize_coding; /* TRUE=optimize entropy encoding parms */
  155690. boolean CCIR601_sampling; /* TRUE=first samples are cosited */
  155691. int smoothing_factor; /* 1..100, or 0 for no input smoothing */
  155692. J_DCT_METHOD dct_method; /* DCT algorithm selector */
  155693. /* The restart interval can be specified in absolute MCUs by setting
  155694. * restart_interval, or in MCU rows by setting restart_in_rows
  155695. * (in which case the correct restart_interval will be figured
  155696. * for each scan).
  155697. */
  155698. unsigned int restart_interval; /* MCUs per restart, or 0 for no restart */
  155699. int restart_in_rows; /* if > 0, MCU rows per restart interval */
  155700. /* Parameters controlling emission of special markers. */
  155701. boolean write_JFIF_header; /* should a JFIF marker be written? */
  155702. UINT8 JFIF_major_version; /* What to write for the JFIF version number */
  155703. UINT8 JFIF_minor_version;
  155704. /* These three values are not used by the JPEG code, merely copied */
  155705. /* into the JFIF APP0 marker. density_unit can be 0 for unknown, */
  155706. /* 1 for dots/inch, or 2 for dots/cm. Note that the pixel aspect */
  155707. /* ratio is defined by X_density/Y_density even when density_unit=0. */
  155708. UINT8 density_unit; /* JFIF code for pixel size units */
  155709. UINT16 X_density; /* Horizontal pixel density */
  155710. UINT16 Y_density; /* Vertical pixel density */
  155711. boolean write_Adobe_marker; /* should an Adobe marker be written? */
  155712. /* State variable: index of next scanline to be written to
  155713. * jpeg_write_scanlines(). Application may use this to control its
  155714. * processing loop, e.g., "while (next_scanline < image_height)".
  155715. */
  155716. JDIMENSION next_scanline; /* 0 .. image_height-1 */
  155717. /* Remaining fields are known throughout compressor, but generally
  155718. * should not be touched by a surrounding application.
  155719. */
  155720. /*
  155721. * These fields are computed during compression startup
  155722. */
  155723. boolean progressive_mode; /* TRUE if scan script uses progressive mode */
  155724. int max_h_samp_factor; /* largest h_samp_factor */
  155725. int max_v_samp_factor; /* largest v_samp_factor */
  155726. JDIMENSION total_iMCU_rows; /* # of iMCU rows to be input to coef ctlr */
  155727. /* The coefficient controller receives data in units of MCU rows as defined
  155728. * for fully interleaved scans (whether the JPEG file is interleaved or not).
  155729. * There are v_samp_factor * DCTSIZE sample rows of each component in an
  155730. * "iMCU" (interleaved MCU) row.
  155731. */
  155732. /*
  155733. * These fields are valid during any one scan.
  155734. * They describe the components and MCUs actually appearing in the scan.
  155735. */
  155736. int comps_in_scan; /* # of JPEG components in this scan */
  155737. jpeg_component_info * cur_comp_info[MAX_COMPS_IN_SCAN];
  155738. /* *cur_comp_info[i] describes component that appears i'th in SOS */
  155739. JDIMENSION MCUs_per_row; /* # of MCUs across the image */
  155740. JDIMENSION MCU_rows_in_scan; /* # of MCU rows in the image */
  155741. int blocks_in_MCU; /* # of DCT blocks per MCU */
  155742. int MCU_membership[C_MAX_BLOCKS_IN_MCU];
  155743. /* MCU_membership[i] is index in cur_comp_info of component owning */
  155744. /* i'th block in an MCU */
  155745. int Ss, Se, Ah, Al; /* progressive JPEG parameters for scan */
  155746. /*
  155747. * Links to compression subobjects (methods and private variables of modules)
  155748. */
  155749. struct jpeg_comp_master * master;
  155750. struct jpeg_c_main_controller * main;
  155751. struct jpeg_c_prep_controller * prep;
  155752. struct jpeg_c_coef_controller * coef;
  155753. struct jpeg_marker_writer * marker;
  155754. struct jpeg_color_converter * cconvert;
  155755. struct jpeg_downsampler * downsample;
  155756. struct jpeg_forward_dct * fdct;
  155757. struct jpeg_entropy_encoder * entropy;
  155758. jpeg_scan_info * script_space; /* workspace for jpeg_simple_progression */
  155759. int script_space_size;
  155760. };
  155761. /* Master record for a decompression instance */
  155762. struct jpeg_decompress_struct {
  155763. jpeg_common_fields; /* Fields shared with jpeg_compress_struct */
  155764. /* Source of compressed data */
  155765. struct jpeg_source_mgr * src;
  155766. /* Basic description of image --- filled in by jpeg_read_header(). */
  155767. /* Application may inspect these values to decide how to process image. */
  155768. JDIMENSION image_width; /* nominal image width (from SOF marker) */
  155769. JDIMENSION image_height; /* nominal image height */
  155770. int num_components; /* # of color components in JPEG image */
  155771. J_COLOR_SPACE jpeg_color_space; /* colorspace of JPEG image */
  155772. /* Decompression processing parameters --- these fields must be set before
  155773. * calling jpeg_start_decompress(). Note that jpeg_read_header() initializes
  155774. * them to default values.
  155775. */
  155776. J_COLOR_SPACE out_color_space; /* colorspace for output */
  155777. unsigned int scale_num, scale_denom; /* fraction by which to scale image */
  155778. double output_gamma; /* image gamma wanted in output */
  155779. boolean buffered_image; /* TRUE=multiple output passes */
  155780. boolean raw_data_out; /* TRUE=downsampled data wanted */
  155781. J_DCT_METHOD dct_method; /* IDCT algorithm selector */
  155782. boolean do_fancy_upsampling; /* TRUE=apply fancy upsampling */
  155783. boolean do_block_smoothing; /* TRUE=apply interblock smoothing */
  155784. boolean quantize_colors; /* TRUE=colormapped output wanted */
  155785. /* the following are ignored if not quantize_colors: */
  155786. J_DITHER_MODE dither_mode; /* type of color dithering to use */
  155787. boolean two_pass_quantize; /* TRUE=use two-pass color quantization */
  155788. int desired_number_of_colors; /* max # colors to use in created colormap */
  155789. /* these are significant only in buffered-image mode: */
  155790. boolean enable_1pass_quant; /* enable future use of 1-pass quantizer */
  155791. boolean enable_external_quant;/* enable future use of external colormap */
  155792. boolean enable_2pass_quant; /* enable future use of 2-pass quantizer */
  155793. /* Description of actual output image that will be returned to application.
  155794. * These fields are computed by jpeg_start_decompress().
  155795. * You can also use jpeg_calc_output_dimensions() to determine these values
  155796. * in advance of calling jpeg_start_decompress().
  155797. */
  155798. JDIMENSION output_width; /* scaled image width */
  155799. JDIMENSION output_height; /* scaled image height */
  155800. int out_color_components; /* # of color components in out_color_space */
  155801. int output_components; /* # of color components returned */
  155802. /* output_components is 1 (a colormap index) when quantizing colors;
  155803. * otherwise it equals out_color_components.
  155804. */
  155805. int rec_outbuf_height; /* min recommended height of scanline buffer */
  155806. /* If the buffer passed to jpeg_read_scanlines() is less than this many rows
  155807. * high, space and time will be wasted due to unnecessary data copying.
  155808. * Usually rec_outbuf_height will be 1 or 2, at most 4.
  155809. */
  155810. /* When quantizing colors, the output colormap is described by these fields.
  155811. * The application can supply a colormap by setting colormap non-NULL before
  155812. * calling jpeg_start_decompress; otherwise a colormap is created during
  155813. * jpeg_start_decompress or jpeg_start_output.
  155814. * The map has out_color_components rows and actual_number_of_colors columns.
  155815. */
  155816. int actual_number_of_colors; /* number of entries in use */
  155817. JSAMPARRAY colormap; /* The color map as a 2-D pixel array */
  155818. /* State variables: these variables indicate the progress of decompression.
  155819. * The application may examine these but must not modify them.
  155820. */
  155821. /* Row index of next scanline to be read from jpeg_read_scanlines().
  155822. * Application may use this to control its processing loop, e.g.,
  155823. * "while (output_scanline < output_height)".
  155824. */
  155825. JDIMENSION output_scanline; /* 0 .. output_height-1 */
  155826. /* Current input scan number and number of iMCU rows completed in scan.
  155827. * These indicate the progress of the decompressor input side.
  155828. */
  155829. int input_scan_number; /* Number of SOS markers seen so far */
  155830. JDIMENSION input_iMCU_row; /* Number of iMCU rows completed */
  155831. /* The "output scan number" is the notional scan being displayed by the
  155832. * output side. The decompressor will not allow output scan/row number
  155833. * to get ahead of input scan/row, but it can fall arbitrarily far behind.
  155834. */
  155835. int output_scan_number; /* Nominal scan number being displayed */
  155836. JDIMENSION output_iMCU_row; /* Number of iMCU rows read */
  155837. /* Current progression status. coef_bits[c][i] indicates the precision
  155838. * with which component c's DCT coefficient i (in zigzag order) is known.
  155839. * It is -1 when no data has yet been received, otherwise it is the point
  155840. * transform (shift) value for the most recent scan of the coefficient
  155841. * (thus, 0 at completion of the progression).
  155842. * This pointer is NULL when reading a non-progressive file.
  155843. */
  155844. int (*coef_bits)[DCTSIZE2]; /* -1 or current Al value for each coef */
  155845. /* Internal JPEG parameters --- the application usually need not look at
  155846. * these fields. Note that the decompressor output side may not use
  155847. * any parameters that can change between scans.
  155848. */
  155849. /* Quantization and Huffman tables are carried forward across input
  155850. * datastreams when processing abbreviated JPEG datastreams.
  155851. */
  155852. JQUANT_TBL * quant_tbl_ptrs[NUM_QUANT_TBLS];
  155853. /* ptrs to coefficient quantization tables, or NULL if not defined */
  155854. JHUFF_TBL * dc_huff_tbl_ptrs[NUM_HUFF_TBLS];
  155855. JHUFF_TBL * ac_huff_tbl_ptrs[NUM_HUFF_TBLS];
  155856. /* ptrs to Huffman coding tables, or NULL if not defined */
  155857. /* These parameters are never carried across datastreams, since they
  155858. * are given in SOF/SOS markers or defined to be reset by SOI.
  155859. */
  155860. int data_precision; /* bits of precision in image data */
  155861. jpeg_component_info * comp_info;
  155862. /* comp_info[i] describes component that appears i'th in SOF */
  155863. boolean progressive_mode; /* TRUE if SOFn specifies progressive mode */
  155864. boolean arith_code; /* TRUE=arithmetic coding, FALSE=Huffman */
  155865. UINT8 arith_dc_L[NUM_ARITH_TBLS]; /* L values for DC arith-coding tables */
  155866. UINT8 arith_dc_U[NUM_ARITH_TBLS]; /* U values for DC arith-coding tables */
  155867. UINT8 arith_ac_K[NUM_ARITH_TBLS]; /* Kx values for AC arith-coding tables */
  155868. unsigned int restart_interval; /* MCUs per restart interval, or 0 for no restart */
  155869. /* These fields record data obtained from optional markers recognized by
  155870. * the JPEG library.
  155871. */
  155872. boolean saw_JFIF_marker; /* TRUE iff a JFIF APP0 marker was found */
  155873. /* Data copied from JFIF marker; only valid if saw_JFIF_marker is TRUE: */
  155874. UINT8 JFIF_major_version; /* JFIF version number */
  155875. UINT8 JFIF_minor_version;
  155876. UINT8 density_unit; /* JFIF code for pixel size units */
  155877. UINT16 X_density; /* Horizontal pixel density */
  155878. UINT16 Y_density; /* Vertical pixel density */
  155879. boolean saw_Adobe_marker; /* TRUE iff an Adobe APP14 marker was found */
  155880. UINT8 Adobe_transform; /* Color transform code from Adobe marker */
  155881. boolean CCIR601_sampling; /* TRUE=first samples are cosited */
  155882. /* Aside from the specific data retained from APPn markers known to the
  155883. * library, the uninterpreted contents of any or all APPn and COM markers
  155884. * can be saved in a list for examination by the application.
  155885. */
  155886. jpeg_saved_marker_ptr marker_list; /* Head of list of saved markers */
  155887. /* Remaining fields are known throughout decompressor, but generally
  155888. * should not be touched by a surrounding application.
  155889. */
  155890. /*
  155891. * These fields are computed during decompression startup
  155892. */
  155893. int max_h_samp_factor; /* largest h_samp_factor */
  155894. int max_v_samp_factor; /* largest v_samp_factor */
  155895. int min_DCT_scaled_size; /* smallest DCT_scaled_size of any component */
  155896. JDIMENSION total_iMCU_rows; /* # of iMCU rows in image */
  155897. /* The coefficient controller's input and output progress is measured in
  155898. * units of "iMCU" (interleaved MCU) rows. These are the same as MCU rows
  155899. * in fully interleaved JPEG scans, but are used whether the scan is
  155900. * interleaved or not. We define an iMCU row as v_samp_factor DCT block
  155901. * rows of each component. Therefore, the IDCT output contains
  155902. * v_samp_factor*DCT_scaled_size sample rows of a component per iMCU row.
  155903. */
  155904. JSAMPLE * sample_range_limit; /* table for fast range-limiting */
  155905. /*
  155906. * These fields are valid during any one scan.
  155907. * They describe the components and MCUs actually appearing in the scan.
  155908. * Note that the decompressor output side must not use these fields.
  155909. */
  155910. int comps_in_scan; /* # of JPEG components in this scan */
  155911. jpeg_component_info * cur_comp_info[MAX_COMPS_IN_SCAN];
  155912. /* *cur_comp_info[i] describes component that appears i'th in SOS */
  155913. JDIMENSION MCUs_per_row; /* # of MCUs across the image */
  155914. JDIMENSION MCU_rows_in_scan; /* # of MCU rows in the image */
  155915. int blocks_in_MCU; /* # of DCT blocks per MCU */
  155916. int MCU_membership[D_MAX_BLOCKS_IN_MCU];
  155917. /* MCU_membership[i] is index in cur_comp_info of component owning */
  155918. /* i'th block in an MCU */
  155919. int Ss, Se, Ah, Al; /* progressive JPEG parameters for scan */
  155920. /* This field is shared between entropy decoder and marker parser.
  155921. * It is either zero or the code of a JPEG marker that has been
  155922. * read from the data source, but has not yet been processed.
  155923. */
  155924. int unread_marker;
  155925. /*
  155926. * Links to decompression subobjects (methods, private variables of modules)
  155927. */
  155928. struct jpeg_decomp_master * master;
  155929. struct jpeg_d_main_controller * main;
  155930. struct jpeg_d_coef_controller * coef;
  155931. struct jpeg_d_post_controller * post;
  155932. struct jpeg_input_controller * inputctl;
  155933. struct jpeg_marker_reader * marker;
  155934. struct jpeg_entropy_decoder * entropy;
  155935. struct jpeg_inverse_dct * idct;
  155936. struct jpeg_upsampler * upsample;
  155937. struct jpeg_color_deconverter * cconvert;
  155938. struct jpeg_color_quantizer * cquantize;
  155939. };
  155940. /* "Object" declarations for JPEG modules that may be supplied or called
  155941. * directly by the surrounding application.
  155942. * As with all objects in the JPEG library, these structs only define the
  155943. * publicly visible methods and state variables of a module. Additional
  155944. * private fields may exist after the public ones.
  155945. */
  155946. /* Error handler object */
  155947. struct jpeg_error_mgr {
  155948. /* Error exit handler: does not return to caller */
  155949. JMETHOD(void, error_exit, (j_common_ptr cinfo));
  155950. /* Conditionally emit a trace or warning message */
  155951. JMETHOD(void, emit_message, (j_common_ptr cinfo, int msg_level));
  155952. /* Routine that actually outputs a trace or error message */
  155953. JMETHOD(void, output_message, (j_common_ptr cinfo));
  155954. /* Format a message string for the most recent JPEG error or message */
  155955. JMETHOD(void, format_message, (j_common_ptr cinfo, char * buffer));
  155956. #define JMSG_LENGTH_MAX 200 /* recommended size of format_message buffer */
  155957. /* Reset error state variables at start of a new image */
  155958. JMETHOD(void, reset_error_mgr, (j_common_ptr cinfo));
  155959. /* The message ID code and any parameters are saved here.
  155960. * A message can have one string parameter or up to 8 int parameters.
  155961. */
  155962. int msg_code;
  155963. #define JMSG_STR_PARM_MAX 80
  155964. union {
  155965. int i[8];
  155966. char s[JMSG_STR_PARM_MAX];
  155967. } msg_parm;
  155968. /* Standard state variables for error facility */
  155969. int trace_level; /* max msg_level that will be displayed */
  155970. /* For recoverable corrupt-data errors, we emit a warning message,
  155971. * but keep going unless emit_message chooses to abort. emit_message
  155972. * should count warnings in num_warnings. The surrounding application
  155973. * can check for bad data by seeing if num_warnings is nonzero at the
  155974. * end of processing.
  155975. */
  155976. long num_warnings; /* number of corrupt-data warnings */
  155977. /* These fields point to the table(s) of error message strings.
  155978. * An application can change the table pointer to switch to a different
  155979. * message list (typically, to change the language in which errors are
  155980. * reported). Some applications may wish to add additional error codes
  155981. * that will be handled by the JPEG library error mechanism; the second
  155982. * table pointer is used for this purpose.
  155983. *
  155984. * First table includes all errors generated by JPEG library itself.
  155985. * Error code 0 is reserved for a "no such error string" message.
  155986. */
  155987. const char * const * jpeg_message_table; /* Library errors */
  155988. int last_jpeg_message; /* Table contains strings 0..last_jpeg_message */
  155989. /* Second table can be added by application (see cjpeg/djpeg for example).
  155990. * It contains strings numbered first_addon_message..last_addon_message.
  155991. */
  155992. const char * const * addon_message_table; /* Non-library errors */
  155993. int first_addon_message; /* code for first string in addon table */
  155994. int last_addon_message; /* code for last string in addon table */
  155995. };
  155996. /* Progress monitor object */
  155997. struct jpeg_progress_mgr {
  155998. JMETHOD(void, progress_monitor, (j_common_ptr cinfo));
  155999. long pass_counter; /* work units completed in this pass */
  156000. long pass_limit; /* total number of work units in this pass */
  156001. int completed_passes; /* passes completed so far */
  156002. int total_passes; /* total number of passes expected */
  156003. };
  156004. /* Data destination object for compression */
  156005. struct jpeg_destination_mgr {
  156006. JOCTET * next_output_byte; /* => next byte to write in buffer */
  156007. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  156008. JMETHOD(void, init_destination, (j_compress_ptr cinfo));
  156009. JMETHOD(boolean, empty_output_buffer, (j_compress_ptr cinfo));
  156010. JMETHOD(void, term_destination, (j_compress_ptr cinfo));
  156011. };
  156012. /* Data source object for decompression */
  156013. struct jpeg_source_mgr {
  156014. const JOCTET * next_input_byte; /* => next byte to read from buffer */
  156015. size_t bytes_in_buffer; /* # of bytes remaining in buffer */
  156016. JMETHOD(void, init_source, (j_decompress_ptr cinfo));
  156017. JMETHOD(boolean, fill_input_buffer, (j_decompress_ptr cinfo));
  156018. JMETHOD(void, skip_input_data, (j_decompress_ptr cinfo, long num_bytes));
  156019. JMETHOD(boolean, resync_to_restart, (j_decompress_ptr cinfo, int desired));
  156020. JMETHOD(void, term_source, (j_decompress_ptr cinfo));
  156021. };
  156022. /* Memory manager object.
  156023. * Allocates "small" objects (a few K total), "large" objects (tens of K),
  156024. * and "really big" objects (virtual arrays with backing store if needed).
  156025. * The memory manager does not allow individual objects to be freed; rather,
  156026. * each created object is assigned to a pool, and whole pools can be freed
  156027. * at once. This is faster and more convenient than remembering exactly what
  156028. * to free, especially where malloc()/free() are not too speedy.
  156029. * NB: alloc routines never return NULL. They exit to error_exit if not
  156030. * successful.
  156031. */
  156032. #define JPOOL_PERMANENT 0 /* lasts until master record is destroyed */
  156033. #define JPOOL_IMAGE 1 /* lasts until done with image/datastream */
  156034. #define JPOOL_NUMPOOLS 2
  156035. typedef struct jvirt_sarray_control * jvirt_sarray_ptr;
  156036. typedef struct jvirt_barray_control * jvirt_barray_ptr;
  156037. struct jpeg_memory_mgr {
  156038. /* Method pointers */
  156039. JMETHOD(void *, alloc_small, (j_common_ptr cinfo, int pool_id,
  156040. size_t sizeofobject));
  156041. JMETHOD(void FAR *, alloc_large, (j_common_ptr cinfo, int pool_id,
  156042. size_t sizeofobject));
  156043. JMETHOD(JSAMPARRAY, alloc_sarray, (j_common_ptr cinfo, int pool_id,
  156044. JDIMENSION samplesperrow,
  156045. JDIMENSION numrows));
  156046. JMETHOD(JBLOCKARRAY, alloc_barray, (j_common_ptr cinfo, int pool_id,
  156047. JDIMENSION blocksperrow,
  156048. JDIMENSION numrows));
  156049. JMETHOD(jvirt_sarray_ptr, request_virt_sarray, (j_common_ptr cinfo,
  156050. int pool_id,
  156051. boolean pre_zero,
  156052. JDIMENSION samplesperrow,
  156053. JDIMENSION numrows,
  156054. JDIMENSION maxaccess));
  156055. JMETHOD(jvirt_barray_ptr, request_virt_barray, (j_common_ptr cinfo,
  156056. int pool_id,
  156057. boolean pre_zero,
  156058. JDIMENSION blocksperrow,
  156059. JDIMENSION numrows,
  156060. JDIMENSION maxaccess));
  156061. JMETHOD(void, realize_virt_arrays, (j_common_ptr cinfo));
  156062. JMETHOD(JSAMPARRAY, access_virt_sarray, (j_common_ptr cinfo,
  156063. jvirt_sarray_ptr ptr,
  156064. JDIMENSION start_row,
  156065. JDIMENSION num_rows,
  156066. boolean writable));
  156067. JMETHOD(JBLOCKARRAY, access_virt_barray, (j_common_ptr cinfo,
  156068. jvirt_barray_ptr ptr,
  156069. JDIMENSION start_row,
  156070. JDIMENSION num_rows,
  156071. boolean writable));
  156072. JMETHOD(void, free_pool, (j_common_ptr cinfo, int pool_id));
  156073. JMETHOD(void, self_destruct, (j_common_ptr cinfo));
  156074. /* Limit on memory allocation for this JPEG object. (Note that this is
  156075. * merely advisory, not a guaranteed maximum; it only affects the space
  156076. * used for virtual-array buffers.) May be changed by outer application
  156077. * after creating the JPEG object.
  156078. */
  156079. long max_memory_to_use;
  156080. /* Maximum allocation request accepted by alloc_large. */
  156081. long max_alloc_chunk;
  156082. };
  156083. /* Routine signature for application-supplied marker processing methods.
  156084. * Need not pass marker code since it is stored in cinfo->unread_marker.
  156085. */
  156086. typedef JMETHOD(boolean, jpeg_marker_parser_method, (j_decompress_ptr cinfo));
  156087. /* Declarations for routines called by application.
  156088. * The JPP macro hides prototype parameters from compilers that can't cope.
  156089. * Note JPP requires double parentheses.
  156090. */
  156091. #ifdef HAVE_PROTOTYPES
  156092. #define JPP(arglist) arglist
  156093. #else
  156094. #define JPP(arglist) ()
  156095. #endif
  156096. /* Short forms of external names for systems with brain-damaged linkers.
  156097. * We shorten external names to be unique in the first six letters, which
  156098. * is good enough for all known systems.
  156099. * (If your compiler itself needs names to be unique in less than 15
  156100. * characters, you are out of luck. Get a better compiler.)
  156101. */
  156102. #ifdef NEED_SHORT_EXTERNAL_NAMES
  156103. #define jpeg_std_error jStdError
  156104. #define jpeg_CreateCompress jCreaCompress
  156105. #define jpeg_CreateDecompress jCreaDecompress
  156106. #define jpeg_destroy_compress jDestCompress
  156107. #define jpeg_destroy_decompress jDestDecompress
  156108. #define jpeg_stdio_dest jStdDest
  156109. #define jpeg_stdio_src jStdSrc
  156110. #define jpeg_set_defaults jSetDefaults
  156111. #define jpeg_set_colorspace jSetColorspace
  156112. #define jpeg_default_colorspace jDefColorspace
  156113. #define jpeg_set_quality jSetQuality
  156114. #define jpeg_set_linear_quality jSetLQuality
  156115. #define jpeg_add_quant_table jAddQuantTable
  156116. #define jpeg_quality_scaling jQualityScaling
  156117. #define jpeg_simple_progression jSimProgress
  156118. #define jpeg_suppress_tables jSuppressTables
  156119. #define jpeg_alloc_quant_table jAlcQTable
  156120. #define jpeg_alloc_huff_table jAlcHTable
  156121. #define jpeg_start_compress jStrtCompress
  156122. #define jpeg_write_scanlines jWrtScanlines
  156123. #define jpeg_finish_compress jFinCompress
  156124. #define jpeg_write_raw_data jWrtRawData
  156125. #define jpeg_write_marker jWrtMarker
  156126. #define jpeg_write_m_header jWrtMHeader
  156127. #define jpeg_write_m_byte jWrtMByte
  156128. #define jpeg_write_tables jWrtTables
  156129. #define jpeg_read_header jReadHeader
  156130. #define jpeg_start_decompress jStrtDecompress
  156131. #define jpeg_read_scanlines jReadScanlines
  156132. #define jpeg_finish_decompress jFinDecompress
  156133. #define jpeg_read_raw_data jReadRawData
  156134. #define jpeg_has_multiple_scans jHasMultScn
  156135. #define jpeg_start_output jStrtOutput
  156136. #define jpeg_finish_output jFinOutput
  156137. #define jpeg_input_complete jInComplete
  156138. #define jpeg_new_colormap jNewCMap
  156139. #define jpeg_consume_input jConsumeInput
  156140. #define jpeg_calc_output_dimensions jCalcDimensions
  156141. #define jpeg_save_markers jSaveMarkers
  156142. #define jpeg_set_marker_processor jSetMarker
  156143. #define jpeg_read_coefficients jReadCoefs
  156144. #define jpeg_write_coefficients jWrtCoefs
  156145. #define jpeg_copy_critical_parameters jCopyCrit
  156146. #define jpeg_abort_compress jAbrtCompress
  156147. #define jpeg_abort_decompress jAbrtDecompress
  156148. #define jpeg_abort jAbort
  156149. #define jpeg_destroy jDestroy
  156150. #define jpeg_resync_to_restart jResyncRestart
  156151. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  156152. /* Default error-management setup */
  156153. EXTERN(struct jpeg_error_mgr *) jpeg_std_error
  156154. JPP((struct jpeg_error_mgr * err));
  156155. /* Initialization of JPEG compression objects.
  156156. * jpeg_create_compress() and jpeg_create_decompress() are the exported
  156157. * names that applications should call. These expand to calls on
  156158. * jpeg_CreateCompress and jpeg_CreateDecompress with additional information
  156159. * passed for version mismatch checking.
  156160. * NB: you must set up the error-manager BEFORE calling jpeg_create_xxx.
  156161. */
  156162. #define jpeg_create_compress(cinfo) \
  156163. jpeg_CreateCompress((cinfo), JPEG_LIB_VERSION, \
  156164. (size_t) sizeof(struct jpeg_compress_struct))
  156165. #define jpeg_create_decompress(cinfo) \
  156166. jpeg_CreateDecompress((cinfo), JPEG_LIB_VERSION, \
  156167. (size_t) sizeof(struct jpeg_decompress_struct))
  156168. EXTERN(void) jpeg_CreateCompress JPP((j_compress_ptr cinfo,
  156169. int version, size_t structsize));
  156170. EXTERN(void) jpeg_CreateDecompress JPP((j_decompress_ptr cinfo,
  156171. int version, size_t structsize));
  156172. /* Destruction of JPEG compression objects */
  156173. EXTERN(void) jpeg_destroy_compress JPP((j_compress_ptr cinfo));
  156174. EXTERN(void) jpeg_destroy_decompress JPP((j_decompress_ptr cinfo));
  156175. /* Standard data source and destination managers: stdio streams. */
  156176. /* Caller is responsible for opening the file before and closing after. */
  156177. EXTERN(void) jpeg_stdio_dest JPP((j_compress_ptr cinfo, FILE * outfile));
  156178. EXTERN(void) jpeg_stdio_src JPP((j_decompress_ptr cinfo, FILE * infile));
  156179. /* Default parameter setup for compression */
  156180. EXTERN(void) jpeg_set_defaults JPP((j_compress_ptr cinfo));
  156181. /* Compression parameter setup aids */
  156182. EXTERN(void) jpeg_set_colorspace JPP((j_compress_ptr cinfo,
  156183. J_COLOR_SPACE colorspace));
  156184. EXTERN(void) jpeg_default_colorspace JPP((j_compress_ptr cinfo));
  156185. EXTERN(void) jpeg_set_quality JPP((j_compress_ptr cinfo, int quality,
  156186. boolean force_baseline));
  156187. EXTERN(void) jpeg_set_linear_quality JPP((j_compress_ptr cinfo,
  156188. int scale_factor,
  156189. boolean force_baseline));
  156190. EXTERN(void) jpeg_add_quant_table JPP((j_compress_ptr cinfo, int which_tbl,
  156191. const unsigned int *basic_table,
  156192. int scale_factor,
  156193. boolean force_baseline));
  156194. EXTERN(int) jpeg_quality_scaling JPP((int quality));
  156195. EXTERN(void) jpeg_simple_progression JPP((j_compress_ptr cinfo));
  156196. EXTERN(void) jpeg_suppress_tables JPP((j_compress_ptr cinfo,
  156197. boolean suppress));
  156198. EXTERN(JQUANT_TBL *) jpeg_alloc_quant_table JPP((j_common_ptr cinfo));
  156199. EXTERN(JHUFF_TBL *) jpeg_alloc_huff_table JPP((j_common_ptr cinfo));
  156200. /* Main entry points for compression */
  156201. EXTERN(void) jpeg_start_compress JPP((j_compress_ptr cinfo,
  156202. boolean write_all_tables));
  156203. EXTERN(JDIMENSION) jpeg_write_scanlines JPP((j_compress_ptr cinfo,
  156204. JSAMPARRAY scanlines,
  156205. JDIMENSION num_lines));
  156206. EXTERN(void) jpeg_finish_compress JPP((j_compress_ptr cinfo));
  156207. /* Replaces jpeg_write_scanlines when writing raw downsampled data. */
  156208. EXTERN(JDIMENSION) jpeg_write_raw_data JPP((j_compress_ptr cinfo,
  156209. JSAMPIMAGE data,
  156210. JDIMENSION num_lines));
  156211. /* Write a special marker. See libjpeg.doc concerning safe usage. */
  156212. EXTERN(void) jpeg_write_marker
  156213. JPP((j_compress_ptr cinfo, int marker,
  156214. const JOCTET * dataptr, unsigned int datalen));
  156215. /* Same, but piecemeal. */
  156216. EXTERN(void) jpeg_write_m_header
  156217. JPP((j_compress_ptr cinfo, int marker, unsigned int datalen));
  156218. EXTERN(void) jpeg_write_m_byte
  156219. JPP((j_compress_ptr cinfo, int val));
  156220. /* Alternate compression function: just write an abbreviated table file */
  156221. EXTERN(void) jpeg_write_tables JPP((j_compress_ptr cinfo));
  156222. /* Decompression startup: read start of JPEG datastream to see what's there */
  156223. EXTERN(int) jpeg_read_header JPP((j_decompress_ptr cinfo,
  156224. boolean require_image));
  156225. /* Return value is one of: */
  156226. #define JPEG_SUSPENDED 0 /* Suspended due to lack of input data */
  156227. #define JPEG_HEADER_OK 1 /* Found valid image datastream */
  156228. #define JPEG_HEADER_TABLES_ONLY 2 /* Found valid table-specs-only datastream */
  156229. /* If you pass require_image = TRUE (normal case), you need not check for
  156230. * a TABLES_ONLY return code; an abbreviated file will cause an error exit.
  156231. * JPEG_SUSPENDED is only possible if you use a data source module that can
  156232. * give a suspension return (the stdio source module doesn't).
  156233. */
  156234. /* Main entry points for decompression */
  156235. EXTERN(boolean) jpeg_start_decompress JPP((j_decompress_ptr cinfo));
  156236. EXTERN(JDIMENSION) jpeg_read_scanlines JPP((j_decompress_ptr cinfo,
  156237. JSAMPARRAY scanlines,
  156238. JDIMENSION max_lines));
  156239. EXTERN(boolean) jpeg_finish_decompress JPP((j_decompress_ptr cinfo));
  156240. /* Replaces jpeg_read_scanlines when reading raw downsampled data. */
  156241. EXTERN(JDIMENSION) jpeg_read_raw_data JPP((j_decompress_ptr cinfo,
  156242. JSAMPIMAGE data,
  156243. JDIMENSION max_lines));
  156244. /* Additional entry points for buffered-image mode. */
  156245. EXTERN(boolean) jpeg_has_multiple_scans JPP((j_decompress_ptr cinfo));
  156246. EXTERN(boolean) jpeg_start_output JPP((j_decompress_ptr cinfo,
  156247. int scan_number));
  156248. EXTERN(boolean) jpeg_finish_output JPP((j_decompress_ptr cinfo));
  156249. EXTERN(boolean) jpeg_input_complete JPP((j_decompress_ptr cinfo));
  156250. EXTERN(void) jpeg_new_colormap JPP((j_decompress_ptr cinfo));
  156251. EXTERN(int) jpeg_consume_input JPP((j_decompress_ptr cinfo));
  156252. /* Return value is one of: */
  156253. /* #define JPEG_SUSPENDED 0 Suspended due to lack of input data */
  156254. #define JPEG_REACHED_SOS 1 /* Reached start of new scan */
  156255. #define JPEG_REACHED_EOI 2 /* Reached end of image */
  156256. #define JPEG_ROW_COMPLETED 3 /* Completed one iMCU row */
  156257. #define JPEG_SCAN_COMPLETED 4 /* Completed last iMCU row of a scan */
  156258. /* Precalculate output dimensions for current decompression parameters. */
  156259. EXTERN(void) jpeg_calc_output_dimensions JPP((j_decompress_ptr cinfo));
  156260. /* Control saving of COM and APPn markers into marker_list. */
  156261. EXTERN(void) jpeg_save_markers
  156262. JPP((j_decompress_ptr cinfo, int marker_code,
  156263. unsigned int length_limit));
  156264. /* Install a special processing method for COM or APPn markers. */
  156265. EXTERN(void) jpeg_set_marker_processor
  156266. JPP((j_decompress_ptr cinfo, int marker_code,
  156267. jpeg_marker_parser_method routine));
  156268. /* Read or write raw DCT coefficients --- useful for lossless transcoding. */
  156269. EXTERN(jvirt_barray_ptr *) jpeg_read_coefficients JPP((j_decompress_ptr cinfo));
  156270. EXTERN(void) jpeg_write_coefficients JPP((j_compress_ptr cinfo,
  156271. jvirt_barray_ptr * coef_arrays));
  156272. EXTERN(void) jpeg_copy_critical_parameters JPP((j_decompress_ptr srcinfo,
  156273. j_compress_ptr dstinfo));
  156274. /* If you choose to abort compression or decompression before completing
  156275. * jpeg_finish_(de)compress, then you need to clean up to release memory,
  156276. * temporary files, etc. You can just call jpeg_destroy_(de)compress
  156277. * if you're done with the JPEG object, but if you want to clean it up and
  156278. * reuse it, call this:
  156279. */
  156280. EXTERN(void) jpeg_abort_compress JPP((j_compress_ptr cinfo));
  156281. EXTERN(void) jpeg_abort_decompress JPP((j_decompress_ptr cinfo));
  156282. /* Generic versions of jpeg_abort and jpeg_destroy that work on either
  156283. * flavor of JPEG object. These may be more convenient in some places.
  156284. */
  156285. EXTERN(void) jpeg_abort JPP((j_common_ptr cinfo));
  156286. EXTERN(void) jpeg_destroy JPP((j_common_ptr cinfo));
  156287. /* Default restart-marker-resync procedure for use by data source modules */
  156288. EXTERN(boolean) jpeg_resync_to_restart JPP((j_decompress_ptr cinfo,
  156289. int desired));
  156290. /* These marker codes are exported since applications and data source modules
  156291. * are likely to want to use them.
  156292. */
  156293. #define JPEG_RST0 0xD0 /* RST0 marker code */
  156294. #define JPEG_EOI 0xD9 /* EOI marker code */
  156295. #define JPEG_APP0 0xE0 /* APP0 marker code */
  156296. #define JPEG_COM 0xFE /* COM marker code */
  156297. /* If we have a brain-damaged compiler that emits warnings (or worse, errors)
  156298. * for structure definitions that are never filled in, keep it quiet by
  156299. * supplying dummy definitions for the various substructures.
  156300. */
  156301. #ifdef INCOMPLETE_TYPES_BROKEN
  156302. #ifndef JPEG_INTERNALS /* will be defined in jpegint.h */
  156303. struct jvirt_sarray_control { long dummy; };
  156304. struct jvirt_barray_control { long dummy; };
  156305. struct jpeg_comp_master { long dummy; };
  156306. struct jpeg_c_main_controller { long dummy; };
  156307. struct jpeg_c_prep_controller { long dummy; };
  156308. struct jpeg_c_coef_controller { long dummy; };
  156309. struct jpeg_marker_writer { long dummy; };
  156310. struct jpeg_color_converter { long dummy; };
  156311. struct jpeg_downsampler { long dummy; };
  156312. struct jpeg_forward_dct { long dummy; };
  156313. struct jpeg_entropy_encoder { long dummy; };
  156314. struct jpeg_decomp_master { long dummy; };
  156315. struct jpeg_d_main_controller { long dummy; };
  156316. struct jpeg_d_coef_controller { long dummy; };
  156317. struct jpeg_d_post_controller { long dummy; };
  156318. struct jpeg_input_controller { long dummy; };
  156319. struct jpeg_marker_reader { long dummy; };
  156320. struct jpeg_entropy_decoder { long dummy; };
  156321. struct jpeg_inverse_dct { long dummy; };
  156322. struct jpeg_upsampler { long dummy; };
  156323. struct jpeg_color_deconverter { long dummy; };
  156324. struct jpeg_color_quantizer { long dummy; };
  156325. #endif /* JPEG_INTERNALS */
  156326. #endif /* INCOMPLETE_TYPES_BROKEN */
  156327. /*
  156328. * The JPEG library modules define JPEG_INTERNALS before including this file.
  156329. * The internal structure declarations are read only when that is true.
  156330. * Applications using the library should not include jpegint.h, but may wish
  156331. * to include jerror.h.
  156332. */
  156333. #ifdef JPEG_INTERNALS
  156334. /********* Start of inlined file: jpegint.h *********/
  156335. /* Declarations for both compression & decompression */
  156336. typedef enum { /* Operating modes for buffer controllers */
  156337. JBUF_PASS_THRU, /* Plain stripwise operation */
  156338. /* Remaining modes require a full-image buffer to have been created */
  156339. JBUF_SAVE_SOURCE, /* Run source subobject only, save output */
  156340. JBUF_CRANK_DEST, /* Run dest subobject only, using saved data */
  156341. JBUF_SAVE_AND_PASS /* Run both subobjects, save output */
  156342. } J_BUF_MODE;
  156343. /* Values of global_state field (jdapi.c has some dependencies on ordering!) */
  156344. #define CSTATE_START 100 /* after create_compress */
  156345. #define CSTATE_SCANNING 101 /* start_compress done, write_scanlines OK */
  156346. #define CSTATE_RAW_OK 102 /* start_compress done, write_raw_data OK */
  156347. #define CSTATE_WRCOEFS 103 /* jpeg_write_coefficients done */
  156348. #define DSTATE_START 200 /* after create_decompress */
  156349. #define DSTATE_INHEADER 201 /* reading header markers, no SOS yet */
  156350. #define DSTATE_READY 202 /* found SOS, ready for start_decompress */
  156351. #define DSTATE_PRELOAD 203 /* reading multiscan file in start_decompress*/
  156352. #define DSTATE_PRESCAN 204 /* performing dummy pass for 2-pass quant */
  156353. #define DSTATE_SCANNING 205 /* start_decompress done, read_scanlines OK */
  156354. #define DSTATE_RAW_OK 206 /* start_decompress done, read_raw_data OK */
  156355. #define DSTATE_BUFIMAGE 207 /* expecting jpeg_start_output */
  156356. #define DSTATE_BUFPOST 208 /* looking for SOS/EOI in jpeg_finish_output */
  156357. #define DSTATE_RDCOEFS 209 /* reading file in jpeg_read_coefficients */
  156358. #define DSTATE_STOPPING 210 /* looking for EOI in jpeg_finish_decompress */
  156359. /* Declarations for compression modules */
  156360. /* Master control module */
  156361. struct jpeg_comp_master {
  156362. JMETHOD(void, prepare_for_pass, (j_compress_ptr cinfo));
  156363. JMETHOD(void, pass_startup, (j_compress_ptr cinfo));
  156364. JMETHOD(void, finish_pass, (j_compress_ptr cinfo));
  156365. /* State variables made visible to other modules */
  156366. boolean call_pass_startup; /* True if pass_startup must be called */
  156367. boolean is_last_pass; /* True during last pass */
  156368. };
  156369. /* Main buffer control (downsampled-data buffer) */
  156370. struct jpeg_c_main_controller {
  156371. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  156372. JMETHOD(void, process_data, (j_compress_ptr cinfo,
  156373. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  156374. JDIMENSION in_rows_avail));
  156375. };
  156376. /* Compression preprocessing (downsampling input buffer control) */
  156377. struct jpeg_c_prep_controller {
  156378. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  156379. JMETHOD(void, pre_process_data, (j_compress_ptr cinfo,
  156380. JSAMPARRAY input_buf,
  156381. JDIMENSION *in_row_ctr,
  156382. JDIMENSION in_rows_avail,
  156383. JSAMPIMAGE output_buf,
  156384. JDIMENSION *out_row_group_ctr,
  156385. JDIMENSION out_row_groups_avail));
  156386. };
  156387. /* Coefficient buffer control */
  156388. struct jpeg_c_coef_controller {
  156389. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  156390. JMETHOD(boolean, compress_data, (j_compress_ptr cinfo,
  156391. JSAMPIMAGE input_buf));
  156392. };
  156393. /* Colorspace conversion */
  156394. struct jpeg_color_converter {
  156395. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  156396. JMETHOD(void, color_convert, (j_compress_ptr cinfo,
  156397. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  156398. JDIMENSION output_row, int num_rows));
  156399. };
  156400. /* Downsampling */
  156401. struct jpeg_downsampler {
  156402. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  156403. JMETHOD(void, downsample, (j_compress_ptr cinfo,
  156404. JSAMPIMAGE input_buf, JDIMENSION in_row_index,
  156405. JSAMPIMAGE output_buf,
  156406. JDIMENSION out_row_group_index));
  156407. boolean need_context_rows; /* TRUE if need rows above & below */
  156408. };
  156409. /* Forward DCT (also controls coefficient quantization) */
  156410. struct jpeg_forward_dct {
  156411. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  156412. /* perhaps this should be an array??? */
  156413. JMETHOD(void, forward_DCT, (j_compress_ptr cinfo,
  156414. jpeg_component_info * compptr,
  156415. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  156416. JDIMENSION start_row, JDIMENSION start_col,
  156417. JDIMENSION num_blocks));
  156418. };
  156419. /* Entropy encoding */
  156420. struct jpeg_entropy_encoder {
  156421. JMETHOD(void, start_pass, (j_compress_ptr cinfo, boolean gather_statistics));
  156422. JMETHOD(boolean, encode_mcu, (j_compress_ptr cinfo, JBLOCKROW *MCU_data));
  156423. JMETHOD(void, finish_pass, (j_compress_ptr cinfo));
  156424. };
  156425. /* Marker writing */
  156426. struct jpeg_marker_writer {
  156427. JMETHOD(void, write_file_header, (j_compress_ptr cinfo));
  156428. JMETHOD(void, write_frame_header, (j_compress_ptr cinfo));
  156429. JMETHOD(void, write_scan_header, (j_compress_ptr cinfo));
  156430. JMETHOD(void, write_file_trailer, (j_compress_ptr cinfo));
  156431. JMETHOD(void, write_tables_only, (j_compress_ptr cinfo));
  156432. /* These routines are exported to allow insertion of extra markers */
  156433. /* Probably only COM and APPn markers should be written this way */
  156434. JMETHOD(void, write_marker_header, (j_compress_ptr cinfo, int marker,
  156435. unsigned int datalen));
  156436. JMETHOD(void, write_marker_byte, (j_compress_ptr cinfo, int val));
  156437. };
  156438. /* Declarations for decompression modules */
  156439. /* Master control module */
  156440. struct jpeg_decomp_master {
  156441. JMETHOD(void, prepare_for_output_pass, (j_decompress_ptr cinfo));
  156442. JMETHOD(void, finish_output_pass, (j_decompress_ptr cinfo));
  156443. /* State variables made visible to other modules */
  156444. boolean is_dummy_pass; /* True during 1st pass for 2-pass quant */
  156445. };
  156446. /* Input control module */
  156447. struct jpeg_input_controller {
  156448. JMETHOD(int, consume_input, (j_decompress_ptr cinfo));
  156449. JMETHOD(void, reset_input_controller, (j_decompress_ptr cinfo));
  156450. JMETHOD(void, start_input_pass, (j_decompress_ptr cinfo));
  156451. JMETHOD(void, finish_input_pass, (j_decompress_ptr cinfo));
  156452. /* State variables made visible to other modules */
  156453. boolean has_multiple_scans; /* True if file has multiple scans */
  156454. boolean eoi_reached; /* True when EOI has been consumed */
  156455. };
  156456. /* Main buffer control (downsampled-data buffer) */
  156457. struct jpeg_d_main_controller {
  156458. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, J_BUF_MODE pass_mode));
  156459. JMETHOD(void, process_data, (j_decompress_ptr cinfo,
  156460. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  156461. JDIMENSION out_rows_avail));
  156462. };
  156463. /* Coefficient buffer control */
  156464. struct jpeg_d_coef_controller {
  156465. JMETHOD(void, start_input_pass, (j_decompress_ptr cinfo));
  156466. JMETHOD(int, consume_data, (j_decompress_ptr cinfo));
  156467. JMETHOD(void, start_output_pass, (j_decompress_ptr cinfo));
  156468. JMETHOD(int, decompress_data, (j_decompress_ptr cinfo,
  156469. JSAMPIMAGE output_buf));
  156470. /* Pointer to array of coefficient virtual arrays, or NULL if none */
  156471. jvirt_barray_ptr *coef_arrays;
  156472. };
  156473. /* Decompression postprocessing (color quantization buffer control) */
  156474. struct jpeg_d_post_controller {
  156475. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, J_BUF_MODE pass_mode));
  156476. JMETHOD(void, post_process_data, (j_decompress_ptr cinfo,
  156477. JSAMPIMAGE input_buf,
  156478. JDIMENSION *in_row_group_ctr,
  156479. JDIMENSION in_row_groups_avail,
  156480. JSAMPARRAY output_buf,
  156481. JDIMENSION *out_row_ctr,
  156482. JDIMENSION out_rows_avail));
  156483. };
  156484. /* Marker reading & parsing */
  156485. struct jpeg_marker_reader {
  156486. JMETHOD(void, reset_marker_reader, (j_decompress_ptr cinfo));
  156487. /* Read markers until SOS or EOI.
  156488. * Returns same codes as are defined for jpeg_consume_input:
  156489. * JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  156490. */
  156491. JMETHOD(int, read_markers, (j_decompress_ptr cinfo));
  156492. /* Read a restart marker --- exported for use by entropy decoder only */
  156493. jpeg_marker_parser_method read_restart_marker;
  156494. /* State of marker reader --- nominally internal, but applications
  156495. * supplying COM or APPn handlers might like to know the state.
  156496. */
  156497. boolean saw_SOI; /* found SOI? */
  156498. boolean saw_SOF; /* found SOF? */
  156499. int next_restart_num; /* next restart number expected (0-7) */
  156500. unsigned int discarded_bytes; /* # of bytes skipped looking for a marker */
  156501. };
  156502. /* Entropy decoding */
  156503. struct jpeg_entropy_decoder {
  156504. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  156505. JMETHOD(boolean, decode_mcu, (j_decompress_ptr cinfo,
  156506. JBLOCKROW *MCU_data));
  156507. /* This is here to share code between baseline and progressive decoders; */
  156508. /* other modules probably should not use it */
  156509. boolean insufficient_data; /* set TRUE after emitting warning */
  156510. };
  156511. /* Inverse DCT (also performs dequantization) */
  156512. typedef JMETHOD(void, inverse_DCT_method_ptr,
  156513. (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  156514. JCOEFPTR coef_block,
  156515. JSAMPARRAY output_buf, JDIMENSION output_col));
  156516. struct jpeg_inverse_dct {
  156517. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  156518. /* It is useful to allow each component to have a separate IDCT method. */
  156519. inverse_DCT_method_ptr inverse_DCT[MAX_COMPONENTS];
  156520. };
  156521. /* Upsampling (note that upsampler must also call color converter) */
  156522. struct jpeg_upsampler {
  156523. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  156524. JMETHOD(void, upsample, (j_decompress_ptr cinfo,
  156525. JSAMPIMAGE input_buf,
  156526. JDIMENSION *in_row_group_ctr,
  156527. JDIMENSION in_row_groups_avail,
  156528. JSAMPARRAY output_buf,
  156529. JDIMENSION *out_row_ctr,
  156530. JDIMENSION out_rows_avail));
  156531. boolean need_context_rows; /* TRUE if need rows above & below */
  156532. };
  156533. /* Colorspace conversion */
  156534. struct jpeg_color_deconverter {
  156535. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  156536. JMETHOD(void, color_convert, (j_decompress_ptr cinfo,
  156537. JSAMPIMAGE input_buf, JDIMENSION input_row,
  156538. JSAMPARRAY output_buf, int num_rows));
  156539. };
  156540. /* Color quantization or color precision reduction */
  156541. struct jpeg_color_quantizer {
  156542. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, boolean is_pre_scan));
  156543. JMETHOD(void, color_quantize, (j_decompress_ptr cinfo,
  156544. JSAMPARRAY input_buf, JSAMPARRAY output_buf,
  156545. int num_rows));
  156546. JMETHOD(void, finish_pass, (j_decompress_ptr cinfo));
  156547. JMETHOD(void, new_color_map, (j_decompress_ptr cinfo));
  156548. };
  156549. /* Miscellaneous useful macros */
  156550. #undef MAX
  156551. #define MAX(a,b) ((a) > (b) ? (a) : (b))
  156552. #undef MIN
  156553. #define MIN(a,b) ((a) < (b) ? (a) : (b))
  156554. /* We assume that right shift corresponds to signed division by 2 with
  156555. * rounding towards minus infinity. This is correct for typical "arithmetic
  156556. * shift" instructions that shift in copies of the sign bit. But some
  156557. * C compilers implement >> with an unsigned shift. For these machines you
  156558. * must define RIGHT_SHIFT_IS_UNSIGNED.
  156559. * RIGHT_SHIFT provides a proper signed right shift of an INT32 quantity.
  156560. * It is only applied with constant shift counts. SHIFT_TEMPS must be
  156561. * included in the variables of any routine using RIGHT_SHIFT.
  156562. */
  156563. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  156564. #define SHIFT_TEMPS INT32 shift_temp;
  156565. #define RIGHT_SHIFT(x,shft) \
  156566. ((shift_temp = (x)) < 0 ? \
  156567. (shift_temp >> (shft)) | ((~((INT32) 0)) << (32-(shft))) : \
  156568. (shift_temp >> (shft)))
  156569. #else
  156570. #define SHIFT_TEMPS
  156571. #define RIGHT_SHIFT(x,shft) ((x) >> (shft))
  156572. #endif
  156573. /* Short forms of external names for systems with brain-damaged linkers. */
  156574. #ifdef NEED_SHORT_EXTERNAL_NAMES
  156575. #define jinit_compress_master jICompress
  156576. #define jinit_c_master_control jICMaster
  156577. #define jinit_c_main_controller jICMainC
  156578. #define jinit_c_prep_controller jICPrepC
  156579. #define jinit_c_coef_controller jICCoefC
  156580. #define jinit_color_converter jICColor
  156581. #define jinit_downsampler jIDownsampler
  156582. #define jinit_forward_dct jIFDCT
  156583. #define jinit_huff_encoder jIHEncoder
  156584. #define jinit_phuff_encoder jIPHEncoder
  156585. #define jinit_marker_writer jIMWriter
  156586. #define jinit_master_decompress jIDMaster
  156587. #define jinit_d_main_controller jIDMainC
  156588. #define jinit_d_coef_controller jIDCoefC
  156589. #define jinit_d_post_controller jIDPostC
  156590. #define jinit_input_controller jIInCtlr
  156591. #define jinit_marker_reader jIMReader
  156592. #define jinit_huff_decoder jIHDecoder
  156593. #define jinit_phuff_decoder jIPHDecoder
  156594. #define jinit_inverse_dct jIIDCT
  156595. #define jinit_upsampler jIUpsampler
  156596. #define jinit_color_deconverter jIDColor
  156597. #define jinit_1pass_quantizer jI1Quant
  156598. #define jinit_2pass_quantizer jI2Quant
  156599. #define jinit_merged_upsampler jIMUpsampler
  156600. #define jinit_memory_mgr jIMemMgr
  156601. #define jdiv_round_up jDivRound
  156602. #define jround_up jRound
  156603. #define jcopy_sample_rows jCopySamples
  156604. #define jcopy_block_row jCopyBlocks
  156605. #define jzero_far jZeroFar
  156606. #define jpeg_zigzag_order jZIGTable
  156607. #define jpeg_natural_order jZAGTable
  156608. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  156609. /* Compression module initialization routines */
  156610. EXTERN(void) jinit_compress_master JPP((j_compress_ptr cinfo));
  156611. EXTERN(void) jinit_c_master_control JPP((j_compress_ptr cinfo,
  156612. boolean transcode_only));
  156613. EXTERN(void) jinit_c_main_controller JPP((j_compress_ptr cinfo,
  156614. boolean need_full_buffer));
  156615. EXTERN(void) jinit_c_prep_controller JPP((j_compress_ptr cinfo,
  156616. boolean need_full_buffer));
  156617. EXTERN(void) jinit_c_coef_controller JPP((j_compress_ptr cinfo,
  156618. boolean need_full_buffer));
  156619. EXTERN(void) jinit_color_converter JPP((j_compress_ptr cinfo));
  156620. EXTERN(void) jinit_downsampler JPP((j_compress_ptr cinfo));
  156621. EXTERN(void) jinit_forward_dct JPP((j_compress_ptr cinfo));
  156622. EXTERN(void) jinit_huff_encoder JPP((j_compress_ptr cinfo));
  156623. EXTERN(void) jinit_phuff_encoder JPP((j_compress_ptr cinfo));
  156624. EXTERN(void) jinit_marker_writer JPP((j_compress_ptr cinfo));
  156625. /* Decompression module initialization routines */
  156626. EXTERN(void) jinit_master_decompress JPP((j_decompress_ptr cinfo));
  156627. EXTERN(void) jinit_d_main_controller JPP((j_decompress_ptr cinfo,
  156628. boolean need_full_buffer));
  156629. EXTERN(void) jinit_d_coef_controller JPP((j_decompress_ptr cinfo,
  156630. boolean need_full_buffer));
  156631. EXTERN(void) jinit_d_post_controller JPP((j_decompress_ptr cinfo,
  156632. boolean need_full_buffer));
  156633. EXTERN(void) jinit_input_controller JPP((j_decompress_ptr cinfo));
  156634. EXTERN(void) jinit_marker_reader JPP((j_decompress_ptr cinfo));
  156635. EXTERN(void) jinit_huff_decoder JPP((j_decompress_ptr cinfo));
  156636. EXTERN(void) jinit_phuff_decoder JPP((j_decompress_ptr cinfo));
  156637. EXTERN(void) jinit_inverse_dct JPP((j_decompress_ptr cinfo));
  156638. EXTERN(void) jinit_upsampler JPP((j_decompress_ptr cinfo));
  156639. EXTERN(void) jinit_color_deconverter JPP((j_decompress_ptr cinfo));
  156640. EXTERN(void) jinit_1pass_quantizer JPP((j_decompress_ptr cinfo));
  156641. EXTERN(void) jinit_2pass_quantizer JPP((j_decompress_ptr cinfo));
  156642. EXTERN(void) jinit_merged_upsampler JPP((j_decompress_ptr cinfo));
  156643. /* Memory manager initialization */
  156644. EXTERN(void) jinit_memory_mgr JPP((j_common_ptr cinfo));
  156645. /* Utility routines in jutils.c */
  156646. EXTERN(long) jdiv_round_up JPP((long a, long b));
  156647. EXTERN(long) jround_up JPP((long a, long b));
  156648. EXTERN(void) jcopy_sample_rows JPP((JSAMPARRAY input_array, int source_row,
  156649. JSAMPARRAY output_array, int dest_row,
  156650. int num_rows, JDIMENSION num_cols));
  156651. EXTERN(void) jcopy_block_row JPP((JBLOCKROW input_row, JBLOCKROW output_row,
  156652. JDIMENSION num_blocks));
  156653. EXTERN(void) jzero_far JPP((void FAR * target, size_t bytestozero));
  156654. /* Constant tables in jutils.c */
  156655. #if 0 /* This table is not actually needed in v6a */
  156656. extern const int jpeg_zigzag_order[]; /* natural coef order to zigzag order */
  156657. #endif
  156658. extern const int jpeg_natural_order[]; /* zigzag coef order to natural order */
  156659. /* Suppress undefined-structure complaints if necessary. */
  156660. #ifdef INCOMPLETE_TYPES_BROKEN
  156661. #ifndef AM_MEMORY_MANAGER /* only jmemmgr.c defines these */
  156662. struct jvirt_sarray_control { long dummy; };
  156663. struct jvirt_barray_control { long dummy; };
  156664. #endif
  156665. #endif /* INCOMPLETE_TYPES_BROKEN */
  156666. /********* End of inlined file: jpegint.h *********/
  156667. /* fetch private declarations */
  156668. /********* Start of inlined file: jerror.h *********/
  156669. /*
  156670. * To define the enum list of message codes, include this file without
  156671. * defining macro JMESSAGE. To create a message string table, include it
  156672. * again with a suitable JMESSAGE definition (see jerror.c for an example).
  156673. */
  156674. #ifndef JMESSAGE
  156675. #ifndef JERROR_H
  156676. /* First time through, define the enum list */
  156677. #define JMAKE_ENUM_LIST
  156678. #else
  156679. /* Repeated inclusions of this file are no-ops unless JMESSAGE is defined */
  156680. #define JMESSAGE(code,string)
  156681. #endif /* JERROR_H */
  156682. #endif /* JMESSAGE */
  156683. #ifdef JMAKE_ENUM_LIST
  156684. typedef enum {
  156685. #define JMESSAGE(code,string) code ,
  156686. #endif /* JMAKE_ENUM_LIST */
  156687. JMESSAGE(JMSG_NOMESSAGE, "Bogus message code %d") /* Must be first entry! */
  156688. /* For maintenance convenience, list is alphabetical by message code name */
  156689. JMESSAGE(JERR_ARITH_NOTIMPL,
  156690. "Sorry, there are legal restrictions on arithmetic coding")
  156691. JMESSAGE(JERR_BAD_ALIGN_TYPE, "ALIGN_TYPE is wrong, please fix")
  156692. JMESSAGE(JERR_BAD_ALLOC_CHUNK, "MAX_ALLOC_CHUNK is wrong, please fix")
  156693. JMESSAGE(JERR_BAD_BUFFER_MODE, "Bogus buffer control mode")
  156694. JMESSAGE(JERR_BAD_COMPONENT_ID, "Invalid component ID %d in SOS")
  156695. JMESSAGE(JERR_BAD_DCT_COEF, "DCT coefficient out of range")
  156696. JMESSAGE(JERR_BAD_DCTSIZE, "IDCT output block size %d not supported")
  156697. JMESSAGE(JERR_BAD_HUFF_TABLE, "Bogus Huffman table definition")
  156698. JMESSAGE(JERR_BAD_IN_COLORSPACE, "Bogus input colorspace")
  156699. JMESSAGE(JERR_BAD_J_COLORSPACE, "Bogus JPEG colorspace")
  156700. JMESSAGE(JERR_BAD_LENGTH, "Bogus marker length")
  156701. JMESSAGE(JERR_BAD_LIB_VERSION,
  156702. "Wrong JPEG library version: library is %d, caller expects %d")
  156703. JMESSAGE(JERR_BAD_MCU_SIZE, "Sampling factors too large for interleaved scan")
  156704. JMESSAGE(JERR_BAD_POOL_ID, "Invalid memory pool code %d")
  156705. JMESSAGE(JERR_BAD_PRECISION, "Unsupported JPEG data precision %d")
  156706. JMESSAGE(JERR_BAD_PROGRESSION,
  156707. "Invalid progressive parameters Ss=%d Se=%d Ah=%d Al=%d")
  156708. JMESSAGE(JERR_BAD_PROG_SCRIPT,
  156709. "Invalid progressive parameters at scan script entry %d")
  156710. JMESSAGE(JERR_BAD_SAMPLING, "Bogus sampling factors")
  156711. JMESSAGE(JERR_BAD_SCAN_SCRIPT, "Invalid scan script at entry %d")
  156712. JMESSAGE(JERR_BAD_STATE, "Improper call to JPEG library in state %d")
  156713. JMESSAGE(JERR_BAD_STRUCT_SIZE,
  156714. "JPEG parameter struct mismatch: library thinks size is %u, caller expects %u")
  156715. JMESSAGE(JERR_BAD_VIRTUAL_ACCESS, "Bogus virtual array access")
  156716. JMESSAGE(JERR_BUFFER_SIZE, "Buffer passed to JPEG library is too small")
  156717. JMESSAGE(JERR_CANT_SUSPEND, "Suspension not allowed here")
  156718. JMESSAGE(JERR_CCIR601_NOTIMPL, "CCIR601 sampling not implemented yet")
  156719. JMESSAGE(JERR_COMPONENT_COUNT, "Too many color components: %d, max %d")
  156720. JMESSAGE(JERR_CONVERSION_NOTIMPL, "Unsupported color conversion request")
  156721. JMESSAGE(JERR_DAC_INDEX, "Bogus DAC index %d")
  156722. JMESSAGE(JERR_DAC_VALUE, "Bogus DAC value 0x%x")
  156723. JMESSAGE(JERR_DHT_INDEX, "Bogus DHT index %d")
  156724. JMESSAGE(JERR_DQT_INDEX, "Bogus DQT index %d")
  156725. JMESSAGE(JERR_EMPTY_IMAGE, "Empty JPEG image (DNL not supported)")
  156726. JMESSAGE(JERR_EMS_READ, "Read from EMS failed")
  156727. JMESSAGE(JERR_EMS_WRITE, "Write to EMS failed")
  156728. JMESSAGE(JERR_EOI_EXPECTED, "Didn't expect more than one scan")
  156729. JMESSAGE(JERR_FILE_READ, "Input file read error")
  156730. JMESSAGE(JERR_FILE_WRITE, "Output file write error --- out of disk space?")
  156731. JMESSAGE(JERR_FRACT_SAMPLE_NOTIMPL, "Fractional sampling not implemented yet")
  156732. JMESSAGE(JERR_HUFF_CLEN_OVERFLOW, "Huffman code size table overflow")
  156733. JMESSAGE(JERR_HUFF_MISSING_CODE, "Missing Huffman code table entry")
  156734. JMESSAGE(JERR_IMAGE_TOO_BIG, "Maximum supported image dimension is %u pixels")
  156735. JMESSAGE(JERR_INPUT_EMPTY, "Empty input file")
  156736. JMESSAGE(JERR_INPUT_EOF, "Premature end of input file")
  156737. JMESSAGE(JERR_MISMATCHED_QUANT_TABLE,
  156738. "Cannot transcode due to multiple use of quantization table %d")
  156739. JMESSAGE(JERR_MISSING_DATA, "Scan script does not transmit all data")
  156740. JMESSAGE(JERR_MODE_CHANGE, "Invalid color quantization mode change")
  156741. JMESSAGE(JERR_NOTIMPL, "Not implemented yet")
  156742. JMESSAGE(JERR_NOT_COMPILED, "Requested feature was omitted at compile time")
  156743. JMESSAGE(JERR_NO_BACKING_STORE, "Backing store not supported")
  156744. JMESSAGE(JERR_NO_HUFF_TABLE, "Huffman table 0x%02x was not defined")
  156745. JMESSAGE(JERR_NO_IMAGE, "JPEG datastream contains no image")
  156746. JMESSAGE(JERR_NO_QUANT_TABLE, "Quantization table 0x%02x was not defined")
  156747. JMESSAGE(JERR_NO_SOI, "Not a JPEG file: starts with 0x%02x 0x%02x")
  156748. JMESSAGE(JERR_OUT_OF_MEMORY, "Insufficient memory (case %d)")
  156749. JMESSAGE(JERR_QUANT_COMPONENTS,
  156750. "Cannot quantize more than %d color components")
  156751. JMESSAGE(JERR_QUANT_FEW_COLORS, "Cannot quantize to fewer than %d colors")
  156752. JMESSAGE(JERR_QUANT_MANY_COLORS, "Cannot quantize to more than %d colors")
  156753. JMESSAGE(JERR_SOF_DUPLICATE, "Invalid JPEG file structure: two SOF markers")
  156754. JMESSAGE(JERR_SOF_NO_SOS, "Invalid JPEG file structure: missing SOS marker")
  156755. JMESSAGE(JERR_SOF_UNSUPPORTED, "Unsupported JPEG process: SOF type 0x%02x")
  156756. JMESSAGE(JERR_SOI_DUPLICATE, "Invalid JPEG file structure: two SOI markers")
  156757. JMESSAGE(JERR_SOS_NO_SOF, "Invalid JPEG file structure: SOS before SOF")
  156758. JMESSAGE(JERR_TFILE_CREATE, "Failed to create temporary file %s")
  156759. JMESSAGE(JERR_TFILE_READ, "Read failed on temporary file")
  156760. JMESSAGE(JERR_TFILE_SEEK, "Seek failed on temporary file")
  156761. JMESSAGE(JERR_TFILE_WRITE,
  156762. "Write failed on temporary file --- out of disk space?")
  156763. JMESSAGE(JERR_TOO_LITTLE_DATA, "Application transferred too few scanlines")
  156764. JMESSAGE(JERR_UNKNOWN_MARKER, "Unsupported marker type 0x%02x")
  156765. JMESSAGE(JERR_VIRTUAL_BUG, "Virtual array controller messed up")
  156766. JMESSAGE(JERR_WIDTH_OVERFLOW, "Image too wide for this implementation")
  156767. JMESSAGE(JERR_XMS_READ, "Read from XMS failed")
  156768. JMESSAGE(JERR_XMS_WRITE, "Write to XMS failed")
  156769. JMESSAGE(JMSG_COPYRIGHT, JCOPYRIGHT)
  156770. JMESSAGE(JMSG_VERSION, JVERSION)
  156771. JMESSAGE(JTRC_16BIT_TABLES,
  156772. "Caution: quantization tables are too coarse for baseline JPEG")
  156773. JMESSAGE(JTRC_ADOBE,
  156774. "Adobe APP14 marker: version %d, flags 0x%04x 0x%04x, transform %d")
  156775. JMESSAGE(JTRC_APP0, "Unknown APP0 marker (not JFIF), length %u")
  156776. JMESSAGE(JTRC_APP14, "Unknown APP14 marker (not Adobe), length %u")
  156777. JMESSAGE(JTRC_DAC, "Define Arithmetic Table 0x%02x: 0x%02x")
  156778. JMESSAGE(JTRC_DHT, "Define Huffman Table 0x%02x")
  156779. JMESSAGE(JTRC_DQT, "Define Quantization Table %d precision %d")
  156780. JMESSAGE(JTRC_DRI, "Define Restart Interval %u")
  156781. JMESSAGE(JTRC_EMS_CLOSE, "Freed EMS handle %u")
  156782. JMESSAGE(JTRC_EMS_OPEN, "Obtained EMS handle %u")
  156783. JMESSAGE(JTRC_EOI, "End Of Image")
  156784. JMESSAGE(JTRC_HUFFBITS, " %3d %3d %3d %3d %3d %3d %3d %3d")
  156785. JMESSAGE(JTRC_JFIF, "JFIF APP0 marker: version %d.%02d, density %dx%d %d")
  156786. JMESSAGE(JTRC_JFIF_BADTHUMBNAILSIZE,
  156787. "Warning: thumbnail image size does not match data length %u")
  156788. JMESSAGE(JTRC_JFIF_EXTENSION,
  156789. "JFIF extension marker: type 0x%02x, length %u")
  156790. JMESSAGE(JTRC_JFIF_THUMBNAIL, " with %d x %d thumbnail image")
  156791. JMESSAGE(JTRC_MISC_MARKER, "Miscellaneous marker 0x%02x, length %u")
  156792. JMESSAGE(JTRC_PARMLESS_MARKER, "Unexpected marker 0x%02x")
  156793. JMESSAGE(JTRC_QUANTVALS, " %4u %4u %4u %4u %4u %4u %4u %4u")
  156794. JMESSAGE(JTRC_QUANT_3_NCOLORS, "Quantizing to %d = %d*%d*%d colors")
  156795. JMESSAGE(JTRC_QUANT_NCOLORS, "Quantizing to %d colors")
  156796. JMESSAGE(JTRC_QUANT_SELECTED, "Selected %d colors for quantization")
  156797. JMESSAGE(JTRC_RECOVERY_ACTION, "At marker 0x%02x, recovery action %d")
  156798. JMESSAGE(JTRC_RST, "RST%d")
  156799. JMESSAGE(JTRC_SMOOTH_NOTIMPL,
  156800. "Smoothing not supported with nonstandard sampling ratios")
  156801. JMESSAGE(JTRC_SOF, "Start Of Frame 0x%02x: width=%u, height=%u, components=%d")
  156802. JMESSAGE(JTRC_SOF_COMPONENT, " Component %d: %dhx%dv q=%d")
  156803. JMESSAGE(JTRC_SOI, "Start of Image")
  156804. JMESSAGE(JTRC_SOS, "Start Of Scan: %d components")
  156805. JMESSAGE(JTRC_SOS_COMPONENT, " Component %d: dc=%d ac=%d")
  156806. JMESSAGE(JTRC_SOS_PARAMS, " Ss=%d, Se=%d, Ah=%d, Al=%d")
  156807. JMESSAGE(JTRC_TFILE_CLOSE, "Closed temporary file %s")
  156808. JMESSAGE(JTRC_TFILE_OPEN, "Opened temporary file %s")
  156809. JMESSAGE(JTRC_THUMB_JPEG,
  156810. "JFIF extension marker: JPEG-compressed thumbnail image, length %u")
  156811. JMESSAGE(JTRC_THUMB_PALETTE,
  156812. "JFIF extension marker: palette thumbnail image, length %u")
  156813. JMESSAGE(JTRC_THUMB_RGB,
  156814. "JFIF extension marker: RGB thumbnail image, length %u")
  156815. JMESSAGE(JTRC_UNKNOWN_IDS,
  156816. "Unrecognized component IDs %d %d %d, assuming YCbCr")
  156817. JMESSAGE(JTRC_XMS_CLOSE, "Freed XMS handle %u")
  156818. JMESSAGE(JTRC_XMS_OPEN, "Obtained XMS handle %u")
  156819. JMESSAGE(JWRN_ADOBE_XFORM, "Unknown Adobe color transform code %d")
  156820. JMESSAGE(JWRN_BOGUS_PROGRESSION,
  156821. "Inconsistent progression sequence for component %d coefficient %d")
  156822. JMESSAGE(JWRN_EXTRANEOUS_DATA,
  156823. "Corrupt JPEG data: %u extraneous bytes before marker 0x%02x")
  156824. JMESSAGE(JWRN_HIT_MARKER, "Corrupt JPEG data: premature end of data segment")
  156825. JMESSAGE(JWRN_HUFF_BAD_CODE, "Corrupt JPEG data: bad Huffman code")
  156826. JMESSAGE(JWRN_JFIF_MAJOR, "Warning: unknown JFIF revision number %d.%02d")
  156827. JMESSAGE(JWRN_JPEG_EOF, "Premature end of JPEG file")
  156828. JMESSAGE(JWRN_MUST_RESYNC,
  156829. "Corrupt JPEG data: found marker 0x%02x instead of RST%d")
  156830. JMESSAGE(JWRN_NOT_SEQUENTIAL, "Invalid SOS parameters for sequential JPEG")
  156831. JMESSAGE(JWRN_TOO_MUCH_DATA, "Application transferred too many scanlines")
  156832. #ifdef JMAKE_ENUM_LIST
  156833. JMSG_LASTMSGCODE
  156834. } J_MESSAGE_CODE;
  156835. #undef JMAKE_ENUM_LIST
  156836. #endif /* JMAKE_ENUM_LIST */
  156837. /* Zap JMESSAGE macro so that future re-inclusions do nothing by default */
  156838. #undef JMESSAGE
  156839. #ifndef JERROR_H
  156840. #define JERROR_H
  156841. /* Macros to simplify using the error and trace message stuff */
  156842. /* The first parameter is either type of cinfo pointer */
  156843. /* Fatal errors (print message and exit) */
  156844. #define ERREXIT(cinfo,code) \
  156845. ((cinfo)->err->msg_code = (code), \
  156846. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  156847. #define ERREXIT1(cinfo,code,p1) \
  156848. ((cinfo)->err->msg_code = (code), \
  156849. (cinfo)->err->msg_parm.i[0] = (p1), \
  156850. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  156851. #define ERREXIT2(cinfo,code,p1,p2) \
  156852. ((cinfo)->err->msg_code = (code), \
  156853. (cinfo)->err->msg_parm.i[0] = (p1), \
  156854. (cinfo)->err->msg_parm.i[1] = (p2), \
  156855. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  156856. #define ERREXIT3(cinfo,code,p1,p2,p3) \
  156857. ((cinfo)->err->msg_code = (code), \
  156858. (cinfo)->err->msg_parm.i[0] = (p1), \
  156859. (cinfo)->err->msg_parm.i[1] = (p2), \
  156860. (cinfo)->err->msg_parm.i[2] = (p3), \
  156861. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  156862. #define ERREXIT4(cinfo,code,p1,p2,p3,p4) \
  156863. ((cinfo)->err->msg_code = (code), \
  156864. (cinfo)->err->msg_parm.i[0] = (p1), \
  156865. (cinfo)->err->msg_parm.i[1] = (p2), \
  156866. (cinfo)->err->msg_parm.i[2] = (p3), \
  156867. (cinfo)->err->msg_parm.i[3] = (p4), \
  156868. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  156869. #define ERREXITS(cinfo,code,str) \
  156870. ((cinfo)->err->msg_code = (code), \
  156871. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  156872. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  156873. #define MAKESTMT(stuff) do { stuff } while (0)
  156874. /* Nonfatal errors (we can keep going, but the data is probably corrupt) */
  156875. #define WARNMS(cinfo,code) \
  156876. ((cinfo)->err->msg_code = (code), \
  156877. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  156878. #define WARNMS1(cinfo,code,p1) \
  156879. ((cinfo)->err->msg_code = (code), \
  156880. (cinfo)->err->msg_parm.i[0] = (p1), \
  156881. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  156882. #define WARNMS2(cinfo,code,p1,p2) \
  156883. ((cinfo)->err->msg_code = (code), \
  156884. (cinfo)->err->msg_parm.i[0] = (p1), \
  156885. (cinfo)->err->msg_parm.i[1] = (p2), \
  156886. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  156887. /* Informational/debugging messages */
  156888. #define TRACEMS(cinfo,lvl,code) \
  156889. ((cinfo)->err->msg_code = (code), \
  156890. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  156891. #define TRACEMS1(cinfo,lvl,code,p1) \
  156892. ((cinfo)->err->msg_code = (code), \
  156893. (cinfo)->err->msg_parm.i[0] = (p1), \
  156894. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  156895. #define TRACEMS2(cinfo,lvl,code,p1,p2) \
  156896. ((cinfo)->err->msg_code = (code), \
  156897. (cinfo)->err->msg_parm.i[0] = (p1), \
  156898. (cinfo)->err->msg_parm.i[1] = (p2), \
  156899. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  156900. #define TRACEMS3(cinfo,lvl,code,p1,p2,p3) \
  156901. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  156902. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); \
  156903. (cinfo)->err->msg_code = (code); \
  156904. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  156905. #define TRACEMS4(cinfo,lvl,code,p1,p2,p3,p4) \
  156906. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  156907. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  156908. (cinfo)->err->msg_code = (code); \
  156909. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  156910. #define TRACEMS5(cinfo,lvl,code,p1,p2,p3,p4,p5) \
  156911. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  156912. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  156913. _mp[4] = (p5); \
  156914. (cinfo)->err->msg_code = (code); \
  156915. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  156916. #define TRACEMS8(cinfo,lvl,code,p1,p2,p3,p4,p5,p6,p7,p8) \
  156917. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  156918. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  156919. _mp[4] = (p5); _mp[5] = (p6); _mp[6] = (p7); _mp[7] = (p8); \
  156920. (cinfo)->err->msg_code = (code); \
  156921. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  156922. #define TRACEMSS(cinfo,lvl,code,str) \
  156923. ((cinfo)->err->msg_code = (code), \
  156924. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  156925. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  156926. #endif /* JERROR_H */
  156927. /********* End of inlined file: jerror.h *********/
  156928. /* fetch error codes too */
  156929. #endif
  156930. #endif /* JPEGLIB_H */
  156931. /********* End of inlined file: jpeglib.h *********/
  156932. /********* Start of inlined file: jcapimin.c *********/
  156933. #define JPEG_INTERNALS
  156934. /********* Start of inlined file: jinclude.h *********/
  156935. /* Include auto-config file to find out which system include files we need. */
  156936. #ifndef __jinclude_h__
  156937. #define __jinclude_h__
  156938. /********* Start of inlined file: jconfig.h *********/
  156939. /* see jconfig.doc for explanations */
  156940. // disable all the warnings under MSVC
  156941. #ifdef _MSC_VER
  156942. #pragma warning (disable: 4996 4267 4100 4127 4702 4244)
  156943. #endif
  156944. #ifdef __BORLANDC__
  156945. #pragma warn -8057
  156946. #pragma warn -8019
  156947. #pragma warn -8004
  156948. #pragma warn -8008
  156949. #endif
  156950. #define HAVE_PROTOTYPES
  156951. #define HAVE_UNSIGNED_CHAR
  156952. #define HAVE_UNSIGNED_SHORT
  156953. /* #define void char */
  156954. /* #define const */
  156955. #undef CHAR_IS_UNSIGNED
  156956. #define HAVE_STDDEF_H
  156957. #define HAVE_STDLIB_H
  156958. #undef NEED_BSD_STRINGS
  156959. #undef NEED_SYS_TYPES_H
  156960. #undef NEED_FAR_POINTERS /* we presume a 32-bit flat memory model */
  156961. #undef NEED_SHORT_EXTERNAL_NAMES
  156962. #undef INCOMPLETE_TYPES_BROKEN
  156963. /* Define "boolean" as unsigned char, not int, per Windows custom */
  156964. #ifndef __RPCNDR_H__ /* don't conflict if rpcndr.h already read */
  156965. typedef unsigned char boolean;
  156966. #endif
  156967. #define HAVE_BOOLEAN /* prevent jmorecfg.h from redefining it */
  156968. #ifdef JPEG_INTERNALS
  156969. #undef RIGHT_SHIFT_IS_UNSIGNED
  156970. #endif /* JPEG_INTERNALS */
  156971. #ifdef JPEG_CJPEG_DJPEG
  156972. #define BMP_SUPPORTED /* BMP image file format */
  156973. #define GIF_SUPPORTED /* GIF image file format */
  156974. #define PPM_SUPPORTED /* PBMPLUS PPM/PGM image file format */
  156975. #undef RLE_SUPPORTED /* Utah RLE image file format */
  156976. #define TARGA_SUPPORTED /* Targa image file format */
  156977. #define TWO_FILE_COMMANDLINE /* optional */
  156978. #define USE_SETMODE /* Microsoft has setmode() */
  156979. #undef NEED_SIGNAL_CATCHER
  156980. #undef DONT_USE_B_MODE
  156981. #undef PROGRESS_REPORT /* optional */
  156982. #endif /* JPEG_CJPEG_DJPEG */
  156983. /********* End of inlined file: jconfig.h *********/
  156984. /* auto configuration options */
  156985. #define JCONFIG_INCLUDED /* so that jpeglib.h doesn't do it again */
  156986. /*
  156987. * We need the NULL macro and size_t typedef.
  156988. * On an ANSI-conforming system it is sufficient to include <stddef.h>.
  156989. * Otherwise, we get them from <stdlib.h> or <stdio.h>; we may have to
  156990. * pull in <sys/types.h> as well.
  156991. * Note that the core JPEG library does not require <stdio.h>;
  156992. * only the default error handler and data source/destination modules do.
  156993. * But we must pull it in because of the references to FILE in jpeglib.h.
  156994. * You can remove those references if you want to compile without <stdio.h>.
  156995. */
  156996. #ifdef HAVE_STDDEF_H
  156997. #include <stddef.h>
  156998. #endif
  156999. #ifdef HAVE_STDLIB_H
  157000. #include <stdlib.h>
  157001. #endif
  157002. #ifdef NEED_SYS_TYPES_H
  157003. #include <sys/types.h>
  157004. #endif
  157005. #include <stdio.h>
  157006. /*
  157007. * We need memory copying and zeroing functions, plus strncpy().
  157008. * ANSI and System V implementations declare these in <string.h>.
  157009. * BSD doesn't have the mem() functions, but it does have bcopy()/bzero().
  157010. * Some systems may declare memset and memcpy in <memory.h>.
  157011. *
  157012. * NOTE: we assume the size parameters to these functions are of type size_t.
  157013. * Change the casts in these macros if not!
  157014. */
  157015. #ifdef NEED_BSD_STRINGS
  157016. #include <strings.h>
  157017. #define MEMZERO(target,size) bzero((void *)(target), (size_t)(size))
  157018. #define MEMCOPY(dest,src,size) bcopy((const void *)(src), (void *)(dest), (size_t)(size))
  157019. #else /* not BSD, assume ANSI/SysV string lib */
  157020. #include <string.h>
  157021. #define MEMZERO(target,size) memset((void *)(target), 0, (size_t)(size))
  157022. #define MEMCOPY(dest,src,size) memcpy((void *)(dest), (const void *)(src), (size_t)(size))
  157023. #endif
  157024. /*
  157025. * In ANSI C, and indeed any rational implementation, size_t is also the
  157026. * type returned by sizeof(). However, it seems there are some irrational
  157027. * implementations out there, in which sizeof() returns an int even though
  157028. * size_t is defined as long or unsigned long. To ensure consistent results
  157029. * we always use this SIZEOF() macro in place of using sizeof() directly.
  157030. */
  157031. #define SIZEOF(object) ((size_t) sizeof(object))
  157032. /*
  157033. * The modules that use fread() and fwrite() always invoke them through
  157034. * these macros. On some systems you may need to twiddle the argument casts.
  157035. * CAUTION: argument order is different from underlying functions!
  157036. */
  157037. #define JFREAD(file,buf,sizeofbuf) \
  157038. ((size_t) fread((void *) (buf), (size_t) 1, (size_t) (sizeofbuf), (file)))
  157039. #define JFWRITE(file,buf,sizeofbuf) \
  157040. ((size_t) fwrite((const void *) (buf), (size_t) 1, (size_t) (sizeofbuf), (file)))
  157041. typedef enum { /* JPEG marker codes */
  157042. M_SOF0 = 0xc0,
  157043. M_SOF1 = 0xc1,
  157044. M_SOF2 = 0xc2,
  157045. M_SOF3 = 0xc3,
  157046. M_SOF5 = 0xc5,
  157047. M_SOF6 = 0xc6,
  157048. M_SOF7 = 0xc7,
  157049. M_JPG = 0xc8,
  157050. M_SOF9 = 0xc9,
  157051. M_SOF10 = 0xca,
  157052. M_SOF11 = 0xcb,
  157053. M_SOF13 = 0xcd,
  157054. M_SOF14 = 0xce,
  157055. M_SOF15 = 0xcf,
  157056. M_DHT = 0xc4,
  157057. M_DAC = 0xcc,
  157058. M_RST0 = 0xd0,
  157059. M_RST1 = 0xd1,
  157060. M_RST2 = 0xd2,
  157061. M_RST3 = 0xd3,
  157062. M_RST4 = 0xd4,
  157063. M_RST5 = 0xd5,
  157064. M_RST6 = 0xd6,
  157065. M_RST7 = 0xd7,
  157066. M_SOI = 0xd8,
  157067. M_EOI = 0xd9,
  157068. M_SOS = 0xda,
  157069. M_DQT = 0xdb,
  157070. M_DNL = 0xdc,
  157071. M_DRI = 0xdd,
  157072. M_DHP = 0xde,
  157073. M_EXP = 0xdf,
  157074. M_APP0 = 0xe0,
  157075. M_APP1 = 0xe1,
  157076. M_APP2 = 0xe2,
  157077. M_APP3 = 0xe3,
  157078. M_APP4 = 0xe4,
  157079. M_APP5 = 0xe5,
  157080. M_APP6 = 0xe6,
  157081. M_APP7 = 0xe7,
  157082. M_APP8 = 0xe8,
  157083. M_APP9 = 0xe9,
  157084. M_APP10 = 0xea,
  157085. M_APP11 = 0xeb,
  157086. M_APP12 = 0xec,
  157087. M_APP13 = 0xed,
  157088. M_APP14 = 0xee,
  157089. M_APP15 = 0xef,
  157090. M_JPG0 = 0xf0,
  157091. M_JPG13 = 0xfd,
  157092. M_COM = 0xfe,
  157093. M_TEM = 0x01,
  157094. M_ERROR = 0x100
  157095. } JPEG_MARKER;
  157096. /*
  157097. * Figure F.12: extend sign bit.
  157098. * On some machines, a shift and add will be faster than a table lookup.
  157099. */
  157100. #ifdef AVOID_TABLES
  157101. #define HUFF_EXTEND(x,s) ((x) < (1<<((s)-1)) ? (x) + (((-1)<<(s)) + 1) : (x))
  157102. #else
  157103. #define HUFF_EXTEND(x,s) ((x) < extend_test[s] ? (x) + extend_offset[s] : (x))
  157104. static const int extend_test[16] = /* entry n is 2**(n-1) */
  157105. { 0, 0x0001, 0x0002, 0x0004, 0x0008, 0x0010, 0x0020, 0x0040, 0x0080,
  157106. 0x0100, 0x0200, 0x0400, 0x0800, 0x1000, 0x2000, 0x4000 };
  157107. static const int extend_offset[16] = /* entry n is (-1 << n) + 1 */
  157108. { 0, ((-1)<<1) + 1, ((-1)<<2) + 1, ((-1)<<3) + 1, ((-1)<<4) + 1,
  157109. ((-1)<<5) + 1, ((-1)<<6) + 1, ((-1)<<7) + 1, ((-1)<<8) + 1,
  157110. ((-1)<<9) + 1, ((-1)<<10) + 1, ((-1)<<11) + 1, ((-1)<<12) + 1,
  157111. ((-1)<<13) + 1, ((-1)<<14) + 1, ((-1)<<15) + 1 };
  157112. #endif /* AVOID_TABLES */
  157113. #endif
  157114. /********* End of inlined file: jinclude.h *********/
  157115. /*
  157116. * Initialization of a JPEG compression object.
  157117. * The error manager must already be set up (in case memory manager fails).
  157118. */
  157119. GLOBAL(void)
  157120. jpeg_CreateCompress (j_compress_ptr cinfo, int version, size_t structsize)
  157121. {
  157122. int i;
  157123. /* Guard against version mismatches between library and caller. */
  157124. cinfo->mem = NULL; /* so jpeg_destroy knows mem mgr not called */
  157125. if (version != JPEG_LIB_VERSION)
  157126. ERREXIT2(cinfo, JERR_BAD_LIB_VERSION, JPEG_LIB_VERSION, version);
  157127. if (structsize != SIZEOF(struct jpeg_compress_struct))
  157128. ERREXIT2(cinfo, JERR_BAD_STRUCT_SIZE,
  157129. (int) SIZEOF(struct jpeg_compress_struct), (int) structsize);
  157130. /* For debugging purposes, we zero the whole master structure.
  157131. * But the application has already set the err pointer, and may have set
  157132. * client_data, so we have to save and restore those fields.
  157133. * Note: if application hasn't set client_data, tools like Purify may
  157134. * complain here.
  157135. */
  157136. {
  157137. struct jpeg_error_mgr * err = cinfo->err;
  157138. void * client_data = cinfo->client_data; /* ignore Purify complaint here */
  157139. MEMZERO(cinfo, SIZEOF(struct jpeg_compress_struct));
  157140. cinfo->err = err;
  157141. cinfo->client_data = client_data;
  157142. }
  157143. cinfo->is_decompressor = FALSE;
  157144. /* Initialize a memory manager instance for this object */
  157145. jinit_memory_mgr((j_common_ptr) cinfo);
  157146. /* Zero out pointers to permanent structures. */
  157147. cinfo->progress = NULL;
  157148. cinfo->dest = NULL;
  157149. cinfo->comp_info = NULL;
  157150. for (i = 0; i < NUM_QUANT_TBLS; i++)
  157151. cinfo->quant_tbl_ptrs[i] = NULL;
  157152. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  157153. cinfo->dc_huff_tbl_ptrs[i] = NULL;
  157154. cinfo->ac_huff_tbl_ptrs[i] = NULL;
  157155. }
  157156. cinfo->script_space = NULL;
  157157. cinfo->input_gamma = 1.0; /* in case application forgets */
  157158. /* OK, I'm ready */
  157159. cinfo->global_state = CSTATE_START;
  157160. }
  157161. /*
  157162. * Destruction of a JPEG compression object
  157163. */
  157164. GLOBAL(void)
  157165. jpeg_destroy_compress (j_compress_ptr cinfo)
  157166. {
  157167. jpeg_destroy((j_common_ptr) cinfo); /* use common routine */
  157168. }
  157169. /*
  157170. * Abort processing of a JPEG compression operation,
  157171. * but don't destroy the object itself.
  157172. */
  157173. GLOBAL(void)
  157174. jpeg_abort_compress (j_compress_ptr cinfo)
  157175. {
  157176. jpeg_abort((j_common_ptr) cinfo); /* use common routine */
  157177. }
  157178. /*
  157179. * Forcibly suppress or un-suppress all quantization and Huffman tables.
  157180. * Marks all currently defined tables as already written (if suppress)
  157181. * or not written (if !suppress). This will control whether they get emitted
  157182. * by a subsequent jpeg_start_compress call.
  157183. *
  157184. * This routine is exported for use by applications that want to produce
  157185. * abbreviated JPEG datastreams. It logically belongs in jcparam.c, but
  157186. * since it is called by jpeg_start_compress, we put it here --- otherwise
  157187. * jcparam.o would be linked whether the application used it or not.
  157188. */
  157189. GLOBAL(void)
  157190. jpeg_suppress_tables (j_compress_ptr cinfo, boolean suppress)
  157191. {
  157192. int i;
  157193. JQUANT_TBL * qtbl;
  157194. JHUFF_TBL * htbl;
  157195. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  157196. if ((qtbl = cinfo->quant_tbl_ptrs[i]) != NULL)
  157197. qtbl->sent_table = suppress;
  157198. }
  157199. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  157200. if ((htbl = cinfo->dc_huff_tbl_ptrs[i]) != NULL)
  157201. htbl->sent_table = suppress;
  157202. if ((htbl = cinfo->ac_huff_tbl_ptrs[i]) != NULL)
  157203. htbl->sent_table = suppress;
  157204. }
  157205. }
  157206. /*
  157207. * Finish JPEG compression.
  157208. *
  157209. * If a multipass operating mode was selected, this may do a great deal of
  157210. * work including most of the actual output.
  157211. */
  157212. GLOBAL(void)
  157213. jpeg_finish_compress (j_compress_ptr cinfo)
  157214. {
  157215. JDIMENSION iMCU_row;
  157216. if (cinfo->global_state == CSTATE_SCANNING ||
  157217. cinfo->global_state == CSTATE_RAW_OK) {
  157218. /* Terminate first pass */
  157219. if (cinfo->next_scanline < cinfo->image_height)
  157220. ERREXIT(cinfo, JERR_TOO_LITTLE_DATA);
  157221. (*cinfo->master->finish_pass) (cinfo);
  157222. } else if (cinfo->global_state != CSTATE_WRCOEFS)
  157223. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  157224. /* Perform any remaining passes */
  157225. while (! cinfo->master->is_last_pass) {
  157226. (*cinfo->master->prepare_for_pass) (cinfo);
  157227. for (iMCU_row = 0; iMCU_row < cinfo->total_iMCU_rows; iMCU_row++) {
  157228. if (cinfo->progress != NULL) {
  157229. cinfo->progress->pass_counter = (long) iMCU_row;
  157230. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows;
  157231. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  157232. }
  157233. /* We bypass the main controller and invoke coef controller directly;
  157234. * all work is being done from the coefficient buffer.
  157235. */
  157236. if (! (*cinfo->coef->compress_data) (cinfo, (JSAMPIMAGE) NULL))
  157237. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  157238. }
  157239. (*cinfo->master->finish_pass) (cinfo);
  157240. }
  157241. /* Write EOI, do final cleanup */
  157242. (*cinfo->marker->write_file_trailer) (cinfo);
  157243. (*cinfo->dest->term_destination) (cinfo);
  157244. /* We can use jpeg_abort to release memory and reset global_state */
  157245. jpeg_abort((j_common_ptr) cinfo);
  157246. }
  157247. /*
  157248. * Write a special marker.
  157249. * This is only recommended for writing COM or APPn markers.
  157250. * Must be called after jpeg_start_compress() and before
  157251. * first call to jpeg_write_scanlines() or jpeg_write_raw_data().
  157252. */
  157253. GLOBAL(void)
  157254. jpeg_write_marker (j_compress_ptr cinfo, int marker,
  157255. const JOCTET *dataptr, unsigned int datalen)
  157256. {
  157257. JMETHOD(void, write_marker_byte, (j_compress_ptr info, int val));
  157258. if (cinfo->next_scanline != 0 ||
  157259. (cinfo->global_state != CSTATE_SCANNING &&
  157260. cinfo->global_state != CSTATE_RAW_OK &&
  157261. cinfo->global_state != CSTATE_WRCOEFS))
  157262. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  157263. (*cinfo->marker->write_marker_header) (cinfo, marker, datalen);
  157264. write_marker_byte = cinfo->marker->write_marker_byte; /* copy for speed */
  157265. while (datalen--) {
  157266. (*write_marker_byte) (cinfo, *dataptr);
  157267. dataptr++;
  157268. }
  157269. }
  157270. /* Same, but piecemeal. */
  157271. GLOBAL(void)
  157272. jpeg_write_m_header (j_compress_ptr cinfo, int marker, unsigned int datalen)
  157273. {
  157274. if (cinfo->next_scanline != 0 ||
  157275. (cinfo->global_state != CSTATE_SCANNING &&
  157276. cinfo->global_state != CSTATE_RAW_OK &&
  157277. cinfo->global_state != CSTATE_WRCOEFS))
  157278. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  157279. (*cinfo->marker->write_marker_header) (cinfo, marker, datalen);
  157280. }
  157281. GLOBAL(void)
  157282. jpeg_write_m_byte (j_compress_ptr cinfo, int val)
  157283. {
  157284. (*cinfo->marker->write_marker_byte) (cinfo, val);
  157285. }
  157286. /*
  157287. * Alternate compression function: just write an abbreviated table file.
  157288. * Before calling this, all parameters and a data destination must be set up.
  157289. *
  157290. * To produce a pair of files containing abbreviated tables and abbreviated
  157291. * image data, one would proceed as follows:
  157292. *
  157293. * initialize JPEG object
  157294. * set JPEG parameters
  157295. * set destination to table file
  157296. * jpeg_write_tables(cinfo);
  157297. * set destination to image file
  157298. * jpeg_start_compress(cinfo, FALSE);
  157299. * write data...
  157300. * jpeg_finish_compress(cinfo);
  157301. *
  157302. * jpeg_write_tables has the side effect of marking all tables written
  157303. * (same as jpeg_suppress_tables(..., TRUE)). Thus a subsequent start_compress
  157304. * will not re-emit the tables unless it is passed write_all_tables=TRUE.
  157305. */
  157306. GLOBAL(void)
  157307. jpeg_write_tables (j_compress_ptr cinfo)
  157308. {
  157309. if (cinfo->global_state != CSTATE_START)
  157310. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  157311. /* (Re)initialize error mgr and destination modules */
  157312. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  157313. (*cinfo->dest->init_destination) (cinfo);
  157314. /* Initialize the marker writer ... bit of a crock to do it here. */
  157315. jinit_marker_writer(cinfo);
  157316. /* Write them tables! */
  157317. (*cinfo->marker->write_tables_only) (cinfo);
  157318. /* And clean up. */
  157319. (*cinfo->dest->term_destination) (cinfo);
  157320. /*
  157321. * In library releases up through v6a, we called jpeg_abort() here to free
  157322. * any working memory allocated by the destination manager and marker
  157323. * writer. Some applications had a problem with that: they allocated space
  157324. * of their own from the library memory manager, and didn't want it to go
  157325. * away during write_tables. So now we do nothing. This will cause a
  157326. * memory leak if an app calls write_tables repeatedly without doing a full
  157327. * compression cycle or otherwise resetting the JPEG object. However, that
  157328. * seems less bad than unexpectedly freeing memory in the normal case.
  157329. * An app that prefers the old behavior can call jpeg_abort for itself after
  157330. * each call to jpeg_write_tables().
  157331. */
  157332. }
  157333. /********* End of inlined file: jcapimin.c *********/
  157334. /********* Start of inlined file: jcapistd.c *********/
  157335. #define JPEG_INTERNALS
  157336. /*
  157337. * Compression initialization.
  157338. * Before calling this, all parameters and a data destination must be set up.
  157339. *
  157340. * We require a write_all_tables parameter as a failsafe check when writing
  157341. * multiple datastreams from the same compression object. Since prior runs
  157342. * will have left all the tables marked sent_table=TRUE, a subsequent run
  157343. * would emit an abbreviated stream (no tables) by default. This may be what
  157344. * is wanted, but for safety's sake it should not be the default behavior:
  157345. * programmers should have to make a deliberate choice to emit abbreviated
  157346. * images. Therefore the documentation and examples should encourage people
  157347. * to pass write_all_tables=TRUE; then it will take active thought to do the
  157348. * wrong thing.
  157349. */
  157350. GLOBAL(void)
  157351. jpeg_start_compress (j_compress_ptr cinfo, boolean write_all_tables)
  157352. {
  157353. if (cinfo->global_state != CSTATE_START)
  157354. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  157355. if (write_all_tables)
  157356. jpeg_suppress_tables(cinfo, FALSE); /* mark all tables to be written */
  157357. /* (Re)initialize error mgr and destination modules */
  157358. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  157359. (*cinfo->dest->init_destination) (cinfo);
  157360. /* Perform master selection of active modules */
  157361. jinit_compress_master(cinfo);
  157362. /* Set up for the first pass */
  157363. (*cinfo->master->prepare_for_pass) (cinfo);
  157364. /* Ready for application to drive first pass through jpeg_write_scanlines
  157365. * or jpeg_write_raw_data.
  157366. */
  157367. cinfo->next_scanline = 0;
  157368. cinfo->global_state = (cinfo->raw_data_in ? CSTATE_RAW_OK : CSTATE_SCANNING);
  157369. }
  157370. /*
  157371. * Write some scanlines of data to the JPEG compressor.
  157372. *
  157373. * The return value will be the number of lines actually written.
  157374. * This should be less than the supplied num_lines only in case that
  157375. * the data destination module has requested suspension of the compressor,
  157376. * or if more than image_height scanlines are passed in.
  157377. *
  157378. * Note: we warn about excess calls to jpeg_write_scanlines() since
  157379. * this likely signals an application programmer error. However,
  157380. * excess scanlines passed in the last valid call are *silently* ignored,
  157381. * so that the application need not adjust num_lines for end-of-image
  157382. * when using a multiple-scanline buffer.
  157383. */
  157384. GLOBAL(JDIMENSION)
  157385. jpeg_write_scanlines (j_compress_ptr cinfo, JSAMPARRAY scanlines,
  157386. JDIMENSION num_lines)
  157387. {
  157388. JDIMENSION row_ctr, rows_left;
  157389. if (cinfo->global_state != CSTATE_SCANNING)
  157390. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  157391. if (cinfo->next_scanline >= cinfo->image_height)
  157392. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  157393. /* Call progress monitor hook if present */
  157394. if (cinfo->progress != NULL) {
  157395. cinfo->progress->pass_counter = (long) cinfo->next_scanline;
  157396. cinfo->progress->pass_limit = (long) cinfo->image_height;
  157397. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  157398. }
  157399. /* Give master control module another chance if this is first call to
  157400. * jpeg_write_scanlines. This lets output of the frame/scan headers be
  157401. * delayed so that application can write COM, etc, markers between
  157402. * jpeg_start_compress and jpeg_write_scanlines.
  157403. */
  157404. if (cinfo->master->call_pass_startup)
  157405. (*cinfo->master->pass_startup) (cinfo);
  157406. /* Ignore any extra scanlines at bottom of image. */
  157407. rows_left = cinfo->image_height - cinfo->next_scanline;
  157408. if (num_lines > rows_left)
  157409. num_lines = rows_left;
  157410. row_ctr = 0;
  157411. (*cinfo->main->process_data) (cinfo, scanlines, &row_ctr, num_lines);
  157412. cinfo->next_scanline += row_ctr;
  157413. return row_ctr;
  157414. }
  157415. /*
  157416. * Alternate entry point to write raw data.
  157417. * Processes exactly one iMCU row per call, unless suspended.
  157418. */
  157419. GLOBAL(JDIMENSION)
  157420. jpeg_write_raw_data (j_compress_ptr cinfo, JSAMPIMAGE data,
  157421. JDIMENSION num_lines)
  157422. {
  157423. JDIMENSION lines_per_iMCU_row;
  157424. if (cinfo->global_state != CSTATE_RAW_OK)
  157425. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  157426. if (cinfo->next_scanline >= cinfo->image_height) {
  157427. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  157428. return 0;
  157429. }
  157430. /* Call progress monitor hook if present */
  157431. if (cinfo->progress != NULL) {
  157432. cinfo->progress->pass_counter = (long) cinfo->next_scanline;
  157433. cinfo->progress->pass_limit = (long) cinfo->image_height;
  157434. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  157435. }
  157436. /* Give master control module another chance if this is first call to
  157437. * jpeg_write_raw_data. This lets output of the frame/scan headers be
  157438. * delayed so that application can write COM, etc, markers between
  157439. * jpeg_start_compress and jpeg_write_raw_data.
  157440. */
  157441. if (cinfo->master->call_pass_startup)
  157442. (*cinfo->master->pass_startup) (cinfo);
  157443. /* Verify that at least one iMCU row has been passed. */
  157444. lines_per_iMCU_row = cinfo->max_v_samp_factor * DCTSIZE;
  157445. if (num_lines < lines_per_iMCU_row)
  157446. ERREXIT(cinfo, JERR_BUFFER_SIZE);
  157447. /* Directly compress the row. */
  157448. if (! (*cinfo->coef->compress_data) (cinfo, data)) {
  157449. /* If compressor did not consume the whole row, suspend processing. */
  157450. return 0;
  157451. }
  157452. /* OK, we processed one iMCU row. */
  157453. cinfo->next_scanline += lines_per_iMCU_row;
  157454. return lines_per_iMCU_row;
  157455. }
  157456. /********* End of inlined file: jcapistd.c *********/
  157457. /********* Start of inlined file: jccoefct.c *********/
  157458. #define JPEG_INTERNALS
  157459. /* We use a full-image coefficient buffer when doing Huffman optimization,
  157460. * and also for writing multiple-scan JPEG files. In all cases, the DCT
  157461. * step is run during the first pass, and subsequent passes need only read
  157462. * the buffered coefficients.
  157463. */
  157464. #ifdef ENTROPY_OPT_SUPPORTED
  157465. #define FULL_COEF_BUFFER_SUPPORTED
  157466. #else
  157467. #ifdef C_MULTISCAN_FILES_SUPPORTED
  157468. #define FULL_COEF_BUFFER_SUPPORTED
  157469. #endif
  157470. #endif
  157471. /* Private buffer controller object */
  157472. typedef struct {
  157473. struct jpeg_c_coef_controller pub; /* public fields */
  157474. JDIMENSION iMCU_row_num; /* iMCU row # within image */
  157475. JDIMENSION mcu_ctr; /* counts MCUs processed in current row */
  157476. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  157477. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  157478. /* For single-pass compression, it's sufficient to buffer just one MCU
  157479. * (although this may prove a bit slow in practice). We allocate a
  157480. * workspace of C_MAX_BLOCKS_IN_MCU coefficient blocks, and reuse it for each
  157481. * MCU constructed and sent. (On 80x86, the workspace is FAR even though
  157482. * it's not really very big; this is to keep the module interfaces unchanged
  157483. * when a large coefficient buffer is necessary.)
  157484. * In multi-pass modes, this array points to the current MCU's blocks
  157485. * within the virtual arrays.
  157486. */
  157487. JBLOCKROW MCU_buffer[C_MAX_BLOCKS_IN_MCU];
  157488. /* In multi-pass modes, we need a virtual block array for each component. */
  157489. jvirt_barray_ptr whole_image[MAX_COMPONENTS];
  157490. } my_coef_controller;
  157491. typedef my_coef_controller * my_coef_ptr;
  157492. /* Forward declarations */
  157493. METHODDEF(boolean) compress_data
  157494. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  157495. #ifdef FULL_COEF_BUFFER_SUPPORTED
  157496. METHODDEF(boolean) compress_first_pass
  157497. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  157498. METHODDEF(boolean) compress_output
  157499. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  157500. #endif
  157501. LOCAL(void)
  157502. start_iMCU_row (j_compress_ptr cinfo)
  157503. /* Reset within-iMCU-row counters for a new row */
  157504. {
  157505. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  157506. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  157507. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  157508. * But at the bottom of the image, process only what's left.
  157509. */
  157510. if (cinfo->comps_in_scan > 1) {
  157511. coef->MCU_rows_per_iMCU_row = 1;
  157512. } else {
  157513. if (coef->iMCU_row_num < (cinfo->total_iMCU_rows-1))
  157514. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  157515. else
  157516. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  157517. }
  157518. coef->mcu_ctr = 0;
  157519. coef->MCU_vert_offset = 0;
  157520. }
  157521. /*
  157522. * Initialize for a processing pass.
  157523. */
  157524. METHODDEF(void)
  157525. start_pass_coef (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  157526. {
  157527. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  157528. coef->iMCU_row_num = 0;
  157529. start_iMCU_row(cinfo);
  157530. switch (pass_mode) {
  157531. case JBUF_PASS_THRU:
  157532. if (coef->whole_image[0] != NULL)
  157533. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  157534. coef->pub.compress_data = compress_data;
  157535. break;
  157536. #ifdef FULL_COEF_BUFFER_SUPPORTED
  157537. case JBUF_SAVE_AND_PASS:
  157538. if (coef->whole_image[0] == NULL)
  157539. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  157540. coef->pub.compress_data = compress_first_pass;
  157541. break;
  157542. case JBUF_CRANK_DEST:
  157543. if (coef->whole_image[0] == NULL)
  157544. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  157545. coef->pub.compress_data = compress_output;
  157546. break;
  157547. #endif
  157548. default:
  157549. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  157550. break;
  157551. }
  157552. }
  157553. /*
  157554. * Process some data in the single-pass case.
  157555. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  157556. * per call, ie, v_samp_factor block rows for each component in the image.
  157557. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  157558. *
  157559. * NB: input_buf contains a plane for each component in image,
  157560. * which we index according to the component's SOF position.
  157561. */
  157562. METHODDEF(boolean)
  157563. compress_data (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
  157564. {
  157565. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  157566. JDIMENSION MCU_col_num; /* index of current MCU within row */
  157567. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  157568. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  157569. int blkn, bi, ci, yindex, yoffset, blockcnt;
  157570. JDIMENSION ypos, xpos;
  157571. jpeg_component_info *compptr;
  157572. /* Loop to write as much as one whole iMCU row */
  157573. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  157574. yoffset++) {
  157575. for (MCU_col_num = coef->mcu_ctr; MCU_col_num <= last_MCU_col;
  157576. MCU_col_num++) {
  157577. /* Determine where data comes from in input_buf and do the DCT thing.
  157578. * Each call on forward_DCT processes a horizontal row of DCT blocks
  157579. * as wide as an MCU; we rely on having allocated the MCU_buffer[] blocks
  157580. * sequentially. Dummy blocks at the right or bottom edge are filled in
  157581. * specially. The data in them does not matter for image reconstruction,
  157582. * so we fill them with values that will encode to the smallest amount of
  157583. * data, viz: all zeroes in the AC entries, DC entries equal to previous
  157584. * block's DC value. (Thanks to Thomas Kinsman for this idea.)
  157585. */
  157586. blkn = 0;
  157587. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  157588. compptr = cinfo->cur_comp_info[ci];
  157589. blockcnt = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  157590. : compptr->last_col_width;
  157591. xpos = MCU_col_num * compptr->MCU_sample_width;
  157592. ypos = yoffset * DCTSIZE; /* ypos == (yoffset+yindex) * DCTSIZE */
  157593. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  157594. if (coef->iMCU_row_num < last_iMCU_row ||
  157595. yoffset+yindex < compptr->last_row_height) {
  157596. (*cinfo->fdct->forward_DCT) (cinfo, compptr,
  157597. input_buf[compptr->component_index],
  157598. coef->MCU_buffer[blkn],
  157599. ypos, xpos, (JDIMENSION) blockcnt);
  157600. if (blockcnt < compptr->MCU_width) {
  157601. /* Create some dummy blocks at the right edge of the image. */
  157602. jzero_far((void FAR *) coef->MCU_buffer[blkn + blockcnt],
  157603. (compptr->MCU_width - blockcnt) * SIZEOF(JBLOCK));
  157604. for (bi = blockcnt; bi < compptr->MCU_width; bi++) {
  157605. coef->MCU_buffer[blkn+bi][0][0] = coef->MCU_buffer[blkn+bi-1][0][0];
  157606. }
  157607. }
  157608. } else {
  157609. /* Create a row of dummy blocks at the bottom of the image. */
  157610. jzero_far((void FAR *) coef->MCU_buffer[blkn],
  157611. compptr->MCU_width * SIZEOF(JBLOCK));
  157612. for (bi = 0; bi < compptr->MCU_width; bi++) {
  157613. coef->MCU_buffer[blkn+bi][0][0] = coef->MCU_buffer[blkn-1][0][0];
  157614. }
  157615. }
  157616. blkn += compptr->MCU_width;
  157617. ypos += DCTSIZE;
  157618. }
  157619. }
  157620. /* Try to write the MCU. In event of a suspension failure, we will
  157621. * re-DCT the MCU on restart (a bit inefficient, could be fixed...)
  157622. */
  157623. if (! (*cinfo->entropy->encode_mcu) (cinfo, coef->MCU_buffer)) {
  157624. /* Suspension forced; update state counters and exit */
  157625. coef->MCU_vert_offset = yoffset;
  157626. coef->mcu_ctr = MCU_col_num;
  157627. return FALSE;
  157628. }
  157629. }
  157630. /* Completed an MCU row, but perhaps not an iMCU row */
  157631. coef->mcu_ctr = 0;
  157632. }
  157633. /* Completed the iMCU row, advance counters for next one */
  157634. coef->iMCU_row_num++;
  157635. start_iMCU_row(cinfo);
  157636. return TRUE;
  157637. }
  157638. #ifdef FULL_COEF_BUFFER_SUPPORTED
  157639. /*
  157640. * Process some data in the first pass of a multi-pass case.
  157641. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  157642. * per call, ie, v_samp_factor block rows for each component in the image.
  157643. * This amount of data is read from the source buffer, DCT'd and quantized,
  157644. * and saved into the virtual arrays. We also generate suitable dummy blocks
  157645. * as needed at the right and lower edges. (The dummy blocks are constructed
  157646. * in the virtual arrays, which have been padded appropriately.) This makes
  157647. * it possible for subsequent passes not to worry about real vs. dummy blocks.
  157648. *
  157649. * We must also emit the data to the entropy encoder. This is conveniently
  157650. * done by calling compress_output() after we've loaded the current strip
  157651. * of the virtual arrays.
  157652. *
  157653. * NB: input_buf contains a plane for each component in image. All
  157654. * components are DCT'd and loaded into the virtual arrays in this pass.
  157655. * However, it may be that only a subset of the components are emitted to
  157656. * the entropy encoder during this first pass; be careful about looking
  157657. * at the scan-dependent variables (MCU dimensions, etc).
  157658. */
  157659. METHODDEF(boolean)
  157660. compress_first_pass (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
  157661. {
  157662. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  157663. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  157664. JDIMENSION blocks_across, MCUs_across, MCUindex;
  157665. int bi, ci, h_samp_factor, block_row, block_rows, ndummy;
  157666. JCOEF lastDC;
  157667. jpeg_component_info *compptr;
  157668. JBLOCKARRAY buffer;
  157669. JBLOCKROW thisblockrow, lastblockrow;
  157670. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  157671. ci++, compptr++) {
  157672. /* Align the virtual buffer for this component. */
  157673. buffer = (*cinfo->mem->access_virt_barray)
  157674. ((j_common_ptr) cinfo, coef->whole_image[ci],
  157675. coef->iMCU_row_num * compptr->v_samp_factor,
  157676. (JDIMENSION) compptr->v_samp_factor, TRUE);
  157677. /* Count non-dummy DCT block rows in this iMCU row. */
  157678. if (coef->iMCU_row_num < last_iMCU_row)
  157679. block_rows = compptr->v_samp_factor;
  157680. else {
  157681. /* NB: can't use last_row_height here, since may not be set! */
  157682. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  157683. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  157684. }
  157685. blocks_across = compptr->width_in_blocks;
  157686. h_samp_factor = compptr->h_samp_factor;
  157687. /* Count number of dummy blocks to be added at the right margin. */
  157688. ndummy = (int) (blocks_across % h_samp_factor);
  157689. if (ndummy > 0)
  157690. ndummy = h_samp_factor - ndummy;
  157691. /* Perform DCT for all non-dummy blocks in this iMCU row. Each call
  157692. * on forward_DCT processes a complete horizontal row of DCT blocks.
  157693. */
  157694. for (block_row = 0; block_row < block_rows; block_row++) {
  157695. thisblockrow = buffer[block_row];
  157696. (*cinfo->fdct->forward_DCT) (cinfo, compptr,
  157697. input_buf[ci], thisblockrow,
  157698. (JDIMENSION) (block_row * DCTSIZE),
  157699. (JDIMENSION) 0, blocks_across);
  157700. if (ndummy > 0) {
  157701. /* Create dummy blocks at the right edge of the image. */
  157702. thisblockrow += blocks_across; /* => first dummy block */
  157703. jzero_far((void FAR *) thisblockrow, ndummy * SIZEOF(JBLOCK));
  157704. lastDC = thisblockrow[-1][0];
  157705. for (bi = 0; bi < ndummy; bi++) {
  157706. thisblockrow[bi][0] = lastDC;
  157707. }
  157708. }
  157709. }
  157710. /* If at end of image, create dummy block rows as needed.
  157711. * The tricky part here is that within each MCU, we want the DC values
  157712. * of the dummy blocks to match the last real block's DC value.
  157713. * This squeezes a few more bytes out of the resulting file...
  157714. */
  157715. if (coef->iMCU_row_num == last_iMCU_row) {
  157716. blocks_across += ndummy; /* include lower right corner */
  157717. MCUs_across = blocks_across / h_samp_factor;
  157718. for (block_row = block_rows; block_row < compptr->v_samp_factor;
  157719. block_row++) {
  157720. thisblockrow = buffer[block_row];
  157721. lastblockrow = buffer[block_row-1];
  157722. jzero_far((void FAR *) thisblockrow,
  157723. (size_t) (blocks_across * SIZEOF(JBLOCK)));
  157724. for (MCUindex = 0; MCUindex < MCUs_across; MCUindex++) {
  157725. lastDC = lastblockrow[h_samp_factor-1][0];
  157726. for (bi = 0; bi < h_samp_factor; bi++) {
  157727. thisblockrow[bi][0] = lastDC;
  157728. }
  157729. thisblockrow += h_samp_factor; /* advance to next MCU in row */
  157730. lastblockrow += h_samp_factor;
  157731. }
  157732. }
  157733. }
  157734. }
  157735. /* NB: compress_output will increment iMCU_row_num if successful.
  157736. * A suspension return will result in redoing all the work above next time.
  157737. */
  157738. /* Emit data to the entropy encoder, sharing code with subsequent passes */
  157739. return compress_output(cinfo, input_buf);
  157740. }
  157741. /*
  157742. * Process some data in subsequent passes of a multi-pass case.
  157743. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  157744. * per call, ie, v_samp_factor block rows for each component in the scan.
  157745. * The data is obtained from the virtual arrays and fed to the entropy coder.
  157746. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  157747. *
  157748. * NB: input_buf is ignored; it is likely to be a NULL pointer.
  157749. */
  157750. METHODDEF(boolean)
  157751. compress_output (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
  157752. {
  157753. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  157754. JDIMENSION MCU_col_num; /* index of current MCU within row */
  157755. int blkn, ci, xindex, yindex, yoffset;
  157756. JDIMENSION start_col;
  157757. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  157758. JBLOCKROW buffer_ptr;
  157759. jpeg_component_info *compptr;
  157760. /* Align the virtual buffers for the components used in this scan.
  157761. * NB: during first pass, this is safe only because the buffers will
  157762. * already be aligned properly, so jmemmgr.c won't need to do any I/O.
  157763. */
  157764. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  157765. compptr = cinfo->cur_comp_info[ci];
  157766. buffer[ci] = (*cinfo->mem->access_virt_barray)
  157767. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  157768. coef->iMCU_row_num * compptr->v_samp_factor,
  157769. (JDIMENSION) compptr->v_samp_factor, FALSE);
  157770. }
  157771. /* Loop to process one whole iMCU row */
  157772. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  157773. yoffset++) {
  157774. for (MCU_col_num = coef->mcu_ctr; MCU_col_num < cinfo->MCUs_per_row;
  157775. MCU_col_num++) {
  157776. /* Construct list of pointers to DCT blocks belonging to this MCU */
  157777. blkn = 0; /* index of current DCT block within MCU */
  157778. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  157779. compptr = cinfo->cur_comp_info[ci];
  157780. start_col = MCU_col_num * compptr->MCU_width;
  157781. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  157782. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  157783. for (xindex = 0; xindex < compptr->MCU_width; xindex++) {
  157784. coef->MCU_buffer[blkn++] = buffer_ptr++;
  157785. }
  157786. }
  157787. }
  157788. /* Try to write the MCU. */
  157789. if (! (*cinfo->entropy->encode_mcu) (cinfo, coef->MCU_buffer)) {
  157790. /* Suspension forced; update state counters and exit */
  157791. coef->MCU_vert_offset = yoffset;
  157792. coef->mcu_ctr = MCU_col_num;
  157793. return FALSE;
  157794. }
  157795. }
  157796. /* Completed an MCU row, but perhaps not an iMCU row */
  157797. coef->mcu_ctr = 0;
  157798. }
  157799. /* Completed the iMCU row, advance counters for next one */
  157800. coef->iMCU_row_num++;
  157801. start_iMCU_row(cinfo);
  157802. return TRUE;
  157803. }
  157804. #endif /* FULL_COEF_BUFFER_SUPPORTED */
  157805. /*
  157806. * Initialize coefficient buffer controller.
  157807. */
  157808. GLOBAL(void)
  157809. jinit_c_coef_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  157810. {
  157811. my_coef_ptr coef;
  157812. coef = (my_coef_ptr)
  157813. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  157814. SIZEOF(my_coef_controller));
  157815. cinfo->coef = (struct jpeg_c_coef_controller *) coef;
  157816. coef->pub.start_pass = start_pass_coef;
  157817. /* Create the coefficient buffer. */
  157818. if (need_full_buffer) {
  157819. #ifdef FULL_COEF_BUFFER_SUPPORTED
  157820. /* Allocate a full-image virtual array for each component, */
  157821. /* padded to a multiple of samp_factor DCT blocks in each direction. */
  157822. int ci;
  157823. jpeg_component_info *compptr;
  157824. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  157825. ci++, compptr++) {
  157826. coef->whole_image[ci] = (*cinfo->mem->request_virt_barray)
  157827. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  157828. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  157829. (long) compptr->h_samp_factor),
  157830. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  157831. (long) compptr->v_samp_factor),
  157832. (JDIMENSION) compptr->v_samp_factor);
  157833. }
  157834. #else
  157835. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  157836. #endif
  157837. } else {
  157838. /* We only need a single-MCU buffer. */
  157839. JBLOCKROW buffer;
  157840. int i;
  157841. buffer = (JBLOCKROW)
  157842. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  157843. C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  157844. for (i = 0; i < C_MAX_BLOCKS_IN_MCU; i++) {
  157845. coef->MCU_buffer[i] = buffer + i;
  157846. }
  157847. coef->whole_image[0] = NULL; /* flag for no virtual arrays */
  157848. }
  157849. }
  157850. /********* End of inlined file: jccoefct.c *********/
  157851. /********* Start of inlined file: jccolor.c *********/
  157852. #define JPEG_INTERNALS
  157853. /* Private subobject */
  157854. typedef struct {
  157855. struct jpeg_color_converter pub; /* public fields */
  157856. /* Private state for RGB->YCC conversion */
  157857. INT32 * rgb_ycc_tab; /* => table for RGB to YCbCr conversion */
  157858. } my_color_converter;
  157859. typedef my_color_converter * my_cconvert_ptr;
  157860. /**************** RGB -> YCbCr conversion: most common case **************/
  157861. /*
  157862. * YCbCr is defined per CCIR 601-1, except that Cb and Cr are
  157863. * normalized to the range 0..MAXJSAMPLE rather than -0.5 .. 0.5.
  157864. * The conversion equations to be implemented are therefore
  157865. * Y = 0.29900 * R + 0.58700 * G + 0.11400 * B
  157866. * Cb = -0.16874 * R - 0.33126 * G + 0.50000 * B + CENTERJSAMPLE
  157867. * Cr = 0.50000 * R - 0.41869 * G - 0.08131 * B + CENTERJSAMPLE
  157868. * (These numbers are derived from TIFF 6.0 section 21, dated 3-June-92.)
  157869. * Note: older versions of the IJG code used a zero offset of MAXJSAMPLE/2,
  157870. * rather than CENTERJSAMPLE, for Cb and Cr. This gave equal positive and
  157871. * negative swings for Cb/Cr, but meant that grayscale values (Cb=Cr=0)
  157872. * were not represented exactly. Now we sacrifice exact representation of
  157873. * maximum red and maximum blue in order to get exact grayscales.
  157874. *
  157875. * To avoid floating-point arithmetic, we represent the fractional constants
  157876. * as integers scaled up by 2^16 (about 4 digits precision); we have to divide
  157877. * the products by 2^16, with appropriate rounding, to get the correct answer.
  157878. *
  157879. * For even more speed, we avoid doing any multiplications in the inner loop
  157880. * by precalculating the constants times R,G,B for all possible values.
  157881. * For 8-bit JSAMPLEs this is very reasonable (only 256 entries per table);
  157882. * for 12-bit samples it is still acceptable. It's not very reasonable for
  157883. * 16-bit samples, but if you want lossless storage you shouldn't be changing
  157884. * colorspace anyway.
  157885. * The CENTERJSAMPLE offsets and the rounding fudge-factor of 0.5 are included
  157886. * in the tables to save adding them separately in the inner loop.
  157887. */
  157888. #define SCALEBITS 16 /* speediest right-shift on some machines */
  157889. #define CBCR_OFFSET ((INT32) CENTERJSAMPLE << SCALEBITS)
  157890. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  157891. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  157892. /* We allocate one big table and divide it up into eight parts, instead of
  157893. * doing eight alloc_small requests. This lets us use a single table base
  157894. * address, which can be held in a register in the inner loops on many
  157895. * machines (more than can hold all eight addresses, anyway).
  157896. */
  157897. #define R_Y_OFF 0 /* offset to R => Y section */
  157898. #define G_Y_OFF (1*(MAXJSAMPLE+1)) /* offset to G => Y section */
  157899. #define B_Y_OFF (2*(MAXJSAMPLE+1)) /* etc. */
  157900. #define R_CB_OFF (3*(MAXJSAMPLE+1))
  157901. #define G_CB_OFF (4*(MAXJSAMPLE+1))
  157902. #define B_CB_OFF (5*(MAXJSAMPLE+1))
  157903. #define R_CR_OFF B_CB_OFF /* B=>Cb, R=>Cr are the same */
  157904. #define G_CR_OFF (6*(MAXJSAMPLE+1))
  157905. #define B_CR_OFF (7*(MAXJSAMPLE+1))
  157906. #define TABLE_SIZE (8*(MAXJSAMPLE+1))
  157907. /*
  157908. * Initialize for RGB->YCC colorspace conversion.
  157909. */
  157910. METHODDEF(void)
  157911. rgb_ycc_start (j_compress_ptr cinfo)
  157912. {
  157913. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  157914. INT32 * rgb_ycc_tab;
  157915. INT32 i;
  157916. /* Allocate and fill in the conversion tables. */
  157917. cconvert->rgb_ycc_tab = rgb_ycc_tab = (INT32 *)
  157918. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  157919. (TABLE_SIZE * SIZEOF(INT32)));
  157920. for (i = 0; i <= MAXJSAMPLE; i++) {
  157921. rgb_ycc_tab[i+R_Y_OFF] = FIX(0.29900) * i;
  157922. rgb_ycc_tab[i+G_Y_OFF] = FIX(0.58700) * i;
  157923. rgb_ycc_tab[i+B_Y_OFF] = FIX(0.11400) * i + ONE_HALF;
  157924. rgb_ycc_tab[i+R_CB_OFF] = (-FIX(0.16874)) * i;
  157925. rgb_ycc_tab[i+G_CB_OFF] = (-FIX(0.33126)) * i;
  157926. /* We use a rounding fudge-factor of 0.5-epsilon for Cb and Cr.
  157927. * This ensures that the maximum output will round to MAXJSAMPLE
  157928. * not MAXJSAMPLE+1, and thus that we don't have to range-limit.
  157929. */
  157930. rgb_ycc_tab[i+B_CB_OFF] = FIX(0.50000) * i + CBCR_OFFSET + ONE_HALF-1;
  157931. /* B=>Cb and R=>Cr tables are the same
  157932. rgb_ycc_tab[i+R_CR_OFF] = FIX(0.50000) * i + CBCR_OFFSET + ONE_HALF-1;
  157933. */
  157934. rgb_ycc_tab[i+G_CR_OFF] = (-FIX(0.41869)) * i;
  157935. rgb_ycc_tab[i+B_CR_OFF] = (-FIX(0.08131)) * i;
  157936. }
  157937. }
  157938. /*
  157939. * Convert some rows of samples to the JPEG colorspace.
  157940. *
  157941. * Note that we change from the application's interleaved-pixel format
  157942. * to our internal noninterleaved, one-plane-per-component format.
  157943. * The input buffer is therefore three times as wide as the output buffer.
  157944. *
  157945. * A starting row offset is provided only for the output buffer. The caller
  157946. * can easily adjust the passed input_buf value to accommodate any row
  157947. * offset required on that side.
  157948. */
  157949. METHODDEF(void)
  157950. rgb_ycc_convert (j_compress_ptr cinfo,
  157951. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  157952. JDIMENSION output_row, int num_rows)
  157953. {
  157954. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  157955. register int r, g, b;
  157956. register INT32 * ctab = cconvert->rgb_ycc_tab;
  157957. register JSAMPROW inptr;
  157958. register JSAMPROW outptr0, outptr1, outptr2;
  157959. register JDIMENSION col;
  157960. JDIMENSION num_cols = cinfo->image_width;
  157961. while (--num_rows >= 0) {
  157962. inptr = *input_buf++;
  157963. outptr0 = output_buf[0][output_row];
  157964. outptr1 = output_buf[1][output_row];
  157965. outptr2 = output_buf[2][output_row];
  157966. output_row++;
  157967. for (col = 0; col < num_cols; col++) {
  157968. r = GETJSAMPLE(inptr[RGB_RED]);
  157969. g = GETJSAMPLE(inptr[RGB_GREEN]);
  157970. b = GETJSAMPLE(inptr[RGB_BLUE]);
  157971. inptr += RGB_PIXELSIZE;
  157972. /* If the inputs are 0..MAXJSAMPLE, the outputs of these equations
  157973. * must be too; we do not need an explicit range-limiting operation.
  157974. * Hence the value being shifted is never negative, and we don't
  157975. * need the general RIGHT_SHIFT macro.
  157976. */
  157977. /* Y */
  157978. outptr0[col] = (JSAMPLE)
  157979. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  157980. >> SCALEBITS);
  157981. /* Cb */
  157982. outptr1[col] = (JSAMPLE)
  157983. ((ctab[r+R_CB_OFF] + ctab[g+G_CB_OFF] + ctab[b+B_CB_OFF])
  157984. >> SCALEBITS);
  157985. /* Cr */
  157986. outptr2[col] = (JSAMPLE)
  157987. ((ctab[r+R_CR_OFF] + ctab[g+G_CR_OFF] + ctab[b+B_CR_OFF])
  157988. >> SCALEBITS);
  157989. }
  157990. }
  157991. }
  157992. /**************** Cases other than RGB -> YCbCr **************/
  157993. /*
  157994. * Convert some rows of samples to the JPEG colorspace.
  157995. * This version handles RGB->grayscale conversion, which is the same
  157996. * as the RGB->Y portion of RGB->YCbCr.
  157997. * We assume rgb_ycc_start has been called (we only use the Y tables).
  157998. */
  157999. METHODDEF(void)
  158000. rgb_gray_convert (j_compress_ptr cinfo,
  158001. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  158002. JDIMENSION output_row, int num_rows)
  158003. {
  158004. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  158005. register int r, g, b;
  158006. register INT32 * ctab = cconvert->rgb_ycc_tab;
  158007. register JSAMPROW inptr;
  158008. register JSAMPROW outptr;
  158009. register JDIMENSION col;
  158010. JDIMENSION num_cols = cinfo->image_width;
  158011. while (--num_rows >= 0) {
  158012. inptr = *input_buf++;
  158013. outptr = output_buf[0][output_row];
  158014. output_row++;
  158015. for (col = 0; col < num_cols; col++) {
  158016. r = GETJSAMPLE(inptr[RGB_RED]);
  158017. g = GETJSAMPLE(inptr[RGB_GREEN]);
  158018. b = GETJSAMPLE(inptr[RGB_BLUE]);
  158019. inptr += RGB_PIXELSIZE;
  158020. /* Y */
  158021. outptr[col] = (JSAMPLE)
  158022. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  158023. >> SCALEBITS);
  158024. }
  158025. }
  158026. }
  158027. /*
  158028. * Convert some rows of samples to the JPEG colorspace.
  158029. * This version handles Adobe-style CMYK->YCCK conversion,
  158030. * where we convert R=1-C, G=1-M, and B=1-Y to YCbCr using the same
  158031. * conversion as above, while passing K (black) unchanged.
  158032. * We assume rgb_ycc_start has been called.
  158033. */
  158034. METHODDEF(void)
  158035. cmyk_ycck_convert (j_compress_ptr cinfo,
  158036. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  158037. JDIMENSION output_row, int num_rows)
  158038. {
  158039. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  158040. register int r, g, b;
  158041. register INT32 * ctab = cconvert->rgb_ycc_tab;
  158042. register JSAMPROW inptr;
  158043. register JSAMPROW outptr0, outptr1, outptr2, outptr3;
  158044. register JDIMENSION col;
  158045. JDIMENSION num_cols = cinfo->image_width;
  158046. while (--num_rows >= 0) {
  158047. inptr = *input_buf++;
  158048. outptr0 = output_buf[0][output_row];
  158049. outptr1 = output_buf[1][output_row];
  158050. outptr2 = output_buf[2][output_row];
  158051. outptr3 = output_buf[3][output_row];
  158052. output_row++;
  158053. for (col = 0; col < num_cols; col++) {
  158054. r = MAXJSAMPLE - GETJSAMPLE(inptr[0]);
  158055. g = MAXJSAMPLE - GETJSAMPLE(inptr[1]);
  158056. b = MAXJSAMPLE - GETJSAMPLE(inptr[2]);
  158057. /* K passes through as-is */
  158058. outptr3[col] = inptr[3]; /* don't need GETJSAMPLE here */
  158059. inptr += 4;
  158060. /* If the inputs are 0..MAXJSAMPLE, the outputs of these equations
  158061. * must be too; we do not need an explicit range-limiting operation.
  158062. * Hence the value being shifted is never negative, and we don't
  158063. * need the general RIGHT_SHIFT macro.
  158064. */
  158065. /* Y */
  158066. outptr0[col] = (JSAMPLE)
  158067. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  158068. >> SCALEBITS);
  158069. /* Cb */
  158070. outptr1[col] = (JSAMPLE)
  158071. ((ctab[r+R_CB_OFF] + ctab[g+G_CB_OFF] + ctab[b+B_CB_OFF])
  158072. >> SCALEBITS);
  158073. /* Cr */
  158074. outptr2[col] = (JSAMPLE)
  158075. ((ctab[r+R_CR_OFF] + ctab[g+G_CR_OFF] + ctab[b+B_CR_OFF])
  158076. >> SCALEBITS);
  158077. }
  158078. }
  158079. }
  158080. /*
  158081. * Convert some rows of samples to the JPEG colorspace.
  158082. * This version handles grayscale output with no conversion.
  158083. * The source can be either plain grayscale or YCbCr (since Y == gray).
  158084. */
  158085. METHODDEF(void)
  158086. grayscale_convert (j_compress_ptr cinfo,
  158087. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  158088. JDIMENSION output_row, int num_rows)
  158089. {
  158090. register JSAMPROW inptr;
  158091. register JSAMPROW outptr;
  158092. register JDIMENSION col;
  158093. JDIMENSION num_cols = cinfo->image_width;
  158094. int instride = cinfo->input_components;
  158095. while (--num_rows >= 0) {
  158096. inptr = *input_buf++;
  158097. outptr = output_buf[0][output_row];
  158098. output_row++;
  158099. for (col = 0; col < num_cols; col++) {
  158100. outptr[col] = inptr[0]; /* don't need GETJSAMPLE() here */
  158101. inptr += instride;
  158102. }
  158103. }
  158104. }
  158105. /*
  158106. * Convert some rows of samples to the JPEG colorspace.
  158107. * This version handles multi-component colorspaces without conversion.
  158108. * We assume input_components == num_components.
  158109. */
  158110. METHODDEF(void)
  158111. null_convert (j_compress_ptr cinfo,
  158112. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  158113. JDIMENSION output_row, int num_rows)
  158114. {
  158115. register JSAMPROW inptr;
  158116. register JSAMPROW outptr;
  158117. register JDIMENSION col;
  158118. register int ci;
  158119. int nc = cinfo->num_components;
  158120. JDIMENSION num_cols = cinfo->image_width;
  158121. while (--num_rows >= 0) {
  158122. /* It seems fastest to make a separate pass for each component. */
  158123. for (ci = 0; ci < nc; ci++) {
  158124. inptr = *input_buf;
  158125. outptr = output_buf[ci][output_row];
  158126. for (col = 0; col < num_cols; col++) {
  158127. outptr[col] = inptr[ci]; /* don't need GETJSAMPLE() here */
  158128. inptr += nc;
  158129. }
  158130. }
  158131. input_buf++;
  158132. output_row++;
  158133. }
  158134. }
  158135. /*
  158136. * Empty method for start_pass.
  158137. */
  158138. METHODDEF(void)
  158139. null_method (j_compress_ptr cinfo)
  158140. {
  158141. /* no work needed */
  158142. }
  158143. /*
  158144. * Module initialization routine for input colorspace conversion.
  158145. */
  158146. GLOBAL(void)
  158147. jinit_color_converter (j_compress_ptr cinfo)
  158148. {
  158149. my_cconvert_ptr cconvert;
  158150. cconvert = (my_cconvert_ptr)
  158151. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  158152. SIZEOF(my_color_converter));
  158153. cinfo->cconvert = (struct jpeg_color_converter *) cconvert;
  158154. /* set start_pass to null method until we find out differently */
  158155. cconvert->pub.start_pass = null_method;
  158156. /* Make sure input_components agrees with in_color_space */
  158157. switch (cinfo->in_color_space) {
  158158. case JCS_GRAYSCALE:
  158159. if (cinfo->input_components != 1)
  158160. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  158161. break;
  158162. case JCS_RGB:
  158163. #if RGB_PIXELSIZE != 3
  158164. if (cinfo->input_components != RGB_PIXELSIZE)
  158165. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  158166. break;
  158167. #endif /* else share code with YCbCr */
  158168. case JCS_YCbCr:
  158169. if (cinfo->input_components != 3)
  158170. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  158171. break;
  158172. case JCS_CMYK:
  158173. case JCS_YCCK:
  158174. if (cinfo->input_components != 4)
  158175. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  158176. break;
  158177. default: /* JCS_UNKNOWN can be anything */
  158178. if (cinfo->input_components < 1)
  158179. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  158180. break;
  158181. }
  158182. /* Check num_components, set conversion method based on requested space */
  158183. switch (cinfo->jpeg_color_space) {
  158184. case JCS_GRAYSCALE:
  158185. if (cinfo->num_components != 1)
  158186. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  158187. if (cinfo->in_color_space == JCS_GRAYSCALE)
  158188. cconvert->pub.color_convert = grayscale_convert;
  158189. else if (cinfo->in_color_space == JCS_RGB) {
  158190. cconvert->pub.start_pass = rgb_ycc_start;
  158191. cconvert->pub.color_convert = rgb_gray_convert;
  158192. } else if (cinfo->in_color_space == JCS_YCbCr)
  158193. cconvert->pub.color_convert = grayscale_convert;
  158194. else
  158195. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  158196. break;
  158197. case JCS_RGB:
  158198. if (cinfo->num_components != 3)
  158199. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  158200. if (cinfo->in_color_space == JCS_RGB && RGB_PIXELSIZE == 3)
  158201. cconvert->pub.color_convert = null_convert;
  158202. else
  158203. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  158204. break;
  158205. case JCS_YCbCr:
  158206. if (cinfo->num_components != 3)
  158207. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  158208. if (cinfo->in_color_space == JCS_RGB) {
  158209. cconvert->pub.start_pass = rgb_ycc_start;
  158210. cconvert->pub.color_convert = rgb_ycc_convert;
  158211. } else if (cinfo->in_color_space == JCS_YCbCr)
  158212. cconvert->pub.color_convert = null_convert;
  158213. else
  158214. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  158215. break;
  158216. case JCS_CMYK:
  158217. if (cinfo->num_components != 4)
  158218. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  158219. if (cinfo->in_color_space == JCS_CMYK)
  158220. cconvert->pub.color_convert = null_convert;
  158221. else
  158222. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  158223. break;
  158224. case JCS_YCCK:
  158225. if (cinfo->num_components != 4)
  158226. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  158227. if (cinfo->in_color_space == JCS_CMYK) {
  158228. cconvert->pub.start_pass = rgb_ycc_start;
  158229. cconvert->pub.color_convert = cmyk_ycck_convert;
  158230. } else if (cinfo->in_color_space == JCS_YCCK)
  158231. cconvert->pub.color_convert = null_convert;
  158232. else
  158233. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  158234. break;
  158235. default: /* allow null conversion of JCS_UNKNOWN */
  158236. if (cinfo->jpeg_color_space != cinfo->in_color_space ||
  158237. cinfo->num_components != cinfo->input_components)
  158238. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  158239. cconvert->pub.color_convert = null_convert;
  158240. break;
  158241. }
  158242. }
  158243. /********* End of inlined file: jccolor.c *********/
  158244. #undef FIX
  158245. /********* Start of inlined file: jcdctmgr.c *********/
  158246. #define JPEG_INTERNALS
  158247. /********* Start of inlined file: jdct.h *********/
  158248. /*
  158249. * A forward DCT routine is given a pointer to a work area of type DCTELEM[];
  158250. * the DCT is to be performed in-place in that buffer. Type DCTELEM is int
  158251. * for 8-bit samples, INT32 for 12-bit samples. (NOTE: Floating-point DCT
  158252. * implementations use an array of type FAST_FLOAT, instead.)
  158253. * The DCT inputs are expected to be signed (range +-CENTERJSAMPLE).
  158254. * The DCT outputs are returned scaled up by a factor of 8; they therefore
  158255. * have a range of +-8K for 8-bit data, +-128K for 12-bit data. This
  158256. * convention improves accuracy in integer implementations and saves some
  158257. * work in floating-point ones.
  158258. * Quantization of the output coefficients is done by jcdctmgr.c.
  158259. */
  158260. #ifndef __jdct_h__
  158261. #define __jdct_h__
  158262. #if BITS_IN_JSAMPLE == 8
  158263. typedef int DCTELEM; /* 16 or 32 bits is fine */
  158264. #else
  158265. typedef INT32 DCTELEM; /* must have 32 bits */
  158266. #endif
  158267. typedef JMETHOD(void, forward_DCT_method_ptr, (DCTELEM * data));
  158268. typedef JMETHOD(void, float_DCT_method_ptr, (FAST_FLOAT * data));
  158269. /*
  158270. * An inverse DCT routine is given a pointer to the input JBLOCK and a pointer
  158271. * to an output sample array. The routine must dequantize the input data as
  158272. * well as perform the IDCT; for dequantization, it uses the multiplier table
  158273. * pointed to by compptr->dct_table. The output data is to be placed into the
  158274. * sample array starting at a specified column. (Any row offset needed will
  158275. * be applied to the array pointer before it is passed to the IDCT code.)
  158276. * Note that the number of samples emitted by the IDCT routine is
  158277. * DCT_scaled_size * DCT_scaled_size.
  158278. */
  158279. /* typedef inverse_DCT_method_ptr is declared in jpegint.h */
  158280. /*
  158281. * Each IDCT routine has its own ideas about the best dct_table element type.
  158282. */
  158283. typedef MULTIPLIER ISLOW_MULT_TYPE; /* short or int, whichever is faster */
  158284. #if BITS_IN_JSAMPLE == 8
  158285. typedef MULTIPLIER IFAST_MULT_TYPE; /* 16 bits is OK, use short if faster */
  158286. #define IFAST_SCALE_BITS 2 /* fractional bits in scale factors */
  158287. #else
  158288. typedef INT32 IFAST_MULT_TYPE; /* need 32 bits for scaled quantizers */
  158289. #define IFAST_SCALE_BITS 13 /* fractional bits in scale factors */
  158290. #endif
  158291. typedef FAST_FLOAT FLOAT_MULT_TYPE; /* preferred floating type */
  158292. /*
  158293. * Each IDCT routine is responsible for range-limiting its results and
  158294. * converting them to unsigned form (0..MAXJSAMPLE). The raw outputs could
  158295. * be quite far out of range if the input data is corrupt, so a bulletproof
  158296. * range-limiting step is required. We use a mask-and-table-lookup method
  158297. * to do the combined operations quickly. See the comments with
  158298. * prepare_range_limit_table (in jdmaster.c) for more info.
  158299. */
  158300. #define IDCT_range_limit(cinfo) ((cinfo)->sample_range_limit + CENTERJSAMPLE)
  158301. #define RANGE_MASK (MAXJSAMPLE * 4 + 3) /* 2 bits wider than legal samples */
  158302. /* Short forms of external names for systems with brain-damaged linkers. */
  158303. #ifdef NEED_SHORT_EXTERNAL_NAMES
  158304. #define jpeg_fdct_islow jFDislow
  158305. #define jpeg_fdct_ifast jFDifast
  158306. #define jpeg_fdct_float jFDfloat
  158307. #define jpeg_idct_islow jRDislow
  158308. #define jpeg_idct_ifast jRDifast
  158309. #define jpeg_idct_float jRDfloat
  158310. #define jpeg_idct_4x4 jRD4x4
  158311. #define jpeg_idct_2x2 jRD2x2
  158312. #define jpeg_idct_1x1 jRD1x1
  158313. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  158314. /* Extern declarations for the forward and inverse DCT routines. */
  158315. EXTERN(void) jpeg_fdct_islow JPP((DCTELEM * data));
  158316. EXTERN(void) jpeg_fdct_ifast JPP((DCTELEM * data));
  158317. EXTERN(void) jpeg_fdct_float JPP((FAST_FLOAT * data));
  158318. EXTERN(void) jpeg_idct_islow
  158319. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  158320. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  158321. EXTERN(void) jpeg_idct_ifast
  158322. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  158323. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  158324. EXTERN(void) jpeg_idct_float
  158325. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  158326. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  158327. EXTERN(void) jpeg_idct_4x4
  158328. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  158329. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  158330. EXTERN(void) jpeg_idct_2x2
  158331. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  158332. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  158333. EXTERN(void) jpeg_idct_1x1
  158334. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  158335. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  158336. /*
  158337. * Macros for handling fixed-point arithmetic; these are used by many
  158338. * but not all of the DCT/IDCT modules.
  158339. *
  158340. * All values are expected to be of type INT32.
  158341. * Fractional constants are scaled left by CONST_BITS bits.
  158342. * CONST_BITS is defined within each module using these macros,
  158343. * and may differ from one module to the next.
  158344. */
  158345. #define ONE ((INT32) 1)
  158346. #define CONST_SCALE (ONE << CONST_BITS)
  158347. /* Convert a positive real constant to an integer scaled by CONST_SCALE.
  158348. * Caution: some C compilers fail to reduce "FIX(constant)" at compile time,
  158349. * thus causing a lot of useless floating-point operations at run time.
  158350. */
  158351. #define FIX(x) ((INT32) ((x) * CONST_SCALE + 0.5))
  158352. /* Descale and correctly round an INT32 value that's scaled by N bits.
  158353. * We assume RIGHT_SHIFT rounds towards minus infinity, so adding
  158354. * the fudge factor is correct for either sign of X.
  158355. */
  158356. #define DESCALE(x,n) RIGHT_SHIFT((x) + (ONE << ((n)-1)), n)
  158357. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  158358. * This macro is used only when the two inputs will actually be no more than
  158359. * 16 bits wide, so that a 16x16->32 bit multiply can be used instead of a
  158360. * full 32x32 multiply. This provides a useful speedup on many machines.
  158361. * Unfortunately there is no way to specify a 16x16->32 multiply portably
  158362. * in C, but some C compilers will do the right thing if you provide the
  158363. * correct combination of casts.
  158364. */
  158365. #ifdef SHORTxSHORT_32 /* may work if 'int' is 32 bits */
  158366. #define MULTIPLY16C16(var,const) (((INT16) (var)) * ((INT16) (const)))
  158367. #endif
  158368. #ifdef SHORTxLCONST_32 /* known to work with Microsoft C 6.0 */
  158369. #define MULTIPLY16C16(var,const) (((INT16) (var)) * ((INT32) (const)))
  158370. #endif
  158371. #ifndef MULTIPLY16C16 /* default definition */
  158372. #define MULTIPLY16C16(var,const) ((var) * (const))
  158373. #endif
  158374. /* Same except both inputs are variables. */
  158375. #ifdef SHORTxSHORT_32 /* may work if 'int' is 32 bits */
  158376. #define MULTIPLY16V16(var1,var2) (((INT16) (var1)) * ((INT16) (var2)))
  158377. #endif
  158378. #ifndef MULTIPLY16V16 /* default definition */
  158379. #define MULTIPLY16V16(var1,var2) ((var1) * (var2))
  158380. #endif
  158381. #endif
  158382. /********* End of inlined file: jdct.h *********/
  158383. /* Private declarations for DCT subsystem */
  158384. /* Private subobject for this module */
  158385. typedef struct {
  158386. struct jpeg_forward_dct pub; /* public fields */
  158387. /* Pointer to the DCT routine actually in use */
  158388. forward_DCT_method_ptr do_dct;
  158389. /* The actual post-DCT divisors --- not identical to the quant table
  158390. * entries, because of scaling (especially for an unnormalized DCT).
  158391. * Each table is given in normal array order.
  158392. */
  158393. DCTELEM * divisors[NUM_QUANT_TBLS];
  158394. #ifdef DCT_FLOAT_SUPPORTED
  158395. /* Same as above for the floating-point case. */
  158396. float_DCT_method_ptr do_float_dct;
  158397. FAST_FLOAT * float_divisors[NUM_QUANT_TBLS];
  158398. #endif
  158399. } my_fdct_controller;
  158400. typedef my_fdct_controller * my_fdct_ptr;
  158401. /*
  158402. * Initialize for a processing pass.
  158403. * Verify that all referenced Q-tables are present, and set up
  158404. * the divisor table for each one.
  158405. * In the current implementation, DCT of all components is done during
  158406. * the first pass, even if only some components will be output in the
  158407. * first scan. Hence all components should be examined here.
  158408. */
  158409. METHODDEF(void)
  158410. start_pass_fdctmgr (j_compress_ptr cinfo)
  158411. {
  158412. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  158413. int ci, qtblno, i;
  158414. jpeg_component_info *compptr;
  158415. JQUANT_TBL * qtbl;
  158416. DCTELEM * dtbl;
  158417. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  158418. ci++, compptr++) {
  158419. qtblno = compptr->quant_tbl_no;
  158420. /* Make sure specified quantization table is present */
  158421. if (qtblno < 0 || qtblno >= NUM_QUANT_TBLS ||
  158422. cinfo->quant_tbl_ptrs[qtblno] == NULL)
  158423. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, qtblno);
  158424. qtbl = cinfo->quant_tbl_ptrs[qtblno];
  158425. /* Compute divisors for this quant table */
  158426. /* We may do this more than once for same table, but it's not a big deal */
  158427. switch (cinfo->dct_method) {
  158428. #ifdef DCT_ISLOW_SUPPORTED
  158429. case JDCT_ISLOW:
  158430. /* For LL&M IDCT method, divisors are equal to raw quantization
  158431. * coefficients multiplied by 8 (to counteract scaling).
  158432. */
  158433. if (fdct->divisors[qtblno] == NULL) {
  158434. fdct->divisors[qtblno] = (DCTELEM *)
  158435. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  158436. DCTSIZE2 * SIZEOF(DCTELEM));
  158437. }
  158438. dtbl = fdct->divisors[qtblno];
  158439. for (i = 0; i < DCTSIZE2; i++) {
  158440. dtbl[i] = ((DCTELEM) qtbl->quantval[i]) << 3;
  158441. }
  158442. break;
  158443. #endif
  158444. #ifdef DCT_IFAST_SUPPORTED
  158445. case JDCT_IFAST:
  158446. {
  158447. /* For AA&N IDCT method, divisors are equal to quantization
  158448. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  158449. * scalefactor[0] = 1
  158450. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  158451. * We apply a further scale factor of 8.
  158452. */
  158453. #define CONST_BITS 14
  158454. static const INT16 aanscales[DCTSIZE2] = {
  158455. /* precomputed values scaled up by 14 bits */
  158456. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  158457. 22725, 31521, 29692, 26722, 22725, 17855, 12299, 6270,
  158458. 21407, 29692, 27969, 25172, 21407, 16819, 11585, 5906,
  158459. 19266, 26722, 25172, 22654, 19266, 15137, 10426, 5315,
  158460. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  158461. 12873, 17855, 16819, 15137, 12873, 10114, 6967, 3552,
  158462. 8867, 12299, 11585, 10426, 8867, 6967, 4799, 2446,
  158463. 4520, 6270, 5906, 5315, 4520, 3552, 2446, 1247
  158464. };
  158465. SHIFT_TEMPS
  158466. if (fdct->divisors[qtblno] == NULL) {
  158467. fdct->divisors[qtblno] = (DCTELEM *)
  158468. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  158469. DCTSIZE2 * SIZEOF(DCTELEM));
  158470. }
  158471. dtbl = fdct->divisors[qtblno];
  158472. for (i = 0; i < DCTSIZE2; i++) {
  158473. dtbl[i] = (DCTELEM)
  158474. DESCALE(MULTIPLY16V16((INT32) qtbl->quantval[i],
  158475. (INT32) aanscales[i]),
  158476. CONST_BITS-3);
  158477. }
  158478. }
  158479. break;
  158480. #endif
  158481. #ifdef DCT_FLOAT_SUPPORTED
  158482. case JDCT_FLOAT:
  158483. {
  158484. /* For float AA&N IDCT method, divisors are equal to quantization
  158485. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  158486. * scalefactor[0] = 1
  158487. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  158488. * We apply a further scale factor of 8.
  158489. * What's actually stored is 1/divisor so that the inner loop can
  158490. * use a multiplication rather than a division.
  158491. */
  158492. FAST_FLOAT * fdtbl;
  158493. int row, col;
  158494. static const double aanscalefactor[DCTSIZE] = {
  158495. 1.0, 1.387039845, 1.306562965, 1.175875602,
  158496. 1.0, 0.785694958, 0.541196100, 0.275899379
  158497. };
  158498. if (fdct->float_divisors[qtblno] == NULL) {
  158499. fdct->float_divisors[qtblno] = (FAST_FLOAT *)
  158500. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  158501. DCTSIZE2 * SIZEOF(FAST_FLOAT));
  158502. }
  158503. fdtbl = fdct->float_divisors[qtblno];
  158504. i = 0;
  158505. for (row = 0; row < DCTSIZE; row++) {
  158506. for (col = 0; col < DCTSIZE; col++) {
  158507. fdtbl[i] = (FAST_FLOAT)
  158508. (1.0 / (((double) qtbl->quantval[i] *
  158509. aanscalefactor[row] * aanscalefactor[col] * 8.0)));
  158510. i++;
  158511. }
  158512. }
  158513. }
  158514. break;
  158515. #endif
  158516. default:
  158517. ERREXIT(cinfo, JERR_NOT_COMPILED);
  158518. break;
  158519. }
  158520. }
  158521. }
  158522. /*
  158523. * Perform forward DCT on one or more blocks of a component.
  158524. *
  158525. * The input samples are taken from the sample_data[] array starting at
  158526. * position start_row/start_col, and moving to the right for any additional
  158527. * blocks. The quantized coefficients are returned in coef_blocks[].
  158528. */
  158529. METHODDEF(void)
  158530. forward_DCT (j_compress_ptr cinfo, jpeg_component_info * compptr,
  158531. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  158532. JDIMENSION start_row, JDIMENSION start_col,
  158533. JDIMENSION num_blocks)
  158534. /* This version is used for integer DCT implementations. */
  158535. {
  158536. /* This routine is heavily used, so it's worth coding it tightly. */
  158537. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  158538. forward_DCT_method_ptr do_dct = fdct->do_dct;
  158539. DCTELEM * divisors = fdct->divisors[compptr->quant_tbl_no];
  158540. DCTELEM workspace[DCTSIZE2]; /* work area for FDCT subroutine */
  158541. JDIMENSION bi;
  158542. sample_data += start_row; /* fold in the vertical offset once */
  158543. for (bi = 0; bi < num_blocks; bi++, start_col += DCTSIZE) {
  158544. /* Load data into workspace, applying unsigned->signed conversion */
  158545. { register DCTELEM *workspaceptr;
  158546. register JSAMPROW elemptr;
  158547. register int elemr;
  158548. workspaceptr = workspace;
  158549. for (elemr = 0; elemr < DCTSIZE; elemr++) {
  158550. elemptr = sample_data[elemr] + start_col;
  158551. #if DCTSIZE == 8 /* unroll the inner loop */
  158552. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  158553. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  158554. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  158555. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  158556. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  158557. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  158558. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  158559. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  158560. #else
  158561. { register int elemc;
  158562. for (elemc = DCTSIZE; elemc > 0; elemc--) {
  158563. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  158564. }
  158565. }
  158566. #endif
  158567. }
  158568. }
  158569. /* Perform the DCT */
  158570. (*do_dct) (workspace);
  158571. /* Quantize/descale the coefficients, and store into coef_blocks[] */
  158572. { register DCTELEM temp, qval;
  158573. register int i;
  158574. register JCOEFPTR output_ptr = coef_blocks[bi];
  158575. for (i = 0; i < DCTSIZE2; i++) {
  158576. qval = divisors[i];
  158577. temp = workspace[i];
  158578. /* Divide the coefficient value by qval, ensuring proper rounding.
  158579. * Since C does not specify the direction of rounding for negative
  158580. * quotients, we have to force the dividend positive for portability.
  158581. *
  158582. * In most files, at least half of the output values will be zero
  158583. * (at default quantization settings, more like three-quarters...)
  158584. * so we should ensure that this case is fast. On many machines,
  158585. * a comparison is enough cheaper than a divide to make a special test
  158586. * a win. Since both inputs will be nonnegative, we need only test
  158587. * for a < b to discover whether a/b is 0.
  158588. * If your machine's division is fast enough, define FAST_DIVIDE.
  158589. */
  158590. #ifdef FAST_DIVIDE
  158591. #define DIVIDE_BY(a,b) a /= b
  158592. #else
  158593. #define DIVIDE_BY(a,b) if (a >= b) a /= b; else a = 0
  158594. #endif
  158595. if (temp < 0) {
  158596. temp = -temp;
  158597. temp += qval>>1; /* for rounding */
  158598. DIVIDE_BY(temp, qval);
  158599. temp = -temp;
  158600. } else {
  158601. temp += qval>>1; /* for rounding */
  158602. DIVIDE_BY(temp, qval);
  158603. }
  158604. output_ptr[i] = (JCOEF) temp;
  158605. }
  158606. }
  158607. }
  158608. }
  158609. #ifdef DCT_FLOAT_SUPPORTED
  158610. METHODDEF(void)
  158611. forward_DCT_float (j_compress_ptr cinfo, jpeg_component_info * compptr,
  158612. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  158613. JDIMENSION start_row, JDIMENSION start_col,
  158614. JDIMENSION num_blocks)
  158615. /* This version is used for floating-point DCT implementations. */
  158616. {
  158617. /* This routine is heavily used, so it's worth coding it tightly. */
  158618. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  158619. float_DCT_method_ptr do_dct = fdct->do_float_dct;
  158620. FAST_FLOAT * divisors = fdct->float_divisors[compptr->quant_tbl_no];
  158621. FAST_FLOAT workspace[DCTSIZE2]; /* work area for FDCT subroutine */
  158622. JDIMENSION bi;
  158623. sample_data += start_row; /* fold in the vertical offset once */
  158624. for (bi = 0; bi < num_blocks; bi++, start_col += DCTSIZE) {
  158625. /* Load data into workspace, applying unsigned->signed conversion */
  158626. { register FAST_FLOAT *workspaceptr;
  158627. register JSAMPROW elemptr;
  158628. register int elemr;
  158629. workspaceptr = workspace;
  158630. for (elemr = 0; elemr < DCTSIZE; elemr++) {
  158631. elemptr = sample_data[elemr] + start_col;
  158632. #if DCTSIZE == 8 /* unroll the inner loop */
  158633. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  158634. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  158635. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  158636. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  158637. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  158638. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  158639. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  158640. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  158641. #else
  158642. { register int elemc;
  158643. for (elemc = DCTSIZE; elemc > 0; elemc--) {
  158644. *workspaceptr++ = (FAST_FLOAT)
  158645. (GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  158646. }
  158647. }
  158648. #endif
  158649. }
  158650. }
  158651. /* Perform the DCT */
  158652. (*do_dct) (workspace);
  158653. /* Quantize/descale the coefficients, and store into coef_blocks[] */
  158654. { register FAST_FLOAT temp;
  158655. register int i;
  158656. register JCOEFPTR output_ptr = coef_blocks[bi];
  158657. for (i = 0; i < DCTSIZE2; i++) {
  158658. /* Apply the quantization and scaling factor */
  158659. temp = workspace[i] * divisors[i];
  158660. /* Round to nearest integer.
  158661. * Since C does not specify the direction of rounding for negative
  158662. * quotients, we have to force the dividend positive for portability.
  158663. * The maximum coefficient size is +-16K (for 12-bit data), so this
  158664. * code should work for either 16-bit or 32-bit ints.
  158665. */
  158666. output_ptr[i] = (JCOEF) ((int) (temp + (FAST_FLOAT) 16384.5) - 16384);
  158667. }
  158668. }
  158669. }
  158670. }
  158671. #endif /* DCT_FLOAT_SUPPORTED */
  158672. /*
  158673. * Initialize FDCT manager.
  158674. */
  158675. GLOBAL(void)
  158676. jinit_forward_dct (j_compress_ptr cinfo)
  158677. {
  158678. my_fdct_ptr fdct;
  158679. int i;
  158680. fdct = (my_fdct_ptr)
  158681. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  158682. SIZEOF(my_fdct_controller));
  158683. cinfo->fdct = (struct jpeg_forward_dct *) fdct;
  158684. fdct->pub.start_pass = start_pass_fdctmgr;
  158685. switch (cinfo->dct_method) {
  158686. #ifdef DCT_ISLOW_SUPPORTED
  158687. case JDCT_ISLOW:
  158688. fdct->pub.forward_DCT = forward_DCT;
  158689. fdct->do_dct = jpeg_fdct_islow;
  158690. break;
  158691. #endif
  158692. #ifdef DCT_IFAST_SUPPORTED
  158693. case JDCT_IFAST:
  158694. fdct->pub.forward_DCT = forward_DCT;
  158695. fdct->do_dct = jpeg_fdct_ifast;
  158696. break;
  158697. #endif
  158698. #ifdef DCT_FLOAT_SUPPORTED
  158699. case JDCT_FLOAT:
  158700. fdct->pub.forward_DCT = forward_DCT_float;
  158701. fdct->do_float_dct = jpeg_fdct_float;
  158702. break;
  158703. #endif
  158704. default:
  158705. ERREXIT(cinfo, JERR_NOT_COMPILED);
  158706. break;
  158707. }
  158708. /* Mark divisor tables unallocated */
  158709. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  158710. fdct->divisors[i] = NULL;
  158711. #ifdef DCT_FLOAT_SUPPORTED
  158712. fdct->float_divisors[i] = NULL;
  158713. #endif
  158714. }
  158715. }
  158716. /********* End of inlined file: jcdctmgr.c *********/
  158717. #undef CONST_BITS
  158718. /********* Start of inlined file: jchuff.c *********/
  158719. #define JPEG_INTERNALS
  158720. /********* Start of inlined file: jchuff.h *********/
  158721. /* The legal range of a DCT coefficient is
  158722. * -1024 .. +1023 for 8-bit data;
  158723. * -16384 .. +16383 for 12-bit data.
  158724. * Hence the magnitude should always fit in 10 or 14 bits respectively.
  158725. */
  158726. #ifndef _jchuff_h_
  158727. #define _jchuff_h_
  158728. #if BITS_IN_JSAMPLE == 8
  158729. #define MAX_COEF_BITS 10
  158730. #else
  158731. #define MAX_COEF_BITS 14
  158732. #endif
  158733. /* Derived data constructed for each Huffman table */
  158734. typedef struct {
  158735. unsigned int ehufco[256]; /* code for each symbol */
  158736. char ehufsi[256]; /* length of code for each symbol */
  158737. /* If no code has been allocated for a symbol S, ehufsi[S] contains 0 */
  158738. } c_derived_tbl;
  158739. /* Short forms of external names for systems with brain-damaged linkers. */
  158740. #ifdef NEED_SHORT_EXTERNAL_NAMES
  158741. #define jpeg_make_c_derived_tbl jMkCDerived
  158742. #define jpeg_gen_optimal_table jGenOptTbl
  158743. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  158744. /* Expand a Huffman table definition into the derived format */
  158745. EXTERN(void) jpeg_make_c_derived_tbl
  158746. JPP((j_compress_ptr cinfo, boolean isDC, int tblno,
  158747. c_derived_tbl ** pdtbl));
  158748. /* Generate an optimal table definition given the specified counts */
  158749. EXTERN(void) jpeg_gen_optimal_table
  158750. JPP((j_compress_ptr cinfo, JHUFF_TBL * htbl, long freq[]));
  158751. #endif
  158752. /********* End of inlined file: jchuff.h *********/
  158753. /* Declarations shared with jcphuff.c */
  158754. /* Expanded entropy encoder object for Huffman encoding.
  158755. *
  158756. * The savable_state subrecord contains fields that change within an MCU,
  158757. * but must not be updated permanently until we complete the MCU.
  158758. */
  158759. typedef struct {
  158760. INT32 put_buffer; /* current bit-accumulation buffer */
  158761. int put_bits; /* # of bits now in it */
  158762. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  158763. } savable_state;
  158764. /* This macro is to work around compilers with missing or broken
  158765. * structure assignment. You'll need to fix this code if you have
  158766. * such a compiler and you change MAX_COMPS_IN_SCAN.
  158767. */
  158768. #ifndef NO_STRUCT_ASSIGN
  158769. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  158770. #else
  158771. #if MAX_COMPS_IN_SCAN == 4
  158772. #define ASSIGN_STATE(dest,src) \
  158773. ((dest).put_buffer = (src).put_buffer, \
  158774. (dest).put_bits = (src).put_bits, \
  158775. (dest).last_dc_val[0] = (src).last_dc_val[0], \
  158776. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  158777. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  158778. (dest).last_dc_val[3] = (src).last_dc_val[3])
  158779. #endif
  158780. #endif
  158781. typedef struct {
  158782. struct jpeg_entropy_encoder pub; /* public fields */
  158783. savable_state saved; /* Bit buffer & DC state at start of MCU */
  158784. /* These fields are NOT loaded into local working state. */
  158785. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  158786. int next_restart_num; /* next restart number to write (0-7) */
  158787. /* Pointers to derived tables (these workspaces have image lifespan) */
  158788. c_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS];
  158789. c_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS];
  158790. #ifdef ENTROPY_OPT_SUPPORTED /* Statistics tables for optimization */
  158791. long * dc_count_ptrs[NUM_HUFF_TBLS];
  158792. long * ac_count_ptrs[NUM_HUFF_TBLS];
  158793. #endif
  158794. } huff_entropy_encoder;
  158795. typedef huff_entropy_encoder * huff_entropy_ptr;
  158796. /* Working state while writing an MCU.
  158797. * This struct contains all the fields that are needed by subroutines.
  158798. */
  158799. typedef struct {
  158800. JOCTET * next_output_byte; /* => next byte to write in buffer */
  158801. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  158802. savable_state cur; /* Current bit buffer & DC state */
  158803. j_compress_ptr cinfo; /* dump_buffer needs access to this */
  158804. } working_state;
  158805. /* Forward declarations */
  158806. METHODDEF(boolean) encode_mcu_huff JPP((j_compress_ptr cinfo,
  158807. JBLOCKROW *MCU_data));
  158808. METHODDEF(void) finish_pass_huff JPP((j_compress_ptr cinfo));
  158809. #ifdef ENTROPY_OPT_SUPPORTED
  158810. METHODDEF(boolean) encode_mcu_gather JPP((j_compress_ptr cinfo,
  158811. JBLOCKROW *MCU_data));
  158812. METHODDEF(void) finish_pass_gather JPP((j_compress_ptr cinfo));
  158813. #endif
  158814. /*
  158815. * Initialize for a Huffman-compressed scan.
  158816. * If gather_statistics is TRUE, we do not output anything during the scan,
  158817. * just count the Huffman symbols used and generate Huffman code tables.
  158818. */
  158819. METHODDEF(void)
  158820. start_pass_huff (j_compress_ptr cinfo, boolean gather_statistics)
  158821. {
  158822. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  158823. int ci, dctbl, actbl;
  158824. jpeg_component_info * compptr;
  158825. if (gather_statistics) {
  158826. #ifdef ENTROPY_OPT_SUPPORTED
  158827. entropy->pub.encode_mcu = encode_mcu_gather;
  158828. entropy->pub.finish_pass = finish_pass_gather;
  158829. #else
  158830. ERREXIT(cinfo, JERR_NOT_COMPILED);
  158831. #endif
  158832. } else {
  158833. entropy->pub.encode_mcu = encode_mcu_huff;
  158834. entropy->pub.finish_pass = finish_pass_huff;
  158835. }
  158836. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  158837. compptr = cinfo->cur_comp_info[ci];
  158838. dctbl = compptr->dc_tbl_no;
  158839. actbl = compptr->ac_tbl_no;
  158840. if (gather_statistics) {
  158841. #ifdef ENTROPY_OPT_SUPPORTED
  158842. /* Check for invalid table indexes */
  158843. /* (make_c_derived_tbl does this in the other path) */
  158844. if (dctbl < 0 || dctbl >= NUM_HUFF_TBLS)
  158845. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, dctbl);
  158846. if (actbl < 0 || actbl >= NUM_HUFF_TBLS)
  158847. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, actbl);
  158848. /* Allocate and zero the statistics tables */
  158849. /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */
  158850. if (entropy->dc_count_ptrs[dctbl] == NULL)
  158851. entropy->dc_count_ptrs[dctbl] = (long *)
  158852. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  158853. 257 * SIZEOF(long));
  158854. MEMZERO(entropy->dc_count_ptrs[dctbl], 257 * SIZEOF(long));
  158855. if (entropy->ac_count_ptrs[actbl] == NULL)
  158856. entropy->ac_count_ptrs[actbl] = (long *)
  158857. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  158858. 257 * SIZEOF(long));
  158859. MEMZERO(entropy->ac_count_ptrs[actbl], 257 * SIZEOF(long));
  158860. #endif
  158861. } else {
  158862. /* Compute derived values for Huffman tables */
  158863. /* We may do this more than once for a table, but it's not expensive */
  158864. jpeg_make_c_derived_tbl(cinfo, TRUE, dctbl,
  158865. & entropy->dc_derived_tbls[dctbl]);
  158866. jpeg_make_c_derived_tbl(cinfo, FALSE, actbl,
  158867. & entropy->ac_derived_tbls[actbl]);
  158868. }
  158869. /* Initialize DC predictions to 0 */
  158870. entropy->saved.last_dc_val[ci] = 0;
  158871. }
  158872. /* Initialize bit buffer to empty */
  158873. entropy->saved.put_buffer = 0;
  158874. entropy->saved.put_bits = 0;
  158875. /* Initialize restart stuff */
  158876. entropy->restarts_to_go = cinfo->restart_interval;
  158877. entropy->next_restart_num = 0;
  158878. }
  158879. /*
  158880. * Compute the derived values for a Huffman table.
  158881. * This routine also performs some validation checks on the table.
  158882. *
  158883. * Note this is also used by jcphuff.c.
  158884. */
  158885. GLOBAL(void)
  158886. jpeg_make_c_derived_tbl (j_compress_ptr cinfo, boolean isDC, int tblno,
  158887. c_derived_tbl ** pdtbl)
  158888. {
  158889. JHUFF_TBL *htbl;
  158890. c_derived_tbl *dtbl;
  158891. int p, i, l, lastp, si, maxsymbol;
  158892. char huffsize[257];
  158893. unsigned int huffcode[257];
  158894. unsigned int code;
  158895. /* Note that huffsize[] and huffcode[] are filled in code-length order,
  158896. * paralleling the order of the symbols themselves in htbl->huffval[].
  158897. */
  158898. /* Find the input Huffman table */
  158899. if (tblno < 0 || tblno >= NUM_HUFF_TBLS)
  158900. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  158901. htbl =
  158902. isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno];
  158903. if (htbl == NULL)
  158904. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  158905. /* Allocate a workspace if we haven't already done so. */
  158906. if (*pdtbl == NULL)
  158907. *pdtbl = (c_derived_tbl *)
  158908. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  158909. SIZEOF(c_derived_tbl));
  158910. dtbl = *pdtbl;
  158911. /* Figure C.1: make table of Huffman code length for each symbol */
  158912. p = 0;
  158913. for (l = 1; l <= 16; l++) {
  158914. i = (int) htbl->bits[l];
  158915. if (i < 0 || p + i > 256) /* protect against table overrun */
  158916. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  158917. while (i--)
  158918. huffsize[p++] = (char) l;
  158919. }
  158920. huffsize[p] = 0;
  158921. lastp = p;
  158922. /* Figure C.2: generate the codes themselves */
  158923. /* We also validate that the counts represent a legal Huffman code tree. */
  158924. code = 0;
  158925. si = huffsize[0];
  158926. p = 0;
  158927. while (huffsize[p]) {
  158928. while (((int) huffsize[p]) == si) {
  158929. huffcode[p++] = code;
  158930. code++;
  158931. }
  158932. /* code is now 1 more than the last code used for codelength si; but
  158933. * it must still fit in si bits, since no code is allowed to be all ones.
  158934. */
  158935. if (((INT32) code) >= (((INT32) 1) << si))
  158936. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  158937. code <<= 1;
  158938. si++;
  158939. }
  158940. /* Figure C.3: generate encoding tables */
  158941. /* These are code and size indexed by symbol value */
  158942. /* Set all codeless symbols to have code length 0;
  158943. * this lets us detect duplicate VAL entries here, and later
  158944. * allows emit_bits to detect any attempt to emit such symbols.
  158945. */
  158946. MEMZERO(dtbl->ehufsi, SIZEOF(dtbl->ehufsi));
  158947. /* This is also a convenient place to check for out-of-range
  158948. * and duplicated VAL entries. We allow 0..255 for AC symbols
  158949. * but only 0..15 for DC. (We could constrain them further
  158950. * based on data depth and mode, but this seems enough.)
  158951. */
  158952. maxsymbol = isDC ? 15 : 255;
  158953. for (p = 0; p < lastp; p++) {
  158954. i = htbl->huffval[p];
  158955. if (i < 0 || i > maxsymbol || dtbl->ehufsi[i])
  158956. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  158957. dtbl->ehufco[i] = huffcode[p];
  158958. dtbl->ehufsi[i] = huffsize[p];
  158959. }
  158960. }
  158961. /* Outputting bytes to the file */
  158962. /* Emit a byte, taking 'action' if must suspend. */
  158963. #define emit_byte(state,val,action) \
  158964. { *(state)->next_output_byte++ = (JOCTET) (val); \
  158965. if (--(state)->free_in_buffer == 0) \
  158966. if (! dump_buffer(state)) \
  158967. { action; } }
  158968. LOCAL(boolean)
  158969. dump_buffer (working_state * state)
  158970. /* Empty the output buffer; return TRUE if successful, FALSE if must suspend */
  158971. {
  158972. struct jpeg_destination_mgr * dest = state->cinfo->dest;
  158973. if (! (*dest->empty_output_buffer) (state->cinfo))
  158974. return FALSE;
  158975. /* After a successful buffer dump, must reset buffer pointers */
  158976. state->next_output_byte = dest->next_output_byte;
  158977. state->free_in_buffer = dest->free_in_buffer;
  158978. return TRUE;
  158979. }
  158980. /* Outputting bits to the file */
  158981. /* Only the right 24 bits of put_buffer are used; the valid bits are
  158982. * left-justified in this part. At most 16 bits can be passed to emit_bits
  158983. * in one call, and we never retain more than 7 bits in put_buffer
  158984. * between calls, so 24 bits are sufficient.
  158985. */
  158986. INLINE
  158987. LOCAL(boolean)
  158988. emit_bits (working_state * state, unsigned int code, int size)
  158989. /* Emit some bits; return TRUE if successful, FALSE if must suspend */
  158990. {
  158991. /* This routine is heavily used, so it's worth coding tightly. */
  158992. register INT32 put_buffer = (INT32) code;
  158993. register int put_bits = state->cur.put_bits;
  158994. /* if size is 0, caller used an invalid Huffman table entry */
  158995. if (size == 0)
  158996. ERREXIT(state->cinfo, JERR_HUFF_MISSING_CODE);
  158997. put_buffer &= (((INT32) 1)<<size) - 1; /* mask off any extra bits in code */
  158998. put_bits += size; /* new number of bits in buffer */
  158999. put_buffer <<= 24 - put_bits; /* align incoming bits */
  159000. put_buffer |= state->cur.put_buffer; /* and merge with old buffer contents */
  159001. while (put_bits >= 8) {
  159002. int c = (int) ((put_buffer >> 16) & 0xFF);
  159003. emit_byte(state, c, return FALSE);
  159004. if (c == 0xFF) { /* need to stuff a zero byte? */
  159005. emit_byte(state, 0, return FALSE);
  159006. }
  159007. put_buffer <<= 8;
  159008. put_bits -= 8;
  159009. }
  159010. state->cur.put_buffer = put_buffer; /* update state variables */
  159011. state->cur.put_bits = put_bits;
  159012. return TRUE;
  159013. }
  159014. LOCAL(boolean)
  159015. flush_bits (working_state * state)
  159016. {
  159017. if (! emit_bits(state, 0x7F, 7)) /* fill any partial byte with ones */
  159018. return FALSE;
  159019. state->cur.put_buffer = 0; /* and reset bit-buffer to empty */
  159020. state->cur.put_bits = 0;
  159021. return TRUE;
  159022. }
  159023. /* Encode a single block's worth of coefficients */
  159024. LOCAL(boolean)
  159025. encode_one_block (working_state * state, JCOEFPTR block, int last_dc_val,
  159026. c_derived_tbl *dctbl, c_derived_tbl *actbl)
  159027. {
  159028. register int temp, temp2;
  159029. register int nbits;
  159030. register int k, r, i;
  159031. /* Encode the DC coefficient difference per section F.1.2.1 */
  159032. temp = temp2 = block[0] - last_dc_val;
  159033. if (temp < 0) {
  159034. temp = -temp; /* temp is abs value of input */
  159035. /* For a negative input, want temp2 = bitwise complement of abs(input) */
  159036. /* This code assumes we are on a two's complement machine */
  159037. temp2--;
  159038. }
  159039. /* Find the number of bits needed for the magnitude of the coefficient */
  159040. nbits = 0;
  159041. while (temp) {
  159042. nbits++;
  159043. temp >>= 1;
  159044. }
  159045. /* Check for out-of-range coefficient values.
  159046. * Since we're encoding a difference, the range limit is twice as much.
  159047. */
  159048. if (nbits > MAX_COEF_BITS+1)
  159049. ERREXIT(state->cinfo, JERR_BAD_DCT_COEF);
  159050. /* Emit the Huffman-coded symbol for the number of bits */
  159051. if (! emit_bits(state, dctbl->ehufco[nbits], dctbl->ehufsi[nbits]))
  159052. return FALSE;
  159053. /* Emit that number of bits of the value, if positive, */
  159054. /* or the complement of its magnitude, if negative. */
  159055. if (nbits) /* emit_bits rejects calls with size 0 */
  159056. if (! emit_bits(state, (unsigned int) temp2, nbits))
  159057. return FALSE;
  159058. /* Encode the AC coefficients per section F.1.2.2 */
  159059. r = 0; /* r = run length of zeros */
  159060. for (k = 1; k < DCTSIZE2; k++) {
  159061. if ((temp = block[jpeg_natural_order[k]]) == 0) {
  159062. r++;
  159063. } else {
  159064. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  159065. while (r > 15) {
  159066. if (! emit_bits(state, actbl->ehufco[0xF0], actbl->ehufsi[0xF0]))
  159067. return FALSE;
  159068. r -= 16;
  159069. }
  159070. temp2 = temp;
  159071. if (temp < 0) {
  159072. temp = -temp; /* temp is abs value of input */
  159073. /* This code assumes we are on a two's complement machine */
  159074. temp2--;
  159075. }
  159076. /* Find the number of bits needed for the magnitude of the coefficient */
  159077. nbits = 1; /* there must be at least one 1 bit */
  159078. while ((temp >>= 1))
  159079. nbits++;
  159080. /* Check for out-of-range coefficient values */
  159081. if (nbits > MAX_COEF_BITS)
  159082. ERREXIT(state->cinfo, JERR_BAD_DCT_COEF);
  159083. /* Emit Huffman symbol for run length / number of bits */
  159084. i = (r << 4) + nbits;
  159085. if (! emit_bits(state, actbl->ehufco[i], actbl->ehufsi[i]))
  159086. return FALSE;
  159087. /* Emit that number of bits of the value, if positive, */
  159088. /* or the complement of its magnitude, if negative. */
  159089. if (! emit_bits(state, (unsigned int) temp2, nbits))
  159090. return FALSE;
  159091. r = 0;
  159092. }
  159093. }
  159094. /* If the last coef(s) were zero, emit an end-of-block code */
  159095. if (r > 0)
  159096. if (! emit_bits(state, actbl->ehufco[0], actbl->ehufsi[0]))
  159097. return FALSE;
  159098. return TRUE;
  159099. }
  159100. /*
  159101. * Emit a restart marker & resynchronize predictions.
  159102. */
  159103. LOCAL(boolean)
  159104. emit_restart (working_state * state, int restart_num)
  159105. {
  159106. int ci;
  159107. if (! flush_bits(state))
  159108. return FALSE;
  159109. emit_byte(state, 0xFF, return FALSE);
  159110. emit_byte(state, JPEG_RST0 + restart_num, return FALSE);
  159111. /* Re-initialize DC predictions to 0 */
  159112. for (ci = 0; ci < state->cinfo->comps_in_scan; ci++)
  159113. state->cur.last_dc_val[ci] = 0;
  159114. /* The restart counter is not updated until we successfully write the MCU. */
  159115. return TRUE;
  159116. }
  159117. /*
  159118. * Encode and output one MCU's worth of Huffman-compressed coefficients.
  159119. */
  159120. METHODDEF(boolean)
  159121. encode_mcu_huff (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  159122. {
  159123. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  159124. working_state state;
  159125. int blkn, ci;
  159126. jpeg_component_info * compptr;
  159127. /* Load up working state */
  159128. state.next_output_byte = cinfo->dest->next_output_byte;
  159129. state.free_in_buffer = cinfo->dest->free_in_buffer;
  159130. ASSIGN_STATE(state.cur, entropy->saved);
  159131. state.cinfo = cinfo;
  159132. /* Emit restart marker if needed */
  159133. if (cinfo->restart_interval) {
  159134. if (entropy->restarts_to_go == 0)
  159135. if (! emit_restart(&state, entropy->next_restart_num))
  159136. return FALSE;
  159137. }
  159138. /* Encode the MCU data blocks */
  159139. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  159140. ci = cinfo->MCU_membership[blkn];
  159141. compptr = cinfo->cur_comp_info[ci];
  159142. if (! encode_one_block(&state,
  159143. MCU_data[blkn][0], state.cur.last_dc_val[ci],
  159144. entropy->dc_derived_tbls[compptr->dc_tbl_no],
  159145. entropy->ac_derived_tbls[compptr->ac_tbl_no]))
  159146. return FALSE;
  159147. /* Update last_dc_val */
  159148. state.cur.last_dc_val[ci] = MCU_data[blkn][0][0];
  159149. }
  159150. /* Completed MCU, so update state */
  159151. cinfo->dest->next_output_byte = state.next_output_byte;
  159152. cinfo->dest->free_in_buffer = state.free_in_buffer;
  159153. ASSIGN_STATE(entropy->saved, state.cur);
  159154. /* Update restart-interval state too */
  159155. if (cinfo->restart_interval) {
  159156. if (entropy->restarts_to_go == 0) {
  159157. entropy->restarts_to_go = cinfo->restart_interval;
  159158. entropy->next_restart_num++;
  159159. entropy->next_restart_num &= 7;
  159160. }
  159161. entropy->restarts_to_go--;
  159162. }
  159163. return TRUE;
  159164. }
  159165. /*
  159166. * Finish up at the end of a Huffman-compressed scan.
  159167. */
  159168. METHODDEF(void)
  159169. finish_pass_huff (j_compress_ptr cinfo)
  159170. {
  159171. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  159172. working_state state;
  159173. /* Load up working state ... flush_bits needs it */
  159174. state.next_output_byte = cinfo->dest->next_output_byte;
  159175. state.free_in_buffer = cinfo->dest->free_in_buffer;
  159176. ASSIGN_STATE(state.cur, entropy->saved);
  159177. state.cinfo = cinfo;
  159178. /* Flush out the last data */
  159179. if (! flush_bits(&state))
  159180. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  159181. /* Update state */
  159182. cinfo->dest->next_output_byte = state.next_output_byte;
  159183. cinfo->dest->free_in_buffer = state.free_in_buffer;
  159184. ASSIGN_STATE(entropy->saved, state.cur);
  159185. }
  159186. /*
  159187. * Huffman coding optimization.
  159188. *
  159189. * We first scan the supplied data and count the number of uses of each symbol
  159190. * that is to be Huffman-coded. (This process MUST agree with the code above.)
  159191. * Then we build a Huffman coding tree for the observed counts.
  159192. * Symbols which are not needed at all for the particular image are not
  159193. * assigned any code, which saves space in the DHT marker as well as in
  159194. * the compressed data.
  159195. */
  159196. #ifdef ENTROPY_OPT_SUPPORTED
  159197. /* Process a single block's worth of coefficients */
  159198. LOCAL(void)
  159199. htest_one_block (j_compress_ptr cinfo, JCOEFPTR block, int last_dc_val,
  159200. long dc_counts[], long ac_counts[])
  159201. {
  159202. register int temp;
  159203. register int nbits;
  159204. register int k, r;
  159205. /* Encode the DC coefficient difference per section F.1.2.1 */
  159206. temp = block[0] - last_dc_val;
  159207. if (temp < 0)
  159208. temp = -temp;
  159209. /* Find the number of bits needed for the magnitude of the coefficient */
  159210. nbits = 0;
  159211. while (temp) {
  159212. nbits++;
  159213. temp >>= 1;
  159214. }
  159215. /* Check for out-of-range coefficient values.
  159216. * Since we're encoding a difference, the range limit is twice as much.
  159217. */
  159218. if (nbits > MAX_COEF_BITS+1)
  159219. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  159220. /* Count the Huffman symbol for the number of bits */
  159221. dc_counts[nbits]++;
  159222. /* Encode the AC coefficients per section F.1.2.2 */
  159223. r = 0; /* r = run length of zeros */
  159224. for (k = 1; k < DCTSIZE2; k++) {
  159225. if ((temp = block[jpeg_natural_order[k]]) == 0) {
  159226. r++;
  159227. } else {
  159228. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  159229. while (r > 15) {
  159230. ac_counts[0xF0]++;
  159231. r -= 16;
  159232. }
  159233. /* Find the number of bits needed for the magnitude of the coefficient */
  159234. if (temp < 0)
  159235. temp = -temp;
  159236. /* Find the number of bits needed for the magnitude of the coefficient */
  159237. nbits = 1; /* there must be at least one 1 bit */
  159238. while ((temp >>= 1))
  159239. nbits++;
  159240. /* Check for out-of-range coefficient values */
  159241. if (nbits > MAX_COEF_BITS)
  159242. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  159243. /* Count Huffman symbol for run length / number of bits */
  159244. ac_counts[(r << 4) + nbits]++;
  159245. r = 0;
  159246. }
  159247. }
  159248. /* If the last coef(s) were zero, emit an end-of-block code */
  159249. if (r > 0)
  159250. ac_counts[0]++;
  159251. }
  159252. /*
  159253. * Trial-encode one MCU's worth of Huffman-compressed coefficients.
  159254. * No data is actually output, so no suspension return is possible.
  159255. */
  159256. METHODDEF(boolean)
  159257. encode_mcu_gather (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  159258. {
  159259. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  159260. int blkn, ci;
  159261. jpeg_component_info * compptr;
  159262. /* Take care of restart intervals if needed */
  159263. if (cinfo->restart_interval) {
  159264. if (entropy->restarts_to_go == 0) {
  159265. /* Re-initialize DC predictions to 0 */
  159266. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  159267. entropy->saved.last_dc_val[ci] = 0;
  159268. /* Update restart state */
  159269. entropy->restarts_to_go = cinfo->restart_interval;
  159270. }
  159271. entropy->restarts_to_go--;
  159272. }
  159273. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  159274. ci = cinfo->MCU_membership[blkn];
  159275. compptr = cinfo->cur_comp_info[ci];
  159276. htest_one_block(cinfo, MCU_data[blkn][0], entropy->saved.last_dc_val[ci],
  159277. entropy->dc_count_ptrs[compptr->dc_tbl_no],
  159278. entropy->ac_count_ptrs[compptr->ac_tbl_no]);
  159279. entropy->saved.last_dc_val[ci] = MCU_data[blkn][0][0];
  159280. }
  159281. return TRUE;
  159282. }
  159283. /*
  159284. * Generate the best Huffman code table for the given counts, fill htbl.
  159285. * Note this is also used by jcphuff.c.
  159286. *
  159287. * The JPEG standard requires that no symbol be assigned a codeword of all
  159288. * one bits (so that padding bits added at the end of a compressed segment
  159289. * can't look like a valid code). Because of the canonical ordering of
  159290. * codewords, this just means that there must be an unused slot in the
  159291. * longest codeword length category. Section K.2 of the JPEG spec suggests
  159292. * reserving such a slot by pretending that symbol 256 is a valid symbol
  159293. * with count 1. In theory that's not optimal; giving it count zero but
  159294. * including it in the symbol set anyway should give a better Huffman code.
  159295. * But the theoretically better code actually seems to come out worse in
  159296. * practice, because it produces more all-ones bytes (which incur stuffed
  159297. * zero bytes in the final file). In any case the difference is tiny.
  159298. *
  159299. * The JPEG standard requires Huffman codes to be no more than 16 bits long.
  159300. * If some symbols have a very small but nonzero probability, the Huffman tree
  159301. * must be adjusted to meet the code length restriction. We currently use
  159302. * the adjustment method suggested in JPEG section K.2. This method is *not*
  159303. * optimal; it may not choose the best possible limited-length code. But
  159304. * typically only very-low-frequency symbols will be given less-than-optimal
  159305. * lengths, so the code is almost optimal. Experimental comparisons against
  159306. * an optimal limited-length-code algorithm indicate that the difference is
  159307. * microscopic --- usually less than a hundredth of a percent of total size.
  159308. * So the extra complexity of an optimal algorithm doesn't seem worthwhile.
  159309. */
  159310. GLOBAL(void)
  159311. jpeg_gen_optimal_table (j_compress_ptr cinfo, JHUFF_TBL * htbl, long freq[])
  159312. {
  159313. #define MAX_CLEN 32 /* assumed maximum initial code length */
  159314. UINT8 bits[MAX_CLEN+1]; /* bits[k] = # of symbols with code length k */
  159315. int codesize[257]; /* codesize[k] = code length of symbol k */
  159316. int others[257]; /* next symbol in current branch of tree */
  159317. int c1, c2;
  159318. int p, i, j;
  159319. long v;
  159320. /* This algorithm is explained in section K.2 of the JPEG standard */
  159321. MEMZERO(bits, SIZEOF(bits));
  159322. MEMZERO(codesize, SIZEOF(codesize));
  159323. for (i = 0; i < 257; i++)
  159324. others[i] = -1; /* init links to empty */
  159325. freq[256] = 1; /* make sure 256 has a nonzero count */
  159326. /* Including the pseudo-symbol 256 in the Huffman procedure guarantees
  159327. * that no real symbol is given code-value of all ones, because 256
  159328. * will be placed last in the largest codeword category.
  159329. */
  159330. /* Huffman's basic algorithm to assign optimal code lengths to symbols */
  159331. for (;;) {
  159332. /* Find the smallest nonzero frequency, set c1 = its symbol */
  159333. /* In case of ties, take the larger symbol number */
  159334. c1 = -1;
  159335. v = 1000000000L;
  159336. for (i = 0; i <= 256; i++) {
  159337. if (freq[i] && freq[i] <= v) {
  159338. v = freq[i];
  159339. c1 = i;
  159340. }
  159341. }
  159342. /* Find the next smallest nonzero frequency, set c2 = its symbol */
  159343. /* In case of ties, take the larger symbol number */
  159344. c2 = -1;
  159345. v = 1000000000L;
  159346. for (i = 0; i <= 256; i++) {
  159347. if (freq[i] && freq[i] <= v && i != c1) {
  159348. v = freq[i];
  159349. c2 = i;
  159350. }
  159351. }
  159352. /* Done if we've merged everything into one frequency */
  159353. if (c2 < 0)
  159354. break;
  159355. /* Else merge the two counts/trees */
  159356. freq[c1] += freq[c2];
  159357. freq[c2] = 0;
  159358. /* Increment the codesize of everything in c1's tree branch */
  159359. codesize[c1]++;
  159360. while (others[c1] >= 0) {
  159361. c1 = others[c1];
  159362. codesize[c1]++;
  159363. }
  159364. others[c1] = c2; /* chain c2 onto c1's tree branch */
  159365. /* Increment the codesize of everything in c2's tree branch */
  159366. codesize[c2]++;
  159367. while (others[c2] >= 0) {
  159368. c2 = others[c2];
  159369. codesize[c2]++;
  159370. }
  159371. }
  159372. /* Now count the number of symbols of each code length */
  159373. for (i = 0; i <= 256; i++) {
  159374. if (codesize[i]) {
  159375. /* The JPEG standard seems to think that this can't happen, */
  159376. /* but I'm paranoid... */
  159377. if (codesize[i] > MAX_CLEN)
  159378. ERREXIT(cinfo, JERR_HUFF_CLEN_OVERFLOW);
  159379. bits[codesize[i]]++;
  159380. }
  159381. }
  159382. /* JPEG doesn't allow symbols with code lengths over 16 bits, so if the pure
  159383. * Huffman procedure assigned any such lengths, we must adjust the coding.
  159384. * Here is what the JPEG spec says about how this next bit works:
  159385. * Since symbols are paired for the longest Huffman code, the symbols are
  159386. * removed from this length category two at a time. The prefix for the pair
  159387. * (which is one bit shorter) is allocated to one of the pair; then,
  159388. * skipping the BITS entry for that prefix length, a code word from the next
  159389. * shortest nonzero BITS entry is converted into a prefix for two code words
  159390. * one bit longer.
  159391. */
  159392. for (i = MAX_CLEN; i > 16; i--) {
  159393. while (bits[i] > 0) {
  159394. j = i - 2; /* find length of new prefix to be used */
  159395. while (bits[j] == 0)
  159396. j--;
  159397. bits[i] -= 2; /* remove two symbols */
  159398. bits[i-1]++; /* one goes in this length */
  159399. bits[j+1] += 2; /* two new symbols in this length */
  159400. bits[j]--; /* symbol of this length is now a prefix */
  159401. }
  159402. }
  159403. /* Remove the count for the pseudo-symbol 256 from the largest codelength */
  159404. while (bits[i] == 0) /* find largest codelength still in use */
  159405. i--;
  159406. bits[i]--;
  159407. /* Return final symbol counts (only for lengths 0..16) */
  159408. MEMCOPY(htbl->bits, bits, SIZEOF(htbl->bits));
  159409. /* Return a list of the symbols sorted by code length */
  159410. /* It's not real clear to me why we don't need to consider the codelength
  159411. * changes made above, but the JPEG spec seems to think this works.
  159412. */
  159413. p = 0;
  159414. for (i = 1; i <= MAX_CLEN; i++) {
  159415. for (j = 0; j <= 255; j++) {
  159416. if (codesize[j] == i) {
  159417. htbl->huffval[p] = (UINT8) j;
  159418. p++;
  159419. }
  159420. }
  159421. }
  159422. /* Set sent_table FALSE so updated table will be written to JPEG file. */
  159423. htbl->sent_table = FALSE;
  159424. }
  159425. /*
  159426. * Finish up a statistics-gathering pass and create the new Huffman tables.
  159427. */
  159428. METHODDEF(void)
  159429. finish_pass_gather (j_compress_ptr cinfo)
  159430. {
  159431. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  159432. int ci, dctbl, actbl;
  159433. jpeg_component_info * compptr;
  159434. JHUFF_TBL **htblptr;
  159435. boolean did_dc[NUM_HUFF_TBLS];
  159436. boolean did_ac[NUM_HUFF_TBLS];
  159437. /* It's important not to apply jpeg_gen_optimal_table more than once
  159438. * per table, because it clobbers the input frequency counts!
  159439. */
  159440. MEMZERO(did_dc, SIZEOF(did_dc));
  159441. MEMZERO(did_ac, SIZEOF(did_ac));
  159442. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  159443. compptr = cinfo->cur_comp_info[ci];
  159444. dctbl = compptr->dc_tbl_no;
  159445. actbl = compptr->ac_tbl_no;
  159446. if (! did_dc[dctbl]) {
  159447. htblptr = & cinfo->dc_huff_tbl_ptrs[dctbl];
  159448. if (*htblptr == NULL)
  159449. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  159450. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->dc_count_ptrs[dctbl]);
  159451. did_dc[dctbl] = TRUE;
  159452. }
  159453. if (! did_ac[actbl]) {
  159454. htblptr = & cinfo->ac_huff_tbl_ptrs[actbl];
  159455. if (*htblptr == NULL)
  159456. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  159457. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->ac_count_ptrs[actbl]);
  159458. did_ac[actbl] = TRUE;
  159459. }
  159460. }
  159461. }
  159462. #endif /* ENTROPY_OPT_SUPPORTED */
  159463. /*
  159464. * Module initialization routine for Huffman entropy encoding.
  159465. */
  159466. GLOBAL(void)
  159467. jinit_huff_encoder (j_compress_ptr cinfo)
  159468. {
  159469. huff_entropy_ptr entropy;
  159470. int i;
  159471. entropy = (huff_entropy_ptr)
  159472. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  159473. SIZEOF(huff_entropy_encoder));
  159474. cinfo->entropy = (struct jpeg_entropy_encoder *) entropy;
  159475. entropy->pub.start_pass = start_pass_huff;
  159476. /* Mark tables unallocated */
  159477. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  159478. entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
  159479. #ifdef ENTROPY_OPT_SUPPORTED
  159480. entropy->dc_count_ptrs[i] = entropy->ac_count_ptrs[i] = NULL;
  159481. #endif
  159482. }
  159483. }
  159484. /********* End of inlined file: jchuff.c *********/
  159485. #undef emit_byte
  159486. /********* Start of inlined file: jcinit.c *********/
  159487. #define JPEG_INTERNALS
  159488. /*
  159489. * Master selection of compression modules.
  159490. * This is done once at the start of processing an image. We determine
  159491. * which modules will be used and give them appropriate initialization calls.
  159492. */
  159493. GLOBAL(void)
  159494. jinit_compress_master (j_compress_ptr cinfo)
  159495. {
  159496. /* Initialize master control (includes parameter checking/processing) */
  159497. jinit_c_master_control(cinfo, FALSE /* full compression */);
  159498. /* Preprocessing */
  159499. if (! cinfo->raw_data_in) {
  159500. jinit_color_converter(cinfo);
  159501. jinit_downsampler(cinfo);
  159502. jinit_c_prep_controller(cinfo, FALSE /* never need full buffer here */);
  159503. }
  159504. /* Forward DCT */
  159505. jinit_forward_dct(cinfo);
  159506. /* Entropy encoding: either Huffman or arithmetic coding. */
  159507. if (cinfo->arith_code) {
  159508. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  159509. } else {
  159510. if (cinfo->progressive_mode) {
  159511. #ifdef C_PROGRESSIVE_SUPPORTED
  159512. jinit_phuff_encoder(cinfo);
  159513. #else
  159514. ERREXIT(cinfo, JERR_NOT_COMPILED);
  159515. #endif
  159516. } else
  159517. jinit_huff_encoder(cinfo);
  159518. }
  159519. /* Need a full-image coefficient buffer in any multi-pass mode. */
  159520. jinit_c_coef_controller(cinfo,
  159521. (boolean) (cinfo->num_scans > 1 || cinfo->optimize_coding));
  159522. jinit_c_main_controller(cinfo, FALSE /* never need full buffer here */);
  159523. jinit_marker_writer(cinfo);
  159524. /* We can now tell the memory manager to allocate virtual arrays. */
  159525. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  159526. /* Write the datastream header (SOI) immediately.
  159527. * Frame and scan headers are postponed till later.
  159528. * This lets application insert special markers after the SOI.
  159529. */
  159530. (*cinfo->marker->write_file_header) (cinfo);
  159531. }
  159532. /********* End of inlined file: jcinit.c *********/
  159533. /********* Start of inlined file: jcmainct.c *********/
  159534. #define JPEG_INTERNALS
  159535. /* Note: currently, there is no operating mode in which a full-image buffer
  159536. * is needed at this step. If there were, that mode could not be used with
  159537. * "raw data" input, since this module is bypassed in that case. However,
  159538. * we've left the code here for possible use in special applications.
  159539. */
  159540. #undef FULL_MAIN_BUFFER_SUPPORTED
  159541. /* Private buffer controller object */
  159542. typedef struct {
  159543. struct jpeg_c_main_controller pub; /* public fields */
  159544. JDIMENSION cur_iMCU_row; /* number of current iMCU row */
  159545. JDIMENSION rowgroup_ctr; /* counts row groups received in iMCU row */
  159546. boolean suspended; /* remember if we suspended output */
  159547. J_BUF_MODE pass_mode; /* current operating mode */
  159548. /* If using just a strip buffer, this points to the entire set of buffers
  159549. * (we allocate one for each component). In the full-image case, this
  159550. * points to the currently accessible strips of the virtual arrays.
  159551. */
  159552. JSAMPARRAY buffer[MAX_COMPONENTS];
  159553. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  159554. /* If using full-image storage, this array holds pointers to virtual-array
  159555. * control blocks for each component. Unused if not full-image storage.
  159556. */
  159557. jvirt_sarray_ptr whole_image[MAX_COMPONENTS];
  159558. #endif
  159559. } my_main_controller;
  159560. typedef my_main_controller * my_main_ptr;
  159561. /* Forward declarations */
  159562. METHODDEF(void) process_data_simple_main
  159563. JPP((j_compress_ptr cinfo, JSAMPARRAY input_buf,
  159564. JDIMENSION *in_row_ctr, JDIMENSION in_rows_avail));
  159565. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  159566. METHODDEF(void) process_data_buffer_main
  159567. JPP((j_compress_ptr cinfo, JSAMPARRAY input_buf,
  159568. JDIMENSION *in_row_ctr, JDIMENSION in_rows_avail));
  159569. #endif
  159570. /*
  159571. * Initialize for a processing pass.
  159572. */
  159573. METHODDEF(void)
  159574. start_pass_main (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  159575. {
  159576. my_main_ptr main_ = (my_main_ptr) cinfo->main;
  159577. /* Do nothing in raw-data mode. */
  159578. if (cinfo->raw_data_in)
  159579. return;
  159580. main_->cur_iMCU_row = 0; /* initialize counters */
  159581. main_->rowgroup_ctr = 0;
  159582. main_->suspended = FALSE;
  159583. main_->pass_mode = pass_mode; /* save mode for use by process_data */
  159584. switch (pass_mode) {
  159585. case JBUF_PASS_THRU:
  159586. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  159587. if (main_->whole_image[0] != NULL)
  159588. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  159589. #endif
  159590. main_->pub.process_data = process_data_simple_main;
  159591. break;
  159592. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  159593. case JBUF_SAVE_SOURCE:
  159594. case JBUF_CRANK_DEST:
  159595. case JBUF_SAVE_AND_PASS:
  159596. if (main_->whole_image[0] == NULL)
  159597. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  159598. main_->pub.process_data = process_data_buffer_main;
  159599. break;
  159600. #endif
  159601. default:
  159602. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  159603. break;
  159604. }
  159605. }
  159606. /*
  159607. * Process some data.
  159608. * This routine handles the simple pass-through mode,
  159609. * where we have only a strip buffer.
  159610. */
  159611. METHODDEF(void)
  159612. process_data_simple_main (j_compress_ptr cinfo,
  159613. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  159614. JDIMENSION in_rows_avail)
  159615. {
  159616. my_main_ptr main_ = (my_main_ptr) cinfo->main;
  159617. while (main_->cur_iMCU_row < cinfo->total_iMCU_rows) {
  159618. /* Read input data if we haven't filled the main buffer yet */
  159619. if (main_->rowgroup_ctr < DCTSIZE)
  159620. (*cinfo->prep->pre_process_data) (cinfo,
  159621. input_buf, in_row_ctr, in_rows_avail,
  159622. main_->buffer, &main_->rowgroup_ctr,
  159623. (JDIMENSION) DCTSIZE);
  159624. /* If we don't have a full iMCU row buffered, return to application for
  159625. * more data. Note that preprocessor will always pad to fill the iMCU row
  159626. * at the bottom of the image.
  159627. */
  159628. if (main_->rowgroup_ctr != DCTSIZE)
  159629. return;
  159630. /* Send the completed row to the compressor */
  159631. if (! (*cinfo->coef->compress_data) (cinfo, main_->buffer)) {
  159632. /* If compressor did not consume the whole row, then we must need to
  159633. * suspend processing and return to the application. In this situation
  159634. * we pretend we didn't yet consume the last input row; otherwise, if
  159635. * it happened to be the last row of the image, the application would
  159636. * think we were done.
  159637. */
  159638. if (! main_->suspended) {
  159639. (*in_row_ctr)--;
  159640. main_->suspended = TRUE;
  159641. }
  159642. return;
  159643. }
  159644. /* We did finish the row. Undo our little suspension hack if a previous
  159645. * call suspended; then mark the main buffer empty.
  159646. */
  159647. if (main_->suspended) {
  159648. (*in_row_ctr)++;
  159649. main_->suspended = FALSE;
  159650. }
  159651. main_->rowgroup_ctr = 0;
  159652. main_->cur_iMCU_row++;
  159653. }
  159654. }
  159655. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  159656. /*
  159657. * Process some data.
  159658. * This routine handles all of the modes that use a full-size buffer.
  159659. */
  159660. METHODDEF(void)
  159661. process_data_buffer_main (j_compress_ptr cinfo,
  159662. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  159663. JDIMENSION in_rows_avail)
  159664. {
  159665. my_main_ptr main = (my_main_ptr) cinfo->main;
  159666. int ci;
  159667. jpeg_component_info *compptr;
  159668. boolean writing = (main->pass_mode != JBUF_CRANK_DEST);
  159669. while (main->cur_iMCU_row < cinfo->total_iMCU_rows) {
  159670. /* Realign the virtual buffers if at the start of an iMCU row. */
  159671. if (main->rowgroup_ctr == 0) {
  159672. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  159673. ci++, compptr++) {
  159674. main->buffer[ci] = (*cinfo->mem->access_virt_sarray)
  159675. ((j_common_ptr) cinfo, main->whole_image[ci],
  159676. main->cur_iMCU_row * (compptr->v_samp_factor * DCTSIZE),
  159677. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE), writing);
  159678. }
  159679. /* In a read pass, pretend we just read some source data. */
  159680. if (! writing) {
  159681. *in_row_ctr += cinfo->max_v_samp_factor * DCTSIZE;
  159682. main->rowgroup_ctr = DCTSIZE;
  159683. }
  159684. }
  159685. /* If a write pass, read input data until the current iMCU row is full. */
  159686. /* Note: preprocessor will pad if necessary to fill the last iMCU row. */
  159687. if (writing) {
  159688. (*cinfo->prep->pre_process_data) (cinfo,
  159689. input_buf, in_row_ctr, in_rows_avail,
  159690. main->buffer, &main->rowgroup_ctr,
  159691. (JDIMENSION) DCTSIZE);
  159692. /* Return to application if we need more data to fill the iMCU row. */
  159693. if (main->rowgroup_ctr < DCTSIZE)
  159694. return;
  159695. }
  159696. /* Emit data, unless this is a sink-only pass. */
  159697. if (main->pass_mode != JBUF_SAVE_SOURCE) {
  159698. if (! (*cinfo->coef->compress_data) (cinfo, main->buffer)) {
  159699. /* If compressor did not consume the whole row, then we must need to
  159700. * suspend processing and return to the application. In this situation
  159701. * we pretend we didn't yet consume the last input row; otherwise, if
  159702. * it happened to be the last row of the image, the application would
  159703. * think we were done.
  159704. */
  159705. if (! main->suspended) {
  159706. (*in_row_ctr)--;
  159707. main->suspended = TRUE;
  159708. }
  159709. return;
  159710. }
  159711. /* We did finish the row. Undo our little suspension hack if a previous
  159712. * call suspended; then mark the main buffer empty.
  159713. */
  159714. if (main->suspended) {
  159715. (*in_row_ctr)++;
  159716. main->suspended = FALSE;
  159717. }
  159718. }
  159719. /* If get here, we are done with this iMCU row. Mark buffer empty. */
  159720. main->rowgroup_ctr = 0;
  159721. main->cur_iMCU_row++;
  159722. }
  159723. }
  159724. #endif /* FULL_MAIN_BUFFER_SUPPORTED */
  159725. /*
  159726. * Initialize main buffer controller.
  159727. */
  159728. GLOBAL(void)
  159729. jinit_c_main_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  159730. {
  159731. my_main_ptr main_;
  159732. int ci;
  159733. jpeg_component_info *compptr;
  159734. main_ = (my_main_ptr)
  159735. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  159736. SIZEOF(my_main_controller));
  159737. cinfo->main = (struct jpeg_c_main_controller *) main_;
  159738. main_->pub.start_pass = start_pass_main;
  159739. /* We don't need to create a buffer in raw-data mode. */
  159740. if (cinfo->raw_data_in)
  159741. return;
  159742. /* Create the buffer. It holds downsampled data, so each component
  159743. * may be of a different size.
  159744. */
  159745. if (need_full_buffer) {
  159746. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  159747. /* Allocate a full-image virtual array for each component */
  159748. /* Note we pad the bottom to a multiple of the iMCU height */
  159749. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  159750. ci++, compptr++) {
  159751. main->whole_image[ci] = (*cinfo->mem->request_virt_sarray)
  159752. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  159753. compptr->width_in_blocks * DCTSIZE,
  159754. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  159755. (long) compptr->v_samp_factor) * DCTSIZE,
  159756. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE));
  159757. }
  159758. #else
  159759. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  159760. #endif
  159761. } else {
  159762. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  159763. main_->whole_image[0] = NULL; /* flag for no virtual arrays */
  159764. #endif
  159765. /* Allocate a strip buffer for each component */
  159766. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  159767. ci++, compptr++) {
  159768. main_->buffer[ci] = (*cinfo->mem->alloc_sarray)
  159769. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  159770. compptr->width_in_blocks * DCTSIZE,
  159771. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE));
  159772. }
  159773. }
  159774. }
  159775. /********* End of inlined file: jcmainct.c *********/
  159776. /********* Start of inlined file: jcmarker.c *********/
  159777. #define JPEG_INTERNALS
  159778. /* Private state */
  159779. typedef struct {
  159780. struct jpeg_marker_writer pub; /* public fields */
  159781. unsigned int last_restart_interval; /* last DRI value emitted; 0 after SOI */
  159782. } my_marker_writer;
  159783. typedef my_marker_writer * my_marker_ptr;
  159784. /*
  159785. * Basic output routines.
  159786. *
  159787. * Note that we do not support suspension while writing a marker.
  159788. * Therefore, an application using suspension must ensure that there is
  159789. * enough buffer space for the initial markers (typ. 600-700 bytes) before
  159790. * calling jpeg_start_compress, and enough space to write the trailing EOI
  159791. * (a few bytes) before calling jpeg_finish_compress. Multipass compression
  159792. * modes are not supported at all with suspension, so those two are the only
  159793. * points where markers will be written.
  159794. */
  159795. LOCAL(void)
  159796. emit_byte (j_compress_ptr cinfo, int val)
  159797. /* Emit a byte */
  159798. {
  159799. struct jpeg_destination_mgr * dest = cinfo->dest;
  159800. *(dest->next_output_byte)++ = (JOCTET) val;
  159801. if (--dest->free_in_buffer == 0) {
  159802. if (! (*dest->empty_output_buffer) (cinfo))
  159803. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  159804. }
  159805. }
  159806. LOCAL(void)
  159807. emit_marker (j_compress_ptr cinfo, JPEG_MARKER mark)
  159808. /* Emit a marker code */
  159809. {
  159810. emit_byte(cinfo, 0xFF);
  159811. emit_byte(cinfo, (int) mark);
  159812. }
  159813. LOCAL(void)
  159814. emit_2bytes (j_compress_ptr cinfo, int value)
  159815. /* Emit a 2-byte integer; these are always MSB first in JPEG files */
  159816. {
  159817. emit_byte(cinfo, (value >> 8) & 0xFF);
  159818. emit_byte(cinfo, value & 0xFF);
  159819. }
  159820. /*
  159821. * Routines to write specific marker types.
  159822. */
  159823. LOCAL(int)
  159824. emit_dqt (j_compress_ptr cinfo, int index)
  159825. /* Emit a DQT marker */
  159826. /* Returns the precision used (0 = 8bits, 1 = 16bits) for baseline checking */
  159827. {
  159828. JQUANT_TBL * qtbl = cinfo->quant_tbl_ptrs[index];
  159829. int prec;
  159830. int i;
  159831. if (qtbl == NULL)
  159832. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, index);
  159833. prec = 0;
  159834. for (i = 0; i < DCTSIZE2; i++) {
  159835. if (qtbl->quantval[i] > 255)
  159836. prec = 1;
  159837. }
  159838. if (! qtbl->sent_table) {
  159839. emit_marker(cinfo, M_DQT);
  159840. emit_2bytes(cinfo, prec ? DCTSIZE2*2 + 1 + 2 : DCTSIZE2 + 1 + 2);
  159841. emit_byte(cinfo, index + (prec<<4));
  159842. for (i = 0; i < DCTSIZE2; i++) {
  159843. /* The table entries must be emitted in zigzag order. */
  159844. unsigned int qval = qtbl->quantval[jpeg_natural_order[i]];
  159845. if (prec)
  159846. emit_byte(cinfo, (int) (qval >> 8));
  159847. emit_byte(cinfo, (int) (qval & 0xFF));
  159848. }
  159849. qtbl->sent_table = TRUE;
  159850. }
  159851. return prec;
  159852. }
  159853. LOCAL(void)
  159854. emit_dht (j_compress_ptr cinfo, int index, boolean is_ac)
  159855. /* Emit a DHT marker */
  159856. {
  159857. JHUFF_TBL * htbl;
  159858. int length, i;
  159859. if (is_ac) {
  159860. htbl = cinfo->ac_huff_tbl_ptrs[index];
  159861. index += 0x10; /* output index has AC bit set */
  159862. } else {
  159863. htbl = cinfo->dc_huff_tbl_ptrs[index];
  159864. }
  159865. if (htbl == NULL)
  159866. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, index);
  159867. if (! htbl->sent_table) {
  159868. emit_marker(cinfo, M_DHT);
  159869. length = 0;
  159870. for (i = 1; i <= 16; i++)
  159871. length += htbl->bits[i];
  159872. emit_2bytes(cinfo, length + 2 + 1 + 16);
  159873. emit_byte(cinfo, index);
  159874. for (i = 1; i <= 16; i++)
  159875. emit_byte(cinfo, htbl->bits[i]);
  159876. for (i = 0; i < length; i++)
  159877. emit_byte(cinfo, htbl->huffval[i]);
  159878. htbl->sent_table = TRUE;
  159879. }
  159880. }
  159881. LOCAL(void)
  159882. emit_dac (j_compress_ptr cinfo)
  159883. /* Emit a DAC marker */
  159884. /* Since the useful info is so small, we want to emit all the tables in */
  159885. /* one DAC marker. Therefore this routine does its own scan of the table. */
  159886. {
  159887. #ifdef C_ARITH_CODING_SUPPORTED
  159888. char dc_in_use[NUM_ARITH_TBLS];
  159889. char ac_in_use[NUM_ARITH_TBLS];
  159890. int length, i;
  159891. jpeg_component_info *compptr;
  159892. for (i = 0; i < NUM_ARITH_TBLS; i++)
  159893. dc_in_use[i] = ac_in_use[i] = 0;
  159894. for (i = 0; i < cinfo->comps_in_scan; i++) {
  159895. compptr = cinfo->cur_comp_info[i];
  159896. dc_in_use[compptr->dc_tbl_no] = 1;
  159897. ac_in_use[compptr->ac_tbl_no] = 1;
  159898. }
  159899. length = 0;
  159900. for (i = 0; i < NUM_ARITH_TBLS; i++)
  159901. length += dc_in_use[i] + ac_in_use[i];
  159902. emit_marker(cinfo, M_DAC);
  159903. emit_2bytes(cinfo, length*2 + 2);
  159904. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  159905. if (dc_in_use[i]) {
  159906. emit_byte(cinfo, i);
  159907. emit_byte(cinfo, cinfo->arith_dc_L[i] + (cinfo->arith_dc_U[i]<<4));
  159908. }
  159909. if (ac_in_use[i]) {
  159910. emit_byte(cinfo, i + 0x10);
  159911. emit_byte(cinfo, cinfo->arith_ac_K[i]);
  159912. }
  159913. }
  159914. #endif /* C_ARITH_CODING_SUPPORTED */
  159915. }
  159916. LOCAL(void)
  159917. emit_dri (j_compress_ptr cinfo)
  159918. /* Emit a DRI marker */
  159919. {
  159920. emit_marker(cinfo, M_DRI);
  159921. emit_2bytes(cinfo, 4); /* fixed length */
  159922. emit_2bytes(cinfo, (int) cinfo->restart_interval);
  159923. }
  159924. LOCAL(void)
  159925. emit_sof (j_compress_ptr cinfo, JPEG_MARKER code)
  159926. /* Emit a SOF marker */
  159927. {
  159928. int ci;
  159929. jpeg_component_info *compptr;
  159930. emit_marker(cinfo, code);
  159931. emit_2bytes(cinfo, 3 * cinfo->num_components + 2 + 5 + 1); /* length */
  159932. /* Make sure image isn't bigger than SOF field can handle */
  159933. if ((long) cinfo->image_height > 65535L ||
  159934. (long) cinfo->image_width > 65535L)
  159935. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) 65535);
  159936. emit_byte(cinfo, cinfo->data_precision);
  159937. emit_2bytes(cinfo, (int) cinfo->image_height);
  159938. emit_2bytes(cinfo, (int) cinfo->image_width);
  159939. emit_byte(cinfo, cinfo->num_components);
  159940. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  159941. ci++, compptr++) {
  159942. emit_byte(cinfo, compptr->component_id);
  159943. emit_byte(cinfo, (compptr->h_samp_factor << 4) + compptr->v_samp_factor);
  159944. emit_byte(cinfo, compptr->quant_tbl_no);
  159945. }
  159946. }
  159947. LOCAL(void)
  159948. emit_sos (j_compress_ptr cinfo)
  159949. /* Emit a SOS marker */
  159950. {
  159951. int i, td, ta;
  159952. jpeg_component_info *compptr;
  159953. emit_marker(cinfo, M_SOS);
  159954. emit_2bytes(cinfo, 2 * cinfo->comps_in_scan + 2 + 1 + 3); /* length */
  159955. emit_byte(cinfo, cinfo->comps_in_scan);
  159956. for (i = 0; i < cinfo->comps_in_scan; i++) {
  159957. compptr = cinfo->cur_comp_info[i];
  159958. emit_byte(cinfo, compptr->component_id);
  159959. td = compptr->dc_tbl_no;
  159960. ta = compptr->ac_tbl_no;
  159961. if (cinfo->progressive_mode) {
  159962. /* Progressive mode: only DC or only AC tables are used in one scan;
  159963. * furthermore, Huffman coding of DC refinement uses no table at all.
  159964. * We emit 0 for unused field(s); this is recommended by the P&M text
  159965. * but does not seem to be specified in the standard.
  159966. */
  159967. if (cinfo->Ss == 0) {
  159968. ta = 0; /* DC scan */
  159969. if (cinfo->Ah != 0 && !cinfo->arith_code)
  159970. td = 0; /* no DC table either */
  159971. } else {
  159972. td = 0; /* AC scan */
  159973. }
  159974. }
  159975. emit_byte(cinfo, (td << 4) + ta);
  159976. }
  159977. emit_byte(cinfo, cinfo->Ss);
  159978. emit_byte(cinfo, cinfo->Se);
  159979. emit_byte(cinfo, (cinfo->Ah << 4) + cinfo->Al);
  159980. }
  159981. LOCAL(void)
  159982. emit_jfif_app0 (j_compress_ptr cinfo)
  159983. /* Emit a JFIF-compliant APP0 marker */
  159984. {
  159985. /*
  159986. * Length of APP0 block (2 bytes)
  159987. * Block ID (4 bytes - ASCII "JFIF")
  159988. * Zero byte (1 byte to terminate the ID string)
  159989. * Version Major, Minor (2 bytes - major first)
  159990. * Units (1 byte - 0x00 = none, 0x01 = inch, 0x02 = cm)
  159991. * Xdpu (2 bytes - dots per unit horizontal)
  159992. * Ydpu (2 bytes - dots per unit vertical)
  159993. * Thumbnail X size (1 byte)
  159994. * Thumbnail Y size (1 byte)
  159995. */
  159996. emit_marker(cinfo, M_APP0);
  159997. emit_2bytes(cinfo, 2 + 4 + 1 + 2 + 1 + 2 + 2 + 1 + 1); /* length */
  159998. emit_byte(cinfo, 0x4A); /* Identifier: ASCII "JFIF" */
  159999. emit_byte(cinfo, 0x46);
  160000. emit_byte(cinfo, 0x49);
  160001. emit_byte(cinfo, 0x46);
  160002. emit_byte(cinfo, 0);
  160003. emit_byte(cinfo, cinfo->JFIF_major_version); /* Version fields */
  160004. emit_byte(cinfo, cinfo->JFIF_minor_version);
  160005. emit_byte(cinfo, cinfo->density_unit); /* Pixel size information */
  160006. emit_2bytes(cinfo, (int) cinfo->X_density);
  160007. emit_2bytes(cinfo, (int) cinfo->Y_density);
  160008. emit_byte(cinfo, 0); /* No thumbnail image */
  160009. emit_byte(cinfo, 0);
  160010. }
  160011. LOCAL(void)
  160012. emit_adobe_app14 (j_compress_ptr cinfo)
  160013. /* Emit an Adobe APP14 marker */
  160014. {
  160015. /*
  160016. * Length of APP14 block (2 bytes)
  160017. * Block ID (5 bytes - ASCII "Adobe")
  160018. * Version Number (2 bytes - currently 100)
  160019. * Flags0 (2 bytes - currently 0)
  160020. * Flags1 (2 bytes - currently 0)
  160021. * Color transform (1 byte)
  160022. *
  160023. * Although Adobe TN 5116 mentions Version = 101, all the Adobe files
  160024. * now in circulation seem to use Version = 100, so that's what we write.
  160025. *
  160026. * We write the color transform byte as 1 if the JPEG color space is
  160027. * YCbCr, 2 if it's YCCK, 0 otherwise. Adobe's definition has to do with
  160028. * whether the encoder performed a transformation, which is pretty useless.
  160029. */
  160030. emit_marker(cinfo, M_APP14);
  160031. emit_2bytes(cinfo, 2 + 5 + 2 + 2 + 2 + 1); /* length */
  160032. emit_byte(cinfo, 0x41); /* Identifier: ASCII "Adobe" */
  160033. emit_byte(cinfo, 0x64);
  160034. emit_byte(cinfo, 0x6F);
  160035. emit_byte(cinfo, 0x62);
  160036. emit_byte(cinfo, 0x65);
  160037. emit_2bytes(cinfo, 100); /* Version */
  160038. emit_2bytes(cinfo, 0); /* Flags0 */
  160039. emit_2bytes(cinfo, 0); /* Flags1 */
  160040. switch (cinfo->jpeg_color_space) {
  160041. case JCS_YCbCr:
  160042. emit_byte(cinfo, 1); /* Color transform = 1 */
  160043. break;
  160044. case JCS_YCCK:
  160045. emit_byte(cinfo, 2); /* Color transform = 2 */
  160046. break;
  160047. default:
  160048. emit_byte(cinfo, 0); /* Color transform = 0 */
  160049. break;
  160050. }
  160051. }
  160052. /*
  160053. * These routines allow writing an arbitrary marker with parameters.
  160054. * The only intended use is to emit COM or APPn markers after calling
  160055. * write_file_header and before calling write_frame_header.
  160056. * Other uses are not guaranteed to produce desirable results.
  160057. * Counting the parameter bytes properly is the caller's responsibility.
  160058. */
  160059. METHODDEF(void)
  160060. write_marker_header (j_compress_ptr cinfo, int marker, unsigned int datalen)
  160061. /* Emit an arbitrary marker header */
  160062. {
  160063. if (datalen > (unsigned int) 65533) /* safety check */
  160064. ERREXIT(cinfo, JERR_BAD_LENGTH);
  160065. emit_marker(cinfo, (JPEG_MARKER) marker);
  160066. emit_2bytes(cinfo, (int) (datalen + 2)); /* total length */
  160067. }
  160068. METHODDEF(void)
  160069. write_marker_byte (j_compress_ptr cinfo, int val)
  160070. /* Emit one byte of marker parameters following write_marker_header */
  160071. {
  160072. emit_byte(cinfo, val);
  160073. }
  160074. /*
  160075. * Write datastream header.
  160076. * This consists of an SOI and optional APPn markers.
  160077. * We recommend use of the JFIF marker, but not the Adobe marker,
  160078. * when using YCbCr or grayscale data. The JFIF marker should NOT
  160079. * be used for any other JPEG colorspace. The Adobe marker is helpful
  160080. * to distinguish RGB, CMYK, and YCCK colorspaces.
  160081. * Note that an application can write additional header markers after
  160082. * jpeg_start_compress returns.
  160083. */
  160084. METHODDEF(void)
  160085. write_file_header (j_compress_ptr cinfo)
  160086. {
  160087. my_marker_ptr marker = (my_marker_ptr) cinfo->marker;
  160088. emit_marker(cinfo, M_SOI); /* first the SOI */
  160089. /* SOI is defined to reset restart interval to 0 */
  160090. marker->last_restart_interval = 0;
  160091. if (cinfo->write_JFIF_header) /* next an optional JFIF APP0 */
  160092. emit_jfif_app0(cinfo);
  160093. if (cinfo->write_Adobe_marker) /* next an optional Adobe APP14 */
  160094. emit_adobe_app14(cinfo);
  160095. }
  160096. /*
  160097. * Write frame header.
  160098. * This consists of DQT and SOFn markers.
  160099. * Note that we do not emit the SOF until we have emitted the DQT(s).
  160100. * This avoids compatibility problems with incorrect implementations that
  160101. * try to error-check the quant table numbers as soon as they see the SOF.
  160102. */
  160103. METHODDEF(void)
  160104. write_frame_header (j_compress_ptr cinfo)
  160105. {
  160106. int ci, prec;
  160107. boolean is_baseline;
  160108. jpeg_component_info *compptr;
  160109. /* Emit DQT for each quantization table.
  160110. * Note that emit_dqt() suppresses any duplicate tables.
  160111. */
  160112. prec = 0;
  160113. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  160114. ci++, compptr++) {
  160115. prec += emit_dqt(cinfo, compptr->quant_tbl_no);
  160116. }
  160117. /* now prec is nonzero iff there are any 16-bit quant tables. */
  160118. /* Check for a non-baseline specification.
  160119. * Note we assume that Huffman table numbers won't be changed later.
  160120. */
  160121. if (cinfo->arith_code || cinfo->progressive_mode ||
  160122. cinfo->data_precision != 8) {
  160123. is_baseline = FALSE;
  160124. } else {
  160125. is_baseline = TRUE;
  160126. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  160127. ci++, compptr++) {
  160128. if (compptr->dc_tbl_no > 1 || compptr->ac_tbl_no > 1)
  160129. is_baseline = FALSE;
  160130. }
  160131. if (prec && is_baseline) {
  160132. is_baseline = FALSE;
  160133. /* If it's baseline except for quantizer size, warn the user */
  160134. TRACEMS(cinfo, 0, JTRC_16BIT_TABLES);
  160135. }
  160136. }
  160137. /* Emit the proper SOF marker */
  160138. if (cinfo->arith_code) {
  160139. emit_sof(cinfo, M_SOF9); /* SOF code for arithmetic coding */
  160140. } else {
  160141. if (cinfo->progressive_mode)
  160142. emit_sof(cinfo, M_SOF2); /* SOF code for progressive Huffman */
  160143. else if (is_baseline)
  160144. emit_sof(cinfo, M_SOF0); /* SOF code for baseline implementation */
  160145. else
  160146. emit_sof(cinfo, M_SOF1); /* SOF code for non-baseline Huffman file */
  160147. }
  160148. }
  160149. /*
  160150. * Write scan header.
  160151. * This consists of DHT or DAC markers, optional DRI, and SOS.
  160152. * Compressed data will be written following the SOS.
  160153. */
  160154. METHODDEF(void)
  160155. write_scan_header (j_compress_ptr cinfo)
  160156. {
  160157. my_marker_ptr marker = (my_marker_ptr) cinfo->marker;
  160158. int i;
  160159. jpeg_component_info *compptr;
  160160. if (cinfo->arith_code) {
  160161. /* Emit arith conditioning info. We may have some duplication
  160162. * if the file has multiple scans, but it's so small it's hardly
  160163. * worth worrying about.
  160164. */
  160165. emit_dac(cinfo);
  160166. } else {
  160167. /* Emit Huffman tables.
  160168. * Note that emit_dht() suppresses any duplicate tables.
  160169. */
  160170. for (i = 0; i < cinfo->comps_in_scan; i++) {
  160171. compptr = cinfo->cur_comp_info[i];
  160172. if (cinfo->progressive_mode) {
  160173. /* Progressive mode: only DC or only AC tables are used in one scan */
  160174. if (cinfo->Ss == 0) {
  160175. if (cinfo->Ah == 0) /* DC needs no table for refinement scan */
  160176. emit_dht(cinfo, compptr->dc_tbl_no, FALSE);
  160177. } else {
  160178. emit_dht(cinfo, compptr->ac_tbl_no, TRUE);
  160179. }
  160180. } else {
  160181. /* Sequential mode: need both DC and AC tables */
  160182. emit_dht(cinfo, compptr->dc_tbl_no, FALSE);
  160183. emit_dht(cinfo, compptr->ac_tbl_no, TRUE);
  160184. }
  160185. }
  160186. }
  160187. /* Emit DRI if required --- note that DRI value could change for each scan.
  160188. * We avoid wasting space with unnecessary DRIs, however.
  160189. */
  160190. if (cinfo->restart_interval != marker->last_restart_interval) {
  160191. emit_dri(cinfo);
  160192. marker->last_restart_interval = cinfo->restart_interval;
  160193. }
  160194. emit_sos(cinfo);
  160195. }
  160196. /*
  160197. * Write datastream trailer.
  160198. */
  160199. METHODDEF(void)
  160200. write_file_trailer (j_compress_ptr cinfo)
  160201. {
  160202. emit_marker(cinfo, M_EOI);
  160203. }
  160204. /*
  160205. * Write an abbreviated table-specification datastream.
  160206. * This consists of SOI, DQT and DHT tables, and EOI.
  160207. * Any table that is defined and not marked sent_table = TRUE will be
  160208. * emitted. Note that all tables will be marked sent_table = TRUE at exit.
  160209. */
  160210. METHODDEF(void)
  160211. write_tables_only (j_compress_ptr cinfo)
  160212. {
  160213. int i;
  160214. emit_marker(cinfo, M_SOI);
  160215. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  160216. if (cinfo->quant_tbl_ptrs[i] != NULL)
  160217. (void) emit_dqt(cinfo, i);
  160218. }
  160219. if (! cinfo->arith_code) {
  160220. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  160221. if (cinfo->dc_huff_tbl_ptrs[i] != NULL)
  160222. emit_dht(cinfo, i, FALSE);
  160223. if (cinfo->ac_huff_tbl_ptrs[i] != NULL)
  160224. emit_dht(cinfo, i, TRUE);
  160225. }
  160226. }
  160227. emit_marker(cinfo, M_EOI);
  160228. }
  160229. /*
  160230. * Initialize the marker writer module.
  160231. */
  160232. GLOBAL(void)
  160233. jinit_marker_writer (j_compress_ptr cinfo)
  160234. {
  160235. my_marker_ptr marker;
  160236. /* Create the subobject */
  160237. marker = (my_marker_ptr)
  160238. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  160239. SIZEOF(my_marker_writer));
  160240. cinfo->marker = (struct jpeg_marker_writer *) marker;
  160241. /* Initialize method pointers */
  160242. marker->pub.write_file_header = write_file_header;
  160243. marker->pub.write_frame_header = write_frame_header;
  160244. marker->pub.write_scan_header = write_scan_header;
  160245. marker->pub.write_file_trailer = write_file_trailer;
  160246. marker->pub.write_tables_only = write_tables_only;
  160247. marker->pub.write_marker_header = write_marker_header;
  160248. marker->pub.write_marker_byte = write_marker_byte;
  160249. /* Initialize private state */
  160250. marker->last_restart_interval = 0;
  160251. }
  160252. /********* End of inlined file: jcmarker.c *********/
  160253. /********* Start of inlined file: jcmaster.c *********/
  160254. #define JPEG_INTERNALS
  160255. /* Private state */
  160256. typedef enum {
  160257. main_pass, /* input data, also do first output step */
  160258. huff_opt_pass, /* Huffman code optimization pass */
  160259. output_pass /* data output pass */
  160260. } c_pass_type;
  160261. typedef struct {
  160262. struct jpeg_comp_master pub; /* public fields */
  160263. c_pass_type pass_type; /* the type of the current pass */
  160264. int pass_number; /* # of passes completed */
  160265. int total_passes; /* total # of passes needed */
  160266. int scan_number; /* current index in scan_info[] */
  160267. } my_comp_master;
  160268. typedef my_comp_master * my_master_ptr;
  160269. /*
  160270. * Support routines that do various essential calculations.
  160271. */
  160272. LOCAL(void)
  160273. initial_setup (j_compress_ptr cinfo)
  160274. /* Do computations that are needed before master selection phase */
  160275. {
  160276. int ci;
  160277. jpeg_component_info *compptr;
  160278. long samplesperrow;
  160279. JDIMENSION jd_samplesperrow;
  160280. /* Sanity check on image dimensions */
  160281. if (cinfo->image_height <= 0 || cinfo->image_width <= 0
  160282. || cinfo->num_components <= 0 || cinfo->input_components <= 0)
  160283. ERREXIT(cinfo, JERR_EMPTY_IMAGE);
  160284. /* Make sure image isn't bigger than I can handle */
  160285. if ((long) cinfo->image_height > (long) JPEG_MAX_DIMENSION ||
  160286. (long) cinfo->image_width > (long) JPEG_MAX_DIMENSION)
  160287. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) JPEG_MAX_DIMENSION);
  160288. /* Width of an input scanline must be representable as JDIMENSION. */
  160289. samplesperrow = (long) cinfo->image_width * (long) cinfo->input_components;
  160290. jd_samplesperrow = (JDIMENSION) samplesperrow;
  160291. if ((long) jd_samplesperrow != samplesperrow)
  160292. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  160293. /* For now, precision must match compiled-in value... */
  160294. if (cinfo->data_precision != BITS_IN_JSAMPLE)
  160295. ERREXIT1(cinfo, JERR_BAD_PRECISION, cinfo->data_precision);
  160296. /* Check that number of components won't exceed internal array sizes */
  160297. if (cinfo->num_components > MAX_COMPONENTS)
  160298. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  160299. MAX_COMPONENTS);
  160300. /* Compute maximum sampling factors; check factor validity */
  160301. cinfo->max_h_samp_factor = 1;
  160302. cinfo->max_v_samp_factor = 1;
  160303. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  160304. ci++, compptr++) {
  160305. if (compptr->h_samp_factor<=0 || compptr->h_samp_factor>MAX_SAMP_FACTOR ||
  160306. compptr->v_samp_factor<=0 || compptr->v_samp_factor>MAX_SAMP_FACTOR)
  160307. ERREXIT(cinfo, JERR_BAD_SAMPLING);
  160308. cinfo->max_h_samp_factor = MAX(cinfo->max_h_samp_factor,
  160309. compptr->h_samp_factor);
  160310. cinfo->max_v_samp_factor = MAX(cinfo->max_v_samp_factor,
  160311. compptr->v_samp_factor);
  160312. }
  160313. /* Compute dimensions of components */
  160314. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  160315. ci++, compptr++) {
  160316. /* Fill in the correct component_index value; don't rely on application */
  160317. compptr->component_index = ci;
  160318. /* For compression, we never do DCT scaling. */
  160319. compptr->DCT_scaled_size = DCTSIZE;
  160320. /* Size in DCT blocks */
  160321. compptr->width_in_blocks = (JDIMENSION)
  160322. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  160323. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  160324. compptr->height_in_blocks = (JDIMENSION)
  160325. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  160326. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  160327. /* Size in samples */
  160328. compptr->downsampled_width = (JDIMENSION)
  160329. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  160330. (long) cinfo->max_h_samp_factor);
  160331. compptr->downsampled_height = (JDIMENSION)
  160332. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  160333. (long) cinfo->max_v_samp_factor);
  160334. /* Mark component needed (this flag isn't actually used for compression) */
  160335. compptr->component_needed = TRUE;
  160336. }
  160337. /* Compute number of fully interleaved MCU rows (number of times that
  160338. * main controller will call coefficient controller).
  160339. */
  160340. cinfo->total_iMCU_rows = (JDIMENSION)
  160341. jdiv_round_up((long) cinfo->image_height,
  160342. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  160343. }
  160344. #ifdef C_MULTISCAN_FILES_SUPPORTED
  160345. LOCAL(void)
  160346. validate_script (j_compress_ptr cinfo)
  160347. /* Verify that the scan script in cinfo->scan_info[] is valid; also
  160348. * determine whether it uses progressive JPEG, and set cinfo->progressive_mode.
  160349. */
  160350. {
  160351. const jpeg_scan_info * scanptr;
  160352. int scanno, ncomps, ci, coefi, thisi;
  160353. int Ss, Se, Ah, Al;
  160354. boolean component_sent[MAX_COMPONENTS];
  160355. #ifdef C_PROGRESSIVE_SUPPORTED
  160356. int * last_bitpos_ptr;
  160357. int last_bitpos[MAX_COMPONENTS][DCTSIZE2];
  160358. /* -1 until that coefficient has been seen; then last Al for it */
  160359. #endif
  160360. if (cinfo->num_scans <= 0)
  160361. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, 0);
  160362. /* For sequential JPEG, all scans must have Ss=0, Se=DCTSIZE2-1;
  160363. * for progressive JPEG, no scan can have this.
  160364. */
  160365. scanptr = cinfo->scan_info;
  160366. if (scanptr->Ss != 0 || scanptr->Se != DCTSIZE2-1) {
  160367. #ifdef C_PROGRESSIVE_SUPPORTED
  160368. cinfo->progressive_mode = TRUE;
  160369. last_bitpos_ptr = & last_bitpos[0][0];
  160370. for (ci = 0; ci < cinfo->num_components; ci++)
  160371. for (coefi = 0; coefi < DCTSIZE2; coefi++)
  160372. *last_bitpos_ptr++ = -1;
  160373. #else
  160374. ERREXIT(cinfo, JERR_NOT_COMPILED);
  160375. #endif
  160376. } else {
  160377. cinfo->progressive_mode = FALSE;
  160378. for (ci = 0; ci < cinfo->num_components; ci++)
  160379. component_sent[ci] = FALSE;
  160380. }
  160381. for (scanno = 1; scanno <= cinfo->num_scans; scanptr++, scanno++) {
  160382. /* Validate component indexes */
  160383. ncomps = scanptr->comps_in_scan;
  160384. if (ncomps <= 0 || ncomps > MAX_COMPS_IN_SCAN)
  160385. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, ncomps, MAX_COMPS_IN_SCAN);
  160386. for (ci = 0; ci < ncomps; ci++) {
  160387. thisi = scanptr->component_index[ci];
  160388. if (thisi < 0 || thisi >= cinfo->num_components)
  160389. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  160390. /* Components must appear in SOF order within each scan */
  160391. if (ci > 0 && thisi <= scanptr->component_index[ci-1])
  160392. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  160393. }
  160394. /* Validate progression parameters */
  160395. Ss = scanptr->Ss;
  160396. Se = scanptr->Se;
  160397. Ah = scanptr->Ah;
  160398. Al = scanptr->Al;
  160399. if (cinfo->progressive_mode) {
  160400. #ifdef C_PROGRESSIVE_SUPPORTED
  160401. /* The JPEG spec simply gives the ranges 0..13 for Ah and Al, but that
  160402. * seems wrong: the upper bound ought to depend on data precision.
  160403. * Perhaps they really meant 0..N+1 for N-bit precision.
  160404. * Here we allow 0..10 for 8-bit data; Al larger than 10 results in
  160405. * out-of-range reconstructed DC values during the first DC scan,
  160406. * which might cause problems for some decoders.
  160407. */
  160408. #if BITS_IN_JSAMPLE == 8
  160409. #define MAX_AH_AL 10
  160410. #else
  160411. #define MAX_AH_AL 13
  160412. #endif
  160413. if (Ss < 0 || Ss >= DCTSIZE2 || Se < Ss || Se >= DCTSIZE2 ||
  160414. Ah < 0 || Ah > MAX_AH_AL || Al < 0 || Al > MAX_AH_AL)
  160415. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  160416. if (Ss == 0) {
  160417. if (Se != 0) /* DC and AC together not OK */
  160418. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  160419. } else {
  160420. if (ncomps != 1) /* AC scans must be for only one component */
  160421. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  160422. }
  160423. for (ci = 0; ci < ncomps; ci++) {
  160424. last_bitpos_ptr = & last_bitpos[scanptr->component_index[ci]][0];
  160425. if (Ss != 0 && last_bitpos_ptr[0] < 0) /* AC without prior DC scan */
  160426. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  160427. for (coefi = Ss; coefi <= Se; coefi++) {
  160428. if (last_bitpos_ptr[coefi] < 0) {
  160429. /* first scan of this coefficient */
  160430. if (Ah != 0)
  160431. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  160432. } else {
  160433. /* not first scan */
  160434. if (Ah != last_bitpos_ptr[coefi] || Al != Ah-1)
  160435. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  160436. }
  160437. last_bitpos_ptr[coefi] = Al;
  160438. }
  160439. }
  160440. #endif
  160441. } else {
  160442. /* For sequential JPEG, all progression parameters must be these: */
  160443. if (Ss != 0 || Se != DCTSIZE2-1 || Ah != 0 || Al != 0)
  160444. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  160445. /* Make sure components are not sent twice */
  160446. for (ci = 0; ci < ncomps; ci++) {
  160447. thisi = scanptr->component_index[ci];
  160448. if (component_sent[thisi])
  160449. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  160450. component_sent[thisi] = TRUE;
  160451. }
  160452. }
  160453. }
  160454. /* Now verify that everything got sent. */
  160455. if (cinfo->progressive_mode) {
  160456. #ifdef C_PROGRESSIVE_SUPPORTED
  160457. /* For progressive mode, we only check that at least some DC data
  160458. * got sent for each component; the spec does not require that all bits
  160459. * of all coefficients be transmitted. Would it be wiser to enforce
  160460. * transmission of all coefficient bits??
  160461. */
  160462. for (ci = 0; ci < cinfo->num_components; ci++) {
  160463. if (last_bitpos[ci][0] < 0)
  160464. ERREXIT(cinfo, JERR_MISSING_DATA);
  160465. }
  160466. #endif
  160467. } else {
  160468. for (ci = 0; ci < cinfo->num_components; ci++) {
  160469. if (! component_sent[ci])
  160470. ERREXIT(cinfo, JERR_MISSING_DATA);
  160471. }
  160472. }
  160473. }
  160474. #endif /* C_MULTISCAN_FILES_SUPPORTED */
  160475. LOCAL(void)
  160476. select_scan_parameters (j_compress_ptr cinfo)
  160477. /* Set up the scan parameters for the current scan */
  160478. {
  160479. int ci;
  160480. #ifdef C_MULTISCAN_FILES_SUPPORTED
  160481. if (cinfo->scan_info != NULL) {
  160482. /* Prepare for current scan --- the script is already validated */
  160483. my_master_ptr master = (my_master_ptr) cinfo->master;
  160484. const jpeg_scan_info * scanptr = cinfo->scan_info + master->scan_number;
  160485. cinfo->comps_in_scan = scanptr->comps_in_scan;
  160486. for (ci = 0; ci < scanptr->comps_in_scan; ci++) {
  160487. cinfo->cur_comp_info[ci] =
  160488. &cinfo->comp_info[scanptr->component_index[ci]];
  160489. }
  160490. cinfo->Ss = scanptr->Ss;
  160491. cinfo->Se = scanptr->Se;
  160492. cinfo->Ah = scanptr->Ah;
  160493. cinfo->Al = scanptr->Al;
  160494. }
  160495. else
  160496. #endif
  160497. {
  160498. /* Prepare for single sequential-JPEG scan containing all components */
  160499. if (cinfo->num_components > MAX_COMPS_IN_SCAN)
  160500. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  160501. MAX_COMPS_IN_SCAN);
  160502. cinfo->comps_in_scan = cinfo->num_components;
  160503. for (ci = 0; ci < cinfo->num_components; ci++) {
  160504. cinfo->cur_comp_info[ci] = &cinfo->comp_info[ci];
  160505. }
  160506. cinfo->Ss = 0;
  160507. cinfo->Se = DCTSIZE2-1;
  160508. cinfo->Ah = 0;
  160509. cinfo->Al = 0;
  160510. }
  160511. }
  160512. LOCAL(void)
  160513. per_scan_setup (j_compress_ptr cinfo)
  160514. /* Do computations that are needed before processing a JPEG scan */
  160515. /* cinfo->comps_in_scan and cinfo->cur_comp_info[] are already set */
  160516. {
  160517. int ci, mcublks, tmp;
  160518. jpeg_component_info *compptr;
  160519. if (cinfo->comps_in_scan == 1) {
  160520. /* Noninterleaved (single-component) scan */
  160521. compptr = cinfo->cur_comp_info[0];
  160522. /* Overall image size in MCUs */
  160523. cinfo->MCUs_per_row = compptr->width_in_blocks;
  160524. cinfo->MCU_rows_in_scan = compptr->height_in_blocks;
  160525. /* For noninterleaved scan, always one block per MCU */
  160526. compptr->MCU_width = 1;
  160527. compptr->MCU_height = 1;
  160528. compptr->MCU_blocks = 1;
  160529. compptr->MCU_sample_width = DCTSIZE;
  160530. compptr->last_col_width = 1;
  160531. /* For noninterleaved scans, it is convenient to define last_row_height
  160532. * as the number of block rows present in the last iMCU row.
  160533. */
  160534. tmp = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  160535. if (tmp == 0) tmp = compptr->v_samp_factor;
  160536. compptr->last_row_height = tmp;
  160537. /* Prepare array describing MCU composition */
  160538. cinfo->blocks_in_MCU = 1;
  160539. cinfo->MCU_membership[0] = 0;
  160540. } else {
  160541. /* Interleaved (multi-component) scan */
  160542. if (cinfo->comps_in_scan <= 0 || cinfo->comps_in_scan > MAX_COMPS_IN_SCAN)
  160543. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->comps_in_scan,
  160544. MAX_COMPS_IN_SCAN);
  160545. /* Overall image size in MCUs */
  160546. cinfo->MCUs_per_row = (JDIMENSION)
  160547. jdiv_round_up((long) cinfo->image_width,
  160548. (long) (cinfo->max_h_samp_factor*DCTSIZE));
  160549. cinfo->MCU_rows_in_scan = (JDIMENSION)
  160550. jdiv_round_up((long) cinfo->image_height,
  160551. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  160552. cinfo->blocks_in_MCU = 0;
  160553. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  160554. compptr = cinfo->cur_comp_info[ci];
  160555. /* Sampling factors give # of blocks of component in each MCU */
  160556. compptr->MCU_width = compptr->h_samp_factor;
  160557. compptr->MCU_height = compptr->v_samp_factor;
  160558. compptr->MCU_blocks = compptr->MCU_width * compptr->MCU_height;
  160559. compptr->MCU_sample_width = compptr->MCU_width * DCTSIZE;
  160560. /* Figure number of non-dummy blocks in last MCU column & row */
  160561. tmp = (int) (compptr->width_in_blocks % compptr->MCU_width);
  160562. if (tmp == 0) tmp = compptr->MCU_width;
  160563. compptr->last_col_width = tmp;
  160564. tmp = (int) (compptr->height_in_blocks % compptr->MCU_height);
  160565. if (tmp == 0) tmp = compptr->MCU_height;
  160566. compptr->last_row_height = tmp;
  160567. /* Prepare array describing MCU composition */
  160568. mcublks = compptr->MCU_blocks;
  160569. if (cinfo->blocks_in_MCU + mcublks > C_MAX_BLOCKS_IN_MCU)
  160570. ERREXIT(cinfo, JERR_BAD_MCU_SIZE);
  160571. while (mcublks-- > 0) {
  160572. cinfo->MCU_membership[cinfo->blocks_in_MCU++] = ci;
  160573. }
  160574. }
  160575. }
  160576. /* Convert restart specified in rows to actual MCU count. */
  160577. /* Note that count must fit in 16 bits, so we provide limiting. */
  160578. if (cinfo->restart_in_rows > 0) {
  160579. long nominal = (long) cinfo->restart_in_rows * (long) cinfo->MCUs_per_row;
  160580. cinfo->restart_interval = (unsigned int) MIN(nominal, 65535L);
  160581. }
  160582. }
  160583. /*
  160584. * Per-pass setup.
  160585. * This is called at the beginning of each pass. We determine which modules
  160586. * will be active during this pass and give them appropriate start_pass calls.
  160587. * We also set is_last_pass to indicate whether any more passes will be
  160588. * required.
  160589. */
  160590. METHODDEF(void)
  160591. prepare_for_pass (j_compress_ptr cinfo)
  160592. {
  160593. my_master_ptr master = (my_master_ptr) cinfo->master;
  160594. switch (master->pass_type) {
  160595. case main_pass:
  160596. /* Initial pass: will collect input data, and do either Huffman
  160597. * optimization or data output for the first scan.
  160598. */
  160599. select_scan_parameters(cinfo);
  160600. per_scan_setup(cinfo);
  160601. if (! cinfo->raw_data_in) {
  160602. (*cinfo->cconvert->start_pass) (cinfo);
  160603. (*cinfo->downsample->start_pass) (cinfo);
  160604. (*cinfo->prep->start_pass) (cinfo, JBUF_PASS_THRU);
  160605. }
  160606. (*cinfo->fdct->start_pass) (cinfo);
  160607. (*cinfo->entropy->start_pass) (cinfo, cinfo->optimize_coding);
  160608. (*cinfo->coef->start_pass) (cinfo,
  160609. (master->total_passes > 1 ?
  160610. JBUF_SAVE_AND_PASS : JBUF_PASS_THRU));
  160611. (*cinfo->main->start_pass) (cinfo, JBUF_PASS_THRU);
  160612. if (cinfo->optimize_coding) {
  160613. /* No immediate data output; postpone writing frame/scan headers */
  160614. master->pub.call_pass_startup = FALSE;
  160615. } else {
  160616. /* Will write frame/scan headers at first jpeg_write_scanlines call */
  160617. master->pub.call_pass_startup = TRUE;
  160618. }
  160619. break;
  160620. #ifdef ENTROPY_OPT_SUPPORTED
  160621. case huff_opt_pass:
  160622. /* Do Huffman optimization for a scan after the first one. */
  160623. select_scan_parameters(cinfo);
  160624. per_scan_setup(cinfo);
  160625. if (cinfo->Ss != 0 || cinfo->Ah == 0 || cinfo->arith_code) {
  160626. (*cinfo->entropy->start_pass) (cinfo, TRUE);
  160627. (*cinfo->coef->start_pass) (cinfo, JBUF_CRANK_DEST);
  160628. master->pub.call_pass_startup = FALSE;
  160629. break;
  160630. }
  160631. /* Special case: Huffman DC refinement scans need no Huffman table
  160632. * and therefore we can skip the optimization pass for them.
  160633. */
  160634. master->pass_type = output_pass;
  160635. master->pass_number++;
  160636. /*FALLTHROUGH*/
  160637. #endif
  160638. case output_pass:
  160639. /* Do a data-output pass. */
  160640. /* We need not repeat per-scan setup if prior optimization pass did it. */
  160641. if (! cinfo->optimize_coding) {
  160642. select_scan_parameters(cinfo);
  160643. per_scan_setup(cinfo);
  160644. }
  160645. (*cinfo->entropy->start_pass) (cinfo, FALSE);
  160646. (*cinfo->coef->start_pass) (cinfo, JBUF_CRANK_DEST);
  160647. /* We emit frame/scan headers now */
  160648. if (master->scan_number == 0)
  160649. (*cinfo->marker->write_frame_header) (cinfo);
  160650. (*cinfo->marker->write_scan_header) (cinfo);
  160651. master->pub.call_pass_startup = FALSE;
  160652. break;
  160653. default:
  160654. ERREXIT(cinfo, JERR_NOT_COMPILED);
  160655. }
  160656. master->pub.is_last_pass = (master->pass_number == master->total_passes-1);
  160657. /* Set up progress monitor's pass info if present */
  160658. if (cinfo->progress != NULL) {
  160659. cinfo->progress->completed_passes = master->pass_number;
  160660. cinfo->progress->total_passes = master->total_passes;
  160661. }
  160662. }
  160663. /*
  160664. * Special start-of-pass hook.
  160665. * This is called by jpeg_write_scanlines if call_pass_startup is TRUE.
  160666. * In single-pass processing, we need this hook because we don't want to
  160667. * write frame/scan headers during jpeg_start_compress; we want to let the
  160668. * application write COM markers etc. between jpeg_start_compress and the
  160669. * jpeg_write_scanlines loop.
  160670. * In multi-pass processing, this routine is not used.
  160671. */
  160672. METHODDEF(void)
  160673. pass_startup (j_compress_ptr cinfo)
  160674. {
  160675. cinfo->master->call_pass_startup = FALSE; /* reset flag so call only once */
  160676. (*cinfo->marker->write_frame_header) (cinfo);
  160677. (*cinfo->marker->write_scan_header) (cinfo);
  160678. }
  160679. /*
  160680. * Finish up at end of pass.
  160681. */
  160682. METHODDEF(void)
  160683. finish_pass_master (j_compress_ptr cinfo)
  160684. {
  160685. my_master_ptr master = (my_master_ptr) cinfo->master;
  160686. /* The entropy coder always needs an end-of-pass call,
  160687. * either to analyze statistics or to flush its output buffer.
  160688. */
  160689. (*cinfo->entropy->finish_pass) (cinfo);
  160690. /* Update state for next pass */
  160691. switch (master->pass_type) {
  160692. case main_pass:
  160693. /* next pass is either output of scan 0 (after optimization)
  160694. * or output of scan 1 (if no optimization).
  160695. */
  160696. master->pass_type = output_pass;
  160697. if (! cinfo->optimize_coding)
  160698. master->scan_number++;
  160699. break;
  160700. case huff_opt_pass:
  160701. /* next pass is always output of current scan */
  160702. master->pass_type = output_pass;
  160703. break;
  160704. case output_pass:
  160705. /* next pass is either optimization or output of next scan */
  160706. if (cinfo->optimize_coding)
  160707. master->pass_type = huff_opt_pass;
  160708. master->scan_number++;
  160709. break;
  160710. }
  160711. master->pass_number++;
  160712. }
  160713. /*
  160714. * Initialize master compression control.
  160715. */
  160716. GLOBAL(void)
  160717. jinit_c_master_control (j_compress_ptr cinfo, boolean transcode_only)
  160718. {
  160719. my_master_ptr master;
  160720. master = (my_master_ptr)
  160721. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  160722. SIZEOF(my_comp_master));
  160723. cinfo->master = (struct jpeg_comp_master *) master;
  160724. master->pub.prepare_for_pass = prepare_for_pass;
  160725. master->pub.pass_startup = pass_startup;
  160726. master->pub.finish_pass = finish_pass_master;
  160727. master->pub.is_last_pass = FALSE;
  160728. /* Validate parameters, determine derived values */
  160729. initial_setup(cinfo);
  160730. if (cinfo->scan_info != NULL) {
  160731. #ifdef C_MULTISCAN_FILES_SUPPORTED
  160732. validate_script(cinfo);
  160733. #else
  160734. ERREXIT(cinfo, JERR_NOT_COMPILED);
  160735. #endif
  160736. } else {
  160737. cinfo->progressive_mode = FALSE;
  160738. cinfo->num_scans = 1;
  160739. }
  160740. if (cinfo->progressive_mode) /* TEMPORARY HACK ??? */
  160741. cinfo->optimize_coding = TRUE; /* assume default tables no good for progressive mode */
  160742. /* Initialize my private state */
  160743. if (transcode_only) {
  160744. /* no main pass in transcoding */
  160745. if (cinfo->optimize_coding)
  160746. master->pass_type = huff_opt_pass;
  160747. else
  160748. master->pass_type = output_pass;
  160749. } else {
  160750. /* for normal compression, first pass is always this type: */
  160751. master->pass_type = main_pass;
  160752. }
  160753. master->scan_number = 0;
  160754. master->pass_number = 0;
  160755. if (cinfo->optimize_coding)
  160756. master->total_passes = cinfo->num_scans * 2;
  160757. else
  160758. master->total_passes = cinfo->num_scans;
  160759. }
  160760. /********* End of inlined file: jcmaster.c *********/
  160761. /********* Start of inlined file: jcomapi.c *********/
  160762. #define JPEG_INTERNALS
  160763. /*
  160764. * Abort processing of a JPEG compression or decompression operation,
  160765. * but don't destroy the object itself.
  160766. *
  160767. * For this, we merely clean up all the nonpermanent memory pools.
  160768. * Note that temp files (virtual arrays) are not allowed to belong to
  160769. * the permanent pool, so we will be able to close all temp files here.
  160770. * Closing a data source or destination, if necessary, is the application's
  160771. * responsibility.
  160772. */
  160773. GLOBAL(void)
  160774. jpeg_abort (j_common_ptr cinfo)
  160775. {
  160776. int pool;
  160777. /* Do nothing if called on a not-initialized or destroyed JPEG object. */
  160778. if (cinfo->mem == NULL)
  160779. return;
  160780. /* Releasing pools in reverse order might help avoid fragmentation
  160781. * with some (brain-damaged) malloc libraries.
  160782. */
  160783. for (pool = JPOOL_NUMPOOLS-1; pool > JPOOL_PERMANENT; pool--) {
  160784. (*cinfo->mem->free_pool) (cinfo, pool);
  160785. }
  160786. /* Reset overall state for possible reuse of object */
  160787. if (cinfo->is_decompressor) {
  160788. cinfo->global_state = DSTATE_START;
  160789. /* Try to keep application from accessing now-deleted marker list.
  160790. * A bit kludgy to do it here, but this is the most central place.
  160791. */
  160792. ((j_decompress_ptr) cinfo)->marker_list = NULL;
  160793. } else {
  160794. cinfo->global_state = CSTATE_START;
  160795. }
  160796. }
  160797. /*
  160798. * Destruction of a JPEG object.
  160799. *
  160800. * Everything gets deallocated except the master jpeg_compress_struct itself
  160801. * and the error manager struct. Both of these are supplied by the application
  160802. * and must be freed, if necessary, by the application. (Often they are on
  160803. * the stack and so don't need to be freed anyway.)
  160804. * Closing a data source or destination, if necessary, is the application's
  160805. * responsibility.
  160806. */
  160807. GLOBAL(void)
  160808. jpeg_destroy (j_common_ptr cinfo)
  160809. {
  160810. /* We need only tell the memory manager to release everything. */
  160811. /* NB: mem pointer is NULL if memory mgr failed to initialize. */
  160812. if (cinfo->mem != NULL)
  160813. (*cinfo->mem->self_destruct) (cinfo);
  160814. cinfo->mem = NULL; /* be safe if jpeg_destroy is called twice */
  160815. cinfo->global_state = 0; /* mark it destroyed */
  160816. }
  160817. /*
  160818. * Convenience routines for allocating quantization and Huffman tables.
  160819. * (Would jutils.c be a more reasonable place to put these?)
  160820. */
  160821. GLOBAL(JQUANT_TBL *)
  160822. jpeg_alloc_quant_table (j_common_ptr cinfo)
  160823. {
  160824. JQUANT_TBL *tbl;
  160825. tbl = (JQUANT_TBL *)
  160826. (*cinfo->mem->alloc_small) (cinfo, JPOOL_PERMANENT, SIZEOF(JQUANT_TBL));
  160827. tbl->sent_table = FALSE; /* make sure this is false in any new table */
  160828. return tbl;
  160829. }
  160830. GLOBAL(JHUFF_TBL *)
  160831. jpeg_alloc_huff_table (j_common_ptr cinfo)
  160832. {
  160833. JHUFF_TBL *tbl;
  160834. tbl = (JHUFF_TBL *)
  160835. (*cinfo->mem->alloc_small) (cinfo, JPOOL_PERMANENT, SIZEOF(JHUFF_TBL));
  160836. tbl->sent_table = FALSE; /* make sure this is false in any new table */
  160837. return tbl;
  160838. }
  160839. /********* End of inlined file: jcomapi.c *********/
  160840. /********* Start of inlined file: jcparam.c *********/
  160841. #define JPEG_INTERNALS
  160842. /*
  160843. * Quantization table setup routines
  160844. */
  160845. GLOBAL(void)
  160846. jpeg_add_quant_table (j_compress_ptr cinfo, int which_tbl,
  160847. const unsigned int *basic_table,
  160848. int scale_factor, boolean force_baseline)
  160849. /* Define a quantization table equal to the basic_table times
  160850. * a scale factor (given as a percentage).
  160851. * If force_baseline is TRUE, the computed quantization table entries
  160852. * are limited to 1..255 for JPEG baseline compatibility.
  160853. */
  160854. {
  160855. JQUANT_TBL ** qtblptr;
  160856. int i;
  160857. long temp;
  160858. /* Safety check to ensure start_compress not called yet. */
  160859. if (cinfo->global_state != CSTATE_START)
  160860. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  160861. if (which_tbl < 0 || which_tbl >= NUM_QUANT_TBLS)
  160862. ERREXIT1(cinfo, JERR_DQT_INDEX, which_tbl);
  160863. qtblptr = & cinfo->quant_tbl_ptrs[which_tbl];
  160864. if (*qtblptr == NULL)
  160865. *qtblptr = jpeg_alloc_quant_table((j_common_ptr) cinfo);
  160866. for (i = 0; i < DCTSIZE2; i++) {
  160867. temp = ((long) basic_table[i] * scale_factor + 50L) / 100L;
  160868. /* limit the values to the valid range */
  160869. if (temp <= 0L) temp = 1L;
  160870. if (temp > 32767L) temp = 32767L; /* max quantizer needed for 12 bits */
  160871. if (force_baseline && temp > 255L)
  160872. temp = 255L; /* limit to baseline range if requested */
  160873. (*qtblptr)->quantval[i] = (UINT16) temp;
  160874. }
  160875. /* Initialize sent_table FALSE so table will be written to JPEG file. */
  160876. (*qtblptr)->sent_table = FALSE;
  160877. }
  160878. GLOBAL(void)
  160879. jpeg_set_linear_quality (j_compress_ptr cinfo, int scale_factor,
  160880. boolean force_baseline)
  160881. /* Set or change the 'quality' (quantization) setting, using default tables
  160882. * and a straight percentage-scaling quality scale. In most cases it's better
  160883. * to use jpeg_set_quality (below); this entry point is provided for
  160884. * applications that insist on a linear percentage scaling.
  160885. */
  160886. {
  160887. /* These are the sample quantization tables given in JPEG spec section K.1.
  160888. * The spec says that the values given produce "good" quality, and
  160889. * when divided by 2, "very good" quality.
  160890. */
  160891. static const unsigned int std_luminance_quant_tbl[DCTSIZE2] = {
  160892. 16, 11, 10, 16, 24, 40, 51, 61,
  160893. 12, 12, 14, 19, 26, 58, 60, 55,
  160894. 14, 13, 16, 24, 40, 57, 69, 56,
  160895. 14, 17, 22, 29, 51, 87, 80, 62,
  160896. 18, 22, 37, 56, 68, 109, 103, 77,
  160897. 24, 35, 55, 64, 81, 104, 113, 92,
  160898. 49, 64, 78, 87, 103, 121, 120, 101,
  160899. 72, 92, 95, 98, 112, 100, 103, 99
  160900. };
  160901. static const unsigned int std_chrominance_quant_tbl[DCTSIZE2] = {
  160902. 17, 18, 24, 47, 99, 99, 99, 99,
  160903. 18, 21, 26, 66, 99, 99, 99, 99,
  160904. 24, 26, 56, 99, 99, 99, 99, 99,
  160905. 47, 66, 99, 99, 99, 99, 99, 99,
  160906. 99, 99, 99, 99, 99, 99, 99, 99,
  160907. 99, 99, 99, 99, 99, 99, 99, 99,
  160908. 99, 99, 99, 99, 99, 99, 99, 99,
  160909. 99, 99, 99, 99, 99, 99, 99, 99
  160910. };
  160911. /* Set up two quantization tables using the specified scaling */
  160912. jpeg_add_quant_table(cinfo, 0, std_luminance_quant_tbl,
  160913. scale_factor, force_baseline);
  160914. jpeg_add_quant_table(cinfo, 1, std_chrominance_quant_tbl,
  160915. scale_factor, force_baseline);
  160916. }
  160917. GLOBAL(int)
  160918. jpeg_quality_scaling (int quality)
  160919. /* Convert a user-specified quality rating to a percentage scaling factor
  160920. * for an underlying quantization table, using our recommended scaling curve.
  160921. * The input 'quality' factor should be 0 (terrible) to 100 (very good).
  160922. */
  160923. {
  160924. /* Safety limit on quality factor. Convert 0 to 1 to avoid zero divide. */
  160925. if (quality <= 0) quality = 1;
  160926. if (quality > 100) quality = 100;
  160927. /* The basic table is used as-is (scaling 100) for a quality of 50.
  160928. * Qualities 50..100 are converted to scaling percentage 200 - 2*Q;
  160929. * note that at Q=100 the scaling is 0, which will cause jpeg_add_quant_table
  160930. * to make all the table entries 1 (hence, minimum quantization loss).
  160931. * Qualities 1..50 are converted to scaling percentage 5000/Q.
  160932. */
  160933. if (quality < 50)
  160934. quality = 5000 / quality;
  160935. else
  160936. quality = 200 - quality*2;
  160937. return quality;
  160938. }
  160939. GLOBAL(void)
  160940. jpeg_set_quality (j_compress_ptr cinfo, int quality, boolean force_baseline)
  160941. /* Set or change the 'quality' (quantization) setting, using default tables.
  160942. * This is the standard quality-adjusting entry point for typical user
  160943. * interfaces; only those who want detailed control over quantization tables
  160944. * would use the preceding three routines directly.
  160945. */
  160946. {
  160947. /* Convert user 0-100 rating to percentage scaling */
  160948. quality = jpeg_quality_scaling(quality);
  160949. /* Set up standard quality tables */
  160950. jpeg_set_linear_quality(cinfo, quality, force_baseline);
  160951. }
  160952. /*
  160953. * Huffman table setup routines
  160954. */
  160955. LOCAL(void)
  160956. add_huff_table (j_compress_ptr cinfo,
  160957. JHUFF_TBL **htblptr, const UINT8 *bits, const UINT8 *val)
  160958. /* Define a Huffman table */
  160959. {
  160960. int nsymbols, len;
  160961. if (*htblptr == NULL)
  160962. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  160963. /* Copy the number-of-symbols-of-each-code-length counts */
  160964. MEMCOPY((*htblptr)->bits, bits, SIZEOF((*htblptr)->bits));
  160965. /* Validate the counts. We do this here mainly so we can copy the right
  160966. * number of symbols from the val[] array, without risking marching off
  160967. * the end of memory. jchuff.c will do a more thorough test later.
  160968. */
  160969. nsymbols = 0;
  160970. for (len = 1; len <= 16; len++)
  160971. nsymbols += bits[len];
  160972. if (nsymbols < 1 || nsymbols > 256)
  160973. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  160974. MEMCOPY((*htblptr)->huffval, val, nsymbols * SIZEOF(UINT8));
  160975. /* Initialize sent_table FALSE so table will be written to JPEG file. */
  160976. (*htblptr)->sent_table = FALSE;
  160977. }
  160978. LOCAL(void)
  160979. std_huff_tables (j_compress_ptr cinfo)
  160980. /* Set up the standard Huffman tables (cf. JPEG standard section K.3) */
  160981. /* IMPORTANT: these are only valid for 8-bit data precision! */
  160982. {
  160983. static const UINT8 bits_dc_luminance[17] =
  160984. { /* 0-base */ 0, 0, 1, 5, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0 };
  160985. static const UINT8 val_dc_luminance[] =
  160986. { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
  160987. static const UINT8 bits_dc_chrominance[17] =
  160988. { /* 0-base */ 0, 0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0 };
  160989. static const UINT8 val_dc_chrominance[] =
  160990. { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
  160991. static const UINT8 bits_ac_luminance[17] =
  160992. { /* 0-base */ 0, 0, 2, 1, 3, 3, 2, 4, 3, 5, 5, 4, 4, 0, 0, 1, 0x7d };
  160993. static const UINT8 val_ac_luminance[] =
  160994. { 0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12,
  160995. 0x21, 0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07,
  160996. 0x22, 0x71, 0x14, 0x32, 0x81, 0x91, 0xa1, 0x08,
  160997. 0x23, 0x42, 0xb1, 0xc1, 0x15, 0x52, 0xd1, 0xf0,
  160998. 0x24, 0x33, 0x62, 0x72, 0x82, 0x09, 0x0a, 0x16,
  160999. 0x17, 0x18, 0x19, 0x1a, 0x25, 0x26, 0x27, 0x28,
  161000. 0x29, 0x2a, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39,
  161001. 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49,
  161002. 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59,
  161003. 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69,
  161004. 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79,
  161005. 0x7a, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89,
  161006. 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98,
  161007. 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,
  161008. 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6,
  161009. 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, 0xc4, 0xc5,
  161010. 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4,
  161011. 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xe1, 0xe2,
  161012. 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea,
  161013. 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
  161014. 0xf9, 0xfa };
  161015. static const UINT8 bits_ac_chrominance[17] =
  161016. { /* 0-base */ 0, 0, 2, 1, 2, 4, 4, 3, 4, 7, 5, 4, 4, 0, 1, 2, 0x77 };
  161017. static const UINT8 val_ac_chrominance[] =
  161018. { 0x00, 0x01, 0x02, 0x03, 0x11, 0x04, 0x05, 0x21,
  161019. 0x31, 0x06, 0x12, 0x41, 0x51, 0x07, 0x61, 0x71,
  161020. 0x13, 0x22, 0x32, 0x81, 0x08, 0x14, 0x42, 0x91,
  161021. 0xa1, 0xb1, 0xc1, 0x09, 0x23, 0x33, 0x52, 0xf0,
  161022. 0x15, 0x62, 0x72, 0xd1, 0x0a, 0x16, 0x24, 0x34,
  161023. 0xe1, 0x25, 0xf1, 0x17, 0x18, 0x19, 0x1a, 0x26,
  161024. 0x27, 0x28, 0x29, 0x2a, 0x35, 0x36, 0x37, 0x38,
  161025. 0x39, 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48,
  161026. 0x49, 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58,
  161027. 0x59, 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68,
  161028. 0x69, 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78,
  161029. 0x79, 0x7a, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
  161030. 0x88, 0x89, 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96,
  161031. 0x97, 0x98, 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5,
  161032. 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4,
  161033. 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3,
  161034. 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2,
  161035. 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda,
  161036. 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9,
  161037. 0xea, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
  161038. 0xf9, 0xfa };
  161039. add_huff_table(cinfo, &cinfo->dc_huff_tbl_ptrs[0],
  161040. bits_dc_luminance, val_dc_luminance);
  161041. add_huff_table(cinfo, &cinfo->ac_huff_tbl_ptrs[0],
  161042. bits_ac_luminance, val_ac_luminance);
  161043. add_huff_table(cinfo, &cinfo->dc_huff_tbl_ptrs[1],
  161044. bits_dc_chrominance, val_dc_chrominance);
  161045. add_huff_table(cinfo, &cinfo->ac_huff_tbl_ptrs[1],
  161046. bits_ac_chrominance, val_ac_chrominance);
  161047. }
  161048. /*
  161049. * Default parameter setup for compression.
  161050. *
  161051. * Applications that don't choose to use this routine must do their
  161052. * own setup of all these parameters. Alternately, you can call this
  161053. * to establish defaults and then alter parameters selectively. This
  161054. * is the recommended approach since, if we add any new parameters,
  161055. * your code will still work (they'll be set to reasonable defaults).
  161056. */
  161057. GLOBAL(void)
  161058. jpeg_set_defaults (j_compress_ptr cinfo)
  161059. {
  161060. int i;
  161061. /* Safety check to ensure start_compress not called yet. */
  161062. if (cinfo->global_state != CSTATE_START)
  161063. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161064. /* Allocate comp_info array large enough for maximum component count.
  161065. * Array is made permanent in case application wants to compress
  161066. * multiple images at same param settings.
  161067. */
  161068. if (cinfo->comp_info == NULL)
  161069. cinfo->comp_info = (jpeg_component_info *)
  161070. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  161071. MAX_COMPONENTS * SIZEOF(jpeg_component_info));
  161072. /* Initialize everything not dependent on the color space */
  161073. cinfo->data_precision = BITS_IN_JSAMPLE;
  161074. /* Set up two quantization tables using default quality of 75 */
  161075. jpeg_set_quality(cinfo, 75, TRUE);
  161076. /* Set up two Huffman tables */
  161077. std_huff_tables(cinfo);
  161078. /* Initialize default arithmetic coding conditioning */
  161079. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  161080. cinfo->arith_dc_L[i] = 0;
  161081. cinfo->arith_dc_U[i] = 1;
  161082. cinfo->arith_ac_K[i] = 5;
  161083. }
  161084. /* Default is no multiple-scan output */
  161085. cinfo->scan_info = NULL;
  161086. cinfo->num_scans = 0;
  161087. /* Expect normal source image, not raw downsampled data */
  161088. cinfo->raw_data_in = FALSE;
  161089. /* Use Huffman coding, not arithmetic coding, by default */
  161090. cinfo->arith_code = FALSE;
  161091. /* By default, don't do extra passes to optimize entropy coding */
  161092. cinfo->optimize_coding = FALSE;
  161093. /* The standard Huffman tables are only valid for 8-bit data precision.
  161094. * If the precision is higher, force optimization on so that usable
  161095. * tables will be computed. This test can be removed if default tables
  161096. * are supplied that are valid for the desired precision.
  161097. */
  161098. if (cinfo->data_precision > 8)
  161099. cinfo->optimize_coding = TRUE;
  161100. /* By default, use the simpler non-cosited sampling alignment */
  161101. cinfo->CCIR601_sampling = FALSE;
  161102. /* No input smoothing */
  161103. cinfo->smoothing_factor = 0;
  161104. /* DCT algorithm preference */
  161105. cinfo->dct_method = JDCT_DEFAULT;
  161106. /* No restart markers */
  161107. cinfo->restart_interval = 0;
  161108. cinfo->restart_in_rows = 0;
  161109. /* Fill in default JFIF marker parameters. Note that whether the marker
  161110. * will actually be written is determined by jpeg_set_colorspace.
  161111. *
  161112. * By default, the library emits JFIF version code 1.01.
  161113. * An application that wants to emit JFIF 1.02 extension markers should set
  161114. * JFIF_minor_version to 2. We could probably get away with just defaulting
  161115. * to 1.02, but there may still be some decoders in use that will complain
  161116. * about that; saying 1.01 should minimize compatibility problems.
  161117. */
  161118. cinfo->JFIF_major_version = 1; /* Default JFIF version = 1.01 */
  161119. cinfo->JFIF_minor_version = 1;
  161120. cinfo->density_unit = 0; /* Pixel size is unknown by default */
  161121. cinfo->X_density = 1; /* Pixel aspect ratio is square by default */
  161122. cinfo->Y_density = 1;
  161123. /* Choose JPEG colorspace based on input space, set defaults accordingly */
  161124. jpeg_default_colorspace(cinfo);
  161125. }
  161126. /*
  161127. * Select an appropriate JPEG colorspace for in_color_space.
  161128. */
  161129. GLOBAL(void)
  161130. jpeg_default_colorspace (j_compress_ptr cinfo)
  161131. {
  161132. switch (cinfo->in_color_space) {
  161133. case JCS_GRAYSCALE:
  161134. jpeg_set_colorspace(cinfo, JCS_GRAYSCALE);
  161135. break;
  161136. case JCS_RGB:
  161137. jpeg_set_colorspace(cinfo, JCS_YCbCr);
  161138. break;
  161139. case JCS_YCbCr:
  161140. jpeg_set_colorspace(cinfo, JCS_YCbCr);
  161141. break;
  161142. case JCS_CMYK:
  161143. jpeg_set_colorspace(cinfo, JCS_CMYK); /* By default, no translation */
  161144. break;
  161145. case JCS_YCCK:
  161146. jpeg_set_colorspace(cinfo, JCS_YCCK);
  161147. break;
  161148. case JCS_UNKNOWN:
  161149. jpeg_set_colorspace(cinfo, JCS_UNKNOWN);
  161150. break;
  161151. default:
  161152. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  161153. }
  161154. }
  161155. /*
  161156. * Set the JPEG colorspace, and choose colorspace-dependent default values.
  161157. */
  161158. GLOBAL(void)
  161159. jpeg_set_colorspace (j_compress_ptr cinfo, J_COLOR_SPACE colorspace)
  161160. {
  161161. jpeg_component_info * compptr;
  161162. int ci;
  161163. #define SET_COMP(index,id,hsamp,vsamp,quant,dctbl,actbl) \
  161164. (compptr = &cinfo->comp_info[index], \
  161165. compptr->component_id = (id), \
  161166. compptr->h_samp_factor = (hsamp), \
  161167. compptr->v_samp_factor = (vsamp), \
  161168. compptr->quant_tbl_no = (quant), \
  161169. compptr->dc_tbl_no = (dctbl), \
  161170. compptr->ac_tbl_no = (actbl) )
  161171. /* Safety check to ensure start_compress not called yet. */
  161172. if (cinfo->global_state != CSTATE_START)
  161173. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161174. /* For all colorspaces, we use Q and Huff tables 0 for luminance components,
  161175. * tables 1 for chrominance components.
  161176. */
  161177. cinfo->jpeg_color_space = colorspace;
  161178. cinfo->write_JFIF_header = FALSE; /* No marker for non-JFIF colorspaces */
  161179. cinfo->write_Adobe_marker = FALSE; /* write no Adobe marker by default */
  161180. switch (colorspace) {
  161181. case JCS_GRAYSCALE:
  161182. cinfo->write_JFIF_header = TRUE; /* Write a JFIF marker */
  161183. cinfo->num_components = 1;
  161184. /* JFIF specifies component ID 1 */
  161185. SET_COMP(0, 1, 1,1, 0, 0,0);
  161186. break;
  161187. case JCS_RGB:
  161188. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag RGB */
  161189. cinfo->num_components = 3;
  161190. SET_COMP(0, 0x52 /* 'R' */, 1,1, 0, 0,0);
  161191. SET_COMP(1, 0x47 /* 'G' */, 1,1, 0, 0,0);
  161192. SET_COMP(2, 0x42 /* 'B' */, 1,1, 0, 0,0);
  161193. break;
  161194. case JCS_YCbCr:
  161195. cinfo->write_JFIF_header = TRUE; /* Write a JFIF marker */
  161196. cinfo->num_components = 3;
  161197. /* JFIF specifies component IDs 1,2,3 */
  161198. /* We default to 2x2 subsamples of chrominance */
  161199. SET_COMP(0, 1, 2,2, 0, 0,0);
  161200. SET_COMP(1, 2, 1,1, 1, 1,1);
  161201. SET_COMP(2, 3, 1,1, 1, 1,1);
  161202. break;
  161203. case JCS_CMYK:
  161204. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag CMYK */
  161205. cinfo->num_components = 4;
  161206. SET_COMP(0, 0x43 /* 'C' */, 1,1, 0, 0,0);
  161207. SET_COMP(1, 0x4D /* 'M' */, 1,1, 0, 0,0);
  161208. SET_COMP(2, 0x59 /* 'Y' */, 1,1, 0, 0,0);
  161209. SET_COMP(3, 0x4B /* 'K' */, 1,1, 0, 0,0);
  161210. break;
  161211. case JCS_YCCK:
  161212. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag YCCK */
  161213. cinfo->num_components = 4;
  161214. SET_COMP(0, 1, 2,2, 0, 0,0);
  161215. SET_COMP(1, 2, 1,1, 1, 1,1);
  161216. SET_COMP(2, 3, 1,1, 1, 1,1);
  161217. SET_COMP(3, 4, 2,2, 0, 0,0);
  161218. break;
  161219. case JCS_UNKNOWN:
  161220. cinfo->num_components = cinfo->input_components;
  161221. if (cinfo->num_components < 1 || cinfo->num_components > MAX_COMPONENTS)
  161222. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  161223. MAX_COMPONENTS);
  161224. for (ci = 0; ci < cinfo->num_components; ci++) {
  161225. SET_COMP(ci, ci, 1,1, 0, 0,0);
  161226. }
  161227. break;
  161228. default:
  161229. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  161230. }
  161231. }
  161232. #ifdef C_PROGRESSIVE_SUPPORTED
  161233. LOCAL(jpeg_scan_info *)
  161234. fill_a_scan (jpeg_scan_info * scanptr, int ci,
  161235. int Ss, int Se, int Ah, int Al)
  161236. /* Support routine: generate one scan for specified component */
  161237. {
  161238. scanptr->comps_in_scan = 1;
  161239. scanptr->component_index[0] = ci;
  161240. scanptr->Ss = Ss;
  161241. scanptr->Se = Se;
  161242. scanptr->Ah = Ah;
  161243. scanptr->Al = Al;
  161244. scanptr++;
  161245. return scanptr;
  161246. }
  161247. LOCAL(jpeg_scan_info *)
  161248. fill_scans (jpeg_scan_info * scanptr, int ncomps,
  161249. int Ss, int Se, int Ah, int Al)
  161250. /* Support routine: generate one scan for each component */
  161251. {
  161252. int ci;
  161253. for (ci = 0; ci < ncomps; ci++) {
  161254. scanptr->comps_in_scan = 1;
  161255. scanptr->component_index[0] = ci;
  161256. scanptr->Ss = Ss;
  161257. scanptr->Se = Se;
  161258. scanptr->Ah = Ah;
  161259. scanptr->Al = Al;
  161260. scanptr++;
  161261. }
  161262. return scanptr;
  161263. }
  161264. LOCAL(jpeg_scan_info *)
  161265. fill_dc_scans (jpeg_scan_info * scanptr, int ncomps, int Ah, int Al)
  161266. /* Support routine: generate interleaved DC scan if possible, else N scans */
  161267. {
  161268. int ci;
  161269. if (ncomps <= MAX_COMPS_IN_SCAN) {
  161270. /* Single interleaved DC scan */
  161271. scanptr->comps_in_scan = ncomps;
  161272. for (ci = 0; ci < ncomps; ci++)
  161273. scanptr->component_index[ci] = ci;
  161274. scanptr->Ss = scanptr->Se = 0;
  161275. scanptr->Ah = Ah;
  161276. scanptr->Al = Al;
  161277. scanptr++;
  161278. } else {
  161279. /* Noninterleaved DC scan for each component */
  161280. scanptr = fill_scans(scanptr, ncomps, 0, 0, Ah, Al);
  161281. }
  161282. return scanptr;
  161283. }
  161284. /*
  161285. * Create a recommended progressive-JPEG script.
  161286. * cinfo->num_components and cinfo->jpeg_color_space must be correct.
  161287. */
  161288. GLOBAL(void)
  161289. jpeg_simple_progression (j_compress_ptr cinfo)
  161290. {
  161291. int ncomps = cinfo->num_components;
  161292. int nscans;
  161293. jpeg_scan_info * scanptr;
  161294. /* Safety check to ensure start_compress not called yet. */
  161295. if (cinfo->global_state != CSTATE_START)
  161296. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161297. /* Figure space needed for script. Calculation must match code below! */
  161298. if (ncomps == 3 && cinfo->jpeg_color_space == JCS_YCbCr) {
  161299. /* Custom script for YCbCr color images. */
  161300. nscans = 10;
  161301. } else {
  161302. /* All-purpose script for other color spaces. */
  161303. if (ncomps > MAX_COMPS_IN_SCAN)
  161304. nscans = 6 * ncomps; /* 2 DC + 4 AC scans per component */
  161305. else
  161306. nscans = 2 + 4 * ncomps; /* 2 DC scans; 4 AC scans per component */
  161307. }
  161308. /* Allocate space for script.
  161309. * We need to put it in the permanent pool in case the application performs
  161310. * multiple compressions without changing the settings. To avoid a memory
  161311. * leak if jpeg_simple_progression is called repeatedly for the same JPEG
  161312. * object, we try to re-use previously allocated space, and we allocate
  161313. * enough space to handle YCbCr even if initially asked for grayscale.
  161314. */
  161315. if (cinfo->script_space == NULL || cinfo->script_space_size < nscans) {
  161316. cinfo->script_space_size = MAX(nscans, 10);
  161317. cinfo->script_space = (jpeg_scan_info *)
  161318. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  161319. cinfo->script_space_size * SIZEOF(jpeg_scan_info));
  161320. }
  161321. scanptr = cinfo->script_space;
  161322. cinfo->scan_info = scanptr;
  161323. cinfo->num_scans = nscans;
  161324. if (ncomps == 3 && cinfo->jpeg_color_space == JCS_YCbCr) {
  161325. /* Custom script for YCbCr color images. */
  161326. /* Initial DC scan */
  161327. scanptr = fill_dc_scans(scanptr, ncomps, 0, 1);
  161328. /* Initial AC scan: get some luma data out in a hurry */
  161329. scanptr = fill_a_scan(scanptr, 0, 1, 5, 0, 2);
  161330. /* Chroma data is too small to be worth expending many scans on */
  161331. scanptr = fill_a_scan(scanptr, 2, 1, 63, 0, 1);
  161332. scanptr = fill_a_scan(scanptr, 1, 1, 63, 0, 1);
  161333. /* Complete spectral selection for luma AC */
  161334. scanptr = fill_a_scan(scanptr, 0, 6, 63, 0, 2);
  161335. /* Refine next bit of luma AC */
  161336. scanptr = fill_a_scan(scanptr, 0, 1, 63, 2, 1);
  161337. /* Finish DC successive approximation */
  161338. scanptr = fill_dc_scans(scanptr, ncomps, 1, 0);
  161339. /* Finish AC successive approximation */
  161340. scanptr = fill_a_scan(scanptr, 2, 1, 63, 1, 0);
  161341. scanptr = fill_a_scan(scanptr, 1, 1, 63, 1, 0);
  161342. /* Luma bottom bit comes last since it's usually largest scan */
  161343. scanptr = fill_a_scan(scanptr, 0, 1, 63, 1, 0);
  161344. } else {
  161345. /* All-purpose script for other color spaces. */
  161346. /* Successive approximation first pass */
  161347. scanptr = fill_dc_scans(scanptr, ncomps, 0, 1);
  161348. scanptr = fill_scans(scanptr, ncomps, 1, 5, 0, 2);
  161349. scanptr = fill_scans(scanptr, ncomps, 6, 63, 0, 2);
  161350. /* Successive approximation second pass */
  161351. scanptr = fill_scans(scanptr, ncomps, 1, 63, 2, 1);
  161352. /* Successive approximation final pass */
  161353. scanptr = fill_dc_scans(scanptr, ncomps, 1, 0);
  161354. scanptr = fill_scans(scanptr, ncomps, 1, 63, 1, 0);
  161355. }
  161356. }
  161357. #endif /* C_PROGRESSIVE_SUPPORTED */
  161358. /********* End of inlined file: jcparam.c *********/
  161359. /********* Start of inlined file: jcphuff.c *********/
  161360. #define JPEG_INTERNALS
  161361. #ifdef C_PROGRESSIVE_SUPPORTED
  161362. /* Expanded entropy encoder object for progressive Huffman encoding. */
  161363. typedef struct {
  161364. struct jpeg_entropy_encoder pub; /* public fields */
  161365. /* Mode flag: TRUE for optimization, FALSE for actual data output */
  161366. boolean gather_statistics;
  161367. /* Bit-level coding status.
  161368. * next_output_byte/free_in_buffer are local copies of cinfo->dest fields.
  161369. */
  161370. JOCTET * next_output_byte; /* => next byte to write in buffer */
  161371. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  161372. INT32 put_buffer; /* current bit-accumulation buffer */
  161373. int put_bits; /* # of bits now in it */
  161374. j_compress_ptr cinfo; /* link to cinfo (needed for dump_buffer) */
  161375. /* Coding status for DC components */
  161376. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  161377. /* Coding status for AC components */
  161378. int ac_tbl_no; /* the table number of the single component */
  161379. unsigned int EOBRUN; /* run length of EOBs */
  161380. unsigned int BE; /* # of buffered correction bits before MCU */
  161381. char * bit_buffer; /* buffer for correction bits (1 per char) */
  161382. /* packing correction bits tightly would save some space but cost time... */
  161383. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  161384. int next_restart_num; /* next restart number to write (0-7) */
  161385. /* Pointers to derived tables (these workspaces have image lifespan).
  161386. * Since any one scan codes only DC or only AC, we only need one set
  161387. * of tables, not one for DC and one for AC.
  161388. */
  161389. c_derived_tbl * derived_tbls[NUM_HUFF_TBLS];
  161390. /* Statistics tables for optimization; again, one set is enough */
  161391. long * count_ptrs[NUM_HUFF_TBLS];
  161392. } phuff_entropy_encoder;
  161393. typedef phuff_entropy_encoder * phuff_entropy_ptr;
  161394. /* MAX_CORR_BITS is the number of bits the AC refinement correction-bit
  161395. * buffer can hold. Larger sizes may slightly improve compression, but
  161396. * 1000 is already well into the realm of overkill.
  161397. * The minimum safe size is 64 bits.
  161398. */
  161399. #define MAX_CORR_BITS 1000 /* Max # of correction bits I can buffer */
  161400. /* IRIGHT_SHIFT is like RIGHT_SHIFT, but works on int rather than INT32.
  161401. * We assume that int right shift is unsigned if INT32 right shift is,
  161402. * which should be safe.
  161403. */
  161404. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  161405. #define ISHIFT_TEMPS int ishift_temp;
  161406. #define IRIGHT_SHIFT(x,shft) \
  161407. ((ishift_temp = (x)) < 0 ? \
  161408. (ishift_temp >> (shft)) | ((~0) << (16-(shft))) : \
  161409. (ishift_temp >> (shft)))
  161410. #else
  161411. #define ISHIFT_TEMPS
  161412. #define IRIGHT_SHIFT(x,shft) ((x) >> (shft))
  161413. #endif
  161414. /* Forward declarations */
  161415. METHODDEF(boolean) encode_mcu_DC_first JPP((j_compress_ptr cinfo,
  161416. JBLOCKROW *MCU_data));
  161417. METHODDEF(boolean) encode_mcu_AC_first JPP((j_compress_ptr cinfo,
  161418. JBLOCKROW *MCU_data));
  161419. METHODDEF(boolean) encode_mcu_DC_refine JPP((j_compress_ptr cinfo,
  161420. JBLOCKROW *MCU_data));
  161421. METHODDEF(boolean) encode_mcu_AC_refine JPP((j_compress_ptr cinfo,
  161422. JBLOCKROW *MCU_data));
  161423. METHODDEF(void) finish_pass_phuff JPP((j_compress_ptr cinfo));
  161424. METHODDEF(void) finish_pass_gather_phuff JPP((j_compress_ptr cinfo));
  161425. /*
  161426. * Initialize for a Huffman-compressed scan using progressive JPEG.
  161427. */
  161428. METHODDEF(void)
  161429. start_pass_phuff (j_compress_ptr cinfo, boolean gather_statistics)
  161430. {
  161431. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  161432. boolean is_DC_band;
  161433. int ci, tbl;
  161434. jpeg_component_info * compptr;
  161435. entropy->cinfo = cinfo;
  161436. entropy->gather_statistics = gather_statistics;
  161437. is_DC_band = (cinfo->Ss == 0);
  161438. /* We assume jcmaster.c already validated the scan parameters. */
  161439. /* Select execution routines */
  161440. if (cinfo->Ah == 0) {
  161441. if (is_DC_band)
  161442. entropy->pub.encode_mcu = encode_mcu_DC_first;
  161443. else
  161444. entropy->pub.encode_mcu = encode_mcu_AC_first;
  161445. } else {
  161446. if (is_DC_band)
  161447. entropy->pub.encode_mcu = encode_mcu_DC_refine;
  161448. else {
  161449. entropy->pub.encode_mcu = encode_mcu_AC_refine;
  161450. /* AC refinement needs a correction bit buffer */
  161451. if (entropy->bit_buffer == NULL)
  161452. entropy->bit_buffer = (char *)
  161453. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  161454. MAX_CORR_BITS * SIZEOF(char));
  161455. }
  161456. }
  161457. if (gather_statistics)
  161458. entropy->pub.finish_pass = finish_pass_gather_phuff;
  161459. else
  161460. entropy->pub.finish_pass = finish_pass_phuff;
  161461. /* Only DC coefficients may be interleaved, so cinfo->comps_in_scan = 1
  161462. * for AC coefficients.
  161463. */
  161464. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  161465. compptr = cinfo->cur_comp_info[ci];
  161466. /* Initialize DC predictions to 0 */
  161467. entropy->last_dc_val[ci] = 0;
  161468. /* Get table index */
  161469. if (is_DC_band) {
  161470. if (cinfo->Ah != 0) /* DC refinement needs no table */
  161471. continue;
  161472. tbl = compptr->dc_tbl_no;
  161473. } else {
  161474. entropy->ac_tbl_no = tbl = compptr->ac_tbl_no;
  161475. }
  161476. if (gather_statistics) {
  161477. /* Check for invalid table index */
  161478. /* (make_c_derived_tbl does this in the other path) */
  161479. if (tbl < 0 || tbl >= NUM_HUFF_TBLS)
  161480. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tbl);
  161481. /* Allocate and zero the statistics tables */
  161482. /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */
  161483. if (entropy->count_ptrs[tbl] == NULL)
  161484. entropy->count_ptrs[tbl] = (long *)
  161485. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  161486. 257 * SIZEOF(long));
  161487. MEMZERO(entropy->count_ptrs[tbl], 257 * SIZEOF(long));
  161488. } else {
  161489. /* Compute derived values for Huffman table */
  161490. /* We may do this more than once for a table, but it's not expensive */
  161491. jpeg_make_c_derived_tbl(cinfo, is_DC_band, tbl,
  161492. & entropy->derived_tbls[tbl]);
  161493. }
  161494. }
  161495. /* Initialize AC stuff */
  161496. entropy->EOBRUN = 0;
  161497. entropy->BE = 0;
  161498. /* Initialize bit buffer to empty */
  161499. entropy->put_buffer = 0;
  161500. entropy->put_bits = 0;
  161501. /* Initialize restart stuff */
  161502. entropy->restarts_to_go = cinfo->restart_interval;
  161503. entropy->next_restart_num = 0;
  161504. }
  161505. /* Outputting bytes to the file.
  161506. * NB: these must be called only when actually outputting,
  161507. * that is, entropy->gather_statistics == FALSE.
  161508. */
  161509. /* Emit a byte */
  161510. #define emit_byte(entropy,val) \
  161511. { *(entropy)->next_output_byte++ = (JOCTET) (val); \
  161512. if (--(entropy)->free_in_buffer == 0) \
  161513. dump_buffer_p(entropy); }
  161514. LOCAL(void)
  161515. dump_buffer_p (phuff_entropy_ptr entropy)
  161516. /* Empty the output buffer; we do not support suspension in this module. */
  161517. {
  161518. struct jpeg_destination_mgr * dest = entropy->cinfo->dest;
  161519. if (! (*dest->empty_output_buffer) (entropy->cinfo))
  161520. ERREXIT(entropy->cinfo, JERR_CANT_SUSPEND);
  161521. /* After a successful buffer dump, must reset buffer pointers */
  161522. entropy->next_output_byte = dest->next_output_byte;
  161523. entropy->free_in_buffer = dest->free_in_buffer;
  161524. }
  161525. /* Outputting bits to the file */
  161526. /* Only the right 24 bits of put_buffer are used; the valid bits are
  161527. * left-justified in this part. At most 16 bits can be passed to emit_bits
  161528. * in one call, and we never retain more than 7 bits in put_buffer
  161529. * between calls, so 24 bits are sufficient.
  161530. */
  161531. INLINE
  161532. LOCAL(void)
  161533. emit_bits_p (phuff_entropy_ptr entropy, unsigned int code, int size)
  161534. /* Emit some bits, unless we are in gather mode */
  161535. {
  161536. /* This routine is heavily used, so it's worth coding tightly. */
  161537. register INT32 put_buffer = (INT32) code;
  161538. register int put_bits = entropy->put_bits;
  161539. /* if size is 0, caller used an invalid Huffman table entry */
  161540. if (size == 0)
  161541. ERREXIT(entropy->cinfo, JERR_HUFF_MISSING_CODE);
  161542. if (entropy->gather_statistics)
  161543. return; /* do nothing if we're only getting stats */
  161544. put_buffer &= (((INT32) 1)<<size) - 1; /* mask off any extra bits in code */
  161545. put_bits += size; /* new number of bits in buffer */
  161546. put_buffer <<= 24 - put_bits; /* align incoming bits */
  161547. put_buffer |= entropy->put_buffer; /* and merge with old buffer contents */
  161548. while (put_bits >= 8) {
  161549. int c = (int) ((put_buffer >> 16) & 0xFF);
  161550. emit_byte(entropy, c);
  161551. if (c == 0xFF) { /* need to stuff a zero byte? */
  161552. emit_byte(entropy, 0);
  161553. }
  161554. put_buffer <<= 8;
  161555. put_bits -= 8;
  161556. }
  161557. entropy->put_buffer = put_buffer; /* update variables */
  161558. entropy->put_bits = put_bits;
  161559. }
  161560. LOCAL(void)
  161561. flush_bits_p (phuff_entropy_ptr entropy)
  161562. {
  161563. emit_bits_p(entropy, 0x7F, 7); /* fill any partial byte with ones */
  161564. entropy->put_buffer = 0; /* and reset bit-buffer to empty */
  161565. entropy->put_bits = 0;
  161566. }
  161567. /*
  161568. * Emit (or just count) a Huffman symbol.
  161569. */
  161570. INLINE
  161571. LOCAL(void)
  161572. emit_symbol (phuff_entropy_ptr entropy, int tbl_no, int symbol)
  161573. {
  161574. if (entropy->gather_statistics)
  161575. entropy->count_ptrs[tbl_no][symbol]++;
  161576. else {
  161577. c_derived_tbl * tbl = entropy->derived_tbls[tbl_no];
  161578. emit_bits_p(entropy, tbl->ehufco[symbol], tbl->ehufsi[symbol]);
  161579. }
  161580. }
  161581. /*
  161582. * Emit bits from a correction bit buffer.
  161583. */
  161584. LOCAL(void)
  161585. emit_buffered_bits (phuff_entropy_ptr entropy, char * bufstart,
  161586. unsigned int nbits)
  161587. {
  161588. if (entropy->gather_statistics)
  161589. return; /* no real work */
  161590. while (nbits > 0) {
  161591. emit_bits_p(entropy, (unsigned int) (*bufstart), 1);
  161592. bufstart++;
  161593. nbits--;
  161594. }
  161595. }
  161596. /*
  161597. * Emit any pending EOBRUN symbol.
  161598. */
  161599. LOCAL(void)
  161600. emit_eobrun (phuff_entropy_ptr entropy)
  161601. {
  161602. register int temp, nbits;
  161603. if (entropy->EOBRUN > 0) { /* if there is any pending EOBRUN */
  161604. temp = entropy->EOBRUN;
  161605. nbits = 0;
  161606. while ((temp >>= 1))
  161607. nbits++;
  161608. /* safety check: shouldn't happen given limited correction-bit buffer */
  161609. if (nbits > 14)
  161610. ERREXIT(entropy->cinfo, JERR_HUFF_MISSING_CODE);
  161611. emit_symbol(entropy, entropy->ac_tbl_no, nbits << 4);
  161612. if (nbits)
  161613. emit_bits_p(entropy, entropy->EOBRUN, nbits);
  161614. entropy->EOBRUN = 0;
  161615. /* Emit any buffered correction bits */
  161616. emit_buffered_bits(entropy, entropy->bit_buffer, entropy->BE);
  161617. entropy->BE = 0;
  161618. }
  161619. }
  161620. /*
  161621. * Emit a restart marker & resynchronize predictions.
  161622. */
  161623. LOCAL(void)
  161624. emit_restart_p (phuff_entropy_ptr entropy, int restart_num)
  161625. {
  161626. int ci;
  161627. emit_eobrun(entropy);
  161628. if (! entropy->gather_statistics) {
  161629. flush_bits_p(entropy);
  161630. emit_byte(entropy, 0xFF);
  161631. emit_byte(entropy, JPEG_RST0 + restart_num);
  161632. }
  161633. if (entropy->cinfo->Ss == 0) {
  161634. /* Re-initialize DC predictions to 0 */
  161635. for (ci = 0; ci < entropy->cinfo->comps_in_scan; ci++)
  161636. entropy->last_dc_val[ci] = 0;
  161637. } else {
  161638. /* Re-initialize all AC-related fields to 0 */
  161639. entropy->EOBRUN = 0;
  161640. entropy->BE = 0;
  161641. }
  161642. }
  161643. /*
  161644. * MCU encoding for DC initial scan (either spectral selection,
  161645. * or first pass of successive approximation).
  161646. */
  161647. METHODDEF(boolean)
  161648. encode_mcu_DC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  161649. {
  161650. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  161651. register int temp, temp2;
  161652. register int nbits;
  161653. int blkn, ci;
  161654. int Al = cinfo->Al;
  161655. JBLOCKROW block;
  161656. jpeg_component_info * compptr;
  161657. ISHIFT_TEMPS
  161658. entropy->next_output_byte = cinfo->dest->next_output_byte;
  161659. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  161660. /* Emit restart marker if needed */
  161661. if (cinfo->restart_interval)
  161662. if (entropy->restarts_to_go == 0)
  161663. emit_restart_p(entropy, entropy->next_restart_num);
  161664. /* Encode the MCU data blocks */
  161665. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  161666. block = MCU_data[blkn];
  161667. ci = cinfo->MCU_membership[blkn];
  161668. compptr = cinfo->cur_comp_info[ci];
  161669. /* Compute the DC value after the required point transform by Al.
  161670. * This is simply an arithmetic right shift.
  161671. */
  161672. temp2 = IRIGHT_SHIFT((int) ((*block)[0]), Al);
  161673. /* DC differences are figured on the point-transformed values. */
  161674. temp = temp2 - entropy->last_dc_val[ci];
  161675. entropy->last_dc_val[ci] = temp2;
  161676. /* Encode the DC coefficient difference per section G.1.2.1 */
  161677. temp2 = temp;
  161678. if (temp < 0) {
  161679. temp = -temp; /* temp is abs value of input */
  161680. /* For a negative input, want temp2 = bitwise complement of abs(input) */
  161681. /* This code assumes we are on a two's complement machine */
  161682. temp2--;
  161683. }
  161684. /* Find the number of bits needed for the magnitude of the coefficient */
  161685. nbits = 0;
  161686. while (temp) {
  161687. nbits++;
  161688. temp >>= 1;
  161689. }
  161690. /* Check for out-of-range coefficient values.
  161691. * Since we're encoding a difference, the range limit is twice as much.
  161692. */
  161693. if (nbits > MAX_COEF_BITS+1)
  161694. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  161695. /* Count/emit the Huffman-coded symbol for the number of bits */
  161696. emit_symbol(entropy, compptr->dc_tbl_no, nbits);
  161697. /* Emit that number of bits of the value, if positive, */
  161698. /* or the complement of its magnitude, if negative. */
  161699. if (nbits) /* emit_bits rejects calls with size 0 */
  161700. emit_bits_p(entropy, (unsigned int) temp2, nbits);
  161701. }
  161702. cinfo->dest->next_output_byte = entropy->next_output_byte;
  161703. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  161704. /* Update restart-interval state too */
  161705. if (cinfo->restart_interval) {
  161706. if (entropy->restarts_to_go == 0) {
  161707. entropy->restarts_to_go = cinfo->restart_interval;
  161708. entropy->next_restart_num++;
  161709. entropy->next_restart_num &= 7;
  161710. }
  161711. entropy->restarts_to_go--;
  161712. }
  161713. return TRUE;
  161714. }
  161715. /*
  161716. * MCU encoding for AC initial scan (either spectral selection,
  161717. * or first pass of successive approximation).
  161718. */
  161719. METHODDEF(boolean)
  161720. encode_mcu_AC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  161721. {
  161722. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  161723. register int temp, temp2;
  161724. register int nbits;
  161725. register int r, k;
  161726. int Se = cinfo->Se;
  161727. int Al = cinfo->Al;
  161728. JBLOCKROW block;
  161729. entropy->next_output_byte = cinfo->dest->next_output_byte;
  161730. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  161731. /* Emit restart marker if needed */
  161732. if (cinfo->restart_interval)
  161733. if (entropy->restarts_to_go == 0)
  161734. emit_restart_p(entropy, entropy->next_restart_num);
  161735. /* Encode the MCU data block */
  161736. block = MCU_data[0];
  161737. /* Encode the AC coefficients per section G.1.2.2, fig. G.3 */
  161738. r = 0; /* r = run length of zeros */
  161739. for (k = cinfo->Ss; k <= Se; k++) {
  161740. if ((temp = (*block)[jpeg_natural_order[k]]) == 0) {
  161741. r++;
  161742. continue;
  161743. }
  161744. /* We must apply the point transform by Al. For AC coefficients this
  161745. * is an integer division with rounding towards 0. To do this portably
  161746. * in C, we shift after obtaining the absolute value; so the code is
  161747. * interwoven with finding the abs value (temp) and output bits (temp2).
  161748. */
  161749. if (temp < 0) {
  161750. temp = -temp; /* temp is abs value of input */
  161751. temp >>= Al; /* apply the point transform */
  161752. /* For a negative coef, want temp2 = bitwise complement of abs(coef) */
  161753. temp2 = ~temp;
  161754. } else {
  161755. temp >>= Al; /* apply the point transform */
  161756. temp2 = temp;
  161757. }
  161758. /* Watch out for case that nonzero coef is zero after point transform */
  161759. if (temp == 0) {
  161760. r++;
  161761. continue;
  161762. }
  161763. /* Emit any pending EOBRUN */
  161764. if (entropy->EOBRUN > 0)
  161765. emit_eobrun(entropy);
  161766. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  161767. while (r > 15) {
  161768. emit_symbol(entropy, entropy->ac_tbl_no, 0xF0);
  161769. r -= 16;
  161770. }
  161771. /* Find the number of bits needed for the magnitude of the coefficient */
  161772. nbits = 1; /* there must be at least one 1 bit */
  161773. while ((temp >>= 1))
  161774. nbits++;
  161775. /* Check for out-of-range coefficient values */
  161776. if (nbits > MAX_COEF_BITS)
  161777. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  161778. /* Count/emit Huffman symbol for run length / number of bits */
  161779. emit_symbol(entropy, entropy->ac_tbl_no, (r << 4) + nbits);
  161780. /* Emit that number of bits of the value, if positive, */
  161781. /* or the complement of its magnitude, if negative. */
  161782. emit_bits_p(entropy, (unsigned int) temp2, nbits);
  161783. r = 0; /* reset zero run length */
  161784. }
  161785. if (r > 0) { /* If there are trailing zeroes, */
  161786. entropy->EOBRUN++; /* count an EOB */
  161787. if (entropy->EOBRUN == 0x7FFF)
  161788. emit_eobrun(entropy); /* force it out to avoid overflow */
  161789. }
  161790. cinfo->dest->next_output_byte = entropy->next_output_byte;
  161791. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  161792. /* Update restart-interval state too */
  161793. if (cinfo->restart_interval) {
  161794. if (entropy->restarts_to_go == 0) {
  161795. entropy->restarts_to_go = cinfo->restart_interval;
  161796. entropy->next_restart_num++;
  161797. entropy->next_restart_num &= 7;
  161798. }
  161799. entropy->restarts_to_go--;
  161800. }
  161801. return TRUE;
  161802. }
  161803. /*
  161804. * MCU encoding for DC successive approximation refinement scan.
  161805. * Note: we assume such scans can be multi-component, although the spec
  161806. * is not very clear on the point.
  161807. */
  161808. METHODDEF(boolean)
  161809. encode_mcu_DC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  161810. {
  161811. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  161812. register int temp;
  161813. int blkn;
  161814. int Al = cinfo->Al;
  161815. JBLOCKROW block;
  161816. entropy->next_output_byte = cinfo->dest->next_output_byte;
  161817. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  161818. /* Emit restart marker if needed */
  161819. if (cinfo->restart_interval)
  161820. if (entropy->restarts_to_go == 0)
  161821. emit_restart_p(entropy, entropy->next_restart_num);
  161822. /* Encode the MCU data blocks */
  161823. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  161824. block = MCU_data[blkn];
  161825. /* We simply emit the Al'th bit of the DC coefficient value. */
  161826. temp = (*block)[0];
  161827. emit_bits_p(entropy, (unsigned int) (temp >> Al), 1);
  161828. }
  161829. cinfo->dest->next_output_byte = entropy->next_output_byte;
  161830. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  161831. /* Update restart-interval state too */
  161832. if (cinfo->restart_interval) {
  161833. if (entropy->restarts_to_go == 0) {
  161834. entropy->restarts_to_go = cinfo->restart_interval;
  161835. entropy->next_restart_num++;
  161836. entropy->next_restart_num &= 7;
  161837. }
  161838. entropy->restarts_to_go--;
  161839. }
  161840. return TRUE;
  161841. }
  161842. /*
  161843. * MCU encoding for AC successive approximation refinement scan.
  161844. */
  161845. METHODDEF(boolean)
  161846. encode_mcu_AC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  161847. {
  161848. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  161849. register int temp;
  161850. register int r, k;
  161851. int EOB;
  161852. char *BR_buffer;
  161853. unsigned int BR;
  161854. int Se = cinfo->Se;
  161855. int Al = cinfo->Al;
  161856. JBLOCKROW block;
  161857. int absvalues[DCTSIZE2];
  161858. entropy->next_output_byte = cinfo->dest->next_output_byte;
  161859. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  161860. /* Emit restart marker if needed */
  161861. if (cinfo->restart_interval)
  161862. if (entropy->restarts_to_go == 0)
  161863. emit_restart_p(entropy, entropy->next_restart_num);
  161864. /* Encode the MCU data block */
  161865. block = MCU_data[0];
  161866. /* It is convenient to make a pre-pass to determine the transformed
  161867. * coefficients' absolute values and the EOB position.
  161868. */
  161869. EOB = 0;
  161870. for (k = cinfo->Ss; k <= Se; k++) {
  161871. temp = (*block)[jpeg_natural_order[k]];
  161872. /* We must apply the point transform by Al. For AC coefficients this
  161873. * is an integer division with rounding towards 0. To do this portably
  161874. * in C, we shift after obtaining the absolute value.
  161875. */
  161876. if (temp < 0)
  161877. temp = -temp; /* temp is abs value of input */
  161878. temp >>= Al; /* apply the point transform */
  161879. absvalues[k] = temp; /* save abs value for main pass */
  161880. if (temp == 1)
  161881. EOB = k; /* EOB = index of last newly-nonzero coef */
  161882. }
  161883. /* Encode the AC coefficients per section G.1.2.3, fig. G.7 */
  161884. r = 0; /* r = run length of zeros */
  161885. BR = 0; /* BR = count of buffered bits added now */
  161886. BR_buffer = entropy->bit_buffer + entropy->BE; /* Append bits to buffer */
  161887. for (k = cinfo->Ss; k <= Se; k++) {
  161888. if ((temp = absvalues[k]) == 0) {
  161889. r++;
  161890. continue;
  161891. }
  161892. /* Emit any required ZRLs, but not if they can be folded into EOB */
  161893. while (r > 15 && k <= EOB) {
  161894. /* emit any pending EOBRUN and the BE correction bits */
  161895. emit_eobrun(entropy);
  161896. /* Emit ZRL */
  161897. emit_symbol(entropy, entropy->ac_tbl_no, 0xF0);
  161898. r -= 16;
  161899. /* Emit buffered correction bits that must be associated with ZRL */
  161900. emit_buffered_bits(entropy, BR_buffer, BR);
  161901. BR_buffer = entropy->bit_buffer; /* BE bits are gone now */
  161902. BR = 0;
  161903. }
  161904. /* If the coef was previously nonzero, it only needs a correction bit.
  161905. * NOTE: a straight translation of the spec's figure G.7 would suggest
  161906. * that we also need to test r > 15. But if r > 15, we can only get here
  161907. * if k > EOB, which implies that this coefficient is not 1.
  161908. */
  161909. if (temp > 1) {
  161910. /* The correction bit is the next bit of the absolute value. */
  161911. BR_buffer[BR++] = (char) (temp & 1);
  161912. continue;
  161913. }
  161914. /* Emit any pending EOBRUN and the BE correction bits */
  161915. emit_eobrun(entropy);
  161916. /* Count/emit Huffman symbol for run length / number of bits */
  161917. emit_symbol(entropy, entropy->ac_tbl_no, (r << 4) + 1);
  161918. /* Emit output bit for newly-nonzero coef */
  161919. temp = ((*block)[jpeg_natural_order[k]] < 0) ? 0 : 1;
  161920. emit_bits_p(entropy, (unsigned int) temp, 1);
  161921. /* Emit buffered correction bits that must be associated with this code */
  161922. emit_buffered_bits(entropy, BR_buffer, BR);
  161923. BR_buffer = entropy->bit_buffer; /* BE bits are gone now */
  161924. BR = 0;
  161925. r = 0; /* reset zero run length */
  161926. }
  161927. if (r > 0 || BR > 0) { /* If there are trailing zeroes, */
  161928. entropy->EOBRUN++; /* count an EOB */
  161929. entropy->BE += BR; /* concat my correction bits to older ones */
  161930. /* We force out the EOB if we risk either:
  161931. * 1. overflow of the EOB counter;
  161932. * 2. overflow of the correction bit buffer during the next MCU.
  161933. */
  161934. if (entropy->EOBRUN == 0x7FFF || entropy->BE > (MAX_CORR_BITS-DCTSIZE2+1))
  161935. emit_eobrun(entropy);
  161936. }
  161937. cinfo->dest->next_output_byte = entropy->next_output_byte;
  161938. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  161939. /* Update restart-interval state too */
  161940. if (cinfo->restart_interval) {
  161941. if (entropy->restarts_to_go == 0) {
  161942. entropy->restarts_to_go = cinfo->restart_interval;
  161943. entropy->next_restart_num++;
  161944. entropy->next_restart_num &= 7;
  161945. }
  161946. entropy->restarts_to_go--;
  161947. }
  161948. return TRUE;
  161949. }
  161950. /*
  161951. * Finish up at the end of a Huffman-compressed progressive scan.
  161952. */
  161953. METHODDEF(void)
  161954. finish_pass_phuff (j_compress_ptr cinfo)
  161955. {
  161956. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  161957. entropy->next_output_byte = cinfo->dest->next_output_byte;
  161958. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  161959. /* Flush out any buffered data */
  161960. emit_eobrun(entropy);
  161961. flush_bits_p(entropy);
  161962. cinfo->dest->next_output_byte = entropy->next_output_byte;
  161963. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  161964. }
  161965. /*
  161966. * Finish up a statistics-gathering pass and create the new Huffman tables.
  161967. */
  161968. METHODDEF(void)
  161969. finish_pass_gather_phuff (j_compress_ptr cinfo)
  161970. {
  161971. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  161972. boolean is_DC_band;
  161973. int ci, tbl;
  161974. jpeg_component_info * compptr;
  161975. JHUFF_TBL **htblptr;
  161976. boolean did[NUM_HUFF_TBLS];
  161977. /* Flush out buffered data (all we care about is counting the EOB symbol) */
  161978. emit_eobrun(entropy);
  161979. is_DC_band = (cinfo->Ss == 0);
  161980. /* It's important not to apply jpeg_gen_optimal_table more than once
  161981. * per table, because it clobbers the input frequency counts!
  161982. */
  161983. MEMZERO(did, SIZEOF(did));
  161984. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  161985. compptr = cinfo->cur_comp_info[ci];
  161986. if (is_DC_band) {
  161987. if (cinfo->Ah != 0) /* DC refinement needs no table */
  161988. continue;
  161989. tbl = compptr->dc_tbl_no;
  161990. } else {
  161991. tbl = compptr->ac_tbl_no;
  161992. }
  161993. if (! did[tbl]) {
  161994. if (is_DC_band)
  161995. htblptr = & cinfo->dc_huff_tbl_ptrs[tbl];
  161996. else
  161997. htblptr = & cinfo->ac_huff_tbl_ptrs[tbl];
  161998. if (*htblptr == NULL)
  161999. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  162000. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->count_ptrs[tbl]);
  162001. did[tbl] = TRUE;
  162002. }
  162003. }
  162004. }
  162005. /*
  162006. * Module initialization routine for progressive Huffman entropy encoding.
  162007. */
  162008. GLOBAL(void)
  162009. jinit_phuff_encoder (j_compress_ptr cinfo)
  162010. {
  162011. phuff_entropy_ptr entropy;
  162012. int i;
  162013. entropy = (phuff_entropy_ptr)
  162014. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162015. SIZEOF(phuff_entropy_encoder));
  162016. cinfo->entropy = (struct jpeg_entropy_encoder *) entropy;
  162017. entropy->pub.start_pass = start_pass_phuff;
  162018. /* Mark tables unallocated */
  162019. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  162020. entropy->derived_tbls[i] = NULL;
  162021. entropy->count_ptrs[i] = NULL;
  162022. }
  162023. entropy->bit_buffer = NULL; /* needed only in AC refinement scan */
  162024. }
  162025. #endif /* C_PROGRESSIVE_SUPPORTED */
  162026. /********* End of inlined file: jcphuff.c *********/
  162027. /********* Start of inlined file: jcprepct.c *********/
  162028. #define JPEG_INTERNALS
  162029. /* At present, jcsample.c can request context rows only for smoothing.
  162030. * In the future, we might also need context rows for CCIR601 sampling
  162031. * or other more-complex downsampling procedures. The code to support
  162032. * context rows should be compiled only if needed.
  162033. */
  162034. #ifdef INPUT_SMOOTHING_SUPPORTED
  162035. #define CONTEXT_ROWS_SUPPORTED
  162036. #endif
  162037. /*
  162038. * For the simple (no-context-row) case, we just need to buffer one
  162039. * row group's worth of pixels for the downsampling step. At the bottom of
  162040. * the image, we pad to a full row group by replicating the last pixel row.
  162041. * The downsampler's last output row is then replicated if needed to pad
  162042. * out to a full iMCU row.
  162043. *
  162044. * When providing context rows, we must buffer three row groups' worth of
  162045. * pixels. Three row groups are physically allocated, but the row pointer
  162046. * arrays are made five row groups high, with the extra pointers above and
  162047. * below "wrapping around" to point to the last and first real row groups.
  162048. * This allows the downsampler to access the proper context rows.
  162049. * At the top and bottom of the image, we create dummy context rows by
  162050. * copying the first or last real pixel row. This copying could be avoided
  162051. * by pointer hacking as is done in jdmainct.c, but it doesn't seem worth the
  162052. * trouble on the compression side.
  162053. */
  162054. /* Private buffer controller object */
  162055. typedef struct {
  162056. struct jpeg_c_prep_controller pub; /* public fields */
  162057. /* Downsampling input buffer. This buffer holds color-converted data
  162058. * until we have enough to do a downsample step.
  162059. */
  162060. JSAMPARRAY color_buf[MAX_COMPONENTS];
  162061. JDIMENSION rows_to_go; /* counts rows remaining in source image */
  162062. int next_buf_row; /* index of next row to store in color_buf */
  162063. #ifdef CONTEXT_ROWS_SUPPORTED /* only needed for context case */
  162064. int this_row_group; /* starting row index of group to process */
  162065. int next_buf_stop; /* downsample when we reach this index */
  162066. #endif
  162067. } my_prep_controller;
  162068. typedef my_prep_controller * my_prep_ptr;
  162069. /*
  162070. * Initialize for a processing pass.
  162071. */
  162072. METHODDEF(void)
  162073. start_pass_prep (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  162074. {
  162075. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  162076. if (pass_mode != JBUF_PASS_THRU)
  162077. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  162078. /* Initialize total-height counter for detecting bottom of image */
  162079. prep->rows_to_go = cinfo->image_height;
  162080. /* Mark the conversion buffer empty */
  162081. prep->next_buf_row = 0;
  162082. #ifdef CONTEXT_ROWS_SUPPORTED
  162083. /* Preset additional state variables for context mode.
  162084. * These aren't used in non-context mode, so we needn't test which mode.
  162085. */
  162086. prep->this_row_group = 0;
  162087. /* Set next_buf_stop to stop after two row groups have been read in. */
  162088. prep->next_buf_stop = 2 * cinfo->max_v_samp_factor;
  162089. #endif
  162090. }
  162091. /*
  162092. * Expand an image vertically from height input_rows to height output_rows,
  162093. * by duplicating the bottom row.
  162094. */
  162095. LOCAL(void)
  162096. expand_bottom_edge (JSAMPARRAY image_data, JDIMENSION num_cols,
  162097. int input_rows, int output_rows)
  162098. {
  162099. register int row;
  162100. for (row = input_rows; row < output_rows; row++) {
  162101. jcopy_sample_rows(image_data, input_rows-1, image_data, row,
  162102. 1, num_cols);
  162103. }
  162104. }
  162105. /*
  162106. * Process some data in the simple no-context case.
  162107. *
  162108. * Preprocessor output data is counted in "row groups". A row group
  162109. * is defined to be v_samp_factor sample rows of each component.
  162110. * Downsampling will produce this much data from each max_v_samp_factor
  162111. * input rows.
  162112. */
  162113. METHODDEF(void)
  162114. pre_process_data (j_compress_ptr cinfo,
  162115. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  162116. JDIMENSION in_rows_avail,
  162117. JSAMPIMAGE output_buf, JDIMENSION *out_row_group_ctr,
  162118. JDIMENSION out_row_groups_avail)
  162119. {
  162120. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  162121. int numrows, ci;
  162122. JDIMENSION inrows;
  162123. jpeg_component_info * compptr;
  162124. while (*in_row_ctr < in_rows_avail &&
  162125. *out_row_group_ctr < out_row_groups_avail) {
  162126. /* Do color conversion to fill the conversion buffer. */
  162127. inrows = in_rows_avail - *in_row_ctr;
  162128. numrows = cinfo->max_v_samp_factor - prep->next_buf_row;
  162129. numrows = (int) MIN((JDIMENSION) numrows, inrows);
  162130. (*cinfo->cconvert->color_convert) (cinfo, input_buf + *in_row_ctr,
  162131. prep->color_buf,
  162132. (JDIMENSION) prep->next_buf_row,
  162133. numrows);
  162134. *in_row_ctr += numrows;
  162135. prep->next_buf_row += numrows;
  162136. prep->rows_to_go -= numrows;
  162137. /* If at bottom of image, pad to fill the conversion buffer. */
  162138. if (prep->rows_to_go == 0 &&
  162139. prep->next_buf_row < cinfo->max_v_samp_factor) {
  162140. for (ci = 0; ci < cinfo->num_components; ci++) {
  162141. expand_bottom_edge(prep->color_buf[ci], cinfo->image_width,
  162142. prep->next_buf_row, cinfo->max_v_samp_factor);
  162143. }
  162144. prep->next_buf_row = cinfo->max_v_samp_factor;
  162145. }
  162146. /* If we've filled the conversion buffer, empty it. */
  162147. if (prep->next_buf_row == cinfo->max_v_samp_factor) {
  162148. (*cinfo->downsample->downsample) (cinfo,
  162149. prep->color_buf, (JDIMENSION) 0,
  162150. output_buf, *out_row_group_ctr);
  162151. prep->next_buf_row = 0;
  162152. (*out_row_group_ctr)++;
  162153. }
  162154. /* If at bottom of image, pad the output to a full iMCU height.
  162155. * Note we assume the caller is providing a one-iMCU-height output buffer!
  162156. */
  162157. if (prep->rows_to_go == 0 &&
  162158. *out_row_group_ctr < out_row_groups_avail) {
  162159. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  162160. ci++, compptr++) {
  162161. expand_bottom_edge(output_buf[ci],
  162162. compptr->width_in_blocks * DCTSIZE,
  162163. (int) (*out_row_group_ctr * compptr->v_samp_factor),
  162164. (int) (out_row_groups_avail * compptr->v_samp_factor));
  162165. }
  162166. *out_row_group_ctr = out_row_groups_avail;
  162167. break; /* can exit outer loop without test */
  162168. }
  162169. }
  162170. }
  162171. #ifdef CONTEXT_ROWS_SUPPORTED
  162172. /*
  162173. * Process some data in the context case.
  162174. */
  162175. METHODDEF(void)
  162176. pre_process_context (j_compress_ptr cinfo,
  162177. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  162178. JDIMENSION in_rows_avail,
  162179. JSAMPIMAGE output_buf, JDIMENSION *out_row_group_ctr,
  162180. JDIMENSION out_row_groups_avail)
  162181. {
  162182. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  162183. int numrows, ci;
  162184. int buf_height = cinfo->max_v_samp_factor * 3;
  162185. JDIMENSION inrows;
  162186. while (*out_row_group_ctr < out_row_groups_avail) {
  162187. if (*in_row_ctr < in_rows_avail) {
  162188. /* Do color conversion to fill the conversion buffer. */
  162189. inrows = in_rows_avail - *in_row_ctr;
  162190. numrows = prep->next_buf_stop - prep->next_buf_row;
  162191. numrows = (int) MIN((JDIMENSION) numrows, inrows);
  162192. (*cinfo->cconvert->color_convert) (cinfo, input_buf + *in_row_ctr,
  162193. prep->color_buf,
  162194. (JDIMENSION) prep->next_buf_row,
  162195. numrows);
  162196. /* Pad at top of image, if first time through */
  162197. if (prep->rows_to_go == cinfo->image_height) {
  162198. for (ci = 0; ci < cinfo->num_components; ci++) {
  162199. int row;
  162200. for (row = 1; row <= cinfo->max_v_samp_factor; row++) {
  162201. jcopy_sample_rows(prep->color_buf[ci], 0,
  162202. prep->color_buf[ci], -row,
  162203. 1, cinfo->image_width);
  162204. }
  162205. }
  162206. }
  162207. *in_row_ctr += numrows;
  162208. prep->next_buf_row += numrows;
  162209. prep->rows_to_go -= numrows;
  162210. } else {
  162211. /* Return for more data, unless we are at the bottom of the image. */
  162212. if (prep->rows_to_go != 0)
  162213. break;
  162214. /* When at bottom of image, pad to fill the conversion buffer. */
  162215. if (prep->next_buf_row < prep->next_buf_stop) {
  162216. for (ci = 0; ci < cinfo->num_components; ci++) {
  162217. expand_bottom_edge(prep->color_buf[ci], cinfo->image_width,
  162218. prep->next_buf_row, prep->next_buf_stop);
  162219. }
  162220. prep->next_buf_row = prep->next_buf_stop;
  162221. }
  162222. }
  162223. /* If we've gotten enough data, downsample a row group. */
  162224. if (prep->next_buf_row == prep->next_buf_stop) {
  162225. (*cinfo->downsample->downsample) (cinfo,
  162226. prep->color_buf,
  162227. (JDIMENSION) prep->this_row_group,
  162228. output_buf, *out_row_group_ctr);
  162229. (*out_row_group_ctr)++;
  162230. /* Advance pointers with wraparound as necessary. */
  162231. prep->this_row_group += cinfo->max_v_samp_factor;
  162232. if (prep->this_row_group >= buf_height)
  162233. prep->this_row_group = 0;
  162234. if (prep->next_buf_row >= buf_height)
  162235. prep->next_buf_row = 0;
  162236. prep->next_buf_stop = prep->next_buf_row + cinfo->max_v_samp_factor;
  162237. }
  162238. }
  162239. }
  162240. /*
  162241. * Create the wrapped-around downsampling input buffer needed for context mode.
  162242. */
  162243. LOCAL(void)
  162244. create_context_buffer (j_compress_ptr cinfo)
  162245. {
  162246. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  162247. int rgroup_height = cinfo->max_v_samp_factor;
  162248. int ci, i;
  162249. jpeg_component_info * compptr;
  162250. JSAMPARRAY true_buffer, fake_buffer;
  162251. /* Grab enough space for fake row pointers for all the components;
  162252. * we need five row groups' worth of pointers for each component.
  162253. */
  162254. fake_buffer = (JSAMPARRAY)
  162255. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162256. (cinfo->num_components * 5 * rgroup_height) *
  162257. SIZEOF(JSAMPROW));
  162258. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  162259. ci++, compptr++) {
  162260. /* Allocate the actual buffer space (3 row groups) for this component.
  162261. * We make the buffer wide enough to allow the downsampler to edge-expand
  162262. * horizontally within the buffer, if it so chooses.
  162263. */
  162264. true_buffer = (*cinfo->mem->alloc_sarray)
  162265. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162266. (JDIMENSION) (((long) compptr->width_in_blocks * DCTSIZE *
  162267. cinfo->max_h_samp_factor) / compptr->h_samp_factor),
  162268. (JDIMENSION) (3 * rgroup_height));
  162269. /* Copy true buffer row pointers into the middle of the fake row array */
  162270. MEMCOPY(fake_buffer + rgroup_height, true_buffer,
  162271. 3 * rgroup_height * SIZEOF(JSAMPROW));
  162272. /* Fill in the above and below wraparound pointers */
  162273. for (i = 0; i < rgroup_height; i++) {
  162274. fake_buffer[i] = true_buffer[2 * rgroup_height + i];
  162275. fake_buffer[4 * rgroup_height + i] = true_buffer[i];
  162276. }
  162277. prep->color_buf[ci] = fake_buffer + rgroup_height;
  162278. fake_buffer += 5 * rgroup_height; /* point to space for next component */
  162279. }
  162280. }
  162281. #endif /* CONTEXT_ROWS_SUPPORTED */
  162282. /*
  162283. * Initialize preprocessing controller.
  162284. */
  162285. GLOBAL(void)
  162286. jinit_c_prep_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  162287. {
  162288. my_prep_ptr prep;
  162289. int ci;
  162290. jpeg_component_info * compptr;
  162291. if (need_full_buffer) /* safety check */
  162292. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  162293. prep = (my_prep_ptr)
  162294. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162295. SIZEOF(my_prep_controller));
  162296. cinfo->prep = (struct jpeg_c_prep_controller *) prep;
  162297. prep->pub.start_pass = start_pass_prep;
  162298. /* Allocate the color conversion buffer.
  162299. * We make the buffer wide enough to allow the downsampler to edge-expand
  162300. * horizontally within the buffer, if it so chooses.
  162301. */
  162302. if (cinfo->downsample->need_context_rows) {
  162303. /* Set up to provide context rows */
  162304. #ifdef CONTEXT_ROWS_SUPPORTED
  162305. prep->pub.pre_process_data = pre_process_context;
  162306. create_context_buffer(cinfo);
  162307. #else
  162308. ERREXIT(cinfo, JERR_NOT_COMPILED);
  162309. #endif
  162310. } else {
  162311. /* No context, just make it tall enough for one row group */
  162312. prep->pub.pre_process_data = pre_process_data;
  162313. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  162314. ci++, compptr++) {
  162315. prep->color_buf[ci] = (*cinfo->mem->alloc_sarray)
  162316. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162317. (JDIMENSION) (((long) compptr->width_in_blocks * DCTSIZE *
  162318. cinfo->max_h_samp_factor) / compptr->h_samp_factor),
  162319. (JDIMENSION) cinfo->max_v_samp_factor);
  162320. }
  162321. }
  162322. }
  162323. /********* End of inlined file: jcprepct.c *********/
  162324. /********* Start of inlined file: jcsample.c *********/
  162325. #define JPEG_INTERNALS
  162326. /* Pointer to routine to downsample a single component */
  162327. typedef JMETHOD(void, downsample1_ptr,
  162328. (j_compress_ptr cinfo, jpeg_component_info * compptr,
  162329. JSAMPARRAY input_data, JSAMPARRAY output_data));
  162330. /* Private subobject */
  162331. typedef struct {
  162332. struct jpeg_downsampler pub; /* public fields */
  162333. /* Downsampling method pointers, one per component */
  162334. downsample1_ptr methods[MAX_COMPONENTS];
  162335. } my_downsampler;
  162336. typedef my_downsampler * my_downsample_ptr;
  162337. /*
  162338. * Initialize for a downsampling pass.
  162339. */
  162340. METHODDEF(void)
  162341. start_pass_downsample (j_compress_ptr cinfo)
  162342. {
  162343. /* no work for now */
  162344. }
  162345. /*
  162346. * Expand a component horizontally from width input_cols to width output_cols,
  162347. * by duplicating the rightmost samples.
  162348. */
  162349. LOCAL(void)
  162350. expand_right_edge (JSAMPARRAY image_data, int num_rows,
  162351. JDIMENSION input_cols, JDIMENSION output_cols)
  162352. {
  162353. register JSAMPROW ptr;
  162354. register JSAMPLE pixval;
  162355. register int count;
  162356. int row;
  162357. int numcols = (int) (output_cols - input_cols);
  162358. if (numcols > 0) {
  162359. for (row = 0; row < num_rows; row++) {
  162360. ptr = image_data[row] + input_cols;
  162361. pixval = ptr[-1]; /* don't need GETJSAMPLE() here */
  162362. for (count = numcols; count > 0; count--)
  162363. *ptr++ = pixval;
  162364. }
  162365. }
  162366. }
  162367. /*
  162368. * Do downsampling for a whole row group (all components).
  162369. *
  162370. * In this version we simply downsample each component independently.
  162371. */
  162372. METHODDEF(void)
  162373. sep_downsample (j_compress_ptr cinfo,
  162374. JSAMPIMAGE input_buf, JDIMENSION in_row_index,
  162375. JSAMPIMAGE output_buf, JDIMENSION out_row_group_index)
  162376. {
  162377. my_downsample_ptr downsample = (my_downsample_ptr) cinfo->downsample;
  162378. int ci;
  162379. jpeg_component_info * compptr;
  162380. JSAMPARRAY in_ptr, out_ptr;
  162381. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  162382. ci++, compptr++) {
  162383. in_ptr = input_buf[ci] + in_row_index;
  162384. out_ptr = output_buf[ci] + (out_row_group_index * compptr->v_samp_factor);
  162385. (*downsample->methods[ci]) (cinfo, compptr, in_ptr, out_ptr);
  162386. }
  162387. }
  162388. /*
  162389. * Downsample pixel values of a single component.
  162390. * One row group is processed per call.
  162391. * This version handles arbitrary integral sampling ratios, without smoothing.
  162392. * Note that this version is not actually used for customary sampling ratios.
  162393. */
  162394. METHODDEF(void)
  162395. int_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  162396. JSAMPARRAY input_data, JSAMPARRAY output_data)
  162397. {
  162398. int inrow, outrow, h_expand, v_expand, numpix, numpix2, h, v;
  162399. JDIMENSION outcol, outcol_h; /* outcol_h == outcol*h_expand */
  162400. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  162401. JSAMPROW inptr, outptr;
  162402. INT32 outvalue;
  162403. h_expand = cinfo->max_h_samp_factor / compptr->h_samp_factor;
  162404. v_expand = cinfo->max_v_samp_factor / compptr->v_samp_factor;
  162405. numpix = h_expand * v_expand;
  162406. numpix2 = numpix/2;
  162407. /* Expand input data enough to let all the output samples be generated
  162408. * by the standard loop. Special-casing padded output would be more
  162409. * efficient.
  162410. */
  162411. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  162412. cinfo->image_width, output_cols * h_expand);
  162413. inrow = 0;
  162414. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  162415. outptr = output_data[outrow];
  162416. for (outcol = 0, outcol_h = 0; outcol < output_cols;
  162417. outcol++, outcol_h += h_expand) {
  162418. outvalue = 0;
  162419. for (v = 0; v < v_expand; v++) {
  162420. inptr = input_data[inrow+v] + outcol_h;
  162421. for (h = 0; h < h_expand; h++) {
  162422. outvalue += (INT32) GETJSAMPLE(*inptr++);
  162423. }
  162424. }
  162425. *outptr++ = (JSAMPLE) ((outvalue + numpix2) / numpix);
  162426. }
  162427. inrow += v_expand;
  162428. }
  162429. }
  162430. /*
  162431. * Downsample pixel values of a single component.
  162432. * This version handles the special case of a full-size component,
  162433. * without smoothing.
  162434. */
  162435. METHODDEF(void)
  162436. fullsize_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  162437. JSAMPARRAY input_data, JSAMPARRAY output_data)
  162438. {
  162439. /* Copy the data */
  162440. jcopy_sample_rows(input_data, 0, output_data, 0,
  162441. cinfo->max_v_samp_factor, cinfo->image_width);
  162442. /* Edge-expand */
  162443. expand_right_edge(output_data, cinfo->max_v_samp_factor,
  162444. cinfo->image_width, compptr->width_in_blocks * DCTSIZE);
  162445. }
  162446. /*
  162447. * Downsample pixel values of a single component.
  162448. * This version handles the common case of 2:1 horizontal and 1:1 vertical,
  162449. * without smoothing.
  162450. *
  162451. * A note about the "bias" calculations: when rounding fractional values to
  162452. * integer, we do not want to always round 0.5 up to the next integer.
  162453. * If we did that, we'd introduce a noticeable bias towards larger values.
  162454. * Instead, this code is arranged so that 0.5 will be rounded up or down at
  162455. * alternate pixel locations (a simple ordered dither pattern).
  162456. */
  162457. METHODDEF(void)
  162458. h2v1_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  162459. JSAMPARRAY input_data, JSAMPARRAY output_data)
  162460. {
  162461. int outrow;
  162462. JDIMENSION outcol;
  162463. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  162464. register JSAMPROW inptr, outptr;
  162465. register int bias;
  162466. /* Expand input data enough to let all the output samples be generated
  162467. * by the standard loop. Special-casing padded output would be more
  162468. * efficient.
  162469. */
  162470. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  162471. cinfo->image_width, output_cols * 2);
  162472. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  162473. outptr = output_data[outrow];
  162474. inptr = input_data[outrow];
  162475. bias = 0; /* bias = 0,1,0,1,... for successive samples */
  162476. for (outcol = 0; outcol < output_cols; outcol++) {
  162477. *outptr++ = (JSAMPLE) ((GETJSAMPLE(*inptr) + GETJSAMPLE(inptr[1])
  162478. + bias) >> 1);
  162479. bias ^= 1; /* 0=>1, 1=>0 */
  162480. inptr += 2;
  162481. }
  162482. }
  162483. }
  162484. /*
  162485. * Downsample pixel values of a single component.
  162486. * This version handles the standard case of 2:1 horizontal and 2:1 vertical,
  162487. * without smoothing.
  162488. */
  162489. METHODDEF(void)
  162490. h2v2_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  162491. JSAMPARRAY input_data, JSAMPARRAY output_data)
  162492. {
  162493. int inrow, outrow;
  162494. JDIMENSION outcol;
  162495. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  162496. register JSAMPROW inptr0, inptr1, outptr;
  162497. register int bias;
  162498. /* Expand input data enough to let all the output samples be generated
  162499. * by the standard loop. Special-casing padded output would be more
  162500. * efficient.
  162501. */
  162502. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  162503. cinfo->image_width, output_cols * 2);
  162504. inrow = 0;
  162505. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  162506. outptr = output_data[outrow];
  162507. inptr0 = input_data[inrow];
  162508. inptr1 = input_data[inrow+1];
  162509. bias = 1; /* bias = 1,2,1,2,... for successive samples */
  162510. for (outcol = 0; outcol < output_cols; outcol++) {
  162511. *outptr++ = (JSAMPLE) ((GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  162512. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1])
  162513. + bias) >> 2);
  162514. bias ^= 3; /* 1=>2, 2=>1 */
  162515. inptr0 += 2; inptr1 += 2;
  162516. }
  162517. inrow += 2;
  162518. }
  162519. }
  162520. #ifdef INPUT_SMOOTHING_SUPPORTED
  162521. /*
  162522. * Downsample pixel values of a single component.
  162523. * This version handles the standard case of 2:1 horizontal and 2:1 vertical,
  162524. * with smoothing. One row of context is required.
  162525. */
  162526. METHODDEF(void)
  162527. h2v2_smooth_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  162528. JSAMPARRAY input_data, JSAMPARRAY output_data)
  162529. {
  162530. int inrow, outrow;
  162531. JDIMENSION colctr;
  162532. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  162533. register JSAMPROW inptr0, inptr1, above_ptr, below_ptr, outptr;
  162534. INT32 membersum, neighsum, memberscale, neighscale;
  162535. /* Expand input data enough to let all the output samples be generated
  162536. * by the standard loop. Special-casing padded output would be more
  162537. * efficient.
  162538. */
  162539. expand_right_edge(input_data - 1, cinfo->max_v_samp_factor + 2,
  162540. cinfo->image_width, output_cols * 2);
  162541. /* We don't bother to form the individual "smoothed" input pixel values;
  162542. * we can directly compute the output which is the average of the four
  162543. * smoothed values. Each of the four member pixels contributes a fraction
  162544. * (1-8*SF) to its own smoothed image and a fraction SF to each of the three
  162545. * other smoothed pixels, therefore a total fraction (1-5*SF)/4 to the final
  162546. * output. The four corner-adjacent neighbor pixels contribute a fraction
  162547. * SF to just one smoothed pixel, or SF/4 to the final output; while the
  162548. * eight edge-adjacent neighbors contribute SF to each of two smoothed
  162549. * pixels, or SF/2 overall. In order to use integer arithmetic, these
  162550. * factors are scaled by 2^16 = 65536.
  162551. * Also recall that SF = smoothing_factor / 1024.
  162552. */
  162553. memberscale = 16384 - cinfo->smoothing_factor * 80; /* scaled (1-5*SF)/4 */
  162554. neighscale = cinfo->smoothing_factor * 16; /* scaled SF/4 */
  162555. inrow = 0;
  162556. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  162557. outptr = output_data[outrow];
  162558. inptr0 = input_data[inrow];
  162559. inptr1 = input_data[inrow+1];
  162560. above_ptr = input_data[inrow-1];
  162561. below_ptr = input_data[inrow+2];
  162562. /* Special case for first column: pretend column -1 is same as column 0 */
  162563. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  162564. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  162565. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  162566. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  162567. GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[2]) +
  162568. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[2]);
  162569. neighsum += neighsum;
  162570. neighsum += GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[2]) +
  162571. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[2]);
  162572. membersum = membersum * memberscale + neighsum * neighscale;
  162573. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  162574. inptr0 += 2; inptr1 += 2; above_ptr += 2; below_ptr += 2;
  162575. for (colctr = output_cols - 2; colctr > 0; colctr--) {
  162576. /* sum of pixels directly mapped to this output element */
  162577. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  162578. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  162579. /* sum of edge-neighbor pixels */
  162580. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  162581. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  162582. GETJSAMPLE(inptr0[-1]) + GETJSAMPLE(inptr0[2]) +
  162583. GETJSAMPLE(inptr1[-1]) + GETJSAMPLE(inptr1[2]);
  162584. /* The edge-neighbors count twice as much as corner-neighbors */
  162585. neighsum += neighsum;
  162586. /* Add in the corner-neighbors */
  162587. neighsum += GETJSAMPLE(above_ptr[-1]) + GETJSAMPLE(above_ptr[2]) +
  162588. GETJSAMPLE(below_ptr[-1]) + GETJSAMPLE(below_ptr[2]);
  162589. /* form final output scaled up by 2^16 */
  162590. membersum = membersum * memberscale + neighsum * neighscale;
  162591. /* round, descale and output it */
  162592. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  162593. inptr0 += 2; inptr1 += 2; above_ptr += 2; below_ptr += 2;
  162594. }
  162595. /* Special case for last column */
  162596. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  162597. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  162598. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  162599. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  162600. GETJSAMPLE(inptr0[-1]) + GETJSAMPLE(inptr0[1]) +
  162601. GETJSAMPLE(inptr1[-1]) + GETJSAMPLE(inptr1[1]);
  162602. neighsum += neighsum;
  162603. neighsum += GETJSAMPLE(above_ptr[-1]) + GETJSAMPLE(above_ptr[1]) +
  162604. GETJSAMPLE(below_ptr[-1]) + GETJSAMPLE(below_ptr[1]);
  162605. membersum = membersum * memberscale + neighsum * neighscale;
  162606. *outptr = (JSAMPLE) ((membersum + 32768) >> 16);
  162607. inrow += 2;
  162608. }
  162609. }
  162610. /*
  162611. * Downsample pixel values of a single component.
  162612. * This version handles the special case of a full-size component,
  162613. * with smoothing. One row of context is required.
  162614. */
  162615. METHODDEF(void)
  162616. fullsize_smooth_downsample (j_compress_ptr cinfo, jpeg_component_info *compptr,
  162617. JSAMPARRAY input_data, JSAMPARRAY output_data)
  162618. {
  162619. int outrow;
  162620. JDIMENSION colctr;
  162621. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  162622. register JSAMPROW inptr, above_ptr, below_ptr, outptr;
  162623. INT32 membersum, neighsum, memberscale, neighscale;
  162624. int colsum, lastcolsum, nextcolsum;
  162625. /* Expand input data enough to let all the output samples be generated
  162626. * by the standard loop. Special-casing padded output would be more
  162627. * efficient.
  162628. */
  162629. expand_right_edge(input_data - 1, cinfo->max_v_samp_factor + 2,
  162630. cinfo->image_width, output_cols);
  162631. /* Each of the eight neighbor pixels contributes a fraction SF to the
  162632. * smoothed pixel, while the main pixel contributes (1-8*SF). In order
  162633. * to use integer arithmetic, these factors are multiplied by 2^16 = 65536.
  162634. * Also recall that SF = smoothing_factor / 1024.
  162635. */
  162636. memberscale = 65536L - cinfo->smoothing_factor * 512L; /* scaled 1-8*SF */
  162637. neighscale = cinfo->smoothing_factor * 64; /* scaled SF */
  162638. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  162639. outptr = output_data[outrow];
  162640. inptr = input_data[outrow];
  162641. above_ptr = input_data[outrow-1];
  162642. below_ptr = input_data[outrow+1];
  162643. /* Special case for first column */
  162644. colsum = GETJSAMPLE(*above_ptr++) + GETJSAMPLE(*below_ptr++) +
  162645. GETJSAMPLE(*inptr);
  162646. membersum = GETJSAMPLE(*inptr++);
  162647. nextcolsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(*below_ptr) +
  162648. GETJSAMPLE(*inptr);
  162649. neighsum = colsum + (colsum - membersum) + nextcolsum;
  162650. membersum = membersum * memberscale + neighsum * neighscale;
  162651. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  162652. lastcolsum = colsum; colsum = nextcolsum;
  162653. for (colctr = output_cols - 2; colctr > 0; colctr--) {
  162654. membersum = GETJSAMPLE(*inptr++);
  162655. above_ptr++; below_ptr++;
  162656. nextcolsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(*below_ptr) +
  162657. GETJSAMPLE(*inptr);
  162658. neighsum = lastcolsum + (colsum - membersum) + nextcolsum;
  162659. membersum = membersum * memberscale + neighsum * neighscale;
  162660. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  162661. lastcolsum = colsum; colsum = nextcolsum;
  162662. }
  162663. /* Special case for last column */
  162664. membersum = GETJSAMPLE(*inptr);
  162665. neighsum = lastcolsum + (colsum - membersum) + colsum;
  162666. membersum = membersum * memberscale + neighsum * neighscale;
  162667. *outptr = (JSAMPLE) ((membersum + 32768) >> 16);
  162668. }
  162669. }
  162670. #endif /* INPUT_SMOOTHING_SUPPORTED */
  162671. /*
  162672. * Module initialization routine for downsampling.
  162673. * Note that we must select a routine for each component.
  162674. */
  162675. GLOBAL(void)
  162676. jinit_downsampler (j_compress_ptr cinfo)
  162677. {
  162678. my_downsample_ptr downsample;
  162679. int ci;
  162680. jpeg_component_info * compptr;
  162681. boolean smoothok = TRUE;
  162682. downsample = (my_downsample_ptr)
  162683. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162684. SIZEOF(my_downsampler));
  162685. cinfo->downsample = (struct jpeg_downsampler *) downsample;
  162686. downsample->pub.start_pass = start_pass_downsample;
  162687. downsample->pub.downsample = sep_downsample;
  162688. downsample->pub.need_context_rows = FALSE;
  162689. if (cinfo->CCIR601_sampling)
  162690. ERREXIT(cinfo, JERR_CCIR601_NOTIMPL);
  162691. /* Verify we can handle the sampling factors, and set up method pointers */
  162692. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  162693. ci++, compptr++) {
  162694. if (compptr->h_samp_factor == cinfo->max_h_samp_factor &&
  162695. compptr->v_samp_factor == cinfo->max_v_samp_factor) {
  162696. #ifdef INPUT_SMOOTHING_SUPPORTED
  162697. if (cinfo->smoothing_factor) {
  162698. downsample->methods[ci] = fullsize_smooth_downsample;
  162699. downsample->pub.need_context_rows = TRUE;
  162700. } else
  162701. #endif
  162702. downsample->methods[ci] = fullsize_downsample;
  162703. } else if (compptr->h_samp_factor * 2 == cinfo->max_h_samp_factor &&
  162704. compptr->v_samp_factor == cinfo->max_v_samp_factor) {
  162705. smoothok = FALSE;
  162706. downsample->methods[ci] = h2v1_downsample;
  162707. } else if (compptr->h_samp_factor * 2 == cinfo->max_h_samp_factor &&
  162708. compptr->v_samp_factor * 2 == cinfo->max_v_samp_factor) {
  162709. #ifdef INPUT_SMOOTHING_SUPPORTED
  162710. if (cinfo->smoothing_factor) {
  162711. downsample->methods[ci] = h2v2_smooth_downsample;
  162712. downsample->pub.need_context_rows = TRUE;
  162713. } else
  162714. #endif
  162715. downsample->methods[ci] = h2v2_downsample;
  162716. } else if ((cinfo->max_h_samp_factor % compptr->h_samp_factor) == 0 &&
  162717. (cinfo->max_v_samp_factor % compptr->v_samp_factor) == 0) {
  162718. smoothok = FALSE;
  162719. downsample->methods[ci] = int_downsample;
  162720. } else
  162721. ERREXIT(cinfo, JERR_FRACT_SAMPLE_NOTIMPL);
  162722. }
  162723. #ifdef INPUT_SMOOTHING_SUPPORTED
  162724. if (cinfo->smoothing_factor && !smoothok)
  162725. TRACEMS(cinfo, 0, JTRC_SMOOTH_NOTIMPL);
  162726. #endif
  162727. }
  162728. /********* End of inlined file: jcsample.c *********/
  162729. /********* Start of inlined file: jctrans.c *********/
  162730. #define JPEG_INTERNALS
  162731. /* Forward declarations */
  162732. LOCAL(void) transencode_master_selection
  162733. JPP((j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays));
  162734. LOCAL(void) transencode_coef_controller
  162735. JPP((j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays));
  162736. /*
  162737. * Compression initialization for writing raw-coefficient data.
  162738. * Before calling this, all parameters and a data destination must be set up.
  162739. * Call jpeg_finish_compress() to actually write the data.
  162740. *
  162741. * The number of passed virtual arrays must match cinfo->num_components.
  162742. * Note that the virtual arrays need not be filled or even realized at
  162743. * the time write_coefficients is called; indeed, if the virtual arrays
  162744. * were requested from this compression object's memory manager, they
  162745. * typically will be realized during this routine and filled afterwards.
  162746. */
  162747. GLOBAL(void)
  162748. jpeg_write_coefficients (j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays)
  162749. {
  162750. if (cinfo->global_state != CSTATE_START)
  162751. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  162752. /* Mark all tables to be written */
  162753. jpeg_suppress_tables(cinfo, FALSE);
  162754. /* (Re)initialize error mgr and destination modules */
  162755. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  162756. (*cinfo->dest->init_destination) (cinfo);
  162757. /* Perform master selection of active modules */
  162758. transencode_master_selection(cinfo, coef_arrays);
  162759. /* Wait for jpeg_finish_compress() call */
  162760. cinfo->next_scanline = 0; /* so jpeg_write_marker works */
  162761. cinfo->global_state = CSTATE_WRCOEFS;
  162762. }
  162763. /*
  162764. * Initialize the compression object with default parameters,
  162765. * then copy from the source object all parameters needed for lossless
  162766. * transcoding. Parameters that can be varied without loss (such as
  162767. * scan script and Huffman optimization) are left in their default states.
  162768. */
  162769. GLOBAL(void)
  162770. jpeg_copy_critical_parameters (j_decompress_ptr srcinfo,
  162771. j_compress_ptr dstinfo)
  162772. {
  162773. JQUANT_TBL ** qtblptr;
  162774. jpeg_component_info *incomp, *outcomp;
  162775. JQUANT_TBL *c_quant, *slot_quant;
  162776. int tblno, ci, coefi;
  162777. /* Safety check to ensure start_compress not called yet. */
  162778. if (dstinfo->global_state != CSTATE_START)
  162779. ERREXIT1(dstinfo, JERR_BAD_STATE, dstinfo->global_state);
  162780. /* Copy fundamental image dimensions */
  162781. dstinfo->image_width = srcinfo->image_width;
  162782. dstinfo->image_height = srcinfo->image_height;
  162783. dstinfo->input_components = srcinfo->num_components;
  162784. dstinfo->in_color_space = srcinfo->jpeg_color_space;
  162785. /* Initialize all parameters to default values */
  162786. jpeg_set_defaults(dstinfo);
  162787. /* jpeg_set_defaults may choose wrong colorspace, eg YCbCr if input is RGB.
  162788. * Fix it to get the right header markers for the image colorspace.
  162789. */
  162790. jpeg_set_colorspace(dstinfo, srcinfo->jpeg_color_space);
  162791. dstinfo->data_precision = srcinfo->data_precision;
  162792. dstinfo->CCIR601_sampling = srcinfo->CCIR601_sampling;
  162793. /* Copy the source's quantization tables. */
  162794. for (tblno = 0; tblno < NUM_QUANT_TBLS; tblno++) {
  162795. if (srcinfo->quant_tbl_ptrs[tblno] != NULL) {
  162796. qtblptr = & dstinfo->quant_tbl_ptrs[tblno];
  162797. if (*qtblptr == NULL)
  162798. *qtblptr = jpeg_alloc_quant_table((j_common_ptr) dstinfo);
  162799. MEMCOPY((*qtblptr)->quantval,
  162800. srcinfo->quant_tbl_ptrs[tblno]->quantval,
  162801. SIZEOF((*qtblptr)->quantval));
  162802. (*qtblptr)->sent_table = FALSE;
  162803. }
  162804. }
  162805. /* Copy the source's per-component info.
  162806. * Note we assume jpeg_set_defaults has allocated the dest comp_info array.
  162807. */
  162808. dstinfo->num_components = srcinfo->num_components;
  162809. if (dstinfo->num_components < 1 || dstinfo->num_components > MAX_COMPONENTS)
  162810. ERREXIT2(dstinfo, JERR_COMPONENT_COUNT, dstinfo->num_components,
  162811. MAX_COMPONENTS);
  162812. for (ci = 0, incomp = srcinfo->comp_info, outcomp = dstinfo->comp_info;
  162813. ci < dstinfo->num_components; ci++, incomp++, outcomp++) {
  162814. outcomp->component_id = incomp->component_id;
  162815. outcomp->h_samp_factor = incomp->h_samp_factor;
  162816. outcomp->v_samp_factor = incomp->v_samp_factor;
  162817. outcomp->quant_tbl_no = incomp->quant_tbl_no;
  162818. /* Make sure saved quantization table for component matches the qtable
  162819. * slot. If not, the input file re-used this qtable slot.
  162820. * IJG encoder currently cannot duplicate this.
  162821. */
  162822. tblno = outcomp->quant_tbl_no;
  162823. if (tblno < 0 || tblno >= NUM_QUANT_TBLS ||
  162824. srcinfo->quant_tbl_ptrs[tblno] == NULL)
  162825. ERREXIT1(dstinfo, JERR_NO_QUANT_TABLE, tblno);
  162826. slot_quant = srcinfo->quant_tbl_ptrs[tblno];
  162827. c_quant = incomp->quant_table;
  162828. if (c_quant != NULL) {
  162829. for (coefi = 0; coefi < DCTSIZE2; coefi++) {
  162830. if (c_quant->quantval[coefi] != slot_quant->quantval[coefi])
  162831. ERREXIT1(dstinfo, JERR_MISMATCHED_QUANT_TABLE, tblno);
  162832. }
  162833. }
  162834. /* Note: we do not copy the source's Huffman table assignments;
  162835. * instead we rely on jpeg_set_colorspace to have made a suitable choice.
  162836. */
  162837. }
  162838. /* Also copy JFIF version and resolution information, if available.
  162839. * Strictly speaking this isn't "critical" info, but it's nearly
  162840. * always appropriate to copy it if available. In particular,
  162841. * if the application chooses to copy JFIF 1.02 extension markers from
  162842. * the source file, we need to copy the version to make sure we don't
  162843. * emit a file that has 1.02 extensions but a claimed version of 1.01.
  162844. * We will *not*, however, copy version info from mislabeled "2.01" files.
  162845. */
  162846. if (srcinfo->saw_JFIF_marker) {
  162847. if (srcinfo->JFIF_major_version == 1) {
  162848. dstinfo->JFIF_major_version = srcinfo->JFIF_major_version;
  162849. dstinfo->JFIF_minor_version = srcinfo->JFIF_minor_version;
  162850. }
  162851. dstinfo->density_unit = srcinfo->density_unit;
  162852. dstinfo->X_density = srcinfo->X_density;
  162853. dstinfo->Y_density = srcinfo->Y_density;
  162854. }
  162855. }
  162856. /*
  162857. * Master selection of compression modules for transcoding.
  162858. * This substitutes for jcinit.c's initialization of the full compressor.
  162859. */
  162860. LOCAL(void)
  162861. transencode_master_selection (j_compress_ptr cinfo,
  162862. jvirt_barray_ptr * coef_arrays)
  162863. {
  162864. /* Although we don't actually use input_components for transcoding,
  162865. * jcmaster.c's initial_setup will complain if input_components is 0.
  162866. */
  162867. cinfo->input_components = 1;
  162868. /* Initialize master control (includes parameter checking/processing) */
  162869. jinit_c_master_control(cinfo, TRUE /* transcode only */);
  162870. /* Entropy encoding: either Huffman or arithmetic coding. */
  162871. if (cinfo->arith_code) {
  162872. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  162873. } else {
  162874. if (cinfo->progressive_mode) {
  162875. #ifdef C_PROGRESSIVE_SUPPORTED
  162876. jinit_phuff_encoder(cinfo);
  162877. #else
  162878. ERREXIT(cinfo, JERR_NOT_COMPILED);
  162879. #endif
  162880. } else
  162881. jinit_huff_encoder(cinfo);
  162882. }
  162883. /* We need a special coefficient buffer controller. */
  162884. transencode_coef_controller(cinfo, coef_arrays);
  162885. jinit_marker_writer(cinfo);
  162886. /* We can now tell the memory manager to allocate virtual arrays. */
  162887. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  162888. /* Write the datastream header (SOI, JFIF) immediately.
  162889. * Frame and scan headers are postponed till later.
  162890. * This lets application insert special markers after the SOI.
  162891. */
  162892. (*cinfo->marker->write_file_header) (cinfo);
  162893. }
  162894. /*
  162895. * The rest of this file is a special implementation of the coefficient
  162896. * buffer controller. This is similar to jccoefct.c, but it handles only
  162897. * output from presupplied virtual arrays. Furthermore, we generate any
  162898. * dummy padding blocks on-the-fly rather than expecting them to be present
  162899. * in the arrays.
  162900. */
  162901. /* Private buffer controller object */
  162902. typedef struct {
  162903. struct jpeg_c_coef_controller pub; /* public fields */
  162904. JDIMENSION iMCU_row_num; /* iMCU row # within image */
  162905. JDIMENSION mcu_ctr; /* counts MCUs processed in current row */
  162906. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  162907. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  162908. /* Virtual block array for each component. */
  162909. jvirt_barray_ptr * whole_image;
  162910. /* Workspace for constructing dummy blocks at right/bottom edges. */
  162911. JBLOCKROW dummy_buffer[C_MAX_BLOCKS_IN_MCU];
  162912. } my_coef_controller2;
  162913. typedef my_coef_controller2 * my_coef_ptr2;
  162914. LOCAL(void)
  162915. start_iMCU_row2 (j_compress_ptr cinfo)
  162916. /* Reset within-iMCU-row counters for a new row */
  162917. {
  162918. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  162919. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  162920. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  162921. * But at the bottom of the image, process only what's left.
  162922. */
  162923. if (cinfo->comps_in_scan > 1) {
  162924. coef->MCU_rows_per_iMCU_row = 1;
  162925. } else {
  162926. if (coef->iMCU_row_num < (cinfo->total_iMCU_rows-1))
  162927. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  162928. else
  162929. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  162930. }
  162931. coef->mcu_ctr = 0;
  162932. coef->MCU_vert_offset = 0;
  162933. }
  162934. /*
  162935. * Initialize for a processing pass.
  162936. */
  162937. METHODDEF(void)
  162938. start_pass_coef2 (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  162939. {
  162940. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  162941. if (pass_mode != JBUF_CRANK_DEST)
  162942. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  162943. coef->iMCU_row_num = 0;
  162944. start_iMCU_row2(cinfo);
  162945. }
  162946. /*
  162947. * Process some data.
  162948. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  162949. * per call, ie, v_samp_factor block rows for each component in the scan.
  162950. * The data is obtained from the virtual arrays and fed to the entropy coder.
  162951. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  162952. *
  162953. * NB: input_buf is ignored; it is likely to be a NULL pointer.
  162954. */
  162955. METHODDEF(boolean)
  162956. compress_output2 (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
  162957. {
  162958. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  162959. JDIMENSION MCU_col_num; /* index of current MCU within row */
  162960. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  162961. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  162962. int blkn, ci, xindex, yindex, yoffset, blockcnt;
  162963. JDIMENSION start_col;
  162964. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  162965. JBLOCKROW MCU_buffer[C_MAX_BLOCKS_IN_MCU];
  162966. JBLOCKROW buffer_ptr;
  162967. jpeg_component_info *compptr;
  162968. /* Align the virtual buffers for the components used in this scan. */
  162969. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  162970. compptr = cinfo->cur_comp_info[ci];
  162971. buffer[ci] = (*cinfo->mem->access_virt_barray)
  162972. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  162973. coef->iMCU_row_num * compptr->v_samp_factor,
  162974. (JDIMENSION) compptr->v_samp_factor, FALSE);
  162975. }
  162976. /* Loop to process one whole iMCU row */
  162977. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  162978. yoffset++) {
  162979. for (MCU_col_num = coef->mcu_ctr; MCU_col_num < cinfo->MCUs_per_row;
  162980. MCU_col_num++) {
  162981. /* Construct list of pointers to DCT blocks belonging to this MCU */
  162982. blkn = 0; /* index of current DCT block within MCU */
  162983. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  162984. compptr = cinfo->cur_comp_info[ci];
  162985. start_col = MCU_col_num * compptr->MCU_width;
  162986. blockcnt = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  162987. : compptr->last_col_width;
  162988. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  162989. if (coef->iMCU_row_num < last_iMCU_row ||
  162990. yindex+yoffset < compptr->last_row_height) {
  162991. /* Fill in pointers to real blocks in this row */
  162992. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  162993. for (xindex = 0; xindex < blockcnt; xindex++)
  162994. MCU_buffer[blkn++] = buffer_ptr++;
  162995. } else {
  162996. /* At bottom of image, need a whole row of dummy blocks */
  162997. xindex = 0;
  162998. }
  162999. /* Fill in any dummy blocks needed in this row.
  163000. * Dummy blocks are filled in the same way as in jccoefct.c:
  163001. * all zeroes in the AC entries, DC entries equal to previous
  163002. * block's DC value. The init routine has already zeroed the
  163003. * AC entries, so we need only set the DC entries correctly.
  163004. */
  163005. for (; xindex < compptr->MCU_width; xindex++) {
  163006. MCU_buffer[blkn] = coef->dummy_buffer[blkn];
  163007. MCU_buffer[blkn][0][0] = MCU_buffer[blkn-1][0][0];
  163008. blkn++;
  163009. }
  163010. }
  163011. }
  163012. /* Try to write the MCU. */
  163013. if (! (*cinfo->entropy->encode_mcu) (cinfo, MCU_buffer)) {
  163014. /* Suspension forced; update state counters and exit */
  163015. coef->MCU_vert_offset = yoffset;
  163016. coef->mcu_ctr = MCU_col_num;
  163017. return FALSE;
  163018. }
  163019. }
  163020. /* Completed an MCU row, but perhaps not an iMCU row */
  163021. coef->mcu_ctr = 0;
  163022. }
  163023. /* Completed the iMCU row, advance counters for next one */
  163024. coef->iMCU_row_num++;
  163025. start_iMCU_row2(cinfo);
  163026. return TRUE;
  163027. }
  163028. /*
  163029. * Initialize coefficient buffer controller.
  163030. *
  163031. * Each passed coefficient array must be the right size for that
  163032. * coefficient: width_in_blocks wide and height_in_blocks high,
  163033. * with unitheight at least v_samp_factor.
  163034. */
  163035. LOCAL(void)
  163036. transencode_coef_controller (j_compress_ptr cinfo,
  163037. jvirt_barray_ptr * coef_arrays)
  163038. {
  163039. my_coef_ptr2 coef;
  163040. JBLOCKROW buffer;
  163041. int i;
  163042. coef = (my_coef_ptr2)
  163043. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163044. SIZEOF(my_coef_controller2));
  163045. cinfo->coef = (struct jpeg_c_coef_controller *) coef;
  163046. coef->pub.start_pass = start_pass_coef2;
  163047. coef->pub.compress_data = compress_output2;
  163048. /* Save pointer to virtual arrays */
  163049. coef->whole_image = coef_arrays;
  163050. /* Allocate and pre-zero space for dummy DCT blocks. */
  163051. buffer = (JBLOCKROW)
  163052. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163053. C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  163054. jzero_far((void FAR *) buffer, C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  163055. for (i = 0; i < C_MAX_BLOCKS_IN_MCU; i++) {
  163056. coef->dummy_buffer[i] = buffer + i;
  163057. }
  163058. }
  163059. /********* End of inlined file: jctrans.c *********/
  163060. /********* Start of inlined file: jdapistd.c *********/
  163061. #define JPEG_INTERNALS
  163062. /* Forward declarations */
  163063. LOCAL(boolean) output_pass_setup JPP((j_decompress_ptr cinfo));
  163064. /*
  163065. * Decompression initialization.
  163066. * jpeg_read_header must be completed before calling this.
  163067. *
  163068. * If a multipass operating mode was selected, this will do all but the
  163069. * last pass, and thus may take a great deal of time.
  163070. *
  163071. * Returns FALSE if suspended. The return value need be inspected only if
  163072. * a suspending data source is used.
  163073. */
  163074. GLOBAL(boolean)
  163075. jpeg_start_decompress (j_decompress_ptr cinfo)
  163076. {
  163077. if (cinfo->global_state == DSTATE_READY) {
  163078. /* First call: initialize master control, select active modules */
  163079. jinit_master_decompress(cinfo);
  163080. if (cinfo->buffered_image) {
  163081. /* No more work here; expecting jpeg_start_output next */
  163082. cinfo->global_state = DSTATE_BUFIMAGE;
  163083. return TRUE;
  163084. }
  163085. cinfo->global_state = DSTATE_PRELOAD;
  163086. }
  163087. if (cinfo->global_state == DSTATE_PRELOAD) {
  163088. /* If file has multiple scans, absorb them all into the coef buffer */
  163089. if (cinfo->inputctl->has_multiple_scans) {
  163090. #ifdef D_MULTISCAN_FILES_SUPPORTED
  163091. for (;;) {
  163092. int retcode;
  163093. /* Call progress monitor hook if present */
  163094. if (cinfo->progress != NULL)
  163095. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  163096. /* Absorb some more input */
  163097. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  163098. if (retcode == JPEG_SUSPENDED)
  163099. return FALSE;
  163100. if (retcode == JPEG_REACHED_EOI)
  163101. break;
  163102. /* Advance progress counter if appropriate */
  163103. if (cinfo->progress != NULL &&
  163104. (retcode == JPEG_ROW_COMPLETED || retcode == JPEG_REACHED_SOS)) {
  163105. if (++cinfo->progress->pass_counter >= cinfo->progress->pass_limit) {
  163106. /* jdmaster underestimated number of scans; ratchet up one scan */
  163107. cinfo->progress->pass_limit += (long) cinfo->total_iMCU_rows;
  163108. }
  163109. }
  163110. }
  163111. #else
  163112. ERREXIT(cinfo, JERR_NOT_COMPILED);
  163113. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  163114. }
  163115. cinfo->output_scan_number = cinfo->input_scan_number;
  163116. } else if (cinfo->global_state != DSTATE_PRESCAN)
  163117. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  163118. /* Perform any dummy output passes, and set up for the final pass */
  163119. return output_pass_setup(cinfo);
  163120. }
  163121. /*
  163122. * Set up for an output pass, and perform any dummy pass(es) needed.
  163123. * Common subroutine for jpeg_start_decompress and jpeg_start_output.
  163124. * Entry: global_state = DSTATE_PRESCAN only if previously suspended.
  163125. * Exit: If done, returns TRUE and sets global_state for proper output mode.
  163126. * If suspended, returns FALSE and sets global_state = DSTATE_PRESCAN.
  163127. */
  163128. LOCAL(boolean)
  163129. output_pass_setup (j_decompress_ptr cinfo)
  163130. {
  163131. if (cinfo->global_state != DSTATE_PRESCAN) {
  163132. /* First call: do pass setup */
  163133. (*cinfo->master->prepare_for_output_pass) (cinfo);
  163134. cinfo->output_scanline = 0;
  163135. cinfo->global_state = DSTATE_PRESCAN;
  163136. }
  163137. /* Loop over any required dummy passes */
  163138. while (cinfo->master->is_dummy_pass) {
  163139. #ifdef QUANT_2PASS_SUPPORTED
  163140. /* Crank through the dummy pass */
  163141. while (cinfo->output_scanline < cinfo->output_height) {
  163142. JDIMENSION last_scanline;
  163143. /* Call progress monitor hook if present */
  163144. if (cinfo->progress != NULL) {
  163145. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  163146. cinfo->progress->pass_limit = (long) cinfo->output_height;
  163147. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  163148. }
  163149. /* Process some data */
  163150. last_scanline = cinfo->output_scanline;
  163151. (*cinfo->main->process_data) (cinfo, (JSAMPARRAY) NULL,
  163152. &cinfo->output_scanline, (JDIMENSION) 0);
  163153. if (cinfo->output_scanline == last_scanline)
  163154. return FALSE; /* No progress made, must suspend */
  163155. }
  163156. /* Finish up dummy pass, and set up for another one */
  163157. (*cinfo->master->finish_output_pass) (cinfo);
  163158. (*cinfo->master->prepare_for_output_pass) (cinfo);
  163159. cinfo->output_scanline = 0;
  163160. #else
  163161. ERREXIT(cinfo, JERR_NOT_COMPILED);
  163162. #endif /* QUANT_2PASS_SUPPORTED */
  163163. }
  163164. /* Ready for application to drive output pass through
  163165. * jpeg_read_scanlines or jpeg_read_raw_data.
  163166. */
  163167. cinfo->global_state = cinfo->raw_data_out ? DSTATE_RAW_OK : DSTATE_SCANNING;
  163168. return TRUE;
  163169. }
  163170. /*
  163171. * Read some scanlines of data from the JPEG decompressor.
  163172. *
  163173. * The return value will be the number of lines actually read.
  163174. * This may be less than the number requested in several cases,
  163175. * including bottom of image, data source suspension, and operating
  163176. * modes that emit multiple scanlines at a time.
  163177. *
  163178. * Note: we warn about excess calls to jpeg_read_scanlines() since
  163179. * this likely signals an application programmer error. However,
  163180. * an oversize buffer (max_lines > scanlines remaining) is not an error.
  163181. */
  163182. GLOBAL(JDIMENSION)
  163183. jpeg_read_scanlines (j_decompress_ptr cinfo, JSAMPARRAY scanlines,
  163184. JDIMENSION max_lines)
  163185. {
  163186. JDIMENSION row_ctr;
  163187. if (cinfo->global_state != DSTATE_SCANNING)
  163188. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  163189. if (cinfo->output_scanline >= cinfo->output_height) {
  163190. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  163191. return 0;
  163192. }
  163193. /* Call progress monitor hook if present */
  163194. if (cinfo->progress != NULL) {
  163195. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  163196. cinfo->progress->pass_limit = (long) cinfo->output_height;
  163197. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  163198. }
  163199. /* Process some data */
  163200. row_ctr = 0;
  163201. (*cinfo->main->process_data) (cinfo, scanlines, &row_ctr, max_lines);
  163202. cinfo->output_scanline += row_ctr;
  163203. return row_ctr;
  163204. }
  163205. /*
  163206. * Alternate entry point to read raw data.
  163207. * Processes exactly one iMCU row per call, unless suspended.
  163208. */
  163209. GLOBAL(JDIMENSION)
  163210. jpeg_read_raw_data (j_decompress_ptr cinfo, JSAMPIMAGE data,
  163211. JDIMENSION max_lines)
  163212. {
  163213. JDIMENSION lines_per_iMCU_row;
  163214. if (cinfo->global_state != DSTATE_RAW_OK)
  163215. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  163216. if (cinfo->output_scanline >= cinfo->output_height) {
  163217. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  163218. return 0;
  163219. }
  163220. /* Call progress monitor hook if present */
  163221. if (cinfo->progress != NULL) {
  163222. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  163223. cinfo->progress->pass_limit = (long) cinfo->output_height;
  163224. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  163225. }
  163226. /* Verify that at least one iMCU row can be returned. */
  163227. lines_per_iMCU_row = cinfo->max_v_samp_factor * cinfo->min_DCT_scaled_size;
  163228. if (max_lines < lines_per_iMCU_row)
  163229. ERREXIT(cinfo, JERR_BUFFER_SIZE);
  163230. /* Decompress directly into user's buffer. */
  163231. if (! (*cinfo->coef->decompress_data) (cinfo, data))
  163232. return 0; /* suspension forced, can do nothing more */
  163233. /* OK, we processed one iMCU row. */
  163234. cinfo->output_scanline += lines_per_iMCU_row;
  163235. return lines_per_iMCU_row;
  163236. }
  163237. /* Additional entry points for buffered-image mode. */
  163238. #ifdef D_MULTISCAN_FILES_SUPPORTED
  163239. /*
  163240. * Initialize for an output pass in buffered-image mode.
  163241. */
  163242. GLOBAL(boolean)
  163243. jpeg_start_output (j_decompress_ptr cinfo, int scan_number)
  163244. {
  163245. if (cinfo->global_state != DSTATE_BUFIMAGE &&
  163246. cinfo->global_state != DSTATE_PRESCAN)
  163247. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  163248. /* Limit scan number to valid range */
  163249. if (scan_number <= 0)
  163250. scan_number = 1;
  163251. if (cinfo->inputctl->eoi_reached &&
  163252. scan_number > cinfo->input_scan_number)
  163253. scan_number = cinfo->input_scan_number;
  163254. cinfo->output_scan_number = scan_number;
  163255. /* Perform any dummy output passes, and set up for the real pass */
  163256. return output_pass_setup(cinfo);
  163257. }
  163258. /*
  163259. * Finish up after an output pass in buffered-image mode.
  163260. *
  163261. * Returns FALSE if suspended. The return value need be inspected only if
  163262. * a suspending data source is used.
  163263. */
  163264. GLOBAL(boolean)
  163265. jpeg_finish_output (j_decompress_ptr cinfo)
  163266. {
  163267. if ((cinfo->global_state == DSTATE_SCANNING ||
  163268. cinfo->global_state == DSTATE_RAW_OK) && cinfo->buffered_image) {
  163269. /* Terminate this pass. */
  163270. /* We do not require the whole pass to have been completed. */
  163271. (*cinfo->master->finish_output_pass) (cinfo);
  163272. cinfo->global_state = DSTATE_BUFPOST;
  163273. } else if (cinfo->global_state != DSTATE_BUFPOST) {
  163274. /* BUFPOST = repeat call after a suspension, anything else is error */
  163275. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  163276. }
  163277. /* Read markers looking for SOS or EOI */
  163278. while (cinfo->input_scan_number <= cinfo->output_scan_number &&
  163279. ! cinfo->inputctl->eoi_reached) {
  163280. if ((*cinfo->inputctl->consume_input) (cinfo) == JPEG_SUSPENDED)
  163281. return FALSE; /* Suspend, come back later */
  163282. }
  163283. cinfo->global_state = DSTATE_BUFIMAGE;
  163284. return TRUE;
  163285. }
  163286. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  163287. /********* End of inlined file: jdapistd.c *********/
  163288. /********* Start of inlined file: jdapimin.c *********/
  163289. #define JPEG_INTERNALS
  163290. /*
  163291. * Initialization of a JPEG decompression object.
  163292. * The error manager must already be set up (in case memory manager fails).
  163293. */
  163294. GLOBAL(void)
  163295. jpeg_CreateDecompress (j_decompress_ptr cinfo, int version, size_t structsize)
  163296. {
  163297. int i;
  163298. /* Guard against version mismatches between library and caller. */
  163299. cinfo->mem = NULL; /* so jpeg_destroy knows mem mgr not called */
  163300. if (version != JPEG_LIB_VERSION)
  163301. ERREXIT2(cinfo, JERR_BAD_LIB_VERSION, JPEG_LIB_VERSION, version);
  163302. if (structsize != SIZEOF(struct jpeg_decompress_struct))
  163303. ERREXIT2(cinfo, JERR_BAD_STRUCT_SIZE,
  163304. (int) SIZEOF(struct jpeg_decompress_struct), (int) structsize);
  163305. /* For debugging purposes, we zero the whole master structure.
  163306. * But the application has already set the err pointer, and may have set
  163307. * client_data, so we have to save and restore those fields.
  163308. * Note: if application hasn't set client_data, tools like Purify may
  163309. * complain here.
  163310. */
  163311. {
  163312. struct jpeg_error_mgr * err = cinfo->err;
  163313. void * client_data = cinfo->client_data; /* ignore Purify complaint here */
  163314. MEMZERO(cinfo, SIZEOF(struct jpeg_decompress_struct));
  163315. cinfo->err = err;
  163316. cinfo->client_data = client_data;
  163317. }
  163318. cinfo->is_decompressor = TRUE;
  163319. /* Initialize a memory manager instance for this object */
  163320. jinit_memory_mgr((j_common_ptr) cinfo);
  163321. /* Zero out pointers to permanent structures. */
  163322. cinfo->progress = NULL;
  163323. cinfo->src = NULL;
  163324. for (i = 0; i < NUM_QUANT_TBLS; i++)
  163325. cinfo->quant_tbl_ptrs[i] = NULL;
  163326. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  163327. cinfo->dc_huff_tbl_ptrs[i] = NULL;
  163328. cinfo->ac_huff_tbl_ptrs[i] = NULL;
  163329. }
  163330. /* Initialize marker processor so application can override methods
  163331. * for COM, APPn markers before calling jpeg_read_header.
  163332. */
  163333. cinfo->marker_list = NULL;
  163334. jinit_marker_reader(cinfo);
  163335. /* And initialize the overall input controller. */
  163336. jinit_input_controller(cinfo);
  163337. /* OK, I'm ready */
  163338. cinfo->global_state = DSTATE_START;
  163339. }
  163340. /*
  163341. * Destruction of a JPEG decompression object
  163342. */
  163343. GLOBAL(void)
  163344. jpeg_destroy_decompress (j_decompress_ptr cinfo)
  163345. {
  163346. jpeg_destroy((j_common_ptr) cinfo); /* use common routine */
  163347. }
  163348. /*
  163349. * Abort processing of a JPEG decompression operation,
  163350. * but don't destroy the object itself.
  163351. */
  163352. GLOBAL(void)
  163353. jpeg_abort_decompress (j_decompress_ptr cinfo)
  163354. {
  163355. jpeg_abort((j_common_ptr) cinfo); /* use common routine */
  163356. }
  163357. /*
  163358. * Set default decompression parameters.
  163359. */
  163360. LOCAL(void)
  163361. default_decompress_parms (j_decompress_ptr cinfo)
  163362. {
  163363. /* Guess the input colorspace, and set output colorspace accordingly. */
  163364. /* (Wish JPEG committee had provided a real way to specify this...) */
  163365. /* Note application may override our guesses. */
  163366. switch (cinfo->num_components) {
  163367. case 1:
  163368. cinfo->jpeg_color_space = JCS_GRAYSCALE;
  163369. cinfo->out_color_space = JCS_GRAYSCALE;
  163370. break;
  163371. case 3:
  163372. if (cinfo->saw_JFIF_marker) {
  163373. cinfo->jpeg_color_space = JCS_YCbCr; /* JFIF implies YCbCr */
  163374. } else if (cinfo->saw_Adobe_marker) {
  163375. switch (cinfo->Adobe_transform) {
  163376. case 0:
  163377. cinfo->jpeg_color_space = JCS_RGB;
  163378. break;
  163379. case 1:
  163380. cinfo->jpeg_color_space = JCS_YCbCr;
  163381. break;
  163382. default:
  163383. WARNMS1(cinfo, JWRN_ADOBE_XFORM, cinfo->Adobe_transform);
  163384. cinfo->jpeg_color_space = JCS_YCbCr; /* assume it's YCbCr */
  163385. break;
  163386. }
  163387. } else {
  163388. /* Saw no special markers, try to guess from the component IDs */
  163389. int cid0 = cinfo->comp_info[0].component_id;
  163390. int cid1 = cinfo->comp_info[1].component_id;
  163391. int cid2 = cinfo->comp_info[2].component_id;
  163392. if (cid0 == 1 && cid1 == 2 && cid2 == 3)
  163393. cinfo->jpeg_color_space = JCS_YCbCr; /* assume JFIF w/out marker */
  163394. else if (cid0 == 82 && cid1 == 71 && cid2 == 66)
  163395. cinfo->jpeg_color_space = JCS_RGB; /* ASCII 'R', 'G', 'B' */
  163396. else {
  163397. TRACEMS3(cinfo, 1, JTRC_UNKNOWN_IDS, cid0, cid1, cid2);
  163398. cinfo->jpeg_color_space = JCS_YCbCr; /* assume it's YCbCr */
  163399. }
  163400. }
  163401. /* Always guess RGB is proper output colorspace. */
  163402. cinfo->out_color_space = JCS_RGB;
  163403. break;
  163404. case 4:
  163405. if (cinfo->saw_Adobe_marker) {
  163406. switch (cinfo->Adobe_transform) {
  163407. case 0:
  163408. cinfo->jpeg_color_space = JCS_CMYK;
  163409. break;
  163410. case 2:
  163411. cinfo->jpeg_color_space = JCS_YCCK;
  163412. break;
  163413. default:
  163414. WARNMS1(cinfo, JWRN_ADOBE_XFORM, cinfo->Adobe_transform);
  163415. cinfo->jpeg_color_space = JCS_YCCK; /* assume it's YCCK */
  163416. break;
  163417. }
  163418. } else {
  163419. /* No special markers, assume straight CMYK. */
  163420. cinfo->jpeg_color_space = JCS_CMYK;
  163421. }
  163422. cinfo->out_color_space = JCS_CMYK;
  163423. break;
  163424. default:
  163425. cinfo->jpeg_color_space = JCS_UNKNOWN;
  163426. cinfo->out_color_space = JCS_UNKNOWN;
  163427. break;
  163428. }
  163429. /* Set defaults for other decompression parameters. */
  163430. cinfo->scale_num = 1; /* 1:1 scaling */
  163431. cinfo->scale_denom = 1;
  163432. cinfo->output_gamma = 1.0;
  163433. cinfo->buffered_image = FALSE;
  163434. cinfo->raw_data_out = FALSE;
  163435. cinfo->dct_method = JDCT_DEFAULT;
  163436. cinfo->do_fancy_upsampling = TRUE;
  163437. cinfo->do_block_smoothing = TRUE;
  163438. cinfo->quantize_colors = FALSE;
  163439. /* We set these in case application only sets quantize_colors. */
  163440. cinfo->dither_mode = JDITHER_FS;
  163441. #ifdef QUANT_2PASS_SUPPORTED
  163442. cinfo->two_pass_quantize = TRUE;
  163443. #else
  163444. cinfo->two_pass_quantize = FALSE;
  163445. #endif
  163446. cinfo->desired_number_of_colors = 256;
  163447. cinfo->colormap = NULL;
  163448. /* Initialize for no mode change in buffered-image mode. */
  163449. cinfo->enable_1pass_quant = FALSE;
  163450. cinfo->enable_external_quant = FALSE;
  163451. cinfo->enable_2pass_quant = FALSE;
  163452. }
  163453. /*
  163454. * Decompression startup: read start of JPEG datastream to see what's there.
  163455. * Need only initialize JPEG object and supply a data source before calling.
  163456. *
  163457. * This routine will read as far as the first SOS marker (ie, actual start of
  163458. * compressed data), and will save all tables and parameters in the JPEG
  163459. * object. It will also initialize the decompression parameters to default
  163460. * values, and finally return JPEG_HEADER_OK. On return, the application may
  163461. * adjust the decompression parameters and then call jpeg_start_decompress.
  163462. * (Or, if the application only wanted to determine the image parameters,
  163463. * the data need not be decompressed. In that case, call jpeg_abort or
  163464. * jpeg_destroy to release any temporary space.)
  163465. * If an abbreviated (tables only) datastream is presented, the routine will
  163466. * return JPEG_HEADER_TABLES_ONLY upon reaching EOI. The application may then
  163467. * re-use the JPEG object to read the abbreviated image datastream(s).
  163468. * It is unnecessary (but OK) to call jpeg_abort in this case.
  163469. * The JPEG_SUSPENDED return code only occurs if the data source module
  163470. * requests suspension of the decompressor. In this case the application
  163471. * should load more source data and then re-call jpeg_read_header to resume
  163472. * processing.
  163473. * If a non-suspending data source is used and require_image is TRUE, then the
  163474. * return code need not be inspected since only JPEG_HEADER_OK is possible.
  163475. *
  163476. * This routine is now just a front end to jpeg_consume_input, with some
  163477. * extra error checking.
  163478. */
  163479. GLOBAL(int)
  163480. jpeg_read_header (j_decompress_ptr cinfo, boolean require_image)
  163481. {
  163482. int retcode;
  163483. if (cinfo->global_state != DSTATE_START &&
  163484. cinfo->global_state != DSTATE_INHEADER)
  163485. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  163486. retcode = jpeg_consume_input(cinfo);
  163487. switch (retcode) {
  163488. case JPEG_REACHED_SOS:
  163489. retcode = JPEG_HEADER_OK;
  163490. break;
  163491. case JPEG_REACHED_EOI:
  163492. if (require_image) /* Complain if application wanted an image */
  163493. ERREXIT(cinfo, JERR_NO_IMAGE);
  163494. /* Reset to start state; it would be safer to require the application to
  163495. * call jpeg_abort, but we can't change it now for compatibility reasons.
  163496. * A side effect is to free any temporary memory (there shouldn't be any).
  163497. */
  163498. jpeg_abort((j_common_ptr) cinfo); /* sets state = DSTATE_START */
  163499. retcode = JPEG_HEADER_TABLES_ONLY;
  163500. break;
  163501. case JPEG_SUSPENDED:
  163502. /* no work */
  163503. break;
  163504. }
  163505. return retcode;
  163506. }
  163507. /*
  163508. * Consume data in advance of what the decompressor requires.
  163509. * This can be called at any time once the decompressor object has
  163510. * been created and a data source has been set up.
  163511. *
  163512. * This routine is essentially a state machine that handles a couple
  163513. * of critical state-transition actions, namely initial setup and
  163514. * transition from header scanning to ready-for-start_decompress.
  163515. * All the actual input is done via the input controller's consume_input
  163516. * method.
  163517. */
  163518. GLOBAL(int)
  163519. jpeg_consume_input (j_decompress_ptr cinfo)
  163520. {
  163521. int retcode = JPEG_SUSPENDED;
  163522. /* NB: every possible DSTATE value should be listed in this switch */
  163523. switch (cinfo->global_state) {
  163524. case DSTATE_START:
  163525. /* Start-of-datastream actions: reset appropriate modules */
  163526. (*cinfo->inputctl->reset_input_controller) (cinfo);
  163527. /* Initialize application's data source module */
  163528. (*cinfo->src->init_source) (cinfo);
  163529. cinfo->global_state = DSTATE_INHEADER;
  163530. /*FALLTHROUGH*/
  163531. case DSTATE_INHEADER:
  163532. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  163533. if (retcode == JPEG_REACHED_SOS) { /* Found SOS, prepare to decompress */
  163534. /* Set up default parameters based on header data */
  163535. default_decompress_parms(cinfo);
  163536. /* Set global state: ready for start_decompress */
  163537. cinfo->global_state = DSTATE_READY;
  163538. }
  163539. break;
  163540. case DSTATE_READY:
  163541. /* Can't advance past first SOS until start_decompress is called */
  163542. retcode = JPEG_REACHED_SOS;
  163543. break;
  163544. case DSTATE_PRELOAD:
  163545. case DSTATE_PRESCAN:
  163546. case DSTATE_SCANNING:
  163547. case DSTATE_RAW_OK:
  163548. case DSTATE_BUFIMAGE:
  163549. case DSTATE_BUFPOST:
  163550. case DSTATE_STOPPING:
  163551. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  163552. break;
  163553. default:
  163554. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  163555. }
  163556. return retcode;
  163557. }
  163558. /*
  163559. * Have we finished reading the input file?
  163560. */
  163561. GLOBAL(boolean)
  163562. jpeg_input_complete (j_decompress_ptr cinfo)
  163563. {
  163564. /* Check for valid jpeg object */
  163565. if (cinfo->global_state < DSTATE_START ||
  163566. cinfo->global_state > DSTATE_STOPPING)
  163567. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  163568. return cinfo->inputctl->eoi_reached;
  163569. }
  163570. /*
  163571. * Is there more than one scan?
  163572. */
  163573. GLOBAL(boolean)
  163574. jpeg_has_multiple_scans (j_decompress_ptr cinfo)
  163575. {
  163576. /* Only valid after jpeg_read_header completes */
  163577. if (cinfo->global_state < DSTATE_READY ||
  163578. cinfo->global_state > DSTATE_STOPPING)
  163579. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  163580. return cinfo->inputctl->has_multiple_scans;
  163581. }
  163582. /*
  163583. * Finish JPEG decompression.
  163584. *
  163585. * This will normally just verify the file trailer and release temp storage.
  163586. *
  163587. * Returns FALSE if suspended. The return value need be inspected only if
  163588. * a suspending data source is used.
  163589. */
  163590. GLOBAL(boolean)
  163591. jpeg_finish_decompress (j_decompress_ptr cinfo)
  163592. {
  163593. if ((cinfo->global_state == DSTATE_SCANNING ||
  163594. cinfo->global_state == DSTATE_RAW_OK) && ! cinfo->buffered_image) {
  163595. /* Terminate final pass of non-buffered mode */
  163596. if (cinfo->output_scanline < cinfo->output_height)
  163597. ERREXIT(cinfo, JERR_TOO_LITTLE_DATA);
  163598. (*cinfo->master->finish_output_pass) (cinfo);
  163599. cinfo->global_state = DSTATE_STOPPING;
  163600. } else if (cinfo->global_state == DSTATE_BUFIMAGE) {
  163601. /* Finishing after a buffered-image operation */
  163602. cinfo->global_state = DSTATE_STOPPING;
  163603. } else if (cinfo->global_state != DSTATE_STOPPING) {
  163604. /* STOPPING = repeat call after a suspension, anything else is error */
  163605. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  163606. }
  163607. /* Read until EOI */
  163608. while (! cinfo->inputctl->eoi_reached) {
  163609. if ((*cinfo->inputctl->consume_input) (cinfo) == JPEG_SUSPENDED)
  163610. return FALSE; /* Suspend, come back later */
  163611. }
  163612. /* Do final cleanup */
  163613. (*cinfo->src->term_source) (cinfo);
  163614. /* We can use jpeg_abort to release memory and reset global_state */
  163615. jpeg_abort((j_common_ptr) cinfo);
  163616. return TRUE;
  163617. }
  163618. /********* End of inlined file: jdapimin.c *********/
  163619. /********* Start of inlined file: jdatasrc.c *********/
  163620. /* this is not a core library module, so it doesn't define JPEG_INTERNALS */
  163621. /********* Start of inlined file: jerror.h *********/
  163622. /*
  163623. * To define the enum list of message codes, include this file without
  163624. * defining macro JMESSAGE. To create a message string table, include it
  163625. * again with a suitable JMESSAGE definition (see jerror.c for an example).
  163626. */
  163627. #ifndef JMESSAGE
  163628. #ifndef JERROR_H
  163629. /* First time through, define the enum list */
  163630. #define JMAKE_ENUM_LIST
  163631. #else
  163632. /* Repeated inclusions of this file are no-ops unless JMESSAGE is defined */
  163633. #define JMESSAGE(code,string)
  163634. #endif /* JERROR_H */
  163635. #endif /* JMESSAGE */
  163636. #ifdef JMAKE_ENUM_LIST
  163637. typedef enum {
  163638. #define JMESSAGE(code,string) code ,
  163639. #endif /* JMAKE_ENUM_LIST */
  163640. JMESSAGE(JMSG_NOMESSAGE, "Bogus message code %d") /* Must be first entry! */
  163641. /* For maintenance convenience, list is alphabetical by message code name */
  163642. JMESSAGE(JERR_ARITH_NOTIMPL,
  163643. "Sorry, there are legal restrictions on arithmetic coding")
  163644. JMESSAGE(JERR_BAD_ALIGN_TYPE, "ALIGN_TYPE is wrong, please fix")
  163645. JMESSAGE(JERR_BAD_ALLOC_CHUNK, "MAX_ALLOC_CHUNK is wrong, please fix")
  163646. JMESSAGE(JERR_BAD_BUFFER_MODE, "Bogus buffer control mode")
  163647. JMESSAGE(JERR_BAD_COMPONENT_ID, "Invalid component ID %d in SOS")
  163648. JMESSAGE(JERR_BAD_DCT_COEF, "DCT coefficient out of range")
  163649. JMESSAGE(JERR_BAD_DCTSIZE, "IDCT output block size %d not supported")
  163650. JMESSAGE(JERR_BAD_HUFF_TABLE, "Bogus Huffman table definition")
  163651. JMESSAGE(JERR_BAD_IN_COLORSPACE, "Bogus input colorspace")
  163652. JMESSAGE(JERR_BAD_J_COLORSPACE, "Bogus JPEG colorspace")
  163653. JMESSAGE(JERR_BAD_LENGTH, "Bogus marker length")
  163654. JMESSAGE(JERR_BAD_LIB_VERSION,
  163655. "Wrong JPEG library version: library is %d, caller expects %d")
  163656. JMESSAGE(JERR_BAD_MCU_SIZE, "Sampling factors too large for interleaved scan")
  163657. JMESSAGE(JERR_BAD_POOL_ID, "Invalid memory pool code %d")
  163658. JMESSAGE(JERR_BAD_PRECISION, "Unsupported JPEG data precision %d")
  163659. JMESSAGE(JERR_BAD_PROGRESSION,
  163660. "Invalid progressive parameters Ss=%d Se=%d Ah=%d Al=%d")
  163661. JMESSAGE(JERR_BAD_PROG_SCRIPT,
  163662. "Invalid progressive parameters at scan script entry %d")
  163663. JMESSAGE(JERR_BAD_SAMPLING, "Bogus sampling factors")
  163664. JMESSAGE(JERR_BAD_SCAN_SCRIPT, "Invalid scan script at entry %d")
  163665. JMESSAGE(JERR_BAD_STATE, "Improper call to JPEG library in state %d")
  163666. JMESSAGE(JERR_BAD_STRUCT_SIZE,
  163667. "JPEG parameter struct mismatch: library thinks size is %u, caller expects %u")
  163668. JMESSAGE(JERR_BAD_VIRTUAL_ACCESS, "Bogus virtual array access")
  163669. JMESSAGE(JERR_BUFFER_SIZE, "Buffer passed to JPEG library is too small")
  163670. JMESSAGE(JERR_CANT_SUSPEND, "Suspension not allowed here")
  163671. JMESSAGE(JERR_CCIR601_NOTIMPL, "CCIR601 sampling not implemented yet")
  163672. JMESSAGE(JERR_COMPONENT_COUNT, "Too many color components: %d, max %d")
  163673. JMESSAGE(JERR_CONVERSION_NOTIMPL, "Unsupported color conversion request")
  163674. JMESSAGE(JERR_DAC_INDEX, "Bogus DAC index %d")
  163675. JMESSAGE(JERR_DAC_VALUE, "Bogus DAC value 0x%x")
  163676. JMESSAGE(JERR_DHT_INDEX, "Bogus DHT index %d")
  163677. JMESSAGE(JERR_DQT_INDEX, "Bogus DQT index %d")
  163678. JMESSAGE(JERR_EMPTY_IMAGE, "Empty JPEG image (DNL not supported)")
  163679. JMESSAGE(JERR_EMS_READ, "Read from EMS failed")
  163680. JMESSAGE(JERR_EMS_WRITE, "Write to EMS failed")
  163681. JMESSAGE(JERR_EOI_EXPECTED, "Didn't expect more than one scan")
  163682. JMESSAGE(JERR_FILE_READ, "Input file read error")
  163683. JMESSAGE(JERR_FILE_WRITE, "Output file write error --- out of disk space?")
  163684. JMESSAGE(JERR_FRACT_SAMPLE_NOTIMPL, "Fractional sampling not implemented yet")
  163685. JMESSAGE(JERR_HUFF_CLEN_OVERFLOW, "Huffman code size table overflow")
  163686. JMESSAGE(JERR_HUFF_MISSING_CODE, "Missing Huffman code table entry")
  163687. JMESSAGE(JERR_IMAGE_TOO_BIG, "Maximum supported image dimension is %u pixels")
  163688. JMESSAGE(JERR_INPUT_EMPTY, "Empty input file")
  163689. JMESSAGE(JERR_INPUT_EOF, "Premature end of input file")
  163690. JMESSAGE(JERR_MISMATCHED_QUANT_TABLE,
  163691. "Cannot transcode due to multiple use of quantization table %d")
  163692. JMESSAGE(JERR_MISSING_DATA, "Scan script does not transmit all data")
  163693. JMESSAGE(JERR_MODE_CHANGE, "Invalid color quantization mode change")
  163694. JMESSAGE(JERR_NOTIMPL, "Not implemented yet")
  163695. JMESSAGE(JERR_NOT_COMPILED, "Requested feature was omitted at compile time")
  163696. JMESSAGE(JERR_NO_BACKING_STORE, "Backing store not supported")
  163697. JMESSAGE(JERR_NO_HUFF_TABLE, "Huffman table 0x%02x was not defined")
  163698. JMESSAGE(JERR_NO_IMAGE, "JPEG datastream contains no image")
  163699. JMESSAGE(JERR_NO_QUANT_TABLE, "Quantization table 0x%02x was not defined")
  163700. JMESSAGE(JERR_NO_SOI, "Not a JPEG file: starts with 0x%02x 0x%02x")
  163701. JMESSAGE(JERR_OUT_OF_MEMORY, "Insufficient memory (case %d)")
  163702. JMESSAGE(JERR_QUANT_COMPONENTS,
  163703. "Cannot quantize more than %d color components")
  163704. JMESSAGE(JERR_QUANT_FEW_COLORS, "Cannot quantize to fewer than %d colors")
  163705. JMESSAGE(JERR_QUANT_MANY_COLORS, "Cannot quantize to more than %d colors")
  163706. JMESSAGE(JERR_SOF_DUPLICATE, "Invalid JPEG file structure: two SOF markers")
  163707. JMESSAGE(JERR_SOF_NO_SOS, "Invalid JPEG file structure: missing SOS marker")
  163708. JMESSAGE(JERR_SOF_UNSUPPORTED, "Unsupported JPEG process: SOF type 0x%02x")
  163709. JMESSAGE(JERR_SOI_DUPLICATE, "Invalid JPEG file structure: two SOI markers")
  163710. JMESSAGE(JERR_SOS_NO_SOF, "Invalid JPEG file structure: SOS before SOF")
  163711. JMESSAGE(JERR_TFILE_CREATE, "Failed to create temporary file %s")
  163712. JMESSAGE(JERR_TFILE_READ, "Read failed on temporary file")
  163713. JMESSAGE(JERR_TFILE_SEEK, "Seek failed on temporary file")
  163714. JMESSAGE(JERR_TFILE_WRITE,
  163715. "Write failed on temporary file --- out of disk space?")
  163716. JMESSAGE(JERR_TOO_LITTLE_DATA, "Application transferred too few scanlines")
  163717. JMESSAGE(JERR_UNKNOWN_MARKER, "Unsupported marker type 0x%02x")
  163718. JMESSAGE(JERR_VIRTUAL_BUG, "Virtual array controller messed up")
  163719. JMESSAGE(JERR_WIDTH_OVERFLOW, "Image too wide for this implementation")
  163720. JMESSAGE(JERR_XMS_READ, "Read from XMS failed")
  163721. JMESSAGE(JERR_XMS_WRITE, "Write to XMS failed")
  163722. JMESSAGE(JMSG_COPYRIGHT, JCOPYRIGHT)
  163723. JMESSAGE(JMSG_VERSION, JVERSION)
  163724. JMESSAGE(JTRC_16BIT_TABLES,
  163725. "Caution: quantization tables are too coarse for baseline JPEG")
  163726. JMESSAGE(JTRC_ADOBE,
  163727. "Adobe APP14 marker: version %d, flags 0x%04x 0x%04x, transform %d")
  163728. JMESSAGE(JTRC_APP0, "Unknown APP0 marker (not JFIF), length %u")
  163729. JMESSAGE(JTRC_APP14, "Unknown APP14 marker (not Adobe), length %u")
  163730. JMESSAGE(JTRC_DAC, "Define Arithmetic Table 0x%02x: 0x%02x")
  163731. JMESSAGE(JTRC_DHT, "Define Huffman Table 0x%02x")
  163732. JMESSAGE(JTRC_DQT, "Define Quantization Table %d precision %d")
  163733. JMESSAGE(JTRC_DRI, "Define Restart Interval %u")
  163734. JMESSAGE(JTRC_EMS_CLOSE, "Freed EMS handle %u")
  163735. JMESSAGE(JTRC_EMS_OPEN, "Obtained EMS handle %u")
  163736. JMESSAGE(JTRC_EOI, "End Of Image")
  163737. JMESSAGE(JTRC_HUFFBITS, " %3d %3d %3d %3d %3d %3d %3d %3d")
  163738. JMESSAGE(JTRC_JFIF, "JFIF APP0 marker: version %d.%02d, density %dx%d %d")
  163739. JMESSAGE(JTRC_JFIF_BADTHUMBNAILSIZE,
  163740. "Warning: thumbnail image size does not match data length %u")
  163741. JMESSAGE(JTRC_JFIF_EXTENSION,
  163742. "JFIF extension marker: type 0x%02x, length %u")
  163743. JMESSAGE(JTRC_JFIF_THUMBNAIL, " with %d x %d thumbnail image")
  163744. JMESSAGE(JTRC_MISC_MARKER, "Miscellaneous marker 0x%02x, length %u")
  163745. JMESSAGE(JTRC_PARMLESS_MARKER, "Unexpected marker 0x%02x")
  163746. JMESSAGE(JTRC_QUANTVALS, " %4u %4u %4u %4u %4u %4u %4u %4u")
  163747. JMESSAGE(JTRC_QUANT_3_NCOLORS, "Quantizing to %d = %d*%d*%d colors")
  163748. JMESSAGE(JTRC_QUANT_NCOLORS, "Quantizing to %d colors")
  163749. JMESSAGE(JTRC_QUANT_SELECTED, "Selected %d colors for quantization")
  163750. JMESSAGE(JTRC_RECOVERY_ACTION, "At marker 0x%02x, recovery action %d")
  163751. JMESSAGE(JTRC_RST, "RST%d")
  163752. JMESSAGE(JTRC_SMOOTH_NOTIMPL,
  163753. "Smoothing not supported with nonstandard sampling ratios")
  163754. JMESSAGE(JTRC_SOF, "Start Of Frame 0x%02x: width=%u, height=%u, components=%d")
  163755. JMESSAGE(JTRC_SOF_COMPONENT, " Component %d: %dhx%dv q=%d")
  163756. JMESSAGE(JTRC_SOI, "Start of Image")
  163757. JMESSAGE(JTRC_SOS, "Start Of Scan: %d components")
  163758. JMESSAGE(JTRC_SOS_COMPONENT, " Component %d: dc=%d ac=%d")
  163759. JMESSAGE(JTRC_SOS_PARAMS, " Ss=%d, Se=%d, Ah=%d, Al=%d")
  163760. JMESSAGE(JTRC_TFILE_CLOSE, "Closed temporary file %s")
  163761. JMESSAGE(JTRC_TFILE_OPEN, "Opened temporary file %s")
  163762. JMESSAGE(JTRC_THUMB_JPEG,
  163763. "JFIF extension marker: JPEG-compressed thumbnail image, length %u")
  163764. JMESSAGE(JTRC_THUMB_PALETTE,
  163765. "JFIF extension marker: palette thumbnail image, length %u")
  163766. JMESSAGE(JTRC_THUMB_RGB,
  163767. "JFIF extension marker: RGB thumbnail image, length %u")
  163768. JMESSAGE(JTRC_UNKNOWN_IDS,
  163769. "Unrecognized component IDs %d %d %d, assuming YCbCr")
  163770. JMESSAGE(JTRC_XMS_CLOSE, "Freed XMS handle %u")
  163771. JMESSAGE(JTRC_XMS_OPEN, "Obtained XMS handle %u")
  163772. JMESSAGE(JWRN_ADOBE_XFORM, "Unknown Adobe color transform code %d")
  163773. JMESSAGE(JWRN_BOGUS_PROGRESSION,
  163774. "Inconsistent progression sequence for component %d coefficient %d")
  163775. JMESSAGE(JWRN_EXTRANEOUS_DATA,
  163776. "Corrupt JPEG data: %u extraneous bytes before marker 0x%02x")
  163777. JMESSAGE(JWRN_HIT_MARKER, "Corrupt JPEG data: premature end of data segment")
  163778. JMESSAGE(JWRN_HUFF_BAD_CODE, "Corrupt JPEG data: bad Huffman code")
  163779. JMESSAGE(JWRN_JFIF_MAJOR, "Warning: unknown JFIF revision number %d.%02d")
  163780. JMESSAGE(JWRN_JPEG_EOF, "Premature end of JPEG file")
  163781. JMESSAGE(JWRN_MUST_RESYNC,
  163782. "Corrupt JPEG data: found marker 0x%02x instead of RST%d")
  163783. JMESSAGE(JWRN_NOT_SEQUENTIAL, "Invalid SOS parameters for sequential JPEG")
  163784. JMESSAGE(JWRN_TOO_MUCH_DATA, "Application transferred too many scanlines")
  163785. #ifdef JMAKE_ENUM_LIST
  163786. JMSG_LASTMSGCODE
  163787. } J_MESSAGE_CODE;
  163788. #undef JMAKE_ENUM_LIST
  163789. #endif /* JMAKE_ENUM_LIST */
  163790. /* Zap JMESSAGE macro so that future re-inclusions do nothing by default */
  163791. #undef JMESSAGE
  163792. #ifndef JERROR_H
  163793. #define JERROR_H
  163794. /* Macros to simplify using the error and trace message stuff */
  163795. /* The first parameter is either type of cinfo pointer */
  163796. /* Fatal errors (print message and exit) */
  163797. #define ERREXIT(cinfo,code) \
  163798. ((cinfo)->err->msg_code = (code), \
  163799. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  163800. #define ERREXIT1(cinfo,code,p1) \
  163801. ((cinfo)->err->msg_code = (code), \
  163802. (cinfo)->err->msg_parm.i[0] = (p1), \
  163803. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  163804. #define ERREXIT2(cinfo,code,p1,p2) \
  163805. ((cinfo)->err->msg_code = (code), \
  163806. (cinfo)->err->msg_parm.i[0] = (p1), \
  163807. (cinfo)->err->msg_parm.i[1] = (p2), \
  163808. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  163809. #define ERREXIT3(cinfo,code,p1,p2,p3) \
  163810. ((cinfo)->err->msg_code = (code), \
  163811. (cinfo)->err->msg_parm.i[0] = (p1), \
  163812. (cinfo)->err->msg_parm.i[1] = (p2), \
  163813. (cinfo)->err->msg_parm.i[2] = (p3), \
  163814. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  163815. #define ERREXIT4(cinfo,code,p1,p2,p3,p4) \
  163816. ((cinfo)->err->msg_code = (code), \
  163817. (cinfo)->err->msg_parm.i[0] = (p1), \
  163818. (cinfo)->err->msg_parm.i[1] = (p2), \
  163819. (cinfo)->err->msg_parm.i[2] = (p3), \
  163820. (cinfo)->err->msg_parm.i[3] = (p4), \
  163821. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  163822. #define ERREXITS(cinfo,code,str) \
  163823. ((cinfo)->err->msg_code = (code), \
  163824. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  163825. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  163826. #define MAKESTMT(stuff) do { stuff } while (0)
  163827. /* Nonfatal errors (we can keep going, but the data is probably corrupt) */
  163828. #define WARNMS(cinfo,code) \
  163829. ((cinfo)->err->msg_code = (code), \
  163830. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  163831. #define WARNMS1(cinfo,code,p1) \
  163832. ((cinfo)->err->msg_code = (code), \
  163833. (cinfo)->err->msg_parm.i[0] = (p1), \
  163834. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  163835. #define WARNMS2(cinfo,code,p1,p2) \
  163836. ((cinfo)->err->msg_code = (code), \
  163837. (cinfo)->err->msg_parm.i[0] = (p1), \
  163838. (cinfo)->err->msg_parm.i[1] = (p2), \
  163839. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  163840. /* Informational/debugging messages */
  163841. #define TRACEMS(cinfo,lvl,code) \
  163842. ((cinfo)->err->msg_code = (code), \
  163843. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  163844. #define TRACEMS1(cinfo,lvl,code,p1) \
  163845. ((cinfo)->err->msg_code = (code), \
  163846. (cinfo)->err->msg_parm.i[0] = (p1), \
  163847. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  163848. #define TRACEMS2(cinfo,lvl,code,p1,p2) \
  163849. ((cinfo)->err->msg_code = (code), \
  163850. (cinfo)->err->msg_parm.i[0] = (p1), \
  163851. (cinfo)->err->msg_parm.i[1] = (p2), \
  163852. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  163853. #define TRACEMS3(cinfo,lvl,code,p1,p2,p3) \
  163854. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  163855. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); \
  163856. (cinfo)->err->msg_code = (code); \
  163857. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  163858. #define TRACEMS4(cinfo,lvl,code,p1,p2,p3,p4) \
  163859. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  163860. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  163861. (cinfo)->err->msg_code = (code); \
  163862. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  163863. #define TRACEMS5(cinfo,lvl,code,p1,p2,p3,p4,p5) \
  163864. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  163865. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  163866. _mp[4] = (p5); \
  163867. (cinfo)->err->msg_code = (code); \
  163868. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  163869. #define TRACEMS8(cinfo,lvl,code,p1,p2,p3,p4,p5,p6,p7,p8) \
  163870. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  163871. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  163872. _mp[4] = (p5); _mp[5] = (p6); _mp[6] = (p7); _mp[7] = (p8); \
  163873. (cinfo)->err->msg_code = (code); \
  163874. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  163875. #define TRACEMSS(cinfo,lvl,code,str) \
  163876. ((cinfo)->err->msg_code = (code), \
  163877. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  163878. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  163879. #endif /* JERROR_H */
  163880. /********* End of inlined file: jerror.h *********/
  163881. /* Expanded data source object for stdio input */
  163882. typedef struct {
  163883. struct jpeg_source_mgr pub; /* public fields */
  163884. FILE * infile; /* source stream */
  163885. JOCTET * buffer; /* start of buffer */
  163886. boolean start_of_file; /* have we gotten any data yet? */
  163887. } my_source_mgr;
  163888. typedef my_source_mgr * my_src_ptr;
  163889. #define INPUT_BUF_SIZE 4096 /* choose an efficiently fread'able size */
  163890. /*
  163891. * Initialize source --- called by jpeg_read_header
  163892. * before any data is actually read.
  163893. */
  163894. METHODDEF(void)
  163895. init_source (j_decompress_ptr cinfo)
  163896. {
  163897. my_src_ptr src = (my_src_ptr) cinfo->src;
  163898. /* We reset the empty-input-file flag for each image,
  163899. * but we don't clear the input buffer.
  163900. * This is correct behavior for reading a series of images from one source.
  163901. */
  163902. src->start_of_file = TRUE;
  163903. }
  163904. /*
  163905. * Fill the input buffer --- called whenever buffer is emptied.
  163906. *
  163907. * In typical applications, this should read fresh data into the buffer
  163908. * (ignoring the current state of next_input_byte & bytes_in_buffer),
  163909. * reset the pointer & count to the start of the buffer, and return TRUE
  163910. * indicating that the buffer has been reloaded. It is not necessary to
  163911. * fill the buffer entirely, only to obtain at least one more byte.
  163912. *
  163913. * There is no such thing as an EOF return. If the end of the file has been
  163914. * reached, the routine has a choice of ERREXIT() or inserting fake data into
  163915. * the buffer. In most cases, generating a warning message and inserting a
  163916. * fake EOI marker is the best course of action --- this will allow the
  163917. * decompressor to output however much of the image is there. However,
  163918. * the resulting error message is misleading if the real problem is an empty
  163919. * input file, so we handle that case specially.
  163920. *
  163921. * In applications that need to be able to suspend compression due to input
  163922. * not being available yet, a FALSE return indicates that no more data can be
  163923. * obtained right now, but more may be forthcoming later. In this situation,
  163924. * the decompressor will return to its caller (with an indication of the
  163925. * number of scanlines it has read, if any). The application should resume
  163926. * decompression after it has loaded more data into the input buffer. Note
  163927. * that there are substantial restrictions on the use of suspension --- see
  163928. * the documentation.
  163929. *
  163930. * When suspending, the decompressor will back up to a convenient restart point
  163931. * (typically the start of the current MCU). next_input_byte & bytes_in_buffer
  163932. * indicate where the restart point will be if the current call returns FALSE.
  163933. * Data beyond this point must be rescanned after resumption, so move it to
  163934. * the front of the buffer rather than discarding it.
  163935. */
  163936. METHODDEF(boolean)
  163937. fill_input_buffer (j_decompress_ptr cinfo)
  163938. {
  163939. my_src_ptr src = (my_src_ptr) cinfo->src;
  163940. size_t nbytes;
  163941. nbytes = JFREAD(src->infile, src->buffer, INPUT_BUF_SIZE);
  163942. if (nbytes <= 0) {
  163943. if (src->start_of_file) /* Treat empty input file as fatal error */
  163944. ERREXIT(cinfo, JERR_INPUT_EMPTY);
  163945. WARNMS(cinfo, JWRN_JPEG_EOF);
  163946. /* Insert a fake EOI marker */
  163947. src->buffer[0] = (JOCTET) 0xFF;
  163948. src->buffer[1] = (JOCTET) JPEG_EOI;
  163949. nbytes = 2;
  163950. }
  163951. src->pub.next_input_byte = src->buffer;
  163952. src->pub.bytes_in_buffer = nbytes;
  163953. src->start_of_file = FALSE;
  163954. return TRUE;
  163955. }
  163956. /*
  163957. * Skip data --- used to skip over a potentially large amount of
  163958. * uninteresting data (such as an APPn marker).
  163959. *
  163960. * Writers of suspendable-input applications must note that skip_input_data
  163961. * is not granted the right to give a suspension return. If the skip extends
  163962. * beyond the data currently in the buffer, the buffer can be marked empty so
  163963. * that the next read will cause a fill_input_buffer call that can suspend.
  163964. * Arranging for additional bytes to be discarded before reloading the input
  163965. * buffer is the application writer's problem.
  163966. */
  163967. METHODDEF(void)
  163968. skip_input_data (j_decompress_ptr cinfo, long num_bytes)
  163969. {
  163970. my_src_ptr src = (my_src_ptr) cinfo->src;
  163971. /* Just a dumb implementation for now. Could use fseek() except
  163972. * it doesn't work on pipes. Not clear that being smart is worth
  163973. * any trouble anyway --- large skips are infrequent.
  163974. */
  163975. if (num_bytes > 0) {
  163976. while (num_bytes > (long) src->pub.bytes_in_buffer) {
  163977. num_bytes -= (long) src->pub.bytes_in_buffer;
  163978. (void) fill_input_buffer(cinfo);
  163979. /* note we assume that fill_input_buffer will never return FALSE,
  163980. * so suspension need not be handled.
  163981. */
  163982. }
  163983. src->pub.next_input_byte += (size_t) num_bytes;
  163984. src->pub.bytes_in_buffer -= (size_t) num_bytes;
  163985. }
  163986. }
  163987. /*
  163988. * An additional method that can be provided by data source modules is the
  163989. * resync_to_restart method for error recovery in the presence of RST markers.
  163990. * For the moment, this source module just uses the default resync method
  163991. * provided by the JPEG library. That method assumes that no backtracking
  163992. * is possible.
  163993. */
  163994. /*
  163995. * Terminate source --- called by jpeg_finish_decompress
  163996. * after all data has been read. Often a no-op.
  163997. *
  163998. * NB: *not* called by jpeg_abort or jpeg_destroy; surrounding
  163999. * application must deal with any cleanup that should happen even
  164000. * for error exit.
  164001. */
  164002. METHODDEF(void)
  164003. term_source (j_decompress_ptr cinfo)
  164004. {
  164005. /* no work necessary here */
  164006. }
  164007. /*
  164008. * Prepare for input from a stdio stream.
  164009. * The caller must have already opened the stream, and is responsible
  164010. * for closing it after finishing decompression.
  164011. */
  164012. GLOBAL(void)
  164013. jpeg_stdio_src (j_decompress_ptr cinfo, FILE * infile)
  164014. {
  164015. my_src_ptr src;
  164016. /* The source object and input buffer are made permanent so that a series
  164017. * of JPEG images can be read from the same file by calling jpeg_stdio_src
  164018. * only before the first one. (If we discarded the buffer at the end of
  164019. * one image, we'd likely lose the start of the next one.)
  164020. * This makes it unsafe to use this manager and a different source
  164021. * manager serially with the same JPEG object. Caveat programmer.
  164022. */
  164023. if (cinfo->src == NULL) { /* first time for this JPEG object? */
  164024. cinfo->src = (struct jpeg_source_mgr *)
  164025. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  164026. SIZEOF(my_source_mgr));
  164027. src = (my_src_ptr) cinfo->src;
  164028. src->buffer = (JOCTET *)
  164029. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  164030. INPUT_BUF_SIZE * SIZEOF(JOCTET));
  164031. }
  164032. src = (my_src_ptr) cinfo->src;
  164033. src->pub.init_source = init_source;
  164034. src->pub.fill_input_buffer = fill_input_buffer;
  164035. src->pub.skip_input_data = skip_input_data;
  164036. src->pub.resync_to_restart = jpeg_resync_to_restart; /* use default method */
  164037. src->pub.term_source = term_source;
  164038. src->infile = infile;
  164039. src->pub.bytes_in_buffer = 0; /* forces fill_input_buffer on first read */
  164040. src->pub.next_input_byte = NULL; /* until buffer loaded */
  164041. }
  164042. /********* End of inlined file: jdatasrc.c *********/
  164043. /********* Start of inlined file: jdcoefct.c *********/
  164044. #define JPEG_INTERNALS
  164045. /* Block smoothing is only applicable for progressive JPEG, so: */
  164046. #ifndef D_PROGRESSIVE_SUPPORTED
  164047. #undef BLOCK_SMOOTHING_SUPPORTED
  164048. #endif
  164049. /* Private buffer controller object */
  164050. typedef struct {
  164051. struct jpeg_d_coef_controller pub; /* public fields */
  164052. /* These variables keep track of the current location of the input side. */
  164053. /* cinfo->input_iMCU_row is also used for this. */
  164054. JDIMENSION MCU_ctr; /* counts MCUs processed in current row */
  164055. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  164056. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  164057. /* The output side's location is represented by cinfo->output_iMCU_row. */
  164058. /* In single-pass modes, it's sufficient to buffer just one MCU.
  164059. * We allocate a workspace of D_MAX_BLOCKS_IN_MCU coefficient blocks,
  164060. * and let the entropy decoder write into that workspace each time.
  164061. * (On 80x86, the workspace is FAR even though it's not really very big;
  164062. * this is to keep the module interfaces unchanged when a large coefficient
  164063. * buffer is necessary.)
  164064. * In multi-pass modes, this array points to the current MCU's blocks
  164065. * within the virtual arrays; it is used only by the input side.
  164066. */
  164067. JBLOCKROW MCU_buffer[D_MAX_BLOCKS_IN_MCU];
  164068. #ifdef D_MULTISCAN_FILES_SUPPORTED
  164069. /* In multi-pass modes, we need a virtual block array for each component. */
  164070. jvirt_barray_ptr whole_image[MAX_COMPONENTS];
  164071. #endif
  164072. #ifdef BLOCK_SMOOTHING_SUPPORTED
  164073. /* When doing block smoothing, we latch coefficient Al values here */
  164074. int * coef_bits_latch;
  164075. #define SAVED_COEFS 6 /* we save coef_bits[0..5] */
  164076. #endif
  164077. } my_coef_controller3;
  164078. typedef my_coef_controller3 * my_coef_ptr3;
  164079. /* Forward declarations */
  164080. METHODDEF(int) decompress_onepass
  164081. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  164082. #ifdef D_MULTISCAN_FILES_SUPPORTED
  164083. METHODDEF(int) decompress_data
  164084. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  164085. #endif
  164086. #ifdef BLOCK_SMOOTHING_SUPPORTED
  164087. LOCAL(boolean) smoothing_ok JPP((j_decompress_ptr cinfo));
  164088. METHODDEF(int) decompress_smooth_data
  164089. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  164090. #endif
  164091. LOCAL(void)
  164092. start_iMCU_row3 (j_decompress_ptr cinfo)
  164093. /* Reset within-iMCU-row counters for a new row (input side) */
  164094. {
  164095. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  164096. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  164097. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  164098. * But at the bottom of the image, process only what's left.
  164099. */
  164100. if (cinfo->comps_in_scan > 1) {
  164101. coef->MCU_rows_per_iMCU_row = 1;
  164102. } else {
  164103. if (cinfo->input_iMCU_row < (cinfo->total_iMCU_rows-1))
  164104. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  164105. else
  164106. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  164107. }
  164108. coef->MCU_ctr = 0;
  164109. coef->MCU_vert_offset = 0;
  164110. }
  164111. /*
  164112. * Initialize for an input processing pass.
  164113. */
  164114. METHODDEF(void)
  164115. start_input_pass (j_decompress_ptr cinfo)
  164116. {
  164117. cinfo->input_iMCU_row = 0;
  164118. start_iMCU_row3(cinfo);
  164119. }
  164120. /*
  164121. * Initialize for an output processing pass.
  164122. */
  164123. METHODDEF(void)
  164124. start_output_pass (j_decompress_ptr cinfo)
  164125. {
  164126. #ifdef BLOCK_SMOOTHING_SUPPORTED
  164127. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  164128. /* If multipass, check to see whether to use block smoothing on this pass */
  164129. if (coef->pub.coef_arrays != NULL) {
  164130. if (cinfo->do_block_smoothing && smoothing_ok(cinfo))
  164131. coef->pub.decompress_data = decompress_smooth_data;
  164132. else
  164133. coef->pub.decompress_data = decompress_data;
  164134. }
  164135. #endif
  164136. cinfo->output_iMCU_row = 0;
  164137. }
  164138. /*
  164139. * Decompress and return some data in the single-pass case.
  164140. * Always attempts to emit one fully interleaved MCU row ("iMCU" row).
  164141. * Input and output must run in lockstep since we have only a one-MCU buffer.
  164142. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  164143. *
  164144. * NB: output_buf contains a plane for each component in image,
  164145. * which we index according to the component's SOF position.
  164146. */
  164147. METHODDEF(int)
  164148. decompress_onepass (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  164149. {
  164150. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  164151. JDIMENSION MCU_col_num; /* index of current MCU within row */
  164152. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  164153. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  164154. int blkn, ci, xindex, yindex, yoffset, useful_width;
  164155. JSAMPARRAY output_ptr;
  164156. JDIMENSION start_col, output_col;
  164157. jpeg_component_info *compptr;
  164158. inverse_DCT_method_ptr inverse_DCT;
  164159. /* Loop to process as much as one whole iMCU row */
  164160. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  164161. yoffset++) {
  164162. for (MCU_col_num = coef->MCU_ctr; MCU_col_num <= last_MCU_col;
  164163. MCU_col_num++) {
  164164. /* Try to fetch an MCU. Entropy decoder expects buffer to be zeroed. */
  164165. jzero_far((void FAR *) coef->MCU_buffer[0],
  164166. (size_t) (cinfo->blocks_in_MCU * SIZEOF(JBLOCK)));
  164167. if (! (*cinfo->entropy->decode_mcu) (cinfo, coef->MCU_buffer)) {
  164168. /* Suspension forced; update state counters and exit */
  164169. coef->MCU_vert_offset = yoffset;
  164170. coef->MCU_ctr = MCU_col_num;
  164171. return JPEG_SUSPENDED;
  164172. }
  164173. /* Determine where data should go in output_buf and do the IDCT thing.
  164174. * We skip dummy blocks at the right and bottom edges (but blkn gets
  164175. * incremented past them!). Note the inner loop relies on having
  164176. * allocated the MCU_buffer[] blocks sequentially.
  164177. */
  164178. blkn = 0; /* index of current DCT block within MCU */
  164179. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  164180. compptr = cinfo->cur_comp_info[ci];
  164181. /* Don't bother to IDCT an uninteresting component. */
  164182. if (! compptr->component_needed) {
  164183. blkn += compptr->MCU_blocks;
  164184. continue;
  164185. }
  164186. inverse_DCT = cinfo->idct->inverse_DCT[compptr->component_index];
  164187. useful_width = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  164188. : compptr->last_col_width;
  164189. output_ptr = output_buf[compptr->component_index] +
  164190. yoffset * compptr->DCT_scaled_size;
  164191. start_col = MCU_col_num * compptr->MCU_sample_width;
  164192. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  164193. if (cinfo->input_iMCU_row < last_iMCU_row ||
  164194. yoffset+yindex < compptr->last_row_height) {
  164195. output_col = start_col;
  164196. for (xindex = 0; xindex < useful_width; xindex++) {
  164197. (*inverse_DCT) (cinfo, compptr,
  164198. (JCOEFPTR) coef->MCU_buffer[blkn+xindex],
  164199. output_ptr, output_col);
  164200. output_col += compptr->DCT_scaled_size;
  164201. }
  164202. }
  164203. blkn += compptr->MCU_width;
  164204. output_ptr += compptr->DCT_scaled_size;
  164205. }
  164206. }
  164207. }
  164208. /* Completed an MCU row, but perhaps not an iMCU row */
  164209. coef->MCU_ctr = 0;
  164210. }
  164211. /* Completed the iMCU row, advance counters for next one */
  164212. cinfo->output_iMCU_row++;
  164213. if (++(cinfo->input_iMCU_row) < cinfo->total_iMCU_rows) {
  164214. start_iMCU_row3(cinfo);
  164215. return JPEG_ROW_COMPLETED;
  164216. }
  164217. /* Completed the scan */
  164218. (*cinfo->inputctl->finish_input_pass) (cinfo);
  164219. return JPEG_SCAN_COMPLETED;
  164220. }
  164221. /*
  164222. * Dummy consume-input routine for single-pass operation.
  164223. */
  164224. METHODDEF(int)
  164225. dummy_consume_data (j_decompress_ptr cinfo)
  164226. {
  164227. return JPEG_SUSPENDED; /* Always indicate nothing was done */
  164228. }
  164229. #ifdef D_MULTISCAN_FILES_SUPPORTED
  164230. /*
  164231. * Consume input data and store it in the full-image coefficient buffer.
  164232. * We read as much as one fully interleaved MCU row ("iMCU" row) per call,
  164233. * ie, v_samp_factor block rows for each component in the scan.
  164234. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  164235. */
  164236. METHODDEF(int)
  164237. consume_data (j_decompress_ptr cinfo)
  164238. {
  164239. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  164240. JDIMENSION MCU_col_num; /* index of current MCU within row */
  164241. int blkn, ci, xindex, yindex, yoffset;
  164242. JDIMENSION start_col;
  164243. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  164244. JBLOCKROW buffer_ptr;
  164245. jpeg_component_info *compptr;
  164246. /* Align the virtual buffers for the components used in this scan. */
  164247. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  164248. compptr = cinfo->cur_comp_info[ci];
  164249. buffer[ci] = (*cinfo->mem->access_virt_barray)
  164250. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  164251. cinfo->input_iMCU_row * compptr->v_samp_factor,
  164252. (JDIMENSION) compptr->v_samp_factor, TRUE);
  164253. /* Note: entropy decoder expects buffer to be zeroed,
  164254. * but this is handled automatically by the memory manager
  164255. * because we requested a pre-zeroed array.
  164256. */
  164257. }
  164258. /* Loop to process one whole iMCU row */
  164259. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  164260. yoffset++) {
  164261. for (MCU_col_num = coef->MCU_ctr; MCU_col_num < cinfo->MCUs_per_row;
  164262. MCU_col_num++) {
  164263. /* Construct list of pointers to DCT blocks belonging to this MCU */
  164264. blkn = 0; /* index of current DCT block within MCU */
  164265. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  164266. compptr = cinfo->cur_comp_info[ci];
  164267. start_col = MCU_col_num * compptr->MCU_width;
  164268. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  164269. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  164270. for (xindex = 0; xindex < compptr->MCU_width; xindex++) {
  164271. coef->MCU_buffer[blkn++] = buffer_ptr++;
  164272. }
  164273. }
  164274. }
  164275. /* Try to fetch the MCU. */
  164276. if (! (*cinfo->entropy->decode_mcu) (cinfo, coef->MCU_buffer)) {
  164277. /* Suspension forced; update state counters and exit */
  164278. coef->MCU_vert_offset = yoffset;
  164279. coef->MCU_ctr = MCU_col_num;
  164280. return JPEG_SUSPENDED;
  164281. }
  164282. }
  164283. /* Completed an MCU row, but perhaps not an iMCU row */
  164284. coef->MCU_ctr = 0;
  164285. }
  164286. /* Completed the iMCU row, advance counters for next one */
  164287. if (++(cinfo->input_iMCU_row) < cinfo->total_iMCU_rows) {
  164288. start_iMCU_row3(cinfo);
  164289. return JPEG_ROW_COMPLETED;
  164290. }
  164291. /* Completed the scan */
  164292. (*cinfo->inputctl->finish_input_pass) (cinfo);
  164293. return JPEG_SCAN_COMPLETED;
  164294. }
  164295. /*
  164296. * Decompress and return some data in the multi-pass case.
  164297. * Always attempts to emit one fully interleaved MCU row ("iMCU" row).
  164298. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  164299. *
  164300. * NB: output_buf contains a plane for each component in image.
  164301. */
  164302. METHODDEF(int)
  164303. decompress_data (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  164304. {
  164305. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  164306. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  164307. JDIMENSION block_num;
  164308. int ci, block_row, block_rows;
  164309. JBLOCKARRAY buffer;
  164310. JBLOCKROW buffer_ptr;
  164311. JSAMPARRAY output_ptr;
  164312. JDIMENSION output_col;
  164313. jpeg_component_info *compptr;
  164314. inverse_DCT_method_ptr inverse_DCT;
  164315. /* Force some input to be done if we are getting ahead of the input. */
  164316. while (cinfo->input_scan_number < cinfo->output_scan_number ||
  164317. (cinfo->input_scan_number == cinfo->output_scan_number &&
  164318. cinfo->input_iMCU_row <= cinfo->output_iMCU_row)) {
  164319. if ((*cinfo->inputctl->consume_input)(cinfo) == JPEG_SUSPENDED)
  164320. return JPEG_SUSPENDED;
  164321. }
  164322. /* OK, output from the virtual arrays. */
  164323. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164324. ci++, compptr++) {
  164325. /* Don't bother to IDCT an uninteresting component. */
  164326. if (! compptr->component_needed)
  164327. continue;
  164328. /* Align the virtual buffer for this component. */
  164329. buffer = (*cinfo->mem->access_virt_barray)
  164330. ((j_common_ptr) cinfo, coef->whole_image[ci],
  164331. cinfo->output_iMCU_row * compptr->v_samp_factor,
  164332. (JDIMENSION) compptr->v_samp_factor, FALSE);
  164333. /* Count non-dummy DCT block rows in this iMCU row. */
  164334. if (cinfo->output_iMCU_row < last_iMCU_row)
  164335. block_rows = compptr->v_samp_factor;
  164336. else {
  164337. /* NB: can't use last_row_height here; it is input-side-dependent! */
  164338. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  164339. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  164340. }
  164341. inverse_DCT = cinfo->idct->inverse_DCT[ci];
  164342. output_ptr = output_buf[ci];
  164343. /* Loop over all DCT blocks to be processed. */
  164344. for (block_row = 0; block_row < block_rows; block_row++) {
  164345. buffer_ptr = buffer[block_row];
  164346. output_col = 0;
  164347. for (block_num = 0; block_num < compptr->width_in_blocks; block_num++) {
  164348. (*inverse_DCT) (cinfo, compptr, (JCOEFPTR) buffer_ptr,
  164349. output_ptr, output_col);
  164350. buffer_ptr++;
  164351. output_col += compptr->DCT_scaled_size;
  164352. }
  164353. output_ptr += compptr->DCT_scaled_size;
  164354. }
  164355. }
  164356. if (++(cinfo->output_iMCU_row) < cinfo->total_iMCU_rows)
  164357. return JPEG_ROW_COMPLETED;
  164358. return JPEG_SCAN_COMPLETED;
  164359. }
  164360. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  164361. #ifdef BLOCK_SMOOTHING_SUPPORTED
  164362. /*
  164363. * This code applies interblock smoothing as described by section K.8
  164364. * of the JPEG standard: the first 5 AC coefficients are estimated from
  164365. * the DC values of a DCT block and its 8 neighboring blocks.
  164366. * We apply smoothing only for progressive JPEG decoding, and only if
  164367. * the coefficients it can estimate are not yet known to full precision.
  164368. */
  164369. /* Natural-order array positions of the first 5 zigzag-order coefficients */
  164370. #define Q01_POS 1
  164371. #define Q10_POS 8
  164372. #define Q20_POS 16
  164373. #define Q11_POS 9
  164374. #define Q02_POS 2
  164375. /*
  164376. * Determine whether block smoothing is applicable and safe.
  164377. * We also latch the current states of the coef_bits[] entries for the
  164378. * AC coefficients; otherwise, if the input side of the decompressor
  164379. * advances into a new scan, we might think the coefficients are known
  164380. * more accurately than they really are.
  164381. */
  164382. LOCAL(boolean)
  164383. smoothing_ok (j_decompress_ptr cinfo)
  164384. {
  164385. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  164386. boolean smoothing_useful = FALSE;
  164387. int ci, coefi;
  164388. jpeg_component_info *compptr;
  164389. JQUANT_TBL * qtable;
  164390. int * coef_bits;
  164391. int * coef_bits_latch;
  164392. if (! cinfo->progressive_mode || cinfo->coef_bits == NULL)
  164393. return FALSE;
  164394. /* Allocate latch area if not already done */
  164395. if (coef->coef_bits_latch == NULL)
  164396. coef->coef_bits_latch = (int *)
  164397. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164398. cinfo->num_components *
  164399. (SAVED_COEFS * SIZEOF(int)));
  164400. coef_bits_latch = coef->coef_bits_latch;
  164401. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164402. ci++, compptr++) {
  164403. /* All components' quantization values must already be latched. */
  164404. if ((qtable = compptr->quant_table) == NULL)
  164405. return FALSE;
  164406. /* Verify DC & first 5 AC quantizers are nonzero to avoid zero-divide. */
  164407. if (qtable->quantval[0] == 0 ||
  164408. qtable->quantval[Q01_POS] == 0 ||
  164409. qtable->quantval[Q10_POS] == 0 ||
  164410. qtable->quantval[Q20_POS] == 0 ||
  164411. qtable->quantval[Q11_POS] == 0 ||
  164412. qtable->quantval[Q02_POS] == 0)
  164413. return FALSE;
  164414. /* DC values must be at least partly known for all components. */
  164415. coef_bits = cinfo->coef_bits[ci];
  164416. if (coef_bits[0] < 0)
  164417. return FALSE;
  164418. /* Block smoothing is helpful if some AC coefficients remain inaccurate. */
  164419. for (coefi = 1; coefi <= 5; coefi++) {
  164420. coef_bits_latch[coefi] = coef_bits[coefi];
  164421. if (coef_bits[coefi] != 0)
  164422. smoothing_useful = TRUE;
  164423. }
  164424. coef_bits_latch += SAVED_COEFS;
  164425. }
  164426. return smoothing_useful;
  164427. }
  164428. /*
  164429. * Variant of decompress_data for use when doing block smoothing.
  164430. */
  164431. METHODDEF(int)
  164432. decompress_smooth_data (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  164433. {
  164434. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  164435. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  164436. JDIMENSION block_num, last_block_column;
  164437. int ci, block_row, block_rows, access_rows;
  164438. JBLOCKARRAY buffer;
  164439. JBLOCKROW buffer_ptr, prev_block_row, next_block_row;
  164440. JSAMPARRAY output_ptr;
  164441. JDIMENSION output_col;
  164442. jpeg_component_info *compptr;
  164443. inverse_DCT_method_ptr inverse_DCT;
  164444. boolean first_row, last_row;
  164445. JBLOCK workspace;
  164446. int *coef_bits;
  164447. JQUANT_TBL *quanttbl;
  164448. INT32 Q00,Q01,Q02,Q10,Q11,Q20, num;
  164449. int DC1,DC2,DC3,DC4,DC5,DC6,DC7,DC8,DC9;
  164450. int Al, pred;
  164451. /* Force some input to be done if we are getting ahead of the input. */
  164452. while (cinfo->input_scan_number <= cinfo->output_scan_number &&
  164453. ! cinfo->inputctl->eoi_reached) {
  164454. if (cinfo->input_scan_number == cinfo->output_scan_number) {
  164455. /* If input is working on current scan, we ordinarily want it to
  164456. * have completed the current row. But if input scan is DC,
  164457. * we want it to keep one row ahead so that next block row's DC
  164458. * values are up to date.
  164459. */
  164460. JDIMENSION delta = (cinfo->Ss == 0) ? 1 : 0;
  164461. if (cinfo->input_iMCU_row > cinfo->output_iMCU_row+delta)
  164462. break;
  164463. }
  164464. if ((*cinfo->inputctl->consume_input)(cinfo) == JPEG_SUSPENDED)
  164465. return JPEG_SUSPENDED;
  164466. }
  164467. /* OK, output from the virtual arrays. */
  164468. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164469. ci++, compptr++) {
  164470. /* Don't bother to IDCT an uninteresting component. */
  164471. if (! compptr->component_needed)
  164472. continue;
  164473. /* Count non-dummy DCT block rows in this iMCU row. */
  164474. if (cinfo->output_iMCU_row < last_iMCU_row) {
  164475. block_rows = compptr->v_samp_factor;
  164476. access_rows = block_rows * 2; /* this and next iMCU row */
  164477. last_row = FALSE;
  164478. } else {
  164479. /* NB: can't use last_row_height here; it is input-side-dependent! */
  164480. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  164481. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  164482. access_rows = block_rows; /* this iMCU row only */
  164483. last_row = TRUE;
  164484. }
  164485. /* Align the virtual buffer for this component. */
  164486. if (cinfo->output_iMCU_row > 0) {
  164487. access_rows += compptr->v_samp_factor; /* prior iMCU row too */
  164488. buffer = (*cinfo->mem->access_virt_barray)
  164489. ((j_common_ptr) cinfo, coef->whole_image[ci],
  164490. (cinfo->output_iMCU_row - 1) * compptr->v_samp_factor,
  164491. (JDIMENSION) access_rows, FALSE);
  164492. buffer += compptr->v_samp_factor; /* point to current iMCU row */
  164493. first_row = FALSE;
  164494. } else {
  164495. buffer = (*cinfo->mem->access_virt_barray)
  164496. ((j_common_ptr) cinfo, coef->whole_image[ci],
  164497. (JDIMENSION) 0, (JDIMENSION) access_rows, FALSE);
  164498. first_row = TRUE;
  164499. }
  164500. /* Fetch component-dependent info */
  164501. coef_bits = coef->coef_bits_latch + (ci * SAVED_COEFS);
  164502. quanttbl = compptr->quant_table;
  164503. Q00 = quanttbl->quantval[0];
  164504. Q01 = quanttbl->quantval[Q01_POS];
  164505. Q10 = quanttbl->quantval[Q10_POS];
  164506. Q20 = quanttbl->quantval[Q20_POS];
  164507. Q11 = quanttbl->quantval[Q11_POS];
  164508. Q02 = quanttbl->quantval[Q02_POS];
  164509. inverse_DCT = cinfo->idct->inverse_DCT[ci];
  164510. output_ptr = output_buf[ci];
  164511. /* Loop over all DCT blocks to be processed. */
  164512. for (block_row = 0; block_row < block_rows; block_row++) {
  164513. buffer_ptr = buffer[block_row];
  164514. if (first_row && block_row == 0)
  164515. prev_block_row = buffer_ptr;
  164516. else
  164517. prev_block_row = buffer[block_row-1];
  164518. if (last_row && block_row == block_rows-1)
  164519. next_block_row = buffer_ptr;
  164520. else
  164521. next_block_row = buffer[block_row+1];
  164522. /* We fetch the surrounding DC values using a sliding-register approach.
  164523. * Initialize all nine here so as to do the right thing on narrow pics.
  164524. */
  164525. DC1 = DC2 = DC3 = (int) prev_block_row[0][0];
  164526. DC4 = DC5 = DC6 = (int) buffer_ptr[0][0];
  164527. DC7 = DC8 = DC9 = (int) next_block_row[0][0];
  164528. output_col = 0;
  164529. last_block_column = compptr->width_in_blocks - 1;
  164530. for (block_num = 0; block_num <= last_block_column; block_num++) {
  164531. /* Fetch current DCT block into workspace so we can modify it. */
  164532. jcopy_block_row(buffer_ptr, (JBLOCKROW) workspace, (JDIMENSION) 1);
  164533. /* Update DC values */
  164534. if (block_num < last_block_column) {
  164535. DC3 = (int) prev_block_row[1][0];
  164536. DC6 = (int) buffer_ptr[1][0];
  164537. DC9 = (int) next_block_row[1][0];
  164538. }
  164539. /* Compute coefficient estimates per K.8.
  164540. * An estimate is applied only if coefficient is still zero,
  164541. * and is not known to be fully accurate.
  164542. */
  164543. /* AC01 */
  164544. if ((Al=coef_bits[1]) != 0 && workspace[1] == 0) {
  164545. num = 36 * Q00 * (DC4 - DC6);
  164546. if (num >= 0) {
  164547. pred = (int) (((Q01<<7) + num) / (Q01<<8));
  164548. if (Al > 0 && pred >= (1<<Al))
  164549. pred = (1<<Al)-1;
  164550. } else {
  164551. pred = (int) (((Q01<<7) - num) / (Q01<<8));
  164552. if (Al > 0 && pred >= (1<<Al))
  164553. pred = (1<<Al)-1;
  164554. pred = -pred;
  164555. }
  164556. workspace[1] = (JCOEF) pred;
  164557. }
  164558. /* AC10 */
  164559. if ((Al=coef_bits[2]) != 0 && workspace[8] == 0) {
  164560. num = 36 * Q00 * (DC2 - DC8);
  164561. if (num >= 0) {
  164562. pred = (int) (((Q10<<7) + num) / (Q10<<8));
  164563. if (Al > 0 && pred >= (1<<Al))
  164564. pred = (1<<Al)-1;
  164565. } else {
  164566. pred = (int) (((Q10<<7) - num) / (Q10<<8));
  164567. if (Al > 0 && pred >= (1<<Al))
  164568. pred = (1<<Al)-1;
  164569. pred = -pred;
  164570. }
  164571. workspace[8] = (JCOEF) pred;
  164572. }
  164573. /* AC20 */
  164574. if ((Al=coef_bits[3]) != 0 && workspace[16] == 0) {
  164575. num = 9 * Q00 * (DC2 + DC8 - 2*DC5);
  164576. if (num >= 0) {
  164577. pred = (int) (((Q20<<7) + num) / (Q20<<8));
  164578. if (Al > 0 && pred >= (1<<Al))
  164579. pred = (1<<Al)-1;
  164580. } else {
  164581. pred = (int) (((Q20<<7) - num) / (Q20<<8));
  164582. if (Al > 0 && pred >= (1<<Al))
  164583. pred = (1<<Al)-1;
  164584. pred = -pred;
  164585. }
  164586. workspace[16] = (JCOEF) pred;
  164587. }
  164588. /* AC11 */
  164589. if ((Al=coef_bits[4]) != 0 && workspace[9] == 0) {
  164590. num = 5 * Q00 * (DC1 - DC3 - DC7 + DC9);
  164591. if (num >= 0) {
  164592. pred = (int) (((Q11<<7) + num) / (Q11<<8));
  164593. if (Al > 0 && pred >= (1<<Al))
  164594. pred = (1<<Al)-1;
  164595. } else {
  164596. pred = (int) (((Q11<<7) - num) / (Q11<<8));
  164597. if (Al > 0 && pred >= (1<<Al))
  164598. pred = (1<<Al)-1;
  164599. pred = -pred;
  164600. }
  164601. workspace[9] = (JCOEF) pred;
  164602. }
  164603. /* AC02 */
  164604. if ((Al=coef_bits[5]) != 0 && workspace[2] == 0) {
  164605. num = 9 * Q00 * (DC4 + DC6 - 2*DC5);
  164606. if (num >= 0) {
  164607. pred = (int) (((Q02<<7) + num) / (Q02<<8));
  164608. if (Al > 0 && pred >= (1<<Al))
  164609. pred = (1<<Al)-1;
  164610. } else {
  164611. pred = (int) (((Q02<<7) - num) / (Q02<<8));
  164612. if (Al > 0 && pred >= (1<<Al))
  164613. pred = (1<<Al)-1;
  164614. pred = -pred;
  164615. }
  164616. workspace[2] = (JCOEF) pred;
  164617. }
  164618. /* OK, do the IDCT */
  164619. (*inverse_DCT) (cinfo, compptr, (JCOEFPTR) workspace,
  164620. output_ptr, output_col);
  164621. /* Advance for next column */
  164622. DC1 = DC2; DC2 = DC3;
  164623. DC4 = DC5; DC5 = DC6;
  164624. DC7 = DC8; DC8 = DC9;
  164625. buffer_ptr++, prev_block_row++, next_block_row++;
  164626. output_col += compptr->DCT_scaled_size;
  164627. }
  164628. output_ptr += compptr->DCT_scaled_size;
  164629. }
  164630. }
  164631. if (++(cinfo->output_iMCU_row) < cinfo->total_iMCU_rows)
  164632. return JPEG_ROW_COMPLETED;
  164633. return JPEG_SCAN_COMPLETED;
  164634. }
  164635. #endif /* BLOCK_SMOOTHING_SUPPORTED */
  164636. /*
  164637. * Initialize coefficient buffer controller.
  164638. */
  164639. GLOBAL(void)
  164640. jinit_d_coef_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  164641. {
  164642. my_coef_ptr3 coef;
  164643. coef = (my_coef_ptr3)
  164644. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164645. SIZEOF(my_coef_controller3));
  164646. cinfo->coef = (struct jpeg_d_coef_controller *) coef;
  164647. coef->pub.start_input_pass = start_input_pass;
  164648. coef->pub.start_output_pass = start_output_pass;
  164649. #ifdef BLOCK_SMOOTHING_SUPPORTED
  164650. coef->coef_bits_latch = NULL;
  164651. #endif
  164652. /* Create the coefficient buffer. */
  164653. if (need_full_buffer) {
  164654. #ifdef D_MULTISCAN_FILES_SUPPORTED
  164655. /* Allocate a full-image virtual array for each component, */
  164656. /* padded to a multiple of samp_factor DCT blocks in each direction. */
  164657. /* Note we ask for a pre-zeroed array. */
  164658. int ci, access_rows;
  164659. jpeg_component_info *compptr;
  164660. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164661. ci++, compptr++) {
  164662. access_rows = compptr->v_samp_factor;
  164663. #ifdef BLOCK_SMOOTHING_SUPPORTED
  164664. /* If block smoothing could be used, need a bigger window */
  164665. if (cinfo->progressive_mode)
  164666. access_rows *= 3;
  164667. #endif
  164668. coef->whole_image[ci] = (*cinfo->mem->request_virt_barray)
  164669. ((j_common_ptr) cinfo, JPOOL_IMAGE, TRUE,
  164670. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  164671. (long) compptr->h_samp_factor),
  164672. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  164673. (long) compptr->v_samp_factor),
  164674. (JDIMENSION) access_rows);
  164675. }
  164676. coef->pub.consume_data = consume_data;
  164677. coef->pub.decompress_data = decompress_data;
  164678. coef->pub.coef_arrays = coef->whole_image; /* link to virtual arrays */
  164679. #else
  164680. ERREXIT(cinfo, JERR_NOT_COMPILED);
  164681. #endif
  164682. } else {
  164683. /* We only need a single-MCU buffer. */
  164684. JBLOCKROW buffer;
  164685. int i;
  164686. buffer = (JBLOCKROW)
  164687. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164688. D_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  164689. for (i = 0; i < D_MAX_BLOCKS_IN_MCU; i++) {
  164690. coef->MCU_buffer[i] = buffer + i;
  164691. }
  164692. coef->pub.consume_data = dummy_consume_data;
  164693. coef->pub.decompress_data = decompress_onepass;
  164694. coef->pub.coef_arrays = NULL; /* flag for no virtual arrays */
  164695. }
  164696. }
  164697. /********* End of inlined file: jdcoefct.c *********/
  164698. #undef FIX
  164699. /********* Start of inlined file: jdcolor.c *********/
  164700. #define JPEG_INTERNALS
  164701. /* Private subobject */
  164702. typedef struct {
  164703. struct jpeg_color_deconverter pub; /* public fields */
  164704. /* Private state for YCC->RGB conversion */
  164705. int * Cr_r_tab; /* => table for Cr to R conversion */
  164706. int * Cb_b_tab; /* => table for Cb to B conversion */
  164707. INT32 * Cr_g_tab; /* => table for Cr to G conversion */
  164708. INT32 * Cb_g_tab; /* => table for Cb to G conversion */
  164709. } my_color_deconverter2;
  164710. typedef my_color_deconverter2 * my_cconvert_ptr2;
  164711. /**************** YCbCr -> RGB conversion: most common case **************/
  164712. /*
  164713. * YCbCr is defined per CCIR 601-1, except that Cb and Cr are
  164714. * normalized to the range 0..MAXJSAMPLE rather than -0.5 .. 0.5.
  164715. * The conversion equations to be implemented are therefore
  164716. * R = Y + 1.40200 * Cr
  164717. * G = Y - 0.34414 * Cb - 0.71414 * Cr
  164718. * B = Y + 1.77200 * Cb
  164719. * where Cb and Cr represent the incoming values less CENTERJSAMPLE.
  164720. * (These numbers are derived from TIFF 6.0 section 21, dated 3-June-92.)
  164721. *
  164722. * To avoid floating-point arithmetic, we represent the fractional constants
  164723. * as integers scaled up by 2^16 (about 4 digits precision); we have to divide
  164724. * the products by 2^16, with appropriate rounding, to get the correct answer.
  164725. * Notice that Y, being an integral input, does not contribute any fraction
  164726. * so it need not participate in the rounding.
  164727. *
  164728. * For even more speed, we avoid doing any multiplications in the inner loop
  164729. * by precalculating the constants times Cb and Cr for all possible values.
  164730. * For 8-bit JSAMPLEs this is very reasonable (only 256 entries per table);
  164731. * for 12-bit samples it is still acceptable. It's not very reasonable for
  164732. * 16-bit samples, but if you want lossless storage you shouldn't be changing
  164733. * colorspace anyway.
  164734. * The Cr=>R and Cb=>B values can be rounded to integers in advance; the
  164735. * values for the G calculation are left scaled up, since we must add them
  164736. * together before rounding.
  164737. */
  164738. #define SCALEBITS 16 /* speediest right-shift on some machines */
  164739. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  164740. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  164741. /*
  164742. * Initialize tables for YCC->RGB colorspace conversion.
  164743. */
  164744. LOCAL(void)
  164745. build_ycc_rgb_table (j_decompress_ptr cinfo)
  164746. {
  164747. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  164748. int i;
  164749. INT32 x;
  164750. SHIFT_TEMPS
  164751. cconvert->Cr_r_tab = (int *)
  164752. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164753. (MAXJSAMPLE+1) * SIZEOF(int));
  164754. cconvert->Cb_b_tab = (int *)
  164755. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164756. (MAXJSAMPLE+1) * SIZEOF(int));
  164757. cconvert->Cr_g_tab = (INT32 *)
  164758. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164759. (MAXJSAMPLE+1) * SIZEOF(INT32));
  164760. cconvert->Cb_g_tab = (INT32 *)
  164761. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164762. (MAXJSAMPLE+1) * SIZEOF(INT32));
  164763. for (i = 0, x = -CENTERJSAMPLE; i <= MAXJSAMPLE; i++, x++) {
  164764. /* i is the actual input pixel value, in the range 0..MAXJSAMPLE */
  164765. /* The Cb or Cr value we are thinking of is x = i - CENTERJSAMPLE */
  164766. /* Cr=>R value is nearest int to 1.40200 * x */
  164767. cconvert->Cr_r_tab[i] = (int)
  164768. RIGHT_SHIFT(FIX(1.40200) * x + ONE_HALF, SCALEBITS);
  164769. /* Cb=>B value is nearest int to 1.77200 * x */
  164770. cconvert->Cb_b_tab[i] = (int)
  164771. RIGHT_SHIFT(FIX(1.77200) * x + ONE_HALF, SCALEBITS);
  164772. /* Cr=>G value is scaled-up -0.71414 * x */
  164773. cconvert->Cr_g_tab[i] = (- FIX(0.71414)) * x;
  164774. /* Cb=>G value is scaled-up -0.34414 * x */
  164775. /* We also add in ONE_HALF so that need not do it in inner loop */
  164776. cconvert->Cb_g_tab[i] = (- FIX(0.34414)) * x + ONE_HALF;
  164777. }
  164778. }
  164779. /*
  164780. * Convert some rows of samples to the output colorspace.
  164781. *
  164782. * Note that we change from noninterleaved, one-plane-per-component format
  164783. * to interleaved-pixel format. The output buffer is therefore three times
  164784. * as wide as the input buffer.
  164785. * A starting row offset is provided only for the input buffer. The caller
  164786. * can easily adjust the passed output_buf value to accommodate any row
  164787. * offset required on that side.
  164788. */
  164789. METHODDEF(void)
  164790. ycc_rgb_convert (j_decompress_ptr cinfo,
  164791. JSAMPIMAGE input_buf, JDIMENSION input_row,
  164792. JSAMPARRAY output_buf, int num_rows)
  164793. {
  164794. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  164795. register int y, cb, cr;
  164796. register JSAMPROW outptr;
  164797. register JSAMPROW inptr0, inptr1, inptr2;
  164798. register JDIMENSION col;
  164799. JDIMENSION num_cols = cinfo->output_width;
  164800. /* copy these pointers into registers if possible */
  164801. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  164802. register int * Crrtab = cconvert->Cr_r_tab;
  164803. register int * Cbbtab = cconvert->Cb_b_tab;
  164804. register INT32 * Crgtab = cconvert->Cr_g_tab;
  164805. register INT32 * Cbgtab = cconvert->Cb_g_tab;
  164806. SHIFT_TEMPS
  164807. while (--num_rows >= 0) {
  164808. inptr0 = input_buf[0][input_row];
  164809. inptr1 = input_buf[1][input_row];
  164810. inptr2 = input_buf[2][input_row];
  164811. input_row++;
  164812. outptr = *output_buf++;
  164813. for (col = 0; col < num_cols; col++) {
  164814. y = GETJSAMPLE(inptr0[col]);
  164815. cb = GETJSAMPLE(inptr1[col]);
  164816. cr = GETJSAMPLE(inptr2[col]);
  164817. /* Range-limiting is essential due to noise introduced by DCT losses. */
  164818. outptr[RGB_RED] = range_limit[y + Crrtab[cr]];
  164819. outptr[RGB_GREEN] = range_limit[y +
  164820. ((int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr],
  164821. SCALEBITS))];
  164822. outptr[RGB_BLUE] = range_limit[y + Cbbtab[cb]];
  164823. outptr += RGB_PIXELSIZE;
  164824. }
  164825. }
  164826. }
  164827. /**************** Cases other than YCbCr -> RGB **************/
  164828. /*
  164829. * Color conversion for no colorspace change: just copy the data,
  164830. * converting from separate-planes to interleaved representation.
  164831. */
  164832. METHODDEF(void)
  164833. null_convert2 (j_decompress_ptr cinfo,
  164834. JSAMPIMAGE input_buf, JDIMENSION input_row,
  164835. JSAMPARRAY output_buf, int num_rows)
  164836. {
  164837. register JSAMPROW inptr, outptr;
  164838. register JDIMENSION count;
  164839. register int num_components = cinfo->num_components;
  164840. JDIMENSION num_cols = cinfo->output_width;
  164841. int ci;
  164842. while (--num_rows >= 0) {
  164843. for (ci = 0; ci < num_components; ci++) {
  164844. inptr = input_buf[ci][input_row];
  164845. outptr = output_buf[0] + ci;
  164846. for (count = num_cols; count > 0; count--) {
  164847. *outptr = *inptr++; /* needn't bother with GETJSAMPLE() here */
  164848. outptr += num_components;
  164849. }
  164850. }
  164851. input_row++;
  164852. output_buf++;
  164853. }
  164854. }
  164855. /*
  164856. * Color conversion for grayscale: just copy the data.
  164857. * This also works for YCbCr -> grayscale conversion, in which
  164858. * we just copy the Y (luminance) component and ignore chrominance.
  164859. */
  164860. METHODDEF(void)
  164861. grayscale_convert2 (j_decompress_ptr cinfo,
  164862. JSAMPIMAGE input_buf, JDIMENSION input_row,
  164863. JSAMPARRAY output_buf, int num_rows)
  164864. {
  164865. jcopy_sample_rows(input_buf[0], (int) input_row, output_buf, 0,
  164866. num_rows, cinfo->output_width);
  164867. }
  164868. /*
  164869. * Convert grayscale to RGB: just duplicate the graylevel three times.
  164870. * This is provided to support applications that don't want to cope
  164871. * with grayscale as a separate case.
  164872. */
  164873. METHODDEF(void)
  164874. gray_rgb_convert (j_decompress_ptr cinfo,
  164875. JSAMPIMAGE input_buf, JDIMENSION input_row,
  164876. JSAMPARRAY output_buf, int num_rows)
  164877. {
  164878. register JSAMPROW inptr, outptr;
  164879. register JDIMENSION col;
  164880. JDIMENSION num_cols = cinfo->output_width;
  164881. while (--num_rows >= 0) {
  164882. inptr = input_buf[0][input_row++];
  164883. outptr = *output_buf++;
  164884. for (col = 0; col < num_cols; col++) {
  164885. /* We can dispense with GETJSAMPLE() here */
  164886. outptr[RGB_RED] = outptr[RGB_GREEN] = outptr[RGB_BLUE] = inptr[col];
  164887. outptr += RGB_PIXELSIZE;
  164888. }
  164889. }
  164890. }
  164891. /*
  164892. * Adobe-style YCCK->CMYK conversion.
  164893. * We convert YCbCr to R=1-C, G=1-M, and B=1-Y using the same
  164894. * conversion as above, while passing K (black) unchanged.
  164895. * We assume build_ycc_rgb_table has been called.
  164896. */
  164897. METHODDEF(void)
  164898. ycck_cmyk_convert (j_decompress_ptr cinfo,
  164899. JSAMPIMAGE input_buf, JDIMENSION input_row,
  164900. JSAMPARRAY output_buf, int num_rows)
  164901. {
  164902. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  164903. register int y, cb, cr;
  164904. register JSAMPROW outptr;
  164905. register JSAMPROW inptr0, inptr1, inptr2, inptr3;
  164906. register JDIMENSION col;
  164907. JDIMENSION num_cols = cinfo->output_width;
  164908. /* copy these pointers into registers if possible */
  164909. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  164910. register int * Crrtab = cconvert->Cr_r_tab;
  164911. register int * Cbbtab = cconvert->Cb_b_tab;
  164912. register INT32 * Crgtab = cconvert->Cr_g_tab;
  164913. register INT32 * Cbgtab = cconvert->Cb_g_tab;
  164914. SHIFT_TEMPS
  164915. while (--num_rows >= 0) {
  164916. inptr0 = input_buf[0][input_row];
  164917. inptr1 = input_buf[1][input_row];
  164918. inptr2 = input_buf[2][input_row];
  164919. inptr3 = input_buf[3][input_row];
  164920. input_row++;
  164921. outptr = *output_buf++;
  164922. for (col = 0; col < num_cols; col++) {
  164923. y = GETJSAMPLE(inptr0[col]);
  164924. cb = GETJSAMPLE(inptr1[col]);
  164925. cr = GETJSAMPLE(inptr2[col]);
  164926. /* Range-limiting is essential due to noise introduced by DCT losses. */
  164927. outptr[0] = range_limit[MAXJSAMPLE - (y + Crrtab[cr])]; /* red */
  164928. outptr[1] = range_limit[MAXJSAMPLE - (y + /* green */
  164929. ((int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr],
  164930. SCALEBITS)))];
  164931. outptr[2] = range_limit[MAXJSAMPLE - (y + Cbbtab[cb])]; /* blue */
  164932. /* K passes through unchanged */
  164933. outptr[3] = inptr3[col]; /* don't need GETJSAMPLE here */
  164934. outptr += 4;
  164935. }
  164936. }
  164937. }
  164938. /*
  164939. * Empty method for start_pass.
  164940. */
  164941. METHODDEF(void)
  164942. start_pass_dcolor (j_decompress_ptr cinfo)
  164943. {
  164944. /* no work needed */
  164945. }
  164946. /*
  164947. * Module initialization routine for output colorspace conversion.
  164948. */
  164949. GLOBAL(void)
  164950. jinit_color_deconverter (j_decompress_ptr cinfo)
  164951. {
  164952. my_cconvert_ptr2 cconvert;
  164953. int ci;
  164954. cconvert = (my_cconvert_ptr2)
  164955. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164956. SIZEOF(my_color_deconverter2));
  164957. cinfo->cconvert = (struct jpeg_color_deconverter *) cconvert;
  164958. cconvert->pub.start_pass = start_pass_dcolor;
  164959. /* Make sure num_components agrees with jpeg_color_space */
  164960. switch (cinfo->jpeg_color_space) {
  164961. case JCS_GRAYSCALE:
  164962. if (cinfo->num_components != 1)
  164963. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  164964. break;
  164965. case JCS_RGB:
  164966. case JCS_YCbCr:
  164967. if (cinfo->num_components != 3)
  164968. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  164969. break;
  164970. case JCS_CMYK:
  164971. case JCS_YCCK:
  164972. if (cinfo->num_components != 4)
  164973. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  164974. break;
  164975. default: /* JCS_UNKNOWN can be anything */
  164976. if (cinfo->num_components < 1)
  164977. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  164978. break;
  164979. }
  164980. /* Set out_color_components and conversion method based on requested space.
  164981. * Also clear the component_needed flags for any unused components,
  164982. * so that earlier pipeline stages can avoid useless computation.
  164983. */
  164984. switch (cinfo->out_color_space) {
  164985. case JCS_GRAYSCALE:
  164986. cinfo->out_color_components = 1;
  164987. if (cinfo->jpeg_color_space == JCS_GRAYSCALE ||
  164988. cinfo->jpeg_color_space == JCS_YCbCr) {
  164989. cconvert->pub.color_convert = grayscale_convert2;
  164990. /* For color->grayscale conversion, only the Y (0) component is needed */
  164991. for (ci = 1; ci < cinfo->num_components; ci++)
  164992. cinfo->comp_info[ci].component_needed = FALSE;
  164993. } else
  164994. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  164995. break;
  164996. case JCS_RGB:
  164997. cinfo->out_color_components = RGB_PIXELSIZE;
  164998. if (cinfo->jpeg_color_space == JCS_YCbCr) {
  164999. cconvert->pub.color_convert = ycc_rgb_convert;
  165000. build_ycc_rgb_table(cinfo);
  165001. } else if (cinfo->jpeg_color_space == JCS_GRAYSCALE) {
  165002. cconvert->pub.color_convert = gray_rgb_convert;
  165003. } else if (cinfo->jpeg_color_space == JCS_RGB && RGB_PIXELSIZE == 3) {
  165004. cconvert->pub.color_convert = null_convert2;
  165005. } else
  165006. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  165007. break;
  165008. case JCS_CMYK:
  165009. cinfo->out_color_components = 4;
  165010. if (cinfo->jpeg_color_space == JCS_YCCK) {
  165011. cconvert->pub.color_convert = ycck_cmyk_convert;
  165012. build_ycc_rgb_table(cinfo);
  165013. } else if (cinfo->jpeg_color_space == JCS_CMYK) {
  165014. cconvert->pub.color_convert = null_convert2;
  165015. } else
  165016. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  165017. break;
  165018. default:
  165019. /* Permit null conversion to same output space */
  165020. if (cinfo->out_color_space == cinfo->jpeg_color_space) {
  165021. cinfo->out_color_components = cinfo->num_components;
  165022. cconvert->pub.color_convert = null_convert2;
  165023. } else /* unsupported non-null conversion */
  165024. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  165025. break;
  165026. }
  165027. if (cinfo->quantize_colors)
  165028. cinfo->output_components = 1; /* single colormapped output component */
  165029. else
  165030. cinfo->output_components = cinfo->out_color_components;
  165031. }
  165032. /********* End of inlined file: jdcolor.c *********/
  165033. #undef FIX
  165034. /********* Start of inlined file: jddctmgr.c *********/
  165035. #define JPEG_INTERNALS
  165036. /*
  165037. * The decompressor input side (jdinput.c) saves away the appropriate
  165038. * quantization table for each component at the start of the first scan
  165039. * involving that component. (This is necessary in order to correctly
  165040. * decode files that reuse Q-table slots.)
  165041. * When we are ready to make an output pass, the saved Q-table is converted
  165042. * to a multiplier table that will actually be used by the IDCT routine.
  165043. * The multiplier table contents are IDCT-method-dependent. To support
  165044. * application changes in IDCT method between scans, we can remake the
  165045. * multiplier tables if necessary.
  165046. * In buffered-image mode, the first output pass may occur before any data
  165047. * has been seen for some components, and thus before their Q-tables have
  165048. * been saved away. To handle this case, multiplier tables are preset
  165049. * to zeroes; the result of the IDCT will be a neutral gray level.
  165050. */
  165051. /* Private subobject for this module */
  165052. typedef struct {
  165053. struct jpeg_inverse_dct pub; /* public fields */
  165054. /* This array contains the IDCT method code that each multiplier table
  165055. * is currently set up for, or -1 if it's not yet set up.
  165056. * The actual multiplier tables are pointed to by dct_table in the
  165057. * per-component comp_info structures.
  165058. */
  165059. int cur_method[MAX_COMPONENTS];
  165060. } my_idct_controller;
  165061. typedef my_idct_controller * my_idct_ptr;
  165062. /* Allocated multiplier tables: big enough for any supported variant */
  165063. typedef union {
  165064. ISLOW_MULT_TYPE islow_array[DCTSIZE2];
  165065. #ifdef DCT_IFAST_SUPPORTED
  165066. IFAST_MULT_TYPE ifast_array[DCTSIZE2];
  165067. #endif
  165068. #ifdef DCT_FLOAT_SUPPORTED
  165069. FLOAT_MULT_TYPE float_array[DCTSIZE2];
  165070. #endif
  165071. } multiplier_table;
  165072. /* The current scaled-IDCT routines require ISLOW-style multiplier tables,
  165073. * so be sure to compile that code if either ISLOW or SCALING is requested.
  165074. */
  165075. #ifdef DCT_ISLOW_SUPPORTED
  165076. #define PROVIDE_ISLOW_TABLES
  165077. #else
  165078. #ifdef IDCT_SCALING_SUPPORTED
  165079. #define PROVIDE_ISLOW_TABLES
  165080. #endif
  165081. #endif
  165082. /*
  165083. * Prepare for an output pass.
  165084. * Here we select the proper IDCT routine for each component and build
  165085. * a matching multiplier table.
  165086. */
  165087. METHODDEF(void)
  165088. start_pass (j_decompress_ptr cinfo)
  165089. {
  165090. my_idct_ptr idct = (my_idct_ptr) cinfo->idct;
  165091. int ci, i;
  165092. jpeg_component_info *compptr;
  165093. int method = 0;
  165094. inverse_DCT_method_ptr method_ptr = NULL;
  165095. JQUANT_TBL * qtbl;
  165096. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  165097. ci++, compptr++) {
  165098. /* Select the proper IDCT routine for this component's scaling */
  165099. switch (compptr->DCT_scaled_size) {
  165100. #ifdef IDCT_SCALING_SUPPORTED
  165101. case 1:
  165102. method_ptr = jpeg_idct_1x1;
  165103. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  165104. break;
  165105. case 2:
  165106. method_ptr = jpeg_idct_2x2;
  165107. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  165108. break;
  165109. case 4:
  165110. method_ptr = jpeg_idct_4x4;
  165111. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  165112. break;
  165113. #endif
  165114. case DCTSIZE:
  165115. switch (cinfo->dct_method) {
  165116. #ifdef DCT_ISLOW_SUPPORTED
  165117. case JDCT_ISLOW:
  165118. method_ptr = jpeg_idct_islow;
  165119. method = JDCT_ISLOW;
  165120. break;
  165121. #endif
  165122. #ifdef DCT_IFAST_SUPPORTED
  165123. case JDCT_IFAST:
  165124. method_ptr = jpeg_idct_ifast;
  165125. method = JDCT_IFAST;
  165126. break;
  165127. #endif
  165128. #ifdef DCT_FLOAT_SUPPORTED
  165129. case JDCT_FLOAT:
  165130. method_ptr = jpeg_idct_float;
  165131. method = JDCT_FLOAT;
  165132. break;
  165133. #endif
  165134. default:
  165135. ERREXIT(cinfo, JERR_NOT_COMPILED);
  165136. break;
  165137. }
  165138. break;
  165139. default:
  165140. ERREXIT1(cinfo, JERR_BAD_DCTSIZE, compptr->DCT_scaled_size);
  165141. break;
  165142. }
  165143. idct->pub.inverse_DCT[ci] = method_ptr;
  165144. /* Create multiplier table from quant table.
  165145. * However, we can skip this if the component is uninteresting
  165146. * or if we already built the table. Also, if no quant table
  165147. * has yet been saved for the component, we leave the
  165148. * multiplier table all-zero; we'll be reading zeroes from the
  165149. * coefficient controller's buffer anyway.
  165150. */
  165151. if (! compptr->component_needed || idct->cur_method[ci] == method)
  165152. continue;
  165153. qtbl = compptr->quant_table;
  165154. if (qtbl == NULL) /* happens if no data yet for component */
  165155. continue;
  165156. idct->cur_method[ci] = method;
  165157. switch (method) {
  165158. #ifdef PROVIDE_ISLOW_TABLES
  165159. case JDCT_ISLOW:
  165160. {
  165161. /* For LL&M IDCT method, multipliers are equal to raw quantization
  165162. * coefficients, but are stored as ints to ensure access efficiency.
  165163. */
  165164. ISLOW_MULT_TYPE * ismtbl = (ISLOW_MULT_TYPE *) compptr->dct_table;
  165165. for (i = 0; i < DCTSIZE2; i++) {
  165166. ismtbl[i] = (ISLOW_MULT_TYPE) qtbl->quantval[i];
  165167. }
  165168. }
  165169. break;
  165170. #endif
  165171. #ifdef DCT_IFAST_SUPPORTED
  165172. case JDCT_IFAST:
  165173. {
  165174. /* For AA&N IDCT method, multipliers are equal to quantization
  165175. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  165176. * scalefactor[0] = 1
  165177. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  165178. * For integer operation, the multiplier table is to be scaled by
  165179. * IFAST_SCALE_BITS.
  165180. */
  165181. IFAST_MULT_TYPE * ifmtbl = (IFAST_MULT_TYPE *) compptr->dct_table;
  165182. #define CONST_BITS 14
  165183. static const INT16 aanscales[DCTSIZE2] = {
  165184. /* precomputed values scaled up by 14 bits */
  165185. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  165186. 22725, 31521, 29692, 26722, 22725, 17855, 12299, 6270,
  165187. 21407, 29692, 27969, 25172, 21407, 16819, 11585, 5906,
  165188. 19266, 26722, 25172, 22654, 19266, 15137, 10426, 5315,
  165189. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  165190. 12873, 17855, 16819, 15137, 12873, 10114, 6967, 3552,
  165191. 8867, 12299, 11585, 10426, 8867, 6967, 4799, 2446,
  165192. 4520, 6270, 5906, 5315, 4520, 3552, 2446, 1247
  165193. };
  165194. SHIFT_TEMPS
  165195. for (i = 0; i < DCTSIZE2; i++) {
  165196. ifmtbl[i] = (IFAST_MULT_TYPE)
  165197. DESCALE(MULTIPLY16V16((INT32) qtbl->quantval[i],
  165198. (INT32) aanscales[i]),
  165199. CONST_BITS-IFAST_SCALE_BITS);
  165200. }
  165201. }
  165202. break;
  165203. #endif
  165204. #ifdef DCT_FLOAT_SUPPORTED
  165205. case JDCT_FLOAT:
  165206. {
  165207. /* For float AA&N IDCT method, multipliers are equal to quantization
  165208. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  165209. * scalefactor[0] = 1
  165210. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  165211. */
  165212. FLOAT_MULT_TYPE * fmtbl = (FLOAT_MULT_TYPE *) compptr->dct_table;
  165213. int row, col;
  165214. static const double aanscalefactor[DCTSIZE] = {
  165215. 1.0, 1.387039845, 1.306562965, 1.175875602,
  165216. 1.0, 0.785694958, 0.541196100, 0.275899379
  165217. };
  165218. i = 0;
  165219. for (row = 0; row < DCTSIZE; row++) {
  165220. for (col = 0; col < DCTSIZE; col++) {
  165221. fmtbl[i] = (FLOAT_MULT_TYPE)
  165222. ((double) qtbl->quantval[i] *
  165223. aanscalefactor[row] * aanscalefactor[col]);
  165224. i++;
  165225. }
  165226. }
  165227. }
  165228. break;
  165229. #endif
  165230. default:
  165231. ERREXIT(cinfo, JERR_NOT_COMPILED);
  165232. break;
  165233. }
  165234. }
  165235. }
  165236. /*
  165237. * Initialize IDCT manager.
  165238. */
  165239. GLOBAL(void)
  165240. jinit_inverse_dct (j_decompress_ptr cinfo)
  165241. {
  165242. my_idct_ptr idct;
  165243. int ci;
  165244. jpeg_component_info *compptr;
  165245. idct = (my_idct_ptr)
  165246. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165247. SIZEOF(my_idct_controller));
  165248. cinfo->idct = (struct jpeg_inverse_dct *) idct;
  165249. idct->pub.start_pass = start_pass;
  165250. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  165251. ci++, compptr++) {
  165252. /* Allocate and pre-zero a multiplier table for each component */
  165253. compptr->dct_table =
  165254. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165255. SIZEOF(multiplier_table));
  165256. MEMZERO(compptr->dct_table, SIZEOF(multiplier_table));
  165257. /* Mark multiplier table not yet set up for any method */
  165258. idct->cur_method[ci] = -1;
  165259. }
  165260. }
  165261. /********* End of inlined file: jddctmgr.c *********/
  165262. #undef CONST_BITS
  165263. #undef ASSIGN_STATE
  165264. /********* Start of inlined file: jdhuff.c *********/
  165265. #define JPEG_INTERNALS
  165266. /********* Start of inlined file: jdhuff.h *********/
  165267. /* Short forms of external names for systems with brain-damaged linkers. */
  165268. #ifndef __jdhuff_h__
  165269. #define __jdhuff_h__
  165270. #ifdef NEED_SHORT_EXTERNAL_NAMES
  165271. #define jpeg_make_d_derived_tbl jMkDDerived
  165272. #define jpeg_fill_bit_buffer jFilBitBuf
  165273. #define jpeg_huff_decode jHufDecode
  165274. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  165275. /* Derived data constructed for each Huffman table */
  165276. #define HUFF_LOOKAHEAD 8 /* # of bits of lookahead */
  165277. typedef struct {
  165278. /* Basic tables: (element [0] of each array is unused) */
  165279. INT32 maxcode[18]; /* largest code of length k (-1 if none) */
  165280. /* (maxcode[17] is a sentinel to ensure jpeg_huff_decode terminates) */
  165281. INT32 valoffset[17]; /* huffval[] offset for codes of length k */
  165282. /* valoffset[k] = huffval[] index of 1st symbol of code length k, less
  165283. * the smallest code of length k; so given a code of length k, the
  165284. * corresponding symbol is huffval[code + valoffset[k]]
  165285. */
  165286. /* Link to public Huffman table (needed only in jpeg_huff_decode) */
  165287. JHUFF_TBL *pub;
  165288. /* Lookahead tables: indexed by the next HUFF_LOOKAHEAD bits of
  165289. * the input data stream. If the next Huffman code is no more
  165290. * than HUFF_LOOKAHEAD bits long, we can obtain its length and
  165291. * the corresponding symbol directly from these tables.
  165292. */
  165293. int look_nbits[1<<HUFF_LOOKAHEAD]; /* # bits, or 0 if too long */
  165294. UINT8 look_sym[1<<HUFF_LOOKAHEAD]; /* symbol, or unused */
  165295. } d_derived_tbl;
  165296. /* Expand a Huffman table definition into the derived format */
  165297. EXTERN(void) jpeg_make_d_derived_tbl
  165298. JPP((j_decompress_ptr cinfo, boolean isDC, int tblno,
  165299. d_derived_tbl ** pdtbl));
  165300. /*
  165301. * Fetching the next N bits from the input stream is a time-critical operation
  165302. * for the Huffman decoders. We implement it with a combination of inline
  165303. * macros and out-of-line subroutines. Note that N (the number of bits
  165304. * demanded at one time) never exceeds 15 for JPEG use.
  165305. *
  165306. * We read source bytes into get_buffer and dole out bits as needed.
  165307. * If get_buffer already contains enough bits, they are fetched in-line
  165308. * by the macros CHECK_BIT_BUFFER and GET_BITS. When there aren't enough
  165309. * bits, jpeg_fill_bit_buffer is called; it will attempt to fill get_buffer
  165310. * as full as possible (not just to the number of bits needed; this
  165311. * prefetching reduces the overhead cost of calling jpeg_fill_bit_buffer).
  165312. * Note that jpeg_fill_bit_buffer may return FALSE to indicate suspension.
  165313. * On TRUE return, jpeg_fill_bit_buffer guarantees that get_buffer contains
  165314. * at least the requested number of bits --- dummy zeroes are inserted if
  165315. * necessary.
  165316. */
  165317. typedef INT32 bit_buf_type; /* type of bit-extraction buffer */
  165318. #define BIT_BUF_SIZE 32 /* size of buffer in bits */
  165319. /* If long is > 32 bits on your machine, and shifting/masking longs is
  165320. * reasonably fast, making bit_buf_type be long and setting BIT_BUF_SIZE
  165321. * appropriately should be a win. Unfortunately we can't define the size
  165322. * with something like #define BIT_BUF_SIZE (sizeof(bit_buf_type)*8)
  165323. * because not all machines measure sizeof in 8-bit bytes.
  165324. */
  165325. typedef struct { /* Bitreading state saved across MCUs */
  165326. bit_buf_type get_buffer; /* current bit-extraction buffer */
  165327. int bits_left; /* # of unused bits in it */
  165328. } bitread_perm_state;
  165329. typedef struct { /* Bitreading working state within an MCU */
  165330. /* Current data source location */
  165331. /* We need a copy, rather than munging the original, in case of suspension */
  165332. const JOCTET * next_input_byte; /* => next byte to read from source */
  165333. size_t bytes_in_buffer; /* # of bytes remaining in source buffer */
  165334. /* Bit input buffer --- note these values are kept in register variables,
  165335. * not in this struct, inside the inner loops.
  165336. */
  165337. bit_buf_type get_buffer; /* current bit-extraction buffer */
  165338. int bits_left; /* # of unused bits in it */
  165339. /* Pointer needed by jpeg_fill_bit_buffer. */
  165340. j_decompress_ptr cinfo; /* back link to decompress master record */
  165341. } bitread_working_state;
  165342. /* Macros to declare and load/save bitread local variables. */
  165343. #define BITREAD_STATE_VARS \
  165344. register bit_buf_type get_buffer; \
  165345. register int bits_left; \
  165346. bitread_working_state br_state
  165347. #define BITREAD_LOAD_STATE(cinfop,permstate) \
  165348. br_state.cinfo = cinfop; \
  165349. br_state.next_input_byte = cinfop->src->next_input_byte; \
  165350. br_state.bytes_in_buffer = cinfop->src->bytes_in_buffer; \
  165351. get_buffer = permstate.get_buffer; \
  165352. bits_left = permstate.bits_left;
  165353. #define BITREAD_SAVE_STATE(cinfop,permstate) \
  165354. cinfop->src->next_input_byte = br_state.next_input_byte; \
  165355. cinfop->src->bytes_in_buffer = br_state.bytes_in_buffer; \
  165356. permstate.get_buffer = get_buffer; \
  165357. permstate.bits_left = bits_left
  165358. /*
  165359. * These macros provide the in-line portion of bit fetching.
  165360. * Use CHECK_BIT_BUFFER to ensure there are N bits in get_buffer
  165361. * before using GET_BITS, PEEK_BITS, or DROP_BITS.
  165362. * The variables get_buffer and bits_left are assumed to be locals,
  165363. * but the state struct might not be (jpeg_huff_decode needs this).
  165364. * CHECK_BIT_BUFFER(state,n,action);
  165365. * Ensure there are N bits in get_buffer; if suspend, take action.
  165366. * val = GET_BITS(n);
  165367. * Fetch next N bits.
  165368. * val = PEEK_BITS(n);
  165369. * Fetch next N bits without removing them from the buffer.
  165370. * DROP_BITS(n);
  165371. * Discard next N bits.
  165372. * The value N should be a simple variable, not an expression, because it
  165373. * is evaluated multiple times.
  165374. */
  165375. #define CHECK_BIT_BUFFER(state,nbits,action) \
  165376. { if (bits_left < (nbits)) { \
  165377. if (! jpeg_fill_bit_buffer(&(state),get_buffer,bits_left,nbits)) \
  165378. { action; } \
  165379. get_buffer = (state).get_buffer; bits_left = (state).bits_left; } }
  165380. #define GET_BITS(nbits) \
  165381. (((int) (get_buffer >> (bits_left -= (nbits)))) & ((1<<(nbits))-1))
  165382. #define PEEK_BITS(nbits) \
  165383. (((int) (get_buffer >> (bits_left - (nbits)))) & ((1<<(nbits))-1))
  165384. #define DROP_BITS(nbits) \
  165385. (bits_left -= (nbits))
  165386. /* Load up the bit buffer to a depth of at least nbits */
  165387. EXTERN(boolean) jpeg_fill_bit_buffer
  165388. JPP((bitread_working_state * state, register bit_buf_type get_buffer,
  165389. register int bits_left, int nbits));
  165390. /*
  165391. * Code for extracting next Huffman-coded symbol from input bit stream.
  165392. * Again, this is time-critical and we make the main paths be macros.
  165393. *
  165394. * We use a lookahead table to process codes of up to HUFF_LOOKAHEAD bits
  165395. * without looping. Usually, more than 95% of the Huffman codes will be 8
  165396. * or fewer bits long. The few overlength codes are handled with a loop,
  165397. * which need not be inline code.
  165398. *
  165399. * Notes about the HUFF_DECODE macro:
  165400. * 1. Near the end of the data segment, we may fail to get enough bits
  165401. * for a lookahead. In that case, we do it the hard way.
  165402. * 2. If the lookahead table contains no entry, the next code must be
  165403. * more than HUFF_LOOKAHEAD bits long.
  165404. * 3. jpeg_huff_decode returns -1 if forced to suspend.
  165405. */
  165406. #define HUFF_DECODE(result,state,htbl,failaction,slowlabel) \
  165407. { register int nb, look; \
  165408. if (bits_left < HUFF_LOOKAHEAD) { \
  165409. if (! jpeg_fill_bit_buffer(&state,get_buffer,bits_left, 0)) {failaction;} \
  165410. get_buffer = state.get_buffer; bits_left = state.bits_left; \
  165411. if (bits_left < HUFF_LOOKAHEAD) { \
  165412. nb = 1; goto slowlabel; \
  165413. } \
  165414. } \
  165415. look = PEEK_BITS(HUFF_LOOKAHEAD); \
  165416. if ((nb = htbl->look_nbits[look]) != 0) { \
  165417. DROP_BITS(nb); \
  165418. result = htbl->look_sym[look]; \
  165419. } else { \
  165420. nb = HUFF_LOOKAHEAD+1; \
  165421. slowlabel: \
  165422. if ((result=jpeg_huff_decode(&state,get_buffer,bits_left,htbl,nb)) < 0) \
  165423. { failaction; } \
  165424. get_buffer = state.get_buffer; bits_left = state.bits_left; \
  165425. } \
  165426. }
  165427. /* Out-of-line case for Huffman code fetching */
  165428. EXTERN(int) jpeg_huff_decode
  165429. JPP((bitread_working_state * state, register bit_buf_type get_buffer,
  165430. register int bits_left, d_derived_tbl * htbl, int min_bits));
  165431. #endif
  165432. /********* End of inlined file: jdhuff.h *********/
  165433. /* Declarations shared with jdphuff.c */
  165434. /*
  165435. * Expanded entropy decoder object for Huffman decoding.
  165436. *
  165437. * The savable_state subrecord contains fields that change within an MCU,
  165438. * but must not be updated permanently until we complete the MCU.
  165439. */
  165440. typedef struct {
  165441. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  165442. } savable_state2;
  165443. /* This macro is to work around compilers with missing or broken
  165444. * structure assignment. You'll need to fix this code if you have
  165445. * such a compiler and you change MAX_COMPS_IN_SCAN.
  165446. */
  165447. #ifndef NO_STRUCT_ASSIGN
  165448. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  165449. #else
  165450. #if MAX_COMPS_IN_SCAN == 4
  165451. #define ASSIGN_STATE(dest,src) \
  165452. ((dest).last_dc_val[0] = (src).last_dc_val[0], \
  165453. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  165454. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  165455. (dest).last_dc_val[3] = (src).last_dc_val[3])
  165456. #endif
  165457. #endif
  165458. typedef struct {
  165459. struct jpeg_entropy_decoder pub; /* public fields */
  165460. /* These fields are loaded into local variables at start of each MCU.
  165461. * In case of suspension, we exit WITHOUT updating them.
  165462. */
  165463. bitread_perm_state bitstate; /* Bit buffer at start of MCU */
  165464. savable_state2 saved; /* Other state at start of MCU */
  165465. /* These fields are NOT loaded into local working state. */
  165466. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  165467. /* Pointers to derived tables (these workspaces have image lifespan) */
  165468. d_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS];
  165469. d_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS];
  165470. /* Precalculated info set up by start_pass for use in decode_mcu: */
  165471. /* Pointers to derived tables to be used for each block within an MCU */
  165472. d_derived_tbl * dc_cur_tbls[D_MAX_BLOCKS_IN_MCU];
  165473. d_derived_tbl * ac_cur_tbls[D_MAX_BLOCKS_IN_MCU];
  165474. /* Whether we care about the DC and AC coefficient values for each block */
  165475. boolean dc_needed[D_MAX_BLOCKS_IN_MCU];
  165476. boolean ac_needed[D_MAX_BLOCKS_IN_MCU];
  165477. } huff_entropy_decoder2;
  165478. typedef huff_entropy_decoder2 * huff_entropy_ptr2;
  165479. /*
  165480. * Initialize for a Huffman-compressed scan.
  165481. */
  165482. METHODDEF(void)
  165483. start_pass_huff_decoder (j_decompress_ptr cinfo)
  165484. {
  165485. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  165486. int ci, blkn, dctbl, actbl;
  165487. jpeg_component_info * compptr;
  165488. /* Check that the scan parameters Ss, Se, Ah/Al are OK for sequential JPEG.
  165489. * This ought to be an error condition, but we make it a warning because
  165490. * there are some baseline files out there with all zeroes in these bytes.
  165491. */
  165492. if (cinfo->Ss != 0 || cinfo->Se != DCTSIZE2-1 ||
  165493. cinfo->Ah != 0 || cinfo->Al != 0)
  165494. WARNMS(cinfo, JWRN_NOT_SEQUENTIAL);
  165495. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  165496. compptr = cinfo->cur_comp_info[ci];
  165497. dctbl = compptr->dc_tbl_no;
  165498. actbl = compptr->ac_tbl_no;
  165499. /* Compute derived values for Huffman tables */
  165500. /* We may do this more than once for a table, but it's not expensive */
  165501. jpeg_make_d_derived_tbl(cinfo, TRUE, dctbl,
  165502. & entropy->dc_derived_tbls[dctbl]);
  165503. jpeg_make_d_derived_tbl(cinfo, FALSE, actbl,
  165504. & entropy->ac_derived_tbls[actbl]);
  165505. /* Initialize DC predictions to 0 */
  165506. entropy->saved.last_dc_val[ci] = 0;
  165507. }
  165508. /* Precalculate decoding info for each block in an MCU of this scan */
  165509. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  165510. ci = cinfo->MCU_membership[blkn];
  165511. compptr = cinfo->cur_comp_info[ci];
  165512. /* Precalculate which table to use for each block */
  165513. entropy->dc_cur_tbls[blkn] = entropy->dc_derived_tbls[compptr->dc_tbl_no];
  165514. entropy->ac_cur_tbls[blkn] = entropy->ac_derived_tbls[compptr->ac_tbl_no];
  165515. /* Decide whether we really care about the coefficient values */
  165516. if (compptr->component_needed) {
  165517. entropy->dc_needed[blkn] = TRUE;
  165518. /* we don't need the ACs if producing a 1/8th-size image */
  165519. entropy->ac_needed[blkn] = (compptr->DCT_scaled_size > 1);
  165520. } else {
  165521. entropy->dc_needed[blkn] = entropy->ac_needed[blkn] = FALSE;
  165522. }
  165523. }
  165524. /* Initialize bitread state variables */
  165525. entropy->bitstate.bits_left = 0;
  165526. entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */
  165527. entropy->pub.insufficient_data = FALSE;
  165528. /* Initialize restart counter */
  165529. entropy->restarts_to_go = cinfo->restart_interval;
  165530. }
  165531. /*
  165532. * Compute the derived values for a Huffman table.
  165533. * This routine also performs some validation checks on the table.
  165534. *
  165535. * Note this is also used by jdphuff.c.
  165536. */
  165537. GLOBAL(void)
  165538. jpeg_make_d_derived_tbl (j_decompress_ptr cinfo, boolean isDC, int tblno,
  165539. d_derived_tbl ** pdtbl)
  165540. {
  165541. JHUFF_TBL *htbl;
  165542. d_derived_tbl *dtbl;
  165543. int p, i, l, si, numsymbols;
  165544. int lookbits, ctr;
  165545. char huffsize[257];
  165546. unsigned int huffcode[257];
  165547. unsigned int code;
  165548. /* Note that huffsize[] and huffcode[] are filled in code-length order,
  165549. * paralleling the order of the symbols themselves in htbl->huffval[].
  165550. */
  165551. /* Find the input Huffman table */
  165552. if (tblno < 0 || tblno >= NUM_HUFF_TBLS)
  165553. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  165554. htbl =
  165555. isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno];
  165556. if (htbl == NULL)
  165557. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  165558. /* Allocate a workspace if we haven't already done so. */
  165559. if (*pdtbl == NULL)
  165560. *pdtbl = (d_derived_tbl *)
  165561. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165562. SIZEOF(d_derived_tbl));
  165563. dtbl = *pdtbl;
  165564. dtbl->pub = htbl; /* fill in back link */
  165565. /* Figure C.1: make table of Huffman code length for each symbol */
  165566. p = 0;
  165567. for (l = 1; l <= 16; l++) {
  165568. i = (int) htbl->bits[l];
  165569. if (i < 0 || p + i > 256) /* protect against table overrun */
  165570. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  165571. while (i--)
  165572. huffsize[p++] = (char) l;
  165573. }
  165574. huffsize[p] = 0;
  165575. numsymbols = p;
  165576. /* Figure C.2: generate the codes themselves */
  165577. /* We also validate that the counts represent a legal Huffman code tree. */
  165578. code = 0;
  165579. si = huffsize[0];
  165580. p = 0;
  165581. while (huffsize[p]) {
  165582. while (((int) huffsize[p]) == si) {
  165583. huffcode[p++] = code;
  165584. code++;
  165585. }
  165586. /* code is now 1 more than the last code used for codelength si; but
  165587. * it must still fit in si bits, since no code is allowed to be all ones.
  165588. */
  165589. if (((INT32) code) >= (((INT32) 1) << si))
  165590. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  165591. code <<= 1;
  165592. si++;
  165593. }
  165594. /* Figure F.15: generate decoding tables for bit-sequential decoding */
  165595. p = 0;
  165596. for (l = 1; l <= 16; l++) {
  165597. if (htbl->bits[l]) {
  165598. /* valoffset[l] = huffval[] index of 1st symbol of code length l,
  165599. * minus the minimum code of length l
  165600. */
  165601. dtbl->valoffset[l] = (INT32) p - (INT32) huffcode[p];
  165602. p += htbl->bits[l];
  165603. dtbl->maxcode[l] = huffcode[p-1]; /* maximum code of length l */
  165604. } else {
  165605. dtbl->maxcode[l] = -1; /* -1 if no codes of this length */
  165606. }
  165607. }
  165608. dtbl->maxcode[17] = 0xFFFFFL; /* ensures jpeg_huff_decode terminates */
  165609. /* Compute lookahead tables to speed up decoding.
  165610. * First we set all the table entries to 0, indicating "too long";
  165611. * then we iterate through the Huffman codes that are short enough and
  165612. * fill in all the entries that correspond to bit sequences starting
  165613. * with that code.
  165614. */
  165615. MEMZERO(dtbl->look_nbits, SIZEOF(dtbl->look_nbits));
  165616. p = 0;
  165617. for (l = 1; l <= HUFF_LOOKAHEAD; l++) {
  165618. for (i = 1; i <= (int) htbl->bits[l]; i++, p++) {
  165619. /* l = current code's length, p = its index in huffcode[] & huffval[]. */
  165620. /* Generate left-justified code followed by all possible bit sequences */
  165621. lookbits = huffcode[p] << (HUFF_LOOKAHEAD-l);
  165622. for (ctr = 1 << (HUFF_LOOKAHEAD-l); ctr > 0; ctr--) {
  165623. dtbl->look_nbits[lookbits] = l;
  165624. dtbl->look_sym[lookbits] = htbl->huffval[p];
  165625. lookbits++;
  165626. }
  165627. }
  165628. }
  165629. /* Validate symbols as being reasonable.
  165630. * For AC tables, we make no check, but accept all byte values 0..255.
  165631. * For DC tables, we require the symbols to be in range 0..15.
  165632. * (Tighter bounds could be applied depending on the data depth and mode,
  165633. * but this is sufficient to ensure safe decoding.)
  165634. */
  165635. if (isDC) {
  165636. for (i = 0; i < numsymbols; i++) {
  165637. int sym = htbl->huffval[i];
  165638. if (sym < 0 || sym > 15)
  165639. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  165640. }
  165641. }
  165642. }
  165643. /*
  165644. * Out-of-line code for bit fetching (shared with jdphuff.c).
  165645. * See jdhuff.h for info about usage.
  165646. * Note: current values of get_buffer and bits_left are passed as parameters,
  165647. * but are returned in the corresponding fields of the state struct.
  165648. *
  165649. * On most machines MIN_GET_BITS should be 25 to allow the full 32-bit width
  165650. * of get_buffer to be used. (On machines with wider words, an even larger
  165651. * buffer could be used.) However, on some machines 32-bit shifts are
  165652. * quite slow and take time proportional to the number of places shifted.
  165653. * (This is true with most PC compilers, for instance.) In this case it may
  165654. * be a win to set MIN_GET_BITS to the minimum value of 15. This reduces the
  165655. * average shift distance at the cost of more calls to jpeg_fill_bit_buffer.
  165656. */
  165657. #ifdef SLOW_SHIFT_32
  165658. #define MIN_GET_BITS 15 /* minimum allowable value */
  165659. #else
  165660. #define MIN_GET_BITS (BIT_BUF_SIZE-7)
  165661. #endif
  165662. GLOBAL(boolean)
  165663. jpeg_fill_bit_buffer (bitread_working_state * state,
  165664. register bit_buf_type get_buffer, register int bits_left,
  165665. int nbits)
  165666. /* Load up the bit buffer to a depth of at least nbits */
  165667. {
  165668. /* Copy heavily used state fields into locals (hopefully registers) */
  165669. register const JOCTET * next_input_byte = state->next_input_byte;
  165670. register size_t bytes_in_buffer = state->bytes_in_buffer;
  165671. j_decompress_ptr cinfo = state->cinfo;
  165672. /* Attempt to load at least MIN_GET_BITS bits into get_buffer. */
  165673. /* (It is assumed that no request will be for more than that many bits.) */
  165674. /* We fail to do so only if we hit a marker or are forced to suspend. */
  165675. if (cinfo->unread_marker == 0) { /* cannot advance past a marker */
  165676. while (bits_left < MIN_GET_BITS) {
  165677. register int c;
  165678. /* Attempt to read a byte */
  165679. if (bytes_in_buffer == 0) {
  165680. if (! (*cinfo->src->fill_input_buffer) (cinfo))
  165681. return FALSE;
  165682. next_input_byte = cinfo->src->next_input_byte;
  165683. bytes_in_buffer = cinfo->src->bytes_in_buffer;
  165684. }
  165685. bytes_in_buffer--;
  165686. c = GETJOCTET(*next_input_byte++);
  165687. /* If it's 0xFF, check and discard stuffed zero byte */
  165688. if (c == 0xFF) {
  165689. /* Loop here to discard any padding FF's on terminating marker,
  165690. * so that we can save a valid unread_marker value. NOTE: we will
  165691. * accept multiple FF's followed by a 0 as meaning a single FF data
  165692. * byte. This data pattern is not valid according to the standard.
  165693. */
  165694. do {
  165695. if (bytes_in_buffer == 0) {
  165696. if (! (*cinfo->src->fill_input_buffer) (cinfo))
  165697. return FALSE;
  165698. next_input_byte = cinfo->src->next_input_byte;
  165699. bytes_in_buffer = cinfo->src->bytes_in_buffer;
  165700. }
  165701. bytes_in_buffer--;
  165702. c = GETJOCTET(*next_input_byte++);
  165703. } while (c == 0xFF);
  165704. if (c == 0) {
  165705. /* Found FF/00, which represents an FF data byte */
  165706. c = 0xFF;
  165707. } else {
  165708. /* Oops, it's actually a marker indicating end of compressed data.
  165709. * Save the marker code for later use.
  165710. * Fine point: it might appear that we should save the marker into
  165711. * bitread working state, not straight into permanent state. But
  165712. * once we have hit a marker, we cannot need to suspend within the
  165713. * current MCU, because we will read no more bytes from the data
  165714. * source. So it is OK to update permanent state right away.
  165715. */
  165716. cinfo->unread_marker = c;
  165717. /* See if we need to insert some fake zero bits. */
  165718. goto no_more_bytes;
  165719. }
  165720. }
  165721. /* OK, load c into get_buffer */
  165722. get_buffer = (get_buffer << 8) | c;
  165723. bits_left += 8;
  165724. } /* end while */
  165725. } else {
  165726. no_more_bytes:
  165727. /* We get here if we've read the marker that terminates the compressed
  165728. * data segment. There should be enough bits in the buffer register
  165729. * to satisfy the request; if so, no problem.
  165730. */
  165731. if (nbits > bits_left) {
  165732. /* Uh-oh. Report corrupted data to user and stuff zeroes into
  165733. * the data stream, so that we can produce some kind of image.
  165734. * We use a nonvolatile flag to ensure that only one warning message
  165735. * appears per data segment.
  165736. */
  165737. if (! cinfo->entropy->insufficient_data) {
  165738. WARNMS(cinfo, JWRN_HIT_MARKER);
  165739. cinfo->entropy->insufficient_data = TRUE;
  165740. }
  165741. /* Fill the buffer with zero bits */
  165742. get_buffer <<= MIN_GET_BITS - bits_left;
  165743. bits_left = MIN_GET_BITS;
  165744. }
  165745. }
  165746. /* Unload the local registers */
  165747. state->next_input_byte = next_input_byte;
  165748. state->bytes_in_buffer = bytes_in_buffer;
  165749. state->get_buffer = get_buffer;
  165750. state->bits_left = bits_left;
  165751. return TRUE;
  165752. }
  165753. /*
  165754. * Out-of-line code for Huffman code decoding.
  165755. * See jdhuff.h for info about usage.
  165756. */
  165757. GLOBAL(int)
  165758. jpeg_huff_decode (bitread_working_state * state,
  165759. register bit_buf_type get_buffer, register int bits_left,
  165760. d_derived_tbl * htbl, int min_bits)
  165761. {
  165762. register int l = min_bits;
  165763. register INT32 code;
  165764. /* HUFF_DECODE has determined that the code is at least min_bits */
  165765. /* bits long, so fetch that many bits in one swoop. */
  165766. CHECK_BIT_BUFFER(*state, l, return -1);
  165767. code = GET_BITS(l);
  165768. /* Collect the rest of the Huffman code one bit at a time. */
  165769. /* This is per Figure F.16 in the JPEG spec. */
  165770. while (code > htbl->maxcode[l]) {
  165771. code <<= 1;
  165772. CHECK_BIT_BUFFER(*state, 1, return -1);
  165773. code |= GET_BITS(1);
  165774. l++;
  165775. }
  165776. /* Unload the local registers */
  165777. state->get_buffer = get_buffer;
  165778. state->bits_left = bits_left;
  165779. /* With garbage input we may reach the sentinel value l = 17. */
  165780. if (l > 16) {
  165781. WARNMS(state->cinfo, JWRN_HUFF_BAD_CODE);
  165782. return 0; /* fake a zero as the safest result */
  165783. }
  165784. return htbl->pub->huffval[ (int) (code + htbl->valoffset[l]) ];
  165785. }
  165786. /*
  165787. * Check for a restart marker & resynchronize decoder.
  165788. * Returns FALSE if must suspend.
  165789. */
  165790. LOCAL(boolean)
  165791. process_restart (j_decompress_ptr cinfo)
  165792. {
  165793. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  165794. int ci;
  165795. /* Throw away any unused bits remaining in bit buffer; */
  165796. /* include any full bytes in next_marker's count of discarded bytes */
  165797. cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8;
  165798. entropy->bitstate.bits_left = 0;
  165799. /* Advance past the RSTn marker */
  165800. if (! (*cinfo->marker->read_restart_marker) (cinfo))
  165801. return FALSE;
  165802. /* Re-initialize DC predictions to 0 */
  165803. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  165804. entropy->saved.last_dc_val[ci] = 0;
  165805. /* Reset restart counter */
  165806. entropy->restarts_to_go = cinfo->restart_interval;
  165807. /* Reset out-of-data flag, unless read_restart_marker left us smack up
  165808. * against a marker. In that case we will end up treating the next data
  165809. * segment as empty, and we can avoid producing bogus output pixels by
  165810. * leaving the flag set.
  165811. */
  165812. if (cinfo->unread_marker == 0)
  165813. entropy->pub.insufficient_data = FALSE;
  165814. return TRUE;
  165815. }
  165816. /*
  165817. * Decode and return one MCU's worth of Huffman-compressed coefficients.
  165818. * The coefficients are reordered from zigzag order into natural array order,
  165819. * but are not dequantized.
  165820. *
  165821. * The i'th block of the MCU is stored into the block pointed to by
  165822. * MCU_data[i]. WE ASSUME THIS AREA HAS BEEN ZEROED BY THE CALLER.
  165823. * (Wholesale zeroing is usually a little faster than retail...)
  165824. *
  165825. * Returns FALSE if data source requested suspension. In that case no
  165826. * changes have been made to permanent state. (Exception: some output
  165827. * coefficients may already have been assigned. This is harmless for
  165828. * this module, since we'll just re-assign them on the next call.)
  165829. */
  165830. METHODDEF(boolean)
  165831. decode_mcu (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  165832. {
  165833. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  165834. int blkn;
  165835. BITREAD_STATE_VARS;
  165836. savable_state2 state;
  165837. /* Process restart marker if needed; may have to suspend */
  165838. if (cinfo->restart_interval) {
  165839. if (entropy->restarts_to_go == 0)
  165840. if (! process_restart(cinfo))
  165841. return FALSE;
  165842. }
  165843. /* If we've run out of data, just leave the MCU set to zeroes.
  165844. * This way, we return uniform gray for the remainder of the segment.
  165845. */
  165846. if (! entropy->pub.insufficient_data) {
  165847. /* Load up working state */
  165848. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  165849. ASSIGN_STATE(state, entropy->saved);
  165850. /* Outer loop handles each block in the MCU */
  165851. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  165852. JBLOCKROW block = MCU_data[blkn];
  165853. d_derived_tbl * dctbl = entropy->dc_cur_tbls[blkn];
  165854. d_derived_tbl * actbl = entropy->ac_cur_tbls[blkn];
  165855. register int s, k, r;
  165856. /* Decode a single block's worth of coefficients */
  165857. /* Section F.2.2.1: decode the DC coefficient difference */
  165858. HUFF_DECODE(s, br_state, dctbl, return FALSE, label1);
  165859. if (s) {
  165860. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  165861. r = GET_BITS(s);
  165862. s = HUFF_EXTEND(r, s);
  165863. }
  165864. if (entropy->dc_needed[blkn]) {
  165865. /* Convert DC difference to actual value, update last_dc_val */
  165866. int ci = cinfo->MCU_membership[blkn];
  165867. s += state.last_dc_val[ci];
  165868. state.last_dc_val[ci] = s;
  165869. /* Output the DC coefficient (assumes jpeg_natural_order[0] = 0) */
  165870. (*block)[0] = (JCOEF) s;
  165871. }
  165872. if (entropy->ac_needed[blkn]) {
  165873. /* Section F.2.2.2: decode the AC coefficients */
  165874. /* Since zeroes are skipped, output area must be cleared beforehand */
  165875. for (k = 1; k < DCTSIZE2; k++) {
  165876. HUFF_DECODE(s, br_state, actbl, return FALSE, label2);
  165877. r = s >> 4;
  165878. s &= 15;
  165879. if (s) {
  165880. k += r;
  165881. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  165882. r = GET_BITS(s);
  165883. s = HUFF_EXTEND(r, s);
  165884. /* Output coefficient in natural (dezigzagged) order.
  165885. * Note: the extra entries in jpeg_natural_order[] will save us
  165886. * if k >= DCTSIZE2, which could happen if the data is corrupted.
  165887. */
  165888. (*block)[jpeg_natural_order[k]] = (JCOEF) s;
  165889. } else {
  165890. if (r != 15)
  165891. break;
  165892. k += 15;
  165893. }
  165894. }
  165895. } else {
  165896. /* Section F.2.2.2: decode the AC coefficients */
  165897. /* In this path we just discard the values */
  165898. for (k = 1; k < DCTSIZE2; k++) {
  165899. HUFF_DECODE(s, br_state, actbl, return FALSE, label3);
  165900. r = s >> 4;
  165901. s &= 15;
  165902. if (s) {
  165903. k += r;
  165904. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  165905. DROP_BITS(s);
  165906. } else {
  165907. if (r != 15)
  165908. break;
  165909. k += 15;
  165910. }
  165911. }
  165912. }
  165913. }
  165914. /* Completed MCU, so update state */
  165915. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  165916. ASSIGN_STATE(entropy->saved, state);
  165917. }
  165918. /* Account for restart interval (no-op if not using restarts) */
  165919. entropy->restarts_to_go--;
  165920. return TRUE;
  165921. }
  165922. /*
  165923. * Module initialization routine for Huffman entropy decoding.
  165924. */
  165925. GLOBAL(void)
  165926. jinit_huff_decoder (j_decompress_ptr cinfo)
  165927. {
  165928. huff_entropy_ptr2 entropy;
  165929. int i;
  165930. entropy = (huff_entropy_ptr2)
  165931. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165932. SIZEOF(huff_entropy_decoder2));
  165933. cinfo->entropy = (struct jpeg_entropy_decoder *) entropy;
  165934. entropy->pub.start_pass = start_pass_huff_decoder;
  165935. entropy->pub.decode_mcu = decode_mcu;
  165936. /* Mark tables unallocated */
  165937. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  165938. entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
  165939. }
  165940. }
  165941. /********* End of inlined file: jdhuff.c *********/
  165942. /********* Start of inlined file: jdinput.c *********/
  165943. #define JPEG_INTERNALS
  165944. /* Private state */
  165945. typedef struct {
  165946. struct jpeg_input_controller pub; /* public fields */
  165947. boolean inheaders; /* TRUE until first SOS is reached */
  165948. } my_input_controller;
  165949. typedef my_input_controller * my_inputctl_ptr;
  165950. /* Forward declarations */
  165951. METHODDEF(int) consume_markers JPP((j_decompress_ptr cinfo));
  165952. /*
  165953. * Routines to calculate various quantities related to the size of the image.
  165954. */
  165955. LOCAL(void)
  165956. initial_setup2 (j_decompress_ptr cinfo)
  165957. /* Called once, when first SOS marker is reached */
  165958. {
  165959. int ci;
  165960. jpeg_component_info *compptr;
  165961. /* Make sure image isn't bigger than I can handle */
  165962. if ((long) cinfo->image_height > (long) JPEG_MAX_DIMENSION ||
  165963. (long) cinfo->image_width > (long) JPEG_MAX_DIMENSION)
  165964. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) JPEG_MAX_DIMENSION);
  165965. /* For now, precision must match compiled-in value... */
  165966. if (cinfo->data_precision != BITS_IN_JSAMPLE)
  165967. ERREXIT1(cinfo, JERR_BAD_PRECISION, cinfo->data_precision);
  165968. /* Check that number of components won't exceed internal array sizes */
  165969. if (cinfo->num_components > MAX_COMPONENTS)
  165970. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  165971. MAX_COMPONENTS);
  165972. /* Compute maximum sampling factors; check factor validity */
  165973. cinfo->max_h_samp_factor = 1;
  165974. cinfo->max_v_samp_factor = 1;
  165975. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  165976. ci++, compptr++) {
  165977. if (compptr->h_samp_factor<=0 || compptr->h_samp_factor>MAX_SAMP_FACTOR ||
  165978. compptr->v_samp_factor<=0 || compptr->v_samp_factor>MAX_SAMP_FACTOR)
  165979. ERREXIT(cinfo, JERR_BAD_SAMPLING);
  165980. cinfo->max_h_samp_factor = MAX(cinfo->max_h_samp_factor,
  165981. compptr->h_samp_factor);
  165982. cinfo->max_v_samp_factor = MAX(cinfo->max_v_samp_factor,
  165983. compptr->v_samp_factor);
  165984. }
  165985. /* We initialize DCT_scaled_size and min_DCT_scaled_size to DCTSIZE.
  165986. * In the full decompressor, this will be overridden by jdmaster.c;
  165987. * but in the transcoder, jdmaster.c is not used, so we must do it here.
  165988. */
  165989. cinfo->min_DCT_scaled_size = DCTSIZE;
  165990. /* Compute dimensions of components */
  165991. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  165992. ci++, compptr++) {
  165993. compptr->DCT_scaled_size = DCTSIZE;
  165994. /* Size in DCT blocks */
  165995. compptr->width_in_blocks = (JDIMENSION)
  165996. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  165997. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  165998. compptr->height_in_blocks = (JDIMENSION)
  165999. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  166000. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  166001. /* downsampled_width and downsampled_height will also be overridden by
  166002. * jdmaster.c if we are doing full decompression. The transcoder library
  166003. * doesn't use these values, but the calling application might.
  166004. */
  166005. /* Size in samples */
  166006. compptr->downsampled_width = (JDIMENSION)
  166007. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  166008. (long) cinfo->max_h_samp_factor);
  166009. compptr->downsampled_height = (JDIMENSION)
  166010. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  166011. (long) cinfo->max_v_samp_factor);
  166012. /* Mark component needed, until color conversion says otherwise */
  166013. compptr->component_needed = TRUE;
  166014. /* Mark no quantization table yet saved for component */
  166015. compptr->quant_table = NULL;
  166016. }
  166017. /* Compute number of fully interleaved MCU rows. */
  166018. cinfo->total_iMCU_rows = (JDIMENSION)
  166019. jdiv_round_up((long) cinfo->image_height,
  166020. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  166021. /* Decide whether file contains multiple scans */
  166022. if (cinfo->comps_in_scan < cinfo->num_components || cinfo->progressive_mode)
  166023. cinfo->inputctl->has_multiple_scans = TRUE;
  166024. else
  166025. cinfo->inputctl->has_multiple_scans = FALSE;
  166026. }
  166027. LOCAL(void)
  166028. per_scan_setup2 (j_decompress_ptr cinfo)
  166029. /* Do computations that are needed before processing a JPEG scan */
  166030. /* cinfo->comps_in_scan and cinfo->cur_comp_info[] were set from SOS marker */
  166031. {
  166032. int ci, mcublks, tmp;
  166033. jpeg_component_info *compptr;
  166034. if (cinfo->comps_in_scan == 1) {
  166035. /* Noninterleaved (single-component) scan */
  166036. compptr = cinfo->cur_comp_info[0];
  166037. /* Overall image size in MCUs */
  166038. cinfo->MCUs_per_row = compptr->width_in_blocks;
  166039. cinfo->MCU_rows_in_scan = compptr->height_in_blocks;
  166040. /* For noninterleaved scan, always one block per MCU */
  166041. compptr->MCU_width = 1;
  166042. compptr->MCU_height = 1;
  166043. compptr->MCU_blocks = 1;
  166044. compptr->MCU_sample_width = compptr->DCT_scaled_size;
  166045. compptr->last_col_width = 1;
  166046. /* For noninterleaved scans, it is convenient to define last_row_height
  166047. * as the number of block rows present in the last iMCU row.
  166048. */
  166049. tmp = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  166050. if (tmp == 0) tmp = compptr->v_samp_factor;
  166051. compptr->last_row_height = tmp;
  166052. /* Prepare array describing MCU composition */
  166053. cinfo->blocks_in_MCU = 1;
  166054. cinfo->MCU_membership[0] = 0;
  166055. } else {
  166056. /* Interleaved (multi-component) scan */
  166057. if (cinfo->comps_in_scan <= 0 || cinfo->comps_in_scan > MAX_COMPS_IN_SCAN)
  166058. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->comps_in_scan,
  166059. MAX_COMPS_IN_SCAN);
  166060. /* Overall image size in MCUs */
  166061. cinfo->MCUs_per_row = (JDIMENSION)
  166062. jdiv_round_up((long) cinfo->image_width,
  166063. (long) (cinfo->max_h_samp_factor*DCTSIZE));
  166064. cinfo->MCU_rows_in_scan = (JDIMENSION)
  166065. jdiv_round_up((long) cinfo->image_height,
  166066. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  166067. cinfo->blocks_in_MCU = 0;
  166068. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  166069. compptr = cinfo->cur_comp_info[ci];
  166070. /* Sampling factors give # of blocks of component in each MCU */
  166071. compptr->MCU_width = compptr->h_samp_factor;
  166072. compptr->MCU_height = compptr->v_samp_factor;
  166073. compptr->MCU_blocks = compptr->MCU_width * compptr->MCU_height;
  166074. compptr->MCU_sample_width = compptr->MCU_width * compptr->DCT_scaled_size;
  166075. /* Figure number of non-dummy blocks in last MCU column & row */
  166076. tmp = (int) (compptr->width_in_blocks % compptr->MCU_width);
  166077. if (tmp == 0) tmp = compptr->MCU_width;
  166078. compptr->last_col_width = tmp;
  166079. tmp = (int) (compptr->height_in_blocks % compptr->MCU_height);
  166080. if (tmp == 0) tmp = compptr->MCU_height;
  166081. compptr->last_row_height = tmp;
  166082. /* Prepare array describing MCU composition */
  166083. mcublks = compptr->MCU_blocks;
  166084. if (cinfo->blocks_in_MCU + mcublks > D_MAX_BLOCKS_IN_MCU)
  166085. ERREXIT(cinfo, JERR_BAD_MCU_SIZE);
  166086. while (mcublks-- > 0) {
  166087. cinfo->MCU_membership[cinfo->blocks_in_MCU++] = ci;
  166088. }
  166089. }
  166090. }
  166091. }
  166092. /*
  166093. * Save away a copy of the Q-table referenced by each component present
  166094. * in the current scan, unless already saved during a prior scan.
  166095. *
  166096. * In a multiple-scan JPEG file, the encoder could assign different components
  166097. * the same Q-table slot number, but change table definitions between scans
  166098. * so that each component uses a different Q-table. (The IJG encoder is not
  166099. * currently capable of doing this, but other encoders might.) Since we want
  166100. * to be able to dequantize all the components at the end of the file, this
  166101. * means that we have to save away the table actually used for each component.
  166102. * We do this by copying the table at the start of the first scan containing
  166103. * the component.
  166104. * The JPEG spec prohibits the encoder from changing the contents of a Q-table
  166105. * slot between scans of a component using that slot. If the encoder does so
  166106. * anyway, this decoder will simply use the Q-table values that were current
  166107. * at the start of the first scan for the component.
  166108. *
  166109. * The decompressor output side looks only at the saved quant tables,
  166110. * not at the current Q-table slots.
  166111. */
  166112. LOCAL(void)
  166113. latch_quant_tables (j_decompress_ptr cinfo)
  166114. {
  166115. int ci, qtblno;
  166116. jpeg_component_info *compptr;
  166117. JQUANT_TBL * qtbl;
  166118. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  166119. compptr = cinfo->cur_comp_info[ci];
  166120. /* No work if we already saved Q-table for this component */
  166121. if (compptr->quant_table != NULL)
  166122. continue;
  166123. /* Make sure specified quantization table is present */
  166124. qtblno = compptr->quant_tbl_no;
  166125. if (qtblno < 0 || qtblno >= NUM_QUANT_TBLS ||
  166126. cinfo->quant_tbl_ptrs[qtblno] == NULL)
  166127. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, qtblno);
  166128. /* OK, save away the quantization table */
  166129. qtbl = (JQUANT_TBL *)
  166130. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166131. SIZEOF(JQUANT_TBL));
  166132. MEMCOPY(qtbl, cinfo->quant_tbl_ptrs[qtblno], SIZEOF(JQUANT_TBL));
  166133. compptr->quant_table = qtbl;
  166134. }
  166135. }
  166136. /*
  166137. * Initialize the input modules to read a scan of compressed data.
  166138. * The first call to this is done by jdmaster.c after initializing
  166139. * the entire decompressor (during jpeg_start_decompress).
  166140. * Subsequent calls come from consume_markers, below.
  166141. */
  166142. METHODDEF(void)
  166143. start_input_pass2 (j_decompress_ptr cinfo)
  166144. {
  166145. per_scan_setup2(cinfo);
  166146. latch_quant_tables(cinfo);
  166147. (*cinfo->entropy->start_pass) (cinfo);
  166148. (*cinfo->coef->start_input_pass) (cinfo);
  166149. cinfo->inputctl->consume_input = cinfo->coef->consume_data;
  166150. }
  166151. /*
  166152. * Finish up after inputting a compressed-data scan.
  166153. * This is called by the coefficient controller after it's read all
  166154. * the expected data of the scan.
  166155. */
  166156. METHODDEF(void)
  166157. finish_input_pass (j_decompress_ptr cinfo)
  166158. {
  166159. cinfo->inputctl->consume_input = consume_markers;
  166160. }
  166161. /*
  166162. * Read JPEG markers before, between, or after compressed-data scans.
  166163. * Change state as necessary when a new scan is reached.
  166164. * Return value is JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  166165. *
  166166. * The consume_input method pointer points either here or to the
  166167. * coefficient controller's consume_data routine, depending on whether
  166168. * we are reading a compressed data segment or inter-segment markers.
  166169. */
  166170. METHODDEF(int)
  166171. consume_markers (j_decompress_ptr cinfo)
  166172. {
  166173. my_inputctl_ptr inputctl = (my_inputctl_ptr) cinfo->inputctl;
  166174. int val;
  166175. if (inputctl->pub.eoi_reached) /* After hitting EOI, read no further */
  166176. return JPEG_REACHED_EOI;
  166177. val = (*cinfo->marker->read_markers) (cinfo);
  166178. switch (val) {
  166179. case JPEG_REACHED_SOS: /* Found SOS */
  166180. if (inputctl->inheaders) { /* 1st SOS */
  166181. initial_setup2(cinfo);
  166182. inputctl->inheaders = FALSE;
  166183. /* Note: start_input_pass must be called by jdmaster.c
  166184. * before any more input can be consumed. jdapimin.c is
  166185. * responsible for enforcing this sequencing.
  166186. */
  166187. } else { /* 2nd or later SOS marker */
  166188. if (! inputctl->pub.has_multiple_scans)
  166189. ERREXIT(cinfo, JERR_EOI_EXPECTED); /* Oops, I wasn't expecting this! */
  166190. start_input_pass2(cinfo);
  166191. }
  166192. break;
  166193. case JPEG_REACHED_EOI: /* Found EOI */
  166194. inputctl->pub.eoi_reached = TRUE;
  166195. if (inputctl->inheaders) { /* Tables-only datastream, apparently */
  166196. if (cinfo->marker->saw_SOF)
  166197. ERREXIT(cinfo, JERR_SOF_NO_SOS);
  166198. } else {
  166199. /* Prevent infinite loop in coef ctlr's decompress_data routine
  166200. * if user set output_scan_number larger than number of scans.
  166201. */
  166202. if (cinfo->output_scan_number > cinfo->input_scan_number)
  166203. cinfo->output_scan_number = cinfo->input_scan_number;
  166204. }
  166205. break;
  166206. case JPEG_SUSPENDED:
  166207. break;
  166208. }
  166209. return val;
  166210. }
  166211. /*
  166212. * Reset state to begin a fresh datastream.
  166213. */
  166214. METHODDEF(void)
  166215. reset_input_controller (j_decompress_ptr cinfo)
  166216. {
  166217. my_inputctl_ptr inputctl = (my_inputctl_ptr) cinfo->inputctl;
  166218. inputctl->pub.consume_input = consume_markers;
  166219. inputctl->pub.has_multiple_scans = FALSE; /* "unknown" would be better */
  166220. inputctl->pub.eoi_reached = FALSE;
  166221. inputctl->inheaders = TRUE;
  166222. /* Reset other modules */
  166223. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  166224. (*cinfo->marker->reset_marker_reader) (cinfo);
  166225. /* Reset progression state -- would be cleaner if entropy decoder did this */
  166226. cinfo->coef_bits = NULL;
  166227. }
  166228. /*
  166229. * Initialize the input controller module.
  166230. * This is called only once, when the decompression object is created.
  166231. */
  166232. GLOBAL(void)
  166233. jinit_input_controller (j_decompress_ptr cinfo)
  166234. {
  166235. my_inputctl_ptr inputctl;
  166236. /* Create subobject in permanent pool */
  166237. inputctl = (my_inputctl_ptr)
  166238. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  166239. SIZEOF(my_input_controller));
  166240. cinfo->inputctl = (struct jpeg_input_controller *) inputctl;
  166241. /* Initialize method pointers */
  166242. inputctl->pub.consume_input = consume_markers;
  166243. inputctl->pub.reset_input_controller = reset_input_controller;
  166244. inputctl->pub.start_input_pass = start_input_pass2;
  166245. inputctl->pub.finish_input_pass = finish_input_pass;
  166246. /* Initialize state: can't use reset_input_controller since we don't
  166247. * want to try to reset other modules yet.
  166248. */
  166249. inputctl->pub.has_multiple_scans = FALSE; /* "unknown" would be better */
  166250. inputctl->pub.eoi_reached = FALSE;
  166251. inputctl->inheaders = TRUE;
  166252. }
  166253. /********* End of inlined file: jdinput.c *********/
  166254. /********* Start of inlined file: jdmainct.c *********/
  166255. #define JPEG_INTERNALS
  166256. /*
  166257. * In the current system design, the main buffer need never be a full-image
  166258. * buffer; any full-height buffers will be found inside the coefficient or
  166259. * postprocessing controllers. Nonetheless, the main controller is not
  166260. * trivial. Its responsibility is to provide context rows for upsampling/
  166261. * rescaling, and doing this in an efficient fashion is a bit tricky.
  166262. *
  166263. * Postprocessor input data is counted in "row groups". A row group
  166264. * is defined to be (v_samp_factor * DCT_scaled_size / min_DCT_scaled_size)
  166265. * sample rows of each component. (We require DCT_scaled_size values to be
  166266. * chosen such that these numbers are integers. In practice DCT_scaled_size
  166267. * values will likely be powers of two, so we actually have the stronger
  166268. * condition that DCT_scaled_size / min_DCT_scaled_size is an integer.)
  166269. * Upsampling will typically produce max_v_samp_factor pixel rows from each
  166270. * row group (times any additional scale factor that the upsampler is
  166271. * applying).
  166272. *
  166273. * The coefficient controller will deliver data to us one iMCU row at a time;
  166274. * each iMCU row contains v_samp_factor * DCT_scaled_size sample rows, or
  166275. * exactly min_DCT_scaled_size row groups. (This amount of data corresponds
  166276. * to one row of MCUs when the image is fully interleaved.) Note that the
  166277. * number of sample rows varies across components, but the number of row
  166278. * groups does not. Some garbage sample rows may be included in the last iMCU
  166279. * row at the bottom of the image.
  166280. *
  166281. * Depending on the vertical scaling algorithm used, the upsampler may need
  166282. * access to the sample row(s) above and below its current input row group.
  166283. * The upsampler is required to set need_context_rows TRUE at global selection
  166284. * time if so. When need_context_rows is FALSE, this controller can simply
  166285. * obtain one iMCU row at a time from the coefficient controller and dole it
  166286. * out as row groups to the postprocessor.
  166287. *
  166288. * When need_context_rows is TRUE, this controller guarantees that the buffer
  166289. * passed to postprocessing contains at least one row group's worth of samples
  166290. * above and below the row group(s) being processed. Note that the context
  166291. * rows "above" the first passed row group appear at negative row offsets in
  166292. * the passed buffer. At the top and bottom of the image, the required
  166293. * context rows are manufactured by duplicating the first or last real sample
  166294. * row; this avoids having special cases in the upsampling inner loops.
  166295. *
  166296. * The amount of context is fixed at one row group just because that's a
  166297. * convenient number for this controller to work with. The existing
  166298. * upsamplers really only need one sample row of context. An upsampler
  166299. * supporting arbitrary output rescaling might wish for more than one row
  166300. * group of context when shrinking the image; tough, we don't handle that.
  166301. * (This is justified by the assumption that downsizing will be handled mostly
  166302. * by adjusting the DCT_scaled_size values, so that the actual scale factor at
  166303. * the upsample step needn't be much less than one.)
  166304. *
  166305. * To provide the desired context, we have to retain the last two row groups
  166306. * of one iMCU row while reading in the next iMCU row. (The last row group
  166307. * can't be processed until we have another row group for its below-context,
  166308. * and so we have to save the next-to-last group too for its above-context.)
  166309. * We could do this most simply by copying data around in our buffer, but
  166310. * that'd be very slow. We can avoid copying any data by creating a rather
  166311. * strange pointer structure. Here's how it works. We allocate a workspace
  166312. * consisting of M+2 row groups (where M = min_DCT_scaled_size is the number
  166313. * of row groups per iMCU row). We create two sets of redundant pointers to
  166314. * the workspace. Labeling the physical row groups 0 to M+1, the synthesized
  166315. * pointer lists look like this:
  166316. * M+1 M-1
  166317. * master pointer --> 0 master pointer --> 0
  166318. * 1 1
  166319. * ... ...
  166320. * M-3 M-3
  166321. * M-2 M
  166322. * M-1 M+1
  166323. * M M-2
  166324. * M+1 M-1
  166325. * 0 0
  166326. * We read alternate iMCU rows using each master pointer; thus the last two
  166327. * row groups of the previous iMCU row remain un-overwritten in the workspace.
  166328. * The pointer lists are set up so that the required context rows appear to
  166329. * be adjacent to the proper places when we pass the pointer lists to the
  166330. * upsampler.
  166331. *
  166332. * The above pictures describe the normal state of the pointer lists.
  166333. * At top and bottom of the image, we diddle the pointer lists to duplicate
  166334. * the first or last sample row as necessary (this is cheaper than copying
  166335. * sample rows around).
  166336. *
  166337. * This scheme breaks down if M < 2, ie, min_DCT_scaled_size is 1. In that
  166338. * situation each iMCU row provides only one row group so the buffering logic
  166339. * must be different (eg, we must read two iMCU rows before we can emit the
  166340. * first row group). For now, we simply do not support providing context
  166341. * rows when min_DCT_scaled_size is 1. That combination seems unlikely to
  166342. * be worth providing --- if someone wants a 1/8th-size preview, they probably
  166343. * want it quick and dirty, so a context-free upsampler is sufficient.
  166344. */
  166345. /* Private buffer controller object */
  166346. typedef struct {
  166347. struct jpeg_d_main_controller pub; /* public fields */
  166348. /* Pointer to allocated workspace (M or M+2 row groups). */
  166349. JSAMPARRAY buffer[MAX_COMPONENTS];
  166350. boolean buffer_full; /* Have we gotten an iMCU row from decoder? */
  166351. JDIMENSION rowgroup_ctr; /* counts row groups output to postprocessor */
  166352. /* Remaining fields are only used in the context case. */
  166353. /* These are the master pointers to the funny-order pointer lists. */
  166354. JSAMPIMAGE xbuffer[2]; /* pointers to weird pointer lists */
  166355. int whichptr; /* indicates which pointer set is now in use */
  166356. int context_state; /* process_data state machine status */
  166357. JDIMENSION rowgroups_avail; /* row groups available to postprocessor */
  166358. JDIMENSION iMCU_row_ctr; /* counts iMCU rows to detect image top/bot */
  166359. } my_main_controller4;
  166360. typedef my_main_controller4 * my_main_ptr4;
  166361. /* context_state values: */
  166362. #define CTX_PREPARE_FOR_IMCU 0 /* need to prepare for MCU row */
  166363. #define CTX_PROCESS_IMCU 1 /* feeding iMCU to postprocessor */
  166364. #define CTX_POSTPONED_ROW 2 /* feeding postponed row group */
  166365. /* Forward declarations */
  166366. METHODDEF(void) process_data_simple_main2
  166367. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  166368. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  166369. METHODDEF(void) process_data_context_main
  166370. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  166371. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  166372. #ifdef QUANT_2PASS_SUPPORTED
  166373. METHODDEF(void) process_data_crank_post
  166374. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  166375. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  166376. #endif
  166377. LOCAL(void)
  166378. alloc_funny_pointers (j_decompress_ptr cinfo)
  166379. /* Allocate space for the funny pointer lists.
  166380. * This is done only once, not once per pass.
  166381. */
  166382. {
  166383. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  166384. int ci, rgroup;
  166385. int M = cinfo->min_DCT_scaled_size;
  166386. jpeg_component_info *compptr;
  166387. JSAMPARRAY xbuf;
  166388. /* Get top-level space for component array pointers.
  166389. * We alloc both arrays with one call to save a few cycles.
  166390. */
  166391. main_->xbuffer[0] = (JSAMPIMAGE)
  166392. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166393. cinfo->num_components * 2 * SIZEOF(JSAMPARRAY));
  166394. main_->xbuffer[1] = main_->xbuffer[0] + cinfo->num_components;
  166395. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166396. ci++, compptr++) {
  166397. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  166398. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  166399. /* Get space for pointer lists --- M+4 row groups in each list.
  166400. * We alloc both pointer lists with one call to save a few cycles.
  166401. */
  166402. xbuf = (JSAMPARRAY)
  166403. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166404. 2 * (rgroup * (M + 4)) * SIZEOF(JSAMPROW));
  166405. xbuf += rgroup; /* want one row group at negative offsets */
  166406. main_->xbuffer[0][ci] = xbuf;
  166407. xbuf += rgroup * (M + 4);
  166408. main_->xbuffer[1][ci] = xbuf;
  166409. }
  166410. }
  166411. LOCAL(void)
  166412. make_funny_pointers (j_decompress_ptr cinfo)
  166413. /* Create the funny pointer lists discussed in the comments above.
  166414. * The actual workspace is already allocated (in main->buffer),
  166415. * and the space for the pointer lists is allocated too.
  166416. * This routine just fills in the curiously ordered lists.
  166417. * This will be repeated at the beginning of each pass.
  166418. */
  166419. {
  166420. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  166421. int ci, i, rgroup;
  166422. int M = cinfo->min_DCT_scaled_size;
  166423. jpeg_component_info *compptr;
  166424. JSAMPARRAY buf, xbuf0, xbuf1;
  166425. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166426. ci++, compptr++) {
  166427. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  166428. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  166429. xbuf0 = main_->xbuffer[0][ci];
  166430. xbuf1 = main_->xbuffer[1][ci];
  166431. /* First copy the workspace pointers as-is */
  166432. buf = main_->buffer[ci];
  166433. for (i = 0; i < rgroup * (M + 2); i++) {
  166434. xbuf0[i] = xbuf1[i] = buf[i];
  166435. }
  166436. /* In the second list, put the last four row groups in swapped order */
  166437. for (i = 0; i < rgroup * 2; i++) {
  166438. xbuf1[rgroup*(M-2) + i] = buf[rgroup*M + i];
  166439. xbuf1[rgroup*M + i] = buf[rgroup*(M-2) + i];
  166440. }
  166441. /* The wraparound pointers at top and bottom will be filled later
  166442. * (see set_wraparound_pointers, below). Initially we want the "above"
  166443. * pointers to duplicate the first actual data line. This only needs
  166444. * to happen in xbuffer[0].
  166445. */
  166446. for (i = 0; i < rgroup; i++) {
  166447. xbuf0[i - rgroup] = xbuf0[0];
  166448. }
  166449. }
  166450. }
  166451. LOCAL(void)
  166452. set_wraparound_pointers (j_decompress_ptr cinfo)
  166453. /* Set up the "wraparound" pointers at top and bottom of the pointer lists.
  166454. * This changes the pointer list state from top-of-image to the normal state.
  166455. */
  166456. {
  166457. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  166458. int ci, i, rgroup;
  166459. int M = cinfo->min_DCT_scaled_size;
  166460. jpeg_component_info *compptr;
  166461. JSAMPARRAY xbuf0, xbuf1;
  166462. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166463. ci++, compptr++) {
  166464. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  166465. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  166466. xbuf0 = main_->xbuffer[0][ci];
  166467. xbuf1 = main_->xbuffer[1][ci];
  166468. for (i = 0; i < rgroup; i++) {
  166469. xbuf0[i - rgroup] = xbuf0[rgroup*(M+1) + i];
  166470. xbuf1[i - rgroup] = xbuf1[rgroup*(M+1) + i];
  166471. xbuf0[rgroup*(M+2) + i] = xbuf0[i];
  166472. xbuf1[rgroup*(M+2) + i] = xbuf1[i];
  166473. }
  166474. }
  166475. }
  166476. LOCAL(void)
  166477. set_bottom_pointers (j_decompress_ptr cinfo)
  166478. /* Change the pointer lists to duplicate the last sample row at the bottom
  166479. * of the image. whichptr indicates which xbuffer holds the final iMCU row.
  166480. * Also sets rowgroups_avail to indicate number of nondummy row groups in row.
  166481. */
  166482. {
  166483. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  166484. int ci, i, rgroup, iMCUheight, rows_left;
  166485. jpeg_component_info *compptr;
  166486. JSAMPARRAY xbuf;
  166487. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166488. ci++, compptr++) {
  166489. /* Count sample rows in one iMCU row and in one row group */
  166490. iMCUheight = compptr->v_samp_factor * compptr->DCT_scaled_size;
  166491. rgroup = iMCUheight / cinfo->min_DCT_scaled_size;
  166492. /* Count nondummy sample rows remaining for this component */
  166493. rows_left = (int) (compptr->downsampled_height % (JDIMENSION) iMCUheight);
  166494. if (rows_left == 0) rows_left = iMCUheight;
  166495. /* Count nondummy row groups. Should get same answer for each component,
  166496. * so we need only do it once.
  166497. */
  166498. if (ci == 0) {
  166499. main_->rowgroups_avail = (JDIMENSION) ((rows_left-1) / rgroup + 1);
  166500. }
  166501. /* Duplicate the last real sample row rgroup*2 times; this pads out the
  166502. * last partial rowgroup and ensures at least one full rowgroup of context.
  166503. */
  166504. xbuf = main_->xbuffer[main_->whichptr][ci];
  166505. for (i = 0; i < rgroup * 2; i++) {
  166506. xbuf[rows_left + i] = xbuf[rows_left-1];
  166507. }
  166508. }
  166509. }
  166510. /*
  166511. * Initialize for a processing pass.
  166512. */
  166513. METHODDEF(void)
  166514. start_pass_main2 (j_decompress_ptr cinfo, J_BUF_MODE pass_mode)
  166515. {
  166516. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  166517. switch (pass_mode) {
  166518. case JBUF_PASS_THRU:
  166519. if (cinfo->upsample->need_context_rows) {
  166520. main_->pub.process_data = process_data_context_main;
  166521. make_funny_pointers(cinfo); /* Create the xbuffer[] lists */
  166522. main_->whichptr = 0; /* Read first iMCU row into xbuffer[0] */
  166523. main_->context_state = CTX_PREPARE_FOR_IMCU;
  166524. main_->iMCU_row_ctr = 0;
  166525. } else {
  166526. /* Simple case with no context needed */
  166527. main_->pub.process_data = process_data_simple_main2;
  166528. }
  166529. main_->buffer_full = FALSE; /* Mark buffer empty */
  166530. main_->rowgroup_ctr = 0;
  166531. break;
  166532. #ifdef QUANT_2PASS_SUPPORTED
  166533. case JBUF_CRANK_DEST:
  166534. /* For last pass of 2-pass quantization, just crank the postprocessor */
  166535. main_->pub.process_data = process_data_crank_post;
  166536. break;
  166537. #endif
  166538. default:
  166539. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  166540. break;
  166541. }
  166542. }
  166543. /*
  166544. * Process some data.
  166545. * This handles the simple case where no context is required.
  166546. */
  166547. METHODDEF(void)
  166548. process_data_simple_main2 (j_decompress_ptr cinfo,
  166549. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  166550. JDIMENSION out_rows_avail)
  166551. {
  166552. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  166553. JDIMENSION rowgroups_avail;
  166554. /* Read input data if we haven't filled the main buffer yet */
  166555. if (! main_->buffer_full) {
  166556. if (! (*cinfo->coef->decompress_data) (cinfo, main_->buffer))
  166557. return; /* suspension forced, can do nothing more */
  166558. main_->buffer_full = TRUE; /* OK, we have an iMCU row to work with */
  166559. }
  166560. /* There are always min_DCT_scaled_size row groups in an iMCU row. */
  166561. rowgroups_avail = (JDIMENSION) cinfo->min_DCT_scaled_size;
  166562. /* Note: at the bottom of the image, we may pass extra garbage row groups
  166563. * to the postprocessor. The postprocessor has to check for bottom
  166564. * of image anyway (at row resolution), so no point in us doing it too.
  166565. */
  166566. /* Feed the postprocessor */
  166567. (*cinfo->post->post_process_data) (cinfo, main_->buffer,
  166568. &main_->rowgroup_ctr, rowgroups_avail,
  166569. output_buf, out_row_ctr, out_rows_avail);
  166570. /* Has postprocessor consumed all the data yet? If so, mark buffer empty */
  166571. if (main_->rowgroup_ctr >= rowgroups_avail) {
  166572. main_->buffer_full = FALSE;
  166573. main_->rowgroup_ctr = 0;
  166574. }
  166575. }
  166576. /*
  166577. * Process some data.
  166578. * This handles the case where context rows must be provided.
  166579. */
  166580. METHODDEF(void)
  166581. process_data_context_main (j_decompress_ptr cinfo,
  166582. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  166583. JDIMENSION out_rows_avail)
  166584. {
  166585. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  166586. /* Read input data if we haven't filled the main buffer yet */
  166587. if (! main_->buffer_full) {
  166588. if (! (*cinfo->coef->decompress_data) (cinfo,
  166589. main_->xbuffer[main_->whichptr]))
  166590. return; /* suspension forced, can do nothing more */
  166591. main_->buffer_full = TRUE; /* OK, we have an iMCU row to work with */
  166592. main_->iMCU_row_ctr++; /* count rows received */
  166593. }
  166594. /* Postprocessor typically will not swallow all the input data it is handed
  166595. * in one call (due to filling the output buffer first). Must be prepared
  166596. * to exit and restart. This switch lets us keep track of how far we got.
  166597. * Note that each case falls through to the next on successful completion.
  166598. */
  166599. switch (main_->context_state) {
  166600. case CTX_POSTPONED_ROW:
  166601. /* Call postprocessor using previously set pointers for postponed row */
  166602. (*cinfo->post->post_process_data) (cinfo, main_->xbuffer[main_->whichptr],
  166603. &main_->rowgroup_ctr, main_->rowgroups_avail,
  166604. output_buf, out_row_ctr, out_rows_avail);
  166605. if (main_->rowgroup_ctr < main_->rowgroups_avail)
  166606. return; /* Need to suspend */
  166607. main_->context_state = CTX_PREPARE_FOR_IMCU;
  166608. if (*out_row_ctr >= out_rows_avail)
  166609. return; /* Postprocessor exactly filled output buf */
  166610. /*FALLTHROUGH*/
  166611. case CTX_PREPARE_FOR_IMCU:
  166612. /* Prepare to process first M-1 row groups of this iMCU row */
  166613. main_->rowgroup_ctr = 0;
  166614. main_->rowgroups_avail = (JDIMENSION) (cinfo->min_DCT_scaled_size - 1);
  166615. /* Check for bottom of image: if so, tweak pointers to "duplicate"
  166616. * the last sample row, and adjust rowgroups_avail to ignore padding rows.
  166617. */
  166618. if (main_->iMCU_row_ctr == cinfo->total_iMCU_rows)
  166619. set_bottom_pointers(cinfo);
  166620. main_->context_state = CTX_PROCESS_IMCU;
  166621. /*FALLTHROUGH*/
  166622. case CTX_PROCESS_IMCU:
  166623. /* Call postprocessor using previously set pointers */
  166624. (*cinfo->post->post_process_data) (cinfo, main_->xbuffer[main_->whichptr],
  166625. &main_->rowgroup_ctr, main_->rowgroups_avail,
  166626. output_buf, out_row_ctr, out_rows_avail);
  166627. if (main_->rowgroup_ctr < main_->rowgroups_avail)
  166628. return; /* Need to suspend */
  166629. /* After the first iMCU, change wraparound pointers to normal state */
  166630. if (main_->iMCU_row_ctr == 1)
  166631. set_wraparound_pointers(cinfo);
  166632. /* Prepare to load new iMCU row using other xbuffer list */
  166633. main_->whichptr ^= 1; /* 0=>1 or 1=>0 */
  166634. main_->buffer_full = FALSE;
  166635. /* Still need to process last row group of this iMCU row, */
  166636. /* which is saved at index M+1 of the other xbuffer */
  166637. main_->rowgroup_ctr = (JDIMENSION) (cinfo->min_DCT_scaled_size + 1);
  166638. main_->rowgroups_avail = (JDIMENSION) (cinfo->min_DCT_scaled_size + 2);
  166639. main_->context_state = CTX_POSTPONED_ROW;
  166640. }
  166641. }
  166642. /*
  166643. * Process some data.
  166644. * Final pass of two-pass quantization: just call the postprocessor.
  166645. * Source data will be the postprocessor controller's internal buffer.
  166646. */
  166647. #ifdef QUANT_2PASS_SUPPORTED
  166648. METHODDEF(void)
  166649. process_data_crank_post (j_decompress_ptr cinfo,
  166650. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  166651. JDIMENSION out_rows_avail)
  166652. {
  166653. (*cinfo->post->post_process_data) (cinfo, (JSAMPIMAGE) NULL,
  166654. (JDIMENSION *) NULL, (JDIMENSION) 0,
  166655. output_buf, out_row_ctr, out_rows_avail);
  166656. }
  166657. #endif /* QUANT_2PASS_SUPPORTED */
  166658. /*
  166659. * Initialize main buffer controller.
  166660. */
  166661. GLOBAL(void)
  166662. jinit_d_main_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  166663. {
  166664. my_main_ptr4 main_;
  166665. int ci, rgroup, ngroups;
  166666. jpeg_component_info *compptr;
  166667. main_ = (my_main_ptr4)
  166668. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166669. SIZEOF(my_main_controller4));
  166670. cinfo->main = (struct jpeg_d_main_controller *) main_;
  166671. main_->pub.start_pass = start_pass_main2;
  166672. if (need_full_buffer) /* shouldn't happen */
  166673. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  166674. /* Allocate the workspace.
  166675. * ngroups is the number of row groups we need.
  166676. */
  166677. if (cinfo->upsample->need_context_rows) {
  166678. if (cinfo->min_DCT_scaled_size < 2) /* unsupported, see comments above */
  166679. ERREXIT(cinfo, JERR_NOTIMPL);
  166680. alloc_funny_pointers(cinfo); /* Alloc space for xbuffer[] lists */
  166681. ngroups = cinfo->min_DCT_scaled_size + 2;
  166682. } else {
  166683. ngroups = cinfo->min_DCT_scaled_size;
  166684. }
  166685. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166686. ci++, compptr++) {
  166687. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  166688. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  166689. main_->buffer[ci] = (*cinfo->mem->alloc_sarray)
  166690. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166691. compptr->width_in_blocks * compptr->DCT_scaled_size,
  166692. (JDIMENSION) (rgroup * ngroups));
  166693. }
  166694. }
  166695. /********* End of inlined file: jdmainct.c *********/
  166696. /********* Start of inlined file: jdmarker.c *********/
  166697. #define JPEG_INTERNALS
  166698. /* Private state */
  166699. typedef struct {
  166700. struct jpeg_marker_reader pub; /* public fields */
  166701. /* Application-overridable marker processing methods */
  166702. jpeg_marker_parser_method process_COM;
  166703. jpeg_marker_parser_method process_APPn[16];
  166704. /* Limit on marker data length to save for each marker type */
  166705. unsigned int length_limit_COM;
  166706. unsigned int length_limit_APPn[16];
  166707. /* Status of COM/APPn marker saving */
  166708. jpeg_saved_marker_ptr cur_marker; /* NULL if not processing a marker */
  166709. unsigned int bytes_read; /* data bytes read so far in marker */
  166710. /* Note: cur_marker is not linked into marker_list until it's all read. */
  166711. } my_marker_reader;
  166712. typedef my_marker_reader * my_marker_ptr2;
  166713. /*
  166714. * Macros for fetching data from the data source module.
  166715. *
  166716. * At all times, cinfo->src->next_input_byte and ->bytes_in_buffer reflect
  166717. * the current restart point; we update them only when we have reached a
  166718. * suitable place to restart if a suspension occurs.
  166719. */
  166720. /* Declare and initialize local copies of input pointer/count */
  166721. #define INPUT_VARS(cinfo) \
  166722. struct jpeg_source_mgr * datasrc = (cinfo)->src; \
  166723. const JOCTET * next_input_byte = datasrc->next_input_byte; \
  166724. size_t bytes_in_buffer = datasrc->bytes_in_buffer
  166725. /* Unload the local copies --- do this only at a restart boundary */
  166726. #define INPUT_SYNC(cinfo) \
  166727. ( datasrc->next_input_byte = next_input_byte, \
  166728. datasrc->bytes_in_buffer = bytes_in_buffer )
  166729. /* Reload the local copies --- used only in MAKE_BYTE_AVAIL */
  166730. #define INPUT_RELOAD(cinfo) \
  166731. ( next_input_byte = datasrc->next_input_byte, \
  166732. bytes_in_buffer = datasrc->bytes_in_buffer )
  166733. /* Internal macro for INPUT_BYTE and INPUT_2BYTES: make a byte available.
  166734. * Note we do *not* do INPUT_SYNC before calling fill_input_buffer,
  166735. * but we must reload the local copies after a successful fill.
  166736. */
  166737. #define MAKE_BYTE_AVAIL(cinfo,action) \
  166738. if (bytes_in_buffer == 0) { \
  166739. if (! (*datasrc->fill_input_buffer) (cinfo)) \
  166740. { action; } \
  166741. INPUT_RELOAD(cinfo); \
  166742. }
  166743. /* Read a byte into variable V.
  166744. * If must suspend, take the specified action (typically "return FALSE").
  166745. */
  166746. #define INPUT_BYTE(cinfo,V,action) \
  166747. MAKESTMT( MAKE_BYTE_AVAIL(cinfo,action); \
  166748. bytes_in_buffer--; \
  166749. V = GETJOCTET(*next_input_byte++); )
  166750. /* As above, but read two bytes interpreted as an unsigned 16-bit integer.
  166751. * V should be declared unsigned int or perhaps INT32.
  166752. */
  166753. #define INPUT_2BYTES(cinfo,V,action) \
  166754. MAKESTMT( MAKE_BYTE_AVAIL(cinfo,action); \
  166755. bytes_in_buffer--; \
  166756. V = ((unsigned int) GETJOCTET(*next_input_byte++)) << 8; \
  166757. MAKE_BYTE_AVAIL(cinfo,action); \
  166758. bytes_in_buffer--; \
  166759. V += GETJOCTET(*next_input_byte++); )
  166760. /*
  166761. * Routines to process JPEG markers.
  166762. *
  166763. * Entry condition: JPEG marker itself has been read and its code saved
  166764. * in cinfo->unread_marker; input restart point is just after the marker.
  166765. *
  166766. * Exit: if return TRUE, have read and processed any parameters, and have
  166767. * updated the restart point to point after the parameters.
  166768. * If return FALSE, was forced to suspend before reaching end of
  166769. * marker parameters; restart point has not been moved. Same routine
  166770. * will be called again after application supplies more input data.
  166771. *
  166772. * This approach to suspension assumes that all of a marker's parameters
  166773. * can fit into a single input bufferload. This should hold for "normal"
  166774. * markers. Some COM/APPn markers might have large parameter segments
  166775. * that might not fit. If we are simply dropping such a marker, we use
  166776. * skip_input_data to get past it, and thereby put the problem on the
  166777. * source manager's shoulders. If we are saving the marker's contents
  166778. * into memory, we use a slightly different convention: when forced to
  166779. * suspend, the marker processor updates the restart point to the end of
  166780. * what it's consumed (ie, the end of the buffer) before returning FALSE.
  166781. * On resumption, cinfo->unread_marker still contains the marker code,
  166782. * but the data source will point to the next chunk of marker data.
  166783. * The marker processor must retain internal state to deal with this.
  166784. *
  166785. * Note that we don't bother to avoid duplicate trace messages if a
  166786. * suspension occurs within marker parameters. Other side effects
  166787. * require more care.
  166788. */
  166789. LOCAL(boolean)
  166790. get_soi (j_decompress_ptr cinfo)
  166791. /* Process an SOI marker */
  166792. {
  166793. int i;
  166794. TRACEMS(cinfo, 1, JTRC_SOI);
  166795. if (cinfo->marker->saw_SOI)
  166796. ERREXIT(cinfo, JERR_SOI_DUPLICATE);
  166797. /* Reset all parameters that are defined to be reset by SOI */
  166798. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  166799. cinfo->arith_dc_L[i] = 0;
  166800. cinfo->arith_dc_U[i] = 1;
  166801. cinfo->arith_ac_K[i] = 5;
  166802. }
  166803. cinfo->restart_interval = 0;
  166804. /* Set initial assumptions for colorspace etc */
  166805. cinfo->jpeg_color_space = JCS_UNKNOWN;
  166806. cinfo->CCIR601_sampling = FALSE; /* Assume non-CCIR sampling??? */
  166807. cinfo->saw_JFIF_marker = FALSE;
  166808. cinfo->JFIF_major_version = 1; /* set default JFIF APP0 values */
  166809. cinfo->JFIF_minor_version = 1;
  166810. cinfo->density_unit = 0;
  166811. cinfo->X_density = 1;
  166812. cinfo->Y_density = 1;
  166813. cinfo->saw_Adobe_marker = FALSE;
  166814. cinfo->Adobe_transform = 0;
  166815. cinfo->marker->saw_SOI = TRUE;
  166816. return TRUE;
  166817. }
  166818. LOCAL(boolean)
  166819. get_sof (j_decompress_ptr cinfo, boolean is_prog, boolean is_arith)
  166820. /* Process a SOFn marker */
  166821. {
  166822. INT32 length;
  166823. int c, ci;
  166824. jpeg_component_info * compptr;
  166825. INPUT_VARS(cinfo);
  166826. cinfo->progressive_mode = is_prog;
  166827. cinfo->arith_code = is_arith;
  166828. INPUT_2BYTES(cinfo, length, return FALSE);
  166829. INPUT_BYTE(cinfo, cinfo->data_precision, return FALSE);
  166830. INPUT_2BYTES(cinfo, cinfo->image_height, return FALSE);
  166831. INPUT_2BYTES(cinfo, cinfo->image_width, return FALSE);
  166832. INPUT_BYTE(cinfo, cinfo->num_components, return FALSE);
  166833. length -= 8;
  166834. TRACEMS4(cinfo, 1, JTRC_SOF, cinfo->unread_marker,
  166835. (int) cinfo->image_width, (int) cinfo->image_height,
  166836. cinfo->num_components);
  166837. if (cinfo->marker->saw_SOF)
  166838. ERREXIT(cinfo, JERR_SOF_DUPLICATE);
  166839. /* We don't support files in which the image height is initially specified */
  166840. /* as 0 and is later redefined by DNL. As long as we have to check that, */
  166841. /* might as well have a general sanity check. */
  166842. if (cinfo->image_height <= 0 || cinfo->image_width <= 0
  166843. || cinfo->num_components <= 0)
  166844. ERREXIT(cinfo, JERR_EMPTY_IMAGE);
  166845. if (length != (cinfo->num_components * 3))
  166846. ERREXIT(cinfo, JERR_BAD_LENGTH);
  166847. if (cinfo->comp_info == NULL) /* do only once, even if suspend */
  166848. cinfo->comp_info = (jpeg_component_info *) (*cinfo->mem->alloc_small)
  166849. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166850. cinfo->num_components * SIZEOF(jpeg_component_info));
  166851. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166852. ci++, compptr++) {
  166853. compptr->component_index = ci;
  166854. INPUT_BYTE(cinfo, compptr->component_id, return FALSE);
  166855. INPUT_BYTE(cinfo, c, return FALSE);
  166856. compptr->h_samp_factor = (c >> 4) & 15;
  166857. compptr->v_samp_factor = (c ) & 15;
  166858. INPUT_BYTE(cinfo, compptr->quant_tbl_no, return FALSE);
  166859. TRACEMS4(cinfo, 1, JTRC_SOF_COMPONENT,
  166860. compptr->component_id, compptr->h_samp_factor,
  166861. compptr->v_samp_factor, compptr->quant_tbl_no);
  166862. }
  166863. cinfo->marker->saw_SOF = TRUE;
  166864. INPUT_SYNC(cinfo);
  166865. return TRUE;
  166866. }
  166867. LOCAL(boolean)
  166868. get_sos (j_decompress_ptr cinfo)
  166869. /* Process a SOS marker */
  166870. {
  166871. INT32 length;
  166872. int i, ci, n, c, cc;
  166873. jpeg_component_info * compptr;
  166874. INPUT_VARS(cinfo);
  166875. if (! cinfo->marker->saw_SOF)
  166876. ERREXIT(cinfo, JERR_SOS_NO_SOF);
  166877. INPUT_2BYTES(cinfo, length, return FALSE);
  166878. INPUT_BYTE(cinfo, n, return FALSE); /* Number of components */
  166879. TRACEMS1(cinfo, 1, JTRC_SOS, n);
  166880. if (length != (n * 2 + 6) || n < 1 || n > MAX_COMPS_IN_SCAN)
  166881. ERREXIT(cinfo, JERR_BAD_LENGTH);
  166882. cinfo->comps_in_scan = n;
  166883. /* Collect the component-spec parameters */
  166884. for (i = 0; i < n; i++) {
  166885. INPUT_BYTE(cinfo, cc, return FALSE);
  166886. INPUT_BYTE(cinfo, c, return FALSE);
  166887. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166888. ci++, compptr++) {
  166889. if (cc == compptr->component_id)
  166890. goto id_found;
  166891. }
  166892. ERREXIT1(cinfo, JERR_BAD_COMPONENT_ID, cc);
  166893. id_found:
  166894. cinfo->cur_comp_info[i] = compptr;
  166895. compptr->dc_tbl_no = (c >> 4) & 15;
  166896. compptr->ac_tbl_no = (c ) & 15;
  166897. TRACEMS3(cinfo, 1, JTRC_SOS_COMPONENT, cc,
  166898. compptr->dc_tbl_no, compptr->ac_tbl_no);
  166899. }
  166900. /* Collect the additional scan parameters Ss, Se, Ah/Al. */
  166901. INPUT_BYTE(cinfo, c, return FALSE);
  166902. cinfo->Ss = c;
  166903. INPUT_BYTE(cinfo, c, return FALSE);
  166904. cinfo->Se = c;
  166905. INPUT_BYTE(cinfo, c, return FALSE);
  166906. cinfo->Ah = (c >> 4) & 15;
  166907. cinfo->Al = (c ) & 15;
  166908. TRACEMS4(cinfo, 1, JTRC_SOS_PARAMS, cinfo->Ss, cinfo->Se,
  166909. cinfo->Ah, cinfo->Al);
  166910. /* Prepare to scan data & restart markers */
  166911. cinfo->marker->next_restart_num = 0;
  166912. /* Count another SOS marker */
  166913. cinfo->input_scan_number++;
  166914. INPUT_SYNC(cinfo);
  166915. return TRUE;
  166916. }
  166917. #ifdef D_ARITH_CODING_SUPPORTED
  166918. LOCAL(boolean)
  166919. get_dac (j_decompress_ptr cinfo)
  166920. /* Process a DAC marker */
  166921. {
  166922. INT32 length;
  166923. int index, val;
  166924. INPUT_VARS(cinfo);
  166925. INPUT_2BYTES(cinfo, length, return FALSE);
  166926. length -= 2;
  166927. while (length > 0) {
  166928. INPUT_BYTE(cinfo, index, return FALSE);
  166929. INPUT_BYTE(cinfo, val, return FALSE);
  166930. length -= 2;
  166931. TRACEMS2(cinfo, 1, JTRC_DAC, index, val);
  166932. if (index < 0 || index >= (2*NUM_ARITH_TBLS))
  166933. ERREXIT1(cinfo, JERR_DAC_INDEX, index);
  166934. if (index >= NUM_ARITH_TBLS) { /* define AC table */
  166935. cinfo->arith_ac_K[index-NUM_ARITH_TBLS] = (UINT8) val;
  166936. } else { /* define DC table */
  166937. cinfo->arith_dc_L[index] = (UINT8) (val & 0x0F);
  166938. cinfo->arith_dc_U[index] = (UINT8) (val >> 4);
  166939. if (cinfo->arith_dc_L[index] > cinfo->arith_dc_U[index])
  166940. ERREXIT1(cinfo, JERR_DAC_VALUE, val);
  166941. }
  166942. }
  166943. if (length != 0)
  166944. ERREXIT(cinfo, JERR_BAD_LENGTH);
  166945. INPUT_SYNC(cinfo);
  166946. return TRUE;
  166947. }
  166948. #else /* ! D_ARITH_CODING_SUPPORTED */
  166949. #define get_dac(cinfo) skip_variable(cinfo)
  166950. #endif /* D_ARITH_CODING_SUPPORTED */
  166951. LOCAL(boolean)
  166952. get_dht (j_decompress_ptr cinfo)
  166953. /* Process a DHT marker */
  166954. {
  166955. INT32 length;
  166956. UINT8 bits[17];
  166957. UINT8 huffval[256];
  166958. int i, index, count;
  166959. JHUFF_TBL **htblptr;
  166960. INPUT_VARS(cinfo);
  166961. INPUT_2BYTES(cinfo, length, return FALSE);
  166962. length -= 2;
  166963. while (length > 16) {
  166964. INPUT_BYTE(cinfo, index, return FALSE);
  166965. TRACEMS1(cinfo, 1, JTRC_DHT, index);
  166966. bits[0] = 0;
  166967. count = 0;
  166968. for (i = 1; i <= 16; i++) {
  166969. INPUT_BYTE(cinfo, bits[i], return FALSE);
  166970. count += bits[i];
  166971. }
  166972. length -= 1 + 16;
  166973. TRACEMS8(cinfo, 2, JTRC_HUFFBITS,
  166974. bits[1], bits[2], bits[3], bits[4],
  166975. bits[5], bits[6], bits[7], bits[8]);
  166976. TRACEMS8(cinfo, 2, JTRC_HUFFBITS,
  166977. bits[9], bits[10], bits[11], bits[12],
  166978. bits[13], bits[14], bits[15], bits[16]);
  166979. /* Here we just do minimal validation of the counts to avoid walking
  166980. * off the end of our table space. jdhuff.c will check more carefully.
  166981. */
  166982. if (count > 256 || ((INT32) count) > length)
  166983. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  166984. for (i = 0; i < count; i++)
  166985. INPUT_BYTE(cinfo, huffval[i], return FALSE);
  166986. length -= count;
  166987. if (index & 0x10) { /* AC table definition */
  166988. index -= 0x10;
  166989. htblptr = &cinfo->ac_huff_tbl_ptrs[index];
  166990. } else { /* DC table definition */
  166991. htblptr = &cinfo->dc_huff_tbl_ptrs[index];
  166992. }
  166993. if (index < 0 || index >= NUM_HUFF_TBLS)
  166994. ERREXIT1(cinfo, JERR_DHT_INDEX, index);
  166995. if (*htblptr == NULL)
  166996. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  166997. MEMCOPY((*htblptr)->bits, bits, SIZEOF((*htblptr)->bits));
  166998. MEMCOPY((*htblptr)->huffval, huffval, SIZEOF((*htblptr)->huffval));
  166999. }
  167000. if (length != 0)
  167001. ERREXIT(cinfo, JERR_BAD_LENGTH);
  167002. INPUT_SYNC(cinfo);
  167003. return TRUE;
  167004. }
  167005. LOCAL(boolean)
  167006. get_dqt (j_decompress_ptr cinfo)
  167007. /* Process a DQT marker */
  167008. {
  167009. INT32 length;
  167010. int n, i, prec;
  167011. unsigned int tmp;
  167012. JQUANT_TBL *quant_ptr;
  167013. INPUT_VARS(cinfo);
  167014. INPUT_2BYTES(cinfo, length, return FALSE);
  167015. length -= 2;
  167016. while (length > 0) {
  167017. INPUT_BYTE(cinfo, n, return FALSE);
  167018. prec = n >> 4;
  167019. n &= 0x0F;
  167020. TRACEMS2(cinfo, 1, JTRC_DQT, n, prec);
  167021. if (n >= NUM_QUANT_TBLS)
  167022. ERREXIT1(cinfo, JERR_DQT_INDEX, n);
  167023. if (cinfo->quant_tbl_ptrs[n] == NULL)
  167024. cinfo->quant_tbl_ptrs[n] = jpeg_alloc_quant_table((j_common_ptr) cinfo);
  167025. quant_ptr = cinfo->quant_tbl_ptrs[n];
  167026. for (i = 0; i < DCTSIZE2; i++) {
  167027. if (prec)
  167028. INPUT_2BYTES(cinfo, tmp, return FALSE);
  167029. else
  167030. INPUT_BYTE(cinfo, tmp, return FALSE);
  167031. /* We convert the zigzag-order table to natural array order. */
  167032. quant_ptr->quantval[jpeg_natural_order[i]] = (UINT16) tmp;
  167033. }
  167034. if (cinfo->err->trace_level >= 2) {
  167035. for (i = 0; i < DCTSIZE2; i += 8) {
  167036. TRACEMS8(cinfo, 2, JTRC_QUANTVALS,
  167037. quant_ptr->quantval[i], quant_ptr->quantval[i+1],
  167038. quant_ptr->quantval[i+2], quant_ptr->quantval[i+3],
  167039. quant_ptr->quantval[i+4], quant_ptr->quantval[i+5],
  167040. quant_ptr->quantval[i+6], quant_ptr->quantval[i+7]);
  167041. }
  167042. }
  167043. length -= DCTSIZE2+1;
  167044. if (prec) length -= DCTSIZE2;
  167045. }
  167046. if (length != 0)
  167047. ERREXIT(cinfo, JERR_BAD_LENGTH);
  167048. INPUT_SYNC(cinfo);
  167049. return TRUE;
  167050. }
  167051. LOCAL(boolean)
  167052. get_dri (j_decompress_ptr cinfo)
  167053. /* Process a DRI marker */
  167054. {
  167055. INT32 length;
  167056. unsigned int tmp;
  167057. INPUT_VARS(cinfo);
  167058. INPUT_2BYTES(cinfo, length, return FALSE);
  167059. if (length != 4)
  167060. ERREXIT(cinfo, JERR_BAD_LENGTH);
  167061. INPUT_2BYTES(cinfo, tmp, return FALSE);
  167062. TRACEMS1(cinfo, 1, JTRC_DRI, tmp);
  167063. cinfo->restart_interval = tmp;
  167064. INPUT_SYNC(cinfo);
  167065. return TRUE;
  167066. }
  167067. /*
  167068. * Routines for processing APPn and COM markers.
  167069. * These are either saved in memory or discarded, per application request.
  167070. * APP0 and APP14 are specially checked to see if they are
  167071. * JFIF and Adobe markers, respectively.
  167072. */
  167073. #define APP0_DATA_LEN 14 /* Length of interesting data in APP0 */
  167074. #define APP14_DATA_LEN 12 /* Length of interesting data in APP14 */
  167075. #define APPN_DATA_LEN 14 /* Must be the largest of the above!! */
  167076. LOCAL(void)
  167077. examine_app0 (j_decompress_ptr cinfo, JOCTET FAR * data,
  167078. unsigned int datalen, INT32 remaining)
  167079. /* Examine first few bytes from an APP0.
  167080. * Take appropriate action if it is a JFIF marker.
  167081. * datalen is # of bytes at data[], remaining is length of rest of marker data.
  167082. */
  167083. {
  167084. INT32 totallen = (INT32) datalen + remaining;
  167085. if (datalen >= APP0_DATA_LEN &&
  167086. GETJOCTET(data[0]) == 0x4A &&
  167087. GETJOCTET(data[1]) == 0x46 &&
  167088. GETJOCTET(data[2]) == 0x49 &&
  167089. GETJOCTET(data[3]) == 0x46 &&
  167090. GETJOCTET(data[4]) == 0) {
  167091. /* Found JFIF APP0 marker: save info */
  167092. cinfo->saw_JFIF_marker = TRUE;
  167093. cinfo->JFIF_major_version = GETJOCTET(data[5]);
  167094. cinfo->JFIF_minor_version = GETJOCTET(data[6]);
  167095. cinfo->density_unit = GETJOCTET(data[7]);
  167096. cinfo->X_density = (GETJOCTET(data[8]) << 8) + GETJOCTET(data[9]);
  167097. cinfo->Y_density = (GETJOCTET(data[10]) << 8) + GETJOCTET(data[11]);
  167098. /* Check version.
  167099. * Major version must be 1, anything else signals an incompatible change.
  167100. * (We used to treat this as an error, but now it's a nonfatal warning,
  167101. * because some bozo at Hijaak couldn't read the spec.)
  167102. * Minor version should be 0..2, but process anyway if newer.
  167103. */
  167104. if (cinfo->JFIF_major_version != 1)
  167105. WARNMS2(cinfo, JWRN_JFIF_MAJOR,
  167106. cinfo->JFIF_major_version, cinfo->JFIF_minor_version);
  167107. /* Generate trace messages */
  167108. TRACEMS5(cinfo, 1, JTRC_JFIF,
  167109. cinfo->JFIF_major_version, cinfo->JFIF_minor_version,
  167110. cinfo->X_density, cinfo->Y_density, cinfo->density_unit);
  167111. /* Validate thumbnail dimensions and issue appropriate messages */
  167112. if (GETJOCTET(data[12]) | GETJOCTET(data[13]))
  167113. TRACEMS2(cinfo, 1, JTRC_JFIF_THUMBNAIL,
  167114. GETJOCTET(data[12]), GETJOCTET(data[13]));
  167115. totallen -= APP0_DATA_LEN;
  167116. if (totallen !=
  167117. ((INT32)GETJOCTET(data[12]) * (INT32)GETJOCTET(data[13]) * (INT32) 3))
  167118. TRACEMS1(cinfo, 1, JTRC_JFIF_BADTHUMBNAILSIZE, (int) totallen);
  167119. } else if (datalen >= 6 &&
  167120. GETJOCTET(data[0]) == 0x4A &&
  167121. GETJOCTET(data[1]) == 0x46 &&
  167122. GETJOCTET(data[2]) == 0x58 &&
  167123. GETJOCTET(data[3]) == 0x58 &&
  167124. GETJOCTET(data[4]) == 0) {
  167125. /* Found JFIF "JFXX" extension APP0 marker */
  167126. /* The library doesn't actually do anything with these,
  167127. * but we try to produce a helpful trace message.
  167128. */
  167129. switch (GETJOCTET(data[5])) {
  167130. case 0x10:
  167131. TRACEMS1(cinfo, 1, JTRC_THUMB_JPEG, (int) totallen);
  167132. break;
  167133. case 0x11:
  167134. TRACEMS1(cinfo, 1, JTRC_THUMB_PALETTE, (int) totallen);
  167135. break;
  167136. case 0x13:
  167137. TRACEMS1(cinfo, 1, JTRC_THUMB_RGB, (int) totallen);
  167138. break;
  167139. default:
  167140. TRACEMS2(cinfo, 1, JTRC_JFIF_EXTENSION,
  167141. GETJOCTET(data[5]), (int) totallen);
  167142. break;
  167143. }
  167144. } else {
  167145. /* Start of APP0 does not match "JFIF" or "JFXX", or too short */
  167146. TRACEMS1(cinfo, 1, JTRC_APP0, (int) totallen);
  167147. }
  167148. }
  167149. LOCAL(void)
  167150. examine_app14 (j_decompress_ptr cinfo, JOCTET FAR * data,
  167151. unsigned int datalen, INT32 remaining)
  167152. /* Examine first few bytes from an APP14.
  167153. * Take appropriate action if it is an Adobe marker.
  167154. * datalen is # of bytes at data[], remaining is length of rest of marker data.
  167155. */
  167156. {
  167157. unsigned int version, flags0, flags1, transform;
  167158. if (datalen >= APP14_DATA_LEN &&
  167159. GETJOCTET(data[0]) == 0x41 &&
  167160. GETJOCTET(data[1]) == 0x64 &&
  167161. GETJOCTET(data[2]) == 0x6F &&
  167162. GETJOCTET(data[3]) == 0x62 &&
  167163. GETJOCTET(data[4]) == 0x65) {
  167164. /* Found Adobe APP14 marker */
  167165. version = (GETJOCTET(data[5]) << 8) + GETJOCTET(data[6]);
  167166. flags0 = (GETJOCTET(data[7]) << 8) + GETJOCTET(data[8]);
  167167. flags1 = (GETJOCTET(data[9]) << 8) + GETJOCTET(data[10]);
  167168. transform = GETJOCTET(data[11]);
  167169. TRACEMS4(cinfo, 1, JTRC_ADOBE, version, flags0, flags1, transform);
  167170. cinfo->saw_Adobe_marker = TRUE;
  167171. cinfo->Adobe_transform = (UINT8) transform;
  167172. } else {
  167173. /* Start of APP14 does not match "Adobe", or too short */
  167174. TRACEMS1(cinfo, 1, JTRC_APP14, (int) (datalen + remaining));
  167175. }
  167176. }
  167177. METHODDEF(boolean)
  167178. get_interesting_appn (j_decompress_ptr cinfo)
  167179. /* Process an APP0 or APP14 marker without saving it */
  167180. {
  167181. INT32 length;
  167182. JOCTET b[APPN_DATA_LEN];
  167183. unsigned int i, numtoread;
  167184. INPUT_VARS(cinfo);
  167185. INPUT_2BYTES(cinfo, length, return FALSE);
  167186. length -= 2;
  167187. /* get the interesting part of the marker data */
  167188. if (length >= APPN_DATA_LEN)
  167189. numtoread = APPN_DATA_LEN;
  167190. else if (length > 0)
  167191. numtoread = (unsigned int) length;
  167192. else
  167193. numtoread = 0;
  167194. for (i = 0; i < numtoread; i++)
  167195. INPUT_BYTE(cinfo, b[i], return FALSE);
  167196. length -= numtoread;
  167197. /* process it */
  167198. switch (cinfo->unread_marker) {
  167199. case M_APP0:
  167200. examine_app0(cinfo, (JOCTET FAR *) b, numtoread, length);
  167201. break;
  167202. case M_APP14:
  167203. examine_app14(cinfo, (JOCTET FAR *) b, numtoread, length);
  167204. break;
  167205. default:
  167206. /* can't get here unless jpeg_save_markers chooses wrong processor */
  167207. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, cinfo->unread_marker);
  167208. break;
  167209. }
  167210. /* skip any remaining data -- could be lots */
  167211. INPUT_SYNC(cinfo);
  167212. if (length > 0)
  167213. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  167214. return TRUE;
  167215. }
  167216. #ifdef SAVE_MARKERS_SUPPORTED
  167217. METHODDEF(boolean)
  167218. save_marker (j_decompress_ptr cinfo)
  167219. /* Save an APPn or COM marker into the marker list */
  167220. {
  167221. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  167222. jpeg_saved_marker_ptr cur_marker = marker->cur_marker;
  167223. unsigned int bytes_read, data_length;
  167224. JOCTET FAR * data;
  167225. INT32 length = 0;
  167226. INPUT_VARS(cinfo);
  167227. if (cur_marker == NULL) {
  167228. /* begin reading a marker */
  167229. INPUT_2BYTES(cinfo, length, return FALSE);
  167230. length -= 2;
  167231. if (length >= 0) { /* watch out for bogus length word */
  167232. /* figure out how much we want to save */
  167233. unsigned int limit;
  167234. if (cinfo->unread_marker == (int) M_COM)
  167235. limit = marker->length_limit_COM;
  167236. else
  167237. limit = marker->length_limit_APPn[cinfo->unread_marker - (int) M_APP0];
  167238. if ((unsigned int) length < limit)
  167239. limit = (unsigned int) length;
  167240. /* allocate and initialize the marker item */
  167241. cur_marker = (jpeg_saved_marker_ptr)
  167242. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167243. SIZEOF(struct jpeg_marker_struct) + limit);
  167244. cur_marker->next = NULL;
  167245. cur_marker->marker = (UINT8) cinfo->unread_marker;
  167246. cur_marker->original_length = (unsigned int) length;
  167247. cur_marker->data_length = limit;
  167248. /* data area is just beyond the jpeg_marker_struct */
  167249. data = cur_marker->data = (JOCTET FAR *) (cur_marker + 1);
  167250. marker->cur_marker = cur_marker;
  167251. marker->bytes_read = 0;
  167252. bytes_read = 0;
  167253. data_length = limit;
  167254. } else {
  167255. /* deal with bogus length word */
  167256. bytes_read = data_length = 0;
  167257. data = NULL;
  167258. }
  167259. } else {
  167260. /* resume reading a marker */
  167261. bytes_read = marker->bytes_read;
  167262. data_length = cur_marker->data_length;
  167263. data = cur_marker->data + bytes_read;
  167264. }
  167265. while (bytes_read < data_length) {
  167266. INPUT_SYNC(cinfo); /* move the restart point to here */
  167267. marker->bytes_read = bytes_read;
  167268. /* If there's not at least one byte in buffer, suspend */
  167269. MAKE_BYTE_AVAIL(cinfo, return FALSE);
  167270. /* Copy bytes with reasonable rapidity */
  167271. while (bytes_read < data_length && bytes_in_buffer > 0) {
  167272. *data++ = *next_input_byte++;
  167273. bytes_in_buffer--;
  167274. bytes_read++;
  167275. }
  167276. }
  167277. /* Done reading what we want to read */
  167278. if (cur_marker != NULL) { /* will be NULL if bogus length word */
  167279. /* Add new marker to end of list */
  167280. if (cinfo->marker_list == NULL) {
  167281. cinfo->marker_list = cur_marker;
  167282. } else {
  167283. jpeg_saved_marker_ptr prev = cinfo->marker_list;
  167284. while (prev->next != NULL)
  167285. prev = prev->next;
  167286. prev->next = cur_marker;
  167287. }
  167288. /* Reset pointer & calc remaining data length */
  167289. data = cur_marker->data;
  167290. length = cur_marker->original_length - data_length;
  167291. }
  167292. /* Reset to initial state for next marker */
  167293. marker->cur_marker = NULL;
  167294. /* Process the marker if interesting; else just make a generic trace msg */
  167295. switch (cinfo->unread_marker) {
  167296. case M_APP0:
  167297. examine_app0(cinfo, data, data_length, length);
  167298. break;
  167299. case M_APP14:
  167300. examine_app14(cinfo, data, data_length, length);
  167301. break;
  167302. default:
  167303. TRACEMS2(cinfo, 1, JTRC_MISC_MARKER, cinfo->unread_marker,
  167304. (int) (data_length + length));
  167305. break;
  167306. }
  167307. /* skip any remaining data -- could be lots */
  167308. INPUT_SYNC(cinfo); /* do before skip_input_data */
  167309. if (length > 0)
  167310. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  167311. return TRUE;
  167312. }
  167313. #endif /* SAVE_MARKERS_SUPPORTED */
  167314. METHODDEF(boolean)
  167315. skip_variable (j_decompress_ptr cinfo)
  167316. /* Skip over an unknown or uninteresting variable-length marker */
  167317. {
  167318. INT32 length;
  167319. INPUT_VARS(cinfo);
  167320. INPUT_2BYTES(cinfo, length, return FALSE);
  167321. length -= 2;
  167322. TRACEMS2(cinfo, 1, JTRC_MISC_MARKER, cinfo->unread_marker, (int) length);
  167323. INPUT_SYNC(cinfo); /* do before skip_input_data */
  167324. if (length > 0)
  167325. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  167326. return TRUE;
  167327. }
  167328. /*
  167329. * Find the next JPEG marker, save it in cinfo->unread_marker.
  167330. * Returns FALSE if had to suspend before reaching a marker;
  167331. * in that case cinfo->unread_marker is unchanged.
  167332. *
  167333. * Note that the result might not be a valid marker code,
  167334. * but it will never be 0 or FF.
  167335. */
  167336. LOCAL(boolean)
  167337. next_marker (j_decompress_ptr cinfo)
  167338. {
  167339. int c;
  167340. INPUT_VARS(cinfo);
  167341. for (;;) {
  167342. INPUT_BYTE(cinfo, c, return FALSE);
  167343. /* Skip any non-FF bytes.
  167344. * This may look a bit inefficient, but it will not occur in a valid file.
  167345. * We sync after each discarded byte so that a suspending data source
  167346. * can discard the byte from its buffer.
  167347. */
  167348. while (c != 0xFF) {
  167349. cinfo->marker->discarded_bytes++;
  167350. INPUT_SYNC(cinfo);
  167351. INPUT_BYTE(cinfo, c, return FALSE);
  167352. }
  167353. /* This loop swallows any duplicate FF bytes. Extra FFs are legal as
  167354. * pad bytes, so don't count them in discarded_bytes. We assume there
  167355. * will not be so many consecutive FF bytes as to overflow a suspending
  167356. * data source's input buffer.
  167357. */
  167358. do {
  167359. INPUT_BYTE(cinfo, c, return FALSE);
  167360. } while (c == 0xFF);
  167361. if (c != 0)
  167362. break; /* found a valid marker, exit loop */
  167363. /* Reach here if we found a stuffed-zero data sequence (FF/00).
  167364. * Discard it and loop back to try again.
  167365. */
  167366. cinfo->marker->discarded_bytes += 2;
  167367. INPUT_SYNC(cinfo);
  167368. }
  167369. if (cinfo->marker->discarded_bytes != 0) {
  167370. WARNMS2(cinfo, JWRN_EXTRANEOUS_DATA, cinfo->marker->discarded_bytes, c);
  167371. cinfo->marker->discarded_bytes = 0;
  167372. }
  167373. cinfo->unread_marker = c;
  167374. INPUT_SYNC(cinfo);
  167375. return TRUE;
  167376. }
  167377. LOCAL(boolean)
  167378. first_marker (j_decompress_ptr cinfo)
  167379. /* Like next_marker, but used to obtain the initial SOI marker. */
  167380. /* For this marker, we do not allow preceding garbage or fill; otherwise,
  167381. * we might well scan an entire input file before realizing it ain't JPEG.
  167382. * If an application wants to process non-JFIF files, it must seek to the
  167383. * SOI before calling the JPEG library.
  167384. */
  167385. {
  167386. int c, c2;
  167387. INPUT_VARS(cinfo);
  167388. INPUT_BYTE(cinfo, c, return FALSE);
  167389. INPUT_BYTE(cinfo, c2, return FALSE);
  167390. if (c != 0xFF || c2 != (int) M_SOI)
  167391. ERREXIT2(cinfo, JERR_NO_SOI, c, c2);
  167392. cinfo->unread_marker = c2;
  167393. INPUT_SYNC(cinfo);
  167394. return TRUE;
  167395. }
  167396. /*
  167397. * Read markers until SOS or EOI.
  167398. *
  167399. * Returns same codes as are defined for jpeg_consume_input:
  167400. * JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  167401. */
  167402. METHODDEF(int)
  167403. read_markers (j_decompress_ptr cinfo)
  167404. {
  167405. /* Outer loop repeats once for each marker. */
  167406. for (;;) {
  167407. /* Collect the marker proper, unless we already did. */
  167408. /* NB: first_marker() enforces the requirement that SOI appear first. */
  167409. if (cinfo->unread_marker == 0) {
  167410. if (! cinfo->marker->saw_SOI) {
  167411. if (! first_marker(cinfo))
  167412. return JPEG_SUSPENDED;
  167413. } else {
  167414. if (! next_marker(cinfo))
  167415. return JPEG_SUSPENDED;
  167416. }
  167417. }
  167418. /* At this point cinfo->unread_marker contains the marker code and the
  167419. * input point is just past the marker proper, but before any parameters.
  167420. * A suspension will cause us to return with this state still true.
  167421. */
  167422. switch (cinfo->unread_marker) {
  167423. case M_SOI:
  167424. if (! get_soi(cinfo))
  167425. return JPEG_SUSPENDED;
  167426. break;
  167427. case M_SOF0: /* Baseline */
  167428. case M_SOF1: /* Extended sequential, Huffman */
  167429. if (! get_sof(cinfo, FALSE, FALSE))
  167430. return JPEG_SUSPENDED;
  167431. break;
  167432. case M_SOF2: /* Progressive, Huffman */
  167433. if (! get_sof(cinfo, TRUE, FALSE))
  167434. return JPEG_SUSPENDED;
  167435. break;
  167436. case M_SOF9: /* Extended sequential, arithmetic */
  167437. if (! get_sof(cinfo, FALSE, TRUE))
  167438. return JPEG_SUSPENDED;
  167439. break;
  167440. case M_SOF10: /* Progressive, arithmetic */
  167441. if (! get_sof(cinfo, TRUE, TRUE))
  167442. return JPEG_SUSPENDED;
  167443. break;
  167444. /* Currently unsupported SOFn types */
  167445. case M_SOF3: /* Lossless, Huffman */
  167446. case M_SOF5: /* Differential sequential, Huffman */
  167447. case M_SOF6: /* Differential progressive, Huffman */
  167448. case M_SOF7: /* Differential lossless, Huffman */
  167449. case M_JPG: /* Reserved for JPEG extensions */
  167450. case M_SOF11: /* Lossless, arithmetic */
  167451. case M_SOF13: /* Differential sequential, arithmetic */
  167452. case M_SOF14: /* Differential progressive, arithmetic */
  167453. case M_SOF15: /* Differential lossless, arithmetic */
  167454. ERREXIT1(cinfo, JERR_SOF_UNSUPPORTED, cinfo->unread_marker);
  167455. break;
  167456. case M_SOS:
  167457. if (! get_sos(cinfo))
  167458. return JPEG_SUSPENDED;
  167459. cinfo->unread_marker = 0; /* processed the marker */
  167460. return JPEG_REACHED_SOS;
  167461. case M_EOI:
  167462. TRACEMS(cinfo, 1, JTRC_EOI);
  167463. cinfo->unread_marker = 0; /* processed the marker */
  167464. return JPEG_REACHED_EOI;
  167465. case M_DAC:
  167466. if (! get_dac(cinfo))
  167467. return JPEG_SUSPENDED;
  167468. break;
  167469. case M_DHT:
  167470. if (! get_dht(cinfo))
  167471. return JPEG_SUSPENDED;
  167472. break;
  167473. case M_DQT:
  167474. if (! get_dqt(cinfo))
  167475. return JPEG_SUSPENDED;
  167476. break;
  167477. case M_DRI:
  167478. if (! get_dri(cinfo))
  167479. return JPEG_SUSPENDED;
  167480. break;
  167481. case M_APP0:
  167482. case M_APP1:
  167483. case M_APP2:
  167484. case M_APP3:
  167485. case M_APP4:
  167486. case M_APP5:
  167487. case M_APP6:
  167488. case M_APP7:
  167489. case M_APP8:
  167490. case M_APP9:
  167491. case M_APP10:
  167492. case M_APP11:
  167493. case M_APP12:
  167494. case M_APP13:
  167495. case M_APP14:
  167496. case M_APP15:
  167497. if (! (*((my_marker_ptr2) cinfo->marker)->process_APPn[
  167498. cinfo->unread_marker - (int) M_APP0]) (cinfo))
  167499. return JPEG_SUSPENDED;
  167500. break;
  167501. case M_COM:
  167502. if (! (*((my_marker_ptr2) cinfo->marker)->process_COM) (cinfo))
  167503. return JPEG_SUSPENDED;
  167504. break;
  167505. case M_RST0: /* these are all parameterless */
  167506. case M_RST1:
  167507. case M_RST2:
  167508. case M_RST3:
  167509. case M_RST4:
  167510. case M_RST5:
  167511. case M_RST6:
  167512. case M_RST7:
  167513. case M_TEM:
  167514. TRACEMS1(cinfo, 1, JTRC_PARMLESS_MARKER, cinfo->unread_marker);
  167515. break;
  167516. case M_DNL: /* Ignore DNL ... perhaps the wrong thing */
  167517. if (! skip_variable(cinfo))
  167518. return JPEG_SUSPENDED;
  167519. break;
  167520. default: /* must be DHP, EXP, JPGn, or RESn */
  167521. /* For now, we treat the reserved markers as fatal errors since they are
  167522. * likely to be used to signal incompatible JPEG Part 3 extensions.
  167523. * Once the JPEG 3 version-number marker is well defined, this code
  167524. * ought to change!
  167525. */
  167526. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, cinfo->unread_marker);
  167527. break;
  167528. }
  167529. /* Successfully processed marker, so reset state variable */
  167530. cinfo->unread_marker = 0;
  167531. } /* end loop */
  167532. }
  167533. /*
  167534. * Read a restart marker, which is expected to appear next in the datastream;
  167535. * if the marker is not there, take appropriate recovery action.
  167536. * Returns FALSE if suspension is required.
  167537. *
  167538. * This is called by the entropy decoder after it has read an appropriate
  167539. * number of MCUs. cinfo->unread_marker may be nonzero if the entropy decoder
  167540. * has already read a marker from the data source. Under normal conditions
  167541. * cinfo->unread_marker will be reset to 0 before returning; if not reset,
  167542. * it holds a marker which the decoder will be unable to read past.
  167543. */
  167544. METHODDEF(boolean)
  167545. read_restart_marker (j_decompress_ptr cinfo)
  167546. {
  167547. /* Obtain a marker unless we already did. */
  167548. /* Note that next_marker will complain if it skips any data. */
  167549. if (cinfo->unread_marker == 0) {
  167550. if (! next_marker(cinfo))
  167551. return FALSE;
  167552. }
  167553. if (cinfo->unread_marker ==
  167554. ((int) M_RST0 + cinfo->marker->next_restart_num)) {
  167555. /* Normal case --- swallow the marker and let entropy decoder continue */
  167556. TRACEMS1(cinfo, 3, JTRC_RST, cinfo->marker->next_restart_num);
  167557. cinfo->unread_marker = 0;
  167558. } else {
  167559. /* Uh-oh, the restart markers have been messed up. */
  167560. /* Let the data source manager determine how to resync. */
  167561. if (! (*cinfo->src->resync_to_restart) (cinfo,
  167562. cinfo->marker->next_restart_num))
  167563. return FALSE;
  167564. }
  167565. /* Update next-restart state */
  167566. cinfo->marker->next_restart_num = (cinfo->marker->next_restart_num + 1) & 7;
  167567. return TRUE;
  167568. }
  167569. /*
  167570. * This is the default resync_to_restart method for data source managers
  167571. * to use if they don't have any better approach. Some data source managers
  167572. * may be able to back up, or may have additional knowledge about the data
  167573. * which permits a more intelligent recovery strategy; such managers would
  167574. * presumably supply their own resync method.
  167575. *
  167576. * read_restart_marker calls resync_to_restart if it finds a marker other than
  167577. * the restart marker it was expecting. (This code is *not* used unless
  167578. * a nonzero restart interval has been declared.) cinfo->unread_marker is
  167579. * the marker code actually found (might be anything, except 0 or FF).
  167580. * The desired restart marker number (0..7) is passed as a parameter.
  167581. * This routine is supposed to apply whatever error recovery strategy seems
  167582. * appropriate in order to position the input stream to the next data segment.
  167583. * Note that cinfo->unread_marker is treated as a marker appearing before
  167584. * the current data-source input point; usually it should be reset to zero
  167585. * before returning.
  167586. * Returns FALSE if suspension is required.
  167587. *
  167588. * This implementation is substantially constrained by wanting to treat the
  167589. * input as a data stream; this means we can't back up. Therefore, we have
  167590. * only the following actions to work with:
  167591. * 1. Simply discard the marker and let the entropy decoder resume at next
  167592. * byte of file.
  167593. * 2. Read forward until we find another marker, discarding intervening
  167594. * data. (In theory we could look ahead within the current bufferload,
  167595. * without having to discard data if we don't find the desired marker.
  167596. * This idea is not implemented here, in part because it makes behavior
  167597. * dependent on buffer size and chance buffer-boundary positions.)
  167598. * 3. Leave the marker unread (by failing to zero cinfo->unread_marker).
  167599. * This will cause the entropy decoder to process an empty data segment,
  167600. * inserting dummy zeroes, and then we will reprocess the marker.
  167601. *
  167602. * #2 is appropriate if we think the desired marker lies ahead, while #3 is
  167603. * appropriate if the found marker is a future restart marker (indicating
  167604. * that we have missed the desired restart marker, probably because it got
  167605. * corrupted).
  167606. * We apply #2 or #3 if the found marker is a restart marker no more than
  167607. * two counts behind or ahead of the expected one. We also apply #2 if the
  167608. * found marker is not a legal JPEG marker code (it's certainly bogus data).
  167609. * If the found marker is a restart marker more than 2 counts away, we do #1
  167610. * (too much risk that the marker is erroneous; with luck we will be able to
  167611. * resync at some future point).
  167612. * For any valid non-restart JPEG marker, we apply #3. This keeps us from
  167613. * overrunning the end of a scan. An implementation limited to single-scan
  167614. * files might find it better to apply #2 for markers other than EOI, since
  167615. * any other marker would have to be bogus data in that case.
  167616. */
  167617. GLOBAL(boolean)
  167618. jpeg_resync_to_restart (j_decompress_ptr cinfo, int desired)
  167619. {
  167620. int marker = cinfo->unread_marker;
  167621. int action = 1;
  167622. /* Always put up a warning. */
  167623. WARNMS2(cinfo, JWRN_MUST_RESYNC, marker, desired);
  167624. /* Outer loop handles repeated decision after scanning forward. */
  167625. for (;;) {
  167626. if (marker < (int) M_SOF0)
  167627. action = 2; /* invalid marker */
  167628. else if (marker < (int) M_RST0 || marker > (int) M_RST7)
  167629. action = 3; /* valid non-restart marker */
  167630. else {
  167631. if (marker == ((int) M_RST0 + ((desired+1) & 7)) ||
  167632. marker == ((int) M_RST0 + ((desired+2) & 7)))
  167633. action = 3; /* one of the next two expected restarts */
  167634. else if (marker == ((int) M_RST0 + ((desired-1) & 7)) ||
  167635. marker == ((int) M_RST0 + ((desired-2) & 7)))
  167636. action = 2; /* a prior restart, so advance */
  167637. else
  167638. action = 1; /* desired restart or too far away */
  167639. }
  167640. TRACEMS2(cinfo, 4, JTRC_RECOVERY_ACTION, marker, action);
  167641. switch (action) {
  167642. case 1:
  167643. /* Discard marker and let entropy decoder resume processing. */
  167644. cinfo->unread_marker = 0;
  167645. return TRUE;
  167646. case 2:
  167647. /* Scan to the next marker, and repeat the decision loop. */
  167648. if (! next_marker(cinfo))
  167649. return FALSE;
  167650. marker = cinfo->unread_marker;
  167651. break;
  167652. case 3:
  167653. /* Return without advancing past this marker. */
  167654. /* Entropy decoder will be forced to process an empty segment. */
  167655. return TRUE;
  167656. }
  167657. } /* end loop */
  167658. }
  167659. /*
  167660. * Reset marker processing state to begin a fresh datastream.
  167661. */
  167662. METHODDEF(void)
  167663. reset_marker_reader (j_decompress_ptr cinfo)
  167664. {
  167665. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  167666. cinfo->comp_info = NULL; /* until allocated by get_sof */
  167667. cinfo->input_scan_number = 0; /* no SOS seen yet */
  167668. cinfo->unread_marker = 0; /* no pending marker */
  167669. marker->pub.saw_SOI = FALSE; /* set internal state too */
  167670. marker->pub.saw_SOF = FALSE;
  167671. marker->pub.discarded_bytes = 0;
  167672. marker->cur_marker = NULL;
  167673. }
  167674. /*
  167675. * Initialize the marker reader module.
  167676. * This is called only once, when the decompression object is created.
  167677. */
  167678. GLOBAL(void)
  167679. jinit_marker_reader (j_decompress_ptr cinfo)
  167680. {
  167681. my_marker_ptr2 marker;
  167682. int i;
  167683. /* Create subobject in permanent pool */
  167684. marker = (my_marker_ptr2)
  167685. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  167686. SIZEOF(my_marker_reader));
  167687. cinfo->marker = (struct jpeg_marker_reader *) marker;
  167688. /* Initialize public method pointers */
  167689. marker->pub.reset_marker_reader = reset_marker_reader;
  167690. marker->pub.read_markers = read_markers;
  167691. marker->pub.read_restart_marker = read_restart_marker;
  167692. /* Initialize COM/APPn processing.
  167693. * By default, we examine and then discard APP0 and APP14,
  167694. * but simply discard COM and all other APPn.
  167695. */
  167696. marker->process_COM = skip_variable;
  167697. marker->length_limit_COM = 0;
  167698. for (i = 0; i < 16; i++) {
  167699. marker->process_APPn[i] = skip_variable;
  167700. marker->length_limit_APPn[i] = 0;
  167701. }
  167702. marker->process_APPn[0] = get_interesting_appn;
  167703. marker->process_APPn[14] = get_interesting_appn;
  167704. /* Reset marker processing state */
  167705. reset_marker_reader(cinfo);
  167706. }
  167707. /*
  167708. * Control saving of COM and APPn markers into marker_list.
  167709. */
  167710. #ifdef SAVE_MARKERS_SUPPORTED
  167711. GLOBAL(void)
  167712. jpeg_save_markers (j_decompress_ptr cinfo, int marker_code,
  167713. unsigned int length_limit)
  167714. {
  167715. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  167716. long maxlength;
  167717. jpeg_marker_parser_method processor;
  167718. /* Length limit mustn't be larger than what we can allocate
  167719. * (should only be a concern in a 16-bit environment).
  167720. */
  167721. maxlength = cinfo->mem->max_alloc_chunk - SIZEOF(struct jpeg_marker_struct);
  167722. if (((long) length_limit) > maxlength)
  167723. length_limit = (unsigned int) maxlength;
  167724. /* Choose processor routine to use.
  167725. * APP0/APP14 have special requirements.
  167726. */
  167727. if (length_limit) {
  167728. processor = save_marker;
  167729. /* If saving APP0/APP14, save at least enough for our internal use. */
  167730. if (marker_code == (int) M_APP0 && length_limit < APP0_DATA_LEN)
  167731. length_limit = APP0_DATA_LEN;
  167732. else if (marker_code == (int) M_APP14 && length_limit < APP14_DATA_LEN)
  167733. length_limit = APP14_DATA_LEN;
  167734. } else {
  167735. processor = skip_variable;
  167736. /* If discarding APP0/APP14, use our regular on-the-fly processor. */
  167737. if (marker_code == (int) M_APP0 || marker_code == (int) M_APP14)
  167738. processor = get_interesting_appn;
  167739. }
  167740. if (marker_code == (int) M_COM) {
  167741. marker->process_COM = processor;
  167742. marker->length_limit_COM = length_limit;
  167743. } else if (marker_code >= (int) M_APP0 && marker_code <= (int) M_APP15) {
  167744. marker->process_APPn[marker_code - (int) M_APP0] = processor;
  167745. marker->length_limit_APPn[marker_code - (int) M_APP0] = length_limit;
  167746. } else
  167747. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, marker_code);
  167748. }
  167749. #endif /* SAVE_MARKERS_SUPPORTED */
  167750. /*
  167751. * Install a special processing method for COM or APPn markers.
  167752. */
  167753. GLOBAL(void)
  167754. jpeg_set_marker_processor (j_decompress_ptr cinfo, int marker_code,
  167755. jpeg_marker_parser_method routine)
  167756. {
  167757. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  167758. if (marker_code == (int) M_COM)
  167759. marker->process_COM = routine;
  167760. else if (marker_code >= (int) M_APP0 && marker_code <= (int) M_APP15)
  167761. marker->process_APPn[marker_code - (int) M_APP0] = routine;
  167762. else
  167763. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, marker_code);
  167764. }
  167765. /********* End of inlined file: jdmarker.c *********/
  167766. /********* Start of inlined file: jdmaster.c *********/
  167767. #define JPEG_INTERNALS
  167768. /* Private state */
  167769. typedef struct {
  167770. struct jpeg_decomp_master pub; /* public fields */
  167771. int pass_number; /* # of passes completed */
  167772. boolean using_merged_upsample; /* TRUE if using merged upsample/cconvert */
  167773. /* Saved references to initialized quantizer modules,
  167774. * in case we need to switch modes.
  167775. */
  167776. struct jpeg_color_quantizer * quantizer_1pass;
  167777. struct jpeg_color_quantizer * quantizer_2pass;
  167778. } my_decomp_master;
  167779. typedef my_decomp_master * my_master_ptr6;
  167780. /*
  167781. * Determine whether merged upsample/color conversion should be used.
  167782. * CRUCIAL: this must match the actual capabilities of jdmerge.c!
  167783. */
  167784. LOCAL(boolean)
  167785. use_merged_upsample (j_decompress_ptr cinfo)
  167786. {
  167787. #ifdef UPSAMPLE_MERGING_SUPPORTED
  167788. /* Merging is the equivalent of plain box-filter upsampling */
  167789. if (cinfo->do_fancy_upsampling || cinfo->CCIR601_sampling)
  167790. return FALSE;
  167791. /* jdmerge.c only supports YCC=>RGB color conversion */
  167792. if (cinfo->jpeg_color_space != JCS_YCbCr || cinfo->num_components != 3 ||
  167793. cinfo->out_color_space != JCS_RGB ||
  167794. cinfo->out_color_components != RGB_PIXELSIZE)
  167795. return FALSE;
  167796. /* and it only handles 2h1v or 2h2v sampling ratios */
  167797. if (cinfo->comp_info[0].h_samp_factor != 2 ||
  167798. cinfo->comp_info[1].h_samp_factor != 1 ||
  167799. cinfo->comp_info[2].h_samp_factor != 1 ||
  167800. cinfo->comp_info[0].v_samp_factor > 2 ||
  167801. cinfo->comp_info[1].v_samp_factor != 1 ||
  167802. cinfo->comp_info[2].v_samp_factor != 1)
  167803. return FALSE;
  167804. /* furthermore, it doesn't work if we've scaled the IDCTs differently */
  167805. if (cinfo->comp_info[0].DCT_scaled_size != cinfo->min_DCT_scaled_size ||
  167806. cinfo->comp_info[1].DCT_scaled_size != cinfo->min_DCT_scaled_size ||
  167807. cinfo->comp_info[2].DCT_scaled_size != cinfo->min_DCT_scaled_size)
  167808. return FALSE;
  167809. /* ??? also need to test for upsample-time rescaling, when & if supported */
  167810. return TRUE; /* by golly, it'll work... */
  167811. #else
  167812. return FALSE;
  167813. #endif
  167814. }
  167815. /*
  167816. * Compute output image dimensions and related values.
  167817. * NOTE: this is exported for possible use by application.
  167818. * Hence it mustn't do anything that can't be done twice.
  167819. * Also note that it may be called before the master module is initialized!
  167820. */
  167821. GLOBAL(void)
  167822. jpeg_calc_output_dimensions (j_decompress_ptr cinfo)
  167823. /* Do computations that are needed before master selection phase */
  167824. {
  167825. #ifdef IDCT_SCALING_SUPPORTED
  167826. int ci;
  167827. jpeg_component_info *compptr;
  167828. #endif
  167829. /* Prevent application from calling me at wrong times */
  167830. if (cinfo->global_state != DSTATE_READY)
  167831. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167832. #ifdef IDCT_SCALING_SUPPORTED
  167833. /* Compute actual output image dimensions and DCT scaling choices. */
  167834. if (cinfo->scale_num * 8 <= cinfo->scale_denom) {
  167835. /* Provide 1/8 scaling */
  167836. cinfo->output_width = (JDIMENSION)
  167837. jdiv_round_up((long) cinfo->image_width, 8L);
  167838. cinfo->output_height = (JDIMENSION)
  167839. jdiv_round_up((long) cinfo->image_height, 8L);
  167840. cinfo->min_DCT_scaled_size = 1;
  167841. } else if (cinfo->scale_num * 4 <= cinfo->scale_denom) {
  167842. /* Provide 1/4 scaling */
  167843. cinfo->output_width = (JDIMENSION)
  167844. jdiv_round_up((long) cinfo->image_width, 4L);
  167845. cinfo->output_height = (JDIMENSION)
  167846. jdiv_round_up((long) cinfo->image_height, 4L);
  167847. cinfo->min_DCT_scaled_size = 2;
  167848. } else if (cinfo->scale_num * 2 <= cinfo->scale_denom) {
  167849. /* Provide 1/2 scaling */
  167850. cinfo->output_width = (JDIMENSION)
  167851. jdiv_round_up((long) cinfo->image_width, 2L);
  167852. cinfo->output_height = (JDIMENSION)
  167853. jdiv_round_up((long) cinfo->image_height, 2L);
  167854. cinfo->min_DCT_scaled_size = 4;
  167855. } else {
  167856. /* Provide 1/1 scaling */
  167857. cinfo->output_width = cinfo->image_width;
  167858. cinfo->output_height = cinfo->image_height;
  167859. cinfo->min_DCT_scaled_size = DCTSIZE;
  167860. }
  167861. /* In selecting the actual DCT scaling for each component, we try to
  167862. * scale up the chroma components via IDCT scaling rather than upsampling.
  167863. * This saves time if the upsampler gets to use 1:1 scaling.
  167864. * Note this code assumes that the supported DCT scalings are powers of 2.
  167865. */
  167866. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  167867. ci++, compptr++) {
  167868. int ssize = cinfo->min_DCT_scaled_size;
  167869. while (ssize < DCTSIZE &&
  167870. (compptr->h_samp_factor * ssize * 2 <=
  167871. cinfo->max_h_samp_factor * cinfo->min_DCT_scaled_size) &&
  167872. (compptr->v_samp_factor * ssize * 2 <=
  167873. cinfo->max_v_samp_factor * cinfo->min_DCT_scaled_size)) {
  167874. ssize = ssize * 2;
  167875. }
  167876. compptr->DCT_scaled_size = ssize;
  167877. }
  167878. /* Recompute downsampled dimensions of components;
  167879. * application needs to know these if using raw downsampled data.
  167880. */
  167881. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  167882. ci++, compptr++) {
  167883. /* Size in samples, after IDCT scaling */
  167884. compptr->downsampled_width = (JDIMENSION)
  167885. jdiv_round_up((long) cinfo->image_width *
  167886. (long) (compptr->h_samp_factor * compptr->DCT_scaled_size),
  167887. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  167888. compptr->downsampled_height = (JDIMENSION)
  167889. jdiv_round_up((long) cinfo->image_height *
  167890. (long) (compptr->v_samp_factor * compptr->DCT_scaled_size),
  167891. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  167892. }
  167893. #else /* !IDCT_SCALING_SUPPORTED */
  167894. /* Hardwire it to "no scaling" */
  167895. cinfo->output_width = cinfo->image_width;
  167896. cinfo->output_height = cinfo->image_height;
  167897. /* jdinput.c has already initialized DCT_scaled_size to DCTSIZE,
  167898. * and has computed unscaled downsampled_width and downsampled_height.
  167899. */
  167900. #endif /* IDCT_SCALING_SUPPORTED */
  167901. /* Report number of components in selected colorspace. */
  167902. /* Probably this should be in the color conversion module... */
  167903. switch (cinfo->out_color_space) {
  167904. case JCS_GRAYSCALE:
  167905. cinfo->out_color_components = 1;
  167906. break;
  167907. case JCS_RGB:
  167908. #if RGB_PIXELSIZE != 3
  167909. cinfo->out_color_components = RGB_PIXELSIZE;
  167910. break;
  167911. #endif /* else share code with YCbCr */
  167912. case JCS_YCbCr:
  167913. cinfo->out_color_components = 3;
  167914. break;
  167915. case JCS_CMYK:
  167916. case JCS_YCCK:
  167917. cinfo->out_color_components = 4;
  167918. break;
  167919. default: /* else must be same colorspace as in file */
  167920. cinfo->out_color_components = cinfo->num_components;
  167921. break;
  167922. }
  167923. cinfo->output_components = (cinfo->quantize_colors ? 1 :
  167924. cinfo->out_color_components);
  167925. /* See if upsampler will want to emit more than one row at a time */
  167926. if (use_merged_upsample(cinfo))
  167927. cinfo->rec_outbuf_height = cinfo->max_v_samp_factor;
  167928. else
  167929. cinfo->rec_outbuf_height = 1;
  167930. }
  167931. /*
  167932. * Several decompression processes need to range-limit values to the range
  167933. * 0..MAXJSAMPLE; the input value may fall somewhat outside this range
  167934. * due to noise introduced by quantization, roundoff error, etc. These
  167935. * processes are inner loops and need to be as fast as possible. On most
  167936. * machines, particularly CPUs with pipelines or instruction prefetch,
  167937. * a (subscript-check-less) C table lookup
  167938. * x = sample_range_limit[x];
  167939. * is faster than explicit tests
  167940. * if (x < 0) x = 0;
  167941. * else if (x > MAXJSAMPLE) x = MAXJSAMPLE;
  167942. * These processes all use a common table prepared by the routine below.
  167943. *
  167944. * For most steps we can mathematically guarantee that the initial value
  167945. * of x is within MAXJSAMPLE+1 of the legal range, so a table running from
  167946. * -(MAXJSAMPLE+1) to 2*MAXJSAMPLE+1 is sufficient. But for the initial
  167947. * limiting step (just after the IDCT), a wildly out-of-range value is
  167948. * possible if the input data is corrupt. To avoid any chance of indexing
  167949. * off the end of memory and getting a bad-pointer trap, we perform the
  167950. * post-IDCT limiting thus:
  167951. * x = range_limit[x & MASK];
  167952. * where MASK is 2 bits wider than legal sample data, ie 10 bits for 8-bit
  167953. * samples. Under normal circumstances this is more than enough range and
  167954. * a correct output will be generated; with bogus input data the mask will
  167955. * cause wraparound, and we will safely generate a bogus-but-in-range output.
  167956. * For the post-IDCT step, we want to convert the data from signed to unsigned
  167957. * representation by adding CENTERJSAMPLE at the same time that we limit it.
  167958. * So the post-IDCT limiting table ends up looking like this:
  167959. * CENTERJSAMPLE,CENTERJSAMPLE+1,...,MAXJSAMPLE,
  167960. * MAXJSAMPLE (repeat 2*(MAXJSAMPLE+1)-CENTERJSAMPLE times),
  167961. * 0 (repeat 2*(MAXJSAMPLE+1)-CENTERJSAMPLE times),
  167962. * 0,1,...,CENTERJSAMPLE-1
  167963. * Negative inputs select values from the upper half of the table after
  167964. * masking.
  167965. *
  167966. * We can save some space by overlapping the start of the post-IDCT table
  167967. * with the simpler range limiting table. The post-IDCT table begins at
  167968. * sample_range_limit + CENTERJSAMPLE.
  167969. *
  167970. * Note that the table is allocated in near data space on PCs; it's small
  167971. * enough and used often enough to justify this.
  167972. */
  167973. LOCAL(void)
  167974. prepare_range_limit_table (j_decompress_ptr cinfo)
  167975. /* Allocate and fill in the sample_range_limit table */
  167976. {
  167977. JSAMPLE * table;
  167978. int i;
  167979. table = (JSAMPLE *)
  167980. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167981. (5 * (MAXJSAMPLE+1) + CENTERJSAMPLE) * SIZEOF(JSAMPLE));
  167982. table += (MAXJSAMPLE+1); /* allow negative subscripts of simple table */
  167983. cinfo->sample_range_limit = table;
  167984. /* First segment of "simple" table: limit[x] = 0 for x < 0 */
  167985. MEMZERO(table - (MAXJSAMPLE+1), (MAXJSAMPLE+1) * SIZEOF(JSAMPLE));
  167986. /* Main part of "simple" table: limit[x] = x */
  167987. for (i = 0; i <= MAXJSAMPLE; i++)
  167988. table[i] = (JSAMPLE) i;
  167989. table += CENTERJSAMPLE; /* Point to where post-IDCT table starts */
  167990. /* End of simple table, rest of first half of post-IDCT table */
  167991. for (i = CENTERJSAMPLE; i < 2*(MAXJSAMPLE+1); i++)
  167992. table[i] = MAXJSAMPLE;
  167993. /* Second half of post-IDCT table */
  167994. MEMZERO(table + (2 * (MAXJSAMPLE+1)),
  167995. (2 * (MAXJSAMPLE+1) - CENTERJSAMPLE) * SIZEOF(JSAMPLE));
  167996. MEMCOPY(table + (4 * (MAXJSAMPLE+1) - CENTERJSAMPLE),
  167997. cinfo->sample_range_limit, CENTERJSAMPLE * SIZEOF(JSAMPLE));
  167998. }
  167999. /*
  168000. * Master selection of decompression modules.
  168001. * This is done once at jpeg_start_decompress time. We determine
  168002. * which modules will be used and give them appropriate initialization calls.
  168003. * We also initialize the decompressor input side to begin consuming data.
  168004. *
  168005. * Since jpeg_read_header has finished, we know what is in the SOF
  168006. * and (first) SOS markers. We also have all the application parameter
  168007. * settings.
  168008. */
  168009. LOCAL(void)
  168010. master_selection (j_decompress_ptr cinfo)
  168011. {
  168012. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  168013. boolean use_c_buffer;
  168014. long samplesperrow;
  168015. JDIMENSION jd_samplesperrow;
  168016. /* Initialize dimensions and other stuff */
  168017. jpeg_calc_output_dimensions(cinfo);
  168018. prepare_range_limit_table(cinfo);
  168019. /* Width of an output scanline must be representable as JDIMENSION. */
  168020. samplesperrow = (long) cinfo->output_width * (long) cinfo->out_color_components;
  168021. jd_samplesperrow = (JDIMENSION) samplesperrow;
  168022. if ((long) jd_samplesperrow != samplesperrow)
  168023. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  168024. /* Initialize my private state */
  168025. master->pass_number = 0;
  168026. master->using_merged_upsample = use_merged_upsample(cinfo);
  168027. /* Color quantizer selection */
  168028. master->quantizer_1pass = NULL;
  168029. master->quantizer_2pass = NULL;
  168030. /* No mode changes if not using buffered-image mode. */
  168031. if (! cinfo->quantize_colors || ! cinfo->buffered_image) {
  168032. cinfo->enable_1pass_quant = FALSE;
  168033. cinfo->enable_external_quant = FALSE;
  168034. cinfo->enable_2pass_quant = FALSE;
  168035. }
  168036. if (cinfo->quantize_colors) {
  168037. if (cinfo->raw_data_out)
  168038. ERREXIT(cinfo, JERR_NOTIMPL);
  168039. /* 2-pass quantizer only works in 3-component color space. */
  168040. if (cinfo->out_color_components != 3) {
  168041. cinfo->enable_1pass_quant = TRUE;
  168042. cinfo->enable_external_quant = FALSE;
  168043. cinfo->enable_2pass_quant = FALSE;
  168044. cinfo->colormap = NULL;
  168045. } else if (cinfo->colormap != NULL) {
  168046. cinfo->enable_external_quant = TRUE;
  168047. } else if (cinfo->two_pass_quantize) {
  168048. cinfo->enable_2pass_quant = TRUE;
  168049. } else {
  168050. cinfo->enable_1pass_quant = TRUE;
  168051. }
  168052. if (cinfo->enable_1pass_quant) {
  168053. #ifdef QUANT_1PASS_SUPPORTED
  168054. jinit_1pass_quantizer(cinfo);
  168055. master->quantizer_1pass = cinfo->cquantize;
  168056. #else
  168057. ERREXIT(cinfo, JERR_NOT_COMPILED);
  168058. #endif
  168059. }
  168060. /* We use the 2-pass code to map to external colormaps. */
  168061. if (cinfo->enable_2pass_quant || cinfo->enable_external_quant) {
  168062. #ifdef QUANT_2PASS_SUPPORTED
  168063. jinit_2pass_quantizer(cinfo);
  168064. master->quantizer_2pass = cinfo->cquantize;
  168065. #else
  168066. ERREXIT(cinfo, JERR_NOT_COMPILED);
  168067. #endif
  168068. }
  168069. /* If both quantizers are initialized, the 2-pass one is left active;
  168070. * this is necessary for starting with quantization to an external map.
  168071. */
  168072. }
  168073. /* Post-processing: in particular, color conversion first */
  168074. if (! cinfo->raw_data_out) {
  168075. if (master->using_merged_upsample) {
  168076. #ifdef UPSAMPLE_MERGING_SUPPORTED
  168077. jinit_merged_upsampler(cinfo); /* does color conversion too */
  168078. #else
  168079. ERREXIT(cinfo, JERR_NOT_COMPILED);
  168080. #endif
  168081. } else {
  168082. jinit_color_deconverter(cinfo);
  168083. jinit_upsampler(cinfo);
  168084. }
  168085. jinit_d_post_controller(cinfo, cinfo->enable_2pass_quant);
  168086. }
  168087. /* Inverse DCT */
  168088. jinit_inverse_dct(cinfo);
  168089. /* Entropy decoding: either Huffman or arithmetic coding. */
  168090. if (cinfo->arith_code) {
  168091. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  168092. } else {
  168093. if (cinfo->progressive_mode) {
  168094. #ifdef D_PROGRESSIVE_SUPPORTED
  168095. jinit_phuff_decoder(cinfo);
  168096. #else
  168097. ERREXIT(cinfo, JERR_NOT_COMPILED);
  168098. #endif
  168099. } else
  168100. jinit_huff_decoder(cinfo);
  168101. }
  168102. /* Initialize principal buffer controllers. */
  168103. use_c_buffer = cinfo->inputctl->has_multiple_scans || cinfo->buffered_image;
  168104. jinit_d_coef_controller(cinfo, use_c_buffer);
  168105. if (! cinfo->raw_data_out)
  168106. jinit_d_main_controller(cinfo, FALSE /* never need full buffer here */);
  168107. /* We can now tell the memory manager to allocate virtual arrays. */
  168108. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  168109. /* Initialize input side of decompressor to consume first scan. */
  168110. (*cinfo->inputctl->start_input_pass) (cinfo);
  168111. #ifdef D_MULTISCAN_FILES_SUPPORTED
  168112. /* If jpeg_start_decompress will read the whole file, initialize
  168113. * progress monitoring appropriately. The input step is counted
  168114. * as one pass.
  168115. */
  168116. if (cinfo->progress != NULL && ! cinfo->buffered_image &&
  168117. cinfo->inputctl->has_multiple_scans) {
  168118. int nscans;
  168119. /* Estimate number of scans to set pass_limit. */
  168120. if (cinfo->progressive_mode) {
  168121. /* Arbitrarily estimate 2 interleaved DC scans + 3 AC scans/component. */
  168122. nscans = 2 + 3 * cinfo->num_components;
  168123. } else {
  168124. /* For a nonprogressive multiscan file, estimate 1 scan per component. */
  168125. nscans = cinfo->num_components;
  168126. }
  168127. cinfo->progress->pass_counter = 0L;
  168128. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows * nscans;
  168129. cinfo->progress->completed_passes = 0;
  168130. cinfo->progress->total_passes = (cinfo->enable_2pass_quant ? 3 : 2);
  168131. /* Count the input pass as done */
  168132. master->pass_number++;
  168133. }
  168134. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  168135. }
  168136. /*
  168137. * Per-pass setup.
  168138. * This is called at the beginning of each output pass. We determine which
  168139. * modules will be active during this pass and give them appropriate
  168140. * start_pass calls. We also set is_dummy_pass to indicate whether this
  168141. * is a "real" output pass or a dummy pass for color quantization.
  168142. * (In the latter case, jdapistd.c will crank the pass to completion.)
  168143. */
  168144. METHODDEF(void)
  168145. prepare_for_output_pass (j_decompress_ptr cinfo)
  168146. {
  168147. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  168148. if (master->pub.is_dummy_pass) {
  168149. #ifdef QUANT_2PASS_SUPPORTED
  168150. /* Final pass of 2-pass quantization */
  168151. master->pub.is_dummy_pass = FALSE;
  168152. (*cinfo->cquantize->start_pass) (cinfo, FALSE);
  168153. (*cinfo->post->start_pass) (cinfo, JBUF_CRANK_DEST);
  168154. (*cinfo->main->start_pass) (cinfo, JBUF_CRANK_DEST);
  168155. #else
  168156. ERREXIT(cinfo, JERR_NOT_COMPILED);
  168157. #endif /* QUANT_2PASS_SUPPORTED */
  168158. } else {
  168159. if (cinfo->quantize_colors && cinfo->colormap == NULL) {
  168160. /* Select new quantization method */
  168161. if (cinfo->two_pass_quantize && cinfo->enable_2pass_quant) {
  168162. cinfo->cquantize = master->quantizer_2pass;
  168163. master->pub.is_dummy_pass = TRUE;
  168164. } else if (cinfo->enable_1pass_quant) {
  168165. cinfo->cquantize = master->quantizer_1pass;
  168166. } else {
  168167. ERREXIT(cinfo, JERR_MODE_CHANGE);
  168168. }
  168169. }
  168170. (*cinfo->idct->start_pass) (cinfo);
  168171. (*cinfo->coef->start_output_pass) (cinfo);
  168172. if (! cinfo->raw_data_out) {
  168173. if (! master->using_merged_upsample)
  168174. (*cinfo->cconvert->start_pass) (cinfo);
  168175. (*cinfo->upsample->start_pass) (cinfo);
  168176. if (cinfo->quantize_colors)
  168177. (*cinfo->cquantize->start_pass) (cinfo, master->pub.is_dummy_pass);
  168178. (*cinfo->post->start_pass) (cinfo,
  168179. (master->pub.is_dummy_pass ? JBUF_SAVE_AND_PASS : JBUF_PASS_THRU));
  168180. (*cinfo->main->start_pass) (cinfo, JBUF_PASS_THRU);
  168181. }
  168182. }
  168183. /* Set up progress monitor's pass info if present */
  168184. if (cinfo->progress != NULL) {
  168185. cinfo->progress->completed_passes = master->pass_number;
  168186. cinfo->progress->total_passes = master->pass_number +
  168187. (master->pub.is_dummy_pass ? 2 : 1);
  168188. /* In buffered-image mode, we assume one more output pass if EOI not
  168189. * yet reached, but no more passes if EOI has been reached.
  168190. */
  168191. if (cinfo->buffered_image && ! cinfo->inputctl->eoi_reached) {
  168192. cinfo->progress->total_passes += (cinfo->enable_2pass_quant ? 2 : 1);
  168193. }
  168194. }
  168195. }
  168196. /*
  168197. * Finish up at end of an output pass.
  168198. */
  168199. METHODDEF(void)
  168200. finish_output_pass (j_decompress_ptr cinfo)
  168201. {
  168202. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  168203. if (cinfo->quantize_colors)
  168204. (*cinfo->cquantize->finish_pass) (cinfo);
  168205. master->pass_number++;
  168206. }
  168207. #ifdef D_MULTISCAN_FILES_SUPPORTED
  168208. /*
  168209. * Switch to a new external colormap between output passes.
  168210. */
  168211. GLOBAL(void)
  168212. jpeg_new_colormap (j_decompress_ptr cinfo)
  168213. {
  168214. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  168215. /* Prevent application from calling me at wrong times */
  168216. if (cinfo->global_state != DSTATE_BUFIMAGE)
  168217. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  168218. if (cinfo->quantize_colors && cinfo->enable_external_quant &&
  168219. cinfo->colormap != NULL) {
  168220. /* Select 2-pass quantizer for external colormap use */
  168221. cinfo->cquantize = master->quantizer_2pass;
  168222. /* Notify quantizer of colormap change */
  168223. (*cinfo->cquantize->new_color_map) (cinfo);
  168224. master->pub.is_dummy_pass = FALSE; /* just in case */
  168225. } else
  168226. ERREXIT(cinfo, JERR_MODE_CHANGE);
  168227. }
  168228. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  168229. /*
  168230. * Initialize master decompression control and select active modules.
  168231. * This is performed at the start of jpeg_start_decompress.
  168232. */
  168233. GLOBAL(void)
  168234. jinit_master_decompress (j_decompress_ptr cinfo)
  168235. {
  168236. my_master_ptr6 master;
  168237. master = (my_master_ptr6)
  168238. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168239. SIZEOF(my_decomp_master));
  168240. cinfo->master = (struct jpeg_decomp_master *) master;
  168241. master->pub.prepare_for_output_pass = prepare_for_output_pass;
  168242. master->pub.finish_output_pass = finish_output_pass;
  168243. master->pub.is_dummy_pass = FALSE;
  168244. master_selection(cinfo);
  168245. }
  168246. /********* End of inlined file: jdmaster.c *********/
  168247. #undef FIX
  168248. /********* Start of inlined file: jdmerge.c *********/
  168249. #define JPEG_INTERNALS
  168250. #ifdef UPSAMPLE_MERGING_SUPPORTED
  168251. /* Private subobject */
  168252. typedef struct {
  168253. struct jpeg_upsampler pub; /* public fields */
  168254. /* Pointer to routine to do actual upsampling/conversion of one row group */
  168255. JMETHOD(void, upmethod, (j_decompress_ptr cinfo,
  168256. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  168257. JSAMPARRAY output_buf));
  168258. /* Private state for YCC->RGB conversion */
  168259. int * Cr_r_tab; /* => table for Cr to R conversion */
  168260. int * Cb_b_tab; /* => table for Cb to B conversion */
  168261. INT32 * Cr_g_tab; /* => table for Cr to G conversion */
  168262. INT32 * Cb_g_tab; /* => table for Cb to G conversion */
  168263. /* For 2:1 vertical sampling, we produce two output rows at a time.
  168264. * We need a "spare" row buffer to hold the second output row if the
  168265. * application provides just a one-row buffer; we also use the spare
  168266. * to discard the dummy last row if the image height is odd.
  168267. */
  168268. JSAMPROW spare_row;
  168269. boolean spare_full; /* T if spare buffer is occupied */
  168270. JDIMENSION out_row_width; /* samples per output row */
  168271. JDIMENSION rows_to_go; /* counts rows remaining in image */
  168272. } my_upsampler;
  168273. typedef my_upsampler * my_upsample_ptr;
  168274. #define SCALEBITS 16 /* speediest right-shift on some machines */
  168275. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  168276. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  168277. /*
  168278. * Initialize tables for YCC->RGB colorspace conversion.
  168279. * This is taken directly from jdcolor.c; see that file for more info.
  168280. */
  168281. LOCAL(void)
  168282. build_ycc_rgb_table2 (j_decompress_ptr cinfo)
  168283. {
  168284. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  168285. int i;
  168286. INT32 x;
  168287. SHIFT_TEMPS
  168288. upsample->Cr_r_tab = (int *)
  168289. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168290. (MAXJSAMPLE+1) * SIZEOF(int));
  168291. upsample->Cb_b_tab = (int *)
  168292. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168293. (MAXJSAMPLE+1) * SIZEOF(int));
  168294. upsample->Cr_g_tab = (INT32 *)
  168295. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168296. (MAXJSAMPLE+1) * SIZEOF(INT32));
  168297. upsample->Cb_g_tab = (INT32 *)
  168298. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168299. (MAXJSAMPLE+1) * SIZEOF(INT32));
  168300. for (i = 0, x = -CENTERJSAMPLE; i <= MAXJSAMPLE; i++, x++) {
  168301. /* i is the actual input pixel value, in the range 0..MAXJSAMPLE */
  168302. /* The Cb or Cr value we are thinking of is x = i - CENTERJSAMPLE */
  168303. /* Cr=>R value is nearest int to 1.40200 * x */
  168304. upsample->Cr_r_tab[i] = (int)
  168305. RIGHT_SHIFT(FIX(1.40200) * x + ONE_HALF, SCALEBITS);
  168306. /* Cb=>B value is nearest int to 1.77200 * x */
  168307. upsample->Cb_b_tab[i] = (int)
  168308. RIGHT_SHIFT(FIX(1.77200) * x + ONE_HALF, SCALEBITS);
  168309. /* Cr=>G value is scaled-up -0.71414 * x */
  168310. upsample->Cr_g_tab[i] = (- FIX(0.71414)) * x;
  168311. /* Cb=>G value is scaled-up -0.34414 * x */
  168312. /* We also add in ONE_HALF so that need not do it in inner loop */
  168313. upsample->Cb_g_tab[i] = (- FIX(0.34414)) * x + ONE_HALF;
  168314. }
  168315. }
  168316. /*
  168317. * Initialize for an upsampling pass.
  168318. */
  168319. METHODDEF(void)
  168320. start_pass_merged_upsample (j_decompress_ptr cinfo)
  168321. {
  168322. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  168323. /* Mark the spare buffer empty */
  168324. upsample->spare_full = FALSE;
  168325. /* Initialize total-height counter for detecting bottom of image */
  168326. upsample->rows_to_go = cinfo->output_height;
  168327. }
  168328. /*
  168329. * Control routine to do upsampling (and color conversion).
  168330. *
  168331. * The control routine just handles the row buffering considerations.
  168332. */
  168333. METHODDEF(void)
  168334. merged_2v_upsample (j_decompress_ptr cinfo,
  168335. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  168336. JDIMENSION in_row_groups_avail,
  168337. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  168338. JDIMENSION out_rows_avail)
  168339. /* 2:1 vertical sampling case: may need a spare row. */
  168340. {
  168341. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  168342. JSAMPROW work_ptrs[2];
  168343. JDIMENSION num_rows; /* number of rows returned to caller */
  168344. if (upsample->spare_full) {
  168345. /* If we have a spare row saved from a previous cycle, just return it. */
  168346. jcopy_sample_rows(& upsample->spare_row, 0, output_buf + *out_row_ctr, 0,
  168347. 1, upsample->out_row_width);
  168348. num_rows = 1;
  168349. upsample->spare_full = FALSE;
  168350. } else {
  168351. /* Figure number of rows to return to caller. */
  168352. num_rows = 2;
  168353. /* Not more than the distance to the end of the image. */
  168354. if (num_rows > upsample->rows_to_go)
  168355. num_rows = upsample->rows_to_go;
  168356. /* And not more than what the client can accept: */
  168357. out_rows_avail -= *out_row_ctr;
  168358. if (num_rows > out_rows_avail)
  168359. num_rows = out_rows_avail;
  168360. /* Create output pointer array for upsampler. */
  168361. work_ptrs[0] = output_buf[*out_row_ctr];
  168362. if (num_rows > 1) {
  168363. work_ptrs[1] = output_buf[*out_row_ctr + 1];
  168364. } else {
  168365. work_ptrs[1] = upsample->spare_row;
  168366. upsample->spare_full = TRUE;
  168367. }
  168368. /* Now do the upsampling. */
  168369. (*upsample->upmethod) (cinfo, input_buf, *in_row_group_ctr, work_ptrs);
  168370. }
  168371. /* Adjust counts */
  168372. *out_row_ctr += num_rows;
  168373. upsample->rows_to_go -= num_rows;
  168374. /* When the buffer is emptied, declare this input row group consumed */
  168375. if (! upsample->spare_full)
  168376. (*in_row_group_ctr)++;
  168377. }
  168378. METHODDEF(void)
  168379. merged_1v_upsample (j_decompress_ptr cinfo,
  168380. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  168381. JDIMENSION in_row_groups_avail,
  168382. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  168383. JDIMENSION out_rows_avail)
  168384. /* 1:1 vertical sampling case: much easier, never need a spare row. */
  168385. {
  168386. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  168387. /* Just do the upsampling. */
  168388. (*upsample->upmethod) (cinfo, input_buf, *in_row_group_ctr,
  168389. output_buf + *out_row_ctr);
  168390. /* Adjust counts */
  168391. (*out_row_ctr)++;
  168392. (*in_row_group_ctr)++;
  168393. }
  168394. /*
  168395. * These are the routines invoked by the control routines to do
  168396. * the actual upsampling/conversion. One row group is processed per call.
  168397. *
  168398. * Note: since we may be writing directly into application-supplied buffers,
  168399. * we have to be honest about the output width; we can't assume the buffer
  168400. * has been rounded up to an even width.
  168401. */
  168402. /*
  168403. * Upsample and color convert for the case of 2:1 horizontal and 1:1 vertical.
  168404. */
  168405. METHODDEF(void)
  168406. h2v1_merged_upsample (j_decompress_ptr cinfo,
  168407. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  168408. JSAMPARRAY output_buf)
  168409. {
  168410. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  168411. register int y, cred, cgreen, cblue;
  168412. int cb, cr;
  168413. register JSAMPROW outptr;
  168414. JSAMPROW inptr0, inptr1, inptr2;
  168415. JDIMENSION col;
  168416. /* copy these pointers into registers if possible */
  168417. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  168418. int * Crrtab = upsample->Cr_r_tab;
  168419. int * Cbbtab = upsample->Cb_b_tab;
  168420. INT32 * Crgtab = upsample->Cr_g_tab;
  168421. INT32 * Cbgtab = upsample->Cb_g_tab;
  168422. SHIFT_TEMPS
  168423. inptr0 = input_buf[0][in_row_group_ctr];
  168424. inptr1 = input_buf[1][in_row_group_ctr];
  168425. inptr2 = input_buf[2][in_row_group_ctr];
  168426. outptr = output_buf[0];
  168427. /* Loop for each pair of output pixels */
  168428. for (col = cinfo->output_width >> 1; col > 0; col--) {
  168429. /* Do the chroma part of the calculation */
  168430. cb = GETJSAMPLE(*inptr1++);
  168431. cr = GETJSAMPLE(*inptr2++);
  168432. cred = Crrtab[cr];
  168433. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  168434. cblue = Cbbtab[cb];
  168435. /* Fetch 2 Y values and emit 2 pixels */
  168436. y = GETJSAMPLE(*inptr0++);
  168437. outptr[RGB_RED] = range_limit[y + cred];
  168438. outptr[RGB_GREEN] = range_limit[y + cgreen];
  168439. outptr[RGB_BLUE] = range_limit[y + cblue];
  168440. outptr += RGB_PIXELSIZE;
  168441. y = GETJSAMPLE(*inptr0++);
  168442. outptr[RGB_RED] = range_limit[y + cred];
  168443. outptr[RGB_GREEN] = range_limit[y + cgreen];
  168444. outptr[RGB_BLUE] = range_limit[y + cblue];
  168445. outptr += RGB_PIXELSIZE;
  168446. }
  168447. /* If image width is odd, do the last output column separately */
  168448. if (cinfo->output_width & 1) {
  168449. cb = GETJSAMPLE(*inptr1);
  168450. cr = GETJSAMPLE(*inptr2);
  168451. cred = Crrtab[cr];
  168452. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  168453. cblue = Cbbtab[cb];
  168454. y = GETJSAMPLE(*inptr0);
  168455. outptr[RGB_RED] = range_limit[y + cred];
  168456. outptr[RGB_GREEN] = range_limit[y + cgreen];
  168457. outptr[RGB_BLUE] = range_limit[y + cblue];
  168458. }
  168459. }
  168460. /*
  168461. * Upsample and color convert for the case of 2:1 horizontal and 2:1 vertical.
  168462. */
  168463. METHODDEF(void)
  168464. h2v2_merged_upsample (j_decompress_ptr cinfo,
  168465. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  168466. JSAMPARRAY output_buf)
  168467. {
  168468. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  168469. register int y, cred, cgreen, cblue;
  168470. int cb, cr;
  168471. register JSAMPROW outptr0, outptr1;
  168472. JSAMPROW inptr00, inptr01, inptr1, inptr2;
  168473. JDIMENSION col;
  168474. /* copy these pointers into registers if possible */
  168475. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  168476. int * Crrtab = upsample->Cr_r_tab;
  168477. int * Cbbtab = upsample->Cb_b_tab;
  168478. INT32 * Crgtab = upsample->Cr_g_tab;
  168479. INT32 * Cbgtab = upsample->Cb_g_tab;
  168480. SHIFT_TEMPS
  168481. inptr00 = input_buf[0][in_row_group_ctr*2];
  168482. inptr01 = input_buf[0][in_row_group_ctr*2 + 1];
  168483. inptr1 = input_buf[1][in_row_group_ctr];
  168484. inptr2 = input_buf[2][in_row_group_ctr];
  168485. outptr0 = output_buf[0];
  168486. outptr1 = output_buf[1];
  168487. /* Loop for each group of output pixels */
  168488. for (col = cinfo->output_width >> 1; col > 0; col--) {
  168489. /* Do the chroma part of the calculation */
  168490. cb = GETJSAMPLE(*inptr1++);
  168491. cr = GETJSAMPLE(*inptr2++);
  168492. cred = Crrtab[cr];
  168493. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  168494. cblue = Cbbtab[cb];
  168495. /* Fetch 4 Y values and emit 4 pixels */
  168496. y = GETJSAMPLE(*inptr00++);
  168497. outptr0[RGB_RED] = range_limit[y + cred];
  168498. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  168499. outptr0[RGB_BLUE] = range_limit[y + cblue];
  168500. outptr0 += RGB_PIXELSIZE;
  168501. y = GETJSAMPLE(*inptr00++);
  168502. outptr0[RGB_RED] = range_limit[y + cred];
  168503. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  168504. outptr0[RGB_BLUE] = range_limit[y + cblue];
  168505. outptr0 += RGB_PIXELSIZE;
  168506. y = GETJSAMPLE(*inptr01++);
  168507. outptr1[RGB_RED] = range_limit[y + cred];
  168508. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  168509. outptr1[RGB_BLUE] = range_limit[y + cblue];
  168510. outptr1 += RGB_PIXELSIZE;
  168511. y = GETJSAMPLE(*inptr01++);
  168512. outptr1[RGB_RED] = range_limit[y + cred];
  168513. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  168514. outptr1[RGB_BLUE] = range_limit[y + cblue];
  168515. outptr1 += RGB_PIXELSIZE;
  168516. }
  168517. /* If image width is odd, do the last output column separately */
  168518. if (cinfo->output_width & 1) {
  168519. cb = GETJSAMPLE(*inptr1);
  168520. cr = GETJSAMPLE(*inptr2);
  168521. cred = Crrtab[cr];
  168522. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  168523. cblue = Cbbtab[cb];
  168524. y = GETJSAMPLE(*inptr00);
  168525. outptr0[RGB_RED] = range_limit[y + cred];
  168526. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  168527. outptr0[RGB_BLUE] = range_limit[y + cblue];
  168528. y = GETJSAMPLE(*inptr01);
  168529. outptr1[RGB_RED] = range_limit[y + cred];
  168530. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  168531. outptr1[RGB_BLUE] = range_limit[y + cblue];
  168532. }
  168533. }
  168534. /*
  168535. * Module initialization routine for merged upsampling/color conversion.
  168536. *
  168537. * NB: this is called under the conditions determined by use_merged_upsample()
  168538. * in jdmaster.c. That routine MUST correspond to the actual capabilities
  168539. * of this module; no safety checks are made here.
  168540. */
  168541. GLOBAL(void)
  168542. jinit_merged_upsampler (j_decompress_ptr cinfo)
  168543. {
  168544. my_upsample_ptr upsample;
  168545. upsample = (my_upsample_ptr)
  168546. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168547. SIZEOF(my_upsampler));
  168548. cinfo->upsample = (struct jpeg_upsampler *) upsample;
  168549. upsample->pub.start_pass = start_pass_merged_upsample;
  168550. upsample->pub.need_context_rows = FALSE;
  168551. upsample->out_row_width = cinfo->output_width * cinfo->out_color_components;
  168552. if (cinfo->max_v_samp_factor == 2) {
  168553. upsample->pub.upsample = merged_2v_upsample;
  168554. upsample->upmethod = h2v2_merged_upsample;
  168555. /* Allocate a spare row buffer */
  168556. upsample->spare_row = (JSAMPROW)
  168557. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168558. (size_t) (upsample->out_row_width * SIZEOF(JSAMPLE)));
  168559. } else {
  168560. upsample->pub.upsample = merged_1v_upsample;
  168561. upsample->upmethod = h2v1_merged_upsample;
  168562. /* No spare row needed */
  168563. upsample->spare_row = NULL;
  168564. }
  168565. build_ycc_rgb_table2(cinfo);
  168566. }
  168567. #endif /* UPSAMPLE_MERGING_SUPPORTED */
  168568. /********* End of inlined file: jdmerge.c *********/
  168569. #undef ASSIGN_STATE
  168570. /********* Start of inlined file: jdphuff.c *********/
  168571. #define JPEG_INTERNALS
  168572. #ifdef D_PROGRESSIVE_SUPPORTED
  168573. /*
  168574. * Expanded entropy decoder object for progressive Huffman decoding.
  168575. *
  168576. * The savable_state subrecord contains fields that change within an MCU,
  168577. * but must not be updated permanently until we complete the MCU.
  168578. */
  168579. typedef struct {
  168580. unsigned int EOBRUN; /* remaining EOBs in EOBRUN */
  168581. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  168582. } savable_state3;
  168583. /* This macro is to work around compilers with missing or broken
  168584. * structure assignment. You'll need to fix this code if you have
  168585. * such a compiler and you change MAX_COMPS_IN_SCAN.
  168586. */
  168587. #ifndef NO_STRUCT_ASSIGN
  168588. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  168589. #else
  168590. #if MAX_COMPS_IN_SCAN == 4
  168591. #define ASSIGN_STATE(dest,src) \
  168592. ((dest).EOBRUN = (src).EOBRUN, \
  168593. (dest).last_dc_val[0] = (src).last_dc_val[0], \
  168594. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  168595. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  168596. (dest).last_dc_val[3] = (src).last_dc_val[3])
  168597. #endif
  168598. #endif
  168599. typedef struct {
  168600. struct jpeg_entropy_decoder pub; /* public fields */
  168601. /* These fields are loaded into local variables at start of each MCU.
  168602. * In case of suspension, we exit WITHOUT updating them.
  168603. */
  168604. bitread_perm_state bitstate; /* Bit buffer at start of MCU */
  168605. savable_state3 saved; /* Other state at start of MCU */
  168606. /* These fields are NOT loaded into local working state. */
  168607. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  168608. /* Pointers to derived tables (these workspaces have image lifespan) */
  168609. d_derived_tbl * derived_tbls[NUM_HUFF_TBLS];
  168610. d_derived_tbl * ac_derived_tbl; /* active table during an AC scan */
  168611. } phuff_entropy_decoder;
  168612. typedef phuff_entropy_decoder * phuff_entropy_ptr2;
  168613. /* Forward declarations */
  168614. METHODDEF(boolean) decode_mcu_DC_first JPP((j_decompress_ptr cinfo,
  168615. JBLOCKROW *MCU_data));
  168616. METHODDEF(boolean) decode_mcu_AC_first JPP((j_decompress_ptr cinfo,
  168617. JBLOCKROW *MCU_data));
  168618. METHODDEF(boolean) decode_mcu_DC_refine JPP((j_decompress_ptr cinfo,
  168619. JBLOCKROW *MCU_data));
  168620. METHODDEF(boolean) decode_mcu_AC_refine JPP((j_decompress_ptr cinfo,
  168621. JBLOCKROW *MCU_data));
  168622. /*
  168623. * Initialize for a Huffman-compressed scan.
  168624. */
  168625. METHODDEF(void)
  168626. start_pass_phuff_decoder (j_decompress_ptr cinfo)
  168627. {
  168628. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  168629. boolean is_DC_band, bad;
  168630. int ci, coefi, tbl;
  168631. int *coef_bit_ptr;
  168632. jpeg_component_info * compptr;
  168633. is_DC_band = (cinfo->Ss == 0);
  168634. /* Validate scan parameters */
  168635. bad = FALSE;
  168636. if (is_DC_band) {
  168637. if (cinfo->Se != 0)
  168638. bad = TRUE;
  168639. } else {
  168640. /* need not check Ss/Se < 0 since they came from unsigned bytes */
  168641. if (cinfo->Ss > cinfo->Se || cinfo->Se >= DCTSIZE2)
  168642. bad = TRUE;
  168643. /* AC scans may have only one component */
  168644. if (cinfo->comps_in_scan != 1)
  168645. bad = TRUE;
  168646. }
  168647. if (cinfo->Ah != 0) {
  168648. /* Successive approximation refinement scan: must have Al = Ah-1. */
  168649. if (cinfo->Al != cinfo->Ah-1)
  168650. bad = TRUE;
  168651. }
  168652. if (cinfo->Al > 13) /* need not check for < 0 */
  168653. bad = TRUE;
  168654. /* Arguably the maximum Al value should be less than 13 for 8-bit precision,
  168655. * but the spec doesn't say so, and we try to be liberal about what we
  168656. * accept. Note: large Al values could result in out-of-range DC
  168657. * coefficients during early scans, leading to bizarre displays due to
  168658. * overflows in the IDCT math. But we won't crash.
  168659. */
  168660. if (bad)
  168661. ERREXIT4(cinfo, JERR_BAD_PROGRESSION,
  168662. cinfo->Ss, cinfo->Se, cinfo->Ah, cinfo->Al);
  168663. /* Update progression status, and verify that scan order is legal.
  168664. * Note that inter-scan inconsistencies are treated as warnings
  168665. * not fatal errors ... not clear if this is right way to behave.
  168666. */
  168667. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  168668. int cindex = cinfo->cur_comp_info[ci]->component_index;
  168669. coef_bit_ptr = & cinfo->coef_bits[cindex][0];
  168670. if (!is_DC_band && coef_bit_ptr[0] < 0) /* AC without prior DC scan */
  168671. WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, 0);
  168672. for (coefi = cinfo->Ss; coefi <= cinfo->Se; coefi++) {
  168673. int expected = (coef_bit_ptr[coefi] < 0) ? 0 : coef_bit_ptr[coefi];
  168674. if (cinfo->Ah != expected)
  168675. WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, coefi);
  168676. coef_bit_ptr[coefi] = cinfo->Al;
  168677. }
  168678. }
  168679. /* Select MCU decoding routine */
  168680. if (cinfo->Ah == 0) {
  168681. if (is_DC_band)
  168682. entropy->pub.decode_mcu = decode_mcu_DC_first;
  168683. else
  168684. entropy->pub.decode_mcu = decode_mcu_AC_first;
  168685. } else {
  168686. if (is_DC_band)
  168687. entropy->pub.decode_mcu = decode_mcu_DC_refine;
  168688. else
  168689. entropy->pub.decode_mcu = decode_mcu_AC_refine;
  168690. }
  168691. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  168692. compptr = cinfo->cur_comp_info[ci];
  168693. /* Make sure requested tables are present, and compute derived tables.
  168694. * We may build same derived table more than once, but it's not expensive.
  168695. */
  168696. if (is_DC_band) {
  168697. if (cinfo->Ah == 0) { /* DC refinement needs no table */
  168698. tbl = compptr->dc_tbl_no;
  168699. jpeg_make_d_derived_tbl(cinfo, TRUE, tbl,
  168700. & entropy->derived_tbls[tbl]);
  168701. }
  168702. } else {
  168703. tbl = compptr->ac_tbl_no;
  168704. jpeg_make_d_derived_tbl(cinfo, FALSE, tbl,
  168705. & entropy->derived_tbls[tbl]);
  168706. /* remember the single active table */
  168707. entropy->ac_derived_tbl = entropy->derived_tbls[tbl];
  168708. }
  168709. /* Initialize DC predictions to 0 */
  168710. entropy->saved.last_dc_val[ci] = 0;
  168711. }
  168712. /* Initialize bitread state variables */
  168713. entropy->bitstate.bits_left = 0;
  168714. entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */
  168715. entropy->pub.insufficient_data = FALSE;
  168716. /* Initialize private state variables */
  168717. entropy->saved.EOBRUN = 0;
  168718. /* Initialize restart counter */
  168719. entropy->restarts_to_go = cinfo->restart_interval;
  168720. }
  168721. /*
  168722. * Check for a restart marker & resynchronize decoder.
  168723. * Returns FALSE if must suspend.
  168724. */
  168725. LOCAL(boolean)
  168726. process_restartp (j_decompress_ptr cinfo)
  168727. {
  168728. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  168729. int ci;
  168730. /* Throw away any unused bits remaining in bit buffer; */
  168731. /* include any full bytes in next_marker's count of discarded bytes */
  168732. cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8;
  168733. entropy->bitstate.bits_left = 0;
  168734. /* Advance past the RSTn marker */
  168735. if (! (*cinfo->marker->read_restart_marker) (cinfo))
  168736. return FALSE;
  168737. /* Re-initialize DC predictions to 0 */
  168738. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  168739. entropy->saved.last_dc_val[ci] = 0;
  168740. /* Re-init EOB run count, too */
  168741. entropy->saved.EOBRUN = 0;
  168742. /* Reset restart counter */
  168743. entropy->restarts_to_go = cinfo->restart_interval;
  168744. /* Reset out-of-data flag, unless read_restart_marker left us smack up
  168745. * against a marker. In that case we will end up treating the next data
  168746. * segment as empty, and we can avoid producing bogus output pixels by
  168747. * leaving the flag set.
  168748. */
  168749. if (cinfo->unread_marker == 0)
  168750. entropy->pub.insufficient_data = FALSE;
  168751. return TRUE;
  168752. }
  168753. /*
  168754. * Huffman MCU decoding.
  168755. * Each of these routines decodes and returns one MCU's worth of
  168756. * Huffman-compressed coefficients.
  168757. * The coefficients are reordered from zigzag order into natural array order,
  168758. * but are not dequantized.
  168759. *
  168760. * The i'th block of the MCU is stored into the block pointed to by
  168761. * MCU_data[i]. WE ASSUME THIS AREA IS INITIALLY ZEROED BY THE CALLER.
  168762. *
  168763. * We return FALSE if data source requested suspension. In that case no
  168764. * changes have been made to permanent state. (Exception: some output
  168765. * coefficients may already have been assigned. This is harmless for
  168766. * spectral selection, since we'll just re-assign them on the next call.
  168767. * Successive approximation AC refinement has to be more careful, however.)
  168768. */
  168769. /*
  168770. * MCU decoding for DC initial scan (either spectral selection,
  168771. * or first pass of successive approximation).
  168772. */
  168773. METHODDEF(boolean)
  168774. decode_mcu_DC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  168775. {
  168776. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  168777. int Al = cinfo->Al;
  168778. register int s, r;
  168779. int blkn, ci;
  168780. JBLOCKROW block;
  168781. BITREAD_STATE_VARS;
  168782. savable_state3 state;
  168783. d_derived_tbl * tbl;
  168784. jpeg_component_info * compptr;
  168785. /* Process restart marker if needed; may have to suspend */
  168786. if (cinfo->restart_interval) {
  168787. if (entropy->restarts_to_go == 0)
  168788. if (! process_restartp(cinfo))
  168789. return FALSE;
  168790. }
  168791. /* If we've run out of data, just leave the MCU set to zeroes.
  168792. * This way, we return uniform gray for the remainder of the segment.
  168793. */
  168794. if (! entropy->pub.insufficient_data) {
  168795. /* Load up working state */
  168796. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  168797. ASSIGN_STATE(state, entropy->saved);
  168798. /* Outer loop handles each block in the MCU */
  168799. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  168800. block = MCU_data[blkn];
  168801. ci = cinfo->MCU_membership[blkn];
  168802. compptr = cinfo->cur_comp_info[ci];
  168803. tbl = entropy->derived_tbls[compptr->dc_tbl_no];
  168804. /* Decode a single block's worth of coefficients */
  168805. /* Section F.2.2.1: decode the DC coefficient difference */
  168806. HUFF_DECODE(s, br_state, tbl, return FALSE, label1);
  168807. if (s) {
  168808. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  168809. r = GET_BITS(s);
  168810. s = HUFF_EXTEND(r, s);
  168811. }
  168812. /* Convert DC difference to actual value, update last_dc_val */
  168813. s += state.last_dc_val[ci];
  168814. state.last_dc_val[ci] = s;
  168815. /* Scale and output the coefficient (assumes jpeg_natural_order[0]=0) */
  168816. (*block)[0] = (JCOEF) (s << Al);
  168817. }
  168818. /* Completed MCU, so update state */
  168819. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  168820. ASSIGN_STATE(entropy->saved, state);
  168821. }
  168822. /* Account for restart interval (no-op if not using restarts) */
  168823. entropy->restarts_to_go--;
  168824. return TRUE;
  168825. }
  168826. /*
  168827. * MCU decoding for AC initial scan (either spectral selection,
  168828. * or first pass of successive approximation).
  168829. */
  168830. METHODDEF(boolean)
  168831. decode_mcu_AC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  168832. {
  168833. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  168834. int Se = cinfo->Se;
  168835. int Al = cinfo->Al;
  168836. register int s, k, r;
  168837. unsigned int EOBRUN;
  168838. JBLOCKROW block;
  168839. BITREAD_STATE_VARS;
  168840. d_derived_tbl * tbl;
  168841. /* Process restart marker if needed; may have to suspend */
  168842. if (cinfo->restart_interval) {
  168843. if (entropy->restarts_to_go == 0)
  168844. if (! process_restartp(cinfo))
  168845. return FALSE;
  168846. }
  168847. /* If we've run out of data, just leave the MCU set to zeroes.
  168848. * This way, we return uniform gray for the remainder of the segment.
  168849. */
  168850. if (! entropy->pub.insufficient_data) {
  168851. /* Load up working state.
  168852. * We can avoid loading/saving bitread state if in an EOB run.
  168853. */
  168854. EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we need */
  168855. /* There is always only one block per MCU */
  168856. if (EOBRUN > 0) /* if it's a band of zeroes... */
  168857. EOBRUN--; /* ...process it now (we do nothing) */
  168858. else {
  168859. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  168860. block = MCU_data[0];
  168861. tbl = entropy->ac_derived_tbl;
  168862. for (k = cinfo->Ss; k <= Se; k++) {
  168863. HUFF_DECODE(s, br_state, tbl, return FALSE, label2);
  168864. r = s >> 4;
  168865. s &= 15;
  168866. if (s) {
  168867. k += r;
  168868. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  168869. r = GET_BITS(s);
  168870. s = HUFF_EXTEND(r, s);
  168871. /* Scale and output coefficient in natural (dezigzagged) order */
  168872. (*block)[jpeg_natural_order[k]] = (JCOEF) (s << Al);
  168873. } else {
  168874. if (r == 15) { /* ZRL */
  168875. k += 15; /* skip 15 zeroes in band */
  168876. } else { /* EOBr, run length is 2^r + appended bits */
  168877. EOBRUN = 1 << r;
  168878. if (r) { /* EOBr, r > 0 */
  168879. CHECK_BIT_BUFFER(br_state, r, return FALSE);
  168880. r = GET_BITS(r);
  168881. EOBRUN += r;
  168882. }
  168883. EOBRUN--; /* this band is processed at this moment */
  168884. break; /* force end-of-band */
  168885. }
  168886. }
  168887. }
  168888. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  168889. }
  168890. /* Completed MCU, so update state */
  168891. entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we need */
  168892. }
  168893. /* Account for restart interval (no-op if not using restarts) */
  168894. entropy->restarts_to_go--;
  168895. return TRUE;
  168896. }
  168897. /*
  168898. * MCU decoding for DC successive approximation refinement scan.
  168899. * Note: we assume such scans can be multi-component, although the spec
  168900. * is not very clear on the point.
  168901. */
  168902. METHODDEF(boolean)
  168903. decode_mcu_DC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  168904. {
  168905. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  168906. int p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */
  168907. int blkn;
  168908. JBLOCKROW block;
  168909. BITREAD_STATE_VARS;
  168910. /* Process restart marker if needed; may have to suspend */
  168911. if (cinfo->restart_interval) {
  168912. if (entropy->restarts_to_go == 0)
  168913. if (! process_restartp(cinfo))
  168914. return FALSE;
  168915. }
  168916. /* Not worth the cycles to check insufficient_data here,
  168917. * since we will not change the data anyway if we read zeroes.
  168918. */
  168919. /* Load up working state */
  168920. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  168921. /* Outer loop handles each block in the MCU */
  168922. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  168923. block = MCU_data[blkn];
  168924. /* Encoded data is simply the next bit of the two's-complement DC value */
  168925. CHECK_BIT_BUFFER(br_state, 1, return FALSE);
  168926. if (GET_BITS(1))
  168927. (*block)[0] |= p1;
  168928. /* Note: since we use |=, repeating the assignment later is safe */
  168929. }
  168930. /* Completed MCU, so update state */
  168931. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  168932. /* Account for restart interval (no-op if not using restarts) */
  168933. entropy->restarts_to_go--;
  168934. return TRUE;
  168935. }
  168936. /*
  168937. * MCU decoding for AC successive approximation refinement scan.
  168938. */
  168939. METHODDEF(boolean)
  168940. decode_mcu_AC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  168941. {
  168942. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  168943. int Se = cinfo->Se;
  168944. int p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */
  168945. int m1 = (-1) << cinfo->Al; /* -1 in the bit position being coded */
  168946. register int s, k, r;
  168947. unsigned int EOBRUN;
  168948. JBLOCKROW block;
  168949. JCOEFPTR thiscoef;
  168950. BITREAD_STATE_VARS;
  168951. d_derived_tbl * tbl;
  168952. int num_newnz;
  168953. int newnz_pos[DCTSIZE2];
  168954. /* Process restart marker if needed; may have to suspend */
  168955. if (cinfo->restart_interval) {
  168956. if (entropy->restarts_to_go == 0)
  168957. if (! process_restartp(cinfo))
  168958. return FALSE;
  168959. }
  168960. /* If we've run out of data, don't modify the MCU.
  168961. */
  168962. if (! entropy->pub.insufficient_data) {
  168963. /* Load up working state */
  168964. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  168965. EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we need */
  168966. /* There is always only one block per MCU */
  168967. block = MCU_data[0];
  168968. tbl = entropy->ac_derived_tbl;
  168969. /* If we are forced to suspend, we must undo the assignments to any newly
  168970. * nonzero coefficients in the block, because otherwise we'd get confused
  168971. * next time about which coefficients were already nonzero.
  168972. * But we need not undo addition of bits to already-nonzero coefficients;
  168973. * instead, we can test the current bit to see if we already did it.
  168974. */
  168975. num_newnz = 0;
  168976. /* initialize coefficient loop counter to start of band */
  168977. k = cinfo->Ss;
  168978. if (EOBRUN == 0) {
  168979. for (; k <= Se; k++) {
  168980. HUFF_DECODE(s, br_state, tbl, goto undoit, label3);
  168981. r = s >> 4;
  168982. s &= 15;
  168983. if (s) {
  168984. if (s != 1) /* size of new coef should always be 1 */
  168985. WARNMS(cinfo, JWRN_HUFF_BAD_CODE);
  168986. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  168987. if (GET_BITS(1))
  168988. s = p1; /* newly nonzero coef is positive */
  168989. else
  168990. s = m1; /* newly nonzero coef is negative */
  168991. } else {
  168992. if (r != 15) {
  168993. EOBRUN = 1 << r; /* EOBr, run length is 2^r + appended bits */
  168994. if (r) {
  168995. CHECK_BIT_BUFFER(br_state, r, goto undoit);
  168996. r = GET_BITS(r);
  168997. EOBRUN += r;
  168998. }
  168999. break; /* rest of block is handled by EOB logic */
  169000. }
  169001. /* note s = 0 for processing ZRL */
  169002. }
  169003. /* Advance over already-nonzero coefs and r still-zero coefs,
  169004. * appending correction bits to the nonzeroes. A correction bit is 1
  169005. * if the absolute value of the coefficient must be increased.
  169006. */
  169007. do {
  169008. thiscoef = *block + jpeg_natural_order[k];
  169009. if (*thiscoef != 0) {
  169010. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  169011. if (GET_BITS(1)) {
  169012. if ((*thiscoef & p1) == 0) { /* do nothing if already set it */
  169013. if (*thiscoef >= 0)
  169014. *thiscoef += p1;
  169015. else
  169016. *thiscoef += m1;
  169017. }
  169018. }
  169019. } else {
  169020. if (--r < 0)
  169021. break; /* reached target zero coefficient */
  169022. }
  169023. k++;
  169024. } while (k <= Se);
  169025. if (s) {
  169026. int pos = jpeg_natural_order[k];
  169027. /* Output newly nonzero coefficient */
  169028. (*block)[pos] = (JCOEF) s;
  169029. /* Remember its position in case we have to suspend */
  169030. newnz_pos[num_newnz++] = pos;
  169031. }
  169032. }
  169033. }
  169034. if (EOBRUN > 0) {
  169035. /* Scan any remaining coefficient positions after the end-of-band
  169036. * (the last newly nonzero coefficient, if any). Append a correction
  169037. * bit to each already-nonzero coefficient. A correction bit is 1
  169038. * if the absolute value of the coefficient must be increased.
  169039. */
  169040. for (; k <= Se; k++) {
  169041. thiscoef = *block + jpeg_natural_order[k];
  169042. if (*thiscoef != 0) {
  169043. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  169044. if (GET_BITS(1)) {
  169045. if ((*thiscoef & p1) == 0) { /* do nothing if already changed it */
  169046. if (*thiscoef >= 0)
  169047. *thiscoef += p1;
  169048. else
  169049. *thiscoef += m1;
  169050. }
  169051. }
  169052. }
  169053. }
  169054. /* Count one block completed in EOB run */
  169055. EOBRUN--;
  169056. }
  169057. /* Completed MCU, so update state */
  169058. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  169059. entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we need */
  169060. }
  169061. /* Account for restart interval (no-op if not using restarts) */
  169062. entropy->restarts_to_go--;
  169063. return TRUE;
  169064. undoit:
  169065. /* Re-zero any output coefficients that we made newly nonzero */
  169066. while (num_newnz > 0)
  169067. (*block)[newnz_pos[--num_newnz]] = 0;
  169068. return FALSE;
  169069. }
  169070. /*
  169071. * Module initialization routine for progressive Huffman entropy decoding.
  169072. */
  169073. GLOBAL(void)
  169074. jinit_phuff_decoder (j_decompress_ptr cinfo)
  169075. {
  169076. phuff_entropy_ptr2 entropy;
  169077. int *coef_bit_ptr;
  169078. int ci, i;
  169079. entropy = (phuff_entropy_ptr2)
  169080. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169081. SIZEOF(phuff_entropy_decoder));
  169082. cinfo->entropy = (struct jpeg_entropy_decoder *) entropy;
  169083. entropy->pub.start_pass = start_pass_phuff_decoder;
  169084. /* Mark derived tables unallocated */
  169085. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  169086. entropy->derived_tbls[i] = NULL;
  169087. }
  169088. /* Create progression status table */
  169089. cinfo->coef_bits = (int (*)[DCTSIZE2])
  169090. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169091. cinfo->num_components*DCTSIZE2*SIZEOF(int));
  169092. coef_bit_ptr = & cinfo->coef_bits[0][0];
  169093. for (ci = 0; ci < cinfo->num_components; ci++)
  169094. for (i = 0; i < DCTSIZE2; i++)
  169095. *coef_bit_ptr++ = -1;
  169096. }
  169097. #endif /* D_PROGRESSIVE_SUPPORTED */
  169098. /********* End of inlined file: jdphuff.c *********/
  169099. /********* Start of inlined file: jdpostct.c *********/
  169100. #define JPEG_INTERNALS
  169101. /* Private buffer controller object */
  169102. typedef struct {
  169103. struct jpeg_d_post_controller pub; /* public fields */
  169104. /* Color quantization source buffer: this holds output data from
  169105. * the upsample/color conversion step to be passed to the quantizer.
  169106. * For two-pass color quantization, we need a full-image buffer;
  169107. * for one-pass operation, a strip buffer is sufficient.
  169108. */
  169109. jvirt_sarray_ptr whole_image; /* virtual array, or NULL if one-pass */
  169110. JSAMPARRAY buffer; /* strip buffer, or current strip of virtual */
  169111. JDIMENSION strip_height; /* buffer size in rows */
  169112. /* for two-pass mode only: */
  169113. JDIMENSION starting_row; /* row # of first row in current strip */
  169114. JDIMENSION next_row; /* index of next row to fill/empty in strip */
  169115. } my_post_controller;
  169116. typedef my_post_controller * my_post_ptr;
  169117. /* Forward declarations */
  169118. METHODDEF(void) post_process_1pass
  169119. JPP((j_decompress_ptr cinfo,
  169120. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  169121. JDIMENSION in_row_groups_avail,
  169122. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  169123. JDIMENSION out_rows_avail));
  169124. #ifdef QUANT_2PASS_SUPPORTED
  169125. METHODDEF(void) post_process_prepass
  169126. JPP((j_decompress_ptr cinfo,
  169127. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  169128. JDIMENSION in_row_groups_avail,
  169129. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  169130. JDIMENSION out_rows_avail));
  169131. METHODDEF(void) post_process_2pass
  169132. JPP((j_decompress_ptr cinfo,
  169133. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  169134. JDIMENSION in_row_groups_avail,
  169135. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  169136. JDIMENSION out_rows_avail));
  169137. #endif
  169138. /*
  169139. * Initialize for a processing pass.
  169140. */
  169141. METHODDEF(void)
  169142. start_pass_dpost (j_decompress_ptr cinfo, J_BUF_MODE pass_mode)
  169143. {
  169144. my_post_ptr post = (my_post_ptr) cinfo->post;
  169145. switch (pass_mode) {
  169146. case JBUF_PASS_THRU:
  169147. if (cinfo->quantize_colors) {
  169148. /* Single-pass processing with color quantization. */
  169149. post->pub.post_process_data = post_process_1pass;
  169150. /* We could be doing buffered-image output before starting a 2-pass
  169151. * color quantization; in that case, jinit_d_post_controller did not
  169152. * allocate a strip buffer. Use the virtual-array buffer as workspace.
  169153. */
  169154. if (post->buffer == NULL) {
  169155. post->buffer = (*cinfo->mem->access_virt_sarray)
  169156. ((j_common_ptr) cinfo, post->whole_image,
  169157. (JDIMENSION) 0, post->strip_height, TRUE);
  169158. }
  169159. } else {
  169160. /* For single-pass processing without color quantization,
  169161. * I have no work to do; just call the upsampler directly.
  169162. */
  169163. post->pub.post_process_data = cinfo->upsample->upsample;
  169164. }
  169165. break;
  169166. #ifdef QUANT_2PASS_SUPPORTED
  169167. case JBUF_SAVE_AND_PASS:
  169168. /* First pass of 2-pass quantization */
  169169. if (post->whole_image == NULL)
  169170. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  169171. post->pub.post_process_data = post_process_prepass;
  169172. break;
  169173. case JBUF_CRANK_DEST:
  169174. /* Second pass of 2-pass quantization */
  169175. if (post->whole_image == NULL)
  169176. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  169177. post->pub.post_process_data = post_process_2pass;
  169178. break;
  169179. #endif /* QUANT_2PASS_SUPPORTED */
  169180. default:
  169181. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  169182. break;
  169183. }
  169184. post->starting_row = post->next_row = 0;
  169185. }
  169186. /*
  169187. * Process some data in the one-pass (strip buffer) case.
  169188. * This is used for color precision reduction as well as one-pass quantization.
  169189. */
  169190. METHODDEF(void)
  169191. post_process_1pass (j_decompress_ptr cinfo,
  169192. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  169193. JDIMENSION in_row_groups_avail,
  169194. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  169195. JDIMENSION out_rows_avail)
  169196. {
  169197. my_post_ptr post = (my_post_ptr) cinfo->post;
  169198. JDIMENSION num_rows, max_rows;
  169199. /* Fill the buffer, but not more than what we can dump out in one go. */
  169200. /* Note we rely on the upsampler to detect bottom of image. */
  169201. max_rows = out_rows_avail - *out_row_ctr;
  169202. if (max_rows > post->strip_height)
  169203. max_rows = post->strip_height;
  169204. num_rows = 0;
  169205. (*cinfo->upsample->upsample) (cinfo,
  169206. input_buf, in_row_group_ctr, in_row_groups_avail,
  169207. post->buffer, &num_rows, max_rows);
  169208. /* Quantize and emit data. */
  169209. (*cinfo->cquantize->color_quantize) (cinfo,
  169210. post->buffer, output_buf + *out_row_ctr, (int) num_rows);
  169211. *out_row_ctr += num_rows;
  169212. }
  169213. #ifdef QUANT_2PASS_SUPPORTED
  169214. /*
  169215. * Process some data in the first pass of 2-pass quantization.
  169216. */
  169217. METHODDEF(void)
  169218. post_process_prepass (j_decompress_ptr cinfo,
  169219. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  169220. JDIMENSION in_row_groups_avail,
  169221. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  169222. JDIMENSION out_rows_avail)
  169223. {
  169224. my_post_ptr post = (my_post_ptr) cinfo->post;
  169225. JDIMENSION old_next_row, num_rows;
  169226. /* Reposition virtual buffer if at start of strip. */
  169227. if (post->next_row == 0) {
  169228. post->buffer = (*cinfo->mem->access_virt_sarray)
  169229. ((j_common_ptr) cinfo, post->whole_image,
  169230. post->starting_row, post->strip_height, TRUE);
  169231. }
  169232. /* Upsample some data (up to a strip height's worth). */
  169233. old_next_row = post->next_row;
  169234. (*cinfo->upsample->upsample) (cinfo,
  169235. input_buf, in_row_group_ctr, in_row_groups_avail,
  169236. post->buffer, &post->next_row, post->strip_height);
  169237. /* Allow quantizer to scan new data. No data is emitted, */
  169238. /* but we advance out_row_ctr so outer loop can tell when we're done. */
  169239. if (post->next_row > old_next_row) {
  169240. num_rows = post->next_row - old_next_row;
  169241. (*cinfo->cquantize->color_quantize) (cinfo, post->buffer + old_next_row,
  169242. (JSAMPARRAY) NULL, (int) num_rows);
  169243. *out_row_ctr += num_rows;
  169244. }
  169245. /* Advance if we filled the strip. */
  169246. if (post->next_row >= post->strip_height) {
  169247. post->starting_row += post->strip_height;
  169248. post->next_row = 0;
  169249. }
  169250. }
  169251. /*
  169252. * Process some data in the second pass of 2-pass quantization.
  169253. */
  169254. METHODDEF(void)
  169255. post_process_2pass (j_decompress_ptr cinfo,
  169256. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  169257. JDIMENSION in_row_groups_avail,
  169258. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  169259. JDIMENSION out_rows_avail)
  169260. {
  169261. my_post_ptr post = (my_post_ptr) cinfo->post;
  169262. JDIMENSION num_rows, max_rows;
  169263. /* Reposition virtual buffer if at start of strip. */
  169264. if (post->next_row == 0) {
  169265. post->buffer = (*cinfo->mem->access_virt_sarray)
  169266. ((j_common_ptr) cinfo, post->whole_image,
  169267. post->starting_row, post->strip_height, FALSE);
  169268. }
  169269. /* Determine number of rows to emit. */
  169270. num_rows = post->strip_height - post->next_row; /* available in strip */
  169271. max_rows = out_rows_avail - *out_row_ctr; /* available in output area */
  169272. if (num_rows > max_rows)
  169273. num_rows = max_rows;
  169274. /* We have to check bottom of image here, can't depend on upsampler. */
  169275. max_rows = cinfo->output_height - post->starting_row;
  169276. if (num_rows > max_rows)
  169277. num_rows = max_rows;
  169278. /* Quantize and emit data. */
  169279. (*cinfo->cquantize->color_quantize) (cinfo,
  169280. post->buffer + post->next_row, output_buf + *out_row_ctr,
  169281. (int) num_rows);
  169282. *out_row_ctr += num_rows;
  169283. /* Advance if we filled the strip. */
  169284. post->next_row += num_rows;
  169285. if (post->next_row >= post->strip_height) {
  169286. post->starting_row += post->strip_height;
  169287. post->next_row = 0;
  169288. }
  169289. }
  169290. #endif /* QUANT_2PASS_SUPPORTED */
  169291. /*
  169292. * Initialize postprocessing controller.
  169293. */
  169294. GLOBAL(void)
  169295. jinit_d_post_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  169296. {
  169297. my_post_ptr post;
  169298. post = (my_post_ptr)
  169299. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169300. SIZEOF(my_post_controller));
  169301. cinfo->post = (struct jpeg_d_post_controller *) post;
  169302. post->pub.start_pass = start_pass_dpost;
  169303. post->whole_image = NULL; /* flag for no virtual arrays */
  169304. post->buffer = NULL; /* flag for no strip buffer */
  169305. /* Create the quantization buffer, if needed */
  169306. if (cinfo->quantize_colors) {
  169307. /* The buffer strip height is max_v_samp_factor, which is typically
  169308. * an efficient number of rows for upsampling to return.
  169309. * (In the presence of output rescaling, we might want to be smarter?)
  169310. */
  169311. post->strip_height = (JDIMENSION) cinfo->max_v_samp_factor;
  169312. if (need_full_buffer) {
  169313. /* Two-pass color quantization: need full-image storage. */
  169314. /* We round up the number of rows to a multiple of the strip height. */
  169315. #ifdef QUANT_2PASS_SUPPORTED
  169316. post->whole_image = (*cinfo->mem->request_virt_sarray)
  169317. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  169318. cinfo->output_width * cinfo->out_color_components,
  169319. (JDIMENSION) jround_up((long) cinfo->output_height,
  169320. (long) post->strip_height),
  169321. post->strip_height);
  169322. #else
  169323. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  169324. #endif /* QUANT_2PASS_SUPPORTED */
  169325. } else {
  169326. /* One-pass color quantization: just make a strip buffer. */
  169327. post->buffer = (*cinfo->mem->alloc_sarray)
  169328. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169329. cinfo->output_width * cinfo->out_color_components,
  169330. post->strip_height);
  169331. }
  169332. }
  169333. }
  169334. /********* End of inlined file: jdpostct.c *********/
  169335. #undef FIX
  169336. /********* Start of inlined file: jdsample.c *********/
  169337. #define JPEG_INTERNALS
  169338. /* Pointer to routine to upsample a single component */
  169339. typedef JMETHOD(void, upsample1_ptr,
  169340. (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  169341. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr));
  169342. /* Private subobject */
  169343. typedef struct {
  169344. struct jpeg_upsampler pub; /* public fields */
  169345. /* Color conversion buffer. When using separate upsampling and color
  169346. * conversion steps, this buffer holds one upsampled row group until it
  169347. * has been color converted and output.
  169348. * Note: we do not allocate any storage for component(s) which are full-size,
  169349. * ie do not need rescaling. The corresponding entry of color_buf[] is
  169350. * simply set to point to the input data array, thereby avoiding copying.
  169351. */
  169352. JSAMPARRAY color_buf[MAX_COMPONENTS];
  169353. /* Per-component upsampling method pointers */
  169354. upsample1_ptr methods[MAX_COMPONENTS];
  169355. int next_row_out; /* counts rows emitted from color_buf */
  169356. JDIMENSION rows_to_go; /* counts rows remaining in image */
  169357. /* Height of an input row group for each component. */
  169358. int rowgroup_height[MAX_COMPONENTS];
  169359. /* These arrays save pixel expansion factors so that int_expand need not
  169360. * recompute them each time. They are unused for other upsampling methods.
  169361. */
  169362. UINT8 h_expand[MAX_COMPONENTS];
  169363. UINT8 v_expand[MAX_COMPONENTS];
  169364. } my_upsampler2;
  169365. typedef my_upsampler2 * my_upsample_ptr2;
  169366. /*
  169367. * Initialize for an upsampling pass.
  169368. */
  169369. METHODDEF(void)
  169370. start_pass_upsample (j_decompress_ptr cinfo)
  169371. {
  169372. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  169373. /* Mark the conversion buffer empty */
  169374. upsample->next_row_out = cinfo->max_v_samp_factor;
  169375. /* Initialize total-height counter for detecting bottom of image */
  169376. upsample->rows_to_go = cinfo->output_height;
  169377. }
  169378. /*
  169379. * Control routine to do upsampling (and color conversion).
  169380. *
  169381. * In this version we upsample each component independently.
  169382. * We upsample one row group into the conversion buffer, then apply
  169383. * color conversion a row at a time.
  169384. */
  169385. METHODDEF(void)
  169386. sep_upsample (j_decompress_ptr cinfo,
  169387. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  169388. JDIMENSION in_row_groups_avail,
  169389. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  169390. JDIMENSION out_rows_avail)
  169391. {
  169392. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  169393. int ci;
  169394. jpeg_component_info * compptr;
  169395. JDIMENSION num_rows;
  169396. /* Fill the conversion buffer, if it's empty */
  169397. if (upsample->next_row_out >= cinfo->max_v_samp_factor) {
  169398. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  169399. ci++, compptr++) {
  169400. /* Invoke per-component upsample method. Notice we pass a POINTER
  169401. * to color_buf[ci], so that fullsize_upsample can change it.
  169402. */
  169403. (*upsample->methods[ci]) (cinfo, compptr,
  169404. input_buf[ci] + (*in_row_group_ctr * upsample->rowgroup_height[ci]),
  169405. upsample->color_buf + ci);
  169406. }
  169407. upsample->next_row_out = 0;
  169408. }
  169409. /* Color-convert and emit rows */
  169410. /* How many we have in the buffer: */
  169411. num_rows = (JDIMENSION) (cinfo->max_v_samp_factor - upsample->next_row_out);
  169412. /* Not more than the distance to the end of the image. Need this test
  169413. * in case the image height is not a multiple of max_v_samp_factor:
  169414. */
  169415. if (num_rows > upsample->rows_to_go)
  169416. num_rows = upsample->rows_to_go;
  169417. /* And not more than what the client can accept: */
  169418. out_rows_avail -= *out_row_ctr;
  169419. if (num_rows > out_rows_avail)
  169420. num_rows = out_rows_avail;
  169421. (*cinfo->cconvert->color_convert) (cinfo, upsample->color_buf,
  169422. (JDIMENSION) upsample->next_row_out,
  169423. output_buf + *out_row_ctr,
  169424. (int) num_rows);
  169425. /* Adjust counts */
  169426. *out_row_ctr += num_rows;
  169427. upsample->rows_to_go -= num_rows;
  169428. upsample->next_row_out += num_rows;
  169429. /* When the buffer is emptied, declare this input row group consumed */
  169430. if (upsample->next_row_out >= cinfo->max_v_samp_factor)
  169431. (*in_row_group_ctr)++;
  169432. }
  169433. /*
  169434. * These are the routines invoked by sep_upsample to upsample pixel values
  169435. * of a single component. One row group is processed per call.
  169436. */
  169437. /*
  169438. * For full-size components, we just make color_buf[ci] point at the
  169439. * input buffer, and thus avoid copying any data. Note that this is
  169440. * safe only because sep_upsample doesn't declare the input row group
  169441. * "consumed" until we are done color converting and emitting it.
  169442. */
  169443. METHODDEF(void)
  169444. fullsize_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  169445. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  169446. {
  169447. *output_data_ptr = input_data;
  169448. }
  169449. /*
  169450. * This is a no-op version used for "uninteresting" components.
  169451. * These components will not be referenced by color conversion.
  169452. */
  169453. METHODDEF(void)
  169454. noop_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  169455. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  169456. {
  169457. *output_data_ptr = NULL; /* safety check */
  169458. }
  169459. /*
  169460. * This version handles any integral sampling ratios.
  169461. * This is not used for typical JPEG files, so it need not be fast.
  169462. * Nor, for that matter, is it particularly accurate: the algorithm is
  169463. * simple replication of the input pixel onto the corresponding output
  169464. * pixels. The hi-falutin sampling literature refers to this as a
  169465. * "box filter". A box filter tends to introduce visible artifacts,
  169466. * so if you are actually going to use 3:1 or 4:1 sampling ratios
  169467. * you would be well advised to improve this code.
  169468. */
  169469. METHODDEF(void)
  169470. int_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  169471. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  169472. {
  169473. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  169474. JSAMPARRAY output_data = *output_data_ptr;
  169475. register JSAMPROW inptr, outptr;
  169476. register JSAMPLE invalue;
  169477. register int h;
  169478. JSAMPROW outend;
  169479. int h_expand, v_expand;
  169480. int inrow, outrow;
  169481. h_expand = upsample->h_expand[compptr->component_index];
  169482. v_expand = upsample->v_expand[compptr->component_index];
  169483. inrow = outrow = 0;
  169484. while (outrow < cinfo->max_v_samp_factor) {
  169485. /* Generate one output row with proper horizontal expansion */
  169486. inptr = input_data[inrow];
  169487. outptr = output_data[outrow];
  169488. outend = outptr + cinfo->output_width;
  169489. while (outptr < outend) {
  169490. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  169491. for (h = h_expand; h > 0; h--) {
  169492. *outptr++ = invalue;
  169493. }
  169494. }
  169495. /* Generate any additional output rows by duplicating the first one */
  169496. if (v_expand > 1) {
  169497. jcopy_sample_rows(output_data, outrow, output_data, outrow+1,
  169498. v_expand-1, cinfo->output_width);
  169499. }
  169500. inrow++;
  169501. outrow += v_expand;
  169502. }
  169503. }
  169504. /*
  169505. * Fast processing for the common case of 2:1 horizontal and 1:1 vertical.
  169506. * It's still a box filter.
  169507. */
  169508. METHODDEF(void)
  169509. h2v1_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  169510. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  169511. {
  169512. JSAMPARRAY output_data = *output_data_ptr;
  169513. register JSAMPROW inptr, outptr;
  169514. register JSAMPLE invalue;
  169515. JSAMPROW outend;
  169516. int inrow;
  169517. for (inrow = 0; inrow < cinfo->max_v_samp_factor; inrow++) {
  169518. inptr = input_data[inrow];
  169519. outptr = output_data[inrow];
  169520. outend = outptr + cinfo->output_width;
  169521. while (outptr < outend) {
  169522. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  169523. *outptr++ = invalue;
  169524. *outptr++ = invalue;
  169525. }
  169526. }
  169527. }
  169528. /*
  169529. * Fast processing for the common case of 2:1 horizontal and 2:1 vertical.
  169530. * It's still a box filter.
  169531. */
  169532. METHODDEF(void)
  169533. h2v2_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  169534. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  169535. {
  169536. JSAMPARRAY output_data = *output_data_ptr;
  169537. register JSAMPROW inptr, outptr;
  169538. register JSAMPLE invalue;
  169539. JSAMPROW outend;
  169540. int inrow, outrow;
  169541. inrow = outrow = 0;
  169542. while (outrow < cinfo->max_v_samp_factor) {
  169543. inptr = input_data[inrow];
  169544. outptr = output_data[outrow];
  169545. outend = outptr + cinfo->output_width;
  169546. while (outptr < outend) {
  169547. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  169548. *outptr++ = invalue;
  169549. *outptr++ = invalue;
  169550. }
  169551. jcopy_sample_rows(output_data, outrow, output_data, outrow+1,
  169552. 1, cinfo->output_width);
  169553. inrow++;
  169554. outrow += 2;
  169555. }
  169556. }
  169557. /*
  169558. * Fancy processing for the common case of 2:1 horizontal and 1:1 vertical.
  169559. *
  169560. * The upsampling algorithm is linear interpolation between pixel centers,
  169561. * also known as a "triangle filter". This is a good compromise between
  169562. * speed and visual quality. The centers of the output pixels are 1/4 and 3/4
  169563. * of the way between input pixel centers.
  169564. *
  169565. * A note about the "bias" calculations: when rounding fractional values to
  169566. * integer, we do not want to always round 0.5 up to the next integer.
  169567. * If we did that, we'd introduce a noticeable bias towards larger values.
  169568. * Instead, this code is arranged so that 0.5 will be rounded up or down at
  169569. * alternate pixel locations (a simple ordered dither pattern).
  169570. */
  169571. METHODDEF(void)
  169572. h2v1_fancy_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  169573. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  169574. {
  169575. JSAMPARRAY output_data = *output_data_ptr;
  169576. register JSAMPROW inptr, outptr;
  169577. register int invalue;
  169578. register JDIMENSION colctr;
  169579. int inrow;
  169580. for (inrow = 0; inrow < cinfo->max_v_samp_factor; inrow++) {
  169581. inptr = input_data[inrow];
  169582. outptr = output_data[inrow];
  169583. /* Special case for first column */
  169584. invalue = GETJSAMPLE(*inptr++);
  169585. *outptr++ = (JSAMPLE) invalue;
  169586. *outptr++ = (JSAMPLE) ((invalue * 3 + GETJSAMPLE(*inptr) + 2) >> 2);
  169587. for (colctr = compptr->downsampled_width - 2; colctr > 0; colctr--) {
  169588. /* General case: 3/4 * nearer pixel + 1/4 * further pixel */
  169589. invalue = GETJSAMPLE(*inptr++) * 3;
  169590. *outptr++ = (JSAMPLE) ((invalue + GETJSAMPLE(inptr[-2]) + 1) >> 2);
  169591. *outptr++ = (JSAMPLE) ((invalue + GETJSAMPLE(*inptr) + 2) >> 2);
  169592. }
  169593. /* Special case for last column */
  169594. invalue = GETJSAMPLE(*inptr);
  169595. *outptr++ = (JSAMPLE) ((invalue * 3 + GETJSAMPLE(inptr[-1]) + 1) >> 2);
  169596. *outptr++ = (JSAMPLE) invalue;
  169597. }
  169598. }
  169599. /*
  169600. * Fancy processing for the common case of 2:1 horizontal and 2:1 vertical.
  169601. * Again a triangle filter; see comments for h2v1 case, above.
  169602. *
  169603. * It is OK for us to reference the adjacent input rows because we demanded
  169604. * context from the main buffer controller (see initialization code).
  169605. */
  169606. METHODDEF(void)
  169607. h2v2_fancy_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  169608. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  169609. {
  169610. JSAMPARRAY output_data = *output_data_ptr;
  169611. register JSAMPROW inptr0, inptr1, outptr;
  169612. #if BITS_IN_JSAMPLE == 8
  169613. register int thiscolsum, lastcolsum, nextcolsum;
  169614. #else
  169615. register INT32 thiscolsum, lastcolsum, nextcolsum;
  169616. #endif
  169617. register JDIMENSION colctr;
  169618. int inrow, outrow, v;
  169619. inrow = outrow = 0;
  169620. while (outrow < cinfo->max_v_samp_factor) {
  169621. for (v = 0; v < 2; v++) {
  169622. /* inptr0 points to nearest input row, inptr1 points to next nearest */
  169623. inptr0 = input_data[inrow];
  169624. if (v == 0) /* next nearest is row above */
  169625. inptr1 = input_data[inrow-1];
  169626. else /* next nearest is row below */
  169627. inptr1 = input_data[inrow+1];
  169628. outptr = output_data[outrow++];
  169629. /* Special case for first column */
  169630. thiscolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  169631. nextcolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  169632. *outptr++ = (JSAMPLE) ((thiscolsum * 4 + 8) >> 4);
  169633. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + nextcolsum + 7) >> 4);
  169634. lastcolsum = thiscolsum; thiscolsum = nextcolsum;
  169635. for (colctr = compptr->downsampled_width - 2; colctr > 0; colctr--) {
  169636. /* General case: 3/4 * nearer pixel + 1/4 * further pixel in each */
  169637. /* dimension, thus 9/16, 3/16, 3/16, 1/16 overall */
  169638. nextcolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  169639. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + lastcolsum + 8) >> 4);
  169640. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + nextcolsum + 7) >> 4);
  169641. lastcolsum = thiscolsum; thiscolsum = nextcolsum;
  169642. }
  169643. /* Special case for last column */
  169644. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + lastcolsum + 8) >> 4);
  169645. *outptr++ = (JSAMPLE) ((thiscolsum * 4 + 7) >> 4);
  169646. }
  169647. inrow++;
  169648. }
  169649. }
  169650. /*
  169651. * Module initialization routine for upsampling.
  169652. */
  169653. GLOBAL(void)
  169654. jinit_upsampler (j_decompress_ptr cinfo)
  169655. {
  169656. my_upsample_ptr2 upsample;
  169657. int ci;
  169658. jpeg_component_info * compptr;
  169659. boolean need_buffer, do_fancy;
  169660. int h_in_group, v_in_group, h_out_group, v_out_group;
  169661. upsample = (my_upsample_ptr2)
  169662. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169663. SIZEOF(my_upsampler2));
  169664. cinfo->upsample = (struct jpeg_upsampler *) upsample;
  169665. upsample->pub.start_pass = start_pass_upsample;
  169666. upsample->pub.upsample = sep_upsample;
  169667. upsample->pub.need_context_rows = FALSE; /* until we find out differently */
  169668. if (cinfo->CCIR601_sampling) /* this isn't supported */
  169669. ERREXIT(cinfo, JERR_CCIR601_NOTIMPL);
  169670. /* jdmainct.c doesn't support context rows when min_DCT_scaled_size = 1,
  169671. * so don't ask for it.
  169672. */
  169673. do_fancy = cinfo->do_fancy_upsampling && cinfo->min_DCT_scaled_size > 1;
  169674. /* Verify we can handle the sampling factors, select per-component methods,
  169675. * and create storage as needed.
  169676. */
  169677. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  169678. ci++, compptr++) {
  169679. /* Compute size of an "input group" after IDCT scaling. This many samples
  169680. * are to be converted to max_h_samp_factor * max_v_samp_factor pixels.
  169681. */
  169682. h_in_group = (compptr->h_samp_factor * compptr->DCT_scaled_size) /
  169683. cinfo->min_DCT_scaled_size;
  169684. v_in_group = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  169685. cinfo->min_DCT_scaled_size;
  169686. h_out_group = cinfo->max_h_samp_factor;
  169687. v_out_group = cinfo->max_v_samp_factor;
  169688. upsample->rowgroup_height[ci] = v_in_group; /* save for use later */
  169689. need_buffer = TRUE;
  169690. if (! compptr->component_needed) {
  169691. /* Don't bother to upsample an uninteresting component. */
  169692. upsample->methods[ci] = noop_upsample;
  169693. need_buffer = FALSE;
  169694. } else if (h_in_group == h_out_group && v_in_group == v_out_group) {
  169695. /* Fullsize components can be processed without any work. */
  169696. upsample->methods[ci] = fullsize_upsample;
  169697. need_buffer = FALSE;
  169698. } else if (h_in_group * 2 == h_out_group &&
  169699. v_in_group == v_out_group) {
  169700. /* Special cases for 2h1v upsampling */
  169701. if (do_fancy && compptr->downsampled_width > 2)
  169702. upsample->methods[ci] = h2v1_fancy_upsample;
  169703. else
  169704. upsample->methods[ci] = h2v1_upsample;
  169705. } else if (h_in_group * 2 == h_out_group &&
  169706. v_in_group * 2 == v_out_group) {
  169707. /* Special cases for 2h2v upsampling */
  169708. if (do_fancy && compptr->downsampled_width > 2) {
  169709. upsample->methods[ci] = h2v2_fancy_upsample;
  169710. upsample->pub.need_context_rows = TRUE;
  169711. } else
  169712. upsample->methods[ci] = h2v2_upsample;
  169713. } else if ((h_out_group % h_in_group) == 0 &&
  169714. (v_out_group % v_in_group) == 0) {
  169715. /* Generic integral-factors upsampling method */
  169716. upsample->methods[ci] = int_upsample;
  169717. upsample->h_expand[ci] = (UINT8) (h_out_group / h_in_group);
  169718. upsample->v_expand[ci] = (UINT8) (v_out_group / v_in_group);
  169719. } else
  169720. ERREXIT(cinfo, JERR_FRACT_SAMPLE_NOTIMPL);
  169721. if (need_buffer) {
  169722. upsample->color_buf[ci] = (*cinfo->mem->alloc_sarray)
  169723. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169724. (JDIMENSION) jround_up((long) cinfo->output_width,
  169725. (long) cinfo->max_h_samp_factor),
  169726. (JDIMENSION) cinfo->max_v_samp_factor);
  169727. }
  169728. }
  169729. }
  169730. /********* End of inlined file: jdsample.c *********/
  169731. /********* Start of inlined file: jdtrans.c *********/
  169732. #define JPEG_INTERNALS
  169733. /* Forward declarations */
  169734. LOCAL(void) transdecode_master_selection JPP((j_decompress_ptr cinfo));
  169735. /*
  169736. * Read the coefficient arrays from a JPEG file.
  169737. * jpeg_read_header must be completed before calling this.
  169738. *
  169739. * The entire image is read into a set of virtual coefficient-block arrays,
  169740. * one per component. The return value is a pointer to the array of
  169741. * virtual-array descriptors. These can be manipulated directly via the
  169742. * JPEG memory manager, or handed off to jpeg_write_coefficients().
  169743. * To release the memory occupied by the virtual arrays, call
  169744. * jpeg_finish_decompress() when done with the data.
  169745. *
  169746. * An alternative usage is to simply obtain access to the coefficient arrays
  169747. * during a buffered-image-mode decompression operation. This is allowed
  169748. * after any jpeg_finish_output() call. The arrays can be accessed until
  169749. * jpeg_finish_decompress() is called. (Note that any call to the library
  169750. * may reposition the arrays, so don't rely on access_virt_barray() results
  169751. * to stay valid across library calls.)
  169752. *
  169753. * Returns NULL if suspended. This case need be checked only if
  169754. * a suspending data source is used.
  169755. */
  169756. GLOBAL(jvirt_barray_ptr *)
  169757. jpeg_read_coefficients (j_decompress_ptr cinfo)
  169758. {
  169759. if (cinfo->global_state == DSTATE_READY) {
  169760. /* First call: initialize active modules */
  169761. transdecode_master_selection(cinfo);
  169762. cinfo->global_state = DSTATE_RDCOEFS;
  169763. }
  169764. if (cinfo->global_state == DSTATE_RDCOEFS) {
  169765. /* Absorb whole file into the coef buffer */
  169766. for (;;) {
  169767. int retcode;
  169768. /* Call progress monitor hook if present */
  169769. if (cinfo->progress != NULL)
  169770. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  169771. /* Absorb some more input */
  169772. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  169773. if (retcode == JPEG_SUSPENDED)
  169774. return NULL;
  169775. if (retcode == JPEG_REACHED_EOI)
  169776. break;
  169777. /* Advance progress counter if appropriate */
  169778. if (cinfo->progress != NULL &&
  169779. (retcode == JPEG_ROW_COMPLETED || retcode == JPEG_REACHED_SOS)) {
  169780. if (++cinfo->progress->pass_counter >= cinfo->progress->pass_limit) {
  169781. /* startup underestimated number of scans; ratchet up one scan */
  169782. cinfo->progress->pass_limit += (long) cinfo->total_iMCU_rows;
  169783. }
  169784. }
  169785. }
  169786. /* Set state so that jpeg_finish_decompress does the right thing */
  169787. cinfo->global_state = DSTATE_STOPPING;
  169788. }
  169789. /* At this point we should be in state DSTATE_STOPPING if being used
  169790. * standalone, or in state DSTATE_BUFIMAGE if being invoked to get access
  169791. * to the coefficients during a full buffered-image-mode decompression.
  169792. */
  169793. if ((cinfo->global_state == DSTATE_STOPPING ||
  169794. cinfo->global_state == DSTATE_BUFIMAGE) && cinfo->buffered_image) {
  169795. return cinfo->coef->coef_arrays;
  169796. }
  169797. /* Oops, improper usage */
  169798. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  169799. return NULL; /* keep compiler happy */
  169800. }
  169801. /*
  169802. * Master selection of decompression modules for transcoding.
  169803. * This substitutes for jdmaster.c's initialization of the full decompressor.
  169804. */
  169805. LOCAL(void)
  169806. transdecode_master_selection (j_decompress_ptr cinfo)
  169807. {
  169808. /* This is effectively a buffered-image operation. */
  169809. cinfo->buffered_image = TRUE;
  169810. /* Entropy decoding: either Huffman or arithmetic coding. */
  169811. if (cinfo->arith_code) {
  169812. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  169813. } else {
  169814. if (cinfo->progressive_mode) {
  169815. #ifdef D_PROGRESSIVE_SUPPORTED
  169816. jinit_phuff_decoder(cinfo);
  169817. #else
  169818. ERREXIT(cinfo, JERR_NOT_COMPILED);
  169819. #endif
  169820. } else
  169821. jinit_huff_decoder(cinfo);
  169822. }
  169823. /* Always get a full-image coefficient buffer. */
  169824. jinit_d_coef_controller(cinfo, TRUE);
  169825. /* We can now tell the memory manager to allocate virtual arrays. */
  169826. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  169827. /* Initialize input side of decompressor to consume first scan. */
  169828. (*cinfo->inputctl->start_input_pass) (cinfo);
  169829. /* Initialize progress monitoring. */
  169830. if (cinfo->progress != NULL) {
  169831. int nscans;
  169832. /* Estimate number of scans to set pass_limit. */
  169833. if (cinfo->progressive_mode) {
  169834. /* Arbitrarily estimate 2 interleaved DC scans + 3 AC scans/component. */
  169835. nscans = 2 + 3 * cinfo->num_components;
  169836. } else if (cinfo->inputctl->has_multiple_scans) {
  169837. /* For a nonprogressive multiscan file, estimate 1 scan per component. */
  169838. nscans = cinfo->num_components;
  169839. } else {
  169840. nscans = 1;
  169841. }
  169842. cinfo->progress->pass_counter = 0L;
  169843. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows * nscans;
  169844. cinfo->progress->completed_passes = 0;
  169845. cinfo->progress->total_passes = 1;
  169846. }
  169847. }
  169848. /********* End of inlined file: jdtrans.c *********/
  169849. /********* Start of inlined file: jfdctflt.c *********/
  169850. #define JPEG_INTERNALS
  169851. #ifdef DCT_FLOAT_SUPPORTED
  169852. /*
  169853. * This module is specialized to the case DCTSIZE = 8.
  169854. */
  169855. #if DCTSIZE != 8
  169856. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  169857. #endif
  169858. /*
  169859. * Perform the forward DCT on one block of samples.
  169860. */
  169861. GLOBAL(void)
  169862. jpeg_fdct_float (FAST_FLOAT * data)
  169863. {
  169864. FAST_FLOAT tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  169865. FAST_FLOAT tmp10, tmp11, tmp12, tmp13;
  169866. FAST_FLOAT z1, z2, z3, z4, z5, z11, z13;
  169867. FAST_FLOAT *dataptr;
  169868. int ctr;
  169869. /* Pass 1: process rows. */
  169870. dataptr = data;
  169871. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  169872. tmp0 = dataptr[0] + dataptr[7];
  169873. tmp7 = dataptr[0] - dataptr[7];
  169874. tmp1 = dataptr[1] + dataptr[6];
  169875. tmp6 = dataptr[1] - dataptr[6];
  169876. tmp2 = dataptr[2] + dataptr[5];
  169877. tmp5 = dataptr[2] - dataptr[5];
  169878. tmp3 = dataptr[3] + dataptr[4];
  169879. tmp4 = dataptr[3] - dataptr[4];
  169880. /* Even part */
  169881. tmp10 = tmp0 + tmp3; /* phase 2 */
  169882. tmp13 = tmp0 - tmp3;
  169883. tmp11 = tmp1 + tmp2;
  169884. tmp12 = tmp1 - tmp2;
  169885. dataptr[0] = tmp10 + tmp11; /* phase 3 */
  169886. dataptr[4] = tmp10 - tmp11;
  169887. z1 = (tmp12 + tmp13) * ((FAST_FLOAT) 0.707106781); /* c4 */
  169888. dataptr[2] = tmp13 + z1; /* phase 5 */
  169889. dataptr[6] = tmp13 - z1;
  169890. /* Odd part */
  169891. tmp10 = tmp4 + tmp5; /* phase 2 */
  169892. tmp11 = tmp5 + tmp6;
  169893. tmp12 = tmp6 + tmp7;
  169894. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  169895. z5 = (tmp10 - tmp12) * ((FAST_FLOAT) 0.382683433); /* c6 */
  169896. z2 = ((FAST_FLOAT) 0.541196100) * tmp10 + z5; /* c2-c6 */
  169897. z4 = ((FAST_FLOAT) 1.306562965) * tmp12 + z5; /* c2+c6 */
  169898. z3 = tmp11 * ((FAST_FLOAT) 0.707106781); /* c4 */
  169899. z11 = tmp7 + z3; /* phase 5 */
  169900. z13 = tmp7 - z3;
  169901. dataptr[5] = z13 + z2; /* phase 6 */
  169902. dataptr[3] = z13 - z2;
  169903. dataptr[1] = z11 + z4;
  169904. dataptr[7] = z11 - z4;
  169905. dataptr += DCTSIZE; /* advance pointer to next row */
  169906. }
  169907. /* Pass 2: process columns. */
  169908. dataptr = data;
  169909. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  169910. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  169911. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  169912. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  169913. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  169914. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  169915. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  169916. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  169917. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  169918. /* Even part */
  169919. tmp10 = tmp0 + tmp3; /* phase 2 */
  169920. tmp13 = tmp0 - tmp3;
  169921. tmp11 = tmp1 + tmp2;
  169922. tmp12 = tmp1 - tmp2;
  169923. dataptr[DCTSIZE*0] = tmp10 + tmp11; /* phase 3 */
  169924. dataptr[DCTSIZE*4] = tmp10 - tmp11;
  169925. z1 = (tmp12 + tmp13) * ((FAST_FLOAT) 0.707106781); /* c4 */
  169926. dataptr[DCTSIZE*2] = tmp13 + z1; /* phase 5 */
  169927. dataptr[DCTSIZE*6] = tmp13 - z1;
  169928. /* Odd part */
  169929. tmp10 = tmp4 + tmp5; /* phase 2 */
  169930. tmp11 = tmp5 + tmp6;
  169931. tmp12 = tmp6 + tmp7;
  169932. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  169933. z5 = (tmp10 - tmp12) * ((FAST_FLOAT) 0.382683433); /* c6 */
  169934. z2 = ((FAST_FLOAT) 0.541196100) * tmp10 + z5; /* c2-c6 */
  169935. z4 = ((FAST_FLOAT) 1.306562965) * tmp12 + z5; /* c2+c6 */
  169936. z3 = tmp11 * ((FAST_FLOAT) 0.707106781); /* c4 */
  169937. z11 = tmp7 + z3; /* phase 5 */
  169938. z13 = tmp7 - z3;
  169939. dataptr[DCTSIZE*5] = z13 + z2; /* phase 6 */
  169940. dataptr[DCTSIZE*3] = z13 - z2;
  169941. dataptr[DCTSIZE*1] = z11 + z4;
  169942. dataptr[DCTSIZE*7] = z11 - z4;
  169943. dataptr++; /* advance pointer to next column */
  169944. }
  169945. }
  169946. #endif /* DCT_FLOAT_SUPPORTED */
  169947. /********* End of inlined file: jfdctflt.c *********/
  169948. /********* Start of inlined file: jfdctint.c *********/
  169949. #define JPEG_INTERNALS
  169950. #ifdef DCT_ISLOW_SUPPORTED
  169951. /*
  169952. * This module is specialized to the case DCTSIZE = 8.
  169953. */
  169954. #if DCTSIZE != 8
  169955. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  169956. #endif
  169957. /*
  169958. * The poop on this scaling stuff is as follows:
  169959. *
  169960. * Each 1-D DCT step produces outputs which are a factor of sqrt(N)
  169961. * larger than the true DCT outputs. The final outputs are therefore
  169962. * a factor of N larger than desired; since N=8 this can be cured by
  169963. * a simple right shift at the end of the algorithm. The advantage of
  169964. * this arrangement is that we save two multiplications per 1-D DCT,
  169965. * because the y0 and y4 outputs need not be divided by sqrt(N).
  169966. * In the IJG code, this factor of 8 is removed by the quantization step
  169967. * (in jcdctmgr.c), NOT in this module.
  169968. *
  169969. * We have to do addition and subtraction of the integer inputs, which
  169970. * is no problem, and multiplication by fractional constants, which is
  169971. * a problem to do in integer arithmetic. We multiply all the constants
  169972. * by CONST_SCALE and convert them to integer constants (thus retaining
  169973. * CONST_BITS bits of precision in the constants). After doing a
  169974. * multiplication we have to divide the product by CONST_SCALE, with proper
  169975. * rounding, to produce the correct output. This division can be done
  169976. * cheaply as a right shift of CONST_BITS bits. We postpone shifting
  169977. * as long as possible so that partial sums can be added together with
  169978. * full fractional precision.
  169979. *
  169980. * The outputs of the first pass are scaled up by PASS1_BITS bits so that
  169981. * they are represented to better-than-integral precision. These outputs
  169982. * require BITS_IN_JSAMPLE + PASS1_BITS + 3 bits; this fits in a 16-bit word
  169983. * with the recommended scaling. (For 12-bit sample data, the intermediate
  169984. * array is INT32 anyway.)
  169985. *
  169986. * To avoid overflow of the 32-bit intermediate results in pass 2, we must
  169987. * have BITS_IN_JSAMPLE + CONST_BITS + PASS1_BITS <= 26. Error analysis
  169988. * shows that the values given below are the most effective.
  169989. */
  169990. #if BITS_IN_JSAMPLE == 8
  169991. #define CONST_BITS 13
  169992. #define PASS1_BITS 2
  169993. #else
  169994. #define CONST_BITS 13
  169995. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  169996. #endif
  169997. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  169998. * causing a lot of useless floating-point operations at run time.
  169999. * To get around this we use the following pre-calculated constants.
  170000. * If you change CONST_BITS you may want to add appropriate values.
  170001. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  170002. */
  170003. #if CONST_BITS == 13
  170004. #define FIX_0_298631336 ((INT32) 2446) /* FIX(0.298631336) */
  170005. #define FIX_0_390180644 ((INT32) 3196) /* FIX(0.390180644) */
  170006. #define FIX_0_541196100 ((INT32) 4433) /* FIX(0.541196100) */
  170007. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  170008. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  170009. #define FIX_1_175875602 ((INT32) 9633) /* FIX(1.175875602) */
  170010. #define FIX_1_501321110 ((INT32) 12299) /* FIX(1.501321110) */
  170011. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  170012. #define FIX_1_961570560 ((INT32) 16069) /* FIX(1.961570560) */
  170013. #define FIX_2_053119869 ((INT32) 16819) /* FIX(2.053119869) */
  170014. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  170015. #define FIX_3_072711026 ((INT32) 25172) /* FIX(3.072711026) */
  170016. #else
  170017. #define FIX_0_298631336 FIX(0.298631336)
  170018. #define FIX_0_390180644 FIX(0.390180644)
  170019. #define FIX_0_541196100 FIX(0.541196100)
  170020. #define FIX_0_765366865 FIX(0.765366865)
  170021. #define FIX_0_899976223 FIX(0.899976223)
  170022. #define FIX_1_175875602 FIX(1.175875602)
  170023. #define FIX_1_501321110 FIX(1.501321110)
  170024. #define FIX_1_847759065 FIX(1.847759065)
  170025. #define FIX_1_961570560 FIX(1.961570560)
  170026. #define FIX_2_053119869 FIX(2.053119869)
  170027. #define FIX_2_562915447 FIX(2.562915447)
  170028. #define FIX_3_072711026 FIX(3.072711026)
  170029. #endif
  170030. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  170031. * For 8-bit samples with the recommended scaling, all the variable
  170032. * and constant values involved are no more than 16 bits wide, so a
  170033. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  170034. * For 12-bit samples, a full 32-bit multiplication will be needed.
  170035. */
  170036. #if BITS_IN_JSAMPLE == 8
  170037. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  170038. #else
  170039. #define MULTIPLY(var,const) ((var) * (const))
  170040. #endif
  170041. /*
  170042. * Perform the forward DCT on one block of samples.
  170043. */
  170044. GLOBAL(void)
  170045. jpeg_fdct_islow (DCTELEM * data)
  170046. {
  170047. INT32 tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  170048. INT32 tmp10, tmp11, tmp12, tmp13;
  170049. INT32 z1, z2, z3, z4, z5;
  170050. DCTELEM *dataptr;
  170051. int ctr;
  170052. SHIFT_TEMPS
  170053. /* Pass 1: process rows. */
  170054. /* Note results are scaled up by sqrt(8) compared to a true DCT; */
  170055. /* furthermore, we scale the results by 2**PASS1_BITS. */
  170056. dataptr = data;
  170057. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  170058. tmp0 = dataptr[0] + dataptr[7];
  170059. tmp7 = dataptr[0] - dataptr[7];
  170060. tmp1 = dataptr[1] + dataptr[6];
  170061. tmp6 = dataptr[1] - dataptr[6];
  170062. tmp2 = dataptr[2] + dataptr[5];
  170063. tmp5 = dataptr[2] - dataptr[5];
  170064. tmp3 = dataptr[3] + dataptr[4];
  170065. tmp4 = dataptr[3] - dataptr[4];
  170066. /* Even part per LL&M figure 1 --- note that published figure is faulty;
  170067. * rotator "sqrt(2)*c1" should be "sqrt(2)*c6".
  170068. */
  170069. tmp10 = tmp0 + tmp3;
  170070. tmp13 = tmp0 - tmp3;
  170071. tmp11 = tmp1 + tmp2;
  170072. tmp12 = tmp1 - tmp2;
  170073. dataptr[0] = (DCTELEM) ((tmp10 + tmp11) << PASS1_BITS);
  170074. dataptr[4] = (DCTELEM) ((tmp10 - tmp11) << PASS1_BITS);
  170075. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_541196100);
  170076. dataptr[2] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp13, FIX_0_765366865),
  170077. CONST_BITS-PASS1_BITS);
  170078. dataptr[6] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp12, - FIX_1_847759065),
  170079. CONST_BITS-PASS1_BITS);
  170080. /* Odd part per figure 8 --- note paper omits factor of sqrt(2).
  170081. * cK represents cos(K*pi/16).
  170082. * i0..i3 in the paper are tmp4..tmp7 here.
  170083. */
  170084. z1 = tmp4 + tmp7;
  170085. z2 = tmp5 + tmp6;
  170086. z3 = tmp4 + tmp6;
  170087. z4 = tmp5 + tmp7;
  170088. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  170089. tmp4 = MULTIPLY(tmp4, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  170090. tmp5 = MULTIPLY(tmp5, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  170091. tmp6 = MULTIPLY(tmp6, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  170092. tmp7 = MULTIPLY(tmp7, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  170093. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  170094. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  170095. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  170096. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  170097. z3 += z5;
  170098. z4 += z5;
  170099. dataptr[7] = (DCTELEM) DESCALE(tmp4 + z1 + z3, CONST_BITS-PASS1_BITS);
  170100. dataptr[5] = (DCTELEM) DESCALE(tmp5 + z2 + z4, CONST_BITS-PASS1_BITS);
  170101. dataptr[3] = (DCTELEM) DESCALE(tmp6 + z2 + z3, CONST_BITS-PASS1_BITS);
  170102. dataptr[1] = (DCTELEM) DESCALE(tmp7 + z1 + z4, CONST_BITS-PASS1_BITS);
  170103. dataptr += DCTSIZE; /* advance pointer to next row */
  170104. }
  170105. /* Pass 2: process columns.
  170106. * We remove the PASS1_BITS scaling, but leave the results scaled up
  170107. * by an overall factor of 8.
  170108. */
  170109. dataptr = data;
  170110. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  170111. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  170112. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  170113. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  170114. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  170115. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  170116. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  170117. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  170118. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  170119. /* Even part per LL&M figure 1 --- note that published figure is faulty;
  170120. * rotator "sqrt(2)*c1" should be "sqrt(2)*c6".
  170121. */
  170122. tmp10 = tmp0 + tmp3;
  170123. tmp13 = tmp0 - tmp3;
  170124. tmp11 = tmp1 + tmp2;
  170125. tmp12 = tmp1 - tmp2;
  170126. dataptr[DCTSIZE*0] = (DCTELEM) DESCALE(tmp10 + tmp11, PASS1_BITS);
  170127. dataptr[DCTSIZE*4] = (DCTELEM) DESCALE(tmp10 - tmp11, PASS1_BITS);
  170128. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_541196100);
  170129. dataptr[DCTSIZE*2] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp13, FIX_0_765366865),
  170130. CONST_BITS+PASS1_BITS);
  170131. dataptr[DCTSIZE*6] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp12, - FIX_1_847759065),
  170132. CONST_BITS+PASS1_BITS);
  170133. /* Odd part per figure 8 --- note paper omits factor of sqrt(2).
  170134. * cK represents cos(K*pi/16).
  170135. * i0..i3 in the paper are tmp4..tmp7 here.
  170136. */
  170137. z1 = tmp4 + tmp7;
  170138. z2 = tmp5 + tmp6;
  170139. z3 = tmp4 + tmp6;
  170140. z4 = tmp5 + tmp7;
  170141. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  170142. tmp4 = MULTIPLY(tmp4, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  170143. tmp5 = MULTIPLY(tmp5, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  170144. tmp6 = MULTIPLY(tmp6, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  170145. tmp7 = MULTIPLY(tmp7, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  170146. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  170147. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  170148. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  170149. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  170150. z3 += z5;
  170151. z4 += z5;
  170152. dataptr[DCTSIZE*7] = (DCTELEM) DESCALE(tmp4 + z1 + z3,
  170153. CONST_BITS+PASS1_BITS);
  170154. dataptr[DCTSIZE*5] = (DCTELEM) DESCALE(tmp5 + z2 + z4,
  170155. CONST_BITS+PASS1_BITS);
  170156. dataptr[DCTSIZE*3] = (DCTELEM) DESCALE(tmp6 + z2 + z3,
  170157. CONST_BITS+PASS1_BITS);
  170158. dataptr[DCTSIZE*1] = (DCTELEM) DESCALE(tmp7 + z1 + z4,
  170159. CONST_BITS+PASS1_BITS);
  170160. dataptr++; /* advance pointer to next column */
  170161. }
  170162. }
  170163. #endif /* DCT_ISLOW_SUPPORTED */
  170164. /********* End of inlined file: jfdctint.c *********/
  170165. #undef CONST_BITS
  170166. #undef MULTIPLY
  170167. #undef FIX_0_541196100
  170168. /********* Start of inlined file: jfdctfst.c *********/
  170169. #define JPEG_INTERNALS
  170170. #ifdef DCT_IFAST_SUPPORTED
  170171. /*
  170172. * This module is specialized to the case DCTSIZE = 8.
  170173. */
  170174. #if DCTSIZE != 8
  170175. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  170176. #endif
  170177. /* Scaling decisions are generally the same as in the LL&M algorithm;
  170178. * see jfdctint.c for more details. However, we choose to descale
  170179. * (right shift) multiplication products as soon as they are formed,
  170180. * rather than carrying additional fractional bits into subsequent additions.
  170181. * This compromises accuracy slightly, but it lets us save a few shifts.
  170182. * More importantly, 16-bit arithmetic is then adequate (for 8-bit samples)
  170183. * everywhere except in the multiplications proper; this saves a good deal
  170184. * of work on 16-bit-int machines.
  170185. *
  170186. * Again to save a few shifts, the intermediate results between pass 1 and
  170187. * pass 2 are not upscaled, but are represented only to integral precision.
  170188. *
  170189. * A final compromise is to represent the multiplicative constants to only
  170190. * 8 fractional bits, rather than 13. This saves some shifting work on some
  170191. * machines, and may also reduce the cost of multiplication (since there
  170192. * are fewer one-bits in the constants).
  170193. */
  170194. #define CONST_BITS 8
  170195. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  170196. * causing a lot of useless floating-point operations at run time.
  170197. * To get around this we use the following pre-calculated constants.
  170198. * If you change CONST_BITS you may want to add appropriate values.
  170199. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  170200. */
  170201. #if CONST_BITS == 8
  170202. #define FIX_0_382683433 ((INT32) 98) /* FIX(0.382683433) */
  170203. #define FIX_0_541196100 ((INT32) 139) /* FIX(0.541196100) */
  170204. #define FIX_0_707106781 ((INT32) 181) /* FIX(0.707106781) */
  170205. #define FIX_1_306562965 ((INT32) 334) /* FIX(1.306562965) */
  170206. #else
  170207. #define FIX_0_382683433 FIX(0.382683433)
  170208. #define FIX_0_541196100 FIX(0.541196100)
  170209. #define FIX_0_707106781 FIX(0.707106781)
  170210. #define FIX_1_306562965 FIX(1.306562965)
  170211. #endif
  170212. /* We can gain a little more speed, with a further compromise in accuracy,
  170213. * by omitting the addition in a descaling shift. This yields an incorrectly
  170214. * rounded result half the time...
  170215. */
  170216. #ifndef USE_ACCURATE_ROUNDING
  170217. #undef DESCALE
  170218. #define DESCALE(x,n) RIGHT_SHIFT(x, n)
  170219. #endif
  170220. /* Multiply a DCTELEM variable by an INT32 constant, and immediately
  170221. * descale to yield a DCTELEM result.
  170222. */
  170223. #define MULTIPLY(var,const) ((DCTELEM) DESCALE((var) * (const), CONST_BITS))
  170224. /*
  170225. * Perform the forward DCT on one block of samples.
  170226. */
  170227. GLOBAL(void)
  170228. jpeg_fdct_ifast (DCTELEM * data)
  170229. {
  170230. DCTELEM tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  170231. DCTELEM tmp10, tmp11, tmp12, tmp13;
  170232. DCTELEM z1, z2, z3, z4, z5, z11, z13;
  170233. DCTELEM *dataptr;
  170234. int ctr;
  170235. SHIFT_TEMPS
  170236. /* Pass 1: process rows. */
  170237. dataptr = data;
  170238. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  170239. tmp0 = dataptr[0] + dataptr[7];
  170240. tmp7 = dataptr[0] - dataptr[7];
  170241. tmp1 = dataptr[1] + dataptr[6];
  170242. tmp6 = dataptr[1] - dataptr[6];
  170243. tmp2 = dataptr[2] + dataptr[5];
  170244. tmp5 = dataptr[2] - dataptr[5];
  170245. tmp3 = dataptr[3] + dataptr[4];
  170246. tmp4 = dataptr[3] - dataptr[4];
  170247. /* Even part */
  170248. tmp10 = tmp0 + tmp3; /* phase 2 */
  170249. tmp13 = tmp0 - tmp3;
  170250. tmp11 = tmp1 + tmp2;
  170251. tmp12 = tmp1 - tmp2;
  170252. dataptr[0] = tmp10 + tmp11; /* phase 3 */
  170253. dataptr[4] = tmp10 - tmp11;
  170254. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_707106781); /* c4 */
  170255. dataptr[2] = tmp13 + z1; /* phase 5 */
  170256. dataptr[6] = tmp13 - z1;
  170257. /* Odd part */
  170258. tmp10 = tmp4 + tmp5; /* phase 2 */
  170259. tmp11 = tmp5 + tmp6;
  170260. tmp12 = tmp6 + tmp7;
  170261. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  170262. z5 = MULTIPLY(tmp10 - tmp12, FIX_0_382683433); /* c6 */
  170263. z2 = MULTIPLY(tmp10, FIX_0_541196100) + z5; /* c2-c6 */
  170264. z4 = MULTIPLY(tmp12, FIX_1_306562965) + z5; /* c2+c6 */
  170265. z3 = MULTIPLY(tmp11, FIX_0_707106781); /* c4 */
  170266. z11 = tmp7 + z3; /* phase 5 */
  170267. z13 = tmp7 - z3;
  170268. dataptr[5] = z13 + z2; /* phase 6 */
  170269. dataptr[3] = z13 - z2;
  170270. dataptr[1] = z11 + z4;
  170271. dataptr[7] = z11 - z4;
  170272. dataptr += DCTSIZE; /* advance pointer to next row */
  170273. }
  170274. /* Pass 2: process columns. */
  170275. dataptr = data;
  170276. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  170277. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  170278. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  170279. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  170280. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  170281. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  170282. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  170283. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  170284. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  170285. /* Even part */
  170286. tmp10 = tmp0 + tmp3; /* phase 2 */
  170287. tmp13 = tmp0 - tmp3;
  170288. tmp11 = tmp1 + tmp2;
  170289. tmp12 = tmp1 - tmp2;
  170290. dataptr[DCTSIZE*0] = tmp10 + tmp11; /* phase 3 */
  170291. dataptr[DCTSIZE*4] = tmp10 - tmp11;
  170292. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_707106781); /* c4 */
  170293. dataptr[DCTSIZE*2] = tmp13 + z1; /* phase 5 */
  170294. dataptr[DCTSIZE*6] = tmp13 - z1;
  170295. /* Odd part */
  170296. tmp10 = tmp4 + tmp5; /* phase 2 */
  170297. tmp11 = tmp5 + tmp6;
  170298. tmp12 = tmp6 + tmp7;
  170299. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  170300. z5 = MULTIPLY(tmp10 - tmp12, FIX_0_382683433); /* c6 */
  170301. z2 = MULTIPLY(tmp10, FIX_0_541196100) + z5; /* c2-c6 */
  170302. z4 = MULTIPLY(tmp12, FIX_1_306562965) + z5; /* c2+c6 */
  170303. z3 = MULTIPLY(tmp11, FIX_0_707106781); /* c4 */
  170304. z11 = tmp7 + z3; /* phase 5 */
  170305. z13 = tmp7 - z3;
  170306. dataptr[DCTSIZE*5] = z13 + z2; /* phase 6 */
  170307. dataptr[DCTSIZE*3] = z13 - z2;
  170308. dataptr[DCTSIZE*1] = z11 + z4;
  170309. dataptr[DCTSIZE*7] = z11 - z4;
  170310. dataptr++; /* advance pointer to next column */
  170311. }
  170312. }
  170313. #endif /* DCT_IFAST_SUPPORTED */
  170314. /********* End of inlined file: jfdctfst.c *********/
  170315. #undef FIX_0_541196100
  170316. /********* Start of inlined file: jidctflt.c *********/
  170317. #define JPEG_INTERNALS
  170318. #ifdef DCT_FLOAT_SUPPORTED
  170319. /*
  170320. * This module is specialized to the case DCTSIZE = 8.
  170321. */
  170322. #if DCTSIZE != 8
  170323. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  170324. #endif
  170325. /* Dequantize a coefficient by multiplying it by the multiplier-table
  170326. * entry; produce a float result.
  170327. */
  170328. #define DEQUANTIZE(coef,quantval) (((FAST_FLOAT) (coef)) * (quantval))
  170329. /*
  170330. * Perform dequantization and inverse DCT on one block of coefficients.
  170331. */
  170332. GLOBAL(void)
  170333. jpeg_idct_float (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  170334. JCOEFPTR coef_block,
  170335. JSAMPARRAY output_buf, JDIMENSION output_col)
  170336. {
  170337. FAST_FLOAT tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  170338. FAST_FLOAT tmp10, tmp11, tmp12, tmp13;
  170339. FAST_FLOAT z5, z10, z11, z12, z13;
  170340. JCOEFPTR inptr;
  170341. FLOAT_MULT_TYPE * quantptr;
  170342. FAST_FLOAT * wsptr;
  170343. JSAMPROW outptr;
  170344. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  170345. int ctr;
  170346. FAST_FLOAT workspace[DCTSIZE2]; /* buffers data between passes */
  170347. SHIFT_TEMPS
  170348. /* Pass 1: process columns from input, store into work array. */
  170349. inptr = coef_block;
  170350. quantptr = (FLOAT_MULT_TYPE *) compptr->dct_table;
  170351. wsptr = workspace;
  170352. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  170353. /* Due to quantization, we will usually find that many of the input
  170354. * coefficients are zero, especially the AC terms. We can exploit this
  170355. * by short-circuiting the IDCT calculation for any column in which all
  170356. * the AC terms are zero. In that case each output is equal to the
  170357. * DC coefficient (with scale factor as needed).
  170358. * With typical images and quantization tables, half or more of the
  170359. * column DCT calculations can be simplified this way.
  170360. */
  170361. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  170362. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  170363. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  170364. inptr[DCTSIZE*7] == 0) {
  170365. /* AC terms all zero */
  170366. FAST_FLOAT dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  170367. wsptr[DCTSIZE*0] = dcval;
  170368. wsptr[DCTSIZE*1] = dcval;
  170369. wsptr[DCTSIZE*2] = dcval;
  170370. wsptr[DCTSIZE*3] = dcval;
  170371. wsptr[DCTSIZE*4] = dcval;
  170372. wsptr[DCTSIZE*5] = dcval;
  170373. wsptr[DCTSIZE*6] = dcval;
  170374. wsptr[DCTSIZE*7] = dcval;
  170375. inptr++; /* advance pointers to next column */
  170376. quantptr++;
  170377. wsptr++;
  170378. continue;
  170379. }
  170380. /* Even part */
  170381. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  170382. tmp1 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  170383. tmp2 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  170384. tmp3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  170385. tmp10 = tmp0 + tmp2; /* phase 3 */
  170386. tmp11 = tmp0 - tmp2;
  170387. tmp13 = tmp1 + tmp3; /* phases 5-3 */
  170388. tmp12 = (tmp1 - tmp3) * ((FAST_FLOAT) 1.414213562) - tmp13; /* 2*c4 */
  170389. tmp0 = tmp10 + tmp13; /* phase 2 */
  170390. tmp3 = tmp10 - tmp13;
  170391. tmp1 = tmp11 + tmp12;
  170392. tmp2 = tmp11 - tmp12;
  170393. /* Odd part */
  170394. tmp4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  170395. tmp5 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  170396. tmp6 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  170397. tmp7 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  170398. z13 = tmp6 + tmp5; /* phase 6 */
  170399. z10 = tmp6 - tmp5;
  170400. z11 = tmp4 + tmp7;
  170401. z12 = tmp4 - tmp7;
  170402. tmp7 = z11 + z13; /* phase 5 */
  170403. tmp11 = (z11 - z13) * ((FAST_FLOAT) 1.414213562); /* 2*c4 */
  170404. z5 = (z10 + z12) * ((FAST_FLOAT) 1.847759065); /* 2*c2 */
  170405. tmp10 = ((FAST_FLOAT) 1.082392200) * z12 - z5; /* 2*(c2-c6) */
  170406. tmp12 = ((FAST_FLOAT) -2.613125930) * z10 + z5; /* -2*(c2+c6) */
  170407. tmp6 = tmp12 - tmp7; /* phase 2 */
  170408. tmp5 = tmp11 - tmp6;
  170409. tmp4 = tmp10 + tmp5;
  170410. wsptr[DCTSIZE*0] = tmp0 + tmp7;
  170411. wsptr[DCTSIZE*7] = tmp0 - tmp7;
  170412. wsptr[DCTSIZE*1] = tmp1 + tmp6;
  170413. wsptr[DCTSIZE*6] = tmp1 - tmp6;
  170414. wsptr[DCTSIZE*2] = tmp2 + tmp5;
  170415. wsptr[DCTSIZE*5] = tmp2 - tmp5;
  170416. wsptr[DCTSIZE*4] = tmp3 + tmp4;
  170417. wsptr[DCTSIZE*3] = tmp3 - tmp4;
  170418. inptr++; /* advance pointers to next column */
  170419. quantptr++;
  170420. wsptr++;
  170421. }
  170422. /* Pass 2: process rows from work array, store into output array. */
  170423. /* Note that we must descale the results by a factor of 8 == 2**3. */
  170424. wsptr = workspace;
  170425. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  170426. outptr = output_buf[ctr] + output_col;
  170427. /* Rows of zeroes can be exploited in the same way as we did with columns.
  170428. * However, the column calculation has created many nonzero AC terms, so
  170429. * the simplification applies less often (typically 5% to 10% of the time).
  170430. * And testing floats for zero is relatively expensive, so we don't bother.
  170431. */
  170432. /* Even part */
  170433. tmp10 = wsptr[0] + wsptr[4];
  170434. tmp11 = wsptr[0] - wsptr[4];
  170435. tmp13 = wsptr[2] + wsptr[6];
  170436. tmp12 = (wsptr[2] - wsptr[6]) * ((FAST_FLOAT) 1.414213562) - tmp13;
  170437. tmp0 = tmp10 + tmp13;
  170438. tmp3 = tmp10 - tmp13;
  170439. tmp1 = tmp11 + tmp12;
  170440. tmp2 = tmp11 - tmp12;
  170441. /* Odd part */
  170442. z13 = wsptr[5] + wsptr[3];
  170443. z10 = wsptr[5] - wsptr[3];
  170444. z11 = wsptr[1] + wsptr[7];
  170445. z12 = wsptr[1] - wsptr[7];
  170446. tmp7 = z11 + z13;
  170447. tmp11 = (z11 - z13) * ((FAST_FLOAT) 1.414213562);
  170448. z5 = (z10 + z12) * ((FAST_FLOAT) 1.847759065); /* 2*c2 */
  170449. tmp10 = ((FAST_FLOAT) 1.082392200) * z12 - z5; /* 2*(c2-c6) */
  170450. tmp12 = ((FAST_FLOAT) -2.613125930) * z10 + z5; /* -2*(c2+c6) */
  170451. tmp6 = tmp12 - tmp7;
  170452. tmp5 = tmp11 - tmp6;
  170453. tmp4 = tmp10 + tmp5;
  170454. /* Final output stage: scale down by a factor of 8 and range-limit */
  170455. outptr[0] = range_limit[(int) DESCALE((INT32) (tmp0 + tmp7), 3)
  170456. & RANGE_MASK];
  170457. outptr[7] = range_limit[(int) DESCALE((INT32) (tmp0 - tmp7), 3)
  170458. & RANGE_MASK];
  170459. outptr[1] = range_limit[(int) DESCALE((INT32) (tmp1 + tmp6), 3)
  170460. & RANGE_MASK];
  170461. outptr[6] = range_limit[(int) DESCALE((INT32) (tmp1 - tmp6), 3)
  170462. & RANGE_MASK];
  170463. outptr[2] = range_limit[(int) DESCALE((INT32) (tmp2 + tmp5), 3)
  170464. & RANGE_MASK];
  170465. outptr[5] = range_limit[(int) DESCALE((INT32) (tmp2 - tmp5), 3)
  170466. & RANGE_MASK];
  170467. outptr[4] = range_limit[(int) DESCALE((INT32) (tmp3 + tmp4), 3)
  170468. & RANGE_MASK];
  170469. outptr[3] = range_limit[(int) DESCALE((INT32) (tmp3 - tmp4), 3)
  170470. & RANGE_MASK];
  170471. wsptr += DCTSIZE; /* advance pointer to next row */
  170472. }
  170473. }
  170474. #endif /* DCT_FLOAT_SUPPORTED */
  170475. /********* End of inlined file: jidctflt.c *********/
  170476. #undef CONST_BITS
  170477. #undef FIX_1_847759065
  170478. #undef MULTIPLY
  170479. #undef DEQUANTIZE
  170480. #undef DESCALE
  170481. /********* Start of inlined file: jidctfst.c *********/
  170482. #define JPEG_INTERNALS
  170483. #ifdef DCT_IFAST_SUPPORTED
  170484. /*
  170485. * This module is specialized to the case DCTSIZE = 8.
  170486. */
  170487. #if DCTSIZE != 8
  170488. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  170489. #endif
  170490. /* Scaling decisions are generally the same as in the LL&M algorithm;
  170491. * see jidctint.c for more details. However, we choose to descale
  170492. * (right shift) multiplication products as soon as they are formed,
  170493. * rather than carrying additional fractional bits into subsequent additions.
  170494. * This compromises accuracy slightly, but it lets us save a few shifts.
  170495. * More importantly, 16-bit arithmetic is then adequate (for 8-bit samples)
  170496. * everywhere except in the multiplications proper; this saves a good deal
  170497. * of work on 16-bit-int machines.
  170498. *
  170499. * The dequantized coefficients are not integers because the AA&N scaling
  170500. * factors have been incorporated. We represent them scaled up by PASS1_BITS,
  170501. * so that the first and second IDCT rounds have the same input scaling.
  170502. * For 8-bit JSAMPLEs, we choose IFAST_SCALE_BITS = PASS1_BITS so as to
  170503. * avoid a descaling shift; this compromises accuracy rather drastically
  170504. * for small quantization table entries, but it saves a lot of shifts.
  170505. * For 12-bit JSAMPLEs, there's no hope of using 16x16 multiplies anyway,
  170506. * so we use a much larger scaling factor to preserve accuracy.
  170507. *
  170508. * A final compromise is to represent the multiplicative constants to only
  170509. * 8 fractional bits, rather than 13. This saves some shifting work on some
  170510. * machines, and may also reduce the cost of multiplication (since there
  170511. * are fewer one-bits in the constants).
  170512. */
  170513. #if BITS_IN_JSAMPLE == 8
  170514. #define CONST_BITS 8
  170515. #define PASS1_BITS 2
  170516. #else
  170517. #define CONST_BITS 8
  170518. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  170519. #endif
  170520. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  170521. * causing a lot of useless floating-point operations at run time.
  170522. * To get around this we use the following pre-calculated constants.
  170523. * If you change CONST_BITS you may want to add appropriate values.
  170524. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  170525. */
  170526. #if CONST_BITS == 8
  170527. #define FIX_1_082392200 ((INT32) 277) /* FIX(1.082392200) */
  170528. #define FIX_1_414213562 ((INT32) 362) /* FIX(1.414213562) */
  170529. #define FIX_1_847759065 ((INT32) 473) /* FIX(1.847759065) */
  170530. #define FIX_2_613125930 ((INT32) 669) /* FIX(2.613125930) */
  170531. #else
  170532. #define FIX_1_082392200 FIX(1.082392200)
  170533. #define FIX_1_414213562 FIX(1.414213562)
  170534. #define FIX_1_847759065 FIX(1.847759065)
  170535. #define FIX_2_613125930 FIX(2.613125930)
  170536. #endif
  170537. /* We can gain a little more speed, with a further compromise in accuracy,
  170538. * by omitting the addition in a descaling shift. This yields an incorrectly
  170539. * rounded result half the time...
  170540. */
  170541. #ifndef USE_ACCURATE_ROUNDING
  170542. #undef DESCALE
  170543. #define DESCALE(x,n) RIGHT_SHIFT(x, n)
  170544. #endif
  170545. /* Multiply a DCTELEM variable by an INT32 constant, and immediately
  170546. * descale to yield a DCTELEM result.
  170547. */
  170548. #define MULTIPLY(var,const) ((DCTELEM) DESCALE((var) * (const), CONST_BITS))
  170549. /* Dequantize a coefficient by multiplying it by the multiplier-table
  170550. * entry; produce a DCTELEM result. For 8-bit data a 16x16->16
  170551. * multiplication will do. For 12-bit data, the multiplier table is
  170552. * declared INT32, so a 32-bit multiply will be used.
  170553. */
  170554. #if BITS_IN_JSAMPLE == 8
  170555. #define DEQUANTIZE(coef,quantval) (((IFAST_MULT_TYPE) (coef)) * (quantval))
  170556. #else
  170557. #define DEQUANTIZE(coef,quantval) \
  170558. DESCALE((coef)*(quantval), IFAST_SCALE_BITS-PASS1_BITS)
  170559. #endif
  170560. /* Like DESCALE, but applies to a DCTELEM and produces an int.
  170561. * We assume that int right shift is unsigned if INT32 right shift is.
  170562. */
  170563. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  170564. #define ISHIFT_TEMPS DCTELEM ishift_temp;
  170565. #if BITS_IN_JSAMPLE == 8
  170566. #define DCTELEMBITS 16 /* DCTELEM may be 16 or 32 bits */
  170567. #else
  170568. #define DCTELEMBITS 32 /* DCTELEM must be 32 bits */
  170569. #endif
  170570. #define IRIGHT_SHIFT(x,shft) \
  170571. ((ishift_temp = (x)) < 0 ? \
  170572. (ishift_temp >> (shft)) | ((~((DCTELEM) 0)) << (DCTELEMBITS-(shft))) : \
  170573. (ishift_temp >> (shft)))
  170574. #else
  170575. #define ISHIFT_TEMPS
  170576. #define IRIGHT_SHIFT(x,shft) ((x) >> (shft))
  170577. #endif
  170578. #ifdef USE_ACCURATE_ROUNDING
  170579. #define IDESCALE(x,n) ((int) IRIGHT_SHIFT((x) + (1 << ((n)-1)), n))
  170580. #else
  170581. #define IDESCALE(x,n) ((int) IRIGHT_SHIFT(x, n))
  170582. #endif
  170583. /*
  170584. * Perform dequantization and inverse DCT on one block of coefficients.
  170585. */
  170586. GLOBAL(void)
  170587. jpeg_idct_ifast (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  170588. JCOEFPTR coef_block,
  170589. JSAMPARRAY output_buf, JDIMENSION output_col)
  170590. {
  170591. DCTELEM tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  170592. DCTELEM tmp10, tmp11, tmp12, tmp13;
  170593. DCTELEM z5, z10, z11, z12, z13;
  170594. JCOEFPTR inptr;
  170595. IFAST_MULT_TYPE * quantptr;
  170596. int * wsptr;
  170597. JSAMPROW outptr;
  170598. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  170599. int ctr;
  170600. int workspace[DCTSIZE2]; /* buffers data between passes */
  170601. SHIFT_TEMPS /* for DESCALE */
  170602. ISHIFT_TEMPS /* for IDESCALE */
  170603. /* Pass 1: process columns from input, store into work array. */
  170604. inptr = coef_block;
  170605. quantptr = (IFAST_MULT_TYPE *) compptr->dct_table;
  170606. wsptr = workspace;
  170607. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  170608. /* Due to quantization, we will usually find that many of the input
  170609. * coefficients are zero, especially the AC terms. We can exploit this
  170610. * by short-circuiting the IDCT calculation for any column in which all
  170611. * the AC terms are zero. In that case each output is equal to the
  170612. * DC coefficient (with scale factor as needed).
  170613. * With typical images and quantization tables, half or more of the
  170614. * column DCT calculations can be simplified this way.
  170615. */
  170616. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  170617. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  170618. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  170619. inptr[DCTSIZE*7] == 0) {
  170620. /* AC terms all zero */
  170621. int dcval = (int) DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  170622. wsptr[DCTSIZE*0] = dcval;
  170623. wsptr[DCTSIZE*1] = dcval;
  170624. wsptr[DCTSIZE*2] = dcval;
  170625. wsptr[DCTSIZE*3] = dcval;
  170626. wsptr[DCTSIZE*4] = dcval;
  170627. wsptr[DCTSIZE*5] = dcval;
  170628. wsptr[DCTSIZE*6] = dcval;
  170629. wsptr[DCTSIZE*7] = dcval;
  170630. inptr++; /* advance pointers to next column */
  170631. quantptr++;
  170632. wsptr++;
  170633. continue;
  170634. }
  170635. /* Even part */
  170636. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  170637. tmp1 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  170638. tmp2 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  170639. tmp3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  170640. tmp10 = tmp0 + tmp2; /* phase 3 */
  170641. tmp11 = tmp0 - tmp2;
  170642. tmp13 = tmp1 + tmp3; /* phases 5-3 */
  170643. tmp12 = MULTIPLY(tmp1 - tmp3, FIX_1_414213562) - tmp13; /* 2*c4 */
  170644. tmp0 = tmp10 + tmp13; /* phase 2 */
  170645. tmp3 = tmp10 - tmp13;
  170646. tmp1 = tmp11 + tmp12;
  170647. tmp2 = tmp11 - tmp12;
  170648. /* Odd part */
  170649. tmp4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  170650. tmp5 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  170651. tmp6 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  170652. tmp7 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  170653. z13 = tmp6 + tmp5; /* phase 6 */
  170654. z10 = tmp6 - tmp5;
  170655. z11 = tmp4 + tmp7;
  170656. z12 = tmp4 - tmp7;
  170657. tmp7 = z11 + z13; /* phase 5 */
  170658. tmp11 = MULTIPLY(z11 - z13, FIX_1_414213562); /* 2*c4 */
  170659. z5 = MULTIPLY(z10 + z12, FIX_1_847759065); /* 2*c2 */
  170660. tmp10 = MULTIPLY(z12, FIX_1_082392200) - z5; /* 2*(c2-c6) */
  170661. tmp12 = MULTIPLY(z10, - FIX_2_613125930) + z5; /* -2*(c2+c6) */
  170662. tmp6 = tmp12 - tmp7; /* phase 2 */
  170663. tmp5 = tmp11 - tmp6;
  170664. tmp4 = tmp10 + tmp5;
  170665. wsptr[DCTSIZE*0] = (int) (tmp0 + tmp7);
  170666. wsptr[DCTSIZE*7] = (int) (tmp0 - tmp7);
  170667. wsptr[DCTSIZE*1] = (int) (tmp1 + tmp6);
  170668. wsptr[DCTSIZE*6] = (int) (tmp1 - tmp6);
  170669. wsptr[DCTSIZE*2] = (int) (tmp2 + tmp5);
  170670. wsptr[DCTSIZE*5] = (int) (tmp2 - tmp5);
  170671. wsptr[DCTSIZE*4] = (int) (tmp3 + tmp4);
  170672. wsptr[DCTSIZE*3] = (int) (tmp3 - tmp4);
  170673. inptr++; /* advance pointers to next column */
  170674. quantptr++;
  170675. wsptr++;
  170676. }
  170677. /* Pass 2: process rows from work array, store into output array. */
  170678. /* Note that we must descale the results by a factor of 8 == 2**3, */
  170679. /* and also undo the PASS1_BITS scaling. */
  170680. wsptr = workspace;
  170681. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  170682. outptr = output_buf[ctr] + output_col;
  170683. /* Rows of zeroes can be exploited in the same way as we did with columns.
  170684. * However, the column calculation has created many nonzero AC terms, so
  170685. * the simplification applies less often (typically 5% to 10% of the time).
  170686. * On machines with very fast multiplication, it's possible that the
  170687. * test takes more time than it's worth. In that case this section
  170688. * may be commented out.
  170689. */
  170690. #ifndef NO_ZERO_ROW_TEST
  170691. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 && wsptr[4] == 0 &&
  170692. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  170693. /* AC terms all zero */
  170694. JSAMPLE dcval = range_limit[IDESCALE(wsptr[0], PASS1_BITS+3)
  170695. & RANGE_MASK];
  170696. outptr[0] = dcval;
  170697. outptr[1] = dcval;
  170698. outptr[2] = dcval;
  170699. outptr[3] = dcval;
  170700. outptr[4] = dcval;
  170701. outptr[5] = dcval;
  170702. outptr[6] = dcval;
  170703. outptr[7] = dcval;
  170704. wsptr += DCTSIZE; /* advance pointer to next row */
  170705. continue;
  170706. }
  170707. #endif
  170708. /* Even part */
  170709. tmp10 = ((DCTELEM) wsptr[0] + (DCTELEM) wsptr[4]);
  170710. tmp11 = ((DCTELEM) wsptr[0] - (DCTELEM) wsptr[4]);
  170711. tmp13 = ((DCTELEM) wsptr[2] + (DCTELEM) wsptr[6]);
  170712. tmp12 = MULTIPLY((DCTELEM) wsptr[2] - (DCTELEM) wsptr[6], FIX_1_414213562)
  170713. - tmp13;
  170714. tmp0 = tmp10 + tmp13;
  170715. tmp3 = tmp10 - tmp13;
  170716. tmp1 = tmp11 + tmp12;
  170717. tmp2 = tmp11 - tmp12;
  170718. /* Odd part */
  170719. z13 = (DCTELEM) wsptr[5] + (DCTELEM) wsptr[3];
  170720. z10 = (DCTELEM) wsptr[5] - (DCTELEM) wsptr[3];
  170721. z11 = (DCTELEM) wsptr[1] + (DCTELEM) wsptr[7];
  170722. z12 = (DCTELEM) wsptr[1] - (DCTELEM) wsptr[7];
  170723. tmp7 = z11 + z13; /* phase 5 */
  170724. tmp11 = MULTIPLY(z11 - z13, FIX_1_414213562); /* 2*c4 */
  170725. z5 = MULTIPLY(z10 + z12, FIX_1_847759065); /* 2*c2 */
  170726. tmp10 = MULTIPLY(z12, FIX_1_082392200) - z5; /* 2*(c2-c6) */
  170727. tmp12 = MULTIPLY(z10, - FIX_2_613125930) + z5; /* -2*(c2+c6) */
  170728. tmp6 = tmp12 - tmp7; /* phase 2 */
  170729. tmp5 = tmp11 - tmp6;
  170730. tmp4 = tmp10 + tmp5;
  170731. /* Final output stage: scale down by a factor of 8 and range-limit */
  170732. outptr[0] = range_limit[IDESCALE(tmp0 + tmp7, PASS1_BITS+3)
  170733. & RANGE_MASK];
  170734. outptr[7] = range_limit[IDESCALE(tmp0 - tmp7, PASS1_BITS+3)
  170735. & RANGE_MASK];
  170736. outptr[1] = range_limit[IDESCALE(tmp1 + tmp6, PASS1_BITS+3)
  170737. & RANGE_MASK];
  170738. outptr[6] = range_limit[IDESCALE(tmp1 - tmp6, PASS1_BITS+3)
  170739. & RANGE_MASK];
  170740. outptr[2] = range_limit[IDESCALE(tmp2 + tmp5, PASS1_BITS+3)
  170741. & RANGE_MASK];
  170742. outptr[5] = range_limit[IDESCALE(tmp2 - tmp5, PASS1_BITS+3)
  170743. & RANGE_MASK];
  170744. outptr[4] = range_limit[IDESCALE(tmp3 + tmp4, PASS1_BITS+3)
  170745. & RANGE_MASK];
  170746. outptr[3] = range_limit[IDESCALE(tmp3 - tmp4, PASS1_BITS+3)
  170747. & RANGE_MASK];
  170748. wsptr += DCTSIZE; /* advance pointer to next row */
  170749. }
  170750. }
  170751. #endif /* DCT_IFAST_SUPPORTED */
  170752. /********* End of inlined file: jidctfst.c *********/
  170753. #undef CONST_BITS
  170754. #undef FIX_1_847759065
  170755. #undef MULTIPLY
  170756. #undef DEQUANTIZE
  170757. /********* Start of inlined file: jidctint.c *********/
  170758. #define JPEG_INTERNALS
  170759. #ifdef DCT_ISLOW_SUPPORTED
  170760. /*
  170761. * This module is specialized to the case DCTSIZE = 8.
  170762. */
  170763. #if DCTSIZE != 8
  170764. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  170765. #endif
  170766. /*
  170767. * The poop on this scaling stuff is as follows:
  170768. *
  170769. * Each 1-D IDCT step produces outputs which are a factor of sqrt(N)
  170770. * larger than the true IDCT outputs. The final outputs are therefore
  170771. * a factor of N larger than desired; since N=8 this can be cured by
  170772. * a simple right shift at the end of the algorithm. The advantage of
  170773. * this arrangement is that we save two multiplications per 1-D IDCT,
  170774. * because the y0 and y4 inputs need not be divided by sqrt(N).
  170775. *
  170776. * We have to do addition and subtraction of the integer inputs, which
  170777. * is no problem, and multiplication by fractional constants, which is
  170778. * a problem to do in integer arithmetic. We multiply all the constants
  170779. * by CONST_SCALE and convert them to integer constants (thus retaining
  170780. * CONST_BITS bits of precision in the constants). After doing a
  170781. * multiplication we have to divide the product by CONST_SCALE, with proper
  170782. * rounding, to produce the correct output. This division can be done
  170783. * cheaply as a right shift of CONST_BITS bits. We postpone shifting
  170784. * as long as possible so that partial sums can be added together with
  170785. * full fractional precision.
  170786. *
  170787. * The outputs of the first pass are scaled up by PASS1_BITS bits so that
  170788. * they are represented to better-than-integral precision. These outputs
  170789. * require BITS_IN_JSAMPLE + PASS1_BITS + 3 bits; this fits in a 16-bit word
  170790. * with the recommended scaling. (To scale up 12-bit sample data further, an
  170791. * intermediate INT32 array would be needed.)
  170792. *
  170793. * To avoid overflow of the 32-bit intermediate results in pass 2, we must
  170794. * have BITS_IN_JSAMPLE + CONST_BITS + PASS1_BITS <= 26. Error analysis
  170795. * shows that the values given below are the most effective.
  170796. */
  170797. #if BITS_IN_JSAMPLE == 8
  170798. #define CONST_BITS 13
  170799. #define PASS1_BITS 2
  170800. #else
  170801. #define CONST_BITS 13
  170802. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  170803. #endif
  170804. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  170805. * causing a lot of useless floating-point operations at run time.
  170806. * To get around this we use the following pre-calculated constants.
  170807. * If you change CONST_BITS you may want to add appropriate values.
  170808. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  170809. */
  170810. #if CONST_BITS == 13
  170811. #define FIX_0_298631336 ((INT32) 2446) /* FIX(0.298631336) */
  170812. #define FIX_0_390180644 ((INT32) 3196) /* FIX(0.390180644) */
  170813. #define FIX_0_541196100 ((INT32) 4433) /* FIX(0.541196100) */
  170814. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  170815. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  170816. #define FIX_1_175875602 ((INT32) 9633) /* FIX(1.175875602) */
  170817. #define FIX_1_501321110 ((INT32) 12299) /* FIX(1.501321110) */
  170818. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  170819. #define FIX_1_961570560 ((INT32) 16069) /* FIX(1.961570560) */
  170820. #define FIX_2_053119869 ((INT32) 16819) /* FIX(2.053119869) */
  170821. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  170822. #define FIX_3_072711026 ((INT32) 25172) /* FIX(3.072711026) */
  170823. #else
  170824. #define FIX_0_298631336 FIX(0.298631336)
  170825. #define FIX_0_390180644 FIX(0.390180644)
  170826. #define FIX_0_541196100 FIX(0.541196100)
  170827. #define FIX_0_765366865 FIX(0.765366865)
  170828. #define FIX_0_899976223 FIX(0.899976223)
  170829. #define FIX_1_175875602 FIX(1.175875602)
  170830. #define FIX_1_501321110 FIX(1.501321110)
  170831. #define FIX_1_847759065 FIX(1.847759065)
  170832. #define FIX_1_961570560 FIX(1.961570560)
  170833. #define FIX_2_053119869 FIX(2.053119869)
  170834. #define FIX_2_562915447 FIX(2.562915447)
  170835. #define FIX_3_072711026 FIX(3.072711026)
  170836. #endif
  170837. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  170838. * For 8-bit samples with the recommended scaling, all the variable
  170839. * and constant values involved are no more than 16 bits wide, so a
  170840. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  170841. * For 12-bit samples, a full 32-bit multiplication will be needed.
  170842. */
  170843. #if BITS_IN_JSAMPLE == 8
  170844. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  170845. #else
  170846. #define MULTIPLY(var,const) ((var) * (const))
  170847. #endif
  170848. /* Dequantize a coefficient by multiplying it by the multiplier-table
  170849. * entry; produce an int result. In this module, both inputs and result
  170850. * are 16 bits or less, so either int or short multiply will work.
  170851. */
  170852. #define DEQUANTIZE(coef,quantval) (((ISLOW_MULT_TYPE) (coef)) * (quantval))
  170853. /*
  170854. * Perform dequantization and inverse DCT on one block of coefficients.
  170855. */
  170856. GLOBAL(void)
  170857. jpeg_idct_islow (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  170858. JCOEFPTR coef_block,
  170859. JSAMPARRAY output_buf, JDIMENSION output_col)
  170860. {
  170861. INT32 tmp0, tmp1, tmp2, tmp3;
  170862. INT32 tmp10, tmp11, tmp12, tmp13;
  170863. INT32 z1, z2, z3, z4, z5;
  170864. JCOEFPTR inptr;
  170865. ISLOW_MULT_TYPE * quantptr;
  170866. int * wsptr;
  170867. JSAMPROW outptr;
  170868. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  170869. int ctr;
  170870. int workspace[DCTSIZE2]; /* buffers data between passes */
  170871. SHIFT_TEMPS
  170872. /* Pass 1: process columns from input, store into work array. */
  170873. /* Note results are scaled up by sqrt(8) compared to a true IDCT; */
  170874. /* furthermore, we scale the results by 2**PASS1_BITS. */
  170875. inptr = coef_block;
  170876. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  170877. wsptr = workspace;
  170878. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  170879. /* Due to quantization, we will usually find that many of the input
  170880. * coefficients are zero, especially the AC terms. We can exploit this
  170881. * by short-circuiting the IDCT calculation for any column in which all
  170882. * the AC terms are zero. In that case each output is equal to the
  170883. * DC coefficient (with scale factor as needed).
  170884. * With typical images and quantization tables, half or more of the
  170885. * column DCT calculations can be simplified this way.
  170886. */
  170887. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  170888. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  170889. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  170890. inptr[DCTSIZE*7] == 0) {
  170891. /* AC terms all zero */
  170892. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  170893. wsptr[DCTSIZE*0] = dcval;
  170894. wsptr[DCTSIZE*1] = dcval;
  170895. wsptr[DCTSIZE*2] = dcval;
  170896. wsptr[DCTSIZE*3] = dcval;
  170897. wsptr[DCTSIZE*4] = dcval;
  170898. wsptr[DCTSIZE*5] = dcval;
  170899. wsptr[DCTSIZE*6] = dcval;
  170900. wsptr[DCTSIZE*7] = dcval;
  170901. inptr++; /* advance pointers to next column */
  170902. quantptr++;
  170903. wsptr++;
  170904. continue;
  170905. }
  170906. /* Even part: reverse the even part of the forward DCT. */
  170907. /* The rotator is sqrt(2)*c(-6). */
  170908. z2 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  170909. z3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  170910. z1 = MULTIPLY(z2 + z3, FIX_0_541196100);
  170911. tmp2 = z1 + MULTIPLY(z3, - FIX_1_847759065);
  170912. tmp3 = z1 + MULTIPLY(z2, FIX_0_765366865);
  170913. z2 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  170914. z3 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  170915. tmp0 = (z2 + z3) << CONST_BITS;
  170916. tmp1 = (z2 - z3) << CONST_BITS;
  170917. tmp10 = tmp0 + tmp3;
  170918. tmp13 = tmp0 - tmp3;
  170919. tmp11 = tmp1 + tmp2;
  170920. tmp12 = tmp1 - tmp2;
  170921. /* Odd part per figure 8; the matrix is unitary and hence its
  170922. * transpose is its inverse. i0..i3 are y7,y5,y3,y1 respectively.
  170923. */
  170924. tmp0 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  170925. tmp1 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  170926. tmp2 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  170927. tmp3 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  170928. z1 = tmp0 + tmp3;
  170929. z2 = tmp1 + tmp2;
  170930. z3 = tmp0 + tmp2;
  170931. z4 = tmp1 + tmp3;
  170932. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  170933. tmp0 = MULTIPLY(tmp0, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  170934. tmp1 = MULTIPLY(tmp1, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  170935. tmp2 = MULTIPLY(tmp2, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  170936. tmp3 = MULTIPLY(tmp3, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  170937. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  170938. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  170939. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  170940. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  170941. z3 += z5;
  170942. z4 += z5;
  170943. tmp0 += z1 + z3;
  170944. tmp1 += z2 + z4;
  170945. tmp2 += z2 + z3;
  170946. tmp3 += z1 + z4;
  170947. /* Final output stage: inputs are tmp10..tmp13, tmp0..tmp3 */
  170948. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp3, CONST_BITS-PASS1_BITS);
  170949. wsptr[DCTSIZE*7] = (int) DESCALE(tmp10 - tmp3, CONST_BITS-PASS1_BITS);
  170950. wsptr[DCTSIZE*1] = (int) DESCALE(tmp11 + tmp2, CONST_BITS-PASS1_BITS);
  170951. wsptr[DCTSIZE*6] = (int) DESCALE(tmp11 - tmp2, CONST_BITS-PASS1_BITS);
  170952. wsptr[DCTSIZE*2] = (int) DESCALE(tmp12 + tmp1, CONST_BITS-PASS1_BITS);
  170953. wsptr[DCTSIZE*5] = (int) DESCALE(tmp12 - tmp1, CONST_BITS-PASS1_BITS);
  170954. wsptr[DCTSIZE*3] = (int) DESCALE(tmp13 + tmp0, CONST_BITS-PASS1_BITS);
  170955. wsptr[DCTSIZE*4] = (int) DESCALE(tmp13 - tmp0, CONST_BITS-PASS1_BITS);
  170956. inptr++; /* advance pointers to next column */
  170957. quantptr++;
  170958. wsptr++;
  170959. }
  170960. /* Pass 2: process rows from work array, store into output array. */
  170961. /* Note that we must descale the results by a factor of 8 == 2**3, */
  170962. /* and also undo the PASS1_BITS scaling. */
  170963. wsptr = workspace;
  170964. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  170965. outptr = output_buf[ctr] + output_col;
  170966. /* Rows of zeroes can be exploited in the same way as we did with columns.
  170967. * However, the column calculation has created many nonzero AC terms, so
  170968. * the simplification applies less often (typically 5% to 10% of the time).
  170969. * On machines with very fast multiplication, it's possible that the
  170970. * test takes more time than it's worth. In that case this section
  170971. * may be commented out.
  170972. */
  170973. #ifndef NO_ZERO_ROW_TEST
  170974. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 && wsptr[4] == 0 &&
  170975. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  170976. /* AC terms all zero */
  170977. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  170978. & RANGE_MASK];
  170979. outptr[0] = dcval;
  170980. outptr[1] = dcval;
  170981. outptr[2] = dcval;
  170982. outptr[3] = dcval;
  170983. outptr[4] = dcval;
  170984. outptr[5] = dcval;
  170985. outptr[6] = dcval;
  170986. outptr[7] = dcval;
  170987. wsptr += DCTSIZE; /* advance pointer to next row */
  170988. continue;
  170989. }
  170990. #endif
  170991. /* Even part: reverse the even part of the forward DCT. */
  170992. /* The rotator is sqrt(2)*c(-6). */
  170993. z2 = (INT32) wsptr[2];
  170994. z3 = (INT32) wsptr[6];
  170995. z1 = MULTIPLY(z2 + z3, FIX_0_541196100);
  170996. tmp2 = z1 + MULTIPLY(z3, - FIX_1_847759065);
  170997. tmp3 = z1 + MULTIPLY(z2, FIX_0_765366865);
  170998. tmp0 = ((INT32) wsptr[0] + (INT32) wsptr[4]) << CONST_BITS;
  170999. tmp1 = ((INT32) wsptr[0] - (INT32) wsptr[4]) << CONST_BITS;
  171000. tmp10 = tmp0 + tmp3;
  171001. tmp13 = tmp0 - tmp3;
  171002. tmp11 = tmp1 + tmp2;
  171003. tmp12 = tmp1 - tmp2;
  171004. /* Odd part per figure 8; the matrix is unitary and hence its
  171005. * transpose is its inverse. i0..i3 are y7,y5,y3,y1 respectively.
  171006. */
  171007. tmp0 = (INT32) wsptr[7];
  171008. tmp1 = (INT32) wsptr[5];
  171009. tmp2 = (INT32) wsptr[3];
  171010. tmp3 = (INT32) wsptr[1];
  171011. z1 = tmp0 + tmp3;
  171012. z2 = tmp1 + tmp2;
  171013. z3 = tmp0 + tmp2;
  171014. z4 = tmp1 + tmp3;
  171015. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  171016. tmp0 = MULTIPLY(tmp0, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  171017. tmp1 = MULTIPLY(tmp1, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  171018. tmp2 = MULTIPLY(tmp2, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  171019. tmp3 = MULTIPLY(tmp3, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  171020. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  171021. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  171022. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  171023. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  171024. z3 += z5;
  171025. z4 += z5;
  171026. tmp0 += z1 + z3;
  171027. tmp1 += z2 + z4;
  171028. tmp2 += z2 + z3;
  171029. tmp3 += z1 + z4;
  171030. /* Final output stage: inputs are tmp10..tmp13, tmp0..tmp3 */
  171031. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp3,
  171032. CONST_BITS+PASS1_BITS+3)
  171033. & RANGE_MASK];
  171034. outptr[7] = range_limit[(int) DESCALE(tmp10 - tmp3,
  171035. CONST_BITS+PASS1_BITS+3)
  171036. & RANGE_MASK];
  171037. outptr[1] = range_limit[(int) DESCALE(tmp11 + tmp2,
  171038. CONST_BITS+PASS1_BITS+3)
  171039. & RANGE_MASK];
  171040. outptr[6] = range_limit[(int) DESCALE(tmp11 - tmp2,
  171041. CONST_BITS+PASS1_BITS+3)
  171042. & RANGE_MASK];
  171043. outptr[2] = range_limit[(int) DESCALE(tmp12 + tmp1,
  171044. CONST_BITS+PASS1_BITS+3)
  171045. & RANGE_MASK];
  171046. outptr[5] = range_limit[(int) DESCALE(tmp12 - tmp1,
  171047. CONST_BITS+PASS1_BITS+3)
  171048. & RANGE_MASK];
  171049. outptr[3] = range_limit[(int) DESCALE(tmp13 + tmp0,
  171050. CONST_BITS+PASS1_BITS+3)
  171051. & RANGE_MASK];
  171052. outptr[4] = range_limit[(int) DESCALE(tmp13 - tmp0,
  171053. CONST_BITS+PASS1_BITS+3)
  171054. & RANGE_MASK];
  171055. wsptr += DCTSIZE; /* advance pointer to next row */
  171056. }
  171057. }
  171058. #endif /* DCT_ISLOW_SUPPORTED */
  171059. /********* End of inlined file: jidctint.c *********/
  171060. /********* Start of inlined file: jidctred.c *********/
  171061. #define JPEG_INTERNALS
  171062. #ifdef IDCT_SCALING_SUPPORTED
  171063. /*
  171064. * This module is specialized to the case DCTSIZE = 8.
  171065. */
  171066. #if DCTSIZE != 8
  171067. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  171068. #endif
  171069. /* Scaling is the same as in jidctint.c. */
  171070. #if BITS_IN_JSAMPLE == 8
  171071. #define CONST_BITS 13
  171072. #define PASS1_BITS 2
  171073. #else
  171074. #define CONST_BITS 13
  171075. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  171076. #endif
  171077. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  171078. * causing a lot of useless floating-point operations at run time.
  171079. * To get around this we use the following pre-calculated constants.
  171080. * If you change CONST_BITS you may want to add appropriate values.
  171081. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  171082. */
  171083. #if CONST_BITS == 13
  171084. #define FIX_0_211164243 ((INT32) 1730) /* FIX(0.211164243) */
  171085. #define FIX_0_509795579 ((INT32) 4176) /* FIX(0.509795579) */
  171086. #define FIX_0_601344887 ((INT32) 4926) /* FIX(0.601344887) */
  171087. #define FIX_0_720959822 ((INT32) 5906) /* FIX(0.720959822) */
  171088. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  171089. #define FIX_0_850430095 ((INT32) 6967) /* FIX(0.850430095) */
  171090. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  171091. #define FIX_1_061594337 ((INT32) 8697) /* FIX(1.061594337) */
  171092. #define FIX_1_272758580 ((INT32) 10426) /* FIX(1.272758580) */
  171093. #define FIX_1_451774981 ((INT32) 11893) /* FIX(1.451774981) */
  171094. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  171095. #define FIX_2_172734803 ((INT32) 17799) /* FIX(2.172734803) */
  171096. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  171097. #define FIX_3_624509785 ((INT32) 29692) /* FIX(3.624509785) */
  171098. #else
  171099. #define FIX_0_211164243 FIX(0.211164243)
  171100. #define FIX_0_509795579 FIX(0.509795579)
  171101. #define FIX_0_601344887 FIX(0.601344887)
  171102. #define FIX_0_720959822 FIX(0.720959822)
  171103. #define FIX_0_765366865 FIX(0.765366865)
  171104. #define FIX_0_850430095 FIX(0.850430095)
  171105. #define FIX_0_899976223 FIX(0.899976223)
  171106. #define FIX_1_061594337 FIX(1.061594337)
  171107. #define FIX_1_272758580 FIX(1.272758580)
  171108. #define FIX_1_451774981 FIX(1.451774981)
  171109. #define FIX_1_847759065 FIX(1.847759065)
  171110. #define FIX_2_172734803 FIX(2.172734803)
  171111. #define FIX_2_562915447 FIX(2.562915447)
  171112. #define FIX_3_624509785 FIX(3.624509785)
  171113. #endif
  171114. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  171115. * For 8-bit samples with the recommended scaling, all the variable
  171116. * and constant values involved are no more than 16 bits wide, so a
  171117. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  171118. * For 12-bit samples, a full 32-bit multiplication will be needed.
  171119. */
  171120. #if BITS_IN_JSAMPLE == 8
  171121. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  171122. #else
  171123. #define MULTIPLY(var,const) ((var) * (const))
  171124. #endif
  171125. /* Dequantize a coefficient by multiplying it by the multiplier-table
  171126. * entry; produce an int result. In this module, both inputs and result
  171127. * are 16 bits or less, so either int or short multiply will work.
  171128. */
  171129. #define DEQUANTIZE(coef,quantval) (((ISLOW_MULT_TYPE) (coef)) * (quantval))
  171130. /*
  171131. * Perform dequantization and inverse DCT on one block of coefficients,
  171132. * producing a reduced-size 4x4 output block.
  171133. */
  171134. GLOBAL(void)
  171135. jpeg_idct_4x4 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  171136. JCOEFPTR coef_block,
  171137. JSAMPARRAY output_buf, JDIMENSION output_col)
  171138. {
  171139. INT32 tmp0, tmp2, tmp10, tmp12;
  171140. INT32 z1, z2, z3, z4;
  171141. JCOEFPTR inptr;
  171142. ISLOW_MULT_TYPE * quantptr;
  171143. int * wsptr;
  171144. JSAMPROW outptr;
  171145. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  171146. int ctr;
  171147. int workspace[DCTSIZE*4]; /* buffers data between passes */
  171148. SHIFT_TEMPS
  171149. /* Pass 1: process columns from input, store into work array. */
  171150. inptr = coef_block;
  171151. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  171152. wsptr = workspace;
  171153. for (ctr = DCTSIZE; ctr > 0; inptr++, quantptr++, wsptr++, ctr--) {
  171154. /* Don't bother to process column 4, because second pass won't use it */
  171155. if (ctr == DCTSIZE-4)
  171156. continue;
  171157. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  171158. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*5] == 0 &&
  171159. inptr[DCTSIZE*6] == 0 && inptr[DCTSIZE*7] == 0) {
  171160. /* AC terms all zero; we need not examine term 4 for 4x4 output */
  171161. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  171162. wsptr[DCTSIZE*0] = dcval;
  171163. wsptr[DCTSIZE*1] = dcval;
  171164. wsptr[DCTSIZE*2] = dcval;
  171165. wsptr[DCTSIZE*3] = dcval;
  171166. continue;
  171167. }
  171168. /* Even part */
  171169. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  171170. tmp0 <<= (CONST_BITS+1);
  171171. z2 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  171172. z3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  171173. tmp2 = MULTIPLY(z2, FIX_1_847759065) + MULTIPLY(z3, - FIX_0_765366865);
  171174. tmp10 = tmp0 + tmp2;
  171175. tmp12 = tmp0 - tmp2;
  171176. /* Odd part */
  171177. z1 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  171178. z2 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  171179. z3 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  171180. z4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  171181. tmp0 = MULTIPLY(z1, - FIX_0_211164243) /* sqrt(2) * (c3-c1) */
  171182. + MULTIPLY(z2, FIX_1_451774981) /* sqrt(2) * (c3+c7) */
  171183. + MULTIPLY(z3, - FIX_2_172734803) /* sqrt(2) * (-c1-c5) */
  171184. + MULTIPLY(z4, FIX_1_061594337); /* sqrt(2) * (c5+c7) */
  171185. tmp2 = MULTIPLY(z1, - FIX_0_509795579) /* sqrt(2) * (c7-c5) */
  171186. + MULTIPLY(z2, - FIX_0_601344887) /* sqrt(2) * (c5-c1) */
  171187. + MULTIPLY(z3, FIX_0_899976223) /* sqrt(2) * (c3-c7) */
  171188. + MULTIPLY(z4, FIX_2_562915447); /* sqrt(2) * (c1+c3) */
  171189. /* Final output stage */
  171190. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp2, CONST_BITS-PASS1_BITS+1);
  171191. wsptr[DCTSIZE*3] = (int) DESCALE(tmp10 - tmp2, CONST_BITS-PASS1_BITS+1);
  171192. wsptr[DCTSIZE*1] = (int) DESCALE(tmp12 + tmp0, CONST_BITS-PASS1_BITS+1);
  171193. wsptr[DCTSIZE*2] = (int) DESCALE(tmp12 - tmp0, CONST_BITS-PASS1_BITS+1);
  171194. }
  171195. /* Pass 2: process 4 rows from work array, store into output array. */
  171196. wsptr = workspace;
  171197. for (ctr = 0; ctr < 4; ctr++) {
  171198. outptr = output_buf[ctr] + output_col;
  171199. /* It's not clear whether a zero row test is worthwhile here ... */
  171200. #ifndef NO_ZERO_ROW_TEST
  171201. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 &&
  171202. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  171203. /* AC terms all zero */
  171204. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  171205. & RANGE_MASK];
  171206. outptr[0] = dcval;
  171207. outptr[1] = dcval;
  171208. outptr[2] = dcval;
  171209. outptr[3] = dcval;
  171210. wsptr += DCTSIZE; /* advance pointer to next row */
  171211. continue;
  171212. }
  171213. #endif
  171214. /* Even part */
  171215. tmp0 = ((INT32) wsptr[0]) << (CONST_BITS+1);
  171216. tmp2 = MULTIPLY((INT32) wsptr[2], FIX_1_847759065)
  171217. + MULTIPLY((INT32) wsptr[6], - FIX_0_765366865);
  171218. tmp10 = tmp0 + tmp2;
  171219. tmp12 = tmp0 - tmp2;
  171220. /* Odd part */
  171221. z1 = (INT32) wsptr[7];
  171222. z2 = (INT32) wsptr[5];
  171223. z3 = (INT32) wsptr[3];
  171224. z4 = (INT32) wsptr[1];
  171225. tmp0 = MULTIPLY(z1, - FIX_0_211164243) /* sqrt(2) * (c3-c1) */
  171226. + MULTIPLY(z2, FIX_1_451774981) /* sqrt(2) * (c3+c7) */
  171227. + MULTIPLY(z3, - FIX_2_172734803) /* sqrt(2) * (-c1-c5) */
  171228. + MULTIPLY(z4, FIX_1_061594337); /* sqrt(2) * (c5+c7) */
  171229. tmp2 = MULTIPLY(z1, - FIX_0_509795579) /* sqrt(2) * (c7-c5) */
  171230. + MULTIPLY(z2, - FIX_0_601344887) /* sqrt(2) * (c5-c1) */
  171231. + MULTIPLY(z3, FIX_0_899976223) /* sqrt(2) * (c3-c7) */
  171232. + MULTIPLY(z4, FIX_2_562915447); /* sqrt(2) * (c1+c3) */
  171233. /* Final output stage */
  171234. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp2,
  171235. CONST_BITS+PASS1_BITS+3+1)
  171236. & RANGE_MASK];
  171237. outptr[3] = range_limit[(int) DESCALE(tmp10 - tmp2,
  171238. CONST_BITS+PASS1_BITS+3+1)
  171239. & RANGE_MASK];
  171240. outptr[1] = range_limit[(int) DESCALE(tmp12 + tmp0,
  171241. CONST_BITS+PASS1_BITS+3+1)
  171242. & RANGE_MASK];
  171243. outptr[2] = range_limit[(int) DESCALE(tmp12 - tmp0,
  171244. CONST_BITS+PASS1_BITS+3+1)
  171245. & RANGE_MASK];
  171246. wsptr += DCTSIZE; /* advance pointer to next row */
  171247. }
  171248. }
  171249. /*
  171250. * Perform dequantization and inverse DCT on one block of coefficients,
  171251. * producing a reduced-size 2x2 output block.
  171252. */
  171253. GLOBAL(void)
  171254. jpeg_idct_2x2 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  171255. JCOEFPTR coef_block,
  171256. JSAMPARRAY output_buf, JDIMENSION output_col)
  171257. {
  171258. INT32 tmp0, tmp10, z1;
  171259. JCOEFPTR inptr;
  171260. ISLOW_MULT_TYPE * quantptr;
  171261. int * wsptr;
  171262. JSAMPROW outptr;
  171263. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  171264. int ctr;
  171265. int workspace[DCTSIZE*2]; /* buffers data between passes */
  171266. SHIFT_TEMPS
  171267. /* Pass 1: process columns from input, store into work array. */
  171268. inptr = coef_block;
  171269. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  171270. wsptr = workspace;
  171271. for (ctr = DCTSIZE; ctr > 0; inptr++, quantptr++, wsptr++, ctr--) {
  171272. /* Don't bother to process columns 2,4,6 */
  171273. if (ctr == DCTSIZE-2 || ctr == DCTSIZE-4 || ctr == DCTSIZE-6)
  171274. continue;
  171275. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*3] == 0 &&
  171276. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*7] == 0) {
  171277. /* AC terms all zero; we need not examine terms 2,4,6 for 2x2 output */
  171278. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  171279. wsptr[DCTSIZE*0] = dcval;
  171280. wsptr[DCTSIZE*1] = dcval;
  171281. continue;
  171282. }
  171283. /* Even part */
  171284. z1 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  171285. tmp10 = z1 << (CONST_BITS+2);
  171286. /* Odd part */
  171287. z1 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  171288. tmp0 = MULTIPLY(z1, - FIX_0_720959822); /* sqrt(2) * (c7-c5+c3-c1) */
  171289. z1 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  171290. tmp0 += MULTIPLY(z1, FIX_0_850430095); /* sqrt(2) * (-c1+c3+c5+c7) */
  171291. z1 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  171292. tmp0 += MULTIPLY(z1, - FIX_1_272758580); /* sqrt(2) * (-c1+c3-c5-c7) */
  171293. z1 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  171294. tmp0 += MULTIPLY(z1, FIX_3_624509785); /* sqrt(2) * (c1+c3+c5+c7) */
  171295. /* Final output stage */
  171296. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp0, CONST_BITS-PASS1_BITS+2);
  171297. wsptr[DCTSIZE*1] = (int) DESCALE(tmp10 - tmp0, CONST_BITS-PASS1_BITS+2);
  171298. }
  171299. /* Pass 2: process 2 rows from work array, store into output array. */
  171300. wsptr = workspace;
  171301. for (ctr = 0; ctr < 2; ctr++) {
  171302. outptr = output_buf[ctr] + output_col;
  171303. /* It's not clear whether a zero row test is worthwhile here ... */
  171304. #ifndef NO_ZERO_ROW_TEST
  171305. if (wsptr[1] == 0 && wsptr[3] == 0 && wsptr[5] == 0 && wsptr[7] == 0) {
  171306. /* AC terms all zero */
  171307. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  171308. & RANGE_MASK];
  171309. outptr[0] = dcval;
  171310. outptr[1] = dcval;
  171311. wsptr += DCTSIZE; /* advance pointer to next row */
  171312. continue;
  171313. }
  171314. #endif
  171315. /* Even part */
  171316. tmp10 = ((INT32) wsptr[0]) << (CONST_BITS+2);
  171317. /* Odd part */
  171318. tmp0 = MULTIPLY((INT32) wsptr[7], - FIX_0_720959822) /* sqrt(2) * (c7-c5+c3-c1) */
  171319. + MULTIPLY((INT32) wsptr[5], FIX_0_850430095) /* sqrt(2) * (-c1+c3+c5+c7) */
  171320. + MULTIPLY((INT32) wsptr[3], - FIX_1_272758580) /* sqrt(2) * (-c1+c3-c5-c7) */
  171321. + MULTIPLY((INT32) wsptr[1], FIX_3_624509785); /* sqrt(2) * (c1+c3+c5+c7) */
  171322. /* Final output stage */
  171323. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp0,
  171324. CONST_BITS+PASS1_BITS+3+2)
  171325. & RANGE_MASK];
  171326. outptr[1] = range_limit[(int) DESCALE(tmp10 - tmp0,
  171327. CONST_BITS+PASS1_BITS+3+2)
  171328. & RANGE_MASK];
  171329. wsptr += DCTSIZE; /* advance pointer to next row */
  171330. }
  171331. }
  171332. /*
  171333. * Perform dequantization and inverse DCT on one block of coefficients,
  171334. * producing a reduced-size 1x1 output block.
  171335. */
  171336. GLOBAL(void)
  171337. jpeg_idct_1x1 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  171338. JCOEFPTR coef_block,
  171339. JSAMPARRAY output_buf, JDIMENSION output_col)
  171340. {
  171341. int dcval;
  171342. ISLOW_MULT_TYPE * quantptr;
  171343. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  171344. SHIFT_TEMPS
  171345. /* We hardly need an inverse DCT routine for this: just take the
  171346. * average pixel value, which is one-eighth of the DC coefficient.
  171347. */
  171348. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  171349. dcval = DEQUANTIZE(coef_block[0], quantptr[0]);
  171350. dcval = (int) DESCALE((INT32) dcval, 3);
  171351. output_buf[0][output_col] = range_limit[dcval & RANGE_MASK];
  171352. }
  171353. #endif /* IDCT_SCALING_SUPPORTED */
  171354. /********* End of inlined file: jidctred.c *********/
  171355. /********* Start of inlined file: jmemmgr.c *********/
  171356. #define JPEG_INTERNALS
  171357. #define AM_MEMORY_MANAGER /* we define jvirt_Xarray_control structs */
  171358. /********* Start of inlined file: jmemsys.h *********/
  171359. #ifndef __jmemsys_h__
  171360. #define __jmemsys_h__
  171361. /* Short forms of external names for systems with brain-damaged linkers. */
  171362. #ifdef NEED_SHORT_EXTERNAL_NAMES
  171363. #define jpeg_get_small jGetSmall
  171364. #define jpeg_free_small jFreeSmall
  171365. #define jpeg_get_large jGetLarge
  171366. #define jpeg_free_large jFreeLarge
  171367. #define jpeg_mem_available jMemAvail
  171368. #define jpeg_open_backing_store jOpenBackStore
  171369. #define jpeg_mem_init jMemInit
  171370. #define jpeg_mem_term jMemTerm
  171371. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  171372. /*
  171373. * These two functions are used to allocate and release small chunks of
  171374. * memory. (Typically the total amount requested through jpeg_get_small is
  171375. * no more than 20K or so; this will be requested in chunks of a few K each.)
  171376. * Behavior should be the same as for the standard library functions malloc
  171377. * and free; in particular, jpeg_get_small must return NULL on failure.
  171378. * On most systems, these ARE malloc and free. jpeg_free_small is passed the
  171379. * size of the object being freed, just in case it's needed.
  171380. * On an 80x86 machine using small-data memory model, these manage near heap.
  171381. */
  171382. EXTERN(void *) jpeg_get_small JPP((j_common_ptr cinfo, size_t sizeofobject));
  171383. EXTERN(void) jpeg_free_small JPP((j_common_ptr cinfo, void * object,
  171384. size_t sizeofobject));
  171385. /*
  171386. * These two functions are used to allocate and release large chunks of
  171387. * memory (up to the total free space designated by jpeg_mem_available).
  171388. * The interface is the same as above, except that on an 80x86 machine,
  171389. * far pointers are used. On most other machines these are identical to
  171390. * the jpeg_get/free_small routines; but we keep them separate anyway,
  171391. * in case a different allocation strategy is desirable for large chunks.
  171392. */
  171393. EXTERN(void FAR *) jpeg_get_large JPP((j_common_ptr cinfo,
  171394. size_t sizeofobject));
  171395. EXTERN(void) jpeg_free_large JPP((j_common_ptr cinfo, void FAR * object,
  171396. size_t sizeofobject));
  171397. /*
  171398. * The macro MAX_ALLOC_CHUNK designates the maximum number of bytes that may
  171399. * be requested in a single call to jpeg_get_large (and jpeg_get_small for that
  171400. * matter, but that case should never come into play). This macro is needed
  171401. * to model the 64Kb-segment-size limit of far addressing on 80x86 machines.
  171402. * On those machines, we expect that jconfig.h will provide a proper value.
  171403. * On machines with 32-bit flat address spaces, any large constant may be used.
  171404. *
  171405. * NB: jmemmgr.c expects that MAX_ALLOC_CHUNK will be representable as type
  171406. * size_t and will be a multiple of sizeof(align_type).
  171407. */
  171408. #ifndef MAX_ALLOC_CHUNK /* may be overridden in jconfig.h */
  171409. #define MAX_ALLOC_CHUNK 1000000000L
  171410. #endif
  171411. /*
  171412. * This routine computes the total space still available for allocation by
  171413. * jpeg_get_large. If more space than this is needed, backing store will be
  171414. * used. NOTE: any memory already allocated must not be counted.
  171415. *
  171416. * There is a minimum space requirement, corresponding to the minimum
  171417. * feasible buffer sizes; jmemmgr.c will request that much space even if
  171418. * jpeg_mem_available returns zero. The maximum space needed, enough to hold
  171419. * all working storage in memory, is also passed in case it is useful.
  171420. * Finally, the total space already allocated is passed. If no better
  171421. * method is available, cinfo->mem->max_memory_to_use - already_allocated
  171422. * is often a suitable calculation.
  171423. *
  171424. * It is OK for jpeg_mem_available to underestimate the space available
  171425. * (that'll just lead to more backing-store access than is really necessary).
  171426. * However, an overestimate will lead to failure. Hence it's wise to subtract
  171427. * a slop factor from the true available space. 5% should be enough.
  171428. *
  171429. * On machines with lots of virtual memory, any large constant may be returned.
  171430. * Conversely, zero may be returned to always use the minimum amount of memory.
  171431. */
  171432. EXTERN(long) jpeg_mem_available JPP((j_common_ptr cinfo,
  171433. long min_bytes_needed,
  171434. long max_bytes_needed,
  171435. long already_allocated));
  171436. /*
  171437. * This structure holds whatever state is needed to access a single
  171438. * backing-store object. The read/write/close method pointers are called
  171439. * by jmemmgr.c to manipulate the backing-store object; all other fields
  171440. * are private to the system-dependent backing store routines.
  171441. */
  171442. #define TEMP_NAME_LENGTH 64 /* max length of a temporary file's name */
  171443. #ifdef USE_MSDOS_MEMMGR /* DOS-specific junk */
  171444. typedef unsigned short XMSH; /* type of extended-memory handles */
  171445. typedef unsigned short EMSH; /* type of expanded-memory handles */
  171446. typedef union {
  171447. short file_handle; /* DOS file handle if it's a temp file */
  171448. XMSH xms_handle; /* handle if it's a chunk of XMS */
  171449. EMSH ems_handle; /* handle if it's a chunk of EMS */
  171450. } handle_union;
  171451. #endif /* USE_MSDOS_MEMMGR */
  171452. #ifdef USE_MAC_MEMMGR /* Mac-specific junk */
  171453. #include <Files.h>
  171454. #endif /* USE_MAC_MEMMGR */
  171455. //typedef struct backing_store_struct * backing_store_ptr;
  171456. typedef struct backing_store_struct {
  171457. /* Methods for reading/writing/closing this backing-store object */
  171458. JMETHOD(void, read_backing_store, (j_common_ptr cinfo,
  171459. struct backing_store_struct *info,
  171460. void FAR * buffer_address,
  171461. long file_offset, long byte_count));
  171462. JMETHOD(void, write_backing_store, (j_common_ptr cinfo,
  171463. struct backing_store_struct *info,
  171464. void FAR * buffer_address,
  171465. long file_offset, long byte_count));
  171466. JMETHOD(void, close_backing_store, (j_common_ptr cinfo,
  171467. struct backing_store_struct *info));
  171468. /* Private fields for system-dependent backing-store management */
  171469. #ifdef USE_MSDOS_MEMMGR
  171470. /* For the MS-DOS manager (jmemdos.c), we need: */
  171471. handle_union handle; /* reference to backing-store storage object */
  171472. char temp_name[TEMP_NAME_LENGTH]; /* name if it's a file */
  171473. #else
  171474. #ifdef USE_MAC_MEMMGR
  171475. /* For the Mac manager (jmemmac.c), we need: */
  171476. short temp_file; /* file reference number to temp file */
  171477. FSSpec tempSpec; /* the FSSpec for the temp file */
  171478. char temp_name[TEMP_NAME_LENGTH]; /* name if it's a file */
  171479. #else
  171480. /* For a typical implementation with temp files, we need: */
  171481. FILE * temp_file; /* stdio reference to temp file */
  171482. char temp_name[TEMP_NAME_LENGTH]; /* name of temp file */
  171483. #endif
  171484. #endif
  171485. } backing_store_info;
  171486. /*
  171487. * Initial opening of a backing-store object. This must fill in the
  171488. * read/write/close pointers in the object. The read/write routines
  171489. * may take an error exit if the specified maximum file size is exceeded.
  171490. * (If jpeg_mem_available always returns a large value, this routine can
  171491. * just take an error exit.)
  171492. */
  171493. EXTERN(void) jpeg_open_backing_store JPP((j_common_ptr cinfo,
  171494. struct backing_store_struct *info,
  171495. long total_bytes_needed));
  171496. /*
  171497. * These routines take care of any system-dependent initialization and
  171498. * cleanup required. jpeg_mem_init will be called before anything is
  171499. * allocated (and, therefore, nothing in cinfo is of use except the error
  171500. * manager pointer). It should return a suitable default value for
  171501. * max_memory_to_use; this may subsequently be overridden by the surrounding
  171502. * application. (Note that max_memory_to_use is only important if
  171503. * jpeg_mem_available chooses to consult it ... no one else will.)
  171504. * jpeg_mem_term may assume that all requested memory has been freed and that
  171505. * all opened backing-store objects have been closed.
  171506. */
  171507. EXTERN(long) jpeg_mem_init JPP((j_common_ptr cinfo));
  171508. EXTERN(void) jpeg_mem_term JPP((j_common_ptr cinfo));
  171509. #endif
  171510. /********* End of inlined file: jmemsys.h *********/
  171511. /* import the system-dependent declarations */
  171512. #ifndef NO_GETENV
  171513. #ifndef HAVE_STDLIB_H /* <stdlib.h> should declare getenv() */
  171514. extern char * getenv JPP((const char * name));
  171515. #endif
  171516. #endif
  171517. /*
  171518. * Some important notes:
  171519. * The allocation routines provided here must never return NULL.
  171520. * They should exit to error_exit if unsuccessful.
  171521. *
  171522. * It's not a good idea to try to merge the sarray and barray routines,
  171523. * even though they are textually almost the same, because samples are
  171524. * usually stored as bytes while coefficients are shorts or ints. Thus,
  171525. * in machines where byte pointers have a different representation from
  171526. * word pointers, the resulting machine code could not be the same.
  171527. */
  171528. /*
  171529. * Many machines require storage alignment: longs must start on 4-byte
  171530. * boundaries, doubles on 8-byte boundaries, etc. On such machines, malloc()
  171531. * always returns pointers that are multiples of the worst-case alignment
  171532. * requirement, and we had better do so too.
  171533. * There isn't any really portable way to determine the worst-case alignment
  171534. * requirement. This module assumes that the alignment requirement is
  171535. * multiples of sizeof(ALIGN_TYPE).
  171536. * By default, we define ALIGN_TYPE as double. This is necessary on some
  171537. * workstations (where doubles really do need 8-byte alignment) and will work
  171538. * fine on nearly everything. If your machine has lesser alignment needs,
  171539. * you can save a few bytes by making ALIGN_TYPE smaller.
  171540. * The only place I know of where this will NOT work is certain Macintosh
  171541. * 680x0 compilers that define double as a 10-byte IEEE extended float.
  171542. * Doing 10-byte alignment is counterproductive because longwords won't be
  171543. * aligned well. Put "#define ALIGN_TYPE long" in jconfig.h if you have
  171544. * such a compiler.
  171545. */
  171546. #ifndef ALIGN_TYPE /* so can override from jconfig.h */
  171547. #define ALIGN_TYPE double
  171548. #endif
  171549. /*
  171550. * We allocate objects from "pools", where each pool is gotten with a single
  171551. * request to jpeg_get_small() or jpeg_get_large(). There is no per-object
  171552. * overhead within a pool, except for alignment padding. Each pool has a
  171553. * header with a link to the next pool of the same class.
  171554. * Small and large pool headers are identical except that the latter's
  171555. * link pointer must be FAR on 80x86 machines.
  171556. * Notice that the "real" header fields are union'ed with a dummy ALIGN_TYPE
  171557. * field. This forces the compiler to make SIZEOF(small_pool_hdr) a multiple
  171558. * of the alignment requirement of ALIGN_TYPE.
  171559. */
  171560. typedef union small_pool_struct * small_pool_ptr;
  171561. typedef union small_pool_struct {
  171562. struct {
  171563. small_pool_ptr next; /* next in list of pools */
  171564. size_t bytes_used; /* how many bytes already used within pool */
  171565. size_t bytes_left; /* bytes still available in this pool */
  171566. } hdr;
  171567. ALIGN_TYPE dummy; /* included in union to ensure alignment */
  171568. } small_pool_hdr;
  171569. typedef union large_pool_struct FAR * large_pool_ptr;
  171570. typedef union large_pool_struct {
  171571. struct {
  171572. large_pool_ptr next; /* next in list of pools */
  171573. size_t bytes_used; /* how many bytes already used within pool */
  171574. size_t bytes_left; /* bytes still available in this pool */
  171575. } hdr;
  171576. ALIGN_TYPE dummy; /* included in union to ensure alignment */
  171577. } large_pool_hdr;
  171578. /*
  171579. * Here is the full definition of a memory manager object.
  171580. */
  171581. typedef struct {
  171582. struct jpeg_memory_mgr pub; /* public fields */
  171583. /* Each pool identifier (lifetime class) names a linked list of pools. */
  171584. small_pool_ptr small_list[JPOOL_NUMPOOLS];
  171585. large_pool_ptr large_list[JPOOL_NUMPOOLS];
  171586. /* Since we only have one lifetime class of virtual arrays, only one
  171587. * linked list is necessary (for each datatype). Note that the virtual
  171588. * array control blocks being linked together are actually stored somewhere
  171589. * in the small-pool list.
  171590. */
  171591. jvirt_sarray_ptr virt_sarray_list;
  171592. jvirt_barray_ptr virt_barray_list;
  171593. /* This counts total space obtained from jpeg_get_small/large */
  171594. long total_space_allocated;
  171595. /* alloc_sarray and alloc_barray set this value for use by virtual
  171596. * array routines.
  171597. */
  171598. JDIMENSION last_rowsperchunk; /* from most recent alloc_sarray/barray */
  171599. } my_memory_mgr;
  171600. typedef my_memory_mgr * my_mem_ptr;
  171601. /*
  171602. * The control blocks for virtual arrays.
  171603. * Note that these blocks are allocated in the "small" pool area.
  171604. * System-dependent info for the associated backing store (if any) is hidden
  171605. * inside the backing_store_info struct.
  171606. */
  171607. struct jvirt_sarray_control {
  171608. JSAMPARRAY mem_buffer; /* => the in-memory buffer */
  171609. JDIMENSION rows_in_array; /* total virtual array height */
  171610. JDIMENSION samplesperrow; /* width of array (and of memory buffer) */
  171611. JDIMENSION maxaccess; /* max rows accessed by access_virt_sarray */
  171612. JDIMENSION rows_in_mem; /* height of memory buffer */
  171613. JDIMENSION rowsperchunk; /* allocation chunk size in mem_buffer */
  171614. JDIMENSION cur_start_row; /* first logical row # in the buffer */
  171615. JDIMENSION first_undef_row; /* row # of first uninitialized row */
  171616. boolean pre_zero; /* pre-zero mode requested? */
  171617. boolean dirty; /* do current buffer contents need written? */
  171618. boolean b_s_open; /* is backing-store data valid? */
  171619. jvirt_sarray_ptr next; /* link to next virtual sarray control block */
  171620. backing_store_info b_s_info; /* System-dependent control info */
  171621. };
  171622. struct jvirt_barray_control {
  171623. JBLOCKARRAY mem_buffer; /* => the in-memory buffer */
  171624. JDIMENSION rows_in_array; /* total virtual array height */
  171625. JDIMENSION blocksperrow; /* width of array (and of memory buffer) */
  171626. JDIMENSION maxaccess; /* max rows accessed by access_virt_barray */
  171627. JDIMENSION rows_in_mem; /* height of memory buffer */
  171628. JDIMENSION rowsperchunk; /* allocation chunk size in mem_buffer */
  171629. JDIMENSION cur_start_row; /* first logical row # in the buffer */
  171630. JDIMENSION first_undef_row; /* row # of first uninitialized row */
  171631. boolean pre_zero; /* pre-zero mode requested? */
  171632. boolean dirty; /* do current buffer contents need written? */
  171633. boolean b_s_open; /* is backing-store data valid? */
  171634. jvirt_barray_ptr next; /* link to next virtual barray control block */
  171635. backing_store_info b_s_info; /* System-dependent control info */
  171636. };
  171637. #ifdef MEM_STATS /* optional extra stuff for statistics */
  171638. LOCAL(void)
  171639. print_mem_stats (j_common_ptr cinfo, int pool_id)
  171640. {
  171641. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  171642. small_pool_ptr shdr_ptr;
  171643. large_pool_ptr lhdr_ptr;
  171644. /* Since this is only a debugging stub, we can cheat a little by using
  171645. * fprintf directly rather than going through the trace message code.
  171646. * This is helpful because message parm array can't handle longs.
  171647. */
  171648. fprintf(stderr, "Freeing pool %d, total space = %ld\n",
  171649. pool_id, mem->total_space_allocated);
  171650. for (lhdr_ptr = mem->large_list[pool_id]; lhdr_ptr != NULL;
  171651. lhdr_ptr = lhdr_ptr->hdr.next) {
  171652. fprintf(stderr, " Large chunk used %ld\n",
  171653. (long) lhdr_ptr->hdr.bytes_used);
  171654. }
  171655. for (shdr_ptr = mem->small_list[pool_id]; shdr_ptr != NULL;
  171656. shdr_ptr = shdr_ptr->hdr.next) {
  171657. fprintf(stderr, " Small chunk used %ld free %ld\n",
  171658. (long) shdr_ptr->hdr.bytes_used,
  171659. (long) shdr_ptr->hdr.bytes_left);
  171660. }
  171661. }
  171662. #endif /* MEM_STATS */
  171663. LOCAL(void)
  171664. out_of_memory (j_common_ptr cinfo, int which)
  171665. /* Report an out-of-memory error and stop execution */
  171666. /* If we compiled MEM_STATS support, report alloc requests before dying */
  171667. {
  171668. #ifdef MEM_STATS
  171669. cinfo->err->trace_level = 2; /* force self_destruct to report stats */
  171670. #endif
  171671. ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, which);
  171672. }
  171673. /*
  171674. * Allocation of "small" objects.
  171675. *
  171676. * For these, we use pooled storage. When a new pool must be created,
  171677. * we try to get enough space for the current request plus a "slop" factor,
  171678. * where the slop will be the amount of leftover space in the new pool.
  171679. * The speed vs. space tradeoff is largely determined by the slop values.
  171680. * A different slop value is provided for each pool class (lifetime),
  171681. * and we also distinguish the first pool of a class from later ones.
  171682. * NOTE: the values given work fairly well on both 16- and 32-bit-int
  171683. * machines, but may be too small if longs are 64 bits or more.
  171684. */
  171685. static const size_t first_pool_slop[JPOOL_NUMPOOLS] =
  171686. {
  171687. 1600, /* first PERMANENT pool */
  171688. 16000 /* first IMAGE pool */
  171689. };
  171690. static const size_t extra_pool_slop[JPOOL_NUMPOOLS] =
  171691. {
  171692. 0, /* additional PERMANENT pools */
  171693. 5000 /* additional IMAGE pools */
  171694. };
  171695. #define MIN_SLOP 50 /* greater than 0 to avoid futile looping */
  171696. METHODDEF(void *)
  171697. alloc_small (j_common_ptr cinfo, int pool_id, size_t sizeofobject)
  171698. /* Allocate a "small" object */
  171699. {
  171700. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  171701. small_pool_ptr hdr_ptr, prev_hdr_ptr;
  171702. char * data_ptr;
  171703. size_t odd_bytes, min_request, slop;
  171704. /* Check for unsatisfiable request (do now to ensure no overflow below) */
  171705. if (sizeofobject > (size_t) (MAX_ALLOC_CHUNK-SIZEOF(small_pool_hdr)))
  171706. out_of_memory(cinfo, 1); /* request exceeds malloc's ability */
  171707. /* Round up the requested size to a multiple of SIZEOF(ALIGN_TYPE) */
  171708. odd_bytes = sizeofobject % SIZEOF(ALIGN_TYPE);
  171709. if (odd_bytes > 0)
  171710. sizeofobject += SIZEOF(ALIGN_TYPE) - odd_bytes;
  171711. /* See if space is available in any existing pool */
  171712. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  171713. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  171714. prev_hdr_ptr = NULL;
  171715. hdr_ptr = mem->small_list[pool_id];
  171716. while (hdr_ptr != NULL) {
  171717. if (hdr_ptr->hdr.bytes_left >= sizeofobject)
  171718. break; /* found pool with enough space */
  171719. prev_hdr_ptr = hdr_ptr;
  171720. hdr_ptr = hdr_ptr->hdr.next;
  171721. }
  171722. /* Time to make a new pool? */
  171723. if (hdr_ptr == NULL) {
  171724. /* min_request is what we need now, slop is what will be leftover */
  171725. min_request = sizeofobject + SIZEOF(small_pool_hdr);
  171726. if (prev_hdr_ptr == NULL) /* first pool in class? */
  171727. slop = first_pool_slop[pool_id];
  171728. else
  171729. slop = extra_pool_slop[pool_id];
  171730. /* Don't ask for more than MAX_ALLOC_CHUNK */
  171731. if (slop > (size_t) (MAX_ALLOC_CHUNK-min_request))
  171732. slop = (size_t) (MAX_ALLOC_CHUNK-min_request);
  171733. /* Try to get space, if fail reduce slop and try again */
  171734. for (;;) {
  171735. hdr_ptr = (small_pool_ptr) jpeg_get_small(cinfo, min_request + slop);
  171736. if (hdr_ptr != NULL)
  171737. break;
  171738. slop /= 2;
  171739. if (slop < MIN_SLOP) /* give up when it gets real small */
  171740. out_of_memory(cinfo, 2); /* jpeg_get_small failed */
  171741. }
  171742. mem->total_space_allocated += min_request + slop;
  171743. /* Success, initialize the new pool header and add to end of list */
  171744. hdr_ptr->hdr.next = NULL;
  171745. hdr_ptr->hdr.bytes_used = 0;
  171746. hdr_ptr->hdr.bytes_left = sizeofobject + slop;
  171747. if (prev_hdr_ptr == NULL) /* first pool in class? */
  171748. mem->small_list[pool_id] = hdr_ptr;
  171749. else
  171750. prev_hdr_ptr->hdr.next = hdr_ptr;
  171751. }
  171752. /* OK, allocate the object from the current pool */
  171753. data_ptr = (char *) (hdr_ptr + 1); /* point to first data byte in pool */
  171754. data_ptr += hdr_ptr->hdr.bytes_used; /* point to place for object */
  171755. hdr_ptr->hdr.bytes_used += sizeofobject;
  171756. hdr_ptr->hdr.bytes_left -= sizeofobject;
  171757. return (void *) data_ptr;
  171758. }
  171759. /*
  171760. * Allocation of "large" objects.
  171761. *
  171762. * The external semantics of these are the same as "small" objects,
  171763. * except that FAR pointers are used on 80x86. However the pool
  171764. * management heuristics are quite different. We assume that each
  171765. * request is large enough that it may as well be passed directly to
  171766. * jpeg_get_large; the pool management just links everything together
  171767. * so that we can free it all on demand.
  171768. * Note: the major use of "large" objects is in JSAMPARRAY and JBLOCKARRAY
  171769. * structures. The routines that create these structures (see below)
  171770. * deliberately bunch rows together to ensure a large request size.
  171771. */
  171772. METHODDEF(void FAR *)
  171773. alloc_large (j_common_ptr cinfo, int pool_id, size_t sizeofobject)
  171774. /* Allocate a "large" object */
  171775. {
  171776. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  171777. large_pool_ptr hdr_ptr;
  171778. size_t odd_bytes;
  171779. /* Check for unsatisfiable request (do now to ensure no overflow below) */
  171780. if (sizeofobject > (size_t) (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)))
  171781. out_of_memory(cinfo, 3); /* request exceeds malloc's ability */
  171782. /* Round up the requested size to a multiple of SIZEOF(ALIGN_TYPE) */
  171783. odd_bytes = sizeofobject % SIZEOF(ALIGN_TYPE);
  171784. if (odd_bytes > 0)
  171785. sizeofobject += SIZEOF(ALIGN_TYPE) - odd_bytes;
  171786. /* Always make a new pool */
  171787. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  171788. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  171789. hdr_ptr = (large_pool_ptr) jpeg_get_large(cinfo, sizeofobject +
  171790. SIZEOF(large_pool_hdr));
  171791. if (hdr_ptr == NULL)
  171792. out_of_memory(cinfo, 4); /* jpeg_get_large failed */
  171793. mem->total_space_allocated += sizeofobject + SIZEOF(large_pool_hdr);
  171794. /* Success, initialize the new pool header and add to list */
  171795. hdr_ptr->hdr.next = mem->large_list[pool_id];
  171796. /* We maintain space counts in each pool header for statistical purposes,
  171797. * even though they are not needed for allocation.
  171798. */
  171799. hdr_ptr->hdr.bytes_used = sizeofobject;
  171800. hdr_ptr->hdr.bytes_left = 0;
  171801. mem->large_list[pool_id] = hdr_ptr;
  171802. return (void FAR *) (hdr_ptr + 1); /* point to first data byte in pool */
  171803. }
  171804. /*
  171805. * Creation of 2-D sample arrays.
  171806. * The pointers are in near heap, the samples themselves in FAR heap.
  171807. *
  171808. * To minimize allocation overhead and to allow I/O of large contiguous
  171809. * blocks, we allocate the sample rows in groups of as many rows as possible
  171810. * without exceeding MAX_ALLOC_CHUNK total bytes per allocation request.
  171811. * NB: the virtual array control routines, later in this file, know about
  171812. * this chunking of rows. The rowsperchunk value is left in the mem manager
  171813. * object so that it can be saved away if this sarray is the workspace for
  171814. * a virtual array.
  171815. */
  171816. METHODDEF(JSAMPARRAY)
  171817. alloc_sarray (j_common_ptr cinfo, int pool_id,
  171818. JDIMENSION samplesperrow, JDIMENSION numrows)
  171819. /* Allocate a 2-D sample array */
  171820. {
  171821. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  171822. JSAMPARRAY result;
  171823. JSAMPROW workspace;
  171824. JDIMENSION rowsperchunk, currow, i;
  171825. long ltemp;
  171826. /* Calculate max # of rows allowed in one allocation chunk */
  171827. ltemp = (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)) /
  171828. ((long) samplesperrow * SIZEOF(JSAMPLE));
  171829. if (ltemp <= 0)
  171830. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  171831. if (ltemp < (long) numrows)
  171832. rowsperchunk = (JDIMENSION) ltemp;
  171833. else
  171834. rowsperchunk = numrows;
  171835. mem->last_rowsperchunk = rowsperchunk;
  171836. /* Get space for row pointers (small object) */
  171837. result = (JSAMPARRAY) alloc_small(cinfo, pool_id,
  171838. (size_t) (numrows * SIZEOF(JSAMPROW)));
  171839. /* Get the rows themselves (large objects) */
  171840. currow = 0;
  171841. while (currow < numrows) {
  171842. rowsperchunk = MIN(rowsperchunk, numrows - currow);
  171843. workspace = (JSAMPROW) alloc_large(cinfo, pool_id,
  171844. (size_t) ((size_t) rowsperchunk * (size_t) samplesperrow
  171845. * SIZEOF(JSAMPLE)));
  171846. for (i = rowsperchunk; i > 0; i--) {
  171847. result[currow++] = workspace;
  171848. workspace += samplesperrow;
  171849. }
  171850. }
  171851. return result;
  171852. }
  171853. /*
  171854. * Creation of 2-D coefficient-block arrays.
  171855. * This is essentially the same as the code for sample arrays, above.
  171856. */
  171857. METHODDEF(JBLOCKARRAY)
  171858. alloc_barray (j_common_ptr cinfo, int pool_id,
  171859. JDIMENSION blocksperrow, JDIMENSION numrows)
  171860. /* Allocate a 2-D coefficient-block array */
  171861. {
  171862. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  171863. JBLOCKARRAY result;
  171864. JBLOCKROW workspace;
  171865. JDIMENSION rowsperchunk, currow, i;
  171866. long ltemp;
  171867. /* Calculate max # of rows allowed in one allocation chunk */
  171868. ltemp = (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)) /
  171869. ((long) blocksperrow * SIZEOF(JBLOCK));
  171870. if (ltemp <= 0)
  171871. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  171872. if (ltemp < (long) numrows)
  171873. rowsperchunk = (JDIMENSION) ltemp;
  171874. else
  171875. rowsperchunk = numrows;
  171876. mem->last_rowsperchunk = rowsperchunk;
  171877. /* Get space for row pointers (small object) */
  171878. result = (JBLOCKARRAY) alloc_small(cinfo, pool_id,
  171879. (size_t) (numrows * SIZEOF(JBLOCKROW)));
  171880. /* Get the rows themselves (large objects) */
  171881. currow = 0;
  171882. while (currow < numrows) {
  171883. rowsperchunk = MIN(rowsperchunk, numrows - currow);
  171884. workspace = (JBLOCKROW) alloc_large(cinfo, pool_id,
  171885. (size_t) ((size_t) rowsperchunk * (size_t) blocksperrow
  171886. * SIZEOF(JBLOCK)));
  171887. for (i = rowsperchunk; i > 0; i--) {
  171888. result[currow++] = workspace;
  171889. workspace += blocksperrow;
  171890. }
  171891. }
  171892. return result;
  171893. }
  171894. /*
  171895. * About virtual array management:
  171896. *
  171897. * The above "normal" array routines are only used to allocate strip buffers
  171898. * (as wide as the image, but just a few rows high). Full-image-sized buffers
  171899. * are handled as "virtual" arrays. The array is still accessed a strip at a
  171900. * time, but the memory manager must save the whole array for repeated
  171901. * accesses. The intended implementation is that there is a strip buffer in
  171902. * memory (as high as is possible given the desired memory limit), plus a
  171903. * backing file that holds the rest of the array.
  171904. *
  171905. * The request_virt_array routines are told the total size of the image and
  171906. * the maximum number of rows that will be accessed at once. The in-memory
  171907. * buffer must be at least as large as the maxaccess value.
  171908. *
  171909. * The request routines create control blocks but not the in-memory buffers.
  171910. * That is postponed until realize_virt_arrays is called. At that time the
  171911. * total amount of space needed is known (approximately, anyway), so free
  171912. * memory can be divided up fairly.
  171913. *
  171914. * The access_virt_array routines are responsible for making a specific strip
  171915. * area accessible (after reading or writing the backing file, if necessary).
  171916. * Note that the access routines are told whether the caller intends to modify
  171917. * the accessed strip; during a read-only pass this saves having to rewrite
  171918. * data to disk. The access routines are also responsible for pre-zeroing
  171919. * any newly accessed rows, if pre-zeroing was requested.
  171920. *
  171921. * In current usage, the access requests are usually for nonoverlapping
  171922. * strips; that is, successive access start_row numbers differ by exactly
  171923. * num_rows = maxaccess. This means we can get good performance with simple
  171924. * buffer dump/reload logic, by making the in-memory buffer be a multiple
  171925. * of the access height; then there will never be accesses across bufferload
  171926. * boundaries. The code will still work with overlapping access requests,
  171927. * but it doesn't handle bufferload overlaps very efficiently.
  171928. */
  171929. METHODDEF(jvirt_sarray_ptr)
  171930. request_virt_sarray (j_common_ptr cinfo, int pool_id, boolean pre_zero,
  171931. JDIMENSION samplesperrow, JDIMENSION numrows,
  171932. JDIMENSION maxaccess)
  171933. /* Request a virtual 2-D sample array */
  171934. {
  171935. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  171936. jvirt_sarray_ptr result;
  171937. /* Only IMAGE-lifetime virtual arrays are currently supported */
  171938. if (pool_id != JPOOL_IMAGE)
  171939. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  171940. /* get control block */
  171941. result = (jvirt_sarray_ptr) alloc_small(cinfo, pool_id,
  171942. SIZEOF(struct jvirt_sarray_control));
  171943. result->mem_buffer = NULL; /* marks array not yet realized */
  171944. result->rows_in_array = numrows;
  171945. result->samplesperrow = samplesperrow;
  171946. result->maxaccess = maxaccess;
  171947. result->pre_zero = pre_zero;
  171948. result->b_s_open = FALSE; /* no associated backing-store object */
  171949. result->next = mem->virt_sarray_list; /* add to list of virtual arrays */
  171950. mem->virt_sarray_list = result;
  171951. return result;
  171952. }
  171953. METHODDEF(jvirt_barray_ptr)
  171954. request_virt_barray (j_common_ptr cinfo, int pool_id, boolean pre_zero,
  171955. JDIMENSION blocksperrow, JDIMENSION numrows,
  171956. JDIMENSION maxaccess)
  171957. /* Request a virtual 2-D coefficient-block array */
  171958. {
  171959. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  171960. jvirt_barray_ptr result;
  171961. /* Only IMAGE-lifetime virtual arrays are currently supported */
  171962. if (pool_id != JPOOL_IMAGE)
  171963. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  171964. /* get control block */
  171965. result = (jvirt_barray_ptr) alloc_small(cinfo, pool_id,
  171966. SIZEOF(struct jvirt_barray_control));
  171967. result->mem_buffer = NULL; /* marks array not yet realized */
  171968. result->rows_in_array = numrows;
  171969. result->blocksperrow = blocksperrow;
  171970. result->maxaccess = maxaccess;
  171971. result->pre_zero = pre_zero;
  171972. result->b_s_open = FALSE; /* no associated backing-store object */
  171973. result->next = mem->virt_barray_list; /* add to list of virtual arrays */
  171974. mem->virt_barray_list = result;
  171975. return result;
  171976. }
  171977. METHODDEF(void)
  171978. realize_virt_arrays (j_common_ptr cinfo)
  171979. /* Allocate the in-memory buffers for any unrealized virtual arrays */
  171980. {
  171981. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  171982. long space_per_minheight, maximum_space, avail_mem;
  171983. long minheights, max_minheights;
  171984. jvirt_sarray_ptr sptr;
  171985. jvirt_barray_ptr bptr;
  171986. /* Compute the minimum space needed (maxaccess rows in each buffer)
  171987. * and the maximum space needed (full image height in each buffer).
  171988. * These may be of use to the system-dependent jpeg_mem_available routine.
  171989. */
  171990. space_per_minheight = 0;
  171991. maximum_space = 0;
  171992. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  171993. if (sptr->mem_buffer == NULL) { /* if not realized yet */
  171994. space_per_minheight += (long) sptr->maxaccess *
  171995. (long) sptr->samplesperrow * SIZEOF(JSAMPLE);
  171996. maximum_space += (long) sptr->rows_in_array *
  171997. (long) sptr->samplesperrow * SIZEOF(JSAMPLE);
  171998. }
  171999. }
  172000. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  172001. if (bptr->mem_buffer == NULL) { /* if not realized yet */
  172002. space_per_minheight += (long) bptr->maxaccess *
  172003. (long) bptr->blocksperrow * SIZEOF(JBLOCK);
  172004. maximum_space += (long) bptr->rows_in_array *
  172005. (long) bptr->blocksperrow * SIZEOF(JBLOCK);
  172006. }
  172007. }
  172008. if (space_per_minheight <= 0)
  172009. return; /* no unrealized arrays, no work */
  172010. /* Determine amount of memory to actually use; this is system-dependent. */
  172011. avail_mem = jpeg_mem_available(cinfo, space_per_minheight, maximum_space,
  172012. mem->total_space_allocated);
  172013. /* If the maximum space needed is available, make all the buffers full
  172014. * height; otherwise parcel it out with the same number of minheights
  172015. * in each buffer.
  172016. */
  172017. if (avail_mem >= maximum_space)
  172018. max_minheights = 1000000000L;
  172019. else {
  172020. max_minheights = avail_mem / space_per_minheight;
  172021. /* If there doesn't seem to be enough space, try to get the minimum
  172022. * anyway. This allows a "stub" implementation of jpeg_mem_available().
  172023. */
  172024. if (max_minheights <= 0)
  172025. max_minheights = 1;
  172026. }
  172027. /* Allocate the in-memory buffers and initialize backing store as needed. */
  172028. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  172029. if (sptr->mem_buffer == NULL) { /* if not realized yet */
  172030. minheights = ((long) sptr->rows_in_array - 1L) / sptr->maxaccess + 1L;
  172031. if (minheights <= max_minheights) {
  172032. /* This buffer fits in memory */
  172033. sptr->rows_in_mem = sptr->rows_in_array;
  172034. } else {
  172035. /* It doesn't fit in memory, create backing store. */
  172036. sptr->rows_in_mem = (JDIMENSION) (max_minheights * sptr->maxaccess);
  172037. jpeg_open_backing_store(cinfo, & sptr->b_s_info,
  172038. (long) sptr->rows_in_array *
  172039. (long) sptr->samplesperrow *
  172040. (long) SIZEOF(JSAMPLE));
  172041. sptr->b_s_open = TRUE;
  172042. }
  172043. sptr->mem_buffer = alloc_sarray(cinfo, JPOOL_IMAGE,
  172044. sptr->samplesperrow, sptr->rows_in_mem);
  172045. sptr->rowsperchunk = mem->last_rowsperchunk;
  172046. sptr->cur_start_row = 0;
  172047. sptr->first_undef_row = 0;
  172048. sptr->dirty = FALSE;
  172049. }
  172050. }
  172051. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  172052. if (bptr->mem_buffer == NULL) { /* if not realized yet */
  172053. minheights = ((long) bptr->rows_in_array - 1L) / bptr->maxaccess + 1L;
  172054. if (minheights <= max_minheights) {
  172055. /* This buffer fits in memory */
  172056. bptr->rows_in_mem = bptr->rows_in_array;
  172057. } else {
  172058. /* It doesn't fit in memory, create backing store. */
  172059. bptr->rows_in_mem = (JDIMENSION) (max_minheights * bptr->maxaccess);
  172060. jpeg_open_backing_store(cinfo, & bptr->b_s_info,
  172061. (long) bptr->rows_in_array *
  172062. (long) bptr->blocksperrow *
  172063. (long) SIZEOF(JBLOCK));
  172064. bptr->b_s_open = TRUE;
  172065. }
  172066. bptr->mem_buffer = alloc_barray(cinfo, JPOOL_IMAGE,
  172067. bptr->blocksperrow, bptr->rows_in_mem);
  172068. bptr->rowsperchunk = mem->last_rowsperchunk;
  172069. bptr->cur_start_row = 0;
  172070. bptr->first_undef_row = 0;
  172071. bptr->dirty = FALSE;
  172072. }
  172073. }
  172074. }
  172075. LOCAL(void)
  172076. do_sarray_io (j_common_ptr cinfo, jvirt_sarray_ptr ptr, boolean writing)
  172077. /* Do backing store read or write of a virtual sample array */
  172078. {
  172079. long bytesperrow, file_offset, byte_count, rows, thisrow, i;
  172080. bytesperrow = (long) ptr->samplesperrow * SIZEOF(JSAMPLE);
  172081. file_offset = ptr->cur_start_row * bytesperrow;
  172082. /* Loop to read or write each allocation chunk in mem_buffer */
  172083. for (i = 0; i < (long) ptr->rows_in_mem; i += ptr->rowsperchunk) {
  172084. /* One chunk, but check for short chunk at end of buffer */
  172085. rows = MIN((long) ptr->rowsperchunk, (long) ptr->rows_in_mem - i);
  172086. /* Transfer no more than is currently defined */
  172087. thisrow = (long) ptr->cur_start_row + i;
  172088. rows = MIN(rows, (long) ptr->first_undef_row - thisrow);
  172089. /* Transfer no more than fits in file */
  172090. rows = MIN(rows, (long) ptr->rows_in_array - thisrow);
  172091. if (rows <= 0) /* this chunk might be past end of file! */
  172092. break;
  172093. byte_count = rows * bytesperrow;
  172094. if (writing)
  172095. (*ptr->b_s_info.write_backing_store) (cinfo, & ptr->b_s_info,
  172096. (void FAR *) ptr->mem_buffer[i],
  172097. file_offset, byte_count);
  172098. else
  172099. (*ptr->b_s_info.read_backing_store) (cinfo, & ptr->b_s_info,
  172100. (void FAR *) ptr->mem_buffer[i],
  172101. file_offset, byte_count);
  172102. file_offset += byte_count;
  172103. }
  172104. }
  172105. LOCAL(void)
  172106. do_barray_io (j_common_ptr cinfo, jvirt_barray_ptr ptr, boolean writing)
  172107. /* Do backing store read or write of a virtual coefficient-block array */
  172108. {
  172109. long bytesperrow, file_offset, byte_count, rows, thisrow, i;
  172110. bytesperrow = (long) ptr->blocksperrow * SIZEOF(JBLOCK);
  172111. file_offset = ptr->cur_start_row * bytesperrow;
  172112. /* Loop to read or write each allocation chunk in mem_buffer */
  172113. for (i = 0; i < (long) ptr->rows_in_mem; i += ptr->rowsperchunk) {
  172114. /* One chunk, but check for short chunk at end of buffer */
  172115. rows = MIN((long) ptr->rowsperchunk, (long) ptr->rows_in_mem - i);
  172116. /* Transfer no more than is currently defined */
  172117. thisrow = (long) ptr->cur_start_row + i;
  172118. rows = MIN(rows, (long) ptr->first_undef_row - thisrow);
  172119. /* Transfer no more than fits in file */
  172120. rows = MIN(rows, (long) ptr->rows_in_array - thisrow);
  172121. if (rows <= 0) /* this chunk might be past end of file! */
  172122. break;
  172123. byte_count = rows * bytesperrow;
  172124. if (writing)
  172125. (*ptr->b_s_info.write_backing_store) (cinfo, & ptr->b_s_info,
  172126. (void FAR *) ptr->mem_buffer[i],
  172127. file_offset, byte_count);
  172128. else
  172129. (*ptr->b_s_info.read_backing_store) (cinfo, & ptr->b_s_info,
  172130. (void FAR *) ptr->mem_buffer[i],
  172131. file_offset, byte_count);
  172132. file_offset += byte_count;
  172133. }
  172134. }
  172135. METHODDEF(JSAMPARRAY)
  172136. access_virt_sarray (j_common_ptr cinfo, jvirt_sarray_ptr ptr,
  172137. JDIMENSION start_row, JDIMENSION num_rows,
  172138. boolean writable)
  172139. /* Access the part of a virtual sample array starting at start_row */
  172140. /* and extending for num_rows rows. writable is true if */
  172141. /* caller intends to modify the accessed area. */
  172142. {
  172143. JDIMENSION end_row = start_row + num_rows;
  172144. JDIMENSION undef_row;
  172145. /* debugging check */
  172146. if (end_row > ptr->rows_in_array || num_rows > ptr->maxaccess ||
  172147. ptr->mem_buffer == NULL)
  172148. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  172149. /* Make the desired part of the virtual array accessible */
  172150. if (start_row < ptr->cur_start_row ||
  172151. end_row > ptr->cur_start_row+ptr->rows_in_mem) {
  172152. if (! ptr->b_s_open)
  172153. ERREXIT(cinfo, JERR_VIRTUAL_BUG);
  172154. /* Flush old buffer contents if necessary */
  172155. if (ptr->dirty) {
  172156. do_sarray_io(cinfo, ptr, TRUE);
  172157. ptr->dirty = FALSE;
  172158. }
  172159. /* Decide what part of virtual array to access.
  172160. * Algorithm: if target address > current window, assume forward scan,
  172161. * load starting at target address. If target address < current window,
  172162. * assume backward scan, load so that target area is top of window.
  172163. * Note that when switching from forward write to forward read, will have
  172164. * start_row = 0, so the limiting case applies and we load from 0 anyway.
  172165. */
  172166. if (start_row > ptr->cur_start_row) {
  172167. ptr->cur_start_row = start_row;
  172168. } else {
  172169. /* use long arithmetic here to avoid overflow & unsigned problems */
  172170. long ltemp;
  172171. ltemp = (long) end_row - (long) ptr->rows_in_mem;
  172172. if (ltemp < 0)
  172173. ltemp = 0; /* don't fall off front end of file */
  172174. ptr->cur_start_row = (JDIMENSION) ltemp;
  172175. }
  172176. /* Read in the selected part of the array.
  172177. * During the initial write pass, we will do no actual read
  172178. * because the selected part is all undefined.
  172179. */
  172180. do_sarray_io(cinfo, ptr, FALSE);
  172181. }
  172182. /* Ensure the accessed part of the array is defined; prezero if needed.
  172183. * To improve locality of access, we only prezero the part of the array
  172184. * that the caller is about to access, not the entire in-memory array.
  172185. */
  172186. if (ptr->first_undef_row < end_row) {
  172187. if (ptr->first_undef_row < start_row) {
  172188. if (writable) /* writer skipped over a section of array */
  172189. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  172190. undef_row = start_row; /* but reader is allowed to read ahead */
  172191. } else {
  172192. undef_row = ptr->first_undef_row;
  172193. }
  172194. if (writable)
  172195. ptr->first_undef_row = end_row;
  172196. if (ptr->pre_zero) {
  172197. size_t bytesperrow = (size_t) ptr->samplesperrow * SIZEOF(JSAMPLE);
  172198. undef_row -= ptr->cur_start_row; /* make indexes relative to buffer */
  172199. end_row -= ptr->cur_start_row;
  172200. while (undef_row < end_row) {
  172201. jzero_far((void FAR *) ptr->mem_buffer[undef_row], bytesperrow);
  172202. undef_row++;
  172203. }
  172204. } else {
  172205. if (! writable) /* reader looking at undefined data */
  172206. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  172207. }
  172208. }
  172209. /* Flag the buffer dirty if caller will write in it */
  172210. if (writable)
  172211. ptr->dirty = TRUE;
  172212. /* Return address of proper part of the buffer */
  172213. return ptr->mem_buffer + (start_row - ptr->cur_start_row);
  172214. }
  172215. METHODDEF(JBLOCKARRAY)
  172216. access_virt_barray (j_common_ptr cinfo, jvirt_barray_ptr ptr,
  172217. JDIMENSION start_row, JDIMENSION num_rows,
  172218. boolean writable)
  172219. /* Access the part of a virtual block array starting at start_row */
  172220. /* and extending for num_rows rows. writable is true if */
  172221. /* caller intends to modify the accessed area. */
  172222. {
  172223. JDIMENSION end_row = start_row + num_rows;
  172224. JDIMENSION undef_row;
  172225. /* debugging check */
  172226. if (end_row > ptr->rows_in_array || num_rows > ptr->maxaccess ||
  172227. ptr->mem_buffer == NULL)
  172228. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  172229. /* Make the desired part of the virtual array accessible */
  172230. if (start_row < ptr->cur_start_row ||
  172231. end_row > ptr->cur_start_row+ptr->rows_in_mem) {
  172232. if (! ptr->b_s_open)
  172233. ERREXIT(cinfo, JERR_VIRTUAL_BUG);
  172234. /* Flush old buffer contents if necessary */
  172235. if (ptr->dirty) {
  172236. do_barray_io(cinfo, ptr, TRUE);
  172237. ptr->dirty = FALSE;
  172238. }
  172239. /* Decide what part of virtual array to access.
  172240. * Algorithm: if target address > current window, assume forward scan,
  172241. * load starting at target address. If target address < current window,
  172242. * assume backward scan, load so that target area is top of window.
  172243. * Note that when switching from forward write to forward read, will have
  172244. * start_row = 0, so the limiting case applies and we load from 0 anyway.
  172245. */
  172246. if (start_row > ptr->cur_start_row) {
  172247. ptr->cur_start_row = start_row;
  172248. } else {
  172249. /* use long arithmetic here to avoid overflow & unsigned problems */
  172250. long ltemp;
  172251. ltemp = (long) end_row - (long) ptr->rows_in_mem;
  172252. if (ltemp < 0)
  172253. ltemp = 0; /* don't fall off front end of file */
  172254. ptr->cur_start_row = (JDIMENSION) ltemp;
  172255. }
  172256. /* Read in the selected part of the array.
  172257. * During the initial write pass, we will do no actual read
  172258. * because the selected part is all undefined.
  172259. */
  172260. do_barray_io(cinfo, ptr, FALSE);
  172261. }
  172262. /* Ensure the accessed part of the array is defined; prezero if needed.
  172263. * To improve locality of access, we only prezero the part of the array
  172264. * that the caller is about to access, not the entire in-memory array.
  172265. */
  172266. if (ptr->first_undef_row < end_row) {
  172267. if (ptr->first_undef_row < start_row) {
  172268. if (writable) /* writer skipped over a section of array */
  172269. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  172270. undef_row = start_row; /* but reader is allowed to read ahead */
  172271. } else {
  172272. undef_row = ptr->first_undef_row;
  172273. }
  172274. if (writable)
  172275. ptr->first_undef_row = end_row;
  172276. if (ptr->pre_zero) {
  172277. size_t bytesperrow = (size_t) ptr->blocksperrow * SIZEOF(JBLOCK);
  172278. undef_row -= ptr->cur_start_row; /* make indexes relative to buffer */
  172279. end_row -= ptr->cur_start_row;
  172280. while (undef_row < end_row) {
  172281. jzero_far((void FAR *) ptr->mem_buffer[undef_row], bytesperrow);
  172282. undef_row++;
  172283. }
  172284. } else {
  172285. if (! writable) /* reader looking at undefined data */
  172286. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  172287. }
  172288. }
  172289. /* Flag the buffer dirty if caller will write in it */
  172290. if (writable)
  172291. ptr->dirty = TRUE;
  172292. /* Return address of proper part of the buffer */
  172293. return ptr->mem_buffer + (start_row - ptr->cur_start_row);
  172294. }
  172295. /*
  172296. * Release all objects belonging to a specified pool.
  172297. */
  172298. METHODDEF(void)
  172299. free_pool (j_common_ptr cinfo, int pool_id)
  172300. {
  172301. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  172302. small_pool_ptr shdr_ptr;
  172303. large_pool_ptr lhdr_ptr;
  172304. size_t space_freed;
  172305. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  172306. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  172307. #ifdef MEM_STATS
  172308. if (cinfo->err->trace_level > 1)
  172309. print_mem_stats(cinfo, pool_id); /* print pool's memory usage statistics */
  172310. #endif
  172311. /* If freeing IMAGE pool, close any virtual arrays first */
  172312. if (pool_id == JPOOL_IMAGE) {
  172313. jvirt_sarray_ptr sptr;
  172314. jvirt_barray_ptr bptr;
  172315. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  172316. if (sptr->b_s_open) { /* there may be no backing store */
  172317. sptr->b_s_open = FALSE; /* prevent recursive close if error */
  172318. (*sptr->b_s_info.close_backing_store) (cinfo, & sptr->b_s_info);
  172319. }
  172320. }
  172321. mem->virt_sarray_list = NULL;
  172322. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  172323. if (bptr->b_s_open) { /* there may be no backing store */
  172324. bptr->b_s_open = FALSE; /* prevent recursive close if error */
  172325. (*bptr->b_s_info.close_backing_store) (cinfo, & bptr->b_s_info);
  172326. }
  172327. }
  172328. mem->virt_barray_list = NULL;
  172329. }
  172330. /* Release large objects */
  172331. lhdr_ptr = mem->large_list[pool_id];
  172332. mem->large_list[pool_id] = NULL;
  172333. while (lhdr_ptr != NULL) {
  172334. large_pool_ptr next_lhdr_ptr = lhdr_ptr->hdr.next;
  172335. space_freed = lhdr_ptr->hdr.bytes_used +
  172336. lhdr_ptr->hdr.bytes_left +
  172337. SIZEOF(large_pool_hdr);
  172338. jpeg_free_large(cinfo, (void FAR *) lhdr_ptr, space_freed);
  172339. mem->total_space_allocated -= space_freed;
  172340. lhdr_ptr = next_lhdr_ptr;
  172341. }
  172342. /* Release small objects */
  172343. shdr_ptr = mem->small_list[pool_id];
  172344. mem->small_list[pool_id] = NULL;
  172345. while (shdr_ptr != NULL) {
  172346. small_pool_ptr next_shdr_ptr = shdr_ptr->hdr.next;
  172347. space_freed = shdr_ptr->hdr.bytes_used +
  172348. shdr_ptr->hdr.bytes_left +
  172349. SIZEOF(small_pool_hdr);
  172350. jpeg_free_small(cinfo, (void *) shdr_ptr, space_freed);
  172351. mem->total_space_allocated -= space_freed;
  172352. shdr_ptr = next_shdr_ptr;
  172353. }
  172354. }
  172355. /*
  172356. * Close up shop entirely.
  172357. * Note that this cannot be called unless cinfo->mem is non-NULL.
  172358. */
  172359. METHODDEF(void)
  172360. self_destruct (j_common_ptr cinfo)
  172361. {
  172362. int pool;
  172363. /* Close all backing store, release all memory.
  172364. * Releasing pools in reverse order might help avoid fragmentation
  172365. * with some (brain-damaged) malloc libraries.
  172366. */
  172367. for (pool = JPOOL_NUMPOOLS-1; pool >= JPOOL_PERMANENT; pool--) {
  172368. free_pool(cinfo, pool);
  172369. }
  172370. /* Release the memory manager control block too. */
  172371. jpeg_free_small(cinfo, (void *) cinfo->mem, SIZEOF(my_memory_mgr));
  172372. cinfo->mem = NULL; /* ensures I will be called only once */
  172373. jpeg_mem_term(cinfo); /* system-dependent cleanup */
  172374. }
  172375. /*
  172376. * Memory manager initialization.
  172377. * When this is called, only the error manager pointer is valid in cinfo!
  172378. */
  172379. GLOBAL(void)
  172380. jinit_memory_mgr (j_common_ptr cinfo)
  172381. {
  172382. my_mem_ptr mem;
  172383. long max_to_use;
  172384. int pool;
  172385. size_t test_mac;
  172386. cinfo->mem = NULL; /* for safety if init fails */
  172387. /* Check for configuration errors.
  172388. * SIZEOF(ALIGN_TYPE) should be a power of 2; otherwise, it probably
  172389. * doesn't reflect any real hardware alignment requirement.
  172390. * The test is a little tricky: for X>0, X and X-1 have no one-bits
  172391. * in common if and only if X is a power of 2, ie has only one one-bit.
  172392. * Some compilers may give an "unreachable code" warning here; ignore it.
  172393. */
  172394. if ((SIZEOF(ALIGN_TYPE) & (SIZEOF(ALIGN_TYPE)-1)) != 0)
  172395. ERREXIT(cinfo, JERR_BAD_ALIGN_TYPE);
  172396. /* MAX_ALLOC_CHUNK must be representable as type size_t, and must be
  172397. * a multiple of SIZEOF(ALIGN_TYPE).
  172398. * Again, an "unreachable code" warning may be ignored here.
  172399. * But a "constant too large" warning means you need to fix MAX_ALLOC_CHUNK.
  172400. */
  172401. test_mac = (size_t) MAX_ALLOC_CHUNK;
  172402. if ((long) test_mac != MAX_ALLOC_CHUNK ||
  172403. (MAX_ALLOC_CHUNK % SIZEOF(ALIGN_TYPE)) != 0)
  172404. ERREXIT(cinfo, JERR_BAD_ALLOC_CHUNK);
  172405. max_to_use = jpeg_mem_init(cinfo); /* system-dependent initialization */
  172406. /* Attempt to allocate memory manager's control block */
  172407. mem = (my_mem_ptr) jpeg_get_small(cinfo, SIZEOF(my_memory_mgr));
  172408. if (mem == NULL) {
  172409. jpeg_mem_term(cinfo); /* system-dependent cleanup */
  172410. ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, 0);
  172411. }
  172412. /* OK, fill in the method pointers */
  172413. mem->pub.alloc_small = alloc_small;
  172414. mem->pub.alloc_large = alloc_large;
  172415. mem->pub.alloc_sarray = alloc_sarray;
  172416. mem->pub.alloc_barray = alloc_barray;
  172417. mem->pub.request_virt_sarray = request_virt_sarray;
  172418. mem->pub.request_virt_barray = request_virt_barray;
  172419. mem->pub.realize_virt_arrays = realize_virt_arrays;
  172420. mem->pub.access_virt_sarray = access_virt_sarray;
  172421. mem->pub.access_virt_barray = access_virt_barray;
  172422. mem->pub.free_pool = free_pool;
  172423. mem->pub.self_destruct = self_destruct;
  172424. /* Make MAX_ALLOC_CHUNK accessible to other modules */
  172425. mem->pub.max_alloc_chunk = MAX_ALLOC_CHUNK;
  172426. /* Initialize working state */
  172427. mem->pub.max_memory_to_use = max_to_use;
  172428. for (pool = JPOOL_NUMPOOLS-1; pool >= JPOOL_PERMANENT; pool--) {
  172429. mem->small_list[pool] = NULL;
  172430. mem->large_list[pool] = NULL;
  172431. }
  172432. mem->virt_sarray_list = NULL;
  172433. mem->virt_barray_list = NULL;
  172434. mem->total_space_allocated = SIZEOF(my_memory_mgr);
  172435. /* Declare ourselves open for business */
  172436. cinfo->mem = & mem->pub;
  172437. /* Check for an environment variable JPEGMEM; if found, override the
  172438. * default max_memory setting from jpeg_mem_init. Note that the
  172439. * surrounding application may again override this value.
  172440. * If your system doesn't support getenv(), define NO_GETENV to disable
  172441. * this feature.
  172442. */
  172443. #ifndef NO_GETENV
  172444. { char * memenv;
  172445. if ((memenv = getenv("JPEGMEM")) != NULL) {
  172446. char ch = 'x';
  172447. if (sscanf(memenv, "%ld%c", &max_to_use, &ch) > 0) {
  172448. if (ch == 'm' || ch == 'M')
  172449. max_to_use *= 1000L;
  172450. mem->pub.max_memory_to_use = max_to_use * 1000L;
  172451. }
  172452. }
  172453. }
  172454. #endif
  172455. }
  172456. /********* End of inlined file: jmemmgr.c *********/
  172457. /********* Start of inlined file: jmemnobs.c *********/
  172458. #define JPEG_INTERNALS
  172459. #ifndef HAVE_STDLIB_H /* <stdlib.h> should declare malloc(),free() */
  172460. extern void * malloc JPP((size_t size));
  172461. extern void free JPP((void *ptr));
  172462. #endif
  172463. /*
  172464. * Memory allocation and freeing are controlled by the regular library
  172465. * routines malloc() and free().
  172466. */
  172467. GLOBAL(void *)
  172468. jpeg_get_small (j_common_ptr cinfo, size_t sizeofobject)
  172469. {
  172470. return (void *) malloc(sizeofobject);
  172471. }
  172472. GLOBAL(void)
  172473. jpeg_free_small (j_common_ptr cinfo, void * object, size_t sizeofobject)
  172474. {
  172475. free(object);
  172476. }
  172477. /*
  172478. * "Large" objects are treated the same as "small" ones.
  172479. * NB: although we include FAR keywords in the routine declarations,
  172480. * this file won't actually work in 80x86 small/medium model; at least,
  172481. * you probably won't be able to process useful-size images in only 64KB.
  172482. */
  172483. GLOBAL(void FAR *)
  172484. jpeg_get_large (j_common_ptr cinfo, size_t sizeofobject)
  172485. {
  172486. return (void FAR *) malloc(sizeofobject);
  172487. }
  172488. GLOBAL(void)
  172489. jpeg_free_large (j_common_ptr cinfo, void FAR * object, size_t sizeofobject)
  172490. {
  172491. free(object);
  172492. }
  172493. /*
  172494. * This routine computes the total memory space available for allocation.
  172495. * Here we always say, "we got all you want bud!"
  172496. */
  172497. GLOBAL(long)
  172498. jpeg_mem_available (j_common_ptr cinfo, long min_bytes_needed,
  172499. long max_bytes_needed, long already_allocated)
  172500. {
  172501. return max_bytes_needed;
  172502. }
  172503. /*
  172504. * Backing store (temporary file) management.
  172505. * Since jpeg_mem_available always promised the moon,
  172506. * this should never be called and we can just error out.
  172507. */
  172508. GLOBAL(void)
  172509. jpeg_open_backing_store (j_common_ptr cinfo, struct backing_store_struct *info,
  172510. long total_bytes_needed)
  172511. {
  172512. ERREXIT(cinfo, JERR_NO_BACKING_STORE);
  172513. }
  172514. /*
  172515. * These routines take care of any system-dependent initialization and
  172516. * cleanup required. Here, there isn't any.
  172517. */
  172518. GLOBAL(long)
  172519. jpeg_mem_init (j_common_ptr cinfo)
  172520. {
  172521. return 0; /* just set max_memory_to_use to 0 */
  172522. }
  172523. GLOBAL(void)
  172524. jpeg_mem_term (j_common_ptr cinfo)
  172525. {
  172526. /* no work */
  172527. }
  172528. /********* End of inlined file: jmemnobs.c *********/
  172529. /********* Start of inlined file: jquant1.c *********/
  172530. #define JPEG_INTERNALS
  172531. #ifdef QUANT_1PASS_SUPPORTED
  172532. /*
  172533. * The main purpose of 1-pass quantization is to provide a fast, if not very
  172534. * high quality, colormapped output capability. A 2-pass quantizer usually
  172535. * gives better visual quality; however, for quantized grayscale output this
  172536. * quantizer is perfectly adequate. Dithering is highly recommended with this
  172537. * quantizer, though you can turn it off if you really want to.
  172538. *
  172539. * In 1-pass quantization the colormap must be chosen in advance of seeing the
  172540. * image. We use a map consisting of all combinations of Ncolors[i] color
  172541. * values for the i'th component. The Ncolors[] values are chosen so that
  172542. * their product, the total number of colors, is no more than that requested.
  172543. * (In most cases, the product will be somewhat less.)
  172544. *
  172545. * Since the colormap is orthogonal, the representative value for each color
  172546. * component can be determined without considering the other components;
  172547. * then these indexes can be combined into a colormap index by a standard
  172548. * N-dimensional-array-subscript calculation. Most of the arithmetic involved
  172549. * can be precalculated and stored in the lookup table colorindex[].
  172550. * colorindex[i][j] maps pixel value j in component i to the nearest
  172551. * representative value (grid plane) for that component; this index is
  172552. * multiplied by the array stride for component i, so that the
  172553. * index of the colormap entry closest to a given pixel value is just
  172554. * sum( colorindex[component-number][pixel-component-value] )
  172555. * Aside from being fast, this scheme allows for variable spacing between
  172556. * representative values with no additional lookup cost.
  172557. *
  172558. * If gamma correction has been applied in color conversion, it might be wise
  172559. * to adjust the color grid spacing so that the representative colors are
  172560. * equidistant in linear space. At this writing, gamma correction is not
  172561. * implemented by jdcolor, so nothing is done here.
  172562. */
  172563. /* Declarations for ordered dithering.
  172564. *
  172565. * We use a standard 16x16 ordered dither array. The basic concept of ordered
  172566. * dithering is described in many references, for instance Dale Schumacher's
  172567. * chapter II.2 of Graphics Gems II (James Arvo, ed. Academic Press, 1991).
  172568. * In place of Schumacher's comparisons against a "threshold" value, we add a
  172569. * "dither" value to the input pixel and then round the result to the nearest
  172570. * output value. The dither value is equivalent to (0.5 - threshold) times
  172571. * the distance between output values. For ordered dithering, we assume that
  172572. * the output colors are equally spaced; if not, results will probably be
  172573. * worse, since the dither may be too much or too little at a given point.
  172574. *
  172575. * The normal calculation would be to form pixel value + dither, range-limit
  172576. * this to 0..MAXJSAMPLE, and then index into the colorindex table as usual.
  172577. * We can skip the separate range-limiting step by extending the colorindex
  172578. * table in both directions.
  172579. */
  172580. #define ODITHER_SIZE 16 /* dimension of dither matrix */
  172581. /* NB: if ODITHER_SIZE is not a power of 2, ODITHER_MASK uses will break */
  172582. #define ODITHER_CELLS (ODITHER_SIZE*ODITHER_SIZE) /* # cells in matrix */
  172583. #define ODITHER_MASK (ODITHER_SIZE-1) /* mask for wrapping around counters */
  172584. typedef int ODITHER_MATRIX[ODITHER_SIZE][ODITHER_SIZE];
  172585. typedef int (*ODITHER_MATRIX_PTR)[ODITHER_SIZE];
  172586. static const UINT8 base_dither_matrix[ODITHER_SIZE][ODITHER_SIZE] = {
  172587. /* Bayer's order-4 dither array. Generated by the code given in
  172588. * Stephen Hawley's article "Ordered Dithering" in Graphics Gems I.
  172589. * The values in this array must range from 0 to ODITHER_CELLS-1.
  172590. */
  172591. { 0,192, 48,240, 12,204, 60,252, 3,195, 51,243, 15,207, 63,255 },
  172592. { 128, 64,176,112,140, 76,188,124,131, 67,179,115,143, 79,191,127 },
  172593. { 32,224, 16,208, 44,236, 28,220, 35,227, 19,211, 47,239, 31,223 },
  172594. { 160, 96,144, 80,172,108,156, 92,163, 99,147, 83,175,111,159, 95 },
  172595. { 8,200, 56,248, 4,196, 52,244, 11,203, 59,251, 7,199, 55,247 },
  172596. { 136, 72,184,120,132, 68,180,116,139, 75,187,123,135, 71,183,119 },
  172597. { 40,232, 24,216, 36,228, 20,212, 43,235, 27,219, 39,231, 23,215 },
  172598. { 168,104,152, 88,164,100,148, 84,171,107,155, 91,167,103,151, 87 },
  172599. { 2,194, 50,242, 14,206, 62,254, 1,193, 49,241, 13,205, 61,253 },
  172600. { 130, 66,178,114,142, 78,190,126,129, 65,177,113,141, 77,189,125 },
  172601. { 34,226, 18,210, 46,238, 30,222, 33,225, 17,209, 45,237, 29,221 },
  172602. { 162, 98,146, 82,174,110,158, 94,161, 97,145, 81,173,109,157, 93 },
  172603. { 10,202, 58,250, 6,198, 54,246, 9,201, 57,249, 5,197, 53,245 },
  172604. { 138, 74,186,122,134, 70,182,118,137, 73,185,121,133, 69,181,117 },
  172605. { 42,234, 26,218, 38,230, 22,214, 41,233, 25,217, 37,229, 21,213 },
  172606. { 170,106,154, 90,166,102,150, 86,169,105,153, 89,165,101,149, 85 }
  172607. };
  172608. /* Declarations for Floyd-Steinberg dithering.
  172609. *
  172610. * Errors are accumulated into the array fserrors[], at a resolution of
  172611. * 1/16th of a pixel count. The error at a given pixel is propagated
  172612. * to its not-yet-processed neighbors using the standard F-S fractions,
  172613. * ... (here) 7/16
  172614. * 3/16 5/16 1/16
  172615. * We work left-to-right on even rows, right-to-left on odd rows.
  172616. *
  172617. * We can get away with a single array (holding one row's worth of errors)
  172618. * by using it to store the current row's errors at pixel columns not yet
  172619. * processed, but the next row's errors at columns already processed. We
  172620. * need only a few extra variables to hold the errors immediately around the
  172621. * current column. (If we are lucky, those variables are in registers, but
  172622. * even if not, they're probably cheaper to access than array elements are.)
  172623. *
  172624. * The fserrors[] array is indexed [component#][position].
  172625. * We provide (#columns + 2) entries per component; the extra entry at each
  172626. * end saves us from special-casing the first and last pixels.
  172627. *
  172628. * Note: on a wide image, we might not have enough room in a PC's near data
  172629. * segment to hold the error array; so it is allocated with alloc_large.
  172630. */
  172631. #if BITS_IN_JSAMPLE == 8
  172632. typedef INT16 FSERROR; /* 16 bits should be enough */
  172633. typedef int LOCFSERROR; /* use 'int' for calculation temps */
  172634. #else
  172635. typedef INT32 FSERROR; /* may need more than 16 bits */
  172636. typedef INT32 LOCFSERROR; /* be sure calculation temps are big enough */
  172637. #endif
  172638. typedef FSERROR FAR *FSERRPTR; /* pointer to error array (in FAR storage!) */
  172639. /* Private subobject */
  172640. #define MAX_Q_COMPS 4 /* max components I can handle */
  172641. typedef struct {
  172642. struct jpeg_color_quantizer pub; /* public fields */
  172643. /* Initially allocated colormap is saved here */
  172644. JSAMPARRAY sv_colormap; /* The color map as a 2-D pixel array */
  172645. int sv_actual; /* number of entries in use */
  172646. JSAMPARRAY colorindex; /* Precomputed mapping for speed */
  172647. /* colorindex[i][j] = index of color closest to pixel value j in component i,
  172648. * premultiplied as described above. Since colormap indexes must fit into
  172649. * JSAMPLEs, the entries of this array will too.
  172650. */
  172651. boolean is_padded; /* is the colorindex padded for odither? */
  172652. int Ncolors[MAX_Q_COMPS]; /* # of values alloced to each component */
  172653. /* Variables for ordered dithering */
  172654. int row_index; /* cur row's vertical index in dither matrix */
  172655. ODITHER_MATRIX_PTR odither[MAX_Q_COMPS]; /* one dither array per component */
  172656. /* Variables for Floyd-Steinberg dithering */
  172657. FSERRPTR fserrors[MAX_Q_COMPS]; /* accumulated errors */
  172658. boolean on_odd_row; /* flag to remember which row we are on */
  172659. } my_cquantizer;
  172660. typedef my_cquantizer * my_cquantize_ptr;
  172661. /*
  172662. * Policy-making subroutines for create_colormap and create_colorindex.
  172663. * These routines determine the colormap to be used. The rest of the module
  172664. * only assumes that the colormap is orthogonal.
  172665. *
  172666. * * select_ncolors decides how to divvy up the available colors
  172667. * among the components.
  172668. * * output_value defines the set of representative values for a component.
  172669. * * largest_input_value defines the mapping from input values to
  172670. * representative values for a component.
  172671. * Note that the latter two routines may impose different policies for
  172672. * different components, though this is not currently done.
  172673. */
  172674. LOCAL(int)
  172675. select_ncolors (j_decompress_ptr cinfo, int Ncolors[])
  172676. /* Determine allocation of desired colors to components, */
  172677. /* and fill in Ncolors[] array to indicate choice. */
  172678. /* Return value is total number of colors (product of Ncolors[] values). */
  172679. {
  172680. int nc = cinfo->out_color_components; /* number of color components */
  172681. int max_colors = cinfo->desired_number_of_colors;
  172682. int total_colors, iroot, i, j;
  172683. boolean changed;
  172684. long temp;
  172685. static const int RGB_order[3] = { RGB_GREEN, RGB_RED, RGB_BLUE };
  172686. /* We can allocate at least the nc'th root of max_colors per component. */
  172687. /* Compute floor(nc'th root of max_colors). */
  172688. iroot = 1;
  172689. do {
  172690. iroot++;
  172691. temp = iroot; /* set temp = iroot ** nc */
  172692. for (i = 1; i < nc; i++)
  172693. temp *= iroot;
  172694. } while (temp <= (long) max_colors); /* repeat till iroot exceeds root */
  172695. iroot--; /* now iroot = floor(root) */
  172696. /* Must have at least 2 color values per component */
  172697. if (iroot < 2)
  172698. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, (int) temp);
  172699. /* Initialize to iroot color values for each component */
  172700. total_colors = 1;
  172701. for (i = 0; i < nc; i++) {
  172702. Ncolors[i] = iroot;
  172703. total_colors *= iroot;
  172704. }
  172705. /* We may be able to increment the count for one or more components without
  172706. * exceeding max_colors, though we know not all can be incremented.
  172707. * Sometimes, the first component can be incremented more than once!
  172708. * (Example: for 16 colors, we start at 2*2*2, go to 3*2*2, then 4*2*2.)
  172709. * In RGB colorspace, try to increment G first, then R, then B.
  172710. */
  172711. do {
  172712. changed = FALSE;
  172713. for (i = 0; i < nc; i++) {
  172714. j = (cinfo->out_color_space == JCS_RGB ? RGB_order[i] : i);
  172715. /* calculate new total_colors if Ncolors[j] is incremented */
  172716. temp = total_colors / Ncolors[j];
  172717. temp *= Ncolors[j]+1; /* done in long arith to avoid oflo */
  172718. if (temp > (long) max_colors)
  172719. break; /* won't fit, done with this pass */
  172720. Ncolors[j]++; /* OK, apply the increment */
  172721. total_colors = (int) temp;
  172722. changed = TRUE;
  172723. }
  172724. } while (changed);
  172725. return total_colors;
  172726. }
  172727. LOCAL(int)
  172728. output_value (j_decompress_ptr cinfo, int ci, int j, int maxj)
  172729. /* Return j'th output value, where j will range from 0 to maxj */
  172730. /* The output values must fall in 0..MAXJSAMPLE in increasing order */
  172731. {
  172732. /* We always provide values 0 and MAXJSAMPLE for each component;
  172733. * any additional values are equally spaced between these limits.
  172734. * (Forcing the upper and lower values to the limits ensures that
  172735. * dithering can't produce a color outside the selected gamut.)
  172736. */
  172737. return (int) (((INT32) j * MAXJSAMPLE + maxj/2) / maxj);
  172738. }
  172739. LOCAL(int)
  172740. largest_input_value (j_decompress_ptr cinfo, int ci, int j, int maxj)
  172741. /* Return largest input value that should map to j'th output value */
  172742. /* Must have largest(j=0) >= 0, and largest(j=maxj) >= MAXJSAMPLE */
  172743. {
  172744. /* Breakpoints are halfway between values returned by output_value */
  172745. return (int) (((INT32) (2*j + 1) * MAXJSAMPLE + maxj) / (2*maxj));
  172746. }
  172747. /*
  172748. * Create the colormap.
  172749. */
  172750. LOCAL(void)
  172751. create_colormap (j_decompress_ptr cinfo)
  172752. {
  172753. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  172754. JSAMPARRAY colormap; /* Created colormap */
  172755. int total_colors; /* Number of distinct output colors */
  172756. int i,j,k, nci, blksize, blkdist, ptr, val;
  172757. /* Select number of colors for each component */
  172758. total_colors = select_ncolors(cinfo, cquantize->Ncolors);
  172759. /* Report selected color counts */
  172760. if (cinfo->out_color_components == 3)
  172761. TRACEMS4(cinfo, 1, JTRC_QUANT_3_NCOLORS,
  172762. total_colors, cquantize->Ncolors[0],
  172763. cquantize->Ncolors[1], cquantize->Ncolors[2]);
  172764. else
  172765. TRACEMS1(cinfo, 1, JTRC_QUANT_NCOLORS, total_colors);
  172766. /* Allocate and fill in the colormap. */
  172767. /* The colors are ordered in the map in standard row-major order, */
  172768. /* i.e. rightmost (highest-indexed) color changes most rapidly. */
  172769. colormap = (*cinfo->mem->alloc_sarray)
  172770. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172771. (JDIMENSION) total_colors, (JDIMENSION) cinfo->out_color_components);
  172772. /* blksize is number of adjacent repeated entries for a component */
  172773. /* blkdist is distance between groups of identical entries for a component */
  172774. blkdist = total_colors;
  172775. for (i = 0; i < cinfo->out_color_components; i++) {
  172776. /* fill in colormap entries for i'th color component */
  172777. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  172778. blksize = blkdist / nci;
  172779. for (j = 0; j < nci; j++) {
  172780. /* Compute j'th output value (out of nci) for component */
  172781. val = output_value(cinfo, i, j, nci-1);
  172782. /* Fill in all colormap entries that have this value of this component */
  172783. for (ptr = j * blksize; ptr < total_colors; ptr += blkdist) {
  172784. /* fill in blksize entries beginning at ptr */
  172785. for (k = 0; k < blksize; k++)
  172786. colormap[i][ptr+k] = (JSAMPLE) val;
  172787. }
  172788. }
  172789. blkdist = blksize; /* blksize of this color is blkdist of next */
  172790. }
  172791. /* Save the colormap in private storage,
  172792. * where it will survive color quantization mode changes.
  172793. */
  172794. cquantize->sv_colormap = colormap;
  172795. cquantize->sv_actual = total_colors;
  172796. }
  172797. /*
  172798. * Create the color index table.
  172799. */
  172800. LOCAL(void)
  172801. create_colorindex (j_decompress_ptr cinfo)
  172802. {
  172803. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  172804. JSAMPROW indexptr;
  172805. int i,j,k, nci, blksize, val, pad;
  172806. /* For ordered dither, we pad the color index tables by MAXJSAMPLE in
  172807. * each direction (input index values can be -MAXJSAMPLE .. 2*MAXJSAMPLE).
  172808. * This is not necessary in the other dithering modes. However, we
  172809. * flag whether it was done in case user changes dithering mode.
  172810. */
  172811. if (cinfo->dither_mode == JDITHER_ORDERED) {
  172812. pad = MAXJSAMPLE*2;
  172813. cquantize->is_padded = TRUE;
  172814. } else {
  172815. pad = 0;
  172816. cquantize->is_padded = FALSE;
  172817. }
  172818. cquantize->colorindex = (*cinfo->mem->alloc_sarray)
  172819. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172820. (JDIMENSION) (MAXJSAMPLE+1 + pad),
  172821. (JDIMENSION) cinfo->out_color_components);
  172822. /* blksize is number of adjacent repeated entries for a component */
  172823. blksize = cquantize->sv_actual;
  172824. for (i = 0; i < cinfo->out_color_components; i++) {
  172825. /* fill in colorindex entries for i'th color component */
  172826. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  172827. blksize = blksize / nci;
  172828. /* adjust colorindex pointers to provide padding at negative indexes. */
  172829. if (pad)
  172830. cquantize->colorindex[i] += MAXJSAMPLE;
  172831. /* in loop, val = index of current output value, */
  172832. /* and k = largest j that maps to current val */
  172833. indexptr = cquantize->colorindex[i];
  172834. val = 0;
  172835. k = largest_input_value(cinfo, i, 0, nci-1);
  172836. for (j = 0; j <= MAXJSAMPLE; j++) {
  172837. while (j > k) /* advance val if past boundary */
  172838. k = largest_input_value(cinfo, i, ++val, nci-1);
  172839. /* premultiply so that no multiplication needed in main processing */
  172840. indexptr[j] = (JSAMPLE) (val * blksize);
  172841. }
  172842. /* Pad at both ends if necessary */
  172843. if (pad)
  172844. for (j = 1; j <= MAXJSAMPLE; j++) {
  172845. indexptr[-j] = indexptr[0];
  172846. indexptr[MAXJSAMPLE+j] = indexptr[MAXJSAMPLE];
  172847. }
  172848. }
  172849. }
  172850. /*
  172851. * Create an ordered-dither array for a component having ncolors
  172852. * distinct output values.
  172853. */
  172854. LOCAL(ODITHER_MATRIX_PTR)
  172855. make_odither_array (j_decompress_ptr cinfo, int ncolors)
  172856. {
  172857. ODITHER_MATRIX_PTR odither;
  172858. int j,k;
  172859. INT32 num,den;
  172860. odither = (ODITHER_MATRIX_PTR)
  172861. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172862. SIZEOF(ODITHER_MATRIX));
  172863. /* The inter-value distance for this color is MAXJSAMPLE/(ncolors-1).
  172864. * Hence the dither value for the matrix cell with fill order f
  172865. * (f=0..N-1) should be (N-1-2*f)/(2*N) * MAXJSAMPLE/(ncolors-1).
  172866. * On 16-bit-int machine, be careful to avoid overflow.
  172867. */
  172868. den = 2 * ODITHER_CELLS * ((INT32) (ncolors - 1));
  172869. for (j = 0; j < ODITHER_SIZE; j++) {
  172870. for (k = 0; k < ODITHER_SIZE; k++) {
  172871. num = ((INT32) (ODITHER_CELLS-1 - 2*((int)base_dither_matrix[j][k])))
  172872. * MAXJSAMPLE;
  172873. /* Ensure round towards zero despite C's lack of consistency
  172874. * about rounding negative values in integer division...
  172875. */
  172876. odither[j][k] = (int) (num<0 ? -((-num)/den) : num/den);
  172877. }
  172878. }
  172879. return odither;
  172880. }
  172881. /*
  172882. * Create the ordered-dither tables.
  172883. * Components having the same number of representative colors may
  172884. * share a dither table.
  172885. */
  172886. LOCAL(void)
  172887. create_odither_tables (j_decompress_ptr cinfo)
  172888. {
  172889. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  172890. ODITHER_MATRIX_PTR odither;
  172891. int i, j, nci;
  172892. for (i = 0; i < cinfo->out_color_components; i++) {
  172893. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  172894. odither = NULL; /* search for matching prior component */
  172895. for (j = 0; j < i; j++) {
  172896. if (nci == cquantize->Ncolors[j]) {
  172897. odither = cquantize->odither[j];
  172898. break;
  172899. }
  172900. }
  172901. if (odither == NULL) /* need a new table? */
  172902. odither = make_odither_array(cinfo, nci);
  172903. cquantize->odither[i] = odither;
  172904. }
  172905. }
  172906. /*
  172907. * Map some rows of pixels to the output colormapped representation.
  172908. */
  172909. METHODDEF(void)
  172910. color_quantize (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  172911. JSAMPARRAY output_buf, int num_rows)
  172912. /* General case, no dithering */
  172913. {
  172914. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  172915. JSAMPARRAY colorindex = cquantize->colorindex;
  172916. register int pixcode, ci;
  172917. register JSAMPROW ptrin, ptrout;
  172918. int row;
  172919. JDIMENSION col;
  172920. JDIMENSION width = cinfo->output_width;
  172921. register int nc = cinfo->out_color_components;
  172922. for (row = 0; row < num_rows; row++) {
  172923. ptrin = input_buf[row];
  172924. ptrout = output_buf[row];
  172925. for (col = width; col > 0; col--) {
  172926. pixcode = 0;
  172927. for (ci = 0; ci < nc; ci++) {
  172928. pixcode += GETJSAMPLE(colorindex[ci][GETJSAMPLE(*ptrin++)]);
  172929. }
  172930. *ptrout++ = (JSAMPLE) pixcode;
  172931. }
  172932. }
  172933. }
  172934. METHODDEF(void)
  172935. color_quantize3 (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  172936. JSAMPARRAY output_buf, int num_rows)
  172937. /* Fast path for out_color_components==3, no dithering */
  172938. {
  172939. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  172940. register int pixcode;
  172941. register JSAMPROW ptrin, ptrout;
  172942. JSAMPROW colorindex0 = cquantize->colorindex[0];
  172943. JSAMPROW colorindex1 = cquantize->colorindex[1];
  172944. JSAMPROW colorindex2 = cquantize->colorindex[2];
  172945. int row;
  172946. JDIMENSION col;
  172947. JDIMENSION width = cinfo->output_width;
  172948. for (row = 0; row < num_rows; row++) {
  172949. ptrin = input_buf[row];
  172950. ptrout = output_buf[row];
  172951. for (col = width; col > 0; col--) {
  172952. pixcode = GETJSAMPLE(colorindex0[GETJSAMPLE(*ptrin++)]);
  172953. pixcode += GETJSAMPLE(colorindex1[GETJSAMPLE(*ptrin++)]);
  172954. pixcode += GETJSAMPLE(colorindex2[GETJSAMPLE(*ptrin++)]);
  172955. *ptrout++ = (JSAMPLE) pixcode;
  172956. }
  172957. }
  172958. }
  172959. METHODDEF(void)
  172960. quantize_ord_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  172961. JSAMPARRAY output_buf, int num_rows)
  172962. /* General case, with ordered dithering */
  172963. {
  172964. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  172965. register JSAMPROW input_ptr;
  172966. register JSAMPROW output_ptr;
  172967. JSAMPROW colorindex_ci;
  172968. int * dither; /* points to active row of dither matrix */
  172969. int row_index, col_index; /* current indexes into dither matrix */
  172970. int nc = cinfo->out_color_components;
  172971. int ci;
  172972. int row;
  172973. JDIMENSION col;
  172974. JDIMENSION width = cinfo->output_width;
  172975. for (row = 0; row < num_rows; row++) {
  172976. /* Initialize output values to 0 so can process components separately */
  172977. jzero_far((void FAR *) output_buf[row],
  172978. (size_t) (width * SIZEOF(JSAMPLE)));
  172979. row_index = cquantize->row_index;
  172980. for (ci = 0; ci < nc; ci++) {
  172981. input_ptr = input_buf[row] + ci;
  172982. output_ptr = output_buf[row];
  172983. colorindex_ci = cquantize->colorindex[ci];
  172984. dither = cquantize->odither[ci][row_index];
  172985. col_index = 0;
  172986. for (col = width; col > 0; col--) {
  172987. /* Form pixel value + dither, range-limit to 0..MAXJSAMPLE,
  172988. * select output value, accumulate into output code for this pixel.
  172989. * Range-limiting need not be done explicitly, as we have extended
  172990. * the colorindex table to produce the right answers for out-of-range
  172991. * inputs. The maximum dither is +- MAXJSAMPLE; this sets the
  172992. * required amount of padding.
  172993. */
  172994. *output_ptr += colorindex_ci[GETJSAMPLE(*input_ptr)+dither[col_index]];
  172995. input_ptr += nc;
  172996. output_ptr++;
  172997. col_index = (col_index + 1) & ODITHER_MASK;
  172998. }
  172999. }
  173000. /* Advance row index for next row */
  173001. row_index = (row_index + 1) & ODITHER_MASK;
  173002. cquantize->row_index = row_index;
  173003. }
  173004. }
  173005. METHODDEF(void)
  173006. quantize3_ord_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  173007. JSAMPARRAY output_buf, int num_rows)
  173008. /* Fast path for out_color_components==3, with ordered dithering */
  173009. {
  173010. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  173011. register int pixcode;
  173012. register JSAMPROW input_ptr;
  173013. register JSAMPROW output_ptr;
  173014. JSAMPROW colorindex0 = cquantize->colorindex[0];
  173015. JSAMPROW colorindex1 = cquantize->colorindex[1];
  173016. JSAMPROW colorindex2 = cquantize->colorindex[2];
  173017. int * dither0; /* points to active row of dither matrix */
  173018. int * dither1;
  173019. int * dither2;
  173020. int row_index, col_index; /* current indexes into dither matrix */
  173021. int row;
  173022. JDIMENSION col;
  173023. JDIMENSION width = cinfo->output_width;
  173024. for (row = 0; row < num_rows; row++) {
  173025. row_index = cquantize->row_index;
  173026. input_ptr = input_buf[row];
  173027. output_ptr = output_buf[row];
  173028. dither0 = cquantize->odither[0][row_index];
  173029. dither1 = cquantize->odither[1][row_index];
  173030. dither2 = cquantize->odither[2][row_index];
  173031. col_index = 0;
  173032. for (col = width; col > 0; col--) {
  173033. pixcode = GETJSAMPLE(colorindex0[GETJSAMPLE(*input_ptr++) +
  173034. dither0[col_index]]);
  173035. pixcode += GETJSAMPLE(colorindex1[GETJSAMPLE(*input_ptr++) +
  173036. dither1[col_index]]);
  173037. pixcode += GETJSAMPLE(colorindex2[GETJSAMPLE(*input_ptr++) +
  173038. dither2[col_index]]);
  173039. *output_ptr++ = (JSAMPLE) pixcode;
  173040. col_index = (col_index + 1) & ODITHER_MASK;
  173041. }
  173042. row_index = (row_index + 1) & ODITHER_MASK;
  173043. cquantize->row_index = row_index;
  173044. }
  173045. }
  173046. METHODDEF(void)
  173047. quantize_fs_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  173048. JSAMPARRAY output_buf, int num_rows)
  173049. /* General case, with Floyd-Steinberg dithering */
  173050. {
  173051. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  173052. register LOCFSERROR cur; /* current error or pixel value */
  173053. LOCFSERROR belowerr; /* error for pixel below cur */
  173054. LOCFSERROR bpreverr; /* error for below/prev col */
  173055. LOCFSERROR bnexterr; /* error for below/next col */
  173056. LOCFSERROR delta;
  173057. register FSERRPTR errorptr; /* => fserrors[] at column before current */
  173058. register JSAMPROW input_ptr;
  173059. register JSAMPROW output_ptr;
  173060. JSAMPROW colorindex_ci;
  173061. JSAMPROW colormap_ci;
  173062. int pixcode;
  173063. int nc = cinfo->out_color_components;
  173064. int dir; /* 1 for left-to-right, -1 for right-to-left */
  173065. int dirnc; /* dir * nc */
  173066. int ci;
  173067. int row;
  173068. JDIMENSION col;
  173069. JDIMENSION width = cinfo->output_width;
  173070. JSAMPLE *range_limit = cinfo->sample_range_limit;
  173071. SHIFT_TEMPS
  173072. for (row = 0; row < num_rows; row++) {
  173073. /* Initialize output values to 0 so can process components separately */
  173074. jzero_far((void FAR *) output_buf[row],
  173075. (size_t) (width * SIZEOF(JSAMPLE)));
  173076. for (ci = 0; ci < nc; ci++) {
  173077. input_ptr = input_buf[row] + ci;
  173078. output_ptr = output_buf[row];
  173079. if (cquantize->on_odd_row) {
  173080. /* work right to left in this row */
  173081. input_ptr += (width-1) * nc; /* so point to rightmost pixel */
  173082. output_ptr += width-1;
  173083. dir = -1;
  173084. dirnc = -nc;
  173085. errorptr = cquantize->fserrors[ci] + (width+1); /* => entry after last column */
  173086. } else {
  173087. /* work left to right in this row */
  173088. dir = 1;
  173089. dirnc = nc;
  173090. errorptr = cquantize->fserrors[ci]; /* => entry before first column */
  173091. }
  173092. colorindex_ci = cquantize->colorindex[ci];
  173093. colormap_ci = cquantize->sv_colormap[ci];
  173094. /* Preset error values: no error propagated to first pixel from left */
  173095. cur = 0;
  173096. /* and no error propagated to row below yet */
  173097. belowerr = bpreverr = 0;
  173098. for (col = width; col > 0; col--) {
  173099. /* cur holds the error propagated from the previous pixel on the
  173100. * current line. Add the error propagated from the previous line
  173101. * to form the complete error correction term for this pixel, and
  173102. * round the error term (which is expressed * 16) to an integer.
  173103. * RIGHT_SHIFT rounds towards minus infinity, so adding 8 is correct
  173104. * for either sign of the error value.
  173105. * Note: errorptr points to *previous* column's array entry.
  173106. */
  173107. cur = RIGHT_SHIFT(cur + errorptr[dir] + 8, 4);
  173108. /* Form pixel value + error, and range-limit to 0..MAXJSAMPLE.
  173109. * The maximum error is +- MAXJSAMPLE; this sets the required size
  173110. * of the range_limit array.
  173111. */
  173112. cur += GETJSAMPLE(*input_ptr);
  173113. cur = GETJSAMPLE(range_limit[cur]);
  173114. /* Select output value, accumulate into output code for this pixel */
  173115. pixcode = GETJSAMPLE(colorindex_ci[cur]);
  173116. *output_ptr += (JSAMPLE) pixcode;
  173117. /* Compute actual representation error at this pixel */
  173118. /* Note: we can do this even though we don't have the final */
  173119. /* pixel code, because the colormap is orthogonal. */
  173120. cur -= GETJSAMPLE(colormap_ci[pixcode]);
  173121. /* Compute error fractions to be propagated to adjacent pixels.
  173122. * Add these into the running sums, and simultaneously shift the
  173123. * next-line error sums left by 1 column.
  173124. */
  173125. bnexterr = cur;
  173126. delta = cur * 2;
  173127. cur += delta; /* form error * 3 */
  173128. errorptr[0] = (FSERROR) (bpreverr + cur);
  173129. cur += delta; /* form error * 5 */
  173130. bpreverr = belowerr + cur;
  173131. belowerr = bnexterr;
  173132. cur += delta; /* form error * 7 */
  173133. /* At this point cur contains the 7/16 error value to be propagated
  173134. * to the next pixel on the current line, and all the errors for the
  173135. * next line have been shifted over. We are therefore ready to move on.
  173136. */
  173137. input_ptr += dirnc; /* advance input ptr to next column */
  173138. output_ptr += dir; /* advance output ptr to next column */
  173139. errorptr += dir; /* advance errorptr to current column */
  173140. }
  173141. /* Post-loop cleanup: we must unload the final error value into the
  173142. * final fserrors[] entry. Note we need not unload belowerr because
  173143. * it is for the dummy column before or after the actual array.
  173144. */
  173145. errorptr[0] = (FSERROR) bpreverr; /* unload prev err into array */
  173146. }
  173147. cquantize->on_odd_row = (cquantize->on_odd_row ? FALSE : TRUE);
  173148. }
  173149. }
  173150. /*
  173151. * Allocate workspace for Floyd-Steinberg errors.
  173152. */
  173153. LOCAL(void)
  173154. alloc_fs_workspace (j_decompress_ptr cinfo)
  173155. {
  173156. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  173157. size_t arraysize;
  173158. int i;
  173159. arraysize = (size_t) ((cinfo->output_width + 2) * SIZEOF(FSERROR));
  173160. for (i = 0; i < cinfo->out_color_components; i++) {
  173161. cquantize->fserrors[i] = (FSERRPTR)
  173162. (*cinfo->mem->alloc_large)((j_common_ptr) cinfo, JPOOL_IMAGE, arraysize);
  173163. }
  173164. }
  173165. /*
  173166. * Initialize for one-pass color quantization.
  173167. */
  173168. METHODDEF(void)
  173169. start_pass_1_quant (j_decompress_ptr cinfo, boolean is_pre_scan)
  173170. {
  173171. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  173172. size_t arraysize;
  173173. int i;
  173174. /* Install my colormap. */
  173175. cinfo->colormap = cquantize->sv_colormap;
  173176. cinfo->actual_number_of_colors = cquantize->sv_actual;
  173177. /* Initialize for desired dithering mode. */
  173178. switch (cinfo->dither_mode) {
  173179. case JDITHER_NONE:
  173180. if (cinfo->out_color_components == 3)
  173181. cquantize->pub.color_quantize = color_quantize3;
  173182. else
  173183. cquantize->pub.color_quantize = color_quantize;
  173184. break;
  173185. case JDITHER_ORDERED:
  173186. if (cinfo->out_color_components == 3)
  173187. cquantize->pub.color_quantize = quantize3_ord_dither;
  173188. else
  173189. cquantize->pub.color_quantize = quantize_ord_dither;
  173190. cquantize->row_index = 0; /* initialize state for ordered dither */
  173191. /* If user changed to ordered dither from another mode,
  173192. * we must recreate the color index table with padding.
  173193. * This will cost extra space, but probably isn't very likely.
  173194. */
  173195. if (! cquantize->is_padded)
  173196. create_colorindex(cinfo);
  173197. /* Create ordered-dither tables if we didn't already. */
  173198. if (cquantize->odither[0] == NULL)
  173199. create_odither_tables(cinfo);
  173200. break;
  173201. case JDITHER_FS:
  173202. cquantize->pub.color_quantize = quantize_fs_dither;
  173203. cquantize->on_odd_row = FALSE; /* initialize state for F-S dither */
  173204. /* Allocate Floyd-Steinberg workspace if didn't already. */
  173205. if (cquantize->fserrors[0] == NULL)
  173206. alloc_fs_workspace(cinfo);
  173207. /* Initialize the propagated errors to zero. */
  173208. arraysize = (size_t) ((cinfo->output_width + 2) * SIZEOF(FSERROR));
  173209. for (i = 0; i < cinfo->out_color_components; i++)
  173210. jzero_far((void FAR *) cquantize->fserrors[i], arraysize);
  173211. break;
  173212. default:
  173213. ERREXIT(cinfo, JERR_NOT_COMPILED);
  173214. break;
  173215. }
  173216. }
  173217. /*
  173218. * Finish up at the end of the pass.
  173219. */
  173220. METHODDEF(void)
  173221. finish_pass_1_quant (j_decompress_ptr cinfo)
  173222. {
  173223. /* no work in 1-pass case */
  173224. }
  173225. /*
  173226. * Switch to a new external colormap between output passes.
  173227. * Shouldn't get to this module!
  173228. */
  173229. METHODDEF(void)
  173230. new_color_map_1_quant (j_decompress_ptr cinfo)
  173231. {
  173232. ERREXIT(cinfo, JERR_MODE_CHANGE);
  173233. }
  173234. /*
  173235. * Module initialization routine for 1-pass color quantization.
  173236. */
  173237. GLOBAL(void)
  173238. jinit_1pass_quantizer (j_decompress_ptr cinfo)
  173239. {
  173240. my_cquantize_ptr cquantize;
  173241. cquantize = (my_cquantize_ptr)
  173242. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173243. SIZEOF(my_cquantizer));
  173244. cinfo->cquantize = (struct jpeg_color_quantizer *) cquantize;
  173245. cquantize->pub.start_pass = start_pass_1_quant;
  173246. cquantize->pub.finish_pass = finish_pass_1_quant;
  173247. cquantize->pub.new_color_map = new_color_map_1_quant;
  173248. cquantize->fserrors[0] = NULL; /* Flag FS workspace not allocated */
  173249. cquantize->odither[0] = NULL; /* Also flag odither arrays not allocated */
  173250. /* Make sure my internal arrays won't overflow */
  173251. if (cinfo->out_color_components > MAX_Q_COMPS)
  173252. ERREXIT1(cinfo, JERR_QUANT_COMPONENTS, MAX_Q_COMPS);
  173253. /* Make sure colormap indexes can be represented by JSAMPLEs */
  173254. if (cinfo->desired_number_of_colors > (MAXJSAMPLE+1))
  173255. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXJSAMPLE+1);
  173256. /* Create the colormap and color index table. */
  173257. create_colormap(cinfo);
  173258. create_colorindex(cinfo);
  173259. /* Allocate Floyd-Steinberg workspace now if requested.
  173260. * We do this now since it is FAR storage and may affect the memory
  173261. * manager's space calculations. If the user changes to FS dither
  173262. * mode in a later pass, we will allocate the space then, and will
  173263. * possibly overrun the max_memory_to_use setting.
  173264. */
  173265. if (cinfo->dither_mode == JDITHER_FS)
  173266. alloc_fs_workspace(cinfo);
  173267. }
  173268. #endif /* QUANT_1PASS_SUPPORTED */
  173269. /********* End of inlined file: jquant1.c *********/
  173270. /********* Start of inlined file: jquant2.c *********/
  173271. #define JPEG_INTERNALS
  173272. #ifdef QUANT_2PASS_SUPPORTED
  173273. /*
  173274. * This module implements the well-known Heckbert paradigm for color
  173275. * quantization. Most of the ideas used here can be traced back to
  173276. * Heckbert's seminal paper
  173277. * Heckbert, Paul. "Color Image Quantization for Frame Buffer Display",
  173278. * Proc. SIGGRAPH '82, Computer Graphics v.16 #3 (July 1982), pp 297-304.
  173279. *
  173280. * In the first pass over the image, we accumulate a histogram showing the
  173281. * usage count of each possible color. To keep the histogram to a reasonable
  173282. * size, we reduce the precision of the input; typical practice is to retain
  173283. * 5 or 6 bits per color, so that 8 or 4 different input values are counted
  173284. * in the same histogram cell.
  173285. *
  173286. * Next, the color-selection step begins with a box representing the whole
  173287. * color space, and repeatedly splits the "largest" remaining box until we
  173288. * have as many boxes as desired colors. Then the mean color in each
  173289. * remaining box becomes one of the possible output colors.
  173290. *
  173291. * The second pass over the image maps each input pixel to the closest output
  173292. * color (optionally after applying a Floyd-Steinberg dithering correction).
  173293. * This mapping is logically trivial, but making it go fast enough requires
  173294. * considerable care.
  173295. *
  173296. * Heckbert-style quantizers vary a good deal in their policies for choosing
  173297. * the "largest" box and deciding where to cut it. The particular policies
  173298. * used here have proved out well in experimental comparisons, but better ones
  173299. * may yet be found.
  173300. *
  173301. * In earlier versions of the IJG code, this module quantized in YCbCr color
  173302. * space, processing the raw upsampled data without a color conversion step.
  173303. * This allowed the color conversion math to be done only once per colormap
  173304. * entry, not once per pixel. However, that optimization precluded other
  173305. * useful optimizations (such as merging color conversion with upsampling)
  173306. * and it also interfered with desired capabilities such as quantizing to an
  173307. * externally-supplied colormap. We have therefore abandoned that approach.
  173308. * The present code works in the post-conversion color space, typically RGB.
  173309. *
  173310. * To improve the visual quality of the results, we actually work in scaled
  173311. * RGB space, giving G distances more weight than R, and R in turn more than
  173312. * B. To do everything in integer math, we must use integer scale factors.
  173313. * The 2/3/1 scale factors used here correspond loosely to the relative
  173314. * weights of the colors in the NTSC grayscale equation.
  173315. * If you want to use this code to quantize a non-RGB color space, you'll
  173316. * probably need to change these scale factors.
  173317. */
  173318. #define R_SCALE 2 /* scale R distances by this much */
  173319. #define G_SCALE 3 /* scale G distances by this much */
  173320. #define B_SCALE 1 /* and B by this much */
  173321. /* Relabel R/G/B as components 0/1/2, respecting the RGB ordering defined
  173322. * in jmorecfg.h. As the code stands, it will do the right thing for R,G,B
  173323. * and B,G,R orders. If you define some other weird order in jmorecfg.h,
  173324. * you'll get compile errors until you extend this logic. In that case
  173325. * you'll probably want to tweak the histogram sizes too.
  173326. */
  173327. #if RGB_RED == 0
  173328. #define C0_SCALE R_SCALE
  173329. #endif
  173330. #if RGB_BLUE == 0
  173331. #define C0_SCALE B_SCALE
  173332. #endif
  173333. #if RGB_GREEN == 1
  173334. #define C1_SCALE G_SCALE
  173335. #endif
  173336. #if RGB_RED == 2
  173337. #define C2_SCALE R_SCALE
  173338. #endif
  173339. #if RGB_BLUE == 2
  173340. #define C2_SCALE B_SCALE
  173341. #endif
  173342. /*
  173343. * First we have the histogram data structure and routines for creating it.
  173344. *
  173345. * The number of bits of precision can be adjusted by changing these symbols.
  173346. * We recommend keeping 6 bits for G and 5 each for R and B.
  173347. * If you have plenty of memory and cycles, 6 bits all around gives marginally
  173348. * better results; if you are short of memory, 5 bits all around will save
  173349. * some space but degrade the results.
  173350. * To maintain a fully accurate histogram, we'd need to allocate a "long"
  173351. * (preferably unsigned long) for each cell. In practice this is overkill;
  173352. * we can get by with 16 bits per cell. Few of the cell counts will overflow,
  173353. * and clamping those that do overflow to the maximum value will give close-
  173354. * enough results. This reduces the recommended histogram size from 256Kb
  173355. * to 128Kb, which is a useful savings on PC-class machines.
  173356. * (In the second pass the histogram space is re-used for pixel mapping data;
  173357. * in that capacity, each cell must be able to store zero to the number of
  173358. * desired colors. 16 bits/cell is plenty for that too.)
  173359. * Since the JPEG code is intended to run in small memory model on 80x86
  173360. * machines, we can't just allocate the histogram in one chunk. Instead
  173361. * of a true 3-D array, we use a row of pointers to 2-D arrays. Each
  173362. * pointer corresponds to a C0 value (typically 2^5 = 32 pointers) and
  173363. * each 2-D array has 2^6*2^5 = 2048 or 2^6*2^6 = 4096 entries. Note that
  173364. * on 80x86 machines, the pointer row is in near memory but the actual
  173365. * arrays are in far memory (same arrangement as we use for image arrays).
  173366. */
  173367. #define MAXNUMCOLORS (MAXJSAMPLE+1) /* maximum size of colormap */
  173368. /* These will do the right thing for either R,G,B or B,G,R color order,
  173369. * but you may not like the results for other color orders.
  173370. */
  173371. #define HIST_C0_BITS 5 /* bits of precision in R/B histogram */
  173372. #define HIST_C1_BITS 6 /* bits of precision in G histogram */
  173373. #define HIST_C2_BITS 5 /* bits of precision in B/R histogram */
  173374. /* Number of elements along histogram axes. */
  173375. #define HIST_C0_ELEMS (1<<HIST_C0_BITS)
  173376. #define HIST_C1_ELEMS (1<<HIST_C1_BITS)
  173377. #define HIST_C2_ELEMS (1<<HIST_C2_BITS)
  173378. /* These are the amounts to shift an input value to get a histogram index. */
  173379. #define C0_SHIFT (BITS_IN_JSAMPLE-HIST_C0_BITS)
  173380. #define C1_SHIFT (BITS_IN_JSAMPLE-HIST_C1_BITS)
  173381. #define C2_SHIFT (BITS_IN_JSAMPLE-HIST_C2_BITS)
  173382. typedef UINT16 histcell; /* histogram cell; prefer an unsigned type */
  173383. typedef histcell FAR * histptr; /* for pointers to histogram cells */
  173384. typedef histcell hist1d[HIST_C2_ELEMS]; /* typedefs for the array */
  173385. typedef hist1d FAR * hist2d; /* type for the 2nd-level pointers */
  173386. typedef hist2d * hist3d; /* type for top-level pointer */
  173387. /* Declarations for Floyd-Steinberg dithering.
  173388. *
  173389. * Errors are accumulated into the array fserrors[], at a resolution of
  173390. * 1/16th of a pixel count. The error at a given pixel is propagated
  173391. * to its not-yet-processed neighbors using the standard F-S fractions,
  173392. * ... (here) 7/16
  173393. * 3/16 5/16 1/16
  173394. * We work left-to-right on even rows, right-to-left on odd rows.
  173395. *
  173396. * We can get away with a single array (holding one row's worth of errors)
  173397. * by using it to store the current row's errors at pixel columns not yet
  173398. * processed, but the next row's errors at columns already processed. We
  173399. * need only a few extra variables to hold the errors immediately around the
  173400. * current column. (If we are lucky, those variables are in registers, but
  173401. * even if not, they're probably cheaper to access than array elements are.)
  173402. *
  173403. * The fserrors[] array has (#columns + 2) entries; the extra entry at
  173404. * each end saves us from special-casing the first and last pixels.
  173405. * Each entry is three values long, one value for each color component.
  173406. *
  173407. * Note: on a wide image, we might not have enough room in a PC's near data
  173408. * segment to hold the error array; so it is allocated with alloc_large.
  173409. */
  173410. #if BITS_IN_JSAMPLE == 8
  173411. typedef INT16 FSERROR; /* 16 bits should be enough */
  173412. typedef int LOCFSERROR; /* use 'int' for calculation temps */
  173413. #else
  173414. typedef INT32 FSERROR; /* may need more than 16 bits */
  173415. typedef INT32 LOCFSERROR; /* be sure calculation temps are big enough */
  173416. #endif
  173417. typedef FSERROR FAR *FSERRPTR; /* pointer to error array (in FAR storage!) */
  173418. /* Private subobject */
  173419. typedef struct {
  173420. struct jpeg_color_quantizer pub; /* public fields */
  173421. /* Space for the eventually created colormap is stashed here */
  173422. JSAMPARRAY sv_colormap; /* colormap allocated at init time */
  173423. int desired; /* desired # of colors = size of colormap */
  173424. /* Variables for accumulating image statistics */
  173425. hist3d histogram; /* pointer to the histogram */
  173426. boolean needs_zeroed; /* TRUE if next pass must zero histogram */
  173427. /* Variables for Floyd-Steinberg dithering */
  173428. FSERRPTR fserrors; /* accumulated errors */
  173429. boolean on_odd_row; /* flag to remember which row we are on */
  173430. int * error_limiter; /* table for clamping the applied error */
  173431. } my_cquantizer2;
  173432. typedef my_cquantizer2 * my_cquantize_ptr2;
  173433. /*
  173434. * Prescan some rows of pixels.
  173435. * In this module the prescan simply updates the histogram, which has been
  173436. * initialized to zeroes by start_pass.
  173437. * An output_buf parameter is required by the method signature, but no data
  173438. * is actually output (in fact the buffer controller is probably passing a
  173439. * NULL pointer).
  173440. */
  173441. METHODDEF(void)
  173442. prescan_quantize (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  173443. JSAMPARRAY output_buf, int num_rows)
  173444. {
  173445. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  173446. register JSAMPROW ptr;
  173447. register histptr histp;
  173448. register hist3d histogram = cquantize->histogram;
  173449. int row;
  173450. JDIMENSION col;
  173451. JDIMENSION width = cinfo->output_width;
  173452. for (row = 0; row < num_rows; row++) {
  173453. ptr = input_buf[row];
  173454. for (col = width; col > 0; col--) {
  173455. /* get pixel value and index into the histogram */
  173456. histp = & histogram[GETJSAMPLE(ptr[0]) >> C0_SHIFT]
  173457. [GETJSAMPLE(ptr[1]) >> C1_SHIFT]
  173458. [GETJSAMPLE(ptr[2]) >> C2_SHIFT];
  173459. /* increment, check for overflow and undo increment if so. */
  173460. if (++(*histp) <= 0)
  173461. (*histp)--;
  173462. ptr += 3;
  173463. }
  173464. }
  173465. }
  173466. /*
  173467. * Next we have the really interesting routines: selection of a colormap
  173468. * given the completed histogram.
  173469. * These routines work with a list of "boxes", each representing a rectangular
  173470. * subset of the input color space (to histogram precision).
  173471. */
  173472. typedef struct {
  173473. /* The bounds of the box (inclusive); expressed as histogram indexes */
  173474. int c0min, c0max;
  173475. int c1min, c1max;
  173476. int c2min, c2max;
  173477. /* The volume (actually 2-norm) of the box */
  173478. INT32 volume;
  173479. /* The number of nonzero histogram cells within this box */
  173480. long colorcount;
  173481. } box;
  173482. typedef box * boxptr;
  173483. LOCAL(boxptr)
  173484. find_biggest_color_pop (boxptr boxlist, int numboxes)
  173485. /* Find the splittable box with the largest color population */
  173486. /* Returns NULL if no splittable boxes remain */
  173487. {
  173488. register boxptr boxp;
  173489. register int i;
  173490. register long maxc = 0;
  173491. boxptr which = NULL;
  173492. for (i = 0, boxp = boxlist; i < numboxes; i++, boxp++) {
  173493. if (boxp->colorcount > maxc && boxp->volume > 0) {
  173494. which = boxp;
  173495. maxc = boxp->colorcount;
  173496. }
  173497. }
  173498. return which;
  173499. }
  173500. LOCAL(boxptr)
  173501. find_biggest_volume (boxptr boxlist, int numboxes)
  173502. /* Find the splittable box with the largest (scaled) volume */
  173503. /* Returns NULL if no splittable boxes remain */
  173504. {
  173505. register boxptr boxp;
  173506. register int i;
  173507. register INT32 maxv = 0;
  173508. boxptr which = NULL;
  173509. for (i = 0, boxp = boxlist; i < numboxes; i++, boxp++) {
  173510. if (boxp->volume > maxv) {
  173511. which = boxp;
  173512. maxv = boxp->volume;
  173513. }
  173514. }
  173515. return which;
  173516. }
  173517. LOCAL(void)
  173518. update_box (j_decompress_ptr cinfo, boxptr boxp)
  173519. /* Shrink the min/max bounds of a box to enclose only nonzero elements, */
  173520. /* and recompute its volume and population */
  173521. {
  173522. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  173523. hist3d histogram = cquantize->histogram;
  173524. histptr histp;
  173525. int c0,c1,c2;
  173526. int c0min,c0max,c1min,c1max,c2min,c2max;
  173527. INT32 dist0,dist1,dist2;
  173528. long ccount;
  173529. c0min = boxp->c0min; c0max = boxp->c0max;
  173530. c1min = boxp->c1min; c1max = boxp->c1max;
  173531. c2min = boxp->c2min; c2max = boxp->c2max;
  173532. if (c0max > c0min)
  173533. for (c0 = c0min; c0 <= c0max; c0++)
  173534. for (c1 = c1min; c1 <= c1max; c1++) {
  173535. histp = & histogram[c0][c1][c2min];
  173536. for (c2 = c2min; c2 <= c2max; c2++)
  173537. if (*histp++ != 0) {
  173538. boxp->c0min = c0min = c0;
  173539. goto have_c0min;
  173540. }
  173541. }
  173542. have_c0min:
  173543. if (c0max > c0min)
  173544. for (c0 = c0max; c0 >= c0min; c0--)
  173545. for (c1 = c1min; c1 <= c1max; c1++) {
  173546. histp = & histogram[c0][c1][c2min];
  173547. for (c2 = c2min; c2 <= c2max; c2++)
  173548. if (*histp++ != 0) {
  173549. boxp->c0max = c0max = c0;
  173550. goto have_c0max;
  173551. }
  173552. }
  173553. have_c0max:
  173554. if (c1max > c1min)
  173555. for (c1 = c1min; c1 <= c1max; c1++)
  173556. for (c0 = c0min; c0 <= c0max; c0++) {
  173557. histp = & histogram[c0][c1][c2min];
  173558. for (c2 = c2min; c2 <= c2max; c2++)
  173559. if (*histp++ != 0) {
  173560. boxp->c1min = c1min = c1;
  173561. goto have_c1min;
  173562. }
  173563. }
  173564. have_c1min:
  173565. if (c1max > c1min)
  173566. for (c1 = c1max; c1 >= c1min; c1--)
  173567. for (c0 = c0min; c0 <= c0max; c0++) {
  173568. histp = & histogram[c0][c1][c2min];
  173569. for (c2 = c2min; c2 <= c2max; c2++)
  173570. if (*histp++ != 0) {
  173571. boxp->c1max = c1max = c1;
  173572. goto have_c1max;
  173573. }
  173574. }
  173575. have_c1max:
  173576. if (c2max > c2min)
  173577. for (c2 = c2min; c2 <= c2max; c2++)
  173578. for (c0 = c0min; c0 <= c0max; c0++) {
  173579. histp = & histogram[c0][c1min][c2];
  173580. for (c1 = c1min; c1 <= c1max; c1++, histp += HIST_C2_ELEMS)
  173581. if (*histp != 0) {
  173582. boxp->c2min = c2min = c2;
  173583. goto have_c2min;
  173584. }
  173585. }
  173586. have_c2min:
  173587. if (c2max > c2min)
  173588. for (c2 = c2max; c2 >= c2min; c2--)
  173589. for (c0 = c0min; c0 <= c0max; c0++) {
  173590. histp = & histogram[c0][c1min][c2];
  173591. for (c1 = c1min; c1 <= c1max; c1++, histp += HIST_C2_ELEMS)
  173592. if (*histp != 0) {
  173593. boxp->c2max = c2max = c2;
  173594. goto have_c2max;
  173595. }
  173596. }
  173597. have_c2max:
  173598. /* Update box volume.
  173599. * We use 2-norm rather than real volume here; this biases the method
  173600. * against making long narrow boxes, and it has the side benefit that
  173601. * a box is splittable iff norm > 0.
  173602. * Since the differences are expressed in histogram-cell units,
  173603. * we have to shift back to JSAMPLE units to get consistent distances;
  173604. * after which, we scale according to the selected distance scale factors.
  173605. */
  173606. dist0 = ((c0max - c0min) << C0_SHIFT) * C0_SCALE;
  173607. dist1 = ((c1max - c1min) << C1_SHIFT) * C1_SCALE;
  173608. dist2 = ((c2max - c2min) << C2_SHIFT) * C2_SCALE;
  173609. boxp->volume = dist0*dist0 + dist1*dist1 + dist2*dist2;
  173610. /* Now scan remaining volume of box and compute population */
  173611. ccount = 0;
  173612. for (c0 = c0min; c0 <= c0max; c0++)
  173613. for (c1 = c1min; c1 <= c1max; c1++) {
  173614. histp = & histogram[c0][c1][c2min];
  173615. for (c2 = c2min; c2 <= c2max; c2++, histp++)
  173616. if (*histp != 0) {
  173617. ccount++;
  173618. }
  173619. }
  173620. boxp->colorcount = ccount;
  173621. }
  173622. LOCAL(int)
  173623. median_cut (j_decompress_ptr cinfo, boxptr boxlist, int numboxes,
  173624. int desired_colors)
  173625. /* Repeatedly select and split the largest box until we have enough boxes */
  173626. {
  173627. int n,lb;
  173628. int c0,c1,c2,cmax;
  173629. register boxptr b1,b2;
  173630. while (numboxes < desired_colors) {
  173631. /* Select box to split.
  173632. * Current algorithm: by population for first half, then by volume.
  173633. */
  173634. if (numboxes*2 <= desired_colors) {
  173635. b1 = find_biggest_color_pop(boxlist, numboxes);
  173636. } else {
  173637. b1 = find_biggest_volume(boxlist, numboxes);
  173638. }
  173639. if (b1 == NULL) /* no splittable boxes left! */
  173640. break;
  173641. b2 = &boxlist[numboxes]; /* where new box will go */
  173642. /* Copy the color bounds to the new box. */
  173643. b2->c0max = b1->c0max; b2->c1max = b1->c1max; b2->c2max = b1->c2max;
  173644. b2->c0min = b1->c0min; b2->c1min = b1->c1min; b2->c2min = b1->c2min;
  173645. /* Choose which axis to split the box on.
  173646. * Current algorithm: longest scaled axis.
  173647. * See notes in update_box about scaling distances.
  173648. */
  173649. c0 = ((b1->c0max - b1->c0min) << C0_SHIFT) * C0_SCALE;
  173650. c1 = ((b1->c1max - b1->c1min) << C1_SHIFT) * C1_SCALE;
  173651. c2 = ((b1->c2max - b1->c2min) << C2_SHIFT) * C2_SCALE;
  173652. /* We want to break any ties in favor of green, then red, blue last.
  173653. * This code does the right thing for R,G,B or B,G,R color orders only.
  173654. */
  173655. #if RGB_RED == 0
  173656. cmax = c1; n = 1;
  173657. if (c0 > cmax) { cmax = c0; n = 0; }
  173658. if (c2 > cmax) { n = 2; }
  173659. #else
  173660. cmax = c1; n = 1;
  173661. if (c2 > cmax) { cmax = c2; n = 2; }
  173662. if (c0 > cmax) { n = 0; }
  173663. #endif
  173664. /* Choose split point along selected axis, and update box bounds.
  173665. * Current algorithm: split at halfway point.
  173666. * (Since the box has been shrunk to minimum volume,
  173667. * any split will produce two nonempty subboxes.)
  173668. * Note that lb value is max for lower box, so must be < old max.
  173669. */
  173670. switch (n) {
  173671. case 0:
  173672. lb = (b1->c0max + b1->c0min) / 2;
  173673. b1->c0max = lb;
  173674. b2->c0min = lb+1;
  173675. break;
  173676. case 1:
  173677. lb = (b1->c1max + b1->c1min) / 2;
  173678. b1->c1max = lb;
  173679. b2->c1min = lb+1;
  173680. break;
  173681. case 2:
  173682. lb = (b1->c2max + b1->c2min) / 2;
  173683. b1->c2max = lb;
  173684. b2->c2min = lb+1;
  173685. break;
  173686. }
  173687. /* Update stats for boxes */
  173688. update_box(cinfo, b1);
  173689. update_box(cinfo, b2);
  173690. numboxes++;
  173691. }
  173692. return numboxes;
  173693. }
  173694. LOCAL(void)
  173695. compute_color (j_decompress_ptr cinfo, boxptr boxp, int icolor)
  173696. /* Compute representative color for a box, put it in colormap[icolor] */
  173697. {
  173698. /* Current algorithm: mean weighted by pixels (not colors) */
  173699. /* Note it is important to get the rounding correct! */
  173700. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  173701. hist3d histogram = cquantize->histogram;
  173702. histptr histp;
  173703. int c0,c1,c2;
  173704. int c0min,c0max,c1min,c1max,c2min,c2max;
  173705. long count;
  173706. long total = 0;
  173707. long c0total = 0;
  173708. long c1total = 0;
  173709. long c2total = 0;
  173710. c0min = boxp->c0min; c0max = boxp->c0max;
  173711. c1min = boxp->c1min; c1max = boxp->c1max;
  173712. c2min = boxp->c2min; c2max = boxp->c2max;
  173713. for (c0 = c0min; c0 <= c0max; c0++)
  173714. for (c1 = c1min; c1 <= c1max; c1++) {
  173715. histp = & histogram[c0][c1][c2min];
  173716. for (c2 = c2min; c2 <= c2max; c2++) {
  173717. if ((count = *histp++) != 0) {
  173718. total += count;
  173719. c0total += ((c0 << C0_SHIFT) + ((1<<C0_SHIFT)>>1)) * count;
  173720. c1total += ((c1 << C1_SHIFT) + ((1<<C1_SHIFT)>>1)) * count;
  173721. c2total += ((c2 << C2_SHIFT) + ((1<<C2_SHIFT)>>1)) * count;
  173722. }
  173723. }
  173724. }
  173725. cinfo->colormap[0][icolor] = (JSAMPLE) ((c0total + (total>>1)) / total);
  173726. cinfo->colormap[1][icolor] = (JSAMPLE) ((c1total + (total>>1)) / total);
  173727. cinfo->colormap[2][icolor] = (JSAMPLE) ((c2total + (total>>1)) / total);
  173728. }
  173729. LOCAL(void)
  173730. select_colors (j_decompress_ptr cinfo, int desired_colors)
  173731. /* Master routine for color selection */
  173732. {
  173733. boxptr boxlist;
  173734. int numboxes;
  173735. int i;
  173736. /* Allocate workspace for box list */
  173737. boxlist = (boxptr) (*cinfo->mem->alloc_small)
  173738. ((j_common_ptr) cinfo, JPOOL_IMAGE, desired_colors * SIZEOF(box));
  173739. /* Initialize one box containing whole space */
  173740. numboxes = 1;
  173741. boxlist[0].c0min = 0;
  173742. boxlist[0].c0max = MAXJSAMPLE >> C0_SHIFT;
  173743. boxlist[0].c1min = 0;
  173744. boxlist[0].c1max = MAXJSAMPLE >> C1_SHIFT;
  173745. boxlist[0].c2min = 0;
  173746. boxlist[0].c2max = MAXJSAMPLE >> C2_SHIFT;
  173747. /* Shrink it to actually-used volume and set its statistics */
  173748. update_box(cinfo, & boxlist[0]);
  173749. /* Perform median-cut to produce final box list */
  173750. numboxes = median_cut(cinfo, boxlist, numboxes, desired_colors);
  173751. /* Compute the representative color for each box, fill colormap */
  173752. for (i = 0; i < numboxes; i++)
  173753. compute_color(cinfo, & boxlist[i], i);
  173754. cinfo->actual_number_of_colors = numboxes;
  173755. TRACEMS1(cinfo, 1, JTRC_QUANT_SELECTED, numboxes);
  173756. }
  173757. /*
  173758. * These routines are concerned with the time-critical task of mapping input
  173759. * colors to the nearest color in the selected colormap.
  173760. *
  173761. * We re-use the histogram space as an "inverse color map", essentially a
  173762. * cache for the results of nearest-color searches. All colors within a
  173763. * histogram cell will be mapped to the same colormap entry, namely the one
  173764. * closest to the cell's center. This may not be quite the closest entry to
  173765. * the actual input color, but it's almost as good. A zero in the cache
  173766. * indicates we haven't found the nearest color for that cell yet; the array
  173767. * is cleared to zeroes before starting the mapping pass. When we find the
  173768. * nearest color for a cell, its colormap index plus one is recorded in the
  173769. * cache for future use. The pass2 scanning routines call fill_inverse_cmap
  173770. * when they need to use an unfilled entry in the cache.
  173771. *
  173772. * Our method of efficiently finding nearest colors is based on the "locally
  173773. * sorted search" idea described by Heckbert and on the incremental distance
  173774. * calculation described by Spencer W. Thomas in chapter III.1 of Graphics
  173775. * Gems II (James Arvo, ed. Academic Press, 1991). Thomas points out that
  173776. * the distances from a given colormap entry to each cell of the histogram can
  173777. * be computed quickly using an incremental method: the differences between
  173778. * distances to adjacent cells themselves differ by a constant. This allows a
  173779. * fairly fast implementation of the "brute force" approach of computing the
  173780. * distance from every colormap entry to every histogram cell. Unfortunately,
  173781. * it needs a work array to hold the best-distance-so-far for each histogram
  173782. * cell (because the inner loop has to be over cells, not colormap entries).
  173783. * The work array elements have to be INT32s, so the work array would need
  173784. * 256Kb at our recommended precision. This is not feasible in DOS machines.
  173785. *
  173786. * To get around these problems, we apply Thomas' method to compute the
  173787. * nearest colors for only the cells within a small subbox of the histogram.
  173788. * The work array need be only as big as the subbox, so the memory usage
  173789. * problem is solved. Furthermore, we need not fill subboxes that are never
  173790. * referenced in pass2; many images use only part of the color gamut, so a
  173791. * fair amount of work is saved. An additional advantage of this
  173792. * approach is that we can apply Heckbert's locality criterion to quickly
  173793. * eliminate colormap entries that are far away from the subbox; typically
  173794. * three-fourths of the colormap entries are rejected by Heckbert's criterion,
  173795. * and we need not compute their distances to individual cells in the subbox.
  173796. * The speed of this approach is heavily influenced by the subbox size: too
  173797. * small means too much overhead, too big loses because Heckbert's criterion
  173798. * can't eliminate as many colormap entries. Empirically the best subbox
  173799. * size seems to be about 1/512th of the histogram (1/8th in each direction).
  173800. *
  173801. * Thomas' article also describes a refined method which is asymptotically
  173802. * faster than the brute-force method, but it is also far more complex and
  173803. * cannot efficiently be applied to small subboxes. It is therefore not
  173804. * useful for programs intended to be portable to DOS machines. On machines
  173805. * with plenty of memory, filling the whole histogram in one shot with Thomas'
  173806. * refined method might be faster than the present code --- but then again,
  173807. * it might not be any faster, and it's certainly more complicated.
  173808. */
  173809. /* log2(histogram cells in update box) for each axis; this can be adjusted */
  173810. #define BOX_C0_LOG (HIST_C0_BITS-3)
  173811. #define BOX_C1_LOG (HIST_C1_BITS-3)
  173812. #define BOX_C2_LOG (HIST_C2_BITS-3)
  173813. #define BOX_C0_ELEMS (1<<BOX_C0_LOG) /* # of hist cells in update box */
  173814. #define BOX_C1_ELEMS (1<<BOX_C1_LOG)
  173815. #define BOX_C2_ELEMS (1<<BOX_C2_LOG)
  173816. #define BOX_C0_SHIFT (C0_SHIFT + BOX_C0_LOG)
  173817. #define BOX_C1_SHIFT (C1_SHIFT + BOX_C1_LOG)
  173818. #define BOX_C2_SHIFT (C2_SHIFT + BOX_C2_LOG)
  173819. /*
  173820. * The next three routines implement inverse colormap filling. They could
  173821. * all be folded into one big routine, but splitting them up this way saves
  173822. * some stack space (the mindist[] and bestdist[] arrays need not coexist)
  173823. * and may allow some compilers to produce better code by registerizing more
  173824. * inner-loop variables.
  173825. */
  173826. LOCAL(int)
  173827. find_nearby_colors (j_decompress_ptr cinfo, int minc0, int minc1, int minc2,
  173828. JSAMPLE colorlist[])
  173829. /* Locate the colormap entries close enough to an update box to be candidates
  173830. * for the nearest entry to some cell(s) in the update box. The update box
  173831. * is specified by the center coordinates of its first cell. The number of
  173832. * candidate colormap entries is returned, and their colormap indexes are
  173833. * placed in colorlist[].
  173834. * This routine uses Heckbert's "locally sorted search" criterion to select
  173835. * the colors that need further consideration.
  173836. */
  173837. {
  173838. int numcolors = cinfo->actual_number_of_colors;
  173839. int maxc0, maxc1, maxc2;
  173840. int centerc0, centerc1, centerc2;
  173841. int i, x, ncolors;
  173842. INT32 minmaxdist, min_dist, max_dist, tdist;
  173843. INT32 mindist[MAXNUMCOLORS]; /* min distance to colormap entry i */
  173844. /* Compute true coordinates of update box's upper corner and center.
  173845. * Actually we compute the coordinates of the center of the upper-corner
  173846. * histogram cell, which are the upper bounds of the volume we care about.
  173847. * Note that since ">>" rounds down, the "center" values may be closer to
  173848. * min than to max; hence comparisons to them must be "<=", not "<".
  173849. */
  173850. maxc0 = minc0 + ((1 << BOX_C0_SHIFT) - (1 << C0_SHIFT));
  173851. centerc0 = (minc0 + maxc0) >> 1;
  173852. maxc1 = minc1 + ((1 << BOX_C1_SHIFT) - (1 << C1_SHIFT));
  173853. centerc1 = (minc1 + maxc1) >> 1;
  173854. maxc2 = minc2 + ((1 << BOX_C2_SHIFT) - (1 << C2_SHIFT));
  173855. centerc2 = (minc2 + maxc2) >> 1;
  173856. /* For each color in colormap, find:
  173857. * 1. its minimum squared-distance to any point in the update box
  173858. * (zero if color is within update box);
  173859. * 2. its maximum squared-distance to any point in the update box.
  173860. * Both of these can be found by considering only the corners of the box.
  173861. * We save the minimum distance for each color in mindist[];
  173862. * only the smallest maximum distance is of interest.
  173863. */
  173864. minmaxdist = 0x7FFFFFFFL;
  173865. for (i = 0; i < numcolors; i++) {
  173866. /* We compute the squared-c0-distance term, then add in the other two. */
  173867. x = GETJSAMPLE(cinfo->colormap[0][i]);
  173868. if (x < minc0) {
  173869. tdist = (x - minc0) * C0_SCALE;
  173870. min_dist = tdist*tdist;
  173871. tdist = (x - maxc0) * C0_SCALE;
  173872. max_dist = tdist*tdist;
  173873. } else if (x > maxc0) {
  173874. tdist = (x - maxc0) * C0_SCALE;
  173875. min_dist = tdist*tdist;
  173876. tdist = (x - minc0) * C0_SCALE;
  173877. max_dist = tdist*tdist;
  173878. } else {
  173879. /* within cell range so no contribution to min_dist */
  173880. min_dist = 0;
  173881. if (x <= centerc0) {
  173882. tdist = (x - maxc0) * C0_SCALE;
  173883. max_dist = tdist*tdist;
  173884. } else {
  173885. tdist = (x - minc0) * C0_SCALE;
  173886. max_dist = tdist*tdist;
  173887. }
  173888. }
  173889. x = GETJSAMPLE(cinfo->colormap[1][i]);
  173890. if (x < minc1) {
  173891. tdist = (x - minc1) * C1_SCALE;
  173892. min_dist += tdist*tdist;
  173893. tdist = (x - maxc1) * C1_SCALE;
  173894. max_dist += tdist*tdist;
  173895. } else if (x > maxc1) {
  173896. tdist = (x - maxc1) * C1_SCALE;
  173897. min_dist += tdist*tdist;
  173898. tdist = (x - minc1) * C1_SCALE;
  173899. max_dist += tdist*tdist;
  173900. } else {
  173901. /* within cell range so no contribution to min_dist */
  173902. if (x <= centerc1) {
  173903. tdist = (x - maxc1) * C1_SCALE;
  173904. max_dist += tdist*tdist;
  173905. } else {
  173906. tdist = (x - minc1) * C1_SCALE;
  173907. max_dist += tdist*tdist;
  173908. }
  173909. }
  173910. x = GETJSAMPLE(cinfo->colormap[2][i]);
  173911. if (x < minc2) {
  173912. tdist = (x - minc2) * C2_SCALE;
  173913. min_dist += tdist*tdist;
  173914. tdist = (x - maxc2) * C2_SCALE;
  173915. max_dist += tdist*tdist;
  173916. } else if (x > maxc2) {
  173917. tdist = (x - maxc2) * C2_SCALE;
  173918. min_dist += tdist*tdist;
  173919. tdist = (x - minc2) * C2_SCALE;
  173920. max_dist += tdist*tdist;
  173921. } else {
  173922. /* within cell range so no contribution to min_dist */
  173923. if (x <= centerc2) {
  173924. tdist = (x - maxc2) * C2_SCALE;
  173925. max_dist += tdist*tdist;
  173926. } else {
  173927. tdist = (x - minc2) * C2_SCALE;
  173928. max_dist += tdist*tdist;
  173929. }
  173930. }
  173931. mindist[i] = min_dist; /* save away the results */
  173932. if (max_dist < minmaxdist)
  173933. minmaxdist = max_dist;
  173934. }
  173935. /* Now we know that no cell in the update box is more than minmaxdist
  173936. * away from some colormap entry. Therefore, only colors that are
  173937. * within minmaxdist of some part of the box need be considered.
  173938. */
  173939. ncolors = 0;
  173940. for (i = 0; i < numcolors; i++) {
  173941. if (mindist[i] <= minmaxdist)
  173942. colorlist[ncolors++] = (JSAMPLE) i;
  173943. }
  173944. return ncolors;
  173945. }
  173946. LOCAL(void)
  173947. find_best_colors (j_decompress_ptr cinfo, int minc0, int minc1, int minc2,
  173948. int numcolors, JSAMPLE colorlist[], JSAMPLE bestcolor[])
  173949. /* Find the closest colormap entry for each cell in the update box,
  173950. * given the list of candidate colors prepared by find_nearby_colors.
  173951. * Return the indexes of the closest entries in the bestcolor[] array.
  173952. * This routine uses Thomas' incremental distance calculation method to
  173953. * find the distance from a colormap entry to successive cells in the box.
  173954. */
  173955. {
  173956. int ic0, ic1, ic2;
  173957. int i, icolor;
  173958. register INT32 * bptr; /* pointer into bestdist[] array */
  173959. JSAMPLE * cptr; /* pointer into bestcolor[] array */
  173960. INT32 dist0, dist1; /* initial distance values */
  173961. register INT32 dist2; /* current distance in inner loop */
  173962. INT32 xx0, xx1; /* distance increments */
  173963. register INT32 xx2;
  173964. INT32 inc0, inc1, inc2; /* initial values for increments */
  173965. /* This array holds the distance to the nearest-so-far color for each cell */
  173966. INT32 bestdist[BOX_C0_ELEMS * BOX_C1_ELEMS * BOX_C2_ELEMS];
  173967. /* Initialize best-distance for each cell of the update box */
  173968. bptr = bestdist;
  173969. for (i = BOX_C0_ELEMS*BOX_C1_ELEMS*BOX_C2_ELEMS-1; i >= 0; i--)
  173970. *bptr++ = 0x7FFFFFFFL;
  173971. /* For each color selected by find_nearby_colors,
  173972. * compute its distance to the center of each cell in the box.
  173973. * If that's less than best-so-far, update best distance and color number.
  173974. */
  173975. /* Nominal steps between cell centers ("x" in Thomas article) */
  173976. #define STEP_C0 ((1 << C0_SHIFT) * C0_SCALE)
  173977. #define STEP_C1 ((1 << C1_SHIFT) * C1_SCALE)
  173978. #define STEP_C2 ((1 << C2_SHIFT) * C2_SCALE)
  173979. for (i = 0; i < numcolors; i++) {
  173980. icolor = GETJSAMPLE(colorlist[i]);
  173981. /* Compute (square of) distance from minc0/c1/c2 to this color */
  173982. inc0 = (minc0 - GETJSAMPLE(cinfo->colormap[0][icolor])) * C0_SCALE;
  173983. dist0 = inc0*inc0;
  173984. inc1 = (minc1 - GETJSAMPLE(cinfo->colormap[1][icolor])) * C1_SCALE;
  173985. dist0 += inc1*inc1;
  173986. inc2 = (minc2 - GETJSAMPLE(cinfo->colormap[2][icolor])) * C2_SCALE;
  173987. dist0 += inc2*inc2;
  173988. /* Form the initial difference increments */
  173989. inc0 = inc0 * (2 * STEP_C0) + STEP_C0 * STEP_C0;
  173990. inc1 = inc1 * (2 * STEP_C1) + STEP_C1 * STEP_C1;
  173991. inc2 = inc2 * (2 * STEP_C2) + STEP_C2 * STEP_C2;
  173992. /* Now loop over all cells in box, updating distance per Thomas method */
  173993. bptr = bestdist;
  173994. cptr = bestcolor;
  173995. xx0 = inc0;
  173996. for (ic0 = BOX_C0_ELEMS-1; ic0 >= 0; ic0--) {
  173997. dist1 = dist0;
  173998. xx1 = inc1;
  173999. for (ic1 = BOX_C1_ELEMS-1; ic1 >= 0; ic1--) {
  174000. dist2 = dist1;
  174001. xx2 = inc2;
  174002. for (ic2 = BOX_C2_ELEMS-1; ic2 >= 0; ic2--) {
  174003. if (dist2 < *bptr) {
  174004. *bptr = dist2;
  174005. *cptr = (JSAMPLE) icolor;
  174006. }
  174007. dist2 += xx2;
  174008. xx2 += 2 * STEP_C2 * STEP_C2;
  174009. bptr++;
  174010. cptr++;
  174011. }
  174012. dist1 += xx1;
  174013. xx1 += 2 * STEP_C1 * STEP_C1;
  174014. }
  174015. dist0 += xx0;
  174016. xx0 += 2 * STEP_C0 * STEP_C0;
  174017. }
  174018. }
  174019. }
  174020. LOCAL(void)
  174021. fill_inverse_cmap (j_decompress_ptr cinfo, int c0, int c1, int c2)
  174022. /* Fill the inverse-colormap entries in the update box that contains */
  174023. /* histogram cell c0/c1/c2. (Only that one cell MUST be filled, but */
  174024. /* we can fill as many others as we wish.) */
  174025. {
  174026. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  174027. hist3d histogram = cquantize->histogram;
  174028. int minc0, minc1, minc2; /* lower left corner of update box */
  174029. int ic0, ic1, ic2;
  174030. register JSAMPLE * cptr; /* pointer into bestcolor[] array */
  174031. register histptr cachep; /* pointer into main cache array */
  174032. /* This array lists the candidate colormap indexes. */
  174033. JSAMPLE colorlist[MAXNUMCOLORS];
  174034. int numcolors; /* number of candidate colors */
  174035. /* This array holds the actually closest colormap index for each cell. */
  174036. JSAMPLE bestcolor[BOX_C0_ELEMS * BOX_C1_ELEMS * BOX_C2_ELEMS];
  174037. /* Convert cell coordinates to update box ID */
  174038. c0 >>= BOX_C0_LOG;
  174039. c1 >>= BOX_C1_LOG;
  174040. c2 >>= BOX_C2_LOG;
  174041. /* Compute true coordinates of update box's origin corner.
  174042. * Actually we compute the coordinates of the center of the corner
  174043. * histogram cell, which are the lower bounds of the volume we care about.
  174044. */
  174045. minc0 = (c0 << BOX_C0_SHIFT) + ((1 << C0_SHIFT) >> 1);
  174046. minc1 = (c1 << BOX_C1_SHIFT) + ((1 << C1_SHIFT) >> 1);
  174047. minc2 = (c2 << BOX_C2_SHIFT) + ((1 << C2_SHIFT) >> 1);
  174048. /* Determine which colormap entries are close enough to be candidates
  174049. * for the nearest entry to some cell in the update box.
  174050. */
  174051. numcolors = find_nearby_colors(cinfo, minc0, minc1, minc2, colorlist);
  174052. /* Determine the actually nearest colors. */
  174053. find_best_colors(cinfo, minc0, minc1, minc2, numcolors, colorlist,
  174054. bestcolor);
  174055. /* Save the best color numbers (plus 1) in the main cache array */
  174056. c0 <<= BOX_C0_LOG; /* convert ID back to base cell indexes */
  174057. c1 <<= BOX_C1_LOG;
  174058. c2 <<= BOX_C2_LOG;
  174059. cptr = bestcolor;
  174060. for (ic0 = 0; ic0 < BOX_C0_ELEMS; ic0++) {
  174061. for (ic1 = 0; ic1 < BOX_C1_ELEMS; ic1++) {
  174062. cachep = & histogram[c0+ic0][c1+ic1][c2];
  174063. for (ic2 = 0; ic2 < BOX_C2_ELEMS; ic2++) {
  174064. *cachep++ = (histcell) (GETJSAMPLE(*cptr++) + 1);
  174065. }
  174066. }
  174067. }
  174068. }
  174069. /*
  174070. * Map some rows of pixels to the output colormapped representation.
  174071. */
  174072. METHODDEF(void)
  174073. pass2_no_dither (j_decompress_ptr cinfo,
  174074. JSAMPARRAY input_buf, JSAMPARRAY output_buf, int num_rows)
  174075. /* This version performs no dithering */
  174076. {
  174077. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  174078. hist3d histogram = cquantize->histogram;
  174079. register JSAMPROW inptr, outptr;
  174080. register histptr cachep;
  174081. register int c0, c1, c2;
  174082. int row;
  174083. JDIMENSION col;
  174084. JDIMENSION width = cinfo->output_width;
  174085. for (row = 0; row < num_rows; row++) {
  174086. inptr = input_buf[row];
  174087. outptr = output_buf[row];
  174088. for (col = width; col > 0; col--) {
  174089. /* get pixel value and index into the cache */
  174090. c0 = GETJSAMPLE(*inptr++) >> C0_SHIFT;
  174091. c1 = GETJSAMPLE(*inptr++) >> C1_SHIFT;
  174092. c2 = GETJSAMPLE(*inptr++) >> C2_SHIFT;
  174093. cachep = & histogram[c0][c1][c2];
  174094. /* If we have not seen this color before, find nearest colormap entry */
  174095. /* and update the cache */
  174096. if (*cachep == 0)
  174097. fill_inverse_cmap(cinfo, c0,c1,c2);
  174098. /* Now emit the colormap index for this cell */
  174099. *outptr++ = (JSAMPLE) (*cachep - 1);
  174100. }
  174101. }
  174102. }
  174103. METHODDEF(void)
  174104. pass2_fs_dither (j_decompress_ptr cinfo,
  174105. JSAMPARRAY input_buf, JSAMPARRAY output_buf, int num_rows)
  174106. /* This version performs Floyd-Steinberg dithering */
  174107. {
  174108. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  174109. hist3d histogram = cquantize->histogram;
  174110. register LOCFSERROR cur0, cur1, cur2; /* current error or pixel value */
  174111. LOCFSERROR belowerr0, belowerr1, belowerr2; /* error for pixel below cur */
  174112. LOCFSERROR bpreverr0, bpreverr1, bpreverr2; /* error for below/prev col */
  174113. register FSERRPTR errorptr; /* => fserrors[] at column before current */
  174114. JSAMPROW inptr; /* => current input pixel */
  174115. JSAMPROW outptr; /* => current output pixel */
  174116. histptr cachep;
  174117. int dir; /* +1 or -1 depending on direction */
  174118. int dir3; /* 3*dir, for advancing inptr & errorptr */
  174119. int row;
  174120. JDIMENSION col;
  174121. JDIMENSION width = cinfo->output_width;
  174122. JSAMPLE *range_limit = cinfo->sample_range_limit;
  174123. int *error_limit = cquantize->error_limiter;
  174124. JSAMPROW colormap0 = cinfo->colormap[0];
  174125. JSAMPROW colormap1 = cinfo->colormap[1];
  174126. JSAMPROW colormap2 = cinfo->colormap[2];
  174127. SHIFT_TEMPS
  174128. for (row = 0; row < num_rows; row++) {
  174129. inptr = input_buf[row];
  174130. outptr = output_buf[row];
  174131. if (cquantize->on_odd_row) {
  174132. /* work right to left in this row */
  174133. inptr += (width-1) * 3; /* so point to rightmost pixel */
  174134. outptr += width-1;
  174135. dir = -1;
  174136. dir3 = -3;
  174137. errorptr = cquantize->fserrors + (width+1)*3; /* => entry after last column */
  174138. cquantize->on_odd_row = FALSE; /* flip for next time */
  174139. } else {
  174140. /* work left to right in this row */
  174141. dir = 1;
  174142. dir3 = 3;
  174143. errorptr = cquantize->fserrors; /* => entry before first real column */
  174144. cquantize->on_odd_row = TRUE; /* flip for next time */
  174145. }
  174146. /* Preset error values: no error propagated to first pixel from left */
  174147. cur0 = cur1 = cur2 = 0;
  174148. /* and no error propagated to row below yet */
  174149. belowerr0 = belowerr1 = belowerr2 = 0;
  174150. bpreverr0 = bpreverr1 = bpreverr2 = 0;
  174151. for (col = width; col > 0; col--) {
  174152. /* curN holds the error propagated from the previous pixel on the
  174153. * current line. Add the error propagated from the previous line
  174154. * to form the complete error correction term for this pixel, and
  174155. * round the error term (which is expressed * 16) to an integer.
  174156. * RIGHT_SHIFT rounds towards minus infinity, so adding 8 is correct
  174157. * for either sign of the error value.
  174158. * Note: errorptr points to *previous* column's array entry.
  174159. */
  174160. cur0 = RIGHT_SHIFT(cur0 + errorptr[dir3+0] + 8, 4);
  174161. cur1 = RIGHT_SHIFT(cur1 + errorptr[dir3+1] + 8, 4);
  174162. cur2 = RIGHT_SHIFT(cur2 + errorptr[dir3+2] + 8, 4);
  174163. /* Limit the error using transfer function set by init_error_limit.
  174164. * See comments with init_error_limit for rationale.
  174165. */
  174166. cur0 = error_limit[cur0];
  174167. cur1 = error_limit[cur1];
  174168. cur2 = error_limit[cur2];
  174169. /* Form pixel value + error, and range-limit to 0..MAXJSAMPLE.
  174170. * The maximum error is +- MAXJSAMPLE (or less with error limiting);
  174171. * this sets the required size of the range_limit array.
  174172. */
  174173. cur0 += GETJSAMPLE(inptr[0]);
  174174. cur1 += GETJSAMPLE(inptr[1]);
  174175. cur2 += GETJSAMPLE(inptr[2]);
  174176. cur0 = GETJSAMPLE(range_limit[cur0]);
  174177. cur1 = GETJSAMPLE(range_limit[cur1]);
  174178. cur2 = GETJSAMPLE(range_limit[cur2]);
  174179. /* Index into the cache with adjusted pixel value */
  174180. cachep = & histogram[cur0>>C0_SHIFT][cur1>>C1_SHIFT][cur2>>C2_SHIFT];
  174181. /* If we have not seen this color before, find nearest colormap */
  174182. /* entry and update the cache */
  174183. if (*cachep == 0)
  174184. fill_inverse_cmap(cinfo, cur0>>C0_SHIFT,cur1>>C1_SHIFT,cur2>>C2_SHIFT);
  174185. /* Now emit the colormap index for this cell */
  174186. { register int pixcode = *cachep - 1;
  174187. *outptr = (JSAMPLE) pixcode;
  174188. /* Compute representation error for this pixel */
  174189. cur0 -= GETJSAMPLE(colormap0[pixcode]);
  174190. cur1 -= GETJSAMPLE(colormap1[pixcode]);
  174191. cur2 -= GETJSAMPLE(colormap2[pixcode]);
  174192. }
  174193. /* Compute error fractions to be propagated to adjacent pixels.
  174194. * Add these into the running sums, and simultaneously shift the
  174195. * next-line error sums left by 1 column.
  174196. */
  174197. { register LOCFSERROR bnexterr, delta;
  174198. bnexterr = cur0; /* Process component 0 */
  174199. delta = cur0 * 2;
  174200. cur0 += delta; /* form error * 3 */
  174201. errorptr[0] = (FSERROR) (bpreverr0 + cur0);
  174202. cur0 += delta; /* form error * 5 */
  174203. bpreverr0 = belowerr0 + cur0;
  174204. belowerr0 = bnexterr;
  174205. cur0 += delta; /* form error * 7 */
  174206. bnexterr = cur1; /* Process component 1 */
  174207. delta = cur1 * 2;
  174208. cur1 += delta; /* form error * 3 */
  174209. errorptr[1] = (FSERROR) (bpreverr1 + cur1);
  174210. cur1 += delta; /* form error * 5 */
  174211. bpreverr1 = belowerr1 + cur1;
  174212. belowerr1 = bnexterr;
  174213. cur1 += delta; /* form error * 7 */
  174214. bnexterr = cur2; /* Process component 2 */
  174215. delta = cur2 * 2;
  174216. cur2 += delta; /* form error * 3 */
  174217. errorptr[2] = (FSERROR) (bpreverr2 + cur2);
  174218. cur2 += delta; /* form error * 5 */
  174219. bpreverr2 = belowerr2 + cur2;
  174220. belowerr2 = bnexterr;
  174221. cur2 += delta; /* form error * 7 */
  174222. }
  174223. /* At this point curN contains the 7/16 error value to be propagated
  174224. * to the next pixel on the current line, and all the errors for the
  174225. * next line have been shifted over. We are therefore ready to move on.
  174226. */
  174227. inptr += dir3; /* Advance pixel pointers to next column */
  174228. outptr += dir;
  174229. errorptr += dir3; /* advance errorptr to current column */
  174230. }
  174231. /* Post-loop cleanup: we must unload the final error values into the
  174232. * final fserrors[] entry. Note we need not unload belowerrN because
  174233. * it is for the dummy column before or after the actual array.
  174234. */
  174235. errorptr[0] = (FSERROR) bpreverr0; /* unload prev errs into array */
  174236. errorptr[1] = (FSERROR) bpreverr1;
  174237. errorptr[2] = (FSERROR) bpreverr2;
  174238. }
  174239. }
  174240. /*
  174241. * Initialize the error-limiting transfer function (lookup table).
  174242. * The raw F-S error computation can potentially compute error values of up to
  174243. * +- MAXJSAMPLE. But we want the maximum correction applied to a pixel to be
  174244. * much less, otherwise obviously wrong pixels will be created. (Typical
  174245. * effects include weird fringes at color-area boundaries, isolated bright
  174246. * pixels in a dark area, etc.) The standard advice for avoiding this problem
  174247. * is to ensure that the "corners" of the color cube are allocated as output
  174248. * colors; then repeated errors in the same direction cannot cause cascading
  174249. * error buildup. However, that only prevents the error from getting
  174250. * completely out of hand; Aaron Giles reports that error limiting improves
  174251. * the results even with corner colors allocated.
  174252. * A simple clamping of the error values to about +- MAXJSAMPLE/8 works pretty
  174253. * well, but the smoother transfer function used below is even better. Thanks
  174254. * to Aaron Giles for this idea.
  174255. */
  174256. LOCAL(void)
  174257. init_error_limit (j_decompress_ptr cinfo)
  174258. /* Allocate and fill in the error_limiter table */
  174259. {
  174260. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  174261. int * table;
  174262. int in, out;
  174263. table = (int *) (*cinfo->mem->alloc_small)
  174264. ((j_common_ptr) cinfo, JPOOL_IMAGE, (MAXJSAMPLE*2+1) * SIZEOF(int));
  174265. table += MAXJSAMPLE; /* so can index -MAXJSAMPLE .. +MAXJSAMPLE */
  174266. cquantize->error_limiter = table;
  174267. #define STEPSIZE ((MAXJSAMPLE+1)/16)
  174268. /* Map errors 1:1 up to +- MAXJSAMPLE/16 */
  174269. out = 0;
  174270. for (in = 0; in < STEPSIZE; in++, out++) {
  174271. table[in] = out; table[-in] = -out;
  174272. }
  174273. /* Map errors 1:2 up to +- 3*MAXJSAMPLE/16 */
  174274. for (; in < STEPSIZE*3; in++, out += (in&1) ? 0 : 1) {
  174275. table[in] = out; table[-in] = -out;
  174276. }
  174277. /* Clamp the rest to final out value (which is (MAXJSAMPLE+1)/8) */
  174278. for (; in <= MAXJSAMPLE; in++) {
  174279. table[in] = out; table[-in] = -out;
  174280. }
  174281. #undef STEPSIZE
  174282. }
  174283. /*
  174284. * Finish up at the end of each pass.
  174285. */
  174286. METHODDEF(void)
  174287. finish_pass1 (j_decompress_ptr cinfo)
  174288. {
  174289. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  174290. /* Select the representative colors and fill in cinfo->colormap */
  174291. cinfo->colormap = cquantize->sv_colormap;
  174292. select_colors(cinfo, cquantize->desired);
  174293. /* Force next pass to zero the color index table */
  174294. cquantize->needs_zeroed = TRUE;
  174295. }
  174296. METHODDEF(void)
  174297. finish_pass2 (j_decompress_ptr cinfo)
  174298. {
  174299. /* no work */
  174300. }
  174301. /*
  174302. * Initialize for each processing pass.
  174303. */
  174304. METHODDEF(void)
  174305. start_pass_2_quant (j_decompress_ptr cinfo, boolean is_pre_scan)
  174306. {
  174307. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  174308. hist3d histogram = cquantize->histogram;
  174309. int i;
  174310. /* Only F-S dithering or no dithering is supported. */
  174311. /* If user asks for ordered dither, give him F-S. */
  174312. if (cinfo->dither_mode != JDITHER_NONE)
  174313. cinfo->dither_mode = JDITHER_FS;
  174314. if (is_pre_scan) {
  174315. /* Set up method pointers */
  174316. cquantize->pub.color_quantize = prescan_quantize;
  174317. cquantize->pub.finish_pass = finish_pass1;
  174318. cquantize->needs_zeroed = TRUE; /* Always zero histogram */
  174319. } else {
  174320. /* Set up method pointers */
  174321. if (cinfo->dither_mode == JDITHER_FS)
  174322. cquantize->pub.color_quantize = pass2_fs_dither;
  174323. else
  174324. cquantize->pub.color_quantize = pass2_no_dither;
  174325. cquantize->pub.finish_pass = finish_pass2;
  174326. /* Make sure color count is acceptable */
  174327. i = cinfo->actual_number_of_colors;
  174328. if (i < 1)
  174329. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, 1);
  174330. if (i > MAXNUMCOLORS)
  174331. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXNUMCOLORS);
  174332. if (cinfo->dither_mode == JDITHER_FS) {
  174333. size_t arraysize = (size_t) ((cinfo->output_width + 2) *
  174334. (3 * SIZEOF(FSERROR)));
  174335. /* Allocate Floyd-Steinberg workspace if we didn't already. */
  174336. if (cquantize->fserrors == NULL)
  174337. cquantize->fserrors = (FSERRPTR) (*cinfo->mem->alloc_large)
  174338. ((j_common_ptr) cinfo, JPOOL_IMAGE, arraysize);
  174339. /* Initialize the propagated errors to zero. */
  174340. jzero_far((void FAR *) cquantize->fserrors, arraysize);
  174341. /* Make the error-limit table if we didn't already. */
  174342. if (cquantize->error_limiter == NULL)
  174343. init_error_limit(cinfo);
  174344. cquantize->on_odd_row = FALSE;
  174345. }
  174346. }
  174347. /* Zero the histogram or inverse color map, if necessary */
  174348. if (cquantize->needs_zeroed) {
  174349. for (i = 0; i < HIST_C0_ELEMS; i++) {
  174350. jzero_far((void FAR *) histogram[i],
  174351. HIST_C1_ELEMS*HIST_C2_ELEMS * SIZEOF(histcell));
  174352. }
  174353. cquantize->needs_zeroed = FALSE;
  174354. }
  174355. }
  174356. /*
  174357. * Switch to a new external colormap between output passes.
  174358. */
  174359. METHODDEF(void)
  174360. new_color_map_2_quant (j_decompress_ptr cinfo)
  174361. {
  174362. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  174363. /* Reset the inverse color map */
  174364. cquantize->needs_zeroed = TRUE;
  174365. }
  174366. /*
  174367. * Module initialization routine for 2-pass color quantization.
  174368. */
  174369. GLOBAL(void)
  174370. jinit_2pass_quantizer (j_decompress_ptr cinfo)
  174371. {
  174372. my_cquantize_ptr2 cquantize;
  174373. int i;
  174374. cquantize = (my_cquantize_ptr2)
  174375. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  174376. SIZEOF(my_cquantizer2));
  174377. cinfo->cquantize = (struct jpeg_color_quantizer *) cquantize;
  174378. cquantize->pub.start_pass = start_pass_2_quant;
  174379. cquantize->pub.new_color_map = new_color_map_2_quant;
  174380. cquantize->fserrors = NULL; /* flag optional arrays not allocated */
  174381. cquantize->error_limiter = NULL;
  174382. /* Make sure jdmaster didn't give me a case I can't handle */
  174383. if (cinfo->out_color_components != 3)
  174384. ERREXIT(cinfo, JERR_NOTIMPL);
  174385. /* Allocate the histogram/inverse colormap storage */
  174386. cquantize->histogram = (hist3d) (*cinfo->mem->alloc_small)
  174387. ((j_common_ptr) cinfo, JPOOL_IMAGE, HIST_C0_ELEMS * SIZEOF(hist2d));
  174388. for (i = 0; i < HIST_C0_ELEMS; i++) {
  174389. cquantize->histogram[i] = (hist2d) (*cinfo->mem->alloc_large)
  174390. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  174391. HIST_C1_ELEMS*HIST_C2_ELEMS * SIZEOF(histcell));
  174392. }
  174393. cquantize->needs_zeroed = TRUE; /* histogram is garbage now */
  174394. /* Allocate storage for the completed colormap, if required.
  174395. * We do this now since it is FAR storage and may affect
  174396. * the memory manager's space calculations.
  174397. */
  174398. if (cinfo->enable_2pass_quant) {
  174399. /* Make sure color count is acceptable */
  174400. int desired = cinfo->desired_number_of_colors;
  174401. /* Lower bound on # of colors ... somewhat arbitrary as long as > 0 */
  174402. if (desired < 8)
  174403. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, 8);
  174404. /* Make sure colormap indexes can be represented by JSAMPLEs */
  174405. if (desired > MAXNUMCOLORS)
  174406. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXNUMCOLORS);
  174407. cquantize->sv_colormap = (*cinfo->mem->alloc_sarray)
  174408. ((j_common_ptr) cinfo,JPOOL_IMAGE, (JDIMENSION) desired, (JDIMENSION) 3);
  174409. cquantize->desired = desired;
  174410. } else
  174411. cquantize->sv_colormap = NULL;
  174412. /* Only F-S dithering or no dithering is supported. */
  174413. /* If user asks for ordered dither, give him F-S. */
  174414. if (cinfo->dither_mode != JDITHER_NONE)
  174415. cinfo->dither_mode = JDITHER_FS;
  174416. /* Allocate Floyd-Steinberg workspace if necessary.
  174417. * This isn't really needed until pass 2, but again it is FAR storage.
  174418. * Although we will cope with a later change in dither_mode,
  174419. * we do not promise to honor max_memory_to_use if dither_mode changes.
  174420. */
  174421. if (cinfo->dither_mode == JDITHER_FS) {
  174422. cquantize->fserrors = (FSERRPTR) (*cinfo->mem->alloc_large)
  174423. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  174424. (size_t) ((cinfo->output_width + 2) * (3 * SIZEOF(FSERROR))));
  174425. /* Might as well create the error-limiting table too. */
  174426. init_error_limit(cinfo);
  174427. }
  174428. }
  174429. #endif /* QUANT_2PASS_SUPPORTED */
  174430. /********* End of inlined file: jquant2.c *********/
  174431. /********* Start of inlined file: jutils.c *********/
  174432. #define JPEG_INTERNALS
  174433. /*
  174434. * jpeg_zigzag_order[i] is the zigzag-order position of the i'th element
  174435. * of a DCT block read in natural order (left to right, top to bottom).
  174436. */
  174437. #if 0 /* This table is not actually needed in v6a */
  174438. const int jpeg_zigzag_order[DCTSIZE2] = {
  174439. 0, 1, 5, 6, 14, 15, 27, 28,
  174440. 2, 4, 7, 13, 16, 26, 29, 42,
  174441. 3, 8, 12, 17, 25, 30, 41, 43,
  174442. 9, 11, 18, 24, 31, 40, 44, 53,
  174443. 10, 19, 23, 32, 39, 45, 52, 54,
  174444. 20, 22, 33, 38, 46, 51, 55, 60,
  174445. 21, 34, 37, 47, 50, 56, 59, 61,
  174446. 35, 36, 48, 49, 57, 58, 62, 63
  174447. };
  174448. #endif
  174449. /*
  174450. * jpeg_natural_order[i] is the natural-order position of the i'th element
  174451. * of zigzag order.
  174452. *
  174453. * When reading corrupted data, the Huffman decoders could attempt
  174454. * to reference an entry beyond the end of this array (if the decoded
  174455. * zero run length reaches past the end of the block). To prevent
  174456. * wild stores without adding an inner-loop test, we put some extra
  174457. * "63"s after the real entries. This will cause the extra coefficient
  174458. * to be stored in location 63 of the block, not somewhere random.
  174459. * The worst case would be a run-length of 15, which means we need 16
  174460. * fake entries.
  174461. */
  174462. const int jpeg_natural_order[DCTSIZE2+16] = {
  174463. 0, 1, 8, 16, 9, 2, 3, 10,
  174464. 17, 24, 32, 25, 18, 11, 4, 5,
  174465. 12, 19, 26, 33, 40, 48, 41, 34,
  174466. 27, 20, 13, 6, 7, 14, 21, 28,
  174467. 35, 42, 49, 56, 57, 50, 43, 36,
  174468. 29, 22, 15, 23, 30, 37, 44, 51,
  174469. 58, 59, 52, 45, 38, 31, 39, 46,
  174470. 53, 60, 61, 54, 47, 55, 62, 63,
  174471. 63, 63, 63, 63, 63, 63, 63, 63, /* extra entries for safety in decoder */
  174472. 63, 63, 63, 63, 63, 63, 63, 63
  174473. };
  174474. /*
  174475. * Arithmetic utilities
  174476. */
  174477. GLOBAL(long)
  174478. jdiv_round_up (long a, long b)
  174479. /* Compute a/b rounded up to next integer, ie, ceil(a/b) */
  174480. /* Assumes a >= 0, b > 0 */
  174481. {
  174482. return (a + b - 1L) / b;
  174483. }
  174484. GLOBAL(long)
  174485. jround_up (long a, long b)
  174486. /* Compute a rounded up to next multiple of b, ie, ceil(a/b)*b */
  174487. /* Assumes a >= 0, b > 0 */
  174488. {
  174489. a += b - 1L;
  174490. return a - (a % b);
  174491. }
  174492. /* On normal machines we can apply MEMCOPY() and MEMZERO() to sample arrays
  174493. * and coefficient-block arrays. This won't work on 80x86 because the arrays
  174494. * are FAR and we're assuming a small-pointer memory model. However, some
  174495. * DOS compilers provide far-pointer versions of memcpy() and memset() even
  174496. * in the small-model libraries. These will be used if USE_FMEM is defined.
  174497. * Otherwise, the routines below do it the hard way. (The performance cost
  174498. * is not all that great, because these routines aren't very heavily used.)
  174499. */
  174500. #ifndef NEED_FAR_POINTERS /* normal case, same as regular macros */
  174501. #define FMEMCOPY(dest,src,size) MEMCOPY(dest,src,size)
  174502. #define FMEMZERO(target,size) MEMZERO(target,size)
  174503. #else /* 80x86 case, define if we can */
  174504. #ifdef USE_FMEM
  174505. #define FMEMCOPY(dest,src,size) _fmemcpy((void FAR *)(dest), (const void FAR *)(src), (size_t)(size))
  174506. #define FMEMZERO(target,size) _fmemset((void FAR *)(target), 0, (size_t)(size))
  174507. #endif
  174508. #endif
  174509. GLOBAL(void)
  174510. jcopy_sample_rows (JSAMPARRAY input_array, int source_row,
  174511. JSAMPARRAY output_array, int dest_row,
  174512. int num_rows, JDIMENSION num_cols)
  174513. /* Copy some rows of samples from one place to another.
  174514. * num_rows rows are copied from input_array[source_row++]
  174515. * to output_array[dest_row++]; these areas may overlap for duplication.
  174516. * The source and destination arrays must be at least as wide as num_cols.
  174517. */
  174518. {
  174519. register JSAMPROW inptr, outptr;
  174520. #ifdef FMEMCOPY
  174521. register size_t count = (size_t) (num_cols * SIZEOF(JSAMPLE));
  174522. #else
  174523. register JDIMENSION count;
  174524. #endif
  174525. register int row;
  174526. input_array += source_row;
  174527. output_array += dest_row;
  174528. for (row = num_rows; row > 0; row--) {
  174529. inptr = *input_array++;
  174530. outptr = *output_array++;
  174531. #ifdef FMEMCOPY
  174532. FMEMCOPY(outptr, inptr, count);
  174533. #else
  174534. for (count = num_cols; count > 0; count--)
  174535. *outptr++ = *inptr++; /* needn't bother with GETJSAMPLE() here */
  174536. #endif
  174537. }
  174538. }
  174539. GLOBAL(void)
  174540. jcopy_block_row (JBLOCKROW input_row, JBLOCKROW output_row,
  174541. JDIMENSION num_blocks)
  174542. /* Copy a row of coefficient blocks from one place to another. */
  174543. {
  174544. #ifdef FMEMCOPY
  174545. FMEMCOPY(output_row, input_row, num_blocks * (DCTSIZE2 * SIZEOF(JCOEF)));
  174546. #else
  174547. register JCOEFPTR inptr, outptr;
  174548. register long count;
  174549. inptr = (JCOEFPTR) input_row;
  174550. outptr = (JCOEFPTR) output_row;
  174551. for (count = (long) num_blocks * DCTSIZE2; count > 0; count--) {
  174552. *outptr++ = *inptr++;
  174553. }
  174554. #endif
  174555. }
  174556. GLOBAL(void)
  174557. jzero_far (void FAR * target, size_t bytestozero)
  174558. /* Zero out a chunk of FAR memory. */
  174559. /* This might be sample-array data, block-array data, or alloc_large data. */
  174560. {
  174561. #ifdef FMEMZERO
  174562. FMEMZERO(target, bytestozero);
  174563. #else
  174564. register char FAR * ptr = (char FAR *) target;
  174565. register size_t count;
  174566. for (count = bytestozero; count > 0; count--) {
  174567. *ptr++ = 0;
  174568. }
  174569. #endif
  174570. }
  174571. /********* End of inlined file: jutils.c *********/
  174572. /********* Start of inlined file: transupp.c *********/
  174573. /* Although this file really shouldn't have access to the library internals,
  174574. * it's helpful to let it call jround_up() and jcopy_block_row().
  174575. */
  174576. #define JPEG_INTERNALS
  174577. /********* Start of inlined file: transupp.h *********/
  174578. /* If you happen not to want the image transform support, disable it here */
  174579. #ifndef TRANSFORMS_SUPPORTED
  174580. #define TRANSFORMS_SUPPORTED 1 /* 0 disables transform code */
  174581. #endif
  174582. /* Short forms of external names for systems with brain-damaged linkers. */
  174583. #ifdef NEED_SHORT_EXTERNAL_NAMES
  174584. #define jtransform_request_workspace jTrRequest
  174585. #define jtransform_adjust_parameters jTrAdjust
  174586. #define jtransform_execute_transformation jTrExec
  174587. #define jcopy_markers_setup jCMrkSetup
  174588. #define jcopy_markers_execute jCMrkExec
  174589. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  174590. /*
  174591. * Codes for supported types of image transformations.
  174592. */
  174593. typedef enum {
  174594. JXFORM_NONE, /* no transformation */
  174595. JXFORM_FLIP_H, /* horizontal flip */
  174596. JXFORM_FLIP_V, /* vertical flip */
  174597. JXFORM_TRANSPOSE, /* transpose across UL-to-LR axis */
  174598. JXFORM_TRANSVERSE, /* transpose across UR-to-LL axis */
  174599. JXFORM_ROT_90, /* 90-degree clockwise rotation */
  174600. JXFORM_ROT_180, /* 180-degree rotation */
  174601. JXFORM_ROT_270 /* 270-degree clockwise (or 90 ccw) */
  174602. } JXFORM_CODE;
  174603. /*
  174604. * Although rotating and flipping data expressed as DCT coefficients is not
  174605. * hard, there is an asymmetry in the JPEG format specification for images
  174606. * whose dimensions aren't multiples of the iMCU size. The right and bottom
  174607. * image edges are padded out to the next iMCU boundary with junk data; but
  174608. * no padding is possible at the top and left edges. If we were to flip
  174609. * the whole image including the pad data, then pad garbage would become
  174610. * visible at the top and/or left, and real pixels would disappear into the
  174611. * pad margins --- perhaps permanently, since encoders & decoders may not
  174612. * bother to preserve DCT blocks that appear to be completely outside the
  174613. * nominal image area. So, we have to exclude any partial iMCUs from the
  174614. * basic transformation.
  174615. *
  174616. * Transpose is the only transformation that can handle partial iMCUs at the
  174617. * right and bottom edges completely cleanly. flip_h can flip partial iMCUs
  174618. * at the bottom, but leaves any partial iMCUs at the right edge untouched.
  174619. * Similarly flip_v leaves any partial iMCUs at the bottom edge untouched.
  174620. * The other transforms are defined as combinations of these basic transforms
  174621. * and process edge blocks in a way that preserves the equivalence.
  174622. *
  174623. * The "trim" option causes untransformable partial iMCUs to be dropped;
  174624. * this is not strictly lossless, but it usually gives the best-looking
  174625. * result for odd-size images. Note that when this option is active,
  174626. * the expected mathematical equivalences between the transforms may not hold.
  174627. * (For example, -rot 270 -trim trims only the bottom edge, but -rot 90 -trim
  174628. * followed by -rot 180 -trim trims both edges.)
  174629. *
  174630. * We also offer a "force to grayscale" option, which simply discards the
  174631. * chrominance channels of a YCbCr image. This is lossless in the sense that
  174632. * the luminance channel is preserved exactly. It's not the same kind of
  174633. * thing as the rotate/flip transformations, but it's convenient to handle it
  174634. * as part of this package, mainly because the transformation routines have to
  174635. * be aware of the option to know how many components to work on.
  174636. */
  174637. typedef struct {
  174638. /* Options: set by caller */
  174639. JXFORM_CODE transform; /* image transform operator */
  174640. boolean trim; /* if TRUE, trim partial MCUs as needed */
  174641. boolean force_grayscale; /* if TRUE, convert color image to grayscale */
  174642. /* Internal workspace: caller should not touch these */
  174643. int num_components; /* # of components in workspace */
  174644. jvirt_barray_ptr * workspace_coef_arrays; /* workspace for transformations */
  174645. } jpeg_transform_info;
  174646. #if TRANSFORMS_SUPPORTED
  174647. /* Request any required workspace */
  174648. EXTERN(void) jtransform_request_workspace
  174649. JPP((j_decompress_ptr srcinfo, jpeg_transform_info *info));
  174650. /* Adjust output image parameters */
  174651. EXTERN(jvirt_barray_ptr *) jtransform_adjust_parameters
  174652. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  174653. jvirt_barray_ptr *src_coef_arrays,
  174654. jpeg_transform_info *info));
  174655. /* Execute the actual transformation, if any */
  174656. EXTERN(void) jtransform_execute_transformation
  174657. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  174658. jvirt_barray_ptr *src_coef_arrays,
  174659. jpeg_transform_info *info));
  174660. #endif /* TRANSFORMS_SUPPORTED */
  174661. /*
  174662. * Support for copying optional markers from source to destination file.
  174663. */
  174664. typedef enum {
  174665. JCOPYOPT_NONE, /* copy no optional markers */
  174666. JCOPYOPT_COMMENTS, /* copy only comment (COM) markers */
  174667. JCOPYOPT_ALL /* copy all optional markers */
  174668. } JCOPY_OPTION;
  174669. #define JCOPYOPT_DEFAULT JCOPYOPT_COMMENTS /* recommended default */
  174670. /* Setup decompression object to save desired markers in memory */
  174671. EXTERN(void) jcopy_markers_setup
  174672. JPP((j_decompress_ptr srcinfo, JCOPY_OPTION option));
  174673. /* Copy markers saved in the given source object to the destination object */
  174674. EXTERN(void) jcopy_markers_execute
  174675. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  174676. JCOPY_OPTION option));
  174677. /********* End of inlined file: transupp.h *********/
  174678. /* My own external interface */
  174679. #if TRANSFORMS_SUPPORTED
  174680. /*
  174681. * Lossless image transformation routines. These routines work on DCT
  174682. * coefficient arrays and thus do not require any lossy decompression
  174683. * or recompression of the image.
  174684. * Thanks to Guido Vollbeding for the initial design and code of this feature.
  174685. *
  174686. * Horizontal flipping is done in-place, using a single top-to-bottom
  174687. * pass through the virtual source array. It will thus be much the
  174688. * fastest option for images larger than main memory.
  174689. *
  174690. * The other routines require a set of destination virtual arrays, so they
  174691. * need twice as much memory as jpegtran normally does. The destination
  174692. * arrays are always written in normal scan order (top to bottom) because
  174693. * the virtual array manager expects this. The source arrays will be scanned
  174694. * in the corresponding order, which means multiple passes through the source
  174695. * arrays for most of the transforms. That could result in much thrashing
  174696. * if the image is larger than main memory.
  174697. *
  174698. * Some notes about the operating environment of the individual transform
  174699. * routines:
  174700. * 1. Both the source and destination virtual arrays are allocated from the
  174701. * source JPEG object, and therefore should be manipulated by calling the
  174702. * source's memory manager.
  174703. * 2. The destination's component count should be used. It may be smaller
  174704. * than the source's when forcing to grayscale.
  174705. * 3. Likewise the destination's sampling factors should be used. When
  174706. * forcing to grayscale the destination's sampling factors will be all 1,
  174707. * and we may as well take that as the effective iMCU size.
  174708. * 4. When "trim" is in effect, the destination's dimensions will be the
  174709. * trimmed values but the source's will be untrimmed.
  174710. * 5. All the routines assume that the source and destination buffers are
  174711. * padded out to a full iMCU boundary. This is true, although for the
  174712. * source buffer it is an undocumented property of jdcoefct.c.
  174713. * Notes 2,3,4 boil down to this: generally we should use the destination's
  174714. * dimensions and ignore the source's.
  174715. */
  174716. LOCAL(void)
  174717. do_flip_h (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  174718. jvirt_barray_ptr *src_coef_arrays)
  174719. /* Horizontal flip; done in-place, so no separate dest array is required */
  174720. {
  174721. JDIMENSION MCU_cols, comp_width, blk_x, blk_y;
  174722. int ci, k, offset_y;
  174723. JBLOCKARRAY buffer;
  174724. JCOEFPTR ptr1, ptr2;
  174725. JCOEF temp1, temp2;
  174726. jpeg_component_info *compptr;
  174727. /* Horizontal mirroring of DCT blocks is accomplished by swapping
  174728. * pairs of blocks in-place. Within a DCT block, we perform horizontal
  174729. * mirroring by changing the signs of odd-numbered columns.
  174730. * Partial iMCUs at the right edge are left untouched.
  174731. */
  174732. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  174733. for (ci = 0; ci < dstinfo->num_components; ci++) {
  174734. compptr = dstinfo->comp_info + ci;
  174735. comp_width = MCU_cols * compptr->h_samp_factor;
  174736. for (blk_y = 0; blk_y < compptr->height_in_blocks;
  174737. blk_y += compptr->v_samp_factor) {
  174738. buffer = (*srcinfo->mem->access_virt_barray)
  174739. ((j_common_ptr) srcinfo, src_coef_arrays[ci], blk_y,
  174740. (JDIMENSION) compptr->v_samp_factor, TRUE);
  174741. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  174742. for (blk_x = 0; blk_x * 2 < comp_width; blk_x++) {
  174743. ptr1 = buffer[offset_y][blk_x];
  174744. ptr2 = buffer[offset_y][comp_width - blk_x - 1];
  174745. /* this unrolled loop doesn't need to know which row it's on... */
  174746. for (k = 0; k < DCTSIZE2; k += 2) {
  174747. temp1 = *ptr1; /* swap even column */
  174748. temp2 = *ptr2;
  174749. *ptr1++ = temp2;
  174750. *ptr2++ = temp1;
  174751. temp1 = *ptr1; /* swap odd column with sign change */
  174752. temp2 = *ptr2;
  174753. *ptr1++ = -temp2;
  174754. *ptr2++ = -temp1;
  174755. }
  174756. }
  174757. }
  174758. }
  174759. }
  174760. }
  174761. LOCAL(void)
  174762. do_flip_v (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  174763. jvirt_barray_ptr *src_coef_arrays,
  174764. jvirt_barray_ptr *dst_coef_arrays)
  174765. /* Vertical flip */
  174766. {
  174767. JDIMENSION MCU_rows, comp_height, dst_blk_x, dst_blk_y;
  174768. int ci, i, j, offset_y;
  174769. JBLOCKARRAY src_buffer, dst_buffer;
  174770. JBLOCKROW src_row_ptr, dst_row_ptr;
  174771. JCOEFPTR src_ptr, dst_ptr;
  174772. jpeg_component_info *compptr;
  174773. /* We output into a separate array because we can't touch different
  174774. * rows of the source virtual array simultaneously. Otherwise, this
  174775. * is a pretty straightforward analog of horizontal flip.
  174776. * Within a DCT block, vertical mirroring is done by changing the signs
  174777. * of odd-numbered rows.
  174778. * Partial iMCUs at the bottom edge are copied verbatim.
  174779. */
  174780. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  174781. for (ci = 0; ci < dstinfo->num_components; ci++) {
  174782. compptr = dstinfo->comp_info + ci;
  174783. comp_height = MCU_rows * compptr->v_samp_factor;
  174784. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  174785. dst_blk_y += compptr->v_samp_factor) {
  174786. dst_buffer = (*srcinfo->mem->access_virt_barray)
  174787. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  174788. (JDIMENSION) compptr->v_samp_factor, TRUE);
  174789. if (dst_blk_y < comp_height) {
  174790. /* Row is within the mirrorable area. */
  174791. src_buffer = (*srcinfo->mem->access_virt_barray)
  174792. ((j_common_ptr) srcinfo, src_coef_arrays[ci],
  174793. comp_height - dst_blk_y - (JDIMENSION) compptr->v_samp_factor,
  174794. (JDIMENSION) compptr->v_samp_factor, FALSE);
  174795. } else {
  174796. /* Bottom-edge blocks will be copied verbatim. */
  174797. src_buffer = (*srcinfo->mem->access_virt_barray)
  174798. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_y,
  174799. (JDIMENSION) compptr->v_samp_factor, FALSE);
  174800. }
  174801. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  174802. if (dst_blk_y < comp_height) {
  174803. /* Row is within the mirrorable area. */
  174804. dst_row_ptr = dst_buffer[offset_y];
  174805. src_row_ptr = src_buffer[compptr->v_samp_factor - offset_y - 1];
  174806. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  174807. dst_blk_x++) {
  174808. dst_ptr = dst_row_ptr[dst_blk_x];
  174809. src_ptr = src_row_ptr[dst_blk_x];
  174810. for (i = 0; i < DCTSIZE; i += 2) {
  174811. /* copy even row */
  174812. for (j = 0; j < DCTSIZE; j++)
  174813. *dst_ptr++ = *src_ptr++;
  174814. /* copy odd row with sign change */
  174815. for (j = 0; j < DCTSIZE; j++)
  174816. *dst_ptr++ = - *src_ptr++;
  174817. }
  174818. }
  174819. } else {
  174820. /* Just copy row verbatim. */
  174821. jcopy_block_row(src_buffer[offset_y], dst_buffer[offset_y],
  174822. compptr->width_in_blocks);
  174823. }
  174824. }
  174825. }
  174826. }
  174827. }
  174828. LOCAL(void)
  174829. do_transpose (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  174830. jvirt_barray_ptr *src_coef_arrays,
  174831. jvirt_barray_ptr *dst_coef_arrays)
  174832. /* Transpose source into destination */
  174833. {
  174834. JDIMENSION dst_blk_x, dst_blk_y;
  174835. int ci, i, j, offset_x, offset_y;
  174836. JBLOCKARRAY src_buffer, dst_buffer;
  174837. JCOEFPTR src_ptr, dst_ptr;
  174838. jpeg_component_info *compptr;
  174839. /* Transposing pixels within a block just requires transposing the
  174840. * DCT coefficients.
  174841. * Partial iMCUs at the edges require no special treatment; we simply
  174842. * process all the available DCT blocks for every component.
  174843. */
  174844. for (ci = 0; ci < dstinfo->num_components; ci++) {
  174845. compptr = dstinfo->comp_info + ci;
  174846. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  174847. dst_blk_y += compptr->v_samp_factor) {
  174848. dst_buffer = (*srcinfo->mem->access_virt_barray)
  174849. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  174850. (JDIMENSION) compptr->v_samp_factor, TRUE);
  174851. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  174852. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  174853. dst_blk_x += compptr->h_samp_factor) {
  174854. src_buffer = (*srcinfo->mem->access_virt_barray)
  174855. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  174856. (JDIMENSION) compptr->h_samp_factor, FALSE);
  174857. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  174858. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  174859. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  174860. for (i = 0; i < DCTSIZE; i++)
  174861. for (j = 0; j < DCTSIZE; j++)
  174862. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  174863. }
  174864. }
  174865. }
  174866. }
  174867. }
  174868. }
  174869. LOCAL(void)
  174870. do_rot_90 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  174871. jvirt_barray_ptr *src_coef_arrays,
  174872. jvirt_barray_ptr *dst_coef_arrays)
  174873. /* 90 degree rotation is equivalent to
  174874. * 1. Transposing the image;
  174875. * 2. Horizontal mirroring.
  174876. * These two steps are merged into a single processing routine.
  174877. */
  174878. {
  174879. JDIMENSION MCU_cols, comp_width, dst_blk_x, dst_blk_y;
  174880. int ci, i, j, offset_x, offset_y;
  174881. JBLOCKARRAY src_buffer, dst_buffer;
  174882. JCOEFPTR src_ptr, dst_ptr;
  174883. jpeg_component_info *compptr;
  174884. /* Because of the horizontal mirror step, we can't process partial iMCUs
  174885. * at the (output) right edge properly. They just get transposed and
  174886. * not mirrored.
  174887. */
  174888. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  174889. for (ci = 0; ci < dstinfo->num_components; ci++) {
  174890. compptr = dstinfo->comp_info + ci;
  174891. comp_width = MCU_cols * compptr->h_samp_factor;
  174892. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  174893. dst_blk_y += compptr->v_samp_factor) {
  174894. dst_buffer = (*srcinfo->mem->access_virt_barray)
  174895. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  174896. (JDIMENSION) compptr->v_samp_factor, TRUE);
  174897. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  174898. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  174899. dst_blk_x += compptr->h_samp_factor) {
  174900. src_buffer = (*srcinfo->mem->access_virt_barray)
  174901. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  174902. (JDIMENSION) compptr->h_samp_factor, FALSE);
  174903. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  174904. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  174905. if (dst_blk_x < comp_width) {
  174906. /* Block is within the mirrorable area. */
  174907. dst_ptr = dst_buffer[offset_y]
  174908. [comp_width - dst_blk_x - offset_x - 1];
  174909. for (i = 0; i < DCTSIZE; i++) {
  174910. for (j = 0; j < DCTSIZE; j++)
  174911. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  174912. i++;
  174913. for (j = 0; j < DCTSIZE; j++)
  174914. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  174915. }
  174916. } else {
  174917. /* Edge blocks are transposed but not mirrored. */
  174918. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  174919. for (i = 0; i < DCTSIZE; i++)
  174920. for (j = 0; j < DCTSIZE; j++)
  174921. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  174922. }
  174923. }
  174924. }
  174925. }
  174926. }
  174927. }
  174928. }
  174929. LOCAL(void)
  174930. do_rot_270 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  174931. jvirt_barray_ptr *src_coef_arrays,
  174932. jvirt_barray_ptr *dst_coef_arrays)
  174933. /* 270 degree rotation is equivalent to
  174934. * 1. Horizontal mirroring;
  174935. * 2. Transposing the image.
  174936. * These two steps are merged into a single processing routine.
  174937. */
  174938. {
  174939. JDIMENSION MCU_rows, comp_height, dst_blk_x, dst_blk_y;
  174940. int ci, i, j, offset_x, offset_y;
  174941. JBLOCKARRAY src_buffer, dst_buffer;
  174942. JCOEFPTR src_ptr, dst_ptr;
  174943. jpeg_component_info *compptr;
  174944. /* Because of the horizontal mirror step, we can't process partial iMCUs
  174945. * at the (output) bottom edge properly. They just get transposed and
  174946. * not mirrored.
  174947. */
  174948. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  174949. for (ci = 0; ci < dstinfo->num_components; ci++) {
  174950. compptr = dstinfo->comp_info + ci;
  174951. comp_height = MCU_rows * compptr->v_samp_factor;
  174952. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  174953. dst_blk_y += compptr->v_samp_factor) {
  174954. dst_buffer = (*srcinfo->mem->access_virt_barray)
  174955. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  174956. (JDIMENSION) compptr->v_samp_factor, TRUE);
  174957. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  174958. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  174959. dst_blk_x += compptr->h_samp_factor) {
  174960. src_buffer = (*srcinfo->mem->access_virt_barray)
  174961. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  174962. (JDIMENSION) compptr->h_samp_factor, FALSE);
  174963. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  174964. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  174965. if (dst_blk_y < comp_height) {
  174966. /* Block is within the mirrorable area. */
  174967. src_ptr = src_buffer[offset_x]
  174968. [comp_height - dst_blk_y - offset_y - 1];
  174969. for (i = 0; i < DCTSIZE; i++) {
  174970. for (j = 0; j < DCTSIZE; j++) {
  174971. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  174972. j++;
  174973. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  174974. }
  174975. }
  174976. } else {
  174977. /* Edge blocks are transposed but not mirrored. */
  174978. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  174979. for (i = 0; i < DCTSIZE; i++)
  174980. for (j = 0; j < DCTSIZE; j++)
  174981. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  174982. }
  174983. }
  174984. }
  174985. }
  174986. }
  174987. }
  174988. }
  174989. LOCAL(void)
  174990. do_rot_180 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  174991. jvirt_barray_ptr *src_coef_arrays,
  174992. jvirt_barray_ptr *dst_coef_arrays)
  174993. /* 180 degree rotation is equivalent to
  174994. * 1. Vertical mirroring;
  174995. * 2. Horizontal mirroring.
  174996. * These two steps are merged into a single processing routine.
  174997. */
  174998. {
  174999. JDIMENSION MCU_cols, MCU_rows, comp_width, comp_height, dst_blk_x, dst_blk_y;
  175000. int ci, i, j, offset_y;
  175001. JBLOCKARRAY src_buffer, dst_buffer;
  175002. JBLOCKROW src_row_ptr, dst_row_ptr;
  175003. JCOEFPTR src_ptr, dst_ptr;
  175004. jpeg_component_info *compptr;
  175005. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  175006. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  175007. for (ci = 0; ci < dstinfo->num_components; ci++) {
  175008. compptr = dstinfo->comp_info + ci;
  175009. comp_width = MCU_cols * compptr->h_samp_factor;
  175010. comp_height = MCU_rows * compptr->v_samp_factor;
  175011. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  175012. dst_blk_y += compptr->v_samp_factor) {
  175013. dst_buffer = (*srcinfo->mem->access_virt_barray)
  175014. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  175015. (JDIMENSION) compptr->v_samp_factor, TRUE);
  175016. if (dst_blk_y < comp_height) {
  175017. /* Row is within the vertically mirrorable area. */
  175018. src_buffer = (*srcinfo->mem->access_virt_barray)
  175019. ((j_common_ptr) srcinfo, src_coef_arrays[ci],
  175020. comp_height - dst_blk_y - (JDIMENSION) compptr->v_samp_factor,
  175021. (JDIMENSION) compptr->v_samp_factor, FALSE);
  175022. } else {
  175023. /* Bottom-edge rows are only mirrored horizontally. */
  175024. src_buffer = (*srcinfo->mem->access_virt_barray)
  175025. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_y,
  175026. (JDIMENSION) compptr->v_samp_factor, FALSE);
  175027. }
  175028. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  175029. if (dst_blk_y < comp_height) {
  175030. /* Row is within the mirrorable area. */
  175031. dst_row_ptr = dst_buffer[offset_y];
  175032. src_row_ptr = src_buffer[compptr->v_samp_factor - offset_y - 1];
  175033. /* Process the blocks that can be mirrored both ways. */
  175034. for (dst_blk_x = 0; dst_blk_x < comp_width; dst_blk_x++) {
  175035. dst_ptr = dst_row_ptr[dst_blk_x];
  175036. src_ptr = src_row_ptr[comp_width - dst_blk_x - 1];
  175037. for (i = 0; i < DCTSIZE; i += 2) {
  175038. /* For even row, negate every odd column. */
  175039. for (j = 0; j < DCTSIZE; j += 2) {
  175040. *dst_ptr++ = *src_ptr++;
  175041. *dst_ptr++ = - *src_ptr++;
  175042. }
  175043. /* For odd row, negate every even column. */
  175044. for (j = 0; j < DCTSIZE; j += 2) {
  175045. *dst_ptr++ = - *src_ptr++;
  175046. *dst_ptr++ = *src_ptr++;
  175047. }
  175048. }
  175049. }
  175050. /* Any remaining right-edge blocks are only mirrored vertically. */
  175051. for (; dst_blk_x < compptr->width_in_blocks; dst_blk_x++) {
  175052. dst_ptr = dst_row_ptr[dst_blk_x];
  175053. src_ptr = src_row_ptr[dst_blk_x];
  175054. for (i = 0; i < DCTSIZE; i += 2) {
  175055. for (j = 0; j < DCTSIZE; j++)
  175056. *dst_ptr++ = *src_ptr++;
  175057. for (j = 0; j < DCTSIZE; j++)
  175058. *dst_ptr++ = - *src_ptr++;
  175059. }
  175060. }
  175061. } else {
  175062. /* Remaining rows are just mirrored horizontally. */
  175063. dst_row_ptr = dst_buffer[offset_y];
  175064. src_row_ptr = src_buffer[offset_y];
  175065. /* Process the blocks that can be mirrored. */
  175066. for (dst_blk_x = 0; dst_blk_x < comp_width; dst_blk_x++) {
  175067. dst_ptr = dst_row_ptr[dst_blk_x];
  175068. src_ptr = src_row_ptr[comp_width - dst_blk_x - 1];
  175069. for (i = 0; i < DCTSIZE2; i += 2) {
  175070. *dst_ptr++ = *src_ptr++;
  175071. *dst_ptr++ = - *src_ptr++;
  175072. }
  175073. }
  175074. /* Any remaining right-edge blocks are only copied. */
  175075. for (; dst_blk_x < compptr->width_in_blocks; dst_blk_x++) {
  175076. dst_ptr = dst_row_ptr[dst_blk_x];
  175077. src_ptr = src_row_ptr[dst_blk_x];
  175078. for (i = 0; i < DCTSIZE2; i++)
  175079. *dst_ptr++ = *src_ptr++;
  175080. }
  175081. }
  175082. }
  175083. }
  175084. }
  175085. }
  175086. LOCAL(void)
  175087. do_transverse (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  175088. jvirt_barray_ptr *src_coef_arrays,
  175089. jvirt_barray_ptr *dst_coef_arrays)
  175090. /* Transverse transpose is equivalent to
  175091. * 1. 180 degree rotation;
  175092. * 2. Transposition;
  175093. * or
  175094. * 1. Horizontal mirroring;
  175095. * 2. Transposition;
  175096. * 3. Horizontal mirroring.
  175097. * These steps are merged into a single processing routine.
  175098. */
  175099. {
  175100. JDIMENSION MCU_cols, MCU_rows, comp_width, comp_height, dst_blk_x, dst_blk_y;
  175101. int ci, i, j, offset_x, offset_y;
  175102. JBLOCKARRAY src_buffer, dst_buffer;
  175103. JCOEFPTR src_ptr, dst_ptr;
  175104. jpeg_component_info *compptr;
  175105. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  175106. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  175107. for (ci = 0; ci < dstinfo->num_components; ci++) {
  175108. compptr = dstinfo->comp_info + ci;
  175109. comp_width = MCU_cols * compptr->h_samp_factor;
  175110. comp_height = MCU_rows * compptr->v_samp_factor;
  175111. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  175112. dst_blk_y += compptr->v_samp_factor) {
  175113. dst_buffer = (*srcinfo->mem->access_virt_barray)
  175114. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  175115. (JDIMENSION) compptr->v_samp_factor, TRUE);
  175116. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  175117. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  175118. dst_blk_x += compptr->h_samp_factor) {
  175119. src_buffer = (*srcinfo->mem->access_virt_barray)
  175120. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  175121. (JDIMENSION) compptr->h_samp_factor, FALSE);
  175122. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  175123. if (dst_blk_y < comp_height) {
  175124. src_ptr = src_buffer[offset_x]
  175125. [comp_height - dst_blk_y - offset_y - 1];
  175126. if (dst_blk_x < comp_width) {
  175127. /* Block is within the mirrorable area. */
  175128. dst_ptr = dst_buffer[offset_y]
  175129. [comp_width - dst_blk_x - offset_x - 1];
  175130. for (i = 0; i < DCTSIZE; i++) {
  175131. for (j = 0; j < DCTSIZE; j++) {
  175132. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  175133. j++;
  175134. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  175135. }
  175136. i++;
  175137. for (j = 0; j < DCTSIZE; j++) {
  175138. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  175139. j++;
  175140. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  175141. }
  175142. }
  175143. } else {
  175144. /* Right-edge blocks are mirrored in y only */
  175145. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  175146. for (i = 0; i < DCTSIZE; i++) {
  175147. for (j = 0; j < DCTSIZE; j++) {
  175148. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  175149. j++;
  175150. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  175151. }
  175152. }
  175153. }
  175154. } else {
  175155. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  175156. if (dst_blk_x < comp_width) {
  175157. /* Bottom-edge blocks are mirrored in x only */
  175158. dst_ptr = dst_buffer[offset_y]
  175159. [comp_width - dst_blk_x - offset_x - 1];
  175160. for (i = 0; i < DCTSIZE; i++) {
  175161. for (j = 0; j < DCTSIZE; j++)
  175162. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  175163. i++;
  175164. for (j = 0; j < DCTSIZE; j++)
  175165. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  175166. }
  175167. } else {
  175168. /* At lower right corner, just transpose, no mirroring */
  175169. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  175170. for (i = 0; i < DCTSIZE; i++)
  175171. for (j = 0; j < DCTSIZE; j++)
  175172. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  175173. }
  175174. }
  175175. }
  175176. }
  175177. }
  175178. }
  175179. }
  175180. }
  175181. /* Request any required workspace.
  175182. *
  175183. * We allocate the workspace virtual arrays from the source decompression
  175184. * object, so that all the arrays (both the original data and the workspace)
  175185. * will be taken into account while making memory management decisions.
  175186. * Hence, this routine must be called after jpeg_read_header (which reads
  175187. * the image dimensions) and before jpeg_read_coefficients (which realizes
  175188. * the source's virtual arrays).
  175189. */
  175190. GLOBAL(void)
  175191. jtransform_request_workspace (j_decompress_ptr srcinfo,
  175192. jpeg_transform_info *info)
  175193. {
  175194. jvirt_barray_ptr *coef_arrays = NULL;
  175195. jpeg_component_info *compptr;
  175196. int ci;
  175197. if (info->force_grayscale &&
  175198. srcinfo->jpeg_color_space == JCS_YCbCr &&
  175199. srcinfo->num_components == 3) {
  175200. /* We'll only process the first component */
  175201. info->num_components = 1;
  175202. } else {
  175203. /* Process all the components */
  175204. info->num_components = srcinfo->num_components;
  175205. }
  175206. switch (info->transform) {
  175207. case JXFORM_NONE:
  175208. case JXFORM_FLIP_H:
  175209. /* Don't need a workspace array */
  175210. break;
  175211. case JXFORM_FLIP_V:
  175212. case JXFORM_ROT_180:
  175213. /* Need workspace arrays having same dimensions as source image.
  175214. * Note that we allocate arrays padded out to the next iMCU boundary,
  175215. * so that transform routines need not worry about missing edge blocks.
  175216. */
  175217. coef_arrays = (jvirt_barray_ptr *)
  175218. (*srcinfo->mem->alloc_small) ((j_common_ptr) srcinfo, JPOOL_IMAGE,
  175219. SIZEOF(jvirt_barray_ptr) * info->num_components);
  175220. for (ci = 0; ci < info->num_components; ci++) {
  175221. compptr = srcinfo->comp_info + ci;
  175222. coef_arrays[ci] = (*srcinfo->mem->request_virt_barray)
  175223. ((j_common_ptr) srcinfo, JPOOL_IMAGE, FALSE,
  175224. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  175225. (long) compptr->h_samp_factor),
  175226. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  175227. (long) compptr->v_samp_factor),
  175228. (JDIMENSION) compptr->v_samp_factor);
  175229. }
  175230. break;
  175231. case JXFORM_TRANSPOSE:
  175232. case JXFORM_TRANSVERSE:
  175233. case JXFORM_ROT_90:
  175234. case JXFORM_ROT_270:
  175235. /* Need workspace arrays having transposed dimensions.
  175236. * Note that we allocate arrays padded out to the next iMCU boundary,
  175237. * so that transform routines need not worry about missing edge blocks.
  175238. */
  175239. coef_arrays = (jvirt_barray_ptr *)
  175240. (*srcinfo->mem->alloc_small) ((j_common_ptr) srcinfo, JPOOL_IMAGE,
  175241. SIZEOF(jvirt_barray_ptr) * info->num_components);
  175242. for (ci = 0; ci < info->num_components; ci++) {
  175243. compptr = srcinfo->comp_info + ci;
  175244. coef_arrays[ci] = (*srcinfo->mem->request_virt_barray)
  175245. ((j_common_ptr) srcinfo, JPOOL_IMAGE, FALSE,
  175246. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  175247. (long) compptr->v_samp_factor),
  175248. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  175249. (long) compptr->h_samp_factor),
  175250. (JDIMENSION) compptr->h_samp_factor);
  175251. }
  175252. break;
  175253. }
  175254. info->workspace_coef_arrays = coef_arrays;
  175255. }
  175256. /* Transpose destination image parameters */
  175257. LOCAL(void)
  175258. transpose_critical_parameters (j_compress_ptr dstinfo)
  175259. {
  175260. int tblno, i, j, ci, itemp;
  175261. jpeg_component_info *compptr;
  175262. JQUANT_TBL *qtblptr;
  175263. JDIMENSION dtemp;
  175264. UINT16 qtemp;
  175265. /* Transpose basic image dimensions */
  175266. dtemp = dstinfo->image_width;
  175267. dstinfo->image_width = dstinfo->image_height;
  175268. dstinfo->image_height = dtemp;
  175269. /* Transpose sampling factors */
  175270. for (ci = 0; ci < dstinfo->num_components; ci++) {
  175271. compptr = dstinfo->comp_info + ci;
  175272. itemp = compptr->h_samp_factor;
  175273. compptr->h_samp_factor = compptr->v_samp_factor;
  175274. compptr->v_samp_factor = itemp;
  175275. }
  175276. /* Transpose quantization tables */
  175277. for (tblno = 0; tblno < NUM_QUANT_TBLS; tblno++) {
  175278. qtblptr = dstinfo->quant_tbl_ptrs[tblno];
  175279. if (qtblptr != NULL) {
  175280. for (i = 0; i < DCTSIZE; i++) {
  175281. for (j = 0; j < i; j++) {
  175282. qtemp = qtblptr->quantval[i*DCTSIZE+j];
  175283. qtblptr->quantval[i*DCTSIZE+j] = qtblptr->quantval[j*DCTSIZE+i];
  175284. qtblptr->quantval[j*DCTSIZE+i] = qtemp;
  175285. }
  175286. }
  175287. }
  175288. }
  175289. }
  175290. /* Trim off any partial iMCUs on the indicated destination edge */
  175291. LOCAL(void)
  175292. trim_right_edge (j_compress_ptr dstinfo)
  175293. {
  175294. int ci, max_h_samp_factor;
  175295. JDIMENSION MCU_cols;
  175296. /* We have to compute max_h_samp_factor ourselves,
  175297. * because it hasn't been set yet in the destination
  175298. * (and we don't want to use the source's value).
  175299. */
  175300. max_h_samp_factor = 1;
  175301. for (ci = 0; ci < dstinfo->num_components; ci++) {
  175302. int h_samp_factor = dstinfo->comp_info[ci].h_samp_factor;
  175303. max_h_samp_factor = MAX(max_h_samp_factor, h_samp_factor);
  175304. }
  175305. MCU_cols = dstinfo->image_width / (max_h_samp_factor * DCTSIZE);
  175306. if (MCU_cols > 0) /* can't trim to 0 pixels */
  175307. dstinfo->image_width = MCU_cols * (max_h_samp_factor * DCTSIZE);
  175308. }
  175309. LOCAL(void)
  175310. trim_bottom_edge (j_compress_ptr dstinfo)
  175311. {
  175312. int ci, max_v_samp_factor;
  175313. JDIMENSION MCU_rows;
  175314. /* We have to compute max_v_samp_factor ourselves,
  175315. * because it hasn't been set yet in the destination
  175316. * (and we don't want to use the source's value).
  175317. */
  175318. max_v_samp_factor = 1;
  175319. for (ci = 0; ci < dstinfo->num_components; ci++) {
  175320. int v_samp_factor = dstinfo->comp_info[ci].v_samp_factor;
  175321. max_v_samp_factor = MAX(max_v_samp_factor, v_samp_factor);
  175322. }
  175323. MCU_rows = dstinfo->image_height / (max_v_samp_factor * DCTSIZE);
  175324. if (MCU_rows > 0) /* can't trim to 0 pixels */
  175325. dstinfo->image_height = MCU_rows * (max_v_samp_factor * DCTSIZE);
  175326. }
  175327. /* Adjust output image parameters as needed.
  175328. *
  175329. * This must be called after jpeg_copy_critical_parameters()
  175330. * and before jpeg_write_coefficients().
  175331. *
  175332. * The return value is the set of virtual coefficient arrays to be written
  175333. * (either the ones allocated by jtransform_request_workspace, or the
  175334. * original source data arrays). The caller will need to pass this value
  175335. * to jpeg_write_coefficients().
  175336. */
  175337. GLOBAL(jvirt_barray_ptr *)
  175338. jtransform_adjust_parameters (j_decompress_ptr srcinfo,
  175339. j_compress_ptr dstinfo,
  175340. jvirt_barray_ptr *src_coef_arrays,
  175341. jpeg_transform_info *info)
  175342. {
  175343. /* If force-to-grayscale is requested, adjust destination parameters */
  175344. if (info->force_grayscale) {
  175345. /* We use jpeg_set_colorspace to make sure subsidiary settings get fixed
  175346. * properly. Among other things, the target h_samp_factor & v_samp_factor
  175347. * will get set to 1, which typically won't match the source.
  175348. * In fact we do this even if the source is already grayscale; that
  175349. * provides an easy way of coercing a grayscale JPEG with funny sampling
  175350. * factors to the customary 1,1. (Some decoders fail on other factors.)
  175351. */
  175352. if ((dstinfo->jpeg_color_space == JCS_YCbCr &&
  175353. dstinfo->num_components == 3) ||
  175354. (dstinfo->jpeg_color_space == JCS_GRAYSCALE &&
  175355. dstinfo->num_components == 1)) {
  175356. /* We have to preserve the source's quantization table number. */
  175357. int sv_quant_tbl_no = dstinfo->comp_info[0].quant_tbl_no;
  175358. jpeg_set_colorspace(dstinfo, JCS_GRAYSCALE);
  175359. dstinfo->comp_info[0].quant_tbl_no = sv_quant_tbl_no;
  175360. } else {
  175361. /* Sorry, can't do it */
  175362. ERREXIT(dstinfo, JERR_CONVERSION_NOTIMPL);
  175363. }
  175364. }
  175365. /* Correct the destination's image dimensions etc if necessary */
  175366. switch (info->transform) {
  175367. case JXFORM_NONE:
  175368. /* Nothing to do */
  175369. break;
  175370. case JXFORM_FLIP_H:
  175371. if (info->trim)
  175372. trim_right_edge(dstinfo);
  175373. break;
  175374. case JXFORM_FLIP_V:
  175375. if (info->trim)
  175376. trim_bottom_edge(dstinfo);
  175377. break;
  175378. case JXFORM_TRANSPOSE:
  175379. transpose_critical_parameters(dstinfo);
  175380. /* transpose does NOT have to trim anything */
  175381. break;
  175382. case JXFORM_TRANSVERSE:
  175383. transpose_critical_parameters(dstinfo);
  175384. if (info->trim) {
  175385. trim_right_edge(dstinfo);
  175386. trim_bottom_edge(dstinfo);
  175387. }
  175388. break;
  175389. case JXFORM_ROT_90:
  175390. transpose_critical_parameters(dstinfo);
  175391. if (info->trim)
  175392. trim_right_edge(dstinfo);
  175393. break;
  175394. case JXFORM_ROT_180:
  175395. if (info->trim) {
  175396. trim_right_edge(dstinfo);
  175397. trim_bottom_edge(dstinfo);
  175398. }
  175399. break;
  175400. case JXFORM_ROT_270:
  175401. transpose_critical_parameters(dstinfo);
  175402. if (info->trim)
  175403. trim_bottom_edge(dstinfo);
  175404. break;
  175405. }
  175406. /* Return the appropriate output data set */
  175407. if (info->workspace_coef_arrays != NULL)
  175408. return info->workspace_coef_arrays;
  175409. return src_coef_arrays;
  175410. }
  175411. /* Execute the actual transformation, if any.
  175412. *
  175413. * This must be called *after* jpeg_write_coefficients, because it depends
  175414. * on jpeg_write_coefficients to have computed subsidiary values such as
  175415. * the per-component width and height fields in the destination object.
  175416. *
  175417. * Note that some transformations will modify the source data arrays!
  175418. */
  175419. GLOBAL(void)
  175420. jtransform_execute_transformation (j_decompress_ptr srcinfo,
  175421. j_compress_ptr dstinfo,
  175422. jvirt_barray_ptr *src_coef_arrays,
  175423. jpeg_transform_info *info)
  175424. {
  175425. jvirt_barray_ptr *dst_coef_arrays = info->workspace_coef_arrays;
  175426. switch (info->transform) {
  175427. case JXFORM_NONE:
  175428. break;
  175429. case JXFORM_FLIP_H:
  175430. do_flip_h(srcinfo, dstinfo, src_coef_arrays);
  175431. break;
  175432. case JXFORM_FLIP_V:
  175433. do_flip_v(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  175434. break;
  175435. case JXFORM_TRANSPOSE:
  175436. do_transpose(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  175437. break;
  175438. case JXFORM_TRANSVERSE:
  175439. do_transverse(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  175440. break;
  175441. case JXFORM_ROT_90:
  175442. do_rot_90(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  175443. break;
  175444. case JXFORM_ROT_180:
  175445. do_rot_180(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  175446. break;
  175447. case JXFORM_ROT_270:
  175448. do_rot_270(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  175449. break;
  175450. }
  175451. }
  175452. #endif /* TRANSFORMS_SUPPORTED */
  175453. /* Setup decompression object to save desired markers in memory.
  175454. * This must be called before jpeg_read_header() to have the desired effect.
  175455. */
  175456. GLOBAL(void)
  175457. jcopy_markers_setup (j_decompress_ptr srcinfo, JCOPY_OPTION option)
  175458. {
  175459. #ifdef SAVE_MARKERS_SUPPORTED
  175460. int m;
  175461. /* Save comments except under NONE option */
  175462. if (option != JCOPYOPT_NONE) {
  175463. jpeg_save_markers(srcinfo, JPEG_COM, 0xFFFF);
  175464. }
  175465. /* Save all types of APPn markers iff ALL option */
  175466. if (option == JCOPYOPT_ALL) {
  175467. for (m = 0; m < 16; m++)
  175468. jpeg_save_markers(srcinfo, JPEG_APP0 + m, 0xFFFF);
  175469. }
  175470. #endif /* SAVE_MARKERS_SUPPORTED */
  175471. }
  175472. /* Copy markers saved in the given source object to the destination object.
  175473. * This should be called just after jpeg_start_compress() or
  175474. * jpeg_write_coefficients().
  175475. * Note that those routines will have written the SOI, and also the
  175476. * JFIF APP0 or Adobe APP14 markers if selected.
  175477. */
  175478. GLOBAL(void)
  175479. jcopy_markers_execute (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  175480. JCOPY_OPTION option)
  175481. {
  175482. jpeg_saved_marker_ptr marker;
  175483. /* In the current implementation, we don't actually need to examine the
  175484. * option flag here; we just copy everything that got saved.
  175485. * But to avoid confusion, we do not output JFIF and Adobe APP14 markers
  175486. * if the encoder library already wrote one.
  175487. */
  175488. for (marker = srcinfo->marker_list; marker != NULL; marker = marker->next) {
  175489. if (dstinfo->write_JFIF_header &&
  175490. marker->marker == JPEG_APP0 &&
  175491. marker->data_length >= 5 &&
  175492. GETJOCTET(marker->data[0]) == 0x4A &&
  175493. GETJOCTET(marker->data[1]) == 0x46 &&
  175494. GETJOCTET(marker->data[2]) == 0x49 &&
  175495. GETJOCTET(marker->data[3]) == 0x46 &&
  175496. GETJOCTET(marker->data[4]) == 0)
  175497. continue; /* reject duplicate JFIF */
  175498. if (dstinfo->write_Adobe_marker &&
  175499. marker->marker == JPEG_APP0+14 &&
  175500. marker->data_length >= 5 &&
  175501. GETJOCTET(marker->data[0]) == 0x41 &&
  175502. GETJOCTET(marker->data[1]) == 0x64 &&
  175503. GETJOCTET(marker->data[2]) == 0x6F &&
  175504. GETJOCTET(marker->data[3]) == 0x62 &&
  175505. GETJOCTET(marker->data[4]) == 0x65)
  175506. continue; /* reject duplicate Adobe */
  175507. #ifdef NEED_FAR_POINTERS
  175508. /* We could use jpeg_write_marker if the data weren't FAR... */
  175509. {
  175510. unsigned int i;
  175511. jpeg_write_m_header(dstinfo, marker->marker, marker->data_length);
  175512. for (i = 0; i < marker->data_length; i++)
  175513. jpeg_write_m_byte(dstinfo, marker->data[i]);
  175514. }
  175515. #else
  175516. jpeg_write_marker(dstinfo, marker->marker,
  175517. marker->data, marker->data_length);
  175518. #endif
  175519. }
  175520. }
  175521. /********* End of inlined file: transupp.c *********/
  175522. }
  175523. #else
  175524. #define JPEG_INTERNALS
  175525. #undef FAR
  175526. #include <jpeglib.h>
  175527. #endif
  175528. }
  175529. #if JUCE_MSVC
  175530. #pragma warning (pop)
  175531. #endif
  175532. BEGIN_JUCE_NAMESPACE
  175533. using namespace jpeglibNamespace;
  175534. #if ! JUCE_WIN32
  175535. using jpeglibNamespace::boolean;
  175536. #endif
  175537. struct JPEGDecodingFailure {};
  175538. static void fatalErrorHandler (j_common_ptr)
  175539. {
  175540. throw JPEGDecodingFailure();
  175541. }
  175542. static void silentErrorCallback1 (j_common_ptr) {}
  175543. static void silentErrorCallback2 (j_common_ptr, int) {}
  175544. static void silentErrorCallback3 (j_common_ptr, char*) {}
  175545. static void setupSilentErrorHandler (struct jpeg_error_mgr& err)
  175546. {
  175547. zerostruct (err);
  175548. err.error_exit = fatalErrorHandler;
  175549. err.emit_message = silentErrorCallback2;
  175550. err.output_message = silentErrorCallback1;
  175551. err.format_message = silentErrorCallback3;
  175552. err.reset_error_mgr = silentErrorCallback1;
  175553. }
  175554. static void dummyCallback1 (j_decompress_ptr) throw()
  175555. {
  175556. }
  175557. static void jpegSkip (j_decompress_ptr decompStruct, long num) throw()
  175558. {
  175559. decompStruct->src->next_input_byte += num;
  175560. num = jmin (num, (int) decompStruct->src->bytes_in_buffer);
  175561. decompStruct->src->bytes_in_buffer -= num;
  175562. }
  175563. static boolean jpegFill (j_decompress_ptr) throw()
  175564. {
  175565. return 0;
  175566. }
  175567. Image* juce_loadJPEGImageFromStream (InputStream& in) throw()
  175568. {
  175569. MemoryBlock mb;
  175570. in.readIntoMemoryBlock (mb);
  175571. Image* image = 0;
  175572. if (mb.getSize() > 16)
  175573. {
  175574. struct jpeg_decompress_struct jpegDecompStruct;
  175575. struct jpeg_error_mgr jerr;
  175576. setupSilentErrorHandler (jerr);
  175577. jpegDecompStruct.err = &jerr;
  175578. jpeg_create_decompress (&jpegDecompStruct);
  175579. jpegDecompStruct.src = (jpeg_source_mgr*)(jpegDecompStruct.mem->alloc_small)
  175580. ((j_common_ptr)(&jpegDecompStruct), JPOOL_PERMANENT, sizeof (jpeg_source_mgr));
  175581. jpegDecompStruct.src->init_source = dummyCallback1;
  175582. jpegDecompStruct.src->fill_input_buffer = jpegFill;
  175583. jpegDecompStruct.src->skip_input_data = jpegSkip;
  175584. jpegDecompStruct.src->resync_to_restart = jpeg_resync_to_restart;
  175585. jpegDecompStruct.src->term_source = dummyCallback1;
  175586. jpegDecompStruct.src->next_input_byte = (const unsigned char*) mb.getData();
  175587. jpegDecompStruct.src->bytes_in_buffer = mb.getSize();
  175588. try
  175589. {
  175590. jpeg_read_header (&jpegDecompStruct, TRUE);
  175591. jpeg_calc_output_dimensions (&jpegDecompStruct);
  175592. const int width = jpegDecompStruct.output_width;
  175593. const int height = jpegDecompStruct.output_height;
  175594. jpegDecompStruct.out_color_space = JCS_RGB;
  175595. JSAMPARRAY buffer
  175596. = (*jpegDecompStruct.mem->alloc_sarray) ((j_common_ptr) &jpegDecompStruct,
  175597. JPOOL_IMAGE,
  175598. width * 3, 1);
  175599. if (jpeg_start_decompress (&jpegDecompStruct))
  175600. {
  175601. image = new Image (Image::RGB, width, height, false);
  175602. for (int y = 0; y < height; ++y)
  175603. {
  175604. jpeg_read_scanlines (&jpegDecompStruct, buffer, 1);
  175605. int stride, pixelStride;
  175606. uint8* pixels = image->lockPixelDataReadWrite (0, y, width, 1, stride, pixelStride);
  175607. const uint8* src = *buffer;
  175608. uint8* dest = pixels;
  175609. for (int i = width; --i >= 0;)
  175610. {
  175611. ((PixelRGB*) dest)->setARGB (0, src[0], src[1], src[2]);
  175612. dest += pixelStride;
  175613. src += 3;
  175614. }
  175615. image->releasePixelDataReadWrite (pixels);
  175616. }
  175617. jpeg_finish_decompress (&jpegDecompStruct);
  175618. in.setPosition (((char*) jpegDecompStruct.src->next_input_byte) - (char*) mb.getData());
  175619. }
  175620. jpeg_destroy_decompress (&jpegDecompStruct);
  175621. }
  175622. catch (...)
  175623. {}
  175624. }
  175625. return image;
  175626. }
  175627. static const int bufferSize = 512;
  175628. struct JuceJpegDest : public jpeg_destination_mgr
  175629. {
  175630. OutputStream* output;
  175631. char* buffer;
  175632. };
  175633. static void jpegWriteInit (j_compress_ptr) throw()
  175634. {
  175635. }
  175636. static void jpegWriteTerminate (j_compress_ptr cinfo) throw()
  175637. {
  175638. JuceJpegDest* const dest = (JuceJpegDest*) cinfo->dest;
  175639. const int numToWrite = bufferSize - dest->free_in_buffer;
  175640. dest->output->write (dest->buffer, numToWrite);
  175641. }
  175642. static boolean jpegWriteFlush (j_compress_ptr cinfo) throw()
  175643. {
  175644. JuceJpegDest* const dest = (JuceJpegDest*) cinfo->dest;
  175645. const int numToWrite = bufferSize;
  175646. dest->next_output_byte = (JOCTET*) dest->buffer;
  175647. dest->free_in_buffer = bufferSize;
  175648. return dest->output->write (dest->buffer, numToWrite);
  175649. }
  175650. bool juce_writeJPEGImageToStream (const Image& image,
  175651. OutputStream& out,
  175652. float quality) throw()
  175653. {
  175654. if (image.hasAlphaChannel())
  175655. {
  175656. // this method could fill the background in white and still save the image..
  175657. jassertfalse
  175658. return true;
  175659. }
  175660. struct jpeg_compress_struct jpegCompStruct;
  175661. struct jpeg_error_mgr jerr;
  175662. setupSilentErrorHandler (jerr);
  175663. jpegCompStruct.err = &jerr;
  175664. jpeg_create_compress (&jpegCompStruct);
  175665. JuceJpegDest dest;
  175666. jpegCompStruct.dest = &dest;
  175667. dest.output = &out;
  175668. dest.buffer = (char*) juce_malloc (bufferSize);
  175669. dest.next_output_byte = (JOCTET*) dest.buffer;
  175670. dest.free_in_buffer = bufferSize;
  175671. dest.init_destination = jpegWriteInit;
  175672. dest.empty_output_buffer = jpegWriteFlush;
  175673. dest.term_destination = jpegWriteTerminate;
  175674. jpegCompStruct.image_width = image.getWidth();
  175675. jpegCompStruct.image_height = image.getHeight();
  175676. jpegCompStruct.input_components = 3;
  175677. jpegCompStruct.in_color_space = JCS_RGB;
  175678. jpegCompStruct.write_JFIF_header = 1;
  175679. jpegCompStruct.X_density = 72;
  175680. jpegCompStruct.Y_density = 72;
  175681. jpeg_set_defaults (&jpegCompStruct);
  175682. jpegCompStruct.dct_method = JDCT_FLOAT;
  175683. jpegCompStruct.optimize_coding = 1;
  175684. // jpegCompStruct.smoothing_factor = 10;
  175685. if (quality < 0.0f)
  175686. quality = 0.85f;
  175687. jpeg_set_quality (&jpegCompStruct, jlimit (0, 100, roundFloatToInt (quality * 100.0f)), TRUE);
  175688. jpeg_start_compress (&jpegCompStruct, TRUE);
  175689. const int strideBytes = jpegCompStruct.image_width * jpegCompStruct.input_components;
  175690. JSAMPARRAY buffer = (*jpegCompStruct.mem->alloc_sarray) ((j_common_ptr) &jpegCompStruct,
  175691. JPOOL_IMAGE,
  175692. strideBytes, 1);
  175693. while (jpegCompStruct.next_scanline < jpegCompStruct.image_height)
  175694. {
  175695. int stride, pixelStride;
  175696. const uint8* pixels = image.lockPixelDataReadOnly (0, jpegCompStruct.next_scanline, jpegCompStruct.image_width, 1, stride, pixelStride);
  175697. const uint8* src = pixels;
  175698. uint8* dst = *buffer;
  175699. for (int i = jpegCompStruct.image_width; --i >= 0;)
  175700. {
  175701. *dst++ = ((const PixelRGB*) src)->getRed();
  175702. *dst++ = ((const PixelRGB*) src)->getGreen();
  175703. *dst++ = ((const PixelRGB*) src)->getBlue();
  175704. src += pixelStride;
  175705. }
  175706. jpeg_write_scanlines (&jpegCompStruct, buffer, 1);
  175707. image.releasePixelDataReadOnly (pixels);
  175708. }
  175709. jpeg_finish_compress (&jpegCompStruct);
  175710. jpeg_destroy_compress (&jpegCompStruct);
  175711. juce_free (dest.buffer);
  175712. out.flush();
  175713. return true;
  175714. }
  175715. END_JUCE_NAMESPACE
  175716. /********* End of inlined file: juce_JPEGLoader.cpp *********/
  175717. /********* Start of inlined file: juce_PNGLoader.cpp *********/
  175718. #ifdef _MSC_VER
  175719. #pragma warning (push)
  175720. #pragma warning (disable: 4390 4611)
  175721. #endif
  175722. namespace zlibNamespace
  175723. {
  175724. #if JUCE_INCLUDE_ZLIB_CODE
  175725. #undef OS_CODE
  175726. #undef fdopen
  175727. #undef OS_CODE
  175728. #else
  175729. #include <zlib.h>
  175730. #endif
  175731. }
  175732. namespace pnglibNamespace
  175733. {
  175734. using namespace zlibNamespace;
  175735. #if JUCE_INCLUDE_PNGLIB_CODE
  175736. #if _MSC_VER != 1310
  175737. using ::calloc; // (causes conflict in VS.NET 2003)
  175738. using ::malloc;
  175739. using ::free;
  175740. #endif
  175741. extern "C"
  175742. {
  175743. using ::abs;
  175744. #define PNG_INTERNAL
  175745. #define NO_DUMMY_DECL
  175746. #define PNG_SETJMP_NOT_SUPPORTED
  175747. /********* Start of inlined file: png.h *********/
  175748. /* png.h - header file for PNG reference library
  175749. *
  175750. * libpng version 1.2.21 - October 4, 2007
  175751. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  175752. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  175753. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  175754. *
  175755. * Authors and maintainers:
  175756. * libpng versions 0.71, May 1995, through 0.88, January 1996: Guy Schalnat
  175757. * libpng versions 0.89c, June 1996, through 0.96, May 1997: Andreas Dilger
  175758. * libpng versions 0.97, January 1998, through 1.2.21 - October 4, 2007: Glenn
  175759. * See also "Contributing Authors", below.
  175760. *
  175761. * Note about libpng version numbers:
  175762. *
  175763. * Due to various miscommunications, unforeseen code incompatibilities
  175764. * and occasional factors outside the authors' control, version numbering
  175765. * on the library has not always been consistent and straightforward.
  175766. * The following table summarizes matters since version 0.89c, which was
  175767. * the first widely used release:
  175768. *
  175769. * source png.h png.h shared-lib
  175770. * version string int version
  175771. * ------- ------ ----- ----------
  175772. * 0.89c "1.0 beta 3" 0.89 89 1.0.89
  175773. * 0.90 "1.0 beta 4" 0.90 90 0.90 [should have been 2.0.90]
  175774. * 0.95 "1.0 beta 5" 0.95 95 0.95 [should have been 2.0.95]
  175775. * 0.96 "1.0 beta 6" 0.96 96 0.96 [should have been 2.0.96]
  175776. * 0.97b "1.00.97 beta 7" 1.00.97 97 1.0.1 [should have been 2.0.97]
  175777. * 0.97c 0.97 97 2.0.97
  175778. * 0.98 0.98 98 2.0.98
  175779. * 0.99 0.99 98 2.0.99
  175780. * 0.99a-m 0.99 99 2.0.99
  175781. * 1.00 1.00 100 2.1.0 [100 should be 10000]
  175782. * 1.0.0 (from here on, the 100 2.1.0 [100 should be 10000]
  175783. * 1.0.1 png.h string is 10001 2.1.0
  175784. * 1.0.1a-e identical to the 10002 from here on, the shared library
  175785. * 1.0.2 source version) 10002 is 2.V where V is the source code
  175786. * 1.0.2a-b 10003 version, except as noted.
  175787. * 1.0.3 10003
  175788. * 1.0.3a-d 10004
  175789. * 1.0.4 10004
  175790. * 1.0.4a-f 10005
  175791. * 1.0.5 (+ 2 patches) 10005
  175792. * 1.0.5a-d 10006
  175793. * 1.0.5e-r 10100 (not source compatible)
  175794. * 1.0.5s-v 10006 (not binary compatible)
  175795. * 1.0.6 (+ 3 patches) 10006 (still binary incompatible)
  175796. * 1.0.6d-f 10007 (still binary incompatible)
  175797. * 1.0.6g 10007
  175798. * 1.0.6h 10007 10.6h (testing xy.z so-numbering)
  175799. * 1.0.6i 10007 10.6i
  175800. * 1.0.6j 10007 2.1.0.6j (incompatible with 1.0.0)
  175801. * 1.0.7beta11-14 DLLNUM 10007 2.1.0.7beta11-14 (binary compatible)
  175802. * 1.0.7beta15-18 1 10007 2.1.0.7beta15-18 (binary compatible)
  175803. * 1.0.7rc1-2 1 10007 2.1.0.7rc1-2 (binary compatible)
  175804. * 1.0.7 1 10007 (still compatible)
  175805. * 1.0.8beta1-4 1 10008 2.1.0.8beta1-4
  175806. * 1.0.8rc1 1 10008 2.1.0.8rc1
  175807. * 1.0.8 1 10008 2.1.0.8
  175808. * 1.0.9beta1-6 1 10009 2.1.0.9beta1-6
  175809. * 1.0.9rc1 1 10009 2.1.0.9rc1
  175810. * 1.0.9beta7-10 1 10009 2.1.0.9beta7-10
  175811. * 1.0.9rc2 1 10009 2.1.0.9rc2
  175812. * 1.0.9 1 10009 2.1.0.9
  175813. * 1.0.10beta1 1 10010 2.1.0.10beta1
  175814. * 1.0.10rc1 1 10010 2.1.0.10rc1
  175815. * 1.0.10 1 10010 2.1.0.10
  175816. * 1.0.11beta1-3 1 10011 2.1.0.11beta1-3
  175817. * 1.0.11rc1 1 10011 2.1.0.11rc1
  175818. * 1.0.11 1 10011 2.1.0.11
  175819. * 1.0.12beta1-2 2 10012 2.1.0.12beta1-2
  175820. * 1.0.12rc1 2 10012 2.1.0.12rc1
  175821. * 1.0.12 2 10012 2.1.0.12
  175822. * 1.1.0a-f - 10100 2.1.1.0a-f (branch abandoned)
  175823. * 1.2.0beta1-2 2 10200 2.1.2.0beta1-2
  175824. * 1.2.0beta3-5 3 10200 3.1.2.0beta3-5
  175825. * 1.2.0rc1 3 10200 3.1.2.0rc1
  175826. * 1.2.0 3 10200 3.1.2.0
  175827. * 1.2.1beta1-4 3 10201 3.1.2.1beta1-4
  175828. * 1.2.1rc1-2 3 10201 3.1.2.1rc1-2
  175829. * 1.2.1 3 10201 3.1.2.1
  175830. * 1.2.2beta1-6 12 10202 12.so.0.1.2.2beta1-6
  175831. * 1.0.13beta1 10 10013 10.so.0.1.0.13beta1
  175832. * 1.0.13rc1 10 10013 10.so.0.1.0.13rc1
  175833. * 1.2.2rc1 12 10202 12.so.0.1.2.2rc1
  175834. * 1.0.13 10 10013 10.so.0.1.0.13
  175835. * 1.2.2 12 10202 12.so.0.1.2.2
  175836. * 1.2.3rc1-6 12 10203 12.so.0.1.2.3rc1-6
  175837. * 1.2.3 12 10203 12.so.0.1.2.3
  175838. * 1.2.4beta1-3 13 10204 12.so.0.1.2.4beta1-3
  175839. * 1.0.14rc1 13 10014 10.so.0.1.0.14rc1
  175840. * 1.2.4rc1 13 10204 12.so.0.1.2.4rc1
  175841. * 1.0.14 10 10014 10.so.0.1.0.14
  175842. * 1.2.4 13 10204 12.so.0.1.2.4
  175843. * 1.2.5beta1-2 13 10205 12.so.0.1.2.5beta1-2
  175844. * 1.0.15rc1-3 10 10015 10.so.0.1.0.15rc1-3
  175845. * 1.2.5rc1-3 13 10205 12.so.0.1.2.5rc1-3
  175846. * 1.0.15 10 10015 10.so.0.1.0.15
  175847. * 1.2.5 13 10205 12.so.0.1.2.5
  175848. * 1.2.6beta1-4 13 10206 12.so.0.1.2.6beta1-4
  175849. * 1.0.16 10 10016 10.so.0.1.0.16
  175850. * 1.2.6 13 10206 12.so.0.1.2.6
  175851. * 1.2.7beta1-2 13 10207 12.so.0.1.2.7beta1-2
  175852. * 1.0.17rc1 10 10017 10.so.0.1.0.17rc1
  175853. * 1.2.7rc1 13 10207 12.so.0.1.2.7rc1
  175854. * 1.0.17 10 10017 10.so.0.1.0.17
  175855. * 1.2.7 13 10207 12.so.0.1.2.7
  175856. * 1.2.8beta1-5 13 10208 12.so.0.1.2.8beta1-5
  175857. * 1.0.18rc1-5 10 10018 10.so.0.1.0.18rc1-5
  175858. * 1.2.8rc1-5 13 10208 12.so.0.1.2.8rc1-5
  175859. * 1.0.18 10 10018 10.so.0.1.0.18
  175860. * 1.2.8 13 10208 12.so.0.1.2.8
  175861. * 1.2.9beta1-3 13 10209 12.so.0.1.2.9beta1-3
  175862. * 1.2.9beta4-11 13 10209 12.so.0.9[.0]
  175863. * 1.2.9rc1 13 10209 12.so.0.9[.0]
  175864. * 1.2.9 13 10209 12.so.0.9[.0]
  175865. * 1.2.10beta1-8 13 10210 12.so.0.10[.0]
  175866. * 1.2.10rc1-3 13 10210 12.so.0.10[.0]
  175867. * 1.2.10 13 10210 12.so.0.10[.0]
  175868. * 1.2.11beta1-4 13 10211 12.so.0.11[.0]
  175869. * 1.0.19rc1-5 10 10019 10.so.0.19[.0]
  175870. * 1.2.11rc1-5 13 10211 12.so.0.11[.0]
  175871. * 1.0.19 10 10019 10.so.0.19[.0]
  175872. * 1.2.11 13 10211 12.so.0.11[.0]
  175873. * 1.0.20 10 10020 10.so.0.20[.0]
  175874. * 1.2.12 13 10212 12.so.0.12[.0]
  175875. * 1.2.13beta1 13 10213 12.so.0.13[.0]
  175876. * 1.0.21 10 10021 10.so.0.21[.0]
  175877. * 1.2.13 13 10213 12.so.0.13[.0]
  175878. * 1.2.14beta1-2 13 10214 12.so.0.14[.0]
  175879. * 1.0.22rc1 10 10022 10.so.0.22[.0]
  175880. * 1.2.14rc1 13 10214 12.so.0.14[.0]
  175881. * 1.0.22 10 10022 10.so.0.22[.0]
  175882. * 1.2.14 13 10214 12.so.0.14[.0]
  175883. * 1.2.15beta1-6 13 10215 12.so.0.15[.0]
  175884. * 1.0.23rc1-5 10 10023 10.so.0.23[.0]
  175885. * 1.2.15rc1-5 13 10215 12.so.0.15[.0]
  175886. * 1.0.23 10 10023 10.so.0.23[.0]
  175887. * 1.2.15 13 10215 12.so.0.15[.0]
  175888. * 1.2.16beta1-2 13 10216 12.so.0.16[.0]
  175889. * 1.2.16rc1 13 10216 12.so.0.16[.0]
  175890. * 1.0.24 10 10024 10.so.0.24[.0]
  175891. * 1.2.16 13 10216 12.so.0.16[.0]
  175892. * 1.2.17beta1-2 13 10217 12.so.0.17[.0]
  175893. * 1.0.25rc1 10 10025 10.so.0.25[.0]
  175894. * 1.2.17rc1-3 13 10217 12.so.0.17[.0]
  175895. * 1.0.25 10 10025 10.so.0.25[.0]
  175896. * 1.2.17 13 10217 12.so.0.17[.0]
  175897. * 1.0.26 10 10026 10.so.0.26[.0]
  175898. * 1.2.18 13 10218 12.so.0.18[.0]
  175899. * 1.2.19beta1-31 13 10219 12.so.0.19[.0]
  175900. * 1.0.27rc1-6 10 10027 10.so.0.27[.0]
  175901. * 1.2.19rc1-6 13 10219 12.so.0.19[.0]
  175902. * 1.0.27 10 10027 10.so.0.27[.0]
  175903. * 1.2.19 13 10219 12.so.0.19[.0]
  175904. * 1.2.20beta01-04 13 10220 12.so.0.20[.0]
  175905. * 1.0.28rc1-6 10 10028 10.so.0.28[.0]
  175906. * 1.2.20rc1-6 13 10220 12.so.0.20[.0]
  175907. * 1.0.28 10 10028 10.so.0.28[.0]
  175908. * 1.2.20 13 10220 12.so.0.20[.0]
  175909. * 1.2.21beta1-2 13 10221 12.so.0.21[.0]
  175910. * 1.2.21rc1-3 13 10221 12.so.0.21[.0]
  175911. * 1.0.29 10 10029 10.so.0.29[.0]
  175912. * 1.2.21 13 10221 12.so.0.21[.0]
  175913. *
  175914. * Henceforth the source version will match the shared-library major
  175915. * and minor numbers; the shared-library major version number will be
  175916. * used for changes in backward compatibility, as it is intended. The
  175917. * PNG_LIBPNG_VER macro, which is not used within libpng but is available
  175918. * for applications, is an unsigned integer of the form xyyzz corresponding
  175919. * to the source version x.y.z (leading zeros in y and z). Beta versions
  175920. * were given the previous public release number plus a letter, until
  175921. * version 1.0.6j; from then on they were given the upcoming public
  175922. * release number plus "betaNN" or "rcN".
  175923. *
  175924. * Binary incompatibility exists only when applications make direct access
  175925. * to the info_ptr or png_ptr members through png.h, and the compiled
  175926. * application is loaded with a different version of the library.
  175927. *
  175928. * DLLNUM will change each time there are forward or backward changes
  175929. * in binary compatibility (e.g., when a new feature is added).
  175930. *
  175931. * See libpng.txt or libpng.3 for more information. The PNG specification
  175932. * is available as a W3C Recommendation and as an ISO Specification,
  175933. * <http://www.w3.org/TR/2003/REC-PNG-20031110/
  175934. */
  175935. /*
  175936. * COPYRIGHT NOTICE, DISCLAIMER, and LICENSE:
  175937. *
  175938. * If you modify libpng you may insert additional notices immediately following
  175939. * this sentence.
  175940. *
  175941. * libpng versions 1.2.6, August 15, 2004, through 1.2.21, October 4, 2007, are
  175942. * Copyright (c) 2004, 2006-2007 Glenn Randers-Pehrson, and are
  175943. * distributed according to the same disclaimer and license as libpng-1.2.5
  175944. * with the following individual added to the list of Contributing Authors:
  175945. *
  175946. * Cosmin Truta
  175947. *
  175948. * libpng versions 1.0.7, July 1, 2000, through 1.2.5, October 3, 2002, are
  175949. * Copyright (c) 2000-2002 Glenn Randers-Pehrson, and are
  175950. * distributed according to the same disclaimer and license as libpng-1.0.6
  175951. * with the following individuals added to the list of Contributing Authors:
  175952. *
  175953. * Simon-Pierre Cadieux
  175954. * Eric S. Raymond
  175955. * Gilles Vollant
  175956. *
  175957. * and with the following additions to the disclaimer:
  175958. *
  175959. * There is no warranty against interference with your enjoyment of the
  175960. * library or against infringement. There is no warranty that our
  175961. * efforts or the library will fulfill any of your particular purposes
  175962. * or needs. This library is provided with all faults, and the entire
  175963. * risk of satisfactory quality, performance, accuracy, and effort is with
  175964. * the user.
  175965. *
  175966. * libpng versions 0.97, January 1998, through 1.0.6, March 20, 2000, are
  175967. * Copyright (c) 1998, 1999, 2000 Glenn Randers-Pehrson, and are
  175968. * distributed according to the same disclaimer and license as libpng-0.96,
  175969. * with the following individuals added to the list of Contributing Authors:
  175970. *
  175971. * Tom Lane
  175972. * Glenn Randers-Pehrson
  175973. * Willem van Schaik
  175974. *
  175975. * libpng versions 0.89, June 1996, through 0.96, May 1997, are
  175976. * Copyright (c) 1996, 1997 Andreas Dilger
  175977. * Distributed according to the same disclaimer and license as libpng-0.88,
  175978. * with the following individuals added to the list of Contributing Authors:
  175979. *
  175980. * John Bowler
  175981. * Kevin Bracey
  175982. * Sam Bushell
  175983. * Magnus Holmgren
  175984. * Greg Roelofs
  175985. * Tom Tanner
  175986. *
  175987. * libpng versions 0.5, May 1995, through 0.88, January 1996, are
  175988. * Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.
  175989. *
  175990. * For the purposes of this copyright and license, "Contributing Authors"
  175991. * is defined as the following set of individuals:
  175992. *
  175993. * Andreas Dilger
  175994. * Dave Martindale
  175995. * Guy Eric Schalnat
  175996. * Paul Schmidt
  175997. * Tim Wegner
  175998. *
  175999. * The PNG Reference Library is supplied "AS IS". The Contributing Authors
  176000. * and Group 42, Inc. disclaim all warranties, expressed or implied,
  176001. * including, without limitation, the warranties of merchantability and of
  176002. * fitness for any purpose. The Contributing Authors and Group 42, Inc.
  176003. * assume no liability for direct, indirect, incidental, special, exemplary,
  176004. * or consequential damages, which may result from the use of the PNG
  176005. * Reference Library, even if advised of the possibility of such damage.
  176006. *
  176007. * Permission is hereby granted to use, copy, modify, and distribute this
  176008. * source code, or portions hereof, for any purpose, without fee, subject
  176009. * to the following restrictions:
  176010. *
  176011. * 1. The origin of this source code must not be misrepresented.
  176012. *
  176013. * 2. Altered versions must be plainly marked as such and
  176014. * must not be misrepresented as being the original source.
  176015. *
  176016. * 3. This Copyright notice may not be removed or altered from
  176017. * any source or altered source distribution.
  176018. *
  176019. * The Contributing Authors and Group 42, Inc. specifically permit, without
  176020. * fee, and encourage the use of this source code as a component to
  176021. * supporting the PNG file format in commercial products. If you use this
  176022. * source code in a product, acknowledgment is not required but would be
  176023. * appreciated.
  176024. */
  176025. /*
  176026. * A "png_get_copyright" function is available, for convenient use in "about"
  176027. * boxes and the like:
  176028. *
  176029. * printf("%s",png_get_copyright(NULL));
  176030. *
  176031. * Also, the PNG logo (in PNG format, of course) is supplied in the
  176032. * files "pngbar.png" and "pngbar.jpg (88x31) and "pngnow.png" (98x31).
  176033. */
  176034. /*
  176035. * Libpng is OSI Certified Open Source Software. OSI Certified is a
  176036. * certification mark of the Open Source Initiative.
  176037. */
  176038. /*
  176039. * The contributing authors would like to thank all those who helped
  176040. * with testing, bug fixes, and patience. This wouldn't have been
  176041. * possible without all of you.
  176042. *
  176043. * Thanks to Frank J. T. Wojcik for helping with the documentation.
  176044. */
  176045. /*
  176046. * Y2K compliance in libpng:
  176047. * =========================
  176048. *
  176049. * October 4, 2007
  176050. *
  176051. * Since the PNG Development group is an ad-hoc body, we can't make
  176052. * an official declaration.
  176053. *
  176054. * This is your unofficial assurance that libpng from version 0.71 and
  176055. * upward through 1.2.21 are Y2K compliant. It is my belief that earlier
  176056. * versions were also Y2K compliant.
  176057. *
  176058. * Libpng only has three year fields. One is a 2-byte unsigned integer
  176059. * that will hold years up to 65535. The other two hold the date in text
  176060. * format, and will hold years up to 9999.
  176061. *
  176062. * The integer is
  176063. * "png_uint_16 year" in png_time_struct.
  176064. *
  176065. * The strings are
  176066. * "png_charp time_buffer" in png_struct and
  176067. * "near_time_buffer", which is a local character string in png.c.
  176068. *
  176069. * There are seven time-related functions:
  176070. * png.c: png_convert_to_rfc_1123() in png.c
  176071. * (formerly png_convert_to_rfc_1152() in error)
  176072. * png_convert_from_struct_tm() in pngwrite.c, called in pngwrite.c
  176073. * png_convert_from_time_t() in pngwrite.c
  176074. * png_get_tIME() in pngget.c
  176075. * png_handle_tIME() in pngrutil.c, called in pngread.c
  176076. * png_set_tIME() in pngset.c
  176077. * png_write_tIME() in pngwutil.c, called in pngwrite.c
  176078. *
  176079. * All handle dates properly in a Y2K environment. The
  176080. * png_convert_from_time_t() function calls gmtime() to convert from system
  176081. * clock time, which returns (year - 1900), which we properly convert to
  176082. * the full 4-digit year. There is a possibility that applications using
  176083. * libpng are not passing 4-digit years into the png_convert_to_rfc_1123()
  176084. * function, or that they are incorrectly passing only a 2-digit year
  176085. * instead of "year - 1900" into the png_convert_from_struct_tm() function,
  176086. * but this is not under our control. The libpng documentation has always
  176087. * stated that it works with 4-digit years, and the APIs have been
  176088. * documented as such.
  176089. *
  176090. * The tIME chunk itself is also Y2K compliant. It uses a 2-byte unsigned
  176091. * integer to hold the year, and can hold years as large as 65535.
  176092. *
  176093. * zlib, upon which libpng depends, is also Y2K compliant. It contains
  176094. * no date-related code.
  176095. *
  176096. * Glenn Randers-Pehrson
  176097. * libpng maintainer
  176098. * PNG Development Group
  176099. */
  176100. #ifndef PNG_H
  176101. #define PNG_H
  176102. /* This is not the place to learn how to use libpng. The file libpng.txt
  176103. * describes how to use libpng, and the file example.c summarizes it
  176104. * with some code on which to build. This file is useful for looking
  176105. * at the actual function definitions and structure components.
  176106. */
  176107. /* Version information for png.h - this should match the version in png.c */
  176108. #define PNG_LIBPNG_VER_STRING "1.2.21"
  176109. #define PNG_HEADER_VERSION_STRING \
  176110. " libpng version 1.2.21 - October 4, 2007\n"
  176111. #define PNG_LIBPNG_VER_SONUM 0
  176112. #define PNG_LIBPNG_VER_DLLNUM 13
  176113. /* These should match the first 3 components of PNG_LIBPNG_VER_STRING: */
  176114. #define PNG_LIBPNG_VER_MAJOR 1
  176115. #define PNG_LIBPNG_VER_MINOR 2
  176116. #define PNG_LIBPNG_VER_RELEASE 21
  176117. /* This should match the numeric part of the final component of
  176118. * PNG_LIBPNG_VER_STRING, omitting any leading zero: */
  176119. #define PNG_LIBPNG_VER_BUILD 0
  176120. /* Release Status */
  176121. #define PNG_LIBPNG_BUILD_ALPHA 1
  176122. #define PNG_LIBPNG_BUILD_BETA 2
  176123. #define PNG_LIBPNG_BUILD_RC 3
  176124. #define PNG_LIBPNG_BUILD_STABLE 4
  176125. #define PNG_LIBPNG_BUILD_RELEASE_STATUS_MASK 7
  176126. /* Release-Specific Flags */
  176127. #define PNG_LIBPNG_BUILD_PATCH 8 /* Can be OR'ed with
  176128. PNG_LIBPNG_BUILD_STABLE only */
  176129. #define PNG_LIBPNG_BUILD_PRIVATE 16 /* Cannot be OR'ed with
  176130. PNG_LIBPNG_BUILD_SPECIAL */
  176131. #define PNG_LIBPNG_BUILD_SPECIAL 32 /* Cannot be OR'ed with
  176132. PNG_LIBPNG_BUILD_PRIVATE */
  176133. #define PNG_LIBPNG_BUILD_BASE_TYPE PNG_LIBPNG_BUILD_STABLE
  176134. /* Careful here. At one time, Guy wanted to use 082, but that would be octal.
  176135. * We must not include leading zeros.
  176136. * Versions 0.7 through 1.0.0 were in the range 0 to 100 here (only
  176137. * version 1.0.0 was mis-numbered 100 instead of 10000). From
  176138. * version 1.0.1 it's xxyyzz, where x=major, y=minor, z=release */
  176139. #define PNG_LIBPNG_VER 10221 /* 1.2.21 */
  176140. #ifndef PNG_VERSION_INFO_ONLY
  176141. /* include the compression library's header */
  176142. #endif
  176143. /* include all user configurable info, including optional assembler routines */
  176144. /********* Start of inlined file: pngconf.h *********/
  176145. /* pngconf.h - machine configurable file for libpng
  176146. *
  176147. * libpng version 1.2.21 - October 4, 2007
  176148. * For conditions of distribution and use, see copyright notice in png.h
  176149. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  176150. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  176151. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  176152. */
  176153. /* Any machine specific code is near the front of this file, so if you
  176154. * are configuring libpng for a machine, you may want to read the section
  176155. * starting here down to where it starts to typedef png_color, png_text,
  176156. * and png_info.
  176157. */
  176158. #ifndef PNGCONF_H
  176159. #define PNGCONF_H
  176160. #define PNG_1_2_X
  176161. // These are some Juce config settings that should remove any unnecessary code bloat..
  176162. #define PNG_NO_STDIO 1
  176163. #define PNG_DEBUG 0
  176164. #define PNG_NO_WARNINGS 1
  176165. #define PNG_NO_ERROR_TEXT 1
  176166. #define PNG_NO_ERROR_NUMBERS 1
  176167. #define PNG_NO_USER_MEM 1
  176168. #define PNG_NO_READ_iCCP 1
  176169. #define PNG_NO_READ_UNKNOWN_CHUNKS 1
  176170. #define PNG_NO_READ_USER_CHUNKS 1
  176171. #define PNG_NO_READ_iTXt 1
  176172. #define PNG_NO_READ_sCAL 1
  176173. #define PNG_NO_READ_sPLT 1
  176174. #define png_error(a, b) png_err(a)
  176175. #define png_warning(a, b)
  176176. #define png_chunk_error(a, b) png_err(a)
  176177. #define png_chunk_warning(a, b)
  176178. /*
  176179. * PNG_USER_CONFIG has to be defined on the compiler command line. This
  176180. * includes the resource compiler for Windows DLL configurations.
  176181. */
  176182. #ifdef PNG_USER_CONFIG
  176183. # ifndef PNG_USER_PRIVATEBUILD
  176184. # define PNG_USER_PRIVATEBUILD
  176185. # endif
  176186. #include "pngusr.h"
  176187. #endif
  176188. /* PNG_CONFIGURE_LIBPNG is set by the "configure" script. */
  176189. #ifdef PNG_CONFIGURE_LIBPNG
  176190. #ifdef HAVE_CONFIG_H
  176191. #include "config.h"
  176192. #endif
  176193. #endif
  176194. /*
  176195. * Added at libpng-1.2.8
  176196. *
  176197. * If you create a private DLL you need to define in "pngusr.h" the followings:
  176198. * #define PNG_USER_PRIVATEBUILD <Describes by whom and why this version of
  176199. * the DLL was built>
  176200. * e.g. #define PNG_USER_PRIVATEBUILD "Build by MyCompany for xyz reasons."
  176201. * #define PNG_USER_DLLFNAME_POSTFIX <two-letter postfix that serve to
  176202. * distinguish your DLL from those of the official release. These
  176203. * correspond to the trailing letters that come after the version
  176204. * number and must match your private DLL name>
  176205. * e.g. // private DLL "libpng13gx.dll"
  176206. * #define PNG_USER_DLLFNAME_POSTFIX "gx"
  176207. *
  176208. * The following macros are also at your disposal if you want to complete the
  176209. * DLL VERSIONINFO structure.
  176210. * - PNG_USER_VERSIONINFO_COMMENTS
  176211. * - PNG_USER_VERSIONINFO_COMPANYNAME
  176212. * - PNG_USER_VERSIONINFO_LEGALTRADEMARKS
  176213. */
  176214. #ifdef __STDC__
  176215. #ifdef SPECIALBUILD
  176216. # pragma message("PNG_LIBPNG_SPECIALBUILD (and deprecated SPECIALBUILD)\
  176217. are now LIBPNG reserved macros. Use PNG_USER_PRIVATEBUILD instead.")
  176218. #endif
  176219. #ifdef PRIVATEBUILD
  176220. # pragma message("PRIVATEBUILD is deprecated.\
  176221. Use PNG_USER_PRIVATEBUILD instead.")
  176222. # define PNG_USER_PRIVATEBUILD PRIVATEBUILD
  176223. #endif
  176224. #endif /* __STDC__ */
  176225. #ifndef PNG_VERSION_INFO_ONLY
  176226. /* End of material added to libpng-1.2.8 */
  176227. /* Added at libpng-1.2.19, removed at libpng-1.2.20 because it caused trouble
  176228. Restored at libpng-1.2.21 */
  176229. # define PNG_WARN_UNINITIALIZED_ROW 1
  176230. /* End of material added at libpng-1.2.19/1.2.21 */
  176231. /* This is the size of the compression buffer, and thus the size of
  176232. * an IDAT chunk. Make this whatever size you feel is best for your
  176233. * machine. One of these will be allocated per png_struct. When this
  176234. * is full, it writes the data to the disk, and does some other
  176235. * calculations. Making this an extremely small size will slow
  176236. * the library down, but you may want to experiment to determine
  176237. * where it becomes significant, if you are concerned with memory
  176238. * usage. Note that zlib allocates at least 32Kb also. For readers,
  176239. * this describes the size of the buffer available to read the data in.
  176240. * Unless this gets smaller than the size of a row (compressed),
  176241. * it should not make much difference how big this is.
  176242. */
  176243. #ifndef PNG_ZBUF_SIZE
  176244. # define PNG_ZBUF_SIZE 8192
  176245. #endif
  176246. /* Enable if you want a write-only libpng */
  176247. #ifndef PNG_NO_READ_SUPPORTED
  176248. # define PNG_READ_SUPPORTED
  176249. #endif
  176250. /* Enable if you want a read-only libpng */
  176251. #ifndef PNG_NO_WRITE_SUPPORTED
  176252. # define PNG_WRITE_SUPPORTED
  176253. #endif
  176254. /* Enabled by default in 1.2.0. You can disable this if you don't need to
  176255. support PNGs that are embedded in MNG datastreams */
  176256. #if !defined(PNG_1_0_X) && !defined(PNG_NO_MNG_FEATURES)
  176257. # ifndef PNG_MNG_FEATURES_SUPPORTED
  176258. # define PNG_MNG_FEATURES_SUPPORTED
  176259. # endif
  176260. #endif
  176261. #ifndef PNG_NO_FLOATING_POINT_SUPPORTED
  176262. # ifndef PNG_FLOATING_POINT_SUPPORTED
  176263. # define PNG_FLOATING_POINT_SUPPORTED
  176264. # endif
  176265. #endif
  176266. /* If you are running on a machine where you cannot allocate more
  176267. * than 64K of memory at once, uncomment this. While libpng will not
  176268. * normally need that much memory in a chunk (unless you load up a very
  176269. * large file), zlib needs to know how big of a chunk it can use, and
  176270. * libpng thus makes sure to check any memory allocation to verify it
  176271. * will fit into memory.
  176272. #define PNG_MAX_MALLOC_64K
  176273. */
  176274. #if defined(MAXSEG_64K) && !defined(PNG_MAX_MALLOC_64K)
  176275. # define PNG_MAX_MALLOC_64K
  176276. #endif
  176277. /* Special munging to support doing things the 'cygwin' way:
  176278. * 'Normal' png-on-win32 defines/defaults:
  176279. * PNG_BUILD_DLL -- building dll
  176280. * PNG_USE_DLL -- building an application, linking to dll
  176281. * (no define) -- building static library, or building an
  176282. * application and linking to the static lib
  176283. * 'Cygwin' defines/defaults:
  176284. * PNG_BUILD_DLL -- (ignored) building the dll
  176285. * (no define) -- (ignored) building an application, linking to the dll
  176286. * PNG_STATIC -- (ignored) building the static lib, or building an
  176287. * application that links to the static lib.
  176288. * ALL_STATIC -- (ignored) building various static libs, or building an
  176289. * application that links to the static libs.
  176290. * Thus,
  176291. * a cygwin user should define either PNG_BUILD_DLL or PNG_STATIC, and
  176292. * this bit of #ifdefs will define the 'correct' config variables based on
  176293. * that. If a cygwin user *wants* to define 'PNG_USE_DLL' that's okay, but
  176294. * unnecessary.
  176295. *
  176296. * Also, the precedence order is:
  176297. * ALL_STATIC (since we can't #undef something outside our namespace)
  176298. * PNG_BUILD_DLL
  176299. * PNG_STATIC
  176300. * (nothing) == PNG_USE_DLL
  176301. *
  176302. * CYGWIN (2002-01-20): The preceding is now obsolete. With the advent
  176303. * of auto-import in binutils, we no longer need to worry about
  176304. * __declspec(dllexport) / __declspec(dllimport) and friends. Therefore,
  176305. * we don't need to worry about PNG_STATIC or ALL_STATIC when it comes
  176306. * to __declspec() stuff. However, we DO need to worry about
  176307. * PNG_BUILD_DLL and PNG_STATIC because those change some defaults
  176308. * such as CONSOLE_IO and whether GLOBAL_ARRAYS are allowed.
  176309. */
  176310. #if defined(__CYGWIN__)
  176311. # if defined(ALL_STATIC)
  176312. # if defined(PNG_BUILD_DLL)
  176313. # undef PNG_BUILD_DLL
  176314. # endif
  176315. # if defined(PNG_USE_DLL)
  176316. # undef PNG_USE_DLL
  176317. # endif
  176318. # if defined(PNG_DLL)
  176319. # undef PNG_DLL
  176320. # endif
  176321. # if !defined(PNG_STATIC)
  176322. # define PNG_STATIC
  176323. # endif
  176324. # else
  176325. # if defined (PNG_BUILD_DLL)
  176326. # if defined(PNG_STATIC)
  176327. # undef PNG_STATIC
  176328. # endif
  176329. # if defined(PNG_USE_DLL)
  176330. # undef PNG_USE_DLL
  176331. # endif
  176332. # if !defined(PNG_DLL)
  176333. # define PNG_DLL
  176334. # endif
  176335. # else
  176336. # if defined(PNG_STATIC)
  176337. # if defined(PNG_USE_DLL)
  176338. # undef PNG_USE_DLL
  176339. # endif
  176340. # if defined(PNG_DLL)
  176341. # undef PNG_DLL
  176342. # endif
  176343. # else
  176344. # if !defined(PNG_USE_DLL)
  176345. # define PNG_USE_DLL
  176346. # endif
  176347. # if !defined(PNG_DLL)
  176348. # define PNG_DLL
  176349. # endif
  176350. # endif
  176351. # endif
  176352. # endif
  176353. #endif
  176354. /* This protects us against compilers that run on a windowing system
  176355. * and thus don't have or would rather us not use the stdio types:
  176356. * stdin, stdout, and stderr. The only one currently used is stderr
  176357. * in png_error() and png_warning(). #defining PNG_NO_CONSOLE_IO will
  176358. * prevent these from being compiled and used. #defining PNG_NO_STDIO
  176359. * will also prevent these, plus will prevent the entire set of stdio
  176360. * macros and functions (FILE *, printf, etc.) from being compiled and used,
  176361. * unless (PNG_DEBUG > 0) has been #defined.
  176362. *
  176363. * #define PNG_NO_CONSOLE_IO
  176364. * #define PNG_NO_STDIO
  176365. */
  176366. #if defined(_WIN32_WCE)
  176367. # include <windows.h>
  176368. /* Console I/O functions are not supported on WindowsCE */
  176369. # define PNG_NO_CONSOLE_IO
  176370. # ifdef PNG_DEBUG
  176371. # undef PNG_DEBUG
  176372. # endif
  176373. #endif
  176374. #ifdef PNG_BUILD_DLL
  176375. # ifndef PNG_CONSOLE_IO_SUPPORTED
  176376. # ifndef PNG_NO_CONSOLE_IO
  176377. # define PNG_NO_CONSOLE_IO
  176378. # endif
  176379. # endif
  176380. #endif
  176381. # ifdef PNG_NO_STDIO
  176382. # ifndef PNG_NO_CONSOLE_IO
  176383. # define PNG_NO_CONSOLE_IO
  176384. # endif
  176385. # ifdef PNG_DEBUG
  176386. # if (PNG_DEBUG > 0)
  176387. # include <stdio.h>
  176388. # endif
  176389. # endif
  176390. # else
  176391. # if !defined(_WIN32_WCE)
  176392. /* "stdio.h" functions are not supported on WindowsCE */
  176393. # include <stdio.h>
  176394. # endif
  176395. # endif
  176396. /* This macro protects us against machines that don't have function
  176397. * prototypes (ie K&R style headers). If your compiler does not handle
  176398. * function prototypes, define this macro and use the included ansi2knr.
  176399. * I've always been able to use _NO_PROTO as the indicator, but you may
  176400. * need to drag the empty declaration out in front of here, or change the
  176401. * ifdef to suit your own needs.
  176402. */
  176403. #ifndef PNGARG
  176404. #ifdef OF /* zlib prototype munger */
  176405. # define PNGARG(arglist) OF(arglist)
  176406. #else
  176407. #ifdef _NO_PROTO
  176408. # define PNGARG(arglist) ()
  176409. # ifndef PNG_TYPECAST_NULL
  176410. # define PNG_TYPECAST_NULL
  176411. # endif
  176412. #else
  176413. # define PNGARG(arglist) arglist
  176414. #endif /* _NO_PROTO */
  176415. #endif /* OF */
  176416. #endif /* PNGARG */
  176417. /* Try to determine if we are compiling on a Mac. Note that testing for
  176418. * just __MWERKS__ is not good enough, because the Codewarrior is now used
  176419. * on non-Mac platforms.
  176420. */
  176421. #ifndef MACOS
  176422. # if (defined(__MWERKS__) && defined(macintosh)) || defined(applec) || \
  176423. defined(THINK_C) || defined(__SC__) || defined(TARGET_OS_MAC)
  176424. # define MACOS
  176425. # endif
  176426. #endif
  176427. /* enough people need this for various reasons to include it here */
  176428. #if !defined(MACOS) && !defined(RISCOS) && !defined(_WIN32_WCE)
  176429. # include <sys/types.h>
  176430. #endif
  176431. #if !defined(PNG_SETJMP_NOT_SUPPORTED) && !defined(PNG_NO_SETJMP_SUPPORTED)
  176432. # define PNG_SETJMP_SUPPORTED
  176433. #endif
  176434. #ifdef PNG_SETJMP_SUPPORTED
  176435. /* This is an attempt to force a single setjmp behaviour on Linux. If
  176436. * the X config stuff didn't define _BSD_SOURCE we wouldn't need this.
  176437. */
  176438. # ifdef __linux__
  176439. # ifdef _BSD_SOURCE
  176440. # define PNG_SAVE_BSD_SOURCE
  176441. # undef _BSD_SOURCE
  176442. # endif
  176443. # ifdef _SETJMP_H
  176444. /* If you encounter a compiler error here, see the explanation
  176445. * near the end of INSTALL.
  176446. */
  176447. __png.h__ already includes setjmp.h;
  176448. __dont__ include it again.;
  176449. # endif
  176450. # endif /* __linux__ */
  176451. /* include setjmp.h for error handling */
  176452. # include <setjmp.h>
  176453. # ifdef __linux__
  176454. # ifdef PNG_SAVE_BSD_SOURCE
  176455. # define _BSD_SOURCE
  176456. # undef PNG_SAVE_BSD_SOURCE
  176457. # endif
  176458. # endif /* __linux__ */
  176459. #endif /* PNG_SETJMP_SUPPORTED */
  176460. #ifdef BSD
  176461. #if ! JUCE_MAC
  176462. # include <strings.h>
  176463. #endif
  176464. #else
  176465. # include <string.h>
  176466. #endif
  176467. /* Other defines for things like memory and the like can go here. */
  176468. #ifdef PNG_INTERNAL
  176469. #include <stdlib.h>
  176470. /* The functions exported by PNG_EXTERN are PNG_INTERNAL functions, which
  176471. * aren't usually used outside the library (as far as I know), so it is
  176472. * debatable if they should be exported at all. In the future, when it is
  176473. * possible to have run-time registry of chunk-handling functions, some of
  176474. * these will be made available again.
  176475. #define PNG_EXTERN extern
  176476. */
  176477. #define PNG_EXTERN
  176478. /* Other defines specific to compilers can go here. Try to keep
  176479. * them inside an appropriate ifdef/endif pair for portability.
  176480. */
  176481. #if defined(PNG_FLOATING_POINT_SUPPORTED)
  176482. # if defined(MACOS)
  176483. /* We need to check that <math.h> hasn't already been included earlier
  176484. * as it seems it doesn't agree with <fp.h>, yet we should really use
  176485. * <fp.h> if possible.
  176486. */
  176487. # if !defined(__MATH_H__) && !defined(__MATH_H) && !defined(__cmath__)
  176488. # include <fp.h>
  176489. # endif
  176490. # else
  176491. # include <math.h>
  176492. # endif
  176493. # if defined(_AMIGA) && defined(__SASC) && defined(_M68881)
  176494. /* Amiga SAS/C: We must include builtin FPU functions when compiling using
  176495. * MATH=68881
  176496. */
  176497. # include <m68881.h>
  176498. # endif
  176499. #endif
  176500. /* Codewarrior on NT has linking problems without this. */
  176501. #if (defined(__MWERKS__) && defined(WIN32)) || defined(__STDC__)
  176502. # define PNG_ALWAYS_EXTERN
  176503. #endif
  176504. /* This provides the non-ANSI (far) memory allocation routines. */
  176505. #if defined(__TURBOC__) && defined(__MSDOS__)
  176506. # include <mem.h>
  176507. # include <alloc.h>
  176508. #endif
  176509. /* I have no idea why is this necessary... */
  176510. #if defined(_MSC_VER) && (defined(WIN32) || defined(_Windows) || \
  176511. defined(_WINDOWS) || defined(_WIN32) || defined(__WIN32__))
  176512. # include <malloc.h>
  176513. #endif
  176514. /* This controls how fine the dithering gets. As this allocates
  176515. * a largish chunk of memory (32K), those who are not as concerned
  176516. * with dithering quality can decrease some or all of these.
  176517. */
  176518. #ifndef PNG_DITHER_RED_BITS
  176519. # define PNG_DITHER_RED_BITS 5
  176520. #endif
  176521. #ifndef PNG_DITHER_GREEN_BITS
  176522. # define PNG_DITHER_GREEN_BITS 5
  176523. #endif
  176524. #ifndef PNG_DITHER_BLUE_BITS
  176525. # define PNG_DITHER_BLUE_BITS 5
  176526. #endif
  176527. /* This controls how fine the gamma correction becomes when you
  176528. * are only interested in 8 bits anyway. Increasing this value
  176529. * results in more memory being used, and more pow() functions
  176530. * being called to fill in the gamma tables. Don't set this value
  176531. * less then 8, and even that may not work (I haven't tested it).
  176532. */
  176533. #ifndef PNG_MAX_GAMMA_8
  176534. # define PNG_MAX_GAMMA_8 11
  176535. #endif
  176536. /* This controls how much a difference in gamma we can tolerate before
  176537. * we actually start doing gamma conversion.
  176538. */
  176539. #ifndef PNG_GAMMA_THRESHOLD
  176540. # define PNG_GAMMA_THRESHOLD 0.05
  176541. #endif
  176542. #endif /* PNG_INTERNAL */
  176543. /* The following uses const char * instead of char * for error
  176544. * and warning message functions, so some compilers won't complain.
  176545. * If you do not want to use const, define PNG_NO_CONST here.
  176546. */
  176547. #ifndef PNG_NO_CONST
  176548. # define PNG_CONST const
  176549. #else
  176550. # define PNG_CONST
  176551. #endif
  176552. /* The following defines give you the ability to remove code from the
  176553. * library that you will not be using. I wish I could figure out how to
  176554. * automate this, but I can't do that without making it seriously hard
  176555. * on the users. So if you are not using an ability, change the #define
  176556. * to and #undef, and that part of the library will not be compiled. If
  176557. * your linker can't find a function, you may want to make sure the
  176558. * ability is defined here. Some of these depend upon some others being
  176559. * defined. I haven't figured out all the interactions here, so you may
  176560. * have to experiment awhile to get everything to compile. If you are
  176561. * creating or using a shared library, you probably shouldn't touch this,
  176562. * as it will affect the size of the structures, and this will cause bad
  176563. * things to happen if the library and/or application ever change.
  176564. */
  176565. /* Any features you will not be using can be undef'ed here */
  176566. /* GR-P, 0.96a: Set "*TRANSFORMS_SUPPORTED as default but allow user
  176567. * to turn it off with "*TRANSFORMS_NOT_SUPPORTED" or *PNG_NO_*_TRANSFORMS
  176568. * on the compile line, then pick and choose which ones to define without
  176569. * having to edit this file. It is safe to use the *TRANSFORMS_NOT_SUPPORTED
  176570. * if you only want to have a png-compliant reader/writer but don't need
  176571. * any of the extra transformations. This saves about 80 kbytes in a
  176572. * typical installation of the library. (PNG_NO_* form added in version
  176573. * 1.0.1c, for consistency)
  176574. */
  176575. /* The size of the png_text structure changed in libpng-1.0.6 when
  176576. * iTXt support was added. iTXt support was turned off by default through
  176577. * libpng-1.2.x, to support old apps that malloc the png_text structure
  176578. * instead of calling png_set_text() and letting libpng malloc it. It
  176579. * was turned on by default in libpng-1.3.0.
  176580. */
  176581. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  176582. # ifndef PNG_NO_iTXt_SUPPORTED
  176583. # define PNG_NO_iTXt_SUPPORTED
  176584. # endif
  176585. # ifndef PNG_NO_READ_iTXt
  176586. # define PNG_NO_READ_iTXt
  176587. # endif
  176588. # ifndef PNG_NO_WRITE_iTXt
  176589. # define PNG_NO_WRITE_iTXt
  176590. # endif
  176591. #endif
  176592. #if !defined(PNG_NO_iTXt_SUPPORTED)
  176593. # if !defined(PNG_READ_iTXt_SUPPORTED) && !defined(PNG_NO_READ_iTXt)
  176594. # define PNG_READ_iTXt
  176595. # endif
  176596. # if !defined(PNG_WRITE_iTXt_SUPPORTED) && !defined(PNG_NO_WRITE_iTXt)
  176597. # define PNG_WRITE_iTXt
  176598. # endif
  176599. #endif
  176600. /* The following support, added after version 1.0.0, can be turned off here en
  176601. * masse by defining PNG_LEGACY_SUPPORTED in case you need binary compatibility
  176602. * with old applications that require the length of png_struct and png_info
  176603. * to remain unchanged.
  176604. */
  176605. #ifdef PNG_LEGACY_SUPPORTED
  176606. # define PNG_NO_FREE_ME
  176607. # define PNG_NO_READ_UNKNOWN_CHUNKS
  176608. # define PNG_NO_WRITE_UNKNOWN_CHUNKS
  176609. # define PNG_NO_READ_USER_CHUNKS
  176610. # define PNG_NO_READ_iCCP
  176611. # define PNG_NO_WRITE_iCCP
  176612. # define PNG_NO_READ_iTXt
  176613. # define PNG_NO_WRITE_iTXt
  176614. # define PNG_NO_READ_sCAL
  176615. # define PNG_NO_WRITE_sCAL
  176616. # define PNG_NO_READ_sPLT
  176617. # define PNG_NO_WRITE_sPLT
  176618. # define PNG_NO_INFO_IMAGE
  176619. # define PNG_NO_READ_RGB_TO_GRAY
  176620. # define PNG_NO_READ_USER_TRANSFORM
  176621. # define PNG_NO_WRITE_USER_TRANSFORM
  176622. # define PNG_NO_USER_MEM
  176623. # define PNG_NO_READ_EMPTY_PLTE
  176624. # define PNG_NO_MNG_FEATURES
  176625. # define PNG_NO_FIXED_POINT_SUPPORTED
  176626. #endif
  176627. /* Ignore attempt to turn off both floating and fixed point support */
  176628. #if !defined(PNG_FLOATING_POINT_SUPPORTED) || \
  176629. !defined(PNG_NO_FIXED_POINT_SUPPORTED)
  176630. # define PNG_FIXED_POINT_SUPPORTED
  176631. #endif
  176632. #ifndef PNG_NO_FREE_ME
  176633. # define PNG_FREE_ME_SUPPORTED
  176634. #endif
  176635. #if defined(PNG_READ_SUPPORTED)
  176636. #if !defined(PNG_READ_TRANSFORMS_NOT_SUPPORTED) && \
  176637. !defined(PNG_NO_READ_TRANSFORMS)
  176638. # define PNG_READ_TRANSFORMS_SUPPORTED
  176639. #endif
  176640. #ifdef PNG_READ_TRANSFORMS_SUPPORTED
  176641. # ifndef PNG_NO_READ_EXPAND
  176642. # define PNG_READ_EXPAND_SUPPORTED
  176643. # endif
  176644. # ifndef PNG_NO_READ_SHIFT
  176645. # define PNG_READ_SHIFT_SUPPORTED
  176646. # endif
  176647. # ifndef PNG_NO_READ_PACK
  176648. # define PNG_READ_PACK_SUPPORTED
  176649. # endif
  176650. # ifndef PNG_NO_READ_BGR
  176651. # define PNG_READ_BGR_SUPPORTED
  176652. # endif
  176653. # ifndef PNG_NO_READ_SWAP
  176654. # define PNG_READ_SWAP_SUPPORTED
  176655. # endif
  176656. # ifndef PNG_NO_READ_PACKSWAP
  176657. # define PNG_READ_PACKSWAP_SUPPORTED
  176658. # endif
  176659. # ifndef PNG_NO_READ_INVERT
  176660. # define PNG_READ_INVERT_SUPPORTED
  176661. # endif
  176662. # ifndef PNG_NO_READ_DITHER
  176663. # define PNG_READ_DITHER_SUPPORTED
  176664. # endif
  176665. # ifndef PNG_NO_READ_BACKGROUND
  176666. # define PNG_READ_BACKGROUND_SUPPORTED
  176667. # endif
  176668. # ifndef PNG_NO_READ_16_TO_8
  176669. # define PNG_READ_16_TO_8_SUPPORTED
  176670. # endif
  176671. # ifndef PNG_NO_READ_FILLER
  176672. # define PNG_READ_FILLER_SUPPORTED
  176673. # endif
  176674. # ifndef PNG_NO_READ_GAMMA
  176675. # define PNG_READ_GAMMA_SUPPORTED
  176676. # endif
  176677. # ifndef PNG_NO_READ_GRAY_TO_RGB
  176678. # define PNG_READ_GRAY_TO_RGB_SUPPORTED
  176679. # endif
  176680. # ifndef PNG_NO_READ_SWAP_ALPHA
  176681. # define PNG_READ_SWAP_ALPHA_SUPPORTED
  176682. # endif
  176683. # ifndef PNG_NO_READ_INVERT_ALPHA
  176684. # define PNG_READ_INVERT_ALPHA_SUPPORTED
  176685. # endif
  176686. # ifndef PNG_NO_READ_STRIP_ALPHA
  176687. # define PNG_READ_STRIP_ALPHA_SUPPORTED
  176688. # endif
  176689. # ifndef PNG_NO_READ_USER_TRANSFORM
  176690. # define PNG_READ_USER_TRANSFORM_SUPPORTED
  176691. # endif
  176692. # ifndef PNG_NO_READ_RGB_TO_GRAY
  176693. # define PNG_READ_RGB_TO_GRAY_SUPPORTED
  176694. # endif
  176695. #endif /* PNG_READ_TRANSFORMS_SUPPORTED */
  176696. #if !defined(PNG_NO_PROGRESSIVE_READ) && \
  176697. !defined(PNG_PROGRESSIVE_READ_SUPPORTED) /* if you don't do progressive */
  176698. # define PNG_PROGRESSIVE_READ_SUPPORTED /* reading. This is not talking */
  176699. #endif /* about interlacing capability! You'll */
  176700. /* still have interlacing unless you change the following line: */
  176701. #define PNG_READ_INTERLACING_SUPPORTED /* required in PNG-compliant decoders */
  176702. #ifndef PNG_NO_READ_COMPOSITE_NODIV
  176703. # ifndef PNG_NO_READ_COMPOSITED_NODIV /* libpng-1.0.x misspelling */
  176704. # define PNG_READ_COMPOSITE_NODIV_SUPPORTED /* well tested on Intel, SGI */
  176705. # endif
  176706. #endif
  176707. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  176708. /* Deprecated, will be removed from version 2.0.0.
  176709. Use PNG_MNG_FEATURES_SUPPORTED instead. */
  176710. #ifndef PNG_NO_READ_EMPTY_PLTE
  176711. # define PNG_READ_EMPTY_PLTE_SUPPORTED
  176712. #endif
  176713. #endif
  176714. #endif /* PNG_READ_SUPPORTED */
  176715. #if defined(PNG_WRITE_SUPPORTED)
  176716. # if !defined(PNG_WRITE_TRANSFORMS_NOT_SUPPORTED) && \
  176717. !defined(PNG_NO_WRITE_TRANSFORMS)
  176718. # define PNG_WRITE_TRANSFORMS_SUPPORTED
  176719. #endif
  176720. #ifdef PNG_WRITE_TRANSFORMS_SUPPORTED
  176721. # ifndef PNG_NO_WRITE_SHIFT
  176722. # define PNG_WRITE_SHIFT_SUPPORTED
  176723. # endif
  176724. # ifndef PNG_NO_WRITE_PACK
  176725. # define PNG_WRITE_PACK_SUPPORTED
  176726. # endif
  176727. # ifndef PNG_NO_WRITE_BGR
  176728. # define PNG_WRITE_BGR_SUPPORTED
  176729. # endif
  176730. # ifndef PNG_NO_WRITE_SWAP
  176731. # define PNG_WRITE_SWAP_SUPPORTED
  176732. # endif
  176733. # ifndef PNG_NO_WRITE_PACKSWAP
  176734. # define PNG_WRITE_PACKSWAP_SUPPORTED
  176735. # endif
  176736. # ifndef PNG_NO_WRITE_INVERT
  176737. # define PNG_WRITE_INVERT_SUPPORTED
  176738. # endif
  176739. # ifndef PNG_NO_WRITE_FILLER
  176740. # define PNG_WRITE_FILLER_SUPPORTED /* same as WRITE_STRIP_ALPHA */
  176741. # endif
  176742. # ifndef PNG_NO_WRITE_SWAP_ALPHA
  176743. # define PNG_WRITE_SWAP_ALPHA_SUPPORTED
  176744. # endif
  176745. # ifndef PNG_NO_WRITE_INVERT_ALPHA
  176746. # define PNG_WRITE_INVERT_ALPHA_SUPPORTED
  176747. # endif
  176748. # ifndef PNG_NO_WRITE_USER_TRANSFORM
  176749. # define PNG_WRITE_USER_TRANSFORM_SUPPORTED
  176750. # endif
  176751. #endif /* PNG_WRITE_TRANSFORMS_SUPPORTED */
  176752. #if !defined(PNG_NO_WRITE_INTERLACING_SUPPORTED) && \
  176753. !defined(PNG_WRITE_INTERLACING_SUPPORTED)
  176754. #define PNG_WRITE_INTERLACING_SUPPORTED /* not required for PNG-compliant
  176755. encoders, but can cause trouble
  176756. if left undefined */
  176757. #endif
  176758. #if !defined(PNG_NO_WRITE_WEIGHTED_FILTER) && \
  176759. !defined(PNG_WRITE_WEIGHTED_FILTER) && \
  176760. defined(PNG_FLOATING_POINT_SUPPORTED)
  176761. # define PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
  176762. #endif
  176763. #ifndef PNG_NO_WRITE_FLUSH
  176764. # define PNG_WRITE_FLUSH_SUPPORTED
  176765. #endif
  176766. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  176767. /* Deprecated, see PNG_MNG_FEATURES_SUPPORTED, above */
  176768. #ifndef PNG_NO_WRITE_EMPTY_PLTE
  176769. # define PNG_WRITE_EMPTY_PLTE_SUPPORTED
  176770. #endif
  176771. #endif
  176772. #endif /* PNG_WRITE_SUPPORTED */
  176773. #ifndef PNG_1_0_X
  176774. # ifndef PNG_NO_ERROR_NUMBERS
  176775. # define PNG_ERROR_NUMBERS_SUPPORTED
  176776. # endif
  176777. #endif /* PNG_1_0_X */
  176778. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  176779. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  176780. # ifndef PNG_NO_USER_TRANSFORM_PTR
  176781. # define PNG_USER_TRANSFORM_PTR_SUPPORTED
  176782. # endif
  176783. #endif
  176784. #ifndef PNG_NO_STDIO
  176785. # define PNG_TIME_RFC1123_SUPPORTED
  176786. #endif
  176787. /* This adds extra functions in pngget.c for accessing data from the
  176788. * info pointer (added in version 0.99)
  176789. * png_get_image_width()
  176790. * png_get_image_height()
  176791. * png_get_bit_depth()
  176792. * png_get_color_type()
  176793. * png_get_compression_type()
  176794. * png_get_filter_type()
  176795. * png_get_interlace_type()
  176796. * png_get_pixel_aspect_ratio()
  176797. * png_get_pixels_per_meter()
  176798. * png_get_x_offset_pixels()
  176799. * png_get_y_offset_pixels()
  176800. * png_get_x_offset_microns()
  176801. * png_get_y_offset_microns()
  176802. */
  176803. #if !defined(PNG_NO_EASY_ACCESS) && !defined(PNG_EASY_ACCESS_SUPPORTED)
  176804. # define PNG_EASY_ACCESS_SUPPORTED
  176805. #endif
  176806. /* PNG_ASSEMBLER_CODE was enabled by default in version 1.2.0
  176807. * and removed from version 1.2.20. The following will be removed
  176808. * from libpng-1.4.0
  176809. */
  176810. #if defined(PNG_READ_SUPPORTED) && !defined(PNG_NO_OPTIMIZED_CODE)
  176811. # ifndef PNG_OPTIMIZED_CODE_SUPPORTED
  176812. # define PNG_OPTIMIZED_CODE_SUPPORTED
  176813. # endif
  176814. #endif
  176815. #if defined(PNG_READ_SUPPORTED) && !defined(PNG_NO_ASSEMBLER_CODE)
  176816. # ifndef PNG_ASSEMBLER_CODE_SUPPORTED
  176817. # define PNG_ASSEMBLER_CODE_SUPPORTED
  176818. # endif
  176819. # if defined(__GNUC__) && defined(__x86_64__) && (__GNUC__ < 4)
  176820. /* work around 64-bit gcc compiler bugs in gcc-3.x */
  176821. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  176822. # define PNG_NO_MMX_CODE
  176823. # endif
  176824. # endif
  176825. # if defined(__APPLE__)
  176826. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  176827. # define PNG_NO_MMX_CODE
  176828. # endif
  176829. # endif
  176830. # if (defined(__MWERKS__) && ((__MWERKS__ < 0x0900) || macintosh))
  176831. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  176832. # define PNG_NO_MMX_CODE
  176833. # endif
  176834. # endif
  176835. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  176836. # define PNG_MMX_CODE_SUPPORTED
  176837. # endif
  176838. #endif
  176839. /* end of obsolete code to be removed from libpng-1.4.0 */
  176840. #if !defined(PNG_1_0_X)
  176841. #if !defined(PNG_NO_USER_MEM) && !defined(PNG_USER_MEM_SUPPORTED)
  176842. # define PNG_USER_MEM_SUPPORTED
  176843. #endif
  176844. #endif /* PNG_1_0_X */
  176845. /* Added at libpng-1.2.6 */
  176846. #if !defined(PNG_1_0_X)
  176847. #ifndef PNG_SET_USER_LIMITS_SUPPORTED
  176848. #if !defined(PNG_NO_SET_USER_LIMITS) && !defined(PNG_SET_USER_LIMITS_SUPPORTED)
  176849. # define PNG_SET_USER_LIMITS_SUPPORTED
  176850. #endif
  176851. #endif
  176852. #endif /* PNG_1_0_X */
  176853. /* Added at libpng-1.0.16 and 1.2.6. To accept all valid PNGS no matter
  176854. * how large, set these limits to 0x7fffffffL
  176855. */
  176856. #ifndef PNG_USER_WIDTH_MAX
  176857. # define PNG_USER_WIDTH_MAX 1000000L
  176858. #endif
  176859. #ifndef PNG_USER_HEIGHT_MAX
  176860. # define PNG_USER_HEIGHT_MAX 1000000L
  176861. #endif
  176862. /* These are currently experimental features, define them if you want */
  176863. /* very little testing */
  176864. /*
  176865. #ifdef PNG_READ_SUPPORTED
  176866. # ifndef PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED
  176867. # define PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED
  176868. # endif
  176869. #endif
  176870. */
  176871. /* This is only for PowerPC big-endian and 680x0 systems */
  176872. /* some testing */
  176873. /*
  176874. #ifndef PNG_READ_BIG_ENDIAN_SUPPORTED
  176875. # define PNG_READ_BIG_ENDIAN_SUPPORTED
  176876. #endif
  176877. */
  176878. /* Buggy compilers (e.g., gcc 2.7.2.2) need this */
  176879. /*
  176880. #define PNG_NO_POINTER_INDEXING
  176881. */
  176882. /* These functions are turned off by default, as they will be phased out. */
  176883. /*
  176884. #define PNG_USELESS_TESTS_SUPPORTED
  176885. #define PNG_CORRECT_PALETTE_SUPPORTED
  176886. */
  176887. /* Any chunks you are not interested in, you can undef here. The
  176888. * ones that allocate memory may be expecially important (hIST,
  176889. * tEXt, zTXt, tRNS, pCAL). Others will just save time and make png_info
  176890. * a bit smaller.
  176891. */
  176892. #if defined(PNG_READ_SUPPORTED) && \
  176893. !defined(PNG_READ_ANCILLARY_CHUNKS_NOT_SUPPORTED) && \
  176894. !defined(PNG_NO_READ_ANCILLARY_CHUNKS)
  176895. # define PNG_READ_ANCILLARY_CHUNKS_SUPPORTED
  176896. #endif
  176897. #if defined(PNG_WRITE_SUPPORTED) && \
  176898. !defined(PNG_WRITE_ANCILLARY_CHUNKS_NOT_SUPPORTED) && \
  176899. !defined(PNG_NO_WRITE_ANCILLARY_CHUNKS)
  176900. # define PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED
  176901. #endif
  176902. #ifdef PNG_READ_ANCILLARY_CHUNKS_SUPPORTED
  176903. #ifdef PNG_NO_READ_TEXT
  176904. # define PNG_NO_READ_iTXt
  176905. # define PNG_NO_READ_tEXt
  176906. # define PNG_NO_READ_zTXt
  176907. #endif
  176908. #ifndef PNG_NO_READ_bKGD
  176909. # define PNG_READ_bKGD_SUPPORTED
  176910. # define PNG_bKGD_SUPPORTED
  176911. #endif
  176912. #ifndef PNG_NO_READ_cHRM
  176913. # define PNG_READ_cHRM_SUPPORTED
  176914. # define PNG_cHRM_SUPPORTED
  176915. #endif
  176916. #ifndef PNG_NO_READ_gAMA
  176917. # define PNG_READ_gAMA_SUPPORTED
  176918. # define PNG_gAMA_SUPPORTED
  176919. #endif
  176920. #ifndef PNG_NO_READ_hIST
  176921. # define PNG_READ_hIST_SUPPORTED
  176922. # define PNG_hIST_SUPPORTED
  176923. #endif
  176924. #ifndef PNG_NO_READ_iCCP
  176925. # define PNG_READ_iCCP_SUPPORTED
  176926. # define PNG_iCCP_SUPPORTED
  176927. #endif
  176928. #ifndef PNG_NO_READ_iTXt
  176929. # ifndef PNG_READ_iTXt_SUPPORTED
  176930. # define PNG_READ_iTXt_SUPPORTED
  176931. # endif
  176932. # ifndef PNG_iTXt_SUPPORTED
  176933. # define PNG_iTXt_SUPPORTED
  176934. # endif
  176935. #endif
  176936. #ifndef PNG_NO_READ_oFFs
  176937. # define PNG_READ_oFFs_SUPPORTED
  176938. # define PNG_oFFs_SUPPORTED
  176939. #endif
  176940. #ifndef PNG_NO_READ_pCAL
  176941. # define PNG_READ_pCAL_SUPPORTED
  176942. # define PNG_pCAL_SUPPORTED
  176943. #endif
  176944. #ifndef PNG_NO_READ_sCAL
  176945. # define PNG_READ_sCAL_SUPPORTED
  176946. # define PNG_sCAL_SUPPORTED
  176947. #endif
  176948. #ifndef PNG_NO_READ_pHYs
  176949. # define PNG_READ_pHYs_SUPPORTED
  176950. # define PNG_pHYs_SUPPORTED
  176951. #endif
  176952. #ifndef PNG_NO_READ_sBIT
  176953. # define PNG_READ_sBIT_SUPPORTED
  176954. # define PNG_sBIT_SUPPORTED
  176955. #endif
  176956. #ifndef PNG_NO_READ_sPLT
  176957. # define PNG_READ_sPLT_SUPPORTED
  176958. # define PNG_sPLT_SUPPORTED
  176959. #endif
  176960. #ifndef PNG_NO_READ_sRGB
  176961. # define PNG_READ_sRGB_SUPPORTED
  176962. # define PNG_sRGB_SUPPORTED
  176963. #endif
  176964. #ifndef PNG_NO_READ_tEXt
  176965. # define PNG_READ_tEXt_SUPPORTED
  176966. # define PNG_tEXt_SUPPORTED
  176967. #endif
  176968. #ifndef PNG_NO_READ_tIME
  176969. # define PNG_READ_tIME_SUPPORTED
  176970. # define PNG_tIME_SUPPORTED
  176971. #endif
  176972. #ifndef PNG_NO_READ_tRNS
  176973. # define PNG_READ_tRNS_SUPPORTED
  176974. # define PNG_tRNS_SUPPORTED
  176975. #endif
  176976. #ifndef PNG_NO_READ_zTXt
  176977. # define PNG_READ_zTXt_SUPPORTED
  176978. # define PNG_zTXt_SUPPORTED
  176979. #endif
  176980. #ifndef PNG_NO_READ_UNKNOWN_CHUNKS
  176981. # define PNG_READ_UNKNOWN_CHUNKS_SUPPORTED
  176982. # ifndef PNG_UNKNOWN_CHUNKS_SUPPORTED
  176983. # define PNG_UNKNOWN_CHUNKS_SUPPORTED
  176984. # endif
  176985. # ifndef PNG_NO_HANDLE_AS_UNKNOWN
  176986. # define PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  176987. # endif
  176988. #endif
  176989. #if !defined(PNG_NO_READ_USER_CHUNKS) && \
  176990. defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  176991. # define PNG_READ_USER_CHUNKS_SUPPORTED
  176992. # define PNG_USER_CHUNKS_SUPPORTED
  176993. # ifdef PNG_NO_READ_UNKNOWN_CHUNKS
  176994. # undef PNG_NO_READ_UNKNOWN_CHUNKS
  176995. # endif
  176996. # ifdef PNG_NO_HANDLE_AS_UNKNOWN
  176997. # undef PNG_NO_HANDLE_AS_UNKNOWN
  176998. # endif
  176999. #endif
  177000. #ifndef PNG_NO_READ_OPT_PLTE
  177001. # define PNG_READ_OPT_PLTE_SUPPORTED /* only affects support of the */
  177002. #endif /* optional PLTE chunk in RGB and RGBA images */
  177003. #if defined(PNG_READ_iTXt_SUPPORTED) || defined(PNG_READ_tEXt_SUPPORTED) || \
  177004. defined(PNG_READ_zTXt_SUPPORTED)
  177005. # define PNG_READ_TEXT_SUPPORTED
  177006. # define PNG_TEXT_SUPPORTED
  177007. #endif
  177008. #endif /* PNG_READ_ANCILLARY_CHUNKS_SUPPORTED */
  177009. #ifdef PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED
  177010. #ifdef PNG_NO_WRITE_TEXT
  177011. # define PNG_NO_WRITE_iTXt
  177012. # define PNG_NO_WRITE_tEXt
  177013. # define PNG_NO_WRITE_zTXt
  177014. #endif
  177015. #ifndef PNG_NO_WRITE_bKGD
  177016. # define PNG_WRITE_bKGD_SUPPORTED
  177017. # ifndef PNG_bKGD_SUPPORTED
  177018. # define PNG_bKGD_SUPPORTED
  177019. # endif
  177020. #endif
  177021. #ifndef PNG_NO_WRITE_cHRM
  177022. # define PNG_WRITE_cHRM_SUPPORTED
  177023. # ifndef PNG_cHRM_SUPPORTED
  177024. # define PNG_cHRM_SUPPORTED
  177025. # endif
  177026. #endif
  177027. #ifndef PNG_NO_WRITE_gAMA
  177028. # define PNG_WRITE_gAMA_SUPPORTED
  177029. # ifndef PNG_gAMA_SUPPORTED
  177030. # define PNG_gAMA_SUPPORTED
  177031. # endif
  177032. #endif
  177033. #ifndef PNG_NO_WRITE_hIST
  177034. # define PNG_WRITE_hIST_SUPPORTED
  177035. # ifndef PNG_hIST_SUPPORTED
  177036. # define PNG_hIST_SUPPORTED
  177037. # endif
  177038. #endif
  177039. #ifndef PNG_NO_WRITE_iCCP
  177040. # define PNG_WRITE_iCCP_SUPPORTED
  177041. # ifndef PNG_iCCP_SUPPORTED
  177042. # define PNG_iCCP_SUPPORTED
  177043. # endif
  177044. #endif
  177045. #ifndef PNG_NO_WRITE_iTXt
  177046. # ifndef PNG_WRITE_iTXt_SUPPORTED
  177047. # define PNG_WRITE_iTXt_SUPPORTED
  177048. # endif
  177049. # ifndef PNG_iTXt_SUPPORTED
  177050. # define PNG_iTXt_SUPPORTED
  177051. # endif
  177052. #endif
  177053. #ifndef PNG_NO_WRITE_oFFs
  177054. # define PNG_WRITE_oFFs_SUPPORTED
  177055. # ifndef PNG_oFFs_SUPPORTED
  177056. # define PNG_oFFs_SUPPORTED
  177057. # endif
  177058. #endif
  177059. #ifndef PNG_NO_WRITE_pCAL
  177060. # define PNG_WRITE_pCAL_SUPPORTED
  177061. # ifndef PNG_pCAL_SUPPORTED
  177062. # define PNG_pCAL_SUPPORTED
  177063. # endif
  177064. #endif
  177065. #ifndef PNG_NO_WRITE_sCAL
  177066. # define PNG_WRITE_sCAL_SUPPORTED
  177067. # ifndef PNG_sCAL_SUPPORTED
  177068. # define PNG_sCAL_SUPPORTED
  177069. # endif
  177070. #endif
  177071. #ifndef PNG_NO_WRITE_pHYs
  177072. # define PNG_WRITE_pHYs_SUPPORTED
  177073. # ifndef PNG_pHYs_SUPPORTED
  177074. # define PNG_pHYs_SUPPORTED
  177075. # endif
  177076. #endif
  177077. #ifndef PNG_NO_WRITE_sBIT
  177078. # define PNG_WRITE_sBIT_SUPPORTED
  177079. # ifndef PNG_sBIT_SUPPORTED
  177080. # define PNG_sBIT_SUPPORTED
  177081. # endif
  177082. #endif
  177083. #ifndef PNG_NO_WRITE_sPLT
  177084. # define PNG_WRITE_sPLT_SUPPORTED
  177085. # ifndef PNG_sPLT_SUPPORTED
  177086. # define PNG_sPLT_SUPPORTED
  177087. # endif
  177088. #endif
  177089. #ifndef PNG_NO_WRITE_sRGB
  177090. # define PNG_WRITE_sRGB_SUPPORTED
  177091. # ifndef PNG_sRGB_SUPPORTED
  177092. # define PNG_sRGB_SUPPORTED
  177093. # endif
  177094. #endif
  177095. #ifndef PNG_NO_WRITE_tEXt
  177096. # define PNG_WRITE_tEXt_SUPPORTED
  177097. # ifndef PNG_tEXt_SUPPORTED
  177098. # define PNG_tEXt_SUPPORTED
  177099. # endif
  177100. #endif
  177101. #ifndef PNG_NO_WRITE_tIME
  177102. # define PNG_WRITE_tIME_SUPPORTED
  177103. # ifndef PNG_tIME_SUPPORTED
  177104. # define PNG_tIME_SUPPORTED
  177105. # endif
  177106. #endif
  177107. #ifndef PNG_NO_WRITE_tRNS
  177108. # define PNG_WRITE_tRNS_SUPPORTED
  177109. # ifndef PNG_tRNS_SUPPORTED
  177110. # define PNG_tRNS_SUPPORTED
  177111. # endif
  177112. #endif
  177113. #ifndef PNG_NO_WRITE_zTXt
  177114. # define PNG_WRITE_zTXt_SUPPORTED
  177115. # ifndef PNG_zTXt_SUPPORTED
  177116. # define PNG_zTXt_SUPPORTED
  177117. # endif
  177118. #endif
  177119. #ifndef PNG_NO_WRITE_UNKNOWN_CHUNKS
  177120. # define PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED
  177121. # ifndef PNG_UNKNOWN_CHUNKS_SUPPORTED
  177122. # define PNG_UNKNOWN_CHUNKS_SUPPORTED
  177123. # endif
  177124. # ifndef PNG_NO_HANDLE_AS_UNKNOWN
  177125. # ifndef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  177126. # define PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  177127. # endif
  177128. # endif
  177129. #endif
  177130. #if defined(PNG_WRITE_iTXt_SUPPORTED) || defined(PNG_WRITE_tEXt_SUPPORTED) || \
  177131. defined(PNG_WRITE_zTXt_SUPPORTED)
  177132. # define PNG_WRITE_TEXT_SUPPORTED
  177133. # ifndef PNG_TEXT_SUPPORTED
  177134. # define PNG_TEXT_SUPPORTED
  177135. # endif
  177136. #endif
  177137. #endif /* PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED */
  177138. /* Turn this off to disable png_read_png() and
  177139. * png_write_png() and leave the row_pointers member
  177140. * out of the info structure.
  177141. */
  177142. #ifndef PNG_NO_INFO_IMAGE
  177143. # define PNG_INFO_IMAGE_SUPPORTED
  177144. #endif
  177145. /* need the time information for reading tIME chunks */
  177146. #if defined(PNG_tIME_SUPPORTED)
  177147. # if !defined(_WIN32_WCE)
  177148. /* "time.h" functions are not supported on WindowsCE */
  177149. # include <time.h>
  177150. # endif
  177151. #endif
  177152. /* Some typedefs to get us started. These should be safe on most of the
  177153. * common platforms. The typedefs should be at least as large as the
  177154. * numbers suggest (a png_uint_32 must be at least 32 bits long), but they
  177155. * don't have to be exactly that size. Some compilers dislike passing
  177156. * unsigned shorts as function parameters, so you may be better off using
  177157. * unsigned int for png_uint_16. Likewise, for 64-bit systems, you may
  177158. * want to have unsigned int for png_uint_32 instead of unsigned long.
  177159. */
  177160. typedef unsigned long png_uint_32;
  177161. typedef long png_int_32;
  177162. typedef unsigned short png_uint_16;
  177163. typedef short png_int_16;
  177164. typedef unsigned char png_byte;
  177165. /* This is usually size_t. It is typedef'ed just in case you need it to
  177166. change (I'm not sure if you will or not, so I thought I'd be safe) */
  177167. #ifdef PNG_SIZE_T
  177168. typedef PNG_SIZE_T png_size_t;
  177169. # define png_sizeof(x) png_convert_size(sizeof (x))
  177170. #else
  177171. typedef size_t png_size_t;
  177172. # define png_sizeof(x) sizeof (x)
  177173. #endif
  177174. /* The following is needed for medium model support. It cannot be in the
  177175. * PNG_INTERNAL section. Needs modification for other compilers besides
  177176. * MSC. Model independent support declares all arrays and pointers to be
  177177. * large using the far keyword. The zlib version used must also support
  177178. * model independent data. As of version zlib 1.0.4, the necessary changes
  177179. * have been made in zlib. The USE_FAR_KEYWORD define triggers other
  177180. * changes that are needed. (Tim Wegner)
  177181. */
  177182. /* Separate compiler dependencies (problem here is that zlib.h always
  177183. defines FAR. (SJT) */
  177184. #ifdef __BORLANDC__
  177185. # if defined(__LARGE__) || defined(__HUGE__) || defined(__COMPACT__)
  177186. # define LDATA 1
  177187. # else
  177188. # define LDATA 0
  177189. # endif
  177190. /* GRR: why is Cygwin in here? Cygwin is not Borland C... */
  177191. # if !defined(__WIN32__) && !defined(__FLAT__) && !defined(__CYGWIN__)
  177192. # define PNG_MAX_MALLOC_64K
  177193. # if (LDATA != 1)
  177194. # ifndef FAR
  177195. # define FAR __far
  177196. # endif
  177197. # define USE_FAR_KEYWORD
  177198. # endif /* LDATA != 1 */
  177199. /* Possibly useful for moving data out of default segment.
  177200. * Uncomment it if you want. Could also define FARDATA as
  177201. * const if your compiler supports it. (SJT)
  177202. # define FARDATA FAR
  177203. */
  177204. # endif /* __WIN32__, __FLAT__, __CYGWIN__ */
  177205. #endif /* __BORLANDC__ */
  177206. /* Suggest testing for specific compiler first before testing for
  177207. * FAR. The Watcom compiler defines both __MEDIUM__ and M_I86MM,
  177208. * making reliance oncertain keywords suspect. (SJT)
  177209. */
  177210. /* MSC Medium model */
  177211. #if defined(FAR)
  177212. # if defined(M_I86MM)
  177213. # define USE_FAR_KEYWORD
  177214. # define FARDATA FAR
  177215. # include <dos.h>
  177216. # endif
  177217. #endif
  177218. /* SJT: default case */
  177219. #ifndef FAR
  177220. # define FAR
  177221. #endif
  177222. /* At this point FAR is always defined */
  177223. #ifndef FARDATA
  177224. # define FARDATA
  177225. #endif
  177226. /* Typedef for floating-point numbers that are converted
  177227. to fixed-point with a multiple of 100,000, e.g., int_gamma */
  177228. typedef png_int_32 png_fixed_point;
  177229. /* Add typedefs for pointers */
  177230. typedef void FAR * png_voidp;
  177231. typedef png_byte FAR * png_bytep;
  177232. typedef png_uint_32 FAR * png_uint_32p;
  177233. typedef png_int_32 FAR * png_int_32p;
  177234. typedef png_uint_16 FAR * png_uint_16p;
  177235. typedef png_int_16 FAR * png_int_16p;
  177236. typedef PNG_CONST char FAR * png_const_charp;
  177237. typedef char FAR * png_charp;
  177238. typedef png_fixed_point FAR * png_fixed_point_p;
  177239. #ifndef PNG_NO_STDIO
  177240. #if defined(_WIN32_WCE)
  177241. typedef HANDLE png_FILE_p;
  177242. #else
  177243. typedef FILE * png_FILE_p;
  177244. #endif
  177245. #endif
  177246. #ifdef PNG_FLOATING_POINT_SUPPORTED
  177247. typedef double FAR * png_doublep;
  177248. #endif
  177249. /* Pointers to pointers; i.e. arrays */
  177250. typedef png_byte FAR * FAR * png_bytepp;
  177251. typedef png_uint_32 FAR * FAR * png_uint_32pp;
  177252. typedef png_int_32 FAR * FAR * png_int_32pp;
  177253. typedef png_uint_16 FAR * FAR * png_uint_16pp;
  177254. typedef png_int_16 FAR * FAR * png_int_16pp;
  177255. typedef PNG_CONST char FAR * FAR * png_const_charpp;
  177256. typedef char FAR * FAR * png_charpp;
  177257. typedef png_fixed_point FAR * FAR * png_fixed_point_pp;
  177258. #ifdef PNG_FLOATING_POINT_SUPPORTED
  177259. typedef double FAR * FAR * png_doublepp;
  177260. #endif
  177261. /* Pointers to pointers to pointers; i.e., pointer to array */
  177262. typedef char FAR * FAR * FAR * png_charppp;
  177263. #if 0
  177264. /* SPC - Is this stuff deprecated? */
  177265. /* It'll be removed as of libpng-1.3.0 - GR-P */
  177266. /* libpng typedefs for types in zlib. If zlib changes
  177267. * or another compression library is used, then change these.
  177268. * Eliminates need to change all the source files.
  177269. */
  177270. typedef charf * png_zcharp;
  177271. typedef charf * FAR * png_zcharpp;
  177272. typedef z_stream FAR * png_zstreamp;
  177273. #endif /* (PNG_1_0_X) || defined(PNG_1_2_X) */
  177274. /*
  177275. * Define PNG_BUILD_DLL if the module being built is a Windows
  177276. * LIBPNG DLL.
  177277. *
  177278. * Define PNG_USE_DLL if you want to *link* to the Windows LIBPNG DLL.
  177279. * It is equivalent to Microsoft predefined macro _DLL that is
  177280. * automatically defined when you compile using the share
  177281. * version of the CRT (C Run-Time library)
  177282. *
  177283. * The cygwin mods make this behavior a little different:
  177284. * Define PNG_BUILD_DLL if you are building a dll for use with cygwin
  177285. * Define PNG_STATIC if you are building a static library for use with cygwin,
  177286. * -or- if you are building an application that you want to link to the
  177287. * static library.
  177288. * PNG_USE_DLL is defined by default (no user action needed) unless one of
  177289. * the other flags is defined.
  177290. */
  177291. #if !defined(PNG_DLL) && (defined(PNG_BUILD_DLL) || defined(PNG_USE_DLL))
  177292. # define PNG_DLL
  177293. #endif
  177294. /* If CYGWIN, then disallow GLOBAL ARRAYS unless building a static lib.
  177295. * When building a static lib, default to no GLOBAL ARRAYS, but allow
  177296. * command-line override
  177297. */
  177298. #if defined(__CYGWIN__)
  177299. # if !defined(PNG_STATIC)
  177300. # if defined(PNG_USE_GLOBAL_ARRAYS)
  177301. # undef PNG_USE_GLOBAL_ARRAYS
  177302. # endif
  177303. # if !defined(PNG_USE_LOCAL_ARRAYS)
  177304. # define PNG_USE_LOCAL_ARRAYS
  177305. # endif
  177306. # else
  177307. # if defined(PNG_USE_LOCAL_ARRAYS) || defined(PNG_NO_GLOBAL_ARRAYS)
  177308. # if defined(PNG_USE_GLOBAL_ARRAYS)
  177309. # undef PNG_USE_GLOBAL_ARRAYS
  177310. # endif
  177311. # endif
  177312. # endif
  177313. # if !defined(PNG_USE_LOCAL_ARRAYS) && !defined(PNG_USE_GLOBAL_ARRAYS)
  177314. # define PNG_USE_LOCAL_ARRAYS
  177315. # endif
  177316. #endif
  177317. /* Do not use global arrays (helps with building DLL's)
  177318. * They are no longer used in libpng itself, since version 1.0.5c,
  177319. * but might be required for some pre-1.0.5c applications.
  177320. */
  177321. #if !defined(PNG_USE_LOCAL_ARRAYS) && !defined(PNG_USE_GLOBAL_ARRAYS)
  177322. # if defined(PNG_NO_GLOBAL_ARRAYS) || \
  177323. (defined(__GNUC__) && defined(PNG_DLL)) || defined(_MSC_VER)
  177324. # define PNG_USE_LOCAL_ARRAYS
  177325. # else
  177326. # define PNG_USE_GLOBAL_ARRAYS
  177327. # endif
  177328. #endif
  177329. #if defined(__CYGWIN__)
  177330. # undef PNGAPI
  177331. # define PNGAPI __cdecl
  177332. # undef PNG_IMPEXP
  177333. # define PNG_IMPEXP
  177334. #endif
  177335. /* If you define PNGAPI, e.g., with compiler option "-DPNGAPI=__stdcall",
  177336. * you may get warnings regarding the linkage of png_zalloc and png_zfree.
  177337. * Don't ignore those warnings; you must also reset the default calling
  177338. * convention in your compiler to match your PNGAPI, and you must build
  177339. * zlib and your applications the same way you build libpng.
  177340. */
  177341. #if defined(__MINGW32__) && !defined(PNG_MODULEDEF)
  177342. # ifndef PNG_NO_MODULEDEF
  177343. # define PNG_NO_MODULEDEF
  177344. # endif
  177345. #endif
  177346. #if !defined(PNG_IMPEXP) && defined(PNG_BUILD_DLL) && !defined(PNG_NO_MODULEDEF)
  177347. # define PNG_IMPEXP
  177348. #endif
  177349. #if defined(PNG_DLL) || defined(_DLL) || defined(__DLL__ ) || \
  177350. (( defined(_Windows) || defined(_WINDOWS) || \
  177351. defined(WIN32) || defined(_WIN32) || defined(__WIN32__) ))
  177352. # ifndef PNGAPI
  177353. # if defined(__GNUC__) || (defined (_MSC_VER) && (_MSC_VER >= 800))
  177354. # define PNGAPI __cdecl
  177355. # else
  177356. # define PNGAPI _cdecl
  177357. # endif
  177358. # endif
  177359. # if !defined(PNG_IMPEXP) && (!defined(PNG_DLL) || \
  177360. 0 /* WINCOMPILER_WITH_NO_SUPPORT_FOR_DECLIMPEXP */)
  177361. # define PNG_IMPEXP
  177362. # endif
  177363. # if !defined(PNG_IMPEXP)
  177364. # define PNG_EXPORT_TYPE1(type,symbol) PNG_IMPEXP type PNGAPI symbol
  177365. # define PNG_EXPORT_TYPE2(type,symbol) type PNG_IMPEXP PNGAPI symbol
  177366. /* Borland/Microsoft */
  177367. # if defined(_MSC_VER) || defined(__BORLANDC__)
  177368. # if (_MSC_VER >= 800) || (__BORLANDC__ >= 0x500)
  177369. # define PNG_EXPORT PNG_EXPORT_TYPE1
  177370. # else
  177371. # define PNG_EXPORT PNG_EXPORT_TYPE2
  177372. # if defined(PNG_BUILD_DLL)
  177373. # define PNG_IMPEXP __export
  177374. # else
  177375. # define PNG_IMPEXP /*__import */ /* doesn't exist AFAIK in
  177376. VC++ */
  177377. # endif /* Exists in Borland C++ for
  177378. C++ classes (== huge) */
  177379. # endif
  177380. # endif
  177381. # if !defined(PNG_IMPEXP)
  177382. # if defined(PNG_BUILD_DLL)
  177383. # define PNG_IMPEXP __declspec(dllexport)
  177384. # else
  177385. # define PNG_IMPEXP __declspec(dllimport)
  177386. # endif
  177387. # endif
  177388. # endif /* PNG_IMPEXP */
  177389. #else /* !(DLL || non-cygwin WINDOWS) */
  177390. # if (defined(__IBMC__) || defined(__IBMCPP__)) && defined(__OS2__)
  177391. # ifndef PNGAPI
  177392. # define PNGAPI _System
  177393. # endif
  177394. # else
  177395. # if 0 /* ... other platforms, with other meanings */
  177396. # endif
  177397. # endif
  177398. #endif
  177399. #ifndef PNGAPI
  177400. # define PNGAPI
  177401. #endif
  177402. #ifndef PNG_IMPEXP
  177403. # define PNG_IMPEXP
  177404. #endif
  177405. #ifdef PNG_BUILDSYMS
  177406. # ifndef PNG_EXPORT
  177407. # define PNG_EXPORT(type,symbol) PNG_FUNCTION_EXPORT symbol END
  177408. # endif
  177409. # ifdef PNG_USE_GLOBAL_ARRAYS
  177410. # ifndef PNG_EXPORT_VAR
  177411. # define PNG_EXPORT_VAR(type) PNG_DATA_EXPORT
  177412. # endif
  177413. # endif
  177414. #endif
  177415. #ifndef PNG_EXPORT
  177416. # define PNG_EXPORT(type,symbol) PNG_IMPEXP type PNGAPI symbol
  177417. #endif
  177418. #ifdef PNG_USE_GLOBAL_ARRAYS
  177419. # ifndef PNG_EXPORT_VAR
  177420. # define PNG_EXPORT_VAR(type) extern PNG_IMPEXP type
  177421. # endif
  177422. #endif
  177423. /* User may want to use these so they are not in PNG_INTERNAL. Any library
  177424. * functions that are passed far data must be model independent.
  177425. */
  177426. #ifndef PNG_ABORT
  177427. # define PNG_ABORT() abort()
  177428. #endif
  177429. #ifdef PNG_SETJMP_SUPPORTED
  177430. # define png_jmpbuf(png_ptr) ((png_ptr)->jmpbuf)
  177431. #else
  177432. # define png_jmpbuf(png_ptr) \
  177433. (LIBPNG_WAS_COMPILED_WITH__PNG_SETJMP_NOT_SUPPORTED)
  177434. #endif
  177435. #if defined(USE_FAR_KEYWORD) /* memory model independent fns */
  177436. /* use this to make far-to-near assignments */
  177437. # define CHECK 1
  177438. # define NOCHECK 0
  177439. # define CVT_PTR(ptr) (png_far_to_near(png_ptr,ptr,CHECK))
  177440. # define CVT_PTR_NOCHECK(ptr) (png_far_to_near(png_ptr,ptr,NOCHECK))
  177441. # define png_snprintf _fsnprintf /* Added to v 1.2.19 */
  177442. # define png_strcpy _fstrcpy
  177443. # define png_strncpy _fstrncpy /* Added to v 1.2.6 */
  177444. # define png_strlen _fstrlen
  177445. # define png_memcmp _fmemcmp /* SJT: added */
  177446. # define png_memcpy _fmemcpy
  177447. # define png_memset _fmemset
  177448. #else /* use the usual functions */
  177449. # define CVT_PTR(ptr) (ptr)
  177450. # define CVT_PTR_NOCHECK(ptr) (ptr)
  177451. # ifndef PNG_NO_SNPRINTF
  177452. # ifdef _MSC_VER
  177453. # define png_snprintf _snprintf /* Added to v 1.2.19 */
  177454. # define png_snprintf2 _snprintf
  177455. # define png_snprintf6 _snprintf
  177456. # else
  177457. # define png_snprintf snprintf /* Added to v 1.2.19 */
  177458. # define png_snprintf2 snprintf
  177459. # define png_snprintf6 snprintf
  177460. # endif
  177461. # else
  177462. /* You don't have or don't want to use snprintf(). Caution: Using
  177463. * sprintf instead of snprintf exposes your application to accidental
  177464. * or malevolent buffer overflows. If you don't have snprintf()
  177465. * as a general rule you should provide one (you can get one from
  177466. * Portable OpenSSH). */
  177467. # define png_snprintf(s1,n,fmt,x1) sprintf(s1,fmt,x1)
  177468. # define png_snprintf2(s1,n,fmt,x1,x2) sprintf(s1,fmt,x1,x2)
  177469. # define png_snprintf6(s1,n,fmt,x1,x2,x3,x4,x5,x6) \
  177470. sprintf(s1,fmt,x1,x2,x3,x4,x5,x6)
  177471. # endif
  177472. # define png_strcpy strcpy
  177473. # define png_strncpy strncpy /* Added to v 1.2.6 */
  177474. # define png_strlen strlen
  177475. # define png_memcmp memcmp /* SJT: added */
  177476. # define png_memcpy memcpy
  177477. # define png_memset memset
  177478. #endif
  177479. /* End of memory model independent support */
  177480. /* Just a little check that someone hasn't tried to define something
  177481. * contradictory.
  177482. */
  177483. #if (PNG_ZBUF_SIZE > 65536L) && defined(PNG_MAX_MALLOC_64K)
  177484. # undef PNG_ZBUF_SIZE
  177485. # define PNG_ZBUF_SIZE 65536L
  177486. #endif
  177487. /* Added at libpng-1.2.8 */
  177488. #endif /* PNG_VERSION_INFO_ONLY */
  177489. #endif /* PNGCONF_H */
  177490. /********* End of inlined file: pngconf.h *********/
  177491. #ifdef _MSC_VER
  177492. #pragma warning (disable: 4996 4100)
  177493. #endif
  177494. /*
  177495. * Added at libpng-1.2.8 */
  177496. /* Ref MSDN: Private as priority over Special
  177497. * VS_FF_PRIVATEBUILD File *was not* built using standard release
  177498. * procedures. If this value is given, the StringFileInfo block must
  177499. * contain a PrivateBuild string.
  177500. *
  177501. * VS_FF_SPECIALBUILD File *was* built by the original company using
  177502. * standard release procedures but is a variation of the standard
  177503. * file of the same version number. If this value is given, the
  177504. * StringFileInfo block must contain a SpecialBuild string.
  177505. */
  177506. #if defined(PNG_USER_PRIVATEBUILD)
  177507. # define PNG_LIBPNG_BUILD_TYPE \
  177508. (PNG_LIBPNG_BUILD_BASE_TYPE | PNG_LIBPNG_BUILD_PRIVATE)
  177509. #else
  177510. # if defined(PNG_LIBPNG_SPECIALBUILD)
  177511. # define PNG_LIBPNG_BUILD_TYPE \
  177512. (PNG_LIBPNG_BUILD_BASE_TYPE | PNG_LIBPNG_BUILD_SPECIAL)
  177513. # else
  177514. # define PNG_LIBPNG_BUILD_TYPE (PNG_LIBPNG_BUILD_BASE_TYPE)
  177515. # endif
  177516. #endif
  177517. #ifndef PNG_VERSION_INFO_ONLY
  177518. /* Inhibit C++ name-mangling for libpng functions but not for system calls. */
  177519. #ifdef __cplusplus
  177520. extern "C" {
  177521. #endif /* __cplusplus */
  177522. /* This file is arranged in several sections. The first section contains
  177523. * structure and type definitions. The second section contains the external
  177524. * library functions, while the third has the internal library functions,
  177525. * which applications aren't expected to use directly.
  177526. */
  177527. #ifndef PNG_NO_TYPECAST_NULL
  177528. #define int_p_NULL (int *)NULL
  177529. #define png_bytep_NULL (png_bytep)NULL
  177530. #define png_bytepp_NULL (png_bytepp)NULL
  177531. #define png_doublep_NULL (png_doublep)NULL
  177532. #define png_error_ptr_NULL (png_error_ptr)NULL
  177533. #define png_flush_ptr_NULL (png_flush_ptr)NULL
  177534. #define png_free_ptr_NULL (png_free_ptr)NULL
  177535. #define png_infopp_NULL (png_infopp)NULL
  177536. #define png_malloc_ptr_NULL (png_malloc_ptr)NULL
  177537. #define png_read_status_ptr_NULL (png_read_status_ptr)NULL
  177538. #define png_rw_ptr_NULL (png_rw_ptr)NULL
  177539. #define png_structp_NULL (png_structp)NULL
  177540. #define png_uint_16p_NULL (png_uint_16p)NULL
  177541. #define png_voidp_NULL (png_voidp)NULL
  177542. #define png_write_status_ptr_NULL (png_write_status_ptr)NULL
  177543. #else
  177544. #define int_p_NULL NULL
  177545. #define png_bytep_NULL NULL
  177546. #define png_bytepp_NULL NULL
  177547. #define png_doublep_NULL NULL
  177548. #define png_error_ptr_NULL NULL
  177549. #define png_flush_ptr_NULL NULL
  177550. #define png_free_ptr_NULL NULL
  177551. #define png_infopp_NULL NULL
  177552. #define png_malloc_ptr_NULL NULL
  177553. #define png_read_status_ptr_NULL NULL
  177554. #define png_rw_ptr_NULL NULL
  177555. #define png_structp_NULL NULL
  177556. #define png_uint_16p_NULL NULL
  177557. #define png_voidp_NULL NULL
  177558. #define png_write_status_ptr_NULL NULL
  177559. #endif
  177560. /* variables declared in png.c - only it needs to define PNG_NO_EXTERN */
  177561. #if !defined(PNG_NO_EXTERN) || defined(PNG_ALWAYS_EXTERN)
  177562. /* Version information for C files, stored in png.c. This had better match
  177563. * the version above.
  177564. */
  177565. #ifdef PNG_USE_GLOBAL_ARRAYS
  177566. PNG_EXPORT_VAR (PNG_CONST char) png_libpng_ver[18];
  177567. /* need room for 99.99.99beta99z */
  177568. #else
  177569. #define png_libpng_ver png_get_header_ver(NULL)
  177570. #endif
  177571. #ifdef PNG_USE_GLOBAL_ARRAYS
  177572. /* This was removed in version 1.0.5c */
  177573. /* Structures to facilitate easy interlacing. See png.c for more details */
  177574. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_start[7];
  177575. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_inc[7];
  177576. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_ystart[7];
  177577. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_yinc[7];
  177578. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_mask[7];
  177579. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_dsp_mask[7];
  177580. /* This isn't currently used. If you need it, see png.c for more details.
  177581. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_height[7];
  177582. */
  177583. #endif
  177584. #endif /* PNG_NO_EXTERN */
  177585. /* Three color definitions. The order of the red, green, and blue, (and the
  177586. * exact size) is not important, although the size of the fields need to
  177587. * be png_byte or png_uint_16 (as defined below).
  177588. */
  177589. typedef struct png_color_struct
  177590. {
  177591. png_byte red;
  177592. png_byte green;
  177593. png_byte blue;
  177594. } png_color;
  177595. typedef png_color FAR * png_colorp;
  177596. typedef png_color FAR * FAR * png_colorpp;
  177597. typedef struct png_color_16_struct
  177598. {
  177599. png_byte index; /* used for palette files */
  177600. png_uint_16 red; /* for use in red green blue files */
  177601. png_uint_16 green;
  177602. png_uint_16 blue;
  177603. png_uint_16 gray; /* for use in grayscale files */
  177604. } png_color_16;
  177605. typedef png_color_16 FAR * png_color_16p;
  177606. typedef png_color_16 FAR * FAR * png_color_16pp;
  177607. typedef struct png_color_8_struct
  177608. {
  177609. png_byte red; /* for use in red green blue files */
  177610. png_byte green;
  177611. png_byte blue;
  177612. png_byte gray; /* for use in grayscale files */
  177613. png_byte alpha; /* for alpha channel files */
  177614. } png_color_8;
  177615. typedef png_color_8 FAR * png_color_8p;
  177616. typedef png_color_8 FAR * FAR * png_color_8pp;
  177617. /*
  177618. * The following two structures are used for the in-core representation
  177619. * of sPLT chunks.
  177620. */
  177621. typedef struct png_sPLT_entry_struct
  177622. {
  177623. png_uint_16 red;
  177624. png_uint_16 green;
  177625. png_uint_16 blue;
  177626. png_uint_16 alpha;
  177627. png_uint_16 frequency;
  177628. } png_sPLT_entry;
  177629. typedef png_sPLT_entry FAR * png_sPLT_entryp;
  177630. typedef png_sPLT_entry FAR * FAR * png_sPLT_entrypp;
  177631. /* When the depth of the sPLT palette is 8 bits, the color and alpha samples
  177632. * occupy the LSB of their respective members, and the MSB of each member
  177633. * is zero-filled. The frequency member always occupies the full 16 bits.
  177634. */
  177635. typedef struct png_sPLT_struct
  177636. {
  177637. png_charp name; /* palette name */
  177638. png_byte depth; /* depth of palette samples */
  177639. png_sPLT_entryp entries; /* palette entries */
  177640. png_int_32 nentries; /* number of palette entries */
  177641. } png_sPLT_t;
  177642. typedef png_sPLT_t FAR * png_sPLT_tp;
  177643. typedef png_sPLT_t FAR * FAR * png_sPLT_tpp;
  177644. #ifdef PNG_TEXT_SUPPORTED
  177645. /* png_text holds the contents of a text/ztxt/itxt chunk in a PNG file,
  177646. * and whether that contents is compressed or not. The "key" field
  177647. * points to a regular zero-terminated C string. The "text", "lang", and
  177648. * "lang_key" fields can be regular C strings, empty strings, or NULL pointers.
  177649. * However, the * structure returned by png_get_text() will always contain
  177650. * regular zero-terminated C strings (possibly empty), never NULL pointers,
  177651. * so they can be safely used in printf() and other string-handling functions.
  177652. */
  177653. typedef struct png_text_struct
  177654. {
  177655. int compression; /* compression value:
  177656. -1: tEXt, none
  177657. 0: zTXt, deflate
  177658. 1: iTXt, none
  177659. 2: iTXt, deflate */
  177660. png_charp key; /* keyword, 1-79 character description of "text" */
  177661. png_charp text; /* comment, may be an empty string (ie "")
  177662. or a NULL pointer */
  177663. png_size_t text_length; /* length of the text string */
  177664. #ifdef PNG_iTXt_SUPPORTED
  177665. png_size_t itxt_length; /* length of the itxt string */
  177666. png_charp lang; /* language code, 0-79 characters
  177667. or a NULL pointer */
  177668. png_charp lang_key; /* keyword translated UTF-8 string, 0 or more
  177669. chars or a NULL pointer */
  177670. #endif
  177671. } png_text;
  177672. typedef png_text FAR * png_textp;
  177673. typedef png_text FAR * FAR * png_textpp;
  177674. #endif
  177675. /* Supported compression types for text in PNG files (tEXt, and zTXt).
  177676. * The values of the PNG_TEXT_COMPRESSION_ defines should NOT be changed. */
  177677. #define PNG_TEXT_COMPRESSION_NONE_WR -3
  177678. #define PNG_TEXT_COMPRESSION_zTXt_WR -2
  177679. #define PNG_TEXT_COMPRESSION_NONE -1
  177680. #define PNG_TEXT_COMPRESSION_zTXt 0
  177681. #define PNG_ITXT_COMPRESSION_NONE 1
  177682. #define PNG_ITXT_COMPRESSION_zTXt 2
  177683. #define PNG_TEXT_COMPRESSION_LAST 3 /* Not a valid value */
  177684. /* png_time is a way to hold the time in an machine independent way.
  177685. * Two conversions are provided, both from time_t and struct tm. There
  177686. * is no portable way to convert to either of these structures, as far
  177687. * as I know. If you know of a portable way, send it to me. As a side
  177688. * note - PNG has always been Year 2000 compliant!
  177689. */
  177690. typedef struct png_time_struct
  177691. {
  177692. png_uint_16 year; /* full year, as in, 1995 */
  177693. png_byte month; /* month of year, 1 - 12 */
  177694. png_byte day; /* day of month, 1 - 31 */
  177695. png_byte hour; /* hour of day, 0 - 23 */
  177696. png_byte minute; /* minute of hour, 0 - 59 */
  177697. png_byte second; /* second of minute, 0 - 60 (for leap seconds) */
  177698. } png_time;
  177699. typedef png_time FAR * png_timep;
  177700. typedef png_time FAR * FAR * png_timepp;
  177701. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  177702. /* png_unknown_chunk is a structure to hold queued chunks for which there is
  177703. * no specific support. The idea is that we can use this to queue
  177704. * up private chunks for output even though the library doesn't actually
  177705. * know about their semantics.
  177706. */
  177707. typedef struct png_unknown_chunk_t
  177708. {
  177709. png_byte name[5];
  177710. png_byte *data;
  177711. png_size_t size;
  177712. /* libpng-using applications should NOT directly modify this byte. */
  177713. png_byte location; /* mode of operation at read time */
  177714. }
  177715. png_unknown_chunk;
  177716. typedef png_unknown_chunk FAR * png_unknown_chunkp;
  177717. typedef png_unknown_chunk FAR * FAR * png_unknown_chunkpp;
  177718. #endif
  177719. /* png_info is a structure that holds the information in a PNG file so
  177720. * that the application can find out the characteristics of the image.
  177721. * If you are reading the file, this structure will tell you what is
  177722. * in the PNG file. If you are writing the file, fill in the information
  177723. * you want to put into the PNG file, then call png_write_info().
  177724. * The names chosen should be very close to the PNG specification, so
  177725. * consult that document for information about the meaning of each field.
  177726. *
  177727. * With libpng < 0.95, it was only possible to directly set and read the
  177728. * the values in the png_info_struct, which meant that the contents and
  177729. * order of the values had to remain fixed. With libpng 0.95 and later,
  177730. * however, there are now functions that abstract the contents of
  177731. * png_info_struct from the application, so this makes it easier to use
  177732. * libpng with dynamic libraries, and even makes it possible to use
  177733. * libraries that don't have all of the libpng ancillary chunk-handing
  177734. * functionality.
  177735. *
  177736. * In any case, the order of the parameters in png_info_struct should NOT
  177737. * be changed for as long as possible to keep compatibility with applications
  177738. * that use the old direct-access method with png_info_struct.
  177739. *
  177740. * The following members may have allocated storage attached that should be
  177741. * cleaned up before the structure is discarded: palette, trans, text,
  177742. * pcal_purpose, pcal_units, pcal_params, hist, iccp_name, iccp_profile,
  177743. * splt_palettes, scal_unit, row_pointers, and unknowns. By default, these
  177744. * are automatically freed when the info structure is deallocated, if they were
  177745. * allocated internally by libpng. This behavior can be changed by means
  177746. * of the png_data_freer() function.
  177747. *
  177748. * More allocation details: all the chunk-reading functions that
  177749. * change these members go through the corresponding png_set_*
  177750. * functions. A function to clear these members is available: see
  177751. * png_free_data(). The png_set_* functions do not depend on being
  177752. * able to point info structure members to any of the storage they are
  177753. * passed (they make their own copies), EXCEPT that the png_set_text
  177754. * functions use the same storage passed to them in the text_ptr or
  177755. * itxt_ptr structure argument, and the png_set_rows and png_set_unknowns
  177756. * functions do not make their own copies.
  177757. */
  177758. typedef struct png_info_struct
  177759. {
  177760. /* the following are necessary for every PNG file */
  177761. png_uint_32 width; /* width of image in pixels (from IHDR) */
  177762. png_uint_32 height; /* height of image in pixels (from IHDR) */
  177763. png_uint_32 valid; /* valid chunk data (see PNG_INFO_ below) */
  177764. png_uint_32 rowbytes; /* bytes needed to hold an untransformed row */
  177765. png_colorp palette; /* array of color values (valid & PNG_INFO_PLTE) */
  177766. png_uint_16 num_palette; /* number of color entries in "palette" (PLTE) */
  177767. png_uint_16 num_trans; /* number of transparent palette color (tRNS) */
  177768. png_byte bit_depth; /* 1, 2, 4, 8, or 16 bits/channel (from IHDR) */
  177769. png_byte color_type; /* see PNG_COLOR_TYPE_ below (from IHDR) */
  177770. /* The following three should have been named *_method not *_type */
  177771. png_byte compression_type; /* must be PNG_COMPRESSION_TYPE_BASE (IHDR) */
  177772. png_byte filter_type; /* must be PNG_FILTER_TYPE_BASE (from IHDR) */
  177773. png_byte interlace_type; /* One of PNG_INTERLACE_NONE, PNG_INTERLACE_ADAM7 */
  177774. /* The following is informational only on read, and not used on writes. */
  177775. png_byte channels; /* number of data channels per pixel (1, 2, 3, 4) */
  177776. png_byte pixel_depth; /* number of bits per pixel */
  177777. png_byte spare_byte; /* to align the data, and for future use */
  177778. png_byte signature[8]; /* magic bytes read by libpng from start of file */
  177779. /* The rest of the data is optional. If you are reading, check the
  177780. * valid field to see if the information in these are valid. If you
  177781. * are writing, set the valid field to those chunks you want written,
  177782. * and initialize the appropriate fields below.
  177783. */
  177784. #if defined(PNG_gAMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  177785. /* The gAMA chunk describes the gamma characteristics of the system
  177786. * on which the image was created, normally in the range [1.0, 2.5].
  177787. * Data is valid if (valid & PNG_INFO_gAMA) is non-zero.
  177788. */
  177789. float gamma; /* gamma value of image, if (valid & PNG_INFO_gAMA) */
  177790. #endif
  177791. #if defined(PNG_sRGB_SUPPORTED)
  177792. /* GR-P, 0.96a */
  177793. /* Data valid if (valid & PNG_INFO_sRGB) non-zero. */
  177794. png_byte srgb_intent; /* sRGB rendering intent [0, 1, 2, or 3] */
  177795. #endif
  177796. #if defined(PNG_TEXT_SUPPORTED)
  177797. /* The tEXt, and zTXt chunks contain human-readable textual data in
  177798. * uncompressed, compressed, and optionally compressed forms, respectively.
  177799. * The data in "text" is an array of pointers to uncompressed,
  177800. * null-terminated C strings. Each chunk has a keyword that describes the
  177801. * textual data contained in that chunk. Keywords are not required to be
  177802. * unique, and the text string may be empty. Any number of text chunks may
  177803. * be in an image.
  177804. */
  177805. int num_text; /* number of comments read/to write */
  177806. int max_text; /* current size of text array */
  177807. png_textp text; /* array of comments read/to write */
  177808. #endif /* PNG_TEXT_SUPPORTED */
  177809. #if defined(PNG_tIME_SUPPORTED)
  177810. /* The tIME chunk holds the last time the displayed image data was
  177811. * modified. See the png_time struct for the contents of this struct.
  177812. */
  177813. png_time mod_time;
  177814. #endif
  177815. #if defined(PNG_sBIT_SUPPORTED)
  177816. /* The sBIT chunk specifies the number of significant high-order bits
  177817. * in the pixel data. Values are in the range [1, bit_depth], and are
  177818. * only specified for the channels in the pixel data. The contents of
  177819. * the low-order bits is not specified. Data is valid if
  177820. * (valid & PNG_INFO_sBIT) is non-zero.
  177821. */
  177822. png_color_8 sig_bit; /* significant bits in color channels */
  177823. #endif
  177824. #if defined(PNG_tRNS_SUPPORTED) || defined(PNG_READ_EXPAND_SUPPORTED) || \
  177825. defined(PNG_READ_BACKGROUND_SUPPORTED)
  177826. /* The tRNS chunk supplies transparency data for paletted images and
  177827. * other image types that don't need a full alpha channel. There are
  177828. * "num_trans" transparency values for a paletted image, stored in the
  177829. * same order as the palette colors, starting from index 0. Values
  177830. * for the data are in the range [0, 255], ranging from fully transparent
  177831. * to fully opaque, respectively. For non-paletted images, there is a
  177832. * single color specified that should be treated as fully transparent.
  177833. * Data is valid if (valid & PNG_INFO_tRNS) is non-zero.
  177834. */
  177835. png_bytep trans; /* transparent values for paletted image */
  177836. png_color_16 trans_values; /* transparent color for non-palette image */
  177837. #endif
  177838. #if defined(PNG_bKGD_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  177839. /* The bKGD chunk gives the suggested image background color if the
  177840. * display program does not have its own background color and the image
  177841. * is needs to composited onto a background before display. The colors
  177842. * in "background" are normally in the same color space/depth as the
  177843. * pixel data. Data is valid if (valid & PNG_INFO_bKGD) is non-zero.
  177844. */
  177845. png_color_16 background;
  177846. #endif
  177847. #if defined(PNG_oFFs_SUPPORTED)
  177848. /* The oFFs chunk gives the offset in "offset_unit_type" units rightwards
  177849. * and downwards from the top-left corner of the display, page, or other
  177850. * application-specific co-ordinate space. See the PNG_OFFSET_ defines
  177851. * below for the unit types. Valid if (valid & PNG_INFO_oFFs) non-zero.
  177852. */
  177853. png_int_32 x_offset; /* x offset on page */
  177854. png_int_32 y_offset; /* y offset on page */
  177855. png_byte offset_unit_type; /* offset units type */
  177856. #endif
  177857. #if defined(PNG_pHYs_SUPPORTED)
  177858. /* The pHYs chunk gives the physical pixel density of the image for
  177859. * display or printing in "phys_unit_type" units (see PNG_RESOLUTION_
  177860. * defines below). Data is valid if (valid & PNG_INFO_pHYs) is non-zero.
  177861. */
  177862. png_uint_32 x_pixels_per_unit; /* horizontal pixel density */
  177863. png_uint_32 y_pixels_per_unit; /* vertical pixel density */
  177864. png_byte phys_unit_type; /* resolution type (see PNG_RESOLUTION_ below) */
  177865. #endif
  177866. #if defined(PNG_hIST_SUPPORTED)
  177867. /* The hIST chunk contains the relative frequency or importance of the
  177868. * various palette entries, so that a viewer can intelligently select a
  177869. * reduced-color palette, if required. Data is an array of "num_palette"
  177870. * values in the range [0,65535]. Data valid if (valid & PNG_INFO_hIST)
  177871. * is non-zero.
  177872. */
  177873. png_uint_16p hist;
  177874. #endif
  177875. #ifdef PNG_cHRM_SUPPORTED
  177876. /* The cHRM chunk describes the CIE color characteristics of the monitor
  177877. * on which the PNG was created. This data allows the viewer to do gamut
  177878. * mapping of the input image to ensure that the viewer sees the same
  177879. * colors in the image as the creator. Values are in the range
  177880. * [0.0, 0.8]. Data valid if (valid & PNG_INFO_cHRM) non-zero.
  177881. */
  177882. #ifdef PNG_FLOATING_POINT_SUPPORTED
  177883. float x_white;
  177884. float y_white;
  177885. float x_red;
  177886. float y_red;
  177887. float x_green;
  177888. float y_green;
  177889. float x_blue;
  177890. float y_blue;
  177891. #endif
  177892. #endif
  177893. #if defined(PNG_pCAL_SUPPORTED)
  177894. /* The pCAL chunk describes a transformation between the stored pixel
  177895. * values and original physical data values used to create the image.
  177896. * The integer range [0, 2^bit_depth - 1] maps to the floating-point
  177897. * range given by [pcal_X0, pcal_X1], and are further transformed by a
  177898. * (possibly non-linear) transformation function given by "pcal_type"
  177899. * and "pcal_params" into "pcal_units". Please see the PNG_EQUATION_
  177900. * defines below, and the PNG-Group's PNG extensions document for a
  177901. * complete description of the transformations and how they should be
  177902. * implemented, and for a description of the ASCII parameter strings.
  177903. * Data values are valid if (valid & PNG_INFO_pCAL) non-zero.
  177904. */
  177905. png_charp pcal_purpose; /* pCAL chunk description string */
  177906. png_int_32 pcal_X0; /* minimum value */
  177907. png_int_32 pcal_X1; /* maximum value */
  177908. png_charp pcal_units; /* Latin-1 string giving physical units */
  177909. png_charpp pcal_params; /* ASCII strings containing parameter values */
  177910. png_byte pcal_type; /* equation type (see PNG_EQUATION_ below) */
  177911. png_byte pcal_nparams; /* number of parameters given in pcal_params */
  177912. #endif
  177913. /* New members added in libpng-1.0.6 */
  177914. #ifdef PNG_FREE_ME_SUPPORTED
  177915. png_uint_32 free_me; /* flags items libpng is responsible for freeing */
  177916. #endif
  177917. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  177918. /* storage for unknown chunks that the library doesn't recognize. */
  177919. png_unknown_chunkp unknown_chunks;
  177920. png_size_t unknown_chunks_num;
  177921. #endif
  177922. #if defined(PNG_iCCP_SUPPORTED)
  177923. /* iCCP chunk data. */
  177924. png_charp iccp_name; /* profile name */
  177925. png_charp iccp_profile; /* International Color Consortium profile data */
  177926. /* Note to maintainer: should be png_bytep */
  177927. png_uint_32 iccp_proflen; /* ICC profile data length */
  177928. png_byte iccp_compression; /* Always zero */
  177929. #endif
  177930. #if defined(PNG_sPLT_SUPPORTED)
  177931. /* data on sPLT chunks (there may be more than one). */
  177932. png_sPLT_tp splt_palettes;
  177933. png_uint_32 splt_palettes_num;
  177934. #endif
  177935. #if defined(PNG_sCAL_SUPPORTED)
  177936. /* The sCAL chunk describes the actual physical dimensions of the
  177937. * subject matter of the graphic. The chunk contains a unit specification
  177938. * a byte value, and two ASCII strings representing floating-point
  177939. * values. The values are width and height corresponsing to one pixel
  177940. * in the image. This external representation is converted to double
  177941. * here. Data values are valid if (valid & PNG_INFO_sCAL) is non-zero.
  177942. */
  177943. png_byte scal_unit; /* unit of physical scale */
  177944. #ifdef PNG_FLOATING_POINT_SUPPORTED
  177945. double scal_pixel_width; /* width of one pixel */
  177946. double scal_pixel_height; /* height of one pixel */
  177947. #endif
  177948. #ifdef PNG_FIXED_POINT_SUPPORTED
  177949. png_charp scal_s_width; /* string containing height */
  177950. png_charp scal_s_height; /* string containing width */
  177951. #endif
  177952. #endif
  177953. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  177954. /* Memory has been allocated if (valid & PNG_ALLOCATED_INFO_ROWS) non-zero */
  177955. /* Data valid if (valid & PNG_INFO_IDAT) non-zero */
  177956. png_bytepp row_pointers; /* the image bits */
  177957. #endif
  177958. #if defined(PNG_FIXED_POINT_SUPPORTED) && defined(PNG_gAMA_SUPPORTED)
  177959. png_fixed_point int_gamma; /* gamma of image, if (valid & PNG_INFO_gAMA) */
  177960. #endif
  177961. #if defined(PNG_cHRM_SUPPORTED) && defined(PNG_FIXED_POINT_SUPPORTED)
  177962. png_fixed_point int_x_white;
  177963. png_fixed_point int_y_white;
  177964. png_fixed_point int_x_red;
  177965. png_fixed_point int_y_red;
  177966. png_fixed_point int_x_green;
  177967. png_fixed_point int_y_green;
  177968. png_fixed_point int_x_blue;
  177969. png_fixed_point int_y_blue;
  177970. #endif
  177971. } png_info;
  177972. typedef png_info FAR * png_infop;
  177973. typedef png_info FAR * FAR * png_infopp;
  177974. /* Maximum positive integer used in PNG is (2^31)-1 */
  177975. #define PNG_UINT_31_MAX ((png_uint_32)0x7fffffffL)
  177976. #define PNG_UINT_32_MAX ((png_uint_32)(-1))
  177977. #define PNG_SIZE_MAX ((png_size_t)(-1))
  177978. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  177979. /* PNG_MAX_UINT is deprecated; use PNG_UINT_31_MAX instead. */
  177980. #define PNG_MAX_UINT PNG_UINT_31_MAX
  177981. #endif
  177982. /* These describe the color_type field in png_info. */
  177983. /* color type masks */
  177984. #define PNG_COLOR_MASK_PALETTE 1
  177985. #define PNG_COLOR_MASK_COLOR 2
  177986. #define PNG_COLOR_MASK_ALPHA 4
  177987. /* color types. Note that not all combinations are legal */
  177988. #define PNG_COLOR_TYPE_GRAY 0
  177989. #define PNG_COLOR_TYPE_PALETTE (PNG_COLOR_MASK_COLOR | PNG_COLOR_MASK_PALETTE)
  177990. #define PNG_COLOR_TYPE_RGB (PNG_COLOR_MASK_COLOR)
  177991. #define PNG_COLOR_TYPE_RGB_ALPHA (PNG_COLOR_MASK_COLOR | PNG_COLOR_MASK_ALPHA)
  177992. #define PNG_COLOR_TYPE_GRAY_ALPHA (PNG_COLOR_MASK_ALPHA)
  177993. /* aliases */
  177994. #define PNG_COLOR_TYPE_RGBA PNG_COLOR_TYPE_RGB_ALPHA
  177995. #define PNG_COLOR_TYPE_GA PNG_COLOR_TYPE_GRAY_ALPHA
  177996. /* This is for compression type. PNG 1.0-1.2 only define the single type. */
  177997. #define PNG_COMPRESSION_TYPE_BASE 0 /* Deflate method 8, 32K window */
  177998. #define PNG_COMPRESSION_TYPE_DEFAULT PNG_COMPRESSION_TYPE_BASE
  177999. /* This is for filter type. PNG 1.0-1.2 only define the single type. */
  178000. #define PNG_FILTER_TYPE_BASE 0 /* Single row per-byte filtering */
  178001. #define PNG_INTRAPIXEL_DIFFERENCING 64 /* Used only in MNG datastreams */
  178002. #define PNG_FILTER_TYPE_DEFAULT PNG_FILTER_TYPE_BASE
  178003. /* These are for the interlacing type. These values should NOT be changed. */
  178004. #define PNG_INTERLACE_NONE 0 /* Non-interlaced image */
  178005. #define PNG_INTERLACE_ADAM7 1 /* Adam7 interlacing */
  178006. #define PNG_INTERLACE_LAST 2 /* Not a valid value */
  178007. /* These are for the oFFs chunk. These values should NOT be changed. */
  178008. #define PNG_OFFSET_PIXEL 0 /* Offset in pixels */
  178009. #define PNG_OFFSET_MICROMETER 1 /* Offset in micrometers (1/10^6 meter) */
  178010. #define PNG_OFFSET_LAST 2 /* Not a valid value */
  178011. /* These are for the pCAL chunk. These values should NOT be changed. */
  178012. #define PNG_EQUATION_LINEAR 0 /* Linear transformation */
  178013. #define PNG_EQUATION_BASE_E 1 /* Exponential base e transform */
  178014. #define PNG_EQUATION_ARBITRARY 2 /* Arbitrary base exponential transform */
  178015. #define PNG_EQUATION_HYPERBOLIC 3 /* Hyperbolic sine transformation */
  178016. #define PNG_EQUATION_LAST 4 /* Not a valid value */
  178017. /* These are for the sCAL chunk. These values should NOT be changed. */
  178018. #define PNG_SCALE_UNKNOWN 0 /* unknown unit (image scale) */
  178019. #define PNG_SCALE_METER 1 /* meters per pixel */
  178020. #define PNG_SCALE_RADIAN 2 /* radians per pixel */
  178021. #define PNG_SCALE_LAST 3 /* Not a valid value */
  178022. /* These are for the pHYs chunk. These values should NOT be changed. */
  178023. #define PNG_RESOLUTION_UNKNOWN 0 /* pixels/unknown unit (aspect ratio) */
  178024. #define PNG_RESOLUTION_METER 1 /* pixels/meter */
  178025. #define PNG_RESOLUTION_LAST 2 /* Not a valid value */
  178026. /* These are for the sRGB chunk. These values should NOT be changed. */
  178027. #define PNG_sRGB_INTENT_PERCEPTUAL 0
  178028. #define PNG_sRGB_INTENT_RELATIVE 1
  178029. #define PNG_sRGB_INTENT_SATURATION 2
  178030. #define PNG_sRGB_INTENT_ABSOLUTE 3
  178031. #define PNG_sRGB_INTENT_LAST 4 /* Not a valid value */
  178032. /* This is for text chunks */
  178033. #define PNG_KEYWORD_MAX_LENGTH 79
  178034. /* Maximum number of entries in PLTE/sPLT/tRNS arrays */
  178035. #define PNG_MAX_PALETTE_LENGTH 256
  178036. /* These determine if an ancillary chunk's data has been successfully read
  178037. * from the PNG header, or if the application has filled in the corresponding
  178038. * data in the info_struct to be written into the output file. The values
  178039. * of the PNG_INFO_<chunk> defines should NOT be changed.
  178040. */
  178041. #define PNG_INFO_gAMA 0x0001
  178042. #define PNG_INFO_sBIT 0x0002
  178043. #define PNG_INFO_cHRM 0x0004
  178044. #define PNG_INFO_PLTE 0x0008
  178045. #define PNG_INFO_tRNS 0x0010
  178046. #define PNG_INFO_bKGD 0x0020
  178047. #define PNG_INFO_hIST 0x0040
  178048. #define PNG_INFO_pHYs 0x0080
  178049. #define PNG_INFO_oFFs 0x0100
  178050. #define PNG_INFO_tIME 0x0200
  178051. #define PNG_INFO_pCAL 0x0400
  178052. #define PNG_INFO_sRGB 0x0800 /* GR-P, 0.96a */
  178053. #define PNG_INFO_iCCP 0x1000 /* ESR, 1.0.6 */
  178054. #define PNG_INFO_sPLT 0x2000 /* ESR, 1.0.6 */
  178055. #define PNG_INFO_sCAL 0x4000 /* ESR, 1.0.6 */
  178056. #define PNG_INFO_IDAT 0x8000L /* ESR, 1.0.6 */
  178057. /* This is used for the transformation routines, as some of them
  178058. * change these values for the row. It also should enable using
  178059. * the routines for other purposes.
  178060. */
  178061. typedef struct png_row_info_struct
  178062. {
  178063. png_uint_32 width; /* width of row */
  178064. png_uint_32 rowbytes; /* number of bytes in row */
  178065. png_byte color_type; /* color type of row */
  178066. png_byte bit_depth; /* bit depth of row */
  178067. png_byte channels; /* number of channels (1, 2, 3, or 4) */
  178068. png_byte pixel_depth; /* bits per pixel (depth * channels) */
  178069. } png_row_info;
  178070. typedef png_row_info FAR * png_row_infop;
  178071. typedef png_row_info FAR * FAR * png_row_infopp;
  178072. /* These are the function types for the I/O functions and for the functions
  178073. * that allow the user to override the default I/O functions with his or her
  178074. * own. The png_error_ptr type should match that of user-supplied warning
  178075. * and error functions, while the png_rw_ptr type should match that of the
  178076. * user read/write data functions.
  178077. */
  178078. typedef struct png_struct_def png_struct;
  178079. typedef png_struct FAR * png_structp;
  178080. typedef void (PNGAPI *png_error_ptr) PNGARG((png_structp, png_const_charp));
  178081. typedef void (PNGAPI *png_rw_ptr) PNGARG((png_structp, png_bytep, png_size_t));
  178082. typedef void (PNGAPI *png_flush_ptr) PNGARG((png_structp));
  178083. typedef void (PNGAPI *png_read_status_ptr) PNGARG((png_structp, png_uint_32,
  178084. int));
  178085. typedef void (PNGAPI *png_write_status_ptr) PNGARG((png_structp, png_uint_32,
  178086. int));
  178087. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  178088. typedef void (PNGAPI *png_progressive_info_ptr) PNGARG((png_structp, png_infop));
  178089. typedef void (PNGAPI *png_progressive_end_ptr) PNGARG((png_structp, png_infop));
  178090. typedef void (PNGAPI *png_progressive_row_ptr) PNGARG((png_structp, png_bytep,
  178091. png_uint_32, int));
  178092. #endif
  178093. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  178094. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  178095. defined(PNG_LEGACY_SUPPORTED)
  178096. typedef void (PNGAPI *png_user_transform_ptr) PNGARG((png_structp,
  178097. png_row_infop, png_bytep));
  178098. #endif
  178099. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  178100. typedef int (PNGAPI *png_user_chunk_ptr) PNGARG((png_structp, png_unknown_chunkp));
  178101. #endif
  178102. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  178103. typedef void (PNGAPI *png_unknown_chunk_ptr) PNGARG((png_structp));
  178104. #endif
  178105. /* Transform masks for the high-level interface */
  178106. #define PNG_TRANSFORM_IDENTITY 0x0000 /* read and write */
  178107. #define PNG_TRANSFORM_STRIP_16 0x0001 /* read only */
  178108. #define PNG_TRANSFORM_STRIP_ALPHA 0x0002 /* read only */
  178109. #define PNG_TRANSFORM_PACKING 0x0004 /* read and write */
  178110. #define PNG_TRANSFORM_PACKSWAP 0x0008 /* read and write */
  178111. #define PNG_TRANSFORM_EXPAND 0x0010 /* read only */
  178112. #define PNG_TRANSFORM_INVERT_MONO 0x0020 /* read and write */
  178113. #define PNG_TRANSFORM_SHIFT 0x0040 /* read and write */
  178114. #define PNG_TRANSFORM_BGR 0x0080 /* read and write */
  178115. #define PNG_TRANSFORM_SWAP_ALPHA 0x0100 /* read and write */
  178116. #define PNG_TRANSFORM_SWAP_ENDIAN 0x0200 /* read and write */
  178117. #define PNG_TRANSFORM_INVERT_ALPHA 0x0400 /* read and write */
  178118. #define PNG_TRANSFORM_STRIP_FILLER 0x0800 /* WRITE only */
  178119. /* Flags for MNG supported features */
  178120. #define PNG_FLAG_MNG_EMPTY_PLTE 0x01
  178121. #define PNG_FLAG_MNG_FILTER_64 0x04
  178122. #define PNG_ALL_MNG_FEATURES 0x05
  178123. typedef png_voidp (*png_malloc_ptr) PNGARG((png_structp, png_size_t));
  178124. typedef void (*png_free_ptr) PNGARG((png_structp, png_voidp));
  178125. /* The structure that holds the information to read and write PNG files.
  178126. * The only people who need to care about what is inside of this are the
  178127. * people who will be modifying the library for their own special needs.
  178128. * It should NOT be accessed directly by an application, except to store
  178129. * the jmp_buf.
  178130. */
  178131. struct png_struct_def
  178132. {
  178133. #ifdef PNG_SETJMP_SUPPORTED
  178134. jmp_buf jmpbuf; /* used in png_error */
  178135. #endif
  178136. png_error_ptr error_fn; /* function for printing errors and aborting */
  178137. png_error_ptr warning_fn; /* function for printing warnings */
  178138. png_voidp error_ptr; /* user supplied struct for error functions */
  178139. png_rw_ptr write_data_fn; /* function for writing output data */
  178140. png_rw_ptr read_data_fn; /* function for reading input data */
  178141. png_voidp io_ptr; /* ptr to application struct for I/O functions */
  178142. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  178143. png_user_transform_ptr read_user_transform_fn; /* user read transform */
  178144. #endif
  178145. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  178146. png_user_transform_ptr write_user_transform_fn; /* user write transform */
  178147. #endif
  178148. /* These were added in libpng-1.0.2 */
  178149. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  178150. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  178151. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  178152. png_voidp user_transform_ptr; /* user supplied struct for user transform */
  178153. png_byte user_transform_depth; /* bit depth of user transformed pixels */
  178154. png_byte user_transform_channels; /* channels in user transformed pixels */
  178155. #endif
  178156. #endif
  178157. png_uint_32 mode; /* tells us where we are in the PNG file */
  178158. png_uint_32 flags; /* flags indicating various things to libpng */
  178159. png_uint_32 transformations; /* which transformations to perform */
  178160. z_stream zstream; /* pointer to decompression structure (below) */
  178161. png_bytep zbuf; /* buffer for zlib */
  178162. png_size_t zbuf_size; /* size of zbuf */
  178163. int zlib_level; /* holds zlib compression level */
  178164. int zlib_method; /* holds zlib compression method */
  178165. int zlib_window_bits; /* holds zlib compression window bits */
  178166. int zlib_mem_level; /* holds zlib compression memory level */
  178167. int zlib_strategy; /* holds zlib compression strategy */
  178168. png_uint_32 width; /* width of image in pixels */
  178169. png_uint_32 height; /* height of image in pixels */
  178170. png_uint_32 num_rows; /* number of rows in current pass */
  178171. png_uint_32 usr_width; /* width of row at start of write */
  178172. png_uint_32 rowbytes; /* size of row in bytes */
  178173. png_uint_32 irowbytes; /* size of current interlaced row in bytes */
  178174. png_uint_32 iwidth; /* width of current interlaced row in pixels */
  178175. png_uint_32 row_number; /* current row in interlace pass */
  178176. png_bytep prev_row; /* buffer to save previous (unfiltered) row */
  178177. png_bytep row_buf; /* buffer to save current (unfiltered) row */
  178178. png_bytep sub_row; /* buffer to save "sub" row when filtering */
  178179. png_bytep up_row; /* buffer to save "up" row when filtering */
  178180. png_bytep avg_row; /* buffer to save "avg" row when filtering */
  178181. png_bytep paeth_row; /* buffer to save "Paeth" row when filtering */
  178182. png_row_info row_info; /* used for transformation routines */
  178183. png_uint_32 idat_size; /* current IDAT size for read */
  178184. png_uint_32 crc; /* current chunk CRC value */
  178185. png_colorp palette; /* palette from the input file */
  178186. png_uint_16 num_palette; /* number of color entries in palette */
  178187. png_uint_16 num_trans; /* number of transparency values */
  178188. png_byte chunk_name[5]; /* null-terminated name of current chunk */
  178189. png_byte compression; /* file compression type (always 0) */
  178190. png_byte filter; /* file filter type (always 0) */
  178191. png_byte interlaced; /* PNG_INTERLACE_NONE, PNG_INTERLACE_ADAM7 */
  178192. png_byte pass; /* current interlace pass (0 - 6) */
  178193. png_byte do_filter; /* row filter flags (see PNG_FILTER_ below ) */
  178194. png_byte color_type; /* color type of file */
  178195. png_byte bit_depth; /* bit depth of file */
  178196. png_byte usr_bit_depth; /* bit depth of users row */
  178197. png_byte pixel_depth; /* number of bits per pixel */
  178198. png_byte channels; /* number of channels in file */
  178199. png_byte usr_channels; /* channels at start of write */
  178200. png_byte sig_bytes; /* magic bytes read/written from start of file */
  178201. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  178202. #ifdef PNG_LEGACY_SUPPORTED
  178203. png_byte filler; /* filler byte for pixel expansion */
  178204. #else
  178205. png_uint_16 filler; /* filler bytes for pixel expansion */
  178206. #endif
  178207. #endif
  178208. #if defined(PNG_bKGD_SUPPORTED)
  178209. png_byte background_gamma_type;
  178210. # ifdef PNG_FLOATING_POINT_SUPPORTED
  178211. float background_gamma;
  178212. # endif
  178213. png_color_16 background; /* background color in screen gamma space */
  178214. #if defined(PNG_READ_GAMMA_SUPPORTED)
  178215. png_color_16 background_1; /* background normalized to gamma 1.0 */
  178216. #endif
  178217. #endif /* PNG_bKGD_SUPPORTED */
  178218. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  178219. png_flush_ptr output_flush_fn;/* Function for flushing output */
  178220. png_uint_32 flush_dist; /* how many rows apart to flush, 0 - no flush */
  178221. png_uint_32 flush_rows; /* number of rows written since last flush */
  178222. #endif
  178223. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  178224. int gamma_shift; /* number of "insignificant" bits 16-bit gamma */
  178225. #ifdef PNG_FLOATING_POINT_SUPPORTED
  178226. float gamma; /* file gamma value */
  178227. float screen_gamma; /* screen gamma value (display_exponent) */
  178228. #endif
  178229. #endif
  178230. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  178231. png_bytep gamma_table; /* gamma table for 8-bit depth files */
  178232. png_bytep gamma_from_1; /* converts from 1.0 to screen */
  178233. png_bytep gamma_to_1; /* converts from file to 1.0 */
  178234. png_uint_16pp gamma_16_table; /* gamma table for 16-bit depth files */
  178235. png_uint_16pp gamma_16_from_1; /* converts from 1.0 to screen */
  178236. png_uint_16pp gamma_16_to_1; /* converts from file to 1.0 */
  178237. #endif
  178238. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_sBIT_SUPPORTED)
  178239. png_color_8 sig_bit; /* significant bits in each available channel */
  178240. #endif
  178241. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  178242. png_color_8 shift; /* shift for significant bit tranformation */
  178243. #endif
  178244. #if defined(PNG_tRNS_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED) \
  178245. || defined(PNG_READ_EXPAND_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  178246. png_bytep trans; /* transparency values for paletted files */
  178247. png_color_16 trans_values; /* transparency values for non-paletted files */
  178248. #endif
  178249. png_read_status_ptr read_row_fn; /* called after each row is decoded */
  178250. png_write_status_ptr write_row_fn; /* called after each row is encoded */
  178251. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  178252. png_progressive_info_ptr info_fn; /* called after header data fully read */
  178253. png_progressive_row_ptr row_fn; /* called after each prog. row is decoded */
  178254. png_progressive_end_ptr end_fn; /* called after image is complete */
  178255. png_bytep save_buffer_ptr; /* current location in save_buffer */
  178256. png_bytep save_buffer; /* buffer for previously read data */
  178257. png_bytep current_buffer_ptr; /* current location in current_buffer */
  178258. png_bytep current_buffer; /* buffer for recently used data */
  178259. png_uint_32 push_length; /* size of current input chunk */
  178260. png_uint_32 skip_length; /* bytes to skip in input data */
  178261. png_size_t save_buffer_size; /* amount of data now in save_buffer */
  178262. png_size_t save_buffer_max; /* total size of save_buffer */
  178263. png_size_t buffer_size; /* total amount of available input data */
  178264. png_size_t current_buffer_size; /* amount of data now in current_buffer */
  178265. int process_mode; /* what push library is currently doing */
  178266. int cur_palette; /* current push library palette index */
  178267. # if defined(PNG_TEXT_SUPPORTED)
  178268. png_size_t current_text_size; /* current size of text input data */
  178269. png_size_t current_text_left; /* how much text left to read in input */
  178270. png_charp current_text; /* current text chunk buffer */
  178271. png_charp current_text_ptr; /* current location in current_text */
  178272. # endif /* PNG_TEXT_SUPPORTED */
  178273. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  178274. #if defined(__TURBOC__) && !defined(_Windows) && !defined(__FLAT__)
  178275. /* for the Borland special 64K segment handler */
  178276. png_bytepp offset_table_ptr;
  178277. png_bytep offset_table;
  178278. png_uint_16 offset_table_number;
  178279. png_uint_16 offset_table_count;
  178280. png_uint_16 offset_table_count_free;
  178281. #endif
  178282. #if defined(PNG_READ_DITHER_SUPPORTED)
  178283. png_bytep palette_lookup; /* lookup table for dithering */
  178284. png_bytep dither_index; /* index translation for palette files */
  178285. #endif
  178286. #if defined(PNG_READ_DITHER_SUPPORTED) || defined(PNG_hIST_SUPPORTED)
  178287. png_uint_16p hist; /* histogram */
  178288. #endif
  178289. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  178290. png_byte heuristic_method; /* heuristic for row filter selection */
  178291. png_byte num_prev_filters; /* number of weights for previous rows */
  178292. png_bytep prev_filters; /* filter type(s) of previous row(s) */
  178293. png_uint_16p filter_weights; /* weight(s) for previous line(s) */
  178294. png_uint_16p inv_filter_weights; /* 1/weight(s) for previous line(s) */
  178295. png_uint_16p filter_costs; /* relative filter calculation cost */
  178296. png_uint_16p inv_filter_costs; /* 1/relative filter calculation cost */
  178297. #endif
  178298. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  178299. png_charp time_buffer; /* String to hold RFC 1123 time text */
  178300. #endif
  178301. /* New members added in libpng-1.0.6 */
  178302. #ifdef PNG_FREE_ME_SUPPORTED
  178303. png_uint_32 free_me; /* flags items libpng is responsible for freeing */
  178304. #endif
  178305. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  178306. png_voidp user_chunk_ptr;
  178307. png_user_chunk_ptr read_user_chunk_fn; /* user read chunk handler */
  178308. #endif
  178309. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  178310. int num_chunk_list;
  178311. png_bytep chunk_list;
  178312. #endif
  178313. /* New members added in libpng-1.0.3 */
  178314. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  178315. png_byte rgb_to_gray_status;
  178316. /* These were changed from png_byte in libpng-1.0.6 */
  178317. png_uint_16 rgb_to_gray_red_coeff;
  178318. png_uint_16 rgb_to_gray_green_coeff;
  178319. png_uint_16 rgb_to_gray_blue_coeff;
  178320. #endif
  178321. /* New member added in libpng-1.0.4 (renamed in 1.0.9) */
  178322. #if defined(PNG_MNG_FEATURES_SUPPORTED) || \
  178323. defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  178324. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  178325. /* changed from png_byte to png_uint_32 at version 1.2.0 */
  178326. #ifdef PNG_1_0_X
  178327. png_byte mng_features_permitted;
  178328. #else
  178329. png_uint_32 mng_features_permitted;
  178330. #endif /* PNG_1_0_X */
  178331. #endif
  178332. /* New member added in libpng-1.0.7 */
  178333. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  178334. png_fixed_point int_gamma;
  178335. #endif
  178336. /* New member added in libpng-1.0.9, ifdef'ed out in 1.0.12, enabled in 1.2.0 */
  178337. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  178338. png_byte filter_type;
  178339. #endif
  178340. #if defined(PNG_1_0_X)
  178341. /* New member added in libpng-1.0.10, ifdef'ed out in 1.2.0 */
  178342. png_uint_32 row_buf_size;
  178343. #endif
  178344. /* New members added in libpng-1.2.0 */
  178345. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  178346. # if !defined(PNG_1_0_X)
  178347. # if defined(PNG_MMX_CODE_SUPPORTED)
  178348. png_byte mmx_bitdepth_threshold;
  178349. png_uint_32 mmx_rowbytes_threshold;
  178350. # endif
  178351. png_uint_32 asm_flags;
  178352. # endif
  178353. #endif
  178354. /* New members added in libpng-1.0.2 but first enabled by default in 1.2.0 */
  178355. #ifdef PNG_USER_MEM_SUPPORTED
  178356. png_voidp mem_ptr; /* user supplied struct for mem functions */
  178357. png_malloc_ptr malloc_fn; /* function for allocating memory */
  178358. png_free_ptr free_fn; /* function for freeing memory */
  178359. #endif
  178360. /* New member added in libpng-1.0.13 and 1.2.0 */
  178361. png_bytep big_row_buf; /* buffer to save current (unfiltered) row */
  178362. #if defined(PNG_READ_DITHER_SUPPORTED)
  178363. /* The following three members were added at version 1.0.14 and 1.2.4 */
  178364. png_bytep dither_sort; /* working sort array */
  178365. png_bytep index_to_palette; /* where the original index currently is */
  178366. /* in the palette */
  178367. png_bytep palette_to_index; /* which original index points to this */
  178368. /* palette color */
  178369. #endif
  178370. /* New members added in libpng-1.0.16 and 1.2.6 */
  178371. png_byte compression_type;
  178372. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  178373. png_uint_32 user_width_max;
  178374. png_uint_32 user_height_max;
  178375. #endif
  178376. /* New member added in libpng-1.0.25 and 1.2.17 */
  178377. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  178378. /* storage for unknown chunk that the library doesn't recognize. */
  178379. png_unknown_chunk unknown_chunk;
  178380. #endif
  178381. };
  178382. /* This triggers a compiler error in png.c, if png.c and png.h
  178383. * do not agree upon the version number.
  178384. */
  178385. typedef png_structp version_1_2_21;
  178386. typedef png_struct FAR * FAR * png_structpp;
  178387. /* Here are the function definitions most commonly used. This is not
  178388. * the place to find out how to use libpng. See libpng.txt for the
  178389. * full explanation, see example.c for the summary. This just provides
  178390. * a simple one line description of the use of each function.
  178391. */
  178392. /* Returns the version number of the library */
  178393. extern PNG_EXPORT(png_uint_32,png_access_version_number) PNGARG((void));
  178394. /* Tell lib we have already handled the first <num_bytes> magic bytes.
  178395. * Handling more than 8 bytes from the beginning of the file is an error.
  178396. */
  178397. extern PNG_EXPORT(void,png_set_sig_bytes) PNGARG((png_structp png_ptr,
  178398. int num_bytes));
  178399. /* Check sig[start] through sig[start + num_to_check - 1] to see if it's a
  178400. * PNG file. Returns zero if the supplied bytes match the 8-byte PNG
  178401. * signature, and non-zero otherwise. Having num_to_check == 0 or
  178402. * start > 7 will always fail (ie return non-zero).
  178403. */
  178404. extern PNG_EXPORT(int,png_sig_cmp) PNGARG((png_bytep sig, png_size_t start,
  178405. png_size_t num_to_check));
  178406. /* Simple signature checking function. This is the same as calling
  178407. * png_check_sig(sig, n) := !png_sig_cmp(sig, 0, n).
  178408. */
  178409. extern PNG_EXPORT(int,png_check_sig) PNGARG((png_bytep sig, int num));
  178410. /* Allocate and initialize png_ptr struct for reading, and any other memory. */
  178411. extern PNG_EXPORT(png_structp,png_create_read_struct)
  178412. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  178413. png_error_ptr error_fn, png_error_ptr warn_fn));
  178414. /* Allocate and initialize png_ptr struct for writing, and any other memory */
  178415. extern PNG_EXPORT(png_structp,png_create_write_struct)
  178416. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  178417. png_error_ptr error_fn, png_error_ptr warn_fn));
  178418. #ifdef PNG_WRITE_SUPPORTED
  178419. extern PNG_EXPORT(png_uint_32,png_get_compression_buffer_size)
  178420. PNGARG((png_structp png_ptr));
  178421. #endif
  178422. #ifdef PNG_WRITE_SUPPORTED
  178423. extern PNG_EXPORT(void,png_set_compression_buffer_size)
  178424. PNGARG((png_structp png_ptr, png_uint_32 size));
  178425. #endif
  178426. /* Reset the compression stream */
  178427. extern PNG_EXPORT(int,png_reset_zstream) PNGARG((png_structp png_ptr));
  178428. /* New functions added in libpng-1.0.2 (not enabled by default until 1.2.0) */
  178429. #ifdef PNG_USER_MEM_SUPPORTED
  178430. extern PNG_EXPORT(png_structp,png_create_read_struct_2)
  178431. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  178432. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  178433. png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  178434. extern PNG_EXPORT(png_structp,png_create_write_struct_2)
  178435. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  178436. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  178437. png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  178438. #endif
  178439. /* Write a PNG chunk - size, type, (optional) data, CRC. */
  178440. extern PNG_EXPORT(void,png_write_chunk) PNGARG((png_structp png_ptr,
  178441. png_bytep chunk_name, png_bytep data, png_size_t length));
  178442. /* Write the start of a PNG chunk - length and chunk name. */
  178443. extern PNG_EXPORT(void,png_write_chunk_start) PNGARG((png_structp png_ptr,
  178444. png_bytep chunk_name, png_uint_32 length));
  178445. /* Write the data of a PNG chunk started with png_write_chunk_start(). */
  178446. extern PNG_EXPORT(void,png_write_chunk_data) PNGARG((png_structp png_ptr,
  178447. png_bytep data, png_size_t length));
  178448. /* Finish a chunk started with png_write_chunk_start() (includes CRC). */
  178449. extern PNG_EXPORT(void,png_write_chunk_end) PNGARG((png_structp png_ptr));
  178450. /* Allocate and initialize the info structure */
  178451. extern PNG_EXPORT(png_infop,png_create_info_struct)
  178452. PNGARG((png_structp png_ptr));
  178453. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  178454. /* Initialize the info structure (old interface - DEPRECATED) */
  178455. extern PNG_EXPORT(void,png_info_init) PNGARG((png_infop info_ptr));
  178456. #undef png_info_init
  178457. #define png_info_init(info_ptr) png_info_init_3(&info_ptr,\
  178458. png_sizeof(png_info));
  178459. #endif
  178460. extern PNG_EXPORT(void,png_info_init_3) PNGARG((png_infopp info_ptr,
  178461. png_size_t png_info_struct_size));
  178462. /* Writes all the PNG information before the image. */
  178463. extern PNG_EXPORT(void,png_write_info_before_PLTE) PNGARG((png_structp png_ptr,
  178464. png_infop info_ptr));
  178465. extern PNG_EXPORT(void,png_write_info) PNGARG((png_structp png_ptr,
  178466. png_infop info_ptr));
  178467. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  178468. /* read the information before the actual image data. */
  178469. extern PNG_EXPORT(void,png_read_info) PNGARG((png_structp png_ptr,
  178470. png_infop info_ptr));
  178471. #endif
  178472. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  178473. extern PNG_EXPORT(png_charp,png_convert_to_rfc1123)
  178474. PNGARG((png_structp png_ptr, png_timep ptime));
  178475. #endif
  178476. #if !defined(_WIN32_WCE)
  178477. /* "time.h" functions are not supported on WindowsCE */
  178478. #if defined(PNG_WRITE_tIME_SUPPORTED)
  178479. /* convert from a struct tm to png_time */
  178480. extern PNG_EXPORT(void,png_convert_from_struct_tm) PNGARG((png_timep ptime,
  178481. struct tm FAR * ttime));
  178482. /* convert from time_t to png_time. Uses gmtime() */
  178483. extern PNG_EXPORT(void,png_convert_from_time_t) PNGARG((png_timep ptime,
  178484. time_t ttime));
  178485. #endif /* PNG_WRITE_tIME_SUPPORTED */
  178486. #endif /* _WIN32_WCE */
  178487. #if defined(PNG_READ_EXPAND_SUPPORTED)
  178488. /* Expand data to 24-bit RGB, or 8-bit grayscale, with alpha if available. */
  178489. extern PNG_EXPORT(void,png_set_expand) PNGARG((png_structp png_ptr));
  178490. #if !defined(PNG_1_0_X)
  178491. extern PNG_EXPORT(void,png_set_expand_gray_1_2_4_to_8) PNGARG((png_structp
  178492. png_ptr));
  178493. #endif
  178494. extern PNG_EXPORT(void,png_set_palette_to_rgb) PNGARG((png_structp png_ptr));
  178495. extern PNG_EXPORT(void,png_set_tRNS_to_alpha) PNGARG((png_structp png_ptr));
  178496. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  178497. /* Deprecated */
  178498. extern PNG_EXPORT(void,png_set_gray_1_2_4_to_8) PNGARG((png_structp png_ptr));
  178499. #endif
  178500. #endif
  178501. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  178502. /* Use blue, green, red order for pixels. */
  178503. extern PNG_EXPORT(void,png_set_bgr) PNGARG((png_structp png_ptr));
  178504. #endif
  178505. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  178506. /* Expand the grayscale to 24-bit RGB if necessary. */
  178507. extern PNG_EXPORT(void,png_set_gray_to_rgb) PNGARG((png_structp png_ptr));
  178508. #endif
  178509. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  178510. /* Reduce RGB to grayscale. */
  178511. #ifdef PNG_FLOATING_POINT_SUPPORTED
  178512. extern PNG_EXPORT(void,png_set_rgb_to_gray) PNGARG((png_structp png_ptr,
  178513. int error_action, double red, double green ));
  178514. #endif
  178515. extern PNG_EXPORT(void,png_set_rgb_to_gray_fixed) PNGARG((png_structp png_ptr,
  178516. int error_action, png_fixed_point red, png_fixed_point green ));
  178517. extern PNG_EXPORT(png_byte,png_get_rgb_to_gray_status) PNGARG((png_structp
  178518. png_ptr));
  178519. #endif
  178520. extern PNG_EXPORT(void,png_build_grayscale_palette) PNGARG((int bit_depth,
  178521. png_colorp palette));
  178522. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  178523. extern PNG_EXPORT(void,png_set_strip_alpha) PNGARG((png_structp png_ptr));
  178524. #endif
  178525. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED) || \
  178526. defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  178527. extern PNG_EXPORT(void,png_set_swap_alpha) PNGARG((png_structp png_ptr));
  178528. #endif
  178529. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED) || \
  178530. defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  178531. extern PNG_EXPORT(void,png_set_invert_alpha) PNGARG((png_structp png_ptr));
  178532. #endif
  178533. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  178534. /* Add a filler byte to 8-bit Gray or 24-bit RGB images. */
  178535. extern PNG_EXPORT(void,png_set_filler) PNGARG((png_structp png_ptr,
  178536. png_uint_32 filler, int flags));
  178537. /* The values of the PNG_FILLER_ defines should NOT be changed */
  178538. #define PNG_FILLER_BEFORE 0
  178539. #define PNG_FILLER_AFTER 1
  178540. /* Add an alpha byte to 8-bit Gray or 24-bit RGB images. */
  178541. #if !defined(PNG_1_0_X)
  178542. extern PNG_EXPORT(void,png_set_add_alpha) PNGARG((png_structp png_ptr,
  178543. png_uint_32 filler, int flags));
  178544. #endif
  178545. #endif /* PNG_READ_FILLER_SUPPORTED || PNG_WRITE_FILLER_SUPPORTED */
  178546. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  178547. /* Swap bytes in 16-bit depth files. */
  178548. extern PNG_EXPORT(void,png_set_swap) PNGARG((png_structp png_ptr));
  178549. #endif
  178550. #if defined(PNG_READ_PACK_SUPPORTED) || defined(PNG_WRITE_PACK_SUPPORTED)
  178551. /* Use 1 byte per pixel in 1, 2, or 4-bit depth files. */
  178552. extern PNG_EXPORT(void,png_set_packing) PNGARG((png_structp png_ptr));
  178553. #endif
  178554. #if defined(PNG_READ_PACKSWAP_SUPPORTED) || defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  178555. /* Swap packing order of pixels in bytes. */
  178556. extern PNG_EXPORT(void,png_set_packswap) PNGARG((png_structp png_ptr));
  178557. #endif
  178558. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  178559. /* Converts files to legal bit depths. */
  178560. extern PNG_EXPORT(void,png_set_shift) PNGARG((png_structp png_ptr,
  178561. png_color_8p true_bits));
  178562. #endif
  178563. #if defined(PNG_READ_INTERLACING_SUPPORTED) || \
  178564. defined(PNG_WRITE_INTERLACING_SUPPORTED)
  178565. /* Have the code handle the interlacing. Returns the number of passes. */
  178566. extern PNG_EXPORT(int,png_set_interlace_handling) PNGARG((png_structp png_ptr));
  178567. #endif
  178568. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  178569. /* Invert monochrome files */
  178570. extern PNG_EXPORT(void,png_set_invert_mono) PNGARG((png_structp png_ptr));
  178571. #endif
  178572. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  178573. /* Handle alpha and tRNS by replacing with a background color. */
  178574. #ifdef PNG_FLOATING_POINT_SUPPORTED
  178575. extern PNG_EXPORT(void,png_set_background) PNGARG((png_structp png_ptr,
  178576. png_color_16p background_color, int background_gamma_code,
  178577. int need_expand, double background_gamma));
  178578. #endif
  178579. #define PNG_BACKGROUND_GAMMA_UNKNOWN 0
  178580. #define PNG_BACKGROUND_GAMMA_SCREEN 1
  178581. #define PNG_BACKGROUND_GAMMA_FILE 2
  178582. #define PNG_BACKGROUND_GAMMA_UNIQUE 3
  178583. #endif
  178584. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  178585. /* strip the second byte of information from a 16-bit depth file. */
  178586. extern PNG_EXPORT(void,png_set_strip_16) PNGARG((png_structp png_ptr));
  178587. #endif
  178588. #if defined(PNG_READ_DITHER_SUPPORTED)
  178589. /* Turn on dithering, and reduce the palette to the number of colors available. */
  178590. extern PNG_EXPORT(void,png_set_dither) PNGARG((png_structp png_ptr,
  178591. png_colorp palette, int num_palette, int maximum_colors,
  178592. png_uint_16p histogram, int full_dither));
  178593. #endif
  178594. #if defined(PNG_READ_GAMMA_SUPPORTED)
  178595. /* Handle gamma correction. Screen_gamma=(display_exponent) */
  178596. #ifdef PNG_FLOATING_POINT_SUPPORTED
  178597. extern PNG_EXPORT(void,png_set_gamma) PNGARG((png_structp png_ptr,
  178598. double screen_gamma, double default_file_gamma));
  178599. #endif
  178600. #endif
  178601. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  178602. #if defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  178603. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  178604. /* Permit or disallow empty PLTE (0: not permitted, 1: permitted) */
  178605. /* Deprecated and will be removed. Use png_permit_mng_features() instead. */
  178606. extern PNG_EXPORT(void,png_permit_empty_plte) PNGARG((png_structp png_ptr,
  178607. int empty_plte_permitted));
  178608. #endif
  178609. #endif
  178610. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  178611. /* Set how many lines between output flushes - 0 for no flushing */
  178612. extern PNG_EXPORT(void,png_set_flush) PNGARG((png_structp png_ptr, int nrows));
  178613. /* Flush the current PNG output buffer */
  178614. extern PNG_EXPORT(void,png_write_flush) PNGARG((png_structp png_ptr));
  178615. #endif
  178616. /* optional update palette with requested transformations */
  178617. extern PNG_EXPORT(void,png_start_read_image) PNGARG((png_structp png_ptr));
  178618. /* optional call to update the users info structure */
  178619. extern PNG_EXPORT(void,png_read_update_info) PNGARG((png_structp png_ptr,
  178620. png_infop info_ptr));
  178621. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  178622. /* read one or more rows of image data. */
  178623. extern PNG_EXPORT(void,png_read_rows) PNGARG((png_structp png_ptr,
  178624. png_bytepp row, png_bytepp display_row, png_uint_32 num_rows));
  178625. #endif
  178626. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  178627. /* read a row of data. */
  178628. extern PNG_EXPORT(void,png_read_row) PNGARG((png_structp png_ptr,
  178629. png_bytep row,
  178630. png_bytep display_row));
  178631. #endif
  178632. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  178633. /* read the whole image into memory at once. */
  178634. extern PNG_EXPORT(void,png_read_image) PNGARG((png_structp png_ptr,
  178635. png_bytepp image));
  178636. #endif
  178637. /* write a row of image data */
  178638. extern PNG_EXPORT(void,png_write_row) PNGARG((png_structp png_ptr,
  178639. png_bytep row));
  178640. /* write a few rows of image data */
  178641. extern PNG_EXPORT(void,png_write_rows) PNGARG((png_structp png_ptr,
  178642. png_bytepp row, png_uint_32 num_rows));
  178643. /* write the image data */
  178644. extern PNG_EXPORT(void,png_write_image) PNGARG((png_structp png_ptr,
  178645. png_bytepp image));
  178646. /* writes the end of the PNG file. */
  178647. extern PNG_EXPORT(void,png_write_end) PNGARG((png_structp png_ptr,
  178648. png_infop info_ptr));
  178649. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  178650. /* read the end of the PNG file. */
  178651. extern PNG_EXPORT(void,png_read_end) PNGARG((png_structp png_ptr,
  178652. png_infop info_ptr));
  178653. #endif
  178654. /* free any memory associated with the png_info_struct */
  178655. extern PNG_EXPORT(void,png_destroy_info_struct) PNGARG((png_structp png_ptr,
  178656. png_infopp info_ptr_ptr));
  178657. /* free any memory associated with the png_struct and the png_info_structs */
  178658. extern PNG_EXPORT(void,png_destroy_read_struct) PNGARG((png_structpp
  178659. png_ptr_ptr, png_infopp info_ptr_ptr, png_infopp end_info_ptr_ptr));
  178660. /* free all memory used by the read (old method - NOT DLL EXPORTED) */
  178661. extern void png_read_destroy PNGARG((png_structp png_ptr, png_infop info_ptr,
  178662. png_infop end_info_ptr));
  178663. /* free any memory associated with the png_struct and the png_info_structs */
  178664. extern PNG_EXPORT(void,png_destroy_write_struct)
  178665. PNGARG((png_structpp png_ptr_ptr, png_infopp info_ptr_ptr));
  178666. /* free any memory used in png_ptr struct (old method - NOT DLL EXPORTED) */
  178667. extern void png_write_destroy PNGARG((png_structp png_ptr));
  178668. /* set the libpng method of handling chunk CRC errors */
  178669. extern PNG_EXPORT(void,png_set_crc_action) PNGARG((png_structp png_ptr,
  178670. int crit_action, int ancil_action));
  178671. /* Values for png_set_crc_action() to say how to handle CRC errors in
  178672. * ancillary and critical chunks, and whether to use the data contained
  178673. * therein. Note that it is impossible to "discard" data in a critical
  178674. * chunk. For versions prior to 0.90, the action was always error/quit,
  178675. * whereas in version 0.90 and later, the action for CRC errors in ancillary
  178676. * chunks is warn/discard. These values should NOT be changed.
  178677. *
  178678. * value action:critical action:ancillary
  178679. */
  178680. #define PNG_CRC_DEFAULT 0 /* error/quit warn/discard data */
  178681. #define PNG_CRC_ERROR_QUIT 1 /* error/quit error/quit */
  178682. #define PNG_CRC_WARN_DISCARD 2 /* (INVALID) warn/discard data */
  178683. #define PNG_CRC_WARN_USE 3 /* warn/use data warn/use data */
  178684. #define PNG_CRC_QUIET_USE 4 /* quiet/use data quiet/use data */
  178685. #define PNG_CRC_NO_CHANGE 5 /* use current value use current value */
  178686. /* These functions give the user control over the scan-line filtering in
  178687. * libpng and the compression methods used by zlib. These functions are
  178688. * mainly useful for testing, as the defaults should work with most users.
  178689. * Those users who are tight on memory or want faster performance at the
  178690. * expense of compression can modify them. See the compression library
  178691. * header file (zlib.h) for an explination of the compression functions.
  178692. */
  178693. /* set the filtering method(s) used by libpng. Currently, the only valid
  178694. * value for "method" is 0.
  178695. */
  178696. extern PNG_EXPORT(void,png_set_filter) PNGARG((png_structp png_ptr, int method,
  178697. int filters));
  178698. /* Flags for png_set_filter() to say which filters to use. The flags
  178699. * are chosen so that they don't conflict with real filter types
  178700. * below, in case they are supplied instead of the #defined constants.
  178701. * These values should NOT be changed.
  178702. */
  178703. #define PNG_NO_FILTERS 0x00
  178704. #define PNG_FILTER_NONE 0x08
  178705. #define PNG_FILTER_SUB 0x10
  178706. #define PNG_FILTER_UP 0x20
  178707. #define PNG_FILTER_AVG 0x40
  178708. #define PNG_FILTER_PAETH 0x80
  178709. #define PNG_ALL_FILTERS (PNG_FILTER_NONE | PNG_FILTER_SUB | PNG_FILTER_UP | \
  178710. PNG_FILTER_AVG | PNG_FILTER_PAETH)
  178711. /* Filter values (not flags) - used in pngwrite.c, pngwutil.c for now.
  178712. * These defines should NOT be changed.
  178713. */
  178714. #define PNG_FILTER_VALUE_NONE 0
  178715. #define PNG_FILTER_VALUE_SUB 1
  178716. #define PNG_FILTER_VALUE_UP 2
  178717. #define PNG_FILTER_VALUE_AVG 3
  178718. #define PNG_FILTER_VALUE_PAETH 4
  178719. #define PNG_FILTER_VALUE_LAST 5
  178720. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED) /* EXPERIMENTAL */
  178721. /* The "heuristic_method" is given by one of the PNG_FILTER_HEURISTIC_
  178722. * defines, either the default (minimum-sum-of-absolute-differences), or
  178723. * the experimental method (weighted-minimum-sum-of-absolute-differences).
  178724. *
  178725. * Weights are factors >= 1.0, indicating how important it is to keep the
  178726. * filter type consistent between rows. Larger numbers mean the current
  178727. * filter is that many times as likely to be the same as the "num_weights"
  178728. * previous filters. This is cumulative for each previous row with a weight.
  178729. * There needs to be "num_weights" values in "filter_weights", or it can be
  178730. * NULL if the weights aren't being specified. Weights have no influence on
  178731. * the selection of the first row filter. Well chosen weights can (in theory)
  178732. * improve the compression for a given image.
  178733. *
  178734. * Costs are factors >= 1.0 indicating the relative decoding costs of a
  178735. * filter type. Higher costs indicate more decoding expense, and are
  178736. * therefore less likely to be selected over a filter with lower computational
  178737. * costs. There needs to be a value in "filter_costs" for each valid filter
  178738. * type (given by PNG_FILTER_VALUE_LAST), or it can be NULL if you aren't
  178739. * setting the costs. Costs try to improve the speed of decompression without
  178740. * unduly increasing the compressed image size.
  178741. *
  178742. * A negative weight or cost indicates the default value is to be used, and
  178743. * values in the range [0.0, 1.0) indicate the value is to remain unchanged.
  178744. * The default values for both weights and costs are currently 1.0, but may
  178745. * change if good general weighting/cost heuristics can be found. If both
  178746. * the weights and costs are set to 1.0, this degenerates the WEIGHTED method
  178747. * to the UNWEIGHTED method, but with added encoding time/computation.
  178748. */
  178749. #ifdef PNG_FLOATING_POINT_SUPPORTED
  178750. extern PNG_EXPORT(void,png_set_filter_heuristics) PNGARG((png_structp png_ptr,
  178751. int heuristic_method, int num_weights, png_doublep filter_weights,
  178752. png_doublep filter_costs));
  178753. #endif
  178754. #endif /* PNG_WRITE_WEIGHTED_FILTER_SUPPORTED */
  178755. /* Heuristic used for row filter selection. These defines should NOT be
  178756. * changed.
  178757. */
  178758. #define PNG_FILTER_HEURISTIC_DEFAULT 0 /* Currently "UNWEIGHTED" */
  178759. #define PNG_FILTER_HEURISTIC_UNWEIGHTED 1 /* Used by libpng < 0.95 */
  178760. #define PNG_FILTER_HEURISTIC_WEIGHTED 2 /* Experimental feature */
  178761. #define PNG_FILTER_HEURISTIC_LAST 3 /* Not a valid value */
  178762. /* Set the library compression level. Currently, valid values range from
  178763. * 0 - 9, corresponding directly to the zlib compression levels 0 - 9
  178764. * (0 - no compression, 9 - "maximal" compression). Note that tests have
  178765. * shown that zlib compression levels 3-6 usually perform as well as level 9
  178766. * for PNG images, and do considerably fewer caclulations. In the future,
  178767. * these values may not correspond directly to the zlib compression levels.
  178768. */
  178769. extern PNG_EXPORT(void,png_set_compression_level) PNGARG((png_structp png_ptr,
  178770. int level));
  178771. extern PNG_EXPORT(void,png_set_compression_mem_level)
  178772. PNGARG((png_structp png_ptr, int mem_level));
  178773. extern PNG_EXPORT(void,png_set_compression_strategy)
  178774. PNGARG((png_structp png_ptr, int strategy));
  178775. extern PNG_EXPORT(void,png_set_compression_window_bits)
  178776. PNGARG((png_structp png_ptr, int window_bits));
  178777. extern PNG_EXPORT(void,png_set_compression_method) PNGARG((png_structp png_ptr,
  178778. int method));
  178779. /* These next functions are called for input/output, memory, and error
  178780. * handling. They are in the file pngrio.c, pngwio.c, and pngerror.c,
  178781. * and call standard C I/O routines such as fread(), fwrite(), and
  178782. * fprintf(). These functions can be made to use other I/O routines
  178783. * at run time for those applications that need to handle I/O in a
  178784. * different manner by calling png_set_???_fn(). See libpng.txt for
  178785. * more information.
  178786. */
  178787. #if !defined(PNG_NO_STDIO)
  178788. /* Initialize the input/output for the PNG file to the default functions. */
  178789. extern PNG_EXPORT(void,png_init_io) PNGARG((png_structp png_ptr, png_FILE_p fp));
  178790. #endif
  178791. /* Replace the (error and abort), and warning functions with user
  178792. * supplied functions. If no messages are to be printed you must still
  178793. * write and use replacement functions. The replacement error_fn should
  178794. * still do a longjmp to the last setjmp location if you are using this
  178795. * method of error handling. If error_fn or warning_fn is NULL, the
  178796. * default function will be used.
  178797. */
  178798. extern PNG_EXPORT(void,png_set_error_fn) PNGARG((png_structp png_ptr,
  178799. png_voidp error_ptr, png_error_ptr error_fn, png_error_ptr warning_fn));
  178800. /* Return the user pointer associated with the error functions */
  178801. extern PNG_EXPORT(png_voidp,png_get_error_ptr) PNGARG((png_structp png_ptr));
  178802. /* Replace the default data output functions with a user supplied one(s).
  178803. * If buffered output is not used, then output_flush_fn can be set to NULL.
  178804. * If PNG_WRITE_FLUSH_SUPPORTED is not defined at libpng compile time
  178805. * output_flush_fn will be ignored (and thus can be NULL).
  178806. */
  178807. extern PNG_EXPORT(void,png_set_write_fn) PNGARG((png_structp png_ptr,
  178808. png_voidp io_ptr, png_rw_ptr write_data_fn, png_flush_ptr output_flush_fn));
  178809. /* Replace the default data input function with a user supplied one. */
  178810. extern PNG_EXPORT(void,png_set_read_fn) PNGARG((png_structp png_ptr,
  178811. png_voidp io_ptr, png_rw_ptr read_data_fn));
  178812. /* Return the user pointer associated with the I/O functions */
  178813. extern PNG_EXPORT(png_voidp,png_get_io_ptr) PNGARG((png_structp png_ptr));
  178814. extern PNG_EXPORT(void,png_set_read_status_fn) PNGARG((png_structp png_ptr,
  178815. png_read_status_ptr read_row_fn));
  178816. extern PNG_EXPORT(void,png_set_write_status_fn) PNGARG((png_structp png_ptr,
  178817. png_write_status_ptr write_row_fn));
  178818. #ifdef PNG_USER_MEM_SUPPORTED
  178819. /* Replace the default memory allocation functions with user supplied one(s). */
  178820. extern PNG_EXPORT(void,png_set_mem_fn) PNGARG((png_structp png_ptr,
  178821. png_voidp mem_ptr, png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  178822. /* Return the user pointer associated with the memory functions */
  178823. extern PNG_EXPORT(png_voidp,png_get_mem_ptr) PNGARG((png_structp png_ptr));
  178824. #endif
  178825. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  178826. defined(PNG_LEGACY_SUPPORTED)
  178827. extern PNG_EXPORT(void,png_set_read_user_transform_fn) PNGARG((png_structp
  178828. png_ptr, png_user_transform_ptr read_user_transform_fn));
  178829. #endif
  178830. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  178831. defined(PNG_LEGACY_SUPPORTED)
  178832. extern PNG_EXPORT(void,png_set_write_user_transform_fn) PNGARG((png_structp
  178833. png_ptr, png_user_transform_ptr write_user_transform_fn));
  178834. #endif
  178835. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  178836. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  178837. defined(PNG_LEGACY_SUPPORTED)
  178838. extern PNG_EXPORT(void,png_set_user_transform_info) PNGARG((png_structp
  178839. png_ptr, png_voidp user_transform_ptr, int user_transform_depth,
  178840. int user_transform_channels));
  178841. /* Return the user pointer associated with the user transform functions */
  178842. extern PNG_EXPORT(png_voidp,png_get_user_transform_ptr)
  178843. PNGARG((png_structp png_ptr));
  178844. #endif
  178845. #ifdef PNG_USER_CHUNKS_SUPPORTED
  178846. extern PNG_EXPORT(void,png_set_read_user_chunk_fn) PNGARG((png_structp png_ptr,
  178847. png_voidp user_chunk_ptr, png_user_chunk_ptr read_user_chunk_fn));
  178848. extern PNG_EXPORT(png_voidp,png_get_user_chunk_ptr) PNGARG((png_structp
  178849. png_ptr));
  178850. #endif
  178851. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  178852. /* Sets the function callbacks for the push reader, and a pointer to a
  178853. * user-defined structure available to the callback functions.
  178854. */
  178855. extern PNG_EXPORT(void,png_set_progressive_read_fn) PNGARG((png_structp png_ptr,
  178856. png_voidp progressive_ptr,
  178857. png_progressive_info_ptr info_fn, png_progressive_row_ptr row_fn,
  178858. png_progressive_end_ptr end_fn));
  178859. /* returns the user pointer associated with the push read functions */
  178860. extern PNG_EXPORT(png_voidp,png_get_progressive_ptr)
  178861. PNGARG((png_structp png_ptr));
  178862. /* function to be called when data becomes available */
  178863. extern PNG_EXPORT(void,png_process_data) PNGARG((png_structp png_ptr,
  178864. png_infop info_ptr, png_bytep buffer, png_size_t buffer_size));
  178865. /* function that combines rows. Not very much different than the
  178866. * png_combine_row() call. Is this even used?????
  178867. */
  178868. extern PNG_EXPORT(void,png_progressive_combine_row) PNGARG((png_structp png_ptr,
  178869. png_bytep old_row, png_bytep new_row));
  178870. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  178871. extern PNG_EXPORT(png_voidp,png_malloc) PNGARG((png_structp png_ptr,
  178872. png_uint_32 size));
  178873. #if defined(PNG_1_0_X)
  178874. # define png_malloc_warn png_malloc
  178875. #else
  178876. /* Added at libpng version 1.2.4 */
  178877. extern PNG_EXPORT(png_voidp,png_malloc_warn) PNGARG((png_structp png_ptr,
  178878. png_uint_32 size));
  178879. #endif
  178880. /* frees a pointer allocated by png_malloc() */
  178881. extern PNG_EXPORT(void,png_free) PNGARG((png_structp png_ptr, png_voidp ptr));
  178882. #if defined(PNG_1_0_X)
  178883. /* Function to allocate memory for zlib. */
  178884. extern PNG_EXPORT(voidpf,png_zalloc) PNGARG((voidpf png_ptr, uInt items,
  178885. uInt size));
  178886. /* Function to free memory for zlib */
  178887. extern PNG_EXPORT(void,png_zfree) PNGARG((voidpf png_ptr, voidpf ptr));
  178888. #endif
  178889. /* Free data that was allocated internally */
  178890. extern PNG_EXPORT(void,png_free_data) PNGARG((png_structp png_ptr,
  178891. png_infop info_ptr, png_uint_32 free_me, int num));
  178892. #ifdef PNG_FREE_ME_SUPPORTED
  178893. /* Reassign responsibility for freeing existing data, whether allocated
  178894. * by libpng or by the application */
  178895. extern PNG_EXPORT(void,png_data_freer) PNGARG((png_structp png_ptr,
  178896. png_infop info_ptr, int freer, png_uint_32 mask));
  178897. #endif
  178898. /* assignments for png_data_freer */
  178899. #define PNG_DESTROY_WILL_FREE_DATA 1
  178900. #define PNG_SET_WILL_FREE_DATA 1
  178901. #define PNG_USER_WILL_FREE_DATA 2
  178902. /* Flags for png_ptr->free_me and info_ptr->free_me */
  178903. #define PNG_FREE_HIST 0x0008
  178904. #define PNG_FREE_ICCP 0x0010
  178905. #define PNG_FREE_SPLT 0x0020
  178906. #define PNG_FREE_ROWS 0x0040
  178907. #define PNG_FREE_PCAL 0x0080
  178908. #define PNG_FREE_SCAL 0x0100
  178909. #define PNG_FREE_UNKN 0x0200
  178910. #define PNG_FREE_LIST 0x0400
  178911. #define PNG_FREE_PLTE 0x1000
  178912. #define PNG_FREE_TRNS 0x2000
  178913. #define PNG_FREE_TEXT 0x4000
  178914. #define PNG_FREE_ALL 0x7fff
  178915. #define PNG_FREE_MUL 0x4220 /* PNG_FREE_SPLT|PNG_FREE_TEXT|PNG_FREE_UNKN */
  178916. #ifdef PNG_USER_MEM_SUPPORTED
  178917. extern PNG_EXPORT(png_voidp,png_malloc_default) PNGARG((png_structp png_ptr,
  178918. png_uint_32 size));
  178919. extern PNG_EXPORT(void,png_free_default) PNGARG((png_structp png_ptr,
  178920. png_voidp ptr));
  178921. #endif
  178922. extern PNG_EXPORT(png_voidp,png_memcpy_check) PNGARG((png_structp png_ptr,
  178923. png_voidp s1, png_voidp s2, png_uint_32 size));
  178924. extern PNG_EXPORT(png_voidp,png_memset_check) PNGARG((png_structp png_ptr,
  178925. png_voidp s1, int value, png_uint_32 size));
  178926. #if defined(USE_FAR_KEYWORD) /* memory model conversion function */
  178927. extern void *png_far_to_near PNGARG((png_structp png_ptr,png_voidp ptr,
  178928. int check));
  178929. #endif /* USE_FAR_KEYWORD */
  178930. #ifndef PNG_NO_ERROR_TEXT
  178931. /* Fatal error in PNG image of libpng - can't continue */
  178932. extern PNG_EXPORT(void,png_error) PNGARG((png_structp png_ptr,
  178933. png_const_charp error_message));
  178934. /* The same, but the chunk name is prepended to the error string. */
  178935. extern PNG_EXPORT(void,png_chunk_error) PNGARG((png_structp png_ptr,
  178936. png_const_charp error_message));
  178937. #else
  178938. /* Fatal error in PNG image of libpng - can't continue */
  178939. extern PNG_EXPORT(void,png_err) PNGARG((png_structp png_ptr));
  178940. #endif
  178941. #ifndef PNG_NO_WARNINGS
  178942. /* Non-fatal error in libpng. Can continue, but may have a problem. */
  178943. extern PNG_EXPORT(void,png_warning) PNGARG((png_structp png_ptr,
  178944. png_const_charp warning_message));
  178945. #ifdef PNG_READ_SUPPORTED
  178946. /* Non-fatal error in libpng, chunk name is prepended to message. */
  178947. extern PNG_EXPORT(void,png_chunk_warning) PNGARG((png_structp png_ptr,
  178948. png_const_charp warning_message));
  178949. #endif /* PNG_READ_SUPPORTED */
  178950. #endif /* PNG_NO_WARNINGS */
  178951. /* The png_set_<chunk> functions are for storing values in the png_info_struct.
  178952. * Similarly, the png_get_<chunk> calls are used to read values from the
  178953. * png_info_struct, either storing the parameters in the passed variables, or
  178954. * setting pointers into the png_info_struct where the data is stored. The
  178955. * png_get_<chunk> functions return a non-zero value if the data was available
  178956. * in info_ptr, or return zero and do not change any of the parameters if the
  178957. * data was not available.
  178958. *
  178959. * These functions should be used instead of directly accessing png_info
  178960. * to avoid problems with future changes in the size and internal layout of
  178961. * png_info_struct.
  178962. */
  178963. /* Returns "flag" if chunk data is valid in info_ptr. */
  178964. extern PNG_EXPORT(png_uint_32,png_get_valid) PNGARG((png_structp png_ptr,
  178965. png_infop info_ptr, png_uint_32 flag));
  178966. /* Returns number of bytes needed to hold a transformed row. */
  178967. extern PNG_EXPORT(png_uint_32,png_get_rowbytes) PNGARG((png_structp png_ptr,
  178968. png_infop info_ptr));
  178969. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  178970. /* Returns row_pointers, which is an array of pointers to scanlines that was
  178971. returned from png_read_png(). */
  178972. extern PNG_EXPORT(png_bytepp,png_get_rows) PNGARG((png_structp png_ptr,
  178973. png_infop info_ptr));
  178974. /* Set row_pointers, which is an array of pointers to scanlines for use
  178975. by png_write_png(). */
  178976. extern PNG_EXPORT(void,png_set_rows) PNGARG((png_structp png_ptr,
  178977. png_infop info_ptr, png_bytepp row_pointers));
  178978. #endif
  178979. /* Returns number of color channels in image. */
  178980. extern PNG_EXPORT(png_byte,png_get_channels) PNGARG((png_structp png_ptr,
  178981. png_infop info_ptr));
  178982. #ifdef PNG_EASY_ACCESS_SUPPORTED
  178983. /* Returns image width in pixels. */
  178984. extern PNG_EXPORT(png_uint_32, png_get_image_width) PNGARG((png_structp
  178985. png_ptr, png_infop info_ptr));
  178986. /* Returns image height in pixels. */
  178987. extern PNG_EXPORT(png_uint_32, png_get_image_height) PNGARG((png_structp
  178988. png_ptr, png_infop info_ptr));
  178989. /* Returns image bit_depth. */
  178990. extern PNG_EXPORT(png_byte, png_get_bit_depth) PNGARG((png_structp
  178991. png_ptr, png_infop info_ptr));
  178992. /* Returns image color_type. */
  178993. extern PNG_EXPORT(png_byte, png_get_color_type) PNGARG((png_structp
  178994. png_ptr, png_infop info_ptr));
  178995. /* Returns image filter_type. */
  178996. extern PNG_EXPORT(png_byte, png_get_filter_type) PNGARG((png_structp
  178997. png_ptr, png_infop info_ptr));
  178998. /* Returns image interlace_type. */
  178999. extern PNG_EXPORT(png_byte, png_get_interlace_type) PNGARG((png_structp
  179000. png_ptr, png_infop info_ptr));
  179001. /* Returns image compression_type. */
  179002. extern PNG_EXPORT(png_byte, png_get_compression_type) PNGARG((png_structp
  179003. png_ptr, png_infop info_ptr));
  179004. /* Returns image resolution in pixels per meter, from pHYs chunk data. */
  179005. extern PNG_EXPORT(png_uint_32, png_get_pixels_per_meter) PNGARG((png_structp
  179006. png_ptr, png_infop info_ptr));
  179007. extern PNG_EXPORT(png_uint_32, png_get_x_pixels_per_meter) PNGARG((png_structp
  179008. png_ptr, png_infop info_ptr));
  179009. extern PNG_EXPORT(png_uint_32, png_get_y_pixels_per_meter) PNGARG((png_structp
  179010. png_ptr, png_infop info_ptr));
  179011. /* Returns pixel aspect ratio, computed from pHYs chunk data. */
  179012. #ifdef PNG_FLOATING_POINT_SUPPORTED
  179013. extern PNG_EXPORT(float, png_get_pixel_aspect_ratio) PNGARG((png_structp
  179014. png_ptr, png_infop info_ptr));
  179015. #endif
  179016. /* Returns image x, y offset in pixels or microns, from oFFs chunk data. */
  179017. extern PNG_EXPORT(png_int_32, png_get_x_offset_pixels) PNGARG((png_structp
  179018. png_ptr, png_infop info_ptr));
  179019. extern PNG_EXPORT(png_int_32, png_get_y_offset_pixels) PNGARG((png_structp
  179020. png_ptr, png_infop info_ptr));
  179021. extern PNG_EXPORT(png_int_32, png_get_x_offset_microns) PNGARG((png_structp
  179022. png_ptr, png_infop info_ptr));
  179023. extern PNG_EXPORT(png_int_32, png_get_y_offset_microns) PNGARG((png_structp
  179024. png_ptr, png_infop info_ptr));
  179025. #endif /* PNG_EASY_ACCESS_SUPPORTED */
  179026. /* Returns pointer to signature string read from PNG header */
  179027. extern PNG_EXPORT(png_bytep,png_get_signature) PNGARG((png_structp png_ptr,
  179028. png_infop info_ptr));
  179029. #if defined(PNG_bKGD_SUPPORTED)
  179030. extern PNG_EXPORT(png_uint_32,png_get_bKGD) PNGARG((png_structp png_ptr,
  179031. png_infop info_ptr, png_color_16p *background));
  179032. #endif
  179033. #if defined(PNG_bKGD_SUPPORTED)
  179034. extern PNG_EXPORT(void,png_set_bKGD) PNGARG((png_structp png_ptr,
  179035. png_infop info_ptr, png_color_16p background));
  179036. #endif
  179037. #if defined(PNG_cHRM_SUPPORTED)
  179038. #ifdef PNG_FLOATING_POINT_SUPPORTED
  179039. extern PNG_EXPORT(png_uint_32,png_get_cHRM) PNGARG((png_structp png_ptr,
  179040. png_infop info_ptr, double *white_x, double *white_y, double *red_x,
  179041. double *red_y, double *green_x, double *green_y, double *blue_x,
  179042. double *blue_y));
  179043. #endif
  179044. #ifdef PNG_FIXED_POINT_SUPPORTED
  179045. extern PNG_EXPORT(png_uint_32,png_get_cHRM_fixed) PNGARG((png_structp png_ptr,
  179046. png_infop info_ptr, png_fixed_point *int_white_x, png_fixed_point
  179047. *int_white_y, png_fixed_point *int_red_x, png_fixed_point *int_red_y,
  179048. png_fixed_point *int_green_x, png_fixed_point *int_green_y, png_fixed_point
  179049. *int_blue_x, png_fixed_point *int_blue_y));
  179050. #endif
  179051. #endif
  179052. #if defined(PNG_cHRM_SUPPORTED)
  179053. #ifdef PNG_FLOATING_POINT_SUPPORTED
  179054. extern PNG_EXPORT(void,png_set_cHRM) PNGARG((png_structp png_ptr,
  179055. png_infop info_ptr, double white_x, double white_y, double red_x,
  179056. double red_y, double green_x, double green_y, double blue_x, double blue_y));
  179057. #endif
  179058. #ifdef PNG_FIXED_POINT_SUPPORTED
  179059. extern PNG_EXPORT(void,png_set_cHRM_fixed) PNGARG((png_structp png_ptr,
  179060. png_infop info_ptr, png_fixed_point int_white_x, png_fixed_point int_white_y,
  179061. png_fixed_point int_red_x, png_fixed_point int_red_y, png_fixed_point
  179062. int_green_x, png_fixed_point int_green_y, png_fixed_point int_blue_x,
  179063. png_fixed_point int_blue_y));
  179064. #endif
  179065. #endif
  179066. #if defined(PNG_gAMA_SUPPORTED)
  179067. #ifdef PNG_FLOATING_POINT_SUPPORTED
  179068. extern PNG_EXPORT(png_uint_32,png_get_gAMA) PNGARG((png_structp png_ptr,
  179069. png_infop info_ptr, double *file_gamma));
  179070. #endif
  179071. extern PNG_EXPORT(png_uint_32,png_get_gAMA_fixed) PNGARG((png_structp png_ptr,
  179072. png_infop info_ptr, png_fixed_point *int_file_gamma));
  179073. #endif
  179074. #if defined(PNG_gAMA_SUPPORTED)
  179075. #ifdef PNG_FLOATING_POINT_SUPPORTED
  179076. extern PNG_EXPORT(void,png_set_gAMA) PNGARG((png_structp png_ptr,
  179077. png_infop info_ptr, double file_gamma));
  179078. #endif
  179079. extern PNG_EXPORT(void,png_set_gAMA_fixed) PNGARG((png_structp png_ptr,
  179080. png_infop info_ptr, png_fixed_point int_file_gamma));
  179081. #endif
  179082. #if defined(PNG_hIST_SUPPORTED)
  179083. extern PNG_EXPORT(png_uint_32,png_get_hIST) PNGARG((png_structp png_ptr,
  179084. png_infop info_ptr, png_uint_16p *hist));
  179085. #endif
  179086. #if defined(PNG_hIST_SUPPORTED)
  179087. extern PNG_EXPORT(void,png_set_hIST) PNGARG((png_structp png_ptr,
  179088. png_infop info_ptr, png_uint_16p hist));
  179089. #endif
  179090. extern PNG_EXPORT(png_uint_32,png_get_IHDR) PNGARG((png_structp png_ptr,
  179091. png_infop info_ptr, png_uint_32 *width, png_uint_32 *height,
  179092. int *bit_depth, int *color_type, int *interlace_method,
  179093. int *compression_method, int *filter_method));
  179094. extern PNG_EXPORT(void,png_set_IHDR) PNGARG((png_structp png_ptr,
  179095. png_infop info_ptr, png_uint_32 width, png_uint_32 height, int bit_depth,
  179096. int color_type, int interlace_method, int compression_method,
  179097. int filter_method));
  179098. #if defined(PNG_oFFs_SUPPORTED)
  179099. extern PNG_EXPORT(png_uint_32,png_get_oFFs) PNGARG((png_structp png_ptr,
  179100. png_infop info_ptr, png_int_32 *offset_x, png_int_32 *offset_y,
  179101. int *unit_type));
  179102. #endif
  179103. #if defined(PNG_oFFs_SUPPORTED)
  179104. extern PNG_EXPORT(void,png_set_oFFs) PNGARG((png_structp png_ptr,
  179105. png_infop info_ptr, png_int_32 offset_x, png_int_32 offset_y,
  179106. int unit_type));
  179107. #endif
  179108. #if defined(PNG_pCAL_SUPPORTED)
  179109. extern PNG_EXPORT(png_uint_32,png_get_pCAL) PNGARG((png_structp png_ptr,
  179110. png_infop info_ptr, png_charp *purpose, png_int_32 *X0, png_int_32 *X1,
  179111. int *type, int *nparams, png_charp *units, png_charpp *params));
  179112. #endif
  179113. #if defined(PNG_pCAL_SUPPORTED)
  179114. extern PNG_EXPORT(void,png_set_pCAL) PNGARG((png_structp png_ptr,
  179115. png_infop info_ptr, png_charp purpose, png_int_32 X0, png_int_32 X1,
  179116. int type, int nparams, png_charp units, png_charpp params));
  179117. #endif
  179118. #if defined(PNG_pHYs_SUPPORTED)
  179119. extern PNG_EXPORT(png_uint_32,png_get_pHYs) PNGARG((png_structp png_ptr,
  179120. png_infop info_ptr, png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type));
  179121. #endif
  179122. #if defined(PNG_pHYs_SUPPORTED)
  179123. extern PNG_EXPORT(void,png_set_pHYs) PNGARG((png_structp png_ptr,
  179124. png_infop info_ptr, png_uint_32 res_x, png_uint_32 res_y, int unit_type));
  179125. #endif
  179126. extern PNG_EXPORT(png_uint_32,png_get_PLTE) PNGARG((png_structp png_ptr,
  179127. png_infop info_ptr, png_colorp *palette, int *num_palette));
  179128. extern PNG_EXPORT(void,png_set_PLTE) PNGARG((png_structp png_ptr,
  179129. png_infop info_ptr, png_colorp palette, int num_palette));
  179130. #if defined(PNG_sBIT_SUPPORTED)
  179131. extern PNG_EXPORT(png_uint_32,png_get_sBIT) PNGARG((png_structp png_ptr,
  179132. png_infop info_ptr, png_color_8p *sig_bit));
  179133. #endif
  179134. #if defined(PNG_sBIT_SUPPORTED)
  179135. extern PNG_EXPORT(void,png_set_sBIT) PNGARG((png_structp png_ptr,
  179136. png_infop info_ptr, png_color_8p sig_bit));
  179137. #endif
  179138. #if defined(PNG_sRGB_SUPPORTED)
  179139. extern PNG_EXPORT(png_uint_32,png_get_sRGB) PNGARG((png_structp png_ptr,
  179140. png_infop info_ptr, int *intent));
  179141. #endif
  179142. #if defined(PNG_sRGB_SUPPORTED)
  179143. extern PNG_EXPORT(void,png_set_sRGB) PNGARG((png_structp png_ptr,
  179144. png_infop info_ptr, int intent));
  179145. extern PNG_EXPORT(void,png_set_sRGB_gAMA_and_cHRM) PNGARG((png_structp png_ptr,
  179146. png_infop info_ptr, int intent));
  179147. #endif
  179148. #if defined(PNG_iCCP_SUPPORTED)
  179149. extern PNG_EXPORT(png_uint_32,png_get_iCCP) PNGARG((png_structp png_ptr,
  179150. png_infop info_ptr, png_charpp name, int *compression_type,
  179151. png_charpp profile, png_uint_32 *proflen));
  179152. /* Note to maintainer: profile should be png_bytepp */
  179153. #endif
  179154. #if defined(PNG_iCCP_SUPPORTED)
  179155. extern PNG_EXPORT(void,png_set_iCCP) PNGARG((png_structp png_ptr,
  179156. png_infop info_ptr, png_charp name, int compression_type,
  179157. png_charp profile, png_uint_32 proflen));
  179158. /* Note to maintainer: profile should be png_bytep */
  179159. #endif
  179160. #if defined(PNG_sPLT_SUPPORTED)
  179161. extern PNG_EXPORT(png_uint_32,png_get_sPLT) PNGARG((png_structp png_ptr,
  179162. png_infop info_ptr, png_sPLT_tpp entries));
  179163. #endif
  179164. #if defined(PNG_sPLT_SUPPORTED)
  179165. extern PNG_EXPORT(void,png_set_sPLT) PNGARG((png_structp png_ptr,
  179166. png_infop info_ptr, png_sPLT_tp entries, int nentries));
  179167. #endif
  179168. #if defined(PNG_TEXT_SUPPORTED)
  179169. /* png_get_text also returns the number of text chunks in *num_text */
  179170. extern PNG_EXPORT(png_uint_32,png_get_text) PNGARG((png_structp png_ptr,
  179171. png_infop info_ptr, png_textp *text_ptr, int *num_text));
  179172. #endif
  179173. /*
  179174. * Note while png_set_text() will accept a structure whose text,
  179175. * language, and translated keywords are NULL pointers, the structure
  179176. * returned by png_get_text will always contain regular
  179177. * zero-terminated C strings. They might be empty strings but
  179178. * they will never be NULL pointers.
  179179. */
  179180. #if defined(PNG_TEXT_SUPPORTED)
  179181. extern PNG_EXPORT(void,png_set_text) PNGARG((png_structp png_ptr,
  179182. png_infop info_ptr, png_textp text_ptr, int num_text));
  179183. #endif
  179184. #if defined(PNG_tIME_SUPPORTED)
  179185. extern PNG_EXPORT(png_uint_32,png_get_tIME) PNGARG((png_structp png_ptr,
  179186. png_infop info_ptr, png_timep *mod_time));
  179187. #endif
  179188. #if defined(PNG_tIME_SUPPORTED)
  179189. extern PNG_EXPORT(void,png_set_tIME) PNGARG((png_structp png_ptr,
  179190. png_infop info_ptr, png_timep mod_time));
  179191. #endif
  179192. #if defined(PNG_tRNS_SUPPORTED)
  179193. extern PNG_EXPORT(png_uint_32,png_get_tRNS) PNGARG((png_structp png_ptr,
  179194. png_infop info_ptr, png_bytep *trans, int *num_trans,
  179195. png_color_16p *trans_values));
  179196. #endif
  179197. #if defined(PNG_tRNS_SUPPORTED)
  179198. extern PNG_EXPORT(void,png_set_tRNS) PNGARG((png_structp png_ptr,
  179199. png_infop info_ptr, png_bytep trans, int num_trans,
  179200. png_color_16p trans_values));
  179201. #endif
  179202. #if defined(PNG_tRNS_SUPPORTED)
  179203. #endif
  179204. #if defined(PNG_sCAL_SUPPORTED)
  179205. #ifdef PNG_FLOATING_POINT_SUPPORTED
  179206. extern PNG_EXPORT(png_uint_32,png_get_sCAL) PNGARG((png_structp png_ptr,
  179207. png_infop info_ptr, int *unit, double *width, double *height));
  179208. #else
  179209. #ifdef PNG_FIXED_POINT_SUPPORTED
  179210. extern PNG_EXPORT(png_uint_32,png_get_sCAL_s) PNGARG((png_structp png_ptr,
  179211. png_infop info_ptr, int *unit, png_charpp swidth, png_charpp sheight));
  179212. #endif
  179213. #endif
  179214. #endif /* PNG_sCAL_SUPPORTED */
  179215. #if defined(PNG_sCAL_SUPPORTED)
  179216. #ifdef PNG_FLOATING_POINT_SUPPORTED
  179217. extern PNG_EXPORT(void,png_set_sCAL) PNGARG((png_structp png_ptr,
  179218. png_infop info_ptr, int unit, double width, double height));
  179219. #else
  179220. #ifdef PNG_FIXED_POINT_SUPPORTED
  179221. extern PNG_EXPORT(void,png_set_sCAL_s) PNGARG((png_structp png_ptr,
  179222. png_infop info_ptr, int unit, png_charp swidth, png_charp sheight));
  179223. #endif
  179224. #endif
  179225. #endif /* PNG_sCAL_SUPPORTED || PNG_WRITE_sCAL_SUPPORTED */
  179226. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  179227. /* provide a list of chunks and how they are to be handled, if the built-in
  179228. handling or default unknown chunk handling is not desired. Any chunks not
  179229. listed will be handled in the default manner. The IHDR and IEND chunks
  179230. must not be listed.
  179231. keep = 0: follow default behaviour
  179232. = 1: do not keep
  179233. = 2: keep only if safe-to-copy
  179234. = 3: keep even if unsafe-to-copy
  179235. */
  179236. extern PNG_EXPORT(void, png_set_keep_unknown_chunks) PNGARG((png_structp
  179237. png_ptr, int keep, png_bytep chunk_list, int num_chunks));
  179238. extern PNG_EXPORT(void, png_set_unknown_chunks) PNGARG((png_structp png_ptr,
  179239. png_infop info_ptr, png_unknown_chunkp unknowns, int num_unknowns));
  179240. extern PNG_EXPORT(void, png_set_unknown_chunk_location)
  179241. PNGARG((png_structp png_ptr, png_infop info_ptr, int chunk, int location));
  179242. extern PNG_EXPORT(png_uint_32,png_get_unknown_chunks) PNGARG((png_structp
  179243. png_ptr, png_infop info_ptr, png_unknown_chunkpp entries));
  179244. #endif
  179245. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  179246. PNG_EXPORT(int,png_handle_as_unknown) PNGARG((png_structp png_ptr, png_bytep
  179247. chunk_name));
  179248. #endif
  179249. /* Png_free_data() will turn off the "valid" flag for anything it frees.
  179250. If you need to turn it off for a chunk that your application has freed,
  179251. you can use png_set_invalid(png_ptr, info_ptr, PNG_INFO_CHNK); */
  179252. extern PNG_EXPORT(void, png_set_invalid) PNGARG((png_structp png_ptr,
  179253. png_infop info_ptr, int mask));
  179254. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  179255. /* The "params" pointer is currently not used and is for future expansion. */
  179256. extern PNG_EXPORT(void, png_read_png) PNGARG((png_structp png_ptr,
  179257. png_infop info_ptr,
  179258. int transforms,
  179259. png_voidp params));
  179260. extern PNG_EXPORT(void, png_write_png) PNGARG((png_structp png_ptr,
  179261. png_infop info_ptr,
  179262. int transforms,
  179263. png_voidp params));
  179264. #endif
  179265. /* Define PNG_DEBUG at compile time for debugging information. Higher
  179266. * numbers for PNG_DEBUG mean more debugging information. This has
  179267. * only been added since version 0.95 so it is not implemented throughout
  179268. * libpng yet, but more support will be added as needed.
  179269. */
  179270. #ifdef PNG_DEBUG
  179271. #if (PNG_DEBUG > 0)
  179272. #if !defined(PNG_DEBUG_FILE) && defined(_MSC_VER)
  179273. #include <crtdbg.h>
  179274. #if (PNG_DEBUG > 1)
  179275. #define png_debug(l,m) _RPT0(_CRT_WARN,m)
  179276. #define png_debug1(l,m,p1) _RPT1(_CRT_WARN,m,p1)
  179277. #define png_debug2(l,m,p1,p2) _RPT2(_CRT_WARN,m,p1,p2)
  179278. #endif
  179279. #else /* PNG_DEBUG_FILE || !_MSC_VER */
  179280. #ifndef PNG_DEBUG_FILE
  179281. #define PNG_DEBUG_FILE stderr
  179282. #endif /* PNG_DEBUG_FILE */
  179283. #if (PNG_DEBUG > 1)
  179284. #define png_debug(l,m) \
  179285. { \
  179286. int num_tabs=l; \
  179287. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  179288. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":"")))); \
  179289. }
  179290. #define png_debug1(l,m,p1) \
  179291. { \
  179292. int num_tabs=l; \
  179293. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  179294. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":""))),p1); \
  179295. }
  179296. #define png_debug2(l,m,p1,p2) \
  179297. { \
  179298. int num_tabs=l; \
  179299. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  179300. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":""))),p1,p2); \
  179301. }
  179302. #endif /* (PNG_DEBUG > 1) */
  179303. #endif /* _MSC_VER */
  179304. #endif /* (PNG_DEBUG > 0) */
  179305. #endif /* PNG_DEBUG */
  179306. #ifndef png_debug
  179307. #define png_debug(l, m)
  179308. #endif
  179309. #ifndef png_debug1
  179310. #define png_debug1(l, m, p1)
  179311. #endif
  179312. #ifndef png_debug2
  179313. #define png_debug2(l, m, p1, p2)
  179314. #endif
  179315. extern PNG_EXPORT(png_charp,png_get_copyright) PNGARG((png_structp png_ptr));
  179316. extern PNG_EXPORT(png_charp,png_get_header_ver) PNGARG((png_structp png_ptr));
  179317. extern PNG_EXPORT(png_charp,png_get_header_version) PNGARG((png_structp png_ptr));
  179318. extern PNG_EXPORT(png_charp,png_get_libpng_ver) PNGARG((png_structp png_ptr));
  179319. #ifdef PNG_MNG_FEATURES_SUPPORTED
  179320. extern PNG_EXPORT(png_uint_32,png_permit_mng_features) PNGARG((png_structp
  179321. png_ptr, png_uint_32 mng_features_permitted));
  179322. #endif
  179323. /* For use in png_set_keep_unknown, added to version 1.2.6 */
  179324. #define PNG_HANDLE_CHUNK_AS_DEFAULT 0
  179325. #define PNG_HANDLE_CHUNK_NEVER 1
  179326. #define PNG_HANDLE_CHUNK_IF_SAFE 2
  179327. #define PNG_HANDLE_CHUNK_ALWAYS 3
  179328. /* Added to version 1.2.0 */
  179329. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  179330. #if defined(PNG_MMX_CODE_SUPPORTED)
  179331. #define PNG_ASM_FLAG_MMX_SUPPORT_COMPILED 0x01 /* not user-settable */
  179332. #define PNG_ASM_FLAG_MMX_SUPPORT_IN_CPU 0x02 /* not user-settable */
  179333. #define PNG_ASM_FLAG_MMX_READ_COMBINE_ROW 0x04
  179334. #define PNG_ASM_FLAG_MMX_READ_INTERLACE 0x08
  179335. #define PNG_ASM_FLAG_MMX_READ_FILTER_SUB 0x10
  179336. #define PNG_ASM_FLAG_MMX_READ_FILTER_UP 0x20
  179337. #define PNG_ASM_FLAG_MMX_READ_FILTER_AVG 0x40
  179338. #define PNG_ASM_FLAG_MMX_READ_FILTER_PAETH 0x80
  179339. #define PNG_ASM_FLAGS_INITIALIZED 0x80000000 /* not user-settable */
  179340. #define PNG_MMX_READ_FLAGS ( PNG_ASM_FLAG_MMX_READ_COMBINE_ROW \
  179341. | PNG_ASM_FLAG_MMX_READ_INTERLACE \
  179342. | PNG_ASM_FLAG_MMX_READ_FILTER_SUB \
  179343. | PNG_ASM_FLAG_MMX_READ_FILTER_UP \
  179344. | PNG_ASM_FLAG_MMX_READ_FILTER_AVG \
  179345. | PNG_ASM_FLAG_MMX_READ_FILTER_PAETH )
  179346. #define PNG_MMX_WRITE_FLAGS ( 0 )
  179347. #define PNG_MMX_FLAGS ( PNG_ASM_FLAG_MMX_SUPPORT_COMPILED \
  179348. | PNG_ASM_FLAG_MMX_SUPPORT_IN_CPU \
  179349. | PNG_MMX_READ_FLAGS \
  179350. | PNG_MMX_WRITE_FLAGS )
  179351. #define PNG_SELECT_READ 1
  179352. #define PNG_SELECT_WRITE 2
  179353. #endif /* PNG_MMX_CODE_SUPPORTED */
  179354. #if !defined(PNG_1_0_X)
  179355. /* pngget.c */
  179356. extern PNG_EXPORT(png_uint_32,png_get_mmx_flagmask)
  179357. PNGARG((int flag_select, int *compilerID));
  179358. /* pngget.c */
  179359. extern PNG_EXPORT(png_uint_32,png_get_asm_flagmask)
  179360. PNGARG((int flag_select));
  179361. /* pngget.c */
  179362. extern PNG_EXPORT(png_uint_32,png_get_asm_flags)
  179363. PNGARG((png_structp png_ptr));
  179364. /* pngget.c */
  179365. extern PNG_EXPORT(png_byte,png_get_mmx_bitdepth_threshold)
  179366. PNGARG((png_structp png_ptr));
  179367. /* pngget.c */
  179368. extern PNG_EXPORT(png_uint_32,png_get_mmx_rowbytes_threshold)
  179369. PNGARG((png_structp png_ptr));
  179370. /* pngset.c */
  179371. extern PNG_EXPORT(void,png_set_asm_flags)
  179372. PNGARG((png_structp png_ptr, png_uint_32 asm_flags));
  179373. /* pngset.c */
  179374. extern PNG_EXPORT(void,png_set_mmx_thresholds)
  179375. PNGARG((png_structp png_ptr, png_byte mmx_bitdepth_threshold,
  179376. png_uint_32 mmx_rowbytes_threshold));
  179377. #endif /* PNG_1_0_X */
  179378. #if !defined(PNG_1_0_X)
  179379. /* png.c, pnggccrd.c, or pngvcrd.c */
  179380. extern PNG_EXPORT(int,png_mmx_support) PNGARG((void));
  179381. #endif /* PNG_ASSEMBLER_CODE_SUPPORTED */
  179382. /* Strip the prepended error numbers ("#nnn ") from error and warning
  179383. * messages before passing them to the error or warning handler. */
  179384. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  179385. extern PNG_EXPORT(void,png_set_strip_error_numbers) PNGARG((png_structp
  179386. png_ptr, png_uint_32 strip_mode));
  179387. #endif
  179388. #endif /* PNG_1_0_X */
  179389. /* Added at libpng-1.2.6 */
  179390. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  179391. extern PNG_EXPORT(void,png_set_user_limits) PNGARG((png_structp
  179392. png_ptr, png_uint_32 user_width_max, png_uint_32 user_height_max));
  179393. extern PNG_EXPORT(png_uint_32,png_get_user_width_max) PNGARG((png_structp
  179394. png_ptr));
  179395. extern PNG_EXPORT(png_uint_32,png_get_user_height_max) PNGARG((png_structp
  179396. png_ptr));
  179397. #endif
  179398. /* Maintainer: Put new public prototypes here ^, in libpng.3, and project defs */
  179399. #ifdef PNG_READ_COMPOSITE_NODIV_SUPPORTED
  179400. /* With these routines we avoid an integer divide, which will be slower on
  179401. * most machines. However, it does take more operations than the corresponding
  179402. * divide method, so it may be slower on a few RISC systems. There are two
  179403. * shifts (by 8 or 16 bits) and an addition, versus a single integer divide.
  179404. *
  179405. * Note that the rounding factors are NOT supposed to be the same! 128 and
  179406. * 32768 are correct for the NODIV code; 127 and 32767 are correct for the
  179407. * standard method.
  179408. *
  179409. * [Optimized code by Greg Roelofs and Mark Adler...blame us for bugs. :-) ]
  179410. */
  179411. /* fg and bg should be in `gamma 1.0' space; alpha is the opacity */
  179412. # define png_composite(composite, fg, alpha, bg) \
  179413. { png_uint_16 temp = (png_uint_16)((png_uint_16)(fg) * (png_uint_16)(alpha) \
  179414. + (png_uint_16)(bg)*(png_uint_16)(255 - \
  179415. (png_uint_16)(alpha)) + (png_uint_16)128); \
  179416. (composite) = (png_byte)((temp + (temp >> 8)) >> 8); }
  179417. # define png_composite_16(composite, fg, alpha, bg) \
  179418. { png_uint_32 temp = (png_uint_32)((png_uint_32)(fg) * (png_uint_32)(alpha) \
  179419. + (png_uint_32)(bg)*(png_uint_32)(65535L - \
  179420. (png_uint_32)(alpha)) + (png_uint_32)32768L); \
  179421. (composite) = (png_uint_16)((temp + (temp >> 16)) >> 16); }
  179422. #else /* standard method using integer division */
  179423. # define png_composite(composite, fg, alpha, bg) \
  179424. (composite) = (png_byte)(((png_uint_16)(fg) * (png_uint_16)(alpha) + \
  179425. (png_uint_16)(bg) * (png_uint_16)(255 - (png_uint_16)(alpha)) + \
  179426. (png_uint_16)127) / 255)
  179427. # define png_composite_16(composite, fg, alpha, bg) \
  179428. (composite) = (png_uint_16)(((png_uint_32)(fg) * (png_uint_32)(alpha) + \
  179429. (png_uint_32)(bg)*(png_uint_32)(65535L - (png_uint_32)(alpha)) + \
  179430. (png_uint_32)32767) / (png_uint_32)65535L)
  179431. #endif /* PNG_READ_COMPOSITE_NODIV_SUPPORTED */
  179432. /* Inline macros to do direct reads of bytes from the input buffer. These
  179433. * require that you are using an architecture that uses PNG byte ordering
  179434. * (MSB first) and supports unaligned data storage. I think that PowerPC
  179435. * in big-endian mode and 680x0 are the only ones that will support this.
  179436. * The x86 line of processors definitely do not. The png_get_int_32()
  179437. * routine also assumes we are using two's complement format for negative
  179438. * values, which is almost certainly true.
  179439. */
  179440. #if defined(PNG_READ_BIG_ENDIAN_SUPPORTED)
  179441. # define png_get_uint_32(buf) ( *((png_uint_32p) (buf)))
  179442. # define png_get_uint_16(buf) ( *((png_uint_16p) (buf)))
  179443. # define png_get_int_32(buf) ( *((png_int_32p) (buf)))
  179444. #else
  179445. extern PNG_EXPORT(png_uint_32,png_get_uint_32) PNGARG((png_bytep buf));
  179446. extern PNG_EXPORT(png_uint_16,png_get_uint_16) PNGARG((png_bytep buf));
  179447. extern PNG_EXPORT(png_int_32,png_get_int_32) PNGARG((png_bytep buf));
  179448. #endif /* !PNG_READ_BIG_ENDIAN_SUPPORTED */
  179449. extern PNG_EXPORT(png_uint_32,png_get_uint_31)
  179450. PNGARG((png_structp png_ptr, png_bytep buf));
  179451. /* No png_get_int_16 -- may be added if there's a real need for it. */
  179452. /* Place a 32-bit number into a buffer in PNG byte order (big-endian).
  179453. */
  179454. extern PNG_EXPORT(void,png_save_uint_32)
  179455. PNGARG((png_bytep buf, png_uint_32 i));
  179456. extern PNG_EXPORT(void,png_save_int_32)
  179457. PNGARG((png_bytep buf, png_int_32 i));
  179458. /* Place a 16-bit number into a buffer in PNG byte order.
  179459. * The parameter is declared unsigned int, not png_uint_16,
  179460. * just to avoid potential problems on pre-ANSI C compilers.
  179461. */
  179462. extern PNG_EXPORT(void,png_save_uint_16)
  179463. PNGARG((png_bytep buf, unsigned int i));
  179464. /* No png_save_int_16 -- may be added if there's a real need for it. */
  179465. /* ************************************************************************* */
  179466. /* These next functions are used internally in the code. They generally
  179467. * shouldn't be used unless you are writing code to add or replace some
  179468. * functionality in libpng. More information about most functions can
  179469. * be found in the files where the functions are located.
  179470. */
  179471. /* Various modes of operation, that are visible to applications because
  179472. * they are used for unknown chunk location.
  179473. */
  179474. #define PNG_HAVE_IHDR 0x01
  179475. #define PNG_HAVE_PLTE 0x02
  179476. #define PNG_HAVE_IDAT 0x04
  179477. #define PNG_AFTER_IDAT 0x08 /* Have complete zlib datastream */
  179478. #define PNG_HAVE_IEND 0x10
  179479. #if defined(PNG_INTERNAL)
  179480. /* More modes of operation. Note that after an init, mode is set to
  179481. * zero automatically when the structure is created.
  179482. */
  179483. #define PNG_HAVE_gAMA 0x20
  179484. #define PNG_HAVE_cHRM 0x40
  179485. #define PNG_HAVE_sRGB 0x80
  179486. #define PNG_HAVE_CHUNK_HEADER 0x100
  179487. #define PNG_WROTE_tIME 0x200
  179488. #define PNG_WROTE_INFO_BEFORE_PLTE 0x400
  179489. #define PNG_BACKGROUND_IS_GRAY 0x800
  179490. #define PNG_HAVE_PNG_SIGNATURE 0x1000
  179491. #define PNG_HAVE_CHUNK_AFTER_IDAT 0x2000 /* Have another chunk after IDAT */
  179492. /* flags for the transformations the PNG library does on the image data */
  179493. #define PNG_BGR 0x0001
  179494. #define PNG_INTERLACE 0x0002
  179495. #define PNG_PACK 0x0004
  179496. #define PNG_SHIFT 0x0008
  179497. #define PNG_SWAP_BYTES 0x0010
  179498. #define PNG_INVERT_MONO 0x0020
  179499. #define PNG_DITHER 0x0040
  179500. #define PNG_BACKGROUND 0x0080
  179501. #define PNG_BACKGROUND_EXPAND 0x0100
  179502. /* 0x0200 unused */
  179503. #define PNG_16_TO_8 0x0400
  179504. #define PNG_RGBA 0x0800
  179505. #define PNG_EXPAND 0x1000
  179506. #define PNG_GAMMA 0x2000
  179507. #define PNG_GRAY_TO_RGB 0x4000
  179508. #define PNG_FILLER 0x8000L
  179509. #define PNG_PACKSWAP 0x10000L
  179510. #define PNG_SWAP_ALPHA 0x20000L
  179511. #define PNG_STRIP_ALPHA 0x40000L
  179512. #define PNG_INVERT_ALPHA 0x80000L
  179513. #define PNG_USER_TRANSFORM 0x100000L
  179514. #define PNG_RGB_TO_GRAY_ERR 0x200000L
  179515. #define PNG_RGB_TO_GRAY_WARN 0x400000L
  179516. #define PNG_RGB_TO_GRAY 0x600000L /* two bits, RGB_TO_GRAY_ERR|WARN */
  179517. /* 0x800000L Unused */
  179518. #define PNG_ADD_ALPHA 0x1000000L /* Added to libpng-1.2.7 */
  179519. #define PNG_EXPAND_tRNS 0x2000000L /* Added to libpng-1.2.9 */
  179520. /* 0x4000000L unused */
  179521. /* 0x8000000L unused */
  179522. /* 0x10000000L unused */
  179523. /* 0x20000000L unused */
  179524. /* 0x40000000L unused */
  179525. /* flags for png_create_struct */
  179526. #define PNG_STRUCT_PNG 0x0001
  179527. #define PNG_STRUCT_INFO 0x0002
  179528. /* Scaling factor for filter heuristic weighting calculations */
  179529. #define PNG_WEIGHT_SHIFT 8
  179530. #define PNG_WEIGHT_FACTOR (1<<(PNG_WEIGHT_SHIFT))
  179531. #define PNG_COST_SHIFT 3
  179532. #define PNG_COST_FACTOR (1<<(PNG_COST_SHIFT))
  179533. /* flags for the png_ptr->flags rather than declaring a byte for each one */
  179534. #define PNG_FLAG_ZLIB_CUSTOM_STRATEGY 0x0001
  179535. #define PNG_FLAG_ZLIB_CUSTOM_LEVEL 0x0002
  179536. #define PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL 0x0004
  179537. #define PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS 0x0008
  179538. #define PNG_FLAG_ZLIB_CUSTOM_METHOD 0x0010
  179539. #define PNG_FLAG_ZLIB_FINISHED 0x0020
  179540. #define PNG_FLAG_ROW_INIT 0x0040
  179541. #define PNG_FLAG_FILLER_AFTER 0x0080
  179542. #define PNG_FLAG_CRC_ANCILLARY_USE 0x0100
  179543. #define PNG_FLAG_CRC_ANCILLARY_NOWARN 0x0200
  179544. #define PNG_FLAG_CRC_CRITICAL_USE 0x0400
  179545. #define PNG_FLAG_CRC_CRITICAL_IGNORE 0x0800
  179546. #define PNG_FLAG_FREE_PLTE 0x1000
  179547. #define PNG_FLAG_FREE_TRNS 0x2000
  179548. #define PNG_FLAG_FREE_HIST 0x4000
  179549. #define PNG_FLAG_KEEP_UNKNOWN_CHUNKS 0x8000L
  179550. #define PNG_FLAG_KEEP_UNSAFE_CHUNKS 0x10000L
  179551. #define PNG_FLAG_LIBRARY_MISMATCH 0x20000L
  179552. #define PNG_FLAG_STRIP_ERROR_NUMBERS 0x40000L
  179553. #define PNG_FLAG_STRIP_ERROR_TEXT 0x80000L
  179554. #define PNG_FLAG_MALLOC_NULL_MEM_OK 0x100000L
  179555. #define PNG_FLAG_ADD_ALPHA 0x200000L /* Added to libpng-1.2.8 */
  179556. #define PNG_FLAG_STRIP_ALPHA 0x400000L /* Added to libpng-1.2.8 */
  179557. /* 0x800000L unused */
  179558. /* 0x1000000L unused */
  179559. /* 0x2000000L unused */
  179560. /* 0x4000000L unused */
  179561. /* 0x8000000L unused */
  179562. /* 0x10000000L unused */
  179563. /* 0x20000000L unused */
  179564. /* 0x40000000L unused */
  179565. #define PNG_FLAG_CRC_ANCILLARY_MASK (PNG_FLAG_CRC_ANCILLARY_USE | \
  179566. PNG_FLAG_CRC_ANCILLARY_NOWARN)
  179567. #define PNG_FLAG_CRC_CRITICAL_MASK (PNG_FLAG_CRC_CRITICAL_USE | \
  179568. PNG_FLAG_CRC_CRITICAL_IGNORE)
  179569. #define PNG_FLAG_CRC_MASK (PNG_FLAG_CRC_ANCILLARY_MASK | \
  179570. PNG_FLAG_CRC_CRITICAL_MASK)
  179571. /* save typing and make code easier to understand */
  179572. #define PNG_COLOR_DIST(c1, c2) (abs((int)((c1).red) - (int)((c2).red)) + \
  179573. abs((int)((c1).green) - (int)((c2).green)) + \
  179574. abs((int)((c1).blue) - (int)((c2).blue)))
  179575. /* Added to libpng-1.2.6 JB */
  179576. #define PNG_ROWBYTES(pixel_bits, width) \
  179577. ((pixel_bits) >= 8 ? \
  179578. ((width) * (((png_uint_32)(pixel_bits)) >> 3)) : \
  179579. (( ((width) * ((png_uint_32)(pixel_bits))) + 7) >> 3) )
  179580. /* PNG_OUT_OF_RANGE returns true if value is outside the range
  179581. ideal-delta..ideal+delta. Each argument is evaluated twice.
  179582. "ideal" and "delta" should be constants, normally simple
  179583. integers, "value" a variable. Added to libpng-1.2.6 JB */
  179584. #define PNG_OUT_OF_RANGE(value, ideal, delta) \
  179585. ( (value) < (ideal)-(delta) || (value) > (ideal)+(delta) )
  179586. /* variables declared in png.c - only it needs to define PNG_NO_EXTERN */
  179587. #if !defined(PNG_NO_EXTERN) || defined(PNG_ALWAYS_EXTERN)
  179588. /* place to hold the signature string for a PNG file. */
  179589. #ifdef PNG_USE_GLOBAL_ARRAYS
  179590. PNG_EXPORT_VAR (PNG_CONST png_byte FARDATA) png_sig[8];
  179591. #else
  179592. #endif
  179593. #endif /* PNG_NO_EXTERN */
  179594. /* Constant strings for known chunk types. If you need to add a chunk,
  179595. * define the name here, and add an invocation of the macro in png.c and
  179596. * wherever it's needed.
  179597. */
  179598. #define PNG_IHDR png_byte png_IHDR[5] = { 73, 72, 68, 82, '\0'}
  179599. #define PNG_IDAT png_byte png_IDAT[5] = { 73, 68, 65, 84, '\0'}
  179600. #define PNG_IEND png_byte png_IEND[5] = { 73, 69, 78, 68, '\0'}
  179601. #define PNG_PLTE png_byte png_PLTE[5] = { 80, 76, 84, 69, '\0'}
  179602. #define PNG_bKGD png_byte png_bKGD[5] = { 98, 75, 71, 68, '\0'}
  179603. #define PNG_cHRM png_byte png_cHRM[5] = { 99, 72, 82, 77, '\0'}
  179604. #define PNG_gAMA png_byte png_gAMA[5] = {103, 65, 77, 65, '\0'}
  179605. #define PNG_hIST png_byte png_hIST[5] = {104, 73, 83, 84, '\0'}
  179606. #define PNG_iCCP png_byte png_iCCP[5] = {105, 67, 67, 80, '\0'}
  179607. #define PNG_iTXt png_byte png_iTXt[5] = {105, 84, 88, 116, '\0'}
  179608. #define PNG_oFFs png_byte png_oFFs[5] = {111, 70, 70, 115, '\0'}
  179609. #define PNG_pCAL png_byte png_pCAL[5] = {112, 67, 65, 76, '\0'}
  179610. #define PNG_sCAL png_byte png_sCAL[5] = {115, 67, 65, 76, '\0'}
  179611. #define PNG_pHYs png_byte png_pHYs[5] = {112, 72, 89, 115, '\0'}
  179612. #define PNG_sBIT png_byte png_sBIT[5] = {115, 66, 73, 84, '\0'}
  179613. #define PNG_sPLT png_byte png_sPLT[5] = {115, 80, 76, 84, '\0'}
  179614. #define PNG_sRGB png_byte png_sRGB[5] = {115, 82, 71, 66, '\0'}
  179615. #define PNG_tEXt png_byte png_tEXt[5] = {116, 69, 88, 116, '\0'}
  179616. #define PNG_tIME png_byte png_tIME[5] = {116, 73, 77, 69, '\0'}
  179617. #define PNG_tRNS png_byte png_tRNS[5] = {116, 82, 78, 83, '\0'}
  179618. #define PNG_zTXt png_byte png_zTXt[5] = {122, 84, 88, 116, '\0'}
  179619. #ifdef PNG_USE_GLOBAL_ARRAYS
  179620. PNG_EXPORT_VAR (png_byte FARDATA) png_IHDR[5];
  179621. PNG_EXPORT_VAR (png_byte FARDATA) png_IDAT[5];
  179622. PNG_EXPORT_VAR (png_byte FARDATA) png_IEND[5];
  179623. PNG_EXPORT_VAR (png_byte FARDATA) png_PLTE[5];
  179624. PNG_EXPORT_VAR (png_byte FARDATA) png_bKGD[5];
  179625. PNG_EXPORT_VAR (png_byte FARDATA) png_cHRM[5];
  179626. PNG_EXPORT_VAR (png_byte FARDATA) png_gAMA[5];
  179627. PNG_EXPORT_VAR (png_byte FARDATA) png_hIST[5];
  179628. PNG_EXPORT_VAR (png_byte FARDATA) png_iCCP[5];
  179629. PNG_EXPORT_VAR (png_byte FARDATA) png_iTXt[5];
  179630. PNG_EXPORT_VAR (png_byte FARDATA) png_oFFs[5];
  179631. PNG_EXPORT_VAR (png_byte FARDATA) png_pCAL[5];
  179632. PNG_EXPORT_VAR (png_byte FARDATA) png_sCAL[5];
  179633. PNG_EXPORT_VAR (png_byte FARDATA) png_pHYs[5];
  179634. PNG_EXPORT_VAR (png_byte FARDATA) png_sBIT[5];
  179635. PNG_EXPORT_VAR (png_byte FARDATA) png_sPLT[5];
  179636. PNG_EXPORT_VAR (png_byte FARDATA) png_sRGB[5];
  179637. PNG_EXPORT_VAR (png_byte FARDATA) png_tEXt[5];
  179638. PNG_EXPORT_VAR (png_byte FARDATA) png_tIME[5];
  179639. PNG_EXPORT_VAR (png_byte FARDATA) png_tRNS[5];
  179640. PNG_EXPORT_VAR (png_byte FARDATA) png_zTXt[5];
  179641. #endif /* PNG_USE_GLOBAL_ARRAYS */
  179642. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  179643. /* Initialize png_ptr struct for reading, and allocate any other memory.
  179644. * (old interface - DEPRECATED - use png_create_read_struct instead).
  179645. */
  179646. extern PNG_EXPORT(void,png_read_init) PNGARG((png_structp png_ptr));
  179647. #undef png_read_init
  179648. #define png_read_init(png_ptr) png_read_init_3(&png_ptr, \
  179649. PNG_LIBPNG_VER_STRING, png_sizeof(png_struct));
  179650. #endif
  179651. extern PNG_EXPORT(void,png_read_init_3) PNGARG((png_structpp ptr_ptr,
  179652. png_const_charp user_png_ver, png_size_t png_struct_size));
  179653. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  179654. extern PNG_EXPORT(void,png_read_init_2) PNGARG((png_structp png_ptr,
  179655. png_const_charp user_png_ver, png_size_t png_struct_size, png_size_t
  179656. png_info_size));
  179657. #endif
  179658. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  179659. /* Initialize png_ptr struct for writing, and allocate any other memory.
  179660. * (old interface - DEPRECATED - use png_create_write_struct instead).
  179661. */
  179662. extern PNG_EXPORT(void,png_write_init) PNGARG((png_structp png_ptr));
  179663. #undef png_write_init
  179664. #define png_write_init(png_ptr) png_write_init_3(&png_ptr, \
  179665. PNG_LIBPNG_VER_STRING, png_sizeof(png_struct));
  179666. #endif
  179667. extern PNG_EXPORT(void,png_write_init_3) PNGARG((png_structpp ptr_ptr,
  179668. png_const_charp user_png_ver, png_size_t png_struct_size));
  179669. extern PNG_EXPORT(void,png_write_init_2) PNGARG((png_structp png_ptr,
  179670. png_const_charp user_png_ver, png_size_t png_struct_size, png_size_t
  179671. png_info_size));
  179672. /* Allocate memory for an internal libpng struct */
  179673. PNG_EXTERN png_voidp png_create_struct PNGARG((int type));
  179674. /* Free memory from internal libpng struct */
  179675. PNG_EXTERN void png_destroy_struct PNGARG((png_voidp struct_ptr));
  179676. PNG_EXTERN png_voidp png_create_struct_2 PNGARG((int type, png_malloc_ptr
  179677. malloc_fn, png_voidp mem_ptr));
  179678. PNG_EXTERN void png_destroy_struct_2 PNGARG((png_voidp struct_ptr,
  179679. png_free_ptr free_fn, png_voidp mem_ptr));
  179680. /* Free any memory that info_ptr points to and reset struct. */
  179681. PNG_EXTERN void png_info_destroy PNGARG((png_structp png_ptr,
  179682. png_infop info_ptr));
  179683. #ifndef PNG_1_0_X
  179684. /* Function to allocate memory for zlib. */
  179685. PNG_EXTERN voidpf png_zalloc PNGARG((voidpf png_ptr, uInt items, uInt size));
  179686. /* Function to free memory for zlib */
  179687. PNG_EXTERN void png_zfree PNGARG((voidpf png_ptr, voidpf ptr));
  179688. #ifdef PNG_SIZE_T
  179689. /* Function to convert a sizeof an item to png_sizeof item */
  179690. PNG_EXTERN png_size_t PNGAPI png_convert_size PNGARG((size_t size));
  179691. #endif
  179692. /* Next four functions are used internally as callbacks. PNGAPI is required
  179693. * but not PNG_EXPORT. PNGAPI added at libpng version 1.2.3. */
  179694. PNG_EXTERN void PNGAPI png_default_read_data PNGARG((png_structp png_ptr,
  179695. png_bytep data, png_size_t length));
  179696. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  179697. PNG_EXTERN void PNGAPI png_push_fill_buffer PNGARG((png_structp png_ptr,
  179698. png_bytep buffer, png_size_t length));
  179699. #endif
  179700. PNG_EXTERN void PNGAPI png_default_write_data PNGARG((png_structp png_ptr,
  179701. png_bytep data, png_size_t length));
  179702. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  179703. #if !defined(PNG_NO_STDIO)
  179704. PNG_EXTERN void PNGAPI png_default_flush PNGARG((png_structp png_ptr));
  179705. #endif
  179706. #endif
  179707. #else /* PNG_1_0_X */
  179708. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  179709. PNG_EXTERN void png_push_fill_buffer PNGARG((png_structp png_ptr,
  179710. png_bytep buffer, png_size_t length));
  179711. #endif
  179712. #endif /* PNG_1_0_X */
  179713. /* Reset the CRC variable */
  179714. PNG_EXTERN void png_reset_crc PNGARG((png_structp png_ptr));
  179715. /* Write the "data" buffer to whatever output you are using. */
  179716. PNG_EXTERN void png_write_data PNGARG((png_structp png_ptr, png_bytep data,
  179717. png_size_t length));
  179718. /* Read data from whatever input you are using into the "data" buffer */
  179719. PNG_EXTERN void png_read_data PNGARG((png_structp png_ptr, png_bytep data,
  179720. png_size_t length));
  179721. /* Read bytes into buf, and update png_ptr->crc */
  179722. PNG_EXTERN void png_crc_read PNGARG((png_structp png_ptr, png_bytep buf,
  179723. png_size_t length));
  179724. /* Decompress data in a chunk that uses compression */
  179725. #if defined(PNG_zTXt_SUPPORTED) || defined(PNG_iTXt_SUPPORTED) || \
  179726. defined(PNG_iCCP_SUPPORTED) || defined(PNG_sPLT_SUPPORTED)
  179727. PNG_EXTERN png_charp png_decompress_chunk PNGARG((png_structp png_ptr,
  179728. int comp_type, png_charp chunkdata, png_size_t chunklength,
  179729. png_size_t prefix_length, png_size_t *data_length));
  179730. #endif
  179731. /* Read "skip" bytes, read the file crc, and (optionally) verify png_ptr->crc */
  179732. PNG_EXTERN int png_crc_finish PNGARG((png_structp png_ptr, png_uint_32 skip));
  179733. /* Read the CRC from the file and compare it to the libpng calculated CRC */
  179734. PNG_EXTERN int png_crc_error PNGARG((png_structp png_ptr));
  179735. /* Calculate the CRC over a section of data. Note that we are only
  179736. * passing a maximum of 64K on systems that have this as a memory limit,
  179737. * since this is the maximum buffer size we can specify.
  179738. */
  179739. PNG_EXTERN void png_calculate_crc PNGARG((png_structp png_ptr, png_bytep ptr,
  179740. png_size_t length));
  179741. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  179742. PNG_EXTERN void png_flush PNGARG((png_structp png_ptr));
  179743. #endif
  179744. /* simple function to write the signature */
  179745. PNG_EXTERN void png_write_sig PNGARG((png_structp png_ptr));
  179746. /* write various chunks */
  179747. /* Write the IHDR chunk, and update the png_struct with the necessary
  179748. * information.
  179749. */
  179750. PNG_EXTERN void png_write_IHDR PNGARG((png_structp png_ptr, png_uint_32 width,
  179751. png_uint_32 height,
  179752. int bit_depth, int color_type, int compression_method, int filter_method,
  179753. int interlace_method));
  179754. PNG_EXTERN void png_write_PLTE PNGARG((png_structp png_ptr, png_colorp palette,
  179755. png_uint_32 num_pal));
  179756. PNG_EXTERN void png_write_IDAT PNGARG((png_structp png_ptr, png_bytep data,
  179757. png_size_t length));
  179758. PNG_EXTERN void png_write_IEND PNGARG((png_structp png_ptr));
  179759. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  179760. #ifdef PNG_FLOATING_POINT_SUPPORTED
  179761. PNG_EXTERN void png_write_gAMA PNGARG((png_structp png_ptr, double file_gamma));
  179762. #endif
  179763. #ifdef PNG_FIXED_POINT_SUPPORTED
  179764. PNG_EXTERN void png_write_gAMA_fixed PNGARG((png_structp png_ptr, png_fixed_point
  179765. file_gamma));
  179766. #endif
  179767. #endif
  179768. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  179769. PNG_EXTERN void png_write_sBIT PNGARG((png_structp png_ptr, png_color_8p sbit,
  179770. int color_type));
  179771. #endif
  179772. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  179773. #ifdef PNG_FLOATING_POINT_SUPPORTED
  179774. PNG_EXTERN void png_write_cHRM PNGARG((png_structp png_ptr,
  179775. double white_x, double white_y,
  179776. double red_x, double red_y, double green_x, double green_y,
  179777. double blue_x, double blue_y));
  179778. #endif
  179779. #ifdef PNG_FIXED_POINT_SUPPORTED
  179780. PNG_EXTERN void png_write_cHRM_fixed PNGARG((png_structp png_ptr,
  179781. png_fixed_point int_white_x, png_fixed_point int_white_y,
  179782. png_fixed_point int_red_x, png_fixed_point int_red_y, png_fixed_point
  179783. int_green_x, png_fixed_point int_green_y, png_fixed_point int_blue_x,
  179784. png_fixed_point int_blue_y));
  179785. #endif
  179786. #endif
  179787. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  179788. PNG_EXTERN void png_write_sRGB PNGARG((png_structp png_ptr,
  179789. int intent));
  179790. #endif
  179791. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  179792. PNG_EXTERN void png_write_iCCP PNGARG((png_structp png_ptr,
  179793. png_charp name, int compression_type,
  179794. png_charp profile, int proflen));
  179795. /* Note to maintainer: profile should be png_bytep */
  179796. #endif
  179797. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  179798. PNG_EXTERN void png_write_sPLT PNGARG((png_structp png_ptr,
  179799. png_sPLT_tp palette));
  179800. #endif
  179801. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  179802. PNG_EXTERN void png_write_tRNS PNGARG((png_structp png_ptr, png_bytep trans,
  179803. png_color_16p values, int number, int color_type));
  179804. #endif
  179805. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  179806. PNG_EXTERN void png_write_bKGD PNGARG((png_structp png_ptr,
  179807. png_color_16p values, int color_type));
  179808. #endif
  179809. #if defined(PNG_WRITE_hIST_SUPPORTED)
  179810. PNG_EXTERN void png_write_hIST PNGARG((png_structp png_ptr, png_uint_16p hist,
  179811. int num_hist));
  179812. #endif
  179813. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_pCAL_SUPPORTED) || \
  179814. defined(PNG_WRITE_iCCP_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  179815. PNG_EXTERN png_size_t png_check_keyword PNGARG((png_structp png_ptr,
  179816. png_charp key, png_charpp new_key));
  179817. #endif
  179818. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  179819. PNG_EXTERN void png_write_tEXt PNGARG((png_structp png_ptr, png_charp key,
  179820. png_charp text, png_size_t text_len));
  179821. #endif
  179822. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  179823. PNG_EXTERN void png_write_zTXt PNGARG((png_structp png_ptr, png_charp key,
  179824. png_charp text, png_size_t text_len, int compression));
  179825. #endif
  179826. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  179827. PNG_EXTERN void png_write_iTXt PNGARG((png_structp png_ptr,
  179828. int compression, png_charp key, png_charp lang, png_charp lang_key,
  179829. png_charp text));
  179830. #endif
  179831. #if defined(PNG_TEXT_SUPPORTED) /* Added at version 1.0.14 and 1.2.4 */
  179832. PNG_EXTERN int png_set_text_2 PNGARG((png_structp png_ptr,
  179833. png_infop info_ptr, png_textp text_ptr, int num_text));
  179834. #endif
  179835. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  179836. PNG_EXTERN void png_write_oFFs PNGARG((png_structp png_ptr,
  179837. png_int_32 x_offset, png_int_32 y_offset, int unit_type));
  179838. #endif
  179839. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  179840. PNG_EXTERN void png_write_pCAL PNGARG((png_structp png_ptr, png_charp purpose,
  179841. png_int_32 X0, png_int_32 X1, int type, int nparams,
  179842. png_charp units, png_charpp params));
  179843. #endif
  179844. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  179845. PNG_EXTERN void png_write_pHYs PNGARG((png_structp png_ptr,
  179846. png_uint_32 x_pixels_per_unit, png_uint_32 y_pixels_per_unit,
  179847. int unit_type));
  179848. #endif
  179849. #if defined(PNG_WRITE_tIME_SUPPORTED)
  179850. PNG_EXTERN void png_write_tIME PNGARG((png_structp png_ptr,
  179851. png_timep mod_time));
  179852. #endif
  179853. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  179854. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  179855. PNG_EXTERN void png_write_sCAL PNGARG((png_structp png_ptr,
  179856. int unit, double width, double height));
  179857. #else
  179858. #ifdef PNG_FIXED_POINT_SUPPORTED
  179859. PNG_EXTERN void png_write_sCAL_s PNGARG((png_structp png_ptr,
  179860. int unit, png_charp width, png_charp height));
  179861. #endif
  179862. #endif
  179863. #endif
  179864. /* Called when finished processing a row of data */
  179865. PNG_EXTERN void png_write_finish_row PNGARG((png_structp png_ptr));
  179866. /* Internal use only. Called before first row of data */
  179867. PNG_EXTERN void png_write_start_row PNGARG((png_structp png_ptr));
  179868. #if defined(PNG_READ_GAMMA_SUPPORTED)
  179869. PNG_EXTERN void png_build_gamma_table PNGARG((png_structp png_ptr));
  179870. #endif
  179871. /* combine a row of data, dealing with alpha, etc. if requested */
  179872. PNG_EXTERN void png_combine_row PNGARG((png_structp png_ptr, png_bytep row,
  179873. int mask));
  179874. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  179875. /* expand an interlaced row */
  179876. /* OLD pre-1.0.9 interface:
  179877. PNG_EXTERN void png_do_read_interlace PNGARG((png_row_infop row_info,
  179878. png_bytep row, int pass, png_uint_32 transformations));
  179879. */
  179880. PNG_EXTERN void png_do_read_interlace PNGARG((png_structp png_ptr));
  179881. #endif
  179882. /* GRR TO DO (2.0 or whenever): simplify other internal calling interfaces */
  179883. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  179884. /* grab pixels out of a row for an interlaced pass */
  179885. PNG_EXTERN void png_do_write_interlace PNGARG((png_row_infop row_info,
  179886. png_bytep row, int pass));
  179887. #endif
  179888. /* unfilter a row */
  179889. PNG_EXTERN void png_read_filter_row PNGARG((png_structp png_ptr,
  179890. png_row_infop row_info, png_bytep row, png_bytep prev_row, int filter));
  179891. /* Choose the best filter to use and filter the row data */
  179892. PNG_EXTERN void png_write_find_filter PNGARG((png_structp png_ptr,
  179893. png_row_infop row_info));
  179894. /* Write out the filtered row. */
  179895. PNG_EXTERN void png_write_filtered_row PNGARG((png_structp png_ptr,
  179896. png_bytep filtered_row));
  179897. /* finish a row while reading, dealing with interlacing passes, etc. */
  179898. PNG_EXTERN void png_read_finish_row PNGARG((png_structp png_ptr));
  179899. /* initialize the row buffers, etc. */
  179900. PNG_EXTERN void png_read_start_row PNGARG((png_structp png_ptr));
  179901. /* optional call to update the users info structure */
  179902. PNG_EXTERN void png_read_transform_info PNGARG((png_structp png_ptr,
  179903. png_infop info_ptr));
  179904. /* these are the functions that do the transformations */
  179905. #if defined(PNG_READ_FILLER_SUPPORTED)
  179906. PNG_EXTERN void png_do_read_filler PNGARG((png_row_infop row_info,
  179907. png_bytep row, png_uint_32 filler, png_uint_32 flags));
  179908. #endif
  179909. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  179910. PNG_EXTERN void png_do_read_swap_alpha PNGARG((png_row_infop row_info,
  179911. png_bytep row));
  179912. #endif
  179913. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  179914. PNG_EXTERN void png_do_write_swap_alpha PNGARG((png_row_infop row_info,
  179915. png_bytep row));
  179916. #endif
  179917. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  179918. PNG_EXTERN void png_do_read_invert_alpha PNGARG((png_row_infop row_info,
  179919. png_bytep row));
  179920. #endif
  179921. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  179922. PNG_EXTERN void png_do_write_invert_alpha PNGARG((png_row_infop row_info,
  179923. png_bytep row));
  179924. #endif
  179925. #if defined(PNG_WRITE_FILLER_SUPPORTED) || \
  179926. defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  179927. PNG_EXTERN void png_do_strip_filler PNGARG((png_row_infop row_info,
  179928. png_bytep row, png_uint_32 flags));
  179929. #endif
  179930. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  179931. PNG_EXTERN void png_do_swap PNGARG((png_row_infop row_info, png_bytep row));
  179932. #endif
  179933. #if defined(PNG_READ_PACKSWAP_SUPPORTED) || defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  179934. PNG_EXTERN void png_do_packswap PNGARG((png_row_infop row_info, png_bytep row));
  179935. #endif
  179936. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  179937. PNG_EXTERN int png_do_rgb_to_gray PNGARG((png_structp png_ptr, png_row_infop
  179938. row_info, png_bytep row));
  179939. #endif
  179940. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  179941. PNG_EXTERN void png_do_gray_to_rgb PNGARG((png_row_infop row_info,
  179942. png_bytep row));
  179943. #endif
  179944. #if defined(PNG_READ_PACK_SUPPORTED)
  179945. PNG_EXTERN void png_do_unpack PNGARG((png_row_infop row_info, png_bytep row));
  179946. #endif
  179947. #if defined(PNG_READ_SHIFT_SUPPORTED)
  179948. PNG_EXTERN void png_do_unshift PNGARG((png_row_infop row_info, png_bytep row,
  179949. png_color_8p sig_bits));
  179950. #endif
  179951. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  179952. PNG_EXTERN void png_do_invert PNGARG((png_row_infop row_info, png_bytep row));
  179953. #endif
  179954. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  179955. PNG_EXTERN void png_do_chop PNGARG((png_row_infop row_info, png_bytep row));
  179956. #endif
  179957. #if defined(PNG_READ_DITHER_SUPPORTED)
  179958. PNG_EXTERN void png_do_dither PNGARG((png_row_infop row_info,
  179959. png_bytep row, png_bytep palette_lookup, png_bytep dither_lookup));
  179960. # if defined(PNG_CORRECT_PALETTE_SUPPORTED)
  179961. PNG_EXTERN void png_correct_palette PNGARG((png_structp png_ptr,
  179962. png_colorp palette, int num_palette));
  179963. # endif
  179964. #endif
  179965. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  179966. PNG_EXTERN void png_do_bgr PNGARG((png_row_infop row_info, png_bytep row));
  179967. #endif
  179968. #if defined(PNG_WRITE_PACK_SUPPORTED)
  179969. PNG_EXTERN void png_do_pack PNGARG((png_row_infop row_info,
  179970. png_bytep row, png_uint_32 bit_depth));
  179971. #endif
  179972. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  179973. PNG_EXTERN void png_do_shift PNGARG((png_row_infop row_info, png_bytep row,
  179974. png_color_8p bit_depth));
  179975. #endif
  179976. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  179977. #if defined(PNG_READ_GAMMA_SUPPORTED)
  179978. PNG_EXTERN void png_do_background PNGARG((png_row_infop row_info, png_bytep row,
  179979. png_color_16p trans_values, png_color_16p background,
  179980. png_color_16p background_1,
  179981. png_bytep gamma_table, png_bytep gamma_from_1, png_bytep gamma_to_1,
  179982. png_uint_16pp gamma_16, png_uint_16pp gamma_16_from_1,
  179983. png_uint_16pp gamma_16_to_1, int gamma_shift));
  179984. #else
  179985. PNG_EXTERN void png_do_background PNGARG((png_row_infop row_info, png_bytep row,
  179986. png_color_16p trans_values, png_color_16p background));
  179987. #endif
  179988. #endif
  179989. #if defined(PNG_READ_GAMMA_SUPPORTED)
  179990. PNG_EXTERN void png_do_gamma PNGARG((png_row_infop row_info, png_bytep row,
  179991. png_bytep gamma_table, png_uint_16pp gamma_16_table,
  179992. int gamma_shift));
  179993. #endif
  179994. #if defined(PNG_READ_EXPAND_SUPPORTED)
  179995. PNG_EXTERN void png_do_expand_palette PNGARG((png_row_infop row_info,
  179996. png_bytep row, png_colorp palette, png_bytep trans, int num_trans));
  179997. PNG_EXTERN void png_do_expand PNGARG((png_row_infop row_info,
  179998. png_bytep row, png_color_16p trans_value));
  179999. #endif
  180000. /* The following decodes the appropriate chunks, and does error correction,
  180001. * then calls the appropriate callback for the chunk if it is valid.
  180002. */
  180003. /* decode the IHDR chunk */
  180004. PNG_EXTERN void png_handle_IHDR PNGARG((png_structp png_ptr, png_infop info_ptr,
  180005. png_uint_32 length));
  180006. PNG_EXTERN void png_handle_PLTE PNGARG((png_structp png_ptr, png_infop info_ptr,
  180007. png_uint_32 length));
  180008. PNG_EXTERN void png_handle_IEND PNGARG((png_structp png_ptr, png_infop info_ptr,
  180009. png_uint_32 length));
  180010. #if defined(PNG_READ_bKGD_SUPPORTED)
  180011. PNG_EXTERN void png_handle_bKGD PNGARG((png_structp png_ptr, png_infop info_ptr,
  180012. png_uint_32 length));
  180013. #endif
  180014. #if defined(PNG_READ_cHRM_SUPPORTED)
  180015. PNG_EXTERN void png_handle_cHRM PNGARG((png_structp png_ptr, png_infop info_ptr,
  180016. png_uint_32 length));
  180017. #endif
  180018. #if defined(PNG_READ_gAMA_SUPPORTED)
  180019. PNG_EXTERN void png_handle_gAMA PNGARG((png_structp png_ptr, png_infop info_ptr,
  180020. png_uint_32 length));
  180021. #endif
  180022. #if defined(PNG_READ_hIST_SUPPORTED)
  180023. PNG_EXTERN void png_handle_hIST PNGARG((png_structp png_ptr, png_infop info_ptr,
  180024. png_uint_32 length));
  180025. #endif
  180026. #if defined(PNG_READ_iCCP_SUPPORTED)
  180027. extern void png_handle_iCCP PNGARG((png_structp png_ptr, png_infop info_ptr,
  180028. png_uint_32 length));
  180029. #endif /* PNG_READ_iCCP_SUPPORTED */
  180030. #if defined(PNG_READ_iTXt_SUPPORTED)
  180031. PNG_EXTERN void png_handle_iTXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  180032. png_uint_32 length));
  180033. #endif
  180034. #if defined(PNG_READ_oFFs_SUPPORTED)
  180035. PNG_EXTERN void png_handle_oFFs PNGARG((png_structp png_ptr, png_infop info_ptr,
  180036. png_uint_32 length));
  180037. #endif
  180038. #if defined(PNG_READ_pCAL_SUPPORTED)
  180039. PNG_EXTERN void png_handle_pCAL PNGARG((png_structp png_ptr, png_infop info_ptr,
  180040. png_uint_32 length));
  180041. #endif
  180042. #if defined(PNG_READ_pHYs_SUPPORTED)
  180043. PNG_EXTERN void png_handle_pHYs PNGARG((png_structp png_ptr, png_infop info_ptr,
  180044. png_uint_32 length));
  180045. #endif
  180046. #if defined(PNG_READ_sBIT_SUPPORTED)
  180047. PNG_EXTERN void png_handle_sBIT PNGARG((png_structp png_ptr, png_infop info_ptr,
  180048. png_uint_32 length));
  180049. #endif
  180050. #if defined(PNG_READ_sCAL_SUPPORTED)
  180051. PNG_EXTERN void png_handle_sCAL PNGARG((png_structp png_ptr, png_infop info_ptr,
  180052. png_uint_32 length));
  180053. #endif
  180054. #if defined(PNG_READ_sPLT_SUPPORTED)
  180055. extern void png_handle_sPLT PNGARG((png_structp png_ptr, png_infop info_ptr,
  180056. png_uint_32 length));
  180057. #endif /* PNG_READ_sPLT_SUPPORTED */
  180058. #if defined(PNG_READ_sRGB_SUPPORTED)
  180059. PNG_EXTERN void png_handle_sRGB PNGARG((png_structp png_ptr, png_infop info_ptr,
  180060. png_uint_32 length));
  180061. #endif
  180062. #if defined(PNG_READ_tEXt_SUPPORTED)
  180063. PNG_EXTERN void png_handle_tEXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  180064. png_uint_32 length));
  180065. #endif
  180066. #if defined(PNG_READ_tIME_SUPPORTED)
  180067. PNG_EXTERN void png_handle_tIME PNGARG((png_structp png_ptr, png_infop info_ptr,
  180068. png_uint_32 length));
  180069. #endif
  180070. #if defined(PNG_READ_tRNS_SUPPORTED)
  180071. PNG_EXTERN void png_handle_tRNS PNGARG((png_structp png_ptr, png_infop info_ptr,
  180072. png_uint_32 length));
  180073. #endif
  180074. #if defined(PNG_READ_zTXt_SUPPORTED)
  180075. PNG_EXTERN void png_handle_zTXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  180076. png_uint_32 length));
  180077. #endif
  180078. PNG_EXTERN void png_handle_unknown PNGARG((png_structp png_ptr,
  180079. png_infop info_ptr, png_uint_32 length));
  180080. PNG_EXTERN void png_check_chunk_name PNGARG((png_structp png_ptr,
  180081. png_bytep chunk_name));
  180082. /* handle the transformations for reading and writing */
  180083. PNG_EXTERN void png_do_read_transformations PNGARG((png_structp png_ptr));
  180084. PNG_EXTERN void png_do_write_transformations PNGARG((png_structp png_ptr));
  180085. PNG_EXTERN void png_init_read_transformations PNGARG((png_structp png_ptr));
  180086. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  180087. PNG_EXTERN void png_push_read_chunk PNGARG((png_structp png_ptr,
  180088. png_infop info_ptr));
  180089. PNG_EXTERN void png_push_read_sig PNGARG((png_structp png_ptr,
  180090. png_infop info_ptr));
  180091. PNG_EXTERN void png_push_check_crc PNGARG((png_structp png_ptr));
  180092. PNG_EXTERN void png_push_crc_skip PNGARG((png_structp png_ptr,
  180093. png_uint_32 length));
  180094. PNG_EXTERN void png_push_crc_finish PNGARG((png_structp png_ptr));
  180095. PNG_EXTERN void png_push_save_buffer PNGARG((png_structp png_ptr));
  180096. PNG_EXTERN void png_push_restore_buffer PNGARG((png_structp png_ptr,
  180097. png_bytep buffer, png_size_t buffer_length));
  180098. PNG_EXTERN void png_push_read_IDAT PNGARG((png_structp png_ptr));
  180099. PNG_EXTERN void png_process_IDAT_data PNGARG((png_structp png_ptr,
  180100. png_bytep buffer, png_size_t buffer_length));
  180101. PNG_EXTERN void png_push_process_row PNGARG((png_structp png_ptr));
  180102. PNG_EXTERN void png_push_handle_unknown PNGARG((png_structp png_ptr,
  180103. png_infop info_ptr, png_uint_32 length));
  180104. PNG_EXTERN void png_push_have_info PNGARG((png_structp png_ptr,
  180105. png_infop info_ptr));
  180106. PNG_EXTERN void png_push_have_end PNGARG((png_structp png_ptr,
  180107. png_infop info_ptr));
  180108. PNG_EXTERN void png_push_have_row PNGARG((png_structp png_ptr, png_bytep row));
  180109. PNG_EXTERN void png_push_read_end PNGARG((png_structp png_ptr,
  180110. png_infop info_ptr));
  180111. PNG_EXTERN void png_process_some_data PNGARG((png_structp png_ptr,
  180112. png_infop info_ptr));
  180113. PNG_EXTERN void png_read_push_finish_row PNGARG((png_structp png_ptr));
  180114. #if defined(PNG_READ_tEXt_SUPPORTED)
  180115. PNG_EXTERN void png_push_handle_tEXt PNGARG((png_structp png_ptr,
  180116. png_infop info_ptr, png_uint_32 length));
  180117. PNG_EXTERN void png_push_read_tEXt PNGARG((png_structp png_ptr,
  180118. png_infop info_ptr));
  180119. #endif
  180120. #if defined(PNG_READ_zTXt_SUPPORTED)
  180121. PNG_EXTERN void png_push_handle_zTXt PNGARG((png_structp png_ptr,
  180122. png_infop info_ptr, png_uint_32 length));
  180123. PNG_EXTERN void png_push_read_zTXt PNGARG((png_structp png_ptr,
  180124. png_infop info_ptr));
  180125. #endif
  180126. #if defined(PNG_READ_iTXt_SUPPORTED)
  180127. PNG_EXTERN void png_push_handle_iTXt PNGARG((png_structp png_ptr,
  180128. png_infop info_ptr, png_uint_32 length));
  180129. PNG_EXTERN void png_push_read_iTXt PNGARG((png_structp png_ptr,
  180130. png_infop info_ptr));
  180131. #endif
  180132. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  180133. #ifdef PNG_MNG_FEATURES_SUPPORTED
  180134. PNG_EXTERN void png_do_read_intrapixel PNGARG((png_row_infop row_info,
  180135. png_bytep row));
  180136. PNG_EXTERN void png_do_write_intrapixel PNGARG((png_row_infop row_info,
  180137. png_bytep row));
  180138. #endif
  180139. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  180140. #if defined(PNG_MMX_CODE_SUPPORTED)
  180141. /* png.c */ /* PRIVATE */
  180142. PNG_EXTERN void png_init_mmx_flags PNGARG((png_structp png_ptr));
  180143. #endif
  180144. #endif
  180145. #if defined(PNG_INCH_CONVERSIONS) && defined(PNG_FLOATING_POINT_SUPPORTED)
  180146. PNG_EXTERN png_uint_32 png_get_pixels_per_inch PNGARG((png_structp png_ptr,
  180147. png_infop info_ptr));
  180148. PNG_EXTERN png_uint_32 png_get_x_pixels_per_inch PNGARG((png_structp png_ptr,
  180149. png_infop info_ptr));
  180150. PNG_EXTERN png_uint_32 png_get_y_pixels_per_inch PNGARG((png_structp png_ptr,
  180151. png_infop info_ptr));
  180152. PNG_EXTERN float png_get_x_offset_inches PNGARG((png_structp png_ptr,
  180153. png_infop info_ptr));
  180154. PNG_EXTERN float png_get_y_offset_inches PNGARG((png_structp png_ptr,
  180155. png_infop info_ptr));
  180156. #if defined(PNG_pHYs_SUPPORTED)
  180157. PNG_EXTERN png_uint_32 png_get_pHYs_dpi PNGARG((png_structp png_ptr,
  180158. png_infop info_ptr, png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type));
  180159. #endif /* PNG_pHYs_SUPPORTED */
  180160. #endif /* PNG_INCH_CONVERSIONS && PNG_FLOATING_POINT_SUPPORTED */
  180161. /* Maintainer: Put new private prototypes here ^ and in libpngpf.3 */
  180162. #endif /* PNG_INTERNAL */
  180163. #ifdef __cplusplus
  180164. }
  180165. #endif
  180166. #endif /* PNG_VERSION_INFO_ONLY */
  180167. /* do not put anything past this line */
  180168. #endif /* PNG_H */
  180169. /********* End of inlined file: png.h *********/
  180170. #define PNG_NO_EXTERN
  180171. /********* Start of inlined file: png.c *********/
  180172. /* png.c - location for general purpose libpng functions
  180173. *
  180174. * Last changed in libpng 1.2.21 [October 4, 2007]
  180175. * For conditions of distribution and use, see copyright notice in png.h
  180176. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  180177. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  180178. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  180179. */
  180180. #define PNG_INTERNAL
  180181. #define PNG_NO_EXTERN
  180182. /* Generate a compiler error if there is an old png.h in the search path. */
  180183. typedef version_1_2_21 Your_png_h_is_not_version_1_2_21;
  180184. /* Version information for C files. This had better match the version
  180185. * string defined in png.h. */
  180186. #ifdef PNG_USE_GLOBAL_ARRAYS
  180187. /* png_libpng_ver was changed to a function in version 1.0.5c */
  180188. PNG_CONST char png_libpng_ver[18] = PNG_LIBPNG_VER_STRING;
  180189. #ifdef PNG_READ_SUPPORTED
  180190. /* png_sig was changed to a function in version 1.0.5c */
  180191. /* Place to hold the signature string for a PNG file. */
  180192. PNG_CONST png_byte FARDATA png_sig[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  180193. #endif /* PNG_READ_SUPPORTED */
  180194. /* Invoke global declarations for constant strings for known chunk types */
  180195. PNG_IHDR;
  180196. PNG_IDAT;
  180197. PNG_IEND;
  180198. PNG_PLTE;
  180199. PNG_bKGD;
  180200. PNG_cHRM;
  180201. PNG_gAMA;
  180202. PNG_hIST;
  180203. PNG_iCCP;
  180204. PNG_iTXt;
  180205. PNG_oFFs;
  180206. PNG_pCAL;
  180207. PNG_sCAL;
  180208. PNG_pHYs;
  180209. PNG_sBIT;
  180210. PNG_sPLT;
  180211. PNG_sRGB;
  180212. PNG_tEXt;
  180213. PNG_tIME;
  180214. PNG_tRNS;
  180215. PNG_zTXt;
  180216. #ifdef PNG_READ_SUPPORTED
  180217. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  180218. /* start of interlace block */
  180219. PNG_CONST int FARDATA png_pass_start[] = {0, 4, 0, 2, 0, 1, 0};
  180220. /* offset to next interlace block */
  180221. PNG_CONST int FARDATA png_pass_inc[] = {8, 8, 4, 4, 2, 2, 1};
  180222. /* start of interlace block in the y direction */
  180223. PNG_CONST int FARDATA png_pass_ystart[] = {0, 0, 4, 0, 2, 0, 1};
  180224. /* offset to next interlace block in the y direction */
  180225. PNG_CONST int FARDATA png_pass_yinc[] = {8, 8, 8, 4, 4, 2, 2};
  180226. /* Height of interlace block. This is not currently used - if you need
  180227. * it, uncomment it here and in png.h
  180228. PNG_CONST int FARDATA png_pass_height[] = {8, 8, 4, 4, 2, 2, 1};
  180229. */
  180230. /* Mask to determine which pixels are valid in a pass */
  180231. PNG_CONST int FARDATA png_pass_mask[] = {0x80, 0x08, 0x88, 0x22, 0xaa, 0x55, 0xff};
  180232. /* Mask to determine which pixels to overwrite while displaying */
  180233. PNG_CONST int FARDATA png_pass_dsp_mask[]
  180234. = {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55, 0xff};
  180235. #endif /* PNG_READ_SUPPORTED */
  180236. #endif /* PNG_USE_GLOBAL_ARRAYS */
  180237. /* Tells libpng that we have already handled the first "num_bytes" bytes
  180238. * of the PNG file signature. If the PNG data is embedded into another
  180239. * stream we can set num_bytes = 8 so that libpng will not attempt to read
  180240. * or write any of the magic bytes before it starts on the IHDR.
  180241. */
  180242. #ifdef PNG_READ_SUPPORTED
  180243. void PNGAPI
  180244. png_set_sig_bytes(png_structp png_ptr, int num_bytes)
  180245. {
  180246. if(png_ptr == NULL) return;
  180247. png_debug(1, "in png_set_sig_bytes\n");
  180248. if (num_bytes > 8)
  180249. png_error(png_ptr, "Too many bytes for PNG signature.");
  180250. png_ptr->sig_bytes = (png_byte)(num_bytes < 0 ? 0 : num_bytes);
  180251. }
  180252. /* Checks whether the supplied bytes match the PNG signature. We allow
  180253. * checking less than the full 8-byte signature so that those apps that
  180254. * already read the first few bytes of a file to determine the file type
  180255. * can simply check the remaining bytes for extra assurance. Returns
  180256. * an integer less than, equal to, or greater than zero if sig is found,
  180257. * respectively, to be less than, to match, or be greater than the correct
  180258. * PNG signature (this is the same behaviour as strcmp, memcmp, etc).
  180259. */
  180260. int PNGAPI
  180261. png_sig_cmp(png_bytep sig, png_size_t start, png_size_t num_to_check)
  180262. {
  180263. png_byte png_signature[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  180264. if (num_to_check > 8)
  180265. num_to_check = 8;
  180266. else if (num_to_check < 1)
  180267. return (-1);
  180268. if (start > 7)
  180269. return (-1);
  180270. if (start + num_to_check > 8)
  180271. num_to_check = 8 - start;
  180272. return ((int)(png_memcmp(&sig[start], &png_signature[start], num_to_check)));
  180273. }
  180274. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  180275. /* (Obsolete) function to check signature bytes. It does not allow one
  180276. * to check a partial signature. This function might be removed in the
  180277. * future - use png_sig_cmp(). Returns true (nonzero) if the file is PNG.
  180278. */
  180279. int PNGAPI
  180280. png_check_sig(png_bytep sig, int num)
  180281. {
  180282. return ((int)!png_sig_cmp(sig, (png_size_t)0, (png_size_t)num));
  180283. }
  180284. #endif
  180285. #endif /* PNG_READ_SUPPORTED */
  180286. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  180287. /* Function to allocate memory for zlib and clear it to 0. */
  180288. #ifdef PNG_1_0_X
  180289. voidpf PNGAPI
  180290. #else
  180291. voidpf /* private */
  180292. #endif
  180293. png_zalloc(voidpf png_ptr, uInt items, uInt size)
  180294. {
  180295. png_voidp ptr;
  180296. png_structp p=(png_structp)png_ptr;
  180297. png_uint_32 save_flags=p->flags;
  180298. png_uint_32 num_bytes;
  180299. if(png_ptr == NULL) return (NULL);
  180300. if (items > PNG_UINT_32_MAX/size)
  180301. {
  180302. png_warning (p, "Potential overflow in png_zalloc()");
  180303. return (NULL);
  180304. }
  180305. num_bytes = (png_uint_32)items * size;
  180306. p->flags|=PNG_FLAG_MALLOC_NULL_MEM_OK;
  180307. ptr = (png_voidp)png_malloc((png_structp)png_ptr, num_bytes);
  180308. p->flags=save_flags;
  180309. #if defined(PNG_1_0_X) && !defined(PNG_NO_ZALLOC_ZERO)
  180310. if (ptr == NULL)
  180311. return ((voidpf)ptr);
  180312. if (num_bytes > (png_uint_32)0x8000L)
  180313. {
  180314. png_memset(ptr, 0, (png_size_t)0x8000L);
  180315. png_memset((png_bytep)ptr + (png_size_t)0x8000L, 0,
  180316. (png_size_t)(num_bytes - (png_uint_32)0x8000L));
  180317. }
  180318. else
  180319. {
  180320. png_memset(ptr, 0, (png_size_t)num_bytes);
  180321. }
  180322. #endif
  180323. return ((voidpf)ptr);
  180324. }
  180325. /* function to free memory for zlib */
  180326. #ifdef PNG_1_0_X
  180327. void PNGAPI
  180328. #else
  180329. void /* private */
  180330. #endif
  180331. png_zfree(voidpf png_ptr, voidpf ptr)
  180332. {
  180333. png_free((png_structp)png_ptr, (png_voidp)ptr);
  180334. }
  180335. /* Reset the CRC variable to 32 bits of 1's. Care must be taken
  180336. * in case CRC is > 32 bits to leave the top bits 0.
  180337. */
  180338. void /* PRIVATE */
  180339. png_reset_crc(png_structp png_ptr)
  180340. {
  180341. png_ptr->crc = crc32(0, Z_NULL, 0);
  180342. }
  180343. /* Calculate the CRC over a section of data. We can only pass as
  180344. * much data to this routine as the largest single buffer size. We
  180345. * also check that this data will actually be used before going to the
  180346. * trouble of calculating it.
  180347. */
  180348. void /* PRIVATE */
  180349. png_calculate_crc(png_structp png_ptr, png_bytep ptr, png_size_t length)
  180350. {
  180351. int need_crc = 1;
  180352. if (png_ptr->chunk_name[0] & 0x20) /* ancillary */
  180353. {
  180354. if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_MASK) ==
  180355. (PNG_FLAG_CRC_ANCILLARY_USE | PNG_FLAG_CRC_ANCILLARY_NOWARN))
  180356. need_crc = 0;
  180357. }
  180358. else /* critical */
  180359. {
  180360. if (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_IGNORE)
  180361. need_crc = 0;
  180362. }
  180363. if (need_crc)
  180364. png_ptr->crc = crc32(png_ptr->crc, ptr, (uInt)length);
  180365. }
  180366. /* Allocate the memory for an info_struct for the application. We don't
  180367. * really need the png_ptr, but it could potentially be useful in the
  180368. * future. This should be used in favour of malloc(png_sizeof(png_info))
  180369. * and png_info_init() so that applications that want to use a shared
  180370. * libpng don't have to be recompiled if png_info changes size.
  180371. */
  180372. png_infop PNGAPI
  180373. png_create_info_struct(png_structp png_ptr)
  180374. {
  180375. png_infop info_ptr;
  180376. png_debug(1, "in png_create_info_struct\n");
  180377. if(png_ptr == NULL) return (NULL);
  180378. #ifdef PNG_USER_MEM_SUPPORTED
  180379. info_ptr = (png_infop)png_create_struct_2(PNG_STRUCT_INFO,
  180380. png_ptr->malloc_fn, png_ptr->mem_ptr);
  180381. #else
  180382. info_ptr = (png_infop)png_create_struct(PNG_STRUCT_INFO);
  180383. #endif
  180384. if (info_ptr != NULL)
  180385. png_info_init_3(&info_ptr, png_sizeof(png_info));
  180386. return (info_ptr);
  180387. }
  180388. /* This function frees the memory associated with a single info struct.
  180389. * Normally, one would use either png_destroy_read_struct() or
  180390. * png_destroy_write_struct() to free an info struct, but this may be
  180391. * useful for some applications.
  180392. */
  180393. void PNGAPI
  180394. png_destroy_info_struct(png_structp png_ptr, png_infopp info_ptr_ptr)
  180395. {
  180396. png_infop info_ptr = NULL;
  180397. if(png_ptr == NULL) return;
  180398. png_debug(1, "in png_destroy_info_struct\n");
  180399. if (info_ptr_ptr != NULL)
  180400. info_ptr = *info_ptr_ptr;
  180401. if (info_ptr != NULL)
  180402. {
  180403. png_info_destroy(png_ptr, info_ptr);
  180404. #ifdef PNG_USER_MEM_SUPPORTED
  180405. png_destroy_struct_2((png_voidp)info_ptr, png_ptr->free_fn,
  180406. png_ptr->mem_ptr);
  180407. #else
  180408. png_destroy_struct((png_voidp)info_ptr);
  180409. #endif
  180410. *info_ptr_ptr = NULL;
  180411. }
  180412. }
  180413. /* Initialize the info structure. This is now an internal function (0.89)
  180414. * and applications using it are urged to use png_create_info_struct()
  180415. * instead.
  180416. */
  180417. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  180418. #undef png_info_init
  180419. void PNGAPI
  180420. png_info_init(png_infop info_ptr)
  180421. {
  180422. /* We only come here via pre-1.0.12-compiled applications */
  180423. png_info_init_3(&info_ptr, 0);
  180424. }
  180425. #endif
  180426. void PNGAPI
  180427. png_info_init_3(png_infopp ptr_ptr, png_size_t png_info_struct_size)
  180428. {
  180429. png_infop info_ptr = *ptr_ptr;
  180430. if(info_ptr == NULL) return;
  180431. png_debug(1, "in png_info_init_3\n");
  180432. if(png_sizeof(png_info) > png_info_struct_size)
  180433. {
  180434. png_destroy_struct(info_ptr);
  180435. info_ptr = (png_infop)png_create_struct(PNG_STRUCT_INFO);
  180436. *ptr_ptr = info_ptr;
  180437. }
  180438. /* set everything to 0 */
  180439. png_memset(info_ptr, 0, png_sizeof (png_info));
  180440. }
  180441. #ifdef PNG_FREE_ME_SUPPORTED
  180442. void PNGAPI
  180443. png_data_freer(png_structp png_ptr, png_infop info_ptr,
  180444. int freer, png_uint_32 mask)
  180445. {
  180446. png_debug(1, "in png_data_freer\n");
  180447. if (png_ptr == NULL || info_ptr == NULL)
  180448. return;
  180449. if(freer == PNG_DESTROY_WILL_FREE_DATA)
  180450. info_ptr->free_me |= mask;
  180451. else if(freer == PNG_USER_WILL_FREE_DATA)
  180452. info_ptr->free_me &= ~mask;
  180453. else
  180454. png_warning(png_ptr,
  180455. "Unknown freer parameter in png_data_freer.");
  180456. }
  180457. #endif
  180458. void PNGAPI
  180459. png_free_data(png_structp png_ptr, png_infop info_ptr, png_uint_32 mask,
  180460. int num)
  180461. {
  180462. png_debug(1, "in png_free_data\n");
  180463. if (png_ptr == NULL || info_ptr == NULL)
  180464. return;
  180465. #if defined(PNG_TEXT_SUPPORTED)
  180466. /* free text item num or (if num == -1) all text items */
  180467. #ifdef PNG_FREE_ME_SUPPORTED
  180468. if ((mask & PNG_FREE_TEXT) & info_ptr->free_me)
  180469. #else
  180470. if (mask & PNG_FREE_TEXT)
  180471. #endif
  180472. {
  180473. if (num != -1)
  180474. {
  180475. if (info_ptr->text && info_ptr->text[num].key)
  180476. {
  180477. png_free(png_ptr, info_ptr->text[num].key);
  180478. info_ptr->text[num].key = NULL;
  180479. }
  180480. }
  180481. else
  180482. {
  180483. int i;
  180484. for (i = 0; i < info_ptr->num_text; i++)
  180485. png_free_data(png_ptr, info_ptr, PNG_FREE_TEXT, i);
  180486. png_free(png_ptr, info_ptr->text);
  180487. info_ptr->text = NULL;
  180488. info_ptr->num_text=0;
  180489. }
  180490. }
  180491. #endif
  180492. #if defined(PNG_tRNS_SUPPORTED)
  180493. /* free any tRNS entry */
  180494. #ifdef PNG_FREE_ME_SUPPORTED
  180495. if ((mask & PNG_FREE_TRNS) & info_ptr->free_me)
  180496. #else
  180497. if ((mask & PNG_FREE_TRNS) && (png_ptr->flags & PNG_FLAG_FREE_TRNS))
  180498. #endif
  180499. {
  180500. png_free(png_ptr, info_ptr->trans);
  180501. info_ptr->valid &= ~PNG_INFO_tRNS;
  180502. #ifndef PNG_FREE_ME_SUPPORTED
  180503. png_ptr->flags &= ~PNG_FLAG_FREE_TRNS;
  180504. #endif
  180505. info_ptr->trans = NULL;
  180506. }
  180507. #endif
  180508. #if defined(PNG_sCAL_SUPPORTED)
  180509. /* free any sCAL entry */
  180510. #ifdef PNG_FREE_ME_SUPPORTED
  180511. if ((mask & PNG_FREE_SCAL) & info_ptr->free_me)
  180512. #else
  180513. if (mask & PNG_FREE_SCAL)
  180514. #endif
  180515. {
  180516. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  180517. png_free(png_ptr, info_ptr->scal_s_width);
  180518. png_free(png_ptr, info_ptr->scal_s_height);
  180519. info_ptr->scal_s_width = NULL;
  180520. info_ptr->scal_s_height = NULL;
  180521. #endif
  180522. info_ptr->valid &= ~PNG_INFO_sCAL;
  180523. }
  180524. #endif
  180525. #if defined(PNG_pCAL_SUPPORTED)
  180526. /* free any pCAL entry */
  180527. #ifdef PNG_FREE_ME_SUPPORTED
  180528. if ((mask & PNG_FREE_PCAL) & info_ptr->free_me)
  180529. #else
  180530. if (mask & PNG_FREE_PCAL)
  180531. #endif
  180532. {
  180533. png_free(png_ptr, info_ptr->pcal_purpose);
  180534. png_free(png_ptr, info_ptr->pcal_units);
  180535. info_ptr->pcal_purpose = NULL;
  180536. info_ptr->pcal_units = NULL;
  180537. if (info_ptr->pcal_params != NULL)
  180538. {
  180539. int i;
  180540. for (i = 0; i < (int)info_ptr->pcal_nparams; i++)
  180541. {
  180542. png_free(png_ptr, info_ptr->pcal_params[i]);
  180543. info_ptr->pcal_params[i]=NULL;
  180544. }
  180545. png_free(png_ptr, info_ptr->pcal_params);
  180546. info_ptr->pcal_params = NULL;
  180547. }
  180548. info_ptr->valid &= ~PNG_INFO_pCAL;
  180549. }
  180550. #endif
  180551. #if defined(PNG_iCCP_SUPPORTED)
  180552. /* free any iCCP entry */
  180553. #ifdef PNG_FREE_ME_SUPPORTED
  180554. if ((mask & PNG_FREE_ICCP) & info_ptr->free_me)
  180555. #else
  180556. if (mask & PNG_FREE_ICCP)
  180557. #endif
  180558. {
  180559. png_free(png_ptr, info_ptr->iccp_name);
  180560. png_free(png_ptr, info_ptr->iccp_profile);
  180561. info_ptr->iccp_name = NULL;
  180562. info_ptr->iccp_profile = NULL;
  180563. info_ptr->valid &= ~PNG_INFO_iCCP;
  180564. }
  180565. #endif
  180566. #if defined(PNG_sPLT_SUPPORTED)
  180567. /* free a given sPLT entry, or (if num == -1) all sPLT entries */
  180568. #ifdef PNG_FREE_ME_SUPPORTED
  180569. if ((mask & PNG_FREE_SPLT) & info_ptr->free_me)
  180570. #else
  180571. if (mask & PNG_FREE_SPLT)
  180572. #endif
  180573. {
  180574. if (num != -1)
  180575. {
  180576. if(info_ptr->splt_palettes)
  180577. {
  180578. png_free(png_ptr, info_ptr->splt_palettes[num].name);
  180579. png_free(png_ptr, info_ptr->splt_palettes[num].entries);
  180580. info_ptr->splt_palettes[num].name = NULL;
  180581. info_ptr->splt_palettes[num].entries = NULL;
  180582. }
  180583. }
  180584. else
  180585. {
  180586. if(info_ptr->splt_palettes_num)
  180587. {
  180588. int i;
  180589. for (i = 0; i < (int)info_ptr->splt_palettes_num; i++)
  180590. png_free_data(png_ptr, info_ptr, PNG_FREE_SPLT, i);
  180591. png_free(png_ptr, info_ptr->splt_palettes);
  180592. info_ptr->splt_palettes = NULL;
  180593. info_ptr->splt_palettes_num = 0;
  180594. }
  180595. info_ptr->valid &= ~PNG_INFO_sPLT;
  180596. }
  180597. }
  180598. #endif
  180599. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  180600. if(png_ptr->unknown_chunk.data)
  180601. {
  180602. png_free(png_ptr, png_ptr->unknown_chunk.data);
  180603. png_ptr->unknown_chunk.data = NULL;
  180604. }
  180605. #ifdef PNG_FREE_ME_SUPPORTED
  180606. if ((mask & PNG_FREE_UNKN) & info_ptr->free_me)
  180607. #else
  180608. if (mask & PNG_FREE_UNKN)
  180609. #endif
  180610. {
  180611. if (num != -1)
  180612. {
  180613. if(info_ptr->unknown_chunks)
  180614. {
  180615. png_free(png_ptr, info_ptr->unknown_chunks[num].data);
  180616. info_ptr->unknown_chunks[num].data = NULL;
  180617. }
  180618. }
  180619. else
  180620. {
  180621. int i;
  180622. if(info_ptr->unknown_chunks_num)
  180623. {
  180624. for (i = 0; i < (int)info_ptr->unknown_chunks_num; i++)
  180625. png_free_data(png_ptr, info_ptr, PNG_FREE_UNKN, i);
  180626. png_free(png_ptr, info_ptr->unknown_chunks);
  180627. info_ptr->unknown_chunks = NULL;
  180628. info_ptr->unknown_chunks_num = 0;
  180629. }
  180630. }
  180631. }
  180632. #endif
  180633. #if defined(PNG_hIST_SUPPORTED)
  180634. /* free any hIST entry */
  180635. #ifdef PNG_FREE_ME_SUPPORTED
  180636. if ((mask & PNG_FREE_HIST) & info_ptr->free_me)
  180637. #else
  180638. if ((mask & PNG_FREE_HIST) && (png_ptr->flags & PNG_FLAG_FREE_HIST))
  180639. #endif
  180640. {
  180641. png_free(png_ptr, info_ptr->hist);
  180642. info_ptr->hist = NULL;
  180643. info_ptr->valid &= ~PNG_INFO_hIST;
  180644. #ifndef PNG_FREE_ME_SUPPORTED
  180645. png_ptr->flags &= ~PNG_FLAG_FREE_HIST;
  180646. #endif
  180647. }
  180648. #endif
  180649. /* free any PLTE entry that was internally allocated */
  180650. #ifdef PNG_FREE_ME_SUPPORTED
  180651. if ((mask & PNG_FREE_PLTE) & info_ptr->free_me)
  180652. #else
  180653. if ((mask & PNG_FREE_PLTE) && (png_ptr->flags & PNG_FLAG_FREE_PLTE))
  180654. #endif
  180655. {
  180656. png_zfree(png_ptr, info_ptr->palette);
  180657. info_ptr->palette = NULL;
  180658. info_ptr->valid &= ~PNG_INFO_PLTE;
  180659. #ifndef PNG_FREE_ME_SUPPORTED
  180660. png_ptr->flags &= ~PNG_FLAG_FREE_PLTE;
  180661. #endif
  180662. info_ptr->num_palette = 0;
  180663. }
  180664. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  180665. /* free any image bits attached to the info structure */
  180666. #ifdef PNG_FREE_ME_SUPPORTED
  180667. if ((mask & PNG_FREE_ROWS) & info_ptr->free_me)
  180668. #else
  180669. if (mask & PNG_FREE_ROWS)
  180670. #endif
  180671. {
  180672. if(info_ptr->row_pointers)
  180673. {
  180674. int row;
  180675. for (row = 0; row < (int)info_ptr->height; row++)
  180676. {
  180677. png_free(png_ptr, info_ptr->row_pointers[row]);
  180678. info_ptr->row_pointers[row]=NULL;
  180679. }
  180680. png_free(png_ptr, info_ptr->row_pointers);
  180681. info_ptr->row_pointers=NULL;
  180682. }
  180683. info_ptr->valid &= ~PNG_INFO_IDAT;
  180684. }
  180685. #endif
  180686. #ifdef PNG_FREE_ME_SUPPORTED
  180687. if(num == -1)
  180688. info_ptr->free_me &= ~mask;
  180689. else
  180690. info_ptr->free_me &= ~(mask & ~PNG_FREE_MUL);
  180691. #endif
  180692. }
  180693. /* This is an internal routine to free any memory that the info struct is
  180694. * pointing to before re-using it or freeing the struct itself. Recall
  180695. * that png_free() checks for NULL pointers for us.
  180696. */
  180697. void /* PRIVATE */
  180698. png_info_destroy(png_structp png_ptr, png_infop info_ptr)
  180699. {
  180700. png_debug(1, "in png_info_destroy\n");
  180701. png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1);
  180702. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  180703. if (png_ptr->num_chunk_list)
  180704. {
  180705. png_free(png_ptr, png_ptr->chunk_list);
  180706. png_ptr->chunk_list=NULL;
  180707. png_ptr->num_chunk_list=0;
  180708. }
  180709. #endif
  180710. png_info_init_3(&info_ptr, png_sizeof(png_info));
  180711. }
  180712. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  180713. /* This function returns a pointer to the io_ptr associated with the user
  180714. * functions. The application should free any memory associated with this
  180715. * pointer before png_write_destroy() or png_read_destroy() are called.
  180716. */
  180717. png_voidp PNGAPI
  180718. png_get_io_ptr(png_structp png_ptr)
  180719. {
  180720. if(png_ptr == NULL) return (NULL);
  180721. return (png_ptr->io_ptr);
  180722. }
  180723. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  180724. #if !defined(PNG_NO_STDIO)
  180725. /* Initialize the default input/output functions for the PNG file. If you
  180726. * use your own read or write routines, you can call either png_set_read_fn()
  180727. * or png_set_write_fn() instead of png_init_io(). If you have defined
  180728. * PNG_NO_STDIO, you must use a function of your own because "FILE *" isn't
  180729. * necessarily available.
  180730. */
  180731. void PNGAPI
  180732. png_init_io(png_structp png_ptr, png_FILE_p fp)
  180733. {
  180734. png_debug(1, "in png_init_io\n");
  180735. if(png_ptr == NULL) return;
  180736. png_ptr->io_ptr = (png_voidp)fp;
  180737. }
  180738. #endif
  180739. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  180740. /* Convert the supplied time into an RFC 1123 string suitable for use in
  180741. * a "Creation Time" or other text-based time string.
  180742. */
  180743. png_charp PNGAPI
  180744. png_convert_to_rfc1123(png_structp png_ptr, png_timep ptime)
  180745. {
  180746. static PNG_CONST char short_months[12][4] =
  180747. {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
  180748. "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
  180749. if(png_ptr == NULL) return (NULL);
  180750. if (png_ptr->time_buffer == NULL)
  180751. {
  180752. png_ptr->time_buffer = (png_charp)png_malloc(png_ptr, (png_uint_32)(29*
  180753. png_sizeof(char)));
  180754. }
  180755. #if defined(_WIN32_WCE)
  180756. {
  180757. wchar_t time_buf[29];
  180758. wsprintf(time_buf, TEXT("%d %S %d %02d:%02d:%02d +0000"),
  180759. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  180760. ptime->year, ptime->hour % 24, ptime->minute % 60,
  180761. ptime->second % 61);
  180762. WideCharToMultiByte(CP_ACP, 0, time_buf, -1, png_ptr->time_buffer, 29,
  180763. NULL, NULL);
  180764. }
  180765. #else
  180766. #ifdef USE_FAR_KEYWORD
  180767. {
  180768. char near_time_buf[29];
  180769. png_snprintf6(near_time_buf,29,"%d %s %d %02d:%02d:%02d +0000",
  180770. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  180771. ptime->year, ptime->hour % 24, ptime->minute % 60,
  180772. ptime->second % 61);
  180773. png_memcpy(png_ptr->time_buffer, near_time_buf,
  180774. 29*png_sizeof(char));
  180775. }
  180776. #else
  180777. png_snprintf6(png_ptr->time_buffer,29,"%d %s %d %02d:%02d:%02d +0000",
  180778. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  180779. ptime->year, ptime->hour % 24, ptime->minute % 60,
  180780. ptime->second % 61);
  180781. #endif
  180782. #endif /* _WIN32_WCE */
  180783. return ((png_charp)png_ptr->time_buffer);
  180784. }
  180785. #endif /* PNG_TIME_RFC1123_SUPPORTED */
  180786. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  180787. png_charp PNGAPI
  180788. png_get_copyright(png_structp png_ptr)
  180789. {
  180790. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  180791. return ((png_charp) "\n libpng version 1.2.21 - October 4, 2007\n\
  180792. Copyright (c) 1998-2007 Glenn Randers-Pehrson\n\
  180793. Copyright (c) 1996-1997 Andreas Dilger\n\
  180794. Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc.\n");
  180795. }
  180796. /* The following return the library version as a short string in the
  180797. * format 1.0.0 through 99.99.99zz. To get the version of *.h files
  180798. * used with your application, print out PNG_LIBPNG_VER_STRING, which
  180799. * is defined in png.h.
  180800. * Note: now there is no difference between png_get_libpng_ver() and
  180801. * png_get_header_ver(). Due to the version_nn_nn_nn typedef guard,
  180802. * it is guaranteed that png.c uses the correct version of png.h.
  180803. */
  180804. png_charp PNGAPI
  180805. png_get_libpng_ver(png_structp png_ptr)
  180806. {
  180807. /* Version of *.c files used when building libpng */
  180808. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  180809. return ((png_charp) PNG_LIBPNG_VER_STRING);
  180810. }
  180811. png_charp PNGAPI
  180812. png_get_header_ver(png_structp png_ptr)
  180813. {
  180814. /* Version of *.h files used when building libpng */
  180815. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  180816. return ((png_charp) PNG_LIBPNG_VER_STRING);
  180817. }
  180818. png_charp PNGAPI
  180819. png_get_header_version(png_structp png_ptr)
  180820. {
  180821. /* Returns longer string containing both version and date */
  180822. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  180823. return ((png_charp) PNG_HEADER_VERSION_STRING
  180824. #ifndef PNG_READ_SUPPORTED
  180825. " (NO READ SUPPORT)"
  180826. #endif
  180827. "\n");
  180828. }
  180829. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  180830. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  180831. int PNGAPI
  180832. png_handle_as_unknown(png_structp png_ptr, png_bytep chunk_name)
  180833. {
  180834. /* check chunk_name and return "keep" value if it's on the list, else 0 */
  180835. int i;
  180836. png_bytep p;
  180837. if(png_ptr == NULL || chunk_name == NULL || png_ptr->num_chunk_list<=0)
  180838. return 0;
  180839. p=png_ptr->chunk_list+png_ptr->num_chunk_list*5-5;
  180840. for (i = png_ptr->num_chunk_list; i; i--, p-=5)
  180841. if (!png_memcmp(chunk_name, p, 4))
  180842. return ((int)*(p+4));
  180843. return 0;
  180844. }
  180845. #endif
  180846. /* This function, added to libpng-1.0.6g, is untested. */
  180847. int PNGAPI
  180848. png_reset_zstream(png_structp png_ptr)
  180849. {
  180850. if (png_ptr == NULL) return Z_STREAM_ERROR;
  180851. return (inflateReset(&png_ptr->zstream));
  180852. }
  180853. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  180854. /* This function was added to libpng-1.0.7 */
  180855. png_uint_32 PNGAPI
  180856. png_access_version_number(void)
  180857. {
  180858. /* Version of *.c files used when building libpng */
  180859. return((png_uint_32) PNG_LIBPNG_VER);
  180860. }
  180861. #if defined(PNG_READ_SUPPORTED) && defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  180862. #if !defined(PNG_1_0_X)
  180863. /* this function was added to libpng 1.2.0 */
  180864. int PNGAPI
  180865. png_mmx_support(void)
  180866. {
  180867. /* obsolete, to be removed from libpng-1.4.0 */
  180868. return -1;
  180869. }
  180870. #endif /* PNG_1_0_X */
  180871. #endif /* PNG_READ_SUPPORTED && PNG_ASSEMBLER_CODE_SUPPORTED */
  180872. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  180873. #ifdef PNG_SIZE_T
  180874. /* Added at libpng version 1.2.6 */
  180875. PNG_EXTERN png_size_t PNGAPI png_convert_size PNGARG((size_t size));
  180876. png_size_t PNGAPI
  180877. png_convert_size(size_t size)
  180878. {
  180879. if (size > (png_size_t)-1)
  180880. PNG_ABORT(); /* We haven't got access to png_ptr, so no png_error() */
  180881. return ((png_size_t)size);
  180882. }
  180883. #endif /* PNG_SIZE_T */
  180884. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  180885. /********* End of inlined file: png.c *********/
  180886. /********* Start of inlined file: pngerror.c *********/
  180887. /* pngerror.c - stub functions for i/o and memory allocation
  180888. *
  180889. * Last changed in libpng 1.2.20 October 4, 2007
  180890. * For conditions of distribution and use, see copyright notice in png.h
  180891. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  180892. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  180893. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  180894. *
  180895. * This file provides a location for all error handling. Users who
  180896. * need special error handling are expected to write replacement functions
  180897. * and use png_set_error_fn() to use those functions. See the instructions
  180898. * at each function.
  180899. */
  180900. #define PNG_INTERNAL
  180901. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  180902. static void /* PRIVATE */
  180903. png_default_error PNGARG((png_structp png_ptr,
  180904. png_const_charp error_message));
  180905. #ifndef PNG_NO_WARNINGS
  180906. static void /* PRIVATE */
  180907. png_default_warning PNGARG((png_structp png_ptr,
  180908. png_const_charp warning_message));
  180909. #endif /* PNG_NO_WARNINGS */
  180910. /* This function is called whenever there is a fatal error. This function
  180911. * should not be changed. If there is a need to handle errors differently,
  180912. * you should supply a replacement error function and use png_set_error_fn()
  180913. * to replace the error function at run-time.
  180914. */
  180915. #ifndef PNG_NO_ERROR_TEXT
  180916. void PNGAPI
  180917. png_error(png_structp png_ptr, png_const_charp error_message)
  180918. {
  180919. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  180920. char msg[16];
  180921. if (png_ptr != NULL)
  180922. {
  180923. if (png_ptr->flags&
  180924. (PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))
  180925. {
  180926. if (*error_message == '#')
  180927. {
  180928. int offset;
  180929. for (offset=1; offset<15; offset++)
  180930. if (*(error_message+offset) == ' ')
  180931. break;
  180932. if (png_ptr->flags&PNG_FLAG_STRIP_ERROR_TEXT)
  180933. {
  180934. int i;
  180935. for (i=0; i<offset-1; i++)
  180936. msg[i]=error_message[i+1];
  180937. msg[i]='\0';
  180938. error_message=msg;
  180939. }
  180940. else
  180941. error_message+=offset;
  180942. }
  180943. else
  180944. {
  180945. if (png_ptr->flags&PNG_FLAG_STRIP_ERROR_TEXT)
  180946. {
  180947. msg[0]='0';
  180948. msg[1]='\0';
  180949. error_message=msg;
  180950. }
  180951. }
  180952. }
  180953. }
  180954. #endif
  180955. if (png_ptr != NULL && png_ptr->error_fn != NULL)
  180956. (*(png_ptr->error_fn))(png_ptr, error_message);
  180957. /* If the custom handler doesn't exist, or if it returns,
  180958. use the default handler, which will not return. */
  180959. png_default_error(png_ptr, error_message);
  180960. }
  180961. #else
  180962. void PNGAPI
  180963. png_err(png_structp png_ptr)
  180964. {
  180965. if (png_ptr != NULL && png_ptr->error_fn != NULL)
  180966. (*(png_ptr->error_fn))(png_ptr, '\0');
  180967. /* If the custom handler doesn't exist, or if it returns,
  180968. use the default handler, which will not return. */
  180969. png_default_error(png_ptr, '\0');
  180970. }
  180971. #endif /* PNG_NO_ERROR_TEXT */
  180972. #ifndef PNG_NO_WARNINGS
  180973. /* This function is called whenever there is a non-fatal error. This function
  180974. * should not be changed. If there is a need to handle warnings differently,
  180975. * you should supply a replacement warning function and use
  180976. * png_set_error_fn() to replace the warning function at run-time.
  180977. */
  180978. void PNGAPI
  180979. png_warning(png_structp png_ptr, png_const_charp warning_message)
  180980. {
  180981. int offset = 0;
  180982. if (png_ptr != NULL)
  180983. {
  180984. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  180985. if (png_ptr->flags&
  180986. (PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))
  180987. #endif
  180988. {
  180989. if (*warning_message == '#')
  180990. {
  180991. for (offset=1; offset<15; offset++)
  180992. if (*(warning_message+offset) == ' ')
  180993. break;
  180994. }
  180995. }
  180996. if (png_ptr != NULL && png_ptr->warning_fn != NULL)
  180997. (*(png_ptr->warning_fn))(png_ptr, warning_message+offset);
  180998. }
  180999. else
  181000. png_default_warning(png_ptr, warning_message+offset);
  181001. }
  181002. #endif /* PNG_NO_WARNINGS */
  181003. /* These utilities are used internally to build an error message that relates
  181004. * to the current chunk. The chunk name comes from png_ptr->chunk_name,
  181005. * this is used to prefix the message. The message is limited in length
  181006. * to 63 bytes, the name characters are output as hex digits wrapped in []
  181007. * if the character is invalid.
  181008. */
  181009. #define isnonalpha(c) ((c) < 65 || (c) > 122 || ((c) > 90 && (c) < 97))
  181010. /*static PNG_CONST char png_digit[16] = {
  181011. '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
  181012. 'A', 'B', 'C', 'D', 'E', 'F'
  181013. };*/
  181014. #if !defined(PNG_NO_WARNINGS) || !defined(PNG_NO_ERROR_TEXT)
  181015. static void /* PRIVATE */
  181016. png_format_buffer(png_structp png_ptr, png_charp buffer, png_const_charp
  181017. error_message)
  181018. {
  181019. int iout = 0, iin = 0;
  181020. while (iin < 4)
  181021. {
  181022. int c = png_ptr->chunk_name[iin++];
  181023. if (isnonalpha(c))
  181024. {
  181025. buffer[iout++] = '[';
  181026. buffer[iout++] = png_digit[(c & 0xf0) >> 4];
  181027. buffer[iout++] = png_digit[c & 0x0f];
  181028. buffer[iout++] = ']';
  181029. }
  181030. else
  181031. {
  181032. buffer[iout++] = (png_byte)c;
  181033. }
  181034. }
  181035. if (error_message == NULL)
  181036. buffer[iout] = 0;
  181037. else
  181038. {
  181039. buffer[iout++] = ':';
  181040. buffer[iout++] = ' ';
  181041. png_strncpy(buffer+iout, error_message, 63);
  181042. buffer[iout+63] = 0;
  181043. }
  181044. }
  181045. #ifdef PNG_READ_SUPPORTED
  181046. void PNGAPI
  181047. png_chunk_error(png_structp png_ptr, png_const_charp error_message)
  181048. {
  181049. char msg[18+64];
  181050. if (png_ptr == NULL)
  181051. png_error(png_ptr, error_message);
  181052. else
  181053. {
  181054. png_format_buffer(png_ptr, msg, error_message);
  181055. png_error(png_ptr, msg);
  181056. }
  181057. }
  181058. #endif /* PNG_READ_SUPPORTED */
  181059. #endif /* !defined(PNG_NO_WARNINGS) || !defined(PNG_NO_ERROR_TEXT) */
  181060. #ifndef PNG_NO_WARNINGS
  181061. void PNGAPI
  181062. png_chunk_warning(png_structp png_ptr, png_const_charp warning_message)
  181063. {
  181064. char msg[18+64];
  181065. if (png_ptr == NULL)
  181066. png_warning(png_ptr, warning_message);
  181067. else
  181068. {
  181069. png_format_buffer(png_ptr, msg, warning_message);
  181070. png_warning(png_ptr, msg);
  181071. }
  181072. }
  181073. #endif /* PNG_NO_WARNINGS */
  181074. /* This is the default error handling function. Note that replacements for
  181075. * this function MUST NOT RETURN, or the program will likely crash. This
  181076. * function is used by default, or if the program supplies NULL for the
  181077. * error function pointer in png_set_error_fn().
  181078. */
  181079. static void /* PRIVATE */
  181080. png_default_error(png_structp png_ptr, png_const_charp error_message)
  181081. {
  181082. #ifndef PNG_NO_CONSOLE_IO
  181083. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  181084. if (*error_message == '#')
  181085. {
  181086. int offset;
  181087. char error_number[16];
  181088. for (offset=0; offset<15; offset++)
  181089. {
  181090. error_number[offset] = *(error_message+offset+1);
  181091. if (*(error_message+offset) == ' ')
  181092. break;
  181093. }
  181094. if((offset > 1) && (offset < 15))
  181095. {
  181096. error_number[offset-1]='\0';
  181097. fprintf(stderr, "libpng error no. %s: %s\n", error_number,
  181098. error_message+offset);
  181099. }
  181100. else
  181101. fprintf(stderr, "libpng error: %s, offset=%d\n", error_message,offset);
  181102. }
  181103. else
  181104. #endif
  181105. fprintf(stderr, "libpng error: %s\n", error_message);
  181106. #endif
  181107. #ifdef PNG_SETJMP_SUPPORTED
  181108. if (png_ptr)
  181109. {
  181110. # ifdef USE_FAR_KEYWORD
  181111. {
  181112. jmp_buf jmpbuf;
  181113. png_memcpy(jmpbuf, png_ptr->jmpbuf, png_sizeof(jmp_buf));
  181114. longjmp(jmpbuf, 1);
  181115. }
  181116. # else
  181117. longjmp(png_ptr->jmpbuf, 1);
  181118. # endif
  181119. }
  181120. #else
  181121. PNG_ABORT();
  181122. #endif
  181123. #ifdef PNG_NO_CONSOLE_IO
  181124. error_message = error_message; /* make compiler happy */
  181125. #endif
  181126. }
  181127. #ifndef PNG_NO_WARNINGS
  181128. /* This function is called when there is a warning, but the library thinks
  181129. * it can continue anyway. Replacement functions don't have to do anything
  181130. * here if you don't want them to. In the default configuration, png_ptr is
  181131. * not used, but it is passed in case it may be useful.
  181132. */
  181133. static void /* PRIVATE */
  181134. png_default_warning(png_structp png_ptr, png_const_charp warning_message)
  181135. {
  181136. #ifndef PNG_NO_CONSOLE_IO
  181137. # ifdef PNG_ERROR_NUMBERS_SUPPORTED
  181138. if (*warning_message == '#')
  181139. {
  181140. int offset;
  181141. char warning_number[16];
  181142. for (offset=0; offset<15; offset++)
  181143. {
  181144. warning_number[offset]=*(warning_message+offset+1);
  181145. if (*(warning_message+offset) == ' ')
  181146. break;
  181147. }
  181148. if((offset > 1) && (offset < 15))
  181149. {
  181150. warning_number[offset-1]='\0';
  181151. fprintf(stderr, "libpng warning no. %s: %s\n", warning_number,
  181152. warning_message+offset);
  181153. }
  181154. else
  181155. fprintf(stderr, "libpng warning: %s\n", warning_message);
  181156. }
  181157. else
  181158. # endif
  181159. fprintf(stderr, "libpng warning: %s\n", warning_message);
  181160. #else
  181161. warning_message = warning_message; /* make compiler happy */
  181162. #endif
  181163. png_ptr = png_ptr; /* make compiler happy */
  181164. }
  181165. #endif /* PNG_NO_WARNINGS */
  181166. /* This function is called when the application wants to use another method
  181167. * of handling errors and warnings. Note that the error function MUST NOT
  181168. * return to the calling routine or serious problems will occur. The return
  181169. * method used in the default routine calls longjmp(png_ptr->jmpbuf, 1)
  181170. */
  181171. void PNGAPI
  181172. png_set_error_fn(png_structp png_ptr, png_voidp error_ptr,
  181173. png_error_ptr error_fn, png_error_ptr warning_fn)
  181174. {
  181175. if (png_ptr == NULL)
  181176. return;
  181177. png_ptr->error_ptr = error_ptr;
  181178. png_ptr->error_fn = error_fn;
  181179. png_ptr->warning_fn = warning_fn;
  181180. }
  181181. /* This function returns a pointer to the error_ptr associated with the user
  181182. * functions. The application should free any memory associated with this
  181183. * pointer before png_write_destroy and png_read_destroy are called.
  181184. */
  181185. png_voidp PNGAPI
  181186. png_get_error_ptr(png_structp png_ptr)
  181187. {
  181188. if (png_ptr == NULL)
  181189. return NULL;
  181190. return ((png_voidp)png_ptr->error_ptr);
  181191. }
  181192. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  181193. void PNGAPI
  181194. png_set_strip_error_numbers(png_structp png_ptr, png_uint_32 strip_mode)
  181195. {
  181196. if(png_ptr != NULL)
  181197. {
  181198. png_ptr->flags &=
  181199. ((~(PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))&strip_mode);
  181200. }
  181201. }
  181202. #endif
  181203. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  181204. /********* End of inlined file: pngerror.c *********/
  181205. /********* Start of inlined file: pngget.c *********/
  181206. /* pngget.c - retrieval of values from info struct
  181207. *
  181208. * Last changed in libpng 1.2.15 January 5, 2007
  181209. * For conditions of distribution and use, see copyright notice in png.h
  181210. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  181211. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  181212. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  181213. */
  181214. #define PNG_INTERNAL
  181215. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  181216. png_uint_32 PNGAPI
  181217. png_get_valid(png_structp png_ptr, png_infop info_ptr, png_uint_32 flag)
  181218. {
  181219. if (png_ptr != NULL && info_ptr != NULL)
  181220. return(info_ptr->valid & flag);
  181221. else
  181222. return(0);
  181223. }
  181224. png_uint_32 PNGAPI
  181225. png_get_rowbytes(png_structp png_ptr, png_infop info_ptr)
  181226. {
  181227. if (png_ptr != NULL && info_ptr != NULL)
  181228. return(info_ptr->rowbytes);
  181229. else
  181230. return(0);
  181231. }
  181232. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  181233. png_bytepp PNGAPI
  181234. png_get_rows(png_structp png_ptr, png_infop info_ptr)
  181235. {
  181236. if (png_ptr != NULL && info_ptr != NULL)
  181237. return(info_ptr->row_pointers);
  181238. else
  181239. return(0);
  181240. }
  181241. #endif
  181242. #ifdef PNG_EASY_ACCESS_SUPPORTED
  181243. /* easy access to info, added in libpng-0.99 */
  181244. png_uint_32 PNGAPI
  181245. png_get_image_width(png_structp png_ptr, png_infop info_ptr)
  181246. {
  181247. if (png_ptr != NULL && info_ptr != NULL)
  181248. {
  181249. return info_ptr->width;
  181250. }
  181251. return (0);
  181252. }
  181253. png_uint_32 PNGAPI
  181254. png_get_image_height(png_structp png_ptr, png_infop info_ptr)
  181255. {
  181256. if (png_ptr != NULL && info_ptr != NULL)
  181257. {
  181258. return info_ptr->height;
  181259. }
  181260. return (0);
  181261. }
  181262. png_byte PNGAPI
  181263. png_get_bit_depth(png_structp png_ptr, png_infop info_ptr)
  181264. {
  181265. if (png_ptr != NULL && info_ptr != NULL)
  181266. {
  181267. return info_ptr->bit_depth;
  181268. }
  181269. return (0);
  181270. }
  181271. png_byte PNGAPI
  181272. png_get_color_type(png_structp png_ptr, png_infop info_ptr)
  181273. {
  181274. if (png_ptr != NULL && info_ptr != NULL)
  181275. {
  181276. return info_ptr->color_type;
  181277. }
  181278. return (0);
  181279. }
  181280. png_byte PNGAPI
  181281. png_get_filter_type(png_structp png_ptr, png_infop info_ptr)
  181282. {
  181283. if (png_ptr != NULL && info_ptr != NULL)
  181284. {
  181285. return info_ptr->filter_type;
  181286. }
  181287. return (0);
  181288. }
  181289. png_byte PNGAPI
  181290. png_get_interlace_type(png_structp png_ptr, png_infop info_ptr)
  181291. {
  181292. if (png_ptr != NULL && info_ptr != NULL)
  181293. {
  181294. return info_ptr->interlace_type;
  181295. }
  181296. return (0);
  181297. }
  181298. png_byte PNGAPI
  181299. png_get_compression_type(png_structp png_ptr, png_infop info_ptr)
  181300. {
  181301. if (png_ptr != NULL && info_ptr != NULL)
  181302. {
  181303. return info_ptr->compression_type;
  181304. }
  181305. return (0);
  181306. }
  181307. png_uint_32 PNGAPI
  181308. png_get_x_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  181309. {
  181310. if (png_ptr != NULL && info_ptr != NULL)
  181311. #if defined(PNG_pHYs_SUPPORTED)
  181312. if (info_ptr->valid & PNG_INFO_pHYs)
  181313. {
  181314. png_debug1(1, "in %s retrieval function\n", "png_get_x_pixels_per_meter");
  181315. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER)
  181316. return (0);
  181317. else return (info_ptr->x_pixels_per_unit);
  181318. }
  181319. #else
  181320. return (0);
  181321. #endif
  181322. return (0);
  181323. }
  181324. png_uint_32 PNGAPI
  181325. png_get_y_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  181326. {
  181327. if (png_ptr != NULL && info_ptr != NULL)
  181328. #if defined(PNG_pHYs_SUPPORTED)
  181329. if (info_ptr->valid & PNG_INFO_pHYs)
  181330. {
  181331. png_debug1(1, "in %s retrieval function\n", "png_get_y_pixels_per_meter");
  181332. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER)
  181333. return (0);
  181334. else return (info_ptr->y_pixels_per_unit);
  181335. }
  181336. #else
  181337. return (0);
  181338. #endif
  181339. return (0);
  181340. }
  181341. png_uint_32 PNGAPI
  181342. png_get_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  181343. {
  181344. if (png_ptr != NULL && info_ptr != NULL)
  181345. #if defined(PNG_pHYs_SUPPORTED)
  181346. if (info_ptr->valid & PNG_INFO_pHYs)
  181347. {
  181348. png_debug1(1, "in %s retrieval function\n", "png_get_pixels_per_meter");
  181349. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER ||
  181350. info_ptr->x_pixels_per_unit != info_ptr->y_pixels_per_unit)
  181351. return (0);
  181352. else return (info_ptr->x_pixels_per_unit);
  181353. }
  181354. #else
  181355. return (0);
  181356. #endif
  181357. return (0);
  181358. }
  181359. #ifdef PNG_FLOATING_POINT_SUPPORTED
  181360. float PNGAPI
  181361. png_get_pixel_aspect_ratio(png_structp png_ptr, png_infop info_ptr)
  181362. {
  181363. if (png_ptr != NULL && info_ptr != NULL)
  181364. #if defined(PNG_pHYs_SUPPORTED)
  181365. if (info_ptr->valid & PNG_INFO_pHYs)
  181366. {
  181367. png_debug1(1, "in %s retrieval function\n", "png_get_aspect_ratio");
  181368. if (info_ptr->x_pixels_per_unit == 0)
  181369. return ((float)0.0);
  181370. else
  181371. return ((float)((float)info_ptr->y_pixels_per_unit
  181372. /(float)info_ptr->x_pixels_per_unit));
  181373. }
  181374. #else
  181375. return (0.0);
  181376. #endif
  181377. return ((float)0.0);
  181378. }
  181379. #endif
  181380. png_int_32 PNGAPI
  181381. png_get_x_offset_microns(png_structp png_ptr, png_infop info_ptr)
  181382. {
  181383. if (png_ptr != NULL && info_ptr != NULL)
  181384. #if defined(PNG_oFFs_SUPPORTED)
  181385. if (info_ptr->valid & PNG_INFO_oFFs)
  181386. {
  181387. png_debug1(1, "in %s retrieval function\n", "png_get_x_offset_microns");
  181388. if(info_ptr->offset_unit_type != PNG_OFFSET_MICROMETER)
  181389. return (0);
  181390. else return (info_ptr->x_offset);
  181391. }
  181392. #else
  181393. return (0);
  181394. #endif
  181395. return (0);
  181396. }
  181397. png_int_32 PNGAPI
  181398. png_get_y_offset_microns(png_structp png_ptr, png_infop info_ptr)
  181399. {
  181400. if (png_ptr != NULL && info_ptr != NULL)
  181401. #if defined(PNG_oFFs_SUPPORTED)
  181402. if (info_ptr->valid & PNG_INFO_oFFs)
  181403. {
  181404. png_debug1(1, "in %s retrieval function\n", "png_get_y_offset_microns");
  181405. if(info_ptr->offset_unit_type != PNG_OFFSET_MICROMETER)
  181406. return (0);
  181407. else return (info_ptr->y_offset);
  181408. }
  181409. #else
  181410. return (0);
  181411. #endif
  181412. return (0);
  181413. }
  181414. png_int_32 PNGAPI
  181415. png_get_x_offset_pixels(png_structp png_ptr, png_infop info_ptr)
  181416. {
  181417. if (png_ptr != NULL && info_ptr != NULL)
  181418. #if defined(PNG_oFFs_SUPPORTED)
  181419. if (info_ptr->valid & PNG_INFO_oFFs)
  181420. {
  181421. png_debug1(1, "in %s retrieval function\n", "png_get_x_offset_microns");
  181422. if(info_ptr->offset_unit_type != PNG_OFFSET_PIXEL)
  181423. return (0);
  181424. else return (info_ptr->x_offset);
  181425. }
  181426. #else
  181427. return (0);
  181428. #endif
  181429. return (0);
  181430. }
  181431. png_int_32 PNGAPI
  181432. png_get_y_offset_pixels(png_structp png_ptr, png_infop info_ptr)
  181433. {
  181434. if (png_ptr != NULL && info_ptr != NULL)
  181435. #if defined(PNG_oFFs_SUPPORTED)
  181436. if (info_ptr->valid & PNG_INFO_oFFs)
  181437. {
  181438. png_debug1(1, "in %s retrieval function\n", "png_get_y_offset_microns");
  181439. if(info_ptr->offset_unit_type != PNG_OFFSET_PIXEL)
  181440. return (0);
  181441. else return (info_ptr->y_offset);
  181442. }
  181443. #else
  181444. return (0);
  181445. #endif
  181446. return (0);
  181447. }
  181448. #if defined(PNG_INCH_CONVERSIONS) && defined(PNG_FLOATING_POINT_SUPPORTED)
  181449. png_uint_32 PNGAPI
  181450. png_get_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  181451. {
  181452. return ((png_uint_32)((float)png_get_pixels_per_meter(png_ptr, info_ptr)
  181453. *.0254 +.5));
  181454. }
  181455. png_uint_32 PNGAPI
  181456. png_get_x_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  181457. {
  181458. return ((png_uint_32)((float)png_get_x_pixels_per_meter(png_ptr, info_ptr)
  181459. *.0254 +.5));
  181460. }
  181461. png_uint_32 PNGAPI
  181462. png_get_y_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  181463. {
  181464. return ((png_uint_32)((float)png_get_y_pixels_per_meter(png_ptr, info_ptr)
  181465. *.0254 +.5));
  181466. }
  181467. float PNGAPI
  181468. png_get_x_offset_inches(png_structp png_ptr, png_infop info_ptr)
  181469. {
  181470. return ((float)png_get_x_offset_microns(png_ptr, info_ptr)
  181471. *.00003937);
  181472. }
  181473. float PNGAPI
  181474. png_get_y_offset_inches(png_structp png_ptr, png_infop info_ptr)
  181475. {
  181476. return ((float)png_get_y_offset_microns(png_ptr, info_ptr)
  181477. *.00003937);
  181478. }
  181479. #if defined(PNG_pHYs_SUPPORTED)
  181480. png_uint_32 PNGAPI
  181481. png_get_pHYs_dpi(png_structp png_ptr, png_infop info_ptr,
  181482. png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type)
  181483. {
  181484. png_uint_32 retval = 0;
  181485. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_pHYs))
  181486. {
  181487. png_debug1(1, "in %s retrieval function\n", "pHYs");
  181488. if (res_x != NULL)
  181489. {
  181490. *res_x = info_ptr->x_pixels_per_unit;
  181491. retval |= PNG_INFO_pHYs;
  181492. }
  181493. if (res_y != NULL)
  181494. {
  181495. *res_y = info_ptr->y_pixels_per_unit;
  181496. retval |= PNG_INFO_pHYs;
  181497. }
  181498. if (unit_type != NULL)
  181499. {
  181500. *unit_type = (int)info_ptr->phys_unit_type;
  181501. retval |= PNG_INFO_pHYs;
  181502. if(*unit_type == 1)
  181503. {
  181504. if (res_x != NULL) *res_x = (png_uint_32)(*res_x * .0254 + .50);
  181505. if (res_y != NULL) *res_y = (png_uint_32)(*res_y * .0254 + .50);
  181506. }
  181507. }
  181508. }
  181509. return (retval);
  181510. }
  181511. #endif /* PNG_pHYs_SUPPORTED */
  181512. #endif /* PNG_INCH_CONVERSIONS && PNG_FLOATING_POINT_SUPPORTED */
  181513. /* png_get_channels really belongs in here, too, but it's been around longer */
  181514. #endif /* PNG_EASY_ACCESS_SUPPORTED */
  181515. png_byte PNGAPI
  181516. png_get_channels(png_structp png_ptr, png_infop info_ptr)
  181517. {
  181518. if (png_ptr != NULL && info_ptr != NULL)
  181519. return(info_ptr->channels);
  181520. else
  181521. return (0);
  181522. }
  181523. png_bytep PNGAPI
  181524. png_get_signature(png_structp png_ptr, png_infop info_ptr)
  181525. {
  181526. if (png_ptr != NULL && info_ptr != NULL)
  181527. return(info_ptr->signature);
  181528. else
  181529. return (NULL);
  181530. }
  181531. #if defined(PNG_bKGD_SUPPORTED)
  181532. png_uint_32 PNGAPI
  181533. png_get_bKGD(png_structp png_ptr, png_infop info_ptr,
  181534. png_color_16p *background)
  181535. {
  181536. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_bKGD)
  181537. && background != NULL)
  181538. {
  181539. png_debug1(1, "in %s retrieval function\n", "bKGD");
  181540. *background = &(info_ptr->background);
  181541. return (PNG_INFO_bKGD);
  181542. }
  181543. return (0);
  181544. }
  181545. #endif
  181546. #if defined(PNG_cHRM_SUPPORTED)
  181547. #ifdef PNG_FLOATING_POINT_SUPPORTED
  181548. png_uint_32 PNGAPI
  181549. png_get_cHRM(png_structp png_ptr, png_infop info_ptr,
  181550. double *white_x, double *white_y, double *red_x, double *red_y,
  181551. double *green_x, double *green_y, double *blue_x, double *blue_y)
  181552. {
  181553. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  181554. {
  181555. png_debug1(1, "in %s retrieval function\n", "cHRM");
  181556. if (white_x != NULL)
  181557. *white_x = (double)info_ptr->x_white;
  181558. if (white_y != NULL)
  181559. *white_y = (double)info_ptr->y_white;
  181560. if (red_x != NULL)
  181561. *red_x = (double)info_ptr->x_red;
  181562. if (red_y != NULL)
  181563. *red_y = (double)info_ptr->y_red;
  181564. if (green_x != NULL)
  181565. *green_x = (double)info_ptr->x_green;
  181566. if (green_y != NULL)
  181567. *green_y = (double)info_ptr->y_green;
  181568. if (blue_x != NULL)
  181569. *blue_x = (double)info_ptr->x_blue;
  181570. if (blue_y != NULL)
  181571. *blue_y = (double)info_ptr->y_blue;
  181572. return (PNG_INFO_cHRM);
  181573. }
  181574. return (0);
  181575. }
  181576. #endif
  181577. #ifdef PNG_FIXED_POINT_SUPPORTED
  181578. png_uint_32 PNGAPI
  181579. png_get_cHRM_fixed(png_structp png_ptr, png_infop info_ptr,
  181580. png_fixed_point *white_x, png_fixed_point *white_y, png_fixed_point *red_x,
  181581. png_fixed_point *red_y, png_fixed_point *green_x, png_fixed_point *green_y,
  181582. png_fixed_point *blue_x, png_fixed_point *blue_y)
  181583. {
  181584. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  181585. {
  181586. png_debug1(1, "in %s retrieval function\n", "cHRM");
  181587. if (white_x != NULL)
  181588. *white_x = info_ptr->int_x_white;
  181589. if (white_y != NULL)
  181590. *white_y = info_ptr->int_y_white;
  181591. if (red_x != NULL)
  181592. *red_x = info_ptr->int_x_red;
  181593. if (red_y != NULL)
  181594. *red_y = info_ptr->int_y_red;
  181595. if (green_x != NULL)
  181596. *green_x = info_ptr->int_x_green;
  181597. if (green_y != NULL)
  181598. *green_y = info_ptr->int_y_green;
  181599. if (blue_x != NULL)
  181600. *blue_x = info_ptr->int_x_blue;
  181601. if (blue_y != NULL)
  181602. *blue_y = info_ptr->int_y_blue;
  181603. return (PNG_INFO_cHRM);
  181604. }
  181605. return (0);
  181606. }
  181607. #endif
  181608. #endif
  181609. #if defined(PNG_gAMA_SUPPORTED)
  181610. #ifdef PNG_FLOATING_POINT_SUPPORTED
  181611. png_uint_32 PNGAPI
  181612. png_get_gAMA(png_structp png_ptr, png_infop info_ptr, double *file_gamma)
  181613. {
  181614. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  181615. && file_gamma != NULL)
  181616. {
  181617. png_debug1(1, "in %s retrieval function\n", "gAMA");
  181618. *file_gamma = (double)info_ptr->gamma;
  181619. return (PNG_INFO_gAMA);
  181620. }
  181621. return (0);
  181622. }
  181623. #endif
  181624. #ifdef PNG_FIXED_POINT_SUPPORTED
  181625. png_uint_32 PNGAPI
  181626. png_get_gAMA_fixed(png_structp png_ptr, png_infop info_ptr,
  181627. png_fixed_point *int_file_gamma)
  181628. {
  181629. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  181630. && int_file_gamma != NULL)
  181631. {
  181632. png_debug1(1, "in %s retrieval function\n", "gAMA");
  181633. *int_file_gamma = info_ptr->int_gamma;
  181634. return (PNG_INFO_gAMA);
  181635. }
  181636. return (0);
  181637. }
  181638. #endif
  181639. #endif
  181640. #if defined(PNG_sRGB_SUPPORTED)
  181641. png_uint_32 PNGAPI
  181642. png_get_sRGB(png_structp png_ptr, png_infop info_ptr, int *file_srgb_intent)
  181643. {
  181644. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB)
  181645. && file_srgb_intent != NULL)
  181646. {
  181647. png_debug1(1, "in %s retrieval function\n", "sRGB");
  181648. *file_srgb_intent = (int)info_ptr->srgb_intent;
  181649. return (PNG_INFO_sRGB);
  181650. }
  181651. return (0);
  181652. }
  181653. #endif
  181654. #if defined(PNG_iCCP_SUPPORTED)
  181655. png_uint_32 PNGAPI
  181656. png_get_iCCP(png_structp png_ptr, png_infop info_ptr,
  181657. png_charpp name, int *compression_type,
  181658. png_charpp profile, png_uint_32 *proflen)
  181659. {
  181660. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_iCCP)
  181661. && name != NULL && profile != NULL && proflen != NULL)
  181662. {
  181663. png_debug1(1, "in %s retrieval function\n", "iCCP");
  181664. *name = info_ptr->iccp_name;
  181665. *profile = info_ptr->iccp_profile;
  181666. /* compression_type is a dummy so the API won't have to change
  181667. if we introduce multiple compression types later. */
  181668. *proflen = (int)info_ptr->iccp_proflen;
  181669. *compression_type = (int)info_ptr->iccp_compression;
  181670. return (PNG_INFO_iCCP);
  181671. }
  181672. return (0);
  181673. }
  181674. #endif
  181675. #if defined(PNG_sPLT_SUPPORTED)
  181676. png_uint_32 PNGAPI
  181677. png_get_sPLT(png_structp png_ptr, png_infop info_ptr,
  181678. png_sPLT_tpp spalettes)
  181679. {
  181680. if (png_ptr != NULL && info_ptr != NULL && spalettes != NULL)
  181681. {
  181682. *spalettes = info_ptr->splt_palettes;
  181683. return ((png_uint_32)info_ptr->splt_palettes_num);
  181684. }
  181685. return (0);
  181686. }
  181687. #endif
  181688. #if defined(PNG_hIST_SUPPORTED)
  181689. png_uint_32 PNGAPI
  181690. png_get_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_16p *hist)
  181691. {
  181692. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_hIST)
  181693. && hist != NULL)
  181694. {
  181695. png_debug1(1, "in %s retrieval function\n", "hIST");
  181696. *hist = info_ptr->hist;
  181697. return (PNG_INFO_hIST);
  181698. }
  181699. return (0);
  181700. }
  181701. #endif
  181702. png_uint_32 PNGAPI
  181703. png_get_IHDR(png_structp png_ptr, png_infop info_ptr,
  181704. png_uint_32 *width, png_uint_32 *height, int *bit_depth,
  181705. int *color_type, int *interlace_type, int *compression_type,
  181706. int *filter_type)
  181707. {
  181708. if (png_ptr != NULL && info_ptr != NULL && width != NULL && height != NULL &&
  181709. bit_depth != NULL && color_type != NULL)
  181710. {
  181711. png_debug1(1, "in %s retrieval function\n", "IHDR");
  181712. *width = info_ptr->width;
  181713. *height = info_ptr->height;
  181714. *bit_depth = info_ptr->bit_depth;
  181715. if (info_ptr->bit_depth < 1 || info_ptr->bit_depth > 16)
  181716. png_error(png_ptr, "Invalid bit depth");
  181717. *color_type = info_ptr->color_type;
  181718. if (info_ptr->color_type > 6)
  181719. png_error(png_ptr, "Invalid color type");
  181720. if (compression_type != NULL)
  181721. *compression_type = info_ptr->compression_type;
  181722. if (filter_type != NULL)
  181723. *filter_type = info_ptr->filter_type;
  181724. if (interlace_type != NULL)
  181725. *interlace_type = info_ptr->interlace_type;
  181726. /* check for potential overflow of rowbytes */
  181727. if (*width == 0 || *width > PNG_UINT_31_MAX)
  181728. png_error(png_ptr, "Invalid image width");
  181729. if (*height == 0 || *height > PNG_UINT_31_MAX)
  181730. png_error(png_ptr, "Invalid image height");
  181731. if (info_ptr->width > (PNG_UINT_32_MAX
  181732. >> 3) /* 8-byte RGBA pixels */
  181733. - 64 /* bigrowbuf hack */
  181734. - 1 /* filter byte */
  181735. - 7*8 /* rounding of width to multiple of 8 pixels */
  181736. - 8) /* extra max_pixel_depth pad */
  181737. {
  181738. png_warning(png_ptr,
  181739. "Width too large for libpng to process image data.");
  181740. }
  181741. return (1);
  181742. }
  181743. return (0);
  181744. }
  181745. #if defined(PNG_oFFs_SUPPORTED)
  181746. png_uint_32 PNGAPI
  181747. png_get_oFFs(png_structp png_ptr, png_infop info_ptr,
  181748. png_int_32 *offset_x, png_int_32 *offset_y, int *unit_type)
  181749. {
  181750. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_oFFs)
  181751. && offset_x != NULL && offset_y != NULL && unit_type != NULL)
  181752. {
  181753. png_debug1(1, "in %s retrieval function\n", "oFFs");
  181754. *offset_x = info_ptr->x_offset;
  181755. *offset_y = info_ptr->y_offset;
  181756. *unit_type = (int)info_ptr->offset_unit_type;
  181757. return (PNG_INFO_oFFs);
  181758. }
  181759. return (0);
  181760. }
  181761. #endif
  181762. #if defined(PNG_pCAL_SUPPORTED)
  181763. png_uint_32 PNGAPI
  181764. png_get_pCAL(png_structp png_ptr, png_infop info_ptr,
  181765. png_charp *purpose, png_int_32 *X0, png_int_32 *X1, int *type, int *nparams,
  181766. png_charp *units, png_charpp *params)
  181767. {
  181768. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_pCAL)
  181769. && purpose != NULL && X0 != NULL && X1 != NULL && type != NULL &&
  181770. nparams != NULL && units != NULL && params != NULL)
  181771. {
  181772. png_debug1(1, "in %s retrieval function\n", "pCAL");
  181773. *purpose = info_ptr->pcal_purpose;
  181774. *X0 = info_ptr->pcal_X0;
  181775. *X1 = info_ptr->pcal_X1;
  181776. *type = (int)info_ptr->pcal_type;
  181777. *nparams = (int)info_ptr->pcal_nparams;
  181778. *units = info_ptr->pcal_units;
  181779. *params = info_ptr->pcal_params;
  181780. return (PNG_INFO_pCAL);
  181781. }
  181782. return (0);
  181783. }
  181784. #endif
  181785. #if defined(PNG_sCAL_SUPPORTED)
  181786. #ifdef PNG_FLOATING_POINT_SUPPORTED
  181787. png_uint_32 PNGAPI
  181788. png_get_sCAL(png_structp png_ptr, png_infop info_ptr,
  181789. int *unit, double *width, double *height)
  181790. {
  181791. if (png_ptr != NULL && info_ptr != NULL &&
  181792. (info_ptr->valid & PNG_INFO_sCAL))
  181793. {
  181794. *unit = info_ptr->scal_unit;
  181795. *width = info_ptr->scal_pixel_width;
  181796. *height = info_ptr->scal_pixel_height;
  181797. return (PNG_INFO_sCAL);
  181798. }
  181799. return(0);
  181800. }
  181801. #else
  181802. #ifdef PNG_FIXED_POINT_SUPPORTED
  181803. png_uint_32 PNGAPI
  181804. png_get_sCAL_s(png_structp png_ptr, png_infop info_ptr,
  181805. int *unit, png_charpp width, png_charpp height)
  181806. {
  181807. if (png_ptr != NULL && info_ptr != NULL &&
  181808. (info_ptr->valid & PNG_INFO_sCAL))
  181809. {
  181810. *unit = info_ptr->scal_unit;
  181811. *width = info_ptr->scal_s_width;
  181812. *height = info_ptr->scal_s_height;
  181813. return (PNG_INFO_sCAL);
  181814. }
  181815. return(0);
  181816. }
  181817. #endif
  181818. #endif
  181819. #endif
  181820. #if defined(PNG_pHYs_SUPPORTED)
  181821. png_uint_32 PNGAPI
  181822. png_get_pHYs(png_structp png_ptr, png_infop info_ptr,
  181823. png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type)
  181824. {
  181825. png_uint_32 retval = 0;
  181826. if (png_ptr != NULL && info_ptr != NULL &&
  181827. (info_ptr->valid & PNG_INFO_pHYs))
  181828. {
  181829. png_debug1(1, "in %s retrieval function\n", "pHYs");
  181830. if (res_x != NULL)
  181831. {
  181832. *res_x = info_ptr->x_pixels_per_unit;
  181833. retval |= PNG_INFO_pHYs;
  181834. }
  181835. if (res_y != NULL)
  181836. {
  181837. *res_y = info_ptr->y_pixels_per_unit;
  181838. retval |= PNG_INFO_pHYs;
  181839. }
  181840. if (unit_type != NULL)
  181841. {
  181842. *unit_type = (int)info_ptr->phys_unit_type;
  181843. retval |= PNG_INFO_pHYs;
  181844. }
  181845. }
  181846. return (retval);
  181847. }
  181848. #endif
  181849. png_uint_32 PNGAPI
  181850. png_get_PLTE(png_structp png_ptr, png_infop info_ptr, png_colorp *palette,
  181851. int *num_palette)
  181852. {
  181853. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_PLTE)
  181854. && palette != NULL)
  181855. {
  181856. png_debug1(1, "in %s retrieval function\n", "PLTE");
  181857. *palette = info_ptr->palette;
  181858. *num_palette = info_ptr->num_palette;
  181859. png_debug1(3, "num_palette = %d\n", *num_palette);
  181860. return (PNG_INFO_PLTE);
  181861. }
  181862. return (0);
  181863. }
  181864. #if defined(PNG_sBIT_SUPPORTED)
  181865. png_uint_32 PNGAPI
  181866. png_get_sBIT(png_structp png_ptr, png_infop info_ptr, png_color_8p *sig_bit)
  181867. {
  181868. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_sBIT)
  181869. && sig_bit != NULL)
  181870. {
  181871. png_debug1(1, "in %s retrieval function\n", "sBIT");
  181872. *sig_bit = &(info_ptr->sig_bit);
  181873. return (PNG_INFO_sBIT);
  181874. }
  181875. return (0);
  181876. }
  181877. #endif
  181878. #if defined(PNG_TEXT_SUPPORTED)
  181879. png_uint_32 PNGAPI
  181880. png_get_text(png_structp png_ptr, png_infop info_ptr, png_textp *text_ptr,
  181881. int *num_text)
  181882. {
  181883. if (png_ptr != NULL && info_ptr != NULL && info_ptr->num_text > 0)
  181884. {
  181885. png_debug1(1, "in %s retrieval function\n",
  181886. (png_ptr->chunk_name[0] == '\0' ? "text"
  181887. : (png_const_charp)png_ptr->chunk_name));
  181888. if (text_ptr != NULL)
  181889. *text_ptr = info_ptr->text;
  181890. if (num_text != NULL)
  181891. *num_text = info_ptr->num_text;
  181892. return ((png_uint_32)info_ptr->num_text);
  181893. }
  181894. if (num_text != NULL)
  181895. *num_text = 0;
  181896. return(0);
  181897. }
  181898. #endif
  181899. #if defined(PNG_tIME_SUPPORTED)
  181900. png_uint_32 PNGAPI
  181901. png_get_tIME(png_structp png_ptr, png_infop info_ptr, png_timep *mod_time)
  181902. {
  181903. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_tIME)
  181904. && mod_time != NULL)
  181905. {
  181906. png_debug1(1, "in %s retrieval function\n", "tIME");
  181907. *mod_time = &(info_ptr->mod_time);
  181908. return (PNG_INFO_tIME);
  181909. }
  181910. return (0);
  181911. }
  181912. #endif
  181913. #if defined(PNG_tRNS_SUPPORTED)
  181914. png_uint_32 PNGAPI
  181915. png_get_tRNS(png_structp png_ptr, png_infop info_ptr,
  181916. png_bytep *trans, int *num_trans, png_color_16p *trans_values)
  181917. {
  181918. png_uint_32 retval = 0;
  181919. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  181920. {
  181921. png_debug1(1, "in %s retrieval function\n", "tRNS");
  181922. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  181923. {
  181924. if (trans != NULL)
  181925. {
  181926. *trans = info_ptr->trans;
  181927. retval |= PNG_INFO_tRNS;
  181928. }
  181929. if (trans_values != NULL)
  181930. *trans_values = &(info_ptr->trans_values);
  181931. }
  181932. else /* if (info_ptr->color_type != PNG_COLOR_TYPE_PALETTE) */
  181933. {
  181934. if (trans_values != NULL)
  181935. {
  181936. *trans_values = &(info_ptr->trans_values);
  181937. retval |= PNG_INFO_tRNS;
  181938. }
  181939. if(trans != NULL)
  181940. *trans = NULL;
  181941. }
  181942. if(num_trans != NULL)
  181943. {
  181944. *num_trans = info_ptr->num_trans;
  181945. retval |= PNG_INFO_tRNS;
  181946. }
  181947. }
  181948. return (retval);
  181949. }
  181950. #endif
  181951. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  181952. png_uint_32 PNGAPI
  181953. png_get_unknown_chunks(png_structp png_ptr, png_infop info_ptr,
  181954. png_unknown_chunkpp unknowns)
  181955. {
  181956. if (png_ptr != NULL && info_ptr != NULL && unknowns != NULL)
  181957. {
  181958. *unknowns = info_ptr->unknown_chunks;
  181959. return ((png_uint_32)info_ptr->unknown_chunks_num);
  181960. }
  181961. return (0);
  181962. }
  181963. #endif
  181964. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  181965. png_byte PNGAPI
  181966. png_get_rgb_to_gray_status (png_structp png_ptr)
  181967. {
  181968. return (png_byte)(png_ptr? png_ptr->rgb_to_gray_status : 0);
  181969. }
  181970. #endif
  181971. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  181972. png_voidp PNGAPI
  181973. png_get_user_chunk_ptr(png_structp png_ptr)
  181974. {
  181975. return (png_ptr? png_ptr->user_chunk_ptr : NULL);
  181976. }
  181977. #endif
  181978. #ifdef PNG_WRITE_SUPPORTED
  181979. png_uint_32 PNGAPI
  181980. png_get_compression_buffer_size(png_structp png_ptr)
  181981. {
  181982. return (png_uint_32)(png_ptr? png_ptr->zbuf_size : 0L);
  181983. }
  181984. #endif
  181985. #ifdef PNG_ASSEMBLER_CODE_SUPPORTED
  181986. #ifndef PNG_1_0_X
  181987. /* this function was added to libpng 1.2.0 and should exist by default */
  181988. png_uint_32 PNGAPI
  181989. png_get_asm_flags (png_structp png_ptr)
  181990. {
  181991. /* obsolete, to be removed from libpng-1.4.0 */
  181992. return (png_ptr? 0L: 0L);
  181993. }
  181994. /* this function was added to libpng 1.2.0 and should exist by default */
  181995. png_uint_32 PNGAPI
  181996. png_get_asm_flagmask (int flag_select)
  181997. {
  181998. /* obsolete, to be removed from libpng-1.4.0 */
  181999. flag_select=flag_select;
  182000. return 0L;
  182001. }
  182002. /* GRR: could add this: && defined(PNG_MMX_CODE_SUPPORTED) */
  182003. /* this function was added to libpng 1.2.0 */
  182004. png_uint_32 PNGAPI
  182005. png_get_mmx_flagmask (int flag_select, int *compilerID)
  182006. {
  182007. /* obsolete, to be removed from libpng-1.4.0 */
  182008. flag_select=flag_select;
  182009. *compilerID = -1; /* unknown (i.e., no asm/MMX code compiled) */
  182010. return 0L;
  182011. }
  182012. /* this function was added to libpng 1.2.0 */
  182013. png_byte PNGAPI
  182014. png_get_mmx_bitdepth_threshold (png_structp png_ptr)
  182015. {
  182016. /* obsolete, to be removed from libpng-1.4.0 */
  182017. return (png_ptr? 0: 0);
  182018. }
  182019. /* this function was added to libpng 1.2.0 */
  182020. png_uint_32 PNGAPI
  182021. png_get_mmx_rowbytes_threshold (png_structp png_ptr)
  182022. {
  182023. /* obsolete, to be removed from libpng-1.4.0 */
  182024. return (png_ptr? 0L: 0L);
  182025. }
  182026. #endif /* ?PNG_1_0_X */
  182027. #endif /* ?PNG_ASSEMBLER_CODE_SUPPORTED */
  182028. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  182029. /* these functions were added to libpng 1.2.6 */
  182030. png_uint_32 PNGAPI
  182031. png_get_user_width_max (png_structp png_ptr)
  182032. {
  182033. return (png_ptr? png_ptr->user_width_max : 0);
  182034. }
  182035. png_uint_32 PNGAPI
  182036. png_get_user_height_max (png_structp png_ptr)
  182037. {
  182038. return (png_ptr? png_ptr->user_height_max : 0);
  182039. }
  182040. #endif /* ?PNG_SET_USER_LIMITS_SUPPORTED */
  182041. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  182042. /********* End of inlined file: pngget.c *********/
  182043. /********* Start of inlined file: pngmem.c *********/
  182044. /* pngmem.c - stub functions for memory allocation
  182045. *
  182046. * Last changed in libpng 1.2.13 November 13, 2006
  182047. * For conditions of distribution and use, see copyright notice in png.h
  182048. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  182049. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  182050. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  182051. *
  182052. * This file provides a location for all memory allocation. Users who
  182053. * need special memory handling are expected to supply replacement
  182054. * functions for png_malloc() and png_free(), and to use
  182055. * png_create_read_struct_2() and png_create_write_struct_2() to
  182056. * identify the replacement functions.
  182057. */
  182058. #define PNG_INTERNAL
  182059. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  182060. /* Borland DOS special memory handler */
  182061. #if defined(__TURBOC__) && !defined(_Windows) && !defined(__FLAT__)
  182062. /* if you change this, be sure to change the one in png.h also */
  182063. /* Allocate memory for a png_struct. The malloc and memset can be replaced
  182064. by a single call to calloc() if this is thought to improve performance. */
  182065. png_voidp /* PRIVATE */
  182066. png_create_struct(int type)
  182067. {
  182068. #ifdef PNG_USER_MEM_SUPPORTED
  182069. return (png_create_struct_2(type, png_malloc_ptr_NULL, png_voidp_NULL));
  182070. }
  182071. /* Alternate version of png_create_struct, for use with user-defined malloc. */
  182072. png_voidp /* PRIVATE */
  182073. png_create_struct_2(int type, png_malloc_ptr malloc_fn, png_voidp mem_ptr)
  182074. {
  182075. #endif /* PNG_USER_MEM_SUPPORTED */
  182076. png_size_t size;
  182077. png_voidp struct_ptr;
  182078. if (type == PNG_STRUCT_INFO)
  182079. size = png_sizeof(png_info);
  182080. else if (type == PNG_STRUCT_PNG)
  182081. size = png_sizeof(png_struct);
  182082. else
  182083. return (png_get_copyright(NULL));
  182084. #ifdef PNG_USER_MEM_SUPPORTED
  182085. if(malloc_fn != NULL)
  182086. {
  182087. png_struct dummy_struct;
  182088. png_structp png_ptr = &dummy_struct;
  182089. png_ptr->mem_ptr=mem_ptr;
  182090. struct_ptr = (*(malloc_fn))(png_ptr, (png_uint_32)size);
  182091. }
  182092. else
  182093. #endif /* PNG_USER_MEM_SUPPORTED */
  182094. struct_ptr = (png_voidp)farmalloc(size);
  182095. if (struct_ptr != NULL)
  182096. png_memset(struct_ptr, 0, size);
  182097. return (struct_ptr);
  182098. }
  182099. /* Free memory allocated by a png_create_struct() call */
  182100. void /* PRIVATE */
  182101. png_destroy_struct(png_voidp struct_ptr)
  182102. {
  182103. #ifdef PNG_USER_MEM_SUPPORTED
  182104. png_destroy_struct_2(struct_ptr, png_free_ptr_NULL, png_voidp_NULL);
  182105. }
  182106. /* Free memory allocated by a png_create_struct() call */
  182107. void /* PRIVATE */
  182108. png_destroy_struct_2(png_voidp struct_ptr, png_free_ptr free_fn,
  182109. png_voidp mem_ptr)
  182110. {
  182111. #endif
  182112. if (struct_ptr != NULL)
  182113. {
  182114. #ifdef PNG_USER_MEM_SUPPORTED
  182115. if(free_fn != NULL)
  182116. {
  182117. png_struct dummy_struct;
  182118. png_structp png_ptr = &dummy_struct;
  182119. png_ptr->mem_ptr=mem_ptr;
  182120. (*(free_fn))(png_ptr, struct_ptr);
  182121. return;
  182122. }
  182123. #endif /* PNG_USER_MEM_SUPPORTED */
  182124. farfree (struct_ptr);
  182125. }
  182126. }
  182127. /* Allocate memory. For reasonable files, size should never exceed
  182128. * 64K. However, zlib may allocate more then 64K if you don't tell
  182129. * it not to. See zconf.h and png.h for more information. zlib does
  182130. * need to allocate exactly 64K, so whatever you call here must
  182131. * have the ability to do that.
  182132. *
  182133. * Borland seems to have a problem in DOS mode for exactly 64K.
  182134. * It gives you a segment with an offset of 8 (perhaps to store its
  182135. * memory stuff). zlib doesn't like this at all, so we have to
  182136. * detect and deal with it. This code should not be needed in
  182137. * Windows or OS/2 modes, and only in 16 bit mode. This code has
  182138. * been updated by Alexander Lehmann for version 0.89 to waste less
  182139. * memory.
  182140. *
  182141. * Note that we can't use png_size_t for the "size" declaration,
  182142. * since on some systems a png_size_t is a 16-bit quantity, and as a
  182143. * result, we would be truncating potentially larger memory requests
  182144. * (which should cause a fatal error) and introducing major problems.
  182145. */
  182146. png_voidp PNGAPI
  182147. png_malloc(png_structp png_ptr, png_uint_32 size)
  182148. {
  182149. png_voidp ret;
  182150. if (png_ptr == NULL || size == 0)
  182151. return (NULL);
  182152. #ifdef PNG_USER_MEM_SUPPORTED
  182153. if(png_ptr->malloc_fn != NULL)
  182154. ret = ((png_voidp)(*(png_ptr->malloc_fn))(png_ptr, (png_size_t)size));
  182155. else
  182156. ret = (png_malloc_default(png_ptr, size));
  182157. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  182158. png_error(png_ptr, "Out of memory!");
  182159. return (ret);
  182160. }
  182161. png_voidp PNGAPI
  182162. png_malloc_default(png_structp png_ptr, png_uint_32 size)
  182163. {
  182164. png_voidp ret;
  182165. #endif /* PNG_USER_MEM_SUPPORTED */
  182166. if (png_ptr == NULL || size == 0)
  182167. return (NULL);
  182168. #ifdef PNG_MAX_MALLOC_64K
  182169. if (size > (png_uint_32)65536L)
  182170. {
  182171. png_warning(png_ptr, "Cannot Allocate > 64K");
  182172. ret = NULL;
  182173. }
  182174. else
  182175. #endif
  182176. if (size != (size_t)size)
  182177. ret = NULL;
  182178. else if (size == (png_uint_32)65536L)
  182179. {
  182180. if (png_ptr->offset_table == NULL)
  182181. {
  182182. /* try to see if we need to do any of this fancy stuff */
  182183. ret = farmalloc(size);
  182184. if (ret == NULL || ((png_size_t)ret & 0xffff))
  182185. {
  182186. int num_blocks;
  182187. png_uint_32 total_size;
  182188. png_bytep table;
  182189. int i;
  182190. png_byte huge * hptr;
  182191. if (ret != NULL)
  182192. {
  182193. farfree(ret);
  182194. ret = NULL;
  182195. }
  182196. if(png_ptr->zlib_window_bits > 14)
  182197. num_blocks = (int)(1 << (png_ptr->zlib_window_bits - 14));
  182198. else
  182199. num_blocks = 1;
  182200. if (png_ptr->zlib_mem_level >= 7)
  182201. num_blocks += (int)(1 << (png_ptr->zlib_mem_level - 7));
  182202. else
  182203. num_blocks++;
  182204. total_size = ((png_uint_32)65536L) * (png_uint_32)num_blocks+16;
  182205. table = farmalloc(total_size);
  182206. if (table == NULL)
  182207. {
  182208. #ifndef PNG_USER_MEM_SUPPORTED
  182209. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  182210. png_error(png_ptr, "Out Of Memory."); /* Note "O" and "M" */
  182211. else
  182212. png_warning(png_ptr, "Out Of Memory.");
  182213. #endif
  182214. return (NULL);
  182215. }
  182216. if ((png_size_t)table & 0xfff0)
  182217. {
  182218. #ifndef PNG_USER_MEM_SUPPORTED
  182219. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  182220. png_error(png_ptr,
  182221. "Farmalloc didn't return normalized pointer");
  182222. else
  182223. png_warning(png_ptr,
  182224. "Farmalloc didn't return normalized pointer");
  182225. #endif
  182226. return (NULL);
  182227. }
  182228. png_ptr->offset_table = table;
  182229. png_ptr->offset_table_ptr = farmalloc(num_blocks *
  182230. png_sizeof (png_bytep));
  182231. if (png_ptr->offset_table_ptr == NULL)
  182232. {
  182233. #ifndef PNG_USER_MEM_SUPPORTED
  182234. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  182235. png_error(png_ptr, "Out Of memory."); /* Note "O" and "M" */
  182236. else
  182237. png_warning(png_ptr, "Out Of memory.");
  182238. #endif
  182239. return (NULL);
  182240. }
  182241. hptr = (png_byte huge *)table;
  182242. if ((png_size_t)hptr & 0xf)
  182243. {
  182244. hptr = (png_byte huge *)((long)(hptr) & 0xfffffff0L);
  182245. hptr = hptr + 16L; /* "hptr += 16L" fails on Turbo C++ 3.0 */
  182246. }
  182247. for (i = 0; i < num_blocks; i++)
  182248. {
  182249. png_ptr->offset_table_ptr[i] = (png_bytep)hptr;
  182250. hptr = hptr + (png_uint_32)65536L; /* "+=" fails on TC++3.0 */
  182251. }
  182252. png_ptr->offset_table_number = num_blocks;
  182253. png_ptr->offset_table_count = 0;
  182254. png_ptr->offset_table_count_free = 0;
  182255. }
  182256. }
  182257. if (png_ptr->offset_table_count >= png_ptr->offset_table_number)
  182258. {
  182259. #ifndef PNG_USER_MEM_SUPPORTED
  182260. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  182261. png_error(png_ptr, "Out of Memory."); /* Note "o" and "M" */
  182262. else
  182263. png_warning(png_ptr, "Out of Memory.");
  182264. #endif
  182265. return (NULL);
  182266. }
  182267. ret = png_ptr->offset_table_ptr[png_ptr->offset_table_count++];
  182268. }
  182269. else
  182270. ret = farmalloc(size);
  182271. #ifndef PNG_USER_MEM_SUPPORTED
  182272. if (ret == NULL)
  182273. {
  182274. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  182275. png_error(png_ptr, "Out of memory."); /* Note "o" and "m" */
  182276. else
  182277. png_warning(png_ptr, "Out of memory."); /* Note "o" and "m" */
  182278. }
  182279. #endif
  182280. return (ret);
  182281. }
  182282. /* free a pointer allocated by png_malloc(). In the default
  182283. configuration, png_ptr is not used, but is passed in case it
  182284. is needed. If ptr is NULL, return without taking any action. */
  182285. void PNGAPI
  182286. png_free(png_structp png_ptr, png_voidp ptr)
  182287. {
  182288. if (png_ptr == NULL || ptr == NULL)
  182289. return;
  182290. #ifdef PNG_USER_MEM_SUPPORTED
  182291. if (png_ptr->free_fn != NULL)
  182292. {
  182293. (*(png_ptr->free_fn))(png_ptr, ptr);
  182294. return;
  182295. }
  182296. else png_free_default(png_ptr, ptr);
  182297. }
  182298. void PNGAPI
  182299. png_free_default(png_structp png_ptr, png_voidp ptr)
  182300. {
  182301. #endif /* PNG_USER_MEM_SUPPORTED */
  182302. if(png_ptr == NULL) return;
  182303. if (png_ptr->offset_table != NULL)
  182304. {
  182305. int i;
  182306. for (i = 0; i < png_ptr->offset_table_count; i++)
  182307. {
  182308. if (ptr == png_ptr->offset_table_ptr[i])
  182309. {
  182310. ptr = NULL;
  182311. png_ptr->offset_table_count_free++;
  182312. break;
  182313. }
  182314. }
  182315. if (png_ptr->offset_table_count_free == png_ptr->offset_table_count)
  182316. {
  182317. farfree(png_ptr->offset_table);
  182318. farfree(png_ptr->offset_table_ptr);
  182319. png_ptr->offset_table = NULL;
  182320. png_ptr->offset_table_ptr = NULL;
  182321. }
  182322. }
  182323. if (ptr != NULL)
  182324. {
  182325. farfree(ptr);
  182326. }
  182327. }
  182328. #else /* Not the Borland DOS special memory handler */
  182329. /* Allocate memory for a png_struct or a png_info. The malloc and
  182330. memset can be replaced by a single call to calloc() if this is thought
  182331. to improve performance noticably. */
  182332. png_voidp /* PRIVATE */
  182333. png_create_struct(int type)
  182334. {
  182335. #ifdef PNG_USER_MEM_SUPPORTED
  182336. return (png_create_struct_2(type, png_malloc_ptr_NULL, png_voidp_NULL));
  182337. }
  182338. /* Allocate memory for a png_struct or a png_info. The malloc and
  182339. memset can be replaced by a single call to calloc() if this is thought
  182340. to improve performance noticably. */
  182341. png_voidp /* PRIVATE */
  182342. png_create_struct_2(int type, png_malloc_ptr malloc_fn, png_voidp mem_ptr)
  182343. {
  182344. #endif /* PNG_USER_MEM_SUPPORTED */
  182345. png_size_t size;
  182346. png_voidp struct_ptr;
  182347. if (type == PNG_STRUCT_INFO)
  182348. size = png_sizeof(png_info);
  182349. else if (type == PNG_STRUCT_PNG)
  182350. size = png_sizeof(png_struct);
  182351. else
  182352. return (NULL);
  182353. #ifdef PNG_USER_MEM_SUPPORTED
  182354. if(malloc_fn != NULL)
  182355. {
  182356. png_struct dummy_struct;
  182357. png_structp png_ptr = &dummy_struct;
  182358. png_ptr->mem_ptr=mem_ptr;
  182359. struct_ptr = (*(malloc_fn))(png_ptr, size);
  182360. if (struct_ptr != NULL)
  182361. png_memset(struct_ptr, 0, size);
  182362. return (struct_ptr);
  182363. }
  182364. #endif /* PNG_USER_MEM_SUPPORTED */
  182365. #if defined(__TURBOC__) && !defined(__FLAT__)
  182366. struct_ptr = (png_voidp)farmalloc(size);
  182367. #else
  182368. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  182369. struct_ptr = (png_voidp)halloc(size,1);
  182370. # else
  182371. struct_ptr = (png_voidp)malloc(size);
  182372. # endif
  182373. #endif
  182374. if (struct_ptr != NULL)
  182375. png_memset(struct_ptr, 0, size);
  182376. return (struct_ptr);
  182377. }
  182378. /* Free memory allocated by a png_create_struct() call */
  182379. void /* PRIVATE */
  182380. png_destroy_struct(png_voidp struct_ptr)
  182381. {
  182382. #ifdef PNG_USER_MEM_SUPPORTED
  182383. png_destroy_struct_2(struct_ptr, png_free_ptr_NULL, png_voidp_NULL);
  182384. }
  182385. /* Free memory allocated by a png_create_struct() call */
  182386. void /* PRIVATE */
  182387. png_destroy_struct_2(png_voidp struct_ptr, png_free_ptr free_fn,
  182388. png_voidp mem_ptr)
  182389. {
  182390. #endif /* PNG_USER_MEM_SUPPORTED */
  182391. if (struct_ptr != NULL)
  182392. {
  182393. #ifdef PNG_USER_MEM_SUPPORTED
  182394. if(free_fn != NULL)
  182395. {
  182396. png_struct dummy_struct;
  182397. png_structp png_ptr = &dummy_struct;
  182398. png_ptr->mem_ptr=mem_ptr;
  182399. (*(free_fn))(png_ptr, struct_ptr);
  182400. return;
  182401. }
  182402. #endif /* PNG_USER_MEM_SUPPORTED */
  182403. #if defined(__TURBOC__) && !defined(__FLAT__)
  182404. farfree(struct_ptr);
  182405. #else
  182406. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  182407. hfree(struct_ptr);
  182408. # else
  182409. free(struct_ptr);
  182410. # endif
  182411. #endif
  182412. }
  182413. }
  182414. /* Allocate memory. For reasonable files, size should never exceed
  182415. 64K. However, zlib may allocate more then 64K if you don't tell
  182416. it not to. See zconf.h and png.h for more information. zlib does
  182417. need to allocate exactly 64K, so whatever you call here must
  182418. have the ability to do that. */
  182419. png_voidp PNGAPI
  182420. png_malloc(png_structp png_ptr, png_uint_32 size)
  182421. {
  182422. png_voidp ret;
  182423. #ifdef PNG_USER_MEM_SUPPORTED
  182424. if (png_ptr == NULL || size == 0)
  182425. return (NULL);
  182426. if(png_ptr->malloc_fn != NULL)
  182427. ret = ((png_voidp)(*(png_ptr->malloc_fn))(png_ptr, (png_size_t)size));
  182428. else
  182429. ret = (png_malloc_default(png_ptr, size));
  182430. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  182431. png_error(png_ptr, "Out of Memory!");
  182432. return (ret);
  182433. }
  182434. png_voidp PNGAPI
  182435. png_malloc_default(png_structp png_ptr, png_uint_32 size)
  182436. {
  182437. png_voidp ret;
  182438. #endif /* PNG_USER_MEM_SUPPORTED */
  182439. if (png_ptr == NULL || size == 0)
  182440. return (NULL);
  182441. #ifdef PNG_MAX_MALLOC_64K
  182442. if (size > (png_uint_32)65536L)
  182443. {
  182444. #ifndef PNG_USER_MEM_SUPPORTED
  182445. if(png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  182446. png_error(png_ptr, "Cannot Allocate > 64K");
  182447. else
  182448. #endif
  182449. return NULL;
  182450. }
  182451. #endif
  182452. /* Check for overflow */
  182453. #if defined(__TURBOC__) && !defined(__FLAT__)
  182454. if (size != (unsigned long)size)
  182455. ret = NULL;
  182456. else
  182457. ret = farmalloc(size);
  182458. #else
  182459. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  182460. if (size != (unsigned long)size)
  182461. ret = NULL;
  182462. else
  182463. ret = halloc(size, 1);
  182464. # else
  182465. if (size != (size_t)size)
  182466. ret = NULL;
  182467. else
  182468. ret = malloc((size_t)size);
  182469. # endif
  182470. #endif
  182471. #ifndef PNG_USER_MEM_SUPPORTED
  182472. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  182473. png_error(png_ptr, "Out of Memory");
  182474. #endif
  182475. return (ret);
  182476. }
  182477. /* Free a pointer allocated by png_malloc(). If ptr is NULL, return
  182478. without taking any action. */
  182479. void PNGAPI
  182480. png_free(png_structp png_ptr, png_voidp ptr)
  182481. {
  182482. if (png_ptr == NULL || ptr == NULL)
  182483. return;
  182484. #ifdef PNG_USER_MEM_SUPPORTED
  182485. if (png_ptr->free_fn != NULL)
  182486. {
  182487. (*(png_ptr->free_fn))(png_ptr, ptr);
  182488. return;
  182489. }
  182490. else png_free_default(png_ptr, ptr);
  182491. }
  182492. void PNGAPI
  182493. png_free_default(png_structp png_ptr, png_voidp ptr)
  182494. {
  182495. if (png_ptr == NULL || ptr == NULL)
  182496. return;
  182497. #endif /* PNG_USER_MEM_SUPPORTED */
  182498. #if defined(__TURBOC__) && !defined(__FLAT__)
  182499. farfree(ptr);
  182500. #else
  182501. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  182502. hfree(ptr);
  182503. # else
  182504. free(ptr);
  182505. # endif
  182506. #endif
  182507. }
  182508. #endif /* Not Borland DOS special memory handler */
  182509. #if defined(PNG_1_0_X)
  182510. # define png_malloc_warn png_malloc
  182511. #else
  182512. /* This function was added at libpng version 1.2.3. The png_malloc_warn()
  182513. * function will set up png_malloc() to issue a png_warning and return NULL
  182514. * instead of issuing a png_error, if it fails to allocate the requested
  182515. * memory.
  182516. */
  182517. png_voidp PNGAPI
  182518. png_malloc_warn(png_structp png_ptr, png_uint_32 size)
  182519. {
  182520. png_voidp ptr;
  182521. png_uint_32 save_flags;
  182522. if(png_ptr == NULL) return (NULL);
  182523. save_flags=png_ptr->flags;
  182524. png_ptr->flags|=PNG_FLAG_MALLOC_NULL_MEM_OK;
  182525. ptr = (png_voidp)png_malloc((png_structp)png_ptr, size);
  182526. png_ptr->flags=save_flags;
  182527. return(ptr);
  182528. }
  182529. #endif
  182530. png_voidp PNGAPI
  182531. png_memcpy_check (png_structp png_ptr, png_voidp s1, png_voidp s2,
  182532. png_uint_32 length)
  182533. {
  182534. png_size_t size;
  182535. size = (png_size_t)length;
  182536. if ((png_uint_32)size != length)
  182537. png_error(png_ptr,"Overflow in png_memcpy_check.");
  182538. return(png_memcpy (s1, s2, size));
  182539. }
  182540. png_voidp PNGAPI
  182541. png_memset_check (png_structp png_ptr, png_voidp s1, int value,
  182542. png_uint_32 length)
  182543. {
  182544. png_size_t size;
  182545. size = (png_size_t)length;
  182546. if ((png_uint_32)size != length)
  182547. png_error(png_ptr,"Overflow in png_memset_check.");
  182548. return (png_memset (s1, value, size));
  182549. }
  182550. #ifdef PNG_USER_MEM_SUPPORTED
  182551. /* This function is called when the application wants to use another method
  182552. * of allocating and freeing memory.
  182553. */
  182554. void PNGAPI
  182555. png_set_mem_fn(png_structp png_ptr, png_voidp mem_ptr, png_malloc_ptr
  182556. malloc_fn, png_free_ptr free_fn)
  182557. {
  182558. if(png_ptr != NULL) {
  182559. png_ptr->mem_ptr = mem_ptr;
  182560. png_ptr->malloc_fn = malloc_fn;
  182561. png_ptr->free_fn = free_fn;
  182562. }
  182563. }
  182564. /* This function returns a pointer to the mem_ptr associated with the user
  182565. * functions. The application should free any memory associated with this
  182566. * pointer before png_write_destroy and png_read_destroy are called.
  182567. */
  182568. png_voidp PNGAPI
  182569. png_get_mem_ptr(png_structp png_ptr)
  182570. {
  182571. if(png_ptr == NULL) return (NULL);
  182572. return ((png_voidp)png_ptr->mem_ptr);
  182573. }
  182574. #endif /* PNG_USER_MEM_SUPPORTED */
  182575. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  182576. /********* End of inlined file: pngmem.c *********/
  182577. /********* Start of inlined file: pngread.c *********/
  182578. /* pngread.c - read a PNG file
  182579. *
  182580. * Last changed in libpng 1.2.20 September 7, 2007
  182581. * For conditions of distribution and use, see copyright notice in png.h
  182582. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  182583. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  182584. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  182585. *
  182586. * This file contains routines that an application calls directly to
  182587. * read a PNG file or stream.
  182588. */
  182589. #define PNG_INTERNAL
  182590. #if defined(PNG_READ_SUPPORTED)
  182591. /* Create a PNG structure for reading, and allocate any memory needed. */
  182592. png_structp PNGAPI
  182593. png_create_read_struct(png_const_charp user_png_ver, png_voidp error_ptr,
  182594. png_error_ptr error_fn, png_error_ptr warn_fn)
  182595. {
  182596. #ifdef PNG_USER_MEM_SUPPORTED
  182597. return (png_create_read_struct_2(user_png_ver, error_ptr, error_fn,
  182598. warn_fn, png_voidp_NULL, png_malloc_ptr_NULL, png_free_ptr_NULL));
  182599. }
  182600. /* Alternate create PNG structure for reading, and allocate any memory needed. */
  182601. png_structp PNGAPI
  182602. png_create_read_struct_2(png_const_charp user_png_ver, png_voidp error_ptr,
  182603. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  182604. png_malloc_ptr malloc_fn, png_free_ptr free_fn)
  182605. {
  182606. #endif /* PNG_USER_MEM_SUPPORTED */
  182607. png_structp png_ptr;
  182608. #ifdef PNG_SETJMP_SUPPORTED
  182609. #ifdef USE_FAR_KEYWORD
  182610. jmp_buf jmpbuf;
  182611. #endif
  182612. #endif
  182613. int i;
  182614. png_debug(1, "in png_create_read_struct\n");
  182615. #ifdef PNG_USER_MEM_SUPPORTED
  182616. png_ptr = (png_structp)png_create_struct_2(PNG_STRUCT_PNG,
  182617. (png_malloc_ptr)malloc_fn, (png_voidp)mem_ptr);
  182618. #else
  182619. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  182620. #endif
  182621. if (png_ptr == NULL)
  182622. return (NULL);
  182623. /* added at libpng-1.2.6 */
  182624. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  182625. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  182626. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  182627. #endif
  182628. #ifdef PNG_SETJMP_SUPPORTED
  182629. #ifdef USE_FAR_KEYWORD
  182630. if (setjmp(jmpbuf))
  182631. #else
  182632. if (setjmp(png_ptr->jmpbuf))
  182633. #endif
  182634. {
  182635. png_free(png_ptr, png_ptr->zbuf);
  182636. png_ptr->zbuf=NULL;
  182637. #ifdef PNG_USER_MEM_SUPPORTED
  182638. png_destroy_struct_2((png_voidp)png_ptr,
  182639. (png_free_ptr)free_fn, (png_voidp)mem_ptr);
  182640. #else
  182641. png_destroy_struct((png_voidp)png_ptr);
  182642. #endif
  182643. return (NULL);
  182644. }
  182645. #ifdef USE_FAR_KEYWORD
  182646. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  182647. #endif
  182648. #endif
  182649. #ifdef PNG_USER_MEM_SUPPORTED
  182650. png_set_mem_fn(png_ptr, mem_ptr, malloc_fn, free_fn);
  182651. #endif
  182652. png_set_error_fn(png_ptr, error_ptr, error_fn, warn_fn);
  182653. i=0;
  182654. do
  182655. {
  182656. if(user_png_ver[i] != png_libpng_ver[i])
  182657. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  182658. } while (png_libpng_ver[i++]);
  182659. if (png_ptr->flags & PNG_FLAG_LIBRARY_MISMATCH)
  182660. {
  182661. /* Libpng 0.90 and later are binary incompatible with libpng 0.89, so
  182662. * we must recompile any applications that use any older library version.
  182663. * For versions after libpng 1.0, we will be compatible, so we need
  182664. * only check the first digit.
  182665. */
  182666. if (user_png_ver == NULL || user_png_ver[0] != png_libpng_ver[0] ||
  182667. (user_png_ver[0] == '1' && user_png_ver[2] != png_libpng_ver[2]) ||
  182668. (user_png_ver[0] == '0' && user_png_ver[2] < '9'))
  182669. {
  182670. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  182671. char msg[80];
  182672. if (user_png_ver)
  182673. {
  182674. png_snprintf(msg, 80,
  182675. "Application was compiled with png.h from libpng-%.20s",
  182676. user_png_ver);
  182677. png_warning(png_ptr, msg);
  182678. }
  182679. png_snprintf(msg, 80,
  182680. "Application is running with png.c from libpng-%.20s",
  182681. png_libpng_ver);
  182682. png_warning(png_ptr, msg);
  182683. #endif
  182684. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  182685. png_ptr->flags=0;
  182686. #endif
  182687. png_error(png_ptr,
  182688. "Incompatible libpng version in application and library");
  182689. }
  182690. }
  182691. /* initialize zbuf - compression buffer */
  182692. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  182693. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  182694. (png_uint_32)png_ptr->zbuf_size);
  182695. png_ptr->zstream.zalloc = png_zalloc;
  182696. png_ptr->zstream.zfree = png_zfree;
  182697. png_ptr->zstream.opaque = (voidpf)png_ptr;
  182698. switch (inflateInit(&png_ptr->zstream))
  182699. {
  182700. case Z_OK: /* Do nothing */ break;
  182701. case Z_MEM_ERROR:
  182702. case Z_STREAM_ERROR: png_error(png_ptr, "zlib memory error"); break;
  182703. case Z_VERSION_ERROR: png_error(png_ptr, "zlib version error"); break;
  182704. default: png_error(png_ptr, "Unknown zlib error");
  182705. }
  182706. png_ptr->zstream.next_out = png_ptr->zbuf;
  182707. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  182708. png_set_read_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL);
  182709. #ifdef PNG_SETJMP_SUPPORTED
  182710. /* Applications that neglect to set up their own setjmp() and then encounter
  182711. a png_error() will longjmp here. Since the jmpbuf is then meaningless we
  182712. abort instead of returning. */
  182713. #ifdef USE_FAR_KEYWORD
  182714. if (setjmp(jmpbuf))
  182715. PNG_ABORT();
  182716. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  182717. #else
  182718. if (setjmp(png_ptr->jmpbuf))
  182719. PNG_ABORT();
  182720. #endif
  182721. #endif
  182722. return (png_ptr);
  182723. }
  182724. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  182725. /* Initialize PNG structure for reading, and allocate any memory needed.
  182726. This interface is deprecated in favour of the png_create_read_struct(),
  182727. and it will disappear as of libpng-1.3.0. */
  182728. #undef png_read_init
  182729. void PNGAPI
  182730. png_read_init(png_structp png_ptr)
  182731. {
  182732. /* We only come here via pre-1.0.7-compiled applications */
  182733. png_read_init_2(png_ptr, "1.0.6 or earlier", 0, 0);
  182734. }
  182735. void PNGAPI
  182736. png_read_init_2(png_structp png_ptr, png_const_charp user_png_ver,
  182737. png_size_t png_struct_size, png_size_t png_info_size)
  182738. {
  182739. /* We only come here via pre-1.0.12-compiled applications */
  182740. if(png_ptr == NULL) return;
  182741. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  182742. if(png_sizeof(png_struct) > png_struct_size ||
  182743. png_sizeof(png_info) > png_info_size)
  182744. {
  182745. char msg[80];
  182746. png_ptr->warning_fn=NULL;
  182747. if (user_png_ver)
  182748. {
  182749. png_snprintf(msg, 80,
  182750. "Application was compiled with png.h from libpng-%.20s",
  182751. user_png_ver);
  182752. png_warning(png_ptr, msg);
  182753. }
  182754. png_snprintf(msg, 80,
  182755. "Application is running with png.c from libpng-%.20s",
  182756. png_libpng_ver);
  182757. png_warning(png_ptr, msg);
  182758. }
  182759. #endif
  182760. if(png_sizeof(png_struct) > png_struct_size)
  182761. {
  182762. png_ptr->error_fn=NULL;
  182763. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  182764. png_ptr->flags=0;
  182765. #endif
  182766. png_error(png_ptr,
  182767. "The png struct allocated by the application for reading is too small.");
  182768. }
  182769. if(png_sizeof(png_info) > png_info_size)
  182770. {
  182771. png_ptr->error_fn=NULL;
  182772. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  182773. png_ptr->flags=0;
  182774. #endif
  182775. png_error(png_ptr,
  182776. "The info struct allocated by application for reading is too small.");
  182777. }
  182778. png_read_init_3(&png_ptr, user_png_ver, png_struct_size);
  182779. }
  182780. #endif /* PNG_1_0_X || PNG_1_2_X */
  182781. void PNGAPI
  182782. png_read_init_3(png_structpp ptr_ptr, png_const_charp user_png_ver,
  182783. png_size_t png_struct_size)
  182784. {
  182785. #ifdef PNG_SETJMP_SUPPORTED
  182786. jmp_buf tmp_jmp; /* to save current jump buffer */
  182787. #endif
  182788. int i=0;
  182789. png_structp png_ptr=*ptr_ptr;
  182790. if(png_ptr == NULL) return;
  182791. do
  182792. {
  182793. if(user_png_ver[i] != png_libpng_ver[i])
  182794. {
  182795. #ifdef PNG_LEGACY_SUPPORTED
  182796. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  182797. #else
  182798. png_ptr->warning_fn=NULL;
  182799. png_warning(png_ptr,
  182800. "Application uses deprecated png_read_init() and should be recompiled.");
  182801. break;
  182802. #endif
  182803. }
  182804. } while (png_libpng_ver[i++]);
  182805. png_debug(1, "in png_read_init_3\n");
  182806. #ifdef PNG_SETJMP_SUPPORTED
  182807. /* save jump buffer and error functions */
  182808. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  182809. #endif
  182810. if(png_sizeof(png_struct) > png_struct_size)
  182811. {
  182812. png_destroy_struct(png_ptr);
  182813. *ptr_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  182814. png_ptr = *ptr_ptr;
  182815. }
  182816. /* reset all variables to 0 */
  182817. png_memset(png_ptr, 0, png_sizeof (png_struct));
  182818. #ifdef PNG_SETJMP_SUPPORTED
  182819. /* restore jump buffer */
  182820. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  182821. #endif
  182822. /* added at libpng-1.2.6 */
  182823. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  182824. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  182825. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  182826. #endif
  182827. /* initialize zbuf - compression buffer */
  182828. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  182829. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  182830. (png_uint_32)png_ptr->zbuf_size);
  182831. png_ptr->zstream.zalloc = png_zalloc;
  182832. png_ptr->zstream.zfree = png_zfree;
  182833. png_ptr->zstream.opaque = (voidpf)png_ptr;
  182834. switch (inflateInit(&png_ptr->zstream))
  182835. {
  182836. case Z_OK: /* Do nothing */ break;
  182837. case Z_MEM_ERROR:
  182838. case Z_STREAM_ERROR: png_error(png_ptr, "zlib memory"); break;
  182839. case Z_VERSION_ERROR: png_error(png_ptr, "zlib version"); break;
  182840. default: png_error(png_ptr, "Unknown zlib error");
  182841. }
  182842. png_ptr->zstream.next_out = png_ptr->zbuf;
  182843. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  182844. png_set_read_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL);
  182845. }
  182846. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  182847. /* Read the information before the actual image data. This has been
  182848. * changed in v0.90 to allow reading a file that already has the magic
  182849. * bytes read from the stream. You can tell libpng how many bytes have
  182850. * been read from the beginning of the stream (up to the maximum of 8)
  182851. * via png_set_sig_bytes(), and we will only check the remaining bytes
  182852. * here. The application can then have access to the signature bytes we
  182853. * read if it is determined that this isn't a valid PNG file.
  182854. */
  182855. void PNGAPI
  182856. png_read_info(png_structp png_ptr, png_infop info_ptr)
  182857. {
  182858. if(png_ptr == NULL) return;
  182859. png_debug(1, "in png_read_info\n");
  182860. /* If we haven't checked all of the PNG signature bytes, do so now. */
  182861. if (png_ptr->sig_bytes < 8)
  182862. {
  182863. png_size_t num_checked = png_ptr->sig_bytes,
  182864. num_to_check = 8 - num_checked;
  182865. png_read_data(png_ptr, &(info_ptr->signature[num_checked]), num_to_check);
  182866. png_ptr->sig_bytes = 8;
  182867. if (png_sig_cmp(info_ptr->signature, num_checked, num_to_check))
  182868. {
  182869. if (num_checked < 4 &&
  182870. png_sig_cmp(info_ptr->signature, num_checked, num_to_check - 4))
  182871. png_error(png_ptr, "Not a PNG file");
  182872. else
  182873. png_error(png_ptr, "PNG file corrupted by ASCII conversion");
  182874. }
  182875. if (num_checked < 3)
  182876. png_ptr->mode |= PNG_HAVE_PNG_SIGNATURE;
  182877. }
  182878. for(;;)
  182879. {
  182880. #ifdef PNG_USE_LOCAL_ARRAYS
  182881. PNG_CONST PNG_IHDR;
  182882. PNG_CONST PNG_IDAT;
  182883. PNG_CONST PNG_IEND;
  182884. PNG_CONST PNG_PLTE;
  182885. #if defined(PNG_READ_bKGD_SUPPORTED)
  182886. PNG_CONST PNG_bKGD;
  182887. #endif
  182888. #if defined(PNG_READ_cHRM_SUPPORTED)
  182889. PNG_CONST PNG_cHRM;
  182890. #endif
  182891. #if defined(PNG_READ_gAMA_SUPPORTED)
  182892. PNG_CONST PNG_gAMA;
  182893. #endif
  182894. #if defined(PNG_READ_hIST_SUPPORTED)
  182895. PNG_CONST PNG_hIST;
  182896. #endif
  182897. #if defined(PNG_READ_iCCP_SUPPORTED)
  182898. PNG_CONST PNG_iCCP;
  182899. #endif
  182900. #if defined(PNG_READ_iTXt_SUPPORTED)
  182901. PNG_CONST PNG_iTXt;
  182902. #endif
  182903. #if defined(PNG_READ_oFFs_SUPPORTED)
  182904. PNG_CONST PNG_oFFs;
  182905. #endif
  182906. #if defined(PNG_READ_pCAL_SUPPORTED)
  182907. PNG_CONST PNG_pCAL;
  182908. #endif
  182909. #if defined(PNG_READ_pHYs_SUPPORTED)
  182910. PNG_CONST PNG_pHYs;
  182911. #endif
  182912. #if defined(PNG_READ_sBIT_SUPPORTED)
  182913. PNG_CONST PNG_sBIT;
  182914. #endif
  182915. #if defined(PNG_READ_sCAL_SUPPORTED)
  182916. PNG_CONST PNG_sCAL;
  182917. #endif
  182918. #if defined(PNG_READ_sPLT_SUPPORTED)
  182919. PNG_CONST PNG_sPLT;
  182920. #endif
  182921. #if defined(PNG_READ_sRGB_SUPPORTED)
  182922. PNG_CONST PNG_sRGB;
  182923. #endif
  182924. #if defined(PNG_READ_tEXt_SUPPORTED)
  182925. PNG_CONST PNG_tEXt;
  182926. #endif
  182927. #if defined(PNG_READ_tIME_SUPPORTED)
  182928. PNG_CONST PNG_tIME;
  182929. #endif
  182930. #if defined(PNG_READ_tRNS_SUPPORTED)
  182931. PNG_CONST PNG_tRNS;
  182932. #endif
  182933. #if defined(PNG_READ_zTXt_SUPPORTED)
  182934. PNG_CONST PNG_zTXt;
  182935. #endif
  182936. #endif /* PNG_USE_LOCAL_ARRAYS */
  182937. png_byte chunk_length[4];
  182938. png_uint_32 length;
  182939. png_read_data(png_ptr, chunk_length, 4);
  182940. length = png_get_uint_31(png_ptr,chunk_length);
  182941. png_reset_crc(png_ptr);
  182942. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  182943. png_debug2(0, "Reading %s chunk, length=%lu.\n", png_ptr->chunk_name,
  182944. length);
  182945. /* This should be a binary subdivision search or a hash for
  182946. * matching the chunk name rather than a linear search.
  182947. */
  182948. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  182949. if(png_ptr->mode & PNG_AFTER_IDAT)
  182950. png_ptr->mode |= PNG_HAVE_CHUNK_AFTER_IDAT;
  182951. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  182952. png_handle_IHDR(png_ptr, info_ptr, length);
  182953. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  182954. png_handle_IEND(png_ptr, info_ptr, length);
  182955. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  182956. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  182957. {
  182958. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  182959. png_ptr->mode |= PNG_HAVE_IDAT;
  182960. png_handle_unknown(png_ptr, info_ptr, length);
  182961. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  182962. png_ptr->mode |= PNG_HAVE_PLTE;
  182963. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  182964. {
  182965. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  182966. png_error(png_ptr, "Missing IHDR before IDAT");
  182967. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  182968. !(png_ptr->mode & PNG_HAVE_PLTE))
  182969. png_error(png_ptr, "Missing PLTE before IDAT");
  182970. break;
  182971. }
  182972. }
  182973. #endif
  182974. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  182975. png_handle_PLTE(png_ptr, info_ptr, length);
  182976. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  182977. {
  182978. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  182979. png_error(png_ptr, "Missing IHDR before IDAT");
  182980. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  182981. !(png_ptr->mode & PNG_HAVE_PLTE))
  182982. png_error(png_ptr, "Missing PLTE before IDAT");
  182983. png_ptr->idat_size = length;
  182984. png_ptr->mode |= PNG_HAVE_IDAT;
  182985. break;
  182986. }
  182987. #if defined(PNG_READ_bKGD_SUPPORTED)
  182988. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  182989. png_handle_bKGD(png_ptr, info_ptr, length);
  182990. #endif
  182991. #if defined(PNG_READ_cHRM_SUPPORTED)
  182992. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  182993. png_handle_cHRM(png_ptr, info_ptr, length);
  182994. #endif
  182995. #if defined(PNG_READ_gAMA_SUPPORTED)
  182996. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  182997. png_handle_gAMA(png_ptr, info_ptr, length);
  182998. #endif
  182999. #if defined(PNG_READ_hIST_SUPPORTED)
  183000. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  183001. png_handle_hIST(png_ptr, info_ptr, length);
  183002. #endif
  183003. #if defined(PNG_READ_oFFs_SUPPORTED)
  183004. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  183005. png_handle_oFFs(png_ptr, info_ptr, length);
  183006. #endif
  183007. #if defined(PNG_READ_pCAL_SUPPORTED)
  183008. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  183009. png_handle_pCAL(png_ptr, info_ptr, length);
  183010. #endif
  183011. #if defined(PNG_READ_sCAL_SUPPORTED)
  183012. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  183013. png_handle_sCAL(png_ptr, info_ptr, length);
  183014. #endif
  183015. #if defined(PNG_READ_pHYs_SUPPORTED)
  183016. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  183017. png_handle_pHYs(png_ptr, info_ptr, length);
  183018. #endif
  183019. #if defined(PNG_READ_sBIT_SUPPORTED)
  183020. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  183021. png_handle_sBIT(png_ptr, info_ptr, length);
  183022. #endif
  183023. #if defined(PNG_READ_sRGB_SUPPORTED)
  183024. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  183025. png_handle_sRGB(png_ptr, info_ptr, length);
  183026. #endif
  183027. #if defined(PNG_READ_iCCP_SUPPORTED)
  183028. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  183029. png_handle_iCCP(png_ptr, info_ptr, length);
  183030. #endif
  183031. #if defined(PNG_READ_sPLT_SUPPORTED)
  183032. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  183033. png_handle_sPLT(png_ptr, info_ptr, length);
  183034. #endif
  183035. #if defined(PNG_READ_tEXt_SUPPORTED)
  183036. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  183037. png_handle_tEXt(png_ptr, info_ptr, length);
  183038. #endif
  183039. #if defined(PNG_READ_tIME_SUPPORTED)
  183040. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  183041. png_handle_tIME(png_ptr, info_ptr, length);
  183042. #endif
  183043. #if defined(PNG_READ_tRNS_SUPPORTED)
  183044. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  183045. png_handle_tRNS(png_ptr, info_ptr, length);
  183046. #endif
  183047. #if defined(PNG_READ_zTXt_SUPPORTED)
  183048. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  183049. png_handle_zTXt(png_ptr, info_ptr, length);
  183050. #endif
  183051. #if defined(PNG_READ_iTXt_SUPPORTED)
  183052. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  183053. png_handle_iTXt(png_ptr, info_ptr, length);
  183054. #endif
  183055. else
  183056. png_handle_unknown(png_ptr, info_ptr, length);
  183057. }
  183058. }
  183059. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  183060. /* optional call to update the users info_ptr structure */
  183061. void PNGAPI
  183062. png_read_update_info(png_structp png_ptr, png_infop info_ptr)
  183063. {
  183064. png_debug(1, "in png_read_update_info\n");
  183065. if(png_ptr == NULL) return;
  183066. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  183067. png_read_start_row(png_ptr);
  183068. else
  183069. png_warning(png_ptr,
  183070. "Ignoring extra png_read_update_info() call; row buffer not reallocated");
  183071. png_read_transform_info(png_ptr, info_ptr);
  183072. }
  183073. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  183074. /* Initialize palette, background, etc, after transformations
  183075. * are set, but before any reading takes place. This allows
  183076. * the user to obtain a gamma-corrected palette, for example.
  183077. * If the user doesn't call this, we will do it ourselves.
  183078. */
  183079. void PNGAPI
  183080. png_start_read_image(png_structp png_ptr)
  183081. {
  183082. png_debug(1, "in png_start_read_image\n");
  183083. if(png_ptr == NULL) return;
  183084. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  183085. png_read_start_row(png_ptr);
  183086. }
  183087. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  183088. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  183089. void PNGAPI
  183090. png_read_row(png_structp png_ptr, png_bytep row, png_bytep dsp_row)
  183091. {
  183092. #ifdef PNG_USE_LOCAL_ARRAYS
  183093. PNG_CONST PNG_IDAT;
  183094. PNG_CONST int png_pass_dsp_mask[7] = {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55,
  183095. 0xff};
  183096. PNG_CONST int png_pass_mask[7] = {0x80, 0x08, 0x88, 0x22, 0xaa, 0x55, 0xff};
  183097. #endif
  183098. int ret;
  183099. if(png_ptr == NULL) return;
  183100. png_debug2(1, "in png_read_row (row %lu, pass %d)\n",
  183101. png_ptr->row_number, png_ptr->pass);
  183102. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  183103. png_read_start_row(png_ptr);
  183104. if (png_ptr->row_number == 0 && png_ptr->pass == 0)
  183105. {
  183106. /* check for transforms that have been set but were defined out */
  183107. #if defined(PNG_WRITE_INVERT_SUPPORTED) && !defined(PNG_READ_INVERT_SUPPORTED)
  183108. if (png_ptr->transformations & PNG_INVERT_MONO)
  183109. png_warning(png_ptr, "PNG_READ_INVERT_SUPPORTED is not defined.");
  183110. #endif
  183111. #if defined(PNG_WRITE_FILLER_SUPPORTED) && !defined(PNG_READ_FILLER_SUPPORTED)
  183112. if (png_ptr->transformations & PNG_FILLER)
  183113. png_warning(png_ptr, "PNG_READ_FILLER_SUPPORTED is not defined.");
  183114. #endif
  183115. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED) && !defined(PNG_READ_PACKSWAP_SUPPORTED)
  183116. if (png_ptr->transformations & PNG_PACKSWAP)
  183117. png_warning(png_ptr, "PNG_READ_PACKSWAP_SUPPORTED is not defined.");
  183118. #endif
  183119. #if defined(PNG_WRITE_PACK_SUPPORTED) && !defined(PNG_READ_PACK_SUPPORTED)
  183120. if (png_ptr->transformations & PNG_PACK)
  183121. png_warning(png_ptr, "PNG_READ_PACK_SUPPORTED is not defined.");
  183122. #endif
  183123. #if defined(PNG_WRITE_SHIFT_SUPPORTED) && !defined(PNG_READ_SHIFT_SUPPORTED)
  183124. if (png_ptr->transformations & PNG_SHIFT)
  183125. png_warning(png_ptr, "PNG_READ_SHIFT_SUPPORTED is not defined.");
  183126. #endif
  183127. #if defined(PNG_WRITE_BGR_SUPPORTED) && !defined(PNG_READ_BGR_SUPPORTED)
  183128. if (png_ptr->transformations & PNG_BGR)
  183129. png_warning(png_ptr, "PNG_READ_BGR_SUPPORTED is not defined.");
  183130. #endif
  183131. #if defined(PNG_WRITE_SWAP_SUPPORTED) && !defined(PNG_READ_SWAP_SUPPORTED)
  183132. if (png_ptr->transformations & PNG_SWAP_BYTES)
  183133. png_warning(png_ptr, "PNG_READ_SWAP_SUPPORTED is not defined.");
  183134. #endif
  183135. }
  183136. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  183137. /* if interlaced and we do not need a new row, combine row and return */
  183138. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  183139. {
  183140. switch (png_ptr->pass)
  183141. {
  183142. case 0:
  183143. if (png_ptr->row_number & 0x07)
  183144. {
  183145. if (dsp_row != NULL)
  183146. png_combine_row(png_ptr, dsp_row,
  183147. png_pass_dsp_mask[png_ptr->pass]);
  183148. png_read_finish_row(png_ptr);
  183149. return;
  183150. }
  183151. break;
  183152. case 1:
  183153. if ((png_ptr->row_number & 0x07) || png_ptr->width < 5)
  183154. {
  183155. if (dsp_row != NULL)
  183156. png_combine_row(png_ptr, dsp_row,
  183157. png_pass_dsp_mask[png_ptr->pass]);
  183158. png_read_finish_row(png_ptr);
  183159. return;
  183160. }
  183161. break;
  183162. case 2:
  183163. if ((png_ptr->row_number & 0x07) != 4)
  183164. {
  183165. if (dsp_row != NULL && (png_ptr->row_number & 4))
  183166. png_combine_row(png_ptr, dsp_row,
  183167. png_pass_dsp_mask[png_ptr->pass]);
  183168. png_read_finish_row(png_ptr);
  183169. return;
  183170. }
  183171. break;
  183172. case 3:
  183173. if ((png_ptr->row_number & 3) || png_ptr->width < 3)
  183174. {
  183175. if (dsp_row != NULL)
  183176. png_combine_row(png_ptr, dsp_row,
  183177. png_pass_dsp_mask[png_ptr->pass]);
  183178. png_read_finish_row(png_ptr);
  183179. return;
  183180. }
  183181. break;
  183182. case 4:
  183183. if ((png_ptr->row_number & 3) != 2)
  183184. {
  183185. if (dsp_row != NULL && (png_ptr->row_number & 2))
  183186. png_combine_row(png_ptr, dsp_row,
  183187. png_pass_dsp_mask[png_ptr->pass]);
  183188. png_read_finish_row(png_ptr);
  183189. return;
  183190. }
  183191. break;
  183192. case 5:
  183193. if ((png_ptr->row_number & 1) || png_ptr->width < 2)
  183194. {
  183195. if (dsp_row != NULL)
  183196. png_combine_row(png_ptr, dsp_row,
  183197. png_pass_dsp_mask[png_ptr->pass]);
  183198. png_read_finish_row(png_ptr);
  183199. return;
  183200. }
  183201. break;
  183202. case 6:
  183203. if (!(png_ptr->row_number & 1))
  183204. {
  183205. png_read_finish_row(png_ptr);
  183206. return;
  183207. }
  183208. break;
  183209. }
  183210. }
  183211. #endif
  183212. if (!(png_ptr->mode & PNG_HAVE_IDAT))
  183213. png_error(png_ptr, "Invalid attempt to read row data");
  183214. png_ptr->zstream.next_out = png_ptr->row_buf;
  183215. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  183216. do
  183217. {
  183218. if (!(png_ptr->zstream.avail_in))
  183219. {
  183220. while (!png_ptr->idat_size)
  183221. {
  183222. png_byte chunk_length[4];
  183223. png_crc_finish(png_ptr, 0);
  183224. png_read_data(png_ptr, chunk_length, 4);
  183225. png_ptr->idat_size = png_get_uint_31(png_ptr,chunk_length);
  183226. png_reset_crc(png_ptr);
  183227. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  183228. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  183229. png_error(png_ptr, "Not enough image data");
  183230. }
  183231. png_ptr->zstream.avail_in = (uInt)png_ptr->zbuf_size;
  183232. png_ptr->zstream.next_in = png_ptr->zbuf;
  183233. if (png_ptr->zbuf_size > png_ptr->idat_size)
  183234. png_ptr->zstream.avail_in = (uInt)png_ptr->idat_size;
  183235. png_crc_read(png_ptr, png_ptr->zbuf,
  183236. (png_size_t)png_ptr->zstream.avail_in);
  183237. png_ptr->idat_size -= png_ptr->zstream.avail_in;
  183238. }
  183239. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  183240. if (ret == Z_STREAM_END)
  183241. {
  183242. if (png_ptr->zstream.avail_out || png_ptr->zstream.avail_in ||
  183243. png_ptr->idat_size)
  183244. png_error(png_ptr, "Extra compressed data");
  183245. png_ptr->mode |= PNG_AFTER_IDAT;
  183246. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  183247. break;
  183248. }
  183249. if (ret != Z_OK)
  183250. png_error(png_ptr, png_ptr->zstream.msg ? png_ptr->zstream.msg :
  183251. "Decompression error");
  183252. } while (png_ptr->zstream.avail_out);
  183253. png_ptr->row_info.color_type = png_ptr->color_type;
  183254. png_ptr->row_info.width = png_ptr->iwidth;
  183255. png_ptr->row_info.channels = png_ptr->channels;
  183256. png_ptr->row_info.bit_depth = png_ptr->bit_depth;
  183257. png_ptr->row_info.pixel_depth = png_ptr->pixel_depth;
  183258. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  183259. png_ptr->row_info.width);
  183260. if(png_ptr->row_buf[0])
  183261. png_read_filter_row(png_ptr, &(png_ptr->row_info),
  183262. png_ptr->row_buf + 1, png_ptr->prev_row + 1,
  183263. (int)(png_ptr->row_buf[0]));
  183264. png_memcpy_check(png_ptr, png_ptr->prev_row, png_ptr->row_buf,
  183265. png_ptr->rowbytes + 1);
  183266. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  183267. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  183268. (png_ptr->filter_type == PNG_INTRAPIXEL_DIFFERENCING))
  183269. {
  183270. /* Intrapixel differencing */
  183271. png_do_read_intrapixel(&(png_ptr->row_info), png_ptr->row_buf + 1);
  183272. }
  183273. #endif
  183274. if (png_ptr->transformations || (png_ptr->flags&PNG_FLAG_STRIP_ALPHA))
  183275. png_do_read_transformations(png_ptr);
  183276. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  183277. /* blow up interlaced rows to full size */
  183278. if (png_ptr->interlaced &&
  183279. (png_ptr->transformations & PNG_INTERLACE))
  183280. {
  183281. if (png_ptr->pass < 6)
  183282. /* old interface (pre-1.0.9):
  183283. png_do_read_interlace(&(png_ptr->row_info),
  183284. png_ptr->row_buf + 1, png_ptr->pass, png_ptr->transformations);
  183285. */
  183286. png_do_read_interlace(png_ptr);
  183287. if (dsp_row != NULL)
  183288. png_combine_row(png_ptr, dsp_row,
  183289. png_pass_dsp_mask[png_ptr->pass]);
  183290. if (row != NULL)
  183291. png_combine_row(png_ptr, row,
  183292. png_pass_mask[png_ptr->pass]);
  183293. }
  183294. else
  183295. #endif
  183296. {
  183297. if (row != NULL)
  183298. png_combine_row(png_ptr, row, 0xff);
  183299. if (dsp_row != NULL)
  183300. png_combine_row(png_ptr, dsp_row, 0xff);
  183301. }
  183302. png_read_finish_row(png_ptr);
  183303. if (png_ptr->read_row_fn != NULL)
  183304. (*(png_ptr->read_row_fn))(png_ptr, png_ptr->row_number, png_ptr->pass);
  183305. }
  183306. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  183307. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  183308. /* Read one or more rows of image data. If the image is interlaced,
  183309. * and png_set_interlace_handling() has been called, the rows need to
  183310. * contain the contents of the rows from the previous pass. If the
  183311. * image has alpha or transparency, and png_handle_alpha()[*] has been
  183312. * called, the rows contents must be initialized to the contents of the
  183313. * screen.
  183314. *
  183315. * "row" holds the actual image, and pixels are placed in it
  183316. * as they arrive. If the image is displayed after each pass, it will
  183317. * appear to "sparkle" in. "display_row" can be used to display a
  183318. * "chunky" progressive image, with finer detail added as it becomes
  183319. * available. If you do not want this "chunky" display, you may pass
  183320. * NULL for display_row. If you do not want the sparkle display, and
  183321. * you have not called png_handle_alpha(), you may pass NULL for rows.
  183322. * If you have called png_handle_alpha(), and the image has either an
  183323. * alpha channel or a transparency chunk, you must provide a buffer for
  183324. * rows. In this case, you do not have to provide a display_row buffer
  183325. * also, but you may. If the image is not interlaced, or if you have
  183326. * not called png_set_interlace_handling(), the display_row buffer will
  183327. * be ignored, so pass NULL to it.
  183328. *
  183329. * [*] png_handle_alpha() does not exist yet, as of this version of libpng
  183330. */
  183331. void PNGAPI
  183332. png_read_rows(png_structp png_ptr, png_bytepp row,
  183333. png_bytepp display_row, png_uint_32 num_rows)
  183334. {
  183335. png_uint_32 i;
  183336. png_bytepp rp;
  183337. png_bytepp dp;
  183338. png_debug(1, "in png_read_rows\n");
  183339. if(png_ptr == NULL) return;
  183340. rp = row;
  183341. dp = display_row;
  183342. if (rp != NULL && dp != NULL)
  183343. for (i = 0; i < num_rows; i++)
  183344. {
  183345. png_bytep rptr = *rp++;
  183346. png_bytep dptr = *dp++;
  183347. png_read_row(png_ptr, rptr, dptr);
  183348. }
  183349. else if(rp != NULL)
  183350. for (i = 0; i < num_rows; i++)
  183351. {
  183352. png_bytep rptr = *rp;
  183353. png_read_row(png_ptr, rptr, png_bytep_NULL);
  183354. rp++;
  183355. }
  183356. else if(dp != NULL)
  183357. for (i = 0; i < num_rows; i++)
  183358. {
  183359. png_bytep dptr = *dp;
  183360. png_read_row(png_ptr, png_bytep_NULL, dptr);
  183361. dp++;
  183362. }
  183363. }
  183364. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  183365. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  183366. /* Read the entire image. If the image has an alpha channel or a tRNS
  183367. * chunk, and you have called png_handle_alpha()[*], you will need to
  183368. * initialize the image to the current image that PNG will be overlaying.
  183369. * We set the num_rows again here, in case it was incorrectly set in
  183370. * png_read_start_row() by a call to png_read_update_info() or
  183371. * png_start_read_image() if png_set_interlace_handling() wasn't called
  183372. * prior to either of these functions like it should have been. You can
  183373. * only call this function once. If you desire to have an image for
  183374. * each pass of a interlaced image, use png_read_rows() instead.
  183375. *
  183376. * [*] png_handle_alpha() does not exist yet, as of this version of libpng
  183377. */
  183378. void PNGAPI
  183379. png_read_image(png_structp png_ptr, png_bytepp image)
  183380. {
  183381. png_uint_32 i,image_height;
  183382. int pass, j;
  183383. png_bytepp rp;
  183384. png_debug(1, "in png_read_image\n");
  183385. if(png_ptr == NULL) return;
  183386. #ifdef PNG_READ_INTERLACING_SUPPORTED
  183387. pass = png_set_interlace_handling(png_ptr);
  183388. #else
  183389. if (png_ptr->interlaced)
  183390. png_error(png_ptr,
  183391. "Cannot read interlaced image -- interlace handler disabled.");
  183392. pass = 1;
  183393. #endif
  183394. image_height=png_ptr->height;
  183395. png_ptr->num_rows = image_height; /* Make sure this is set correctly */
  183396. for (j = 0; j < pass; j++)
  183397. {
  183398. rp = image;
  183399. for (i = 0; i < image_height; i++)
  183400. {
  183401. png_read_row(png_ptr, *rp, png_bytep_NULL);
  183402. rp++;
  183403. }
  183404. }
  183405. }
  183406. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  183407. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  183408. /* Read the end of the PNG file. Will not read past the end of the
  183409. * file, will verify the end is accurate, and will read any comments
  183410. * or time information at the end of the file, if info is not NULL.
  183411. */
  183412. void PNGAPI
  183413. png_read_end(png_structp png_ptr, png_infop info_ptr)
  183414. {
  183415. png_byte chunk_length[4];
  183416. png_uint_32 length;
  183417. png_debug(1, "in png_read_end\n");
  183418. if(png_ptr == NULL) return;
  183419. png_crc_finish(png_ptr, 0); /* Finish off CRC from last IDAT chunk */
  183420. do
  183421. {
  183422. #ifdef PNG_USE_LOCAL_ARRAYS
  183423. PNG_CONST PNG_IHDR;
  183424. PNG_CONST PNG_IDAT;
  183425. PNG_CONST PNG_IEND;
  183426. PNG_CONST PNG_PLTE;
  183427. #if defined(PNG_READ_bKGD_SUPPORTED)
  183428. PNG_CONST PNG_bKGD;
  183429. #endif
  183430. #if defined(PNG_READ_cHRM_SUPPORTED)
  183431. PNG_CONST PNG_cHRM;
  183432. #endif
  183433. #if defined(PNG_READ_gAMA_SUPPORTED)
  183434. PNG_CONST PNG_gAMA;
  183435. #endif
  183436. #if defined(PNG_READ_hIST_SUPPORTED)
  183437. PNG_CONST PNG_hIST;
  183438. #endif
  183439. #if defined(PNG_READ_iCCP_SUPPORTED)
  183440. PNG_CONST PNG_iCCP;
  183441. #endif
  183442. #if defined(PNG_READ_iTXt_SUPPORTED)
  183443. PNG_CONST PNG_iTXt;
  183444. #endif
  183445. #if defined(PNG_READ_oFFs_SUPPORTED)
  183446. PNG_CONST PNG_oFFs;
  183447. #endif
  183448. #if defined(PNG_READ_pCAL_SUPPORTED)
  183449. PNG_CONST PNG_pCAL;
  183450. #endif
  183451. #if defined(PNG_READ_pHYs_SUPPORTED)
  183452. PNG_CONST PNG_pHYs;
  183453. #endif
  183454. #if defined(PNG_READ_sBIT_SUPPORTED)
  183455. PNG_CONST PNG_sBIT;
  183456. #endif
  183457. #if defined(PNG_READ_sCAL_SUPPORTED)
  183458. PNG_CONST PNG_sCAL;
  183459. #endif
  183460. #if defined(PNG_READ_sPLT_SUPPORTED)
  183461. PNG_CONST PNG_sPLT;
  183462. #endif
  183463. #if defined(PNG_READ_sRGB_SUPPORTED)
  183464. PNG_CONST PNG_sRGB;
  183465. #endif
  183466. #if defined(PNG_READ_tEXt_SUPPORTED)
  183467. PNG_CONST PNG_tEXt;
  183468. #endif
  183469. #if defined(PNG_READ_tIME_SUPPORTED)
  183470. PNG_CONST PNG_tIME;
  183471. #endif
  183472. #if defined(PNG_READ_tRNS_SUPPORTED)
  183473. PNG_CONST PNG_tRNS;
  183474. #endif
  183475. #if defined(PNG_READ_zTXt_SUPPORTED)
  183476. PNG_CONST PNG_zTXt;
  183477. #endif
  183478. #endif /* PNG_USE_LOCAL_ARRAYS */
  183479. png_read_data(png_ptr, chunk_length, 4);
  183480. length = png_get_uint_31(png_ptr,chunk_length);
  183481. png_reset_crc(png_ptr);
  183482. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  183483. png_debug1(0, "Reading %s chunk.\n", png_ptr->chunk_name);
  183484. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  183485. png_handle_IHDR(png_ptr, info_ptr, length);
  183486. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  183487. png_handle_IEND(png_ptr, info_ptr, length);
  183488. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  183489. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  183490. {
  183491. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  183492. {
  183493. if ((length > 0) || (png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  183494. png_error(png_ptr, "Too many IDAT's found");
  183495. }
  183496. png_handle_unknown(png_ptr, info_ptr, length);
  183497. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  183498. png_ptr->mode |= PNG_HAVE_PLTE;
  183499. }
  183500. #endif
  183501. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  183502. {
  183503. /* Zero length IDATs are legal after the last IDAT has been
  183504. * read, but not after other chunks have been read.
  183505. */
  183506. if ((length > 0) || (png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  183507. png_error(png_ptr, "Too many IDAT's found");
  183508. png_crc_finish(png_ptr, length);
  183509. }
  183510. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  183511. png_handle_PLTE(png_ptr, info_ptr, length);
  183512. #if defined(PNG_READ_bKGD_SUPPORTED)
  183513. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  183514. png_handle_bKGD(png_ptr, info_ptr, length);
  183515. #endif
  183516. #if defined(PNG_READ_cHRM_SUPPORTED)
  183517. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  183518. png_handle_cHRM(png_ptr, info_ptr, length);
  183519. #endif
  183520. #if defined(PNG_READ_gAMA_SUPPORTED)
  183521. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  183522. png_handle_gAMA(png_ptr, info_ptr, length);
  183523. #endif
  183524. #if defined(PNG_READ_hIST_SUPPORTED)
  183525. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  183526. png_handle_hIST(png_ptr, info_ptr, length);
  183527. #endif
  183528. #if defined(PNG_READ_oFFs_SUPPORTED)
  183529. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  183530. png_handle_oFFs(png_ptr, info_ptr, length);
  183531. #endif
  183532. #if defined(PNG_READ_pCAL_SUPPORTED)
  183533. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  183534. png_handle_pCAL(png_ptr, info_ptr, length);
  183535. #endif
  183536. #if defined(PNG_READ_sCAL_SUPPORTED)
  183537. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  183538. png_handle_sCAL(png_ptr, info_ptr, length);
  183539. #endif
  183540. #if defined(PNG_READ_pHYs_SUPPORTED)
  183541. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  183542. png_handle_pHYs(png_ptr, info_ptr, length);
  183543. #endif
  183544. #if defined(PNG_READ_sBIT_SUPPORTED)
  183545. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  183546. png_handle_sBIT(png_ptr, info_ptr, length);
  183547. #endif
  183548. #if defined(PNG_READ_sRGB_SUPPORTED)
  183549. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  183550. png_handle_sRGB(png_ptr, info_ptr, length);
  183551. #endif
  183552. #if defined(PNG_READ_iCCP_SUPPORTED)
  183553. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  183554. png_handle_iCCP(png_ptr, info_ptr, length);
  183555. #endif
  183556. #if defined(PNG_READ_sPLT_SUPPORTED)
  183557. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  183558. png_handle_sPLT(png_ptr, info_ptr, length);
  183559. #endif
  183560. #if defined(PNG_READ_tEXt_SUPPORTED)
  183561. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  183562. png_handle_tEXt(png_ptr, info_ptr, length);
  183563. #endif
  183564. #if defined(PNG_READ_tIME_SUPPORTED)
  183565. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  183566. png_handle_tIME(png_ptr, info_ptr, length);
  183567. #endif
  183568. #if defined(PNG_READ_tRNS_SUPPORTED)
  183569. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  183570. png_handle_tRNS(png_ptr, info_ptr, length);
  183571. #endif
  183572. #if defined(PNG_READ_zTXt_SUPPORTED)
  183573. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  183574. png_handle_zTXt(png_ptr, info_ptr, length);
  183575. #endif
  183576. #if defined(PNG_READ_iTXt_SUPPORTED)
  183577. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  183578. png_handle_iTXt(png_ptr, info_ptr, length);
  183579. #endif
  183580. else
  183581. png_handle_unknown(png_ptr, info_ptr, length);
  183582. } while (!(png_ptr->mode & PNG_HAVE_IEND));
  183583. }
  183584. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  183585. /* free all memory used by the read */
  183586. void PNGAPI
  183587. png_destroy_read_struct(png_structpp png_ptr_ptr, png_infopp info_ptr_ptr,
  183588. png_infopp end_info_ptr_ptr)
  183589. {
  183590. png_structp png_ptr = NULL;
  183591. png_infop info_ptr = NULL, end_info_ptr = NULL;
  183592. #ifdef PNG_USER_MEM_SUPPORTED
  183593. png_free_ptr free_fn;
  183594. png_voidp mem_ptr;
  183595. #endif
  183596. png_debug(1, "in png_destroy_read_struct\n");
  183597. if (png_ptr_ptr != NULL)
  183598. png_ptr = *png_ptr_ptr;
  183599. if (info_ptr_ptr != NULL)
  183600. info_ptr = *info_ptr_ptr;
  183601. if (end_info_ptr_ptr != NULL)
  183602. end_info_ptr = *end_info_ptr_ptr;
  183603. #ifdef PNG_USER_MEM_SUPPORTED
  183604. free_fn = png_ptr->free_fn;
  183605. mem_ptr = png_ptr->mem_ptr;
  183606. #endif
  183607. png_read_destroy(png_ptr, info_ptr, end_info_ptr);
  183608. if (info_ptr != NULL)
  183609. {
  183610. #if defined(PNG_TEXT_SUPPORTED)
  183611. png_free_data(png_ptr, info_ptr, PNG_FREE_TEXT, -1);
  183612. #endif
  183613. #ifdef PNG_USER_MEM_SUPPORTED
  183614. png_destroy_struct_2((png_voidp)info_ptr, (png_free_ptr)free_fn,
  183615. (png_voidp)mem_ptr);
  183616. #else
  183617. png_destroy_struct((png_voidp)info_ptr);
  183618. #endif
  183619. *info_ptr_ptr = NULL;
  183620. }
  183621. if (end_info_ptr != NULL)
  183622. {
  183623. #if defined(PNG_READ_TEXT_SUPPORTED)
  183624. png_free_data(png_ptr, end_info_ptr, PNG_FREE_TEXT, -1);
  183625. #endif
  183626. #ifdef PNG_USER_MEM_SUPPORTED
  183627. png_destroy_struct_2((png_voidp)end_info_ptr, (png_free_ptr)free_fn,
  183628. (png_voidp)mem_ptr);
  183629. #else
  183630. png_destroy_struct((png_voidp)end_info_ptr);
  183631. #endif
  183632. *end_info_ptr_ptr = NULL;
  183633. }
  183634. if (png_ptr != NULL)
  183635. {
  183636. #ifdef PNG_USER_MEM_SUPPORTED
  183637. png_destroy_struct_2((png_voidp)png_ptr, (png_free_ptr)free_fn,
  183638. (png_voidp)mem_ptr);
  183639. #else
  183640. png_destroy_struct((png_voidp)png_ptr);
  183641. #endif
  183642. *png_ptr_ptr = NULL;
  183643. }
  183644. }
  183645. /* free all memory used by the read (old method) */
  183646. void /* PRIVATE */
  183647. png_read_destroy(png_structp png_ptr, png_infop info_ptr, png_infop end_info_ptr)
  183648. {
  183649. #ifdef PNG_SETJMP_SUPPORTED
  183650. jmp_buf tmp_jmp;
  183651. #endif
  183652. png_error_ptr error_fn;
  183653. png_error_ptr warning_fn;
  183654. png_voidp error_ptr;
  183655. #ifdef PNG_USER_MEM_SUPPORTED
  183656. png_free_ptr free_fn;
  183657. #endif
  183658. png_debug(1, "in png_read_destroy\n");
  183659. if (info_ptr != NULL)
  183660. png_info_destroy(png_ptr, info_ptr);
  183661. if (end_info_ptr != NULL)
  183662. png_info_destroy(png_ptr, end_info_ptr);
  183663. png_free(png_ptr, png_ptr->zbuf);
  183664. png_free(png_ptr, png_ptr->big_row_buf);
  183665. png_free(png_ptr, png_ptr->prev_row);
  183666. #if defined(PNG_READ_DITHER_SUPPORTED)
  183667. png_free(png_ptr, png_ptr->palette_lookup);
  183668. png_free(png_ptr, png_ptr->dither_index);
  183669. #endif
  183670. #if defined(PNG_READ_GAMMA_SUPPORTED)
  183671. png_free(png_ptr, png_ptr->gamma_table);
  183672. #endif
  183673. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  183674. png_free(png_ptr, png_ptr->gamma_from_1);
  183675. png_free(png_ptr, png_ptr->gamma_to_1);
  183676. #endif
  183677. #ifdef PNG_FREE_ME_SUPPORTED
  183678. if (png_ptr->free_me & PNG_FREE_PLTE)
  183679. png_zfree(png_ptr, png_ptr->palette);
  183680. png_ptr->free_me &= ~PNG_FREE_PLTE;
  183681. #else
  183682. if (png_ptr->flags & PNG_FLAG_FREE_PLTE)
  183683. png_zfree(png_ptr, png_ptr->palette);
  183684. png_ptr->flags &= ~PNG_FLAG_FREE_PLTE;
  183685. #endif
  183686. #if defined(PNG_tRNS_SUPPORTED) || \
  183687. defined(PNG_READ_EXPAND_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  183688. #ifdef PNG_FREE_ME_SUPPORTED
  183689. if (png_ptr->free_me & PNG_FREE_TRNS)
  183690. png_free(png_ptr, png_ptr->trans);
  183691. png_ptr->free_me &= ~PNG_FREE_TRNS;
  183692. #else
  183693. if (png_ptr->flags & PNG_FLAG_FREE_TRNS)
  183694. png_free(png_ptr, png_ptr->trans);
  183695. png_ptr->flags &= ~PNG_FLAG_FREE_TRNS;
  183696. #endif
  183697. #endif
  183698. #if defined(PNG_READ_hIST_SUPPORTED)
  183699. #ifdef PNG_FREE_ME_SUPPORTED
  183700. if (png_ptr->free_me & PNG_FREE_HIST)
  183701. png_free(png_ptr, png_ptr->hist);
  183702. png_ptr->free_me &= ~PNG_FREE_HIST;
  183703. #else
  183704. if (png_ptr->flags & PNG_FLAG_FREE_HIST)
  183705. png_free(png_ptr, png_ptr->hist);
  183706. png_ptr->flags &= ~PNG_FLAG_FREE_HIST;
  183707. #endif
  183708. #endif
  183709. #if defined(PNG_READ_GAMMA_SUPPORTED)
  183710. if (png_ptr->gamma_16_table != NULL)
  183711. {
  183712. int i;
  183713. int istop = (1 << (8 - png_ptr->gamma_shift));
  183714. for (i = 0; i < istop; i++)
  183715. {
  183716. png_free(png_ptr, png_ptr->gamma_16_table[i]);
  183717. }
  183718. png_free(png_ptr, png_ptr->gamma_16_table);
  183719. }
  183720. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  183721. if (png_ptr->gamma_16_from_1 != NULL)
  183722. {
  183723. int i;
  183724. int istop = (1 << (8 - png_ptr->gamma_shift));
  183725. for (i = 0; i < istop; i++)
  183726. {
  183727. png_free(png_ptr, png_ptr->gamma_16_from_1[i]);
  183728. }
  183729. png_free(png_ptr, png_ptr->gamma_16_from_1);
  183730. }
  183731. if (png_ptr->gamma_16_to_1 != NULL)
  183732. {
  183733. int i;
  183734. int istop = (1 << (8 - png_ptr->gamma_shift));
  183735. for (i = 0; i < istop; i++)
  183736. {
  183737. png_free(png_ptr, png_ptr->gamma_16_to_1[i]);
  183738. }
  183739. png_free(png_ptr, png_ptr->gamma_16_to_1);
  183740. }
  183741. #endif
  183742. #endif
  183743. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  183744. png_free(png_ptr, png_ptr->time_buffer);
  183745. #endif
  183746. inflateEnd(&png_ptr->zstream);
  183747. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  183748. png_free(png_ptr, png_ptr->save_buffer);
  183749. #endif
  183750. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  183751. #ifdef PNG_TEXT_SUPPORTED
  183752. png_free(png_ptr, png_ptr->current_text);
  183753. #endif /* PNG_TEXT_SUPPORTED */
  183754. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  183755. /* Save the important info out of the png_struct, in case it is
  183756. * being used again.
  183757. */
  183758. #ifdef PNG_SETJMP_SUPPORTED
  183759. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  183760. #endif
  183761. error_fn = png_ptr->error_fn;
  183762. warning_fn = png_ptr->warning_fn;
  183763. error_ptr = png_ptr->error_ptr;
  183764. #ifdef PNG_USER_MEM_SUPPORTED
  183765. free_fn = png_ptr->free_fn;
  183766. #endif
  183767. png_memset(png_ptr, 0, png_sizeof (png_struct));
  183768. png_ptr->error_fn = error_fn;
  183769. png_ptr->warning_fn = warning_fn;
  183770. png_ptr->error_ptr = error_ptr;
  183771. #ifdef PNG_USER_MEM_SUPPORTED
  183772. png_ptr->free_fn = free_fn;
  183773. #endif
  183774. #ifdef PNG_SETJMP_SUPPORTED
  183775. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  183776. #endif
  183777. }
  183778. void PNGAPI
  183779. png_set_read_status_fn(png_structp png_ptr, png_read_status_ptr read_row_fn)
  183780. {
  183781. if(png_ptr == NULL) return;
  183782. png_ptr->read_row_fn = read_row_fn;
  183783. }
  183784. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  183785. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  183786. void PNGAPI
  183787. png_read_png(png_structp png_ptr, png_infop info_ptr,
  183788. int transforms,
  183789. voidp params)
  183790. {
  183791. int row;
  183792. if(png_ptr == NULL) return;
  183793. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  183794. /* invert the alpha channel from opacity to transparency
  183795. */
  183796. if (transforms & PNG_TRANSFORM_INVERT_ALPHA)
  183797. png_set_invert_alpha(png_ptr);
  183798. #endif
  183799. /* png_read_info() gives us all of the information from the
  183800. * PNG file before the first IDAT (image data chunk).
  183801. */
  183802. png_read_info(png_ptr, info_ptr);
  183803. if (info_ptr->height > PNG_UINT_32_MAX/png_sizeof(png_bytep))
  183804. png_error(png_ptr,"Image is too high to process with png_read_png()");
  183805. /* -------------- image transformations start here ------------------- */
  183806. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  183807. /* tell libpng to strip 16 bit/color files down to 8 bits per color
  183808. */
  183809. if (transforms & PNG_TRANSFORM_STRIP_16)
  183810. png_set_strip_16(png_ptr);
  183811. #endif
  183812. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  183813. /* Strip alpha bytes from the input data without combining with
  183814. * the background (not recommended).
  183815. */
  183816. if (transforms & PNG_TRANSFORM_STRIP_ALPHA)
  183817. png_set_strip_alpha(png_ptr);
  183818. #endif
  183819. #if defined(PNG_READ_PACK_SUPPORTED) && !defined(PNG_READ_EXPAND_SUPPORTED)
  183820. /* Extract multiple pixels with bit depths of 1, 2, or 4 from a single
  183821. * byte into separate bytes (useful for paletted and grayscale images).
  183822. */
  183823. if (transforms & PNG_TRANSFORM_PACKING)
  183824. png_set_packing(png_ptr);
  183825. #endif
  183826. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  183827. /* Change the order of packed pixels to least significant bit first
  183828. * (not useful if you are using png_set_packing).
  183829. */
  183830. if (transforms & PNG_TRANSFORM_PACKSWAP)
  183831. png_set_packswap(png_ptr);
  183832. #endif
  183833. #if defined(PNG_READ_EXPAND_SUPPORTED)
  183834. /* Expand paletted colors into true RGB triplets
  183835. * Expand grayscale images to full 8 bits from 1, 2, or 4 bits/pixel
  183836. * Expand paletted or RGB images with transparency to full alpha
  183837. * channels so the data will be available as RGBA quartets.
  183838. */
  183839. if (transforms & PNG_TRANSFORM_EXPAND)
  183840. if ((png_ptr->bit_depth < 8) ||
  183841. (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE) ||
  183842. (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)))
  183843. png_set_expand(png_ptr);
  183844. #endif
  183845. /* We don't handle background color or gamma transformation or dithering.
  183846. */
  183847. #if defined(PNG_READ_INVERT_SUPPORTED)
  183848. /* invert monochrome files to have 0 as white and 1 as black
  183849. */
  183850. if (transforms & PNG_TRANSFORM_INVERT_MONO)
  183851. png_set_invert_mono(png_ptr);
  183852. #endif
  183853. #if defined(PNG_READ_SHIFT_SUPPORTED)
  183854. /* If you want to shift the pixel values from the range [0,255] or
  183855. * [0,65535] to the original [0,7] or [0,31], or whatever range the
  183856. * colors were originally in:
  183857. */
  183858. if ((transforms & PNG_TRANSFORM_SHIFT)
  183859. && png_get_valid(png_ptr, info_ptr, PNG_INFO_sBIT))
  183860. {
  183861. png_color_8p sig_bit;
  183862. png_get_sBIT(png_ptr, info_ptr, &sig_bit);
  183863. png_set_shift(png_ptr, sig_bit);
  183864. }
  183865. #endif
  183866. #if defined(PNG_READ_BGR_SUPPORTED)
  183867. /* flip the RGB pixels to BGR (or RGBA to BGRA)
  183868. */
  183869. if (transforms & PNG_TRANSFORM_BGR)
  183870. png_set_bgr(png_ptr);
  183871. #endif
  183872. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  183873. /* swap the RGBA or GA data to ARGB or AG (or BGRA to ABGR)
  183874. */
  183875. if (transforms & PNG_TRANSFORM_SWAP_ALPHA)
  183876. png_set_swap_alpha(png_ptr);
  183877. #endif
  183878. #if defined(PNG_READ_SWAP_SUPPORTED)
  183879. /* swap bytes of 16 bit files to least significant byte first
  183880. */
  183881. if (transforms & PNG_TRANSFORM_SWAP_ENDIAN)
  183882. png_set_swap(png_ptr);
  183883. #endif
  183884. /* We don't handle adding filler bytes */
  183885. /* Optional call to gamma correct and add the background to the palette
  183886. * and update info structure. REQUIRED if you are expecting libpng to
  183887. * update the palette for you (i.e., you selected such a transform above).
  183888. */
  183889. png_read_update_info(png_ptr, info_ptr);
  183890. /* -------------- image transformations end here ------------------- */
  183891. #ifdef PNG_FREE_ME_SUPPORTED
  183892. png_free_data(png_ptr, info_ptr, PNG_FREE_ROWS, 0);
  183893. #endif
  183894. if(info_ptr->row_pointers == NULL)
  183895. {
  183896. info_ptr->row_pointers = (png_bytepp)png_malloc(png_ptr,
  183897. info_ptr->height * png_sizeof(png_bytep));
  183898. #ifdef PNG_FREE_ME_SUPPORTED
  183899. info_ptr->free_me |= PNG_FREE_ROWS;
  183900. #endif
  183901. for (row = 0; row < (int)info_ptr->height; row++)
  183902. {
  183903. info_ptr->row_pointers[row] = (png_bytep)png_malloc(png_ptr,
  183904. png_get_rowbytes(png_ptr, info_ptr));
  183905. }
  183906. }
  183907. png_read_image(png_ptr, info_ptr->row_pointers);
  183908. info_ptr->valid |= PNG_INFO_IDAT;
  183909. /* read rest of file, and get additional chunks in info_ptr - REQUIRED */
  183910. png_read_end(png_ptr, info_ptr);
  183911. transforms = transforms; /* quiet compiler warnings */
  183912. params = params;
  183913. }
  183914. #endif /* PNG_INFO_IMAGE_SUPPORTED */
  183915. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  183916. #endif /* PNG_READ_SUPPORTED */
  183917. /********* End of inlined file: pngread.c *********/
  183918. /********* Start of inlined file: pngpread.c *********/
  183919. /* pngpread.c - read a png file in push mode
  183920. *
  183921. * Last changed in libpng 1.2.21 October 4, 2007
  183922. * For conditions of distribution and use, see copyright notice in png.h
  183923. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  183924. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  183925. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  183926. */
  183927. #define PNG_INTERNAL
  183928. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  183929. /* push model modes */
  183930. #define PNG_READ_SIG_MODE 0
  183931. #define PNG_READ_CHUNK_MODE 1
  183932. #define PNG_READ_IDAT_MODE 2
  183933. #define PNG_SKIP_MODE 3
  183934. #define PNG_READ_tEXt_MODE 4
  183935. #define PNG_READ_zTXt_MODE 5
  183936. #define PNG_READ_DONE_MODE 6
  183937. #define PNG_READ_iTXt_MODE 7
  183938. #define PNG_ERROR_MODE 8
  183939. void PNGAPI
  183940. png_process_data(png_structp png_ptr, png_infop info_ptr,
  183941. png_bytep buffer, png_size_t buffer_size)
  183942. {
  183943. if(png_ptr == NULL) return;
  183944. png_push_restore_buffer(png_ptr, buffer, buffer_size);
  183945. while (png_ptr->buffer_size)
  183946. {
  183947. png_process_some_data(png_ptr, info_ptr);
  183948. }
  183949. }
  183950. /* What we do with the incoming data depends on what we were previously
  183951. * doing before we ran out of data...
  183952. */
  183953. void /* PRIVATE */
  183954. png_process_some_data(png_structp png_ptr, png_infop info_ptr)
  183955. {
  183956. if(png_ptr == NULL) return;
  183957. switch (png_ptr->process_mode)
  183958. {
  183959. case PNG_READ_SIG_MODE:
  183960. {
  183961. png_push_read_sig(png_ptr, info_ptr);
  183962. break;
  183963. }
  183964. case PNG_READ_CHUNK_MODE:
  183965. {
  183966. png_push_read_chunk(png_ptr, info_ptr);
  183967. break;
  183968. }
  183969. case PNG_READ_IDAT_MODE:
  183970. {
  183971. png_push_read_IDAT(png_ptr);
  183972. break;
  183973. }
  183974. #if defined(PNG_READ_tEXt_SUPPORTED)
  183975. case PNG_READ_tEXt_MODE:
  183976. {
  183977. png_push_read_tEXt(png_ptr, info_ptr);
  183978. break;
  183979. }
  183980. #endif
  183981. #if defined(PNG_READ_zTXt_SUPPORTED)
  183982. case PNG_READ_zTXt_MODE:
  183983. {
  183984. png_push_read_zTXt(png_ptr, info_ptr);
  183985. break;
  183986. }
  183987. #endif
  183988. #if defined(PNG_READ_iTXt_SUPPORTED)
  183989. case PNG_READ_iTXt_MODE:
  183990. {
  183991. png_push_read_iTXt(png_ptr, info_ptr);
  183992. break;
  183993. }
  183994. #endif
  183995. case PNG_SKIP_MODE:
  183996. {
  183997. png_push_crc_finish(png_ptr);
  183998. break;
  183999. }
  184000. default:
  184001. {
  184002. png_ptr->buffer_size = 0;
  184003. break;
  184004. }
  184005. }
  184006. }
  184007. /* Read any remaining signature bytes from the stream and compare them with
  184008. * the correct PNG signature. It is possible that this routine is called
  184009. * with bytes already read from the signature, either because they have been
  184010. * checked by the calling application, or because of multiple calls to this
  184011. * routine.
  184012. */
  184013. void /* PRIVATE */
  184014. png_push_read_sig(png_structp png_ptr, png_infop info_ptr)
  184015. {
  184016. png_size_t num_checked = png_ptr->sig_bytes,
  184017. num_to_check = 8 - num_checked;
  184018. if (png_ptr->buffer_size < num_to_check)
  184019. {
  184020. num_to_check = png_ptr->buffer_size;
  184021. }
  184022. png_push_fill_buffer(png_ptr, &(info_ptr->signature[num_checked]),
  184023. num_to_check);
  184024. png_ptr->sig_bytes = (png_byte)(png_ptr->sig_bytes+num_to_check);
  184025. if (png_sig_cmp(info_ptr->signature, num_checked, num_to_check))
  184026. {
  184027. if (num_checked < 4 &&
  184028. png_sig_cmp(info_ptr->signature, num_checked, num_to_check - 4))
  184029. png_error(png_ptr, "Not a PNG file");
  184030. else
  184031. png_error(png_ptr, "PNG file corrupted by ASCII conversion");
  184032. }
  184033. else
  184034. {
  184035. if (png_ptr->sig_bytes >= 8)
  184036. {
  184037. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  184038. }
  184039. }
  184040. }
  184041. void /* PRIVATE */
  184042. png_push_read_chunk(png_structp png_ptr, png_infop info_ptr)
  184043. {
  184044. #ifdef PNG_USE_LOCAL_ARRAYS
  184045. PNG_CONST PNG_IHDR;
  184046. PNG_CONST PNG_IDAT;
  184047. PNG_CONST PNG_IEND;
  184048. PNG_CONST PNG_PLTE;
  184049. #if defined(PNG_READ_bKGD_SUPPORTED)
  184050. PNG_CONST PNG_bKGD;
  184051. #endif
  184052. #if defined(PNG_READ_cHRM_SUPPORTED)
  184053. PNG_CONST PNG_cHRM;
  184054. #endif
  184055. #if defined(PNG_READ_gAMA_SUPPORTED)
  184056. PNG_CONST PNG_gAMA;
  184057. #endif
  184058. #if defined(PNG_READ_hIST_SUPPORTED)
  184059. PNG_CONST PNG_hIST;
  184060. #endif
  184061. #if defined(PNG_READ_iCCP_SUPPORTED)
  184062. PNG_CONST PNG_iCCP;
  184063. #endif
  184064. #if defined(PNG_READ_iTXt_SUPPORTED)
  184065. PNG_CONST PNG_iTXt;
  184066. #endif
  184067. #if defined(PNG_READ_oFFs_SUPPORTED)
  184068. PNG_CONST PNG_oFFs;
  184069. #endif
  184070. #if defined(PNG_READ_pCAL_SUPPORTED)
  184071. PNG_CONST PNG_pCAL;
  184072. #endif
  184073. #if defined(PNG_READ_pHYs_SUPPORTED)
  184074. PNG_CONST PNG_pHYs;
  184075. #endif
  184076. #if defined(PNG_READ_sBIT_SUPPORTED)
  184077. PNG_CONST PNG_sBIT;
  184078. #endif
  184079. #if defined(PNG_READ_sCAL_SUPPORTED)
  184080. PNG_CONST PNG_sCAL;
  184081. #endif
  184082. #if defined(PNG_READ_sRGB_SUPPORTED)
  184083. PNG_CONST PNG_sRGB;
  184084. #endif
  184085. #if defined(PNG_READ_sPLT_SUPPORTED)
  184086. PNG_CONST PNG_sPLT;
  184087. #endif
  184088. #if defined(PNG_READ_tEXt_SUPPORTED)
  184089. PNG_CONST PNG_tEXt;
  184090. #endif
  184091. #if defined(PNG_READ_tIME_SUPPORTED)
  184092. PNG_CONST PNG_tIME;
  184093. #endif
  184094. #if defined(PNG_READ_tRNS_SUPPORTED)
  184095. PNG_CONST PNG_tRNS;
  184096. #endif
  184097. #if defined(PNG_READ_zTXt_SUPPORTED)
  184098. PNG_CONST PNG_zTXt;
  184099. #endif
  184100. #endif /* PNG_USE_LOCAL_ARRAYS */
  184101. /* First we make sure we have enough data for the 4 byte chunk name
  184102. * and the 4 byte chunk length before proceeding with decoding the
  184103. * chunk data. To fully decode each of these chunks, we also make
  184104. * sure we have enough data in the buffer for the 4 byte CRC at the
  184105. * end of every chunk (except IDAT, which is handled separately).
  184106. */
  184107. if (!(png_ptr->mode & PNG_HAVE_CHUNK_HEADER))
  184108. {
  184109. png_byte chunk_length[4];
  184110. if (png_ptr->buffer_size < 8)
  184111. {
  184112. png_push_save_buffer(png_ptr);
  184113. return;
  184114. }
  184115. png_push_fill_buffer(png_ptr, chunk_length, 4);
  184116. png_ptr->push_length = png_get_uint_31(png_ptr,chunk_length);
  184117. png_reset_crc(png_ptr);
  184118. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  184119. png_ptr->mode |= PNG_HAVE_CHUNK_HEADER;
  184120. }
  184121. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  184122. if(png_ptr->mode & PNG_AFTER_IDAT)
  184123. png_ptr->mode |= PNG_HAVE_CHUNK_AFTER_IDAT;
  184124. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  184125. {
  184126. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  184127. {
  184128. png_push_save_buffer(png_ptr);
  184129. return;
  184130. }
  184131. png_handle_IHDR(png_ptr, info_ptr, png_ptr->push_length);
  184132. }
  184133. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  184134. {
  184135. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  184136. {
  184137. png_push_save_buffer(png_ptr);
  184138. return;
  184139. }
  184140. png_handle_IEND(png_ptr, info_ptr, png_ptr->push_length);
  184141. png_ptr->process_mode = PNG_READ_DONE_MODE;
  184142. png_push_have_end(png_ptr, info_ptr);
  184143. }
  184144. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  184145. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  184146. {
  184147. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  184148. {
  184149. png_push_save_buffer(png_ptr);
  184150. return;
  184151. }
  184152. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  184153. png_ptr->mode |= PNG_HAVE_IDAT;
  184154. png_handle_unknown(png_ptr, info_ptr, png_ptr->push_length);
  184155. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  184156. png_ptr->mode |= PNG_HAVE_PLTE;
  184157. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  184158. {
  184159. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  184160. png_error(png_ptr, "Missing IHDR before IDAT");
  184161. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  184162. !(png_ptr->mode & PNG_HAVE_PLTE))
  184163. png_error(png_ptr, "Missing PLTE before IDAT");
  184164. }
  184165. }
  184166. #endif
  184167. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  184168. {
  184169. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  184170. {
  184171. png_push_save_buffer(png_ptr);
  184172. return;
  184173. }
  184174. png_handle_PLTE(png_ptr, info_ptr, png_ptr->push_length);
  184175. }
  184176. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  184177. {
  184178. /* If we reach an IDAT chunk, this means we have read all of the
  184179. * header chunks, and we can start reading the image (or if this
  184180. * is called after the image has been read - we have an error).
  184181. */
  184182. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  184183. png_error(png_ptr, "Missing IHDR before IDAT");
  184184. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  184185. !(png_ptr->mode & PNG_HAVE_PLTE))
  184186. png_error(png_ptr, "Missing PLTE before IDAT");
  184187. if (png_ptr->mode & PNG_HAVE_IDAT)
  184188. {
  184189. if (!(png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  184190. if (png_ptr->push_length == 0)
  184191. return;
  184192. if (png_ptr->mode & PNG_AFTER_IDAT)
  184193. png_error(png_ptr, "Too many IDAT's found");
  184194. }
  184195. png_ptr->idat_size = png_ptr->push_length;
  184196. png_ptr->mode |= PNG_HAVE_IDAT;
  184197. png_ptr->process_mode = PNG_READ_IDAT_MODE;
  184198. png_push_have_info(png_ptr, info_ptr);
  184199. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  184200. png_ptr->zstream.next_out = png_ptr->row_buf;
  184201. return;
  184202. }
  184203. #if defined(PNG_READ_gAMA_SUPPORTED)
  184204. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  184205. {
  184206. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  184207. {
  184208. png_push_save_buffer(png_ptr);
  184209. return;
  184210. }
  184211. png_handle_gAMA(png_ptr, info_ptr, png_ptr->push_length);
  184212. }
  184213. #endif
  184214. #if defined(PNG_READ_sBIT_SUPPORTED)
  184215. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  184216. {
  184217. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  184218. {
  184219. png_push_save_buffer(png_ptr);
  184220. return;
  184221. }
  184222. png_handle_sBIT(png_ptr, info_ptr, png_ptr->push_length);
  184223. }
  184224. #endif
  184225. #if defined(PNG_READ_cHRM_SUPPORTED)
  184226. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  184227. {
  184228. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  184229. {
  184230. png_push_save_buffer(png_ptr);
  184231. return;
  184232. }
  184233. png_handle_cHRM(png_ptr, info_ptr, png_ptr->push_length);
  184234. }
  184235. #endif
  184236. #if defined(PNG_READ_sRGB_SUPPORTED)
  184237. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  184238. {
  184239. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  184240. {
  184241. png_push_save_buffer(png_ptr);
  184242. return;
  184243. }
  184244. png_handle_sRGB(png_ptr, info_ptr, png_ptr->push_length);
  184245. }
  184246. #endif
  184247. #if defined(PNG_READ_iCCP_SUPPORTED)
  184248. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  184249. {
  184250. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  184251. {
  184252. png_push_save_buffer(png_ptr);
  184253. return;
  184254. }
  184255. png_handle_iCCP(png_ptr, info_ptr, png_ptr->push_length);
  184256. }
  184257. #endif
  184258. #if defined(PNG_READ_sPLT_SUPPORTED)
  184259. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  184260. {
  184261. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  184262. {
  184263. png_push_save_buffer(png_ptr);
  184264. return;
  184265. }
  184266. png_handle_sPLT(png_ptr, info_ptr, png_ptr->push_length);
  184267. }
  184268. #endif
  184269. #if defined(PNG_READ_tRNS_SUPPORTED)
  184270. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  184271. {
  184272. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  184273. {
  184274. png_push_save_buffer(png_ptr);
  184275. return;
  184276. }
  184277. png_handle_tRNS(png_ptr, info_ptr, png_ptr->push_length);
  184278. }
  184279. #endif
  184280. #if defined(PNG_READ_bKGD_SUPPORTED)
  184281. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  184282. {
  184283. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  184284. {
  184285. png_push_save_buffer(png_ptr);
  184286. return;
  184287. }
  184288. png_handle_bKGD(png_ptr, info_ptr, png_ptr->push_length);
  184289. }
  184290. #endif
  184291. #if defined(PNG_READ_hIST_SUPPORTED)
  184292. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  184293. {
  184294. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  184295. {
  184296. png_push_save_buffer(png_ptr);
  184297. return;
  184298. }
  184299. png_handle_hIST(png_ptr, info_ptr, png_ptr->push_length);
  184300. }
  184301. #endif
  184302. #if defined(PNG_READ_pHYs_SUPPORTED)
  184303. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  184304. {
  184305. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  184306. {
  184307. png_push_save_buffer(png_ptr);
  184308. return;
  184309. }
  184310. png_handle_pHYs(png_ptr, info_ptr, png_ptr->push_length);
  184311. }
  184312. #endif
  184313. #if defined(PNG_READ_oFFs_SUPPORTED)
  184314. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  184315. {
  184316. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  184317. {
  184318. png_push_save_buffer(png_ptr);
  184319. return;
  184320. }
  184321. png_handle_oFFs(png_ptr, info_ptr, png_ptr->push_length);
  184322. }
  184323. #endif
  184324. #if defined(PNG_READ_pCAL_SUPPORTED)
  184325. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  184326. {
  184327. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  184328. {
  184329. png_push_save_buffer(png_ptr);
  184330. return;
  184331. }
  184332. png_handle_pCAL(png_ptr, info_ptr, png_ptr->push_length);
  184333. }
  184334. #endif
  184335. #if defined(PNG_READ_sCAL_SUPPORTED)
  184336. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  184337. {
  184338. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  184339. {
  184340. png_push_save_buffer(png_ptr);
  184341. return;
  184342. }
  184343. png_handle_sCAL(png_ptr, info_ptr, png_ptr->push_length);
  184344. }
  184345. #endif
  184346. #if defined(PNG_READ_tIME_SUPPORTED)
  184347. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  184348. {
  184349. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  184350. {
  184351. png_push_save_buffer(png_ptr);
  184352. return;
  184353. }
  184354. png_handle_tIME(png_ptr, info_ptr, png_ptr->push_length);
  184355. }
  184356. #endif
  184357. #if defined(PNG_READ_tEXt_SUPPORTED)
  184358. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  184359. {
  184360. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  184361. {
  184362. png_push_save_buffer(png_ptr);
  184363. return;
  184364. }
  184365. png_push_handle_tEXt(png_ptr, info_ptr, png_ptr->push_length);
  184366. }
  184367. #endif
  184368. #if defined(PNG_READ_zTXt_SUPPORTED)
  184369. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  184370. {
  184371. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  184372. {
  184373. png_push_save_buffer(png_ptr);
  184374. return;
  184375. }
  184376. png_push_handle_zTXt(png_ptr, info_ptr, png_ptr->push_length);
  184377. }
  184378. #endif
  184379. #if defined(PNG_READ_iTXt_SUPPORTED)
  184380. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  184381. {
  184382. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  184383. {
  184384. png_push_save_buffer(png_ptr);
  184385. return;
  184386. }
  184387. png_push_handle_iTXt(png_ptr, info_ptr, png_ptr->push_length);
  184388. }
  184389. #endif
  184390. else
  184391. {
  184392. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  184393. {
  184394. png_push_save_buffer(png_ptr);
  184395. return;
  184396. }
  184397. png_push_handle_unknown(png_ptr, info_ptr, png_ptr->push_length);
  184398. }
  184399. png_ptr->mode &= ~PNG_HAVE_CHUNK_HEADER;
  184400. }
  184401. void /* PRIVATE */
  184402. png_push_crc_skip(png_structp png_ptr, png_uint_32 skip)
  184403. {
  184404. png_ptr->process_mode = PNG_SKIP_MODE;
  184405. png_ptr->skip_length = skip;
  184406. }
  184407. void /* PRIVATE */
  184408. png_push_crc_finish(png_structp png_ptr)
  184409. {
  184410. if (png_ptr->skip_length && png_ptr->save_buffer_size)
  184411. {
  184412. png_size_t save_size;
  184413. if (png_ptr->skip_length < (png_uint_32)png_ptr->save_buffer_size)
  184414. save_size = (png_size_t)png_ptr->skip_length;
  184415. else
  184416. save_size = png_ptr->save_buffer_size;
  184417. png_calculate_crc(png_ptr, png_ptr->save_buffer_ptr, save_size);
  184418. png_ptr->skip_length -= save_size;
  184419. png_ptr->buffer_size -= save_size;
  184420. png_ptr->save_buffer_size -= save_size;
  184421. png_ptr->save_buffer_ptr += save_size;
  184422. }
  184423. if (png_ptr->skip_length && png_ptr->current_buffer_size)
  184424. {
  184425. png_size_t save_size;
  184426. if (png_ptr->skip_length < (png_uint_32)png_ptr->current_buffer_size)
  184427. save_size = (png_size_t)png_ptr->skip_length;
  184428. else
  184429. save_size = png_ptr->current_buffer_size;
  184430. png_calculate_crc(png_ptr, png_ptr->current_buffer_ptr, save_size);
  184431. png_ptr->skip_length -= save_size;
  184432. png_ptr->buffer_size -= save_size;
  184433. png_ptr->current_buffer_size -= save_size;
  184434. png_ptr->current_buffer_ptr += save_size;
  184435. }
  184436. if (!png_ptr->skip_length)
  184437. {
  184438. if (png_ptr->buffer_size < 4)
  184439. {
  184440. png_push_save_buffer(png_ptr);
  184441. return;
  184442. }
  184443. png_crc_finish(png_ptr, 0);
  184444. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  184445. }
  184446. }
  184447. void PNGAPI
  184448. png_push_fill_buffer(png_structp png_ptr, png_bytep buffer, png_size_t length)
  184449. {
  184450. png_bytep ptr;
  184451. if(png_ptr == NULL) return;
  184452. ptr = buffer;
  184453. if (png_ptr->save_buffer_size)
  184454. {
  184455. png_size_t save_size;
  184456. if (length < png_ptr->save_buffer_size)
  184457. save_size = length;
  184458. else
  184459. save_size = png_ptr->save_buffer_size;
  184460. png_memcpy(ptr, png_ptr->save_buffer_ptr, save_size);
  184461. length -= save_size;
  184462. ptr += save_size;
  184463. png_ptr->buffer_size -= save_size;
  184464. png_ptr->save_buffer_size -= save_size;
  184465. png_ptr->save_buffer_ptr += save_size;
  184466. }
  184467. if (length && png_ptr->current_buffer_size)
  184468. {
  184469. png_size_t save_size;
  184470. if (length < png_ptr->current_buffer_size)
  184471. save_size = length;
  184472. else
  184473. save_size = png_ptr->current_buffer_size;
  184474. png_memcpy(ptr, png_ptr->current_buffer_ptr, save_size);
  184475. png_ptr->buffer_size -= save_size;
  184476. png_ptr->current_buffer_size -= save_size;
  184477. png_ptr->current_buffer_ptr += save_size;
  184478. }
  184479. }
  184480. void /* PRIVATE */
  184481. png_push_save_buffer(png_structp png_ptr)
  184482. {
  184483. if (png_ptr->save_buffer_size)
  184484. {
  184485. if (png_ptr->save_buffer_ptr != png_ptr->save_buffer)
  184486. {
  184487. png_size_t i,istop;
  184488. png_bytep sp;
  184489. png_bytep dp;
  184490. istop = png_ptr->save_buffer_size;
  184491. for (i = 0, sp = png_ptr->save_buffer_ptr, dp = png_ptr->save_buffer;
  184492. i < istop; i++, sp++, dp++)
  184493. {
  184494. *dp = *sp;
  184495. }
  184496. }
  184497. }
  184498. if (png_ptr->save_buffer_size + png_ptr->current_buffer_size >
  184499. png_ptr->save_buffer_max)
  184500. {
  184501. png_size_t new_max;
  184502. png_bytep old_buffer;
  184503. if (png_ptr->save_buffer_size > PNG_SIZE_MAX -
  184504. (png_ptr->current_buffer_size + 256))
  184505. {
  184506. png_error(png_ptr, "Potential overflow of save_buffer");
  184507. }
  184508. new_max = png_ptr->save_buffer_size + png_ptr->current_buffer_size + 256;
  184509. old_buffer = png_ptr->save_buffer;
  184510. png_ptr->save_buffer = (png_bytep)png_malloc(png_ptr,
  184511. (png_uint_32)new_max);
  184512. png_memcpy(png_ptr->save_buffer, old_buffer, png_ptr->save_buffer_size);
  184513. png_free(png_ptr, old_buffer);
  184514. png_ptr->save_buffer_max = new_max;
  184515. }
  184516. if (png_ptr->current_buffer_size)
  184517. {
  184518. png_memcpy(png_ptr->save_buffer + png_ptr->save_buffer_size,
  184519. png_ptr->current_buffer_ptr, png_ptr->current_buffer_size);
  184520. png_ptr->save_buffer_size += png_ptr->current_buffer_size;
  184521. png_ptr->current_buffer_size = 0;
  184522. }
  184523. png_ptr->save_buffer_ptr = png_ptr->save_buffer;
  184524. png_ptr->buffer_size = 0;
  184525. }
  184526. void /* PRIVATE */
  184527. png_push_restore_buffer(png_structp png_ptr, png_bytep buffer,
  184528. png_size_t buffer_length)
  184529. {
  184530. png_ptr->current_buffer = buffer;
  184531. png_ptr->current_buffer_size = buffer_length;
  184532. png_ptr->buffer_size = buffer_length + png_ptr->save_buffer_size;
  184533. png_ptr->current_buffer_ptr = png_ptr->current_buffer;
  184534. }
  184535. void /* PRIVATE */
  184536. png_push_read_IDAT(png_structp png_ptr)
  184537. {
  184538. #ifdef PNG_USE_LOCAL_ARRAYS
  184539. PNG_CONST PNG_IDAT;
  184540. #endif
  184541. if (!(png_ptr->mode & PNG_HAVE_CHUNK_HEADER))
  184542. {
  184543. png_byte chunk_length[4];
  184544. if (png_ptr->buffer_size < 8)
  184545. {
  184546. png_push_save_buffer(png_ptr);
  184547. return;
  184548. }
  184549. png_push_fill_buffer(png_ptr, chunk_length, 4);
  184550. png_ptr->push_length = png_get_uint_31(png_ptr,chunk_length);
  184551. png_reset_crc(png_ptr);
  184552. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  184553. png_ptr->mode |= PNG_HAVE_CHUNK_HEADER;
  184554. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  184555. {
  184556. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  184557. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  184558. png_error(png_ptr, "Not enough compressed data");
  184559. return;
  184560. }
  184561. png_ptr->idat_size = png_ptr->push_length;
  184562. }
  184563. if (png_ptr->idat_size && png_ptr->save_buffer_size)
  184564. {
  184565. png_size_t save_size;
  184566. if (png_ptr->idat_size < (png_uint_32)png_ptr->save_buffer_size)
  184567. {
  184568. save_size = (png_size_t)png_ptr->idat_size;
  184569. /* check for overflow */
  184570. if((png_uint_32)save_size != png_ptr->idat_size)
  184571. png_error(png_ptr, "save_size overflowed in pngpread");
  184572. }
  184573. else
  184574. save_size = png_ptr->save_buffer_size;
  184575. png_calculate_crc(png_ptr, png_ptr->save_buffer_ptr, save_size);
  184576. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  184577. png_process_IDAT_data(png_ptr, png_ptr->save_buffer_ptr, save_size);
  184578. png_ptr->idat_size -= save_size;
  184579. png_ptr->buffer_size -= save_size;
  184580. png_ptr->save_buffer_size -= save_size;
  184581. png_ptr->save_buffer_ptr += save_size;
  184582. }
  184583. if (png_ptr->idat_size && png_ptr->current_buffer_size)
  184584. {
  184585. png_size_t save_size;
  184586. if (png_ptr->idat_size < (png_uint_32)png_ptr->current_buffer_size)
  184587. {
  184588. save_size = (png_size_t)png_ptr->idat_size;
  184589. /* check for overflow */
  184590. if((png_uint_32)save_size != png_ptr->idat_size)
  184591. png_error(png_ptr, "save_size overflowed in pngpread");
  184592. }
  184593. else
  184594. save_size = png_ptr->current_buffer_size;
  184595. png_calculate_crc(png_ptr, png_ptr->current_buffer_ptr, save_size);
  184596. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  184597. png_process_IDAT_data(png_ptr, png_ptr->current_buffer_ptr, save_size);
  184598. png_ptr->idat_size -= save_size;
  184599. png_ptr->buffer_size -= save_size;
  184600. png_ptr->current_buffer_size -= save_size;
  184601. png_ptr->current_buffer_ptr += save_size;
  184602. }
  184603. if (!png_ptr->idat_size)
  184604. {
  184605. if (png_ptr->buffer_size < 4)
  184606. {
  184607. png_push_save_buffer(png_ptr);
  184608. return;
  184609. }
  184610. png_crc_finish(png_ptr, 0);
  184611. png_ptr->mode &= ~PNG_HAVE_CHUNK_HEADER;
  184612. png_ptr->mode |= PNG_AFTER_IDAT;
  184613. }
  184614. }
  184615. void /* PRIVATE */
  184616. png_process_IDAT_data(png_structp png_ptr, png_bytep buffer,
  184617. png_size_t buffer_length)
  184618. {
  184619. int ret;
  184620. if ((png_ptr->flags & PNG_FLAG_ZLIB_FINISHED) && buffer_length)
  184621. png_error(png_ptr, "Extra compression data");
  184622. png_ptr->zstream.next_in = buffer;
  184623. png_ptr->zstream.avail_in = (uInt)buffer_length;
  184624. for(;;)
  184625. {
  184626. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  184627. if (ret != Z_OK)
  184628. {
  184629. if (ret == Z_STREAM_END)
  184630. {
  184631. if (png_ptr->zstream.avail_in)
  184632. png_error(png_ptr, "Extra compressed data");
  184633. if (!(png_ptr->zstream.avail_out))
  184634. {
  184635. png_push_process_row(png_ptr);
  184636. }
  184637. png_ptr->mode |= PNG_AFTER_IDAT;
  184638. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  184639. break;
  184640. }
  184641. else if (ret == Z_BUF_ERROR)
  184642. break;
  184643. else
  184644. png_error(png_ptr, "Decompression Error");
  184645. }
  184646. if (!(png_ptr->zstream.avail_out))
  184647. {
  184648. if ((
  184649. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  184650. png_ptr->interlaced && png_ptr->pass > 6) ||
  184651. (!png_ptr->interlaced &&
  184652. #endif
  184653. png_ptr->row_number == png_ptr->num_rows))
  184654. {
  184655. if (png_ptr->zstream.avail_in)
  184656. {
  184657. png_warning(png_ptr, "Too much data in IDAT chunks");
  184658. }
  184659. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  184660. break;
  184661. }
  184662. png_push_process_row(png_ptr);
  184663. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  184664. png_ptr->zstream.next_out = png_ptr->row_buf;
  184665. }
  184666. else
  184667. break;
  184668. }
  184669. }
  184670. void /* PRIVATE */
  184671. png_push_process_row(png_structp png_ptr)
  184672. {
  184673. png_ptr->row_info.color_type = png_ptr->color_type;
  184674. png_ptr->row_info.width = png_ptr->iwidth;
  184675. png_ptr->row_info.channels = png_ptr->channels;
  184676. png_ptr->row_info.bit_depth = png_ptr->bit_depth;
  184677. png_ptr->row_info.pixel_depth = png_ptr->pixel_depth;
  184678. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  184679. png_ptr->row_info.width);
  184680. png_read_filter_row(png_ptr, &(png_ptr->row_info),
  184681. png_ptr->row_buf + 1, png_ptr->prev_row + 1,
  184682. (int)(png_ptr->row_buf[0]));
  184683. png_memcpy_check(png_ptr, png_ptr->prev_row, png_ptr->row_buf,
  184684. png_ptr->rowbytes + 1);
  184685. if (png_ptr->transformations || (png_ptr->flags&PNG_FLAG_STRIP_ALPHA))
  184686. png_do_read_transformations(png_ptr);
  184687. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  184688. /* blow up interlaced rows to full size */
  184689. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  184690. {
  184691. if (png_ptr->pass < 6)
  184692. /* old interface (pre-1.0.9):
  184693. png_do_read_interlace(&(png_ptr->row_info),
  184694. png_ptr->row_buf + 1, png_ptr->pass, png_ptr->transformations);
  184695. */
  184696. png_do_read_interlace(png_ptr);
  184697. switch (png_ptr->pass)
  184698. {
  184699. case 0:
  184700. {
  184701. int i;
  184702. for (i = 0; i < 8 && png_ptr->pass == 0; i++)
  184703. {
  184704. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  184705. png_read_push_finish_row(png_ptr); /* updates png_ptr->pass */
  184706. }
  184707. if (png_ptr->pass == 2) /* pass 1 might be empty */
  184708. {
  184709. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  184710. {
  184711. png_push_have_row(png_ptr, png_bytep_NULL);
  184712. png_read_push_finish_row(png_ptr);
  184713. }
  184714. }
  184715. if (png_ptr->pass == 4 && png_ptr->height <= 4)
  184716. {
  184717. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  184718. {
  184719. png_push_have_row(png_ptr, png_bytep_NULL);
  184720. png_read_push_finish_row(png_ptr);
  184721. }
  184722. }
  184723. if (png_ptr->pass == 6 && png_ptr->height <= 4)
  184724. {
  184725. png_push_have_row(png_ptr, png_bytep_NULL);
  184726. png_read_push_finish_row(png_ptr);
  184727. }
  184728. break;
  184729. }
  184730. case 1:
  184731. {
  184732. int i;
  184733. for (i = 0; i < 8 && png_ptr->pass == 1; i++)
  184734. {
  184735. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  184736. png_read_push_finish_row(png_ptr);
  184737. }
  184738. if (png_ptr->pass == 2) /* skip top 4 generated rows */
  184739. {
  184740. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  184741. {
  184742. png_push_have_row(png_ptr, png_bytep_NULL);
  184743. png_read_push_finish_row(png_ptr);
  184744. }
  184745. }
  184746. break;
  184747. }
  184748. case 2:
  184749. {
  184750. int i;
  184751. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  184752. {
  184753. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  184754. png_read_push_finish_row(png_ptr);
  184755. }
  184756. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  184757. {
  184758. png_push_have_row(png_ptr, png_bytep_NULL);
  184759. png_read_push_finish_row(png_ptr);
  184760. }
  184761. if (png_ptr->pass == 4) /* pass 3 might be empty */
  184762. {
  184763. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  184764. {
  184765. png_push_have_row(png_ptr, png_bytep_NULL);
  184766. png_read_push_finish_row(png_ptr);
  184767. }
  184768. }
  184769. break;
  184770. }
  184771. case 3:
  184772. {
  184773. int i;
  184774. for (i = 0; i < 4 && png_ptr->pass == 3; i++)
  184775. {
  184776. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  184777. png_read_push_finish_row(png_ptr);
  184778. }
  184779. if (png_ptr->pass == 4) /* skip top two generated rows */
  184780. {
  184781. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  184782. {
  184783. png_push_have_row(png_ptr, png_bytep_NULL);
  184784. png_read_push_finish_row(png_ptr);
  184785. }
  184786. }
  184787. break;
  184788. }
  184789. case 4:
  184790. {
  184791. int i;
  184792. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  184793. {
  184794. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  184795. png_read_push_finish_row(png_ptr);
  184796. }
  184797. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  184798. {
  184799. png_push_have_row(png_ptr, png_bytep_NULL);
  184800. png_read_push_finish_row(png_ptr);
  184801. }
  184802. if (png_ptr->pass == 6) /* pass 5 might be empty */
  184803. {
  184804. png_push_have_row(png_ptr, png_bytep_NULL);
  184805. png_read_push_finish_row(png_ptr);
  184806. }
  184807. break;
  184808. }
  184809. case 5:
  184810. {
  184811. int i;
  184812. for (i = 0; i < 2 && png_ptr->pass == 5; i++)
  184813. {
  184814. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  184815. png_read_push_finish_row(png_ptr);
  184816. }
  184817. if (png_ptr->pass == 6) /* skip top generated row */
  184818. {
  184819. png_push_have_row(png_ptr, png_bytep_NULL);
  184820. png_read_push_finish_row(png_ptr);
  184821. }
  184822. break;
  184823. }
  184824. case 6:
  184825. {
  184826. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  184827. png_read_push_finish_row(png_ptr);
  184828. if (png_ptr->pass != 6)
  184829. break;
  184830. png_push_have_row(png_ptr, png_bytep_NULL);
  184831. png_read_push_finish_row(png_ptr);
  184832. }
  184833. }
  184834. }
  184835. else
  184836. #endif
  184837. {
  184838. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  184839. png_read_push_finish_row(png_ptr);
  184840. }
  184841. }
  184842. void /* PRIVATE */
  184843. png_read_push_finish_row(png_structp png_ptr)
  184844. {
  184845. #ifdef PNG_USE_LOCAL_ARRAYS
  184846. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  184847. /* start of interlace block */
  184848. PNG_CONST int FARDATA png_pass_start[] = {0, 4, 0, 2, 0, 1, 0};
  184849. /* offset to next interlace block */
  184850. PNG_CONST int FARDATA png_pass_inc[] = {8, 8, 4, 4, 2, 2, 1};
  184851. /* start of interlace block in the y direction */
  184852. PNG_CONST int FARDATA png_pass_ystart[] = {0, 0, 4, 0, 2, 0, 1};
  184853. /* offset to next interlace block in the y direction */
  184854. PNG_CONST int FARDATA png_pass_yinc[] = {8, 8, 8, 4, 4, 2, 2};
  184855. /* Height of interlace block. This is not currently used - if you need
  184856. * it, uncomment it here and in png.h
  184857. PNG_CONST int FARDATA png_pass_height[] = {8, 8, 4, 4, 2, 2, 1};
  184858. */
  184859. #endif
  184860. png_ptr->row_number++;
  184861. if (png_ptr->row_number < png_ptr->num_rows)
  184862. return;
  184863. if (png_ptr->interlaced)
  184864. {
  184865. png_ptr->row_number = 0;
  184866. png_memset_check(png_ptr, png_ptr->prev_row, 0,
  184867. png_ptr->rowbytes + 1);
  184868. do
  184869. {
  184870. png_ptr->pass++;
  184871. if ((png_ptr->pass == 1 && png_ptr->width < 5) ||
  184872. (png_ptr->pass == 3 && png_ptr->width < 3) ||
  184873. (png_ptr->pass == 5 && png_ptr->width < 2))
  184874. png_ptr->pass++;
  184875. if (png_ptr->pass > 7)
  184876. png_ptr->pass--;
  184877. if (png_ptr->pass >= 7)
  184878. break;
  184879. png_ptr->iwidth = (png_ptr->width +
  184880. png_pass_inc[png_ptr->pass] - 1 -
  184881. png_pass_start[png_ptr->pass]) /
  184882. png_pass_inc[png_ptr->pass];
  184883. png_ptr->irowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,
  184884. png_ptr->iwidth) + 1;
  184885. if (png_ptr->transformations & PNG_INTERLACE)
  184886. break;
  184887. png_ptr->num_rows = (png_ptr->height +
  184888. png_pass_yinc[png_ptr->pass] - 1 -
  184889. png_pass_ystart[png_ptr->pass]) /
  184890. png_pass_yinc[png_ptr->pass];
  184891. } while (png_ptr->iwidth == 0 || png_ptr->num_rows == 0);
  184892. }
  184893. }
  184894. #if defined(PNG_READ_tEXt_SUPPORTED)
  184895. void /* PRIVATE */
  184896. png_push_handle_tEXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  184897. length)
  184898. {
  184899. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  184900. {
  184901. png_error(png_ptr, "Out of place tEXt");
  184902. info_ptr = info_ptr; /* to quiet some compiler warnings */
  184903. }
  184904. #ifdef PNG_MAX_MALLOC_64K
  184905. png_ptr->skip_length = 0; /* This may not be necessary */
  184906. if (length > (png_uint_32)65535L) /* Can't hold entire string in memory */
  184907. {
  184908. png_warning(png_ptr, "tEXt chunk too large to fit in memory");
  184909. png_ptr->skip_length = length - (png_uint_32)65535L;
  184910. length = (png_uint_32)65535L;
  184911. }
  184912. #endif
  184913. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  184914. (png_uint_32)(length+1));
  184915. png_ptr->current_text[length] = '\0';
  184916. png_ptr->current_text_ptr = png_ptr->current_text;
  184917. png_ptr->current_text_size = (png_size_t)length;
  184918. png_ptr->current_text_left = (png_size_t)length;
  184919. png_ptr->process_mode = PNG_READ_tEXt_MODE;
  184920. }
  184921. void /* PRIVATE */
  184922. png_push_read_tEXt(png_structp png_ptr, png_infop info_ptr)
  184923. {
  184924. if (png_ptr->buffer_size && png_ptr->current_text_left)
  184925. {
  184926. png_size_t text_size;
  184927. if (png_ptr->buffer_size < png_ptr->current_text_left)
  184928. text_size = png_ptr->buffer_size;
  184929. else
  184930. text_size = png_ptr->current_text_left;
  184931. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  184932. png_ptr->current_text_left -= text_size;
  184933. png_ptr->current_text_ptr += text_size;
  184934. }
  184935. if (!(png_ptr->current_text_left))
  184936. {
  184937. png_textp text_ptr;
  184938. png_charp text;
  184939. png_charp key;
  184940. int ret;
  184941. if (png_ptr->buffer_size < 4)
  184942. {
  184943. png_push_save_buffer(png_ptr);
  184944. return;
  184945. }
  184946. png_push_crc_finish(png_ptr);
  184947. #if defined(PNG_MAX_MALLOC_64K)
  184948. if (png_ptr->skip_length)
  184949. return;
  184950. #endif
  184951. key = png_ptr->current_text;
  184952. for (text = key; *text; text++)
  184953. /* empty loop */ ;
  184954. if (text < key + png_ptr->current_text_size)
  184955. text++;
  184956. text_ptr = (png_textp)png_malloc(png_ptr,
  184957. (png_uint_32)png_sizeof(png_text));
  184958. text_ptr->compression = PNG_TEXT_COMPRESSION_NONE;
  184959. text_ptr->key = key;
  184960. #ifdef PNG_iTXt_SUPPORTED
  184961. text_ptr->lang = NULL;
  184962. text_ptr->lang_key = NULL;
  184963. #endif
  184964. text_ptr->text = text;
  184965. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  184966. png_free(png_ptr, key);
  184967. png_free(png_ptr, text_ptr);
  184968. png_ptr->current_text = NULL;
  184969. if (ret)
  184970. png_warning(png_ptr, "Insufficient memory to store text chunk.");
  184971. }
  184972. }
  184973. #endif
  184974. #if defined(PNG_READ_zTXt_SUPPORTED)
  184975. void /* PRIVATE */
  184976. png_push_handle_zTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  184977. length)
  184978. {
  184979. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  184980. {
  184981. png_error(png_ptr, "Out of place zTXt");
  184982. info_ptr = info_ptr; /* to quiet some compiler warnings */
  184983. }
  184984. #ifdef PNG_MAX_MALLOC_64K
  184985. /* We can't handle zTXt chunks > 64K, since we don't have enough space
  184986. * to be able to store the uncompressed data. Actually, the threshold
  184987. * is probably around 32K, but it isn't as definite as 64K is.
  184988. */
  184989. if (length > (png_uint_32)65535L)
  184990. {
  184991. png_warning(png_ptr, "zTXt chunk too large to fit in memory");
  184992. png_push_crc_skip(png_ptr, length);
  184993. return;
  184994. }
  184995. #endif
  184996. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  184997. (png_uint_32)(length+1));
  184998. png_ptr->current_text[length] = '\0';
  184999. png_ptr->current_text_ptr = png_ptr->current_text;
  185000. png_ptr->current_text_size = (png_size_t)length;
  185001. png_ptr->current_text_left = (png_size_t)length;
  185002. png_ptr->process_mode = PNG_READ_zTXt_MODE;
  185003. }
  185004. void /* PRIVATE */
  185005. png_push_read_zTXt(png_structp png_ptr, png_infop info_ptr)
  185006. {
  185007. if (png_ptr->buffer_size && png_ptr->current_text_left)
  185008. {
  185009. png_size_t text_size;
  185010. if (png_ptr->buffer_size < (png_uint_32)png_ptr->current_text_left)
  185011. text_size = png_ptr->buffer_size;
  185012. else
  185013. text_size = png_ptr->current_text_left;
  185014. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  185015. png_ptr->current_text_left -= text_size;
  185016. png_ptr->current_text_ptr += text_size;
  185017. }
  185018. if (!(png_ptr->current_text_left))
  185019. {
  185020. png_textp text_ptr;
  185021. png_charp text;
  185022. png_charp key;
  185023. int ret;
  185024. png_size_t text_size, key_size;
  185025. if (png_ptr->buffer_size < 4)
  185026. {
  185027. png_push_save_buffer(png_ptr);
  185028. return;
  185029. }
  185030. png_push_crc_finish(png_ptr);
  185031. key = png_ptr->current_text;
  185032. for (text = key; *text; text++)
  185033. /* empty loop */ ;
  185034. /* zTXt can't have zero text */
  185035. if (text >= key + png_ptr->current_text_size)
  185036. {
  185037. png_ptr->current_text = NULL;
  185038. png_free(png_ptr, key);
  185039. return;
  185040. }
  185041. text++;
  185042. if (*text != PNG_TEXT_COMPRESSION_zTXt) /* check compression byte */
  185043. {
  185044. png_ptr->current_text = NULL;
  185045. png_free(png_ptr, key);
  185046. return;
  185047. }
  185048. text++;
  185049. png_ptr->zstream.next_in = (png_bytep )text;
  185050. png_ptr->zstream.avail_in = (uInt)(png_ptr->current_text_size -
  185051. (text - key));
  185052. png_ptr->zstream.next_out = png_ptr->zbuf;
  185053. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  185054. key_size = text - key;
  185055. text_size = 0;
  185056. text = NULL;
  185057. ret = Z_STREAM_END;
  185058. while (png_ptr->zstream.avail_in)
  185059. {
  185060. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  185061. if (ret != Z_OK && ret != Z_STREAM_END)
  185062. {
  185063. inflateReset(&png_ptr->zstream);
  185064. png_ptr->zstream.avail_in = 0;
  185065. png_ptr->current_text = NULL;
  185066. png_free(png_ptr, key);
  185067. png_free(png_ptr, text);
  185068. return;
  185069. }
  185070. if (!(png_ptr->zstream.avail_out) || ret == Z_STREAM_END)
  185071. {
  185072. if (text == NULL)
  185073. {
  185074. text = (png_charp)png_malloc(png_ptr,
  185075. (png_uint_32)(png_ptr->zbuf_size - png_ptr->zstream.avail_out
  185076. + key_size + 1));
  185077. png_memcpy(text + key_size, png_ptr->zbuf,
  185078. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  185079. png_memcpy(text, key, key_size);
  185080. text_size = key_size + png_ptr->zbuf_size -
  185081. png_ptr->zstream.avail_out;
  185082. *(text + text_size) = '\0';
  185083. }
  185084. else
  185085. {
  185086. png_charp tmp;
  185087. tmp = text;
  185088. text = (png_charp)png_malloc(png_ptr, text_size +
  185089. (png_uint_32)(png_ptr->zbuf_size - png_ptr->zstream.avail_out
  185090. + 1));
  185091. png_memcpy(text, tmp, text_size);
  185092. png_free(png_ptr, tmp);
  185093. png_memcpy(text + text_size, png_ptr->zbuf,
  185094. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  185095. text_size += png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  185096. *(text + text_size) = '\0';
  185097. }
  185098. if (ret != Z_STREAM_END)
  185099. {
  185100. png_ptr->zstream.next_out = png_ptr->zbuf;
  185101. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  185102. }
  185103. }
  185104. else
  185105. {
  185106. break;
  185107. }
  185108. if (ret == Z_STREAM_END)
  185109. break;
  185110. }
  185111. inflateReset(&png_ptr->zstream);
  185112. png_ptr->zstream.avail_in = 0;
  185113. if (ret != Z_STREAM_END)
  185114. {
  185115. png_ptr->current_text = NULL;
  185116. png_free(png_ptr, key);
  185117. png_free(png_ptr, text);
  185118. return;
  185119. }
  185120. png_ptr->current_text = NULL;
  185121. png_free(png_ptr, key);
  185122. key = text;
  185123. text += key_size;
  185124. text_ptr = (png_textp)png_malloc(png_ptr,
  185125. (png_uint_32)png_sizeof(png_text));
  185126. text_ptr->compression = PNG_TEXT_COMPRESSION_zTXt;
  185127. text_ptr->key = key;
  185128. #ifdef PNG_iTXt_SUPPORTED
  185129. text_ptr->lang = NULL;
  185130. text_ptr->lang_key = NULL;
  185131. #endif
  185132. text_ptr->text = text;
  185133. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  185134. png_free(png_ptr, key);
  185135. png_free(png_ptr, text_ptr);
  185136. if (ret)
  185137. png_warning(png_ptr, "Insufficient memory to store text chunk.");
  185138. }
  185139. }
  185140. #endif
  185141. #if defined(PNG_READ_iTXt_SUPPORTED)
  185142. void /* PRIVATE */
  185143. png_push_handle_iTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  185144. length)
  185145. {
  185146. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  185147. {
  185148. png_error(png_ptr, "Out of place iTXt");
  185149. info_ptr = info_ptr; /* to quiet some compiler warnings */
  185150. }
  185151. #ifdef PNG_MAX_MALLOC_64K
  185152. png_ptr->skip_length = 0; /* This may not be necessary */
  185153. if (length > (png_uint_32)65535L) /* Can't hold entire string in memory */
  185154. {
  185155. png_warning(png_ptr, "iTXt chunk too large to fit in memory");
  185156. png_ptr->skip_length = length - (png_uint_32)65535L;
  185157. length = (png_uint_32)65535L;
  185158. }
  185159. #endif
  185160. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  185161. (png_uint_32)(length+1));
  185162. png_ptr->current_text[length] = '\0';
  185163. png_ptr->current_text_ptr = png_ptr->current_text;
  185164. png_ptr->current_text_size = (png_size_t)length;
  185165. png_ptr->current_text_left = (png_size_t)length;
  185166. png_ptr->process_mode = PNG_READ_iTXt_MODE;
  185167. }
  185168. void /* PRIVATE */
  185169. png_push_read_iTXt(png_structp png_ptr, png_infop info_ptr)
  185170. {
  185171. if (png_ptr->buffer_size && png_ptr->current_text_left)
  185172. {
  185173. png_size_t text_size;
  185174. if (png_ptr->buffer_size < png_ptr->current_text_left)
  185175. text_size = png_ptr->buffer_size;
  185176. else
  185177. text_size = png_ptr->current_text_left;
  185178. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  185179. png_ptr->current_text_left -= text_size;
  185180. png_ptr->current_text_ptr += text_size;
  185181. }
  185182. if (!(png_ptr->current_text_left))
  185183. {
  185184. png_textp text_ptr;
  185185. png_charp key;
  185186. int comp_flag;
  185187. png_charp lang;
  185188. png_charp lang_key;
  185189. png_charp text;
  185190. int ret;
  185191. if (png_ptr->buffer_size < 4)
  185192. {
  185193. png_push_save_buffer(png_ptr);
  185194. return;
  185195. }
  185196. png_push_crc_finish(png_ptr);
  185197. #if defined(PNG_MAX_MALLOC_64K)
  185198. if (png_ptr->skip_length)
  185199. return;
  185200. #endif
  185201. key = png_ptr->current_text;
  185202. for (lang = key; *lang; lang++)
  185203. /* empty loop */ ;
  185204. if (lang < key + png_ptr->current_text_size - 3)
  185205. lang++;
  185206. comp_flag = *lang++;
  185207. lang++; /* skip comp_type, always zero */
  185208. for (lang_key = lang; *lang_key; lang_key++)
  185209. /* empty loop */ ;
  185210. lang_key++; /* skip NUL separator */
  185211. text=lang_key;
  185212. if (lang_key < key + png_ptr->current_text_size - 1)
  185213. {
  185214. for (; *text; text++)
  185215. /* empty loop */ ;
  185216. }
  185217. if (text < key + png_ptr->current_text_size)
  185218. text++;
  185219. text_ptr = (png_textp)png_malloc(png_ptr,
  185220. (png_uint_32)png_sizeof(png_text));
  185221. text_ptr->compression = comp_flag + 2;
  185222. text_ptr->key = key;
  185223. text_ptr->lang = lang;
  185224. text_ptr->lang_key = lang_key;
  185225. text_ptr->text = text;
  185226. text_ptr->text_length = 0;
  185227. text_ptr->itxt_length = png_strlen(text);
  185228. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  185229. png_ptr->current_text = NULL;
  185230. png_free(png_ptr, text_ptr);
  185231. if (ret)
  185232. png_warning(png_ptr, "Insufficient memory to store iTXt chunk.");
  185233. }
  185234. }
  185235. #endif
  185236. /* This function is called when we haven't found a handler for this
  185237. * chunk. If there isn't a problem with the chunk itself (ie a bad chunk
  185238. * name or a critical chunk), the chunk is (currently) silently ignored.
  185239. */
  185240. void /* PRIVATE */
  185241. png_push_handle_unknown(png_structp png_ptr, png_infop info_ptr, png_uint_32
  185242. length)
  185243. {
  185244. png_uint_32 skip=0;
  185245. png_check_chunk_name(png_ptr, png_ptr->chunk_name);
  185246. if (!(png_ptr->chunk_name[0] & 0x20))
  185247. {
  185248. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  185249. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  185250. PNG_HANDLE_CHUNK_ALWAYS
  185251. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  185252. && png_ptr->read_user_chunk_fn == NULL
  185253. #endif
  185254. )
  185255. #endif
  185256. png_chunk_error(png_ptr, "unknown critical chunk");
  185257. info_ptr = info_ptr; /* to quiet some compiler warnings */
  185258. }
  185259. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  185260. if (png_ptr->flags & PNG_FLAG_KEEP_UNKNOWN_CHUNKS)
  185261. {
  185262. #ifdef PNG_MAX_MALLOC_64K
  185263. if (length > (png_uint_32)65535L)
  185264. {
  185265. png_warning(png_ptr, "unknown chunk too large to fit in memory");
  185266. skip = length - (png_uint_32)65535L;
  185267. length = (png_uint_32)65535L;
  185268. }
  185269. #endif
  185270. png_strncpy((png_charp)png_ptr->unknown_chunk.name,
  185271. (png_charp)png_ptr->chunk_name, 5);
  185272. png_ptr->unknown_chunk.data = (png_bytep)png_malloc(png_ptr, length);
  185273. png_ptr->unknown_chunk.size = (png_size_t)length;
  185274. png_crc_read(png_ptr, (png_bytep)png_ptr->unknown_chunk.data, length);
  185275. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  185276. if(png_ptr->read_user_chunk_fn != NULL)
  185277. {
  185278. /* callback to user unknown chunk handler */
  185279. int ret;
  185280. ret = (*(png_ptr->read_user_chunk_fn))
  185281. (png_ptr, &png_ptr->unknown_chunk);
  185282. if (ret < 0)
  185283. png_chunk_error(png_ptr, "error in user chunk");
  185284. if (ret == 0)
  185285. {
  185286. if (!(png_ptr->chunk_name[0] & 0x20))
  185287. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  185288. PNG_HANDLE_CHUNK_ALWAYS)
  185289. png_chunk_error(png_ptr, "unknown critical chunk");
  185290. png_set_unknown_chunks(png_ptr, info_ptr,
  185291. &png_ptr->unknown_chunk, 1);
  185292. }
  185293. }
  185294. #else
  185295. png_set_unknown_chunks(png_ptr, info_ptr, &png_ptr->unknown_chunk, 1);
  185296. #endif
  185297. png_free(png_ptr, png_ptr->unknown_chunk.data);
  185298. png_ptr->unknown_chunk.data = NULL;
  185299. }
  185300. else
  185301. #endif
  185302. skip=length;
  185303. png_push_crc_skip(png_ptr, skip);
  185304. }
  185305. void /* PRIVATE */
  185306. png_push_have_info(png_structp png_ptr, png_infop info_ptr)
  185307. {
  185308. if (png_ptr->info_fn != NULL)
  185309. (*(png_ptr->info_fn))(png_ptr, info_ptr);
  185310. }
  185311. void /* PRIVATE */
  185312. png_push_have_end(png_structp png_ptr, png_infop info_ptr)
  185313. {
  185314. if (png_ptr->end_fn != NULL)
  185315. (*(png_ptr->end_fn))(png_ptr, info_ptr);
  185316. }
  185317. void /* PRIVATE */
  185318. png_push_have_row(png_structp png_ptr, png_bytep row)
  185319. {
  185320. if (png_ptr->row_fn != NULL)
  185321. (*(png_ptr->row_fn))(png_ptr, row, png_ptr->row_number,
  185322. (int)png_ptr->pass);
  185323. }
  185324. void PNGAPI
  185325. png_progressive_combine_row (png_structp png_ptr,
  185326. png_bytep old_row, png_bytep new_row)
  185327. {
  185328. #ifdef PNG_USE_LOCAL_ARRAYS
  185329. PNG_CONST int FARDATA png_pass_dsp_mask[7] =
  185330. {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55, 0xff};
  185331. #endif
  185332. if(png_ptr == NULL) return;
  185333. if (new_row != NULL) /* new_row must == png_ptr->row_buf here. */
  185334. png_combine_row(png_ptr, old_row, png_pass_dsp_mask[png_ptr->pass]);
  185335. }
  185336. void PNGAPI
  185337. png_set_progressive_read_fn(png_structp png_ptr, png_voidp progressive_ptr,
  185338. png_progressive_info_ptr info_fn, png_progressive_row_ptr row_fn,
  185339. png_progressive_end_ptr end_fn)
  185340. {
  185341. if(png_ptr == NULL) return;
  185342. png_ptr->info_fn = info_fn;
  185343. png_ptr->row_fn = row_fn;
  185344. png_ptr->end_fn = end_fn;
  185345. png_set_read_fn(png_ptr, progressive_ptr, png_push_fill_buffer);
  185346. }
  185347. png_voidp PNGAPI
  185348. png_get_progressive_ptr(png_structp png_ptr)
  185349. {
  185350. if(png_ptr == NULL) return (NULL);
  185351. return png_ptr->io_ptr;
  185352. }
  185353. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  185354. /********* End of inlined file: pngpread.c *********/
  185355. /********* Start of inlined file: pngrio.c *********/
  185356. /* pngrio.c - functions for data input
  185357. *
  185358. * Last changed in libpng 1.2.13 November 13, 2006
  185359. * For conditions of distribution and use, see copyright notice in png.h
  185360. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  185361. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  185362. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  185363. *
  185364. * This file provides a location for all input. Users who need
  185365. * special handling are expected to write a function that has the same
  185366. * arguments as this and performs a similar function, but that possibly
  185367. * has a different input method. Note that you shouldn't change this
  185368. * function, but rather write a replacement function and then make
  185369. * libpng use it at run time with png_set_read_fn(...).
  185370. */
  185371. #define PNG_INTERNAL
  185372. #if defined(PNG_READ_SUPPORTED)
  185373. /* Read the data from whatever input you are using. The default routine
  185374. reads from a file pointer. Note that this routine sometimes gets called
  185375. with very small lengths, so you should implement some kind of simple
  185376. buffering if you are using unbuffered reads. This should never be asked
  185377. to read more then 64K on a 16 bit machine. */
  185378. void /* PRIVATE */
  185379. png_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  185380. {
  185381. png_debug1(4,"reading %d bytes\n", (int)length);
  185382. if (png_ptr->read_data_fn != NULL)
  185383. (*(png_ptr->read_data_fn))(png_ptr, data, length);
  185384. else
  185385. png_error(png_ptr, "Call to NULL read function");
  185386. }
  185387. #if !defined(PNG_NO_STDIO)
  185388. /* This is the function that does the actual reading of data. If you are
  185389. not reading from a standard C stream, you should create a replacement
  185390. read_data function and use it at run time with png_set_read_fn(), rather
  185391. than changing the library. */
  185392. #ifndef USE_FAR_KEYWORD
  185393. void PNGAPI
  185394. png_default_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  185395. {
  185396. png_size_t check;
  185397. if(png_ptr == NULL) return;
  185398. /* fread() returns 0 on error, so it is OK to store this in a png_size_t
  185399. * instead of an int, which is what fread() actually returns.
  185400. */
  185401. #if defined(_WIN32_WCE)
  185402. if ( !ReadFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  185403. check = 0;
  185404. #else
  185405. check = (png_size_t)fread(data, (png_size_t)1, length,
  185406. (png_FILE_p)png_ptr->io_ptr);
  185407. #endif
  185408. if (check != length)
  185409. png_error(png_ptr, "Read Error");
  185410. }
  185411. #else
  185412. /* this is the model-independent version. Since the standard I/O library
  185413. can't handle far buffers in the medium and small models, we have to copy
  185414. the data.
  185415. */
  185416. #define NEAR_BUF_SIZE 1024
  185417. #define MIN(a,b) (a <= b ? a : b)
  185418. static void PNGAPI
  185419. png_default_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  185420. {
  185421. int check;
  185422. png_byte *n_data;
  185423. png_FILE_p io_ptr;
  185424. if(png_ptr == NULL) return;
  185425. /* Check if data really is near. If so, use usual code. */
  185426. n_data = (png_byte *)CVT_PTR_NOCHECK(data);
  185427. io_ptr = (png_FILE_p)CVT_PTR(png_ptr->io_ptr);
  185428. if ((png_bytep)n_data == data)
  185429. {
  185430. #if defined(_WIN32_WCE)
  185431. if ( !ReadFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  185432. check = 0;
  185433. #else
  185434. check = fread(n_data, 1, length, io_ptr);
  185435. #endif
  185436. }
  185437. else
  185438. {
  185439. png_byte buf[NEAR_BUF_SIZE];
  185440. png_size_t read, remaining, err;
  185441. check = 0;
  185442. remaining = length;
  185443. do
  185444. {
  185445. read = MIN(NEAR_BUF_SIZE, remaining);
  185446. #if defined(_WIN32_WCE)
  185447. if ( !ReadFile((HANDLE)(io_ptr), buf, read, &err, NULL) )
  185448. err = 0;
  185449. #else
  185450. err = fread(buf, (png_size_t)1, read, io_ptr);
  185451. #endif
  185452. png_memcpy(data, buf, read); /* copy far buffer to near buffer */
  185453. if(err != read)
  185454. break;
  185455. else
  185456. check += err;
  185457. data += read;
  185458. remaining -= read;
  185459. }
  185460. while (remaining != 0);
  185461. }
  185462. if ((png_uint_32)check != (png_uint_32)length)
  185463. png_error(png_ptr, "read Error");
  185464. }
  185465. #endif
  185466. #endif
  185467. /* This function allows the application to supply a new input function
  185468. for libpng if standard C streams aren't being used.
  185469. This function takes as its arguments:
  185470. png_ptr - pointer to a png input data structure
  185471. io_ptr - pointer to user supplied structure containing info about
  185472. the input functions. May be NULL.
  185473. read_data_fn - pointer to a new input function that takes as its
  185474. arguments a pointer to a png_struct, a pointer to
  185475. a location where input data can be stored, and a 32-bit
  185476. unsigned int that is the number of bytes to be read.
  185477. To exit and output any fatal error messages the new write
  185478. function should call png_error(png_ptr, "Error msg"). */
  185479. void PNGAPI
  185480. png_set_read_fn(png_structp png_ptr, png_voidp io_ptr,
  185481. png_rw_ptr read_data_fn)
  185482. {
  185483. if(png_ptr == NULL) return;
  185484. png_ptr->io_ptr = io_ptr;
  185485. #if !defined(PNG_NO_STDIO)
  185486. if (read_data_fn != NULL)
  185487. png_ptr->read_data_fn = read_data_fn;
  185488. else
  185489. png_ptr->read_data_fn = png_default_read_data;
  185490. #else
  185491. png_ptr->read_data_fn = read_data_fn;
  185492. #endif
  185493. /* It is an error to write to a read device */
  185494. if (png_ptr->write_data_fn != NULL)
  185495. {
  185496. png_ptr->write_data_fn = NULL;
  185497. png_warning(png_ptr,
  185498. "It's an error to set both read_data_fn and write_data_fn in the ");
  185499. png_warning(png_ptr,
  185500. "same structure. Resetting write_data_fn to NULL.");
  185501. }
  185502. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  185503. png_ptr->output_flush_fn = NULL;
  185504. #endif
  185505. }
  185506. #endif /* PNG_READ_SUPPORTED */
  185507. /********* End of inlined file: pngrio.c *********/
  185508. /********* Start of inlined file: pngrtran.c *********/
  185509. /* pngrtran.c - transforms the data in a row for PNG readers
  185510. *
  185511. * Last changed in libpng 1.2.21 [October 4, 2007]
  185512. * For conditions of distribution and use, see copyright notice in png.h
  185513. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  185514. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  185515. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  185516. *
  185517. * This file contains functions optionally called by an application
  185518. * in order to tell libpng how to handle data when reading a PNG.
  185519. * Transformations that are used in both reading and writing are
  185520. * in pngtrans.c.
  185521. */
  185522. #define PNG_INTERNAL
  185523. #if defined(PNG_READ_SUPPORTED)
  185524. /* Set the action on getting a CRC error for an ancillary or critical chunk. */
  185525. void PNGAPI
  185526. png_set_crc_action(png_structp png_ptr, int crit_action, int ancil_action)
  185527. {
  185528. png_debug(1, "in png_set_crc_action\n");
  185529. /* Tell libpng how we react to CRC errors in critical chunks */
  185530. if(png_ptr == NULL) return;
  185531. switch (crit_action)
  185532. {
  185533. case PNG_CRC_NO_CHANGE: /* leave setting as is */
  185534. break;
  185535. case PNG_CRC_WARN_USE: /* warn/use data */
  185536. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  185537. png_ptr->flags |= PNG_FLAG_CRC_CRITICAL_USE;
  185538. break;
  185539. case PNG_CRC_QUIET_USE: /* quiet/use data */
  185540. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  185541. png_ptr->flags |= PNG_FLAG_CRC_CRITICAL_USE |
  185542. PNG_FLAG_CRC_CRITICAL_IGNORE;
  185543. break;
  185544. case PNG_CRC_WARN_DISCARD: /* not a valid action for critical data */
  185545. png_warning(png_ptr, "Can't discard critical data on CRC error.");
  185546. case PNG_CRC_ERROR_QUIT: /* error/quit */
  185547. case PNG_CRC_DEFAULT:
  185548. default:
  185549. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  185550. break;
  185551. }
  185552. switch (ancil_action)
  185553. {
  185554. case PNG_CRC_NO_CHANGE: /* leave setting as is */
  185555. break;
  185556. case PNG_CRC_WARN_USE: /* warn/use data */
  185557. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  185558. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_USE;
  185559. break;
  185560. case PNG_CRC_QUIET_USE: /* quiet/use data */
  185561. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  185562. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_USE |
  185563. PNG_FLAG_CRC_ANCILLARY_NOWARN;
  185564. break;
  185565. case PNG_CRC_ERROR_QUIT: /* error/quit */
  185566. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  185567. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_NOWARN;
  185568. break;
  185569. case PNG_CRC_WARN_DISCARD: /* warn/discard data */
  185570. case PNG_CRC_DEFAULT:
  185571. default:
  185572. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  185573. break;
  185574. }
  185575. }
  185576. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && \
  185577. defined(PNG_FLOATING_POINT_SUPPORTED)
  185578. /* handle alpha and tRNS via a background color */
  185579. void PNGAPI
  185580. png_set_background(png_structp png_ptr,
  185581. png_color_16p background_color, int background_gamma_code,
  185582. int need_expand, double background_gamma)
  185583. {
  185584. png_debug(1, "in png_set_background\n");
  185585. if(png_ptr == NULL) return;
  185586. if (background_gamma_code == PNG_BACKGROUND_GAMMA_UNKNOWN)
  185587. {
  185588. png_warning(png_ptr, "Application must supply a known background gamma");
  185589. return;
  185590. }
  185591. png_ptr->transformations |= PNG_BACKGROUND;
  185592. png_memcpy(&(png_ptr->background), background_color,
  185593. png_sizeof(png_color_16));
  185594. png_ptr->background_gamma = (float)background_gamma;
  185595. png_ptr->background_gamma_type = (png_byte)(background_gamma_code);
  185596. png_ptr->transformations |= (need_expand ? PNG_BACKGROUND_EXPAND : 0);
  185597. }
  185598. #endif
  185599. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  185600. /* strip 16 bit depth files to 8 bit depth */
  185601. void PNGAPI
  185602. png_set_strip_16(png_structp png_ptr)
  185603. {
  185604. png_debug(1, "in png_set_strip_16\n");
  185605. if(png_ptr == NULL) return;
  185606. png_ptr->transformations |= PNG_16_TO_8;
  185607. }
  185608. #endif
  185609. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  185610. void PNGAPI
  185611. png_set_strip_alpha(png_structp png_ptr)
  185612. {
  185613. png_debug(1, "in png_set_strip_alpha\n");
  185614. if(png_ptr == NULL) return;
  185615. png_ptr->flags |= PNG_FLAG_STRIP_ALPHA;
  185616. }
  185617. #endif
  185618. #if defined(PNG_READ_DITHER_SUPPORTED)
  185619. /* Dither file to 8 bit. Supply a palette, the current number
  185620. * of elements in the palette, the maximum number of elements
  185621. * allowed, and a histogram if possible. If the current number
  185622. * of colors is greater then the maximum number, the palette will be
  185623. * modified to fit in the maximum number. "full_dither" indicates
  185624. * whether we need a dithering cube set up for RGB images, or if we
  185625. * simply are reducing the number of colors in a paletted image.
  185626. */
  185627. typedef struct png_dsort_struct
  185628. {
  185629. struct png_dsort_struct FAR * next;
  185630. png_byte left;
  185631. png_byte right;
  185632. } png_dsort;
  185633. typedef png_dsort FAR * png_dsortp;
  185634. typedef png_dsort FAR * FAR * png_dsortpp;
  185635. void PNGAPI
  185636. png_set_dither(png_structp png_ptr, png_colorp palette,
  185637. int num_palette, int maximum_colors, png_uint_16p histogram,
  185638. int full_dither)
  185639. {
  185640. png_debug(1, "in png_set_dither\n");
  185641. if(png_ptr == NULL) return;
  185642. png_ptr->transformations |= PNG_DITHER;
  185643. if (!full_dither)
  185644. {
  185645. int i;
  185646. png_ptr->dither_index = (png_bytep)png_malloc(png_ptr,
  185647. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  185648. for (i = 0; i < num_palette; i++)
  185649. png_ptr->dither_index[i] = (png_byte)i;
  185650. }
  185651. if (num_palette > maximum_colors)
  185652. {
  185653. if (histogram != NULL)
  185654. {
  185655. /* This is easy enough, just throw out the least used colors.
  185656. Perhaps not the best solution, but good enough. */
  185657. int i;
  185658. /* initialize an array to sort colors */
  185659. png_ptr->dither_sort = (png_bytep)png_malloc(png_ptr,
  185660. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  185661. /* initialize the dither_sort array */
  185662. for (i = 0; i < num_palette; i++)
  185663. png_ptr->dither_sort[i] = (png_byte)i;
  185664. /* Find the least used palette entries by starting a
  185665. bubble sort, and running it until we have sorted
  185666. out enough colors. Note that we don't care about
  185667. sorting all the colors, just finding which are
  185668. least used. */
  185669. for (i = num_palette - 1; i >= maximum_colors; i--)
  185670. {
  185671. int done; /* to stop early if the list is pre-sorted */
  185672. int j;
  185673. done = 1;
  185674. for (j = 0; j < i; j++)
  185675. {
  185676. if (histogram[png_ptr->dither_sort[j]]
  185677. < histogram[png_ptr->dither_sort[j + 1]])
  185678. {
  185679. png_byte t;
  185680. t = png_ptr->dither_sort[j];
  185681. png_ptr->dither_sort[j] = png_ptr->dither_sort[j + 1];
  185682. png_ptr->dither_sort[j + 1] = t;
  185683. done = 0;
  185684. }
  185685. }
  185686. if (done)
  185687. break;
  185688. }
  185689. /* swap the palette around, and set up a table, if necessary */
  185690. if (full_dither)
  185691. {
  185692. int j = num_palette;
  185693. /* put all the useful colors within the max, but don't
  185694. move the others */
  185695. for (i = 0; i < maximum_colors; i++)
  185696. {
  185697. if ((int)png_ptr->dither_sort[i] >= maximum_colors)
  185698. {
  185699. do
  185700. j--;
  185701. while ((int)png_ptr->dither_sort[j] >= maximum_colors);
  185702. palette[i] = palette[j];
  185703. }
  185704. }
  185705. }
  185706. else
  185707. {
  185708. int j = num_palette;
  185709. /* move all the used colors inside the max limit, and
  185710. develop a translation table */
  185711. for (i = 0; i < maximum_colors; i++)
  185712. {
  185713. /* only move the colors we need to */
  185714. if ((int)png_ptr->dither_sort[i] >= maximum_colors)
  185715. {
  185716. png_color tmp_color;
  185717. do
  185718. j--;
  185719. while ((int)png_ptr->dither_sort[j] >= maximum_colors);
  185720. tmp_color = palette[j];
  185721. palette[j] = palette[i];
  185722. palette[i] = tmp_color;
  185723. /* indicate where the color went */
  185724. png_ptr->dither_index[j] = (png_byte)i;
  185725. png_ptr->dither_index[i] = (png_byte)j;
  185726. }
  185727. }
  185728. /* find closest color for those colors we are not using */
  185729. for (i = 0; i < num_palette; i++)
  185730. {
  185731. if ((int)png_ptr->dither_index[i] >= maximum_colors)
  185732. {
  185733. int min_d, k, min_k, d_index;
  185734. /* find the closest color to one we threw out */
  185735. d_index = png_ptr->dither_index[i];
  185736. min_d = PNG_COLOR_DIST(palette[d_index], palette[0]);
  185737. for (k = 1, min_k = 0; k < maximum_colors; k++)
  185738. {
  185739. int d;
  185740. d = PNG_COLOR_DIST(palette[d_index], palette[k]);
  185741. if (d < min_d)
  185742. {
  185743. min_d = d;
  185744. min_k = k;
  185745. }
  185746. }
  185747. /* point to closest color */
  185748. png_ptr->dither_index[i] = (png_byte)min_k;
  185749. }
  185750. }
  185751. }
  185752. png_free(png_ptr, png_ptr->dither_sort);
  185753. png_ptr->dither_sort=NULL;
  185754. }
  185755. else
  185756. {
  185757. /* This is much harder to do simply (and quickly). Perhaps
  185758. we need to go through a median cut routine, but those
  185759. don't always behave themselves with only a few colors
  185760. as input. So we will just find the closest two colors,
  185761. and throw out one of them (chosen somewhat randomly).
  185762. [We don't understand this at all, so if someone wants to
  185763. work on improving it, be our guest - AED, GRP]
  185764. */
  185765. int i;
  185766. int max_d;
  185767. int num_new_palette;
  185768. png_dsortp t;
  185769. png_dsortpp hash;
  185770. t=NULL;
  185771. /* initialize palette index arrays */
  185772. png_ptr->index_to_palette = (png_bytep)png_malloc(png_ptr,
  185773. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  185774. png_ptr->palette_to_index = (png_bytep)png_malloc(png_ptr,
  185775. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  185776. /* initialize the sort array */
  185777. for (i = 0; i < num_palette; i++)
  185778. {
  185779. png_ptr->index_to_palette[i] = (png_byte)i;
  185780. png_ptr->palette_to_index[i] = (png_byte)i;
  185781. }
  185782. hash = (png_dsortpp)png_malloc(png_ptr, (png_uint_32)(769 *
  185783. png_sizeof (png_dsortp)));
  185784. for (i = 0; i < 769; i++)
  185785. hash[i] = NULL;
  185786. /* png_memset(hash, 0, 769 * png_sizeof (png_dsortp)); */
  185787. num_new_palette = num_palette;
  185788. /* initial wild guess at how far apart the farthest pixel
  185789. pair we will be eliminating will be. Larger
  185790. numbers mean more areas will be allocated, Smaller
  185791. numbers run the risk of not saving enough data, and
  185792. having to do this all over again.
  185793. I have not done extensive checking on this number.
  185794. */
  185795. max_d = 96;
  185796. while (num_new_palette > maximum_colors)
  185797. {
  185798. for (i = 0; i < num_new_palette - 1; i++)
  185799. {
  185800. int j;
  185801. for (j = i + 1; j < num_new_palette; j++)
  185802. {
  185803. int d;
  185804. d = PNG_COLOR_DIST(palette[i], palette[j]);
  185805. if (d <= max_d)
  185806. {
  185807. t = (png_dsortp)png_malloc_warn(png_ptr,
  185808. (png_uint_32)(png_sizeof(png_dsort)));
  185809. if (t == NULL)
  185810. break;
  185811. t->next = hash[d];
  185812. t->left = (png_byte)i;
  185813. t->right = (png_byte)j;
  185814. hash[d] = t;
  185815. }
  185816. }
  185817. if (t == NULL)
  185818. break;
  185819. }
  185820. if (t != NULL)
  185821. for (i = 0; i <= max_d; i++)
  185822. {
  185823. if (hash[i] != NULL)
  185824. {
  185825. png_dsortp p;
  185826. for (p = hash[i]; p; p = p->next)
  185827. {
  185828. if ((int)png_ptr->index_to_palette[p->left]
  185829. < num_new_palette &&
  185830. (int)png_ptr->index_to_palette[p->right]
  185831. < num_new_palette)
  185832. {
  185833. int j, next_j;
  185834. if (num_new_palette & 0x01)
  185835. {
  185836. j = p->left;
  185837. next_j = p->right;
  185838. }
  185839. else
  185840. {
  185841. j = p->right;
  185842. next_j = p->left;
  185843. }
  185844. num_new_palette--;
  185845. palette[png_ptr->index_to_palette[j]]
  185846. = palette[num_new_palette];
  185847. if (!full_dither)
  185848. {
  185849. int k;
  185850. for (k = 0; k < num_palette; k++)
  185851. {
  185852. if (png_ptr->dither_index[k] ==
  185853. png_ptr->index_to_palette[j])
  185854. png_ptr->dither_index[k] =
  185855. png_ptr->index_to_palette[next_j];
  185856. if ((int)png_ptr->dither_index[k] ==
  185857. num_new_palette)
  185858. png_ptr->dither_index[k] =
  185859. png_ptr->index_to_palette[j];
  185860. }
  185861. }
  185862. png_ptr->index_to_palette[png_ptr->palette_to_index
  185863. [num_new_palette]] = png_ptr->index_to_palette[j];
  185864. png_ptr->palette_to_index[png_ptr->index_to_palette[j]]
  185865. = png_ptr->palette_to_index[num_new_palette];
  185866. png_ptr->index_to_palette[j] = (png_byte)num_new_palette;
  185867. png_ptr->palette_to_index[num_new_palette] = (png_byte)j;
  185868. }
  185869. if (num_new_palette <= maximum_colors)
  185870. break;
  185871. }
  185872. if (num_new_palette <= maximum_colors)
  185873. break;
  185874. }
  185875. }
  185876. for (i = 0; i < 769; i++)
  185877. {
  185878. if (hash[i] != NULL)
  185879. {
  185880. png_dsortp p = hash[i];
  185881. while (p)
  185882. {
  185883. t = p->next;
  185884. png_free(png_ptr, p);
  185885. p = t;
  185886. }
  185887. }
  185888. hash[i] = 0;
  185889. }
  185890. max_d += 96;
  185891. }
  185892. png_free(png_ptr, hash);
  185893. png_free(png_ptr, png_ptr->palette_to_index);
  185894. png_free(png_ptr, png_ptr->index_to_palette);
  185895. png_ptr->palette_to_index=NULL;
  185896. png_ptr->index_to_palette=NULL;
  185897. }
  185898. num_palette = maximum_colors;
  185899. }
  185900. if (png_ptr->palette == NULL)
  185901. {
  185902. png_ptr->palette = palette;
  185903. }
  185904. png_ptr->num_palette = (png_uint_16)num_palette;
  185905. if (full_dither)
  185906. {
  185907. int i;
  185908. png_bytep distance;
  185909. int total_bits = PNG_DITHER_RED_BITS + PNG_DITHER_GREEN_BITS +
  185910. PNG_DITHER_BLUE_BITS;
  185911. int num_red = (1 << PNG_DITHER_RED_BITS);
  185912. int num_green = (1 << PNG_DITHER_GREEN_BITS);
  185913. int num_blue = (1 << PNG_DITHER_BLUE_BITS);
  185914. png_size_t num_entries = ((png_size_t)1 << total_bits);
  185915. png_ptr->palette_lookup = (png_bytep )png_malloc(png_ptr,
  185916. (png_uint_32)(num_entries * png_sizeof (png_byte)));
  185917. png_memset(png_ptr->palette_lookup, 0, num_entries *
  185918. png_sizeof (png_byte));
  185919. distance = (png_bytep)png_malloc(png_ptr, (png_uint_32)(num_entries *
  185920. png_sizeof(png_byte)));
  185921. png_memset(distance, 0xff, num_entries * png_sizeof(png_byte));
  185922. for (i = 0; i < num_palette; i++)
  185923. {
  185924. int ir, ig, ib;
  185925. int r = (palette[i].red >> (8 - PNG_DITHER_RED_BITS));
  185926. int g = (palette[i].green >> (8 - PNG_DITHER_GREEN_BITS));
  185927. int b = (palette[i].blue >> (8 - PNG_DITHER_BLUE_BITS));
  185928. for (ir = 0; ir < num_red; ir++)
  185929. {
  185930. /* int dr = abs(ir - r); */
  185931. int dr = ((ir > r) ? ir - r : r - ir);
  185932. int index_r = (ir << (PNG_DITHER_BLUE_BITS + PNG_DITHER_GREEN_BITS));
  185933. for (ig = 0; ig < num_green; ig++)
  185934. {
  185935. /* int dg = abs(ig - g); */
  185936. int dg = ((ig > g) ? ig - g : g - ig);
  185937. int dt = dr + dg;
  185938. int dm = ((dr > dg) ? dr : dg);
  185939. int index_g = index_r | (ig << PNG_DITHER_BLUE_BITS);
  185940. for (ib = 0; ib < num_blue; ib++)
  185941. {
  185942. int d_index = index_g | ib;
  185943. /* int db = abs(ib - b); */
  185944. int db = ((ib > b) ? ib - b : b - ib);
  185945. int dmax = ((dm > db) ? dm : db);
  185946. int d = dmax + dt + db;
  185947. if (d < (int)distance[d_index])
  185948. {
  185949. distance[d_index] = (png_byte)d;
  185950. png_ptr->palette_lookup[d_index] = (png_byte)i;
  185951. }
  185952. }
  185953. }
  185954. }
  185955. }
  185956. png_free(png_ptr, distance);
  185957. }
  185958. }
  185959. #endif
  185960. #if defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  185961. /* Transform the image from the file_gamma to the screen_gamma. We
  185962. * only do transformations on images where the file_gamma and screen_gamma
  185963. * are not close reciprocals, otherwise it slows things down slightly, and
  185964. * also needlessly introduces small errors.
  185965. *
  185966. * We will turn off gamma transformation later if no semitransparent entries
  185967. * are present in the tRNS array for palette images. We can't do it here
  185968. * because we don't necessarily have the tRNS chunk yet.
  185969. */
  185970. void PNGAPI
  185971. png_set_gamma(png_structp png_ptr, double scrn_gamma, double file_gamma)
  185972. {
  185973. png_debug(1, "in png_set_gamma\n");
  185974. if(png_ptr == NULL) return;
  185975. if ((fabs(scrn_gamma * file_gamma - 1.0) > PNG_GAMMA_THRESHOLD) ||
  185976. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA) ||
  185977. (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE))
  185978. png_ptr->transformations |= PNG_GAMMA;
  185979. png_ptr->gamma = (float)file_gamma;
  185980. png_ptr->screen_gamma = (float)scrn_gamma;
  185981. }
  185982. #endif
  185983. #if defined(PNG_READ_EXPAND_SUPPORTED)
  185984. /* Expand paletted images to RGB, expand grayscale images of
  185985. * less than 8-bit depth to 8-bit depth, and expand tRNS chunks
  185986. * to alpha channels.
  185987. */
  185988. void PNGAPI
  185989. png_set_expand(png_structp png_ptr)
  185990. {
  185991. png_debug(1, "in png_set_expand\n");
  185992. if(png_ptr == NULL) return;
  185993. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  185994. #ifdef PNG_WARN_UNINITIALIZED_ROW
  185995. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  185996. #endif
  185997. }
  185998. /* GRR 19990627: the following three functions currently are identical
  185999. * to png_set_expand(). However, it is entirely reasonable that someone
  186000. * might wish to expand an indexed image to RGB but *not* expand a single,
  186001. * fully transparent palette entry to a full alpha channel--perhaps instead
  186002. * convert tRNS to the grayscale/RGB format (16-bit RGB value), or replace
  186003. * the transparent color with a particular RGB value, or drop tRNS entirely.
  186004. * IOW, a future version of the library may make the transformations flag
  186005. * a bit more fine-grained, with separate bits for each of these three
  186006. * functions.
  186007. *
  186008. * More to the point, these functions make it obvious what libpng will be
  186009. * doing, whereas "expand" can (and does) mean any number of things.
  186010. *
  186011. * GRP 20060307: In libpng-1.4.0, png_set_gray_1_2_4_to_8() was modified
  186012. * to expand only the sample depth but not to expand the tRNS to alpha.
  186013. */
  186014. /* Expand paletted images to RGB. */
  186015. void PNGAPI
  186016. png_set_palette_to_rgb(png_structp png_ptr)
  186017. {
  186018. png_debug(1, "in png_set_palette_to_rgb\n");
  186019. if(png_ptr == NULL) return;
  186020. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  186021. #ifdef PNG_WARN_UNINITIALIZED_ROW
  186022. png_ptr->flags &= !(PNG_FLAG_ROW_INIT);
  186023. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  186024. #endif
  186025. }
  186026. #if !defined(PNG_1_0_X)
  186027. /* Expand grayscale images of less than 8-bit depth to 8 bits. */
  186028. void PNGAPI
  186029. png_set_expand_gray_1_2_4_to_8(png_structp png_ptr)
  186030. {
  186031. png_debug(1, "in png_set_expand_gray_1_2_4_to_8\n");
  186032. if(png_ptr == NULL) return;
  186033. png_ptr->transformations |= PNG_EXPAND;
  186034. #ifdef PNG_WARN_UNINITIALIZED_ROW
  186035. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  186036. #endif
  186037. }
  186038. #endif
  186039. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  186040. /* Expand grayscale images of less than 8-bit depth to 8 bits. */
  186041. /* Deprecated as of libpng-1.2.9 */
  186042. void PNGAPI
  186043. png_set_gray_1_2_4_to_8(png_structp png_ptr)
  186044. {
  186045. png_debug(1, "in png_set_gray_1_2_4_to_8\n");
  186046. if(png_ptr == NULL) return;
  186047. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  186048. }
  186049. #endif
  186050. /* Expand tRNS chunks to alpha channels. */
  186051. void PNGAPI
  186052. png_set_tRNS_to_alpha(png_structp png_ptr)
  186053. {
  186054. png_debug(1, "in png_set_tRNS_to_alpha\n");
  186055. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  186056. #ifdef PNG_WARN_UNINITIALIZED_ROW
  186057. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  186058. #endif
  186059. }
  186060. #endif /* defined(PNG_READ_EXPAND_SUPPORTED) */
  186061. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  186062. void PNGAPI
  186063. png_set_gray_to_rgb(png_structp png_ptr)
  186064. {
  186065. png_debug(1, "in png_set_gray_to_rgb\n");
  186066. png_ptr->transformations |= PNG_GRAY_TO_RGB;
  186067. #ifdef PNG_WARN_UNINITIALIZED_ROW
  186068. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  186069. #endif
  186070. }
  186071. #endif
  186072. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  186073. #if defined(PNG_FLOATING_POINT_SUPPORTED)
  186074. /* Convert a RGB image to a grayscale of the same width. This allows us,
  186075. * for example, to convert a 24 bpp RGB image into an 8 bpp grayscale image.
  186076. */
  186077. void PNGAPI
  186078. png_set_rgb_to_gray(png_structp png_ptr, int error_action, double red,
  186079. double green)
  186080. {
  186081. int red_fixed = (int)((float)red*100000.0 + 0.5);
  186082. int green_fixed = (int)((float)green*100000.0 + 0.5);
  186083. if(png_ptr == NULL) return;
  186084. png_set_rgb_to_gray_fixed(png_ptr, error_action, red_fixed, green_fixed);
  186085. }
  186086. #endif
  186087. void PNGAPI
  186088. png_set_rgb_to_gray_fixed(png_structp png_ptr, int error_action,
  186089. png_fixed_point red, png_fixed_point green)
  186090. {
  186091. png_debug(1, "in png_set_rgb_to_gray\n");
  186092. if(png_ptr == NULL) return;
  186093. switch(error_action)
  186094. {
  186095. case 1: png_ptr->transformations |= PNG_RGB_TO_GRAY;
  186096. break;
  186097. case 2: png_ptr->transformations |= PNG_RGB_TO_GRAY_WARN;
  186098. break;
  186099. case 3: png_ptr->transformations |= PNG_RGB_TO_GRAY_ERR;
  186100. }
  186101. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  186102. #if defined(PNG_READ_EXPAND_SUPPORTED)
  186103. png_ptr->transformations |= PNG_EXPAND;
  186104. #else
  186105. {
  186106. png_warning(png_ptr, "Cannot do RGB_TO_GRAY without EXPAND_SUPPORTED.");
  186107. png_ptr->transformations &= ~PNG_RGB_TO_GRAY;
  186108. }
  186109. #endif
  186110. {
  186111. png_uint_16 red_int, green_int;
  186112. if(red < 0 || green < 0)
  186113. {
  186114. red_int = 6968; /* .212671 * 32768 + .5 */
  186115. green_int = 23434; /* .715160 * 32768 + .5 */
  186116. }
  186117. else if(red + green < 100000L)
  186118. {
  186119. red_int = (png_uint_16)(((png_uint_32)red*32768L)/100000L);
  186120. green_int = (png_uint_16)(((png_uint_32)green*32768L)/100000L);
  186121. }
  186122. else
  186123. {
  186124. png_warning(png_ptr, "ignoring out of range rgb_to_gray coefficients");
  186125. red_int = 6968;
  186126. green_int = 23434;
  186127. }
  186128. png_ptr->rgb_to_gray_red_coeff = red_int;
  186129. png_ptr->rgb_to_gray_green_coeff = green_int;
  186130. png_ptr->rgb_to_gray_blue_coeff = (png_uint_16)(32768-red_int-green_int);
  186131. }
  186132. }
  186133. #endif
  186134. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  186135. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  186136. defined(PNG_LEGACY_SUPPORTED)
  186137. void PNGAPI
  186138. png_set_read_user_transform_fn(png_structp png_ptr, png_user_transform_ptr
  186139. read_user_transform_fn)
  186140. {
  186141. png_debug(1, "in png_set_read_user_transform_fn\n");
  186142. if(png_ptr == NULL) return;
  186143. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  186144. png_ptr->transformations |= PNG_USER_TRANSFORM;
  186145. png_ptr->read_user_transform_fn = read_user_transform_fn;
  186146. #endif
  186147. #ifdef PNG_LEGACY_SUPPORTED
  186148. if(read_user_transform_fn)
  186149. png_warning(png_ptr,
  186150. "This version of libpng does not support user transforms");
  186151. #endif
  186152. }
  186153. #endif
  186154. /* Initialize everything needed for the read. This includes modifying
  186155. * the palette.
  186156. */
  186157. void /* PRIVATE */
  186158. png_init_read_transformations(png_structp png_ptr)
  186159. {
  186160. png_debug(1, "in png_init_read_transformations\n");
  186161. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  186162. if(png_ptr != NULL)
  186163. #endif
  186164. {
  186165. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || defined(PNG_READ_SHIFT_SUPPORTED) \
  186166. || defined(PNG_READ_GAMMA_SUPPORTED)
  186167. int color_type = png_ptr->color_type;
  186168. #endif
  186169. #if defined(PNG_READ_EXPAND_SUPPORTED) && defined(PNG_READ_BACKGROUND_SUPPORTED)
  186170. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  186171. /* Detect gray background and attempt to enable optimization
  186172. * for gray --> RGB case */
  186173. /* Note: if PNG_BACKGROUND_EXPAND is set and color_type is either RGB or
  186174. * RGB_ALPHA (in which case need_expand is superfluous anyway), the
  186175. * background color might actually be gray yet not be flagged as such.
  186176. * This is not a problem for the current code, which uses
  186177. * PNG_BACKGROUND_IS_GRAY only to decide when to do the
  186178. * png_do_gray_to_rgb() transformation.
  186179. */
  186180. if ((png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  186181. !(color_type & PNG_COLOR_MASK_COLOR))
  186182. {
  186183. png_ptr->mode |= PNG_BACKGROUND_IS_GRAY;
  186184. } else if ((png_ptr->transformations & PNG_BACKGROUND) &&
  186185. !(png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  186186. (png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  186187. png_ptr->background.red == png_ptr->background.green &&
  186188. png_ptr->background.red == png_ptr->background.blue)
  186189. {
  186190. png_ptr->mode |= PNG_BACKGROUND_IS_GRAY;
  186191. png_ptr->background.gray = png_ptr->background.red;
  186192. }
  186193. #endif
  186194. if ((png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  186195. (png_ptr->transformations & PNG_EXPAND))
  186196. {
  186197. if (!(color_type & PNG_COLOR_MASK_COLOR)) /* i.e., GRAY or GRAY_ALPHA */
  186198. {
  186199. /* expand background and tRNS chunks */
  186200. switch (png_ptr->bit_depth)
  186201. {
  186202. case 1:
  186203. png_ptr->background.gray *= (png_uint_16)0xff;
  186204. png_ptr->background.red = png_ptr->background.green
  186205. = png_ptr->background.blue = png_ptr->background.gray;
  186206. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  186207. {
  186208. png_ptr->trans_values.gray *= (png_uint_16)0xff;
  186209. png_ptr->trans_values.red = png_ptr->trans_values.green
  186210. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  186211. }
  186212. break;
  186213. case 2:
  186214. png_ptr->background.gray *= (png_uint_16)0x55;
  186215. png_ptr->background.red = png_ptr->background.green
  186216. = png_ptr->background.blue = png_ptr->background.gray;
  186217. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  186218. {
  186219. png_ptr->trans_values.gray *= (png_uint_16)0x55;
  186220. png_ptr->trans_values.red = png_ptr->trans_values.green
  186221. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  186222. }
  186223. break;
  186224. case 4:
  186225. png_ptr->background.gray *= (png_uint_16)0x11;
  186226. png_ptr->background.red = png_ptr->background.green
  186227. = png_ptr->background.blue = png_ptr->background.gray;
  186228. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  186229. {
  186230. png_ptr->trans_values.gray *= (png_uint_16)0x11;
  186231. png_ptr->trans_values.red = png_ptr->trans_values.green
  186232. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  186233. }
  186234. break;
  186235. case 8:
  186236. case 16:
  186237. png_ptr->background.red = png_ptr->background.green
  186238. = png_ptr->background.blue = png_ptr->background.gray;
  186239. break;
  186240. }
  186241. }
  186242. else if (color_type == PNG_COLOR_TYPE_PALETTE)
  186243. {
  186244. png_ptr->background.red =
  186245. png_ptr->palette[png_ptr->background.index].red;
  186246. png_ptr->background.green =
  186247. png_ptr->palette[png_ptr->background.index].green;
  186248. png_ptr->background.blue =
  186249. png_ptr->palette[png_ptr->background.index].blue;
  186250. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  186251. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  186252. {
  186253. #if defined(PNG_READ_EXPAND_SUPPORTED)
  186254. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  186255. #endif
  186256. {
  186257. /* invert the alpha channel (in tRNS) unless the pixels are
  186258. going to be expanded, in which case leave it for later */
  186259. int i,istop;
  186260. istop=(int)png_ptr->num_trans;
  186261. for (i=0; i<istop; i++)
  186262. png_ptr->trans[i] = (png_byte)(255 - png_ptr->trans[i]);
  186263. }
  186264. }
  186265. #endif
  186266. }
  186267. }
  186268. #endif
  186269. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && defined(PNG_READ_GAMMA_SUPPORTED)
  186270. png_ptr->background_1 = png_ptr->background;
  186271. #endif
  186272. #if defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  186273. if ((color_type == PNG_COLOR_TYPE_PALETTE && png_ptr->num_trans != 0)
  186274. && (fabs(png_ptr->screen_gamma * png_ptr->gamma - 1.0)
  186275. < PNG_GAMMA_THRESHOLD))
  186276. {
  186277. int i,k;
  186278. k=0;
  186279. for (i=0; i<png_ptr->num_trans; i++)
  186280. {
  186281. if (png_ptr->trans[i] != 0 && png_ptr->trans[i] != 0xff)
  186282. k=1; /* partial transparency is present */
  186283. }
  186284. if (k == 0)
  186285. png_ptr->transformations &= (~PNG_GAMMA);
  186286. }
  186287. if ((png_ptr->transformations & (PNG_GAMMA | PNG_RGB_TO_GRAY)) &&
  186288. png_ptr->gamma != 0.0)
  186289. {
  186290. png_build_gamma_table(png_ptr);
  186291. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  186292. if (png_ptr->transformations & PNG_BACKGROUND)
  186293. {
  186294. if (color_type == PNG_COLOR_TYPE_PALETTE)
  186295. {
  186296. /* could skip if no transparency and
  186297. */
  186298. png_color back, back_1;
  186299. png_colorp palette = png_ptr->palette;
  186300. int num_palette = png_ptr->num_palette;
  186301. int i;
  186302. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_FILE)
  186303. {
  186304. back.red = png_ptr->gamma_table[png_ptr->background.red];
  186305. back.green = png_ptr->gamma_table[png_ptr->background.green];
  186306. back.blue = png_ptr->gamma_table[png_ptr->background.blue];
  186307. back_1.red = png_ptr->gamma_to_1[png_ptr->background.red];
  186308. back_1.green = png_ptr->gamma_to_1[png_ptr->background.green];
  186309. back_1.blue = png_ptr->gamma_to_1[png_ptr->background.blue];
  186310. }
  186311. else
  186312. {
  186313. double g, gs;
  186314. switch (png_ptr->background_gamma_type)
  186315. {
  186316. case PNG_BACKGROUND_GAMMA_SCREEN:
  186317. g = (png_ptr->screen_gamma);
  186318. gs = 1.0;
  186319. break;
  186320. case PNG_BACKGROUND_GAMMA_FILE:
  186321. g = 1.0 / (png_ptr->gamma);
  186322. gs = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  186323. break;
  186324. case PNG_BACKGROUND_GAMMA_UNIQUE:
  186325. g = 1.0 / (png_ptr->background_gamma);
  186326. gs = 1.0 / (png_ptr->background_gamma *
  186327. png_ptr->screen_gamma);
  186328. break;
  186329. default:
  186330. g = 1.0; /* back_1 */
  186331. gs = 1.0; /* back */
  186332. }
  186333. if ( fabs(gs - 1.0) < PNG_GAMMA_THRESHOLD)
  186334. {
  186335. back.red = (png_byte)png_ptr->background.red;
  186336. back.green = (png_byte)png_ptr->background.green;
  186337. back.blue = (png_byte)png_ptr->background.blue;
  186338. }
  186339. else
  186340. {
  186341. back.red = (png_byte)(pow(
  186342. (double)png_ptr->background.red/255, gs) * 255.0 + .5);
  186343. back.green = (png_byte)(pow(
  186344. (double)png_ptr->background.green/255, gs) * 255.0 + .5);
  186345. back.blue = (png_byte)(pow(
  186346. (double)png_ptr->background.blue/255, gs) * 255.0 + .5);
  186347. }
  186348. back_1.red = (png_byte)(pow(
  186349. (double)png_ptr->background.red/255, g) * 255.0 + .5);
  186350. back_1.green = (png_byte)(pow(
  186351. (double)png_ptr->background.green/255, g) * 255.0 + .5);
  186352. back_1.blue = (png_byte)(pow(
  186353. (double)png_ptr->background.blue/255, g) * 255.0 + .5);
  186354. }
  186355. for (i = 0; i < num_palette; i++)
  186356. {
  186357. if (i < (int)png_ptr->num_trans && png_ptr->trans[i] != 0xff)
  186358. {
  186359. if (png_ptr->trans[i] == 0)
  186360. {
  186361. palette[i] = back;
  186362. }
  186363. else /* if (png_ptr->trans[i] != 0xff) */
  186364. {
  186365. png_byte v, w;
  186366. v = png_ptr->gamma_to_1[palette[i].red];
  186367. png_composite(w, v, png_ptr->trans[i], back_1.red);
  186368. palette[i].red = png_ptr->gamma_from_1[w];
  186369. v = png_ptr->gamma_to_1[palette[i].green];
  186370. png_composite(w, v, png_ptr->trans[i], back_1.green);
  186371. palette[i].green = png_ptr->gamma_from_1[w];
  186372. v = png_ptr->gamma_to_1[palette[i].blue];
  186373. png_composite(w, v, png_ptr->trans[i], back_1.blue);
  186374. palette[i].blue = png_ptr->gamma_from_1[w];
  186375. }
  186376. }
  186377. else
  186378. {
  186379. palette[i].red = png_ptr->gamma_table[palette[i].red];
  186380. palette[i].green = png_ptr->gamma_table[palette[i].green];
  186381. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  186382. }
  186383. }
  186384. }
  186385. /* if (png_ptr->background_gamma_type!=PNG_BACKGROUND_GAMMA_UNKNOWN) */
  186386. else
  186387. /* color_type != PNG_COLOR_TYPE_PALETTE */
  186388. {
  186389. double m = (double)(((png_uint_32)1 << png_ptr->bit_depth) - 1);
  186390. double g = 1.0;
  186391. double gs = 1.0;
  186392. switch (png_ptr->background_gamma_type)
  186393. {
  186394. case PNG_BACKGROUND_GAMMA_SCREEN:
  186395. g = (png_ptr->screen_gamma);
  186396. gs = 1.0;
  186397. break;
  186398. case PNG_BACKGROUND_GAMMA_FILE:
  186399. g = 1.0 / (png_ptr->gamma);
  186400. gs = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  186401. break;
  186402. case PNG_BACKGROUND_GAMMA_UNIQUE:
  186403. g = 1.0 / (png_ptr->background_gamma);
  186404. gs = 1.0 / (png_ptr->background_gamma *
  186405. png_ptr->screen_gamma);
  186406. break;
  186407. }
  186408. png_ptr->background_1.gray = (png_uint_16)(pow(
  186409. (double)png_ptr->background.gray / m, g) * m + .5);
  186410. png_ptr->background.gray = (png_uint_16)(pow(
  186411. (double)png_ptr->background.gray / m, gs) * m + .5);
  186412. if ((png_ptr->background.red != png_ptr->background.green) ||
  186413. (png_ptr->background.red != png_ptr->background.blue) ||
  186414. (png_ptr->background.red != png_ptr->background.gray))
  186415. {
  186416. /* RGB or RGBA with color background */
  186417. png_ptr->background_1.red = (png_uint_16)(pow(
  186418. (double)png_ptr->background.red / m, g) * m + .5);
  186419. png_ptr->background_1.green = (png_uint_16)(pow(
  186420. (double)png_ptr->background.green / m, g) * m + .5);
  186421. png_ptr->background_1.blue = (png_uint_16)(pow(
  186422. (double)png_ptr->background.blue / m, g) * m + .5);
  186423. png_ptr->background.red = (png_uint_16)(pow(
  186424. (double)png_ptr->background.red / m, gs) * m + .5);
  186425. png_ptr->background.green = (png_uint_16)(pow(
  186426. (double)png_ptr->background.green / m, gs) * m + .5);
  186427. png_ptr->background.blue = (png_uint_16)(pow(
  186428. (double)png_ptr->background.blue / m, gs) * m + .5);
  186429. }
  186430. else
  186431. {
  186432. /* GRAY, GRAY ALPHA, RGB, or RGBA with gray background */
  186433. png_ptr->background_1.red = png_ptr->background_1.green
  186434. = png_ptr->background_1.blue = png_ptr->background_1.gray;
  186435. png_ptr->background.red = png_ptr->background.green
  186436. = png_ptr->background.blue = png_ptr->background.gray;
  186437. }
  186438. }
  186439. }
  186440. else
  186441. /* transformation does not include PNG_BACKGROUND */
  186442. #endif /* PNG_READ_BACKGROUND_SUPPORTED */
  186443. if (color_type == PNG_COLOR_TYPE_PALETTE)
  186444. {
  186445. png_colorp palette = png_ptr->palette;
  186446. int num_palette = png_ptr->num_palette;
  186447. int i;
  186448. for (i = 0; i < num_palette; i++)
  186449. {
  186450. palette[i].red = png_ptr->gamma_table[palette[i].red];
  186451. palette[i].green = png_ptr->gamma_table[palette[i].green];
  186452. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  186453. }
  186454. }
  186455. }
  186456. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  186457. else
  186458. #endif
  186459. #endif /* PNG_READ_GAMMA_SUPPORTED && PNG_FLOATING_POINT_SUPPORTED */
  186460. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  186461. /* No GAMMA transformation */
  186462. if ((png_ptr->transformations & PNG_BACKGROUND) &&
  186463. (color_type == PNG_COLOR_TYPE_PALETTE))
  186464. {
  186465. int i;
  186466. int istop = (int)png_ptr->num_trans;
  186467. png_color back;
  186468. png_colorp palette = png_ptr->palette;
  186469. back.red = (png_byte)png_ptr->background.red;
  186470. back.green = (png_byte)png_ptr->background.green;
  186471. back.blue = (png_byte)png_ptr->background.blue;
  186472. for (i = 0; i < istop; i++)
  186473. {
  186474. if (png_ptr->trans[i] == 0)
  186475. {
  186476. palette[i] = back;
  186477. }
  186478. else if (png_ptr->trans[i] != 0xff)
  186479. {
  186480. /* The png_composite() macro is defined in png.h */
  186481. png_composite(palette[i].red, palette[i].red,
  186482. png_ptr->trans[i], back.red);
  186483. png_composite(palette[i].green, palette[i].green,
  186484. png_ptr->trans[i], back.green);
  186485. png_composite(palette[i].blue, palette[i].blue,
  186486. png_ptr->trans[i], back.blue);
  186487. }
  186488. }
  186489. }
  186490. #endif /* PNG_READ_BACKGROUND_SUPPORTED */
  186491. #if defined(PNG_READ_SHIFT_SUPPORTED)
  186492. if ((png_ptr->transformations & PNG_SHIFT) &&
  186493. (color_type == PNG_COLOR_TYPE_PALETTE))
  186494. {
  186495. png_uint_16 i;
  186496. png_uint_16 istop = png_ptr->num_palette;
  186497. int sr = 8 - png_ptr->sig_bit.red;
  186498. int sg = 8 - png_ptr->sig_bit.green;
  186499. int sb = 8 - png_ptr->sig_bit.blue;
  186500. if (sr < 0 || sr > 8)
  186501. sr = 0;
  186502. if (sg < 0 || sg > 8)
  186503. sg = 0;
  186504. if (sb < 0 || sb > 8)
  186505. sb = 0;
  186506. for (i = 0; i < istop; i++)
  186507. {
  186508. png_ptr->palette[i].red >>= sr;
  186509. png_ptr->palette[i].green >>= sg;
  186510. png_ptr->palette[i].blue >>= sb;
  186511. }
  186512. }
  186513. #endif /* PNG_READ_SHIFT_SUPPORTED */
  186514. }
  186515. #if !defined(PNG_READ_GAMMA_SUPPORTED) && !defined(PNG_READ_SHIFT_SUPPORTED) \
  186516. && !defined(PNG_READ_BACKGROUND_SUPPORTED)
  186517. if(png_ptr)
  186518. return;
  186519. #endif
  186520. }
  186521. /* Modify the info structure to reflect the transformations. The
  186522. * info should be updated so a PNG file could be written with it,
  186523. * assuming the transformations result in valid PNG data.
  186524. */
  186525. void /* PRIVATE */
  186526. png_read_transform_info(png_structp png_ptr, png_infop info_ptr)
  186527. {
  186528. png_debug(1, "in png_read_transform_info\n");
  186529. #if defined(PNG_READ_EXPAND_SUPPORTED)
  186530. if (png_ptr->transformations & PNG_EXPAND)
  186531. {
  186532. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  186533. {
  186534. if (png_ptr->num_trans && (png_ptr->transformations & PNG_EXPAND_tRNS))
  186535. info_ptr->color_type = PNG_COLOR_TYPE_RGB_ALPHA;
  186536. else
  186537. info_ptr->color_type = PNG_COLOR_TYPE_RGB;
  186538. info_ptr->bit_depth = 8;
  186539. info_ptr->num_trans = 0;
  186540. }
  186541. else
  186542. {
  186543. if (png_ptr->num_trans)
  186544. {
  186545. if (png_ptr->transformations & PNG_EXPAND_tRNS)
  186546. info_ptr->color_type |= PNG_COLOR_MASK_ALPHA;
  186547. else
  186548. info_ptr->color_type |= PNG_COLOR_MASK_COLOR;
  186549. }
  186550. if (info_ptr->bit_depth < 8)
  186551. info_ptr->bit_depth = 8;
  186552. info_ptr->num_trans = 0;
  186553. }
  186554. }
  186555. #endif
  186556. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  186557. if (png_ptr->transformations & PNG_BACKGROUND)
  186558. {
  186559. info_ptr->color_type &= ~PNG_COLOR_MASK_ALPHA;
  186560. info_ptr->num_trans = 0;
  186561. info_ptr->background = png_ptr->background;
  186562. }
  186563. #endif
  186564. #if defined(PNG_READ_GAMMA_SUPPORTED)
  186565. if (png_ptr->transformations & PNG_GAMMA)
  186566. {
  186567. #ifdef PNG_FLOATING_POINT_SUPPORTED
  186568. info_ptr->gamma = png_ptr->gamma;
  186569. #endif
  186570. #ifdef PNG_FIXED_POINT_SUPPORTED
  186571. info_ptr->int_gamma = png_ptr->int_gamma;
  186572. #endif
  186573. }
  186574. #endif
  186575. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  186576. if ((png_ptr->transformations & PNG_16_TO_8) && (info_ptr->bit_depth == 16))
  186577. info_ptr->bit_depth = 8;
  186578. #endif
  186579. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  186580. if (png_ptr->transformations & PNG_GRAY_TO_RGB)
  186581. info_ptr->color_type |= PNG_COLOR_MASK_COLOR;
  186582. #endif
  186583. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  186584. if (png_ptr->transformations & PNG_RGB_TO_GRAY)
  186585. info_ptr->color_type &= ~PNG_COLOR_MASK_COLOR;
  186586. #endif
  186587. #if defined(PNG_READ_DITHER_SUPPORTED)
  186588. if (png_ptr->transformations & PNG_DITHER)
  186589. {
  186590. if (((info_ptr->color_type == PNG_COLOR_TYPE_RGB) ||
  186591. (info_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)) &&
  186592. png_ptr->palette_lookup && info_ptr->bit_depth == 8)
  186593. {
  186594. info_ptr->color_type = PNG_COLOR_TYPE_PALETTE;
  186595. }
  186596. }
  186597. #endif
  186598. #if defined(PNG_READ_PACK_SUPPORTED)
  186599. if ((png_ptr->transformations & PNG_PACK) && (info_ptr->bit_depth < 8))
  186600. info_ptr->bit_depth = 8;
  186601. #endif
  186602. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  186603. info_ptr->channels = 1;
  186604. else if (info_ptr->color_type & PNG_COLOR_MASK_COLOR)
  186605. info_ptr->channels = 3;
  186606. else
  186607. info_ptr->channels = 1;
  186608. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  186609. if (png_ptr->flags & PNG_FLAG_STRIP_ALPHA)
  186610. info_ptr->color_type &= ~PNG_COLOR_MASK_ALPHA;
  186611. #endif
  186612. if (info_ptr->color_type & PNG_COLOR_MASK_ALPHA)
  186613. info_ptr->channels++;
  186614. #if defined(PNG_READ_FILLER_SUPPORTED)
  186615. /* STRIP_ALPHA and FILLER allowed: MASK_ALPHA bit stripped above */
  186616. if ((png_ptr->transformations & PNG_FILLER) &&
  186617. ((info_ptr->color_type == PNG_COLOR_TYPE_RGB) ||
  186618. (info_ptr->color_type == PNG_COLOR_TYPE_GRAY)))
  186619. {
  186620. info_ptr->channels++;
  186621. /* if adding a true alpha channel not just filler */
  186622. #if !defined(PNG_1_0_X)
  186623. if (png_ptr->transformations & PNG_ADD_ALPHA)
  186624. info_ptr->color_type |= PNG_COLOR_MASK_ALPHA;
  186625. #endif
  186626. }
  186627. #endif
  186628. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED) && \
  186629. defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  186630. if(png_ptr->transformations & PNG_USER_TRANSFORM)
  186631. {
  186632. if(info_ptr->bit_depth < png_ptr->user_transform_depth)
  186633. info_ptr->bit_depth = png_ptr->user_transform_depth;
  186634. if(info_ptr->channels < png_ptr->user_transform_channels)
  186635. info_ptr->channels = png_ptr->user_transform_channels;
  186636. }
  186637. #endif
  186638. info_ptr->pixel_depth = (png_byte)(info_ptr->channels *
  186639. info_ptr->bit_depth);
  186640. info_ptr->rowbytes = PNG_ROWBYTES(info_ptr->pixel_depth,info_ptr->width);
  186641. #if !defined(PNG_READ_EXPAND_SUPPORTED)
  186642. if(png_ptr)
  186643. return;
  186644. #endif
  186645. }
  186646. /* Transform the row. The order of transformations is significant,
  186647. * and is very touchy. If you add a transformation, take care to
  186648. * decide how it fits in with the other transformations here.
  186649. */
  186650. void /* PRIVATE */
  186651. png_do_read_transformations(png_structp png_ptr)
  186652. {
  186653. png_debug(1, "in png_do_read_transformations\n");
  186654. if (png_ptr->row_buf == NULL)
  186655. {
  186656. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  186657. char msg[50];
  186658. png_snprintf2(msg, 50,
  186659. "NULL row buffer for row %ld, pass %d", png_ptr->row_number,
  186660. png_ptr->pass);
  186661. png_error(png_ptr, msg);
  186662. #else
  186663. png_error(png_ptr, "NULL row buffer");
  186664. #endif
  186665. }
  186666. #ifdef PNG_WARN_UNINITIALIZED_ROW
  186667. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  186668. /* Application has failed to call either png_read_start_image()
  186669. * or png_read_update_info() after setting transforms that expand
  186670. * pixels. This check added to libpng-1.2.19 */
  186671. #if (PNG_WARN_UNINITIALIZED_ROW==1)
  186672. png_error(png_ptr, "Uninitialized row");
  186673. #else
  186674. png_warning(png_ptr, "Uninitialized row");
  186675. #endif
  186676. #endif
  186677. #if defined(PNG_READ_EXPAND_SUPPORTED)
  186678. if (png_ptr->transformations & PNG_EXPAND)
  186679. {
  186680. if (png_ptr->row_info.color_type == PNG_COLOR_TYPE_PALETTE)
  186681. {
  186682. png_do_expand_palette(&(png_ptr->row_info), png_ptr->row_buf + 1,
  186683. png_ptr->palette, png_ptr->trans, png_ptr->num_trans);
  186684. }
  186685. else
  186686. {
  186687. if (png_ptr->num_trans &&
  186688. (png_ptr->transformations & PNG_EXPAND_tRNS))
  186689. png_do_expand(&(png_ptr->row_info), png_ptr->row_buf + 1,
  186690. &(png_ptr->trans_values));
  186691. else
  186692. png_do_expand(&(png_ptr->row_info), png_ptr->row_buf + 1,
  186693. NULL);
  186694. }
  186695. }
  186696. #endif
  186697. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  186698. if (png_ptr->flags & PNG_FLAG_STRIP_ALPHA)
  186699. png_do_strip_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  186700. PNG_FLAG_FILLER_AFTER | (png_ptr->flags & PNG_FLAG_STRIP_ALPHA));
  186701. #endif
  186702. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  186703. if (png_ptr->transformations & PNG_RGB_TO_GRAY)
  186704. {
  186705. int rgb_error =
  186706. png_do_rgb_to_gray(png_ptr, &(png_ptr->row_info), png_ptr->row_buf + 1);
  186707. if(rgb_error)
  186708. {
  186709. png_ptr->rgb_to_gray_status=1;
  186710. if((png_ptr->transformations & PNG_RGB_TO_GRAY) ==
  186711. PNG_RGB_TO_GRAY_WARN)
  186712. png_warning(png_ptr, "png_do_rgb_to_gray found nongray pixel");
  186713. if((png_ptr->transformations & PNG_RGB_TO_GRAY) ==
  186714. PNG_RGB_TO_GRAY_ERR)
  186715. png_error(png_ptr, "png_do_rgb_to_gray found nongray pixel");
  186716. }
  186717. }
  186718. #endif
  186719. /*
  186720. From Andreas Dilger e-mail to png-implement, 26 March 1998:
  186721. In most cases, the "simple transparency" should be done prior to doing
  186722. gray-to-RGB, or you will have to test 3x as many bytes to check if a
  186723. pixel is transparent. You would also need to make sure that the
  186724. transparency information is upgraded to RGB.
  186725. To summarize, the current flow is:
  186726. - Gray + simple transparency -> compare 1 or 2 gray bytes and composite
  186727. with background "in place" if transparent,
  186728. convert to RGB if necessary
  186729. - Gray + alpha -> composite with gray background and remove alpha bytes,
  186730. convert to RGB if necessary
  186731. To support RGB backgrounds for gray images we need:
  186732. - Gray + simple transparency -> convert to RGB + simple transparency, compare
  186733. 3 or 6 bytes and composite with background
  186734. "in place" if transparent (3x compare/pixel
  186735. compared to doing composite with gray bkgrnd)
  186736. - Gray + alpha -> convert to RGB + alpha, composite with background and
  186737. remove alpha bytes (3x float operations/pixel
  186738. compared with composite on gray background)
  186739. Greg's change will do this. The reason it wasn't done before is for
  186740. performance, as this increases the per-pixel operations. If we would check
  186741. in advance if the background was gray or RGB, and position the gray-to-RGB
  186742. transform appropriately, then it would save a lot of work/time.
  186743. */
  186744. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  186745. /* if gray -> RGB, do so now only if background is non-gray; else do later
  186746. * for performance reasons */
  186747. if ((png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  186748. !(png_ptr->mode & PNG_BACKGROUND_IS_GRAY))
  186749. png_do_gray_to_rgb(&(png_ptr->row_info), png_ptr->row_buf + 1);
  186750. #endif
  186751. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  186752. if ((png_ptr->transformations & PNG_BACKGROUND) &&
  186753. ((png_ptr->num_trans != 0 ) ||
  186754. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA)))
  186755. png_do_background(&(png_ptr->row_info), png_ptr->row_buf + 1,
  186756. &(png_ptr->trans_values), &(png_ptr->background)
  186757. #if defined(PNG_READ_GAMMA_SUPPORTED)
  186758. , &(png_ptr->background_1),
  186759. png_ptr->gamma_table, png_ptr->gamma_from_1,
  186760. png_ptr->gamma_to_1, png_ptr->gamma_16_table,
  186761. png_ptr->gamma_16_from_1, png_ptr->gamma_16_to_1,
  186762. png_ptr->gamma_shift
  186763. #endif
  186764. );
  186765. #endif
  186766. #if defined(PNG_READ_GAMMA_SUPPORTED)
  186767. if ((png_ptr->transformations & PNG_GAMMA) &&
  186768. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  186769. !((png_ptr->transformations & PNG_BACKGROUND) &&
  186770. ((png_ptr->num_trans != 0) ||
  186771. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA))) &&
  186772. #endif
  186773. (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE))
  186774. png_do_gamma(&(png_ptr->row_info), png_ptr->row_buf + 1,
  186775. png_ptr->gamma_table, png_ptr->gamma_16_table,
  186776. png_ptr->gamma_shift);
  186777. #endif
  186778. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  186779. if (png_ptr->transformations & PNG_16_TO_8)
  186780. png_do_chop(&(png_ptr->row_info), png_ptr->row_buf + 1);
  186781. #endif
  186782. #if defined(PNG_READ_DITHER_SUPPORTED)
  186783. if (png_ptr->transformations & PNG_DITHER)
  186784. {
  186785. png_do_dither((png_row_infop)&(png_ptr->row_info), png_ptr->row_buf + 1,
  186786. png_ptr->palette_lookup, png_ptr->dither_index);
  186787. if(png_ptr->row_info.rowbytes == (png_uint_32)0)
  186788. png_error(png_ptr, "png_do_dither returned rowbytes=0");
  186789. }
  186790. #endif
  186791. #if defined(PNG_READ_INVERT_SUPPORTED)
  186792. if (png_ptr->transformations & PNG_INVERT_MONO)
  186793. png_do_invert(&(png_ptr->row_info), png_ptr->row_buf + 1);
  186794. #endif
  186795. #if defined(PNG_READ_SHIFT_SUPPORTED)
  186796. if (png_ptr->transformations & PNG_SHIFT)
  186797. png_do_unshift(&(png_ptr->row_info), png_ptr->row_buf + 1,
  186798. &(png_ptr->shift));
  186799. #endif
  186800. #if defined(PNG_READ_PACK_SUPPORTED)
  186801. if (png_ptr->transformations & PNG_PACK)
  186802. png_do_unpack(&(png_ptr->row_info), png_ptr->row_buf + 1);
  186803. #endif
  186804. #if defined(PNG_READ_BGR_SUPPORTED)
  186805. if (png_ptr->transformations & PNG_BGR)
  186806. png_do_bgr(&(png_ptr->row_info), png_ptr->row_buf + 1);
  186807. #endif
  186808. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  186809. if (png_ptr->transformations & PNG_PACKSWAP)
  186810. png_do_packswap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  186811. #endif
  186812. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  186813. /* if gray -> RGB, do so now only if we did not do so above */
  186814. if ((png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  186815. (png_ptr->mode & PNG_BACKGROUND_IS_GRAY))
  186816. png_do_gray_to_rgb(&(png_ptr->row_info), png_ptr->row_buf + 1);
  186817. #endif
  186818. #if defined(PNG_READ_FILLER_SUPPORTED)
  186819. if (png_ptr->transformations & PNG_FILLER)
  186820. png_do_read_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  186821. (png_uint_32)png_ptr->filler, png_ptr->flags);
  186822. #endif
  186823. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  186824. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  186825. png_do_read_invert_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  186826. #endif
  186827. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  186828. if (png_ptr->transformations & PNG_SWAP_ALPHA)
  186829. png_do_read_swap_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  186830. #endif
  186831. #if defined(PNG_READ_SWAP_SUPPORTED)
  186832. if (png_ptr->transformations & PNG_SWAP_BYTES)
  186833. png_do_swap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  186834. #endif
  186835. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  186836. if (png_ptr->transformations & PNG_USER_TRANSFORM)
  186837. {
  186838. if(png_ptr->read_user_transform_fn != NULL)
  186839. (*(png_ptr->read_user_transform_fn)) /* user read transform function */
  186840. (png_ptr, /* png_ptr */
  186841. &(png_ptr->row_info), /* row_info: */
  186842. /* png_uint_32 width; width of row */
  186843. /* png_uint_32 rowbytes; number of bytes in row */
  186844. /* png_byte color_type; color type of pixels */
  186845. /* png_byte bit_depth; bit depth of samples */
  186846. /* png_byte channels; number of channels (1-4) */
  186847. /* png_byte pixel_depth; bits per pixel (depth*channels) */
  186848. png_ptr->row_buf + 1); /* start of pixel data for row */
  186849. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  186850. if(png_ptr->user_transform_depth)
  186851. png_ptr->row_info.bit_depth = png_ptr->user_transform_depth;
  186852. if(png_ptr->user_transform_channels)
  186853. png_ptr->row_info.channels = png_ptr->user_transform_channels;
  186854. #endif
  186855. png_ptr->row_info.pixel_depth = (png_byte)(png_ptr->row_info.bit_depth *
  186856. png_ptr->row_info.channels);
  186857. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  186858. png_ptr->row_info.width);
  186859. }
  186860. #endif
  186861. }
  186862. #if defined(PNG_READ_PACK_SUPPORTED)
  186863. /* Unpack pixels of 1, 2, or 4 bits per pixel into 1 byte per pixel,
  186864. * without changing the actual values. Thus, if you had a row with
  186865. * a bit depth of 1, you would end up with bytes that only contained
  186866. * the numbers 0 or 1. If you would rather they contain 0 and 255, use
  186867. * png_do_shift() after this.
  186868. */
  186869. void /* PRIVATE */
  186870. png_do_unpack(png_row_infop row_info, png_bytep row)
  186871. {
  186872. png_debug(1, "in png_do_unpack\n");
  186873. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  186874. if (row != NULL && row_info != NULL && row_info->bit_depth < 8)
  186875. #else
  186876. if (row_info->bit_depth < 8)
  186877. #endif
  186878. {
  186879. png_uint_32 i;
  186880. png_uint_32 row_width=row_info->width;
  186881. switch (row_info->bit_depth)
  186882. {
  186883. case 1:
  186884. {
  186885. png_bytep sp = row + (png_size_t)((row_width - 1) >> 3);
  186886. png_bytep dp = row + (png_size_t)row_width - 1;
  186887. png_uint_32 shift = 7 - (int)((row_width + 7) & 0x07);
  186888. for (i = 0; i < row_width; i++)
  186889. {
  186890. *dp = (png_byte)((*sp >> shift) & 0x01);
  186891. if (shift == 7)
  186892. {
  186893. shift = 0;
  186894. sp--;
  186895. }
  186896. else
  186897. shift++;
  186898. dp--;
  186899. }
  186900. break;
  186901. }
  186902. case 2:
  186903. {
  186904. png_bytep sp = row + (png_size_t)((row_width - 1) >> 2);
  186905. png_bytep dp = row + (png_size_t)row_width - 1;
  186906. png_uint_32 shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  186907. for (i = 0; i < row_width; i++)
  186908. {
  186909. *dp = (png_byte)((*sp >> shift) & 0x03);
  186910. if (shift == 6)
  186911. {
  186912. shift = 0;
  186913. sp--;
  186914. }
  186915. else
  186916. shift += 2;
  186917. dp--;
  186918. }
  186919. break;
  186920. }
  186921. case 4:
  186922. {
  186923. png_bytep sp = row + (png_size_t)((row_width - 1) >> 1);
  186924. png_bytep dp = row + (png_size_t)row_width - 1;
  186925. png_uint_32 shift = (int)((1 - ((row_width + 1) & 0x01)) << 2);
  186926. for (i = 0; i < row_width; i++)
  186927. {
  186928. *dp = (png_byte)((*sp >> shift) & 0x0f);
  186929. if (shift == 4)
  186930. {
  186931. shift = 0;
  186932. sp--;
  186933. }
  186934. else
  186935. shift = 4;
  186936. dp--;
  186937. }
  186938. break;
  186939. }
  186940. }
  186941. row_info->bit_depth = 8;
  186942. row_info->pixel_depth = (png_byte)(8 * row_info->channels);
  186943. row_info->rowbytes = row_width * row_info->channels;
  186944. }
  186945. }
  186946. #endif
  186947. #if defined(PNG_READ_SHIFT_SUPPORTED)
  186948. /* Reverse the effects of png_do_shift. This routine merely shifts the
  186949. * pixels back to their significant bits values. Thus, if you have
  186950. * a row of bit depth 8, but only 5 are significant, this will shift
  186951. * the values back to 0 through 31.
  186952. */
  186953. void /* PRIVATE */
  186954. png_do_unshift(png_row_infop row_info, png_bytep row, png_color_8p sig_bits)
  186955. {
  186956. png_debug(1, "in png_do_unshift\n");
  186957. if (
  186958. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  186959. row != NULL && row_info != NULL && sig_bits != NULL &&
  186960. #endif
  186961. row_info->color_type != PNG_COLOR_TYPE_PALETTE)
  186962. {
  186963. int shift[4];
  186964. int channels = 0;
  186965. int c;
  186966. png_uint_16 value = 0;
  186967. png_uint_32 row_width = row_info->width;
  186968. if (row_info->color_type & PNG_COLOR_MASK_COLOR)
  186969. {
  186970. shift[channels++] = row_info->bit_depth - sig_bits->red;
  186971. shift[channels++] = row_info->bit_depth - sig_bits->green;
  186972. shift[channels++] = row_info->bit_depth - sig_bits->blue;
  186973. }
  186974. else
  186975. {
  186976. shift[channels++] = row_info->bit_depth - sig_bits->gray;
  186977. }
  186978. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  186979. {
  186980. shift[channels++] = row_info->bit_depth - sig_bits->alpha;
  186981. }
  186982. for (c = 0; c < channels; c++)
  186983. {
  186984. if (shift[c] <= 0)
  186985. shift[c] = 0;
  186986. else
  186987. value = 1;
  186988. }
  186989. if (!value)
  186990. return;
  186991. switch (row_info->bit_depth)
  186992. {
  186993. case 2:
  186994. {
  186995. png_bytep bp;
  186996. png_uint_32 i;
  186997. png_uint_32 istop = row_info->rowbytes;
  186998. for (bp = row, i = 0; i < istop; i++)
  186999. {
  187000. *bp >>= 1;
  187001. *bp++ &= 0x55;
  187002. }
  187003. break;
  187004. }
  187005. case 4:
  187006. {
  187007. png_bytep bp = row;
  187008. png_uint_32 i;
  187009. png_uint_32 istop = row_info->rowbytes;
  187010. png_byte mask = (png_byte)((((int)0xf0 >> shift[0]) & (int)0xf0) |
  187011. (png_byte)((int)0xf >> shift[0]));
  187012. for (i = 0; i < istop; i++)
  187013. {
  187014. *bp >>= shift[0];
  187015. *bp++ &= mask;
  187016. }
  187017. break;
  187018. }
  187019. case 8:
  187020. {
  187021. png_bytep bp = row;
  187022. png_uint_32 i;
  187023. png_uint_32 istop = row_width * channels;
  187024. for (i = 0; i < istop; i++)
  187025. {
  187026. *bp++ >>= shift[i%channels];
  187027. }
  187028. break;
  187029. }
  187030. case 16:
  187031. {
  187032. png_bytep bp = row;
  187033. png_uint_32 i;
  187034. png_uint_32 istop = channels * row_width;
  187035. for (i = 0; i < istop; i++)
  187036. {
  187037. value = (png_uint_16)((*bp << 8) + *(bp + 1));
  187038. value >>= shift[i%channels];
  187039. *bp++ = (png_byte)(value >> 8);
  187040. *bp++ = (png_byte)(value & 0xff);
  187041. }
  187042. break;
  187043. }
  187044. }
  187045. }
  187046. }
  187047. #endif
  187048. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  187049. /* chop rows of bit depth 16 down to 8 */
  187050. void /* PRIVATE */
  187051. png_do_chop(png_row_infop row_info, png_bytep row)
  187052. {
  187053. png_debug(1, "in png_do_chop\n");
  187054. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  187055. if (row != NULL && row_info != NULL && row_info->bit_depth == 16)
  187056. #else
  187057. if (row_info->bit_depth == 16)
  187058. #endif
  187059. {
  187060. png_bytep sp = row;
  187061. png_bytep dp = row;
  187062. png_uint_32 i;
  187063. png_uint_32 istop = row_info->width * row_info->channels;
  187064. for (i = 0; i<istop; i++, sp += 2, dp++)
  187065. {
  187066. #if defined(PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED)
  187067. /* This does a more accurate scaling of the 16-bit color
  187068. * value, rather than a simple low-byte truncation.
  187069. *
  187070. * What the ideal calculation should be:
  187071. * *dp = (((((png_uint_32)(*sp) << 8) |
  187072. * (png_uint_32)(*(sp + 1))) * 255 + 127) / (png_uint_32)65535L;
  187073. *
  187074. * GRR: no, I think this is what it really should be:
  187075. * *dp = (((((png_uint_32)(*sp) << 8) |
  187076. * (png_uint_32)(*(sp + 1))) + 128L) / (png_uint_32)257L;
  187077. *
  187078. * GRR: here's the exact calculation with shifts:
  187079. * temp = (((png_uint_32)(*sp) << 8) | (png_uint_32)(*(sp + 1))) + 128L;
  187080. * *dp = (temp - (temp >> 8)) >> 8;
  187081. *
  187082. * Approximate calculation with shift/add instead of multiply/divide:
  187083. * *dp = ((((png_uint_32)(*sp) << 8) |
  187084. * (png_uint_32)((int)(*(sp + 1)) - *sp)) + 128) >> 8;
  187085. *
  187086. * What we actually do to avoid extra shifting and conversion:
  187087. */
  187088. *dp = *sp + ((((int)(*(sp + 1)) - *sp) > 128) ? 1 : 0);
  187089. #else
  187090. /* Simply discard the low order byte */
  187091. *dp = *sp;
  187092. #endif
  187093. }
  187094. row_info->bit_depth = 8;
  187095. row_info->pixel_depth = (png_byte)(8 * row_info->channels);
  187096. row_info->rowbytes = row_info->width * row_info->channels;
  187097. }
  187098. }
  187099. #endif
  187100. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  187101. void /* PRIVATE */
  187102. png_do_read_swap_alpha(png_row_infop row_info, png_bytep row)
  187103. {
  187104. png_debug(1, "in png_do_read_swap_alpha\n");
  187105. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  187106. if (row != NULL && row_info != NULL)
  187107. #endif
  187108. {
  187109. png_uint_32 row_width = row_info->width;
  187110. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  187111. {
  187112. /* This converts from RGBA to ARGB */
  187113. if (row_info->bit_depth == 8)
  187114. {
  187115. png_bytep sp = row + row_info->rowbytes;
  187116. png_bytep dp = sp;
  187117. png_byte save;
  187118. png_uint_32 i;
  187119. for (i = 0; i < row_width; i++)
  187120. {
  187121. save = *(--sp);
  187122. *(--dp) = *(--sp);
  187123. *(--dp) = *(--sp);
  187124. *(--dp) = *(--sp);
  187125. *(--dp) = save;
  187126. }
  187127. }
  187128. /* This converts from RRGGBBAA to AARRGGBB */
  187129. else
  187130. {
  187131. png_bytep sp = row + row_info->rowbytes;
  187132. png_bytep dp = sp;
  187133. png_byte save[2];
  187134. png_uint_32 i;
  187135. for (i = 0; i < row_width; i++)
  187136. {
  187137. save[0] = *(--sp);
  187138. save[1] = *(--sp);
  187139. *(--dp) = *(--sp);
  187140. *(--dp) = *(--sp);
  187141. *(--dp) = *(--sp);
  187142. *(--dp) = *(--sp);
  187143. *(--dp) = *(--sp);
  187144. *(--dp) = *(--sp);
  187145. *(--dp) = save[0];
  187146. *(--dp) = save[1];
  187147. }
  187148. }
  187149. }
  187150. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  187151. {
  187152. /* This converts from GA to AG */
  187153. if (row_info->bit_depth == 8)
  187154. {
  187155. png_bytep sp = row + row_info->rowbytes;
  187156. png_bytep dp = sp;
  187157. png_byte save;
  187158. png_uint_32 i;
  187159. for (i = 0; i < row_width; i++)
  187160. {
  187161. save = *(--sp);
  187162. *(--dp) = *(--sp);
  187163. *(--dp) = save;
  187164. }
  187165. }
  187166. /* This converts from GGAA to AAGG */
  187167. else
  187168. {
  187169. png_bytep sp = row + row_info->rowbytes;
  187170. png_bytep dp = sp;
  187171. png_byte save[2];
  187172. png_uint_32 i;
  187173. for (i = 0; i < row_width; i++)
  187174. {
  187175. save[0] = *(--sp);
  187176. save[1] = *(--sp);
  187177. *(--dp) = *(--sp);
  187178. *(--dp) = *(--sp);
  187179. *(--dp) = save[0];
  187180. *(--dp) = save[1];
  187181. }
  187182. }
  187183. }
  187184. }
  187185. }
  187186. #endif
  187187. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  187188. void /* PRIVATE */
  187189. png_do_read_invert_alpha(png_row_infop row_info, png_bytep row)
  187190. {
  187191. png_debug(1, "in png_do_read_invert_alpha\n");
  187192. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  187193. if (row != NULL && row_info != NULL)
  187194. #endif
  187195. {
  187196. png_uint_32 row_width = row_info->width;
  187197. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  187198. {
  187199. /* This inverts the alpha channel in RGBA */
  187200. if (row_info->bit_depth == 8)
  187201. {
  187202. png_bytep sp = row + row_info->rowbytes;
  187203. png_bytep dp = sp;
  187204. png_uint_32 i;
  187205. for (i = 0; i < row_width; i++)
  187206. {
  187207. *(--dp) = (png_byte)(255 - *(--sp));
  187208. /* This does nothing:
  187209. *(--dp) = *(--sp);
  187210. *(--dp) = *(--sp);
  187211. *(--dp) = *(--sp);
  187212. We can replace it with:
  187213. */
  187214. sp-=3;
  187215. dp=sp;
  187216. }
  187217. }
  187218. /* This inverts the alpha channel in RRGGBBAA */
  187219. else
  187220. {
  187221. png_bytep sp = row + row_info->rowbytes;
  187222. png_bytep dp = sp;
  187223. png_uint_32 i;
  187224. for (i = 0; i < row_width; i++)
  187225. {
  187226. *(--dp) = (png_byte)(255 - *(--sp));
  187227. *(--dp) = (png_byte)(255 - *(--sp));
  187228. /* This does nothing:
  187229. *(--dp) = *(--sp);
  187230. *(--dp) = *(--sp);
  187231. *(--dp) = *(--sp);
  187232. *(--dp) = *(--sp);
  187233. *(--dp) = *(--sp);
  187234. *(--dp) = *(--sp);
  187235. We can replace it with:
  187236. */
  187237. sp-=6;
  187238. dp=sp;
  187239. }
  187240. }
  187241. }
  187242. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  187243. {
  187244. /* This inverts the alpha channel in GA */
  187245. if (row_info->bit_depth == 8)
  187246. {
  187247. png_bytep sp = row + row_info->rowbytes;
  187248. png_bytep dp = sp;
  187249. png_uint_32 i;
  187250. for (i = 0; i < row_width; i++)
  187251. {
  187252. *(--dp) = (png_byte)(255 - *(--sp));
  187253. *(--dp) = *(--sp);
  187254. }
  187255. }
  187256. /* This inverts the alpha channel in GGAA */
  187257. else
  187258. {
  187259. png_bytep sp = row + row_info->rowbytes;
  187260. png_bytep dp = sp;
  187261. png_uint_32 i;
  187262. for (i = 0; i < row_width; i++)
  187263. {
  187264. *(--dp) = (png_byte)(255 - *(--sp));
  187265. *(--dp) = (png_byte)(255 - *(--sp));
  187266. /*
  187267. *(--dp) = *(--sp);
  187268. *(--dp) = *(--sp);
  187269. */
  187270. sp-=2;
  187271. dp=sp;
  187272. }
  187273. }
  187274. }
  187275. }
  187276. }
  187277. #endif
  187278. #if defined(PNG_READ_FILLER_SUPPORTED)
  187279. /* Add filler channel if we have RGB color */
  187280. void /* PRIVATE */
  187281. png_do_read_filler(png_row_infop row_info, png_bytep row,
  187282. png_uint_32 filler, png_uint_32 flags)
  187283. {
  187284. png_uint_32 i;
  187285. png_uint_32 row_width = row_info->width;
  187286. png_byte hi_filler = (png_byte)((filler>>8) & 0xff);
  187287. png_byte lo_filler = (png_byte)(filler & 0xff);
  187288. png_debug(1, "in png_do_read_filler\n");
  187289. if (
  187290. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  187291. row != NULL && row_info != NULL &&
  187292. #endif
  187293. row_info->color_type == PNG_COLOR_TYPE_GRAY)
  187294. {
  187295. if(row_info->bit_depth == 8)
  187296. {
  187297. /* This changes the data from G to GX */
  187298. if (flags & PNG_FLAG_FILLER_AFTER)
  187299. {
  187300. png_bytep sp = row + (png_size_t)row_width;
  187301. png_bytep dp = sp + (png_size_t)row_width;
  187302. for (i = 1; i < row_width; i++)
  187303. {
  187304. *(--dp) = lo_filler;
  187305. *(--dp) = *(--sp);
  187306. }
  187307. *(--dp) = lo_filler;
  187308. row_info->channels = 2;
  187309. row_info->pixel_depth = 16;
  187310. row_info->rowbytes = row_width * 2;
  187311. }
  187312. /* This changes the data from G to XG */
  187313. else
  187314. {
  187315. png_bytep sp = row + (png_size_t)row_width;
  187316. png_bytep dp = sp + (png_size_t)row_width;
  187317. for (i = 0; i < row_width; i++)
  187318. {
  187319. *(--dp) = *(--sp);
  187320. *(--dp) = lo_filler;
  187321. }
  187322. row_info->channels = 2;
  187323. row_info->pixel_depth = 16;
  187324. row_info->rowbytes = row_width * 2;
  187325. }
  187326. }
  187327. else if(row_info->bit_depth == 16)
  187328. {
  187329. /* This changes the data from GG to GGXX */
  187330. if (flags & PNG_FLAG_FILLER_AFTER)
  187331. {
  187332. png_bytep sp = row + (png_size_t)row_width * 2;
  187333. png_bytep dp = sp + (png_size_t)row_width * 2;
  187334. for (i = 1; i < row_width; i++)
  187335. {
  187336. *(--dp) = hi_filler;
  187337. *(--dp) = lo_filler;
  187338. *(--dp) = *(--sp);
  187339. *(--dp) = *(--sp);
  187340. }
  187341. *(--dp) = hi_filler;
  187342. *(--dp) = lo_filler;
  187343. row_info->channels = 2;
  187344. row_info->pixel_depth = 32;
  187345. row_info->rowbytes = row_width * 4;
  187346. }
  187347. /* This changes the data from GG to XXGG */
  187348. else
  187349. {
  187350. png_bytep sp = row + (png_size_t)row_width * 2;
  187351. png_bytep dp = sp + (png_size_t)row_width * 2;
  187352. for (i = 0; i < row_width; i++)
  187353. {
  187354. *(--dp) = *(--sp);
  187355. *(--dp) = *(--sp);
  187356. *(--dp) = hi_filler;
  187357. *(--dp) = lo_filler;
  187358. }
  187359. row_info->channels = 2;
  187360. row_info->pixel_depth = 32;
  187361. row_info->rowbytes = row_width * 4;
  187362. }
  187363. }
  187364. } /* COLOR_TYPE == GRAY */
  187365. else if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  187366. {
  187367. if(row_info->bit_depth == 8)
  187368. {
  187369. /* This changes the data from RGB to RGBX */
  187370. if (flags & PNG_FLAG_FILLER_AFTER)
  187371. {
  187372. png_bytep sp = row + (png_size_t)row_width * 3;
  187373. png_bytep dp = sp + (png_size_t)row_width;
  187374. for (i = 1; i < row_width; i++)
  187375. {
  187376. *(--dp) = lo_filler;
  187377. *(--dp) = *(--sp);
  187378. *(--dp) = *(--sp);
  187379. *(--dp) = *(--sp);
  187380. }
  187381. *(--dp) = lo_filler;
  187382. row_info->channels = 4;
  187383. row_info->pixel_depth = 32;
  187384. row_info->rowbytes = row_width * 4;
  187385. }
  187386. /* This changes the data from RGB to XRGB */
  187387. else
  187388. {
  187389. png_bytep sp = row + (png_size_t)row_width * 3;
  187390. png_bytep dp = sp + (png_size_t)row_width;
  187391. for (i = 0; i < row_width; i++)
  187392. {
  187393. *(--dp) = *(--sp);
  187394. *(--dp) = *(--sp);
  187395. *(--dp) = *(--sp);
  187396. *(--dp) = lo_filler;
  187397. }
  187398. row_info->channels = 4;
  187399. row_info->pixel_depth = 32;
  187400. row_info->rowbytes = row_width * 4;
  187401. }
  187402. }
  187403. else if(row_info->bit_depth == 16)
  187404. {
  187405. /* This changes the data from RRGGBB to RRGGBBXX */
  187406. if (flags & PNG_FLAG_FILLER_AFTER)
  187407. {
  187408. png_bytep sp = row + (png_size_t)row_width * 6;
  187409. png_bytep dp = sp + (png_size_t)row_width * 2;
  187410. for (i = 1; i < row_width; i++)
  187411. {
  187412. *(--dp) = hi_filler;
  187413. *(--dp) = lo_filler;
  187414. *(--dp) = *(--sp);
  187415. *(--dp) = *(--sp);
  187416. *(--dp) = *(--sp);
  187417. *(--dp) = *(--sp);
  187418. *(--dp) = *(--sp);
  187419. *(--dp) = *(--sp);
  187420. }
  187421. *(--dp) = hi_filler;
  187422. *(--dp) = lo_filler;
  187423. row_info->channels = 4;
  187424. row_info->pixel_depth = 64;
  187425. row_info->rowbytes = row_width * 8;
  187426. }
  187427. /* This changes the data from RRGGBB to XXRRGGBB */
  187428. else
  187429. {
  187430. png_bytep sp = row + (png_size_t)row_width * 6;
  187431. png_bytep dp = sp + (png_size_t)row_width * 2;
  187432. for (i = 0; i < row_width; i++)
  187433. {
  187434. *(--dp) = *(--sp);
  187435. *(--dp) = *(--sp);
  187436. *(--dp) = *(--sp);
  187437. *(--dp) = *(--sp);
  187438. *(--dp) = *(--sp);
  187439. *(--dp) = *(--sp);
  187440. *(--dp) = hi_filler;
  187441. *(--dp) = lo_filler;
  187442. }
  187443. row_info->channels = 4;
  187444. row_info->pixel_depth = 64;
  187445. row_info->rowbytes = row_width * 8;
  187446. }
  187447. }
  187448. } /* COLOR_TYPE == RGB */
  187449. }
  187450. #endif
  187451. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  187452. /* expand grayscale files to RGB, with or without alpha */
  187453. void /* PRIVATE */
  187454. png_do_gray_to_rgb(png_row_infop row_info, png_bytep row)
  187455. {
  187456. png_uint_32 i;
  187457. png_uint_32 row_width = row_info->width;
  187458. png_debug(1, "in png_do_gray_to_rgb\n");
  187459. if (row_info->bit_depth >= 8 &&
  187460. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  187461. row != NULL && row_info != NULL &&
  187462. #endif
  187463. !(row_info->color_type & PNG_COLOR_MASK_COLOR))
  187464. {
  187465. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  187466. {
  187467. if (row_info->bit_depth == 8)
  187468. {
  187469. png_bytep sp = row + (png_size_t)row_width - 1;
  187470. png_bytep dp = sp + (png_size_t)row_width * 2;
  187471. for (i = 0; i < row_width; i++)
  187472. {
  187473. *(dp--) = *sp;
  187474. *(dp--) = *sp;
  187475. *(dp--) = *(sp--);
  187476. }
  187477. }
  187478. else
  187479. {
  187480. png_bytep sp = row + (png_size_t)row_width * 2 - 1;
  187481. png_bytep dp = sp + (png_size_t)row_width * 4;
  187482. for (i = 0; i < row_width; i++)
  187483. {
  187484. *(dp--) = *sp;
  187485. *(dp--) = *(sp - 1);
  187486. *(dp--) = *sp;
  187487. *(dp--) = *(sp - 1);
  187488. *(dp--) = *(sp--);
  187489. *(dp--) = *(sp--);
  187490. }
  187491. }
  187492. }
  187493. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  187494. {
  187495. if (row_info->bit_depth == 8)
  187496. {
  187497. png_bytep sp = row + (png_size_t)row_width * 2 - 1;
  187498. png_bytep dp = sp + (png_size_t)row_width * 2;
  187499. for (i = 0; i < row_width; i++)
  187500. {
  187501. *(dp--) = *(sp--);
  187502. *(dp--) = *sp;
  187503. *(dp--) = *sp;
  187504. *(dp--) = *(sp--);
  187505. }
  187506. }
  187507. else
  187508. {
  187509. png_bytep sp = row + (png_size_t)row_width * 4 - 1;
  187510. png_bytep dp = sp + (png_size_t)row_width * 4;
  187511. for (i = 0; i < row_width; i++)
  187512. {
  187513. *(dp--) = *(sp--);
  187514. *(dp--) = *(sp--);
  187515. *(dp--) = *sp;
  187516. *(dp--) = *(sp - 1);
  187517. *(dp--) = *sp;
  187518. *(dp--) = *(sp - 1);
  187519. *(dp--) = *(sp--);
  187520. *(dp--) = *(sp--);
  187521. }
  187522. }
  187523. }
  187524. row_info->channels += (png_byte)2;
  187525. row_info->color_type |= PNG_COLOR_MASK_COLOR;
  187526. row_info->pixel_depth = (png_byte)(row_info->channels *
  187527. row_info->bit_depth);
  187528. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  187529. }
  187530. }
  187531. #endif
  187532. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  187533. /* reduce RGB files to grayscale, with or without alpha
  187534. * using the equation given in Poynton's ColorFAQ at
  187535. * <http://www.inforamp.net/~poynton/>
  187536. * Copyright (c) 1998-01-04 Charles Poynton poynton at inforamp.net
  187537. *
  187538. * Y = 0.212671 * R + 0.715160 * G + 0.072169 * B
  187539. *
  187540. * We approximate this with
  187541. *
  187542. * Y = 0.21268 * R + 0.7151 * G + 0.07217 * B
  187543. *
  187544. * which can be expressed with integers as
  187545. *
  187546. * Y = (6969 * R + 23434 * G + 2365 * B)/32768
  187547. *
  187548. * The calculation is to be done in a linear colorspace.
  187549. *
  187550. * Other integer coefficents can be used via png_set_rgb_to_gray().
  187551. */
  187552. int /* PRIVATE */
  187553. png_do_rgb_to_gray(png_structp png_ptr, png_row_infop row_info, png_bytep row)
  187554. {
  187555. png_uint_32 i;
  187556. png_uint_32 row_width = row_info->width;
  187557. int rgb_error = 0;
  187558. png_debug(1, "in png_do_rgb_to_gray\n");
  187559. if (
  187560. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  187561. row != NULL && row_info != NULL &&
  187562. #endif
  187563. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  187564. {
  187565. png_uint_32 rc = png_ptr->rgb_to_gray_red_coeff;
  187566. png_uint_32 gc = png_ptr->rgb_to_gray_green_coeff;
  187567. png_uint_32 bc = png_ptr->rgb_to_gray_blue_coeff;
  187568. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  187569. {
  187570. if (row_info->bit_depth == 8)
  187571. {
  187572. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  187573. if (png_ptr->gamma_from_1 != NULL && png_ptr->gamma_to_1 != NULL)
  187574. {
  187575. png_bytep sp = row;
  187576. png_bytep dp = row;
  187577. for (i = 0; i < row_width; i++)
  187578. {
  187579. png_byte red = png_ptr->gamma_to_1[*(sp++)];
  187580. png_byte green = png_ptr->gamma_to_1[*(sp++)];
  187581. png_byte blue = png_ptr->gamma_to_1[*(sp++)];
  187582. if(red != green || red != blue)
  187583. {
  187584. rgb_error |= 1;
  187585. *(dp++) = png_ptr->gamma_from_1[
  187586. (rc*red+gc*green+bc*blue)>>15];
  187587. }
  187588. else
  187589. *(dp++) = *(sp-1);
  187590. }
  187591. }
  187592. else
  187593. #endif
  187594. {
  187595. png_bytep sp = row;
  187596. png_bytep dp = row;
  187597. for (i = 0; i < row_width; i++)
  187598. {
  187599. png_byte red = *(sp++);
  187600. png_byte green = *(sp++);
  187601. png_byte blue = *(sp++);
  187602. if(red != green || red != blue)
  187603. {
  187604. rgb_error |= 1;
  187605. *(dp++) = (png_byte)((rc*red+gc*green+bc*blue)>>15);
  187606. }
  187607. else
  187608. *(dp++) = *(sp-1);
  187609. }
  187610. }
  187611. }
  187612. else /* RGB bit_depth == 16 */
  187613. {
  187614. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  187615. if (png_ptr->gamma_16_to_1 != NULL &&
  187616. png_ptr->gamma_16_from_1 != NULL)
  187617. {
  187618. png_bytep sp = row;
  187619. png_bytep dp = row;
  187620. for (i = 0; i < row_width; i++)
  187621. {
  187622. png_uint_16 red, green, blue, w;
  187623. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  187624. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  187625. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  187626. if(red == green && red == blue)
  187627. w = red;
  187628. else
  187629. {
  187630. png_uint_16 red_1 = png_ptr->gamma_16_to_1[(red&0xff) >>
  187631. png_ptr->gamma_shift][red>>8];
  187632. png_uint_16 green_1 = png_ptr->gamma_16_to_1[(green&0xff) >>
  187633. png_ptr->gamma_shift][green>>8];
  187634. png_uint_16 blue_1 = png_ptr->gamma_16_to_1[(blue&0xff) >>
  187635. png_ptr->gamma_shift][blue>>8];
  187636. png_uint_16 gray16 = (png_uint_16)((rc*red_1 + gc*green_1
  187637. + bc*blue_1)>>15);
  187638. w = png_ptr->gamma_16_from_1[(gray16&0xff) >>
  187639. png_ptr->gamma_shift][gray16 >> 8];
  187640. rgb_error |= 1;
  187641. }
  187642. *(dp++) = (png_byte)((w>>8) & 0xff);
  187643. *(dp++) = (png_byte)(w & 0xff);
  187644. }
  187645. }
  187646. else
  187647. #endif
  187648. {
  187649. png_bytep sp = row;
  187650. png_bytep dp = row;
  187651. for (i = 0; i < row_width; i++)
  187652. {
  187653. png_uint_16 red, green, blue, gray16;
  187654. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  187655. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  187656. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  187657. if(red != green || red != blue)
  187658. rgb_error |= 1;
  187659. gray16 = (png_uint_16)((rc*red + gc*green + bc*blue)>>15);
  187660. *(dp++) = (png_byte)((gray16>>8) & 0xff);
  187661. *(dp++) = (png_byte)(gray16 & 0xff);
  187662. }
  187663. }
  187664. }
  187665. }
  187666. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  187667. {
  187668. if (row_info->bit_depth == 8)
  187669. {
  187670. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  187671. if (png_ptr->gamma_from_1 != NULL && png_ptr->gamma_to_1 != NULL)
  187672. {
  187673. png_bytep sp = row;
  187674. png_bytep dp = row;
  187675. for (i = 0; i < row_width; i++)
  187676. {
  187677. png_byte red = png_ptr->gamma_to_1[*(sp++)];
  187678. png_byte green = png_ptr->gamma_to_1[*(sp++)];
  187679. png_byte blue = png_ptr->gamma_to_1[*(sp++)];
  187680. if(red != green || red != blue)
  187681. rgb_error |= 1;
  187682. *(dp++) = png_ptr->gamma_from_1
  187683. [(rc*red + gc*green + bc*blue)>>15];
  187684. *(dp++) = *(sp++); /* alpha */
  187685. }
  187686. }
  187687. else
  187688. #endif
  187689. {
  187690. png_bytep sp = row;
  187691. png_bytep dp = row;
  187692. for (i = 0; i < row_width; i++)
  187693. {
  187694. png_byte red = *(sp++);
  187695. png_byte green = *(sp++);
  187696. png_byte blue = *(sp++);
  187697. if(red != green || red != blue)
  187698. rgb_error |= 1;
  187699. *(dp++) = (png_byte)((rc*red + gc*green + bc*blue)>>15);
  187700. *(dp++) = *(sp++); /* alpha */
  187701. }
  187702. }
  187703. }
  187704. else /* RGBA bit_depth == 16 */
  187705. {
  187706. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  187707. if (png_ptr->gamma_16_to_1 != NULL &&
  187708. png_ptr->gamma_16_from_1 != NULL)
  187709. {
  187710. png_bytep sp = row;
  187711. png_bytep dp = row;
  187712. for (i = 0; i < row_width; i++)
  187713. {
  187714. png_uint_16 red, green, blue, w;
  187715. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  187716. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  187717. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  187718. if(red == green && red == blue)
  187719. w = red;
  187720. else
  187721. {
  187722. png_uint_16 red_1 = png_ptr->gamma_16_to_1[(red&0xff) >>
  187723. png_ptr->gamma_shift][red>>8];
  187724. png_uint_16 green_1 = png_ptr->gamma_16_to_1[(green&0xff) >>
  187725. png_ptr->gamma_shift][green>>8];
  187726. png_uint_16 blue_1 = png_ptr->gamma_16_to_1[(blue&0xff) >>
  187727. png_ptr->gamma_shift][blue>>8];
  187728. png_uint_16 gray16 = (png_uint_16)((rc * red_1
  187729. + gc * green_1 + bc * blue_1)>>15);
  187730. w = png_ptr->gamma_16_from_1[(gray16&0xff) >>
  187731. png_ptr->gamma_shift][gray16 >> 8];
  187732. rgb_error |= 1;
  187733. }
  187734. *(dp++) = (png_byte)((w>>8) & 0xff);
  187735. *(dp++) = (png_byte)(w & 0xff);
  187736. *(dp++) = *(sp++); /* alpha */
  187737. *(dp++) = *(sp++);
  187738. }
  187739. }
  187740. else
  187741. #endif
  187742. {
  187743. png_bytep sp = row;
  187744. png_bytep dp = row;
  187745. for (i = 0; i < row_width; i++)
  187746. {
  187747. png_uint_16 red, green, blue, gray16;
  187748. red = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  187749. green = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  187750. blue = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  187751. if(red != green || red != blue)
  187752. rgb_error |= 1;
  187753. gray16 = (png_uint_16)((rc*red + gc*green + bc*blue)>>15);
  187754. *(dp++) = (png_byte)((gray16>>8) & 0xff);
  187755. *(dp++) = (png_byte)(gray16 & 0xff);
  187756. *(dp++) = *(sp++); /* alpha */
  187757. *(dp++) = *(sp++);
  187758. }
  187759. }
  187760. }
  187761. }
  187762. row_info->channels -= (png_byte)2;
  187763. row_info->color_type &= ~PNG_COLOR_MASK_COLOR;
  187764. row_info->pixel_depth = (png_byte)(row_info->channels *
  187765. row_info->bit_depth);
  187766. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  187767. }
  187768. return rgb_error;
  187769. }
  187770. #endif
  187771. /* Build a grayscale palette. Palette is assumed to be 1 << bit_depth
  187772. * large of png_color. This lets grayscale images be treated as
  187773. * paletted. Most useful for gamma correction and simplification
  187774. * of code.
  187775. */
  187776. void PNGAPI
  187777. png_build_grayscale_palette(int bit_depth, png_colorp palette)
  187778. {
  187779. int num_palette;
  187780. int color_inc;
  187781. int i;
  187782. int v;
  187783. png_debug(1, "in png_do_build_grayscale_palette\n");
  187784. if (palette == NULL)
  187785. return;
  187786. switch (bit_depth)
  187787. {
  187788. case 1:
  187789. num_palette = 2;
  187790. color_inc = 0xff;
  187791. break;
  187792. case 2:
  187793. num_palette = 4;
  187794. color_inc = 0x55;
  187795. break;
  187796. case 4:
  187797. num_palette = 16;
  187798. color_inc = 0x11;
  187799. break;
  187800. case 8:
  187801. num_palette = 256;
  187802. color_inc = 1;
  187803. break;
  187804. default:
  187805. num_palette = 0;
  187806. color_inc = 0;
  187807. break;
  187808. }
  187809. for (i = 0, v = 0; i < num_palette; i++, v += color_inc)
  187810. {
  187811. palette[i].red = (png_byte)v;
  187812. palette[i].green = (png_byte)v;
  187813. palette[i].blue = (png_byte)v;
  187814. }
  187815. }
  187816. /* This function is currently unused. Do we really need it? */
  187817. #if defined(PNG_READ_DITHER_SUPPORTED) && defined(PNG_CORRECT_PALETTE_SUPPORTED)
  187818. void /* PRIVATE */
  187819. png_correct_palette(png_structp png_ptr, png_colorp palette,
  187820. int num_palette)
  187821. {
  187822. png_debug(1, "in png_correct_palette\n");
  187823. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && \
  187824. defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  187825. if (png_ptr->transformations & (PNG_GAMMA | PNG_BACKGROUND))
  187826. {
  187827. png_color back, back_1;
  187828. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_FILE)
  187829. {
  187830. back.red = png_ptr->gamma_table[png_ptr->background.red];
  187831. back.green = png_ptr->gamma_table[png_ptr->background.green];
  187832. back.blue = png_ptr->gamma_table[png_ptr->background.blue];
  187833. back_1.red = png_ptr->gamma_to_1[png_ptr->background.red];
  187834. back_1.green = png_ptr->gamma_to_1[png_ptr->background.green];
  187835. back_1.blue = png_ptr->gamma_to_1[png_ptr->background.blue];
  187836. }
  187837. else
  187838. {
  187839. double g;
  187840. g = 1.0 / (png_ptr->background_gamma * png_ptr->screen_gamma);
  187841. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_SCREEN ||
  187842. fabs(g - 1.0) < PNG_GAMMA_THRESHOLD)
  187843. {
  187844. back.red = png_ptr->background.red;
  187845. back.green = png_ptr->background.green;
  187846. back.blue = png_ptr->background.blue;
  187847. }
  187848. else
  187849. {
  187850. back.red =
  187851. (png_byte)(pow((double)png_ptr->background.red/255, g) *
  187852. 255.0 + 0.5);
  187853. back.green =
  187854. (png_byte)(pow((double)png_ptr->background.green/255, g) *
  187855. 255.0 + 0.5);
  187856. back.blue =
  187857. (png_byte)(pow((double)png_ptr->background.blue/255, g) *
  187858. 255.0 + 0.5);
  187859. }
  187860. g = 1.0 / png_ptr->background_gamma;
  187861. back_1.red =
  187862. (png_byte)(pow((double)png_ptr->background.red/255, g) *
  187863. 255.0 + 0.5);
  187864. back_1.green =
  187865. (png_byte)(pow((double)png_ptr->background.green/255, g) *
  187866. 255.0 + 0.5);
  187867. back_1.blue =
  187868. (png_byte)(pow((double)png_ptr->background.blue/255, g) *
  187869. 255.0 + 0.5);
  187870. }
  187871. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  187872. {
  187873. png_uint_32 i;
  187874. for (i = 0; i < (png_uint_32)num_palette; i++)
  187875. {
  187876. if (i < png_ptr->num_trans && png_ptr->trans[i] == 0)
  187877. {
  187878. palette[i] = back;
  187879. }
  187880. else if (i < png_ptr->num_trans && png_ptr->trans[i] != 0xff)
  187881. {
  187882. png_byte v, w;
  187883. v = png_ptr->gamma_to_1[png_ptr->palette[i].red];
  187884. png_composite(w, v, png_ptr->trans[i], back_1.red);
  187885. palette[i].red = png_ptr->gamma_from_1[w];
  187886. v = png_ptr->gamma_to_1[png_ptr->palette[i].green];
  187887. png_composite(w, v, png_ptr->trans[i], back_1.green);
  187888. palette[i].green = png_ptr->gamma_from_1[w];
  187889. v = png_ptr->gamma_to_1[png_ptr->palette[i].blue];
  187890. png_composite(w, v, png_ptr->trans[i], back_1.blue);
  187891. palette[i].blue = png_ptr->gamma_from_1[w];
  187892. }
  187893. else
  187894. {
  187895. palette[i].red = png_ptr->gamma_table[palette[i].red];
  187896. palette[i].green = png_ptr->gamma_table[palette[i].green];
  187897. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  187898. }
  187899. }
  187900. }
  187901. else
  187902. {
  187903. int i;
  187904. for (i = 0; i < num_palette; i++)
  187905. {
  187906. if (palette[i].red == (png_byte)png_ptr->trans_values.gray)
  187907. {
  187908. palette[i] = back;
  187909. }
  187910. else
  187911. {
  187912. palette[i].red = png_ptr->gamma_table[palette[i].red];
  187913. palette[i].green = png_ptr->gamma_table[palette[i].green];
  187914. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  187915. }
  187916. }
  187917. }
  187918. }
  187919. else
  187920. #endif
  187921. #if defined(PNG_READ_GAMMA_SUPPORTED)
  187922. if (png_ptr->transformations & PNG_GAMMA)
  187923. {
  187924. int i;
  187925. for (i = 0; i < num_palette; i++)
  187926. {
  187927. palette[i].red = png_ptr->gamma_table[palette[i].red];
  187928. palette[i].green = png_ptr->gamma_table[palette[i].green];
  187929. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  187930. }
  187931. }
  187932. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  187933. else
  187934. #endif
  187935. #endif
  187936. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  187937. if (png_ptr->transformations & PNG_BACKGROUND)
  187938. {
  187939. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  187940. {
  187941. png_color back;
  187942. back.red = (png_byte)png_ptr->background.red;
  187943. back.green = (png_byte)png_ptr->background.green;
  187944. back.blue = (png_byte)png_ptr->background.blue;
  187945. for (i = 0; i < (int)png_ptr->num_trans; i++)
  187946. {
  187947. if (png_ptr->trans[i] == 0)
  187948. {
  187949. palette[i].red = back.red;
  187950. palette[i].green = back.green;
  187951. palette[i].blue = back.blue;
  187952. }
  187953. else if (png_ptr->trans[i] != 0xff)
  187954. {
  187955. png_composite(palette[i].red, png_ptr->palette[i].red,
  187956. png_ptr->trans[i], back.red);
  187957. png_composite(palette[i].green, png_ptr->palette[i].green,
  187958. png_ptr->trans[i], back.green);
  187959. png_composite(palette[i].blue, png_ptr->palette[i].blue,
  187960. png_ptr->trans[i], back.blue);
  187961. }
  187962. }
  187963. }
  187964. else /* assume grayscale palette (what else could it be?) */
  187965. {
  187966. int i;
  187967. for (i = 0; i < num_palette; i++)
  187968. {
  187969. if (i == (png_byte)png_ptr->trans_values.gray)
  187970. {
  187971. palette[i].red = (png_byte)png_ptr->background.red;
  187972. palette[i].green = (png_byte)png_ptr->background.green;
  187973. palette[i].blue = (png_byte)png_ptr->background.blue;
  187974. }
  187975. }
  187976. }
  187977. }
  187978. #endif
  187979. }
  187980. #endif
  187981. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  187982. /* Replace any alpha or transparency with the supplied background color.
  187983. * "background" is already in the screen gamma, while "background_1" is
  187984. * at a gamma of 1.0. Paletted files have already been taken care of.
  187985. */
  187986. void /* PRIVATE */
  187987. png_do_background(png_row_infop row_info, png_bytep row,
  187988. png_color_16p trans_values, png_color_16p background
  187989. #if defined(PNG_READ_GAMMA_SUPPORTED)
  187990. , png_color_16p background_1,
  187991. png_bytep gamma_table, png_bytep gamma_from_1, png_bytep gamma_to_1,
  187992. png_uint_16pp gamma_16, png_uint_16pp gamma_16_from_1,
  187993. png_uint_16pp gamma_16_to_1, int gamma_shift
  187994. #endif
  187995. )
  187996. {
  187997. png_bytep sp, dp;
  187998. png_uint_32 i;
  187999. png_uint_32 row_width=row_info->width;
  188000. int shift;
  188001. png_debug(1, "in png_do_background\n");
  188002. if (background != NULL &&
  188003. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  188004. row != NULL && row_info != NULL &&
  188005. #endif
  188006. (!(row_info->color_type & PNG_COLOR_MASK_ALPHA) ||
  188007. (row_info->color_type != PNG_COLOR_TYPE_PALETTE && trans_values)))
  188008. {
  188009. switch (row_info->color_type)
  188010. {
  188011. case PNG_COLOR_TYPE_GRAY:
  188012. {
  188013. switch (row_info->bit_depth)
  188014. {
  188015. case 1:
  188016. {
  188017. sp = row;
  188018. shift = 7;
  188019. for (i = 0; i < row_width; i++)
  188020. {
  188021. if ((png_uint_16)((*sp >> shift) & 0x01)
  188022. == trans_values->gray)
  188023. {
  188024. *sp &= (png_byte)((0x7f7f >> (7 - shift)) & 0xff);
  188025. *sp |= (png_byte)(background->gray << shift);
  188026. }
  188027. if (!shift)
  188028. {
  188029. shift = 7;
  188030. sp++;
  188031. }
  188032. else
  188033. shift--;
  188034. }
  188035. break;
  188036. }
  188037. case 2:
  188038. {
  188039. #if defined(PNG_READ_GAMMA_SUPPORTED)
  188040. if (gamma_table != NULL)
  188041. {
  188042. sp = row;
  188043. shift = 6;
  188044. for (i = 0; i < row_width; i++)
  188045. {
  188046. if ((png_uint_16)((*sp >> shift) & 0x03)
  188047. == trans_values->gray)
  188048. {
  188049. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  188050. *sp |= (png_byte)(background->gray << shift);
  188051. }
  188052. else
  188053. {
  188054. png_byte p = (png_byte)((*sp >> shift) & 0x03);
  188055. png_byte g = (png_byte)((gamma_table [p | (p << 2) |
  188056. (p << 4) | (p << 6)] >> 6) & 0x03);
  188057. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  188058. *sp |= (png_byte)(g << shift);
  188059. }
  188060. if (!shift)
  188061. {
  188062. shift = 6;
  188063. sp++;
  188064. }
  188065. else
  188066. shift -= 2;
  188067. }
  188068. }
  188069. else
  188070. #endif
  188071. {
  188072. sp = row;
  188073. shift = 6;
  188074. for (i = 0; i < row_width; i++)
  188075. {
  188076. if ((png_uint_16)((*sp >> shift) & 0x03)
  188077. == trans_values->gray)
  188078. {
  188079. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  188080. *sp |= (png_byte)(background->gray << shift);
  188081. }
  188082. if (!shift)
  188083. {
  188084. shift = 6;
  188085. sp++;
  188086. }
  188087. else
  188088. shift -= 2;
  188089. }
  188090. }
  188091. break;
  188092. }
  188093. case 4:
  188094. {
  188095. #if defined(PNG_READ_GAMMA_SUPPORTED)
  188096. if (gamma_table != NULL)
  188097. {
  188098. sp = row;
  188099. shift = 4;
  188100. for (i = 0; i < row_width; i++)
  188101. {
  188102. if ((png_uint_16)((*sp >> shift) & 0x0f)
  188103. == trans_values->gray)
  188104. {
  188105. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  188106. *sp |= (png_byte)(background->gray << shift);
  188107. }
  188108. else
  188109. {
  188110. png_byte p = (png_byte)((*sp >> shift) & 0x0f);
  188111. png_byte g = (png_byte)((gamma_table[p |
  188112. (p << 4)] >> 4) & 0x0f);
  188113. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  188114. *sp |= (png_byte)(g << shift);
  188115. }
  188116. if (!shift)
  188117. {
  188118. shift = 4;
  188119. sp++;
  188120. }
  188121. else
  188122. shift -= 4;
  188123. }
  188124. }
  188125. else
  188126. #endif
  188127. {
  188128. sp = row;
  188129. shift = 4;
  188130. for (i = 0; i < row_width; i++)
  188131. {
  188132. if ((png_uint_16)((*sp >> shift) & 0x0f)
  188133. == trans_values->gray)
  188134. {
  188135. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  188136. *sp |= (png_byte)(background->gray << shift);
  188137. }
  188138. if (!shift)
  188139. {
  188140. shift = 4;
  188141. sp++;
  188142. }
  188143. else
  188144. shift -= 4;
  188145. }
  188146. }
  188147. break;
  188148. }
  188149. case 8:
  188150. {
  188151. #if defined(PNG_READ_GAMMA_SUPPORTED)
  188152. if (gamma_table != NULL)
  188153. {
  188154. sp = row;
  188155. for (i = 0; i < row_width; i++, sp++)
  188156. {
  188157. if (*sp == trans_values->gray)
  188158. {
  188159. *sp = (png_byte)background->gray;
  188160. }
  188161. else
  188162. {
  188163. *sp = gamma_table[*sp];
  188164. }
  188165. }
  188166. }
  188167. else
  188168. #endif
  188169. {
  188170. sp = row;
  188171. for (i = 0; i < row_width; i++, sp++)
  188172. {
  188173. if (*sp == trans_values->gray)
  188174. {
  188175. *sp = (png_byte)background->gray;
  188176. }
  188177. }
  188178. }
  188179. break;
  188180. }
  188181. case 16:
  188182. {
  188183. #if defined(PNG_READ_GAMMA_SUPPORTED)
  188184. if (gamma_16 != NULL)
  188185. {
  188186. sp = row;
  188187. for (i = 0; i < row_width; i++, sp += 2)
  188188. {
  188189. png_uint_16 v;
  188190. v = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  188191. if (v == trans_values->gray)
  188192. {
  188193. /* background is already in screen gamma */
  188194. *sp = (png_byte)((background->gray >> 8) & 0xff);
  188195. *(sp + 1) = (png_byte)(background->gray & 0xff);
  188196. }
  188197. else
  188198. {
  188199. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  188200. *sp = (png_byte)((v >> 8) & 0xff);
  188201. *(sp + 1) = (png_byte)(v & 0xff);
  188202. }
  188203. }
  188204. }
  188205. else
  188206. #endif
  188207. {
  188208. sp = row;
  188209. for (i = 0; i < row_width; i++, sp += 2)
  188210. {
  188211. png_uint_16 v;
  188212. v = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  188213. if (v == trans_values->gray)
  188214. {
  188215. *sp = (png_byte)((background->gray >> 8) & 0xff);
  188216. *(sp + 1) = (png_byte)(background->gray & 0xff);
  188217. }
  188218. }
  188219. }
  188220. break;
  188221. }
  188222. }
  188223. break;
  188224. }
  188225. case PNG_COLOR_TYPE_RGB:
  188226. {
  188227. if (row_info->bit_depth == 8)
  188228. {
  188229. #if defined(PNG_READ_GAMMA_SUPPORTED)
  188230. if (gamma_table != NULL)
  188231. {
  188232. sp = row;
  188233. for (i = 0; i < row_width; i++, sp += 3)
  188234. {
  188235. if (*sp == trans_values->red &&
  188236. *(sp + 1) == trans_values->green &&
  188237. *(sp + 2) == trans_values->blue)
  188238. {
  188239. *sp = (png_byte)background->red;
  188240. *(sp + 1) = (png_byte)background->green;
  188241. *(sp + 2) = (png_byte)background->blue;
  188242. }
  188243. else
  188244. {
  188245. *sp = gamma_table[*sp];
  188246. *(sp + 1) = gamma_table[*(sp + 1)];
  188247. *(sp + 2) = gamma_table[*(sp + 2)];
  188248. }
  188249. }
  188250. }
  188251. else
  188252. #endif
  188253. {
  188254. sp = row;
  188255. for (i = 0; i < row_width; i++, sp += 3)
  188256. {
  188257. if (*sp == trans_values->red &&
  188258. *(sp + 1) == trans_values->green &&
  188259. *(sp + 2) == trans_values->blue)
  188260. {
  188261. *sp = (png_byte)background->red;
  188262. *(sp + 1) = (png_byte)background->green;
  188263. *(sp + 2) = (png_byte)background->blue;
  188264. }
  188265. }
  188266. }
  188267. }
  188268. else /* if (row_info->bit_depth == 16) */
  188269. {
  188270. #if defined(PNG_READ_GAMMA_SUPPORTED)
  188271. if (gamma_16 != NULL)
  188272. {
  188273. sp = row;
  188274. for (i = 0; i < row_width; i++, sp += 6)
  188275. {
  188276. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  188277. png_uint_16 g = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  188278. png_uint_16 b = (png_uint_16)(((*(sp+4)) << 8) + *(sp+5));
  188279. if (r == trans_values->red && g == trans_values->green &&
  188280. b == trans_values->blue)
  188281. {
  188282. /* background is already in screen gamma */
  188283. *sp = (png_byte)((background->red >> 8) & 0xff);
  188284. *(sp + 1) = (png_byte)(background->red & 0xff);
  188285. *(sp + 2) = (png_byte)((background->green >> 8) & 0xff);
  188286. *(sp + 3) = (png_byte)(background->green & 0xff);
  188287. *(sp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  188288. *(sp + 5) = (png_byte)(background->blue & 0xff);
  188289. }
  188290. else
  188291. {
  188292. png_uint_16 v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  188293. *sp = (png_byte)((v >> 8) & 0xff);
  188294. *(sp + 1) = (png_byte)(v & 0xff);
  188295. v = gamma_16[*(sp + 3) >> gamma_shift][*(sp + 2)];
  188296. *(sp + 2) = (png_byte)((v >> 8) & 0xff);
  188297. *(sp + 3) = (png_byte)(v & 0xff);
  188298. v = gamma_16[*(sp + 5) >> gamma_shift][*(sp + 4)];
  188299. *(sp + 4) = (png_byte)((v >> 8) & 0xff);
  188300. *(sp + 5) = (png_byte)(v & 0xff);
  188301. }
  188302. }
  188303. }
  188304. else
  188305. #endif
  188306. {
  188307. sp = row;
  188308. for (i = 0; i < row_width; i++, sp += 6)
  188309. {
  188310. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp+1));
  188311. png_uint_16 g = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  188312. png_uint_16 b = (png_uint_16)(((*(sp+4)) << 8) + *(sp+5));
  188313. if (r == trans_values->red && g == trans_values->green &&
  188314. b == trans_values->blue)
  188315. {
  188316. *sp = (png_byte)((background->red >> 8) & 0xff);
  188317. *(sp + 1) = (png_byte)(background->red & 0xff);
  188318. *(sp + 2) = (png_byte)((background->green >> 8) & 0xff);
  188319. *(sp + 3) = (png_byte)(background->green & 0xff);
  188320. *(sp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  188321. *(sp + 5) = (png_byte)(background->blue & 0xff);
  188322. }
  188323. }
  188324. }
  188325. }
  188326. break;
  188327. }
  188328. case PNG_COLOR_TYPE_GRAY_ALPHA:
  188329. {
  188330. if (row_info->bit_depth == 8)
  188331. {
  188332. #if defined(PNG_READ_GAMMA_SUPPORTED)
  188333. if (gamma_to_1 != NULL && gamma_from_1 != NULL &&
  188334. gamma_table != NULL)
  188335. {
  188336. sp = row;
  188337. dp = row;
  188338. for (i = 0; i < row_width; i++, sp += 2, dp++)
  188339. {
  188340. png_uint_16 a = *(sp + 1);
  188341. if (a == 0xff)
  188342. {
  188343. *dp = gamma_table[*sp];
  188344. }
  188345. else if (a == 0)
  188346. {
  188347. /* background is already in screen gamma */
  188348. *dp = (png_byte)background->gray;
  188349. }
  188350. else
  188351. {
  188352. png_byte v, w;
  188353. v = gamma_to_1[*sp];
  188354. png_composite(w, v, a, background_1->gray);
  188355. *dp = gamma_from_1[w];
  188356. }
  188357. }
  188358. }
  188359. else
  188360. #endif
  188361. {
  188362. sp = row;
  188363. dp = row;
  188364. for (i = 0; i < row_width; i++, sp += 2, dp++)
  188365. {
  188366. png_byte a = *(sp + 1);
  188367. if (a == 0xff)
  188368. {
  188369. *dp = *sp;
  188370. }
  188371. #if defined(PNG_READ_GAMMA_SUPPORTED)
  188372. else if (a == 0)
  188373. {
  188374. *dp = (png_byte)background->gray;
  188375. }
  188376. else
  188377. {
  188378. png_composite(*dp, *sp, a, background_1->gray);
  188379. }
  188380. #else
  188381. *dp = (png_byte)background->gray;
  188382. #endif
  188383. }
  188384. }
  188385. }
  188386. else /* if (png_ptr->bit_depth == 16) */
  188387. {
  188388. #if defined(PNG_READ_GAMMA_SUPPORTED)
  188389. if (gamma_16 != NULL && gamma_16_from_1 != NULL &&
  188390. gamma_16_to_1 != NULL)
  188391. {
  188392. sp = row;
  188393. dp = row;
  188394. for (i = 0; i < row_width; i++, sp += 4, dp += 2)
  188395. {
  188396. png_uint_16 a = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  188397. if (a == (png_uint_16)0xffff)
  188398. {
  188399. png_uint_16 v;
  188400. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  188401. *dp = (png_byte)((v >> 8) & 0xff);
  188402. *(dp + 1) = (png_byte)(v & 0xff);
  188403. }
  188404. #if defined(PNG_READ_GAMMA_SUPPORTED)
  188405. else if (a == 0)
  188406. #else
  188407. else
  188408. #endif
  188409. {
  188410. /* background is already in screen gamma */
  188411. *dp = (png_byte)((background->gray >> 8) & 0xff);
  188412. *(dp + 1) = (png_byte)(background->gray & 0xff);
  188413. }
  188414. #if defined(PNG_READ_GAMMA_SUPPORTED)
  188415. else
  188416. {
  188417. png_uint_16 g, v, w;
  188418. g = gamma_16_to_1[*(sp + 1) >> gamma_shift][*sp];
  188419. png_composite_16(v, g, a, background_1->gray);
  188420. w = gamma_16_from_1[(v&0xff) >> gamma_shift][v >> 8];
  188421. *dp = (png_byte)((w >> 8) & 0xff);
  188422. *(dp + 1) = (png_byte)(w & 0xff);
  188423. }
  188424. #endif
  188425. }
  188426. }
  188427. else
  188428. #endif
  188429. {
  188430. sp = row;
  188431. dp = row;
  188432. for (i = 0; i < row_width; i++, sp += 4, dp += 2)
  188433. {
  188434. png_uint_16 a = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  188435. if (a == (png_uint_16)0xffff)
  188436. {
  188437. png_memcpy(dp, sp, 2);
  188438. }
  188439. #if defined(PNG_READ_GAMMA_SUPPORTED)
  188440. else if (a == 0)
  188441. #else
  188442. else
  188443. #endif
  188444. {
  188445. *dp = (png_byte)((background->gray >> 8) & 0xff);
  188446. *(dp + 1) = (png_byte)(background->gray & 0xff);
  188447. }
  188448. #if defined(PNG_READ_GAMMA_SUPPORTED)
  188449. else
  188450. {
  188451. png_uint_16 g, v;
  188452. g = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  188453. png_composite_16(v, g, a, background_1->gray);
  188454. *dp = (png_byte)((v >> 8) & 0xff);
  188455. *(dp + 1) = (png_byte)(v & 0xff);
  188456. }
  188457. #endif
  188458. }
  188459. }
  188460. }
  188461. break;
  188462. }
  188463. case PNG_COLOR_TYPE_RGB_ALPHA:
  188464. {
  188465. if (row_info->bit_depth == 8)
  188466. {
  188467. #if defined(PNG_READ_GAMMA_SUPPORTED)
  188468. if (gamma_to_1 != NULL && gamma_from_1 != NULL &&
  188469. gamma_table != NULL)
  188470. {
  188471. sp = row;
  188472. dp = row;
  188473. for (i = 0; i < row_width; i++, sp += 4, dp += 3)
  188474. {
  188475. png_byte a = *(sp + 3);
  188476. if (a == 0xff)
  188477. {
  188478. *dp = gamma_table[*sp];
  188479. *(dp + 1) = gamma_table[*(sp + 1)];
  188480. *(dp + 2) = gamma_table[*(sp + 2)];
  188481. }
  188482. else if (a == 0)
  188483. {
  188484. /* background is already in screen gamma */
  188485. *dp = (png_byte)background->red;
  188486. *(dp + 1) = (png_byte)background->green;
  188487. *(dp + 2) = (png_byte)background->blue;
  188488. }
  188489. else
  188490. {
  188491. png_byte v, w;
  188492. v = gamma_to_1[*sp];
  188493. png_composite(w, v, a, background_1->red);
  188494. *dp = gamma_from_1[w];
  188495. v = gamma_to_1[*(sp + 1)];
  188496. png_composite(w, v, a, background_1->green);
  188497. *(dp + 1) = gamma_from_1[w];
  188498. v = gamma_to_1[*(sp + 2)];
  188499. png_composite(w, v, a, background_1->blue);
  188500. *(dp + 2) = gamma_from_1[w];
  188501. }
  188502. }
  188503. }
  188504. else
  188505. #endif
  188506. {
  188507. sp = row;
  188508. dp = row;
  188509. for (i = 0; i < row_width; i++, sp += 4, dp += 3)
  188510. {
  188511. png_byte a = *(sp + 3);
  188512. if (a == 0xff)
  188513. {
  188514. *dp = *sp;
  188515. *(dp + 1) = *(sp + 1);
  188516. *(dp + 2) = *(sp + 2);
  188517. }
  188518. else if (a == 0)
  188519. {
  188520. *dp = (png_byte)background->red;
  188521. *(dp + 1) = (png_byte)background->green;
  188522. *(dp + 2) = (png_byte)background->blue;
  188523. }
  188524. else
  188525. {
  188526. png_composite(*dp, *sp, a, background->red);
  188527. png_composite(*(dp + 1), *(sp + 1), a,
  188528. background->green);
  188529. png_composite(*(dp + 2), *(sp + 2), a,
  188530. background->blue);
  188531. }
  188532. }
  188533. }
  188534. }
  188535. else /* if (row_info->bit_depth == 16) */
  188536. {
  188537. #if defined(PNG_READ_GAMMA_SUPPORTED)
  188538. if (gamma_16 != NULL && gamma_16_from_1 != NULL &&
  188539. gamma_16_to_1 != NULL)
  188540. {
  188541. sp = row;
  188542. dp = row;
  188543. for (i = 0; i < row_width; i++, sp += 8, dp += 6)
  188544. {
  188545. png_uint_16 a = (png_uint_16)(((png_uint_16)(*(sp + 6))
  188546. << 8) + (png_uint_16)(*(sp + 7)));
  188547. if (a == (png_uint_16)0xffff)
  188548. {
  188549. png_uint_16 v;
  188550. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  188551. *dp = (png_byte)((v >> 8) & 0xff);
  188552. *(dp + 1) = (png_byte)(v & 0xff);
  188553. v = gamma_16[*(sp + 3) >> gamma_shift][*(sp + 2)];
  188554. *(dp + 2) = (png_byte)((v >> 8) & 0xff);
  188555. *(dp + 3) = (png_byte)(v & 0xff);
  188556. v = gamma_16[*(sp + 5) >> gamma_shift][*(sp + 4)];
  188557. *(dp + 4) = (png_byte)((v >> 8) & 0xff);
  188558. *(dp + 5) = (png_byte)(v & 0xff);
  188559. }
  188560. else if (a == 0)
  188561. {
  188562. /* background is already in screen gamma */
  188563. *dp = (png_byte)((background->red >> 8) & 0xff);
  188564. *(dp + 1) = (png_byte)(background->red & 0xff);
  188565. *(dp + 2) = (png_byte)((background->green >> 8) & 0xff);
  188566. *(dp + 3) = (png_byte)(background->green & 0xff);
  188567. *(dp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  188568. *(dp + 5) = (png_byte)(background->blue & 0xff);
  188569. }
  188570. else
  188571. {
  188572. png_uint_16 v, w, x;
  188573. v = gamma_16_to_1[*(sp + 1) >> gamma_shift][*sp];
  188574. png_composite_16(w, v, a, background_1->red);
  188575. x = gamma_16_from_1[((w&0xff) >> gamma_shift)][w >> 8];
  188576. *dp = (png_byte)((x >> 8) & 0xff);
  188577. *(dp + 1) = (png_byte)(x & 0xff);
  188578. v = gamma_16_to_1[*(sp + 3) >> gamma_shift][*(sp + 2)];
  188579. png_composite_16(w, v, a, background_1->green);
  188580. x = gamma_16_from_1[((w&0xff) >> gamma_shift)][w >> 8];
  188581. *(dp + 2) = (png_byte)((x >> 8) & 0xff);
  188582. *(dp + 3) = (png_byte)(x & 0xff);
  188583. v = gamma_16_to_1[*(sp + 5) >> gamma_shift][*(sp + 4)];
  188584. png_composite_16(w, v, a, background_1->blue);
  188585. x = gamma_16_from_1[(w & 0xff) >> gamma_shift][w >> 8];
  188586. *(dp + 4) = (png_byte)((x >> 8) & 0xff);
  188587. *(dp + 5) = (png_byte)(x & 0xff);
  188588. }
  188589. }
  188590. }
  188591. else
  188592. #endif
  188593. {
  188594. sp = row;
  188595. dp = row;
  188596. for (i = 0; i < row_width; i++, sp += 8, dp += 6)
  188597. {
  188598. png_uint_16 a = (png_uint_16)(((png_uint_16)(*(sp + 6))
  188599. << 8) + (png_uint_16)(*(sp + 7)));
  188600. if (a == (png_uint_16)0xffff)
  188601. {
  188602. png_memcpy(dp, sp, 6);
  188603. }
  188604. else if (a == 0)
  188605. {
  188606. *dp = (png_byte)((background->red >> 8) & 0xff);
  188607. *(dp + 1) = (png_byte)(background->red & 0xff);
  188608. *(dp + 2) = (png_byte)((background->green >> 8) & 0xff);
  188609. *(dp + 3) = (png_byte)(background->green & 0xff);
  188610. *(dp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  188611. *(dp + 5) = (png_byte)(background->blue & 0xff);
  188612. }
  188613. else
  188614. {
  188615. png_uint_16 v;
  188616. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  188617. png_uint_16 g = (png_uint_16)(((*(sp + 2)) << 8)
  188618. + *(sp + 3));
  188619. png_uint_16 b = (png_uint_16)(((*(sp + 4)) << 8)
  188620. + *(sp + 5));
  188621. png_composite_16(v, r, a, background->red);
  188622. *dp = (png_byte)((v >> 8) & 0xff);
  188623. *(dp + 1) = (png_byte)(v & 0xff);
  188624. png_composite_16(v, g, a, background->green);
  188625. *(dp + 2) = (png_byte)((v >> 8) & 0xff);
  188626. *(dp + 3) = (png_byte)(v & 0xff);
  188627. png_composite_16(v, b, a, background->blue);
  188628. *(dp + 4) = (png_byte)((v >> 8) & 0xff);
  188629. *(dp + 5) = (png_byte)(v & 0xff);
  188630. }
  188631. }
  188632. }
  188633. }
  188634. break;
  188635. }
  188636. }
  188637. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  188638. {
  188639. row_info->color_type &= ~PNG_COLOR_MASK_ALPHA;
  188640. row_info->channels--;
  188641. row_info->pixel_depth = (png_byte)(row_info->channels *
  188642. row_info->bit_depth);
  188643. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  188644. }
  188645. }
  188646. }
  188647. #endif
  188648. #if defined(PNG_READ_GAMMA_SUPPORTED)
  188649. /* Gamma correct the image, avoiding the alpha channel. Make sure
  188650. * you do this after you deal with the transparency issue on grayscale
  188651. * or RGB images. If your bit depth is 8, use gamma_table, if it
  188652. * is 16, use gamma_16_table and gamma_shift. Build these with
  188653. * build_gamma_table().
  188654. */
  188655. void /* PRIVATE */
  188656. png_do_gamma(png_row_infop row_info, png_bytep row,
  188657. png_bytep gamma_table, png_uint_16pp gamma_16_table,
  188658. int gamma_shift)
  188659. {
  188660. png_bytep sp;
  188661. png_uint_32 i;
  188662. png_uint_32 row_width=row_info->width;
  188663. png_debug(1, "in png_do_gamma\n");
  188664. if (
  188665. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  188666. row != NULL && row_info != NULL &&
  188667. #endif
  188668. ((row_info->bit_depth <= 8 && gamma_table != NULL) ||
  188669. (row_info->bit_depth == 16 && gamma_16_table != NULL)))
  188670. {
  188671. switch (row_info->color_type)
  188672. {
  188673. case PNG_COLOR_TYPE_RGB:
  188674. {
  188675. if (row_info->bit_depth == 8)
  188676. {
  188677. sp = row;
  188678. for (i = 0; i < row_width; i++)
  188679. {
  188680. *sp = gamma_table[*sp];
  188681. sp++;
  188682. *sp = gamma_table[*sp];
  188683. sp++;
  188684. *sp = gamma_table[*sp];
  188685. sp++;
  188686. }
  188687. }
  188688. else /* if (row_info->bit_depth == 16) */
  188689. {
  188690. sp = row;
  188691. for (i = 0; i < row_width; i++)
  188692. {
  188693. png_uint_16 v;
  188694. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  188695. *sp = (png_byte)((v >> 8) & 0xff);
  188696. *(sp + 1) = (png_byte)(v & 0xff);
  188697. sp += 2;
  188698. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  188699. *sp = (png_byte)((v >> 8) & 0xff);
  188700. *(sp + 1) = (png_byte)(v & 0xff);
  188701. sp += 2;
  188702. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  188703. *sp = (png_byte)((v >> 8) & 0xff);
  188704. *(sp + 1) = (png_byte)(v & 0xff);
  188705. sp += 2;
  188706. }
  188707. }
  188708. break;
  188709. }
  188710. case PNG_COLOR_TYPE_RGB_ALPHA:
  188711. {
  188712. if (row_info->bit_depth == 8)
  188713. {
  188714. sp = row;
  188715. for (i = 0; i < row_width; i++)
  188716. {
  188717. *sp = gamma_table[*sp];
  188718. sp++;
  188719. *sp = gamma_table[*sp];
  188720. sp++;
  188721. *sp = gamma_table[*sp];
  188722. sp++;
  188723. sp++;
  188724. }
  188725. }
  188726. else /* if (row_info->bit_depth == 16) */
  188727. {
  188728. sp = row;
  188729. for (i = 0; i < row_width; i++)
  188730. {
  188731. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  188732. *sp = (png_byte)((v >> 8) & 0xff);
  188733. *(sp + 1) = (png_byte)(v & 0xff);
  188734. sp += 2;
  188735. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  188736. *sp = (png_byte)((v >> 8) & 0xff);
  188737. *(sp + 1) = (png_byte)(v & 0xff);
  188738. sp += 2;
  188739. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  188740. *sp = (png_byte)((v >> 8) & 0xff);
  188741. *(sp + 1) = (png_byte)(v & 0xff);
  188742. sp += 4;
  188743. }
  188744. }
  188745. break;
  188746. }
  188747. case PNG_COLOR_TYPE_GRAY_ALPHA:
  188748. {
  188749. if (row_info->bit_depth == 8)
  188750. {
  188751. sp = row;
  188752. for (i = 0; i < row_width; i++)
  188753. {
  188754. *sp = gamma_table[*sp];
  188755. sp += 2;
  188756. }
  188757. }
  188758. else /* if (row_info->bit_depth == 16) */
  188759. {
  188760. sp = row;
  188761. for (i = 0; i < row_width; i++)
  188762. {
  188763. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  188764. *sp = (png_byte)((v >> 8) & 0xff);
  188765. *(sp + 1) = (png_byte)(v & 0xff);
  188766. sp += 4;
  188767. }
  188768. }
  188769. break;
  188770. }
  188771. case PNG_COLOR_TYPE_GRAY:
  188772. {
  188773. if (row_info->bit_depth == 2)
  188774. {
  188775. sp = row;
  188776. for (i = 0; i < row_width; i += 4)
  188777. {
  188778. int a = *sp & 0xc0;
  188779. int b = *sp & 0x30;
  188780. int c = *sp & 0x0c;
  188781. int d = *sp & 0x03;
  188782. *sp = (png_byte)(
  188783. ((((int)gamma_table[a|(a>>2)|(a>>4)|(a>>6)]) ) & 0xc0)|
  188784. ((((int)gamma_table[(b<<2)|b|(b>>2)|(b>>4)])>>2) & 0x30)|
  188785. ((((int)gamma_table[(c<<4)|(c<<2)|c|(c>>2)])>>4) & 0x0c)|
  188786. ((((int)gamma_table[(d<<6)|(d<<4)|(d<<2)|d])>>6) ));
  188787. sp++;
  188788. }
  188789. }
  188790. if (row_info->bit_depth == 4)
  188791. {
  188792. sp = row;
  188793. for (i = 0; i < row_width; i += 2)
  188794. {
  188795. int msb = *sp & 0xf0;
  188796. int lsb = *sp & 0x0f;
  188797. *sp = (png_byte)((((int)gamma_table[msb | (msb >> 4)]) & 0xf0)
  188798. | (((int)gamma_table[(lsb << 4) | lsb]) >> 4));
  188799. sp++;
  188800. }
  188801. }
  188802. else if (row_info->bit_depth == 8)
  188803. {
  188804. sp = row;
  188805. for (i = 0; i < row_width; i++)
  188806. {
  188807. *sp = gamma_table[*sp];
  188808. sp++;
  188809. }
  188810. }
  188811. else if (row_info->bit_depth == 16)
  188812. {
  188813. sp = row;
  188814. for (i = 0; i < row_width; i++)
  188815. {
  188816. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  188817. *sp = (png_byte)((v >> 8) & 0xff);
  188818. *(sp + 1) = (png_byte)(v & 0xff);
  188819. sp += 2;
  188820. }
  188821. }
  188822. break;
  188823. }
  188824. }
  188825. }
  188826. }
  188827. #endif
  188828. #if defined(PNG_READ_EXPAND_SUPPORTED)
  188829. /* Expands a palette row to an RGB or RGBA row depending
  188830. * upon whether you supply trans and num_trans.
  188831. */
  188832. void /* PRIVATE */
  188833. png_do_expand_palette(png_row_infop row_info, png_bytep row,
  188834. png_colorp palette, png_bytep trans, int num_trans)
  188835. {
  188836. int shift, value;
  188837. png_bytep sp, dp;
  188838. png_uint_32 i;
  188839. png_uint_32 row_width=row_info->width;
  188840. png_debug(1, "in png_do_expand_palette\n");
  188841. if (
  188842. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  188843. row != NULL && row_info != NULL &&
  188844. #endif
  188845. row_info->color_type == PNG_COLOR_TYPE_PALETTE)
  188846. {
  188847. if (row_info->bit_depth < 8)
  188848. {
  188849. switch (row_info->bit_depth)
  188850. {
  188851. case 1:
  188852. {
  188853. sp = row + (png_size_t)((row_width - 1) >> 3);
  188854. dp = row + (png_size_t)row_width - 1;
  188855. shift = 7 - (int)((row_width + 7) & 0x07);
  188856. for (i = 0; i < row_width; i++)
  188857. {
  188858. if ((*sp >> shift) & 0x01)
  188859. *dp = 1;
  188860. else
  188861. *dp = 0;
  188862. if (shift == 7)
  188863. {
  188864. shift = 0;
  188865. sp--;
  188866. }
  188867. else
  188868. shift++;
  188869. dp--;
  188870. }
  188871. break;
  188872. }
  188873. case 2:
  188874. {
  188875. sp = row + (png_size_t)((row_width - 1) >> 2);
  188876. dp = row + (png_size_t)row_width - 1;
  188877. shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  188878. for (i = 0; i < row_width; i++)
  188879. {
  188880. value = (*sp >> shift) & 0x03;
  188881. *dp = (png_byte)value;
  188882. if (shift == 6)
  188883. {
  188884. shift = 0;
  188885. sp--;
  188886. }
  188887. else
  188888. shift += 2;
  188889. dp--;
  188890. }
  188891. break;
  188892. }
  188893. case 4:
  188894. {
  188895. sp = row + (png_size_t)((row_width - 1) >> 1);
  188896. dp = row + (png_size_t)row_width - 1;
  188897. shift = (int)((row_width & 0x01) << 2);
  188898. for (i = 0; i < row_width; i++)
  188899. {
  188900. value = (*sp >> shift) & 0x0f;
  188901. *dp = (png_byte)value;
  188902. if (shift == 4)
  188903. {
  188904. shift = 0;
  188905. sp--;
  188906. }
  188907. else
  188908. shift += 4;
  188909. dp--;
  188910. }
  188911. break;
  188912. }
  188913. }
  188914. row_info->bit_depth = 8;
  188915. row_info->pixel_depth = 8;
  188916. row_info->rowbytes = row_width;
  188917. }
  188918. switch (row_info->bit_depth)
  188919. {
  188920. case 8:
  188921. {
  188922. if (trans != NULL)
  188923. {
  188924. sp = row + (png_size_t)row_width - 1;
  188925. dp = row + (png_size_t)(row_width << 2) - 1;
  188926. for (i = 0; i < row_width; i++)
  188927. {
  188928. if ((int)(*sp) >= num_trans)
  188929. *dp-- = 0xff;
  188930. else
  188931. *dp-- = trans[*sp];
  188932. *dp-- = palette[*sp].blue;
  188933. *dp-- = palette[*sp].green;
  188934. *dp-- = palette[*sp].red;
  188935. sp--;
  188936. }
  188937. row_info->bit_depth = 8;
  188938. row_info->pixel_depth = 32;
  188939. row_info->rowbytes = row_width * 4;
  188940. row_info->color_type = 6;
  188941. row_info->channels = 4;
  188942. }
  188943. else
  188944. {
  188945. sp = row + (png_size_t)row_width - 1;
  188946. dp = row + (png_size_t)(row_width * 3) - 1;
  188947. for (i = 0; i < row_width; i++)
  188948. {
  188949. *dp-- = palette[*sp].blue;
  188950. *dp-- = palette[*sp].green;
  188951. *dp-- = palette[*sp].red;
  188952. sp--;
  188953. }
  188954. row_info->bit_depth = 8;
  188955. row_info->pixel_depth = 24;
  188956. row_info->rowbytes = row_width * 3;
  188957. row_info->color_type = 2;
  188958. row_info->channels = 3;
  188959. }
  188960. break;
  188961. }
  188962. }
  188963. }
  188964. }
  188965. /* If the bit depth < 8, it is expanded to 8. Also, if the already
  188966. * expanded transparency value is supplied, an alpha channel is built.
  188967. */
  188968. void /* PRIVATE */
  188969. png_do_expand(png_row_infop row_info, png_bytep row,
  188970. png_color_16p trans_value)
  188971. {
  188972. int shift, value;
  188973. png_bytep sp, dp;
  188974. png_uint_32 i;
  188975. png_uint_32 row_width=row_info->width;
  188976. png_debug(1, "in png_do_expand\n");
  188977. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  188978. if (row != NULL && row_info != NULL)
  188979. #endif
  188980. {
  188981. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  188982. {
  188983. png_uint_16 gray = (png_uint_16)(trans_value ? trans_value->gray : 0);
  188984. if (row_info->bit_depth < 8)
  188985. {
  188986. switch (row_info->bit_depth)
  188987. {
  188988. case 1:
  188989. {
  188990. gray = (png_uint_16)((gray&0x01)*0xff);
  188991. sp = row + (png_size_t)((row_width - 1) >> 3);
  188992. dp = row + (png_size_t)row_width - 1;
  188993. shift = 7 - (int)((row_width + 7) & 0x07);
  188994. for (i = 0; i < row_width; i++)
  188995. {
  188996. if ((*sp >> shift) & 0x01)
  188997. *dp = 0xff;
  188998. else
  188999. *dp = 0;
  189000. if (shift == 7)
  189001. {
  189002. shift = 0;
  189003. sp--;
  189004. }
  189005. else
  189006. shift++;
  189007. dp--;
  189008. }
  189009. break;
  189010. }
  189011. case 2:
  189012. {
  189013. gray = (png_uint_16)((gray&0x03)*0x55);
  189014. sp = row + (png_size_t)((row_width - 1) >> 2);
  189015. dp = row + (png_size_t)row_width - 1;
  189016. shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  189017. for (i = 0; i < row_width; i++)
  189018. {
  189019. value = (*sp >> shift) & 0x03;
  189020. *dp = (png_byte)(value | (value << 2) | (value << 4) |
  189021. (value << 6));
  189022. if (shift == 6)
  189023. {
  189024. shift = 0;
  189025. sp--;
  189026. }
  189027. else
  189028. shift += 2;
  189029. dp--;
  189030. }
  189031. break;
  189032. }
  189033. case 4:
  189034. {
  189035. gray = (png_uint_16)((gray&0x0f)*0x11);
  189036. sp = row + (png_size_t)((row_width - 1) >> 1);
  189037. dp = row + (png_size_t)row_width - 1;
  189038. shift = (int)((1 - ((row_width + 1) & 0x01)) << 2);
  189039. for (i = 0; i < row_width; i++)
  189040. {
  189041. value = (*sp >> shift) & 0x0f;
  189042. *dp = (png_byte)(value | (value << 4));
  189043. if (shift == 4)
  189044. {
  189045. shift = 0;
  189046. sp--;
  189047. }
  189048. else
  189049. shift = 4;
  189050. dp--;
  189051. }
  189052. break;
  189053. }
  189054. }
  189055. row_info->bit_depth = 8;
  189056. row_info->pixel_depth = 8;
  189057. row_info->rowbytes = row_width;
  189058. }
  189059. if (trans_value != NULL)
  189060. {
  189061. if (row_info->bit_depth == 8)
  189062. {
  189063. gray = gray & 0xff;
  189064. sp = row + (png_size_t)row_width - 1;
  189065. dp = row + (png_size_t)(row_width << 1) - 1;
  189066. for (i = 0; i < row_width; i++)
  189067. {
  189068. if (*sp == gray)
  189069. *dp-- = 0;
  189070. else
  189071. *dp-- = 0xff;
  189072. *dp-- = *sp--;
  189073. }
  189074. }
  189075. else if (row_info->bit_depth == 16)
  189076. {
  189077. png_byte gray_high = (gray >> 8) & 0xff;
  189078. png_byte gray_low = gray & 0xff;
  189079. sp = row + row_info->rowbytes - 1;
  189080. dp = row + (row_info->rowbytes << 1) - 1;
  189081. for (i = 0; i < row_width; i++)
  189082. {
  189083. if (*(sp-1) == gray_high && *(sp) == gray_low)
  189084. {
  189085. *dp-- = 0;
  189086. *dp-- = 0;
  189087. }
  189088. else
  189089. {
  189090. *dp-- = 0xff;
  189091. *dp-- = 0xff;
  189092. }
  189093. *dp-- = *sp--;
  189094. *dp-- = *sp--;
  189095. }
  189096. }
  189097. row_info->color_type = PNG_COLOR_TYPE_GRAY_ALPHA;
  189098. row_info->channels = 2;
  189099. row_info->pixel_depth = (png_byte)(row_info->bit_depth << 1);
  189100. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  189101. row_width);
  189102. }
  189103. }
  189104. else if (row_info->color_type == PNG_COLOR_TYPE_RGB && trans_value)
  189105. {
  189106. if (row_info->bit_depth == 8)
  189107. {
  189108. png_byte red = trans_value->red & 0xff;
  189109. png_byte green = trans_value->green & 0xff;
  189110. png_byte blue = trans_value->blue & 0xff;
  189111. sp = row + (png_size_t)row_info->rowbytes - 1;
  189112. dp = row + (png_size_t)(row_width << 2) - 1;
  189113. for (i = 0; i < row_width; i++)
  189114. {
  189115. if (*(sp - 2) == red && *(sp - 1) == green && *(sp) == blue)
  189116. *dp-- = 0;
  189117. else
  189118. *dp-- = 0xff;
  189119. *dp-- = *sp--;
  189120. *dp-- = *sp--;
  189121. *dp-- = *sp--;
  189122. }
  189123. }
  189124. else if (row_info->bit_depth == 16)
  189125. {
  189126. png_byte red_high = (trans_value->red >> 8) & 0xff;
  189127. png_byte green_high = (trans_value->green >> 8) & 0xff;
  189128. png_byte blue_high = (trans_value->blue >> 8) & 0xff;
  189129. png_byte red_low = trans_value->red & 0xff;
  189130. png_byte green_low = trans_value->green & 0xff;
  189131. png_byte blue_low = trans_value->blue & 0xff;
  189132. sp = row + row_info->rowbytes - 1;
  189133. dp = row + (png_size_t)(row_width << 3) - 1;
  189134. for (i = 0; i < row_width; i++)
  189135. {
  189136. if (*(sp - 5) == red_high &&
  189137. *(sp - 4) == red_low &&
  189138. *(sp - 3) == green_high &&
  189139. *(sp - 2) == green_low &&
  189140. *(sp - 1) == blue_high &&
  189141. *(sp ) == blue_low)
  189142. {
  189143. *dp-- = 0;
  189144. *dp-- = 0;
  189145. }
  189146. else
  189147. {
  189148. *dp-- = 0xff;
  189149. *dp-- = 0xff;
  189150. }
  189151. *dp-- = *sp--;
  189152. *dp-- = *sp--;
  189153. *dp-- = *sp--;
  189154. *dp-- = *sp--;
  189155. *dp-- = *sp--;
  189156. *dp-- = *sp--;
  189157. }
  189158. }
  189159. row_info->color_type = PNG_COLOR_TYPE_RGB_ALPHA;
  189160. row_info->channels = 4;
  189161. row_info->pixel_depth = (png_byte)(row_info->bit_depth << 2);
  189162. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  189163. }
  189164. }
  189165. }
  189166. #endif
  189167. #if defined(PNG_READ_DITHER_SUPPORTED)
  189168. void /* PRIVATE */
  189169. png_do_dither(png_row_infop row_info, png_bytep row,
  189170. png_bytep palette_lookup, png_bytep dither_lookup)
  189171. {
  189172. png_bytep sp, dp;
  189173. png_uint_32 i;
  189174. png_uint_32 row_width=row_info->width;
  189175. png_debug(1, "in png_do_dither\n");
  189176. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  189177. if (row != NULL && row_info != NULL)
  189178. #endif
  189179. {
  189180. if (row_info->color_type == PNG_COLOR_TYPE_RGB &&
  189181. palette_lookup && row_info->bit_depth == 8)
  189182. {
  189183. int r, g, b, p;
  189184. sp = row;
  189185. dp = row;
  189186. for (i = 0; i < row_width; i++)
  189187. {
  189188. r = *sp++;
  189189. g = *sp++;
  189190. b = *sp++;
  189191. /* this looks real messy, but the compiler will reduce
  189192. it down to a reasonable formula. For example, with
  189193. 5 bits per color, we get:
  189194. p = (((r >> 3) & 0x1f) << 10) |
  189195. (((g >> 3) & 0x1f) << 5) |
  189196. ((b >> 3) & 0x1f);
  189197. */
  189198. p = (((r >> (8 - PNG_DITHER_RED_BITS)) &
  189199. ((1 << PNG_DITHER_RED_BITS) - 1)) <<
  189200. (PNG_DITHER_GREEN_BITS + PNG_DITHER_BLUE_BITS)) |
  189201. (((g >> (8 - PNG_DITHER_GREEN_BITS)) &
  189202. ((1 << PNG_DITHER_GREEN_BITS) - 1)) <<
  189203. (PNG_DITHER_BLUE_BITS)) |
  189204. ((b >> (8 - PNG_DITHER_BLUE_BITS)) &
  189205. ((1 << PNG_DITHER_BLUE_BITS) - 1));
  189206. *dp++ = palette_lookup[p];
  189207. }
  189208. row_info->color_type = PNG_COLOR_TYPE_PALETTE;
  189209. row_info->channels = 1;
  189210. row_info->pixel_depth = row_info->bit_depth;
  189211. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  189212. }
  189213. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA &&
  189214. palette_lookup != NULL && row_info->bit_depth == 8)
  189215. {
  189216. int r, g, b, p;
  189217. sp = row;
  189218. dp = row;
  189219. for (i = 0; i < row_width; i++)
  189220. {
  189221. r = *sp++;
  189222. g = *sp++;
  189223. b = *sp++;
  189224. sp++;
  189225. p = (((r >> (8 - PNG_DITHER_RED_BITS)) &
  189226. ((1 << PNG_DITHER_RED_BITS) - 1)) <<
  189227. (PNG_DITHER_GREEN_BITS + PNG_DITHER_BLUE_BITS)) |
  189228. (((g >> (8 - PNG_DITHER_GREEN_BITS)) &
  189229. ((1 << PNG_DITHER_GREEN_BITS) - 1)) <<
  189230. (PNG_DITHER_BLUE_BITS)) |
  189231. ((b >> (8 - PNG_DITHER_BLUE_BITS)) &
  189232. ((1 << PNG_DITHER_BLUE_BITS) - 1));
  189233. *dp++ = palette_lookup[p];
  189234. }
  189235. row_info->color_type = PNG_COLOR_TYPE_PALETTE;
  189236. row_info->channels = 1;
  189237. row_info->pixel_depth = row_info->bit_depth;
  189238. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  189239. }
  189240. else if (row_info->color_type == PNG_COLOR_TYPE_PALETTE &&
  189241. dither_lookup && row_info->bit_depth == 8)
  189242. {
  189243. sp = row;
  189244. for (i = 0; i < row_width; i++, sp++)
  189245. {
  189246. *sp = dither_lookup[*sp];
  189247. }
  189248. }
  189249. }
  189250. }
  189251. #endif
  189252. #ifdef PNG_FLOATING_POINT_SUPPORTED
  189253. #if defined(PNG_READ_GAMMA_SUPPORTED)
  189254. static PNG_CONST int png_gamma_shift[] =
  189255. {0x10, 0x21, 0x42, 0x84, 0x110, 0x248, 0x550, 0xff0, 0x00};
  189256. /* We build the 8- or 16-bit gamma tables here. Note that for 16-bit
  189257. * tables, we don't make a full table if we are reducing to 8-bit in
  189258. * the future. Note also how the gamma_16 tables are segmented so that
  189259. * we don't need to allocate > 64K chunks for a full 16-bit table.
  189260. */
  189261. void /* PRIVATE */
  189262. png_build_gamma_table(png_structp png_ptr)
  189263. {
  189264. png_debug(1, "in png_build_gamma_table\n");
  189265. if (png_ptr->bit_depth <= 8)
  189266. {
  189267. int i;
  189268. double g;
  189269. if (png_ptr->screen_gamma > .000001)
  189270. g = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  189271. else
  189272. g = 1.0;
  189273. png_ptr->gamma_table = (png_bytep)png_malloc(png_ptr,
  189274. (png_uint_32)256);
  189275. for (i = 0; i < 256; i++)
  189276. {
  189277. png_ptr->gamma_table[i] = (png_byte)(pow((double)i / 255.0,
  189278. g) * 255.0 + .5);
  189279. }
  189280. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || \
  189281. defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  189282. if (png_ptr->transformations & ((PNG_BACKGROUND) | PNG_RGB_TO_GRAY))
  189283. {
  189284. g = 1.0 / (png_ptr->gamma);
  189285. png_ptr->gamma_to_1 = (png_bytep)png_malloc(png_ptr,
  189286. (png_uint_32)256);
  189287. for (i = 0; i < 256; i++)
  189288. {
  189289. png_ptr->gamma_to_1[i] = (png_byte)(pow((double)i / 255.0,
  189290. g) * 255.0 + .5);
  189291. }
  189292. png_ptr->gamma_from_1 = (png_bytep)png_malloc(png_ptr,
  189293. (png_uint_32)256);
  189294. if(png_ptr->screen_gamma > 0.000001)
  189295. g = 1.0 / png_ptr->screen_gamma;
  189296. else
  189297. g = png_ptr->gamma; /* probably doing rgb_to_gray */
  189298. for (i = 0; i < 256; i++)
  189299. {
  189300. png_ptr->gamma_from_1[i] = (png_byte)(pow((double)i / 255.0,
  189301. g) * 255.0 + .5);
  189302. }
  189303. }
  189304. #endif /* PNG_READ_BACKGROUND_SUPPORTED || PNG_RGB_TO_GRAY_SUPPORTED */
  189305. }
  189306. else
  189307. {
  189308. double g;
  189309. int i, j, shift, num;
  189310. int sig_bit;
  189311. png_uint_32 ig;
  189312. if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  189313. {
  189314. sig_bit = (int)png_ptr->sig_bit.red;
  189315. if ((int)png_ptr->sig_bit.green > sig_bit)
  189316. sig_bit = png_ptr->sig_bit.green;
  189317. if ((int)png_ptr->sig_bit.blue > sig_bit)
  189318. sig_bit = png_ptr->sig_bit.blue;
  189319. }
  189320. else
  189321. {
  189322. sig_bit = (int)png_ptr->sig_bit.gray;
  189323. }
  189324. if (sig_bit > 0)
  189325. shift = 16 - sig_bit;
  189326. else
  189327. shift = 0;
  189328. if (png_ptr->transformations & PNG_16_TO_8)
  189329. {
  189330. if (shift < (16 - PNG_MAX_GAMMA_8))
  189331. shift = (16 - PNG_MAX_GAMMA_8);
  189332. }
  189333. if (shift > 8)
  189334. shift = 8;
  189335. if (shift < 0)
  189336. shift = 0;
  189337. png_ptr->gamma_shift = (png_byte)shift;
  189338. num = (1 << (8 - shift));
  189339. if (png_ptr->screen_gamma > .000001)
  189340. g = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  189341. else
  189342. g = 1.0;
  189343. png_ptr->gamma_16_table = (png_uint_16pp)png_malloc(png_ptr,
  189344. (png_uint_32)(num * png_sizeof (png_uint_16p)));
  189345. if (png_ptr->transformations & (PNG_16_TO_8 | PNG_BACKGROUND))
  189346. {
  189347. double fin, fout;
  189348. png_uint_32 last, max;
  189349. for (i = 0; i < num; i++)
  189350. {
  189351. png_ptr->gamma_16_table[i] = (png_uint_16p)png_malloc(png_ptr,
  189352. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  189353. }
  189354. g = 1.0 / g;
  189355. last = 0;
  189356. for (i = 0; i < 256; i++)
  189357. {
  189358. fout = ((double)i + 0.5) / 256.0;
  189359. fin = pow(fout, g);
  189360. max = (png_uint_32)(fin * (double)((png_uint_32)num << 8));
  189361. while (last <= max)
  189362. {
  189363. png_ptr->gamma_16_table[(int)(last & (0xff >> shift))]
  189364. [(int)(last >> (8 - shift))] = (png_uint_16)(
  189365. (png_uint_16)i | ((png_uint_16)i << 8));
  189366. last++;
  189367. }
  189368. }
  189369. while (last < ((png_uint_32)num << 8))
  189370. {
  189371. png_ptr->gamma_16_table[(int)(last & (0xff >> shift))]
  189372. [(int)(last >> (8 - shift))] = (png_uint_16)65535L;
  189373. last++;
  189374. }
  189375. }
  189376. else
  189377. {
  189378. for (i = 0; i < num; i++)
  189379. {
  189380. png_ptr->gamma_16_table[i] = (png_uint_16p)png_malloc(png_ptr,
  189381. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  189382. ig = (((png_uint_32)i * (png_uint_32)png_gamma_shift[shift]) >> 4);
  189383. for (j = 0; j < 256; j++)
  189384. {
  189385. png_ptr->gamma_16_table[i][j] =
  189386. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  189387. 65535.0, g) * 65535.0 + .5);
  189388. }
  189389. }
  189390. }
  189391. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || \
  189392. defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  189393. if (png_ptr->transformations & (PNG_BACKGROUND | PNG_RGB_TO_GRAY))
  189394. {
  189395. g = 1.0 / (png_ptr->gamma);
  189396. png_ptr->gamma_16_to_1 = (png_uint_16pp)png_malloc(png_ptr,
  189397. (png_uint_32)(num * png_sizeof (png_uint_16p )));
  189398. for (i = 0; i < num; i++)
  189399. {
  189400. png_ptr->gamma_16_to_1[i] = (png_uint_16p)png_malloc(png_ptr,
  189401. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  189402. ig = (((png_uint_32)i *
  189403. (png_uint_32)png_gamma_shift[shift]) >> 4);
  189404. for (j = 0; j < 256; j++)
  189405. {
  189406. png_ptr->gamma_16_to_1[i][j] =
  189407. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  189408. 65535.0, g) * 65535.0 + .5);
  189409. }
  189410. }
  189411. if(png_ptr->screen_gamma > 0.000001)
  189412. g = 1.0 / png_ptr->screen_gamma;
  189413. else
  189414. g = png_ptr->gamma; /* probably doing rgb_to_gray */
  189415. png_ptr->gamma_16_from_1 = (png_uint_16pp)png_malloc(png_ptr,
  189416. (png_uint_32)(num * png_sizeof (png_uint_16p)));
  189417. for (i = 0; i < num; i++)
  189418. {
  189419. png_ptr->gamma_16_from_1[i] = (png_uint_16p)png_malloc(png_ptr,
  189420. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  189421. ig = (((png_uint_32)i *
  189422. (png_uint_32)png_gamma_shift[shift]) >> 4);
  189423. for (j = 0; j < 256; j++)
  189424. {
  189425. png_ptr->gamma_16_from_1[i][j] =
  189426. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  189427. 65535.0, g) * 65535.0 + .5);
  189428. }
  189429. }
  189430. }
  189431. #endif /* PNG_READ_BACKGROUND_SUPPORTED || PNG_RGB_TO_GRAY_SUPPORTED */
  189432. }
  189433. }
  189434. #endif
  189435. /* To do: install integer version of png_build_gamma_table here */
  189436. #endif
  189437. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  189438. /* undoes intrapixel differencing */
  189439. void /* PRIVATE */
  189440. png_do_read_intrapixel(png_row_infop row_info, png_bytep row)
  189441. {
  189442. png_debug(1, "in png_do_read_intrapixel\n");
  189443. if (
  189444. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  189445. row != NULL && row_info != NULL &&
  189446. #endif
  189447. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  189448. {
  189449. int bytes_per_pixel;
  189450. png_uint_32 row_width = row_info->width;
  189451. if (row_info->bit_depth == 8)
  189452. {
  189453. png_bytep rp;
  189454. png_uint_32 i;
  189455. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  189456. bytes_per_pixel = 3;
  189457. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  189458. bytes_per_pixel = 4;
  189459. else
  189460. return;
  189461. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  189462. {
  189463. *(rp) = (png_byte)((256 + *rp + *(rp+1))&0xff);
  189464. *(rp+2) = (png_byte)((256 + *(rp+2) + *(rp+1))&0xff);
  189465. }
  189466. }
  189467. else if (row_info->bit_depth == 16)
  189468. {
  189469. png_bytep rp;
  189470. png_uint_32 i;
  189471. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  189472. bytes_per_pixel = 6;
  189473. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  189474. bytes_per_pixel = 8;
  189475. else
  189476. return;
  189477. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  189478. {
  189479. png_uint_32 s0 = (*(rp ) << 8) | *(rp+1);
  189480. png_uint_32 s1 = (*(rp+2) << 8) | *(rp+3);
  189481. png_uint_32 s2 = (*(rp+4) << 8) | *(rp+5);
  189482. png_uint_32 red = (png_uint_32)((s0+s1+65536L) & 0xffffL);
  189483. png_uint_32 blue = (png_uint_32)((s2+s1+65536L) & 0xffffL);
  189484. *(rp ) = (png_byte)((red >> 8) & 0xff);
  189485. *(rp+1) = (png_byte)(red & 0xff);
  189486. *(rp+4) = (png_byte)((blue >> 8) & 0xff);
  189487. *(rp+5) = (png_byte)(blue & 0xff);
  189488. }
  189489. }
  189490. }
  189491. }
  189492. #endif /* PNG_MNG_FEATURES_SUPPORTED */
  189493. #endif /* PNG_READ_SUPPORTED */
  189494. /********* End of inlined file: pngrtran.c *********/
  189495. /********* Start of inlined file: pngrutil.c *********/
  189496. /* pngrutil.c - utilities to read a PNG file
  189497. *
  189498. * Last changed in libpng 1.2.21 [October 4, 2007]
  189499. * For conditions of distribution and use, see copyright notice in png.h
  189500. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  189501. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  189502. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  189503. *
  189504. * This file contains routines that are only called from within
  189505. * libpng itself during the course of reading an image.
  189506. */
  189507. #define PNG_INTERNAL
  189508. #if defined(PNG_READ_SUPPORTED)
  189509. #if defined(_WIN32_WCE) && (_WIN32_WCE<0x500)
  189510. # define WIN32_WCE_OLD
  189511. #endif
  189512. #ifdef PNG_FLOATING_POINT_SUPPORTED
  189513. # if defined(WIN32_WCE_OLD)
  189514. /* strtod() function is not supported on WindowsCE */
  189515. __inline double png_strtod(png_structp png_ptr, PNG_CONST char *nptr, char **endptr)
  189516. {
  189517. double result = 0;
  189518. int len;
  189519. wchar_t *str, *end;
  189520. len = MultiByteToWideChar(CP_ACP, 0, nptr, -1, NULL, 0);
  189521. str = (wchar_t *)png_malloc(png_ptr, len * sizeof(wchar_t));
  189522. if ( NULL != str )
  189523. {
  189524. MultiByteToWideChar(CP_ACP, 0, nptr, -1, str, len);
  189525. result = wcstod(str, &end);
  189526. len = WideCharToMultiByte(CP_ACP, 0, end, -1, NULL, 0, NULL, NULL);
  189527. *endptr = (char *)nptr + (png_strlen(nptr) - len + 1);
  189528. png_free(png_ptr, str);
  189529. }
  189530. return result;
  189531. }
  189532. # else
  189533. # define png_strtod(p,a,b) strtod(a,b)
  189534. # endif
  189535. #endif
  189536. png_uint_32 PNGAPI
  189537. png_get_uint_31(png_structp png_ptr, png_bytep buf)
  189538. {
  189539. png_uint_32 i = png_get_uint_32(buf);
  189540. if (i > PNG_UINT_31_MAX)
  189541. png_error(png_ptr, "PNG unsigned integer out of range.");
  189542. return (i);
  189543. }
  189544. #ifndef PNG_READ_BIG_ENDIAN_SUPPORTED
  189545. /* Grab an unsigned 32-bit integer from a buffer in big-endian format. */
  189546. png_uint_32 PNGAPI
  189547. png_get_uint_32(png_bytep buf)
  189548. {
  189549. png_uint_32 i = ((png_uint_32)(*buf) << 24) +
  189550. ((png_uint_32)(*(buf + 1)) << 16) +
  189551. ((png_uint_32)(*(buf + 2)) << 8) +
  189552. (png_uint_32)(*(buf + 3));
  189553. return (i);
  189554. }
  189555. /* Grab a signed 32-bit integer from a buffer in big-endian format. The
  189556. * data is stored in the PNG file in two's complement format, and it is
  189557. * assumed that the machine format for signed integers is the same. */
  189558. png_int_32 PNGAPI
  189559. png_get_int_32(png_bytep buf)
  189560. {
  189561. png_int_32 i = ((png_int_32)(*buf) << 24) +
  189562. ((png_int_32)(*(buf + 1)) << 16) +
  189563. ((png_int_32)(*(buf + 2)) << 8) +
  189564. (png_int_32)(*(buf + 3));
  189565. return (i);
  189566. }
  189567. /* Grab an unsigned 16-bit integer from a buffer in big-endian format. */
  189568. png_uint_16 PNGAPI
  189569. png_get_uint_16(png_bytep buf)
  189570. {
  189571. png_uint_16 i = (png_uint_16)(((png_uint_16)(*buf) << 8) +
  189572. (png_uint_16)(*(buf + 1)));
  189573. return (i);
  189574. }
  189575. #endif /* PNG_READ_BIG_ENDIAN_SUPPORTED */
  189576. /* Read data, and (optionally) run it through the CRC. */
  189577. void /* PRIVATE */
  189578. png_crc_read(png_structp png_ptr, png_bytep buf, png_size_t length)
  189579. {
  189580. if(png_ptr == NULL) return;
  189581. png_read_data(png_ptr, buf, length);
  189582. png_calculate_crc(png_ptr, buf, length);
  189583. }
  189584. /* Optionally skip data and then check the CRC. Depending on whether we
  189585. are reading a ancillary or critical chunk, and how the program has set
  189586. things up, we may calculate the CRC on the data and print a message.
  189587. Returns '1' if there was a CRC error, '0' otherwise. */
  189588. int /* PRIVATE */
  189589. png_crc_finish(png_structp png_ptr, png_uint_32 skip)
  189590. {
  189591. png_size_t i;
  189592. png_size_t istop = png_ptr->zbuf_size;
  189593. for (i = (png_size_t)skip; i > istop; i -= istop)
  189594. {
  189595. png_crc_read(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  189596. }
  189597. if (i)
  189598. {
  189599. png_crc_read(png_ptr, png_ptr->zbuf, i);
  189600. }
  189601. if (png_crc_error(png_ptr))
  189602. {
  189603. if (((png_ptr->chunk_name[0] & 0x20) && /* Ancillary */
  189604. !(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN)) ||
  189605. (!(png_ptr->chunk_name[0] & 0x20) && /* Critical */
  189606. (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_USE)))
  189607. {
  189608. png_chunk_warning(png_ptr, "CRC error");
  189609. }
  189610. else
  189611. {
  189612. png_chunk_error(png_ptr, "CRC error");
  189613. }
  189614. return (1);
  189615. }
  189616. return (0);
  189617. }
  189618. /* Compare the CRC stored in the PNG file with that calculated by libpng from
  189619. the data it has read thus far. */
  189620. int /* PRIVATE */
  189621. png_crc_error(png_structp png_ptr)
  189622. {
  189623. png_byte crc_bytes[4];
  189624. png_uint_32 crc;
  189625. int need_crc = 1;
  189626. if (png_ptr->chunk_name[0] & 0x20) /* ancillary */
  189627. {
  189628. if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_MASK) ==
  189629. (PNG_FLAG_CRC_ANCILLARY_USE | PNG_FLAG_CRC_ANCILLARY_NOWARN))
  189630. need_crc = 0;
  189631. }
  189632. else /* critical */
  189633. {
  189634. if (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_IGNORE)
  189635. need_crc = 0;
  189636. }
  189637. png_read_data(png_ptr, crc_bytes, 4);
  189638. if (need_crc)
  189639. {
  189640. crc = png_get_uint_32(crc_bytes);
  189641. return ((int)(crc != png_ptr->crc));
  189642. }
  189643. else
  189644. return (0);
  189645. }
  189646. #if defined(PNG_READ_zTXt_SUPPORTED) || defined(PNG_READ_iTXt_SUPPORTED) || \
  189647. defined(PNG_READ_iCCP_SUPPORTED)
  189648. /*
  189649. * Decompress trailing data in a chunk. The assumption is that chunkdata
  189650. * points at an allocated area holding the contents of a chunk with a
  189651. * trailing compressed part. What we get back is an allocated area
  189652. * holding the original prefix part and an uncompressed version of the
  189653. * trailing part (the malloc area passed in is freed).
  189654. */
  189655. png_charp /* PRIVATE */
  189656. png_decompress_chunk(png_structp png_ptr, int comp_type,
  189657. png_charp chunkdata, png_size_t chunklength,
  189658. png_size_t prefix_size, png_size_t *newlength)
  189659. {
  189660. static PNG_CONST char msg[] = "Error decoding compressed text";
  189661. png_charp text;
  189662. png_size_t text_size;
  189663. if (comp_type == PNG_COMPRESSION_TYPE_BASE)
  189664. {
  189665. int ret = Z_OK;
  189666. png_ptr->zstream.next_in = (png_bytep)(chunkdata + prefix_size);
  189667. png_ptr->zstream.avail_in = (uInt)(chunklength - prefix_size);
  189668. png_ptr->zstream.next_out = png_ptr->zbuf;
  189669. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  189670. text_size = 0;
  189671. text = NULL;
  189672. while (png_ptr->zstream.avail_in)
  189673. {
  189674. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  189675. if (ret != Z_OK && ret != Z_STREAM_END)
  189676. {
  189677. if (png_ptr->zstream.msg != NULL)
  189678. png_warning(png_ptr, png_ptr->zstream.msg);
  189679. else
  189680. png_warning(png_ptr, msg);
  189681. inflateReset(&png_ptr->zstream);
  189682. png_ptr->zstream.avail_in = 0;
  189683. if (text == NULL)
  189684. {
  189685. text_size = prefix_size + png_sizeof(msg) + 1;
  189686. text = (png_charp)png_malloc_warn(png_ptr, text_size);
  189687. if (text == NULL)
  189688. {
  189689. png_free(png_ptr,chunkdata);
  189690. png_error(png_ptr,"Not enough memory to decompress chunk");
  189691. }
  189692. png_memcpy(text, chunkdata, prefix_size);
  189693. }
  189694. text[text_size - 1] = 0x00;
  189695. /* Copy what we can of the error message into the text chunk */
  189696. text_size = (png_size_t)(chunklength - (text - chunkdata) - 1);
  189697. text_size = png_sizeof(msg) > text_size ? text_size :
  189698. png_sizeof(msg);
  189699. png_memcpy(text + prefix_size, msg, text_size + 1);
  189700. break;
  189701. }
  189702. if (!png_ptr->zstream.avail_out || ret == Z_STREAM_END)
  189703. {
  189704. if (text == NULL)
  189705. {
  189706. text_size = prefix_size +
  189707. png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  189708. text = (png_charp)png_malloc_warn(png_ptr, text_size + 1);
  189709. if (text == NULL)
  189710. {
  189711. png_free(png_ptr,chunkdata);
  189712. png_error(png_ptr,"Not enough memory to decompress chunk.");
  189713. }
  189714. png_memcpy(text + prefix_size, png_ptr->zbuf,
  189715. text_size - prefix_size);
  189716. png_memcpy(text, chunkdata, prefix_size);
  189717. *(text + text_size) = 0x00;
  189718. }
  189719. else
  189720. {
  189721. png_charp tmp;
  189722. tmp = text;
  189723. text = (png_charp)png_malloc_warn(png_ptr,
  189724. (png_uint_32)(text_size +
  189725. png_ptr->zbuf_size - png_ptr->zstream.avail_out + 1));
  189726. if (text == NULL)
  189727. {
  189728. png_free(png_ptr, tmp);
  189729. png_free(png_ptr, chunkdata);
  189730. png_error(png_ptr,"Not enough memory to decompress chunk..");
  189731. }
  189732. png_memcpy(text, tmp, text_size);
  189733. png_free(png_ptr, tmp);
  189734. png_memcpy(text + text_size, png_ptr->zbuf,
  189735. (png_ptr->zbuf_size - png_ptr->zstream.avail_out));
  189736. text_size += png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  189737. *(text + text_size) = 0x00;
  189738. }
  189739. if (ret == Z_STREAM_END)
  189740. break;
  189741. else
  189742. {
  189743. png_ptr->zstream.next_out = png_ptr->zbuf;
  189744. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  189745. }
  189746. }
  189747. }
  189748. if (ret != Z_STREAM_END)
  189749. {
  189750. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  189751. char umsg[52];
  189752. if (ret == Z_BUF_ERROR)
  189753. png_snprintf(umsg, 52,
  189754. "Buffer error in compressed datastream in %s chunk",
  189755. png_ptr->chunk_name);
  189756. else if (ret == Z_DATA_ERROR)
  189757. png_snprintf(umsg, 52,
  189758. "Data error in compressed datastream in %s chunk",
  189759. png_ptr->chunk_name);
  189760. else
  189761. png_snprintf(umsg, 52,
  189762. "Incomplete compressed datastream in %s chunk",
  189763. png_ptr->chunk_name);
  189764. png_warning(png_ptr, umsg);
  189765. #else
  189766. png_warning(png_ptr,
  189767. "Incomplete compressed datastream in chunk other than IDAT");
  189768. #endif
  189769. text_size=prefix_size;
  189770. if (text == NULL)
  189771. {
  189772. text = (png_charp)png_malloc_warn(png_ptr, text_size+1);
  189773. if (text == NULL)
  189774. {
  189775. png_free(png_ptr, chunkdata);
  189776. png_error(png_ptr,"Not enough memory for text.");
  189777. }
  189778. png_memcpy(text, chunkdata, prefix_size);
  189779. }
  189780. *(text + text_size) = 0x00;
  189781. }
  189782. inflateReset(&png_ptr->zstream);
  189783. png_ptr->zstream.avail_in = 0;
  189784. png_free(png_ptr, chunkdata);
  189785. chunkdata = text;
  189786. *newlength=text_size;
  189787. }
  189788. else /* if (comp_type != PNG_COMPRESSION_TYPE_BASE) */
  189789. {
  189790. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  189791. char umsg[50];
  189792. png_snprintf(umsg, 50,
  189793. "Unknown zTXt compression type %d", comp_type);
  189794. png_warning(png_ptr, umsg);
  189795. #else
  189796. png_warning(png_ptr, "Unknown zTXt compression type");
  189797. #endif
  189798. *(chunkdata + prefix_size) = 0x00;
  189799. *newlength=prefix_size;
  189800. }
  189801. return chunkdata;
  189802. }
  189803. #endif
  189804. /* read and check the IDHR chunk */
  189805. void /* PRIVATE */
  189806. png_handle_IHDR(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  189807. {
  189808. png_byte buf[13];
  189809. png_uint_32 width, height;
  189810. int bit_depth, color_type, compression_type, filter_type;
  189811. int interlace_type;
  189812. png_debug(1, "in png_handle_IHDR\n");
  189813. if (png_ptr->mode & PNG_HAVE_IHDR)
  189814. png_error(png_ptr, "Out of place IHDR");
  189815. /* check the length */
  189816. if (length != 13)
  189817. png_error(png_ptr, "Invalid IHDR chunk");
  189818. png_ptr->mode |= PNG_HAVE_IHDR;
  189819. png_crc_read(png_ptr, buf, 13);
  189820. png_crc_finish(png_ptr, 0);
  189821. width = png_get_uint_31(png_ptr, buf);
  189822. height = png_get_uint_31(png_ptr, buf + 4);
  189823. bit_depth = buf[8];
  189824. color_type = buf[9];
  189825. compression_type = buf[10];
  189826. filter_type = buf[11];
  189827. interlace_type = buf[12];
  189828. /* set internal variables */
  189829. png_ptr->width = width;
  189830. png_ptr->height = height;
  189831. png_ptr->bit_depth = (png_byte)bit_depth;
  189832. png_ptr->interlaced = (png_byte)interlace_type;
  189833. png_ptr->color_type = (png_byte)color_type;
  189834. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  189835. png_ptr->filter_type = (png_byte)filter_type;
  189836. #endif
  189837. png_ptr->compression_type = (png_byte)compression_type;
  189838. /* find number of channels */
  189839. switch (png_ptr->color_type)
  189840. {
  189841. case PNG_COLOR_TYPE_GRAY:
  189842. case PNG_COLOR_TYPE_PALETTE:
  189843. png_ptr->channels = 1;
  189844. break;
  189845. case PNG_COLOR_TYPE_RGB:
  189846. png_ptr->channels = 3;
  189847. break;
  189848. case PNG_COLOR_TYPE_GRAY_ALPHA:
  189849. png_ptr->channels = 2;
  189850. break;
  189851. case PNG_COLOR_TYPE_RGB_ALPHA:
  189852. png_ptr->channels = 4;
  189853. break;
  189854. }
  189855. /* set up other useful info */
  189856. png_ptr->pixel_depth = (png_byte)(png_ptr->bit_depth *
  189857. png_ptr->channels);
  189858. png_ptr->rowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,png_ptr->width);
  189859. png_debug1(3,"bit_depth = %d\n", png_ptr->bit_depth);
  189860. png_debug1(3,"channels = %d\n", png_ptr->channels);
  189861. png_debug1(3,"rowbytes = %lu\n", png_ptr->rowbytes);
  189862. png_set_IHDR(png_ptr, info_ptr, width, height, bit_depth,
  189863. color_type, interlace_type, compression_type, filter_type);
  189864. }
  189865. /* read and check the palette */
  189866. void /* PRIVATE */
  189867. png_handle_PLTE(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  189868. {
  189869. png_color palette[PNG_MAX_PALETTE_LENGTH];
  189870. int num, i;
  189871. #ifndef PNG_NO_POINTER_INDEXING
  189872. png_colorp pal_ptr;
  189873. #endif
  189874. png_debug(1, "in png_handle_PLTE\n");
  189875. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  189876. png_error(png_ptr, "Missing IHDR before PLTE");
  189877. else if (png_ptr->mode & PNG_HAVE_IDAT)
  189878. {
  189879. png_warning(png_ptr, "Invalid PLTE after IDAT");
  189880. png_crc_finish(png_ptr, length);
  189881. return;
  189882. }
  189883. else if (png_ptr->mode & PNG_HAVE_PLTE)
  189884. png_error(png_ptr, "Duplicate PLTE chunk");
  189885. png_ptr->mode |= PNG_HAVE_PLTE;
  189886. if (!(png_ptr->color_type&PNG_COLOR_MASK_COLOR))
  189887. {
  189888. png_warning(png_ptr,
  189889. "Ignoring PLTE chunk in grayscale PNG");
  189890. png_crc_finish(png_ptr, length);
  189891. return;
  189892. }
  189893. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  189894. if (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE)
  189895. {
  189896. png_crc_finish(png_ptr, length);
  189897. return;
  189898. }
  189899. #endif
  189900. if (length > 3*PNG_MAX_PALETTE_LENGTH || length % 3)
  189901. {
  189902. if (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE)
  189903. {
  189904. png_warning(png_ptr, "Invalid palette chunk");
  189905. png_crc_finish(png_ptr, length);
  189906. return;
  189907. }
  189908. else
  189909. {
  189910. png_error(png_ptr, "Invalid palette chunk");
  189911. }
  189912. }
  189913. num = (int)length / 3;
  189914. #ifndef PNG_NO_POINTER_INDEXING
  189915. for (i = 0, pal_ptr = palette; i < num; i++, pal_ptr++)
  189916. {
  189917. png_byte buf[3];
  189918. png_crc_read(png_ptr, buf, 3);
  189919. pal_ptr->red = buf[0];
  189920. pal_ptr->green = buf[1];
  189921. pal_ptr->blue = buf[2];
  189922. }
  189923. #else
  189924. for (i = 0; i < num; i++)
  189925. {
  189926. png_byte buf[3];
  189927. png_crc_read(png_ptr, buf, 3);
  189928. /* don't depend upon png_color being any order */
  189929. palette[i].red = buf[0];
  189930. palette[i].green = buf[1];
  189931. palette[i].blue = buf[2];
  189932. }
  189933. #endif
  189934. /* If we actually NEED the PLTE chunk (ie for a paletted image), we do
  189935. whatever the normal CRC configuration tells us. However, if we
  189936. have an RGB image, the PLTE can be considered ancillary, so
  189937. we will act as though it is. */
  189938. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  189939. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  189940. #endif
  189941. {
  189942. png_crc_finish(png_ptr, 0);
  189943. }
  189944. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  189945. else if (png_crc_error(png_ptr)) /* Only if we have a CRC error */
  189946. {
  189947. /* If we don't want to use the data from an ancillary chunk,
  189948. we have two options: an error abort, or a warning and we
  189949. ignore the data in this chunk (which should be OK, since
  189950. it's considered ancillary for a RGB or RGBA image). */
  189951. if (!(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_USE))
  189952. {
  189953. if (png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN)
  189954. {
  189955. png_chunk_error(png_ptr, "CRC error");
  189956. }
  189957. else
  189958. {
  189959. png_chunk_warning(png_ptr, "CRC error");
  189960. return;
  189961. }
  189962. }
  189963. /* Otherwise, we (optionally) emit a warning and use the chunk. */
  189964. else if (!(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN))
  189965. {
  189966. png_chunk_warning(png_ptr, "CRC error");
  189967. }
  189968. }
  189969. #endif
  189970. png_set_PLTE(png_ptr, info_ptr, palette, num);
  189971. #if defined(PNG_READ_tRNS_SUPPORTED)
  189972. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  189973. {
  189974. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  189975. {
  189976. if (png_ptr->num_trans > (png_uint_16)num)
  189977. {
  189978. png_warning(png_ptr, "Truncating incorrect tRNS chunk length");
  189979. png_ptr->num_trans = (png_uint_16)num;
  189980. }
  189981. if (info_ptr->num_trans > (png_uint_16)num)
  189982. {
  189983. png_warning(png_ptr, "Truncating incorrect info tRNS chunk length");
  189984. info_ptr->num_trans = (png_uint_16)num;
  189985. }
  189986. }
  189987. }
  189988. #endif
  189989. }
  189990. void /* PRIVATE */
  189991. png_handle_IEND(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  189992. {
  189993. png_debug(1, "in png_handle_IEND\n");
  189994. if (!(png_ptr->mode & PNG_HAVE_IHDR) || !(png_ptr->mode & PNG_HAVE_IDAT))
  189995. {
  189996. png_error(png_ptr, "No image in file");
  189997. }
  189998. png_ptr->mode |= (PNG_AFTER_IDAT | PNG_HAVE_IEND);
  189999. if (length != 0)
  190000. {
  190001. png_warning(png_ptr, "Incorrect IEND chunk length");
  190002. }
  190003. png_crc_finish(png_ptr, length);
  190004. info_ptr =info_ptr; /* quiet compiler warnings about unused info_ptr */
  190005. }
  190006. #if defined(PNG_READ_gAMA_SUPPORTED)
  190007. void /* PRIVATE */
  190008. png_handle_gAMA(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  190009. {
  190010. png_fixed_point igamma;
  190011. #ifdef PNG_FLOATING_POINT_SUPPORTED
  190012. float file_gamma;
  190013. #endif
  190014. png_byte buf[4];
  190015. png_debug(1, "in png_handle_gAMA\n");
  190016. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  190017. png_error(png_ptr, "Missing IHDR before gAMA");
  190018. else if (png_ptr->mode & PNG_HAVE_IDAT)
  190019. {
  190020. png_warning(png_ptr, "Invalid gAMA after IDAT");
  190021. png_crc_finish(png_ptr, length);
  190022. return;
  190023. }
  190024. else if (png_ptr->mode & PNG_HAVE_PLTE)
  190025. /* Should be an error, but we can cope with it */
  190026. png_warning(png_ptr, "Out of place gAMA chunk");
  190027. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  190028. #if defined(PNG_READ_sRGB_SUPPORTED)
  190029. && !(info_ptr->valid & PNG_INFO_sRGB)
  190030. #endif
  190031. )
  190032. {
  190033. png_warning(png_ptr, "Duplicate gAMA chunk");
  190034. png_crc_finish(png_ptr, length);
  190035. return;
  190036. }
  190037. if (length != 4)
  190038. {
  190039. png_warning(png_ptr, "Incorrect gAMA chunk length");
  190040. png_crc_finish(png_ptr, length);
  190041. return;
  190042. }
  190043. png_crc_read(png_ptr, buf, 4);
  190044. if (png_crc_finish(png_ptr, 0))
  190045. return;
  190046. igamma = (png_fixed_point)png_get_uint_32(buf);
  190047. /* check for zero gamma */
  190048. if (igamma == 0)
  190049. {
  190050. png_warning(png_ptr,
  190051. "Ignoring gAMA chunk with gamma=0");
  190052. return;
  190053. }
  190054. #if defined(PNG_READ_sRGB_SUPPORTED)
  190055. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB))
  190056. if (PNG_OUT_OF_RANGE(igamma, 45500L, 500))
  190057. {
  190058. png_warning(png_ptr,
  190059. "Ignoring incorrect gAMA value when sRGB is also present");
  190060. #ifndef PNG_NO_CONSOLE_IO
  190061. fprintf(stderr, "gamma = (%d/100000)\n", (int)igamma);
  190062. #endif
  190063. return;
  190064. }
  190065. #endif /* PNG_READ_sRGB_SUPPORTED */
  190066. #ifdef PNG_FLOATING_POINT_SUPPORTED
  190067. file_gamma = (float)igamma / (float)100000.0;
  190068. # ifdef PNG_READ_GAMMA_SUPPORTED
  190069. png_ptr->gamma = file_gamma;
  190070. # endif
  190071. png_set_gAMA(png_ptr, info_ptr, file_gamma);
  190072. #endif
  190073. #ifdef PNG_FIXED_POINT_SUPPORTED
  190074. png_set_gAMA_fixed(png_ptr, info_ptr, igamma);
  190075. #endif
  190076. }
  190077. #endif
  190078. #if defined(PNG_READ_sBIT_SUPPORTED)
  190079. void /* PRIVATE */
  190080. png_handle_sBIT(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  190081. {
  190082. png_size_t truelen;
  190083. png_byte buf[4];
  190084. png_debug(1, "in png_handle_sBIT\n");
  190085. buf[0] = buf[1] = buf[2] = buf[3] = 0;
  190086. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  190087. png_error(png_ptr, "Missing IHDR before sBIT");
  190088. else if (png_ptr->mode & PNG_HAVE_IDAT)
  190089. {
  190090. png_warning(png_ptr, "Invalid sBIT after IDAT");
  190091. png_crc_finish(png_ptr, length);
  190092. return;
  190093. }
  190094. else if (png_ptr->mode & PNG_HAVE_PLTE)
  190095. {
  190096. /* Should be an error, but we can cope with it */
  190097. png_warning(png_ptr, "Out of place sBIT chunk");
  190098. }
  190099. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sBIT))
  190100. {
  190101. png_warning(png_ptr, "Duplicate sBIT chunk");
  190102. png_crc_finish(png_ptr, length);
  190103. return;
  190104. }
  190105. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  190106. truelen = 3;
  190107. else
  190108. truelen = (png_size_t)png_ptr->channels;
  190109. if (length != truelen || length > 4)
  190110. {
  190111. png_warning(png_ptr, "Incorrect sBIT chunk length");
  190112. png_crc_finish(png_ptr, length);
  190113. return;
  190114. }
  190115. png_crc_read(png_ptr, buf, truelen);
  190116. if (png_crc_finish(png_ptr, 0))
  190117. return;
  190118. if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  190119. {
  190120. png_ptr->sig_bit.red = buf[0];
  190121. png_ptr->sig_bit.green = buf[1];
  190122. png_ptr->sig_bit.blue = buf[2];
  190123. png_ptr->sig_bit.alpha = buf[3];
  190124. }
  190125. else
  190126. {
  190127. png_ptr->sig_bit.gray = buf[0];
  190128. png_ptr->sig_bit.red = buf[0];
  190129. png_ptr->sig_bit.green = buf[0];
  190130. png_ptr->sig_bit.blue = buf[0];
  190131. png_ptr->sig_bit.alpha = buf[1];
  190132. }
  190133. png_set_sBIT(png_ptr, info_ptr, &(png_ptr->sig_bit));
  190134. }
  190135. #endif
  190136. #if defined(PNG_READ_cHRM_SUPPORTED)
  190137. void /* PRIVATE */
  190138. png_handle_cHRM(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  190139. {
  190140. png_byte buf[4];
  190141. #ifdef PNG_FLOATING_POINT_SUPPORTED
  190142. float white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y;
  190143. #endif
  190144. png_fixed_point int_x_white, int_y_white, int_x_red, int_y_red, int_x_green,
  190145. int_y_green, int_x_blue, int_y_blue;
  190146. png_uint_32 uint_x, uint_y;
  190147. png_debug(1, "in png_handle_cHRM\n");
  190148. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  190149. png_error(png_ptr, "Missing IHDR before cHRM");
  190150. else if (png_ptr->mode & PNG_HAVE_IDAT)
  190151. {
  190152. png_warning(png_ptr, "Invalid cHRM after IDAT");
  190153. png_crc_finish(png_ptr, length);
  190154. return;
  190155. }
  190156. else if (png_ptr->mode & PNG_HAVE_PLTE)
  190157. /* Should be an error, but we can cope with it */
  190158. png_warning(png_ptr, "Missing PLTE before cHRM");
  190159. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM)
  190160. #if defined(PNG_READ_sRGB_SUPPORTED)
  190161. && !(info_ptr->valid & PNG_INFO_sRGB)
  190162. #endif
  190163. )
  190164. {
  190165. png_warning(png_ptr, "Duplicate cHRM chunk");
  190166. png_crc_finish(png_ptr, length);
  190167. return;
  190168. }
  190169. if (length != 32)
  190170. {
  190171. png_warning(png_ptr, "Incorrect cHRM chunk length");
  190172. png_crc_finish(png_ptr, length);
  190173. return;
  190174. }
  190175. png_crc_read(png_ptr, buf, 4);
  190176. uint_x = png_get_uint_32(buf);
  190177. png_crc_read(png_ptr, buf, 4);
  190178. uint_y = png_get_uint_32(buf);
  190179. if (uint_x > 80000L || uint_y > 80000L ||
  190180. uint_x + uint_y > 100000L)
  190181. {
  190182. png_warning(png_ptr, "Invalid cHRM white point");
  190183. png_crc_finish(png_ptr, 24);
  190184. return;
  190185. }
  190186. int_x_white = (png_fixed_point)uint_x;
  190187. int_y_white = (png_fixed_point)uint_y;
  190188. png_crc_read(png_ptr, buf, 4);
  190189. uint_x = png_get_uint_32(buf);
  190190. png_crc_read(png_ptr, buf, 4);
  190191. uint_y = png_get_uint_32(buf);
  190192. if (uint_x + uint_y > 100000L)
  190193. {
  190194. png_warning(png_ptr, "Invalid cHRM red point");
  190195. png_crc_finish(png_ptr, 16);
  190196. return;
  190197. }
  190198. int_x_red = (png_fixed_point)uint_x;
  190199. int_y_red = (png_fixed_point)uint_y;
  190200. png_crc_read(png_ptr, buf, 4);
  190201. uint_x = png_get_uint_32(buf);
  190202. png_crc_read(png_ptr, buf, 4);
  190203. uint_y = png_get_uint_32(buf);
  190204. if (uint_x + uint_y > 100000L)
  190205. {
  190206. png_warning(png_ptr, "Invalid cHRM green point");
  190207. png_crc_finish(png_ptr, 8);
  190208. return;
  190209. }
  190210. int_x_green = (png_fixed_point)uint_x;
  190211. int_y_green = (png_fixed_point)uint_y;
  190212. png_crc_read(png_ptr, buf, 4);
  190213. uint_x = png_get_uint_32(buf);
  190214. png_crc_read(png_ptr, buf, 4);
  190215. uint_y = png_get_uint_32(buf);
  190216. if (uint_x + uint_y > 100000L)
  190217. {
  190218. png_warning(png_ptr, "Invalid cHRM blue point");
  190219. png_crc_finish(png_ptr, 0);
  190220. return;
  190221. }
  190222. int_x_blue = (png_fixed_point)uint_x;
  190223. int_y_blue = (png_fixed_point)uint_y;
  190224. #ifdef PNG_FLOATING_POINT_SUPPORTED
  190225. white_x = (float)int_x_white / (float)100000.0;
  190226. white_y = (float)int_y_white / (float)100000.0;
  190227. red_x = (float)int_x_red / (float)100000.0;
  190228. red_y = (float)int_y_red / (float)100000.0;
  190229. green_x = (float)int_x_green / (float)100000.0;
  190230. green_y = (float)int_y_green / (float)100000.0;
  190231. blue_x = (float)int_x_blue / (float)100000.0;
  190232. blue_y = (float)int_y_blue / (float)100000.0;
  190233. #endif
  190234. #if defined(PNG_READ_sRGB_SUPPORTED)
  190235. if ((info_ptr != NULL) && (info_ptr->valid & PNG_INFO_sRGB))
  190236. {
  190237. if (PNG_OUT_OF_RANGE(int_x_white, 31270, 1000) ||
  190238. PNG_OUT_OF_RANGE(int_y_white, 32900, 1000) ||
  190239. PNG_OUT_OF_RANGE(int_x_red, 64000L, 1000) ||
  190240. PNG_OUT_OF_RANGE(int_y_red, 33000, 1000) ||
  190241. PNG_OUT_OF_RANGE(int_x_green, 30000, 1000) ||
  190242. PNG_OUT_OF_RANGE(int_y_green, 60000L, 1000) ||
  190243. PNG_OUT_OF_RANGE(int_x_blue, 15000, 1000) ||
  190244. PNG_OUT_OF_RANGE(int_y_blue, 6000, 1000))
  190245. {
  190246. png_warning(png_ptr,
  190247. "Ignoring incorrect cHRM value when sRGB is also present");
  190248. #ifndef PNG_NO_CONSOLE_IO
  190249. #ifdef PNG_FLOATING_POINT_SUPPORTED
  190250. fprintf(stderr,"wx=%f, wy=%f, rx=%f, ry=%f\n",
  190251. white_x, white_y, red_x, red_y);
  190252. fprintf(stderr,"gx=%f, gy=%f, bx=%f, by=%f\n",
  190253. green_x, green_y, blue_x, blue_y);
  190254. #else
  190255. fprintf(stderr,"wx=%ld, wy=%ld, rx=%ld, ry=%ld\n",
  190256. int_x_white, int_y_white, int_x_red, int_y_red);
  190257. fprintf(stderr,"gx=%ld, gy=%ld, bx=%ld, by=%ld\n",
  190258. int_x_green, int_y_green, int_x_blue, int_y_blue);
  190259. #endif
  190260. #endif /* PNG_NO_CONSOLE_IO */
  190261. }
  190262. png_crc_finish(png_ptr, 0);
  190263. return;
  190264. }
  190265. #endif /* PNG_READ_sRGB_SUPPORTED */
  190266. #ifdef PNG_FLOATING_POINT_SUPPORTED
  190267. png_set_cHRM(png_ptr, info_ptr,
  190268. white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y);
  190269. #endif
  190270. #ifdef PNG_FIXED_POINT_SUPPORTED
  190271. png_set_cHRM_fixed(png_ptr, info_ptr,
  190272. int_x_white, int_y_white, int_x_red, int_y_red, int_x_green,
  190273. int_y_green, int_x_blue, int_y_blue);
  190274. #endif
  190275. if (png_crc_finish(png_ptr, 0))
  190276. return;
  190277. }
  190278. #endif
  190279. #if defined(PNG_READ_sRGB_SUPPORTED)
  190280. void /* PRIVATE */
  190281. png_handle_sRGB(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  190282. {
  190283. int intent;
  190284. png_byte buf[1];
  190285. png_debug(1, "in png_handle_sRGB\n");
  190286. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  190287. png_error(png_ptr, "Missing IHDR before sRGB");
  190288. else if (png_ptr->mode & PNG_HAVE_IDAT)
  190289. {
  190290. png_warning(png_ptr, "Invalid sRGB after IDAT");
  190291. png_crc_finish(png_ptr, length);
  190292. return;
  190293. }
  190294. else if (png_ptr->mode & PNG_HAVE_PLTE)
  190295. /* Should be an error, but we can cope with it */
  190296. png_warning(png_ptr, "Out of place sRGB chunk");
  190297. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB))
  190298. {
  190299. png_warning(png_ptr, "Duplicate sRGB chunk");
  190300. png_crc_finish(png_ptr, length);
  190301. return;
  190302. }
  190303. if (length != 1)
  190304. {
  190305. png_warning(png_ptr, "Incorrect sRGB chunk length");
  190306. png_crc_finish(png_ptr, length);
  190307. return;
  190308. }
  190309. png_crc_read(png_ptr, buf, 1);
  190310. if (png_crc_finish(png_ptr, 0))
  190311. return;
  190312. intent = buf[0];
  190313. /* check for bad intent */
  190314. if (intent >= PNG_sRGB_INTENT_LAST)
  190315. {
  190316. png_warning(png_ptr, "Unknown sRGB intent");
  190317. return;
  190318. }
  190319. #if defined(PNG_READ_gAMA_SUPPORTED) && defined(PNG_READ_GAMMA_SUPPORTED)
  190320. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA))
  190321. {
  190322. png_fixed_point igamma;
  190323. #ifdef PNG_FIXED_POINT_SUPPORTED
  190324. igamma=info_ptr->int_gamma;
  190325. #else
  190326. # ifdef PNG_FLOATING_POINT_SUPPORTED
  190327. igamma=(png_fixed_point)(info_ptr->gamma * 100000.);
  190328. # endif
  190329. #endif
  190330. if (PNG_OUT_OF_RANGE(igamma, 45500L, 500))
  190331. {
  190332. png_warning(png_ptr,
  190333. "Ignoring incorrect gAMA value when sRGB is also present");
  190334. #ifndef PNG_NO_CONSOLE_IO
  190335. # ifdef PNG_FIXED_POINT_SUPPORTED
  190336. fprintf(stderr,"incorrect gamma=(%d/100000)\n",(int)png_ptr->int_gamma);
  190337. # else
  190338. # ifdef PNG_FLOATING_POINT_SUPPORTED
  190339. fprintf(stderr,"incorrect gamma=%f\n",png_ptr->gamma);
  190340. # endif
  190341. # endif
  190342. #endif
  190343. }
  190344. }
  190345. #endif /* PNG_READ_gAMA_SUPPORTED */
  190346. #ifdef PNG_READ_cHRM_SUPPORTED
  190347. #ifdef PNG_FIXED_POINT_SUPPORTED
  190348. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  190349. if (PNG_OUT_OF_RANGE(info_ptr->int_x_white, 31270, 1000) ||
  190350. PNG_OUT_OF_RANGE(info_ptr->int_y_white, 32900, 1000) ||
  190351. PNG_OUT_OF_RANGE(info_ptr->int_x_red, 64000L, 1000) ||
  190352. PNG_OUT_OF_RANGE(info_ptr->int_y_red, 33000, 1000) ||
  190353. PNG_OUT_OF_RANGE(info_ptr->int_x_green, 30000, 1000) ||
  190354. PNG_OUT_OF_RANGE(info_ptr->int_y_green, 60000L, 1000) ||
  190355. PNG_OUT_OF_RANGE(info_ptr->int_x_blue, 15000, 1000) ||
  190356. PNG_OUT_OF_RANGE(info_ptr->int_y_blue, 6000, 1000))
  190357. {
  190358. png_warning(png_ptr,
  190359. "Ignoring incorrect cHRM value when sRGB is also present");
  190360. }
  190361. #endif /* PNG_FIXED_POINT_SUPPORTED */
  190362. #endif /* PNG_READ_cHRM_SUPPORTED */
  190363. png_set_sRGB_gAMA_and_cHRM(png_ptr, info_ptr, intent);
  190364. }
  190365. #endif /* PNG_READ_sRGB_SUPPORTED */
  190366. #if defined(PNG_READ_iCCP_SUPPORTED)
  190367. void /* PRIVATE */
  190368. png_handle_iCCP(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  190369. /* Note: this does not properly handle chunks that are > 64K under DOS */
  190370. {
  190371. png_charp chunkdata;
  190372. png_byte compression_type;
  190373. png_bytep pC;
  190374. png_charp profile;
  190375. png_uint_32 skip = 0;
  190376. png_uint_32 profile_size, profile_length;
  190377. png_size_t slength, prefix_length, data_length;
  190378. png_debug(1, "in png_handle_iCCP\n");
  190379. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  190380. png_error(png_ptr, "Missing IHDR before iCCP");
  190381. else if (png_ptr->mode & PNG_HAVE_IDAT)
  190382. {
  190383. png_warning(png_ptr, "Invalid iCCP after IDAT");
  190384. png_crc_finish(png_ptr, length);
  190385. return;
  190386. }
  190387. else if (png_ptr->mode & PNG_HAVE_PLTE)
  190388. /* Should be an error, but we can cope with it */
  190389. png_warning(png_ptr, "Out of place iCCP chunk");
  190390. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_iCCP))
  190391. {
  190392. png_warning(png_ptr, "Duplicate iCCP chunk");
  190393. png_crc_finish(png_ptr, length);
  190394. return;
  190395. }
  190396. #ifdef PNG_MAX_MALLOC_64K
  190397. if (length > (png_uint_32)65535L)
  190398. {
  190399. png_warning(png_ptr, "iCCP chunk too large to fit in memory");
  190400. skip = length - (png_uint_32)65535L;
  190401. length = (png_uint_32)65535L;
  190402. }
  190403. #endif
  190404. chunkdata = (png_charp)png_malloc(png_ptr, length + 1);
  190405. slength = (png_size_t)length;
  190406. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  190407. if (png_crc_finish(png_ptr, skip))
  190408. {
  190409. png_free(png_ptr, chunkdata);
  190410. return;
  190411. }
  190412. chunkdata[slength] = 0x00;
  190413. for (profile = chunkdata; *profile; profile++)
  190414. /* empty loop to find end of name */ ;
  190415. ++profile;
  190416. /* there should be at least one zero (the compression type byte)
  190417. following the separator, and we should be on it */
  190418. if ( profile >= chunkdata + slength - 1)
  190419. {
  190420. png_free(png_ptr, chunkdata);
  190421. png_warning(png_ptr, "Malformed iCCP chunk");
  190422. return;
  190423. }
  190424. /* compression_type should always be zero */
  190425. compression_type = *profile++;
  190426. if (compression_type)
  190427. {
  190428. png_warning(png_ptr, "Ignoring nonzero compression type in iCCP chunk");
  190429. compression_type=0x00; /* Reset it to zero (libpng-1.0.6 through 1.0.8
  190430. wrote nonzero) */
  190431. }
  190432. prefix_length = profile - chunkdata;
  190433. chunkdata = png_decompress_chunk(png_ptr, compression_type, chunkdata,
  190434. slength, prefix_length, &data_length);
  190435. profile_length = data_length - prefix_length;
  190436. if ( prefix_length > data_length || profile_length < 4)
  190437. {
  190438. png_free(png_ptr, chunkdata);
  190439. png_warning(png_ptr, "Profile size field missing from iCCP chunk");
  190440. return;
  190441. }
  190442. /* Check the profile_size recorded in the first 32 bits of the ICC profile */
  190443. pC = (png_bytep)(chunkdata+prefix_length);
  190444. profile_size = ((*(pC ))<<24) |
  190445. ((*(pC+1))<<16) |
  190446. ((*(pC+2))<< 8) |
  190447. ((*(pC+3)) );
  190448. if(profile_size < profile_length)
  190449. profile_length = profile_size;
  190450. if(profile_size > profile_length)
  190451. {
  190452. png_free(png_ptr, chunkdata);
  190453. png_warning(png_ptr, "Ignoring truncated iCCP profile.");
  190454. return;
  190455. }
  190456. png_set_iCCP(png_ptr, info_ptr, chunkdata, compression_type,
  190457. chunkdata + prefix_length, profile_length);
  190458. png_free(png_ptr, chunkdata);
  190459. }
  190460. #endif /* PNG_READ_iCCP_SUPPORTED */
  190461. #if defined(PNG_READ_sPLT_SUPPORTED)
  190462. void /* PRIVATE */
  190463. png_handle_sPLT(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  190464. /* Note: this does not properly handle chunks that are > 64K under DOS */
  190465. {
  190466. png_bytep chunkdata;
  190467. png_bytep entry_start;
  190468. png_sPLT_t new_palette;
  190469. #ifdef PNG_NO_POINTER_INDEXING
  190470. png_sPLT_entryp pp;
  190471. #endif
  190472. int data_length, entry_size, i;
  190473. png_uint_32 skip = 0;
  190474. png_size_t slength;
  190475. png_debug(1, "in png_handle_sPLT\n");
  190476. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  190477. png_error(png_ptr, "Missing IHDR before sPLT");
  190478. else if (png_ptr->mode & PNG_HAVE_IDAT)
  190479. {
  190480. png_warning(png_ptr, "Invalid sPLT after IDAT");
  190481. png_crc_finish(png_ptr, length);
  190482. return;
  190483. }
  190484. #ifdef PNG_MAX_MALLOC_64K
  190485. if (length > (png_uint_32)65535L)
  190486. {
  190487. png_warning(png_ptr, "sPLT chunk too large to fit in memory");
  190488. skip = length - (png_uint_32)65535L;
  190489. length = (png_uint_32)65535L;
  190490. }
  190491. #endif
  190492. chunkdata = (png_bytep)png_malloc(png_ptr, length + 1);
  190493. slength = (png_size_t)length;
  190494. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  190495. if (png_crc_finish(png_ptr, skip))
  190496. {
  190497. png_free(png_ptr, chunkdata);
  190498. return;
  190499. }
  190500. chunkdata[slength] = 0x00;
  190501. for (entry_start = chunkdata; *entry_start; entry_start++)
  190502. /* empty loop to find end of name */ ;
  190503. ++entry_start;
  190504. /* a sample depth should follow the separator, and we should be on it */
  190505. if (entry_start > chunkdata + slength - 2)
  190506. {
  190507. png_free(png_ptr, chunkdata);
  190508. png_warning(png_ptr, "malformed sPLT chunk");
  190509. return;
  190510. }
  190511. new_palette.depth = *entry_start++;
  190512. entry_size = (new_palette.depth == 8 ? 6 : 10);
  190513. data_length = (slength - (entry_start - chunkdata));
  190514. /* integrity-check the data length */
  190515. if (data_length % entry_size)
  190516. {
  190517. png_free(png_ptr, chunkdata);
  190518. png_warning(png_ptr, "sPLT chunk has bad length");
  190519. return;
  190520. }
  190521. new_palette.nentries = (png_int_32) ( data_length / entry_size);
  190522. if ((png_uint_32) new_palette.nentries > (png_uint_32) (PNG_SIZE_MAX /
  190523. png_sizeof(png_sPLT_entry)))
  190524. {
  190525. png_warning(png_ptr, "sPLT chunk too long");
  190526. return;
  190527. }
  190528. new_palette.entries = (png_sPLT_entryp)png_malloc_warn(
  190529. png_ptr, new_palette.nentries * png_sizeof(png_sPLT_entry));
  190530. if (new_palette.entries == NULL)
  190531. {
  190532. png_warning(png_ptr, "sPLT chunk requires too much memory");
  190533. return;
  190534. }
  190535. #ifndef PNG_NO_POINTER_INDEXING
  190536. for (i = 0; i < new_palette.nentries; i++)
  190537. {
  190538. png_sPLT_entryp pp = new_palette.entries + i;
  190539. if (new_palette.depth == 8)
  190540. {
  190541. pp->red = *entry_start++;
  190542. pp->green = *entry_start++;
  190543. pp->blue = *entry_start++;
  190544. pp->alpha = *entry_start++;
  190545. }
  190546. else
  190547. {
  190548. pp->red = png_get_uint_16(entry_start); entry_start += 2;
  190549. pp->green = png_get_uint_16(entry_start); entry_start += 2;
  190550. pp->blue = png_get_uint_16(entry_start); entry_start += 2;
  190551. pp->alpha = png_get_uint_16(entry_start); entry_start += 2;
  190552. }
  190553. pp->frequency = png_get_uint_16(entry_start); entry_start += 2;
  190554. }
  190555. #else
  190556. pp = new_palette.entries;
  190557. for (i = 0; i < new_palette.nentries; i++)
  190558. {
  190559. if (new_palette.depth == 8)
  190560. {
  190561. pp[i].red = *entry_start++;
  190562. pp[i].green = *entry_start++;
  190563. pp[i].blue = *entry_start++;
  190564. pp[i].alpha = *entry_start++;
  190565. }
  190566. else
  190567. {
  190568. pp[i].red = png_get_uint_16(entry_start); entry_start += 2;
  190569. pp[i].green = png_get_uint_16(entry_start); entry_start += 2;
  190570. pp[i].blue = png_get_uint_16(entry_start); entry_start += 2;
  190571. pp[i].alpha = png_get_uint_16(entry_start); entry_start += 2;
  190572. }
  190573. pp->frequency = png_get_uint_16(entry_start); entry_start += 2;
  190574. }
  190575. #endif
  190576. /* discard all chunk data except the name and stash that */
  190577. new_palette.name = (png_charp)chunkdata;
  190578. png_set_sPLT(png_ptr, info_ptr, &new_palette, 1);
  190579. png_free(png_ptr, chunkdata);
  190580. png_free(png_ptr, new_palette.entries);
  190581. }
  190582. #endif /* PNG_READ_sPLT_SUPPORTED */
  190583. #if defined(PNG_READ_tRNS_SUPPORTED)
  190584. void /* PRIVATE */
  190585. png_handle_tRNS(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  190586. {
  190587. png_byte readbuf[PNG_MAX_PALETTE_LENGTH];
  190588. int bit_mask;
  190589. png_debug(1, "in png_handle_tRNS\n");
  190590. /* For non-indexed color, mask off any bits in the tRNS value that
  190591. * exceed the bit depth. Some creators were writing extra bits there.
  190592. * This is not needed for indexed color. */
  190593. bit_mask = (1 << png_ptr->bit_depth) - 1;
  190594. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  190595. png_error(png_ptr, "Missing IHDR before tRNS");
  190596. else if (png_ptr->mode & PNG_HAVE_IDAT)
  190597. {
  190598. png_warning(png_ptr, "Invalid tRNS after IDAT");
  190599. png_crc_finish(png_ptr, length);
  190600. return;
  190601. }
  190602. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  190603. {
  190604. png_warning(png_ptr, "Duplicate tRNS chunk");
  190605. png_crc_finish(png_ptr, length);
  190606. return;
  190607. }
  190608. if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  190609. {
  190610. png_byte buf[2];
  190611. if (length != 2)
  190612. {
  190613. png_warning(png_ptr, "Incorrect tRNS chunk length");
  190614. png_crc_finish(png_ptr, length);
  190615. return;
  190616. }
  190617. png_crc_read(png_ptr, buf, 2);
  190618. png_ptr->num_trans = 1;
  190619. png_ptr->trans_values.gray = png_get_uint_16(buf) & bit_mask;
  190620. }
  190621. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  190622. {
  190623. png_byte buf[6];
  190624. if (length != 6)
  190625. {
  190626. png_warning(png_ptr, "Incorrect tRNS chunk length");
  190627. png_crc_finish(png_ptr, length);
  190628. return;
  190629. }
  190630. png_crc_read(png_ptr, buf, (png_size_t)length);
  190631. png_ptr->num_trans = 1;
  190632. png_ptr->trans_values.red = png_get_uint_16(buf) & bit_mask;
  190633. png_ptr->trans_values.green = png_get_uint_16(buf + 2) & bit_mask;
  190634. png_ptr->trans_values.blue = png_get_uint_16(buf + 4) & bit_mask;
  190635. }
  190636. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  190637. {
  190638. if (!(png_ptr->mode & PNG_HAVE_PLTE))
  190639. {
  190640. /* Should be an error, but we can cope with it. */
  190641. png_warning(png_ptr, "Missing PLTE before tRNS");
  190642. }
  190643. if (length > (png_uint_32)png_ptr->num_palette ||
  190644. length > PNG_MAX_PALETTE_LENGTH)
  190645. {
  190646. png_warning(png_ptr, "Incorrect tRNS chunk length");
  190647. png_crc_finish(png_ptr, length);
  190648. return;
  190649. }
  190650. if (length == 0)
  190651. {
  190652. png_warning(png_ptr, "Zero length tRNS chunk");
  190653. png_crc_finish(png_ptr, length);
  190654. return;
  190655. }
  190656. png_crc_read(png_ptr, readbuf, (png_size_t)length);
  190657. png_ptr->num_trans = (png_uint_16)length;
  190658. }
  190659. else
  190660. {
  190661. png_warning(png_ptr, "tRNS chunk not allowed with alpha channel");
  190662. png_crc_finish(png_ptr, length);
  190663. return;
  190664. }
  190665. if (png_crc_finish(png_ptr, 0))
  190666. {
  190667. png_ptr->num_trans = 0;
  190668. return;
  190669. }
  190670. png_set_tRNS(png_ptr, info_ptr, readbuf, png_ptr->num_trans,
  190671. &(png_ptr->trans_values));
  190672. }
  190673. #endif
  190674. #if defined(PNG_READ_bKGD_SUPPORTED)
  190675. void /* PRIVATE */
  190676. png_handle_bKGD(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  190677. {
  190678. png_size_t truelen;
  190679. png_byte buf[6];
  190680. png_debug(1, "in png_handle_bKGD\n");
  190681. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  190682. png_error(png_ptr, "Missing IHDR before bKGD");
  190683. else if (png_ptr->mode & PNG_HAVE_IDAT)
  190684. {
  190685. png_warning(png_ptr, "Invalid bKGD after IDAT");
  190686. png_crc_finish(png_ptr, length);
  190687. return;
  190688. }
  190689. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  190690. !(png_ptr->mode & PNG_HAVE_PLTE))
  190691. {
  190692. png_warning(png_ptr, "Missing PLTE before bKGD");
  190693. png_crc_finish(png_ptr, length);
  190694. return;
  190695. }
  190696. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_bKGD))
  190697. {
  190698. png_warning(png_ptr, "Duplicate bKGD chunk");
  190699. png_crc_finish(png_ptr, length);
  190700. return;
  190701. }
  190702. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  190703. truelen = 1;
  190704. else if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  190705. truelen = 6;
  190706. else
  190707. truelen = 2;
  190708. if (length != truelen)
  190709. {
  190710. png_warning(png_ptr, "Incorrect bKGD chunk length");
  190711. png_crc_finish(png_ptr, length);
  190712. return;
  190713. }
  190714. png_crc_read(png_ptr, buf, truelen);
  190715. if (png_crc_finish(png_ptr, 0))
  190716. return;
  190717. /* We convert the index value into RGB components so that we can allow
  190718. * arbitrary RGB values for background when we have transparency, and
  190719. * so it is easy to determine the RGB values of the background color
  190720. * from the info_ptr struct. */
  190721. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  190722. {
  190723. png_ptr->background.index = buf[0];
  190724. if(info_ptr->num_palette)
  190725. {
  190726. if(buf[0] > info_ptr->num_palette)
  190727. {
  190728. png_warning(png_ptr, "Incorrect bKGD chunk index value");
  190729. return;
  190730. }
  190731. png_ptr->background.red =
  190732. (png_uint_16)png_ptr->palette[buf[0]].red;
  190733. png_ptr->background.green =
  190734. (png_uint_16)png_ptr->palette[buf[0]].green;
  190735. png_ptr->background.blue =
  190736. (png_uint_16)png_ptr->palette[buf[0]].blue;
  190737. }
  190738. }
  190739. else if (!(png_ptr->color_type & PNG_COLOR_MASK_COLOR)) /* GRAY */
  190740. {
  190741. png_ptr->background.red =
  190742. png_ptr->background.green =
  190743. png_ptr->background.blue =
  190744. png_ptr->background.gray = png_get_uint_16(buf);
  190745. }
  190746. else
  190747. {
  190748. png_ptr->background.red = png_get_uint_16(buf);
  190749. png_ptr->background.green = png_get_uint_16(buf + 2);
  190750. png_ptr->background.blue = png_get_uint_16(buf + 4);
  190751. }
  190752. png_set_bKGD(png_ptr, info_ptr, &(png_ptr->background));
  190753. }
  190754. #endif
  190755. #if defined(PNG_READ_hIST_SUPPORTED)
  190756. void /* PRIVATE */
  190757. png_handle_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  190758. {
  190759. unsigned int num, i;
  190760. png_uint_16 readbuf[PNG_MAX_PALETTE_LENGTH];
  190761. png_debug(1, "in png_handle_hIST\n");
  190762. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  190763. png_error(png_ptr, "Missing IHDR before hIST");
  190764. else if (png_ptr->mode & PNG_HAVE_IDAT)
  190765. {
  190766. png_warning(png_ptr, "Invalid hIST after IDAT");
  190767. png_crc_finish(png_ptr, length);
  190768. return;
  190769. }
  190770. else if (!(png_ptr->mode & PNG_HAVE_PLTE))
  190771. {
  190772. png_warning(png_ptr, "Missing PLTE before hIST");
  190773. png_crc_finish(png_ptr, length);
  190774. return;
  190775. }
  190776. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_hIST))
  190777. {
  190778. png_warning(png_ptr, "Duplicate hIST chunk");
  190779. png_crc_finish(png_ptr, length);
  190780. return;
  190781. }
  190782. num = length / 2 ;
  190783. if (num != (unsigned int) png_ptr->num_palette || num >
  190784. (unsigned int) PNG_MAX_PALETTE_LENGTH)
  190785. {
  190786. png_warning(png_ptr, "Incorrect hIST chunk length");
  190787. png_crc_finish(png_ptr, length);
  190788. return;
  190789. }
  190790. for (i = 0; i < num; i++)
  190791. {
  190792. png_byte buf[2];
  190793. png_crc_read(png_ptr, buf, 2);
  190794. readbuf[i] = png_get_uint_16(buf);
  190795. }
  190796. if (png_crc_finish(png_ptr, 0))
  190797. return;
  190798. png_set_hIST(png_ptr, info_ptr, readbuf);
  190799. }
  190800. #endif
  190801. #if defined(PNG_READ_pHYs_SUPPORTED)
  190802. void /* PRIVATE */
  190803. png_handle_pHYs(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  190804. {
  190805. png_byte buf[9];
  190806. png_uint_32 res_x, res_y;
  190807. int unit_type;
  190808. png_debug(1, "in png_handle_pHYs\n");
  190809. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  190810. png_error(png_ptr, "Missing IHDR before pHYs");
  190811. else if (png_ptr->mode & PNG_HAVE_IDAT)
  190812. {
  190813. png_warning(png_ptr, "Invalid pHYs after IDAT");
  190814. png_crc_finish(png_ptr, length);
  190815. return;
  190816. }
  190817. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_pHYs))
  190818. {
  190819. png_warning(png_ptr, "Duplicate pHYs chunk");
  190820. png_crc_finish(png_ptr, length);
  190821. return;
  190822. }
  190823. if (length != 9)
  190824. {
  190825. png_warning(png_ptr, "Incorrect pHYs chunk length");
  190826. png_crc_finish(png_ptr, length);
  190827. return;
  190828. }
  190829. png_crc_read(png_ptr, buf, 9);
  190830. if (png_crc_finish(png_ptr, 0))
  190831. return;
  190832. res_x = png_get_uint_32(buf);
  190833. res_y = png_get_uint_32(buf + 4);
  190834. unit_type = buf[8];
  190835. png_set_pHYs(png_ptr, info_ptr, res_x, res_y, unit_type);
  190836. }
  190837. #endif
  190838. #if defined(PNG_READ_oFFs_SUPPORTED)
  190839. void /* PRIVATE */
  190840. png_handle_oFFs(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  190841. {
  190842. png_byte buf[9];
  190843. png_int_32 offset_x, offset_y;
  190844. int unit_type;
  190845. png_debug(1, "in png_handle_oFFs\n");
  190846. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  190847. png_error(png_ptr, "Missing IHDR before oFFs");
  190848. else if (png_ptr->mode & PNG_HAVE_IDAT)
  190849. {
  190850. png_warning(png_ptr, "Invalid oFFs after IDAT");
  190851. png_crc_finish(png_ptr, length);
  190852. return;
  190853. }
  190854. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_oFFs))
  190855. {
  190856. png_warning(png_ptr, "Duplicate oFFs chunk");
  190857. png_crc_finish(png_ptr, length);
  190858. return;
  190859. }
  190860. if (length != 9)
  190861. {
  190862. png_warning(png_ptr, "Incorrect oFFs chunk length");
  190863. png_crc_finish(png_ptr, length);
  190864. return;
  190865. }
  190866. png_crc_read(png_ptr, buf, 9);
  190867. if (png_crc_finish(png_ptr, 0))
  190868. return;
  190869. offset_x = png_get_int_32(buf);
  190870. offset_y = png_get_int_32(buf + 4);
  190871. unit_type = buf[8];
  190872. png_set_oFFs(png_ptr, info_ptr, offset_x, offset_y, unit_type);
  190873. }
  190874. #endif
  190875. #if defined(PNG_READ_pCAL_SUPPORTED)
  190876. /* read the pCAL chunk (described in the PNG Extensions document) */
  190877. void /* PRIVATE */
  190878. png_handle_pCAL(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  190879. {
  190880. png_charp purpose;
  190881. png_int_32 X0, X1;
  190882. png_byte type, nparams;
  190883. png_charp buf, units, endptr;
  190884. png_charpp params;
  190885. png_size_t slength;
  190886. int i;
  190887. png_debug(1, "in png_handle_pCAL\n");
  190888. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  190889. png_error(png_ptr, "Missing IHDR before pCAL");
  190890. else if (png_ptr->mode & PNG_HAVE_IDAT)
  190891. {
  190892. png_warning(png_ptr, "Invalid pCAL after IDAT");
  190893. png_crc_finish(png_ptr, length);
  190894. return;
  190895. }
  190896. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_pCAL))
  190897. {
  190898. png_warning(png_ptr, "Duplicate pCAL chunk");
  190899. png_crc_finish(png_ptr, length);
  190900. return;
  190901. }
  190902. png_debug1(2, "Allocating and reading pCAL chunk data (%lu bytes)\n",
  190903. length + 1);
  190904. purpose = (png_charp)png_malloc_warn(png_ptr, length + 1);
  190905. if (purpose == NULL)
  190906. {
  190907. png_warning(png_ptr, "No memory for pCAL purpose.");
  190908. return;
  190909. }
  190910. slength = (png_size_t)length;
  190911. png_crc_read(png_ptr, (png_bytep)purpose, slength);
  190912. if (png_crc_finish(png_ptr, 0))
  190913. {
  190914. png_free(png_ptr, purpose);
  190915. return;
  190916. }
  190917. purpose[slength] = 0x00; /* null terminate the last string */
  190918. png_debug(3, "Finding end of pCAL purpose string\n");
  190919. for (buf = purpose; *buf; buf++)
  190920. /* empty loop */ ;
  190921. endptr = purpose + slength;
  190922. /* We need to have at least 12 bytes after the purpose string
  190923. in order to get the parameter information. */
  190924. if (endptr <= buf + 12)
  190925. {
  190926. png_warning(png_ptr, "Invalid pCAL data");
  190927. png_free(png_ptr, purpose);
  190928. return;
  190929. }
  190930. png_debug(3, "Reading pCAL X0, X1, type, nparams, and units\n");
  190931. X0 = png_get_int_32((png_bytep)buf+1);
  190932. X1 = png_get_int_32((png_bytep)buf+5);
  190933. type = buf[9];
  190934. nparams = buf[10];
  190935. units = buf + 11;
  190936. png_debug(3, "Checking pCAL equation type and number of parameters\n");
  190937. /* Check that we have the right number of parameters for known
  190938. equation types. */
  190939. if ((type == PNG_EQUATION_LINEAR && nparams != 2) ||
  190940. (type == PNG_EQUATION_BASE_E && nparams != 3) ||
  190941. (type == PNG_EQUATION_ARBITRARY && nparams != 3) ||
  190942. (type == PNG_EQUATION_HYPERBOLIC && nparams != 4))
  190943. {
  190944. png_warning(png_ptr, "Invalid pCAL parameters for equation type");
  190945. png_free(png_ptr, purpose);
  190946. return;
  190947. }
  190948. else if (type >= PNG_EQUATION_LAST)
  190949. {
  190950. png_warning(png_ptr, "Unrecognized equation type for pCAL chunk");
  190951. }
  190952. for (buf = units; *buf; buf++)
  190953. /* Empty loop to move past the units string. */ ;
  190954. png_debug(3, "Allocating pCAL parameters array\n");
  190955. params = (png_charpp)png_malloc_warn(png_ptr, (png_uint_32)(nparams
  190956. *png_sizeof(png_charp))) ;
  190957. if (params == NULL)
  190958. {
  190959. png_free(png_ptr, purpose);
  190960. png_warning(png_ptr, "No memory for pCAL params.");
  190961. return;
  190962. }
  190963. /* Get pointers to the start of each parameter string. */
  190964. for (i = 0; i < (int)nparams; i++)
  190965. {
  190966. buf++; /* Skip the null string terminator from previous parameter. */
  190967. png_debug1(3, "Reading pCAL parameter %d\n", i);
  190968. for (params[i] = buf; buf <= endptr && *buf != 0x00; buf++)
  190969. /* Empty loop to move past each parameter string */ ;
  190970. /* Make sure we haven't run out of data yet */
  190971. if (buf > endptr)
  190972. {
  190973. png_warning(png_ptr, "Invalid pCAL data");
  190974. png_free(png_ptr, purpose);
  190975. png_free(png_ptr, params);
  190976. return;
  190977. }
  190978. }
  190979. png_set_pCAL(png_ptr, info_ptr, purpose, X0, X1, type, nparams,
  190980. units, params);
  190981. png_free(png_ptr, purpose);
  190982. png_free(png_ptr, params);
  190983. }
  190984. #endif
  190985. #if defined(PNG_READ_sCAL_SUPPORTED)
  190986. /* read the sCAL chunk */
  190987. void /* PRIVATE */
  190988. png_handle_sCAL(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  190989. {
  190990. png_charp buffer, ep;
  190991. #ifdef PNG_FLOATING_POINT_SUPPORTED
  190992. double width, height;
  190993. png_charp vp;
  190994. #else
  190995. #ifdef PNG_FIXED_POINT_SUPPORTED
  190996. png_charp swidth, sheight;
  190997. #endif
  190998. #endif
  190999. png_size_t slength;
  191000. png_debug(1, "in png_handle_sCAL\n");
  191001. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  191002. png_error(png_ptr, "Missing IHDR before sCAL");
  191003. else if (png_ptr->mode & PNG_HAVE_IDAT)
  191004. {
  191005. png_warning(png_ptr, "Invalid sCAL after IDAT");
  191006. png_crc_finish(png_ptr, length);
  191007. return;
  191008. }
  191009. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sCAL))
  191010. {
  191011. png_warning(png_ptr, "Duplicate sCAL chunk");
  191012. png_crc_finish(png_ptr, length);
  191013. return;
  191014. }
  191015. png_debug1(2, "Allocating and reading sCAL chunk data (%lu bytes)\n",
  191016. length + 1);
  191017. buffer = (png_charp)png_malloc_warn(png_ptr, length + 1);
  191018. if (buffer == NULL)
  191019. {
  191020. png_warning(png_ptr, "Out of memory while processing sCAL chunk");
  191021. return;
  191022. }
  191023. slength = (png_size_t)length;
  191024. png_crc_read(png_ptr, (png_bytep)buffer, slength);
  191025. if (png_crc_finish(png_ptr, 0))
  191026. {
  191027. png_free(png_ptr, buffer);
  191028. return;
  191029. }
  191030. buffer[slength] = 0x00; /* null terminate the last string */
  191031. ep = buffer + 1; /* skip unit byte */
  191032. #ifdef PNG_FLOATING_POINT_SUPPORTED
  191033. width = png_strtod(png_ptr, ep, &vp);
  191034. if (*vp)
  191035. {
  191036. png_warning(png_ptr, "malformed width string in sCAL chunk");
  191037. return;
  191038. }
  191039. #else
  191040. #ifdef PNG_FIXED_POINT_SUPPORTED
  191041. swidth = (png_charp)png_malloc_warn(png_ptr, png_strlen(ep) + 1);
  191042. if (swidth == NULL)
  191043. {
  191044. png_warning(png_ptr, "Out of memory while processing sCAL chunk width");
  191045. return;
  191046. }
  191047. png_memcpy(swidth, ep, (png_size_t)png_strlen(ep));
  191048. #endif
  191049. #endif
  191050. for (ep = buffer; *ep; ep++)
  191051. /* empty loop */ ;
  191052. ep++;
  191053. if (buffer + slength < ep)
  191054. {
  191055. png_warning(png_ptr, "Truncated sCAL chunk");
  191056. #if defined(PNG_FIXED_POINT_SUPPORTED) && \
  191057. !defined(PNG_FLOATING_POINT_SUPPORTED)
  191058. png_free(png_ptr, swidth);
  191059. #endif
  191060. png_free(png_ptr, buffer);
  191061. return;
  191062. }
  191063. #ifdef PNG_FLOATING_POINT_SUPPORTED
  191064. height = png_strtod(png_ptr, ep, &vp);
  191065. if (*vp)
  191066. {
  191067. png_warning(png_ptr, "malformed height string in sCAL chunk");
  191068. return;
  191069. }
  191070. #else
  191071. #ifdef PNG_FIXED_POINT_SUPPORTED
  191072. sheight = (png_charp)png_malloc_warn(png_ptr, png_strlen(ep) + 1);
  191073. if (swidth == NULL)
  191074. {
  191075. png_warning(png_ptr, "Out of memory while processing sCAL chunk height");
  191076. return;
  191077. }
  191078. png_memcpy(sheight, ep, (png_size_t)png_strlen(ep));
  191079. #endif
  191080. #endif
  191081. if (buffer + slength < ep
  191082. #ifdef PNG_FLOATING_POINT_SUPPORTED
  191083. || width <= 0. || height <= 0.
  191084. #endif
  191085. )
  191086. {
  191087. png_warning(png_ptr, "Invalid sCAL data");
  191088. png_free(png_ptr, buffer);
  191089. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  191090. png_free(png_ptr, swidth);
  191091. png_free(png_ptr, sheight);
  191092. #endif
  191093. return;
  191094. }
  191095. #ifdef PNG_FLOATING_POINT_SUPPORTED
  191096. png_set_sCAL(png_ptr, info_ptr, buffer[0], width, height);
  191097. #else
  191098. #ifdef PNG_FIXED_POINT_SUPPORTED
  191099. png_set_sCAL_s(png_ptr, info_ptr, buffer[0], swidth, sheight);
  191100. #endif
  191101. #endif
  191102. png_free(png_ptr, buffer);
  191103. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  191104. png_free(png_ptr, swidth);
  191105. png_free(png_ptr, sheight);
  191106. #endif
  191107. }
  191108. #endif
  191109. #if defined(PNG_READ_tIME_SUPPORTED)
  191110. void /* PRIVATE */
  191111. png_handle_tIME(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  191112. {
  191113. png_byte buf[7];
  191114. png_time mod_time;
  191115. png_debug(1, "in png_handle_tIME\n");
  191116. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  191117. png_error(png_ptr, "Out of place tIME chunk");
  191118. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tIME))
  191119. {
  191120. png_warning(png_ptr, "Duplicate tIME chunk");
  191121. png_crc_finish(png_ptr, length);
  191122. return;
  191123. }
  191124. if (png_ptr->mode & PNG_HAVE_IDAT)
  191125. png_ptr->mode |= PNG_AFTER_IDAT;
  191126. if (length != 7)
  191127. {
  191128. png_warning(png_ptr, "Incorrect tIME chunk length");
  191129. png_crc_finish(png_ptr, length);
  191130. return;
  191131. }
  191132. png_crc_read(png_ptr, buf, 7);
  191133. if (png_crc_finish(png_ptr, 0))
  191134. return;
  191135. mod_time.second = buf[6];
  191136. mod_time.minute = buf[5];
  191137. mod_time.hour = buf[4];
  191138. mod_time.day = buf[3];
  191139. mod_time.month = buf[2];
  191140. mod_time.year = png_get_uint_16(buf);
  191141. png_set_tIME(png_ptr, info_ptr, &mod_time);
  191142. }
  191143. #endif
  191144. #if defined(PNG_READ_tEXt_SUPPORTED)
  191145. /* Note: this does not properly handle chunks that are > 64K under DOS */
  191146. void /* PRIVATE */
  191147. png_handle_tEXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  191148. {
  191149. png_textp text_ptr;
  191150. png_charp key;
  191151. png_charp text;
  191152. png_uint_32 skip = 0;
  191153. png_size_t slength;
  191154. int ret;
  191155. png_debug(1, "in png_handle_tEXt\n");
  191156. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  191157. png_error(png_ptr, "Missing IHDR before tEXt");
  191158. if (png_ptr->mode & PNG_HAVE_IDAT)
  191159. png_ptr->mode |= PNG_AFTER_IDAT;
  191160. #ifdef PNG_MAX_MALLOC_64K
  191161. if (length > (png_uint_32)65535L)
  191162. {
  191163. png_warning(png_ptr, "tEXt chunk too large to fit in memory");
  191164. skip = length - (png_uint_32)65535L;
  191165. length = (png_uint_32)65535L;
  191166. }
  191167. #endif
  191168. key = (png_charp)png_malloc_warn(png_ptr, length + 1);
  191169. if (key == NULL)
  191170. {
  191171. png_warning(png_ptr, "No memory to process text chunk.");
  191172. return;
  191173. }
  191174. slength = (png_size_t)length;
  191175. png_crc_read(png_ptr, (png_bytep)key, slength);
  191176. if (png_crc_finish(png_ptr, skip))
  191177. {
  191178. png_free(png_ptr, key);
  191179. return;
  191180. }
  191181. key[slength] = 0x00;
  191182. for (text = key; *text; text++)
  191183. /* empty loop to find end of key */ ;
  191184. if (text != key + slength)
  191185. text++;
  191186. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  191187. (png_uint_32)png_sizeof(png_text));
  191188. if (text_ptr == NULL)
  191189. {
  191190. png_warning(png_ptr, "Not enough memory to process text chunk.");
  191191. png_free(png_ptr, key);
  191192. return;
  191193. }
  191194. text_ptr->compression = PNG_TEXT_COMPRESSION_NONE;
  191195. text_ptr->key = key;
  191196. #ifdef PNG_iTXt_SUPPORTED
  191197. text_ptr->lang = NULL;
  191198. text_ptr->lang_key = NULL;
  191199. text_ptr->itxt_length = 0;
  191200. #endif
  191201. text_ptr->text = text;
  191202. text_ptr->text_length = png_strlen(text);
  191203. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  191204. png_free(png_ptr, key);
  191205. png_free(png_ptr, text_ptr);
  191206. if (ret)
  191207. png_warning(png_ptr, "Insufficient memory to process text chunk.");
  191208. }
  191209. #endif
  191210. #if defined(PNG_READ_zTXt_SUPPORTED)
  191211. /* note: this does not correctly handle chunks that are > 64K under DOS */
  191212. void /* PRIVATE */
  191213. png_handle_zTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  191214. {
  191215. png_textp text_ptr;
  191216. png_charp chunkdata;
  191217. png_charp text;
  191218. int comp_type;
  191219. int ret;
  191220. png_size_t slength, prefix_len, data_len;
  191221. png_debug(1, "in png_handle_zTXt\n");
  191222. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  191223. png_error(png_ptr, "Missing IHDR before zTXt");
  191224. if (png_ptr->mode & PNG_HAVE_IDAT)
  191225. png_ptr->mode |= PNG_AFTER_IDAT;
  191226. #ifdef PNG_MAX_MALLOC_64K
  191227. /* We will no doubt have problems with chunks even half this size, but
  191228. there is no hard and fast rule to tell us where to stop. */
  191229. if (length > (png_uint_32)65535L)
  191230. {
  191231. png_warning(png_ptr,"zTXt chunk too large to fit in memory");
  191232. png_crc_finish(png_ptr, length);
  191233. return;
  191234. }
  191235. #endif
  191236. chunkdata = (png_charp)png_malloc_warn(png_ptr, length + 1);
  191237. if (chunkdata == NULL)
  191238. {
  191239. png_warning(png_ptr,"Out of memory processing zTXt chunk.");
  191240. return;
  191241. }
  191242. slength = (png_size_t)length;
  191243. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  191244. if (png_crc_finish(png_ptr, 0))
  191245. {
  191246. png_free(png_ptr, chunkdata);
  191247. return;
  191248. }
  191249. chunkdata[slength] = 0x00;
  191250. for (text = chunkdata; *text; text++)
  191251. /* empty loop */ ;
  191252. /* zTXt must have some text after the chunkdataword */
  191253. if (text >= chunkdata + slength - 2)
  191254. {
  191255. png_warning(png_ptr, "Truncated zTXt chunk");
  191256. png_free(png_ptr, chunkdata);
  191257. return;
  191258. }
  191259. else
  191260. {
  191261. comp_type = *(++text);
  191262. if (comp_type != PNG_TEXT_COMPRESSION_zTXt)
  191263. {
  191264. png_warning(png_ptr, "Unknown compression type in zTXt chunk");
  191265. comp_type = PNG_TEXT_COMPRESSION_zTXt;
  191266. }
  191267. text++; /* skip the compression_method byte */
  191268. }
  191269. prefix_len = text - chunkdata;
  191270. chunkdata = (png_charp)png_decompress_chunk(png_ptr, comp_type, chunkdata,
  191271. (png_size_t)length, prefix_len, &data_len);
  191272. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  191273. (png_uint_32)png_sizeof(png_text));
  191274. if (text_ptr == NULL)
  191275. {
  191276. png_warning(png_ptr,"Not enough memory to process zTXt chunk.");
  191277. png_free(png_ptr, chunkdata);
  191278. return;
  191279. }
  191280. text_ptr->compression = comp_type;
  191281. text_ptr->key = chunkdata;
  191282. #ifdef PNG_iTXt_SUPPORTED
  191283. text_ptr->lang = NULL;
  191284. text_ptr->lang_key = NULL;
  191285. text_ptr->itxt_length = 0;
  191286. #endif
  191287. text_ptr->text = chunkdata + prefix_len;
  191288. text_ptr->text_length = data_len;
  191289. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  191290. png_free(png_ptr, text_ptr);
  191291. png_free(png_ptr, chunkdata);
  191292. if (ret)
  191293. png_error(png_ptr, "Insufficient memory to store zTXt chunk.");
  191294. }
  191295. #endif
  191296. #if defined(PNG_READ_iTXt_SUPPORTED)
  191297. /* note: this does not correctly handle chunks that are > 64K under DOS */
  191298. void /* PRIVATE */
  191299. png_handle_iTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  191300. {
  191301. png_textp text_ptr;
  191302. png_charp chunkdata;
  191303. png_charp key, lang, text, lang_key;
  191304. int comp_flag;
  191305. int comp_type = 0;
  191306. int ret;
  191307. png_size_t slength, prefix_len, data_len;
  191308. png_debug(1, "in png_handle_iTXt\n");
  191309. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  191310. png_error(png_ptr, "Missing IHDR before iTXt");
  191311. if (png_ptr->mode & PNG_HAVE_IDAT)
  191312. png_ptr->mode |= PNG_AFTER_IDAT;
  191313. #ifdef PNG_MAX_MALLOC_64K
  191314. /* We will no doubt have problems with chunks even half this size, but
  191315. there is no hard and fast rule to tell us where to stop. */
  191316. if (length > (png_uint_32)65535L)
  191317. {
  191318. png_warning(png_ptr,"iTXt chunk too large to fit in memory");
  191319. png_crc_finish(png_ptr, length);
  191320. return;
  191321. }
  191322. #endif
  191323. chunkdata = (png_charp)png_malloc_warn(png_ptr, length + 1);
  191324. if (chunkdata == NULL)
  191325. {
  191326. png_warning(png_ptr, "No memory to process iTXt chunk.");
  191327. return;
  191328. }
  191329. slength = (png_size_t)length;
  191330. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  191331. if (png_crc_finish(png_ptr, 0))
  191332. {
  191333. png_free(png_ptr, chunkdata);
  191334. return;
  191335. }
  191336. chunkdata[slength] = 0x00;
  191337. for (lang = chunkdata; *lang; lang++)
  191338. /* empty loop */ ;
  191339. lang++; /* skip NUL separator */
  191340. /* iTXt must have a language tag (possibly empty), two compression bytes,
  191341. translated keyword (possibly empty), and possibly some text after the
  191342. keyword */
  191343. if (lang >= chunkdata + slength - 3)
  191344. {
  191345. png_warning(png_ptr, "Truncated iTXt chunk");
  191346. png_free(png_ptr, chunkdata);
  191347. return;
  191348. }
  191349. else
  191350. {
  191351. comp_flag = *lang++;
  191352. comp_type = *lang++;
  191353. }
  191354. for (lang_key = lang; *lang_key; lang_key++)
  191355. /* empty loop */ ;
  191356. lang_key++; /* skip NUL separator */
  191357. if (lang_key >= chunkdata + slength)
  191358. {
  191359. png_warning(png_ptr, "Truncated iTXt chunk");
  191360. png_free(png_ptr, chunkdata);
  191361. return;
  191362. }
  191363. for (text = lang_key; *text; text++)
  191364. /* empty loop */ ;
  191365. text++; /* skip NUL separator */
  191366. if (text >= chunkdata + slength)
  191367. {
  191368. png_warning(png_ptr, "Malformed iTXt chunk");
  191369. png_free(png_ptr, chunkdata);
  191370. return;
  191371. }
  191372. prefix_len = text - chunkdata;
  191373. key=chunkdata;
  191374. if (comp_flag)
  191375. chunkdata = png_decompress_chunk(png_ptr, comp_type, chunkdata,
  191376. (size_t)length, prefix_len, &data_len);
  191377. else
  191378. data_len=png_strlen(chunkdata + prefix_len);
  191379. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  191380. (png_uint_32)png_sizeof(png_text));
  191381. if (text_ptr == NULL)
  191382. {
  191383. png_warning(png_ptr,"Not enough memory to process iTXt chunk.");
  191384. png_free(png_ptr, chunkdata);
  191385. return;
  191386. }
  191387. text_ptr->compression = (int)comp_flag + 1;
  191388. text_ptr->lang_key = chunkdata+(lang_key-key);
  191389. text_ptr->lang = chunkdata+(lang-key);
  191390. text_ptr->itxt_length = data_len;
  191391. text_ptr->text_length = 0;
  191392. text_ptr->key = chunkdata;
  191393. text_ptr->text = chunkdata + prefix_len;
  191394. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  191395. png_free(png_ptr, text_ptr);
  191396. png_free(png_ptr, chunkdata);
  191397. if (ret)
  191398. png_error(png_ptr, "Insufficient memory to store iTXt chunk.");
  191399. }
  191400. #endif
  191401. /* This function is called when we haven't found a handler for a
  191402. chunk. If there isn't a problem with the chunk itself (ie bad
  191403. chunk name, CRC, or a critical chunk), the chunk is silently ignored
  191404. -- unless the PNG_FLAG_UNKNOWN_CHUNKS_SUPPORTED flag is on in which
  191405. case it will be saved away to be written out later. */
  191406. void /* PRIVATE */
  191407. png_handle_unknown(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  191408. {
  191409. png_uint_32 skip = 0;
  191410. png_debug(1, "in png_handle_unknown\n");
  191411. if (png_ptr->mode & PNG_HAVE_IDAT)
  191412. {
  191413. #ifdef PNG_USE_LOCAL_ARRAYS
  191414. PNG_CONST PNG_IDAT;
  191415. #endif
  191416. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4)) /* not an IDAT */
  191417. png_ptr->mode |= PNG_AFTER_IDAT;
  191418. }
  191419. png_check_chunk_name(png_ptr, png_ptr->chunk_name);
  191420. if (!(png_ptr->chunk_name[0] & 0x20))
  191421. {
  191422. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  191423. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  191424. PNG_HANDLE_CHUNK_ALWAYS
  191425. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  191426. && png_ptr->read_user_chunk_fn == NULL
  191427. #endif
  191428. )
  191429. #endif
  191430. png_chunk_error(png_ptr, "unknown critical chunk");
  191431. }
  191432. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  191433. if ((png_ptr->flags & PNG_FLAG_KEEP_UNKNOWN_CHUNKS) ||
  191434. (png_ptr->read_user_chunk_fn != NULL))
  191435. {
  191436. #ifdef PNG_MAX_MALLOC_64K
  191437. if (length > (png_uint_32)65535L)
  191438. {
  191439. png_warning(png_ptr, "unknown chunk too large to fit in memory");
  191440. skip = length - (png_uint_32)65535L;
  191441. length = (png_uint_32)65535L;
  191442. }
  191443. #endif
  191444. png_strncpy((png_charp)png_ptr->unknown_chunk.name,
  191445. (png_charp)png_ptr->chunk_name, 5);
  191446. png_ptr->unknown_chunk.data = (png_bytep)png_malloc(png_ptr, length);
  191447. png_ptr->unknown_chunk.size = (png_size_t)length;
  191448. png_crc_read(png_ptr, (png_bytep)png_ptr->unknown_chunk.data, length);
  191449. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  191450. if(png_ptr->read_user_chunk_fn != NULL)
  191451. {
  191452. /* callback to user unknown chunk handler */
  191453. int ret;
  191454. ret = (*(png_ptr->read_user_chunk_fn))
  191455. (png_ptr, &png_ptr->unknown_chunk);
  191456. if (ret < 0)
  191457. png_chunk_error(png_ptr, "error in user chunk");
  191458. if (ret == 0)
  191459. {
  191460. if (!(png_ptr->chunk_name[0] & 0x20))
  191461. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  191462. PNG_HANDLE_CHUNK_ALWAYS)
  191463. png_chunk_error(png_ptr, "unknown critical chunk");
  191464. png_set_unknown_chunks(png_ptr, info_ptr,
  191465. &png_ptr->unknown_chunk, 1);
  191466. }
  191467. }
  191468. #else
  191469. png_set_unknown_chunks(png_ptr, info_ptr, &png_ptr->unknown_chunk, 1);
  191470. #endif
  191471. png_free(png_ptr, png_ptr->unknown_chunk.data);
  191472. png_ptr->unknown_chunk.data = NULL;
  191473. }
  191474. else
  191475. #endif
  191476. skip = length;
  191477. png_crc_finish(png_ptr, skip);
  191478. #if !defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  191479. info_ptr = info_ptr; /* quiet compiler warnings about unused info_ptr */
  191480. #endif
  191481. }
  191482. /* This function is called to verify that a chunk name is valid.
  191483. This function can't have the "critical chunk check" incorporated
  191484. into it, since in the future we will need to be able to call user
  191485. functions to handle unknown critical chunks after we check that
  191486. the chunk name itself is valid. */
  191487. #define isnonalpha(c) ((c) < 65 || (c) > 122 || ((c) > 90 && (c) < 97))
  191488. void /* PRIVATE */
  191489. png_check_chunk_name(png_structp png_ptr, png_bytep chunk_name)
  191490. {
  191491. png_debug(1, "in png_check_chunk_name\n");
  191492. if (isnonalpha(chunk_name[0]) || isnonalpha(chunk_name[1]) ||
  191493. isnonalpha(chunk_name[2]) || isnonalpha(chunk_name[3]))
  191494. {
  191495. png_chunk_error(png_ptr, "invalid chunk type");
  191496. }
  191497. }
  191498. /* Combines the row recently read in with the existing pixels in the
  191499. row. This routine takes care of alpha and transparency if requested.
  191500. This routine also handles the two methods of progressive display
  191501. of interlaced images, depending on the mask value.
  191502. The mask value describes which pixels are to be combined with
  191503. the row. The pattern always repeats every 8 pixels, so just 8
  191504. bits are needed. A one indicates the pixel is to be combined,
  191505. a zero indicates the pixel is to be skipped. This is in addition
  191506. to any alpha or transparency value associated with the pixel. If
  191507. you want all pixels to be combined, pass 0xff (255) in mask. */
  191508. void /* PRIVATE */
  191509. png_combine_row(png_structp png_ptr, png_bytep row, int mask)
  191510. {
  191511. png_debug(1,"in png_combine_row\n");
  191512. if (mask == 0xff)
  191513. {
  191514. png_memcpy(row, png_ptr->row_buf + 1,
  191515. PNG_ROWBYTES(png_ptr->row_info.pixel_depth, png_ptr->width));
  191516. }
  191517. else
  191518. {
  191519. switch (png_ptr->row_info.pixel_depth)
  191520. {
  191521. case 1:
  191522. {
  191523. png_bytep sp = png_ptr->row_buf + 1;
  191524. png_bytep dp = row;
  191525. int s_inc, s_start, s_end;
  191526. int m = 0x80;
  191527. int shift;
  191528. png_uint_32 i;
  191529. png_uint_32 row_width = png_ptr->width;
  191530. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  191531. if (png_ptr->transformations & PNG_PACKSWAP)
  191532. {
  191533. s_start = 0;
  191534. s_end = 7;
  191535. s_inc = 1;
  191536. }
  191537. else
  191538. #endif
  191539. {
  191540. s_start = 7;
  191541. s_end = 0;
  191542. s_inc = -1;
  191543. }
  191544. shift = s_start;
  191545. for (i = 0; i < row_width; i++)
  191546. {
  191547. if (m & mask)
  191548. {
  191549. int value;
  191550. value = (*sp >> shift) & 0x01;
  191551. *dp &= (png_byte)((0x7f7f >> (7 - shift)) & 0xff);
  191552. *dp |= (png_byte)(value << shift);
  191553. }
  191554. if (shift == s_end)
  191555. {
  191556. shift = s_start;
  191557. sp++;
  191558. dp++;
  191559. }
  191560. else
  191561. shift += s_inc;
  191562. if (m == 1)
  191563. m = 0x80;
  191564. else
  191565. m >>= 1;
  191566. }
  191567. break;
  191568. }
  191569. case 2:
  191570. {
  191571. png_bytep sp = png_ptr->row_buf + 1;
  191572. png_bytep dp = row;
  191573. int s_start, s_end, s_inc;
  191574. int m = 0x80;
  191575. int shift;
  191576. png_uint_32 i;
  191577. png_uint_32 row_width = png_ptr->width;
  191578. int value;
  191579. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  191580. if (png_ptr->transformations & PNG_PACKSWAP)
  191581. {
  191582. s_start = 0;
  191583. s_end = 6;
  191584. s_inc = 2;
  191585. }
  191586. else
  191587. #endif
  191588. {
  191589. s_start = 6;
  191590. s_end = 0;
  191591. s_inc = -2;
  191592. }
  191593. shift = s_start;
  191594. for (i = 0; i < row_width; i++)
  191595. {
  191596. if (m & mask)
  191597. {
  191598. value = (*sp >> shift) & 0x03;
  191599. *dp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  191600. *dp |= (png_byte)(value << shift);
  191601. }
  191602. if (shift == s_end)
  191603. {
  191604. shift = s_start;
  191605. sp++;
  191606. dp++;
  191607. }
  191608. else
  191609. shift += s_inc;
  191610. if (m == 1)
  191611. m = 0x80;
  191612. else
  191613. m >>= 1;
  191614. }
  191615. break;
  191616. }
  191617. case 4:
  191618. {
  191619. png_bytep sp = png_ptr->row_buf + 1;
  191620. png_bytep dp = row;
  191621. int s_start, s_end, s_inc;
  191622. int m = 0x80;
  191623. int shift;
  191624. png_uint_32 i;
  191625. png_uint_32 row_width = png_ptr->width;
  191626. int value;
  191627. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  191628. if (png_ptr->transformations & PNG_PACKSWAP)
  191629. {
  191630. s_start = 0;
  191631. s_end = 4;
  191632. s_inc = 4;
  191633. }
  191634. else
  191635. #endif
  191636. {
  191637. s_start = 4;
  191638. s_end = 0;
  191639. s_inc = -4;
  191640. }
  191641. shift = s_start;
  191642. for (i = 0; i < row_width; i++)
  191643. {
  191644. if (m & mask)
  191645. {
  191646. value = (*sp >> shift) & 0xf;
  191647. *dp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  191648. *dp |= (png_byte)(value << shift);
  191649. }
  191650. if (shift == s_end)
  191651. {
  191652. shift = s_start;
  191653. sp++;
  191654. dp++;
  191655. }
  191656. else
  191657. shift += s_inc;
  191658. if (m == 1)
  191659. m = 0x80;
  191660. else
  191661. m >>= 1;
  191662. }
  191663. break;
  191664. }
  191665. default:
  191666. {
  191667. png_bytep sp = png_ptr->row_buf + 1;
  191668. png_bytep dp = row;
  191669. png_size_t pixel_bytes = (png_ptr->row_info.pixel_depth >> 3);
  191670. png_uint_32 i;
  191671. png_uint_32 row_width = png_ptr->width;
  191672. png_byte m = 0x80;
  191673. for (i = 0; i < row_width; i++)
  191674. {
  191675. if (m & mask)
  191676. {
  191677. png_memcpy(dp, sp, pixel_bytes);
  191678. }
  191679. sp += pixel_bytes;
  191680. dp += pixel_bytes;
  191681. if (m == 1)
  191682. m = 0x80;
  191683. else
  191684. m >>= 1;
  191685. }
  191686. break;
  191687. }
  191688. }
  191689. }
  191690. }
  191691. #ifdef PNG_READ_INTERLACING_SUPPORTED
  191692. /* OLD pre-1.0.9 interface:
  191693. void png_do_read_interlace(png_row_infop row_info, png_bytep row, int pass,
  191694. png_uint_32 transformations)
  191695. */
  191696. void /* PRIVATE */
  191697. png_do_read_interlace(png_structp png_ptr)
  191698. {
  191699. png_row_infop row_info = &(png_ptr->row_info);
  191700. png_bytep row = png_ptr->row_buf + 1;
  191701. int pass = png_ptr->pass;
  191702. png_uint_32 transformations = png_ptr->transformations;
  191703. #ifdef PNG_USE_LOCAL_ARRAYS
  191704. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  191705. /* offset to next interlace block */
  191706. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  191707. #endif
  191708. png_debug(1,"in png_do_read_interlace\n");
  191709. if (row != NULL && row_info != NULL)
  191710. {
  191711. png_uint_32 final_width;
  191712. final_width = row_info->width * png_pass_inc[pass];
  191713. switch (row_info->pixel_depth)
  191714. {
  191715. case 1:
  191716. {
  191717. png_bytep sp = row + (png_size_t)((row_info->width - 1) >> 3);
  191718. png_bytep dp = row + (png_size_t)((final_width - 1) >> 3);
  191719. int sshift, dshift;
  191720. int s_start, s_end, s_inc;
  191721. int jstop = png_pass_inc[pass];
  191722. png_byte v;
  191723. png_uint_32 i;
  191724. int j;
  191725. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  191726. if (transformations & PNG_PACKSWAP)
  191727. {
  191728. sshift = (int)((row_info->width + 7) & 0x07);
  191729. dshift = (int)((final_width + 7) & 0x07);
  191730. s_start = 7;
  191731. s_end = 0;
  191732. s_inc = -1;
  191733. }
  191734. else
  191735. #endif
  191736. {
  191737. sshift = 7 - (int)((row_info->width + 7) & 0x07);
  191738. dshift = 7 - (int)((final_width + 7) & 0x07);
  191739. s_start = 0;
  191740. s_end = 7;
  191741. s_inc = 1;
  191742. }
  191743. for (i = 0; i < row_info->width; i++)
  191744. {
  191745. v = (png_byte)((*sp >> sshift) & 0x01);
  191746. for (j = 0; j < jstop; j++)
  191747. {
  191748. *dp &= (png_byte)((0x7f7f >> (7 - dshift)) & 0xff);
  191749. *dp |= (png_byte)(v << dshift);
  191750. if (dshift == s_end)
  191751. {
  191752. dshift = s_start;
  191753. dp--;
  191754. }
  191755. else
  191756. dshift += s_inc;
  191757. }
  191758. if (sshift == s_end)
  191759. {
  191760. sshift = s_start;
  191761. sp--;
  191762. }
  191763. else
  191764. sshift += s_inc;
  191765. }
  191766. break;
  191767. }
  191768. case 2:
  191769. {
  191770. png_bytep sp = row + (png_uint_32)((row_info->width - 1) >> 2);
  191771. png_bytep dp = row + (png_uint_32)((final_width - 1) >> 2);
  191772. int sshift, dshift;
  191773. int s_start, s_end, s_inc;
  191774. int jstop = png_pass_inc[pass];
  191775. png_uint_32 i;
  191776. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  191777. if (transformations & PNG_PACKSWAP)
  191778. {
  191779. sshift = (int)(((row_info->width + 3) & 0x03) << 1);
  191780. dshift = (int)(((final_width + 3) & 0x03) << 1);
  191781. s_start = 6;
  191782. s_end = 0;
  191783. s_inc = -2;
  191784. }
  191785. else
  191786. #endif
  191787. {
  191788. sshift = (int)((3 - ((row_info->width + 3) & 0x03)) << 1);
  191789. dshift = (int)((3 - ((final_width + 3) & 0x03)) << 1);
  191790. s_start = 0;
  191791. s_end = 6;
  191792. s_inc = 2;
  191793. }
  191794. for (i = 0; i < row_info->width; i++)
  191795. {
  191796. png_byte v;
  191797. int j;
  191798. v = (png_byte)((*sp >> sshift) & 0x03);
  191799. for (j = 0; j < jstop; j++)
  191800. {
  191801. *dp &= (png_byte)((0x3f3f >> (6 - dshift)) & 0xff);
  191802. *dp |= (png_byte)(v << dshift);
  191803. if (dshift == s_end)
  191804. {
  191805. dshift = s_start;
  191806. dp--;
  191807. }
  191808. else
  191809. dshift += s_inc;
  191810. }
  191811. if (sshift == s_end)
  191812. {
  191813. sshift = s_start;
  191814. sp--;
  191815. }
  191816. else
  191817. sshift += s_inc;
  191818. }
  191819. break;
  191820. }
  191821. case 4:
  191822. {
  191823. png_bytep sp = row + (png_size_t)((row_info->width - 1) >> 1);
  191824. png_bytep dp = row + (png_size_t)((final_width - 1) >> 1);
  191825. int sshift, dshift;
  191826. int s_start, s_end, s_inc;
  191827. png_uint_32 i;
  191828. int jstop = png_pass_inc[pass];
  191829. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  191830. if (transformations & PNG_PACKSWAP)
  191831. {
  191832. sshift = (int)(((row_info->width + 1) & 0x01) << 2);
  191833. dshift = (int)(((final_width + 1) & 0x01) << 2);
  191834. s_start = 4;
  191835. s_end = 0;
  191836. s_inc = -4;
  191837. }
  191838. else
  191839. #endif
  191840. {
  191841. sshift = (int)((1 - ((row_info->width + 1) & 0x01)) << 2);
  191842. dshift = (int)((1 - ((final_width + 1) & 0x01)) << 2);
  191843. s_start = 0;
  191844. s_end = 4;
  191845. s_inc = 4;
  191846. }
  191847. for (i = 0; i < row_info->width; i++)
  191848. {
  191849. png_byte v = (png_byte)((*sp >> sshift) & 0xf);
  191850. int j;
  191851. for (j = 0; j < jstop; j++)
  191852. {
  191853. *dp &= (png_byte)((0xf0f >> (4 - dshift)) & 0xff);
  191854. *dp |= (png_byte)(v << dshift);
  191855. if (dshift == s_end)
  191856. {
  191857. dshift = s_start;
  191858. dp--;
  191859. }
  191860. else
  191861. dshift += s_inc;
  191862. }
  191863. if (sshift == s_end)
  191864. {
  191865. sshift = s_start;
  191866. sp--;
  191867. }
  191868. else
  191869. sshift += s_inc;
  191870. }
  191871. break;
  191872. }
  191873. default:
  191874. {
  191875. png_size_t pixel_bytes = (row_info->pixel_depth >> 3);
  191876. png_bytep sp = row + (png_size_t)(row_info->width - 1) * pixel_bytes;
  191877. png_bytep dp = row + (png_size_t)(final_width - 1) * pixel_bytes;
  191878. int jstop = png_pass_inc[pass];
  191879. png_uint_32 i;
  191880. for (i = 0; i < row_info->width; i++)
  191881. {
  191882. png_byte v[8];
  191883. int j;
  191884. png_memcpy(v, sp, pixel_bytes);
  191885. for (j = 0; j < jstop; j++)
  191886. {
  191887. png_memcpy(dp, v, pixel_bytes);
  191888. dp -= pixel_bytes;
  191889. }
  191890. sp -= pixel_bytes;
  191891. }
  191892. break;
  191893. }
  191894. }
  191895. row_info->width = final_width;
  191896. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,final_width);
  191897. }
  191898. #if !defined(PNG_READ_PACKSWAP_SUPPORTED)
  191899. transformations = transformations; /* silence compiler warning */
  191900. #endif
  191901. }
  191902. #endif /* PNG_READ_INTERLACING_SUPPORTED */
  191903. void /* PRIVATE */
  191904. png_read_filter_row(png_structp png_ptr, png_row_infop row_info, png_bytep row,
  191905. png_bytep prev_row, int filter)
  191906. {
  191907. png_debug(1, "in png_read_filter_row\n");
  191908. png_debug2(2,"row = %lu, filter = %d\n", png_ptr->row_number, filter);
  191909. switch (filter)
  191910. {
  191911. case PNG_FILTER_VALUE_NONE:
  191912. break;
  191913. case PNG_FILTER_VALUE_SUB:
  191914. {
  191915. png_uint_32 i;
  191916. png_uint_32 istop = row_info->rowbytes;
  191917. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  191918. png_bytep rp = row + bpp;
  191919. png_bytep lp = row;
  191920. for (i = bpp; i < istop; i++)
  191921. {
  191922. *rp = (png_byte)(((int)(*rp) + (int)(*lp++)) & 0xff);
  191923. rp++;
  191924. }
  191925. break;
  191926. }
  191927. case PNG_FILTER_VALUE_UP:
  191928. {
  191929. png_uint_32 i;
  191930. png_uint_32 istop = row_info->rowbytes;
  191931. png_bytep rp = row;
  191932. png_bytep pp = prev_row;
  191933. for (i = 0; i < istop; i++)
  191934. {
  191935. *rp = (png_byte)(((int)(*rp) + (int)(*pp++)) & 0xff);
  191936. rp++;
  191937. }
  191938. break;
  191939. }
  191940. case PNG_FILTER_VALUE_AVG:
  191941. {
  191942. png_uint_32 i;
  191943. png_bytep rp = row;
  191944. png_bytep pp = prev_row;
  191945. png_bytep lp = row;
  191946. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  191947. png_uint_32 istop = row_info->rowbytes - bpp;
  191948. for (i = 0; i < bpp; i++)
  191949. {
  191950. *rp = (png_byte)(((int)(*rp) +
  191951. ((int)(*pp++) / 2 )) & 0xff);
  191952. rp++;
  191953. }
  191954. for (i = 0; i < istop; i++)
  191955. {
  191956. *rp = (png_byte)(((int)(*rp) +
  191957. (int)(*pp++ + *lp++) / 2 ) & 0xff);
  191958. rp++;
  191959. }
  191960. break;
  191961. }
  191962. case PNG_FILTER_VALUE_PAETH:
  191963. {
  191964. png_uint_32 i;
  191965. png_bytep rp = row;
  191966. png_bytep pp = prev_row;
  191967. png_bytep lp = row;
  191968. png_bytep cp = prev_row;
  191969. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  191970. png_uint_32 istop=row_info->rowbytes - bpp;
  191971. for (i = 0; i < bpp; i++)
  191972. {
  191973. *rp = (png_byte)(((int)(*rp) + (int)(*pp++)) & 0xff);
  191974. rp++;
  191975. }
  191976. for (i = 0; i < istop; i++) /* use leftover rp,pp */
  191977. {
  191978. int a, b, c, pa, pb, pc, p;
  191979. a = *lp++;
  191980. b = *pp++;
  191981. c = *cp++;
  191982. p = b - c;
  191983. pc = a - c;
  191984. #ifdef PNG_USE_ABS
  191985. pa = abs(p);
  191986. pb = abs(pc);
  191987. pc = abs(p + pc);
  191988. #else
  191989. pa = p < 0 ? -p : p;
  191990. pb = pc < 0 ? -pc : pc;
  191991. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  191992. #endif
  191993. /*
  191994. if (pa <= pb && pa <= pc)
  191995. p = a;
  191996. else if (pb <= pc)
  191997. p = b;
  191998. else
  191999. p = c;
  192000. */
  192001. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  192002. *rp = (png_byte)(((int)(*rp) + p) & 0xff);
  192003. rp++;
  192004. }
  192005. break;
  192006. }
  192007. default:
  192008. png_warning(png_ptr, "Ignoring bad adaptive filter type");
  192009. *row=0;
  192010. break;
  192011. }
  192012. }
  192013. void /* PRIVATE */
  192014. png_read_finish_row(png_structp png_ptr)
  192015. {
  192016. #ifdef PNG_USE_LOCAL_ARRAYS
  192017. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  192018. /* start of interlace block */
  192019. PNG_CONST int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  192020. /* offset to next interlace block */
  192021. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  192022. /* start of interlace block in the y direction */
  192023. PNG_CONST int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  192024. /* offset to next interlace block in the y direction */
  192025. PNG_CONST int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  192026. #endif
  192027. png_debug(1, "in png_read_finish_row\n");
  192028. png_ptr->row_number++;
  192029. if (png_ptr->row_number < png_ptr->num_rows)
  192030. return;
  192031. if (png_ptr->interlaced)
  192032. {
  192033. png_ptr->row_number = 0;
  192034. png_memset_check(png_ptr, png_ptr->prev_row, 0,
  192035. png_ptr->rowbytes + 1);
  192036. do
  192037. {
  192038. png_ptr->pass++;
  192039. if (png_ptr->pass >= 7)
  192040. break;
  192041. png_ptr->iwidth = (png_ptr->width +
  192042. png_pass_inc[png_ptr->pass] - 1 -
  192043. png_pass_start[png_ptr->pass]) /
  192044. png_pass_inc[png_ptr->pass];
  192045. png_ptr->irowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,
  192046. png_ptr->iwidth) + 1;
  192047. if (!(png_ptr->transformations & PNG_INTERLACE))
  192048. {
  192049. png_ptr->num_rows = (png_ptr->height +
  192050. png_pass_yinc[png_ptr->pass] - 1 -
  192051. png_pass_ystart[png_ptr->pass]) /
  192052. png_pass_yinc[png_ptr->pass];
  192053. if (!(png_ptr->num_rows))
  192054. continue;
  192055. }
  192056. else /* if (png_ptr->transformations & PNG_INTERLACE) */
  192057. break;
  192058. } while (png_ptr->iwidth == 0);
  192059. if (png_ptr->pass < 7)
  192060. return;
  192061. }
  192062. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  192063. {
  192064. #ifdef PNG_USE_LOCAL_ARRAYS
  192065. PNG_CONST PNG_IDAT;
  192066. #endif
  192067. char extra;
  192068. int ret;
  192069. png_ptr->zstream.next_out = (Bytef *)&extra;
  192070. png_ptr->zstream.avail_out = (uInt)1;
  192071. for(;;)
  192072. {
  192073. if (!(png_ptr->zstream.avail_in))
  192074. {
  192075. while (!png_ptr->idat_size)
  192076. {
  192077. png_byte chunk_length[4];
  192078. png_crc_finish(png_ptr, 0);
  192079. png_read_data(png_ptr, chunk_length, 4);
  192080. png_ptr->idat_size = png_get_uint_31(png_ptr, chunk_length);
  192081. png_reset_crc(png_ptr);
  192082. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  192083. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  192084. png_error(png_ptr, "Not enough image data");
  192085. }
  192086. png_ptr->zstream.avail_in = (uInt)png_ptr->zbuf_size;
  192087. png_ptr->zstream.next_in = png_ptr->zbuf;
  192088. if (png_ptr->zbuf_size > png_ptr->idat_size)
  192089. png_ptr->zstream.avail_in = (uInt)png_ptr->idat_size;
  192090. png_crc_read(png_ptr, png_ptr->zbuf, png_ptr->zstream.avail_in);
  192091. png_ptr->idat_size -= png_ptr->zstream.avail_in;
  192092. }
  192093. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  192094. if (ret == Z_STREAM_END)
  192095. {
  192096. if (!(png_ptr->zstream.avail_out) || png_ptr->zstream.avail_in ||
  192097. png_ptr->idat_size)
  192098. png_warning(png_ptr, "Extra compressed data");
  192099. png_ptr->mode |= PNG_AFTER_IDAT;
  192100. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  192101. break;
  192102. }
  192103. if (ret != Z_OK)
  192104. png_error(png_ptr, png_ptr->zstream.msg ? png_ptr->zstream.msg :
  192105. "Decompression Error");
  192106. if (!(png_ptr->zstream.avail_out))
  192107. {
  192108. png_warning(png_ptr, "Extra compressed data.");
  192109. png_ptr->mode |= PNG_AFTER_IDAT;
  192110. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  192111. break;
  192112. }
  192113. }
  192114. png_ptr->zstream.avail_out = 0;
  192115. }
  192116. if (png_ptr->idat_size || png_ptr->zstream.avail_in)
  192117. png_warning(png_ptr, "Extra compression data");
  192118. inflateReset(&png_ptr->zstream);
  192119. png_ptr->mode |= PNG_AFTER_IDAT;
  192120. }
  192121. void /* PRIVATE */
  192122. png_read_start_row(png_structp png_ptr)
  192123. {
  192124. #ifdef PNG_USE_LOCAL_ARRAYS
  192125. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  192126. /* start of interlace block */
  192127. PNG_CONST int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  192128. /* offset to next interlace block */
  192129. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  192130. /* start of interlace block in the y direction */
  192131. PNG_CONST int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  192132. /* offset to next interlace block in the y direction */
  192133. PNG_CONST int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  192134. #endif
  192135. int max_pixel_depth;
  192136. png_uint_32 row_bytes;
  192137. png_debug(1, "in png_read_start_row\n");
  192138. png_ptr->zstream.avail_in = 0;
  192139. png_init_read_transformations(png_ptr);
  192140. if (png_ptr->interlaced)
  192141. {
  192142. if (!(png_ptr->transformations & PNG_INTERLACE))
  192143. png_ptr->num_rows = (png_ptr->height + png_pass_yinc[0] - 1 -
  192144. png_pass_ystart[0]) / png_pass_yinc[0];
  192145. else
  192146. png_ptr->num_rows = png_ptr->height;
  192147. png_ptr->iwidth = (png_ptr->width +
  192148. png_pass_inc[png_ptr->pass] - 1 -
  192149. png_pass_start[png_ptr->pass]) /
  192150. png_pass_inc[png_ptr->pass];
  192151. row_bytes = PNG_ROWBYTES(png_ptr->pixel_depth,png_ptr->iwidth) + 1;
  192152. png_ptr->irowbytes = (png_size_t)row_bytes;
  192153. if((png_uint_32)png_ptr->irowbytes != row_bytes)
  192154. png_error(png_ptr, "Rowbytes overflow in png_read_start_row");
  192155. }
  192156. else
  192157. {
  192158. png_ptr->num_rows = png_ptr->height;
  192159. png_ptr->iwidth = png_ptr->width;
  192160. png_ptr->irowbytes = png_ptr->rowbytes + 1;
  192161. }
  192162. max_pixel_depth = png_ptr->pixel_depth;
  192163. #if defined(PNG_READ_PACK_SUPPORTED)
  192164. if ((png_ptr->transformations & PNG_PACK) && png_ptr->bit_depth < 8)
  192165. max_pixel_depth = 8;
  192166. #endif
  192167. #if defined(PNG_READ_EXPAND_SUPPORTED)
  192168. if (png_ptr->transformations & PNG_EXPAND)
  192169. {
  192170. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  192171. {
  192172. if (png_ptr->num_trans)
  192173. max_pixel_depth = 32;
  192174. else
  192175. max_pixel_depth = 24;
  192176. }
  192177. else if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  192178. {
  192179. if (max_pixel_depth < 8)
  192180. max_pixel_depth = 8;
  192181. if (png_ptr->num_trans)
  192182. max_pixel_depth *= 2;
  192183. }
  192184. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  192185. {
  192186. if (png_ptr->num_trans)
  192187. {
  192188. max_pixel_depth *= 4;
  192189. max_pixel_depth /= 3;
  192190. }
  192191. }
  192192. }
  192193. #endif
  192194. #if defined(PNG_READ_FILLER_SUPPORTED)
  192195. if (png_ptr->transformations & (PNG_FILLER))
  192196. {
  192197. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  192198. max_pixel_depth = 32;
  192199. else if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  192200. {
  192201. if (max_pixel_depth <= 8)
  192202. max_pixel_depth = 16;
  192203. else
  192204. max_pixel_depth = 32;
  192205. }
  192206. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  192207. {
  192208. if (max_pixel_depth <= 32)
  192209. max_pixel_depth = 32;
  192210. else
  192211. max_pixel_depth = 64;
  192212. }
  192213. }
  192214. #endif
  192215. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  192216. if (png_ptr->transformations & PNG_GRAY_TO_RGB)
  192217. {
  192218. if (
  192219. #if defined(PNG_READ_EXPAND_SUPPORTED)
  192220. (png_ptr->num_trans && (png_ptr->transformations & PNG_EXPAND)) ||
  192221. #endif
  192222. #if defined(PNG_READ_FILLER_SUPPORTED)
  192223. (png_ptr->transformations & (PNG_FILLER)) ||
  192224. #endif
  192225. png_ptr->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  192226. {
  192227. if (max_pixel_depth <= 16)
  192228. max_pixel_depth = 32;
  192229. else
  192230. max_pixel_depth = 64;
  192231. }
  192232. else
  192233. {
  192234. if (max_pixel_depth <= 8)
  192235. {
  192236. if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  192237. max_pixel_depth = 32;
  192238. else
  192239. max_pixel_depth = 24;
  192240. }
  192241. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  192242. max_pixel_depth = 64;
  192243. else
  192244. max_pixel_depth = 48;
  192245. }
  192246. }
  192247. #endif
  192248. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) && \
  192249. defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  192250. if(png_ptr->transformations & PNG_USER_TRANSFORM)
  192251. {
  192252. int user_pixel_depth=png_ptr->user_transform_depth*
  192253. png_ptr->user_transform_channels;
  192254. if(user_pixel_depth > max_pixel_depth)
  192255. max_pixel_depth=user_pixel_depth;
  192256. }
  192257. #endif
  192258. /* align the width on the next larger 8 pixels. Mainly used
  192259. for interlacing */
  192260. row_bytes = ((png_ptr->width + 7) & ~((png_uint_32)7));
  192261. /* calculate the maximum bytes needed, adding a byte and a pixel
  192262. for safety's sake */
  192263. row_bytes = PNG_ROWBYTES(max_pixel_depth,row_bytes) +
  192264. 1 + ((max_pixel_depth + 7) >> 3);
  192265. #ifdef PNG_MAX_MALLOC_64K
  192266. if (row_bytes > (png_uint_32)65536L)
  192267. png_error(png_ptr, "This image requires a row greater than 64KB");
  192268. #endif
  192269. png_ptr->big_row_buf = (png_bytep)png_malloc(png_ptr, row_bytes+64);
  192270. png_ptr->row_buf = png_ptr->big_row_buf+32;
  192271. #ifdef PNG_MAX_MALLOC_64K
  192272. if ((png_uint_32)png_ptr->rowbytes + 1 > (png_uint_32)65536L)
  192273. png_error(png_ptr, "This image requires a row greater than 64KB");
  192274. #endif
  192275. if ((png_uint_32)png_ptr->rowbytes > (png_uint_32)(PNG_SIZE_MAX - 1))
  192276. png_error(png_ptr, "Row has too many bytes to allocate in memory.");
  192277. png_ptr->prev_row = (png_bytep)png_malloc(png_ptr, (png_uint_32)(
  192278. png_ptr->rowbytes + 1));
  192279. png_memset_check(png_ptr, png_ptr->prev_row, 0, png_ptr->rowbytes + 1);
  192280. png_debug1(3, "width = %lu,\n", png_ptr->width);
  192281. png_debug1(3, "height = %lu,\n", png_ptr->height);
  192282. png_debug1(3, "iwidth = %lu,\n", png_ptr->iwidth);
  192283. png_debug1(3, "num_rows = %lu\n", png_ptr->num_rows);
  192284. png_debug1(3, "rowbytes = %lu,\n", png_ptr->rowbytes);
  192285. png_debug1(3, "irowbytes = %lu,\n", png_ptr->irowbytes);
  192286. png_ptr->flags |= PNG_FLAG_ROW_INIT;
  192287. }
  192288. #endif /* PNG_READ_SUPPORTED */
  192289. /********* End of inlined file: pngrutil.c *********/
  192290. /********* Start of inlined file: pngset.c *********/
  192291. /* pngset.c - storage of image information into info struct
  192292. *
  192293. * Last changed in libpng 1.2.21 [October 4, 2007]
  192294. * For conditions of distribution and use, see copyright notice in png.h
  192295. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  192296. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  192297. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  192298. *
  192299. * The functions here are used during reads to store data from the file
  192300. * into the info struct, and during writes to store application data
  192301. * into the info struct for writing into the file. This abstracts the
  192302. * info struct and allows us to change the structure in the future.
  192303. */
  192304. #define PNG_INTERNAL
  192305. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  192306. #if defined(PNG_bKGD_SUPPORTED)
  192307. void PNGAPI
  192308. png_set_bKGD(png_structp png_ptr, png_infop info_ptr, png_color_16p background)
  192309. {
  192310. png_debug1(1, "in %s storage function\n", "bKGD");
  192311. if (png_ptr == NULL || info_ptr == NULL)
  192312. return;
  192313. png_memcpy(&(info_ptr->background), background, png_sizeof(png_color_16));
  192314. info_ptr->valid |= PNG_INFO_bKGD;
  192315. }
  192316. #endif
  192317. #if defined(PNG_cHRM_SUPPORTED)
  192318. #ifdef PNG_FLOATING_POINT_SUPPORTED
  192319. void PNGAPI
  192320. png_set_cHRM(png_structp png_ptr, png_infop info_ptr,
  192321. double white_x, double white_y, double red_x, double red_y,
  192322. double green_x, double green_y, double blue_x, double blue_y)
  192323. {
  192324. png_debug1(1, "in %s storage function\n", "cHRM");
  192325. if (png_ptr == NULL || info_ptr == NULL)
  192326. return;
  192327. if (white_x < 0.0 || white_y < 0.0 ||
  192328. red_x < 0.0 || red_y < 0.0 ||
  192329. green_x < 0.0 || green_y < 0.0 ||
  192330. blue_x < 0.0 || blue_y < 0.0)
  192331. {
  192332. png_warning(png_ptr,
  192333. "Ignoring attempt to set negative chromaticity value");
  192334. return;
  192335. }
  192336. if (white_x > 21474.83 || white_y > 21474.83 ||
  192337. red_x > 21474.83 || red_y > 21474.83 ||
  192338. green_x > 21474.83 || green_y > 21474.83 ||
  192339. blue_x > 21474.83 || blue_y > 21474.83)
  192340. {
  192341. png_warning(png_ptr,
  192342. "Ignoring attempt to set chromaticity value exceeding 21474.83");
  192343. return;
  192344. }
  192345. info_ptr->x_white = (float)white_x;
  192346. info_ptr->y_white = (float)white_y;
  192347. info_ptr->x_red = (float)red_x;
  192348. info_ptr->y_red = (float)red_y;
  192349. info_ptr->x_green = (float)green_x;
  192350. info_ptr->y_green = (float)green_y;
  192351. info_ptr->x_blue = (float)blue_x;
  192352. info_ptr->y_blue = (float)blue_y;
  192353. #ifdef PNG_FIXED_POINT_SUPPORTED
  192354. info_ptr->int_x_white = (png_fixed_point)(white_x*100000.+0.5);
  192355. info_ptr->int_y_white = (png_fixed_point)(white_y*100000.+0.5);
  192356. info_ptr->int_x_red = (png_fixed_point)( red_x*100000.+0.5);
  192357. info_ptr->int_y_red = (png_fixed_point)( red_y*100000.+0.5);
  192358. info_ptr->int_x_green = (png_fixed_point)(green_x*100000.+0.5);
  192359. info_ptr->int_y_green = (png_fixed_point)(green_y*100000.+0.5);
  192360. info_ptr->int_x_blue = (png_fixed_point)( blue_x*100000.+0.5);
  192361. info_ptr->int_y_blue = (png_fixed_point)( blue_y*100000.+0.5);
  192362. #endif
  192363. info_ptr->valid |= PNG_INFO_cHRM;
  192364. }
  192365. #endif
  192366. #ifdef PNG_FIXED_POINT_SUPPORTED
  192367. void PNGAPI
  192368. png_set_cHRM_fixed(png_structp png_ptr, png_infop info_ptr,
  192369. png_fixed_point white_x, png_fixed_point white_y, png_fixed_point red_x,
  192370. png_fixed_point red_y, png_fixed_point green_x, png_fixed_point green_y,
  192371. png_fixed_point blue_x, png_fixed_point blue_y)
  192372. {
  192373. png_debug1(1, "in %s storage function\n", "cHRM");
  192374. if (png_ptr == NULL || info_ptr == NULL)
  192375. return;
  192376. if (white_x < 0 || white_y < 0 ||
  192377. red_x < 0 || red_y < 0 ||
  192378. green_x < 0 || green_y < 0 ||
  192379. blue_x < 0 || blue_y < 0)
  192380. {
  192381. png_warning(png_ptr,
  192382. "Ignoring attempt to set negative chromaticity value");
  192383. return;
  192384. }
  192385. #ifdef PNG_FLOATING_POINT_SUPPORTED
  192386. if (white_x > (double) PNG_UINT_31_MAX ||
  192387. white_y > (double) PNG_UINT_31_MAX ||
  192388. red_x > (double) PNG_UINT_31_MAX ||
  192389. red_y > (double) PNG_UINT_31_MAX ||
  192390. green_x > (double) PNG_UINT_31_MAX ||
  192391. green_y > (double) PNG_UINT_31_MAX ||
  192392. blue_x > (double) PNG_UINT_31_MAX ||
  192393. blue_y > (double) PNG_UINT_31_MAX)
  192394. #else
  192395. if (white_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  192396. white_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  192397. red_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  192398. red_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  192399. green_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  192400. green_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  192401. blue_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  192402. blue_y > (png_fixed_point) PNG_UINT_31_MAX/100000L)
  192403. #endif
  192404. {
  192405. png_warning(png_ptr,
  192406. "Ignoring attempt to set chromaticity value exceeding 21474.83");
  192407. return;
  192408. }
  192409. info_ptr->int_x_white = white_x;
  192410. info_ptr->int_y_white = white_y;
  192411. info_ptr->int_x_red = red_x;
  192412. info_ptr->int_y_red = red_y;
  192413. info_ptr->int_x_green = green_x;
  192414. info_ptr->int_y_green = green_y;
  192415. info_ptr->int_x_blue = blue_x;
  192416. info_ptr->int_y_blue = blue_y;
  192417. #ifdef PNG_FLOATING_POINT_SUPPORTED
  192418. info_ptr->x_white = (float)(white_x/100000.);
  192419. info_ptr->y_white = (float)(white_y/100000.);
  192420. info_ptr->x_red = (float)( red_x/100000.);
  192421. info_ptr->y_red = (float)( red_y/100000.);
  192422. info_ptr->x_green = (float)(green_x/100000.);
  192423. info_ptr->y_green = (float)(green_y/100000.);
  192424. info_ptr->x_blue = (float)( blue_x/100000.);
  192425. info_ptr->y_blue = (float)( blue_y/100000.);
  192426. #endif
  192427. info_ptr->valid |= PNG_INFO_cHRM;
  192428. }
  192429. #endif
  192430. #endif
  192431. #if defined(PNG_gAMA_SUPPORTED)
  192432. #ifdef PNG_FLOATING_POINT_SUPPORTED
  192433. void PNGAPI
  192434. png_set_gAMA(png_structp png_ptr, png_infop info_ptr, double file_gamma)
  192435. {
  192436. double gamma;
  192437. png_debug1(1, "in %s storage function\n", "gAMA");
  192438. if (png_ptr == NULL || info_ptr == NULL)
  192439. return;
  192440. /* Check for overflow */
  192441. if (file_gamma > 21474.83)
  192442. {
  192443. png_warning(png_ptr, "Limiting gamma to 21474.83");
  192444. gamma=21474.83;
  192445. }
  192446. else
  192447. gamma=file_gamma;
  192448. info_ptr->gamma = (float)gamma;
  192449. #ifdef PNG_FIXED_POINT_SUPPORTED
  192450. info_ptr->int_gamma = (int)(gamma*100000.+.5);
  192451. #endif
  192452. info_ptr->valid |= PNG_INFO_gAMA;
  192453. if(gamma == 0.0)
  192454. png_warning(png_ptr, "Setting gamma=0");
  192455. }
  192456. #endif
  192457. void PNGAPI
  192458. png_set_gAMA_fixed(png_structp png_ptr, png_infop info_ptr, png_fixed_point
  192459. int_gamma)
  192460. {
  192461. png_fixed_point gamma;
  192462. png_debug1(1, "in %s storage function\n", "gAMA");
  192463. if (png_ptr == NULL || info_ptr == NULL)
  192464. return;
  192465. if (int_gamma > (png_fixed_point) PNG_UINT_31_MAX)
  192466. {
  192467. png_warning(png_ptr, "Limiting gamma to 21474.83");
  192468. gamma=PNG_UINT_31_MAX;
  192469. }
  192470. else
  192471. {
  192472. if (int_gamma < 0)
  192473. {
  192474. png_warning(png_ptr, "Setting negative gamma to zero");
  192475. gamma=0;
  192476. }
  192477. else
  192478. gamma=int_gamma;
  192479. }
  192480. #ifdef PNG_FLOATING_POINT_SUPPORTED
  192481. info_ptr->gamma = (float)(gamma/100000.);
  192482. #endif
  192483. #ifdef PNG_FIXED_POINT_SUPPORTED
  192484. info_ptr->int_gamma = gamma;
  192485. #endif
  192486. info_ptr->valid |= PNG_INFO_gAMA;
  192487. if(gamma == 0)
  192488. png_warning(png_ptr, "Setting gamma=0");
  192489. }
  192490. #endif
  192491. #if defined(PNG_hIST_SUPPORTED)
  192492. void PNGAPI
  192493. png_set_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_16p hist)
  192494. {
  192495. int i;
  192496. png_debug1(1, "in %s storage function\n", "hIST");
  192497. if (png_ptr == NULL || info_ptr == NULL)
  192498. return;
  192499. if (info_ptr->num_palette == 0 || info_ptr->num_palette
  192500. > PNG_MAX_PALETTE_LENGTH)
  192501. {
  192502. png_warning(png_ptr,
  192503. "Invalid palette size, hIST allocation skipped.");
  192504. return;
  192505. }
  192506. #ifdef PNG_FREE_ME_SUPPORTED
  192507. png_free_data(png_ptr, info_ptr, PNG_FREE_HIST, 0);
  192508. #endif
  192509. /* Changed from info->num_palette to PNG_MAX_PALETTE_LENGTH in version
  192510. 1.2.1 */
  192511. png_ptr->hist = (png_uint_16p)png_malloc_warn(png_ptr,
  192512. (png_uint_32)(PNG_MAX_PALETTE_LENGTH * png_sizeof (png_uint_16)));
  192513. if (png_ptr->hist == NULL)
  192514. {
  192515. png_warning(png_ptr, "Insufficient memory for hIST chunk data.");
  192516. return;
  192517. }
  192518. for (i = 0; i < info_ptr->num_palette; i++)
  192519. png_ptr->hist[i] = hist[i];
  192520. info_ptr->hist = png_ptr->hist;
  192521. info_ptr->valid |= PNG_INFO_hIST;
  192522. #ifdef PNG_FREE_ME_SUPPORTED
  192523. info_ptr->free_me |= PNG_FREE_HIST;
  192524. #else
  192525. png_ptr->flags |= PNG_FLAG_FREE_HIST;
  192526. #endif
  192527. }
  192528. #endif
  192529. void PNGAPI
  192530. png_set_IHDR(png_structp png_ptr, png_infop info_ptr,
  192531. png_uint_32 width, png_uint_32 height, int bit_depth,
  192532. int color_type, int interlace_type, int compression_type,
  192533. int filter_type)
  192534. {
  192535. png_debug1(1, "in %s storage function\n", "IHDR");
  192536. if (png_ptr == NULL || info_ptr == NULL)
  192537. return;
  192538. /* check for width and height valid values */
  192539. if (width == 0 || height == 0)
  192540. png_error(png_ptr, "Image width or height is zero in IHDR");
  192541. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  192542. if (width > png_ptr->user_width_max || height > png_ptr->user_height_max)
  192543. png_error(png_ptr, "image size exceeds user limits in IHDR");
  192544. #else
  192545. if (width > PNG_USER_WIDTH_MAX || height > PNG_USER_HEIGHT_MAX)
  192546. png_error(png_ptr, "image size exceeds user limits in IHDR");
  192547. #endif
  192548. if (width > PNG_UINT_31_MAX || height > PNG_UINT_31_MAX)
  192549. png_error(png_ptr, "Invalid image size in IHDR");
  192550. if ( width > (PNG_UINT_32_MAX
  192551. >> 3) /* 8-byte RGBA pixels */
  192552. - 64 /* bigrowbuf hack */
  192553. - 1 /* filter byte */
  192554. - 7*8 /* rounding of width to multiple of 8 pixels */
  192555. - 8) /* extra max_pixel_depth pad */
  192556. png_warning(png_ptr, "Width is too large for libpng to process pixels");
  192557. /* check other values */
  192558. if (bit_depth != 1 && bit_depth != 2 && bit_depth != 4 &&
  192559. bit_depth != 8 && bit_depth != 16)
  192560. png_error(png_ptr, "Invalid bit depth in IHDR");
  192561. if (color_type < 0 || color_type == 1 ||
  192562. color_type == 5 || color_type > 6)
  192563. png_error(png_ptr, "Invalid color type in IHDR");
  192564. if (((color_type == PNG_COLOR_TYPE_PALETTE) && bit_depth > 8) ||
  192565. ((color_type == PNG_COLOR_TYPE_RGB ||
  192566. color_type == PNG_COLOR_TYPE_GRAY_ALPHA ||
  192567. color_type == PNG_COLOR_TYPE_RGB_ALPHA) && bit_depth < 8))
  192568. png_error(png_ptr, "Invalid color type/bit depth combination in IHDR");
  192569. if (interlace_type >= PNG_INTERLACE_LAST)
  192570. png_error(png_ptr, "Unknown interlace method in IHDR");
  192571. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  192572. png_error(png_ptr, "Unknown compression method in IHDR");
  192573. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  192574. /* Accept filter_method 64 (intrapixel differencing) only if
  192575. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  192576. * 2. Libpng did not read a PNG signature (this filter_method is only
  192577. * used in PNG datastreams that are embedded in MNG datastreams) and
  192578. * 3. The application called png_permit_mng_features with a mask that
  192579. * included PNG_FLAG_MNG_FILTER_64 and
  192580. * 4. The filter_method is 64 and
  192581. * 5. The color_type is RGB or RGBA
  192582. */
  192583. if((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)&&png_ptr->mng_features_permitted)
  192584. png_warning(png_ptr,"MNG features are not allowed in a PNG datastream");
  192585. if(filter_type != PNG_FILTER_TYPE_BASE)
  192586. {
  192587. if(!((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  192588. (filter_type == PNG_INTRAPIXEL_DIFFERENCING) &&
  192589. ((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE) == 0) &&
  192590. (color_type == PNG_COLOR_TYPE_RGB ||
  192591. color_type == PNG_COLOR_TYPE_RGB_ALPHA)))
  192592. png_error(png_ptr, "Unknown filter method in IHDR");
  192593. if(png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)
  192594. png_warning(png_ptr, "Invalid filter method in IHDR");
  192595. }
  192596. #else
  192597. if(filter_type != PNG_FILTER_TYPE_BASE)
  192598. png_error(png_ptr, "Unknown filter method in IHDR");
  192599. #endif
  192600. info_ptr->width = width;
  192601. info_ptr->height = height;
  192602. info_ptr->bit_depth = (png_byte)bit_depth;
  192603. info_ptr->color_type =(png_byte) color_type;
  192604. info_ptr->compression_type = (png_byte)compression_type;
  192605. info_ptr->filter_type = (png_byte)filter_type;
  192606. info_ptr->interlace_type = (png_byte)interlace_type;
  192607. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  192608. info_ptr->channels = 1;
  192609. else if (info_ptr->color_type & PNG_COLOR_MASK_COLOR)
  192610. info_ptr->channels = 3;
  192611. else
  192612. info_ptr->channels = 1;
  192613. if (info_ptr->color_type & PNG_COLOR_MASK_ALPHA)
  192614. info_ptr->channels++;
  192615. info_ptr->pixel_depth = (png_byte)(info_ptr->channels * info_ptr->bit_depth);
  192616. /* check for potential overflow */
  192617. if (width > (PNG_UINT_32_MAX
  192618. >> 3) /* 8-byte RGBA pixels */
  192619. - 64 /* bigrowbuf hack */
  192620. - 1 /* filter byte */
  192621. - 7*8 /* rounding of width to multiple of 8 pixels */
  192622. - 8) /* extra max_pixel_depth pad */
  192623. info_ptr->rowbytes = (png_size_t)0;
  192624. else
  192625. info_ptr->rowbytes = PNG_ROWBYTES(info_ptr->pixel_depth,width);
  192626. }
  192627. #if defined(PNG_oFFs_SUPPORTED)
  192628. void PNGAPI
  192629. png_set_oFFs(png_structp png_ptr, png_infop info_ptr,
  192630. png_int_32 offset_x, png_int_32 offset_y, int unit_type)
  192631. {
  192632. png_debug1(1, "in %s storage function\n", "oFFs");
  192633. if (png_ptr == NULL || info_ptr == NULL)
  192634. return;
  192635. info_ptr->x_offset = offset_x;
  192636. info_ptr->y_offset = offset_y;
  192637. info_ptr->offset_unit_type = (png_byte)unit_type;
  192638. info_ptr->valid |= PNG_INFO_oFFs;
  192639. }
  192640. #endif
  192641. #if defined(PNG_pCAL_SUPPORTED)
  192642. void PNGAPI
  192643. png_set_pCAL(png_structp png_ptr, png_infop info_ptr,
  192644. png_charp purpose, png_int_32 X0, png_int_32 X1, int type, int nparams,
  192645. png_charp units, png_charpp params)
  192646. {
  192647. png_uint_32 length;
  192648. int i;
  192649. png_debug1(1, "in %s storage function\n", "pCAL");
  192650. if (png_ptr == NULL || info_ptr == NULL)
  192651. return;
  192652. length = png_strlen(purpose) + 1;
  192653. png_debug1(3, "allocating purpose for info (%lu bytes)\n", length);
  192654. info_ptr->pcal_purpose = (png_charp)png_malloc_warn(png_ptr, length);
  192655. if (info_ptr->pcal_purpose == NULL)
  192656. {
  192657. png_warning(png_ptr, "Insufficient memory for pCAL purpose.");
  192658. return;
  192659. }
  192660. png_memcpy(info_ptr->pcal_purpose, purpose, (png_size_t)length);
  192661. png_debug(3, "storing X0, X1, type, and nparams in info\n");
  192662. info_ptr->pcal_X0 = X0;
  192663. info_ptr->pcal_X1 = X1;
  192664. info_ptr->pcal_type = (png_byte)type;
  192665. info_ptr->pcal_nparams = (png_byte)nparams;
  192666. length = png_strlen(units) + 1;
  192667. png_debug1(3, "allocating units for info (%lu bytes)\n", length);
  192668. info_ptr->pcal_units = (png_charp)png_malloc_warn(png_ptr, length);
  192669. if (info_ptr->pcal_units == NULL)
  192670. {
  192671. png_warning(png_ptr, "Insufficient memory for pCAL units.");
  192672. return;
  192673. }
  192674. png_memcpy(info_ptr->pcal_units, units, (png_size_t)length);
  192675. info_ptr->pcal_params = (png_charpp)png_malloc_warn(png_ptr,
  192676. (png_uint_32)((nparams + 1) * png_sizeof(png_charp)));
  192677. if (info_ptr->pcal_params == NULL)
  192678. {
  192679. png_warning(png_ptr, "Insufficient memory for pCAL params.");
  192680. return;
  192681. }
  192682. info_ptr->pcal_params[nparams] = NULL;
  192683. for (i = 0; i < nparams; i++)
  192684. {
  192685. length = png_strlen(params[i]) + 1;
  192686. png_debug2(3, "allocating parameter %d for info (%lu bytes)\n", i, length);
  192687. info_ptr->pcal_params[i] = (png_charp)png_malloc_warn(png_ptr, length);
  192688. if (info_ptr->pcal_params[i] == NULL)
  192689. {
  192690. png_warning(png_ptr, "Insufficient memory for pCAL parameter.");
  192691. return;
  192692. }
  192693. png_memcpy(info_ptr->pcal_params[i], params[i], (png_size_t)length);
  192694. }
  192695. info_ptr->valid |= PNG_INFO_pCAL;
  192696. #ifdef PNG_FREE_ME_SUPPORTED
  192697. info_ptr->free_me |= PNG_FREE_PCAL;
  192698. #endif
  192699. }
  192700. #endif
  192701. #if defined(PNG_READ_sCAL_SUPPORTED) || defined(PNG_WRITE_sCAL_SUPPORTED)
  192702. #ifdef PNG_FLOATING_POINT_SUPPORTED
  192703. void PNGAPI
  192704. png_set_sCAL(png_structp png_ptr, png_infop info_ptr,
  192705. int unit, double width, double height)
  192706. {
  192707. png_debug1(1, "in %s storage function\n", "sCAL");
  192708. if (png_ptr == NULL || info_ptr == NULL)
  192709. return;
  192710. info_ptr->scal_unit = (png_byte)unit;
  192711. info_ptr->scal_pixel_width = width;
  192712. info_ptr->scal_pixel_height = height;
  192713. info_ptr->valid |= PNG_INFO_sCAL;
  192714. }
  192715. #else
  192716. #ifdef PNG_FIXED_POINT_SUPPORTED
  192717. void PNGAPI
  192718. png_set_sCAL_s(png_structp png_ptr, png_infop info_ptr,
  192719. int unit, png_charp swidth, png_charp sheight)
  192720. {
  192721. png_uint_32 length;
  192722. png_debug1(1, "in %s storage function\n", "sCAL");
  192723. if (png_ptr == NULL || info_ptr == NULL)
  192724. return;
  192725. info_ptr->scal_unit = (png_byte)unit;
  192726. length = png_strlen(swidth) + 1;
  192727. png_debug1(3, "allocating unit for info (%d bytes)\n", length);
  192728. info_ptr->scal_s_width = (png_charp)png_malloc_warn(png_ptr, length);
  192729. if (info_ptr->scal_s_width == NULL)
  192730. {
  192731. png_warning(png_ptr,
  192732. "Memory allocation failed while processing sCAL.");
  192733. }
  192734. png_memcpy(info_ptr->scal_s_width, swidth, (png_size_t)length);
  192735. length = png_strlen(sheight) + 1;
  192736. png_debug1(3, "allocating unit for info (%d bytes)\n", length);
  192737. info_ptr->scal_s_height = (png_charp)png_malloc_warn(png_ptr, length);
  192738. if (info_ptr->scal_s_height == NULL)
  192739. {
  192740. png_free (png_ptr, info_ptr->scal_s_width);
  192741. png_warning(png_ptr,
  192742. "Memory allocation failed while processing sCAL.");
  192743. }
  192744. png_memcpy(info_ptr->scal_s_height, sheight, (png_size_t)length);
  192745. info_ptr->valid |= PNG_INFO_sCAL;
  192746. #ifdef PNG_FREE_ME_SUPPORTED
  192747. info_ptr->free_me |= PNG_FREE_SCAL;
  192748. #endif
  192749. }
  192750. #endif
  192751. #endif
  192752. #endif
  192753. #if defined(PNG_pHYs_SUPPORTED)
  192754. void PNGAPI
  192755. png_set_pHYs(png_structp png_ptr, png_infop info_ptr,
  192756. png_uint_32 res_x, png_uint_32 res_y, int unit_type)
  192757. {
  192758. png_debug1(1, "in %s storage function\n", "pHYs");
  192759. if (png_ptr == NULL || info_ptr == NULL)
  192760. return;
  192761. info_ptr->x_pixels_per_unit = res_x;
  192762. info_ptr->y_pixels_per_unit = res_y;
  192763. info_ptr->phys_unit_type = (png_byte)unit_type;
  192764. info_ptr->valid |= PNG_INFO_pHYs;
  192765. }
  192766. #endif
  192767. void PNGAPI
  192768. png_set_PLTE(png_structp png_ptr, png_infop info_ptr,
  192769. png_colorp palette, int num_palette)
  192770. {
  192771. png_debug1(1, "in %s storage function\n", "PLTE");
  192772. if (png_ptr == NULL || info_ptr == NULL)
  192773. return;
  192774. if (num_palette < 0 || num_palette > PNG_MAX_PALETTE_LENGTH)
  192775. {
  192776. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  192777. png_error(png_ptr, "Invalid palette length");
  192778. else
  192779. {
  192780. png_warning(png_ptr, "Invalid palette length");
  192781. return;
  192782. }
  192783. }
  192784. /*
  192785. * It may not actually be necessary to set png_ptr->palette here;
  192786. * we do it for backward compatibility with the way the png_handle_tRNS
  192787. * function used to do the allocation.
  192788. */
  192789. #ifdef PNG_FREE_ME_SUPPORTED
  192790. png_free_data(png_ptr, info_ptr, PNG_FREE_PLTE, 0);
  192791. #endif
  192792. /* Changed in libpng-1.2.1 to allocate PNG_MAX_PALETTE_LENGTH instead
  192793. of num_palette entries,
  192794. in case of an invalid PNG file that has too-large sample values. */
  192795. png_ptr->palette = (png_colorp)png_malloc(png_ptr,
  192796. PNG_MAX_PALETTE_LENGTH * png_sizeof(png_color));
  192797. png_memset(png_ptr->palette, 0, PNG_MAX_PALETTE_LENGTH *
  192798. png_sizeof(png_color));
  192799. png_memcpy(png_ptr->palette, palette, num_palette * png_sizeof (png_color));
  192800. info_ptr->palette = png_ptr->palette;
  192801. info_ptr->num_palette = png_ptr->num_palette = (png_uint_16)num_palette;
  192802. #ifdef PNG_FREE_ME_SUPPORTED
  192803. info_ptr->free_me |= PNG_FREE_PLTE;
  192804. #else
  192805. png_ptr->flags |= PNG_FLAG_FREE_PLTE;
  192806. #endif
  192807. info_ptr->valid |= PNG_INFO_PLTE;
  192808. }
  192809. #if defined(PNG_sBIT_SUPPORTED)
  192810. void PNGAPI
  192811. png_set_sBIT(png_structp png_ptr, png_infop info_ptr,
  192812. png_color_8p sig_bit)
  192813. {
  192814. png_debug1(1, "in %s storage function\n", "sBIT");
  192815. if (png_ptr == NULL || info_ptr == NULL)
  192816. return;
  192817. png_memcpy(&(info_ptr->sig_bit), sig_bit, png_sizeof (png_color_8));
  192818. info_ptr->valid |= PNG_INFO_sBIT;
  192819. }
  192820. #endif
  192821. #if defined(PNG_sRGB_SUPPORTED)
  192822. void PNGAPI
  192823. png_set_sRGB(png_structp png_ptr, png_infop info_ptr, int intent)
  192824. {
  192825. png_debug1(1, "in %s storage function\n", "sRGB");
  192826. if (png_ptr == NULL || info_ptr == NULL)
  192827. return;
  192828. info_ptr->srgb_intent = (png_byte)intent;
  192829. info_ptr->valid |= PNG_INFO_sRGB;
  192830. }
  192831. void PNGAPI
  192832. png_set_sRGB_gAMA_and_cHRM(png_structp png_ptr, png_infop info_ptr,
  192833. int intent)
  192834. {
  192835. #if defined(PNG_gAMA_SUPPORTED)
  192836. #ifdef PNG_FLOATING_POINT_SUPPORTED
  192837. float file_gamma;
  192838. #endif
  192839. #ifdef PNG_FIXED_POINT_SUPPORTED
  192840. png_fixed_point int_file_gamma;
  192841. #endif
  192842. #endif
  192843. #if defined(PNG_cHRM_SUPPORTED)
  192844. #ifdef PNG_FLOATING_POINT_SUPPORTED
  192845. float white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y;
  192846. #endif
  192847. #ifdef PNG_FIXED_POINT_SUPPORTED
  192848. png_fixed_point int_white_x, int_white_y, int_red_x, int_red_y, int_green_x,
  192849. int_green_y, int_blue_x, int_blue_y;
  192850. #endif
  192851. #endif
  192852. png_debug1(1, "in %s storage function\n", "sRGB_gAMA_and_cHRM");
  192853. if (png_ptr == NULL || info_ptr == NULL)
  192854. return;
  192855. png_set_sRGB(png_ptr, info_ptr, intent);
  192856. #if defined(PNG_gAMA_SUPPORTED)
  192857. #ifdef PNG_FLOATING_POINT_SUPPORTED
  192858. file_gamma = (float).45455;
  192859. png_set_gAMA(png_ptr, info_ptr, file_gamma);
  192860. #endif
  192861. #ifdef PNG_FIXED_POINT_SUPPORTED
  192862. int_file_gamma = 45455L;
  192863. png_set_gAMA_fixed(png_ptr, info_ptr, int_file_gamma);
  192864. #endif
  192865. #endif
  192866. #if defined(PNG_cHRM_SUPPORTED)
  192867. #ifdef PNG_FIXED_POINT_SUPPORTED
  192868. int_white_x = 31270L;
  192869. int_white_y = 32900L;
  192870. int_red_x = 64000L;
  192871. int_red_y = 33000L;
  192872. int_green_x = 30000L;
  192873. int_green_y = 60000L;
  192874. int_blue_x = 15000L;
  192875. int_blue_y = 6000L;
  192876. png_set_cHRM_fixed(png_ptr, info_ptr,
  192877. int_white_x, int_white_y, int_red_x, int_red_y, int_green_x, int_green_y,
  192878. int_blue_x, int_blue_y);
  192879. #endif
  192880. #ifdef PNG_FLOATING_POINT_SUPPORTED
  192881. white_x = (float).3127;
  192882. white_y = (float).3290;
  192883. red_x = (float).64;
  192884. red_y = (float).33;
  192885. green_x = (float).30;
  192886. green_y = (float).60;
  192887. blue_x = (float).15;
  192888. blue_y = (float).06;
  192889. png_set_cHRM(png_ptr, info_ptr,
  192890. white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y);
  192891. #endif
  192892. #endif
  192893. }
  192894. #endif
  192895. #if defined(PNG_iCCP_SUPPORTED)
  192896. void PNGAPI
  192897. png_set_iCCP(png_structp png_ptr, png_infop info_ptr,
  192898. png_charp name, int compression_type,
  192899. png_charp profile, png_uint_32 proflen)
  192900. {
  192901. png_charp new_iccp_name;
  192902. png_charp new_iccp_profile;
  192903. png_debug1(1, "in %s storage function\n", "iCCP");
  192904. if (png_ptr == NULL || info_ptr == NULL || name == NULL || profile == NULL)
  192905. return;
  192906. new_iccp_name = (png_charp)png_malloc_warn(png_ptr, png_strlen(name)+1);
  192907. if (new_iccp_name == NULL)
  192908. {
  192909. png_warning(png_ptr, "Insufficient memory to process iCCP chunk.");
  192910. return;
  192911. }
  192912. png_strncpy(new_iccp_name, name, png_strlen(name)+1);
  192913. new_iccp_profile = (png_charp)png_malloc_warn(png_ptr, proflen);
  192914. if (new_iccp_profile == NULL)
  192915. {
  192916. png_free (png_ptr, new_iccp_name);
  192917. png_warning(png_ptr, "Insufficient memory to process iCCP profile.");
  192918. return;
  192919. }
  192920. png_memcpy(new_iccp_profile, profile, (png_size_t)proflen);
  192921. png_free_data(png_ptr, info_ptr, PNG_FREE_ICCP, 0);
  192922. info_ptr->iccp_proflen = proflen;
  192923. info_ptr->iccp_name = new_iccp_name;
  192924. info_ptr->iccp_profile = new_iccp_profile;
  192925. /* Compression is always zero but is here so the API and info structure
  192926. * does not have to change if we introduce multiple compression types */
  192927. info_ptr->iccp_compression = (png_byte)compression_type;
  192928. #ifdef PNG_FREE_ME_SUPPORTED
  192929. info_ptr->free_me |= PNG_FREE_ICCP;
  192930. #endif
  192931. info_ptr->valid |= PNG_INFO_iCCP;
  192932. }
  192933. #endif
  192934. #if defined(PNG_TEXT_SUPPORTED)
  192935. void PNGAPI
  192936. png_set_text(png_structp png_ptr, png_infop info_ptr, png_textp text_ptr,
  192937. int num_text)
  192938. {
  192939. int ret;
  192940. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, num_text);
  192941. if (ret)
  192942. png_error(png_ptr, "Insufficient memory to store text");
  192943. }
  192944. int /* PRIVATE */
  192945. png_set_text_2(png_structp png_ptr, png_infop info_ptr, png_textp text_ptr,
  192946. int num_text)
  192947. {
  192948. int i;
  192949. png_debug1(1, "in %s storage function\n", (png_ptr->chunk_name[0] == '\0' ?
  192950. "text" : (png_const_charp)png_ptr->chunk_name));
  192951. if (png_ptr == NULL || info_ptr == NULL || num_text == 0)
  192952. return(0);
  192953. /* Make sure we have enough space in the "text" array in info_struct
  192954. * to hold all of the incoming text_ptr objects.
  192955. */
  192956. if (info_ptr->num_text + num_text > info_ptr->max_text)
  192957. {
  192958. if (info_ptr->text != NULL)
  192959. {
  192960. png_textp old_text;
  192961. int old_max;
  192962. old_max = info_ptr->max_text;
  192963. info_ptr->max_text = info_ptr->num_text + num_text + 8;
  192964. old_text = info_ptr->text;
  192965. info_ptr->text = (png_textp)png_malloc_warn(png_ptr,
  192966. (png_uint_32)(info_ptr->max_text * png_sizeof (png_text)));
  192967. if (info_ptr->text == NULL)
  192968. {
  192969. png_free(png_ptr, old_text);
  192970. return(1);
  192971. }
  192972. png_memcpy(info_ptr->text, old_text, (png_size_t)(old_max *
  192973. png_sizeof(png_text)));
  192974. png_free(png_ptr, old_text);
  192975. }
  192976. else
  192977. {
  192978. info_ptr->max_text = num_text + 8;
  192979. info_ptr->num_text = 0;
  192980. info_ptr->text = (png_textp)png_malloc_warn(png_ptr,
  192981. (png_uint_32)(info_ptr->max_text * png_sizeof (png_text)));
  192982. if (info_ptr->text == NULL)
  192983. return(1);
  192984. #ifdef PNG_FREE_ME_SUPPORTED
  192985. info_ptr->free_me |= PNG_FREE_TEXT;
  192986. #endif
  192987. }
  192988. png_debug1(3, "allocated %d entries for info_ptr->text\n",
  192989. info_ptr->max_text);
  192990. }
  192991. for (i = 0; i < num_text; i++)
  192992. {
  192993. png_size_t text_length,key_len;
  192994. png_size_t lang_len,lang_key_len;
  192995. png_textp textp = &(info_ptr->text[info_ptr->num_text]);
  192996. if (text_ptr[i].key == NULL)
  192997. continue;
  192998. key_len = png_strlen(text_ptr[i].key);
  192999. if(text_ptr[i].compression <= 0)
  193000. {
  193001. lang_len = 0;
  193002. lang_key_len = 0;
  193003. }
  193004. else
  193005. #ifdef PNG_iTXt_SUPPORTED
  193006. {
  193007. /* set iTXt data */
  193008. if (text_ptr[i].lang != NULL)
  193009. lang_len = png_strlen(text_ptr[i].lang);
  193010. else
  193011. lang_len = 0;
  193012. if (text_ptr[i].lang_key != NULL)
  193013. lang_key_len = png_strlen(text_ptr[i].lang_key);
  193014. else
  193015. lang_key_len = 0;
  193016. }
  193017. #else
  193018. {
  193019. png_warning(png_ptr, "iTXt chunk not supported.");
  193020. continue;
  193021. }
  193022. #endif
  193023. if (text_ptr[i].text == NULL || text_ptr[i].text[0] == '\0')
  193024. {
  193025. text_length = 0;
  193026. #ifdef PNG_iTXt_SUPPORTED
  193027. if(text_ptr[i].compression > 0)
  193028. textp->compression = PNG_ITXT_COMPRESSION_NONE;
  193029. else
  193030. #endif
  193031. textp->compression = PNG_TEXT_COMPRESSION_NONE;
  193032. }
  193033. else
  193034. {
  193035. text_length = png_strlen(text_ptr[i].text);
  193036. textp->compression = text_ptr[i].compression;
  193037. }
  193038. textp->key = (png_charp)png_malloc_warn(png_ptr,
  193039. (png_uint_32)(key_len + text_length + lang_len + lang_key_len + 4));
  193040. if (textp->key == NULL)
  193041. return(1);
  193042. png_debug2(2, "Allocated %lu bytes at %x in png_set_text\n",
  193043. (png_uint_32)(key_len + lang_len + lang_key_len + text_length + 4),
  193044. (int)textp->key);
  193045. png_memcpy(textp->key, text_ptr[i].key,
  193046. (png_size_t)(key_len));
  193047. *(textp->key+key_len) = '\0';
  193048. #ifdef PNG_iTXt_SUPPORTED
  193049. if (text_ptr[i].compression > 0)
  193050. {
  193051. textp->lang=textp->key + key_len + 1;
  193052. png_memcpy(textp->lang, text_ptr[i].lang, lang_len);
  193053. *(textp->lang+lang_len) = '\0';
  193054. textp->lang_key=textp->lang + lang_len + 1;
  193055. png_memcpy(textp->lang_key, text_ptr[i].lang_key, lang_key_len);
  193056. *(textp->lang_key+lang_key_len) = '\0';
  193057. textp->text=textp->lang_key + lang_key_len + 1;
  193058. }
  193059. else
  193060. #endif
  193061. {
  193062. #ifdef PNG_iTXt_SUPPORTED
  193063. textp->lang=NULL;
  193064. textp->lang_key=NULL;
  193065. #endif
  193066. textp->text=textp->key + key_len + 1;
  193067. }
  193068. if(text_length)
  193069. png_memcpy(textp->text, text_ptr[i].text,
  193070. (png_size_t)(text_length));
  193071. *(textp->text+text_length) = '\0';
  193072. #ifdef PNG_iTXt_SUPPORTED
  193073. if(textp->compression > 0)
  193074. {
  193075. textp->text_length = 0;
  193076. textp->itxt_length = text_length;
  193077. }
  193078. else
  193079. #endif
  193080. {
  193081. textp->text_length = text_length;
  193082. #ifdef PNG_iTXt_SUPPORTED
  193083. textp->itxt_length = 0;
  193084. #endif
  193085. }
  193086. info_ptr->num_text++;
  193087. png_debug1(3, "transferred text chunk %d\n", info_ptr->num_text);
  193088. }
  193089. return(0);
  193090. }
  193091. #endif
  193092. #if defined(PNG_tIME_SUPPORTED)
  193093. void PNGAPI
  193094. png_set_tIME(png_structp png_ptr, png_infop info_ptr, png_timep mod_time)
  193095. {
  193096. png_debug1(1, "in %s storage function\n", "tIME");
  193097. if (png_ptr == NULL || info_ptr == NULL ||
  193098. (png_ptr->mode & PNG_WROTE_tIME))
  193099. return;
  193100. png_memcpy(&(info_ptr->mod_time), mod_time, png_sizeof (png_time));
  193101. info_ptr->valid |= PNG_INFO_tIME;
  193102. }
  193103. #endif
  193104. #if defined(PNG_tRNS_SUPPORTED)
  193105. void PNGAPI
  193106. png_set_tRNS(png_structp png_ptr, png_infop info_ptr,
  193107. png_bytep trans, int num_trans, png_color_16p trans_values)
  193108. {
  193109. png_debug1(1, "in %s storage function\n", "tRNS");
  193110. if (png_ptr == NULL || info_ptr == NULL)
  193111. return;
  193112. if (trans != NULL)
  193113. {
  193114. /*
  193115. * It may not actually be necessary to set png_ptr->trans here;
  193116. * we do it for backward compatibility with the way the png_handle_tRNS
  193117. * function used to do the allocation.
  193118. */
  193119. #ifdef PNG_FREE_ME_SUPPORTED
  193120. png_free_data(png_ptr, info_ptr, PNG_FREE_TRNS, 0);
  193121. #endif
  193122. /* Changed from num_trans to PNG_MAX_PALETTE_LENGTH in version 1.2.1 */
  193123. png_ptr->trans = info_ptr->trans = (png_bytep)png_malloc(png_ptr,
  193124. (png_uint_32)PNG_MAX_PALETTE_LENGTH);
  193125. if (num_trans <= PNG_MAX_PALETTE_LENGTH)
  193126. png_memcpy(info_ptr->trans, trans, (png_size_t)num_trans);
  193127. #ifdef PNG_FREE_ME_SUPPORTED
  193128. info_ptr->free_me |= PNG_FREE_TRNS;
  193129. #else
  193130. png_ptr->flags |= PNG_FLAG_FREE_TRNS;
  193131. #endif
  193132. }
  193133. if (trans_values != NULL)
  193134. {
  193135. png_memcpy(&(info_ptr->trans_values), trans_values,
  193136. png_sizeof(png_color_16));
  193137. if (num_trans == 0)
  193138. num_trans = 1;
  193139. }
  193140. info_ptr->num_trans = (png_uint_16)num_trans;
  193141. info_ptr->valid |= PNG_INFO_tRNS;
  193142. }
  193143. #endif
  193144. #if defined(PNG_sPLT_SUPPORTED)
  193145. void PNGAPI
  193146. png_set_sPLT(png_structp png_ptr,
  193147. png_infop info_ptr, png_sPLT_tp entries, int nentries)
  193148. {
  193149. png_sPLT_tp np;
  193150. int i;
  193151. if (png_ptr == NULL || info_ptr == NULL)
  193152. return;
  193153. np = (png_sPLT_tp)png_malloc_warn(png_ptr,
  193154. (info_ptr->splt_palettes_num + nentries) * png_sizeof(png_sPLT_t));
  193155. if (np == NULL)
  193156. {
  193157. png_warning(png_ptr, "No memory for sPLT palettes.");
  193158. return;
  193159. }
  193160. png_memcpy(np, info_ptr->splt_palettes,
  193161. info_ptr->splt_palettes_num * png_sizeof(png_sPLT_t));
  193162. png_free(png_ptr, info_ptr->splt_palettes);
  193163. info_ptr->splt_palettes=NULL;
  193164. for (i = 0; i < nentries; i++)
  193165. {
  193166. png_sPLT_tp to = np + info_ptr->splt_palettes_num + i;
  193167. png_sPLT_tp from = entries + i;
  193168. to->name = (png_charp)png_malloc_warn(png_ptr,
  193169. png_strlen(from->name) + 1);
  193170. if (to->name == NULL)
  193171. {
  193172. png_warning(png_ptr,
  193173. "Out of memory while processing sPLT chunk");
  193174. }
  193175. /* TODO: use png_malloc_warn */
  193176. png_strncpy(to->name, from->name, png_strlen(from->name)+1);
  193177. to->entries = (png_sPLT_entryp)png_malloc_warn(png_ptr,
  193178. from->nentries * png_sizeof(png_sPLT_entry));
  193179. /* TODO: use png_malloc_warn */
  193180. png_memcpy(to->entries, from->entries,
  193181. from->nentries * png_sizeof(png_sPLT_entry));
  193182. if (to->entries == NULL)
  193183. {
  193184. png_warning(png_ptr,
  193185. "Out of memory while processing sPLT chunk");
  193186. png_free(png_ptr,to->name);
  193187. to->name = NULL;
  193188. }
  193189. to->nentries = from->nentries;
  193190. to->depth = from->depth;
  193191. }
  193192. info_ptr->splt_palettes = np;
  193193. info_ptr->splt_palettes_num += nentries;
  193194. info_ptr->valid |= PNG_INFO_sPLT;
  193195. #ifdef PNG_FREE_ME_SUPPORTED
  193196. info_ptr->free_me |= PNG_FREE_SPLT;
  193197. #endif
  193198. }
  193199. #endif /* PNG_sPLT_SUPPORTED */
  193200. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  193201. void PNGAPI
  193202. png_set_unknown_chunks(png_structp png_ptr,
  193203. png_infop info_ptr, png_unknown_chunkp unknowns, int num_unknowns)
  193204. {
  193205. png_unknown_chunkp np;
  193206. int i;
  193207. if (png_ptr == NULL || info_ptr == NULL || num_unknowns == 0)
  193208. return;
  193209. np = (png_unknown_chunkp)png_malloc_warn(png_ptr,
  193210. (info_ptr->unknown_chunks_num + num_unknowns) *
  193211. png_sizeof(png_unknown_chunk));
  193212. if (np == NULL)
  193213. {
  193214. png_warning(png_ptr,
  193215. "Out of memory while processing unknown chunk.");
  193216. return;
  193217. }
  193218. png_memcpy(np, info_ptr->unknown_chunks,
  193219. info_ptr->unknown_chunks_num * png_sizeof(png_unknown_chunk));
  193220. png_free(png_ptr, info_ptr->unknown_chunks);
  193221. info_ptr->unknown_chunks=NULL;
  193222. for (i = 0; i < num_unknowns; i++)
  193223. {
  193224. png_unknown_chunkp to = np + info_ptr->unknown_chunks_num + i;
  193225. png_unknown_chunkp from = unknowns + i;
  193226. png_strncpy((png_charp)to->name, (png_charp)from->name, 5);
  193227. to->data = (png_bytep)png_malloc_warn(png_ptr, from->size);
  193228. if (to->data == NULL)
  193229. {
  193230. png_warning(png_ptr,
  193231. "Out of memory while processing unknown chunk.");
  193232. }
  193233. else
  193234. {
  193235. png_memcpy(to->data, from->data, from->size);
  193236. to->size = from->size;
  193237. /* note our location in the read or write sequence */
  193238. to->location = (png_byte)(png_ptr->mode & 0xff);
  193239. }
  193240. }
  193241. info_ptr->unknown_chunks = np;
  193242. info_ptr->unknown_chunks_num += num_unknowns;
  193243. #ifdef PNG_FREE_ME_SUPPORTED
  193244. info_ptr->free_me |= PNG_FREE_UNKN;
  193245. #endif
  193246. }
  193247. void PNGAPI
  193248. png_set_unknown_chunk_location(png_structp png_ptr, png_infop info_ptr,
  193249. int chunk, int location)
  193250. {
  193251. if(png_ptr != NULL && info_ptr != NULL && chunk >= 0 && chunk <
  193252. (int)info_ptr->unknown_chunks_num)
  193253. info_ptr->unknown_chunks[chunk].location = (png_byte)location;
  193254. }
  193255. #endif
  193256. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  193257. #if defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  193258. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  193259. void PNGAPI
  193260. png_permit_empty_plte (png_structp png_ptr, int empty_plte_permitted)
  193261. {
  193262. /* This function is deprecated in favor of png_permit_mng_features()
  193263. and will be removed from libpng-1.3.0 */
  193264. png_debug(1, "in png_permit_empty_plte, DEPRECATED.\n");
  193265. if (png_ptr == NULL)
  193266. return;
  193267. png_ptr->mng_features_permitted = (png_byte)
  193268. ((png_ptr->mng_features_permitted & (~(PNG_FLAG_MNG_EMPTY_PLTE))) |
  193269. ((empty_plte_permitted & PNG_FLAG_MNG_EMPTY_PLTE)));
  193270. }
  193271. #endif
  193272. #endif
  193273. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  193274. png_uint_32 PNGAPI
  193275. png_permit_mng_features (png_structp png_ptr, png_uint_32 mng_features)
  193276. {
  193277. png_debug(1, "in png_permit_mng_features\n");
  193278. if (png_ptr == NULL)
  193279. return (png_uint_32)0;
  193280. png_ptr->mng_features_permitted =
  193281. (png_byte)(mng_features & PNG_ALL_MNG_FEATURES);
  193282. return (png_uint_32)png_ptr->mng_features_permitted;
  193283. }
  193284. #endif
  193285. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  193286. void PNGAPI
  193287. png_set_keep_unknown_chunks(png_structp png_ptr, int keep, png_bytep
  193288. chunk_list, int num_chunks)
  193289. {
  193290. png_bytep new_list, p;
  193291. int i, old_num_chunks;
  193292. if (png_ptr == NULL)
  193293. return;
  193294. if (num_chunks == 0)
  193295. {
  193296. if(keep == PNG_HANDLE_CHUNK_ALWAYS || keep == PNG_HANDLE_CHUNK_IF_SAFE)
  193297. png_ptr->flags |= PNG_FLAG_KEEP_UNKNOWN_CHUNKS;
  193298. else
  193299. png_ptr->flags &= ~PNG_FLAG_KEEP_UNKNOWN_CHUNKS;
  193300. if(keep == PNG_HANDLE_CHUNK_ALWAYS)
  193301. png_ptr->flags |= PNG_FLAG_KEEP_UNSAFE_CHUNKS;
  193302. else
  193303. png_ptr->flags &= ~PNG_FLAG_KEEP_UNSAFE_CHUNKS;
  193304. return;
  193305. }
  193306. if (chunk_list == NULL)
  193307. return;
  193308. old_num_chunks=png_ptr->num_chunk_list;
  193309. new_list=(png_bytep)png_malloc(png_ptr,
  193310. (png_uint_32)(5*(num_chunks+old_num_chunks)));
  193311. if(png_ptr->chunk_list != NULL)
  193312. {
  193313. png_memcpy(new_list, png_ptr->chunk_list,
  193314. (png_size_t)(5*old_num_chunks));
  193315. png_free(png_ptr, png_ptr->chunk_list);
  193316. png_ptr->chunk_list=NULL;
  193317. }
  193318. png_memcpy(new_list+5*old_num_chunks, chunk_list,
  193319. (png_size_t)(5*num_chunks));
  193320. for (p=new_list+5*old_num_chunks+4, i=0; i<num_chunks; i++, p+=5)
  193321. *p=(png_byte)keep;
  193322. png_ptr->num_chunk_list=old_num_chunks+num_chunks;
  193323. png_ptr->chunk_list=new_list;
  193324. #ifdef PNG_FREE_ME_SUPPORTED
  193325. png_ptr->free_me |= PNG_FREE_LIST;
  193326. #endif
  193327. }
  193328. #endif
  193329. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  193330. void PNGAPI
  193331. png_set_read_user_chunk_fn(png_structp png_ptr, png_voidp user_chunk_ptr,
  193332. png_user_chunk_ptr read_user_chunk_fn)
  193333. {
  193334. png_debug(1, "in png_set_read_user_chunk_fn\n");
  193335. if (png_ptr == NULL)
  193336. return;
  193337. png_ptr->read_user_chunk_fn = read_user_chunk_fn;
  193338. png_ptr->user_chunk_ptr = user_chunk_ptr;
  193339. }
  193340. #endif
  193341. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  193342. void PNGAPI
  193343. png_set_rows(png_structp png_ptr, png_infop info_ptr, png_bytepp row_pointers)
  193344. {
  193345. png_debug1(1, "in %s storage function\n", "rows");
  193346. if (png_ptr == NULL || info_ptr == NULL)
  193347. return;
  193348. if(info_ptr->row_pointers && (info_ptr->row_pointers != row_pointers))
  193349. png_free_data(png_ptr, info_ptr, PNG_FREE_ROWS, 0);
  193350. info_ptr->row_pointers = row_pointers;
  193351. if(row_pointers)
  193352. info_ptr->valid |= PNG_INFO_IDAT;
  193353. }
  193354. #endif
  193355. #ifdef PNG_WRITE_SUPPORTED
  193356. void PNGAPI
  193357. png_set_compression_buffer_size(png_structp png_ptr, png_uint_32 size)
  193358. {
  193359. if (png_ptr == NULL)
  193360. return;
  193361. if(png_ptr->zbuf)
  193362. png_free(png_ptr, png_ptr->zbuf);
  193363. png_ptr->zbuf_size = (png_size_t)size;
  193364. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr, size);
  193365. png_ptr->zstream.next_out = png_ptr->zbuf;
  193366. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  193367. }
  193368. #endif
  193369. void PNGAPI
  193370. png_set_invalid(png_structp png_ptr, png_infop info_ptr, int mask)
  193371. {
  193372. if (png_ptr && info_ptr)
  193373. info_ptr->valid &= ~(mask);
  193374. }
  193375. #ifndef PNG_1_0_X
  193376. #ifdef PNG_ASSEMBLER_CODE_SUPPORTED
  193377. /* function was added to libpng 1.2.0 and should always exist by default */
  193378. void PNGAPI
  193379. png_set_asm_flags (png_structp png_ptr, png_uint_32 asm_flags)
  193380. {
  193381. /* Obsolete as of libpng-1.2.20 and will be removed from libpng-1.4.0 */
  193382. if (png_ptr != NULL)
  193383. png_ptr->asm_flags = 0;
  193384. }
  193385. /* this function was added to libpng 1.2.0 */
  193386. void PNGAPI
  193387. png_set_mmx_thresholds (png_structp png_ptr,
  193388. png_byte mmx_bitdepth_threshold,
  193389. png_uint_32 mmx_rowbytes_threshold)
  193390. {
  193391. /* Obsolete as of libpng-1.2.20 and will be removed from libpng-1.4.0 */
  193392. if (png_ptr == NULL)
  193393. return;
  193394. }
  193395. #endif /* ?PNG_ASSEMBLER_CODE_SUPPORTED */
  193396. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  193397. /* this function was added to libpng 1.2.6 */
  193398. void PNGAPI
  193399. png_set_user_limits (png_structp png_ptr, png_uint_32 user_width_max,
  193400. png_uint_32 user_height_max)
  193401. {
  193402. /* Images with dimensions larger than these limits will be
  193403. * rejected by png_set_IHDR(). To accept any PNG datastream
  193404. * regardless of dimensions, set both limits to 0x7ffffffL.
  193405. */
  193406. if(png_ptr == NULL) return;
  193407. png_ptr->user_width_max = user_width_max;
  193408. png_ptr->user_height_max = user_height_max;
  193409. }
  193410. #endif /* ?PNG_SET_USER_LIMITS_SUPPORTED */
  193411. #endif /* ?PNG_1_0_X */
  193412. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  193413. /********* End of inlined file: pngset.c *********/
  193414. /********* Start of inlined file: pngtrans.c *********/
  193415. /* pngtrans.c - transforms the data in a row (used by both readers and writers)
  193416. *
  193417. * Last changed in libpng 1.2.17 May 15, 2007
  193418. * For conditions of distribution and use, see copyright notice in png.h
  193419. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  193420. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  193421. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  193422. */
  193423. #define PNG_INTERNAL
  193424. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  193425. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  193426. /* turn on BGR-to-RGB mapping */
  193427. void PNGAPI
  193428. png_set_bgr(png_structp png_ptr)
  193429. {
  193430. png_debug(1, "in png_set_bgr\n");
  193431. if(png_ptr == NULL) return;
  193432. png_ptr->transformations |= PNG_BGR;
  193433. }
  193434. #endif
  193435. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  193436. /* turn on 16 bit byte swapping */
  193437. void PNGAPI
  193438. png_set_swap(png_structp png_ptr)
  193439. {
  193440. png_debug(1, "in png_set_swap\n");
  193441. if(png_ptr == NULL) return;
  193442. if (png_ptr->bit_depth == 16)
  193443. png_ptr->transformations |= PNG_SWAP_BYTES;
  193444. }
  193445. #endif
  193446. #if defined(PNG_READ_PACK_SUPPORTED) || defined(PNG_WRITE_PACK_SUPPORTED)
  193447. /* turn on pixel packing */
  193448. void PNGAPI
  193449. png_set_packing(png_structp png_ptr)
  193450. {
  193451. png_debug(1, "in png_set_packing\n");
  193452. if(png_ptr == NULL) return;
  193453. if (png_ptr->bit_depth < 8)
  193454. {
  193455. png_ptr->transformations |= PNG_PACK;
  193456. png_ptr->usr_bit_depth = 8;
  193457. }
  193458. }
  193459. #endif
  193460. #if defined(PNG_READ_PACKSWAP_SUPPORTED)||defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  193461. /* turn on packed pixel swapping */
  193462. void PNGAPI
  193463. png_set_packswap(png_structp png_ptr)
  193464. {
  193465. png_debug(1, "in png_set_packswap\n");
  193466. if(png_ptr == NULL) return;
  193467. if (png_ptr->bit_depth < 8)
  193468. png_ptr->transformations |= PNG_PACKSWAP;
  193469. }
  193470. #endif
  193471. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  193472. void PNGAPI
  193473. png_set_shift(png_structp png_ptr, png_color_8p true_bits)
  193474. {
  193475. png_debug(1, "in png_set_shift\n");
  193476. if(png_ptr == NULL) return;
  193477. png_ptr->transformations |= PNG_SHIFT;
  193478. png_ptr->shift = *true_bits;
  193479. }
  193480. #endif
  193481. #if defined(PNG_READ_INTERLACING_SUPPORTED) || \
  193482. defined(PNG_WRITE_INTERLACING_SUPPORTED)
  193483. int PNGAPI
  193484. png_set_interlace_handling(png_structp png_ptr)
  193485. {
  193486. png_debug(1, "in png_set_interlace handling\n");
  193487. if (png_ptr && png_ptr->interlaced)
  193488. {
  193489. png_ptr->transformations |= PNG_INTERLACE;
  193490. return (7);
  193491. }
  193492. return (1);
  193493. }
  193494. #endif
  193495. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  193496. /* Add a filler byte on read, or remove a filler or alpha byte on write.
  193497. * The filler type has changed in v0.95 to allow future 2-byte fillers
  193498. * for 48-bit input data, as well as to avoid problems with some compilers
  193499. * that don't like bytes as parameters.
  193500. */
  193501. void PNGAPI
  193502. png_set_filler(png_structp png_ptr, png_uint_32 filler, int filler_loc)
  193503. {
  193504. png_debug(1, "in png_set_filler\n");
  193505. if(png_ptr == NULL) return;
  193506. png_ptr->transformations |= PNG_FILLER;
  193507. png_ptr->filler = (png_byte)filler;
  193508. if (filler_loc == PNG_FILLER_AFTER)
  193509. png_ptr->flags |= PNG_FLAG_FILLER_AFTER;
  193510. else
  193511. png_ptr->flags &= ~PNG_FLAG_FILLER_AFTER;
  193512. /* This should probably go in the "do_read_filler" routine.
  193513. * I attempted to do that in libpng-1.0.1a but that caused problems
  193514. * so I restored it in libpng-1.0.2a
  193515. */
  193516. if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  193517. {
  193518. png_ptr->usr_channels = 4;
  193519. }
  193520. /* Also I added this in libpng-1.0.2a (what happens when we expand
  193521. * a less-than-8-bit grayscale to GA? */
  193522. if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY && png_ptr->bit_depth >= 8)
  193523. {
  193524. png_ptr->usr_channels = 2;
  193525. }
  193526. }
  193527. #if !defined(PNG_1_0_X)
  193528. /* Added to libpng-1.2.7 */
  193529. void PNGAPI
  193530. png_set_add_alpha(png_structp png_ptr, png_uint_32 filler, int filler_loc)
  193531. {
  193532. png_debug(1, "in png_set_add_alpha\n");
  193533. if(png_ptr == NULL) return;
  193534. png_set_filler(png_ptr, filler, filler_loc);
  193535. png_ptr->transformations |= PNG_ADD_ALPHA;
  193536. }
  193537. #endif
  193538. #endif
  193539. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED) || \
  193540. defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  193541. void PNGAPI
  193542. png_set_swap_alpha(png_structp png_ptr)
  193543. {
  193544. png_debug(1, "in png_set_swap_alpha\n");
  193545. if(png_ptr == NULL) return;
  193546. png_ptr->transformations |= PNG_SWAP_ALPHA;
  193547. }
  193548. #endif
  193549. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED) || \
  193550. defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  193551. void PNGAPI
  193552. png_set_invert_alpha(png_structp png_ptr)
  193553. {
  193554. png_debug(1, "in png_set_invert_alpha\n");
  193555. if(png_ptr == NULL) return;
  193556. png_ptr->transformations |= PNG_INVERT_ALPHA;
  193557. }
  193558. #endif
  193559. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  193560. void PNGAPI
  193561. png_set_invert_mono(png_structp png_ptr)
  193562. {
  193563. png_debug(1, "in png_set_invert_mono\n");
  193564. if(png_ptr == NULL) return;
  193565. png_ptr->transformations |= PNG_INVERT_MONO;
  193566. }
  193567. /* invert monochrome grayscale data */
  193568. void /* PRIVATE */
  193569. png_do_invert(png_row_infop row_info, png_bytep row)
  193570. {
  193571. png_debug(1, "in png_do_invert\n");
  193572. /* This test removed from libpng version 1.0.13 and 1.2.0:
  193573. * if (row_info->bit_depth == 1 &&
  193574. */
  193575. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193576. if (row == NULL || row_info == NULL)
  193577. return;
  193578. #endif
  193579. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  193580. {
  193581. png_bytep rp = row;
  193582. png_uint_32 i;
  193583. png_uint_32 istop = row_info->rowbytes;
  193584. for (i = 0; i < istop; i++)
  193585. {
  193586. *rp = (png_byte)(~(*rp));
  193587. rp++;
  193588. }
  193589. }
  193590. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  193591. row_info->bit_depth == 8)
  193592. {
  193593. png_bytep rp = row;
  193594. png_uint_32 i;
  193595. png_uint_32 istop = row_info->rowbytes;
  193596. for (i = 0; i < istop; i+=2)
  193597. {
  193598. *rp = (png_byte)(~(*rp));
  193599. rp+=2;
  193600. }
  193601. }
  193602. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  193603. row_info->bit_depth == 16)
  193604. {
  193605. png_bytep rp = row;
  193606. png_uint_32 i;
  193607. png_uint_32 istop = row_info->rowbytes;
  193608. for (i = 0; i < istop; i+=4)
  193609. {
  193610. *rp = (png_byte)(~(*rp));
  193611. *(rp+1) = (png_byte)(~(*(rp+1)));
  193612. rp+=4;
  193613. }
  193614. }
  193615. }
  193616. #endif
  193617. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  193618. /* swaps byte order on 16 bit depth images */
  193619. void /* PRIVATE */
  193620. png_do_swap(png_row_infop row_info, png_bytep row)
  193621. {
  193622. png_debug(1, "in png_do_swap\n");
  193623. if (
  193624. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193625. row != NULL && row_info != NULL &&
  193626. #endif
  193627. row_info->bit_depth == 16)
  193628. {
  193629. png_bytep rp = row;
  193630. png_uint_32 i;
  193631. png_uint_32 istop= row_info->width * row_info->channels;
  193632. for (i = 0; i < istop; i++, rp += 2)
  193633. {
  193634. png_byte t = *rp;
  193635. *rp = *(rp + 1);
  193636. *(rp + 1) = t;
  193637. }
  193638. }
  193639. }
  193640. #endif
  193641. #if defined(PNG_READ_PACKSWAP_SUPPORTED)||defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  193642. static PNG_CONST png_byte onebppswaptable[256] = {
  193643. 0x00, 0x80, 0x40, 0xC0, 0x20, 0xA0, 0x60, 0xE0,
  193644. 0x10, 0x90, 0x50, 0xD0, 0x30, 0xB0, 0x70, 0xF0,
  193645. 0x08, 0x88, 0x48, 0xC8, 0x28, 0xA8, 0x68, 0xE8,
  193646. 0x18, 0x98, 0x58, 0xD8, 0x38, 0xB8, 0x78, 0xF8,
  193647. 0x04, 0x84, 0x44, 0xC4, 0x24, 0xA4, 0x64, 0xE4,
  193648. 0x14, 0x94, 0x54, 0xD4, 0x34, 0xB4, 0x74, 0xF4,
  193649. 0x0C, 0x8C, 0x4C, 0xCC, 0x2C, 0xAC, 0x6C, 0xEC,
  193650. 0x1C, 0x9C, 0x5C, 0xDC, 0x3C, 0xBC, 0x7C, 0xFC,
  193651. 0x02, 0x82, 0x42, 0xC2, 0x22, 0xA2, 0x62, 0xE2,
  193652. 0x12, 0x92, 0x52, 0xD2, 0x32, 0xB2, 0x72, 0xF2,
  193653. 0x0A, 0x8A, 0x4A, 0xCA, 0x2A, 0xAA, 0x6A, 0xEA,
  193654. 0x1A, 0x9A, 0x5A, 0xDA, 0x3A, 0xBA, 0x7A, 0xFA,
  193655. 0x06, 0x86, 0x46, 0xC6, 0x26, 0xA6, 0x66, 0xE6,
  193656. 0x16, 0x96, 0x56, 0xD6, 0x36, 0xB6, 0x76, 0xF6,
  193657. 0x0E, 0x8E, 0x4E, 0xCE, 0x2E, 0xAE, 0x6E, 0xEE,
  193658. 0x1E, 0x9E, 0x5E, 0xDE, 0x3E, 0xBE, 0x7E, 0xFE,
  193659. 0x01, 0x81, 0x41, 0xC1, 0x21, 0xA1, 0x61, 0xE1,
  193660. 0x11, 0x91, 0x51, 0xD1, 0x31, 0xB1, 0x71, 0xF1,
  193661. 0x09, 0x89, 0x49, 0xC9, 0x29, 0xA9, 0x69, 0xE9,
  193662. 0x19, 0x99, 0x59, 0xD9, 0x39, 0xB9, 0x79, 0xF9,
  193663. 0x05, 0x85, 0x45, 0xC5, 0x25, 0xA5, 0x65, 0xE5,
  193664. 0x15, 0x95, 0x55, 0xD5, 0x35, 0xB5, 0x75, 0xF5,
  193665. 0x0D, 0x8D, 0x4D, 0xCD, 0x2D, 0xAD, 0x6D, 0xED,
  193666. 0x1D, 0x9D, 0x5D, 0xDD, 0x3D, 0xBD, 0x7D, 0xFD,
  193667. 0x03, 0x83, 0x43, 0xC3, 0x23, 0xA3, 0x63, 0xE3,
  193668. 0x13, 0x93, 0x53, 0xD3, 0x33, 0xB3, 0x73, 0xF3,
  193669. 0x0B, 0x8B, 0x4B, 0xCB, 0x2B, 0xAB, 0x6B, 0xEB,
  193670. 0x1B, 0x9B, 0x5B, 0xDB, 0x3B, 0xBB, 0x7B, 0xFB,
  193671. 0x07, 0x87, 0x47, 0xC7, 0x27, 0xA7, 0x67, 0xE7,
  193672. 0x17, 0x97, 0x57, 0xD7, 0x37, 0xB7, 0x77, 0xF7,
  193673. 0x0F, 0x8F, 0x4F, 0xCF, 0x2F, 0xAF, 0x6F, 0xEF,
  193674. 0x1F, 0x9F, 0x5F, 0xDF, 0x3F, 0xBF, 0x7F, 0xFF
  193675. };
  193676. static PNG_CONST png_byte twobppswaptable[256] = {
  193677. 0x00, 0x40, 0x80, 0xC0, 0x10, 0x50, 0x90, 0xD0,
  193678. 0x20, 0x60, 0xA0, 0xE0, 0x30, 0x70, 0xB0, 0xF0,
  193679. 0x04, 0x44, 0x84, 0xC4, 0x14, 0x54, 0x94, 0xD4,
  193680. 0x24, 0x64, 0xA4, 0xE4, 0x34, 0x74, 0xB4, 0xF4,
  193681. 0x08, 0x48, 0x88, 0xC8, 0x18, 0x58, 0x98, 0xD8,
  193682. 0x28, 0x68, 0xA8, 0xE8, 0x38, 0x78, 0xB8, 0xF8,
  193683. 0x0C, 0x4C, 0x8C, 0xCC, 0x1C, 0x5C, 0x9C, 0xDC,
  193684. 0x2C, 0x6C, 0xAC, 0xEC, 0x3C, 0x7C, 0xBC, 0xFC,
  193685. 0x01, 0x41, 0x81, 0xC1, 0x11, 0x51, 0x91, 0xD1,
  193686. 0x21, 0x61, 0xA1, 0xE1, 0x31, 0x71, 0xB1, 0xF1,
  193687. 0x05, 0x45, 0x85, 0xC5, 0x15, 0x55, 0x95, 0xD5,
  193688. 0x25, 0x65, 0xA5, 0xE5, 0x35, 0x75, 0xB5, 0xF5,
  193689. 0x09, 0x49, 0x89, 0xC9, 0x19, 0x59, 0x99, 0xD9,
  193690. 0x29, 0x69, 0xA9, 0xE9, 0x39, 0x79, 0xB9, 0xF9,
  193691. 0x0D, 0x4D, 0x8D, 0xCD, 0x1D, 0x5D, 0x9D, 0xDD,
  193692. 0x2D, 0x6D, 0xAD, 0xED, 0x3D, 0x7D, 0xBD, 0xFD,
  193693. 0x02, 0x42, 0x82, 0xC2, 0x12, 0x52, 0x92, 0xD2,
  193694. 0x22, 0x62, 0xA2, 0xE2, 0x32, 0x72, 0xB2, 0xF2,
  193695. 0x06, 0x46, 0x86, 0xC6, 0x16, 0x56, 0x96, 0xD6,
  193696. 0x26, 0x66, 0xA6, 0xE6, 0x36, 0x76, 0xB6, 0xF6,
  193697. 0x0A, 0x4A, 0x8A, 0xCA, 0x1A, 0x5A, 0x9A, 0xDA,
  193698. 0x2A, 0x6A, 0xAA, 0xEA, 0x3A, 0x7A, 0xBA, 0xFA,
  193699. 0x0E, 0x4E, 0x8E, 0xCE, 0x1E, 0x5E, 0x9E, 0xDE,
  193700. 0x2E, 0x6E, 0xAE, 0xEE, 0x3E, 0x7E, 0xBE, 0xFE,
  193701. 0x03, 0x43, 0x83, 0xC3, 0x13, 0x53, 0x93, 0xD3,
  193702. 0x23, 0x63, 0xA3, 0xE3, 0x33, 0x73, 0xB3, 0xF3,
  193703. 0x07, 0x47, 0x87, 0xC7, 0x17, 0x57, 0x97, 0xD7,
  193704. 0x27, 0x67, 0xA7, 0xE7, 0x37, 0x77, 0xB7, 0xF7,
  193705. 0x0B, 0x4B, 0x8B, 0xCB, 0x1B, 0x5B, 0x9B, 0xDB,
  193706. 0x2B, 0x6B, 0xAB, 0xEB, 0x3B, 0x7B, 0xBB, 0xFB,
  193707. 0x0F, 0x4F, 0x8F, 0xCF, 0x1F, 0x5F, 0x9F, 0xDF,
  193708. 0x2F, 0x6F, 0xAF, 0xEF, 0x3F, 0x7F, 0xBF, 0xFF
  193709. };
  193710. static PNG_CONST png_byte fourbppswaptable[256] = {
  193711. 0x00, 0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70,
  193712. 0x80, 0x90, 0xA0, 0xB0, 0xC0, 0xD0, 0xE0, 0xF0,
  193713. 0x01, 0x11, 0x21, 0x31, 0x41, 0x51, 0x61, 0x71,
  193714. 0x81, 0x91, 0xA1, 0xB1, 0xC1, 0xD1, 0xE1, 0xF1,
  193715. 0x02, 0x12, 0x22, 0x32, 0x42, 0x52, 0x62, 0x72,
  193716. 0x82, 0x92, 0xA2, 0xB2, 0xC2, 0xD2, 0xE2, 0xF2,
  193717. 0x03, 0x13, 0x23, 0x33, 0x43, 0x53, 0x63, 0x73,
  193718. 0x83, 0x93, 0xA3, 0xB3, 0xC3, 0xD3, 0xE3, 0xF3,
  193719. 0x04, 0x14, 0x24, 0x34, 0x44, 0x54, 0x64, 0x74,
  193720. 0x84, 0x94, 0xA4, 0xB4, 0xC4, 0xD4, 0xE4, 0xF4,
  193721. 0x05, 0x15, 0x25, 0x35, 0x45, 0x55, 0x65, 0x75,
  193722. 0x85, 0x95, 0xA5, 0xB5, 0xC5, 0xD5, 0xE5, 0xF5,
  193723. 0x06, 0x16, 0x26, 0x36, 0x46, 0x56, 0x66, 0x76,
  193724. 0x86, 0x96, 0xA6, 0xB6, 0xC6, 0xD6, 0xE6, 0xF6,
  193725. 0x07, 0x17, 0x27, 0x37, 0x47, 0x57, 0x67, 0x77,
  193726. 0x87, 0x97, 0xA7, 0xB7, 0xC7, 0xD7, 0xE7, 0xF7,
  193727. 0x08, 0x18, 0x28, 0x38, 0x48, 0x58, 0x68, 0x78,
  193728. 0x88, 0x98, 0xA8, 0xB8, 0xC8, 0xD8, 0xE8, 0xF8,
  193729. 0x09, 0x19, 0x29, 0x39, 0x49, 0x59, 0x69, 0x79,
  193730. 0x89, 0x99, 0xA9, 0xB9, 0xC9, 0xD9, 0xE9, 0xF9,
  193731. 0x0A, 0x1A, 0x2A, 0x3A, 0x4A, 0x5A, 0x6A, 0x7A,
  193732. 0x8A, 0x9A, 0xAA, 0xBA, 0xCA, 0xDA, 0xEA, 0xFA,
  193733. 0x0B, 0x1B, 0x2B, 0x3B, 0x4B, 0x5B, 0x6B, 0x7B,
  193734. 0x8B, 0x9B, 0xAB, 0xBB, 0xCB, 0xDB, 0xEB, 0xFB,
  193735. 0x0C, 0x1C, 0x2C, 0x3C, 0x4C, 0x5C, 0x6C, 0x7C,
  193736. 0x8C, 0x9C, 0xAC, 0xBC, 0xCC, 0xDC, 0xEC, 0xFC,
  193737. 0x0D, 0x1D, 0x2D, 0x3D, 0x4D, 0x5D, 0x6D, 0x7D,
  193738. 0x8D, 0x9D, 0xAD, 0xBD, 0xCD, 0xDD, 0xED, 0xFD,
  193739. 0x0E, 0x1E, 0x2E, 0x3E, 0x4E, 0x5E, 0x6E, 0x7E,
  193740. 0x8E, 0x9E, 0xAE, 0xBE, 0xCE, 0xDE, 0xEE, 0xFE,
  193741. 0x0F, 0x1F, 0x2F, 0x3F, 0x4F, 0x5F, 0x6F, 0x7F,
  193742. 0x8F, 0x9F, 0xAF, 0xBF, 0xCF, 0xDF, 0xEF, 0xFF
  193743. };
  193744. /* swaps pixel packing order within bytes */
  193745. void /* PRIVATE */
  193746. png_do_packswap(png_row_infop row_info, png_bytep row)
  193747. {
  193748. png_debug(1, "in png_do_packswap\n");
  193749. if (
  193750. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193751. row != NULL && row_info != NULL &&
  193752. #endif
  193753. row_info->bit_depth < 8)
  193754. {
  193755. png_bytep rp, end, table;
  193756. end = row + row_info->rowbytes;
  193757. if (row_info->bit_depth == 1)
  193758. table = (png_bytep)onebppswaptable;
  193759. else if (row_info->bit_depth == 2)
  193760. table = (png_bytep)twobppswaptable;
  193761. else if (row_info->bit_depth == 4)
  193762. table = (png_bytep)fourbppswaptable;
  193763. else
  193764. return;
  193765. for (rp = row; rp < end; rp++)
  193766. *rp = table[*rp];
  193767. }
  193768. }
  193769. #endif /* PNG_READ_PACKSWAP_SUPPORTED or PNG_WRITE_PACKSWAP_SUPPORTED */
  193770. #if defined(PNG_WRITE_FILLER_SUPPORTED) || \
  193771. defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  193772. /* remove filler or alpha byte(s) */
  193773. void /* PRIVATE */
  193774. png_do_strip_filler(png_row_infop row_info, png_bytep row, png_uint_32 flags)
  193775. {
  193776. png_debug(1, "in png_do_strip_filler\n");
  193777. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193778. if (row != NULL && row_info != NULL)
  193779. #endif
  193780. {
  193781. png_bytep sp=row;
  193782. png_bytep dp=row;
  193783. png_uint_32 row_width=row_info->width;
  193784. png_uint_32 i;
  193785. if ((row_info->color_type == PNG_COLOR_TYPE_RGB ||
  193786. (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA &&
  193787. (flags & PNG_FLAG_STRIP_ALPHA))) &&
  193788. row_info->channels == 4)
  193789. {
  193790. if (row_info->bit_depth == 8)
  193791. {
  193792. /* This converts from RGBX or RGBA to RGB */
  193793. if (flags & PNG_FLAG_FILLER_AFTER)
  193794. {
  193795. dp+=3; sp+=4;
  193796. for (i = 1; i < row_width; i++)
  193797. {
  193798. *dp++ = *sp++;
  193799. *dp++ = *sp++;
  193800. *dp++ = *sp++;
  193801. sp++;
  193802. }
  193803. }
  193804. /* This converts from XRGB or ARGB to RGB */
  193805. else
  193806. {
  193807. for (i = 0; i < row_width; i++)
  193808. {
  193809. sp++;
  193810. *dp++ = *sp++;
  193811. *dp++ = *sp++;
  193812. *dp++ = *sp++;
  193813. }
  193814. }
  193815. row_info->pixel_depth = 24;
  193816. row_info->rowbytes = row_width * 3;
  193817. }
  193818. else /* if (row_info->bit_depth == 16) */
  193819. {
  193820. if (flags & PNG_FLAG_FILLER_AFTER)
  193821. {
  193822. /* This converts from RRGGBBXX or RRGGBBAA to RRGGBB */
  193823. sp += 8; dp += 6;
  193824. for (i = 1; i < row_width; i++)
  193825. {
  193826. /* This could be (although png_memcpy is probably slower):
  193827. png_memcpy(dp, sp, 6);
  193828. sp += 8;
  193829. dp += 6;
  193830. */
  193831. *dp++ = *sp++;
  193832. *dp++ = *sp++;
  193833. *dp++ = *sp++;
  193834. *dp++ = *sp++;
  193835. *dp++ = *sp++;
  193836. *dp++ = *sp++;
  193837. sp += 2;
  193838. }
  193839. }
  193840. else
  193841. {
  193842. /* This converts from XXRRGGBB or AARRGGBB to RRGGBB */
  193843. for (i = 0; i < row_width; i++)
  193844. {
  193845. /* This could be (although png_memcpy is probably slower):
  193846. png_memcpy(dp, sp, 6);
  193847. sp += 8;
  193848. dp += 6;
  193849. */
  193850. sp+=2;
  193851. *dp++ = *sp++;
  193852. *dp++ = *sp++;
  193853. *dp++ = *sp++;
  193854. *dp++ = *sp++;
  193855. *dp++ = *sp++;
  193856. *dp++ = *sp++;
  193857. }
  193858. }
  193859. row_info->pixel_depth = 48;
  193860. row_info->rowbytes = row_width * 6;
  193861. }
  193862. row_info->channels = 3;
  193863. }
  193864. else if ((row_info->color_type == PNG_COLOR_TYPE_GRAY ||
  193865. (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  193866. (flags & PNG_FLAG_STRIP_ALPHA))) &&
  193867. row_info->channels == 2)
  193868. {
  193869. if (row_info->bit_depth == 8)
  193870. {
  193871. /* This converts from GX or GA to G */
  193872. if (flags & PNG_FLAG_FILLER_AFTER)
  193873. {
  193874. for (i = 0; i < row_width; i++)
  193875. {
  193876. *dp++ = *sp++;
  193877. sp++;
  193878. }
  193879. }
  193880. /* This converts from XG or AG to G */
  193881. else
  193882. {
  193883. for (i = 0; i < row_width; i++)
  193884. {
  193885. sp++;
  193886. *dp++ = *sp++;
  193887. }
  193888. }
  193889. row_info->pixel_depth = 8;
  193890. row_info->rowbytes = row_width;
  193891. }
  193892. else /* if (row_info->bit_depth == 16) */
  193893. {
  193894. if (flags & PNG_FLAG_FILLER_AFTER)
  193895. {
  193896. /* This converts from GGXX or GGAA to GG */
  193897. sp += 4; dp += 2;
  193898. for (i = 1; i < row_width; i++)
  193899. {
  193900. *dp++ = *sp++;
  193901. *dp++ = *sp++;
  193902. sp += 2;
  193903. }
  193904. }
  193905. else
  193906. {
  193907. /* This converts from XXGG or AAGG to GG */
  193908. for (i = 0; i < row_width; i++)
  193909. {
  193910. sp += 2;
  193911. *dp++ = *sp++;
  193912. *dp++ = *sp++;
  193913. }
  193914. }
  193915. row_info->pixel_depth = 16;
  193916. row_info->rowbytes = row_width * 2;
  193917. }
  193918. row_info->channels = 1;
  193919. }
  193920. if (flags & PNG_FLAG_STRIP_ALPHA)
  193921. row_info->color_type &= ~PNG_COLOR_MASK_ALPHA;
  193922. }
  193923. }
  193924. #endif
  193925. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  193926. /* swaps red and blue bytes within a pixel */
  193927. void /* PRIVATE */
  193928. png_do_bgr(png_row_infop row_info, png_bytep row)
  193929. {
  193930. png_debug(1, "in png_do_bgr\n");
  193931. if (
  193932. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193933. row != NULL && row_info != NULL &&
  193934. #endif
  193935. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  193936. {
  193937. png_uint_32 row_width = row_info->width;
  193938. if (row_info->bit_depth == 8)
  193939. {
  193940. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  193941. {
  193942. png_bytep rp;
  193943. png_uint_32 i;
  193944. for (i = 0, rp = row; i < row_width; i++, rp += 3)
  193945. {
  193946. png_byte save = *rp;
  193947. *rp = *(rp + 2);
  193948. *(rp + 2) = save;
  193949. }
  193950. }
  193951. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  193952. {
  193953. png_bytep rp;
  193954. png_uint_32 i;
  193955. for (i = 0, rp = row; i < row_width; i++, rp += 4)
  193956. {
  193957. png_byte save = *rp;
  193958. *rp = *(rp + 2);
  193959. *(rp + 2) = save;
  193960. }
  193961. }
  193962. }
  193963. else if (row_info->bit_depth == 16)
  193964. {
  193965. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  193966. {
  193967. png_bytep rp;
  193968. png_uint_32 i;
  193969. for (i = 0, rp = row; i < row_width; i++, rp += 6)
  193970. {
  193971. png_byte save = *rp;
  193972. *rp = *(rp + 4);
  193973. *(rp + 4) = save;
  193974. save = *(rp + 1);
  193975. *(rp + 1) = *(rp + 5);
  193976. *(rp + 5) = save;
  193977. }
  193978. }
  193979. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  193980. {
  193981. png_bytep rp;
  193982. png_uint_32 i;
  193983. for (i = 0, rp = row; i < row_width; i++, rp += 8)
  193984. {
  193985. png_byte save = *rp;
  193986. *rp = *(rp + 4);
  193987. *(rp + 4) = save;
  193988. save = *(rp + 1);
  193989. *(rp + 1) = *(rp + 5);
  193990. *(rp + 5) = save;
  193991. }
  193992. }
  193993. }
  193994. }
  193995. }
  193996. #endif /* PNG_READ_BGR_SUPPORTED or PNG_WRITE_BGR_SUPPORTED */
  193997. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  193998. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  193999. defined(PNG_LEGACY_SUPPORTED)
  194000. void PNGAPI
  194001. png_set_user_transform_info(png_structp png_ptr, png_voidp
  194002. user_transform_ptr, int user_transform_depth, int user_transform_channels)
  194003. {
  194004. png_debug(1, "in png_set_user_transform_info\n");
  194005. if(png_ptr == NULL) return;
  194006. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  194007. png_ptr->user_transform_ptr = user_transform_ptr;
  194008. png_ptr->user_transform_depth = (png_byte)user_transform_depth;
  194009. png_ptr->user_transform_channels = (png_byte)user_transform_channels;
  194010. #else
  194011. if(user_transform_ptr || user_transform_depth || user_transform_channels)
  194012. png_warning(png_ptr,
  194013. "This version of libpng does not support user transform info");
  194014. #endif
  194015. }
  194016. #endif
  194017. /* This function returns a pointer to the user_transform_ptr associated with
  194018. * the user transform functions. The application should free any memory
  194019. * associated with this pointer before png_write_destroy and png_read_destroy
  194020. * are called.
  194021. */
  194022. png_voidp PNGAPI
  194023. png_get_user_transform_ptr(png_structp png_ptr)
  194024. {
  194025. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  194026. if (png_ptr == NULL) return (NULL);
  194027. return ((png_voidp)png_ptr->user_transform_ptr);
  194028. #else
  194029. return (NULL);
  194030. #endif
  194031. }
  194032. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  194033. /********* End of inlined file: pngtrans.c *********/
  194034. /********* Start of inlined file: pngwio.c *********/
  194035. /* pngwio.c - functions for data output
  194036. *
  194037. * Last changed in libpng 1.2.13 November 13, 2006
  194038. * For conditions of distribution and use, see copyright notice in png.h
  194039. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  194040. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  194041. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  194042. *
  194043. * This file provides a location for all output. Users who need
  194044. * special handling are expected to write functions that have the same
  194045. * arguments as these and perform similar functions, but that possibly
  194046. * use different output methods. Note that you shouldn't change these
  194047. * functions, but rather write replacement functions and then change
  194048. * them at run time with png_set_write_fn(...).
  194049. */
  194050. #define PNG_INTERNAL
  194051. #ifdef PNG_WRITE_SUPPORTED
  194052. /* Write the data to whatever output you are using. The default routine
  194053. writes to a file pointer. Note that this routine sometimes gets called
  194054. with very small lengths, so you should implement some kind of simple
  194055. buffering if you are using unbuffered writes. This should never be asked
  194056. to write more than 64K on a 16 bit machine. */
  194057. void /* PRIVATE */
  194058. png_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  194059. {
  194060. if (png_ptr->write_data_fn != NULL )
  194061. (*(png_ptr->write_data_fn))(png_ptr, data, length);
  194062. else
  194063. png_error(png_ptr, "Call to NULL write function");
  194064. }
  194065. #if !defined(PNG_NO_STDIO)
  194066. /* This is the function that does the actual writing of data. If you are
  194067. not writing to a standard C stream, you should create a replacement
  194068. write_data function and use it at run time with png_set_write_fn(), rather
  194069. than changing the library. */
  194070. #ifndef USE_FAR_KEYWORD
  194071. void PNGAPI
  194072. png_default_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  194073. {
  194074. png_uint_32 check;
  194075. if(png_ptr == NULL) return;
  194076. #if defined(_WIN32_WCE)
  194077. if ( !WriteFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  194078. check = 0;
  194079. #else
  194080. check = fwrite(data, 1, length, (png_FILE_p)(png_ptr->io_ptr));
  194081. #endif
  194082. if (check != length)
  194083. png_error(png_ptr, "Write Error");
  194084. }
  194085. #else
  194086. /* this is the model-independent version. Since the standard I/O library
  194087. can't handle far buffers in the medium and small models, we have to copy
  194088. the data.
  194089. */
  194090. #define NEAR_BUF_SIZE 1024
  194091. #define MIN(a,b) (a <= b ? a : b)
  194092. void PNGAPI
  194093. png_default_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  194094. {
  194095. png_uint_32 check;
  194096. png_byte *near_data; /* Needs to be "png_byte *" instead of "png_bytep" */
  194097. png_FILE_p io_ptr;
  194098. if(png_ptr == NULL) return;
  194099. /* Check if data really is near. If so, use usual code. */
  194100. near_data = (png_byte *)CVT_PTR_NOCHECK(data);
  194101. io_ptr = (png_FILE_p)CVT_PTR(png_ptr->io_ptr);
  194102. if ((png_bytep)near_data == data)
  194103. {
  194104. #if defined(_WIN32_WCE)
  194105. if ( !WriteFile(io_ptr, near_data, length, &check, NULL) )
  194106. check = 0;
  194107. #else
  194108. check = fwrite(near_data, 1, length, io_ptr);
  194109. #endif
  194110. }
  194111. else
  194112. {
  194113. png_byte buf[NEAR_BUF_SIZE];
  194114. png_size_t written, remaining, err;
  194115. check = 0;
  194116. remaining = length;
  194117. do
  194118. {
  194119. written = MIN(NEAR_BUF_SIZE, remaining);
  194120. png_memcpy(buf, data, written); /* copy far buffer to near buffer */
  194121. #if defined(_WIN32_WCE)
  194122. if ( !WriteFile(io_ptr, buf, written, &err, NULL) )
  194123. err = 0;
  194124. #else
  194125. err = fwrite(buf, 1, written, io_ptr);
  194126. #endif
  194127. if (err != written)
  194128. break;
  194129. else
  194130. check += err;
  194131. data += written;
  194132. remaining -= written;
  194133. }
  194134. while (remaining != 0);
  194135. }
  194136. if (check != length)
  194137. png_error(png_ptr, "Write Error");
  194138. }
  194139. #endif
  194140. #endif
  194141. /* This function is called to output any data pending writing (normally
  194142. to disk). After png_flush is called, there should be no data pending
  194143. writing in any buffers. */
  194144. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  194145. void /* PRIVATE */
  194146. png_flush(png_structp png_ptr)
  194147. {
  194148. if (png_ptr->output_flush_fn != NULL)
  194149. (*(png_ptr->output_flush_fn))(png_ptr);
  194150. }
  194151. #if !defined(PNG_NO_STDIO)
  194152. void PNGAPI
  194153. png_default_flush(png_structp png_ptr)
  194154. {
  194155. #if !defined(_WIN32_WCE)
  194156. png_FILE_p io_ptr;
  194157. #endif
  194158. if(png_ptr == NULL) return;
  194159. #if !defined(_WIN32_WCE)
  194160. io_ptr = (png_FILE_p)CVT_PTR((png_ptr->io_ptr));
  194161. if (io_ptr != NULL)
  194162. fflush(io_ptr);
  194163. #endif
  194164. }
  194165. #endif
  194166. #endif
  194167. /* This function allows the application to supply new output functions for
  194168. libpng if standard C streams aren't being used.
  194169. This function takes as its arguments:
  194170. png_ptr - pointer to a png output data structure
  194171. io_ptr - pointer to user supplied structure containing info about
  194172. the output functions. May be NULL.
  194173. write_data_fn - pointer to a new output function that takes as its
  194174. arguments a pointer to a png_struct, a pointer to
  194175. data to be written, and a 32-bit unsigned int that is
  194176. the number of bytes to be written. The new write
  194177. function should call png_error(png_ptr, "Error msg")
  194178. to exit and output any fatal error messages.
  194179. flush_data_fn - pointer to a new flush function that takes as its
  194180. arguments a pointer to a png_struct. After a call to
  194181. the flush function, there should be no data in any buffers
  194182. or pending transmission. If the output method doesn't do
  194183. any buffering of ouput, a function prototype must still be
  194184. supplied although it doesn't have to do anything. If
  194185. PNG_WRITE_FLUSH_SUPPORTED is not defined at libpng compile
  194186. time, output_flush_fn will be ignored, although it must be
  194187. supplied for compatibility. */
  194188. void PNGAPI
  194189. png_set_write_fn(png_structp png_ptr, png_voidp io_ptr,
  194190. png_rw_ptr write_data_fn, png_flush_ptr output_flush_fn)
  194191. {
  194192. if(png_ptr == NULL) return;
  194193. png_ptr->io_ptr = io_ptr;
  194194. #if !defined(PNG_NO_STDIO)
  194195. if (write_data_fn != NULL)
  194196. png_ptr->write_data_fn = write_data_fn;
  194197. else
  194198. png_ptr->write_data_fn = png_default_write_data;
  194199. #else
  194200. png_ptr->write_data_fn = write_data_fn;
  194201. #endif
  194202. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  194203. #if !defined(PNG_NO_STDIO)
  194204. if (output_flush_fn != NULL)
  194205. png_ptr->output_flush_fn = output_flush_fn;
  194206. else
  194207. png_ptr->output_flush_fn = png_default_flush;
  194208. #else
  194209. png_ptr->output_flush_fn = output_flush_fn;
  194210. #endif
  194211. #endif /* PNG_WRITE_FLUSH_SUPPORTED */
  194212. /* It is an error to read while writing a png file */
  194213. if (png_ptr->read_data_fn != NULL)
  194214. {
  194215. png_ptr->read_data_fn = NULL;
  194216. png_warning(png_ptr,
  194217. "Attempted to set both read_data_fn and write_data_fn in");
  194218. png_warning(png_ptr,
  194219. "the same structure. Resetting read_data_fn to NULL.");
  194220. }
  194221. }
  194222. #if defined(USE_FAR_KEYWORD)
  194223. #if defined(_MSC_VER)
  194224. void *png_far_to_near(png_structp png_ptr,png_voidp ptr, int check)
  194225. {
  194226. void *near_ptr;
  194227. void FAR *far_ptr;
  194228. FP_OFF(near_ptr) = FP_OFF(ptr);
  194229. far_ptr = (void FAR *)near_ptr;
  194230. if(check != 0)
  194231. if(FP_SEG(ptr) != FP_SEG(far_ptr))
  194232. png_error(png_ptr,"segment lost in conversion");
  194233. return(near_ptr);
  194234. }
  194235. # else
  194236. void *png_far_to_near(png_structp png_ptr,png_voidp ptr, int check)
  194237. {
  194238. void *near_ptr;
  194239. void FAR *far_ptr;
  194240. near_ptr = (void FAR *)ptr;
  194241. far_ptr = (void FAR *)near_ptr;
  194242. if(check != 0)
  194243. if(far_ptr != ptr)
  194244. png_error(png_ptr,"segment lost in conversion");
  194245. return(near_ptr);
  194246. }
  194247. # endif
  194248. # endif
  194249. #endif /* PNG_WRITE_SUPPORTED */
  194250. /********* End of inlined file: pngwio.c *********/
  194251. /********* Start of inlined file: pngwrite.c *********/
  194252. /* pngwrite.c - general routines to write a PNG file
  194253. *
  194254. * Last changed in libpng 1.2.15 January 5, 2007
  194255. * For conditions of distribution and use, see copyright notice in png.h
  194256. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  194257. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  194258. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  194259. */
  194260. /* get internal access to png.h */
  194261. #define PNG_INTERNAL
  194262. #ifdef PNG_WRITE_SUPPORTED
  194263. /* Writes all the PNG information. This is the suggested way to use the
  194264. * library. If you have a new chunk to add, make a function to write it,
  194265. * and put it in the correct location here. If you want the chunk written
  194266. * after the image data, put it in png_write_end(). I strongly encourage
  194267. * you to supply a PNG_INFO_ flag, and check info_ptr->valid before writing
  194268. * the chunk, as that will keep the code from breaking if you want to just
  194269. * write a plain PNG file. If you have long comments, I suggest writing
  194270. * them in png_write_end(), and compressing them.
  194271. */
  194272. void PNGAPI
  194273. png_write_info_before_PLTE(png_structp png_ptr, png_infop info_ptr)
  194274. {
  194275. png_debug(1, "in png_write_info_before_PLTE\n");
  194276. if (png_ptr == NULL || info_ptr == NULL)
  194277. return;
  194278. if (!(png_ptr->mode & PNG_WROTE_INFO_BEFORE_PLTE))
  194279. {
  194280. png_write_sig(png_ptr); /* write PNG signature */
  194281. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  194282. if((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)&&(png_ptr->mng_features_permitted))
  194283. {
  194284. png_warning(png_ptr,"MNG features are not allowed in a PNG datastream");
  194285. png_ptr->mng_features_permitted=0;
  194286. }
  194287. #endif
  194288. /* write IHDR information. */
  194289. png_write_IHDR(png_ptr, info_ptr->width, info_ptr->height,
  194290. info_ptr->bit_depth, info_ptr->color_type, info_ptr->compression_type,
  194291. info_ptr->filter_type,
  194292. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  194293. info_ptr->interlace_type);
  194294. #else
  194295. 0);
  194296. #endif
  194297. /* the rest of these check to see if the valid field has the appropriate
  194298. flag set, and if it does, writes the chunk. */
  194299. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  194300. if (info_ptr->valid & PNG_INFO_gAMA)
  194301. {
  194302. # ifdef PNG_FLOATING_POINT_SUPPORTED
  194303. png_write_gAMA(png_ptr, info_ptr->gamma);
  194304. #else
  194305. #ifdef PNG_FIXED_POINT_SUPPORTED
  194306. png_write_gAMA_fixed(png_ptr, info_ptr->int_gamma);
  194307. # endif
  194308. #endif
  194309. }
  194310. #endif
  194311. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  194312. if (info_ptr->valid & PNG_INFO_sRGB)
  194313. png_write_sRGB(png_ptr, (int)info_ptr->srgb_intent);
  194314. #endif
  194315. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  194316. if (info_ptr->valid & PNG_INFO_iCCP)
  194317. png_write_iCCP(png_ptr, info_ptr->iccp_name, PNG_COMPRESSION_TYPE_BASE,
  194318. info_ptr->iccp_profile, (int)info_ptr->iccp_proflen);
  194319. #endif
  194320. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  194321. if (info_ptr->valid & PNG_INFO_sBIT)
  194322. png_write_sBIT(png_ptr, &(info_ptr->sig_bit), info_ptr->color_type);
  194323. #endif
  194324. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  194325. if (info_ptr->valid & PNG_INFO_cHRM)
  194326. {
  194327. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194328. png_write_cHRM(png_ptr,
  194329. info_ptr->x_white, info_ptr->y_white,
  194330. info_ptr->x_red, info_ptr->y_red,
  194331. info_ptr->x_green, info_ptr->y_green,
  194332. info_ptr->x_blue, info_ptr->y_blue);
  194333. #else
  194334. # ifdef PNG_FIXED_POINT_SUPPORTED
  194335. png_write_cHRM_fixed(png_ptr,
  194336. info_ptr->int_x_white, info_ptr->int_y_white,
  194337. info_ptr->int_x_red, info_ptr->int_y_red,
  194338. info_ptr->int_x_green, info_ptr->int_y_green,
  194339. info_ptr->int_x_blue, info_ptr->int_y_blue);
  194340. # endif
  194341. #endif
  194342. }
  194343. #endif
  194344. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  194345. if (info_ptr->unknown_chunks_num)
  194346. {
  194347. png_unknown_chunk *up;
  194348. png_debug(5, "writing extra chunks\n");
  194349. for (up = info_ptr->unknown_chunks;
  194350. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  194351. up++)
  194352. {
  194353. int keep=png_handle_as_unknown(png_ptr, up->name);
  194354. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  194355. up->location && !(up->location & PNG_HAVE_PLTE) &&
  194356. !(up->location & PNG_HAVE_IDAT) &&
  194357. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  194358. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  194359. {
  194360. png_write_chunk(png_ptr, up->name, up->data, up->size);
  194361. }
  194362. }
  194363. }
  194364. #endif
  194365. png_ptr->mode |= PNG_WROTE_INFO_BEFORE_PLTE;
  194366. }
  194367. }
  194368. void PNGAPI
  194369. png_write_info(png_structp png_ptr, png_infop info_ptr)
  194370. {
  194371. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  194372. int i;
  194373. #endif
  194374. png_debug(1, "in png_write_info\n");
  194375. if (png_ptr == NULL || info_ptr == NULL)
  194376. return;
  194377. png_write_info_before_PLTE(png_ptr, info_ptr);
  194378. if (info_ptr->valid & PNG_INFO_PLTE)
  194379. png_write_PLTE(png_ptr, info_ptr->palette,
  194380. (png_uint_32)info_ptr->num_palette);
  194381. else if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  194382. png_error(png_ptr, "Valid palette required for paletted images");
  194383. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  194384. if (info_ptr->valid & PNG_INFO_tRNS)
  194385. {
  194386. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  194387. /* invert the alpha channel (in tRNS) */
  194388. if ((png_ptr->transformations & PNG_INVERT_ALPHA) &&
  194389. info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  194390. {
  194391. int j;
  194392. for (j=0; j<(int)info_ptr->num_trans; j++)
  194393. info_ptr->trans[j] = (png_byte)(255 - info_ptr->trans[j]);
  194394. }
  194395. #endif
  194396. png_write_tRNS(png_ptr, info_ptr->trans, &(info_ptr->trans_values),
  194397. info_ptr->num_trans, info_ptr->color_type);
  194398. }
  194399. #endif
  194400. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  194401. if (info_ptr->valid & PNG_INFO_bKGD)
  194402. png_write_bKGD(png_ptr, &(info_ptr->background), info_ptr->color_type);
  194403. #endif
  194404. #if defined(PNG_WRITE_hIST_SUPPORTED)
  194405. if (info_ptr->valid & PNG_INFO_hIST)
  194406. png_write_hIST(png_ptr, info_ptr->hist, info_ptr->num_palette);
  194407. #endif
  194408. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  194409. if (info_ptr->valid & PNG_INFO_oFFs)
  194410. png_write_oFFs(png_ptr, info_ptr->x_offset, info_ptr->y_offset,
  194411. info_ptr->offset_unit_type);
  194412. #endif
  194413. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  194414. if (info_ptr->valid & PNG_INFO_pCAL)
  194415. png_write_pCAL(png_ptr, info_ptr->pcal_purpose, info_ptr->pcal_X0,
  194416. info_ptr->pcal_X1, info_ptr->pcal_type, info_ptr->pcal_nparams,
  194417. info_ptr->pcal_units, info_ptr->pcal_params);
  194418. #endif
  194419. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  194420. if (info_ptr->valid & PNG_INFO_sCAL)
  194421. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  194422. png_write_sCAL(png_ptr, (int)info_ptr->scal_unit,
  194423. info_ptr->scal_pixel_width, info_ptr->scal_pixel_height);
  194424. #else
  194425. #ifdef PNG_FIXED_POINT_SUPPORTED
  194426. png_write_sCAL_s(png_ptr, (int)info_ptr->scal_unit,
  194427. info_ptr->scal_s_width, info_ptr->scal_s_height);
  194428. #else
  194429. png_warning(png_ptr,
  194430. "png_write_sCAL not supported; sCAL chunk not written.");
  194431. #endif
  194432. #endif
  194433. #endif
  194434. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  194435. if (info_ptr->valid & PNG_INFO_pHYs)
  194436. png_write_pHYs(png_ptr, info_ptr->x_pixels_per_unit,
  194437. info_ptr->y_pixels_per_unit, info_ptr->phys_unit_type);
  194438. #endif
  194439. #if defined(PNG_WRITE_tIME_SUPPORTED)
  194440. if (info_ptr->valid & PNG_INFO_tIME)
  194441. {
  194442. png_write_tIME(png_ptr, &(info_ptr->mod_time));
  194443. png_ptr->mode |= PNG_WROTE_tIME;
  194444. }
  194445. #endif
  194446. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  194447. if (info_ptr->valid & PNG_INFO_sPLT)
  194448. for (i = 0; i < (int)info_ptr->splt_palettes_num; i++)
  194449. png_write_sPLT(png_ptr, info_ptr->splt_palettes + i);
  194450. #endif
  194451. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  194452. /* Check to see if we need to write text chunks */
  194453. for (i = 0; i < info_ptr->num_text; i++)
  194454. {
  194455. png_debug2(2, "Writing header text chunk %d, type %d\n", i,
  194456. info_ptr->text[i].compression);
  194457. /* an internationalized chunk? */
  194458. if (info_ptr->text[i].compression > 0)
  194459. {
  194460. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  194461. /* write international chunk */
  194462. png_write_iTXt(png_ptr,
  194463. info_ptr->text[i].compression,
  194464. info_ptr->text[i].key,
  194465. info_ptr->text[i].lang,
  194466. info_ptr->text[i].lang_key,
  194467. info_ptr->text[i].text);
  194468. #else
  194469. png_warning(png_ptr, "Unable to write international text");
  194470. #endif
  194471. /* Mark this chunk as written */
  194472. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  194473. }
  194474. /* If we want a compressed text chunk */
  194475. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_zTXt)
  194476. {
  194477. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  194478. /* write compressed chunk */
  194479. png_write_zTXt(png_ptr, info_ptr->text[i].key,
  194480. info_ptr->text[i].text, 0,
  194481. info_ptr->text[i].compression);
  194482. #else
  194483. png_warning(png_ptr, "Unable to write compressed text");
  194484. #endif
  194485. /* Mark this chunk as written */
  194486. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_zTXt_WR;
  194487. }
  194488. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_NONE)
  194489. {
  194490. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  194491. /* write uncompressed chunk */
  194492. png_write_tEXt(png_ptr, info_ptr->text[i].key,
  194493. info_ptr->text[i].text,
  194494. 0);
  194495. #else
  194496. png_warning(png_ptr, "Unable to write uncompressed text");
  194497. #endif
  194498. /* Mark this chunk as written */
  194499. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  194500. }
  194501. }
  194502. #endif
  194503. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  194504. if (info_ptr->unknown_chunks_num)
  194505. {
  194506. png_unknown_chunk *up;
  194507. png_debug(5, "writing extra chunks\n");
  194508. for (up = info_ptr->unknown_chunks;
  194509. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  194510. up++)
  194511. {
  194512. int keep=png_handle_as_unknown(png_ptr, up->name);
  194513. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  194514. up->location && (up->location & PNG_HAVE_PLTE) &&
  194515. !(up->location & PNG_HAVE_IDAT) &&
  194516. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  194517. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  194518. {
  194519. png_write_chunk(png_ptr, up->name, up->data, up->size);
  194520. }
  194521. }
  194522. }
  194523. #endif
  194524. }
  194525. /* Writes the end of the PNG file. If you don't want to write comments or
  194526. * time information, you can pass NULL for info. If you already wrote these
  194527. * in png_write_info(), do not write them again here. If you have long
  194528. * comments, I suggest writing them here, and compressing them.
  194529. */
  194530. void PNGAPI
  194531. png_write_end(png_structp png_ptr, png_infop info_ptr)
  194532. {
  194533. png_debug(1, "in png_write_end\n");
  194534. if (png_ptr == NULL)
  194535. return;
  194536. if (!(png_ptr->mode & PNG_HAVE_IDAT))
  194537. png_error(png_ptr, "No IDATs written into file");
  194538. /* see if user wants us to write information chunks */
  194539. if (info_ptr != NULL)
  194540. {
  194541. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  194542. int i; /* local index variable */
  194543. #endif
  194544. #if defined(PNG_WRITE_tIME_SUPPORTED)
  194545. /* check to see if user has supplied a time chunk */
  194546. if ((info_ptr->valid & PNG_INFO_tIME) &&
  194547. !(png_ptr->mode & PNG_WROTE_tIME))
  194548. png_write_tIME(png_ptr, &(info_ptr->mod_time));
  194549. #endif
  194550. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  194551. /* loop through comment chunks */
  194552. for (i = 0; i < info_ptr->num_text; i++)
  194553. {
  194554. png_debug2(2, "Writing trailer text chunk %d, type %d\n", i,
  194555. info_ptr->text[i].compression);
  194556. /* an internationalized chunk? */
  194557. if (info_ptr->text[i].compression > 0)
  194558. {
  194559. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  194560. /* write international chunk */
  194561. png_write_iTXt(png_ptr,
  194562. info_ptr->text[i].compression,
  194563. info_ptr->text[i].key,
  194564. info_ptr->text[i].lang,
  194565. info_ptr->text[i].lang_key,
  194566. info_ptr->text[i].text);
  194567. #else
  194568. png_warning(png_ptr, "Unable to write international text");
  194569. #endif
  194570. /* Mark this chunk as written */
  194571. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  194572. }
  194573. else if (info_ptr->text[i].compression >= PNG_TEXT_COMPRESSION_zTXt)
  194574. {
  194575. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  194576. /* write compressed chunk */
  194577. png_write_zTXt(png_ptr, info_ptr->text[i].key,
  194578. info_ptr->text[i].text, 0,
  194579. info_ptr->text[i].compression);
  194580. #else
  194581. png_warning(png_ptr, "Unable to write compressed text");
  194582. #endif
  194583. /* Mark this chunk as written */
  194584. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_zTXt_WR;
  194585. }
  194586. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_NONE)
  194587. {
  194588. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  194589. /* write uncompressed chunk */
  194590. png_write_tEXt(png_ptr, info_ptr->text[i].key,
  194591. info_ptr->text[i].text, 0);
  194592. #else
  194593. png_warning(png_ptr, "Unable to write uncompressed text");
  194594. #endif
  194595. /* Mark this chunk as written */
  194596. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  194597. }
  194598. }
  194599. #endif
  194600. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  194601. if (info_ptr->unknown_chunks_num)
  194602. {
  194603. png_unknown_chunk *up;
  194604. png_debug(5, "writing extra chunks\n");
  194605. for (up = info_ptr->unknown_chunks;
  194606. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  194607. up++)
  194608. {
  194609. int keep=png_handle_as_unknown(png_ptr, up->name);
  194610. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  194611. up->location && (up->location & PNG_AFTER_IDAT) &&
  194612. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  194613. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  194614. {
  194615. png_write_chunk(png_ptr, up->name, up->data, up->size);
  194616. }
  194617. }
  194618. }
  194619. #endif
  194620. }
  194621. png_ptr->mode |= PNG_AFTER_IDAT;
  194622. /* write end of PNG file */
  194623. png_write_IEND(png_ptr);
  194624. }
  194625. #if defined(PNG_WRITE_tIME_SUPPORTED)
  194626. #if !defined(_WIN32_WCE)
  194627. /* "time.h" functions are not supported on WindowsCE */
  194628. void PNGAPI
  194629. png_convert_from_struct_tm(png_timep ptime, struct tm FAR * ttime)
  194630. {
  194631. png_debug(1, "in png_convert_from_struct_tm\n");
  194632. ptime->year = (png_uint_16)(1900 + ttime->tm_year);
  194633. ptime->month = (png_byte)(ttime->tm_mon + 1);
  194634. ptime->day = (png_byte)ttime->tm_mday;
  194635. ptime->hour = (png_byte)ttime->tm_hour;
  194636. ptime->minute = (png_byte)ttime->tm_min;
  194637. ptime->second = (png_byte)ttime->tm_sec;
  194638. }
  194639. void PNGAPI
  194640. png_convert_from_time_t(png_timep ptime, time_t ttime)
  194641. {
  194642. struct tm *tbuf;
  194643. png_debug(1, "in png_convert_from_time_t\n");
  194644. tbuf = gmtime(&ttime);
  194645. png_convert_from_struct_tm(ptime, tbuf);
  194646. }
  194647. #endif
  194648. #endif
  194649. /* Initialize png_ptr structure, and allocate any memory needed */
  194650. png_structp PNGAPI
  194651. png_create_write_struct(png_const_charp user_png_ver, png_voidp error_ptr,
  194652. png_error_ptr error_fn, png_error_ptr warn_fn)
  194653. {
  194654. #ifdef PNG_USER_MEM_SUPPORTED
  194655. return (png_create_write_struct_2(user_png_ver, error_ptr, error_fn,
  194656. warn_fn, png_voidp_NULL, png_malloc_ptr_NULL, png_free_ptr_NULL));
  194657. }
  194658. /* Alternate initialize png_ptr structure, and allocate any memory needed */
  194659. png_structp PNGAPI
  194660. png_create_write_struct_2(png_const_charp user_png_ver, png_voidp error_ptr,
  194661. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  194662. png_malloc_ptr malloc_fn, png_free_ptr free_fn)
  194663. {
  194664. #endif /* PNG_USER_MEM_SUPPORTED */
  194665. png_structp png_ptr;
  194666. #ifdef PNG_SETJMP_SUPPORTED
  194667. #ifdef USE_FAR_KEYWORD
  194668. jmp_buf jmpbuf;
  194669. #endif
  194670. #endif
  194671. int i;
  194672. png_debug(1, "in png_create_write_struct\n");
  194673. #ifdef PNG_USER_MEM_SUPPORTED
  194674. png_ptr = (png_structp)png_create_struct_2(PNG_STRUCT_PNG,
  194675. (png_malloc_ptr)malloc_fn, (png_voidp)mem_ptr);
  194676. #else
  194677. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  194678. #endif /* PNG_USER_MEM_SUPPORTED */
  194679. if (png_ptr == NULL)
  194680. return (NULL);
  194681. /* added at libpng-1.2.6 */
  194682. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  194683. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  194684. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  194685. #endif
  194686. #ifdef PNG_SETJMP_SUPPORTED
  194687. #ifdef USE_FAR_KEYWORD
  194688. if (setjmp(jmpbuf))
  194689. #else
  194690. if (setjmp(png_ptr->jmpbuf))
  194691. #endif
  194692. {
  194693. png_free(png_ptr, png_ptr->zbuf);
  194694. png_ptr->zbuf=NULL;
  194695. png_destroy_struct(png_ptr);
  194696. return (NULL);
  194697. }
  194698. #ifdef USE_FAR_KEYWORD
  194699. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  194700. #endif
  194701. #endif
  194702. #ifdef PNG_USER_MEM_SUPPORTED
  194703. png_set_mem_fn(png_ptr, mem_ptr, malloc_fn, free_fn);
  194704. #endif /* PNG_USER_MEM_SUPPORTED */
  194705. png_set_error_fn(png_ptr, error_ptr, error_fn, warn_fn);
  194706. i=0;
  194707. do
  194708. {
  194709. if(user_png_ver[i] != png_libpng_ver[i])
  194710. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  194711. } while (png_libpng_ver[i++]);
  194712. if (png_ptr->flags & PNG_FLAG_LIBRARY_MISMATCH)
  194713. {
  194714. /* Libpng 0.90 and later are binary incompatible with libpng 0.89, so
  194715. * we must recompile any applications that use any older library version.
  194716. * For versions after libpng 1.0, we will be compatible, so we need
  194717. * only check the first digit.
  194718. */
  194719. if (user_png_ver == NULL || user_png_ver[0] != png_libpng_ver[0] ||
  194720. (user_png_ver[0] == '1' && user_png_ver[2] != png_libpng_ver[2]) ||
  194721. (user_png_ver[0] == '0' && user_png_ver[2] < '9'))
  194722. {
  194723. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  194724. char msg[80];
  194725. if (user_png_ver)
  194726. {
  194727. png_snprintf(msg, 80,
  194728. "Application was compiled with png.h from libpng-%.20s",
  194729. user_png_ver);
  194730. png_warning(png_ptr, msg);
  194731. }
  194732. png_snprintf(msg, 80,
  194733. "Application is running with png.c from libpng-%.20s",
  194734. png_libpng_ver);
  194735. png_warning(png_ptr, msg);
  194736. #endif
  194737. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  194738. png_ptr->flags=0;
  194739. #endif
  194740. png_error(png_ptr,
  194741. "Incompatible libpng version in application and library");
  194742. }
  194743. }
  194744. /* initialize zbuf - compression buffer */
  194745. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  194746. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  194747. (png_uint_32)png_ptr->zbuf_size);
  194748. png_set_write_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL,
  194749. png_flush_ptr_NULL);
  194750. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  194751. png_set_filter_heuristics(png_ptr, PNG_FILTER_HEURISTIC_DEFAULT,
  194752. 1, png_doublep_NULL, png_doublep_NULL);
  194753. #endif
  194754. #ifdef PNG_SETJMP_SUPPORTED
  194755. /* Applications that neglect to set up their own setjmp() and then encounter
  194756. a png_error() will longjmp here. Since the jmpbuf is then meaningless we
  194757. abort instead of returning. */
  194758. #ifdef USE_FAR_KEYWORD
  194759. if (setjmp(jmpbuf))
  194760. PNG_ABORT();
  194761. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  194762. #else
  194763. if (setjmp(png_ptr->jmpbuf))
  194764. PNG_ABORT();
  194765. #endif
  194766. #endif
  194767. return (png_ptr);
  194768. }
  194769. /* Initialize png_ptr structure, and allocate any memory needed */
  194770. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  194771. /* Deprecated. */
  194772. #undef png_write_init
  194773. void PNGAPI
  194774. png_write_init(png_structp png_ptr)
  194775. {
  194776. /* We only come here via pre-1.0.7-compiled applications */
  194777. png_write_init_2(png_ptr, "1.0.6 or earlier", 0, 0);
  194778. }
  194779. void PNGAPI
  194780. png_write_init_2(png_structp png_ptr, png_const_charp user_png_ver,
  194781. png_size_t png_struct_size, png_size_t png_info_size)
  194782. {
  194783. /* We only come here via pre-1.0.12-compiled applications */
  194784. if(png_ptr == NULL) return;
  194785. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  194786. if(png_sizeof(png_struct) > png_struct_size ||
  194787. png_sizeof(png_info) > png_info_size)
  194788. {
  194789. char msg[80];
  194790. png_ptr->warning_fn=NULL;
  194791. if (user_png_ver)
  194792. {
  194793. png_snprintf(msg, 80,
  194794. "Application was compiled with png.h from libpng-%.20s",
  194795. user_png_ver);
  194796. png_warning(png_ptr, msg);
  194797. }
  194798. png_snprintf(msg, 80,
  194799. "Application is running with png.c from libpng-%.20s",
  194800. png_libpng_ver);
  194801. png_warning(png_ptr, msg);
  194802. }
  194803. #endif
  194804. if(png_sizeof(png_struct) > png_struct_size)
  194805. {
  194806. png_ptr->error_fn=NULL;
  194807. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  194808. png_ptr->flags=0;
  194809. #endif
  194810. png_error(png_ptr,
  194811. "The png struct allocated by the application for writing is too small.");
  194812. }
  194813. if(png_sizeof(png_info) > png_info_size)
  194814. {
  194815. png_ptr->error_fn=NULL;
  194816. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  194817. png_ptr->flags=0;
  194818. #endif
  194819. png_error(png_ptr,
  194820. "The info struct allocated by the application for writing is too small.");
  194821. }
  194822. png_write_init_3(&png_ptr, user_png_ver, png_struct_size);
  194823. }
  194824. #endif /* PNG_1_0_X || PNG_1_2_X */
  194825. void PNGAPI
  194826. png_write_init_3(png_structpp ptr_ptr, png_const_charp user_png_ver,
  194827. png_size_t png_struct_size)
  194828. {
  194829. png_structp png_ptr=*ptr_ptr;
  194830. #ifdef PNG_SETJMP_SUPPORTED
  194831. jmp_buf tmp_jmp; /* to save current jump buffer */
  194832. #endif
  194833. int i = 0;
  194834. if (png_ptr == NULL)
  194835. return;
  194836. do
  194837. {
  194838. if (user_png_ver[i] != png_libpng_ver[i])
  194839. {
  194840. #ifdef PNG_LEGACY_SUPPORTED
  194841. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  194842. #else
  194843. png_ptr->warning_fn=NULL;
  194844. png_warning(png_ptr,
  194845. "Application uses deprecated png_write_init() and should be recompiled.");
  194846. break;
  194847. #endif
  194848. }
  194849. } while (png_libpng_ver[i++]);
  194850. png_debug(1, "in png_write_init_3\n");
  194851. #ifdef PNG_SETJMP_SUPPORTED
  194852. /* save jump buffer and error functions */
  194853. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  194854. #endif
  194855. if (png_sizeof(png_struct) > png_struct_size)
  194856. {
  194857. png_destroy_struct(png_ptr);
  194858. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  194859. *ptr_ptr = png_ptr;
  194860. }
  194861. /* reset all variables to 0 */
  194862. png_memset(png_ptr, 0, png_sizeof (png_struct));
  194863. /* added at libpng-1.2.6 */
  194864. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  194865. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  194866. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  194867. #endif
  194868. #ifdef PNG_SETJMP_SUPPORTED
  194869. /* restore jump buffer */
  194870. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  194871. #endif
  194872. png_set_write_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL,
  194873. png_flush_ptr_NULL);
  194874. /* initialize zbuf - compression buffer */
  194875. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  194876. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  194877. (png_uint_32)png_ptr->zbuf_size);
  194878. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  194879. png_set_filter_heuristics(png_ptr, PNG_FILTER_HEURISTIC_DEFAULT,
  194880. 1, png_doublep_NULL, png_doublep_NULL);
  194881. #endif
  194882. }
  194883. /* Write a few rows of image data. If the image is interlaced,
  194884. * either you will have to write the 7 sub images, or, if you
  194885. * have called png_set_interlace_handling(), you will have to
  194886. * "write" the image seven times.
  194887. */
  194888. void PNGAPI
  194889. png_write_rows(png_structp png_ptr, png_bytepp row,
  194890. png_uint_32 num_rows)
  194891. {
  194892. png_uint_32 i; /* row counter */
  194893. png_bytepp rp; /* row pointer */
  194894. png_debug(1, "in png_write_rows\n");
  194895. if (png_ptr == NULL)
  194896. return;
  194897. /* loop through the rows */
  194898. for (i = 0, rp = row; i < num_rows; i++, rp++)
  194899. {
  194900. png_write_row(png_ptr, *rp);
  194901. }
  194902. }
  194903. /* Write the image. You only need to call this function once, even
  194904. * if you are writing an interlaced image.
  194905. */
  194906. void PNGAPI
  194907. png_write_image(png_structp png_ptr, png_bytepp image)
  194908. {
  194909. png_uint_32 i; /* row index */
  194910. int pass, num_pass; /* pass variables */
  194911. png_bytepp rp; /* points to current row */
  194912. if (png_ptr == NULL)
  194913. return;
  194914. png_debug(1, "in png_write_image\n");
  194915. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  194916. /* intialize interlace handling. If image is not interlaced,
  194917. this will set pass to 1 */
  194918. num_pass = png_set_interlace_handling(png_ptr);
  194919. #else
  194920. num_pass = 1;
  194921. #endif
  194922. /* loop through passes */
  194923. for (pass = 0; pass < num_pass; pass++)
  194924. {
  194925. /* loop through image */
  194926. for (i = 0, rp = image; i < png_ptr->height; i++, rp++)
  194927. {
  194928. png_write_row(png_ptr, *rp);
  194929. }
  194930. }
  194931. }
  194932. /* called by user to write a row of image data */
  194933. void PNGAPI
  194934. png_write_row(png_structp png_ptr, png_bytep row)
  194935. {
  194936. if (png_ptr == NULL)
  194937. return;
  194938. png_debug2(1, "in png_write_row (row %ld, pass %d)\n",
  194939. png_ptr->row_number, png_ptr->pass);
  194940. /* initialize transformations and other stuff if first time */
  194941. if (png_ptr->row_number == 0 && png_ptr->pass == 0)
  194942. {
  194943. /* make sure we wrote the header info */
  194944. if (!(png_ptr->mode & PNG_WROTE_INFO_BEFORE_PLTE))
  194945. png_error(png_ptr,
  194946. "png_write_info was never called before png_write_row.");
  194947. /* check for transforms that have been set but were defined out */
  194948. #if !defined(PNG_WRITE_INVERT_SUPPORTED) && defined(PNG_READ_INVERT_SUPPORTED)
  194949. if (png_ptr->transformations & PNG_INVERT_MONO)
  194950. png_warning(png_ptr, "PNG_WRITE_INVERT_SUPPORTED is not defined.");
  194951. #endif
  194952. #if !defined(PNG_WRITE_FILLER_SUPPORTED) && defined(PNG_READ_FILLER_SUPPORTED)
  194953. if (png_ptr->transformations & PNG_FILLER)
  194954. png_warning(png_ptr, "PNG_WRITE_FILLER_SUPPORTED is not defined.");
  194955. #endif
  194956. #if !defined(PNG_WRITE_PACKSWAP_SUPPORTED) && defined(PNG_READ_PACKSWAP_SUPPORTED)
  194957. if (png_ptr->transformations & PNG_PACKSWAP)
  194958. png_warning(png_ptr, "PNG_WRITE_PACKSWAP_SUPPORTED is not defined.");
  194959. #endif
  194960. #if !defined(PNG_WRITE_PACK_SUPPORTED) && defined(PNG_READ_PACK_SUPPORTED)
  194961. if (png_ptr->transformations & PNG_PACK)
  194962. png_warning(png_ptr, "PNG_WRITE_PACK_SUPPORTED is not defined.");
  194963. #endif
  194964. #if !defined(PNG_WRITE_SHIFT_SUPPORTED) && defined(PNG_READ_SHIFT_SUPPORTED)
  194965. if (png_ptr->transformations & PNG_SHIFT)
  194966. png_warning(png_ptr, "PNG_WRITE_SHIFT_SUPPORTED is not defined.");
  194967. #endif
  194968. #if !defined(PNG_WRITE_BGR_SUPPORTED) && defined(PNG_READ_BGR_SUPPORTED)
  194969. if (png_ptr->transformations & PNG_BGR)
  194970. png_warning(png_ptr, "PNG_WRITE_BGR_SUPPORTED is not defined.");
  194971. #endif
  194972. #if !defined(PNG_WRITE_SWAP_SUPPORTED) && defined(PNG_READ_SWAP_SUPPORTED)
  194973. if (png_ptr->transformations & PNG_SWAP_BYTES)
  194974. png_warning(png_ptr, "PNG_WRITE_SWAP_SUPPORTED is not defined.");
  194975. #endif
  194976. png_write_start_row(png_ptr);
  194977. }
  194978. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  194979. /* if interlaced and not interested in row, return */
  194980. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  194981. {
  194982. switch (png_ptr->pass)
  194983. {
  194984. case 0:
  194985. if (png_ptr->row_number & 0x07)
  194986. {
  194987. png_write_finish_row(png_ptr);
  194988. return;
  194989. }
  194990. break;
  194991. case 1:
  194992. if ((png_ptr->row_number & 0x07) || png_ptr->width < 5)
  194993. {
  194994. png_write_finish_row(png_ptr);
  194995. return;
  194996. }
  194997. break;
  194998. case 2:
  194999. if ((png_ptr->row_number & 0x07) != 4)
  195000. {
  195001. png_write_finish_row(png_ptr);
  195002. return;
  195003. }
  195004. break;
  195005. case 3:
  195006. if ((png_ptr->row_number & 0x03) || png_ptr->width < 3)
  195007. {
  195008. png_write_finish_row(png_ptr);
  195009. return;
  195010. }
  195011. break;
  195012. case 4:
  195013. if ((png_ptr->row_number & 0x03) != 2)
  195014. {
  195015. png_write_finish_row(png_ptr);
  195016. return;
  195017. }
  195018. break;
  195019. case 5:
  195020. if ((png_ptr->row_number & 0x01) || png_ptr->width < 2)
  195021. {
  195022. png_write_finish_row(png_ptr);
  195023. return;
  195024. }
  195025. break;
  195026. case 6:
  195027. if (!(png_ptr->row_number & 0x01))
  195028. {
  195029. png_write_finish_row(png_ptr);
  195030. return;
  195031. }
  195032. break;
  195033. }
  195034. }
  195035. #endif
  195036. /* set up row info for transformations */
  195037. png_ptr->row_info.color_type = png_ptr->color_type;
  195038. png_ptr->row_info.width = png_ptr->usr_width;
  195039. png_ptr->row_info.channels = png_ptr->usr_channels;
  195040. png_ptr->row_info.bit_depth = png_ptr->usr_bit_depth;
  195041. png_ptr->row_info.pixel_depth = (png_byte)(png_ptr->row_info.bit_depth *
  195042. png_ptr->row_info.channels);
  195043. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  195044. png_ptr->row_info.width);
  195045. png_debug1(3, "row_info->color_type = %d\n", png_ptr->row_info.color_type);
  195046. png_debug1(3, "row_info->width = %lu\n", png_ptr->row_info.width);
  195047. png_debug1(3, "row_info->channels = %d\n", png_ptr->row_info.channels);
  195048. png_debug1(3, "row_info->bit_depth = %d\n", png_ptr->row_info.bit_depth);
  195049. png_debug1(3, "row_info->pixel_depth = %d\n", png_ptr->row_info.pixel_depth);
  195050. png_debug1(3, "row_info->rowbytes = %lu\n", png_ptr->row_info.rowbytes);
  195051. /* Copy user's row into buffer, leaving room for filter byte. */
  195052. png_memcpy_check(png_ptr, png_ptr->row_buf + 1, row,
  195053. png_ptr->row_info.rowbytes);
  195054. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  195055. /* handle interlacing */
  195056. if (png_ptr->interlaced && png_ptr->pass < 6 &&
  195057. (png_ptr->transformations & PNG_INTERLACE))
  195058. {
  195059. png_do_write_interlace(&(png_ptr->row_info),
  195060. png_ptr->row_buf + 1, png_ptr->pass);
  195061. /* this should always get caught above, but still ... */
  195062. if (!(png_ptr->row_info.width))
  195063. {
  195064. png_write_finish_row(png_ptr);
  195065. return;
  195066. }
  195067. }
  195068. #endif
  195069. /* handle other transformations */
  195070. if (png_ptr->transformations)
  195071. png_do_write_transformations(png_ptr);
  195072. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  195073. /* Write filter_method 64 (intrapixel differencing) only if
  195074. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  195075. * 2. Libpng did not write a PNG signature (this filter_method is only
  195076. * used in PNG datastreams that are embedded in MNG datastreams) and
  195077. * 3. The application called png_permit_mng_features with a mask that
  195078. * included PNG_FLAG_MNG_FILTER_64 and
  195079. * 4. The filter_method is 64 and
  195080. * 5. The color_type is RGB or RGBA
  195081. */
  195082. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  195083. (png_ptr->filter_type == PNG_INTRAPIXEL_DIFFERENCING))
  195084. {
  195085. /* Intrapixel differencing */
  195086. png_do_write_intrapixel(&(png_ptr->row_info), png_ptr->row_buf + 1);
  195087. }
  195088. #endif
  195089. /* Find a filter if necessary, filter the row and write it out. */
  195090. png_write_find_filter(png_ptr, &(png_ptr->row_info));
  195091. if (png_ptr->write_row_fn != NULL)
  195092. (*(png_ptr->write_row_fn))(png_ptr, png_ptr->row_number, png_ptr->pass);
  195093. }
  195094. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  195095. /* Set the automatic flush interval or 0 to turn flushing off */
  195096. void PNGAPI
  195097. png_set_flush(png_structp png_ptr, int nrows)
  195098. {
  195099. png_debug(1, "in png_set_flush\n");
  195100. if (png_ptr == NULL)
  195101. return;
  195102. png_ptr->flush_dist = (nrows < 0 ? 0 : nrows);
  195103. }
  195104. /* flush the current output buffers now */
  195105. void PNGAPI
  195106. png_write_flush(png_structp png_ptr)
  195107. {
  195108. int wrote_IDAT;
  195109. png_debug(1, "in png_write_flush\n");
  195110. if (png_ptr == NULL)
  195111. return;
  195112. /* We have already written out all of the data */
  195113. if (png_ptr->row_number >= png_ptr->num_rows)
  195114. return;
  195115. do
  195116. {
  195117. int ret;
  195118. /* compress the data */
  195119. ret = deflate(&png_ptr->zstream, Z_SYNC_FLUSH);
  195120. wrote_IDAT = 0;
  195121. /* check for compression errors */
  195122. if (ret != Z_OK)
  195123. {
  195124. if (png_ptr->zstream.msg != NULL)
  195125. png_error(png_ptr, png_ptr->zstream.msg);
  195126. else
  195127. png_error(png_ptr, "zlib error");
  195128. }
  195129. if (!(png_ptr->zstream.avail_out))
  195130. {
  195131. /* write the IDAT and reset the zlib output buffer */
  195132. png_write_IDAT(png_ptr, png_ptr->zbuf,
  195133. png_ptr->zbuf_size);
  195134. png_ptr->zstream.next_out = png_ptr->zbuf;
  195135. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  195136. wrote_IDAT = 1;
  195137. }
  195138. } while(wrote_IDAT == 1);
  195139. /* If there is any data left to be output, write it into a new IDAT */
  195140. if (png_ptr->zbuf_size != png_ptr->zstream.avail_out)
  195141. {
  195142. /* write the IDAT and reset the zlib output buffer */
  195143. png_write_IDAT(png_ptr, png_ptr->zbuf,
  195144. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  195145. png_ptr->zstream.next_out = png_ptr->zbuf;
  195146. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  195147. }
  195148. png_ptr->flush_rows = 0;
  195149. png_flush(png_ptr);
  195150. }
  195151. #endif /* PNG_WRITE_FLUSH_SUPPORTED */
  195152. /* free all memory used by the write */
  195153. void PNGAPI
  195154. png_destroy_write_struct(png_structpp png_ptr_ptr, png_infopp info_ptr_ptr)
  195155. {
  195156. png_structp png_ptr = NULL;
  195157. png_infop info_ptr = NULL;
  195158. #ifdef PNG_USER_MEM_SUPPORTED
  195159. png_free_ptr free_fn = NULL;
  195160. png_voidp mem_ptr = NULL;
  195161. #endif
  195162. png_debug(1, "in png_destroy_write_struct\n");
  195163. if (png_ptr_ptr != NULL)
  195164. {
  195165. png_ptr = *png_ptr_ptr;
  195166. #ifdef PNG_USER_MEM_SUPPORTED
  195167. free_fn = png_ptr->free_fn;
  195168. mem_ptr = png_ptr->mem_ptr;
  195169. #endif
  195170. }
  195171. if (info_ptr_ptr != NULL)
  195172. info_ptr = *info_ptr_ptr;
  195173. if (info_ptr != NULL)
  195174. {
  195175. png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1);
  195176. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  195177. if (png_ptr->num_chunk_list)
  195178. {
  195179. png_free(png_ptr, png_ptr->chunk_list);
  195180. png_ptr->chunk_list=NULL;
  195181. png_ptr->num_chunk_list=0;
  195182. }
  195183. #endif
  195184. #ifdef PNG_USER_MEM_SUPPORTED
  195185. png_destroy_struct_2((png_voidp)info_ptr, (png_free_ptr)free_fn,
  195186. (png_voidp)mem_ptr);
  195187. #else
  195188. png_destroy_struct((png_voidp)info_ptr);
  195189. #endif
  195190. *info_ptr_ptr = NULL;
  195191. }
  195192. if (png_ptr != NULL)
  195193. {
  195194. png_write_destroy(png_ptr);
  195195. #ifdef PNG_USER_MEM_SUPPORTED
  195196. png_destroy_struct_2((png_voidp)png_ptr, (png_free_ptr)free_fn,
  195197. (png_voidp)mem_ptr);
  195198. #else
  195199. png_destroy_struct((png_voidp)png_ptr);
  195200. #endif
  195201. *png_ptr_ptr = NULL;
  195202. }
  195203. }
  195204. /* Free any memory used in png_ptr struct (old method) */
  195205. void /* PRIVATE */
  195206. png_write_destroy(png_structp png_ptr)
  195207. {
  195208. #ifdef PNG_SETJMP_SUPPORTED
  195209. jmp_buf tmp_jmp; /* save jump buffer */
  195210. #endif
  195211. png_error_ptr error_fn;
  195212. png_error_ptr warning_fn;
  195213. png_voidp error_ptr;
  195214. #ifdef PNG_USER_MEM_SUPPORTED
  195215. png_free_ptr free_fn;
  195216. #endif
  195217. png_debug(1, "in png_write_destroy\n");
  195218. /* free any memory zlib uses */
  195219. deflateEnd(&png_ptr->zstream);
  195220. /* free our memory. png_free checks NULL for us. */
  195221. png_free(png_ptr, png_ptr->zbuf);
  195222. png_free(png_ptr, png_ptr->row_buf);
  195223. png_free(png_ptr, png_ptr->prev_row);
  195224. png_free(png_ptr, png_ptr->sub_row);
  195225. png_free(png_ptr, png_ptr->up_row);
  195226. png_free(png_ptr, png_ptr->avg_row);
  195227. png_free(png_ptr, png_ptr->paeth_row);
  195228. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  195229. png_free(png_ptr, png_ptr->time_buffer);
  195230. #endif
  195231. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  195232. png_free(png_ptr, png_ptr->prev_filters);
  195233. png_free(png_ptr, png_ptr->filter_weights);
  195234. png_free(png_ptr, png_ptr->inv_filter_weights);
  195235. png_free(png_ptr, png_ptr->filter_costs);
  195236. png_free(png_ptr, png_ptr->inv_filter_costs);
  195237. #endif
  195238. #ifdef PNG_SETJMP_SUPPORTED
  195239. /* reset structure */
  195240. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  195241. #endif
  195242. error_fn = png_ptr->error_fn;
  195243. warning_fn = png_ptr->warning_fn;
  195244. error_ptr = png_ptr->error_ptr;
  195245. #ifdef PNG_USER_MEM_SUPPORTED
  195246. free_fn = png_ptr->free_fn;
  195247. #endif
  195248. png_memset(png_ptr, 0, png_sizeof (png_struct));
  195249. png_ptr->error_fn = error_fn;
  195250. png_ptr->warning_fn = warning_fn;
  195251. png_ptr->error_ptr = error_ptr;
  195252. #ifdef PNG_USER_MEM_SUPPORTED
  195253. png_ptr->free_fn = free_fn;
  195254. #endif
  195255. #ifdef PNG_SETJMP_SUPPORTED
  195256. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  195257. #endif
  195258. }
  195259. /* Allow the application to select one or more row filters to use. */
  195260. void PNGAPI
  195261. png_set_filter(png_structp png_ptr, int method, int filters)
  195262. {
  195263. png_debug(1, "in png_set_filter\n");
  195264. if (png_ptr == NULL)
  195265. return;
  195266. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  195267. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  195268. (method == PNG_INTRAPIXEL_DIFFERENCING))
  195269. method = PNG_FILTER_TYPE_BASE;
  195270. #endif
  195271. if (method == PNG_FILTER_TYPE_BASE)
  195272. {
  195273. switch (filters & (PNG_ALL_FILTERS | 0x07))
  195274. {
  195275. #ifndef PNG_NO_WRITE_FILTER
  195276. case 5:
  195277. case 6:
  195278. case 7: png_warning(png_ptr, "Unknown row filter for method 0");
  195279. #endif /* PNG_NO_WRITE_FILTER */
  195280. case PNG_FILTER_VALUE_NONE:
  195281. png_ptr->do_filter=PNG_FILTER_NONE; break;
  195282. #ifndef PNG_NO_WRITE_FILTER
  195283. case PNG_FILTER_VALUE_SUB:
  195284. png_ptr->do_filter=PNG_FILTER_SUB; break;
  195285. case PNG_FILTER_VALUE_UP:
  195286. png_ptr->do_filter=PNG_FILTER_UP; break;
  195287. case PNG_FILTER_VALUE_AVG:
  195288. png_ptr->do_filter=PNG_FILTER_AVG; break;
  195289. case PNG_FILTER_VALUE_PAETH:
  195290. png_ptr->do_filter=PNG_FILTER_PAETH; break;
  195291. default: png_ptr->do_filter = (png_byte)filters; break;
  195292. #else
  195293. default: png_warning(png_ptr, "Unknown row filter for method 0");
  195294. #endif /* PNG_NO_WRITE_FILTER */
  195295. }
  195296. /* If we have allocated the row_buf, this means we have already started
  195297. * with the image and we should have allocated all of the filter buffers
  195298. * that have been selected. If prev_row isn't already allocated, then
  195299. * it is too late to start using the filters that need it, since we
  195300. * will be missing the data in the previous row. If an application
  195301. * wants to start and stop using particular filters during compression,
  195302. * it should start out with all of the filters, and then add and
  195303. * remove them after the start of compression.
  195304. */
  195305. if (png_ptr->row_buf != NULL)
  195306. {
  195307. #ifndef PNG_NO_WRITE_FILTER
  195308. if ((png_ptr->do_filter & PNG_FILTER_SUB) && png_ptr->sub_row == NULL)
  195309. {
  195310. png_ptr->sub_row = (png_bytep)png_malloc(png_ptr,
  195311. (png_ptr->rowbytes + 1));
  195312. png_ptr->sub_row[0] = PNG_FILTER_VALUE_SUB;
  195313. }
  195314. if ((png_ptr->do_filter & PNG_FILTER_UP) && png_ptr->up_row == NULL)
  195315. {
  195316. if (png_ptr->prev_row == NULL)
  195317. {
  195318. png_warning(png_ptr, "Can't add Up filter after starting");
  195319. png_ptr->do_filter &= ~PNG_FILTER_UP;
  195320. }
  195321. else
  195322. {
  195323. png_ptr->up_row = (png_bytep)png_malloc(png_ptr,
  195324. (png_ptr->rowbytes + 1));
  195325. png_ptr->up_row[0] = PNG_FILTER_VALUE_UP;
  195326. }
  195327. }
  195328. if ((png_ptr->do_filter & PNG_FILTER_AVG) && png_ptr->avg_row == NULL)
  195329. {
  195330. if (png_ptr->prev_row == NULL)
  195331. {
  195332. png_warning(png_ptr, "Can't add Average filter after starting");
  195333. png_ptr->do_filter &= ~PNG_FILTER_AVG;
  195334. }
  195335. else
  195336. {
  195337. png_ptr->avg_row = (png_bytep)png_malloc(png_ptr,
  195338. (png_ptr->rowbytes + 1));
  195339. png_ptr->avg_row[0] = PNG_FILTER_VALUE_AVG;
  195340. }
  195341. }
  195342. if ((png_ptr->do_filter & PNG_FILTER_PAETH) &&
  195343. png_ptr->paeth_row == NULL)
  195344. {
  195345. if (png_ptr->prev_row == NULL)
  195346. {
  195347. png_warning(png_ptr, "Can't add Paeth filter after starting");
  195348. png_ptr->do_filter &= (png_byte)(~PNG_FILTER_PAETH);
  195349. }
  195350. else
  195351. {
  195352. png_ptr->paeth_row = (png_bytep)png_malloc(png_ptr,
  195353. (png_ptr->rowbytes + 1));
  195354. png_ptr->paeth_row[0] = PNG_FILTER_VALUE_PAETH;
  195355. }
  195356. }
  195357. if (png_ptr->do_filter == PNG_NO_FILTERS)
  195358. #endif /* PNG_NO_WRITE_FILTER */
  195359. png_ptr->do_filter = PNG_FILTER_NONE;
  195360. }
  195361. }
  195362. else
  195363. png_error(png_ptr, "Unknown custom filter method");
  195364. }
  195365. /* This allows us to influence the way in which libpng chooses the "best"
  195366. * filter for the current scanline. While the "minimum-sum-of-absolute-
  195367. * differences metric is relatively fast and effective, there is some
  195368. * question as to whether it can be improved upon by trying to keep the
  195369. * filtered data going to zlib more consistent, hopefully resulting in
  195370. * better compression.
  195371. */
  195372. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED) /* GRR 970116 */
  195373. void PNGAPI
  195374. png_set_filter_heuristics(png_structp png_ptr, int heuristic_method,
  195375. int num_weights, png_doublep filter_weights,
  195376. png_doublep filter_costs)
  195377. {
  195378. int i;
  195379. png_debug(1, "in png_set_filter_heuristics\n");
  195380. if (png_ptr == NULL)
  195381. return;
  195382. if (heuristic_method >= PNG_FILTER_HEURISTIC_LAST)
  195383. {
  195384. png_warning(png_ptr, "Unknown filter heuristic method");
  195385. return;
  195386. }
  195387. if (heuristic_method == PNG_FILTER_HEURISTIC_DEFAULT)
  195388. {
  195389. heuristic_method = PNG_FILTER_HEURISTIC_UNWEIGHTED;
  195390. }
  195391. if (num_weights < 0 || filter_weights == NULL ||
  195392. heuristic_method == PNG_FILTER_HEURISTIC_UNWEIGHTED)
  195393. {
  195394. num_weights = 0;
  195395. }
  195396. png_ptr->num_prev_filters = (png_byte)num_weights;
  195397. png_ptr->heuristic_method = (png_byte)heuristic_method;
  195398. if (num_weights > 0)
  195399. {
  195400. if (png_ptr->prev_filters == NULL)
  195401. {
  195402. png_ptr->prev_filters = (png_bytep)png_malloc(png_ptr,
  195403. (png_uint_32)(png_sizeof(png_byte) * num_weights));
  195404. /* To make sure that the weighting starts out fairly */
  195405. for (i = 0; i < num_weights; i++)
  195406. {
  195407. png_ptr->prev_filters[i] = 255;
  195408. }
  195409. }
  195410. if (png_ptr->filter_weights == NULL)
  195411. {
  195412. png_ptr->filter_weights = (png_uint_16p)png_malloc(png_ptr,
  195413. (png_uint_32)(png_sizeof(png_uint_16) * num_weights));
  195414. png_ptr->inv_filter_weights = (png_uint_16p)png_malloc(png_ptr,
  195415. (png_uint_32)(png_sizeof(png_uint_16) * num_weights));
  195416. for (i = 0; i < num_weights; i++)
  195417. {
  195418. png_ptr->inv_filter_weights[i] =
  195419. png_ptr->filter_weights[i] = PNG_WEIGHT_FACTOR;
  195420. }
  195421. }
  195422. for (i = 0; i < num_weights; i++)
  195423. {
  195424. if (filter_weights[i] < 0.0)
  195425. {
  195426. png_ptr->inv_filter_weights[i] =
  195427. png_ptr->filter_weights[i] = PNG_WEIGHT_FACTOR;
  195428. }
  195429. else
  195430. {
  195431. png_ptr->inv_filter_weights[i] =
  195432. (png_uint_16)((double)PNG_WEIGHT_FACTOR*filter_weights[i]+0.5);
  195433. png_ptr->filter_weights[i] =
  195434. (png_uint_16)((double)PNG_WEIGHT_FACTOR/filter_weights[i]+0.5);
  195435. }
  195436. }
  195437. }
  195438. /* If, in the future, there are other filter methods, this would
  195439. * need to be based on png_ptr->filter.
  195440. */
  195441. if (png_ptr->filter_costs == NULL)
  195442. {
  195443. png_ptr->filter_costs = (png_uint_16p)png_malloc(png_ptr,
  195444. (png_uint_32)(png_sizeof(png_uint_16) * PNG_FILTER_VALUE_LAST));
  195445. png_ptr->inv_filter_costs = (png_uint_16p)png_malloc(png_ptr,
  195446. (png_uint_32)(png_sizeof(png_uint_16) * PNG_FILTER_VALUE_LAST));
  195447. for (i = 0; i < PNG_FILTER_VALUE_LAST; i++)
  195448. {
  195449. png_ptr->inv_filter_costs[i] =
  195450. png_ptr->filter_costs[i] = PNG_COST_FACTOR;
  195451. }
  195452. }
  195453. /* Here is where we set the relative costs of the different filters. We
  195454. * should take the desired compression level into account when setting
  195455. * the costs, so that Paeth, for instance, has a high relative cost at low
  195456. * compression levels, while it has a lower relative cost at higher
  195457. * compression settings. The filter types are in order of increasing
  195458. * relative cost, so it would be possible to do this with an algorithm.
  195459. */
  195460. for (i = 0; i < PNG_FILTER_VALUE_LAST; i++)
  195461. {
  195462. if (filter_costs == NULL || filter_costs[i] < 0.0)
  195463. {
  195464. png_ptr->inv_filter_costs[i] =
  195465. png_ptr->filter_costs[i] = PNG_COST_FACTOR;
  195466. }
  195467. else if (filter_costs[i] >= 1.0)
  195468. {
  195469. png_ptr->inv_filter_costs[i] =
  195470. (png_uint_16)((double)PNG_COST_FACTOR / filter_costs[i] + 0.5);
  195471. png_ptr->filter_costs[i] =
  195472. (png_uint_16)((double)PNG_COST_FACTOR * filter_costs[i] + 0.5);
  195473. }
  195474. }
  195475. }
  195476. #endif /* PNG_WRITE_WEIGHTED_FILTER_SUPPORTED */
  195477. void PNGAPI
  195478. png_set_compression_level(png_structp png_ptr, int level)
  195479. {
  195480. png_debug(1, "in png_set_compression_level\n");
  195481. if (png_ptr == NULL)
  195482. return;
  195483. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_LEVEL;
  195484. png_ptr->zlib_level = level;
  195485. }
  195486. void PNGAPI
  195487. png_set_compression_mem_level(png_structp png_ptr, int mem_level)
  195488. {
  195489. png_debug(1, "in png_set_compression_mem_level\n");
  195490. if (png_ptr == NULL)
  195491. return;
  195492. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL;
  195493. png_ptr->zlib_mem_level = mem_level;
  195494. }
  195495. void PNGAPI
  195496. png_set_compression_strategy(png_structp png_ptr, int strategy)
  195497. {
  195498. png_debug(1, "in png_set_compression_strategy\n");
  195499. if (png_ptr == NULL)
  195500. return;
  195501. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_STRATEGY;
  195502. png_ptr->zlib_strategy = strategy;
  195503. }
  195504. void PNGAPI
  195505. png_set_compression_window_bits(png_structp png_ptr, int window_bits)
  195506. {
  195507. if (png_ptr == NULL)
  195508. return;
  195509. if (window_bits > 15)
  195510. png_warning(png_ptr, "Only compression windows <= 32k supported by PNG");
  195511. else if (window_bits < 8)
  195512. png_warning(png_ptr, "Only compression windows >= 256 supported by PNG");
  195513. #ifndef WBITS_8_OK
  195514. /* avoid libpng bug with 256-byte windows */
  195515. if (window_bits == 8)
  195516. {
  195517. png_warning(png_ptr, "Compression window is being reset to 512");
  195518. window_bits=9;
  195519. }
  195520. #endif
  195521. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS;
  195522. png_ptr->zlib_window_bits = window_bits;
  195523. }
  195524. void PNGAPI
  195525. png_set_compression_method(png_structp png_ptr, int method)
  195526. {
  195527. png_debug(1, "in png_set_compression_method\n");
  195528. if (png_ptr == NULL)
  195529. return;
  195530. if (method != 8)
  195531. png_warning(png_ptr, "Only compression method 8 is supported by PNG");
  195532. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_METHOD;
  195533. png_ptr->zlib_method = method;
  195534. }
  195535. void PNGAPI
  195536. png_set_write_status_fn(png_structp png_ptr, png_write_status_ptr write_row_fn)
  195537. {
  195538. if (png_ptr == NULL)
  195539. return;
  195540. png_ptr->write_row_fn = write_row_fn;
  195541. }
  195542. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  195543. void PNGAPI
  195544. png_set_write_user_transform_fn(png_structp png_ptr, png_user_transform_ptr
  195545. write_user_transform_fn)
  195546. {
  195547. png_debug(1, "in png_set_write_user_transform_fn\n");
  195548. if (png_ptr == NULL)
  195549. return;
  195550. png_ptr->transformations |= PNG_USER_TRANSFORM;
  195551. png_ptr->write_user_transform_fn = write_user_transform_fn;
  195552. }
  195553. #endif
  195554. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  195555. void PNGAPI
  195556. png_write_png(png_structp png_ptr, png_infop info_ptr,
  195557. int transforms, voidp params)
  195558. {
  195559. if (png_ptr == NULL || info_ptr == NULL)
  195560. return;
  195561. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  195562. /* invert the alpha channel from opacity to transparency */
  195563. if (transforms & PNG_TRANSFORM_INVERT_ALPHA)
  195564. png_set_invert_alpha(png_ptr);
  195565. #endif
  195566. /* Write the file header information. */
  195567. png_write_info(png_ptr, info_ptr);
  195568. /* ------ these transformations don't touch the info structure ------- */
  195569. #if defined(PNG_WRITE_INVERT_SUPPORTED)
  195570. /* invert monochrome pixels */
  195571. if (transforms & PNG_TRANSFORM_INVERT_MONO)
  195572. png_set_invert_mono(png_ptr);
  195573. #endif
  195574. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  195575. /* Shift the pixels up to a legal bit depth and fill in
  195576. * as appropriate to correctly scale the image.
  195577. */
  195578. if ((transforms & PNG_TRANSFORM_SHIFT)
  195579. && (info_ptr->valid & PNG_INFO_sBIT))
  195580. png_set_shift(png_ptr, &info_ptr->sig_bit);
  195581. #endif
  195582. #if defined(PNG_WRITE_PACK_SUPPORTED)
  195583. /* pack pixels into bytes */
  195584. if (transforms & PNG_TRANSFORM_PACKING)
  195585. png_set_packing(png_ptr);
  195586. #endif
  195587. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  195588. /* swap location of alpha bytes from ARGB to RGBA */
  195589. if (transforms & PNG_TRANSFORM_SWAP_ALPHA)
  195590. png_set_swap_alpha(png_ptr);
  195591. #endif
  195592. #if defined(PNG_WRITE_FILLER_SUPPORTED)
  195593. /* Get rid of filler (OR ALPHA) bytes, pack XRGB/RGBX/ARGB/RGBA into
  195594. * RGB (4 channels -> 3 channels). The second parameter is not used.
  195595. */
  195596. if (transforms & PNG_TRANSFORM_STRIP_FILLER)
  195597. png_set_filler(png_ptr, 0, PNG_FILLER_BEFORE);
  195598. #endif
  195599. #if defined(PNG_WRITE_BGR_SUPPORTED)
  195600. /* flip BGR pixels to RGB */
  195601. if (transforms & PNG_TRANSFORM_BGR)
  195602. png_set_bgr(png_ptr);
  195603. #endif
  195604. #if defined(PNG_WRITE_SWAP_SUPPORTED)
  195605. /* swap bytes of 16-bit files to most significant byte first */
  195606. if (transforms & PNG_TRANSFORM_SWAP_ENDIAN)
  195607. png_set_swap(png_ptr);
  195608. #endif
  195609. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  195610. /* swap bits of 1, 2, 4 bit packed pixel formats */
  195611. if (transforms & PNG_TRANSFORM_PACKSWAP)
  195612. png_set_packswap(png_ptr);
  195613. #endif
  195614. /* ----------------------- end of transformations ------------------- */
  195615. /* write the bits */
  195616. if (info_ptr->valid & PNG_INFO_IDAT)
  195617. png_write_image(png_ptr, info_ptr->row_pointers);
  195618. /* It is REQUIRED to call this to finish writing the rest of the file */
  195619. png_write_end(png_ptr, info_ptr);
  195620. transforms = transforms; /* quiet compiler warnings */
  195621. params = params;
  195622. }
  195623. #endif
  195624. #endif /* PNG_WRITE_SUPPORTED */
  195625. /********* End of inlined file: pngwrite.c *********/
  195626. /********* Start of inlined file: pngwtran.c *********/
  195627. /* pngwtran.c - transforms the data in a row for PNG writers
  195628. *
  195629. * Last changed in libpng 1.2.9 April 14, 2006
  195630. * For conditions of distribution and use, see copyright notice in png.h
  195631. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  195632. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  195633. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  195634. */
  195635. #define PNG_INTERNAL
  195636. #ifdef PNG_WRITE_SUPPORTED
  195637. /* Transform the data according to the user's wishes. The order of
  195638. * transformations is significant.
  195639. */
  195640. void /* PRIVATE */
  195641. png_do_write_transformations(png_structp png_ptr)
  195642. {
  195643. png_debug(1, "in png_do_write_transformations\n");
  195644. if (png_ptr == NULL)
  195645. return;
  195646. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  195647. if (png_ptr->transformations & PNG_USER_TRANSFORM)
  195648. if(png_ptr->write_user_transform_fn != NULL)
  195649. (*(png_ptr->write_user_transform_fn)) /* user write transform function */
  195650. (png_ptr, /* png_ptr */
  195651. &(png_ptr->row_info), /* row_info: */
  195652. /* png_uint_32 width; width of row */
  195653. /* png_uint_32 rowbytes; number of bytes in row */
  195654. /* png_byte color_type; color type of pixels */
  195655. /* png_byte bit_depth; bit depth of samples */
  195656. /* png_byte channels; number of channels (1-4) */
  195657. /* png_byte pixel_depth; bits per pixel (depth*channels) */
  195658. png_ptr->row_buf + 1); /* start of pixel data for row */
  195659. #endif
  195660. #if defined(PNG_WRITE_FILLER_SUPPORTED)
  195661. if (png_ptr->transformations & PNG_FILLER)
  195662. png_do_strip_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  195663. png_ptr->flags);
  195664. #endif
  195665. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  195666. if (png_ptr->transformations & PNG_PACKSWAP)
  195667. png_do_packswap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  195668. #endif
  195669. #if defined(PNG_WRITE_PACK_SUPPORTED)
  195670. if (png_ptr->transformations & PNG_PACK)
  195671. png_do_pack(&(png_ptr->row_info), png_ptr->row_buf + 1,
  195672. (png_uint_32)png_ptr->bit_depth);
  195673. #endif
  195674. #if defined(PNG_WRITE_SWAP_SUPPORTED)
  195675. if (png_ptr->transformations & PNG_SWAP_BYTES)
  195676. png_do_swap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  195677. #endif
  195678. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  195679. if (png_ptr->transformations & PNG_SHIFT)
  195680. png_do_shift(&(png_ptr->row_info), png_ptr->row_buf + 1,
  195681. &(png_ptr->shift));
  195682. #endif
  195683. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  195684. if (png_ptr->transformations & PNG_SWAP_ALPHA)
  195685. png_do_write_swap_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  195686. #endif
  195687. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  195688. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  195689. png_do_write_invert_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  195690. #endif
  195691. #if defined(PNG_WRITE_BGR_SUPPORTED)
  195692. if (png_ptr->transformations & PNG_BGR)
  195693. png_do_bgr(&(png_ptr->row_info), png_ptr->row_buf + 1);
  195694. #endif
  195695. #if defined(PNG_WRITE_INVERT_SUPPORTED)
  195696. if (png_ptr->transformations & PNG_INVERT_MONO)
  195697. png_do_invert(&(png_ptr->row_info), png_ptr->row_buf + 1);
  195698. #endif
  195699. }
  195700. #if defined(PNG_WRITE_PACK_SUPPORTED)
  195701. /* Pack pixels into bytes. Pass the true bit depth in bit_depth. The
  195702. * row_info bit depth should be 8 (one pixel per byte). The channels
  195703. * should be 1 (this only happens on grayscale and paletted images).
  195704. */
  195705. void /* PRIVATE */
  195706. png_do_pack(png_row_infop row_info, png_bytep row, png_uint_32 bit_depth)
  195707. {
  195708. png_debug(1, "in png_do_pack\n");
  195709. if (row_info->bit_depth == 8 &&
  195710. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  195711. row != NULL && row_info != NULL &&
  195712. #endif
  195713. row_info->channels == 1)
  195714. {
  195715. switch ((int)bit_depth)
  195716. {
  195717. case 1:
  195718. {
  195719. png_bytep sp, dp;
  195720. int mask, v;
  195721. png_uint_32 i;
  195722. png_uint_32 row_width = row_info->width;
  195723. sp = row;
  195724. dp = row;
  195725. mask = 0x80;
  195726. v = 0;
  195727. for (i = 0; i < row_width; i++)
  195728. {
  195729. if (*sp != 0)
  195730. v |= mask;
  195731. sp++;
  195732. if (mask > 1)
  195733. mask >>= 1;
  195734. else
  195735. {
  195736. mask = 0x80;
  195737. *dp = (png_byte)v;
  195738. dp++;
  195739. v = 0;
  195740. }
  195741. }
  195742. if (mask != 0x80)
  195743. *dp = (png_byte)v;
  195744. break;
  195745. }
  195746. case 2:
  195747. {
  195748. png_bytep sp, dp;
  195749. int shift, v;
  195750. png_uint_32 i;
  195751. png_uint_32 row_width = row_info->width;
  195752. sp = row;
  195753. dp = row;
  195754. shift = 6;
  195755. v = 0;
  195756. for (i = 0; i < row_width; i++)
  195757. {
  195758. png_byte value;
  195759. value = (png_byte)(*sp & 0x03);
  195760. v |= (value << shift);
  195761. if (shift == 0)
  195762. {
  195763. shift = 6;
  195764. *dp = (png_byte)v;
  195765. dp++;
  195766. v = 0;
  195767. }
  195768. else
  195769. shift -= 2;
  195770. sp++;
  195771. }
  195772. if (shift != 6)
  195773. *dp = (png_byte)v;
  195774. break;
  195775. }
  195776. case 4:
  195777. {
  195778. png_bytep sp, dp;
  195779. int shift, v;
  195780. png_uint_32 i;
  195781. png_uint_32 row_width = row_info->width;
  195782. sp = row;
  195783. dp = row;
  195784. shift = 4;
  195785. v = 0;
  195786. for (i = 0; i < row_width; i++)
  195787. {
  195788. png_byte value;
  195789. value = (png_byte)(*sp & 0x0f);
  195790. v |= (value << shift);
  195791. if (shift == 0)
  195792. {
  195793. shift = 4;
  195794. *dp = (png_byte)v;
  195795. dp++;
  195796. v = 0;
  195797. }
  195798. else
  195799. shift -= 4;
  195800. sp++;
  195801. }
  195802. if (shift != 4)
  195803. *dp = (png_byte)v;
  195804. break;
  195805. }
  195806. }
  195807. row_info->bit_depth = (png_byte)bit_depth;
  195808. row_info->pixel_depth = (png_byte)(bit_depth * row_info->channels);
  195809. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  195810. row_info->width);
  195811. }
  195812. }
  195813. #endif
  195814. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  195815. /* Shift pixel values to take advantage of whole range. Pass the
  195816. * true number of bits in bit_depth. The row should be packed
  195817. * according to row_info->bit_depth. Thus, if you had a row of
  195818. * bit depth 4, but the pixels only had values from 0 to 7, you
  195819. * would pass 3 as bit_depth, and this routine would translate the
  195820. * data to 0 to 15.
  195821. */
  195822. void /* PRIVATE */
  195823. png_do_shift(png_row_infop row_info, png_bytep row, png_color_8p bit_depth)
  195824. {
  195825. png_debug(1, "in png_do_shift\n");
  195826. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  195827. if (row != NULL && row_info != NULL &&
  195828. #else
  195829. if (
  195830. #endif
  195831. row_info->color_type != PNG_COLOR_TYPE_PALETTE)
  195832. {
  195833. int shift_start[4], shift_dec[4];
  195834. int channels = 0;
  195835. if (row_info->color_type & PNG_COLOR_MASK_COLOR)
  195836. {
  195837. shift_start[channels] = row_info->bit_depth - bit_depth->red;
  195838. shift_dec[channels] = bit_depth->red;
  195839. channels++;
  195840. shift_start[channels] = row_info->bit_depth - bit_depth->green;
  195841. shift_dec[channels] = bit_depth->green;
  195842. channels++;
  195843. shift_start[channels] = row_info->bit_depth - bit_depth->blue;
  195844. shift_dec[channels] = bit_depth->blue;
  195845. channels++;
  195846. }
  195847. else
  195848. {
  195849. shift_start[channels] = row_info->bit_depth - bit_depth->gray;
  195850. shift_dec[channels] = bit_depth->gray;
  195851. channels++;
  195852. }
  195853. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  195854. {
  195855. shift_start[channels] = row_info->bit_depth - bit_depth->alpha;
  195856. shift_dec[channels] = bit_depth->alpha;
  195857. channels++;
  195858. }
  195859. /* with low row depths, could only be grayscale, so one channel */
  195860. if (row_info->bit_depth < 8)
  195861. {
  195862. png_bytep bp = row;
  195863. png_uint_32 i;
  195864. png_byte mask;
  195865. png_uint_32 row_bytes = row_info->rowbytes;
  195866. if (bit_depth->gray == 1 && row_info->bit_depth == 2)
  195867. mask = 0x55;
  195868. else if (row_info->bit_depth == 4 && bit_depth->gray == 3)
  195869. mask = 0x11;
  195870. else
  195871. mask = 0xff;
  195872. for (i = 0; i < row_bytes; i++, bp++)
  195873. {
  195874. png_uint_16 v;
  195875. int j;
  195876. v = *bp;
  195877. *bp = 0;
  195878. for (j = shift_start[0]; j > -shift_dec[0]; j -= shift_dec[0])
  195879. {
  195880. if (j > 0)
  195881. *bp |= (png_byte)((v << j) & 0xff);
  195882. else
  195883. *bp |= (png_byte)((v >> (-j)) & mask);
  195884. }
  195885. }
  195886. }
  195887. else if (row_info->bit_depth == 8)
  195888. {
  195889. png_bytep bp = row;
  195890. png_uint_32 i;
  195891. png_uint_32 istop = channels * row_info->width;
  195892. for (i = 0; i < istop; i++, bp++)
  195893. {
  195894. png_uint_16 v;
  195895. int j;
  195896. int c = (int)(i%channels);
  195897. v = *bp;
  195898. *bp = 0;
  195899. for (j = shift_start[c]; j > -shift_dec[c]; j -= shift_dec[c])
  195900. {
  195901. if (j > 0)
  195902. *bp |= (png_byte)((v << j) & 0xff);
  195903. else
  195904. *bp |= (png_byte)((v >> (-j)) & 0xff);
  195905. }
  195906. }
  195907. }
  195908. else
  195909. {
  195910. png_bytep bp;
  195911. png_uint_32 i;
  195912. png_uint_32 istop = channels * row_info->width;
  195913. for (bp = row, i = 0; i < istop; i++)
  195914. {
  195915. int c = (int)(i%channels);
  195916. png_uint_16 value, v;
  195917. int j;
  195918. v = (png_uint_16)(((png_uint_16)(*bp) << 8) + *(bp + 1));
  195919. value = 0;
  195920. for (j = shift_start[c]; j > -shift_dec[c]; j -= shift_dec[c])
  195921. {
  195922. if (j > 0)
  195923. value |= (png_uint_16)((v << j) & (png_uint_16)0xffff);
  195924. else
  195925. value |= (png_uint_16)((v >> (-j)) & (png_uint_16)0xffff);
  195926. }
  195927. *bp++ = (png_byte)(value >> 8);
  195928. *bp++ = (png_byte)(value & 0xff);
  195929. }
  195930. }
  195931. }
  195932. }
  195933. #endif
  195934. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  195935. void /* PRIVATE */
  195936. png_do_write_swap_alpha(png_row_infop row_info, png_bytep row)
  195937. {
  195938. png_debug(1, "in png_do_write_swap_alpha\n");
  195939. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  195940. if (row != NULL && row_info != NULL)
  195941. #endif
  195942. {
  195943. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  195944. {
  195945. /* This converts from ARGB to RGBA */
  195946. if (row_info->bit_depth == 8)
  195947. {
  195948. png_bytep sp, dp;
  195949. png_uint_32 i;
  195950. png_uint_32 row_width = row_info->width;
  195951. for (i = 0, sp = dp = row; i < row_width; i++)
  195952. {
  195953. png_byte save = *(sp++);
  195954. *(dp++) = *(sp++);
  195955. *(dp++) = *(sp++);
  195956. *(dp++) = *(sp++);
  195957. *(dp++) = save;
  195958. }
  195959. }
  195960. /* This converts from AARRGGBB to RRGGBBAA */
  195961. else
  195962. {
  195963. png_bytep sp, dp;
  195964. png_uint_32 i;
  195965. png_uint_32 row_width = row_info->width;
  195966. for (i = 0, sp = dp = row; i < row_width; i++)
  195967. {
  195968. png_byte save[2];
  195969. save[0] = *(sp++);
  195970. save[1] = *(sp++);
  195971. *(dp++) = *(sp++);
  195972. *(dp++) = *(sp++);
  195973. *(dp++) = *(sp++);
  195974. *(dp++) = *(sp++);
  195975. *(dp++) = *(sp++);
  195976. *(dp++) = *(sp++);
  195977. *(dp++) = save[0];
  195978. *(dp++) = save[1];
  195979. }
  195980. }
  195981. }
  195982. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  195983. {
  195984. /* This converts from AG to GA */
  195985. if (row_info->bit_depth == 8)
  195986. {
  195987. png_bytep sp, dp;
  195988. png_uint_32 i;
  195989. png_uint_32 row_width = row_info->width;
  195990. for (i = 0, sp = dp = row; i < row_width; i++)
  195991. {
  195992. png_byte save = *(sp++);
  195993. *(dp++) = *(sp++);
  195994. *(dp++) = save;
  195995. }
  195996. }
  195997. /* This converts from AAGG to GGAA */
  195998. else
  195999. {
  196000. png_bytep sp, dp;
  196001. png_uint_32 i;
  196002. png_uint_32 row_width = row_info->width;
  196003. for (i = 0, sp = dp = row; i < row_width; i++)
  196004. {
  196005. png_byte save[2];
  196006. save[0] = *(sp++);
  196007. save[1] = *(sp++);
  196008. *(dp++) = *(sp++);
  196009. *(dp++) = *(sp++);
  196010. *(dp++) = save[0];
  196011. *(dp++) = save[1];
  196012. }
  196013. }
  196014. }
  196015. }
  196016. }
  196017. #endif
  196018. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  196019. void /* PRIVATE */
  196020. png_do_write_invert_alpha(png_row_infop row_info, png_bytep row)
  196021. {
  196022. png_debug(1, "in png_do_write_invert_alpha\n");
  196023. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  196024. if (row != NULL && row_info != NULL)
  196025. #endif
  196026. {
  196027. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  196028. {
  196029. /* This inverts the alpha channel in RGBA */
  196030. if (row_info->bit_depth == 8)
  196031. {
  196032. png_bytep sp, dp;
  196033. png_uint_32 i;
  196034. png_uint_32 row_width = row_info->width;
  196035. for (i = 0, sp = dp = row; i < row_width; i++)
  196036. {
  196037. /* does nothing
  196038. *(dp++) = *(sp++);
  196039. *(dp++) = *(sp++);
  196040. *(dp++) = *(sp++);
  196041. */
  196042. sp+=3; dp = sp;
  196043. *(dp++) = (png_byte)(255 - *(sp++));
  196044. }
  196045. }
  196046. /* This inverts the alpha channel in RRGGBBAA */
  196047. else
  196048. {
  196049. png_bytep sp, dp;
  196050. png_uint_32 i;
  196051. png_uint_32 row_width = row_info->width;
  196052. for (i = 0, sp = dp = row; i < row_width; i++)
  196053. {
  196054. /* does nothing
  196055. *(dp++) = *(sp++);
  196056. *(dp++) = *(sp++);
  196057. *(dp++) = *(sp++);
  196058. *(dp++) = *(sp++);
  196059. *(dp++) = *(sp++);
  196060. *(dp++) = *(sp++);
  196061. */
  196062. sp+=6; dp = sp;
  196063. *(dp++) = (png_byte)(255 - *(sp++));
  196064. *(dp++) = (png_byte)(255 - *(sp++));
  196065. }
  196066. }
  196067. }
  196068. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  196069. {
  196070. /* This inverts the alpha channel in GA */
  196071. if (row_info->bit_depth == 8)
  196072. {
  196073. png_bytep sp, dp;
  196074. png_uint_32 i;
  196075. png_uint_32 row_width = row_info->width;
  196076. for (i = 0, sp = dp = row; i < row_width; i++)
  196077. {
  196078. *(dp++) = *(sp++);
  196079. *(dp++) = (png_byte)(255 - *(sp++));
  196080. }
  196081. }
  196082. /* This inverts the alpha channel in GGAA */
  196083. else
  196084. {
  196085. png_bytep sp, dp;
  196086. png_uint_32 i;
  196087. png_uint_32 row_width = row_info->width;
  196088. for (i = 0, sp = dp = row; i < row_width; i++)
  196089. {
  196090. /* does nothing
  196091. *(dp++) = *(sp++);
  196092. *(dp++) = *(sp++);
  196093. */
  196094. sp+=2; dp = sp;
  196095. *(dp++) = (png_byte)(255 - *(sp++));
  196096. *(dp++) = (png_byte)(255 - *(sp++));
  196097. }
  196098. }
  196099. }
  196100. }
  196101. }
  196102. #endif
  196103. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  196104. /* undoes intrapixel differencing */
  196105. void /* PRIVATE */
  196106. png_do_write_intrapixel(png_row_infop row_info, png_bytep row)
  196107. {
  196108. png_debug(1, "in png_do_write_intrapixel\n");
  196109. if (
  196110. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  196111. row != NULL && row_info != NULL &&
  196112. #endif
  196113. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  196114. {
  196115. int bytes_per_pixel;
  196116. png_uint_32 row_width = row_info->width;
  196117. if (row_info->bit_depth == 8)
  196118. {
  196119. png_bytep rp;
  196120. png_uint_32 i;
  196121. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  196122. bytes_per_pixel = 3;
  196123. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  196124. bytes_per_pixel = 4;
  196125. else
  196126. return;
  196127. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  196128. {
  196129. *(rp) = (png_byte)((*rp - *(rp+1))&0xff);
  196130. *(rp+2) = (png_byte)((*(rp+2) - *(rp+1))&0xff);
  196131. }
  196132. }
  196133. else if (row_info->bit_depth == 16)
  196134. {
  196135. png_bytep rp;
  196136. png_uint_32 i;
  196137. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  196138. bytes_per_pixel = 6;
  196139. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  196140. bytes_per_pixel = 8;
  196141. else
  196142. return;
  196143. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  196144. {
  196145. png_uint_32 s0 = (*(rp ) << 8) | *(rp+1);
  196146. png_uint_32 s1 = (*(rp+2) << 8) | *(rp+3);
  196147. png_uint_32 s2 = (*(rp+4) << 8) | *(rp+5);
  196148. png_uint_32 red = (png_uint_32)((s0-s1) & 0xffffL);
  196149. png_uint_32 blue = (png_uint_32)((s2-s1) & 0xffffL);
  196150. *(rp ) = (png_byte)((red >> 8) & 0xff);
  196151. *(rp+1) = (png_byte)(red & 0xff);
  196152. *(rp+4) = (png_byte)((blue >> 8) & 0xff);
  196153. *(rp+5) = (png_byte)(blue & 0xff);
  196154. }
  196155. }
  196156. }
  196157. }
  196158. #endif /* PNG_MNG_FEATURES_SUPPORTED */
  196159. #endif /* PNG_WRITE_SUPPORTED */
  196160. /********* End of inlined file: pngwtran.c *********/
  196161. /********* Start of inlined file: pngwutil.c *********/
  196162. /* pngwutil.c - utilities to write a PNG file
  196163. *
  196164. * Last changed in libpng 1.2.20 Septhember 3, 2007
  196165. * For conditions of distribution and use, see copyright notice in png.h
  196166. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  196167. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  196168. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  196169. */
  196170. #define PNG_INTERNAL
  196171. #ifdef PNG_WRITE_SUPPORTED
  196172. /* Place a 32-bit number into a buffer in PNG byte order. We work
  196173. * with unsigned numbers for convenience, although one supported
  196174. * ancillary chunk uses signed (two's complement) numbers.
  196175. */
  196176. void PNGAPI
  196177. png_save_uint_32(png_bytep buf, png_uint_32 i)
  196178. {
  196179. buf[0] = (png_byte)((i >> 24) & 0xff);
  196180. buf[1] = (png_byte)((i >> 16) & 0xff);
  196181. buf[2] = (png_byte)((i >> 8) & 0xff);
  196182. buf[3] = (png_byte)(i & 0xff);
  196183. }
  196184. /* The png_save_int_32 function assumes integers are stored in two's
  196185. * complement format. If this isn't the case, then this routine needs to
  196186. * be modified to write data in two's complement format.
  196187. */
  196188. void PNGAPI
  196189. png_save_int_32(png_bytep buf, png_int_32 i)
  196190. {
  196191. buf[0] = (png_byte)((i >> 24) & 0xff);
  196192. buf[1] = (png_byte)((i >> 16) & 0xff);
  196193. buf[2] = (png_byte)((i >> 8) & 0xff);
  196194. buf[3] = (png_byte)(i & 0xff);
  196195. }
  196196. /* Place a 16-bit number into a buffer in PNG byte order.
  196197. * The parameter is declared unsigned int, not png_uint_16,
  196198. * just to avoid potential problems on pre-ANSI C compilers.
  196199. */
  196200. void PNGAPI
  196201. png_save_uint_16(png_bytep buf, unsigned int i)
  196202. {
  196203. buf[0] = (png_byte)((i >> 8) & 0xff);
  196204. buf[1] = (png_byte)(i & 0xff);
  196205. }
  196206. /* Write a PNG chunk all at once. The type is an array of ASCII characters
  196207. * representing the chunk name. The array must be at least 4 bytes in
  196208. * length, and does not need to be null terminated. To be safe, pass the
  196209. * pre-defined chunk names here, and if you need a new one, define it
  196210. * where the others are defined. The length is the length of the data.
  196211. * All the data must be present. If that is not possible, use the
  196212. * png_write_chunk_start(), png_write_chunk_data(), and png_write_chunk_end()
  196213. * functions instead.
  196214. */
  196215. void PNGAPI
  196216. png_write_chunk(png_structp png_ptr, png_bytep chunk_name,
  196217. png_bytep data, png_size_t length)
  196218. {
  196219. if(png_ptr == NULL) return;
  196220. png_write_chunk_start(png_ptr, chunk_name, (png_uint_32)length);
  196221. png_write_chunk_data(png_ptr, data, length);
  196222. png_write_chunk_end(png_ptr);
  196223. }
  196224. /* Write the start of a PNG chunk. The type is the chunk type.
  196225. * The total_length is the sum of the lengths of all the data you will be
  196226. * passing in png_write_chunk_data().
  196227. */
  196228. void PNGAPI
  196229. png_write_chunk_start(png_structp png_ptr, png_bytep chunk_name,
  196230. png_uint_32 length)
  196231. {
  196232. png_byte buf[4];
  196233. png_debug2(0, "Writing %s chunk (%lu bytes)\n", chunk_name, length);
  196234. if(png_ptr == NULL) return;
  196235. /* write the length */
  196236. png_save_uint_32(buf, length);
  196237. png_write_data(png_ptr, buf, (png_size_t)4);
  196238. /* write the chunk name */
  196239. png_write_data(png_ptr, chunk_name, (png_size_t)4);
  196240. /* reset the crc and run it over the chunk name */
  196241. png_reset_crc(png_ptr);
  196242. png_calculate_crc(png_ptr, chunk_name, (png_size_t)4);
  196243. }
  196244. /* Write the data of a PNG chunk started with png_write_chunk_start().
  196245. * Note that multiple calls to this function are allowed, and that the
  196246. * sum of the lengths from these calls *must* add up to the total_length
  196247. * given to png_write_chunk_start().
  196248. */
  196249. void PNGAPI
  196250. png_write_chunk_data(png_structp png_ptr, png_bytep data, png_size_t length)
  196251. {
  196252. /* write the data, and run the CRC over it */
  196253. if(png_ptr == NULL) return;
  196254. if (data != NULL && length > 0)
  196255. {
  196256. png_calculate_crc(png_ptr, data, length);
  196257. png_write_data(png_ptr, data, length);
  196258. }
  196259. }
  196260. /* Finish a chunk started with png_write_chunk_start(). */
  196261. void PNGAPI
  196262. png_write_chunk_end(png_structp png_ptr)
  196263. {
  196264. png_byte buf[4];
  196265. if(png_ptr == NULL) return;
  196266. /* write the crc */
  196267. png_save_uint_32(buf, png_ptr->crc);
  196268. png_write_data(png_ptr, buf, (png_size_t)4);
  196269. }
  196270. /* Simple function to write the signature. If we have already written
  196271. * the magic bytes of the signature, or more likely, the PNG stream is
  196272. * being embedded into another stream and doesn't need its own signature,
  196273. * we should call png_set_sig_bytes() to tell libpng how many of the
  196274. * bytes have already been written.
  196275. */
  196276. void /* PRIVATE */
  196277. png_write_sig(png_structp png_ptr)
  196278. {
  196279. png_byte png_signature[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  196280. /* write the rest of the 8 byte signature */
  196281. png_write_data(png_ptr, &png_signature[png_ptr->sig_bytes],
  196282. (png_size_t)8 - png_ptr->sig_bytes);
  196283. if(png_ptr->sig_bytes < 3)
  196284. png_ptr->mode |= PNG_HAVE_PNG_SIGNATURE;
  196285. }
  196286. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_iCCP_SUPPORTED)
  196287. /*
  196288. * This pair of functions encapsulates the operation of (a) compressing a
  196289. * text string, and (b) issuing it later as a series of chunk data writes.
  196290. * The compression_state structure is shared context for these functions
  196291. * set up by the caller in order to make the whole mess thread-safe.
  196292. */
  196293. typedef struct
  196294. {
  196295. char *input; /* the uncompressed input data */
  196296. int input_len; /* its length */
  196297. int num_output_ptr; /* number of output pointers used */
  196298. int max_output_ptr; /* size of output_ptr */
  196299. png_charpp output_ptr; /* array of pointers to output */
  196300. } compression_state;
  196301. /* compress given text into storage in the png_ptr structure */
  196302. static int /* PRIVATE */
  196303. png_text_compress(png_structp png_ptr,
  196304. png_charp text, png_size_t text_len, int compression,
  196305. compression_state *comp)
  196306. {
  196307. int ret;
  196308. comp->num_output_ptr = 0;
  196309. comp->max_output_ptr = 0;
  196310. comp->output_ptr = NULL;
  196311. comp->input = NULL;
  196312. comp->input_len = 0;
  196313. /* we may just want to pass the text right through */
  196314. if (compression == PNG_TEXT_COMPRESSION_NONE)
  196315. {
  196316. comp->input = text;
  196317. comp->input_len = text_len;
  196318. return((int)text_len);
  196319. }
  196320. if (compression >= PNG_TEXT_COMPRESSION_LAST)
  196321. {
  196322. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  196323. char msg[50];
  196324. png_snprintf(msg, 50, "Unknown compression type %d", compression);
  196325. png_warning(png_ptr, msg);
  196326. #else
  196327. png_warning(png_ptr, "Unknown compression type");
  196328. #endif
  196329. }
  196330. /* We can't write the chunk until we find out how much data we have,
  196331. * which means we need to run the compressor first and save the
  196332. * output. This shouldn't be a problem, as the vast majority of
  196333. * comments should be reasonable, but we will set up an array of
  196334. * malloc'd pointers to be sure.
  196335. *
  196336. * If we knew the application was well behaved, we could simplify this
  196337. * greatly by assuming we can always malloc an output buffer large
  196338. * enough to hold the compressed text ((1001 * text_len / 1000) + 12)
  196339. * and malloc this directly. The only time this would be a bad idea is
  196340. * if we can't malloc more than 64K and we have 64K of random input
  196341. * data, or if the input string is incredibly large (although this
  196342. * wouldn't cause a failure, just a slowdown due to swapping).
  196343. */
  196344. /* set up the compression buffers */
  196345. png_ptr->zstream.avail_in = (uInt)text_len;
  196346. png_ptr->zstream.next_in = (Bytef *)text;
  196347. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  196348. png_ptr->zstream.next_out = (Bytef *)png_ptr->zbuf;
  196349. /* this is the same compression loop as in png_write_row() */
  196350. do
  196351. {
  196352. /* compress the data */
  196353. ret = deflate(&png_ptr->zstream, Z_NO_FLUSH);
  196354. if (ret != Z_OK)
  196355. {
  196356. /* error */
  196357. if (png_ptr->zstream.msg != NULL)
  196358. png_error(png_ptr, png_ptr->zstream.msg);
  196359. else
  196360. png_error(png_ptr, "zlib error");
  196361. }
  196362. /* check to see if we need more room */
  196363. if (!(png_ptr->zstream.avail_out))
  196364. {
  196365. /* make sure the output array has room */
  196366. if (comp->num_output_ptr >= comp->max_output_ptr)
  196367. {
  196368. int old_max;
  196369. old_max = comp->max_output_ptr;
  196370. comp->max_output_ptr = comp->num_output_ptr + 4;
  196371. if (comp->output_ptr != NULL)
  196372. {
  196373. png_charpp old_ptr;
  196374. old_ptr = comp->output_ptr;
  196375. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  196376. (png_uint_32)(comp->max_output_ptr *
  196377. png_sizeof (png_charpp)));
  196378. png_memcpy(comp->output_ptr, old_ptr, old_max
  196379. * png_sizeof (png_charp));
  196380. png_free(png_ptr, old_ptr);
  196381. }
  196382. else
  196383. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  196384. (png_uint_32)(comp->max_output_ptr *
  196385. png_sizeof (png_charp)));
  196386. }
  196387. /* save the data */
  196388. comp->output_ptr[comp->num_output_ptr] = (png_charp)png_malloc(png_ptr,
  196389. (png_uint_32)png_ptr->zbuf_size);
  196390. png_memcpy(comp->output_ptr[comp->num_output_ptr], png_ptr->zbuf,
  196391. png_ptr->zbuf_size);
  196392. comp->num_output_ptr++;
  196393. /* and reset the buffer */
  196394. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  196395. png_ptr->zstream.next_out = png_ptr->zbuf;
  196396. }
  196397. /* continue until we don't have any more to compress */
  196398. } while (png_ptr->zstream.avail_in);
  196399. /* finish the compression */
  196400. do
  196401. {
  196402. /* tell zlib we are finished */
  196403. ret = deflate(&png_ptr->zstream, Z_FINISH);
  196404. if (ret == Z_OK)
  196405. {
  196406. /* check to see if we need more room */
  196407. if (!(png_ptr->zstream.avail_out))
  196408. {
  196409. /* check to make sure our output array has room */
  196410. if (comp->num_output_ptr >= comp->max_output_ptr)
  196411. {
  196412. int old_max;
  196413. old_max = comp->max_output_ptr;
  196414. comp->max_output_ptr = comp->num_output_ptr + 4;
  196415. if (comp->output_ptr != NULL)
  196416. {
  196417. png_charpp old_ptr;
  196418. old_ptr = comp->output_ptr;
  196419. /* This could be optimized to realloc() */
  196420. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  196421. (png_uint_32)(comp->max_output_ptr *
  196422. png_sizeof (png_charpp)));
  196423. png_memcpy(comp->output_ptr, old_ptr,
  196424. old_max * png_sizeof (png_charp));
  196425. png_free(png_ptr, old_ptr);
  196426. }
  196427. else
  196428. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  196429. (png_uint_32)(comp->max_output_ptr *
  196430. png_sizeof (png_charp)));
  196431. }
  196432. /* save off the data */
  196433. comp->output_ptr[comp->num_output_ptr] =
  196434. (png_charp)png_malloc(png_ptr, (png_uint_32)png_ptr->zbuf_size);
  196435. png_memcpy(comp->output_ptr[comp->num_output_ptr], png_ptr->zbuf,
  196436. png_ptr->zbuf_size);
  196437. comp->num_output_ptr++;
  196438. /* and reset the buffer pointers */
  196439. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  196440. png_ptr->zstream.next_out = png_ptr->zbuf;
  196441. }
  196442. }
  196443. else if (ret != Z_STREAM_END)
  196444. {
  196445. /* we got an error */
  196446. if (png_ptr->zstream.msg != NULL)
  196447. png_error(png_ptr, png_ptr->zstream.msg);
  196448. else
  196449. png_error(png_ptr, "zlib error");
  196450. }
  196451. } while (ret != Z_STREAM_END);
  196452. /* text length is number of buffers plus last buffer */
  196453. text_len = png_ptr->zbuf_size * comp->num_output_ptr;
  196454. if (png_ptr->zstream.avail_out < png_ptr->zbuf_size)
  196455. text_len += png_ptr->zbuf_size - (png_size_t)png_ptr->zstream.avail_out;
  196456. return((int)text_len);
  196457. }
  196458. /* ship the compressed text out via chunk writes */
  196459. static void /* PRIVATE */
  196460. png_write_compressed_data_out(png_structp png_ptr, compression_state *comp)
  196461. {
  196462. int i;
  196463. /* handle the no-compression case */
  196464. if (comp->input)
  196465. {
  196466. png_write_chunk_data(png_ptr, (png_bytep)comp->input,
  196467. (png_size_t)comp->input_len);
  196468. return;
  196469. }
  196470. /* write saved output buffers, if any */
  196471. for (i = 0; i < comp->num_output_ptr; i++)
  196472. {
  196473. png_write_chunk_data(png_ptr,(png_bytep)comp->output_ptr[i],
  196474. png_ptr->zbuf_size);
  196475. png_free(png_ptr, comp->output_ptr[i]);
  196476. comp->output_ptr[i]=NULL;
  196477. }
  196478. if (comp->max_output_ptr != 0)
  196479. png_free(png_ptr, comp->output_ptr);
  196480. comp->output_ptr=NULL;
  196481. /* write anything left in zbuf */
  196482. if (png_ptr->zstream.avail_out < (png_uint_32)png_ptr->zbuf_size)
  196483. png_write_chunk_data(png_ptr, png_ptr->zbuf,
  196484. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  196485. /* reset zlib for another zTXt/iTXt or image data */
  196486. deflateReset(&png_ptr->zstream);
  196487. png_ptr->zstream.data_type = Z_BINARY;
  196488. }
  196489. #endif
  196490. /* Write the IHDR chunk, and update the png_struct with the necessary
  196491. * information. Note that the rest of this code depends upon this
  196492. * information being correct.
  196493. */
  196494. void /* PRIVATE */
  196495. png_write_IHDR(png_structp png_ptr, png_uint_32 width, png_uint_32 height,
  196496. int bit_depth, int color_type, int compression_type, int filter_type,
  196497. int interlace_type)
  196498. {
  196499. #ifdef PNG_USE_LOCAL_ARRAYS
  196500. PNG_IHDR;
  196501. #endif
  196502. png_byte buf[13]; /* buffer to store the IHDR info */
  196503. png_debug(1, "in png_write_IHDR\n");
  196504. /* Check that we have valid input data from the application info */
  196505. switch (color_type)
  196506. {
  196507. case PNG_COLOR_TYPE_GRAY:
  196508. switch (bit_depth)
  196509. {
  196510. case 1:
  196511. case 2:
  196512. case 4:
  196513. case 8:
  196514. case 16: png_ptr->channels = 1; break;
  196515. default: png_error(png_ptr,"Invalid bit depth for grayscale image");
  196516. }
  196517. break;
  196518. case PNG_COLOR_TYPE_RGB:
  196519. if (bit_depth != 8 && bit_depth != 16)
  196520. png_error(png_ptr, "Invalid bit depth for RGB image");
  196521. png_ptr->channels = 3;
  196522. break;
  196523. case PNG_COLOR_TYPE_PALETTE:
  196524. switch (bit_depth)
  196525. {
  196526. case 1:
  196527. case 2:
  196528. case 4:
  196529. case 8: png_ptr->channels = 1; break;
  196530. default: png_error(png_ptr, "Invalid bit depth for paletted image");
  196531. }
  196532. break;
  196533. case PNG_COLOR_TYPE_GRAY_ALPHA:
  196534. if (bit_depth != 8 && bit_depth != 16)
  196535. png_error(png_ptr, "Invalid bit depth for grayscale+alpha image");
  196536. png_ptr->channels = 2;
  196537. break;
  196538. case PNG_COLOR_TYPE_RGB_ALPHA:
  196539. if (bit_depth != 8 && bit_depth != 16)
  196540. png_error(png_ptr, "Invalid bit depth for RGBA image");
  196541. png_ptr->channels = 4;
  196542. break;
  196543. default:
  196544. png_error(png_ptr, "Invalid image color type specified");
  196545. }
  196546. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  196547. {
  196548. png_warning(png_ptr, "Invalid compression type specified");
  196549. compression_type = PNG_COMPRESSION_TYPE_BASE;
  196550. }
  196551. /* Write filter_method 64 (intrapixel differencing) only if
  196552. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  196553. * 2. Libpng did not write a PNG signature (this filter_method is only
  196554. * used in PNG datastreams that are embedded in MNG datastreams) and
  196555. * 3. The application called png_permit_mng_features with a mask that
  196556. * included PNG_FLAG_MNG_FILTER_64 and
  196557. * 4. The filter_method is 64 and
  196558. * 5. The color_type is RGB or RGBA
  196559. */
  196560. if (
  196561. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  196562. !((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  196563. ((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE) == 0) &&
  196564. (color_type == PNG_COLOR_TYPE_RGB ||
  196565. color_type == PNG_COLOR_TYPE_RGB_ALPHA) &&
  196566. (filter_type == PNG_INTRAPIXEL_DIFFERENCING)) &&
  196567. #endif
  196568. filter_type != PNG_FILTER_TYPE_BASE)
  196569. {
  196570. png_warning(png_ptr, "Invalid filter type specified");
  196571. filter_type = PNG_FILTER_TYPE_BASE;
  196572. }
  196573. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  196574. if (interlace_type != PNG_INTERLACE_NONE &&
  196575. interlace_type != PNG_INTERLACE_ADAM7)
  196576. {
  196577. png_warning(png_ptr, "Invalid interlace type specified");
  196578. interlace_type = PNG_INTERLACE_ADAM7;
  196579. }
  196580. #else
  196581. interlace_type=PNG_INTERLACE_NONE;
  196582. #endif
  196583. /* save off the relevent information */
  196584. png_ptr->bit_depth = (png_byte)bit_depth;
  196585. png_ptr->color_type = (png_byte)color_type;
  196586. png_ptr->interlaced = (png_byte)interlace_type;
  196587. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  196588. png_ptr->filter_type = (png_byte)filter_type;
  196589. #endif
  196590. png_ptr->compression_type = (png_byte)compression_type;
  196591. png_ptr->width = width;
  196592. png_ptr->height = height;
  196593. png_ptr->pixel_depth = (png_byte)(bit_depth * png_ptr->channels);
  196594. png_ptr->rowbytes = PNG_ROWBYTES(png_ptr->pixel_depth, width);
  196595. /* set the usr info, so any transformations can modify it */
  196596. png_ptr->usr_width = png_ptr->width;
  196597. png_ptr->usr_bit_depth = png_ptr->bit_depth;
  196598. png_ptr->usr_channels = png_ptr->channels;
  196599. /* pack the header information into the buffer */
  196600. png_save_uint_32(buf, width);
  196601. png_save_uint_32(buf + 4, height);
  196602. buf[8] = (png_byte)bit_depth;
  196603. buf[9] = (png_byte)color_type;
  196604. buf[10] = (png_byte)compression_type;
  196605. buf[11] = (png_byte)filter_type;
  196606. buf[12] = (png_byte)interlace_type;
  196607. /* write the chunk */
  196608. png_write_chunk(png_ptr, png_IHDR, buf, (png_size_t)13);
  196609. /* initialize zlib with PNG info */
  196610. png_ptr->zstream.zalloc = png_zalloc;
  196611. png_ptr->zstream.zfree = png_zfree;
  196612. png_ptr->zstream.opaque = (voidpf)png_ptr;
  196613. if (!(png_ptr->do_filter))
  196614. {
  196615. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE ||
  196616. png_ptr->bit_depth < 8)
  196617. png_ptr->do_filter = PNG_FILTER_NONE;
  196618. else
  196619. png_ptr->do_filter = PNG_ALL_FILTERS;
  196620. }
  196621. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_STRATEGY))
  196622. {
  196623. if (png_ptr->do_filter != PNG_FILTER_NONE)
  196624. png_ptr->zlib_strategy = Z_FILTERED;
  196625. else
  196626. png_ptr->zlib_strategy = Z_DEFAULT_STRATEGY;
  196627. }
  196628. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_LEVEL))
  196629. png_ptr->zlib_level = Z_DEFAULT_COMPRESSION;
  196630. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL))
  196631. png_ptr->zlib_mem_level = 8;
  196632. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS))
  196633. png_ptr->zlib_window_bits = 15;
  196634. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_METHOD))
  196635. png_ptr->zlib_method = 8;
  196636. if (deflateInit2(&png_ptr->zstream, png_ptr->zlib_level,
  196637. png_ptr->zlib_method, png_ptr->zlib_window_bits,
  196638. png_ptr->zlib_mem_level, png_ptr->zlib_strategy) != Z_OK)
  196639. png_error(png_ptr, "zlib failed to initialize compressor");
  196640. png_ptr->zstream.next_out = png_ptr->zbuf;
  196641. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  196642. /* libpng is not interested in zstream.data_type */
  196643. /* set it to a predefined value, to avoid its evaluation inside zlib */
  196644. png_ptr->zstream.data_type = Z_BINARY;
  196645. png_ptr->mode = PNG_HAVE_IHDR;
  196646. }
  196647. /* write the palette. We are careful not to trust png_color to be in the
  196648. * correct order for PNG, so people can redefine it to any convenient
  196649. * structure.
  196650. */
  196651. void /* PRIVATE */
  196652. png_write_PLTE(png_structp png_ptr, png_colorp palette, png_uint_32 num_pal)
  196653. {
  196654. #ifdef PNG_USE_LOCAL_ARRAYS
  196655. PNG_PLTE;
  196656. #endif
  196657. png_uint_32 i;
  196658. png_colorp pal_ptr;
  196659. png_byte buf[3];
  196660. png_debug(1, "in png_write_PLTE\n");
  196661. if ((
  196662. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  196663. !(png_ptr->mng_features_permitted & PNG_FLAG_MNG_EMPTY_PLTE) &&
  196664. #endif
  196665. num_pal == 0) || num_pal > 256)
  196666. {
  196667. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  196668. {
  196669. png_error(png_ptr, "Invalid number of colors in palette");
  196670. }
  196671. else
  196672. {
  196673. png_warning(png_ptr, "Invalid number of colors in palette");
  196674. return;
  196675. }
  196676. }
  196677. if (!(png_ptr->color_type&PNG_COLOR_MASK_COLOR))
  196678. {
  196679. png_warning(png_ptr,
  196680. "Ignoring request to write a PLTE chunk in grayscale PNG");
  196681. return;
  196682. }
  196683. png_ptr->num_palette = (png_uint_16)num_pal;
  196684. png_debug1(3, "num_palette = %d\n", png_ptr->num_palette);
  196685. png_write_chunk_start(png_ptr, png_PLTE, num_pal * 3);
  196686. #ifndef PNG_NO_POINTER_INDEXING
  196687. for (i = 0, pal_ptr = palette; i < num_pal; i++, pal_ptr++)
  196688. {
  196689. buf[0] = pal_ptr->red;
  196690. buf[1] = pal_ptr->green;
  196691. buf[2] = pal_ptr->blue;
  196692. png_write_chunk_data(png_ptr, buf, (png_size_t)3);
  196693. }
  196694. #else
  196695. /* This is a little slower but some buggy compilers need to do this instead */
  196696. pal_ptr=palette;
  196697. for (i = 0; i < num_pal; i++)
  196698. {
  196699. buf[0] = pal_ptr[i].red;
  196700. buf[1] = pal_ptr[i].green;
  196701. buf[2] = pal_ptr[i].blue;
  196702. png_write_chunk_data(png_ptr, buf, (png_size_t)3);
  196703. }
  196704. #endif
  196705. png_write_chunk_end(png_ptr);
  196706. png_ptr->mode |= PNG_HAVE_PLTE;
  196707. }
  196708. /* write an IDAT chunk */
  196709. void /* PRIVATE */
  196710. png_write_IDAT(png_structp png_ptr, png_bytep data, png_size_t length)
  196711. {
  196712. #ifdef PNG_USE_LOCAL_ARRAYS
  196713. PNG_IDAT;
  196714. #endif
  196715. png_debug(1, "in png_write_IDAT\n");
  196716. /* Optimize the CMF field in the zlib stream. */
  196717. /* This hack of the zlib stream is compliant to the stream specification. */
  196718. if (!(png_ptr->mode & PNG_HAVE_IDAT) &&
  196719. png_ptr->compression_type == PNG_COMPRESSION_TYPE_BASE)
  196720. {
  196721. unsigned int z_cmf = data[0]; /* zlib compression method and flags */
  196722. if ((z_cmf & 0x0f) == 8 && (z_cmf & 0xf0) <= 0x70)
  196723. {
  196724. /* Avoid memory underflows and multiplication overflows. */
  196725. /* The conditions below are practically always satisfied;
  196726. however, they still must be checked. */
  196727. if (length >= 2 &&
  196728. png_ptr->height < 16384 && png_ptr->width < 16384)
  196729. {
  196730. png_uint_32 uncompressed_idat_size = png_ptr->height *
  196731. ((png_ptr->width *
  196732. png_ptr->channels * png_ptr->bit_depth + 15) >> 3);
  196733. unsigned int z_cinfo = z_cmf >> 4;
  196734. unsigned int half_z_window_size = 1 << (z_cinfo + 7);
  196735. while (uncompressed_idat_size <= half_z_window_size &&
  196736. half_z_window_size >= 256)
  196737. {
  196738. z_cinfo--;
  196739. half_z_window_size >>= 1;
  196740. }
  196741. z_cmf = (z_cmf & 0x0f) | (z_cinfo << 4);
  196742. if (data[0] != (png_byte)z_cmf)
  196743. {
  196744. data[0] = (png_byte)z_cmf;
  196745. data[1] &= 0xe0;
  196746. data[1] += (png_byte)(0x1f - ((z_cmf << 8) + data[1]) % 0x1f);
  196747. }
  196748. }
  196749. }
  196750. else
  196751. png_error(png_ptr,
  196752. "Invalid zlib compression method or flags in IDAT");
  196753. }
  196754. png_write_chunk(png_ptr, png_IDAT, data, length);
  196755. png_ptr->mode |= PNG_HAVE_IDAT;
  196756. }
  196757. /* write an IEND chunk */
  196758. void /* PRIVATE */
  196759. png_write_IEND(png_structp png_ptr)
  196760. {
  196761. #ifdef PNG_USE_LOCAL_ARRAYS
  196762. PNG_IEND;
  196763. #endif
  196764. png_debug(1, "in png_write_IEND\n");
  196765. png_write_chunk(png_ptr, png_IEND, png_bytep_NULL,
  196766. (png_size_t)0);
  196767. png_ptr->mode |= PNG_HAVE_IEND;
  196768. }
  196769. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  196770. /* write a gAMA chunk */
  196771. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196772. void /* PRIVATE */
  196773. png_write_gAMA(png_structp png_ptr, double file_gamma)
  196774. {
  196775. #ifdef PNG_USE_LOCAL_ARRAYS
  196776. PNG_gAMA;
  196777. #endif
  196778. png_uint_32 igamma;
  196779. png_byte buf[4];
  196780. png_debug(1, "in png_write_gAMA\n");
  196781. /* file_gamma is saved in 1/100,000ths */
  196782. igamma = (png_uint_32)(file_gamma * 100000.0 + 0.5);
  196783. png_save_uint_32(buf, igamma);
  196784. png_write_chunk(png_ptr, png_gAMA, buf, (png_size_t)4);
  196785. }
  196786. #endif
  196787. #ifdef PNG_FIXED_POINT_SUPPORTED
  196788. void /* PRIVATE */
  196789. png_write_gAMA_fixed(png_structp png_ptr, png_fixed_point file_gamma)
  196790. {
  196791. #ifdef PNG_USE_LOCAL_ARRAYS
  196792. PNG_gAMA;
  196793. #endif
  196794. png_byte buf[4];
  196795. png_debug(1, "in png_write_gAMA\n");
  196796. /* file_gamma is saved in 1/100,000ths */
  196797. png_save_uint_32(buf, (png_uint_32)file_gamma);
  196798. png_write_chunk(png_ptr, png_gAMA, buf, (png_size_t)4);
  196799. }
  196800. #endif
  196801. #endif
  196802. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  196803. /* write a sRGB chunk */
  196804. void /* PRIVATE */
  196805. png_write_sRGB(png_structp png_ptr, int srgb_intent)
  196806. {
  196807. #ifdef PNG_USE_LOCAL_ARRAYS
  196808. PNG_sRGB;
  196809. #endif
  196810. png_byte buf[1];
  196811. png_debug(1, "in png_write_sRGB\n");
  196812. if(srgb_intent >= PNG_sRGB_INTENT_LAST)
  196813. png_warning(png_ptr,
  196814. "Invalid sRGB rendering intent specified");
  196815. buf[0]=(png_byte)srgb_intent;
  196816. png_write_chunk(png_ptr, png_sRGB, buf, (png_size_t)1);
  196817. }
  196818. #endif
  196819. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  196820. /* write an iCCP chunk */
  196821. void /* PRIVATE */
  196822. png_write_iCCP(png_structp png_ptr, png_charp name, int compression_type,
  196823. png_charp profile, int profile_len)
  196824. {
  196825. #ifdef PNG_USE_LOCAL_ARRAYS
  196826. PNG_iCCP;
  196827. #endif
  196828. png_size_t name_len;
  196829. png_charp new_name;
  196830. compression_state comp;
  196831. int embedded_profile_len = 0;
  196832. png_debug(1, "in png_write_iCCP\n");
  196833. comp.num_output_ptr = 0;
  196834. comp.max_output_ptr = 0;
  196835. comp.output_ptr = NULL;
  196836. comp.input = NULL;
  196837. comp.input_len = 0;
  196838. if (name == NULL || (name_len = png_check_keyword(png_ptr, name,
  196839. &new_name)) == 0)
  196840. {
  196841. png_warning(png_ptr, "Empty keyword in iCCP chunk");
  196842. return;
  196843. }
  196844. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  196845. png_warning(png_ptr, "Unknown compression type in iCCP chunk");
  196846. if (profile == NULL)
  196847. profile_len = 0;
  196848. if (profile_len > 3)
  196849. embedded_profile_len =
  196850. ((*( (png_bytep)profile ))<<24) |
  196851. ((*( (png_bytep)profile+1))<<16) |
  196852. ((*( (png_bytep)profile+2))<< 8) |
  196853. ((*( (png_bytep)profile+3)) );
  196854. if (profile_len < embedded_profile_len)
  196855. {
  196856. png_warning(png_ptr,
  196857. "Embedded profile length too large in iCCP chunk");
  196858. return;
  196859. }
  196860. if (profile_len > embedded_profile_len)
  196861. {
  196862. png_warning(png_ptr,
  196863. "Truncating profile to actual length in iCCP chunk");
  196864. profile_len = embedded_profile_len;
  196865. }
  196866. if (profile_len)
  196867. profile_len = png_text_compress(png_ptr, profile, (png_size_t)profile_len,
  196868. PNG_COMPRESSION_TYPE_BASE, &comp);
  196869. /* make sure we include the NULL after the name and the compression type */
  196870. png_write_chunk_start(png_ptr, png_iCCP,
  196871. (png_uint_32)name_len+profile_len+2);
  196872. new_name[name_len+1]=0x00;
  196873. png_write_chunk_data(png_ptr, (png_bytep)new_name, name_len + 2);
  196874. if (profile_len)
  196875. png_write_compressed_data_out(png_ptr, &comp);
  196876. png_write_chunk_end(png_ptr);
  196877. png_free(png_ptr, new_name);
  196878. }
  196879. #endif
  196880. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  196881. /* write a sPLT chunk */
  196882. void /* PRIVATE */
  196883. png_write_sPLT(png_structp png_ptr, png_sPLT_tp spalette)
  196884. {
  196885. #ifdef PNG_USE_LOCAL_ARRAYS
  196886. PNG_sPLT;
  196887. #endif
  196888. png_size_t name_len;
  196889. png_charp new_name;
  196890. png_byte entrybuf[10];
  196891. int entry_size = (spalette->depth == 8 ? 6 : 10);
  196892. int palette_size = entry_size * spalette->nentries;
  196893. png_sPLT_entryp ep;
  196894. #ifdef PNG_NO_POINTER_INDEXING
  196895. int i;
  196896. #endif
  196897. png_debug(1, "in png_write_sPLT\n");
  196898. if (spalette->name == NULL || (name_len = png_check_keyword(png_ptr,
  196899. spalette->name, &new_name))==0)
  196900. {
  196901. png_warning(png_ptr, "Empty keyword in sPLT chunk");
  196902. return;
  196903. }
  196904. /* make sure we include the NULL after the name */
  196905. png_write_chunk_start(png_ptr, png_sPLT,
  196906. (png_uint_32)(name_len + 2 + palette_size));
  196907. png_write_chunk_data(png_ptr, (png_bytep)new_name, name_len + 1);
  196908. png_write_chunk_data(png_ptr, (png_bytep)&spalette->depth, 1);
  196909. /* loop through each palette entry, writing appropriately */
  196910. #ifndef PNG_NO_POINTER_INDEXING
  196911. for (ep = spalette->entries; ep<spalette->entries+spalette->nentries; ep++)
  196912. {
  196913. if (spalette->depth == 8)
  196914. {
  196915. entrybuf[0] = (png_byte)ep->red;
  196916. entrybuf[1] = (png_byte)ep->green;
  196917. entrybuf[2] = (png_byte)ep->blue;
  196918. entrybuf[3] = (png_byte)ep->alpha;
  196919. png_save_uint_16(entrybuf + 4, ep->frequency);
  196920. }
  196921. else
  196922. {
  196923. png_save_uint_16(entrybuf + 0, ep->red);
  196924. png_save_uint_16(entrybuf + 2, ep->green);
  196925. png_save_uint_16(entrybuf + 4, ep->blue);
  196926. png_save_uint_16(entrybuf + 6, ep->alpha);
  196927. png_save_uint_16(entrybuf + 8, ep->frequency);
  196928. }
  196929. png_write_chunk_data(png_ptr, entrybuf, (png_size_t)entry_size);
  196930. }
  196931. #else
  196932. ep=spalette->entries;
  196933. for (i=0; i>spalette->nentries; i++)
  196934. {
  196935. if (spalette->depth == 8)
  196936. {
  196937. entrybuf[0] = (png_byte)ep[i].red;
  196938. entrybuf[1] = (png_byte)ep[i].green;
  196939. entrybuf[2] = (png_byte)ep[i].blue;
  196940. entrybuf[3] = (png_byte)ep[i].alpha;
  196941. png_save_uint_16(entrybuf + 4, ep[i].frequency);
  196942. }
  196943. else
  196944. {
  196945. png_save_uint_16(entrybuf + 0, ep[i].red);
  196946. png_save_uint_16(entrybuf + 2, ep[i].green);
  196947. png_save_uint_16(entrybuf + 4, ep[i].blue);
  196948. png_save_uint_16(entrybuf + 6, ep[i].alpha);
  196949. png_save_uint_16(entrybuf + 8, ep[i].frequency);
  196950. }
  196951. png_write_chunk_data(png_ptr, entrybuf, entry_size);
  196952. }
  196953. #endif
  196954. png_write_chunk_end(png_ptr);
  196955. png_free(png_ptr, new_name);
  196956. }
  196957. #endif
  196958. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  196959. /* write the sBIT chunk */
  196960. void /* PRIVATE */
  196961. png_write_sBIT(png_structp png_ptr, png_color_8p sbit, int color_type)
  196962. {
  196963. #ifdef PNG_USE_LOCAL_ARRAYS
  196964. PNG_sBIT;
  196965. #endif
  196966. png_byte buf[4];
  196967. png_size_t size;
  196968. png_debug(1, "in png_write_sBIT\n");
  196969. /* make sure we don't depend upon the order of PNG_COLOR_8 */
  196970. if (color_type & PNG_COLOR_MASK_COLOR)
  196971. {
  196972. png_byte maxbits;
  196973. maxbits = (png_byte)(color_type==PNG_COLOR_TYPE_PALETTE ? 8 :
  196974. png_ptr->usr_bit_depth);
  196975. if (sbit->red == 0 || sbit->red > maxbits ||
  196976. sbit->green == 0 || sbit->green > maxbits ||
  196977. sbit->blue == 0 || sbit->blue > maxbits)
  196978. {
  196979. png_warning(png_ptr, "Invalid sBIT depth specified");
  196980. return;
  196981. }
  196982. buf[0] = sbit->red;
  196983. buf[1] = sbit->green;
  196984. buf[2] = sbit->blue;
  196985. size = 3;
  196986. }
  196987. else
  196988. {
  196989. if (sbit->gray == 0 || sbit->gray > png_ptr->usr_bit_depth)
  196990. {
  196991. png_warning(png_ptr, "Invalid sBIT depth specified");
  196992. return;
  196993. }
  196994. buf[0] = sbit->gray;
  196995. size = 1;
  196996. }
  196997. if (color_type & PNG_COLOR_MASK_ALPHA)
  196998. {
  196999. if (sbit->alpha == 0 || sbit->alpha > png_ptr->usr_bit_depth)
  197000. {
  197001. png_warning(png_ptr, "Invalid sBIT depth specified");
  197002. return;
  197003. }
  197004. buf[size++] = sbit->alpha;
  197005. }
  197006. png_write_chunk(png_ptr, png_sBIT, buf, size);
  197007. }
  197008. #endif
  197009. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  197010. /* write the cHRM chunk */
  197011. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197012. void /* PRIVATE */
  197013. png_write_cHRM(png_structp png_ptr, double white_x, double white_y,
  197014. double red_x, double red_y, double green_x, double green_y,
  197015. double blue_x, double blue_y)
  197016. {
  197017. #ifdef PNG_USE_LOCAL_ARRAYS
  197018. PNG_cHRM;
  197019. #endif
  197020. png_byte buf[32];
  197021. png_uint_32 itemp;
  197022. png_debug(1, "in png_write_cHRM\n");
  197023. /* each value is saved in 1/100,000ths */
  197024. if (white_x < 0 || white_x > 0.8 || white_y < 0 || white_y > 0.8 ||
  197025. white_x + white_y > 1.0)
  197026. {
  197027. png_warning(png_ptr, "Invalid cHRM white point specified");
  197028. #if !defined(PNG_NO_CONSOLE_IO)
  197029. fprintf(stderr,"white_x=%f, white_y=%f\n",white_x, white_y);
  197030. #endif
  197031. return;
  197032. }
  197033. itemp = (png_uint_32)(white_x * 100000.0 + 0.5);
  197034. png_save_uint_32(buf, itemp);
  197035. itemp = (png_uint_32)(white_y * 100000.0 + 0.5);
  197036. png_save_uint_32(buf + 4, itemp);
  197037. if (red_x < 0 || red_y < 0 || red_x + red_y > 1.0)
  197038. {
  197039. png_warning(png_ptr, "Invalid cHRM red point specified");
  197040. return;
  197041. }
  197042. itemp = (png_uint_32)(red_x * 100000.0 + 0.5);
  197043. png_save_uint_32(buf + 8, itemp);
  197044. itemp = (png_uint_32)(red_y * 100000.0 + 0.5);
  197045. png_save_uint_32(buf + 12, itemp);
  197046. if (green_x < 0 || green_y < 0 || green_x + green_y > 1.0)
  197047. {
  197048. png_warning(png_ptr, "Invalid cHRM green point specified");
  197049. return;
  197050. }
  197051. itemp = (png_uint_32)(green_x * 100000.0 + 0.5);
  197052. png_save_uint_32(buf + 16, itemp);
  197053. itemp = (png_uint_32)(green_y * 100000.0 + 0.5);
  197054. png_save_uint_32(buf + 20, itemp);
  197055. if (blue_x < 0 || blue_y < 0 || blue_x + blue_y > 1.0)
  197056. {
  197057. png_warning(png_ptr, "Invalid cHRM blue point specified");
  197058. return;
  197059. }
  197060. itemp = (png_uint_32)(blue_x * 100000.0 + 0.5);
  197061. png_save_uint_32(buf + 24, itemp);
  197062. itemp = (png_uint_32)(blue_y * 100000.0 + 0.5);
  197063. png_save_uint_32(buf + 28, itemp);
  197064. png_write_chunk(png_ptr, png_cHRM, buf, (png_size_t)32);
  197065. }
  197066. #endif
  197067. #ifdef PNG_FIXED_POINT_SUPPORTED
  197068. void /* PRIVATE */
  197069. png_write_cHRM_fixed(png_structp png_ptr, png_fixed_point white_x,
  197070. png_fixed_point white_y, png_fixed_point red_x, png_fixed_point red_y,
  197071. png_fixed_point green_x, png_fixed_point green_y, png_fixed_point blue_x,
  197072. png_fixed_point blue_y)
  197073. {
  197074. #ifdef PNG_USE_LOCAL_ARRAYS
  197075. PNG_cHRM;
  197076. #endif
  197077. png_byte buf[32];
  197078. png_debug(1, "in png_write_cHRM\n");
  197079. /* each value is saved in 1/100,000ths */
  197080. if (white_x > 80000L || white_y > 80000L || white_x + white_y > 100000L)
  197081. {
  197082. png_warning(png_ptr, "Invalid fixed cHRM white point specified");
  197083. #if !defined(PNG_NO_CONSOLE_IO)
  197084. fprintf(stderr,"white_x=%ld, white_y=%ld\n",white_x, white_y);
  197085. #endif
  197086. return;
  197087. }
  197088. png_save_uint_32(buf, (png_uint_32)white_x);
  197089. png_save_uint_32(buf + 4, (png_uint_32)white_y);
  197090. if (red_x + red_y > 100000L)
  197091. {
  197092. png_warning(png_ptr, "Invalid cHRM fixed red point specified");
  197093. return;
  197094. }
  197095. png_save_uint_32(buf + 8, (png_uint_32)red_x);
  197096. png_save_uint_32(buf + 12, (png_uint_32)red_y);
  197097. if (green_x + green_y > 100000L)
  197098. {
  197099. png_warning(png_ptr, "Invalid fixed cHRM green point specified");
  197100. return;
  197101. }
  197102. png_save_uint_32(buf + 16, (png_uint_32)green_x);
  197103. png_save_uint_32(buf + 20, (png_uint_32)green_y);
  197104. if (blue_x + blue_y > 100000L)
  197105. {
  197106. png_warning(png_ptr, "Invalid fixed cHRM blue point specified");
  197107. return;
  197108. }
  197109. png_save_uint_32(buf + 24, (png_uint_32)blue_x);
  197110. png_save_uint_32(buf + 28, (png_uint_32)blue_y);
  197111. png_write_chunk(png_ptr, png_cHRM, buf, (png_size_t)32);
  197112. }
  197113. #endif
  197114. #endif
  197115. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  197116. /* write the tRNS chunk */
  197117. void /* PRIVATE */
  197118. png_write_tRNS(png_structp png_ptr, png_bytep trans, png_color_16p tran,
  197119. int num_trans, int color_type)
  197120. {
  197121. #ifdef PNG_USE_LOCAL_ARRAYS
  197122. PNG_tRNS;
  197123. #endif
  197124. png_byte buf[6];
  197125. png_debug(1, "in png_write_tRNS\n");
  197126. if (color_type == PNG_COLOR_TYPE_PALETTE)
  197127. {
  197128. if (num_trans <= 0 || num_trans > (int)png_ptr->num_palette)
  197129. {
  197130. png_warning(png_ptr,"Invalid number of transparent colors specified");
  197131. return;
  197132. }
  197133. /* write the chunk out as it is */
  197134. png_write_chunk(png_ptr, png_tRNS, trans, (png_size_t)num_trans);
  197135. }
  197136. else if (color_type == PNG_COLOR_TYPE_GRAY)
  197137. {
  197138. /* one 16 bit value */
  197139. if(tran->gray >= (1 << png_ptr->bit_depth))
  197140. {
  197141. png_warning(png_ptr,
  197142. "Ignoring attempt to write tRNS chunk out-of-range for bit_depth");
  197143. return;
  197144. }
  197145. png_save_uint_16(buf, tran->gray);
  197146. png_write_chunk(png_ptr, png_tRNS, buf, (png_size_t)2);
  197147. }
  197148. else if (color_type == PNG_COLOR_TYPE_RGB)
  197149. {
  197150. /* three 16 bit values */
  197151. png_save_uint_16(buf, tran->red);
  197152. png_save_uint_16(buf + 2, tran->green);
  197153. png_save_uint_16(buf + 4, tran->blue);
  197154. if(png_ptr->bit_depth == 8 && (buf[0] | buf[2] | buf[4]))
  197155. {
  197156. png_warning(png_ptr,
  197157. "Ignoring attempt to write 16-bit tRNS chunk when bit_depth is 8");
  197158. return;
  197159. }
  197160. png_write_chunk(png_ptr, png_tRNS, buf, (png_size_t)6);
  197161. }
  197162. else
  197163. {
  197164. png_warning(png_ptr, "Can't write tRNS with an alpha channel");
  197165. }
  197166. }
  197167. #endif
  197168. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  197169. /* write the background chunk */
  197170. void /* PRIVATE */
  197171. png_write_bKGD(png_structp png_ptr, png_color_16p back, int color_type)
  197172. {
  197173. #ifdef PNG_USE_LOCAL_ARRAYS
  197174. PNG_bKGD;
  197175. #endif
  197176. png_byte buf[6];
  197177. png_debug(1, "in png_write_bKGD\n");
  197178. if (color_type == PNG_COLOR_TYPE_PALETTE)
  197179. {
  197180. if (
  197181. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  197182. (png_ptr->num_palette ||
  197183. (!(png_ptr->mng_features_permitted & PNG_FLAG_MNG_EMPTY_PLTE))) &&
  197184. #endif
  197185. back->index > png_ptr->num_palette)
  197186. {
  197187. png_warning(png_ptr, "Invalid background palette index");
  197188. return;
  197189. }
  197190. buf[0] = back->index;
  197191. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)1);
  197192. }
  197193. else if (color_type & PNG_COLOR_MASK_COLOR)
  197194. {
  197195. png_save_uint_16(buf, back->red);
  197196. png_save_uint_16(buf + 2, back->green);
  197197. png_save_uint_16(buf + 4, back->blue);
  197198. if(png_ptr->bit_depth == 8 && (buf[0] | buf[2] | buf[4]))
  197199. {
  197200. png_warning(png_ptr,
  197201. "Ignoring attempt to write 16-bit bKGD chunk when bit_depth is 8");
  197202. return;
  197203. }
  197204. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)6);
  197205. }
  197206. else
  197207. {
  197208. if(back->gray >= (1 << png_ptr->bit_depth))
  197209. {
  197210. png_warning(png_ptr,
  197211. "Ignoring attempt to write bKGD chunk out-of-range for bit_depth");
  197212. return;
  197213. }
  197214. png_save_uint_16(buf, back->gray);
  197215. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)2);
  197216. }
  197217. }
  197218. #endif
  197219. #if defined(PNG_WRITE_hIST_SUPPORTED)
  197220. /* write the histogram */
  197221. void /* PRIVATE */
  197222. png_write_hIST(png_structp png_ptr, png_uint_16p hist, int num_hist)
  197223. {
  197224. #ifdef PNG_USE_LOCAL_ARRAYS
  197225. PNG_hIST;
  197226. #endif
  197227. int i;
  197228. png_byte buf[3];
  197229. png_debug(1, "in png_write_hIST\n");
  197230. if (num_hist > (int)png_ptr->num_palette)
  197231. {
  197232. png_debug2(3, "num_hist = %d, num_palette = %d\n", num_hist,
  197233. png_ptr->num_palette);
  197234. png_warning(png_ptr, "Invalid number of histogram entries specified");
  197235. return;
  197236. }
  197237. png_write_chunk_start(png_ptr, png_hIST, (png_uint_32)(num_hist * 2));
  197238. for (i = 0; i < num_hist; i++)
  197239. {
  197240. png_save_uint_16(buf, hist[i]);
  197241. png_write_chunk_data(png_ptr, buf, (png_size_t)2);
  197242. }
  197243. png_write_chunk_end(png_ptr);
  197244. }
  197245. #endif
  197246. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_pCAL_SUPPORTED) || \
  197247. defined(PNG_WRITE_iCCP_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  197248. /* Check that the tEXt or zTXt keyword is valid per PNG 1.0 specification,
  197249. * and if invalid, correct the keyword rather than discarding the entire
  197250. * chunk. The PNG 1.0 specification requires keywords 1-79 characters in
  197251. * length, forbids leading or trailing whitespace, multiple internal spaces,
  197252. * and the non-break space (0x80) from ISO 8859-1. Returns keyword length.
  197253. *
  197254. * The new_key is allocated to hold the corrected keyword and must be freed
  197255. * by the calling routine. This avoids problems with trying to write to
  197256. * static keywords without having to have duplicate copies of the strings.
  197257. */
  197258. png_size_t /* PRIVATE */
  197259. png_check_keyword(png_structp png_ptr, png_charp key, png_charpp new_key)
  197260. {
  197261. png_size_t key_len;
  197262. png_charp kp, dp;
  197263. int kflag;
  197264. int kwarn=0;
  197265. png_debug(1, "in png_check_keyword\n");
  197266. *new_key = NULL;
  197267. if (key == NULL || (key_len = png_strlen(key)) == 0)
  197268. {
  197269. png_warning(png_ptr, "zero length keyword");
  197270. return ((png_size_t)0);
  197271. }
  197272. png_debug1(2, "Keyword to be checked is '%s'\n", key);
  197273. *new_key = (png_charp)png_malloc_warn(png_ptr, (png_uint_32)(key_len + 2));
  197274. if (*new_key == NULL)
  197275. {
  197276. png_warning(png_ptr, "Out of memory while procesing keyword");
  197277. return ((png_size_t)0);
  197278. }
  197279. /* Replace non-printing characters with a blank and print a warning */
  197280. for (kp = key, dp = *new_key; *kp != '\0'; kp++, dp++)
  197281. {
  197282. if ((png_byte)*kp < 0x20 ||
  197283. ((png_byte)*kp > 0x7E && (png_byte)*kp < 0xA1))
  197284. {
  197285. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  197286. char msg[40];
  197287. png_snprintf(msg, 40,
  197288. "invalid keyword character 0x%02X", (png_byte)*kp);
  197289. png_warning(png_ptr, msg);
  197290. #else
  197291. png_warning(png_ptr, "invalid character in keyword");
  197292. #endif
  197293. *dp = ' ';
  197294. }
  197295. else
  197296. {
  197297. *dp = *kp;
  197298. }
  197299. }
  197300. *dp = '\0';
  197301. /* Remove any trailing white space. */
  197302. kp = *new_key + key_len - 1;
  197303. if (*kp == ' ')
  197304. {
  197305. png_warning(png_ptr, "trailing spaces removed from keyword");
  197306. while (*kp == ' ')
  197307. {
  197308. *(kp--) = '\0';
  197309. key_len--;
  197310. }
  197311. }
  197312. /* Remove any leading white space. */
  197313. kp = *new_key;
  197314. if (*kp == ' ')
  197315. {
  197316. png_warning(png_ptr, "leading spaces removed from keyword");
  197317. while (*kp == ' ')
  197318. {
  197319. kp++;
  197320. key_len--;
  197321. }
  197322. }
  197323. png_debug1(2, "Checking for multiple internal spaces in '%s'\n", kp);
  197324. /* Remove multiple internal spaces. */
  197325. for (kflag = 0, dp = *new_key; *kp != '\0'; kp++)
  197326. {
  197327. if (*kp == ' ' && kflag == 0)
  197328. {
  197329. *(dp++) = *kp;
  197330. kflag = 1;
  197331. }
  197332. else if (*kp == ' ')
  197333. {
  197334. key_len--;
  197335. kwarn=1;
  197336. }
  197337. else
  197338. {
  197339. *(dp++) = *kp;
  197340. kflag = 0;
  197341. }
  197342. }
  197343. *dp = '\0';
  197344. if(kwarn)
  197345. png_warning(png_ptr, "extra interior spaces removed from keyword");
  197346. if (key_len == 0)
  197347. {
  197348. png_free(png_ptr, *new_key);
  197349. *new_key=NULL;
  197350. png_warning(png_ptr, "Zero length keyword");
  197351. }
  197352. if (key_len > 79)
  197353. {
  197354. png_warning(png_ptr, "keyword length must be 1 - 79 characters");
  197355. new_key[79] = '\0';
  197356. key_len = 79;
  197357. }
  197358. return (key_len);
  197359. }
  197360. #endif
  197361. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  197362. /* write a tEXt chunk */
  197363. void /* PRIVATE */
  197364. png_write_tEXt(png_structp png_ptr, png_charp key, png_charp text,
  197365. png_size_t text_len)
  197366. {
  197367. #ifdef PNG_USE_LOCAL_ARRAYS
  197368. PNG_tEXt;
  197369. #endif
  197370. png_size_t key_len;
  197371. png_charp new_key;
  197372. png_debug(1, "in png_write_tEXt\n");
  197373. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  197374. {
  197375. png_warning(png_ptr, "Empty keyword in tEXt chunk");
  197376. return;
  197377. }
  197378. if (text == NULL || *text == '\0')
  197379. text_len = 0;
  197380. else
  197381. text_len = png_strlen(text);
  197382. /* make sure we include the 0 after the key */
  197383. png_write_chunk_start(png_ptr, png_tEXt, (png_uint_32)key_len+text_len+1);
  197384. /*
  197385. * We leave it to the application to meet PNG-1.0 requirements on the
  197386. * contents of the text. PNG-1.0 through PNG-1.2 discourage the use of
  197387. * any non-Latin-1 characters except for NEWLINE. ISO PNG will forbid them.
  197388. * The NUL character is forbidden by PNG-1.0 through PNG-1.2 and ISO PNG.
  197389. */
  197390. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  197391. if (text_len)
  197392. png_write_chunk_data(png_ptr, (png_bytep)text, text_len);
  197393. png_write_chunk_end(png_ptr);
  197394. png_free(png_ptr, new_key);
  197395. }
  197396. #endif
  197397. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  197398. /* write a compressed text chunk */
  197399. void /* PRIVATE */
  197400. png_write_zTXt(png_structp png_ptr, png_charp key, png_charp text,
  197401. png_size_t text_len, int compression)
  197402. {
  197403. #ifdef PNG_USE_LOCAL_ARRAYS
  197404. PNG_zTXt;
  197405. #endif
  197406. png_size_t key_len;
  197407. char buf[1];
  197408. png_charp new_key;
  197409. compression_state comp;
  197410. png_debug(1, "in png_write_zTXt\n");
  197411. comp.num_output_ptr = 0;
  197412. comp.max_output_ptr = 0;
  197413. comp.output_ptr = NULL;
  197414. comp.input = NULL;
  197415. comp.input_len = 0;
  197416. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  197417. {
  197418. png_warning(png_ptr, "Empty keyword in zTXt chunk");
  197419. return;
  197420. }
  197421. if (text == NULL || *text == '\0' || compression==PNG_TEXT_COMPRESSION_NONE)
  197422. {
  197423. png_write_tEXt(png_ptr, new_key, text, (png_size_t)0);
  197424. png_free(png_ptr, new_key);
  197425. return;
  197426. }
  197427. text_len = png_strlen(text);
  197428. /* compute the compressed data; do it now for the length */
  197429. text_len = png_text_compress(png_ptr, text, text_len, compression,
  197430. &comp);
  197431. /* write start of chunk */
  197432. png_write_chunk_start(png_ptr, png_zTXt, (png_uint_32)
  197433. (key_len+text_len+2));
  197434. /* write key */
  197435. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  197436. png_free(png_ptr, new_key);
  197437. buf[0] = (png_byte)compression;
  197438. /* write compression */
  197439. png_write_chunk_data(png_ptr, (png_bytep)buf, (png_size_t)1);
  197440. /* write the compressed data */
  197441. png_write_compressed_data_out(png_ptr, &comp);
  197442. /* close the chunk */
  197443. png_write_chunk_end(png_ptr);
  197444. }
  197445. #endif
  197446. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  197447. /* write an iTXt chunk */
  197448. void /* PRIVATE */
  197449. png_write_iTXt(png_structp png_ptr, int compression, png_charp key,
  197450. png_charp lang, png_charp lang_key, png_charp text)
  197451. {
  197452. #ifdef PNG_USE_LOCAL_ARRAYS
  197453. PNG_iTXt;
  197454. #endif
  197455. png_size_t lang_len, key_len, lang_key_len, text_len;
  197456. png_charp new_lang, new_key;
  197457. png_byte cbuf[2];
  197458. compression_state comp;
  197459. png_debug(1, "in png_write_iTXt\n");
  197460. comp.num_output_ptr = 0;
  197461. comp.max_output_ptr = 0;
  197462. comp.output_ptr = NULL;
  197463. comp.input = NULL;
  197464. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  197465. {
  197466. png_warning(png_ptr, "Empty keyword in iTXt chunk");
  197467. return;
  197468. }
  197469. if (lang == NULL || (lang_len = png_check_keyword(png_ptr, lang, &new_lang))==0)
  197470. {
  197471. png_warning(png_ptr, "Empty language field in iTXt chunk");
  197472. new_lang = NULL;
  197473. lang_len = 0;
  197474. }
  197475. if (lang_key == NULL)
  197476. lang_key_len = 0;
  197477. else
  197478. lang_key_len = png_strlen(lang_key);
  197479. if (text == NULL)
  197480. text_len = 0;
  197481. else
  197482. text_len = png_strlen(text);
  197483. /* compute the compressed data; do it now for the length */
  197484. text_len = png_text_compress(png_ptr, text, text_len, compression-2,
  197485. &comp);
  197486. /* make sure we include the compression flag, the compression byte,
  197487. * and the NULs after the key, lang, and lang_key parts */
  197488. png_write_chunk_start(png_ptr, png_iTXt,
  197489. (png_uint_32)(
  197490. 5 /* comp byte, comp flag, terminators for key, lang and lang_key */
  197491. + key_len
  197492. + lang_len
  197493. + lang_key_len
  197494. + text_len));
  197495. /*
  197496. * We leave it to the application to meet PNG-1.0 requirements on the
  197497. * contents of the text. PNG-1.0 through PNG-1.2 discourage the use of
  197498. * any non-Latin-1 characters except for NEWLINE. ISO PNG will forbid them.
  197499. * The NUL character is forbidden by PNG-1.0 through PNG-1.2 and ISO PNG.
  197500. */
  197501. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  197502. /* set the compression flag */
  197503. if (compression == PNG_ITXT_COMPRESSION_NONE || \
  197504. compression == PNG_TEXT_COMPRESSION_NONE)
  197505. cbuf[0] = 0;
  197506. else /* compression == PNG_ITXT_COMPRESSION_zTXt */
  197507. cbuf[0] = 1;
  197508. /* set the compression method */
  197509. cbuf[1] = 0;
  197510. png_write_chunk_data(png_ptr, cbuf, 2);
  197511. cbuf[0] = 0;
  197512. png_write_chunk_data(png_ptr, (new_lang ? (png_bytep)new_lang : cbuf), lang_len + 1);
  197513. png_write_chunk_data(png_ptr, (lang_key ? (png_bytep)lang_key : cbuf), lang_key_len + 1);
  197514. png_write_compressed_data_out(png_ptr, &comp);
  197515. png_write_chunk_end(png_ptr);
  197516. png_free(png_ptr, new_key);
  197517. if (new_lang)
  197518. png_free(png_ptr, new_lang);
  197519. }
  197520. #endif
  197521. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  197522. /* write the oFFs chunk */
  197523. void /* PRIVATE */
  197524. png_write_oFFs(png_structp png_ptr, png_int_32 x_offset, png_int_32 y_offset,
  197525. int unit_type)
  197526. {
  197527. #ifdef PNG_USE_LOCAL_ARRAYS
  197528. PNG_oFFs;
  197529. #endif
  197530. png_byte buf[9];
  197531. png_debug(1, "in png_write_oFFs\n");
  197532. if (unit_type >= PNG_OFFSET_LAST)
  197533. png_warning(png_ptr, "Unrecognized unit type for oFFs chunk");
  197534. png_save_int_32(buf, x_offset);
  197535. png_save_int_32(buf + 4, y_offset);
  197536. buf[8] = (png_byte)unit_type;
  197537. png_write_chunk(png_ptr, png_oFFs, buf, (png_size_t)9);
  197538. }
  197539. #endif
  197540. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  197541. /* write the pCAL chunk (described in the PNG extensions document) */
  197542. void /* PRIVATE */
  197543. png_write_pCAL(png_structp png_ptr, png_charp purpose, png_int_32 X0,
  197544. png_int_32 X1, int type, int nparams, png_charp units, png_charpp params)
  197545. {
  197546. #ifdef PNG_USE_LOCAL_ARRAYS
  197547. PNG_pCAL;
  197548. #endif
  197549. png_size_t purpose_len, units_len, total_len;
  197550. png_uint_32p params_len;
  197551. png_byte buf[10];
  197552. png_charp new_purpose;
  197553. int i;
  197554. png_debug1(1, "in png_write_pCAL (%d parameters)\n", nparams);
  197555. if (type >= PNG_EQUATION_LAST)
  197556. png_warning(png_ptr, "Unrecognized equation type for pCAL chunk");
  197557. purpose_len = png_check_keyword(png_ptr, purpose, &new_purpose) + 1;
  197558. png_debug1(3, "pCAL purpose length = %d\n", (int)purpose_len);
  197559. units_len = png_strlen(units) + (nparams == 0 ? 0 : 1);
  197560. png_debug1(3, "pCAL units length = %d\n", (int)units_len);
  197561. total_len = purpose_len + units_len + 10;
  197562. params_len = (png_uint_32p)png_malloc(png_ptr, (png_uint_32)(nparams
  197563. *png_sizeof(png_uint_32)));
  197564. /* Find the length of each parameter, making sure we don't count the
  197565. null terminator for the last parameter. */
  197566. for (i = 0; i < nparams; i++)
  197567. {
  197568. params_len[i] = png_strlen(params[i]) + (i == nparams - 1 ? 0 : 1);
  197569. png_debug2(3, "pCAL parameter %d length = %lu\n", i, params_len[i]);
  197570. total_len += (png_size_t)params_len[i];
  197571. }
  197572. png_debug1(3, "pCAL total length = %d\n", (int)total_len);
  197573. png_write_chunk_start(png_ptr, png_pCAL, (png_uint_32)total_len);
  197574. png_write_chunk_data(png_ptr, (png_bytep)new_purpose, purpose_len);
  197575. png_save_int_32(buf, X0);
  197576. png_save_int_32(buf + 4, X1);
  197577. buf[8] = (png_byte)type;
  197578. buf[9] = (png_byte)nparams;
  197579. png_write_chunk_data(png_ptr, buf, (png_size_t)10);
  197580. png_write_chunk_data(png_ptr, (png_bytep)units, (png_size_t)units_len);
  197581. png_free(png_ptr, new_purpose);
  197582. for (i = 0; i < nparams; i++)
  197583. {
  197584. png_write_chunk_data(png_ptr, (png_bytep)params[i],
  197585. (png_size_t)params_len[i]);
  197586. }
  197587. png_free(png_ptr, params_len);
  197588. png_write_chunk_end(png_ptr);
  197589. }
  197590. #endif
  197591. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  197592. /* write the sCAL chunk */
  197593. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  197594. void /* PRIVATE */
  197595. png_write_sCAL(png_structp png_ptr, int unit, double width, double height)
  197596. {
  197597. #ifdef PNG_USE_LOCAL_ARRAYS
  197598. PNG_sCAL;
  197599. #endif
  197600. char buf[64];
  197601. png_size_t total_len;
  197602. png_debug(1, "in png_write_sCAL\n");
  197603. buf[0] = (char)unit;
  197604. #if defined(_WIN32_WCE)
  197605. /* sprintf() function is not supported on WindowsCE */
  197606. {
  197607. wchar_t wc_buf[32];
  197608. size_t wc_len;
  197609. swprintf(wc_buf, TEXT("%12.12e"), width);
  197610. wc_len = wcslen(wc_buf);
  197611. WideCharToMultiByte(CP_ACP, 0, wc_buf, -1, buf + 1, wc_len, NULL, NULL);
  197612. total_len = wc_len + 2;
  197613. swprintf(wc_buf, TEXT("%12.12e"), height);
  197614. wc_len = wcslen(wc_buf);
  197615. WideCharToMultiByte(CP_ACP, 0, wc_buf, -1, buf + total_len, wc_len,
  197616. NULL, NULL);
  197617. total_len += wc_len;
  197618. }
  197619. #else
  197620. png_snprintf(buf + 1, 63, "%12.12e", width);
  197621. total_len = 1 + png_strlen(buf + 1) + 1;
  197622. png_snprintf(buf + total_len, 64-total_len, "%12.12e", height);
  197623. total_len += png_strlen(buf + total_len);
  197624. #endif
  197625. png_debug1(3, "sCAL total length = %u\n", (unsigned int)total_len);
  197626. png_write_chunk(png_ptr, png_sCAL, (png_bytep)buf, total_len);
  197627. }
  197628. #else
  197629. #ifdef PNG_FIXED_POINT_SUPPORTED
  197630. void /* PRIVATE */
  197631. png_write_sCAL_s(png_structp png_ptr, int unit, png_charp width,
  197632. png_charp height)
  197633. {
  197634. #ifdef PNG_USE_LOCAL_ARRAYS
  197635. PNG_sCAL;
  197636. #endif
  197637. png_byte buf[64];
  197638. png_size_t wlen, hlen, total_len;
  197639. png_debug(1, "in png_write_sCAL_s\n");
  197640. wlen = png_strlen(width);
  197641. hlen = png_strlen(height);
  197642. total_len = wlen + hlen + 2;
  197643. if (total_len > 64)
  197644. {
  197645. png_warning(png_ptr, "Can't write sCAL (buffer too small)");
  197646. return;
  197647. }
  197648. buf[0] = (png_byte)unit;
  197649. png_memcpy(buf + 1, width, wlen + 1); /* append the '\0' here */
  197650. png_memcpy(buf + wlen + 2, height, hlen); /* do NOT append the '\0' here */
  197651. png_debug1(3, "sCAL total length = %u\n", (unsigned int)total_len);
  197652. png_write_chunk(png_ptr, png_sCAL, buf, total_len);
  197653. }
  197654. #endif
  197655. #endif
  197656. #endif
  197657. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  197658. /* write the pHYs chunk */
  197659. void /* PRIVATE */
  197660. png_write_pHYs(png_structp png_ptr, png_uint_32 x_pixels_per_unit,
  197661. png_uint_32 y_pixels_per_unit,
  197662. int unit_type)
  197663. {
  197664. #ifdef PNG_USE_LOCAL_ARRAYS
  197665. PNG_pHYs;
  197666. #endif
  197667. png_byte buf[9];
  197668. png_debug(1, "in png_write_pHYs\n");
  197669. if (unit_type >= PNG_RESOLUTION_LAST)
  197670. png_warning(png_ptr, "Unrecognized unit type for pHYs chunk");
  197671. png_save_uint_32(buf, x_pixels_per_unit);
  197672. png_save_uint_32(buf + 4, y_pixels_per_unit);
  197673. buf[8] = (png_byte)unit_type;
  197674. png_write_chunk(png_ptr, png_pHYs, buf, (png_size_t)9);
  197675. }
  197676. #endif
  197677. #if defined(PNG_WRITE_tIME_SUPPORTED)
  197678. /* Write the tIME chunk. Use either png_convert_from_struct_tm()
  197679. * or png_convert_from_time_t(), or fill in the structure yourself.
  197680. */
  197681. void /* PRIVATE */
  197682. png_write_tIME(png_structp png_ptr, png_timep mod_time)
  197683. {
  197684. #ifdef PNG_USE_LOCAL_ARRAYS
  197685. PNG_tIME;
  197686. #endif
  197687. png_byte buf[7];
  197688. png_debug(1, "in png_write_tIME\n");
  197689. if (mod_time->month > 12 || mod_time->month < 1 ||
  197690. mod_time->day > 31 || mod_time->day < 1 ||
  197691. mod_time->hour > 23 || mod_time->second > 60)
  197692. {
  197693. png_warning(png_ptr, "Invalid time specified for tIME chunk");
  197694. return;
  197695. }
  197696. png_save_uint_16(buf, mod_time->year);
  197697. buf[2] = mod_time->month;
  197698. buf[3] = mod_time->day;
  197699. buf[4] = mod_time->hour;
  197700. buf[5] = mod_time->minute;
  197701. buf[6] = mod_time->second;
  197702. png_write_chunk(png_ptr, png_tIME, buf, (png_size_t)7);
  197703. }
  197704. #endif
  197705. /* initializes the row writing capability of libpng */
  197706. void /* PRIVATE */
  197707. png_write_start_row(png_structp png_ptr)
  197708. {
  197709. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  197710. #ifdef PNG_USE_LOCAL_ARRAYS
  197711. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  197712. /* start of interlace block */
  197713. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  197714. /* offset to next interlace block */
  197715. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  197716. /* start of interlace block in the y direction */
  197717. int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  197718. /* offset to next interlace block in the y direction */
  197719. int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  197720. #endif
  197721. #endif
  197722. png_size_t buf_size;
  197723. png_debug(1, "in png_write_start_row\n");
  197724. buf_size = (png_size_t)(PNG_ROWBYTES(
  197725. png_ptr->usr_channels*png_ptr->usr_bit_depth,png_ptr->width)+1);
  197726. /* set up row buffer */
  197727. png_ptr->row_buf = (png_bytep)png_malloc(png_ptr, (png_uint_32)buf_size);
  197728. png_ptr->row_buf[0] = PNG_FILTER_VALUE_NONE;
  197729. #ifndef PNG_NO_WRITE_FILTERING
  197730. /* set up filtering buffer, if using this filter */
  197731. if (png_ptr->do_filter & PNG_FILTER_SUB)
  197732. {
  197733. png_ptr->sub_row = (png_bytep)png_malloc(png_ptr,
  197734. (png_ptr->rowbytes + 1));
  197735. png_ptr->sub_row[0] = PNG_FILTER_VALUE_SUB;
  197736. }
  197737. /* We only need to keep the previous row if we are using one of these. */
  197738. if (png_ptr->do_filter & (PNG_FILTER_AVG | PNG_FILTER_UP | PNG_FILTER_PAETH))
  197739. {
  197740. /* set up previous row buffer */
  197741. png_ptr->prev_row = (png_bytep)png_malloc(png_ptr, (png_uint_32)buf_size);
  197742. png_memset(png_ptr->prev_row, 0, buf_size);
  197743. if (png_ptr->do_filter & PNG_FILTER_UP)
  197744. {
  197745. png_ptr->up_row = (png_bytep)png_malloc(png_ptr,
  197746. (png_ptr->rowbytes + 1));
  197747. png_ptr->up_row[0] = PNG_FILTER_VALUE_UP;
  197748. }
  197749. if (png_ptr->do_filter & PNG_FILTER_AVG)
  197750. {
  197751. png_ptr->avg_row = (png_bytep)png_malloc(png_ptr,
  197752. (png_ptr->rowbytes + 1));
  197753. png_ptr->avg_row[0] = PNG_FILTER_VALUE_AVG;
  197754. }
  197755. if (png_ptr->do_filter & PNG_FILTER_PAETH)
  197756. {
  197757. png_ptr->paeth_row = (png_bytep)png_malloc(png_ptr,
  197758. (png_ptr->rowbytes + 1));
  197759. png_ptr->paeth_row[0] = PNG_FILTER_VALUE_PAETH;
  197760. }
  197761. #endif /* PNG_NO_WRITE_FILTERING */
  197762. }
  197763. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  197764. /* if interlaced, we need to set up width and height of pass */
  197765. if (png_ptr->interlaced)
  197766. {
  197767. if (!(png_ptr->transformations & PNG_INTERLACE))
  197768. {
  197769. png_ptr->num_rows = (png_ptr->height + png_pass_yinc[0] - 1 -
  197770. png_pass_ystart[0]) / png_pass_yinc[0];
  197771. png_ptr->usr_width = (png_ptr->width + png_pass_inc[0] - 1 -
  197772. png_pass_start[0]) / png_pass_inc[0];
  197773. }
  197774. else
  197775. {
  197776. png_ptr->num_rows = png_ptr->height;
  197777. png_ptr->usr_width = png_ptr->width;
  197778. }
  197779. }
  197780. else
  197781. #endif
  197782. {
  197783. png_ptr->num_rows = png_ptr->height;
  197784. png_ptr->usr_width = png_ptr->width;
  197785. }
  197786. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  197787. png_ptr->zstream.next_out = png_ptr->zbuf;
  197788. }
  197789. /* Internal use only. Called when finished processing a row of data. */
  197790. void /* PRIVATE */
  197791. png_write_finish_row(png_structp png_ptr)
  197792. {
  197793. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  197794. #ifdef PNG_USE_LOCAL_ARRAYS
  197795. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  197796. /* start of interlace block */
  197797. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  197798. /* offset to next interlace block */
  197799. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  197800. /* start of interlace block in the y direction */
  197801. int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  197802. /* offset to next interlace block in the y direction */
  197803. int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  197804. #endif
  197805. #endif
  197806. int ret;
  197807. png_debug(1, "in png_write_finish_row\n");
  197808. /* next row */
  197809. png_ptr->row_number++;
  197810. /* see if we are done */
  197811. if (png_ptr->row_number < png_ptr->num_rows)
  197812. return;
  197813. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  197814. /* if interlaced, go to next pass */
  197815. if (png_ptr->interlaced)
  197816. {
  197817. png_ptr->row_number = 0;
  197818. if (png_ptr->transformations & PNG_INTERLACE)
  197819. {
  197820. png_ptr->pass++;
  197821. }
  197822. else
  197823. {
  197824. /* loop until we find a non-zero width or height pass */
  197825. do
  197826. {
  197827. png_ptr->pass++;
  197828. if (png_ptr->pass >= 7)
  197829. break;
  197830. png_ptr->usr_width = (png_ptr->width +
  197831. png_pass_inc[png_ptr->pass] - 1 -
  197832. png_pass_start[png_ptr->pass]) /
  197833. png_pass_inc[png_ptr->pass];
  197834. png_ptr->num_rows = (png_ptr->height +
  197835. png_pass_yinc[png_ptr->pass] - 1 -
  197836. png_pass_ystart[png_ptr->pass]) /
  197837. png_pass_yinc[png_ptr->pass];
  197838. if (png_ptr->transformations & PNG_INTERLACE)
  197839. break;
  197840. } while (png_ptr->usr_width == 0 || png_ptr->num_rows == 0);
  197841. }
  197842. /* reset the row above the image for the next pass */
  197843. if (png_ptr->pass < 7)
  197844. {
  197845. if (png_ptr->prev_row != NULL)
  197846. png_memset(png_ptr->prev_row, 0,
  197847. (png_size_t)(PNG_ROWBYTES(png_ptr->usr_channels*
  197848. png_ptr->usr_bit_depth,png_ptr->width))+1);
  197849. return;
  197850. }
  197851. }
  197852. #endif
  197853. /* if we get here, we've just written the last row, so we need
  197854. to flush the compressor */
  197855. do
  197856. {
  197857. /* tell the compressor we are done */
  197858. ret = deflate(&png_ptr->zstream, Z_FINISH);
  197859. /* check for an error */
  197860. if (ret == Z_OK)
  197861. {
  197862. /* check to see if we need more room */
  197863. if (!(png_ptr->zstream.avail_out))
  197864. {
  197865. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  197866. png_ptr->zstream.next_out = png_ptr->zbuf;
  197867. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  197868. }
  197869. }
  197870. else if (ret != Z_STREAM_END)
  197871. {
  197872. if (png_ptr->zstream.msg != NULL)
  197873. png_error(png_ptr, png_ptr->zstream.msg);
  197874. else
  197875. png_error(png_ptr, "zlib error");
  197876. }
  197877. } while (ret != Z_STREAM_END);
  197878. /* write any extra space */
  197879. if (png_ptr->zstream.avail_out < png_ptr->zbuf_size)
  197880. {
  197881. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size -
  197882. png_ptr->zstream.avail_out);
  197883. }
  197884. deflateReset(&png_ptr->zstream);
  197885. png_ptr->zstream.data_type = Z_BINARY;
  197886. }
  197887. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  197888. /* Pick out the correct pixels for the interlace pass.
  197889. * The basic idea here is to go through the row with a source
  197890. * pointer and a destination pointer (sp and dp), and copy the
  197891. * correct pixels for the pass. As the row gets compacted,
  197892. * sp will always be >= dp, so we should never overwrite anything.
  197893. * See the default: case for the easiest code to understand.
  197894. */
  197895. void /* PRIVATE */
  197896. png_do_write_interlace(png_row_infop row_info, png_bytep row, int pass)
  197897. {
  197898. #ifdef PNG_USE_LOCAL_ARRAYS
  197899. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  197900. /* start of interlace block */
  197901. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  197902. /* offset to next interlace block */
  197903. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  197904. #endif
  197905. png_debug(1, "in png_do_write_interlace\n");
  197906. /* we don't have to do anything on the last pass (6) */
  197907. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  197908. if (row != NULL && row_info != NULL && pass < 6)
  197909. #else
  197910. if (pass < 6)
  197911. #endif
  197912. {
  197913. /* each pixel depth is handled separately */
  197914. switch (row_info->pixel_depth)
  197915. {
  197916. case 1:
  197917. {
  197918. png_bytep sp;
  197919. png_bytep dp;
  197920. int shift;
  197921. int d;
  197922. int value;
  197923. png_uint_32 i;
  197924. png_uint_32 row_width = row_info->width;
  197925. dp = row;
  197926. d = 0;
  197927. shift = 7;
  197928. for (i = png_pass_start[pass]; i < row_width;
  197929. i += png_pass_inc[pass])
  197930. {
  197931. sp = row + (png_size_t)(i >> 3);
  197932. value = (int)(*sp >> (7 - (int)(i & 0x07))) & 0x01;
  197933. d |= (value << shift);
  197934. if (shift == 0)
  197935. {
  197936. shift = 7;
  197937. *dp++ = (png_byte)d;
  197938. d = 0;
  197939. }
  197940. else
  197941. shift--;
  197942. }
  197943. if (shift != 7)
  197944. *dp = (png_byte)d;
  197945. break;
  197946. }
  197947. case 2:
  197948. {
  197949. png_bytep sp;
  197950. png_bytep dp;
  197951. int shift;
  197952. int d;
  197953. int value;
  197954. png_uint_32 i;
  197955. png_uint_32 row_width = row_info->width;
  197956. dp = row;
  197957. shift = 6;
  197958. d = 0;
  197959. for (i = png_pass_start[pass]; i < row_width;
  197960. i += png_pass_inc[pass])
  197961. {
  197962. sp = row + (png_size_t)(i >> 2);
  197963. value = (*sp >> ((3 - (int)(i & 0x03)) << 1)) & 0x03;
  197964. d |= (value << shift);
  197965. if (shift == 0)
  197966. {
  197967. shift = 6;
  197968. *dp++ = (png_byte)d;
  197969. d = 0;
  197970. }
  197971. else
  197972. shift -= 2;
  197973. }
  197974. if (shift != 6)
  197975. *dp = (png_byte)d;
  197976. break;
  197977. }
  197978. case 4:
  197979. {
  197980. png_bytep sp;
  197981. png_bytep dp;
  197982. int shift;
  197983. int d;
  197984. int value;
  197985. png_uint_32 i;
  197986. png_uint_32 row_width = row_info->width;
  197987. dp = row;
  197988. shift = 4;
  197989. d = 0;
  197990. for (i = png_pass_start[pass]; i < row_width;
  197991. i += png_pass_inc[pass])
  197992. {
  197993. sp = row + (png_size_t)(i >> 1);
  197994. value = (*sp >> ((1 - (int)(i & 0x01)) << 2)) & 0x0f;
  197995. d |= (value << shift);
  197996. if (shift == 0)
  197997. {
  197998. shift = 4;
  197999. *dp++ = (png_byte)d;
  198000. d = 0;
  198001. }
  198002. else
  198003. shift -= 4;
  198004. }
  198005. if (shift != 4)
  198006. *dp = (png_byte)d;
  198007. break;
  198008. }
  198009. default:
  198010. {
  198011. png_bytep sp;
  198012. png_bytep dp;
  198013. png_uint_32 i;
  198014. png_uint_32 row_width = row_info->width;
  198015. png_size_t pixel_bytes;
  198016. /* start at the beginning */
  198017. dp = row;
  198018. /* find out how many bytes each pixel takes up */
  198019. pixel_bytes = (row_info->pixel_depth >> 3);
  198020. /* loop through the row, only looking at the pixels that
  198021. matter */
  198022. for (i = png_pass_start[pass]; i < row_width;
  198023. i += png_pass_inc[pass])
  198024. {
  198025. /* find out where the original pixel is */
  198026. sp = row + (png_size_t)i * pixel_bytes;
  198027. /* move the pixel */
  198028. if (dp != sp)
  198029. png_memcpy(dp, sp, pixel_bytes);
  198030. /* next pixel */
  198031. dp += pixel_bytes;
  198032. }
  198033. break;
  198034. }
  198035. }
  198036. /* set new row width */
  198037. row_info->width = (row_info->width +
  198038. png_pass_inc[pass] - 1 -
  198039. png_pass_start[pass]) /
  198040. png_pass_inc[pass];
  198041. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  198042. row_info->width);
  198043. }
  198044. }
  198045. #endif
  198046. /* This filters the row, chooses which filter to use, if it has not already
  198047. * been specified by the application, and then writes the row out with the
  198048. * chosen filter.
  198049. */
  198050. #define PNG_MAXSUM (((png_uint_32)(-1)) >> 1)
  198051. #define PNG_HISHIFT 10
  198052. #define PNG_LOMASK ((png_uint_32)0xffffL)
  198053. #define PNG_HIMASK ((png_uint_32)(~PNG_LOMASK >> PNG_HISHIFT))
  198054. void /* PRIVATE */
  198055. png_write_find_filter(png_structp png_ptr, png_row_infop row_info)
  198056. {
  198057. png_bytep best_row;
  198058. #ifndef PNG_NO_WRITE_FILTER
  198059. png_bytep prev_row, row_buf;
  198060. png_uint_32 mins, bpp;
  198061. png_byte filter_to_do = png_ptr->do_filter;
  198062. png_uint_32 row_bytes = row_info->rowbytes;
  198063. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  198064. int num_p_filters = (int)png_ptr->num_prev_filters;
  198065. #endif
  198066. png_debug(1, "in png_write_find_filter\n");
  198067. /* find out how many bytes offset each pixel is */
  198068. bpp = (row_info->pixel_depth + 7) >> 3;
  198069. prev_row = png_ptr->prev_row;
  198070. #endif
  198071. best_row = png_ptr->row_buf;
  198072. #ifndef PNG_NO_WRITE_FILTER
  198073. row_buf = best_row;
  198074. mins = PNG_MAXSUM;
  198075. /* The prediction method we use is to find which method provides the
  198076. * smallest value when summing the absolute values of the distances
  198077. * from zero, using anything >= 128 as negative numbers. This is known
  198078. * as the "minimum sum of absolute differences" heuristic. Other
  198079. * heuristics are the "weighted minimum sum of absolute differences"
  198080. * (experimental and can in theory improve compression), and the "zlib
  198081. * predictive" method (not implemented yet), which does test compressions
  198082. * of lines using different filter methods, and then chooses the
  198083. * (series of) filter(s) that give minimum compressed data size (VERY
  198084. * computationally expensive).
  198085. *
  198086. * GRR 980525: consider also
  198087. * (1) minimum sum of absolute differences from running average (i.e.,
  198088. * keep running sum of non-absolute differences & count of bytes)
  198089. * [track dispersion, too? restart average if dispersion too large?]
  198090. * (1b) minimum sum of absolute differences from sliding average, probably
  198091. * with window size <= deflate window (usually 32K)
  198092. * (2) minimum sum of squared differences from zero or running average
  198093. * (i.e., ~ root-mean-square approach)
  198094. */
  198095. /* We don't need to test the 'no filter' case if this is the only filter
  198096. * that has been chosen, as it doesn't actually do anything to the data.
  198097. */
  198098. if ((filter_to_do & PNG_FILTER_NONE) &&
  198099. filter_to_do != PNG_FILTER_NONE)
  198100. {
  198101. png_bytep rp;
  198102. png_uint_32 sum = 0;
  198103. png_uint_32 i;
  198104. int v;
  198105. for (i = 0, rp = row_buf + 1; i < row_bytes; i++, rp++)
  198106. {
  198107. v = *rp;
  198108. sum += (v < 128) ? v : 256 - v;
  198109. }
  198110. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  198111. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  198112. {
  198113. png_uint_32 sumhi, sumlo;
  198114. int j;
  198115. sumlo = sum & PNG_LOMASK;
  198116. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK; /* Gives us some footroom */
  198117. /* Reduce the sum if we match any of the previous rows */
  198118. for (j = 0; j < num_p_filters; j++)
  198119. {
  198120. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_NONE)
  198121. {
  198122. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  198123. PNG_WEIGHT_SHIFT;
  198124. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  198125. PNG_WEIGHT_SHIFT;
  198126. }
  198127. }
  198128. /* Factor in the cost of this filter (this is here for completeness,
  198129. * but it makes no sense to have a "cost" for the NONE filter, as
  198130. * it has the minimum possible computational cost - none).
  198131. */
  198132. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_NONE]) >>
  198133. PNG_COST_SHIFT;
  198134. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_NONE]) >>
  198135. PNG_COST_SHIFT;
  198136. if (sumhi > PNG_HIMASK)
  198137. sum = PNG_MAXSUM;
  198138. else
  198139. sum = (sumhi << PNG_HISHIFT) + sumlo;
  198140. }
  198141. #endif
  198142. mins = sum;
  198143. }
  198144. /* sub filter */
  198145. if (filter_to_do == PNG_FILTER_SUB)
  198146. /* it's the only filter so no testing is needed */
  198147. {
  198148. png_bytep rp, lp, dp;
  198149. png_uint_32 i;
  198150. for (i = 0, rp = row_buf + 1, dp = png_ptr->sub_row + 1; i < bpp;
  198151. i++, rp++, dp++)
  198152. {
  198153. *dp = *rp;
  198154. }
  198155. for (lp = row_buf + 1; i < row_bytes;
  198156. i++, rp++, lp++, dp++)
  198157. {
  198158. *dp = (png_byte)(((int)*rp - (int)*lp) & 0xff);
  198159. }
  198160. best_row = png_ptr->sub_row;
  198161. }
  198162. else if (filter_to_do & PNG_FILTER_SUB)
  198163. {
  198164. png_bytep rp, dp, lp;
  198165. png_uint_32 sum = 0, lmins = mins;
  198166. png_uint_32 i;
  198167. int v;
  198168. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  198169. /* We temporarily increase the "minimum sum" by the factor we
  198170. * would reduce the sum of this filter, so that we can do the
  198171. * early exit comparison without scaling the sum each time.
  198172. */
  198173. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  198174. {
  198175. int j;
  198176. png_uint_32 lmhi, lmlo;
  198177. lmlo = lmins & PNG_LOMASK;
  198178. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  198179. for (j = 0; j < num_p_filters; j++)
  198180. {
  198181. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_SUB)
  198182. {
  198183. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  198184. PNG_WEIGHT_SHIFT;
  198185. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  198186. PNG_WEIGHT_SHIFT;
  198187. }
  198188. }
  198189. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  198190. PNG_COST_SHIFT;
  198191. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  198192. PNG_COST_SHIFT;
  198193. if (lmhi > PNG_HIMASK)
  198194. lmins = PNG_MAXSUM;
  198195. else
  198196. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  198197. }
  198198. #endif
  198199. for (i = 0, rp = row_buf + 1, dp = png_ptr->sub_row + 1; i < bpp;
  198200. i++, rp++, dp++)
  198201. {
  198202. v = *dp = *rp;
  198203. sum += (v < 128) ? v : 256 - v;
  198204. }
  198205. for (lp = row_buf + 1; i < row_bytes;
  198206. i++, rp++, lp++, dp++)
  198207. {
  198208. v = *dp = (png_byte)(((int)*rp - (int)*lp) & 0xff);
  198209. sum += (v < 128) ? v : 256 - v;
  198210. if (sum > lmins) /* We are already worse, don't continue. */
  198211. break;
  198212. }
  198213. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  198214. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  198215. {
  198216. int j;
  198217. png_uint_32 sumhi, sumlo;
  198218. sumlo = sum & PNG_LOMASK;
  198219. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  198220. for (j = 0; j < num_p_filters; j++)
  198221. {
  198222. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_SUB)
  198223. {
  198224. sumlo = (sumlo * png_ptr->inv_filter_weights[j]) >>
  198225. PNG_WEIGHT_SHIFT;
  198226. sumhi = (sumhi * png_ptr->inv_filter_weights[j]) >>
  198227. PNG_WEIGHT_SHIFT;
  198228. }
  198229. }
  198230. sumlo = (sumlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  198231. PNG_COST_SHIFT;
  198232. sumhi = (sumhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  198233. PNG_COST_SHIFT;
  198234. if (sumhi > PNG_HIMASK)
  198235. sum = PNG_MAXSUM;
  198236. else
  198237. sum = (sumhi << PNG_HISHIFT) + sumlo;
  198238. }
  198239. #endif
  198240. if (sum < mins)
  198241. {
  198242. mins = sum;
  198243. best_row = png_ptr->sub_row;
  198244. }
  198245. }
  198246. /* up filter */
  198247. if (filter_to_do == PNG_FILTER_UP)
  198248. {
  198249. png_bytep rp, dp, pp;
  198250. png_uint_32 i;
  198251. for (i = 0, rp = row_buf + 1, dp = png_ptr->up_row + 1,
  198252. pp = prev_row + 1; i < row_bytes;
  198253. i++, rp++, pp++, dp++)
  198254. {
  198255. *dp = (png_byte)(((int)*rp - (int)*pp) & 0xff);
  198256. }
  198257. best_row = png_ptr->up_row;
  198258. }
  198259. else if (filter_to_do & PNG_FILTER_UP)
  198260. {
  198261. png_bytep rp, dp, pp;
  198262. png_uint_32 sum = 0, lmins = mins;
  198263. png_uint_32 i;
  198264. int v;
  198265. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  198266. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  198267. {
  198268. int j;
  198269. png_uint_32 lmhi, lmlo;
  198270. lmlo = lmins & PNG_LOMASK;
  198271. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  198272. for (j = 0; j < num_p_filters; j++)
  198273. {
  198274. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_UP)
  198275. {
  198276. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  198277. PNG_WEIGHT_SHIFT;
  198278. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  198279. PNG_WEIGHT_SHIFT;
  198280. }
  198281. }
  198282. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_UP]) >>
  198283. PNG_COST_SHIFT;
  198284. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_UP]) >>
  198285. PNG_COST_SHIFT;
  198286. if (lmhi > PNG_HIMASK)
  198287. lmins = PNG_MAXSUM;
  198288. else
  198289. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  198290. }
  198291. #endif
  198292. for (i = 0, rp = row_buf + 1, dp = png_ptr->up_row + 1,
  198293. pp = prev_row + 1; i < row_bytes; i++)
  198294. {
  198295. v = *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  198296. sum += (v < 128) ? v : 256 - v;
  198297. if (sum > lmins) /* We are already worse, don't continue. */
  198298. break;
  198299. }
  198300. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  198301. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  198302. {
  198303. int j;
  198304. png_uint_32 sumhi, sumlo;
  198305. sumlo = sum & PNG_LOMASK;
  198306. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  198307. for (j = 0; j < num_p_filters; j++)
  198308. {
  198309. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_UP)
  198310. {
  198311. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  198312. PNG_WEIGHT_SHIFT;
  198313. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  198314. PNG_WEIGHT_SHIFT;
  198315. }
  198316. }
  198317. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_UP]) >>
  198318. PNG_COST_SHIFT;
  198319. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_UP]) >>
  198320. PNG_COST_SHIFT;
  198321. if (sumhi > PNG_HIMASK)
  198322. sum = PNG_MAXSUM;
  198323. else
  198324. sum = (sumhi << PNG_HISHIFT) + sumlo;
  198325. }
  198326. #endif
  198327. if (sum < mins)
  198328. {
  198329. mins = sum;
  198330. best_row = png_ptr->up_row;
  198331. }
  198332. }
  198333. /* avg filter */
  198334. if (filter_to_do == PNG_FILTER_AVG)
  198335. {
  198336. png_bytep rp, dp, pp, lp;
  198337. png_uint_32 i;
  198338. for (i = 0, rp = row_buf + 1, dp = png_ptr->avg_row + 1,
  198339. pp = prev_row + 1; i < bpp; i++)
  198340. {
  198341. *dp++ = (png_byte)(((int)*rp++ - ((int)*pp++ / 2)) & 0xff);
  198342. }
  198343. for (lp = row_buf + 1; i < row_bytes; i++)
  198344. {
  198345. *dp++ = (png_byte)(((int)*rp++ - (((int)*pp++ + (int)*lp++) / 2))
  198346. & 0xff);
  198347. }
  198348. best_row = png_ptr->avg_row;
  198349. }
  198350. else if (filter_to_do & PNG_FILTER_AVG)
  198351. {
  198352. png_bytep rp, dp, pp, lp;
  198353. png_uint_32 sum = 0, lmins = mins;
  198354. png_uint_32 i;
  198355. int v;
  198356. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  198357. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  198358. {
  198359. int j;
  198360. png_uint_32 lmhi, lmlo;
  198361. lmlo = lmins & PNG_LOMASK;
  198362. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  198363. for (j = 0; j < num_p_filters; j++)
  198364. {
  198365. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_AVG)
  198366. {
  198367. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  198368. PNG_WEIGHT_SHIFT;
  198369. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  198370. PNG_WEIGHT_SHIFT;
  198371. }
  198372. }
  198373. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_AVG]) >>
  198374. PNG_COST_SHIFT;
  198375. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_AVG]) >>
  198376. PNG_COST_SHIFT;
  198377. if (lmhi > PNG_HIMASK)
  198378. lmins = PNG_MAXSUM;
  198379. else
  198380. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  198381. }
  198382. #endif
  198383. for (i = 0, rp = row_buf + 1, dp = png_ptr->avg_row + 1,
  198384. pp = prev_row + 1; i < bpp; i++)
  198385. {
  198386. v = *dp++ = (png_byte)(((int)*rp++ - ((int)*pp++ / 2)) & 0xff);
  198387. sum += (v < 128) ? v : 256 - v;
  198388. }
  198389. for (lp = row_buf + 1; i < row_bytes; i++)
  198390. {
  198391. v = *dp++ =
  198392. (png_byte)(((int)*rp++ - (((int)*pp++ + (int)*lp++) / 2)) & 0xff);
  198393. sum += (v < 128) ? v : 256 - v;
  198394. if (sum > lmins) /* We are already worse, don't continue. */
  198395. break;
  198396. }
  198397. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  198398. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  198399. {
  198400. int j;
  198401. png_uint_32 sumhi, sumlo;
  198402. sumlo = sum & PNG_LOMASK;
  198403. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  198404. for (j = 0; j < num_p_filters; j++)
  198405. {
  198406. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_NONE)
  198407. {
  198408. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  198409. PNG_WEIGHT_SHIFT;
  198410. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  198411. PNG_WEIGHT_SHIFT;
  198412. }
  198413. }
  198414. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_AVG]) >>
  198415. PNG_COST_SHIFT;
  198416. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_AVG]) >>
  198417. PNG_COST_SHIFT;
  198418. if (sumhi > PNG_HIMASK)
  198419. sum = PNG_MAXSUM;
  198420. else
  198421. sum = (sumhi << PNG_HISHIFT) + sumlo;
  198422. }
  198423. #endif
  198424. if (sum < mins)
  198425. {
  198426. mins = sum;
  198427. best_row = png_ptr->avg_row;
  198428. }
  198429. }
  198430. /* Paeth filter */
  198431. if (filter_to_do == PNG_FILTER_PAETH)
  198432. {
  198433. png_bytep rp, dp, pp, cp, lp;
  198434. png_uint_32 i;
  198435. for (i = 0, rp = row_buf + 1, dp = png_ptr->paeth_row + 1,
  198436. pp = prev_row + 1; i < bpp; i++)
  198437. {
  198438. *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  198439. }
  198440. for (lp = row_buf + 1, cp = prev_row + 1; i < row_bytes; i++)
  198441. {
  198442. int a, b, c, pa, pb, pc, p;
  198443. b = *pp++;
  198444. c = *cp++;
  198445. a = *lp++;
  198446. p = b - c;
  198447. pc = a - c;
  198448. #ifdef PNG_USE_ABS
  198449. pa = abs(p);
  198450. pb = abs(pc);
  198451. pc = abs(p + pc);
  198452. #else
  198453. pa = p < 0 ? -p : p;
  198454. pb = pc < 0 ? -pc : pc;
  198455. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  198456. #endif
  198457. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  198458. *dp++ = (png_byte)(((int)*rp++ - p) & 0xff);
  198459. }
  198460. best_row = png_ptr->paeth_row;
  198461. }
  198462. else if (filter_to_do & PNG_FILTER_PAETH)
  198463. {
  198464. png_bytep rp, dp, pp, cp, lp;
  198465. png_uint_32 sum = 0, lmins = mins;
  198466. png_uint_32 i;
  198467. int v;
  198468. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  198469. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  198470. {
  198471. int j;
  198472. png_uint_32 lmhi, lmlo;
  198473. lmlo = lmins & PNG_LOMASK;
  198474. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  198475. for (j = 0; j < num_p_filters; j++)
  198476. {
  198477. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_PAETH)
  198478. {
  198479. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  198480. PNG_WEIGHT_SHIFT;
  198481. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  198482. PNG_WEIGHT_SHIFT;
  198483. }
  198484. }
  198485. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  198486. PNG_COST_SHIFT;
  198487. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  198488. PNG_COST_SHIFT;
  198489. if (lmhi > PNG_HIMASK)
  198490. lmins = PNG_MAXSUM;
  198491. else
  198492. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  198493. }
  198494. #endif
  198495. for (i = 0, rp = row_buf + 1, dp = png_ptr->paeth_row + 1,
  198496. pp = prev_row + 1; i < bpp; i++)
  198497. {
  198498. v = *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  198499. sum += (v < 128) ? v : 256 - v;
  198500. }
  198501. for (lp = row_buf + 1, cp = prev_row + 1; i < row_bytes; i++)
  198502. {
  198503. int a, b, c, pa, pb, pc, p;
  198504. b = *pp++;
  198505. c = *cp++;
  198506. a = *lp++;
  198507. #ifndef PNG_SLOW_PAETH
  198508. p = b - c;
  198509. pc = a - c;
  198510. #ifdef PNG_USE_ABS
  198511. pa = abs(p);
  198512. pb = abs(pc);
  198513. pc = abs(p + pc);
  198514. #else
  198515. pa = p < 0 ? -p : p;
  198516. pb = pc < 0 ? -pc : pc;
  198517. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  198518. #endif
  198519. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  198520. #else /* PNG_SLOW_PAETH */
  198521. p = a + b - c;
  198522. pa = abs(p - a);
  198523. pb = abs(p - b);
  198524. pc = abs(p - c);
  198525. if (pa <= pb && pa <= pc)
  198526. p = a;
  198527. else if (pb <= pc)
  198528. p = b;
  198529. else
  198530. p = c;
  198531. #endif /* PNG_SLOW_PAETH */
  198532. v = *dp++ = (png_byte)(((int)*rp++ - p) & 0xff);
  198533. sum += (v < 128) ? v : 256 - v;
  198534. if (sum > lmins) /* We are already worse, don't continue. */
  198535. break;
  198536. }
  198537. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  198538. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  198539. {
  198540. int j;
  198541. png_uint_32 sumhi, sumlo;
  198542. sumlo = sum & PNG_LOMASK;
  198543. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  198544. for (j = 0; j < num_p_filters; j++)
  198545. {
  198546. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_PAETH)
  198547. {
  198548. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  198549. PNG_WEIGHT_SHIFT;
  198550. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  198551. PNG_WEIGHT_SHIFT;
  198552. }
  198553. }
  198554. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  198555. PNG_COST_SHIFT;
  198556. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  198557. PNG_COST_SHIFT;
  198558. if (sumhi > PNG_HIMASK)
  198559. sum = PNG_MAXSUM;
  198560. else
  198561. sum = (sumhi << PNG_HISHIFT) + sumlo;
  198562. }
  198563. #endif
  198564. if (sum < mins)
  198565. {
  198566. best_row = png_ptr->paeth_row;
  198567. }
  198568. }
  198569. #endif /* PNG_NO_WRITE_FILTER */
  198570. /* Do the actual writing of the filtered row data from the chosen filter. */
  198571. png_write_filtered_row(png_ptr, best_row);
  198572. #ifndef PNG_NO_WRITE_FILTER
  198573. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  198574. /* Save the type of filter we picked this time for future calculations */
  198575. if (png_ptr->num_prev_filters > 0)
  198576. {
  198577. int j;
  198578. for (j = 1; j < num_p_filters; j++)
  198579. {
  198580. png_ptr->prev_filters[j] = png_ptr->prev_filters[j - 1];
  198581. }
  198582. png_ptr->prev_filters[j] = best_row[0];
  198583. }
  198584. #endif
  198585. #endif /* PNG_NO_WRITE_FILTER */
  198586. }
  198587. /* Do the actual writing of a previously filtered row. */
  198588. void /* PRIVATE */
  198589. png_write_filtered_row(png_structp png_ptr, png_bytep filtered_row)
  198590. {
  198591. png_debug(1, "in png_write_filtered_row\n");
  198592. png_debug1(2, "filter = %d\n", filtered_row[0]);
  198593. /* set up the zlib input buffer */
  198594. png_ptr->zstream.next_in = filtered_row;
  198595. png_ptr->zstream.avail_in = (uInt)png_ptr->row_info.rowbytes + 1;
  198596. /* repeat until we have compressed all the data */
  198597. do
  198598. {
  198599. int ret; /* return of zlib */
  198600. /* compress the data */
  198601. ret = deflate(&png_ptr->zstream, Z_NO_FLUSH);
  198602. /* check for compression errors */
  198603. if (ret != Z_OK)
  198604. {
  198605. if (png_ptr->zstream.msg != NULL)
  198606. png_error(png_ptr, png_ptr->zstream.msg);
  198607. else
  198608. png_error(png_ptr, "zlib error");
  198609. }
  198610. /* see if it is time to write another IDAT */
  198611. if (!(png_ptr->zstream.avail_out))
  198612. {
  198613. /* write the IDAT and reset the zlib output buffer */
  198614. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  198615. png_ptr->zstream.next_out = png_ptr->zbuf;
  198616. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  198617. }
  198618. /* repeat until all data has been compressed */
  198619. } while (png_ptr->zstream.avail_in);
  198620. /* swap the current and previous rows */
  198621. if (png_ptr->prev_row != NULL)
  198622. {
  198623. png_bytep tptr;
  198624. tptr = png_ptr->prev_row;
  198625. png_ptr->prev_row = png_ptr->row_buf;
  198626. png_ptr->row_buf = tptr;
  198627. }
  198628. /* finish row - updates counters and flushes zlib if last row */
  198629. png_write_finish_row(png_ptr);
  198630. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  198631. png_ptr->flush_rows++;
  198632. if (png_ptr->flush_dist > 0 &&
  198633. png_ptr->flush_rows >= png_ptr->flush_dist)
  198634. {
  198635. png_write_flush(png_ptr);
  198636. }
  198637. #endif
  198638. }
  198639. #endif /* PNG_WRITE_SUPPORTED */
  198640. /********* End of inlined file: pngwutil.c *********/
  198641. }
  198642. #else
  198643. #define PNG_INTERNAL
  198644. #define PNG_SETJMP_NOT_SUPPORTED
  198645. #include <png.h>
  198646. #include <pngconf.h>
  198647. #endif
  198648. }
  198649. #ifdef _MSC_VER
  198650. #pragma warning (pop)
  198651. #endif
  198652. BEGIN_JUCE_NAMESPACE
  198653. using namespace pnglibNamespace;
  198654. using ::calloc;
  198655. using ::malloc;
  198656. using ::free;
  198657. static void pngReadCallback (png_structp pngReadStruct, png_bytep data, png_size_t length) throw()
  198658. {
  198659. InputStream* const in = (InputStream*) png_get_io_ptr (pngReadStruct);
  198660. in->read (data, (int) length);
  198661. }
  198662. struct PNGErrorStruct {};
  198663. static void pngErrorCallback (png_structp, png_const_charp)
  198664. {
  198665. throw PNGErrorStruct();
  198666. }
  198667. Image* juce_loadPNGImageFromStream (InputStream& in) throw()
  198668. {
  198669. Image* image = 0;
  198670. png_structp pngReadStruct;
  198671. png_infop pngInfoStruct;
  198672. pngReadStruct = png_create_read_struct (PNG_LIBPNG_VER_STRING, 0, 0, 0);
  198673. if (pngReadStruct != 0)
  198674. {
  198675. pngInfoStruct = png_create_info_struct (pngReadStruct);
  198676. if (pngInfoStruct == 0)
  198677. {
  198678. png_destroy_read_struct (&pngReadStruct, 0, 0);
  198679. return 0;
  198680. }
  198681. png_set_error_fn (pngReadStruct, 0, pngErrorCallback, pngErrorCallback);
  198682. // read the header..
  198683. png_set_read_fn (pngReadStruct, &in, pngReadCallback);
  198684. png_uint_32 width, height;
  198685. int bitDepth, colorType, interlaceType;
  198686. png_read_info (pngReadStruct, pngInfoStruct);
  198687. png_get_IHDR (pngReadStruct, pngInfoStruct,
  198688. &width, &height,
  198689. &bitDepth, &colorType,
  198690. &interlaceType, 0, 0);
  198691. if (bitDepth == 16)
  198692. png_set_strip_16 (pngReadStruct);
  198693. if (colorType == PNG_COLOR_TYPE_PALETTE)
  198694. png_set_expand (pngReadStruct);
  198695. if (bitDepth < 8)
  198696. png_set_expand (pngReadStruct);
  198697. if (png_get_valid (pngReadStruct, pngInfoStruct, PNG_INFO_tRNS))
  198698. png_set_expand (pngReadStruct);
  198699. if (colorType == PNG_COLOR_TYPE_GRAY || colorType == PNG_COLOR_TYPE_GRAY_ALPHA)
  198700. png_set_gray_to_rgb (pngReadStruct);
  198701. png_set_add_alpha (pngReadStruct, 0xff, PNG_FILLER_AFTER);
  198702. const bool hasAlphaChan = (colorType & PNG_COLOR_MASK_ALPHA) != 0
  198703. || pngInfoStruct->num_trans > 0;
  198704. // Load the image into a temp buffer in the pnglib format..
  198705. uint8* const tempBuffer = (uint8*) juce_malloc (height * (width << 2));
  198706. png_bytepp rows = (png_bytepp) juce_malloc (sizeof (png_bytep) * height);
  198707. int y;
  198708. for (y = (int) height; --y >= 0;)
  198709. rows[y] = (png_bytep) (tempBuffer + (width << 2) * y);
  198710. png_read_image (pngReadStruct, rows);
  198711. png_read_end (pngReadStruct, pngInfoStruct);
  198712. juce_free (rows);
  198713. png_destroy_read_struct (&pngReadStruct, &pngInfoStruct, 0);
  198714. // now convert the data to a juce image format..
  198715. image = new Image (hasAlphaChan ? Image::ARGB : Image::RGB,
  198716. width, height, hasAlphaChan);
  198717. int stride, pixelStride;
  198718. uint8* const pixels = image->lockPixelDataReadWrite (0, 0, width, height, stride, pixelStride);
  198719. uint8* srcRow = tempBuffer;
  198720. uint8* destRow = pixels;
  198721. for (y = 0; y < (int) height; ++y)
  198722. {
  198723. const uint8* src = srcRow;
  198724. srcRow += (width << 2);
  198725. uint8* dest = destRow;
  198726. destRow += stride;
  198727. if (hasAlphaChan)
  198728. {
  198729. for (int i = width; --i >= 0;)
  198730. {
  198731. ((PixelARGB*) dest)->setARGB (src[3], src[0], src[1], src[2]);
  198732. ((PixelARGB*) dest)->premultiply();
  198733. dest += pixelStride;
  198734. src += 4;
  198735. }
  198736. }
  198737. else
  198738. {
  198739. for (int i = width; --i >= 0;)
  198740. {
  198741. ((PixelRGB*) dest)->setARGB (0, src[0], src[1], src[2]);
  198742. dest += pixelStride;
  198743. src += 4;
  198744. }
  198745. }
  198746. }
  198747. image->releasePixelDataReadWrite (pixels);
  198748. juce_free (tempBuffer);
  198749. }
  198750. return image;
  198751. }
  198752. static void pngWriteDataCallback (png_structp png_ptr, png_bytep data, png_size_t length) throw()
  198753. {
  198754. OutputStream* const out = (OutputStream*) png_ptr->io_ptr;
  198755. const bool ok = out->write (data, length);
  198756. (void) ok;
  198757. jassert (ok);
  198758. }
  198759. bool juce_writePNGImageToStream (const Image& image, OutputStream& out) throw()
  198760. {
  198761. const int width = image.getWidth();
  198762. const int height = image.getHeight();
  198763. png_structp pngWriteStruct = png_create_write_struct (PNG_LIBPNG_VER_STRING, 0, 0, 0);
  198764. if (pngWriteStruct == 0)
  198765. return false;
  198766. png_infop pngInfoStruct = png_create_info_struct (pngWriteStruct);
  198767. if (pngInfoStruct == 0)
  198768. {
  198769. png_destroy_write_struct (&pngWriteStruct, (png_infopp) 0);
  198770. return false;
  198771. }
  198772. png_set_write_fn (pngWriteStruct, &out, pngWriteDataCallback, 0);
  198773. png_set_IHDR (pngWriteStruct, pngInfoStruct, width, height, 8,
  198774. image.hasAlphaChannel() ? PNG_COLOR_TYPE_RGB_ALPHA
  198775. : PNG_COLOR_TYPE_RGB,
  198776. PNG_INTERLACE_NONE,
  198777. PNG_COMPRESSION_TYPE_BASE,
  198778. PNG_FILTER_TYPE_BASE);
  198779. png_bytep rowData = (png_bytep) juce_malloc (width * 4 * sizeof (png_byte));
  198780. png_color_8 sig_bit;
  198781. sig_bit.red = 8;
  198782. sig_bit.green = 8;
  198783. sig_bit.blue = 8;
  198784. sig_bit.alpha = 8;
  198785. png_set_sBIT (pngWriteStruct, pngInfoStruct, &sig_bit);
  198786. png_write_info (pngWriteStruct, pngInfoStruct);
  198787. png_set_shift (pngWriteStruct, &sig_bit);
  198788. png_set_packing (pngWriteStruct);
  198789. for (int y = 0; y < height; ++y)
  198790. {
  198791. uint8* dst = (uint8*) rowData;
  198792. int stride, pixelStride;
  198793. const uint8* pixels = image.lockPixelDataReadOnly (0, y, width, 1, stride, pixelStride);
  198794. const uint8* src = pixels;
  198795. if (image.hasAlphaChannel())
  198796. {
  198797. for (int i = width; --i >= 0;)
  198798. {
  198799. PixelARGB p (*(const PixelARGB*) src);
  198800. p.unpremultiply();
  198801. *dst++ = p.getRed();
  198802. *dst++ = p.getGreen();
  198803. *dst++ = p.getBlue();
  198804. *dst++ = p.getAlpha();
  198805. src += pixelStride;
  198806. }
  198807. }
  198808. else
  198809. {
  198810. for (int i = width; --i >= 0;)
  198811. {
  198812. *dst++ = ((const PixelRGB*) src)->getRed();
  198813. *dst++ = ((const PixelRGB*) src)->getGreen();
  198814. *dst++ = ((const PixelRGB*) src)->getBlue();
  198815. src += pixelStride;
  198816. }
  198817. }
  198818. png_write_rows (pngWriteStruct, &rowData, 1);
  198819. image.releasePixelDataReadOnly (pixels);
  198820. }
  198821. juce_free (rowData);
  198822. png_write_end (pngWriteStruct, pngInfoStruct);
  198823. png_destroy_write_struct (&pngWriteStruct, &pngInfoStruct);
  198824. out.flush();
  198825. return true;
  198826. }
  198827. END_JUCE_NAMESPACE
  198828. /********* End of inlined file: juce_PNGLoader.cpp *********/
  198829. #endif
  198830. //==============================================================================
  198831. #if JUCE_WIN32
  198832. /********* Start of inlined file: juce_win32_NativeCode.cpp *********/
  198833. /*
  198834. This file wraps together all the win32-specific code, so that
  198835. we can include all the native headers just once, and compile all our
  198836. platform-specific stuff in one big lump, keeping it out of the way of
  198837. the rest of the codebase.
  198838. */
  198839. BEGIN_JUCE_NAMESPACE
  198840. #define JUCE_INCLUDED_FILE 1
  198841. // Now include the actual code files..
  198842. /********* Start of inlined file: juce_win32_DynamicLibraryLoader.cpp *********/
  198843. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  198844. // compiled on its own).
  198845. #if JUCE_INCLUDED_FILE
  198846. /********* Start of inlined file: juce_win32_DynamicLibraryLoader.h *********/
  198847. #ifndef __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  198848. #define __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  198849. #ifndef DOXYGEN
  198850. // use with DynamicLibraryLoader to simplify importing functions
  198851. //
  198852. // functionName: function to import
  198853. // localFunctionName: name you want to use to actually call it (must be different)
  198854. // returnType: the return type
  198855. // object: the DynamicLibraryLoader to use
  198856. // params: list of params (bracketed)
  198857. //
  198858. #define DynamicLibraryImport(functionName, localFunctionName, returnType, object, params) \
  198859. typedef returnType (WINAPI *type##localFunctionName) params; \
  198860. type##localFunctionName localFunctionName \
  198861. = (type##localFunctionName)object.findProcAddress (#functionName);
  198862. // loads and unloads a DLL automatically
  198863. class JUCE_API DynamicLibraryLoader
  198864. {
  198865. public:
  198866. DynamicLibraryLoader (const String& name);
  198867. ~DynamicLibraryLoader();
  198868. void* findProcAddress (const String& functionName);
  198869. private:
  198870. void* libHandle;
  198871. };
  198872. #endif
  198873. #endif // __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  198874. /********* End of inlined file: juce_win32_DynamicLibraryLoader.h *********/
  198875. DynamicLibraryLoader::DynamicLibraryLoader (const String& name)
  198876. {
  198877. libHandle = LoadLibrary (name);
  198878. }
  198879. DynamicLibraryLoader::~DynamicLibraryLoader()
  198880. {
  198881. FreeLibrary ((HMODULE) libHandle);
  198882. }
  198883. void* DynamicLibraryLoader::findProcAddress (const String& functionName)
  198884. {
  198885. return (void*) GetProcAddress ((HMODULE) libHandle, functionName);
  198886. }
  198887. #endif
  198888. /********* End of inlined file: juce_win32_DynamicLibraryLoader.cpp *********/
  198889. /********* Start of inlined file: juce_win32_SystemStats.cpp *********/
  198890. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  198891. // compiled on its own).
  198892. #if JUCE_INCLUDED_FILE
  198893. extern void juce_updateMultiMonitorInfo() throw();
  198894. extern void juce_initialiseThreadEvents() throw();
  198895. void Logger::outputDebugString (const String& text) throw()
  198896. {
  198897. OutputDebugString (text + T("\n"));
  198898. }
  198899. void Logger::outputDebugPrintf (const tchar* format, ...) throw()
  198900. {
  198901. String text;
  198902. va_list args;
  198903. va_start (args, format);
  198904. text.vprintf(format, args);
  198905. outputDebugString (text);
  198906. }
  198907. static int64 hiResTicksPerSecond;
  198908. static double hiResTicksScaleFactor;
  198909. #if JUCE_USE_INTRINSICS
  198910. // CPU info functions using intrinsics...
  198911. #pragma intrinsic (__cpuid)
  198912. #pragma intrinsic (__rdtsc)
  198913. /*static unsigned int getCPUIDWord (int* familyModel = 0, int* extFeatures = 0) throw()
  198914. {
  198915. int info [4];
  198916. __cpuid (info, 1);
  198917. if (familyModel != 0)
  198918. *familyModel = info [0];
  198919. if (extFeatures != 0)
  198920. *extFeatures = info[1];
  198921. return info[3];
  198922. }*/
  198923. const String SystemStats::getCpuVendor() throw()
  198924. {
  198925. int info [4];
  198926. __cpuid (info, 0);
  198927. char v [12];
  198928. memcpy (v, info + 1, 4);
  198929. memcpy (v + 4, info + 3, 4);
  198930. memcpy (v + 8, info + 2, 4);
  198931. return String (v, 12);
  198932. }
  198933. #else
  198934. // CPU info functions using old fashioned inline asm...
  198935. /*static juce_noinline unsigned int getCPUIDWord (int* familyModel = 0, int* extFeatures = 0)
  198936. {
  198937. unsigned int cpu = 0;
  198938. unsigned int ext = 0;
  198939. unsigned int family = 0;
  198940. #if JUCE_GCC
  198941. unsigned int dummy = 0;
  198942. #endif
  198943. #ifndef __MINGW32__
  198944. __try
  198945. #endif
  198946. {
  198947. #if JUCE_GCC
  198948. __asm__ ("cpuid" : "=a" (family), "=b" (ext), "=c" (dummy),"=d" (cpu) : "a" (1));
  198949. #else
  198950. __asm
  198951. {
  198952. mov eax, 1
  198953. cpuid
  198954. mov cpu, edx
  198955. mov family, eax
  198956. mov ext, ebx
  198957. }
  198958. #endif
  198959. }
  198960. #ifndef __MINGW32__
  198961. __except (EXCEPTION_EXECUTE_HANDLER)
  198962. {
  198963. return 0;
  198964. }
  198965. #endif
  198966. if (familyModel != 0)
  198967. *familyModel = family;
  198968. if (extFeatures != 0)
  198969. *extFeatures = ext;
  198970. return cpu;
  198971. }*/
  198972. static void juce_getCpuVendor (char* const v)
  198973. {
  198974. int vendor[4];
  198975. zeromem (vendor, 16);
  198976. #ifdef JUCE_64BIT
  198977. #else
  198978. #ifndef __MINGW32__
  198979. __try
  198980. #endif
  198981. {
  198982. #if JUCE_GCC
  198983. unsigned int dummy = 0;
  198984. __asm__ ("cpuid" : "=a" (dummy), "=b" (vendor[0]), "=c" (vendor[2]),"=d" (vendor[1]) : "a" (0));
  198985. #else
  198986. __asm
  198987. {
  198988. mov eax, 0
  198989. cpuid
  198990. mov [vendor], ebx
  198991. mov [vendor + 4], edx
  198992. mov [vendor + 8], ecx
  198993. }
  198994. #endif
  198995. }
  198996. #ifndef __MINGW32__
  198997. __except (EXCEPTION_EXECUTE_HANDLER)
  198998. {
  198999. *v = 0;
  199000. }
  199001. #endif
  199002. #endif
  199003. memcpy (v, vendor, 16);
  199004. }
  199005. const String SystemStats::getCpuVendor() throw()
  199006. {
  199007. char v [16];
  199008. juce_getCpuVendor (v);
  199009. return String (v, 16);
  199010. }
  199011. #endif
  199012. struct CPUFlags
  199013. {
  199014. bool hasMMX : 1;
  199015. bool hasSSE : 1;
  199016. bool hasSSE2 : 1;
  199017. bool has3DNow : 1;
  199018. };
  199019. static CPUFlags cpuFlags;
  199020. bool SystemStats::hasMMX() throw()
  199021. {
  199022. return cpuFlags.hasMMX;
  199023. }
  199024. bool SystemStats::hasSSE() throw()
  199025. {
  199026. return cpuFlags.hasSSE;
  199027. }
  199028. bool SystemStats::hasSSE2() throw()
  199029. {
  199030. return cpuFlags.hasSSE2;
  199031. }
  199032. bool SystemStats::has3DNow() throw()
  199033. {
  199034. return cpuFlags.has3DNow;
  199035. }
  199036. void SystemStats::initialiseStats() throw()
  199037. {
  199038. juce_initialiseThreadEvents();
  199039. cpuFlags.hasMMX = IsProcessorFeaturePresent (PF_MMX_INSTRUCTIONS_AVAILABLE) != 0;
  199040. cpuFlags.hasSSE = IsProcessorFeaturePresent (PF_XMMI_INSTRUCTIONS_AVAILABLE) != 0;
  199041. cpuFlags.hasSSE2 = IsProcessorFeaturePresent (PF_XMMI64_INSTRUCTIONS_AVAILABLE) != 0;
  199042. #ifdef PF_AMD3D_INSTRUCTIONS_AVAILABLE
  199043. cpuFlags.has3DNow = IsProcessorFeaturePresent (PF_AMD3D_INSTRUCTIONS_AVAILABLE) != 0;
  199044. #else
  199045. cpuFlags.has3DNow = IsProcessorFeaturePresent (PF_3DNOW_INSTRUCTIONS_AVAILABLE) != 0;
  199046. #endif
  199047. LARGE_INTEGER f;
  199048. QueryPerformanceFrequency (&f);
  199049. hiResTicksPerSecond = f.QuadPart;
  199050. hiResTicksScaleFactor = 1000.0 / hiResTicksPerSecond;
  199051. String s (SystemStats::getJUCEVersion());
  199052. #ifdef JUCE_DEBUG
  199053. const MMRESULT res = timeBeginPeriod (1);
  199054. jassert (res == TIMERR_NOERROR);
  199055. #else
  199056. timeBeginPeriod (1);
  199057. #endif
  199058. #if defined (JUCE_DEBUG) && JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  199059. _CrtSetDbgFlag (_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
  199060. #endif
  199061. }
  199062. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType() throw()
  199063. {
  199064. OSVERSIONINFO info;
  199065. info.dwOSVersionInfoSize = sizeof (info);
  199066. GetVersionEx (&info);
  199067. if (info.dwPlatformId == VER_PLATFORM_WIN32_NT)
  199068. {
  199069. switch (info.dwMajorVersion)
  199070. {
  199071. case 5: return (info.dwMinorVersion == 0) ? Win2000 : WinXP;
  199072. case 6: return (info.dwMinorVersion == 0) ? WinVista : Windows7;
  199073. default: jassertfalse; break; // !! not a supported OS!
  199074. }
  199075. }
  199076. else if (info.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS)
  199077. {
  199078. jassert (info.dwMinorVersion != 0); // !! still running on Windows 95??
  199079. return Win98;
  199080. }
  199081. return UnknownOS;
  199082. }
  199083. const String SystemStats::getOperatingSystemName() throw()
  199084. {
  199085. const char* name = "Unknown OS";
  199086. switch (getOperatingSystemType())
  199087. {
  199088. case Windows7: name = "Windows 7"; break;
  199089. case WinVista: name = "Windows Vista"; break;
  199090. case WinXP: name = "Windows XP"; break;
  199091. case Win2000: name = "Windows 2000"; break;
  199092. case Win98: name = "Windows 98"; break;
  199093. default: jassertfalse; break; // !! new type of OS?
  199094. }
  199095. return name;
  199096. }
  199097. bool SystemStats::isOperatingSystem64Bit() throw()
  199098. {
  199099. #ifdef _WIN64
  199100. return true;
  199101. #else
  199102. typedef BOOL (WINAPI* LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
  199103. LPFN_ISWOW64PROCESS fnIsWow64Process = (LPFN_ISWOW64PROCESS) GetProcAddress (GetModuleHandle (L"kernel32"), "IsWow64Process");
  199104. BOOL isWow64 = FALSE;
  199105. return (fnIsWow64Process != 0)
  199106. && fnIsWow64Process (GetCurrentProcess(), &isWow64)
  199107. && (isWow64 != FALSE);
  199108. #endif
  199109. }
  199110. int SystemStats::getMemorySizeInMegabytes() throw()
  199111. {
  199112. MEMORYSTATUSEX mem;
  199113. mem.dwLength = sizeof (mem);
  199114. GlobalMemoryStatusEx (&mem);
  199115. return (int) (mem.ullTotalPhys / (1024 * 1024)) + 1;
  199116. }
  199117. int SystemStats::getNumCpus() throw()
  199118. {
  199119. SYSTEM_INFO systemInfo;
  199120. GetSystemInfo (&systemInfo);
  199121. return systemInfo.dwNumberOfProcessors;
  199122. }
  199123. uint32 juce_millisecondsSinceStartup() throw()
  199124. {
  199125. return (uint32) GetTickCount();
  199126. }
  199127. int64 Time::getHighResolutionTicks() throw()
  199128. {
  199129. LARGE_INTEGER ticks;
  199130. QueryPerformanceCounter (&ticks);
  199131. const int64 mainCounterAsHiResTicks = (GetTickCount() * hiResTicksPerSecond) / 1000;
  199132. const int64 newOffset = mainCounterAsHiResTicks - ticks.QuadPart;
  199133. // fix for a very obscure PCI hardware bug that can make the counter
  199134. // sometimes jump forwards by a few seconds..
  199135. static int64 hiResTicksOffset = 0;
  199136. const int64 offsetDrift = abs64 (newOffset - hiResTicksOffset);
  199137. if (offsetDrift > (hiResTicksPerSecond >> 1))
  199138. hiResTicksOffset = newOffset;
  199139. return ticks.QuadPart + hiResTicksOffset;
  199140. }
  199141. double Time::getMillisecondCounterHiRes() throw()
  199142. {
  199143. return getHighResolutionTicks() * hiResTicksScaleFactor;
  199144. }
  199145. int64 Time::getHighResolutionTicksPerSecond() throw()
  199146. {
  199147. return hiResTicksPerSecond;
  199148. }
  199149. int64 SystemStats::getClockCycleCounter() throw()
  199150. {
  199151. #if JUCE_USE_INTRINSICS
  199152. // MS intrinsics version...
  199153. return __rdtsc();
  199154. #elif JUCE_GCC
  199155. // GNU inline asm version...
  199156. unsigned int hi = 0, lo = 0;
  199157. __asm__ __volatile__ (
  199158. "xor %%eax, %%eax \n\
  199159. xor %%edx, %%edx \n\
  199160. rdtsc \n\
  199161. movl %%eax, %[lo] \n\
  199162. movl %%edx, %[hi]"
  199163. :
  199164. : [hi] "m" (hi),
  199165. [lo] "m" (lo)
  199166. : "cc", "eax", "ebx", "ecx", "edx", "memory");
  199167. return (int64) ((((uint64) hi) << 32) | lo);
  199168. #else
  199169. // MSVC inline asm version...
  199170. unsigned int hi = 0, lo = 0;
  199171. __asm
  199172. {
  199173. xor eax, eax
  199174. xor edx, edx
  199175. rdtsc
  199176. mov lo, eax
  199177. mov hi, edx
  199178. }
  199179. return (int64) ((((uint64) hi) << 32) | lo);
  199180. #endif
  199181. }
  199182. int SystemStats::getCpuSpeedInMegaherz() throw()
  199183. {
  199184. const int64 cycles = SystemStats::getClockCycleCounter();
  199185. const uint32 millis = Time::getMillisecondCounter();
  199186. int lastResult = 0;
  199187. for (;;)
  199188. {
  199189. int n = 1000000;
  199190. while (--n > 0) {}
  199191. const uint32 millisElapsed = Time::getMillisecondCounter() - millis;
  199192. const int64 cyclesNow = SystemStats::getClockCycleCounter();
  199193. if (millisElapsed > 80)
  199194. {
  199195. const int newResult = (int) (((cyclesNow - cycles) / millisElapsed) / 1000);
  199196. if (millisElapsed > 500 || (lastResult == newResult && newResult > 100))
  199197. return newResult;
  199198. lastResult = newResult;
  199199. }
  199200. }
  199201. }
  199202. bool Time::setSystemTimeToThisTime() const throw()
  199203. {
  199204. SYSTEMTIME st;
  199205. st.wDayOfWeek = 0;
  199206. st.wYear = (WORD) getYear();
  199207. st.wMonth = (WORD) (getMonth() + 1);
  199208. st.wDay = (WORD) getDayOfMonth();
  199209. st.wHour = (WORD) getHours();
  199210. st.wMinute = (WORD) getMinutes();
  199211. st.wSecond = (WORD) getSeconds();
  199212. st.wMilliseconds = (WORD) (millisSinceEpoch % 1000);
  199213. // do this twice because of daylight saving conversion problems - the
  199214. // first one sets it up, the second one kicks it in.
  199215. return SetLocalTime (&st) != 0
  199216. && SetLocalTime (&st) != 0;
  199217. }
  199218. int SystemStats::getPageSize() throw()
  199219. {
  199220. SYSTEM_INFO systemInfo;
  199221. GetSystemInfo (&systemInfo);
  199222. return systemInfo.dwPageSize;
  199223. }
  199224. #endif
  199225. /********* End of inlined file: juce_win32_SystemStats.cpp *********/
  199226. /********* Start of inlined file: juce_win32_Threads.cpp *********/
  199227. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  199228. // compiled on its own).
  199229. #if JUCE_INCLUDED_FILE
  199230. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  199231. extern HWND juce_messageWindowHandle;
  199232. #endif
  199233. CriticalSection::CriticalSection() throw()
  199234. {
  199235. // (just to check the MS haven't changed this structure and broken things...)
  199236. #if _MSC_VER >= 1400
  199237. static_jassert (sizeof (CRITICAL_SECTION) <= sizeof (internal));
  199238. #else
  199239. static_jassert (sizeof (CRITICAL_SECTION) <= 24);
  199240. #endif
  199241. InitializeCriticalSection ((CRITICAL_SECTION*) internal);
  199242. }
  199243. CriticalSection::~CriticalSection() throw()
  199244. {
  199245. DeleteCriticalSection ((CRITICAL_SECTION*) internal);
  199246. }
  199247. void CriticalSection::enter() const throw()
  199248. {
  199249. EnterCriticalSection ((CRITICAL_SECTION*) internal);
  199250. }
  199251. bool CriticalSection::tryEnter() const throw()
  199252. {
  199253. return TryEnterCriticalSection ((CRITICAL_SECTION*) internal) != FALSE;
  199254. }
  199255. void CriticalSection::exit() const throw()
  199256. {
  199257. LeaveCriticalSection ((CRITICAL_SECTION*) internal);
  199258. }
  199259. WaitableEvent::WaitableEvent() throw()
  199260. : internal (CreateEvent (0, FALSE, FALSE, 0))
  199261. {
  199262. }
  199263. WaitableEvent::~WaitableEvent() throw()
  199264. {
  199265. CloseHandle (internal);
  199266. }
  199267. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  199268. {
  199269. return WaitForSingleObject (internal, timeOutMillisecs) == WAIT_OBJECT_0;
  199270. }
  199271. void WaitableEvent::signal() const throw()
  199272. {
  199273. SetEvent (internal);
  199274. }
  199275. void WaitableEvent::reset() const throw()
  199276. {
  199277. ResetEvent (internal);
  199278. }
  199279. void JUCE_API juce_threadEntryPoint (void*);
  199280. static unsigned int __stdcall threadEntryProc (void* userData) throw()
  199281. {
  199282. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  199283. AttachThreadInput (GetWindowThreadProcessId (juce_messageWindowHandle, 0),
  199284. GetCurrentThreadId(), TRUE);
  199285. #endif
  199286. juce_threadEntryPoint (userData);
  199287. _endthreadex (0);
  199288. return 0;
  199289. }
  199290. void juce_CloseThreadHandle (void* handle) throw()
  199291. {
  199292. CloseHandle ((HANDLE) handle);
  199293. }
  199294. void* juce_createThread (void* userData) throw()
  199295. {
  199296. unsigned int threadId;
  199297. return (void*) _beginthreadex (0, 0,
  199298. &threadEntryProc,
  199299. userData,
  199300. 0, &threadId);
  199301. }
  199302. void juce_killThread (void* handle) throw()
  199303. {
  199304. if (handle != 0)
  199305. {
  199306. #ifdef JUCE_DEBUG
  199307. OutputDebugString (_T("** Warning - Forced thread termination **\n"));
  199308. #endif
  199309. TerminateThread (handle, 0);
  199310. }
  199311. }
  199312. void juce_setCurrentThreadName (const String& name) throw()
  199313. {
  199314. #if defined (JUCE_DEBUG) && JUCE_MSVC
  199315. struct
  199316. {
  199317. DWORD dwType;
  199318. LPCSTR szName;
  199319. DWORD dwThreadID;
  199320. DWORD dwFlags;
  199321. } info;
  199322. info.dwType = 0x1000;
  199323. info.szName = name;
  199324. info.dwThreadID = GetCurrentThreadId();
  199325. info.dwFlags = 0;
  199326. #define MS_VC_EXCEPTION 0x406d1388
  199327. __try
  199328. {
  199329. RaiseException (MS_VC_EXCEPTION, 0, sizeof (info) / sizeof (ULONG_PTR), (ULONG_PTR*) &info);
  199330. }
  199331. __except (EXCEPTION_CONTINUE_EXECUTION)
  199332. {}
  199333. #else
  199334. (void) name;
  199335. #endif
  199336. }
  199337. Thread::ThreadID Thread::getCurrentThreadId() throw()
  199338. {
  199339. return (ThreadID) (pointer_sized_int) GetCurrentThreadId();
  199340. }
  199341. // priority 1 to 10 where 5=normal, 1=low
  199342. bool juce_setThreadPriority (void* threadHandle, int priority) throw()
  199343. {
  199344. int pri = THREAD_PRIORITY_TIME_CRITICAL;
  199345. if (priority < 1)
  199346. pri = THREAD_PRIORITY_IDLE;
  199347. else if (priority < 2)
  199348. pri = THREAD_PRIORITY_LOWEST;
  199349. else if (priority < 5)
  199350. pri = THREAD_PRIORITY_BELOW_NORMAL;
  199351. else if (priority < 7)
  199352. pri = THREAD_PRIORITY_NORMAL;
  199353. else if (priority < 9)
  199354. pri = THREAD_PRIORITY_ABOVE_NORMAL;
  199355. else if (priority < 10)
  199356. pri = THREAD_PRIORITY_HIGHEST;
  199357. if (threadHandle == 0)
  199358. threadHandle = GetCurrentThread();
  199359. return SetThreadPriority (threadHandle, pri) != FALSE;
  199360. }
  199361. void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask) throw()
  199362. {
  199363. SetThreadAffinityMask (GetCurrentThread(), affinityMask);
  199364. }
  199365. static HANDLE sleepEvent = 0;
  199366. void juce_initialiseThreadEvents() throw()
  199367. {
  199368. if (sleepEvent == 0)
  199369. #ifdef JUCE_DEBUG
  199370. sleepEvent = CreateEvent (0, 0, 0, _T("Juce Sleep Event"));
  199371. #else
  199372. sleepEvent = CreateEvent (0, 0, 0, 0);
  199373. #endif
  199374. }
  199375. void Thread::yield() throw()
  199376. {
  199377. Sleep (0);
  199378. }
  199379. void JUCE_CALLTYPE Thread::sleep (const int millisecs) throw()
  199380. {
  199381. if (millisecs >= 10)
  199382. {
  199383. Sleep (millisecs);
  199384. }
  199385. else
  199386. {
  199387. jassert (sleepEvent != 0);
  199388. // unlike Sleep() this is guaranteed to return to the current thread after
  199389. // the time expires, so we'll use this for short waits, which are more likely
  199390. // to need to be accurate
  199391. WaitForSingleObject (sleepEvent, millisecs);
  199392. }
  199393. }
  199394. static int lastProcessPriority = -1;
  199395. // called by WindowDriver because Windows does wierd things to process priority
  199396. // when you swap apps, and this forces an update when the app is brought to the front.
  199397. void juce_repeatLastProcessPriority() throw()
  199398. {
  199399. if (lastProcessPriority >= 0) // (avoid changing this if it's not been explicitly set by the app..)
  199400. {
  199401. DWORD p;
  199402. switch (lastProcessPriority)
  199403. {
  199404. case Process::LowPriority:
  199405. p = IDLE_PRIORITY_CLASS;
  199406. break;
  199407. case Process::NormalPriority:
  199408. p = NORMAL_PRIORITY_CLASS;
  199409. break;
  199410. case Process::HighPriority:
  199411. p = HIGH_PRIORITY_CLASS;
  199412. break;
  199413. case Process::RealtimePriority:
  199414. p = REALTIME_PRIORITY_CLASS;
  199415. break;
  199416. default:
  199417. jassertfalse // bad priority value
  199418. return;
  199419. }
  199420. SetPriorityClass (GetCurrentProcess(), p);
  199421. }
  199422. }
  199423. void Process::setPriority (ProcessPriority prior)
  199424. {
  199425. if (lastProcessPriority != (int) prior)
  199426. {
  199427. lastProcessPriority = (int) prior;
  199428. juce_repeatLastProcessPriority();
  199429. }
  199430. }
  199431. bool JUCE_API JUCE_CALLTYPE juce_isRunningUnderDebugger() throw()
  199432. {
  199433. return IsDebuggerPresent() != FALSE;
  199434. }
  199435. bool JUCE_CALLTYPE Process::isRunningUnderDebugger() throw()
  199436. {
  199437. return juce_isRunningUnderDebugger();
  199438. }
  199439. void Process::raisePrivilege()
  199440. {
  199441. jassertfalse // xxx not implemented
  199442. }
  199443. void Process::lowerPrivilege()
  199444. {
  199445. jassertfalse // xxx not implemented
  199446. }
  199447. void Process::terminate()
  199448. {
  199449. #if defined (JUCE_DEBUG) && JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  199450. _CrtDumpMemoryLeaks();
  199451. #endif
  199452. // bullet in the head in case there's a problem shutting down..
  199453. ExitProcess (0);
  199454. }
  199455. void* PlatformUtilities::loadDynamicLibrary (const String& name)
  199456. {
  199457. void* result = 0;
  199458. JUCE_TRY
  199459. {
  199460. result = (void*) LoadLibrary (name);
  199461. }
  199462. JUCE_CATCH_ALL
  199463. return result;
  199464. }
  199465. void PlatformUtilities::freeDynamicLibrary (void* h)
  199466. {
  199467. JUCE_TRY
  199468. {
  199469. if (h != 0)
  199470. FreeLibrary ((HMODULE) h);
  199471. }
  199472. JUCE_CATCH_ALL
  199473. }
  199474. void* PlatformUtilities::getProcedureEntryPoint (void* h, const String& name)
  199475. {
  199476. return (h != 0) ? (void*) GetProcAddress ((HMODULE) h, name)
  199477. : 0;
  199478. }
  199479. InterProcessLock::InterProcessLock (const String& name_) throw()
  199480. : internal (0),
  199481. name (name_),
  199482. reentrancyLevel (0)
  199483. {
  199484. }
  199485. InterProcessLock::~InterProcessLock() throw()
  199486. {
  199487. exit();
  199488. }
  199489. bool InterProcessLock::enter (const int timeOutMillisecs) throw()
  199490. {
  199491. if (reentrancyLevel++ == 0)
  199492. {
  199493. internal = CreateMutex (0, TRUE, name);
  199494. if (internal != 0 && GetLastError() == ERROR_ALREADY_EXISTS)
  199495. {
  199496. if (timeOutMillisecs == 0
  199497. || WaitForSingleObject (internal, (timeOutMillisecs < 0) ? INFINITE : timeOutMillisecs)
  199498. == WAIT_TIMEOUT)
  199499. {
  199500. ReleaseMutex (internal);
  199501. CloseHandle (internal);
  199502. internal = 0;
  199503. }
  199504. }
  199505. }
  199506. return (internal != 0);
  199507. }
  199508. void InterProcessLock::exit() throw()
  199509. {
  199510. if (--reentrancyLevel == 0 && internal != 0)
  199511. {
  199512. ReleaseMutex (internal);
  199513. CloseHandle (internal);
  199514. internal = 0;
  199515. }
  199516. }
  199517. #endif
  199518. /********* End of inlined file: juce_win32_Threads.cpp *********/
  199519. /********* Start of inlined file: juce_win32_Files.cpp *********/
  199520. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  199521. // compiled on its own).
  199522. #if JUCE_INCLUDED_FILE
  199523. #ifndef CSIDL_MYMUSIC
  199524. #define CSIDL_MYMUSIC 0x000d
  199525. #endif
  199526. #ifndef CSIDL_MYVIDEO
  199527. #define CSIDL_MYVIDEO 0x000e
  199528. #endif
  199529. const tchar File::separator = T('\\');
  199530. const tchar* File::separatorString = T("\\");
  199531. bool juce_fileExists (const String& fileName,
  199532. const bool dontCountDirectories) throw()
  199533. {
  199534. if (fileName.isEmpty())
  199535. return false;
  199536. const DWORD attr = GetFileAttributes (fileName);
  199537. return dontCountDirectories ? ((attr & FILE_ATTRIBUTE_DIRECTORY) == 0)
  199538. : (attr != 0xffffffff);
  199539. }
  199540. bool juce_isDirectory (const String& fileName) throw()
  199541. {
  199542. const DWORD attr = GetFileAttributes (fileName);
  199543. return (attr != 0xffffffff)
  199544. && ((attr & FILE_ATTRIBUTE_DIRECTORY) != 0);
  199545. }
  199546. bool juce_canWriteToFile (const String& fileName) throw()
  199547. {
  199548. const DWORD attr = GetFileAttributes (fileName);
  199549. return ((attr & FILE_ATTRIBUTE_READONLY) == 0);
  199550. }
  199551. bool juce_setFileReadOnly (const String& fileName,
  199552. bool isReadOnly) throw()
  199553. {
  199554. DWORD attr = GetFileAttributes (fileName);
  199555. if (attr == 0xffffffff)
  199556. return false;
  199557. if (isReadOnly != juce_canWriteToFile (fileName))
  199558. return true;
  199559. if (isReadOnly)
  199560. attr |= FILE_ATTRIBUTE_READONLY;
  199561. else
  199562. attr &= ~FILE_ATTRIBUTE_READONLY;
  199563. return SetFileAttributes (fileName, attr) != FALSE;
  199564. }
  199565. bool File::isHidden() const throw()
  199566. {
  199567. return (GetFileAttributes (getFullPathName()) & FILE_ATTRIBUTE_HIDDEN) != 0;
  199568. }
  199569. bool juce_deleteFile (const String& fileName) throw()
  199570. {
  199571. if (juce_isDirectory (fileName))
  199572. return RemoveDirectory (fileName) != 0;
  199573. return DeleteFile (fileName) != 0;
  199574. }
  199575. bool File::moveToTrash() const throw()
  199576. {
  199577. if (! exists())
  199578. return true;
  199579. SHFILEOPSTRUCT fos;
  199580. zerostruct (fos);
  199581. // The string we pass in must be double null terminated..
  199582. String doubleNullTermPath (getFullPathName() + " ");
  199583. TCHAR* p = (TCHAR*) (const TCHAR*) doubleNullTermPath;
  199584. p [getFullPathName().length()] = 0;
  199585. fos.wFunc = FO_DELETE;
  199586. fos.hwnd = (HWND) 0;
  199587. fos.pFrom = p;
  199588. fos.pTo = NULL;
  199589. fos.fFlags = FOF_ALLOWUNDO | FOF_NOERRORUI | FOF_SILENT | FOF_NOCONFIRMATION
  199590. | FOF_NOCONFIRMMKDIR | FOF_RENAMEONCOLLISION;
  199591. return SHFileOperation (&fos) == 0;
  199592. }
  199593. bool juce_moveFile (const String& source, const String& dest) throw()
  199594. {
  199595. return MoveFile (source, dest) != 0;
  199596. }
  199597. bool juce_copyFile (const String& source, const String& dest) throw()
  199598. {
  199599. return CopyFile (source, dest, false) != 0;
  199600. }
  199601. void juce_createDirectory (const String& fileName) throw()
  199602. {
  199603. if (! juce_fileExists (fileName, true))
  199604. {
  199605. CreateDirectory (fileName, 0);
  199606. }
  199607. }
  199608. // return 0 if not possible
  199609. void* juce_fileOpen (const String& fileName, bool forWriting) throw()
  199610. {
  199611. HANDLE h;
  199612. if (forWriting)
  199613. {
  199614. h = CreateFile (fileName, GENERIC_WRITE, FILE_SHARE_READ, 0,
  199615. OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
  199616. if (h != INVALID_HANDLE_VALUE)
  199617. SetFilePointer (h, 0, 0, FILE_END);
  199618. else
  199619. h = 0;
  199620. }
  199621. else
  199622. {
  199623. h = CreateFile (fileName, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, 0,
  199624. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN, 0);
  199625. if (h == INVALID_HANDLE_VALUE)
  199626. h = 0;
  199627. }
  199628. return (void*) h;
  199629. }
  199630. void juce_fileClose (void* handle) throw()
  199631. {
  199632. CloseHandle (handle);
  199633. }
  199634. int juce_fileRead (void* handle, void* buffer, int size) throw()
  199635. {
  199636. DWORD num = 0;
  199637. ReadFile ((HANDLE) handle, buffer, size, &num, 0);
  199638. return num;
  199639. }
  199640. int juce_fileWrite (void* handle, const void* buffer, int size) throw()
  199641. {
  199642. DWORD num;
  199643. WriteFile ((HANDLE) handle,
  199644. buffer, size,
  199645. &num, 0);
  199646. return num;
  199647. }
  199648. int64 juce_fileSetPosition (void* handle, int64 pos) throw()
  199649. {
  199650. LARGE_INTEGER li;
  199651. li.QuadPart = pos;
  199652. li.LowPart = SetFilePointer ((HANDLE) handle,
  199653. li.LowPart,
  199654. &li.HighPart,
  199655. FILE_BEGIN); // (returns -1 if it fails)
  199656. return li.QuadPart;
  199657. }
  199658. int64 juce_fileGetPosition (void* handle) throw()
  199659. {
  199660. LARGE_INTEGER li;
  199661. li.QuadPart = 0;
  199662. li.LowPart = SetFilePointer ((HANDLE) handle,
  199663. 0, &li.HighPart,
  199664. FILE_CURRENT); // (returns -1 if it fails)
  199665. return jmax ((int64) 0, li.QuadPart);
  199666. }
  199667. void juce_fileFlush (void* handle) throw()
  199668. {
  199669. FlushFileBuffers ((HANDLE) handle);
  199670. }
  199671. int64 juce_getFileSize (const String& fileName) throw()
  199672. {
  199673. WIN32_FILE_ATTRIBUTE_DATA attributes;
  199674. if (GetFileAttributesEx (fileName, GetFileExInfoStandard, &attributes))
  199675. {
  199676. return (((int64) attributes.nFileSizeHigh) << 32)
  199677. | attributes.nFileSizeLow;
  199678. }
  199679. return 0;
  199680. }
  199681. static int64 fileTimeToTime (const FILETIME* const ft) throw()
  199682. {
  199683. // tell me if this fails!
  199684. static_jassert (sizeof (ULARGE_INTEGER) == sizeof (FILETIME));
  199685. #if JUCE_GCC
  199686. return (((const ULARGE_INTEGER*) ft)->QuadPart - 116444736000000000LL) / 10000;
  199687. #else
  199688. return (((const ULARGE_INTEGER*) ft)->QuadPart - 116444736000000000) / 10000;
  199689. #endif
  199690. }
  199691. static void timeToFileTime (const int64 time, FILETIME* const ft) throw()
  199692. {
  199693. #if JUCE_GCC
  199694. ((ULARGE_INTEGER*) ft)->QuadPart = time * 10000 + 116444736000000000LL;
  199695. #else
  199696. ((ULARGE_INTEGER*) ft)->QuadPart = time * 10000 + 116444736000000000;
  199697. #endif
  199698. }
  199699. void juce_getFileTimes (const String& fileName,
  199700. int64& modificationTime,
  199701. int64& accessTime,
  199702. int64& creationTime) throw()
  199703. {
  199704. WIN32_FILE_ATTRIBUTE_DATA attributes;
  199705. if (GetFileAttributesEx (fileName, GetFileExInfoStandard, &attributes))
  199706. {
  199707. modificationTime = fileTimeToTime (&attributes.ftLastWriteTime);
  199708. creationTime = fileTimeToTime (&attributes.ftCreationTime);
  199709. accessTime = fileTimeToTime (&attributes.ftLastAccessTime);
  199710. }
  199711. else
  199712. {
  199713. creationTime = accessTime = modificationTime = 0;
  199714. }
  199715. }
  199716. bool juce_setFileTimes (const String& fileName,
  199717. int64 modificationTime,
  199718. int64 accessTime,
  199719. int64 creationTime) throw()
  199720. {
  199721. FILETIME m, a, c;
  199722. if (modificationTime > 0)
  199723. timeToFileTime (modificationTime, &m);
  199724. if (accessTime > 0)
  199725. timeToFileTime (accessTime, &a);
  199726. if (creationTime > 0)
  199727. timeToFileTime (creationTime, &c);
  199728. void* const h = juce_fileOpen (fileName, true);
  199729. bool ok = false;
  199730. if (h != 0)
  199731. {
  199732. ok = SetFileTime ((HANDLE) h,
  199733. (creationTime > 0) ? &c : 0,
  199734. (accessTime > 0) ? &a : 0,
  199735. (modificationTime > 0) ? &m : 0) != 0;
  199736. juce_fileClose (h);
  199737. }
  199738. return ok;
  199739. }
  199740. // return '\0' separated list of strings
  199741. const StringArray juce_getFileSystemRoots() throw()
  199742. {
  199743. TCHAR buffer [2048];
  199744. buffer[0] = 0;
  199745. buffer[1] = 0;
  199746. GetLogicalDriveStrings (2048, buffer);
  199747. TCHAR* n = buffer;
  199748. StringArray roots;
  199749. while (*n != 0)
  199750. {
  199751. roots.add (String (n));
  199752. while (*n++ != 0)
  199753. {
  199754. }
  199755. }
  199756. roots.sort (true);
  199757. return roots;
  199758. }
  199759. const String juce_getVolumeLabel (const String& filenameOnVolume,
  199760. int& volumeSerialNumber) throw()
  199761. {
  199762. TCHAR n [4];
  199763. n[0] = *(const TCHAR*) filenameOnVolume;
  199764. n[1] = L':';
  199765. n[2] = L'\\';
  199766. n[3] = 0;
  199767. TCHAR dest [64];
  199768. DWORD serialNum;
  199769. if (! GetVolumeInformation (n, dest, 64, (DWORD*) &serialNum, 0, 0, 0, 0))
  199770. {
  199771. dest[0] = 0;
  199772. serialNum = 0;
  199773. }
  199774. volumeSerialNumber = serialNum;
  199775. return String (dest);
  199776. }
  199777. static int64 getDiskSpaceInfo (String fn, const bool total) throw()
  199778. {
  199779. if (fn[1] == T(':'))
  199780. fn = fn.substring (0, 2) + T("\\");
  199781. ULARGE_INTEGER spc, tot, totFree;
  199782. if (GetDiskFreeSpaceEx (fn, &spc, &tot, &totFree))
  199783. return (int64) (total ? tot.QuadPart
  199784. : spc.QuadPart);
  199785. return 0;
  199786. }
  199787. int64 File::getBytesFreeOnVolume() const throw()
  199788. {
  199789. return getDiskSpaceInfo (getFullPathName(), false);
  199790. }
  199791. int64 File::getVolumeTotalSize() const throw()
  199792. {
  199793. return getDiskSpaceInfo (getFullPathName(), true);
  199794. }
  199795. static unsigned int getWindowsDriveType (const String& fileName) throw()
  199796. {
  199797. TCHAR n[4];
  199798. n[0] = *(const TCHAR*) fileName;
  199799. n[1] = L':';
  199800. n[2] = L'\\';
  199801. n[3] = 0;
  199802. return GetDriveType (n);
  199803. }
  199804. bool File::isOnCDRomDrive() const throw()
  199805. {
  199806. return getWindowsDriveType (getFullPathName()) == DRIVE_CDROM;
  199807. }
  199808. bool File::isOnHardDisk() const throw()
  199809. {
  199810. if (fullPath.isEmpty())
  199811. return false;
  199812. const unsigned int n = getWindowsDriveType (getFullPathName());
  199813. if (fullPath.toLowerCase()[0] <= 'b'
  199814. && fullPath[1] == T(':'))
  199815. {
  199816. return n != DRIVE_REMOVABLE;
  199817. }
  199818. else
  199819. {
  199820. return n != DRIVE_CDROM && n != DRIVE_REMOTE;
  199821. }
  199822. }
  199823. bool File::isOnRemovableDrive() const throw()
  199824. {
  199825. if (fullPath.isEmpty())
  199826. return false;
  199827. const unsigned int n = getWindowsDriveType (getFullPathName());
  199828. return n == DRIVE_CDROM
  199829. || n == DRIVE_REMOTE
  199830. || n == DRIVE_REMOVABLE
  199831. || n == DRIVE_RAMDISK;
  199832. }
  199833. #define MAX_PATH_CHARS (MAX_PATH + 256)
  199834. static const File juce_getSpecialFolderPath (int type) throw()
  199835. {
  199836. WCHAR path [MAX_PATH_CHARS];
  199837. if (SHGetSpecialFolderPath (0, path, type, 0))
  199838. return File (String (path));
  199839. return File::nonexistent;
  199840. }
  199841. const File JUCE_CALLTYPE File::getSpecialLocation (const SpecialLocationType type)
  199842. {
  199843. int csidlType = 0;
  199844. switch (type)
  199845. {
  199846. case userHomeDirectory:
  199847. csidlType = CSIDL_PROFILE;
  199848. break;
  199849. case userDocumentsDirectory:
  199850. csidlType = CSIDL_PERSONAL;
  199851. break;
  199852. case userDesktopDirectory:
  199853. csidlType = CSIDL_DESKTOP;
  199854. break;
  199855. case userApplicationDataDirectory:
  199856. csidlType = CSIDL_APPDATA;
  199857. break;
  199858. case commonApplicationDataDirectory:
  199859. csidlType = CSIDL_COMMON_APPDATA;
  199860. break;
  199861. case globalApplicationsDirectory:
  199862. csidlType = CSIDL_PROGRAM_FILES;
  199863. break;
  199864. case userMusicDirectory:
  199865. csidlType = CSIDL_MYMUSIC;
  199866. break;
  199867. case userMoviesDirectory:
  199868. csidlType = CSIDL_MYVIDEO;
  199869. break;
  199870. case tempDirectory:
  199871. {
  199872. WCHAR dest [2048];
  199873. dest[0] = 0;
  199874. GetTempPath (2048, dest);
  199875. return File (String (dest));
  199876. }
  199877. case currentExecutableFile:
  199878. case currentApplicationFile:
  199879. {
  199880. HINSTANCE moduleHandle = (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle();
  199881. WCHAR dest [MAX_PATH_CHARS];
  199882. dest[0] = 0;
  199883. GetModuleFileName (moduleHandle, dest, MAX_PATH_CHARS);
  199884. return File (String (dest));
  199885. }
  199886. break;
  199887. default:
  199888. jassertfalse // unknown type?
  199889. return File::nonexistent;
  199890. }
  199891. return juce_getSpecialFolderPath (csidlType);
  199892. }
  199893. const File File::getCurrentWorkingDirectory() throw()
  199894. {
  199895. WCHAR dest [MAX_PATH_CHARS];
  199896. dest[0] = 0;
  199897. GetCurrentDirectory (MAX_PATH_CHARS, dest);
  199898. return File (String (dest));
  199899. }
  199900. bool File::setAsCurrentWorkingDirectory() const throw()
  199901. {
  199902. return SetCurrentDirectory (getFullPathName()) != FALSE;
  199903. }
  199904. const String File::getVersion() const throw()
  199905. {
  199906. String result;
  199907. DWORD handle = 0;
  199908. DWORD bufferSize = GetFileVersionInfoSize (getFullPathName(), &handle);
  199909. void* buffer = juce_calloc (bufferSize);
  199910. if (GetFileVersionInfo (getFullPathName(), 0, bufferSize, buffer))
  199911. {
  199912. VS_FIXEDFILEINFO* vffi;
  199913. UINT len = 0;
  199914. if (VerQueryValue (buffer, _T("\\"), (LPVOID*) &vffi, &len))
  199915. {
  199916. result.printf (T("%d.%d.%d.%d"),
  199917. HIWORD (vffi->dwFileVersionMS),
  199918. LOWORD (vffi->dwFileVersionMS),
  199919. HIWORD (vffi->dwFileVersionLS),
  199920. LOWORD (vffi->dwFileVersionLS));
  199921. }
  199922. }
  199923. juce_free (buffer);
  199924. return result;
  199925. }
  199926. const File File::getLinkedTarget() const throw()
  199927. {
  199928. File result (*this);
  199929. String p (getFullPathName());
  199930. if (! exists())
  199931. p += T(".lnk");
  199932. else if (getFileExtension() != T(".lnk"))
  199933. return result;
  199934. ComSmartPtr <IShellLink> shellLink;
  199935. if (SUCCEEDED (shellLink.CoCreateInstance (CLSID_ShellLink, CLSCTX_INPROC_SERVER)))
  199936. {
  199937. ComSmartPtr <IPersistFile> persistFile;
  199938. if (SUCCEEDED (shellLink->QueryInterface (IID_IPersistFile, (LPVOID*) &persistFile)))
  199939. {
  199940. if (SUCCEEDED (persistFile->Load ((const WCHAR*) p, STGM_READ))
  199941. && SUCCEEDED (shellLink->Resolve (0, SLR_ANY_MATCH | SLR_NO_UI)))
  199942. {
  199943. WIN32_FIND_DATA winFindData;
  199944. WCHAR resolvedPath [MAX_PATH];
  199945. if (SUCCEEDED (shellLink->GetPath (resolvedPath, MAX_PATH, &winFindData, SLGP_UNCPRIORITY)))
  199946. result = File (resolvedPath);
  199947. }
  199948. }
  199949. }
  199950. return result;
  199951. }
  199952. template <class FindDataType>
  199953. static void getFindFileInfo (FindDataType& findData,
  199954. String& filename, bool* const isDir, bool* const isHidden,
  199955. int64* const fileSize, Time* const modTime, Time* const creationTime,
  199956. bool* const isReadOnly) throw()
  199957. {
  199958. filename = findData.cFileName;
  199959. if (isDir != 0)
  199960. *isDir = ((findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0);
  199961. if (isHidden != 0)
  199962. *isHidden = ((findData.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN) != 0);
  199963. if (fileSize != 0)
  199964. *fileSize = findData.nFileSizeLow + (((int64) findData.nFileSizeHigh) << 32);
  199965. if (modTime != 0)
  199966. *modTime = fileTimeToTime (&findData.ftLastWriteTime);
  199967. if (creationTime != 0)
  199968. *creationTime = fileTimeToTime (&findData.ftCreationTime);
  199969. if (isReadOnly != 0)
  199970. *isReadOnly = ((findData.dwFileAttributes & FILE_ATTRIBUTE_READONLY) != 0);
  199971. }
  199972. void* juce_findFileStart (const String& directory, const String& wildCard, String& firstResult,
  199973. bool* isDir, bool* isHidden, int64* fileSize,
  199974. Time* modTime, Time* creationTime, bool* isReadOnly) throw()
  199975. {
  199976. String wc (directory);
  199977. if (! wc.endsWithChar (File::separator))
  199978. wc += File::separator;
  199979. wc += wildCard;
  199980. WIN32_FIND_DATA findData;
  199981. HANDLE h = FindFirstFile (wc, &findData);
  199982. if (h != INVALID_HANDLE_VALUE)
  199983. {
  199984. getFindFileInfo (findData, firstResult, isDir, isHidden, fileSize,
  199985. modTime, creationTime, isReadOnly);
  199986. return h;
  199987. }
  199988. firstResult = String::empty;
  199989. return 0;
  199990. }
  199991. bool juce_findFileNext (void* handle, String& resultFile,
  199992. bool* isDir, bool* isHidden, int64* fileSize,
  199993. Time* modTime, Time* creationTime, bool* isReadOnly) throw()
  199994. {
  199995. WIN32_FIND_DATA findData;
  199996. if (handle != 0 && FindNextFile ((HANDLE) handle, &findData) != 0)
  199997. {
  199998. getFindFileInfo (findData, resultFile, isDir, isHidden, fileSize,
  199999. modTime, creationTime, isReadOnly);
  200000. return true;
  200001. }
  200002. resultFile = String::empty;
  200003. return false;
  200004. }
  200005. void juce_findFileClose (void* handle) throw()
  200006. {
  200007. FindClose (handle);
  200008. }
  200009. bool juce_launchFile (const String& fileName,
  200010. const String& parameters) throw()
  200011. {
  200012. HINSTANCE hInstance = 0;
  200013. JUCE_TRY
  200014. {
  200015. hInstance = ShellExecute (0, 0, fileName, parameters, 0, SW_SHOWDEFAULT);
  200016. }
  200017. JUCE_CATCH_ALL
  200018. return hInstance > (HINSTANCE) 32;
  200019. }
  200020. struct NamedPipeInternal
  200021. {
  200022. HANDLE pipeH;
  200023. HANDLE cancelEvent;
  200024. bool connected, createdPipe;
  200025. NamedPipeInternal()
  200026. : pipeH (0),
  200027. cancelEvent (0),
  200028. connected (false),
  200029. createdPipe (false)
  200030. {
  200031. cancelEvent = CreateEvent (0, FALSE, FALSE, 0);
  200032. }
  200033. ~NamedPipeInternal()
  200034. {
  200035. disconnect();
  200036. if (pipeH != 0)
  200037. CloseHandle (pipeH);
  200038. CloseHandle (cancelEvent);
  200039. }
  200040. bool connect (const int timeOutMs)
  200041. {
  200042. if (! createdPipe)
  200043. return true;
  200044. if (! connected)
  200045. {
  200046. OVERLAPPED over;
  200047. zerostruct (over);
  200048. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  200049. if (ConnectNamedPipe (pipeH, &over))
  200050. {
  200051. connected = false; // yes, you read that right. In overlapped mode it should always return 0.
  200052. }
  200053. else
  200054. {
  200055. const int err = GetLastError();
  200056. if (err == ERROR_IO_PENDING || err == ERROR_PIPE_LISTENING)
  200057. {
  200058. HANDLE handles[] = { over.hEvent, cancelEvent };
  200059. if (WaitForMultipleObjects (2, handles, FALSE,
  200060. timeOutMs >= 0 ? timeOutMs : INFINITE) == WAIT_OBJECT_0)
  200061. connected = true;
  200062. }
  200063. else if (err == ERROR_PIPE_CONNECTED)
  200064. {
  200065. connected = true;
  200066. }
  200067. }
  200068. CloseHandle (over.hEvent);
  200069. }
  200070. return connected;
  200071. }
  200072. void disconnect()
  200073. {
  200074. if (connected)
  200075. {
  200076. DisconnectNamedPipe (pipeH);
  200077. connected = false;
  200078. }
  200079. }
  200080. };
  200081. void NamedPipe::close()
  200082. {
  200083. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  200084. delete intern;
  200085. internal = 0;
  200086. }
  200087. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  200088. {
  200089. close();
  200090. NamedPipeInternal* const intern = new NamedPipeInternal();
  200091. String file ("\\\\.\\pipe\\");
  200092. file += pipeName;
  200093. intern->createdPipe = createPipe;
  200094. if (createPipe)
  200095. {
  200096. intern->pipeH = CreateNamedPipe (file, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED, 0,
  200097. PIPE_UNLIMITED_INSTANCES,
  200098. 4096, 4096, 0, NULL);
  200099. }
  200100. else
  200101. {
  200102. intern->pipeH = CreateFile (file, GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING,
  200103. FILE_FLAG_OVERLAPPED, 0);
  200104. }
  200105. if (intern->pipeH != INVALID_HANDLE_VALUE)
  200106. {
  200107. internal = intern;
  200108. return true;
  200109. }
  200110. delete intern;
  200111. return false;
  200112. }
  200113. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int timeOutMilliseconds)
  200114. {
  200115. int bytesRead = -1;
  200116. bool waitAgain = true;
  200117. while (waitAgain && internal != 0)
  200118. {
  200119. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  200120. waitAgain = false;
  200121. if (! intern->connect (timeOutMilliseconds))
  200122. break;
  200123. if (maxBytesToRead <= 0)
  200124. return 0;
  200125. OVERLAPPED over;
  200126. zerostruct (over);
  200127. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  200128. unsigned long numRead;
  200129. if (ReadFile (intern->pipeH, destBuffer, maxBytesToRead, &numRead, &over))
  200130. {
  200131. bytesRead = (int) numRead;
  200132. }
  200133. else if (GetLastError() == ERROR_IO_PENDING)
  200134. {
  200135. HANDLE handles[] = { over.hEvent, intern->cancelEvent };
  200136. DWORD waitResult = WaitForMultipleObjects (2, handles, FALSE,
  200137. timeOutMilliseconds >= 0 ? timeOutMilliseconds
  200138. : INFINITE);
  200139. if (waitResult != WAIT_OBJECT_0)
  200140. {
  200141. // if the operation timed out, let's cancel it...
  200142. CancelIo (intern->pipeH);
  200143. WaitForSingleObject (over.hEvent, INFINITE); // makes sure cancel is complete
  200144. }
  200145. if (GetOverlappedResult (intern->pipeH, &over, &numRead, FALSE))
  200146. {
  200147. bytesRead = (int) numRead;
  200148. }
  200149. else if (GetLastError() == ERROR_BROKEN_PIPE && intern->createdPipe)
  200150. {
  200151. intern->disconnect();
  200152. waitAgain = true;
  200153. }
  200154. }
  200155. else
  200156. {
  200157. waitAgain = internal != 0;
  200158. Sleep (5);
  200159. }
  200160. CloseHandle (over.hEvent);
  200161. }
  200162. return bytesRead;
  200163. }
  200164. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  200165. {
  200166. int bytesWritten = -1;
  200167. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  200168. if (intern != 0 && intern->connect (timeOutMilliseconds))
  200169. {
  200170. if (numBytesToWrite <= 0)
  200171. return 0;
  200172. OVERLAPPED over;
  200173. zerostruct (over);
  200174. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  200175. unsigned long numWritten;
  200176. if (WriteFile (intern->pipeH, sourceBuffer, numBytesToWrite, &numWritten, &over))
  200177. {
  200178. bytesWritten = (int) numWritten;
  200179. }
  200180. else if (GetLastError() == ERROR_IO_PENDING)
  200181. {
  200182. HANDLE handles[] = { over.hEvent, intern->cancelEvent };
  200183. DWORD waitResult;
  200184. waitResult = WaitForMultipleObjects (2, handles, FALSE,
  200185. timeOutMilliseconds >= 0 ? timeOutMilliseconds
  200186. : INFINITE);
  200187. if (waitResult != WAIT_OBJECT_0)
  200188. {
  200189. CancelIo (intern->pipeH);
  200190. WaitForSingleObject (over.hEvent, INFINITE);
  200191. }
  200192. if (GetOverlappedResult (intern->pipeH, &over, &numWritten, FALSE))
  200193. {
  200194. bytesWritten = (int) numWritten;
  200195. }
  200196. else if (GetLastError() == ERROR_BROKEN_PIPE && intern->createdPipe)
  200197. {
  200198. intern->disconnect();
  200199. }
  200200. }
  200201. CloseHandle (over.hEvent);
  200202. }
  200203. return bytesWritten;
  200204. }
  200205. void NamedPipe::cancelPendingReads()
  200206. {
  200207. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  200208. if (intern != 0)
  200209. SetEvent (intern->cancelEvent);
  200210. }
  200211. #endif
  200212. /********* End of inlined file: juce_win32_Files.cpp *********/
  200213. /********* Start of inlined file: juce_win32_Network.cpp *********/
  200214. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  200215. // compiled on its own).
  200216. #if JUCE_INCLUDED_FILE
  200217. #ifndef INTERNET_FLAG_NEED_FILE
  200218. #define INTERNET_FLAG_NEED_FILE 0x00000010
  200219. #endif
  200220. bool juce_isOnLine()
  200221. {
  200222. DWORD connectionType;
  200223. return InternetGetConnectedState (&connectionType, 0) != 0
  200224. || (connectionType & (INTERNET_CONNECTION_LAN | INTERNET_CONNECTION_PROXY)) != 0;
  200225. }
  200226. struct ConnectionAndRequestStruct
  200227. {
  200228. HINTERNET connection, request;
  200229. };
  200230. static HINTERNET sessionHandle = 0;
  200231. void* juce_openInternetFile (const String& url,
  200232. const String& headers,
  200233. const MemoryBlock& postData,
  200234. const bool isPost,
  200235. URL::OpenStreamProgressCallback* callback,
  200236. void* callbackContext,
  200237. int timeOutMs)
  200238. {
  200239. if (sessionHandle == 0)
  200240. sessionHandle = InternetOpen (_T("juce"),
  200241. INTERNET_OPEN_TYPE_PRECONFIG,
  200242. 0, 0, 0);
  200243. if (sessionHandle != 0)
  200244. {
  200245. // break up the url..
  200246. TCHAR file[1024], server[1024];
  200247. URL_COMPONENTS uc;
  200248. zerostruct (uc);
  200249. uc.dwStructSize = sizeof (uc);
  200250. uc.dwUrlPathLength = sizeof (file);
  200251. uc.dwHostNameLength = sizeof (server);
  200252. uc.lpszUrlPath = file;
  200253. uc.lpszHostName = server;
  200254. if (InternetCrackUrl (url, 0, 0, &uc))
  200255. {
  200256. if (timeOutMs == 0)
  200257. timeOutMs = 30000;
  200258. else if (timeOutMs < 0)
  200259. timeOutMs = -1;
  200260. InternetSetOption (sessionHandle, INTERNET_OPTION_CONNECT_TIMEOUT, &timeOutMs, sizeof (timeOutMs));
  200261. const bool isFtp = url.startsWithIgnoreCase (T("ftp:"));
  200262. HINTERNET connection = InternetConnect (sessionHandle,
  200263. uc.lpszHostName,
  200264. uc.nPort,
  200265. _T(""), _T(""),
  200266. isFtp ? INTERNET_SERVICE_FTP
  200267. : INTERNET_SERVICE_HTTP,
  200268. 0, 0);
  200269. if (connection != 0)
  200270. {
  200271. if (isFtp)
  200272. {
  200273. HINTERNET request = FtpOpenFile (connection,
  200274. uc.lpszUrlPath,
  200275. GENERIC_READ,
  200276. FTP_TRANSFER_TYPE_BINARY | INTERNET_FLAG_NEED_FILE,
  200277. 0);
  200278. ConnectionAndRequestStruct* const result = new ConnectionAndRequestStruct();
  200279. result->connection = connection;
  200280. result->request = request;
  200281. return result;
  200282. }
  200283. else
  200284. {
  200285. const TCHAR* mimeTypes[] = { _T("*/*"), 0 };
  200286. DWORD flags = INTERNET_FLAG_RELOAD | INTERNET_FLAG_NO_CACHE_WRITE;
  200287. if (url.startsWithIgnoreCase (T("https:")))
  200288. flags |= INTERNET_FLAG_SECURE; // (this flag only seems necessary if the OS is running IE6 -
  200289. // IE7 seems to automatically work out when it's https)
  200290. HINTERNET request = HttpOpenRequest (connection,
  200291. isPost ? _T("POST")
  200292. : _T("GET"),
  200293. uc.lpszUrlPath,
  200294. 0, 0, mimeTypes, flags, 0);
  200295. if (request != 0)
  200296. {
  200297. INTERNET_BUFFERS buffers;
  200298. zerostruct (buffers);
  200299. buffers.dwStructSize = sizeof (INTERNET_BUFFERS);
  200300. buffers.lpcszHeader = (LPCTSTR) headers;
  200301. buffers.dwHeadersLength = headers.length();
  200302. buffers.dwBufferTotal = (DWORD) postData.getSize();
  200303. ConnectionAndRequestStruct* result = 0;
  200304. if (HttpSendRequestEx (request, &buffers, 0, HSR_INITIATE, 0))
  200305. {
  200306. int bytesSent = 0;
  200307. for (;;)
  200308. {
  200309. const int bytesToDo = jmin (1024, postData.getSize() - bytesSent);
  200310. DWORD bytesDone = 0;
  200311. if (bytesToDo > 0
  200312. && ! InternetWriteFile (request,
  200313. ((const char*) postData.getData()) + bytesSent,
  200314. bytesToDo, &bytesDone))
  200315. {
  200316. break;
  200317. }
  200318. if (bytesToDo == 0 || (int) bytesDone < bytesToDo)
  200319. {
  200320. result = new ConnectionAndRequestStruct();
  200321. result->connection = connection;
  200322. result->request = request;
  200323. HttpEndRequest (request, 0, 0, 0);
  200324. return result;
  200325. }
  200326. bytesSent += bytesDone;
  200327. if (callback != 0 && ! callback (callbackContext, bytesSent, postData.getSize()))
  200328. break;
  200329. }
  200330. }
  200331. InternetCloseHandle (request);
  200332. }
  200333. InternetCloseHandle (connection);
  200334. }
  200335. }
  200336. }
  200337. }
  200338. return 0;
  200339. }
  200340. int juce_readFromInternetFile (void* handle, void* buffer, int bytesToRead)
  200341. {
  200342. DWORD bytesRead = 0;
  200343. const ConnectionAndRequestStruct* const crs = (const ConnectionAndRequestStruct*) handle;
  200344. if (crs != 0)
  200345. InternetReadFile (crs->request,
  200346. buffer, bytesToRead,
  200347. &bytesRead);
  200348. return bytesRead;
  200349. }
  200350. int juce_seekInInternetFile (void* handle, int newPosition)
  200351. {
  200352. if (handle != 0)
  200353. {
  200354. const ConnectionAndRequestStruct* const crs = (const ConnectionAndRequestStruct*) handle;
  200355. return InternetSetFilePointer (crs->request,
  200356. newPosition, 0,
  200357. FILE_BEGIN, 0);
  200358. }
  200359. else
  200360. {
  200361. return -1;
  200362. }
  200363. }
  200364. int64 juce_getInternetFileContentLength (void* handle)
  200365. {
  200366. const ConnectionAndRequestStruct* const crs = (const ConnectionAndRequestStruct*) handle;
  200367. if (crs != 0)
  200368. {
  200369. DWORD index = 0;
  200370. DWORD result = 0;
  200371. DWORD size = sizeof (result);
  200372. if (HttpQueryInfo (crs->request,
  200373. HTTP_QUERY_CONTENT_LENGTH | HTTP_QUERY_FLAG_NUMBER,
  200374. &result,
  200375. &size,
  200376. &index))
  200377. {
  200378. return (int64) result;
  200379. }
  200380. }
  200381. return -1;
  200382. }
  200383. void juce_closeInternetFile (void* handle)
  200384. {
  200385. if (handle != 0)
  200386. {
  200387. ConnectionAndRequestStruct* const crs = (ConnectionAndRequestStruct*) handle;
  200388. InternetCloseHandle (crs->request);
  200389. InternetCloseHandle (crs->connection);
  200390. delete crs;
  200391. }
  200392. }
  200393. static int getMACAddressViaGetAdaptersInfo (int64* addresses, int maxNum, const bool littleEndian) throw()
  200394. {
  200395. int numFound = 0;
  200396. DynamicLibraryLoader dll ("iphlpapi.dll");
  200397. DynamicLibraryImport (GetAdaptersInfo, getAdaptersInfo, DWORD, dll, (PIP_ADAPTER_INFO, PULONG))
  200398. if (getAdaptersInfo != 0)
  200399. {
  200400. ULONG len = sizeof (IP_ADAPTER_INFO);
  200401. MemoryBlock mb;
  200402. PIP_ADAPTER_INFO adapterInfo = (PIP_ADAPTER_INFO) mb.getData();
  200403. if (getAdaptersInfo (adapterInfo, &len) == ERROR_BUFFER_OVERFLOW)
  200404. {
  200405. mb.setSize (len);
  200406. adapterInfo = (PIP_ADAPTER_INFO) mb.getData();
  200407. }
  200408. if (getAdaptersInfo (adapterInfo, &len) == NO_ERROR)
  200409. {
  200410. PIP_ADAPTER_INFO adapter = adapterInfo;
  200411. while (adapter != 0)
  200412. {
  200413. int64 mac = 0;
  200414. for (unsigned int i = 0; i < adapter->AddressLength; ++i)
  200415. mac = (mac << 8) | adapter->Address[i];
  200416. if (littleEndian)
  200417. mac = (int64) swapByteOrder ((uint64) mac);
  200418. if (numFound < maxNum && mac != 0)
  200419. addresses [numFound++] = mac;
  200420. adapter = adapter->Next;
  200421. }
  200422. }
  200423. }
  200424. return numFound;
  200425. }
  200426. static int getMACAddressesViaNetBios (int64* addresses, int maxNum, const bool littleEndian) throw()
  200427. {
  200428. int numFound = 0;
  200429. DynamicLibraryLoader dll ("netapi32.dll");
  200430. DynamicLibraryImport (Netbios, NetbiosCall, UCHAR, dll, (PNCB))
  200431. if (NetbiosCall != 0)
  200432. {
  200433. NCB ncb;
  200434. zerostruct (ncb);
  200435. typedef struct _ASTAT_
  200436. {
  200437. ADAPTER_STATUS adapt;
  200438. NAME_BUFFER NameBuff [30];
  200439. } ASTAT;
  200440. ASTAT astat;
  200441. zerostruct (astat);
  200442. LANA_ENUM enums;
  200443. zerostruct (enums);
  200444. ncb.ncb_command = NCBENUM;
  200445. ncb.ncb_buffer = (unsigned char*) &enums;
  200446. ncb.ncb_length = sizeof (LANA_ENUM);
  200447. NetbiosCall (&ncb);
  200448. for (int i = 0; i < enums.length; ++i)
  200449. {
  200450. zerostruct (ncb);
  200451. ncb.ncb_command = NCBRESET;
  200452. ncb.ncb_lana_num = enums.lana[i];
  200453. if (NetbiosCall (&ncb) == 0)
  200454. {
  200455. zerostruct (ncb);
  200456. memcpy (ncb.ncb_callname, "* ", NCBNAMSZ);
  200457. ncb.ncb_command = NCBASTAT;
  200458. ncb.ncb_lana_num = enums.lana[i];
  200459. ncb.ncb_buffer = (unsigned char*) &astat;
  200460. ncb.ncb_length = sizeof (ASTAT);
  200461. if (NetbiosCall (&ncb) == 0)
  200462. {
  200463. if (astat.adapt.adapter_type == 0xfe)
  200464. {
  200465. int64 mac = 0;
  200466. for (unsigned int i = 0; i < 6; ++i)
  200467. mac = (mac << 8) | astat.adapt.adapter_address[i];
  200468. if (littleEndian)
  200469. mac = (int64) swapByteOrder ((uint64) mac);
  200470. if (numFound < maxNum && mac != 0)
  200471. addresses [numFound++] = mac;
  200472. }
  200473. }
  200474. }
  200475. }
  200476. }
  200477. return numFound;
  200478. }
  200479. int SystemStats::getMACAddresses (int64* addresses, int maxNum, const bool littleEndian) throw()
  200480. {
  200481. int numFound = getMACAddressViaGetAdaptersInfo (addresses, maxNum, littleEndian);
  200482. if (numFound == 0)
  200483. numFound = getMACAddressesViaNetBios (addresses, maxNum, littleEndian);
  200484. return numFound;
  200485. }
  200486. typedef ULONG (WINAPI *MAPISendMailType) (LHANDLE, ULONG, lpMapiMessage, ::FLAGS, ULONG);
  200487. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  200488. const String& emailSubject,
  200489. const String& bodyText,
  200490. const StringArray& filesToAttach)
  200491. {
  200492. HMODULE h = LoadLibraryA ("MAPI32.dll");
  200493. MAPISendMailType mapiSendMail = (MAPISendMailType) GetProcAddress (h, "MAPISendMail");
  200494. bool ok = false;
  200495. if (mapiSendMail != 0)
  200496. {
  200497. MapiMessage message;
  200498. zerostruct (message);
  200499. message.lpszSubject = (LPSTR) (LPCSTR) emailSubject;
  200500. message.lpszNoteText = (LPSTR) (LPCSTR) bodyText;
  200501. MapiRecipDesc recip;
  200502. zerostruct (recip);
  200503. recip.ulRecipClass = MAPI_TO;
  200504. String targetEmailAddress_ (targetEmailAddress);
  200505. if (targetEmailAddress_.isEmpty())
  200506. targetEmailAddress_ = " "; // (Windows Mail can't deal with a blank address)
  200507. recip.lpszName = (LPSTR) (LPCSTR) targetEmailAddress_;
  200508. message.nRecipCount = 1;
  200509. message.lpRecips = &recip;
  200510. MemoryBlock mb (sizeof (MapiFileDesc) * filesToAttach.size());
  200511. mb.fillWith (0);
  200512. MapiFileDesc* files = (MapiFileDesc*) mb.getData();
  200513. message.nFileCount = filesToAttach.size();
  200514. message.lpFiles = files;
  200515. for (int i = 0; i < filesToAttach.size(); ++i)
  200516. {
  200517. files[i].nPosition = (ULONG) -1;
  200518. files[i].lpszPathName = (LPSTR) (LPCSTR) filesToAttach [i];
  200519. }
  200520. ok = (mapiSendMail (0, 0, &message, MAPI_DIALOG | MAPI_LOGON_UI, 0) == SUCCESS_SUCCESS);
  200521. }
  200522. FreeLibrary (h);
  200523. return ok;
  200524. }
  200525. #endif
  200526. /********* End of inlined file: juce_win32_Network.cpp *********/
  200527. /********* Start of inlined file: juce_win32_PlatformUtils.cpp *********/
  200528. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  200529. // compiled on its own).
  200530. #if JUCE_INCLUDED_FILE
  200531. static HKEY findKeyForPath (String name,
  200532. const bool createForWriting,
  200533. String& valueName) throw()
  200534. {
  200535. HKEY rootKey = 0;
  200536. if (name.startsWithIgnoreCase (T("HKEY_CURRENT_USER\\")))
  200537. rootKey = HKEY_CURRENT_USER;
  200538. else if (name.startsWithIgnoreCase (T("HKEY_LOCAL_MACHINE\\")))
  200539. rootKey = HKEY_LOCAL_MACHINE;
  200540. else if (name.startsWithIgnoreCase (T("HKEY_CLASSES_ROOT\\")))
  200541. rootKey = HKEY_CLASSES_ROOT;
  200542. if (rootKey != 0)
  200543. {
  200544. name = name.substring (name.indexOfChar (T('\\')) + 1);
  200545. const int lastSlash = name.lastIndexOfChar (T('\\'));
  200546. valueName = name.substring (lastSlash + 1);
  200547. name = name.substring (0, lastSlash);
  200548. HKEY key;
  200549. DWORD result;
  200550. if (createForWriting)
  200551. {
  200552. if (RegCreateKeyEx (rootKey, name, 0, L"", REG_OPTION_NON_VOLATILE,
  200553. (KEY_WRITE | KEY_QUERY_VALUE), 0, &key, &result) == ERROR_SUCCESS)
  200554. return key;
  200555. }
  200556. else
  200557. {
  200558. if (RegOpenKeyEx (rootKey, name, 0, KEY_READ, &key) == ERROR_SUCCESS)
  200559. return key;
  200560. }
  200561. }
  200562. return 0;
  200563. }
  200564. const String PlatformUtilities::getRegistryValue (const String& regValuePath,
  200565. const String& defaultValue)
  200566. {
  200567. String valueName, s;
  200568. HKEY k = findKeyForPath (regValuePath, false, valueName);
  200569. if (k != 0)
  200570. {
  200571. WCHAR buffer [2048];
  200572. unsigned long bufferSize = sizeof (buffer);
  200573. DWORD type = REG_SZ;
  200574. if (RegQueryValueEx (k, valueName, 0, &type, (LPBYTE) buffer, &bufferSize) == ERROR_SUCCESS)
  200575. s = buffer;
  200576. else
  200577. s = defaultValue;
  200578. RegCloseKey (k);
  200579. }
  200580. return s;
  200581. }
  200582. void PlatformUtilities::setRegistryValue (const String& regValuePath,
  200583. const String& value)
  200584. {
  200585. String valueName;
  200586. HKEY k = findKeyForPath (regValuePath, true, valueName);
  200587. if (k != 0)
  200588. {
  200589. RegSetValueEx (k, valueName, 0, REG_SZ,
  200590. (const BYTE*) (const WCHAR*) value,
  200591. sizeof (WCHAR) * (value.length() + 1));
  200592. RegCloseKey (k);
  200593. }
  200594. }
  200595. bool PlatformUtilities::registryValueExists (const String& regValuePath)
  200596. {
  200597. bool exists = false;
  200598. String valueName;
  200599. HKEY k = findKeyForPath (regValuePath, false, valueName);
  200600. if (k != 0)
  200601. {
  200602. unsigned char buffer [2048];
  200603. unsigned long bufferSize = sizeof (buffer);
  200604. DWORD type = 0;
  200605. if (RegQueryValueEx (k, valueName, 0, &type, buffer, &bufferSize) == ERROR_SUCCESS)
  200606. exists = true;
  200607. RegCloseKey (k);
  200608. }
  200609. return exists;
  200610. }
  200611. void PlatformUtilities::deleteRegistryValue (const String& regValuePath)
  200612. {
  200613. String valueName;
  200614. HKEY k = findKeyForPath (regValuePath, true, valueName);
  200615. if (k != 0)
  200616. {
  200617. RegDeleteValue (k, valueName);
  200618. RegCloseKey (k);
  200619. }
  200620. }
  200621. void PlatformUtilities::deleteRegistryKey (const String& regKeyPath)
  200622. {
  200623. String valueName;
  200624. HKEY k = findKeyForPath (regKeyPath, true, valueName);
  200625. if (k != 0)
  200626. {
  200627. RegDeleteKey (k, valueName);
  200628. RegCloseKey (k);
  200629. }
  200630. }
  200631. void PlatformUtilities::registerFileAssociation (const String& fileExtension,
  200632. const String& symbolicDescription,
  200633. const String& fullDescription,
  200634. const File& targetExecutable,
  200635. int iconResourceNumber)
  200636. {
  200637. setRegistryValue ("HKEY_CLASSES_ROOT\\" + fileExtension + "\\", symbolicDescription);
  200638. const String key ("HKEY_CLASSES_ROOT\\" + symbolicDescription);
  200639. if (iconResourceNumber != 0)
  200640. setRegistryValue (key + "\\DefaultIcon\\",
  200641. targetExecutable.getFullPathName() + "," + String (-iconResourceNumber));
  200642. setRegistryValue (key + "\\", fullDescription);
  200643. setRegistryValue (key + "\\shell\\open\\command\\",
  200644. targetExecutable.getFullPathName() + " %1");
  200645. }
  200646. bool juce_IsRunningInWine() throw()
  200647. {
  200648. HKEY key;
  200649. if (RegOpenKeyEx (HKEY_CURRENT_USER, _T("Software\\Wine"), 0, KEY_READ, &key) == ERROR_SUCCESS)
  200650. {
  200651. RegCloseKey (key);
  200652. return true;
  200653. }
  200654. return false;
  200655. }
  200656. const String JUCE_CALLTYPE PlatformUtilities::getCurrentCommandLineParams() throw()
  200657. {
  200658. String s (::GetCommandLineW());
  200659. StringArray tokens;
  200660. tokens.addTokens (s, true); // tokenise so that we can remove the initial filename argument
  200661. return tokens.joinIntoString (T(" "), 1);
  200662. }
  200663. static void* currentModuleHandle = 0;
  200664. void* PlatformUtilities::getCurrentModuleInstanceHandle() throw()
  200665. {
  200666. if (currentModuleHandle == 0)
  200667. currentModuleHandle = GetModuleHandle (0);
  200668. return currentModuleHandle;
  200669. }
  200670. void PlatformUtilities::setCurrentModuleInstanceHandle (void* const newHandle) throw()
  200671. {
  200672. currentModuleHandle = newHandle;
  200673. }
  200674. void PlatformUtilities::fpuReset()
  200675. {
  200676. #if JUCE_MSVC
  200677. _clearfp();
  200678. #endif
  200679. }
  200680. void PlatformUtilities::beep()
  200681. {
  200682. MessageBeep (MB_OK);
  200683. }
  200684. #endif
  200685. /********* End of inlined file: juce_win32_PlatformUtils.cpp *********/
  200686. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  200687. /********* Start of inlined file: juce_win32_Messaging.cpp *********/
  200688. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  200689. // compiled on its own).
  200690. #if JUCE_INCLUDED_FILE
  200691. static const unsigned int specialId = WM_APP + 0x4400;
  200692. static const unsigned int broadcastId = WM_APP + 0x4403;
  200693. static const unsigned int specialCallbackId = WM_APP + 0x4402;
  200694. static const TCHAR* const messageWindowName = _T("JUCEWindow");
  200695. HWND juce_messageWindowHandle = 0;
  200696. extern long improbableWindowNumber; // defined in windowing.cpp
  200697. static LRESULT CALLBACK juce_MessageWndProc (HWND h,
  200698. const UINT message,
  200699. const WPARAM wParam,
  200700. const LPARAM lParam) throw()
  200701. {
  200702. JUCE_TRY
  200703. {
  200704. if (h == juce_messageWindowHandle)
  200705. {
  200706. if (message == specialCallbackId)
  200707. {
  200708. MessageCallbackFunction* const func = (MessageCallbackFunction*) wParam;
  200709. return (LRESULT) (*func) ((void*) lParam);
  200710. }
  200711. else if (message == specialId)
  200712. {
  200713. // these are trapped early in the dispatch call, but must also be checked
  200714. // here in case there are windows modal dialog boxes doing their own
  200715. // dispatch loop and not calling our version
  200716. MessageManager::getInstance()->deliverMessage ((void*) lParam);
  200717. return 0;
  200718. }
  200719. else if (message == broadcastId)
  200720. {
  200721. String* const messageString = (String*) lParam;
  200722. MessageManager::getInstance()->deliverBroadcastMessage (*messageString);
  200723. delete messageString;
  200724. return 0;
  200725. }
  200726. else if (message == WM_COPYDATA && ((const COPYDATASTRUCT*) lParam)->dwData == broadcastId)
  200727. {
  200728. const String messageString ((const juce_wchar*) ((const COPYDATASTRUCT*) lParam)->lpData,
  200729. ((const COPYDATASTRUCT*) lParam)->cbData / sizeof (juce_wchar));
  200730. PostMessage (juce_messageWindowHandle, broadcastId, 0, (LPARAM) new String (messageString));
  200731. return 0;
  200732. }
  200733. }
  200734. }
  200735. JUCE_CATCH_EXCEPTION
  200736. return DefWindowProc (h, message, wParam, lParam);
  200737. }
  200738. static bool isEventBlockedByModalComps (MSG& m)
  200739. {
  200740. if (Component::getNumCurrentlyModalComponents() == 0
  200741. || GetWindowLong (m.hwnd, GWLP_USERDATA) == improbableWindowNumber)
  200742. return false;
  200743. switch (m.message)
  200744. {
  200745. case WM_MOUSEMOVE:
  200746. case WM_NCMOUSEMOVE:
  200747. case 0x020A: /* WM_MOUSEWHEEL */
  200748. case 0x020E: /* WM_MOUSEHWHEEL */
  200749. case WM_KEYUP:
  200750. case WM_SYSKEYUP:
  200751. case WM_CHAR:
  200752. case WM_APPCOMMAND:
  200753. case WM_LBUTTONUP:
  200754. case WM_MBUTTONUP:
  200755. case WM_RBUTTONUP:
  200756. case WM_MOUSEACTIVATE:
  200757. case WM_NCMOUSEHOVER:
  200758. case WM_MOUSEHOVER:
  200759. return true;
  200760. case WM_NCLBUTTONDOWN:
  200761. case WM_NCLBUTTONDBLCLK:
  200762. case WM_NCRBUTTONDOWN:
  200763. case WM_NCRBUTTONDBLCLK:
  200764. case WM_NCMBUTTONDOWN:
  200765. case WM_NCMBUTTONDBLCLK:
  200766. case WM_LBUTTONDOWN:
  200767. case WM_LBUTTONDBLCLK:
  200768. case WM_MBUTTONDOWN:
  200769. case WM_MBUTTONDBLCLK:
  200770. case WM_RBUTTONDOWN:
  200771. case WM_RBUTTONDBLCLK:
  200772. case WM_KEYDOWN:
  200773. case WM_SYSKEYDOWN:
  200774. {
  200775. Component* const modal = Component::getCurrentlyModalComponent (0);
  200776. if (modal != 0)
  200777. modal->inputAttemptWhenModal();
  200778. return true;
  200779. }
  200780. default:
  200781. break;
  200782. }
  200783. return false;
  200784. }
  200785. bool juce_dispatchNextMessageOnSystemQueue (const bool returnIfNoPendingMessages)
  200786. {
  200787. MSG m;
  200788. if (returnIfNoPendingMessages && ! PeekMessage (&m, (HWND) 0, 0, 0, 0))
  200789. return false;
  200790. if (GetMessage (&m, (HWND) 0, 0, 0) > 0)
  200791. {
  200792. if (m.message == specialId
  200793. && m.hwnd == juce_messageWindowHandle)
  200794. {
  200795. MessageManager::getInstance()->deliverMessage ((void*) m.lParam);
  200796. }
  200797. else if (! isEventBlockedByModalComps (m))
  200798. {
  200799. if (GetWindowLong (m.hwnd, GWLP_USERDATA) != improbableWindowNumber
  200800. && (m.message == WM_LBUTTONDOWN || m.message == WM_RBUTTONDOWN))
  200801. {
  200802. // if it's someone else's window being clicked on, and the focus is
  200803. // currently on a juce window, pass the kb focus over..
  200804. HWND currentFocus = GetFocus();
  200805. if (currentFocus == 0 || GetWindowLong (currentFocus, GWLP_USERDATA) == improbableWindowNumber)
  200806. SetFocus (m.hwnd);
  200807. }
  200808. TranslateMessage (&m);
  200809. DispatchMessage (&m);
  200810. }
  200811. }
  200812. return true;
  200813. }
  200814. bool juce_postMessageToSystemQueue (void* message)
  200815. {
  200816. return PostMessage (juce_messageWindowHandle, specialId, 0, (LPARAM) message) != 0;
  200817. }
  200818. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* callback,
  200819. void* userData)
  200820. {
  200821. if (MessageManager::getInstance()->isThisTheMessageThread())
  200822. {
  200823. return (*callback) (userData);
  200824. }
  200825. else
  200826. {
  200827. // If a thread has a MessageManagerLock and then tries to call this method, it'll
  200828. // deadlock because the message manager is blocked from running, and can't
  200829. // call your function..
  200830. jassert (! MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  200831. return (void*) SendMessage (juce_messageWindowHandle,
  200832. specialCallbackId,
  200833. (WPARAM) callback,
  200834. (LPARAM) userData);
  200835. }
  200836. }
  200837. static BOOL CALLBACK BroadcastEnumWindowProc (HWND hwnd, LPARAM lParam)
  200838. {
  200839. if (hwnd != juce_messageWindowHandle)
  200840. (reinterpret_cast <VoidArray*> (lParam))->add ((void*) hwnd);
  200841. return TRUE;
  200842. }
  200843. void MessageManager::broadcastMessage (const String& value) throw()
  200844. {
  200845. VoidArray windows;
  200846. EnumWindows (&BroadcastEnumWindowProc, (LPARAM) &windows);
  200847. const String localCopy (value);
  200848. COPYDATASTRUCT data;
  200849. data.dwData = broadcastId;
  200850. data.cbData = (localCopy.length() + 1) * sizeof (juce_wchar);
  200851. data.lpData = (void*) (const juce_wchar*) localCopy;
  200852. for (int i = windows.size(); --i >= 0;)
  200853. {
  200854. HWND hwnd = (HWND) windows.getUnchecked(i);
  200855. TCHAR windowName [64]; // no need to read longer strings than this
  200856. GetWindowText (hwnd, windowName, 64);
  200857. windowName [63] = 0;
  200858. if (String (windowName) == String (messageWindowName))
  200859. {
  200860. DWORD_PTR result;
  200861. SendMessageTimeout (hwnd, WM_COPYDATA,
  200862. (WPARAM) juce_messageWindowHandle,
  200863. (LPARAM) &data,
  200864. SMTO_BLOCK | SMTO_ABORTIFHUNG,
  200865. 8000,
  200866. &result);
  200867. }
  200868. }
  200869. }
  200870. static const String getMessageWindowClassName()
  200871. {
  200872. // this name has to be different for each app/dll instance because otherwise
  200873. // poor old Win32 can get a bit confused (even despite it not being a process-global
  200874. // window class).
  200875. static int number = 0;
  200876. if (number == 0)
  200877. number = 0x7fffffff & (int) Time::getHighResolutionTicks();
  200878. return T("JUCEcs_") + String (number);
  200879. }
  200880. void MessageManager::doPlatformSpecificInitialisation()
  200881. {
  200882. OleInitialize (0);
  200883. const String className (getMessageWindowClassName());
  200884. HMODULE hmod = (HMODULE) PlatformUtilities::getCurrentModuleInstanceHandle();
  200885. WNDCLASSEX wc;
  200886. zerostruct (wc);
  200887. wc.cbSize = sizeof (wc);
  200888. wc.lpfnWndProc = (WNDPROC) juce_MessageWndProc;
  200889. wc.cbWndExtra = 4;
  200890. wc.hInstance = hmod;
  200891. wc.lpszClassName = className;
  200892. RegisterClassEx (&wc);
  200893. juce_messageWindowHandle = CreateWindow (wc.lpszClassName,
  200894. messageWindowName,
  200895. 0, 0, 0, 0, 0, 0, 0,
  200896. hmod, 0);
  200897. }
  200898. void MessageManager::doPlatformSpecificShutdown()
  200899. {
  200900. DestroyWindow (juce_messageWindowHandle);
  200901. UnregisterClass (getMessageWindowClassName(), 0);
  200902. OleUninitialize();
  200903. }
  200904. #endif
  200905. /********* End of inlined file: juce_win32_Messaging.cpp *********/
  200906. /********* Start of inlined file: juce_win32_Windowing.cpp *********/
  200907. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  200908. // compiled on its own).
  200909. #if JUCE_INCLUDED_FILE
  200910. #undef GetSystemMetrics // multimon overrides this for some reason and causes a mess..
  200911. // these are in the windows SDK, but need to be repeated here for GCC..
  200912. #ifndef GET_APPCOMMAND_LPARAM
  200913. #define FAPPCOMMAND_MASK 0xF000
  200914. #define GET_APPCOMMAND_LPARAM(lParam) ((short) (HIWORD (lParam) & ~FAPPCOMMAND_MASK))
  200915. #define APPCOMMAND_MEDIA_NEXTTRACK 11
  200916. #define APPCOMMAND_MEDIA_PREVIOUSTRACK 12
  200917. #define APPCOMMAND_MEDIA_STOP 13
  200918. #define APPCOMMAND_MEDIA_PLAY_PAUSE 14
  200919. #define WM_APPCOMMAND 0x0319
  200920. #endif
  200921. extern void juce_repeatLastProcessPriority() throw(); // in juce_win32_Threads.cpp
  200922. extern void juce_CheckCurrentlyFocusedTopLevelWindow() throw(); // in juce_TopLevelWindow.cpp
  200923. extern bool juce_IsRunningInWine() throw();
  200924. #ifndef ULW_ALPHA
  200925. #define ULW_ALPHA 0x00000002
  200926. #endif
  200927. #ifndef AC_SRC_ALPHA
  200928. #define AC_SRC_ALPHA 0x01
  200929. #endif
  200930. #define DEBUG_REPAINT_TIMES 0
  200931. static HPALETTE palette = 0;
  200932. static bool createPaletteIfNeeded = true;
  200933. static bool shouldDeactivateTitleBar = true;
  200934. static HICON createHICONFromImage (const Image& image, const BOOL isIcon, int hotspotX, int hotspotY) throw();
  200935. #define WM_TRAYNOTIFY WM_USER + 100
  200936. using ::abs;
  200937. typedef BOOL (WINAPI* UpdateLayeredWinFunc) (HWND, HDC, POINT*, SIZE*, HDC, POINT*, COLORREF, BLENDFUNCTION*, DWORD);
  200938. static UpdateLayeredWinFunc updateLayeredWindow = 0;
  200939. bool Desktop::canUseSemiTransparentWindows() throw()
  200940. {
  200941. if (updateLayeredWindow == 0)
  200942. {
  200943. if (! juce_IsRunningInWine())
  200944. {
  200945. HMODULE user32Mod = GetModuleHandle (_T("user32.dll"));
  200946. updateLayeredWindow = (UpdateLayeredWinFunc) GetProcAddress (user32Mod, "UpdateLayeredWindow");
  200947. }
  200948. }
  200949. return updateLayeredWindow != 0;
  200950. }
  200951. #undef DefWindowProc
  200952. #define DefWindowProc DefWindowProcW
  200953. const int extendedKeyModifier = 0x10000;
  200954. const int KeyPress::spaceKey = VK_SPACE;
  200955. const int KeyPress::returnKey = VK_RETURN;
  200956. const int KeyPress::escapeKey = VK_ESCAPE;
  200957. const int KeyPress::backspaceKey = VK_BACK;
  200958. const int KeyPress::deleteKey = VK_DELETE | extendedKeyModifier;
  200959. const int KeyPress::insertKey = VK_INSERT | extendedKeyModifier;
  200960. const int KeyPress::tabKey = VK_TAB;
  200961. const int KeyPress::leftKey = VK_LEFT | extendedKeyModifier;
  200962. const int KeyPress::rightKey = VK_RIGHT | extendedKeyModifier;
  200963. const int KeyPress::upKey = VK_UP | extendedKeyModifier;
  200964. const int KeyPress::downKey = VK_DOWN | extendedKeyModifier;
  200965. const int KeyPress::homeKey = VK_HOME | extendedKeyModifier;
  200966. const int KeyPress::endKey = VK_END | extendedKeyModifier;
  200967. const int KeyPress::pageUpKey = VK_PRIOR | extendedKeyModifier;
  200968. const int KeyPress::pageDownKey = VK_NEXT | extendedKeyModifier;
  200969. const int KeyPress::F1Key = VK_F1 | extendedKeyModifier;
  200970. const int KeyPress::F2Key = VK_F2 | extendedKeyModifier;
  200971. const int KeyPress::F3Key = VK_F3 | extendedKeyModifier;
  200972. const int KeyPress::F4Key = VK_F4 | extendedKeyModifier;
  200973. const int KeyPress::F5Key = VK_F5 | extendedKeyModifier;
  200974. const int KeyPress::F6Key = VK_F6 | extendedKeyModifier;
  200975. const int KeyPress::F7Key = VK_F7 | extendedKeyModifier;
  200976. const int KeyPress::F8Key = VK_F8 | extendedKeyModifier;
  200977. const int KeyPress::F9Key = VK_F9 | extendedKeyModifier;
  200978. const int KeyPress::F10Key = VK_F10 | extendedKeyModifier;
  200979. const int KeyPress::F11Key = VK_F11 | extendedKeyModifier;
  200980. const int KeyPress::F12Key = VK_F12 | extendedKeyModifier;
  200981. const int KeyPress::F13Key = VK_F13 | extendedKeyModifier;
  200982. const int KeyPress::F14Key = VK_F14 | extendedKeyModifier;
  200983. const int KeyPress::F15Key = VK_F15 | extendedKeyModifier;
  200984. const int KeyPress::F16Key = VK_F16 | extendedKeyModifier;
  200985. const int KeyPress::numberPad0 = VK_NUMPAD0 | extendedKeyModifier;
  200986. const int KeyPress::numberPad1 = VK_NUMPAD1 | extendedKeyModifier;
  200987. const int KeyPress::numberPad2 = VK_NUMPAD2 | extendedKeyModifier;
  200988. const int KeyPress::numberPad3 = VK_NUMPAD3 | extendedKeyModifier;
  200989. const int KeyPress::numberPad4 = VK_NUMPAD4 | extendedKeyModifier;
  200990. const int KeyPress::numberPad5 = VK_NUMPAD5 | extendedKeyModifier;
  200991. const int KeyPress::numberPad6 = VK_NUMPAD6 | extendedKeyModifier;
  200992. const int KeyPress::numberPad7 = VK_NUMPAD7 | extendedKeyModifier;
  200993. const int KeyPress::numberPad8 = VK_NUMPAD8 | extendedKeyModifier;
  200994. const int KeyPress::numberPad9 = VK_NUMPAD9 | extendedKeyModifier;
  200995. const int KeyPress::numberPadAdd = VK_ADD | extendedKeyModifier;
  200996. const int KeyPress::numberPadSubtract = VK_SUBTRACT | extendedKeyModifier;
  200997. const int KeyPress::numberPadMultiply = VK_MULTIPLY | extendedKeyModifier;
  200998. const int KeyPress::numberPadDivide = VK_DIVIDE | extendedKeyModifier;
  200999. const int KeyPress::numberPadSeparator = VK_SEPARATOR | extendedKeyModifier;
  201000. const int KeyPress::numberPadDecimalPoint = VK_DECIMAL | extendedKeyModifier;
  201001. const int KeyPress::numberPadEquals = 0x92 /*VK_OEM_NEC_EQUAL*/ | extendedKeyModifier;
  201002. const int KeyPress::numberPadDelete = VK_DELETE | extendedKeyModifier;
  201003. const int KeyPress::playKey = 0x30000;
  201004. const int KeyPress::stopKey = 0x30001;
  201005. const int KeyPress::fastForwardKey = 0x30002;
  201006. const int KeyPress::rewindKey = 0x30003;
  201007. class WindowsBitmapImage : public Image
  201008. {
  201009. public:
  201010. HBITMAP hBitmap;
  201011. BITMAPV4HEADER bitmapInfo;
  201012. HDC hdc;
  201013. unsigned char* bitmapData;
  201014. WindowsBitmapImage (const PixelFormat format_,
  201015. const int w, const int h, const bool clearImage)
  201016. : Image (format_, w, h)
  201017. {
  201018. jassert (format_ == RGB || format_ == ARGB);
  201019. pixelStride = (format_ == RGB) ? 3 : 4;
  201020. zerostruct (bitmapInfo);
  201021. bitmapInfo.bV4Size = sizeof (BITMAPV4HEADER);
  201022. bitmapInfo.bV4Width = w;
  201023. bitmapInfo.bV4Height = h;
  201024. bitmapInfo.bV4Planes = 1;
  201025. bitmapInfo.bV4CSType = 1;
  201026. bitmapInfo.bV4BitCount = (unsigned short) (pixelStride * 8);
  201027. if (format_ == ARGB)
  201028. {
  201029. bitmapInfo.bV4AlphaMask = 0xff000000;
  201030. bitmapInfo.bV4RedMask = 0xff0000;
  201031. bitmapInfo.bV4GreenMask = 0xff00;
  201032. bitmapInfo.bV4BlueMask = 0xff;
  201033. bitmapInfo.bV4V4Compression = BI_BITFIELDS;
  201034. }
  201035. else
  201036. {
  201037. bitmapInfo.bV4V4Compression = BI_RGB;
  201038. }
  201039. lineStride = -((w * pixelStride + 3) & ~3);
  201040. HDC dc = GetDC (0);
  201041. hdc = CreateCompatibleDC (dc);
  201042. ReleaseDC (0, dc);
  201043. SetMapMode (hdc, MM_TEXT);
  201044. hBitmap = CreateDIBSection (hdc,
  201045. (BITMAPINFO*) &(bitmapInfo),
  201046. DIB_RGB_COLORS,
  201047. (void**) &bitmapData,
  201048. 0, 0);
  201049. SelectObject (hdc, hBitmap);
  201050. if (format_ == ARGB && clearImage)
  201051. zeromem (bitmapData, abs (h * lineStride));
  201052. imageData = bitmapData - (lineStride * (h - 1));
  201053. }
  201054. ~WindowsBitmapImage()
  201055. {
  201056. DeleteDC (hdc);
  201057. DeleteObject (hBitmap);
  201058. imageData = 0; // to stop the base class freeing this
  201059. }
  201060. void blitToWindow (HWND hwnd, HDC dc, const bool transparent,
  201061. const int x, const int y,
  201062. const RectangleList& maskedRegion) throw()
  201063. {
  201064. static HDRAWDIB hdd = 0;
  201065. static bool needToCreateDrawDib = true;
  201066. if (needToCreateDrawDib)
  201067. {
  201068. needToCreateDrawDib = false;
  201069. HDC dc = GetDC (0);
  201070. const int n = GetDeviceCaps (dc, BITSPIXEL);
  201071. ReleaseDC (0, dc);
  201072. // only open if we're not palettised
  201073. if (n > 8)
  201074. hdd = DrawDibOpen();
  201075. }
  201076. if (createPaletteIfNeeded)
  201077. {
  201078. HDC dc = GetDC (0);
  201079. const int n = GetDeviceCaps (dc, BITSPIXEL);
  201080. ReleaseDC (0, dc);
  201081. if (n <= 8)
  201082. palette = CreateHalftonePalette (dc);
  201083. createPaletteIfNeeded = false;
  201084. }
  201085. if (palette != 0)
  201086. {
  201087. SelectPalette (dc, palette, FALSE);
  201088. RealizePalette (dc);
  201089. SetStretchBltMode (dc, HALFTONE);
  201090. }
  201091. SetMapMode (dc, MM_TEXT);
  201092. if (transparent)
  201093. {
  201094. POINT p, pos;
  201095. SIZE size;
  201096. RECT windowBounds;
  201097. GetWindowRect (hwnd, &windowBounds);
  201098. p.x = -x;
  201099. p.y = -y;
  201100. pos.x = windowBounds.left;
  201101. pos.y = windowBounds.top;
  201102. size.cx = windowBounds.right - windowBounds.left;
  201103. size.cy = windowBounds.bottom - windowBounds.top;
  201104. BLENDFUNCTION bf;
  201105. bf.AlphaFormat = AC_SRC_ALPHA;
  201106. bf.BlendFlags = 0;
  201107. bf.BlendOp = AC_SRC_OVER;
  201108. bf.SourceConstantAlpha = 0xff;
  201109. if (! maskedRegion.isEmpty())
  201110. {
  201111. for (RectangleList::Iterator i (maskedRegion); i.next();)
  201112. {
  201113. const Rectangle& r = *i.getRectangle();
  201114. ExcludeClipRect (hdc, r.getX(), r.getY(), r.getRight(), r.getBottom());
  201115. }
  201116. }
  201117. updateLayeredWindow (hwnd, 0, &pos, &size, hdc, &p, 0, &bf, ULW_ALPHA);
  201118. }
  201119. else
  201120. {
  201121. int savedDC = 0;
  201122. if (! maskedRegion.isEmpty())
  201123. {
  201124. savedDC = SaveDC (dc);
  201125. for (RectangleList::Iterator i (maskedRegion); i.next();)
  201126. {
  201127. const Rectangle& r = *i.getRectangle();
  201128. ExcludeClipRect (dc, r.getX(), r.getY(), r.getRight(), r.getBottom());
  201129. }
  201130. }
  201131. const int w = getWidth();
  201132. const int h = getHeight();
  201133. if (hdd == 0)
  201134. {
  201135. StretchDIBits (dc,
  201136. x, y, w, h,
  201137. 0, 0, w, h,
  201138. bitmapData, (const BITMAPINFO*) &bitmapInfo,
  201139. DIB_RGB_COLORS, SRCCOPY);
  201140. }
  201141. else
  201142. {
  201143. DrawDibDraw (hdd, dc, x, y, -1, -1,
  201144. (BITMAPINFOHEADER*) &bitmapInfo, bitmapData,
  201145. 0, 0, w, h, 0);
  201146. }
  201147. if (! maskedRegion.isEmpty())
  201148. RestoreDC (dc, savedDC);
  201149. }
  201150. }
  201151. juce_UseDebuggingNewOperator
  201152. private:
  201153. WindowsBitmapImage (const WindowsBitmapImage&);
  201154. const WindowsBitmapImage& operator= (const WindowsBitmapImage&);
  201155. };
  201156. long improbableWindowNumber = 0xf965aa01; // also referenced by messaging.cpp
  201157. static int currentModifiers = 0;
  201158. static int modifiersAtLastCallback = 0;
  201159. static void updateKeyModifiers() throw()
  201160. {
  201161. currentModifiers &= ~(ModifierKeys::shiftModifier
  201162. | ModifierKeys::ctrlModifier
  201163. | ModifierKeys::altModifier);
  201164. if ((GetKeyState (VK_SHIFT) & 0x8000) != 0)
  201165. currentModifiers |= ModifierKeys::shiftModifier;
  201166. if ((GetKeyState (VK_CONTROL) & 0x8000) != 0)
  201167. currentModifiers |= ModifierKeys::ctrlModifier;
  201168. if ((GetKeyState (VK_MENU) & 0x8000) != 0)
  201169. currentModifiers |= ModifierKeys::altModifier;
  201170. if ((GetKeyState (VK_RMENU) & 0x8000) != 0)
  201171. currentModifiers &= ~(ModifierKeys::ctrlModifier | ModifierKeys::altModifier);
  201172. }
  201173. void ModifierKeys::updateCurrentModifiers() throw()
  201174. {
  201175. currentModifierFlags = currentModifiers;
  201176. }
  201177. bool KeyPress::isKeyCurrentlyDown (const int keyCode) throw()
  201178. {
  201179. SHORT k = (SHORT) keyCode;
  201180. if ((keyCode & extendedKeyModifier) == 0
  201181. && (k >= (SHORT) T('a') && k <= (SHORT) T('z')))
  201182. k += (SHORT) T('A') - (SHORT) T('a');
  201183. const SHORT translatedValues[] = { (SHORT) ',', VK_OEM_COMMA,
  201184. (SHORT) '+', VK_OEM_PLUS,
  201185. (SHORT) '-', VK_OEM_MINUS,
  201186. (SHORT) '.', VK_OEM_PERIOD,
  201187. (SHORT) ';', VK_OEM_1,
  201188. (SHORT) ':', VK_OEM_1,
  201189. (SHORT) '/', VK_OEM_2,
  201190. (SHORT) '?', VK_OEM_2,
  201191. (SHORT) '[', VK_OEM_4,
  201192. (SHORT) ']', VK_OEM_6 };
  201193. for (int i = 0; i < numElementsInArray (translatedValues); i += 2)
  201194. if (k == translatedValues [i])
  201195. k = translatedValues [i + 1];
  201196. return (GetKeyState (k) & 0x8000) != 0;
  201197. }
  201198. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  201199. {
  201200. updateKeyModifiers();
  201201. currentModifiers &= ~ModifierKeys::allMouseButtonModifiers;
  201202. if ((GetKeyState (VK_LBUTTON) & 0x8000) != 0)
  201203. currentModifiers |= ModifierKeys::leftButtonModifier;
  201204. if ((GetKeyState (VK_RBUTTON) & 0x8000) != 0)
  201205. currentModifiers |= ModifierKeys::rightButtonModifier;
  201206. if ((GetKeyState (VK_MBUTTON) & 0x8000) != 0)
  201207. currentModifiers |= ModifierKeys::middleButtonModifier;
  201208. return ModifierKeys (currentModifiers);
  201209. }
  201210. static int64 getMouseEventTime() throw()
  201211. {
  201212. static int64 eventTimeOffset = 0;
  201213. static DWORD lastMessageTime = 0;
  201214. const DWORD thisMessageTime = GetMessageTime();
  201215. if (thisMessageTime < lastMessageTime || lastMessageTime == 0)
  201216. {
  201217. lastMessageTime = thisMessageTime;
  201218. eventTimeOffset = Time::currentTimeMillis() - thisMessageTime;
  201219. }
  201220. return eventTimeOffset + thisMessageTime;
  201221. }
  201222. static void* callFunctionIfNotLocked (MessageCallbackFunction* callback, void* userData)
  201223. {
  201224. if (MessageManager::getInstance()->currentThreadHasLockedMessageManager())
  201225. return callback (userData);
  201226. else
  201227. return MessageManager::getInstance()->callFunctionOnMessageThread (callback, userData);
  201228. }
  201229. class Win32ComponentPeer : public ComponentPeer
  201230. {
  201231. public:
  201232. Win32ComponentPeer (Component* const component,
  201233. const int windowStyleFlags)
  201234. : ComponentPeer (component, windowStyleFlags),
  201235. dontRepaint (false),
  201236. fullScreen (false),
  201237. isDragging (false),
  201238. isMouseOver (false),
  201239. hasCreatedCaret (false),
  201240. currentWindowIcon (0),
  201241. taskBarIcon (0),
  201242. dropTarget (0)
  201243. {
  201244. callFunctionIfNotLocked (&createWindowCallback, (void*) this);
  201245. setTitle (component->getName());
  201246. if ((windowStyleFlags & windowHasDropShadow) != 0
  201247. && Desktop::canUseSemiTransparentWindows())
  201248. {
  201249. shadower = component->getLookAndFeel().createDropShadowerForComponent (component);
  201250. if (shadower != 0)
  201251. shadower->setOwner (component);
  201252. }
  201253. else
  201254. {
  201255. shadower = 0;
  201256. }
  201257. }
  201258. ~Win32ComponentPeer()
  201259. {
  201260. setTaskBarIcon (0);
  201261. deleteAndZero (shadower);
  201262. // do this before the next bit to avoid messages arriving for this window
  201263. // before it's destroyed
  201264. SetWindowLongPtr (hwnd, GWLP_USERDATA, 0);
  201265. callFunctionIfNotLocked (&destroyWindowCallback, (void*) hwnd);
  201266. if (currentWindowIcon != 0)
  201267. DestroyIcon (currentWindowIcon);
  201268. if (dropTarget != 0)
  201269. {
  201270. dropTarget->Release();
  201271. dropTarget = 0;
  201272. }
  201273. }
  201274. void* getNativeHandle() const
  201275. {
  201276. return (void*) hwnd;
  201277. }
  201278. void setVisible (bool shouldBeVisible)
  201279. {
  201280. ShowWindow (hwnd, shouldBeVisible ? SW_SHOWNA : SW_HIDE);
  201281. if (shouldBeVisible)
  201282. InvalidateRect (hwnd, 0, 0);
  201283. else
  201284. lastPaintTime = 0;
  201285. }
  201286. void setTitle (const String& title)
  201287. {
  201288. SetWindowText (hwnd, title);
  201289. }
  201290. void setPosition (int x, int y)
  201291. {
  201292. offsetWithinParent (x, y);
  201293. SetWindowPos (hwnd, 0,
  201294. x - windowBorder.getLeft(),
  201295. y - windowBorder.getTop(),
  201296. 0, 0,
  201297. SWP_NOACTIVATE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  201298. }
  201299. void repaintNowIfTransparent()
  201300. {
  201301. if (isTransparent() && lastPaintTime > 0 && Time::getMillisecondCounter() > lastPaintTime + 30)
  201302. handlePaintMessage();
  201303. }
  201304. void updateBorderSize()
  201305. {
  201306. WINDOWINFO info;
  201307. info.cbSize = sizeof (info);
  201308. if (GetWindowInfo (hwnd, &info))
  201309. {
  201310. windowBorder = BorderSize (info.rcClient.top - info.rcWindow.top,
  201311. info.rcClient.left - info.rcWindow.left,
  201312. info.rcWindow.bottom - info.rcClient.bottom,
  201313. info.rcWindow.right - info.rcClient.right);
  201314. }
  201315. }
  201316. void setSize (int w, int h)
  201317. {
  201318. SetWindowPos (hwnd, 0, 0, 0,
  201319. w + windowBorder.getLeftAndRight(),
  201320. h + windowBorder.getTopAndBottom(),
  201321. SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  201322. updateBorderSize();
  201323. repaintNowIfTransparent();
  201324. }
  201325. void setBounds (int x, int y, int w, int h, const bool isNowFullScreen)
  201326. {
  201327. fullScreen = isNowFullScreen;
  201328. offsetWithinParent (x, y);
  201329. SetWindowPos (hwnd, 0,
  201330. x - windowBorder.getLeft(),
  201331. y - windowBorder.getTop(),
  201332. w + windowBorder.getLeftAndRight(),
  201333. h + windowBorder.getTopAndBottom(),
  201334. SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  201335. updateBorderSize();
  201336. repaintNowIfTransparent();
  201337. }
  201338. void getBounds (int& x, int& y, int& w, int& h) const
  201339. {
  201340. RECT r;
  201341. GetWindowRect (hwnd, &r);
  201342. x = r.left;
  201343. y = r.top;
  201344. w = r.right - x;
  201345. h = r.bottom - y;
  201346. HWND parentH = GetParent (hwnd);
  201347. if (parentH != 0)
  201348. {
  201349. GetWindowRect (parentH, &r);
  201350. x -= r.left;
  201351. y -= r.top;
  201352. }
  201353. x += windowBorder.getLeft();
  201354. y += windowBorder.getTop();
  201355. w -= windowBorder.getLeftAndRight();
  201356. h -= windowBorder.getTopAndBottom();
  201357. }
  201358. int getScreenX() const
  201359. {
  201360. RECT r;
  201361. GetWindowRect (hwnd, &r);
  201362. return r.left + windowBorder.getLeft();
  201363. }
  201364. int getScreenY() const
  201365. {
  201366. RECT r;
  201367. GetWindowRect (hwnd, &r);
  201368. return r.top + windowBorder.getTop();
  201369. }
  201370. void relativePositionToGlobal (int& x, int& y)
  201371. {
  201372. RECT r;
  201373. GetWindowRect (hwnd, &r);
  201374. x += r.left + windowBorder.getLeft();
  201375. y += r.top + windowBorder.getTop();
  201376. }
  201377. void globalPositionToRelative (int& x, int& y)
  201378. {
  201379. RECT r;
  201380. GetWindowRect (hwnd, &r);
  201381. x -= r.left + windowBorder.getLeft();
  201382. y -= r.top + windowBorder.getTop();
  201383. }
  201384. void setMinimised (bool shouldBeMinimised)
  201385. {
  201386. if (shouldBeMinimised != isMinimised())
  201387. ShowWindow (hwnd, shouldBeMinimised ? SW_MINIMIZE : SW_SHOWNORMAL);
  201388. }
  201389. bool isMinimised() const
  201390. {
  201391. WINDOWPLACEMENT wp;
  201392. wp.length = sizeof (WINDOWPLACEMENT);
  201393. GetWindowPlacement (hwnd, &wp);
  201394. return wp.showCmd == SW_SHOWMINIMIZED;
  201395. }
  201396. void setFullScreen (bool shouldBeFullScreen)
  201397. {
  201398. setMinimised (false);
  201399. if (fullScreen != shouldBeFullScreen)
  201400. {
  201401. fullScreen = shouldBeFullScreen;
  201402. const ComponentDeletionWatcher deletionChecker (component);
  201403. if (! fullScreen)
  201404. {
  201405. const Rectangle boundsCopy (lastNonFullscreenBounds);
  201406. if (hasTitleBar())
  201407. ShowWindow (hwnd, SW_SHOWNORMAL);
  201408. if (! boundsCopy.isEmpty())
  201409. {
  201410. setBounds (boundsCopy.getX(),
  201411. boundsCopy.getY(),
  201412. boundsCopy.getWidth(),
  201413. boundsCopy.getHeight(),
  201414. false);
  201415. }
  201416. }
  201417. else
  201418. {
  201419. if (hasTitleBar())
  201420. ShowWindow (hwnd, SW_SHOWMAXIMIZED);
  201421. else
  201422. SendMessageW (hwnd, WM_SETTINGCHANGE, 0, 0);
  201423. }
  201424. if (! deletionChecker.hasBeenDeleted())
  201425. handleMovedOrResized();
  201426. }
  201427. }
  201428. bool isFullScreen() const
  201429. {
  201430. if (! hasTitleBar())
  201431. return fullScreen;
  201432. WINDOWPLACEMENT wp;
  201433. wp.length = sizeof (wp);
  201434. GetWindowPlacement (hwnd, &wp);
  201435. return wp.showCmd == SW_SHOWMAXIMIZED;
  201436. }
  201437. bool contains (int x, int y, bool trueIfInAChildWindow) const
  201438. {
  201439. RECT r;
  201440. GetWindowRect (hwnd, &r);
  201441. POINT p;
  201442. p.x = x + r.left + windowBorder.getLeft();
  201443. p.y = y + r.top + windowBorder.getTop();
  201444. HWND w = WindowFromPoint (p);
  201445. return w == hwnd || (trueIfInAChildWindow && (IsChild (hwnd, w) != 0));
  201446. }
  201447. const BorderSize getFrameSize() const
  201448. {
  201449. return windowBorder;
  201450. }
  201451. bool setAlwaysOnTop (bool alwaysOnTop)
  201452. {
  201453. const bool oldDeactivate = shouldDeactivateTitleBar;
  201454. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  201455. SetWindowPos (hwnd, alwaysOnTop ? HWND_TOPMOST : HWND_NOTOPMOST,
  201456. 0, 0, 0, 0,
  201457. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  201458. shouldDeactivateTitleBar = oldDeactivate;
  201459. if (shadower != 0)
  201460. shadower->componentBroughtToFront (*component);
  201461. return true;
  201462. }
  201463. void toFront (bool makeActive)
  201464. {
  201465. setMinimised (false);
  201466. const bool oldDeactivate = shouldDeactivateTitleBar;
  201467. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  201468. callFunctionIfNotLocked (makeActive ? &toFrontCallback1
  201469. : &toFrontCallback2,
  201470. (void*) hwnd);
  201471. shouldDeactivateTitleBar = oldDeactivate;
  201472. if (! makeActive)
  201473. {
  201474. // in this case a broughttofront call won't have occured, so do it now..
  201475. handleBroughtToFront();
  201476. }
  201477. }
  201478. void toBehind (ComponentPeer* other)
  201479. {
  201480. Win32ComponentPeer* const otherPeer = dynamic_cast <Win32ComponentPeer*> (other);
  201481. jassert (otherPeer != 0); // wrong type of window?
  201482. if (otherPeer != 0)
  201483. {
  201484. setMinimised (false);
  201485. // must be careful not to try to put a topmost window behind a normal one, or win32
  201486. // promotes the normal one to be topmost!
  201487. if (getComponent()->isAlwaysOnTop() == otherPeer->getComponent()->isAlwaysOnTop())
  201488. SetWindowPos (hwnd, otherPeer->hwnd, 0, 0, 0, 0,
  201489. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  201490. else if (otherPeer->getComponent()->isAlwaysOnTop())
  201491. SetWindowPos (hwnd, HWND_TOP, 0, 0, 0, 0,
  201492. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  201493. }
  201494. }
  201495. bool isFocused() const
  201496. {
  201497. return callFunctionIfNotLocked (&getFocusCallback, 0) == (void*) hwnd;
  201498. }
  201499. void grabFocus()
  201500. {
  201501. const bool oldDeactivate = shouldDeactivateTitleBar;
  201502. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  201503. callFunctionIfNotLocked (&setFocusCallback, (void*) hwnd);
  201504. shouldDeactivateTitleBar = oldDeactivate;
  201505. }
  201506. void textInputRequired (int /*x*/, int /*y*/)
  201507. {
  201508. if (! hasCreatedCaret)
  201509. {
  201510. hasCreatedCaret = true;
  201511. CreateCaret (hwnd, (HBITMAP) 1, 0, 0);
  201512. }
  201513. ShowCaret (hwnd);
  201514. SetCaretPos (0, 0);
  201515. }
  201516. void repaint (int x, int y, int w, int h)
  201517. {
  201518. const RECT r = { x, y, x + w, y + h };
  201519. InvalidateRect (hwnd, &r, FALSE);
  201520. }
  201521. void performAnyPendingRepaintsNow()
  201522. {
  201523. MSG m;
  201524. if (component->isVisible() && PeekMessage (&m, hwnd, WM_PAINT, WM_PAINT, PM_REMOVE))
  201525. DispatchMessage (&m);
  201526. }
  201527. static Win32ComponentPeer* getOwnerOfWindow (HWND h) throw()
  201528. {
  201529. if (h != 0 && GetWindowLongPtr (h, GWLP_USERDATA) == improbableWindowNumber)
  201530. return (Win32ComponentPeer*) (pointer_sized_int) GetWindowLongPtr (h, 8);
  201531. return 0;
  201532. }
  201533. void setTaskBarIcon (const Image* const image)
  201534. {
  201535. if (image != 0)
  201536. {
  201537. HICON hicon = createHICONFromImage (*image, TRUE, 0, 0);
  201538. if (taskBarIcon == 0)
  201539. {
  201540. taskBarIcon = new NOTIFYICONDATA();
  201541. taskBarIcon->cbSize = sizeof (NOTIFYICONDATA);
  201542. taskBarIcon->hWnd = (HWND) hwnd;
  201543. taskBarIcon->uID = (int) (pointer_sized_int) hwnd;
  201544. taskBarIcon->uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP;
  201545. taskBarIcon->uCallbackMessage = WM_TRAYNOTIFY;
  201546. taskBarIcon->hIcon = hicon;
  201547. taskBarIcon->szTip[0] = 0;
  201548. Shell_NotifyIcon (NIM_ADD, taskBarIcon);
  201549. }
  201550. else
  201551. {
  201552. HICON oldIcon = taskBarIcon->hIcon;
  201553. taskBarIcon->hIcon = hicon;
  201554. taskBarIcon->uFlags = NIF_ICON;
  201555. Shell_NotifyIcon (NIM_MODIFY, taskBarIcon);
  201556. DestroyIcon (oldIcon);
  201557. }
  201558. DestroyIcon (hicon);
  201559. }
  201560. else if (taskBarIcon != 0)
  201561. {
  201562. taskBarIcon->uFlags = 0;
  201563. Shell_NotifyIcon (NIM_DELETE, taskBarIcon);
  201564. DestroyIcon (taskBarIcon->hIcon);
  201565. deleteAndZero (taskBarIcon);
  201566. }
  201567. }
  201568. void setTaskBarIconToolTip (const String& toolTip) const
  201569. {
  201570. if (taskBarIcon != 0)
  201571. {
  201572. taskBarIcon->uFlags = NIF_TIP;
  201573. toolTip.copyToBuffer (taskBarIcon->szTip, sizeof (taskBarIcon->szTip) - 1);
  201574. Shell_NotifyIcon (NIM_MODIFY, taskBarIcon);
  201575. }
  201576. }
  201577. bool isInside (HWND h) const
  201578. {
  201579. return GetAncestor (hwnd, GA_ROOT) == h;
  201580. }
  201581. juce_UseDebuggingNewOperator
  201582. bool dontRepaint;
  201583. private:
  201584. HWND hwnd;
  201585. DropShadower* shadower;
  201586. bool fullScreen, isDragging, isMouseOver, hasCreatedCaret;
  201587. BorderSize windowBorder;
  201588. HICON currentWindowIcon;
  201589. NOTIFYICONDATA* taskBarIcon;
  201590. IDropTarget* dropTarget;
  201591. class TemporaryImage : public Timer
  201592. {
  201593. public:
  201594. TemporaryImage()
  201595. : image (0)
  201596. {
  201597. }
  201598. ~TemporaryImage()
  201599. {
  201600. delete image;
  201601. }
  201602. WindowsBitmapImage* getImage (const bool transparent, const int w, const int h) throw()
  201603. {
  201604. const Image::PixelFormat format = transparent ? Image::ARGB : Image::RGB;
  201605. if (image == 0 || image->getWidth() < w || image->getHeight() < h || image->getFormat() != format)
  201606. {
  201607. delete image;
  201608. image = new WindowsBitmapImage (format, (w + 31) & ~31, (h + 31) & ~31, false);
  201609. }
  201610. startTimer (3000);
  201611. return image;
  201612. }
  201613. void timerCallback()
  201614. {
  201615. stopTimer();
  201616. deleteAndZero (image);
  201617. }
  201618. private:
  201619. WindowsBitmapImage* image;
  201620. TemporaryImage (const TemporaryImage&);
  201621. const TemporaryImage& operator= (const TemporaryImage&);
  201622. };
  201623. TemporaryImage offscreenImageGenerator;
  201624. class WindowClassHolder : public DeletedAtShutdown
  201625. {
  201626. public:
  201627. WindowClassHolder()
  201628. : windowClassName ("JUCE_")
  201629. {
  201630. // this name has to be different for each app/dll instance because otherwise
  201631. // poor old Win32 can get a bit confused (even despite it not being a process-global
  201632. // window class).
  201633. windowClassName << (int) (Time::currentTimeMillis() & 0x7fffffff);
  201634. HINSTANCE moduleHandle = (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle();
  201635. TCHAR moduleFile [1024];
  201636. moduleFile[0] = 0;
  201637. GetModuleFileName (moduleHandle, moduleFile, 1024);
  201638. WORD iconNum = 0;
  201639. WNDCLASSEX wcex;
  201640. wcex.cbSize = sizeof (wcex);
  201641. wcex.style = CS_OWNDC;
  201642. wcex.lpfnWndProc = (WNDPROC) windowProc;
  201643. wcex.lpszClassName = windowClassName;
  201644. wcex.cbClsExtra = 0;
  201645. wcex.cbWndExtra = 32;
  201646. wcex.hInstance = moduleHandle;
  201647. wcex.hIcon = ExtractAssociatedIcon (moduleHandle, moduleFile, &iconNum);
  201648. iconNum = 1;
  201649. wcex.hIconSm = ExtractAssociatedIcon (moduleHandle, moduleFile, &iconNum);
  201650. wcex.hCursor = 0;
  201651. wcex.hbrBackground = 0;
  201652. wcex.lpszMenuName = 0;
  201653. RegisterClassEx (&wcex);
  201654. }
  201655. ~WindowClassHolder()
  201656. {
  201657. if (ComponentPeer::getNumPeers() == 0)
  201658. UnregisterClass (windowClassName, (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle());
  201659. clearSingletonInstance();
  201660. }
  201661. String windowClassName;
  201662. juce_DeclareSingleton_SingleThreaded_Minimal (WindowClassHolder);
  201663. };
  201664. static void* createWindowCallback (void* userData)
  201665. {
  201666. ((Win32ComponentPeer*) userData)->createWindow();
  201667. return 0;
  201668. }
  201669. void createWindow()
  201670. {
  201671. DWORD exstyle = WS_EX_ACCEPTFILES;
  201672. DWORD type = WS_CLIPSIBLINGS | WS_CLIPCHILDREN;
  201673. if (hasTitleBar())
  201674. {
  201675. type |= WS_OVERLAPPED;
  201676. exstyle |= WS_EX_APPWINDOW;
  201677. if ((styleFlags & windowHasCloseButton) != 0)
  201678. {
  201679. type |= WS_SYSMENU;
  201680. }
  201681. else
  201682. {
  201683. // annoyingly, windows won't let you have a min/max button without a close button
  201684. jassert ((styleFlags & (windowHasMinimiseButton | windowHasMaximiseButton)) == 0);
  201685. }
  201686. if ((styleFlags & windowIsResizable) != 0)
  201687. type |= WS_THICKFRAME;
  201688. }
  201689. else
  201690. {
  201691. type |= WS_POPUP | WS_SYSMENU;
  201692. if ((styleFlags & windowAppearsOnTaskbar) == 0)
  201693. exstyle |= WS_EX_TOOLWINDOW;
  201694. else
  201695. exstyle |= WS_EX_APPWINDOW;
  201696. }
  201697. if ((styleFlags & windowHasMinimiseButton) != 0)
  201698. type |= WS_MINIMIZEBOX;
  201699. if ((styleFlags & windowHasMaximiseButton) != 0)
  201700. type |= WS_MAXIMIZEBOX;
  201701. if ((styleFlags & windowIgnoresMouseClicks) != 0)
  201702. exstyle |= WS_EX_TRANSPARENT;
  201703. if ((styleFlags & windowIsSemiTransparent) != 0
  201704. && Desktop::canUseSemiTransparentWindows())
  201705. exstyle |= WS_EX_LAYERED;
  201706. hwnd = CreateWindowEx (exstyle, WindowClassHolder::getInstance()->windowClassName, L"", type, 0, 0, 0, 0, 0, 0, 0, 0);
  201707. if (hwnd != 0)
  201708. {
  201709. SetWindowLongPtr (hwnd, 0, 0);
  201710. SetWindowLongPtr (hwnd, 8, (LONG_PTR) this);
  201711. SetWindowLongPtr (hwnd, GWLP_USERDATA, improbableWindowNumber);
  201712. if (dropTarget == 0)
  201713. dropTarget = new JuceDropTarget (this);
  201714. RegisterDragDrop (hwnd, dropTarget);
  201715. updateBorderSize();
  201716. // Calling this function here is (for some reason) necessary to make Windows
  201717. // correctly enable the menu items that we specify in the wm_initmenu message.
  201718. GetSystemMenu (hwnd, false);
  201719. }
  201720. else
  201721. {
  201722. jassertfalse
  201723. }
  201724. }
  201725. static void* destroyWindowCallback (void* handle)
  201726. {
  201727. RevokeDragDrop ((HWND) handle);
  201728. DestroyWindow ((HWND) handle);
  201729. return 0;
  201730. }
  201731. static void* toFrontCallback1 (void* h)
  201732. {
  201733. SetForegroundWindow ((HWND) h);
  201734. return 0;
  201735. }
  201736. static void* toFrontCallback2 (void* h)
  201737. {
  201738. SetWindowPos ((HWND) h, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  201739. return 0;
  201740. }
  201741. static void* setFocusCallback (void* h)
  201742. {
  201743. SetFocus ((HWND) h);
  201744. return 0;
  201745. }
  201746. static void* getFocusCallback (void*)
  201747. {
  201748. return (void*) GetFocus();
  201749. }
  201750. void offsetWithinParent (int& x, int& y) const
  201751. {
  201752. if (isTransparent())
  201753. {
  201754. HWND parentHwnd = GetParent (hwnd);
  201755. if (parentHwnd != 0)
  201756. {
  201757. RECT parentRect;
  201758. GetWindowRect (parentHwnd, &parentRect);
  201759. x += parentRect.left;
  201760. y += parentRect.top;
  201761. }
  201762. }
  201763. }
  201764. bool isTransparent() const
  201765. {
  201766. return (GetWindowLong (hwnd, GWL_EXSTYLE) & WS_EX_LAYERED) != 0;
  201767. }
  201768. inline bool hasTitleBar() const throw() { return (styleFlags & windowHasTitleBar) != 0; }
  201769. void setIcon (const Image& newIcon)
  201770. {
  201771. HICON hicon = createHICONFromImage (newIcon, TRUE, 0, 0);
  201772. if (hicon != 0)
  201773. {
  201774. SendMessage (hwnd, WM_SETICON, ICON_BIG, (LPARAM) hicon);
  201775. SendMessage (hwnd, WM_SETICON, ICON_SMALL, (LPARAM) hicon);
  201776. if (currentWindowIcon != 0)
  201777. DestroyIcon (currentWindowIcon);
  201778. currentWindowIcon = hicon;
  201779. }
  201780. }
  201781. void handlePaintMessage()
  201782. {
  201783. #if DEBUG_REPAINT_TIMES
  201784. const double paintStart = Time::getMillisecondCounterHiRes();
  201785. #endif
  201786. HRGN rgn = CreateRectRgn (0, 0, 0, 0);
  201787. const int regionType = GetUpdateRgn (hwnd, rgn, false);
  201788. PAINTSTRUCT paintStruct;
  201789. HDC dc = BeginPaint (hwnd, &paintStruct); // Note this can immediately generate a WM_NCPAINT
  201790. // message and become re-entrant, but that's OK
  201791. // if something in a paint handler calls, e.g. a message box, this can become reentrant and
  201792. // corrupt the image it's using to paint into, so do a check here.
  201793. static bool reentrant = false;
  201794. if (reentrant)
  201795. {
  201796. DeleteObject (rgn);
  201797. EndPaint (hwnd, &paintStruct);
  201798. return;
  201799. }
  201800. reentrant = true;
  201801. // this is the rectangle to update..
  201802. int x = paintStruct.rcPaint.left;
  201803. int y = paintStruct.rcPaint.top;
  201804. int w = paintStruct.rcPaint.right - x;
  201805. int h = paintStruct.rcPaint.bottom - y;
  201806. const bool transparent = isTransparent();
  201807. if (transparent)
  201808. {
  201809. // it's not possible to have a transparent window with a title bar at the moment!
  201810. jassert (! hasTitleBar());
  201811. RECT r;
  201812. GetWindowRect (hwnd, &r);
  201813. x = y = 0;
  201814. w = r.right - r.left;
  201815. h = r.bottom - r.top;
  201816. }
  201817. if (w > 0 && h > 0)
  201818. {
  201819. clearMaskedRegion();
  201820. WindowsBitmapImage* const offscreenImage = offscreenImageGenerator.getImage (transparent, w, h);
  201821. LowLevelGraphicsSoftwareRenderer context (*offscreenImage);
  201822. RectangleList* const contextClip = context.getRawClipRegion();
  201823. contextClip->clear();
  201824. context.setOrigin (-x, -y);
  201825. bool needToPaintAll = true;
  201826. if (regionType == COMPLEXREGION && ! transparent)
  201827. {
  201828. HRGN clipRgn = CreateRectRgnIndirect (&paintStruct.rcPaint);
  201829. CombineRgn (rgn, rgn, clipRgn, RGN_AND);
  201830. DeleteObject (clipRgn);
  201831. char rgnData [8192];
  201832. const DWORD res = GetRegionData (rgn, sizeof (rgnData), (RGNDATA*) rgnData);
  201833. if (res > 0 && res <= sizeof (rgnData))
  201834. {
  201835. const RGNDATAHEADER* const hdr = &(((const RGNDATA*) rgnData)->rdh);
  201836. if (hdr->iType == RDH_RECTANGLES
  201837. && hdr->rcBound.right - hdr->rcBound.left >= w
  201838. && hdr->rcBound.bottom - hdr->rcBound.top >= h)
  201839. {
  201840. needToPaintAll = false;
  201841. const RECT* rects = (const RECT*) (rgnData + sizeof (RGNDATAHEADER));
  201842. int num = ((RGNDATA*) rgnData)->rdh.nCount;
  201843. while (--num >= 0)
  201844. {
  201845. // (need to move this one pixel to the left because of a win32 bug)
  201846. const int cx = jmax (x, rects->left - 1);
  201847. const int cy = rects->top;
  201848. const int cw = rects->right - cx;
  201849. const int ch = rects->bottom - rects->top;
  201850. if (cx + cw - x <= w && cy + ch - y <= h)
  201851. {
  201852. contextClip->addWithoutMerging (Rectangle (cx - x, cy - y, cw, ch));
  201853. }
  201854. else
  201855. {
  201856. needToPaintAll = true;
  201857. break;
  201858. }
  201859. ++rects;
  201860. }
  201861. }
  201862. }
  201863. }
  201864. if (needToPaintAll)
  201865. {
  201866. contextClip->clear();
  201867. contextClip->addWithoutMerging (Rectangle (0, 0, w, h));
  201868. }
  201869. if (transparent)
  201870. {
  201871. RectangleList::Iterator i (*contextClip);
  201872. while (i.next())
  201873. {
  201874. const Rectangle& r = *i.getRectangle();
  201875. offscreenImage->clear (r.getX(), r.getY(), r.getWidth(), r.getHeight());
  201876. }
  201877. }
  201878. // if the component's not opaque, this won't draw properly unless the platform can support this
  201879. jassert (Desktop::canUseSemiTransparentWindows() || component->isOpaque());
  201880. updateCurrentModifiers();
  201881. handlePaint (context);
  201882. if (! dontRepaint)
  201883. offscreenImage->blitToWindow (hwnd, dc, transparent, x, y, maskedRegion);
  201884. }
  201885. DeleteObject (rgn);
  201886. EndPaint (hwnd, &paintStruct);
  201887. reentrant = false;
  201888. #ifndef JUCE_GCC //xxx should add this fn for gcc..
  201889. _fpreset(); // because some graphics cards can unmask FP exceptions
  201890. #endif
  201891. lastPaintTime = Time::getMillisecondCounter();
  201892. #if DEBUG_REPAINT_TIMES
  201893. const double elapsed = Time::getMillisecondCounterHiRes() - paintStart;
  201894. Logger::outputDebugString (T("repaint time: ") + String (elapsed, 2));
  201895. #endif
  201896. }
  201897. void doMouseMove (const int x, const int y)
  201898. {
  201899. static uint32 lastMouseTime = 0;
  201900. // this can be set to throttle the mouse-messages to less than a
  201901. // certain number per second, as things can get unresponsive
  201902. // if each drag or move callback has to do a lot of work.
  201903. const int maxMouseMovesPerSecond = 60;
  201904. const int64 mouseEventTime = getMouseEventTime();
  201905. if (! isMouseOver)
  201906. {
  201907. isMouseOver = true;
  201908. TRACKMOUSEEVENT tme;
  201909. tme.cbSize = sizeof (tme);
  201910. tme.dwFlags = TME_LEAVE;
  201911. tme.hwndTrack = hwnd;
  201912. tme.dwHoverTime = 0;
  201913. if (! TrackMouseEvent (&tme))
  201914. {
  201915. jassertfalse;
  201916. }
  201917. updateKeyModifiers();
  201918. handleMouseEnter (x, y, mouseEventTime);
  201919. }
  201920. else if (! isDragging)
  201921. {
  201922. if (((unsigned int) x) < (unsigned int) component->getWidth()
  201923. && ((unsigned int) y) < (unsigned int) component->getHeight())
  201924. {
  201925. RECT r;
  201926. GetWindowRect (hwnd, &r);
  201927. POINT p;
  201928. p.x = x + r.left + windowBorder.getLeft();
  201929. p.y = y + r.top + windowBorder.getTop();
  201930. if (WindowFromPoint (p) == hwnd)
  201931. {
  201932. const uint32 now = Time::getMillisecondCounter();
  201933. if (now > lastMouseTime + 1000 / maxMouseMovesPerSecond)
  201934. {
  201935. lastMouseTime = now;
  201936. handleMouseMove (x, y, mouseEventTime);
  201937. }
  201938. }
  201939. }
  201940. }
  201941. else
  201942. {
  201943. const uint32 now = Time::getMillisecondCounter();
  201944. if (now > lastMouseTime + 1000 / maxMouseMovesPerSecond)
  201945. {
  201946. lastMouseTime = now;
  201947. handleMouseDrag (x, y, mouseEventTime);
  201948. }
  201949. }
  201950. }
  201951. void doMouseDown (const int x, const int y, const WPARAM wParam)
  201952. {
  201953. if (GetCapture() != hwnd)
  201954. SetCapture (hwnd);
  201955. doMouseMove (x, y);
  201956. currentModifiers &= ~ModifierKeys::allMouseButtonModifiers;
  201957. if ((wParam & MK_LBUTTON) != 0)
  201958. currentModifiers |= ModifierKeys::leftButtonModifier;
  201959. if ((wParam & MK_RBUTTON) != 0)
  201960. currentModifiers |= ModifierKeys::rightButtonModifier;
  201961. if ((wParam & MK_MBUTTON) != 0)
  201962. currentModifiers |= ModifierKeys::middleButtonModifier;
  201963. updateKeyModifiers();
  201964. isDragging = true;
  201965. handleMouseDown (x, y, getMouseEventTime());
  201966. }
  201967. void doMouseUp (const int x, const int y, const WPARAM wParam)
  201968. {
  201969. int numButtons = 0;
  201970. if ((wParam & MK_LBUTTON) != 0)
  201971. ++numButtons;
  201972. if ((wParam & MK_RBUTTON) != 0)
  201973. ++numButtons;
  201974. if ((wParam & MK_MBUTTON) != 0)
  201975. ++numButtons;
  201976. const int oldModifiers = currentModifiers;
  201977. // update the currentmodifiers only after the callback, so the callback
  201978. // knows which button was released.
  201979. currentModifiers &= ~ModifierKeys::allMouseButtonModifiers;
  201980. if ((wParam & MK_LBUTTON) != 0)
  201981. currentModifiers |= ModifierKeys::leftButtonModifier;
  201982. if ((wParam & MK_RBUTTON) != 0)
  201983. currentModifiers |= ModifierKeys::rightButtonModifier;
  201984. if ((wParam & MK_MBUTTON) != 0)
  201985. currentModifiers |= ModifierKeys::middleButtonModifier;
  201986. updateKeyModifiers();
  201987. isDragging = false;
  201988. // release the mouse capture if the user's not still got a button down
  201989. if (numButtons == 0 && hwnd == GetCapture())
  201990. ReleaseCapture();
  201991. handleMouseUp (oldModifiers, x, y, getMouseEventTime());
  201992. }
  201993. void doCaptureChanged()
  201994. {
  201995. if (isDragging)
  201996. {
  201997. RECT wr;
  201998. GetWindowRect (hwnd, &wr);
  201999. const DWORD mp = GetMessagePos();
  202000. doMouseUp (GET_X_LPARAM (mp) - wr.left - windowBorder.getLeft(),
  202001. GET_Y_LPARAM (mp) - wr.top - windowBorder.getTop(),
  202002. (WPARAM) getMouseEventTime());
  202003. }
  202004. }
  202005. void doMouseExit()
  202006. {
  202007. if (isMouseOver)
  202008. {
  202009. isMouseOver = false;
  202010. RECT wr;
  202011. GetWindowRect (hwnd, &wr);
  202012. const DWORD mp = GetMessagePos();
  202013. handleMouseExit (GET_X_LPARAM (mp) - wr.left - windowBorder.getLeft(),
  202014. GET_Y_LPARAM (mp) - wr.top - windowBorder.getTop(),
  202015. getMouseEventTime());
  202016. }
  202017. }
  202018. void doMouseWheel (const WPARAM wParam, const bool isVertical)
  202019. {
  202020. updateKeyModifiers();
  202021. const int amount = jlimit (-1000, 1000, (int) (0.75f * (short) HIWORD (wParam)));
  202022. handleMouseWheel (isVertical ? 0 : amount,
  202023. isVertical ? amount : 0,
  202024. getMouseEventTime());
  202025. }
  202026. void sendModifierKeyChangeIfNeeded()
  202027. {
  202028. if (modifiersAtLastCallback != currentModifiers)
  202029. {
  202030. modifiersAtLastCallback = currentModifiers;
  202031. handleModifierKeysChange();
  202032. }
  202033. }
  202034. bool doKeyUp (const WPARAM key)
  202035. {
  202036. updateKeyModifiers();
  202037. switch (key)
  202038. {
  202039. case VK_SHIFT:
  202040. case VK_CONTROL:
  202041. case VK_MENU:
  202042. case VK_CAPITAL:
  202043. case VK_LWIN:
  202044. case VK_RWIN:
  202045. case VK_APPS:
  202046. case VK_NUMLOCK:
  202047. case VK_SCROLL:
  202048. case VK_LSHIFT:
  202049. case VK_RSHIFT:
  202050. case VK_LCONTROL:
  202051. case VK_LMENU:
  202052. case VK_RCONTROL:
  202053. case VK_RMENU:
  202054. sendModifierKeyChangeIfNeeded();
  202055. }
  202056. return handleKeyUpOrDown (false)
  202057. || Component::getCurrentlyModalComponent() != 0;
  202058. }
  202059. bool doKeyDown (const WPARAM key)
  202060. {
  202061. updateKeyModifiers();
  202062. bool used = false;
  202063. switch (key)
  202064. {
  202065. case VK_SHIFT:
  202066. case VK_LSHIFT:
  202067. case VK_RSHIFT:
  202068. case VK_CONTROL:
  202069. case VK_LCONTROL:
  202070. case VK_RCONTROL:
  202071. case VK_MENU:
  202072. case VK_LMENU:
  202073. case VK_RMENU:
  202074. case VK_LWIN:
  202075. case VK_RWIN:
  202076. case VK_CAPITAL:
  202077. case VK_NUMLOCK:
  202078. case VK_SCROLL:
  202079. case VK_APPS:
  202080. sendModifierKeyChangeIfNeeded();
  202081. break;
  202082. case VK_LEFT:
  202083. case VK_RIGHT:
  202084. case VK_UP:
  202085. case VK_DOWN:
  202086. case VK_PRIOR:
  202087. case VK_NEXT:
  202088. case VK_HOME:
  202089. case VK_END:
  202090. case VK_DELETE:
  202091. case VK_INSERT:
  202092. case VK_F1:
  202093. case VK_F2:
  202094. case VK_F3:
  202095. case VK_F4:
  202096. case VK_F5:
  202097. case VK_F6:
  202098. case VK_F7:
  202099. case VK_F8:
  202100. case VK_F9:
  202101. case VK_F10:
  202102. case VK_F11:
  202103. case VK_F12:
  202104. case VK_F13:
  202105. case VK_F14:
  202106. case VK_F15:
  202107. case VK_F16:
  202108. used = handleKeyUpOrDown (true);
  202109. used = handleKeyPress (extendedKeyModifier | (int) key, 0) || used;
  202110. break;
  202111. case VK_ADD:
  202112. case VK_SUBTRACT:
  202113. case VK_MULTIPLY:
  202114. case VK_DIVIDE:
  202115. case VK_SEPARATOR:
  202116. case VK_DECIMAL:
  202117. used = handleKeyUpOrDown (true);
  202118. break;
  202119. default:
  202120. used = handleKeyUpOrDown (true);
  202121. {
  202122. MSG msg;
  202123. if (! PeekMessage (&msg, hwnd, WM_CHAR, WM_DEADCHAR, PM_NOREMOVE))
  202124. {
  202125. // if there isn't a WM_CHAR or WM_DEADCHAR message pending, we need to
  202126. // manually generate the key-press event that matches this key-down.
  202127. const UINT keyChar = MapVirtualKey (key, 2);
  202128. used = handleKeyPress ((int) LOWORD (keyChar), 0) || used;
  202129. }
  202130. }
  202131. break;
  202132. }
  202133. if (Component::getCurrentlyModalComponent() != 0)
  202134. used = true;
  202135. return used;
  202136. }
  202137. bool doKeyChar (int key, const LPARAM flags)
  202138. {
  202139. updateKeyModifiers();
  202140. juce_wchar textChar = (juce_wchar) key;
  202141. const int virtualScanCode = (flags >> 16) & 0xff;
  202142. if (key >= '0' && key <= '9')
  202143. {
  202144. switch (virtualScanCode) // check for a numeric keypad scan-code
  202145. {
  202146. case 0x52:
  202147. case 0x4f:
  202148. case 0x50:
  202149. case 0x51:
  202150. case 0x4b:
  202151. case 0x4c:
  202152. case 0x4d:
  202153. case 0x47:
  202154. case 0x48:
  202155. case 0x49:
  202156. key = (key - '0') + KeyPress::numberPad0;
  202157. break;
  202158. default:
  202159. break;
  202160. }
  202161. }
  202162. else
  202163. {
  202164. // convert the scan code to an unmodified character code..
  202165. const UINT virtualKey = MapVirtualKey (virtualScanCode, 1);
  202166. UINT keyChar = MapVirtualKey (virtualKey, 2);
  202167. keyChar = LOWORD (keyChar);
  202168. if (keyChar != 0)
  202169. key = (int) keyChar;
  202170. // avoid sending junk text characters for some control-key combinations
  202171. if (textChar < ' ' && (currentModifiers & (ModifierKeys::ctrlModifier | ModifierKeys::altModifier)) != 0)
  202172. textChar = 0;
  202173. }
  202174. return handleKeyPress (key, textChar);
  202175. }
  202176. bool doAppCommand (const LPARAM lParam)
  202177. {
  202178. int key = 0;
  202179. switch (GET_APPCOMMAND_LPARAM (lParam))
  202180. {
  202181. case APPCOMMAND_MEDIA_PLAY_PAUSE:
  202182. key = KeyPress::playKey;
  202183. break;
  202184. case APPCOMMAND_MEDIA_STOP:
  202185. key = KeyPress::stopKey;
  202186. break;
  202187. case APPCOMMAND_MEDIA_NEXTTRACK:
  202188. key = KeyPress::fastForwardKey;
  202189. break;
  202190. case APPCOMMAND_MEDIA_PREVIOUSTRACK:
  202191. key = KeyPress::rewindKey;
  202192. break;
  202193. }
  202194. if (key != 0)
  202195. {
  202196. updateKeyModifiers();
  202197. if (hwnd == GetActiveWindow())
  202198. {
  202199. handleKeyPress (key, 0);
  202200. return true;
  202201. }
  202202. }
  202203. return false;
  202204. }
  202205. class JuceDropTarget : public IDropTarget
  202206. {
  202207. public:
  202208. JuceDropTarget (Win32ComponentPeer* const owner_)
  202209. : owner (owner_),
  202210. refCount (1)
  202211. {
  202212. }
  202213. virtual ~JuceDropTarget()
  202214. {
  202215. jassert (refCount == 0);
  202216. }
  202217. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  202218. {
  202219. if (id == IID_IUnknown || id == IID_IDropTarget)
  202220. {
  202221. AddRef();
  202222. *result = this;
  202223. return S_OK;
  202224. }
  202225. *result = 0;
  202226. return E_NOINTERFACE;
  202227. }
  202228. ULONG __stdcall AddRef() { return ++refCount; }
  202229. ULONG __stdcall Release() { jassert (refCount > 0); const int r = --refCount; if (r == 0) delete this; return r; }
  202230. HRESULT __stdcall DragEnter (IDataObject* pDataObject, DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  202231. {
  202232. updateFileList (pDataObject);
  202233. int x = mousePos.x, y = mousePos.y;
  202234. owner->globalPositionToRelative (x, y);
  202235. owner->handleFileDragMove (files, x, y);
  202236. *pdwEffect = DROPEFFECT_COPY;
  202237. return S_OK;
  202238. }
  202239. HRESULT __stdcall DragLeave()
  202240. {
  202241. owner->handleFileDragExit (files);
  202242. return S_OK;
  202243. }
  202244. HRESULT __stdcall DragOver (DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  202245. {
  202246. int x = mousePos.x, y = mousePos.y;
  202247. owner->globalPositionToRelative (x, y);
  202248. owner->handleFileDragMove (files, x, y);
  202249. *pdwEffect = DROPEFFECT_COPY;
  202250. return S_OK;
  202251. }
  202252. HRESULT __stdcall Drop (IDataObject* pDataObject, DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  202253. {
  202254. updateFileList (pDataObject);
  202255. int x = mousePos.x, y = mousePos.y;
  202256. owner->globalPositionToRelative (x, y);
  202257. owner->handleFileDragDrop (files, x, y);
  202258. *pdwEffect = DROPEFFECT_COPY;
  202259. return S_OK;
  202260. }
  202261. private:
  202262. Win32ComponentPeer* const owner;
  202263. int refCount;
  202264. StringArray files;
  202265. void updateFileList (IDataObject* const pDataObject)
  202266. {
  202267. files.clear();
  202268. FORMATETC format = { CF_HDROP, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  202269. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  202270. if (pDataObject->GetData (&format, &medium) == S_OK)
  202271. {
  202272. const SIZE_T totalLen = GlobalSize (medium.hGlobal);
  202273. const LPDROPFILES pDropFiles = (const LPDROPFILES) GlobalLock (medium.hGlobal);
  202274. unsigned int i = 0;
  202275. if (pDropFiles->fWide)
  202276. {
  202277. const WCHAR* const fname = (WCHAR*) (((const char*) pDropFiles) + sizeof (DROPFILES));
  202278. for (;;)
  202279. {
  202280. unsigned int len = 0;
  202281. while (i + len < totalLen && fname [i + len] != 0)
  202282. ++len;
  202283. if (len == 0)
  202284. break;
  202285. files.add (String (fname + i, len));
  202286. i += len + 1;
  202287. }
  202288. }
  202289. else
  202290. {
  202291. const char* const fname = ((const char*) pDropFiles) + sizeof (DROPFILES);
  202292. for (;;)
  202293. {
  202294. unsigned int len = 0;
  202295. while (i + len < totalLen && fname [i + len] != 0)
  202296. ++len;
  202297. if (len == 0)
  202298. break;
  202299. files.add (String (fname + i, len));
  202300. i += len + 1;
  202301. }
  202302. }
  202303. GlobalUnlock (medium.hGlobal);
  202304. }
  202305. }
  202306. JuceDropTarget (const JuceDropTarget&);
  202307. const JuceDropTarget& operator= (const JuceDropTarget&);
  202308. };
  202309. void doSettingChange()
  202310. {
  202311. Desktop::getInstance().refreshMonitorSizes();
  202312. if (fullScreen && ! isMinimised())
  202313. {
  202314. const Rectangle r (component->getParentMonitorArea());
  202315. SetWindowPos (hwnd, 0,
  202316. r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  202317. SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER | SWP_NOSENDCHANGING);
  202318. }
  202319. }
  202320. public:
  202321. static LRESULT CALLBACK windowProc (HWND h, UINT message, WPARAM wParam, LPARAM lParam)
  202322. {
  202323. Win32ComponentPeer* const peer = getOwnerOfWindow (h);
  202324. if (peer != 0)
  202325. return peer->peerWindowProc (h, message, wParam, lParam);
  202326. return DefWindowProc (h, message, wParam, lParam);
  202327. }
  202328. private:
  202329. LRESULT peerWindowProc (HWND h, UINT message, WPARAM wParam, LPARAM lParam)
  202330. {
  202331. {
  202332. if (isValidPeer (this))
  202333. {
  202334. switch (message)
  202335. {
  202336. case WM_NCHITTEST:
  202337. if (hasTitleBar())
  202338. break;
  202339. return HTCLIENT;
  202340. case WM_PAINT:
  202341. handlePaintMessage();
  202342. return 0;
  202343. case WM_NCPAINT:
  202344. if (wParam != 1)
  202345. handlePaintMessage();
  202346. if (hasTitleBar())
  202347. break;
  202348. return 0;
  202349. case WM_ERASEBKGND:
  202350. case WM_NCCALCSIZE:
  202351. if (hasTitleBar())
  202352. break;
  202353. return 1;
  202354. case WM_MOUSEMOVE:
  202355. doMouseMove (GET_X_LPARAM (lParam), GET_Y_LPARAM (lParam));
  202356. return 0;
  202357. case WM_MOUSELEAVE:
  202358. doMouseExit();
  202359. return 0;
  202360. case WM_LBUTTONDOWN:
  202361. case WM_MBUTTONDOWN:
  202362. case WM_RBUTTONDOWN:
  202363. doMouseDown (GET_X_LPARAM (lParam), GET_Y_LPARAM (lParam), wParam);
  202364. return 0;
  202365. case WM_LBUTTONUP:
  202366. case WM_MBUTTONUP:
  202367. case WM_RBUTTONUP:
  202368. doMouseUp (GET_X_LPARAM (lParam), GET_Y_LPARAM (lParam), wParam);
  202369. return 0;
  202370. case WM_CAPTURECHANGED:
  202371. doCaptureChanged();
  202372. return 0;
  202373. case WM_NCMOUSEMOVE:
  202374. if (hasTitleBar())
  202375. break;
  202376. return 0;
  202377. case 0x020A: /* WM_MOUSEWHEEL */
  202378. doMouseWheel (wParam, true);
  202379. return 0;
  202380. case 0x020E: /* WM_MOUSEHWHEEL */
  202381. doMouseWheel (wParam, false);
  202382. return 0;
  202383. case WM_WINDOWPOSCHANGING:
  202384. if ((styleFlags & (windowHasTitleBar | windowIsResizable)) == (windowHasTitleBar | windowIsResizable))
  202385. {
  202386. WINDOWPOS* const wp = (WINDOWPOS*) lParam;
  202387. if ((wp->flags & (SWP_NOMOVE | SWP_NOSIZE)) != (SWP_NOMOVE | SWP_NOSIZE))
  202388. {
  202389. if (constrainer != 0)
  202390. {
  202391. const Rectangle current (component->getX() - windowBorder.getLeft(),
  202392. component->getY() - windowBorder.getTop(),
  202393. component->getWidth() + windowBorder.getLeftAndRight(),
  202394. component->getHeight() + windowBorder.getTopAndBottom());
  202395. constrainer->checkBounds (wp->x, wp->y, wp->cx, wp->cy,
  202396. current,
  202397. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  202398. wp->y != current.getY() && wp->y + wp->cy == current.getBottom(),
  202399. wp->x != current.getX() && wp->x + wp->cx == current.getRight(),
  202400. wp->y == current.getY() && wp->y + wp->cy != current.getBottom(),
  202401. wp->x == current.getX() && wp->x + wp->cx != current.getRight());
  202402. }
  202403. }
  202404. }
  202405. return 0;
  202406. case WM_WINDOWPOSCHANGED:
  202407. handleMovedOrResized();
  202408. if (dontRepaint)
  202409. break; // needed for non-accelerated openGL windows to draw themselves correctly..
  202410. else
  202411. return 0;
  202412. case WM_KEYDOWN:
  202413. case WM_SYSKEYDOWN:
  202414. if (doKeyDown (wParam))
  202415. return 0;
  202416. break;
  202417. case WM_KEYUP:
  202418. case WM_SYSKEYUP:
  202419. if (doKeyUp (wParam))
  202420. return 0;
  202421. break;
  202422. case WM_CHAR:
  202423. if (doKeyChar ((int) wParam, lParam))
  202424. return 0;
  202425. break;
  202426. case WM_APPCOMMAND:
  202427. if (doAppCommand (lParam))
  202428. return TRUE;
  202429. break;
  202430. case WM_SETFOCUS:
  202431. updateKeyModifiers();
  202432. handleFocusGain();
  202433. break;
  202434. case WM_KILLFOCUS:
  202435. if (hasCreatedCaret)
  202436. {
  202437. hasCreatedCaret = false;
  202438. DestroyCaret();
  202439. }
  202440. handleFocusLoss();
  202441. break;
  202442. case WM_ACTIVATEAPP:
  202443. // Windows does weird things to process priority when you swap apps,
  202444. // so this forces an update when the app is brought to the front
  202445. if (wParam != FALSE)
  202446. juce_repeatLastProcessPriority();
  202447. else
  202448. Desktop::getInstance().setKioskModeComponent (0); // turn kiosk mode off if we lose focus
  202449. juce_CheckCurrentlyFocusedTopLevelWindow();
  202450. modifiersAtLastCallback = -1;
  202451. return 0;
  202452. case WM_ACTIVATE:
  202453. if (LOWORD (wParam) == WA_ACTIVE || LOWORD (wParam) == WA_CLICKACTIVE)
  202454. {
  202455. modifiersAtLastCallback = -1;
  202456. updateKeyModifiers();
  202457. if (isMinimised())
  202458. {
  202459. component->repaint();
  202460. handleMovedOrResized();
  202461. if (! isValidMessageListener())
  202462. return 0;
  202463. }
  202464. if (LOWORD (wParam) == WA_CLICKACTIVE
  202465. && component->isCurrentlyBlockedByAnotherModalComponent())
  202466. {
  202467. int mx, my;
  202468. component->getMouseXYRelative (mx, my);
  202469. Component* const underMouse = component->getComponentAt (mx, my);
  202470. if (underMouse != 0 && underMouse->isCurrentlyBlockedByAnotherModalComponent())
  202471. Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  202472. return 0;
  202473. }
  202474. handleBroughtToFront();
  202475. if (component->isCurrentlyBlockedByAnotherModalComponent())
  202476. Component::getCurrentlyModalComponent()->toFront (true);
  202477. return 0;
  202478. }
  202479. break;
  202480. case WM_NCACTIVATE:
  202481. // while a temporary window is being shown, prevent Windows from deactivating the
  202482. // title bars of our main windows.
  202483. if (wParam == 0 && ! shouldDeactivateTitleBar)
  202484. wParam = TRUE; // change this and let it get passed to the DefWindowProc.
  202485. break;
  202486. case WM_MOUSEACTIVATE:
  202487. if (! component->getMouseClickGrabsKeyboardFocus())
  202488. return MA_NOACTIVATE;
  202489. break;
  202490. case WM_SHOWWINDOW:
  202491. if (wParam != 0)
  202492. handleBroughtToFront();
  202493. break;
  202494. case WM_CLOSE:
  202495. if (! component->isCurrentlyBlockedByAnotherModalComponent())
  202496. handleUserClosingWindow();
  202497. return 0;
  202498. case WM_QUIT:
  202499. if (JUCEApplication::getInstance() != 0)
  202500. JUCEApplication::getInstance()->systemRequestedQuit();
  202501. return 0;
  202502. case WM_QUERYENDSESSION:
  202503. if (JUCEApplication::getInstance() != 0)
  202504. {
  202505. JUCEApplication::getInstance()->systemRequestedQuit();
  202506. return MessageManager::getInstance()->hasStopMessageBeenSent();
  202507. }
  202508. return TRUE;
  202509. case WM_TRAYNOTIFY:
  202510. if (component->isCurrentlyBlockedByAnotherModalComponent())
  202511. {
  202512. if (lParam == WM_LBUTTONDOWN || lParam == WM_RBUTTONDOWN
  202513. || lParam == WM_LBUTTONDBLCLK || lParam == WM_LBUTTONDBLCLK)
  202514. {
  202515. Component* const current = Component::getCurrentlyModalComponent();
  202516. if (current != 0)
  202517. current->inputAttemptWhenModal();
  202518. }
  202519. }
  202520. else
  202521. {
  202522. const int oldModifiers = currentModifiers;
  202523. MouseEvent e (0, 0, ModifierKeys::getCurrentModifiersRealtime(), component,
  202524. getMouseEventTime(), 0, 0, getMouseEventTime(), 1, false);
  202525. if (lParam == WM_LBUTTONDOWN || lParam == WM_LBUTTONDBLCLK)
  202526. e.mods = ModifierKeys (e.mods.getRawFlags() | ModifierKeys::leftButtonModifier);
  202527. else if (lParam == WM_RBUTTONDOWN || lParam == WM_RBUTTONDBLCLK)
  202528. e.mods = ModifierKeys (e.mods.getRawFlags() | ModifierKeys::rightButtonModifier);
  202529. if (lParam == WM_LBUTTONDOWN || lParam == WM_RBUTTONDOWN)
  202530. {
  202531. SetFocus (hwnd);
  202532. SetForegroundWindow (hwnd);
  202533. component->mouseDown (e);
  202534. }
  202535. else if (lParam == WM_LBUTTONUP || lParam == WM_RBUTTONUP)
  202536. {
  202537. e.mods = ModifierKeys (oldModifiers);
  202538. component->mouseUp (e);
  202539. }
  202540. else if (lParam == WM_LBUTTONDBLCLK || lParam == WM_LBUTTONDBLCLK)
  202541. {
  202542. e.mods = ModifierKeys (oldModifiers);
  202543. component->mouseDoubleClick (e);
  202544. }
  202545. else if (lParam == WM_MOUSEMOVE)
  202546. {
  202547. component->mouseMove (e);
  202548. }
  202549. }
  202550. break;
  202551. case WM_SYNCPAINT:
  202552. return 0;
  202553. case WM_PALETTECHANGED:
  202554. InvalidateRect (h, 0, 0);
  202555. break;
  202556. case WM_DISPLAYCHANGE:
  202557. InvalidateRect (h, 0, 0);
  202558. createPaletteIfNeeded = true;
  202559. // intentional fall-through...
  202560. case WM_SETTINGCHANGE: // note the fall-through in the previous case!
  202561. doSettingChange();
  202562. break;
  202563. case WM_INITMENU:
  202564. if (! hasTitleBar())
  202565. {
  202566. if (isFullScreen())
  202567. {
  202568. EnableMenuItem ((HMENU) wParam, SC_RESTORE, MF_BYCOMMAND | MF_ENABLED);
  202569. EnableMenuItem ((HMENU) wParam, SC_MOVE, MF_BYCOMMAND | MF_GRAYED);
  202570. }
  202571. else if (! isMinimised())
  202572. {
  202573. EnableMenuItem ((HMENU) wParam, SC_MAXIMIZE, MF_BYCOMMAND | MF_GRAYED);
  202574. }
  202575. }
  202576. break;
  202577. case WM_SYSCOMMAND:
  202578. switch (wParam & 0xfff0)
  202579. {
  202580. case SC_CLOSE:
  202581. if (sendInputAttemptWhenModalMessage())
  202582. return 0;
  202583. if (hasTitleBar())
  202584. {
  202585. PostMessage (h, WM_CLOSE, 0, 0);
  202586. return 0;
  202587. }
  202588. break;
  202589. case SC_KEYMENU:
  202590. // (NB mustn't call sendInputAttemptWhenModalMessage() here because of very
  202591. // obscure situations that can arise if a modal loop is started from an alt-key
  202592. // keypress).
  202593. if (hasTitleBar() && h == GetCapture())
  202594. ReleaseCapture();
  202595. break;
  202596. case SC_MAXIMIZE:
  202597. if (sendInputAttemptWhenModalMessage())
  202598. return 0;
  202599. setFullScreen (true);
  202600. return 0;
  202601. case SC_MINIMIZE:
  202602. if (sendInputAttemptWhenModalMessage())
  202603. return 0;
  202604. if (! hasTitleBar())
  202605. {
  202606. setMinimised (true);
  202607. return 0;
  202608. }
  202609. break;
  202610. case SC_RESTORE:
  202611. if (sendInputAttemptWhenModalMessage())
  202612. return 0;
  202613. if (hasTitleBar())
  202614. {
  202615. if (isFullScreen())
  202616. {
  202617. setFullScreen (false);
  202618. return 0;
  202619. }
  202620. }
  202621. else
  202622. {
  202623. if (isMinimised())
  202624. setMinimised (false);
  202625. else if (isFullScreen())
  202626. setFullScreen (false);
  202627. return 0;
  202628. }
  202629. break;
  202630. }
  202631. break;
  202632. case WM_NCLBUTTONDOWN:
  202633. case WM_NCRBUTTONDOWN:
  202634. case WM_NCMBUTTONDOWN:
  202635. sendInputAttemptWhenModalMessage();
  202636. break;
  202637. //case WM_IME_STARTCOMPOSITION;
  202638. // return 0;
  202639. case WM_GETDLGCODE:
  202640. return DLGC_WANTALLKEYS;
  202641. default:
  202642. break;
  202643. }
  202644. }
  202645. }
  202646. // (the message manager lock exits before calling this, to avoid deadlocks if
  202647. // this calls into non-juce windows)
  202648. return DefWindowProc (h, message, wParam, lParam);
  202649. }
  202650. bool sendInputAttemptWhenModalMessage()
  202651. {
  202652. if (component->isCurrentlyBlockedByAnotherModalComponent())
  202653. {
  202654. Component* const current = Component::getCurrentlyModalComponent();
  202655. if (current != 0)
  202656. current->inputAttemptWhenModal();
  202657. return true;
  202658. }
  202659. return false;
  202660. }
  202661. Win32ComponentPeer (const Win32ComponentPeer&);
  202662. const Win32ComponentPeer& operator= (const Win32ComponentPeer&);
  202663. };
  202664. ComponentPeer* Component::createNewPeer (int styleFlags, void* /*nativeWindowToAttachTo*/)
  202665. {
  202666. return new Win32ComponentPeer (this, styleFlags);
  202667. }
  202668. juce_ImplementSingleton_SingleThreaded (Win32ComponentPeer::WindowClassHolder);
  202669. void SystemTrayIconComponent::setIconImage (const Image& newImage)
  202670. {
  202671. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (getPeer());
  202672. if (wp != 0)
  202673. wp->setTaskBarIcon (&newImage);
  202674. }
  202675. void SystemTrayIconComponent::setIconTooltip (const String& tooltip)
  202676. {
  202677. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (getPeer());
  202678. if (wp != 0)
  202679. wp->setTaskBarIconToolTip (tooltip);
  202680. }
  202681. void juce_setWindowStyleBit (HWND h, const int styleType, const int feature, const bool bitIsSet) throw()
  202682. {
  202683. DWORD val = GetWindowLong (h, styleType);
  202684. if (bitIsSet)
  202685. val |= feature;
  202686. else
  202687. val &= ~feature;
  202688. SetWindowLongPtr (h, styleType, val);
  202689. SetWindowPos (h, 0, 0, 0, 0, 0,
  202690. SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER
  202691. | SWP_NOOWNERZORDER | SWP_FRAMECHANGED | SWP_NOSENDCHANGING);
  202692. }
  202693. bool Process::isForegroundProcess() throw()
  202694. {
  202695. HWND fg = GetForegroundWindow();
  202696. if (fg == 0)
  202697. return true;
  202698. // when running as a plugin in IE8, the browser UI runs in a different process to the plugin, so
  202699. // process ID isn't a reliable way to check if the foreground window belongs to us - instead, we
  202700. // have to see if any of our windows are children of the foreground window
  202701. fg = GetAncestor (fg, GA_ROOT);
  202702. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  202703. {
  202704. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (ComponentPeer::getPeer (i));
  202705. if (wp != 0 && wp->isInside (fg))
  202706. return true;
  202707. }
  202708. return false;
  202709. }
  202710. bool AlertWindow::showNativeDialogBox (const String& title,
  202711. const String& bodyText,
  202712. bool isOkCancel)
  202713. {
  202714. return MessageBox (0, bodyText, title,
  202715. MB_SETFOREGROUND | (isOkCancel ? MB_OKCANCEL
  202716. : MB_OK)) == IDOK;
  202717. }
  202718. void Desktop::getMousePosition (int& x, int& y) throw()
  202719. {
  202720. POINT mousePos;
  202721. GetCursorPos (&mousePos);
  202722. x = mousePos.x;
  202723. y = mousePos.y;
  202724. }
  202725. void Desktop::setMousePosition (int x, int y) throw()
  202726. {
  202727. SetCursorPos (x, y);
  202728. }
  202729. class ScreenSaverDefeater : public Timer,
  202730. public DeletedAtShutdown
  202731. {
  202732. public:
  202733. ScreenSaverDefeater() throw()
  202734. {
  202735. startTimer (10000);
  202736. timerCallback();
  202737. }
  202738. ~ScreenSaverDefeater() {}
  202739. void timerCallback()
  202740. {
  202741. if (Process::isForegroundProcess())
  202742. {
  202743. // simulate a shift key getting pressed..
  202744. INPUT input[2];
  202745. input[0].type = INPUT_KEYBOARD;
  202746. input[0].ki.wVk = VK_SHIFT;
  202747. input[0].ki.dwFlags = 0;
  202748. input[0].ki.dwExtraInfo = 0;
  202749. input[1].type = INPUT_KEYBOARD;
  202750. input[1].ki.wVk = VK_SHIFT;
  202751. input[1].ki.dwFlags = KEYEVENTF_KEYUP;
  202752. input[1].ki.dwExtraInfo = 0;
  202753. SendInput (2, input, sizeof (INPUT));
  202754. }
  202755. }
  202756. };
  202757. static ScreenSaverDefeater* screenSaverDefeater = 0;
  202758. void Desktop::setScreenSaverEnabled (const bool isEnabled) throw()
  202759. {
  202760. if (isEnabled)
  202761. {
  202762. deleteAndZero (screenSaverDefeater);
  202763. }
  202764. else if (screenSaverDefeater == 0)
  202765. {
  202766. screenSaverDefeater = new ScreenSaverDefeater();
  202767. }
  202768. }
  202769. bool Desktop::isScreenSaverEnabled() throw()
  202770. {
  202771. return screenSaverDefeater == 0;
  202772. }
  202773. /* (The code below is the "correct" way to disable the screen saver, but it
  202774. completely fails on winXP when the saver is password-protected...)
  202775. static bool juce_screenSaverEnabled = true;
  202776. void Desktop::setScreenSaverEnabled (const bool isEnabled) throw()
  202777. {
  202778. juce_screenSaverEnabled = isEnabled;
  202779. SetThreadExecutionState (isEnabled ? ES_CONTINUOUS
  202780. : (ES_DISPLAY_REQUIRED | ES_CONTINUOUS));
  202781. }
  202782. bool Desktop::isScreenSaverEnabled() throw()
  202783. {
  202784. return juce_screenSaverEnabled;
  202785. }
  202786. */
  202787. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool /*allowMenusAndBars*/)
  202788. {
  202789. if (enableOrDisable)
  202790. kioskModeComponent->setBounds (Desktop::getInstance().getMainMonitorArea (false));
  202791. }
  202792. static BOOL CALLBACK enumMonitorsProc (HMONITOR, HDC, LPRECT r, LPARAM userInfo)
  202793. {
  202794. Array <Rectangle>* const monitorCoords = (Array <Rectangle>*) userInfo;
  202795. monitorCoords->add (Rectangle (r->left, r->top, r->right - r->left, r->bottom - r->top));
  202796. return TRUE;
  202797. }
  202798. void juce_updateMultiMonitorInfo (Array <Rectangle>& monitorCoords, const bool clipToWorkArea) throw()
  202799. {
  202800. EnumDisplayMonitors (0, 0, &enumMonitorsProc, (LPARAM) &monitorCoords);
  202801. // make sure the first in the list is the main monitor
  202802. for (int i = 1; i < monitorCoords.size(); ++i)
  202803. if (monitorCoords[i].getX() == 0 && monitorCoords[i].getY() == 0)
  202804. monitorCoords.swap (i, 0);
  202805. if (monitorCoords.size() == 0)
  202806. {
  202807. RECT r;
  202808. GetWindowRect (GetDesktopWindow(), &r);
  202809. monitorCoords.add (Rectangle (r.left, r.top, r.right - r.left, r.bottom - r.top));
  202810. }
  202811. if (clipToWorkArea)
  202812. {
  202813. // clip the main monitor to the active non-taskbar area
  202814. RECT r;
  202815. SystemParametersInfo (SPI_GETWORKAREA, 0, &r, 0);
  202816. Rectangle& screen = monitorCoords.getReference (0);
  202817. screen.setPosition (jmax (screen.getX(), r.left),
  202818. jmax (screen.getY(), r.top));
  202819. screen.setSize (jmin (screen.getRight(), r.right) - screen.getX(),
  202820. jmin (screen.getBottom(), r.bottom) - screen.getY());
  202821. }
  202822. }
  202823. static Image* createImageFromHBITMAP (HBITMAP bitmap) throw()
  202824. {
  202825. Image* im = 0;
  202826. if (bitmap != 0)
  202827. {
  202828. BITMAP bm;
  202829. if (GetObject (bitmap, sizeof (BITMAP), &bm)
  202830. && bm.bmWidth > 0 && bm.bmHeight > 0)
  202831. {
  202832. HDC tempDC = GetDC (0);
  202833. HDC dc = CreateCompatibleDC (tempDC);
  202834. ReleaseDC (0, tempDC);
  202835. SelectObject (dc, bitmap);
  202836. im = new Image (Image::ARGB, bm.bmWidth, bm.bmHeight, true);
  202837. for (int y = bm.bmHeight; --y >= 0;)
  202838. {
  202839. for (int x = bm.bmWidth; --x >= 0;)
  202840. {
  202841. COLORREF col = GetPixel (dc, x, y);
  202842. im->setPixelAt (x, y, Colour ((uint8) GetRValue (col),
  202843. (uint8) GetGValue (col),
  202844. (uint8) GetBValue (col)));
  202845. }
  202846. }
  202847. DeleteDC (dc);
  202848. }
  202849. }
  202850. return im;
  202851. }
  202852. static Image* createImageFromHICON (HICON icon) throw()
  202853. {
  202854. ICONINFO info;
  202855. if (GetIconInfo (icon, &info))
  202856. {
  202857. Image* const mask = createImageFromHBITMAP (info.hbmMask);
  202858. if (mask == 0)
  202859. return 0;
  202860. Image* const image = createImageFromHBITMAP (info.hbmColor);
  202861. if (image == 0)
  202862. return mask;
  202863. for (int y = image->getHeight(); --y >= 0;)
  202864. {
  202865. for (int x = image->getWidth(); --x >= 0;)
  202866. {
  202867. const float brightness = mask->getPixelAt (x, y).getBrightness();
  202868. if (brightness > 0.0f)
  202869. image->multiplyAlphaAt (x, y, 1.0f - brightness);
  202870. }
  202871. }
  202872. delete mask;
  202873. return image;
  202874. }
  202875. return 0;
  202876. }
  202877. static HICON createHICONFromImage (const Image& image, const BOOL isIcon, int hotspotX, int hotspotY) throw()
  202878. {
  202879. HBITMAP mask = CreateBitmap (image.getWidth(), image.getHeight(), 1, 1, 0);
  202880. ICONINFO info;
  202881. info.fIcon = isIcon;
  202882. info.xHotspot = hotspotX;
  202883. info.yHotspot = hotspotY;
  202884. info.hbmMask = mask;
  202885. HICON hi = 0;
  202886. if (SystemStats::getOperatingSystemType() >= SystemStats::WinXP)
  202887. {
  202888. WindowsBitmapImage bitmap (Image::ARGB, image.getWidth(), image.getHeight(), true);
  202889. Graphics g (bitmap);
  202890. g.drawImageAt (&image, 0, 0);
  202891. info.hbmColor = bitmap.hBitmap;
  202892. hi = CreateIconIndirect (&info);
  202893. }
  202894. else
  202895. {
  202896. HBITMAP colour = CreateCompatibleBitmap (GetDC (0), image.getWidth(), image.getHeight());
  202897. HDC colDC = CreateCompatibleDC (GetDC (0));
  202898. HDC alphaDC = CreateCompatibleDC (GetDC (0));
  202899. SelectObject (colDC, colour);
  202900. SelectObject (alphaDC, mask);
  202901. for (int y = image.getHeight(); --y >= 0;)
  202902. {
  202903. for (int x = image.getWidth(); --x >= 0;)
  202904. {
  202905. const Colour c (image.getPixelAt (x, y));
  202906. SetPixel (colDC, x, y, COLORREF (c.getRed() | (c.getGreen() << 8) | (c.getBlue() << 16)));
  202907. SetPixel (alphaDC, x, y, COLORREF (0xffffff - (c.getAlpha() | (c.getAlpha() << 8) | (c.getAlpha() << 16))));
  202908. }
  202909. }
  202910. DeleteDC (colDC);
  202911. DeleteDC (alphaDC);
  202912. info.hbmColor = colour;
  202913. hi = CreateIconIndirect (&info);
  202914. DeleteObject (colour);
  202915. }
  202916. DeleteObject (mask);
  202917. return hi;
  202918. }
  202919. Image* juce_createIconForFile (const File& file)
  202920. {
  202921. Image* image = 0;
  202922. TCHAR filename [1024];
  202923. file.getFullPathName().copyToBuffer (filename, 1023);
  202924. WORD iconNum = 0;
  202925. HICON icon = ExtractAssociatedIcon ((HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle(),
  202926. filename, &iconNum);
  202927. if (icon != 0)
  202928. {
  202929. image = createImageFromHICON (icon);
  202930. DestroyIcon (icon);
  202931. }
  202932. return image;
  202933. }
  202934. void* juce_createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY) throw()
  202935. {
  202936. const int maxW = GetSystemMetrics (SM_CXCURSOR);
  202937. const int maxH = GetSystemMetrics (SM_CYCURSOR);
  202938. const Image* im = &image;
  202939. Image* newIm = 0;
  202940. if (image.getWidth() > maxW || image.getHeight() > maxH)
  202941. {
  202942. im = newIm = image.createCopy (maxW, maxH);
  202943. hotspotX = (hotspotX * maxW) / image.getWidth();
  202944. hotspotY = (hotspotY * maxH) / image.getHeight();
  202945. }
  202946. void* cursorH = 0;
  202947. const SystemStats::OperatingSystemType os = SystemStats::getOperatingSystemType();
  202948. if (os == SystemStats::WinXP)
  202949. {
  202950. cursorH = (void*) createHICONFromImage (*im, FALSE, hotspotX, hotspotY);
  202951. }
  202952. else
  202953. {
  202954. const int stride = (maxW + 7) >> 3;
  202955. uint8* const andPlane = (uint8*) juce_calloc (stride * maxH);
  202956. uint8* const xorPlane = (uint8*) juce_calloc (stride * maxH);
  202957. int index = 0;
  202958. for (int y = 0; y < maxH; ++y)
  202959. {
  202960. for (int x = 0; x < maxW; ++x)
  202961. {
  202962. const unsigned char bit = (unsigned char) (1 << (7 - (x & 7)));
  202963. const Colour pixelColour (im->getPixelAt (x, y));
  202964. if (pixelColour.getAlpha() < 127)
  202965. andPlane [index + (x >> 3)] |= bit;
  202966. else if (pixelColour.getBrightness() >= 0.5f)
  202967. xorPlane [index + (x >> 3)] |= bit;
  202968. }
  202969. index += stride;
  202970. }
  202971. cursorH = CreateCursor (0, hotspotX, hotspotY, maxW, maxH, andPlane, xorPlane);
  202972. juce_free (andPlane);
  202973. juce_free (xorPlane);
  202974. }
  202975. delete newIm;
  202976. return cursorH;
  202977. }
  202978. void juce_deleteMouseCursor (void* const cursorHandle, const bool isStandard) throw()
  202979. {
  202980. if (cursorHandle != 0 && ! isStandard)
  202981. DestroyCursor ((HCURSOR) cursorHandle);
  202982. }
  202983. void* juce_createStandardMouseCursor (MouseCursor::StandardCursorType type) throw()
  202984. {
  202985. LPCTSTR cursorName = IDC_ARROW;
  202986. switch (type)
  202987. {
  202988. case MouseCursor::NormalCursor:
  202989. cursorName = IDC_ARROW;
  202990. break;
  202991. case MouseCursor::NoCursor:
  202992. return 0;
  202993. case MouseCursor::DraggingHandCursor:
  202994. {
  202995. static void* dragHandCursor = 0;
  202996. if (dragHandCursor == 0)
  202997. {
  202998. static const unsigned char dragHandData[] =
  202999. { 71,73,70,56,57,97,16,0,16,0,145,2,0,0,0,0,255,255,255,0,0,0,0,0,0,33,249,4,1,0,0,2,0,44,0,0,0,0,16,0,
  203000. 16,0,0,2,52,148,47,0,200,185,16,130,90,12,74,139,107,84,123,39, 132,117,151,116,132,146,248,60,209,138,
  203001. 98,22,203,114,34,236,37,52,77,217,247,154,191,119,110,240,193,128,193,95,163,56,60,234,98,135,2,0,59 };
  203002. Image* const image = ImageFileFormat::loadFrom ((const char*) dragHandData, sizeof (dragHandData));
  203003. dragHandCursor = juce_createMouseCursorFromImage (*image, 8, 7);
  203004. delete image;
  203005. }
  203006. return dragHandCursor;
  203007. }
  203008. case MouseCursor::WaitCursor:
  203009. cursorName = IDC_WAIT;
  203010. break;
  203011. case MouseCursor::IBeamCursor:
  203012. cursorName = IDC_IBEAM;
  203013. break;
  203014. case MouseCursor::PointingHandCursor:
  203015. cursorName = MAKEINTRESOURCE(32649);
  203016. break;
  203017. case MouseCursor::LeftRightResizeCursor:
  203018. case MouseCursor::LeftEdgeResizeCursor:
  203019. case MouseCursor::RightEdgeResizeCursor:
  203020. cursorName = IDC_SIZEWE;
  203021. break;
  203022. case MouseCursor::UpDownResizeCursor:
  203023. case MouseCursor::TopEdgeResizeCursor:
  203024. case MouseCursor::BottomEdgeResizeCursor:
  203025. cursorName = IDC_SIZENS;
  203026. break;
  203027. case MouseCursor::TopLeftCornerResizeCursor:
  203028. case MouseCursor::BottomRightCornerResizeCursor:
  203029. cursorName = IDC_SIZENWSE;
  203030. break;
  203031. case MouseCursor::TopRightCornerResizeCursor:
  203032. case MouseCursor::BottomLeftCornerResizeCursor:
  203033. cursorName = IDC_SIZENESW;
  203034. break;
  203035. case MouseCursor::UpDownLeftRightResizeCursor:
  203036. cursorName = IDC_SIZEALL;
  203037. break;
  203038. case MouseCursor::CrosshairCursor:
  203039. cursorName = IDC_CROSS;
  203040. break;
  203041. case MouseCursor::CopyingCursor:
  203042. // can't seem to find one of these in the win32 list..
  203043. break;
  203044. }
  203045. HCURSOR cursorH = LoadCursor (0, cursorName);
  203046. if (cursorH == 0)
  203047. cursorH = LoadCursor (0, IDC_ARROW);
  203048. return (void*) cursorH;
  203049. }
  203050. void MouseCursor::showInWindow (ComponentPeer*) const throw()
  203051. {
  203052. SetCursor ((HCURSOR) getHandle());
  203053. }
  203054. void MouseCursor::showInAllWindows() const throw()
  203055. {
  203056. showInWindow (0);
  203057. }
  203058. class JuceDropSource : public IDropSource
  203059. {
  203060. int refCount;
  203061. public:
  203062. JuceDropSource()
  203063. : refCount (1)
  203064. {
  203065. }
  203066. virtual ~JuceDropSource()
  203067. {
  203068. jassert (refCount == 0);
  203069. }
  203070. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  203071. {
  203072. if (id == IID_IUnknown || id == IID_IDropSource)
  203073. {
  203074. AddRef();
  203075. *result = this;
  203076. return S_OK;
  203077. }
  203078. *result = 0;
  203079. return E_NOINTERFACE;
  203080. }
  203081. ULONG __stdcall AddRef() { return ++refCount; }
  203082. ULONG __stdcall Release() { jassert (refCount > 0); const int r = --refCount; if (r == 0) delete this; return r; }
  203083. HRESULT __stdcall QueryContinueDrag (BOOL escapePressed, DWORD keys)
  203084. {
  203085. if (escapePressed)
  203086. return DRAGDROP_S_CANCEL;
  203087. if ((keys & (MK_LBUTTON | MK_RBUTTON)) == 0)
  203088. return DRAGDROP_S_DROP;
  203089. return S_OK;
  203090. }
  203091. HRESULT __stdcall GiveFeedback (DWORD)
  203092. {
  203093. return DRAGDROP_S_USEDEFAULTCURSORS;
  203094. }
  203095. };
  203096. class JuceEnumFormatEtc : public IEnumFORMATETC
  203097. {
  203098. public:
  203099. JuceEnumFormatEtc (const FORMATETC* const format_)
  203100. : refCount (1),
  203101. format (format_),
  203102. index (0)
  203103. {
  203104. }
  203105. virtual ~JuceEnumFormatEtc()
  203106. {
  203107. jassert (refCount == 0);
  203108. }
  203109. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  203110. {
  203111. if (id == IID_IUnknown || id == IID_IEnumFORMATETC)
  203112. {
  203113. AddRef();
  203114. *result = this;
  203115. return S_OK;
  203116. }
  203117. *result = 0;
  203118. return E_NOINTERFACE;
  203119. }
  203120. ULONG __stdcall AddRef() { return ++refCount; }
  203121. ULONG __stdcall Release() { jassert (refCount > 0); const int r = --refCount; if (r == 0) delete this; return r; }
  203122. HRESULT __stdcall Clone (IEnumFORMATETC** result)
  203123. {
  203124. if (result == 0)
  203125. return E_POINTER;
  203126. JuceEnumFormatEtc* const newOne = new JuceEnumFormatEtc (format);
  203127. newOne->index = index;
  203128. *result = newOne;
  203129. return S_OK;
  203130. }
  203131. HRESULT __stdcall Next (ULONG celt, LPFORMATETC lpFormatEtc, ULONG* pceltFetched)
  203132. {
  203133. if (pceltFetched != 0)
  203134. *pceltFetched = 0;
  203135. else if (celt != 1)
  203136. return S_FALSE;
  203137. if (index == 0 && celt > 0 && lpFormatEtc != 0)
  203138. {
  203139. copyFormatEtc (lpFormatEtc [0], *format);
  203140. ++index;
  203141. if (pceltFetched != 0)
  203142. *pceltFetched = 1;
  203143. return S_OK;
  203144. }
  203145. return S_FALSE;
  203146. }
  203147. HRESULT __stdcall Skip (ULONG celt)
  203148. {
  203149. if (index + (int) celt >= 1)
  203150. return S_FALSE;
  203151. index += celt;
  203152. return S_OK;
  203153. }
  203154. HRESULT __stdcall Reset()
  203155. {
  203156. index = 0;
  203157. return S_OK;
  203158. }
  203159. private:
  203160. int refCount;
  203161. const FORMATETC* const format;
  203162. int index;
  203163. static void copyFormatEtc (FORMATETC& dest, const FORMATETC& source)
  203164. {
  203165. dest = source;
  203166. if (source.ptd != 0)
  203167. {
  203168. dest.ptd = (DVTARGETDEVICE*) CoTaskMemAlloc (sizeof (DVTARGETDEVICE));
  203169. *(dest.ptd) = *(source.ptd);
  203170. }
  203171. }
  203172. JuceEnumFormatEtc (const JuceEnumFormatEtc&);
  203173. const JuceEnumFormatEtc& operator= (const JuceEnumFormatEtc&);
  203174. };
  203175. class JuceDataObject : public IDataObject
  203176. {
  203177. JuceDropSource* const dropSource;
  203178. const FORMATETC* const format;
  203179. const STGMEDIUM* const medium;
  203180. int refCount;
  203181. JuceDataObject (const JuceDataObject&);
  203182. const JuceDataObject& operator= (const JuceDataObject&);
  203183. public:
  203184. JuceDataObject (JuceDropSource* const dropSource_,
  203185. const FORMATETC* const format_,
  203186. const STGMEDIUM* const medium_)
  203187. : dropSource (dropSource_),
  203188. format (format_),
  203189. medium (medium_),
  203190. refCount (1)
  203191. {
  203192. }
  203193. virtual ~JuceDataObject()
  203194. {
  203195. jassert (refCount == 0);
  203196. }
  203197. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  203198. {
  203199. if (id == IID_IUnknown || id == IID_IDataObject)
  203200. {
  203201. AddRef();
  203202. *result = this;
  203203. return S_OK;
  203204. }
  203205. *result = 0;
  203206. return E_NOINTERFACE;
  203207. }
  203208. ULONG __stdcall AddRef() { return ++refCount; }
  203209. ULONG __stdcall Release() { jassert (refCount > 0); const int r = --refCount; if (r == 0) delete this; return r; }
  203210. HRESULT __stdcall GetData (FORMATETC __RPC_FAR* pFormatEtc, STGMEDIUM __RPC_FAR* pMedium)
  203211. {
  203212. if (pFormatEtc->tymed == format->tymed
  203213. && pFormatEtc->cfFormat == format->cfFormat
  203214. && pFormatEtc->dwAspect == format->dwAspect)
  203215. {
  203216. pMedium->tymed = format->tymed;
  203217. pMedium->pUnkForRelease = 0;
  203218. if (format->tymed == TYMED_HGLOBAL)
  203219. {
  203220. const SIZE_T len = GlobalSize (medium->hGlobal);
  203221. void* const src = GlobalLock (medium->hGlobal);
  203222. void* const dst = GlobalAlloc (GMEM_FIXED, len);
  203223. memcpy (dst, src, len);
  203224. GlobalUnlock (medium->hGlobal);
  203225. pMedium->hGlobal = dst;
  203226. return S_OK;
  203227. }
  203228. }
  203229. return DV_E_FORMATETC;
  203230. }
  203231. HRESULT __stdcall QueryGetData (FORMATETC __RPC_FAR* f)
  203232. {
  203233. if (f == 0)
  203234. return E_INVALIDARG;
  203235. if (f->tymed == format->tymed
  203236. && f->cfFormat == format->cfFormat
  203237. && f->dwAspect == format->dwAspect)
  203238. return S_OK;
  203239. return DV_E_FORMATETC;
  203240. }
  203241. HRESULT __stdcall GetCanonicalFormatEtc (FORMATETC __RPC_FAR*, FORMATETC __RPC_FAR* pFormatEtcOut)
  203242. {
  203243. pFormatEtcOut->ptd = 0;
  203244. return E_NOTIMPL;
  203245. }
  203246. HRESULT __stdcall EnumFormatEtc (DWORD direction, IEnumFORMATETC __RPC_FAR *__RPC_FAR *result)
  203247. {
  203248. if (result == 0)
  203249. return E_POINTER;
  203250. if (direction == DATADIR_GET)
  203251. {
  203252. *result = new JuceEnumFormatEtc (format);
  203253. return S_OK;
  203254. }
  203255. *result = 0;
  203256. return E_NOTIMPL;
  203257. }
  203258. HRESULT __stdcall GetDataHere (FORMATETC __RPC_FAR*, STGMEDIUM __RPC_FAR*) { return DATA_E_FORMATETC; }
  203259. HRESULT __stdcall SetData (FORMATETC __RPC_FAR*, STGMEDIUM __RPC_FAR*, BOOL) { return E_NOTIMPL; }
  203260. HRESULT __stdcall DAdvise (FORMATETC __RPC_FAR*, DWORD, IAdviseSink __RPC_FAR*, DWORD __RPC_FAR*) { return OLE_E_ADVISENOTSUPPORTED; }
  203261. HRESULT __stdcall DUnadvise (DWORD) { return E_NOTIMPL; }
  203262. HRESULT __stdcall EnumDAdvise (IEnumSTATDATA __RPC_FAR *__RPC_FAR *) { return OLE_E_ADVISENOTSUPPORTED; }
  203263. };
  203264. static HDROP createHDrop (const StringArray& fileNames) throw()
  203265. {
  203266. int totalChars = 0;
  203267. for (int i = fileNames.size(); --i >= 0;)
  203268. totalChars += fileNames[i].length() + 1;
  203269. HDROP hDrop = (HDROP) GlobalAlloc (GMEM_MOVEABLE | GMEM_ZEROINIT,
  203270. sizeof (DROPFILES)
  203271. + sizeof (WCHAR) * (totalChars + 2));
  203272. if (hDrop != 0)
  203273. {
  203274. LPDROPFILES pDropFiles = (LPDROPFILES) GlobalLock (hDrop);
  203275. pDropFiles->pFiles = sizeof (DROPFILES);
  203276. pDropFiles->fWide = true;
  203277. WCHAR* fname = (WCHAR*) (((char*) pDropFiles) + sizeof (DROPFILES));
  203278. for (int i = 0; i < fileNames.size(); ++i)
  203279. {
  203280. fileNames[i].copyToBuffer (fname, 2048);
  203281. fname += fileNames[i].length() + 1;
  203282. }
  203283. *fname = 0;
  203284. GlobalUnlock (hDrop);
  203285. }
  203286. return hDrop;
  203287. }
  203288. static bool performDragDrop (FORMATETC* const format, STGMEDIUM* const medium, const DWORD whatToDo) throw()
  203289. {
  203290. JuceDropSource* const source = new JuceDropSource();
  203291. JuceDataObject* const data = new JuceDataObject (source, format, medium);
  203292. DWORD effect;
  203293. const HRESULT res = DoDragDrop (data, source, whatToDo, &effect);
  203294. data->Release();
  203295. source->Release();
  203296. return res == DRAGDROP_S_DROP;
  203297. }
  203298. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMove)
  203299. {
  203300. FORMATETC format = { CF_HDROP, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  203301. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  203302. medium.hGlobal = createHDrop (files);
  203303. return performDragDrop (&format, &medium, canMove ? (DROPEFFECT_COPY | DROPEFFECT_MOVE)
  203304. : DROPEFFECT_COPY);
  203305. }
  203306. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  203307. {
  203308. FORMATETC format = { CF_TEXT, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  203309. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  203310. const int numChars = text.length();
  203311. medium.hGlobal = GlobalAlloc (GMEM_MOVEABLE | GMEM_ZEROINIT, (numChars + 2) * sizeof (WCHAR));
  203312. char* d = (char*) GlobalLock (medium.hGlobal);
  203313. text.copyToBuffer ((WCHAR*) d, numChars + 1);
  203314. format.cfFormat = CF_UNICODETEXT;
  203315. GlobalUnlock (medium.hGlobal);
  203316. return performDragDrop (&format, &medium, DROPEFFECT_COPY | DROPEFFECT_MOVE);
  203317. }
  203318. #endif
  203319. /********* End of inlined file: juce_win32_Windowing.cpp *********/
  203320. /********* Start of inlined file: juce_win32_Fonts.cpp *********/
  203321. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  203322. // compiled on its own).
  203323. #if JUCE_INCLUDED_FILE
  203324. static int CALLBACK wfontEnum2 (ENUMLOGFONTEXW* lpelfe,
  203325. NEWTEXTMETRICEXW*,
  203326. int type,
  203327. LPARAM lParam)
  203328. {
  203329. if (lpelfe != 0 && (type & RASTER_FONTTYPE) == 0)
  203330. {
  203331. const String fontName (lpelfe->elfLogFont.lfFaceName);
  203332. ((StringArray*) lParam)->addIfNotAlreadyThere (fontName.removeCharacters (T("@")));
  203333. }
  203334. return 1;
  203335. }
  203336. static int CALLBACK wfontEnum1 (ENUMLOGFONTEXW* lpelfe,
  203337. NEWTEXTMETRICEXW*,
  203338. int type,
  203339. LPARAM lParam)
  203340. {
  203341. if (lpelfe != 0 && (type & RASTER_FONTTYPE) == 0)
  203342. {
  203343. LOGFONTW lf;
  203344. zerostruct (lf);
  203345. lf.lfWeight = FW_DONTCARE;
  203346. lf.lfOutPrecision = OUT_OUTLINE_PRECIS;
  203347. lf.lfQuality = DEFAULT_QUALITY;
  203348. lf.lfCharSet = DEFAULT_CHARSET;
  203349. lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  203350. lf.lfPitchAndFamily = FF_DONTCARE;
  203351. const String fontName (lpelfe->elfLogFont.lfFaceName);
  203352. fontName.copyToBuffer (lf.lfFaceName, LF_FACESIZE - 1);
  203353. HDC dc = CreateCompatibleDC (0);
  203354. EnumFontFamiliesEx (dc, &lf,
  203355. (FONTENUMPROCW) &wfontEnum2,
  203356. lParam, 0);
  203357. DeleteDC (dc);
  203358. }
  203359. return 1;
  203360. }
  203361. const StringArray Font::findAllTypefaceNames() throw()
  203362. {
  203363. StringArray results;
  203364. HDC dc = CreateCompatibleDC (0);
  203365. {
  203366. LOGFONTW lf;
  203367. zerostruct (lf);
  203368. lf.lfWeight = FW_DONTCARE;
  203369. lf.lfOutPrecision = OUT_OUTLINE_PRECIS;
  203370. lf.lfQuality = DEFAULT_QUALITY;
  203371. lf.lfCharSet = DEFAULT_CHARSET;
  203372. lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  203373. lf.lfPitchAndFamily = FF_DONTCARE;
  203374. lf.lfFaceName[0] = 0;
  203375. EnumFontFamiliesEx (dc, &lf,
  203376. (FONTENUMPROCW) &wfontEnum1,
  203377. (LPARAM) &results, 0);
  203378. }
  203379. DeleteDC (dc);
  203380. results.sort (true);
  203381. return results;
  203382. }
  203383. extern bool juce_IsRunningInWine() throw();
  203384. void Typeface::getDefaultFontNames (String& defaultSans,
  203385. String& defaultSerif,
  203386. String& defaultFixed) throw()
  203387. {
  203388. if (juce_IsRunningInWine())
  203389. {
  203390. // If we're running in Wine, then use fonts that might be available on Linux..
  203391. defaultSans = "Bitstream Vera Sans";
  203392. defaultSerif = "Bitstream Vera Serif";
  203393. defaultFixed = "Bitstream Vera Sans Mono";
  203394. }
  203395. else
  203396. {
  203397. defaultSans = "Verdana";
  203398. defaultSerif = "Times";
  203399. defaultFixed = "Lucida Console";
  203400. }
  203401. }
  203402. class FontDCHolder : private DeletedAtShutdown
  203403. {
  203404. HDC dc;
  203405. String fontName;
  203406. KERNINGPAIR* kps;
  203407. int numKPs;
  203408. bool bold, italic;
  203409. int size;
  203410. FontDCHolder (const FontDCHolder&);
  203411. const FontDCHolder& operator= (const FontDCHolder&);
  203412. public:
  203413. HFONT fontH;
  203414. FontDCHolder() throw()
  203415. : dc (0),
  203416. kps (0),
  203417. numKPs (0),
  203418. bold (false),
  203419. italic (false),
  203420. size (0)
  203421. {
  203422. }
  203423. ~FontDCHolder() throw()
  203424. {
  203425. if (dc != 0)
  203426. {
  203427. DeleteDC (dc);
  203428. DeleteObject (fontH);
  203429. juce_free (kps);
  203430. }
  203431. clearSingletonInstance();
  203432. }
  203433. juce_DeclareSingleton_SingleThreaded_Minimal (FontDCHolder);
  203434. HDC loadFont (const String& fontName_,
  203435. const bool bold_,
  203436. const bool italic_,
  203437. const int size_) throw()
  203438. {
  203439. if (fontName != fontName_ || bold != bold_ || italic != italic_ || size != size_)
  203440. {
  203441. fontName = fontName_;
  203442. bold = bold_;
  203443. italic = italic_;
  203444. size = size_;
  203445. if (dc != 0)
  203446. {
  203447. DeleteDC (dc);
  203448. DeleteObject (fontH);
  203449. juce_free (kps);
  203450. kps = 0;
  203451. }
  203452. fontH = 0;
  203453. dc = CreateCompatibleDC (0);
  203454. SetMapperFlags (dc, 0);
  203455. SetMapMode (dc, MM_TEXT);
  203456. LOGFONTW lfw;
  203457. zerostruct (lfw);
  203458. lfw.lfCharSet = DEFAULT_CHARSET;
  203459. lfw.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  203460. lfw.lfOutPrecision = OUT_OUTLINE_PRECIS;
  203461. lfw.lfPitchAndFamily = DEFAULT_PITCH | FF_DONTCARE;
  203462. lfw.lfQuality = PROOF_QUALITY;
  203463. lfw.lfItalic = (BYTE) (italic ? TRUE : FALSE);
  203464. lfw.lfWeight = bold ? FW_BOLD : FW_NORMAL;
  203465. fontName.copyToBuffer (lfw.lfFaceName, LF_FACESIZE - 1);
  203466. lfw.lfHeight = size > 0 ? size : -256;
  203467. HFONT standardSizedFont = CreateFontIndirect (&lfw);
  203468. if (standardSizedFont != 0)
  203469. {
  203470. if (SelectObject (dc, standardSizedFont) != 0)
  203471. {
  203472. fontH = standardSizedFont;
  203473. if (size == 0)
  203474. {
  203475. OUTLINETEXTMETRIC otm;
  203476. if (GetOutlineTextMetrics (dc, sizeof (otm), &otm) != 0)
  203477. {
  203478. lfw.lfHeight = -(int) otm.otmEMSquare;
  203479. fontH = CreateFontIndirect (&lfw);
  203480. SelectObject (dc, fontH);
  203481. DeleteObject (standardSizedFont);
  203482. }
  203483. }
  203484. }
  203485. else
  203486. {
  203487. jassertfalse
  203488. }
  203489. }
  203490. else
  203491. {
  203492. jassertfalse
  203493. }
  203494. }
  203495. return dc;
  203496. }
  203497. KERNINGPAIR* getKerningPairs (int& numKPs_) throw()
  203498. {
  203499. if (kps == 0)
  203500. {
  203501. numKPs = GetKerningPairs (dc, 0, 0);
  203502. kps = (KERNINGPAIR*) juce_calloc (sizeof (KERNINGPAIR) * numKPs);
  203503. GetKerningPairs (dc, numKPs, kps);
  203504. }
  203505. numKPs_ = numKPs;
  203506. return kps;
  203507. }
  203508. };
  203509. juce_ImplementSingleton_SingleThreaded (FontDCHolder);
  203510. static bool addGlyphToTypeface (HDC dc,
  203511. juce_wchar character,
  203512. Typeface& dest,
  203513. bool addKerning)
  203514. {
  203515. Path destShape;
  203516. GLYPHMETRICS gm;
  203517. float height;
  203518. BOOL ok = false;
  203519. {
  203520. const WCHAR charToTest[] = { (WCHAR) character, 0 };
  203521. WORD index = 0;
  203522. if (GetGlyphIndices (dc, charToTest, 1, &index, GGI_MARK_NONEXISTING_GLYPHS) != GDI_ERROR
  203523. && index == 0xffff)
  203524. {
  203525. return false;
  203526. }
  203527. }
  203528. TEXTMETRIC tm;
  203529. ok = GetTextMetrics (dc, &tm);
  203530. height = (float) tm.tmHeight;
  203531. if (! ok)
  203532. {
  203533. dest.addGlyph (character, destShape, 0);
  203534. return true;
  203535. }
  203536. const float scaleX = 1.0f / height;
  203537. const float scaleY = -1.0f / height;
  203538. static const MAT2 identityMatrix = { { 0, 1 }, { 0, 0 }, { 0, 0 }, { 0, 1 } };
  203539. const int bufSize = GetGlyphOutline (dc, character, GGO_NATIVE,
  203540. &gm, 0, 0, &identityMatrix);
  203541. if (bufSize > 0)
  203542. {
  203543. char* const data = (char*) juce_malloc (bufSize);
  203544. GetGlyphOutline (dc, character, GGO_NATIVE, &gm,
  203545. bufSize, data, &identityMatrix);
  203546. const TTPOLYGONHEADER* pheader = (TTPOLYGONHEADER*) data;
  203547. while ((char*) pheader < data + bufSize)
  203548. {
  203549. #define remapX(v) (scaleX * (v).x.value)
  203550. #define remapY(v) (scaleY * (v).y.value)
  203551. float x = remapX (pheader->pfxStart);
  203552. float y = remapY (pheader->pfxStart);
  203553. destShape.startNewSubPath (x, y);
  203554. const TTPOLYCURVE* curve = (const TTPOLYCURVE*) ((const char*) pheader + sizeof (TTPOLYGONHEADER));
  203555. const char* const curveEnd = ((const char*) pheader) + pheader->cb;
  203556. while ((const char*) curve < curveEnd)
  203557. {
  203558. if (curve->wType == TT_PRIM_LINE)
  203559. {
  203560. for (int i = 0; i < curve->cpfx; ++i)
  203561. {
  203562. x = remapX (curve->apfx [i]);
  203563. y = remapY (curve->apfx [i]);
  203564. destShape.lineTo (x, y);
  203565. }
  203566. }
  203567. else if (curve->wType == TT_PRIM_QSPLINE)
  203568. {
  203569. for (int i = 0; i < curve->cpfx - 1; ++i)
  203570. {
  203571. const float x2 = remapX (curve->apfx [i]);
  203572. const float y2 = remapY (curve->apfx [i]);
  203573. float x3, y3;
  203574. if (i < curve->cpfx - 2)
  203575. {
  203576. x3 = 0.5f * (x2 + remapX (curve->apfx [i + 1]));
  203577. y3 = 0.5f * (y2 + remapY (curve->apfx [i + 1]));
  203578. }
  203579. else
  203580. {
  203581. x3 = remapX (curve->apfx [i + 1]);
  203582. y3 = remapY (curve->apfx [i + 1]);
  203583. }
  203584. destShape.quadraticTo (x2, y2, x3, y3);
  203585. x = x3;
  203586. y = y3;
  203587. }
  203588. }
  203589. curve = (const TTPOLYCURVE*) &(curve->apfx [curve->cpfx]);
  203590. }
  203591. pheader = (const TTPOLYGONHEADER*) curve;
  203592. destShape.closeSubPath();
  203593. }
  203594. juce_free (data);
  203595. }
  203596. dest.addGlyph (character, destShape, gm.gmCellIncX / height);
  203597. if (addKerning)
  203598. {
  203599. int numKPs;
  203600. const KERNINGPAIR* const kps = FontDCHolder::getInstance()->getKerningPairs (numKPs);
  203601. for (int i = 0; i < numKPs; ++i)
  203602. {
  203603. if (kps[i].wFirst == character)
  203604. {
  203605. dest.addKerningPair (kps[i].wFirst,
  203606. kps[i].wSecond,
  203607. kps[i].iKernAmount / height);
  203608. }
  203609. }
  203610. }
  203611. return true;
  203612. }
  203613. bool Typeface::findAndAddSystemGlyph (juce_wchar character) throw()
  203614. {
  203615. HDC dc = FontDCHolder::getInstance()->loadFont (getName(), isBold(), isItalic(), 0);
  203616. return addGlyphToTypeface (dc, character, *this, true);
  203617. }
  203618. /*Image* Typeface::renderGlyphToImage (juce_wchar character, float& topLeftX, float& topLeftY)
  203619. {
  203620. HDC dc = FontDCHolder::getInstance()->loadFont (getName(), isBold(), isItalic(), hintingSize);
  203621. int bufSize;
  203622. GLYPHMETRICS gm;
  203623. const UINT format = GGO_GRAY2_BITMAP;
  203624. const int shift = 6;
  203625. if (wGetGlyphOutlineW != 0)
  203626. bufSize = wGetGlyphOutlineW (dc, character, format, &gm, 0, 0, &identityMatrix);
  203627. else
  203628. bufSize = GetGlyphOutline (dc, character, format, &gm, 0, 0, &identityMatrix);
  203629. Image* im = new Image (Image::SingleChannel, jmax (1, gm.gmBlackBoxX), jmax (1, gm.gmBlackBoxY), true);
  203630. if (bufSize > 0)
  203631. {
  203632. topLeftX = (float) gm.gmptGlyphOrigin.x;
  203633. topLeftY = (float) -gm.gmptGlyphOrigin.y;
  203634. uint8* const data = (uint8*) juce_calloc (bufSize);
  203635. if (wGetGlyphOutlineW != 0)
  203636. wGetGlyphOutlineW (dc, character, format, &gm, bufSize, data, &identityMatrix);
  203637. else
  203638. GetGlyphOutline (dc, character, format, &gm, bufSize, data, &identityMatrix);
  203639. const int stride = ((gm.gmBlackBoxX + 3) & ~3);
  203640. for (int y = gm.gmBlackBoxY; --y >= 0;)
  203641. {
  203642. for (int x = gm.gmBlackBoxX; --x >= 0;)
  203643. {
  203644. const int level = data [x + y * stride] << shift;
  203645. if (level > 0)
  203646. im->setPixelAt (x, y, Colour ((uint8) 0xff, (uint8) 0xff, (uint8) 0xff, (uint8) jmin (0xff, level)));
  203647. }
  203648. }
  203649. juce_free (data);
  203650. }
  203651. return im;
  203652. }*/
  203653. void Typeface::initialiseTypefaceCharacteristics (const String& fontName,
  203654. bool bold,
  203655. bool italic,
  203656. bool addAllGlyphsToFont) throw()
  203657. {
  203658. clear();
  203659. HDC dc = FontDCHolder::getInstance()->loadFont (fontName, bold, italic, 0);
  203660. float height;
  203661. int firstChar, lastChar;
  203662. {
  203663. TEXTMETRIC tm;
  203664. GetTextMetrics (dc, &tm);
  203665. height = (float) tm.tmHeight;
  203666. firstChar = tm.tmFirstChar;
  203667. lastChar = tm.tmLastChar;
  203668. setAscent (tm.tmAscent / height);
  203669. setDefaultCharacter (tm.tmDefaultChar);
  203670. }
  203671. setName (fontName);
  203672. setBold (bold);
  203673. setItalic (italic);
  203674. if (addAllGlyphsToFont)
  203675. {
  203676. for (int character = firstChar; character <= lastChar; ++character)
  203677. addGlyphToTypeface (dc, (juce_wchar) character, *this, false);
  203678. int numKPs;
  203679. const KERNINGPAIR* const kps = FontDCHolder::getInstance()->getKerningPairs (numKPs);
  203680. for (int i = 0; i < numKPs; ++i)
  203681. {
  203682. addKerningPair (kps[i].wFirst,
  203683. kps[i].wSecond,
  203684. kps[i].iKernAmount / height);
  203685. }
  203686. }
  203687. }
  203688. #endif
  203689. /********* End of inlined file: juce_win32_Fonts.cpp *********/
  203690. /********* Start of inlined file: juce_win32_FileChooser.cpp *********/
  203691. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  203692. // compiled on its own).
  203693. #if JUCE_INCLUDED_FILE
  203694. static const void* defaultDirPath = 0;
  203695. static String returnedString; // need this to get non-existent pathnames from the directory chooser
  203696. static Component* currentExtraFileWin = 0;
  203697. static bool areThereAnyAlwaysOnTopWindows()
  203698. {
  203699. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  203700. {
  203701. Component* c = Desktop::getInstance().getComponent (i);
  203702. if (c != 0 && c->isAlwaysOnTop() && c->isShowing())
  203703. return true;
  203704. }
  203705. return false;
  203706. }
  203707. static int CALLBACK browseCallbackProc (HWND hWnd, UINT msg, LPARAM lParam, LPARAM /*lpData*/)
  203708. {
  203709. if (msg == BFFM_INITIALIZED)
  203710. {
  203711. SendMessage (hWnd, BFFM_SETSELECTIONW, TRUE, (LPARAM) defaultDirPath);
  203712. }
  203713. else if (msg == BFFM_VALIDATEFAILEDW)
  203714. {
  203715. returnedString = (LPCWSTR) lParam;
  203716. }
  203717. else if (msg == BFFM_VALIDATEFAILEDA)
  203718. {
  203719. returnedString = (const char*) lParam;
  203720. }
  203721. return 0;
  203722. }
  203723. void juce_setWindowStyleBit (HWND h, const int styleType, const int feature, const bool bitIsSet) throw();
  203724. static UINT_PTR CALLBACK openCallback (HWND hdlg, UINT uiMsg, WPARAM /*wParam*/, LPARAM lParam)
  203725. {
  203726. if (currentExtraFileWin != 0)
  203727. {
  203728. if (uiMsg == WM_INITDIALOG)
  203729. {
  203730. HWND dialogH = GetParent (hdlg);
  203731. jassert (dialogH != 0);
  203732. if (dialogH == 0)
  203733. dialogH = hdlg;
  203734. RECT r, cr;
  203735. GetWindowRect (dialogH, &r);
  203736. GetClientRect (dialogH, &cr);
  203737. SetWindowPos (dialogH, 0,
  203738. r.left, r.top,
  203739. currentExtraFileWin->getWidth() + jmax (150, r.right - r.left),
  203740. jmax (150, r.bottom - r.top),
  203741. SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER);
  203742. currentExtraFileWin->setBounds (cr.right, cr.top, currentExtraFileWin->getWidth(), cr.bottom - cr.top);
  203743. currentExtraFileWin->getChildComponent(0)->setBounds (0, 0, currentExtraFileWin->getWidth(), currentExtraFileWin->getHeight());
  203744. SetParent ((HWND) currentExtraFileWin->getWindowHandle(), (HWND) dialogH);
  203745. juce_setWindowStyleBit ((HWND)currentExtraFileWin->getWindowHandle(), GWL_STYLE, WS_CHILD, (dialogH != 0));
  203746. juce_setWindowStyleBit ((HWND)currentExtraFileWin->getWindowHandle(), GWL_STYLE, WS_POPUP, (dialogH == 0));
  203747. }
  203748. else if (uiMsg == WM_NOTIFY)
  203749. {
  203750. LPOFNOTIFY ofn = (LPOFNOTIFY) lParam;
  203751. if (ofn->hdr.code == CDN_SELCHANGE)
  203752. {
  203753. FilePreviewComponent* comp = (FilePreviewComponent*) currentExtraFileWin->getChildComponent(0);
  203754. if (comp != 0)
  203755. {
  203756. TCHAR path [MAX_PATH * 2];
  203757. path[0] = 0;
  203758. CommDlg_OpenSave_GetFilePath (GetParent (hdlg), (LPARAM) &path, MAX_PATH);
  203759. const String fn ((const WCHAR*) path);
  203760. comp->selectedFileChanged (File (fn));
  203761. }
  203762. }
  203763. }
  203764. }
  203765. return 0;
  203766. }
  203767. class FPComponentHolder : public Component
  203768. {
  203769. public:
  203770. FPComponentHolder()
  203771. {
  203772. setVisible (true);
  203773. setOpaque (true);
  203774. }
  203775. ~FPComponentHolder()
  203776. {
  203777. }
  203778. void paint (Graphics& g)
  203779. {
  203780. g.fillAll (Colours::lightgrey);
  203781. }
  203782. private:
  203783. FPComponentHolder (const FPComponentHolder&);
  203784. const FPComponentHolder& operator= (const FPComponentHolder&);
  203785. };
  203786. void FileChooser::showPlatformDialog (OwnedArray<File>& results,
  203787. const String& title,
  203788. const File& currentFileOrDirectory,
  203789. const String& filter,
  203790. bool selectsDirectory,
  203791. bool isSaveDialogue,
  203792. bool warnAboutOverwritingExistingFiles,
  203793. bool selectMultipleFiles,
  203794. FilePreviewComponent* extraInfoComponent)
  203795. {
  203796. const int numCharsAvailable = 32768;
  203797. MemoryBlock filenameSpace ((numCharsAvailable + 1) * sizeof (WCHAR), true);
  203798. WCHAR* const fname = (WCHAR*) filenameSpace.getData();
  203799. int fnameIdx = 0;
  203800. JUCE_TRY
  203801. {
  203802. // use a modal window as the parent for this dialog box
  203803. // to block input from other app windows
  203804. const Rectangle mainMon (Desktop::getInstance().getMainMonitorArea());
  203805. Component w (String::empty);
  203806. w.setBounds (mainMon.getX() + mainMon.getWidth() / 4,
  203807. mainMon.getY() + mainMon.getHeight() / 4,
  203808. 0, 0);
  203809. w.setOpaque (true);
  203810. w.setAlwaysOnTop (areThereAnyAlwaysOnTopWindows());
  203811. w.addToDesktop (0);
  203812. if (extraInfoComponent == 0)
  203813. w.enterModalState();
  203814. String initialDir;
  203815. if (currentFileOrDirectory.isDirectory())
  203816. {
  203817. initialDir = currentFileOrDirectory.getFullPathName();
  203818. }
  203819. else
  203820. {
  203821. currentFileOrDirectory.getFileName().copyToBuffer (fname, numCharsAvailable);
  203822. initialDir = currentFileOrDirectory.getParentDirectory().getFullPathName();
  203823. }
  203824. if (currentExtraFileWin->isValidComponent())
  203825. {
  203826. jassertfalse
  203827. return;
  203828. }
  203829. if (selectsDirectory)
  203830. {
  203831. LPITEMIDLIST list = 0;
  203832. filenameSpace.fillWith (0);
  203833. {
  203834. BROWSEINFO bi;
  203835. zerostruct (bi);
  203836. bi.hwndOwner = (HWND) w.getWindowHandle();
  203837. bi.pszDisplayName = fname;
  203838. bi.lpszTitle = title;
  203839. bi.lpfn = browseCallbackProc;
  203840. #ifdef BIF_USENEWUI
  203841. bi.ulFlags = BIF_USENEWUI | BIF_VALIDATE;
  203842. #else
  203843. bi.ulFlags = 0x50;
  203844. #endif
  203845. defaultDirPath = (const WCHAR*) initialDir;
  203846. list = SHBrowseForFolder (&bi);
  203847. if (! SHGetPathFromIDListW (list, fname))
  203848. {
  203849. fname[0] = 0;
  203850. returnedString = String::empty;
  203851. }
  203852. }
  203853. LPMALLOC al;
  203854. if (list != 0 && SUCCEEDED (SHGetMalloc (&al)))
  203855. al->Free (list);
  203856. defaultDirPath = 0;
  203857. if (returnedString.isNotEmpty())
  203858. {
  203859. const String stringFName (fname);
  203860. results.add (new File (File (stringFName).getSiblingFile (returnedString)));
  203861. returnedString = String::empty;
  203862. return;
  203863. }
  203864. }
  203865. else
  203866. {
  203867. DWORD flags = OFN_EXPLORER | OFN_PATHMUSTEXIST | OFN_NOCHANGEDIR | OFN_HIDEREADONLY;
  203868. if (warnAboutOverwritingExistingFiles)
  203869. flags |= OFN_OVERWRITEPROMPT;
  203870. if (selectMultipleFiles)
  203871. flags |= OFN_ALLOWMULTISELECT;
  203872. if (extraInfoComponent != 0)
  203873. {
  203874. flags |= OFN_ENABLEHOOK;
  203875. currentExtraFileWin = new FPComponentHolder();
  203876. currentExtraFileWin->addAndMakeVisible (extraInfoComponent);
  203877. currentExtraFileWin->setSize (jlimit (20, 800, extraInfoComponent->getWidth()),
  203878. extraInfoComponent->getHeight());
  203879. currentExtraFileWin->addToDesktop (0);
  203880. currentExtraFileWin->enterModalState();
  203881. }
  203882. {
  203883. WCHAR filters [1024];
  203884. zeromem (filters, sizeof (filters));
  203885. filter.copyToBuffer (filters, 1024);
  203886. filter.copyToBuffer (filters + filter.length() + 1,
  203887. 1022 - filter.length());
  203888. OPENFILENAMEW of;
  203889. zerostruct (of);
  203890. #ifdef OPENFILENAME_SIZE_VERSION_400W
  203891. of.lStructSize = OPENFILENAME_SIZE_VERSION_400W;
  203892. #else
  203893. of.lStructSize = sizeof (of);
  203894. #endif
  203895. of.hwndOwner = (HWND) w.getWindowHandle();
  203896. of.lpstrFilter = filters;
  203897. of.nFilterIndex = 1;
  203898. of.lpstrFile = fname;
  203899. of.nMaxFile = numCharsAvailable;
  203900. of.lpstrInitialDir = initialDir;
  203901. of.lpstrTitle = title;
  203902. of.Flags = flags;
  203903. if (extraInfoComponent != 0)
  203904. of.lpfnHook = &openCallback;
  203905. if (isSaveDialogue)
  203906. {
  203907. if (! GetSaveFileName (&of))
  203908. fname[0] = 0;
  203909. else
  203910. fnameIdx = of.nFileOffset;
  203911. }
  203912. else
  203913. {
  203914. if (! GetOpenFileName (&of))
  203915. fname[0] = 0;
  203916. else
  203917. fnameIdx = of.nFileOffset;
  203918. }
  203919. }
  203920. }
  203921. }
  203922. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  203923. catch (...)
  203924. {
  203925. fname[0] = 0;
  203926. }
  203927. #endif
  203928. deleteAndZero (currentExtraFileWin);
  203929. const WCHAR* const files = fname;
  203930. if (selectMultipleFiles && fnameIdx > 0 && files [fnameIdx - 1] == 0)
  203931. {
  203932. const WCHAR* filename = files + fnameIdx;
  203933. while (*filename != 0)
  203934. {
  203935. const String filepath (String (files) + T("\\") + String (filename));
  203936. results.add (new File (filepath));
  203937. filename += CharacterFunctions::length (filename) + 1;
  203938. }
  203939. }
  203940. else if (files[0] != 0)
  203941. {
  203942. results.add (new File (files));
  203943. }
  203944. }
  203945. #endif
  203946. /********* End of inlined file: juce_win32_FileChooser.cpp *********/
  203947. /********* Start of inlined file: juce_win32_Misc.cpp *********/
  203948. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  203949. // compiled on its own).
  203950. #if JUCE_INCLUDED_FILE
  203951. void SystemClipboard::copyTextToClipboard (const String& text) throw()
  203952. {
  203953. if (OpenClipboard (0) != 0)
  203954. {
  203955. if (EmptyClipboard() != 0)
  203956. {
  203957. const int len = text.length();
  203958. if (len > 0)
  203959. {
  203960. HGLOBAL bufH = GlobalAlloc (GMEM_MOVEABLE | GMEM_DDESHARE,
  203961. (len + 1) * sizeof (wchar_t));
  203962. if (bufH != 0)
  203963. {
  203964. wchar_t* const data = (wchar_t*) GlobalLock (bufH);
  203965. text.copyToBuffer (data, len);
  203966. GlobalUnlock (bufH);
  203967. SetClipboardData (CF_UNICODETEXT, bufH);
  203968. }
  203969. }
  203970. }
  203971. CloseClipboard();
  203972. }
  203973. }
  203974. const String SystemClipboard::getTextFromClipboard() throw()
  203975. {
  203976. String result;
  203977. if (OpenClipboard (0) != 0)
  203978. {
  203979. HANDLE bufH = GetClipboardData (CF_UNICODETEXT);
  203980. if (bufH != 0)
  203981. {
  203982. const wchar_t* const data = (const wchar_t*) GlobalLock (bufH);
  203983. if (data != 0)
  203984. {
  203985. result = String (data, (int) (GlobalSize (bufH) / sizeof (tchar)));
  203986. GlobalUnlock (bufH);
  203987. }
  203988. }
  203989. CloseClipboard();
  203990. }
  203991. return result;
  203992. }
  203993. #endif
  203994. /********* End of inlined file: juce_win32_Misc.cpp *********/
  203995. /********* Start of inlined file: juce_win32_ActiveXComponent.cpp *********/
  203996. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  203997. // compiled on its own).
  203998. #if JUCE_INCLUDED_FILE
  203999. class JuceIStorage : public IStorage
  204000. {
  204001. int refCount;
  204002. public:
  204003. JuceIStorage() : refCount (1) {}
  204004. virtual ~JuceIStorage()
  204005. {
  204006. jassert (refCount == 0);
  204007. }
  204008. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  204009. {
  204010. if (id == IID_IUnknown || id == IID_IStorage)
  204011. {
  204012. AddRef();
  204013. *result = this;
  204014. return S_OK;
  204015. }
  204016. *result = 0;
  204017. return E_NOINTERFACE;
  204018. }
  204019. ULONG __stdcall AddRef() { return ++refCount; }
  204020. ULONG __stdcall Release() { const int r = --refCount; if (r == 0) delete this; return r; }
  204021. HRESULT __stdcall CreateStream (const WCHAR*, DWORD, DWORD, DWORD, IStream**) { return E_NOTIMPL; }
  204022. HRESULT __stdcall OpenStream (const WCHAR*, void*, DWORD, DWORD, IStream**) { return E_NOTIMPL; }
  204023. HRESULT __stdcall CreateStorage (const WCHAR*, DWORD, DWORD, DWORD, IStorage**) { return E_NOTIMPL; }
  204024. HRESULT __stdcall OpenStorage (const WCHAR*, IStorage*, DWORD, SNB, DWORD, IStorage**) { return E_NOTIMPL; }
  204025. HRESULT __stdcall CopyTo (DWORD, IID const*, SNB, IStorage*) { return E_NOTIMPL; }
  204026. HRESULT __stdcall MoveElementTo (const OLECHAR*,IStorage*, const OLECHAR*, DWORD) { return E_NOTIMPL; }
  204027. HRESULT __stdcall Commit (DWORD) { return E_NOTIMPL; }
  204028. HRESULT __stdcall Revert() { return E_NOTIMPL; }
  204029. HRESULT __stdcall EnumElements (DWORD, void*, DWORD, IEnumSTATSTG**) { return E_NOTIMPL; }
  204030. HRESULT __stdcall DestroyElement (const OLECHAR*) { return E_NOTIMPL; }
  204031. HRESULT __stdcall RenameElement (const WCHAR*, const WCHAR*) { return E_NOTIMPL; }
  204032. HRESULT __stdcall SetElementTimes (const WCHAR*, FILETIME const*, FILETIME const*, FILETIME const*) { return E_NOTIMPL; }
  204033. HRESULT __stdcall SetClass (REFCLSID) { return S_OK; }
  204034. HRESULT __stdcall SetStateBits (DWORD, DWORD) { return E_NOTIMPL; }
  204035. HRESULT __stdcall Stat (STATSTG*, DWORD) { return E_NOTIMPL; }
  204036. juce_UseDebuggingNewOperator
  204037. };
  204038. class JuceOleInPlaceFrame : public IOleInPlaceFrame
  204039. {
  204040. int refCount;
  204041. HWND window;
  204042. public:
  204043. JuceOleInPlaceFrame (HWND window_)
  204044. : refCount (1),
  204045. window (window_)
  204046. {
  204047. }
  204048. virtual ~JuceOleInPlaceFrame()
  204049. {
  204050. jassert (refCount == 0);
  204051. }
  204052. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  204053. {
  204054. if (id == IID_IUnknown || id == IID_IOleInPlaceFrame)
  204055. {
  204056. AddRef();
  204057. *result = this;
  204058. return S_OK;
  204059. }
  204060. *result = 0;
  204061. return E_NOINTERFACE;
  204062. }
  204063. ULONG __stdcall AddRef() { return ++refCount; }
  204064. ULONG __stdcall Release() { const int r = --refCount; if (r == 0) delete this; return r; }
  204065. HRESULT __stdcall GetWindow (HWND* lphwnd) { *lphwnd = window; return S_OK; }
  204066. HRESULT __stdcall ContextSensitiveHelp (BOOL) { return E_NOTIMPL; }
  204067. HRESULT __stdcall GetBorder (LPRECT) { return E_NOTIMPL; }
  204068. HRESULT __stdcall RequestBorderSpace (LPCBORDERWIDTHS) { return E_NOTIMPL; }
  204069. HRESULT __stdcall SetBorderSpace (LPCBORDERWIDTHS) { return E_NOTIMPL; }
  204070. HRESULT __stdcall SetActiveObject (IOleInPlaceActiveObject*, LPCOLESTR) { return S_OK; }
  204071. HRESULT __stdcall InsertMenus (HMENU, LPOLEMENUGROUPWIDTHS) { return E_NOTIMPL; }
  204072. HRESULT __stdcall SetMenu (HMENU, HOLEMENU, HWND) { return S_OK; }
  204073. HRESULT __stdcall RemoveMenus (HMENU) { return E_NOTIMPL; }
  204074. HRESULT __stdcall SetStatusText (LPCOLESTR) { return S_OK; }
  204075. HRESULT __stdcall EnableModeless (BOOL) { return S_OK; }
  204076. HRESULT __stdcall TranslateAccelerator(LPMSG, WORD) { return E_NOTIMPL; }
  204077. juce_UseDebuggingNewOperator
  204078. };
  204079. class JuceIOleInPlaceSite : public IOleInPlaceSite
  204080. {
  204081. int refCount;
  204082. HWND window;
  204083. JuceOleInPlaceFrame* frame;
  204084. public:
  204085. JuceIOleInPlaceSite (HWND window_)
  204086. : refCount (1),
  204087. window (window_)
  204088. {
  204089. frame = new JuceOleInPlaceFrame (window);
  204090. }
  204091. virtual ~JuceIOleInPlaceSite()
  204092. {
  204093. jassert (refCount == 0);
  204094. frame->Release();
  204095. }
  204096. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  204097. {
  204098. if (id == IID_IUnknown || id == IID_IOleInPlaceSite)
  204099. {
  204100. AddRef();
  204101. *result = this;
  204102. return S_OK;
  204103. }
  204104. *result = 0;
  204105. return E_NOINTERFACE;
  204106. }
  204107. ULONG __stdcall AddRef() { return ++refCount; }
  204108. ULONG __stdcall Release() { const int r = --refCount; if (r == 0) delete this; return r; }
  204109. HRESULT __stdcall GetWindow (HWND* lphwnd) { *lphwnd = window; return S_OK; }
  204110. HRESULT __stdcall ContextSensitiveHelp (BOOL) { return E_NOTIMPL; }
  204111. HRESULT __stdcall CanInPlaceActivate() { return S_OK; }
  204112. HRESULT __stdcall OnInPlaceActivate() { return S_OK; }
  204113. HRESULT __stdcall OnUIActivate() { return S_OK; }
  204114. HRESULT __stdcall GetWindowContext (LPOLEINPLACEFRAME* lplpFrame, LPOLEINPLACEUIWINDOW* lplpDoc, LPRECT, LPRECT, LPOLEINPLACEFRAMEINFO lpFrameInfo)
  204115. {
  204116. frame->AddRef();
  204117. *lplpFrame = frame;
  204118. *lplpDoc = 0;
  204119. lpFrameInfo->fMDIApp = FALSE;
  204120. lpFrameInfo->hwndFrame = window;
  204121. lpFrameInfo->haccel = 0;
  204122. lpFrameInfo->cAccelEntries = 0;
  204123. return S_OK;
  204124. }
  204125. HRESULT __stdcall Scroll (SIZE) { return E_NOTIMPL; }
  204126. HRESULT __stdcall OnUIDeactivate (BOOL) { return S_OK; }
  204127. HRESULT __stdcall OnInPlaceDeactivate() { return S_OK; }
  204128. HRESULT __stdcall DiscardUndoState() { return E_NOTIMPL; }
  204129. HRESULT __stdcall DeactivateAndUndo() { return E_NOTIMPL; }
  204130. HRESULT __stdcall OnPosRectChange (LPCRECT) { return S_OK; }
  204131. juce_UseDebuggingNewOperator
  204132. };
  204133. class JuceIOleClientSite : public IOleClientSite
  204134. {
  204135. int refCount;
  204136. JuceIOleInPlaceSite* inplaceSite;
  204137. public:
  204138. JuceIOleClientSite (HWND window)
  204139. : refCount (1)
  204140. {
  204141. inplaceSite = new JuceIOleInPlaceSite (window);
  204142. }
  204143. virtual ~JuceIOleClientSite()
  204144. {
  204145. jassert (refCount == 0);
  204146. inplaceSite->Release();
  204147. }
  204148. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  204149. {
  204150. if (id == IID_IUnknown || id == IID_IOleClientSite)
  204151. {
  204152. AddRef();
  204153. *result = this;
  204154. return S_OK;
  204155. }
  204156. else if (id == IID_IOleInPlaceSite)
  204157. {
  204158. inplaceSite->AddRef();
  204159. *result = inplaceSite;
  204160. return S_OK;
  204161. }
  204162. *result = 0;
  204163. return E_NOINTERFACE;
  204164. }
  204165. ULONG __stdcall AddRef() { return ++refCount; }
  204166. ULONG __stdcall Release() { const int r = --refCount; if (r == 0) delete this; return r; }
  204167. HRESULT __stdcall SaveObject() { return E_NOTIMPL; }
  204168. HRESULT __stdcall GetMoniker (DWORD, DWORD, IMoniker**) { return E_NOTIMPL; }
  204169. HRESULT __stdcall GetContainer (LPOLECONTAINER* ppContainer) { *ppContainer = 0; return E_NOINTERFACE; }
  204170. HRESULT __stdcall ShowObject() { return S_OK; }
  204171. HRESULT __stdcall OnShowWindow (BOOL) { return E_NOTIMPL; }
  204172. HRESULT __stdcall RequestNewObjectLayout() { return E_NOTIMPL; }
  204173. juce_UseDebuggingNewOperator
  204174. };
  204175. class ActiveXControlData : public ComponentMovementWatcher
  204176. {
  204177. ActiveXControlComponent* const owner;
  204178. bool wasShowing;
  204179. public:
  204180. HWND controlHWND;
  204181. IStorage* storage;
  204182. IOleClientSite* clientSite;
  204183. IOleObject* control;
  204184. ActiveXControlData (HWND hwnd,
  204185. ActiveXControlComponent* const owner_)
  204186. : ComponentMovementWatcher (owner_),
  204187. owner (owner_),
  204188. wasShowing (owner_ != 0 && owner_->isShowing()),
  204189. controlHWND (0),
  204190. storage (new JuceIStorage()),
  204191. clientSite (new JuceIOleClientSite (hwnd)),
  204192. control (0)
  204193. {
  204194. }
  204195. ~ActiveXControlData()
  204196. {
  204197. if (control != 0)
  204198. {
  204199. control->Close (OLECLOSE_NOSAVE);
  204200. control->Release();
  204201. }
  204202. clientSite->Release();
  204203. storage->Release();
  204204. }
  204205. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  204206. {
  204207. Component* const topComp = owner->getTopLevelComponent();
  204208. if (topComp->getPeer() != 0)
  204209. {
  204210. int x = 0, y = 0;
  204211. owner->relativePositionToOtherComponent (topComp, x, y);
  204212. owner->setControlBounds (Rectangle (x, y, owner->getWidth(), owner->getHeight()));
  204213. }
  204214. }
  204215. void componentPeerChanged()
  204216. {
  204217. const bool isShowingNow = owner->isShowing();
  204218. if (wasShowing != isShowingNow)
  204219. {
  204220. wasShowing = isShowingNow;
  204221. owner->setControlVisible (isShowingNow);
  204222. }
  204223. componentMovedOrResized (true, true);
  204224. }
  204225. void componentVisibilityChanged (Component&)
  204226. {
  204227. componentPeerChanged();
  204228. }
  204229. static bool doesWindowMatch (const ActiveXControlComponent* const ax, HWND hwnd)
  204230. {
  204231. return ((ActiveXControlData*) ax->control) != 0
  204232. && ((ActiveXControlData*) ax->control)->controlHWND == hwnd;
  204233. }
  204234. };
  204235. static VoidArray activeXComps;
  204236. static HWND getHWND (const ActiveXControlComponent* const component)
  204237. {
  204238. HWND hwnd = 0;
  204239. const IID iid = IID_IOleWindow;
  204240. IOleWindow* const window = (IOleWindow*) component->queryInterface (&iid);
  204241. if (window != 0)
  204242. {
  204243. window->GetWindow (&hwnd);
  204244. window->Release();
  204245. }
  204246. return hwnd;
  204247. }
  204248. static void offerActiveXMouseEventToPeer (ComponentPeer* const peer, HWND hwnd, UINT message, LPARAM lParam)
  204249. {
  204250. RECT activeXRect, peerRect;
  204251. GetWindowRect (hwnd, &activeXRect);
  204252. GetWindowRect ((HWND) peer->getNativeHandle(), &peerRect);
  204253. const int mx = GET_X_LPARAM (lParam) + activeXRect.left - peerRect.left;
  204254. const int my = GET_Y_LPARAM (lParam) + activeXRect.top - peerRect.top;
  204255. const int64 mouseEventTime = getMouseEventTime();
  204256. const int oldModifiers = currentModifiers;
  204257. ModifierKeys::getCurrentModifiersRealtime(); // to update the mouse button flags
  204258. switch (message)
  204259. {
  204260. case WM_MOUSEMOVE:
  204261. if (ModifierKeys (currentModifiers).isAnyMouseButtonDown())
  204262. peer->handleMouseDrag (mx, my, mouseEventTime);
  204263. else
  204264. peer->handleMouseMove (mx, my, mouseEventTime);
  204265. break;
  204266. case WM_LBUTTONDOWN:
  204267. case WM_MBUTTONDOWN:
  204268. case WM_RBUTTONDOWN:
  204269. peer->handleMouseDown (mx, my, mouseEventTime);
  204270. break;
  204271. case WM_LBUTTONUP:
  204272. case WM_MBUTTONUP:
  204273. case WM_RBUTTONUP:
  204274. peer->handleMouseUp (oldModifiers, mx, my, mouseEventTime);
  204275. break;
  204276. default:
  204277. break;
  204278. }
  204279. }
  204280. // intercepts events going to an activeX control, so we can sneakily use the mouse events
  204281. static LRESULT CALLBACK activeXHookWndProc (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
  204282. {
  204283. for (int i = activeXComps.size(); --i >= 0;)
  204284. {
  204285. const ActiveXControlComponent* const ax = (const ActiveXControlComponent*) activeXComps.getUnchecked(i);
  204286. if (ActiveXControlData::doesWindowMatch (ax, hwnd))
  204287. {
  204288. switch (message)
  204289. {
  204290. case WM_MOUSEMOVE:
  204291. case WM_LBUTTONDOWN:
  204292. case WM_MBUTTONDOWN:
  204293. case WM_RBUTTONDOWN:
  204294. case WM_LBUTTONUP:
  204295. case WM_MBUTTONUP:
  204296. case WM_RBUTTONUP:
  204297. case WM_LBUTTONDBLCLK:
  204298. case WM_MBUTTONDBLCLK:
  204299. case WM_RBUTTONDBLCLK:
  204300. if (ax->isShowing())
  204301. {
  204302. ComponentPeer* const peer = ax->getPeer();
  204303. if (peer != 0)
  204304. {
  204305. offerActiveXMouseEventToPeer (peer, hwnd, message, lParam);
  204306. if (! ax->areMouseEventsAllowed())
  204307. return 0;
  204308. }
  204309. }
  204310. break;
  204311. default:
  204312. break;
  204313. }
  204314. return CallWindowProc ((WNDPROC) (ax->originalWndProc), hwnd, message, wParam, lParam);
  204315. }
  204316. }
  204317. return DefWindowProc (hwnd, message, wParam, lParam);
  204318. }
  204319. ActiveXControlComponent::ActiveXControlComponent()
  204320. : originalWndProc (0),
  204321. control (0),
  204322. mouseEventsAllowed (true)
  204323. {
  204324. activeXComps.add (this);
  204325. }
  204326. ActiveXControlComponent::~ActiveXControlComponent()
  204327. {
  204328. deleteControl();
  204329. activeXComps.removeValue (this);
  204330. }
  204331. void ActiveXControlComponent::paint (Graphics& g)
  204332. {
  204333. if (control == 0)
  204334. g.fillAll (Colours::lightgrey);
  204335. }
  204336. bool ActiveXControlComponent::createControl (const void* controlIID)
  204337. {
  204338. deleteControl();
  204339. ComponentPeer* const peer = getPeer();
  204340. // the component must have already been added to a real window when you call this!
  204341. jassert (dynamic_cast <Win32ComponentPeer*> (peer) != 0);
  204342. if (dynamic_cast <Win32ComponentPeer*> (peer) != 0)
  204343. {
  204344. int x = 0, y = 0;
  204345. relativePositionToOtherComponent (getTopLevelComponent(), x, y);
  204346. HWND hwnd = (HWND) peer->getNativeHandle();
  204347. ActiveXControlData* const info = new ActiveXControlData (hwnd, this);
  204348. HRESULT hr;
  204349. if ((hr = OleCreate (*(const IID*) controlIID, IID_IOleObject, 1 /*OLERENDER_DRAW*/, 0,
  204350. info->clientSite, info->storage,
  204351. (void**) &(info->control))) == S_OK)
  204352. {
  204353. info->control->SetHostNames (L"Juce", 0);
  204354. if (OleSetContainedObject (info->control, TRUE) == S_OK)
  204355. {
  204356. RECT rect;
  204357. rect.left = x;
  204358. rect.top = y;
  204359. rect.right = x + getWidth();
  204360. rect.bottom = y + getHeight();
  204361. if (info->control->DoVerb (OLEIVERB_SHOW, 0, info->clientSite, 0, hwnd, &rect) == S_OK)
  204362. {
  204363. control = info;
  204364. setControlBounds (Rectangle (x, y, getWidth(), getHeight()));
  204365. info->controlHWND = getHWND (this);
  204366. if (info->controlHWND != 0)
  204367. {
  204368. originalWndProc = (void*) (pointer_sized_int) GetWindowLongPtr ((HWND) info->controlHWND, GWLP_WNDPROC);
  204369. SetWindowLongPtr ((HWND) info->controlHWND, GWLP_WNDPROC, (LONG_PTR) activeXHookWndProc);
  204370. }
  204371. return true;
  204372. }
  204373. }
  204374. }
  204375. delete info;
  204376. }
  204377. return false;
  204378. }
  204379. void ActiveXControlComponent::deleteControl()
  204380. {
  204381. ActiveXControlData* const info = (ActiveXControlData*) control;
  204382. if (info != 0)
  204383. {
  204384. delete info;
  204385. control = 0;
  204386. originalWndProc = 0;
  204387. }
  204388. }
  204389. void* ActiveXControlComponent::queryInterface (const void* iid) const
  204390. {
  204391. ActiveXControlData* const info = (ActiveXControlData*) control;
  204392. void* result = 0;
  204393. if (info != 0 && info->control != 0
  204394. && info->control->QueryInterface (*(const IID*) iid, &result) == S_OK)
  204395. return result;
  204396. return 0;
  204397. }
  204398. void ActiveXControlComponent::setControlBounds (const Rectangle& newBounds) const
  204399. {
  204400. HWND hwnd = ((ActiveXControlData*) control)->controlHWND;
  204401. if (hwnd != 0)
  204402. MoveWindow (hwnd, newBounds.getX(), newBounds.getY(), newBounds.getWidth(), newBounds.getHeight(), TRUE);
  204403. }
  204404. void ActiveXControlComponent::setControlVisible (const bool shouldBeVisible) const
  204405. {
  204406. HWND hwnd = ((ActiveXControlData*) control)->controlHWND;
  204407. if (hwnd != 0)
  204408. ShowWindow (hwnd, shouldBeVisible ? SW_SHOWNA : SW_HIDE);
  204409. }
  204410. void ActiveXControlComponent::setMouseEventsAllowed (const bool eventsCanReachControl)
  204411. {
  204412. mouseEventsAllowed = eventsCanReachControl;
  204413. }
  204414. #endif
  204415. /********* End of inlined file: juce_win32_ActiveXComponent.cpp *********/
  204416. /********* Start of inlined file: juce_win32_QuickTimeMovieComponent.cpp *********/
  204417. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  204418. // compiled on its own).
  204419. #if JUCE_INCLUDED_FILE && JUCE_QUICKTIME
  204420. using namespace QTOLibrary;
  204421. using namespace QTOControlLib;
  204422. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle);
  204423. static bool isQTAvailable = false;
  204424. struct QTMovieCompInternal
  204425. {
  204426. QTMovieCompInternal()
  204427. : dataHandle (0)
  204428. {
  204429. }
  204430. ~QTMovieCompInternal()
  204431. {
  204432. clearHandle();
  204433. }
  204434. IQTControlPtr qtControlInternal;
  204435. IQTMoviePtr qtMovieInternal;
  204436. Handle dataHandle;
  204437. void clearHandle()
  204438. {
  204439. if (dataHandle != 0)
  204440. {
  204441. DisposeHandle (dataHandle);
  204442. dataHandle = 0;
  204443. }
  204444. }
  204445. };
  204446. #define qtControl (((QTMovieCompInternal*) internal)->qtControlInternal)
  204447. #define qtMovie (((QTMovieCompInternal*) internal)->qtMovieInternal)
  204448. QuickTimeMovieComponent::QuickTimeMovieComponent()
  204449. : movieLoaded (false),
  204450. controllerVisible (true)
  204451. {
  204452. internal = new QTMovieCompInternal();
  204453. setMouseEventsAllowed (false);
  204454. }
  204455. QuickTimeMovieComponent::~QuickTimeMovieComponent()
  204456. {
  204457. closeMovie();
  204458. qtControl = 0;
  204459. deleteControl();
  204460. delete internal;
  204461. internal = 0;
  204462. }
  204463. bool QuickTimeMovieComponent::isQuickTimeAvailable() throw()
  204464. {
  204465. if (! isQTAvailable)
  204466. {
  204467. isQTAvailable = (InitializeQTML (0) == noErr)
  204468. && (EnterMovies() == noErr);
  204469. }
  204470. return isQTAvailable;
  204471. }
  204472. void QuickTimeMovieComponent::createControlIfNeeded()
  204473. {
  204474. if (isShowing() && ! isControlCreated())
  204475. {
  204476. const IID qtIID = __uuidof (QTControl);
  204477. if (createControl (&qtIID))
  204478. {
  204479. const IID qtInterfaceIID = __uuidof (IQTControl);
  204480. qtControl = (IQTControl*) queryInterface (&qtInterfaceIID);
  204481. if (qtControl != 0)
  204482. {
  204483. qtControl->Release(); // it has one ref too many at this point
  204484. qtControl->QuickTimeInitialize();
  204485. qtControl->PutSizing (qtMovieFitsControl);
  204486. if (movieFile != File::nonexistent)
  204487. loadMovie (movieFile, controllerVisible);
  204488. }
  204489. }
  204490. }
  204491. }
  204492. bool QuickTimeMovieComponent::isControlCreated() const
  204493. {
  204494. return isControlOpen();
  204495. }
  204496. bool QuickTimeMovieComponent::loadMovie (InputStream* movieStream,
  204497. const bool isControllerVisible)
  204498. {
  204499. movieFile = File::nonexistent;
  204500. movieLoaded = false;
  204501. qtMovie = 0;
  204502. controllerVisible = isControllerVisible;
  204503. createControlIfNeeded();
  204504. if (isControlCreated())
  204505. {
  204506. if (qtControl != 0)
  204507. {
  204508. qtControl->Put_MovieHandle (0);
  204509. ((QTMovieCompInternal*) internal)->clearHandle();
  204510. Movie movie;
  204511. if (juce_OpenQuickTimeMovieFromStream (movieStream, movie, ((QTMovieCompInternal*) internal)->dataHandle))
  204512. {
  204513. qtControl->Put_MovieHandle ((long) (pointer_sized_int) movie);
  204514. qtMovie = qtControl->GetMovie();
  204515. if (qtMovie != 0)
  204516. qtMovie->PutMovieControllerType (isControllerVisible ? qtMovieControllerTypeStandard
  204517. : qtMovieControllerTypeNone);
  204518. }
  204519. if (movie == 0)
  204520. ((QTMovieCompInternal*) internal)->clearHandle();
  204521. }
  204522. movieLoaded = (qtMovie != 0);
  204523. }
  204524. else
  204525. {
  204526. // You're trying to open a movie when the control hasn't yet been created, probably because
  204527. // you've not yet added this component to a Window and made the whole component hierarchy visible.
  204528. jassertfalse
  204529. }
  204530. delete movieStream;
  204531. return movieLoaded;
  204532. }
  204533. void QuickTimeMovieComponent::closeMovie()
  204534. {
  204535. stop();
  204536. movieFile = File::nonexistent;
  204537. movieLoaded = false;
  204538. qtMovie = 0;
  204539. if (qtControl != 0)
  204540. qtControl->Put_MovieHandle (0);
  204541. ((QTMovieCompInternal*) internal)->clearHandle();
  204542. }
  204543. const File QuickTimeMovieComponent::getCurrentMovieFile() const
  204544. {
  204545. return movieFile;
  204546. }
  204547. bool QuickTimeMovieComponent::isMovieOpen() const
  204548. {
  204549. return movieLoaded;
  204550. }
  204551. double QuickTimeMovieComponent::getMovieDuration() const
  204552. {
  204553. if (qtMovie != 0)
  204554. return qtMovie->GetDuration() / (double) qtMovie->GetTimeScale();
  204555. return 0.0;
  204556. }
  204557. void QuickTimeMovieComponent::getMovieNormalSize (int& width, int& height) const
  204558. {
  204559. if (qtMovie != 0)
  204560. {
  204561. struct QTRECT r = qtMovie->GetNaturalRect();
  204562. width = r.right - r.left;
  204563. height = r.bottom - r.top;
  204564. }
  204565. else
  204566. {
  204567. width = height = 0;
  204568. }
  204569. }
  204570. void QuickTimeMovieComponent::play()
  204571. {
  204572. if (qtMovie != 0)
  204573. qtMovie->Play();
  204574. }
  204575. void QuickTimeMovieComponent::stop()
  204576. {
  204577. if (qtMovie != 0)
  204578. qtMovie->Stop();
  204579. }
  204580. bool QuickTimeMovieComponent::isPlaying() const
  204581. {
  204582. return qtMovie != 0 && qtMovie->GetRate() != 0.0f;
  204583. }
  204584. void QuickTimeMovieComponent::setPosition (const double seconds)
  204585. {
  204586. if (qtMovie != 0)
  204587. qtMovie->PutTime ((long) (seconds * qtMovie->GetTimeScale()));
  204588. }
  204589. double QuickTimeMovieComponent::getPosition() const
  204590. {
  204591. if (qtMovie != 0)
  204592. return qtMovie->GetTime() / (double) qtMovie->GetTimeScale();
  204593. return 0.0;
  204594. }
  204595. void QuickTimeMovieComponent::setSpeed (const float newSpeed)
  204596. {
  204597. if (qtMovie != 0)
  204598. qtMovie->PutRate (newSpeed);
  204599. }
  204600. void QuickTimeMovieComponent::setMovieVolume (const float newVolume)
  204601. {
  204602. if (qtMovie != 0)
  204603. {
  204604. qtMovie->PutAudioVolume (newVolume);
  204605. qtMovie->PutAudioMute (newVolume <= 0);
  204606. }
  204607. }
  204608. float QuickTimeMovieComponent::getMovieVolume() const
  204609. {
  204610. if (qtMovie != 0)
  204611. return qtMovie->GetAudioVolume();
  204612. return 0.0f;
  204613. }
  204614. void QuickTimeMovieComponent::setLooping (const bool shouldLoop)
  204615. {
  204616. if (qtMovie != 0)
  204617. qtMovie->PutLoop (shouldLoop);
  204618. }
  204619. bool QuickTimeMovieComponent::isLooping() const
  204620. {
  204621. return qtMovie != 0 && qtMovie->GetLoop();
  204622. }
  204623. bool QuickTimeMovieComponent::isControllerVisible() const
  204624. {
  204625. return controllerVisible;
  204626. }
  204627. void QuickTimeMovieComponent::parentHierarchyChanged()
  204628. {
  204629. createControlIfNeeded();
  204630. QTCompBaseClass::parentHierarchyChanged();
  204631. }
  204632. void QuickTimeMovieComponent::visibilityChanged()
  204633. {
  204634. createControlIfNeeded();
  204635. QTCompBaseClass::visibilityChanged();
  204636. }
  204637. void QuickTimeMovieComponent::paint (Graphics& g)
  204638. {
  204639. if (! isControlCreated())
  204640. g.fillAll (Colours::black);
  204641. }
  204642. static Handle createHandleDataRef (Handle dataHandle, const char* fileName)
  204643. {
  204644. Handle dataRef = 0;
  204645. OSStatus err = PtrToHand (&dataHandle, &dataRef, sizeof (Handle));
  204646. if (err == noErr)
  204647. {
  204648. Str255 suffix;
  204649. CharacterFunctions::copy ((char*) suffix, fileName, 128);
  204650. StringPtr name = suffix;
  204651. err = PtrAndHand (name, dataRef, name[0] + 1);
  204652. if (err == noErr)
  204653. {
  204654. long atoms[3];
  204655. atoms[0] = EndianU32_NtoB (3 * sizeof (long));
  204656. atoms[1] = EndianU32_NtoB (kDataRefExtensionMacOSFileType);
  204657. atoms[2] = EndianU32_NtoB (MovieFileType);
  204658. err = PtrAndHand (atoms, dataRef, 3 * sizeof (long));
  204659. if (err == noErr)
  204660. return dataRef;
  204661. }
  204662. DisposeHandle (dataRef);
  204663. }
  204664. return 0;
  204665. }
  204666. static CFStringRef juceStringToCFString (const String& s)
  204667. {
  204668. const int len = s.length();
  204669. const juce_wchar* const t = (const juce_wchar*) s;
  204670. UniChar* temp = (UniChar*) juce_malloc (sizeof (UniChar) * len + 4);
  204671. for (int i = 0; i <= len; ++i)
  204672. temp[i] = t[i];
  204673. CFStringRef result = CFStringCreateWithCharacters (kCFAllocatorDefault, temp, len);
  204674. juce_free (temp);
  204675. return result;
  204676. }
  204677. static bool openMovie (QTNewMoviePropertyElement* props, int prop, Movie& movie)
  204678. {
  204679. Boolean trueBool = true;
  204680. props[prop].propClass = kQTPropertyClass_MovieInstantiation;
  204681. props[prop].propID = kQTMovieInstantiationPropertyID_DontResolveDataRefs;
  204682. props[prop].propValueSize = sizeof (trueBool);
  204683. props[prop].propValueAddress = &trueBool;
  204684. ++prop;
  204685. props[prop].propClass = kQTPropertyClass_MovieInstantiation;
  204686. props[prop].propID = kQTMovieInstantiationPropertyID_AsyncOK;
  204687. props[prop].propValueSize = sizeof (trueBool);
  204688. props[prop].propValueAddress = &trueBool;
  204689. ++prop;
  204690. Boolean isActive = true;
  204691. props[prop].propClass = kQTPropertyClass_NewMovieProperty;
  204692. props[prop].propID = kQTNewMoviePropertyID_Active;
  204693. props[prop].propValueSize = sizeof (isActive);
  204694. props[prop].propValueAddress = &isActive;
  204695. ++prop;
  204696. MacSetPort (0);
  204697. jassert (prop <= 5);
  204698. OSStatus err = NewMovieFromProperties (prop, props, 0, 0, &movie);
  204699. return err == noErr;
  204700. }
  204701. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle)
  204702. {
  204703. if (input == 0)
  204704. return false;
  204705. dataHandle = 0;
  204706. bool ok = false;
  204707. QTNewMoviePropertyElement props[5];
  204708. zeromem (props, sizeof (props));
  204709. int prop = 0;
  204710. DataReferenceRecord dr;
  204711. props[prop].propClass = kQTPropertyClass_DataLocation;
  204712. props[prop].propID = kQTDataLocationPropertyID_DataReference;
  204713. props[prop].propValueSize = sizeof (dr);
  204714. props[prop].propValueAddress = (void*) &dr;
  204715. ++prop;
  204716. FileInputStream* const fin = dynamic_cast <FileInputStream*> (input);
  204717. if (fin != 0)
  204718. {
  204719. CFStringRef filePath = juceStringToCFString (fin->getFile().getFullPathName());
  204720. QTNewDataReferenceFromFullPathCFString (filePath, (QTPathStyle) kQTNativeDefaultPathStyle, 0,
  204721. &dr.dataRef, &dr.dataRefType);
  204722. ok = openMovie (props, prop, movie);
  204723. DisposeHandle (dr.dataRef);
  204724. CFRelease (filePath);
  204725. }
  204726. else
  204727. {
  204728. // sanity-check because this currently needs to load the whole stream into memory..
  204729. jassert (input->getTotalLength() < 50 * 1024 * 1024);
  204730. dataHandle = NewHandle ((Size) input->getTotalLength());
  204731. HLock (dataHandle);
  204732. // read the entire stream into memory - this is a pain, but can't get it to work
  204733. // properly using a custom callback to supply the data.
  204734. input->read (*dataHandle, (int) input->getTotalLength());
  204735. HUnlock (dataHandle);
  204736. // different types to get QT to try. (We should really be a bit smarter here by
  204737. // working out in advance which one the stream contains, rather than just trying
  204738. // each one)
  204739. const char* const suffixesToTry[] = { "\04.mov", "\04.mp3",
  204740. "\04.avi", "\04.m4a" };
  204741. for (int i = 0; i < numElementsInArray (suffixesToTry) && ! ok; ++i)
  204742. {
  204743. /* // this fails for some bizarre reason - it can be bodged to work with
  204744. // movies, but can't seem to do it for other file types..
  204745. QTNewMovieUserProcRecord procInfo;
  204746. procInfo.getMovieUserProc = NewGetMovieUPP (readMovieStreamProc);
  204747. procInfo.getMovieUserProcRefcon = this;
  204748. procInfo.defaultDataRef.dataRef = dataRef;
  204749. procInfo.defaultDataRef.dataRefType = HandleDataHandlerSubType;
  204750. props[prop].propClass = kQTPropertyClass_DataLocation;
  204751. props[prop].propID = kQTDataLocationPropertyID_MovieUserProc;
  204752. props[prop].propValueSize = sizeof (procInfo);
  204753. props[prop].propValueAddress = (void*) &procInfo;
  204754. ++prop; */
  204755. dr.dataRef = createHandleDataRef (dataHandle, suffixesToTry [i]);
  204756. dr.dataRefType = HandleDataHandlerSubType;
  204757. ok = openMovie (props, prop, movie);
  204758. DisposeHandle (dr.dataRef);
  204759. }
  204760. }
  204761. return ok;
  204762. }
  204763. bool QuickTimeMovieComponent::loadMovie (const File& movieFile_,
  204764. const bool isControllerVisible)
  204765. {
  204766. const bool ok = loadMovie ((InputStream*) movieFile_.createInputStream(), isControllerVisible);
  204767. movieFile = movieFile_;
  204768. return ok;
  204769. }
  204770. void QuickTimeMovieComponent::goToStart()
  204771. {
  204772. setPosition (0.0);
  204773. }
  204774. void QuickTimeMovieComponent::setBoundsWithCorrectAspectRatio (const Rectangle& spaceToFitWithin,
  204775. const RectanglePlacement& placement)
  204776. {
  204777. int normalWidth, normalHeight;
  204778. getMovieNormalSize (normalWidth, normalHeight);
  204779. if (normalWidth > 0 && normalHeight > 0 && ! spaceToFitWithin.isEmpty())
  204780. {
  204781. double x = 0.0, y = 0.0, w = normalWidth, h = normalHeight;
  204782. placement.applyTo (x, y, w, h,
  204783. spaceToFitWithin.getX(), spaceToFitWithin.getY(),
  204784. spaceToFitWithin.getWidth(), spaceToFitWithin.getHeight());
  204785. if (w > 0 && h > 0)
  204786. {
  204787. setBounds (roundDoubleToInt (x), roundDoubleToInt (y),
  204788. roundDoubleToInt (w), roundDoubleToInt (h));
  204789. }
  204790. }
  204791. else
  204792. {
  204793. setBounds (spaceToFitWithin);
  204794. }
  204795. }
  204796. #endif
  204797. /********* End of inlined file: juce_win32_QuickTimeMovieComponent.cpp *********/
  204798. /********* Start of inlined file: juce_win32_WebBrowserComponent.cpp *********/
  204799. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  204800. // compiled on its own).
  204801. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  204802. class WebBrowserComponentInternal : public ActiveXControlComponent
  204803. {
  204804. public:
  204805. WebBrowserComponentInternal()
  204806. : browser (0),
  204807. connectionPoint (0),
  204808. adviseCookie (0)
  204809. {
  204810. }
  204811. ~WebBrowserComponentInternal()
  204812. {
  204813. if (connectionPoint != 0)
  204814. connectionPoint->Unadvise (adviseCookie);
  204815. if (browser != 0)
  204816. browser->Release();
  204817. }
  204818. void createBrowser()
  204819. {
  204820. createControl (&CLSID_WebBrowser);
  204821. browser = (IWebBrowser2*) queryInterface (&IID_IWebBrowser2);
  204822. IConnectionPointContainer* connectionPointContainer = (IConnectionPointContainer*) queryInterface (&IID_IConnectionPointContainer);
  204823. if (connectionPointContainer != 0)
  204824. {
  204825. connectionPointContainer->FindConnectionPoint (DIID_DWebBrowserEvents2,
  204826. &connectionPoint);
  204827. if (connectionPoint != 0)
  204828. {
  204829. WebBrowserComponent* const owner = dynamic_cast <WebBrowserComponent*> (getParentComponent());
  204830. jassert (owner != 0);
  204831. EventHandler* handler = new EventHandler (owner);
  204832. connectionPoint->Advise (handler, &adviseCookie);
  204833. }
  204834. }
  204835. }
  204836. void goToURL (const String& url,
  204837. const StringArray* headers,
  204838. const MemoryBlock* postData)
  204839. {
  204840. if (browser != 0)
  204841. {
  204842. LPSAFEARRAY sa = 0;
  204843. _variant_t flags, frame, postDataVar, headersVar;
  204844. if (headers != 0)
  204845. headersVar = (const tchar*) headers->joinIntoString ("\r\n");
  204846. if (postData != 0 && postData->getSize() > 0)
  204847. {
  204848. LPSAFEARRAY sa = SafeArrayCreateVector (VT_UI1, 0, postData->getSize());
  204849. if (sa != 0)
  204850. {
  204851. void* data = 0;
  204852. SafeArrayAccessData (sa, &data);
  204853. jassert (data != 0);
  204854. if (data != 0)
  204855. {
  204856. postData->copyTo (data, 0, postData->getSize());
  204857. SafeArrayUnaccessData (sa);
  204858. VARIANT postDataVar2;
  204859. VariantInit (&postDataVar2);
  204860. V_VT (&postDataVar2) = VT_ARRAY | VT_UI1;
  204861. V_ARRAY (&postDataVar2) = sa;
  204862. postDataVar = postDataVar2;
  204863. }
  204864. }
  204865. }
  204866. browser->Navigate ((BSTR) (const OLECHAR*) url,
  204867. &flags, &frame,
  204868. &postDataVar, &headersVar);
  204869. if (sa != 0)
  204870. SafeArrayDestroy (sa);
  204871. }
  204872. }
  204873. IWebBrowser2* browser;
  204874. juce_UseDebuggingNewOperator
  204875. private:
  204876. IConnectionPoint* connectionPoint;
  204877. DWORD adviseCookie;
  204878. class EventHandler : public IDispatch
  204879. {
  204880. public:
  204881. EventHandler (WebBrowserComponent* owner_)
  204882. : owner (owner_),
  204883. refCount (0)
  204884. {
  204885. }
  204886. ~EventHandler()
  204887. {
  204888. }
  204889. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  204890. {
  204891. if (id == IID_IUnknown || id == IID_IDispatch || id == DIID_DWebBrowserEvents2)
  204892. {
  204893. AddRef();
  204894. *result = this;
  204895. return S_OK;
  204896. }
  204897. *result = 0;
  204898. return E_NOINTERFACE;
  204899. }
  204900. ULONG __stdcall AddRef() { return ++refCount; }
  204901. ULONG __stdcall Release() { jassert (refCount > 0); const int r = --refCount; if (r == 0) delete this; return r; }
  204902. HRESULT __stdcall GetTypeInfoCount (UINT __RPC_FAR*) { return E_NOTIMPL; }
  204903. HRESULT __stdcall GetTypeInfo (UINT, LCID, ITypeInfo __RPC_FAR *__RPC_FAR*) { return E_NOTIMPL; }
  204904. HRESULT __stdcall GetIDsOfNames (REFIID, LPOLESTR __RPC_FAR*, UINT, LCID, DISPID __RPC_FAR*) { return E_NOTIMPL; }
  204905. HRESULT __stdcall Invoke (DISPID dispIdMember, REFIID /*riid*/, LCID /*lcid*/,
  204906. WORD /*wFlags*/, DISPPARAMS __RPC_FAR* pDispParams,
  204907. VARIANT __RPC_FAR* /*pVarResult*/, EXCEPINFO __RPC_FAR* /*pExcepInfo*/,
  204908. UINT __RPC_FAR* /*puArgErr*/)
  204909. {
  204910. switch (dispIdMember)
  204911. {
  204912. case DISPID_BEFORENAVIGATE2:
  204913. {
  204914. VARIANT* const vurl = pDispParams->rgvarg[5].pvarVal;
  204915. String url;
  204916. if ((vurl->vt & VT_BYREF) != 0)
  204917. url = *vurl->pbstrVal;
  204918. else
  204919. url = vurl->bstrVal;
  204920. *pDispParams->rgvarg->pboolVal
  204921. = owner->pageAboutToLoad (url) ? VARIANT_FALSE
  204922. : VARIANT_TRUE;
  204923. return S_OK;
  204924. }
  204925. default:
  204926. break;
  204927. }
  204928. return E_NOTIMPL;
  204929. }
  204930. juce_UseDebuggingNewOperator
  204931. private:
  204932. WebBrowserComponent* const owner;
  204933. int refCount;
  204934. EventHandler (const EventHandler&);
  204935. const EventHandler& operator= (const EventHandler&);
  204936. };
  204937. };
  204938. WebBrowserComponent::WebBrowserComponent()
  204939. : browser (0),
  204940. blankPageShown (false)
  204941. {
  204942. setOpaque (true);
  204943. addAndMakeVisible (browser = new WebBrowserComponentInternal());
  204944. }
  204945. WebBrowserComponent::~WebBrowserComponent()
  204946. {
  204947. delete browser;
  204948. }
  204949. void WebBrowserComponent::goToURL (const String& url,
  204950. const StringArray* headers,
  204951. const MemoryBlock* postData)
  204952. {
  204953. lastURL = url;
  204954. lastHeaders.clear();
  204955. if (headers != 0)
  204956. lastHeaders = *headers;
  204957. lastPostData.setSize (0);
  204958. if (postData != 0)
  204959. lastPostData = *postData;
  204960. blankPageShown = false;
  204961. browser->goToURL (url, headers, postData);
  204962. }
  204963. void WebBrowserComponent::stop()
  204964. {
  204965. if (browser->browser != 0)
  204966. browser->browser->Stop();
  204967. }
  204968. void WebBrowserComponent::goBack()
  204969. {
  204970. lastURL = String::empty;
  204971. blankPageShown = false;
  204972. if (browser->browser != 0)
  204973. browser->browser->GoBack();
  204974. }
  204975. void WebBrowserComponent::goForward()
  204976. {
  204977. lastURL = String::empty;
  204978. if (browser->browser != 0)
  204979. browser->browser->GoForward();
  204980. }
  204981. void WebBrowserComponent::refresh()
  204982. {
  204983. if (browser->browser != 0)
  204984. browser->browser->Refresh();
  204985. }
  204986. void WebBrowserComponent::paint (Graphics& g)
  204987. {
  204988. if (browser->browser == 0)
  204989. g.fillAll (Colours::white);
  204990. }
  204991. void WebBrowserComponent::checkWindowAssociation()
  204992. {
  204993. if (isShowing())
  204994. {
  204995. if (browser->browser == 0 && getPeer() != 0)
  204996. {
  204997. browser->createBrowser();
  204998. reloadLastURL();
  204999. }
  205000. else
  205001. {
  205002. if (blankPageShown)
  205003. goBack();
  205004. }
  205005. }
  205006. else
  205007. {
  205008. if (browser != 0 && ! blankPageShown)
  205009. {
  205010. // when the component becomes invisible, some stuff like flash
  205011. // carries on playing audio, so we need to force it onto a blank
  205012. // page to avoid this..
  205013. blankPageShown = true;
  205014. browser->goToURL ("about:blank", 0, 0);
  205015. }
  205016. }
  205017. }
  205018. void WebBrowserComponent::reloadLastURL()
  205019. {
  205020. if (lastURL.isNotEmpty())
  205021. {
  205022. goToURL (lastURL, &lastHeaders, &lastPostData);
  205023. lastURL = String::empty;
  205024. }
  205025. }
  205026. void WebBrowserComponent::parentHierarchyChanged()
  205027. {
  205028. checkWindowAssociation();
  205029. }
  205030. void WebBrowserComponent::resized()
  205031. {
  205032. browser->setSize (getWidth(), getHeight());
  205033. }
  205034. void WebBrowserComponent::visibilityChanged()
  205035. {
  205036. checkWindowAssociation();
  205037. }
  205038. bool WebBrowserComponent::pageAboutToLoad (const String&)
  205039. {
  205040. return true;
  205041. }
  205042. #endif
  205043. /********* End of inlined file: juce_win32_WebBrowserComponent.cpp *********/
  205044. /********* Start of inlined file: juce_win32_OpenGLComponent.cpp *********/
  205045. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  205046. // compiled on its own).
  205047. #if JUCE_INCLUDED_FILE && JUCE_OPENGL
  205048. #define WGL_EXT_FUNCTION_INIT(extType, extFunc) \
  205049. ((extFunc = (extType) wglGetProcAddress (#extFunc)) != 0)
  205050. typedef const char* (WINAPI* PFNWGLGETEXTENSIONSSTRINGARBPROC) (HDC hdc);
  205051. typedef BOOL (WINAPI * PFNWGLGETPIXELFORMATATTRIBIVARBPROC) (HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, const int *piAttributes, int *piValues);
  205052. typedef BOOL (WINAPI * PFNWGLCHOOSEPIXELFORMATARBPROC) (HDC hdc, const int* piAttribIList, const FLOAT *pfAttribFList, UINT nMaxFormats, int *piFormats, UINT *nNumFormats);
  205053. typedef BOOL (WINAPI * PFNWGLSWAPINTERVALEXTPROC) (int interval);
  205054. typedef int (WINAPI * PFNWGLGETSWAPINTERVALEXTPROC) (void);
  205055. #define WGL_NUMBER_PIXEL_FORMATS_ARB 0x2000
  205056. #define WGL_DRAW_TO_WINDOW_ARB 0x2001
  205057. #define WGL_ACCELERATION_ARB 0x2003
  205058. #define WGL_SWAP_METHOD_ARB 0x2007
  205059. #define WGL_SUPPORT_OPENGL_ARB 0x2010
  205060. #define WGL_PIXEL_TYPE_ARB 0x2013
  205061. #define WGL_DOUBLE_BUFFER_ARB 0x2011
  205062. #define WGL_COLOR_BITS_ARB 0x2014
  205063. #define WGL_RED_BITS_ARB 0x2015
  205064. #define WGL_GREEN_BITS_ARB 0x2017
  205065. #define WGL_BLUE_BITS_ARB 0x2019
  205066. #define WGL_ALPHA_BITS_ARB 0x201B
  205067. #define WGL_DEPTH_BITS_ARB 0x2022
  205068. #define WGL_STENCIL_BITS_ARB 0x2023
  205069. #define WGL_FULL_ACCELERATION_ARB 0x2027
  205070. #define WGL_ACCUM_RED_BITS_ARB 0x201E
  205071. #define WGL_ACCUM_GREEN_BITS_ARB 0x201F
  205072. #define WGL_ACCUM_BLUE_BITS_ARB 0x2020
  205073. #define WGL_ACCUM_ALPHA_BITS_ARB 0x2021
  205074. #define WGL_STEREO_ARB 0x2012
  205075. #define WGL_SAMPLE_BUFFERS_ARB 0x2041
  205076. #define WGL_SAMPLES_ARB 0x2042
  205077. #define WGL_TYPE_RGBA_ARB 0x202B
  205078. static void getWglExtensions (HDC dc, StringArray& result) throw()
  205079. {
  205080. PFNWGLGETEXTENSIONSSTRINGARBPROC wglGetExtensionsStringARB = 0;
  205081. if (WGL_EXT_FUNCTION_INIT (PFNWGLGETEXTENSIONSSTRINGARBPROC, wglGetExtensionsStringARB))
  205082. result.addTokens (String (wglGetExtensionsStringARB (dc)), false);
  205083. else
  205084. jassertfalse // If this fails, it may be because you didn't activate the openGL context
  205085. }
  205086. class WindowedGLContext : public OpenGLContext
  205087. {
  205088. public:
  205089. WindowedGLContext (Component* const component_,
  205090. HGLRC contextToShareWith,
  205091. const OpenGLPixelFormat& pixelFormat)
  205092. : renderContext (0),
  205093. nativeWindow (0),
  205094. dc (0),
  205095. component (component_)
  205096. {
  205097. jassert (component != 0);
  205098. createNativeWindow();
  205099. // Use a default pixel format that should be supported everywhere
  205100. PIXELFORMATDESCRIPTOR pfd;
  205101. zerostruct (pfd);
  205102. pfd.nSize = sizeof (pfd);
  205103. pfd.nVersion = 1;
  205104. pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
  205105. pfd.iPixelType = PFD_TYPE_RGBA;
  205106. pfd.cColorBits = 24;
  205107. pfd.cDepthBits = 16;
  205108. const int format = ChoosePixelFormat (dc, &pfd);
  205109. if (format != 0)
  205110. SetPixelFormat (dc, format, &pfd);
  205111. renderContext = wglCreateContext (dc);
  205112. makeActive();
  205113. setPixelFormat (pixelFormat);
  205114. if (contextToShareWith != 0 && renderContext != 0)
  205115. wglShareLists (contextToShareWith, renderContext);
  205116. }
  205117. ~WindowedGLContext()
  205118. {
  205119. makeInactive();
  205120. wglDeleteContext (renderContext);
  205121. ReleaseDC ((HWND) nativeWindow->getNativeHandle(), dc);
  205122. delete nativeWindow;
  205123. }
  205124. bool makeActive() const throw()
  205125. {
  205126. jassert (renderContext != 0);
  205127. return wglMakeCurrent (dc, renderContext) != 0;
  205128. }
  205129. bool makeInactive() const throw()
  205130. {
  205131. return (! isActive()) || (wglMakeCurrent (0, 0) != 0);
  205132. }
  205133. bool isActive() const throw()
  205134. {
  205135. return wglGetCurrentContext() == renderContext;
  205136. }
  205137. const OpenGLPixelFormat getPixelFormat() const
  205138. {
  205139. OpenGLPixelFormat pf;
  205140. makeActive();
  205141. StringArray availableExtensions;
  205142. getWglExtensions (dc, availableExtensions);
  205143. fillInPixelFormatDetails (GetPixelFormat (dc), pf, availableExtensions);
  205144. return pf;
  205145. }
  205146. void* getRawContext() const throw()
  205147. {
  205148. return renderContext;
  205149. }
  205150. bool setPixelFormat (const OpenGLPixelFormat& pixelFormat)
  205151. {
  205152. makeActive();
  205153. PIXELFORMATDESCRIPTOR pfd;
  205154. zerostruct (pfd);
  205155. pfd.nSize = sizeof (pfd);
  205156. pfd.nVersion = 1;
  205157. pfd.dwFlags = PFD_SUPPORT_OPENGL | PFD_DRAW_TO_WINDOW | PFD_DOUBLEBUFFER;
  205158. pfd.iPixelType = PFD_TYPE_RGBA;
  205159. pfd.iLayerType = PFD_MAIN_PLANE;
  205160. pfd.cColorBits = (BYTE) (pixelFormat.redBits + pixelFormat.greenBits + pixelFormat.blueBits);
  205161. pfd.cRedBits = (BYTE) pixelFormat.redBits;
  205162. pfd.cGreenBits = (BYTE) pixelFormat.greenBits;
  205163. pfd.cBlueBits = (BYTE) pixelFormat.blueBits;
  205164. pfd.cAlphaBits = (BYTE) pixelFormat.alphaBits;
  205165. pfd.cDepthBits = (BYTE) pixelFormat.depthBufferBits;
  205166. pfd.cStencilBits = (BYTE) pixelFormat.stencilBufferBits;
  205167. pfd.cAccumBits = (BYTE) (pixelFormat.accumulationBufferRedBits + pixelFormat.accumulationBufferGreenBits
  205168. + pixelFormat.accumulationBufferBlueBits + pixelFormat.accumulationBufferAlphaBits);
  205169. pfd.cAccumRedBits = (BYTE) pixelFormat.accumulationBufferRedBits;
  205170. pfd.cAccumGreenBits = (BYTE) pixelFormat.accumulationBufferGreenBits;
  205171. pfd.cAccumBlueBits = (BYTE) pixelFormat.accumulationBufferBlueBits;
  205172. pfd.cAccumAlphaBits = (BYTE) pixelFormat.accumulationBufferAlphaBits;
  205173. int format = 0;
  205174. PFNWGLCHOOSEPIXELFORMATARBPROC wglChoosePixelFormatARB = 0;
  205175. StringArray availableExtensions;
  205176. getWglExtensions (dc, availableExtensions);
  205177. if (availableExtensions.contains ("WGL_ARB_pixel_format")
  205178. && WGL_EXT_FUNCTION_INIT (PFNWGLCHOOSEPIXELFORMATARBPROC, wglChoosePixelFormatARB))
  205179. {
  205180. int attributes[64];
  205181. int n = 0;
  205182. attributes[n++] = WGL_DRAW_TO_WINDOW_ARB;
  205183. attributes[n++] = GL_TRUE;
  205184. attributes[n++] = WGL_SUPPORT_OPENGL_ARB;
  205185. attributes[n++] = GL_TRUE;
  205186. attributes[n++] = WGL_ACCELERATION_ARB;
  205187. attributes[n++] = WGL_FULL_ACCELERATION_ARB;
  205188. attributes[n++] = WGL_DOUBLE_BUFFER_ARB;
  205189. attributes[n++] = GL_TRUE;
  205190. attributes[n++] = WGL_PIXEL_TYPE_ARB;
  205191. attributes[n++] = WGL_TYPE_RGBA_ARB;
  205192. attributes[n++] = WGL_COLOR_BITS_ARB;
  205193. attributes[n++] = pfd.cColorBits;
  205194. attributes[n++] = WGL_RED_BITS_ARB;
  205195. attributes[n++] = pixelFormat.redBits;
  205196. attributes[n++] = WGL_GREEN_BITS_ARB;
  205197. attributes[n++] = pixelFormat.greenBits;
  205198. attributes[n++] = WGL_BLUE_BITS_ARB;
  205199. attributes[n++] = pixelFormat.blueBits;
  205200. attributes[n++] = WGL_ALPHA_BITS_ARB;
  205201. attributes[n++] = pixelFormat.alphaBits;
  205202. attributes[n++] = WGL_DEPTH_BITS_ARB;
  205203. attributes[n++] = pixelFormat.depthBufferBits;
  205204. if (pixelFormat.stencilBufferBits > 0)
  205205. {
  205206. attributes[n++] = WGL_STENCIL_BITS_ARB;
  205207. attributes[n++] = pixelFormat.stencilBufferBits;
  205208. }
  205209. attributes[n++] = WGL_ACCUM_RED_BITS_ARB;
  205210. attributes[n++] = pixelFormat.accumulationBufferRedBits;
  205211. attributes[n++] = WGL_ACCUM_GREEN_BITS_ARB;
  205212. attributes[n++] = pixelFormat.accumulationBufferGreenBits;
  205213. attributes[n++] = WGL_ACCUM_BLUE_BITS_ARB;
  205214. attributes[n++] = pixelFormat.accumulationBufferBlueBits;
  205215. attributes[n++] = WGL_ACCUM_ALPHA_BITS_ARB;
  205216. attributes[n++] = pixelFormat.accumulationBufferAlphaBits;
  205217. if (availableExtensions.contains ("WGL_ARB_multisample")
  205218. && pixelFormat.fullSceneAntiAliasingNumSamples > 0)
  205219. {
  205220. attributes[n++] = WGL_SAMPLE_BUFFERS_ARB;
  205221. attributes[n++] = 1;
  205222. attributes[n++] = WGL_SAMPLES_ARB;
  205223. attributes[n++] = pixelFormat.fullSceneAntiAliasingNumSamples;
  205224. }
  205225. attributes[n++] = 0;
  205226. UINT formatsCount;
  205227. const BOOL ok = wglChoosePixelFormatARB (dc, attributes, 0, 1, &format, &formatsCount);
  205228. (void) ok;
  205229. jassert (ok);
  205230. }
  205231. else
  205232. {
  205233. format = ChoosePixelFormat (dc, &pfd);
  205234. }
  205235. if (format != 0)
  205236. {
  205237. makeInactive();
  205238. // win32 can't change the pixel format of a window, so need to delete the
  205239. // old one and create a new one..
  205240. jassert (nativeWindow != 0);
  205241. ReleaseDC ((HWND) nativeWindow->getNativeHandle(), dc);
  205242. delete nativeWindow;
  205243. createNativeWindow();
  205244. if (SetPixelFormat (dc, format, &pfd))
  205245. {
  205246. wglDeleteContext (renderContext);
  205247. renderContext = wglCreateContext (dc);
  205248. jassert (renderContext != 0);
  205249. return renderContext != 0;
  205250. }
  205251. }
  205252. return false;
  205253. }
  205254. void updateWindowPosition (int x, int y, int w, int h, int)
  205255. {
  205256. SetWindowPos ((HWND) nativeWindow->getNativeHandle(), 0,
  205257. x, y, w, h,
  205258. SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  205259. }
  205260. void repaint()
  205261. {
  205262. int x, y, w, h;
  205263. nativeWindow->getBounds (x, y, w, h);
  205264. nativeWindow->repaint (0, 0, w, h);
  205265. }
  205266. void swapBuffers()
  205267. {
  205268. SwapBuffers (dc);
  205269. }
  205270. bool setSwapInterval (const int numFramesPerSwap)
  205271. {
  205272. makeActive();
  205273. StringArray availableExtensions;
  205274. getWglExtensions (dc, availableExtensions);
  205275. PFNWGLSWAPINTERVALEXTPROC wglSwapIntervalEXT = 0;
  205276. return availableExtensions.contains ("WGL_EXT_swap_control")
  205277. && WGL_EXT_FUNCTION_INIT (PFNWGLSWAPINTERVALEXTPROC, wglSwapIntervalEXT)
  205278. && wglSwapIntervalEXT (numFramesPerSwap) != FALSE;
  205279. }
  205280. int getSwapInterval() const
  205281. {
  205282. makeActive();
  205283. StringArray availableExtensions;
  205284. getWglExtensions (dc, availableExtensions);
  205285. PFNWGLGETSWAPINTERVALEXTPROC wglGetSwapIntervalEXT = 0;
  205286. if (availableExtensions.contains ("WGL_EXT_swap_control")
  205287. && WGL_EXT_FUNCTION_INIT (PFNWGLGETSWAPINTERVALEXTPROC, wglGetSwapIntervalEXT))
  205288. return wglGetSwapIntervalEXT();
  205289. return 0;
  205290. }
  205291. void findAlternativeOpenGLPixelFormats (OwnedArray <OpenGLPixelFormat>& results)
  205292. {
  205293. jassert (isActive());
  205294. StringArray availableExtensions;
  205295. getWglExtensions (dc, availableExtensions);
  205296. PFNWGLGETPIXELFORMATATTRIBIVARBPROC wglGetPixelFormatAttribivARB = 0;
  205297. int numTypes = 0;
  205298. if (availableExtensions.contains("WGL_ARB_pixel_format")
  205299. && WGL_EXT_FUNCTION_INIT (PFNWGLGETPIXELFORMATATTRIBIVARBPROC, wglGetPixelFormatAttribivARB))
  205300. {
  205301. int attributes = WGL_NUMBER_PIXEL_FORMATS_ARB;
  205302. if (! wglGetPixelFormatAttribivARB (dc, 1, 0, 1, &attributes, &numTypes))
  205303. jassertfalse
  205304. }
  205305. else
  205306. {
  205307. numTypes = DescribePixelFormat (dc, 0, 0, 0);
  205308. }
  205309. OpenGLPixelFormat pf;
  205310. for (int i = 0; i < numTypes; ++i)
  205311. {
  205312. if (fillInPixelFormatDetails (i + 1, pf, availableExtensions))
  205313. {
  205314. bool alreadyListed = false;
  205315. for (int j = results.size(); --j >= 0;)
  205316. if (pf == *results.getUnchecked(j))
  205317. alreadyListed = true;
  205318. if (! alreadyListed)
  205319. results.add (new OpenGLPixelFormat (pf));
  205320. }
  205321. }
  205322. }
  205323. void* getNativeWindowHandle() const
  205324. {
  205325. return nativeWindow != 0 ? nativeWindow->getNativeHandle() : 0;
  205326. }
  205327. juce_UseDebuggingNewOperator
  205328. HGLRC renderContext;
  205329. private:
  205330. Win32ComponentPeer* nativeWindow;
  205331. Component* const component;
  205332. HDC dc;
  205333. void createNativeWindow()
  205334. {
  205335. nativeWindow = new Win32ComponentPeer (component, 0);
  205336. nativeWindow->dontRepaint = true;
  205337. nativeWindow->setVisible (true);
  205338. HWND hwnd = (HWND) nativeWindow->getNativeHandle();
  205339. Win32ComponentPeer* const peer = dynamic_cast <Win32ComponentPeer*> (component->getTopLevelComponent()->getPeer());
  205340. if (peer != 0)
  205341. {
  205342. SetParent (hwnd, (HWND) peer->getNativeHandle());
  205343. juce_setWindowStyleBit (hwnd, GWL_STYLE, WS_CHILD, true);
  205344. juce_setWindowStyleBit (hwnd, GWL_STYLE, WS_POPUP, false);
  205345. }
  205346. dc = GetDC (hwnd);
  205347. }
  205348. bool fillInPixelFormatDetails (const int pixelFormatIndex,
  205349. OpenGLPixelFormat& result,
  205350. const StringArray& availableExtensions) const throw()
  205351. {
  205352. PFNWGLGETPIXELFORMATATTRIBIVARBPROC wglGetPixelFormatAttribivARB = 0;
  205353. if (availableExtensions.contains ("WGL_ARB_pixel_format")
  205354. && WGL_EXT_FUNCTION_INIT (PFNWGLGETPIXELFORMATATTRIBIVARBPROC, wglGetPixelFormatAttribivARB))
  205355. {
  205356. int attributes[32];
  205357. int numAttributes = 0;
  205358. attributes[numAttributes++] = WGL_DRAW_TO_WINDOW_ARB;
  205359. attributes[numAttributes++] = WGL_SUPPORT_OPENGL_ARB;
  205360. attributes[numAttributes++] = WGL_ACCELERATION_ARB;
  205361. attributes[numAttributes++] = WGL_DOUBLE_BUFFER_ARB;
  205362. attributes[numAttributes++] = WGL_PIXEL_TYPE_ARB;
  205363. attributes[numAttributes++] = WGL_RED_BITS_ARB;
  205364. attributes[numAttributes++] = WGL_GREEN_BITS_ARB;
  205365. attributes[numAttributes++] = WGL_BLUE_BITS_ARB;
  205366. attributes[numAttributes++] = WGL_ALPHA_BITS_ARB;
  205367. attributes[numAttributes++] = WGL_DEPTH_BITS_ARB;
  205368. attributes[numAttributes++] = WGL_STENCIL_BITS_ARB;
  205369. attributes[numAttributes++] = WGL_ACCUM_RED_BITS_ARB;
  205370. attributes[numAttributes++] = WGL_ACCUM_GREEN_BITS_ARB;
  205371. attributes[numAttributes++] = WGL_ACCUM_BLUE_BITS_ARB;
  205372. attributes[numAttributes++] = WGL_ACCUM_ALPHA_BITS_ARB;
  205373. if (availableExtensions.contains ("WGL_ARB_multisample"))
  205374. attributes[numAttributes++] = WGL_SAMPLES_ARB;
  205375. int values[32];
  205376. zeromem (values, sizeof (values));
  205377. if (wglGetPixelFormatAttribivARB (dc, pixelFormatIndex, 0, numAttributes, attributes, values))
  205378. {
  205379. int n = 0;
  205380. bool isValidFormat = (values[n++] == GL_TRUE); // WGL_DRAW_TO_WINDOW_ARB
  205381. isValidFormat = (values[n++] == GL_TRUE) && isValidFormat; // WGL_SUPPORT_OPENGL_ARB
  205382. isValidFormat = (values[n++] == WGL_FULL_ACCELERATION_ARB) && isValidFormat; // WGL_ACCELERATION_ARB
  205383. isValidFormat = (values[n++] == GL_TRUE) && isValidFormat; // WGL_DOUBLE_BUFFER_ARB:
  205384. isValidFormat = (values[n++] == WGL_TYPE_RGBA_ARB) && isValidFormat; // WGL_PIXEL_TYPE_ARB
  205385. result.redBits = values[n++]; // WGL_RED_BITS_ARB
  205386. result.greenBits = values[n++]; // WGL_GREEN_BITS_ARB
  205387. result.blueBits = values[n++]; // WGL_BLUE_BITS_ARB
  205388. result.alphaBits = values[n++]; // WGL_ALPHA_BITS_ARB
  205389. result.depthBufferBits = values[n++]; // WGL_DEPTH_BITS_ARB
  205390. result.stencilBufferBits = values[n++]; // WGL_STENCIL_BITS_ARB
  205391. result.accumulationBufferRedBits = values[n++]; // WGL_ACCUM_RED_BITS_ARB
  205392. result.accumulationBufferGreenBits = values[n++]; // WGL_ACCUM_GREEN_BITS_ARB
  205393. result.accumulationBufferBlueBits = values[n++]; // WGL_ACCUM_BLUE_BITS_ARB
  205394. result.accumulationBufferAlphaBits = values[n++]; // WGL_ACCUM_ALPHA_BITS_ARB
  205395. result.fullSceneAntiAliasingNumSamples = (uint8) values[n++]; // WGL_SAMPLES_ARB
  205396. return isValidFormat;
  205397. }
  205398. else
  205399. {
  205400. jassertfalse
  205401. }
  205402. }
  205403. else
  205404. {
  205405. PIXELFORMATDESCRIPTOR pfd;
  205406. if (DescribePixelFormat (dc, pixelFormatIndex, sizeof (pfd), &pfd))
  205407. {
  205408. result.redBits = pfd.cRedBits;
  205409. result.greenBits = pfd.cGreenBits;
  205410. result.blueBits = pfd.cBlueBits;
  205411. result.alphaBits = pfd.cAlphaBits;
  205412. result.depthBufferBits = pfd.cDepthBits;
  205413. result.stencilBufferBits = pfd.cStencilBits;
  205414. result.accumulationBufferRedBits = pfd.cAccumRedBits;
  205415. result.accumulationBufferGreenBits = pfd.cAccumGreenBits;
  205416. result.accumulationBufferBlueBits = pfd.cAccumBlueBits;
  205417. result.accumulationBufferAlphaBits = pfd.cAccumAlphaBits;
  205418. result.fullSceneAntiAliasingNumSamples = 0;
  205419. return true;
  205420. }
  205421. else
  205422. {
  205423. jassertfalse
  205424. }
  205425. }
  205426. return false;
  205427. }
  205428. WindowedGLContext (const WindowedGLContext&);
  205429. const WindowedGLContext& operator= (const WindowedGLContext&);
  205430. };
  205431. OpenGLContext* OpenGLContext::createContextForWindow (Component* const component,
  205432. const OpenGLPixelFormat& pixelFormat,
  205433. const OpenGLContext* const contextToShareWith)
  205434. {
  205435. WindowedGLContext* c = new WindowedGLContext (component,
  205436. contextToShareWith != 0 ? (HGLRC) contextToShareWith->getRawContext() : 0,
  205437. pixelFormat);
  205438. if (c->renderContext == 0)
  205439. deleteAndZero (c);
  205440. return c;
  205441. }
  205442. void* OpenGLComponent::getNativeWindowHandle() const
  205443. {
  205444. return context != 0 ? ((WindowedGLContext*) context)->getNativeWindowHandle() : 0;
  205445. }
  205446. void juce_glViewport (const int w, const int h)
  205447. {
  205448. glViewport (0, 0, w, h);
  205449. }
  205450. void OpenGLPixelFormat::getAvailablePixelFormats (Component* component,
  205451. OwnedArray <OpenGLPixelFormat>& results)
  205452. {
  205453. Component tempComp;
  205454. {
  205455. WindowedGLContext wc (component, 0, OpenGLPixelFormat (8, 8, 16, 0));
  205456. wc.makeActive();
  205457. wc.findAlternativeOpenGLPixelFormats (results);
  205458. }
  205459. }
  205460. #endif
  205461. /********* End of inlined file: juce_win32_OpenGLComponent.cpp *********/
  205462. /********* Start of inlined file: juce_win32_AudioCDReader.cpp *********/
  205463. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  205464. // compiled on its own).
  205465. #if JUCE_INCLUDED_FILE && JUCE_USE_CDBURNER
  205466. //***************************************************************************
  205467. // %%% TARGET STATUS VALUES %%%
  205468. //***************************************************************************
  205469. #define STATUS_GOOD 0x00 // Status Good
  205470. #define STATUS_CHKCOND 0x02 // Check Condition
  205471. #define STATUS_CONDMET 0x04 // Condition Met
  205472. #define STATUS_BUSY 0x08 // Busy
  205473. #define STATUS_INTERM 0x10 // Intermediate
  205474. #define STATUS_INTCDMET 0x14 // Intermediate-condition met
  205475. #define STATUS_RESCONF 0x18 // Reservation conflict
  205476. #define STATUS_COMTERM 0x22 // Command Terminated
  205477. #define STATUS_QFULL 0x28 // Queue full
  205478. //***************************************************************************
  205479. // %%% SCSI MISCELLANEOUS EQUATES %%%
  205480. //***************************************************************************
  205481. #define MAXLUN 7 // Maximum Logical Unit Id
  205482. #define MAXTARG 7 // Maximum Target Id
  205483. #define MAX_SCSI_LUNS 64 // Maximum Number of SCSI LUNs
  205484. #define MAX_NUM_HA 8 // Maximum Number of SCSI HA's
  205485. //***************************************************************************
  205486. // %%% Commands for all Device Types %%%
  205487. //***************************************************************************
  205488. #define SCSI_CHANGE_DEF 0x40 // Change Definition (Optional)
  205489. #define SCSI_COMPARE 0x39 // Compare (O)
  205490. #define SCSI_COPY 0x18 // Copy (O)
  205491. #define SCSI_COP_VERIFY 0x3A // Copy and Verify (O)
  205492. #define SCSI_INQUIRY 0x12 // Inquiry (MANDATORY)
  205493. #define SCSI_LOG_SELECT 0x4C // Log Select (O)
  205494. #define SCSI_LOG_SENSE 0x4D // Log Sense (O)
  205495. #define SCSI_MODE_SEL6 0x15 // Mode Select 6-byte (Device Specific)
  205496. #define SCSI_MODE_SEL10 0x55 // Mode Select 10-byte (Device Specific)
  205497. #define SCSI_MODE_SEN6 0x1A // Mode Sense 6-byte (Device Specific)
  205498. #define SCSI_MODE_SEN10 0x5A // Mode Sense 10-byte (Device Specific)
  205499. #define SCSI_READ_BUFF 0x3C // Read Buffer (O)
  205500. #define SCSI_REQ_SENSE 0x03 // Request Sense (MANDATORY)
  205501. #define SCSI_SEND_DIAG 0x1D // Send Diagnostic (O)
  205502. #define SCSI_TST_U_RDY 0x00 // Test Unit Ready (MANDATORY)
  205503. #define SCSI_WRITE_BUFF 0x3B // Write Buffer (O)
  205504. //***************************************************************************
  205505. // %%% Commands Unique to Direct Access Devices %%%
  205506. //***************************************************************************
  205507. #define SCSI_COMPARE 0x39 // Compare (O)
  205508. #define SCSI_FORMAT 0x04 // Format Unit (MANDATORY)
  205509. #define SCSI_LCK_UN_CAC 0x36 // Lock Unlock Cache (O)
  205510. #define SCSI_PREFETCH 0x34 // Prefetch (O)
  205511. #define SCSI_MED_REMOVL 0x1E // Prevent/Allow medium Removal (O)
  205512. #define SCSI_READ6 0x08 // Read 6-byte (MANDATORY)
  205513. #define SCSI_READ10 0x28 // Read 10-byte (MANDATORY)
  205514. #define SCSI_RD_CAPAC 0x25 // Read Capacity (MANDATORY)
  205515. #define SCSI_RD_DEFECT 0x37 // Read Defect Data (O)
  205516. #define SCSI_READ_LONG 0x3E // Read Long (O)
  205517. #define SCSI_REASS_BLK 0x07 // Reassign Blocks (O)
  205518. #define SCSI_RCV_DIAG 0x1C // Receive Diagnostic Results (O)
  205519. #define SCSI_RELEASE 0x17 // Release Unit (MANDATORY)
  205520. #define SCSI_REZERO 0x01 // Rezero Unit (O)
  205521. #define SCSI_SRCH_DAT_E 0x31 // Search Data Equal (O)
  205522. #define SCSI_SRCH_DAT_H 0x30 // Search Data High (O)
  205523. #define SCSI_SRCH_DAT_L 0x32 // Search Data Low (O)
  205524. #define SCSI_SEEK6 0x0B // Seek 6-Byte (O)
  205525. #define SCSI_SEEK10 0x2B // Seek 10-Byte (O)
  205526. #define SCSI_SEND_DIAG 0x1D // Send Diagnostics (MANDATORY)
  205527. #define SCSI_SET_LIMIT 0x33 // Set Limits (O)
  205528. #define SCSI_START_STP 0x1B // Start/Stop Unit (O)
  205529. #define SCSI_SYNC_CACHE 0x35 // Synchronize Cache (O)
  205530. #define SCSI_VERIFY 0x2F // Verify (O)
  205531. #define SCSI_WRITE6 0x0A // Write 6-Byte (MANDATORY)
  205532. #define SCSI_WRITE10 0x2A // Write 10-Byte (MANDATORY)
  205533. #define SCSI_WRT_VERIFY 0x2E // Write and Verify (O)
  205534. #define SCSI_WRITE_LONG 0x3F // Write Long (O)
  205535. #define SCSI_WRITE_SAME 0x41 // Write Same (O)
  205536. //***************************************************************************
  205537. // %%% Commands Unique to Sequential Access Devices %%%
  205538. //***************************************************************************
  205539. #define SCSI_ERASE 0x19 // Erase (MANDATORY)
  205540. #define SCSI_LOAD_UN 0x1b // Load/Unload (O)
  205541. #define SCSI_LOCATE 0x2B // Locate (O)
  205542. #define SCSI_RD_BLK_LIM 0x05 // Read Block Limits (MANDATORY)
  205543. #define SCSI_READ_POS 0x34 // Read Position (O)
  205544. #define SCSI_READ_REV 0x0F // Read Reverse (O)
  205545. #define SCSI_REC_BF_DAT 0x14 // Recover Buffer Data (O)
  205546. #define SCSI_RESERVE 0x16 // Reserve Unit (MANDATORY)
  205547. #define SCSI_REWIND 0x01 // Rewind (MANDATORY)
  205548. #define SCSI_SPACE 0x11 // Space (MANDATORY)
  205549. #define SCSI_VERIFY_T 0x13 // Verify (Tape) (O)
  205550. #define SCSI_WRT_FILE 0x10 // Write Filemarks (MANDATORY)
  205551. //***************************************************************************
  205552. // %%% Commands Unique to Printer Devices %%%
  205553. //***************************************************************************
  205554. #define SCSI_PRINT 0x0A // Print (MANDATORY)
  205555. #define SCSI_SLEW_PNT 0x0B // Slew and Print (O)
  205556. #define SCSI_STOP_PNT 0x1B // Stop Print (O)
  205557. #define SCSI_SYNC_BUFF 0x10 // Synchronize Buffer (O)
  205558. //***************************************************************************
  205559. // %%% Commands Unique to Processor Devices %%%
  205560. //***************************************************************************
  205561. #define SCSI_RECEIVE 0x08 // Receive (O)
  205562. #define SCSI_SEND 0x0A // Send (O)
  205563. //***************************************************************************
  205564. // %%% Commands Unique to Write-Once Devices %%%
  205565. //***************************************************************************
  205566. #define SCSI_MEDIUM_SCN 0x38 // Medium Scan (O)
  205567. #define SCSI_SRCHDATE10 0x31 // Search Data Equal 10-Byte (O)
  205568. #define SCSI_SRCHDATE12 0xB1 // Search Data Equal 12-Byte (O)
  205569. #define SCSI_SRCHDATH10 0x30 // Search Data High 10-Byte (O)
  205570. #define SCSI_SRCHDATH12 0xB0 // Search Data High 12-Byte (O)
  205571. #define SCSI_SRCHDATL10 0x32 // Search Data Low 10-Byte (O)
  205572. #define SCSI_SRCHDATL12 0xB2 // Search Data Low 12-Byte (O)
  205573. #define SCSI_SET_LIM_10 0x33 // Set Limits 10-Byte (O)
  205574. #define SCSI_SET_LIM_12 0xB3 // Set Limits 10-Byte (O)
  205575. #define SCSI_VERIFY10 0x2F // Verify 10-Byte (O)
  205576. #define SCSI_VERIFY12 0xAF // Verify 12-Byte (O)
  205577. #define SCSI_WRITE12 0xAA // Write 12-Byte (O)
  205578. #define SCSI_WRT_VER10 0x2E // Write and Verify 10-Byte (O)
  205579. #define SCSI_WRT_VER12 0xAE // Write and Verify 12-Byte (O)
  205580. //***************************************************************************
  205581. // %%% Commands Unique to CD-ROM Devices %%%
  205582. //***************************************************************************
  205583. #define SCSI_PLAYAUD_10 0x45 // Play Audio 10-Byte (O)
  205584. #define SCSI_PLAYAUD_12 0xA5 // Play Audio 12-Byte 12-Byte (O)
  205585. #define SCSI_PLAYAUDMSF 0x47 // Play Audio MSF (O)
  205586. #define SCSI_PLAYA_TKIN 0x48 // Play Audio Track/Index (O)
  205587. #define SCSI_PLYTKREL10 0x49 // Play Track Relative 10-Byte (O)
  205588. #define SCSI_PLYTKREL12 0xA9 // Play Track Relative 12-Byte (O)
  205589. #define SCSI_READCDCAP 0x25 // Read CD-ROM Capacity (MANDATORY)
  205590. #define SCSI_READHEADER 0x44 // Read Header (O)
  205591. #define SCSI_SUBCHANNEL 0x42 // Read Subchannel (O)
  205592. #define SCSI_READ_TOC 0x43 // Read TOC (O)
  205593. //***************************************************************************
  205594. // %%% Commands Unique to Scanner Devices %%%
  205595. //***************************************************************************
  205596. #define SCSI_GETDBSTAT 0x34 // Get Data Buffer Status (O)
  205597. #define SCSI_GETWINDOW 0x25 // Get Window (O)
  205598. #define SCSI_OBJECTPOS 0x31 // Object Postion (O)
  205599. #define SCSI_SCAN 0x1B // Scan (O)
  205600. #define SCSI_SETWINDOW 0x24 // Set Window (MANDATORY)
  205601. //***************************************************************************
  205602. // %%% Commands Unique to Optical Memory Devices %%%
  205603. //***************************************************************************
  205604. #define SCSI_UpdateBlk 0x3D // Update Block (O)
  205605. //***************************************************************************
  205606. // %%% Commands Unique to Medium Changer Devices %%%
  205607. //***************************************************************************
  205608. #define SCSI_EXCHMEDIUM 0xA6 // Exchange Medium (O)
  205609. #define SCSI_INITELSTAT 0x07 // Initialize Element Status (O)
  205610. #define SCSI_POSTOELEM 0x2B // Position to Element (O)
  205611. #define SCSI_REQ_VE_ADD 0xB5 // Request Volume Element Address (O)
  205612. #define SCSI_SENDVOLTAG 0xB6 // Send Volume Tag (O)
  205613. //***************************************************************************
  205614. // %%% Commands Unique to Communication Devices %%%
  205615. //***************************************************************************
  205616. #define SCSI_GET_MSG_6 0x08 // Get Message 6-Byte (MANDATORY)
  205617. #define SCSI_GET_MSG_10 0x28 // Get Message 10-Byte (O)
  205618. #define SCSI_GET_MSG_12 0xA8 // Get Message 12-Byte (O)
  205619. #define SCSI_SND_MSG_6 0x0A // Send Message 6-Byte (MANDATORY)
  205620. #define SCSI_SND_MSG_10 0x2A // Send Message 10-Byte (O)
  205621. #define SCSI_SND_MSG_12 0xAA // Send Message 12-Byte (O)
  205622. //***************************************************************************
  205623. // %%% Request Sense Data Format %%%
  205624. //***************************************************************************
  205625. typedef struct {
  205626. BYTE ErrorCode; // Error Code (70H or 71H)
  205627. BYTE SegmentNum; // Number of current segment descriptor
  205628. BYTE SenseKey; // Sense Key(See bit definitions too)
  205629. BYTE InfoByte0; // Information MSB
  205630. BYTE InfoByte1; // Information MID
  205631. BYTE InfoByte2; // Information MID
  205632. BYTE InfoByte3; // Information LSB
  205633. BYTE AddSenLen; // Additional Sense Length
  205634. BYTE ComSpecInf0; // Command Specific Information MSB
  205635. BYTE ComSpecInf1; // Command Specific Information MID
  205636. BYTE ComSpecInf2; // Command Specific Information MID
  205637. BYTE ComSpecInf3; // Command Specific Information LSB
  205638. BYTE AddSenseCode; // Additional Sense Code
  205639. BYTE AddSenQual; // Additional Sense Code Qualifier
  205640. BYTE FieldRepUCode; // Field Replaceable Unit Code
  205641. BYTE SenKeySpec15; // Sense Key Specific 15th byte
  205642. BYTE SenKeySpec16; // Sense Key Specific 16th byte
  205643. BYTE SenKeySpec17; // Sense Key Specific 17th byte
  205644. BYTE AddSenseBytes; // Additional Sense Bytes
  205645. } SENSE_DATA_FMT;
  205646. //***************************************************************************
  205647. // %%% REQUEST SENSE ERROR CODE %%%
  205648. //***************************************************************************
  205649. #define SERROR_CURRENT 0x70 // Current Errors
  205650. #define SERROR_DEFERED 0x71 // Deferred Errors
  205651. //***************************************************************************
  205652. // %%% REQUEST SENSE BIT DEFINITIONS %%%
  205653. //***************************************************************************
  205654. #define SENSE_VALID 0x80 // Byte 0 Bit 7
  205655. #define SENSE_FILEMRK 0x80 // Byte 2 Bit 7
  205656. #define SENSE_EOM 0x40 // Byte 2 Bit 6
  205657. #define SENSE_ILI 0x20 // Byte 2 Bit 5
  205658. //***************************************************************************
  205659. // %%% REQUEST SENSE SENSE KEY DEFINITIONS %%%
  205660. //***************************************************************************
  205661. #define KEY_NOSENSE 0x00 // No Sense
  205662. #define KEY_RECERROR 0x01 // Recovered Error
  205663. #define KEY_NOTREADY 0x02 // Not Ready
  205664. #define KEY_MEDIUMERR 0x03 // Medium Error
  205665. #define KEY_HARDERROR 0x04 // Hardware Error
  205666. #define KEY_ILLGLREQ 0x05 // Illegal Request
  205667. #define KEY_UNITATT 0x06 // Unit Attention
  205668. #define KEY_DATAPROT 0x07 // Data Protect
  205669. #define KEY_BLANKCHK 0x08 // Blank Check
  205670. #define KEY_VENDSPEC 0x09 // Vendor Specific
  205671. #define KEY_COPYABORT 0x0A // Copy Abort
  205672. #define KEY_EQUAL 0x0C // Equal (Search)
  205673. #define KEY_VOLOVRFLW 0x0D // Volume Overflow
  205674. #define KEY_MISCOMP 0x0E // Miscompare (Search)
  205675. #define KEY_RESERVED 0x0F // Reserved
  205676. //***************************************************************************
  205677. // %%% PERIPHERAL DEVICE TYPE DEFINITIONS %%%
  205678. //***************************************************************************
  205679. #define DTYPE_DASD 0x00 // Disk Device
  205680. #define DTYPE_SEQD 0x01 // Tape Device
  205681. #define DTYPE_PRNT 0x02 // Printer
  205682. #define DTYPE_PROC 0x03 // Processor
  205683. #define DTYPE_WORM 0x04 // Write-once read-multiple
  205684. #define DTYPE_CROM 0x05 // CD-ROM device
  205685. #define DTYPE_SCAN 0x06 // Scanner device
  205686. #define DTYPE_OPTI 0x07 // Optical memory device
  205687. #define DTYPE_JUKE 0x08 // Medium Changer device
  205688. #define DTYPE_COMM 0x09 // Communications device
  205689. #define DTYPE_RESL 0x0A // Reserved (low)
  205690. #define DTYPE_RESH 0x1E // Reserved (high)
  205691. #define DTYPE_UNKNOWN 0x1F // Unknown or no device type
  205692. //***************************************************************************
  205693. // %%% ANSI APPROVED VERSION DEFINITIONS %%%
  205694. //***************************************************************************
  205695. #define ANSI_MAYBE 0x0 // Device may or may not be ANSI approved stand
  205696. #define ANSI_SCSI1 0x1 // Device complies to ANSI X3.131-1986 (SCSI-1)
  205697. #define ANSI_SCSI2 0x2 // Device complies to SCSI-2
  205698. #define ANSI_RESLO 0x3 // Reserved (low)
  205699. #define ANSI_RESHI 0x7 // Reserved (high)
  205700. typedef struct
  205701. {
  205702. USHORT Length;
  205703. UCHAR ScsiStatus;
  205704. UCHAR PathId;
  205705. UCHAR TargetId;
  205706. UCHAR Lun;
  205707. UCHAR CdbLength;
  205708. UCHAR SenseInfoLength;
  205709. UCHAR DataIn;
  205710. ULONG DataTransferLength;
  205711. ULONG TimeOutValue;
  205712. ULONG DataBufferOffset;
  205713. ULONG SenseInfoOffset;
  205714. UCHAR Cdb[16];
  205715. } SCSI_PASS_THROUGH, *PSCSI_PASS_THROUGH;
  205716. typedef struct
  205717. {
  205718. USHORT Length;
  205719. UCHAR ScsiStatus;
  205720. UCHAR PathId;
  205721. UCHAR TargetId;
  205722. UCHAR Lun;
  205723. UCHAR CdbLength;
  205724. UCHAR SenseInfoLength;
  205725. UCHAR DataIn;
  205726. ULONG DataTransferLength;
  205727. ULONG TimeOutValue;
  205728. PVOID DataBuffer;
  205729. ULONG SenseInfoOffset;
  205730. UCHAR Cdb[16];
  205731. } SCSI_PASS_THROUGH_DIRECT, *PSCSI_PASS_THROUGH_DIRECT;
  205732. typedef struct
  205733. {
  205734. SCSI_PASS_THROUGH_DIRECT spt;
  205735. ULONG Filler;
  205736. UCHAR ucSenseBuf[32];
  205737. } SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER, *PSCSI_PASS_THROUGH_DIRECT_WITH_BUFFER;
  205738. typedef struct
  205739. {
  205740. ULONG Length;
  205741. UCHAR PortNumber;
  205742. UCHAR PathId;
  205743. UCHAR TargetId;
  205744. UCHAR Lun;
  205745. } SCSI_ADDRESS, *PSCSI_ADDRESS;
  205746. #define METHOD_BUFFERED 0
  205747. #define METHOD_IN_DIRECT 1
  205748. #define METHOD_OUT_DIRECT 2
  205749. #define METHOD_NEITHER 3
  205750. #define FILE_ANY_ACCESS 0
  205751. #ifndef FILE_READ_ACCESS
  205752. #define FILE_READ_ACCESS (0x0001)
  205753. #endif
  205754. #ifndef FILE_WRITE_ACCESS
  205755. #define FILE_WRITE_ACCESS (0x0002)
  205756. #endif
  205757. #define IOCTL_SCSI_BASE 0x00000004
  205758. #define SCSI_IOCTL_DATA_OUT 0
  205759. #define SCSI_IOCTL_DATA_IN 1
  205760. #define SCSI_IOCTL_DATA_UNSPECIFIED 2
  205761. #define CTL_CODE2( DevType, Function, Method, Access ) ( \
  205762. ((DevType) << 16) | ((Access) << 14) | ((Function) << 2) | (Method) \
  205763. )
  205764. #define IOCTL_SCSI_PASS_THROUGH CTL_CODE2( IOCTL_SCSI_BASE, 0x0401, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS )
  205765. #define IOCTL_SCSI_GET_CAPABILITIES CTL_CODE2( IOCTL_SCSI_BASE, 0x0404, METHOD_BUFFERED, FILE_ANY_ACCESS)
  205766. #define IOCTL_SCSI_PASS_THROUGH_DIRECT CTL_CODE2( IOCTL_SCSI_BASE, 0x0405, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS )
  205767. #define IOCTL_SCSI_GET_ADDRESS CTL_CODE2( IOCTL_SCSI_BASE, 0x0406, METHOD_BUFFERED, FILE_ANY_ACCESS )
  205768. #define SENSE_LEN 14
  205769. #define SRB_DIR_SCSI 0x00
  205770. #define SRB_POSTING 0x01
  205771. #define SRB_ENABLE_RESIDUAL_COUNT 0x04
  205772. #define SRB_DIR_IN 0x08
  205773. #define SRB_DIR_OUT 0x10
  205774. #define SRB_EVENT_NOTIFY 0x40
  205775. #define RESIDUAL_COUNT_SUPPORTED 0x02
  205776. #define MAX_SRB_TIMEOUT 1080001u
  205777. #define DEFAULT_SRB_TIMEOUT 1080001u
  205778. #define SC_HA_INQUIRY 0x00
  205779. #define SC_GET_DEV_TYPE 0x01
  205780. #define SC_EXEC_SCSI_CMD 0x02
  205781. #define SC_ABORT_SRB 0x03
  205782. #define SC_RESET_DEV 0x04
  205783. #define SC_SET_HA_PARMS 0x05
  205784. #define SC_GET_DISK_INFO 0x06
  205785. #define SC_RESCAN_SCSI_BUS 0x07
  205786. #define SC_GETSET_TIMEOUTS 0x08
  205787. #define SS_PENDING 0x00
  205788. #define SS_COMP 0x01
  205789. #define SS_ABORTED 0x02
  205790. #define SS_ABORT_FAIL 0x03
  205791. #define SS_ERR 0x04
  205792. #define SS_INVALID_CMD 0x80
  205793. #define SS_INVALID_HA 0x81
  205794. #define SS_NO_DEVICE 0x82
  205795. #define SS_INVALID_SRB 0xE0
  205796. #define SS_OLD_MANAGER 0xE1
  205797. #define SS_BUFFER_ALIGN 0xE1
  205798. #define SS_ILLEGAL_MODE 0xE2
  205799. #define SS_NO_ASPI 0xE3
  205800. #define SS_FAILED_INIT 0xE4
  205801. #define SS_ASPI_IS_BUSY 0xE5
  205802. #define SS_BUFFER_TO_BIG 0xE6
  205803. #define SS_BUFFER_TOO_BIG 0xE6
  205804. #define SS_MISMATCHED_COMPONENTS 0xE7
  205805. #define SS_NO_ADAPTERS 0xE8
  205806. #define SS_INSUFFICIENT_RESOURCES 0xE9
  205807. #define SS_ASPI_IS_SHUTDOWN 0xEA
  205808. #define SS_BAD_INSTALL 0xEB
  205809. #define HASTAT_OK 0x00
  205810. #define HASTAT_SEL_TO 0x11
  205811. #define HASTAT_DO_DU 0x12
  205812. #define HASTAT_BUS_FREE 0x13
  205813. #define HASTAT_PHASE_ERR 0x14
  205814. #define HASTAT_TIMEOUT 0x09
  205815. #define HASTAT_COMMAND_TIMEOUT 0x0B
  205816. #define HASTAT_MESSAGE_REJECT 0x0D
  205817. #define HASTAT_BUS_RESET 0x0E
  205818. #define HASTAT_PARITY_ERROR 0x0F
  205819. #define HASTAT_REQUEST_SENSE_FAILED 0x10
  205820. #define PACKED
  205821. #pragma pack(1)
  205822. typedef struct
  205823. {
  205824. BYTE SRB_Cmd;
  205825. BYTE SRB_Status;
  205826. BYTE SRB_HaID;
  205827. BYTE SRB_Flags;
  205828. DWORD SRB_Hdr_Rsvd;
  205829. BYTE HA_Count;
  205830. BYTE HA_SCSI_ID;
  205831. BYTE HA_ManagerId[16];
  205832. BYTE HA_Identifier[16];
  205833. BYTE HA_Unique[16];
  205834. WORD HA_Rsvd1;
  205835. BYTE pad[20];
  205836. } PACKED SRB_HAInquiry, *PSRB_HAInquiry, FAR *LPSRB_HAInquiry;
  205837. typedef struct
  205838. {
  205839. BYTE SRB_Cmd;
  205840. BYTE SRB_Status;
  205841. BYTE SRB_HaID;
  205842. BYTE SRB_Flags;
  205843. DWORD SRB_Hdr_Rsvd;
  205844. BYTE SRB_Target;
  205845. BYTE SRB_Lun;
  205846. BYTE SRB_DeviceType;
  205847. BYTE SRB_Rsvd1;
  205848. BYTE pad[68];
  205849. } PACKED SRB_GDEVBlock, *PSRB_GDEVBlock, FAR *LPSRB_GDEVBlock;
  205850. typedef struct
  205851. {
  205852. BYTE SRB_Cmd;
  205853. BYTE SRB_Status;
  205854. BYTE SRB_HaID;
  205855. BYTE SRB_Flags;
  205856. DWORD SRB_Hdr_Rsvd;
  205857. BYTE SRB_Target;
  205858. BYTE SRB_Lun;
  205859. WORD SRB_Rsvd1;
  205860. DWORD SRB_BufLen;
  205861. BYTE FAR *SRB_BufPointer;
  205862. BYTE SRB_SenseLen;
  205863. BYTE SRB_CDBLen;
  205864. BYTE SRB_HaStat;
  205865. BYTE SRB_TargStat;
  205866. VOID FAR *SRB_PostProc;
  205867. BYTE SRB_Rsvd2[20];
  205868. BYTE CDBByte[16];
  205869. BYTE SenseArea[SENSE_LEN+2];
  205870. } PACKED SRB_ExecSCSICmd, *PSRB_ExecSCSICmd, FAR *LPSRB_ExecSCSICmd;
  205871. typedef struct
  205872. {
  205873. BYTE SRB_Cmd;
  205874. BYTE SRB_Status;
  205875. BYTE SRB_HaId;
  205876. BYTE SRB_Flags;
  205877. DWORD SRB_Hdr_Rsvd;
  205878. } PACKED SRB, *PSRB, FAR *LPSRB;
  205879. #pragma pack()
  205880. struct CDDeviceInfo
  205881. {
  205882. char vendor[9];
  205883. char productId[17];
  205884. char rev[5];
  205885. char vendorSpec[21];
  205886. BYTE ha;
  205887. BYTE tgt;
  205888. BYTE lun;
  205889. char scsiDriveLetter; // will be 0 if not using scsi
  205890. };
  205891. class CDReadBuffer
  205892. {
  205893. public:
  205894. int startFrame;
  205895. int numFrames;
  205896. int dataStartOffset;
  205897. int dataLength;
  205898. BYTE* buffer;
  205899. int bufferSize;
  205900. int index;
  205901. bool wantsIndex;
  205902. CDReadBuffer (const int numberOfFrames)
  205903. : startFrame (0),
  205904. numFrames (0),
  205905. dataStartOffset (0),
  205906. dataLength (0),
  205907. index (0),
  205908. wantsIndex (false)
  205909. {
  205910. bufferSize = 2352 * numberOfFrames;
  205911. buffer = (BYTE*) malloc (bufferSize);
  205912. }
  205913. ~CDReadBuffer()
  205914. {
  205915. free (buffer);
  205916. }
  205917. bool isZero() const
  205918. {
  205919. BYTE* p = buffer + dataStartOffset;
  205920. for (int i = dataLength; --i >= 0;)
  205921. if (*p++ != 0)
  205922. return false;
  205923. return true;
  205924. }
  205925. };
  205926. class CDDeviceHandle;
  205927. class CDController
  205928. {
  205929. public:
  205930. CDController();
  205931. virtual ~CDController();
  205932. virtual bool read (CDReadBuffer* t) = 0;
  205933. virtual void shutDown();
  205934. bool readAudio (CDReadBuffer* t, CDReadBuffer* overlapBuffer = 0);
  205935. int getLastIndex();
  205936. public:
  205937. bool initialised;
  205938. CDDeviceHandle* deviceInfo;
  205939. int framesToCheck, framesOverlap;
  205940. void prepare (SRB_ExecSCSICmd& s);
  205941. void perform (SRB_ExecSCSICmd& s);
  205942. void setPaused (bool paused);
  205943. };
  205944. #pragma pack(1)
  205945. struct TOCTRACK
  205946. {
  205947. BYTE rsvd;
  205948. BYTE ADR;
  205949. BYTE trackNumber;
  205950. BYTE rsvd2;
  205951. BYTE addr[4];
  205952. };
  205953. struct TOC
  205954. {
  205955. WORD tocLen;
  205956. BYTE firstTrack;
  205957. BYTE lastTrack;
  205958. TOCTRACK tracks[100];
  205959. };
  205960. #pragma pack()
  205961. enum
  205962. {
  205963. READTYPE_ANY = 0,
  205964. READTYPE_ATAPI1 = 1,
  205965. READTYPE_ATAPI2 = 2,
  205966. READTYPE_READ6 = 3,
  205967. READTYPE_READ10 = 4,
  205968. READTYPE_READ_D8 = 5,
  205969. READTYPE_READ_D4 = 6,
  205970. READTYPE_READ_D4_1 = 7,
  205971. READTYPE_READ10_2 = 8
  205972. };
  205973. class CDDeviceHandle
  205974. {
  205975. public:
  205976. CDDeviceHandle (const CDDeviceInfo* const device)
  205977. : scsiHandle (0),
  205978. readType (READTYPE_ANY),
  205979. controller (0)
  205980. {
  205981. memcpy (&info, device, sizeof (info));
  205982. }
  205983. ~CDDeviceHandle()
  205984. {
  205985. if (controller != 0)
  205986. {
  205987. controller->shutDown();
  205988. delete controller;
  205989. }
  205990. if (scsiHandle != 0)
  205991. CloseHandle (scsiHandle);
  205992. }
  205993. bool readTOC (TOC* lpToc, bool useMSF);
  205994. bool readAudio (CDReadBuffer* buffer, CDReadBuffer* overlapBuffer = 0);
  205995. void openDrawer (bool shouldBeOpen);
  205996. CDDeviceInfo info;
  205997. HANDLE scsiHandle;
  205998. BYTE readType;
  205999. private:
  206000. CDController* controller;
  206001. bool testController (const int readType,
  206002. CDController* const newController,
  206003. CDReadBuffer* const bufferToUse);
  206004. };
  206005. DWORD (*fGetASPI32SupportInfo)(void);
  206006. DWORD (*fSendASPI32Command)(LPSRB);
  206007. static HINSTANCE winAspiLib = 0;
  206008. static bool usingScsi = false;
  206009. static bool initialised = false;
  206010. static bool InitialiseCDRipper()
  206011. {
  206012. if (! initialised)
  206013. {
  206014. initialised = true;
  206015. OSVERSIONINFO info;
  206016. info.dwOSVersionInfoSize = sizeof (info);
  206017. GetVersionEx (&info);
  206018. usingScsi = (info.dwPlatformId == VER_PLATFORM_WIN32_NT) && (info.dwMajorVersion > 4);
  206019. if (! usingScsi)
  206020. {
  206021. fGetASPI32SupportInfo = 0;
  206022. fSendASPI32Command = 0;
  206023. winAspiLib = LoadLibrary (_T("WNASPI32.DLL"));
  206024. if (winAspiLib != 0)
  206025. {
  206026. fGetASPI32SupportInfo = (DWORD(*)(void)) GetProcAddress (winAspiLib, "GetASPI32SupportInfo");
  206027. fSendASPI32Command = (DWORD(*)(LPSRB)) GetProcAddress (winAspiLib, "SendASPI32Command");
  206028. if (fGetASPI32SupportInfo == 0 || fSendASPI32Command == 0)
  206029. return false;
  206030. }
  206031. else
  206032. {
  206033. usingScsi = true;
  206034. }
  206035. }
  206036. }
  206037. return true;
  206038. }
  206039. static void DeinitialiseCDRipper()
  206040. {
  206041. if (winAspiLib != 0)
  206042. {
  206043. fGetASPI32SupportInfo = 0;
  206044. fSendASPI32Command = 0;
  206045. FreeLibrary (winAspiLib);
  206046. winAspiLib = 0;
  206047. }
  206048. initialised = false;
  206049. }
  206050. static HANDLE CreateSCSIDeviceHandle (char driveLetter)
  206051. {
  206052. TCHAR devicePath[8];
  206053. devicePath[0] = '\\';
  206054. devicePath[1] = '\\';
  206055. devicePath[2] = '.';
  206056. devicePath[3] = '\\';
  206057. devicePath[4] = driveLetter;
  206058. devicePath[5] = ':';
  206059. devicePath[6] = 0;
  206060. OSVERSIONINFO info;
  206061. info.dwOSVersionInfoSize = sizeof (info);
  206062. GetVersionEx (&info);
  206063. DWORD flags = GENERIC_READ;
  206064. if ((info.dwPlatformId == VER_PLATFORM_WIN32_NT) && (info.dwMajorVersion > 4))
  206065. flags = GENERIC_READ | GENERIC_WRITE;
  206066. HANDLE h = CreateFile (devicePath, flags, FILE_SHARE_WRITE | FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
  206067. if (h == INVALID_HANDLE_VALUE)
  206068. {
  206069. flags ^= GENERIC_WRITE;
  206070. h = CreateFile (devicePath, flags, FILE_SHARE_WRITE | FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
  206071. }
  206072. return h;
  206073. }
  206074. static DWORD performScsiPassThroughCommand (const LPSRB_ExecSCSICmd srb,
  206075. const char driveLetter,
  206076. HANDLE& deviceHandle,
  206077. const bool retryOnFailure = true)
  206078. {
  206079. SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER s;
  206080. zerostruct (s);
  206081. s.spt.Length = sizeof (SCSI_PASS_THROUGH);
  206082. s.spt.CdbLength = srb->SRB_CDBLen;
  206083. s.spt.DataIn = (BYTE) ((srb->SRB_Flags & SRB_DIR_IN)
  206084. ? SCSI_IOCTL_DATA_IN
  206085. : ((srb->SRB_Flags & SRB_DIR_OUT)
  206086. ? SCSI_IOCTL_DATA_OUT
  206087. : SCSI_IOCTL_DATA_UNSPECIFIED));
  206088. s.spt.DataTransferLength = srb->SRB_BufLen;
  206089. s.spt.TimeOutValue = 5;
  206090. s.spt.DataBuffer = srb->SRB_BufPointer;
  206091. s.spt.SenseInfoOffset = offsetof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER, ucSenseBuf);
  206092. memcpy (s.spt.Cdb, srb->CDBByte, srb->SRB_CDBLen);
  206093. srb->SRB_Status = SS_ERR;
  206094. srb->SRB_TargStat = 0x0004;
  206095. DWORD bytesReturned = 0;
  206096. if (DeviceIoControl (deviceHandle, IOCTL_SCSI_PASS_THROUGH_DIRECT,
  206097. &s, sizeof (s),
  206098. &s, sizeof (s),
  206099. &bytesReturned, 0) != 0)
  206100. {
  206101. srb->SRB_Status = SS_COMP;
  206102. }
  206103. else if (retryOnFailure)
  206104. {
  206105. const DWORD error = GetLastError();
  206106. if ((error == ERROR_MEDIA_CHANGED) || (error == ERROR_INVALID_HANDLE))
  206107. {
  206108. if (error != ERROR_INVALID_HANDLE)
  206109. CloseHandle (deviceHandle);
  206110. deviceHandle = CreateSCSIDeviceHandle (driveLetter);
  206111. return performScsiPassThroughCommand (srb, driveLetter, deviceHandle, false);
  206112. }
  206113. }
  206114. return srb->SRB_Status;
  206115. }
  206116. // Controller types..
  206117. class ControllerType1 : public CDController
  206118. {
  206119. public:
  206120. ControllerType1() {}
  206121. ~ControllerType1() {}
  206122. bool read (CDReadBuffer* rb)
  206123. {
  206124. if (rb->numFrames * 2352 > rb->bufferSize)
  206125. return false;
  206126. SRB_ExecSCSICmd s;
  206127. prepare (s);
  206128. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  206129. s.SRB_BufLen = rb->bufferSize;
  206130. s.SRB_BufPointer = rb->buffer;
  206131. s.SRB_CDBLen = 12;
  206132. s.CDBByte[0] = 0xBE;
  206133. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  206134. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  206135. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  206136. s.CDBByte[8] = (BYTE)(rb->numFrames & 0xFF);
  206137. s.CDBByte[9] = (BYTE)((deviceInfo->readType == READTYPE_ATAPI1) ? 0x10 : 0xF0);
  206138. perform (s);
  206139. if (s.SRB_Status != SS_COMP)
  206140. return false;
  206141. rb->dataLength = rb->numFrames * 2352;
  206142. rb->dataStartOffset = 0;
  206143. return true;
  206144. }
  206145. };
  206146. class ControllerType2 : public CDController
  206147. {
  206148. public:
  206149. ControllerType2() {}
  206150. ~ControllerType2() {}
  206151. void shutDown()
  206152. {
  206153. if (initialised)
  206154. {
  206155. BYTE bufPointer[] = { 0, 0, 0, 8, 83, 0, 0, 0, 0, 0, 8, 0 };
  206156. SRB_ExecSCSICmd s;
  206157. prepare (s);
  206158. s.SRB_Flags = SRB_EVENT_NOTIFY | SRB_ENABLE_RESIDUAL_COUNT;
  206159. s.SRB_BufLen = 0x0C;
  206160. s.SRB_BufPointer = bufPointer;
  206161. s.SRB_CDBLen = 6;
  206162. s.CDBByte[0] = 0x15;
  206163. s.CDBByte[4] = 0x0C;
  206164. perform (s);
  206165. }
  206166. }
  206167. bool init()
  206168. {
  206169. SRB_ExecSCSICmd s;
  206170. s.SRB_Status = SS_ERR;
  206171. if (deviceInfo->readType == READTYPE_READ10_2)
  206172. {
  206173. BYTE bufPointer1[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48, 35, 6, 0, 0, 0, 0, 0, 128 };
  206174. BYTE bufPointer2[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48, 1, 6, 32, 7, 0, 0, 0, 0 };
  206175. for (int i = 0; i < 2; ++i)
  206176. {
  206177. prepare (s);
  206178. s.SRB_Flags = SRB_EVENT_NOTIFY;
  206179. s.SRB_BufLen = 0x14;
  206180. s.SRB_BufPointer = (i == 0) ? bufPointer1 : bufPointer2;
  206181. s.SRB_CDBLen = 6;
  206182. s.CDBByte[0] = 0x15;
  206183. s.CDBByte[1] = 0x10;
  206184. s.CDBByte[4] = 0x14;
  206185. perform (s);
  206186. if (s.SRB_Status != SS_COMP)
  206187. return false;
  206188. }
  206189. }
  206190. else
  206191. {
  206192. BYTE bufPointer[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48 };
  206193. prepare (s);
  206194. s.SRB_Flags = SRB_EVENT_NOTIFY;
  206195. s.SRB_BufLen = 0x0C;
  206196. s.SRB_BufPointer = bufPointer;
  206197. s.SRB_CDBLen = 6;
  206198. s.CDBByte[0] = 0x15;
  206199. s.CDBByte[4] = 0x0C;
  206200. perform (s);
  206201. }
  206202. return s.SRB_Status == SS_COMP;
  206203. }
  206204. bool read (CDReadBuffer* rb)
  206205. {
  206206. if (rb->numFrames * 2352 > rb->bufferSize)
  206207. return false;
  206208. if (!initialised)
  206209. {
  206210. initialised = init();
  206211. if (!initialised)
  206212. return false;
  206213. }
  206214. SRB_ExecSCSICmd s;
  206215. prepare (s);
  206216. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  206217. s.SRB_BufLen = rb->bufferSize;
  206218. s.SRB_BufPointer = rb->buffer;
  206219. s.SRB_CDBLen = 10;
  206220. s.CDBByte[0] = 0x28;
  206221. s.CDBByte[1] = (BYTE)(deviceInfo->info.lun << 5);
  206222. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  206223. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  206224. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  206225. s.CDBByte[8] = (BYTE)(rb->numFrames & 0xFF);
  206226. perform (s);
  206227. if (s.SRB_Status != SS_COMP)
  206228. return false;
  206229. rb->dataLength = rb->numFrames * 2352;
  206230. rb->dataStartOffset = 0;
  206231. return true;
  206232. }
  206233. };
  206234. class ControllerType3 : public CDController
  206235. {
  206236. public:
  206237. ControllerType3() {}
  206238. ~ControllerType3() {}
  206239. bool read (CDReadBuffer* rb)
  206240. {
  206241. if (rb->numFrames * 2352 > rb->bufferSize)
  206242. return false;
  206243. if (!initialised)
  206244. {
  206245. setPaused (false);
  206246. initialised = true;
  206247. }
  206248. SRB_ExecSCSICmd s;
  206249. prepare (s);
  206250. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  206251. s.SRB_BufLen = rb->numFrames * 2352;
  206252. s.SRB_BufPointer = rb->buffer;
  206253. s.SRB_CDBLen = 12;
  206254. s.CDBByte[0] = 0xD8;
  206255. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  206256. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  206257. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  206258. s.CDBByte[9] = (BYTE)(rb->numFrames & 0xFF);
  206259. perform (s);
  206260. if (s.SRB_Status != SS_COMP)
  206261. return false;
  206262. rb->dataLength = rb->numFrames * 2352;
  206263. rb->dataStartOffset = 0;
  206264. return true;
  206265. }
  206266. };
  206267. class ControllerType4 : public CDController
  206268. {
  206269. public:
  206270. ControllerType4() {}
  206271. ~ControllerType4() {}
  206272. bool selectD4Mode()
  206273. {
  206274. BYTE bufPointer[12] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 48 };
  206275. SRB_ExecSCSICmd s;
  206276. prepare (s);
  206277. s.SRB_Flags = SRB_EVENT_NOTIFY;
  206278. s.SRB_CDBLen = 6;
  206279. s.SRB_BufLen = 12;
  206280. s.SRB_BufPointer = bufPointer;
  206281. s.CDBByte[0] = 0x15;
  206282. s.CDBByte[1] = 0x10;
  206283. s.CDBByte[4] = 0x08;
  206284. perform (s);
  206285. return s.SRB_Status == SS_COMP;
  206286. }
  206287. bool read (CDReadBuffer* rb)
  206288. {
  206289. if (rb->numFrames * 2352 > rb->bufferSize)
  206290. return false;
  206291. if (!initialised)
  206292. {
  206293. setPaused (true);
  206294. if (deviceInfo->readType == READTYPE_READ_D4_1)
  206295. selectD4Mode();
  206296. initialised = true;
  206297. }
  206298. SRB_ExecSCSICmd s;
  206299. prepare (s);
  206300. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  206301. s.SRB_BufLen = rb->bufferSize;
  206302. s.SRB_BufPointer = rb->buffer;
  206303. s.SRB_CDBLen = 10;
  206304. s.CDBByte[0] = 0xD4;
  206305. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  206306. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  206307. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  206308. s.CDBByte[8] = (BYTE)(rb->numFrames & 0xFF);
  206309. perform (s);
  206310. if (s.SRB_Status != SS_COMP)
  206311. return false;
  206312. rb->dataLength = rb->numFrames * 2352;
  206313. rb->dataStartOffset = 0;
  206314. return true;
  206315. }
  206316. };
  206317. CDController::CDController() : initialised (false)
  206318. {
  206319. }
  206320. CDController::~CDController()
  206321. {
  206322. }
  206323. void CDController::prepare (SRB_ExecSCSICmd& s)
  206324. {
  206325. zerostruct (s);
  206326. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  206327. s.SRB_HaID = deviceInfo->info.ha;
  206328. s.SRB_Target = deviceInfo->info.tgt;
  206329. s.SRB_Lun = deviceInfo->info.lun;
  206330. s.SRB_SenseLen = SENSE_LEN;
  206331. }
  206332. void CDController::perform (SRB_ExecSCSICmd& s)
  206333. {
  206334. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  206335. s.SRB_PostProc = (void*)event;
  206336. ResetEvent (event);
  206337. DWORD status = (usingScsi) ? performScsiPassThroughCommand ((LPSRB_ExecSCSICmd)&s,
  206338. deviceInfo->info.scsiDriveLetter,
  206339. deviceInfo->scsiHandle)
  206340. : fSendASPI32Command ((LPSRB)&s);
  206341. if (status == SS_PENDING)
  206342. WaitForSingleObject (event, 4000);
  206343. CloseHandle (event);
  206344. }
  206345. void CDController::setPaused (bool paused)
  206346. {
  206347. SRB_ExecSCSICmd s;
  206348. prepare (s);
  206349. s.SRB_Flags = SRB_EVENT_NOTIFY;
  206350. s.SRB_CDBLen = 10;
  206351. s.CDBByte[0] = 0x4B;
  206352. s.CDBByte[8] = (BYTE) (paused ? 0 : 1);
  206353. perform (s);
  206354. }
  206355. void CDController::shutDown()
  206356. {
  206357. }
  206358. bool CDController::readAudio (CDReadBuffer* rb, CDReadBuffer* overlapBuffer)
  206359. {
  206360. if (overlapBuffer != 0)
  206361. {
  206362. const bool canDoJitter = (overlapBuffer->bufferSize >= 2352 * framesToCheck);
  206363. const bool doJitter = canDoJitter && ! overlapBuffer->isZero();
  206364. if (doJitter
  206365. && overlapBuffer->startFrame > 0
  206366. && overlapBuffer->numFrames > 0
  206367. && overlapBuffer->dataLength > 0)
  206368. {
  206369. const int numFrames = rb->numFrames;
  206370. if (overlapBuffer->startFrame == (rb->startFrame - framesToCheck))
  206371. {
  206372. rb->startFrame -= framesOverlap;
  206373. if (framesToCheck < framesOverlap
  206374. && numFrames + framesOverlap <= rb->bufferSize / 2352)
  206375. rb->numFrames += framesOverlap;
  206376. }
  206377. else
  206378. {
  206379. overlapBuffer->dataLength = 0;
  206380. overlapBuffer->startFrame = 0;
  206381. overlapBuffer->numFrames = 0;
  206382. }
  206383. }
  206384. if (! read (rb))
  206385. return false;
  206386. if (doJitter)
  206387. {
  206388. const int checkLen = framesToCheck * 2352;
  206389. const int maxToCheck = rb->dataLength - checkLen;
  206390. if (overlapBuffer->dataLength == 0 || overlapBuffer->isZero())
  206391. return true;
  206392. BYTE* const p = overlapBuffer->buffer + overlapBuffer->dataStartOffset;
  206393. bool found = false;
  206394. for (int i = 0; i < maxToCheck; ++i)
  206395. {
  206396. if (!memcmp (p, rb->buffer + i, checkLen))
  206397. {
  206398. i += checkLen;
  206399. rb->dataStartOffset = i;
  206400. rb->dataLength -= i;
  206401. rb->startFrame = overlapBuffer->startFrame + framesToCheck;
  206402. found = true;
  206403. break;
  206404. }
  206405. }
  206406. rb->numFrames = rb->dataLength / 2352;
  206407. rb->dataLength = 2352 * rb->numFrames;
  206408. if (!found)
  206409. return false;
  206410. }
  206411. if (canDoJitter)
  206412. {
  206413. memcpy (overlapBuffer->buffer,
  206414. rb->buffer + rb->dataStartOffset + 2352 * (rb->numFrames - framesToCheck),
  206415. 2352 * framesToCheck);
  206416. overlapBuffer->startFrame = rb->startFrame + rb->numFrames - framesToCheck;
  206417. overlapBuffer->numFrames = framesToCheck;
  206418. overlapBuffer->dataLength = 2352 * framesToCheck;
  206419. overlapBuffer->dataStartOffset = 0;
  206420. }
  206421. else
  206422. {
  206423. overlapBuffer->startFrame = 0;
  206424. overlapBuffer->numFrames = 0;
  206425. overlapBuffer->dataLength = 0;
  206426. }
  206427. return true;
  206428. }
  206429. else
  206430. {
  206431. return read (rb);
  206432. }
  206433. }
  206434. int CDController::getLastIndex()
  206435. {
  206436. char qdata[100];
  206437. SRB_ExecSCSICmd s;
  206438. prepare (s);
  206439. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  206440. s.SRB_BufLen = sizeof (qdata);
  206441. s.SRB_BufPointer = (BYTE*)qdata;
  206442. s.SRB_CDBLen = 12;
  206443. s.CDBByte[0] = 0x42;
  206444. s.CDBByte[1] = (BYTE)(deviceInfo->info.lun << 5);
  206445. s.CDBByte[2] = 64;
  206446. s.CDBByte[3] = 1; // get current position
  206447. s.CDBByte[7] = 0;
  206448. s.CDBByte[8] = (BYTE)sizeof (qdata);
  206449. perform (s);
  206450. if (s.SRB_Status == SS_COMP)
  206451. return qdata[7];
  206452. return 0;
  206453. }
  206454. bool CDDeviceHandle::readTOC (TOC* lpToc, bool useMSF)
  206455. {
  206456. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  206457. SRB_ExecSCSICmd s;
  206458. zerostruct (s);
  206459. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  206460. s.SRB_HaID = info.ha;
  206461. s.SRB_Target = info.tgt;
  206462. s.SRB_Lun = info.lun;
  206463. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  206464. s.SRB_BufLen = 0x324;
  206465. s.SRB_BufPointer = (BYTE*)lpToc;
  206466. s.SRB_SenseLen = 0x0E;
  206467. s.SRB_CDBLen = 0x0A;
  206468. s.SRB_PostProc = (void*)event;
  206469. s.CDBByte[0] = 0x43;
  206470. s.CDBByte[1] = (BYTE)(useMSF ? 0x02 : 0x00);
  206471. s.CDBByte[7] = 0x03;
  206472. s.CDBByte[8] = 0x24;
  206473. ResetEvent (event);
  206474. DWORD status = (usingScsi) ? performScsiPassThroughCommand ((LPSRB_ExecSCSICmd)&s, info.scsiDriveLetter, scsiHandle)
  206475. : fSendASPI32Command ((LPSRB)&s);
  206476. if (status == SS_PENDING)
  206477. WaitForSingleObject (event, 4000);
  206478. CloseHandle (event);
  206479. return (s.SRB_Status == SS_COMP);
  206480. }
  206481. bool CDDeviceHandle::readAudio (CDReadBuffer* const buffer,
  206482. CDReadBuffer* const overlapBuffer)
  206483. {
  206484. if (controller == 0)
  206485. {
  206486. testController (READTYPE_ATAPI2, new ControllerType1(), buffer)
  206487. || testController (READTYPE_ATAPI1, new ControllerType1(), buffer)
  206488. || testController (READTYPE_READ10_2, new ControllerType2(), buffer)
  206489. || testController (READTYPE_READ10, new ControllerType2(), buffer)
  206490. || testController (READTYPE_READ_D8, new ControllerType3(), buffer)
  206491. || testController (READTYPE_READ_D4, new ControllerType4(), buffer)
  206492. || testController (READTYPE_READ_D4_1, new ControllerType4(), buffer);
  206493. }
  206494. buffer->index = 0;
  206495. if ((controller != 0)
  206496. && controller->readAudio (buffer, overlapBuffer))
  206497. {
  206498. if (buffer->wantsIndex)
  206499. buffer->index = controller->getLastIndex();
  206500. return true;
  206501. }
  206502. return false;
  206503. }
  206504. void CDDeviceHandle::openDrawer (bool shouldBeOpen)
  206505. {
  206506. if (shouldBeOpen)
  206507. {
  206508. if (controller != 0)
  206509. {
  206510. controller->shutDown();
  206511. delete controller;
  206512. controller = 0;
  206513. }
  206514. if (scsiHandle != 0)
  206515. {
  206516. CloseHandle (scsiHandle);
  206517. scsiHandle = 0;
  206518. }
  206519. }
  206520. SRB_ExecSCSICmd s;
  206521. zerostruct (s);
  206522. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  206523. s.SRB_HaID = info.ha;
  206524. s.SRB_Target = info.tgt;
  206525. s.SRB_Lun = info.lun;
  206526. s.SRB_SenseLen = SENSE_LEN;
  206527. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  206528. s.SRB_BufLen = 0;
  206529. s.SRB_BufPointer = 0;
  206530. s.SRB_CDBLen = 12;
  206531. s.CDBByte[0] = 0x1b;
  206532. s.CDBByte[1] = (BYTE)(info.lun << 5);
  206533. s.CDBByte[4] = (BYTE)((shouldBeOpen) ? 2 : 3);
  206534. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  206535. s.SRB_PostProc = (void*)event;
  206536. ResetEvent (event);
  206537. DWORD status = (usingScsi) ? performScsiPassThroughCommand ((LPSRB_ExecSCSICmd)&s, info.scsiDriveLetter, scsiHandle)
  206538. : fSendASPI32Command ((LPSRB)&s);
  206539. if (status == SS_PENDING)
  206540. WaitForSingleObject (event, 4000);
  206541. CloseHandle (event);
  206542. }
  206543. bool CDDeviceHandle::testController (const int type,
  206544. CDController* const newController,
  206545. CDReadBuffer* const rb)
  206546. {
  206547. controller = newController;
  206548. readType = (BYTE)type;
  206549. controller->deviceInfo = this;
  206550. controller->framesToCheck = 1;
  206551. controller->framesOverlap = 3;
  206552. bool passed = false;
  206553. memset (rb->buffer, 0xcd, rb->bufferSize);
  206554. if (controller->read (rb))
  206555. {
  206556. passed = true;
  206557. int* p = (int*) (rb->buffer + rb->dataStartOffset);
  206558. int wrong = 0;
  206559. for (int i = rb->dataLength / 4; --i >= 0;)
  206560. {
  206561. if (*p++ == (int) 0xcdcdcdcd)
  206562. {
  206563. if (++wrong == 4)
  206564. {
  206565. passed = false;
  206566. break;
  206567. }
  206568. }
  206569. else
  206570. {
  206571. wrong = 0;
  206572. }
  206573. }
  206574. }
  206575. if (! passed)
  206576. {
  206577. controller->shutDown();
  206578. delete controller;
  206579. controller = 0;
  206580. }
  206581. return passed;
  206582. }
  206583. static void GetAspiDeviceInfo (CDDeviceInfo* dev, BYTE ha, BYTE tgt, BYTE lun)
  206584. {
  206585. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  206586. const int bufSize = 128;
  206587. BYTE buffer[bufSize];
  206588. zeromem (buffer, bufSize);
  206589. SRB_ExecSCSICmd s;
  206590. zerostruct (s);
  206591. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  206592. s.SRB_HaID = ha;
  206593. s.SRB_Target = tgt;
  206594. s.SRB_Lun = lun;
  206595. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  206596. s.SRB_BufLen = bufSize;
  206597. s.SRB_BufPointer = buffer;
  206598. s.SRB_SenseLen = SENSE_LEN;
  206599. s.SRB_CDBLen = 6;
  206600. s.SRB_PostProc = (void*)event;
  206601. s.CDBByte[0] = SCSI_INQUIRY;
  206602. s.CDBByte[4] = 100;
  206603. ResetEvent (event);
  206604. if (fSendASPI32Command ((LPSRB)&s) == SS_PENDING)
  206605. WaitForSingleObject (event, 4000);
  206606. CloseHandle (event);
  206607. if (s.SRB_Status == SS_COMP)
  206608. {
  206609. memcpy (dev->vendor, &buffer[8], 8);
  206610. memcpy (dev->productId, &buffer[16], 16);
  206611. memcpy (dev->rev, &buffer[32], 4);
  206612. memcpy (dev->vendorSpec, &buffer[36], 20);
  206613. }
  206614. }
  206615. static int FindCDDevices (CDDeviceInfo* const list,
  206616. int maxItems)
  206617. {
  206618. int count = 0;
  206619. if (usingScsi)
  206620. {
  206621. for (char driveLetter = 'b'; driveLetter <= 'z'; ++driveLetter)
  206622. {
  206623. TCHAR drivePath[8];
  206624. drivePath[0] = driveLetter;
  206625. drivePath[1] = ':';
  206626. drivePath[2] = '\\';
  206627. drivePath[3] = 0;
  206628. if (GetDriveType (drivePath) == DRIVE_CDROM)
  206629. {
  206630. HANDLE h = CreateSCSIDeviceHandle (driveLetter);
  206631. if (h != INVALID_HANDLE_VALUE)
  206632. {
  206633. BYTE buffer[100], passThroughStruct[1024];
  206634. zeromem (buffer, sizeof (buffer));
  206635. zeromem (passThroughStruct, sizeof (passThroughStruct));
  206636. PSCSI_PASS_THROUGH_DIRECT_WITH_BUFFER p = (PSCSI_PASS_THROUGH_DIRECT_WITH_BUFFER)passThroughStruct;
  206637. p->spt.Length = sizeof (SCSI_PASS_THROUGH);
  206638. p->spt.CdbLength = 6;
  206639. p->spt.SenseInfoLength = 24;
  206640. p->spt.DataIn = SCSI_IOCTL_DATA_IN;
  206641. p->spt.DataTransferLength = 100;
  206642. p->spt.TimeOutValue = 2;
  206643. p->spt.DataBuffer = buffer;
  206644. p->spt.SenseInfoOffset = offsetof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER, ucSenseBuf);
  206645. p->spt.Cdb[0] = 0x12;
  206646. p->spt.Cdb[4] = 100;
  206647. DWORD bytesReturned = 0;
  206648. if (DeviceIoControl (h, IOCTL_SCSI_PASS_THROUGH_DIRECT,
  206649. p, sizeof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER),
  206650. p, sizeof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER),
  206651. &bytesReturned, 0) != 0)
  206652. {
  206653. zeromem (&list[count], sizeof (CDDeviceInfo));
  206654. list[count].scsiDriveLetter = driveLetter;
  206655. memcpy (list[count].vendor, &buffer[8], 8);
  206656. memcpy (list[count].productId, &buffer[16], 16);
  206657. memcpy (list[count].rev, &buffer[32], 4);
  206658. memcpy (list[count].vendorSpec, &buffer[36], 20);
  206659. zeromem (passThroughStruct, sizeof (passThroughStruct));
  206660. PSCSI_ADDRESS scsiAddr = (PSCSI_ADDRESS)passThroughStruct;
  206661. scsiAddr->Length = sizeof (SCSI_ADDRESS);
  206662. if (DeviceIoControl (h, IOCTL_SCSI_GET_ADDRESS,
  206663. 0, 0, scsiAddr, sizeof (SCSI_ADDRESS),
  206664. &bytesReturned, 0) != 0)
  206665. {
  206666. list[count].ha = scsiAddr->PortNumber;
  206667. list[count].tgt = scsiAddr->TargetId;
  206668. list[count].lun = scsiAddr->Lun;
  206669. ++count;
  206670. }
  206671. }
  206672. CloseHandle (h);
  206673. }
  206674. }
  206675. }
  206676. }
  206677. else
  206678. {
  206679. const DWORD d = fGetASPI32SupportInfo();
  206680. BYTE status = HIBYTE (LOWORD (d));
  206681. if (status != SS_COMP || status == SS_NO_ADAPTERS)
  206682. return 0;
  206683. const int numAdapters = LOBYTE (LOWORD (d));
  206684. for (BYTE ha = 0; ha < numAdapters; ++ha)
  206685. {
  206686. SRB_HAInquiry s;
  206687. zerostruct (s);
  206688. s.SRB_Cmd = SC_HA_INQUIRY;
  206689. s.SRB_HaID = ha;
  206690. fSendASPI32Command ((LPSRB)&s);
  206691. if (s.SRB_Status == SS_COMP)
  206692. {
  206693. maxItems = (int)s.HA_Unique[3];
  206694. if (maxItems == 0)
  206695. maxItems = 8;
  206696. for (BYTE tgt = 0; tgt < maxItems; ++tgt)
  206697. {
  206698. for (BYTE lun = 0; lun < 8; ++lun)
  206699. {
  206700. SRB_GDEVBlock sb;
  206701. zerostruct (sb);
  206702. sb.SRB_Cmd = SC_GET_DEV_TYPE;
  206703. sb.SRB_HaID = ha;
  206704. sb.SRB_Target = tgt;
  206705. sb.SRB_Lun = lun;
  206706. fSendASPI32Command ((LPSRB) &sb);
  206707. if (sb.SRB_Status == SS_COMP
  206708. && sb.SRB_DeviceType == DTYPE_CROM)
  206709. {
  206710. zeromem (&list[count], sizeof (CDDeviceInfo));
  206711. list[count].ha = ha;
  206712. list[count].tgt = tgt;
  206713. list[count].lun = lun;
  206714. GetAspiDeviceInfo (&(list[count]), ha, tgt, lun);
  206715. ++count;
  206716. }
  206717. }
  206718. }
  206719. }
  206720. }
  206721. }
  206722. return count;
  206723. }
  206724. static int ripperUsers = 0;
  206725. static bool initialisedOk = false;
  206726. class DeinitialiseTimer : private Timer,
  206727. private DeletedAtShutdown
  206728. {
  206729. DeinitialiseTimer (const DeinitialiseTimer&);
  206730. const DeinitialiseTimer& operator= (const DeinitialiseTimer&);
  206731. public:
  206732. DeinitialiseTimer()
  206733. {
  206734. startTimer (4000);
  206735. }
  206736. ~DeinitialiseTimer()
  206737. {
  206738. if (--ripperUsers == 0)
  206739. DeinitialiseCDRipper();
  206740. }
  206741. void timerCallback()
  206742. {
  206743. delete this;
  206744. }
  206745. juce_UseDebuggingNewOperator
  206746. };
  206747. static void incUserCount()
  206748. {
  206749. if (ripperUsers++ == 0)
  206750. initialisedOk = InitialiseCDRipper();
  206751. }
  206752. static void decUserCount()
  206753. {
  206754. new DeinitialiseTimer();
  206755. }
  206756. struct CDDeviceWrapper
  206757. {
  206758. CDDeviceHandle* cdH;
  206759. CDReadBuffer* overlapBuffer;
  206760. bool jitter;
  206761. };
  206762. static int getAddressOf (const TOCTRACK* const t)
  206763. {
  206764. return (((DWORD)t->addr[0]) << 24) + (((DWORD)t->addr[1]) << 16) +
  206765. (((DWORD)t->addr[2]) << 8) + ((DWORD)t->addr[3]);
  206766. }
  206767. static int getMSFAddressOf (const TOCTRACK* const t)
  206768. {
  206769. return 60 * t->addr[1] + t->addr[2];
  206770. }
  206771. static const int samplesPerFrame = 44100 / 75;
  206772. static const int bytesPerFrame = samplesPerFrame * 4;
  206773. const StringArray AudioCDReader::getAvailableCDNames()
  206774. {
  206775. StringArray results;
  206776. incUserCount();
  206777. if (initialisedOk)
  206778. {
  206779. CDDeviceInfo list[8];
  206780. const int num = FindCDDevices (list, 8);
  206781. decUserCount();
  206782. for (int i = 0; i < num; ++i)
  206783. {
  206784. String s;
  206785. if (list[i].scsiDriveLetter > 0)
  206786. s << String::charToString (list[i].scsiDriveLetter).toUpperCase() << T(": ");
  206787. s << String (list[i].vendor).trim()
  206788. << T(" ") << String (list[i].productId).trim()
  206789. << T(" ") << String (list[i].rev).trim();
  206790. results.add (s);
  206791. }
  206792. }
  206793. return results;
  206794. }
  206795. static CDDeviceHandle* openHandle (const CDDeviceInfo* const device)
  206796. {
  206797. SRB_GDEVBlock s;
  206798. zerostruct (s);
  206799. s.SRB_Cmd = SC_GET_DEV_TYPE;
  206800. s.SRB_HaID = device->ha;
  206801. s.SRB_Target = device->tgt;
  206802. s.SRB_Lun = device->lun;
  206803. if (usingScsi)
  206804. {
  206805. HANDLE h = CreateSCSIDeviceHandle (device->scsiDriveLetter);
  206806. if (h != INVALID_HANDLE_VALUE)
  206807. {
  206808. CDDeviceHandle* cdh = new CDDeviceHandle (device);
  206809. cdh->scsiHandle = h;
  206810. return cdh;
  206811. }
  206812. }
  206813. else
  206814. {
  206815. if (fSendASPI32Command ((LPSRB)&s) == SS_COMP
  206816. && s.SRB_DeviceType == DTYPE_CROM)
  206817. {
  206818. return new CDDeviceHandle (device);
  206819. }
  206820. }
  206821. return 0;
  206822. }
  206823. AudioCDReader* AudioCDReader::createReaderForCD (const int deviceIndex)
  206824. {
  206825. incUserCount();
  206826. if (initialisedOk)
  206827. {
  206828. CDDeviceInfo list[8];
  206829. const int num = FindCDDevices (list, 8);
  206830. if (((unsigned int) deviceIndex) < (unsigned int) num)
  206831. {
  206832. CDDeviceHandle* const handle = openHandle (&(list[deviceIndex]));
  206833. if (handle != 0)
  206834. {
  206835. CDDeviceWrapper* const d = new CDDeviceWrapper();
  206836. d->cdH = handle;
  206837. d->overlapBuffer = new CDReadBuffer(3);
  206838. return new AudioCDReader (d);
  206839. }
  206840. }
  206841. }
  206842. decUserCount();
  206843. return 0;
  206844. }
  206845. AudioCDReader::AudioCDReader (void* handle_)
  206846. : AudioFormatReader (0, T("CD Audio")),
  206847. handle (handle_),
  206848. indexingEnabled (false),
  206849. lastIndex (0),
  206850. firstFrameInBuffer (0),
  206851. samplesInBuffer (0)
  206852. {
  206853. jassert (handle_ != 0);
  206854. refreshTrackLengths();
  206855. sampleRate = 44100.0;
  206856. bitsPerSample = 16;
  206857. lengthInSamples = getPositionOfTrackStart (numTracks);
  206858. numChannels = 2;
  206859. usesFloatingPointData = false;
  206860. buffer.setSize (4 * bytesPerFrame, true);
  206861. }
  206862. AudioCDReader::~AudioCDReader()
  206863. {
  206864. CDDeviceWrapper* const device = (CDDeviceWrapper*)handle;
  206865. delete device->cdH;
  206866. delete device->overlapBuffer;
  206867. delete device;
  206868. decUserCount();
  206869. }
  206870. bool AudioCDReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  206871. int64 startSampleInFile, int numSamples)
  206872. {
  206873. CDDeviceWrapper* const device = (CDDeviceWrapper*) handle;
  206874. bool ok = true;
  206875. while (numSamples > 0)
  206876. {
  206877. const int bufferStartSample = firstFrameInBuffer * samplesPerFrame;
  206878. const int bufferEndSample = bufferStartSample + samplesInBuffer;
  206879. if (startSampleInFile >= bufferStartSample
  206880. && startSampleInFile < bufferEndSample)
  206881. {
  206882. const int toDo = (int) jmin ((int64) numSamples, bufferEndSample - startSampleInFile);
  206883. int* const l = destSamples[0] + startOffsetInDestBuffer;
  206884. int* const r = numDestChannels > 1 ? (destSamples[1] + startOffsetInDestBuffer) : 0;
  206885. const short* src = (const short*) buffer.getData();
  206886. src += 2 * (startSampleInFile - bufferStartSample);
  206887. for (int i = 0; i < toDo; ++i)
  206888. {
  206889. l[i] = src [i << 1] << 16;
  206890. if (r != 0)
  206891. r[i] = src [(i << 1) + 1] << 16;
  206892. }
  206893. startOffsetInDestBuffer += toDo;
  206894. startSampleInFile += toDo;
  206895. numSamples -= toDo;
  206896. }
  206897. else
  206898. {
  206899. const int framesInBuffer = buffer.getSize() / bytesPerFrame;
  206900. const int frameNeeded = (int) (startSampleInFile / samplesPerFrame);
  206901. if (firstFrameInBuffer + framesInBuffer != frameNeeded)
  206902. {
  206903. device->overlapBuffer->dataLength = 0;
  206904. device->overlapBuffer->startFrame = 0;
  206905. device->overlapBuffer->numFrames = 0;
  206906. device->jitter = false;
  206907. }
  206908. firstFrameInBuffer = frameNeeded;
  206909. lastIndex = 0;
  206910. CDReadBuffer readBuffer (framesInBuffer + 4);
  206911. readBuffer.wantsIndex = indexingEnabled;
  206912. int i;
  206913. for (i = 5; --i >= 0;)
  206914. {
  206915. readBuffer.startFrame = frameNeeded;
  206916. readBuffer.numFrames = framesInBuffer;
  206917. if (device->cdH->readAudio (&readBuffer, (device->jitter) ? device->overlapBuffer : 0))
  206918. break;
  206919. else
  206920. device->overlapBuffer->dataLength = 0;
  206921. }
  206922. if (i >= 0)
  206923. {
  206924. memcpy ((char*) buffer.getData(),
  206925. readBuffer.buffer + readBuffer.dataStartOffset,
  206926. readBuffer.dataLength);
  206927. samplesInBuffer = readBuffer.dataLength >> 2;
  206928. lastIndex = readBuffer.index;
  206929. }
  206930. else
  206931. {
  206932. int* l = destSamples[0] + startOffsetInDestBuffer;
  206933. int* r = numDestChannels > 1 ? (destSamples[1] + startOffsetInDestBuffer) : 0;
  206934. while (--numSamples >= 0)
  206935. {
  206936. *l++ = 0;
  206937. if (r != 0)
  206938. *r++ = 0;
  206939. }
  206940. // sometimes the read fails for just the very last couple of blocks, so
  206941. // we'll ignore and errors in the last half-second of the disk..
  206942. ok = startSampleInFile > (trackStarts [numTracks] - 20000);
  206943. break;
  206944. }
  206945. }
  206946. }
  206947. return ok;
  206948. }
  206949. bool AudioCDReader::isCDStillPresent() const
  206950. {
  206951. TOC toc;
  206952. zerostruct (toc);
  206953. return ((CDDeviceWrapper*)handle)->cdH->readTOC (&toc, false);
  206954. }
  206955. int AudioCDReader::getNumTracks() const
  206956. {
  206957. return numTracks;
  206958. }
  206959. int AudioCDReader::getPositionOfTrackStart (int trackNum) const
  206960. {
  206961. return (trackNum >= 0 && trackNum <= numTracks) ? trackStarts [trackNum] * samplesPerFrame
  206962. : 0;
  206963. }
  206964. void AudioCDReader::refreshTrackLengths()
  206965. {
  206966. zeromem (trackStarts, sizeof (trackStarts));
  206967. zeromem (audioTracks, sizeof (audioTracks));
  206968. TOC toc;
  206969. zerostruct (toc);
  206970. if (((CDDeviceWrapper*)handle)->cdH->readTOC (&toc, false))
  206971. {
  206972. numTracks = 1 + toc.lastTrack - toc.firstTrack;
  206973. for (int i = 0; i <= numTracks; ++i)
  206974. {
  206975. trackStarts[i] = getAddressOf (&toc.tracks[i]);
  206976. audioTracks[i] = ((toc.tracks[i].ADR & 4) == 0);
  206977. }
  206978. }
  206979. else
  206980. {
  206981. numTracks = 0;
  206982. }
  206983. }
  206984. bool AudioCDReader::isTrackAudio (int trackNum) const
  206985. {
  206986. return (trackNum >= 0 && trackNum <= numTracks) ? audioTracks [trackNum]
  206987. : false;
  206988. }
  206989. void AudioCDReader::enableIndexScanning (bool b)
  206990. {
  206991. indexingEnabled = b;
  206992. }
  206993. int AudioCDReader::getLastIndex() const
  206994. {
  206995. return lastIndex;
  206996. }
  206997. const int framesPerIndexRead = 4;
  206998. int AudioCDReader::getIndexAt (int samplePos)
  206999. {
  207000. CDDeviceWrapper* const device = (CDDeviceWrapper*) handle;
  207001. const int frameNeeded = samplePos / samplesPerFrame;
  207002. device->overlapBuffer->dataLength = 0;
  207003. device->overlapBuffer->startFrame = 0;
  207004. device->overlapBuffer->numFrames = 0;
  207005. device->jitter = false;
  207006. firstFrameInBuffer = 0;
  207007. lastIndex = 0;
  207008. CDReadBuffer readBuffer (4 + framesPerIndexRead);
  207009. readBuffer.wantsIndex = true;
  207010. int i;
  207011. for (i = 5; --i >= 0;)
  207012. {
  207013. readBuffer.startFrame = frameNeeded;
  207014. readBuffer.numFrames = framesPerIndexRead;
  207015. if (device->cdH->readAudio (&readBuffer, (false) ? device->overlapBuffer : 0))
  207016. break;
  207017. }
  207018. if (i >= 0)
  207019. return readBuffer.index;
  207020. return -1;
  207021. }
  207022. const Array <int> AudioCDReader::findIndexesInTrack (const int trackNumber)
  207023. {
  207024. Array <int> indexes;
  207025. const int trackStart = getPositionOfTrackStart (trackNumber);
  207026. const int trackEnd = getPositionOfTrackStart (trackNumber + 1);
  207027. bool needToScan = true;
  207028. if (trackEnd - trackStart > 20 * 44100)
  207029. {
  207030. // check the end of the track for indexes before scanning the whole thing
  207031. needToScan = false;
  207032. int pos = jmax (trackStart, trackEnd - 44100 * 5);
  207033. bool seenAnIndex = false;
  207034. while (pos <= trackEnd - samplesPerFrame)
  207035. {
  207036. const int index = getIndexAt (pos);
  207037. if (index == 0)
  207038. {
  207039. // lead-out, so skip back a bit if we've not found any indexes yet..
  207040. if (seenAnIndex)
  207041. break;
  207042. pos -= 44100 * 5;
  207043. if (pos < trackStart)
  207044. break;
  207045. }
  207046. else
  207047. {
  207048. if (index > 0)
  207049. seenAnIndex = true;
  207050. if (index > 1)
  207051. {
  207052. needToScan = true;
  207053. break;
  207054. }
  207055. pos += samplesPerFrame * framesPerIndexRead;
  207056. }
  207057. }
  207058. }
  207059. if (needToScan)
  207060. {
  207061. CDDeviceWrapper* const device = (CDDeviceWrapper*) handle;
  207062. int pos = trackStart;
  207063. int last = -1;
  207064. while (pos < trackEnd - samplesPerFrame * 10)
  207065. {
  207066. const int frameNeeded = pos / samplesPerFrame;
  207067. device->overlapBuffer->dataLength = 0;
  207068. device->overlapBuffer->startFrame = 0;
  207069. device->overlapBuffer->numFrames = 0;
  207070. device->jitter = false;
  207071. firstFrameInBuffer = 0;
  207072. CDReadBuffer readBuffer (4);
  207073. readBuffer.wantsIndex = true;
  207074. int i;
  207075. for (i = 5; --i >= 0;)
  207076. {
  207077. readBuffer.startFrame = frameNeeded;
  207078. readBuffer.numFrames = framesPerIndexRead;
  207079. if (device->cdH->readAudio (&readBuffer, (false) ? device->overlapBuffer : 0))
  207080. break;
  207081. }
  207082. if (i < 0)
  207083. break;
  207084. if (readBuffer.index > last && readBuffer.index > 1)
  207085. {
  207086. last = readBuffer.index;
  207087. indexes.add (pos);
  207088. }
  207089. pos += samplesPerFrame * framesPerIndexRead;
  207090. }
  207091. indexes.removeValue (trackStart);
  207092. }
  207093. return indexes;
  207094. }
  207095. int AudioCDReader::getCDDBId()
  207096. {
  207097. refreshTrackLengths();
  207098. if (numTracks > 0)
  207099. {
  207100. TOC toc;
  207101. zerostruct (toc);
  207102. if (((CDDeviceWrapper*) handle)->cdH->readTOC (&toc, true))
  207103. {
  207104. int n = 0;
  207105. for (int i = numTracks; --i >= 0;)
  207106. {
  207107. int j = getMSFAddressOf (&toc.tracks[i]);
  207108. while (j > 0)
  207109. {
  207110. n += (j % 10);
  207111. j /= 10;
  207112. }
  207113. }
  207114. if (n != 0)
  207115. {
  207116. const int t = getMSFAddressOf (&toc.tracks[numTracks])
  207117. - getMSFAddressOf (&toc.tracks[0]);
  207118. return ((n % 0xff) << 24) | (t << 8) | numTracks;
  207119. }
  207120. }
  207121. }
  207122. return 0;
  207123. }
  207124. void AudioCDReader::ejectDisk()
  207125. {
  207126. ((CDDeviceWrapper*) handle)->cdH->openDrawer (true);
  207127. }
  207128. static IDiscRecorder* enumCDBurners (StringArray* list, int indexToOpen, IDiscMaster** master)
  207129. {
  207130. CoInitialize (0);
  207131. IDiscMaster* dm;
  207132. IDiscRecorder* result = 0;
  207133. if (SUCCEEDED (CoCreateInstance (CLSID_MSDiscMasterObj, 0,
  207134. CLSCTX_INPROC_SERVER | CLSCTX_LOCAL_SERVER,
  207135. IID_IDiscMaster,
  207136. (void**) &dm)))
  207137. {
  207138. if (SUCCEEDED (dm->Open()))
  207139. {
  207140. IEnumDiscRecorders* drEnum = 0;
  207141. if (SUCCEEDED (dm->EnumDiscRecorders (&drEnum)))
  207142. {
  207143. IDiscRecorder* dr = 0;
  207144. DWORD dummy;
  207145. int index = 0;
  207146. while (drEnum->Next (1, &dr, &dummy) == S_OK)
  207147. {
  207148. if (indexToOpen == index)
  207149. {
  207150. result = dr;
  207151. break;
  207152. }
  207153. else if (list != 0)
  207154. {
  207155. BSTR path;
  207156. if (SUCCEEDED (dr->GetPath (&path)))
  207157. list->add ((const WCHAR*) path);
  207158. }
  207159. ++index;
  207160. dr->Release();
  207161. }
  207162. drEnum->Release();
  207163. }
  207164. /*if (redbookFormat != 0)
  207165. {
  207166. IEnumDiscMasterFormats* mfEnum;
  207167. if (SUCCEEDED (dm->EnumDiscMasterFormats (&mfEnum)))
  207168. {
  207169. IID formatIID;
  207170. DWORD dummy;
  207171. while (mfEnum->Next (1, &formatIID, &dummy) == S_OK)
  207172. {
  207173. }
  207174. mfEnum->Release();
  207175. }
  207176. redbookFormat
  207177. }*/
  207178. if (master == 0)
  207179. dm->Close();
  207180. }
  207181. if (master != 0)
  207182. *master = dm;
  207183. else
  207184. dm->Release();
  207185. }
  207186. return result;
  207187. }
  207188. const StringArray AudioCDBurner::findAvailableDevices()
  207189. {
  207190. StringArray devs;
  207191. enumCDBurners (&devs, -1, 0);
  207192. return devs;
  207193. }
  207194. AudioCDBurner* AudioCDBurner::openDevice (const int deviceIndex)
  207195. {
  207196. AudioCDBurner* b = new AudioCDBurner (deviceIndex);
  207197. if (b->internal == 0)
  207198. deleteAndZero (b);
  207199. return b;
  207200. }
  207201. class CDBurnerInfo : public IDiscMasterProgressEvents
  207202. {
  207203. public:
  207204. CDBurnerInfo()
  207205. : refCount (1),
  207206. progress (0),
  207207. shouldCancel (false),
  207208. listener (0)
  207209. {
  207210. }
  207211. ~CDBurnerInfo()
  207212. {
  207213. }
  207214. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  207215. {
  207216. if (result == 0)
  207217. return E_POINTER;
  207218. if (id == IID_IUnknown || id == IID_IDiscMasterProgressEvents)
  207219. {
  207220. AddRef();
  207221. *result = this;
  207222. return S_OK;
  207223. }
  207224. *result = 0;
  207225. return E_NOINTERFACE;
  207226. }
  207227. ULONG __stdcall AddRef() { return ++refCount; }
  207228. ULONG __stdcall Release() { jassert (refCount > 0); const int r = --refCount; if (r == 0) delete this; return r; }
  207229. HRESULT __stdcall QueryCancel (boolean* pbCancel)
  207230. {
  207231. if (listener != 0 && ! shouldCancel)
  207232. shouldCancel = listener->audioCDBurnProgress (progress);
  207233. *pbCancel = shouldCancel;
  207234. return S_OK;
  207235. }
  207236. HRESULT __stdcall NotifyBlockProgress (long nCompleted, long nTotal)
  207237. {
  207238. progress = nCompleted / (float) nTotal;
  207239. shouldCancel = listener != 0 && listener->audioCDBurnProgress (progress);
  207240. return E_NOTIMPL;
  207241. }
  207242. HRESULT __stdcall NotifyPnPActivity (void) { return E_NOTIMPL; }
  207243. HRESULT __stdcall NotifyAddProgress (long /*nCompletedSteps*/, long /*nTotalSteps*/) { return E_NOTIMPL; }
  207244. HRESULT __stdcall NotifyTrackProgress (long /*nCurrentTrack*/, long /*nTotalTracks*/) { return E_NOTIMPL; }
  207245. HRESULT __stdcall NotifyPreparingBurn (long /*nEstimatedSeconds*/) { return E_NOTIMPL; }
  207246. HRESULT __stdcall NotifyClosingDisc (long /*nEstimatedSeconds*/) { return E_NOTIMPL; }
  207247. HRESULT __stdcall NotifyBurnComplete (HRESULT /*status*/) { return E_NOTIMPL; }
  207248. HRESULT __stdcall NotifyEraseComplete (HRESULT /*status*/) { return E_NOTIMPL; }
  207249. IDiscMaster* discMaster;
  207250. IDiscRecorder* discRecorder;
  207251. IRedbookDiscMaster* redbook;
  207252. AudioCDBurner::BurnProgressListener* listener;
  207253. float progress;
  207254. bool shouldCancel;
  207255. private:
  207256. int refCount;
  207257. };
  207258. AudioCDBurner::AudioCDBurner (const int deviceIndex)
  207259. : internal (0)
  207260. {
  207261. IDiscMaster* discMaster;
  207262. IDiscRecorder* dr = enumCDBurners (0, deviceIndex, &discMaster);
  207263. if (dr != 0)
  207264. {
  207265. IRedbookDiscMaster* redbook;
  207266. HRESULT hr = discMaster->SetActiveDiscMasterFormat (IID_IRedbookDiscMaster, (void**) &redbook);
  207267. hr = discMaster->SetActiveDiscRecorder (dr);
  207268. CDBurnerInfo* const info = new CDBurnerInfo();
  207269. internal = info;
  207270. info->discMaster = discMaster;
  207271. info->discRecorder = dr;
  207272. info->redbook = redbook;
  207273. }
  207274. }
  207275. AudioCDBurner::~AudioCDBurner()
  207276. {
  207277. CDBurnerInfo* const info = (CDBurnerInfo*) internal;
  207278. if (info != 0)
  207279. {
  207280. info->discRecorder->Close();
  207281. info->redbook->Release();
  207282. info->discRecorder->Release();
  207283. info->discMaster->Release();
  207284. info->Release();
  207285. }
  207286. }
  207287. bool AudioCDBurner::isDiskPresent() const
  207288. {
  207289. CDBurnerInfo* const info = (CDBurnerInfo*) internal;
  207290. HRESULT hr = info->discRecorder->OpenExclusive();
  207291. long type, flags;
  207292. hr = info->discRecorder->QueryMediaType (&type, &flags);
  207293. info->discRecorder->Close();
  207294. return hr == S_OK && type != 0 && (flags & MEDIA_WRITABLE) != 0;
  207295. }
  207296. int AudioCDBurner::getNumAvailableAudioBlocks() const
  207297. {
  207298. CDBurnerInfo* const info = (CDBurnerInfo*) internal;
  207299. long blocksFree = 0;
  207300. info->redbook->GetAvailableAudioTrackBlocks (&blocksFree);
  207301. return blocksFree;
  207302. }
  207303. const String AudioCDBurner::burn (AudioCDBurner::BurnProgressListener* listener,
  207304. const bool ejectDiscAfterwards,
  207305. const bool performFakeBurnForTesting)
  207306. {
  207307. CDBurnerInfo* const info = (CDBurnerInfo*) internal;
  207308. info->listener = listener;
  207309. info->progress = 0;
  207310. info->shouldCancel = false;
  207311. UINT_PTR cookie;
  207312. HRESULT hr = info->discMaster->ProgressAdvise (info, &cookie);
  207313. hr = info->discMaster->RecordDisc (performFakeBurnForTesting,
  207314. ejectDiscAfterwards);
  207315. String error;
  207316. if (hr != S_OK)
  207317. {
  207318. const char* e = "Couldn't open or write to the CD device";
  207319. if (hr == IMAPI_E_USERABORT)
  207320. e = "User cancelled the write operation";
  207321. else if (hr == IMAPI_E_MEDIUM_NOTPRESENT || hr == IMAPI_E_TRACKOPEN)
  207322. e = "No Disk present";
  207323. error = e;
  207324. }
  207325. info->discMaster->ProgressUnadvise (cookie);
  207326. info->listener = 0;
  207327. return error;
  207328. }
  207329. bool AudioCDBurner::addAudioTrack (AudioSource* source, int numSamples)
  207330. {
  207331. if (source == 0)
  207332. return false;
  207333. CDBurnerInfo* const info = (CDBurnerInfo*) internal;
  207334. long bytesPerBlock;
  207335. HRESULT hr = info->redbook->GetAudioBlockSize (&bytesPerBlock);
  207336. const int samplesPerBlock = bytesPerBlock / 4;
  207337. bool ok = true;
  207338. hr = info->redbook->CreateAudioTrack ((long) numSamples / (bytesPerBlock * 4));
  207339. byte* const buffer = (byte*) juce_malloc (bytesPerBlock);
  207340. AudioSampleBuffer sourceBuffer (2, samplesPerBlock);
  207341. int samplesDone = 0;
  207342. source->prepareToPlay (samplesPerBlock, 44100.0);
  207343. while (ok)
  207344. {
  207345. {
  207346. AudioSourceChannelInfo info;
  207347. info.buffer = &sourceBuffer;
  207348. info.numSamples = samplesPerBlock;
  207349. info.startSample = 0;
  207350. sourceBuffer.clear();
  207351. source->getNextAudioBlock (info);
  207352. }
  207353. zeromem (buffer, bytesPerBlock);
  207354. AudioDataConverters::convertFloatToInt16LE (sourceBuffer.getSampleData (0, 0),
  207355. buffer, samplesPerBlock, 4);
  207356. AudioDataConverters::convertFloatToInt16LE (sourceBuffer.getSampleData (1, 0),
  207357. buffer + 2, samplesPerBlock, 4);
  207358. hr = info->redbook->AddAudioTrackBlocks (buffer, bytesPerBlock);
  207359. if (hr != S_OK)
  207360. ok = false;
  207361. samplesDone += samplesPerBlock;
  207362. if (samplesDone >= numSamples)
  207363. break;
  207364. }
  207365. juce_free (buffer);
  207366. hr = info->redbook->CloseAudioTrack();
  207367. delete source;
  207368. return ok && hr == S_OK;
  207369. }
  207370. #endif
  207371. /********* End of inlined file: juce_win32_AudioCDReader.cpp *********/
  207372. /********* Start of inlined file: juce_win32_Midi.cpp *********/
  207373. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  207374. // compiled on its own).
  207375. #if JUCE_INCLUDED_FILE
  207376. static const int midiBufferSize = 1024 * 10;
  207377. static const int numInHeaders = 32;
  207378. static const int inBufferSize = 256;
  207379. static Array <void*, CriticalSection> activeMidiThreads;
  207380. using ::free;
  207381. class MidiInThread : public Thread
  207382. {
  207383. public:
  207384. MidiInThread (MidiInput* const input_,
  207385. MidiInputCallback* const callback_)
  207386. : Thread ("Juce Midi"),
  207387. hIn (0),
  207388. input (input_),
  207389. callback (callback_),
  207390. isStarted (false),
  207391. startTime (0),
  207392. pendingLength(0)
  207393. {
  207394. for (int i = numInHeaders; --i >= 0;)
  207395. {
  207396. zeromem (&hdr[i], sizeof (MIDIHDR));
  207397. hdr[i].lpData = inData[i];
  207398. hdr[i].dwBufferLength = inBufferSize;
  207399. }
  207400. };
  207401. ~MidiInThread()
  207402. {
  207403. stop();
  207404. if (hIn != 0)
  207405. {
  207406. int count = 5;
  207407. while (--count >= 0)
  207408. {
  207409. if (midiInClose (hIn) == MMSYSERR_NOERROR)
  207410. break;
  207411. Sleep (20);
  207412. }
  207413. }
  207414. }
  207415. void handle (const uint32 message, const uint32 timeStamp) throw()
  207416. {
  207417. const int byte = message & 0xff;
  207418. if (byte < 0x80)
  207419. return;
  207420. const int numBytes = MidiMessage::getMessageLengthFromFirstByte ((uint8) byte);
  207421. const double time = timeStampToTime (timeStamp);
  207422. lock.enter();
  207423. if (pendingLength < midiBufferSize - 12)
  207424. {
  207425. char* const p = pending + pendingLength;
  207426. *(double*) p = time;
  207427. *(uint32*) (p + 8) = numBytes;
  207428. *(uint32*) (p + 12) = message;
  207429. pendingLength += 12 + numBytes;
  207430. }
  207431. else
  207432. {
  207433. jassertfalse // midi buffer overflow! You might need to increase the size..
  207434. }
  207435. lock.exit();
  207436. notify();
  207437. }
  207438. void handleSysEx (MIDIHDR* const hdr, const uint32 timeStamp) throw()
  207439. {
  207440. const int num = hdr->dwBytesRecorded;
  207441. if (num > 0)
  207442. {
  207443. const double time = timeStampToTime (timeStamp);
  207444. lock.enter();
  207445. if (pendingLength < midiBufferSize - (8 + num))
  207446. {
  207447. char* const p = pending + pendingLength;
  207448. *(double*) p = time;
  207449. *(uint32*) (p + 8) = num;
  207450. memcpy (p + 12, hdr->lpData, num);
  207451. pendingLength += 12 + num;
  207452. }
  207453. else
  207454. {
  207455. jassertfalse // midi buffer overflow! You might need to increase the size..
  207456. }
  207457. lock.exit();
  207458. notify();
  207459. }
  207460. }
  207461. void writeBlock (const int i) throw()
  207462. {
  207463. hdr[i].dwBytesRecorded = 0;
  207464. MMRESULT res = midiInPrepareHeader (hIn, &hdr[i], sizeof (MIDIHDR));
  207465. jassert (res == MMSYSERR_NOERROR);
  207466. res = midiInAddBuffer (hIn, &hdr[i], sizeof (MIDIHDR));
  207467. jassert (res == MMSYSERR_NOERROR);
  207468. }
  207469. void run()
  207470. {
  207471. MemoryBlock pendingCopy (64);
  207472. while (! threadShouldExit())
  207473. {
  207474. for (int i = 0; i < numInHeaders; ++i)
  207475. {
  207476. if ((hdr[i].dwFlags & WHDR_DONE) != 0)
  207477. {
  207478. MMRESULT res = midiInUnprepareHeader (hIn, &hdr[i], sizeof (MIDIHDR));
  207479. (void) res;
  207480. jassert (res == MMSYSERR_NOERROR);
  207481. writeBlock (i);
  207482. }
  207483. }
  207484. lock.enter();
  207485. int len = pendingLength;
  207486. if (len > 0)
  207487. {
  207488. pendingCopy.ensureSize (len);
  207489. pendingCopy.copyFrom (pending, 0, len);
  207490. pendingLength = 0;
  207491. }
  207492. lock.exit();
  207493. //xxx needs to figure out if blocks are broken up or not
  207494. if (len == 0)
  207495. {
  207496. wait (500);
  207497. }
  207498. else
  207499. {
  207500. const char* p = (const char*) pendingCopy.getData();
  207501. while (len > 0)
  207502. {
  207503. const double time = *(const double*) p;
  207504. const int messageLen = *(const int*) (p + 8);
  207505. const MidiMessage message ((const uint8*) (p + 12), messageLen, time);
  207506. callback->handleIncomingMidiMessage (input, message);
  207507. p += 12 + messageLen;
  207508. len -= 12 + messageLen;
  207509. }
  207510. }
  207511. }
  207512. }
  207513. void start() throw()
  207514. {
  207515. jassert (hIn != 0);
  207516. if (hIn != 0 && ! isStarted)
  207517. {
  207518. stop();
  207519. activeMidiThreads.addIfNotAlreadyThere (this);
  207520. int i;
  207521. for (i = 0; i < numInHeaders; ++i)
  207522. writeBlock (i);
  207523. startTime = Time::getMillisecondCounter();
  207524. MMRESULT res = midiInStart (hIn);
  207525. jassert (res == MMSYSERR_NOERROR);
  207526. if (res == MMSYSERR_NOERROR)
  207527. {
  207528. isStarted = true;
  207529. pendingLength = 0;
  207530. startThread (6);
  207531. }
  207532. }
  207533. }
  207534. void stop() throw()
  207535. {
  207536. if (isStarted)
  207537. {
  207538. stopThread (5000);
  207539. midiInReset (hIn);
  207540. midiInStop (hIn);
  207541. activeMidiThreads.removeValue (this);
  207542. lock.enter();
  207543. lock.exit();
  207544. for (int i = numInHeaders; --i >= 0;)
  207545. {
  207546. if ((hdr[i].dwFlags & WHDR_DONE) != 0)
  207547. {
  207548. int c = 10;
  207549. while (--c >= 0 && midiInUnprepareHeader (hIn, &hdr[i], sizeof (MIDIHDR)) == MIDIERR_STILLPLAYING)
  207550. Sleep (20);
  207551. jassert (c >= 0);
  207552. }
  207553. }
  207554. isStarted = false;
  207555. pendingLength = 0;
  207556. }
  207557. }
  207558. juce_UseDebuggingNewOperator
  207559. HMIDIIN hIn;
  207560. private:
  207561. MidiInput* input;
  207562. MidiInputCallback* callback;
  207563. bool isStarted;
  207564. uint32 startTime;
  207565. CriticalSection lock;
  207566. MIDIHDR hdr [numInHeaders];
  207567. char inData [numInHeaders] [inBufferSize];
  207568. int pendingLength;
  207569. char pending [midiBufferSize];
  207570. double timeStampToTime (uint32 timeStamp) throw()
  207571. {
  207572. timeStamp += startTime;
  207573. const uint32 now = Time::getMillisecondCounter();
  207574. if (timeStamp > now)
  207575. {
  207576. if (timeStamp > now + 2)
  207577. --startTime;
  207578. timeStamp = now;
  207579. }
  207580. return 0.001 * timeStamp;
  207581. }
  207582. MidiInThread (const MidiInThread&);
  207583. const MidiInThread& operator= (const MidiInThread&);
  207584. };
  207585. static void CALLBACK midiInCallback (HMIDIIN,
  207586. UINT uMsg,
  207587. DWORD_PTR dwInstance,
  207588. DWORD_PTR midiMessage,
  207589. DWORD_PTR timeStamp)
  207590. {
  207591. MidiInThread* const thread = (MidiInThread*) dwInstance;
  207592. if (thread != 0 && activeMidiThreads.contains (thread))
  207593. {
  207594. if (uMsg == MIM_DATA)
  207595. thread->handle ((uint32) midiMessage, (uint32) timeStamp);
  207596. else if (uMsg == MIM_LONGDATA)
  207597. thread->handleSysEx ((MIDIHDR*) midiMessage, (uint32) timeStamp);
  207598. }
  207599. }
  207600. const StringArray MidiInput::getDevices()
  207601. {
  207602. StringArray s;
  207603. const int num = midiInGetNumDevs();
  207604. for (int i = 0; i < num; ++i)
  207605. {
  207606. MIDIINCAPS mc;
  207607. zerostruct (mc);
  207608. if (midiInGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  207609. s.add (String (mc.szPname, sizeof (mc.szPname)));
  207610. }
  207611. return s;
  207612. }
  207613. int MidiInput::getDefaultDeviceIndex()
  207614. {
  207615. return 0;
  207616. }
  207617. MidiInput* MidiInput::openDevice (const int index, MidiInputCallback* const callback)
  207618. {
  207619. if (callback == 0)
  207620. return 0;
  207621. UINT deviceId = MIDI_MAPPER;
  207622. int n = 0;
  207623. String name;
  207624. const int num = midiInGetNumDevs();
  207625. for (int i = 0; i < num; ++i)
  207626. {
  207627. MIDIINCAPS mc;
  207628. zerostruct (mc);
  207629. if (midiInGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  207630. {
  207631. if (index == n)
  207632. {
  207633. deviceId = i;
  207634. name = String (mc.szPname, sizeof (mc.szPname));
  207635. break;
  207636. }
  207637. ++n;
  207638. }
  207639. }
  207640. MidiInput* const in = new MidiInput (name);
  207641. MidiInThread* const thread = new MidiInThread (in, callback);
  207642. HMIDIIN h;
  207643. HRESULT err = midiInOpen (&h, deviceId,
  207644. (DWORD_PTR) &midiInCallback,
  207645. (DWORD_PTR) thread,
  207646. CALLBACK_FUNCTION);
  207647. if (err == MMSYSERR_NOERROR)
  207648. {
  207649. thread->hIn = h;
  207650. in->internal = (void*) thread;
  207651. return in;
  207652. }
  207653. else
  207654. {
  207655. delete in;
  207656. delete thread;
  207657. return 0;
  207658. }
  207659. }
  207660. MidiInput::MidiInput (const String& name_)
  207661. : name (name_),
  207662. internal (0)
  207663. {
  207664. }
  207665. MidiInput::~MidiInput()
  207666. {
  207667. if (internal != 0)
  207668. {
  207669. MidiInThread* const thread = (MidiInThread*) internal;
  207670. delete thread;
  207671. }
  207672. }
  207673. void MidiInput::start()
  207674. {
  207675. ((MidiInThread*) internal)->start();
  207676. }
  207677. void MidiInput::stop()
  207678. {
  207679. ((MidiInThread*) internal)->stop();
  207680. }
  207681. struct MidiOutHandle
  207682. {
  207683. int refCount;
  207684. UINT deviceId;
  207685. HMIDIOUT handle;
  207686. juce_UseDebuggingNewOperator
  207687. };
  207688. static VoidArray handles (4);
  207689. const StringArray MidiOutput::getDevices()
  207690. {
  207691. StringArray s;
  207692. const int num = midiOutGetNumDevs();
  207693. for (int i = 0; i < num; ++i)
  207694. {
  207695. MIDIOUTCAPS mc;
  207696. zerostruct (mc);
  207697. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  207698. s.add (String (mc.szPname, sizeof (mc.szPname)));
  207699. }
  207700. return s;
  207701. }
  207702. int MidiOutput::getDefaultDeviceIndex()
  207703. {
  207704. const int num = midiOutGetNumDevs();
  207705. int n = 0;
  207706. for (int i = 0; i < num; ++i)
  207707. {
  207708. MIDIOUTCAPS mc;
  207709. zerostruct (mc);
  207710. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  207711. {
  207712. if ((mc.wTechnology & MOD_MAPPER) != 0)
  207713. return n;
  207714. ++n;
  207715. }
  207716. }
  207717. return 0;
  207718. }
  207719. MidiOutput* MidiOutput::openDevice (int index)
  207720. {
  207721. UINT deviceId = MIDI_MAPPER;
  207722. const int num = midiOutGetNumDevs();
  207723. int i, n = 0;
  207724. for (i = 0; i < num; ++i)
  207725. {
  207726. MIDIOUTCAPS mc;
  207727. zerostruct (mc);
  207728. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  207729. {
  207730. // use the microsoft sw synth as a default - best not to allow deviceId
  207731. // to be MIDI_MAPPER, or else device sharing breaks
  207732. if (String (mc.szPname, sizeof (mc.szPname)).containsIgnoreCase (T("microsoft")))
  207733. deviceId = i;
  207734. if (index == n)
  207735. {
  207736. deviceId = i;
  207737. break;
  207738. }
  207739. ++n;
  207740. }
  207741. }
  207742. for (i = handles.size(); --i >= 0;)
  207743. {
  207744. MidiOutHandle* const han = (MidiOutHandle*) handles.getUnchecked(i);
  207745. if (han != 0 && han->deviceId == deviceId)
  207746. {
  207747. han->refCount++;
  207748. MidiOutput* const out = new MidiOutput();
  207749. out->internal = (void*) han;
  207750. return out;
  207751. }
  207752. }
  207753. for (i = 4; --i >= 0;)
  207754. {
  207755. HMIDIOUT h = 0;
  207756. MMRESULT res = midiOutOpen (&h, deviceId, 0, 0, CALLBACK_NULL);
  207757. if (res == MMSYSERR_NOERROR)
  207758. {
  207759. MidiOutHandle* const han = new MidiOutHandle();
  207760. han->deviceId = deviceId;
  207761. han->refCount = 1;
  207762. han->handle = h;
  207763. handles.add (han);
  207764. MidiOutput* const out = new MidiOutput();
  207765. out->internal = (void*) han;
  207766. return out;
  207767. }
  207768. else if (res == MMSYSERR_ALLOCATED)
  207769. {
  207770. Sleep (100);
  207771. }
  207772. else
  207773. {
  207774. break;
  207775. }
  207776. }
  207777. return 0;
  207778. }
  207779. MidiOutput::~MidiOutput()
  207780. {
  207781. MidiOutHandle* const h = (MidiOutHandle*) internal;
  207782. if (handles.contains ((void*) h) && --(h->refCount) == 0)
  207783. {
  207784. midiOutClose (h->handle);
  207785. handles.removeValue ((void*) h);
  207786. delete h;
  207787. }
  207788. }
  207789. void MidiOutput::reset()
  207790. {
  207791. const MidiOutHandle* const h = (MidiOutHandle*) internal;
  207792. midiOutReset (h->handle);
  207793. }
  207794. bool MidiOutput::getVolume (float& leftVol,
  207795. float& rightVol)
  207796. {
  207797. const MidiOutHandle* const handle = (const MidiOutHandle*) internal;
  207798. DWORD n;
  207799. if (midiOutGetVolume (handle->handle, &n) == MMSYSERR_NOERROR)
  207800. {
  207801. const unsigned short* const nn = (const unsigned short*) &n;
  207802. rightVol = nn[0] / (float) 0xffff;
  207803. leftVol = nn[1] / (float) 0xffff;
  207804. return true;
  207805. }
  207806. else
  207807. {
  207808. rightVol = leftVol = 1.0f;
  207809. return false;
  207810. }
  207811. }
  207812. void MidiOutput::setVolume (float leftVol,
  207813. float rightVol)
  207814. {
  207815. const MidiOutHandle* const handle = (MidiOutHandle*) internal;
  207816. DWORD n;
  207817. unsigned short* const nn = (unsigned short*) &n;
  207818. nn[0] = (unsigned short) jlimit (0, 0xffff, (int)(rightVol * 0xffff));
  207819. nn[1] = (unsigned short) jlimit (0, 0xffff, (int)(leftVol * 0xffff));
  207820. midiOutSetVolume (handle->handle, n);
  207821. }
  207822. void MidiOutput::sendMessageNow (const MidiMessage& message)
  207823. {
  207824. const MidiOutHandle* const handle = (const MidiOutHandle*) internal;
  207825. if (message.getRawDataSize() > 3
  207826. || message.isSysEx())
  207827. {
  207828. MIDIHDR h;
  207829. zerostruct (h);
  207830. h.lpData = (char*) message.getRawData();
  207831. h.dwBufferLength = message.getRawDataSize();
  207832. h.dwBytesRecorded = message.getRawDataSize();
  207833. if (midiOutPrepareHeader (handle->handle, &h, sizeof (MIDIHDR)) == MMSYSERR_NOERROR)
  207834. {
  207835. MMRESULT res = midiOutLongMsg (handle->handle, &h, sizeof (MIDIHDR));
  207836. if (res == MMSYSERR_NOERROR)
  207837. {
  207838. while ((h.dwFlags & MHDR_DONE) == 0)
  207839. Sleep (1);
  207840. int count = 500; // 1 sec timeout
  207841. while (--count >= 0)
  207842. {
  207843. res = midiOutUnprepareHeader (handle->handle, &h, sizeof (MIDIHDR));
  207844. if (res == MIDIERR_STILLPLAYING)
  207845. Sleep (2);
  207846. else
  207847. break;
  207848. }
  207849. }
  207850. }
  207851. }
  207852. else
  207853. {
  207854. midiOutShortMsg (handle->handle,
  207855. *(unsigned int*) message.getRawData());
  207856. }
  207857. }
  207858. #endif
  207859. /********* End of inlined file: juce_win32_Midi.cpp *********/
  207860. /********* Start of inlined file: juce_win32_ASIO.cpp *********/
  207861. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  207862. // compiled on its own).
  207863. #if JUCE_INCLUDED_FILE && JUCE_ASIO
  207864. #undef WINDOWS
  207865. // #define ASIO_DEBUGGING
  207866. #ifdef ASIO_DEBUGGING
  207867. #define log(a) { Logger::writeToLog (a); DBG (a) }
  207868. #else
  207869. #define log(a) {}
  207870. #endif
  207871. #ifdef ASIO_DEBUGGING
  207872. static void logError (const String& context, long error)
  207873. {
  207874. String err ("unknown error");
  207875. if (error == ASE_NotPresent)
  207876. err = "Not Present";
  207877. else if (error == ASE_HWMalfunction)
  207878. err = "Hardware Malfunction";
  207879. else if (error == ASE_InvalidParameter)
  207880. err = "Invalid Parameter";
  207881. else if (error == ASE_InvalidMode)
  207882. err = "Invalid Mode";
  207883. else if (error == ASE_SPNotAdvancing)
  207884. err = "Sample position not advancing";
  207885. else if (error == ASE_NoClock)
  207886. err = "No Clock";
  207887. else if (error == ASE_NoMemory)
  207888. err = "Out of memory";
  207889. log (T("!!error: ") + context + T(" - ") + err);
  207890. }
  207891. #else
  207892. #define logError(a, b) {}
  207893. #endif
  207894. class ASIOAudioIODevice;
  207895. static ASIOAudioIODevice* volatile currentASIODev[3] = { 0, 0, 0 };
  207896. static const int maxASIOChannels = 160;
  207897. class JUCE_API ASIOAudioIODevice : public AudioIODevice,
  207898. private Timer
  207899. {
  207900. public:
  207901. Component ourWindow;
  207902. ASIOAudioIODevice (const String& name_, const CLSID classId_, const int slotNumber,
  207903. const String& optionalDllForDirectLoading_)
  207904. : AudioIODevice (name_, T("ASIO")),
  207905. asioObject (0),
  207906. classId (classId_),
  207907. optionalDllForDirectLoading (optionalDllForDirectLoading_),
  207908. currentBitDepth (16),
  207909. currentSampleRate (0),
  207910. tempBuffer (0),
  207911. isOpen_ (false),
  207912. isStarted (false),
  207913. postOutput (true),
  207914. insideControlPanelModalLoop (false),
  207915. shouldUsePreferredSize (false)
  207916. {
  207917. name = name_;
  207918. ourWindow.addToDesktop (0);
  207919. windowHandle = ourWindow.getWindowHandle();
  207920. jassert (currentASIODev [slotNumber] == 0);
  207921. currentASIODev [slotNumber] = this;
  207922. openDevice();
  207923. }
  207924. ~ASIOAudioIODevice()
  207925. {
  207926. for (int i = 0; i < numElementsInArray (currentASIODev); ++i)
  207927. if (currentASIODev[i] == this)
  207928. currentASIODev[i] = 0;
  207929. close();
  207930. log ("ASIO - exiting");
  207931. removeCurrentDriver();
  207932. juce_free (tempBuffer);
  207933. }
  207934. void updateSampleRates()
  207935. {
  207936. // find a list of sample rates..
  207937. const double possibleSampleRates[] = { 44100.0, 48000.0, 88200.0, 96000.0, 176400.0, 192000.0 };
  207938. sampleRates.clear();
  207939. if (asioObject != 0)
  207940. {
  207941. for (int index = 0; index < numElementsInArray (possibleSampleRates); ++index)
  207942. {
  207943. const long err = asioObject->canSampleRate (possibleSampleRates[index]);
  207944. if (err == 0)
  207945. {
  207946. sampleRates.add ((int) possibleSampleRates[index]);
  207947. log (T("rate: ") + String ((int) possibleSampleRates[index]));
  207948. }
  207949. else if (err != ASE_NoClock)
  207950. {
  207951. logError (T("CanSampleRate"), err);
  207952. }
  207953. }
  207954. if (sampleRates.size() == 0)
  207955. {
  207956. double cr = 0;
  207957. const long err = asioObject->getSampleRate (&cr);
  207958. log (T("No sample rates supported - current rate: ") + String ((int) cr));
  207959. if (err == 0)
  207960. sampleRates.add ((int) cr);
  207961. }
  207962. }
  207963. }
  207964. const StringArray getOutputChannelNames()
  207965. {
  207966. return outputChannelNames;
  207967. }
  207968. const StringArray getInputChannelNames()
  207969. {
  207970. return inputChannelNames;
  207971. }
  207972. int getNumSampleRates()
  207973. {
  207974. return sampleRates.size();
  207975. }
  207976. double getSampleRate (int index)
  207977. {
  207978. return sampleRates [index];
  207979. }
  207980. int getNumBufferSizesAvailable()
  207981. {
  207982. return bufferSizes.size();
  207983. }
  207984. int getBufferSizeSamples (int index)
  207985. {
  207986. return bufferSizes [index];
  207987. }
  207988. int getDefaultBufferSize()
  207989. {
  207990. return preferredSize;
  207991. }
  207992. const String open (const BitArray& inputChannels,
  207993. const BitArray& outputChannels,
  207994. double sr,
  207995. int bufferSizeSamples)
  207996. {
  207997. close();
  207998. currentCallback = 0;
  207999. if (bufferSizeSamples <= 0)
  208000. shouldUsePreferredSize = true;
  208001. if (asioObject == 0 || ! isASIOOpen)
  208002. {
  208003. log ("Warning: device not open");
  208004. const String err (openDevice());
  208005. if (asioObject == 0 || ! isASIOOpen)
  208006. return err;
  208007. }
  208008. isStarted = false;
  208009. bufferIndex = -1;
  208010. long err = 0;
  208011. long newPreferredSize = 0;
  208012. // if the preferred size has just changed, assume it's a control panel thing and use it as the new value.
  208013. minSize = 0;
  208014. maxSize = 0;
  208015. newPreferredSize = 0;
  208016. granularity = 0;
  208017. if (asioObject->getBufferSize (&minSize, &maxSize, &newPreferredSize, &granularity) == 0)
  208018. {
  208019. if (preferredSize != 0 && newPreferredSize != 0 && newPreferredSize != preferredSize)
  208020. shouldUsePreferredSize = true;
  208021. preferredSize = newPreferredSize;
  208022. }
  208023. // unfortunate workaround for certain manufacturers whose drivers crash horribly if you make
  208024. // dynamic changes to the buffer size...
  208025. shouldUsePreferredSize = shouldUsePreferredSize
  208026. || getName().containsIgnoreCase (T("Digidesign"));
  208027. if (shouldUsePreferredSize)
  208028. {
  208029. log ("Using preferred size for buffer..");
  208030. if ((err = asioObject->getBufferSize (&minSize, &maxSize, &preferredSize, &granularity)) == 0)
  208031. {
  208032. bufferSizeSamples = preferredSize;
  208033. }
  208034. else
  208035. {
  208036. bufferSizeSamples = 1024;
  208037. logError ("GetBufferSize1", err);
  208038. }
  208039. shouldUsePreferredSize = false;
  208040. }
  208041. int sampleRate = roundDoubleToInt (sr);
  208042. currentSampleRate = sampleRate;
  208043. currentBlockSizeSamples = bufferSizeSamples;
  208044. currentChansOut.clear();
  208045. currentChansIn.clear();
  208046. zeromem (inBuffers, sizeof (inBuffers));
  208047. zeromem (outBuffers, sizeof (outBuffers));
  208048. updateSampleRates();
  208049. if (sampleRate == 0 || (sampleRates.size() > 0 && ! sampleRates.contains (sampleRate)))
  208050. sampleRate = sampleRates[0];
  208051. jassert (sampleRate != 0);
  208052. if (sampleRate == 0)
  208053. sampleRate = 44100;
  208054. long numSources = 32;
  208055. ASIOClockSource clocks[32];
  208056. zeromem (clocks, sizeof (clocks));
  208057. asioObject->getClockSources (clocks, &numSources);
  208058. bool isSourceSet = false;
  208059. // careful not to remove this loop because it does more than just logging!
  208060. int i;
  208061. for (i = 0; i < numSources; ++i)
  208062. {
  208063. String s ("clock: ");
  208064. s += clocks[i].name;
  208065. if (clocks[i].isCurrentSource)
  208066. {
  208067. isSourceSet = true;
  208068. s << " (cur)";
  208069. }
  208070. log (s);
  208071. }
  208072. if (numSources > 1 && ! isSourceSet)
  208073. {
  208074. log ("setting clock source");
  208075. asioObject->setClockSource (clocks[0].index);
  208076. Thread::sleep (20);
  208077. }
  208078. else
  208079. {
  208080. if (numSources == 0)
  208081. {
  208082. log ("ASIO - no clock sources!");
  208083. }
  208084. }
  208085. double cr = 0;
  208086. err = asioObject->getSampleRate (&cr);
  208087. if (err == 0)
  208088. {
  208089. currentSampleRate = cr;
  208090. }
  208091. else
  208092. {
  208093. logError ("GetSampleRate", err);
  208094. currentSampleRate = 0;
  208095. }
  208096. error = String::empty;
  208097. needToReset = false;
  208098. isReSync = false;
  208099. err = 0;
  208100. bool buffersCreated = false;
  208101. if (currentSampleRate != sampleRate)
  208102. {
  208103. log (T("ASIO samplerate: ") + String (currentSampleRate) + T(" to ") + String (sampleRate));
  208104. err = asioObject->setSampleRate (sampleRate);
  208105. if (err == ASE_NoClock && numSources > 0)
  208106. {
  208107. log ("trying to set a clock source..");
  208108. Thread::sleep (10);
  208109. err = asioObject->setClockSource (clocks[0].index);
  208110. if (err != 0)
  208111. {
  208112. logError ("SetClock", err);
  208113. }
  208114. Thread::sleep (10);
  208115. err = asioObject->setSampleRate (sampleRate);
  208116. }
  208117. }
  208118. if (err == 0)
  208119. {
  208120. currentSampleRate = sampleRate;
  208121. if (needToReset)
  208122. {
  208123. if (isReSync)
  208124. {
  208125. log ("Resync request");
  208126. }
  208127. log ("! Resetting ASIO after sample rate change");
  208128. removeCurrentDriver();
  208129. loadDriver();
  208130. const String error (initDriver());
  208131. if (error.isNotEmpty())
  208132. {
  208133. log (T("ASIOInit: ") + error);
  208134. }
  208135. needToReset = false;
  208136. isReSync = false;
  208137. }
  208138. numActiveInputChans = 0;
  208139. numActiveOutputChans = 0;
  208140. ASIOBufferInfo* info = bufferInfos;
  208141. int i;
  208142. for (i = 0; i < totalNumInputChans; ++i)
  208143. {
  208144. if (inputChannels[i])
  208145. {
  208146. currentChansIn.setBit (i);
  208147. info->isInput = 1;
  208148. info->channelNum = i;
  208149. info->buffers[0] = info->buffers[1] = 0;
  208150. ++info;
  208151. ++numActiveInputChans;
  208152. }
  208153. }
  208154. for (i = 0; i < totalNumOutputChans; ++i)
  208155. {
  208156. if (outputChannels[i])
  208157. {
  208158. currentChansOut.setBit (i);
  208159. info->isInput = 0;
  208160. info->channelNum = i;
  208161. info->buffers[0] = info->buffers[1] = 0;
  208162. ++info;
  208163. ++numActiveOutputChans;
  208164. }
  208165. }
  208166. const int totalBuffers = numActiveInputChans + numActiveOutputChans;
  208167. callbacks.sampleRateDidChange = &sampleRateChangedCallback;
  208168. if (currentASIODev[0] == this)
  208169. {
  208170. callbacks.bufferSwitch = &bufferSwitchCallback0;
  208171. callbacks.asioMessage = &asioMessagesCallback0;
  208172. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback0;
  208173. }
  208174. else if (currentASIODev[1] == this)
  208175. {
  208176. callbacks.bufferSwitch = &bufferSwitchCallback1;
  208177. callbacks.asioMessage = &asioMessagesCallback1;
  208178. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback1;
  208179. }
  208180. else if (currentASIODev[2] == this)
  208181. {
  208182. callbacks.bufferSwitch = &bufferSwitchCallback2;
  208183. callbacks.asioMessage = &asioMessagesCallback2;
  208184. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback2;
  208185. }
  208186. else
  208187. {
  208188. jassertfalse
  208189. }
  208190. log ("disposing buffers");
  208191. err = asioObject->disposeBuffers();
  208192. log (T("creating buffers: ") + String (totalBuffers) + T(", ") + String (currentBlockSizeSamples));
  208193. err = asioObject->createBuffers (bufferInfos,
  208194. totalBuffers,
  208195. currentBlockSizeSamples,
  208196. &callbacks);
  208197. if (err != 0)
  208198. {
  208199. currentBlockSizeSamples = preferredSize;
  208200. logError ("create buffers 2", err);
  208201. asioObject->disposeBuffers();
  208202. err = asioObject->createBuffers (bufferInfos,
  208203. totalBuffers,
  208204. currentBlockSizeSamples,
  208205. &callbacks);
  208206. }
  208207. if (err == 0)
  208208. {
  208209. buffersCreated = true;
  208210. juce_free (tempBuffer);
  208211. tempBuffer = (float*) juce_calloc (totalBuffers * currentBlockSizeSamples * sizeof (float) + 128);
  208212. int n = 0;
  208213. Array <int> types;
  208214. currentBitDepth = 16;
  208215. for (i = 0; i < jmin (totalNumInputChans, maxASIOChannels); ++i)
  208216. {
  208217. if (inputChannels[i])
  208218. {
  208219. inBuffers[n] = tempBuffer + (currentBlockSizeSamples * n);
  208220. ASIOChannelInfo channelInfo;
  208221. zerostruct (channelInfo);
  208222. channelInfo.channel = i;
  208223. channelInfo.isInput = 1;
  208224. asioObject->getChannelInfo (&channelInfo);
  208225. types.addIfNotAlreadyThere (channelInfo.type);
  208226. typeToFormatParameters (channelInfo.type,
  208227. inputChannelBitDepths[n],
  208228. inputChannelBytesPerSample[n],
  208229. inputChannelIsFloat[n],
  208230. inputChannelLittleEndian[n]);
  208231. currentBitDepth = jmax (currentBitDepth, inputChannelBitDepths[n]);
  208232. ++n;
  208233. }
  208234. }
  208235. jassert (numActiveInputChans == n);
  208236. n = 0;
  208237. for (i = 0; i < jmin (totalNumOutputChans, maxASIOChannels); ++i)
  208238. {
  208239. if (outputChannels[i])
  208240. {
  208241. outBuffers[n] = tempBuffer + (currentBlockSizeSamples * (numActiveInputChans + n));
  208242. ASIOChannelInfo channelInfo;
  208243. zerostruct (channelInfo);
  208244. channelInfo.channel = i;
  208245. channelInfo.isInput = 0;
  208246. asioObject->getChannelInfo (&channelInfo);
  208247. types.addIfNotAlreadyThere (channelInfo.type);
  208248. typeToFormatParameters (channelInfo.type,
  208249. outputChannelBitDepths[n],
  208250. outputChannelBytesPerSample[n],
  208251. outputChannelIsFloat[n],
  208252. outputChannelLittleEndian[n]);
  208253. currentBitDepth = jmax (currentBitDepth, outputChannelBitDepths[n]);
  208254. ++n;
  208255. }
  208256. }
  208257. jassert (numActiveOutputChans == n);
  208258. for (i = types.size(); --i >= 0;)
  208259. {
  208260. log (T("channel format: ") + String (types[i]));
  208261. }
  208262. jassert (n <= totalBuffers);
  208263. for (i = 0; i < numActiveOutputChans; ++i)
  208264. {
  208265. const int size = currentBlockSizeSamples * (outputChannelBitDepths[i] >> 3);
  208266. if (bufferInfos [numActiveInputChans + i].buffers[0] == 0
  208267. || bufferInfos [numActiveInputChans + i].buffers[1] == 0)
  208268. {
  208269. log ("!! Null buffers");
  208270. }
  208271. else
  208272. {
  208273. zeromem (bufferInfos[numActiveInputChans + i].buffers[0], size);
  208274. zeromem (bufferInfos[numActiveInputChans + i].buffers[1], size);
  208275. }
  208276. }
  208277. inputLatency = outputLatency = 0;
  208278. if (asioObject->getLatencies (&inputLatency, &outputLatency) != 0)
  208279. {
  208280. log ("ASIO - no latencies");
  208281. }
  208282. else
  208283. {
  208284. log (T("ASIO latencies: ")
  208285. + String ((int) outputLatency)
  208286. + T(", ")
  208287. + String ((int) inputLatency));
  208288. }
  208289. isOpen_ = true;
  208290. log ("starting ASIO");
  208291. calledback = false;
  208292. err = asioObject->start();
  208293. if (err != 0)
  208294. {
  208295. isOpen_ = false;
  208296. log ("ASIO - stop on failure");
  208297. Thread::sleep (10);
  208298. asioObject->stop();
  208299. error = "Can't start device";
  208300. Thread::sleep (10);
  208301. }
  208302. else
  208303. {
  208304. int count = 300;
  208305. while (--count > 0 && ! calledback)
  208306. Thread::sleep (10);
  208307. isStarted = true;
  208308. if (! calledback)
  208309. {
  208310. error = "Device didn't start correctly";
  208311. log ("ASIO didn't callback - stopping..");
  208312. asioObject->stop();
  208313. }
  208314. }
  208315. }
  208316. else
  208317. {
  208318. error = "Can't create i/o buffers";
  208319. }
  208320. }
  208321. else
  208322. {
  208323. error = "Can't set sample rate: ";
  208324. error << sampleRate;
  208325. }
  208326. if (error.isNotEmpty())
  208327. {
  208328. logError (error, err);
  208329. if (asioObject != 0 && buffersCreated)
  208330. asioObject->disposeBuffers();
  208331. Thread::sleep (20);
  208332. isStarted = false;
  208333. isOpen_ = false;
  208334. close();
  208335. }
  208336. needToReset = false;
  208337. isReSync = false;
  208338. return error;
  208339. }
  208340. void close()
  208341. {
  208342. error = String::empty;
  208343. stopTimer();
  208344. stop();
  208345. if (isASIOOpen && isOpen_)
  208346. {
  208347. const ScopedLock sl (callbackLock);
  208348. isOpen_ = false;
  208349. isStarted = false;
  208350. needToReset = false;
  208351. isReSync = false;
  208352. log ("ASIO - stopping");
  208353. if (asioObject != 0)
  208354. {
  208355. Thread::sleep (20);
  208356. asioObject->stop();
  208357. Thread::sleep (10);
  208358. asioObject->disposeBuffers();
  208359. }
  208360. Thread::sleep (10);
  208361. }
  208362. }
  208363. bool isOpen()
  208364. {
  208365. return isOpen_ || insideControlPanelModalLoop;
  208366. }
  208367. int getCurrentBufferSizeSamples()
  208368. {
  208369. return currentBlockSizeSamples;
  208370. }
  208371. double getCurrentSampleRate()
  208372. {
  208373. return currentSampleRate;
  208374. }
  208375. const BitArray getActiveOutputChannels() const
  208376. {
  208377. return currentChansOut;
  208378. }
  208379. const BitArray getActiveInputChannels() const
  208380. {
  208381. return currentChansIn;
  208382. }
  208383. int getCurrentBitDepth()
  208384. {
  208385. return currentBitDepth;
  208386. }
  208387. int getOutputLatencyInSamples()
  208388. {
  208389. return outputLatency + currentBlockSizeSamples / 4;
  208390. }
  208391. int getInputLatencyInSamples()
  208392. {
  208393. return inputLatency + currentBlockSizeSamples / 4;
  208394. }
  208395. void start (AudioIODeviceCallback* callback)
  208396. {
  208397. if (callback != 0)
  208398. {
  208399. callback->audioDeviceAboutToStart (this);
  208400. const ScopedLock sl (callbackLock);
  208401. currentCallback = callback;
  208402. }
  208403. }
  208404. void stop()
  208405. {
  208406. AudioIODeviceCallback* const lastCallback = currentCallback;
  208407. {
  208408. const ScopedLock sl (callbackLock);
  208409. currentCallback = 0;
  208410. }
  208411. if (lastCallback != 0)
  208412. lastCallback->audioDeviceStopped();
  208413. }
  208414. bool isPlaying()
  208415. {
  208416. return isASIOOpen && (currentCallback != 0);
  208417. }
  208418. const String getLastError()
  208419. {
  208420. return error;
  208421. }
  208422. bool hasControlPanel() const
  208423. {
  208424. return true;
  208425. }
  208426. bool showControlPanel()
  208427. {
  208428. log ("ASIO - showing control panel");
  208429. Component modalWindow (String::empty);
  208430. modalWindow.setOpaque (true);
  208431. modalWindow.addToDesktop (0);
  208432. modalWindow.enterModalState();
  208433. bool done = false;
  208434. JUCE_TRY
  208435. {
  208436. // are there are devices that need to be closed before showing their control panel?
  208437. // close();
  208438. insideControlPanelModalLoop = true;
  208439. const uint32 started = Time::getMillisecondCounter();
  208440. if (asioObject != 0)
  208441. {
  208442. asioObject->controlPanel();
  208443. const int spent = (int) Time::getMillisecondCounter() - (int) started;
  208444. log (T("spent: ") + String (spent));
  208445. if (spent > 300)
  208446. {
  208447. shouldUsePreferredSize = true;
  208448. done = true;
  208449. }
  208450. }
  208451. }
  208452. JUCE_CATCH_ALL
  208453. insideControlPanelModalLoop = false;
  208454. return done;
  208455. }
  208456. void resetRequest() throw()
  208457. {
  208458. needToReset = true;
  208459. }
  208460. void resyncRequest() throw()
  208461. {
  208462. needToReset = true;
  208463. isReSync = true;
  208464. }
  208465. void timerCallback()
  208466. {
  208467. if (! insideControlPanelModalLoop)
  208468. {
  208469. stopTimer();
  208470. // used to cause a reset
  208471. log ("! ASIO restart request!");
  208472. if (isOpen_)
  208473. {
  208474. AudioIODeviceCallback* const oldCallback = currentCallback;
  208475. close();
  208476. open (BitArray (currentChansIn), BitArray (currentChansOut),
  208477. currentSampleRate, currentBlockSizeSamples);
  208478. if (oldCallback != 0)
  208479. start (oldCallback);
  208480. }
  208481. }
  208482. else
  208483. {
  208484. startTimer (100);
  208485. }
  208486. }
  208487. juce_UseDebuggingNewOperator
  208488. private:
  208489. IASIO* volatile asioObject;
  208490. ASIOCallbacks callbacks;
  208491. void* windowHandle;
  208492. CLSID classId;
  208493. const String optionalDllForDirectLoading;
  208494. String error;
  208495. long totalNumInputChans, totalNumOutputChans;
  208496. StringArray inputChannelNames, outputChannelNames;
  208497. Array<int> sampleRates, bufferSizes;
  208498. long inputLatency, outputLatency;
  208499. long minSize, maxSize, preferredSize, granularity;
  208500. int volatile currentBlockSizeSamples;
  208501. int volatile currentBitDepth;
  208502. double volatile currentSampleRate;
  208503. BitArray currentChansOut, currentChansIn;
  208504. AudioIODeviceCallback* volatile currentCallback;
  208505. CriticalSection callbackLock;
  208506. ASIOBufferInfo bufferInfos [maxASIOChannels];
  208507. float* inBuffers [maxASIOChannels];
  208508. float* outBuffers [maxASIOChannels];
  208509. int inputChannelBitDepths [maxASIOChannels];
  208510. int outputChannelBitDepths [maxASIOChannels];
  208511. int inputChannelBytesPerSample [maxASIOChannels];
  208512. int outputChannelBytesPerSample [maxASIOChannels];
  208513. bool inputChannelIsFloat [maxASIOChannels];
  208514. bool outputChannelIsFloat [maxASIOChannels];
  208515. bool inputChannelLittleEndian [maxASIOChannels];
  208516. bool outputChannelLittleEndian [maxASIOChannels];
  208517. WaitableEvent event1;
  208518. float* tempBuffer;
  208519. int volatile bufferIndex, numActiveInputChans, numActiveOutputChans;
  208520. bool isOpen_, isStarted;
  208521. bool volatile isASIOOpen;
  208522. bool volatile calledback;
  208523. bool volatile littleEndian, postOutput, needToReset, isReSync;
  208524. bool volatile insideControlPanelModalLoop;
  208525. bool volatile shouldUsePreferredSize;
  208526. void removeCurrentDriver()
  208527. {
  208528. if (asioObject != 0)
  208529. {
  208530. asioObject->Release();
  208531. asioObject = 0;
  208532. }
  208533. }
  208534. bool loadDriver()
  208535. {
  208536. removeCurrentDriver();
  208537. JUCE_TRY
  208538. {
  208539. if (CoCreateInstance (classId, 0, CLSCTX_INPROC_SERVER,
  208540. classId, (void**) &asioObject) == S_OK)
  208541. {
  208542. return true;
  208543. }
  208544. // If a class isn't registered but we have a path for it, we can fallback to
  208545. // doing a direct load of the COM object (only available via the juce_createASIOAudioIODeviceForGUID function).
  208546. if (optionalDllForDirectLoading.isNotEmpty())
  208547. {
  208548. HMODULE h = LoadLibrary (optionalDllForDirectLoading);
  208549. if (h != 0)
  208550. {
  208551. typedef HRESULT (CALLBACK* DllGetClassObjectFunc) (REFCLSID clsid, REFIID iid, LPVOID* ppv);
  208552. DllGetClassObjectFunc dllGetClassObject = (DllGetClassObjectFunc) GetProcAddress (h, "DllGetClassObject");
  208553. if (dllGetClassObject != 0)
  208554. {
  208555. IClassFactory* classFactory = 0;
  208556. HRESULT hr = dllGetClassObject (classId, IID_IClassFactory, (void**) &classFactory);
  208557. if (classFactory != 0)
  208558. {
  208559. hr = classFactory->CreateInstance (0, classId, (void**) &asioObject);
  208560. classFactory->Release();
  208561. }
  208562. return asioObject != 0;
  208563. }
  208564. }
  208565. }
  208566. }
  208567. JUCE_CATCH_ALL
  208568. asioObject = 0;
  208569. return false;
  208570. }
  208571. const String initDriver()
  208572. {
  208573. if (asioObject != 0)
  208574. {
  208575. char buffer [256];
  208576. zeromem (buffer, sizeof (buffer));
  208577. if (! asioObject->init (windowHandle))
  208578. {
  208579. asioObject->getErrorMessage (buffer);
  208580. return String (buffer, sizeof (buffer) - 1);
  208581. }
  208582. // just in case any daft drivers expect this to be called..
  208583. asioObject->getDriverName (buffer);
  208584. return String::empty;
  208585. }
  208586. return "No Driver";
  208587. }
  208588. const String openDevice()
  208589. {
  208590. // use this in case the driver starts opening dialog boxes..
  208591. Component modalWindow (String::empty);
  208592. modalWindow.setOpaque (true);
  208593. modalWindow.addToDesktop (0);
  208594. modalWindow.enterModalState();
  208595. // open the device and get its info..
  208596. log (T("opening ASIO device: ") + getName());
  208597. needToReset = false;
  208598. isReSync = false;
  208599. outputChannelNames.clear();
  208600. inputChannelNames.clear();
  208601. bufferSizes.clear();
  208602. sampleRates.clear();
  208603. isASIOOpen = false;
  208604. isOpen_ = false;
  208605. totalNumInputChans = 0;
  208606. totalNumOutputChans = 0;
  208607. numActiveInputChans = 0;
  208608. numActiveOutputChans = 0;
  208609. currentCallback = 0;
  208610. error = String::empty;
  208611. if (getName().isEmpty())
  208612. return error;
  208613. long err = 0;
  208614. if (loadDriver())
  208615. {
  208616. if ((error = initDriver()).isEmpty())
  208617. {
  208618. numActiveInputChans = 0;
  208619. numActiveOutputChans = 0;
  208620. totalNumInputChans = 0;
  208621. totalNumOutputChans = 0;
  208622. if (asioObject != 0
  208623. && (err = asioObject->getChannels (&totalNumInputChans, &totalNumOutputChans)) == 0)
  208624. {
  208625. log (String ((int) totalNumInputChans) + T(" in, ") + String ((int) totalNumOutputChans) + T(" out"));
  208626. if ((err = asioObject->getBufferSize (&minSize, &maxSize, &preferredSize, &granularity)) == 0)
  208627. {
  208628. // find a list of buffer sizes..
  208629. log (String ((int) minSize) + T(" ") + String ((int) maxSize) + T(" ") + String ((int)preferredSize) + T(" ") + String ((int)granularity));
  208630. if (granularity >= 0)
  208631. {
  208632. granularity = jmax (1, (int) granularity);
  208633. for (int i = jmax (minSize, (int) granularity); i < jmin (6400, maxSize); i += granularity)
  208634. bufferSizes.addIfNotAlreadyThere (granularity * (i / granularity));
  208635. }
  208636. else if (granularity < 0)
  208637. {
  208638. for (int i = 0; i < 18; ++i)
  208639. {
  208640. const int s = (1 << i);
  208641. if (s >= minSize && s <= maxSize)
  208642. bufferSizes.add (s);
  208643. }
  208644. }
  208645. if (! bufferSizes.contains (preferredSize))
  208646. bufferSizes.insert (0, preferredSize);
  208647. double currentRate = 0;
  208648. asioObject->getSampleRate (&currentRate);
  208649. if (currentRate <= 0.0 || currentRate > 192001.0)
  208650. {
  208651. log ("setting sample rate");
  208652. err = asioObject->setSampleRate (44100.0);
  208653. if (err != 0)
  208654. {
  208655. logError ("setting sample rate", err);
  208656. }
  208657. asioObject->getSampleRate (&currentRate);
  208658. }
  208659. currentSampleRate = currentRate;
  208660. postOutput = (asioObject->outputReady() == 0);
  208661. if (postOutput)
  208662. {
  208663. log ("ASIO outputReady = ok");
  208664. }
  208665. updateSampleRates();
  208666. // ..because cubase does it at this point
  208667. inputLatency = outputLatency = 0;
  208668. if (asioObject->getLatencies (&inputLatency, &outputLatency) != 0)
  208669. {
  208670. log ("ASIO - no latencies");
  208671. }
  208672. log (String ("latencies: ")
  208673. + String ((int) inputLatency)
  208674. + T(", ") + String ((int) outputLatency));
  208675. // create some dummy buffers now.. because cubase does..
  208676. numActiveInputChans = 0;
  208677. numActiveOutputChans = 0;
  208678. ASIOBufferInfo* info = bufferInfos;
  208679. int i, numChans = 0;
  208680. for (i = 0; i < jmin (2, totalNumInputChans); ++i)
  208681. {
  208682. info->isInput = 1;
  208683. info->channelNum = i;
  208684. info->buffers[0] = info->buffers[1] = 0;
  208685. ++info;
  208686. ++numChans;
  208687. }
  208688. const int outputBufferIndex = numChans;
  208689. for (i = 0; i < jmin (2, totalNumOutputChans); ++i)
  208690. {
  208691. info->isInput = 0;
  208692. info->channelNum = i;
  208693. info->buffers[0] = info->buffers[1] = 0;
  208694. ++info;
  208695. ++numChans;
  208696. }
  208697. callbacks.sampleRateDidChange = &sampleRateChangedCallback;
  208698. if (currentASIODev[0] == this)
  208699. {
  208700. callbacks.bufferSwitch = &bufferSwitchCallback0;
  208701. callbacks.asioMessage = &asioMessagesCallback0;
  208702. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback0;
  208703. }
  208704. else if (currentASIODev[1] == this)
  208705. {
  208706. callbacks.bufferSwitch = &bufferSwitchCallback1;
  208707. callbacks.asioMessage = &asioMessagesCallback1;
  208708. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback1;
  208709. }
  208710. else if (currentASIODev[2] == this)
  208711. {
  208712. callbacks.bufferSwitch = &bufferSwitchCallback2;
  208713. callbacks.asioMessage = &asioMessagesCallback2;
  208714. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback2;
  208715. }
  208716. else
  208717. {
  208718. jassertfalse
  208719. }
  208720. log (T("creating buffers (dummy): ") + String (numChans)
  208721. + T(", ") + String ((int) preferredSize));
  208722. if (preferredSize > 0)
  208723. {
  208724. err = asioObject->createBuffers (bufferInfos, numChans, preferredSize, &callbacks);
  208725. if (err != 0)
  208726. {
  208727. logError ("dummy buffers", err);
  208728. }
  208729. }
  208730. long newInps = 0, newOuts = 0;
  208731. asioObject->getChannels (&newInps, &newOuts);
  208732. if (totalNumInputChans != newInps || totalNumOutputChans != newOuts)
  208733. {
  208734. totalNumInputChans = newInps;
  208735. totalNumOutputChans = newOuts;
  208736. log (String ((int) totalNumInputChans) + T(" in; ")
  208737. + String ((int) totalNumOutputChans) + T(" out"));
  208738. }
  208739. updateSampleRates();
  208740. ASIOChannelInfo channelInfo;
  208741. channelInfo.type = 0;
  208742. for (i = 0; i < totalNumInputChans; ++i)
  208743. {
  208744. zerostruct (channelInfo);
  208745. channelInfo.channel = i;
  208746. channelInfo.isInput = 1;
  208747. asioObject->getChannelInfo (&channelInfo);
  208748. inputChannelNames.add (String (channelInfo.name));
  208749. }
  208750. for (i = 0; i < totalNumOutputChans; ++i)
  208751. {
  208752. zerostruct (channelInfo);
  208753. channelInfo.channel = i;
  208754. channelInfo.isInput = 0;
  208755. asioObject->getChannelInfo (&channelInfo);
  208756. outputChannelNames.add (String (channelInfo.name));
  208757. typeToFormatParameters (channelInfo.type,
  208758. outputChannelBitDepths[i],
  208759. outputChannelBytesPerSample[i],
  208760. outputChannelIsFloat[i],
  208761. outputChannelLittleEndian[i]);
  208762. if (i < 2)
  208763. {
  208764. // clear the channels that are used with the dummy stuff
  208765. const int bytesPerBuffer = preferredSize * (outputChannelBitDepths[i] >> 3);
  208766. zeromem (bufferInfos [outputBufferIndex + i].buffers[0], bytesPerBuffer);
  208767. zeromem (bufferInfos [outputBufferIndex + i].buffers[1], bytesPerBuffer);
  208768. }
  208769. }
  208770. outputChannelNames.trim();
  208771. inputChannelNames.trim();
  208772. outputChannelNames.appendNumbersToDuplicates (false, true);
  208773. inputChannelNames.appendNumbersToDuplicates (false, true);
  208774. // start and stop because cubase does it..
  208775. asioObject->getLatencies (&inputLatency, &outputLatency);
  208776. if ((err = asioObject->start()) != 0)
  208777. {
  208778. // ignore an error here, as it might start later after setting other stuff up
  208779. logError ("ASIO start", err);
  208780. }
  208781. Thread::sleep (100);
  208782. asioObject->stop();
  208783. }
  208784. else
  208785. {
  208786. error = "Can't detect buffer sizes";
  208787. }
  208788. }
  208789. else
  208790. {
  208791. error = "Can't detect asio channels";
  208792. }
  208793. }
  208794. }
  208795. else
  208796. {
  208797. error = "No such device";
  208798. }
  208799. if (error.isNotEmpty())
  208800. {
  208801. logError (error, err);
  208802. if (asioObject != 0)
  208803. asioObject->disposeBuffers();
  208804. removeCurrentDriver();
  208805. isASIOOpen = false;
  208806. }
  208807. else
  208808. {
  208809. isASIOOpen = true;
  208810. log ("ASIO device open");
  208811. }
  208812. isOpen_ = false;
  208813. needToReset = false;
  208814. isReSync = false;
  208815. return error;
  208816. }
  208817. void callback (const long index) throw()
  208818. {
  208819. if (isStarted)
  208820. {
  208821. bufferIndex = index;
  208822. processBuffer();
  208823. }
  208824. else
  208825. {
  208826. if (postOutput && (asioObject != 0))
  208827. asioObject->outputReady();
  208828. }
  208829. calledback = true;
  208830. }
  208831. void processBuffer() throw()
  208832. {
  208833. const ASIOBufferInfo* const infos = bufferInfos;
  208834. const int bi = bufferIndex;
  208835. const ScopedLock sl (callbackLock);
  208836. if (needToReset)
  208837. {
  208838. needToReset = false;
  208839. if (isReSync)
  208840. {
  208841. log ("! ASIO resync");
  208842. isReSync = false;
  208843. }
  208844. else
  208845. {
  208846. startTimer (20);
  208847. }
  208848. }
  208849. if (bi >= 0)
  208850. {
  208851. const int samps = currentBlockSizeSamples;
  208852. if (currentCallback != 0)
  208853. {
  208854. int i;
  208855. for (i = 0; i < numActiveInputChans; ++i)
  208856. {
  208857. float* const dst = inBuffers[i];
  208858. jassert (dst != 0);
  208859. const char* const src = (const char*) (infos[i].buffers[bi]);
  208860. if (inputChannelIsFloat[i])
  208861. {
  208862. memcpy (dst, src, samps * sizeof (float));
  208863. }
  208864. else
  208865. {
  208866. jassert (dst == tempBuffer + (samps * i));
  208867. switch (inputChannelBitDepths[i])
  208868. {
  208869. case 16:
  208870. convertInt16ToFloat (src, dst, inputChannelBytesPerSample[i],
  208871. samps, inputChannelLittleEndian[i]);
  208872. break;
  208873. case 24:
  208874. convertInt24ToFloat (src, dst, inputChannelBytesPerSample[i],
  208875. samps, inputChannelLittleEndian[i]);
  208876. break;
  208877. case 32:
  208878. convertInt32ToFloat (src, dst, inputChannelBytesPerSample[i],
  208879. samps, inputChannelLittleEndian[i]);
  208880. break;
  208881. case 64:
  208882. jassertfalse
  208883. break;
  208884. }
  208885. }
  208886. }
  208887. currentCallback->audioDeviceIOCallback ((const float**) inBuffers,
  208888. numActiveInputChans,
  208889. outBuffers,
  208890. numActiveOutputChans,
  208891. samps);
  208892. for (i = 0; i < numActiveOutputChans; ++i)
  208893. {
  208894. float* const src = outBuffers[i];
  208895. jassert (src != 0);
  208896. char* const dst = (char*) (infos [numActiveInputChans + i].buffers[bi]);
  208897. if (outputChannelIsFloat[i])
  208898. {
  208899. memcpy (dst, src, samps * sizeof (float));
  208900. }
  208901. else
  208902. {
  208903. jassert (src == tempBuffer + (samps * (numActiveInputChans + i)));
  208904. switch (outputChannelBitDepths[i])
  208905. {
  208906. case 16:
  208907. convertFloatToInt16 (src, dst, outputChannelBytesPerSample[i],
  208908. samps, outputChannelLittleEndian[i]);
  208909. break;
  208910. case 24:
  208911. convertFloatToInt24 (src, dst, outputChannelBytesPerSample[i],
  208912. samps, outputChannelLittleEndian[i]);
  208913. break;
  208914. case 32:
  208915. convertFloatToInt32 (src, dst, outputChannelBytesPerSample[i],
  208916. samps, outputChannelLittleEndian[i]);
  208917. break;
  208918. case 64:
  208919. jassertfalse
  208920. break;
  208921. }
  208922. }
  208923. }
  208924. }
  208925. else
  208926. {
  208927. for (int i = 0; i < numActiveOutputChans; ++i)
  208928. {
  208929. const int bytesPerBuffer = samps * (outputChannelBitDepths[i] >> 3);
  208930. zeromem (infos[numActiveInputChans + i].buffers[bi], bytesPerBuffer);
  208931. }
  208932. }
  208933. }
  208934. if (postOutput)
  208935. asioObject->outputReady();
  208936. }
  208937. static ASIOTime* bufferSwitchTimeInfoCallback0 (ASIOTime*, long index, long) throw()
  208938. {
  208939. if (currentASIODev[0] != 0)
  208940. currentASIODev[0]->callback (index);
  208941. return 0;
  208942. }
  208943. static ASIOTime* bufferSwitchTimeInfoCallback1 (ASIOTime*, long index, long) throw()
  208944. {
  208945. if (currentASIODev[1] != 0)
  208946. currentASIODev[1]->callback (index);
  208947. return 0;
  208948. }
  208949. static ASIOTime* bufferSwitchTimeInfoCallback2 (ASIOTime*, long index, long) throw()
  208950. {
  208951. if (currentASIODev[2] != 0)
  208952. currentASIODev[2]->callback (index);
  208953. return 0;
  208954. }
  208955. static void bufferSwitchCallback0 (long index, long) throw()
  208956. {
  208957. if (currentASIODev[0] != 0)
  208958. currentASIODev[0]->callback (index);
  208959. }
  208960. static void bufferSwitchCallback1 (long index, long) throw()
  208961. {
  208962. if (currentASIODev[1] != 0)
  208963. currentASIODev[1]->callback (index);
  208964. }
  208965. static void bufferSwitchCallback2 (long index, long) throw()
  208966. {
  208967. if (currentASIODev[2] != 0)
  208968. currentASIODev[2]->callback (index);
  208969. }
  208970. static long asioMessagesCallback0 (long selector, long value, void*, double*) throw()
  208971. {
  208972. return asioMessagesCallback (selector, value, 0);
  208973. }
  208974. static long asioMessagesCallback1 (long selector, long value, void*, double*) throw()
  208975. {
  208976. return asioMessagesCallback (selector, value, 1);
  208977. }
  208978. static long asioMessagesCallback2 (long selector, long value, void*, double*) throw()
  208979. {
  208980. return asioMessagesCallback (selector, value, 2);
  208981. }
  208982. static long asioMessagesCallback (long selector, long value, const int deviceIndex) throw()
  208983. {
  208984. switch (selector)
  208985. {
  208986. case kAsioSelectorSupported:
  208987. if (value == kAsioResetRequest
  208988. || value == kAsioEngineVersion
  208989. || value == kAsioResyncRequest
  208990. || value == kAsioLatenciesChanged
  208991. || value == kAsioSupportsInputMonitor)
  208992. return 1;
  208993. break;
  208994. case kAsioBufferSizeChange:
  208995. break;
  208996. case kAsioResetRequest:
  208997. if (currentASIODev[deviceIndex] != 0)
  208998. currentASIODev[deviceIndex]->resetRequest();
  208999. return 1;
  209000. case kAsioResyncRequest:
  209001. if (currentASIODev[deviceIndex] != 0)
  209002. currentASIODev[deviceIndex]->resyncRequest();
  209003. return 1;
  209004. case kAsioLatenciesChanged:
  209005. return 1;
  209006. case kAsioEngineVersion:
  209007. return 2;
  209008. case kAsioSupportsTimeInfo:
  209009. case kAsioSupportsTimeCode:
  209010. return 0;
  209011. }
  209012. return 0;
  209013. }
  209014. static void sampleRateChangedCallback (ASIOSampleRate) throw()
  209015. {
  209016. }
  209017. static void convertInt16ToFloat (const char* src,
  209018. float* dest,
  209019. const int srcStrideBytes,
  209020. int numSamples,
  209021. const bool littleEndian) throw()
  209022. {
  209023. const double g = 1.0 / 32768.0;
  209024. if (littleEndian)
  209025. {
  209026. while (--numSamples >= 0)
  209027. {
  209028. *dest++ = (float) (g * (short) littleEndianShort (src));
  209029. src += srcStrideBytes;
  209030. }
  209031. }
  209032. else
  209033. {
  209034. while (--numSamples >= 0)
  209035. {
  209036. *dest++ = (float) (g * (short) bigEndianShort (src));
  209037. src += srcStrideBytes;
  209038. }
  209039. }
  209040. }
  209041. static void convertFloatToInt16 (const float* src,
  209042. char* dest,
  209043. const int dstStrideBytes,
  209044. int numSamples,
  209045. const bool littleEndian) throw()
  209046. {
  209047. const double maxVal = (double) 0x7fff;
  209048. if (littleEndian)
  209049. {
  209050. while (--numSamples >= 0)
  209051. {
  209052. *(uint16*) dest = swapIfBigEndian ((uint16) (short) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  209053. dest += dstStrideBytes;
  209054. }
  209055. }
  209056. else
  209057. {
  209058. while (--numSamples >= 0)
  209059. {
  209060. *(uint16*) dest = swapIfLittleEndian ((uint16) (short) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  209061. dest += dstStrideBytes;
  209062. }
  209063. }
  209064. }
  209065. static void convertInt24ToFloat (const char* src,
  209066. float* dest,
  209067. const int srcStrideBytes,
  209068. int numSamples,
  209069. const bool littleEndian) throw()
  209070. {
  209071. const double g = 1.0 / 0x7fffff;
  209072. if (littleEndian)
  209073. {
  209074. while (--numSamples >= 0)
  209075. {
  209076. *dest++ = (float) (g * littleEndian24Bit (src));
  209077. src += srcStrideBytes;
  209078. }
  209079. }
  209080. else
  209081. {
  209082. while (--numSamples >= 0)
  209083. {
  209084. *dest++ = (float) (g * bigEndian24Bit (src));
  209085. src += srcStrideBytes;
  209086. }
  209087. }
  209088. }
  209089. static void convertFloatToInt24 (const float* src,
  209090. char* dest,
  209091. const int dstStrideBytes,
  209092. int numSamples,
  209093. const bool littleEndian) throw()
  209094. {
  209095. const double maxVal = (double) 0x7fffff;
  209096. if (littleEndian)
  209097. {
  209098. while (--numSamples >= 0)
  209099. {
  209100. littleEndian24BitToChars ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)), dest);
  209101. dest += dstStrideBytes;
  209102. }
  209103. }
  209104. else
  209105. {
  209106. while (--numSamples >= 0)
  209107. {
  209108. bigEndian24BitToChars ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)), dest);
  209109. dest += dstStrideBytes;
  209110. }
  209111. }
  209112. }
  209113. static void convertInt32ToFloat (const char* src,
  209114. float* dest,
  209115. const int srcStrideBytes,
  209116. int numSamples,
  209117. const bool littleEndian) throw()
  209118. {
  209119. const double g = 1.0 / 0x7fffffff;
  209120. if (littleEndian)
  209121. {
  209122. while (--numSamples >= 0)
  209123. {
  209124. *dest++ = (float) (g * (int) littleEndianInt (src));
  209125. src += srcStrideBytes;
  209126. }
  209127. }
  209128. else
  209129. {
  209130. while (--numSamples >= 0)
  209131. {
  209132. *dest++ = (float) (g * (int) bigEndianInt (src));
  209133. src += srcStrideBytes;
  209134. }
  209135. }
  209136. }
  209137. static void convertFloatToInt32 (const float* src,
  209138. char* dest,
  209139. const int dstStrideBytes,
  209140. int numSamples,
  209141. const bool littleEndian) throw()
  209142. {
  209143. const double maxVal = (double) 0x7fffffff;
  209144. if (littleEndian)
  209145. {
  209146. while (--numSamples >= 0)
  209147. {
  209148. *(uint32*) dest = swapIfBigEndian ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  209149. dest += dstStrideBytes;
  209150. }
  209151. }
  209152. else
  209153. {
  209154. while (--numSamples >= 0)
  209155. {
  209156. *(uint32*) dest = swapIfLittleEndian ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  209157. dest += dstStrideBytes;
  209158. }
  209159. }
  209160. }
  209161. static void typeToFormatParameters (const long type,
  209162. int& bitDepth,
  209163. int& byteStride,
  209164. bool& formatIsFloat,
  209165. bool& littleEndian) throw()
  209166. {
  209167. bitDepth = 0;
  209168. littleEndian = false;
  209169. formatIsFloat = false;
  209170. switch (type)
  209171. {
  209172. case ASIOSTInt16MSB:
  209173. case ASIOSTInt16LSB:
  209174. case ASIOSTInt32MSB16:
  209175. case ASIOSTInt32LSB16:
  209176. bitDepth = 16; break;
  209177. case ASIOSTFloat32MSB:
  209178. case ASIOSTFloat32LSB:
  209179. formatIsFloat = true;
  209180. bitDepth = 32; break;
  209181. case ASIOSTInt32MSB:
  209182. case ASIOSTInt32LSB:
  209183. bitDepth = 32; break;
  209184. case ASIOSTInt24MSB:
  209185. case ASIOSTInt24LSB:
  209186. case ASIOSTInt32MSB24:
  209187. case ASIOSTInt32LSB24:
  209188. case ASIOSTInt32MSB18:
  209189. case ASIOSTInt32MSB20:
  209190. case ASIOSTInt32LSB18:
  209191. case ASIOSTInt32LSB20:
  209192. bitDepth = 24; break;
  209193. case ASIOSTFloat64MSB:
  209194. case ASIOSTFloat64LSB:
  209195. default:
  209196. bitDepth = 64;
  209197. break;
  209198. }
  209199. switch (type)
  209200. {
  209201. case ASIOSTInt16MSB:
  209202. case ASIOSTInt32MSB16:
  209203. case ASIOSTFloat32MSB:
  209204. case ASIOSTFloat64MSB:
  209205. case ASIOSTInt32MSB:
  209206. case ASIOSTInt32MSB18:
  209207. case ASIOSTInt32MSB20:
  209208. case ASIOSTInt32MSB24:
  209209. case ASIOSTInt24MSB:
  209210. littleEndian = false; break;
  209211. case ASIOSTInt16LSB:
  209212. case ASIOSTInt32LSB16:
  209213. case ASIOSTFloat32LSB:
  209214. case ASIOSTFloat64LSB:
  209215. case ASIOSTInt32LSB:
  209216. case ASIOSTInt32LSB18:
  209217. case ASIOSTInt32LSB20:
  209218. case ASIOSTInt32LSB24:
  209219. case ASIOSTInt24LSB:
  209220. littleEndian = true; break;
  209221. default:
  209222. break;
  209223. }
  209224. switch (type)
  209225. {
  209226. case ASIOSTInt16LSB:
  209227. case ASIOSTInt16MSB:
  209228. byteStride = 2; break;
  209229. case ASIOSTInt24LSB:
  209230. case ASIOSTInt24MSB:
  209231. byteStride = 3; break;
  209232. case ASIOSTInt32MSB16:
  209233. case ASIOSTInt32LSB16:
  209234. case ASIOSTInt32MSB:
  209235. case ASIOSTInt32MSB18:
  209236. case ASIOSTInt32MSB20:
  209237. case ASIOSTInt32MSB24:
  209238. case ASIOSTInt32LSB:
  209239. case ASIOSTInt32LSB18:
  209240. case ASIOSTInt32LSB20:
  209241. case ASIOSTInt32LSB24:
  209242. case ASIOSTFloat32LSB:
  209243. case ASIOSTFloat32MSB:
  209244. byteStride = 4; break;
  209245. case ASIOSTFloat64MSB:
  209246. case ASIOSTFloat64LSB:
  209247. byteStride = 8; break;
  209248. default:
  209249. break;
  209250. }
  209251. }
  209252. };
  209253. class ASIOAudioIODeviceType : public AudioIODeviceType
  209254. {
  209255. public:
  209256. ASIOAudioIODeviceType()
  209257. : AudioIODeviceType (T("ASIO")),
  209258. classIds (2),
  209259. hasScanned (false)
  209260. {
  209261. CoInitialize (0);
  209262. }
  209263. ~ASIOAudioIODeviceType()
  209264. {
  209265. }
  209266. void scanForDevices()
  209267. {
  209268. hasScanned = true;
  209269. deviceNames.clear();
  209270. classIds.clear();
  209271. HKEY hk = 0;
  209272. int index = 0;
  209273. if (RegOpenKeyA (HKEY_LOCAL_MACHINE, "software\\asio", &hk) == ERROR_SUCCESS)
  209274. {
  209275. for (;;)
  209276. {
  209277. char name [256];
  209278. if (RegEnumKeyA (hk, index++, name, 256) == ERROR_SUCCESS)
  209279. {
  209280. addDriverInfo (name, hk);
  209281. }
  209282. else
  209283. {
  209284. break;
  209285. }
  209286. }
  209287. RegCloseKey (hk);
  209288. }
  209289. }
  209290. const StringArray getDeviceNames (const bool /*wantInputNames*/) const
  209291. {
  209292. jassert (hasScanned); // need to call scanForDevices() before doing this
  209293. return deviceNames;
  209294. }
  209295. int getDefaultDeviceIndex (const bool) const
  209296. {
  209297. jassert (hasScanned); // need to call scanForDevices() before doing this
  209298. for (int i = deviceNames.size(); --i >= 0;)
  209299. if (deviceNames[i].containsIgnoreCase (T("asio4all")))
  209300. return i; // asio4all is a safe choice for a default..
  209301. #if JUCE_DEBUG
  209302. if (deviceNames.size() > 1 && deviceNames[0].containsIgnoreCase (T("digidesign")))
  209303. return 1; // (the digi m-box driver crashes the app when you run
  209304. // it in the debugger, which can be a bit annoying)
  209305. #endif
  209306. return 0;
  209307. }
  209308. static int findFreeSlot()
  209309. {
  209310. for (int i = 0; i < numElementsInArray (currentASIODev); ++i)
  209311. if (currentASIODev[i] == 0)
  209312. return i;
  209313. jassertfalse; // unfortunately you can only have a finite number
  209314. // of ASIO devices open at the same time..
  209315. return -1;
  209316. }
  209317. int getIndexOfDevice (AudioIODevice* d, const bool /*asInput*/) const
  209318. {
  209319. jassert (hasScanned); // need to call scanForDevices() before doing this
  209320. return d == 0 ? -1 : deviceNames.indexOf (d->getName());
  209321. }
  209322. bool hasSeparateInputsAndOutputs() const { return false; }
  209323. AudioIODevice* createDevice (const String& outputDeviceName,
  209324. const String& inputDeviceName)
  209325. {
  209326. jassert (inputDeviceName == outputDeviceName || outputDeviceName.isEmpty() || inputDeviceName.isEmpty());
  209327. (void) inputDeviceName;
  209328. jassert (hasScanned); // need to call scanForDevices() before doing this
  209329. const int index = deviceNames.indexOf (outputDeviceName);
  209330. if (index >= 0)
  209331. {
  209332. const int freeSlot = findFreeSlot();
  209333. if (freeSlot >= 0)
  209334. return new ASIOAudioIODevice (outputDeviceName, *(classIds [index]), freeSlot, String::empty);
  209335. }
  209336. return 0;
  209337. }
  209338. juce_UseDebuggingNewOperator
  209339. private:
  209340. StringArray deviceNames;
  209341. OwnedArray <CLSID> classIds;
  209342. bool hasScanned;
  209343. static bool checkClassIsOk (const String& classId)
  209344. {
  209345. HKEY hk = 0;
  209346. bool ok = false;
  209347. if (RegOpenKeyA (HKEY_CLASSES_ROOT, "clsid", &hk) == ERROR_SUCCESS)
  209348. {
  209349. int index = 0;
  209350. for (;;)
  209351. {
  209352. char buf [512];
  209353. if (RegEnumKeyA (hk, index++, buf, 512) == ERROR_SUCCESS)
  209354. {
  209355. if (classId.equalsIgnoreCase (buf))
  209356. {
  209357. HKEY subKey, pathKey;
  209358. if (RegOpenKeyExA (hk, buf, 0, KEY_READ, &subKey) == ERROR_SUCCESS)
  209359. {
  209360. if (RegOpenKeyExA (subKey, "InprocServer32", 0, KEY_READ, &pathKey) == ERROR_SUCCESS)
  209361. {
  209362. char pathName [600];
  209363. DWORD dtype = REG_SZ;
  209364. DWORD dsize = sizeof (pathName);
  209365. if (RegQueryValueExA (pathKey, 0, 0, &dtype,
  209366. (LPBYTE) pathName, &dsize) == ERROR_SUCCESS)
  209367. {
  209368. OFSTRUCT of;
  209369. zerostruct (of);
  209370. of.cBytes = sizeof (of);
  209371. ok = (OpenFile (String (pathName), &of, OF_EXIST) != 0);
  209372. }
  209373. RegCloseKey (pathKey);
  209374. }
  209375. RegCloseKey (subKey);
  209376. }
  209377. break;
  209378. }
  209379. }
  209380. else
  209381. {
  209382. break;
  209383. }
  209384. }
  209385. RegCloseKey (hk);
  209386. }
  209387. return ok;
  209388. }
  209389. void addDriverInfo (const String& keyName, HKEY hk)
  209390. {
  209391. HKEY subKey;
  209392. if (RegOpenKeyExA (hk, keyName, 0, KEY_READ, &subKey) == ERROR_SUCCESS)
  209393. {
  209394. char buf [256];
  209395. DWORD dtype = REG_SZ;
  209396. DWORD dsize = sizeof (buf);
  209397. zeromem (buf, dsize);
  209398. if (RegQueryValueExA (subKey, "clsid", 0, &dtype, (LPBYTE) buf, &dsize) == ERROR_SUCCESS)
  209399. {
  209400. if (dsize > 0 && checkClassIsOk (buf))
  209401. {
  209402. wchar_t classIdStr [130];
  209403. MultiByteToWideChar (CP_ACP, 0, buf, -1, classIdStr, 128);
  209404. String deviceName;
  209405. CLSID classId;
  209406. if (CLSIDFromString ((LPOLESTR) classIdStr, &classId) == S_OK)
  209407. {
  209408. dtype = REG_SZ;
  209409. dsize = sizeof (buf);
  209410. if (RegQueryValueExA (subKey, "description", 0, &dtype, (LPBYTE) buf, &dsize) == ERROR_SUCCESS)
  209411. deviceName = buf;
  209412. else
  209413. deviceName = keyName;
  209414. log (T("found ") + deviceName);
  209415. deviceNames.add (deviceName);
  209416. classIds.add (new CLSID (classId));
  209417. }
  209418. }
  209419. RegCloseKey (subKey);
  209420. }
  209421. }
  209422. }
  209423. ASIOAudioIODeviceType (const ASIOAudioIODeviceType&);
  209424. const ASIOAudioIODeviceType& operator= (const ASIOAudioIODeviceType&);
  209425. };
  209426. AudioIODeviceType* juce_createAudioIODeviceType_ASIO()
  209427. {
  209428. return new ASIOAudioIODeviceType();
  209429. }
  209430. AudioIODevice* juce_createASIOAudioIODeviceForGUID (const String& name,
  209431. void* guid,
  209432. const String& optionalDllForDirectLoading)
  209433. {
  209434. const int freeSlot = ASIOAudioIODeviceType::findFreeSlot();
  209435. if (freeSlot < 0)
  209436. return 0;
  209437. return new ASIOAudioIODevice (name, *(CLSID*) guid, freeSlot, optionalDllForDirectLoading);
  209438. }
  209439. #undef log
  209440. #endif
  209441. /********* End of inlined file: juce_win32_ASIO.cpp *********/
  209442. /********* Start of inlined file: juce_win32_DirectSound.cpp *********/
  209443. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  209444. // compiled on its own).
  209445. #if JUCE_INCLUDED_FILE && JUCE_DIRECTSOUND
  209446. END_JUCE_NAMESPACE
  209447. extern "C"
  209448. {
  209449. // Declare just the minimum number of interfaces for the DSound objects that we need..
  209450. typedef struct typeDSBUFFERDESC
  209451. {
  209452. DWORD dwSize;
  209453. DWORD dwFlags;
  209454. DWORD dwBufferBytes;
  209455. DWORD dwReserved;
  209456. LPWAVEFORMATEX lpwfxFormat;
  209457. GUID guid3DAlgorithm;
  209458. } DSBUFFERDESC;
  209459. struct IDirectSoundBuffer;
  209460. #undef INTERFACE
  209461. #define INTERFACE IDirectSound
  209462. DECLARE_INTERFACE_(IDirectSound, IUnknown)
  209463. {
  209464. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  209465. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  209466. STDMETHOD_(ULONG,Release) (THIS) PURE;
  209467. STDMETHOD(CreateSoundBuffer) (THIS_ DSBUFFERDESC*, IDirectSoundBuffer**, LPUNKNOWN) PURE;
  209468. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  209469. STDMETHOD(DuplicateSoundBuffer) (THIS_ IDirectSoundBuffer*, IDirectSoundBuffer**) PURE;
  209470. STDMETHOD(SetCooperativeLevel) (THIS_ HWND, DWORD) PURE;
  209471. STDMETHOD(Compact) (THIS) PURE;
  209472. STDMETHOD(GetSpeakerConfig) (THIS_ LPDWORD) PURE;
  209473. STDMETHOD(SetSpeakerConfig) (THIS_ DWORD) PURE;
  209474. STDMETHOD(Initialize) (THIS_ const GUID*) PURE;
  209475. };
  209476. #undef INTERFACE
  209477. #define INTERFACE IDirectSoundBuffer
  209478. DECLARE_INTERFACE_(IDirectSoundBuffer, IUnknown)
  209479. {
  209480. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  209481. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  209482. STDMETHOD_(ULONG,Release) (THIS) PURE;
  209483. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  209484. STDMETHOD(GetCurrentPosition) (THIS_ LPDWORD, LPDWORD) PURE;
  209485. STDMETHOD(GetFormat) (THIS_ LPWAVEFORMATEX, DWORD, LPDWORD) PURE;
  209486. STDMETHOD(GetVolume) (THIS_ LPLONG) PURE;
  209487. STDMETHOD(GetPan) (THIS_ LPLONG) PURE;
  209488. STDMETHOD(GetFrequency) (THIS_ LPDWORD) PURE;
  209489. STDMETHOD(GetStatus) (THIS_ LPDWORD) PURE;
  209490. STDMETHOD(Initialize) (THIS_ IDirectSound*, DSBUFFERDESC*) PURE;
  209491. STDMETHOD(Lock) (THIS_ DWORD, DWORD, LPVOID*, LPDWORD, LPVOID*, LPDWORD, DWORD) PURE;
  209492. STDMETHOD(Play) (THIS_ DWORD, DWORD, DWORD) PURE;
  209493. STDMETHOD(SetCurrentPosition) (THIS_ DWORD) PURE;
  209494. STDMETHOD(SetFormat) (THIS_ const WAVEFORMATEX*) PURE;
  209495. STDMETHOD(SetVolume) (THIS_ LONG) PURE;
  209496. STDMETHOD(SetPan) (THIS_ LONG) PURE;
  209497. STDMETHOD(SetFrequency) (THIS_ DWORD) PURE;
  209498. STDMETHOD(Stop) (THIS) PURE;
  209499. STDMETHOD(Unlock) (THIS_ LPVOID, DWORD, LPVOID, DWORD) PURE;
  209500. STDMETHOD(Restore) (THIS) PURE;
  209501. };
  209502. typedef struct typeDSCBUFFERDESC
  209503. {
  209504. DWORD dwSize;
  209505. DWORD dwFlags;
  209506. DWORD dwBufferBytes;
  209507. DWORD dwReserved;
  209508. LPWAVEFORMATEX lpwfxFormat;
  209509. } DSCBUFFERDESC;
  209510. struct IDirectSoundCaptureBuffer;
  209511. #undef INTERFACE
  209512. #define INTERFACE IDirectSoundCapture
  209513. DECLARE_INTERFACE_(IDirectSoundCapture, IUnknown)
  209514. {
  209515. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  209516. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  209517. STDMETHOD_(ULONG,Release) (THIS) PURE;
  209518. STDMETHOD(CreateCaptureBuffer) (THIS_ DSCBUFFERDESC*, IDirectSoundCaptureBuffer**, LPUNKNOWN) PURE;
  209519. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  209520. STDMETHOD(Initialize) (THIS_ const GUID*) PURE;
  209521. };
  209522. #undef INTERFACE
  209523. #define INTERFACE IDirectSoundCaptureBuffer
  209524. DECLARE_INTERFACE_(IDirectSoundCaptureBuffer, IUnknown)
  209525. {
  209526. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  209527. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  209528. STDMETHOD_(ULONG,Release) (THIS) PURE;
  209529. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  209530. STDMETHOD(GetCurrentPosition) (THIS_ LPDWORD, LPDWORD) PURE;
  209531. STDMETHOD(GetFormat) (THIS_ LPWAVEFORMATEX, DWORD, LPDWORD) PURE;
  209532. STDMETHOD(GetStatus) (THIS_ LPDWORD) PURE;
  209533. STDMETHOD(Initialize) (THIS_ IDirectSoundCapture*, DSCBUFFERDESC*) PURE;
  209534. STDMETHOD(Lock) (THIS_ DWORD, DWORD, LPVOID*, LPDWORD, LPVOID*, LPDWORD, DWORD) PURE;
  209535. STDMETHOD(Start) (THIS_ DWORD) PURE;
  209536. STDMETHOD(Stop) (THIS) PURE;
  209537. STDMETHOD(Unlock) (THIS_ LPVOID, DWORD, LPVOID, DWORD) PURE;
  209538. };
  209539. };
  209540. BEGIN_JUCE_NAMESPACE
  209541. static const String getDSErrorMessage (HRESULT hr)
  209542. {
  209543. const char* result = 0;
  209544. switch (hr)
  209545. {
  209546. case MAKE_HRESULT(1, 0x878, 10):
  209547. result = "Device already allocated";
  209548. break;
  209549. case MAKE_HRESULT(1, 0x878, 30):
  209550. result = "Control unavailable";
  209551. break;
  209552. case E_INVALIDARG:
  209553. result = "Invalid parameter";
  209554. break;
  209555. case MAKE_HRESULT(1, 0x878, 50):
  209556. result = "Invalid call";
  209557. break;
  209558. case E_FAIL:
  209559. result = "Generic error";
  209560. break;
  209561. case MAKE_HRESULT(1, 0x878, 70):
  209562. result = "Priority level error";
  209563. break;
  209564. case E_OUTOFMEMORY:
  209565. result = "Out of memory";
  209566. break;
  209567. case MAKE_HRESULT(1, 0x878, 100):
  209568. result = "Bad format";
  209569. break;
  209570. case E_NOTIMPL:
  209571. result = "Unsupported function";
  209572. break;
  209573. case MAKE_HRESULT(1, 0x878, 120):
  209574. result = "No driver";
  209575. break;
  209576. case MAKE_HRESULT(1, 0x878, 130):
  209577. result = "Already initialised";
  209578. break;
  209579. case CLASS_E_NOAGGREGATION:
  209580. result = "No aggregation";
  209581. break;
  209582. case MAKE_HRESULT(1, 0x878, 150):
  209583. result = "Buffer lost";
  209584. break;
  209585. case MAKE_HRESULT(1, 0x878, 160):
  209586. result = "Another app has priority";
  209587. break;
  209588. case MAKE_HRESULT(1, 0x878, 170):
  209589. result = "Uninitialised";
  209590. break;
  209591. case E_NOINTERFACE:
  209592. result = "No interface";
  209593. break;
  209594. case S_OK:
  209595. result = "No error";
  209596. break;
  209597. default:
  209598. return "Unknown error: " + String ((int) hr);
  209599. }
  209600. return result;
  209601. }
  209602. #define DS_DEBUGGING 1
  209603. #ifdef DS_DEBUGGING
  209604. #define CATCH JUCE_CATCH_EXCEPTION
  209605. #undef log
  209606. #define log(a) Logger::writeToLog(a);
  209607. #undef logError
  209608. #define logError(a) logDSError(a, __LINE__);
  209609. static void logDSError (HRESULT hr, int lineNum)
  209610. {
  209611. if (hr != S_OK)
  209612. {
  209613. String error ("DS error at line ");
  209614. error << lineNum << T(" - ") << getDSErrorMessage (hr);
  209615. log (error);
  209616. }
  209617. }
  209618. #else
  209619. #define CATCH JUCE_CATCH_ALL
  209620. #define log(a)
  209621. #define logError(a)
  209622. #endif
  209623. #define DSOUND_FUNCTION(functionName, params) \
  209624. typedef HRESULT (WINAPI *type##functionName) params; \
  209625. static type##functionName ds##functionName = 0;
  209626. #define DSOUND_FUNCTION_LOAD(functionName) \
  209627. ds##functionName = (type##functionName) GetProcAddress (h, #functionName); \
  209628. jassert (ds##functionName != 0);
  209629. typedef BOOL (CALLBACK *LPDSENUMCALLBACKW) (LPGUID, LPCWSTR, LPCWSTR, LPVOID);
  209630. typedef BOOL (CALLBACK *LPDSENUMCALLBACKA) (LPGUID, LPCSTR, LPCSTR, LPVOID);
  209631. DSOUND_FUNCTION (DirectSoundCreate, (const GUID*, IDirectSound**, LPUNKNOWN))
  209632. DSOUND_FUNCTION (DirectSoundCaptureCreate, (const GUID*, IDirectSoundCapture**, LPUNKNOWN))
  209633. DSOUND_FUNCTION (DirectSoundEnumerateW, (LPDSENUMCALLBACKW, LPVOID))
  209634. DSOUND_FUNCTION (DirectSoundCaptureEnumerateW, (LPDSENUMCALLBACKW, LPVOID))
  209635. static void initialiseDSoundFunctions()
  209636. {
  209637. if (dsDirectSoundCreate == 0)
  209638. {
  209639. HMODULE h = LoadLibraryA ("dsound.dll");
  209640. DSOUND_FUNCTION_LOAD (DirectSoundCreate)
  209641. DSOUND_FUNCTION_LOAD (DirectSoundCaptureCreate)
  209642. DSOUND_FUNCTION_LOAD (DirectSoundEnumerateW)
  209643. DSOUND_FUNCTION_LOAD (DirectSoundCaptureEnumerateW)
  209644. }
  209645. }
  209646. class DSoundInternalOutChannel
  209647. {
  209648. String name;
  209649. LPGUID guid;
  209650. int sampleRate, bufferSizeSamples;
  209651. float* leftBuffer;
  209652. float* rightBuffer;
  209653. IDirectSound* pDirectSound;
  209654. IDirectSoundBuffer* pOutputBuffer;
  209655. DWORD writeOffset;
  209656. int totalBytesPerBuffer;
  209657. int bytesPerBuffer;
  209658. unsigned int lastPlayCursor;
  209659. public:
  209660. int bitDepth;
  209661. bool doneFlag;
  209662. DSoundInternalOutChannel (const String& name_,
  209663. LPGUID guid_,
  209664. int rate,
  209665. int bufferSize,
  209666. float* left,
  209667. float* right)
  209668. : name (name_),
  209669. guid (guid_),
  209670. sampleRate (rate),
  209671. bufferSizeSamples (bufferSize),
  209672. leftBuffer (left),
  209673. rightBuffer (right),
  209674. pDirectSound (0),
  209675. pOutputBuffer (0),
  209676. bitDepth (16)
  209677. {
  209678. }
  209679. ~DSoundInternalOutChannel()
  209680. {
  209681. close();
  209682. }
  209683. void close()
  209684. {
  209685. HRESULT hr;
  209686. if (pOutputBuffer != 0)
  209687. {
  209688. JUCE_TRY
  209689. {
  209690. log (T("closing dsound out: ") + name);
  209691. hr = pOutputBuffer->Stop();
  209692. logError (hr);
  209693. }
  209694. CATCH
  209695. JUCE_TRY
  209696. {
  209697. hr = pOutputBuffer->Release();
  209698. logError (hr);
  209699. }
  209700. CATCH
  209701. pOutputBuffer = 0;
  209702. }
  209703. if (pDirectSound != 0)
  209704. {
  209705. JUCE_TRY
  209706. {
  209707. hr = pDirectSound->Release();
  209708. logError (hr);
  209709. }
  209710. CATCH
  209711. pDirectSound = 0;
  209712. }
  209713. }
  209714. const String open()
  209715. {
  209716. log (T("opening dsound out device: ") + name
  209717. + T(" rate=") + String (sampleRate)
  209718. + T(" bits=") + String (bitDepth)
  209719. + T(" buf=") + String (bufferSizeSamples));
  209720. pDirectSound = 0;
  209721. pOutputBuffer = 0;
  209722. writeOffset = 0;
  209723. String error;
  209724. HRESULT hr = E_NOINTERFACE;
  209725. if (dsDirectSoundCreate != 0)
  209726. hr = dsDirectSoundCreate (guid, &pDirectSound, 0);
  209727. if (hr == S_OK)
  209728. {
  209729. bytesPerBuffer = (bufferSizeSamples * (bitDepth >> 2)) & ~15;
  209730. totalBytesPerBuffer = (3 * bytesPerBuffer) & ~15;
  209731. const int numChannels = 2;
  209732. hr = pDirectSound->SetCooperativeLevel (GetDesktopWindow(), 2 /* DSSCL_PRIORITY */);
  209733. logError (hr);
  209734. if (hr == S_OK)
  209735. {
  209736. IDirectSoundBuffer* pPrimaryBuffer;
  209737. DSBUFFERDESC primaryDesc;
  209738. zerostruct (primaryDesc);
  209739. primaryDesc.dwSize = sizeof (DSBUFFERDESC);
  209740. primaryDesc.dwFlags = 1 /* DSBCAPS_PRIMARYBUFFER */;
  209741. primaryDesc.dwBufferBytes = 0;
  209742. primaryDesc.lpwfxFormat = 0;
  209743. log ("opening dsound out step 2");
  209744. hr = pDirectSound->CreateSoundBuffer (&primaryDesc, &pPrimaryBuffer, 0);
  209745. logError (hr);
  209746. if (hr == S_OK)
  209747. {
  209748. WAVEFORMATEX wfFormat;
  209749. wfFormat.wFormatTag = WAVE_FORMAT_PCM;
  209750. wfFormat.nChannels = (unsigned short) numChannels;
  209751. wfFormat.nSamplesPerSec = sampleRate;
  209752. wfFormat.wBitsPerSample = (unsigned short) bitDepth;
  209753. wfFormat.nBlockAlign = (unsigned short) (wfFormat.nChannels * wfFormat.wBitsPerSample / 8);
  209754. wfFormat.nAvgBytesPerSec = wfFormat.nSamplesPerSec * wfFormat.nBlockAlign;
  209755. wfFormat.cbSize = 0;
  209756. hr = pPrimaryBuffer->SetFormat (&wfFormat);
  209757. logError (hr);
  209758. if (hr == S_OK)
  209759. {
  209760. DSBUFFERDESC secondaryDesc;
  209761. zerostruct (secondaryDesc);
  209762. secondaryDesc.dwSize = sizeof (DSBUFFERDESC);
  209763. secondaryDesc.dwFlags = 0x8000 /* DSBCAPS_GLOBALFOCUS */
  209764. | 0x10000 /* DSBCAPS_GETCURRENTPOSITION2 */;
  209765. secondaryDesc.dwBufferBytes = totalBytesPerBuffer;
  209766. secondaryDesc.lpwfxFormat = &wfFormat;
  209767. hr = pDirectSound->CreateSoundBuffer (&secondaryDesc, &pOutputBuffer, 0);
  209768. logError (hr);
  209769. if (hr == S_OK)
  209770. {
  209771. log ("opening dsound out step 3");
  209772. DWORD dwDataLen;
  209773. unsigned char* pDSBuffData;
  209774. hr = pOutputBuffer->Lock (0, totalBytesPerBuffer,
  209775. (LPVOID*) &pDSBuffData, &dwDataLen, 0, 0, 0);
  209776. logError (hr);
  209777. if (hr == S_OK)
  209778. {
  209779. zeromem (pDSBuffData, dwDataLen);
  209780. hr = pOutputBuffer->Unlock (pDSBuffData, dwDataLen, 0, 0);
  209781. if (hr == S_OK)
  209782. {
  209783. hr = pOutputBuffer->SetCurrentPosition (0);
  209784. if (hr == S_OK)
  209785. {
  209786. hr = pOutputBuffer->Play (0, 0, 1 /* DSBPLAY_LOOPING */);
  209787. if (hr == S_OK)
  209788. return String::empty;
  209789. }
  209790. }
  209791. }
  209792. }
  209793. }
  209794. }
  209795. }
  209796. }
  209797. error = getDSErrorMessage (hr);
  209798. close();
  209799. return error;
  209800. }
  209801. void synchronisePosition()
  209802. {
  209803. if (pOutputBuffer != 0)
  209804. {
  209805. DWORD playCursor;
  209806. pOutputBuffer->GetCurrentPosition (&playCursor, &writeOffset);
  209807. }
  209808. }
  209809. bool service()
  209810. {
  209811. if (pOutputBuffer == 0)
  209812. return true;
  209813. DWORD playCursor, writeCursor;
  209814. HRESULT hr = pOutputBuffer->GetCurrentPosition (&playCursor, &writeCursor);
  209815. if (hr != S_OK)
  209816. {
  209817. logError (hr);
  209818. jassertfalse
  209819. return true;
  209820. }
  209821. int playWriteGap = writeCursor - playCursor;
  209822. if (playWriteGap < 0)
  209823. playWriteGap += totalBytesPerBuffer;
  209824. int bytesEmpty = playCursor - writeOffset;
  209825. if (bytesEmpty < 0)
  209826. bytesEmpty += totalBytesPerBuffer;
  209827. if (bytesEmpty > (totalBytesPerBuffer - playWriteGap))
  209828. {
  209829. writeOffset = writeCursor;
  209830. bytesEmpty = totalBytesPerBuffer - playWriteGap;
  209831. }
  209832. if (bytesEmpty >= bytesPerBuffer)
  209833. {
  209834. LPBYTE lpbuf1 = 0;
  209835. LPBYTE lpbuf2 = 0;
  209836. DWORD dwSize1 = 0;
  209837. DWORD dwSize2 = 0;
  209838. HRESULT hr = pOutputBuffer->Lock (writeOffset,
  209839. bytesPerBuffer,
  209840. (void**) &lpbuf1, &dwSize1,
  209841. (void**) &lpbuf2, &dwSize2, 0);
  209842. if (hr == MAKE_HRESULT (1, 0x878, 150)) // DSERR_BUFFERLOST
  209843. {
  209844. pOutputBuffer->Restore();
  209845. hr = pOutputBuffer->Lock (writeOffset,
  209846. bytesPerBuffer,
  209847. (void**) &lpbuf1, &dwSize1,
  209848. (void**) &lpbuf2, &dwSize2, 0);
  209849. }
  209850. if (hr == S_OK)
  209851. {
  209852. if (bitDepth == 16)
  209853. {
  209854. const float gainL = 32767.0f;
  209855. const float gainR = 32767.0f;
  209856. int* dest = (int*)lpbuf1;
  209857. const float* left = leftBuffer;
  209858. const float* right = rightBuffer;
  209859. int samples1 = dwSize1 >> 2;
  209860. int samples2 = dwSize2 >> 2;
  209861. if (left == 0)
  209862. {
  209863. while (--samples1 >= 0)
  209864. {
  209865. int r = roundFloatToInt (gainR * *right++);
  209866. if (r < -32768)
  209867. r = -32768;
  209868. else if (r > 32767)
  209869. r = 32767;
  209870. *dest++ = (r << 16);
  209871. }
  209872. dest = (int*)lpbuf2;
  209873. while (--samples2 >= 0)
  209874. {
  209875. int r = roundFloatToInt (gainR * *right++);
  209876. if (r < -32768)
  209877. r = -32768;
  209878. else if (r > 32767)
  209879. r = 32767;
  209880. *dest++ = (r << 16);
  209881. }
  209882. }
  209883. else if (right == 0)
  209884. {
  209885. while (--samples1 >= 0)
  209886. {
  209887. int l = roundFloatToInt (gainL * *left++);
  209888. if (l < -32768)
  209889. l = -32768;
  209890. else if (l > 32767)
  209891. l = 32767;
  209892. l &= 0xffff;
  209893. *dest++ = l;
  209894. }
  209895. dest = (int*)lpbuf2;
  209896. while (--samples2 >= 0)
  209897. {
  209898. int l = roundFloatToInt (gainL * *left++);
  209899. if (l < -32768)
  209900. l = -32768;
  209901. else if (l > 32767)
  209902. l = 32767;
  209903. l &= 0xffff;
  209904. *dest++ = l;
  209905. }
  209906. }
  209907. else
  209908. {
  209909. while (--samples1 >= 0)
  209910. {
  209911. int l = roundFloatToInt (gainL * *left++);
  209912. if (l < -32768)
  209913. l = -32768;
  209914. else if (l > 32767)
  209915. l = 32767;
  209916. l &= 0xffff;
  209917. int r = roundFloatToInt (gainR * *right++);
  209918. if (r < -32768)
  209919. r = -32768;
  209920. else if (r > 32767)
  209921. r = 32767;
  209922. *dest++ = (r << 16) | l;
  209923. }
  209924. dest = (int*)lpbuf2;
  209925. while (--samples2 >= 0)
  209926. {
  209927. int l = roundFloatToInt (gainL * *left++);
  209928. if (l < -32768)
  209929. l = -32768;
  209930. else if (l > 32767)
  209931. l = 32767;
  209932. l &= 0xffff;
  209933. int r = roundFloatToInt (gainR * *right++);
  209934. if (r < -32768)
  209935. r = -32768;
  209936. else if (r > 32767)
  209937. r = 32767;
  209938. *dest++ = (r << 16) | l;
  209939. }
  209940. }
  209941. }
  209942. else
  209943. {
  209944. jassertfalse
  209945. }
  209946. writeOffset = (writeOffset + dwSize1 + dwSize2) % totalBytesPerBuffer;
  209947. pOutputBuffer->Unlock (lpbuf1, dwSize1, lpbuf2, dwSize2);
  209948. }
  209949. else
  209950. {
  209951. jassertfalse
  209952. logError (hr);
  209953. }
  209954. bytesEmpty -= bytesPerBuffer;
  209955. return true;
  209956. }
  209957. else
  209958. {
  209959. return false;
  209960. }
  209961. }
  209962. };
  209963. struct DSoundInternalInChannel
  209964. {
  209965. String name;
  209966. LPGUID guid;
  209967. int sampleRate, bufferSizeSamples;
  209968. float* leftBuffer;
  209969. float* rightBuffer;
  209970. IDirectSound* pDirectSound;
  209971. IDirectSoundCapture* pDirectSoundCapture;
  209972. IDirectSoundCaptureBuffer* pInputBuffer;
  209973. public:
  209974. unsigned int readOffset;
  209975. int bytesPerBuffer, totalBytesPerBuffer;
  209976. int bitDepth;
  209977. bool doneFlag;
  209978. DSoundInternalInChannel (const String& name_,
  209979. LPGUID guid_,
  209980. int rate,
  209981. int bufferSize,
  209982. float* left,
  209983. float* right)
  209984. : name (name_),
  209985. guid (guid_),
  209986. sampleRate (rate),
  209987. bufferSizeSamples (bufferSize),
  209988. leftBuffer (left),
  209989. rightBuffer (right),
  209990. pDirectSound (0),
  209991. pDirectSoundCapture (0),
  209992. pInputBuffer (0),
  209993. bitDepth (16)
  209994. {
  209995. }
  209996. ~DSoundInternalInChannel()
  209997. {
  209998. close();
  209999. }
  210000. void close()
  210001. {
  210002. HRESULT hr;
  210003. if (pInputBuffer != 0)
  210004. {
  210005. JUCE_TRY
  210006. {
  210007. log (T("closing dsound in: ") + name);
  210008. hr = pInputBuffer->Stop();
  210009. logError (hr);
  210010. }
  210011. CATCH
  210012. JUCE_TRY
  210013. {
  210014. hr = pInputBuffer->Release();
  210015. logError (hr);
  210016. }
  210017. CATCH
  210018. pInputBuffer = 0;
  210019. }
  210020. if (pDirectSoundCapture != 0)
  210021. {
  210022. JUCE_TRY
  210023. {
  210024. hr = pDirectSoundCapture->Release();
  210025. logError (hr);
  210026. }
  210027. CATCH
  210028. pDirectSoundCapture = 0;
  210029. }
  210030. if (pDirectSound != 0)
  210031. {
  210032. JUCE_TRY
  210033. {
  210034. hr = pDirectSound->Release();
  210035. logError (hr);
  210036. }
  210037. CATCH
  210038. pDirectSound = 0;
  210039. }
  210040. }
  210041. const String open()
  210042. {
  210043. log (T("opening dsound in device: ") + name
  210044. + T(" rate=") + String (sampleRate) + T(" bits=") + String (bitDepth) + T(" buf=") + String (bufferSizeSamples));
  210045. pDirectSound = 0;
  210046. pDirectSoundCapture = 0;
  210047. pInputBuffer = 0;
  210048. readOffset = 0;
  210049. totalBytesPerBuffer = 0;
  210050. String error;
  210051. HRESULT hr = E_NOINTERFACE;
  210052. if (dsDirectSoundCaptureCreate != 0)
  210053. hr = dsDirectSoundCaptureCreate (guid, &pDirectSoundCapture, 0);
  210054. logError (hr);
  210055. if (hr == S_OK)
  210056. {
  210057. const int numChannels = 2;
  210058. bytesPerBuffer = (bufferSizeSamples * (bitDepth >> 2)) & ~15;
  210059. totalBytesPerBuffer = (3 * bytesPerBuffer) & ~15;
  210060. WAVEFORMATEX wfFormat;
  210061. wfFormat.wFormatTag = WAVE_FORMAT_PCM;
  210062. wfFormat.nChannels = (unsigned short)numChannels;
  210063. wfFormat.nSamplesPerSec = sampleRate;
  210064. wfFormat.wBitsPerSample = (unsigned short)bitDepth;
  210065. wfFormat.nBlockAlign = (unsigned short)(wfFormat.nChannels * (wfFormat.wBitsPerSample / 8));
  210066. wfFormat.nAvgBytesPerSec = wfFormat.nSamplesPerSec * wfFormat.nBlockAlign;
  210067. wfFormat.cbSize = 0;
  210068. DSCBUFFERDESC captureDesc;
  210069. zerostruct (captureDesc);
  210070. captureDesc.dwSize = sizeof (DSCBUFFERDESC);
  210071. captureDesc.dwFlags = 0;
  210072. captureDesc.dwBufferBytes = totalBytesPerBuffer;
  210073. captureDesc.lpwfxFormat = &wfFormat;
  210074. log (T("opening dsound in step 2"));
  210075. hr = pDirectSoundCapture->CreateCaptureBuffer (&captureDesc, &pInputBuffer, 0);
  210076. logError (hr);
  210077. if (hr == S_OK)
  210078. {
  210079. hr = pInputBuffer->Start (1 /* DSCBSTART_LOOPING */);
  210080. logError (hr);
  210081. if (hr == S_OK)
  210082. return String::empty;
  210083. }
  210084. }
  210085. error = getDSErrorMessage (hr);
  210086. close();
  210087. return error;
  210088. }
  210089. void synchronisePosition()
  210090. {
  210091. if (pInputBuffer != 0)
  210092. {
  210093. DWORD capturePos;
  210094. pInputBuffer->GetCurrentPosition (&capturePos, (DWORD*)&readOffset);
  210095. }
  210096. }
  210097. bool service()
  210098. {
  210099. if (pInputBuffer == 0)
  210100. return true;
  210101. DWORD capturePos, readPos;
  210102. HRESULT hr = pInputBuffer->GetCurrentPosition (&capturePos, &readPos);
  210103. logError (hr);
  210104. if (hr != S_OK)
  210105. return true;
  210106. int bytesFilled = readPos - readOffset;
  210107. if (bytesFilled < 0)
  210108. bytesFilled += totalBytesPerBuffer;
  210109. if (bytesFilled >= bytesPerBuffer)
  210110. {
  210111. LPBYTE lpbuf1 = 0;
  210112. LPBYTE lpbuf2 = 0;
  210113. DWORD dwsize1 = 0;
  210114. DWORD dwsize2 = 0;
  210115. HRESULT hr = pInputBuffer->Lock (readOffset,
  210116. bytesPerBuffer,
  210117. (void**) &lpbuf1, &dwsize1,
  210118. (void**) &lpbuf2, &dwsize2, 0);
  210119. if (hr == S_OK)
  210120. {
  210121. if (bitDepth == 16)
  210122. {
  210123. const float g = 1.0f / 32768.0f;
  210124. float* destL = leftBuffer;
  210125. float* destR = rightBuffer;
  210126. int samples1 = dwsize1 >> 2;
  210127. int samples2 = dwsize2 >> 2;
  210128. const short* src = (const short*)lpbuf1;
  210129. if (destL == 0)
  210130. {
  210131. while (--samples1 >= 0)
  210132. {
  210133. ++src;
  210134. *destR++ = *src++ * g;
  210135. }
  210136. src = (const short*)lpbuf2;
  210137. while (--samples2 >= 0)
  210138. {
  210139. ++src;
  210140. *destR++ = *src++ * g;
  210141. }
  210142. }
  210143. else if (destR == 0)
  210144. {
  210145. while (--samples1 >= 0)
  210146. {
  210147. *destL++ = *src++ * g;
  210148. ++src;
  210149. }
  210150. src = (const short*)lpbuf2;
  210151. while (--samples2 >= 0)
  210152. {
  210153. *destL++ = *src++ * g;
  210154. ++src;
  210155. }
  210156. }
  210157. else
  210158. {
  210159. while (--samples1 >= 0)
  210160. {
  210161. *destL++ = *src++ * g;
  210162. *destR++ = *src++ * g;
  210163. }
  210164. src = (const short*)lpbuf2;
  210165. while (--samples2 >= 0)
  210166. {
  210167. *destL++ = *src++ * g;
  210168. *destR++ = *src++ * g;
  210169. }
  210170. }
  210171. }
  210172. else
  210173. {
  210174. jassertfalse
  210175. }
  210176. readOffset = (readOffset + dwsize1 + dwsize2) % totalBytesPerBuffer;
  210177. pInputBuffer->Unlock (lpbuf1, dwsize1, lpbuf2, dwsize2);
  210178. }
  210179. else
  210180. {
  210181. logError (hr);
  210182. jassertfalse
  210183. }
  210184. bytesFilled -= bytesPerBuffer;
  210185. return true;
  210186. }
  210187. else
  210188. {
  210189. return false;
  210190. }
  210191. }
  210192. };
  210193. class DSoundAudioIODevice : public AudioIODevice,
  210194. public Thread
  210195. {
  210196. public:
  210197. DSoundAudioIODevice (const String& deviceName,
  210198. const int outputDeviceIndex_,
  210199. const int inputDeviceIndex_)
  210200. : AudioIODevice (deviceName, "DirectSound"),
  210201. Thread ("Juce DSound"),
  210202. isOpen_ (false),
  210203. isStarted (false),
  210204. outputDeviceIndex (outputDeviceIndex_),
  210205. inputDeviceIndex (inputDeviceIndex_),
  210206. inChans (4),
  210207. outChans (4),
  210208. numInputBuffers (0),
  210209. numOutputBuffers (0),
  210210. totalSamplesOut (0),
  210211. sampleRate (0.0),
  210212. inputBuffers (0),
  210213. outputBuffers (0),
  210214. callback (0),
  210215. bufferSizeSamples (0)
  210216. {
  210217. if (outputDeviceIndex_ >= 0)
  210218. {
  210219. outChannels.add (TRANS("Left"));
  210220. outChannels.add (TRANS("Right"));
  210221. }
  210222. if (inputDeviceIndex_ >= 0)
  210223. {
  210224. inChannels.add (TRANS("Left"));
  210225. inChannels.add (TRANS("Right"));
  210226. }
  210227. }
  210228. ~DSoundAudioIODevice()
  210229. {
  210230. close();
  210231. }
  210232. const StringArray getOutputChannelNames()
  210233. {
  210234. return outChannels;
  210235. }
  210236. const StringArray getInputChannelNames()
  210237. {
  210238. return inChannels;
  210239. }
  210240. int getNumSampleRates()
  210241. {
  210242. return 4;
  210243. }
  210244. double getSampleRate (int index)
  210245. {
  210246. const double samps[] = { 44100.0, 48000.0, 88200.0, 96000.0 };
  210247. return samps [jlimit (0, 3, index)];
  210248. }
  210249. int getNumBufferSizesAvailable()
  210250. {
  210251. return 50;
  210252. }
  210253. int getBufferSizeSamples (int index)
  210254. {
  210255. int n = 64;
  210256. for (int i = 0; i < index; ++i)
  210257. n += (n < 512) ? 32
  210258. : ((n < 1024) ? 64
  210259. : ((n < 2048) ? 128 : 256));
  210260. return n;
  210261. }
  210262. int getDefaultBufferSize()
  210263. {
  210264. return 2560;
  210265. }
  210266. const String open (const BitArray& inputChannels,
  210267. const BitArray& outputChannels,
  210268. double sampleRate,
  210269. int bufferSizeSamples)
  210270. {
  210271. lastError = openDevice (inputChannels, outputChannels, sampleRate, bufferSizeSamples);
  210272. isOpen_ = lastError.isEmpty();
  210273. return lastError;
  210274. }
  210275. void close()
  210276. {
  210277. stop();
  210278. if (isOpen_)
  210279. {
  210280. closeDevice();
  210281. isOpen_ = false;
  210282. }
  210283. }
  210284. bool isOpen()
  210285. {
  210286. return isOpen_ && isThreadRunning();
  210287. }
  210288. int getCurrentBufferSizeSamples()
  210289. {
  210290. return bufferSizeSamples;
  210291. }
  210292. double getCurrentSampleRate()
  210293. {
  210294. return sampleRate;
  210295. }
  210296. int getCurrentBitDepth()
  210297. {
  210298. int i, bits = 256;
  210299. for (i = inChans.size(); --i >= 0;)
  210300. bits = jmin (bits, inChans[i]->bitDepth);
  210301. for (i = outChans.size(); --i >= 0;)
  210302. bits = jmin (bits, outChans[i]->bitDepth);
  210303. if (bits > 32)
  210304. bits = 16;
  210305. return bits;
  210306. }
  210307. const BitArray getActiveOutputChannels() const
  210308. {
  210309. return enabledOutputs;
  210310. }
  210311. const BitArray getActiveInputChannels() const
  210312. {
  210313. return enabledInputs;
  210314. }
  210315. int getOutputLatencyInSamples()
  210316. {
  210317. return (int) (getCurrentBufferSizeSamples() * 1.5);
  210318. }
  210319. int getInputLatencyInSamples()
  210320. {
  210321. return getOutputLatencyInSamples();
  210322. }
  210323. void start (AudioIODeviceCallback* call)
  210324. {
  210325. if (isOpen_ && call != 0 && ! isStarted)
  210326. {
  210327. if (! isThreadRunning())
  210328. {
  210329. // something gone wrong and the thread's stopped..
  210330. isOpen_ = false;
  210331. return;
  210332. }
  210333. call->audioDeviceAboutToStart (this);
  210334. const ScopedLock sl (startStopLock);
  210335. callback = call;
  210336. isStarted = true;
  210337. }
  210338. }
  210339. void stop()
  210340. {
  210341. if (isStarted)
  210342. {
  210343. AudioIODeviceCallback* const callbackLocal = callback;
  210344. {
  210345. const ScopedLock sl (startStopLock);
  210346. isStarted = false;
  210347. }
  210348. if (callbackLocal != 0)
  210349. callbackLocal->audioDeviceStopped();
  210350. }
  210351. }
  210352. bool isPlaying()
  210353. {
  210354. return isStarted && isOpen_ && isThreadRunning();
  210355. }
  210356. const String getLastError()
  210357. {
  210358. return lastError;
  210359. }
  210360. juce_UseDebuggingNewOperator
  210361. StringArray inChannels, outChannels;
  210362. int outputDeviceIndex, inputDeviceIndex;
  210363. private:
  210364. bool isOpen_;
  210365. bool isStarted;
  210366. String lastError;
  210367. OwnedArray <DSoundInternalInChannel> inChans;
  210368. OwnedArray <DSoundInternalOutChannel> outChans;
  210369. WaitableEvent startEvent;
  210370. int numInputBuffers, numOutputBuffers, bufferSizeSamples;
  210371. int volatile totalSamplesOut;
  210372. int64 volatile lastBlockTime;
  210373. double sampleRate;
  210374. BitArray enabledInputs, enabledOutputs;
  210375. float** inputBuffers;
  210376. float** outputBuffers;
  210377. AudioIODeviceCallback* callback;
  210378. CriticalSection startStopLock;
  210379. DSoundAudioIODevice (const DSoundAudioIODevice&);
  210380. const DSoundAudioIODevice& operator= (const DSoundAudioIODevice&);
  210381. const String openDevice (const BitArray& inputChannels,
  210382. const BitArray& outputChannels,
  210383. double sampleRate_,
  210384. int bufferSizeSamples_);
  210385. void closeDevice()
  210386. {
  210387. isStarted = false;
  210388. stopThread (5000);
  210389. inChans.clear();
  210390. outChans.clear();
  210391. int i;
  210392. for (i = 0; i < numInputBuffers; ++i)
  210393. juce_free (inputBuffers[i]);
  210394. delete[] inputBuffers;
  210395. inputBuffers = 0;
  210396. numInputBuffers = 0;
  210397. for (i = 0; i < numOutputBuffers; ++i)
  210398. juce_free (outputBuffers[i]);
  210399. delete[] outputBuffers;
  210400. outputBuffers = 0;
  210401. numOutputBuffers = 0;
  210402. }
  210403. void resync()
  210404. {
  210405. if (! threadShouldExit())
  210406. {
  210407. sleep (5);
  210408. int i;
  210409. for (i = 0; i < outChans.size(); ++i)
  210410. outChans.getUnchecked(i)->synchronisePosition();
  210411. for (i = 0; i < inChans.size(); ++i)
  210412. inChans.getUnchecked(i)->synchronisePosition();
  210413. }
  210414. }
  210415. public:
  210416. void run()
  210417. {
  210418. while (! threadShouldExit())
  210419. {
  210420. if (wait (100))
  210421. break;
  210422. }
  210423. const int latencyMs = (int) (bufferSizeSamples * 1000.0 / sampleRate);
  210424. const int maxTimeMS = jmax (5, 3 * latencyMs);
  210425. while (! threadShouldExit())
  210426. {
  210427. int numToDo = 0;
  210428. uint32 startTime = Time::getMillisecondCounter();
  210429. int i;
  210430. for (i = inChans.size(); --i >= 0;)
  210431. {
  210432. inChans.getUnchecked(i)->doneFlag = false;
  210433. ++numToDo;
  210434. }
  210435. for (i = outChans.size(); --i >= 0;)
  210436. {
  210437. outChans.getUnchecked(i)->doneFlag = false;
  210438. ++numToDo;
  210439. }
  210440. if (numToDo > 0)
  210441. {
  210442. const int maxCount = 3;
  210443. int count = maxCount;
  210444. for (;;)
  210445. {
  210446. for (i = inChans.size(); --i >= 0;)
  210447. {
  210448. DSoundInternalInChannel* const in = inChans.getUnchecked(i);
  210449. if ((! in->doneFlag) && in->service())
  210450. {
  210451. in->doneFlag = true;
  210452. --numToDo;
  210453. }
  210454. }
  210455. for (i = outChans.size(); --i >= 0;)
  210456. {
  210457. DSoundInternalOutChannel* const out = outChans.getUnchecked(i);
  210458. if ((! out->doneFlag) && out->service())
  210459. {
  210460. out->doneFlag = true;
  210461. --numToDo;
  210462. }
  210463. }
  210464. if (numToDo <= 0)
  210465. break;
  210466. if (Time::getMillisecondCounter() > startTime + maxTimeMS)
  210467. {
  210468. resync();
  210469. break;
  210470. }
  210471. if (--count <= 0)
  210472. {
  210473. Sleep (1);
  210474. count = maxCount;
  210475. }
  210476. if (threadShouldExit())
  210477. return;
  210478. }
  210479. }
  210480. else
  210481. {
  210482. sleep (1);
  210483. }
  210484. const ScopedLock sl (startStopLock);
  210485. if (isStarted)
  210486. {
  210487. JUCE_TRY
  210488. {
  210489. callback->audioDeviceIOCallback ((const float**) inputBuffers,
  210490. numInputBuffers,
  210491. outputBuffers,
  210492. numOutputBuffers,
  210493. bufferSizeSamples);
  210494. }
  210495. JUCE_CATCH_EXCEPTION
  210496. totalSamplesOut += bufferSizeSamples;
  210497. }
  210498. else
  210499. {
  210500. for (i = 0; i < numOutputBuffers; ++i)
  210501. if (outputBuffers[i] != 0)
  210502. zeromem (outputBuffers[i], bufferSizeSamples * sizeof (float));
  210503. totalSamplesOut = 0;
  210504. sleep (1);
  210505. }
  210506. }
  210507. }
  210508. };
  210509. class DSoundAudioIODeviceType : public AudioIODeviceType
  210510. {
  210511. public:
  210512. DSoundAudioIODeviceType()
  210513. : AudioIODeviceType (T("DirectSound")),
  210514. hasScanned (false)
  210515. {
  210516. initialiseDSoundFunctions();
  210517. }
  210518. ~DSoundAudioIODeviceType()
  210519. {
  210520. }
  210521. void scanForDevices()
  210522. {
  210523. hasScanned = true;
  210524. outputDeviceNames.clear();
  210525. outputGuids.clear();
  210526. inputDeviceNames.clear();
  210527. inputGuids.clear();
  210528. if (dsDirectSoundEnumerateW != 0)
  210529. {
  210530. dsDirectSoundEnumerateW (outputEnumProcW, this);
  210531. dsDirectSoundCaptureEnumerateW (inputEnumProcW, this);
  210532. }
  210533. }
  210534. const StringArray getDeviceNames (const bool wantInputNames) const
  210535. {
  210536. jassert (hasScanned); // need to call scanForDevices() before doing this
  210537. return wantInputNames ? inputDeviceNames
  210538. : outputDeviceNames;
  210539. }
  210540. int getDefaultDeviceIndex (const bool /*forInput*/) const
  210541. {
  210542. jassert (hasScanned); // need to call scanForDevices() before doing this
  210543. return 0;
  210544. }
  210545. int getIndexOfDevice (AudioIODevice* device, const bool asInput) const
  210546. {
  210547. jassert (hasScanned); // need to call scanForDevices() before doing this
  210548. DSoundAudioIODevice* const d = dynamic_cast <DSoundAudioIODevice*> (device);
  210549. if (d == 0)
  210550. return -1;
  210551. return asInput ? d->inputDeviceIndex
  210552. : d->outputDeviceIndex;
  210553. }
  210554. bool hasSeparateInputsAndOutputs() const { return true; }
  210555. AudioIODevice* createDevice (const String& outputDeviceName,
  210556. const String& inputDeviceName)
  210557. {
  210558. jassert (hasScanned); // need to call scanForDevices() before doing this
  210559. const int outputIndex = outputDeviceNames.indexOf (outputDeviceName);
  210560. const int inputIndex = inputDeviceNames.indexOf (inputDeviceName);
  210561. if (outputIndex >= 0 || inputIndex >= 0)
  210562. return new DSoundAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  210563. : inputDeviceName,
  210564. outputIndex, inputIndex);
  210565. return 0;
  210566. }
  210567. juce_UseDebuggingNewOperator
  210568. StringArray outputDeviceNames;
  210569. OwnedArray <GUID> outputGuids;
  210570. StringArray inputDeviceNames;
  210571. OwnedArray <GUID> inputGuids;
  210572. private:
  210573. bool hasScanned;
  210574. BOOL outputEnumProc (LPGUID lpGUID, String desc)
  210575. {
  210576. desc = desc.trim();
  210577. if (desc.isNotEmpty())
  210578. {
  210579. const String origDesc (desc);
  210580. int n = 2;
  210581. while (outputDeviceNames.contains (desc))
  210582. desc = origDesc + T(" (") + String (n++) + T(")");
  210583. outputDeviceNames.add (desc);
  210584. if (lpGUID != 0)
  210585. outputGuids.add (new GUID (*lpGUID));
  210586. else
  210587. outputGuids.add (0);
  210588. }
  210589. return TRUE;
  210590. }
  210591. static BOOL CALLBACK outputEnumProcW (LPGUID lpGUID, LPCWSTR description, LPCWSTR, LPVOID object)
  210592. {
  210593. return ((DSoundAudioIODeviceType*) object)
  210594. ->outputEnumProc (lpGUID, String (description));
  210595. }
  210596. static BOOL CALLBACK outputEnumProcA (LPGUID lpGUID, LPCTSTR description, LPCTSTR, LPVOID object)
  210597. {
  210598. return ((DSoundAudioIODeviceType*) object)
  210599. ->outputEnumProc (lpGUID, String (description));
  210600. }
  210601. BOOL CALLBACK inputEnumProc (LPGUID lpGUID, String desc)
  210602. {
  210603. desc = desc.trim();
  210604. if (desc.isNotEmpty())
  210605. {
  210606. const String origDesc (desc);
  210607. int n = 2;
  210608. while (inputDeviceNames.contains (desc))
  210609. desc = origDesc + T(" (") + String (n++) + T(")");
  210610. inputDeviceNames.add (desc);
  210611. if (lpGUID != 0)
  210612. inputGuids.add (new GUID (*lpGUID));
  210613. else
  210614. inputGuids.add (0);
  210615. }
  210616. return TRUE;
  210617. }
  210618. static BOOL CALLBACK inputEnumProcW (LPGUID lpGUID, LPCWSTR description, LPCWSTR, LPVOID object)
  210619. {
  210620. return ((DSoundAudioIODeviceType*) object)
  210621. ->inputEnumProc (lpGUID, String (description));
  210622. }
  210623. static BOOL CALLBACK inputEnumProcA (LPGUID lpGUID, LPCTSTR description, LPCTSTR, LPVOID object)
  210624. {
  210625. return ((DSoundAudioIODeviceType*) object)
  210626. ->inputEnumProc (lpGUID, String (description));
  210627. }
  210628. DSoundAudioIODeviceType (const DSoundAudioIODeviceType&);
  210629. const DSoundAudioIODeviceType& operator= (const DSoundAudioIODeviceType&);
  210630. };
  210631. const String DSoundAudioIODevice::openDevice (const BitArray& inputChannels,
  210632. const BitArray& outputChannels,
  210633. double sampleRate_,
  210634. int bufferSizeSamples_)
  210635. {
  210636. closeDevice();
  210637. totalSamplesOut = 0;
  210638. sampleRate = sampleRate_;
  210639. if (bufferSizeSamples_ <= 0)
  210640. bufferSizeSamples_ = 960; // use as a default size if none is set.
  210641. bufferSizeSamples = bufferSizeSamples_ & ~7;
  210642. DSoundAudioIODeviceType dlh;
  210643. dlh.scanForDevices();
  210644. enabledInputs = inputChannels;
  210645. enabledInputs.setRange (inChannels.size(),
  210646. enabledInputs.getHighestBit() + 1 - inChannels.size(),
  210647. false);
  210648. numInputBuffers = enabledInputs.countNumberOfSetBits();
  210649. inputBuffers = new float* [numInputBuffers + 2];
  210650. zeromem (inputBuffers, sizeof (float*) * numInputBuffers + 2);
  210651. int i, numIns = 0;
  210652. for (i = 0; i <= enabledInputs.getHighestBit(); i += 2)
  210653. {
  210654. float* left = 0;
  210655. float* right = 0;
  210656. if (enabledInputs[i])
  210657. left = inputBuffers[numIns++] = (float*) juce_calloc ((bufferSizeSamples + 16) * sizeof (float));
  210658. if (enabledInputs[i + 1])
  210659. right = inputBuffers[numIns++] = (float*) juce_calloc ((bufferSizeSamples + 16) * sizeof (float));
  210660. if (left != 0 || right != 0)
  210661. inChans.add (new DSoundInternalInChannel (dlh.inputDeviceNames [inputDeviceIndex],
  210662. dlh.inputGuids [inputDeviceIndex],
  210663. (int) sampleRate, bufferSizeSamples,
  210664. left, right));
  210665. }
  210666. enabledOutputs = outputChannels;
  210667. enabledOutputs.setRange (outChannels.size(),
  210668. enabledOutputs.getHighestBit() + 1 - outChannels.size(),
  210669. false);
  210670. numOutputBuffers = enabledOutputs.countNumberOfSetBits();
  210671. outputBuffers = new float* [numOutputBuffers + 2];
  210672. zeromem (outputBuffers, sizeof (float*) * numOutputBuffers + 2);
  210673. int numOuts = 0;
  210674. for (i = 0; i <= enabledOutputs.getHighestBit(); i += 2)
  210675. {
  210676. float* left = 0;
  210677. float* right = 0;
  210678. if (enabledOutputs[i])
  210679. left = outputBuffers[numOuts++] = (float*) juce_calloc ((bufferSizeSamples + 16) * sizeof (float));
  210680. if (enabledOutputs[i + 1])
  210681. right = outputBuffers[numOuts++] = (float*) juce_calloc ((bufferSizeSamples + 16) * sizeof (float));
  210682. if (left != 0 || right != 0)
  210683. outChans.add (new DSoundInternalOutChannel (dlh.outputDeviceNames[outputDeviceIndex],
  210684. dlh.outputGuids [outputDeviceIndex],
  210685. (int) sampleRate, bufferSizeSamples,
  210686. left, right));
  210687. }
  210688. String error;
  210689. // boost our priority while opening the devices to try to get better sync between them
  210690. const int oldThreadPri = GetThreadPriority (GetCurrentThread());
  210691. const int oldProcPri = GetPriorityClass (GetCurrentProcess());
  210692. SetThreadPriority (GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);
  210693. SetPriorityClass (GetCurrentProcess(), REALTIME_PRIORITY_CLASS);
  210694. for (i = 0; i < outChans.size(); ++i)
  210695. {
  210696. error = outChans[i]->open();
  210697. if (error.isNotEmpty())
  210698. {
  210699. error = T("Error opening ") + dlh.outputDeviceNames[i]
  210700. + T(": \"") + error + T("\"");
  210701. break;
  210702. }
  210703. }
  210704. if (error.isEmpty())
  210705. {
  210706. for (i = 0; i < inChans.size(); ++i)
  210707. {
  210708. error = inChans[i]->open();
  210709. if (error.isNotEmpty())
  210710. {
  210711. error = T("Error opening ") + dlh.inputDeviceNames[i]
  210712. + T(": \"") + error + T("\"");
  210713. break;
  210714. }
  210715. }
  210716. }
  210717. if (error.isEmpty())
  210718. {
  210719. totalSamplesOut = 0;
  210720. for (i = 0; i < outChans.size(); ++i)
  210721. outChans.getUnchecked(i)->synchronisePosition();
  210722. for (i = 0; i < inChans.size(); ++i)
  210723. inChans.getUnchecked(i)->synchronisePosition();
  210724. startThread (9);
  210725. sleep (10);
  210726. notify();
  210727. }
  210728. else
  210729. {
  210730. log (error);
  210731. }
  210732. SetThreadPriority (GetCurrentThread(), oldThreadPri);
  210733. SetPriorityClass (GetCurrentProcess(), oldProcPri);
  210734. return error;
  210735. }
  210736. AudioIODeviceType* juce_createAudioIODeviceType_DirectSound()
  210737. {
  210738. return new DSoundAudioIODeviceType();
  210739. }
  210740. #undef log
  210741. #endif
  210742. /********* End of inlined file: juce_win32_DirectSound.cpp *********/
  210743. /********* Start of inlined file: juce_win32_WASAPI.cpp *********/
  210744. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  210745. // compiled on its own).
  210746. #if JUCE_INCLUDED_FILE && JUCE_WASAPI
  210747. #if 1
  210748. const String getAudioErrorDesc (HRESULT hr)
  210749. {
  210750. const char* e = 0;
  210751. switch (hr)
  210752. {
  210753. case E_POINTER: e = "E_POINTER"; break;
  210754. case E_INVALIDARG: e = "E_INVALIDARG"; break;
  210755. case AUDCLNT_E_NOT_INITIALIZED: e = "AUDCLNT_E_NOT_INITIALIZED"; break;
  210756. case AUDCLNT_E_ALREADY_INITIALIZED: e = "AUDCLNT_E_ALREADY_INITIALIZED"; break;
  210757. case AUDCLNT_E_WRONG_ENDPOINT_TYPE: e = "AUDCLNT_E_WRONG_ENDPOINT_TYPE"; break;
  210758. case AUDCLNT_E_DEVICE_INVALIDATED: e = "AUDCLNT_E_DEVICE_INVALIDATED"; break;
  210759. case AUDCLNT_E_NOT_STOPPED: e = "AUDCLNT_E_NOT_STOPPED"; break;
  210760. case AUDCLNT_E_BUFFER_TOO_LARGE: e = "AUDCLNT_E_BUFFER_TOO_LARGE"; break;
  210761. case AUDCLNT_E_OUT_OF_ORDER: e = "AUDCLNT_E_OUT_OF_ORDER"; break;
  210762. case AUDCLNT_E_UNSUPPORTED_FORMAT: e = "AUDCLNT_E_UNSUPPORTED_FORMAT"; break;
  210763. case AUDCLNT_E_INVALID_SIZE: e = "AUDCLNT_E_INVALID_SIZE"; break;
  210764. case AUDCLNT_E_DEVICE_IN_USE: e = "AUDCLNT_E_DEVICE_IN_USE"; break;
  210765. case AUDCLNT_E_BUFFER_OPERATION_PENDING: e = "AUDCLNT_E_BUFFER_OPERATION_PENDING"; break;
  210766. case AUDCLNT_E_THREAD_NOT_REGISTERED: e = "AUDCLNT_E_THREAD_NOT_REGISTERED"; break;
  210767. case AUDCLNT_E_EXCLUSIVE_MODE_NOT_ALLOWED: e = "AUDCLNT_E_EXCLUSIVE_MODE_NOT_ALLOWED"; break;
  210768. case AUDCLNT_E_ENDPOINT_CREATE_FAILED: e = "AUDCLNT_E_ENDPOINT_CREATE_FAILED"; break;
  210769. case AUDCLNT_E_SERVICE_NOT_RUNNING: e = "AUDCLNT_E_SERVICE_NOT_RUNNING"; break;
  210770. case AUDCLNT_E_EVENTHANDLE_NOT_EXPECTED: e = "AUDCLNT_E_EVENTHANDLE_NOT_EXPECTED"; break;
  210771. case AUDCLNT_E_EXCLUSIVE_MODE_ONLY: e = "AUDCLNT_E_EXCLUSIVE_MODE_ONLY"; break;
  210772. case AUDCLNT_E_BUFDURATION_PERIOD_NOT_EQUAL: e = "AUDCLNT_E_BUFDURATION_PERIOD_NOT_EQUAL"; break;
  210773. case AUDCLNT_E_EVENTHANDLE_NOT_SET: e = "AUDCLNT_E_EVENTHANDLE_NOT_SET"; break;
  210774. case AUDCLNT_E_INCORRECT_BUFFER_SIZE: e = "AUDCLNT_E_INCORRECT_BUFFER_SIZE"; break;
  210775. case AUDCLNT_E_BUFFER_SIZE_ERROR: e = "AUDCLNT_E_BUFFER_SIZE_ERROR"; break;
  210776. case AUDCLNT_S_BUFFER_EMPTY: e = "AUDCLNT_S_BUFFER_EMPTY"; break;
  210777. case AUDCLNT_S_THREAD_ALREADY_REGISTERED: e = "AUDCLNT_S_THREAD_ALREADY_REGISTERED"; break;
  210778. default: return String::toHexString ((int) hr);
  210779. }
  210780. return e;
  210781. }
  210782. #define logFailure(hr) { if (FAILED (hr)) { DBG ("WASAPI FAIL! " + getAudioErrorDesc (hr)); jassertfalse } }
  210783. #define OK(a) wasapi_checkResult(a)
  210784. static bool wasapi_checkResult (HRESULT hr)
  210785. {
  210786. logFailure (hr);
  210787. return SUCCEEDED (hr);
  210788. }
  210789. #else
  210790. #define logFailure(hr) {}
  210791. #define OK(a) SUCCEEDED(a)
  210792. #endif
  210793. static const String wasapi_getDeviceID (IMMDevice* const device)
  210794. {
  210795. String s;
  210796. WCHAR* deviceId = 0;
  210797. if (OK (device->GetId (&deviceId)))
  210798. {
  210799. s = String (deviceId);
  210800. CoTaskMemFree (deviceId);
  210801. }
  210802. return s;
  210803. }
  210804. static EDataFlow wasapi_getDataFlow (IMMDevice* const device)
  210805. {
  210806. EDataFlow flow = eRender;
  210807. ComSmartPtr <IMMEndpoint> endPoint;
  210808. if (OK (device->QueryInterface (__uuidof (IMMEndpoint), (void**) &endPoint)))
  210809. (void) OK (endPoint->GetDataFlow (&flow));
  210810. return flow;
  210811. }
  210812. static int wasapi_refTimeToSamples (const REFERENCE_TIME& t, const double sampleRate) throw()
  210813. {
  210814. return roundDoubleToInt (sampleRate * ((double) t) * 0.0000001);
  210815. }
  210816. static void wasapi_copyWavFormat (WAVEFORMATEXTENSIBLE& dest, const WAVEFORMATEX* const src) throw()
  210817. {
  210818. memcpy (&dest, src, src->wFormatTag == WAVE_FORMAT_EXTENSIBLE ? sizeof (WAVEFORMATEXTENSIBLE)
  210819. : sizeof (WAVEFORMATEX));
  210820. }
  210821. class WASAPIDeviceBase
  210822. {
  210823. public:
  210824. WASAPIDeviceBase (const ComSmartPtr <IMMDevice>& device_)
  210825. : device (device_),
  210826. sampleRate (0),
  210827. numChannels (0),
  210828. actualNumChannels (0),
  210829. defaultSampleRate (0),
  210830. minBufferSize (0),
  210831. defaultBufferSize (0),
  210832. latencySamples (0)
  210833. {
  210834. clientEvent = CreateEvent (0, false, false, _T("JuceWASAPI"));
  210835. ComSmartPtr <IAudioClient> tempClient (createClient());
  210836. if (tempClient == 0)
  210837. return;
  210838. REFERENCE_TIME defaultPeriod, minPeriod;
  210839. if (! OK (tempClient->GetDevicePeriod (&defaultPeriod, &minPeriod)))
  210840. return;
  210841. WAVEFORMATEX* mixFormat = 0;
  210842. if (! OK (tempClient->GetMixFormat (&mixFormat)))
  210843. return;
  210844. WAVEFORMATEXTENSIBLE format;
  210845. wasapi_copyWavFormat (format, mixFormat);
  210846. CoTaskMemFree (mixFormat);
  210847. actualNumChannels = numChannels = format.Format.nChannels;
  210848. defaultSampleRate = format.Format.nSamplesPerSec;
  210849. minBufferSize = wasapi_refTimeToSamples (minPeriod, defaultSampleRate);
  210850. defaultBufferSize = wasapi_refTimeToSamples (defaultPeriod, defaultSampleRate);
  210851. FloatElementComparator<double> comparator;
  210852. rates.addSorted (comparator, defaultSampleRate);
  210853. static const double ratesToTest[] = { 44100.0, 48000.0, 88200.0, 96000.0 };
  210854. for (int i = 0; i < numElementsInArray (ratesToTest); ++i)
  210855. {
  210856. if (ratesToTest[i] == defaultSampleRate)
  210857. continue;
  210858. format.Format.nSamplesPerSec = roundDoubleToInt (ratesToTest[i]);
  210859. if (SUCCEEDED (tempClient->IsFormatSupported (AUDCLNT_SHAREMODE_SHARED, (WAVEFORMATEX*) &format, 0)))
  210860. if (! rates.contains (ratesToTest[i]))
  210861. rates.addSorted (comparator, ratesToTest[i]);
  210862. }
  210863. }
  210864. ~WASAPIDeviceBase()
  210865. {
  210866. device = 0;
  210867. CloseHandle (clientEvent);
  210868. }
  210869. bool isOk() const throw() { return defaultBufferSize > 0 && defaultSampleRate > 0; }
  210870. bool openClient (const double newSampleRate, const BitArray& newChannels)
  210871. {
  210872. sampleRate = newSampleRate;
  210873. channels = newChannels;
  210874. channels.setRange (actualNumChannels, channels.getHighestBit() + 1 - actualNumChannels, false);
  210875. numChannels = channels.getHighestBit() + 1;
  210876. if (numChannels == 0)
  210877. return true;
  210878. client = createClient();
  210879. if (client != 0
  210880. && (tryInitialisingWithFormat (true, 4) || tryInitialisingWithFormat (false, 4)
  210881. || tryInitialisingWithFormat (false, 3) || tryInitialisingWithFormat (false, 2)))
  210882. {
  210883. channelMaps.clear();
  210884. for (int i = 0; i <= channels.getHighestBit(); ++i)
  210885. if (channels[i])
  210886. channelMaps.add (i);
  210887. REFERENCE_TIME latency;
  210888. if (OK (client->GetStreamLatency (&latency)))
  210889. latencySamples = wasapi_refTimeToSamples (latency, sampleRate);
  210890. (void) OK (client->GetBufferSize (&actualBufferSize));
  210891. return OK (client->SetEventHandle (clientEvent));
  210892. }
  210893. return false;
  210894. }
  210895. void closeClient()
  210896. {
  210897. if (client != 0)
  210898. client->Stop();
  210899. client = 0;
  210900. ResetEvent (clientEvent);
  210901. }
  210902. ComSmartPtr <IMMDevice> device;
  210903. ComSmartPtr <IAudioClient> client;
  210904. double sampleRate, defaultSampleRate;
  210905. int numChannels, actualNumChannels;
  210906. int minBufferSize, defaultBufferSize, latencySamples;
  210907. Array <double> rates;
  210908. HANDLE clientEvent;
  210909. BitArray channels;
  210910. AudioDataConverters::DataFormat dataFormat;
  210911. Array <int> channelMaps;
  210912. UINT32 actualBufferSize;
  210913. int bytesPerSample;
  210914. private:
  210915. const ComSmartPtr <IAudioClient> createClient()
  210916. {
  210917. ComSmartPtr <IAudioClient> client;
  210918. if (device != 0)
  210919. {
  210920. HRESULT hr = device->Activate (__uuidof (IAudioClient), CLSCTX_INPROC_SERVER, 0, (void**) &client);
  210921. logFailure (hr);
  210922. }
  210923. return client;
  210924. }
  210925. bool tryInitialisingWithFormat (const bool useFloat, const int bytesPerSampleToTry)
  210926. {
  210927. WAVEFORMATEXTENSIBLE format;
  210928. zerostruct (format);
  210929. if (numChannels <= 2 && bytesPerSampleToTry <= 2)
  210930. {
  210931. format.Format.wFormatTag = WAVE_FORMAT_PCM;
  210932. }
  210933. else
  210934. {
  210935. format.Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE;
  210936. format.Format.cbSize = sizeof (WAVEFORMATEXTENSIBLE) - sizeof (WAVEFORMATEX);
  210937. }
  210938. format.Format.nSamplesPerSec = roundDoubleToInt (sampleRate);
  210939. format.Format.nChannels = (WORD) numChannels;
  210940. format.Format.wBitsPerSample = (WORD) (8 * bytesPerSampleToTry);
  210941. format.Format.nAvgBytesPerSec = (DWORD) (format.Format.nSamplesPerSec * numChannels * bytesPerSampleToTry);
  210942. format.Format.nBlockAlign = (WORD) (numChannels * bytesPerSampleToTry);
  210943. format.SubFormat = useFloat ? KSDATAFORMAT_SUBTYPE_IEEE_FLOAT : KSDATAFORMAT_SUBTYPE_PCM;
  210944. format.Samples.wValidBitsPerSample = format.Format.wBitsPerSample;
  210945. switch (numChannels)
  210946. {
  210947. case 1: format.dwChannelMask = SPEAKER_FRONT_CENTER; break;
  210948. case 2: format.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT; break;
  210949. case 4: format.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT; break;
  210950. case 6: format.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_FRONT_CENTER | SPEAKER_LOW_FREQUENCY | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT; break;
  210951. case 8: format.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_FRONT_CENTER | SPEAKER_LOW_FREQUENCY | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT | SPEAKER_FRONT_LEFT_OF_CENTER | SPEAKER_FRONT_RIGHT_OF_CENTER; break;
  210952. default: break;
  210953. }
  210954. WAVEFORMATEXTENSIBLE* nearestFormat = 0;
  210955. HRESULT hr = client->IsFormatSupported (AUDCLNT_SHAREMODE_SHARED, (WAVEFORMATEX*) &format, (WAVEFORMATEX**) &nearestFormat);
  210956. logFailure (hr);
  210957. if (hr == S_FALSE && format.Format.nSamplesPerSec == nearestFormat->Format.nSamplesPerSec)
  210958. {
  210959. wasapi_copyWavFormat (format, (WAVEFORMATEX*) nearestFormat);
  210960. hr = S_OK;
  210961. }
  210962. CoTaskMemFree (nearestFormat);
  210963. GUID session;
  210964. if (hr == S_OK
  210965. && OK (client->Initialize (AUDCLNT_SHAREMODE_SHARED, AUDCLNT_STREAMFLAGS_EVENTCALLBACK,
  210966. 0, 0, (WAVEFORMATEX*) &format, &session)))
  210967. {
  210968. actualNumChannels = format.Format.nChannels;
  210969. const bool isFloat = format.Format.wFormatTag == WAVE_FORMAT_EXTENSIBLE && format.SubFormat == KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
  210970. bytesPerSample = format.Format.wBitsPerSample / 8;
  210971. dataFormat = isFloat ? AudioDataConverters::float32LE
  210972. : (bytesPerSample == 4 ? AudioDataConverters::int32LE
  210973. : ((bytesPerSample == 3 ? AudioDataConverters::int24LE
  210974. : AudioDataConverters::int16LE)));
  210975. return true;
  210976. }
  210977. return false;
  210978. }
  210979. };
  210980. class WASAPIInputDevice : public WASAPIDeviceBase
  210981. {
  210982. public:
  210983. WASAPIInputDevice (const ComSmartPtr <IMMDevice>& device_)
  210984. : WASAPIDeviceBase (device_),
  210985. reservoir (1, 1)
  210986. {
  210987. }
  210988. ~WASAPIInputDevice()
  210989. {
  210990. close();
  210991. }
  210992. bool open (const double newSampleRate, const BitArray& newChannels)
  210993. {
  210994. reservoirSize = 0;
  210995. reservoirCapacity = 16384;
  210996. reservoir.setSize (actualNumChannels * reservoirCapacity * sizeof (float));
  210997. return openClient (newSampleRate, newChannels)
  210998. && (numChannels == 0 || OK (client->GetService (__uuidof (IAudioCaptureClient), (void**) &captureClient)));
  210999. }
  211000. void close()
  211001. {
  211002. closeClient();
  211003. captureClient = 0;
  211004. reservoir.setSize (0);
  211005. }
  211006. void copyBuffers (float** destBuffers, int numDestBuffers, int bufferSize, Thread& thread)
  211007. {
  211008. if (numChannels <= 0)
  211009. return;
  211010. int offset = 0;
  211011. while (bufferSize > 0)
  211012. {
  211013. if (reservoirSize > 0) // There's stuff in the reservoir, so use that...
  211014. {
  211015. const int samplesToDo = jmin (bufferSize, (int) reservoirSize);
  211016. for (int i = 0; i < numDestBuffers; ++i)
  211017. {
  211018. float* const dest = destBuffers[i] + offset;
  211019. const int srcChan = channelMaps.getUnchecked(i);
  211020. switch (dataFormat)
  211021. {
  211022. case AudioDataConverters::float32LE:
  211023. AudioDataConverters::convertFloat32LEToFloat (((uint8*) reservoir.getData()) + 4 * srcChan, dest, samplesToDo, 4 * actualNumChannels);
  211024. break;
  211025. case AudioDataConverters::int32LE:
  211026. AudioDataConverters::convertInt32LEToFloat (((uint8*) reservoir.getData()) + 4 * srcChan, dest, samplesToDo, 4 * actualNumChannels);
  211027. break;
  211028. case AudioDataConverters::int24LE:
  211029. AudioDataConverters::convertInt24LEToFloat (((uint8*) reservoir.getData()) + 3 * srcChan, dest, samplesToDo, 3 * actualNumChannels);
  211030. break;
  211031. case AudioDataConverters::int16LE:
  211032. AudioDataConverters::convertInt16LEToFloat (((uint8*) reservoir.getData()) + 2 * srcChan, dest, samplesToDo, 2 * actualNumChannels);
  211033. break;
  211034. default: jassertfalse; break;
  211035. }
  211036. }
  211037. bufferSize -= samplesToDo;
  211038. offset += samplesToDo;
  211039. reservoirSize -= samplesToDo;
  211040. }
  211041. else
  211042. {
  211043. UINT32 packetLength = 0;
  211044. if (! OK (captureClient->GetNextPacketSize (&packetLength)))
  211045. break;
  211046. if (packetLength == 0)
  211047. {
  211048. if (thread.threadShouldExit())
  211049. break;
  211050. Thread::sleep (1);
  211051. continue;
  211052. }
  211053. uint8* inputData = 0;
  211054. UINT32 numSamplesAvailable;
  211055. DWORD flags;
  211056. if (OK (captureClient->GetBuffer (&inputData, &numSamplesAvailable, &flags, 0, 0)))
  211057. {
  211058. const int samplesToDo = jmin (bufferSize, (int) numSamplesAvailable);
  211059. for (int i = 0; i < numDestBuffers; ++i)
  211060. {
  211061. float* const dest = destBuffers[i] + offset;
  211062. const int srcChan = channelMaps.getUnchecked(i);
  211063. switch (dataFormat)
  211064. {
  211065. case AudioDataConverters::float32LE:
  211066. AudioDataConverters::convertFloat32LEToFloat (inputData + 4 * srcChan, dest, samplesToDo, 4 * actualNumChannels);
  211067. break;
  211068. case AudioDataConverters::int32LE:
  211069. AudioDataConverters::convertInt32LEToFloat (inputData + 4 * srcChan, dest, samplesToDo, 4 * actualNumChannels);
  211070. break;
  211071. case AudioDataConverters::int24LE:
  211072. AudioDataConverters::convertInt24LEToFloat (inputData + 3 * srcChan, dest, samplesToDo, 3 * actualNumChannels);
  211073. break;
  211074. case AudioDataConverters::int16LE:
  211075. AudioDataConverters::convertInt16LEToFloat (inputData + 2 * srcChan, dest, samplesToDo, 2 * actualNumChannels);
  211076. break;
  211077. default: jassertfalse; break;
  211078. }
  211079. }
  211080. bufferSize -= samplesToDo;
  211081. offset += samplesToDo;
  211082. if (samplesToDo < numSamplesAvailable)
  211083. {
  211084. reservoirSize = jmin (numSamplesAvailable - samplesToDo, reservoirCapacity);
  211085. memcpy ((uint8*) reservoir.getData(), inputData + bytesPerSample * actualNumChannels * samplesToDo,
  211086. bytesPerSample * actualNumChannels * reservoirSize);
  211087. }
  211088. captureClient->ReleaseBuffer (numSamplesAvailable);
  211089. }
  211090. }
  211091. }
  211092. }
  211093. ComSmartPtr <IAudioCaptureClient> captureClient;
  211094. MemoryBlock reservoir;
  211095. int reservoirSize, reservoirCapacity;
  211096. };
  211097. class WASAPIOutputDevice : public WASAPIDeviceBase
  211098. {
  211099. public:
  211100. WASAPIOutputDevice (const ComSmartPtr <IMMDevice>& device_)
  211101. : WASAPIDeviceBase (device_)
  211102. {
  211103. }
  211104. ~WASAPIOutputDevice()
  211105. {
  211106. close();
  211107. }
  211108. bool open (const double newSampleRate, const BitArray& newChannels)
  211109. {
  211110. return openClient (newSampleRate, newChannels)
  211111. && (numChannels == 0 || OK (client->GetService (__uuidof (IAudioRenderClient), (void**) &renderClient)));
  211112. }
  211113. void close()
  211114. {
  211115. closeClient();
  211116. renderClient = 0;
  211117. }
  211118. void copyBuffers (const float** const srcBuffers, const int numSrcBuffers, int bufferSize, Thread& thread)
  211119. {
  211120. if (numChannels <= 0)
  211121. return;
  211122. int offset = 0;
  211123. while (bufferSize > 0)
  211124. {
  211125. UINT32 padding = 0;
  211126. if (! OK (client->GetCurrentPadding (&padding)))
  211127. return;
  211128. const int samplesToDo = jmin ((int) (actualBufferSize - padding), bufferSize);
  211129. if (samplesToDo <= 0)
  211130. {
  211131. if (thread.threadShouldExit())
  211132. break;
  211133. Thread::sleep (0);
  211134. continue;
  211135. }
  211136. uint8* outputData = 0;
  211137. if (OK (renderClient->GetBuffer (samplesToDo, &outputData)))
  211138. {
  211139. for (int i = 0; i < numSrcBuffers; ++i)
  211140. {
  211141. const float* const source = srcBuffers[i] + offset;
  211142. const int destChan = channelMaps.getUnchecked(i);
  211143. switch (dataFormat)
  211144. {
  211145. case AudioDataConverters::float32LE:
  211146. AudioDataConverters::convertFloatToFloat32LE (source, outputData + 4 * destChan, samplesToDo, 4 * actualNumChannels);
  211147. break;
  211148. case AudioDataConverters::int32LE:
  211149. AudioDataConverters::convertFloatToInt32LE (source, outputData + 4 * destChan, samplesToDo, 4 * actualNumChannels);
  211150. break;
  211151. case AudioDataConverters::int24LE:
  211152. AudioDataConverters::convertFloatToInt24LE (source, outputData + 3 * destChan, samplesToDo, 3 * actualNumChannels);
  211153. break;
  211154. case AudioDataConverters::int16LE:
  211155. AudioDataConverters::convertFloatToInt16LE (source, outputData + 2 * destChan, samplesToDo, 2 * actualNumChannels);
  211156. break;
  211157. default: jassertfalse; break;
  211158. }
  211159. }
  211160. renderClient->ReleaseBuffer (samplesToDo, 0);
  211161. offset += samplesToDo;
  211162. bufferSize -= samplesToDo;
  211163. }
  211164. }
  211165. }
  211166. ComSmartPtr <IAudioRenderClient> renderClient;
  211167. };
  211168. class WASAPIAudioIODevice : public AudioIODevice,
  211169. public Thread
  211170. {
  211171. public:
  211172. WASAPIAudioIODevice (const String& deviceName,
  211173. const String& outputDeviceId_,
  211174. const String& inputDeviceId_)
  211175. : AudioIODevice (deviceName, "Windows Audio"),
  211176. Thread ("Juce WASAPI"),
  211177. isOpen_ (false),
  211178. isStarted (false),
  211179. outputDevice (0),
  211180. outputDeviceId (outputDeviceId_),
  211181. inputDevice (0),
  211182. inputDeviceId (inputDeviceId_),
  211183. currentBufferSizeSamples (0),
  211184. currentSampleRate (0),
  211185. callback (0)
  211186. {
  211187. }
  211188. ~WASAPIAudioIODevice()
  211189. {
  211190. close();
  211191. deleteAndZero (inputDevice);
  211192. deleteAndZero (outputDevice);
  211193. }
  211194. bool initialise()
  211195. {
  211196. double defaultSampleRateIn = 0, defaultSampleRateOut = 0;
  211197. int minBufferSizeIn = 0, defaultBufferSizeIn = 0, minBufferSizeOut = 0, defaultBufferSizeOut = 0;
  211198. latencyIn = latencyOut = 0;
  211199. Array <double> ratesIn, ratesOut;
  211200. if (createDevices())
  211201. {
  211202. jassert (inputDevice != 0 || outputDevice != 0);
  211203. if (inputDevice != 0 && outputDevice != 0)
  211204. {
  211205. defaultSampleRate = jmin (inputDevice->defaultSampleRate, outputDevice->defaultSampleRate);
  211206. minBufferSize = jmin (inputDevice->minBufferSize, outputDevice->minBufferSize);
  211207. defaultBufferSize = jmax (inputDevice->defaultBufferSize, outputDevice->defaultBufferSize);
  211208. sampleRates = inputDevice->rates;
  211209. sampleRates.removeValuesNotIn (outputDevice->rates);
  211210. jassert (sampleRates.size() > 0); // in and out devices don't share any common sample rates!
  211211. }
  211212. else
  211213. {
  211214. WASAPIDeviceBase* const d = inputDevice != 0 ? (WASAPIDeviceBase*) inputDevice : (WASAPIDeviceBase*) outputDevice;
  211215. defaultSampleRate = d->defaultSampleRate;
  211216. minBufferSize = d->minBufferSize;
  211217. defaultBufferSize = d->defaultBufferSize;
  211218. sampleRates = d->rates;
  211219. }
  211220. IntegerElementComparator<int> comparator;
  211221. bufferSizes.addSorted (comparator, defaultBufferSize);
  211222. if (minBufferSize != defaultBufferSize)
  211223. bufferSizes.addSorted (comparator, minBufferSize);
  211224. int n = 64;
  211225. for (int i = 0; i < 40; ++i)
  211226. {
  211227. if (n >= minBufferSize && n <= 2048 && ! bufferSizes.contains (n))
  211228. bufferSizes.addSorted (comparator, n);
  211229. n += (n < 512) ? 32 : (n < 1024 ? 64 : 128);
  211230. }
  211231. return true;
  211232. }
  211233. return false;
  211234. }
  211235. const StringArray getOutputChannelNames()
  211236. {
  211237. StringArray outChannels;
  211238. if (outputDevice != 0)
  211239. for (int i = 1; i <= outputDevice->actualNumChannels; ++i)
  211240. outChannels.add ("Output channel " + String (i));
  211241. return outChannels;
  211242. }
  211243. const StringArray getInputChannelNames()
  211244. {
  211245. StringArray inChannels;
  211246. if (inputDevice != 0)
  211247. for (int i = 1; i <= inputDevice->actualNumChannels; ++i)
  211248. inChannels.add ("Input channel " + String (i));
  211249. return inChannels;
  211250. }
  211251. int getNumSampleRates() { return sampleRates.size(); }
  211252. double getSampleRate (int index) { return sampleRates [index]; }
  211253. int getNumBufferSizesAvailable() { return bufferSizes.size(); }
  211254. int getBufferSizeSamples (int index) { return bufferSizes [index]; }
  211255. int getDefaultBufferSize() { return defaultBufferSize; }
  211256. int getCurrentBufferSizeSamples() { return currentBufferSizeSamples; }
  211257. double getCurrentSampleRate() { return currentSampleRate; }
  211258. int getCurrentBitDepth() { return 32; }
  211259. int getOutputLatencyInSamples() { return latencyOut; }
  211260. int getInputLatencyInSamples() { return latencyIn; }
  211261. const BitArray getActiveOutputChannels() const { return outputDevice != 0 ? outputDevice->channels : BitArray(); }
  211262. const BitArray getActiveInputChannels() const { return inputDevice != 0 ? inputDevice->channels : BitArray(); }
  211263. const String getLastError() { return lastError; }
  211264. const String open (const BitArray& inputChannels, const BitArray& outputChannels,
  211265. double sampleRate, int bufferSizeSamples)
  211266. {
  211267. close();
  211268. lastError = String::empty;
  211269. currentBufferSizeSamples = bufferSizeSamples <= 0 ? defaultBufferSize : jmax (bufferSizeSamples, minBufferSize);
  211270. currentSampleRate = sampleRate > 0 ? sampleRate : defaultSampleRate;
  211271. if (inputDevice != 0 && ! inputDevice->open (currentSampleRate, inputChannels))
  211272. {
  211273. lastError = "Couldn't open the input device!";
  211274. return lastError;
  211275. }
  211276. if (outputDevice != 0 && ! outputDevice->open (currentSampleRate, outputChannels))
  211277. {
  211278. close();
  211279. lastError = "Couldn't open the output device!";
  211280. return lastError;
  211281. }
  211282. if (inputDevice != 0)
  211283. ResetEvent (inputDevice->clientEvent);
  211284. if (outputDevice != 0)
  211285. ResetEvent (outputDevice->clientEvent);
  211286. startThread (8);
  211287. Thread::sleep (5);
  211288. if (inputDevice != 0 && inputDevice->client != 0)
  211289. {
  211290. latencyIn = inputDevice->latencySamples + inputDevice->actualBufferSize + inputDevice->minBufferSize;
  211291. HRESULT hr = inputDevice->client->Start();
  211292. logFailure (hr); //xxx handle this
  211293. }
  211294. if (outputDevice != 0 && outputDevice->client != 0)
  211295. {
  211296. latencyOut = outputDevice->latencySamples + outputDevice->actualBufferSize + outputDevice->minBufferSize;
  211297. HRESULT hr = outputDevice->client->Start();
  211298. logFailure (hr); //xxx handle this
  211299. }
  211300. isOpen_ = true;
  211301. return lastError;
  211302. }
  211303. void close()
  211304. {
  211305. stop();
  211306. if (inputDevice != 0)
  211307. SetEvent (inputDevice->clientEvent);
  211308. if (outputDevice != 0)
  211309. SetEvent (outputDevice->clientEvent);
  211310. stopThread (5000);
  211311. if (inputDevice != 0)
  211312. inputDevice->close();
  211313. if (outputDevice != 0)
  211314. outputDevice->close();
  211315. isOpen_ = false;
  211316. }
  211317. bool isOpen() { return isOpen_ && isThreadRunning(); }
  211318. bool isPlaying() { return isStarted && isOpen_ && isThreadRunning(); }
  211319. void start (AudioIODeviceCallback* call)
  211320. {
  211321. if (isOpen_ && call != 0 && ! isStarted)
  211322. {
  211323. if (! isThreadRunning())
  211324. {
  211325. // something's gone wrong and the thread's stopped..
  211326. isOpen_ = false;
  211327. return;
  211328. }
  211329. call->audioDeviceAboutToStart (this);
  211330. const ScopedLock sl (startStopLock);
  211331. callback = call;
  211332. isStarted = true;
  211333. }
  211334. }
  211335. void stop()
  211336. {
  211337. if (isStarted)
  211338. {
  211339. AudioIODeviceCallback* const callbackLocal = callback;
  211340. {
  211341. const ScopedLock sl (startStopLock);
  211342. isStarted = false;
  211343. }
  211344. if (callbackLocal != 0)
  211345. callbackLocal->audioDeviceStopped();
  211346. }
  211347. }
  211348. void run()
  211349. {
  211350. const int bufferSize = currentBufferSizeSamples;
  211351. HANDLE events[2];
  211352. int numEvents = 0;
  211353. if (inputDevice != 0)
  211354. events [numEvents++] = inputDevice->clientEvent;
  211355. if (outputDevice != 0)
  211356. events [numEvents++] = outputDevice->clientEvent;
  211357. const int numInputBuffers = getActiveInputChannels().countNumberOfSetBits();
  211358. const int numOutputBuffers = getActiveOutputChannels().countNumberOfSetBits();
  211359. AudioSampleBuffer ins (jmax (1, numInputBuffers), bufferSize + 32);
  211360. AudioSampleBuffer outs (jmax (1, numOutputBuffers), bufferSize + 32);
  211361. float** const inputBuffers = ins.getArrayOfChannels();
  211362. float** const outputBuffers = outs.getArrayOfChannels();
  211363. ins.clear();
  211364. while (! threadShouldExit())
  211365. {
  211366. const DWORD result = WaitForMultipleObjects (numEvents, events, true, 1000);
  211367. if (result == WAIT_TIMEOUT)
  211368. continue;
  211369. if (threadShouldExit())
  211370. break;
  211371. if (inputDevice != 0)
  211372. inputDevice->copyBuffers (inputBuffers, numInputBuffers, bufferSize, *this);
  211373. // Make the callback..
  211374. {
  211375. const ScopedLock sl (startStopLock);
  211376. if (isStarted)
  211377. {
  211378. JUCE_TRY
  211379. {
  211380. callback->audioDeviceIOCallback ((const float**) inputBuffers,
  211381. numInputBuffers,
  211382. outputBuffers,
  211383. numOutputBuffers,
  211384. bufferSize);
  211385. }
  211386. JUCE_CATCH_EXCEPTION
  211387. }
  211388. else
  211389. {
  211390. outs.clear();
  211391. }
  211392. }
  211393. if (outputDevice != 0)
  211394. outputDevice->copyBuffers ((const float**) outputBuffers, numOutputBuffers, bufferSize, *this);
  211395. }
  211396. }
  211397. juce_UseDebuggingNewOperator
  211398. String outputDeviceId, inputDeviceId;
  211399. String lastError;
  211400. private:
  211401. // Device stats...
  211402. WASAPIInputDevice* inputDevice;
  211403. WASAPIOutputDevice* outputDevice;
  211404. double defaultSampleRate;
  211405. int minBufferSize, defaultBufferSize;
  211406. int latencyIn, latencyOut;
  211407. Array <double> sampleRates;
  211408. Array <int> bufferSizes;
  211409. // Active state...
  211410. bool isOpen_, isStarted;
  211411. int currentBufferSizeSamples;
  211412. double currentSampleRate;
  211413. AudioIODeviceCallback* callback;
  211414. CriticalSection startStopLock;
  211415. bool createDevices()
  211416. {
  211417. ComSmartPtr <IMMDeviceEnumerator> enumerator;
  211418. if (! OK (enumerator.CoCreateInstance (__uuidof (MMDeviceEnumerator), CLSCTX_INPROC_SERVER)))
  211419. return false;
  211420. ComSmartPtr <IMMDeviceCollection> deviceCollection;
  211421. if (! OK (enumerator->EnumAudioEndpoints (eAll, DEVICE_STATE_ACTIVE, &deviceCollection)))
  211422. return false;
  211423. UINT32 numDevices = 0;
  211424. if (! OK (deviceCollection->GetCount (&numDevices)))
  211425. return false;
  211426. for (UINT32 i = 0; i < numDevices; ++i)
  211427. {
  211428. ComSmartPtr <IMMDevice> device;
  211429. if (! OK (deviceCollection->Item (i, &device)))
  211430. continue;
  211431. const String deviceId (wasapi_getDeviceID (device));
  211432. if (deviceId.isEmpty())
  211433. continue;
  211434. const EDataFlow flow = wasapi_getDataFlow (device);
  211435. if (deviceId == inputDeviceId && flow == eCapture)
  211436. inputDevice = new WASAPIInputDevice (device);
  211437. else if (deviceId == outputDeviceId && flow == eRender)
  211438. outputDevice = new WASAPIOutputDevice (device);
  211439. }
  211440. return (outputDeviceId.isEmpty() || (outputDevice != 0 && outputDevice->isOk()))
  211441. && (inputDeviceId.isEmpty() || (inputDevice != 0 && inputDevice->isOk()));
  211442. }
  211443. WASAPIAudioIODevice (const WASAPIAudioIODevice&);
  211444. const WASAPIAudioIODevice& operator= (const WASAPIAudioIODevice&);
  211445. };
  211446. class WASAPIAudioIODeviceType : public AudioIODeviceType
  211447. {
  211448. public:
  211449. WASAPIAudioIODeviceType()
  211450. : AudioIODeviceType (T("Windows Audio")),
  211451. hasScanned (false)
  211452. {
  211453. }
  211454. ~WASAPIAudioIODeviceType()
  211455. {
  211456. }
  211457. void scanForDevices()
  211458. {
  211459. hasScanned = true;
  211460. outputDeviceNames.clear();
  211461. inputDeviceNames.clear();
  211462. outputDeviceIds.clear();
  211463. inputDeviceIds.clear();
  211464. ComSmartPtr <IMMDeviceEnumerator> enumerator;
  211465. if (! OK (enumerator.CoCreateInstance (__uuidof (MMDeviceEnumerator), CLSCTX_INPROC_SERVER)))
  211466. return;
  211467. const String defaultRenderer = getDefaultEndpoint (enumerator, false);
  211468. const String defaultCapture = getDefaultEndpoint (enumerator, true);
  211469. ComSmartPtr <IMMDeviceCollection> deviceCollection;
  211470. UINT32 numDevices = 0;
  211471. if (! (OK (enumerator->EnumAudioEndpoints (eAll, DEVICE_STATE_ACTIVE, &deviceCollection))
  211472. && OK (deviceCollection->GetCount (&numDevices))))
  211473. return;
  211474. for (UINT32 i = 0; i < numDevices; ++i)
  211475. {
  211476. ComSmartPtr <IMMDevice> device;
  211477. if (! OK (deviceCollection->Item (i, &device)))
  211478. continue;
  211479. const String deviceId (wasapi_getDeviceID (device));
  211480. DWORD state = 0;
  211481. if (! OK (device->GetState (&state)))
  211482. continue;
  211483. if (state != DEVICE_STATE_ACTIVE)
  211484. continue;
  211485. String name;
  211486. {
  211487. ComSmartPtr <IPropertyStore> properties;
  211488. if (! OK (device->OpenPropertyStore (STGM_READ, &properties)))
  211489. continue;
  211490. PROPVARIANT value;
  211491. PropVariantInit (&value);
  211492. if (OK (properties->GetValue (PKEY_Device_FriendlyName, &value)))
  211493. name = value.pwszVal;
  211494. PropVariantClear (&value);
  211495. }
  211496. const EDataFlow flow = wasapi_getDataFlow (device);
  211497. if (flow == eRender)
  211498. {
  211499. const int index = (deviceId == defaultRenderer) ? 0 : -1;
  211500. outputDeviceIds.insert (index, deviceId);
  211501. outputDeviceNames.insert (index, name);
  211502. }
  211503. else if (flow == eCapture)
  211504. {
  211505. const int index = (deviceId == defaultCapture) ? 0 : -1;
  211506. inputDeviceIds.insert (index, deviceId);
  211507. inputDeviceNames.insert (index, name);
  211508. }
  211509. }
  211510. }
  211511. const StringArray getDeviceNames (const bool wantInputNames) const
  211512. {
  211513. jassert (hasScanned); // need to call scanForDevices() before doing this
  211514. return wantInputNames ? inputDeviceNames
  211515. : outputDeviceNames;
  211516. }
  211517. int getDefaultDeviceIndex (const bool /*forInput*/) const
  211518. {
  211519. jassert (hasScanned); // need to call scanForDevices() before doing this
  211520. return 0;
  211521. }
  211522. int getIndexOfDevice (AudioIODevice* device, const bool asInput) const
  211523. {
  211524. jassert (hasScanned); // need to call scanForDevices() before doing this
  211525. WASAPIAudioIODevice* const d = dynamic_cast <WASAPIAudioIODevice*> (device);
  211526. return d == 0 ? -1 : (asInput ? inputDeviceIds.indexOf (d->inputDeviceId)
  211527. : outputDeviceIds.indexOf (d->outputDeviceId));
  211528. }
  211529. bool hasSeparateInputsAndOutputs() const { return true; }
  211530. AudioIODevice* createDevice (const String& outputDeviceName,
  211531. const String& inputDeviceName)
  211532. {
  211533. jassert (hasScanned); // need to call scanForDevices() before doing this
  211534. WASAPIAudioIODevice* d = 0;
  211535. const int outputIndex = outputDeviceNames.indexOf (outputDeviceName);
  211536. const int inputIndex = inputDeviceNames.indexOf (inputDeviceName);
  211537. if (outputIndex >= 0 || inputIndex >= 0)
  211538. {
  211539. d = new WASAPIAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  211540. : inputDeviceName,
  211541. outputDeviceIds [outputIndex],
  211542. inputDeviceIds [inputIndex]);
  211543. if (! d->initialise())
  211544. deleteAndZero (d);
  211545. }
  211546. return d;
  211547. }
  211548. juce_UseDebuggingNewOperator
  211549. StringArray outputDeviceNames, outputDeviceIds;
  211550. StringArray inputDeviceNames, inputDeviceIds;
  211551. private:
  211552. bool hasScanned;
  211553. static const String getDefaultEndpoint (IMMDeviceEnumerator* const enumerator, const bool forCapture)
  211554. {
  211555. String s;
  211556. IMMDevice* dev = 0;
  211557. if (OK (enumerator->GetDefaultAudioEndpoint (forCapture ? eCapture : eRender,
  211558. eMultimedia, &dev)))
  211559. {
  211560. WCHAR* deviceId = 0;
  211561. if (OK (dev->GetId (&deviceId)))
  211562. {
  211563. s = String (deviceId);
  211564. CoTaskMemFree (deviceId);
  211565. }
  211566. dev->Release();
  211567. }
  211568. return s;
  211569. }
  211570. WASAPIAudioIODeviceType (const WASAPIAudioIODeviceType&);
  211571. const WASAPIAudioIODeviceType& operator= (const WASAPIAudioIODeviceType&);
  211572. };
  211573. AudioIODeviceType* juce_createAudioIODeviceType_WASAPI()
  211574. {
  211575. return new WASAPIAudioIODeviceType();
  211576. }
  211577. #undef logFailure
  211578. #undef OK
  211579. #endif
  211580. /********* End of inlined file: juce_win32_WASAPI.cpp *********/
  211581. /********* Start of inlined file: juce_win32_CameraDevice.cpp *********/
  211582. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  211583. // compiled on its own).
  211584. #if JUCE_INCLUDED_FILE && JUCE_USE_CAMERA
  211585. class DShowCameraDeviceInteral : public ChangeBroadcaster
  211586. {
  211587. public:
  211588. DShowCameraDeviceInteral (CameraDevice* const owner_,
  211589. const ComSmartPtr <ICaptureGraphBuilder2>& captureGraphBuilder_,
  211590. const ComSmartPtr <IBaseFilter>& filter_,
  211591. int minWidth, int minHeight,
  211592. int maxWidth, int maxHeight)
  211593. : owner (owner_),
  211594. captureGraphBuilder (captureGraphBuilder_),
  211595. filter (filter_),
  211596. ok (false),
  211597. imageNeedsFlipping (false),
  211598. width (0),
  211599. height (0),
  211600. activeUsers (0),
  211601. recordNextFrameTime (false)
  211602. {
  211603. HRESULT hr = graphBuilder.CoCreateInstance (CLSID_FilterGraph, CLSCTX_INPROC);
  211604. if (FAILED (hr))
  211605. return;
  211606. hr = captureGraphBuilder->SetFiltergraph (graphBuilder);
  211607. if (FAILED (hr))
  211608. return;
  211609. hr = graphBuilder->QueryInterface (IID_IMediaControl, (void**) &mediaControl);
  211610. if (FAILED (hr))
  211611. return;
  211612. {
  211613. ComSmartPtr <IAMStreamConfig> streamConfig;
  211614. hr = captureGraphBuilder->FindInterface (&PIN_CATEGORY_CAPTURE,
  211615. 0,
  211616. filter,
  211617. IID_IAMStreamConfig,
  211618. (void**) &streamConfig);
  211619. if (streamConfig != 0)
  211620. {
  211621. getVideoSizes (streamConfig);
  211622. if (! selectVideoSize (streamConfig, minWidth, minHeight, maxWidth, maxHeight))
  211623. return;
  211624. }
  211625. }
  211626. hr = graphBuilder->AddFilter (filter, _T("Video Capture"));
  211627. if (FAILED (hr))
  211628. return;
  211629. hr = smartTee.CoCreateInstance (CLSID_SmartTee, CLSCTX_INPROC_SERVER);
  211630. if (FAILED (hr))
  211631. return;
  211632. hr = graphBuilder->AddFilter (smartTee, _T("Smart Tee"));
  211633. if (FAILED (hr))
  211634. return;
  211635. if (! connectFilters (filter, smartTee))
  211636. return;
  211637. ComSmartPtr <IBaseFilter> sampleGrabberBase;
  211638. hr = sampleGrabberBase.CoCreateInstance (CLSID_SampleGrabber, CLSCTX_INPROC_SERVER);
  211639. if (FAILED (hr))
  211640. return;
  211641. hr = sampleGrabberBase->QueryInterface (IID_ISampleGrabber, (void**) &sampleGrabber);
  211642. if (FAILED (hr))
  211643. return;
  211644. AM_MEDIA_TYPE mt;
  211645. zerostruct (mt);
  211646. mt.majortype = MEDIATYPE_Video;
  211647. mt.subtype = MEDIASUBTYPE_RGB24;
  211648. mt.formattype = FORMAT_VideoInfo;
  211649. sampleGrabber->SetMediaType (&mt);
  211650. callback = new GrabberCallback (*this);
  211651. sampleGrabber->SetCallback (callback, 1);
  211652. hr = graphBuilder->AddFilter (sampleGrabberBase, _T("Sample Grabber"));
  211653. if (FAILED (hr))
  211654. return;
  211655. ComSmartPtr <IPin> grabberInputPin;
  211656. if (! (getPin (smartTee, PINDIR_OUTPUT, &smartTeeCaptureOutputPin, "capture")
  211657. && getPin (smartTee, PINDIR_OUTPUT, &smartTeePreviewOutputPin, "preview")
  211658. && getPin (sampleGrabberBase, PINDIR_INPUT, &grabberInputPin)))
  211659. return;
  211660. hr = graphBuilder->Connect (smartTeePreviewOutputPin, grabberInputPin);
  211661. if (FAILED (hr))
  211662. return;
  211663. zerostruct (mt);
  211664. hr = sampleGrabber->GetConnectedMediaType (&mt);
  211665. VIDEOINFOHEADER* pVih = (VIDEOINFOHEADER*) (mt.pbFormat);
  211666. width = pVih->bmiHeader.biWidth;
  211667. height = pVih->bmiHeader.biHeight;
  211668. ComSmartPtr <IBaseFilter> nullFilter;
  211669. hr = nullFilter.CoCreateInstance (CLSID_NullRenderer, CLSCTX_INPROC_SERVER);
  211670. hr = graphBuilder->AddFilter (nullFilter, _T("Null Renderer"));
  211671. if (connectFilters (sampleGrabberBase, nullFilter)
  211672. && addGraphToRot())
  211673. {
  211674. activeImage = new Image (Image::RGB, width, height, true);
  211675. loadingImage = new Image (Image::RGB, width, height, true);
  211676. ok = true;
  211677. }
  211678. }
  211679. ~DShowCameraDeviceInteral()
  211680. {
  211681. mediaControl->Stop();
  211682. removeGraphFromRot();
  211683. for (int i = viewerComps.size(); --i >= 0;)
  211684. ((DShowCaptureViewerComp*) viewerComps.getUnchecked(i))->ownerDeleted();
  211685. callback = 0;
  211686. graphBuilder = 0;
  211687. sampleGrabber = 0;
  211688. mediaControl = 0;
  211689. filter = 0;
  211690. captureGraphBuilder = 0;
  211691. smartTee = 0;
  211692. smartTeePreviewOutputPin = 0;
  211693. smartTeeCaptureOutputPin = 0;
  211694. mux = 0;
  211695. fileWriter = 0;
  211696. delete activeImage;
  211697. delete loadingImage;
  211698. }
  211699. void addUser()
  211700. {
  211701. if (ok && activeUsers++ == 0)
  211702. mediaControl->Run();
  211703. }
  211704. void removeUser()
  211705. {
  211706. if (ok && --activeUsers == 0)
  211707. mediaControl->Stop();
  211708. }
  211709. void handleFrame (double /*time*/, BYTE* buffer, long /*bufferSize*/)
  211710. {
  211711. if (recordNextFrameTime)
  211712. {
  211713. firstRecordedTime = Time::getCurrentTime();
  211714. recordNextFrameTime = false;
  211715. }
  211716. imageSwapLock.enter();
  211717. int ls, ps;
  211718. const int lineStride = width * 3;
  211719. uint8* const dest = loadingImage->lockPixelDataReadWrite (0, 0, width, height, ls, ps);
  211720. for (int i = 0; i < height; ++i)
  211721. memcpy (dest + ls * ((height - 1) - i),
  211722. buffer + lineStride * i,
  211723. lineStride);
  211724. loadingImage->releasePixelDataReadWrite (dest);
  211725. imageNeedsFlipping = true;
  211726. imageSwapLock.exit();
  211727. callListeners (*loadingImage);
  211728. sendChangeMessage (this);
  211729. }
  211730. void drawCurrentImage (Graphics& g, int x, int y, int w, int h)
  211731. {
  211732. if (imageNeedsFlipping)
  211733. {
  211734. imageSwapLock.enter();
  211735. swapVariables (loadingImage, activeImage);
  211736. imageNeedsFlipping = false;
  211737. imageSwapLock.exit();
  211738. }
  211739. RectanglePlacement rp (RectanglePlacement::centred);
  211740. double dx = 0, dy = 0, dw = width, dh = height;
  211741. rp.applyTo (dx, dy, dw, dh, x, y, w, h);
  211742. const int rx = roundDoubleToInt (dx), ry = roundDoubleToInt (dy);
  211743. const int rw = roundDoubleToInt (dw), rh = roundDoubleToInt (dh);
  211744. g.saveState();
  211745. g.excludeClipRegion (rx, ry, rw, rh);
  211746. g.fillAll (Colours::black);
  211747. g.restoreState();
  211748. g.drawImage (activeImage, rx, ry, rw, rh, 0, 0, width, height);
  211749. }
  211750. bool createFileCaptureFilter (const File& file)
  211751. {
  211752. removeFileCaptureFilter();
  211753. file.deleteFile();
  211754. mediaControl->Stop();
  211755. firstRecordedTime = Time();
  211756. recordNextFrameTime = true;
  211757. HRESULT hr = mux.CoCreateInstance (CLSID_AviDest, CLSCTX_INPROC_SERVER);
  211758. if (SUCCEEDED (hr))
  211759. {
  211760. hr = graphBuilder->AddFilter (mux, _T("AVI Mux"));
  211761. if (SUCCEEDED (hr))
  211762. {
  211763. fileWriter.CoCreateInstance (CLSID_FileWriter, CLSCTX_INPROC_SERVER);
  211764. if (SUCCEEDED (hr))
  211765. {
  211766. ComSmartPtr <IFileSinkFilter> fileSink;
  211767. hr = fileWriter->QueryInterface (IID_IFileSinkFilter, (void**) &fileSink);
  211768. if (SUCCEEDED (hr))
  211769. {
  211770. AM_MEDIA_TYPE mt;
  211771. zerostruct (mt);
  211772. mt.majortype = MEDIATYPE_Stream;
  211773. mt.subtype = MEDIASUBTYPE_Avi;
  211774. mt.formattype = FORMAT_VideoInfo;
  211775. hr = fileSink->SetFileName (file.getFullPathName(), &mt);
  211776. if (SUCCEEDED (hr))
  211777. {
  211778. hr = graphBuilder->AddFilter (fileWriter, _T("File Writer"));
  211779. if (SUCCEEDED (hr))
  211780. {
  211781. ComSmartPtr <IPin> muxInputPin, muxOutputPin, writerInput;
  211782. if (getPin (mux, PINDIR_INPUT, &muxInputPin)
  211783. && getPin (mux, PINDIR_OUTPUT, &muxOutputPin)
  211784. && getPin (fileWriter, PINDIR_INPUT, &writerInput))
  211785. {
  211786. hr = graphBuilder->Connect (smartTeeCaptureOutputPin, muxInputPin);
  211787. if (SUCCEEDED (hr))
  211788. {
  211789. hr = graphBuilder->Connect (muxOutputPin, writerInput);
  211790. if (SUCCEEDED (hr))
  211791. {
  211792. if (ok && activeUsers > 0)
  211793. mediaControl->Run();
  211794. return true;
  211795. }
  211796. }
  211797. }
  211798. }
  211799. }
  211800. }
  211801. }
  211802. }
  211803. }
  211804. removeFileCaptureFilter();
  211805. if (ok && activeUsers > 0)
  211806. mediaControl->Run();
  211807. return false;
  211808. }
  211809. void removeFileCaptureFilter()
  211810. {
  211811. mediaControl->Stop();
  211812. if (mux != 0)
  211813. {
  211814. graphBuilder->RemoveFilter (mux);
  211815. mux = 0;
  211816. }
  211817. if (fileWriter != 0)
  211818. {
  211819. graphBuilder->RemoveFilter (fileWriter);
  211820. fileWriter = 0;
  211821. }
  211822. if (ok && activeUsers > 0)
  211823. mediaControl->Run();
  211824. }
  211825. void addListener (CameraImageListener* listenerToAdd)
  211826. {
  211827. const ScopedLock sl (listenerLock);
  211828. if (listeners.size() == 0)
  211829. addUser();
  211830. listeners.addIfNotAlreadyThere (listenerToAdd);
  211831. }
  211832. void removeListener (CameraImageListener* listenerToRemove)
  211833. {
  211834. const ScopedLock sl (listenerLock);
  211835. listeners.removeValue (listenerToRemove);
  211836. if (listeners.size() == 0)
  211837. removeUser();
  211838. }
  211839. void callListeners (Image& image)
  211840. {
  211841. const ScopedLock sl (listenerLock);
  211842. for (int i = listeners.size(); --i >= 0;)
  211843. {
  211844. CameraImageListener* l = (CameraImageListener*) listeners[i];
  211845. if (l != 0)
  211846. l->imageReceived (image);
  211847. }
  211848. }
  211849. class DShowCaptureViewerComp : public Component,
  211850. public ChangeListener
  211851. {
  211852. public:
  211853. DShowCaptureViewerComp (DShowCameraDeviceInteral* const owner_)
  211854. : owner (owner_)
  211855. {
  211856. setOpaque (true);
  211857. owner->addChangeListener (this);
  211858. owner->addUser();
  211859. owner->viewerComps.add (this);
  211860. setSize (owner_->width, owner_->height);
  211861. }
  211862. ~DShowCaptureViewerComp()
  211863. {
  211864. if (owner != 0)
  211865. {
  211866. owner->viewerComps.removeValue (this);
  211867. owner->removeUser();
  211868. owner->removeChangeListener (this);
  211869. }
  211870. }
  211871. void ownerDeleted()
  211872. {
  211873. owner = 0;
  211874. }
  211875. void paint (Graphics& g)
  211876. {
  211877. g.setColour (Colours::black);
  211878. g.setImageResamplingQuality (Graphics::lowResamplingQuality);
  211879. if (owner != 0)
  211880. owner->drawCurrentImage (g, 0, 0, getWidth(), getHeight());
  211881. else
  211882. g.fillAll (Colours::black);
  211883. }
  211884. void changeListenerCallback (void*)
  211885. {
  211886. repaint();
  211887. }
  211888. private:
  211889. DShowCameraDeviceInteral* owner;
  211890. };
  211891. bool ok;
  211892. int width, height;
  211893. Time firstRecordedTime;
  211894. VoidArray viewerComps;
  211895. private:
  211896. CameraDevice* const owner;
  211897. ComSmartPtr <ICaptureGraphBuilder2> captureGraphBuilder;
  211898. ComSmartPtr <IBaseFilter> filter;
  211899. ComSmartPtr <IBaseFilter> smartTee;
  211900. ComSmartPtr <IGraphBuilder> graphBuilder;
  211901. ComSmartPtr <ISampleGrabber> sampleGrabber;
  211902. ComSmartPtr <IMediaControl> mediaControl;
  211903. ComSmartPtr <IPin> smartTeePreviewOutputPin;
  211904. ComSmartPtr <IPin> smartTeeCaptureOutputPin;
  211905. ComSmartPtr <IBaseFilter> mux, fileWriter;
  211906. int activeUsers;
  211907. Array <int> widths, heights;
  211908. DWORD graphRegistrationID;
  211909. CriticalSection imageSwapLock;
  211910. bool imageNeedsFlipping;
  211911. Image* loadingImage;
  211912. Image* activeImage;
  211913. bool recordNextFrameTime;
  211914. void getVideoSizes (IAMStreamConfig* const streamConfig)
  211915. {
  211916. widths.clear();
  211917. heights.clear();
  211918. int count = 0, size = 0;
  211919. streamConfig->GetNumberOfCapabilities (&count, &size);
  211920. if (size == sizeof (VIDEO_STREAM_CONFIG_CAPS))
  211921. {
  211922. for (int i = 0; i < count; ++i)
  211923. {
  211924. VIDEO_STREAM_CONFIG_CAPS scc;
  211925. AM_MEDIA_TYPE* config;
  211926. HRESULT hr = streamConfig->GetStreamCaps (i, &config, (BYTE*) &scc);
  211927. if (SUCCEEDED (hr))
  211928. {
  211929. const int w = scc.InputSize.cx;
  211930. const int h = scc.InputSize.cy;
  211931. bool duplicate = false;
  211932. for (int j = widths.size(); --j >= 0;)
  211933. {
  211934. if (w == widths.getUnchecked (j) && h == heights.getUnchecked (j))
  211935. {
  211936. duplicate = true;
  211937. break;
  211938. }
  211939. }
  211940. if (! duplicate)
  211941. {
  211942. DBG ("Camera capture size: " + String (w) + ", " + String (h));
  211943. widths.add (w);
  211944. heights.add (h);
  211945. }
  211946. deleteMediaType (config);
  211947. }
  211948. }
  211949. }
  211950. }
  211951. bool selectVideoSize (IAMStreamConfig* const streamConfig,
  211952. const int minWidth, const int minHeight,
  211953. const int maxWidth, const int maxHeight)
  211954. {
  211955. int count = 0, size = 0;
  211956. streamConfig->GetNumberOfCapabilities (&count, &size);
  211957. if (size == sizeof (VIDEO_STREAM_CONFIG_CAPS))
  211958. {
  211959. for (int i = 0; i < count; ++i)
  211960. {
  211961. VIDEO_STREAM_CONFIG_CAPS scc;
  211962. AM_MEDIA_TYPE* config;
  211963. HRESULT hr = streamConfig->GetStreamCaps (i, &config, (BYTE*) &scc);
  211964. if (SUCCEEDED (hr))
  211965. {
  211966. if (scc.InputSize.cx >= minWidth
  211967. && scc.InputSize.cy >= minHeight
  211968. && scc.InputSize.cx <= maxWidth
  211969. && scc.InputSize.cy <= maxHeight)
  211970. {
  211971. hr = streamConfig->SetFormat (config);
  211972. deleteMediaType (config);
  211973. return SUCCEEDED (hr);
  211974. }
  211975. deleteMediaType (config);
  211976. }
  211977. }
  211978. }
  211979. return false;
  211980. }
  211981. static bool getPin (IBaseFilter* filter, const PIN_DIRECTION wantedDirection, IPin** result, const char* pinName = 0)
  211982. {
  211983. ComSmartPtr <IEnumPins> enumerator;
  211984. ComSmartPtr <IPin> pin;
  211985. filter->EnumPins (&enumerator);
  211986. while (enumerator->Next (1, &pin, 0) == S_OK)
  211987. {
  211988. PIN_DIRECTION dir;
  211989. pin->QueryDirection (&dir);
  211990. if (wantedDirection == dir)
  211991. {
  211992. PIN_INFO info;
  211993. zerostruct (info);
  211994. pin->QueryPinInfo (&info);
  211995. if (pinName == 0 || String (pinName).equalsIgnoreCase (String (info.achName)))
  211996. {
  211997. pin.p->AddRef();
  211998. *result = pin;
  211999. return true;
  212000. }
  212001. }
  212002. }
  212003. return false;
  212004. }
  212005. bool connectFilters (IBaseFilter* const first, IBaseFilter* const second) const
  212006. {
  212007. ComSmartPtr <IPin> in, out;
  212008. return getPin (first, PINDIR_OUTPUT, &out)
  212009. && getPin (second, PINDIR_INPUT, &in)
  212010. && SUCCEEDED (graphBuilder->Connect (out, in));
  212011. }
  212012. bool addGraphToRot()
  212013. {
  212014. ComSmartPtr <IRunningObjectTable> rot;
  212015. if (FAILED (GetRunningObjectTable (0, &rot)))
  212016. return false;
  212017. ComSmartPtr <IMoniker> moniker;
  212018. WCHAR buffer[128];
  212019. HRESULT hr = CreateItemMoniker (_T("!"), buffer, &moniker);
  212020. if (FAILED (hr))
  212021. return false;
  212022. graphRegistrationID = 0;
  212023. return SUCCEEDED (rot->Register (0, graphBuilder, moniker, &graphRegistrationID));
  212024. }
  212025. void removeGraphFromRot()
  212026. {
  212027. ComSmartPtr <IRunningObjectTable> rot;
  212028. if (SUCCEEDED (GetRunningObjectTable (0, &rot)))
  212029. rot->Revoke (graphRegistrationID);
  212030. }
  212031. static void deleteMediaType (AM_MEDIA_TYPE* const pmt)
  212032. {
  212033. if (pmt->cbFormat != 0)
  212034. CoTaskMemFree ((PVOID) pmt->pbFormat);
  212035. if (pmt->pUnk != 0)
  212036. pmt->pUnk->Release();
  212037. CoTaskMemFree (pmt);
  212038. }
  212039. class GrabberCallback : public ISampleGrabberCB
  212040. {
  212041. public:
  212042. GrabberCallback (DShowCameraDeviceInteral& owner_)
  212043. : owner (owner_)
  212044. {
  212045. }
  212046. HRESULT __stdcall QueryInterface (REFIID id, void** result)
  212047. {
  212048. if (id == IID_IUnknown)
  212049. *result = dynamic_cast <IUnknown*> (this);
  212050. else if (id == IID_ISampleGrabberCB)
  212051. *result = dynamic_cast <ISampleGrabberCB*> (this);
  212052. else
  212053. {
  212054. *result = 0;
  212055. return E_NOINTERFACE;
  212056. }
  212057. AddRef();
  212058. return S_OK;
  212059. }
  212060. ULONG __stdcall AddRef() { return ++refCount; }
  212061. ULONG __stdcall Release() { const int r = --refCount; if (r == 0) delete this; return r; }
  212062. STDMETHODIMP SampleCB (double /*SampleTime*/, IMediaSample* /*pSample*/)
  212063. {
  212064. return E_FAIL;
  212065. }
  212066. STDMETHODIMP BufferCB (double time, BYTE* buffer, long bufferSize)
  212067. {
  212068. owner.handleFrame (time, buffer, bufferSize);
  212069. return S_OK;
  212070. }
  212071. private:
  212072. int refCount;
  212073. DShowCameraDeviceInteral& owner;
  212074. GrabberCallback (const GrabberCallback&);
  212075. const GrabberCallback& operator= (const GrabberCallback&);
  212076. };
  212077. ComSmartPtr <GrabberCallback> callback;
  212078. VoidArray listeners;
  212079. CriticalSection listenerLock;
  212080. DShowCameraDeviceInteral (const DShowCameraDeviceInteral&);
  212081. const DShowCameraDeviceInteral& operator= (const DShowCameraDeviceInteral&);
  212082. };
  212083. CameraDevice::CameraDevice (const String& name_, int /*index*/)
  212084. : name (name_)
  212085. {
  212086. isRecording = false;
  212087. }
  212088. CameraDevice::~CameraDevice()
  212089. {
  212090. stopRecording();
  212091. delete (DShowCameraDeviceInteral*) internal;
  212092. internal = 0;
  212093. }
  212094. Component* CameraDevice::createViewerComponent()
  212095. {
  212096. return new DShowCameraDeviceInteral::DShowCaptureViewerComp ((DShowCameraDeviceInteral*) internal);
  212097. }
  212098. const String CameraDevice::getFileExtension()
  212099. {
  212100. return ".avi";
  212101. }
  212102. void CameraDevice::startRecordingToFile (const File& file)
  212103. {
  212104. stopRecording();
  212105. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  212106. d->addUser();
  212107. isRecording = d->createFileCaptureFilter (file);
  212108. }
  212109. const Time CameraDevice::getTimeOfFirstRecordedFrame() const
  212110. {
  212111. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  212112. return d->firstRecordedTime;
  212113. }
  212114. void CameraDevice::stopRecording()
  212115. {
  212116. if (isRecording)
  212117. {
  212118. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  212119. d->removeFileCaptureFilter();
  212120. d->removeUser();
  212121. isRecording = false;
  212122. }
  212123. }
  212124. void CameraDevice::addListener (CameraImageListener* listenerToAdd)
  212125. {
  212126. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  212127. if (listenerToAdd != 0)
  212128. d->addListener (listenerToAdd);
  212129. }
  212130. void CameraDevice::removeListener (CameraImageListener* listenerToRemove)
  212131. {
  212132. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  212133. if (listenerToRemove != 0)
  212134. d->removeListener (listenerToRemove);
  212135. }
  212136. static ComSmartPtr <IBaseFilter> enumerateCameras (StringArray* const names,
  212137. const int deviceIndexToOpen,
  212138. String& name)
  212139. {
  212140. int index = 0;
  212141. ComSmartPtr <IBaseFilter> result;
  212142. ComSmartPtr <ICreateDevEnum> pDevEnum;
  212143. HRESULT hr = pDevEnum.CoCreateInstance (CLSID_SystemDeviceEnum, CLSCTX_INPROC);
  212144. if (SUCCEEDED (hr))
  212145. {
  212146. ComSmartPtr <IEnumMoniker> enumerator;
  212147. hr = pDevEnum->CreateClassEnumerator (CLSID_VideoInputDeviceCategory, &enumerator, 0);
  212148. if (SUCCEEDED (hr) && enumerator != 0)
  212149. {
  212150. ComSmartPtr <IBaseFilter> captureFilter;
  212151. ComSmartPtr <IMoniker> moniker;
  212152. ULONG fetched;
  212153. while (enumerator->Next (1, &moniker, &fetched) == S_OK)
  212154. {
  212155. hr = moniker->BindToObject (0, 0, IID_IBaseFilter, (void**) &captureFilter);
  212156. if (SUCCEEDED (hr))
  212157. {
  212158. ComSmartPtr <IPropertyBag> propertyBag;
  212159. hr = moniker->BindToStorage (0, 0, IID_IPropertyBag, (void**) &propertyBag);
  212160. if (SUCCEEDED (hr))
  212161. {
  212162. VARIANT var;
  212163. var.vt = VT_BSTR;
  212164. hr = propertyBag->Read (_T("FriendlyName"), &var, 0);
  212165. propertyBag = 0;
  212166. if (SUCCEEDED (hr))
  212167. {
  212168. if (names != 0)
  212169. names->add (var.bstrVal);
  212170. if (index == deviceIndexToOpen)
  212171. {
  212172. name = var.bstrVal;
  212173. result = captureFilter;
  212174. captureFilter = 0;
  212175. break;
  212176. }
  212177. ++index;
  212178. }
  212179. moniker = 0;
  212180. }
  212181. captureFilter = 0;
  212182. }
  212183. }
  212184. }
  212185. }
  212186. return result;
  212187. }
  212188. const StringArray CameraDevice::getAvailableDevices()
  212189. {
  212190. StringArray devs;
  212191. String dummy;
  212192. enumerateCameras (&devs, -1, dummy);
  212193. return devs;
  212194. }
  212195. CameraDevice* CameraDevice::openDevice (int index,
  212196. int minWidth, int minHeight,
  212197. int maxWidth, int maxHeight)
  212198. {
  212199. ComSmartPtr <ICaptureGraphBuilder2> captureGraphBuilder;
  212200. HRESULT hr = captureGraphBuilder.CoCreateInstance (CLSID_CaptureGraphBuilder2, CLSCTX_INPROC);
  212201. if (SUCCEEDED (hr))
  212202. {
  212203. String name;
  212204. const ComSmartPtr <IBaseFilter> filter (enumerateCameras (0, index, name));
  212205. if (filter != 0)
  212206. {
  212207. CameraDevice* const cam = new CameraDevice (name, index);
  212208. DShowCameraDeviceInteral* const intern
  212209. = new DShowCameraDeviceInteral (cam, captureGraphBuilder, filter,
  212210. minWidth, minHeight, maxWidth, maxHeight);
  212211. cam->internal = intern;
  212212. if (intern->ok)
  212213. return cam;
  212214. else
  212215. delete cam;
  212216. }
  212217. }
  212218. return 0;
  212219. }
  212220. #endif
  212221. /********* End of inlined file: juce_win32_CameraDevice.cpp *********/
  212222. #endif
  212223. // Auto-link the other win32 libs that are needed by library calls..
  212224. #if (JUCE_AMALGAMATED_TEMPLATE || defined (JUCE_DLL_BUILD)) && JUCE_MSVC && ! DONT_AUTOLINK_TO_WIN32_LIBRARIES
  212225. /********* Start of inlined file: juce_win32_AutoLinkLibraries.h *********/
  212226. // Auto-links to various win32 libs that are needed by library calls..
  212227. #pragma comment(lib, "kernel32.lib")
  212228. #pragma comment(lib, "user32.lib")
  212229. #pragma comment(lib, "shell32.lib")
  212230. #pragma comment(lib, "gdi32.lib")
  212231. #pragma comment(lib, "vfw32.lib")
  212232. #pragma comment(lib, "comdlg32.lib")
  212233. #pragma comment(lib, "winmm.lib")
  212234. #pragma comment(lib, "wininet.lib")
  212235. #pragma comment(lib, "ole32.lib")
  212236. #pragma comment(lib, "advapi32.lib")
  212237. #pragma comment(lib, "ws2_32.lib")
  212238. #pragma comment(lib, "comsupp.lib")
  212239. #pragma comment(lib, "version.lib")
  212240. #if JUCE_OPENGL
  212241. #pragma comment(lib, "OpenGL32.Lib")
  212242. #pragma comment(lib, "GlU32.Lib")
  212243. #endif
  212244. #if JUCE_QUICKTIME
  212245. #pragma comment (lib, "QTMLClient.lib")
  212246. #endif
  212247. #if JUCE_USE_CAMERA
  212248. #pragma comment (lib, "Strmiids.lib")
  212249. #endif
  212250. /********* End of inlined file: juce_win32_AutoLinkLibraries.h *********/
  212251. #endif
  212252. END_JUCE_NAMESPACE
  212253. /********* End of inlined file: juce_win32_NativeCode.cpp *********/
  212254. #endif
  212255. #if JUCE_LINUX
  212256. /********* Start of inlined file: juce_linux_NativeCode.cpp *********/
  212257. /*
  212258. This file wraps together all the mac-specific code, so that
  212259. we can include all the native headers just once, and compile all our
  212260. platform-specific stuff in one big lump, keeping it out of the way of
  212261. the rest of the codebase.
  212262. */
  212263. BEGIN_JUCE_NAMESPACE
  212264. /* Remove this macro if you're having problems compiling the cpu affinity
  212265. calls (the API for these has changed about quite a bit in various Linux
  212266. versions, and a lot of distros seem to ship with obsolete versions)
  212267. */
  212268. #if defined (CPU_ISSET) && ! defined (SUPPORT_AFFINITIES)
  212269. #define SUPPORT_AFFINITIES 1
  212270. #endif
  212271. #define JUCE_INCLUDED_FILE 1
  212272. // Now include the actual code files..
  212273. /********* Start of inlined file: juce_posix_SharedCode.h *********/
  212274. /*
  212275. This file contains posix routines that are common to both the Linux and Mac builds.
  212276. It gets included directly in the cpp files for these platforms.
  212277. */
  212278. CriticalSection::CriticalSection() throw()
  212279. {
  212280. pthread_mutexattr_t atts;
  212281. pthread_mutexattr_init (&atts);
  212282. pthread_mutexattr_settype (&atts, PTHREAD_MUTEX_RECURSIVE);
  212283. pthread_mutex_init (&internal, &atts);
  212284. }
  212285. CriticalSection::~CriticalSection() throw()
  212286. {
  212287. pthread_mutex_destroy (&internal);
  212288. }
  212289. void CriticalSection::enter() const throw()
  212290. {
  212291. pthread_mutex_lock (&internal);
  212292. }
  212293. bool CriticalSection::tryEnter() const throw()
  212294. {
  212295. return pthread_mutex_trylock (&internal) == 0;
  212296. }
  212297. void CriticalSection::exit() const throw()
  212298. {
  212299. pthread_mutex_unlock (&internal);
  212300. }
  212301. struct EventStruct
  212302. {
  212303. pthread_cond_t condition;
  212304. pthread_mutex_t mutex;
  212305. bool triggered;
  212306. };
  212307. WaitableEvent::WaitableEvent() throw()
  212308. {
  212309. EventStruct* const es = new EventStruct();
  212310. es->triggered = false;
  212311. pthread_cond_init (&es->condition, 0);
  212312. pthread_mutex_init (&es->mutex, 0);
  212313. internal = es;
  212314. }
  212315. WaitableEvent::~WaitableEvent() throw()
  212316. {
  212317. EventStruct* const es = (EventStruct*) internal;
  212318. pthread_cond_destroy (&es->condition);
  212319. pthread_mutex_destroy (&es->mutex);
  212320. delete es;
  212321. }
  212322. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  212323. {
  212324. EventStruct* const es = (EventStruct*) internal;
  212325. bool ok = true;
  212326. pthread_mutex_lock (&es->mutex);
  212327. if (timeOutMillisecs < 0)
  212328. {
  212329. while (! es->triggered)
  212330. pthread_cond_wait (&es->condition, &es->mutex);
  212331. }
  212332. else
  212333. {
  212334. while (! es->triggered)
  212335. {
  212336. struct timeval t;
  212337. gettimeofday (&t, 0);
  212338. struct timespec time;
  212339. time.tv_sec = t.tv_sec + (timeOutMillisecs / 1000);
  212340. time.tv_nsec = (t.tv_usec + ((timeOutMillisecs % 1000) * 1000)) * 1000;
  212341. if (time.tv_nsec >= 1000000000)
  212342. {
  212343. time.tv_nsec -= 1000000000;
  212344. time.tv_sec++;
  212345. }
  212346. if (pthread_cond_timedwait (&es->condition, &es->mutex, &time) == ETIMEDOUT)
  212347. {
  212348. ok = false;
  212349. break;
  212350. }
  212351. }
  212352. }
  212353. es->triggered = false;
  212354. pthread_mutex_unlock (&es->mutex);
  212355. return ok;
  212356. }
  212357. void WaitableEvent::signal() const throw()
  212358. {
  212359. EventStruct* const es = (EventStruct*) internal;
  212360. pthread_mutex_lock (&es->mutex);
  212361. es->triggered = true;
  212362. pthread_cond_broadcast (&es->condition);
  212363. pthread_mutex_unlock (&es->mutex);
  212364. }
  212365. void WaitableEvent::reset() const throw()
  212366. {
  212367. EventStruct* const es = (EventStruct*) internal;
  212368. pthread_mutex_lock (&es->mutex);
  212369. es->triggered = false;
  212370. pthread_mutex_unlock (&es->mutex);
  212371. }
  212372. void JUCE_CALLTYPE Thread::sleep (int millisecs) throw()
  212373. {
  212374. struct timespec time;
  212375. time.tv_sec = millisecs / 1000;
  212376. time.tv_nsec = (millisecs % 1000) * 1000000;
  212377. nanosleep (&time, 0);
  212378. }
  212379. const tchar File::separator = T('/');
  212380. const tchar* File::separatorString = T("/");
  212381. bool juce_copyFile (const String& s, const String& d) throw();
  212382. static bool juce_stat (const String& fileName, struct stat& info) throw()
  212383. {
  212384. return fileName.isNotEmpty()
  212385. && (stat (fileName.toUTF8(), &info) == 0);
  212386. }
  212387. bool juce_isDirectory (const String& fileName) throw()
  212388. {
  212389. struct stat info;
  212390. return fileName.isEmpty()
  212391. || (juce_stat (fileName, info)
  212392. && ((info.st_mode & S_IFDIR) != 0));
  212393. }
  212394. bool juce_fileExists (const String& fileName, const bool dontCountDirectories) throw()
  212395. {
  212396. if (fileName.isEmpty())
  212397. return false;
  212398. const char* const fileNameUTF8 = fileName.toUTF8();
  212399. bool exists = access (fileNameUTF8, F_OK) == 0;
  212400. if (exists && dontCountDirectories)
  212401. {
  212402. struct stat info;
  212403. const int res = stat (fileNameUTF8, &info);
  212404. if (res == 0 && (info.st_mode & S_IFDIR) != 0)
  212405. exists = false;
  212406. }
  212407. return exists;
  212408. }
  212409. int64 juce_getFileSize (const String& fileName) throw()
  212410. {
  212411. struct stat info;
  212412. return juce_stat (fileName, info) ? info.st_size : 0;
  212413. }
  212414. bool juce_canWriteToFile (const String& fileName) throw()
  212415. {
  212416. return access (fileName.toUTF8(), W_OK) == 0;
  212417. }
  212418. bool juce_deleteFile (const String& fileName) throw()
  212419. {
  212420. if (juce_isDirectory (fileName))
  212421. return rmdir ((const char*) fileName.toUTF8()) == 0;
  212422. else
  212423. return remove ((const char*) fileName.toUTF8()) == 0;
  212424. }
  212425. bool juce_moveFile (const String& source, const String& dest) throw()
  212426. {
  212427. if (rename (source.toUTF8(), dest.toUTF8()) == 0)
  212428. return true;
  212429. if (juce_canWriteToFile (source)
  212430. && juce_copyFile (source, dest))
  212431. {
  212432. if (juce_deleteFile (source))
  212433. return true;
  212434. juce_deleteFile (dest);
  212435. }
  212436. return false;
  212437. }
  212438. void juce_createDirectory (const String& fileName) throw()
  212439. {
  212440. mkdir (fileName.toUTF8(), 0777);
  212441. }
  212442. void* juce_fileOpen (const String& fileName, bool forWriting) throw()
  212443. {
  212444. int flags = O_RDONLY;
  212445. if (forWriting)
  212446. {
  212447. if (juce_fileExists (fileName, false))
  212448. {
  212449. const int f = open ((const char*) fileName.toUTF8(), O_RDWR, 00644);
  212450. if (f != -1)
  212451. lseek (f, 0, SEEK_END);
  212452. return (void*) f;
  212453. }
  212454. else
  212455. {
  212456. flags = O_RDWR + O_CREAT;
  212457. }
  212458. }
  212459. return (void*) open ((const char*) fileName.toUTF8(), flags, 00644);
  212460. }
  212461. void juce_fileClose (void* handle) throw()
  212462. {
  212463. if (handle != 0)
  212464. close ((int) (pointer_sized_int) handle);
  212465. }
  212466. int juce_fileRead (void* handle, void* buffer, int size) throw()
  212467. {
  212468. if (handle != 0)
  212469. return read ((int) (pointer_sized_int) handle, buffer, size);
  212470. return 0;
  212471. }
  212472. int juce_fileWrite (void* handle, const void* buffer, int size) throw()
  212473. {
  212474. if (handle != 0)
  212475. return write ((int) (pointer_sized_int) handle, buffer, size);
  212476. return 0;
  212477. }
  212478. int64 juce_fileSetPosition (void* handle, int64 pos) throw()
  212479. {
  212480. if (handle != 0 && lseek ((int) (pointer_sized_int) handle, pos, SEEK_SET) == pos)
  212481. return pos;
  212482. return -1;
  212483. }
  212484. int64 juce_fileGetPosition (void* handle) throw()
  212485. {
  212486. if (handle != 0)
  212487. return lseek ((int) (pointer_sized_int) handle, 0, SEEK_CUR);
  212488. else
  212489. return -1;
  212490. }
  212491. void juce_fileFlush (void* handle) throw()
  212492. {
  212493. if (handle != 0)
  212494. fsync ((int) (pointer_sized_int) handle);
  212495. }
  212496. const File juce_getExecutableFile()
  212497. {
  212498. Dl_info exeInfo;
  212499. dladdr ((const void*) juce_getExecutableFile, &exeInfo);
  212500. return File (exeInfo.dli_fname);
  212501. }
  212502. // if this file doesn't exist, find a parent of it that does..
  212503. static bool doStatFS (const File* file, struct statfs& result) throw()
  212504. {
  212505. File f (*file);
  212506. for (int i = 5; --i >= 0;)
  212507. {
  212508. if (f.exists())
  212509. break;
  212510. f = f.getParentDirectory();
  212511. }
  212512. return statfs (f.getFullPathName().toUTF8(), &result) == 0;
  212513. }
  212514. int64 File::getBytesFreeOnVolume() const throw()
  212515. {
  212516. struct statfs buf;
  212517. if (doStatFS (this, buf))
  212518. return (int64) buf.f_bsize * (int64) buf.f_bavail; // Note: this returns space available to non-super user
  212519. return 0;
  212520. }
  212521. int64 File::getVolumeTotalSize() const throw()
  212522. {
  212523. struct statfs buf;
  212524. if (doStatFS (this, buf))
  212525. return (int64) buf.f_bsize * (int64) buf.f_blocks;
  212526. return 0;
  212527. }
  212528. const String juce_getVolumeLabel (const String& filenameOnVolume,
  212529. int& volumeSerialNumber) throw()
  212530. {
  212531. volumeSerialNumber = 0;
  212532. #if JUCE_MAC
  212533. struct VolAttrBuf
  212534. {
  212535. u_int32_t length;
  212536. attrreference_t mountPointRef;
  212537. char mountPointSpace [MAXPATHLEN];
  212538. } attrBuf;
  212539. struct attrlist attrList;
  212540. zerostruct (attrList);
  212541. attrList.bitmapcount = ATTR_BIT_MAP_COUNT;
  212542. attrList.volattr = ATTR_VOL_INFO | ATTR_VOL_NAME;
  212543. File f (filenameOnVolume);
  212544. for (;;)
  212545. {
  212546. if (getattrlist ((const char*) f.getFullPathName().toUTF8(),
  212547. &attrList, &attrBuf, sizeof(attrBuf), 0) == 0)
  212548. {
  212549. return String::fromUTF8 (((const uint8*) &attrBuf.mountPointRef) + attrBuf.mountPointRef.attr_dataoffset,
  212550. (int) attrBuf.mountPointRef.attr_length);
  212551. }
  212552. const File parent (f.getParentDirectory());
  212553. if (f == parent)
  212554. break;
  212555. f = parent;
  212556. }
  212557. #endif
  212558. return String::empty;
  212559. }
  212560. void juce_runSystemCommand (const String& command)
  212561. {
  212562. int result = system ((const char*) command.toUTF8());
  212563. (void) result;
  212564. }
  212565. const String juce_getOutputFromCommand (const String& command)
  212566. {
  212567. // slight bodge here, as we just pipe the output into a temp file and read it...
  212568. const File tempFile (File::getSpecialLocation (File::tempDirectory)
  212569. .getNonexistentChildFile (String::toHexString (Random::getSystemRandom().nextInt()), ".tmp", false));
  212570. juce_runSystemCommand (command + " > " + tempFile.getFullPathName());
  212571. String result (tempFile.loadFileAsString());
  212572. tempFile.deleteFile();
  212573. return result;
  212574. }
  212575. #if JUCE_64BIT
  212576. #define filedesc ((long long) internal)
  212577. #else
  212578. #define filedesc ((int) internal)
  212579. #endif
  212580. InterProcessLock::InterProcessLock (const String& name_) throw()
  212581. : internal (0),
  212582. name (name_),
  212583. reentrancyLevel (0)
  212584. {
  212585. #if JUCE_MAC
  212586. // (don't use getSpecialLocation() to avoid the temp folder being different for each app)
  212587. const File temp (File (T("~/Library/Caches/Juce")).getChildFile (name));
  212588. #else
  212589. const File temp (File::getSpecialLocation (File::tempDirectory).getChildFile (name));
  212590. #endif
  212591. temp.create();
  212592. internal = (void*) open (temp.getFullPathName().toUTF8(), O_RDWR);
  212593. }
  212594. InterProcessLock::~InterProcessLock() throw()
  212595. {
  212596. while (reentrancyLevel > 0)
  212597. this->exit();
  212598. close (filedesc);
  212599. }
  212600. bool InterProcessLock::enter (const int timeOutMillisecs) throw()
  212601. {
  212602. if (internal == 0)
  212603. return false;
  212604. if (reentrancyLevel != 0)
  212605. return true;
  212606. const int64 endTime = Time::currentTimeMillis() + timeOutMillisecs;
  212607. struct flock fl;
  212608. zerostruct (fl);
  212609. fl.l_whence = SEEK_SET;
  212610. fl.l_type = F_WRLCK;
  212611. for (;;)
  212612. {
  212613. const int result = fcntl (filedesc, F_SETLK, &fl);
  212614. if (result >= 0)
  212615. {
  212616. ++reentrancyLevel;
  212617. return true;
  212618. }
  212619. if (errno != EINTR)
  212620. {
  212621. if (timeOutMillisecs == 0
  212622. || (timeOutMillisecs > 0 && Time::currentTimeMillis() >= endTime))
  212623. break;
  212624. Thread::sleep (10);
  212625. }
  212626. }
  212627. return false;
  212628. }
  212629. void InterProcessLock::exit() throw()
  212630. {
  212631. if (reentrancyLevel > 0 && internal != 0)
  212632. {
  212633. --reentrancyLevel;
  212634. struct flock fl;
  212635. zerostruct (fl);
  212636. fl.l_whence = SEEK_SET;
  212637. fl.l_type = F_UNLCK;
  212638. for (;;)
  212639. {
  212640. const int result = fcntl (filedesc, F_SETLKW, &fl);
  212641. if (result >= 0 || errno != EINTR)
  212642. break;
  212643. }
  212644. }
  212645. }
  212646. /********* End of inlined file: juce_posix_SharedCode.h *********/
  212647. /********* Start of inlined file: juce_linux_Files.cpp *********/
  212648. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  212649. // compiled on its own).
  212650. #ifdef JUCE_INCLUDED_FILE
  212651. #define U_ISOFS_SUPER_MAGIC (short) 0x9660 // linux/iso_fs.h
  212652. #define U_MSDOS_SUPER_MAGIC (short) 0x4d44 // linux/msdos_fs.h
  212653. #define U_NFS_SUPER_MAGIC (short) 0x6969 // linux/nfs_fs.h
  212654. #define U_SMB_SUPER_MAGIC (short) 0x517B // linux/smb_fs.h
  212655. void juce_getFileTimes (const String& fileName,
  212656. int64& modificationTime,
  212657. int64& accessTime,
  212658. int64& creationTime) throw()
  212659. {
  212660. modificationTime = 0;
  212661. accessTime = 0;
  212662. creationTime = 0;
  212663. struct stat info;
  212664. const int res = stat (fileName.toUTF8(), &info);
  212665. if (res == 0)
  212666. {
  212667. modificationTime = (int64) info.st_mtime * 1000;
  212668. accessTime = (int64) info.st_atime * 1000;
  212669. creationTime = (int64) info.st_ctime * 1000;
  212670. }
  212671. }
  212672. bool juce_setFileTimes (const String& fileName,
  212673. int64 modificationTime,
  212674. int64 accessTime,
  212675. int64 creationTime) throw()
  212676. {
  212677. struct utimbuf times;
  212678. times.actime = (time_t) (accessTime / 1000);
  212679. times.modtime = (time_t) (modificationTime / 1000);
  212680. return utime (fileName.toUTF8(), &times) == 0;
  212681. }
  212682. bool juce_setFileReadOnly (const String& fileName, bool isReadOnly) throw()
  212683. {
  212684. struct stat info;
  212685. const int res = stat (fileName.toUTF8(), &info);
  212686. if (res != 0)
  212687. return false;
  212688. info.st_mode &= 0777; // Just permissions
  212689. if( isReadOnly )
  212690. info.st_mode &= ~(S_IWUSR | S_IWGRP | S_IWOTH);
  212691. else
  212692. // Give everybody write permission?
  212693. info.st_mode |= S_IWUSR | S_IWGRP | S_IWOTH;
  212694. return chmod (fileName.toUTF8(), info.st_mode) == 0;
  212695. }
  212696. bool juce_copyFile (const String& s, const String& d) throw()
  212697. {
  212698. const File source (s), dest (d);
  212699. FileInputStream* in = source.createInputStream();
  212700. bool ok = false;
  212701. if (in != 0)
  212702. {
  212703. if (dest.deleteFile())
  212704. {
  212705. FileOutputStream* const out = dest.createOutputStream();
  212706. if (out != 0)
  212707. {
  212708. const int bytesCopied = out->writeFromInputStream (*in, -1);
  212709. delete out;
  212710. ok = (bytesCopied == source.getSize());
  212711. if (! ok)
  212712. dest.deleteFile();
  212713. }
  212714. }
  212715. delete in;
  212716. }
  212717. return ok;
  212718. }
  212719. const StringArray juce_getFileSystemRoots() throw()
  212720. {
  212721. StringArray s;
  212722. s.add (T("/"));
  212723. return s;
  212724. }
  212725. bool File::isOnCDRomDrive() const throw()
  212726. {
  212727. struct statfs buf;
  212728. if (statfs (getFullPathName().toUTF8(), &buf) == 0)
  212729. return (buf.f_type == U_ISOFS_SUPER_MAGIC);
  212730. // Assume not if this fails for some reason
  212731. return false;
  212732. }
  212733. bool File::isOnHardDisk() const throw()
  212734. {
  212735. struct statfs buf;
  212736. if (statfs (getFullPathName().toUTF8(), &buf) == 0)
  212737. {
  212738. switch (buf.f_type)
  212739. {
  212740. case U_ISOFS_SUPER_MAGIC: // CD-ROM
  212741. case U_MSDOS_SUPER_MAGIC: // Probably floppy (but could be mounted FAT filesystem)
  212742. case U_NFS_SUPER_MAGIC: // Network NFS
  212743. case U_SMB_SUPER_MAGIC: // Network Samba
  212744. return false;
  212745. default:
  212746. // Assume anything else is a hard-disk (but note it could
  212747. // be a RAM disk. There isn't a good way of determining
  212748. // this for sure)
  212749. return true;
  212750. }
  212751. }
  212752. // Assume so if this fails for some reason
  212753. return true;
  212754. }
  212755. bool File::isOnRemovableDrive() const throw()
  212756. {
  212757. jassertfalse // xxx not implemented for linux!
  212758. return false;
  212759. }
  212760. bool File::isHidden() const throw()
  212761. {
  212762. return getFileName().startsWithChar (T('.'));
  212763. }
  212764. const File File::getSpecialLocation (const SpecialLocationType type)
  212765. {
  212766. switch (type)
  212767. {
  212768. case userHomeDirectory:
  212769. {
  212770. const char* homeDir = getenv ("HOME");
  212771. if (homeDir == 0)
  212772. {
  212773. struct passwd* const pw = getpwuid (getuid());
  212774. if (pw != 0)
  212775. homeDir = pw->pw_dir;
  212776. }
  212777. return File (String::fromUTF8 ((const uint8*) homeDir));
  212778. }
  212779. case userDocumentsDirectory:
  212780. case userMusicDirectory:
  212781. case userMoviesDirectory:
  212782. case userApplicationDataDirectory:
  212783. return File ("~");
  212784. case userDesktopDirectory:
  212785. return File ("~/Desktop");
  212786. case commonApplicationDataDirectory:
  212787. return File ("/var");
  212788. case globalApplicationsDirectory:
  212789. return File ("/usr");
  212790. case tempDirectory:
  212791. {
  212792. File tmp ("/var/tmp");
  212793. if (! tmp.isDirectory())
  212794. {
  212795. tmp = T("/tmp");
  212796. if (! tmp.isDirectory())
  212797. tmp = File::getCurrentWorkingDirectory();
  212798. }
  212799. return tmp;
  212800. }
  212801. case currentExecutableFile:
  212802. case currentApplicationFile:
  212803. return juce_getExecutableFile();
  212804. default:
  212805. jassertfalse // unknown type?
  212806. break;
  212807. }
  212808. return File::nonexistent;
  212809. }
  212810. const File File::getCurrentWorkingDirectory() throw()
  212811. {
  212812. char buf [2048];
  212813. return File (String::fromUTF8 ((const uint8*) getcwd (buf, sizeof (buf))));
  212814. }
  212815. bool File::setAsCurrentWorkingDirectory() const throw()
  212816. {
  212817. return chdir (getFullPathName().toUTF8()) == 0;
  212818. }
  212819. const String File::getVersion() const throw()
  212820. {
  212821. return String::empty; // xxx not yet implemented
  212822. }
  212823. const File File::getLinkedTarget() const throw()
  212824. {
  212825. char buffer [4096];
  212826. size_t numChars = readlink ((const char*) getFullPathName().toUTF8(),
  212827. buffer, sizeof (buffer));
  212828. if (numChars > 0 && numChars <= sizeof (buffer))
  212829. return File (String::fromUTF8 ((const uint8*) buffer, (int) numChars));
  212830. return *this;
  212831. }
  212832. bool File::moveToTrash() const throw()
  212833. {
  212834. if (! exists())
  212835. return true;
  212836. File trashCan (T("~/.Trash"));
  212837. if (! trashCan.isDirectory())
  212838. trashCan = T("~/.local/share/Trash/files");
  212839. if (! trashCan.isDirectory())
  212840. return false;
  212841. return moveFileTo (trashCan.getNonexistentChildFile (getFileNameWithoutExtension(),
  212842. getFileExtension()));
  212843. }
  212844. struct FindFileStruct
  212845. {
  212846. String parentDir, wildCard;
  212847. DIR* dir;
  212848. bool getNextMatch (String& result, bool* const isDir, bool* const isHidden, int64* const fileSize,
  212849. Time* const modTime, Time* const creationTime, bool* const isReadOnly) throw()
  212850. {
  212851. const char* const wildcardUTF8 = wildCard.toUTF8();
  212852. for (;;)
  212853. {
  212854. struct dirent* const de = readdir (dir);
  212855. if (de == 0)
  212856. break;
  212857. if (fnmatch (wildcardUTF8, de->d_name, FNM_CASEFOLD) == 0)
  212858. {
  212859. result = String::fromUTF8 ((const uint8*) de->d_name);
  212860. const String path (parentDir + result);
  212861. if (isDir != 0 || fileSize != 0)
  212862. {
  212863. struct stat info;
  212864. const bool statOk = (stat (path.toUTF8(), &info) == 0);
  212865. if (isDir != 0)
  212866. *isDir = path.isEmpty() || (statOk && ((info.st_mode & S_IFDIR) != 0));
  212867. if (isHidden != 0)
  212868. *isHidden = (de->d_name[0] == '.');
  212869. if (fileSize != 0)
  212870. *fileSize = statOk ? info.st_size : 0;
  212871. }
  212872. if (modTime != 0 || creationTime != 0)
  212873. {
  212874. int64 m, a, c;
  212875. juce_getFileTimes (path, m, a, c);
  212876. if (modTime != 0)
  212877. *modTime = m;
  212878. if (creationTime != 0)
  212879. *creationTime = c;
  212880. }
  212881. if (isReadOnly != 0)
  212882. *isReadOnly = ! juce_canWriteToFile (path);
  212883. return true;
  212884. }
  212885. }
  212886. return false;
  212887. }
  212888. };
  212889. // returns 0 on failure
  212890. void* juce_findFileStart (const String& directory, const String& wildCard, String& firstResultFile,
  212891. bool* isDir, bool* isHidden, int64* fileSize, Time* modTime,
  212892. Time* creationTime, bool* isReadOnly) throw()
  212893. {
  212894. DIR* d = opendir (directory.toUTF8());
  212895. if (d != 0)
  212896. {
  212897. FindFileStruct* ff = new FindFileStruct();
  212898. ff->parentDir = directory;
  212899. if (!ff->parentDir.endsWithChar (File::separator))
  212900. ff->parentDir += File::separator;
  212901. ff->wildCard = wildCard;
  212902. if (wildCard == T("*.*"))
  212903. ff->wildCard = T("*");
  212904. ff->dir = d;
  212905. if (ff->getNextMatch (firstResultFile, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly))
  212906. {
  212907. return ff;
  212908. }
  212909. else
  212910. {
  212911. firstResultFile = String::empty;
  212912. isDir = false;
  212913. isHidden = false;
  212914. closedir (d);
  212915. delete ff;
  212916. }
  212917. }
  212918. return 0;
  212919. }
  212920. bool juce_findFileNext (void* handle, String& resultFile,
  212921. bool* isDir, bool* isHidden, int64* fileSize, Time* modTime, Time* creationTime, bool* isReadOnly) throw()
  212922. {
  212923. FindFileStruct* const ff = (FindFileStruct*) handle;
  212924. if (ff != 0)
  212925. return ff->getNextMatch (resultFile, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly);
  212926. return false;
  212927. }
  212928. void juce_findFileClose (void* handle) throw()
  212929. {
  212930. FindFileStruct* const ff = (FindFileStruct*) handle;
  212931. if (ff != 0)
  212932. {
  212933. closedir (ff->dir);
  212934. delete ff;
  212935. }
  212936. }
  212937. bool juce_launchFile (const String& fileName,
  212938. const String& parameters) throw()
  212939. {
  212940. String cmdString (fileName);
  212941. cmdString << " " << parameters;
  212942. if (URL::isProbablyAWebsiteURL (fileName)
  212943. || URL::isProbablyAnEmailAddress (fileName))
  212944. {
  212945. // create a command that tries to launch a bunch of likely browsers
  212946. const char* const browserNames[] = { "/etc/alternatives/x-www-browser", "firefox", "mozilla", "konqueror", "opera" };
  212947. StringArray cmdLines;
  212948. for (int i = 0; i < numElementsInArray (browserNames); ++i)
  212949. cmdLines.add (String (browserNames[i]) + T(" ") + cmdString.trim().quoted());
  212950. cmdString = cmdLines.joinIntoString (T(" || "));
  212951. }
  212952. if (cmdString.startsWithIgnoreCase (T("file:")))
  212953. cmdString = cmdString.substring (5);
  212954. const char* const argv[4] = { "/bin/sh", "-c", (const char*) cmdString.toUTF8(), 0 };
  212955. const int cpid = fork();
  212956. if (cpid == 0)
  212957. {
  212958. setsid();
  212959. // Child process
  212960. execve (argv[0], (char**) argv, environ);
  212961. exit (0);
  212962. }
  212963. return cpid >= 0;
  212964. }
  212965. #endif
  212966. /********* End of inlined file: juce_linux_Files.cpp *********/
  212967. /********* Start of inlined file: juce_posix_NamedPipe.cpp *********/
  212968. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  212969. // compiled on its own).
  212970. #if JUCE_INCLUDED_FILE
  212971. struct NamedPipeInternal
  212972. {
  212973. String pipeInName, pipeOutName;
  212974. int pipeIn, pipeOut;
  212975. bool volatile createdPipe, blocked, stopReadOperation;
  212976. static void signalHandler (int) {}
  212977. };
  212978. void NamedPipe::cancelPendingReads()
  212979. {
  212980. while (internal != 0 && ((NamedPipeInternal*) internal)->blocked)
  212981. {
  212982. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  212983. intern->stopReadOperation = true;
  212984. char buffer [1] = { 0 };
  212985. int bytesWritten = ::write (intern->pipeIn, buffer, 1);
  212986. (void) bytesWritten;
  212987. int timeout = 2000;
  212988. while (intern->blocked && --timeout >= 0)
  212989. Thread::sleep (2);
  212990. intern->stopReadOperation = false;
  212991. }
  212992. }
  212993. void NamedPipe::close()
  212994. {
  212995. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  212996. if (intern != 0)
  212997. {
  212998. internal = 0;
  212999. if (intern->pipeIn != -1)
  213000. ::close (intern->pipeIn);
  213001. if (intern->pipeOut != -1)
  213002. ::close (intern->pipeOut);
  213003. if (intern->createdPipe)
  213004. {
  213005. unlink (intern->pipeInName);
  213006. unlink (intern->pipeOutName);
  213007. }
  213008. delete intern;
  213009. }
  213010. }
  213011. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  213012. {
  213013. close();
  213014. NamedPipeInternal* const intern = new NamedPipeInternal();
  213015. internal = intern;
  213016. intern->createdPipe = createPipe;
  213017. intern->blocked = false;
  213018. intern->stopReadOperation = false;
  213019. signal (SIGPIPE, NamedPipeInternal::signalHandler);
  213020. siginterrupt (SIGPIPE, 1);
  213021. const String pipePath (T("/tmp/") + File::createLegalFileName (pipeName));
  213022. intern->pipeInName = pipePath + T("_in");
  213023. intern->pipeOutName = pipePath + T("_out");
  213024. intern->pipeIn = -1;
  213025. intern->pipeOut = -1;
  213026. if (createPipe)
  213027. {
  213028. if ((mkfifo (intern->pipeInName, 0666) && errno != EEXIST)
  213029. || (mkfifo (intern->pipeOutName, 0666) && errno != EEXIST))
  213030. {
  213031. delete intern;
  213032. internal = 0;
  213033. return false;
  213034. }
  213035. }
  213036. return true;
  213037. }
  213038. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int /*timeOutMilliseconds*/)
  213039. {
  213040. int bytesRead = -1;
  213041. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  213042. if (intern != 0)
  213043. {
  213044. intern->blocked = true;
  213045. if (intern->pipeIn == -1)
  213046. {
  213047. if (intern->createdPipe)
  213048. intern->pipeIn = ::open (intern->pipeInName, O_RDWR);
  213049. else
  213050. intern->pipeIn = ::open (intern->pipeOutName, O_RDWR);
  213051. if (intern->pipeIn == -1)
  213052. {
  213053. intern->blocked = false;
  213054. return -1;
  213055. }
  213056. }
  213057. bytesRead = 0;
  213058. char* p = (char*) destBuffer;
  213059. while (bytesRead < maxBytesToRead)
  213060. {
  213061. const int bytesThisTime = maxBytesToRead - bytesRead;
  213062. const int numRead = ::read (intern->pipeIn, p, bytesThisTime);
  213063. if (numRead <= 0 || intern->stopReadOperation)
  213064. {
  213065. bytesRead = -1;
  213066. break;
  213067. }
  213068. bytesRead += numRead;
  213069. p += bytesRead;
  213070. }
  213071. intern->blocked = false;
  213072. }
  213073. return bytesRead;
  213074. }
  213075. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  213076. {
  213077. int bytesWritten = -1;
  213078. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  213079. if (intern != 0)
  213080. {
  213081. if (intern->pipeOut == -1)
  213082. {
  213083. if (intern->createdPipe)
  213084. intern->pipeOut = ::open (intern->pipeOutName, O_WRONLY);
  213085. else
  213086. intern->pipeOut = ::open (intern->pipeInName, O_WRONLY);
  213087. if (intern->pipeOut == -1)
  213088. {
  213089. return -1;
  213090. }
  213091. }
  213092. const char* p = (const char*) sourceBuffer;
  213093. bytesWritten = 0;
  213094. const uint32 timeOutTime = Time::getMillisecondCounter() + timeOutMilliseconds;
  213095. while (bytesWritten < numBytesToWrite
  213096. && (timeOutMilliseconds < 0 || Time::getMillisecondCounter() < timeOutTime))
  213097. {
  213098. const int bytesThisTime = numBytesToWrite - bytesWritten;
  213099. const int numWritten = ::write (intern->pipeOut, p, bytesThisTime);
  213100. if (numWritten <= 0)
  213101. {
  213102. bytesWritten = -1;
  213103. break;
  213104. }
  213105. bytesWritten += numWritten;
  213106. p += bytesWritten;
  213107. }
  213108. }
  213109. return bytesWritten;
  213110. }
  213111. #endif
  213112. /********* End of inlined file: juce_posix_NamedPipe.cpp *********/
  213113. /********* Start of inlined file: juce_linux_Network.cpp *********/
  213114. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  213115. // compiled on its own).
  213116. #ifdef JUCE_INCLUDED_FILE
  213117. int SystemStats::getMACAddresses (int64* addresses, int maxNum, const bool littleEndian) throw()
  213118. {
  213119. int numResults = 0;
  213120. const int s = socket (AF_INET, SOCK_DGRAM, 0);
  213121. if (s != -1)
  213122. {
  213123. char buf [1024];
  213124. struct ifconf ifc;
  213125. ifc.ifc_len = sizeof (buf);
  213126. ifc.ifc_buf = buf;
  213127. ioctl (s, SIOCGIFCONF, &ifc);
  213128. for (unsigned int i = 0; i < ifc.ifc_len / sizeof (struct ifreq); ++i)
  213129. {
  213130. struct ifreq ifr;
  213131. strcpy (ifr.ifr_name, ifc.ifc_req[i].ifr_name);
  213132. if (ioctl (s, SIOCGIFFLAGS, &ifr) == 0
  213133. && (ifr.ifr_flags & IFF_LOOPBACK) == 0
  213134. && ioctl (s, SIOCGIFHWADDR, &ifr) == 0
  213135. && numResults < maxNum)
  213136. {
  213137. int64 a = 0;
  213138. for (int j = 6; --j >= 0;)
  213139. a = (a << 8) | (uint8) ifr.ifr_hwaddr.sa_data[j];
  213140. *addresses++ = a;
  213141. ++numResults;
  213142. }
  213143. }
  213144. close (s);
  213145. }
  213146. return numResults;
  213147. }
  213148. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  213149. const String& emailSubject,
  213150. const String& bodyText,
  213151. const StringArray& filesToAttach)
  213152. {
  213153. jassertfalse // xxx todo
  213154. return false;
  213155. }
  213156. /** A HTTP input stream that uses sockets.
  213157. */
  213158. class JUCE_HTTPSocketStream
  213159. {
  213160. public:
  213161. JUCE_HTTPSocketStream()
  213162. : readPosition (0),
  213163. socketHandle (-1),
  213164. levelsOfRedirection (0),
  213165. timeoutSeconds (15)
  213166. {
  213167. }
  213168. ~JUCE_HTTPSocketStream()
  213169. {
  213170. closeSocket();
  213171. }
  213172. bool open (const String& url,
  213173. const String& headers,
  213174. const MemoryBlock& postData,
  213175. const bool isPost,
  213176. URL::OpenStreamProgressCallback* callback,
  213177. void* callbackContext,
  213178. int timeOutMs)
  213179. {
  213180. closeSocket();
  213181. uint32 timeOutTime = Time::getMillisecondCounter();
  213182. if (timeOutMs == 0)
  213183. timeOutTime += 60000;
  213184. else if (timeOutMs < 0)
  213185. timeOutTime = 0xffffffff;
  213186. else
  213187. timeOutTime += timeOutMs;
  213188. String hostName, hostPath;
  213189. int hostPort;
  213190. if (! decomposeURL (url, hostName, hostPath, hostPort))
  213191. return false;
  213192. const struct hostent* host = 0;
  213193. int port = 0;
  213194. String proxyName, proxyPath;
  213195. int proxyPort = 0;
  213196. String proxyURL (getenv ("http_proxy"));
  213197. if (proxyURL.startsWithIgnoreCase (T("http://")))
  213198. {
  213199. if (! decomposeURL (proxyURL, proxyName, proxyPath, proxyPort))
  213200. return false;
  213201. host = gethostbyname ((const char*) proxyName.toUTF8());
  213202. port = proxyPort;
  213203. }
  213204. else
  213205. {
  213206. host = gethostbyname ((const char*) hostName.toUTF8());
  213207. port = hostPort;
  213208. }
  213209. if (host == 0)
  213210. return false;
  213211. struct sockaddr_in address;
  213212. zerostruct (address);
  213213. memcpy ((void*) &address.sin_addr, (const void*) host->h_addr, host->h_length);
  213214. address.sin_family = host->h_addrtype;
  213215. address.sin_port = htons (port);
  213216. socketHandle = socket (host->h_addrtype, SOCK_STREAM, 0);
  213217. if (socketHandle == -1)
  213218. return false;
  213219. int receiveBufferSize = 16384;
  213220. setsockopt (socketHandle, SOL_SOCKET, SO_RCVBUF, (char*) &receiveBufferSize, sizeof (receiveBufferSize));
  213221. setsockopt (socketHandle, SOL_SOCKET, SO_KEEPALIVE, 0, 0);
  213222. #if JUCE_MAC
  213223. setsockopt (socketHandle, SOL_SOCKET, SO_NOSIGPIPE, 0, 0);
  213224. #endif
  213225. if (connect (socketHandle, (struct sockaddr*) &address, sizeof (address)) == -1)
  213226. {
  213227. closeSocket();
  213228. return false;
  213229. }
  213230. const MemoryBlock requestHeader (createRequestHeader (hostName, hostPort,
  213231. proxyName, proxyPort,
  213232. hostPath, url,
  213233. headers, postData,
  213234. isPost));
  213235. int totalHeaderSent = 0;
  213236. while (totalHeaderSent < requestHeader.getSize())
  213237. {
  213238. if (Time::getMillisecondCounter() > timeOutTime)
  213239. {
  213240. closeSocket();
  213241. return false;
  213242. }
  213243. const int numToSend = jmin (1024, requestHeader.getSize() - totalHeaderSent);
  213244. if (send (socketHandle,
  213245. ((const char*) requestHeader.getData()) + totalHeaderSent,
  213246. numToSend, 0)
  213247. != numToSend)
  213248. {
  213249. closeSocket();
  213250. return false;
  213251. }
  213252. totalHeaderSent += numToSend;
  213253. if (callback != 0 && ! callback (callbackContext, totalHeaderSent, requestHeader.getSize()))
  213254. {
  213255. closeSocket();
  213256. return false;
  213257. }
  213258. }
  213259. const String responseHeader (readResponse (timeOutTime));
  213260. if (responseHeader.isNotEmpty())
  213261. {
  213262. //DBG (responseHeader);
  213263. StringArray lines;
  213264. lines.addLines (responseHeader);
  213265. // NB - using charToString() here instead of just T(" "), because that was
  213266. // causing a mysterious gcc internal compiler error...
  213267. const int statusCode = responseHeader.fromFirstOccurrenceOf (String::charToString (T(' ')), false, false)
  213268. .substring (0, 3).getIntValue();
  213269. //int contentLength = findHeaderItem (lines, T("Content-Length:")).getIntValue();
  213270. //bool isChunked = findHeaderItem (lines, T("Transfer-Encoding:")).equalsIgnoreCase ("chunked");
  213271. String location (findHeaderItem (lines, T("Location:")));
  213272. if (statusCode >= 300 && statusCode < 400
  213273. && location.isNotEmpty())
  213274. {
  213275. if (! location.startsWithIgnoreCase (T("http://")))
  213276. location = T("http://") + location;
  213277. if (levelsOfRedirection++ < 3)
  213278. return open (location, headers, postData, isPost, callback, callbackContext, timeOutMs);
  213279. }
  213280. else
  213281. {
  213282. levelsOfRedirection = 0;
  213283. return true;
  213284. }
  213285. }
  213286. closeSocket();
  213287. return false;
  213288. }
  213289. int read (void* buffer, int bytesToRead)
  213290. {
  213291. fd_set readbits;
  213292. FD_ZERO (&readbits);
  213293. FD_SET (socketHandle, &readbits);
  213294. struct timeval tv;
  213295. tv.tv_sec = timeoutSeconds;
  213296. tv.tv_usec = 0;
  213297. if (select (socketHandle + 1, &readbits, 0, 0, &tv) <= 0)
  213298. return 0; // (timeout)
  213299. const int bytesRead = jmax (0, recv (socketHandle, buffer, bytesToRead, MSG_WAITALL));
  213300. readPosition += bytesRead;
  213301. return bytesRead;
  213302. }
  213303. int readPosition;
  213304. juce_UseDebuggingNewOperator
  213305. private:
  213306. int socketHandle, levelsOfRedirection;
  213307. const int timeoutSeconds;
  213308. void closeSocket()
  213309. {
  213310. if (socketHandle >= 0)
  213311. close (socketHandle);
  213312. socketHandle = -1;
  213313. }
  213314. const MemoryBlock createRequestHeader (const String& hostName,
  213315. const int hostPort,
  213316. const String& proxyName,
  213317. const int proxyPort,
  213318. const String& hostPath,
  213319. const String& originalURL,
  213320. const String& headers,
  213321. const MemoryBlock& postData,
  213322. const bool isPost)
  213323. {
  213324. String header (isPost ? "POST " : "GET ");
  213325. if (proxyName.isEmpty())
  213326. {
  213327. header << hostPath << " HTTP/1.0\r\nHost: "
  213328. << hostName << ':' << hostPort;
  213329. }
  213330. else
  213331. {
  213332. header << originalURL << " HTTP/1.0\r\nHost: "
  213333. << proxyName << ':' << proxyPort;
  213334. }
  213335. header << "\r\nUser-Agent: JUCE/"
  213336. << JUCE_MAJOR_VERSION << '.' << JUCE_MINOR_VERSION
  213337. << "\r\nConnection: Close\r\nContent-Length: "
  213338. << postData.getSize() << "\r\n"
  213339. << headers << "\r\n";
  213340. MemoryBlock mb;
  213341. mb.append (header.toUTF8(), (int) strlen (header.toUTF8()));
  213342. mb.append (postData.getData(), postData.getSize());
  213343. return mb;
  213344. }
  213345. const String readResponse (const uint32 timeOutTime)
  213346. {
  213347. int bytesRead = 0, numConsecutiveLFs = 0;
  213348. MemoryBlock buffer (1024, true);
  213349. while (numConsecutiveLFs < 2 && bytesRead < 32768
  213350. && Time::getMillisecondCounter() <= timeOutTime)
  213351. {
  213352. fd_set readbits;
  213353. FD_ZERO (&readbits);
  213354. FD_SET (socketHandle, &readbits);
  213355. struct timeval tv;
  213356. tv.tv_sec = timeoutSeconds;
  213357. tv.tv_usec = 0;
  213358. if (select (socketHandle + 1, &readbits, 0, 0, &tv) <= 0)
  213359. return String::empty; // (timeout)
  213360. buffer.ensureSize (bytesRead + 8, true);
  213361. char* const dest = (char*) buffer.getData() + bytesRead;
  213362. if (recv (socketHandle, dest, 1, 0) == -1)
  213363. return String::empty;
  213364. const char lastByte = *dest;
  213365. ++bytesRead;
  213366. if (lastByte == '\n')
  213367. ++numConsecutiveLFs;
  213368. else if (lastByte != '\r')
  213369. numConsecutiveLFs = 0;
  213370. }
  213371. const String header (String::fromUTF8 ((const uint8*) buffer.getData()));
  213372. if (header.startsWithIgnoreCase (T("HTTP/")))
  213373. return header.trimEnd();
  213374. return String::empty;
  213375. }
  213376. static bool decomposeURL (const String& url,
  213377. String& host, String& path, int& port)
  213378. {
  213379. if (! url.startsWithIgnoreCase (T("http://")))
  213380. return false;
  213381. const int nextSlash = url.indexOfChar (7, '/');
  213382. int nextColon = url.indexOfChar (7, ':');
  213383. if (nextColon > nextSlash && nextSlash > 0)
  213384. nextColon = -1;
  213385. if (nextColon >= 0)
  213386. {
  213387. host = url.substring (7, nextColon);
  213388. if (nextSlash >= 0)
  213389. port = url.substring (nextColon + 1, nextSlash).getIntValue();
  213390. else
  213391. port = url.substring (nextColon + 1).getIntValue();
  213392. }
  213393. else
  213394. {
  213395. port = 80;
  213396. if (nextSlash >= 0)
  213397. host = url.substring (7, nextSlash);
  213398. else
  213399. host = url.substring (7);
  213400. }
  213401. if (nextSlash >= 0)
  213402. path = url.substring (nextSlash);
  213403. else
  213404. path = T("/");
  213405. return true;
  213406. }
  213407. static const String findHeaderItem (const StringArray& lines, const String& itemName)
  213408. {
  213409. for (int i = 0; i < lines.size(); ++i)
  213410. if (lines[i].startsWithIgnoreCase (itemName))
  213411. return lines[i].substring (itemName.length()).trim();
  213412. return String::empty;
  213413. }
  213414. };
  213415. bool juce_isOnLine()
  213416. {
  213417. return true;
  213418. }
  213419. void* juce_openInternetFile (const String& url,
  213420. const String& headers,
  213421. const MemoryBlock& postData,
  213422. const bool isPost,
  213423. URL::OpenStreamProgressCallback* callback,
  213424. void* callbackContext,
  213425. int timeOutMs)
  213426. {
  213427. JUCE_HTTPSocketStream* const s = new JUCE_HTTPSocketStream();
  213428. if (s->open (url, headers, postData, isPost,
  213429. callback, callbackContext, timeOutMs))
  213430. return s;
  213431. delete s;
  213432. return 0;
  213433. }
  213434. void juce_closeInternetFile (void* handle)
  213435. {
  213436. JUCE_HTTPSocketStream* const s = (JUCE_HTTPSocketStream*) handle;
  213437. if (s != 0)
  213438. delete s;
  213439. }
  213440. int juce_readFromInternetFile (void* handle, void* buffer, int bytesToRead)
  213441. {
  213442. JUCE_HTTPSocketStream* const s = (JUCE_HTTPSocketStream*) handle;
  213443. if (s != 0)
  213444. return s->read (buffer, bytesToRead);
  213445. return 0;
  213446. }
  213447. int64 juce_getInternetFileContentLength (void* handle)
  213448. {
  213449. JUCE_HTTPSocketStream* const s = (JUCE_HTTPSocketStream*) handle;
  213450. if (s != 0)
  213451. {
  213452. //xxx todo
  213453. jassertfalse
  213454. }
  213455. return -1;
  213456. }
  213457. int juce_seekInInternetFile (void* handle, int newPosition)
  213458. {
  213459. JUCE_HTTPSocketStream* const s = (JUCE_HTTPSocketStream*) handle;
  213460. if (s != 0)
  213461. return s->readPosition;
  213462. return 0;
  213463. }
  213464. #endif
  213465. /********* End of inlined file: juce_linux_Network.cpp *********/
  213466. /********* Start of inlined file: juce_linux_SystemStats.cpp *********/
  213467. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  213468. // compiled on its own).
  213469. #ifdef JUCE_INCLUDED_FILE
  213470. /*static juce_noinline unsigned int getCPUIDWord (int* familyModel, int* extFeatures) throw()
  213471. {
  213472. unsigned int cpu = 0;
  213473. unsigned int ext = 0;
  213474. unsigned int family = 0;
  213475. unsigned int dummy = 0;
  213476. #if JUCE_64BIT
  213477. __asm__ ("cpuid"
  213478. : "=a" (family), "=b" (ext), "=c" (dummy), "=d" (cpu) : "a" (1));
  213479. #else
  213480. __asm__ ("push %%ebx; cpuid; mov %%ebx, %%edi; pop %%ebx"
  213481. : "=a" (family), "=D" (ext), "=c" (dummy), "=d" (cpu) : "a" (1));
  213482. #endif
  213483. if (familyModel != 0)
  213484. *familyModel = family;
  213485. if (extFeatures != 0)
  213486. *extFeatures = ext;
  213487. return cpu;
  213488. }*/
  213489. void Logger::outputDebugString (const String& text) throw()
  213490. {
  213491. fputs (text.toUTF8(), stdout);
  213492. fputs ("\n", stdout);
  213493. }
  213494. void Logger::outputDebugPrintf (const tchar* format, ...) throw()
  213495. {
  213496. String text;
  213497. va_list args;
  213498. va_start (args, format);
  213499. text.vprintf(format, args);
  213500. outputDebugString(text);
  213501. }
  213502. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType() throw()
  213503. {
  213504. return Linux;
  213505. }
  213506. const String SystemStats::getOperatingSystemName() throw()
  213507. {
  213508. return T("Linux");
  213509. }
  213510. bool SystemStats::isOperatingSystem64Bit() throw()
  213511. {
  213512. #if JUCE_64BIT
  213513. return true;
  213514. #else
  213515. //xxx not sure how to find this out?..
  213516. return false;
  213517. #endif
  213518. }
  213519. static const String getCpuInfo (const char* key, bool lastOne = false) throw()
  213520. {
  213521. String info;
  213522. char buf [256];
  213523. FILE* f = fopen ("/proc/cpuinfo", "r");
  213524. while (f != 0 && fgets (buf, sizeof(buf), f))
  213525. {
  213526. if (strncmp (buf, key, strlen (key)) == 0)
  213527. {
  213528. char* p = buf;
  213529. while (*p && *p != '\n')
  213530. ++p;
  213531. if (*p != 0)
  213532. *p = 0;
  213533. p = buf;
  213534. while (*p != 0 && *p != ':')
  213535. ++p;
  213536. if (*p != 0 && *(p + 1) != 0)
  213537. info = p + 2;
  213538. if (! lastOne)
  213539. break;
  213540. }
  213541. }
  213542. fclose (f);
  213543. return info;
  213544. }
  213545. bool SystemStats::hasMMX() throw()
  213546. {
  213547. return getCpuInfo ("flags").contains (T("mmx"));
  213548. }
  213549. bool SystemStats::hasSSE() throw()
  213550. {
  213551. return getCpuInfo ("flags").contains (T("sse"));
  213552. }
  213553. bool SystemStats::hasSSE2() throw()
  213554. {
  213555. return getCpuInfo ("flags").contains (T("sse2"));
  213556. }
  213557. bool SystemStats::has3DNow() throw()
  213558. {
  213559. return getCpuInfo ("flags").contains (T("3dnow"));
  213560. }
  213561. const String SystemStats::getCpuVendor() throw()
  213562. {
  213563. return getCpuInfo ("vendor_id");
  213564. }
  213565. int SystemStats::getCpuSpeedInMegaherz() throw()
  213566. {
  213567. const String speed (getCpuInfo ("cpu MHz"));
  213568. return (int) (speed.getFloatValue() + 0.5f);
  213569. }
  213570. int SystemStats::getMemorySizeInMegabytes() throw()
  213571. {
  213572. struct sysinfo sysi;
  213573. if (sysinfo (&sysi) == 0)
  213574. return (sysi.totalram * sysi.mem_unit / (1024 * 1024));
  213575. return 0;
  213576. }
  213577. uint32 juce_millisecondsSinceStartup() throw()
  213578. {
  213579. static unsigned int calibrate = 0;
  213580. static bool calibrated = false;
  213581. timeval t;
  213582. unsigned int ret = 0;
  213583. if (! gettimeofday (&t, 0))
  213584. {
  213585. if (! calibrated)
  213586. {
  213587. struct sysinfo sysi;
  213588. if (sysinfo (&sysi) == 0)
  213589. // Safe to assume system was not brought up earlier than 1970!
  213590. calibrate = t.tv_sec - sysi.uptime;
  213591. calibrated = true;
  213592. }
  213593. ret = 1000 * (t.tv_sec - calibrate) + (t.tv_usec / 1000);
  213594. }
  213595. return ret;
  213596. }
  213597. double Time::getMillisecondCounterHiRes() throw()
  213598. {
  213599. return getHighResolutionTicks() * 0.001;
  213600. }
  213601. int64 Time::getHighResolutionTicks() throw()
  213602. {
  213603. timeval t;
  213604. if (gettimeofday (&t, 0))
  213605. return 0;
  213606. return ((int64) t.tv_sec * (int64) 1000000) + (int64) t.tv_usec;
  213607. }
  213608. int64 Time::getHighResolutionTicksPerSecond() throw()
  213609. {
  213610. // Microseconds
  213611. return 1000000;
  213612. }
  213613. bool Time::setSystemTimeToThisTime() const throw()
  213614. {
  213615. timeval t;
  213616. t.tv_sec = millisSinceEpoch % 1000000;
  213617. t.tv_usec = millisSinceEpoch - t.tv_sec;
  213618. return settimeofday (&t, NULL) ? false : true;
  213619. }
  213620. int SystemStats::getPageSize() throw()
  213621. {
  213622. static int systemPageSize = 0;
  213623. if (systemPageSize == 0)
  213624. systemPageSize = sysconf (_SC_PAGESIZE);
  213625. return systemPageSize;
  213626. }
  213627. int SystemStats::getNumCpus() throw()
  213628. {
  213629. const int lastCpu = getCpuInfo ("processor", true).getIntValue();
  213630. return lastCpu + 1;
  213631. }
  213632. void SystemStats::initialiseStats() throw()
  213633. {
  213634. // Process starts off as root when running suid
  213635. Process::lowerPrivilege();
  213636. String s (SystemStats::getJUCEVersion());
  213637. }
  213638. void PlatformUtilities::fpuReset()
  213639. {
  213640. }
  213641. #endif
  213642. /********* End of inlined file: juce_linux_SystemStats.cpp *********/
  213643. /********* Start of inlined file: juce_linux_Threads.cpp *********/
  213644. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  213645. // compiled on its own).
  213646. #ifdef JUCE_INCLUDED_FILE
  213647. /*
  213648. Note that a lot of methods that you'd expect to find in this file actually
  213649. live in juce_posix_SharedCode.h!
  213650. */
  213651. void JUCE_API juce_threadEntryPoint (void*);
  213652. void* threadEntryProc (void* value) throw()
  213653. {
  213654. // New threads start off as root when running suid
  213655. Process::lowerPrivilege();
  213656. juce_threadEntryPoint (value);
  213657. return 0;
  213658. }
  213659. void* juce_createThread (void* userData) throw()
  213660. {
  213661. pthread_t handle = 0;
  213662. if (pthread_create (&handle, 0, threadEntryProc, userData) == 0)
  213663. {
  213664. pthread_detach (handle);
  213665. return (void*)handle;
  213666. }
  213667. return 0;
  213668. }
  213669. void juce_killThread (void* handle) throw()
  213670. {
  213671. if (handle != 0)
  213672. pthread_cancel ((pthread_t)handle);
  213673. }
  213674. void juce_setCurrentThreadName (const String& /*name*/) throw()
  213675. {
  213676. }
  213677. Thread::ThreadID Thread::getCurrentThreadId() throw()
  213678. {
  213679. return (ThreadID) pthread_self();
  213680. }
  213681. /*
  213682. * This is all a bit non-ideal... the trouble is that on Linux you
  213683. * need to call setpriority to affect the dynamic priority for
  213684. * non-realtime processes, but this requires the pid, which is not
  213685. * accessible from the pthread_t. We could get it by calling getpid
  213686. * once each thread has started, but then we would need a list of
  213687. * running threads etc etc.
  213688. * Also there is no such thing as IDLE priority on Linux.
  213689. * For the moment, map idle, low and normal process priorities to
  213690. * SCHED_OTHER, with the thread priority ignored for these classes.
  213691. * Map high priority processes to the lower half of the SCHED_RR
  213692. * range, and realtime to the upper half
  213693. */
  213694. // priority 1 to 10 where 5=normal, 1=low. If the handle is 0, sets the
  213695. // priority of the current thread
  213696. bool juce_setThreadPriority (void* handle, int priority) throw()
  213697. {
  213698. struct sched_param param;
  213699. int policy, maxp, minp, pri;
  213700. if (handle == 0)
  213701. handle = (void*) pthread_self();
  213702. if (pthread_getschedparam ((pthread_t) handle, &policy, &param) == 0
  213703. && policy != SCHED_OTHER)
  213704. {
  213705. minp = sched_get_priority_min(policy);
  213706. maxp = sched_get_priority_max(policy);
  213707. pri = ((maxp - minp) / 2) * (priority - 1) / 9;
  213708. if (param.__sched_priority >= (minp + (maxp - minp) / 2))
  213709. // Realtime process priority
  213710. param.__sched_priority = minp + ((maxp - minp) / 2) + pri;
  213711. else
  213712. // High process priority
  213713. param.__sched_priority = minp + pri;
  213714. param.sched_priority = jlimit (1, 127, 1 + (priority * 126) / 11);
  213715. return pthread_setschedparam ((pthread_t) handle, policy, &param) == 0;
  213716. }
  213717. return false;
  213718. }
  213719. void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask) throw()
  213720. {
  213721. #if SUPPORT_AFFINITIES
  213722. cpu_set_t affinity;
  213723. CPU_ZERO (&affinity);
  213724. for (int i = 0; i < 32; ++i)
  213725. if ((affinityMask & (1 << i)) != 0)
  213726. CPU_SET (i, &affinity);
  213727. /*
  213728. N.B. If this line causes a compile error, then you've probably not got the latest
  213729. version of glibc installed.
  213730. If you don't want to update your copy of glibc and don't care about cpu affinities,
  213731. then you can just disable all this stuff by removing the SUPPORT_AFFINITIES macro
  213732. from the linuxincludes.h file.
  213733. */
  213734. sched_setaffinity (getpid(), sizeof (cpu_set_t), &affinity);
  213735. sched_yield();
  213736. #else
  213737. /* affinities aren't supported because either the appropriate header files weren't found,
  213738. or the SUPPORT_AFFINITIES macro was turned off in linuxheaders.h
  213739. */
  213740. jassertfalse
  213741. #endif
  213742. }
  213743. void Thread::yield() throw()
  213744. {
  213745. sched_yield();
  213746. }
  213747. // sets the process to 0=low priority, 1=normal, 2=high, 3=realtime
  213748. void Process::setPriority (ProcessPriority prior)
  213749. {
  213750. struct sched_param param;
  213751. int policy, maxp, minp;
  213752. const int p = (int) prior;
  213753. if (p <= 1)
  213754. policy = SCHED_OTHER;
  213755. else
  213756. policy = SCHED_RR;
  213757. minp = sched_get_priority_min (policy);
  213758. maxp = sched_get_priority_max (policy);
  213759. if (p < 2)
  213760. param.__sched_priority = 0;
  213761. else if (p == 2 )
  213762. // Set to middle of lower realtime priority range
  213763. param.__sched_priority = minp + (maxp - minp) / 4;
  213764. else
  213765. // Set to middle of higher realtime priority range
  213766. param.__sched_priority = minp + (3 * (maxp - minp) / 4);
  213767. pthread_setschedparam (pthread_self(), policy, &param);
  213768. }
  213769. void Process::terminate()
  213770. {
  213771. exit (0);
  213772. }
  213773. bool JUCE_CALLTYPE juce_isRunningUnderDebugger() throw()
  213774. {
  213775. static char testResult = 0;
  213776. if (testResult == 0)
  213777. {
  213778. testResult = (char) ptrace (PT_TRACE_ME, 0, 0, 0);
  213779. if (testResult >= 0)
  213780. {
  213781. ptrace (PT_DETACH, 0, (caddr_t) 1, 0);
  213782. testResult = 1;
  213783. }
  213784. }
  213785. return testResult < 0;
  213786. }
  213787. bool JUCE_CALLTYPE Process::isRunningUnderDebugger() throw()
  213788. {
  213789. return juce_isRunningUnderDebugger();
  213790. }
  213791. void Process::raisePrivilege()
  213792. {
  213793. // If running suid root, change effective user
  213794. // to root
  213795. if (geteuid() != 0 && getuid() == 0)
  213796. {
  213797. setreuid (geteuid(), getuid());
  213798. setregid (getegid(), getgid());
  213799. }
  213800. }
  213801. void Process::lowerPrivilege()
  213802. {
  213803. // If runing suid root, change effective user
  213804. // back to real user
  213805. if (geteuid() == 0 && getuid() != 0)
  213806. {
  213807. setreuid (geteuid(), getuid());
  213808. setregid (getegid(), getgid());
  213809. }
  213810. }
  213811. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  213812. void* PlatformUtilities::loadDynamicLibrary (const String& name)
  213813. {
  213814. return dlopen ((const char*) name.toUTF8(), RTLD_LOCAL | RTLD_NOW);
  213815. }
  213816. void PlatformUtilities::freeDynamicLibrary (void* handle)
  213817. {
  213818. dlclose(handle);
  213819. }
  213820. void* PlatformUtilities::getProcedureEntryPoint (void* libraryHandle, const String& procedureName)
  213821. {
  213822. return dlsym (libraryHandle, (const char*) procedureName);
  213823. }
  213824. #endif
  213825. #endif
  213826. /********* End of inlined file: juce_linux_Threads.cpp *********/
  213827. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  213828. /********* Start of inlined file: juce_linux_Messaging.cpp *********/
  213829. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  213830. // compiled on its own).
  213831. #ifdef JUCE_INCLUDED_FILE
  213832. #ifdef JUCE_DEBUG
  213833. #define JUCE_DEBUG_XERRORS 1
  213834. #endif
  213835. Display* display = 0; // This is also referenced from WindowDriver.cpp
  213836. static Window juce_messageWindowHandle = None;
  213837. #define SpecialAtom "JUCESpecialAtom"
  213838. #define BroadcastAtom "JUCEBroadcastAtom"
  213839. #define SpecialCallbackAtom "JUCESpecialCallbackAtom"
  213840. static Atom specialId;
  213841. static Atom broadcastId;
  213842. static Atom specialCallbackId;
  213843. // This is referenced from WindowDriver.cpp
  213844. XContext improbableNumber;
  213845. // Defined in WindowDriver.cpp
  213846. extern void juce_windowMessageReceive (XEvent* event);
  213847. struct MessageThreadFuncCall
  213848. {
  213849. MessageCallbackFunction* func;
  213850. void* parameter;
  213851. void* result;
  213852. CriticalSection lock;
  213853. WaitableEvent event;
  213854. };
  213855. static bool errorCondition = false;
  213856. static XErrorHandler oldErrorHandler = (XErrorHandler) 0;
  213857. static XIOErrorHandler oldIOErrorHandler = (XIOErrorHandler) 0;
  213858. // (defined in another file to avoid problems including certain headers in this one)
  213859. extern bool juce_isRunningAsApplication();
  213860. // Usually happens when client-server connection is broken
  213861. static int ioErrorHandler (Display* display)
  213862. {
  213863. DBG (T("ERROR: connection to X server broken.. terminating."));
  213864. errorCondition = true;
  213865. if (juce_isRunningAsApplication())
  213866. Process::terminate();
  213867. return 0;
  213868. }
  213869. // A protocol error has occurred
  213870. static int errorHandler (Display* display, XErrorEvent* event)
  213871. {
  213872. #ifdef JUCE_DEBUG_XERRORS
  213873. char errorStr[64] = { 0 };
  213874. char requestStr[64] = { 0 };
  213875. XGetErrorText (display, event->error_code, errorStr, 64);
  213876. XGetErrorDatabaseText (display,
  213877. "XRequest",
  213878. (const char*) String (event->request_code),
  213879. "Unknown",
  213880. requestStr,
  213881. 64);
  213882. DBG (T("ERROR: X returned ") + String (errorStr) + T(" for operation ") + String (requestStr));
  213883. #endif
  213884. return 0;
  213885. }
  213886. static bool breakIn = false;
  213887. // Breakin from keyboard
  213888. static void sig_handler (int sig)
  213889. {
  213890. if (sig == SIGINT)
  213891. {
  213892. breakIn = true;
  213893. return;
  213894. }
  213895. static bool reentrant = false;
  213896. if (reentrant == false)
  213897. {
  213898. reentrant = true;
  213899. // Illegal instruction
  213900. fflush (stdout);
  213901. Logger::outputDebugString ("ERROR: Program executed illegal instruction.. terminating");
  213902. errorCondition = true;
  213903. if (juce_isRunningAsApplication())
  213904. Process::terminate();
  213905. }
  213906. else
  213907. {
  213908. if (juce_isRunningAsApplication())
  213909. exit(0);
  213910. }
  213911. }
  213912. void MessageManager::doPlatformSpecificInitialisation()
  213913. {
  213914. // Initialise xlib for multiple thread support
  213915. static bool initThreadCalled = false;
  213916. if (! initThreadCalled)
  213917. {
  213918. if (! XInitThreads())
  213919. {
  213920. // This is fatal! Print error and closedown
  213921. Logger::outputDebugString ("Failed to initialise xlib thread support.");
  213922. if (juce_isRunningAsApplication())
  213923. Process::terminate();
  213924. return;
  213925. }
  213926. initThreadCalled = true;
  213927. }
  213928. // This is called if the client/server connection is broken
  213929. oldIOErrorHandler = XSetIOErrorHandler (ioErrorHandler);
  213930. // This is called if a protocol error occurs
  213931. oldErrorHandler = XSetErrorHandler (errorHandler);
  213932. // Install signal handler for break-in
  213933. struct sigaction saction;
  213934. sigset_t maskSet;
  213935. sigemptyset (&maskSet);
  213936. saction.sa_handler = sig_handler;
  213937. saction.sa_mask = maskSet;
  213938. saction.sa_flags = 0;
  213939. sigaction (SIGINT, &saction, NULL);
  213940. #ifndef _DEBUG
  213941. // Setup signal handlers for various fatal errors
  213942. sigaction (SIGILL, &saction, NULL);
  213943. sigaction (SIGBUS, &saction, NULL);
  213944. sigaction (SIGFPE, &saction, NULL);
  213945. sigaction (SIGSEGV, &saction, NULL);
  213946. sigaction (SIGSYS, &saction, NULL);
  213947. #endif
  213948. String displayName (getenv ("DISPLAY"));
  213949. if (displayName.isEmpty())
  213950. displayName = T(":0.0");
  213951. display = XOpenDisplay (displayName);
  213952. if (display == 0)
  213953. {
  213954. // This is fatal! Print error and closedown
  213955. Logger::outputDebugString ("Failed to open the X display.");
  213956. if (juce_isRunningAsApplication())
  213957. Process::terminate();
  213958. return;
  213959. }
  213960. // Get defaults for various properties
  213961. int screen = DefaultScreen (display);
  213962. Window root = RootWindow (display, screen);
  213963. Visual* visual = DefaultVisual (display, screen);
  213964. // Create atoms for our ClientMessages (these cannot be deleted)
  213965. specialId = XInternAtom (display, SpecialAtom, false);
  213966. broadcastId = XInternAtom (display, BroadcastAtom, false);
  213967. specialCallbackId = XInternAtom (display, SpecialCallbackAtom, false);
  213968. // Create a context to store user data associated with Windows we
  213969. // create in WindowDriver
  213970. improbableNumber = XUniqueContext();
  213971. // We're only interested in client messages for this window
  213972. // which are always sent
  213973. XSetWindowAttributes swa;
  213974. swa.event_mask = NoEventMask;
  213975. // Create our message window (this will never be mapped)
  213976. juce_messageWindowHandle = XCreateWindow (display, root,
  213977. 0, 0, 1, 1, 0, 0, InputOnly,
  213978. visual, CWEventMask, &swa);
  213979. }
  213980. void MessageManager::doPlatformSpecificShutdown()
  213981. {
  213982. if (errorCondition == false)
  213983. {
  213984. XDestroyWindow (display, juce_messageWindowHandle);
  213985. XCloseDisplay (display);
  213986. // reset pointers
  213987. juce_messageWindowHandle = 0;
  213988. display = 0;
  213989. // Restore original error handlers
  213990. XSetIOErrorHandler (oldIOErrorHandler);
  213991. oldIOErrorHandler = 0;
  213992. XSetErrorHandler (oldErrorHandler);
  213993. oldErrorHandler = 0;
  213994. }
  213995. }
  213996. bool juce_postMessageToSystemQueue (void* message)
  213997. {
  213998. if (errorCondition)
  213999. return false;
  214000. XClientMessageEvent clientMsg;
  214001. clientMsg.display = display;
  214002. clientMsg.window = juce_messageWindowHandle;
  214003. clientMsg.type = ClientMessage;
  214004. clientMsg.format = 32;
  214005. clientMsg.message_type = specialId;
  214006. #if JUCE_64BIT
  214007. clientMsg.data.l[0] = (long) (0x00000000ffffffff & (((uint64) message) >> 32));
  214008. clientMsg.data.l[1] = (long) (0x00000000ffffffff & (long) message);
  214009. #else
  214010. clientMsg.data.l[0] = (long) message;
  214011. #endif
  214012. XSendEvent (display, juce_messageWindowHandle, false,
  214013. NoEventMask, (XEvent*) &clientMsg);
  214014. XFlush (display); // This is necessary to ensure the event is delivered
  214015. return true;
  214016. }
  214017. void MessageManager::broadcastMessage (const String& value) throw()
  214018. {
  214019. }
  214020. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* func,
  214021. void* parameter)
  214022. {
  214023. void* retVal = 0;
  214024. if (! errorCondition)
  214025. {
  214026. if (! isThisTheMessageThread())
  214027. {
  214028. static MessageThreadFuncCall messageFuncCallContext;
  214029. const ScopedLock sl (messageFuncCallContext.lock);
  214030. XClientMessageEvent clientMsg;
  214031. clientMsg.display = display;
  214032. clientMsg.window = juce_messageWindowHandle;
  214033. clientMsg.type = ClientMessage;
  214034. clientMsg.format = 32;
  214035. clientMsg.message_type = specialCallbackId;
  214036. #if JUCE_64BIT
  214037. clientMsg.data.l[0] = (long) (0x00000000ffffffff & (((uint64) &messageFuncCallContext) >> 32));
  214038. clientMsg.data.l[1] = (long) (0x00000000ffffffff & (uint64) &messageFuncCallContext);
  214039. #else
  214040. clientMsg.data.l[0] = (long) &messageFuncCallContext;
  214041. #endif
  214042. messageFuncCallContext.func = func;
  214043. messageFuncCallContext.parameter = parameter;
  214044. if (XSendEvent (display, juce_messageWindowHandle, false, NoEventMask, (XEvent*) &clientMsg) == 0)
  214045. return 0;
  214046. XFlush (display); // This is necessary to ensure the event is delivered
  214047. // Wait for it to complete before continuing
  214048. messageFuncCallContext.event.wait();
  214049. retVal = messageFuncCallContext.result;
  214050. }
  214051. else
  214052. {
  214053. // Just call the function directly
  214054. retVal = func (parameter);
  214055. }
  214056. }
  214057. return retVal;
  214058. }
  214059. bool juce_dispatchNextMessageOnSystemQueue (bool returnIfNoPendingMessages)
  214060. {
  214061. if (errorCondition)
  214062. return false;
  214063. if (breakIn)
  214064. {
  214065. errorCondition = true;
  214066. if (juce_isRunningAsApplication())
  214067. Process::terminate();
  214068. return false;
  214069. }
  214070. if (returnIfNoPendingMessages && ! XPending (display))
  214071. return false;
  214072. XEvent evt;
  214073. XNextEvent (display, &evt);
  214074. if (evt.type == ClientMessage && evt.xany.window == juce_messageWindowHandle)
  214075. {
  214076. XClientMessageEvent* const clientMsg = (XClientMessageEvent*) &evt;
  214077. if (clientMsg->format != 32)
  214078. {
  214079. jassertfalse
  214080. DBG ("Error: juce_dispatchNextMessageOnSystemQueue received malformed client message.");
  214081. }
  214082. else
  214083. {
  214084. JUCE_TRY
  214085. {
  214086. #if JUCE_64BIT
  214087. void* const messagePtr
  214088. = (void*) ((0xffffffff00000000 & (((uint64) clientMsg->data.l[0]) << 32))
  214089. | (clientMsg->data.l[1] & 0x00000000ffffffff));
  214090. #else
  214091. void* const messagePtr = (void*) (clientMsg->data.l[0]);
  214092. #endif
  214093. if (clientMsg->message_type == specialId)
  214094. {
  214095. MessageManager::getInstance()->deliverMessage (messagePtr);
  214096. }
  214097. else if (clientMsg->message_type == specialCallbackId)
  214098. {
  214099. MessageThreadFuncCall* const call = (MessageThreadFuncCall*) messagePtr;
  214100. MessageCallbackFunction* func = call->func;
  214101. call->result = (*func) (call->parameter);
  214102. call->event.signal();
  214103. }
  214104. else if (clientMsg->message_type == broadcastId)
  214105. {
  214106. #if 0
  214107. TCHAR buffer[8192];
  214108. zeromem (buffer, sizeof (buffer));
  214109. if (GlobalGetAtomName ((ATOM) lParam, buffer, 8192) != 0)
  214110. mq->deliverBroadcastMessage (String (buffer));
  214111. #endif
  214112. }
  214113. else
  214114. {
  214115. DBG ("Error: juce_dispatchNextMessageOnSystemQueue received unknown client message.");
  214116. }
  214117. }
  214118. JUCE_CATCH_ALL
  214119. }
  214120. }
  214121. else if (evt.xany.window != juce_messageWindowHandle)
  214122. {
  214123. juce_windowMessageReceive (&evt);
  214124. }
  214125. return true;
  214126. }
  214127. #endif
  214128. /********* End of inlined file: juce_linux_Messaging.cpp *********/
  214129. /********* Start of inlined file: juce_linux_Fonts.cpp *********/
  214130. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  214131. // compiled on its own).
  214132. #ifdef JUCE_INCLUDED_FILE
  214133. class FreeTypeFontFace
  214134. {
  214135. public:
  214136. enum FontStyle
  214137. {
  214138. Plain = 0,
  214139. Bold = 1,
  214140. Italic = 2
  214141. };
  214142. struct FontNameIndex
  214143. {
  214144. String fileName;
  214145. int faceIndex;
  214146. };
  214147. FreeTypeFontFace (const String& familyName)
  214148. : hasSerif (false),
  214149. monospaced (false)
  214150. {
  214151. family = familyName;
  214152. }
  214153. void setFileName (const String& name,
  214154. const int faceIndex,
  214155. FontStyle style)
  214156. {
  214157. if (names[(int) style].fileName.isEmpty())
  214158. {
  214159. names[(int) style].fileName = name;
  214160. names[(int) style].faceIndex = faceIndex;
  214161. }
  214162. }
  214163. const String& getFamilyName() const throw()
  214164. {
  214165. return family;
  214166. }
  214167. const String& getFileName (int style, int* faceIndex) const throw()
  214168. {
  214169. *faceIndex = names [style].faceIndex;
  214170. return names[style].fileName;
  214171. }
  214172. void setMonospaced (bool mono) { monospaced = mono; }
  214173. bool getMonospaced () const throw() { return monospaced; }
  214174. void setSerif (const bool serif) { hasSerif = serif; }
  214175. bool getSerif () const throw() { return hasSerif; }
  214176. private:
  214177. String family;
  214178. FontNameIndex names[4];
  214179. bool hasSerif, monospaced;
  214180. };
  214181. class FreeTypeInterface : public DeletedAtShutdown
  214182. {
  214183. public:
  214184. FreeTypeInterface() throw()
  214185. : lastFace (0),
  214186. lastBold (false),
  214187. lastItalic (false)
  214188. {
  214189. if (FT_Init_FreeType (&ftLib) != 0)
  214190. {
  214191. ftLib = 0;
  214192. DBG (T("Failed to initialize FreeType"));
  214193. }
  214194. StringArray fontDirs;
  214195. fontDirs.addTokens (String (getenv ("JUCE_FONT_PATH")), T(";,"), 0);
  214196. fontDirs.removeEmptyStrings (true);
  214197. if (fontDirs.size() == 0)
  214198. {
  214199. XmlDocument fontsConfig (File ("/etc/fonts/fonts.conf"));
  214200. XmlElement* const fontsInfo = fontsConfig.getDocumentElement();
  214201. if (fontsInfo != 0)
  214202. {
  214203. forEachXmlChildElementWithTagName (*fontsInfo, e, T("dir"))
  214204. {
  214205. fontDirs.add (e->getAllSubText().trim());
  214206. }
  214207. delete fontsInfo;
  214208. }
  214209. }
  214210. if (fontDirs.size() == 0)
  214211. fontDirs.add ("/usr/X11R6/lib/X11/fonts");
  214212. for (int i = 0; i < fontDirs.size(); ++i)
  214213. enumerateFaces (fontDirs[i]);
  214214. }
  214215. ~FreeTypeInterface() throw()
  214216. {
  214217. if (lastFace != 0)
  214218. FT_Done_Face (lastFace);
  214219. if (ftLib != 0)
  214220. FT_Done_FreeType (ftLib);
  214221. clearSingletonInstance();
  214222. }
  214223. FreeTypeFontFace* findOrCreate (const String& familyName,
  214224. const bool create = false) throw()
  214225. {
  214226. for (int i = 0; i < faces.size(); i++)
  214227. if (faces[i]->getFamilyName() == familyName)
  214228. return faces[i];
  214229. if (! create)
  214230. return NULL;
  214231. FreeTypeFontFace* newFace = new FreeTypeFontFace (familyName);
  214232. faces.add (newFace);
  214233. return newFace;
  214234. }
  214235. // Enumerate all font faces available in a given directory
  214236. void enumerateFaces (const String& path) throw()
  214237. {
  214238. File dirPath (path);
  214239. if (path.isEmpty() || ! dirPath.isDirectory())
  214240. return;
  214241. DirectoryIterator di (dirPath, true);
  214242. while (di.next())
  214243. {
  214244. File possible (di.getFile());
  214245. if (possible.hasFileExtension (T("ttf"))
  214246. || possible.hasFileExtension (T("pfb"))
  214247. || possible.hasFileExtension (T("pcf")))
  214248. {
  214249. FT_Face face;
  214250. int faceIndex = 0;
  214251. int numFaces = 0;
  214252. do
  214253. {
  214254. if (FT_New_Face (ftLib,
  214255. possible.getFullPathName(),
  214256. faceIndex,
  214257. &face) == 0)
  214258. {
  214259. if (faceIndex == 0)
  214260. numFaces = face->num_faces;
  214261. if ((face->face_flags & FT_FACE_FLAG_SCALABLE) != 0)
  214262. {
  214263. FreeTypeFontFace* const newFace = findOrCreate (face->family_name, true);
  214264. int style = (int) FreeTypeFontFace::Plain;
  214265. if ((face->style_flags & FT_STYLE_FLAG_BOLD) != 0)
  214266. style |= (int) FreeTypeFontFace::Bold;
  214267. if ((face->style_flags & FT_STYLE_FLAG_ITALIC) != 0)
  214268. style |= (int) FreeTypeFontFace::Italic;
  214269. newFace->setFileName (possible.getFullPathName(), faceIndex, (FreeTypeFontFace::FontStyle) style);
  214270. if ((face->face_flags & FT_FACE_FLAG_FIXED_WIDTH) != 0)
  214271. newFace->setMonospaced (true);
  214272. else
  214273. newFace->setMonospaced (false);
  214274. // Surely there must be a better way to do this?
  214275. if (String (face->family_name).containsIgnoreCase (T("Sans"))
  214276. || String (face->family_name).containsIgnoreCase (T("Verdana"))
  214277. || String (face->family_name).containsIgnoreCase (T("Arial")))
  214278. {
  214279. newFace->setSerif (false);
  214280. }
  214281. else
  214282. {
  214283. newFace->setSerif (true);
  214284. }
  214285. }
  214286. FT_Done_Face (face);
  214287. }
  214288. ++faceIndex;
  214289. }
  214290. while (faceIndex < numFaces);
  214291. }
  214292. }
  214293. }
  214294. // Create a FreeType face object for a given font
  214295. FT_Face createFT_Face (const String& fontName,
  214296. const bool bold,
  214297. const bool italic) throw()
  214298. {
  214299. FT_Face face = NULL;
  214300. if (fontName == lastFontName && bold == lastBold && italic == lastItalic)
  214301. {
  214302. face = lastFace;
  214303. }
  214304. else
  214305. {
  214306. if (lastFace)
  214307. {
  214308. FT_Done_Face (lastFace);
  214309. lastFace = NULL;
  214310. }
  214311. lastFontName = fontName;
  214312. lastBold = bold;
  214313. lastItalic = italic;
  214314. FreeTypeFontFace* const ftFace = findOrCreate (fontName);
  214315. if (ftFace != 0)
  214316. {
  214317. int style = (int) FreeTypeFontFace::Plain;
  214318. if (bold)
  214319. style |= (int) FreeTypeFontFace::Bold;
  214320. if (italic)
  214321. style |= (int) FreeTypeFontFace::Italic;
  214322. int faceIndex;
  214323. String fileName (ftFace->getFileName (style, &faceIndex));
  214324. if (fileName.isEmpty())
  214325. {
  214326. style ^= (int) FreeTypeFontFace::Bold;
  214327. fileName = ftFace->getFileName (style, &faceIndex);
  214328. if (fileName.isEmpty())
  214329. {
  214330. style ^= (int) FreeTypeFontFace::Bold;
  214331. style ^= (int) FreeTypeFontFace::Italic;
  214332. fileName = ftFace->getFileName (style, &faceIndex);
  214333. if (! fileName.length())
  214334. {
  214335. style ^= (int) FreeTypeFontFace::Bold;
  214336. fileName = ftFace->getFileName (style, &faceIndex);
  214337. }
  214338. }
  214339. }
  214340. if (! FT_New_Face (ftLib, (const char*) fileName, faceIndex, &lastFace))
  214341. {
  214342. face = lastFace;
  214343. // If there isn't a unicode charmap then select the first one.
  214344. if (FT_Select_Charmap (face, ft_encoding_unicode))
  214345. FT_Set_Charmap (face, face->charmaps[0]);
  214346. }
  214347. }
  214348. }
  214349. return face;
  214350. }
  214351. bool addGlyph (FT_Face face, Typeface& dest, uint32 character) throw()
  214352. {
  214353. const unsigned int glyphIndex = FT_Get_Char_Index (face, character);
  214354. const float height = (float) (face->ascender - face->descender);
  214355. const float scaleX = 1.0f / height;
  214356. const float scaleY = -1.0f / height;
  214357. Path destShape;
  214358. #define CONVERTX(val) (scaleX * (val).x)
  214359. #define CONVERTY(val) (scaleY * (val).y)
  214360. if (FT_Load_Glyph (face, glyphIndex, FT_LOAD_NO_SCALE
  214361. | FT_LOAD_NO_BITMAP
  214362. | FT_LOAD_IGNORE_TRANSFORM) != 0
  214363. || face->glyph->format != ft_glyph_format_outline)
  214364. {
  214365. return false;
  214366. }
  214367. const FT_Outline* const outline = &face->glyph->outline;
  214368. const short* const contours = outline->contours;
  214369. const char* const tags = outline->tags;
  214370. FT_Vector* const points = outline->points;
  214371. for (int c = 0; c < outline->n_contours; c++)
  214372. {
  214373. const int startPoint = (c == 0) ? 0 : contours [c - 1] + 1;
  214374. const int endPoint = contours[c];
  214375. for (int p = startPoint; p <= endPoint; p++)
  214376. {
  214377. const float x = CONVERTX (points[p]);
  214378. const float y = CONVERTY (points[p]);
  214379. if (p == startPoint)
  214380. {
  214381. if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Conic)
  214382. {
  214383. float x2 = CONVERTX (points [endPoint]);
  214384. float y2 = CONVERTY (points [endPoint]);
  214385. if (FT_CURVE_TAG (tags[endPoint]) != FT_Curve_Tag_On)
  214386. {
  214387. x2 = (x + x2) * 0.5f;
  214388. y2 = (y + y2) * 0.5f;
  214389. }
  214390. destShape.startNewSubPath (x2, y2);
  214391. }
  214392. else
  214393. {
  214394. destShape.startNewSubPath (x, y);
  214395. }
  214396. }
  214397. if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_On)
  214398. {
  214399. if (p != startPoint)
  214400. destShape.lineTo (x, y);
  214401. }
  214402. else if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Conic)
  214403. {
  214404. const int nextIndex = (p == endPoint) ? startPoint : p + 1;
  214405. float x2 = CONVERTX (points [nextIndex]);
  214406. float y2 = CONVERTY (points [nextIndex]);
  214407. if (FT_CURVE_TAG (tags [nextIndex]) == FT_Curve_Tag_Conic)
  214408. {
  214409. x2 = (x + x2) * 0.5f;
  214410. y2 = (y + y2) * 0.5f;
  214411. }
  214412. else
  214413. {
  214414. ++p;
  214415. }
  214416. destShape.quadraticTo (x, y, x2, y2);
  214417. }
  214418. else if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Cubic)
  214419. {
  214420. if (p >= endPoint)
  214421. return false;
  214422. const int next1 = p + 1;
  214423. const int next2 = (p == (endPoint - 1)) ? startPoint : p + 2;
  214424. const float x2 = CONVERTX (points [next1]);
  214425. const float y2 = CONVERTY (points [next1]);
  214426. const float x3 = CONVERTX (points [next2]);
  214427. const float y3 = CONVERTY (points [next2]);
  214428. if (FT_CURVE_TAG (tags[next1]) != FT_Curve_Tag_Cubic
  214429. || FT_CURVE_TAG (tags[next2]) != FT_Curve_Tag_On)
  214430. return false;
  214431. destShape.cubicTo (x, y, x2, y2, x3, y3);
  214432. p += 2;
  214433. }
  214434. }
  214435. destShape.closeSubPath();
  214436. }
  214437. dest.addGlyph (character, destShape, face->glyph->metrics.horiAdvance/height);
  214438. if ((face->face_flags & FT_FACE_FLAG_KERNING) != 0)
  214439. addKerning (face, dest, character, glyphIndex);
  214440. return true;
  214441. }
  214442. void addKerning (FT_Face face, Typeface& dest, const uint32 character, const uint32 glyphIndex) throw()
  214443. {
  214444. const float height = (float) (face->ascender - face->descender);
  214445. uint32 rightGlyphIndex;
  214446. uint32 rightCharCode = FT_Get_First_Char (face, &rightGlyphIndex);
  214447. while (rightGlyphIndex != 0)
  214448. {
  214449. FT_Vector kerning;
  214450. if (FT_Get_Kerning (face, glyphIndex, rightGlyphIndex, ft_kerning_unscaled, &kerning) == 0)
  214451. {
  214452. if (kerning.x != 0)
  214453. dest.addKerningPair (character, rightCharCode, kerning.x / height);
  214454. }
  214455. rightCharCode = FT_Get_Next_Char (face, rightCharCode, &rightGlyphIndex);
  214456. }
  214457. }
  214458. // Add a glyph to a font
  214459. bool addGlyphToFont (const uint32 character,
  214460. const tchar* fontName, bool bold, bool italic,
  214461. Typeface& dest) throw()
  214462. {
  214463. FT_Face face = createFT_Face (fontName, bold, italic);
  214464. if (face != 0)
  214465. return addGlyph (face, dest, character);
  214466. return false;
  214467. }
  214468. // Create a Typeface object for given name/style
  214469. bool createTypeface (const String& fontName,
  214470. const bool bold, const bool italic,
  214471. Typeface& dest,
  214472. const bool addAllGlyphs) throw()
  214473. {
  214474. dest.clear();
  214475. dest.setName (fontName);
  214476. dest.setBold (bold);
  214477. dest.setItalic (italic);
  214478. FT_Face face = createFT_Face (fontName, bold, italic);
  214479. if (face == 0)
  214480. {
  214481. #ifdef JUCE_DEBUG
  214482. String msg (T("Failed to create typeface: "));
  214483. msg << fontName << " " << (bold ? 'B' : ' ') << (italic ? 'I' : ' ');
  214484. DBG (msg);
  214485. #endif
  214486. return face;
  214487. }
  214488. const float height = (float) (face->ascender - face->descender);
  214489. dest.setAscent (face->ascender / height);
  214490. dest.setDefaultCharacter (L' ');
  214491. if (addAllGlyphs)
  214492. {
  214493. uint32 glyphIndex;
  214494. uint32 charCode = FT_Get_First_Char (face, &glyphIndex);
  214495. while (glyphIndex != 0)
  214496. {
  214497. addGlyph (face, dest, charCode);
  214498. charCode = FT_Get_Next_Char (face, charCode, &glyphIndex);
  214499. }
  214500. }
  214501. return true;
  214502. }
  214503. void getFamilyNames (StringArray& familyNames) const throw()
  214504. {
  214505. for (int i = 0; i < faces.size(); i++)
  214506. familyNames.add (faces[i]->getFamilyName());
  214507. }
  214508. void getMonospacedNames (StringArray& monoSpaced) const throw()
  214509. {
  214510. for (int i = 0; i < faces.size(); i++)
  214511. if (faces[i]->getMonospaced())
  214512. monoSpaced.add (faces[i]->getFamilyName());
  214513. }
  214514. void getSerifNames (StringArray& serif) const throw()
  214515. {
  214516. for (int i = 0; i < faces.size(); i++)
  214517. if (faces[i]->getSerif())
  214518. serif.add (faces[i]->getFamilyName());
  214519. }
  214520. void getSansSerifNames (StringArray& sansSerif) const throw()
  214521. {
  214522. for (int i = 0; i < faces.size(); i++)
  214523. if (! faces[i]->getSerif())
  214524. sansSerif.add (faces[i]->getFamilyName());
  214525. }
  214526. juce_DeclareSingleton_SingleThreaded_Minimal (FreeTypeInterface)
  214527. private:
  214528. FT_Library ftLib;
  214529. FT_Face lastFace;
  214530. String lastFontName;
  214531. bool lastBold, lastItalic;
  214532. OwnedArray<FreeTypeFontFace> faces;
  214533. };
  214534. juce_ImplementSingleton_SingleThreaded (FreeTypeInterface)
  214535. void Typeface::initialiseTypefaceCharacteristics (const String& fontName,
  214536. bool bold, bool italic,
  214537. bool addAllGlyphsToFont) throw()
  214538. {
  214539. FreeTypeInterface::getInstance()
  214540. ->createTypeface (fontName, bold, italic, *this, addAllGlyphsToFont);
  214541. }
  214542. bool Typeface::findAndAddSystemGlyph (juce_wchar character) throw()
  214543. {
  214544. return FreeTypeInterface::getInstance()
  214545. ->addGlyphToFont (character, getName(), isBold(), isItalic(), *this);
  214546. }
  214547. const StringArray Font::findAllTypefaceNames() throw()
  214548. {
  214549. StringArray s;
  214550. FreeTypeInterface::getInstance()->getFamilyNames (s);
  214551. s.sort (true);
  214552. return s;
  214553. }
  214554. static const String pickBestFont (const StringArray& names,
  214555. const char* const choicesString)
  214556. {
  214557. StringArray choices;
  214558. choices.addTokens (String (choicesString), T(","), 0);
  214559. choices.trim();
  214560. choices.removeEmptyStrings();
  214561. int i, j;
  214562. for (j = 0; j < choices.size(); ++j)
  214563. if (names.contains (choices[j], true))
  214564. return choices[j];
  214565. for (j = 0; j < choices.size(); ++j)
  214566. for (i = 0; i < names.size(); i++)
  214567. if (names[i].startsWithIgnoreCase (choices[j]))
  214568. return names[i];
  214569. for (j = 0; j < choices.size(); ++j)
  214570. for (i = 0; i < names.size(); i++)
  214571. if (names[i].containsIgnoreCase (choices[j]))
  214572. return names[i];
  214573. return names[0];
  214574. }
  214575. static const String linux_getDefaultSansSerifFontName()
  214576. {
  214577. StringArray allFonts;
  214578. FreeTypeInterface::getInstance()->getSansSerifNames (allFonts);
  214579. return pickBestFont (allFonts, "Verdana, Bitstream Vera Sans, Luxi Sans, Sans");
  214580. }
  214581. static const String linux_getDefaultSerifFontName()
  214582. {
  214583. StringArray allFonts;
  214584. FreeTypeInterface::getInstance()->getSerifNames (allFonts);
  214585. return pickBestFont (allFonts, "Bitstream Vera Serif, Times, Nimbus Roman, Serif");
  214586. }
  214587. static const String linux_getDefaultMonospacedFontName()
  214588. {
  214589. StringArray allFonts;
  214590. FreeTypeInterface::getInstance()->getMonospacedNames (allFonts);
  214591. return pickBestFont (allFonts, "Bitstream Vera Sans Mono, Courier, Sans Mono, Mono");
  214592. }
  214593. void Typeface::getDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed) throw()
  214594. {
  214595. defaultSans = linux_getDefaultSansSerifFontName();
  214596. defaultSerif = linux_getDefaultSerifFontName();
  214597. defaultFixed = linux_getDefaultMonospacedFontName();
  214598. }
  214599. #endif
  214600. /********* End of inlined file: juce_linux_Fonts.cpp *********/
  214601. /********* Start of inlined file: juce_linux_Windowing.cpp *********/
  214602. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  214603. // compiled on its own).
  214604. #ifdef JUCE_INCLUDED_FILE
  214605. #define TAKE_FOCUS 0
  214606. #define DELETE_WINDOW 1
  214607. #define SYSTEM_TRAY_REQUEST_DOCK 0
  214608. #define SYSTEM_TRAY_BEGIN_MESSAGE 1
  214609. #define SYSTEM_TRAY_CANCEL_MESSAGE 2
  214610. static const int repaintTimerPeriod = 1000 / 100; // 100 fps maximum
  214611. static Atom wm_ChangeState = None;
  214612. static Atom wm_State = None;
  214613. static Atom wm_Protocols = None;
  214614. static Atom wm_ProtocolList [2] = { None, None };
  214615. static Atom wm_ActiveWin = None;
  214616. #define ourDndVersion 3
  214617. static Atom XA_XdndAware = None;
  214618. static Atom XA_XdndEnter = None;
  214619. static Atom XA_XdndLeave = None;
  214620. static Atom XA_XdndPosition = None;
  214621. static Atom XA_XdndStatus = None;
  214622. static Atom XA_XdndDrop = None;
  214623. static Atom XA_XdndFinished = None;
  214624. static Atom XA_XdndSelection = None;
  214625. static Atom XA_XdndProxy = None;
  214626. static Atom XA_XdndTypeList = None;
  214627. static Atom XA_XdndActionList = None;
  214628. static Atom XA_XdndActionDescription = None;
  214629. static Atom XA_XdndActionCopy = None;
  214630. static Atom XA_XdndActionMove = None;
  214631. static Atom XA_XdndActionLink = None;
  214632. static Atom XA_XdndActionAsk = None;
  214633. static Atom XA_XdndActionPrivate = None;
  214634. static Atom XA_JXSelectionWindowProperty = None;
  214635. static Atom XA_MimeTextPlain = None;
  214636. static Atom XA_MimeTextUriList = None;
  214637. static Atom XA_MimeRootDrop = None;
  214638. static XErrorHandler oldHandler = 0;
  214639. static int trappedErrorCode = 0;
  214640. extern "C" int errorTrapHandler (Display* dpy, XErrorEvent* err)
  214641. {
  214642. trappedErrorCode = err->error_code;
  214643. return 0;
  214644. }
  214645. static void trapErrors()
  214646. {
  214647. trappedErrorCode = 0;
  214648. oldHandler = XSetErrorHandler (errorTrapHandler);
  214649. }
  214650. static bool untrapErrors()
  214651. {
  214652. XSetErrorHandler (oldHandler);
  214653. return (trappedErrorCode == 0);
  214654. }
  214655. static bool isActiveApplication = false;
  214656. bool Process::isForegroundProcess() throw()
  214657. {
  214658. return isActiveApplication;
  214659. }
  214660. // (used in the messaging code, declared here for build reasons)
  214661. bool juce_isRunningAsApplication()
  214662. {
  214663. return JUCEApplication::getInstance() != 0;
  214664. }
  214665. // These are defined in juce_linux_Messaging.cpp
  214666. extern Display* display;
  214667. extern XContext improbableNumber;
  214668. static const int eventMask = NoEventMask | KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask
  214669. | EnterWindowMask | LeaveWindowMask | PointerMotionMask | KeymapStateMask
  214670. | ExposureMask | StructureNotifyMask | FocusChangeMask;
  214671. static int pointerMap[5];
  214672. static int lastMousePosX = 0, lastMousePosY = 0;
  214673. enum MouseButtons
  214674. {
  214675. NoButton = 0,
  214676. LeftButton = 1,
  214677. MiddleButton = 2,
  214678. RightButton = 3,
  214679. WheelUp = 4,
  214680. WheelDown = 5
  214681. };
  214682. static void getMousePos (int& x, int& y, int& mouseMods) throw()
  214683. {
  214684. Window root, child;
  214685. int winx, winy;
  214686. unsigned int mask;
  214687. mouseMods = 0;
  214688. if (XQueryPointer (display,
  214689. RootWindow (display, DefaultScreen (display)),
  214690. &root, &child,
  214691. &x, &y, &winx, &winy, &mask) == False)
  214692. {
  214693. // Pointer not on the default screen
  214694. x = y = -1;
  214695. }
  214696. else
  214697. {
  214698. if ((mask & Button1Mask) != 0)
  214699. mouseMods |= ModifierKeys::leftButtonModifier;
  214700. if ((mask & Button2Mask) != 0)
  214701. mouseMods |= ModifierKeys::middleButtonModifier;
  214702. if ((mask & Button3Mask) != 0)
  214703. mouseMods |= ModifierKeys::rightButtonModifier;
  214704. }
  214705. }
  214706. static int AltMask = 0;
  214707. static int NumLockMask = 0;
  214708. static bool numLock = 0;
  214709. static bool capsLock = 0;
  214710. static char keyStates [32];
  214711. static void updateKeyStates (const int keycode, const bool press) throw()
  214712. {
  214713. const int keybyte = keycode >> 3;
  214714. const int keybit = (1 << (keycode & 7));
  214715. if (press)
  214716. keyStates [keybyte] |= keybit;
  214717. else
  214718. keyStates [keybyte] &= ~keybit;
  214719. }
  214720. static bool keyDown (const int keycode) throw()
  214721. {
  214722. const int keybyte = keycode >> 3;
  214723. const int keybit = (1 << (keycode & 7));
  214724. return (keyStates [keybyte] & keybit) != 0;
  214725. }
  214726. static const int extendedKeyModifier = 0x10000000;
  214727. bool KeyPress::isKeyCurrentlyDown (const int keyCode) throw()
  214728. {
  214729. int keysym;
  214730. if (keyCode & extendedKeyModifier)
  214731. {
  214732. keysym = 0xff00 | (keyCode & 0xff);
  214733. }
  214734. else
  214735. {
  214736. keysym = keyCode;
  214737. if (keysym == (XK_Tab & 0xff)
  214738. || keysym == (XK_Return & 0xff)
  214739. || keysym == (XK_Escape & 0xff)
  214740. || keysym == (XK_BackSpace & 0xff))
  214741. {
  214742. keysym |= 0xff00;
  214743. }
  214744. }
  214745. return keyDown (XKeysymToKeycode (display, keysym));
  214746. }
  214747. // Alt and Num lock are not defined by standard X
  214748. // modifier constants: check what they're mapped to
  214749. static void getModifierMapping() throw()
  214750. {
  214751. const int altLeftCode = XKeysymToKeycode (display, XK_Alt_L);
  214752. const int numLockCode = XKeysymToKeycode (display, XK_Num_Lock);
  214753. AltMask = 0;
  214754. NumLockMask = 0;
  214755. XModifierKeymap* mapping = XGetModifierMapping (display);
  214756. if (mapping)
  214757. {
  214758. for (int i = 0; i < 8; i++)
  214759. {
  214760. if (mapping->modifiermap [i << 1] == altLeftCode)
  214761. AltMask = 1 << i;
  214762. else if (mapping->modifiermap [i << 1] == numLockCode)
  214763. NumLockMask = 1 << i;
  214764. }
  214765. XFreeModifiermap (mapping);
  214766. }
  214767. }
  214768. static int currentModifiers = 0;
  214769. void ModifierKeys::updateCurrentModifiers() throw()
  214770. {
  214771. currentModifierFlags = currentModifiers;
  214772. }
  214773. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  214774. {
  214775. int x, y, mouseMods;
  214776. getMousePos (x, y, mouseMods);
  214777. currentModifiers &= ~ModifierKeys::allMouseButtonModifiers;
  214778. currentModifiers |= mouseMods;
  214779. return ModifierKeys (currentModifiers);
  214780. }
  214781. static void updateKeyModifiers (const int status) throw()
  214782. {
  214783. currentModifiers &= ~(ModifierKeys::shiftModifier
  214784. | ModifierKeys::ctrlModifier
  214785. | ModifierKeys::altModifier);
  214786. if (status & ShiftMask)
  214787. currentModifiers |= ModifierKeys::shiftModifier;
  214788. if (status & ControlMask)
  214789. currentModifiers |= ModifierKeys::ctrlModifier;
  214790. if (status & AltMask)
  214791. currentModifiers |= ModifierKeys::altModifier;
  214792. numLock = ((status & NumLockMask) != 0);
  214793. capsLock = ((status & LockMask) != 0);
  214794. }
  214795. static bool updateKeyModifiersFromSym (KeySym sym, const bool press) throw()
  214796. {
  214797. int modifier = 0;
  214798. bool isModifier = true;
  214799. switch (sym)
  214800. {
  214801. case XK_Shift_L:
  214802. case XK_Shift_R:
  214803. modifier = ModifierKeys::shiftModifier;
  214804. break;
  214805. case XK_Control_L:
  214806. case XK_Control_R:
  214807. modifier = ModifierKeys::ctrlModifier;
  214808. break;
  214809. case XK_Alt_L:
  214810. case XK_Alt_R:
  214811. modifier = ModifierKeys::altModifier;
  214812. break;
  214813. case XK_Num_Lock:
  214814. if (press)
  214815. numLock = ! numLock;
  214816. break;
  214817. case XK_Caps_Lock:
  214818. if (press)
  214819. capsLock = ! capsLock;
  214820. break;
  214821. case XK_Scroll_Lock:
  214822. break;
  214823. default:
  214824. isModifier = false;
  214825. break;
  214826. }
  214827. if (modifier != 0)
  214828. {
  214829. if (press)
  214830. currentModifiers |= modifier;
  214831. else
  214832. currentModifiers &= ~modifier;
  214833. }
  214834. return isModifier;
  214835. }
  214836. #if JUCE_USE_XSHM
  214837. static bool isShmAvailable() throw()
  214838. {
  214839. static bool isChecked = false;
  214840. static bool isAvailable = false;
  214841. if (! isChecked)
  214842. {
  214843. isChecked = true;
  214844. int major, minor;
  214845. Bool pixmaps;
  214846. if (XShmQueryVersion (display, &major, &minor, &pixmaps))
  214847. {
  214848. trapErrors();
  214849. XShmSegmentInfo segmentInfo;
  214850. zerostruct (segmentInfo);
  214851. XImage* xImage = XShmCreateImage (display, DefaultVisual (display, DefaultScreen (display)),
  214852. 24, ZPixmap, 0, &segmentInfo, 50, 50);
  214853. if ((segmentInfo.shmid = shmget (IPC_PRIVATE,
  214854. xImage->bytes_per_line * xImage->height,
  214855. IPC_CREAT | 0777)) >= 0)
  214856. {
  214857. segmentInfo.shmaddr = (char*) shmat (segmentInfo.shmid, 0, 0);
  214858. if (segmentInfo.shmaddr != (void*) -1)
  214859. {
  214860. segmentInfo.readOnly = False;
  214861. xImage->data = segmentInfo.shmaddr;
  214862. XSync (display, False);
  214863. if (XShmAttach (display, &segmentInfo) != 0)
  214864. {
  214865. XSync (display, False);
  214866. XShmDetach (display, &segmentInfo);
  214867. isAvailable = true;
  214868. }
  214869. }
  214870. XFlush (display);
  214871. XDestroyImage (xImage);
  214872. shmdt (segmentInfo.shmaddr);
  214873. }
  214874. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  214875. isAvailable &= untrapErrors();
  214876. }
  214877. }
  214878. return isAvailable;
  214879. }
  214880. #endif
  214881. static Pixmap juce_createColourPixmapFromImage (Display* display, const Image& image)
  214882. {
  214883. const int width = image.getWidth();
  214884. const int height = image.getHeight();
  214885. uint32* const colour = (uint32*) juce_malloc (width * height * sizeof (uint32));
  214886. int index = 0;
  214887. for (int y = 0; y < height; ++y)
  214888. for (int x = 0; x < width; ++x)
  214889. colour[index++] = image.getPixelAt (x, y).getARGB();
  214890. XImage* ximage = XCreateImage (display, CopyFromParent, 24, ZPixmap,
  214891. 0, (char*) colour, width, height, 32, 0);
  214892. Pixmap pixmap = XCreatePixmap (display, DefaultRootWindow (display),
  214893. width, height, 24);
  214894. GC gc = XCreateGC (display, pixmap, 0, 0);
  214895. XPutImage (display, pixmap, gc, ximage, 0, 0, 0, 0, width, height);
  214896. XFreeGC (display, gc);
  214897. juce_free (colour);
  214898. return pixmap;
  214899. }
  214900. static Pixmap juce_createMaskPixmapFromImage (Display* display, const Image& image)
  214901. {
  214902. const int width = image.getWidth();
  214903. const int height = image.getHeight();
  214904. const int stride = (width + 7) >> 3;
  214905. uint8* const mask = (uint8*) juce_calloc (stride * height);
  214906. const bool msbfirst = (BitmapBitOrder (display) == MSBFirst);
  214907. for (int y = 0; y < height; ++y)
  214908. {
  214909. for (int x = 0; x < width; ++x)
  214910. {
  214911. const uint8 bit = (uint8) (1 << (msbfirst ? (7 - (x & 7)) : (x & 7)));
  214912. const int offset = y * stride + (x >> 3);
  214913. if (image.getPixelAt (x, y).getAlpha() >= 128)
  214914. mask[offset] |= bit;
  214915. }
  214916. }
  214917. Pixmap pixmap = XCreatePixmapFromBitmapData (display, DefaultRootWindow (display),
  214918. (char*) mask, width, height, 1, 0, 1);
  214919. juce_free (mask);
  214920. return pixmap;
  214921. }
  214922. class XBitmapImage : public Image
  214923. {
  214924. public:
  214925. XBitmapImage (const PixelFormat format_, const int w, const int h,
  214926. const bool clearImage, const bool is16Bit_)
  214927. : Image (format_, w, h),
  214928. is16Bit (is16Bit_)
  214929. {
  214930. jassert (format_ == RGB || format_ == ARGB);
  214931. pixelStride = (format_ == RGB) ? 3 : 4;
  214932. lineStride = ((w * pixelStride + 3) & ~3);
  214933. Visual* const visual = DefaultVisual (display, DefaultScreen (display));
  214934. #if JUCE_USE_XSHM
  214935. usingXShm = false;
  214936. if ((! is16Bit) && isShmAvailable())
  214937. {
  214938. zerostruct (segmentInfo);
  214939. xImage = XShmCreateImage (display, visual, 24, ZPixmap, 0, &segmentInfo, w, h);
  214940. if (xImage != 0)
  214941. {
  214942. if ((segmentInfo.shmid = shmget (IPC_PRIVATE,
  214943. xImage->bytes_per_line * xImage->height,
  214944. IPC_CREAT | 0777)) >= 0)
  214945. {
  214946. segmentInfo.shmaddr = (char*) shmat (segmentInfo.shmid, 0, 0);
  214947. if (segmentInfo.shmaddr != (void*) -1)
  214948. {
  214949. segmentInfo.readOnly = False;
  214950. xImage->data = segmentInfo.shmaddr;
  214951. imageData = (uint8*) segmentInfo.shmaddr;
  214952. XSync (display, False);
  214953. if (XShmAttach (display, &segmentInfo) != 0)
  214954. {
  214955. XSync (display, False);
  214956. usingXShm = true;
  214957. }
  214958. else
  214959. {
  214960. jassertfalse
  214961. }
  214962. }
  214963. else
  214964. {
  214965. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  214966. }
  214967. }
  214968. }
  214969. }
  214970. if (! usingXShm)
  214971. #endif
  214972. {
  214973. imageData = (uint8*) juce_malloc (lineStride * h);
  214974. if (format_ == ARGB && clearImage)
  214975. zeromem (imageData, h * lineStride);
  214976. xImage = (XImage*) juce_calloc (sizeof (XImage));
  214977. xImage->width = w;
  214978. xImage->height = h;
  214979. xImage->xoffset = 0;
  214980. xImage->format = ZPixmap;
  214981. xImage->data = (char*) imageData;
  214982. xImage->byte_order = ImageByteOrder (display);
  214983. xImage->bitmap_unit = BitmapUnit (display);
  214984. xImage->bitmap_bit_order = BitmapBitOrder (display);
  214985. xImage->bitmap_pad = 32;
  214986. xImage->depth = pixelStride * 8;
  214987. xImage->bytes_per_line = lineStride;
  214988. xImage->bits_per_pixel = pixelStride * 8;
  214989. xImage->red_mask = 0x00FF0000;
  214990. xImage->green_mask = 0x0000FF00;
  214991. xImage->blue_mask = 0x000000FF;
  214992. if (is16Bit)
  214993. {
  214994. const int pixelStride = 2;
  214995. const int lineStride = ((w * pixelStride + 3) & ~3);
  214996. xImage->data = (char*) juce_malloc (lineStride * h);
  214997. xImage->bitmap_pad = 16;
  214998. xImage->depth = pixelStride * 8;
  214999. xImage->bytes_per_line = lineStride;
  215000. xImage->bits_per_pixel = pixelStride * 8;
  215001. xImage->red_mask = visual->red_mask;
  215002. xImage->green_mask = visual->green_mask;
  215003. xImage->blue_mask = visual->blue_mask;
  215004. }
  215005. if (! XInitImage (xImage))
  215006. {
  215007. jassertfalse
  215008. }
  215009. }
  215010. }
  215011. ~XBitmapImage()
  215012. {
  215013. #if JUCE_USE_XSHM
  215014. if (usingXShm)
  215015. {
  215016. XShmDetach (display, &segmentInfo);
  215017. XFlush (display);
  215018. XDestroyImage (xImage);
  215019. shmdt (segmentInfo.shmaddr);
  215020. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  215021. }
  215022. else
  215023. #endif
  215024. {
  215025. juce_free (xImage->data);
  215026. xImage->data = 0;
  215027. XDestroyImage (xImage);
  215028. }
  215029. if (! is16Bit)
  215030. imageData = 0; // to stop the base class freeing this (for the 16-bit version we want it to free it)
  215031. }
  215032. void blitToWindow (Window window, int dx, int dy, int dw, int dh, int sx, int sy)
  215033. {
  215034. static GC gc = 0;
  215035. if (gc == 0)
  215036. gc = DefaultGC (display, DefaultScreen (display));
  215037. if (is16Bit)
  215038. {
  215039. const uint32 rMask = xImage->red_mask;
  215040. const uint32 rShiftL = jmax (0, getShiftNeeded (rMask));
  215041. const uint32 rShiftR = jmax (0, -getShiftNeeded (rMask));
  215042. const uint32 gMask = xImage->green_mask;
  215043. const uint32 gShiftL = jmax (0, getShiftNeeded (gMask));
  215044. const uint32 gShiftR = jmax (0, -getShiftNeeded (gMask));
  215045. const uint32 bMask = xImage->blue_mask;
  215046. const uint32 bShiftL = jmax (0, getShiftNeeded (bMask));
  215047. const uint32 bShiftR = jmax (0, -getShiftNeeded (bMask));
  215048. int ls, ps;
  215049. const uint8* const pixels = lockPixelDataReadOnly (0, 0, getWidth(), getHeight(), ls, ps);
  215050. for (int y = sy; y < sy + dh; ++y)
  215051. {
  215052. const uint8* p = pixels + y * ls + sx * ps;
  215053. for (int x = sx; x < sx + dw; ++x)
  215054. {
  215055. const PixelRGB* const pixel = (const PixelRGB*) p;
  215056. p += ps;
  215057. XPutPixel (xImage, x, y,
  215058. (((((uint32) pixel->getRed()) << rShiftL) >> rShiftR) & rMask)
  215059. | (((((uint32) pixel->getGreen()) << gShiftL) >> gShiftR) & gMask)
  215060. | (((((uint32) pixel->getBlue()) << bShiftL) >> bShiftR) & bMask));
  215061. }
  215062. }
  215063. releasePixelDataReadOnly (pixels);
  215064. }
  215065. // blit results to screen.
  215066. #if JUCE_USE_XSHM
  215067. if (usingXShm)
  215068. XShmPutImage (display, (::Drawable) window, gc, xImage, sx, sy, dx, dy, dw, dh, False);
  215069. else
  215070. #endif
  215071. XPutImage (display, (::Drawable) window, gc, xImage, sx, sy, dx, dy, dw, dh);
  215072. }
  215073. juce_UseDebuggingNewOperator
  215074. private:
  215075. XImage* xImage;
  215076. const bool is16Bit;
  215077. #if JUCE_USE_XSHM
  215078. XShmSegmentInfo segmentInfo;
  215079. bool usingXShm;
  215080. #endif
  215081. static int getShiftNeeded (const uint32 mask) throw()
  215082. {
  215083. for (int i = 32; --i >= 0;)
  215084. if (((mask >> i) & 1) != 0)
  215085. return i - 7;
  215086. jassertfalse
  215087. return 0;
  215088. }
  215089. };
  215090. #define checkMessageManagerIsLocked jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  215091. class LinuxComponentPeer : public ComponentPeer
  215092. {
  215093. public:
  215094. LinuxComponentPeer (Component* const component, const int windowStyleFlags)
  215095. : ComponentPeer (component, windowStyleFlags),
  215096. windowH (0),
  215097. parentWindow (0),
  215098. wx (0),
  215099. wy (0),
  215100. ww (0),
  215101. wh (0),
  215102. taskbarImage (0),
  215103. fullScreen (false),
  215104. entered (false),
  215105. mapped (false)
  215106. {
  215107. // it's dangerous to create a window on a thread other than the message thread..
  215108. checkMessageManagerIsLocked
  215109. repainter = new LinuxRepaintManager (this);
  215110. createWindow();
  215111. setTitle (component->getName());
  215112. }
  215113. ~LinuxComponentPeer()
  215114. {
  215115. // it's dangerous to delete a window on a thread other than the message thread..
  215116. checkMessageManagerIsLocked
  215117. deleteTaskBarIcon();
  215118. deleteIconPixmaps();
  215119. destroyWindow();
  215120. windowH = 0;
  215121. delete repainter;
  215122. }
  215123. void* getNativeHandle() const
  215124. {
  215125. return (void*) windowH;
  215126. }
  215127. static LinuxComponentPeer* getPeerFor (Window windowHandle) throw()
  215128. {
  215129. XPointer peer = 0;
  215130. if (! XFindContext (display, (XID) windowHandle, improbableNumber, &peer))
  215131. {
  215132. if (peer != 0 && ! ((LinuxComponentPeer*) peer)->isValidMessageListener())
  215133. peer = 0;
  215134. }
  215135. return (LinuxComponentPeer*) peer;
  215136. }
  215137. void setVisible (bool shouldBeVisible)
  215138. {
  215139. if (shouldBeVisible)
  215140. XMapWindow (display, windowH);
  215141. else
  215142. XUnmapWindow (display, windowH);
  215143. }
  215144. void setTitle (const String& title)
  215145. {
  215146. setWindowTitle (windowH, title);
  215147. }
  215148. void setPosition (int x, int y)
  215149. {
  215150. setBounds (x, y, ww, wh, false);
  215151. }
  215152. void setSize (int w, int h)
  215153. {
  215154. setBounds (wx, wy, w, h, false);
  215155. }
  215156. void setBounds (int x, int y, int w, int h, const bool isNowFullScreen)
  215157. {
  215158. fullScreen = isNowFullScreen;
  215159. if (windowH != 0)
  215160. {
  215161. const ComponentDeletionWatcher deletionChecker (component);
  215162. wx = x;
  215163. wy = y;
  215164. ww = jmax (1, w);
  215165. wh = jmax (1, h);
  215166. // Make sure the Window manager does what we want
  215167. XSizeHints* hints = XAllocSizeHints();
  215168. hints->flags = USSize | USPosition;
  215169. hints->width = ww;
  215170. hints->height = wh;
  215171. hints->x = wx;
  215172. hints->y = wy;
  215173. if ((getStyleFlags() & (windowHasTitleBar | windowIsResizable)) == windowHasTitleBar)
  215174. {
  215175. hints->min_width = hints->max_width = hints->width;
  215176. hints->min_height = hints->max_height = hints->height;
  215177. hints->flags |= PMinSize | PMaxSize;
  215178. }
  215179. XSetWMNormalHints (display, windowH, hints);
  215180. XFree (hints);
  215181. XMoveResizeWindow (display, windowH,
  215182. wx - windowBorder.getLeft(),
  215183. wy - windowBorder.getTop(), ww, wh);
  215184. if (! deletionChecker.hasBeenDeleted())
  215185. {
  215186. updateBorderSize();
  215187. handleMovedOrResized();
  215188. }
  215189. }
  215190. }
  215191. void getBounds (int& x, int& y, int& w, int& h) const
  215192. {
  215193. x = wx;
  215194. y = wy;
  215195. w = ww;
  215196. h = wh;
  215197. }
  215198. int getScreenX() const
  215199. {
  215200. return wx;
  215201. }
  215202. int getScreenY() const
  215203. {
  215204. return wy;
  215205. }
  215206. void relativePositionToGlobal (int& x, int& y)
  215207. {
  215208. x += wx;
  215209. y += wy;
  215210. }
  215211. void globalPositionToRelative (int& x, int& y)
  215212. {
  215213. x -= wx;
  215214. y -= wy;
  215215. }
  215216. void setMinimised (bool shouldBeMinimised)
  215217. {
  215218. if (shouldBeMinimised)
  215219. {
  215220. Window root = RootWindow (display, DefaultScreen (display));
  215221. XClientMessageEvent clientMsg;
  215222. clientMsg.display = display;
  215223. clientMsg.window = windowH;
  215224. clientMsg.type = ClientMessage;
  215225. clientMsg.format = 32;
  215226. clientMsg.message_type = wm_ChangeState;
  215227. clientMsg.data.l[0] = IconicState;
  215228. XSendEvent (display, root, false,
  215229. SubstructureRedirectMask | SubstructureNotifyMask,
  215230. (XEvent*) &clientMsg);
  215231. }
  215232. else
  215233. {
  215234. setVisible (true);
  215235. }
  215236. }
  215237. bool isMinimised() const
  215238. {
  215239. bool minimised = false;
  215240. unsigned char* stateProp;
  215241. unsigned long nitems, bytesLeft;
  215242. Atom actualType;
  215243. int actualFormat;
  215244. if (XGetWindowProperty (display, windowH, wm_State, 0, 64, False,
  215245. wm_State, &actualType, &actualFormat, &nitems, &bytesLeft,
  215246. &stateProp) == Success
  215247. && actualType == wm_State
  215248. && actualFormat == 32
  215249. && nitems > 0)
  215250. {
  215251. if (((unsigned long*) stateProp)[0] == IconicState)
  215252. minimised = true;
  215253. XFree (stateProp);
  215254. }
  215255. return minimised;
  215256. }
  215257. void setFullScreen (const bool shouldBeFullScreen)
  215258. {
  215259. Rectangle r (lastNonFullscreenBounds); // (get a copy of this before de-minimising)
  215260. setMinimised (false);
  215261. if (fullScreen != shouldBeFullScreen)
  215262. {
  215263. if (shouldBeFullScreen)
  215264. r = Desktop::getInstance().getMainMonitorArea();
  215265. if (! r.isEmpty())
  215266. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight(), shouldBeFullScreen);
  215267. getComponent()->repaint();
  215268. }
  215269. }
  215270. bool isFullScreen() const
  215271. {
  215272. return fullScreen;
  215273. }
  215274. bool isChildWindowOf (Window possibleParent) const
  215275. {
  215276. Window* windowList = 0;
  215277. uint32 windowListSize = 0;
  215278. Window parent, root;
  215279. if (XQueryTree (display, windowH, &root, &parent, &windowList, &windowListSize) != 0)
  215280. {
  215281. if (windowList != 0)
  215282. XFree (windowList);
  215283. return parent == possibleParent;
  215284. }
  215285. return false;
  215286. }
  215287. bool isFrontWindow() const
  215288. {
  215289. Window* windowList = 0;
  215290. uint32 windowListSize = 0;
  215291. bool result = false;
  215292. Window parent, root = RootWindow (display, DefaultScreen (display));
  215293. if (XQueryTree (display, root, &root, &parent, &windowList, &windowListSize) != 0)
  215294. {
  215295. for (int i = windowListSize; --i >= 0;)
  215296. {
  215297. LinuxComponentPeer* const peer = LinuxComponentPeer::getPeerFor (windowList[i]);
  215298. if (peer != 0)
  215299. {
  215300. result = (peer == this);
  215301. break;
  215302. }
  215303. }
  215304. }
  215305. if (windowList != 0)
  215306. XFree (windowList);
  215307. return result;
  215308. }
  215309. bool contains (int x, int y, bool trueIfInAChildWindow) const
  215310. {
  215311. jassert (x >= 0 && y >= 0 && x < ww && y < wh); // should only be called for points that are actually inside the bounds
  215312. if (((unsigned int) x) >= (unsigned int) ww
  215313. || ((unsigned int) y) >= (unsigned int) wh)
  215314. return false;
  215315. bool inFront = false;
  215316. for (int i = 0; i < Desktop::getInstance().getNumComponents(); ++i)
  215317. {
  215318. Component* const c = Desktop::getInstance().getComponent (i);
  215319. if (inFront)
  215320. {
  215321. if (c->contains (x + wx - c->getScreenX(),
  215322. y + wy - c->getScreenY()))
  215323. {
  215324. return false;
  215325. }
  215326. }
  215327. else if (c == getComponent())
  215328. {
  215329. inFront = true;
  215330. }
  215331. }
  215332. if (trueIfInAChildWindow)
  215333. return true;
  215334. ::Window root, child;
  215335. unsigned int bw, depth;
  215336. int wx, wy, w, h;
  215337. if (! XGetGeometry (display, (::Drawable) windowH, &root,
  215338. &wx, &wy, (unsigned int*) &w, (unsigned int*) &h,
  215339. &bw, &depth))
  215340. {
  215341. return false;
  215342. }
  215343. if (! XTranslateCoordinates (display, windowH, windowH, x, y, &wx, &wy, &child))
  215344. return false;
  215345. return child == None;
  215346. }
  215347. const BorderSize getFrameSize() const
  215348. {
  215349. return BorderSize();
  215350. }
  215351. bool setAlwaysOnTop (bool alwaysOnTop)
  215352. {
  215353. if (windowH != 0)
  215354. {
  215355. const bool wasVisible = component->isVisible();
  215356. if (wasVisible)
  215357. setVisible (false); // doesn't always seem to work if the window is visible when this is done..
  215358. XSetWindowAttributes swa;
  215359. swa.override_redirect = alwaysOnTop ? True : False;
  215360. XChangeWindowAttributes (display, windowH, CWOverrideRedirect, &swa);
  215361. if (wasVisible)
  215362. setVisible (true);
  215363. }
  215364. return true;
  215365. }
  215366. void toFront (bool makeActive)
  215367. {
  215368. if (makeActive)
  215369. {
  215370. setVisible (true);
  215371. grabFocus();
  215372. }
  215373. XEvent ev;
  215374. ev.xclient.type = ClientMessage;
  215375. ev.xclient.serial = 0;
  215376. ev.xclient.send_event = True;
  215377. ev.xclient.message_type = wm_ActiveWin;
  215378. ev.xclient.window = windowH;
  215379. ev.xclient.format = 32;
  215380. ev.xclient.data.l[0] = 2;
  215381. ev.xclient.data.l[1] = CurrentTime;
  215382. ev.xclient.data.l[2] = 0;
  215383. ev.xclient.data.l[3] = 0;
  215384. ev.xclient.data.l[4] = 0;
  215385. XSendEvent (display, RootWindow (display, DefaultScreen (display)),
  215386. False,
  215387. SubstructureRedirectMask | SubstructureNotifyMask,
  215388. &ev);
  215389. XWindowAttributes attr;
  215390. XGetWindowAttributes (display, windowH, &attr);
  215391. if (attr.override_redirect)
  215392. XRaiseWindow (display, windowH);
  215393. XSync (display, False);
  215394. handleBroughtToFront();
  215395. }
  215396. void toBehind (ComponentPeer* other)
  215397. {
  215398. LinuxComponentPeer* const otherPeer = dynamic_cast <LinuxComponentPeer*> (other);
  215399. jassert (otherPeer != 0); // wrong type of window?
  215400. if (otherPeer != 0)
  215401. {
  215402. setMinimised (false);
  215403. Window newStack[] = { otherPeer->windowH, windowH };
  215404. XRestackWindows (display, newStack, 2);
  215405. }
  215406. }
  215407. bool isFocused() const
  215408. {
  215409. int revert;
  215410. Window focusedWindow = 0;
  215411. XGetInputFocus (display, &focusedWindow, &revert);
  215412. return focusedWindow == windowH;
  215413. }
  215414. void grabFocus()
  215415. {
  215416. XWindowAttributes atts;
  215417. if (windowH != 0
  215418. && XGetWindowAttributes (display, windowH, &atts)
  215419. && atts.map_state == IsViewable
  215420. && ! isFocused())
  215421. {
  215422. XSetInputFocus (display, windowH, RevertToParent, CurrentTime);
  215423. isActiveApplication = true;
  215424. }
  215425. }
  215426. void textInputRequired (int /*x*/, int /*y*/)
  215427. {
  215428. }
  215429. void repaint (int x, int y, int w, int h)
  215430. {
  215431. if (Rectangle::intersectRectangles (x, y, w, h,
  215432. 0, 0,
  215433. getComponent()->getWidth(),
  215434. getComponent()->getHeight()))
  215435. {
  215436. repainter->repaint (x, y, w, h);
  215437. }
  215438. }
  215439. void performAnyPendingRepaintsNow()
  215440. {
  215441. repainter->performAnyPendingRepaintsNow();
  215442. }
  215443. void setIcon (const Image& newIcon)
  215444. {
  215445. const int dataSize = newIcon.getWidth() * newIcon.getHeight() + 2;
  215446. unsigned long* const data = (unsigned long*) juce_malloc (dataSize * sizeof (uint32));
  215447. int index = 0;
  215448. data[index++] = newIcon.getWidth();
  215449. data[index++] = newIcon.getHeight();
  215450. for (int y = 0; y < newIcon.getHeight(); ++y)
  215451. for (int x = 0; x < newIcon.getWidth(); ++x)
  215452. data[index++] = newIcon.getPixelAt (x, y).getARGB();
  215453. XChangeProperty (display, windowH,
  215454. XInternAtom (display, "_NET_WM_ICON", False),
  215455. XA_CARDINAL, 32, PropModeReplace,
  215456. (unsigned char*) data, dataSize);
  215457. juce_free (data);
  215458. deleteIconPixmaps();
  215459. XWMHints* wmHints = XGetWMHints (display, windowH);
  215460. if (wmHints == 0)
  215461. wmHints = XAllocWMHints();
  215462. wmHints->flags |= IconPixmapHint | IconMaskHint;
  215463. wmHints->icon_pixmap = juce_createColourPixmapFromImage (display, newIcon);
  215464. wmHints->icon_mask = juce_createMaskPixmapFromImage (display, newIcon);
  215465. XSetWMHints (display, windowH, wmHints);
  215466. XFree (wmHints);
  215467. XSync (display, False);
  215468. }
  215469. void deleteIconPixmaps()
  215470. {
  215471. XWMHints* wmHints = XGetWMHints (display, windowH);
  215472. if (wmHints != 0)
  215473. {
  215474. if ((wmHints->flags & IconPixmapHint) != 0)
  215475. {
  215476. wmHints->flags &= ~IconPixmapHint;
  215477. XFreePixmap (display, wmHints->icon_pixmap);
  215478. }
  215479. if ((wmHints->flags & IconMaskHint) != 0)
  215480. {
  215481. wmHints->flags &= ~IconMaskHint;
  215482. XFreePixmap (display, wmHints->icon_mask);
  215483. }
  215484. XSetWMHints (display, windowH, wmHints);
  215485. XFree (wmHints);
  215486. }
  215487. }
  215488. void handleWindowMessage (XEvent* event)
  215489. {
  215490. switch (event->xany.type)
  215491. {
  215492. case 2: // 'KeyPress'
  215493. {
  215494. XKeyEvent* const keyEvent = (XKeyEvent*) &event->xkey;
  215495. updateKeyStates (keyEvent->keycode, true);
  215496. char utf8 [64];
  215497. zeromem (utf8, sizeof (utf8));
  215498. KeySym sym;
  215499. XLookupString (keyEvent, utf8, sizeof (utf8), &sym, 0);
  215500. const juce_wchar unicodeChar = *(const juce_wchar*) String::fromUTF8 ((const uint8*) utf8, sizeof (utf8) - 1);
  215501. int keyCode = (int) unicodeChar;
  215502. if (keyCode < 0x20)
  215503. keyCode = XKeycodeToKeysym (display, keyEvent->keycode,
  215504. (currentModifiers & ModifierKeys::shiftModifier) != 0 ? 1 : 0);
  215505. const int oldMods = currentModifiers;
  215506. bool keyPressed = false;
  215507. const bool keyDownChange = (sym != NoSymbol) && ! updateKeyModifiersFromSym (sym, true);
  215508. if ((sym & 0xff00) == 0xff00)
  215509. {
  215510. // Translate keypad
  215511. if (sym == XK_KP_Divide)
  215512. keyCode = XK_slash;
  215513. else if (sym == XK_KP_Multiply)
  215514. keyCode = XK_asterisk;
  215515. else if (sym == XK_KP_Subtract)
  215516. keyCode = XK_hyphen;
  215517. else if (sym == XK_KP_Add)
  215518. keyCode = XK_plus;
  215519. else if (sym == XK_KP_Enter)
  215520. keyCode = XK_Return;
  215521. else if (sym == XK_KP_Decimal)
  215522. keyCode = numLock ? XK_period : XK_Delete;
  215523. else if (sym == XK_KP_0)
  215524. keyCode = numLock ? XK_0 : XK_Insert;
  215525. else if (sym == XK_KP_1)
  215526. keyCode = numLock ? XK_1 : XK_End;
  215527. else if (sym == XK_KP_2)
  215528. keyCode = numLock ? XK_2 : XK_Down;
  215529. else if (sym == XK_KP_3)
  215530. keyCode = numLock ? XK_3 : XK_Page_Down;
  215531. else if (sym == XK_KP_4)
  215532. keyCode = numLock ? XK_4 : XK_Left;
  215533. else if (sym == XK_KP_5)
  215534. keyCode = XK_5;
  215535. else if (sym == XK_KP_6)
  215536. keyCode = numLock ? XK_6 : XK_Right;
  215537. else if (sym == XK_KP_7)
  215538. keyCode = numLock ? XK_7 : XK_Home;
  215539. else if (sym == XK_KP_8)
  215540. keyCode = numLock ? XK_8 : XK_Up;
  215541. else if (sym == XK_KP_9)
  215542. keyCode = numLock ? XK_9 : XK_Page_Up;
  215543. switch (sym)
  215544. {
  215545. case XK_Left:
  215546. case XK_Right:
  215547. case XK_Up:
  215548. case XK_Down:
  215549. case XK_Page_Up:
  215550. case XK_Page_Down:
  215551. case XK_End:
  215552. case XK_Home:
  215553. case XK_Delete:
  215554. case XK_Insert:
  215555. keyPressed = true;
  215556. keyCode = (sym & 0xff) | extendedKeyModifier;
  215557. break;
  215558. case XK_Tab:
  215559. case XK_Return:
  215560. case XK_Escape:
  215561. case XK_BackSpace:
  215562. keyPressed = true;
  215563. keyCode &= 0xff;
  215564. break;
  215565. default:
  215566. {
  215567. if (sym >= XK_F1 && sym <= XK_F16)
  215568. {
  215569. keyPressed = true;
  215570. keyCode = (sym & 0xff) | extendedKeyModifier;
  215571. }
  215572. break;
  215573. }
  215574. }
  215575. }
  215576. if (utf8[0] != 0 || ((sym & 0xff00) == 0 && sym >= 8))
  215577. keyPressed = true;
  215578. if (oldMods != currentModifiers)
  215579. handleModifierKeysChange();
  215580. if (keyDownChange)
  215581. handleKeyUpOrDown (true);
  215582. if (keyPressed)
  215583. handleKeyPress (keyCode, unicodeChar);
  215584. break;
  215585. }
  215586. case KeyRelease:
  215587. {
  215588. const XKeyEvent* const keyEvent = (const XKeyEvent*) &event->xkey;
  215589. updateKeyStates (keyEvent->keycode, false);
  215590. KeySym sym = XKeycodeToKeysym (display, keyEvent->keycode, 0);
  215591. const int oldMods = currentModifiers;
  215592. const bool keyDownChange = (sym != NoSymbol) && ! updateKeyModifiersFromSym (sym, false);
  215593. if (oldMods != currentModifiers)
  215594. handleModifierKeysChange();
  215595. if (keyDownChange)
  215596. handleKeyUpOrDown (false);
  215597. break;
  215598. }
  215599. case ButtonPress:
  215600. {
  215601. const XButtonPressedEvent* const buttonPressEvent = (const XButtonPressedEvent*) &event->xbutton;
  215602. bool buttonMsg = false;
  215603. bool wheelUpMsg = false;
  215604. bool wheelDownMsg = false;
  215605. const int map = pointerMap [buttonPressEvent->button - Button1];
  215606. if (map == LeftButton)
  215607. {
  215608. currentModifiers |= ModifierKeys::leftButtonModifier;
  215609. buttonMsg = true;
  215610. }
  215611. else if (map == RightButton)
  215612. {
  215613. currentModifiers |= ModifierKeys::rightButtonModifier;
  215614. buttonMsg = true;
  215615. }
  215616. else if (map == MiddleButton)
  215617. {
  215618. currentModifiers |= ModifierKeys::middleButtonModifier;
  215619. buttonMsg = true;
  215620. }
  215621. else if (map == WheelUp)
  215622. {
  215623. wheelUpMsg = true;
  215624. }
  215625. else if (map == WheelDown)
  215626. {
  215627. wheelDownMsg = true;
  215628. }
  215629. updateKeyModifiers (buttonPressEvent->state);
  215630. if (buttonMsg)
  215631. {
  215632. toFront (true);
  215633. handleMouseDown (buttonPressEvent->x, buttonPressEvent->y,
  215634. getEventTime (buttonPressEvent->time));
  215635. }
  215636. else if (wheelUpMsg || wheelDownMsg)
  215637. {
  215638. handleMouseWheel (0, wheelDownMsg ? -84 : 84,
  215639. getEventTime (buttonPressEvent->time));
  215640. }
  215641. lastMousePosX = lastMousePosY = 0x100000;
  215642. break;
  215643. }
  215644. case ButtonRelease:
  215645. {
  215646. const XButtonReleasedEvent* const buttonRelEvent = (const XButtonReleasedEvent*) &event->xbutton;
  215647. const int oldModifiers = currentModifiers;
  215648. const int map = pointerMap [buttonRelEvent->button - Button1];
  215649. if (map == LeftButton)
  215650. currentModifiers &= ~ModifierKeys::leftButtonModifier;
  215651. else if (map == RightButton)
  215652. currentModifiers &= ~ModifierKeys::rightButtonModifier;
  215653. else if (map == MiddleButton)
  215654. currentModifiers &= ~ModifierKeys::middleButtonModifier;
  215655. updateKeyModifiers (buttonRelEvent->state);
  215656. handleMouseUp (oldModifiers,
  215657. buttonRelEvent->x, buttonRelEvent->y,
  215658. getEventTime (buttonRelEvent->time));
  215659. lastMousePosX = lastMousePosY = 0x100000;
  215660. break;
  215661. }
  215662. case MotionNotify:
  215663. {
  215664. const XPointerMovedEvent* const movedEvent = (const XPointerMovedEvent*) &event->xmotion;
  215665. updateKeyModifiers (movedEvent->state);
  215666. int x, y, mouseMods;
  215667. getMousePos (x, y, mouseMods);
  215668. if (lastMousePosX != x || lastMousePosY != y)
  215669. {
  215670. lastMousePosX = x;
  215671. lastMousePosY = y;
  215672. if (parentWindow != 0 && (styleFlags & windowHasTitleBar) == 0)
  215673. {
  215674. Window wRoot = 0, wParent = 0;
  215675. Window* wChild = 0;
  215676. unsigned int numChildren;
  215677. XQueryTree (display, windowH, &wRoot, &wParent, &wChild, &numChildren);
  215678. if (wParent != 0
  215679. && wParent != windowH
  215680. && wParent != wRoot)
  215681. {
  215682. parentWindow = wParent;
  215683. updateBounds();
  215684. x -= getScreenX();
  215685. y -= getScreenY();
  215686. }
  215687. else
  215688. {
  215689. parentWindow = 0;
  215690. x -= getScreenX();
  215691. y -= getScreenY();
  215692. }
  215693. }
  215694. else
  215695. {
  215696. x -= getScreenX();
  215697. y -= getScreenY();
  215698. }
  215699. if ((currentModifiers & ModifierKeys::allMouseButtonModifiers) == 0)
  215700. handleMouseMove (x, y, getEventTime (movedEvent->time));
  215701. else
  215702. handleMouseDrag (x, y, getEventTime (movedEvent->time));
  215703. }
  215704. break;
  215705. }
  215706. case EnterNotify:
  215707. {
  215708. lastMousePosX = lastMousePosY = 0x100000;
  215709. const XEnterWindowEvent* const enterEvent = (const XEnterWindowEvent*) &event->xcrossing;
  215710. if ((currentModifiers & ModifierKeys::allMouseButtonModifiers) == 0
  215711. && ! entered)
  215712. {
  215713. updateKeyModifiers (enterEvent->state);
  215714. handleMouseEnter (enterEvent->x, enterEvent->y, getEventTime (enterEvent->time));
  215715. entered = true;
  215716. }
  215717. break;
  215718. }
  215719. case LeaveNotify:
  215720. {
  215721. const XLeaveWindowEvent* const leaveEvent = (const XLeaveWindowEvent*) &event->xcrossing;
  215722. // Suppress the normal leave if we've got a pointer grab, or if
  215723. // it's a bogus one caused by clicking a mouse button when running
  215724. // in a Window manager
  215725. if (((currentModifiers & ModifierKeys::allMouseButtonModifiers) == 0
  215726. && leaveEvent->mode == NotifyNormal)
  215727. || leaveEvent->mode == NotifyUngrab)
  215728. {
  215729. updateKeyModifiers (leaveEvent->state);
  215730. handleMouseExit (leaveEvent->x, leaveEvent->y, getEventTime (leaveEvent->time));
  215731. entered = false;
  215732. }
  215733. break;
  215734. }
  215735. case FocusIn:
  215736. {
  215737. isActiveApplication = true;
  215738. if (isFocused())
  215739. handleFocusGain();
  215740. break;
  215741. }
  215742. case FocusOut:
  215743. {
  215744. isActiveApplication = false;
  215745. if (! isFocused())
  215746. handleFocusLoss();
  215747. break;
  215748. }
  215749. case Expose:
  215750. {
  215751. // Batch together all pending expose events
  215752. XExposeEvent* exposeEvent = (XExposeEvent*) &event->xexpose;
  215753. XEvent nextEvent;
  215754. if (exposeEvent->window != windowH)
  215755. {
  215756. Window child;
  215757. XTranslateCoordinates (display, exposeEvent->window, windowH,
  215758. exposeEvent->x, exposeEvent->y, &exposeEvent->x, &exposeEvent->y,
  215759. &child);
  215760. }
  215761. repaint (exposeEvent->x, exposeEvent->y,
  215762. exposeEvent->width, exposeEvent->height);
  215763. while (XEventsQueued (display, QueuedAfterFlush) > 0)
  215764. {
  215765. XPeekEvent (display, (XEvent*) &nextEvent);
  215766. if (nextEvent.type != Expose || nextEvent.xany.window != event->xany.window)
  215767. break;
  215768. XNextEvent (display, (XEvent*) &nextEvent);
  215769. XExposeEvent* nextExposeEvent = (XExposeEvent*) &nextEvent.xexpose;
  215770. repaint (nextExposeEvent->x, nextExposeEvent->y,
  215771. nextExposeEvent->width, nextExposeEvent->height);
  215772. }
  215773. break;
  215774. }
  215775. case CirculateNotify:
  215776. case CreateNotify:
  215777. case DestroyNotify:
  215778. // Think we can ignore these
  215779. break;
  215780. case ConfigureNotify:
  215781. {
  215782. updateBounds();
  215783. updateBorderSize();
  215784. handleMovedOrResized();
  215785. // if the native title bar is dragged, need to tell any active menus, etc.
  215786. if ((styleFlags & windowHasTitleBar) != 0
  215787. && component->isCurrentlyBlockedByAnotherModalComponent())
  215788. {
  215789. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  215790. if (currentModalComp != 0)
  215791. currentModalComp->inputAttemptWhenModal();
  215792. }
  215793. XConfigureEvent* const confEvent = (XConfigureEvent*) &event->xconfigure;
  215794. if (confEvent->window == windowH
  215795. && confEvent->above != 0
  215796. && isFrontWindow())
  215797. {
  215798. handleBroughtToFront();
  215799. }
  215800. break;
  215801. }
  215802. case ReparentNotify:
  215803. case GravityNotify:
  215804. {
  215805. parentWindow = 0;
  215806. Window wRoot = 0;
  215807. Window* wChild = 0;
  215808. unsigned int numChildren;
  215809. XQueryTree (display, windowH, &wRoot, &parentWindow, &wChild, &numChildren);
  215810. if (parentWindow == windowH || parentWindow == wRoot)
  215811. parentWindow = 0;
  215812. updateBounds();
  215813. updateBorderSize();
  215814. handleMovedOrResized();
  215815. break;
  215816. }
  215817. case MapNotify:
  215818. mapped = true;
  215819. handleBroughtToFront();
  215820. break;
  215821. case UnmapNotify:
  215822. mapped = false;
  215823. break;
  215824. case MappingNotify:
  215825. {
  215826. XMappingEvent* mappingEvent = (XMappingEvent*) &event->xmapping;
  215827. if (mappingEvent->request != MappingPointer)
  215828. {
  215829. // Deal with modifier/keyboard mapping
  215830. XRefreshKeyboardMapping (mappingEvent);
  215831. getModifierMapping();
  215832. }
  215833. break;
  215834. }
  215835. case ClientMessage:
  215836. {
  215837. const XClientMessageEvent* const clientMsg = (const XClientMessageEvent*) &event->xclient;
  215838. if (clientMsg->message_type == wm_Protocols && clientMsg->format == 32)
  215839. {
  215840. const Atom atom = (Atom) clientMsg->data.l[0];
  215841. if (atom == wm_ProtocolList [TAKE_FOCUS])
  215842. {
  215843. XWindowAttributes atts;
  215844. if (clientMsg->window != 0
  215845. && XGetWindowAttributes (display, clientMsg->window, &atts))
  215846. {
  215847. if (atts.map_state == IsViewable)
  215848. XSetInputFocus (display, clientMsg->window, RevertToParent, clientMsg->data.l[1]);
  215849. }
  215850. }
  215851. else if (atom == wm_ProtocolList [DELETE_WINDOW])
  215852. {
  215853. handleUserClosingWindow();
  215854. }
  215855. }
  215856. else if (clientMsg->message_type == XA_XdndEnter)
  215857. {
  215858. handleDragAndDropEnter (clientMsg);
  215859. }
  215860. else if (clientMsg->message_type == XA_XdndLeave)
  215861. {
  215862. resetDragAndDrop();
  215863. }
  215864. else if (clientMsg->message_type == XA_XdndPosition)
  215865. {
  215866. handleDragAndDropPosition (clientMsg);
  215867. }
  215868. else if (clientMsg->message_type == XA_XdndDrop)
  215869. {
  215870. handleDragAndDropDrop (clientMsg);
  215871. }
  215872. else if (clientMsg->message_type == XA_XdndStatus)
  215873. {
  215874. handleDragAndDropStatus (clientMsg);
  215875. }
  215876. else if (clientMsg->message_type == XA_XdndFinished)
  215877. {
  215878. resetDragAndDrop();
  215879. }
  215880. break;
  215881. }
  215882. case SelectionNotify:
  215883. handleDragAndDropSelection (event);
  215884. break;
  215885. case SelectionClear:
  215886. case SelectionRequest:
  215887. break;
  215888. default:
  215889. break;
  215890. }
  215891. }
  215892. void showMouseCursor (Cursor cursor) throw()
  215893. {
  215894. XDefineCursor (display, windowH, cursor);
  215895. }
  215896. void setTaskBarIcon (const Image& image)
  215897. {
  215898. deleteTaskBarIcon();
  215899. taskbarImage = image.createCopy();
  215900. Screen* const screen = XDefaultScreenOfDisplay (display);
  215901. const int screenNumber = XScreenNumberOfScreen (screen);
  215902. char screenAtom[32];
  215903. snprintf (screenAtom, sizeof (screenAtom), "_NET_SYSTEM_TRAY_S%d", screenNumber);
  215904. Atom selectionAtom = XInternAtom (display, screenAtom, false);
  215905. XGrabServer (display);
  215906. Window managerWin = XGetSelectionOwner (display, selectionAtom);
  215907. if (managerWin != None)
  215908. XSelectInput (display, managerWin, StructureNotifyMask);
  215909. XUngrabServer (display);
  215910. XFlush (display);
  215911. if (managerWin != None)
  215912. {
  215913. XEvent ev;
  215914. zerostruct (ev);
  215915. ev.xclient.type = ClientMessage;
  215916. ev.xclient.window = managerWin;
  215917. ev.xclient.message_type = XInternAtom (display, "_NET_SYSTEM_TRAY_OPCODE", False);
  215918. ev.xclient.format = 32;
  215919. ev.xclient.data.l[0] = CurrentTime;
  215920. ev.xclient.data.l[1] = SYSTEM_TRAY_REQUEST_DOCK;
  215921. ev.xclient.data.l[2] = windowH;
  215922. ev.xclient.data.l[3] = 0;
  215923. ev.xclient.data.l[4] = 0;
  215924. XSendEvent (display, managerWin, False, NoEventMask, &ev);
  215925. XSync (display, False);
  215926. }
  215927. // For older KDE's ...
  215928. long atomData = 1;
  215929. Atom trayAtom = XInternAtom (display, "KWM_DOCKWINDOW", false);
  215930. XChangeProperty (display, windowH, trayAtom, trayAtom, 32, PropModeReplace, (unsigned char*) &atomData, 1);
  215931. // For more recent KDE's...
  215932. trayAtom = XInternAtom (display, "_KDE_NET_WM_SYSTEM_TRAY_WINDOW_FOR", false);
  215933. XChangeProperty (display, windowH, trayAtom, XA_WINDOW, 32, PropModeReplace, (unsigned char*) &windowH, 1);
  215934. // a minimum size must be specified for GNOME and Xfce, otherwise the icon is displayed with a width of 1
  215935. XSizeHints* hints = XAllocSizeHints();
  215936. hints->flags = PMinSize;
  215937. hints->min_width = 22;
  215938. hints->min_height = 22;
  215939. XSetWMNormalHints (display, windowH, hints);
  215940. XFree (hints);
  215941. }
  215942. void deleteTaskBarIcon()
  215943. {
  215944. deleteAndZero (taskbarImage);
  215945. }
  215946. const Image* getTaskbarIcon() const throw() { return taskbarImage; }
  215947. juce_UseDebuggingNewOperator
  215948. bool dontRepaint;
  215949. private:
  215950. class LinuxRepaintManager : public Timer
  215951. {
  215952. public:
  215953. LinuxRepaintManager (LinuxComponentPeer* const peer_)
  215954. : peer (peer_),
  215955. image (0),
  215956. lastTimeImageUsed (0)
  215957. {
  215958. #if JUCE_USE_XSHM
  215959. useARGBImagesForRendering = isShmAvailable();
  215960. if (useARGBImagesForRendering)
  215961. {
  215962. XShmSegmentInfo segmentinfo;
  215963. XImage* const testImage
  215964. = XShmCreateImage (display, DefaultVisual (display, DefaultScreen (display)),
  215965. 24, ZPixmap, 0, &segmentinfo, 64, 64);
  215966. useARGBImagesForRendering = (testImage->bits_per_pixel == 32);
  215967. XDestroyImage (testImage);
  215968. }
  215969. #endif
  215970. }
  215971. ~LinuxRepaintManager()
  215972. {
  215973. delete image;
  215974. }
  215975. void timerCallback()
  215976. {
  215977. if (! regionsNeedingRepaint.isEmpty())
  215978. {
  215979. stopTimer();
  215980. performAnyPendingRepaintsNow();
  215981. }
  215982. else if (Time::getApproximateMillisecondCounter() > lastTimeImageUsed + 3000)
  215983. {
  215984. stopTimer();
  215985. deleteAndZero (image);
  215986. }
  215987. }
  215988. void repaint (int x, int y, int w, int h)
  215989. {
  215990. if (! isTimerRunning())
  215991. startTimer (repaintTimerPeriod);
  215992. regionsNeedingRepaint.add (x, y, w, h);
  215993. }
  215994. void performAnyPendingRepaintsNow()
  215995. {
  215996. peer->clearMaskedRegion();
  215997. const Rectangle totalArea (regionsNeedingRepaint.getBounds());
  215998. if (! totalArea.isEmpty())
  215999. {
  216000. if (image == 0 || image->getWidth() < totalArea.getWidth()
  216001. || image->getHeight() < totalArea.getHeight())
  216002. {
  216003. delete image;
  216004. #if JUCE_USE_XSHM
  216005. image = new XBitmapImage (useARGBImagesForRendering ? Image::ARGB
  216006. : Image::RGB,
  216007. #else
  216008. image = new XBitmapImage (Image::RGB,
  216009. #endif
  216010. (totalArea.getWidth() + 31) & ~31,
  216011. (totalArea.getHeight() + 31) & ~31,
  216012. false,
  216013. peer->depthIs16Bit);
  216014. }
  216015. startTimer (repaintTimerPeriod);
  216016. LowLevelGraphicsSoftwareRenderer context (*image);
  216017. context.setOrigin (-totalArea.getX(), -totalArea.getY());
  216018. if (context.reduceClipRegion (regionsNeedingRepaint))
  216019. peer->handlePaint (context);
  216020. if (! peer->maskedRegion.isEmpty())
  216021. regionsNeedingRepaint.subtract (peer->maskedRegion);
  216022. for (RectangleList::Iterator i (regionsNeedingRepaint); i.next();)
  216023. {
  216024. const Rectangle& r = *i.getRectangle();
  216025. image->blitToWindow (peer->windowH,
  216026. r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  216027. r.getX() - totalArea.getX(), r.getY() - totalArea.getY());
  216028. }
  216029. }
  216030. regionsNeedingRepaint.clear();
  216031. lastTimeImageUsed = Time::getApproximateMillisecondCounter();
  216032. startTimer (repaintTimerPeriod);
  216033. }
  216034. private:
  216035. LinuxComponentPeer* const peer;
  216036. XBitmapImage* image;
  216037. uint32 lastTimeImageUsed;
  216038. RectangleList regionsNeedingRepaint;
  216039. #if JUCE_USE_XSHM
  216040. bool useARGBImagesForRendering;
  216041. #endif
  216042. LinuxRepaintManager (const LinuxRepaintManager&);
  216043. const LinuxRepaintManager& operator= (const LinuxRepaintManager&);
  216044. };
  216045. LinuxRepaintManager* repainter;
  216046. friend class LinuxRepaintManager;
  216047. Window windowH, parentWindow;
  216048. int wx, wy, ww, wh;
  216049. Image* taskbarImage;
  216050. bool fullScreen, entered, mapped, depthIs16Bit;
  216051. BorderSize windowBorder;
  216052. void removeWindowDecorations (Window wndH)
  216053. {
  216054. Atom hints = XInternAtom (display, "_MOTIF_WM_HINTS", True);
  216055. if (hints != None)
  216056. {
  216057. typedef struct
  216058. {
  216059. unsigned long flags;
  216060. unsigned long functions;
  216061. unsigned long decorations;
  216062. long input_mode;
  216063. unsigned long status;
  216064. } MotifWmHints;
  216065. MotifWmHints motifHints;
  216066. zerostruct (motifHints);
  216067. motifHints.flags = 2; /* MWM_HINTS_DECORATIONS */
  216068. motifHints.decorations = 0;
  216069. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  216070. (unsigned char*) &motifHints, 4);
  216071. }
  216072. hints = XInternAtom (display, "_WIN_HINTS", True);
  216073. if (hints != None)
  216074. {
  216075. long gnomeHints = 0;
  216076. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  216077. (unsigned char*) &gnomeHints, 1);
  216078. }
  216079. hints = XInternAtom (display, "KWM_WIN_DECORATION", True);
  216080. if (hints != None)
  216081. {
  216082. long kwmHints = 2; /*KDE_tinyDecoration*/
  216083. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  216084. (unsigned char*) &kwmHints, 1);
  216085. }
  216086. hints = XInternAtom (display, "_NET_WM_WINDOW_TYPE", True);
  216087. if (hints != None)
  216088. {
  216089. int netHints [2];
  216090. int numHints = 0;
  216091. if ((styleFlags & windowIsTemporary) != 0)
  216092. netHints [numHints] = XInternAtom (display, "_NET_WM_WINDOW_TYPE_MENU", True);
  216093. else
  216094. netHints [numHints] = XInternAtom (display, "_NET_WM_WINDOW_TYPE_NORMAL", True);
  216095. if (netHints [numHints] != 0)
  216096. ++numHints;
  216097. netHints[numHints] = XInternAtom (display, "_KDE_NET_WM_WINDOW_TYPE_OVERRIDE", True);
  216098. if (netHints [numHints] != 0)
  216099. ++numHints;
  216100. XChangeProperty (display, wndH, hints, XA_ATOM, 32, PropModeReplace,
  216101. (unsigned char*) &netHints, numHints);
  216102. }
  216103. }
  216104. void addWindowButtons (Window wndH)
  216105. {
  216106. Atom hints = XInternAtom (display, "_MOTIF_WM_HINTS", True);
  216107. if (hints != None)
  216108. {
  216109. typedef struct
  216110. {
  216111. unsigned long flags;
  216112. unsigned long functions;
  216113. unsigned long decorations;
  216114. long input_mode;
  216115. unsigned long status;
  216116. } MotifWmHints;
  216117. MotifWmHints motifHints;
  216118. zerostruct (motifHints);
  216119. motifHints.flags = 1 | 2; /* MWM_HINTS_FUNCTIONS | MWM_HINTS_DECORATIONS */
  216120. motifHints.decorations = 2 /* MWM_DECOR_BORDER */ | 8 /* MWM_DECOR_TITLE */ | 16; /* MWM_DECOR_MENU */
  216121. motifHints.functions = 4 /* MWM_FUNC_MOVE */;
  216122. if ((styleFlags & windowHasCloseButton) != 0)
  216123. motifHints.functions |= 32; /* MWM_FUNC_CLOSE */
  216124. if ((styleFlags & windowHasMinimiseButton) != 0)
  216125. {
  216126. motifHints.functions |= 8; /* MWM_FUNC_MINIMIZE */
  216127. motifHints.decorations |= 0x20; /* MWM_DECOR_MINIMIZE */
  216128. }
  216129. if ((styleFlags & windowHasMaximiseButton) != 0)
  216130. {
  216131. motifHints.functions |= 0x10; /* MWM_FUNC_MAXIMIZE */
  216132. motifHints.decorations |= 0x40; /* MWM_DECOR_MAXIMIZE */
  216133. }
  216134. if ((styleFlags & windowIsResizable) != 0)
  216135. {
  216136. motifHints.functions |= 2; /* MWM_FUNC_RESIZE */
  216137. motifHints.decorations |= 0x4; /* MWM_DECOR_RESIZEH */
  216138. }
  216139. XChangeProperty (display, wndH, hints, hints, 32, 0, (unsigned char*) &motifHints, 5);
  216140. }
  216141. hints = XInternAtom (display, "_NET_WM_ALLOWED_ACTIONS", True);
  216142. if (hints != None)
  216143. {
  216144. int netHints [6];
  216145. int num = 0;
  216146. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_RESIZE", (styleFlags & windowIsResizable) ? True : False);
  216147. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_FULLSCREEN", (styleFlags & windowHasMaximiseButton) ? True : False);
  216148. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_MINIMIZE", (styleFlags & windowHasMinimiseButton) ? True : False);
  216149. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_CLOSE", (styleFlags & windowHasCloseButton) ? True : False);
  216150. XChangeProperty (display, wndH, hints, XA_ATOM, 32, PropModeReplace,
  216151. (unsigned char*) &netHints, num);
  216152. }
  216153. }
  216154. void createWindow()
  216155. {
  216156. static bool atomsInitialised = false;
  216157. if (! atomsInitialised)
  216158. {
  216159. atomsInitialised = true;
  216160. wm_Protocols = XInternAtom (display, "WM_PROTOCOLS", 1);
  216161. wm_ProtocolList [TAKE_FOCUS] = XInternAtom (display, "WM_TAKE_FOCUS", 1);
  216162. wm_ProtocolList [DELETE_WINDOW] = XInternAtom (display, "WM_DELETE_WINDOW", 1);
  216163. wm_ChangeState = XInternAtom (display, "WM_CHANGE_STATE", 1);
  216164. wm_State = XInternAtom (display, "WM_STATE", 1);
  216165. wm_ActiveWin = XInternAtom (display, "_NET_ACTIVE_WINDOW", False);
  216166. XA_XdndAware = XInternAtom (display, "XdndAware", 0);
  216167. XA_XdndEnter = XInternAtom (display, "XdndEnter", 0);
  216168. XA_XdndLeave = XInternAtom (display, "XdndLeave", 0);
  216169. XA_XdndPosition = XInternAtom (display, "XdndPosition", 0);
  216170. XA_XdndStatus = XInternAtom (display, "XdndStatus", 0);
  216171. XA_XdndDrop = XInternAtom (display, "XdndDrop", 0);
  216172. XA_XdndFinished = XInternAtom (display, "XdndFinished", 0);
  216173. XA_XdndSelection = XInternAtom (display, "XdndSelection", 0);
  216174. XA_XdndProxy = XInternAtom (display, "XdndProxy", 0);
  216175. XA_XdndTypeList = XInternAtom (display, "XdndTypeList", 0);
  216176. XA_XdndActionList = XInternAtom (display, "XdndActionList", 0);
  216177. XA_XdndActionCopy = XInternAtom (display, "XdndActionCopy", 0);
  216178. XA_XdndActionMove = XInternAtom (display, "XdndActionMove", 0);
  216179. XA_XdndActionLink = XInternAtom (display, "XdndActionLink", 0);
  216180. XA_XdndActionAsk = XInternAtom (display, "XdndActionAsk", 0);
  216181. XA_XdndActionPrivate = XInternAtom (display, "XdndActionPrivate", 0);
  216182. XA_XdndActionDescription = XInternAtom (display, "XdndActionDescription", 0);
  216183. XA_JXSelectionWindowProperty = XInternAtom (display, "JXSelectionWindowProperty", 0);
  216184. XA_MimeTextPlain = XInternAtom (display, "text/plain", 0);
  216185. XA_MimeTextUriList = XInternAtom (display, "text/uri-list", 0);
  216186. XA_MimeRootDrop = XInternAtom (display, "application/x-rootwindow-drop", 0);
  216187. }
  216188. resetDragAndDrop();
  216189. XA_OtherMime = XA_MimeTextPlain; // xxx why??
  216190. allowedMimeTypeAtoms [0] = XA_MimeTextPlain;
  216191. allowedMimeTypeAtoms [1] = XA_OtherMime;
  216192. allowedMimeTypeAtoms [2] = XA_MimeTextUriList;
  216193. allowedActions [0] = XA_XdndActionMove;
  216194. allowedActions [1] = XA_XdndActionCopy;
  216195. allowedActions [2] = XA_XdndActionLink;
  216196. allowedActions [3] = XA_XdndActionAsk;
  216197. allowedActions [4] = XA_XdndActionPrivate;
  216198. // Get defaults for various properties
  216199. const int screen = DefaultScreen (display);
  216200. Window root = RootWindow (display, screen);
  216201. // Attempt to create a 24-bit window on the default screen. If this is not
  216202. // possible then exit
  216203. XVisualInfo desiredVisual;
  216204. desiredVisual.screen = screen;
  216205. desiredVisual.depth = 24;
  216206. depthIs16Bit = false;
  216207. int numVisuals;
  216208. XVisualInfo* visuals = XGetVisualInfo (display, VisualScreenMask | VisualDepthMask,
  216209. &desiredVisual, &numVisuals);
  216210. if (numVisuals < 1 || visuals == 0)
  216211. {
  216212. XFree (visuals);
  216213. desiredVisual.depth = 16;
  216214. visuals = XGetVisualInfo (display, VisualScreenMask | VisualDepthMask,
  216215. &desiredVisual, &numVisuals);
  216216. if (numVisuals < 1 || visuals == 0)
  216217. {
  216218. Logger::outputDebugString ("ERROR: System doesn't support 24 or 16 bit RGB display.\n");
  216219. Process::terminate();
  216220. }
  216221. depthIs16Bit = true;
  216222. }
  216223. XFree (visuals);
  216224. // Set up the window attributes
  216225. XSetWindowAttributes swa;
  216226. swa.border_pixel = 0;
  216227. swa.background_pixmap = None;
  216228. swa.colormap = DefaultColormap (display, screen);
  216229. swa.override_redirect = getComponent()->isAlwaysOnTop() ? True : False;
  216230. swa.event_mask = eventMask;
  216231. Window wndH = XCreateWindow (display, root,
  216232. 0, 0, 1, 1,
  216233. 0, 0, InputOutput, (Visual*) CopyFromParent,
  216234. CWBorderPixel | CWColormap | CWBackPixmap | CWEventMask | CWOverrideRedirect,
  216235. &swa);
  216236. XGrabButton (display, AnyButton, AnyModifier, wndH, False,
  216237. ButtonPressMask | ButtonReleaseMask | EnterWindowMask | LeaveWindowMask | PointerMotionMask,
  216238. GrabModeAsync, GrabModeAsync, None, None);
  216239. // Set the window context to identify the window handle object
  216240. if (XSaveContext (display, (XID) wndH, improbableNumber, (XPointer) this))
  216241. {
  216242. // Failed
  216243. jassertfalse
  216244. Logger::outputDebugString ("Failed to create context information for window.\n");
  216245. XDestroyWindow (display, wndH);
  216246. wndH = 0;
  216247. }
  216248. // Set window manager hints
  216249. XWMHints* wmHints = XAllocWMHints();
  216250. wmHints->flags = InputHint | StateHint;
  216251. wmHints->input = True; // Locally active input model
  216252. wmHints->initial_state = NormalState;
  216253. XSetWMHints (display, wndH, wmHints);
  216254. XFree (wmHints);
  216255. if ((styleFlags & windowIsSemiTransparent) != 0)
  216256. {
  216257. //xxx
  216258. }
  216259. if ((styleFlags & windowAppearsOnTaskbar) != 0)
  216260. {
  216261. //xxx
  216262. }
  216263. //XSetTransientForHint (display, wndH, RootWindow (display, DefaultScreen (display)));
  216264. if ((styleFlags & windowHasTitleBar) == 0)
  216265. removeWindowDecorations (wndH);
  216266. else
  216267. addWindowButtons (wndH);
  216268. // Set window manager protocols
  216269. XChangeProperty (display, wndH, wm_Protocols, XA_ATOM, 32, PropModeReplace,
  216270. (unsigned char*) wm_ProtocolList, 2);
  216271. // Set drag and drop flags
  216272. XChangeProperty (display, wndH, XA_XdndTypeList, XA_ATOM, 32, PropModeReplace,
  216273. (const unsigned char*) allowedMimeTypeAtoms, numElementsInArray (allowedMimeTypeAtoms));
  216274. XChangeProperty (display, wndH, XA_XdndActionList, XA_ATOM, 32, PropModeReplace,
  216275. (const unsigned char*) allowedActions, numElementsInArray (allowedActions));
  216276. XChangeProperty (display, wndH, XA_XdndActionDescription, XA_STRING, 8, PropModeReplace,
  216277. (const unsigned char*) "", 0);
  216278. unsigned long dndVersion = ourDndVersion;
  216279. XChangeProperty (display, wndH, XA_XdndAware, XA_ATOM, 32, PropModeReplace,
  216280. (const unsigned char*) &dndVersion, 1);
  216281. // Set window name
  216282. setWindowTitle (wndH, getComponent()->getName());
  216283. // Initialise the pointer and keyboard mapping
  216284. // This is not the same as the logical pointer mapping the X server uses:
  216285. // we don't mess with this.
  216286. static bool mappingInitialised = false;
  216287. if (! mappingInitialised)
  216288. {
  216289. mappingInitialised = true;
  216290. const int numButtons = XGetPointerMapping (display, 0, 0);
  216291. if (numButtons == 2)
  216292. {
  216293. pointerMap[0] = LeftButton;
  216294. pointerMap[1] = RightButton;
  216295. pointerMap[2] = pointerMap[3] = pointerMap[4] = NoButton;
  216296. }
  216297. else if (numButtons >= 3)
  216298. {
  216299. pointerMap[0] = LeftButton;
  216300. pointerMap[1] = MiddleButton;
  216301. pointerMap[2] = RightButton;
  216302. if (numButtons >= 5)
  216303. {
  216304. pointerMap[3] = WheelUp;
  216305. pointerMap[4] = WheelDown;
  216306. }
  216307. }
  216308. getModifierMapping();
  216309. }
  216310. windowH = wndH;
  216311. }
  216312. void destroyWindow()
  216313. {
  216314. XPointer handlePointer;
  216315. if (! XFindContext (display, (XID) windowH, improbableNumber, &handlePointer))
  216316. XDeleteContext (display, (XID) windowH, improbableNumber);
  216317. XDestroyWindow (display, windowH);
  216318. // Wait for it to complete and then remove any events for this
  216319. // window from the event queue.
  216320. XSync (display, false);
  216321. XEvent event;
  216322. while (XCheckWindowEvent (display, windowH, eventMask, &event) == True)
  216323. {}
  216324. }
  216325. static int64 getEventTime (::Time t) throw()
  216326. {
  216327. static int64 eventTimeOffset = 0x12345678;
  216328. const int64 thisMessageTime = t;
  216329. if (eventTimeOffset == 0x12345678)
  216330. eventTimeOffset = Time::currentTimeMillis() - thisMessageTime;
  216331. return eventTimeOffset + thisMessageTime;
  216332. }
  216333. static void setWindowTitle (Window xwin, const char* const title) throw()
  216334. {
  216335. XTextProperty nameProperty;
  216336. char* strings[] = { (char*) title };
  216337. if (XStringListToTextProperty (strings, 1, &nameProperty))
  216338. {
  216339. XSetWMName (display, xwin, &nameProperty);
  216340. XSetWMIconName (display, xwin, &nameProperty);
  216341. XFree (nameProperty.value);
  216342. }
  216343. }
  216344. void updateBorderSize()
  216345. {
  216346. if ((styleFlags & windowHasTitleBar) == 0)
  216347. {
  216348. windowBorder = BorderSize (0);
  216349. }
  216350. else if (windowBorder.getTopAndBottom() == 0 && windowBorder.getLeftAndRight() == 0)
  216351. {
  216352. Atom hints = XInternAtom (display, "_NET_FRAME_EXTENTS", True);
  216353. if (hints != None)
  216354. {
  216355. unsigned char* data = 0;
  216356. unsigned long nitems, bytesLeft;
  216357. Atom actualType;
  216358. int actualFormat;
  216359. if (XGetWindowProperty (display, windowH, hints, 0, 4, False,
  216360. XA_CARDINAL, &actualType, &actualFormat, &nitems, &bytesLeft,
  216361. &data) == Success)
  216362. {
  216363. const unsigned long* const sizes = (const unsigned long*) data;
  216364. if (actualFormat == 32)
  216365. windowBorder = BorderSize ((int) sizes[2], (int) sizes[0],
  216366. (int) sizes[3], (int) sizes[1]);
  216367. XFree (data);
  216368. }
  216369. }
  216370. }
  216371. }
  216372. void updateBounds()
  216373. {
  216374. jassert (windowH != 0);
  216375. if (windowH != 0)
  216376. {
  216377. Window root, child;
  216378. unsigned int bw, depth;
  216379. if (! XGetGeometry (display, (::Drawable) windowH, &root,
  216380. &wx, &wy, (unsigned int*) &ww, (unsigned int*) &wh,
  216381. &bw, &depth))
  216382. {
  216383. wx = wy = ww = wh = 0;
  216384. }
  216385. else if (! XTranslateCoordinates (display, windowH, root, 0, 0, &wx, &wy, &child))
  216386. {
  216387. wx = wy = 0;
  216388. }
  216389. }
  216390. }
  216391. void resetDragAndDrop()
  216392. {
  216393. dragAndDropFiles.clear();
  216394. lastDropX = lastDropY = -1;
  216395. dragAndDropCurrentMimeType = 0;
  216396. dragAndDropSourceWindow = 0;
  216397. srcMimeTypeAtomList.clear();
  216398. }
  216399. void sendDragAndDropMessage (XClientMessageEvent& msg)
  216400. {
  216401. msg.type = ClientMessage;
  216402. msg.display = display;
  216403. msg.window = dragAndDropSourceWindow;
  216404. msg.format = 32;
  216405. msg.data.l[0] = windowH;
  216406. XSendEvent (display, dragAndDropSourceWindow, False, 0, (XEvent*) &msg);
  216407. }
  216408. void sendDragAndDropStatus (const bool acceptDrop, Atom dropAction)
  216409. {
  216410. XClientMessageEvent msg;
  216411. zerostruct (msg);
  216412. msg.message_type = XA_XdndStatus;
  216413. msg.data.l[1] = (acceptDrop ? 1 : 0) | 2; // 2 indicates that we want to receive position messages
  216414. msg.data.l[4] = dropAction;
  216415. sendDragAndDropMessage (msg);
  216416. }
  216417. void sendDragAndDropLeave()
  216418. {
  216419. XClientMessageEvent msg;
  216420. zerostruct (msg);
  216421. msg.message_type = XA_XdndLeave;
  216422. sendDragAndDropMessage (msg);
  216423. }
  216424. void sendDragAndDropFinish()
  216425. {
  216426. XClientMessageEvent msg;
  216427. zerostruct (msg);
  216428. msg.message_type = XA_XdndFinished;
  216429. sendDragAndDropMessage (msg);
  216430. }
  216431. void handleDragAndDropStatus (const XClientMessageEvent* const clientMsg)
  216432. {
  216433. if ((clientMsg->data.l[1] & 1) == 0)
  216434. {
  216435. sendDragAndDropLeave();
  216436. if (dragAndDropFiles.size() > 0)
  216437. handleFileDragExit (dragAndDropFiles);
  216438. dragAndDropFiles.clear();
  216439. }
  216440. }
  216441. void handleDragAndDropPosition (const XClientMessageEvent* const clientMsg)
  216442. {
  216443. if (dragAndDropSourceWindow == 0)
  216444. return;
  216445. dragAndDropSourceWindow = clientMsg->data.l[0];
  216446. const int dropX = ((int) clientMsg->data.l[2] >> 16) - getScreenX();
  216447. const int dropY = ((int) clientMsg->data.l[2] & 0xffff) - getScreenY();
  216448. if (lastDropX != dropX || lastDropY != dropY)
  216449. {
  216450. lastDropX = dropX;
  216451. lastDropY = dropY;
  216452. dragAndDropTimestamp = clientMsg->data.l[3];
  216453. Atom targetAction = XA_XdndActionCopy;
  216454. for (int i = numElementsInArray (allowedActions); --i >= 0;)
  216455. {
  216456. if ((Atom) clientMsg->data.l[4] == allowedActions[i])
  216457. {
  216458. targetAction = allowedActions[i];
  216459. break;
  216460. }
  216461. }
  216462. sendDragAndDropStatus (true, targetAction);
  216463. if (dragAndDropFiles.size() == 0)
  216464. updateDraggedFileList (clientMsg);
  216465. if (dragAndDropFiles.size() > 0)
  216466. handleFileDragMove (dragAndDropFiles, dropX, dropY);
  216467. }
  216468. }
  216469. void handleDragAndDropDrop (const XClientMessageEvent* const clientMsg)
  216470. {
  216471. if (dragAndDropFiles.size() == 0)
  216472. updateDraggedFileList (clientMsg);
  216473. const StringArray files (dragAndDropFiles);
  216474. const int lastX = lastDropX, lastY = lastDropY;
  216475. sendDragAndDropFinish();
  216476. resetDragAndDrop();
  216477. if (files.size() > 0)
  216478. handleFileDragDrop (files, lastX, lastY);
  216479. }
  216480. void handleDragAndDropEnter (const XClientMessageEvent* const clientMsg)
  216481. {
  216482. dragAndDropFiles.clear();
  216483. srcMimeTypeAtomList.clear();
  216484. dragAndDropCurrentMimeType = 0;
  216485. const int dndCurrentVersion = (int) (clientMsg->data.l[1] & 0xff000000) >> 24;
  216486. if (dndCurrentVersion < 3 || dndCurrentVersion > ourDndVersion)
  216487. {
  216488. dragAndDropSourceWindow = 0;
  216489. return;
  216490. }
  216491. dragAndDropSourceWindow = clientMsg->data.l[0];
  216492. if ((clientMsg->data.l[1] & 1) != 0)
  216493. {
  216494. Atom actual;
  216495. int format;
  216496. unsigned long count = 0, remaining = 0;
  216497. unsigned char* data = 0;
  216498. XGetWindowProperty (display, dragAndDropSourceWindow, XA_XdndTypeList,
  216499. 0, 0x8000000L, False, XA_ATOM, &actual, &format,
  216500. &count, &remaining, &data);
  216501. if (data != 0)
  216502. {
  216503. if (actual == XA_ATOM && format == 32 && count != 0)
  216504. {
  216505. const unsigned long* const types = (const unsigned long*) data;
  216506. for (unsigned int i = 0; i < count; ++i)
  216507. if (types[i] != None)
  216508. srcMimeTypeAtomList.add (types[i]);
  216509. }
  216510. XFree (data);
  216511. }
  216512. }
  216513. if (srcMimeTypeAtomList.size() == 0)
  216514. {
  216515. for (int i = 2; i < 5; ++i)
  216516. if (clientMsg->data.l[i] != None)
  216517. srcMimeTypeAtomList.add (clientMsg->data.l[i]);
  216518. if (srcMimeTypeAtomList.size() == 0)
  216519. {
  216520. dragAndDropSourceWindow = 0;
  216521. return;
  216522. }
  216523. }
  216524. for (int i = 0; i < srcMimeTypeAtomList.size() && dragAndDropCurrentMimeType == 0; ++i)
  216525. for (int j = 0; j < numElementsInArray (allowedMimeTypeAtoms); ++j)
  216526. if (srcMimeTypeAtomList[i] == allowedMimeTypeAtoms[j])
  216527. dragAndDropCurrentMimeType = allowedMimeTypeAtoms[j];
  216528. handleDragAndDropPosition (clientMsg);
  216529. }
  216530. void handleDragAndDropSelection (const XEvent* const evt)
  216531. {
  216532. dragAndDropFiles.clear();
  216533. if (evt->xselection.property != 0)
  216534. {
  216535. StringArray lines;
  216536. {
  216537. MemoryBlock dropData;
  216538. for (;;)
  216539. {
  216540. Atom actual;
  216541. uint8* data = 0;
  216542. unsigned long count = 0, remaining = 0;
  216543. int format = 0;
  216544. if (XGetWindowProperty (display, evt->xany.window, evt->xselection.property,
  216545. dropData.getSize() / 4, 65536, 1, AnyPropertyType, &actual,
  216546. &format, &count, &remaining, &data) == Success)
  216547. {
  216548. dropData.append (data, count * format / 8);
  216549. XFree (data);
  216550. if (remaining == 0)
  216551. break;
  216552. }
  216553. else
  216554. {
  216555. XFree (data);
  216556. break;
  216557. }
  216558. }
  216559. lines.addLines (dropData.toString());
  216560. }
  216561. for (int i = 0; i < lines.size(); ++i)
  216562. dragAndDropFiles.add (URL::removeEscapeChars (lines[i].fromFirstOccurrenceOf (T("file://"), false, true)));
  216563. dragAndDropFiles.trim();
  216564. dragAndDropFiles.removeEmptyStrings();
  216565. }
  216566. }
  216567. void updateDraggedFileList (const XClientMessageEvent* const clientMsg)
  216568. {
  216569. dragAndDropFiles.clear();
  216570. if (dragAndDropSourceWindow != None
  216571. && dragAndDropCurrentMimeType != 0)
  216572. {
  216573. dragAndDropTimestamp = clientMsg->data.l[2];
  216574. XConvertSelection (display,
  216575. XA_XdndSelection,
  216576. dragAndDropCurrentMimeType,
  216577. XA_JXSelectionWindowProperty,
  216578. windowH,
  216579. dragAndDropTimestamp);
  216580. }
  216581. }
  216582. StringArray dragAndDropFiles;
  216583. int dragAndDropTimestamp, lastDropX, lastDropY;
  216584. Atom XA_OtherMime, dragAndDropCurrentMimeType;
  216585. Window dragAndDropSourceWindow;
  216586. unsigned int allowedActions [5];
  216587. unsigned int allowedMimeTypeAtoms [3];
  216588. Array <Atom> srcMimeTypeAtomList;
  216589. };
  216590. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars)
  216591. {
  216592. if (enableOrDisable)
  216593. kioskModeComponent->setBounds (Desktop::getInstance().getMainMonitorArea (false));
  216594. }
  216595. ComponentPeer* Component::createNewPeer (int styleFlags, void* /*nativeWindowToAttachTo*/)
  216596. {
  216597. return new LinuxComponentPeer (this, styleFlags);
  216598. }
  216599. // (this callback is hooked up in the messaging code)
  216600. void juce_windowMessageReceive (XEvent* event)
  216601. {
  216602. if (event->xany.window != None)
  216603. {
  216604. LinuxComponentPeer* const peer = LinuxComponentPeer::getPeerFor (event->xany.window);
  216605. if (ComponentPeer::isValidPeer (peer))
  216606. peer->handleWindowMessage (event);
  216607. }
  216608. else
  216609. {
  216610. switch (event->xany.type)
  216611. {
  216612. case KeymapNotify:
  216613. {
  216614. const XKeymapEvent* const keymapEvent = (const XKeymapEvent*) &event->xkeymap;
  216615. memcpy (keyStates, keymapEvent->key_vector, 32);
  216616. break;
  216617. }
  216618. default:
  216619. break;
  216620. }
  216621. }
  216622. }
  216623. void juce_updateMultiMonitorInfo (Array <Rectangle>& monitorCoords, const bool /*clipToWorkArea*/) throw()
  216624. {
  216625. #if JUCE_USE_XINERAMA
  216626. int major_opcode, first_event, first_error;
  216627. if (XQueryExtension (display, "XINERAMA", &major_opcode, &first_event, &first_error)
  216628. && XineramaIsActive (display))
  216629. {
  216630. int numMonitors = 0;
  216631. XineramaScreenInfo* const screens = XineramaQueryScreens (display, &numMonitors);
  216632. if (screens != 0)
  216633. {
  216634. for (int i = numMonitors; --i >= 0;)
  216635. {
  216636. int index = screens[i].screen_number;
  216637. if (index >= 0)
  216638. {
  216639. while (monitorCoords.size() < index)
  216640. monitorCoords.add (Rectangle (0, 0, 0, 0));
  216641. monitorCoords.set (index, Rectangle (screens[i].x_org,
  216642. screens[i].y_org,
  216643. screens[i].width,
  216644. screens[i].height));
  216645. }
  216646. }
  216647. XFree (screens);
  216648. }
  216649. }
  216650. if (monitorCoords.size() == 0)
  216651. #endif
  216652. {
  216653. Atom hints = XInternAtom (display, "_NET_WORKAREA", True);
  216654. if (hints != None)
  216655. {
  216656. const int numMonitors = ScreenCount (display);
  216657. for (int i = 0; i < numMonitors; ++i)
  216658. {
  216659. Window root = RootWindow (display, i);
  216660. unsigned long nitems, bytesLeft;
  216661. Atom actualType;
  216662. int actualFormat;
  216663. unsigned char* data = 0;
  216664. if (XGetWindowProperty (display, root, hints, 0, 4, False,
  216665. XA_CARDINAL, &actualType, &actualFormat, &nitems, &bytesLeft,
  216666. &data) == Success)
  216667. {
  216668. const long* const position = (const long*) data;
  216669. if (actualType == XA_CARDINAL && actualFormat == 32 && nitems == 4)
  216670. monitorCoords.add (Rectangle (position[0], position[1],
  216671. position[2], position[3]));
  216672. XFree (data);
  216673. }
  216674. }
  216675. }
  216676. if (monitorCoords.size() == 0)
  216677. {
  216678. monitorCoords.add (Rectangle (0, 0,
  216679. DisplayWidth (display, DefaultScreen (display)),
  216680. DisplayHeight (display, DefaultScreen (display))));
  216681. }
  216682. }
  216683. }
  216684. bool Desktop::canUseSemiTransparentWindows() throw()
  216685. {
  216686. return false;
  216687. }
  216688. void Desktop::getMousePosition (int& x, int& y) throw()
  216689. {
  216690. int mouseMods;
  216691. getMousePos (x, y, mouseMods);
  216692. }
  216693. void Desktop::setMousePosition (int x, int y) throw()
  216694. {
  216695. Window root = RootWindow (display, DefaultScreen (display));
  216696. XWarpPointer (display, None, root, 0, 0, 0, 0, x, y);
  216697. }
  216698. static bool screenSaverAllowed = true;
  216699. void Desktop::setScreenSaverEnabled (const bool isEnabled) throw()
  216700. {
  216701. if (screenSaverAllowed != isEnabled)
  216702. {
  216703. screenSaverAllowed = isEnabled;
  216704. typedef void (*tXScreenSaverSuspend) (Display*, Bool);
  216705. static tXScreenSaverSuspend xScreenSaverSuspend = 0;
  216706. if (xScreenSaverSuspend == 0)
  216707. {
  216708. void* h = dlopen ("libXss.so", RTLD_GLOBAL | RTLD_NOW);
  216709. if (h != 0)
  216710. xScreenSaverSuspend = (tXScreenSaverSuspend) dlsym (h, "XScreenSaverSuspend");
  216711. }
  216712. if (xScreenSaverSuspend != 0)
  216713. xScreenSaverSuspend (display, ! isEnabled);
  216714. }
  216715. }
  216716. bool Desktop::isScreenSaverEnabled() throw()
  216717. {
  216718. return screenSaverAllowed;
  216719. }
  216720. void* juce_createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY) throw()
  216721. {
  216722. Window root = RootWindow (display, DefaultScreen (display));
  216723. const unsigned int imageW = image.getWidth();
  216724. const unsigned int imageH = image.getHeight();
  216725. unsigned int cursorW, cursorH;
  216726. if (! XQueryBestCursor (display, root, imageW, imageH, &cursorW, &cursorH))
  216727. return 0;
  216728. Image im (Image::ARGB, cursorW, cursorH, true);
  216729. Graphics g (im);
  216730. if (imageW > cursorW || imageH > cursorH)
  216731. {
  216732. hotspotX = (hotspotX * cursorW) / imageW;
  216733. hotspotY = (hotspotY * cursorH) / imageH;
  216734. g.drawImageWithin (&image, 0, 0, imageW, imageH,
  216735. RectanglePlacement::xLeft | RectanglePlacement::yTop | RectanglePlacement::onlyReduceInSize,
  216736. false);
  216737. }
  216738. else
  216739. {
  216740. g.drawImageAt (&image, 0, 0);
  216741. }
  216742. const int stride = (cursorW + 7) >> 3;
  216743. uint8* const maskPlane = (uint8*) juce_calloc (stride * cursorH);
  216744. uint8* const sourcePlane = (uint8*) juce_calloc (stride * cursorH);
  216745. const bool msbfirst = (BitmapBitOrder (display) == MSBFirst);
  216746. for (int y = cursorH; --y >= 0;)
  216747. {
  216748. for (int x = cursorW; --x >= 0;)
  216749. {
  216750. const uint8 mask = (uint8) (1 << (msbfirst ? (7 - (x & 7)) : (x & 7)));
  216751. const int offset = y * stride + (x >> 3);
  216752. const Colour c (im.getPixelAt (x, y));
  216753. if (c.getAlpha() >= 128)
  216754. maskPlane[offset] |= mask;
  216755. if (c.getBrightness() >= 0.5f)
  216756. sourcePlane[offset] |= mask;
  216757. }
  216758. }
  216759. Pixmap sourcePixmap = XCreatePixmapFromBitmapData (display, root, (char*) sourcePlane, cursorW, cursorH, 0xffff, 0, 1);
  216760. Pixmap maskPixmap = XCreatePixmapFromBitmapData (display, root, (char*) maskPlane, cursorW, cursorH, 0xffff, 0, 1);
  216761. juce_free (maskPlane);
  216762. juce_free (sourcePlane);
  216763. XColor white, black;
  216764. black.red = black.green = black.blue = 0;
  216765. white.red = white.green = white.blue = 0xffff;
  216766. void* result = (void*) XCreatePixmapCursor (display, sourcePixmap, maskPixmap, &white, &black, hotspotX, hotspotY);
  216767. XFreePixmap (display, sourcePixmap);
  216768. XFreePixmap (display, maskPixmap);
  216769. return result;
  216770. }
  216771. void juce_deleteMouseCursor (void* const cursorHandle, const bool) throw()
  216772. {
  216773. if (cursorHandle != None)
  216774. XFreeCursor (display, (Cursor) cursorHandle);
  216775. }
  216776. void* juce_createStandardMouseCursor (MouseCursor::StandardCursorType type) throw()
  216777. {
  216778. unsigned int shape;
  216779. switch (type)
  216780. {
  216781. case MouseCursor::NoCursor:
  216782. {
  216783. const Image im (Image::ARGB, 16, 16, true);
  216784. return juce_createMouseCursorFromImage (im, 0, 0);
  216785. }
  216786. case MouseCursor::NormalCursor:
  216787. return (void*) None; // Use parent cursor
  216788. case MouseCursor::DraggingHandCursor:
  216789. {
  216790. static unsigned char dragHandData[] = {71,73,70,56,57,97,16,0,16,0,145,2,0,0,0,0,255,255,255,0,
  216791. 0,0,0,0,0,33,249,4,1,0,0,2,0,44,0,0,0,0,16,0,
  216792. 16,0,0,2,52,148,47,0,200,185,16,130,90,12,74,139,107,84,123,39,
  216793. 132,117,151,116,132,146,248,60,209,138,98,22,203,114,34,236,37,52,77,217,
  216794. 247,154,191,119,110,240,193,128,193,95,163,56,60,234,98,135,2,0,59 };
  216795. const int dragHandDataSize = 99;
  216796. Image* const im = ImageFileFormat::loadFrom ((const char*) dragHandData, dragHandDataSize);
  216797. void* const dragHandCursor = juce_createMouseCursorFromImage (*im, 8, 7);
  216798. delete im;
  216799. return dragHandCursor;
  216800. }
  216801. case MouseCursor::CopyingCursor:
  216802. {
  216803. static unsigned char copyCursorData[] = {71,73,70,56,57,97,21,0,21,0,145,0,0,0,0,0,255,255,255,0,
  216804. 128,128,255,255,255,33,249,4,1,0,0,3,0,44,0,0,0,0,21,0,
  216805. 21,0,0,2,72,4,134,169,171,16,199,98,11,79,90,71,161,93,56,111,
  216806. 78,133,218,215,137,31,82,154,100,200,86,91,202,142,12,108,212,87,235,174,
  216807. 15,54,214,126,237,226,37,96,59,141,16,37,18,201,142,157,230,204,51,112,
  216808. 252,114,147,74,83,5,50,68,147,208,217,16,71,149,252,124,5,0,59,0,0 };
  216809. const int copyCursorSize = 119;
  216810. Image* const im = ImageFileFormat::loadFrom ((const char*) copyCursorData, copyCursorSize);
  216811. void* const copyCursor = juce_createMouseCursorFromImage (*im, 1, 3);
  216812. delete im;
  216813. return copyCursor;
  216814. }
  216815. case MouseCursor::WaitCursor:
  216816. shape = XC_watch;
  216817. break;
  216818. case MouseCursor::IBeamCursor:
  216819. shape = XC_xterm;
  216820. break;
  216821. case MouseCursor::PointingHandCursor:
  216822. shape = XC_hand2;
  216823. break;
  216824. case MouseCursor::LeftRightResizeCursor:
  216825. shape = XC_sb_h_double_arrow;
  216826. break;
  216827. case MouseCursor::UpDownResizeCursor:
  216828. shape = XC_sb_v_double_arrow;
  216829. break;
  216830. case MouseCursor::UpDownLeftRightResizeCursor:
  216831. shape = XC_fleur;
  216832. break;
  216833. case MouseCursor::TopEdgeResizeCursor:
  216834. shape = XC_top_side;
  216835. break;
  216836. case MouseCursor::BottomEdgeResizeCursor:
  216837. shape = XC_bottom_side;
  216838. break;
  216839. case MouseCursor::LeftEdgeResizeCursor:
  216840. shape = XC_left_side;
  216841. break;
  216842. case MouseCursor::RightEdgeResizeCursor:
  216843. shape = XC_right_side;
  216844. break;
  216845. case MouseCursor::TopLeftCornerResizeCursor:
  216846. shape = XC_top_left_corner;
  216847. break;
  216848. case MouseCursor::TopRightCornerResizeCursor:
  216849. shape = XC_top_right_corner;
  216850. break;
  216851. case MouseCursor::BottomLeftCornerResizeCursor:
  216852. shape = XC_bottom_left_corner;
  216853. break;
  216854. case MouseCursor::BottomRightCornerResizeCursor:
  216855. shape = XC_bottom_right_corner;
  216856. break;
  216857. case MouseCursor::CrosshairCursor:
  216858. shape = XC_crosshair;
  216859. break;
  216860. default:
  216861. return (void*) None; // Use parent cursor
  216862. }
  216863. return (void*) XCreateFontCursor (display, shape);
  216864. }
  216865. void MouseCursor::showInWindow (ComponentPeer* peer) const throw()
  216866. {
  216867. LinuxComponentPeer* const lp = dynamic_cast <LinuxComponentPeer*> (peer);
  216868. if (lp != 0)
  216869. lp->showMouseCursor ((Cursor) getHandle());
  216870. }
  216871. void MouseCursor::showInAllWindows() const throw()
  216872. {
  216873. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  216874. showInWindow (ComponentPeer::getPeer (i));
  216875. }
  216876. Image* juce_createIconForFile (const File& file)
  216877. {
  216878. return 0;
  216879. }
  216880. #if JUCE_OPENGL
  216881. class WindowedGLContext : public OpenGLContext
  216882. {
  216883. public:
  216884. WindowedGLContext (Component* const component,
  216885. const OpenGLPixelFormat& pixelFormat_,
  216886. GLXContext sharedContext)
  216887. : renderContext (0),
  216888. embeddedWindow (0),
  216889. pixelFormat (pixelFormat_)
  216890. {
  216891. jassert (component != 0);
  216892. LinuxComponentPeer* const peer = dynamic_cast <LinuxComponentPeer*> (component->getTopLevelComponent()->getPeer());
  216893. if (peer == 0)
  216894. return;
  216895. XSync (display, False);
  216896. GLint attribs [64];
  216897. int n = 0;
  216898. attribs[n++] = GLX_RGBA;
  216899. attribs[n++] = GLX_DOUBLEBUFFER;
  216900. attribs[n++] = GLX_RED_SIZE;
  216901. attribs[n++] = pixelFormat.redBits;
  216902. attribs[n++] = GLX_GREEN_SIZE;
  216903. attribs[n++] = pixelFormat.greenBits;
  216904. attribs[n++] = GLX_BLUE_SIZE;
  216905. attribs[n++] = pixelFormat.blueBits;
  216906. attribs[n++] = GLX_ALPHA_SIZE;
  216907. attribs[n++] = pixelFormat.alphaBits;
  216908. attribs[n++] = GLX_DEPTH_SIZE;
  216909. attribs[n++] = pixelFormat.depthBufferBits;
  216910. attribs[n++] = GLX_STENCIL_SIZE;
  216911. attribs[n++] = pixelFormat.stencilBufferBits;
  216912. attribs[n++] = GLX_ACCUM_RED_SIZE;
  216913. attribs[n++] = pixelFormat.accumulationBufferRedBits;
  216914. attribs[n++] = GLX_ACCUM_GREEN_SIZE;
  216915. attribs[n++] = pixelFormat.accumulationBufferGreenBits;
  216916. attribs[n++] = GLX_ACCUM_BLUE_SIZE;
  216917. attribs[n++] = pixelFormat.accumulationBufferBlueBits;
  216918. attribs[n++] = GLX_ACCUM_ALPHA_SIZE;
  216919. attribs[n++] = pixelFormat.accumulationBufferAlphaBits;
  216920. // xxx not sure how to do fullSceneAntiAliasingNumSamples on linux..
  216921. attribs[n++] = None;
  216922. XVisualInfo* const bestVisual = glXChooseVisual (display, DefaultScreen (display), attribs);
  216923. if (bestVisual == 0)
  216924. return;
  216925. renderContext = glXCreateContext (display, bestVisual, sharedContext, GL_TRUE);
  216926. Window windowH = (Window) peer->getNativeHandle();
  216927. Colormap colourMap = XCreateColormap (display, windowH, bestVisual->visual, AllocNone);
  216928. XSetWindowAttributes swa;
  216929. swa.colormap = colourMap;
  216930. swa.border_pixel = 0;
  216931. swa.event_mask = ExposureMask | StructureNotifyMask;
  216932. embeddedWindow = XCreateWindow (display, windowH,
  216933. 0, 0, 1, 1, 0,
  216934. bestVisual->depth,
  216935. InputOutput,
  216936. bestVisual->visual,
  216937. CWBorderPixel | CWColormap | CWEventMask,
  216938. &swa);
  216939. XSaveContext (display, (XID) embeddedWindow, improbableNumber, (XPointer) peer);
  216940. XMapWindow (display, embeddedWindow);
  216941. XFreeColormap (display, colourMap);
  216942. XFree (bestVisual);
  216943. XSync (display, False);
  216944. }
  216945. ~WindowedGLContext()
  216946. {
  216947. makeInactive();
  216948. glXDestroyContext (display, renderContext);
  216949. XUnmapWindow (display, embeddedWindow);
  216950. XDestroyWindow (display, embeddedWindow);
  216951. }
  216952. bool makeActive() const throw()
  216953. {
  216954. jassert (renderContext != 0);
  216955. return glXMakeCurrent (display, embeddedWindow, renderContext)
  216956. && XSync (display, False);
  216957. }
  216958. bool makeInactive() const throw()
  216959. {
  216960. return (! isActive()) || glXMakeCurrent (display, None, 0);
  216961. }
  216962. bool isActive() const throw()
  216963. {
  216964. return glXGetCurrentContext() == renderContext;
  216965. }
  216966. const OpenGLPixelFormat getPixelFormat() const
  216967. {
  216968. return pixelFormat;
  216969. }
  216970. void* getRawContext() const throw()
  216971. {
  216972. return renderContext;
  216973. }
  216974. void updateWindowPosition (int x, int y, int w, int h, int)
  216975. {
  216976. XMoveResizeWindow (display, embeddedWindow,
  216977. x, y, jmax (1, w), jmax (1, h));
  216978. }
  216979. void swapBuffers()
  216980. {
  216981. glXSwapBuffers (display, embeddedWindow);
  216982. }
  216983. bool setSwapInterval (const int numFramesPerSwap)
  216984. {
  216985. // xxx needs doing..
  216986. return false;
  216987. }
  216988. int getSwapInterval() const
  216989. {
  216990. // xxx needs doing..
  216991. return 0;
  216992. }
  216993. void repaint()
  216994. {
  216995. }
  216996. juce_UseDebuggingNewOperator
  216997. GLXContext renderContext;
  216998. private:
  216999. Window embeddedWindow;
  217000. OpenGLPixelFormat pixelFormat;
  217001. WindowedGLContext (const WindowedGLContext&);
  217002. const WindowedGLContext& operator= (const WindowedGLContext&);
  217003. };
  217004. OpenGLContext* OpenGLContext::createContextForWindow (Component* const component,
  217005. const OpenGLPixelFormat& pixelFormat,
  217006. const OpenGLContext* const contextToShareWith)
  217007. {
  217008. WindowedGLContext* c = new WindowedGLContext (component, pixelFormat,
  217009. contextToShareWith != 0 ? (GLXContext) contextToShareWith->getRawContext() : 0);
  217010. if (c->renderContext == 0)
  217011. deleteAndZero (c);
  217012. return c;
  217013. }
  217014. void juce_glViewport (const int w, const int h)
  217015. {
  217016. glViewport (0, 0, w, h);
  217017. }
  217018. void OpenGLPixelFormat::getAvailablePixelFormats (Component* component,
  217019. OwnedArray <OpenGLPixelFormat>& results)
  217020. {
  217021. results.add (new OpenGLPixelFormat()); // xxx
  217022. }
  217023. #endif
  217024. static void initClipboard (Window root, Atom* cutBuffers) throw()
  217025. {
  217026. static bool init = false;
  217027. if (! init)
  217028. {
  217029. init = true;
  217030. // Make sure all cut buffers exist before use
  217031. for (int i = 0; i < 8; i++)
  217032. {
  217033. XChangeProperty (display, root, cutBuffers[i],
  217034. XA_STRING, 8, PropModeAppend, NULL, 0);
  217035. }
  217036. }
  217037. }
  217038. // Clipboard implemented currently using cut buffers
  217039. // rather than the more powerful selection method
  217040. void SystemClipboard::copyTextToClipboard (const String& clipText) throw()
  217041. {
  217042. Window root = RootWindow (display, DefaultScreen (display));
  217043. Atom cutBuffers[8] = { XA_CUT_BUFFER0, XA_CUT_BUFFER1, XA_CUT_BUFFER2, XA_CUT_BUFFER3,
  217044. XA_CUT_BUFFER4, XA_CUT_BUFFER5, XA_CUT_BUFFER6, XA_CUT_BUFFER7 };
  217045. initClipboard (root, cutBuffers);
  217046. XRotateWindowProperties (display, root, cutBuffers, 8, 1);
  217047. XChangeProperty (display, root, cutBuffers[0],
  217048. XA_STRING, 8, PropModeReplace, (const unsigned char*) (const char*) clipText,
  217049. clipText.length());
  217050. }
  217051. const String SystemClipboard::getTextFromClipboard() throw()
  217052. {
  217053. const int bufSize = 64; // in words
  217054. String returnData;
  217055. int byteOffset = 0;
  217056. Window root = RootWindow (display, DefaultScreen (display));
  217057. Atom cutBuffers[8] = { XA_CUT_BUFFER0, XA_CUT_BUFFER1, XA_CUT_BUFFER2, XA_CUT_BUFFER3,
  217058. XA_CUT_BUFFER4, XA_CUT_BUFFER5, XA_CUT_BUFFER6, XA_CUT_BUFFER7 };
  217059. initClipboard (root, cutBuffers);
  217060. for (;;)
  217061. {
  217062. unsigned long bytesLeft = 0, nitems = 0;
  217063. unsigned char* clipData = 0;
  217064. int actualFormat = 0;
  217065. Atom actualType;
  217066. if (XGetWindowProperty (display, root, cutBuffers[0], byteOffset >> 2, bufSize,
  217067. False, XA_STRING, &actualType, &actualFormat, &nitems, &bytesLeft,
  217068. &clipData) == Success)
  217069. {
  217070. if (actualType == XA_STRING && actualFormat == 8)
  217071. {
  217072. byteOffset += nitems;
  217073. returnData += String ((const char*) clipData, nitems);
  217074. }
  217075. else
  217076. {
  217077. bytesLeft = 0;
  217078. }
  217079. if (clipData != 0)
  217080. XFree (clipData);
  217081. }
  217082. if (bytesLeft == 0)
  217083. break;
  217084. }
  217085. return returnData;
  217086. }
  217087. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMoveFiles)
  217088. {
  217089. jassertfalse // not implemented!
  217090. return false;
  217091. }
  217092. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  217093. {
  217094. jassertfalse // not implemented!
  217095. return false;
  217096. }
  217097. void SystemTrayIconComponent::setIconImage (const Image& newImage)
  217098. {
  217099. if (! isOnDesktop ())
  217100. addToDesktop (0);
  217101. LinuxComponentPeer* const wp = dynamic_cast <LinuxComponentPeer*> (getPeer());
  217102. if (wp != 0)
  217103. {
  217104. wp->setTaskBarIcon (newImage);
  217105. setVisible (true);
  217106. toFront (false);
  217107. repaint();
  217108. }
  217109. }
  217110. void SystemTrayIconComponent::paint (Graphics& g)
  217111. {
  217112. LinuxComponentPeer* const wp = dynamic_cast <LinuxComponentPeer*> (getPeer());
  217113. if (wp != 0)
  217114. {
  217115. const Image* const image = wp->getTaskbarIcon();
  217116. if (image != 0)
  217117. {
  217118. g.drawImageWithin (image, 0, 0, getWidth(), getHeight(),
  217119. RectanglePlacement::xLeft | RectanglePlacement::yTop | RectanglePlacement::onlyReduceInSize,
  217120. false);
  217121. }
  217122. }
  217123. }
  217124. void SystemTrayIconComponent::setIconTooltip (const String& tooltip)
  217125. {
  217126. // xxx not yet implemented!
  217127. }
  217128. void PlatformUtilities::beep()
  217129. {
  217130. fprintf (stdout, "\a");
  217131. fflush (stdout);
  217132. }
  217133. bool AlertWindow::showNativeDialogBox (const String& title,
  217134. const String& bodyText,
  217135. bool isOkCancel)
  217136. {
  217137. // xxx this is supposed to pop up an alert!
  217138. Logger::outputDebugString (title + ": " + bodyText);
  217139. // use a non-native one for the time being..
  217140. if (isOkCancel)
  217141. return AlertWindow::showOkCancelBox (AlertWindow::NoIcon, title, bodyText);
  217142. else
  217143. AlertWindow::showMessageBox (AlertWindow::NoIcon, title, bodyText);
  217144. return true;
  217145. }
  217146. const int KeyPress::spaceKey = XK_space & 0xff;
  217147. const int KeyPress::returnKey = XK_Return & 0xff;
  217148. const int KeyPress::escapeKey = XK_Escape & 0xff;
  217149. const int KeyPress::backspaceKey = XK_BackSpace & 0xff;
  217150. const int KeyPress::leftKey = (XK_Left & 0xff) | extendedKeyModifier;
  217151. const int KeyPress::rightKey = (XK_Right & 0xff) | extendedKeyModifier;
  217152. const int KeyPress::upKey = (XK_Up & 0xff) | extendedKeyModifier;
  217153. const int KeyPress::downKey = (XK_Down & 0xff) | extendedKeyModifier;
  217154. const int KeyPress::pageUpKey = (XK_Page_Up & 0xff) | extendedKeyModifier;
  217155. const int KeyPress::pageDownKey = (XK_Page_Down & 0xff) | extendedKeyModifier;
  217156. const int KeyPress::endKey = (XK_End & 0xff) | extendedKeyModifier;
  217157. const int KeyPress::homeKey = (XK_Home & 0xff) | extendedKeyModifier;
  217158. const int KeyPress::insertKey = (XK_Insert & 0xff) | extendedKeyModifier;
  217159. const int KeyPress::deleteKey = (XK_Delete & 0xff) | extendedKeyModifier;
  217160. const int KeyPress::tabKey = XK_Tab & 0xff;
  217161. const int KeyPress::F1Key = (XK_F1 & 0xff) | extendedKeyModifier;
  217162. const int KeyPress::F2Key = (XK_F2 & 0xff) | extendedKeyModifier;
  217163. const int KeyPress::F3Key = (XK_F3 & 0xff) | extendedKeyModifier;
  217164. const int KeyPress::F4Key = (XK_F4 & 0xff) | extendedKeyModifier;
  217165. const int KeyPress::F5Key = (XK_F5 & 0xff) | extendedKeyModifier;
  217166. const int KeyPress::F6Key = (XK_F6 & 0xff) | extendedKeyModifier;
  217167. const int KeyPress::F7Key = (XK_F7 & 0xff) | extendedKeyModifier;
  217168. const int KeyPress::F8Key = (XK_F8 & 0xff) | extendedKeyModifier;
  217169. const int KeyPress::F9Key = (XK_F9 & 0xff) | extendedKeyModifier;
  217170. const int KeyPress::F10Key = (XK_F10 & 0xff) | extendedKeyModifier;
  217171. const int KeyPress::F11Key = (XK_F11 & 0xff) | extendedKeyModifier;
  217172. const int KeyPress::F12Key = (XK_F12 & 0xff) | extendedKeyModifier;
  217173. const int KeyPress::F13Key = (XK_F13 & 0xff) | extendedKeyModifier;
  217174. const int KeyPress::F14Key = (XK_F14 & 0xff) | extendedKeyModifier;
  217175. const int KeyPress::F15Key = (XK_F15 & 0xff) | extendedKeyModifier;
  217176. const int KeyPress::F16Key = (XK_F16 & 0xff) | extendedKeyModifier;
  217177. const int KeyPress::numberPad0 = (XK_KP_0 & 0xff) | extendedKeyModifier;
  217178. const int KeyPress::numberPad1 = (XK_KP_1 & 0xff) | extendedKeyModifier;
  217179. const int KeyPress::numberPad2 = (XK_KP_2 & 0xff) | extendedKeyModifier;
  217180. const int KeyPress::numberPad3 = (XK_KP_3 & 0xff) | extendedKeyModifier;
  217181. const int KeyPress::numberPad4 = (XK_KP_4 & 0xff) | extendedKeyModifier;
  217182. const int KeyPress::numberPad5 = (XK_KP_5 & 0xff) | extendedKeyModifier;
  217183. const int KeyPress::numberPad6 = (XK_KP_6 & 0xff) | extendedKeyModifier;
  217184. const int KeyPress::numberPad7 = (XK_KP_7 & 0xff)| extendedKeyModifier;
  217185. const int KeyPress::numberPad8 = (XK_KP_8 & 0xff)| extendedKeyModifier;
  217186. const int KeyPress::numberPad9 = (XK_KP_9 & 0xff)| extendedKeyModifier;
  217187. const int KeyPress::numberPadAdd = (XK_KP_Add & 0xff)| extendedKeyModifier;
  217188. const int KeyPress::numberPadSubtract = (XK_KP_Subtract & 0xff)| extendedKeyModifier;
  217189. const int KeyPress::numberPadMultiply = (XK_KP_Multiply & 0xff)| extendedKeyModifier;
  217190. const int KeyPress::numberPadDivide = (XK_KP_Divide & 0xff)| extendedKeyModifier;
  217191. const int KeyPress::numberPadSeparator = (XK_KP_Separator & 0xff)| extendedKeyModifier;
  217192. const int KeyPress::numberPadDecimalPoint = (XK_KP_Decimal & 0xff)| extendedKeyModifier;
  217193. const int KeyPress::numberPadEquals = (XK_KP_Equal & 0xff)| extendedKeyModifier;
  217194. const int KeyPress::numberPadDelete = (XK_KP_Delete & 0xff)| extendedKeyModifier;
  217195. const int KeyPress::playKey = (0xffeeff00) | extendedKeyModifier;
  217196. const int KeyPress::stopKey = (0xffeeff01) | extendedKeyModifier;
  217197. const int KeyPress::fastForwardKey = (0xffeeff02) | extendedKeyModifier;
  217198. const int KeyPress::rewindKey = (0xffeeff03) | extendedKeyModifier;
  217199. #endif
  217200. /********* End of inlined file: juce_linux_Windowing.cpp *********/
  217201. /********* Start of inlined file: juce_linux_Audio.cpp *********/
  217202. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  217203. // compiled on its own).
  217204. #ifdef JUCE_INCLUDED_FILE && JUCE_ALSA
  217205. static const int maxNumChans = 64;
  217206. static void getDeviceSampleRates (snd_pcm_t* handle, Array <int>& rates)
  217207. {
  217208. const int ratesToTry[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  217209. snd_pcm_hw_params_t* hwParams;
  217210. snd_pcm_hw_params_alloca (&hwParams);
  217211. for (int i = 0; ratesToTry[i] != 0; ++i)
  217212. {
  217213. if (snd_pcm_hw_params_any (handle, hwParams) >= 0
  217214. && snd_pcm_hw_params_test_rate (handle, hwParams, ratesToTry[i], 0) == 0)
  217215. {
  217216. rates.addIfNotAlreadyThere (ratesToTry[i]);
  217217. }
  217218. }
  217219. }
  217220. static void getDeviceNumChannels (snd_pcm_t* handle, unsigned int* minChans, unsigned int* maxChans)
  217221. {
  217222. snd_pcm_hw_params_t *params;
  217223. snd_pcm_hw_params_alloca (&params);
  217224. if (snd_pcm_hw_params_any (handle, params) >= 0)
  217225. {
  217226. snd_pcm_hw_params_get_channels_min (params, minChans);
  217227. snd_pcm_hw_params_get_channels_max (params, maxChans);
  217228. }
  217229. }
  217230. static void getDeviceProperties (const String& id,
  217231. unsigned int& minChansOut,
  217232. unsigned int& maxChansOut,
  217233. unsigned int& minChansIn,
  217234. unsigned int& maxChansIn,
  217235. Array <int>& rates)
  217236. {
  217237. if (id.isEmpty())
  217238. return;
  217239. snd_ctl_t* handle;
  217240. if (snd_ctl_open (&handle, id.upToLastOccurrenceOf (T(","), false, false), SND_CTL_NONBLOCK) >= 0)
  217241. {
  217242. snd_pcm_info_t* info;
  217243. snd_pcm_info_alloca (&info);
  217244. snd_pcm_info_set_stream (info, SND_PCM_STREAM_PLAYBACK);
  217245. snd_pcm_info_set_device (info, id.fromLastOccurrenceOf (T(","), false, false).getIntValue());
  217246. snd_pcm_info_set_subdevice (info, 0);
  217247. if (snd_ctl_pcm_info (handle, info) >= 0)
  217248. {
  217249. snd_pcm_t* pcmHandle;
  217250. if (snd_pcm_open (&pcmHandle, id, SND_PCM_STREAM_PLAYBACK, SND_PCM_ASYNC | SND_PCM_NONBLOCK ) >= 0)
  217251. {
  217252. getDeviceNumChannels (pcmHandle, &minChansOut, &maxChansOut);
  217253. getDeviceSampleRates (pcmHandle, rates);
  217254. snd_pcm_close (pcmHandle);
  217255. }
  217256. }
  217257. snd_pcm_info_set_stream (info, SND_PCM_STREAM_CAPTURE);
  217258. if (snd_ctl_pcm_info (handle, info) >= 0)
  217259. {
  217260. snd_pcm_t* pcmHandle;
  217261. if (snd_pcm_open (&pcmHandle, id, SND_PCM_STREAM_CAPTURE, SND_PCM_ASYNC | SND_PCM_NONBLOCK ) >= 0)
  217262. {
  217263. getDeviceNumChannels (pcmHandle, &minChansIn, &maxChansIn);
  217264. if (rates.size() == 0)
  217265. getDeviceSampleRates (pcmHandle, rates);
  217266. snd_pcm_close (pcmHandle);
  217267. }
  217268. }
  217269. snd_ctl_close (handle);
  217270. }
  217271. }
  217272. class ALSADevice
  217273. {
  217274. public:
  217275. ALSADevice (const String& id,
  217276. const bool forInput)
  217277. : handle (0),
  217278. bitDepth (16),
  217279. numChannelsRunning (0),
  217280. isInput (forInput),
  217281. sampleFormat (AudioDataConverters::int16LE)
  217282. {
  217283. failed (snd_pcm_open (&handle, id,
  217284. forInput ? SND_PCM_STREAM_CAPTURE : SND_PCM_STREAM_PLAYBACK,
  217285. SND_PCM_ASYNC));
  217286. }
  217287. ~ALSADevice()
  217288. {
  217289. if (handle != 0)
  217290. snd_pcm_close (handle);
  217291. }
  217292. bool setParameters (unsigned int sampleRate, int numChannels, int bufferSize)
  217293. {
  217294. if (handle == 0)
  217295. return false;
  217296. snd_pcm_hw_params_t* hwParams;
  217297. snd_pcm_hw_params_alloca (&hwParams);
  217298. if (failed (snd_pcm_hw_params_any (handle, hwParams)))
  217299. return false;
  217300. if (snd_pcm_hw_params_set_access (handle, hwParams, SND_PCM_ACCESS_RW_NONINTERLEAVED) >= 0)
  217301. isInterleaved = false;
  217302. else if (snd_pcm_hw_params_set_access (handle, hwParams, SND_PCM_ACCESS_RW_INTERLEAVED) >= 0)
  217303. isInterleaved = true;
  217304. else
  217305. {
  217306. jassertfalse
  217307. return false;
  217308. }
  217309. const int formatsToTry[] = { SND_PCM_FORMAT_FLOAT_LE, 32, AudioDataConverters::float32LE,
  217310. SND_PCM_FORMAT_FLOAT_BE, 32, AudioDataConverters::float32BE,
  217311. SND_PCM_FORMAT_S32_LE, 32, AudioDataConverters::int32LE,
  217312. SND_PCM_FORMAT_S32_BE, 32, AudioDataConverters::int32BE,
  217313. SND_PCM_FORMAT_S24_3LE, 24, AudioDataConverters::int24LE,
  217314. SND_PCM_FORMAT_S24_3BE, 24, AudioDataConverters::int24BE,
  217315. SND_PCM_FORMAT_S16_LE, 16, AudioDataConverters::int16LE,
  217316. SND_PCM_FORMAT_S16_BE, 16, AudioDataConverters::int16BE };
  217317. bitDepth = 0;
  217318. for (int i = 0; i < numElementsInArray (formatsToTry); i += 3)
  217319. {
  217320. if (snd_pcm_hw_params_set_format (handle, hwParams, (_snd_pcm_format) formatsToTry [i]) >= 0)
  217321. {
  217322. bitDepth = formatsToTry [i + 1];
  217323. sampleFormat = (AudioDataConverters::DataFormat) formatsToTry [i + 2];
  217324. break;
  217325. }
  217326. }
  217327. if (bitDepth == 0)
  217328. {
  217329. error = "device doesn't support a compatible PCM format";
  217330. DBG (T("ALSA error: ") + error + T("\n"));
  217331. return false;
  217332. }
  217333. int dir = 0;
  217334. unsigned int periods = 4;
  217335. snd_pcm_uframes_t samplesPerPeriod = bufferSize;
  217336. if (failed (snd_pcm_hw_params_set_rate_near (handle, hwParams, &sampleRate, 0))
  217337. || failed (snd_pcm_hw_params_set_channels (handle, hwParams, numChannels))
  217338. || failed (snd_pcm_hw_params_set_periods_near (handle, hwParams, &periods, &dir))
  217339. || failed (snd_pcm_hw_params_set_period_size_near (handle, hwParams, &samplesPerPeriod, &dir))
  217340. || failed (snd_pcm_hw_params (handle, hwParams)))
  217341. {
  217342. return false;
  217343. }
  217344. snd_pcm_sw_params_t* swParams;
  217345. snd_pcm_sw_params_alloca (&swParams);
  217346. snd_pcm_uframes_t boundary;
  217347. if (failed (snd_pcm_sw_params_current (handle, swParams))
  217348. || failed (snd_pcm_sw_params_get_boundary (swParams, &boundary))
  217349. || failed (snd_pcm_sw_params_set_silence_threshold (handle, swParams, 0))
  217350. || failed (snd_pcm_sw_params_set_silence_size (handle, swParams, boundary))
  217351. || failed (snd_pcm_sw_params_set_start_threshold (handle, swParams, samplesPerPeriod))
  217352. || failed (snd_pcm_sw_params_set_stop_threshold (handle, swParams, boundary))
  217353. || failed (snd_pcm_sw_params (handle, swParams)))
  217354. {
  217355. return false;
  217356. }
  217357. /*
  217358. #ifdef JUCE_DEBUG
  217359. // enable this to dump the config of the devices that get opened
  217360. snd_output_t* out;
  217361. snd_output_stdio_attach (&out, stderr, 0);
  217362. snd_pcm_hw_params_dump (hwParams, out);
  217363. snd_pcm_sw_params_dump (swParams, out);
  217364. #endif
  217365. */
  217366. numChannelsRunning = numChannels;
  217367. return true;
  217368. }
  217369. bool write (float** const data, const int numSamples)
  217370. {
  217371. if (isInterleaved)
  217372. {
  217373. scratch.ensureSize (sizeof (float) * numSamples * numChannelsRunning, false);
  217374. float* interleaved = (float*) scratch;
  217375. AudioDataConverters::interleaveSamples ((const float**) data, interleaved, numSamples, numChannelsRunning);
  217376. AudioDataConverters::convertFloatToFormat (sampleFormat, interleaved, interleaved, numSamples * numChannelsRunning);
  217377. snd_pcm_sframes_t num = snd_pcm_writei (handle, (void*) interleaved, numSamples);
  217378. if (failed (num) && num != -EPIPE && num != -ESTRPIPE)
  217379. return false;
  217380. }
  217381. else
  217382. {
  217383. for (int i = 0; i < numChannelsRunning; ++i)
  217384. if (data[i] != 0)
  217385. AudioDataConverters::convertFloatToFormat (sampleFormat, data[i], data[i], numSamples);
  217386. snd_pcm_sframes_t num = snd_pcm_writen (handle, (void**) data, numSamples);
  217387. if (failed (num))
  217388. {
  217389. if (num == -EPIPE)
  217390. {
  217391. if (failed (snd_pcm_prepare (handle)))
  217392. return false;
  217393. }
  217394. else if (num != -ESTRPIPE)
  217395. return false;
  217396. }
  217397. }
  217398. return true;
  217399. }
  217400. bool read (float** const data, const int numSamples)
  217401. {
  217402. if (isInterleaved)
  217403. {
  217404. scratch.ensureSize (sizeof (float) * numSamples * numChannelsRunning, false);
  217405. float* interleaved = (float*) scratch;
  217406. snd_pcm_sframes_t num = snd_pcm_readi (handle, (void*) interleaved, numSamples);
  217407. if (failed (num))
  217408. {
  217409. if (num == -EPIPE)
  217410. {
  217411. if (failed (snd_pcm_prepare (handle)))
  217412. return false;
  217413. }
  217414. else if (num != -ESTRPIPE)
  217415. return false;
  217416. }
  217417. AudioDataConverters::convertFormatToFloat (sampleFormat, interleaved, interleaved, numSamples * numChannelsRunning);
  217418. AudioDataConverters::deinterleaveSamples (interleaved, data, numSamples, numChannelsRunning);
  217419. }
  217420. else
  217421. {
  217422. snd_pcm_sframes_t num = snd_pcm_readn (handle, (void**) data, numSamples);
  217423. if (failed (num) && num != -EPIPE && num != -ESTRPIPE)
  217424. return false;
  217425. for (int i = 0; i < numChannelsRunning; ++i)
  217426. if (data[i] != 0)
  217427. AudioDataConverters::convertFormatToFloat (sampleFormat, data[i], data[i], numSamples);
  217428. }
  217429. return true;
  217430. }
  217431. juce_UseDebuggingNewOperator
  217432. snd_pcm_t* handle;
  217433. String error;
  217434. int bitDepth, numChannelsRunning;
  217435. private:
  217436. const bool isInput;
  217437. bool isInterleaved;
  217438. MemoryBlock scratch;
  217439. AudioDataConverters::DataFormat sampleFormat;
  217440. bool failed (const int errorNum)
  217441. {
  217442. if (errorNum >= 0)
  217443. return false;
  217444. error = snd_strerror (errorNum);
  217445. DBG (T("ALSA error: ") + error + T("\n"));
  217446. return true;
  217447. }
  217448. };
  217449. class ALSAThread : public Thread
  217450. {
  217451. public:
  217452. ALSAThread (const String& inputId_,
  217453. const String& outputId_)
  217454. : Thread ("Juce ALSA"),
  217455. sampleRate (0),
  217456. bufferSize (0),
  217457. callback (0),
  217458. inputId (inputId_),
  217459. outputId (outputId_),
  217460. outputDevice (0),
  217461. inputDevice (0),
  217462. numCallbacks (0),
  217463. totalNumInputChannels (0),
  217464. totalNumOutputChannels (0)
  217465. {
  217466. zeromem (outputChannelData, sizeof (outputChannelData));
  217467. zeromem (outputChannelDataForCallback, sizeof (outputChannelDataForCallback));
  217468. zeromem (inputChannelData, sizeof (inputChannelData));
  217469. zeromem (inputChannelDataForCallback, sizeof (inputChannelDataForCallback));
  217470. initialiseRatesAndChannels();
  217471. }
  217472. ~ALSAThread()
  217473. {
  217474. close();
  217475. }
  217476. void open (BitArray inputChannels,
  217477. BitArray outputChannels,
  217478. const double sampleRate_,
  217479. const int bufferSize_)
  217480. {
  217481. close();
  217482. error = String::empty;
  217483. sampleRate = sampleRate_;
  217484. bufferSize = bufferSize_;
  217485. currentInputChans.clear();
  217486. currentOutputChans.clear();
  217487. if (inputChannels.getHighestBit() >= 0)
  217488. {
  217489. for (int i = 0; i <= jmax (inputChannels.getHighestBit(), minChansIn); ++i)
  217490. {
  217491. inputChannelData [i] = (float*) juce_calloc (sizeof (float) * bufferSize);
  217492. if (inputChannels[i])
  217493. {
  217494. inputChannelDataForCallback [totalNumInputChannels++] = inputChannelData [i];
  217495. currentInputChans.setBit (i);
  217496. }
  217497. }
  217498. }
  217499. if (outputChannels.getHighestBit() >= 0)
  217500. {
  217501. for (int i = 0; i <= jmax (outputChannels.getHighestBit(), minChansOut); ++i)
  217502. {
  217503. outputChannelData [i] = (float*) juce_calloc (sizeof (float) * bufferSize);
  217504. if (outputChannels[i])
  217505. {
  217506. outputChannelDataForCallback [totalNumOutputChannels++] = outputChannelData [i];
  217507. currentOutputChans.setBit (i);
  217508. }
  217509. }
  217510. }
  217511. if (totalNumOutputChannels > 0 && outputId.isNotEmpty())
  217512. {
  217513. outputDevice = new ALSADevice (outputId, false);
  217514. if (outputDevice->error.isNotEmpty())
  217515. {
  217516. error = outputDevice->error;
  217517. deleteAndZero (outputDevice);
  217518. return;
  217519. }
  217520. currentOutputChans.setRange (0, minChansOut, true);
  217521. if (! outputDevice->setParameters ((unsigned int) sampleRate,
  217522. jlimit ((int) minChansOut, (int) maxChansOut, currentOutputChans.getHighestBit() + 1),
  217523. bufferSize))
  217524. {
  217525. error = outputDevice->error;
  217526. deleteAndZero (outputDevice);
  217527. return;
  217528. }
  217529. }
  217530. if (totalNumInputChannels > 0 && inputId.isNotEmpty())
  217531. {
  217532. inputDevice = new ALSADevice (inputId, true);
  217533. if (inputDevice->error.isNotEmpty())
  217534. {
  217535. error = inputDevice->error;
  217536. deleteAndZero (inputDevice);
  217537. return;
  217538. }
  217539. currentInputChans.setRange (0, minChansIn, true);
  217540. if (! inputDevice->setParameters ((unsigned int) sampleRate,
  217541. jlimit ((int) minChansIn, (int) maxChansIn, currentInputChans.getHighestBit() + 1),
  217542. bufferSize))
  217543. {
  217544. error = inputDevice->error;
  217545. deleteAndZero (inputDevice);
  217546. return;
  217547. }
  217548. }
  217549. if (outputDevice == 0 && inputDevice == 0)
  217550. {
  217551. error = "no channels";
  217552. return;
  217553. }
  217554. if (outputDevice != 0 && inputDevice != 0)
  217555. {
  217556. snd_pcm_link (outputDevice->handle, inputDevice->handle);
  217557. }
  217558. if (inputDevice != 0 && failed (snd_pcm_prepare (inputDevice->handle)))
  217559. return;
  217560. if (outputDevice != 0 && failed (snd_pcm_prepare (outputDevice->handle)))
  217561. return;
  217562. startThread (9);
  217563. int count = 1000;
  217564. while (numCallbacks == 0)
  217565. {
  217566. sleep (5);
  217567. if (--count < 0 || ! isThreadRunning())
  217568. {
  217569. error = "device didn't start";
  217570. break;
  217571. }
  217572. }
  217573. }
  217574. void close()
  217575. {
  217576. stopThread (6000);
  217577. deleteAndZero (inputDevice);
  217578. deleteAndZero (outputDevice);
  217579. for (int i = 0; i < maxNumChans; ++i)
  217580. {
  217581. juce_free (inputChannelData [i]);
  217582. juce_free (outputChannelData [i]);
  217583. }
  217584. zeromem (outputChannelData, sizeof (outputChannelData));
  217585. zeromem (outputChannelDataForCallback, sizeof (outputChannelDataForCallback));
  217586. zeromem (inputChannelData, sizeof (inputChannelData));
  217587. zeromem (inputChannelDataForCallback, sizeof (inputChannelDataForCallback));
  217588. totalNumOutputChannels = 0;
  217589. totalNumInputChannels = 0;
  217590. numCallbacks = 0;
  217591. }
  217592. void setCallback (AudioIODeviceCallback* const newCallback) throw()
  217593. {
  217594. const ScopedLock sl (callbackLock);
  217595. callback = newCallback;
  217596. }
  217597. void run()
  217598. {
  217599. while (! threadShouldExit())
  217600. {
  217601. if (inputDevice != 0)
  217602. {
  217603. if (! inputDevice->read (inputChannelData, bufferSize))
  217604. {
  217605. DBG ("ALSA: read failure");
  217606. break;
  217607. }
  217608. }
  217609. if (threadShouldExit())
  217610. break;
  217611. {
  217612. const ScopedLock sl (callbackLock);
  217613. ++numCallbacks;
  217614. if (callback != 0)
  217615. {
  217616. callback->audioDeviceIOCallback ((const float**) inputChannelDataForCallback,
  217617. totalNumInputChannels,
  217618. outputChannelDataForCallback,
  217619. totalNumOutputChannels,
  217620. bufferSize);
  217621. }
  217622. else
  217623. {
  217624. for (int i = 0; i < totalNumOutputChannels; ++i)
  217625. zeromem (outputChannelDataForCallback[i], sizeof (float) * bufferSize);
  217626. }
  217627. }
  217628. if (outputDevice != 0)
  217629. {
  217630. failed (snd_pcm_wait (outputDevice->handle, 2000));
  217631. if (threadShouldExit())
  217632. break;
  217633. failed (snd_pcm_avail_update (outputDevice->handle));
  217634. if (! outputDevice->write (outputChannelData, bufferSize))
  217635. {
  217636. DBG ("ALSA: write failure");
  217637. break;
  217638. }
  217639. }
  217640. }
  217641. }
  217642. int getBitDepth() const throw()
  217643. {
  217644. if (outputDevice != 0)
  217645. return outputDevice->bitDepth;
  217646. if (inputDevice != 0)
  217647. return inputDevice->bitDepth;
  217648. return 16;
  217649. }
  217650. juce_UseDebuggingNewOperator
  217651. String error;
  217652. double sampleRate;
  217653. int bufferSize;
  217654. BitArray currentInputChans, currentOutputChans;
  217655. Array <int> sampleRates;
  217656. StringArray channelNamesOut, channelNamesIn;
  217657. AudioIODeviceCallback* callback;
  217658. private:
  217659. const String inputId, outputId;
  217660. ALSADevice* outputDevice;
  217661. ALSADevice* inputDevice;
  217662. int numCallbacks;
  217663. CriticalSection callbackLock;
  217664. float* outputChannelData [maxNumChans];
  217665. float* outputChannelDataForCallback [maxNumChans];
  217666. int totalNumInputChannels;
  217667. float* inputChannelData [maxNumChans];
  217668. float* inputChannelDataForCallback [maxNumChans];
  217669. int totalNumOutputChannels;
  217670. unsigned int minChansOut, maxChansOut;
  217671. unsigned int minChansIn, maxChansIn;
  217672. bool failed (const int errorNum) throw()
  217673. {
  217674. if (errorNum >= 0)
  217675. return false;
  217676. error = snd_strerror (errorNum);
  217677. DBG (T("ALSA error: ") + error + T("\n"));
  217678. return true;
  217679. }
  217680. void initialiseRatesAndChannels() throw()
  217681. {
  217682. sampleRates.clear();
  217683. channelNamesOut.clear();
  217684. channelNamesIn.clear();
  217685. minChansOut = 0;
  217686. maxChansOut = 0;
  217687. minChansIn = 0;
  217688. maxChansIn = 0;
  217689. unsigned int dummy = 0;
  217690. getDeviceProperties (inputId, dummy, dummy, minChansIn, maxChansIn, sampleRates);
  217691. getDeviceProperties (outputId, minChansOut, maxChansOut, dummy, dummy, sampleRates);
  217692. unsigned int i;
  217693. for (i = 0; i < maxChansOut; ++i)
  217694. channelNamesOut.add (T("channel ") + String ((int) i + 1));
  217695. for (i = 0; i < maxChansIn; ++i)
  217696. channelNamesIn.add (T("channel ") + String ((int) i + 1));
  217697. }
  217698. };
  217699. class ALSAAudioIODevice : public AudioIODevice
  217700. {
  217701. public:
  217702. ALSAAudioIODevice (const String& deviceName,
  217703. const String& inputId_,
  217704. const String& outputId_)
  217705. : AudioIODevice (deviceName, T("ALSA")),
  217706. inputId (inputId_),
  217707. outputId (outputId_),
  217708. isOpen_ (false),
  217709. isStarted (false),
  217710. internal (0)
  217711. {
  217712. internal = new ALSAThread (inputId, outputId);
  217713. }
  217714. ~ALSAAudioIODevice()
  217715. {
  217716. delete internal;
  217717. }
  217718. const StringArray getOutputChannelNames()
  217719. {
  217720. return internal->channelNamesOut;
  217721. }
  217722. const StringArray getInputChannelNames()
  217723. {
  217724. return internal->channelNamesIn;
  217725. }
  217726. int getNumSampleRates()
  217727. {
  217728. return internal->sampleRates.size();
  217729. }
  217730. double getSampleRate (int index)
  217731. {
  217732. return internal->sampleRates [index];
  217733. }
  217734. int getNumBufferSizesAvailable()
  217735. {
  217736. return 50;
  217737. }
  217738. int getBufferSizeSamples (int index)
  217739. {
  217740. int n = 16;
  217741. for (int i = 0; i < index; ++i)
  217742. n += n < 64 ? 16
  217743. : (n < 512 ? 32
  217744. : (n < 1024 ? 64
  217745. : (n < 2048 ? 128 : 256)));
  217746. return n;
  217747. }
  217748. int getDefaultBufferSize()
  217749. {
  217750. return 512;
  217751. }
  217752. const String open (const BitArray& inputChannels,
  217753. const BitArray& outputChannels,
  217754. double sampleRate,
  217755. int bufferSizeSamples)
  217756. {
  217757. close();
  217758. if (bufferSizeSamples <= 0)
  217759. bufferSizeSamples = getDefaultBufferSize();
  217760. if (sampleRate <= 0)
  217761. {
  217762. for (int i = 0; i < getNumSampleRates(); ++i)
  217763. {
  217764. if (getSampleRate (i) >= 44100)
  217765. {
  217766. sampleRate = getSampleRate (i);
  217767. break;
  217768. }
  217769. }
  217770. }
  217771. internal->open (inputChannels, outputChannels,
  217772. sampleRate, bufferSizeSamples);
  217773. isOpen_ = internal->error.isEmpty();
  217774. return internal->error;
  217775. }
  217776. void close()
  217777. {
  217778. stop();
  217779. internal->close();
  217780. isOpen_ = false;
  217781. }
  217782. bool isOpen()
  217783. {
  217784. return isOpen_;
  217785. }
  217786. int getCurrentBufferSizeSamples()
  217787. {
  217788. return internal->bufferSize;
  217789. }
  217790. double getCurrentSampleRate()
  217791. {
  217792. return internal->sampleRate;
  217793. }
  217794. int getCurrentBitDepth()
  217795. {
  217796. return internal->getBitDepth();
  217797. }
  217798. const BitArray getActiveOutputChannels() const
  217799. {
  217800. return internal->currentOutputChans;
  217801. }
  217802. const BitArray getActiveInputChannels() const
  217803. {
  217804. return internal->currentInputChans;
  217805. }
  217806. int getOutputLatencyInSamples()
  217807. {
  217808. return 0;
  217809. }
  217810. int getInputLatencyInSamples()
  217811. {
  217812. return 0;
  217813. }
  217814. void start (AudioIODeviceCallback* callback)
  217815. {
  217816. if (! isOpen_)
  217817. callback = 0;
  217818. internal->setCallback (callback);
  217819. if (callback != 0)
  217820. callback->audioDeviceAboutToStart (this);
  217821. isStarted = (callback != 0);
  217822. }
  217823. void stop()
  217824. {
  217825. AudioIODeviceCallback* const oldCallback = internal->callback;
  217826. start (0);
  217827. if (oldCallback != 0)
  217828. oldCallback->audioDeviceStopped();
  217829. }
  217830. bool isPlaying()
  217831. {
  217832. return isStarted && internal->error.isEmpty();
  217833. }
  217834. const String getLastError()
  217835. {
  217836. return internal->error;
  217837. }
  217838. String inputId, outputId;
  217839. private:
  217840. bool isOpen_, isStarted;
  217841. ALSAThread* internal;
  217842. };
  217843. class ALSAAudioIODeviceType : public AudioIODeviceType
  217844. {
  217845. public:
  217846. ALSAAudioIODeviceType()
  217847. : AudioIODeviceType (T("ALSA")),
  217848. hasScanned (false)
  217849. {
  217850. }
  217851. ~ALSAAudioIODeviceType()
  217852. {
  217853. }
  217854. void scanForDevices()
  217855. {
  217856. if (hasScanned)
  217857. return;
  217858. hasScanned = true;
  217859. inputNames.clear();
  217860. inputIds.clear();
  217861. outputNames.clear();
  217862. outputIds.clear();
  217863. snd_ctl_t* handle;
  217864. snd_ctl_card_info_t* info;
  217865. snd_ctl_card_info_alloca (&info);
  217866. int cardNum = -1;
  217867. while (outputIds.size() + inputIds.size() <= 32)
  217868. {
  217869. snd_card_next (&cardNum);
  217870. if (cardNum < 0)
  217871. break;
  217872. if (snd_ctl_open (&handle, T("hw:") + String (cardNum), SND_CTL_NONBLOCK) >= 0)
  217873. {
  217874. if (snd_ctl_card_info (handle, info) >= 0)
  217875. {
  217876. String cardId (snd_ctl_card_info_get_id (info));
  217877. if (cardId.removeCharacters (T("0123456789")).isEmpty())
  217878. cardId = String (cardNum);
  217879. int device = -1;
  217880. for (;;)
  217881. {
  217882. if (snd_ctl_pcm_next_device (handle, &device) < 0 || device < 0)
  217883. break;
  217884. String id, name;
  217885. id << "hw:" << cardId << ',' << device;
  217886. bool isInput, isOutput;
  217887. if (testDevice (id, isInput, isOutput))
  217888. {
  217889. name << snd_ctl_card_info_get_name (info);
  217890. if (name.isEmpty())
  217891. name = id;
  217892. if (isInput)
  217893. {
  217894. inputNames.add (name);
  217895. inputIds.add (id);
  217896. }
  217897. if (isOutput)
  217898. {
  217899. outputNames.add (name);
  217900. outputIds.add (id);
  217901. }
  217902. }
  217903. }
  217904. }
  217905. snd_ctl_close (handle);
  217906. }
  217907. }
  217908. inputNames.appendNumbersToDuplicates (false, true);
  217909. outputNames.appendNumbersToDuplicates (false, true);
  217910. }
  217911. const StringArray getDeviceNames (const bool wantInputNames) const
  217912. {
  217913. jassert (hasScanned); // need to call scanForDevices() before doing this
  217914. return wantInputNames ? inputNames : outputNames;
  217915. }
  217916. int getDefaultDeviceIndex (const bool forInput) const
  217917. {
  217918. jassert (hasScanned); // need to call scanForDevices() before doing this
  217919. return 0;
  217920. }
  217921. bool hasSeparateInputsAndOutputs() const { return true; }
  217922. int getIndexOfDevice (AudioIODevice* device, const bool asInput) const
  217923. {
  217924. jassert (hasScanned); // need to call scanForDevices() before doing this
  217925. ALSAAudioIODevice* const d = dynamic_cast <ALSAAudioIODevice*> (device);
  217926. if (d == 0)
  217927. return -1;
  217928. return asInput ? inputIds.indexOf (d->inputId)
  217929. : outputIds.indexOf (d->outputId);
  217930. }
  217931. AudioIODevice* createDevice (const String& outputDeviceName,
  217932. const String& inputDeviceName)
  217933. {
  217934. jassert (hasScanned); // need to call scanForDevices() before doing this
  217935. const int inputIndex = inputNames.indexOf (inputDeviceName);
  217936. const int outputIndex = outputNames.indexOf (outputDeviceName);
  217937. String deviceName (outputDeviceName);
  217938. if (deviceName.isEmpty())
  217939. deviceName = inputDeviceName;
  217940. if (index >= 0)
  217941. return new ALSAAudioIODevice (deviceName,
  217942. inputIds [inputIndex],
  217943. outputIds [outputIndex]);
  217944. return 0;
  217945. }
  217946. juce_UseDebuggingNewOperator
  217947. private:
  217948. StringArray inputNames, outputNames, inputIds, outputIds;
  217949. bool hasScanned;
  217950. static bool testDevice (const String& id, bool& isInput, bool& isOutput)
  217951. {
  217952. unsigned int minChansOut = 0, maxChansOut = 0;
  217953. unsigned int minChansIn = 0, maxChansIn = 0;
  217954. Array <int> rates;
  217955. getDeviceProperties (id, minChansOut, maxChansOut, minChansIn, maxChansIn, rates);
  217956. DBG (T("ALSA device: ") + id
  217957. + T(" outs=") + String ((int) minChansOut) + T("-") + String ((int) maxChansOut)
  217958. + T(" ins=") + String ((int) minChansIn) + T("-") + String ((int) maxChansIn)
  217959. + T(" rates=") + String (rates.size()));
  217960. isInput = maxChansIn > 0;
  217961. isOutput = maxChansOut > 0;
  217962. return (isInput || isOutput) && rates.size() > 0;
  217963. }
  217964. ALSAAudioIODeviceType (const ALSAAudioIODeviceType&);
  217965. const ALSAAudioIODeviceType& operator= (const ALSAAudioIODeviceType&);
  217966. };
  217967. AudioIODeviceType* juce_createAudioIODeviceType_ALSA()
  217968. {
  217969. return new ALSAAudioIODeviceType();
  217970. }
  217971. #endif
  217972. /********* End of inlined file: juce_linux_Audio.cpp *********/
  217973. /********* Start of inlined file: juce_linux_Midi.cpp *********/
  217974. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  217975. // compiled on its own).
  217976. #ifdef JUCE_INCLUDED_FILE
  217977. #if JUCE_ALSA
  217978. static snd_seq_t* iterateDevices (const bool forInput,
  217979. StringArray& deviceNamesFound,
  217980. const int deviceIndexToOpen)
  217981. {
  217982. snd_seq_t* returnedHandle = 0;
  217983. snd_seq_t* seqHandle;
  217984. if (snd_seq_open (&seqHandle, "default", forInput ? SND_SEQ_OPEN_INPUT
  217985. : SND_SEQ_OPEN_OUTPUT, 0) == 0)
  217986. {
  217987. snd_seq_system_info_t* systemInfo;
  217988. snd_seq_client_info_t* clientInfo;
  217989. if (snd_seq_system_info_malloc (&systemInfo) == 0)
  217990. {
  217991. if (snd_seq_system_info (seqHandle, systemInfo) == 0
  217992. && snd_seq_client_info_malloc (&clientInfo) == 0)
  217993. {
  217994. int numClients = snd_seq_system_info_get_cur_clients (systemInfo);
  217995. while (--numClients >= 0 && returnedHandle == 0)
  217996. {
  217997. if (snd_seq_query_next_client (seqHandle, clientInfo) == 0)
  217998. {
  217999. snd_seq_port_info_t* portInfo;
  218000. if (snd_seq_port_info_malloc (&portInfo) == 0)
  218001. {
  218002. int numPorts = snd_seq_client_info_get_num_ports (clientInfo);
  218003. const int client = snd_seq_client_info_get_client (clientInfo);
  218004. snd_seq_port_info_set_client (portInfo, client);
  218005. snd_seq_port_info_set_port (portInfo, -1);
  218006. while (--numPorts >= 0)
  218007. {
  218008. if (snd_seq_query_next_port (seqHandle, portInfo) == 0
  218009. && (snd_seq_port_info_get_capability (portInfo)
  218010. & (forInput ? SND_SEQ_PORT_CAP_READ
  218011. : SND_SEQ_PORT_CAP_WRITE)) != 0)
  218012. {
  218013. deviceNamesFound.add (snd_seq_client_info_get_name (clientInfo));
  218014. if (deviceNamesFound.size() == deviceIndexToOpen + 1)
  218015. {
  218016. const int sourcePort = snd_seq_port_info_get_port (portInfo);
  218017. const int sourceClient = snd_seq_client_info_get_client (clientInfo);
  218018. if (sourcePort != -1)
  218019. {
  218020. snd_seq_set_client_name (seqHandle,
  218021. forInput ? "Juce Midi Input"
  218022. : "Juce Midi Output");
  218023. const int portId
  218024. = snd_seq_create_simple_port (seqHandle,
  218025. forInput ? "Juce Midi In Port"
  218026. : "Juce Midi Out Port",
  218027. forInput ? (SND_SEQ_PORT_CAP_WRITE | SND_SEQ_PORT_CAP_SUBS_WRITE)
  218028. : (SND_SEQ_PORT_CAP_READ | SND_SEQ_PORT_CAP_SUBS_READ),
  218029. SND_SEQ_PORT_TYPE_MIDI_GENERIC);
  218030. snd_seq_connect_from (seqHandle, portId, sourceClient, sourcePort);
  218031. returnedHandle = seqHandle;
  218032. }
  218033. }
  218034. }
  218035. }
  218036. snd_seq_port_info_free (portInfo);
  218037. }
  218038. }
  218039. }
  218040. snd_seq_client_info_free (clientInfo);
  218041. }
  218042. snd_seq_system_info_free (systemInfo);
  218043. }
  218044. if (returnedHandle == 0)
  218045. snd_seq_close (seqHandle);
  218046. }
  218047. deviceNamesFound.appendNumbersToDuplicates (true, true);
  218048. return returnedHandle;
  218049. }
  218050. static snd_seq_t* createDevice (const bool forInput,
  218051. const String& deviceNameToOpen)
  218052. {
  218053. snd_seq_t* seqHandle = 0;
  218054. if (snd_seq_open (&seqHandle, "default", forInput ? SND_SEQ_OPEN_INPUT
  218055. : SND_SEQ_OPEN_OUTPUT, 0) == 0)
  218056. {
  218057. snd_seq_set_client_name (seqHandle,
  218058. (const char*) (forInput ? (deviceNameToOpen + T(" Input"))
  218059. : (deviceNameToOpen + T(" Output"))));
  218060. const int portId
  218061. = snd_seq_create_simple_port (seqHandle,
  218062. forInput ? "in"
  218063. : "out",
  218064. forInput ? (SND_SEQ_PORT_CAP_WRITE | SND_SEQ_PORT_CAP_SUBS_WRITE)
  218065. : (SND_SEQ_PORT_CAP_READ | SND_SEQ_PORT_CAP_SUBS_READ),
  218066. forInput ? SND_SEQ_PORT_TYPE_APPLICATION
  218067. : SND_SEQ_PORT_TYPE_MIDI_GENERIC);
  218068. if (portId < 0)
  218069. {
  218070. snd_seq_close (seqHandle);
  218071. seqHandle = 0;
  218072. }
  218073. }
  218074. return seqHandle;
  218075. }
  218076. class MidiOutputDevice
  218077. {
  218078. public:
  218079. MidiOutputDevice (MidiOutput* const midiOutput_,
  218080. snd_seq_t* const seqHandle_)
  218081. :
  218082. midiOutput (midiOutput_),
  218083. seqHandle (seqHandle_),
  218084. maxEventSize (16 * 1024)
  218085. {
  218086. jassert (seqHandle != 0 && midiOutput != 0);
  218087. snd_midi_event_new (maxEventSize, &midiParser);
  218088. }
  218089. ~MidiOutputDevice()
  218090. {
  218091. snd_midi_event_free (midiParser);
  218092. snd_seq_close (seqHandle);
  218093. }
  218094. void sendMessageNow (const MidiMessage& message)
  218095. {
  218096. if (message.getRawDataSize() > maxEventSize)
  218097. {
  218098. maxEventSize = message.getRawDataSize();
  218099. snd_midi_event_free (midiParser);
  218100. snd_midi_event_new (maxEventSize, &midiParser);
  218101. }
  218102. snd_seq_event_t event;
  218103. snd_seq_ev_clear (&event);
  218104. snd_midi_event_encode (midiParser,
  218105. message.getRawData(),
  218106. message.getRawDataSize(),
  218107. &event);
  218108. snd_midi_event_reset_encode (midiParser);
  218109. snd_seq_ev_set_source (&event, 0);
  218110. snd_seq_ev_set_subs (&event);
  218111. snd_seq_ev_set_direct (&event);
  218112. snd_seq_event_output (seqHandle, &event);
  218113. snd_seq_drain_output (seqHandle);
  218114. }
  218115. juce_UseDebuggingNewOperator
  218116. private:
  218117. MidiOutput* const midiOutput;
  218118. snd_seq_t* const seqHandle;
  218119. snd_midi_event_t* midiParser;
  218120. int maxEventSize;
  218121. };
  218122. const StringArray MidiOutput::getDevices()
  218123. {
  218124. StringArray devices;
  218125. iterateDevices (false, devices, -1);
  218126. return devices;
  218127. }
  218128. int MidiOutput::getDefaultDeviceIndex()
  218129. {
  218130. return 0;
  218131. }
  218132. MidiOutput* MidiOutput::openDevice (int deviceIndex)
  218133. {
  218134. MidiOutput* newDevice = 0;
  218135. StringArray devices;
  218136. snd_seq_t* const handle = iterateDevices (false, devices, deviceIndex);
  218137. if (handle != 0)
  218138. {
  218139. newDevice = new MidiOutput();
  218140. newDevice->internal = new MidiOutputDevice (newDevice, handle);
  218141. }
  218142. return newDevice;
  218143. }
  218144. MidiOutput* MidiOutput::createNewDevice (const String& deviceName)
  218145. {
  218146. MidiOutput* newDevice = 0;
  218147. snd_seq_t* const handle = createDevice (false, deviceName);
  218148. if (handle != 0)
  218149. {
  218150. newDevice = new MidiOutput();
  218151. newDevice->internal = new MidiOutputDevice (newDevice, handle);
  218152. }
  218153. return newDevice;
  218154. }
  218155. MidiOutput::~MidiOutput()
  218156. {
  218157. MidiOutputDevice* const device = (MidiOutputDevice*) internal;
  218158. delete device;
  218159. }
  218160. void MidiOutput::reset()
  218161. {
  218162. }
  218163. bool MidiOutput::getVolume (float& leftVol, float& rightVol)
  218164. {
  218165. return false;
  218166. }
  218167. void MidiOutput::setVolume (float leftVol, float rightVol)
  218168. {
  218169. }
  218170. void MidiOutput::sendMessageNow (const MidiMessage& message)
  218171. {
  218172. ((MidiOutputDevice*) internal)->sendMessageNow (message);
  218173. }
  218174. class MidiInputThread : public Thread
  218175. {
  218176. public:
  218177. MidiInputThread (MidiInput* const midiInput_,
  218178. snd_seq_t* const seqHandle_,
  218179. MidiInputCallback* const callback_)
  218180. : Thread (T("Juce MIDI Input")),
  218181. midiInput (midiInput_),
  218182. seqHandle (seqHandle_),
  218183. callback (callback_)
  218184. {
  218185. jassert (seqHandle != 0 && callback != 0 && midiInput != 0);
  218186. }
  218187. ~MidiInputThread()
  218188. {
  218189. snd_seq_close (seqHandle);
  218190. }
  218191. void run()
  218192. {
  218193. const int maxEventSize = 16 * 1024;
  218194. snd_midi_event_t* midiParser;
  218195. if (snd_midi_event_new (maxEventSize, &midiParser) >= 0)
  218196. {
  218197. uint8* const buffer = (uint8*) juce_malloc (maxEventSize);
  218198. const int numPfds = snd_seq_poll_descriptors_count (seqHandle, POLLIN);
  218199. struct pollfd* const pfd = (struct pollfd*) alloca (numPfds * sizeof (struct pollfd));
  218200. snd_seq_poll_descriptors (seqHandle, pfd, numPfds, POLLIN);
  218201. while (! threadShouldExit())
  218202. {
  218203. if (poll (pfd, numPfds, 500) > 0)
  218204. {
  218205. snd_seq_event_t* inputEvent = 0;
  218206. snd_seq_nonblock (seqHandle, 1);
  218207. do
  218208. {
  218209. if (snd_seq_event_input (seqHandle, &inputEvent) >= 0)
  218210. {
  218211. // xxx what about SYSEXes that are too big for the buffer?
  218212. const int numBytes = snd_midi_event_decode (midiParser, buffer, maxEventSize, inputEvent);
  218213. snd_midi_event_reset_decode (midiParser);
  218214. if (numBytes > 0)
  218215. {
  218216. const MidiMessage message ((const uint8*) buffer,
  218217. numBytes,
  218218. Time::getMillisecondCounter() * 0.001);
  218219. callback->handleIncomingMidiMessage (midiInput, message);
  218220. }
  218221. snd_seq_free_event (inputEvent);
  218222. }
  218223. }
  218224. while (snd_seq_event_input_pending (seqHandle, 0) > 0);
  218225. snd_seq_free_event (inputEvent);
  218226. }
  218227. }
  218228. snd_midi_event_free (midiParser);
  218229. juce_free (buffer);
  218230. }
  218231. };
  218232. juce_UseDebuggingNewOperator
  218233. private:
  218234. MidiInput* const midiInput;
  218235. snd_seq_t* const seqHandle;
  218236. MidiInputCallback* const callback;
  218237. };
  218238. MidiInput::MidiInput (const String& name_)
  218239. : name (name_),
  218240. internal (0)
  218241. {
  218242. }
  218243. MidiInput::~MidiInput()
  218244. {
  218245. stop();
  218246. MidiInputThread* const thread = (MidiInputThread*) internal;
  218247. delete thread;
  218248. }
  218249. void MidiInput::start()
  218250. {
  218251. ((MidiInputThread*) internal)->startThread();
  218252. }
  218253. void MidiInput::stop()
  218254. {
  218255. ((MidiInputThread*) internal)->stopThread (3000);
  218256. }
  218257. int MidiInput::getDefaultDeviceIndex()
  218258. {
  218259. return 0;
  218260. }
  218261. const StringArray MidiInput::getDevices()
  218262. {
  218263. StringArray devices;
  218264. iterateDevices (true, devices, -1);
  218265. return devices;
  218266. }
  218267. MidiInput* MidiInput::openDevice (int deviceIndex, MidiInputCallback* callback)
  218268. {
  218269. MidiInput* newDevice = 0;
  218270. StringArray devices;
  218271. snd_seq_t* const handle = iterateDevices (true, devices, deviceIndex);
  218272. if (handle != 0)
  218273. {
  218274. newDevice = new MidiInput (devices [deviceIndex]);
  218275. newDevice->internal = new MidiInputThread (newDevice, handle, callback);
  218276. }
  218277. return newDevice;
  218278. }
  218279. MidiInput* MidiInput::createNewDevice (const String& deviceName, MidiInputCallback* callback)
  218280. {
  218281. MidiInput* newDevice = 0;
  218282. snd_seq_t* const handle = createDevice (true, deviceName);
  218283. if (handle != 0)
  218284. {
  218285. newDevice = new MidiInput (deviceName);
  218286. newDevice->internal = new MidiInputThread (newDevice, handle, callback);
  218287. }
  218288. return newDevice;
  218289. }
  218290. #else
  218291. // (These are just stub functions if ALSA is unavailable...)
  218292. const StringArray MidiOutput::getDevices() { return StringArray(); }
  218293. int MidiOutput::getDefaultDeviceIndex() { return 0; }
  218294. MidiOutput* MidiOutput::openDevice (int) { return 0; }
  218295. MidiOutput* MidiOutput::createNewDevice (const String&) { return 0; }
  218296. MidiOutput::~MidiOutput() {}
  218297. void MidiOutput::reset() {}
  218298. bool MidiOutput::getVolume (float&, float&) { return false; }
  218299. void MidiOutput::setVolume (float, float) {}
  218300. void MidiOutput::sendMessageNow (const MidiMessage&) {}
  218301. MidiInput::MidiInput (const String& name_) : name (name_), internal (0) {}
  218302. MidiInput::~MidiInput() {}
  218303. void MidiInput::start() {}
  218304. void MidiInput::stop() {}
  218305. int MidiInput::getDefaultDeviceIndex() { return 0; }
  218306. const StringArray MidiInput::getDevices() { return StringArray(); }
  218307. MidiInput* MidiInput::openDevice (int, MidiInputCallback*) { return 0; }
  218308. MidiInput* MidiInput::createNewDevice (const String&, MidiInputCallback*) { return 0; }
  218309. #endif
  218310. #endif
  218311. /********* End of inlined file: juce_linux_Midi.cpp *********/
  218312. /********* Start of inlined file: juce_linux_AudioCDReader.cpp *********/
  218313. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  218314. // compiled on its own).
  218315. #ifdef JUCE_INCLUDED_FILE
  218316. AudioCDReader::AudioCDReader()
  218317. : AudioFormatReader (0, T("CD Audio"))
  218318. {
  218319. }
  218320. const StringArray AudioCDReader::getAvailableCDNames()
  218321. {
  218322. StringArray names;
  218323. return names;
  218324. }
  218325. AudioCDReader* AudioCDReader::createReaderForCD (const int index)
  218326. {
  218327. return 0;
  218328. }
  218329. AudioCDReader::~AudioCDReader()
  218330. {
  218331. }
  218332. void AudioCDReader::refreshTrackLengths()
  218333. {
  218334. }
  218335. bool AudioCDReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  218336. int64 startSampleInFile, int numSamples)
  218337. {
  218338. return false;
  218339. }
  218340. bool AudioCDReader::isCDStillPresent() const
  218341. {
  218342. return false;
  218343. }
  218344. int AudioCDReader::getNumTracks() const
  218345. {
  218346. return 0;
  218347. }
  218348. int AudioCDReader::getPositionOfTrackStart (int trackNum) const
  218349. {
  218350. return 0;
  218351. }
  218352. bool AudioCDReader::isTrackAudio (int trackNum) const
  218353. {
  218354. return false;
  218355. }
  218356. void AudioCDReader::enableIndexScanning (bool b)
  218357. {
  218358. }
  218359. int AudioCDReader::getLastIndex() const
  218360. {
  218361. return 0;
  218362. }
  218363. const Array<int> AudioCDReader::findIndexesInTrack (const int trackNumber)
  218364. {
  218365. return Array<int>();
  218366. }
  218367. int AudioCDReader::getCDDBId()
  218368. {
  218369. return 0;
  218370. }
  218371. #endif
  218372. /********* End of inlined file: juce_linux_AudioCDReader.cpp *********/
  218373. /********* Start of inlined file: juce_linux_FileChooser.cpp *********/
  218374. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  218375. // compiled on its own).
  218376. #ifdef JUCE_INCLUDED_FILE
  218377. void FileChooser::showPlatformDialog (OwnedArray<File>& results,
  218378. const String& title,
  218379. const File& file,
  218380. const String& filters,
  218381. bool isDirectory,
  218382. bool isSave,
  218383. bool warnAboutOverwritingExistingFiles,
  218384. bool selectMultipleFiles,
  218385. FilePreviewComponent* previewComponent)
  218386. {
  218387. //xxx ain't got one!
  218388. jassertfalse
  218389. }
  218390. #endif
  218391. /********* End of inlined file: juce_linux_FileChooser.cpp *********/
  218392. /********* Start of inlined file: juce_linux_WebBrowserComponent.cpp *********/
  218393. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  218394. // compiled on its own).
  218395. #ifdef JUCE_INCLUDED_FILE
  218396. #if JUCE_WEB_BROWSER
  218397. /*
  218398. Sorry.. This class isn't implemented on Linux!
  218399. */
  218400. WebBrowserComponent::WebBrowserComponent()
  218401. : browser (0),
  218402. blankPageShown (false)
  218403. {
  218404. setOpaque (true);
  218405. }
  218406. WebBrowserComponent::~WebBrowserComponent()
  218407. {
  218408. }
  218409. void WebBrowserComponent::goToURL (const String& url,
  218410. const StringArray* headers,
  218411. const MemoryBlock* postData)
  218412. {
  218413. lastURL = url;
  218414. lastHeaders.clear();
  218415. if (headers != 0)
  218416. lastHeaders = *headers;
  218417. lastPostData.setSize (0);
  218418. if (postData != 0)
  218419. lastPostData = *postData;
  218420. blankPageShown = false;
  218421. }
  218422. void WebBrowserComponent::stop()
  218423. {
  218424. }
  218425. void WebBrowserComponent::goBack()
  218426. {
  218427. lastURL = String::empty;
  218428. blankPageShown = false;
  218429. }
  218430. void WebBrowserComponent::goForward()
  218431. {
  218432. lastURL = String::empty;
  218433. }
  218434. void WebBrowserComponent::refresh()
  218435. {
  218436. }
  218437. void WebBrowserComponent::paint (Graphics& g)
  218438. {
  218439. g.fillAll (Colours::white);
  218440. }
  218441. void WebBrowserComponent::checkWindowAssociation()
  218442. {
  218443. }
  218444. void WebBrowserComponent::reloadLastURL()
  218445. {
  218446. if (lastURL.isNotEmpty())
  218447. {
  218448. goToURL (lastURL, &lastHeaders, &lastPostData);
  218449. lastURL = String::empty;
  218450. }
  218451. }
  218452. void WebBrowserComponent::parentHierarchyChanged()
  218453. {
  218454. checkWindowAssociation();
  218455. }
  218456. void WebBrowserComponent::resized()
  218457. {
  218458. }
  218459. void WebBrowserComponent::visibilityChanged()
  218460. {
  218461. checkWindowAssociation();
  218462. }
  218463. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  218464. {
  218465. return true;
  218466. }
  218467. #endif
  218468. #endif
  218469. /********* End of inlined file: juce_linux_WebBrowserComponent.cpp *********/
  218470. #endif
  218471. END_JUCE_NAMESPACE
  218472. /********* End of inlined file: juce_linux_NativeCode.cpp *********/
  218473. #endif
  218474. #if JUCE_MAC
  218475. /********* Start of inlined file: juce_mac_NativeCode.mm *********/
  218476. /*
  218477. This file wraps together all the mac-specific code, so that
  218478. we can include all the native headers just once, and compile all our
  218479. platform-specific stuff in one big lump, keeping it out of the way of
  218480. the rest of the codebase.
  218481. */
  218482. BEGIN_JUCE_NAMESPACE
  218483. #undef Point
  218484. /** This suffix is used for naming all Obj-C classes that are used inside juce.
  218485. Because of the flat naming structure used by Obj-C, you can get horrible situations where
  218486. two DLLs are loaded into a host, each of which uses classes with the same names, and these get
  218487. cross-linked so that when you make a call to a class that you thought was private, it ends up
  218488. actually calling into a similarly named class in the other module's address space.
  218489. By changing this macro to a unique value, you ensure that all the obj-C classes in your app
  218490. have unique names, and should avoid this problem.
  218491. If you're using the amalgamated version, you can just set this macro to something unique before
  218492. you include juce_amalgamated.cpp.
  218493. */
  218494. #ifndef JUCE_ObjCExtraSuffix
  218495. #define JUCE_ObjCExtraSuffix 3
  218496. #endif
  218497. #define appendMacro1(a, b, c, d) a ## _ ## b ## _ ## c ## _ ## d
  218498. #define appendMacro2(a, b, c, d) appendMacro1(a, b, c, d)
  218499. #define MakeObjCClassName(rootName) appendMacro2 (rootName, JUCE_MAJOR_VERSION, JUCE_MINOR_VERSION, JUCE_ObjCExtraSuffix)
  218500. #define JUCE_INCLUDED_FILE 1
  218501. // Now include the actual code files..
  218502. /********* Start of inlined file: juce_mac_Strings.mm *********/
  218503. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  218504. // compiled on its own).
  218505. #ifdef JUCE_INCLUDED_FILE
  218506. static const String nsStringToJuce (NSString* s)
  218507. {
  218508. return String::fromUTF8 ((uint8*) [s UTF8String]);
  218509. }
  218510. static NSString* juceStringToNS (const String& s)
  218511. {
  218512. return [NSString stringWithUTF8String: (const char*) s.toUTF8()];
  218513. }
  218514. static const String convertUTF16ToString (const UniChar* utf16)
  218515. {
  218516. String s;
  218517. while (*utf16 != 0)
  218518. s += (juce_wchar) *utf16++;
  218519. return s;
  218520. }
  218521. const String PlatformUtilities::cfStringToJuceString (CFStringRef cfString)
  218522. {
  218523. String result;
  218524. if (cfString != 0)
  218525. {
  218526. #if JUCE_STRINGS_ARE_UNICODE
  218527. CFRange range = { 0, CFStringGetLength (cfString) };
  218528. UniChar* const u = (UniChar*) juce_malloc (sizeof (UniChar) * (range.length + 1));
  218529. CFStringGetCharacters (cfString, range, u);
  218530. u[range.length] = 0;
  218531. result = convertUTF16ToString (u);
  218532. juce_free (u);
  218533. #else
  218534. const int len = CFStringGetLength (cfString);
  218535. char* buffer = (char*) juce_malloc (len + 1);
  218536. CFStringGetCString (cfString, buffer, len + 1, CFStringGetSystemEncoding());
  218537. result = buffer;
  218538. juce_free (buffer);
  218539. #endif
  218540. }
  218541. return result;
  218542. }
  218543. CFStringRef PlatformUtilities::juceStringToCFString (const String& s)
  218544. {
  218545. #if JUCE_STRINGS_ARE_UNICODE
  218546. const int len = s.length();
  218547. const juce_wchar* t = (const juce_wchar*) s;
  218548. UniChar* temp = (UniChar*) juce_malloc (sizeof (UniChar) * len + 4);
  218549. for (int i = 0; i <= len; ++i)
  218550. temp[i] = t[i];
  218551. CFStringRef result = CFStringCreateWithCharacters (kCFAllocatorDefault, temp, len);
  218552. juce_free (temp);
  218553. return result;
  218554. #else
  218555. return CFStringCreateWithCString (kCFAllocatorDefault,
  218556. (const char*) s,
  218557. CFStringGetSystemEncoding());
  218558. #endif
  218559. }
  218560. const String PlatformUtilities::convertToPrecomposedUnicode (const String& s)
  218561. {
  218562. UnicodeMapping map;
  218563. map.unicodeEncoding = CreateTextEncoding (kTextEncodingUnicodeDefault,
  218564. kUnicodeNoSubset,
  218565. kTextEncodingDefaultFormat);
  218566. map.otherEncoding = CreateTextEncoding (kTextEncodingUnicodeDefault,
  218567. kUnicodeCanonicalCompVariant,
  218568. kTextEncodingDefaultFormat);
  218569. map.mappingVersion = kUnicodeUseLatestMapping;
  218570. UnicodeToTextInfo conversionInfo = 0;
  218571. String result;
  218572. if (CreateUnicodeToTextInfo (&map, &conversionInfo) == noErr)
  218573. {
  218574. const int len = s.length();
  218575. UniChar* const tempIn = (UniChar*) juce_calloc (sizeof (UniChar) * len + 4);
  218576. UniChar* const tempOut = (UniChar*) juce_calloc (sizeof (UniChar) * len + 4);
  218577. for (int i = 0; i <= len; ++i)
  218578. tempIn[i] = s[i];
  218579. ByteCount bytesRead = 0;
  218580. ByteCount outputBufferSize = 0;
  218581. if (ConvertFromUnicodeToText (conversionInfo,
  218582. len * sizeof (UniChar), tempIn,
  218583. kUnicodeDefaultDirectionMask,
  218584. 0, 0, 0, 0,
  218585. len * sizeof (UniChar), &bytesRead,
  218586. &outputBufferSize, tempOut) == noErr)
  218587. {
  218588. result.preallocateStorage (bytesRead / sizeof (UniChar) + 2);
  218589. tchar* t = const_cast <tchar*> ((const tchar*) result);
  218590. unsigned int i;
  218591. for (i = 0; i < bytesRead / sizeof (UniChar); ++i)
  218592. t[i] = (tchar) tempOut[i];
  218593. t[i] = 0;
  218594. }
  218595. juce_free (tempIn);
  218596. juce_free (tempOut);
  218597. DisposeUnicodeToTextInfo (&conversionInfo);
  218598. }
  218599. return result;
  218600. }
  218601. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  218602. void SystemClipboard::copyTextToClipboard (const String& text) throw()
  218603. {
  218604. [[NSPasteboard generalPasteboard] declareTypes: [NSArray arrayWithObject: NSStringPboardType]
  218605. owner: nil];
  218606. [[NSPasteboard generalPasteboard] setString: juceStringToNS (text)
  218607. forType: NSStringPboardType];
  218608. }
  218609. const String SystemClipboard::getTextFromClipboard() throw()
  218610. {
  218611. NSString* text = [[NSPasteboard generalPasteboard] stringForType: NSStringPboardType];
  218612. return text == 0 ? String::empty
  218613. : nsStringToJuce (text);
  218614. }
  218615. #endif
  218616. #endif
  218617. /********* End of inlined file: juce_mac_Strings.mm *********/
  218618. /********* Start of inlined file: juce_mac_SystemStats.mm *********/
  218619. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  218620. // compiled on its own).
  218621. #ifdef JUCE_INCLUDED_FILE
  218622. static int64 highResTimerFrequency;
  218623. #if JUCE_INTEL
  218624. static void juce_getCpuVendor (char* const v) throw()
  218625. {
  218626. int vendor[4];
  218627. zerostruct (vendor);
  218628. int dummy = 0;
  218629. asm ("mov %%ebx, %%esi \n\t"
  218630. "cpuid \n\t"
  218631. "xchg %%esi, %%ebx"
  218632. : "=a" (dummy), "=S" (vendor[0]), "=c" (vendor[2]), "=d" (vendor[1]) : "a" (0));
  218633. memcpy (v, vendor, 16);
  218634. }
  218635. static unsigned int getCPUIDWord (unsigned int& familyModel, unsigned int& extFeatures) throw()
  218636. {
  218637. unsigned int cpu = 0;
  218638. unsigned int ext = 0;
  218639. unsigned int family = 0;
  218640. unsigned int dummy = 0;
  218641. asm ("mov %%ebx, %%esi \n\t"
  218642. "cpuid \n\t"
  218643. "xchg %%esi, %%ebx"
  218644. : "=a" (family), "=S" (ext), "=c" (dummy), "=d" (cpu) : "a" (1));
  218645. familyModel = family;
  218646. extFeatures = ext;
  218647. return cpu;
  218648. }
  218649. struct CPUFlags
  218650. {
  218651. bool hasMMX : 1;
  218652. bool hasSSE : 1;
  218653. bool hasSSE2 : 1;
  218654. bool has3DNow : 1;
  218655. };
  218656. static CPUFlags cpuFlags;
  218657. #endif
  218658. void SystemStats::initialiseStats() throw()
  218659. {
  218660. static bool initialised = false;
  218661. if (! initialised)
  218662. {
  218663. initialised = true;
  218664. // extremely annoying: adding this line stops the apple menu items from working. Of
  218665. // course, not adding it means that carbon windows (e.g. in plugins) won't get
  218666. // any events.
  218667. //NSApplicationLoad();
  218668. [NSApplication sharedApplication];
  218669. #if JUCE_INTEL
  218670. {
  218671. unsigned int familyModel, extFeatures;
  218672. const unsigned int features = getCPUIDWord (familyModel, extFeatures);
  218673. cpuFlags.hasMMX = ((features & (1 << 23)) != 0);
  218674. cpuFlags.hasSSE = ((features & (1 << 25)) != 0);
  218675. cpuFlags.hasSSE2 = ((features & (1 << 26)) != 0);
  218676. cpuFlags.has3DNow = ((extFeatures & (1 << 31)) != 0);
  218677. }
  218678. #endif
  218679. highResTimerFrequency = (int64) AudioGetHostClockFrequency();
  218680. String s (SystemStats::getJUCEVersion());
  218681. rlimit lim;
  218682. getrlimit (RLIMIT_NOFILE, &lim);
  218683. lim.rlim_cur = lim.rlim_max = RLIM_INFINITY;
  218684. setrlimit (RLIMIT_NOFILE, &lim);
  218685. }
  218686. }
  218687. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType() throw()
  218688. {
  218689. return MacOSX;
  218690. }
  218691. const String SystemStats::getOperatingSystemName() throw()
  218692. {
  218693. return T("Mac OS X");
  218694. }
  218695. bool SystemStats::isOperatingSystem64Bit() throw()
  218696. {
  218697. #if JUCE_64BIT
  218698. return true;
  218699. #else
  218700. //xxx not sure how to find this out?..
  218701. return false;
  218702. #endif
  218703. }
  218704. int SystemStats::getMemorySizeInMegabytes() throw()
  218705. {
  218706. uint64 mem = 0;
  218707. size_t memSize = sizeof (mem);
  218708. int mib[] = { CTL_HW, HW_MEMSIZE };
  218709. sysctl (mib, 2, &mem, &memSize, 0, 0);
  218710. return mem / (1024 * 1024);
  218711. }
  218712. bool SystemStats::hasMMX() throw()
  218713. {
  218714. #if JUCE_INTEL
  218715. return cpuFlags.hasMMX;
  218716. #else
  218717. return false;
  218718. #endif
  218719. }
  218720. bool SystemStats::hasSSE() throw()
  218721. {
  218722. #if JUCE_INTEL
  218723. return cpuFlags.hasSSE;
  218724. #else
  218725. return false;
  218726. #endif
  218727. }
  218728. bool SystemStats::hasSSE2() throw()
  218729. {
  218730. #if JUCE_INTEL
  218731. return cpuFlags.hasSSE2;
  218732. #else
  218733. return false;
  218734. #endif
  218735. }
  218736. bool SystemStats::has3DNow() throw()
  218737. {
  218738. #if JUCE_INTEL
  218739. return cpuFlags.has3DNow;
  218740. #else
  218741. return false;
  218742. #endif
  218743. }
  218744. const String SystemStats::getCpuVendor() throw()
  218745. {
  218746. #if JUCE_INTEL
  218747. char v [16];
  218748. juce_getCpuVendor (v);
  218749. return String (v, 16);
  218750. #else
  218751. return String::empty;
  218752. #endif
  218753. }
  218754. int SystemStats::getCpuSpeedInMegaherz() throw()
  218755. {
  218756. uint64 speedHz = 0;
  218757. size_t speedSize = sizeof (speedHz);
  218758. int mib[] = { CTL_HW, HW_CPU_FREQ };
  218759. sysctl (mib, 2, &speedHz, &speedSize, 0, 0);
  218760. #if JUCE_BIG_ENDIAN
  218761. if (speedSize == 4)
  218762. speedHz >>= 32;
  218763. #endif
  218764. return speedHz / 1000000;
  218765. }
  218766. int SystemStats::getNumCpus() throw()
  218767. {
  218768. #if MACOS_10_4_OR_EARLIER
  218769. return MPProcessors();
  218770. #else
  218771. return [[NSProcessInfo processInfo] activeProcessorCount];
  218772. #endif
  218773. }
  218774. static int64 juce_getMicroseconds() throw()
  218775. {
  218776. UnsignedWide t;
  218777. Microseconds (&t);
  218778. return (((int64) t.hi) << 32) | t.lo;
  218779. }
  218780. uint32 juce_millisecondsSinceStartup() throw()
  218781. {
  218782. return (uint32) (juce_getMicroseconds() / 1000);
  218783. }
  218784. double Time::getMillisecondCounterHiRes() throw()
  218785. {
  218786. // xxx might be more accurate to use a scaled AudioGetCurrentHostTime?
  218787. return juce_getMicroseconds() * 0.001;
  218788. }
  218789. int64 Time::getHighResolutionTicks() throw()
  218790. {
  218791. return (int64) AudioGetCurrentHostTime();
  218792. }
  218793. int64 Time::getHighResolutionTicksPerSecond() throw()
  218794. {
  218795. return highResTimerFrequency;
  218796. }
  218797. int64 SystemStats::getClockCycleCounter() throw()
  218798. {
  218799. return (int64) AudioGetCurrentHostTime();
  218800. }
  218801. bool Time::setSystemTimeToThisTime() const throw()
  218802. {
  218803. jassertfalse
  218804. return false;
  218805. }
  218806. int SystemStats::getPageSize() throw()
  218807. {
  218808. return NSPageSize();
  218809. }
  218810. void PlatformUtilities::fpuReset()
  218811. {
  218812. }
  218813. #endif
  218814. /********* End of inlined file: juce_mac_SystemStats.mm *********/
  218815. /********* Start of inlined file: juce_mac_Network.mm *********/
  218816. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  218817. // compiled on its own).
  218818. #if JUCE_INCLUDED_FILE
  218819. static bool getEthernetIterator (io_iterator_t* matchingServices) throw()
  218820. {
  218821. mach_port_t masterPort;
  218822. if (IOMasterPort (MACH_PORT_NULL, &masterPort) == KERN_SUCCESS)
  218823. {
  218824. CFMutableDictionaryRef dict = IOServiceMatching (kIOEthernetInterfaceClass);
  218825. if (dict != 0)
  218826. {
  218827. CFMutableDictionaryRef propDict = CFDictionaryCreateMutable (kCFAllocatorDefault,
  218828. 0,
  218829. &kCFTypeDictionaryKeyCallBacks,
  218830. &kCFTypeDictionaryValueCallBacks);
  218831. if (propDict != 0)
  218832. {
  218833. CFDictionarySetValue (propDict, CFSTR (kIOPrimaryInterface), kCFBooleanTrue);
  218834. CFDictionarySetValue (dict, CFSTR (kIOPropertyMatchKey), propDict);
  218835. CFRelease (propDict);
  218836. }
  218837. }
  218838. return IOServiceGetMatchingServices (masterPort, dict, matchingServices) == KERN_SUCCESS;
  218839. }
  218840. return false;
  218841. }
  218842. int SystemStats::getMACAddresses (int64* addresses, int maxNum, const bool littleEndian) throw()
  218843. {
  218844. int numResults = 0;
  218845. io_iterator_t it;
  218846. if (getEthernetIterator (&it))
  218847. {
  218848. io_object_t i;
  218849. while ((i = IOIteratorNext (it)) != 0)
  218850. {
  218851. io_object_t controller;
  218852. if (IORegistryEntryGetParentEntry (i, kIOServicePlane, &controller) == KERN_SUCCESS)
  218853. {
  218854. CFTypeRef data = IORegistryEntryCreateCFProperty (controller,
  218855. CFSTR (kIOMACAddress),
  218856. kCFAllocatorDefault,
  218857. 0);
  218858. if (data != 0)
  218859. {
  218860. UInt8 addr [kIOEthernetAddressSize];
  218861. zeromem (addr, sizeof (addr));
  218862. CFDataGetBytes ((CFDataRef) data, CFRangeMake (0, sizeof (addr)), addr);
  218863. CFRelease (data);
  218864. int64 a = 0;
  218865. for (int i = 6; --i >= 0;)
  218866. a = (a << 8) | addr[i];
  218867. if (! littleEndian)
  218868. a = (int64) swapByteOrder ((uint64) a);
  218869. if (numResults < maxNum)
  218870. {
  218871. *addresses++ = a;
  218872. ++numResults;
  218873. }
  218874. }
  218875. IOObjectRelease (controller);
  218876. }
  218877. IOObjectRelease (i);
  218878. }
  218879. IOObjectRelease (it);
  218880. }
  218881. return numResults;
  218882. }
  218883. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  218884. const String& emailSubject,
  218885. const String& bodyText,
  218886. const StringArray& filesToAttach)
  218887. {
  218888. const ScopedAutoReleasePool pool;
  218889. String script;
  218890. script << "tell application \"Mail\"\r\n"
  218891. "set newMessage to make new outgoing message with properties {subject:\""
  218892. << emailSubject.replace (T("\""), T("\\\""))
  218893. << "\", content:\""
  218894. << bodyText.replace (T("\""), T("\\\""))
  218895. << "\" & return & return}\r\n"
  218896. "tell newMessage\r\n"
  218897. "set visible to true\r\n"
  218898. "set sender to \"sdfsdfsdfewf\"\r\n"
  218899. "make new to recipient at end of to recipients with properties {address:\""
  218900. << targetEmailAddress
  218901. << "\"}\r\n";
  218902. for (int i = 0; i < filesToAttach.size(); ++i)
  218903. {
  218904. script << "tell content\r\n"
  218905. "make new attachment with properties {file name:\""
  218906. << filesToAttach[i].replace (T("\""), T("\\\""))
  218907. << "\"} at after the last paragraph\r\n"
  218908. "end tell\r\n";
  218909. }
  218910. script << "end tell\r\n"
  218911. "end tell\r\n";
  218912. NSAppleScript* s = [[NSAppleScript alloc]
  218913. initWithSource: juceStringToNS (script)];
  218914. NSDictionary* error = 0;
  218915. const bool ok = [s executeAndReturnError: &error] != nil;
  218916. [s release];
  218917. return ok;
  218918. }
  218919. END_JUCE_NAMESPACE
  218920. using namespace JUCE_NAMESPACE;
  218921. #define JuceURLConnection MakeObjCClassName(JuceURLConnection)
  218922. @interface JuceURLConnection : NSObject
  218923. {
  218924. @public
  218925. NSURLRequest* request;
  218926. NSURLConnection* connection;
  218927. NSMutableData* data;
  218928. Thread* runLoopThread;
  218929. bool initialised, hasFailed, hasFinished;
  218930. int position;
  218931. int64 contentLength;
  218932. NSLock* dataLock;
  218933. }
  218934. - (JuceURLConnection*) initWithRequest: (NSURLRequest*) req withCallback: (URL::OpenStreamProgressCallback*) callback withContext: (void*) context;
  218935. - (void) dealloc;
  218936. - (void) connection: (NSURLConnection*) connection didReceiveResponse: (NSURLResponse*) response;
  218937. - (void) connection: (NSURLConnection*) connection didFailWithError: (NSError*) error;
  218938. - (void) connection: (NSURLConnection*) connection didReceiveData: (NSData*) data;
  218939. - (void) connectionDidFinishLoading: (NSURLConnection*) connection;
  218940. - (BOOL) isOpen;
  218941. - (int) read: (char*) dest numBytes: (int) num;
  218942. - (int) readPosition;
  218943. - (void) stop;
  218944. - (void) createConnection;
  218945. @end
  218946. class JuceURLConnectionMessageThread : public Thread
  218947. {
  218948. JuceURLConnection* owner;
  218949. public:
  218950. JuceURLConnectionMessageThread (JuceURLConnection* owner_)
  218951. : Thread (T("http connection")),
  218952. owner (owner_)
  218953. {
  218954. }
  218955. ~JuceURLConnectionMessageThread()
  218956. {
  218957. stopThread (10000);
  218958. }
  218959. void run()
  218960. {
  218961. [owner createConnection];
  218962. while (! threadShouldExit())
  218963. {
  218964. const ScopedAutoReleasePool pool;
  218965. [[NSRunLoop currentRunLoop] runUntilDate: [NSDate dateWithTimeIntervalSinceNow: 0.01]];
  218966. }
  218967. }
  218968. };
  218969. @implementation JuceURLConnection
  218970. - (JuceURLConnection*) initWithRequest: (NSURLRequest*) req
  218971. withCallback: (URL::OpenStreamProgressCallback*) callback
  218972. withContext: (void*) context;
  218973. {
  218974. [super init];
  218975. request = req;
  218976. [request retain];
  218977. data = [[NSMutableData data] retain];
  218978. dataLock = [[NSLock alloc] init];
  218979. connection = 0;
  218980. initialised = false;
  218981. hasFailed = false;
  218982. hasFinished = false;
  218983. contentLength = -1;
  218984. runLoopThread = new JuceURLConnectionMessageThread (self);
  218985. runLoopThread->startThread();
  218986. while (runLoopThread->isThreadRunning() && ! initialised)
  218987. {
  218988. if (callback != 0)
  218989. callback (context, -1, [[request HTTPBody] length]);
  218990. Thread::sleep (1);
  218991. }
  218992. return self;
  218993. }
  218994. - (void) dealloc
  218995. {
  218996. [self stop];
  218997. delete runLoopThread;
  218998. [connection release];
  218999. [data release];
  219000. [dataLock release];
  219001. [request release];
  219002. [super dealloc];
  219003. }
  219004. - (void) createConnection
  219005. {
  219006. connection = [[NSURLConnection alloc] initWithRequest: request
  219007. delegate: [self retain]];
  219008. if (connection == nil)
  219009. runLoopThread->signalThreadShouldExit();
  219010. }
  219011. - (void) connection: (NSURLConnection*) connection didReceiveResponse: (NSURLResponse*) response
  219012. {
  219013. [dataLock lock];
  219014. [data setLength: 0];
  219015. [dataLock unlock];
  219016. initialised = true;
  219017. contentLength = [response expectedContentLength];
  219018. }
  219019. - (void) connection: (NSURLConnection*) connection didFailWithError: (NSError*) error
  219020. {
  219021. DBG (nsStringToJuce ([error description]));
  219022. hasFailed = true;
  219023. initialised = true;
  219024. runLoopThread->signalThreadShouldExit();
  219025. }
  219026. - (void) connection: (NSURLConnection*) connection didReceiveData: (NSData*) newData
  219027. {
  219028. [dataLock lock];
  219029. [data appendData: newData];
  219030. [dataLock unlock];
  219031. initialised = true;
  219032. }
  219033. - (void) connectionDidFinishLoading: (NSURLConnection*) connection
  219034. {
  219035. hasFinished = true;
  219036. initialised = true;
  219037. runLoopThread->signalThreadShouldExit();
  219038. }
  219039. - (BOOL) isOpen
  219040. {
  219041. return connection != 0 && ! hasFailed;
  219042. }
  219043. - (int) readPosition
  219044. {
  219045. return position;
  219046. }
  219047. - (int) read: (char*) dest numBytes: (int) numNeeded
  219048. {
  219049. int numDone = 0;
  219050. while (numNeeded > 0)
  219051. {
  219052. int available = jmin (numNeeded, [data length]);
  219053. if (available > 0)
  219054. {
  219055. [dataLock lock];
  219056. [data getBytes: dest length: available];
  219057. [data replaceBytesInRange: NSMakeRange (0, available) withBytes: nil length: 0];
  219058. [dataLock unlock];
  219059. numDone += available;
  219060. numNeeded -= available;
  219061. dest += available;
  219062. }
  219063. else
  219064. {
  219065. if (hasFailed || hasFinished)
  219066. break;
  219067. Thread::sleep (1);
  219068. }
  219069. }
  219070. position += numDone;
  219071. return numDone;
  219072. }
  219073. - (void) stop
  219074. {
  219075. [connection cancel];
  219076. runLoopThread->stopThread (10000);
  219077. }
  219078. @end
  219079. BEGIN_JUCE_NAMESPACE
  219080. bool juce_isOnLine()
  219081. {
  219082. return true;
  219083. }
  219084. void* juce_openInternetFile (const String& url,
  219085. const String& headers,
  219086. const MemoryBlock& postData,
  219087. const bool isPost,
  219088. URL::OpenStreamProgressCallback* callback,
  219089. void* callbackContext,
  219090. int timeOutMs)
  219091. {
  219092. const ScopedAutoReleasePool pool;
  219093. NSMutableURLRequest* req = [NSMutableURLRequest
  219094. requestWithURL: [NSURL URLWithString: juceStringToNS (url)]
  219095. cachePolicy: NSURLRequestUseProtocolCachePolicy
  219096. timeoutInterval: timeOutMs <= 0 ? 60.0 : (timeOutMs / 1000.0)];
  219097. if (req == nil)
  219098. return 0;
  219099. [req setHTTPMethod: isPost ? @"POST" : @"GET"];
  219100. //[req setCachePolicy: NSURLRequestReloadIgnoringLocalAndRemoteCacheData];
  219101. StringArray headerLines;
  219102. headerLines.addLines (headers);
  219103. headerLines.removeEmptyStrings (true);
  219104. for (int i = 0; i < headerLines.size(); ++i)
  219105. {
  219106. const String key (headerLines[i].upToFirstOccurrenceOf (T(":"), false, false).trim());
  219107. const String value (headerLines[i].fromFirstOccurrenceOf (T(":"), false, false).trim());
  219108. if (key.isNotEmpty() && value.isNotEmpty())
  219109. [req addValue: juceStringToNS (value) forHTTPHeaderField: juceStringToNS (key)];
  219110. }
  219111. if (isPost && postData.getSize() > 0)
  219112. {
  219113. [req setHTTPBody: [NSData dataWithBytes: postData.getData()
  219114. length: postData.getSize()]];
  219115. }
  219116. JuceURLConnection* const s = [[JuceURLConnection alloc] initWithRequest: req
  219117. withCallback: callback
  219118. withContext: callbackContext];
  219119. if ([s isOpen])
  219120. return s;
  219121. [s release];
  219122. return 0;
  219123. }
  219124. void juce_closeInternetFile (void* handle)
  219125. {
  219126. JuceURLConnection* const s = (JuceURLConnection*) handle;
  219127. if (s != 0)
  219128. {
  219129. const ScopedAutoReleasePool pool;
  219130. [s stop];
  219131. [s release];
  219132. }
  219133. }
  219134. int juce_readFromInternetFile (void* handle, void* buffer, int bytesToRead)
  219135. {
  219136. JuceURLConnection* const s = (JuceURLConnection*) handle;
  219137. if (s != 0)
  219138. {
  219139. const ScopedAutoReleasePool pool;
  219140. return [s read: (char*) buffer numBytes: bytesToRead];
  219141. }
  219142. return 0;
  219143. }
  219144. int64 juce_getInternetFileContentLength (void* handle)
  219145. {
  219146. JuceURLConnection* const s = (JuceURLConnection*) handle;
  219147. if (s != 0)
  219148. return s->contentLength;
  219149. return -1;
  219150. }
  219151. int juce_seekInInternetFile (void* handle, int newPosition)
  219152. {
  219153. JuceURLConnection* const s = (JuceURLConnection*) handle;
  219154. if (s != 0)
  219155. return [s readPosition];
  219156. return 0;
  219157. }
  219158. #endif
  219159. /********* End of inlined file: juce_mac_Network.mm *********/
  219160. /********* Start of inlined file: juce_posix_NamedPipe.cpp *********/
  219161. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  219162. // compiled on its own).
  219163. #if JUCE_INCLUDED_FILE
  219164. struct NamedPipeInternal
  219165. {
  219166. String pipeInName, pipeOutName;
  219167. int pipeIn, pipeOut;
  219168. bool volatile createdPipe, blocked, stopReadOperation;
  219169. static void signalHandler (int) {}
  219170. };
  219171. void NamedPipe::cancelPendingReads()
  219172. {
  219173. while (internal != 0 && ((NamedPipeInternal*) internal)->blocked)
  219174. {
  219175. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  219176. intern->stopReadOperation = true;
  219177. char buffer [1] = { 0 };
  219178. int bytesWritten = ::write (intern->pipeIn, buffer, 1);
  219179. (void) bytesWritten;
  219180. int timeout = 2000;
  219181. while (intern->blocked && --timeout >= 0)
  219182. Thread::sleep (2);
  219183. intern->stopReadOperation = false;
  219184. }
  219185. }
  219186. void NamedPipe::close()
  219187. {
  219188. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  219189. if (intern != 0)
  219190. {
  219191. internal = 0;
  219192. if (intern->pipeIn != -1)
  219193. ::close (intern->pipeIn);
  219194. if (intern->pipeOut != -1)
  219195. ::close (intern->pipeOut);
  219196. if (intern->createdPipe)
  219197. {
  219198. unlink (intern->pipeInName);
  219199. unlink (intern->pipeOutName);
  219200. }
  219201. delete intern;
  219202. }
  219203. }
  219204. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  219205. {
  219206. close();
  219207. NamedPipeInternal* const intern = new NamedPipeInternal();
  219208. internal = intern;
  219209. intern->createdPipe = createPipe;
  219210. intern->blocked = false;
  219211. intern->stopReadOperation = false;
  219212. signal (SIGPIPE, NamedPipeInternal::signalHandler);
  219213. siginterrupt (SIGPIPE, 1);
  219214. const String pipePath (T("/tmp/") + File::createLegalFileName (pipeName));
  219215. intern->pipeInName = pipePath + T("_in");
  219216. intern->pipeOutName = pipePath + T("_out");
  219217. intern->pipeIn = -1;
  219218. intern->pipeOut = -1;
  219219. if (createPipe)
  219220. {
  219221. if ((mkfifo (intern->pipeInName, 0666) && errno != EEXIST)
  219222. || (mkfifo (intern->pipeOutName, 0666) && errno != EEXIST))
  219223. {
  219224. delete intern;
  219225. internal = 0;
  219226. return false;
  219227. }
  219228. }
  219229. return true;
  219230. }
  219231. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int /*timeOutMilliseconds*/)
  219232. {
  219233. int bytesRead = -1;
  219234. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  219235. if (intern != 0)
  219236. {
  219237. intern->blocked = true;
  219238. if (intern->pipeIn == -1)
  219239. {
  219240. if (intern->createdPipe)
  219241. intern->pipeIn = ::open (intern->pipeInName, O_RDWR);
  219242. else
  219243. intern->pipeIn = ::open (intern->pipeOutName, O_RDWR);
  219244. if (intern->pipeIn == -1)
  219245. {
  219246. intern->blocked = false;
  219247. return -1;
  219248. }
  219249. }
  219250. bytesRead = 0;
  219251. char* p = (char*) destBuffer;
  219252. while (bytesRead < maxBytesToRead)
  219253. {
  219254. const int bytesThisTime = maxBytesToRead - bytesRead;
  219255. const int numRead = ::read (intern->pipeIn, p, bytesThisTime);
  219256. if (numRead <= 0 || intern->stopReadOperation)
  219257. {
  219258. bytesRead = -1;
  219259. break;
  219260. }
  219261. bytesRead += numRead;
  219262. p += bytesRead;
  219263. }
  219264. intern->blocked = false;
  219265. }
  219266. return bytesRead;
  219267. }
  219268. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  219269. {
  219270. int bytesWritten = -1;
  219271. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  219272. if (intern != 0)
  219273. {
  219274. if (intern->pipeOut == -1)
  219275. {
  219276. if (intern->createdPipe)
  219277. intern->pipeOut = ::open (intern->pipeOutName, O_WRONLY);
  219278. else
  219279. intern->pipeOut = ::open (intern->pipeInName, O_WRONLY);
  219280. if (intern->pipeOut == -1)
  219281. {
  219282. return -1;
  219283. }
  219284. }
  219285. const char* p = (const char*) sourceBuffer;
  219286. bytesWritten = 0;
  219287. const uint32 timeOutTime = Time::getMillisecondCounter() + timeOutMilliseconds;
  219288. while (bytesWritten < numBytesToWrite
  219289. && (timeOutMilliseconds < 0 || Time::getMillisecondCounter() < timeOutTime))
  219290. {
  219291. const int bytesThisTime = numBytesToWrite - bytesWritten;
  219292. const int numWritten = ::write (intern->pipeOut, p, bytesThisTime);
  219293. if (numWritten <= 0)
  219294. {
  219295. bytesWritten = -1;
  219296. break;
  219297. }
  219298. bytesWritten += numWritten;
  219299. p += bytesWritten;
  219300. }
  219301. }
  219302. return bytesWritten;
  219303. }
  219304. #endif
  219305. /********* End of inlined file: juce_posix_NamedPipe.cpp *********/
  219306. /********* Start of inlined file: juce_mac_Threads.mm *********/
  219307. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  219308. // compiled on its own).
  219309. #ifdef JUCE_INCLUDED_FILE
  219310. /*
  219311. Note that a lot of methods that you'd expect to find in this file actually
  219312. live in juce_posix_SharedCode.h!
  219313. */
  219314. void JUCE_API juce_threadEntryPoint (void*);
  219315. void* threadEntryProc (void* userData) throw()
  219316. {
  219317. const ScopedAutoReleasePool pool;
  219318. juce_threadEntryPoint (userData);
  219319. return 0;
  219320. }
  219321. void* juce_createThread (void* userData) throw()
  219322. {
  219323. pthread_t handle = 0;
  219324. if (pthread_create (&handle, 0, threadEntryProc, userData) == 0)
  219325. {
  219326. pthread_detach (handle);
  219327. return (void*) handle;
  219328. }
  219329. return 0;
  219330. }
  219331. void juce_killThread (void* handle) throw()
  219332. {
  219333. if (handle != 0)
  219334. pthread_cancel ((pthread_t) handle);
  219335. }
  219336. void juce_setCurrentThreadName (const String& /*name*/) throw()
  219337. {
  219338. }
  219339. Thread::ThreadID Thread::getCurrentThreadId() throw()
  219340. {
  219341. return (ThreadID) pthread_self();
  219342. }
  219343. bool juce_setThreadPriority (void* handle, int priority) throw()
  219344. {
  219345. if (handle == 0)
  219346. handle = (void*) pthread_self();
  219347. struct sched_param param;
  219348. int policy;
  219349. pthread_getschedparam ((pthread_t) handle, &policy, &param);
  219350. param.sched_priority = jlimit (1, 127, 1 + (priority * 126) / 11);
  219351. return pthread_setschedparam ((pthread_t) handle, policy, &param) == 0;
  219352. }
  219353. void Thread::yield() throw()
  219354. {
  219355. sched_yield();
  219356. }
  219357. void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask) throw()
  219358. {
  219359. // xxx
  219360. jassertfalse
  219361. }
  219362. bool Process::isForegroundProcess() throw()
  219363. {
  219364. return [NSApp isActive];
  219365. }
  219366. void Process::raisePrivilege()
  219367. {
  219368. jassertfalse
  219369. }
  219370. void Process::lowerPrivilege()
  219371. {
  219372. jassertfalse
  219373. }
  219374. void Process::terminate()
  219375. {
  219376. exit (0);
  219377. }
  219378. void Process::setPriority (ProcessPriority p)
  219379. {
  219380. // xxx
  219381. }
  219382. #endif
  219383. /********* End of inlined file: juce_mac_Threads.mm *********/
  219384. /********* Start of inlined file: juce_posix_SharedCode.h *********/
  219385. /*
  219386. This file contains posix routines that are common to both the Linux and Mac builds.
  219387. It gets included directly in the cpp files for these platforms.
  219388. */
  219389. CriticalSection::CriticalSection() throw()
  219390. {
  219391. pthread_mutexattr_t atts;
  219392. pthread_mutexattr_init (&atts);
  219393. pthread_mutexattr_settype (&atts, PTHREAD_MUTEX_RECURSIVE);
  219394. pthread_mutex_init (&internal, &atts);
  219395. }
  219396. CriticalSection::~CriticalSection() throw()
  219397. {
  219398. pthread_mutex_destroy (&internal);
  219399. }
  219400. void CriticalSection::enter() const throw()
  219401. {
  219402. pthread_mutex_lock (&internal);
  219403. }
  219404. bool CriticalSection::tryEnter() const throw()
  219405. {
  219406. return pthread_mutex_trylock (&internal) == 0;
  219407. }
  219408. void CriticalSection::exit() const throw()
  219409. {
  219410. pthread_mutex_unlock (&internal);
  219411. }
  219412. struct EventStruct
  219413. {
  219414. pthread_cond_t condition;
  219415. pthread_mutex_t mutex;
  219416. bool triggered;
  219417. };
  219418. WaitableEvent::WaitableEvent() throw()
  219419. {
  219420. EventStruct* const es = new EventStruct();
  219421. es->triggered = false;
  219422. pthread_cond_init (&es->condition, 0);
  219423. pthread_mutex_init (&es->mutex, 0);
  219424. internal = es;
  219425. }
  219426. WaitableEvent::~WaitableEvent() throw()
  219427. {
  219428. EventStruct* const es = (EventStruct*) internal;
  219429. pthread_cond_destroy (&es->condition);
  219430. pthread_mutex_destroy (&es->mutex);
  219431. delete es;
  219432. }
  219433. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  219434. {
  219435. EventStruct* const es = (EventStruct*) internal;
  219436. bool ok = true;
  219437. pthread_mutex_lock (&es->mutex);
  219438. if (timeOutMillisecs < 0)
  219439. {
  219440. while (! es->triggered)
  219441. pthread_cond_wait (&es->condition, &es->mutex);
  219442. }
  219443. else
  219444. {
  219445. while (! es->triggered)
  219446. {
  219447. struct timeval t;
  219448. gettimeofday (&t, 0);
  219449. struct timespec time;
  219450. time.tv_sec = t.tv_sec + (timeOutMillisecs / 1000);
  219451. time.tv_nsec = (t.tv_usec + ((timeOutMillisecs % 1000) * 1000)) * 1000;
  219452. if (time.tv_nsec >= 1000000000)
  219453. {
  219454. time.tv_nsec -= 1000000000;
  219455. time.tv_sec++;
  219456. }
  219457. if (pthread_cond_timedwait (&es->condition, &es->mutex, &time) == ETIMEDOUT)
  219458. {
  219459. ok = false;
  219460. break;
  219461. }
  219462. }
  219463. }
  219464. es->triggered = false;
  219465. pthread_mutex_unlock (&es->mutex);
  219466. return ok;
  219467. }
  219468. void WaitableEvent::signal() const throw()
  219469. {
  219470. EventStruct* const es = (EventStruct*) internal;
  219471. pthread_mutex_lock (&es->mutex);
  219472. es->triggered = true;
  219473. pthread_cond_broadcast (&es->condition);
  219474. pthread_mutex_unlock (&es->mutex);
  219475. }
  219476. void WaitableEvent::reset() const throw()
  219477. {
  219478. EventStruct* const es = (EventStruct*) internal;
  219479. pthread_mutex_lock (&es->mutex);
  219480. es->triggered = false;
  219481. pthread_mutex_unlock (&es->mutex);
  219482. }
  219483. void JUCE_CALLTYPE Thread::sleep (int millisecs) throw()
  219484. {
  219485. struct timespec time;
  219486. time.tv_sec = millisecs / 1000;
  219487. time.tv_nsec = (millisecs % 1000) * 1000000;
  219488. nanosleep (&time, 0);
  219489. }
  219490. const tchar File::separator = T('/');
  219491. const tchar* File::separatorString = T("/");
  219492. bool juce_copyFile (const String& s, const String& d) throw();
  219493. static bool juce_stat (const String& fileName, struct stat& info) throw()
  219494. {
  219495. return fileName.isNotEmpty()
  219496. && (stat (fileName.toUTF8(), &info) == 0);
  219497. }
  219498. bool juce_isDirectory (const String& fileName) throw()
  219499. {
  219500. struct stat info;
  219501. return fileName.isEmpty()
  219502. || (juce_stat (fileName, info)
  219503. && ((info.st_mode & S_IFDIR) != 0));
  219504. }
  219505. bool juce_fileExists (const String& fileName, const bool dontCountDirectories) throw()
  219506. {
  219507. if (fileName.isEmpty())
  219508. return false;
  219509. const char* const fileNameUTF8 = fileName.toUTF8();
  219510. bool exists = access (fileNameUTF8, F_OK) == 0;
  219511. if (exists && dontCountDirectories)
  219512. {
  219513. struct stat info;
  219514. const int res = stat (fileNameUTF8, &info);
  219515. if (res == 0 && (info.st_mode & S_IFDIR) != 0)
  219516. exists = false;
  219517. }
  219518. return exists;
  219519. }
  219520. int64 juce_getFileSize (const String& fileName) throw()
  219521. {
  219522. struct stat info;
  219523. return juce_stat (fileName, info) ? info.st_size : 0;
  219524. }
  219525. bool juce_canWriteToFile (const String& fileName) throw()
  219526. {
  219527. return access (fileName.toUTF8(), W_OK) == 0;
  219528. }
  219529. bool juce_deleteFile (const String& fileName) throw()
  219530. {
  219531. if (juce_isDirectory (fileName))
  219532. return rmdir ((const char*) fileName.toUTF8()) == 0;
  219533. else
  219534. return remove ((const char*) fileName.toUTF8()) == 0;
  219535. }
  219536. bool juce_moveFile (const String& source, const String& dest) throw()
  219537. {
  219538. if (rename (source.toUTF8(), dest.toUTF8()) == 0)
  219539. return true;
  219540. if (juce_canWriteToFile (source)
  219541. && juce_copyFile (source, dest))
  219542. {
  219543. if (juce_deleteFile (source))
  219544. return true;
  219545. juce_deleteFile (dest);
  219546. }
  219547. return false;
  219548. }
  219549. void juce_createDirectory (const String& fileName) throw()
  219550. {
  219551. mkdir (fileName.toUTF8(), 0777);
  219552. }
  219553. void* juce_fileOpen (const String& fileName, bool forWriting) throw()
  219554. {
  219555. int flags = O_RDONLY;
  219556. if (forWriting)
  219557. {
  219558. if (juce_fileExists (fileName, false))
  219559. {
  219560. const int f = open ((const char*) fileName.toUTF8(), O_RDWR, 00644);
  219561. if (f != -1)
  219562. lseek (f, 0, SEEK_END);
  219563. return (void*) f;
  219564. }
  219565. else
  219566. {
  219567. flags = O_RDWR + O_CREAT;
  219568. }
  219569. }
  219570. return (void*) open ((const char*) fileName.toUTF8(), flags, 00644);
  219571. }
  219572. void juce_fileClose (void* handle) throw()
  219573. {
  219574. if (handle != 0)
  219575. close ((int) (pointer_sized_int) handle);
  219576. }
  219577. int juce_fileRead (void* handle, void* buffer, int size) throw()
  219578. {
  219579. if (handle != 0)
  219580. return read ((int) (pointer_sized_int) handle, buffer, size);
  219581. return 0;
  219582. }
  219583. int juce_fileWrite (void* handle, const void* buffer, int size) throw()
  219584. {
  219585. if (handle != 0)
  219586. return write ((int) (pointer_sized_int) handle, buffer, size);
  219587. return 0;
  219588. }
  219589. int64 juce_fileSetPosition (void* handle, int64 pos) throw()
  219590. {
  219591. if (handle != 0 && lseek ((int) (pointer_sized_int) handle, pos, SEEK_SET) == pos)
  219592. return pos;
  219593. return -1;
  219594. }
  219595. int64 juce_fileGetPosition (void* handle) throw()
  219596. {
  219597. if (handle != 0)
  219598. return lseek ((int) (pointer_sized_int) handle, 0, SEEK_CUR);
  219599. else
  219600. return -1;
  219601. }
  219602. void juce_fileFlush (void* handle) throw()
  219603. {
  219604. if (handle != 0)
  219605. fsync ((int) (pointer_sized_int) handle);
  219606. }
  219607. const File juce_getExecutableFile()
  219608. {
  219609. Dl_info exeInfo;
  219610. dladdr ((const void*) juce_getExecutableFile, &exeInfo);
  219611. return File (exeInfo.dli_fname);
  219612. }
  219613. // if this file doesn't exist, find a parent of it that does..
  219614. static bool doStatFS (const File* file, struct statfs& result) throw()
  219615. {
  219616. File f (*file);
  219617. for (int i = 5; --i >= 0;)
  219618. {
  219619. if (f.exists())
  219620. break;
  219621. f = f.getParentDirectory();
  219622. }
  219623. return statfs (f.getFullPathName().toUTF8(), &result) == 0;
  219624. }
  219625. int64 File::getBytesFreeOnVolume() const throw()
  219626. {
  219627. struct statfs buf;
  219628. if (doStatFS (this, buf))
  219629. return (int64) buf.f_bsize * (int64) buf.f_bavail; // Note: this returns space available to non-super user
  219630. return 0;
  219631. }
  219632. int64 File::getVolumeTotalSize() const throw()
  219633. {
  219634. struct statfs buf;
  219635. if (doStatFS (this, buf))
  219636. return (int64) buf.f_bsize * (int64) buf.f_blocks;
  219637. return 0;
  219638. }
  219639. const String juce_getVolumeLabel (const String& filenameOnVolume,
  219640. int& volumeSerialNumber) throw()
  219641. {
  219642. volumeSerialNumber = 0;
  219643. #if JUCE_MAC
  219644. struct VolAttrBuf
  219645. {
  219646. u_int32_t length;
  219647. attrreference_t mountPointRef;
  219648. char mountPointSpace [MAXPATHLEN];
  219649. } attrBuf;
  219650. struct attrlist attrList;
  219651. zerostruct (attrList);
  219652. attrList.bitmapcount = ATTR_BIT_MAP_COUNT;
  219653. attrList.volattr = ATTR_VOL_INFO | ATTR_VOL_NAME;
  219654. File f (filenameOnVolume);
  219655. for (;;)
  219656. {
  219657. if (getattrlist ((const char*) f.getFullPathName().toUTF8(),
  219658. &attrList, &attrBuf, sizeof(attrBuf), 0) == 0)
  219659. {
  219660. return String::fromUTF8 (((const uint8*) &attrBuf.mountPointRef) + attrBuf.mountPointRef.attr_dataoffset,
  219661. (int) attrBuf.mountPointRef.attr_length);
  219662. }
  219663. const File parent (f.getParentDirectory());
  219664. if (f == parent)
  219665. break;
  219666. f = parent;
  219667. }
  219668. #endif
  219669. return String::empty;
  219670. }
  219671. void juce_runSystemCommand (const String& command)
  219672. {
  219673. int result = system ((const char*) command.toUTF8());
  219674. (void) result;
  219675. }
  219676. const String juce_getOutputFromCommand (const String& command)
  219677. {
  219678. // slight bodge here, as we just pipe the output into a temp file and read it...
  219679. const File tempFile (File::getSpecialLocation (File::tempDirectory)
  219680. .getNonexistentChildFile (String::toHexString (Random::getSystemRandom().nextInt()), ".tmp", false));
  219681. juce_runSystemCommand (command + " > " + tempFile.getFullPathName());
  219682. String result (tempFile.loadFileAsString());
  219683. tempFile.deleteFile();
  219684. return result;
  219685. }
  219686. #if JUCE_64BIT
  219687. #define filedesc ((long long) internal)
  219688. #else
  219689. #define filedesc ((int) internal)
  219690. #endif
  219691. InterProcessLock::InterProcessLock (const String& name_) throw()
  219692. : internal (0),
  219693. name (name_),
  219694. reentrancyLevel (0)
  219695. {
  219696. #if JUCE_MAC
  219697. // (don't use getSpecialLocation() to avoid the temp folder being different for each app)
  219698. const File temp (File (T("~/Library/Caches/Juce")).getChildFile (name));
  219699. #else
  219700. const File temp (File::getSpecialLocation (File::tempDirectory).getChildFile (name));
  219701. #endif
  219702. temp.create();
  219703. internal = (void*) open (temp.getFullPathName().toUTF8(), O_RDWR);
  219704. }
  219705. InterProcessLock::~InterProcessLock() throw()
  219706. {
  219707. while (reentrancyLevel > 0)
  219708. this->exit();
  219709. close (filedesc);
  219710. }
  219711. bool InterProcessLock::enter (const int timeOutMillisecs) throw()
  219712. {
  219713. if (internal == 0)
  219714. return false;
  219715. if (reentrancyLevel != 0)
  219716. return true;
  219717. const int64 endTime = Time::currentTimeMillis() + timeOutMillisecs;
  219718. struct flock fl;
  219719. zerostruct (fl);
  219720. fl.l_whence = SEEK_SET;
  219721. fl.l_type = F_WRLCK;
  219722. for (;;)
  219723. {
  219724. const int result = fcntl (filedesc, F_SETLK, &fl);
  219725. if (result >= 0)
  219726. {
  219727. ++reentrancyLevel;
  219728. return true;
  219729. }
  219730. if (errno != EINTR)
  219731. {
  219732. if (timeOutMillisecs == 0
  219733. || (timeOutMillisecs > 0 && Time::currentTimeMillis() >= endTime))
  219734. break;
  219735. Thread::sleep (10);
  219736. }
  219737. }
  219738. return false;
  219739. }
  219740. void InterProcessLock::exit() throw()
  219741. {
  219742. if (reentrancyLevel > 0 && internal != 0)
  219743. {
  219744. --reentrancyLevel;
  219745. struct flock fl;
  219746. zerostruct (fl);
  219747. fl.l_whence = SEEK_SET;
  219748. fl.l_type = F_UNLCK;
  219749. for (;;)
  219750. {
  219751. const int result = fcntl (filedesc, F_SETLKW, &fl);
  219752. if (result >= 0 || errno != EINTR)
  219753. break;
  219754. }
  219755. }
  219756. }
  219757. /********* End of inlined file: juce_posix_SharedCode.h *********/
  219758. /********* Start of inlined file: juce_mac_Files.mm *********/
  219759. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  219760. // compiled on its own).
  219761. #ifdef JUCE_INCLUDED_FILE
  219762. /*
  219763. Note that a lot of methods that you'd expect to find in this file actually
  219764. live in juce_posix_SharedCode.h!
  219765. */
  219766. const unsigned int macTimeToUnixTimeDiff = 0x7c25be90;
  219767. static uint64 utcDateTimeToUnixTime (const UTCDateTime& d) throw()
  219768. {
  219769. if (d.highSeconds == 0 && d.lowSeconds == 0 && d.fraction == 0)
  219770. return 0;
  219771. return (((((uint64) d.highSeconds) << 32) | (uint64) d.lowSeconds) * 1000)
  219772. + ((d.fraction * 1000) >> 16)
  219773. - 2082844800000ll;
  219774. }
  219775. static void unixTimeToUtcDateTime (uint64 t, UTCDateTime& d) throw()
  219776. {
  219777. if (t != 0)
  219778. t += 2082844800000ll;
  219779. d.highSeconds = (t / 1000) >> 32;
  219780. d.lowSeconds = (t / 1000) & (uint64) 0xffffffff;
  219781. d.fraction = ((t % 1000) << 16) / 1000;
  219782. }
  219783. void juce_getFileTimes (const String& fileName,
  219784. int64& modificationTime,
  219785. int64& accessTime,
  219786. int64& creationTime) throw()
  219787. {
  219788. modificationTime = 0;
  219789. accessTime = 0;
  219790. creationTime = 0;
  219791. FSRef fileRef;
  219792. if (PlatformUtilities::makeFSRefFromPath (&fileRef, fileName))
  219793. {
  219794. FSRefParam info;
  219795. zerostruct (info);
  219796. info.ref = &fileRef;
  219797. info.whichInfo = kFSCatInfoAllDates;
  219798. FSCatalogInfo catInfo;
  219799. info.catInfo = &catInfo;
  219800. if (PBGetCatalogInfoSync (&info) == noErr)
  219801. {
  219802. creationTime = utcDateTimeToUnixTime (catInfo.createDate);
  219803. accessTime = utcDateTimeToUnixTime (catInfo.accessDate);
  219804. modificationTime = utcDateTimeToUnixTime (catInfo.contentModDate);
  219805. }
  219806. }
  219807. }
  219808. bool juce_setFileTimes (const String& fileName,
  219809. int64 modificationTime,
  219810. int64 accessTime,
  219811. int64 creationTime) throw()
  219812. {
  219813. FSRef fileRef;
  219814. if (PlatformUtilities::makeFSRefFromPath (&fileRef, fileName))
  219815. {
  219816. FSRefParam info;
  219817. zerostruct (info);
  219818. info.ref = &fileRef;
  219819. info.whichInfo = kFSCatInfoAllDates;
  219820. FSCatalogInfo catInfo;
  219821. info.catInfo = &catInfo;
  219822. if (PBGetCatalogInfoSync (&info) == noErr)
  219823. {
  219824. if (creationTime != 0)
  219825. unixTimeToUtcDateTime (creationTime, catInfo.createDate);
  219826. if (modificationTime != 0)
  219827. unixTimeToUtcDateTime (modificationTime, catInfo.contentModDate);
  219828. if (accessTime != 0)
  219829. unixTimeToUtcDateTime (accessTime, catInfo.accessDate);
  219830. return PBSetCatalogInfoSync (&info) == noErr;
  219831. }
  219832. }
  219833. return false;
  219834. }
  219835. bool juce_setFileReadOnly (const String& fileName, bool isReadOnly) throw()
  219836. {
  219837. const char* const fileNameUTF8 = fileName.toUTF8();
  219838. struct stat info;
  219839. const int res = stat (fileNameUTF8, &info);
  219840. bool ok = false;
  219841. if (res == 0)
  219842. {
  219843. info.st_mode &= 0777; // Just permissions
  219844. if (isReadOnly)
  219845. info.st_mode &= ~(S_IWUSR | S_IWGRP | S_IWOTH);
  219846. else
  219847. // Give everybody write permission?
  219848. info.st_mode |= S_IWUSR | S_IWGRP | S_IWOTH;
  219849. ok = chmod (fileNameUTF8, info.st_mode) == 0;
  219850. }
  219851. return ok;
  219852. }
  219853. bool juce_copyFile (const String& src, const String& dst) throw()
  219854. {
  219855. const ScopedAutoReleasePool pool;
  219856. NSFileManager* fm = [NSFileManager defaultManager];
  219857. return [fm fileExistsAtPath: juceStringToNS (src)]
  219858. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  219859. && [fm copyItemAtPath: juceStringToNS (src)
  219860. toPath: juceStringToNS (dst)
  219861. error: nil];
  219862. #else
  219863. && [fm copyPath: juceStringToNS (src)
  219864. toPath: juceStringToNS (dst)
  219865. handler: nil];
  219866. #endif
  219867. }
  219868. const StringArray juce_getFileSystemRoots() throw()
  219869. {
  219870. StringArray s;
  219871. s.add (T("/"));
  219872. return s;
  219873. }
  219874. static bool isFileOnDriveType (const File* const f, const char** types) throw()
  219875. {
  219876. struct statfs buf;
  219877. if (doStatFS (f, buf))
  219878. {
  219879. const String type (buf.f_fstypename);
  219880. while (*types != 0)
  219881. if (type.equalsIgnoreCase (*types++))
  219882. return true;
  219883. }
  219884. return false;
  219885. }
  219886. bool File::isOnCDRomDrive() const throw()
  219887. {
  219888. static const char* const cdTypes[] = { "cd9660", "cdfs", "cddafs", "udf", 0 };
  219889. return isFileOnDriveType (this, (const char**) cdTypes);
  219890. }
  219891. bool File::isOnHardDisk() const throw()
  219892. {
  219893. static const char* const nonHDTypes[] = { "nfs", "smbfs", "ramfs", 0 };
  219894. return ! (isOnCDRomDrive() || isFileOnDriveType (this, (const char**) nonHDTypes));
  219895. }
  219896. bool File::isOnRemovableDrive() const throw()
  219897. {
  219898. const ScopedAutoReleasePool pool;
  219899. BOOL removable = false;
  219900. [[NSWorkspace sharedWorkspace]
  219901. getFileSystemInfoForPath: juceStringToNS (getFullPathName())
  219902. isRemovable: &removable
  219903. isWritable: nil
  219904. isUnmountable: nil
  219905. description: nil
  219906. type: nil];
  219907. return removable;
  219908. }
  219909. static bool juce_isHiddenFile (const String& path) throw()
  219910. {
  219911. FSRef ref;
  219912. if (! PlatformUtilities::makeFSRefFromPath (&ref, path))
  219913. return false;
  219914. FSCatalogInfo info;
  219915. FSGetCatalogInfo (&ref, kFSCatInfoNodeFlags | kFSCatInfoFinderInfo, &info, 0, 0, 0);
  219916. if ((info.nodeFlags & kFSNodeIsDirectoryBit) != 0)
  219917. return (((FolderInfo*) &info.finderInfo)->finderFlags & kIsInvisible) != 0;
  219918. return (((FileInfo*) &info.finderInfo)->finderFlags & kIsInvisible) != 0;
  219919. }
  219920. bool File::isHidden() const throw()
  219921. {
  219922. return juce_isHiddenFile (getFullPathName());
  219923. }
  219924. const File File::getSpecialLocation (const SpecialLocationType type)
  219925. {
  219926. const ScopedAutoReleasePool pool;
  219927. String resultPath;
  219928. switch (type)
  219929. {
  219930. case userHomeDirectory:
  219931. resultPath = nsStringToJuce (NSHomeDirectory());
  219932. break;
  219933. case userDocumentsDirectory:
  219934. resultPath = "~/Documents";
  219935. break;
  219936. case userDesktopDirectory:
  219937. resultPath = "~/Desktop";
  219938. break;
  219939. case userApplicationDataDirectory:
  219940. resultPath = "~/Library";
  219941. break;
  219942. case commonApplicationDataDirectory:
  219943. resultPath = "/Library";
  219944. break;
  219945. case globalApplicationsDirectory:
  219946. resultPath = "/Applications";
  219947. break;
  219948. case userMusicDirectory:
  219949. resultPath = "~/Music";
  219950. break;
  219951. case userMoviesDirectory:
  219952. resultPath = "~/Movies";
  219953. break;
  219954. case tempDirectory:
  219955. {
  219956. File tmp (T("~/Library/Caches/") + juce_getExecutableFile().getFileNameWithoutExtension());
  219957. tmp.createDirectory();
  219958. return tmp.getFullPathName();
  219959. }
  219960. case currentExecutableFile:
  219961. return juce_getExecutableFile();
  219962. case currentApplicationFile:
  219963. {
  219964. const File exe (juce_getExecutableFile());
  219965. const File parent (exe.getParentDirectory());
  219966. return parent.getFullPathName().endsWithIgnoreCase (T("Contents/MacOS"))
  219967. ? parent.getParentDirectory().getParentDirectory()
  219968. : exe;
  219969. }
  219970. default:
  219971. jassertfalse // unknown type?
  219972. break;
  219973. }
  219974. if (resultPath != 0)
  219975. return File (PlatformUtilities::convertToPrecomposedUnicode (resultPath));
  219976. return File::nonexistent;
  219977. }
  219978. const File File::getCurrentWorkingDirectory() throw()
  219979. {
  219980. char buf [2048];
  219981. getcwd (buf, sizeof(buf));
  219982. return File (PlatformUtilities::convertToPrecomposedUnicode (buf));
  219983. }
  219984. bool File::setAsCurrentWorkingDirectory() const throw()
  219985. {
  219986. return chdir (getFullPathName().toUTF8()) == 0;
  219987. }
  219988. const String File::getVersion() const throw()
  219989. {
  219990. const ScopedAutoReleasePool pool;
  219991. String result;
  219992. NSBundle* bundle = [NSBundle bundleWithPath: juceStringToNS (getFullPathName())];
  219993. if (bundle != 0)
  219994. {
  219995. NSDictionary* info = [bundle infoDictionary];
  219996. if (info != 0)
  219997. {
  219998. NSString* name = [info valueForKey: @"CFBundleShortVersionString"];
  219999. if (name != nil)
  220000. result = nsStringToJuce (name);
  220001. }
  220002. }
  220003. return result;
  220004. }
  220005. const File File::getLinkedTarget() const throw()
  220006. {
  220007. FSRef ref;
  220008. Boolean targetIsAFolder, wasAliased;
  220009. if (PlatformUtilities::makeFSRefFromPath (&ref, getFullPathName())
  220010. && (FSResolveAliasFileWithMountFlags (&ref, true, &targetIsAFolder, &wasAliased, 0) == noErr)
  220011. && wasAliased)
  220012. {
  220013. return File (PlatformUtilities::makePathFromFSRef (&ref));
  220014. }
  220015. return *this;
  220016. }
  220017. bool File::moveToTrash() const throw()
  220018. {
  220019. if (! exists())
  220020. return true;
  220021. const ScopedAutoReleasePool pool;
  220022. NSString* p = juceStringToNS (getFullPathName());
  220023. return [[NSWorkspace sharedWorkspace]
  220024. performFileOperation: NSWorkspaceRecycleOperation
  220025. source: [p stringByDeletingLastPathComponent]
  220026. destination: @""
  220027. files: [NSArray arrayWithObject: [p lastPathComponent]]
  220028. tag: nil ];
  220029. }
  220030. struct FindFileStruct
  220031. {
  220032. String parentDir, wildCard;
  220033. DIR* dir;
  220034. bool getNextMatch (String& result, bool* const isDir, bool* const isHidden, int64* const fileSize,
  220035. Time* const modTime, Time* const creationTime, bool* const isReadOnly) throw()
  220036. {
  220037. const char* const wildCardUTF8 = wildCard.toUTF8();
  220038. for (;;)
  220039. {
  220040. struct dirent* const de = readdir (dir);
  220041. if (de == 0)
  220042. break;
  220043. if (fnmatch (wildCardUTF8, de->d_name, 0) == 0)
  220044. {
  220045. result = String::fromUTF8 ((const uint8*) de->d_name);
  220046. const String path (parentDir + result);
  220047. if (isDir != 0 || fileSize != 0)
  220048. {
  220049. struct stat info;
  220050. const bool statOk = juce_stat (path, info);
  220051. if (isDir != 0)
  220052. *isDir = path.isEmpty() || (statOk && ((info.st_mode & S_IFDIR) != 0));
  220053. if (isHidden != 0)
  220054. *isHidden = (de->d_name[0] == '.')
  220055. || juce_isHiddenFile (path);
  220056. if (fileSize != 0)
  220057. *fileSize = statOk ? info.st_size : 0;
  220058. }
  220059. if (modTime != 0 || creationTime != 0)
  220060. {
  220061. int64 m, a, c;
  220062. juce_getFileTimes (path, m, a, c);
  220063. if (modTime != 0)
  220064. *modTime = m;
  220065. if (creationTime != 0)
  220066. *creationTime = c;
  220067. }
  220068. if (isReadOnly != 0)
  220069. *isReadOnly = ! juce_canWriteToFile (path);
  220070. return true;
  220071. }
  220072. }
  220073. return false;
  220074. }
  220075. };
  220076. // returns 0 on failure
  220077. void* juce_findFileStart (const String& directory, const String& wildCard, String& firstResultFile,
  220078. bool* isDir, bool* isHidden, int64* fileSize, Time* modTime,
  220079. Time* creationTime, bool* isReadOnly) throw()
  220080. {
  220081. DIR* const d = opendir (directory.toUTF8());
  220082. if (d != 0)
  220083. {
  220084. FindFileStruct* const ff = new FindFileStruct();
  220085. ff->parentDir = directory;
  220086. if (!ff->parentDir.endsWithChar (File::separator))
  220087. ff->parentDir += File::separator;
  220088. ff->wildCard = wildCard;
  220089. ff->dir = d;
  220090. if (ff->getNextMatch (firstResultFile, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly))
  220091. {
  220092. return ff;
  220093. }
  220094. else
  220095. {
  220096. firstResultFile = String::empty;
  220097. isDir = false;
  220098. closedir (d);
  220099. delete ff;
  220100. }
  220101. }
  220102. return 0;
  220103. }
  220104. bool juce_findFileNext (void* handle, String& resultFile,
  220105. bool* isDir, bool* isHidden, int64* fileSize, Time* modTime, Time* creationTime, bool* isReadOnly) throw()
  220106. {
  220107. FindFileStruct* const ff = (FindFileStruct*) handle;
  220108. if (ff != 0)
  220109. return ff->getNextMatch (resultFile, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly);
  220110. return false;
  220111. }
  220112. void juce_findFileClose (void* handle) throw()
  220113. {
  220114. FindFileStruct* const ff = (FindFileStruct*)handle;
  220115. if (ff != 0)
  220116. {
  220117. closedir (ff->dir);
  220118. delete ff;
  220119. }
  220120. }
  220121. bool juce_launchExecutable (const String& pathAndArguments) throw()
  220122. {
  220123. const char* const argv[4] = { "/bin/sh", "-c", (const char*) pathAndArguments, 0 };
  220124. const int cpid = fork();
  220125. if (cpid == 0)
  220126. {
  220127. // Child process
  220128. if (execve (argv[0], (char**) argv, 0) < 0)
  220129. exit (0);
  220130. }
  220131. else
  220132. {
  220133. if (cpid < 0)
  220134. return false;
  220135. }
  220136. return true;
  220137. }
  220138. bool juce_launchFile (const String& fileName,
  220139. const String& parameters) throw()
  220140. {
  220141. const ScopedAutoReleasePool pool;
  220142. if (parameters.isEmpty())
  220143. {
  220144. return [[NSWorkspace sharedWorkspace] openFile: juceStringToNS (fileName)]
  220145. || [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: juceStringToNS (fileName)]];
  220146. }
  220147. bool ok = false;
  220148. FSRef ref;
  220149. if (PlatformUtilities::makeFSRefFromPath (&ref, fileName))
  220150. {
  220151. if (PlatformUtilities::isBundle (fileName))
  220152. {
  220153. NSMutableArray* urls = [NSMutableArray array];
  220154. StringArray docs;
  220155. docs.addTokens (parameters, true);
  220156. for (int i = 0; i < docs.size(); ++i)
  220157. [urls addObject: juceStringToNS (docs[i])];
  220158. ok = [[NSWorkspace sharedWorkspace] openURLs: urls
  220159. withAppBundleIdentifier: [[NSBundle bundleWithPath: juceStringToNS (fileName)] bundleIdentifier]
  220160. options: nil
  220161. additionalEventParamDescriptor: nil
  220162. launchIdentifiers: nil];
  220163. }
  220164. else
  220165. {
  220166. ok = juce_launchExecutable (T("\"") + fileName + T("\" ") + parameters);
  220167. }
  220168. }
  220169. return ok;
  220170. }
  220171. bool PlatformUtilities::makeFSRefFromPath (FSRef* destFSRef, const String& path)
  220172. {
  220173. return FSPathMakeRef ((const UInt8*) path.toUTF8(), destFSRef, 0) == noErr;
  220174. }
  220175. const String PlatformUtilities::makePathFromFSRef (FSRef* file)
  220176. {
  220177. uint8 path [2048];
  220178. zeromem (path, sizeof (path));
  220179. String result;
  220180. if (FSRefMakePath (file, (UInt8*) path, sizeof (path) - 1) == noErr)
  220181. result = String::fromUTF8 (path);
  220182. return PlatformUtilities::convertToPrecomposedUnicode (result);
  220183. }
  220184. OSType PlatformUtilities::getTypeOfFile (const String& filename)
  220185. {
  220186. const ScopedAutoReleasePool pool;
  220187. return NSHFSTypeCodeFromFileType (NSHFSTypeOfFile (juceStringToNS (filename)));
  220188. }
  220189. bool PlatformUtilities::isBundle (const String& filename)
  220190. {
  220191. const ScopedAutoReleasePool pool;
  220192. return [[NSWorkspace sharedWorkspace] isFilePackageAtPath: juceStringToNS (filename)];
  220193. }
  220194. #endif
  220195. /********* End of inlined file: juce_mac_Files.mm *********/
  220196. /********* Start of inlined file: juce_mac_MiscUtilities.mm *********/
  220197. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  220198. // compiled on its own).
  220199. #ifdef JUCE_INCLUDED_FILE
  220200. ScopedAutoReleasePool::ScopedAutoReleasePool()
  220201. {
  220202. pool = [[NSAutoreleasePool alloc] init];
  220203. }
  220204. ScopedAutoReleasePool::~ScopedAutoReleasePool()
  220205. {
  220206. [((NSAutoreleasePool*) pool) release];
  220207. }
  220208. void PlatformUtilities::beep()
  220209. {
  220210. NSBeep();
  220211. }
  220212. void PlatformUtilities::addItemToDock (const File& file)
  220213. {
  220214. // check that it's not already there...
  220215. if (! juce_getOutputFromCommand ("defaults read com.apple.dock persistent-apps")
  220216. .containsIgnoreCase (file.getFullPathName()))
  220217. {
  220218. juce_runSystemCommand ("defaults write com.apple.dock persistent-apps -array-add \"<dict><key>tile-data</key><dict><key>file-data</key><dict><key>_CFURLString</key><string>"
  220219. + file.getFullPathName() + "</string><key>_CFURLStringType</key><integer>0</integer></dict></dict></dict>\"");
  220220. juce_runSystemCommand ("osascript -e \"tell application \\\"Dock\\\" to quit\"");
  220221. }
  220222. }
  220223. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  220224. bool AlertWindow::showNativeDialogBox (const String& title,
  220225. const String& bodyText,
  220226. bool isOkCancel)
  220227. {
  220228. const ScopedAutoReleasePool pool;
  220229. return NSRunAlertPanel (juceStringToNS (title),
  220230. juceStringToNS (bodyText),
  220231. @"Ok",
  220232. isOkCancel ? @"Cancel" : nil,
  220233. nil) == NSAlertDefaultReturn;
  220234. }
  220235. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMoveFiles)
  220236. {
  220237. if (files.size() == 0)
  220238. return false;
  220239. Component* sourceComp = Component::getComponentUnderMouse();
  220240. if (sourceComp == 0)
  220241. {
  220242. jassertfalse // this method must be called in response to a
  220243. // component's mouseDrag event!
  220244. return false;
  220245. }
  220246. const ScopedAutoReleasePool pool;
  220247. NSView* view = (NSView*) sourceComp->getWindowHandle();
  220248. if (view == 0)
  220249. return false;
  220250. NSPasteboard* pboard = [NSPasteboard pasteboardWithName: NSDragPboard];
  220251. [pboard declareTypes: [NSArray arrayWithObject: NSFilenamesPboardType]
  220252. owner: nil];
  220253. NSMutableArray* filesArray = [NSMutableArray arrayWithCapacity: 4];
  220254. for (int i = 0; i < files.size(); ++i)
  220255. [filesArray addObject: juceStringToNS (files[i])];
  220256. [pboard setPropertyList: filesArray
  220257. forType: NSFilenamesPboardType];
  220258. NSPoint dragPosition = [view convertPoint: [[[view window] currentEvent] locationInWindow]
  220259. fromView: nil];
  220260. dragPosition.x -= 16;
  220261. dragPosition.y -= 16;
  220262. [view dragImage: [[NSWorkspace sharedWorkspace] iconForFile: juceStringToNS (files[0])]
  220263. at: dragPosition
  220264. offset: NSMakeSize (0, 0)
  220265. event: [[view window] currentEvent]
  220266. pasteboard: pboard
  220267. source: view
  220268. slideBack: YES];
  220269. return true;
  220270. }
  220271. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  220272. {
  220273. jassertfalse // not implemented!
  220274. return false;
  220275. }
  220276. bool Desktop::canUseSemiTransparentWindows() throw()
  220277. {
  220278. return true;
  220279. }
  220280. void Desktop::getMousePosition (int& x, int& y) throw()
  220281. {
  220282. const ScopedAutoReleasePool pool;
  220283. const NSPoint p ([NSEvent mouseLocation]);
  220284. x = roundFloatToInt (p.x);
  220285. y = roundFloatToInt ([[[NSScreen screens] objectAtIndex: 0] frame].size.height - p.y);
  220286. }
  220287. void Desktop::setMousePosition (int x, int y) throw()
  220288. {
  220289. // this rubbish needs to be done around the warp call, to avoid causing a
  220290. // bizarre glitch..
  220291. CGAssociateMouseAndMouseCursorPosition (false);
  220292. #if (! defined (MAC_OS_X_VERSION_10_6)) || MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_6
  220293. CGSetLocalEventsSuppressionInterval (0);
  220294. #endif
  220295. CGPoint pos = { x, y };
  220296. CGWarpMouseCursorPosition (pos);
  220297. CGAssociateMouseAndMouseCursorPosition (true);
  220298. }
  220299. #if MACOS_10_4_OR_EARLIER
  220300. class ScreenSaverDefeater : public Timer,
  220301. public DeletedAtShutdown
  220302. {
  220303. public:
  220304. ScreenSaverDefeater() throw()
  220305. {
  220306. startTimer (10000);
  220307. timerCallback();
  220308. }
  220309. ~ScreenSaverDefeater() {}
  220310. void timerCallback()
  220311. {
  220312. if (Process::isForegroundProcess())
  220313. UpdateSystemActivity (UsrActivity);
  220314. }
  220315. };
  220316. static ScreenSaverDefeater* screenSaverDefeater = 0;
  220317. void Desktop::setScreenSaverEnabled (const bool isEnabled) throw()
  220318. {
  220319. if (isEnabled)
  220320. {
  220321. deleteAndZero (screenSaverDefeater);
  220322. }
  220323. else if (screenSaverDefeater == 0)
  220324. {
  220325. screenSaverDefeater = new ScreenSaverDefeater();
  220326. }
  220327. }
  220328. bool Desktop::isScreenSaverEnabled() throw()
  220329. {
  220330. return screenSaverDefeater == 0;
  220331. }
  220332. #else
  220333. static IOPMAssertionID screenSaverDisablerID = 0;
  220334. void Desktop::setScreenSaverEnabled (const bool isEnabled) throw()
  220335. {
  220336. if (isEnabled)
  220337. {
  220338. if (screenSaverDisablerID != 0)
  220339. {
  220340. IOPMAssertionRelease (screenSaverDisablerID);
  220341. screenSaverDisablerID = 0;
  220342. }
  220343. }
  220344. else
  220345. {
  220346. if (screenSaverDisablerID == 0)
  220347. {
  220348. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  220349. IOPMAssertionCreateWithName (kIOPMAssertionTypeNoIdleSleep, kIOPMAssertionLevelOn,
  220350. CFSTR ("Juce"), &screenSaverDisablerID);
  220351. #else
  220352. IOPMAssertionCreate (kIOPMAssertionTypeNoIdleSleep, kIOPMAssertionLevelOn,
  220353. &screenSaverDisablerID);
  220354. #endif
  220355. }
  220356. }
  220357. }
  220358. bool Desktop::isScreenSaverEnabled() throw()
  220359. {
  220360. return screenSaverDisablerID == 0;
  220361. }
  220362. #endif
  220363. void juce_updateMultiMonitorInfo (Array <Rectangle>& monitorCoords, const bool clipToWorkArea) throw()
  220364. {
  220365. const ScopedAutoReleasePool pool;
  220366. monitorCoords.clear();
  220367. NSArray* screens = [NSScreen screens];
  220368. const float mainScreenBottom = [[[NSScreen screens] objectAtIndex: 0] frame].size.height;
  220369. for (unsigned int i = 0; i < [screens count]; ++i)
  220370. {
  220371. NSScreen* s = (NSScreen*) [screens objectAtIndex: i];
  220372. NSRect r = clipToWorkArea ? [s visibleFrame]
  220373. : [s frame];
  220374. monitorCoords.add (Rectangle ((int) r.origin.x,
  220375. (int) (mainScreenBottom - (r.origin.y + r.size.height)),
  220376. (int) r.size.width,
  220377. (int) r.size.height));
  220378. }
  220379. jassert (monitorCoords.size() > 0);
  220380. }
  220381. #endif
  220382. #endif
  220383. /********* End of inlined file: juce_mac_MiscUtilities.mm *********/
  220384. /********* Start of inlined file: juce_mac_Debugging.mm *********/
  220385. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  220386. // compiled on its own).
  220387. #ifdef JUCE_INCLUDED_FILE
  220388. void Logger::outputDebugString (const String& text) throw()
  220389. {
  220390. fputs (text.toUTF8(), stderr);
  220391. fputs ("\n", stderr);
  220392. }
  220393. void Logger::outputDebugPrintf (const tchar* format, ...) throw()
  220394. {
  220395. String text;
  220396. va_list args;
  220397. va_start (args, format);
  220398. text.vprintf (format, args);
  220399. outputDebugString (text);
  220400. }
  220401. bool JUCE_CALLTYPE juce_isRunningUnderDebugger() throw()
  220402. {
  220403. static char testResult = 0;
  220404. if (testResult == 0)
  220405. {
  220406. struct kinfo_proc info;
  220407. int m[] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, getpid() };
  220408. size_t sz = sizeof (info);
  220409. sysctl (m, 4, &info, &sz, 0, 0);
  220410. testResult = ((info.kp_proc.p_flag & P_TRACED) != 0) ? 1 : -1;
  220411. }
  220412. return testResult > 0;
  220413. }
  220414. bool JUCE_CALLTYPE Process::isRunningUnderDebugger() throw()
  220415. {
  220416. return juce_isRunningUnderDebugger();
  220417. }
  220418. #endif
  220419. /********* End of inlined file: juce_mac_Debugging.mm *********/
  220420. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  220421. /********* Start of inlined file: juce_mac_NSViewComponentPeer.mm *********/
  220422. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  220423. // compiled on its own).
  220424. #ifdef JUCE_INCLUDED_FILE
  220425. class NSViewComponentPeer;
  220426. END_JUCE_NAMESPACE
  220427. #define JuceNSView MakeObjCClassName(JuceNSView)
  220428. @interface JuceNSView : NSView
  220429. {
  220430. @public
  220431. NSViewComponentPeer* owner;
  220432. NSNotificationCenter* notificationCenter;
  220433. }
  220434. - (JuceNSView*) initWithOwner: (NSViewComponentPeer*) owner withFrame: (NSRect) frame;
  220435. - (void) dealloc;
  220436. - (BOOL) isOpaque;
  220437. - (void) drawRect: (NSRect) r;
  220438. - (void) mouseDown: (NSEvent*) ev;
  220439. - (void) asyncMouseDown: (NSEvent*) ev;
  220440. - (void) mouseUp: (NSEvent*) ev;
  220441. - (void) asyncMouseUp: (NSEvent*) ev;
  220442. - (void) mouseDragged: (NSEvent*) ev;
  220443. - (void) mouseMoved: (NSEvent*) ev;
  220444. - (void) mouseEntered: (NSEvent*) ev;
  220445. - (void) mouseExited: (NSEvent*) ev;
  220446. - (void) rightMouseDown: (NSEvent*) ev;
  220447. - (void) rightMouseDragged: (NSEvent*) ev;
  220448. - (void) rightMouseUp: (NSEvent*) ev;
  220449. - (void) otherMouseDown: (NSEvent*) ev;
  220450. - (void) otherMouseDragged: (NSEvent*) ev;
  220451. - (void) otherMouseUp: (NSEvent*) ev;
  220452. - (void) scrollWheel: (NSEvent*) ev;
  220453. - (BOOL) acceptsFirstMouse: (NSEvent*) ev;
  220454. - (void) frameChanged: (NSNotification*) n;
  220455. - (void) keyDown: (NSEvent*) ev;
  220456. - (void) keyUp: (NSEvent*) ev;
  220457. - (void) flagsChanged: (NSEvent*) ev;
  220458. #if MACOS_10_4_OR_EARLIER
  220459. - (BOOL) performKeyEquivalent: (NSEvent*) ev;
  220460. #endif
  220461. - (BOOL) becomeFirstResponder;
  220462. - (BOOL) resignFirstResponder;
  220463. - (BOOL) acceptsFirstResponder;
  220464. - (NSArray*) getSupportedDragTypes;
  220465. - (BOOL) sendDragCallback: (int) type sender: (id <NSDraggingInfo>) sender;
  220466. - (NSDragOperation) draggingEntered: (id <NSDraggingInfo>) sender;
  220467. - (NSDragOperation) draggingUpdated: (id <NSDraggingInfo>) sender;
  220468. - (void) draggingEnded: (id <NSDraggingInfo>) sender;
  220469. - (void) draggingExited: (id <NSDraggingInfo>) sender;
  220470. - (BOOL) prepareForDragOperation: (id <NSDraggingInfo>) sender;
  220471. - (BOOL) performDragOperation: (id <NSDraggingInfo>) sender;
  220472. - (void) concludeDragOperation: (id <NSDraggingInfo>) sender;
  220473. @end
  220474. #define JuceNSWindow MakeObjCClassName(JuceNSWindow)
  220475. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  220476. @interface JuceNSWindow : NSWindow <NSWindowDelegate>
  220477. #else
  220478. @interface JuceNSWindow : NSWindow
  220479. #endif
  220480. {
  220481. @private
  220482. NSViewComponentPeer* owner;
  220483. bool isZooming;
  220484. }
  220485. - (void) setOwner: (NSViewComponentPeer*) owner;
  220486. - (BOOL) canBecomeKeyWindow;
  220487. - (void) becomeKeyWindow;
  220488. - (BOOL) windowShouldClose: (id) window;
  220489. - (NSRect) constrainFrameRect: (NSRect) frameRect toScreen: (NSScreen*) screen;
  220490. - (NSSize) windowWillResize: (NSWindow*) window toSize: (NSSize) proposedFrameSize;
  220491. - (void) zoom: (id) sender;
  220492. @end
  220493. BEGIN_JUCE_NAMESPACE
  220494. class NSViewComponentPeer : public ComponentPeer
  220495. {
  220496. public:
  220497. NSViewComponentPeer (Component* const component,
  220498. const int windowStyleFlags,
  220499. NSView* viewToAttachTo);
  220500. ~NSViewComponentPeer();
  220501. void* getNativeHandle() const;
  220502. void setVisible (bool shouldBeVisible);
  220503. void setTitle (const String& title);
  220504. void setPosition (int x, int y);
  220505. void setSize (int w, int h);
  220506. void setBounds (int x, int y, int w, int h, const bool isNowFullScreen);
  220507. void getBounds (int& x, int& y, int& w, int& h, const bool global) const;
  220508. void getBounds (int& x, int& y, int& w, int& h) const;
  220509. int getScreenX() const;
  220510. int getScreenY() const;
  220511. void relativePositionToGlobal (int& x, int& y);
  220512. void globalPositionToRelative (int& x, int& y);
  220513. void setMinimised (bool shouldBeMinimised);
  220514. bool isMinimised() const;
  220515. void setFullScreen (bool shouldBeFullScreen);
  220516. bool isFullScreen() const;
  220517. bool contains (int x, int y, bool trueIfInAChildWindow) const;
  220518. const BorderSize getFrameSize() const;
  220519. bool setAlwaysOnTop (bool alwaysOnTop);
  220520. void toFront (bool makeActiveWindow);
  220521. void toBehind (ComponentPeer* other);
  220522. void setIcon (const Image& newIcon);
  220523. /* When you use multiple DLLs which share similarly-named obj-c classes - like
  220524. for example having more than one juce plugin loaded into a host, then when a
  220525. method is called, the actual code that runs might actually be in a different module
  220526. than the one you expect... So any calls to library functions or statics that are
  220527. made inside obj-c methods will probably end up getting executed in a different DLL's
  220528. memory space. Not a great thing to happen - this obviously leads to bizarre crashes.
  220529. To work around this insanity, I'm only allowing obj-c methods to make calls to
  220530. virtual methods of an object that's known to live inside the right module's space.
  220531. */
  220532. virtual void redirectMouseDown (NSEvent* ev);
  220533. virtual void redirectMouseUp (NSEvent* ev);
  220534. virtual void redirectMouseDrag (NSEvent* ev);
  220535. virtual void redirectMouseMove (NSEvent* ev);
  220536. virtual void redirectMouseEnter (NSEvent* ev);
  220537. virtual void redirectMouseExit (NSEvent* ev);
  220538. virtual void redirectMouseWheel (NSEvent* ev);
  220539. bool handleKeyEvent (NSEvent* ev, bool isKeyDown);
  220540. virtual bool redirectKeyDown (NSEvent* ev);
  220541. virtual bool redirectKeyUp (NSEvent* ev);
  220542. virtual void redirectModKeyChange (NSEvent* ev);
  220543. #if MACOS_10_4_OR_EARLIER
  220544. virtual bool redirectPerformKeyEquivalent (NSEvent* ev);
  220545. #endif
  220546. virtual BOOL sendDragCallback (int type, id <NSDraggingInfo> sender);
  220547. virtual bool isOpaque();
  220548. virtual void drawRect (NSRect r);
  220549. virtual bool canBecomeKeyWindow();
  220550. virtual bool windowShouldClose();
  220551. virtual void redirectMovedOrResized();
  220552. virtual NSRect constrainRect (NSRect r);
  220553. static void showArrowCursorIfNeeded();
  220554. virtual void viewFocusGain();
  220555. virtual void viewFocusLoss();
  220556. bool isFocused() const;
  220557. void grabFocus();
  220558. void textInputRequired (int x, int y);
  220559. void repaint (int x, int y, int w, int h);
  220560. void performAnyPendingRepaintsNow();
  220561. juce_UseDebuggingNewOperator
  220562. NSWindow* window;
  220563. JuceNSView* view;
  220564. bool isSharedWindow, fullScreen;
  220565. };
  220566. END_JUCE_NAMESPACE
  220567. @implementation JuceNSView
  220568. - (JuceNSView*) initWithOwner: (NSViewComponentPeer*) owner_
  220569. withFrame: (NSRect) frame
  220570. {
  220571. [super initWithFrame: frame];
  220572. owner = owner_;
  220573. notificationCenter = [NSNotificationCenter defaultCenter];
  220574. [notificationCenter addObserver: self
  220575. selector: @selector (frameChanged:)
  220576. name: NSViewFrameDidChangeNotification
  220577. object: self];
  220578. if (! owner_->isSharedWindow)
  220579. {
  220580. [notificationCenter addObserver: self
  220581. selector: @selector (frameChanged:)
  220582. name: NSWindowDidMoveNotification
  220583. object: owner_->window];
  220584. }
  220585. [self registerForDraggedTypes: [self getSupportedDragTypes]];
  220586. return self;
  220587. }
  220588. - (void) dealloc
  220589. {
  220590. [notificationCenter removeObserver: self];
  220591. [super dealloc];
  220592. }
  220593. - (void) drawRect: (NSRect) r
  220594. {
  220595. if (owner != 0)
  220596. owner->drawRect (r);
  220597. }
  220598. - (BOOL) isOpaque
  220599. {
  220600. return owner == 0 || owner->isOpaque();
  220601. }
  220602. - (void) mouseDown: (NSEvent*) ev
  220603. {
  220604. // In some host situations, the host will stop modal loops from working
  220605. // correctly if they're called from a mouse event, so we'll trigger
  220606. // the event asynchronously..
  220607. if (JUCEApplication::getInstance() == 0)
  220608. [self performSelectorOnMainThread: @selector (asyncMouseDown:)
  220609. withObject: ev
  220610. waitUntilDone: NO];
  220611. else
  220612. [self asyncMouseDown: ev];
  220613. }
  220614. - (void) asyncMouseDown: (NSEvent*) ev
  220615. {
  220616. if (owner != 0)
  220617. owner->redirectMouseDown (ev);
  220618. }
  220619. - (void) mouseUp: (NSEvent*) ev
  220620. {
  220621. // In some host situations, the host will stop modal loops from working
  220622. // correctly if they're called from a mouse event, so we'll trigger
  220623. // the event asynchronously..
  220624. if (JUCEApplication::getInstance() == 0)
  220625. [self performSelectorOnMainThread: @selector (asyncMouseUp:)
  220626. withObject: ev
  220627. waitUntilDone: NO];
  220628. else
  220629. [self asyncMouseUp: ev];
  220630. }
  220631. - (void) asyncMouseUp: (NSEvent*) ev
  220632. {
  220633. if (owner != 0)
  220634. owner->redirectMouseUp (ev);
  220635. }
  220636. - (void) mouseDragged: (NSEvent*) ev
  220637. {
  220638. if (owner != 0)
  220639. owner->redirectMouseDrag (ev);
  220640. }
  220641. - (void) mouseMoved: (NSEvent*) ev
  220642. {
  220643. if (owner != 0)
  220644. owner->redirectMouseMove (ev);
  220645. }
  220646. - (void) mouseEntered: (NSEvent*) ev
  220647. {
  220648. if (owner != 0)
  220649. owner->redirectMouseEnter (ev);
  220650. }
  220651. - (void) mouseExited: (NSEvent*) ev
  220652. {
  220653. if (owner != 0)
  220654. owner->redirectMouseExit (ev);
  220655. }
  220656. - (void) rightMouseDown: (NSEvent*) ev
  220657. {
  220658. [self mouseDown: ev];
  220659. }
  220660. - (void) rightMouseDragged: (NSEvent*) ev
  220661. {
  220662. [self mouseDragged: ev];
  220663. }
  220664. - (void) rightMouseUp: (NSEvent*) ev
  220665. {
  220666. [self mouseUp: ev];
  220667. }
  220668. - (void) otherMouseDown: (NSEvent*) ev
  220669. {
  220670. [self mouseDown: ev];
  220671. }
  220672. - (void) otherMouseDragged: (NSEvent*) ev
  220673. {
  220674. [self mouseDragged: ev];
  220675. }
  220676. - (void) otherMouseUp: (NSEvent*) ev
  220677. {
  220678. [self mouseUp: ev];
  220679. }
  220680. - (void) scrollWheel: (NSEvent*) ev
  220681. {
  220682. if (owner != 0)
  220683. owner->redirectMouseWheel (ev);
  220684. }
  220685. - (BOOL) acceptsFirstMouse: (NSEvent*) ev
  220686. {
  220687. return YES;
  220688. }
  220689. - (void) frameChanged: (NSNotification*) n
  220690. {
  220691. if (owner != 0)
  220692. owner->redirectMovedOrResized();
  220693. }
  220694. - (void) keyDown: (NSEvent*) ev
  220695. {
  220696. if (owner == 0 || ! owner->redirectKeyDown (ev))
  220697. [super keyDown: ev];
  220698. }
  220699. - (void) keyUp: (NSEvent*) ev
  220700. {
  220701. if (owner == 0 || ! owner->redirectKeyUp (ev))
  220702. [super keyUp: ev];
  220703. }
  220704. - (void) flagsChanged: (NSEvent*) ev
  220705. {
  220706. if (owner != 0)
  220707. owner->redirectModKeyChange (ev);
  220708. }
  220709. #if MACOS_10_4_OR_EARLIER
  220710. - (BOOL) performKeyEquivalent: (NSEvent*) ev
  220711. {
  220712. if (owner != 0 && owner->redirectPerformKeyEquivalent (ev))
  220713. return true;
  220714. return [super performKeyEquivalent: ev];
  220715. }
  220716. #endif
  220717. - (BOOL) becomeFirstResponder
  220718. {
  220719. if (owner != 0)
  220720. owner->viewFocusGain();
  220721. return true;
  220722. }
  220723. - (BOOL) resignFirstResponder
  220724. {
  220725. if (owner != 0)
  220726. owner->viewFocusLoss();
  220727. return true;
  220728. }
  220729. - (BOOL) acceptsFirstResponder
  220730. {
  220731. return owner != 0 && owner->canBecomeKeyWindow();
  220732. }
  220733. - (NSArray*) getSupportedDragTypes
  220734. {
  220735. return [NSArray arrayWithObjects: NSFilenamesPboardType, /*NSFilesPromisePboardType, NSStringPboardType,*/ nil];
  220736. }
  220737. - (BOOL) sendDragCallback: (int) type sender: (id <NSDraggingInfo>) sender
  220738. {
  220739. return owner != 0 && owner->sendDragCallback (type, sender);
  220740. }
  220741. - (NSDragOperation) draggingEntered: (id <NSDraggingInfo>) sender
  220742. {
  220743. if ([self sendDragCallback: 0 sender: sender])
  220744. return NSDragOperationCopy | NSDragOperationMove | NSDragOperationGeneric;
  220745. else
  220746. return NSDragOperationNone;
  220747. }
  220748. - (NSDragOperation) draggingUpdated: (id <NSDraggingInfo>) sender
  220749. {
  220750. if ([self sendDragCallback: 0 sender: sender])
  220751. return NSDragOperationCopy | NSDragOperationMove | NSDragOperationGeneric;
  220752. else
  220753. return NSDragOperationNone;
  220754. }
  220755. - (void) draggingEnded: (id <NSDraggingInfo>) sender
  220756. {
  220757. [self sendDragCallback: 1 sender: sender];
  220758. }
  220759. - (void) draggingExited: (id <NSDraggingInfo>) sender
  220760. {
  220761. [self sendDragCallback: 1 sender: sender];
  220762. }
  220763. - (BOOL) prepareForDragOperation: (id <NSDraggingInfo>) sender
  220764. {
  220765. return YES;
  220766. }
  220767. - (BOOL) performDragOperation: (id <NSDraggingInfo>) sender
  220768. {
  220769. return [self sendDragCallback: 2 sender: sender];
  220770. }
  220771. - (void) concludeDragOperation: (id <NSDraggingInfo>) sender
  220772. {
  220773. }
  220774. @end
  220775. @implementation JuceNSWindow
  220776. - (void) setOwner: (NSViewComponentPeer*) owner_
  220777. {
  220778. owner = owner_;
  220779. isZooming = false;
  220780. }
  220781. - (BOOL) canBecomeKeyWindow
  220782. {
  220783. return owner != 0 && owner->canBecomeKeyWindow();
  220784. }
  220785. - (void) becomeKeyWindow
  220786. {
  220787. [super becomeKeyWindow];
  220788. if (owner != 0)
  220789. owner->grabFocus();
  220790. }
  220791. - (BOOL) windowShouldClose: (id) window
  220792. {
  220793. return owner == 0 || owner->windowShouldClose();
  220794. }
  220795. - (NSRect) constrainFrameRect: (NSRect) frameRect toScreen: (NSScreen*) screen
  220796. {
  220797. if (owner != 0)
  220798. frameRect = owner->constrainRect (frameRect);
  220799. return frameRect;
  220800. }
  220801. - (NSSize) windowWillResize: (NSWindow*) window toSize: (NSSize) proposedFrameSize
  220802. {
  220803. if (isZooming)
  220804. return proposedFrameSize;
  220805. NSRect frameRect = [self frame];
  220806. frameRect.origin.y -= proposedFrameSize.height - frameRect.size.height;
  220807. frameRect.size = proposedFrameSize;
  220808. if (owner != 0)
  220809. frameRect = owner->constrainRect (frameRect);
  220810. return frameRect.size;
  220811. }
  220812. - (void) zoom: (id) sender
  220813. {
  220814. isZooming = true;
  220815. [super zoom: sender];
  220816. isZooming = false;
  220817. }
  220818. - (void) windowWillMove: (NSNotification*) notification
  220819. {
  220820. if (juce::Component::getCurrentlyModalComponent() != 0
  220821. && owner->getComponent()->isCurrentlyBlockedByAnotherModalComponent()
  220822. && (owner->getStyleFlags() & juce::ComponentPeer::windowHasTitleBar) != 0)
  220823. juce::Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  220824. }
  220825. @end
  220826. BEGIN_JUCE_NAMESPACE
  220827. class JuceNSImage
  220828. {
  220829. public:
  220830. JuceNSImage (const int width, const int height, const bool hasAlpha)
  220831. : juceImage (hasAlpha ? Image::ARGB : Image::RGB,
  220832. width, height, hasAlpha)
  220833. {
  220834. lineStride = 0;
  220835. pixelStride = 0;
  220836. imageData = juceImage.lockPixelDataReadWrite (0, 0, width, height,
  220837. lineStride, pixelStride);
  220838. imageRep = [[NSBitmapImageRep alloc]
  220839. initWithBitmapDataPlanes: &imageData
  220840. pixelsWide: width
  220841. pixelsHigh: height
  220842. bitsPerSample: 8
  220843. samplesPerPixel: pixelStride
  220844. hasAlpha: hasAlpha
  220845. isPlanar: NO
  220846. colorSpaceName: NSCalibratedRGBColorSpace
  220847. bitmapFormat: /*NSAlphaFirstBitmapFormat*/ (NSBitmapFormat) 0
  220848. bytesPerRow: lineStride
  220849. bitsPerPixel: 8 * pixelStride ];
  220850. juceImage.releasePixelDataReadWrite (imageData);
  220851. }
  220852. ~JuceNSImage()
  220853. {
  220854. [imageRep release];
  220855. }
  220856. Image& getJuceImage() throw() { return juceImage; }
  220857. void draw (const float x, const float y,
  220858. const RectangleList& clip,
  220859. const int originX, const int originY) const
  220860. {
  220861. // Our data is BGRA and the damned image rep only takes RGBA, so
  220862. // we need to byte-swap the active areas if there's an alpha channel...
  220863. if (juceImage.hasAlphaChannel())
  220864. {
  220865. RectangleList::Iterator iter (clip);
  220866. while (iter.next())
  220867. {
  220868. const Rectangle* const r = iter.getRectangle();
  220869. swapRGBOrder (r->getX() + originX,
  220870. r->getY() + originY,
  220871. r->getWidth(),
  220872. r->getHeight());
  220873. }
  220874. }
  220875. NSPoint p;
  220876. p.x = x;
  220877. p.y = y;
  220878. [imageRep drawAtPoint: p];
  220879. }
  220880. void drawNSImage (NSImage* imageToDraw)
  220881. {
  220882. const ScopedAutoReleasePool pool;
  220883. [NSGraphicsContext saveGraphicsState];
  220884. [NSGraphicsContext setCurrentContext:
  220885. [NSGraphicsContext graphicsContextWithBitmapImageRep: imageRep]];
  220886. [imageToDraw drawAtPoint: NSZeroPoint
  220887. fromRect: NSMakeRect (0, 0, [imageToDraw size].width, [imageToDraw size].height)
  220888. operation: NSCompositeSourceOver
  220889. fraction: 1.0f];
  220890. [[NSGraphicsContext currentContext] flushGraphics];
  220891. [NSGraphicsContext restoreGraphicsState];
  220892. if (juceImage.hasAlphaChannel())
  220893. swapRGBOrder (0, 0, juceImage.getWidth(), juceImage.getHeight());
  220894. }
  220895. private:
  220896. Image juceImage;
  220897. NSBitmapImageRep* imageRep;
  220898. uint8* imageData;
  220899. int pixelStride, lineStride;
  220900. void swapRGBOrder (const int x, const int y, const int w, int h) const
  220901. {
  220902. #if JUCE_BIG_ENDIAN
  220903. jassert (pixelStride == 4);
  220904. #endif
  220905. jassert (Rectangle (0, 0, juceImage.getWidth(), juceImage.getHeight())
  220906. .contains (Rectangle (x, y, w, h)));
  220907. uint8* start = imageData + x * pixelStride + y * lineStride;
  220908. while (--h >= 0)
  220909. {
  220910. uint8* p = start;
  220911. start += lineStride;
  220912. for (int i = w; --i >= 0;)
  220913. {
  220914. #if JUCE_BIG_ENDIAN
  220915. const uint8 oldp3 = p[3];
  220916. const uint8 oldp1 = p[1];
  220917. p[3] = p[0];
  220918. p[0] = oldp1;
  220919. p[1] = p[2];
  220920. p[2] = oldp3;
  220921. #else
  220922. const uint8 oldp0 = p[0];
  220923. p[0] = p[2];
  220924. p[2] = oldp0;
  220925. #endif
  220926. p += pixelStride;
  220927. }
  220928. }
  220929. }
  220930. };
  220931. static ComponentPeer* currentlyFocusedPeer = 0;
  220932. static VoidArray keysCurrentlyDown;
  220933. bool KeyPress::isKeyCurrentlyDown (const int keyCode) throw()
  220934. {
  220935. if (keysCurrentlyDown.contains ((void*) keyCode))
  220936. return true;
  220937. if (keyCode >= 'A' && keyCode <= 'Z'
  220938. && keysCurrentlyDown.contains ((void*) (int) CharacterFunctions::toLowerCase ((tchar) keyCode)))
  220939. return true;
  220940. if (keyCode >= 'a' && keyCode <= 'z'
  220941. && keysCurrentlyDown.contains ((void*) (int) CharacterFunctions::toUpperCase ((tchar) keyCode)))
  220942. return true;
  220943. return false;
  220944. }
  220945. static int getKeyCodeFromEvent (NSEvent* ev)
  220946. {
  220947. const String unmodified (nsStringToJuce ([ev charactersIgnoringModifiers]));
  220948. int keyCode = unmodified[0];
  220949. if (keyCode == 0x19) // (backwards-tab)
  220950. keyCode = '\t';
  220951. else if (keyCode == 0x03) // (enter)
  220952. keyCode = '\r';
  220953. return keyCode;
  220954. }
  220955. static int currentModifiers = 0;
  220956. static void updateModifiers (NSEvent* e)
  220957. {
  220958. int m = currentModifiers & ~(ModifierKeys::shiftModifier | ModifierKeys::ctrlModifier
  220959. | ModifierKeys::altModifier | ModifierKeys::commandModifier);
  220960. if (([e modifierFlags] & NSShiftKeyMask) != 0)
  220961. m |= ModifierKeys::shiftModifier;
  220962. if (([e modifierFlags] & NSControlKeyMask) != 0)
  220963. m |= ModifierKeys::ctrlModifier;
  220964. if (([e modifierFlags] & NSAlternateKeyMask) != 0)
  220965. m |= ModifierKeys::altModifier;
  220966. if (([e modifierFlags] & NSCommandKeyMask) != 0)
  220967. m |= ModifierKeys::commandModifier;
  220968. currentModifiers = m;
  220969. }
  220970. static void updateKeysDown (NSEvent* ev, bool isKeyDown)
  220971. {
  220972. updateModifiers (ev);
  220973. int keyCode = getKeyCodeFromEvent (ev);
  220974. if (keyCode != 0)
  220975. {
  220976. if (isKeyDown)
  220977. keysCurrentlyDown.addIfNotAlreadyThere ((void*) keyCode);
  220978. else
  220979. keysCurrentlyDown.removeValue ((void*) keyCode);
  220980. }
  220981. }
  220982. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  220983. {
  220984. return ModifierKeys (currentModifiers);
  220985. }
  220986. void ModifierKeys::updateCurrentModifiers() throw()
  220987. {
  220988. currentModifierFlags = currentModifiers;
  220989. }
  220990. static int64 getMouseTime (NSEvent* e) { return (int64) [e timestamp] * 1000.0; }
  220991. static void getMousePos (NSEvent* e, NSView* view, int& x, int& y)
  220992. {
  220993. NSPoint p = [view convertPoint: [e locationInWindow] fromView: nil];
  220994. x = roundFloatToInt (p.x);
  220995. y = roundFloatToInt ([view frame].size.height - p.y);
  220996. }
  220997. static int getModifierForButtonNumber (const int num) throw()
  220998. {
  220999. return num == 0 ? ModifierKeys::leftButtonModifier
  221000. : (num == 1 ? ModifierKeys::rightButtonModifier
  221001. : (num == 2 ? ModifierKeys::middleButtonModifier : 0));
  221002. }
  221003. NSViewComponentPeer::NSViewComponentPeer (Component* const component,
  221004. const int windowStyleFlags,
  221005. NSView* viewToAttachTo)
  221006. : ComponentPeer (component, windowStyleFlags),
  221007. window (0),
  221008. view (0)
  221009. {
  221010. NSRect r;
  221011. r.origin.x = 0;
  221012. r.origin.y = 0;
  221013. r.size.width = (float) component->getWidth();
  221014. r.size.height = (float) component->getHeight();
  221015. view = [[JuceNSView alloc] initWithOwner: this withFrame: r];
  221016. [view setPostsFrameChangedNotifications: YES];
  221017. if (viewToAttachTo != 0)
  221018. {
  221019. window = [viewToAttachTo window];
  221020. [viewToAttachTo addSubview: view];
  221021. isSharedWindow = true;
  221022. setVisible (component->isVisible());
  221023. }
  221024. else
  221025. {
  221026. isSharedWindow = false;
  221027. r.origin.x = (float) component->getX();
  221028. r.origin.y = (float) component->getY();
  221029. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - (r.origin.y + r.size.height);
  221030. unsigned int style = 0;
  221031. if ((windowStyleFlags & windowHasTitleBar) == 0)
  221032. style = NSBorderlessWindowMask;
  221033. else
  221034. style = NSTitledWindowMask;
  221035. if ((windowStyleFlags & windowHasMinimiseButton) != 0)
  221036. style |= NSMiniaturizableWindowMask;
  221037. if ((windowStyleFlags & windowHasCloseButton) != 0)
  221038. style |= NSClosableWindowMask;
  221039. if ((windowStyleFlags & windowIsResizable) != 0)
  221040. style |= NSResizableWindowMask;
  221041. window = [[JuceNSWindow alloc] initWithContentRect: r
  221042. styleMask: style
  221043. backing: NSBackingStoreBuffered
  221044. defer: YES];
  221045. [((JuceNSWindow*) window) setOwner: this];
  221046. [window orderOut: nil];
  221047. [window setDelegate: (JuceNSWindow*) window];
  221048. [window setOpaque: component->isOpaque()];
  221049. [window setHasShadow: ((windowStyleFlags & windowHasDropShadow) != 0)];
  221050. if (component->isAlwaysOnTop())
  221051. [window setLevel: NSFloatingWindowLevel];
  221052. [window setContentView: view];
  221053. [window setAutodisplay: YES];
  221054. [window setAcceptsMouseMovedEvents: YES];
  221055. // We'll both retain and also release this on closing because plugin hosts can unexpectedly
  221056. // close the window for us, and also tend to get cause trouble if setReleasedWhenClosed is NO.
  221057. [window setReleasedWhenClosed: YES];
  221058. [window retain];
  221059. [window setExcludedFromWindowsMenu: (windowStyleFlags & windowIsTemporary) != 0];
  221060. [window setIgnoresMouseEvents: (windowStyleFlags & windowIgnoresMouseClicks) != 0];
  221061. }
  221062. setTitle (component->getName());
  221063. }
  221064. NSViewComponentPeer::~NSViewComponentPeer()
  221065. {
  221066. view->owner = 0;
  221067. [view removeFromSuperview];
  221068. [view release];
  221069. if (! isSharedWindow)
  221070. {
  221071. [((JuceNSWindow*) window) setOwner: 0];
  221072. [window close];
  221073. [window release];
  221074. }
  221075. }
  221076. void* NSViewComponentPeer::getNativeHandle() const
  221077. {
  221078. return view;
  221079. }
  221080. void NSViewComponentPeer::setVisible (bool shouldBeVisible)
  221081. {
  221082. if (isSharedWindow)
  221083. {
  221084. [view setHidden: ! shouldBeVisible];
  221085. }
  221086. else
  221087. {
  221088. if (shouldBeVisible)
  221089. [window orderFront: nil];
  221090. else
  221091. [window orderOut: nil];
  221092. }
  221093. }
  221094. void NSViewComponentPeer::setTitle (const String& title)
  221095. {
  221096. const ScopedAutoReleasePool pool;
  221097. if (! isSharedWindow)
  221098. [window setTitle: juceStringToNS (title)];
  221099. }
  221100. void NSViewComponentPeer::setPosition (int x, int y)
  221101. {
  221102. setBounds (x, y, component->getWidth(), component->getHeight(), false);
  221103. }
  221104. void NSViewComponentPeer::setSize (int w, int h)
  221105. {
  221106. setBounds (component->getX(), component->getY(), w, h, false);
  221107. }
  221108. void NSViewComponentPeer::setBounds (int x, int y, int w, int h, const bool isNowFullScreen)
  221109. {
  221110. fullScreen = isNowFullScreen;
  221111. w = jmax (0, w);
  221112. h = jmax (0, h);
  221113. NSRect r;
  221114. r.origin.x = (float) x;
  221115. r.origin.y = (float) y;
  221116. r.size.width = (float) w;
  221117. r.size.height = (float) h;
  221118. if (isSharedWindow)
  221119. {
  221120. r.origin.y = [[view superview] frame].size.height - (r.origin.y + r.size.height);
  221121. if ([view frame].size.width != r.size.width
  221122. || [view frame].size.height != r.size.height)
  221123. [view setNeedsDisplay: true];
  221124. [view setFrame: r];
  221125. }
  221126. else
  221127. {
  221128. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - (r.origin.y + r.size.height);
  221129. [window setFrame: [window frameRectForContentRect: r]
  221130. display: true];
  221131. }
  221132. }
  221133. void NSViewComponentPeer::getBounds (int& x, int& y, int& w, int& h, const bool global) const
  221134. {
  221135. NSRect r = [view frame];
  221136. if (global && [view window] != 0)
  221137. {
  221138. r = [view convertRect: r toView: nil];
  221139. NSRect wr = [[view window] frame];
  221140. r.origin.x += wr.origin.x;
  221141. r.origin.y += wr.origin.y;
  221142. y = (int) ([[[NSScreen screens] objectAtIndex:0] frame].size.height - r.origin.y - r.size.height);
  221143. }
  221144. else
  221145. {
  221146. y = (int) ([[view superview] frame].size.height - r.origin.y - r.size.height);
  221147. }
  221148. x = (int) r.origin.x;
  221149. w = (int) r.size.width;
  221150. h = (int) r.size.height;
  221151. }
  221152. void NSViewComponentPeer::getBounds (int& x, int& y, int& w, int& h) const
  221153. {
  221154. getBounds (x, y, w, h, ! isSharedWindow);
  221155. }
  221156. int NSViewComponentPeer::getScreenX() const
  221157. {
  221158. int x, y, w, h;
  221159. getBounds (x, y, w, h, true);
  221160. return x;
  221161. }
  221162. int NSViewComponentPeer::getScreenY() const
  221163. {
  221164. int x, y, w, h;
  221165. getBounds (x, y, w, h, true);
  221166. return y;
  221167. }
  221168. void NSViewComponentPeer::relativePositionToGlobal (int& x, int& y)
  221169. {
  221170. int wx, wy, ww, wh;
  221171. getBounds (wx, wy, ww, wh, true);
  221172. x += wx;
  221173. y += wy;
  221174. }
  221175. void NSViewComponentPeer::globalPositionToRelative (int& x, int& y)
  221176. {
  221177. int wx, wy, ww, wh;
  221178. getBounds (wx, wy, ww, wh, true);
  221179. x -= wx;
  221180. y -= wy;
  221181. }
  221182. NSRect NSViewComponentPeer::constrainRect (NSRect r)
  221183. {
  221184. if (constrainer != 0)
  221185. {
  221186. NSRect current = [window frame];
  221187. current.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - current.origin.y - current.size.height;
  221188. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - r.origin.y - r.size.height;
  221189. int x = (int) r.origin.x;
  221190. int y = (int) r.origin.y;
  221191. int w = (int) r.size.width;
  221192. int h = (int) r.size.height;
  221193. Rectangle original ((int) current.origin.x, (int) current.origin.y,
  221194. (int) current.size.width, (int) current.size.height);
  221195. constrainer->checkBounds (x, y, w, h,
  221196. original,
  221197. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  221198. y != original.getY() && y + h == original.getBottom(),
  221199. x != original.getX() && x + w == original.getRight(),
  221200. y == original.getY() && y + h != original.getBottom(),
  221201. x == original.getX() && x + w != original.getRight());
  221202. r.origin.x = x;
  221203. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - r.size.height - y;
  221204. r.size.width = w;
  221205. r.size.height = h;
  221206. }
  221207. return r;
  221208. }
  221209. void NSViewComponentPeer::setMinimised (bool shouldBeMinimised)
  221210. {
  221211. if (! isSharedWindow)
  221212. {
  221213. if (shouldBeMinimised)
  221214. [window miniaturize: nil];
  221215. else
  221216. [window deminiaturize: nil];
  221217. }
  221218. }
  221219. bool NSViewComponentPeer::isMinimised() const
  221220. {
  221221. return window != 0 && [window isMiniaturized];
  221222. }
  221223. void NSViewComponentPeer::setFullScreen (bool shouldBeFullScreen)
  221224. {
  221225. if (! isSharedWindow)
  221226. {
  221227. Rectangle r (lastNonFullscreenBounds);
  221228. setMinimised (false);
  221229. if (fullScreen != shouldBeFullScreen)
  221230. {
  221231. if (shouldBeFullScreen)
  221232. r = Desktop::getInstance().getMainMonitorArea();
  221233. // (can't call the component's setBounds method because that'll reset our fullscreen flag)
  221234. if (r != getComponent()->getBounds() && ! r.isEmpty())
  221235. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight(), shouldBeFullScreen);
  221236. }
  221237. }
  221238. }
  221239. bool NSViewComponentPeer::isFullScreen() const
  221240. {
  221241. return fullScreen;
  221242. }
  221243. bool NSViewComponentPeer::contains (int x, int y, bool trueIfInAChildWindow) const
  221244. {
  221245. if (((unsigned int) x) >= (unsigned int) component->getWidth()
  221246. || ((unsigned int) y) >= (unsigned int) component->getHeight())
  221247. return false;
  221248. NSPoint p;
  221249. p.x = (float) x;
  221250. p.y = (float) y;
  221251. NSView* v = [view hitTest: p];
  221252. if (trueIfInAChildWindow)
  221253. return v != nil;
  221254. return v == view;
  221255. }
  221256. const BorderSize NSViewComponentPeer::getFrameSize() const
  221257. {
  221258. BorderSize b;
  221259. if (! isSharedWindow)
  221260. {
  221261. NSRect v = [view convertRect: [view frame] toView: nil];
  221262. NSRect w = [window frame];
  221263. b.setTop ((int) (w.size.height - (v.origin.y + v.size.height)));
  221264. b.setBottom ((int) v.origin.y);
  221265. b.setLeft ((int) v.origin.x);
  221266. b.setRight ((int) (w.size.width - (v.origin.x + v.size.width)));
  221267. }
  221268. return b;
  221269. }
  221270. bool NSViewComponentPeer::setAlwaysOnTop (bool alwaysOnTop)
  221271. {
  221272. if (! isSharedWindow)
  221273. {
  221274. [window setLevel: alwaysOnTop ? NSFloatingWindowLevel
  221275. : NSNormalWindowLevel];
  221276. }
  221277. return true;
  221278. }
  221279. void NSViewComponentPeer::toFront (bool makeActiveWindow)
  221280. {
  221281. if (isSharedWindow)
  221282. {
  221283. [[view superview] addSubview: view
  221284. positioned: NSWindowAbove
  221285. relativeTo: nil];
  221286. }
  221287. if (window != 0 && component->isVisible())
  221288. {
  221289. if (makeActiveWindow)
  221290. [window makeKeyAndOrderFront: nil];
  221291. else
  221292. [window orderFront: nil];
  221293. }
  221294. }
  221295. void NSViewComponentPeer::toBehind (ComponentPeer* other)
  221296. {
  221297. NSViewComponentPeer* o = (NSViewComponentPeer*) other;
  221298. if (isSharedWindow)
  221299. {
  221300. [[view superview] addSubview: view
  221301. positioned: NSWindowBelow
  221302. relativeTo: o->view];
  221303. }
  221304. else
  221305. {
  221306. [window orderWindow: NSWindowBelow
  221307. relativeTo: o->window != 0 ? [o->window windowNumber]
  221308. : nil ];
  221309. }
  221310. }
  221311. void NSViewComponentPeer::setIcon (const Image& /*newIcon*/)
  221312. {
  221313. // to do..
  221314. }
  221315. void NSViewComponentPeer::viewFocusGain()
  221316. {
  221317. if (currentlyFocusedPeer != this)
  221318. {
  221319. if (ComponentPeer::isValidPeer (currentlyFocusedPeer))
  221320. currentlyFocusedPeer->handleFocusLoss();
  221321. currentlyFocusedPeer = this;
  221322. handleFocusGain();
  221323. }
  221324. }
  221325. void NSViewComponentPeer::viewFocusLoss()
  221326. {
  221327. if (currentlyFocusedPeer == this)
  221328. {
  221329. currentlyFocusedPeer = 0;
  221330. handleFocusLoss();
  221331. }
  221332. }
  221333. void juce_HandleProcessFocusChange()
  221334. {
  221335. keysCurrentlyDown.clear();
  221336. if (NSViewComponentPeer::isValidPeer (currentlyFocusedPeer))
  221337. {
  221338. if (Process::isForegroundProcess())
  221339. {
  221340. currentlyFocusedPeer->handleFocusGain();
  221341. ComponentPeer::bringModalComponentToFront();
  221342. }
  221343. else
  221344. {
  221345. currentlyFocusedPeer->handleFocusLoss();
  221346. // turn kiosk mode off if we lose focus..
  221347. Desktop::getInstance().setKioskModeComponent (0);
  221348. }
  221349. }
  221350. }
  221351. bool NSViewComponentPeer::isFocused() const
  221352. {
  221353. return isSharedWindow ? this == currentlyFocusedPeer
  221354. : (window != 0 && [window isKeyWindow]);
  221355. }
  221356. void NSViewComponentPeer::grabFocus()
  221357. {
  221358. if (window != 0)
  221359. {
  221360. [window makeKeyWindow];
  221361. [window makeFirstResponder: view];
  221362. viewFocusGain();
  221363. }
  221364. }
  221365. void NSViewComponentPeer::textInputRequired (int /*x*/, int /*y*/)
  221366. {
  221367. }
  221368. bool NSViewComponentPeer::handleKeyEvent (NSEvent* ev, bool isKeyDown)
  221369. {
  221370. String unicode (nsStringToJuce ([ev characters]));
  221371. String unmodified (nsStringToJuce ([ev charactersIgnoringModifiers]));
  221372. int keyCode = getKeyCodeFromEvent (ev);
  221373. //DBG ("unicode: " + unicode + " " + String::toHexString ((int) unicode[0]));
  221374. //DBG ("unmodified: " + unmodified + " " + String::toHexString ((int) unmodified[0]));
  221375. if (unicode.isNotEmpty() || keyCode != 0)
  221376. {
  221377. if (isKeyDown)
  221378. {
  221379. bool used = false;
  221380. while (unicode.length() > 0)
  221381. {
  221382. juce_wchar textCharacter = unicode[0];
  221383. unicode = unicode.substring (1);
  221384. if (([ev modifierFlags] & NSCommandKeyMask) != 0)
  221385. textCharacter = 0;
  221386. used = handleKeyUpOrDown (true) || used;
  221387. used = handleKeyPress (keyCode, textCharacter) || used;
  221388. }
  221389. return used;
  221390. }
  221391. else
  221392. {
  221393. if (handleKeyUpOrDown (false))
  221394. return true;
  221395. }
  221396. }
  221397. return false;
  221398. }
  221399. bool NSViewComponentPeer::redirectKeyDown (NSEvent* ev)
  221400. {
  221401. updateKeysDown (ev, true);
  221402. bool used = handleKeyEvent (ev, true);
  221403. if (([ev modifierFlags] & NSCommandKeyMask) != 0)
  221404. {
  221405. // for command keys, the key-up event is thrown away, so simulate one..
  221406. updateKeysDown (ev, false);
  221407. used = (isValidPeer (this) && handleKeyEvent (ev, false)) || used;
  221408. }
  221409. // (If we're running modally, don't allow unused keystrokes to be passed
  221410. // along to other blocked views..)
  221411. if (Component::getCurrentlyModalComponent() != 0)
  221412. used = true;
  221413. return used;
  221414. }
  221415. bool NSViewComponentPeer::redirectKeyUp (NSEvent* ev)
  221416. {
  221417. updateKeysDown (ev, false);
  221418. return handleKeyEvent (ev, false)
  221419. || Component::getCurrentlyModalComponent() != 0;
  221420. }
  221421. void NSViewComponentPeer::redirectModKeyChange (NSEvent* ev)
  221422. {
  221423. updateModifiers (ev);
  221424. handleModifierKeysChange();
  221425. }
  221426. #if MACOS_10_4_OR_EARLIER
  221427. bool NSViewComponentPeer::redirectPerformKeyEquivalent (NSEvent* ev)
  221428. {
  221429. if ([ev type] == NSKeyDown)
  221430. return redirectKeyDown (ev);
  221431. else if ([ev type] == NSKeyUp)
  221432. return redirectKeyUp (ev);
  221433. return false;
  221434. }
  221435. #endif
  221436. void NSViewComponentPeer::redirectMouseDown (NSEvent* ev)
  221437. {
  221438. updateModifiers (ev);
  221439. currentModifiers |= getModifierForButtonNumber ([ev buttonNumber]);
  221440. int x, y;
  221441. getMousePos (ev, view, x, y);
  221442. handleMouseDown (x, y, getMouseTime (ev));
  221443. }
  221444. void NSViewComponentPeer::redirectMouseUp (NSEvent* ev)
  221445. {
  221446. const int oldMods = currentModifiers;
  221447. updateModifiers (ev);
  221448. currentModifiers &= ~getModifierForButtonNumber ([ev buttonNumber]);
  221449. int x, y;
  221450. getMousePos (ev, view, x, y);
  221451. handleMouseUp (oldMods, x, y, getMouseTime (ev));
  221452. showArrowCursorIfNeeded();
  221453. }
  221454. void NSViewComponentPeer::redirectMouseDrag (NSEvent* ev)
  221455. {
  221456. updateModifiers (ev);
  221457. currentModifiers |= getModifierForButtonNumber ([ev buttonNumber]);
  221458. int x, y;
  221459. getMousePos (ev, view, x, y);
  221460. handleMouseDrag (x, y, getMouseTime (ev));
  221461. }
  221462. void NSViewComponentPeer::redirectMouseMove (NSEvent* ev)
  221463. {
  221464. updateModifiers (ev);
  221465. int x, y;
  221466. getMousePos (ev, view, x, y);
  221467. handleMouseMove (x, y, getMouseTime (ev));
  221468. showArrowCursorIfNeeded();
  221469. }
  221470. void NSViewComponentPeer::redirectMouseEnter (NSEvent* ev)
  221471. {
  221472. updateModifiers (ev);
  221473. int x, y;
  221474. getMousePos (ev, view, x, y);
  221475. handleMouseEnter (x, y, getMouseTime (ev));
  221476. }
  221477. void NSViewComponentPeer::redirectMouseExit (NSEvent* ev)
  221478. {
  221479. updateModifiers (ev);
  221480. int x, y;
  221481. getMousePos (ev, view, x, y);
  221482. handleMouseExit (x, y, getMouseTime (ev));
  221483. }
  221484. void NSViewComponentPeer::redirectMouseWheel (NSEvent* ev)
  221485. {
  221486. updateModifiers (ev);
  221487. handleMouseWheel (roundFloatToInt ([ev deltaX] * 10.0f),
  221488. roundFloatToInt ([ev deltaY] * 10.0f),
  221489. getMouseTime (ev));
  221490. }
  221491. void NSViewComponentPeer::showArrowCursorIfNeeded()
  221492. {
  221493. if (Component::getComponentUnderMouse() == 0)
  221494. {
  221495. int mx, my;
  221496. Desktop::getInstance().getMousePosition (mx, my);
  221497. if (Desktop::getInstance().findComponentAt (mx, my) == 0)
  221498. [[NSCursor arrowCursor] set];
  221499. }
  221500. }
  221501. BOOL NSViewComponentPeer::sendDragCallback (int type, id <NSDraggingInfo> sender)
  221502. {
  221503. NSString* bestType
  221504. = [[sender draggingPasteboard] availableTypeFromArray: [view getSupportedDragTypes]];
  221505. if (bestType == nil)
  221506. return false;
  221507. NSPoint p = [view convertPoint: [sender draggingLocation] fromView: nil];
  221508. int x = (int) p.x;
  221509. int y = (int) ([view frame].size.height - p.y);
  221510. StringArray files;
  221511. id list = [[sender draggingPasteboard] propertyListForType: bestType];
  221512. if (list == nil)
  221513. return false;
  221514. if ([list isKindOfClass: [NSArray class]])
  221515. {
  221516. NSArray* items = (NSArray*) list;
  221517. for (unsigned int i = 0; i < [items count]; ++i)
  221518. files.add (nsStringToJuce ((NSString*) [items objectAtIndex: i]));
  221519. }
  221520. if (files.size() == 0)
  221521. return false;
  221522. if (type == 0)
  221523. handleFileDragMove (files, x, y);
  221524. else if (type == 1)
  221525. handleFileDragExit (files);
  221526. else if (type == 2)
  221527. handleFileDragDrop (files, x, y);
  221528. return true;
  221529. }
  221530. bool NSViewComponentPeer::isOpaque()
  221531. {
  221532. if (! getComponent()->isValidComponent())
  221533. return true;
  221534. return getComponent()->isOpaque();
  221535. }
  221536. void NSViewComponentPeer::drawRect (NSRect r)
  221537. {
  221538. if (r.size.width < 1.0f || r.size.height < 1.0f)
  221539. return;
  221540. const float y = [view frame].size.height - (r.origin.y + r.size.height);
  221541. JuceNSImage temp ((int) (r.size.width + 0.5f),
  221542. (int) (r.size.height + 0.5f),
  221543. ! getComponent()->isOpaque());
  221544. LowLevelGraphicsSoftwareRenderer context (temp.getJuceImage());
  221545. const int originX = -roundFloatToInt (r.origin.x);
  221546. const int originY = -roundFloatToInt (y);
  221547. context.setOrigin (originX, originY);
  221548. const NSRect* rects = 0;
  221549. NSInteger numRects = 0;
  221550. [view getRectsBeingDrawn: &rects count: &numRects];
  221551. RectangleList clip;
  221552. for (int i = 0; i < numRects; ++i)
  221553. {
  221554. clip.addWithoutMerging (Rectangle (roundFloatToInt (rects[i].origin.x),
  221555. roundFloatToInt ([view frame].size.height - (rects[i].origin.y + rects[i].size.height)),
  221556. roundFloatToInt (rects[i].size.width),
  221557. roundFloatToInt (rects[i].size.height)));
  221558. }
  221559. if (context.reduceClipRegion (clip))
  221560. {
  221561. handlePaint (context);
  221562. temp.draw (r.origin.x, r.origin.y, clip, originX, originY);
  221563. }
  221564. }
  221565. bool NSViewComponentPeer::canBecomeKeyWindow()
  221566. {
  221567. return (getStyleFlags() & juce::ComponentPeer::windowIgnoresKeyPresses) == 0;
  221568. }
  221569. bool NSViewComponentPeer::windowShouldClose()
  221570. {
  221571. if (! isValidPeer (this))
  221572. return YES;
  221573. handleUserClosingWindow();
  221574. return NO;
  221575. }
  221576. void NSViewComponentPeer::redirectMovedOrResized()
  221577. {
  221578. handleMovedOrResized();
  221579. }
  221580. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars)
  221581. {
  221582. // Very annoyingly, this function has to use the old SetSystemUIMode function,
  221583. // which is in Carbon.framework. But, because there's no Cocoa equivalent, it
  221584. // is apparently still available in 64-bit apps..
  221585. if (enableOrDisable)
  221586. {
  221587. SetSystemUIMode (kUIModeAllSuppressed, allowMenusAndBars ? kUIOptionAutoShowMenuBar : 0);
  221588. kioskModeComponent->setBounds (Desktop::getInstance().getMainMonitorArea (false));
  221589. }
  221590. else
  221591. {
  221592. SetSystemUIMode (kUIModeNormal, 0);
  221593. }
  221594. }
  221595. void NSViewComponentPeer::repaint (int x, int y, int w, int h)
  221596. {
  221597. [view setNeedsDisplayInRect:
  221598. NSMakeRect ((float) x, (float) ([view frame].size.height - (y + h)),
  221599. (float) w, (float) h)];
  221600. }
  221601. void NSViewComponentPeer::performAnyPendingRepaintsNow()
  221602. {
  221603. [view displayIfNeeded];
  221604. }
  221605. ComponentPeer* Component::createNewPeer (int styleFlags, void* windowToAttachTo)
  221606. {
  221607. return new NSViewComponentPeer (this, styleFlags, (NSView*) windowToAttachTo);
  221608. }
  221609. static Image* NSImageToJuceImage (NSImage* image)
  221610. {
  221611. JuceNSImage juceIm ((int) [image size].width,
  221612. (int) [image size].height,
  221613. true);
  221614. juceIm.drawNSImage (image);
  221615. return juceIm.getJuceImage().createCopy();
  221616. }
  221617. Image* juce_createIconForFile (const File& file)
  221618. {
  221619. const ScopedAutoReleasePool pool;
  221620. NSImage* im = [[NSWorkspace sharedWorkspace] iconForFile: juceStringToNS (file.getFullPathName())];
  221621. return NSImageToJuceImage (im);
  221622. }
  221623. const int KeyPress::spaceKey = ' ';
  221624. const int KeyPress::returnKey = 0x0d;
  221625. const int KeyPress::escapeKey = 0x1b;
  221626. const int KeyPress::backspaceKey = 0x7f;
  221627. const int KeyPress::leftKey = NSLeftArrowFunctionKey;
  221628. const int KeyPress::rightKey = NSRightArrowFunctionKey;
  221629. const int KeyPress::upKey = NSUpArrowFunctionKey;
  221630. const int KeyPress::downKey = NSDownArrowFunctionKey;
  221631. const int KeyPress::pageUpKey = NSPageUpFunctionKey;
  221632. const int KeyPress::pageDownKey = NSPageDownFunctionKey;
  221633. const int KeyPress::endKey = NSEndFunctionKey;
  221634. const int KeyPress::homeKey = NSHomeFunctionKey;
  221635. const int KeyPress::deleteKey = NSDeleteFunctionKey;
  221636. const int KeyPress::insertKey = -1;
  221637. const int KeyPress::tabKey = 9;
  221638. const int KeyPress::F1Key = NSF1FunctionKey;
  221639. const int KeyPress::F2Key = NSF2FunctionKey;
  221640. const int KeyPress::F3Key = NSF3FunctionKey;
  221641. const int KeyPress::F4Key = NSF4FunctionKey;
  221642. const int KeyPress::F5Key = NSF5FunctionKey;
  221643. const int KeyPress::F6Key = NSF6FunctionKey;
  221644. const int KeyPress::F7Key = NSF7FunctionKey;
  221645. const int KeyPress::F8Key = NSF8FunctionKey;
  221646. const int KeyPress::F9Key = NSF9FunctionKey;
  221647. const int KeyPress::F10Key = NSF10FunctionKey;
  221648. const int KeyPress::F11Key = NSF1FunctionKey;
  221649. const int KeyPress::F12Key = NSF12FunctionKey;
  221650. const int KeyPress::F13Key = NSF13FunctionKey;
  221651. const int KeyPress::F14Key = NSF14FunctionKey;
  221652. const int KeyPress::F15Key = NSF15FunctionKey;
  221653. const int KeyPress::F16Key = NSF16FunctionKey;
  221654. const int KeyPress::numberPad0 = 0x30020;
  221655. const int KeyPress::numberPad1 = 0x30021;
  221656. const int KeyPress::numberPad2 = 0x30022;
  221657. const int KeyPress::numberPad3 = 0x30023;
  221658. const int KeyPress::numberPad4 = 0x30024;
  221659. const int KeyPress::numberPad5 = 0x30025;
  221660. const int KeyPress::numberPad6 = 0x30026;
  221661. const int KeyPress::numberPad7 = 0x30027;
  221662. const int KeyPress::numberPad8 = 0x30028;
  221663. const int KeyPress::numberPad9 = 0x30029;
  221664. const int KeyPress::numberPadAdd = 0x3002a;
  221665. const int KeyPress::numberPadSubtract = 0x3002b;
  221666. const int KeyPress::numberPadMultiply = 0x3002c;
  221667. const int KeyPress::numberPadDivide = 0x3002d;
  221668. const int KeyPress::numberPadSeparator = 0x3002e;
  221669. const int KeyPress::numberPadDecimalPoint = 0x3002f;
  221670. const int KeyPress::numberPadEquals = 0x30030;
  221671. const int KeyPress::numberPadDelete = 0x30031;
  221672. const int KeyPress::playKey = 0x30000;
  221673. const int KeyPress::stopKey = 0x30001;
  221674. const int KeyPress::fastForwardKey = 0x30002;
  221675. const int KeyPress::rewindKey = 0x30003;
  221676. #endif
  221677. /********* End of inlined file: juce_mac_NSViewComponentPeer.mm *********/
  221678. /********* Start of inlined file: juce_mac_MouseCursor.mm *********/
  221679. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  221680. // compiled on its own).
  221681. #ifdef JUCE_INCLUDED_FILE
  221682. static NSImage* juceImageToNSImage (const Image& image)
  221683. {
  221684. const ScopedAutoReleasePool pool;
  221685. int lineStride, pixelStride;
  221686. const uint8* pixels = image.lockPixelDataReadOnly (0, 0, image.getWidth(), image.getHeight(),
  221687. lineStride, pixelStride);
  221688. NSBitmapImageRep* rep = [[NSBitmapImageRep alloc]
  221689. initWithBitmapDataPlanes: NULL
  221690. pixelsWide: image.getWidth()
  221691. pixelsHigh: image.getHeight()
  221692. bitsPerSample: 8
  221693. samplesPerPixel: image.hasAlphaChannel() ? 4 : 3
  221694. hasAlpha: image.hasAlphaChannel()
  221695. isPlanar: NO
  221696. colorSpaceName: NSCalibratedRGBColorSpace
  221697. bitmapFormat: (NSBitmapFormat) 0
  221698. bytesPerRow: lineStride
  221699. bitsPerPixel: pixelStride * 8];
  221700. unsigned char* newData = [rep bitmapData];
  221701. memcpy (newData, pixels, lineStride * image.getHeight());
  221702. image.releasePixelDataReadOnly (pixels);
  221703. NSImage* im = [[NSImage alloc] init];
  221704. [im addRepresentation: rep];
  221705. [rep release];
  221706. return im;
  221707. }
  221708. void* juce_createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY) throw()
  221709. {
  221710. NSImage* im = juceImageToNSImage (image);
  221711. NSCursor* c = [[NSCursor alloc] initWithImage: im
  221712. hotSpot: NSMakePoint (hotspotX, hotspotY)];
  221713. [im release];
  221714. return (void*) c;
  221715. }
  221716. static void* juce_cursorFromData (const unsigned char* data, const int size, float hx, float hy) throw()
  221717. {
  221718. Image* const im = ImageFileFormat::loadFrom ((const char*) data, size);
  221719. jassert (im != 0);
  221720. if (im == 0)
  221721. return 0;
  221722. void* const curs = juce_createMouseCursorFromImage (*im,
  221723. (int) (hx * im->getWidth()),
  221724. (int) (hy * im->getHeight()));
  221725. delete im;
  221726. return curs;
  221727. }
  221728. static void* juce_cursorFromWebKitFile (const char* filename, float hx, float hy)
  221729. {
  221730. File f ("/System/Library/Frameworks/WebKit.framework/Frameworks/WebCore.framework/Resources");
  221731. MemoryBlock mb;
  221732. if (f.getChildFile (filename).loadFileAsData (mb))
  221733. return juce_cursorFromData ((const unsigned char*) mb.getData(), mb.getSize(), hx, hy);
  221734. return 0;
  221735. }
  221736. void* juce_createStandardMouseCursor (MouseCursor::StandardCursorType type) throw()
  221737. {
  221738. const ScopedAutoReleasePool pool;
  221739. NSCursor* c = 0;
  221740. switch (type)
  221741. {
  221742. case MouseCursor::NormalCursor:
  221743. c = [NSCursor arrowCursor];
  221744. break;
  221745. case MouseCursor::NoCursor:
  221746. {
  221747. Image blank (Image::ARGB, 8, 8, true);
  221748. return juce_createMouseCursorFromImage (blank, 0, 0);
  221749. }
  221750. case MouseCursor::DraggingHandCursor:
  221751. c = [NSCursor openHandCursor];
  221752. break;
  221753. case MouseCursor::CopyingCursor:
  221754. return juce_cursorFromWebKitFile ("copyCursor.png", 0, 0);
  221755. case MouseCursor::WaitCursor:
  221756. c = [NSCursor arrowCursor]; // avoid this on the mac, let the OS provide the beachball
  221757. break;
  221758. //return juce_cursorFromWebKitFile ("waitCursor.png", 0.5f, 0.5f);
  221759. case MouseCursor::IBeamCursor:
  221760. c = [NSCursor IBeamCursor];
  221761. break;
  221762. case MouseCursor::PointingHandCursor:
  221763. c = [NSCursor pointingHandCursor];
  221764. break;
  221765. case MouseCursor::LeftRightResizeCursor:
  221766. c = [NSCursor resizeLeftRightCursor];
  221767. break;
  221768. case MouseCursor::LeftEdgeResizeCursor:
  221769. c = [NSCursor resizeLeftCursor];
  221770. break;
  221771. case MouseCursor::RightEdgeResizeCursor:
  221772. c = [NSCursor resizeRightCursor];
  221773. break;
  221774. case MouseCursor::UpDownResizeCursor:
  221775. case MouseCursor::TopEdgeResizeCursor:
  221776. case MouseCursor::BottomEdgeResizeCursor:
  221777. return juce_cursorFromWebKitFile ("northSouthResizeCursor.png", 0.5f, 0.5f);
  221778. case MouseCursor::TopLeftCornerResizeCursor:
  221779. case MouseCursor::BottomRightCornerResizeCursor:
  221780. return juce_cursorFromWebKitFile ("northWestSouthEastResizeCursor.png", 0.5f, 0.5f);
  221781. case MouseCursor::TopRightCornerResizeCursor:
  221782. case MouseCursor::BottomLeftCornerResizeCursor:
  221783. return juce_cursorFromWebKitFile ("northEastSouthWestResizeCursor.png", 0.5f, 0.5f);
  221784. case MouseCursor::UpDownLeftRightResizeCursor:
  221785. return juce_cursorFromWebKitFile ("moveCursor.png", 0.5f, 0.5f);
  221786. case MouseCursor::CrosshairCursor:
  221787. c = [NSCursor crosshairCursor];
  221788. break;
  221789. }
  221790. [c retain];
  221791. return (void*) c;
  221792. }
  221793. void juce_deleteMouseCursor (void* const cursorHandle, const bool isStandard) throw()
  221794. {
  221795. NSCursor* c = (NSCursor*) cursorHandle;
  221796. [c release];
  221797. }
  221798. void MouseCursor::showInAllWindows() const throw()
  221799. {
  221800. showInWindow (0);
  221801. }
  221802. void MouseCursor::showInWindow (ComponentPeer*) const throw()
  221803. {
  221804. NSCursor* const c = (NSCursor*) getHandle();
  221805. [c set];
  221806. }
  221807. #endif
  221808. /********* End of inlined file: juce_mac_MouseCursor.mm *********/
  221809. /********* Start of inlined file: juce_mac_NSViewComponent.mm *********/
  221810. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  221811. // compiled on its own).
  221812. #ifdef JUCE_INCLUDED_FILE
  221813. class NSViewComponentInternal : public ComponentMovementWatcher
  221814. {
  221815. Component* const owner;
  221816. NSViewComponentPeer* currentPeer;
  221817. bool wasShowing;
  221818. public:
  221819. NSView* const view;
  221820. NSViewComponentInternal (NSView* const view_, Component* const owner_)
  221821. : ComponentMovementWatcher (owner_),
  221822. owner (owner_),
  221823. currentPeer (0),
  221824. wasShowing (false),
  221825. view (view_)
  221826. {
  221827. [view_ retain];
  221828. if (owner_->isShowing())
  221829. componentPeerChanged();
  221830. }
  221831. ~NSViewComponentInternal()
  221832. {
  221833. [view removeFromSuperview];
  221834. [view release];
  221835. }
  221836. void componentMovedOrResized (Component& comp, bool wasMoved, bool wasResized)
  221837. {
  221838. ComponentMovementWatcher::componentMovedOrResized (comp, wasMoved, wasResized);
  221839. // The ComponentMovementWatcher version of this method avoids calling
  221840. // us when the top-level comp is resized, but for an NSView we need to know this
  221841. // because with inverted co-ords, we need to update the position even if the
  221842. // top-left pos hasn't changed
  221843. if (comp.isOnDesktop() && wasResized)
  221844. componentMovedOrResized (wasMoved, wasResized);
  221845. }
  221846. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  221847. {
  221848. Component* const topComp = owner->getTopLevelComponent();
  221849. if (topComp->getPeer() != 0)
  221850. {
  221851. int x = 0, y = 0;
  221852. owner->relativePositionToOtherComponent (topComp, x, y);
  221853. NSRect r;
  221854. r.origin.x = (float) x;
  221855. r.origin.y = (float) y;
  221856. r.size.width = (float) owner->getWidth();
  221857. r.size.height = (float) owner->getHeight();
  221858. r.origin.y = [[view superview] frame].size.height - (r.origin.y + r.size.height);
  221859. [view setFrame: r];
  221860. }
  221861. }
  221862. void componentPeerChanged()
  221863. {
  221864. NSViewComponentPeer* const peer = dynamic_cast <NSViewComponentPeer*> (owner->getPeer());
  221865. if (currentPeer != peer)
  221866. {
  221867. [view removeFromSuperview];
  221868. currentPeer = peer;
  221869. if (peer != 0)
  221870. {
  221871. [peer->view addSubview: view];
  221872. componentMovedOrResized (false, false);
  221873. }
  221874. }
  221875. [view setHidden: ! owner->isShowing()];
  221876. }
  221877. void componentVisibilityChanged (Component&)
  221878. {
  221879. componentPeerChanged();
  221880. }
  221881. juce_UseDebuggingNewOperator
  221882. private:
  221883. NSViewComponentInternal (const NSViewComponentInternal&);
  221884. const NSViewComponentInternal& operator= (const NSViewComponentInternal&);
  221885. };
  221886. NSViewComponent::NSViewComponent()
  221887. : info (0)
  221888. {
  221889. }
  221890. NSViewComponent::~NSViewComponent()
  221891. {
  221892. delete info;
  221893. }
  221894. void NSViewComponent::setView (void* view)
  221895. {
  221896. if (view != getView())
  221897. {
  221898. deleteAndZero (info);
  221899. if (view != 0)
  221900. info = new NSViewComponentInternal ((NSView*) view, this);
  221901. }
  221902. }
  221903. void* NSViewComponent::getView() const
  221904. {
  221905. return info == 0 ? 0 : info->view;
  221906. }
  221907. void NSViewComponent::paint (Graphics& g)
  221908. {
  221909. }
  221910. #endif
  221911. /********* End of inlined file: juce_mac_NSViewComponent.mm *********/
  221912. /********* Start of inlined file: juce_mac_AppleRemote.mm *********/
  221913. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  221914. // compiled on its own).
  221915. #ifdef JUCE_INCLUDED_FILE
  221916. AppleRemoteDevice::AppleRemoteDevice()
  221917. : device (0),
  221918. queue (0),
  221919. remoteId (0)
  221920. {
  221921. }
  221922. AppleRemoteDevice::~AppleRemoteDevice()
  221923. {
  221924. stop();
  221925. }
  221926. static io_object_t getAppleRemoteDevice() throw()
  221927. {
  221928. CFMutableDictionaryRef dict = IOServiceMatching ("AppleIRController");
  221929. io_iterator_t iter = 0;
  221930. io_object_t iod = 0;
  221931. if (IOServiceGetMatchingServices (kIOMasterPortDefault, dict, &iter) == kIOReturnSuccess
  221932. && iter != 0)
  221933. {
  221934. iod = IOIteratorNext (iter);
  221935. }
  221936. IOObjectRelease (iter);
  221937. return iod;
  221938. }
  221939. static bool createAppleRemoteInterface (io_object_t iod, void** device) throw()
  221940. {
  221941. jassert (*device == 0);
  221942. io_name_t classname;
  221943. if (IOObjectGetClass (iod, classname) == kIOReturnSuccess)
  221944. {
  221945. IOCFPlugInInterface** cfPlugInInterface = 0;
  221946. SInt32 score = 0;
  221947. if (IOCreatePlugInInterfaceForService (iod,
  221948. kIOHIDDeviceUserClientTypeID,
  221949. kIOCFPlugInInterfaceID,
  221950. &cfPlugInInterface,
  221951. &score) == kIOReturnSuccess)
  221952. {
  221953. HRESULT hr = (*cfPlugInInterface)->QueryInterface (cfPlugInInterface,
  221954. CFUUIDGetUUIDBytes (kIOHIDDeviceInterfaceID),
  221955. device);
  221956. (void) hr;
  221957. (*cfPlugInInterface)->Release (cfPlugInInterface);
  221958. }
  221959. }
  221960. return *device != 0;
  221961. }
  221962. bool AppleRemoteDevice::start (const bool inExclusiveMode) throw()
  221963. {
  221964. if (queue != 0)
  221965. return true;
  221966. stop();
  221967. bool result = false;
  221968. io_object_t iod = getAppleRemoteDevice();
  221969. if (iod != 0)
  221970. {
  221971. if (createAppleRemoteInterface (iod, &device) && open (inExclusiveMode))
  221972. result = true;
  221973. else
  221974. stop();
  221975. IOObjectRelease (iod);
  221976. }
  221977. return result;
  221978. }
  221979. void AppleRemoteDevice::stop() throw()
  221980. {
  221981. if (queue != 0)
  221982. {
  221983. (*(IOHIDQueueInterface**) queue)->stop ((IOHIDQueueInterface**) queue);
  221984. (*(IOHIDQueueInterface**) queue)->dispose ((IOHIDQueueInterface**) queue);
  221985. (*(IOHIDQueueInterface**) queue)->Release ((IOHIDQueueInterface**) queue);
  221986. queue = 0;
  221987. }
  221988. if (device != 0)
  221989. {
  221990. (*(IOHIDDeviceInterface**) device)->close ((IOHIDDeviceInterface**) device);
  221991. (*(IOHIDDeviceInterface**) device)->Release ((IOHIDDeviceInterface**) device);
  221992. device = 0;
  221993. }
  221994. }
  221995. bool AppleRemoteDevice::isActive() const throw()
  221996. {
  221997. return queue != 0;
  221998. }
  221999. static void appleRemoteQueueCallback (void* const target, const IOReturn result, void*, void*)
  222000. {
  222001. if (result == kIOReturnSuccess)
  222002. ((AppleRemoteDevice*) target)->handleCallbackInternal();
  222003. }
  222004. bool AppleRemoteDevice::open (const bool openInExclusiveMode) throw()
  222005. {
  222006. Array <int> cookies;
  222007. CFArrayRef elements;
  222008. IOHIDDeviceInterface122** const device122 = (IOHIDDeviceInterface122**) device;
  222009. if ((*device122)->copyMatchingElements (device122, 0, &elements) != kIOReturnSuccess)
  222010. return false;
  222011. for (int i = 0; i < CFArrayGetCount (elements); ++i)
  222012. {
  222013. CFDictionaryRef element = (CFDictionaryRef) CFArrayGetValueAtIndex (elements, i);
  222014. // get the cookie
  222015. CFTypeRef object = CFDictionaryGetValue (element, CFSTR (kIOHIDElementCookieKey));
  222016. if (object == 0 || CFGetTypeID (object) != CFNumberGetTypeID())
  222017. continue;
  222018. long number;
  222019. if (! CFNumberGetValue ((CFNumberRef) object, kCFNumberLongType, &number))
  222020. continue;
  222021. cookies.add ((int) number);
  222022. }
  222023. CFRelease (elements);
  222024. if ((*(IOHIDDeviceInterface**) device)
  222025. ->open ((IOHIDDeviceInterface**) device,
  222026. openInExclusiveMode ? kIOHIDOptionsTypeSeizeDevice
  222027. : kIOHIDOptionsTypeNone) == KERN_SUCCESS)
  222028. {
  222029. queue = (*(IOHIDDeviceInterface**) device)->allocQueue ((IOHIDDeviceInterface**) device);
  222030. if (queue != 0)
  222031. {
  222032. (*(IOHIDQueueInterface**) queue)->create ((IOHIDQueueInterface**) queue, 0, 12);
  222033. for (int i = 0; i < cookies.size(); ++i)
  222034. {
  222035. IOHIDElementCookie cookie = (IOHIDElementCookie) cookies.getUnchecked(i);
  222036. (*(IOHIDQueueInterface**) queue)->addElement ((IOHIDQueueInterface**) queue, cookie, 0);
  222037. }
  222038. CFRunLoopSourceRef eventSource;
  222039. if ((*(IOHIDQueueInterface**) queue)
  222040. ->createAsyncEventSource ((IOHIDQueueInterface**) queue, &eventSource) == KERN_SUCCESS)
  222041. {
  222042. if ((*(IOHIDQueueInterface**) queue)->setEventCallout ((IOHIDQueueInterface**) queue,
  222043. appleRemoteQueueCallback, this, 0) == KERN_SUCCESS)
  222044. {
  222045. CFRunLoopAddSource (CFRunLoopGetCurrent(), eventSource, kCFRunLoopDefaultMode);
  222046. (*(IOHIDQueueInterface**) queue)->start ((IOHIDQueueInterface**) queue);
  222047. return true;
  222048. }
  222049. }
  222050. }
  222051. }
  222052. return false;
  222053. }
  222054. void AppleRemoteDevice::handleCallbackInternal()
  222055. {
  222056. int totalValues = 0;
  222057. AbsoluteTime nullTime = { 0, 0 };
  222058. char cookies [12];
  222059. int numCookies = 0;
  222060. while (numCookies < numElementsInArray (cookies))
  222061. {
  222062. IOHIDEventStruct e;
  222063. if ((*(IOHIDQueueInterface**) queue)->getNextEvent ((IOHIDQueueInterface**) queue, &e, nullTime, 0) != kIOReturnSuccess)
  222064. break;
  222065. if ((int) e.elementCookie == 19)
  222066. {
  222067. remoteId = e.value;
  222068. buttonPressed (switched, false);
  222069. }
  222070. else
  222071. {
  222072. totalValues += e.value;
  222073. cookies [numCookies++] = (char) (pointer_sized_int) e.elementCookie;
  222074. }
  222075. }
  222076. cookies [numCookies++] = 0;
  222077. //DBG (String::toHexString ((uint8*) cookies, numCookies, 1) + " " + String (totalValues));
  222078. static const char buttonPatterns[] =
  222079. {
  222080. 0x1f, 0x14, 0x12, 0x1f, 0x14, 0x12, 0,
  222081. 0x1f, 0x15, 0x12, 0x1f, 0x15, 0x12, 0,
  222082. 0x1f, 0x1d, 0x1c, 0x12, 0,
  222083. 0x1f, 0x1e, 0x1c, 0x12, 0,
  222084. 0x1f, 0x16, 0x12, 0x1f, 0x16, 0x12, 0,
  222085. 0x1f, 0x17, 0x12, 0x1f, 0x17, 0x12, 0,
  222086. 0x1f, 0x12, 0x04, 0x02, 0,
  222087. 0x1f, 0x12, 0x03, 0x02, 0,
  222088. 0x1f, 0x12, 0x1f, 0x12, 0,
  222089. 0x23, 0x1f, 0x12, 0x23, 0x1f, 0x12, 0,
  222090. 19, 0
  222091. };
  222092. int buttonNum = (int) menuButton;
  222093. int i = 0;
  222094. while (i < numElementsInArray (buttonPatterns))
  222095. {
  222096. if (strcmp (cookies, buttonPatterns + i) == 0)
  222097. {
  222098. buttonPressed ((ButtonType) buttonNum, totalValues > 0);
  222099. break;
  222100. }
  222101. i += strlen (buttonPatterns + i) + 1;
  222102. ++buttonNum;
  222103. }
  222104. }
  222105. #endif
  222106. /********* End of inlined file: juce_mac_AppleRemote.mm *********/
  222107. /********* Start of inlined file: juce_mac_OpenGLComponent.mm *********/
  222108. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  222109. // compiled on its own).
  222110. #if JUCE_INCLUDED_FILE && JUCE_OPENGL
  222111. END_JUCE_NAMESPACE
  222112. #define ThreadSafeNSOpenGLView MakeObjCClassName(ThreadSafeNSOpenGLView)
  222113. @interface ThreadSafeNSOpenGLView : NSOpenGLView
  222114. {
  222115. CriticalSection* contextLock;
  222116. bool needsUpdate;
  222117. }
  222118. - (id) initWithFrame: (NSRect) frameRect pixelFormat: (NSOpenGLPixelFormat*) format;
  222119. - (bool) makeActive;
  222120. - (void) makeInactive;
  222121. - (void) reshape;
  222122. @end
  222123. @implementation ThreadSafeNSOpenGLView
  222124. - (id) initWithFrame: (NSRect) frameRect
  222125. pixelFormat: (NSOpenGLPixelFormat*) format
  222126. {
  222127. contextLock = new CriticalSection();
  222128. self = [super initWithFrame: frameRect pixelFormat: format];
  222129. if (self != nil)
  222130. [[NSNotificationCenter defaultCenter] addObserver: self
  222131. selector: @selector (_surfaceNeedsUpdate:)
  222132. name: NSViewGlobalFrameDidChangeNotification
  222133. object: self];
  222134. return self;
  222135. }
  222136. - (void) dealloc
  222137. {
  222138. [[NSNotificationCenter defaultCenter] removeObserver: self];
  222139. delete contextLock;
  222140. [super dealloc];
  222141. }
  222142. - (bool) makeActive
  222143. {
  222144. const ScopedLock sl (*contextLock);
  222145. if ([self openGLContext] == 0)
  222146. return false;
  222147. [[self openGLContext] makeCurrentContext];
  222148. if (needsUpdate)
  222149. {
  222150. [super update];
  222151. needsUpdate = false;
  222152. }
  222153. return true;
  222154. }
  222155. - (void) makeInactive
  222156. {
  222157. const ScopedLock sl (*contextLock);
  222158. [NSOpenGLContext clearCurrentContext];
  222159. }
  222160. - (void) _surfaceNeedsUpdate: (NSNotification*) notification
  222161. {
  222162. const ScopedLock sl (*contextLock);
  222163. needsUpdate = true;
  222164. }
  222165. - (void) update
  222166. {
  222167. const ScopedLock sl (*contextLock);
  222168. needsUpdate = true;
  222169. }
  222170. - (void) reshape
  222171. {
  222172. const ScopedLock sl (*contextLock);
  222173. needsUpdate = true;
  222174. }
  222175. @end
  222176. BEGIN_JUCE_NAMESPACE
  222177. class WindowedGLContext : public OpenGLContext
  222178. {
  222179. public:
  222180. WindowedGLContext (Component* const component,
  222181. const OpenGLPixelFormat& pixelFormat_,
  222182. NSOpenGLContext* sharedContext)
  222183. : renderContext (0),
  222184. pixelFormat (pixelFormat_)
  222185. {
  222186. jassert (component != 0);
  222187. NSOpenGLPixelFormatAttribute attribs [64];
  222188. int n = 0;
  222189. attribs[n++] = NSOpenGLPFADoubleBuffer;
  222190. attribs[n++] = NSOpenGLPFAAccelerated;
  222191. attribs[n++] = NSOpenGLPFAMPSafe; // NSOpenGLPFAAccelerated, NSOpenGLPFAMultiScreen, NSOpenGLPFASingleRenderer
  222192. attribs[n++] = NSOpenGLPFAColorSize;
  222193. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.redBits,
  222194. pixelFormat.greenBits,
  222195. pixelFormat.blueBits);
  222196. attribs[n++] = NSOpenGLPFAAlphaSize;
  222197. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.alphaBits;
  222198. attribs[n++] = NSOpenGLPFADepthSize;
  222199. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.depthBufferBits;
  222200. attribs[n++] = NSOpenGLPFAStencilSize;
  222201. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.stencilBufferBits;
  222202. attribs[n++] = NSOpenGLPFAAccumSize;
  222203. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.accumulationBufferRedBits,
  222204. pixelFormat.accumulationBufferGreenBits,
  222205. pixelFormat.accumulationBufferBlueBits,
  222206. pixelFormat.accumulationBufferAlphaBits);
  222207. // xxx not sure how to do fullSceneAntiAliasingNumSamples..
  222208. attribs[n++] = NSOpenGLPFASampleBuffers;
  222209. attribs[n++] = (NSOpenGLPixelFormatAttribute) 1;
  222210. attribs[n++] = NSOpenGLPFAClosestPolicy;
  222211. attribs[n++] = NSOpenGLPFANoRecovery;
  222212. attribs[n++] = (NSOpenGLPixelFormatAttribute) 0;
  222213. NSOpenGLPixelFormat* format
  222214. = [[NSOpenGLPixelFormat alloc] initWithAttributes: attribs];
  222215. view = [[ThreadSafeNSOpenGLView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  222216. pixelFormat: format];
  222217. renderContext = [[[NSOpenGLContext alloc] initWithFormat: format
  222218. shareContext: sharedContext] autorelease];
  222219. const GLint swapInterval = 1;
  222220. [renderContext setValues: &swapInterval forParameter: NSOpenGLCPSwapInterval];
  222221. [view setOpenGLContext: renderContext];
  222222. [renderContext setView: view];
  222223. [format release];
  222224. viewHolder = new NSViewComponentInternal (view, component);
  222225. }
  222226. ~WindowedGLContext()
  222227. {
  222228. makeInactive();
  222229. [renderContext setView: nil];
  222230. delete viewHolder;
  222231. }
  222232. bool makeActive() const throw()
  222233. {
  222234. jassert (renderContext != 0);
  222235. [view makeActive];
  222236. return isActive();
  222237. }
  222238. bool makeInactive() const throw()
  222239. {
  222240. [view makeInactive];
  222241. return true;
  222242. }
  222243. bool isActive() const throw()
  222244. {
  222245. return [NSOpenGLContext currentContext] == renderContext;
  222246. }
  222247. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  222248. void* getRawContext() const throw() { return renderContext; }
  222249. void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight)
  222250. {
  222251. }
  222252. void swapBuffers()
  222253. {
  222254. [renderContext flushBuffer];
  222255. }
  222256. bool setSwapInterval (const int numFramesPerSwap)
  222257. {
  222258. [renderContext setValues: (const GLint*) &numFramesPerSwap
  222259. forParameter: NSOpenGLCPSwapInterval];
  222260. return true;
  222261. }
  222262. int getSwapInterval() const
  222263. {
  222264. GLint numFrames = 0;
  222265. [renderContext getValues: &numFrames
  222266. forParameter: NSOpenGLCPSwapInterval];
  222267. return numFrames;
  222268. }
  222269. void repaint()
  222270. {
  222271. // we need to invalidate the juce view that holds this gl view, to make it
  222272. // cause a repaint callback
  222273. NSView* v = (NSView*) viewHolder->view;
  222274. NSRect r = [v frame];
  222275. // bit of a bodge here.. if we only invalidate the area of the gl component,
  222276. // it's completely covered by the NSOpenGLView, so the OS throws away the
  222277. // repaint message, thus never causing our paint() callback, and never repainting
  222278. // the comp. So invalidating just a little bit around the edge helps..
  222279. [[v superview] setNeedsDisplayInRect: NSInsetRect (r, -2.0f, -2.0f)];
  222280. }
  222281. void* getNativeWindowHandle() const { return viewHolder->view; }
  222282. juce_UseDebuggingNewOperator
  222283. NSOpenGLContext* renderContext;
  222284. ThreadSafeNSOpenGLView* view;
  222285. private:
  222286. OpenGLPixelFormat pixelFormat;
  222287. NSViewComponentInternal* viewHolder;
  222288. WindowedGLContext (const WindowedGLContext&);
  222289. const WindowedGLContext& operator= (const WindowedGLContext&);
  222290. };
  222291. OpenGLContext* OpenGLContext::createContextForWindow (Component* const component,
  222292. const OpenGLPixelFormat& pixelFormat,
  222293. const OpenGLContext* const contextToShareWith)
  222294. {
  222295. WindowedGLContext* c = new WindowedGLContext (component, pixelFormat,
  222296. contextToShareWith != 0 ? (NSOpenGLContext*) contextToShareWith->getRawContext() : 0);
  222297. if (c->renderContext == 0)
  222298. deleteAndZero (c);
  222299. return c;
  222300. }
  222301. void* OpenGLComponent::getNativeWindowHandle() const
  222302. {
  222303. return context != 0 ? ((WindowedGLContext*) context)->getNativeWindowHandle()
  222304. : 0;
  222305. }
  222306. void juce_glViewport (const int w, const int h)
  222307. {
  222308. glViewport (0, 0, w, h);
  222309. }
  222310. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  222311. OwnedArray <OpenGLPixelFormat>& results)
  222312. {
  222313. /* GLint attribs [64];
  222314. int n = 0;
  222315. attribs[n++] = AGL_RGBA;
  222316. attribs[n++] = AGL_DOUBLEBUFFER;
  222317. attribs[n++] = AGL_ACCELERATED;
  222318. attribs[n++] = AGL_NO_RECOVERY;
  222319. attribs[n++] = AGL_NONE;
  222320. AGLPixelFormat p = aglChoosePixelFormat (0, 0, attribs);
  222321. while (p != 0)
  222322. {
  222323. OpenGLPixelFormat* const pf = new OpenGLPixelFormat();
  222324. pf->redBits = getAGLAttribute (p, AGL_RED_SIZE);
  222325. pf->greenBits = getAGLAttribute (p, AGL_GREEN_SIZE);
  222326. pf->blueBits = getAGLAttribute (p, AGL_BLUE_SIZE);
  222327. pf->alphaBits = getAGLAttribute (p, AGL_ALPHA_SIZE);
  222328. pf->depthBufferBits = getAGLAttribute (p, AGL_DEPTH_SIZE);
  222329. pf->stencilBufferBits = getAGLAttribute (p, AGL_STENCIL_SIZE);
  222330. pf->accumulationBufferRedBits = getAGLAttribute (p, AGL_ACCUM_RED_SIZE);
  222331. pf->accumulationBufferGreenBits = getAGLAttribute (p, AGL_ACCUM_GREEN_SIZE);
  222332. pf->accumulationBufferBlueBits = getAGLAttribute (p, AGL_ACCUM_BLUE_SIZE);
  222333. pf->accumulationBufferAlphaBits = getAGLAttribute (p, AGL_ACCUM_ALPHA_SIZE);
  222334. results.add (pf);
  222335. p = aglNextPixelFormat (p);
  222336. }*/
  222337. //jassertfalse //xxx can't see how you do this in cocoa!
  222338. }
  222339. #endif
  222340. /********* End of inlined file: juce_mac_OpenGLComponent.mm *********/
  222341. /********* Start of inlined file: juce_mac_MainMenu.mm *********/
  222342. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  222343. // compiled on its own).
  222344. #ifdef JUCE_INCLUDED_FILE
  222345. class JuceMainMenuHandler;
  222346. END_JUCE_NAMESPACE
  222347. using namespace JUCE_NAMESPACE;
  222348. #define JuceMenuCallback MakeObjCClassName(JuceMenuCallback)
  222349. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  222350. @interface JuceMenuCallback : NSObject <NSMenuDelegate>
  222351. #else
  222352. @interface JuceMenuCallback : NSObject
  222353. #endif
  222354. {
  222355. JuceMainMenuHandler* owner;
  222356. }
  222357. - (JuceMenuCallback*) initWithOwner: (JuceMainMenuHandler*) owner_;
  222358. - (void) dealloc;
  222359. - (void) menuItemInvoked: (id) menu;
  222360. - (void) menuNeedsUpdate: (NSMenu*) menu;
  222361. @end
  222362. BEGIN_JUCE_NAMESPACE
  222363. class JuceMainMenuHandler : private MenuBarModelListener,
  222364. private DeletedAtShutdown
  222365. {
  222366. public:
  222367. static JuceMainMenuHandler* instance;
  222368. JuceMainMenuHandler() throw()
  222369. : currentModel (0),
  222370. lastUpdateTime (0)
  222371. {
  222372. callback = [[JuceMenuCallback alloc] initWithOwner: this];
  222373. }
  222374. ~JuceMainMenuHandler() throw()
  222375. {
  222376. setMenu (0);
  222377. jassert (instance == this);
  222378. instance = 0;
  222379. [callback release];
  222380. }
  222381. void setMenu (MenuBarModel* const newMenuBarModel) throw()
  222382. {
  222383. if (currentModel != newMenuBarModel)
  222384. {
  222385. if (currentModel != 0)
  222386. currentModel->removeListener (this);
  222387. currentModel = newMenuBarModel;
  222388. if (currentModel != 0)
  222389. currentModel->addListener (this);
  222390. menuBarItemsChanged (0);
  222391. }
  222392. }
  222393. void addSubMenu (NSMenu* parent, const PopupMenu& child,
  222394. const String& name, const int menuId, const int tag)
  222395. {
  222396. NSMenuItem* item = [parent addItemWithTitle: juceStringToNS (name)
  222397. action: nil
  222398. keyEquivalent: @""];
  222399. [item setTag: tag];
  222400. NSMenu* sub = createMenu (child, name, menuId, tag);
  222401. [parent setSubmenu: sub forItem: item];
  222402. [sub setAutoenablesItems: false];
  222403. [sub release];
  222404. }
  222405. void updateSubMenu (NSMenuItem* parentItem, const PopupMenu& menuToCopy,
  222406. const String& name, const int menuId, const int tag)
  222407. {
  222408. [parentItem setTag: tag];
  222409. NSMenu* menu = [parentItem submenu];
  222410. [menu setTitle: juceStringToNS (name)];
  222411. while ([menu numberOfItems] > 0)
  222412. [menu removeItemAtIndex: 0];
  222413. PopupMenu::MenuItemIterator iter (menuToCopy);
  222414. while (iter.next())
  222415. addMenuItem (iter, menu, menuId, tag);
  222416. [menu setAutoenablesItems: false];
  222417. [menu update];
  222418. }
  222419. void menuBarItemsChanged (MenuBarModel*)
  222420. {
  222421. lastUpdateTime = Time::getMillisecondCounter();
  222422. StringArray menuNames;
  222423. if (currentModel != 0)
  222424. menuNames = currentModel->getMenuBarNames();
  222425. NSMenu* menuBar = [NSApp mainMenu];
  222426. while ([menuBar numberOfItems] > 1 + menuNames.size())
  222427. [menuBar removeItemAtIndex: [menuBar numberOfItems] - 1];
  222428. int menuId = 1;
  222429. for (int i = 0; i < menuNames.size(); ++i)
  222430. {
  222431. const PopupMenu menu (currentModel->getMenuForIndex (i, menuNames [i]));
  222432. if (i >= [menuBar numberOfItems] - 1)
  222433. addSubMenu (menuBar, menu, menuNames[i], menuId, i);
  222434. else
  222435. updateSubMenu ([menuBar itemAtIndex: 1 + i], menu, menuNames[i], menuId, i);
  222436. }
  222437. }
  222438. static void flashMenuBar (NSMenu* menu)
  222439. {
  222440. const unichar f35Key = NSF35FunctionKey;
  222441. NSString* f35String = [NSString stringWithCharacters: &f35Key length: 1];
  222442. NSMenuItem* item = [[NSMenuItem alloc] initWithTitle: @"x"
  222443. action: nil
  222444. keyEquivalent: f35String];
  222445. [item setTarget: nil];
  222446. [menu insertItem: item atIndex: [menu numberOfItems]];
  222447. [item release];
  222448. NSEvent* f35Event = [NSEvent keyEventWithType: NSKeyDown
  222449. location: NSZeroPoint
  222450. modifierFlags: NSCommandKeyMask
  222451. timestamp: 0
  222452. windowNumber: 0
  222453. context: [NSGraphicsContext currentContext]
  222454. characters: f35String
  222455. charactersIgnoringModifiers: f35String
  222456. isARepeat: NO
  222457. keyCode: 0];
  222458. [menu performKeyEquivalent: f35Event];
  222459. [menu removeItem: item];
  222460. }
  222461. static NSMenuItem* findMenuItem (NSMenu* const menu, const ApplicationCommandTarget::InvocationInfo& info)
  222462. {
  222463. for (int i = [menu numberOfItems]; --i >= 0;)
  222464. {
  222465. NSMenuItem* m = [menu itemAtIndex: i];
  222466. if ([m tag] == info.commandID)
  222467. return m;
  222468. if ([m submenu] != 0)
  222469. {
  222470. NSMenuItem* found = findMenuItem ([m submenu], info);
  222471. if (found != 0)
  222472. return found;
  222473. }
  222474. }
  222475. return 0;
  222476. }
  222477. void menuCommandInvoked (MenuBarModel*, const ApplicationCommandTarget::InvocationInfo& info)
  222478. {
  222479. NSMenuItem* item = findMenuItem ([NSApp mainMenu], info);
  222480. if (item != 0)
  222481. flashMenuBar ([item menu]);
  222482. }
  222483. void updateMenus()
  222484. {
  222485. if (Time::getMillisecondCounter() > lastUpdateTime + 500)
  222486. menuBarItemsChanged (0);
  222487. }
  222488. void invoke (const int commandId, ApplicationCommandManager* const commandManager, const int topLevelIndex) const
  222489. {
  222490. if (currentModel != 0)
  222491. {
  222492. if (commandManager != 0)
  222493. {
  222494. ApplicationCommandTarget::InvocationInfo info (commandId);
  222495. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromMenu;
  222496. commandManager->invoke (info, true);
  222497. }
  222498. currentModel->menuItemSelected (commandId, topLevelIndex);
  222499. }
  222500. }
  222501. MenuBarModel* currentModel;
  222502. uint32 lastUpdateTime;
  222503. void addMenuItem (PopupMenu::MenuItemIterator& iter, NSMenu* menuToAddTo,
  222504. const int topLevelMenuId, const int topLevelIndex)
  222505. {
  222506. NSString* text = juceStringToNS (iter.itemName.upToFirstOccurrenceOf (T("<end>"), false, true));
  222507. if (text == 0)
  222508. text = @"";
  222509. if (iter.isSeparator)
  222510. {
  222511. [menuToAddTo addItem: [NSMenuItem separatorItem]];
  222512. }
  222513. else if (iter.isSectionHeader)
  222514. {
  222515. NSMenuItem* item = [menuToAddTo addItemWithTitle: text
  222516. action: nil
  222517. keyEquivalent: @""];
  222518. [item setEnabled: false];
  222519. }
  222520. else if (iter.subMenu != 0)
  222521. {
  222522. NSMenuItem* item = [menuToAddTo addItemWithTitle: text
  222523. action: nil
  222524. keyEquivalent: @""];
  222525. [item setTag: iter.itemId];
  222526. [item setEnabled: iter.isEnabled];
  222527. NSMenu* sub = createMenu (*iter.subMenu, iter.itemName, topLevelMenuId, topLevelIndex);
  222528. [sub setDelegate: nil];
  222529. [menuToAddTo setSubmenu: sub forItem: item];
  222530. }
  222531. else
  222532. {
  222533. NSMenuItem* item = [menuToAddTo addItemWithTitle: text
  222534. action: @selector (menuItemInvoked:)
  222535. keyEquivalent: @""];
  222536. [item setTag: iter.itemId];
  222537. [item setEnabled: iter.isEnabled];
  222538. [item setState: iter.isTicked ? NSOnState : NSOffState];
  222539. [item setTarget: (id) callback];
  222540. NSMutableArray* info = [NSMutableArray arrayWithObject: [NSNumber numberWithUnsignedLongLong: (pointer_sized_int) (void*) iter.commandManager]];
  222541. [info addObject: [NSNumber numberWithInt: topLevelIndex]];
  222542. [item setRepresentedObject: info];
  222543. if (iter.commandManager != 0)
  222544. {
  222545. const Array <KeyPress> keyPresses (iter.commandManager->getKeyMappings()
  222546. ->getKeyPressesAssignedToCommand (iter.itemId));
  222547. if (keyPresses.size() > 0)
  222548. {
  222549. const KeyPress& kp = keyPresses.getReference(0);
  222550. juce_wchar key = kp.getTextCharacter();
  222551. if (kp.getKeyCode() == KeyPress::backspaceKey)
  222552. key = NSBackspaceCharacter;
  222553. else if (kp.getKeyCode() == KeyPress::deleteKey)
  222554. key = NSDeleteCharacter;
  222555. else if (key == 0)
  222556. key = (juce_wchar) kp.getKeyCode();
  222557. unsigned int mods = 0;
  222558. if (kp.getModifiers().isShiftDown())
  222559. mods |= NSShiftKeyMask;
  222560. if (kp.getModifiers().isCtrlDown())
  222561. mods |= NSControlKeyMask;
  222562. if (kp.getModifiers().isAltDown())
  222563. mods |= NSAlternateKeyMask;
  222564. if (kp.getModifiers().isCommandDown())
  222565. mods |= NSCommandKeyMask;
  222566. [item setKeyEquivalent: juceStringToNS (String::charToString (key))];
  222567. [item setKeyEquivalentModifierMask: mods];
  222568. }
  222569. }
  222570. }
  222571. }
  222572. JuceMenuCallback* callback;
  222573. private:
  222574. NSMenu* createMenu (const PopupMenu menu,
  222575. const String& menuName,
  222576. const int topLevelMenuId,
  222577. const int topLevelIndex)
  222578. {
  222579. NSMenu* m = [[NSMenu alloc] initWithTitle: juceStringToNS (menuName)];
  222580. [m setAutoenablesItems: false];
  222581. [m setDelegate: callback];
  222582. PopupMenu::MenuItemIterator iter (menu);
  222583. while (iter.next())
  222584. addMenuItem (iter, m, topLevelMenuId, topLevelIndex);
  222585. [m update];
  222586. return m;
  222587. }
  222588. };
  222589. JuceMainMenuHandler* JuceMainMenuHandler::instance = 0;
  222590. END_JUCE_NAMESPACE
  222591. @implementation JuceMenuCallback
  222592. - (JuceMenuCallback*) initWithOwner: (JuceMainMenuHandler*) owner_
  222593. {
  222594. [super init];
  222595. owner = owner_;
  222596. return self;
  222597. }
  222598. - (void) dealloc
  222599. {
  222600. [super dealloc];
  222601. }
  222602. - (void) menuItemInvoked: (id) menu
  222603. {
  222604. NSMenuItem* item = (NSMenuItem*) menu;
  222605. if ([[item representedObject] isKindOfClass: [NSArray class]])
  222606. {
  222607. NSArray* info = (NSArray*) [item representedObject];
  222608. owner->invoke ([item tag],
  222609. (ApplicationCommandManager*) (pointer_sized_int)
  222610. [((NSNumber*) [info objectAtIndex: 0]) unsignedLongLongValue],
  222611. (int) [((NSNumber*) [info objectAtIndex: 1]) intValue]);
  222612. }
  222613. }
  222614. - (void) menuNeedsUpdate: (NSMenu*) menu;
  222615. {
  222616. if (JuceMainMenuHandler::instance != 0)
  222617. JuceMainMenuHandler::instance->updateMenus();
  222618. }
  222619. @end
  222620. BEGIN_JUCE_NAMESPACE
  222621. static NSMenu* createStandardAppMenu (NSMenu* menu, const String& appName,
  222622. const PopupMenu* extraItems)
  222623. {
  222624. if (extraItems != 0 && JuceMainMenuHandler::instance != 0 && extraItems->getNumItems() > 0)
  222625. {
  222626. PopupMenu::MenuItemIterator iter (*extraItems);
  222627. while (iter.next())
  222628. JuceMainMenuHandler::instance->addMenuItem (iter, menu, 0, -1);
  222629. [menu addItem: [NSMenuItem separatorItem]];
  222630. }
  222631. NSMenuItem* item;
  222632. // Services...
  222633. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (@"Services", nil)
  222634. action: nil keyEquivalent: @""];
  222635. [menu addItem: item];
  222636. [item release];
  222637. NSMenu* servicesMenu = [[NSMenu alloc] initWithTitle: @"Services"];
  222638. [menu setSubmenu: servicesMenu forItem: item];
  222639. [NSApp setServicesMenu: servicesMenu];
  222640. [servicesMenu release];
  222641. [menu addItem: [NSMenuItem separatorItem]];
  222642. // Hide + Show stuff...
  222643. item = [[NSMenuItem alloc] initWithTitle: juceStringToNS ("Hide " + appName)
  222644. action: @selector (hide:) keyEquivalent: @"h"];
  222645. [item setTarget: NSApp];
  222646. [menu addItem: item];
  222647. [item release];
  222648. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (@"Hide Others", nil)
  222649. action: @selector (hideOtherApplications:) keyEquivalent: @"h"];
  222650. [item setKeyEquivalentModifierMask: NSCommandKeyMask | NSAlternateKeyMask];
  222651. [item setTarget: NSApp];
  222652. [menu addItem: item];
  222653. [item release];
  222654. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (@"Show All", nil)
  222655. action: @selector (unhideAllApplications:) keyEquivalent: @""];
  222656. [item setTarget: NSApp];
  222657. [menu addItem: item];
  222658. [item release];
  222659. [menu addItem: [NSMenuItem separatorItem]];
  222660. // Quit item....
  222661. item = [[NSMenuItem alloc] initWithTitle: juceStringToNS ("Quit " + appName)
  222662. action: @selector (terminate:) keyEquivalent: @"q"];
  222663. [item setTarget: NSApp];
  222664. [menu addItem: item];
  222665. [item release];
  222666. return menu;
  222667. }
  222668. // Since our app has no NIB, this initialises a standard app menu...
  222669. static void rebuildMainMenu (const PopupMenu* extraItems)
  222670. {
  222671. // this can't be used in a plugin!
  222672. jassert (JUCEApplication::getInstance() != 0);
  222673. if (JUCEApplication::getInstance() != 0)
  222674. {
  222675. const ScopedAutoReleasePool pool;
  222676. NSMenu* mainMenu = [[NSMenu alloc] initWithTitle: @"MainMenu"];
  222677. NSMenuItem* item = [mainMenu addItemWithTitle: @"Apple" action: nil keyEquivalent: @""];
  222678. NSMenu* appMenu = [[NSMenu alloc] initWithTitle: @"Apple"];
  222679. [NSApp performSelector: @selector (setAppleMenu:) withObject: appMenu];
  222680. [mainMenu setSubmenu: appMenu forItem: item];
  222681. [NSApp setMainMenu: mainMenu];
  222682. createStandardAppMenu (appMenu, JUCEApplication::getInstance()->getApplicationName(), extraItems);
  222683. [appMenu release];
  222684. [mainMenu release];
  222685. }
  222686. }
  222687. void MenuBarModel::setMacMainMenu (MenuBarModel* newMenuBarModel,
  222688. const PopupMenu* extraAppleMenuItems) throw()
  222689. {
  222690. if (getMacMainMenu() != newMenuBarModel)
  222691. {
  222692. const ScopedAutoReleasePool pool;
  222693. if (newMenuBarModel == 0)
  222694. {
  222695. delete JuceMainMenuHandler::instance;
  222696. jassert (JuceMainMenuHandler::instance == 0); // should be zeroed in the destructor
  222697. jassert (extraAppleMenuItems == 0); // you can't specify some extra items without also supplying a model
  222698. extraAppleMenuItems = 0;
  222699. }
  222700. else
  222701. {
  222702. if (JuceMainMenuHandler::instance == 0)
  222703. JuceMainMenuHandler::instance = new JuceMainMenuHandler();
  222704. JuceMainMenuHandler::instance->setMenu (newMenuBarModel);
  222705. }
  222706. }
  222707. rebuildMainMenu (extraAppleMenuItems);
  222708. if (newMenuBarModel != 0)
  222709. newMenuBarModel->menuItemsChanged();
  222710. }
  222711. MenuBarModel* MenuBarModel::getMacMainMenu() throw()
  222712. {
  222713. return JuceMainMenuHandler::instance != 0
  222714. ? JuceMainMenuHandler::instance->currentModel : 0;
  222715. }
  222716. void initialiseMainMenu()
  222717. {
  222718. if (JUCEApplication::getInstance() != 0) // only needed in an app
  222719. rebuildMainMenu (0);
  222720. }
  222721. #endif
  222722. /********* End of inlined file: juce_mac_MainMenu.mm *********/
  222723. /********* Start of inlined file: juce_mac_FileChooser.mm *********/
  222724. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  222725. // compiled on its own).
  222726. #ifdef JUCE_INCLUDED_FILE
  222727. END_JUCE_NAMESPACE
  222728. using namespace JUCE_NAMESPACE;
  222729. #define JuceFileChooserDelegate MakeObjCClassName(JuceFileChooserDelegate)
  222730. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  222731. @interface JuceFileChooserDelegate : NSObject <NSOpenSavePanelDelegate>
  222732. #else
  222733. @interface JuceFileChooserDelegate : NSObject
  222734. #endif
  222735. {
  222736. StringArray* filters;
  222737. }
  222738. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_;
  222739. - (void) dealloc;
  222740. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename;
  222741. @end
  222742. @implementation JuceFileChooserDelegate
  222743. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_
  222744. {
  222745. [super init];
  222746. filters = filters_;
  222747. return self;
  222748. }
  222749. - (void) dealloc
  222750. {
  222751. delete filters;
  222752. [super dealloc];
  222753. }
  222754. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename
  222755. {
  222756. const String fname (nsStringToJuce (filename));
  222757. for (int i = filters->size(); --i >= 0;)
  222758. if (fname.matchesWildcard ((*filters)[i], true))
  222759. return true;
  222760. return File (fname).isDirectory();
  222761. }
  222762. @end
  222763. BEGIN_JUCE_NAMESPACE
  222764. void FileChooser::showPlatformDialog (OwnedArray<File>& results,
  222765. const String& title,
  222766. const File& currentFileOrDirectory,
  222767. const String& filter,
  222768. bool selectsDirectory,
  222769. bool isSaveDialogue,
  222770. bool warnAboutOverwritingExistingFiles,
  222771. bool selectMultipleFiles,
  222772. FilePreviewComponent* extraInfoComponent)
  222773. {
  222774. const ScopedAutoReleasePool pool;
  222775. StringArray* filters = new StringArray();
  222776. filters->addTokens (filter.replaceCharacters (T(",:"), T(";;")), T(";"), 0);
  222777. filters->trim();
  222778. filters->removeEmptyStrings();
  222779. JuceFileChooserDelegate* delegate = [[JuceFileChooserDelegate alloc] initWithFilters: filters];
  222780. [delegate autorelease];
  222781. NSSavePanel* panel = isSaveDialogue ? [NSSavePanel savePanel]
  222782. : [NSOpenPanel openPanel];
  222783. [panel setTitle: juceStringToNS (title)];
  222784. if (! isSaveDialogue)
  222785. {
  222786. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  222787. [openPanel setCanChooseDirectories: selectsDirectory];
  222788. [openPanel setCanChooseFiles: ! selectsDirectory];
  222789. [openPanel setAllowsMultipleSelection: selectMultipleFiles];
  222790. }
  222791. [panel setDelegate: delegate];
  222792. String directory, filename;
  222793. if (currentFileOrDirectory.isDirectory())
  222794. {
  222795. directory = currentFileOrDirectory.getFullPathName();
  222796. }
  222797. else
  222798. {
  222799. directory = currentFileOrDirectory.getParentDirectory().getFullPathName();
  222800. filename = currentFileOrDirectory.getFileName();
  222801. }
  222802. if ([panel runModalForDirectory: juceStringToNS (directory)
  222803. file: juceStringToNS (filename)]
  222804. == NSOKButton)
  222805. {
  222806. if (isSaveDialogue)
  222807. {
  222808. results.add (new File (nsStringToJuce ([panel filename])));
  222809. }
  222810. else
  222811. {
  222812. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  222813. NSArray* urls = [openPanel filenames];
  222814. for (unsigned int i = 0; i < [urls count]; ++i)
  222815. {
  222816. NSString* f = [urls objectAtIndex: i];
  222817. results.add (new File (nsStringToJuce (f)));
  222818. }
  222819. }
  222820. }
  222821. [panel setDelegate: nil];
  222822. }
  222823. #endif
  222824. /********* End of inlined file: juce_mac_FileChooser.mm *********/
  222825. /********* Start of inlined file: juce_mac_QuickTimeMovieComponent.mm *********/
  222826. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  222827. // compiled on its own).
  222828. #if JUCE_INCLUDED_FILE && JUCE_QUICKTIME
  222829. #define theMovie ((QTMovie*) movie)
  222830. QuickTimeMovieComponent::QuickTimeMovieComponent()
  222831. : movie (0)
  222832. {
  222833. setOpaque (true);
  222834. setVisible (true);
  222835. QTMovieView* view = [[QTMovieView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)];
  222836. setView (view);
  222837. }
  222838. QuickTimeMovieComponent::~QuickTimeMovieComponent()
  222839. {
  222840. closeMovie();
  222841. setView (0);
  222842. }
  222843. bool QuickTimeMovieComponent::isQuickTimeAvailable() throw()
  222844. {
  222845. return true;
  222846. }
  222847. static QTMovie* openMovieFromStream (InputStream* movieStream, File& movieFile)
  222848. {
  222849. // unfortunately, QTMovie objects can only be created on the main thread..
  222850. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  222851. QTMovie* movie = 0;
  222852. FileInputStream* const fin = dynamic_cast <FileInputStream*> (movieStream);
  222853. if (fin != 0)
  222854. {
  222855. movieFile = fin->getFile();
  222856. movie = [QTMovie movieWithFile: juceStringToNS (movieFile.getFullPathName())
  222857. error: nil];
  222858. }
  222859. else
  222860. {
  222861. MemoryBlock temp;
  222862. movieStream->readIntoMemoryBlock (temp);
  222863. const char* const suffixesToTry[] = { ".mov", ".mp3", ".avi", ".m4a" };
  222864. for (int i = 0; i < numElementsInArray (suffixesToTry); ++i)
  222865. {
  222866. movie = [QTMovie movieWithDataReference: [QTDataReference dataReferenceWithReferenceToData: [NSData dataWithBytes: temp.getData()
  222867. length: temp.getSize()]
  222868. name: [NSString stringWithUTF8String: suffixesToTry[i]]
  222869. MIMEType: @""]
  222870. error: nil];
  222871. if (movie != 0)
  222872. break;
  222873. }
  222874. }
  222875. return movie;
  222876. }
  222877. bool QuickTimeMovieComponent::loadMovie (InputStream* movieStream,
  222878. const bool controllerVisible)
  222879. {
  222880. closeMovie();
  222881. if (getPeer() == 0)
  222882. {
  222883. // To open a movie, this component must be visible inside a functioning window, so that
  222884. // the QT control can be assigned to the window.
  222885. jassertfalse
  222886. return false;
  222887. }
  222888. movie = openMovieFromStream (movieStream, movieFile);
  222889. [theMovie retain];
  222890. QTMovieView* view = (QTMovieView*) getView();
  222891. [view setMovie: theMovie];
  222892. [view setControllerVisible: controllerVisible];
  222893. setLooping (looping);
  222894. return movie != nil;
  222895. }
  222896. void QuickTimeMovieComponent::closeMovie()
  222897. {
  222898. stop();
  222899. QTMovieView* view = (QTMovieView*) getView();
  222900. [view setMovie: nil];
  222901. [theMovie release];
  222902. movie = 0;
  222903. movieFile = File::nonexistent;
  222904. }
  222905. bool QuickTimeMovieComponent::isMovieOpen() const
  222906. {
  222907. return movie != nil;
  222908. }
  222909. const File QuickTimeMovieComponent::getCurrentMovieFile() const
  222910. {
  222911. return movieFile;
  222912. }
  222913. void QuickTimeMovieComponent::play()
  222914. {
  222915. [theMovie play];
  222916. }
  222917. void QuickTimeMovieComponent::stop()
  222918. {
  222919. [theMovie stop];
  222920. }
  222921. bool QuickTimeMovieComponent::isPlaying() const
  222922. {
  222923. return movie != 0 && [theMovie rate] != 0;
  222924. }
  222925. void QuickTimeMovieComponent::setPosition (const double seconds)
  222926. {
  222927. if (movie != 0)
  222928. {
  222929. QTTime t;
  222930. t.timeValue = (uint64) (100000.0 * seconds);
  222931. t.timeScale = 100000;
  222932. t.flags = 0;
  222933. [theMovie setCurrentTime: t];
  222934. }
  222935. }
  222936. double QuickTimeMovieComponent::getPosition() const
  222937. {
  222938. if (movie == 0)
  222939. return 0.0;
  222940. QTTime t = [theMovie currentTime];
  222941. return t.timeValue / (double) t.timeScale;
  222942. }
  222943. void QuickTimeMovieComponent::setSpeed (const float newSpeed)
  222944. {
  222945. [theMovie setRate: newSpeed];
  222946. }
  222947. double QuickTimeMovieComponent::getMovieDuration() const
  222948. {
  222949. if (movie == 0)
  222950. return 0.0;
  222951. QTTime t = [theMovie duration];
  222952. return t.timeValue / (double) t.timeScale;
  222953. }
  222954. void QuickTimeMovieComponent::setLooping (const bool shouldLoop)
  222955. {
  222956. looping = shouldLoop;
  222957. [theMovie setAttribute: [NSNumber numberWithBool: shouldLoop]
  222958. forKey: QTMovieLoopsAttribute];
  222959. }
  222960. bool QuickTimeMovieComponent::isLooping() const
  222961. {
  222962. return looping;
  222963. }
  222964. void QuickTimeMovieComponent::setMovieVolume (const float newVolume)
  222965. {
  222966. [theMovie setVolume: newVolume];
  222967. }
  222968. float QuickTimeMovieComponent::getMovieVolume() const
  222969. {
  222970. return movie != 0 ? [theMovie volume] : 0.0f;
  222971. }
  222972. void QuickTimeMovieComponent::getMovieNormalSize (int& width, int& height) const
  222973. {
  222974. width = 0;
  222975. height = 0;
  222976. if (movie != 0)
  222977. {
  222978. NSSize s = [[theMovie attributeForKey: QTMovieNaturalSizeAttribute] sizeValue];
  222979. width = s.width;
  222980. height = s.height;
  222981. }
  222982. }
  222983. void QuickTimeMovieComponent::paint (Graphics& g)
  222984. {
  222985. if (movie == 0)
  222986. g.fillAll (Colours::black);
  222987. }
  222988. bool QuickTimeMovieComponent::isControllerVisible() const
  222989. {
  222990. return controllerVisible;
  222991. }
  222992. bool QuickTimeMovieComponent::loadMovie (const File& movieFile_,
  222993. const bool isControllerVisible)
  222994. {
  222995. const bool ok = loadMovie ((InputStream*) movieFile_.createInputStream(), isControllerVisible);
  222996. movieFile = movieFile_;
  222997. return ok;
  222998. }
  222999. void QuickTimeMovieComponent::goToStart()
  223000. {
  223001. setPosition (0.0);
  223002. }
  223003. void QuickTimeMovieComponent::setBoundsWithCorrectAspectRatio (const Rectangle& spaceToFitWithin,
  223004. const RectanglePlacement& placement)
  223005. {
  223006. int normalWidth, normalHeight;
  223007. getMovieNormalSize (normalWidth, normalHeight);
  223008. if (normalWidth > 0 && normalHeight > 0 && ! spaceToFitWithin.isEmpty())
  223009. {
  223010. double x = 0.0, y = 0.0, w = normalWidth, h = normalHeight;
  223011. placement.applyTo (x, y, w, h,
  223012. spaceToFitWithin.getX(), spaceToFitWithin.getY(),
  223013. spaceToFitWithin.getWidth(), spaceToFitWithin.getHeight());
  223014. if (w > 0 && h > 0)
  223015. {
  223016. setBounds (roundDoubleToInt (x), roundDoubleToInt (y),
  223017. roundDoubleToInt (w), roundDoubleToInt (h));
  223018. }
  223019. }
  223020. else
  223021. {
  223022. setBounds (spaceToFitWithin);
  223023. }
  223024. }
  223025. #if ! (JUCE_MAC && JUCE_64BIT)
  223026. bool juce_OpenQuickTimeMovieFromStream (InputStream* movieStream, Movie& result, Handle& dataHandle)
  223027. {
  223028. if (movieStream == 0)
  223029. return false;
  223030. File file;
  223031. QTMovie* movie = openMovieFromStream (movieStream, file);
  223032. if (movie != nil)
  223033. result = [movie quickTimeMovie];
  223034. return movie != nil;
  223035. }
  223036. #endif
  223037. #endif
  223038. /********* End of inlined file: juce_mac_QuickTimeMovieComponent.mm *********/
  223039. /********* Start of inlined file: juce_mac_AudioCDBurner.mm *********/
  223040. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  223041. // compiled on its own).
  223042. #if JUCE_INCLUDED_FILE && JUCE_USE_CDBURNER
  223043. END_JUCE_NAMESPACE
  223044. #define OpenDiskDevice MakeObjCClassName(OpenDiskDevice)
  223045. @interface OpenDiskDevice : NSObject
  223046. {
  223047. DRDevice* device;
  223048. NSMutableArray* tracks;
  223049. }
  223050. - (OpenDiskDevice*) initWithDevice: (DRDevice*) device;
  223051. - (void) dealloc;
  223052. - (bool) isDiskPresent;
  223053. - (int) getNumAvailableAudioBlocks;
  223054. - (void) addSourceTrack: (JUCE_NAMESPACE::AudioSource*) source numSamples: (int) numSamples_;
  223055. - (void) burn: (JUCE_NAMESPACE::AudioCDBurner::BurnProgressListener*) listener errorString: (JUCE_NAMESPACE::String*) error
  223056. ejectAfterwards: (bool) shouldEject isFake: (bool) peformFakeBurnForTesting;
  223057. @end
  223058. #define AudioTrackProducer MakeObjCClassName(AudioTrackProducer)
  223059. @interface AudioTrackProducer : NSObject
  223060. {
  223061. JUCE_NAMESPACE::AudioSource* source;
  223062. int readPosition, lengthInFrames;
  223063. }
  223064. - (AudioTrackProducer*) init: (int) lengthInFrames;
  223065. - (AudioTrackProducer*) initWithAudioSource: (JUCE_NAMESPACE::AudioSource*) source numSamples: (int) lengthInSamples;
  223066. - (void) dealloc;
  223067. - (void) setupTrackProperties: (DRTrack*) track;
  223068. - (void) cleanupTrackAfterBurn: (DRTrack*) track;
  223069. - (BOOL) cleanupTrackAfterVerification:(DRTrack*)track;
  223070. - (uint64_t) estimateLengthOfTrack:(DRTrack*)track;
  223071. - (BOOL) prepareTrack:(DRTrack*)track forBurn:(DRBurn*)burn
  223072. toMedia:(NSDictionary*)mediaInfo;
  223073. - (BOOL) prepareTrackForVerification:(DRTrack*)track;
  223074. - (uint32_t) produceDataForTrack:(DRTrack*)track intoBuffer:(char*)buffer
  223075. length:(uint32_t)bufferLength atAddress:(uint64_t)address
  223076. blockSize:(uint32_t)blockSize ioFlags:(uint32_t*)flags;
  223077. - (uint32_t) producePreGapForTrack:(DRTrack*)track
  223078. intoBuffer:(char*)buffer length:(uint32_t)bufferLength
  223079. atAddress:(uint64_t)address blockSize:(uint32_t)blockSize
  223080. ioFlags:(uint32_t*)flags;
  223081. - (BOOL) verifyDataForTrack:(DRTrack*)track inBuffer:(const char*)buffer
  223082. length:(uint32_t)bufferLength atAddress:(uint64_t)address
  223083. blockSize:(uint32_t)blockSize ioFlags:(uint32_t*)flags;
  223084. - (uint32_t) producePreGapForTrack:(DRTrack*)track
  223085. intoBuffer:(char*)buffer length:(uint32_t)bufferLength
  223086. atAddress:(uint64_t)address blockSize:(uint32_t)blockSize
  223087. ioFlags:(uint32_t*)flags;
  223088. @end
  223089. @implementation OpenDiskDevice
  223090. - (OpenDiskDevice*) initWithDevice: (DRDevice*) device_
  223091. {
  223092. [super init];
  223093. device = device_;
  223094. tracks = [[NSMutableArray alloc] init];
  223095. return self;
  223096. }
  223097. - (void) dealloc
  223098. {
  223099. [tracks release];
  223100. [super dealloc];
  223101. }
  223102. - (bool) isDiskPresent
  223103. {
  223104. return [device isValid]
  223105. && [[[device status] objectForKey: DRDeviceMediaStateKey]
  223106. isEqualTo: DRDeviceMediaStateMediaPresent];
  223107. }
  223108. - (int) getNumAvailableAudioBlocks
  223109. {
  223110. return [[[[device status] objectForKey: DRDeviceMediaInfoKey]
  223111. objectForKey: DRDeviceMediaBlocksFreeKey] intValue];
  223112. }
  223113. - (void) addSourceTrack: (JUCE_NAMESPACE::AudioSource*) source_ numSamples: (int) numSamples_
  223114. {
  223115. AudioTrackProducer* p = [[AudioTrackProducer alloc] initWithAudioSource: source_ numSamples: numSamples_];
  223116. DRTrack* t = [[DRTrack alloc] initWithProducer: p];
  223117. [p setupTrackProperties: t];
  223118. [tracks addObject: t];
  223119. [t release];
  223120. [p release];
  223121. }
  223122. - (void) burn: (JUCE_NAMESPACE::AudioCDBurner::BurnProgressListener*) listener errorString: (JUCE_NAMESPACE::String*) error
  223123. ejectAfterwards: (bool) shouldEject isFake: (bool) peformFakeBurnForTesting
  223124. {
  223125. DRBurn* burn = [DRBurn burnForDevice: device];
  223126. if (! [device acquireExclusiveAccess])
  223127. {
  223128. *error = "Couldn't open or write to the CD device";
  223129. return;
  223130. }
  223131. [device acquireMediaReservation];
  223132. NSMutableDictionary* d = [[burn properties] mutableCopy];
  223133. [d autorelease];
  223134. [d setObject: [NSNumber numberWithBool: peformFakeBurnForTesting] forKey: DRBurnTestingKey];
  223135. [d setObject: [NSNumber numberWithBool: false] forKey: DRBurnVerifyDiscKey];
  223136. [d setObject: (shouldEject ? DRBurnCompletionActionEject : DRBurnCompletionActionMount)
  223137. forKey: DRBurnCompletionActionKey];
  223138. [burn setProperties: d];
  223139. [burn writeLayout: tracks];
  223140. for (;;)
  223141. {
  223142. JUCE_NAMESPACE::Thread::sleep (300);
  223143. float progress = [[[burn status] objectForKey: DRStatusPercentCompleteKey] floatValue];
  223144. if (listener != 0 && listener->audioCDBurnProgress (progress))
  223145. {
  223146. [burn abort];
  223147. *error = "User cancelled the write operation";
  223148. break;
  223149. }
  223150. if ([[[burn status] objectForKey: DRStatusStateKey] isEqualTo: DRStatusStateFailed])
  223151. {
  223152. *error = "Write operation failed";
  223153. break;
  223154. }
  223155. else if ([[[burn status] objectForKey: DRStatusStateKey] isEqualTo: DRStatusStateDone])
  223156. {
  223157. break;
  223158. }
  223159. NSString* err = (NSString*) [[[burn status] objectForKey: DRErrorStatusKey]
  223160. objectForKey: DRErrorStatusErrorStringKey];
  223161. if ([err length] > 0)
  223162. {
  223163. *error = JUCE_NAMESPACE::String::fromUTF8 ((JUCE_NAMESPACE::uint8*) [err UTF8String]);
  223164. break;
  223165. }
  223166. }
  223167. [device releaseMediaReservation];
  223168. [device releaseExclusiveAccess];
  223169. }
  223170. @end
  223171. @implementation AudioTrackProducer
  223172. - (AudioTrackProducer*) init: (int) lengthInFrames_
  223173. {
  223174. lengthInFrames = lengthInFrames_;
  223175. readPosition = 0;
  223176. return self;
  223177. }
  223178. - (void) setupTrackProperties: (DRTrack*) track
  223179. {
  223180. NSMutableDictionary* p = [[track properties] mutableCopy];
  223181. [p setObject:[DRMSF msfWithFrames: lengthInFrames] forKey: DRTrackLengthKey];
  223182. [p setObject:[NSNumber numberWithUnsignedShort:2352] forKey: DRBlockSizeKey];
  223183. [p setObject:[NSNumber numberWithInt:0] forKey: DRDataFormKey];
  223184. [p setObject:[NSNumber numberWithInt:0] forKey: DRBlockTypeKey];
  223185. [p setObject:[NSNumber numberWithInt:0] forKey: DRTrackModeKey];
  223186. [p setObject:[NSNumber numberWithInt:0] forKey: DRSessionFormatKey];
  223187. [track setProperties: p];
  223188. [p release];
  223189. }
  223190. - (AudioTrackProducer*) initWithAudioSource: (JUCE_NAMESPACE::AudioSource*) source_ numSamples: (int) lengthInSamples
  223191. {
  223192. AudioTrackProducer* s = [self init: (lengthInSamples + 587) / 588];
  223193. if (s != nil)
  223194. s->source = source_;
  223195. return s;
  223196. }
  223197. - (void) dealloc
  223198. {
  223199. if (source != 0)
  223200. {
  223201. source->releaseResources();
  223202. delete source;
  223203. }
  223204. [super dealloc];
  223205. }
  223206. - (void) cleanupTrackAfterBurn: (DRTrack*) track
  223207. {
  223208. }
  223209. - (BOOL) cleanupTrackAfterVerification: (DRTrack*) track
  223210. {
  223211. return true;
  223212. }
  223213. - (uint64_t) estimateLengthOfTrack: (DRTrack*) track
  223214. {
  223215. return lengthInFrames;
  223216. }
  223217. - (BOOL) prepareTrack: (DRTrack*) track forBurn: (DRBurn*) burn
  223218. toMedia: (NSDictionary*) mediaInfo
  223219. {
  223220. if (source != 0)
  223221. source->prepareToPlay (44100 / 75, 44100);
  223222. readPosition = 0;
  223223. return true;
  223224. }
  223225. - (BOOL) prepareTrackForVerification: (DRTrack*) track
  223226. {
  223227. if (source != 0)
  223228. source->prepareToPlay (44100 / 75, 44100);
  223229. return true;
  223230. }
  223231. - (uint32_t) produceDataForTrack: (DRTrack*) track intoBuffer: (char*) buffer
  223232. length: (uint32_t) bufferLength atAddress: (uint64_t) address
  223233. blockSize: (uint32_t) blockSize ioFlags: (uint32_t*) flags
  223234. {
  223235. if (source != 0)
  223236. {
  223237. const int numSamples = JUCE_NAMESPACE::jmin (bufferLength / 4, (lengthInFrames * (44100 / 75)) - readPosition);
  223238. if (numSamples > 0)
  223239. {
  223240. JUCE_NAMESPACE::AudioSampleBuffer tempBuffer (2, numSamples);
  223241. JUCE_NAMESPACE::AudioSourceChannelInfo info;
  223242. info.buffer = &tempBuffer;
  223243. info.startSample = 0;
  223244. info.numSamples = numSamples;
  223245. source->getNextAudioBlock (info);
  223246. JUCE_NAMESPACE::AudioDataConverters::convertFloatToInt16LE (tempBuffer.getSampleData (0),
  223247. buffer, numSamples, 4);
  223248. JUCE_NAMESPACE::AudioDataConverters::convertFloatToInt16LE (tempBuffer.getSampleData (1),
  223249. buffer + 2, numSamples, 4);
  223250. readPosition += numSamples;
  223251. }
  223252. return numSamples * 4;
  223253. }
  223254. return 0;
  223255. }
  223256. - (uint32_t) producePreGapForTrack: (DRTrack*) track
  223257. intoBuffer: (char*) buffer length: (uint32_t) bufferLength
  223258. atAddress: (uint64_t) address blockSize: (uint32_t) blockSize
  223259. ioFlags: (uint32_t*) flags
  223260. {
  223261. zeromem (buffer, bufferLength);
  223262. return bufferLength;
  223263. }
  223264. - (BOOL) verifyDataForTrack: (DRTrack*) track inBuffer: (const char*) buffer
  223265. length: (uint32_t) bufferLength atAddress: (uint64_t) address
  223266. blockSize: (uint32_t) blockSize ioFlags: (uint32_t*) flags
  223267. {
  223268. return true;
  223269. }
  223270. @end
  223271. BEGIN_JUCE_NAMESPACE
  223272. AudioCDBurner::AudioCDBurner (const int deviceIndex)
  223273. : internal (0)
  223274. {
  223275. OpenDiskDevice* dev = [[OpenDiskDevice alloc] initWithDevice: [[DRDevice devices] objectAtIndex: deviceIndex]];
  223276. internal = (void*) dev;
  223277. }
  223278. AudioCDBurner::~AudioCDBurner()
  223279. {
  223280. OpenDiskDevice* dev = (OpenDiskDevice*) internal;
  223281. if (dev != 0)
  223282. [dev release];
  223283. }
  223284. AudioCDBurner* AudioCDBurner::openDevice (const int deviceIndex)
  223285. {
  223286. AudioCDBurner* b = new AudioCDBurner (deviceIndex);
  223287. if (b->internal == 0)
  223288. deleteAndZero (b);
  223289. return b;
  223290. }
  223291. static NSArray* findDiskBurnerDevices()
  223292. {
  223293. NSMutableArray* results = [NSMutableArray array];
  223294. NSArray* devs = [DRDevice devices];
  223295. if (devs != 0)
  223296. {
  223297. int num = [devs count];
  223298. int i;
  223299. for (i = 0; i < num; ++i)
  223300. {
  223301. NSDictionary* dic = [[devs objectAtIndex: i] info];
  223302. NSString* name = [dic valueForKey: DRDeviceProductNameKey];
  223303. if (name != nil)
  223304. [results addObject: name];
  223305. }
  223306. }
  223307. return results;
  223308. }
  223309. const StringArray AudioCDBurner::findAvailableDevices()
  223310. {
  223311. NSArray* names = findDiskBurnerDevices();
  223312. StringArray s;
  223313. for (unsigned int i = 0; i < [names count]; ++i)
  223314. s.add (String::fromUTF8 ((JUCE_NAMESPACE::uint8*) [[names objectAtIndex: i] UTF8String]));
  223315. return s;
  223316. }
  223317. bool AudioCDBurner::isDiskPresent() const
  223318. {
  223319. OpenDiskDevice* dev = (OpenDiskDevice*) internal;
  223320. return dev != 0 && [dev isDiskPresent];
  223321. }
  223322. int AudioCDBurner::getNumAvailableAudioBlocks() const
  223323. {
  223324. OpenDiskDevice* dev = (OpenDiskDevice*) internal;
  223325. return [dev getNumAvailableAudioBlocks];
  223326. }
  223327. bool AudioCDBurner::addAudioTrack (AudioSource* source, int numSamps)
  223328. {
  223329. OpenDiskDevice* dev = (OpenDiskDevice*) internal;
  223330. if (dev != 0)
  223331. {
  223332. [dev addSourceTrack: source numSamples: numSamps];
  223333. return true;
  223334. }
  223335. return false;
  223336. }
  223337. const String AudioCDBurner::burn (JUCE_NAMESPACE::AudioCDBurner::BurnProgressListener* listener,
  223338. const bool ejectDiscAfterwards,
  223339. const bool peformFakeBurnForTesting)
  223340. {
  223341. String error ("Couldn't open or write to the CD device");
  223342. OpenDiskDevice* dev = (OpenDiskDevice*) internal;
  223343. if (dev != 0)
  223344. {
  223345. error = String::empty;
  223346. [dev burn: listener
  223347. errorString: &error
  223348. ejectAfterwards: ejectDiscAfterwards
  223349. isFake: peformFakeBurnForTesting];
  223350. }
  223351. return error;
  223352. }
  223353. void AudioCDReader::ejectDisk()
  223354. {
  223355. const ScopedAutoReleasePool p;
  223356. [[NSWorkspace sharedWorkspace] unmountAndEjectDeviceAtPath: juceStringToNS (volumeDir.getFullPathName())];
  223357. }
  223358. #endif
  223359. /********* End of inlined file: juce_mac_AudioCDBurner.mm *********/
  223360. /********* Start of inlined file: juce_mac_Fonts.mm *********/
  223361. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  223362. // compiled on its own).
  223363. #ifdef JUCE_INCLUDED_FILE
  223364. class FontHelper
  223365. {
  223366. NSFont* font;
  223367. public:
  223368. String name;
  223369. bool isBold, isItalic, needsItalicTransform;
  223370. float fontSize, totalSize, ascent;
  223371. int refCount;
  223372. NSMutableDictionary* attributes;
  223373. FontHelper (const String& name_,
  223374. const bool bold_,
  223375. const bool italic_,
  223376. const float size_)
  223377. : font (0),
  223378. name (name_),
  223379. isBold (bold_),
  223380. isItalic (italic_),
  223381. needsItalicTransform (false),
  223382. fontSize (size_),
  223383. refCount (1)
  223384. {
  223385. attributes = [[NSMutableDictionary dictionaryWithObject: [NSNumber numberWithInt: 0]
  223386. forKey: NSLigatureAttributeName] retain];
  223387. font = [NSFont fontWithName: juceStringToNS (name_) size: size_];
  223388. if (italic_)
  223389. {
  223390. NSFont* newFont = [[NSFontManager sharedFontManager] convertFont: font toHaveTrait: NSItalicFontMask];
  223391. if (newFont == font)
  223392. needsItalicTransform = true; // couldn't find a proper italic version, so fake it with a transform..
  223393. font = newFont;
  223394. }
  223395. if (bold_)
  223396. font = [[NSFontManager sharedFontManager] convertFont: font toHaveTrait: NSBoldFontMask];
  223397. [font retain];
  223398. ascent = fabsf ([font ascender]);
  223399. totalSize = ascent + fabsf ([font descender]);
  223400. }
  223401. ~FontHelper()
  223402. {
  223403. [font release];
  223404. [attributes release];
  223405. }
  223406. bool getPathAndKerning (const juce_wchar char1,
  223407. const juce_wchar char2,
  223408. Path* path,
  223409. float& kerning,
  223410. float* ascent,
  223411. float* descent)
  223412. {
  223413. const ScopedAutoReleasePool pool;
  223414. if (font == 0
  223415. || ! [[font coveredCharacterSet] longCharacterIsMember: (UTF32Char) char1])
  223416. return false;
  223417. String chars;
  223418. chars << ' ' << char1 << char2;
  223419. NSTextStorage* textStorage = [[[NSTextStorage alloc] initWithString: juceStringToNS (chars)
  223420. attributes: attributes] autorelease];
  223421. NSLayoutManager* layoutManager = [[[NSLayoutManager alloc] init] autorelease];
  223422. NSTextContainer* textContainer = [[[NSTextContainer alloc] init] autorelease];
  223423. [layoutManager addTextContainer: textContainer];
  223424. [textStorage addLayoutManager: layoutManager];
  223425. [textStorage setFont: font];
  223426. unsigned int glyphIndex = [layoutManager glyphRangeForCharacterRange: NSMakeRange (1, 1)
  223427. actualCharacterRange: 0].location;
  223428. NSPoint p1 = [layoutManager locationForGlyphAtIndex: glyphIndex];
  223429. NSPoint p2 = [layoutManager locationForGlyphAtIndex: glyphIndex + 1];
  223430. kerning = p2.x - p1.x;
  223431. if (ascent != 0)
  223432. *ascent = this->ascent;
  223433. if (descent != 0)
  223434. *descent = fabsf ([font descender]);
  223435. if (path != 0)
  223436. {
  223437. NSBezierPath* bez = [NSBezierPath bezierPath];
  223438. [bez moveToPoint: NSMakePoint (0, 0)];
  223439. [bez appendBezierPathWithGlyph: [layoutManager glyphAtIndex: glyphIndex]
  223440. inFont: font];
  223441. for (int i = 0; i < [bez elementCount]; ++i)
  223442. {
  223443. NSPoint p[3];
  223444. switch ([bez elementAtIndex: i associatedPoints: p])
  223445. {
  223446. case NSMoveToBezierPathElement:
  223447. path->startNewSubPath (p[0].x, -p[0].y);
  223448. break;
  223449. case NSLineToBezierPathElement:
  223450. path->lineTo (p[0].x, -p[0].y);
  223451. break;
  223452. case NSCurveToBezierPathElement:
  223453. path->cubicTo (p[0].x, -p[0].y, p[1].x, -p[1].y, p[2].x, -p[2].y);
  223454. break;
  223455. case NSClosePathBezierPathElement:
  223456. path->closeSubPath();
  223457. break;
  223458. default:
  223459. jassertfalse
  223460. break;
  223461. }
  223462. }
  223463. if (needsItalicTransform)
  223464. path->applyTransform (AffineTransform::identity.sheared (-0.15, 0));
  223465. }
  223466. return kerning != 0;
  223467. }
  223468. juce_wchar getDefaultChar()
  223469. {
  223470. return 0;
  223471. }
  223472. };
  223473. class FontHelperCache : public Timer,
  223474. public DeletedAtShutdown
  223475. {
  223476. VoidArray cache;
  223477. public:
  223478. FontHelperCache()
  223479. {
  223480. }
  223481. ~FontHelperCache()
  223482. {
  223483. for (int i = cache.size(); --i >= 0;)
  223484. {
  223485. FontHelper* const f = (FontHelper*) cache.getUnchecked(i);
  223486. delete f;
  223487. }
  223488. clearSingletonInstance();
  223489. }
  223490. FontHelper* getFont (const String& name,
  223491. const bool bold,
  223492. const bool italic,
  223493. const float size = 1024)
  223494. {
  223495. for (int i = cache.size(); --i >= 0;)
  223496. {
  223497. FontHelper* const f = (FontHelper*) cache.getUnchecked(i);
  223498. if (f->name == name
  223499. && f->isBold == bold
  223500. && f->isItalic == italic
  223501. && f->fontSize == size)
  223502. {
  223503. f->refCount++;
  223504. return f;
  223505. }
  223506. }
  223507. FontHelper* const f = new FontHelper (name, bold, italic, size);
  223508. cache.add (f);
  223509. return f;
  223510. }
  223511. void releaseFont (FontHelper* f)
  223512. {
  223513. for (int i = cache.size(); --i >= 0;)
  223514. {
  223515. FontHelper* const f2 = (FontHelper*) cache.getUnchecked(i);
  223516. if (f == f2)
  223517. {
  223518. f->refCount--;
  223519. if (f->refCount == 0)
  223520. startTimer (5000);
  223521. break;
  223522. }
  223523. }
  223524. }
  223525. void timerCallback()
  223526. {
  223527. stopTimer();
  223528. for (int i = cache.size(); --i >= 0;)
  223529. {
  223530. FontHelper* const f = (FontHelper*) cache.getUnchecked(i);
  223531. if (f->refCount == 0)
  223532. {
  223533. cache.remove (i);
  223534. delete f;
  223535. }
  223536. }
  223537. if (cache.size() == 0)
  223538. delete this;
  223539. }
  223540. juce_DeclareSingleton_SingleThreaded_Minimal (FontHelperCache)
  223541. };
  223542. juce_ImplementSingleton_SingleThreaded (FontHelperCache)
  223543. void Typeface::initialiseTypefaceCharacteristics (const String& fontName,
  223544. bool bold,
  223545. bool italic,
  223546. bool addAllGlyphsToFont) throw()
  223547. {
  223548. // This method is only safe to be called from the normal UI thread..
  223549. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  223550. FontHelper* const helper = FontHelperCache::getInstance()
  223551. ->getFont (fontName, bold, italic);
  223552. clear();
  223553. setAscent (helper->ascent / helper->totalSize);
  223554. setName (fontName);
  223555. setDefaultCharacter (helper->getDefaultChar());
  223556. setBold (bold);
  223557. setItalic (italic);
  223558. if (addAllGlyphsToFont)
  223559. {
  223560. //xxx
  223561. jassertfalse
  223562. }
  223563. FontHelperCache::getInstance()->releaseFont (helper);
  223564. }
  223565. bool Typeface::findAndAddSystemGlyph (juce_wchar character) throw()
  223566. {
  223567. // This method is only safe to be called from the normal UI thread..
  223568. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  223569. if (character == 0)
  223570. return false;
  223571. FontHelper* const helper = FontHelperCache::getInstance()
  223572. ->getFont (getName(), isBold(), isItalic());
  223573. Path path;
  223574. float width;
  223575. bool foundOne = false;
  223576. if (helper->getPathAndKerning (character, T('I'), &path, width, 0, 0))
  223577. {
  223578. path.applyTransform (AffineTransform::scale (1.0f / helper->totalSize,
  223579. 1.0f / helper->totalSize));
  223580. addGlyph (character, path, width / helper->totalSize);
  223581. for (int i = 0; i < glyphs.size(); ++i)
  223582. {
  223583. const TypefaceGlyphInfo* const g = (const TypefaceGlyphInfo*) glyphs.getUnchecked(i);
  223584. float kerning;
  223585. if (helper->getPathAndKerning (character, g->getCharacter(), 0, kerning, 0, 0))
  223586. {
  223587. kerning = (kerning - width) / helper->totalSize;
  223588. if (kerning != 0)
  223589. addKerningPair (character, g->getCharacter(), kerning);
  223590. }
  223591. if (helper->getPathAndKerning (g->getCharacter(), character, 0, kerning, 0, 0))
  223592. {
  223593. kerning = kerning / helper->totalSize - g->width;
  223594. if (kerning != 0)
  223595. addKerningPair (g->getCharacter(), character, kerning);
  223596. }
  223597. }
  223598. foundOne = true;
  223599. }
  223600. FontHelperCache::getInstance()->releaseFont (helper);
  223601. return foundOne;
  223602. }
  223603. const StringArray Font::findAllTypefaceNames() throw()
  223604. {
  223605. StringArray names;
  223606. const ScopedAutoReleasePool pool;
  223607. NSArray* fonts = [[NSFontManager sharedFontManager] availableFontFamilies];
  223608. for (unsigned int i = 0; i < [fonts count]; ++i)
  223609. names.add (nsStringToJuce ((NSString*) [fonts objectAtIndex: i]));
  223610. names.sort (true);
  223611. return names;
  223612. }
  223613. void Typeface::getDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed) throw()
  223614. {
  223615. defaultSans = "Lucida Grande";
  223616. defaultSerif = "Times New Roman";
  223617. defaultFixed = "Monaco";
  223618. }
  223619. #endif
  223620. /********* End of inlined file: juce_mac_Fonts.mm *********/
  223621. /********* Start of inlined file: juce_mac_MessageManager.mm *********/
  223622. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  223623. // compiled on its own).
  223624. #ifdef JUCE_INCLUDED_FILE
  223625. struct CallbackMessagePayload
  223626. {
  223627. MessageCallbackFunction* function;
  223628. void* parameter;
  223629. void* volatile result;
  223630. bool volatile hasBeenExecuted;
  223631. };
  223632. /* When you use multiple DLLs which share similarly-named obj-c classes - like
  223633. for example having more than one juce plugin loaded into a host, then when a
  223634. method is called, the actual code that runs might actually be in a different module
  223635. than the one you expect... So any calls to library functions or statics that are
  223636. made inside obj-c methods will probably end up getting executed in a different DLL's
  223637. memory space. Not a great thing to happen - this obviously leads to bizarre crashes.
  223638. To work around this insanity, I'm only allowing obj-c methods to make calls to
  223639. virtual methods of an object that's known to live inside the right module's space.
  223640. */
  223641. class AppDelegateRedirector
  223642. {
  223643. public:
  223644. AppDelegateRedirector() {}
  223645. virtual ~AppDelegateRedirector() {}
  223646. virtual NSApplicationTerminateReply shouldTerminate()
  223647. {
  223648. if (JUCEApplication::getInstance() != 0)
  223649. {
  223650. JUCEApplication::getInstance()->systemRequestedQuit();
  223651. return NSTerminateCancel;
  223652. }
  223653. return NSTerminateNow;
  223654. }
  223655. virtual BOOL openFile (const NSString* filename)
  223656. {
  223657. if (JUCEApplication::getInstance() != 0)
  223658. {
  223659. JUCEApplication::getInstance()->anotherInstanceStarted (nsStringToJuce (filename));
  223660. return YES;
  223661. }
  223662. return NO;
  223663. }
  223664. virtual void openFiles (NSArray* filenames)
  223665. {
  223666. StringArray files;
  223667. for (unsigned int i = 0; i < [filenames count]; ++i)
  223668. files.add (nsStringToJuce ((NSString*) [filenames objectAtIndex: i]));
  223669. if (files.size() > 0 && JUCEApplication::getInstance() != 0)
  223670. {
  223671. JUCEApplication::getInstance()->anotherInstanceStarted (files.joinIntoString (T(" ")));
  223672. }
  223673. }
  223674. virtual void focusChanged()
  223675. {
  223676. juce_HandleProcessFocusChange();
  223677. }
  223678. virtual void deliverMessage (void* message)
  223679. {
  223680. // no need for an mm lock here - deliverMessage locks it
  223681. MessageManager::getInstance()->deliverMessage (message);
  223682. }
  223683. virtual void performCallback (CallbackMessagePayload* pl)
  223684. {
  223685. pl->result = (*pl->function) (pl->parameter);
  223686. pl->hasBeenExecuted = true;
  223687. }
  223688. virtual void deleteSelf()
  223689. {
  223690. delete this;
  223691. }
  223692. };
  223693. END_JUCE_NAMESPACE
  223694. using namespace JUCE_NAMESPACE;
  223695. #define JuceAppDelegate MakeObjCClassName(JuceAppDelegate)
  223696. static int numPendingMessages = 0;
  223697. @interface JuceAppDelegate : NSObject
  223698. {
  223699. @private
  223700. id oldDelegate;
  223701. AppDelegateRedirector* redirector;
  223702. @public
  223703. bool flushingMessages;
  223704. }
  223705. - (JuceAppDelegate*) init;
  223706. - (void) dealloc;
  223707. - (BOOL) application: (NSApplication*) theApplication openFile: (NSString*) filename;
  223708. - (void) application: (NSApplication*) sender openFiles: (NSArray*) filenames;
  223709. - (NSApplicationTerminateReply) applicationShouldTerminate: (NSApplication*) app;
  223710. - (void) applicationDidBecomeActive: (NSNotification*) aNotification;
  223711. - (void) applicationDidResignActive: (NSNotification*) aNotification;
  223712. - (void) applicationWillUnhide: (NSNotification*) aNotification;
  223713. - (void) customEvent: (id) data;
  223714. - (void) performCallback: (id) info;
  223715. - (void) dummyMethod;
  223716. @end
  223717. @implementation JuceAppDelegate
  223718. - (JuceAppDelegate*) init
  223719. {
  223720. [super init];
  223721. redirector = new AppDelegateRedirector();
  223722. numPendingMessages = 0;
  223723. flushingMessages = false;
  223724. NSNotificationCenter* center = [NSNotificationCenter defaultCenter];
  223725. if (JUCEApplication::getInstance() != 0)
  223726. {
  223727. oldDelegate = [NSApp delegate];
  223728. [NSApp setDelegate: self];
  223729. }
  223730. else
  223731. {
  223732. oldDelegate = 0;
  223733. [center addObserver: self selector: @selector (applicationDidResignActive:)
  223734. name: NSApplicationDidResignActiveNotification object: NSApp];
  223735. [center addObserver: self selector: @selector (applicationDidBecomeActive:)
  223736. name: NSApplicationDidBecomeActiveNotification object: NSApp];
  223737. [center addObserver: self selector: @selector (applicationWillUnhide:)
  223738. name: NSApplicationWillUnhideNotification object: NSApp];
  223739. }
  223740. return self;
  223741. }
  223742. - (void) dealloc
  223743. {
  223744. if (oldDelegate != 0)
  223745. [NSApp setDelegate: oldDelegate];
  223746. redirector->deleteSelf();
  223747. [super dealloc];
  223748. }
  223749. - (NSApplicationTerminateReply) applicationShouldTerminate: (NSApplication*) app
  223750. {
  223751. return redirector->shouldTerminate();
  223752. }
  223753. - (BOOL) application: (NSApplication*) app openFile: (NSString*) filename
  223754. {
  223755. return redirector->openFile (filename);
  223756. }
  223757. - (void) application: (NSApplication*) sender openFiles: (NSArray*) filenames
  223758. {
  223759. return redirector->openFiles (filenames);
  223760. }
  223761. - (void) applicationDidBecomeActive: (NSNotification*) aNotification
  223762. {
  223763. redirector->focusChanged();
  223764. }
  223765. - (void) applicationDidResignActive: (NSNotification*) aNotification
  223766. {
  223767. redirector->focusChanged();
  223768. }
  223769. - (void) applicationWillUnhide: (NSNotification*) aNotification
  223770. {
  223771. redirector->focusChanged();
  223772. }
  223773. - (void) customEvent: (id) n
  223774. {
  223775. atomicDecrement (numPendingMessages);
  223776. NSData* data = (NSData*) n;
  223777. void* message = 0;
  223778. [data getBytes: &message length: sizeof (message)];
  223779. [data release];
  223780. if (message != 0 && ! flushingMessages)
  223781. redirector->deliverMessage (message);
  223782. }
  223783. - (void) performCallback: (id) info
  223784. {
  223785. if ([info isKindOfClass: [NSData class]])
  223786. {
  223787. CallbackMessagePayload* pl = (CallbackMessagePayload*) [((NSData*) info) bytes];
  223788. if (pl != 0)
  223789. redirector->performCallback (pl);
  223790. }
  223791. else
  223792. {
  223793. jassertfalse // should never get here!
  223794. }
  223795. }
  223796. - (void) dummyMethod {} // (used as a way of running a dummy thread)
  223797. @end
  223798. BEGIN_JUCE_NAMESPACE
  223799. static JuceAppDelegate* juceAppDelegate = 0;
  223800. void MessageManager::runDispatchLoop()
  223801. {
  223802. if (! quitMessagePosted) // check that the quit message wasn't already posted..
  223803. {
  223804. const ScopedAutoReleasePool pool;
  223805. // must only be called by the message thread!
  223806. jassert (isThisTheMessageThread());
  223807. [NSApp run];
  223808. }
  223809. }
  223810. void MessageManager::stopDispatchLoop()
  223811. {
  223812. quitMessagePosted = true;
  223813. [NSApp stop: nil];
  223814. [NSApp activateIgnoringOtherApps: YES]; // (if the app is inactive, it sits there and ignores the quit request until the next time it gets activated)
  223815. [NSEvent startPeriodicEventsAfterDelay: 0 withPeriod: 0.1];
  223816. }
  223817. static bool isEventBlockedByModalComps (NSEvent* e)
  223818. {
  223819. if (Component::getNumCurrentlyModalComponents() == 0)
  223820. return false;
  223821. NSWindow* const w = [e window];
  223822. if (w == 0 || [w worksWhenModal])
  223823. return false;
  223824. bool isKey = false, isInputAttempt = false;
  223825. switch ([e type])
  223826. {
  223827. case NSKeyDown:
  223828. case NSKeyUp:
  223829. isKey = isInputAttempt = true;
  223830. break;
  223831. case NSLeftMouseDown:
  223832. case NSRightMouseDown:
  223833. case NSOtherMouseDown:
  223834. isInputAttempt = true;
  223835. break;
  223836. case NSLeftMouseDragged:
  223837. case NSRightMouseDragged:
  223838. case NSLeftMouseUp:
  223839. case NSRightMouseUp:
  223840. case NSOtherMouseUp:
  223841. case NSOtherMouseDragged:
  223842. if (Component::getComponentUnderMouse() != 0)
  223843. return false;
  223844. break;
  223845. case NSMouseMoved:
  223846. case NSMouseEntered:
  223847. case NSMouseExited:
  223848. case NSCursorUpdate:
  223849. case NSScrollWheel:
  223850. case NSTabletPoint:
  223851. case NSTabletProximity:
  223852. break;
  223853. default:
  223854. return false;
  223855. }
  223856. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  223857. {
  223858. ComponentPeer* const peer = ComponentPeer::getPeer (i);
  223859. NSView* const compView = (NSView*) peer->getNativeHandle();
  223860. if ([compView window] == w)
  223861. {
  223862. if (isKey)
  223863. {
  223864. if (compView == [w firstResponder])
  223865. return false;
  223866. }
  223867. else
  223868. {
  223869. if (NSPointInRect ([compView convertPoint: [e locationInWindow] fromView: nil],
  223870. [compView bounds]))
  223871. return false;
  223872. }
  223873. }
  223874. }
  223875. if (isInputAttempt)
  223876. {
  223877. if (! [NSApp isActive])
  223878. [NSApp activateIgnoringOtherApps: YES];
  223879. Component* const modal = Component::getCurrentlyModalComponent (0);
  223880. if (modal != 0)
  223881. modal->inputAttemptWhenModal();
  223882. }
  223883. return true;
  223884. }
  223885. bool MessageManager::runDispatchLoopUntil (int millisecondsToRunFor)
  223886. {
  223887. const ScopedAutoReleasePool pool;
  223888. jassert (isThisTheMessageThread()); // must only be called by the message thread
  223889. uint32 endTime = Time::getMillisecondCounter() + millisecondsToRunFor;
  223890. NSDate* endDate = [NSDate dateWithTimeIntervalSinceNow: millisecondsToRunFor * 0.001];
  223891. while (! quitMessagePosted)
  223892. {
  223893. const ScopedAutoReleasePool pool;
  223894. [[NSRunLoop currentRunLoop] runMode: NSDefaultRunLoopMode
  223895. beforeDate: endDate];
  223896. NSEvent* e = [NSApp nextEventMatchingMask: NSAnyEventMask
  223897. untilDate: endDate
  223898. inMode: NSDefaultRunLoopMode
  223899. dequeue: YES];
  223900. if (e != 0 && ! isEventBlockedByModalComps (e))
  223901. [NSApp sendEvent: e];
  223902. if (Time::getMillisecondCounter() >= endTime)
  223903. break;
  223904. }
  223905. return ! quitMessagePosted;
  223906. }
  223907. void MessageManager::doPlatformSpecificInitialisation()
  223908. {
  223909. if (juceAppDelegate == 0)
  223910. juceAppDelegate = [[JuceAppDelegate alloc] init];
  223911. // This launches a dummy thread, which forces Cocoa to initialise NSThreads
  223912. // correctly (needed prior to 10.5)
  223913. if (! [NSThread isMultiThreaded])
  223914. [NSThread detachNewThreadSelector: @selector (dummyMethod)
  223915. toTarget: juceAppDelegate
  223916. withObject: nil];
  223917. initialiseMainMenu();
  223918. }
  223919. void MessageManager::doPlatformSpecificShutdown()
  223920. {
  223921. if (juceAppDelegate != 0)
  223922. {
  223923. [[NSRunLoop currentRunLoop] cancelPerformSelectorsWithTarget: juceAppDelegate];
  223924. [[NSNotificationCenter defaultCenter] removeObserver: juceAppDelegate];
  223925. // Annoyingly, cancelPerformSelectorsWithTarget can't actually cancel the messages
  223926. // sent by performSelectorOnMainThread, so need to manually flush these before quitting..
  223927. juceAppDelegate->flushingMessages = true;
  223928. for (int i = 100; --i >= 0 && numPendingMessages > 0;)
  223929. {
  223930. const ScopedAutoReleasePool pool;
  223931. [[NSRunLoop currentRunLoop] runMode: NSDefaultRunLoopMode
  223932. beforeDate: [NSDate dateWithTimeIntervalSinceNow: 5 * 0.001]];
  223933. }
  223934. [juceAppDelegate release];
  223935. juceAppDelegate = 0;
  223936. }
  223937. }
  223938. bool juce_postMessageToSystemQueue (void* message)
  223939. {
  223940. atomicIncrement (numPendingMessages);
  223941. [juceAppDelegate performSelectorOnMainThread: @selector (customEvent:)
  223942. withObject: (id) [[NSData alloc] initWithBytes: &message length: (int) sizeof (message)]
  223943. waitUntilDone: NO];
  223944. return true;
  223945. }
  223946. void MessageManager::broadcastMessage (const String& value) throw()
  223947. {
  223948. }
  223949. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* callback,
  223950. void* data)
  223951. {
  223952. if (isThisTheMessageThread())
  223953. {
  223954. return (*callback) (data);
  223955. }
  223956. else
  223957. {
  223958. // If a thread has a MessageManagerLock and then tries to call this method, it'll
  223959. // deadlock because the message manager is blocked from running, so can never
  223960. // call your function..
  223961. jassert (! MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  223962. const ScopedAutoReleasePool pool;
  223963. CallbackMessagePayload cmp;
  223964. cmp.function = callback;
  223965. cmp.parameter = data;
  223966. cmp.result = 0;
  223967. cmp.hasBeenExecuted = false;
  223968. [juceAppDelegate performSelectorOnMainThread: @selector (performCallback:)
  223969. withObject: [NSData dataWithBytesNoCopy: &cmp
  223970. length: sizeof (cmp)
  223971. freeWhenDone: NO]
  223972. waitUntilDone: YES];
  223973. return cmp.result;
  223974. }
  223975. }
  223976. #endif
  223977. /********* End of inlined file: juce_mac_MessageManager.mm *********/
  223978. /********* Start of inlined file: juce_mac_WebBrowserComponent.mm *********/
  223979. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  223980. // compiled on its own).
  223981. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  223982. END_JUCE_NAMESPACE
  223983. #define DownloadClickDetector MakeObjCClassName(DownloadClickDetector)
  223984. @interface DownloadClickDetector : NSObject
  223985. {
  223986. JUCE_NAMESPACE::WebBrowserComponent* ownerComponent;
  223987. }
  223988. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent;
  223989. - (void) webView: (WebView*) webView decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  223990. request: (NSURLRequest*) request
  223991. frame: (WebFrame*) frame
  223992. decisionListener: (id<WebPolicyDecisionListener>) listener;
  223993. @end
  223994. @implementation DownloadClickDetector
  223995. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent_
  223996. {
  223997. [super init];
  223998. ownerComponent = ownerComponent_;
  223999. return self;
  224000. }
  224001. - (void) webView: (WebView*) sender decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  224002. request: (NSURLRequest*) request
  224003. frame: (WebFrame*) frame
  224004. decisionListener: (id <WebPolicyDecisionListener>) listener
  224005. {
  224006. NSURL* url = [actionInformation valueForKey: @"WebActionOriginalURLKey"];
  224007. if (ownerComponent->pageAboutToLoad (nsStringToJuce ([url absoluteString])))
  224008. [listener use];
  224009. else
  224010. [listener ignore];
  224011. }
  224012. @end
  224013. BEGIN_JUCE_NAMESPACE
  224014. class WebBrowserComponentInternal : public NSViewComponent
  224015. {
  224016. public:
  224017. WebBrowserComponentInternal (WebBrowserComponent* owner)
  224018. {
  224019. webView = [[WebView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  224020. frameName: @""
  224021. groupName: @""];
  224022. setView (webView);
  224023. clickListener = [[DownloadClickDetector alloc] initWithWebBrowserOwner: owner];
  224024. [webView setPolicyDelegate: clickListener];
  224025. }
  224026. ~WebBrowserComponentInternal()
  224027. {
  224028. [webView setPolicyDelegate: nil];
  224029. [clickListener release];
  224030. setView (0);
  224031. }
  224032. void goToURL (const String& url,
  224033. const StringArray* headers,
  224034. const MemoryBlock* postData)
  224035. {
  224036. NSMutableURLRequest* r
  224037. = [NSMutableURLRequest requestWithURL: [NSURL URLWithString: juceStringToNS (url)]
  224038. cachePolicy: NSURLRequestUseProtocolCachePolicy
  224039. timeoutInterval: 30.0];
  224040. if (postData != 0 && postData->getSize() > 0)
  224041. {
  224042. [r setHTTPMethod: @"POST"];
  224043. [r setHTTPBody: [NSData dataWithBytes: postData->getData()
  224044. length: postData->getSize()]];
  224045. }
  224046. if (headers != 0)
  224047. {
  224048. for (int i = 0; i < headers->size(); ++i)
  224049. {
  224050. const String headerName ((*headers)[i].upToFirstOccurrenceOf (T(":"), false, false).trim());
  224051. const String headerValue ((*headers)[i].fromFirstOccurrenceOf (T(":"), false, false).trim());
  224052. [r setValue: juceStringToNS (headerValue)
  224053. forHTTPHeaderField: juceStringToNS (headerName)];
  224054. }
  224055. }
  224056. stop();
  224057. [[webView mainFrame] loadRequest: r];
  224058. }
  224059. void goBack()
  224060. {
  224061. [webView goBack];
  224062. }
  224063. void goForward()
  224064. {
  224065. [webView goForward];
  224066. }
  224067. void stop()
  224068. {
  224069. [webView stopLoading: nil];
  224070. }
  224071. void refresh()
  224072. {
  224073. [webView reload: nil];
  224074. }
  224075. private:
  224076. WebView* webView;
  224077. DownloadClickDetector* clickListener;
  224078. };
  224079. WebBrowserComponent::WebBrowserComponent()
  224080. : browser (0),
  224081. blankPageShown (false)
  224082. {
  224083. setOpaque (true);
  224084. addAndMakeVisible (browser = new WebBrowserComponentInternal (this));
  224085. }
  224086. WebBrowserComponent::~WebBrowserComponent()
  224087. {
  224088. deleteAndZero (browser);
  224089. }
  224090. void WebBrowserComponent::goToURL (const String& url,
  224091. const StringArray* headers,
  224092. const MemoryBlock* postData)
  224093. {
  224094. lastURL = url;
  224095. lastHeaders.clear();
  224096. if (headers != 0)
  224097. lastHeaders = *headers;
  224098. lastPostData.setSize (0);
  224099. if (postData != 0)
  224100. lastPostData = *postData;
  224101. blankPageShown = false;
  224102. browser->goToURL (url, headers, postData);
  224103. }
  224104. void WebBrowserComponent::stop()
  224105. {
  224106. browser->stop();
  224107. }
  224108. void WebBrowserComponent::goBack()
  224109. {
  224110. lastURL = String::empty;
  224111. blankPageShown = false;
  224112. browser->goBack();
  224113. }
  224114. void WebBrowserComponent::goForward()
  224115. {
  224116. lastURL = String::empty;
  224117. browser->goForward();
  224118. }
  224119. void WebBrowserComponent::refresh()
  224120. {
  224121. browser->refresh();
  224122. }
  224123. void WebBrowserComponent::paint (Graphics& g)
  224124. {
  224125. }
  224126. void WebBrowserComponent::checkWindowAssociation()
  224127. {
  224128. // when the component becomes invisible, some stuff like flash
  224129. // carries on playing audio, so we need to force it onto a blank
  224130. // page to avoid this, (and send it back when it's made visible again).
  224131. if (isShowing())
  224132. {
  224133. if (blankPageShown)
  224134. goBack();
  224135. }
  224136. else
  224137. {
  224138. if (! blankPageShown)
  224139. {
  224140. blankPageShown = true;
  224141. browser->goToURL ("about:blank", 0, 0);
  224142. }
  224143. }
  224144. }
  224145. void WebBrowserComponent::reloadLastURL()
  224146. {
  224147. if (lastURL.isNotEmpty())
  224148. {
  224149. goToURL (lastURL, &lastHeaders, &lastPostData);
  224150. lastURL = String::empty;
  224151. }
  224152. }
  224153. void WebBrowserComponent::parentHierarchyChanged()
  224154. {
  224155. checkWindowAssociation();
  224156. }
  224157. void WebBrowserComponent::resized()
  224158. {
  224159. browser->setSize (getWidth(), getHeight());
  224160. }
  224161. void WebBrowserComponent::visibilityChanged()
  224162. {
  224163. checkWindowAssociation();
  224164. }
  224165. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  224166. {
  224167. return true;
  224168. }
  224169. #endif
  224170. /********* End of inlined file: juce_mac_WebBrowserComponent.mm *********/
  224171. /********* Start of inlined file: juce_mac_CoreAudio.cpp *********/
  224172. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224173. // compiled on its own).
  224174. #ifdef JUCE_INCLUDED_FILE
  224175. #ifndef JUCE_COREAUDIO_ERROR_LOGGING_ENABLED
  224176. #define JUCE_COREAUDIO_ERROR_LOGGING_ENABLED 1
  224177. #endif
  224178. #undef log
  224179. #if JUCE_COREAUDIO_LOGGING_ENABLED
  224180. #define log(a) Logger::writeToLog (a)
  224181. #else
  224182. #define log(a)
  224183. #endif
  224184. #undef OK
  224185. #if JUCE_COREAUDIO_ERROR_LOGGING_ENABLED
  224186. static bool logAnyErrors_CoreAudio (const OSStatus err, const int lineNum)
  224187. {
  224188. if (err == noErr)
  224189. return true;
  224190. Logger::writeToLog (T("CoreAudio error: ") + String (lineNum) + T(" - ") + String::toHexString ((int)err));
  224191. jassertfalse
  224192. return false;
  224193. }
  224194. #define OK(a) logAnyErrors_CoreAudio (a, __LINE__)
  224195. #else
  224196. #define OK(a) (a == noErr)
  224197. #endif
  224198. class CoreAudioInternal : public Timer
  224199. {
  224200. public:
  224201. CoreAudioInternal (AudioDeviceID id)
  224202. : inputLatency (0),
  224203. outputLatency (0),
  224204. callback (0),
  224205. #if ! MACOS_10_4_OR_EARLIER
  224206. audioProcID (0),
  224207. #endif
  224208. inputDevice (0),
  224209. isSlaveDevice (false),
  224210. deviceID (id),
  224211. started (false),
  224212. audioBuffer (0),
  224213. numInputChans (0),
  224214. numOutputChans (0),
  224215. callbacksAllowed (true),
  224216. numInputChannelInfos (0),
  224217. numOutputChannelInfos (0),
  224218. tempInputBuffers (0),
  224219. tempOutputBuffers (0),
  224220. inputChannelInfo (0),
  224221. outputChannelInfo (0)
  224222. {
  224223. sampleRate = 0;
  224224. bufferSize = 512;
  224225. if (deviceID == 0)
  224226. {
  224227. error = TRANS("can't open device");
  224228. }
  224229. else
  224230. {
  224231. updateDetailsFromDevice();
  224232. AudioObjectPropertyAddress pa;
  224233. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  224234. pa.mScope = kAudioObjectPropertyScopeWildcard;
  224235. pa.mElement = kAudioObjectPropertyElementWildcard;
  224236. AudioObjectAddPropertyListener (deviceID, &pa, deviceListenerProc, this);
  224237. }
  224238. }
  224239. ~CoreAudioInternal()
  224240. {
  224241. AudioObjectPropertyAddress pa;
  224242. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  224243. pa.mScope = kAudioObjectPropertyScopeWildcard;
  224244. pa.mElement = kAudioObjectPropertyElementWildcard;
  224245. AudioObjectRemovePropertyListener (deviceID, &pa, deviceListenerProc, this);
  224246. stop (false);
  224247. juce_free (audioBuffer);
  224248. juce_free (tempInputBuffers);
  224249. juce_free (tempOutputBuffers);
  224250. juce_free (inputChannelInfo);
  224251. juce_free (outputChannelInfo);
  224252. delete inputDevice;
  224253. }
  224254. void allocateTempBuffers()
  224255. {
  224256. const int tempBufSize = bufferSize + 4;
  224257. juce_free (audioBuffer);
  224258. audioBuffer = (float*) juce_calloc ((numInputChans + numOutputChans) * tempBufSize * sizeof (float));
  224259. juce_free (tempInputBuffers);
  224260. tempInputBuffers = (float**) juce_calloc (sizeof (float*) * (numInputChans + 2));
  224261. juce_free (tempOutputBuffers);
  224262. tempOutputBuffers = (float**) juce_calloc (sizeof (float*) * (numOutputChans + 2));
  224263. int i, count = 0;
  224264. for (i = 0; i < numInputChans; ++i)
  224265. tempInputBuffers[i] = audioBuffer + count++ * tempBufSize;
  224266. for (i = 0; i < numOutputChans; ++i)
  224267. tempOutputBuffers[i] = audioBuffer + count++ * tempBufSize;
  224268. }
  224269. // returns the number of actual available channels
  224270. void fillInChannelInfo (const bool input)
  224271. {
  224272. int chanNum = 0;
  224273. UInt32 size;
  224274. AudioObjectPropertyAddress pa;
  224275. pa.mSelector = kAudioDevicePropertyStreamConfiguration;
  224276. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  224277. pa.mElement = kAudioObjectPropertyElementMaster;
  224278. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  224279. {
  224280. AudioBufferList* const bufList = (AudioBufferList*) juce_calloc (size);
  224281. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, bufList)))
  224282. {
  224283. const int numStreams = bufList->mNumberBuffers;
  224284. for (int i = 0; i < numStreams; ++i)
  224285. {
  224286. const AudioBuffer& b = bufList->mBuffers[i];
  224287. for (unsigned int j = 0; j < b.mNumberChannels; ++j)
  224288. {
  224289. String name;
  224290. {
  224291. uint8 channelName [256];
  224292. zerostruct (channelName);
  224293. UInt32 nameSize = sizeof (channelName);
  224294. UInt32 channelNum = chanNum + 1;
  224295. pa.mSelector = kAudioDevicePropertyChannelName;
  224296. if (AudioObjectGetPropertyData (deviceID, &pa, sizeof (channelNum), &channelNum, &nameSize, channelName) == noErr)
  224297. name = String::fromUTF8 (channelName, nameSize);
  224298. }
  224299. if (input)
  224300. {
  224301. if (activeInputChans[chanNum])
  224302. {
  224303. inputChannelInfo [numInputChannelInfos].streamNum = i;
  224304. inputChannelInfo [numInputChannelInfos].dataOffsetSamples = j;
  224305. inputChannelInfo [numInputChannelInfos].dataStrideSamples = b.mNumberChannels;
  224306. ++numInputChannelInfos;
  224307. }
  224308. if (name.isEmpty())
  224309. name << "Input " << (chanNum + 1);
  224310. inChanNames.add (name);
  224311. }
  224312. else
  224313. {
  224314. if (activeOutputChans[chanNum])
  224315. {
  224316. outputChannelInfo [numOutputChannelInfos].streamNum = i;
  224317. outputChannelInfo [numOutputChannelInfos].dataOffsetSamples = j;
  224318. outputChannelInfo [numOutputChannelInfos].dataStrideSamples = b.mNumberChannels;
  224319. ++numOutputChannelInfos;
  224320. }
  224321. if (name.isEmpty())
  224322. name << "Output " << (chanNum + 1);
  224323. outChanNames.add (name);
  224324. }
  224325. ++chanNum;
  224326. }
  224327. }
  224328. }
  224329. juce_free (bufList);
  224330. }
  224331. }
  224332. void updateDetailsFromDevice()
  224333. {
  224334. stopTimer();
  224335. if (deviceID == 0)
  224336. return;
  224337. const ScopedLock sl (callbackLock);
  224338. Float64 sr;
  224339. UInt32 size = sizeof (Float64);
  224340. AudioObjectPropertyAddress pa;
  224341. pa.mSelector = kAudioDevicePropertyNominalSampleRate;
  224342. pa.mScope = kAudioObjectPropertyScopeWildcard;
  224343. pa.mElement = kAudioObjectPropertyElementMaster;
  224344. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &sr)))
  224345. sampleRate = sr;
  224346. UInt32 framesPerBuf;
  224347. size = sizeof (framesPerBuf);
  224348. pa.mSelector = kAudioDevicePropertyBufferFrameSize;
  224349. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &framesPerBuf)))
  224350. {
  224351. bufferSize = framesPerBuf;
  224352. allocateTempBuffers();
  224353. }
  224354. bufferSizes.clear();
  224355. pa.mSelector = kAudioDevicePropertyBufferFrameSizeRange;
  224356. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  224357. {
  224358. AudioValueRange* ranges = (AudioValueRange*) juce_calloc (size);
  224359. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, ranges)))
  224360. {
  224361. bufferSizes.add ((int) ranges[0].mMinimum);
  224362. for (int i = 32; i < 8192; i += 32)
  224363. {
  224364. for (int j = size / sizeof (AudioValueRange); --j >= 0;)
  224365. {
  224366. if (i >= ranges[j].mMinimum && i <= ranges[j].mMaximum)
  224367. {
  224368. bufferSizes.addIfNotAlreadyThere (i);
  224369. break;
  224370. }
  224371. }
  224372. }
  224373. if (bufferSize > 0)
  224374. bufferSizes.addIfNotAlreadyThere (bufferSize);
  224375. }
  224376. juce_free (ranges);
  224377. }
  224378. if (bufferSizes.size() == 0 && bufferSize > 0)
  224379. bufferSizes.add (bufferSize);
  224380. sampleRates.clear();
  224381. const double possibleRates[] = { 44100.0, 48000.0, 88200.0, 96000.0, 176400.0, 192000.0 };
  224382. String rates;
  224383. pa.mSelector = kAudioDevicePropertyAvailableNominalSampleRates;
  224384. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  224385. {
  224386. AudioValueRange* ranges = (AudioValueRange*) juce_calloc (size);
  224387. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, ranges)))
  224388. {
  224389. for (int i = 0; i < numElementsInArray (possibleRates); ++i)
  224390. {
  224391. bool ok = false;
  224392. for (int j = size / sizeof (AudioValueRange); --j >= 0;)
  224393. if (possibleRates[i] >= ranges[j].mMinimum - 2 && possibleRates[i] <= ranges[j].mMaximum + 2)
  224394. ok = true;
  224395. if (ok)
  224396. {
  224397. sampleRates.add (possibleRates[i]);
  224398. rates << possibleRates[i] << T(" ");
  224399. }
  224400. }
  224401. }
  224402. juce_free (ranges);
  224403. }
  224404. if (sampleRates.size() == 0 && sampleRate > 0)
  224405. {
  224406. sampleRates.add (sampleRate);
  224407. rates << sampleRate;
  224408. }
  224409. log (T("sr: ") + rates);
  224410. inputLatency = 0;
  224411. outputLatency = 0;
  224412. UInt32 lat;
  224413. size = sizeof (lat);
  224414. pa.mSelector = kAudioDevicePropertyLatency;
  224415. pa.mScope = kAudioDevicePropertyScopeInput;
  224416. //if (AudioDeviceGetProperty (deviceID, 0, true, kAudioDevicePropertyLatency, &size, &lat) == noErr)
  224417. if (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &lat) == noErr)
  224418. inputLatency = (int) lat;
  224419. pa.mScope = kAudioDevicePropertyScopeOutput;
  224420. size = sizeof (lat);
  224421. if (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &lat) == noErr)
  224422. outputLatency = (int) lat;
  224423. log (T("lat: ") + String (inputLatency) + T(" ") + String (outputLatency));
  224424. inChanNames.clear();
  224425. outChanNames.clear();
  224426. juce_free (inputChannelInfo);
  224427. inputChannelInfo = (CallbackDetailsForChannel*) juce_calloc (sizeof (CallbackDetailsForChannel) * (numInputChans + 2));
  224428. numInputChannelInfos = 0;
  224429. juce_free (outputChannelInfo);
  224430. outputChannelInfo = (CallbackDetailsForChannel*) juce_calloc (sizeof (CallbackDetailsForChannel) * (numOutputChans + 2));
  224431. numOutputChannelInfos = 0;
  224432. fillInChannelInfo (true);
  224433. fillInChannelInfo (false);
  224434. }
  224435. const StringArray getSources (bool input)
  224436. {
  224437. StringArray s;
  224438. int num = 0;
  224439. OSType* types = getAllDataSourcesForDevice (deviceID, input, num);
  224440. if (types != 0)
  224441. {
  224442. for (int i = 0; i < num; ++i)
  224443. {
  224444. AudioValueTranslation avt;
  224445. char buffer[256];
  224446. avt.mInputData = (void*) &(types[i]);
  224447. avt.mInputDataSize = sizeof (UInt32);
  224448. avt.mOutputData = buffer;
  224449. avt.mOutputDataSize = 256;
  224450. UInt32 transSize = sizeof (avt);
  224451. AudioObjectPropertyAddress pa;
  224452. pa.mSelector = kAudioDevicePropertyDataSourceNameForID;
  224453. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  224454. pa.mElement = kAudioObjectPropertyElementMaster;
  224455. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &transSize, &avt)))
  224456. {
  224457. DBG (buffer);
  224458. s.add (buffer);
  224459. }
  224460. }
  224461. juce_free (types);
  224462. }
  224463. return s;
  224464. }
  224465. int getCurrentSourceIndex (bool input) const
  224466. {
  224467. OSType currentSourceID = 0;
  224468. UInt32 size = sizeof (currentSourceID);
  224469. int result = -1;
  224470. AudioObjectPropertyAddress pa;
  224471. pa.mSelector = kAudioDevicePropertyDataSource;
  224472. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  224473. pa.mElement = kAudioObjectPropertyElementMaster;
  224474. if (deviceID != 0)
  224475. {
  224476. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &currentSourceID)))
  224477. {
  224478. int num = 0;
  224479. OSType* const types = getAllDataSourcesForDevice (deviceID, input, num);
  224480. if (types != 0)
  224481. {
  224482. for (int i = 0; i < num; ++i)
  224483. {
  224484. if (types[num] == currentSourceID)
  224485. {
  224486. result = i;
  224487. break;
  224488. }
  224489. }
  224490. juce_free (types);
  224491. }
  224492. }
  224493. }
  224494. return result;
  224495. }
  224496. void setCurrentSourceIndex (int index, bool input)
  224497. {
  224498. if (deviceID != 0)
  224499. {
  224500. int num = 0;
  224501. OSType* types = getAllDataSourcesForDevice (deviceID, input, num);
  224502. if (types != 0)
  224503. {
  224504. if (((unsigned int) index) < (unsigned int) num)
  224505. {
  224506. AudioObjectPropertyAddress pa;
  224507. pa.mSelector = kAudioDevicePropertyDataSource;
  224508. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  224509. pa.mElement = kAudioObjectPropertyElementMaster;
  224510. OSType typeId = types[index];
  224511. OK (AudioObjectSetPropertyData (deviceID, &pa, 0, 0, sizeof (typeId), &typeId));
  224512. }
  224513. juce_free (types);
  224514. }
  224515. }
  224516. }
  224517. const String reopen (const BitArray& inputChannels,
  224518. const BitArray& outputChannels,
  224519. double newSampleRate,
  224520. int bufferSizeSamples)
  224521. {
  224522. error = String::empty;
  224523. log ("CoreAudio reopen");
  224524. callbacksAllowed = false;
  224525. stopTimer();
  224526. stop (false);
  224527. activeInputChans = inputChannels;
  224528. activeOutputChans = outputChannels;
  224529. activeInputChans.setRange (inChanNames.size(),
  224530. activeInputChans.getHighestBit() + 1 - inChanNames.size(),
  224531. false);
  224532. activeOutputChans.setRange (outChanNames.size(),
  224533. activeOutputChans.getHighestBit() + 1 - outChanNames.size(),
  224534. false);
  224535. numInputChans = activeInputChans.countNumberOfSetBits();
  224536. numOutputChans = activeOutputChans.countNumberOfSetBits();
  224537. // set sample rate
  224538. Float64 sr = newSampleRate;
  224539. UInt32 size = sizeof (sr);
  224540. AudioObjectPropertyAddress pa;
  224541. pa.mSelector = kAudioDevicePropertyNominalSampleRate;
  224542. pa.mScope = kAudioObjectPropertyScopeWildcard;
  224543. pa.mElement = kAudioObjectPropertyElementMaster;
  224544. OK (AudioObjectSetPropertyData (deviceID, &pa, 0, 0, size, &sr));
  224545. // change buffer size
  224546. UInt32 framesPerBuf = bufferSizeSamples;
  224547. size = sizeof (framesPerBuf);
  224548. pa.mSelector = kAudioDevicePropertyBufferFrameSize;
  224549. OK (AudioObjectSetPropertyData (deviceID, &pa, 0, 0, size, &framesPerBuf));
  224550. // wait for the changes to happen (on some devices)
  224551. int i = 30;
  224552. while (--i >= 0)
  224553. {
  224554. updateDetailsFromDevice();
  224555. if (sampleRate == newSampleRate && bufferSizeSamples == bufferSize)
  224556. break;
  224557. Thread::sleep (100);
  224558. }
  224559. if (i < 0)
  224560. error = "Couldn't change sample rate/buffer size";
  224561. if (sampleRates.size() == 0)
  224562. error = "Device has no available sample-rates";
  224563. if (bufferSizes.size() == 0)
  224564. error = "Device has no available buffer-sizes";
  224565. if (inputDevice != 0 && error.isEmpty())
  224566. error = inputDevice->reopen (inputChannels,
  224567. outputChannels,
  224568. newSampleRate,
  224569. bufferSizeSamples);
  224570. callbacksAllowed = true;
  224571. return error;
  224572. }
  224573. bool start (AudioIODeviceCallback* cb)
  224574. {
  224575. if (! started)
  224576. {
  224577. callback = 0;
  224578. if (deviceID != 0)
  224579. {
  224580. #if MACOS_10_4_OR_EARLIER
  224581. if (OK (AudioDeviceAddIOProc (deviceID, audioIOProc, (void*) this)))
  224582. #else
  224583. if (OK (AudioDeviceCreateIOProcID (deviceID, audioIOProc, (void*) this, &audioProcID)))
  224584. #endif
  224585. {
  224586. if (OK (AudioDeviceStart (deviceID, audioIOProc)))
  224587. {
  224588. started = true;
  224589. }
  224590. else
  224591. {
  224592. #if MACOS_10_4_OR_EARLIER
  224593. OK (AudioDeviceRemoveIOProc (deviceID, audioIOProc));
  224594. #else
  224595. OK (AudioDeviceDestroyIOProcID (deviceID, audioProcID));
  224596. audioProcID = 0;
  224597. #endif
  224598. }
  224599. }
  224600. }
  224601. }
  224602. if (started)
  224603. {
  224604. const ScopedLock sl (callbackLock);
  224605. callback = cb;
  224606. }
  224607. if (inputDevice != 0)
  224608. return started && inputDevice->start (cb);
  224609. else
  224610. return started;
  224611. }
  224612. void stop (bool leaveInterruptRunning)
  224613. {
  224614. callbackLock.enter();
  224615. callback = 0;
  224616. callbackLock.exit();
  224617. if (started
  224618. && (deviceID != 0)
  224619. && ! leaveInterruptRunning)
  224620. {
  224621. OK (AudioDeviceStop (deviceID, audioIOProc));
  224622. #if MACOS_10_4_OR_EARLIER
  224623. OK (AudioDeviceRemoveIOProc (deviceID, audioIOProc));
  224624. #else
  224625. OK (AudioDeviceDestroyIOProcID (deviceID, audioProcID));
  224626. audioProcID = 0;
  224627. #endif
  224628. started = false;
  224629. callbackLock.enter();
  224630. callbackLock.exit();
  224631. // wait until it's definately stopped calling back..
  224632. for (int i = 40; --i >= 0;)
  224633. {
  224634. Thread::sleep (50);
  224635. UInt32 running = 0;
  224636. UInt32 size = sizeof (running);
  224637. AudioObjectPropertyAddress pa;
  224638. pa.mSelector = kAudioDevicePropertyDeviceIsRunning;
  224639. pa.mScope = kAudioObjectPropertyScopeWildcard;
  224640. pa.mElement = kAudioObjectPropertyElementMaster;
  224641. OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &running));
  224642. if (running == 0)
  224643. break;
  224644. }
  224645. callbackLock.enter();
  224646. callbackLock.exit();
  224647. }
  224648. if (inputDevice != 0)
  224649. inputDevice->stop (leaveInterruptRunning);
  224650. }
  224651. double getSampleRate() const
  224652. {
  224653. return sampleRate;
  224654. }
  224655. int getBufferSize() const
  224656. {
  224657. return bufferSize;
  224658. }
  224659. void audioCallback (const AudioBufferList* inInputData,
  224660. AudioBufferList* outOutputData)
  224661. {
  224662. int i;
  224663. const ScopedLock sl (callbackLock);
  224664. if (callback != 0)
  224665. {
  224666. if (inputDevice == 0)
  224667. {
  224668. for (i = numInputChans; --i >= 0;)
  224669. {
  224670. const CallbackDetailsForChannel& info = inputChannelInfo[i];
  224671. float* dest = tempInputBuffers [i];
  224672. const float* src = ((const float*) inInputData->mBuffers[info.streamNum].mData)
  224673. + info.dataOffsetSamples;
  224674. const int stride = info.dataStrideSamples;
  224675. if (stride != 0) // if this is zero, info is invalid
  224676. {
  224677. for (int j = bufferSize; --j >= 0;)
  224678. {
  224679. *dest++ = *src;
  224680. src += stride;
  224681. }
  224682. }
  224683. }
  224684. }
  224685. if (! isSlaveDevice)
  224686. {
  224687. if (inputDevice == 0)
  224688. {
  224689. callback->audioDeviceIOCallback ((const float**) tempInputBuffers,
  224690. numInputChans,
  224691. tempOutputBuffers,
  224692. numOutputChans,
  224693. bufferSize);
  224694. }
  224695. else
  224696. {
  224697. jassert (inputDevice->bufferSize == bufferSize);
  224698. // Sometimes the two linked devices seem to get their callbacks in
  224699. // parallel, so we need to lock both devices to stop the input data being
  224700. // changed while inside our callback..
  224701. const ScopedLock sl (inputDevice->callbackLock);
  224702. callback->audioDeviceIOCallback ((const float**) inputDevice->tempInputBuffers,
  224703. inputDevice->numInputChans,
  224704. tempOutputBuffers,
  224705. numOutputChans,
  224706. bufferSize);
  224707. }
  224708. for (i = numOutputChans; --i >= 0;)
  224709. {
  224710. const CallbackDetailsForChannel& info = outputChannelInfo[i];
  224711. const float* src = tempOutputBuffers [i];
  224712. float* dest = ((float*) outOutputData->mBuffers[info.streamNum].mData)
  224713. + info.dataOffsetSamples;
  224714. const int stride = info.dataStrideSamples;
  224715. if (stride != 0) // if this is zero, info is invalid
  224716. {
  224717. for (int j = bufferSize; --j >= 0;)
  224718. {
  224719. *dest = *src++;
  224720. dest += stride;
  224721. }
  224722. }
  224723. }
  224724. }
  224725. }
  224726. else
  224727. {
  224728. for (i = jmin (numOutputChans, numOutputChannelInfos); --i >= 0;)
  224729. {
  224730. const CallbackDetailsForChannel& info = outputChannelInfo[i];
  224731. float* dest = ((float*) outOutputData->mBuffers[info.streamNum].mData)
  224732. + info.dataOffsetSamples;
  224733. const int stride = info.dataStrideSamples;
  224734. if (stride != 0) // if this is zero, info is invalid
  224735. {
  224736. for (int j = bufferSize; --j >= 0;)
  224737. {
  224738. *dest = 0.0f;
  224739. dest += stride;
  224740. }
  224741. }
  224742. }
  224743. }
  224744. }
  224745. // called by callbacks
  224746. void deviceDetailsChanged()
  224747. {
  224748. if (callbacksAllowed)
  224749. startTimer (100);
  224750. }
  224751. void timerCallback()
  224752. {
  224753. stopTimer();
  224754. log ("CoreAudio device changed callback");
  224755. const double oldSampleRate = sampleRate;
  224756. const int oldBufferSize = bufferSize;
  224757. updateDetailsFromDevice();
  224758. if (oldBufferSize != bufferSize || oldSampleRate != sampleRate)
  224759. {
  224760. callbacksAllowed = false;
  224761. stop (false);
  224762. updateDetailsFromDevice();
  224763. callbacksAllowed = true;
  224764. }
  224765. }
  224766. CoreAudioInternal* getRelatedDevice() const
  224767. {
  224768. UInt32 size = 0;
  224769. CoreAudioInternal* result = 0;
  224770. AudioObjectPropertyAddress pa;
  224771. pa.mSelector = kAudioDevicePropertyRelatedDevices;
  224772. pa.mScope = kAudioObjectPropertyScopeWildcard;
  224773. pa.mElement = kAudioObjectPropertyElementMaster;
  224774. if (deviceID != 0
  224775. && AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size) == noErr
  224776. && size > 0)
  224777. {
  224778. AudioDeviceID* devs = (AudioDeviceID*) juce_calloc (size);
  224779. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, devs)))
  224780. {
  224781. for (unsigned int i = 0; i < size / sizeof (AudioDeviceID); ++i)
  224782. {
  224783. if (devs[i] != deviceID && devs[i] != 0)
  224784. {
  224785. result = new CoreAudioInternal (devs[i]);
  224786. if (result->error.isEmpty())
  224787. {
  224788. const bool thisIsInput = inChanNames.size() > 0 && outChanNames.size() == 0;
  224789. const bool otherIsInput = result->inChanNames.size() > 0 && result->outChanNames.size() == 0;
  224790. if (thisIsInput != otherIsInput
  224791. || (inChanNames.size() + outChanNames.size() == 0)
  224792. || (result->inChanNames.size() + result->outChanNames.size()) == 0)
  224793. break;
  224794. }
  224795. deleteAndZero (result);
  224796. }
  224797. }
  224798. }
  224799. juce_free (devs);
  224800. }
  224801. return result;
  224802. }
  224803. juce_UseDebuggingNewOperator
  224804. String error;
  224805. int inputLatency, outputLatency;
  224806. BitArray activeInputChans, activeOutputChans;
  224807. StringArray inChanNames, outChanNames;
  224808. Array <double> sampleRates;
  224809. Array <int> bufferSizes;
  224810. AudioIODeviceCallback* callback;
  224811. #if ! MACOS_10_4_OR_EARLIER
  224812. AudioDeviceIOProcID audioProcID;
  224813. #endif
  224814. CoreAudioInternal* inputDevice;
  224815. bool isSlaveDevice;
  224816. private:
  224817. CriticalSection callbackLock;
  224818. AudioDeviceID deviceID;
  224819. bool started;
  224820. double sampleRate;
  224821. int bufferSize;
  224822. float* audioBuffer;
  224823. int numInputChans, numOutputChans;
  224824. bool callbacksAllowed;
  224825. struct CallbackDetailsForChannel
  224826. {
  224827. int streamNum;
  224828. int dataOffsetSamples;
  224829. int dataStrideSamples;
  224830. };
  224831. int numInputChannelInfos, numOutputChannelInfos;
  224832. CallbackDetailsForChannel* inputChannelInfo;
  224833. CallbackDetailsForChannel* outputChannelInfo;
  224834. float** tempInputBuffers;
  224835. float** tempOutputBuffers;
  224836. CoreAudioInternal (const CoreAudioInternal&);
  224837. const CoreAudioInternal& operator= (const CoreAudioInternal&);
  224838. static OSStatus audioIOProc (AudioDeviceID inDevice,
  224839. const AudioTimeStamp* inNow,
  224840. const AudioBufferList* inInputData,
  224841. const AudioTimeStamp* inInputTime,
  224842. AudioBufferList* outOutputData,
  224843. const AudioTimeStamp* inOutputTime,
  224844. void* device)
  224845. {
  224846. ((CoreAudioInternal*) device)->audioCallback (inInputData, outOutputData);
  224847. return noErr;
  224848. }
  224849. static OSStatus deviceListenerProc (AudioDeviceID /*inDevice*/, UInt32 /*inLine*/, const AudioObjectPropertyAddress* pa, void* inClientData)
  224850. {
  224851. CoreAudioInternal* const intern = (CoreAudioInternal*) inClientData;
  224852. switch (pa->mSelector)
  224853. {
  224854. case kAudioDevicePropertyBufferSize:
  224855. case kAudioDevicePropertyBufferFrameSize:
  224856. case kAudioDevicePropertyNominalSampleRate:
  224857. case kAudioDevicePropertyStreamFormat:
  224858. case kAudioDevicePropertyDeviceIsAlive:
  224859. intern->deviceDetailsChanged();
  224860. break;
  224861. case kAudioDevicePropertyBufferSizeRange:
  224862. case kAudioDevicePropertyVolumeScalar:
  224863. case kAudioDevicePropertyMute:
  224864. case kAudioDevicePropertyPlayThru:
  224865. case kAudioDevicePropertyDataSource:
  224866. case kAudioDevicePropertyDeviceIsRunning:
  224867. break;
  224868. }
  224869. return noErr;
  224870. }
  224871. static OSType* getAllDataSourcesForDevice (AudioDeviceID deviceID, const bool input, int& num)
  224872. {
  224873. OSType* types = 0;
  224874. UInt32 size = 0;
  224875. num = 0;
  224876. AudioObjectPropertyAddress pa;
  224877. pa.mSelector = kAudioDevicePropertyDataSources;
  224878. pa.mScope = kAudioObjectPropertyScopeWildcard;
  224879. pa.mElement = kAudioObjectPropertyElementMaster;
  224880. if (deviceID != 0
  224881. && OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  224882. {
  224883. types = (OSType*) juce_calloc (size);
  224884. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, types)))
  224885. {
  224886. num = size / sizeof (OSType);
  224887. }
  224888. else
  224889. {
  224890. juce_free (types);
  224891. types = 0;
  224892. }
  224893. }
  224894. return types;
  224895. }
  224896. };
  224897. class CoreAudioIODevice : public AudioIODevice
  224898. {
  224899. public:
  224900. CoreAudioIODevice (const String& deviceName,
  224901. AudioDeviceID inputDeviceId,
  224902. const int inputIndex_,
  224903. AudioDeviceID outputDeviceId,
  224904. const int outputIndex_)
  224905. : AudioIODevice (deviceName, "CoreAudio"),
  224906. inputIndex (inputIndex_),
  224907. outputIndex (outputIndex_),
  224908. isOpen_ (false),
  224909. isStarted (false)
  224910. {
  224911. internal = 0;
  224912. CoreAudioInternal* device = 0;
  224913. if (outputDeviceId == 0 || outputDeviceId == inputDeviceId)
  224914. {
  224915. jassert (inputDeviceId != 0);
  224916. device = new CoreAudioInternal (inputDeviceId);
  224917. lastError = device->error;
  224918. if (lastError.isNotEmpty())
  224919. deleteAndZero (device);
  224920. }
  224921. else
  224922. {
  224923. device = new CoreAudioInternal (outputDeviceId);
  224924. lastError = device->error;
  224925. if (lastError.isNotEmpty())
  224926. {
  224927. deleteAndZero (device);
  224928. }
  224929. else if (inputDeviceId != 0)
  224930. {
  224931. CoreAudioInternal* secondDevice = new CoreAudioInternal (inputDeviceId);
  224932. lastError = device->error;
  224933. if (lastError.isNotEmpty())
  224934. {
  224935. delete secondDevice;
  224936. }
  224937. else
  224938. {
  224939. device->inputDevice = secondDevice;
  224940. secondDevice->isSlaveDevice = true;
  224941. }
  224942. }
  224943. }
  224944. internal = device;
  224945. AudioObjectPropertyAddress pa;
  224946. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  224947. pa.mScope = kAudioObjectPropertyScopeWildcard;
  224948. pa.mElement = kAudioObjectPropertyElementWildcard;
  224949. AudioObjectAddPropertyListener (kAudioObjectSystemObject, &pa, hardwareListenerProc, internal);
  224950. }
  224951. ~CoreAudioIODevice()
  224952. {
  224953. AudioObjectPropertyAddress pa;
  224954. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  224955. pa.mScope = kAudioObjectPropertyScopeWildcard;
  224956. pa.mElement = kAudioObjectPropertyElementWildcard;
  224957. AudioObjectRemovePropertyListener (kAudioObjectSystemObject, &pa, hardwareListenerProc, internal);
  224958. delete internal;
  224959. }
  224960. const StringArray getOutputChannelNames()
  224961. {
  224962. return internal->outChanNames;
  224963. }
  224964. const StringArray getInputChannelNames()
  224965. {
  224966. if (internal->inputDevice != 0)
  224967. return internal->inputDevice->inChanNames;
  224968. else
  224969. return internal->inChanNames;
  224970. }
  224971. int getNumSampleRates()
  224972. {
  224973. return internal->sampleRates.size();
  224974. }
  224975. double getSampleRate (int index)
  224976. {
  224977. return internal->sampleRates [index];
  224978. }
  224979. int getNumBufferSizesAvailable()
  224980. {
  224981. return internal->bufferSizes.size();
  224982. }
  224983. int getBufferSizeSamples (int index)
  224984. {
  224985. return internal->bufferSizes [index];
  224986. }
  224987. int getDefaultBufferSize()
  224988. {
  224989. for (int i = 0; i < getNumBufferSizesAvailable(); ++i)
  224990. if (getBufferSizeSamples(i) >= 512)
  224991. return getBufferSizeSamples(i);
  224992. return 512;
  224993. }
  224994. const String open (const BitArray& inputChannels,
  224995. const BitArray& outputChannels,
  224996. double sampleRate,
  224997. int bufferSizeSamples)
  224998. {
  224999. isOpen_ = true;
  225000. if (bufferSizeSamples <= 0)
  225001. bufferSizeSamples = getDefaultBufferSize();
  225002. internal->reopen (inputChannels, outputChannels, sampleRate, bufferSizeSamples);
  225003. lastError = internal->error;
  225004. return lastError;
  225005. }
  225006. void close()
  225007. {
  225008. isOpen_ = false;
  225009. }
  225010. bool isOpen()
  225011. {
  225012. return isOpen_;
  225013. }
  225014. int getCurrentBufferSizeSamples()
  225015. {
  225016. return internal != 0 ? internal->getBufferSize() : 512;
  225017. }
  225018. double getCurrentSampleRate()
  225019. {
  225020. return internal != 0 ? internal->getSampleRate() : 0;
  225021. }
  225022. int getCurrentBitDepth()
  225023. {
  225024. return 32; // no way to find out, so just assume it's high..
  225025. }
  225026. const BitArray getActiveOutputChannels() const
  225027. {
  225028. return internal != 0 ? internal->activeOutputChans : BitArray();
  225029. }
  225030. const BitArray getActiveInputChannels() const
  225031. {
  225032. BitArray chans;
  225033. if (internal != 0)
  225034. {
  225035. chans = internal->activeInputChans;
  225036. if (internal->inputDevice != 0)
  225037. chans.orWith (internal->inputDevice->activeInputChans);
  225038. }
  225039. return chans;
  225040. }
  225041. int getOutputLatencyInSamples()
  225042. {
  225043. if (internal == 0)
  225044. return 0;
  225045. // this seems like a good guess at getting the latency right - comparing
  225046. // this with a round-trip measurement, it gets it to within a few millisecs
  225047. // for the built-in mac soundcard
  225048. return internal->outputLatency + internal->getBufferSize() * 2;
  225049. }
  225050. int getInputLatencyInSamples()
  225051. {
  225052. if (internal == 0)
  225053. return 0;
  225054. return internal->inputLatency + internal->getBufferSize() * 2;
  225055. }
  225056. void start (AudioIODeviceCallback* callback)
  225057. {
  225058. if (internal != 0 && ! isStarted)
  225059. {
  225060. if (callback != 0)
  225061. callback->audioDeviceAboutToStart (this);
  225062. isStarted = true;
  225063. internal->start (callback);
  225064. }
  225065. }
  225066. void stop()
  225067. {
  225068. if (isStarted && internal != 0)
  225069. {
  225070. AudioIODeviceCallback* const lastCallback = internal->callback;
  225071. isStarted = false;
  225072. internal->stop (true);
  225073. if (lastCallback != 0)
  225074. lastCallback->audioDeviceStopped();
  225075. }
  225076. }
  225077. bool isPlaying()
  225078. {
  225079. if (internal->callback == 0)
  225080. isStarted = false;
  225081. return isStarted;
  225082. }
  225083. const String getLastError()
  225084. {
  225085. return lastError;
  225086. }
  225087. int inputIndex, outputIndex;
  225088. juce_UseDebuggingNewOperator
  225089. private:
  225090. CoreAudioInternal* internal;
  225091. bool isOpen_, isStarted;
  225092. String lastError;
  225093. static OSStatus hardwareListenerProc (AudioDeviceID /*inDevice*/, UInt32 /*inLine*/, const AudioObjectPropertyAddress* pa, void* inClientData)
  225094. {
  225095. CoreAudioInternal* const intern = (CoreAudioInternal*) inClientData;
  225096. switch (pa->mSelector)
  225097. {
  225098. case kAudioHardwarePropertyDevices:
  225099. intern->deviceDetailsChanged();
  225100. break;
  225101. case kAudioHardwarePropertyDefaultOutputDevice:
  225102. case kAudioHardwarePropertyDefaultInputDevice:
  225103. case kAudioHardwarePropertyDefaultSystemOutputDevice:
  225104. break;
  225105. }
  225106. return noErr;
  225107. }
  225108. CoreAudioIODevice (const CoreAudioIODevice&);
  225109. const CoreAudioIODevice& operator= (const CoreAudioIODevice&);
  225110. };
  225111. class CoreAudioIODeviceType : public AudioIODeviceType
  225112. {
  225113. public:
  225114. CoreAudioIODeviceType()
  225115. : AudioIODeviceType (T("CoreAudio")),
  225116. hasScanned (false)
  225117. {
  225118. }
  225119. ~CoreAudioIODeviceType()
  225120. {
  225121. }
  225122. void scanForDevices()
  225123. {
  225124. hasScanned = true;
  225125. inputDeviceNames.clear();
  225126. outputDeviceNames.clear();
  225127. inputIds.clear();
  225128. outputIds.clear();
  225129. UInt32 size;
  225130. AudioObjectPropertyAddress pa;
  225131. pa.mSelector = kAudioHardwarePropertyDevices;
  225132. pa.mScope = kAudioObjectPropertyScopeWildcard;
  225133. pa.mElement = kAudioObjectPropertyElementMaster;
  225134. if (OK (AudioObjectGetPropertyDataSize (kAudioObjectSystemObject, &pa, 0, 0, &size)))
  225135. {
  225136. AudioDeviceID* const devs = (AudioDeviceID*) juce_calloc (size);
  225137. if (OK (AudioObjectGetPropertyData (kAudioObjectSystemObject, &pa, 0, 0, &size, devs)))
  225138. {
  225139. static bool alreadyLogged = false;
  225140. const int num = size / sizeof (AudioDeviceID);
  225141. for (int i = 0; i < num; ++i)
  225142. {
  225143. char name [1024];
  225144. size = sizeof (name);
  225145. pa.mSelector = kAudioDevicePropertyDeviceName;
  225146. if (OK (AudioObjectGetPropertyData (devs[i], &pa, 0, 0, &size, name)))
  225147. {
  225148. const String nameString (String::fromUTF8 ((const uint8*) name, strlen (name)));
  225149. if (! alreadyLogged)
  225150. log (T("CoreAudio device: ") + nameString);
  225151. const int numIns = getNumChannels (devs[i], true);
  225152. const int numOuts = getNumChannels (devs[i], false);
  225153. if (numIns > 0)
  225154. {
  225155. inputDeviceNames.add (nameString);
  225156. inputIds.add (devs[i]);
  225157. }
  225158. if (numOuts > 0)
  225159. {
  225160. outputDeviceNames.add (nameString);
  225161. outputIds.add (devs[i]);
  225162. }
  225163. }
  225164. }
  225165. alreadyLogged = true;
  225166. }
  225167. juce_free (devs);
  225168. }
  225169. inputDeviceNames.appendNumbersToDuplicates (false, true);
  225170. outputDeviceNames.appendNumbersToDuplicates (false, true);
  225171. }
  225172. const StringArray getDeviceNames (const bool wantInputNames) const
  225173. {
  225174. jassert (hasScanned); // need to call scanForDevices() before doing this
  225175. if (wantInputNames)
  225176. return inputDeviceNames;
  225177. else
  225178. return outputDeviceNames;
  225179. }
  225180. int getDefaultDeviceIndex (const bool forInput) const
  225181. {
  225182. jassert (hasScanned); // need to call scanForDevices() before doing this
  225183. AudioDeviceID deviceID;
  225184. UInt32 size = sizeof (deviceID);
  225185. // if they're asking for any input channels at all, use the default input, so we
  225186. // get the built-in mic rather than the built-in output with no inputs..
  225187. AudioObjectPropertyAddress pa;
  225188. pa.mSelector = forInput ? kAudioHardwarePropertyDefaultInputDevice : kAudioHardwarePropertyDefaultOutputDevice;
  225189. pa.mScope = kAudioObjectPropertyScopeWildcard;
  225190. pa.mElement = kAudioObjectPropertyElementMaster;
  225191. if (AudioObjectGetPropertyData (kAudioObjectSystemObject, &pa, 0, 0, &size, &deviceID) == noErr)
  225192. {
  225193. if (forInput)
  225194. {
  225195. for (int i = inputIds.size(); --i >= 0;)
  225196. if (inputIds[i] == deviceID)
  225197. return i;
  225198. }
  225199. else
  225200. {
  225201. for (int i = outputIds.size(); --i >= 0;)
  225202. if (outputIds[i] == deviceID)
  225203. return i;
  225204. }
  225205. }
  225206. return 0;
  225207. }
  225208. int getIndexOfDevice (AudioIODevice* device, const bool asInput) const
  225209. {
  225210. jassert (hasScanned); // need to call scanForDevices() before doing this
  225211. CoreAudioIODevice* const d = dynamic_cast <CoreAudioIODevice*> (device);
  225212. if (d == 0)
  225213. return -1;
  225214. return asInput ? d->inputIndex
  225215. : d->outputIndex;
  225216. }
  225217. bool hasSeparateInputsAndOutputs() const { return true; }
  225218. AudioIODevice* createDevice (const String& outputDeviceName,
  225219. const String& inputDeviceName)
  225220. {
  225221. jassert (hasScanned); // need to call scanForDevices() before doing this
  225222. const int inputIndex = inputDeviceNames.indexOf (inputDeviceName);
  225223. const int outputIndex = outputDeviceNames.indexOf (outputDeviceName);
  225224. String deviceName (outputDeviceName);
  225225. if (deviceName.isEmpty())
  225226. deviceName = inputDeviceName;
  225227. if (index >= 0)
  225228. return new CoreAudioIODevice (deviceName,
  225229. inputIds [inputIndex],
  225230. inputIndex,
  225231. outputIds [outputIndex],
  225232. outputIndex);
  225233. return 0;
  225234. }
  225235. juce_UseDebuggingNewOperator
  225236. private:
  225237. StringArray inputDeviceNames, outputDeviceNames;
  225238. Array <AudioDeviceID> inputIds, outputIds;
  225239. bool hasScanned;
  225240. static int getNumChannels (AudioDeviceID deviceID, bool input)
  225241. {
  225242. int total = 0;
  225243. UInt32 size;
  225244. AudioObjectPropertyAddress pa;
  225245. pa.mSelector = kAudioDevicePropertyStreamConfiguration;
  225246. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  225247. pa.mElement = kAudioObjectPropertyElementMaster;
  225248. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  225249. {
  225250. AudioBufferList* const bufList = (AudioBufferList*) juce_calloc (size);
  225251. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, bufList)))
  225252. {
  225253. const int numStreams = bufList->mNumberBuffers;
  225254. for (int i = 0; i < numStreams; ++i)
  225255. {
  225256. const AudioBuffer& b = bufList->mBuffers[i];
  225257. total += b.mNumberChannels;
  225258. }
  225259. }
  225260. juce_free (bufList);
  225261. }
  225262. return total;
  225263. }
  225264. CoreAudioIODeviceType (const CoreAudioIODeviceType&);
  225265. const CoreAudioIODeviceType& operator= (const CoreAudioIODeviceType&);
  225266. };
  225267. AudioIODeviceType* juce_createAudioIODeviceType_CoreAudio()
  225268. {
  225269. return new CoreAudioIODeviceType();
  225270. }
  225271. #undef log
  225272. #endif
  225273. /********* End of inlined file: juce_mac_CoreAudio.cpp *********/
  225274. /********* Start of inlined file: juce_mac_CoreMidi.cpp *********/
  225275. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  225276. // compiled on its own).
  225277. #ifdef JUCE_INCLUDED_FILE
  225278. #undef log
  225279. #define log(a) Logger::writeToLog(a)
  225280. static bool logAnyErrorsMidi (const OSStatus err, const int lineNum)
  225281. {
  225282. if (err == noErr)
  225283. return true;
  225284. log (T("CoreMidi error: ") + String (lineNum) + T(" - ") + String::toHexString ((int)err));
  225285. jassertfalse
  225286. return false;
  225287. }
  225288. #undef OK
  225289. #define OK(a) logAnyErrorsMidi(a, __LINE__)
  225290. static const String getEndpointName (MIDIEndpointRef endpoint, bool isExternal)
  225291. {
  225292. String result;
  225293. CFStringRef str = 0;
  225294. MIDIObjectGetStringProperty (endpoint, kMIDIPropertyName, &str);
  225295. if (str != 0)
  225296. {
  225297. result = PlatformUtilities::cfStringToJuceString (str);
  225298. CFRelease (str);
  225299. str = 0;
  225300. }
  225301. MIDIEntityRef entity = 0;
  225302. MIDIEndpointGetEntity (endpoint, &entity);
  225303. if (entity == 0)
  225304. return result; // probably virtual
  225305. if (result.isEmpty())
  225306. {
  225307. // endpoint name has zero length - try the entity
  225308. MIDIObjectGetStringProperty (entity, kMIDIPropertyName, &str);
  225309. if (str != 0)
  225310. {
  225311. result += PlatformUtilities::cfStringToJuceString (str);
  225312. CFRelease (str);
  225313. str = 0;
  225314. }
  225315. }
  225316. // now consider the device's name
  225317. MIDIDeviceRef device = 0;
  225318. MIDIEntityGetDevice (entity, &device);
  225319. if (device == 0)
  225320. return result;
  225321. MIDIObjectGetStringProperty (device, kMIDIPropertyName, &str);
  225322. if (str != 0)
  225323. {
  225324. const String s (PlatformUtilities::cfStringToJuceString (str));
  225325. CFRelease (str);
  225326. // if an external device has only one entity, throw away
  225327. // the endpoint name and just use the device name
  225328. if (isExternal && MIDIDeviceGetNumberOfEntities (device) < 2)
  225329. {
  225330. result = s;
  225331. }
  225332. else if (! result.startsWithIgnoreCase (s))
  225333. {
  225334. // prepend the device name to the entity name
  225335. result = (s + T(" ") + result).trimEnd();
  225336. }
  225337. }
  225338. return result;
  225339. }
  225340. static const String getConnectedEndpointName (MIDIEndpointRef endpoint)
  225341. {
  225342. String result;
  225343. // Does the endpoint have connections?
  225344. CFDataRef connections = 0;
  225345. int numConnections = 0;
  225346. MIDIObjectGetDataProperty (endpoint, kMIDIPropertyConnectionUniqueID, &connections);
  225347. if (connections != 0)
  225348. {
  225349. numConnections = CFDataGetLength (connections) / sizeof (MIDIUniqueID);
  225350. if (numConnections > 0)
  225351. {
  225352. const SInt32* pid = reinterpret_cast <const SInt32*> (CFDataGetBytePtr (connections));
  225353. for (int i = 0; i < numConnections; ++i, ++pid)
  225354. {
  225355. MIDIUniqueID uid = EndianS32_BtoN (*pid);
  225356. MIDIObjectRef connObject;
  225357. MIDIObjectType connObjectType;
  225358. OSStatus err = MIDIObjectFindByUniqueID (uid, &connObject, &connObjectType);
  225359. if (err == noErr)
  225360. {
  225361. String s;
  225362. if (connObjectType == kMIDIObjectType_ExternalSource
  225363. || connObjectType == kMIDIObjectType_ExternalDestination)
  225364. {
  225365. // Connected to an external device's endpoint (10.3 and later).
  225366. s = getEndpointName (static_cast <MIDIEndpointRef> (connObject), true);
  225367. }
  225368. else
  225369. {
  225370. // Connected to an external device (10.2) (or something else, catch-all)
  225371. CFStringRef str = 0;
  225372. MIDIObjectGetStringProperty (connObject, kMIDIPropertyName, &str);
  225373. if (str != 0)
  225374. {
  225375. s = PlatformUtilities::cfStringToJuceString (str);
  225376. CFRelease (str);
  225377. }
  225378. }
  225379. if (s.isNotEmpty())
  225380. {
  225381. if (result.isNotEmpty())
  225382. result += (", ");
  225383. result += s;
  225384. }
  225385. }
  225386. }
  225387. }
  225388. CFRelease (connections);
  225389. }
  225390. if (result.isNotEmpty())
  225391. return result;
  225392. // Here, either the endpoint had no connections, or we failed to obtain names for any of them.
  225393. return getEndpointName (endpoint, false);
  225394. }
  225395. const StringArray MidiOutput::getDevices()
  225396. {
  225397. StringArray s;
  225398. const ItemCount num = MIDIGetNumberOfDestinations();
  225399. for (ItemCount i = 0; i < num; ++i)
  225400. {
  225401. MIDIEndpointRef dest = MIDIGetDestination (i);
  225402. if (dest != 0)
  225403. {
  225404. String name (getConnectedEndpointName (dest));
  225405. if (name.isEmpty())
  225406. name = "<error>";
  225407. s.add (name);
  225408. }
  225409. else
  225410. {
  225411. s.add ("<error>");
  225412. }
  225413. }
  225414. return s;
  225415. }
  225416. int MidiOutput::getDefaultDeviceIndex()
  225417. {
  225418. return 0;
  225419. }
  225420. static MIDIClientRef globalMidiClient;
  225421. static bool hasGlobalClientBeenCreated = false;
  225422. static bool makeSureClientExists()
  225423. {
  225424. if (! hasGlobalClientBeenCreated)
  225425. {
  225426. String name (T("JUCE"));
  225427. if (JUCEApplication::getInstance() != 0)
  225428. name = JUCEApplication::getInstance()->getApplicationName();
  225429. CFStringRef appName = PlatformUtilities::juceStringToCFString (name);
  225430. hasGlobalClientBeenCreated = OK (MIDIClientCreate (appName, 0, 0, &globalMidiClient));
  225431. CFRelease (appName);
  225432. }
  225433. return hasGlobalClientBeenCreated;
  225434. }
  225435. struct MidiPortAndEndpoint
  225436. {
  225437. MIDIPortRef port;
  225438. MIDIEndpointRef endPoint;
  225439. };
  225440. MidiOutput* MidiOutput::openDevice (int index)
  225441. {
  225442. MidiOutput* mo = 0;
  225443. if (((unsigned int) index) < (unsigned int) MIDIGetNumberOfDestinations())
  225444. {
  225445. MIDIEndpointRef endPoint = MIDIGetDestination (index);
  225446. CFStringRef pname;
  225447. if (OK (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &pname)))
  225448. {
  225449. log (T("CoreMidi - opening out: ") + PlatformUtilities::cfStringToJuceString (pname));
  225450. if (makeSureClientExists())
  225451. {
  225452. MIDIPortRef port;
  225453. if (OK (MIDIOutputPortCreate (globalMidiClient, pname, &port)))
  225454. {
  225455. MidiPortAndEndpoint* mpe = new MidiPortAndEndpoint();
  225456. mpe->port = port;
  225457. mpe->endPoint = endPoint;
  225458. mo = new MidiOutput();
  225459. mo->internal = (void*)mpe;
  225460. }
  225461. }
  225462. CFRelease (pname);
  225463. }
  225464. }
  225465. return mo;
  225466. }
  225467. MidiOutput::~MidiOutput()
  225468. {
  225469. MidiPortAndEndpoint* const mpe = (MidiPortAndEndpoint*)internal;
  225470. MIDIPortDispose (mpe->port);
  225471. delete mpe;
  225472. }
  225473. void MidiOutput::reset()
  225474. {
  225475. }
  225476. bool MidiOutput::getVolume (float& leftVol, float& rightVol)
  225477. {
  225478. return false;
  225479. }
  225480. void MidiOutput::setVolume (float leftVol, float rightVol)
  225481. {
  225482. }
  225483. void MidiOutput::sendMessageNow (const MidiMessage& message)
  225484. {
  225485. MidiPortAndEndpoint* const mpe = (MidiPortAndEndpoint*)internal;
  225486. if (message.isSysEx())
  225487. {
  225488. const int maxPacketSize = 256;
  225489. int pos = 0, bytesLeft = message.getRawDataSize();
  225490. const int numPackets = (bytesLeft + maxPacketSize - 1) / maxPacketSize;
  225491. MIDIPacketList* const packets = (MIDIPacketList*) juce_malloc (32 * numPackets + message.getRawDataSize());
  225492. packets->numPackets = numPackets;
  225493. MIDIPacket* p = packets->packet;
  225494. for (int i = 0; i < numPackets; ++i)
  225495. {
  225496. p->timeStamp = 0;
  225497. p->length = jmin (maxPacketSize, bytesLeft);
  225498. memcpy (p->data, message.getRawData() + pos, p->length);
  225499. pos += p->length;
  225500. bytesLeft -= p->length;
  225501. p = MIDIPacketNext (p);
  225502. }
  225503. MIDISend (mpe->port, mpe->endPoint, packets);
  225504. juce_free (packets);
  225505. }
  225506. else
  225507. {
  225508. MIDIPacketList packets;
  225509. packets.numPackets = 1;
  225510. packets.packet[0].timeStamp = 0;
  225511. packets.packet[0].length = message.getRawDataSize();
  225512. *(int*) (packets.packet[0].data) = *(const int*) message.getRawData();
  225513. MIDISend (mpe->port, mpe->endPoint, &packets);
  225514. }
  225515. }
  225516. const StringArray MidiInput::getDevices()
  225517. {
  225518. StringArray s;
  225519. const ItemCount num = MIDIGetNumberOfSources();
  225520. for (ItemCount i = 0; i < num; ++i)
  225521. {
  225522. MIDIEndpointRef source = MIDIGetSource (i);
  225523. if (source != 0)
  225524. {
  225525. String name (getConnectedEndpointName (source));
  225526. if (name.isEmpty())
  225527. name = "<error>";
  225528. s.add (name);
  225529. }
  225530. else
  225531. {
  225532. s.add ("<error>");
  225533. }
  225534. }
  225535. return s;
  225536. }
  225537. int MidiInput::getDefaultDeviceIndex()
  225538. {
  225539. return 0;
  225540. }
  225541. struct MidiPortAndCallback
  225542. {
  225543. MidiInput* input;
  225544. MIDIPortRef port;
  225545. MIDIEndpointRef endPoint;
  225546. MidiInputCallback* callback;
  225547. MemoryBlock pendingData;
  225548. int pendingBytes;
  225549. double pendingDataTime;
  225550. bool active;
  225551. };
  225552. static CriticalSection callbackLock;
  225553. static VoidArray activeCallbacks;
  225554. static void processSysex (MidiPortAndCallback* const mpe, const uint8*& d, int& size, const double time)
  225555. {
  225556. if (*d == 0xf0)
  225557. {
  225558. mpe->pendingBytes = 0;
  225559. mpe->pendingDataTime = time;
  225560. }
  225561. mpe->pendingData.ensureSize (mpe->pendingBytes + size, false);
  225562. uint8* totalMessage = (uint8*) mpe->pendingData.getData();
  225563. uint8* dest = totalMessage + mpe->pendingBytes;
  225564. while (size > 0)
  225565. {
  225566. if (mpe->pendingBytes > 0 && *d >= 0x80)
  225567. {
  225568. if (*d >= 0xfa || *d == 0xf8)
  225569. {
  225570. mpe->callback->handleIncomingMidiMessage (mpe->input, MidiMessage (*d, time));
  225571. ++d;
  225572. --size;
  225573. }
  225574. else
  225575. {
  225576. if (*d == 0xf7)
  225577. {
  225578. *dest++ = *d++;
  225579. mpe->pendingBytes++;
  225580. --size;
  225581. }
  225582. break;
  225583. }
  225584. }
  225585. else
  225586. {
  225587. *dest++ = *d++;
  225588. mpe->pendingBytes++;
  225589. --size;
  225590. }
  225591. }
  225592. if (totalMessage [mpe->pendingBytes - 1] == 0xf7)
  225593. {
  225594. mpe->callback->handleIncomingMidiMessage (mpe->input, MidiMessage (totalMessage,
  225595. mpe->pendingBytes,
  225596. mpe->pendingDataTime));
  225597. mpe->pendingBytes = 0;
  225598. }
  225599. else
  225600. {
  225601. mpe->callback->handlePartialSysexMessage (mpe->input,
  225602. totalMessage,
  225603. mpe->pendingBytes,
  225604. mpe->pendingDataTime);
  225605. }
  225606. }
  225607. static void midiInputProc (const MIDIPacketList* pktlist,
  225608. void* readProcRefCon,
  225609. void* srcConnRefCon)
  225610. {
  225611. double time = Time::getMillisecondCounterHiRes() * 0.001;
  225612. const double originalTime = time;
  225613. MidiPortAndCallback* const mpe = (MidiPortAndCallback*) readProcRefCon;
  225614. const ScopedLock sl (callbackLock);
  225615. if (activeCallbacks.contains (mpe) && mpe->active)
  225616. {
  225617. const MIDIPacket* packet = &pktlist->packet[0];
  225618. for (unsigned int i = 0; i < pktlist->numPackets; ++i)
  225619. {
  225620. const uint8* d = (const uint8*) (packet->data);
  225621. int size = packet->length;
  225622. while (size > 0)
  225623. {
  225624. time = originalTime;
  225625. if (mpe->pendingBytes > 0 || d[0] == 0xf0)
  225626. {
  225627. processSysex (mpe, d, size, time);
  225628. }
  225629. else
  225630. {
  225631. int used = 0;
  225632. const MidiMessage m (d, size, used, 0, time);
  225633. if (used <= 0)
  225634. {
  225635. jassertfalse // malformed midi message
  225636. break;
  225637. }
  225638. else
  225639. {
  225640. mpe->callback->handleIncomingMidiMessage (mpe->input, m);
  225641. }
  225642. size -= used;
  225643. d += used;
  225644. }
  225645. }
  225646. packet = MIDIPacketNext (packet);
  225647. }
  225648. }
  225649. }
  225650. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback)
  225651. {
  225652. MidiInput* mi = 0;
  225653. if (((unsigned int) index) < (unsigned int) MIDIGetNumberOfSources())
  225654. {
  225655. MIDIEndpointRef endPoint = MIDIGetSource (index);
  225656. if (endPoint != 0)
  225657. {
  225658. CFStringRef pname;
  225659. if (OK (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &pname)))
  225660. {
  225661. log (T("CoreMidi - opening inp: ") + PlatformUtilities::cfStringToJuceString (pname));
  225662. if (makeSureClientExists())
  225663. {
  225664. MIDIPortRef port;
  225665. MidiPortAndCallback* const mpe = new MidiPortAndCallback();
  225666. mpe->active = false;
  225667. if (OK (MIDIInputPortCreate (globalMidiClient, pname, midiInputProc, mpe, &port)))
  225668. {
  225669. if (OK (MIDIPortConnectSource (port, endPoint, 0)))
  225670. {
  225671. mpe->port = port;
  225672. mpe->endPoint = endPoint;
  225673. mpe->callback = callback;
  225674. mpe->pendingBytes = 0;
  225675. mpe->pendingData.ensureSize (128);
  225676. mi = new MidiInput (getDevices() [index]);
  225677. mpe->input = mi;
  225678. mi->internal = (void*) mpe;
  225679. const ScopedLock sl (callbackLock);
  225680. activeCallbacks.add (mpe);
  225681. }
  225682. else
  225683. {
  225684. OK (MIDIPortDispose (port));
  225685. delete mpe;
  225686. }
  225687. }
  225688. else
  225689. {
  225690. delete mpe;
  225691. }
  225692. }
  225693. }
  225694. CFRelease (pname);
  225695. }
  225696. }
  225697. return mi;
  225698. }
  225699. MidiInput::MidiInput (const String& name_)
  225700. : name (name_)
  225701. {
  225702. }
  225703. MidiInput::~MidiInput()
  225704. {
  225705. MidiPortAndCallback* const mpe = (MidiPortAndCallback*) internal;
  225706. mpe->active = false;
  225707. callbackLock.enter();
  225708. activeCallbacks.removeValue (mpe);
  225709. callbackLock.exit();
  225710. OK (MIDIPortDisconnectSource (mpe->port, mpe->endPoint));
  225711. OK (MIDIPortDispose (mpe->port));
  225712. delete mpe;
  225713. }
  225714. void MidiInput::start()
  225715. {
  225716. MidiPortAndCallback* const mpe = (MidiPortAndCallback*) internal;
  225717. const ScopedLock sl (callbackLock);
  225718. mpe->active = true;
  225719. }
  225720. void MidiInput::stop()
  225721. {
  225722. MidiPortAndCallback* const mpe = (MidiPortAndCallback*) internal;
  225723. const ScopedLock sl (callbackLock);
  225724. mpe->active = false;
  225725. }
  225726. #undef log
  225727. #endif
  225728. /********* End of inlined file: juce_mac_CoreMidi.cpp *********/
  225729. /********* Start of inlined file: juce_mac_CameraDevice.mm *********/
  225730. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  225731. // compiled on its own).
  225732. #if JUCE_INCLUDED_FILE && JUCE_QUICKTIME && JUCE_USE_CAMERA
  225733. #define QTCaptureCallbackDelegate MakeObjCClassName(QTCaptureCallbackDelegate)
  225734. class QTCameraDeviceInteral;
  225735. END_JUCE_NAMESPACE
  225736. @interface QTCaptureCallbackDelegate : NSObject
  225737. {
  225738. @public
  225739. CameraDevice* owner;
  225740. QTCameraDeviceInteral* internal;
  225741. Time* firstRecordedTime;
  225742. }
  225743. - (QTCaptureCallbackDelegate*) initWithOwner: (CameraDevice*) owner internalDev: (QTCameraDeviceInteral*) d;
  225744. - (void) dealloc;
  225745. - (void) captureOutput: (QTCaptureOutput*) captureOutput
  225746. didOutputVideoFrame: (CVImageBufferRef) videoFrame
  225747. withSampleBuffer: (QTSampleBuffer*) sampleBuffer
  225748. fromConnection: (QTCaptureConnection*) connection;
  225749. - (void) captureOutput: (QTCaptureFileOutput*) captureOutput
  225750. didOutputSampleBuffer: (QTSampleBuffer*) sampleBuffer
  225751. fromConnection: (QTCaptureConnection*) connection;
  225752. @end
  225753. BEGIN_JUCE_NAMESPACE
  225754. class QTCameraDeviceInteral
  225755. {
  225756. public:
  225757. QTCameraDeviceInteral (CameraDevice* owner, int index)
  225758. {
  225759. const ScopedAutoReleasePool pool;
  225760. session = [[QTCaptureSession alloc] init];
  225761. NSArray* devs = [QTCaptureDevice inputDevicesWithMediaType: QTMediaTypeVideo];
  225762. device = (QTCaptureDevice*) [devs objectAtIndex: index];
  225763. input = 0;
  225764. fileOutput = 0;
  225765. imageOutput = 0;
  225766. callbackDelegate = [[QTCaptureCallbackDelegate alloc] initWithOwner: owner
  225767. internalDev: this];
  225768. NSError* err = 0;
  225769. [device retain];
  225770. [device open: &err];
  225771. if (err == 0)
  225772. {
  225773. input = [[QTCaptureDeviceInput alloc] initWithDevice: device];
  225774. [session addInput: input error: &err];
  225775. if (err == 0)
  225776. {
  225777. resetFile();
  225778. imageOutput = [[QTCaptureDecompressedVideoOutput alloc] init];
  225779. [imageOutput setDelegate: callbackDelegate];
  225780. if (err == 0)
  225781. {
  225782. [session startRunning];
  225783. return;
  225784. }
  225785. }
  225786. }
  225787. openingError = nsStringToJuce ([err description]);
  225788. DBG (openingError);
  225789. }
  225790. ~QTCameraDeviceInteral()
  225791. {
  225792. [session stopRunning];
  225793. [session removeOutput: imageOutput];
  225794. [session release];
  225795. [input release];
  225796. [device release];
  225797. [fileOutput release];
  225798. [imageOutput release];
  225799. [callbackDelegate release];
  225800. }
  225801. void resetFile()
  225802. {
  225803. [session removeOutput: fileOutput];
  225804. [fileOutput release];
  225805. fileOutput = [[QTCaptureMovieFileOutput alloc] init];
  225806. [fileOutput setDelegate: callbackDelegate];
  225807. }
  225808. void addListener (CameraImageListener* listenerToAdd)
  225809. {
  225810. const ScopedLock sl (listenerLock);
  225811. if (listeners.size() == 0)
  225812. [session addOutput: imageOutput error: nil];
  225813. listeners.addIfNotAlreadyThere (listenerToAdd);
  225814. }
  225815. void removeListener (CameraImageListener* listenerToRemove)
  225816. {
  225817. const ScopedLock sl (listenerLock);
  225818. listeners.removeValue (listenerToRemove);
  225819. if (listeners.size() == 0)
  225820. [session removeOutput: imageOutput];
  225821. }
  225822. static void drawNSBitmapIntoJuceImage (Image& dest, NSBitmapImageRep* source)
  225823. {
  225824. const ScopedAutoReleasePool pool;
  225825. int lineStride, pixelStride;
  225826. uint8* pixels = dest.lockPixelDataReadWrite (0, 0, dest.getWidth(), dest.getHeight(),
  225827. lineStride, pixelStride);
  225828. NSBitmapImageRep* rep = [[NSBitmapImageRep alloc]
  225829. initWithBitmapDataPlanes: &pixels
  225830. pixelsWide: dest.getWidth()
  225831. pixelsHigh: dest.getHeight()
  225832. bitsPerSample: 8
  225833. samplesPerPixel: pixelStride
  225834. hasAlpha: dest.hasAlphaChannel()
  225835. isPlanar: NO
  225836. colorSpaceName: NSCalibratedRGBColorSpace
  225837. bitmapFormat: (NSBitmapFormat) 0
  225838. bytesPerRow: lineStride
  225839. bitsPerPixel: pixelStride * 8];
  225840. [NSGraphicsContext saveGraphicsState];
  225841. [NSGraphicsContext setCurrentContext: [NSGraphicsContext graphicsContextWithBitmapImageRep: rep]];
  225842. [source drawAtPoint: NSZeroPoint];
  225843. [[NSGraphicsContext currentContext] flushGraphics];
  225844. [NSGraphicsContext restoreGraphicsState];
  225845. uint8* start = pixels;
  225846. for (int h = dest.getHeight(); --h >= 0;)
  225847. {
  225848. uint8* p = start;
  225849. start += lineStride;
  225850. for (int i = dest.getWidth(); --i >= 0;)
  225851. {
  225852. #if JUCE_BIG_ENDIAN
  225853. const uint8 oldp3 = p[3];
  225854. const uint8 oldp1 = p[1];
  225855. p[3] = p[0];
  225856. p[0] = oldp1;
  225857. p[1] = p[2];
  225858. p[2] = oldp3;
  225859. #else
  225860. const uint8 oldp0 = p[0];
  225861. p[0] = p[2];
  225862. p[2] = oldp0;
  225863. #endif
  225864. p += pixelStride;
  225865. }
  225866. }
  225867. dest.releasePixelDataReadWrite (pixels);
  225868. }
  225869. void callListeners (NSBitmapImageRep* bitmap)
  225870. {
  225871. Image image (Image::ARGB, [bitmap size].width, [bitmap size].height, false);
  225872. drawNSBitmapIntoJuceImage (image, bitmap);
  225873. const ScopedLock sl (listenerLock);
  225874. for (int i = listeners.size(); --i >= 0;)
  225875. {
  225876. CameraImageListener* l = (CameraImageListener*) listeners[i];
  225877. if (l != 0)
  225878. l->imageReceived (image);
  225879. }
  225880. }
  225881. QTCaptureDevice* device;
  225882. QTCaptureDeviceInput* input;
  225883. QTCaptureSession* session;
  225884. QTCaptureMovieFileOutput* fileOutput;
  225885. QTCaptureDecompressedVideoOutput* imageOutput;
  225886. QTCaptureCallbackDelegate* callbackDelegate;
  225887. String openingError;
  225888. VoidArray listeners;
  225889. CriticalSection listenerLock;
  225890. };
  225891. END_JUCE_NAMESPACE
  225892. @implementation QTCaptureCallbackDelegate
  225893. - (QTCaptureCallbackDelegate*) initWithOwner: (CameraDevice*) owner_
  225894. internalDev: (QTCameraDeviceInteral*) d
  225895. {
  225896. [super init];
  225897. owner = owner_;
  225898. internal = d;
  225899. firstRecordedTime = 0;
  225900. return self;
  225901. }
  225902. - (void) dealloc
  225903. {
  225904. delete firstRecordedTime;
  225905. [super dealloc];
  225906. }
  225907. - (void) captureOutput: (QTCaptureOutput*) captureOutput
  225908. didOutputVideoFrame: (CVImageBufferRef) videoFrame
  225909. withSampleBuffer: (QTSampleBuffer*) sampleBuffer
  225910. fromConnection: (QTCaptureConnection*) connection
  225911. {
  225912. const ScopedAutoReleasePool pool;
  225913. CIImage* image = [CIImage imageWithCVImageBuffer: videoFrame];
  225914. NSBitmapImageRep* bitmap = [[[NSBitmapImageRep alloc] initWithCIImage: image] autorelease];
  225915. internal->callListeners (bitmap);
  225916. }
  225917. - (void) captureOutput: (QTCaptureFileOutput*) captureOutput
  225918. didOutputSampleBuffer: (QTSampleBuffer*) sampleBuffer
  225919. fromConnection: (QTCaptureConnection*) connection
  225920. {
  225921. if (firstRecordedTime == 0)
  225922. firstRecordedTime = new Time (Time::getCurrentTime());
  225923. }
  225924. @end
  225925. BEGIN_JUCE_NAMESPACE
  225926. class QTCaptureViewerComp : public NSViewComponent
  225927. {
  225928. public:
  225929. QTCaptureViewerComp (CameraDevice* const cameraDevice, QTCameraDeviceInteral* const internal)
  225930. {
  225931. const ScopedAutoReleasePool pool;
  225932. captureView = [[QTCaptureView alloc] init];
  225933. [captureView setCaptureSession: internal->session];
  225934. setSize (640, 480); // xxx need to somehow get the movie size - how?
  225935. setView (captureView);
  225936. }
  225937. ~QTCaptureViewerComp()
  225938. {
  225939. setView (0);
  225940. [captureView setCaptureSession: nil];
  225941. [captureView release];
  225942. }
  225943. QTCaptureView* captureView;
  225944. };
  225945. CameraDevice::CameraDevice (const String& name_, int index)
  225946. : name (name_)
  225947. {
  225948. isRecording = false;
  225949. QTCameraDeviceInteral* d = new QTCameraDeviceInteral (this, index);
  225950. internal = d;
  225951. }
  225952. CameraDevice::~CameraDevice()
  225953. {
  225954. stopRecording();
  225955. delete (QTCameraDeviceInteral*) internal;
  225956. internal = 0;
  225957. }
  225958. Component* CameraDevice::createViewerComponent()
  225959. {
  225960. return new QTCaptureViewerComp (this, (QTCameraDeviceInteral*) internal);
  225961. }
  225962. const String CameraDevice::getFileExtension()
  225963. {
  225964. return ".mov";
  225965. }
  225966. void CameraDevice::startRecordingToFile (const File& file)
  225967. {
  225968. stopRecording();
  225969. QTCameraDeviceInteral* const d = (QTCameraDeviceInteral*) internal;
  225970. deleteAndZero (d->callbackDelegate->firstRecordedTime);
  225971. file.deleteFile();
  225972. [d->fileOutput recordToOutputFileURL: [NSURL fileURLWithPath: juceStringToNS (file.getFullPathName())]];
  225973. [d->session addOutput: d->fileOutput error: nil];
  225974. isRecording = true;
  225975. }
  225976. const Time CameraDevice::getTimeOfFirstRecordedFrame() const
  225977. {
  225978. QTCameraDeviceInteral* const d = (QTCameraDeviceInteral*) internal;
  225979. if (d->callbackDelegate->firstRecordedTime != 0)
  225980. return *d->callbackDelegate->firstRecordedTime;
  225981. return Time();
  225982. }
  225983. void CameraDevice::stopRecording()
  225984. {
  225985. if (isRecording)
  225986. {
  225987. QTCameraDeviceInteral* const d = (QTCameraDeviceInteral*) internal;
  225988. d->resetFile();
  225989. isRecording = false;
  225990. }
  225991. }
  225992. void CameraDevice::addListener (CameraImageListener* listenerToAdd)
  225993. {
  225994. QTCameraDeviceInteral* const d = (QTCameraDeviceInteral*) internal;
  225995. if (listenerToAdd != 0)
  225996. d->addListener (listenerToAdd);
  225997. }
  225998. void CameraDevice::removeListener (CameraImageListener* listenerToRemove)
  225999. {
  226000. QTCameraDeviceInteral* const d = (QTCameraDeviceInteral*) internal;
  226001. if (listenerToRemove != 0)
  226002. d->removeListener (listenerToRemove);
  226003. }
  226004. const StringArray CameraDevice::getAvailableDevices()
  226005. {
  226006. const ScopedAutoReleasePool pool;
  226007. StringArray results;
  226008. NSArray* devs = [QTCaptureDevice inputDevicesWithMediaType: QTMediaTypeVideo];
  226009. for (int i = 0; i < [devs count]; ++i)
  226010. {
  226011. QTCaptureDevice* dev = (QTCaptureDevice*) [devs objectAtIndex: i];
  226012. results.add (nsStringToJuce ([dev localizedDisplayName]));
  226013. }
  226014. return results;
  226015. }
  226016. CameraDevice* CameraDevice::openDevice (int index,
  226017. int minWidth, int minHeight,
  226018. int maxWidth, int maxHeight)
  226019. {
  226020. CameraDevice* d = new CameraDevice (getAvailableDevices() [index], index);
  226021. if (((QTCameraDeviceInteral*) (d->internal))->openingError.isEmpty())
  226022. return d;
  226023. delete d;
  226024. return 0;
  226025. }
  226026. #endif
  226027. /********* End of inlined file: juce_mac_CameraDevice.mm *********/
  226028. #endif
  226029. END_JUCE_NAMESPACE
  226030. /********* End of inlined file: juce_mac_NativeCode.mm *********/
  226031. #endif